Skip to main content

ifc_geometry/lower/
csg.rs

1//! CSG solids and swept-disk solids.
2//!
3//! # `IfcCsgSolid` is a wrapper, not a shape
4//!
5//! Its single `TreeRootExpression` is either a boolean result or a primitive.
6//! The solid itself contributes no geometry, so it lowers to whatever its root
7//! lowers to. Emitting a distinct node for the wrapper would add a graph level
8//! that no consumer can act on.
9//!
10//! # Primitives are local, placement is separate
11//!
12//! `IfcCsgPrimitive3D` subtypes define their shape in their OWN coordinate
13//! system: an `IfcBlock` always sits with a corner at its local origin and
14//! extends along +x/+y/+z. The `Position` places it. `Primitive::Block` in the
15//! kernel is likewise local-only, so the placement must ride on an Instance
16//! node -- folding it into the extents would be wrong for any non-identity
17//! rotation and would silently discard the origin offset.
18//!
19//! The anchors differ, though. The neutral block is CENTRED on its origin
20//! (the `axiolid-reference` 0.3 tessellator; `axiolid-primitive` states no
21//! anchor), while `IfcBlock` has a corner there (IFC4 ADD2 TC1). The
22//! Instance therefore also carries a half-extent shift inside the block's
23//! own frame; without it every compiled block sits half its size away from
24//! where the file put it. The other primitives already agree: sphere
25//! centred, cylinder, cone and rectangular pyramid with the base centred on
26//! the origin and height along +z, in both definitions.
27//!
28//! # Swept disks sweep a DISK, not a profile
29//!
30//! `IfcSweptDiskSolid` has no `IfcProfileDef`: the radii are given directly.
31//! `InnerRadius` makes it a pipe. The directrix is a curve, which is why this
32//! family waited for curve lowering.
33
34use axiolid_model::{GeometryNode, Instance, NodeId, SolidOperation};
35use axiolid_primitive::Primitive;
36use ifc_model::EntityId;
37
38use crate::error::GeometryResult;
39use crate::lower::curve::lower_sweep_directrix;
40use crate::lower::profile::lower_profile_node;
41use crate::lower::session::LoweringSession;
42use crate::lower::surface::lower_surface_node;
43use crate::lower::swept::directrix_parameter_trims;
44use crate::resource::placement::axis_placement_transform;
45use crate::slots::Slots;
46use crate::solid::csg::{CsgPrimitive3D, CsgSolid};
47use crate::solid::swept::directrix::{
48    SurfaceCurveSweptAreaSolid, SweptDiskSolid, SweptDiskSolidPolygonal,
49};
50use crate::transform::Transform;
51
52const CSG: &str = "csg solid";
53const DISK: &str = "swept disk";
54
55/// Lower an `IfcCsgSolid` by lowering its tree root.
56pub fn lower_csg_solid_node(
57    session: &mut LoweringSession<'_>,
58    id: EntityId,
59    frame: Transform,
60) -> GeometryResult<NodeId> {
61    if let Some(node) = session.memoized(id, CSG, frame) {
62        return Ok(node);
63    }
64    session.enter(id, CSG)?;
65    let result = (|| {
66        let entity = session.entity(id, id)?;
67        let root = CsgSolid::new(id, entity).tree_root_expression()?;
68        // The wrapper contributes nothing; the root IS the solid.
69        session.lower_operand(root, frame)
70    })();
71    session.exit(id);
72    let node = result?;
73    session.memoize(id, CSG, frame, node);
74    Ok(node)
75}
76
77/// Lower an `IfcCsgPrimitive3D` subtype into a placed primitive.
78pub fn lower_csg_primitive_node(
79    session: &mut LoweringSession<'_>,
80    id: EntityId,
81    frame: Transform,
82) -> GeometryResult<NodeId> {
83    if let Some(node) = session.memoized(id, CSG, frame) {
84        return Ok(node);
85    }
86    session.enter(id, CSG)?;
87    let result = build_primitive(session, id, frame);
88    session.exit(id);
89    let node = result?;
90    session.memoize(id, CSG, frame, node);
91    Ok(node)
92}
93
94fn build_primitive(
95    session: &mut LoweringSession<'_>,
96    id: EntityId,
97    frame: Transform,
98) -> GeometryResult<NodeId> {
99    let type_name = session.type_name(id)?;
100    let entity = session.entity(id, id)?;
101    let slots = Slots::new(id, entity);
102    let view = CsgPrimitive3D::new(id, entity);
103
104    // Slot 0 is `Position` on every IfcCsgPrimitive3D subtype.
105    let _ = &view;
106    let position_ref = slots.req_ref(0, "Position")?;
107    let position = session.entity(id, position_ref)?;
108    let local = axis_placement_transform(session.model(), position_ref, position)?
109        .to_metres(session.units());
110
111    let length = |value: f64| session.units().length(value);
112    let primitive = match type_name.as_str() {
113        "IFCBLOCK" => Primitive::Block {
114            x: length(slots.req_f64(1, "XLength")?),
115            y: length(slots.req_f64(2, "YLength")?),
116            z: length(slots.req_f64(3, "ZLength")?),
117        },
118        "IFCSPHERE" => Primitive::Sphere {
119            radius: length(slots.req_f64(1, "Radius")?),
120        },
121        "IFCRIGHTCIRCULARCYLINDER" => Primitive::Cylinder {
122            height: length(slots.req_f64(1, "Height")?),
123            radius: length(slots.req_f64(2, "Radius")?),
124        },
125        "IFCRIGHTCIRCULARCONE" => Primitive::Cone {
126            height: length(slots.req_f64(1, "Height")?),
127            radius: length(slots.req_f64(2, "BottomRadius")?),
128        },
129        // Slots follow IfcBlock (XLength, YLength, then the third length),
130        // NOT IfcRightCircularCone, which puts Height first. Copying the cone
131        // arm here would swap height with x and still build a valid pyramid.
132        "IFCRECTANGULARPYRAMID" => Primitive::Pyramid {
133            x: length(slots.req_f64(1, "XLength")?),
134            y: length(slots.req_f64(2, "YLength")?),
135            height: length(slots.req_f64(3, "Height")?),
136        },
137        other => return Err(session.unsupported(id, other, "CSG primitive family")),
138    };
139
140    // The primitive is local; the placement rides on an Instance so a
141    // non-identity rotation is preserved rather than folded into extents.
142    let source = session.node(GeometryNode::Primitive(primitive))?;
143    let placed = frame.compose(&local).compose(&anchor(&primitive));
144    session.node_for(
145        id,
146        GeometryNode::Instance(Instance {
147            source,
148            transform: placed.to_geom(),
149        }),
150    )
151}
152
153/// Where the IFC primitive's origin lies in the neutral primitive's frame.
154///
155/// Only the block differs: `IfcBlock` has a corner at its origin, the
156/// neutral block is centred, so the block is shifted by half its extents
157/// along its own axes. See the module docs.
158fn anchor(primitive: &Primitive) -> Transform {
159    match *primitive {
160        Primitive::Block { x, y, z } => Transform::translation([x / 2.0, y / 2.0, z / 2.0]),
161        _ => Transform::identity(),
162    }
163}
164
165/// Lower an `IfcSweptDiskSolid` into a `SweptDisk` operation.
166///
167/// The directrix is lowered first so the operation can reference its node,
168/// matching the operand-before-operation ordering the append-only builder
169/// requires.
170pub fn lower_swept_disk_node(
171    session: &mut LoweringSession<'_>,
172    id: EntityId,
173    frame: Transform,
174) -> GeometryResult<NodeId> {
175    if let Some(node) = session.memoized(id, DISK, frame) {
176        return Ok(node);
177    }
178    session.enter(id, DISK)?;
179    let result = build_disk(session, id, frame);
180    session.exit(id);
181    let node = result?;
182    session.memoize(id, DISK, frame, node);
183    Ok(node)
184}
185
186fn build_disk(
187    session: &mut LoweringSession<'_>,
188    id: EntityId,
189    frame: Transform,
190) -> GeometryResult<NodeId> {
191    let entity = session.entity(id, id)?;
192    let view = SweptDiskSolid::new(id, entity);
193
194    // IfcSweptDiskSolidPolygonal adds FilletRadius, which rounds the corners
195    // where consecutive directrix segments meet. The neutral SweptDisk carries
196    // it directly, so the subtype lowers as an ordinary swept disk that
197    // happens to know its corner radius.
198    let fillet_radius = if session
199        .type_name(id)?
200        .eq_ignore_ascii_case("IFCSWEPTDISKSOLIDPOLYGONAL")
201    {
202        SweptDiskSolidPolygonal::new(id, entity)
203            .fillet_radius()
204            .map(|value| session.units().length(value))
205    } else {
206        None
207    };
208
209    // `checked_radii` enforces the schema's inner < outer rule. A pipe whose
210    // inner radius meets or exceeds the outer has no material at all, and the
211    // failure downstream is an empty mesh rather than an error.
212    let (radius_raw, inner_raw) = view.checked_radii()?;
213    let radius = session.units().length(radius_raw);
214    let inner_radius = inner_raw.map(|value| session.units().length(value));
215
216    // StartParam/EndParam are in the DIRECTRIX's parameterisation, which is
217    // not always a length: see lower_sweep_directrix.
218    let (directrix, parameter_range) = lower_sweep_directrix(
219        session,
220        id,
221        "IFCSWEPTDISKSOLID",
222        view.directrix()?,
223        frame,
224        view.start_param(),
225        view.end_param(),
226    )?;
227
228    session.node_for(
229        id,
230        GeometryNode::SolidOperation(SolidOperation::SweptDisk {
231            directrix,
232            radius,
233            inner_radius,
234            parameter_range,
235            fillet_radius,
236        }),
237    )
238}
239
240#[cfg(test)]
241mod tests;
242
243/// Lower an `IfcSurfaceCurveSweptAreaSolid` into a `SurfaceCurveSweep`.
244///
245/// The directrix of this family is a curve that *lies on* the reference
246/// surface. The surface is not decoration: it fixes the sweep's twist. At any
247/// point of the directrix the profile is oriented by the surface normal
248/// there, so two solids with identical profiles and identical directrices but
249/// different reference surfaces are different solids.
250///
251/// Dropping the surface and treating this as a plain directrix sweep produces
252/// a shape with the right footprint and the wrong cross-section rotation --
253/// a duct elbow whose flanges twist. That is why the reference surface is
254/// lowered and referenced rather than ignored.
255pub fn lower_surface_curve_swept_area_solid_node(
256    session: &mut LoweringSession<'_>,
257    id: EntityId,
258    frame: Transform,
259) -> GeometryResult<NodeId> {
260    if let Some(node) = session.memoized(id, CSG, frame) {
261        return Ok(node);
262    }
263    let entity = session.entity(id, id)?;
264    let view = SurfaceCurveSweptAreaSolid::new(id, entity);
265    let base = view.base();
266
267    // An optional Position places the swept solid.
268    let placed = match base.position() {
269        Some(position_id) => {
270            let position = session.entity(id, position_id)?;
271            let local = axis_placement_transform(session.model(), position_id, position)?
272                .to_metres(session.units());
273            frame.compose(&local)
274        }
275        None => frame,
276    };
277
278    let profile = lower_profile_node(session, base.swept_area()?)?;
279    // Same rule as the swept disk: see lower_sweep_directrix. An IFC4X3
280    // length trim is refused, not read as a parameter (#210).
281    const T: &str = "IFCSURFACECURVESWEPTAREASOLID";
282    let (start, end) =
283        directrix_parameter_trims(session, id, T, view.start_param()?, view.end_param()?)?;
284    let (directrix, parameter_range) =
285        lower_sweep_directrix(session, id, T, view.directrix()?, placed, start, end)?;
286    let reference_surface = lower_surface_node(session, view.reference_surface()?, placed)?;
287
288    let node = session.node_for(
289        id,
290        GeometryNode::SolidOperation(SolidOperation::SurfaceCurveSweep {
291            profile,
292            directrix,
293            reference_surface,
294            parameter_range,
295        }),
296    )?;
297    session.memoize(id, CSG, frame, node);
298    Ok(node)
299}