ifc-lite-geometry 5.0.0

Geometry processing and mesh generation for IFC models
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

//! CSG primitive processors.
//!
//! Handles `IfcCsgSolid` (the solid-model wrapper around a CSG tree) and the
//! `IfcCsgPrimitive3D` subtypes that can sit at the leaves of that tree.
//! `IfcBlock` and `IfcSphere` are supported as standalone leaves; the rest
//! (`IfcRectangularPyramid`, `IfcRightCircularCone`, `IfcRightCircularCylinder`)
//! are not yet implemented.

use super::boolean::OperandPath;
use crate::extrusion::apply_transform;
use crate::{scale_segments, Error, Mesh, Result, TessellationQuality, Vector3};
use ifc_lite_core::{DecodedEntity, EntityDecoder, IfcSchema, IfcType};
use nalgebra::Point3;

use super::boolean::BooleanClippingProcessor;
use super::helpers::parse_axis2_placement_3d;
use crate::router::GeometryProcessor;

/// `IfcBlock` — axis-aligned box CSG primitive.
///
/// Attributes (inherits `IfcCsgPrimitive3D` → Position):
///   0: Position (`IfcAxis2Placement3D`)
///   1: XLength
///   2: YLength
///   3: ZLength
///
/// The block occupies `(0,0,0) .. (XLength, YLength, ZLength)` in the local
/// placement frame, then is transformed by Position into the enclosing CSG
/// tree's coordinate system.
pub struct BlockProcessor;

impl BlockProcessor {
    pub fn new() -> Self {
        Self
    }
}

impl Default for BlockProcessor {
    fn default() -> Self {
        Self::new()
    }
}

impl GeometryProcessor for BlockProcessor {
    fn process(
        &self,
        entity: &DecodedEntity,
        decoder: &mut EntityDecoder,
        _schema: &IfcSchema,
        _quality: TessellationQuality,
    ) -> Result<Mesh> {
        let x = entity
            .get_float(1)
            .ok_or_else(|| Error::geometry("IfcBlock missing XLength".to_string()))?;
        let y = entity
            .get_float(2)
            .ok_or_else(|| Error::geometry("IfcBlock missing YLength".to_string()))?;
        let z = entity
            .get_float(3)
            .ok_or_else(|| Error::geometry("IfcBlock missing ZLength".to_string()))?;

        if !(x.is_finite() && y.is_finite() && z.is_finite() && x > 0.0 && y > 0.0 && z > 0.0) {
            return Err(Error::geometry(format!(
                "IfcBlock requires finite positive lengths, got ({}, {}, {})",
                x, y, z
            )));
        }

        let mut mesh = build_axis_aligned_box(x, y, z);

        if let Some(pos_attr) = entity.get(0) {
            if !pos_attr.is_null() {
                if let Some(pos_entity) = decoder.resolve_ref(pos_attr)? {
                    if pos_entity.ifc_type == IfcType::IfcAxis2Placement3D {
                        let transform = parse_axis2_placement_3d(&pos_entity, decoder)?;
                        apply_transform(&mut mesh, &transform);
                    }
                }
            }
        }

        Ok(mesh)
    }

    fn supported_types(&self) -> Vec<IfcType> {
        vec![IfcType::IfcBlock]
    }
}

/// `IfcCsgSolid` — wraps a CSG tree (`TreeRootExpression`, an `IfcCsgSelect`).
///
/// Attribute 0 (`TreeRootExpression`) is either an `IfcBooleanResult` /
/// `IfcBooleanClippingResult` or an `IfcCsgPrimitive3D`. This processor
/// resolves the reference and dispatches it to the matching leaf processor,
/// so callers don't need to know that the geometry was wrapped.
pub struct CsgSolidProcessor {
    /// Per-build small-cut skip, forwarded to the nested
    /// [`BooleanClippingProcessor`] this wraps so a CSG tree shares one scoped
    /// value (see `BooleanClippingProcessor::skip_small_cuts`).
    skip_small_cuts: bool,
}

impl CsgSolidProcessor {
    pub fn new() -> Self {
        Self::with_skip_small_cuts(false)
    }

    /// Construct with the per-build small-cut skip forwarded to the boolean
    /// processor at the root of the wrapped CSG tree.
    pub fn with_skip_small_cuts(skip_small_cuts: bool) -> Self {
        Self { skip_small_cuts }
    }
}

impl Default for CsgSolidProcessor {
    fn default() -> Self {
        Self::new()
    }
}

impl CsgSolidProcessor {
    /// Like [`GeometryProcessor::process`], but carrying the caller's boolean
    /// recursion depth and path-scoped visited set across the hop.
    ///
    /// `IfcCsgSolid.TreeRootExpression` may be an `IfcBooleanResult` whose
    /// operands may be `IfcCsgSolid`, so the two are mutually recursive over
    /// file-supplied references. Entering through `process()` built a FRESH
    /// `BooleanClippingProcessor`, resetting both, so three entities recursed
    /// forever with depth never passing 1 — and a stack overflow ABORTS in
    /// Rust, so nothing could turn it into a load error (#2866).
    ///
    /// The CSG id is inserted too, path-scoped like the boolean side, so
    /// `visited.len()` is an honest frame count. An earlier revision omitted
    /// it because deleting either insert left every test green — which meant
    /// neither was PINNED, not that one was redundant
    /// (`the_path_bound_counts_csg_frames_too_not_only_booleans` now pins it).
    /// Omitting it also made the `IfcCsgSolid -> IfcCsgSolid` rejection below
    /// load-bearing for stack safety instead of a spec check.
    pub(crate) fn process_with_boolean_cycle_guard(
        &self,
        entity: &DecodedEntity,
        decoder: &mut EntityDecoder,
        schema: &IfcSchema,
        depth: u32,
        quality: TessellationQuality,
        visited: &mut OperandPath,
    ) -> Result<Mesh> {
        if !visited.insert(entity.id) {
            return Err(Error::geometry(format!(
                "Cyclic boolean/CSG operand reference at #{}",
                entity.id
            )));
        }
        let out = self.resolve_tree_root(entity, decoder, schema, depth, quality, visited);
        visited.remove(&entity.id);
        out
    }

    /// Shared body of `process` and `process_with_boolean_cycle_guard`.
    fn resolve_tree_root(
        &self,
        entity: &DecodedEntity,
        decoder: &mut EntityDecoder,
        schema: &IfcSchema,
        depth: u32,
        quality: TessellationQuality,
        visited: &mut OperandPath,
    ) -> Result<Mesh> {
        let root_attr = entity.get(0).ok_or_else(|| {
            Error::geometry("IfcCsgSolid missing TreeRootExpression".to_string())
        })?;
        let root = decoder.resolve_ref(root_attr)?.ok_or_else(|| {
            Error::geometry("IfcCsgSolid TreeRootExpression unresolved".to_string())
        })?;

        // Per IFC 4.3 (`TreeRootExpression : IfcCsgSelect`), the root must be
        // an `IfcBooleanResult` or an `IfcCsgPrimitive3D`, NEVER another
        // `IfcCsgSolid`. Reject that case explicitly so a malformed (or
        // adversarial) file with a self-reference can't blow the stack on
        // unbounded recursion. That guard is one hop wide; the visited set
        // threaded through the boolean side closes the two-hop
        // CSG -> Boolean -> CSG cycle it cannot see (#2866).
        match root.ifc_type {
            IfcType::IfcBooleanResult | IfcType::IfcBooleanClippingResult => {
                BooleanClippingProcessor::with_skip_small_cuts(self.skip_small_cuts)
                    .process_with_depth(&root, decoder, schema, depth, quality, visited)
            }
            IfcType::IfcBlock => BlockProcessor::new().process(&root, decoder, schema, quality),
            IfcType::IfcSphere => SphereProcessor::new().process(&root, decoder, schema, quality),
            IfcType::IfcCsgSolid => Err(Error::geometry(
                "IfcCsgSolid TreeRootExpression must be IfcBooleanResult or \
                 IfcCsgPrimitive3D, not another IfcCsgSolid (spec violation)"
                    .to_string(),
            )),
            other => Err(Error::geometry(format!(
                "Unsupported IfcCsgSolid TreeRootExpression: {}",
                other
            ))),
        }
    }
}

impl GeometryProcessor for CsgSolidProcessor {
    fn process(
        &self,
        entity: &DecodedEntity,
        decoder: &mut EntityDecoder,
        schema: &IfcSchema,
        quality: TessellationQuality,
    ) -> Result<Mesh> {
        // Top-level entry (the router registers this processor directly, so
        // this is the path a file whose Body item IS the IfcCsgSolid takes).
        let mut visited = OperandPath::default();
        self.resolve_tree_root(entity, decoder, schema, 0, quality, &mut visited)
    }

    fn supported_types(&self) -> Vec<IfcType> {
        vec![IfcType::IfcCsgSolid]
    }
}

/// `IfcSphere` — CSG primitive: a sphere of given radius centred at the
/// origin of its Position placement.
///
/// Attributes (inherits `IfcCsgPrimitive3D` → Position):
///   0: Position (`IfcAxis2Placement3D`)
///   1: Radius (`IfcPositiveLengthMeasure`)
pub struct SphereProcessor;

impl SphereProcessor {
    pub fn new() -> Self {
        Self
    }
}

impl Default for SphereProcessor {
    fn default() -> Self {
        Self::new()
    }
}

impl GeometryProcessor for SphereProcessor {
    fn process(
        &self,
        entity: &DecodedEntity,
        decoder: &mut EntityDecoder,
        _schema: &IfcSchema,
        quality: TessellationQuality,
    ) -> Result<Mesh> {
        let radius = entity
            .get_float(1)
            .ok_or_else(|| Error::geometry("IfcSphere missing Radius".to_string()))?;

        if !radius.is_finite() || radius <= 0.0 {
            return Err(Error::geometry(format!(
                "IfcSphere requires finite positive radius, got {radius}",
            )));
        }

        // 24 slices × 16 stacks at Medium; scaled by quality.
        let slices = scale_segments(24, 8, 96, quality);
        let stacks = scale_segments(16, 4, 64, quality);
        let mut mesh = build_uv_sphere(radius, slices, stacks);

        if let Some(pos_attr) = entity.get(0) {
            if !pos_attr.is_null() {
                if let Some(pos_entity) = decoder.resolve_ref(pos_attr)? {
                    if pos_entity.ifc_type == IfcType::IfcAxis2Placement3D {
                        let transform = parse_axis2_placement_3d(&pos_entity, decoder)?;
                        apply_transform(&mut mesh, &transform);
                    }
                }
            }
        }

        Ok(mesh)
    }

    fn supported_types(&self) -> Vec<IfcType> {
        vec![IfcType::IfcSphere]
    }
}

/// UV-sphere tessellation. `slices` segments around the equator, `stacks`
/// rings from pole to pole. Pole vertices are duplicated per slice so UV
/// seams don't share normals — sphere is closed and outward-facing.
fn build_uv_sphere(radius: f64, slices: usize, stacks: usize) -> Mesh {
    let slices = slices.max(3);
    let stacks = stacks.max(2);
    let vert_count = (stacks + 1) * (slices + 1);
    let tri_count = stacks * slices * 2;
    let mut mesh = Mesh::with_capacity(vert_count, tri_count * 3);

    for j in 0..=stacks {
        let v = j as f64 / stacks as f64;
        let phi = std::f64::consts::PI * v;
        let sin_phi = phi.sin();
        let cos_phi = phi.cos();
        for i in 0..=slices {
            let u = i as f64 / slices as f64;
            let theta = std::f64::consts::TAU * u;
            let nx = sin_phi * theta.cos();
            let ny = sin_phi * theta.sin();
            let nz = cos_phi;
            mesh.add_vertex(
                Point3::new(radius * nx, radius * ny, radius * nz),
                Vector3::new(nx, ny, nz),
            );
        }
    }

    let stride = slices + 1;
    for j in 0..stacks {
        for i in 0..slices {
            let a = (j * stride + i) as u32;
            let b = a + 1;
            let c = ((j + 1) * stride + i) as u32;
            let d = c + 1;
            // Skip degenerate pole triangles
            if j != 0 {
                mesh.add_triangle(a, c, b);
            }
            if j + 1 != stacks {
                mesh.add_triangle(b, c, d);
            }
        }
    }

    mesh
}

/// Build an axis-aligned box from `(0,0,0)` to `(x, y, z)` with one flat
/// quad per face. Six faces × 4 unique vertices × 2 triangles = 24 verts /
/// 12 tris. Vertices are duplicated per face so per-face normals stay
/// flat-shaded.
fn build_axis_aligned_box(x: f64, y: f64, z: f64) -> Mesh {
    let mut mesh = Mesh::with_capacity(24, 36);

    // Six faces. Each face lists its four corners in CCW order as seen
    // from outside the box, paired with its outward normal.
    let faces: [([Point3<f64>; 4], Vector3<f64>); 6] = [
        // -Z (bottom): viewed from below, CCW is (0,0,0) → (0,y,0) → (x,y,0) → (x,0,0)
        (
            [
                Point3::new(0.0, 0.0, 0.0),
                Point3::new(0.0, y, 0.0),
                Point3::new(x, y, 0.0),
                Point3::new(x, 0.0, 0.0),
            ],
            Vector3::new(0.0, 0.0, -1.0),
        ),
        // +Z (top)
        (
            [
                Point3::new(0.0, 0.0, z),
                Point3::new(x, 0.0, z),
                Point3::new(x, y, z),
                Point3::new(0.0, y, z),
            ],
            Vector3::new(0.0, 0.0, 1.0),
        ),
        // -Y (front)
        (
            [
                Point3::new(0.0, 0.0, 0.0),
                Point3::new(x, 0.0, 0.0),
                Point3::new(x, 0.0, z),
                Point3::new(0.0, 0.0, z),
            ],
            Vector3::new(0.0, -1.0, 0.0),
        ),
        // +Y (back)
        (
            [
                Point3::new(x, y, 0.0),
                Point3::new(0.0, y, 0.0),
                Point3::new(0.0, y, z),
                Point3::new(x, y, z),
            ],
            Vector3::new(0.0, 1.0, 0.0),
        ),
        // -X (left)
        (
            [
                Point3::new(0.0, y, 0.0),
                Point3::new(0.0, 0.0, 0.0),
                Point3::new(0.0, 0.0, z),
                Point3::new(0.0, y, z),
            ],
            Vector3::new(-1.0, 0.0, 0.0),
        ),
        // +X (right)
        (
            [
                Point3::new(x, 0.0, 0.0),
                Point3::new(x, y, 0.0),
                Point3::new(x, y, z),
                Point3::new(x, 0.0, z),
            ],
            Vector3::new(1.0, 0.0, 0.0),
        ),
    ];

    for (corners, normal) in faces {
        let base = (mesh.positions.len() / 3) as u32;
        for p in &corners {
            mesh.add_vertex(*p, normal);
        }
        mesh.add_triangle(base, base + 1, base + 2);
        mesh.add_triangle(base, base + 2, base + 3);
    }

    mesh
}

#[cfg(test)]
#[path = "csg_primitive_tests.rs"]
mod tests;