ifc_lite_export/plan/
builders.rs

1// SPDX-License-Identifier: MPL-2.0
2//! Constructors for the export plan's public types.
3//!
4//! The plan's structs and enums are `#[non_exhaustive]`, so a field or
5//! variant added later is not a breaking change. `PropScope`, `PsetKind`
6//! and the `GlobalId` newtype stay exhaustive: IFC closes them. Outside this crate a struct
7//! is built with its `new` (the fields it cannot do without) and finished with
8//! `with_*` setters, or by assigning its public fields:
9//!
10//! ```
11//! use ifc_lite_export::plan::*;
12//! let wall = NewObject::new(GlobalId(1), ClassSpec::new(IfcClass::Wall), NewPlacement::new(IDENTITY))
13//!     .with_name("Wall")
14//!     .with_container(ObjectRef::Id(70));
15//! assert_eq!(wall.name.as_deref(), Some("Wall"));
16//! ```
17//!
18//! The Add vocabulary's constructors are in `add_builders.rs`.
19
20use super::add_types::GlobalId;
21use super::skeleton::{MapConversion, MapUnit, Skeleton, SkeletonRoot};
22use super::types::{
23    Disposition, DroppedRepresentation, ExportPlan, ExportingApplication, ExportingPerson, GeometryPatch, ObjectRef, Patch, PlacementPatch, PlanContext, PropScope,
24    PropWrite, PsetKind, Refusal, SurfaceColour, TriangleMesh, ValidationFinding,
25};
26
27impl PropWrite {
28    /// A write into property `prop` of set `pset` of `literal`, STEP text
29    /// typed `measure_type` (`PropWrite::new("Pset_WallCommon",
30    /// "ThermalTransmittance", "IFCTHERMALTRANSMITTANCEMEASURE", "0.24", ..)`),
31    /// keeping any unit the existing value carries.
32    pub fn new(
33        pset: impl Into<String>,
34        prop: impl Into<String>,
35        measure_type: impl Into<String>,
36        literal: impl Into<String>,
37        kind: PsetKind,
38        scope: PropScope,
39    ) -> Self {
40        Self { pset: pset.into(), prop: prop.into(), measure_type: measure_type.into(), literal: literal.into(), unit: None, kind, scope, target: None }
41    }
42
43    /// Write exactly the value record `express_id`, not the first property
44    /// of this name in the first set of this name. See [`PropWrite::target`].
45    pub fn with_target(mut self, express_id: u32) -> Self {
46        self.target = Some(express_id);
47        self
48    }
49
50    /// The STEP text of the unit to write (`"#55"`, or `"$"` for none).
51    pub fn with_unit(mut self, unit: impl Into<String>) -> Self {
52        self.unit = Some(unit.into());
53        self
54    }
55}
56
57impl PlacementPatch {
58    pub fn new(matrix: [[f64; 4]; 4]) -> Self {
59        Self { matrix }
60    }
61}
62
63impl TriangleMesh {
64    pub fn new(positions: Vec<[f64; 3]>, triangles: Vec<[u32; 3]>) -> Self {
65        Self { positions, triangles }
66    }
67}
68
69impl SurfaceColour {
70    pub fn new(rgb: [f64; 3], transparency: f64) -> Self {
71        Self { rgb, transparency }
72    }
73}
74
75impl GeometryPatch {
76    pub fn new(mesh: TriangleMesh) -> Self {
77        Self { mesh, colour: None }
78    }
79
80    pub fn with_colour(mut self, colour: SurfaceColour) -> Self {
81        self.colour = Some(colour);
82        self
83    }
84}
85
86impl Patch {
87    /// A patch that changes nothing until a setter names a concern.
88    pub fn new() -> Self {
89        Self::default()
90    }
91
92    pub fn with_name(mut self, name: impl Into<String>) -> Self {
93        self.name = Some(name.into());
94        self
95    }
96
97    pub fn with_psets(mut self, psets: Vec<PropWrite>) -> Self {
98        self.psets = psets;
99        self
100    }
101
102    pub fn with_placement(mut self, placement: PlacementPatch) -> Self {
103        self.placement = Some(placement);
104        self
105    }
106
107    pub fn with_geometry(mut self, geometry: GeometryPatch) -> Self {
108        self.geometry = Some(geometry);
109        self
110    }
111}
112
113impl PlanContext {
114    pub fn new() -> Self {
115        Self::default()
116    }
117
118    /// A context with an exporting application, so a test of anything but
119    /// attribution runs the way a real export does.
120    #[cfg(test)]
121    pub(crate) fn attributed() -> Self {
122        Self::new().with_application(ExportingApplication::new("TestOrg", "TestApp", "test-app", "1.0", "2026-01-01T00:00:00"))
123    }
124
125    pub fn with_author(mut self, author: impl Into<String>) -> Self {
126        self.author = Some(author.into());
127        self
128    }
129
130    pub fn with_organization(mut self, organization: impl Into<String>) -> Self {
131        self.organization = Some(organization.into());
132        self
133    }
134
135    pub fn with_time_stamp(mut self, time_stamp: impl Into<String>) -> Self {
136        self.time_stamp = Some(time_stamp.into());
137        self
138    }
139
140    pub fn with_application(mut self, application: ExportingApplication) -> Self {
141        self.application = Some(application);
142        self
143    }
144
145    pub fn with_file_name(mut self, file_name: impl Into<String>) -> Self {
146        self.file_name = Some(file_name.into());
147        self
148    }
149}
150
151impl ExportingPerson {
152    pub fn new(identification: impl Into<String>, name: impl Into<String>) -> Self {
153        Self { identification: identification.into(), name: name.into() }
154    }
155}
156
157impl ExportingApplication {
158    pub fn new(
159        developer: impl Into<String>,
160        full_name: impl Into<String>,
161        identifier: impl Into<String>,
162        version: impl Into<String>,
163        changed_at: impl Into<String>,
164    ) -> Self {
165        Self {
166            developer: developer.into(),
167            full_name: full_name.into(),
168            identifier: identifier.into(),
169            version: version.into(),
170            person: None,
171            changed_at: changed_at.into(),
172        }
173    }
174
175    pub fn with_person(mut self, person: ExportingPerson) -> Self {
176        self.person = Some(person);
177        self
178    }
179}
180
181impl Refusal {
182    pub fn new(object: ObjectRef, reason: impl Into<String>) -> Self {
183        Self { object, reason: reason.into() }
184    }
185}
186
187impl ValidationFinding {
188    pub fn new(express_id: Option<u32>, message: impl Into<String>) -> Self {
189        Self { express_id, message: message.into() }
190    }
191}
192
193impl DroppedRepresentation {
194    pub fn new(object: ObjectRef, representation: u32, identifier: Option<String>) -> Self {
195        Self { object, representation, identifier }
196    }
197}
198
199impl ExportPlan {
200    pub fn new(dispositions: Vec<(ObjectRef, Disposition)>) -> Self {
201        Self { dispositions, context: PlanContext::default() }
202    }
203
204    pub fn with_context(mut self, context: PlanContext) -> Self {
205        self.context = context;
206        self
207    }
208}
209
210impl SkeletonRoot {
211    pub fn new(global_id: GlobalId) -> Self {
212        Self { global_id, name: None }
213    }
214
215    pub fn with_name(mut self, name: impl Into<String>) -> Self {
216        self.name = Some(name.into());
217        self
218    }
219}
220
221impl MapConversion {
222    /// A conversion to the projected CRS `crs_name`, with the engineering
223    /// origin at `eastings`, `northings` and `orthogonal_height` in metres,
224    /// no rotation (X along grid east) and no scale.
225    pub fn new(crs_name: impl Into<String>, eastings: f64, northings: f64, orthogonal_height: f64) -> Self {
226        Self {
227            crs_name: crs_name.into(),
228            map_unit: MapUnit::Metre,
229            eastings,
230            northings,
231            orthogonal_height,
232            x_axis_abscissa: 1.0,
233            x_axis_ordinate: 0.0,
234            scale: None,
235        }
236    }
237
238    pub fn with_map_unit(mut self, map_unit: MapUnit) -> Self {
239        self.map_unit = map_unit;
240        self
241    }
242
243    /// The engineering X axis in map coordinates; see the field docs.
244    pub fn with_x_axis(mut self, abscissa: f64, ordinate: f64) -> Self {
245        self.x_axis_abscissa = abscissa;
246        self.x_axis_ordinate = ordinate;
247        self
248    }
249
250    pub fn with_scale(mut self, scale: f64) -> Self {
251        self.scale = Some(scale);
252        self
253    }
254}
255
256impl Skeleton {
257    pub fn new(project: SkeletonRoot, site: SkeletonRoot, building: SkeletonRoot) -> Self {
258        Self { project, site, building, true_north: None, map_conversion: None, application: None, file_name: None }
259    }
260
261    pub fn with_application(mut self, application: ExportingApplication) -> Self {
262        self.application = Some(application);
263        self
264    }
265
266    pub fn with_file_name(mut self, file_name: impl Into<String>) -> Self {
267        self.file_name = Some(file_name.into());
268        self
269    }
270
271    pub fn with_true_north(mut self, true_north: [f64; 2]) -> Self {
272        self.true_north = Some(true_north);
273        self
274    }
275
276    pub fn with_map_conversion(mut self, map_conversion: MapConversion) -> Self {
277        self.map_conversion = Some(map_conversion);
278        self
279    }
280}
281
282#[cfg(test)]
283mod tests {
284    use super::*;
285    use crate::plan::IDENTITY;
286
287    #[test]
288    fn each_setter_sets_its_field() {
289        let w = PropWrite::new("S", "P", "IFCLABEL", "'x'", PsetKind::Property, PropScope::Type).with_unit("#5");
290        assert_eq!((w.pset.as_str(), w.prop.as_str(), w.measure_type.as_str(), w.literal.as_str()), ("S", "P", "IFCLABEL", "'x'"));
291        assert_eq!((w.unit.as_deref(), w.kind, w.scope), (Some("#5"), PsetKind::Property, PropScope::Type));
292        let mesh = TriangleMesh::new(vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], vec![[0, 1, 2]]);
293        let p = Patch::new()
294            .with_name("N")
295            .with_psets(vec![w])
296            .with_placement(PlacementPatch::new(IDENTITY))
297            .with_geometry(GeometryPatch::new(mesh).with_colour(SurfaceColour::new([1.0, 0.0, 0.0], 0.0)));
298        assert_eq!(p.name.as_deref(), Some("N"));
299        assert_eq!((p.psets.len(), p.psets[0].prop.as_str()), (1, "P"));
300        assert_eq!(p.placement.map(|pl| pl.matrix), Some(IDENTITY));
301        let g = p.geometry.as_ref().unwrap();
302        assert_eq!((g.mesh.positions.clone(), g.mesh.triangles.clone()), (vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], vec![[0, 1, 2]]));
303        assert_eq!(g.colour.map(|c| (c.rgb, c.transparency)), Some(([1.0, 0.0, 0.0], 0.0)));
304        let c = PlanContext::new().with_author("a").with_organization("o").with_time_stamp("t");
305        assert_eq!((c.author.as_deref(), c.organization.as_deref(), c.time_stamp.as_deref()), (Some("a"), Some("o"), Some("t")));
306        let plan = ExportPlan::new(vec![(ObjectRef::Id(1), Disposition::Delete)]).with_context(c);
307        assert!(matches!(plan.dispositions.as_slice(), [(ObjectRef::Id(1), Disposition::Delete)]));
308        let ctx = &plan.context;
309        assert_eq!((ctx.author.as_deref(), ctx.organization.as_deref(), ctx.time_stamp.as_deref()), (Some("a"), Some("o"), Some("t")));
310        let m = MapConversion::new("EPSG:2056", 1.0, 2.0, 3.0).with_map_unit(MapUnit::Foot).with_x_axis(0.0, 1.0).with_scale(0.5);
311        assert_eq!((m.crs_name.as_str(), m.eastings, m.northings, m.orthogonal_height), ("EPSG:2056", 1.0, 2.0, 3.0));
312        assert_eq!((m.map_unit, m.x_axis_abscissa, m.x_axis_ordinate, m.scale), (MapUnit::Foot, 0.0, 1.0, Some(0.5)));
313        let root = |n: u128, name: &str| SkeletonRoot::new(GlobalId(n)).with_name(name);
314        let s = Skeleton::new(root(1, "P"), root(2, "S"), root(3, "B")).with_true_north([0.0, 1.0]).with_map_conversion(m);
315        let roots = [&s.project, &s.site, &s.building].map(|r| (r.global_id, r.name.clone().unwrap()));
316        assert_eq!(roots, [(GlobalId(1), "P".into()), (GlobalId(2), "S".into()), (GlobalId(3), "B".into())]);
317        assert_eq!(s.true_north, Some([0.0, 1.0]));
318        assert_eq!(s.map_conversion.as_ref().map(|m| (m.crs_name.as_str(), m.scale)), Some(("EPSG:2056", Some(0.5))));
319        let r = Refusal::new(ObjectRef::Id(1), "r");
320        assert_eq!((&r.object, r.reason.as_str()), (&ObjectRef::Id(1), "r"));
321        let f = ValidationFinding::new(Some(4), "m");
322        assert_eq!((f.express_id, f.message.as_str()), (Some(4), "m"));
323        let d = DroppedRepresentation::new(ObjectRef::Id(2), 9, Some("Axis".into()));
324        assert_eq!((&d.object, d.representation, d.identifier.as_deref()), (&ObjectRef::Id(2), 9, Some("Axis")));
325    }
326}