Skip to main content

ifc_georef/authoring/
mod.rs

1//! Transactional authoring of the georeferencing entities.
2//!
3//! # Derived attributes are written as `*`, not `$`
4//!
5//! `IfcGeometricRepresentationSubContext` redeclares four inherited
6//! attributes as DERIVE: they are taken from the parent context, not
7//! supplied here. STEP spells a derived attribute as an asterisk, and
8//! `$` would instead claim the value is absent -- a different
9//! statement, and one that loses the parent's precision and world
10//! coordinate system.
11
12use ifc_model::{Entity, EntityId, Transaction, Value};
13
14use crate::error::{GeorefError, GeorefResult};
15
16mod operation;
17
18pub use operation::{
19    create_angular_rigid_operation, create_geographic_crs, create_map_conversion,
20    create_map_conversion_scaled, create_rigid_operation, create_well_known_text,
21    GeographicCrsDraft, MapConversionDraft,
22};
23
24fn invalid(entity: &'static str, attribute: &'static str, value: impl Into<String>) -> GeorefError {
25    GeorefError::AuthoringInvalid {
26        entity,
27        attribute,
28        value: value.into(),
29    }
30}
31
32fn optional_text(value: Option<&str>) -> Value {
33    value.map_or(Value::Null, |t| Value::Text(t.into()))
34}
35
36/// Stage an `IfcDirection`.
37///
38/// # Errors
39///
40/// Refuses ratios that are not 2 or 3 long, which the schema types as
41/// `LIST [2:3]`, and any non-finite or all-zero ratio: a direction of
42/// zero length has no direction.
43pub fn create_direction(tx: &mut Transaction, ratios: &[f64]) -> GeorefResult<EntityId> {
44    if !(2..=3).contains(&ratios.len()) {
45        return Err(invalid(
46            "IFCDIRECTION",
47            "DirectionRatios",
48            format!("{} ratios", ratios.len()),
49        ));
50    }
51    if ratios.iter().any(|r| !r.is_finite()) {
52        return Err(invalid("IFCDIRECTION", "DirectionRatios", "not finite"));
53    }
54    if ratios.iter().all(|r| *r == 0.0) {
55        return Err(invalid("IFCDIRECTION", "DirectionRatios", "zero length"));
56    }
57    Ok(tx.create(Entity::new(
58        "IFCDIRECTION",
59        vec![Value::List(
60            ratios.iter().copied().map(Value::Real).collect(),
61        )],
62    )))
63}
64
65/// Authored fields for `IfcProjectedCRS`.
66#[derive(Debug, Clone, Copy, Default)]
67#[non_exhaustive]
68pub struct ProjectedCrsDraft<'a> {
69    /// `Name`, the CRS identifier such as `EPSG:25832`.
70    pub name: &'a str,
71    /// `Description`.
72    pub description: Option<&'a str>,
73    /// `GeodeticDatum`.
74    pub geodetic_datum: Option<&'a str>,
75    /// `VerticalDatum`.
76    pub vertical_datum: Option<&'a str>,
77    /// `MapProjection`.
78    pub map_projection: Option<&'a str>,
79    /// `MapZone`.
80    pub map_zone: Option<&'a str>,
81    /// `MapUnit`, an `IfcNamedUnit` reference.
82    pub map_unit: Option<EntityId>,
83}
84
85impl<'a> ProjectedCrsDraft<'a> {
86    /// Starts a draft for the CRS called `name`, such as `EPSG:25832`.
87    #[must_use]
88    pub const fn new(name: &'a str) -> Self {
89        Self {
90            name,
91            description: None,
92            geodetic_datum: None,
93            vertical_datum: None,
94            map_projection: None,
95            map_zone: None,
96            map_unit: None,
97        }
98    }
99
100    /// Sets `Description`.
101    #[must_use]
102    pub const fn description(mut self, value: &'a str) -> Self {
103        self.description = Some(value);
104        self
105    }
106
107    /// Sets `GeodeticDatum`.
108    #[must_use]
109    pub const fn geodetic_datum(mut self, value: &'a str) -> Self {
110        self.geodetic_datum = Some(value);
111        self
112    }
113
114    /// Sets `VerticalDatum`.
115    #[must_use]
116    pub const fn vertical_datum(mut self, value: &'a str) -> Self {
117        self.vertical_datum = Some(value);
118        self
119    }
120
121    /// Sets `MapProjection`.
122    #[must_use]
123    pub const fn map_projection(mut self, value: &'a str) -> Self {
124        self.map_projection = Some(value);
125        self
126    }
127
128    /// Sets `MapZone`.
129    #[must_use]
130    pub const fn map_zone(mut self, value: &'a str) -> Self {
131        self.map_zone = Some(value);
132        self
133    }
134
135    /// Sets `MapUnit`, an `IfcNamedUnit` reference.
136    #[must_use]
137    pub const fn map_unit(mut self, value: EntityId) -> Self {
138        self.map_unit = Some(value);
139        self
140    }
141}
142
143/// Stage an `IfcProjectedCRS`.
144///
145/// `Name` is optional in the schema but required here: the reader
146/// resolves a CRS by name, and an unnamed one cannot be matched to
147/// the projection it claims to use.
148///
149/// # Errors
150///
151/// Refuses a blank name.
152pub fn create_projected_crs(
153    tx: &mut Transaction,
154    draft: ProjectedCrsDraft<'_>,
155) -> GeorefResult<EntityId> {
156    if draft.name.trim().is_empty() {
157        return Err(invalid("IFCPROJECTEDCRS", "Name", draft.name));
158    }
159    Ok(tx.create(Entity::new(
160        "IFCPROJECTEDCRS",
161        vec![
162            Value::Text(draft.name.into()),
163            optional_text(draft.description),
164            optional_text(draft.geodetic_datum),
165            optional_text(draft.vertical_datum),
166            optional_text(draft.map_projection),
167            optional_text(draft.map_zone),
168            draft.map_unit.map_or(Value::Null, Value::Ref),
169        ],
170    )))
171}
172
173/// Stage an `IfcGeometricRepresentationContext`.
174///
175/// # Errors
176///
177/// Refuses a coordinate space dimension outside 1..=3 and a
178/// non-finite precision.
179pub fn create_representation_context(
180    tx: &mut Transaction,
181    context_type: Option<&str>,
182    dimension: i64,
183    precision: Option<f64>,
184    world_coordinate_system: EntityId,
185    true_north: Option<EntityId>,
186) -> GeorefResult<EntityId> {
187    if !(1..=3).contains(&dimension) {
188        return Err(invalid(
189            "IFCGEOMETRICREPRESENTATIONCONTEXT",
190            "CoordinateSpaceDimension",
191            dimension.to_string(),
192        ));
193    }
194    if precision.is_some_and(|p| !p.is_finite()) {
195        return Err(invalid(
196            "IFCGEOMETRICREPRESENTATIONCONTEXT",
197            "Precision",
198            "not finite",
199        ));
200    }
201    Ok(tx.create(Entity::new(
202        "IFCGEOMETRICREPRESENTATIONCONTEXT",
203        vec![
204            // ContextIdentifier at 0, ContextType at 1.
205            Value::Null,
206            optional_text(context_type),
207            Value::Integer(dimension),
208            precision.map_or(Value::Null, Value::Real),
209            Value::Ref(world_coordinate_system),
210            true_north.map_or(Value::Null, Value::Ref),
211        ],
212    )))
213}
214
215/// Stage an `IfcGeometricRepresentationSubContext`.
216///
217/// The four inherited geometry attributes are written as
218/// `Value::Derived`: the schema computes them from `ParentContext`,
219/// and writing `$` instead would claim the parent's precision and
220/// world coordinate system are simply absent.
221///
222/// # Errors
223///
224/// Enforces the schema's two WHERE rules. ParentNoSub: a subcontext
225/// cannot parent another subcontext, since the derived attributes
226/// resolve one level only. UserTargetProvided: a USERDEFINED target
227/// view without a name states a custom view and then fails to name
228/// it, leaving nothing for a consumer to match on.
229pub fn create_representation_subcontext(
230    tx: &mut Transaction,
231    parent: EntityId,
232    parent_is_subcontext: bool,
233    context_identifier: Option<&str>,
234    target_view: &str,
235    user_defined_target_view: Option<&str>,
236) -> GeorefResult<EntityId> {
237    if parent_is_subcontext {
238        return Err(invalid(
239            "IFCGEOMETRICREPRESENTATIONSUBCONTEXT",
240            "ParentContext",
241            "a subcontext cannot parent a subcontext",
242        ));
243    }
244    if target_view.trim().is_empty() {
245        return Err(invalid(
246            "IFCGEOMETRICREPRESENTATIONSUBCONTEXT",
247            "TargetView",
248            target_view,
249        ));
250    }
251    let named = user_defined_target_view.is_some_and(|v| !v.trim().is_empty());
252    if target_view == "USERDEFINED" && !named {
253        return Err(invalid(
254            "IFCGEOMETRICREPRESENTATIONSUBCONTEXT",
255            "UserDefinedTargetView",
256            "required when TargetView is USERDEFINED",
257        ));
258    }
259    Ok(tx.create(Entity::new(
260        "IFCGEOMETRICREPRESENTATIONSUBCONTEXT",
261        vec![
262            optional_text(context_identifier),
263            Value::Null,
264            // CoordinateSpaceDimension, Precision, WorldCoordinateSystem
265            // and TrueNorth: all DERIVE from ParentContext.
266            Value::Derived,
267            Value::Derived,
268            Value::Derived,
269            Value::Derived,
270            Value::Ref(parent),
271            Value::Null,
272            Value::Enum(target_view.into()),
273            optional_text(user_defined_target_view),
274        ],
275    )))
276}