Skip to main content

ifc_geometry/lower/
profile.rs

1//! Exact lowering of swept-area profile definitions.
2//!
3//! IFC units and profile-local placements are resolved here, but curves remain
4//! exact. Tessellation is a geometry-kernel decision and never occurs in the
5//! format adapter.
6//!
7//! # Who reads the slots
8//!
9//! Not this module. The kernel-free [`describe_profile`] reads every family's
10//! attributes into SI parameters, and [`lower_profile`] maps that description
11//! onto the neutral profile model. [`crate::body_description`] reports the same
12//! description, so a rule check and the kernel see identical numbers. Only the
13//! boundary curves of arbitrary and centre-line profiles are read here,
14//! because turning a curve into a contour is lowering.
15
16use axiolid_core::{Interval, Transform2, Vec2};
17use axiolid_curve::{Curve2, Line2};
18use axiolid_model::{GeometryNode, NodeId};
19use axiolid_profile::{CenterLineProfile, Contour, ContourProfile, Profile, ProfileSegment};
20use ifc_model::{EntityId, Model};
21
22use crate::error::{GeometryError, GeometryResult};
23use crate::input::profile::{
24    describe_profile, ProfileDescription, ProfileOperator, ProfileParameters, ProfilePosition,
25};
26use crate::lower::session::LoweringSession;
27use crate::slots::Slots;
28use crate::units::UnitScale;
29
30mod composite;
31mod indexed;
32mod open;
33mod role;
34mod sections;
35pub use open::lower_open_profile_node;
36pub(crate) use role::BoundaryRole;
37
38/// Concrete `IfcProfileDef` families represented exactly by the neutral profile model.
39pub const IMPLEMENTED_PROFILES: &[&str] = &[
40    "IFCARBITRARYCLOSEDPROFILEDEF",
41    "IFCARBITRARYOPENPROFILEDEF",
42    "IFCARBITRARYPROFILEDEFWITHVOIDS",
43    "IFCASYMMETRICISHAPEPROFILEDEF",
44    "IFCCENTERLINEPROFILEDEF",
45    "IFCCIRCLEHOLLOWPROFILEDEF",
46    "IFCCIRCLEPROFILEDEF",
47    "IFCCOMPOSITEPROFILEDEF",
48    "IFCCSHAPEPROFILEDEF",
49    "IFCDERIVEDPROFILEDEF",
50    "IFCELLIPSEPROFILEDEF",
51    "IFCISHAPEPROFILEDEF",
52    "IFCLSHAPEPROFILEDEF",
53    "IFCMIRROREDPROFILEDEF",
54    // IFC4X3; an open profile, lowered by `lower_open_profile_node`.
55    "IFCOPENCROSSPROFILEDEF",
56    "IFCRECTANGLEHOLLOWPROFILEDEF",
57    "IFCRECTANGLEPROFILEDEF",
58    "IFCROUNDEDRECTANGLEPROFILEDEF",
59    "IFCTSHAPEPROFILEDEF",
60    "IFCTRAPEZIUMPROFILEDEF",
61    "IFCUSHAPEPROFILEDEF",
62    "IFCZSHAPEPROFILEDEF",
63];
64
65/// Profile families that are recognized but carry no lowerable geometry.
66///
67/// `IfcProfileDef` is instantiable in IFC4 (it is not declared ABSTRACT), but
68/// it is the bare supertype: it declares only `ProfileType`, `ProfileName` and
69/// the curve slots its subtypes add. A file authoring one has supplied a
70/// profile *label*, not a section, so this is a permanent typed refusal rather
71/// than work awaiting a neutral contract. Every concrete subtype is read.
72///
73/// The refusal itself is raised by [`describe_profile`]; a unit test keeps its
74/// reason identical to the one stated here.
75pub const PLANNED_PROFILES: &[(&str, &str)] = &[(
76    "IFCPROFILEDEF",
77    "generic profile declaration carries no concrete geometry to lower",
78)];
79
80pub(crate) use crate::slots::profile_slot as slot;
81
82/// Concrete profile families this lowerer does not yet build, with reasons.
83///
84/// Paired with `tests/schema_coverage.rs`, which fails if a concrete profile
85/// is neither read by `input/profile/mod.rs` nor listed here. That is what
86/// makes the gap visible: the committed corpus contains no steel sections, so
87/// a corpus-shaped census reported full coverage while 13 families were absent.
88///
89/// A reason starting with `kernel:` needs a change in `axiolid-profile`; the
90/// rest are IFC-side wiring. Every IFC4 ADD2 TC1 and IFC4X3 ADD2 profile
91/// family is read, so the table is empty.
92pub const UNLOWERED: &[(&str, &str)] = &[];
93
94/// Family label used for profile memoization.
95const PROFILE: &str = "profile";
96const OPEN_PROFILE: &str = "open-profile";
97
98/// Append one `IfcProfileDef` to a shared session and return its node.
99///
100/// Profiles are the most-shared geometry in a real model: one section
101/// definition backs every beam of a type. Memoizing here is what keeps a
102/// shared profile a single node instead of one copy per referencing solid.
103/// The frame is the identity because a profile is defined in its own 2D space;
104/// placement is applied by the referencing solid, not baked into the section.
105pub fn lower_profile_node(
106    session: &mut LoweringSession<'_>,
107    id: EntityId,
108) -> GeometryResult<NodeId> {
109    let frame = crate::transform::Transform::identity();
110    if let Some(node) = session.memoized(id, PROFILE, frame) {
111        return Ok(node);
112    }
113    let profile = lower_profile(session.model(), id, session.units())?;
114    let node = session.node_for(id, GeometryNode::Profile(profile))?;
115    session.memoize(id, PROFILE, frame, node);
116    Ok(node)
117}
118
119/// Lower one `IfcProfileDef` to an exact, format-neutral profile.
120///
121/// The family's slots are read once, by the kernel-free [`describe_profile`];
122/// this function only maps the SI description onto the neutral model.
123pub fn lower_profile(model: &Model, id: EntityId, units: &UnitScale) -> GeometryResult<Profile> {
124    let description = describe_profile(model, units, id)?;
125    build(model, units, &description)
126}
127
128/// Map one description, and its nested members, onto the neutral model.
129///
130/// Recursion is bounded: the description tree was built under the reader's
131/// nesting budget and cycle check.
132fn build(
133    model: &Model,
134    units: &UnitScale,
135    description: &ProfileDescription,
136) -> GeometryResult<Profile> {
137    let profile = match &description.parameters {
138        ProfileParameters::ArbitraryClosed { outer_curve } => Profile::Contour(ContourProfile {
139            outer: curve_to_contour(model, *outer_curve, units, BoundaryRole::Profile)?,
140            holes: Vec::new(),
141        }),
142        ProfileParameters::ArbitraryWithVoids {
143            outer_curve,
144            inner_curves,
145        } => {
146            let outer = curve_to_contour(model, *outer_curve, units, BoundaryRole::Profile)?;
147            let mut holes = Vec::with_capacity(inner_curves.len());
148            for curve in inner_curves {
149                holes.push(curve_to_contour(
150                    model,
151                    *curve,
152                    units,
153                    BoundaryRole::Profile,
154                )?);
155            }
156            Profile::Contour(ContourProfile { outer, holes })
157        }
158        // An open profile is a curve, not an area. The neutral profile model
159        // is built on closed contours, so there is nothing to map it onto:
160        // closing the curve would fabricate a face the file never described,
161        // and silently sweeping it would produce a solid from a shape that
162        // bounds no area. State that rather than emitting a generic gap.
163        ProfileParameters::ArbitraryOpen { .. } | ProfileParameters::OpenCross { .. } => {
164            return Err(GeometryError::Unsupported {
165                entity: description.entity,
166                type_name: description.type_name.clone(),
167                detail: "open profiles have no area; use lower_open_profile_node",
168            });
169        }
170        // `Thickness` is the FULL width across the path, which the kernel
171        // stores halved so both offset sides are symmetric by construction.
172        ProfileParameters::CenterLine { curve, thickness } => {
173            let path = open::open_polyline_path(model, *curve, units)?;
174            Profile::CenterLine(CenterLineProfile::from_width(path, *thickness))
175        }
176        // Order is preserved because it is the only identity a composite
177        // member has: nothing else distinguishes two same-shaped members.
178        ProfileParameters::Composite { profiles, .. } => {
179            let mut members = Vec::with_capacity(profiles.len());
180            for member in profiles {
181                members.push(build(model, units, member)?);
182            }
183            Profile::Composite(members)
184        }
185        ProfileParameters::Derived {
186            parent, operator, ..
187        } => Profile::Derived {
188            basis: Box::new(build(model, units, parent)?),
189            transform: operator_2d(operator),
190        },
191        // The mirror about the local y axis is implied by the TYPE: the
192        // schema derives the operator, so there is none to read.
193        ProfileParameters::Mirrored { parent, .. } => Profile::Derived {
194            basis: Box::new(build(model, units, parent)?),
195            transform: Transform2::from_scale(Vec2::new(-1.0, 1.0)),
196        },
197        parameterized => sections::parameterized(description, parameterized)?,
198    };
199    // `IfcParameterizedProfileDef.Position` applies to every parameterised
200    // family, steel sections included.
201    Ok(match &description.position {
202        Some(position) => Profile::Derived {
203            basis: Box::new(profile),
204            transform: position_2d(position),
205        },
206        None => profile,
207    })
208}
209
210/// `IfcParameterizedProfileDef.Position` as a neutral 2D transform.
211fn position_2d(position: &ProfilePosition) -> Transform2 {
212    Transform2::from_cols(
213        Vec2::from_array(position.x_axis),
214        Vec2::from_array(position.y_axis()),
215        Vec2::from_array(position.origin),
216    )
217}
218
219/// `IfcDerivedProfileDef.Operator` as a neutral 2D transform.
220fn operator_2d(operator: &ProfileOperator) -> Transform2 {
221    Transform2::from_cols(
222        Vec2::from_array(operator.x_axis),
223        Vec2::from_array(operator.y_axis),
224        Vec2::from_array(operator.origin),
225    )
226}
227
228/// Lower one closed profile boundary curve into an exact contour.
229///
230/// `IfcPolyline` is one ring of straight edges. `IfcCompositeCurve` chains
231/// polylines, trimmed circles and lines, and nested composites (#43); it is
232/// lowered in `composite`, which refuses gaps rather than bridging them.
233/// `IfcIndexedPolyCurve` lines and three-point arcs (#335) are lowered in
234/// `indexed`, which refuses an open curve rather than closing it.
235///
236/// `role` says who reads the contour: a profile, or a polygonal bounded
237/// half-space boundary (#393, #398), which takes the same composite and
238/// indexed readings under its own plane and joint rules (see
239/// [`BoundaryRole`]).
240pub(crate) fn curve_to_contour(
241    model: &Model,
242    id: EntityId,
243    units: &UnitScale,
244    role: BoundaryRole,
245) -> GeometryResult<Contour> {
246    let entity = model.get(id).ok_or(GeometryError::MissingEntity {
247        referrer: id,
248        missing: id,
249    })?;
250    let type_name = entity.type_name.to_ascii_uppercase();
251    match type_name.as_str() {
252        "IFCPOLYLINE" => {}
253        "IFCCOMPOSITECURVE" => return composite::composite_contour(model, id, units, role),
254        "IFCINDEXEDPOLYCURVE" => return indexed::indexed_contour(model, id, units, role),
255        _ => {
256            return Err(GeometryError::Unsupported {
257                entity: id,
258                type_name,
259                detail: "profile boundaries lower IfcPolyline, IfcCompositeCurve and \
260                         IfcIndexedPolyCurve only",
261            })
262        }
263    }
264
265    let slots = Slots::new(id, entity);
266    let mut points = polyline_points(model, id, units, role)?;
267    drop_closing_duplicate(&mut points);
268    if points.len() < 3 {
269        return Err(slots.degenerate("profile boundary has fewer than 3 distinct points"));
270    }
271
272    let segments = (0..points.len())
273        .map(|index| {
274            let origin = points[index];
275            let next = points[(index + 1) % points.len()];
276            ProfileSegment {
277                curve: Curve2::Line(Line2 {
278                    origin,
279                    direction: next - origin,
280                }),
281                domain: Interval::UNIT,
282                same_sense: true,
283            }
284        })
285        .collect();
286    Ok(Contour::new(segments))
287}
288
289/// An `IfcPolyline`'s points as 2D metres, in authored order.
290///
291/// Shared by the closed-ring and composite-segment readers so both apply the
292/// same unit conversion and the same 2D check, the one `role` states.
293fn polyline_points(
294    model: &Model,
295    id: EntityId,
296    units: &UnitScale,
297    role: BoundaryRole,
298) -> GeometryResult<Vec<Vec2>> {
299    let entity = model.get(id).ok_or(GeometryError::MissingEntity {
300        referrer: id,
301        missing: id,
302    })?;
303    let slots = Slots::new(id, entity);
304    let mut points = Vec::new();
305    for point_id in slots.req_ref_list(0, "Points")? {
306        let point = model.get(point_id).ok_or(GeometryError::MissingEntity {
307            referrer: id,
308            missing: point_id,
309        })?;
310        let coordinates = Slots::new(point_id, point).req_f64_list(0, "Coordinates")?;
311        let [x, y] = role.planar(point_id, &point.type_name, &coordinates)?;
312        points.push(Vec2::new(units.length(x), units.length(y)));
313    }
314    Ok(points)
315}
316
317fn drop_closing_duplicate(points: &mut Vec<Vec2>) {
318    if points.len() >= 2 && points[0].distance(*points.last().expect("length checked")) < 1e-12 {
319        points.pop();
320    }
321}
322
323#[cfg(test)]
324mod tests {
325    /// The refusal the reader raises is the reason this table documents.
326    #[test]
327    fn the_generic_profile_refusal_matches_the_declared_reason() {
328        assert_eq!(
329            super::PLANNED_PROFILES[0].1,
330            crate::input::profile::GENERIC_PROFILE
331        );
332    }
333}