ifc-geometry 0.3.1

IFC semantic views lowered into the format-neutral geometry DAG.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
//! `IfcBSplineSurface` and its knotted / rational refinements.
//!
//! # The same job as [`crate::curve::bspline`], one dimension up
//!
//! Read the parameters, check the invariants, evaluate nothing. What changes
//! in 2D is that every invariant now has a u form and a v form, and the
//! control points are a *grid* rather than a list. The grid is where files go
//! wrong: `ControlPointsList` is `LIST OF LIST OF IfcCartesianPoint`, and a
//! ragged inner list means the surface is not a tensor product at all.
//!
//! # Which index is which
//!
//! `ControlPointsList[i][j]` has `i` running along **u** and `j` along **v**.
//! So the outer list length is the u control point count and the inner length
//! the v count. Transposing them yields a surface that is plausible, is not
//! the one in the file, and passes every count check because the two knot
//! vectors are usually the same length in test data. This module's accessors
//! are named `u_*` and `v_*` for exactly that reason, and the row/column
//! convention is asserted in the tests.
//!
//! # Invariants checked here
//!
//! - Control point grid is rectangular (no ragged rows).
//! - `sum(UMultiplicities) = u control points + UDegree + 1`, and the v form.
//! - `UKnots` / `UMultiplicities` are parallel lists, and the v form.
//! - Weights form a grid of the same shape as the control points, all positive.

use crate::curve::bspline::{KnotType, KnotVector};
use crate::error::GeometryResult;
use crate::slots::Slots;
use ifc_model::{Entity, EntityId, Value};

/// `IfcBSplineSurface` family attribute slots.
///
/// From IFC4 ADD2 TC1. Slots 0-6 come from `IfcBSplineSurface`, 7-11 from
/// `IfcBSplineSurfaceWithKnots`, and 12 from
/// `IfcRationalBSplineSurfaceWithKnots`.
pub(crate) mod slot {
    /// `UDegree`: `IfcInteger`.
    pub const U_DEGREE: usize = 0;
    /// `VDegree`: `IfcInteger`.
    pub const V_DEGREE: usize = 1;
    /// `ControlPointsList`: `LIST OF LIST OF IfcCartesianPoint`, u outer.
    pub const CONTROL_POINTS: usize = 2;
    /// `SurfaceForm`: `IfcBSplineSurfaceForm`.
    pub const SURFACE_FORM: usize = 3;
    /// `UClosed`: `IfcLogical`.
    pub const U_CLOSED: usize = 4;
    /// `VClosed`: `IfcLogical`.
    pub const V_CLOSED: usize = 5;
    /// `SelfIntersect`: `IfcLogical`.
    pub const SELF_INTERSECT: usize = 6;
    /// `UMultiplicities`, from `IfcBSplineSurfaceWithKnots`.
    pub const U_MULTIPLICITIES: usize = 7;
    /// `VMultiplicities`, from `IfcBSplineSurfaceWithKnots`.
    pub const V_MULTIPLICITIES: usize = 8;
    /// `UKnots`, from `IfcBSplineSurfaceWithKnots`.
    pub const U_KNOTS: usize = 9;
    /// `VKnots`, from `IfcBSplineSurfaceWithKnots`.
    pub const V_KNOTS: usize = 10;
    /// `KnotSpec`: `IfcKnotType`, from `IfcBSplineSurfaceWithKnots`.
    pub const KNOT_SPEC: usize = 11;
    /// `WeightsData`, from `IfcRationalBSplineSurfaceWithKnots`.
    pub const WEIGHTS_DATA: usize = 12;
}

/// `IfcBSplineSurfaceForm`: what shape the surface originally was.
///
/// Informational only, exactly like [`crate::curve::BSplineCurveForm`]. A
/// `CYLINDRICAL_SURF` form is not a licence to substitute an
/// `IfcCylindricalSurface`: the control points are what the file actually
/// means.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BSplineSurfaceForm {
    /// Originally a plane.
    PlaneSurf,
    /// Originally a cylinder.
    CylindricalSurf,
    /// Originally a cone.
    ConicalSurf,
    /// Originally a sphere.
    SphericalSurf,
    /// Originally a torus.
    ToroidalSurf,
    /// Originally a surface of revolution.
    SurfOfRevolution,
    /// Originally a ruled surface.
    RuledSurf,
    /// Originally a generalised cone.
    GeneralisedCone,
    /// Originally a quadric.
    QuadricSurf,
    /// Originally a linear extrusion.
    SurfOfLinearExtrusion,
    /// No original form is claimed.
    Unspecified,
}

impl BSplineSurfaceForm {
    /// Parse the enumeration token, `None` if unrecognised.
    pub fn from_token(token: &str) -> Option<Self> {
        match token.to_ascii_uppercase().as_str() {
            "PLANE_SURF" => Some(Self::PlaneSurf),
            "CYLINDRICAL_SURF" => Some(Self::CylindricalSurf),
            "CONICAL_SURF" => Some(Self::ConicalSurf),
            "SPHERICAL_SURF" => Some(Self::SphericalSurf),
            "TOROIDAL_SURF" => Some(Self::ToroidalSurf),
            "SURF_OF_REVOLUTION" => Some(Self::SurfOfRevolution),
            "RULED_SURF" => Some(Self::RuledSurf),
            "GENERALISED_CONE" => Some(Self::GeneralisedCone),
            "QUADRIC_SURF" => Some(Self::QuadricSurf),
            "SURF_OF_LINEAR_EXTRUSION" => Some(Self::SurfOfLinearExtrusion),
            "UNSPECIFIED" => Some(Self::Unspecified),
            _ => None,
        }
    }
}

/// The control point grid, `[u][v]`.
///
/// A distinct type rather than a bare `Vec<Vec<EntityId>>` so the u/v
/// convention is stated once and the rectangularity check cannot be skipped.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ControlPointGrid {
    rows: Vec<Vec<EntityId>>,
}

impl ControlPointGrid {
    /// Number of control points along u; the outer list length.
    pub fn u_count(&self) -> usize {
        self.rows.len()
    }

    /// Number of control points along v; the inner list length.
    pub fn v_count(&self) -> usize {
        self.rows.first().map_or(0, Vec::len)
    }

    /// The control point at `(u_index, v_index)`.
    pub fn get(&self, u_index: usize, v_index: usize) -> Option<EntityId> {
        self.rows.get(u_index)?.get(v_index).copied()
    }

    /// The rows, each a constant-u run of control points.
    pub fn rows(&self) -> &[Vec<EntityId>] {
        &self.rows
    }
}

/// A borrowed view of any `IfcBSplineSurface` subtype.
#[derive(Debug, Clone, Copy)]
pub struct BSplineSurface<'m> {
    slots: Slots<'m>,
}

impl<'m> BSplineSurface<'m> {
    /// Wrap an entity known to be an `IfcBSplineSurface` subtype.
    pub fn new(id: EntityId, entity: &'m Entity) -> Self {
        Self {
            slots: Slots::new(id, entity),
        }
    }

    /// The entity id.
    pub fn id(&self) -> EntityId {
        self.slots.id()
    }

    /// The u polynomial degree, guaranteed to fit the u control count.
    pub fn u_degree(&self) -> GeometryResult<usize> {
        self.degree(slot::U_DEGREE, "UDegree", self.control_points()?.u_count())
    }

    /// The v polynomial degree, guaranteed to fit the v control count.
    pub fn v_degree(&self) -> GeometryResult<usize> {
        self.degree(slot::V_DEGREE, "VDegree", self.control_points()?.v_count())
    }

    /// The control point grid, checked to be rectangular.
    ///
    /// A ragged grid is not a tensor-product surface, so it cannot be
    /// evaluated at all; catching it here beats an out-of-bounds read in a
    /// kernel's inner loop.
    // TODO: `resource::point` will provide a typed point view to resolve these.
    pub fn control_points(&self) -> GeometryResult<ControlPointGrid> {
        let value = self.slots.req(slot::CONTROL_POINTS, "ControlPointsList")?;
        let outer = value.as_list().ok_or_else(|| {
            self.slots
                .degenerate("ControlPointsList must be a list of lists")
        })?;
        if outer.len() < 2 {
            return Err(self.slots.degenerate(format!(
                "ControlPointsList needs at least 2 rows along u, found {}",
                outer.len()
            )));
        }

        let mut rows: Vec<Vec<EntityId>> = Vec::with_capacity(outer.len());
        for (u_index, row_value) in outer.iter().enumerate() {
            let inner = row_value.as_list().ok_or_else(|| {
                self.slots
                    .degenerate(format!("ControlPointsList row {u_index} is not a list"))
            })?;
            let mut row = Vec::with_capacity(inner.len());
            for (v_index, point) in inner.iter().enumerate() {
                let id = point.as_ref_id().ok_or_else(|| {
                    self.slots.degenerate(format!(
                        "ControlPointsList[{u_index}][{v_index}] is not an entity reference"
                    ))
                })?;
                row.push(id);
            }
            rows.push(row);
        }

        let v_count = rows[0].len();
        if v_count < 2 {
            return Err(self.slots.degenerate(format!(
                "ControlPointsList needs at least 2 columns along v, found {v_count}"
            )));
        }
        for (u_index, row) in rows.iter().enumerate() {
            if row.len() != v_count {
                return Err(self.slots.degenerate(format!(
                    "ControlPointsList row {u_index} has {} points but row 0 has {v_count}; \
                     the grid must be rectangular",
                    row.len()
                )));
            }
        }
        Ok(ControlPointGrid { rows })
    }

    /// The declared original form, defaulting to `Unspecified`.
    pub fn surface_form(&self) -> BSplineSurfaceForm {
        self.slots
            .opt_enum(slot::SURFACE_FORM)
            .and_then(BSplineSurfaceForm::from_token)
            .unwrap_or(BSplineSurfaceForm::Unspecified)
    }

    /// The asserted `UClosed` flag; `None` for `.U.` or absent.
    pub fn u_closed(&self) -> Option<bool> {
        self.slots.opt_bool(slot::U_CLOSED)
    }

    /// The asserted `VClosed` flag; `None` for `.U.` or absent.
    pub fn v_closed(&self) -> Option<bool> {
        self.slots.opt_bool(slot::V_CLOSED)
    }

    /// The asserted `SelfIntersect` flag; `None` for `.U.` or absent.
    pub fn self_intersect(&self) -> Option<bool> {
        self.slots.opt_bool(slot::SELF_INTERSECT)
    }

    /// The declared knot type, defaulting to `Unspecified`.
    pub fn knot_spec(&self) -> KnotType {
        self.slots
            .opt_enum(slot::KNOT_SPEC)
            .and_then(KnotType::from_token)
            .unwrap_or(KnotType::Unspecified)
    }

    /// Is this the knotted subtype?
    pub fn has_knots(&self) -> bool {
        self.slots.opt(slot::U_KNOTS).is_some()
    }

    /// Whether the entity declares the rational subtype.
    pub fn is_rational(&self) -> bool {
        self.slots
            .type_name()
            .eq_ignore_ascii_case("IFCRATIONALBSPLINESURFACEWITHKNOTS")
    }

    /// The u knot vector, checked against the u control point count.
    ///
    /// `Ok(None)` for a surface without knots.
    pub fn u_knots(&self) -> GeometryResult<Option<KnotVector>> {
        if !self.has_knots() {
            return Ok(None);
        }
        let expected = self
            .control_points()?
            .u_count()
            .checked_add(self.u_degree()?)
            .and_then(|value| value.checked_add(1))
            .ok_or_else(|| self.slots.degenerate("u knot count overflows usize"))?;
        self.knot_vector(
            slot::U_KNOTS,
            "UKnots",
            slot::U_MULTIPLICITIES,
            "UMultiplicities",
            expected,
        )
        .map(Some)
    }

    /// The v knot vector, checked against the v control point count.
    ///
    /// `Ok(None)` for a surface without knots.
    pub fn v_knots(&self) -> GeometryResult<Option<KnotVector>> {
        if !self.has_knots() {
            return Ok(None);
        }
        let expected = self
            .control_points()?
            .v_count()
            .checked_add(self.v_degree()?)
            .and_then(|value| value.checked_add(1))
            .ok_or_else(|| self.slots.degenerate("v knot count overflows usize"))?;
        self.knot_vector(
            slot::V_KNOTS,
            "VKnots",
            slot::V_MULTIPLICITIES,
            "VMultiplicities",
            expected,
        )
        .map(Some)
    }

    /// The weight grid, matching the control point grid exactly.
    ///
    /// `Ok(None)` for a non-rational surface. Every weight must be finite and positive:
    /// a zero divides by zero at that control point and a negative one flips
    /// the patch through infinity.
    pub fn weights(&self) -> GeometryResult<Option<Vec<Vec<f64>>>> {
        let supplied = self.slots.opt(slot::WEIGHTS_DATA).is_some();
        match (self.is_rational(), supplied) {
            (false, false) => return Ok(None),
            (true, false) => {
                return Err(self
                    .slots
                    .degenerate("rational B-spline surface is missing WeightsData"));
            }
            (false, true) => {
                return Err(self
                    .slots
                    .degenerate("polynomial B-spline surface must not carry WeightsData"));
            }
            (true, true) => {}
        }
        let grid = self.control_points()?;
        let value = self.slots.req(slot::WEIGHTS_DATA, "WeightsData")?;
        let outer = value
            .as_list()
            .ok_or_else(|| self.slots.degenerate("WeightsData must be a list of lists"))?;

        if outer.len() != grid.u_count() {
            return Err(self.slots.degenerate(format!(
                "WeightsData has {} rows but the control point grid has {}",
                outer.len(),
                grid.u_count()
            )));
        }

        let mut weights = Vec::with_capacity(outer.len());
        for (u_index, row_value) in outer.iter().enumerate() {
            let inner = row_value.as_list().ok_or_else(|| {
                self.slots
                    .degenerate(format!("WeightsData row {u_index} is not a list"))
            })?;
            if inner.len() != grid.v_count() {
                return Err(self.slots.degenerate(format!(
                    "WeightsData row {u_index} has {} entries but the grid has {}",
                    inner.len(),
                    grid.v_count()
                )));
            }
            let mut row = Vec::with_capacity(inner.len());
            for (v_index, w) in inner.iter().enumerate() {
                let weight = w.unwrap_typed().as_f64().ok_or_else(|| {
                    self.slots
                        .degenerate(format!("WeightsData[{u_index}][{v_index}] is not a number"))
                })?;
                if !weight.is_finite() {
                    return Err(self.slots.degenerate(format!(
                        "weight {weight} at control point [{u_index}][{v_index}] must be finite"
                    )));
                }
                if weight <= 0.0 {
                    return Err(self.slots.degenerate(format!(
                        "weight {weight} at control point [{u_index}][{v_index}] must be positive"
                    )));
                }
                row.push(weight);
            }
            weights.push(row);
        }
        Ok(Some(weights))
    }

    fn degree(
        &self,
        index: usize,
        name: &'static str,
        control_count: usize,
    ) -> GeometryResult<usize> {
        let raw = self.slots.req_i64(index, name)?;
        if raw < 1 {
            return Err(self
                .slots
                .degenerate(format!("{name} must be at least 1, found {raw}")));
        }
        let degree = usize::try_from(raw).map_err(|_| {
            self.slots
                .degenerate(format!("{name} exceeds platform limits"))
        })?;
        if degree >= control_count {
            return Err(self.slots.degenerate(format!(
                "{name} {degree} must be smaller than the {control_count} control points"
            )));
        }
        Ok(degree)
    }

    /// Read one knot vector and check it against `expected` total multiplicity.
    fn knot_vector(
        &self,
        knots_index: usize,
        knots_name: &'static str,
        mult_index: usize,
        mult_name: &'static str,
        expected: usize,
    ) -> GeometryResult<KnotVector> {
        let values = self.slots.req_f64_list(knots_index, knots_name)?;
        let raw = self.slots.req(mult_index, mult_name)?;
        let items = raw
            .as_list()
            .ok_or_else(|| self.slots.degenerate(format!("{mult_name} must be a list")))?;

        let mut multiplicities = Vec::with_capacity(items.len());
        for item in items {
            match item.unwrap_typed() {
                Value::Integer(i) if *i >= 1 => {
                    multiplicities.push(usize::try_from(*i).map_err(|_| {
                        self.slots
                            .degenerate(format!("{mult_name} exceeds platform limits"))
                    })?);
                }
                other => {
                    return Err(self.slots.degenerate(format!(
                        "{mult_name} entry must be a positive integer, found {other:?}"
                    )));
                }
            }
        }

        if values.len() != multiplicities.len() {
            return Err(self.slots.degenerate(format!(
                "{knots_name} has {} entries but {mult_name} has {}; they are parallel lists",
                values.len(),
                multiplicities.len()
            )));
        }
        for (index, value) in values.iter().enumerate() {
            if !value.is_finite() {
                return Err(self.slots.degenerate(format!(
                    "{knots_name}[{index}] must be finite, found {value}"
                )));
            }
        }
        for pair in values.windows(2) {
            if pair[1] <= pair[0] {
                return Err(self.slots.degenerate(format!(
                    "{knots_name} must be strictly increasing; found {} after {}",
                    pair[1], pair[0]
                )));
            }
        }
        let total = multiplicities.iter().try_fold(0usize, |total, &value| {
            total.checked_add(value).ok_or_else(|| {
                self.slots
                    .degenerate(format!("{mult_name} total overflows usize"))
            })
        })?;
        if total != expected {
            return Err(self.slots.degenerate(format!(
                "{mult_name} sums to {total} but must equal control points + degree + 1 = {expected}"
            )));
        }
        Ok(KnotVector {
            values,
            multiplicities,
        })
    }
}

/// Marker kept so the curve module's knot types are visibly reused.
///
/// The knot representation is identical in one and two dimensions, so
/// duplicating [`KnotVector`] here would create two types that must be kept in
/// sync for no benefit.
pub type SurfaceKnotVector = KnotVector;

#[cfg(test)]
mod tests {
    use super::*;

    /// A `u_count` by `v_count` grid whose ids encode their position as
    /// `u * 10 + v`, so a transposition is visible in the assertion.
    fn grid(u_count: usize, v_count: usize) -> Value {
        Value::List(
            (0..u_count)
                .map(|u| {
                    Value::List(
                        (0..v_count)
                            .map(|v| Value::Ref(EntityId((u * 10 + v) as u64)))
                            .collect(),
                    )
                })
                .collect(),
        )
    }

    fn integers(values: &[i64]) -> Value {
        Value::List(values.iter().map(|i| Value::Integer(*i)).collect())
    }

    fn reals(values: &[f64]) -> Value {
        Value::List(values.iter().map(|r| Value::Real(*r)).collect())
    }

    /// Degree 1 in both directions, 2x2 control points, clamped knots.
    fn bilinear() -> Entity {
        Entity::new(
            "IFCBSPLINESURFACEWITHKNOTS",
            vec![
                Value::Integer(1),
                Value::Integer(1),
                grid(2, 2),
                Value::Enum("UNSPECIFIED".into()),
                Value::Bool(false),
                Value::Bool(false),
                Value::Bool(false),
                integers(&[2, 2]),
                integers(&[2, 2]),
                reals(&[0.0, 1.0]),
                reals(&[0.0, 1.0]),
                Value::Enum("UNSPECIFIED".into()),
            ],
        )
    }

    #[test]
    fn inherited_surface_slots_precede_the_knot_and_weight_slots() {
        let e = bilinear();
        let view = BSplineSurface::new(EntityId(1), &e);
        assert_eq!(view.u_degree().unwrap(), 1);
        assert_eq!(view.v_degree().unwrap(), 1);
        assert!(view.has_knots());
        assert!(!view.is_rational());
        assert_eq!(view.knot_spec(), KnotType::Unspecified);
    }

    /// The outer list runs along u and the inner along v. A transposed read
    /// still typechecks and still passes count checks on a square grid, so it
    /// is pinned by position-encoded ids on a non-square grid.
    #[test]
    fn the_outer_control_point_list_runs_along_u_and_the_inner_along_v() {
        let e = Entity::new(
            "IFCBSPLINESURFACE",
            vec![
                Value::Integer(1),
                Value::Integer(1),
                grid(3, 5),
                Value::Enum("UNSPECIFIED".into()),
                Value::Bool(false),
                Value::Bool(false),
                Value::Bool(false),
            ],
        );
        let points = BSplineSurface::new(EntityId(1), &e)
            .control_points()
            .unwrap();
        assert_eq!(points.u_count(), 3, "outer list length is the u count");
        assert_eq!(points.v_count(), 5, "inner list length is the v count");
        // Id u*10 + v: (2, 4) must be 24, not 42.
        assert_eq!(points.get(2, 4), Some(EntityId(24)));
        assert_eq!(points.rows().len(), 3);
    }

    /// A ragged grid is not a tensor-product surface and cannot be evaluated.
    #[test]
    fn a_ragged_control_point_grid_is_rejected() {
        let mut e = bilinear();
        e.attributes[slot::CONTROL_POINTS] = Value::List(vec![
            Value::List(vec![Value::Ref(EntityId(1)), Value::Ref(EntityId(2))]),
            Value::List(vec![Value::Ref(EntityId(3))]),
        ]);
        let err = BSplineSurface::new(EntityId(7), &e)
            .control_points()
            .unwrap_err();
        assert!(err.to_string().contains("rectangular"), "got: {err}");
        assert!(err.to_string().contains("#7"), "got: {err}");
    }

    #[test]
    fn both_knot_vectors_are_checked_against_their_own_control_point_count() {
        let e = bilinear();
        let view = BSplineSurface::new(EntityId(1), &e);
        let u = view.u_knots().unwrap().unwrap();
        let v = view.v_knots().unwrap().unwrap();
        assert_eq!(u.expanded(), Some(vec![0.0, 0.0, 1.0, 1.0]));
        assert_eq!(v.expanded(), Some(vec![0.0, 0.0, 1.0, 1.0]));
        assert!(u.is_clamped(1));
    }

    /// The u and v checks must be independent: a wrong v multiplicity must not
    /// be masked by a correct u one.
    #[test]
    fn a_wrong_v_multiplicity_sum_is_caught_even_when_u_is_right() {
        let mut e = bilinear();
        e.attributes[slot::V_MULTIPLICITIES] = integers(&[2, 3]);
        let view = BSplineSurface::new(EntityId(1), &e);
        assert!(view.u_knots().is_ok(), "u is untouched and must still pass");
        let err = view.v_knots().unwrap_err();
        assert!(err.to_string().contains("VMultiplicities"), "got: {err}");
    }

    #[test]
    fn parallel_knot_lists_of_different_lengths_are_rejected() {
        let mut e = bilinear();
        e.attributes[slot::U_KNOTS] = reals(&[0.0, 0.5, 1.0]);
        let err = BSplineSurface::new(EntityId(1), &e).u_knots().unwrap_err();
        assert!(err.to_string().contains("parallel"), "got: {err}");
    }

    #[test]
    fn non_increasing_knot_values_are_rejected() {
        let mut e = bilinear();
        e.attributes[slot::U_KNOTS] = reals(&[1.0, 0.0]);
        let err = BSplineSurface::new(EntityId(1), &e).u_knots().unwrap_err();
        assert!(err.to_string().contains("increasing"), "got: {err}");
    }

    #[test]
    fn a_surface_without_knots_reports_none_rather_than_failing() {
        let e = Entity::new(
            "IFCBSPLINESURFACE",
            vec![
                Value::Integer(1),
                Value::Integer(1),
                grid(2, 2),
                Value::Enum("UNSPECIFIED".into()),
                Value::Bool(false),
                Value::Bool(false),
                Value::Bool(false),
            ],
        );
        let view = BSplineSurface::new(EntityId(1), &e);
        assert_eq!(view.u_knots().unwrap(), None);
        assert_eq!(view.v_knots().unwrap(), None);
        assert_eq!(view.weights().unwrap(), None);
    }

    #[test]
    fn rational_weights_form_a_grid_of_the_same_shape_as_the_control_points() {
        let mut attributes = bilinear().attributes;
        attributes.push(Value::List(vec![reals(&[1.0, 0.5]), reals(&[0.5, 1.0])]));
        let e = Entity::new("IFCRATIONALBSPLINESURFACEWITHKNOTS", attributes);
        let view = BSplineSurface::new(EntityId(1), &e);
        assert!(view.is_rational());
        assert_eq!(
            view.weights().unwrap().unwrap(),
            vec![vec![1.0, 0.5], vec![0.5, 1.0]]
        );
    }

    #[test]
    fn a_weight_grid_of_the_wrong_shape_is_rejected() {
        let mut attributes = bilinear().attributes;
        attributes.push(Value::List(vec![reals(&[1.0, 1.0])]));
        let e = Entity::new("IFCRATIONALBSPLINESURFACEWITHKNOTS", attributes);
        let err = BSplineSurface::new(EntityId(1), &e).weights().unwrap_err();
        assert!(err.to_string().contains("rows"), "got: {err}");
    }

    #[test]
    fn a_non_positive_weight_anywhere_in_the_grid_is_degenerate() {
        for bad in [0.0, -1.0] {
            let mut attributes = bilinear().attributes;
            attributes.push(Value::List(vec![reals(&[1.0, 1.0]), reals(&[1.0, bad])]));
            let e = Entity::new("IFCRATIONALBSPLINESURFACEWITHKNOTS", attributes);
            let err = BSplineSurface::new(EntityId(1), &e).weights().unwrap_err();
            assert!(err.to_string().contains("positive"), "weight {bad}: {err}");
            assert!(err.to_string().contains("[1][1]"), "weight {bad}: {err}");
        }
    }

    #[test]
    fn multiplicity_overflow_is_a_typed_error_not_a_panic() {
        let mut e = bilinear();
        e.attributes[slot::U_MULTIPLICITIES] = integers(&[i64::MAX, i64::MAX, i64::MAX]);
        e.attributes[slot::U_KNOTS] = reals(&[0.0, 0.5, 1.0]);
        let err = BSplineSurface::new(EntityId(8), &e).u_knots().unwrap_err();
        assert!(err.to_string().contains("overflow"), "got: {err}");
    }

    #[test]
    fn each_degree_must_not_exceed_its_control_point_upper_index() {
        let mut e = bilinear();
        e.attributes[slot::U_DEGREE] = Value::Integer(2);
        assert!(BSplineSurface::new(EntityId(9), &e)
            .u_degree()
            .unwrap_err()
            .to_string()
            .contains("control points"));

        let mut e = bilinear();
        e.attributes[slot::V_DEGREE] = Value::Integer(2);
        assert!(BSplineSurface::new(EntityId(10), &e)
            .v_degree()
            .unwrap_err()
            .to_string()
            .contains("control points"));
    }

    #[test]
    fn rational_subtype_requires_weights_and_polynomial_rejects_them() {
        let attributes = bilinear().attributes;
        let rational = Entity::new("IFCRATIONALBSPLINESURFACEWITHKNOTS", attributes.clone());
        assert!(BSplineSurface::new(EntityId(11), &rational)
            .weights()
            .unwrap_err()
            .to_string()
            .contains("missing WeightsData"));

        let mut polynomial_attributes = attributes;
        polynomial_attributes.push(Value::List(vec![reals(&[1.0, 1.0]), reals(&[1.0, 1.0])]));
        let polynomial = Entity::new("IFCBSPLINESURFACEWITHKNOTS", polynomial_attributes);
        assert!(BSplineSurface::new(EntityId(12), &polynomial)
            .weights()
            .unwrap_err()
            .to_string()
            .contains("must not carry WeightsData"));
    }

    #[test]
    fn degree_zero_in_either_direction_is_rejected() {
        let mut e = bilinear();
        e.attributes[slot::U_DEGREE] = Value::Integer(0);
        assert!(BSplineSurface::new(EntityId(1), &e).u_degree().is_err());

        let mut e = bilinear();
        e.attributes[slot::V_DEGREE] = Value::Integer(0);
        assert!(BSplineSurface::new(EntityId(1), &e).v_degree().is_err());
    }

    /// The form is provenance, never a licence to swap in an analytic surface.
    #[test]
    fn surface_form_tokens_parse_without_replacing_the_control_points() {
        assert_eq!(
            BSplineSurfaceForm::from_token("SURF_OF_LINEAR_EXTRUSION"),
            Some(BSplineSurfaceForm::SurfOfLinearExtrusion)
        );
        assert_eq!(
            BSplineSurfaceForm::from_token("CYLINDRICAL_SURF"),
            Some(BSplineSurfaceForm::CylindricalSurf)
        );
        assert_eq!(BSplineSurfaceForm::from_token("BLOB"), None);
    }

    #[test]
    fn closure_flags_are_read_independently_for_u_and_v() {
        let mut e = bilinear();
        e.attributes[slot::U_CLOSED] = Value::Bool(true);
        e.attributes[slot::V_CLOSED] = Value::LogicalUnknown;
        let view = BSplineSurface::new(EntityId(1), &e);
        assert_eq!(view.u_closed(), Some(true));
        assert_eq!(view.v_closed(), None, ".U. must not become false");
    }
}