Skip to main content

openbim_ifc_capi/
copying.rs

1//! Copying a product with what it solely owns, and appending entities from
2//! another model (#479).
3//!
4//! Each answers with a `CopyReport` record tape: copy (`REF`, the product's
5//! copy, or `NULL` for an append), copied and reused (`LIST`s of
6//! `CopiedEntity`: original `REF`, copy `REF`, type name `TEXT`), joined,
7//! skipped and regenerated (`LIST`s of `REF`), applied (`BOOL`, false for a
8//! dry run).
9//!
10//! As for the removals, the buffer protocol never applies a copy it cannot
11//! report: the call plans it first, and a size query or a short buffer
12//! answers `BufferTooSmall` with the sizes and leaves the model unchanged.
13//! The applied report has the planned one's size: planning and applying
14//! allocate the same ids.
15
16use openbim_ifc_binding_core::{
17    AppendOptions, BindingError, CopyProductOptions, CopyReport, IfcModel, ToRecord,
18};
19
20use crate::domains::Out;
21use crate::model::{with_model, OpenbimIfcModel};
22use crate::registry::{self, lock, Entry};
23use crate::status::{boundary, OpenbimIfcStatus};
24use crate::tape::{OpenbimIfcValueNode, Tape};
25
26/// `openbim_ifc_v0_1_model_copy_product` flag: do not copy the openings.
27pub const OPENBIM_IFC_COPY_NO_OPENINGS: u32 = 1;
28/// `openbim_ifc_v0_1_model_copy_product` flag: do not copy the fillings of
29/// the copied openings.
30pub const OPENBIM_IFC_COPY_NO_FILLINGS: u32 = 2;
31/// `openbim_ifc_v0_1_model_copy_product` flag: do not contain the copy in
32/// the original's container.
33pub const OPENBIM_IFC_COPY_NO_CONTAINER: u32 = 4;
34/// `openbim_ifc_v0_1_model_copy_product` flag: do not make the copy a part
35/// of the original's whole.
36pub const OPENBIM_IFC_COPY_NO_AGGREGATE: u32 = 8;
37/// `openbim_ifc_v0_1_model_copy_product` flag: report only.
38pub const OPENBIM_IFC_COPY_DRY_RUN: u32 = 16;
39
40/// `openbim_ifc_v0_1_model_append` `GlobalId` mode: keep, refusing one the
41/// target holds.
42pub const OPENBIM_IFC_GLOBAL_IDS_KEEP: u32 = 0;
43/// `openbim_ifc_v0_1_model_append` `GlobalId` mode: regenerate every one.
44pub const OPENBIM_IFC_GLOBAL_IDS_REGENERATE: u32 = 1;
45/// `openbim_ifc_v0_1_model_append` `GlobalId` mode: regenerate the ones the
46/// target holds.
47pub const OPENBIM_IFC_GLOBAL_IDS_REGENERATE_COLLIDING: u32 = 2;
48/// `openbim_ifc_v0_1_model_append` `GlobalId` mode: an `IfcRoot` the target
49/// holds by `GlobalId` and type is reused, its relationships joined.
50pub const OPENBIM_IFC_GLOBAL_IDS_MERGE: u32 = 3;
51
52/// `openbim_ifc_v0_1_model_append` flag: copy units equal to the target's.
53pub const OPENBIM_IFC_APPEND_NO_REUSE_UNITS: u32 = 1;
54/// `openbim_ifc_v0_1_model_append` flag: copy contexts equal to the
55/// target's.
56pub const OPENBIM_IFC_APPEND_NO_REUSE_CONTEXTS: u32 = 2;
57/// `openbim_ifc_v0_1_model_append` flag: copy an owner history equal to
58/// the target's.
59pub const OPENBIM_IFC_APPEND_NO_REUSE_OWNER_HISTORY: u32 = 4;
60/// `openbim_ifc_v0_1_model_append` flag: copy materials equal to the
61/// target's.
62pub const OPENBIM_IFC_APPEND_NO_REUSE_MATERIALS: u32 = 8;
63/// `openbim_ifc_v0_1_model_append` flag: copy styles equal to the target's.
64pub const OPENBIM_IFC_APPEND_NO_REUSE_STYLES: u32 = 16;
65/// `openbim_ifc_v0_1_model_append` flag: report only.
66pub const OPENBIM_IFC_APPEND_DRY_RUN: u32 = 32;
67
68const COPY_FLAGS: u32 = 31;
69const APPEND_FLAGS: u32 = 63;
70
71/// Plan with `run(model, true)`; then write the report, applying with
72/// `run(model, false)` first unless `dry_run`, and only when it fits.
73///
74/// # Safety
75/// The buffers as for `Out`.
76unsafe fn copy_export(
77    model: &mut IfcModel,
78    out: &Out,
79    dry_run: bool,
80    run: impl Fn(&mut IfcModel, bool) -> Result<CopyReport, BindingError>,
81) -> Result<OpenbimIfcStatus, BindingError> {
82    if let Err(status) = out.check() {
83        return Ok(status);
84    }
85    let planned = run(model, true)?;
86    let tape = Tape::encode(&planned.to_record().to_tagged());
87    let fits = tape.nodes.len() <= out.node_capacity && tape.strings.len() <= out.string_capacity;
88    let report = if dry_run || !fits {
89        planned
90    } else {
91        run(model, false)?
92    };
93    // SAFETY: caller contract.
94    unsafe { out.write(&report.to_record().to_tagged()) }
95}
96
97/// Copy product (or type object) `product` with everything it solely owns,
98/// as one checked transaction: its placement, representation, own property
99/// and quantity sets, material usage, ports and, unless a flag says
100/// otherwise, its openings and the doors and windows filling them; joining
101/// its type, shared property sets, classification and, unless a flag says
102/// otherwise, its container and whole. `placement` non-zero places the
103/// copy by that `IfcObjectPlacement`; `offset` non-null (three doubles)
104/// moves it in its parent placement's frame; not both. `flags`:
105/// `OPENBIM_IFC_COPY_NO_OPENINGS`, `OPENBIM_IFC_COPY_NO_FILLINGS`,
106/// `OPENBIM_IFC_COPY_NO_CONTAINER`, `OPENBIM_IFC_COPY_NO_AGGREGATE`,
107/// `OPENBIM_IFC_COPY_DRY_RUN`. The answer is a `CopyReport` tape (see the
108/// module docs); a size query or a short buffer plans the copy and answers
109/// `BufferTooSmall` without applying it.
110///
111/// `MissingEntity`; `WrongEntityType` for neither an `IfcProduct` nor an
112/// `IfcTypeObject`; `Unsupported` for an offset onto a placement that is
113/// not a local placement with a Cartesian location, or a moved copy whose
114/// openings are not placed relative to it; `InvalidValue` for both a
115/// placement and an offset, or a non-finite offset; `InvalidArgument` for
116/// an unknown flag; `FeatureDisabled`.
117///
118/// # Safety
119/// `offset` null or valid for three reads; the buffers as for
120/// `openbim_ifc_v0_1_entity_attribute`.
121#[no_mangle]
122pub unsafe extern "C" fn openbim_ifc_v0_1_model_copy_product(
123    model: OpenbimIfcModel,
124    product: u64,
125    placement: u64,
126    offset: *const f64,
127    flags: u32,
128    nodes: *mut OpenbimIfcValueNode,
129    node_capacity: usize,
130    out_nodes_required: *mut usize,
131    strings: *mut u8,
132    string_capacity: usize,
133    out_strings_required: *mut usize,
134) -> OpenbimIfcStatus {
135    if flags & !COPY_FLAGS != 0 {
136        return OpenbimIfcStatus::InvalidArgument;
137    }
138    let mut options = CopyProductOptions::new();
139    if !offset.is_null() {
140        // SAFETY: three reads (caller contract).
141        options.offset = Some(unsafe { [*offset, *offset.add(1), *offset.add(2)] });
142    }
143    options.placement = (placement != 0).then_some(placement);
144    options.openings = flags & OPENBIM_IFC_COPY_NO_OPENINGS == 0;
145    options.fillings = flags & OPENBIM_IFC_COPY_NO_FILLINGS == 0;
146    options.container = flags & OPENBIM_IFC_COPY_NO_CONTAINER == 0;
147    options.aggregate = flags & OPENBIM_IFC_COPY_NO_AGGREGATE == 0;
148    let dry_run = flags & OPENBIM_IFC_COPY_DRY_RUN != 0;
149    let out = Out {
150        nodes,
151        node_capacity,
152        out_nodes_required,
153        strings,
154        string_capacity,
155        out_strings_required,
156    };
157    boundary(|| {
158        with_model(model, |m| {
159            // SAFETY: caller contract above.
160            unsafe {
161                copy_export(m, &out, dry_run, |m, plan| {
162                    let mut options = options;
163                    options.dry_run = plan;
164                    m.copy_product(product, options)
165                })
166            }
167        })
168    })
169}
170
171/// Copy the `id_count` entities `ids` of model `source` into model
172/// `target` with what belongs to them, as one checked transaction: what
173/// they reference, their property sets, type, material and classification,
174/// their openings, fillings and ports, and what attaches to their geometry.
175/// Units, contexts, the owner history, materials and styles equal to the
176/// target's are reused unless a flag says otherwise. Relationships to
177/// objects not copied (a spatial container) are skipped and reported.
178/// `global_ids`: `OPENBIM_IFC_GLOBAL_IDS_KEEP`, `_REGENERATE`,
179/// `_REGENERATE_COLLIDING` or `_MERGE`. `flags`:
180/// `OPENBIM_IFC_APPEND_NO_REUSE_UNITS`, `_CONTEXTS`, `_OWNER_HISTORY`,
181/// `_MATERIALS`, `_STYLES`, `OPENBIM_IFC_APPEND_DRY_RUN`. The answer is a
182/// `CopyReport` tape (see the module docs); a size query or a short buffer
183/// plans the append and answers `BufferTooSmall` without applying it.
184///
185/// `InvalidHandle`; `InvalidArgument` for `target` and `source` the same
186/// model, an unknown mode or flag; `MissingEntity` for an id `source`
187/// lacks; `Unsupported` when the models' length or plane angle units
188/// differ; `UnsupportedSchema` for an entity the target's release cannot
189/// hold; `InvalidValue` for a kept `GlobalId` the target holds;
190/// `FeatureDisabled`.
191///
192/// # Safety
193/// `ids` null (with `id_count` 0) or valid for `id_count` reads; the
194/// buffers as for `openbim_ifc_v0_1_entity_attribute`.
195#[no_mangle]
196pub unsafe extern "C" fn openbim_ifc_v0_1_model_append(
197    target: OpenbimIfcModel,
198    source: OpenbimIfcModel,
199    ids: *const u64,
200    id_count: usize,
201    global_ids: u32,
202    flags: u32,
203    nodes: *mut OpenbimIfcValueNode,
204    node_capacity: usize,
205    out_nodes_required: *mut usize,
206    strings: *mut u8,
207    string_capacity: usize,
208    out_strings_required: *mut usize,
209) -> OpenbimIfcStatus {
210    if flags & !APPEND_FLAGS != 0 {
211        return OpenbimIfcStatus::InvalidArgument;
212    }
213    let mode = match global_ids {
214        OPENBIM_IFC_GLOBAL_IDS_KEEP => "keep",
215        OPENBIM_IFC_GLOBAL_IDS_REGENERATE => "regenerate",
216        OPENBIM_IFC_GLOBAL_IDS_REGENERATE_COLLIDING => "regenerate-colliding",
217        OPENBIM_IFC_GLOBAL_IDS_MERGE => "merge",
218        _ => return OpenbimIfcStatus::InvalidArgument,
219    };
220    if id_count > 0 && ids.is_null() {
221        return OpenbimIfcStatus::NullPointer;
222    }
223    let roots: Vec<u64> = if id_count == 0 {
224        Vec::new()
225    } else {
226        // SAFETY: `id_count` reads (caller contract).
227        unsafe { std::slice::from_raw_parts(ids, id_count) }.to_vec()
228    };
229    let mut options = AppendOptions::new();
230    options.global_ids = mode.to_owned();
231    options.reuse_units = flags & OPENBIM_IFC_APPEND_NO_REUSE_UNITS == 0;
232    options.reuse_contexts = flags & OPENBIM_IFC_APPEND_NO_REUSE_CONTEXTS == 0;
233    options.reuse_owner_history = flags & OPENBIM_IFC_APPEND_NO_REUSE_OWNER_HISTORY == 0;
234    options.reuse_materials = flags & OPENBIM_IFC_APPEND_NO_REUSE_MATERIALS == 0;
235    options.reuse_styles = flags & OPENBIM_IFC_APPEND_NO_REUSE_STYLES == 0;
236    let dry_run = flags & OPENBIM_IFC_APPEND_DRY_RUN != 0;
237    let out = Out {
238        nodes,
239        node_capacity,
240        out_nodes_required,
241        strings,
242        string_capacity,
243        out_strings_required,
244    };
245    if target == source {
246        return OpenbimIfcStatus::InvalidArgument;
247    }
248    let (Some(into), Some(from)) = (registry::get(target), registry::get(source)) else {
249        return OpenbimIfcStatus::InvalidHandle;
250    };
251    boundary(|| {
252        // Both locks, always in handle order, so two appends between the
253        // same models in opposite directions cannot deadlock.
254        let (mut into, from) = if target < source {
255            let into = lock(&into);
256            (into, lock(&from))
257        } else {
258            let from = lock(&from);
259            (lock(&into), from)
260        };
261        let Entry { model, last_error } = &mut *into;
262        // SAFETY: caller contract above.
263        let result = unsafe {
264            copy_export(model, &out, dry_run, |m, plan| {
265                let mut options = options.clone();
266                options.dry_run = plan;
267                m.append(&from.model, &roots, &options)
268            })
269        };
270        match result {
271            Ok(status) => {
272                *last_error = None;
273                status
274            }
275            Err(error) => {
276                let status = OpenbimIfcStatus::from(&error);
277                *last_error = Some(error);
278                status
279            }
280        }
281    })
282}