ifc-geometry 0.4.4

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
//! `IfcElementarySurface` subtypes: plane, cylinder, sphere, torus.
//!
//! # What they share
//!
//! Exactly one inherited attribute, `Position`, an `IfcAxis2Placement3D`.
//! Unlike `IfcConic::Position` this is *not* a select: an elementary surface
//! is always placed in 3D. The placement is not decoration -- it defines the
//! surface's parameter space, so two cylinders with the same radius and
//! different placements have different `(u, v)` meanings and their p-curves
//! are not interchangeable.
//!
//! # Parameterisation, and why it decides unit handling
//!
//! | Surface | u | v |
//! | --- | --- | --- |
//! | `IfcPlane` | length along local X | length along local Y |
//! | `IfcCylindricalSurface` | **angle** about local Z | length along local Z |
//! | `IfcSphericalSurface` | **angle** about local Z | **angle** from equator |
//! | `IfcToroidalSurface` | **angle** about local Z | **angle** about the tube |
//!
//! A consumer that scales every `IfcPcurve` coordinate by the model's length
//! unit will corrupt every non-planar surface: on a cylinder in millimetres it
//! multiplies an angle by 0.001. [`ParameterKind`] exists so that decision can
//! be made from data rather than from a comment.

use crate::error::GeometryResult;
use crate::resource::placement::Axis2Placement3D;
use crate::resource::resolve;
use crate::slots::Slots;
use ifc_model::{Entity, EntityId, Model};

/// `IfcElementarySurface` family attribute slots.
///
/// From IFC4 ADD2 TC1: slot 0 `Position` is inherited from
/// `IfcElementarySurface` by all four subtypes; radii follow from slot 1.
pub(crate) mod slot {
    /// `Position`: `IfcAxis2Placement3D`, from `IfcElementarySurface`.
    pub const POSITION: usize = 0;
    /// `Radius` on `IfcCylindricalSurface` and `IfcSphericalSurface`.
    pub const RADIUS: usize = 1;
    /// `MajorRadius` on `IfcToroidalSurface`: centre to tube centre.
    pub const MAJOR_RADIUS: usize = 1;
    /// `MinorRadius` on `IfcToroidalSurface`: the tube's own radius.
    pub const MINOR_RADIUS: usize = 2;
}

/// What a surface parameter means, and therefore how to convert it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ParameterKind {
    /// A distance in the model's length unit.
    Length,
    /// An angle in the model's plane-angle unit, which may be degrees.
    Angle,
}

/// A borrowed view of an `IfcPlane`.
///
/// Infinite in both parameters. A file that means a finite patch wraps this in
/// an `IfcCurveBoundedPlane` or an `IfcRectangularTrimmedSurface`; a consumer
/// that renders a bare `IfcPlane` will fill the world.
#[derive(Debug, Clone, Copy)]
pub struct Plane<'m> {
    slots: Slots<'m>,
}

impl<'m> Plane<'m> {
    /// Wrap an entity known to be an `IfcPlane`.
    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 `IfcAxis2Placement3D` whose Z axis is the plane normal.
    ///
    /// The normal direction matters beyond orientation: it decides which side
    /// of a half-space solid is solid.
    pub fn position_ref(&self) -> GeometryResult<EntityId> {
        self.slots.req_ref(slot::POSITION, "Position")
    }

    /// The placement as a typed view, resolved from the model.
    ///
    /// [`Self::position_ref`] returns the raw reference; this resolves it
    /// so callers read location/axis/RefDirection without re-entering the
    /// model themselves. A dangling reference is `MissingEntity` naming this
    /// surface; any target other than an `IfcAxis2Placement3D` is
    /// `WrongEntityType` naming the target.
    pub fn position<'v>(&self, model: &'v Model) -> GeometryResult<Axis2Placement3D<'v>> {
        resolve::axis2_placement_3d(model, self.id(), self.position_ref()?)
    }

    /// Both parameters of a plane are lengths.
    pub fn parameter_kinds(&self) -> (ParameterKind, ParameterKind) {
        (ParameterKind::Length, ParameterKind::Length)
    }
}

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

impl<'m> CylindricalSurface<'m> {
    /// Wrap an entity known to be an `IfcCylindricalSurface`.
    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 placement; local Z is the cylinder axis.
    pub fn position_ref(&self) -> GeometryResult<EntityId> {
        self.slots.req_ref(slot::POSITION, "Position")
    }

    /// The placement as a typed view, resolved from the model.
    ///
    /// [`Self::position_ref`] returns the raw reference; this resolves it
    /// so callers read location/axis/RefDirection without re-entering the
    /// model themselves. A dangling reference is `MissingEntity` naming this
    /// surface; any target other than an `IfcAxis2Placement3D` is
    /// `WrongEntityType` naming the target.
    pub fn position<'v>(&self, model: &'v Model) -> GeometryResult<Axis2Placement3D<'v>> {
        resolve::axis2_placement_3d(model, self.id(), self.position_ref()?)
    }

    /// The radius, guaranteed positive.
    pub fn radius(&self) -> GeometryResult<f64> {
        positive(&self.slots, slot::RADIUS, "Radius")
    }

    /// `u` is an angle about the axis, `v` a length along it.
    pub fn parameter_kinds(&self) -> (ParameterKind, ParameterKind) {
        (ParameterKind::Angle, ParameterKind::Length)
    }
}

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

impl<'m> SphericalSurface<'m> {
    /// Wrap an entity known to be an `IfcSphericalSurface`.
    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 placement; local Z runs through the poles.
    pub fn position_ref(&self) -> GeometryResult<EntityId> {
        self.slots.req_ref(slot::POSITION, "Position")
    }

    /// The placement as a typed view, resolved from the model.
    ///
    /// [`Self::position_ref`] returns the raw reference; this resolves it
    /// so callers read location/axis/RefDirection without re-entering the
    /// model themselves. A dangling reference is `MissingEntity` naming this
    /// surface; any target other than an `IfcAxis2Placement3D` is
    /// `WrongEntityType` naming the target.
    pub fn position<'v>(&self, model: &'v Model) -> GeometryResult<Axis2Placement3D<'v>> {
        resolve::axis2_placement_3d(model, self.id(), self.position_ref()?)
    }

    /// The radius, guaranteed positive.
    pub fn radius(&self) -> GeometryResult<f64> {
        positive(&self.slots, slot::RADIUS, "Radius")
    }

    /// Both parameters are angles: longitude and latitude.
    pub fn parameter_kinds(&self) -> (ParameterKind, ParameterKind) {
        (ParameterKind::Angle, ParameterKind::Angle)
    }
}

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

impl<'m> ToroidalSurface<'m> {
    /// Wrap an entity known to be an `IfcToroidalSurface`.
    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 placement; local Z is the torus axis.
    pub fn position_ref(&self) -> GeometryResult<EntityId> {
        self.slots.req_ref(slot::POSITION, "Position")
    }

    /// The placement as a typed view, resolved from the model.
    ///
    /// [`Self::position_ref`] returns the raw reference; this resolves it
    /// so callers read location/axis/RefDirection without re-entering the
    /// model themselves. A dangling reference is `MissingEntity` naming this
    /// surface; any target other than an `IfcAxis2Placement3D` is
    /// `WrongEntityType` naming the target.
    pub fn position<'v>(&self, model: &'v Model) -> GeometryResult<Axis2Placement3D<'v>> {
        resolve::axis2_placement_3d(model, self.id(), self.position_ref()?)
    }

    /// Distance from the torus centre to the centre of the tube.
    pub fn major_radius(&self) -> GeometryResult<f64> {
        positive(&self.slots, slot::MAJOR_RADIUS, "MajorRadius")
    }

    /// The tube's own radius.
    pub fn minor_radius(&self) -> GeometryResult<f64> {
        positive(&self.slots, slot::MINOR_RADIUS, "MinorRadius")
    }

    /// Is the tube radius at least the major radius?
    ///
    /// IFC permits it and it is not an error: `minor >= major` gives a
    /// self-intersecting "spindle" or "apple" torus rather than a ring. Worth
    /// asking because a kernel that assumes a ring topology will produce
    /// inverted normals on the inner surface, and because it is far more often
    /// a units mistake in the file than a deliberate shape.
    pub fn is_self_intersecting(&self) -> GeometryResult<bool> {
        Ok(self.minor_radius()? >= self.major_radius()?)
    }

    /// Both parameters are angles: around the axis and around the tube.
    pub fn parameter_kinds(&self) -> (ParameterKind, ParameterKind) {
        (ParameterKind::Angle, ParameterKind::Angle)
    }
}

/// Read a radius that the schema declares `IfcPositiveLengthMeasure`.
///
/// STEP does not enforce constrained types, and zero radii reach a kernel as
/// divisions by zero on a surface thousands of entities from the cause.
fn positive(slots: &Slots<'_>, index: usize, name: &'static str) -> GeometryResult<f64> {
    let value = slots.req_f64(index, name)?;
    if value > 0.0 {
        Ok(value)
    } else {
        Err(slots.degenerate(format!("{name} must be positive, found {value}")))
    }
}

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

    fn surface(type_name: &str, radii: &[f64]) -> Entity {
        let mut attributes = vec![Value::Ref(EntityId(70))];
        attributes.extend(radii.iter().map(|r| Value::Real(*r)));
        Entity::new(type_name, attributes)
    }

    #[test]
    fn every_elementary_surface_reads_position_from_the_inherited_slot_zero() {
        let plane = surface("IFCPLANE", &[]);
        assert_eq!(
            Plane::new(EntityId(1), &plane).position_ref().unwrap(),
            EntityId(70)
        );

        let cylinder = surface("IFCCYLINDRICALSURFACE", &[2.0]);
        assert_eq!(
            CylindricalSurface::new(EntityId(1), &cylinder)
                .position_ref()
                .unwrap(),
            EntityId(70)
        );

        let sphere = surface("IFCSPHERICALSURFACE", &[3.0]);
        assert_eq!(
            SphericalSurface::new(EntityId(1), &sphere)
                .position_ref()
                .unwrap(),
            EntityId(70)
        );

        let torus = surface("IFCTOROIDALSURFACE", &[5.0, 1.0]);
        assert_eq!(
            ToroidalSurface::new(EntityId(1), &torus)
                .position_ref()
                .unwrap(),
            EntityId(70)
        );
    }

    #[test]
    fn cylinder_and_sphere_radii_are_read_from_the_slot_after_position() {
        let cylinder = surface("IFCCYLINDRICALSURFACE", &[2.5]);
        assert_eq!(
            CylindricalSurface::new(EntityId(1), &cylinder)
                .radius()
                .unwrap(),
            2.5
        );
        let sphere = surface("IFCSPHERICALSURFACE", &[4.0]);
        assert_eq!(
            SphericalSurface::new(EntityId(1), &sphere)
                .radius()
                .unwrap(),
            4.0
        );
    }

    #[test]
    fn torus_radii_are_read_in_major_then_minor_order() {
        let e = surface("IFCTOROIDALSURFACE", &[5.0, 1.0]);
        let view = ToroidalSurface::new(EntityId(1), &e);
        assert_eq!(view.major_radius().unwrap(), 5.0);
        assert_eq!(view.minor_radius().unwrap(), 1.0);
        assert!(!view.is_self_intersecting().unwrap());
    }

    /// A spindle torus is legal IFC and usually a units bug, so it is flagged
    /// rather than rejected.
    #[test]
    fn a_minor_radius_at_least_the_major_is_reported_as_self_intersecting() {
        let e = surface("IFCTOROIDALSURFACE", &[1.0, 2.0]);
        assert!(ToroidalSurface::new(EntityId(1), &e)
            .is_self_intersecting()
            .unwrap());
    }

    #[test]
    fn a_zero_radius_surface_is_degenerate_and_names_the_attribute() {
        let cylinder = surface("IFCCYLINDRICALSURFACE", &[0.0]);
        let err = CylindricalSurface::new(EntityId(8), &cylinder)
            .radius()
            .unwrap_err();
        assert!(err.to_string().contains("#8"), "got: {err}");
        assert!(err.to_string().contains("Radius"), "got: {err}");

        let torus = surface("IFCTOROIDALSURFACE", &[5.0, -1.0]);
        let err = ToroidalSurface::new(EntityId(1), &torus)
            .minor_radius()
            .unwrap_err();
        assert!(err.to_string().contains("MinorRadius"), "got: {err}");
    }

    /// Scaling an angular surface parameter by a length unit is a silent
    /// corruption, so each surface states which of its parameters are angles.
    #[test]
    fn only_the_plane_has_two_length_parameters() {
        let plane = surface("IFCPLANE", &[]);
        assert_eq!(
            Plane::new(EntityId(1), &plane).parameter_kinds(),
            (ParameterKind::Length, ParameterKind::Length)
        );

        let cylinder = surface("IFCCYLINDRICALSURFACE", &[1.0]);
        assert_eq!(
            CylindricalSurface::new(EntityId(1), &cylinder).parameter_kinds(),
            (ParameterKind::Angle, ParameterKind::Length)
        );

        let sphere = surface("IFCSPHERICALSURFACE", &[1.0]);
        assert_eq!(
            SphericalSurface::new(EntityId(1), &sphere).parameter_kinds(),
            (ParameterKind::Angle, ParameterKind::Angle)
        );

        let torus = surface("IFCTOROIDALSURFACE", &[5.0, 1.0]);
        assert_eq!(
            ToroidalSurface::new(EntityId(1), &torus).parameter_kinds(),
            (ParameterKind::Angle, ParameterKind::Angle)
        );
    }

    #[test]
    fn a_surface_missing_its_position_reports_the_attribute_by_name() {
        let e = Entity::new("IFCPLANE", vec![]);
        let err = Plane::new(EntityId(1), &e).position_ref().unwrap_err();
        assert!(err.to_string().contains("Position"), "got: {err}");
    }

    /// All four elementary surfaces resolve their placement to a typed view.
    ///
    /// The accessor must read the same location the raw reference points at,
    /// for every surface family -- a wrong slot would silently relocate one.
    #[test]
    fn every_elementary_surface_resolves_a_typed_placement_view() {
        let mut model = Model::new();
        model.insert(
            EntityId(60),
            Entity::new(
                "IFCCARTESIANPOINT",
                vec![Value::List(vec![
                    Value::Real(1.0),
                    Value::Real(2.0),
                    Value::Real(3.0),
                ])],
            ),
        );
        model.insert(
            EntityId(70),
            Entity::new("IFCAXIS2PLACEMENT3D", vec![Value::Ref(EntityId(60))]),
        );

        let plane = surface("IFCPLANE", &[]);
        let view = Plane::new(EntityId(1), &plane).position(&model).unwrap();
        assert_eq!(view.id(), EntityId(70));
        assert_eq!(view.location(&model).unwrap(), [1.0, 2.0, 3.0]);

        let cylinder = surface("IFCCYLINDRICALSURFACE", &[2.0]);
        let view = CylindricalSurface::new(EntityId(2), &cylinder)
            .position(&model)
            .unwrap();
        assert_eq!(view.location(&model).unwrap(), [1.0, 2.0, 3.0]);

        let sphere = surface("IFCSPHERICALSURFACE", &[3.0]);
        let view = SphericalSurface::new(EntityId(3), &sphere)
            .position(&model)
            .unwrap();
        assert_eq!(view.location(&model).unwrap(), [1.0, 2.0, 3.0]);

        let torus = surface("IFCTOROIDALSURFACE", &[5.0, 1.0]);
        let view = ToroidalSurface::new(EntityId(4), &torus)
            .position(&model)
            .unwrap();
        assert_eq!(view.location(&model).unwrap(), [1.0, 2.0, 3.0]);
    }

    /// A placement reference to an absent entity is reported, not panicked on.
    #[test]
    fn a_dangling_placement_reference_is_reported() {
        let model = Model::new();
        let plane = surface("IFCPLANE", &[]);
        let error = Plane::new(EntityId(1), &plane)
            .position(&model)
            .expect_err("placement 70 is not in the model");
        assert_eq!(error.entity(), Some(EntityId(1)));
    }

    /// A `Position` naming a 2D placement: the same slot layout starts with a
    /// point, so an unchecked wrap would read it as a 3D frame.
    fn model_with_2d_position() -> Model {
        let mut model = Model::new();
        model.insert(
            EntityId(60),
            Entity::new(
                "IFCCARTESIANPOINT",
                vec![Value::List(vec![Value::Real(1.0), Value::Real(2.0)])],
            ),
        );
        model.insert(
            EntityId(70),
            Entity::new("IFCAXIS2PLACEMENT2D", vec![Value::Ref(EntityId(60))]),
        );
        model
    }

    fn assert_wrong_placement(result: GeometryResult<Axis2Placement3D<'_>>) {
        let error = result.expect_err("#70 is not an IfcAxis2Placement3D");
        assert!(
            matches!(
                error,
                crate::GeometryError::WrongEntityType {
                    entity: EntityId(70),
                    expected: "IfcAxis2Placement3D",
                    ..
                }
            ),
            "got: {error:?}"
        );
    }

    #[test]
    fn a_plane_rejects_a_position_that_is_not_an_axis2_placement_3d() {
        let model = model_with_2d_position();
        let plane = surface("IFCPLANE", &[]);
        assert_wrong_placement(Plane::new(EntityId(1), &plane).position(&model));
    }

    #[test]
    fn a_cylinder_rejects_a_position_that_is_not_an_axis2_placement_3d() {
        let model = model_with_2d_position();
        let cylinder = surface("IFCCYLINDRICALSURFACE", &[2.0]);
        assert_wrong_placement(CylindricalSurface::new(EntityId(2), &cylinder).position(&model));
    }

    #[test]
    fn a_sphere_rejects_a_position_that_is_not_an_axis2_placement_3d() {
        let model = model_with_2d_position();
        let sphere = surface("IFCSPHERICALSURFACE", &[3.0]);
        assert_wrong_placement(SphericalSurface::new(EntityId(3), &sphere).position(&model));
    }

    #[test]
    fn a_torus_rejects_a_position_that_is_not_an_axis2_placement_3d() {
        let model = model_with_2d_position();
        let torus = surface("IFCTOROIDALSURFACE", &[5.0, 1.0]);
        assert_wrong_placement(ToroidalSurface::new(EntityId(4), &torus).position(&model));
    }
}