Skip to main content

ifc_geometry/authoring/
profile2.rs

1//! The profile forms beyond the parameterized catalogue sections.
2//!
3//! Three carry something a slot-filling writer would miss.
4//!
5//! # `IfcMirroredProfileDef` states nothing of its own
6//!
7//! It subtypes `IfcDerivedProfileDef` and redeclares `Operator` as
8//! **DERIVE**: the mirror transform is fixed by the schema, not chosen
9//! by the file. So the slot is written `*`, not `$` and not a
10//! hand-built operator -- the same distinction as `IfcOrientedEdge`.
11//!
12//! # `ProfileType` is not free on every subtype
13//!
14//! `IfcArbitraryProfileDefWithVoids` requires `AREA`: a profile with
15//! voids that claims to be a curve is contradictory. The writer does
16//! not take the type as an argument where the schema fixes it.
17//!
18//! # A rounded rectangle's radius is bounded by the rectangle
19//!
20//! `ValidRadius` caps `RoundingRadius` at half of each dimension. A
21//! larger radius describes no shape, and the check is arithmetic.
22
23use ifc_model::{Entity, EntityId, Transaction, Value};
24
25use super::profile::ProfileType;
26use crate::error::GeometryError;
27use crate::slots::profile_slot as slot;
28
29use super::std_profile::positive;
30use super::{invalid, reals, refs, require_finite};
31
32/// Write `ProfileType` and the optional `ProfileName`.
33fn header(attrs: &mut [Value], profile_type: ProfileType, name: Option<&str>) {
34    attrs[slot::PROFILE_TYPE] = Value::Enum(profile_type.token().into());
35    attrs[slot::PROFILE_NAME] = name.map_or(Value::Null, |n| Value::Text(n.into()));
36}
37
38/// Stage an `IfcArbitraryOpenProfileDef`.
39///
40/// An open profile is a `CURVE`, not an `AREA`: it has no enclosed
41/// region to extrude, and is swept as a surface or used as a
42/// centreline. The type is fixed here rather than taken from the
43/// caller, because `IfcArbitraryOpenProfileDef` has a WHERE rule
44/// forbidding `AREA` on everything except its centre-line subtype.
45pub fn arbitrary_open_profile(
46    tx: &mut Transaction,
47    name: Option<&str>,
48    curve: EntityId,
49) -> EntityId {
50    let mut attrs = vec![Value::Null; 3];
51    header(&mut attrs, ProfileType::Curve, name);
52    attrs[slot::OUTER_CURVE] = Value::Ref(curve);
53    tx.create(Entity::new("IFCARBITRARYOPENPROFILEDEF", attrs))
54}
55
56/// Stage an `IfcCenterLineProfileDef`.
57///
58/// The one open profile that *is* an area: the curve is a centreline
59/// and `thickness` gives it width, so the profile encloses a region
60/// after all. That is why the schema's `AREA` prohibition on open
61/// profiles exempts this subtype.
62///
63/// # Errors
64///
65/// Refuses a non-positive or non-finite thickness.
66pub fn center_line_profile(
67    tx: &mut Transaction,
68    name: Option<&str>,
69    curve: EntityId,
70    thickness: f64,
71) -> Result<EntityId, GeometryError> {
72    const T: &str = "IFCCENTERLINEPROFILEDEF";
73    positive(T, "Thickness", thickness)?;
74    let mut attrs = vec![Value::Null; 4];
75    header(&mut attrs, ProfileType::Area, name);
76    attrs[slot::OUTER_CURVE] = Value::Ref(curve);
77    attrs[3] = Value::Real(thickness);
78    Ok(tx.create(Entity::new(T, attrs)))
79}
80
81/// Stage an `IfcArbitraryProfileDefWithVoids`.
82///
83/// # Errors
84///
85/// Refuses an empty void set: `SET [1:?]`, and a profile with no voids
86/// is an `IfcArbitraryClosedProfileDef` instead. The schema also
87/// forbids an `IfcLine` as an inner curve -- a straight line encloses
88/// nothing -- but that needs the referenced entity's type, which this
89/// writer does not resolve; the conformance validator catches it.
90pub fn arbitrary_profile_with_voids(
91    tx: &mut Transaction,
92    name: Option<&str>,
93    outer_curve: EntityId,
94    inner_curves: &[EntityId],
95) -> Result<EntityId, GeometryError> {
96    const T: &str = "IFCARBITRARYPROFILEDEFWITHVOIDS";
97    if inner_curves.is_empty() {
98        return Err(invalid(
99            T,
100            "InnerCurves",
101            "expected at least one void; without one this is an IfcArbitraryClosedProfileDef",
102        ));
103    }
104    let mut attrs = vec![Value::Null; 4];
105    // WR1 fixes the profile type to AREA, so it is not an argument.
106    header(&mut attrs, ProfileType::Area, name);
107    attrs[slot::OUTER_CURVE] = Value::Ref(outer_curve);
108    attrs[slot::INNER_CURVES] = refs(inner_curves);
109    Ok(tx.create(Entity::new(T, attrs)))
110}
111
112/// Stage an `IfcCompositeProfileDef`.
113///
114/// # Errors
115///
116/// Refuses fewer than two component profiles: `SET [2:?]`, because a
117/// composite of one is just that one.
118pub fn composite_profile(
119    tx: &mut Transaction,
120    profile_type: ProfileType,
121    name: Option<&str>,
122    profiles: &[EntityId],
123    label: Option<&str>,
124) -> Result<EntityId, GeometryError> {
125    const T: &str = "IFCCOMPOSITEPROFILEDEF";
126    if profiles.len() < 2 {
127        return Err(invalid(
128            T,
129            "Profiles",
130            format!("expected at least 2 profiles, got {}", profiles.len()),
131        ));
132    }
133    let mut attrs = vec![Value::Null; 4];
134    header(&mut attrs, profile_type, name);
135    attrs[2] = refs(profiles);
136    attrs[3] = label.map_or(Value::Null, |l| Value::Text(l.into()));
137    Ok(tx.create(Entity::new(T, attrs)))
138}
139
140/// Stage an `IfcDerivedProfileDef`: a parent profile plus a transform.
141///
142/// `operator` is an `IfcCartesianTransformationOperator2D`. For a plain
143/// mirror use [`mirrored_profile`], which the schema derives instead.
144pub fn derived_profile(
145    tx: &mut Transaction,
146    profile_type: ProfileType,
147    name: Option<&str>,
148    parent: EntityId,
149    operator: EntityId,
150    label: Option<&str>,
151) -> EntityId {
152    let mut attrs = vec![Value::Null; 5];
153    header(&mut attrs, profile_type, name);
154    attrs[2] = Value::Ref(parent);
155    attrs[3] = Value::Ref(operator);
156    attrs[4] = label.map_or(Value::Null, |l| Value::Text(l.into()));
157    tx.create(Entity::new("IFCDERIVEDPROFILEDEF", attrs))
158}
159
160/// Stage an `IfcMirroredProfileDef`.
161///
162/// The mirror is about the y axis and is **fixed by the schema**, which
163/// derives `Operator` rather than reading it. So slot 3 is written `*`:
164/// writing an operator there would restate a derived value, and writing
165/// `$` would claim the transform is absent. Neither is conforming.
166///
167/// This is why there is no operator argument: there is nothing to
168/// choose.
169pub fn mirrored_profile(
170    tx: &mut Transaction,
171    profile_type: ProfileType,
172    name: Option<&str>,
173    parent: EntityId,
174    label: Option<&str>,
175) -> EntityId {
176    let mut attrs = vec![Value::Null; 5];
177    header(&mut attrs, profile_type, name);
178    attrs[2] = Value::Ref(parent);
179    attrs[3] = Value::Derived;
180    attrs[4] = label.map_or(Value::Null, |l| Value::Text(l.into()));
181    tx.create(Entity::new("IFCMIRROREDPROFILEDEF", attrs))
182}
183
184/// Stage an `IfcRoundedRectangleProfileDef`.
185///
186/// # Errors
187///
188/// Refuses a non-positive dimension or radius, and a radius exceeding
189/// half of either dimension: `ValidRadius`. At exactly half the smaller
190/// dimension the profile becomes a stadium, which is legal.
191pub fn rounded_rectangle_profile(
192    tx: &mut Transaction,
193    name: Option<&str>,
194    position: Option<EntityId>,
195    x_dim: f64,
196    y_dim: f64,
197    rounding_radius: f64,
198) -> Result<EntityId, GeometryError> {
199    const T: &str = "IFCROUNDEDRECTANGLEPROFILEDEF";
200    positive(T, "XDim", x_dim)?;
201    positive(T, "YDim", y_dim)?;
202    positive(T, "RoundingRadius", rounding_radius)?;
203    if rounding_radius > x_dim / 2.0 || rounding_radius > y_dim / 2.0 {
204        return Err(invalid(
205            T,
206            "RoundingRadius",
207            format!("{rounding_radius} exceeds half of the {x_dim} by {y_dim} rectangle"),
208        ));
209    }
210    let mut attrs = vec![Value::Null; 6];
211    header(&mut attrs, ProfileType::Area, name);
212    attrs[slot::POSITION] = position.map_or(Value::Null, Value::Ref);
213    attrs[slot::X_DIM] = Value::Real(x_dim);
214    attrs[slot::Y_DIM] = Value::Real(y_dim);
215    attrs[5] = Value::Real(rounding_radius);
216    Ok(tx.create(Entity::new(T, attrs)))
217}
218
219/// Stage a bare `IfcProfileDef`.
220///
221/// The supertype is concrete: it names a section and says whether it
222/// bounds an area, without describing its shape. A file may carry one
223/// where the geometry is supplied elsewhere, so this exists to
224/// round-trip such a model rather than to author new sections --
225/// prefer a subtype that states the shape.
226pub fn profile_def(
227    tx: &mut Transaction,
228    profile_type: ProfileType,
229    name: Option<&str>,
230) -> EntityId {
231    let attrs = vec![
232        Value::Enum(profile_type.token().into()),
233        name.map_or(Value::Null, |n| Value::Text(n.into())),
234    ];
235    tx.create(Entity::new("IFCPROFILEDEF", attrs))
236}
237
238/// Stage an `IfcOpenCrossProfileDef`.
239///
240/// A road or rail cross-section given as a chain of segments: each
241/// width is paired with the slope of that segment, so the two lists
242/// run in parallel and must be the same length
243/// (`CorrespondingSlopeWidths`). `Tags` names the *points* between
244/// segments, so it carries exactly one more entry than there are
245/// segments (`CorrespondingTags`).
246///
247/// `ProfileType` is fixed to CURVE by `CorrectProfileType`: an open
248/// chain bounds no area, so it is not a parameter.
249///
250/// # Errors
251///
252/// Refuses empty or mismatched width and slope lists, a `tags` list
253/// that is not `widths.len() + 1`, a negative width
254/// (`IfcNonNegativeLengthMeasure`), and non-finite values.
255pub fn open_cross_profile(
256    tx: &mut Transaction,
257    name: Option<&str>,
258    horizontal_widths: bool,
259    widths: &[f64],
260    slopes: &[f64],
261    tags: Option<&[&str]>,
262    offset_point: Option<EntityId>,
263) -> Result<EntityId, GeometryError> {
264    const ENTITY: &str = "IFCOPENCROSSPROFILEDEF";
265    if widths.is_empty() {
266        return Err(invalid(ENTITY, "Widths", "expected LIST [1:?]"));
267    }
268    if widths.len() != slopes.len() {
269        return Err(invalid(
270            ENTITY,
271            "Slopes",
272            format!(
273                "expected one slope per width: {} widths, {} slopes",
274                widths.len(),
275                slopes.len()
276            ),
277        ));
278    }
279    require_finite(ENTITY, "Widths", widths)?;
280    require_finite(ENTITY, "Slopes", slopes)?;
281    if let Some(bad) = widths.iter().position(|w| *w < 0.0) {
282        return Err(invalid(
283            ENTITY,
284            "Widths",
285            format!("width at index {bad} is negative"),
286        ));
287    }
288    if let Some(tags) = tags {
289        // Tags name the points between segments, so a chain of n
290        // segments has n+1 of them.
291        if tags.len() != widths.len() + 1 {
292            return Err(invalid(
293                ENTITY,
294                "Tags",
295                format!("expected {} tags, got {}", widths.len() + 1, tags.len()),
296            ));
297        }
298    }
299    let attrs = vec![
300        // CorrectProfileType fixes this to CURVE.
301        Value::Enum(ProfileType::Curve.token().into()),
302        name.map_or(Value::Null, |n| Value::Text(n.into())),
303        Value::Bool(horizontal_widths),
304        reals(widths),
305        reals(slopes),
306        tags.map_or(Value::Null, |t| {
307            Value::List(t.iter().map(|v| Value::Text((*v).into())).collect())
308        }),
309        offset_point.map_or(Value::Null, Value::Ref),
310    ];
311    Ok(tx.create(Entity::new(ENTITY, attrs)))
312}