ifc_geometry/solid/tessellated/mod.rs
1//! Tessellated geometry: explicit meshes addressed by index.
2//!
3//! # THE off-by-one that corrupts every mesh
4//!
5//! Every index in this schema is **1-BASED**. `CoordIndex`, `PnIndex` and
6//! `InnerCoordIndices` all count from 1 into the coordinate list, because
7//! EXPRESS aggregates are 1-based and the values are typed `IfcPositiveInteger`
8//! -- the schema literally cannot express a 0.
9//!
10//! Rust slices are 0-based. Feeding a raw `CoordIndex` to a `Vec` either panics
11//! at the last vertex or, far worse, shifts every triangle by one vertex and
12//! produces a mesh that still renders: recognisable, watertight-looking, and
13//! wrong everywhere. This is the single most damaging mistake available in IFC
14//! geometry.
15//!
16//! The views here therefore expose **both** forms explicitly:
17//! `*_indices_1based()` returns the file's own numbers, `*_indices_0based()`
18//! returns slice-ready indices and errors on a 0 rather than wrapping.
19//!
20//! # The PnIndex indirection
21//!
22//! When `PnIndex` is present the face indices do **not** point into
23//! `Coordinates` directly. They point into `PnIndex`, and the value found there
24//! is the (1-based) position in `Coordinates`. Skipping the hop silently
25//! reorders vertices whenever `PnIndex` is not the identity permutation, which
26//! is exactly when an exporter bothered to write it.
27//!
28//! # Coordinates are read by `resource::point`
29//!
30//! `IfcCartesianPointList3D` belongs to `IfcGeometryResource`, owned by
31//! [`crate::resource::point`]. These views return its `EntityId`, and
32//! [`TessellatedFaceSet::coordinate_list`] resolves it into that module's view.
33
34pub mod irregular_network;
35pub mod polygonal;
36pub mod triangulated;
37
38pub use irregular_network::TriangulatedIrregularNetwork;
39pub use polygonal::{IndexedPolygonalFace, IndexedPolygonalFaceWithVoids, PolygonalFaceSet};
40pub use triangulated::TriangulatedFaceSet;
41
42use crate::error::{GeometryError, GeometryResult};
43use crate::resource::point::CartesianPointList3D;
44use crate::resource::resolve;
45use crate::slots::Slots;
46use ifc_model::{Entity, EntityId, Model, Value};
47
48/// Tessellated face set slots shared by both concrete face sets.
49///
50/// EXPRESS (IFC4 ADD2 TC1): `IfcTessellatedFaceSet` declares `Coordinates`;
51/// `IfcTessellatedItem` and `IfcGeometricRepresentationItem` declare no
52/// explicit attributes, so `Coordinates` is absolute slot 0 in both subtypes.
53pub(super) mod face_set_slot {
54 /// `Coordinates : IfcCartesianPointList3D`, on `IfcTessellatedFaceSet`.
55 pub const COORDINATES: usize = 0;
56}
57
58/// `IfcTessellatedItem`: the abstract root of the tessellation family.
59///
60/// It declares no attributes. The view exists so a caller holding an
61/// unclassified tessellated entity can name it in a diagnostic and dispatch on
62/// the type, which is the only thing the supertype offers.
63#[derive(Debug, Clone, Copy)]
64pub struct TessellatedItem<'m> {
65 slots: Slots<'m>,
66}
67
68impl<'m> TessellatedItem<'m> {
69 /// Wrap an entity assumed to be an `IfcTessellatedItem` subtype.
70 pub fn new(id: EntityId, entity: &'m Entity) -> Self {
71 Self {
72 slots: Slots::new(id, entity),
73 }
74 }
75
76 /// The entity id.
77 pub fn id(&self) -> EntityId {
78 self.slots.id()
79 }
80
81 /// The IFC type name, naming the concrete subtype.
82 pub fn type_name(&self) -> &'m str {
83 self.slots.type_name()
84 }
85
86 /// Is this a concrete face set rather than an indexed face?
87 ///
88 /// `IfcIndexedPolygonalFace` is also an `IfcTessellatedItem`, so "is a
89 /// tessellated item" does not imply "has coordinates". The IFC4X3
90 /// `IfcTriangulatedIrregularNetwork` is an `IfcTriangulatedFaceSet`
91 /// subtype and carries the same `Coordinates`.
92 pub fn is_face_set(&self) -> bool {
93 let n = self.type_name();
94 n.eq_ignore_ascii_case("IFCTRIANGULATEDFACESET")
95 || n.eq_ignore_ascii_case(irregular_network::TYPE)
96 || n.eq_ignore_ascii_case("IFCPOLYGONALFACESET")
97 }
98}
99
100/// `IfcTessellatedFaceSet`: the abstract face set, giving access to
101/// `Coordinates`.
102///
103/// Usable over either concrete face set, since `Coordinates` is slot 0 in both.
104#[derive(Debug, Clone, Copy)]
105pub struct TessellatedFaceSet<'m> {
106 slots: Slots<'m>,
107}
108
109impl<'m> TessellatedFaceSet<'m> {
110 /// Wrap an entity assumed to be an `IfcTessellatedFaceSet` subtype.
111 pub fn new(id: EntityId, entity: &'m Entity) -> Self {
112 Self {
113 slots: Slots::new(id, entity),
114 }
115 }
116
117 /// Build from already-wrapped slots, for a subtype delegating upward.
118 pub(super) fn from_slots(slots: Slots<'m>) -> Self {
119 Self { slots }
120 }
121
122 /// The entity id.
123 pub fn id(&self) -> EntityId {
124 self.slots.id()
125 }
126
127 /// The IFC type name, naming the concrete subtype.
128 pub fn type_name(&self) -> &'m str {
129 self.slots.type_name()
130 }
131
132 /// The `IfcCartesianPointList3D` reference holding the vertices.
133 ///
134 /// [`Self::coordinate_list`] resolves it through `resource::point`, which
135 /// owns the point-list view; this module does not define a competing one.
136 pub fn coordinates(&self) -> GeometryResult<EntityId> {
137 self.slots
138 .req_ref(face_set_slot::COORDINATES, "Coordinates")
139 }
140
141 /// The vertex list as a typed view, resolved from the model.
142 ///
143 /// The schema narrows `Coordinates` to the 3D list, so a 2D list is a
144 /// wrong-type error rather than a mesh padded with `z = 0`. Its
145 /// [`CartesianPointList3D::point`] takes the 1-based indices of this
146 /// module's faces directly.
147 pub fn coordinate_list<'v>(
148 &self,
149 model: &'v Model,
150 ) -> GeometryResult<CartesianPointList3D<'v>> {
151 resolve::cartesian_point_list_3d(model, self.id(), self.coordinates()?)
152 }
153}
154
155/// Convert one 1-based STEP index to a 0-based slice index.
156///
157/// Errors instead of wrapping on 0, because `0usize - 1` wraps to
158/// `usize::MAX`, and an index that huge either panics far from the cause or
159/// silently reads whatever a growable buffer happens to hold.
160pub(super) fn to_zero_based(
161 slots: &Slots<'_>,
162 attribute: &'static str,
163 index: i64,
164) -> GeometryResult<usize> {
165 if index < 1 {
166 return Err(GeometryError::Degenerate {
167 entity: slots.id(),
168 type_name: slots.type_name().to_string(),
169 detail: format!(
170 "{attribute} holds {index}, but IFC indices are 1-based and must be at least 1"
171 ),
172 });
173 }
174 Ok((index - 1) as usize)
175}
176
177/// Read a flat list of integers from a slot, unwrapping typed values.
178///
179/// Necessary because `IfcPositiveInteger` may arrive either bare or wrapped by
180/// an exporter that spells out the defined type.
181pub(super) fn int_list(value: &Value) -> Option<Vec<i64>> {
182 let items = value.as_list()?;
183 items
184 .iter()
185 .map(|v| match v.unwrap_typed() {
186 Value::Integer(i) => Some(*i),
187 Value::Real(r) => Some(*r as i64),
188 _ => None,
189 })
190 .collect()
191}
192
193/// Read a list of integer lists from a slot, e.g. `CoordIndex`.
194pub(super) fn int_grid(value: &Value) -> Option<Vec<Vec<i64>>> {
195 let rows = value.as_list()?;
196 rows.iter()
197 .map(|row| int_list(row.unwrap_typed()))
198 .collect()
199}
200
201#[cfg(test)]
202mod tests {
203 use super::*;
204 use crate::solid::testkit::{entity, ints, r};
205
206 #[test]
207 fn coordinates_is_slot_zero_for_both_concrete_face_sets() {
208 for name in ["IFCTRIANGULATEDFACESET", "IFCPOLYGONALFACESET"] {
209 let e = entity(name, vec![r(50)]);
210 assert_eq!(
211 TessellatedFaceSet::new(EntityId(1), &e)
212 .coordinates()
213 .unwrap(),
214 EntityId(50),
215 "{name}"
216 );
217 }
218 }
219
220 #[test]
221 fn the_coordinate_list_resolves_and_serves_one_based_indices() {
222 use crate::solid::testkit::{list, model, n};
223 let row = |x: f64| list(vec![n(x), n(0.0), n(0.0)]);
224 let coords = entity(
225 "IFCCARTESIANPOINTLIST3D",
226 vec![list(vec![row(1.0), row(2.0)])],
227 );
228 let m = model(vec![(50, coords)]);
229 let e = entity("IFCTRIANGULATEDFACESET", vec![r(50)]);
230 let list = TessellatedFaceSet::new(EntityId(1), &e)
231 .coordinate_list(&m)
232 .unwrap();
233 assert_eq!(list.point(2).unwrap(), Some([2.0, 0.0, 0.0]));
234 }
235
236 /// The schema narrows `Coordinates` to the 3D list; a 2D one must not be
237 /// padded into a flat mesh.
238 #[test]
239 fn a_two_dimensional_or_dangling_coordinate_list_is_a_typed_error() {
240 use crate::solid::testkit::{list, model};
241 let m = model(vec![(
242 50,
243 entity("IFCCARTESIANPOINTLIST2D", vec![list(vec![])]),
244 )]);
245 let e = entity("IFCPOLYGONALFACESET", vec![r(50)]);
246 let view = TessellatedFaceSet::new(EntityId(1), &e);
247 assert!(matches!(
248 view.coordinate_list(&m).unwrap_err(),
249 GeometryError::WrongEntityType {
250 entity: EntityId(50),
251 expected: "IfcCartesianPointList3D",
252 ..
253 }
254 ));
255 let err = view.coordinate_list(&Model::new()).unwrap_err();
256 assert_eq!(err.entity(), Some(EntityId(1)));
257 }
258
259 /// An indexed face is a tessellated item but carries no coordinates, so
260 /// "tessellated" alone must not imply a face set.
261 #[test]
262 fn an_indexed_polygonal_face_is_a_tessellated_item_but_not_a_face_set() {
263 let face = entity("IFCINDEXEDPOLYGONALFACE", vec![ints(&[1, 2, 3])]);
264 assert!(!TessellatedItem::new(EntityId(1), &face).is_face_set());
265
266 let set = entity("IFCPOLYGONALFACESET", vec![r(1)]);
267 assert!(TessellatedItem::new(EntityId(1), &set).is_face_set());
268 }
269
270 /// A 0 index cannot occur in valid IFC, and `0 - 1` on a usize wraps to
271 /// usize::MAX, so it must be rejected rather than converted.
272 #[test]
273 fn a_zero_index_is_rejected_instead_of_wrapping_to_usize_max() {
274 let e = entity("IFCTRIANGULATEDFACESET", vec![]);
275 let slots = Slots::new(EntityId(3), &e);
276
277 assert_eq!(to_zero_based(&slots, "CoordIndex", 1).unwrap(), 0);
278 assert_eq!(to_zero_based(&slots, "CoordIndex", 7).unwrap(), 6);
279
280 for bad in [0, -1] {
281 let err = to_zero_based(&slots, "CoordIndex", bad).unwrap_err();
282 assert_eq!(err.entity(), Some(EntityId(3)));
283 assert!(err.to_string().contains("1-based"));
284 }
285 }
286}