ifc_geometry/solid/tessellated/
triangulated.rs1use super::{face_set_slot, int_grid, int_list, to_zero_based, TessellatedFaceSet};
7use crate::error::GeometryResult;
8use crate::slots::Slots;
9use ifc_model::{Entity, EntityId};
10
11pub(crate) mod slot {
18 pub const NORMALS: usize = 1;
20 pub const CLOSED: usize = 2;
22 pub const COORD_INDEX: usize = 3;
24 pub const PN_INDEX: usize = 4;
26}
27
28#[derive(Debug, Clone, Copy)]
44pub struct TriangulatedFaceSet<'m> {
45 slots: Slots<'m>,
46}
47
48impl<'m> TriangulatedFaceSet<'m> {
49 pub fn new(id: EntityId, entity: &'m Entity) -> Self {
51 Self {
52 slots: Slots::new(id, entity),
53 }
54 }
55
56 pub fn id(&self) -> EntityId {
58 self.slots.id()
59 }
60
61 pub fn base(&self) -> TessellatedFaceSet<'m> {
63 TessellatedFaceSet::from_slots(self.slots)
64 }
65
66 pub fn coordinates(&self) -> GeometryResult<EntityId> {
68 self.slots
69 .req_ref(face_set_slot::COORDINATES, "Coordinates")
70 }
71
72 pub fn closed(&self) -> Option<bool> {
78 self.slots.opt_bool(slot::CLOSED)
79 }
80
81 pub fn normals(&self) -> Option<Vec<[f64; 3]>> {
83 let value = self.slots.opt(slot::NORMALS)?;
84 let rows = value.as_list()?;
85 rows.iter()
86 .map(|row| {
87 let v = row.unwrap_typed().as_list()?;
88 if v.len() != 3 {
89 return None;
90 }
91 Some([
92 v[0].unwrap_typed().as_f64()?,
93 v[1].unwrap_typed().as_f64()?,
94 v[2].unwrap_typed().as_f64()?,
95 ])
96 })
97 .collect()
98 }
99
100 pub fn triangles_1based(&self) -> GeometryResult<Vec<[i64; 3]>> {
105 let value = self.slots.req(slot::COORD_INDEX, "CoordIndex")?;
106 let rows = int_grid(value).ok_or_else(|| {
107 self.slots
108 .degenerate("CoordIndex is not a list of integer lists")
109 })?;
110 rows.into_iter()
111 .map(|row| {
112 <[i64; 3]>::try_from(row.as_slice()).map_err(|_| {
113 self.slots.degenerate(format!(
114 "CoordIndex entry has {} indices, but a triangle needs exactly 3",
115 row.len()
116 ))
117 })
118 })
119 .collect()
120 }
121
122 pub fn triangles_0based(&self) -> GeometryResult<Vec<[usize; 3]>> {
128 let pn = self.pn_index_0based()?;
129 self.triangles_1based()?
130 .into_iter()
131 .map(|tri| {
132 let mut out = [0usize; 3];
133 for (slot_i, raw) in tri.iter().enumerate() {
134 let direct = to_zero_based(&self.slots, "CoordIndex", *raw)?;
135 out[slot_i] = match &pn {
136 Some(map) => *map.get(direct).ok_or_else(|| {
137 self.slots.degenerate(format!(
138 "CoordIndex {raw} is past the end of PnIndex ({} entries)",
139 map.len()
140 ))
141 })?,
142 None => direct,
143 };
144 }
145 Ok(out)
146 })
147 .collect()
148 }
149
150 pub fn pn_index_1based(&self) -> Option<Vec<i64>> {
152 int_list(self.slots.opt(slot::PN_INDEX)?)
153 }
154
155 pub fn pn_index_0based(&self) -> GeometryResult<Option<Vec<usize>>> {
161 let Some(raw) = self.pn_index_1based() else {
162 return Ok(None);
163 };
164 raw.into_iter()
165 .map(|i| to_zero_based(&self.slots, "PnIndex", i))
166 .collect::<GeometryResult<Vec<_>>>()
167 .map(Some)
168 }
169
170 pub fn triangle_count(&self) -> GeometryResult<usize> {
172 Ok(self.triangles_1based()?.len())
173 }
174}
175
176#[cfg(test)]
177mod tests {
178 use super::*;
179 use crate::solid::testkit::{entity, int_grid as grid, ints, list, n, r};
180 use ifc_model::Value;
181
182 fn face_set(coord_index: Value, pn: Value) -> Entity {
183 entity(
184 "IFCTRIANGULATEDFACESET",
185 vec![r(50), Value::Null, Value::Bool(true), coord_index, pn],
186 )
187 }
188
189 #[test]
191 fn coord_index_follows_normals_and_closed_in_the_slot_order() {
192 let e = face_set(grid(&[&[1, 2, 3]]), Value::Null);
193 let view = TriangulatedFaceSet::new(EntityId(1), &e);
194 assert_eq!(view.coordinates().unwrap(), EntityId(50));
195 assert_eq!(view.closed(), Some(true));
196 assert_eq!(view.triangles_1based().unwrap(), vec![[1, 2, 3]]);
197 }
198
199 #[test]
202 fn coord_index_is_one_based_and_converts_to_zero_based_slice_indices() {
203 let e = face_set(grid(&[&[1, 2, 3], &[1, 3, 4]]), Value::Null);
204 let view = TriangulatedFaceSet::new(EntityId(1), &e);
205
206 assert_eq!(
207 view.triangles_1based().unwrap(),
208 vec![[1, 2, 3], [1, 3, 4]],
209 "the raw form must preserve the file's own numbers"
210 );
211 assert_eq!(
212 view.triangles_0based().unwrap(),
213 vec![[0, 1, 2], [0, 2, 3]],
214 "index 1 in the file is element 0 of a Rust slice"
215 );
216 }
217
218 #[test]
221 fn the_highest_one_based_index_maps_to_the_last_slice_element() {
222 let vertex_count = 4usize;
223 let e = face_set(grid(&[&[2, 3, 4]]), Value::Null);
224 let view = TriangulatedFaceSet::new(EntityId(1), &e);
225 let tri = view.triangles_0based().unwrap()[0];
226 assert_eq!(tri, [1, 2, 3]);
227 assert!(
228 tri.iter().all(|i| *i < vertex_count),
229 "a valid file's converted indices must all be in range"
230 );
231 }
232
233 #[test]
235 fn a_zero_coord_index_is_rejected_rather_than_wrapping() {
236 let e = face_set(grid(&[&[0, 1, 2]]), Value::Null);
237 let view = TriangulatedFaceSet::new(EntityId(9), &e);
238 assert!(view.triangles_1based().is_ok(), "raw form stays readable");
239 let err = view.triangles_0based().unwrap_err();
240 assert_eq!(err.entity(), Some(EntityId(9)));
241 }
242
243 #[test]
246 fn pn_index_indirection_is_applied_not_skipped() {
247 let e = face_set(grid(&[&[1, 2, 3]]), ints(&[4, 3, 2, 1]));
249 let view = TriangulatedFaceSet::new(EntityId(1), &e);
250
251 assert_eq!(view.pn_index_1based().unwrap(), vec![4, 3, 2, 1]);
252 assert_eq!(view.pn_index_0based().unwrap().unwrap(), vec![3, 2, 1, 0]);
253 assert_eq!(
254 view.triangles_0based().unwrap(),
255 vec![[3, 2, 1]],
256 "CoordIndex 1,2,3 selects PnIndex entries 4,3,2 -> slice 3,2,1"
257 );
258 }
259
260 #[test]
261 fn without_pn_index_the_coord_index_addresses_coordinates_directly() {
262 let e = face_set(grid(&[&[1, 2, 3]]), Value::Null);
263 let view = TriangulatedFaceSet::new(EntityId(1), &e);
264 assert_eq!(view.pn_index_1based(), None);
265 assert_eq!(view.pn_index_0based().unwrap(), None);
266 assert_eq!(view.triangles_0based().unwrap(), vec![[0, 1, 2]]);
267 }
268
269 #[test]
272 fn an_absent_closed_flag_is_distinguishable_from_an_explicit_false() {
273 let stated = entity(
274 "IFCTRIANGULATEDFACESET",
275 vec![r(50), Value::Null, Value::Bool(false), grid(&[&[1, 2, 3]])],
276 );
277 assert_eq!(
278 TriangulatedFaceSet::new(EntityId(1), &stated).closed(),
279 Some(false)
280 );
281
282 let unstated = entity(
283 "IFCTRIANGULATEDFACESET",
284 vec![r(50), Value::Null, Value::Null, grid(&[&[1, 2, 3]])],
285 );
286 assert_eq!(
287 TriangulatedFaceSet::new(EntityId(1), &unstated).closed(),
288 None
289 );
290 }
291
292 #[test]
294 fn a_face_without_exactly_three_indices_is_degenerate() {
295 let e = face_set(grid(&[&[1, 2, 3, 4]]), Value::Null);
296 let err = TriangulatedFaceSet::new(EntityId(4), &e)
297 .triangles_1based()
298 .unwrap_err();
299 assert!(err.to_string().contains("exactly 3"));
300 }
301
302 #[test]
303 fn normals_are_returned_as_written_without_reinterpretation() {
304 let e = entity(
305 "IFCTRIANGULATEDFACESET",
306 vec![
307 r(50),
308 list(vec![list(vec![n(0.0), n(0.0), n(1.0)])]),
309 Value::Bool(true),
310 grid(&[&[1, 2, 3]]),
311 ],
312 );
313 let view = TriangulatedFaceSet::new(EntityId(1), &e);
314 assert_eq!(view.normals().unwrap(), vec![[0.0, 0.0, 1.0]]);
315 assert_eq!(view.triangle_count().unwrap(), 1);
316 }
317}