ifc_lite_export/plan/
skeleton.rs

1// SPDX-License-Identifier: MPL-2.0
2//! A new IFC4 file with nothing in it but its spatial root: the source a plan
3//! of [`super::Disposition::Add`]s is executed against when there is no
4//! existing file to add to.
5//!
6//! The file holds one `IfcProject` (SI units: metre, square metre, cubic
7//! metre, radian), one 3D `Model` context with a `Body` subcontext, one
8//! `IfcSite` and one `IfcBuilding` aggregated under it, and, when asked, the
9//! map conversion that places the project's engineering frame in a projected
10//! CRS. No owner history is written: IFC4 does not require one, and the
11//! executor synthesizes its own for the records a plan adds.
12//!
13//! Every GlobalId is the caller's, and nothing reads a clock, so the same
14//! [`Skeleton`] always produces the same bytes.
15
16use crate::step_ids::IdAllocator;
17use crate::step_text::quoted;
18
19use super::add_types::GlobalId;
20use super::identity::{Identity, Made};
21use super::types::{ExportingApplication, ValidationFinding};
22use super::placement::fmt;
23use super::props_synth::ref_list;
24use super::tessellation::Emit;
25
26/// The schema a skeleton is written in.
27pub const SKELETON_SCHEMA: &str = "IFC4";
28
29/// One spatial root: its GlobalId and optional name.
30#[derive(Debug, Clone)]
31#[non_exhaustive]
32pub struct SkeletonRoot {
33    pub global_id: GlobalId,
34    pub name: Option<String>,
35}
36
37/// The length unit of a projected CRS's map coordinates.
38#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
39#[non_exhaustive]
40pub enum MapUnit {
41    #[default]
42    Metre,
43    /// The international foot, 0.3048 m.
44    Foot,
45    /// The US survey foot, 1200/3937 m.
46    UsSurveyFoot,
47}
48
49/// An `IfcMapConversion` to an `IfcProjectedCRS`: how the project's
50/// engineering frame (metres) maps to map coordinates.
51///
52/// `x_axis_abscissa` and `x_axis_ordinate` are the direction of the
53/// engineering frame's X axis in map coordinates; together they carry the
54/// rotation between grid north and the project's Y axis. They need not be
55/// normalised, but cannot both be zero.
56#[derive(Debug, Clone)]
57#[non_exhaustive]
58pub struct MapConversion {
59    /// `IfcProjectedCRS.Name`, for example `EPSG:2056`.
60    pub crs_name: String,
61    /// The unit `eastings`, `northings` and `orthogonal_height` are in,
62    /// written as the CRS's `MapUnit`. Without one IFC reads map coordinates
63    /// in the project's length unit (metre), which is wrong for a feet-based
64    /// CRS such as a US State Plane zone.
65    pub map_unit: MapUnit,
66    pub eastings: f64,
67    pub northings: f64,
68    pub orthogonal_height: f64,
69    pub x_axis_abscissa: f64,
70    pub x_axis_ordinate: f64,
71    /// `None` writes `$`, which IFC4 reads as 1.
72    pub scale: Option<f64>,
73}
74
75/// What [`skeleton`] writes.
76#[derive(Debug, Clone)]
77#[non_exhaustive]
78pub struct Skeleton {
79    pub project: SkeletonRoot,
80    pub site: SkeletonRoot,
81    pub building: SkeletonRoot,
82    /// Direction of true north in the project's XY plane, written as the
83    /// model context's `TrueNorth`. `None` leaves it unset, which IFC reads
84    /// as +Y.
85    pub true_north: Option<[f64; 2]>,
86    pub map_conversion: Option<MapConversion>,
87    /// The application writing the file. Present, it owns the project, site,
88    /// building and their aggregations (`ADDED`) and the header names it, the
89    /// same way [`super::PlanContext::application`] does for a plan.
90    pub application: Option<ExportingApplication>,
91    /// The header's `FILE_NAME` name. `None` writes an empty one.
92    pub file_name: Option<String>,
93}
94
95/// An `IfcConversionBasedUnit` length unit of `metres` metres.
96fn length_unit(emit: &mut Emit, name: &str, metres: f64, metre: u32) -> Result<u32, String> {
97    let dimensions = emit.record(
98        "IFCDIMENSIONALEXPONENTS",
99        &[
100            ("LengthExponent", "1".into()),
101            ("MassExponent", "0".into()),
102            ("TimeExponent", "0".into()),
103            ("ElectricCurrentExponent", "0".into()),
104            ("ThermodynamicTemperatureExponent", "0".into()),
105            ("AmountOfSubstanceExponent", "0".into()),
106            ("LuminousIntensityExponent", "0".into()),
107        ],
108    )?;
109    let factor = emit.record(
110        "IFCMEASUREWITHUNIT",
111        &[("ValueComponent", format!("IFCLENGTHMEASURE({})", fmt(metres))), ("UnitComponent", format!("#{metre}"))],
112    )?;
113    emit.record(
114        "IFCCONVERSIONBASEDUNIT",
115        &[
116            ("Dimensions", format!("#{dimensions}")),
117            ("UnitType", ".LENGTHUNIT.".into()),
118            ("Name", format!("'{name}'")),
119            ("ConversionFactor", format!("#{factor}")),
120        ],
121    )
122}
123
124/// The skeleton's bytes. A header that doesn't follow buildingSMART's
125/// agreement is not reported here; [`skeleton_with_findings`] reports it.
126///
127/// # Errors
128/// A number is not finite, a direction is zero length, the three roots do
129/// not have distinct GlobalIds, `crs_name` is empty, or an
130/// [`ExportingApplication`] is given whose change time cannot be attributed.
131pub fn skeleton(s: &Skeleton) -> Result<Vec<u8>, String> {
132    build(s, true).map(|(bytes, _)| bytes)
133}
134
135/// [`skeleton`], reporting rather than refusing an application it cannot
136/// attribute the skeleton to: the skeleton is then written unattributed, and
137/// a finding says why. A header that doesn't follow buildingSMART's
138/// agreement is a finding too.
139///
140/// # Errors
141/// As [`skeleton`], but for the application.
142pub fn skeleton_with_findings(s: &Skeleton) -> Result<(Vec<u8>, Vec<ValidationFinding>), String> {
143    build(s, false)
144}
145
146/// The skeleton and its findings, for both entry points.
147fn build(s: &Skeleton, strict: bool) -> Result<(Vec<u8>, Vec<ValidationFinding>), String> {
148    check(s)?;
149    let mut findings = Vec::new();
150    let mut ids = IdAllocator::after(0);
151    let mut out = Vec::new();
152    let mut emit = Emit {
153        schema: SKELETON_SCHEMA,
154        ids: &mut ids,
155        out: &mut out,
156    };
157    // The exporting application owns what the skeleton creates.
158    let identity = identity_of(s, strict, &mut findings)?;
159    let history = owner_slot(identity.as_ref(), &mut emit)?;
160    let name = |root: &SkeletonRoot| root.name.as_deref().map_or("$".to_string(), quoted);
161    let gid = |root: &SkeletonRoot| format!("'{}'", root.global_id.encode());
162
163    let si = |emit: &mut Emit, unit: &str, name: &str| {
164        emit.record(
165            "IFCSIUNIT",
166            &[
167                // Derived in IfcSIUnit, so written `*`.
168                ("Dimensions", "*".into()),
169                ("UnitType", format!(".{unit}.")),
170                ("Name", format!(".{name}.")),
171            ],
172        )
173    };
174    let units = [
175        si(&mut emit, "LENGTHUNIT", "METRE")?,
176        si(&mut emit, "AREAUNIT", "SQUARE_METRE")?,
177        si(&mut emit, "VOLUMEUNIT", "CUBIC_METRE")?,
178        si(&mut emit, "PLANEANGLEUNIT", "RADIAN")?,
179    ];
180    let unit_assignment = emit.record("IFCUNITASSIGNMENT", &[("Units", ref_list(&units))])?;
181
182    let wcs = emit.identity_placement()?;
183    let mut context_fields = vec![
184        ("ContextType", "'Model'".to_string()),
185        ("CoordinateSpaceDimension", "3".into()),
186        ("Precision", "1.E-05".into()),
187        ("WorldCoordinateSystem", format!("#{wcs}")),
188    ];
189    if let Some([x, y]) = s.true_north {
190        let north = emit.record(
191            "IFCDIRECTION",
192            &[("DirectionRatios", format!("({},{})", fmt(x), fmt(y)))],
193        )?;
194        context_fields.push(("TrueNorth", format!("#{north}")));
195    }
196    let context = emit.record("IFCGEOMETRICREPRESENTATIONCONTEXT", &context_fields)?;
197    emit.record(
198        "IFCGEOMETRICREPRESENTATIONSUBCONTEXT",
199        &[
200            ("ContextIdentifier", "'Body'".into()),
201            ("ContextType", "'Model'".into()),
202            // Derived from the parent context in a subcontext.
203            ("CoordinateSpaceDimension", "*".into()),
204            ("Precision", "*".into()),
205            ("WorldCoordinateSystem", "*".into()),
206            ("TrueNorth", "*".into()),
207            ("ParentContext", format!("#{context}")),
208            ("TargetView", ".MODEL_VIEW.".into()),
209        ],
210    )?;
211    if let Some(m) = &s.map_conversion {
212        map_conversion(m, context, units[0], &mut emit)?;
213    }
214
215    let project = emit.record(
216        "IFCPROJECT",
217        &[
218            ("GlobalId", gid(&s.project)),
219            ("OwnerHistory", history.clone()),
220            ("Name", name(&s.project)),
221            ("RepresentationContexts", format!("(#{context})")),
222            ("UnitsInContext", format!("#{unit_assignment}")),
223        ],
224    )?;
225
226    let site_a2p = emit.identity_placement()?;
227    let site_placement = emit.record(
228        "IFCLOCALPLACEMENT",
229        &[("RelativePlacement", format!("#{site_a2p}"))],
230    )?;
231    let site = emit.record(
232        "IFCSITE",
233        &[
234            ("GlobalId", gid(&s.site)),
235            ("OwnerHistory", history.clone()),
236            ("Name", name(&s.site)),
237            ("ObjectPlacement", format!("#{site_placement}")),
238            ("CompositionType", ".ELEMENT.".into()),
239        ],
240    )?;
241    let building_a2p = emit.identity_placement()?;
242    let building_placement = emit.record(
243        "IFCLOCALPLACEMENT",
244        &[
245            ("PlacementRelTo", format!("#{site_placement}")),
246            ("RelativePlacement", format!("#{building_a2p}")),
247        ],
248    )?;
249    let building = emit.record(
250        "IFCBUILDING",
251        &[
252            ("GlobalId", gid(&s.building)),
253            ("OwnerHistory", history.clone()),
254            ("Name", name(&s.building)),
255            ("ObjectPlacement", format!("#{building_placement}")),
256            ("CompositionType", ".ELEMENT.".into()),
257        ],
258    )?;
259    for (relating, related, root) in [(project, site, &s.site), (site, building, &s.building)] {
260        emit.record(
261            "IFCRELAGGREGATES",
262            &[
263                (
264                    "GlobalId",
265                    format!("'{}'", root.global_id.derive("rel/aggregates").encode()),
266                ),
267                ("OwnerHistory", history.clone()),
268                ("RelatingObject", format!("#{relating}")),
269                ("RelatedObjects", format!("(#{related})")),
270            ],
271        )?;
272    }
273
274    Ok((step_text(s.file_name.as_deref(), identity.as_ref(), &out)?, findings))
275}
276
277/// The map conversion from the model `context` to its projected CRS, with
278/// the CRS's length unit (`metre` when it is metres).
279fn map_conversion(m: &MapConversion, context: u32, metre: u32, emit: &mut Emit) -> Result<(), String> {
280    let map_unit = match m.map_unit {
281        MapUnit::Metre => metre,
282        MapUnit::Foot => length_unit(emit, "FOOT", 0.3048, metre)?,
283        MapUnit::UsSurveyFoot => length_unit(emit, "US SURVEY FOOT", ifc_lite_core::US_SURVEY_FOOT_M, metre)?,
284    };
285    let crs = emit.record("IFCPROJECTEDCRS", &[("Name", quoted(&m.crs_name)), ("MapUnit", format!("#{map_unit}"))])?;
286    emit.record(
287        "IFCMAPCONVERSION",
288        &[
289            ("SourceCRS", format!("#{context}")),
290            ("TargetCRS", format!("#{crs}")),
291            ("Eastings", fmt(m.eastings)),
292            ("Northings", fmt(m.northings)),
293            ("OrthogonalHeight", fmt(m.orthogonal_height)),
294            ("XAxisAbscissa", fmt(m.x_axis_abscissa)),
295            ("XAxisOrdinate", fmt(m.x_axis_ordinate)),
296            ("Scale", m.scale.map_or("$".to_string(), fmt)),
297        ],
298    )?;
299    Ok(())
300}
301
302/// The skeleton's exporting identity. An application whose change time
303/// can't be attributed refuses when `strict`; otherwise it is a finding and
304/// the skeleton is written unattributed.
305fn identity_of(s: &Skeleton, strict: bool, findings: &mut Vec<ValidationFinding>) -> Result<Option<Identity>, String> {
306    match s.application.as_ref().map(|app| Identity::resolve(app, findings)).transpose() {
307        Err(message) if strict => Err(message),
308        Err(message) => {
309            findings.push(ValidationFinding::new(None, message));
310            Ok(None)
311        }
312        Ok(identity) => Ok(identity),
313    }
314}
315
316/// The `OwnerHistory` slot of everything the skeleton creates: the
317/// exporting application's `ADDED` history, written first, else unset.
318fn owner_slot(identity: Option<&Identity>, emit: &mut Emit) -> Result<String, String> {
319    let Some(identity) = identity else { return Ok("$".to_string()) };
320    let id = identity.added_in(SKELETON_SCHEMA, emit.ids, None, &mut Made::default(), emit.out).ok_or("id space exhausted")?;
321    Ok(format!("#{id}"))
322}
323
324/// The file: the header (naming the application, toolkit and change time
325/// when there is an application, empty fields otherwise), then the records.
326fn step_text(file_name: Option<&str>, identity: Option<&Identity>, out: &[(u32, String)]) -> Result<Vec<u8>, String> {
327    // Without an application every field is empty, as the skeleton always
328    // wrote it.
329    let empty = || Some(String::new());
330    let mut opts = crate::StepOptions {
331        description: empty(),
332        filename: Some(file_name.unwrap_or("").to_string()),
333        time_stamp: empty(),
334        application: empty(),
335        ..Default::default()
336    };
337    let originating = identity.map(|identity| identity.stamp_header(&mut opts));
338    let mut text = Vec::new();
339    crate::step_header::write_header_originating(&mut text, &opts, None, SKELETON_SCHEMA, originating.as_deref()).map_err(|e| e.to_string())?;
340    for (_, record) in out {
341        text.extend_from_slice(record.as_bytes());
342        text.push(b'\n');
343    }
344    text.extend_from_slice(b"ENDSEC;\nEND-ISO-10303-21;\n");
345    Ok(text)
346}
347
348fn check(s: &Skeleton) -> Result<(), String> {
349    let ids = [s.project.global_id, s.site.global_id, s.building.global_id];
350    if ids[0] == ids[1] || ids[1] == ids[2] || ids[0] == ids[2] {
351        return Err("the project, site and building need distinct GlobalIds".into());
352    }
353    if let Some(north) = s.true_north {
354        check_direction(north, "true north")?;
355    }
356    if let Some(m) = &s.map_conversion {
357        if m.crs_name.trim().is_empty() {
358            return Err("a map conversion needs a CRS name".into());
359        }
360        let values = [
361            m.eastings,
362            m.northings,
363            m.orthogonal_height,
364            m.scale.unwrap_or(1.0),
365        ];
366        if values.iter().any(|v| !v.is_finite()) {
367            return Err("a map conversion value is not finite".into());
368        }
369        if m.scale.is_some_and(|v| v <= 0.0) {
370            return Err("a map conversion scale must be positive".into());
371        }
372        check_direction(
373            [m.x_axis_abscissa, m.x_axis_ordinate],
374            "the map conversion's X axis",
375        )?;
376    }
377    Ok(())
378}
379
380fn check_direction([x, y]: [f64; 2], what: &str) -> Result<(), String> {
381    // `!(.. > ..)` also refuses a NaN.
382    if !(x.is_finite() && y.is_finite() && x.hypot(y) > 1e-12) {
383        return Err(format!("{what} is not a direction"));
384    }
385    Ok(())
386}
387
388#[cfg(test)]
389#[path = "skeleton_tests.rs"]
390mod tests;