Skip to main content

ifc_geometry/surface/
swept.rs

1//! `IfcSweptSurface`: a surface made by moving a profile.
2//!
3//! Covers `IfcSurfaceOfLinearExtrusion` and `IfcSurfaceOfRevolution`.
4//!
5//! # `SweptCurve` is an `IfcProfileDef`, not an `IfcCurve`
6//!
7//! This is the trap. The attribute is named for a curve and typed as a
8//! profile, and an `IfcProfileDef` carries a `ProfileType` of `AREA` or
9//! `CURVE`. Only the *outer curve* of the profile is swept -- a swept surface
10//! is a surface, not a solid, so an `AREA` profile's inner voids contribute
11//! nothing. A consumer that hands the profile to the same code path used for
12//! `IfcExtrudedAreaSolid` will build a solid where the file described a shell.
13//!
14//! # `Position` is optional and its absence is not the identity
15//!
16//! The profile is defined in its own 2D coordinate system; `Position` places
17//! that system in 3D. When absent the profile's XY plane coincides with the
18//! containing representation's XY plane. Treating an absent `Position` as an
19//! error rejects valid files; treating it as "no transform at all" is right
20//! only because the default *is* the identity in the parent's space.
21//!
22//! # Revolution: axis, not direction
23//!
24//! `AxisPosition` is an `IfcAxis1Placement` -- a point plus a direction. Both
25//! halves matter: revolving about a line through the origin gives a different
26//! surface from revolving about a parallel line one metre away. Code that
27//! reads only the direction produces a surface of the right shape in the wrong
28//! place, which is much harder to notice than a missing surface.
29
30use crate::error::GeometryResult;
31use crate::resource::direction::Direction;
32use crate::resource::placement::{Axis1Placement, Axis2Placement3D};
33use crate::resource::resolve;
34use crate::slots::Slots;
35use ifc_model::{Entity, EntityId, Model};
36
37/// `IfcSweptSurface` family attribute slots.
38///
39/// From IFC4 ADD2 TC1: slots 0 and 1 are inherited from `IfcSweptSurface` by
40/// both subtypes; each subtype's own attributes follow from slot 2.
41pub(crate) mod slot {
42    /// `SweptCurve`: `IfcProfileDef`, from `IfcSweptSurface`.
43    pub const SWEPT_CURVE: usize = 0;
44    /// `Position`: `OPTIONAL IfcAxis2Placement3D`, from `IfcSweptSurface`.
45    pub const POSITION: usize = 1;
46    /// `ExtrudedDirection` on `IfcSurfaceOfLinearExtrusion`.
47    pub const EXTRUDED_DIRECTION: usize = 2;
48    /// `Depth` on `IfcSurfaceOfLinearExtrusion`.
49    pub const DEPTH: usize = 3;
50    /// `AxisPosition` on `IfcSurfaceOfRevolution`.
51    pub const AXIS_POSITION: usize = 2;
52}
53
54/// Shared accessors for both swept surfaces.
55///
56/// Split out so the two views cannot drift on the attributes they inherit.
57#[derive(Debug, Clone, Copy)]
58struct SweptBase<'m> {
59    slots: Slots<'m>,
60}
61
62impl<'m> SweptBase<'m> {
63    fn swept_curve_ref(&self) -> GeometryResult<EntityId> {
64        self.slots.req_ref(slot::SWEPT_CURVE, "SweptCurve")
65    }
66
67    fn position_ref(&self) -> Option<EntityId> {
68        self.slots.opt_ref(slot::POSITION)
69    }
70
71    fn position<'v>(&self, model: &'v Model) -> GeometryResult<Option<Axis2Placement3D<'v>>> {
72        self.position_ref()
73            .map(|id| resolve::axis2_placement_3d(model, self.slots.id(), id))
74            .transpose()
75    }
76}
77
78/// A borrowed view of an `IfcSurfaceOfLinearExtrusion`.
79#[derive(Debug, Clone, Copy)]
80pub struct SurfaceOfLinearExtrusion<'m> {
81    base: SweptBase<'m>,
82}
83
84impl<'m> SurfaceOfLinearExtrusion<'m> {
85    /// Wrap an entity known to be an `IfcSurfaceOfLinearExtrusion`.
86    pub fn new(id: EntityId, entity: &'m Entity) -> Self {
87        Self {
88            base: SweptBase {
89                slots: Slots::new(id, entity),
90            },
91        }
92    }
93
94    /// The entity id.
95    pub fn id(&self) -> EntityId {
96        self.base.slots.id()
97    }
98
99    /// The `IfcProfileDef` whose outer curve is swept.
100    ///
101    /// A profile, not a curve, despite the attribute name. Only its outer
102    /// curve contributes; see the module docs.
103    ///
104    /// Stays a reference: profiles are read by
105    /// [`crate::describe_profile`], the one owner of `IfcProfileDef`
106    /// families, so this module does not define a competing profile view.
107    pub fn swept_curve_ref(&self) -> GeometryResult<EntityId> {
108        self.base.swept_curve_ref()
109    }
110
111    /// The optional placement of the profile's coordinate system.
112    ///
113    /// `None` means the identity in the containing representation's space,
114    /// which is a legal and common encoding, not a missing attribute.
115    pub fn position_ref(&self) -> Option<EntityId> {
116        self.base.position_ref()
117    }
118
119    /// The placement as a typed view, resolved from the model.
120    ///
121    /// `Ok(None)` when absent (the identity, see [`Self::position_ref`]); a
122    /// present but dangling or mistyped reference is an error, never `None`.
123    pub fn position<'v>(&self, model: &'v Model) -> GeometryResult<Option<Axis2Placement3D<'v>>> {
124        self.base.position(model)
125    }
126
127    /// The `IfcDirection` the profile is swept along.
128    ///
129    /// Given in the profile's own coordinate system, so it must be transformed
130    /// by `Position` before use in model space.
131    pub fn extruded_direction_ref(&self) -> GeometryResult<EntityId> {
132        self.base
133            .slots
134            .req_ref(slot::EXTRUDED_DIRECTION, "ExtrudedDirection")
135    }
136
137    /// The sweep direction as a typed view, resolved from the model.
138    ///
139    /// Still in the profile's coordinate system and unnormalized; call
140    /// [`Direction::unit`] before scaling it by [`Self::depth`].
141    pub fn extruded_direction<'v>(&self, model: &'v Model) -> GeometryResult<Direction<'v>> {
142        resolve::direction(model, self.id(), self.extruded_direction_ref()?)
143    }
144
145    /// The extrusion depth, guaranteed non-zero.
146    ///
147    /// A zero depth collapses the surface to its generating curve. IFC4
148    /// declares this `IfcLengthMeasure` rather than the positive variant, so a
149    /// negative depth is legal and means the sweep runs the other way; only
150    /// zero is rejected.
151    pub fn depth(&self) -> GeometryResult<f64> {
152        let depth = self.base.slots.req_f64(slot::DEPTH, "Depth")?;
153        if depth == 0.0 {
154            return Err(self
155                .base
156                .slots
157                .degenerate("Depth is zero; the surface collapses to its generating curve"));
158        }
159        Ok(depth)
160    }
161}
162
163/// A borrowed view of an `IfcSurfaceOfRevolution`.
164#[derive(Debug, Clone, Copy)]
165pub struct SurfaceOfRevolution<'m> {
166    base: SweptBase<'m>,
167}
168
169impl<'m> SurfaceOfRevolution<'m> {
170    /// Wrap an entity known to be an `IfcSurfaceOfRevolution`.
171    pub fn new(id: EntityId, entity: &'m Entity) -> Self {
172        Self {
173            base: SweptBase {
174                slots: Slots::new(id, entity),
175            },
176        }
177    }
178
179    /// The entity id.
180    pub fn id(&self) -> EntityId {
181        self.base.slots.id()
182    }
183
184    /// The `IfcProfileDef` whose outer curve is revolved.
185    ///
186    /// Stays a reference for the same reason as
187    /// [`SurfaceOfLinearExtrusion::swept_curve_ref`]:
188    /// [`crate::describe_profile`] owns profile reading.
189    pub fn swept_curve_ref(&self) -> GeometryResult<EntityId> {
190        self.base.swept_curve_ref()
191    }
192
193    /// The optional placement of the profile's coordinate system.
194    pub fn position_ref(&self) -> Option<EntityId> {
195        self.base.position_ref()
196    }
197
198    /// The placement as a typed view; `Ok(None)` when absent.
199    pub fn position<'v>(&self, model: &'v Model) -> GeometryResult<Option<Axis2Placement3D<'v>>> {
200        self.base.position(model)
201    }
202
203    /// The `IfcAxis1Placement` giving the axis of revolution.
204    ///
205    /// Carries a location *and* a direction. Both are needed: the offset
206    /// between the axis and the profile is what makes the surface a torus
207    /// rather than a sphere.
208    pub fn axis_position_ref(&self) -> GeometryResult<EntityId> {
209        self.base.slots.req_ref(slot::AXIS_POSITION, "AxisPosition")
210    }
211
212    /// The axis of revolution as a typed view, resolved from the model.
213    ///
214    /// An `IfcAxis1Placement` only: a 2D or 3D axis-2 placement is not what
215    /// the schema declares, and reading its `RefDirection` as the axis would
216    /// revolve about the wrong line.
217    pub fn axis_position<'v>(&self, model: &'v Model) -> GeometryResult<Axis1Placement<'v>> {
218        resolve::axis1_placement(model, self.id(), self.axis_position_ref()?)
219    }
220}
221
222#[cfg(test)]
223mod tests {
224    use super::*;
225    use ifc_model::Value;
226
227    fn extrusion(position: Value, depth: Value) -> Entity {
228        Entity::new(
229            "IFCSURFACEOFLINEAREXTRUSION",
230            vec![
231                Value::Ref(EntityId(80)),
232                position,
233                Value::Ref(EntityId(82)),
234                depth,
235            ],
236        )
237    }
238
239    #[test]
240    fn extrusion_reads_inherited_swept_curve_before_its_own_direction_and_depth() {
241        let e = extrusion(Value::Ref(EntityId(81)), Value::Real(3.0));
242        let view = SurfaceOfLinearExtrusion::new(EntityId(1), &e);
243        assert_eq!(view.swept_curve_ref().unwrap(), EntityId(80));
244        assert_eq!(view.position_ref(), Some(EntityId(81)));
245        assert_eq!(view.extruded_direction_ref().unwrap(), EntityId(82));
246        assert_eq!(view.depth().unwrap(), 3.0);
247    }
248
249    /// An absent Position is the schema's own default, not a broken file.
250    #[test]
251    fn an_absent_position_is_reported_as_none_rather_than_as_an_error() {
252        let e = extrusion(Value::Null, Value::Real(1.0));
253        let view = SurfaceOfLinearExtrusion::new(EntityId(1), &e);
254        assert_eq!(view.position_ref(), None);
255        // The rest of the surface still reads, since Position is optional.
256        assert_eq!(view.extruded_direction_ref().unwrap(), EntityId(82));
257        assert_eq!(view.depth().unwrap(), 1.0);
258    }
259
260    /// IfcLengthMeasure, not the positive variant: reversal is legal.
261    #[test]
262    fn a_negative_depth_is_accepted_because_it_only_reverses_the_sweep() {
263        let e = extrusion(Value::Ref(EntityId(81)), Value::Real(-2.0));
264        assert_eq!(
265            SurfaceOfLinearExtrusion::new(EntityId(1), &e)
266                .depth()
267                .unwrap(),
268            -2.0
269        );
270    }
271
272    #[test]
273    fn a_zero_depth_is_degenerate() {
274        let e = extrusion(Value::Ref(EntityId(81)), Value::Real(0.0));
275        let err = SurfaceOfLinearExtrusion::new(EntityId(5), &e)
276            .depth()
277            .unwrap_err();
278        assert!(err.to_string().contains("#5"), "got: {err}");
279        assert!(err.to_string().contains("zero"), "got: {err}");
280    }
281
282    #[test]
283    fn depth_reads_through_a_length_measure_wrapper() {
284        let e = extrusion(
285            Value::Ref(EntityId(81)),
286            Value::Typed {
287                type_name: "IFCLENGTHMEASURE".into(),
288                value: Box::new(Value::Real(1.5)),
289            },
290        );
291        assert_eq!(
292            SurfaceOfLinearExtrusion::new(EntityId(1), &e)
293                .depth()
294                .unwrap(),
295            1.5
296        );
297    }
298
299    /// AxisPosition sits at slot 2, where the extrusion keeps
300    /// ExtrudedDirection; reading the wrong slot would silently succeed.
301    #[test]
302    fn revolution_reads_its_axis_from_the_slot_after_the_inherited_two() {
303        let e = Entity::new(
304            "IFCSURFACEOFREVOLUTION",
305            vec![
306                Value::Ref(EntityId(90)),
307                Value::Ref(EntityId(91)),
308                Value::Ref(EntityId(92)),
309            ],
310        );
311        let view = SurfaceOfRevolution::new(EntityId(1), &e);
312        assert_eq!(view.swept_curve_ref().unwrap(), EntityId(90));
313        assert_eq!(view.position_ref(), Some(EntityId(91)));
314        assert_eq!(view.axis_position_ref().unwrap(), EntityId(92));
315    }
316
317    #[test]
318    fn a_revolution_without_an_axis_reports_the_attribute_by_name() {
319        let e = Entity::new(
320            "IFCSURFACEOFREVOLUTION",
321            vec![Value::Ref(EntityId(90)), Value::Null],
322        );
323        let err = SurfaceOfRevolution::new(EntityId(1), &e)
324            .axis_position_ref()
325            .unwrap_err();
326        assert!(err.to_string().contains("AxisPosition"), "got: {err}");
327    }
328
329    fn frame_model() -> Model {
330        let reals = |v: &[f64]| Value::List(v.iter().copied().map(Value::Real).collect());
331        let mut m = Model::new();
332        m.insert(
333            EntityId(70),
334            Entity::new("IFCCARTESIANPOINT", vec![reals(&[1.0, 0.0, 0.0])]),
335        );
336        m.insert(
337            EntityId(71),
338            Entity::new("IFCDIRECTION", vec![reals(&[0.0, 0.0, 2.0])]),
339        );
340        let at = vec![Value::Ref(EntityId(70)), Value::Ref(EntityId(71))];
341        m.insert(EntityId(81), Entity::new("IFCAXIS2PLACEMENT3D", at.clone()));
342        m.insert(
343            EntityId(82),
344            Entity::new("IFCDIRECTION", vec![reals(&[0.0, 3.0, 0.0])]),
345        );
346        m.insert(EntityId(92), Entity::new("IFCAXIS1PLACEMENT", at));
347        m
348    }
349
350    #[test]
351    fn extrusion_position_and_direction_resolve_to_typed_views() {
352        let m = frame_model();
353        let e = extrusion(Value::Ref(EntityId(81)), Value::Real(1.0));
354        let view = SurfaceOfLinearExtrusion::new(EntityId(1), &e);
355        let position = view.position(&m).unwrap().expect("Position is present");
356        assert_eq!(position.location(&m).unwrap(), [1.0, 0.0, 0.0]);
357        assert_eq!(
358            view.extruded_direction(&m).unwrap().unit().unwrap(),
359            [0.0, 1.0, 0.0]
360        );
361
362        let e = extrusion(Value::Null, Value::Real(1.0));
363        let view = SurfaceOfLinearExtrusion::new(EntityId(1), &e);
364        assert!(
365            view.position(&m).unwrap().is_none(),
366            "absent is the identity"
367        );
368    }
369
370    /// Present-but-wrong must not collapse into the "absent" identity case.
371    #[test]
372    fn a_mistyped_extrusion_position_or_direction_is_an_error_not_none() {
373        let m = frame_model();
374        let e = extrusion(Value::Ref(EntityId(92)), Value::Real(1.0));
375        let view = SurfaceOfLinearExtrusion::new(EntityId(1), &e);
376        assert!(matches!(
377            view.position(&m).unwrap_err(),
378            crate::GeometryError::WrongEntityType {
379                entity: EntityId(92),
380                ..
381            }
382        ));
383        let err = view.extruded_direction(&Model::new()).unwrap_err();
384        assert_eq!(err.entity(), Some(EntityId(1)));
385    }
386
387    #[test]
388    fn revolution_axis_and_position_resolve_to_typed_views() {
389        let m = frame_model();
390        let refs = [90, 81, 92].map(|id| Value::Ref(EntityId(id))).to_vec();
391        let e = Entity::new("IFCSURFACEOFREVOLUTION", refs);
392        let view = SurfaceOfRevolution::new(EntityId(1), &e);
393        let axis = view.axis_position(&m).unwrap();
394        assert_eq!(axis.location(&m).unwrap(), [1.0, 0.0, 0.0]);
395        assert_eq!(axis.axis(&m).unwrap(), [0.0, 0.0, 1.0]);
396        assert_eq!(view.position(&m).unwrap().unwrap().id(), EntityId(81));
397    }
398
399    /// An axis-2 placement in the axis slot is the wrong entity, not a
400    /// placement whose Z can stand in for the axis.
401    #[test]
402    fn a_revolution_axis_that_is_an_axis2_placement_is_a_typed_error() {
403        let m = frame_model();
404        let refs = [90, 81, 81].map(|id| Value::Ref(EntityId(id))).to_vec();
405        let e = Entity::new("IFCSURFACEOFREVOLUTION", refs);
406        let err = SurfaceOfRevolution::new(EntityId(1), &e)
407            .axis_position(&m)
408            .unwrap_err();
409        assert!(matches!(
410            err,
411            crate::GeometryError::WrongEntityType {
412                entity: EntityId(81),
413                expected: "IfcAxis1Placement",
414                ..
415            }
416        ));
417    }
418
419    #[test]
420    fn a_swept_surface_without_its_profile_reports_the_attribute_by_name() {
421        let e = Entity::new("IFCSURFACEOFLINEAREXTRUSION", vec![]);
422        let err = SurfaceOfLinearExtrusion::new(EntityId(1), &e)
423            .swept_curve_ref()
424            .unwrap_err();
425        assert!(err.to_string().contains("SweptCurve"), "got: {err}");
426    }
427}