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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
//! One recursive lowering session over one shared graph builder.
//!
//! # Why a session exists
//!
//! Recursive lowering appends to a single session-owned builder, and family
//! lowerers return [`NodeId`] instead of freezing isolated child graphs
//! (`tests/lower_session.rs` pins this). That is not a style preference: a [`NodeId`]
//! is owned by the graph that minted it, so handles from two independently
//! finished graphs are mutually foreign. Every composite IFC family needs two
//! children in one graph:
//!
//! - `IfcBooleanResult` references two operands,
//! - `IfcMappedItem` reuses one source under many transforms,
//! - a B-rep face set shares one surface across many faces,
//! - `IfcCsgSolid` nests operations arbitrarily deep.
//!
//! The session also carries the model and resolved unit scale that every
//! lowerer needs. Approximation policy is deliberately absent: lowering emits
//! exact neutral geometry, while execution providers own tessellation tolerance.
//!
//! # What it guarantees
//!
//! - **One graph.** All nodes land in one builder, so any two lowered results
//!   are composable.
//! - **Memoization.** A shared IFC entity lowered under the same frame yields
//!   the same node instead of a duplicate subtree.
//! - **Bounded recursion.** Cyclic and over-deep chains produce typed errors
//!   rather than a stack overflow.
//! - **Located failures.** Graph construction faults are translated into
//!   [`GeometryError`] values that name the offending IFC entity.

use std::collections::BTreeMap;

use axiolid_model::{GeometryGraphBuilder, GeometryNode, GraphError, NodeId};
use ifc_model::{EntityId, Model};

use crate::error::{GeometryError, GeometryResult};
use crate::lower::{LoweredGeometry, ProvenanceMap};
use crate::slots::Slots;
use crate::transform::Transform;
use crate::units::UnitScale;

/// Recursion budget for chained IFC references.
///
/// IFC places no normative limit on placement or mapped-item nesting, so a
/// budget is the only way to terminate on malformed input that is deep rather
/// than strictly cyclic.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SessionLimits {
    /// Maximum simultaneously active entities in one chain.
    pub max_depth: usize,
    /// Maximum elements one file-declared aggregate may materialize.
    pub max_aggregate_elements: usize,
}

impl SessionLimits {
    /// Depth budget used when a caller states no preference.
    ///
    /// Real exporter output nests placements a few levels deep; 64 is far
    /// above observed depth while still terminating quickly on bad input.
    pub const DEFAULT_MAX_DEPTH: usize = 64;

    /// Aggregate-element budget used when a caller states no preference.
    ///
    /// Sized against the largest thing a legitimate file plausibly declares:
    /// a dense triangulated face set of ~5.5M triangles expands to 16M
    /// indices, and the largest observed knot vectors are four orders of
    /// magnitude smaller. 16M `f64` is ~128 MiB, which bounds a single
    /// aggregate to something a workstation survives while still refusing the
    /// billion-element declarations that motivate this budget.
    ///
    /// This is a refusal threshold, never a truncation point: an aggregate
    /// over the limit produces [`crate::GeometryError::AggregateTooLarge`]
    /// naming the entity, and no geometry is emitted for it.
    pub const DEFAULT_MAX_AGGREGATE_ELEMENTS: usize = 16_777_216;
}

impl Default for SessionLimits {
    fn default() -> Self {
        Self {
            max_depth: Self::DEFAULT_MAX_DEPTH,
            max_aggregate_elements: Self::DEFAULT_MAX_AGGREGATE_ELEMENTS,
        }
    }
}

/// What lowering does with an `IfcPolyLoop` face bound that collapses (#46).
///
/// A poly loop "collapses" when fewer than three of its implied edges join
/// two different points, e.g. `(A, A, B, B)`: it encloses no area, so it
/// cannot bound a face. Authoring tools emit such sliver faces routinely.
///
/// The test is exactly the one the refusal applies, so
/// [`DropAndReport`](Self::DropAndReport) drops precisely the faces that
/// [`Refuse`](Self::Refuse) would have refused over, and nothing else.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum DegenerateFacePolicy {
    /// Refuse the whole representation item with
    /// [`GeometryError::Degenerate`] naming
    /// the loop. The default: a file that says a face exists is not silently
    /// contradicted.
    #[default]
    Refuse,
    /// Leave the face out and record it in
    /// [`ProvenanceMap::dropped_faces`](crate::lower::ProvenanceMap::dropped_faces).
    ///
    /// Only a face whose OUTER bound (or only bound) collapses is dropped:
    /// that face covers no area, so omitting it removes no surface. A
    /// collapsed inner bound of a face that still has a valid outer bound is
    /// still refused, because dropping the face there would remove real area.
    ///
    /// Dropping a face can leave a shell open; the backend's own closure
    /// check still decides whether the result is a solid.
    DropAndReport,
}

/// Identity of one lowering result, used to deduplicate shared entities.
///
/// The frame is part of the key. Two `IfcMappedItem`s reusing one source under
/// different transforms are different results, and collapsing them would place
/// geometry at one location only. Floats are keyed by bit pattern so the key is
/// totally ordered without imposing a tolerance policy: memoization must be an
/// exact-identity optimization, never a geometric approximation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct MemoKey {
    entity: u64,
    family: &'static str,
    basis: [[u64; 3]; 3],
    origin: [u64; 3],
}

impl MemoKey {
    fn new(entity: EntityId, family: &'static str, frame: Transform) -> Self {
        Self {
            entity: entity.0,
            family,
            basis: frame.basis.map(|axis| axis.map(f64::to_bits)),
            origin: frame.origin.map(f64::to_bits),
        }
    }
}

/// A single recursive lowering pass over one shared graph builder.
///
/// Family lowerers take `&mut LoweringSession` and return [`NodeId`]. Only the
/// public entry point calls [`LoweringSession::finish`].
#[derive(Debug)]
pub struct LoweringSession<'a> {
    model: &'a Model,
    units: &'a UnitScale,
    limits: SessionLimits,
    builder: GeometryGraphBuilder,
    nodes: usize,
    memo: BTreeMap<MemoKey, NodeId>,
    active: Vec<EntityId>,
    provenance: ProvenanceMap,
    /// `MappedTo` face set -> its `IfcIndexedTriangleTextureMap`s, built on
    /// first use. Maps point at face sets, not the other way round, so
    /// finding a face set's map means a scan; doing it once per session
    /// keeps lowering linear in the file.
    texture_maps: Option<BTreeMap<EntityId, Vec<EntityId>>>,
    /// What each appended node is, structurally, for net lowering (#44).
    ///
    /// A boolean operand must be a solid, and the graph validator rejects a
    /// `Collection` (or an `Instance` of one) there. Net lowering therefore
    /// has to split a multi-item body into its solid parts, which needs to
    /// see node kinds before the graph is frozen. Recording them at push time
    /// costs one small entry per node and avoids re-walking the builder.
    shapes: BTreeMap<NodeId, NodeShape>,
    /// What to do with a collapsed poly-loop face (#46).
    face_policy: DegenerateFacePolicy,
}

/// The structural kind of a node, as net lowering needs it.
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum NodeShape {
    /// Merges its members; not itself a boolean operand.
    Collection(Vec<NodeId>),
    /// Reuses `source` under `transform`.
    Instance {
        /// The reused node.
        source: NodeId,
        /// Local-to-parent transform.
        transform: axiolid_core::Transform3,
    },
    /// A family the graph validator admits as a boolean operand.
    Solid,
    /// Anything else: curves, surfaces, profiles, points.
    Other,
}

impl NodeShape {
    fn of(node: &GeometryNode) -> Self {
        match node {
            GeometryNode::Collection(members) => Self::Collection(members.clone()),
            GeometryNode::Instance(instance) => Self::Instance {
                source: instance.source,
                transform: instance.transform,
            },
            // Mirrors axiolid-model's `ExpectedReference::Solid`.
            GeometryNode::Primitive(_)
            | GeometryNode::HalfSpace(_)
            | GeometryNode::SolidOperation(_)
            | GeometryNode::BRep(_)
            | GeometryNode::PolygonMesh(_)
            | GeometryNode::TriMesh(_) => Self::Solid,
            _ => Self::Other,
        }
    }
}

impl<'a> LoweringSession<'a> {
    /// Open a session with the default recursion budget.
    pub fn new(model: &'a Model, units: &'a UnitScale) -> Self {
        Self::with_limits(model, units, SessionLimits::default())
    }

    /// Open a session with an explicit recursion budget.
    pub fn with_limits(model: &'a Model, units: &'a UnitScale, limits: SessionLimits) -> Self {
        Self {
            model,
            units,
            limits,
            builder: GeometryGraphBuilder::new(),
            nodes: 0,
            memo: BTreeMap::new(),
            active: Vec::new(),
            provenance: ProvenanceMap::default(),
            texture_maps: None,
            shapes: BTreeMap::new(),
            face_policy: DegenerateFacePolicy::default(),
        }
    }

    /// Set what lowering does with a collapsed poly-loop face (#46).
    ///
    /// Builder-style so the default constructors stay unchanged:
    /// `LoweringSession::new(model, units).with_face_policy(policy)`.
    #[must_use]
    pub fn with_face_policy(mut self, policy: DegenerateFacePolicy) -> Self {
        self.face_policy = policy;
        self
    }

    /// The degenerate-face policy in force.
    pub fn face_policy(&self) -> DegenerateFacePolicy {
        self.face_policy
    }

    /// Record a face left out under [`DegenerateFacePolicy::DropAndReport`].
    pub(crate) fn report_dropped_face(&mut self, face: EntityId) {
        self.provenance.record_dropped_face(face);
    }

    /// The `IfcIndexedTriangleTextureMap`s whose `MappedTo` is `face_set`, in
    /// file order. Empty for an untextured face set.
    pub(crate) fn triangle_texture_maps(&mut self, face_set: EntityId) -> &[EntityId] {
        let model = self.model;
        let index = self.texture_maps.get_or_insert_with(|| {
            let mut index: BTreeMap<EntityId, Vec<EntityId>> = BTreeMap::new();
            // `ids_of_type` yields file order, so each list stays in it.
            for &map in model.ids_of_type("IFCINDEXEDTRIANGLETEXTUREMAP") {
                // `MappedTo` is slot 1 in IFC4 and IFC4X3 alike.
                let target = model
                    .get(map)
                    .and_then(|entity| entity.attributes.get(1))
                    .and_then(ifc_model::Value::as_ref_id);
                if let Some(target) = target {
                    index.entry(target).or_default().push(map);
                }
            }
            index
        });
        index.get(&face_set).map_or(&[], Vec::as_slice)
    }

    /// The model being lowered.
    pub fn model(&self) -> &'a Model {
        self.model
    }

    /// The resolved unit scale for this model.
    pub fn units(&self) -> &'a UnitScale {
        self.units
    }

    /// Number of nodes appended so far.
    ///
    /// Exposed so tests can assert that a memoized hit appends nothing.
    pub fn node_count(&self) -> usize {
        self.nodes
    }

    /// Append one node, attributing any graph fault to the current entity.
    pub fn node(&mut self, node: GeometryNode) -> GeometryResult<NodeId> {
        let source = self.active.last().copied();
        let shape = NodeShape::of(&node);
        let id = self
            .builder
            .push(node)
            .map_err(|error| graph_error(source.unwrap_or(EntityId(0)), error))?;
        self.nodes += 1;
        self.shapes.insert(id, shape);
        if let Some(source) = source {
            self.provenance.record(id, source);
        }
        Ok(id)
    }

    /// Append one node, attributing any graph fault to `entity`.
    pub fn node_for(&mut self, entity: EntityId, node: GeometryNode) -> GeometryResult<NodeId> {
        let shape = NodeShape::of(&node);
        let id = self
            .builder
            .push(node)
            .map_err(|error| graph_error(entity, error))?;
        self.nodes += 1;
        self.shapes.insert(id, shape);
        self.provenance.record(id, entity);
        Ok(id)
    }

    /// The structural kind of an appended node; `None` for a foreign id.
    pub(crate) fn shape(&self, node: NodeId) -> Option<&NodeShape> {
        self.shapes.get(&node)
    }

    /// Source attribution accumulated so far.
    pub fn provenance(&self) -> &ProvenanceMap {
        &self.provenance
    }

    /// Resolve an entity or report the dangling reference against `referrer`.
    pub fn entity(
        &self,
        referrer: EntityId,
        id: EntityId,
    ) -> GeometryResult<&'a ifc_model::Entity> {
        self.model.get(id).ok_or(GeometryError::MissingEntity {
            referrer,
            missing: id,
        })
    }

    /// Look up a previously lowered result for `entity` under `frame`.
    pub fn memoized(
        &self,
        entity: EntityId,
        family: &'static str,
        frame: Transform,
    ) -> Option<NodeId> {
        self.memo.get(&MemoKey::new(entity, family, frame)).copied()
    }

    /// Record the lowered result for `entity` under `frame`.
    pub fn memoize(
        &mut self,
        entity: EntityId,
        family: &'static str,
        frame: Transform,
        node: NodeId,
    ) {
        self.memo.insert(MemoKey::new(entity, family, frame), node);
    }

    /// Mark `entity` as active in the current chain.
    ///
    /// Returns [`GeometryError::CyclicChain`] if the entity is already active
    /// and [`GeometryError::ChainTooDeep`] once the depth budget is exhausted.
    /// Every successful call must be paired with [`LoweringSession::exit`].
    pub fn enter(&mut self, entity: EntityId, kind: &'static str) -> GeometryResult<()> {
        if self.active.contains(&entity) {
            return Err(GeometryError::CyclicChain { entity, kind });
        }
        if self.active.len() >= self.limits.max_depth {
            return Err(GeometryError::ChainTooDeep {
                entity,
                kind,
                limit: self.limits.max_depth,
            });
        }
        self.active.push(entity);
        Ok(())
    }

    /// Release `entity` from the active chain.
    ///
    /// Sharing is not recursion: once a subtree is complete the entity must be
    /// reachable again from a sibling branch.
    pub fn exit(&mut self, entity: EntityId) {
        if self.active.last() == Some(&entity) {
            self.active.pop();
            return;
        }
        debug_assert!(false, "lowering scopes must exit in LIFO order");
        if let Some(index) = self.active.iter().rposition(|&active| active == entity) {
            self.active.remove(index);
        }
    }

    /// Borrowed attribute view for `entity`.
    pub fn slots(&self, entity: EntityId) -> GeometryResult<Slots<'a>> {
        let resolved = self.entity(entity, entity)?;
        Ok(Slots::new(entity, resolved))
    }

    /// Upper-cased IFC type name for `entity`.
    ///
    /// Dispatch compares against canonical upper-case names because STEP files
    /// are case-insensitive in practice and exporters disagree.
    pub fn type_name(&self, entity: EntityId) -> GeometryResult<String> {
        Ok(self.entity(entity, entity)?.type_name.to_ascii_uppercase())
    }

    /// Build a typed `Unsupported` error naming the offending entity.
    pub fn unsupported(
        &self,
        entity: EntityId,
        type_name: &str,
        detail: &'static str,
    ) -> GeometryError {
        GeometryError::Unsupported {
            entity,
            type_name: type_name.to_string(),
            detail,
        }
    }

    /// Build a typed `Degenerate` error naming the offending entity.
    ///
    /// Structurally impossible geometry is distinct from an unimplemented
    /// family: the file is understood and the shape does not exist.
    pub fn degenerate(
        &self,
        entity: EntityId,
        type_name: &str,
        detail: impl Into<String>,
    ) -> GeometryError {
        GeometryError::Degenerate {
            entity,
            type_name: type_name.to_string(),
            detail: detail.into(),
        }
    }

    /// Check a file-declared aggregate size against the element budget.
    ///
    /// Takes `u128` so an overflowing product (`triangles * 3`) can be
    /// computed in a wider type and reported honestly instead of wrapping to a
    /// small number that passes the check. Returns the size as `usize` only
    /// once it is known to fit.
    ///
    /// Call this *before* reserving, not after: the point is to refuse the
    /// declaration, not to survive the allocation.
    pub fn check_aggregate(
        &self,
        entity: EntityId,
        type_name: &str,
        what: &'static str,
        requested: u128,
    ) -> GeometryResult<usize> {
        let limit = self.limits.max_aggregate_elements;
        if requested > limit as u128 {
            return Err(GeometryError::AggregateTooLarge {
                entity,
                type_name: type_name.to_string(),
                what,
                requested,
                limit,
            });
        }
        Ok(requested as usize)
    }

    /// Lower a nested operand through the total dispatcher.
    ///
    /// Kept on the session so recursive families do not each re-import the
    /// dispatcher and risk diverging on cycle/limit handling.
    pub fn lower_operand(&mut self, entity: EntityId, frame: Transform) -> GeometryResult<NodeId> {
        crate::lower::dispatch::lower_representation_item(self, entity, frame)
    }

    /// Freeze the graph with `root` as its single output root.
    pub fn finish(self, root: NodeId) -> GeometryResult<LoweredGeometry> {
        let entity = self.current_entity();
        let graph = self
            .builder
            .finish(vec![root])
            .map_err(|error| graph_error(entity, error))?;
        Ok(LoweredGeometry {
            graph,
            root,
            provenance: self.provenance,
        })
    }

    /// Best-effort attribution target for graph faults raised outside a family.
    fn current_entity(&self) -> EntityId {
        self.active.last().copied().unwrap_or(EntityId(0))
    }
}

/// Translate a graph construction fault into a located IFC error.
///
/// A bare [`GraphError`] names a `NodeId`, which is meaningless when debugging
/// a 500k-entity file; the IFC entity is the addressable unit.
pub(crate) fn graph_error(entity: EntityId, error: GraphError) -> GeometryError {
    GeometryError::Degenerate {
        entity,
        type_name: "geometry graph".to_string(),
        detail: error.to_string(),
    }
}

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

    #[test]
    fn the_memo_key_separates_entity_family_and_frame() {
        let frame = Transform::identity();
        let mut moved = Transform::identity();
        moved.origin = [1.0, 0.0, 0.0];

        let base = MemoKey::new(EntityId(1), "solid", frame);
        assert_eq!(base, MemoKey::new(EntityId(1), "solid", frame));
        assert_ne!(base, MemoKey::new(EntityId(2), "solid", frame));
        assert_ne!(base, MemoKey::new(EntityId(1), "profile", frame));
        assert_ne!(base, MemoKey::new(EntityId(1), "solid", moved));
    }

    #[test]
    fn signed_zero_does_not_alias_positive_zero_in_the_key() {
        // -0.0 == 0.0 numerically but has a distinct bit pattern. Keying on
        // bits keeps memoization an exact-identity optimization.
        let mut negative = Transform::identity();
        negative.origin = [-0.0, 0.0, 0.0];
        assert_ne!(
            MemoKey::new(EntityId(1), "solid", Transform::identity()),
            MemoKey::new(EntityId(1), "solid", negative)
        );
    }

    #[test]
    fn the_default_aggregate_budget_is_documented() {
        assert_eq!(
            SessionLimits::default().max_aggregate_elements,
            SessionLimits::DEFAULT_MAX_AGGREGATE_ELEMENTS
        );
        assert_eq!(SessionLimits::DEFAULT_MAX_AGGREGATE_ELEMENTS, 16_777_216);
    }

    #[test]
    fn the_default_depth_budget_is_documented() {
        assert_eq!(
            SessionLimits::default().max_depth,
            SessionLimits::DEFAULT_MAX_DEPTH
        );
    }
}