Skip to main content

ifc_geometry/curve/
polyline.rs

1//! `IfcPolyline` and `IfcIndexedPolyCurve`: the two vertex-list curves.
2//!
3//! # Why they are in one module
4//!
5//! Both describe a chain of points, but they differ in a way that matters for
6//! file size and for correctness. `IfcPolyline` holds a list of
7//! `IfcCartesianPoint` *entities*, one STEP record per vertex. An
8//! `IfcIndexedPolyCurve` holds a single `IfcCartesianPointList` plus integer
9//! indices into it, which is how IFC4 made large surveyed geometry tractable.
10//!
11//! # The 1-based index trap
12//!
13//! `IfcLineIndex` and `IfcArcIndex` are lists of `IfcPositiveInteger`, indexing
14//! the point list the way EXPRESS aggregates are indexed: **from 1**. Reading
15//! them as Rust indices shifts every vertex by one and produces geometry that
16//! looks almost right, which is the worst kind of wrong. This module never
17//! exposes a raw index: [`PolySegment`] hands back zero-based indices already
18//! converted and range-checked against the point count.
19
20use crate::error::GeometryResult;
21use crate::resource::point::{CartesianPoint, CartesianPointList};
22use crate::resource::resolve;
23use crate::slots::Slots;
24use ifc_model::{Entity, EntityId, Model, Value};
25
26/// `IfcPolyline` attribute slots.
27///
28/// From IFC4 ADD2 TC1: `IfcBoundedCurve` and its supertypes declare no
29/// explicit attributes, so `Points` is slot 0.
30pub(crate) mod polyline_slot {
31    /// `Points`: `LIST [2:?] OF IfcCartesianPoint`.
32    pub const POINTS: usize = 0;
33}
34
35/// `IfcIndexedPolyCurve` attribute slots.
36///
37/// From IFC4 ADD2 TC1.
38pub(crate) mod indexed_slot {
39    /// `Points`: an `IfcCartesianPointList` (2D or 3D).
40    pub const POINTS: usize = 0;
41    /// `Segments`: `OPTIONAL LIST [1:?] OF IfcSegmentIndexSelect`.
42    pub const SEGMENTS: usize = 1;
43    /// `SelfIntersect`: `OPTIONAL IfcBoolean`, informational only.
44    pub const SELF_INTERSECT: usize = 2;
45}
46
47/// A borrowed view of an `IfcPolyline`.
48#[derive(Debug, Clone, Copy)]
49pub struct Polyline<'m> {
50    slots: Slots<'m>,
51}
52
53impl<'m> Polyline<'m> {
54    /// Wrap an entity known to be an `IfcPolyline`.
55    pub fn new(id: EntityId, entity: &'m Entity) -> Self {
56        Self {
57            slots: Slots::new(id, entity),
58        }
59    }
60
61    /// The entity id.
62    pub fn id(&self) -> EntityId {
63        self.slots.id()
64    }
65
66    /// The `IfcCartesianPoint` references, in order.
67    ///
68    /// At least two are required by the schema; fewer is
69    /// [`crate::GeometryError::Degenerate`] because a one-point polyline has
70    /// no edge and would silently contribute nothing to a profile.
71    pub fn point_refs(&self) -> GeometryResult<Vec<EntityId>> {
72        let points = self.slots.req_ref_list(polyline_slot::POINTS, "Points")?;
73        if points.len() < 2 {
74            return Err(self.slots.degenerate(format!(
75                "Points must hold at least 2 entries, found {}",
76                points.len()
77            )));
78        }
79        Ok(points)
80    }
81
82    /// The vertices as typed point views, resolved from the model, in order.
83    ///
84    /// One dangling or mistyped vertex fails the whole call: dropping it would
85    /// change the shape without saying so.
86    pub fn points<'v>(&self, model: &'v Model) -> GeometryResult<Vec<CartesianPoint<'v>>> {
87        resolve::cartesian_points(model, self.id(), &self.point_refs()?)
88    }
89
90    /// Is the last point the same entity as the first?
91    ///
92    /// IFC closes a polyline by *repeating the point reference*, not with a
93    /// flag. A consumer building a face bound must know whether to add a
94    /// closing edge, and comparing coordinates instead of references would
95    /// need a tolerance the schema never defines.
96    ///
97    /// Note the converse is not guaranteed: a file may close a polyline with
98    /// two distinct `IfcCartesianPoint` records holding identical
99    /// coordinates. This reports only the reference-identity case, which is
100    /// what conforming exporters emit.
101    pub fn closes_by_repeating_first_point(&self) -> GeometryResult<bool> {
102        let points = self.point_refs()?;
103        Ok(points.first() == points.last())
104    }
105}
106
107/// One segment of an `IfcIndexedPolyCurve`, with indices already zero-based.
108///
109/// The variants mirror `IfcSegmentIndexSelect`. Cardinality is enforced on
110/// construction so a consumer never has to re-check that an arc really has
111/// three points.
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub enum PolySegment {
114    /// `IfcLineIndex`: a polyline run of 2 or more points.
115    ///
116    /// More than two indices means intermediate vertices, not a spline: every
117    /// consecutive pair is a straight edge.
118    Line(Vec<usize>),
119    /// `IfcArcIndex`: exactly start, a point *on* the arc, and end.
120    ///
121    /// The middle index is a point the arc passes through, **not** a centre.
122    /// Treating it as a centre is a common and silently plausible error.
123    Arc {
124        /// Index of the arc's start point.
125        start: usize,
126        /// Index of a point lying on the arc between start and end.
127        mid: usize,
128        /// Index of the arc's end point.
129        end: usize,
130    },
131}
132
133impl PolySegment {
134    /// The zero-based point indices this segment touches, in order.
135    pub fn indices(&self) -> Vec<usize> {
136        match self {
137            Self::Line(indices) => indices.clone(),
138            Self::Arc { start, mid, end } => vec![*start, *mid, *end],
139        }
140    }
141
142    /// Is this an arc segment?
143    pub fn is_arc(&self) -> bool {
144        matches!(self, Self::Arc { .. })
145    }
146}
147
148/// A borrowed view of an `IfcIndexedPolyCurve`.
149#[derive(Debug, Clone, Copy)]
150pub struct IndexedPolyCurve<'m> {
151    slots: Slots<'m>,
152}
153
154impl<'m> IndexedPolyCurve<'m> {
155    /// Wrap an entity known to be an `IfcIndexedPolyCurve`.
156    pub fn new(id: EntityId, entity: &'m Entity) -> Self {
157        Self {
158            slots: Slots::new(id, entity),
159        }
160    }
161
162    /// The entity id.
163    pub fn id(&self) -> EntityId {
164        self.slots.id()
165    }
166
167    /// The `IfcCartesianPointList2D` or `IfcCartesianPointList3D` reference.
168    pub fn points_ref(&self) -> GeometryResult<EntityId> {
169        self.slots.req_ref(indexed_slot::POINTS, "Points")
170    }
171
172    /// The point list as a typed view, resolved from the model.
173    ///
174    /// The concrete subtype fixes the dimension; see [`CartesianPointList`].
175    pub fn points<'v>(&self, model: &'v Model) -> GeometryResult<CartesianPointList<'v>> {
176        resolve::cartesian_point_list(model, self.id(), self.points_ref()?)
177    }
178
179    /// The informational `SelfIntersect` flag, `None` when absent or `.U.`.
180    pub fn self_intersect(&self) -> Option<bool> {
181        self.slots.opt_bool(indexed_slot::SELF_INTERSECT)
182    }
183
184    /// Does the file supply an explicit segment list?
185    ///
186    /// When it does not, the curve is every point joined in list order by
187    /// straight lines. That default is not stored anywhere, so a consumer
188    /// that only looks at `Segments` will draw nothing for a perfectly valid
189    /// curve.
190    pub fn has_explicit_segments(&self) -> bool {
191        self.slots.opt(indexed_slot::SEGMENTS).is_some()
192    }
193
194    /// The segments, with indices converted to zero-based and range-checked.
195    ///
196    /// `point_count` is the length of the referenced `IfcCartesianPointList`
197    /// and is required because the index bound cannot be checked without it;
198    /// an out-of-range index would otherwise reach a kernel as a panic.
199    ///
200    /// Returns an empty vector when `Segments` is absent. Use
201    /// [`Self::has_explicit_segments`] to distinguish that from an explicitly
202    /// empty list, and see [`Self::implicit_polyline_indices`] for the
203    /// implied all-points-in-order curve.
204    pub fn segments(&self, point_count: usize) -> GeometryResult<Vec<PolySegment>> {
205        let Some(value) = self.slots.opt(indexed_slot::SEGMENTS) else {
206            return Ok(Vec::new());
207        };
208        let items = value.as_list().ok_or_else(|| {
209            self.slots
210                .degenerate("Segments must be a list of IfcSegmentIndexSelect")
211        })?;
212        items
213            .iter()
214            .map(|item| self.parse_segment(item, point_count))
215            .collect()
216    }
217
218    /// The zero-based indices implied when `Segments` is absent.
219    ///
220    /// Simply `0..point_count`, but naming it keeps the schema default in one
221    /// place instead of re-derived at every call site.
222    pub fn implicit_polyline_indices(point_count: usize) -> Vec<usize> {
223        (0..point_count).collect()
224    }
225
226    fn parse_segment(&self, item: &Value, point_count: usize) -> GeometryResult<PolySegment> {
227        // A conforming file writes `IFCLINEINDEX((1,2))`, so the select
228        // arrives as a typed wrapper whose name is the only thing telling
229        // line from arc. Some writers drop the wrapper on the outer list but
230        // keep it here; nothing legitimate omits it entirely.
231        let Value::Typed { type_name, value } = item else {
232            return Err(self.slots.degenerate(
233                "segment is not a typed IfcLineIndex/IfcArcIndex; the select tag is required \
234                 to tell a line from an arc",
235            ));
236        };
237        let raw = value.as_list().ok_or_else(|| {
238            self.slots
239                .degenerate(format!("{type_name} must wrap a list of indices"))
240        })?;
241
242        let mut indices = Vec::with_capacity(raw.len());
243        for v in raw {
244            let n = match v.unwrap_typed() {
245                Value::Integer(i) => *i,
246                other => {
247                    return Err(self
248                        .slots
249                        .degenerate(format!("{type_name} index is not an integer: {other:?}")));
250                }
251            };
252            // EXPRESS aggregates are 1-based. This subtraction is the entire
253            // reason the raw indices are never exposed.
254            if n < 1 {
255                return Err(self.slots.degenerate(format!(
256                    "{type_name} index {n} is not a positive integer; \
257                     IfcPositiveInteger starts at 1"
258                )));
259            }
260            let zero_based = (n - 1) as usize;
261            if zero_based >= point_count {
262                return Err(self.slots.degenerate(format!(
263                    "{type_name} index {n} is out of range for a point list of {point_count}"
264                )));
265            }
266            indices.push(zero_based);
267        }
268
269        match type_name.to_ascii_uppercase().as_str() {
270            "IFCLINEINDEX" => {
271                if indices.len() < 2 {
272                    return Err(self.slots.degenerate(format!(
273                        "IfcLineIndex needs at least 2 indices, found {}",
274                        indices.len()
275                    )));
276                }
277                Ok(PolySegment::Line(indices))
278            }
279            "IFCARCINDEX" => {
280                if indices.len() != 3 {
281                    return Err(self.slots.degenerate(format!(
282                        "IfcArcIndex needs exactly 3 indices (start, on-arc, end), found {}",
283                        indices.len()
284                    )));
285                }
286                Ok(PolySegment::Arc {
287                    start: indices[0],
288                    mid: indices[1],
289                    end: indices[2],
290                })
291            }
292            other => Err(self
293                .slots
294                .degenerate(format!("{other} is not an IfcSegmentIndexSelect member"))),
295        }
296    }
297}
298
299#[cfg(test)]
300mod tests {
301    use super::*;
302
303    fn refs(ids: &[u64]) -> Value {
304        Value::List(ids.iter().map(|i| Value::Ref(EntityId(*i))).collect())
305    }
306
307    fn index_select(name: &str, indices: &[i64]) -> Value {
308        Value::Typed {
309            type_name: name.into(),
310            value: Box::new(Value::List(
311                indices.iter().map(|i| Value::Integer(*i)).collect(),
312            )),
313        }
314    }
315
316    fn indexed(segments: Value) -> Entity {
317        Entity::new(
318            "IFCINDEXEDPOLYCURVE",
319            vec![Value::Ref(EntityId(100)), segments, Value::Bool(false)],
320        )
321    }
322
323    fn point(values: &[f64]) -> Entity {
324        Entity::new(
325            "IFCCARTESIANPOINT",
326            vec![Value::List(
327                values.iter().copied().map(Value::Real).collect(),
328            )],
329        )
330    }
331
332    #[test]
333    fn polyline_points_resolve_in_file_order() {
334        let mut model = Model::new();
335        model.insert(EntityId(1), point(&[0.0, 0.0]));
336        model.insert(EntityId(2), point(&[1.0, 0.0]));
337        let e = Entity::new("IFCPOLYLINE", vec![refs(&[2, 1])]);
338        let points = Polyline::new(EntityId(9), &e).points(&model).unwrap();
339        let ids: Vec<_> = points.iter().map(|p| p.id()).collect();
340        assert_eq!(ids, vec![EntityId(2), EntityId(1)]);
341        assert_eq!(points[0].coordinates().unwrap(), vec![1.0, 0.0]);
342    }
343
344    #[test]
345    fn a_polyline_vertex_of_the_wrong_type_fails_the_whole_list() {
346        let mut model = Model::new();
347        model.insert(EntityId(1), point(&[0.0, 0.0]));
348        model.insert(EntityId(2), Entity::new("IFCDIRECTION", vec![]));
349        let e = Entity::new("IFCPOLYLINE", vec![refs(&[1, 2])]);
350        let err = Polyline::new(EntityId(9), &e).points(&model).unwrap_err();
351        assert!(matches!(
352            err,
353            crate::GeometryError::WrongEntityType {
354                entity: EntityId(2),
355                ..
356            }
357        ));
358    }
359
360    #[test]
361    fn indexed_points_resolve_to_the_declared_list_subtype() {
362        let mut model = Model::new();
363        model.insert(
364            EntityId(100),
365            Entity::new(
366                "IFCCARTESIANPOINTLIST3D",
367                vec![Value::List(vec![Value::List(vec![
368                    Value::Real(0.0),
369                    Value::Real(0.0),
370                    Value::Real(1.0),
371                ])])],
372            ),
373        );
374        let e = indexed(Value::Null);
375        let list = IndexedPolyCurve::new(EntityId(9), &e)
376            .points(&model)
377            .unwrap();
378        assert_eq!(list.id(), EntityId(100));
379        assert_eq!(list.dimension(), 3);
380    }
381
382    #[test]
383    fn indexed_points_reject_a_single_point_and_a_dangling_list() {
384        let mut model = Model::new();
385        model.insert(EntityId(100), point(&[0.0, 0.0]));
386        let e = indexed(Value::Null);
387        let view = IndexedPolyCurve::new(EntityId(9), &e);
388        assert!(matches!(
389            view.points(&model).unwrap_err(),
390            crate::GeometryError::WrongEntityType { .. }
391        ));
392        let err = view.points(&Model::new()).unwrap_err();
393        assert_eq!(err.entity(), Some(EntityId(9)));
394    }
395
396    #[test]
397    fn polyline_reads_its_points_in_file_order() {
398        let e = Entity::new("IFCPOLYLINE", vec![refs(&[1, 2, 3])]);
399        let view = Polyline::new(EntityId(1), &e);
400        assert_eq!(
401            view.point_refs().unwrap(),
402            vec![EntityId(1), EntityId(2), EntityId(3)]
403        );
404    }
405
406    #[test]
407    fn polyline_with_fewer_than_two_points_is_degenerate() {
408        let e = Entity::new("IFCPOLYLINE", vec![refs(&[1])]);
409        let err = Polyline::new(EntityId(4), &e).point_refs().unwrap_err();
410        assert!(err.to_string().contains("#4"), "got: {err}");
411    }
412
413    /// Closure is expressed by repeating the first point reference, and a
414    /// consumer must not add a duplicate closing edge when it is already there.
415    #[test]
416    fn polyline_closure_is_detected_from_a_repeated_first_reference() {
417        let closed = Entity::new("IFCPOLYLINE", vec![refs(&[1, 2, 3, 1])]);
418        let open = Entity::new("IFCPOLYLINE", vec![refs(&[1, 2, 3])]);
419        assert!(Polyline::new(EntityId(1), &closed)
420            .closes_by_repeating_first_point()
421            .unwrap());
422        assert!(!Polyline::new(EntityId(1), &open)
423            .closes_by_repeating_first_point()
424            .unwrap());
425    }
426
427    /// The single most damaging bug in this module would be an off-by-one, so
428    /// it is pinned by an explicit expected value rather than a round trip.
429    #[test]
430    fn one_based_file_indices_become_zero_based_rust_indices() {
431        let e = indexed(Value::List(vec![index_select("IFCLINEINDEX", &[1, 2, 3])]));
432        let segments = IndexedPolyCurve::new(EntityId(1), &e).segments(5).unwrap();
433        assert_eq!(segments, vec![PolySegment::Line(vec![0, 1, 2])]);
434    }
435
436    #[test]
437    fn arc_index_names_its_middle_point_as_on_arc_not_as_a_centre() {
438        let e = indexed(Value::List(vec![index_select("IFCARCINDEX", &[3, 4, 5])]));
439        let segments = IndexedPolyCurve::new(EntityId(1), &e).segments(9).unwrap();
440        assert_eq!(
441            segments,
442            vec![PolySegment::Arc {
443                start: 2,
444                mid: 3,
445                end: 4
446            }]
447        );
448        assert!(segments[0].is_arc());
449    }
450
451    #[test]
452    fn an_index_past_the_end_of_the_point_list_is_rejected() {
453        let e = indexed(Value::List(vec![index_select("IFCLINEINDEX", &[1, 9])]));
454        let err = IndexedPolyCurve::new(EntityId(2), &e)
455            .segments(3)
456            .unwrap_err();
457        assert!(err.to_string().contains("out of range"), "got: {err}");
458    }
459
460    /// Index 0 cannot be a valid IfcPositiveInteger, and accepting it would
461    /// underflow the 1-based conversion.
462    #[test]
463    fn index_zero_is_rejected_rather_than_underflowing() {
464        let e = indexed(Value::List(vec![index_select("IFCLINEINDEX", &[0, 1])]));
465        assert!(IndexedPolyCurve::new(EntityId(1), &e).segments(3).is_err());
466    }
467
468    #[test]
469    fn arc_index_with_the_wrong_cardinality_is_rejected() {
470        let e = indexed(Value::List(vec![index_select("IFCARCINDEX", &[1, 2])]));
471        let err = IndexedPolyCurve::new(EntityId(1), &e)
472            .segments(5)
473            .unwrap_err();
474        assert!(err.to_string().contains("exactly 3"), "got: {err}");
475    }
476
477    #[test]
478    fn line_index_needs_at_least_two_indices() {
479        let e = indexed(Value::List(vec![index_select("IFCLINEINDEX", &[2])]));
480        assert!(IndexedPolyCurve::new(EntityId(1), &e).segments(5).is_err());
481    }
482
483    /// Without the select tag there is no way to know whether three indices
484    /// mean two straight edges or one arc, so guessing is not an option.
485    #[test]
486    fn an_untagged_segment_is_rejected_rather_than_assumed_to_be_a_line() {
487        let e = indexed(Value::List(vec![Value::List(vec![
488            Value::Integer(1),
489            Value::Integer(2),
490        ])]));
491        let err = IndexedPolyCurve::new(EntityId(1), &e)
492            .segments(5)
493            .unwrap_err();
494        assert!(err.to_string().contains("select tag"), "got: {err}");
495    }
496
497    /// Absent Segments means "all points in order", which is a real curve and
498    /// not an empty one.
499    #[test]
500    fn absent_segments_is_distinguishable_from_an_empty_segment_list() {
501        let absent = Entity::new("IFCINDEXEDPOLYCURVE", vec![Value::Ref(EntityId(100))]);
502        let view = IndexedPolyCurve::new(EntityId(1), &absent);
503        assert!(!view.has_explicit_segments());
504        assert!(view.segments(4).unwrap().is_empty());
505        assert_eq!(
506            IndexedPolyCurve::implicit_polyline_indices(4),
507            vec![0, 1, 2, 3]
508        );
509
510        let empty = indexed(Value::List(vec![]));
511        assert!(IndexedPolyCurve::new(EntityId(1), &empty).has_explicit_segments());
512    }
513
514    #[test]
515    fn mixed_line_and_arc_segments_keep_their_file_order() {
516        let e = indexed(Value::List(vec![
517            index_select("IFCLINEINDEX", &[1, 2]),
518            index_select("IFCARCINDEX", &[2, 3, 4]),
519            index_select("IFCLINEINDEX", &[4, 5]),
520        ]));
521        let segments = IndexedPolyCurve::new(EntityId(1), &e).segments(5).unwrap();
522        assert_eq!(segments.len(), 3);
523        assert!(!segments[0].is_arc());
524        assert!(segments[1].is_arc());
525        assert_eq!(segments[2].indices(), vec![3, 4]);
526    }
527}