Skip to main content

ifc_geometry/input/profile/
mod.rs

1//! `IfcProfileDef` families read into SI parameters, without a kernel.
2//!
3//! # One reader, two consumers
4//!
5//! [`describe_profile`] is the only place a profile family's slots are read.
6//! `lower::profile` builds its exact neutral profile from the returned
7//! [`ProfileDescription`], and [`crate::body_description`] hands the same
8//! value to rule checks. A slot index, a unit conversion or an IFC2X3 layout
9//! decision is therefore made once, and the parameters a checker reads are the
10//! parameters the kernel receives.
11//!
12//! It lives in `input` rather than `lower` because a rule check asking "is
13//! this beam an HEA300" must not link a geometry kernel to get the answer;
14//! `tests/kernel_free_build.rs` holds that line.
15//!
16//! # Units
17//!
18//! Lengths are converted to metres and plane angles to radians here, exactly
19//! once. That includes the translation of an `IfcDerivedProfileDef` operator,
20//! which is a length like any other coordinate.
21//!
22//! # Refusals
23//!
24//! A missing required attribute, a dangling reference, a non-physical
25//! dimension, a nesting cycle and an unknown family are all typed errors
26//! naming the entity. Nothing is defaulted to make a description succeed.
27
28mod open_cross;
29mod outline;
30mod section;
31mod types;
32
33#[cfg(feature = "lowering")]
34pub(crate) use open_cross::vertices as open_cross_vertices;
35
36#[cfg(feature = "compile")]
37pub(crate) use outline::{arc_boundary, boundary_curves, ring};
38pub use outline::{profile_outline, ProfileOutline};
39pub use types::{ProfileDescription, ProfileOperator, ProfileParameters, ProfilePosition};
40
41use ifc_model::{EntityId, Model};
42
43use crate::error::{GeometryError, GeometryResult};
44use crate::resource::operator::operator_transform;
45use crate::slots::{profile_slot as slot, section_slot, Slots};
46use crate::units::UnitScale;
47
48/// Why a bare `IfcProfileDef` is refused.
49///
50/// `IfcProfileDef` is instantiable in IFC4 (it is not declared ABSTRACT), but
51/// it is the bare supertype: it declares only `ProfileType` and
52/// `ProfileName`. A file authoring one has supplied a profile *label*, not a
53/// section. `lower::profile::PLANNED_PROFILES` states the same reason.
54pub(crate) const GENERIC_PROFILE: &str =
55    "generic profile declaration carries no concrete geometry to lower";
56
57/// Maximum profile nesting depth.
58///
59/// `IfcCompositeProfileDef` and `IfcDerivedProfileDef` both reference other
60/// profiles, so a broken file can nest them without end. A composite of
61/// derived sections is realistic; sixteen levels is not.
62const MAX_PROFILE_DEPTH: usize = 16;
63
64/// Chain kind reported for a profile nesting cycle or budget refusal.
65const KIND: &str = "profile";
66
67/// Read one `IfcProfileDef` into its family parameters, in metres and radians.
68///
69/// Every concrete IFC4 profile family is described, and the IFC4X3
70/// `IfcOpenCrossProfileDef`. A bare `IfcProfileDef`
71/// and any unknown type are refused as [`GeometryError::Unsupported`]; a
72/// profile that references itself through a composite or derived chain is
73/// refused as [`GeometryError::CyclicChain`].
74pub fn describe_profile(
75    model: &Model,
76    units: &UnitScale,
77    profile: EntityId,
78) -> GeometryResult<ProfileDescription> {
79    let mut chain = Vec::new();
80    describe(model, units, profile, profile, &mut chain)
81}
82
83/// Describe one profile, tracking the chain of nesting profiles above it.
84fn describe(
85    model: &Model,
86    units: &UnitScale,
87    referrer: EntityId,
88    id: EntityId,
89    chain: &mut Vec<EntityId>,
90) -> GeometryResult<ProfileDescription> {
91    if chain.contains(&id) {
92        return Err(GeometryError::CyclicChain {
93            entity: id,
94            kind: KIND,
95        });
96    }
97    if chain.len() >= MAX_PROFILE_DEPTH {
98        return Err(GeometryError::ChainTooDeep {
99            entity: id,
100            kind: KIND,
101            limit: MAX_PROFILE_DEPTH,
102        });
103    }
104    let entity = model.get(id).ok_or(GeometryError::MissingEntity {
105        referrer,
106        missing: id,
107    })?;
108    let slots = Slots::new(id, entity);
109    let type_name = entity.type_name.to_ascii_uppercase();
110
111    chain.push(id);
112    let parameters = parameters(model, units, &slots, &type_name, chain);
113    chain.pop();
114    let parameters = parameters?;
115
116    let position = if is_parameterized(&parameters) {
117        position(model, units, &slots)?
118    } else {
119        None
120    };
121    Ok(ProfileDescription {
122        entity: id,
123        type_name,
124        name: slots.opt_text(slot::PROFILE_NAME),
125        position,
126        parameters,
127    })
128}
129
130/// Dispatch on the concrete family.
131fn parameters(
132    model: &Model,
133    units: &UnitScale,
134    slots: &Slots<'_>,
135    type_name: &str,
136    chain: &mut Vec<EntityId>,
137) -> GeometryResult<ProfileParameters> {
138    let parameters = match type_name {
139        "IFCRECTANGLEPROFILEDEF" => section::rectangle(slots, units, false)?,
140        "IFCROUNDEDRECTANGLEPROFILEDEF" => section::rectangle(slots, units, true)?,
141        "IFCRECTANGLEHOLLOWPROFILEDEF" => section::rectangle_hollow(slots, units)?,
142        "IFCCIRCLEPROFILEDEF" => section::circle(slots, units, false)?,
143        "IFCCIRCLEHOLLOWPROFILEDEF" => section::circle(slots, units, true)?,
144        "IFCELLIPSEPROFILEDEF" => section::ellipse(slots, units)?,
145        "IFCISHAPEPROFILEDEF" => section::i_shape(slots, units)?,
146        "IFCASYMMETRICISHAPEPROFILEDEF" => section::asymmetric_i(slots, units, is_ifc2x3(model))?,
147        "IFCLSHAPEPROFILEDEF" => section::l_shape(slots, units)?,
148        "IFCTSHAPEPROFILEDEF" => section::t_shape(slots, units)?,
149        "IFCUSHAPEPROFILEDEF" => section::u_shape(slots, units)?,
150        "IFCCSHAPEPROFILEDEF" => section::c_shape(slots, units)?,
151        "IFCZSHAPEPROFILEDEF" => section::z_shape(slots, units)?,
152        "IFCTRAPEZIUMPROFILEDEF" => section::trapezium(slots, units)?,
153        "IFCARBITRARYCLOSEDPROFILEDEF" => ProfileParameters::ArbitraryClosed {
154            outer_curve: curve_ref(model, slots, slot::OUTER_CURVE, "OuterCurve")?,
155        },
156        "IFCARBITRARYPROFILEDEFWITHVOIDS" => {
157            let outer_curve = curve_ref(model, slots, slot::OUTER_CURVE, "OuterCurve")?;
158            let inner_curves = slots.req_ref_list(slot::INNER_CURVES, "InnerCurves")?;
159            for curve in &inner_curves {
160                slots.resolve(model, *curve)?;
161            }
162            ProfileParameters::ArbitraryWithVoids {
163                outer_curve,
164                inner_curves,
165            }
166        }
167        // An open profile is described, not refused: it is a valid profile,
168        // it simply bounds no area. `ProfileDescription::bounds_area` says so,
169        // and the area consumers (sweeps, lowering) refuse it there.
170        "IFCARBITRARYOPENPROFILEDEF" => ProfileParameters::ArbitraryOpen {
171            curve: curve_ref(model, slots, slot::OUTER_CURVE, "Curve")?,
172        },
173        // IFC4X3. Open like the arbitrary open profile: described, and
174        // refused by the area consumers through `bounds_area`.
175        "IFCOPENCROSSPROFILEDEF" => open_cross::read(model, units, slots)?,
176        "IFCCENTERLINEPROFILEDEF" => ProfileParameters::CenterLine {
177            curve: curve_ref(model, slots, section_slot::CL_CURVE, "Curve")?,
178            thickness: units.length(slots.req_f64(section_slot::CL_THICKNESS, "Thickness")?),
179        },
180        "IFCCOMPOSITEPROFILEDEF" => {
181            let refs = slots.req_ref_list(section_slot::COMPOSITE_PROFILES, "Profiles")?;
182            let mut profiles = Vec::with_capacity(refs.len());
183            for member in refs {
184                profiles.push(describe(model, units, slots.id(), member, chain)?);
185            }
186            ProfileParameters::Composite {
187                profiles,
188                label: slots.opt_text(section_slot::COMPOSITE_LABEL),
189            }
190        }
191        "IFCDERIVEDPROFILEDEF" => {
192            let parent = slots.req_ref(section_slot::DERIVED_PARENT, "ParentProfile")?;
193            let parent = Box::new(describe(model, units, slots.id(), parent, chain)?);
194            ProfileParameters::Derived {
195                parent,
196                operator: operator(model, units, slots)?,
197                label: slots.opt_text(section_slot::DERIVED_LABEL),
198            }
199        }
200        // IfcMirroredProfileDef derives its Operator in the schema, so no file
201        // carries one: the mirror about the local y axis is implied by the
202        // TYPE alone. Reading Operator here would find `*` and either fail or
203        // yield an unmirrored profile, so this subtype cannot share the
204        // parent's operator read.
205        "IFCMIRROREDPROFILEDEF" => {
206            let parent = slots.req_ref(section_slot::DERIVED_PARENT, "ParentProfile")?;
207            ProfileParameters::Mirrored {
208                parent: Box::new(describe(model, units, slots.id(), parent, chain)?),
209                label: slots.opt_text(section_slot::DERIVED_LABEL),
210            }
211        }
212        "IFCPROFILEDEF" => return Err(slots.unsupported(GENERIC_PROFILE)),
213        _ => return Err(slots.unsupported("profile family is not interpreted")),
214    };
215    Ok(parameters)
216}
217
218/// Is this an `IfcParameterizedProfileDef` family, which carries `Position`?
219fn is_parameterized(parameters: &ProfileParameters) -> bool {
220    !matches!(
221        parameters,
222        ProfileParameters::ArbitraryClosed { .. }
223            | ProfileParameters::ArbitraryWithVoids { .. }
224            | ProfileParameters::ArbitraryOpen { .. }
225            | ProfileParameters::OpenCross { .. }
226            | ProfileParameters::CenterLine { .. }
227            | ProfileParameters::Composite { .. }
228            | ProfileParameters::Derived { .. }
229            | ProfileParameters::Mirrored { .. }
230    )
231}
232
233/// Does the model declare IFC2X3, whose asymmetric-I layout differs?
234fn is_ifc2x3(model: &Model) -> bool {
235    model
236        .header()
237        .schema_token()
238        .is_some_and(|token| token.to_ascii_uppercase().starts_with("IFC2X3"))
239}
240
241/// A required curve reference that must resolve.
242fn curve_ref(
243    model: &Model,
244    slots: &Slots<'_>,
245    index: usize,
246    name: &'static str,
247) -> GeometryResult<EntityId> {
248    let curve = slots.req_ref(index, name)?;
249    slots.resolve(model, curve)?;
250    Ok(curve)
251}
252
253/// `IfcParameterizedProfileDef.Position` (slot 2), in metres.
254fn position(
255    model: &Model,
256    units: &UnitScale,
257    slots: &Slots<'_>,
258) -> GeometryResult<Option<ProfilePosition>> {
259    let Some(position_id) = slots.opt_ref(slot::POSITION) else {
260        return Ok(None);
261    };
262    let position = slots.resolve(model, position_id)?;
263    let position_slots = Slots::new(position_id, position);
264    // IfcPlacement.Location (slot 0), IfcAxis2Placement2D.RefDirection (slot 1).
265    let location_id = position_slots.req_ref(0, "Location")?;
266    let location = position_slots.resolve(model, location_id)?;
267    let coordinates = Slots::new(location_id, location).req_f64_list(0, "Coordinates")?;
268    if coordinates.len() < 2 {
269        return Err(position_slots.degenerate("2D placement location is not 2D"));
270    }
271    let origin = [units.length(coordinates[0]), units.length(coordinates[1])];
272    let x_axis = match position_slots.opt_ref(1) {
273        Some(direction_id) => {
274            let direction = position_slots.resolve(model, direction_id)?;
275            let ratios = Slots::new(direction_id, direction).req_f64_list(0, "DirectionRatios")?;
276            if ratios.len() < 2 {
277                return Err(position_slots.degenerate("2D reference direction is not 2D"));
278            }
279            let length = ratios[0].hypot(ratios[1]);
280            if length == 0.0 || !length.is_finite() {
281                return Err(position_slots.degenerate("2D reference direction has zero length"));
282            }
283            [ratios[0] / length, ratios[1] / length]
284        }
285        None => [1.0, 0.0],
286    };
287    Ok(Some(ProfilePosition { origin, x_axis }))
288}
289
290/// `IfcDerivedProfileDef.Operator` (slot 3) as a 2D map, translation in metres.
291///
292/// Reuses the shared operator reader, which handles the uniform and
293/// non-uniform forms. A profile lives in its own xy plane, so any z component
294/// means the file used a 3D operator where the schema requires a 2D one;
295/// refusing beats silently projecting geometry away.
296fn operator(
297    model: &Model,
298    units: &UnitScale,
299    slots: &Slots<'_>,
300) -> GeometryResult<ProfileOperator> {
301    let operator = slots.req_ref(section_slot::DERIVED_OPERATOR, "Operator")?;
302    let entity = slots.resolve(model, operator)?;
303    let full = operator_transform(model, operator, entity)?;
304    let [x, y, z] = full.basis;
305    let z_leak = z[0].abs() + z[1].abs() + x[2].abs() + y[2].abs();
306    if z_leak > 1e-9 || full.origin[2].abs() > 1e-9 {
307        return Err(Slots::new(operator, entity)
308            .unsupported("profile operator has out-of-plane components"));
309    }
310    Ok(ProfileOperator {
311        x_axis: [x[0], x[1]],
312        y_axis: [y[0], y[1]],
313        origin: [units.length(full.origin[0]), units.length(full.origin[1])],
314    })
315}