ifc_model/model.rs
1//! The entity graph — storage, lookup, and nothing else.
2//!
3//! # What this type deliberately does NOT do
4//!
5//! `Model` has no idea what a cost item, a task, a wall, or a material is. It
6//! stores entities and answers structural questions about them. Every domain
7//! meaning lives in a separate crate that borrows a `&Model` and interprets it.
8//!
9//! That is not a stylistic preference, it is what makes two things possible:
10//!
11//! 1. **Thin builds.** An app that only reads geometry compiles no cost,
12//! schedule, or structural code, because those crates are optional features
13//! rather than parts of the model.
14//! 2. **Lossless round-trips of data we do not understand.** Since the model
15//! stores entities structurally, a cost entity survives parse and re-export
16//! byte-for-byte in content even when `ifc-cost` is not compiled in. If the
17//! model instead held a `CostItem` struct, dropping the feature would drop
18//! the data.
19//!
20//! The rule to preserve: **no `if type_name == "IFCWALL"` in this crate.**
21
22use std::ops::Range;
23use std::sync::atomic::{AtomicU64, Ordering};
24use std::sync::Arc;
25
26use crate::diagnostic::Diagnostic;
27use crate::entity::Entity;
28use crate::header::Header;
29use crate::index::{Derived, Footprint};
30use crate::lazy::{EntitySource, Slot};
31use crate::mutation::{Recording, Step};
32use crate::value::EntityId;
33use ahash::AHashMap;
34
35/// A parsed IFC file: header, entities, and indices over them.
36#[derive(Debug, Clone, Default)]
37pub struct Model {
38 header: Header,
39 /// Entities keyed by their in-file id, so `#42` survives a round-trip.
40 /// A slot holds its entity decoded, or the span `source` decodes it from
41 /// on first access (see [`EntitySource`]).
42 entities: AHashMap<EntityId, Slot>,
43 /// Insertion order, so a re-export preserves the original file order
44 /// instead of hash order. Diffing two exports is otherwise unreadable.
45 order: Vec<EntityId>,
46 /// Type name to entity ids. Built during insertion because "every
47 /// IfcWall" is the most common query in any consumer.
48 by_type: AHashMap<String, Vec<EntityId>>,
49 max_id: u64,
50 /// Replaced by a fresh, process-unique value on every structural change,
51 /// so a revision names one state of one model lineage: an inverse or a
52 /// transaction recorded against another model is refused, not applied.
53 /// A clone shares its source's revision until either side changes.
54 ///
55 /// Bumped by every structural change. A transaction opened against one
56 /// revision refuses to commit against another, so an editor working from
57 /// a stale view is told rather than silently overwriting.
58 ///
59 /// Not a content hash: two different edit sequences can reach the same
60 /// bytes and still get different revisions. It answers "did anything
61 /// change", which is the question optimistic concurrency asks.
62 ///
63 /// [`Model::preview`] is the one call that sets the revision back: it
64 /// restores the exact state that revision named, and the revisions drawn
65 /// inside it are never handed out again.
66 revision: u64,
67 /// Non-fatal findings from the read that produced this model. Empty
68 /// unless a codec recovered from damaged input.
69 diagnostics: Vec<Diagnostic>,
70 /// Decodes lazily registered entities; `None` for a model built only
71 /// from decoded entities. Shared by clones.
72 source: Option<Arc<dyn EntitySource>>,
73 /// Open recordings, innermost last; empty unless a caller is capturing
74 /// an [`Inverse`](crate::Inverse). See `mutation::record`.
75 recording: Recording,
76 /// The reverse and GlobalId indexes, once something asked for them; every
77 /// write keeps them current. See `index::maintained`.
78 derived: Derived,
79}
80
81/// The last revision handed out, process-wide.
82static LAST_REVISION: AtomicU64 = AtomicU64::new(0);
83
84/// A revision no model has had before.
85fn next_revision() -> u64 {
86 LAST_REVISION.fetch_add(1, Ordering::Relaxed) + 1
87}
88
89impl Model {
90 /// An empty model.
91 pub fn new() -> Self {
92 Self::default()
93 }
94
95 /// An empty model whose entities a codec registers with
96 /// [`Model::insert_lazy`] and `source` decodes on first access.
97 pub fn with_source(source: Arc<dyn EntitySource>) -> Self {
98 Self {
99 source: Some(source),
100 ..Self::default()
101 }
102 }
103
104 /// The file header (schema declaration, description, author).
105 pub fn header(&self) -> &Header {
106 &self.header
107 }
108
109 /// Mutable access to the header, for writers and editors.
110 ///
111 /// Counts as a structural change: it bumps [`Model::revision`], and an
112 /// active recording keeps the header it replaces.
113 pub fn header_mut(&mut self) -> &mut Header {
114 if self.is_recording() {
115 let prior = Box::new(self.header.clone());
116 self.record(Step::Header(prior));
117 }
118 self.revision = next_revision();
119 &mut self.header
120 }
121
122 /// Non-fatal problems reported by the codec that read this model.
123 ///
124 /// Empty for a clean file. A non-empty slice means the model is
125 /// incomplete relative to its source: the codec recovered from damage and
126 /// each entry says exactly what was dropped, so a consumer can surface
127 /// "loaded, 1 record skipped" instead of pretending the read was lossless.
128 pub fn diagnostics(&self) -> &[Diagnostic] {
129 &self.diagnostics
130 }
131
132 /// Whether the read that produced this model dropped anything.
133 pub fn is_complete(&self) -> bool {
134 self.diagnostics.is_empty()
135 }
136
137 /// Attaches a codec diagnostic. Called by codecs during a recovered read.
138 pub fn push_diagnostic(&mut self, diagnostic: Diagnostic) {
139 self.diagnostics.push(diagnostic);
140 }
141
142 /// Insert an entity under a specific id, replacing any previous occupant.
143 ///
144 /// Codecs use this to preserve file ids exactly.
145 pub fn insert(&mut self, id: EntityId, entity: Entity) {
146 #[cfg(feature = "authored-dump")]
147 crate::authored_dump::record(&entity.type_name, "insert");
148 let type_name = std::sync::Arc::clone(&entity.type_name);
149 let after = self.derived.is_built().then(|| Footprint::of(&entity));
150 self.place(id, &type_name, Slot::decoded(entity), after);
151 }
152
153 /// Register the entity stored at `span` of this model's source under
154 /// `id`, without decoding it; it is decoded on first access. Replaces
155 /// any previous occupant exactly as [`Model::insert`] does.
156 ///
157 /// `type_name` must be the type the span decodes to, which lets
158 /// [`Model::ids_of_type`] answer without decoding. Only a codec that
159 /// validated the span may register it (see [`EntitySource`]).
160 ///
161 /// # Panics
162 ///
163 /// When the model has no source ([`Model::with_source`]).
164 pub fn insert_lazy(&mut self, id: EntityId, type_name: &str, span: Range<usize>) {
165 assert!(
166 self.source.is_some(),
167 "insert_lazy needs a model built with Model::with_source"
168 );
169 #[cfg(feature = "authored-dump")]
170 crate::authored_dump::record(type_name, "insert");
171 // The span is not decoded here, so its footprint is unknown.
172 self.derived.clear();
173 self.place(id, type_name, Slot::lazy(span), None);
174 }
175
176 /// Reserve room for `additional` more entities; a codec that knows the
177 /// record count up front avoids regrowing the storage while it loads.
178 pub fn reserve(&mut self, additional: usize) {
179 self.entities.reserve(additional);
180 self.order.reserve(additional);
181 }
182
183 /// The shared tail of [`Model::insert`] and [`Model::insert_lazy`].
184 fn place(&mut self, id: EntityId, type_name: &str, slot: Slot, after: Option<Footprint>) {
185 // Type names are ASCII upper case in practice, so the key is
186 // usually `type_name` itself and nothing is allocated per entity.
187 let upper;
188 let key = if type_name.bytes().any(|byte| byte.is_ascii_lowercase()) {
189 upper = type_name.to_ascii_uppercase();
190 upper.as_str()
191 } else {
192 type_name
193 };
194 let recording = self.is_recording();
195 match self.entities.insert(id, slot) {
196 None => {
197 self.order.push(id);
198 if recording {
199 self.record(Step::Remove { id });
200 }
201 self.note_write(id, None, after);
202 }
203 // Replacing an occupant: drop its old type-index entry, otherwise
204 // `ids_of_type` reports the id twice for the same type, or keeps
205 // reporting it under a type the entity no longer has. Both make an
206 // edit layer silently wrong.
207 Some(previous) => {
208 let previous = previous.into_entity(self.source.as_deref());
209 let previous_key = previous.type_name.to_ascii_uppercase();
210 let before = self.derived.is_built().then(|| Footprint::of(&previous));
211 self.note_write(id, before, after);
212 if recording {
213 let bucket = self.bucket_position(&previous_key, id);
214 self.record(Step::Replace {
215 id,
216 entity: previous,
217 bucket,
218 });
219 }
220 if previous_key != key {
221 self.unindex(&previous_key, id);
222 } else {
223 // Same type: the entry is still correct, so re-adding it
224 // below would duplicate it.
225 self.max_id = self.max_id.max(id.0);
226 self.revision = next_revision();
227 return;
228 }
229 }
230 }
231 match self.by_type.get_mut(key) {
232 Some(ids) => ids.push(id),
233 None => {
234 self.by_type.insert(key.to_owned(), vec![id]);
235 }
236 }
237 self.max_id = self.max_id.max(id.0);
238 self.revision = next_revision();
239 }
240
241 /// Append an entity, allocating the next free id.
242 ///
243 /// # Panics
244 ///
245 /// When every id up to `u64::MAX` is taken or reserved: there is no next
246 /// id, and wrapping to `#0` would hand out an id nothing may have.
247 pub fn push(&mut self, entity: Entity) -> EntityId {
248 let id = self.next_id();
249 self.insert(id, entity);
250 id
251 }
252
253 /// How many structural changes this model has seen.
254 ///
255 /// Starts at zero for a model nothing was written to. Every change draws
256 /// a new value that is greater than any handed out before, in any model of
257 /// the process, and not necessarily one more than the last; the absolute
258 /// value carries no meaning beyond comparison. See [`Transaction`](crate::Transaction).
259 ///
260 /// Across a [`Model::preview`] only equality is meaningful: a revision
261 /// seen inside the closure can be greater than the model's afterwards.
262 ///
263 /// [`Model::preview`] is the one call that sets the revision back: it
264 /// restores the exact state that revision named, and the revisions drawn
265 /// inside it are never handed out again.
266 pub fn revision(&self) -> u64 {
267 self.revision
268 }
269
270 /// Record a structural change made through a sibling mutation module.
271 pub(crate) fn bump_revision(&mut self) {
272 self.revision = next_revision();
273 }
274
275 /// The id [`Model::push`] would allocate next.
276 ///
277 /// A transaction reserves ids from here so several creates in one batch
278 /// cannot collide with each other or with existing entities.
279 ///
280 /// # Panics
281 ///
282 /// When `u64::MAX` is taken or reserved: there is no next id.
283 pub fn next_id(&self) -> EntityId {
284 let next = self
285 .max_id
286 .checked_add(1)
287 .expect("no free entity id above u64::MAX");
288 EntityId(next)
289 }
290
291 /// Raises the next free id so that `id` and every lower id stay taken.
292 ///
293 /// `push`, `next_id` and transactions never hand out `id` or a lower id.
294 /// A codec calls this after a read with the highest id the source
295 /// declared or referenced, so a new entity cannot take the id of a record
296 /// that was dropped or of a reference that points nowhere. A no-op when
297 /// `id` is not above every id the model has seen. Otherwise it is a
298 /// structural change: it bumps [`Model::revision`] and, while a recording
299 /// is open, keeps the previous floor like every other write.
300 ///
301 /// # Panics
302 ///
303 /// For `u64::MAX`, after which no id would be left to hand out.
304 pub fn reserve_ids_through(&mut self, id: EntityId) {
305 assert!(id.0 < u64::MAX, "cannot reserve every entity id");
306 if id.0 <= self.max_id {
307 return;
308 }
309 if self.is_recording() {
310 self.record(Step::IdFloor {
311 max_id: self.max_id,
312 });
313 }
314 self.max_id = id.0;
315 self.revision = next_revision();
316 }
317
318 /// Look up one entity, decoding it first if it was loaded lazily.
319 pub fn get(&self, id: EntityId) -> Option<&Entity> {
320 self.entities
321 .get(&id)
322 .map(|slot| slot.get(self.source.as_deref()))
323 }
324
325 /// Whether `id` names an entity, without decoding it.
326 pub fn contains(&self, id: EntityId) -> bool {
327 self.entities.contains_key(&id)
328 }
329
330 /// How many entities have been decoded. Equals [`Model::len`] for a
331 /// model built from decoded entities; for a lazily loaded one it counts
332 /// the entities accessed so far.
333 pub fn decoded_len(&self) -> usize {
334 self.entities
335 .values()
336 .filter(|slot| slot.is_decoded())
337 .count()
338 }
339
340 /// Decode every entity now, on up to `threads` threads.
341 ///
342 /// A lazily loaded model decodes on first access, one entity at a time.
343 /// A consumer about to touch most of the model -- a writer, a full
344 /// validation, a geometry pass -- can decode everything up front in
345 /// parallel instead. Idempotent, and a no-op on a decoded model.
346 pub fn decode_all(&self, threads: usize) {
347 let pending: Vec<&Slot> = self
348 .entities
349 .values()
350 .filter(|slot| !slot.is_decoded())
351 .collect();
352 if pending.is_empty() {
353 return;
354 }
355 let source = self.source.as_deref();
356 let threads = threads.clamp(1, pending.len());
357 if threads == 1 {
358 for slot in pending {
359 slot.get(source);
360 }
361 return;
362 }
363 let chunk = pending.len().div_ceil(threads);
364 std::thread::scope(|scope| {
365 for part in pending.chunks(chunk) {
366 scope.spawn(move || {
367 for slot in part {
368 slot.get(source);
369 }
370 });
371 }
372 });
373 }
374
375 /// Number of entities.
376 pub fn len(&self) -> usize {
377 self.entities.len()
378 }
379
380 /// Whether the model holds no entities.
381 pub fn is_empty(&self) -> bool {
382 self.entities.is_empty()
383 }
384
385 /// Entity ids in original file order.
386 pub fn ids(&self) -> impl Iterator<Item = EntityId> + '_ {
387 self.order.iter().copied()
388 }
389
390 /// Entities in original file order.
391 pub fn iter(&self) -> impl Iterator<Item = (EntityId, &Entity)> + '_ {
392 self.order
393 .iter()
394 .filter_map(move |id| self.get(*id).map(|e| (*id, e)))
395 }
396
397 /// Ids of every entity with this exact type name, case-insensitive.
398 ///
399 /// This is an exact-type query and does **not** include subtypes: asking
400 /// for `IfcElement` will not return walls. Subtype queries need the schema,
401 /// which this crate does not depend on. The facade's
402 /// `ifc::ids_of_type_including_subtypes` (feature `schema`) joins the two.
403 pub fn ids_of_type(&self, type_name: &str) -> &[EntityId] {
404 self.by_type
405 .get(&type_name.to_ascii_uppercase())
406 .map(|v| v.as_slice())
407 .unwrap_or(&[])
408 }
409
410 /// Entities with this exact type name.
411 pub fn of_type<'a>(&'a self, type_name: &str) -> impl Iterator<Item = (EntityId, &'a Entity)> {
412 self.ids_of_type(type_name)
413 .iter()
414 .filter_map(move |id| self.get(*id).map(|e| (*id, e)))
415 .collect::<Vec<_>>()
416 .into_iter()
417 }
418
419 /// Every distinct type name present, with its instance count.
420 ///
421 /// Useful as a cheap file summary and as the basis for a coverage report
422 /// of what a given build can and cannot interpret.
423 pub fn type_histogram(&self) -> Vec<(&str, usize)> {
424 let mut v: Vec<_> = self
425 .by_type
426 .iter()
427 .map(|(k, ids)| (k.as_str(), ids.len()))
428 .collect();
429 v.sort_unstable_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
430 v
431 }
432
433 /// Ids that are referenced by some entity but do not exist.
434 ///
435 /// A dangling reference is the most common corruption in real files, and
436 /// it is a structural question, so it belongs here rather than in a
437 /// validation crate.
438 pub fn dangling_references(&self) -> Vec<(EntityId, EntityId)> {
439 let mut out = Vec::new();
440 for (id, entity) in self.iter() {
441 for target in entity.references() {
442 if !self.entities.contains_key(&target) {
443 out.push((id, target));
444 }
445 }
446 }
447 out
448 }
449
450 // --- crate-internal seams for `mutation::edit` -----------------------
451 //
452 // Kept private-to-crate rather than `pub`: an edit that changes
453 // `type_name` must also fix up `by_type`, or `ids_of_type` silently goes
454 // stale. `mutation::edit` is the only module trusted to touch these
455 // fields directly, and it exists precisely to keep that invariant in one
456 // place instead of copied into every editor.
457
458 /// The entity under `id` for editing, decoded first when needed.
459 pub(crate) fn entity_mut(&mut self, id: EntityId) -> Option<&mut Entity> {
460 let source = self.source.clone();
461 Some(self.entities.get_mut(&id)?.get_mut(source.as_deref()))
462 }
463
464 /// Takes the entity under `id` out of storage, decoded; the caller
465 /// fixes up `by_type` and `order`.
466 pub(crate) fn take_entity(&mut self, id: EntityId) -> Option<Entity> {
467 let slot = self.entities.remove(&id)?;
468 Some(slot.into_entity(self.source.as_deref()))
469 }
470
471 pub(crate) fn by_type_mut(&mut self) -> &mut AHashMap<String, Vec<EntityId>> {
472 &mut self.by_type
473 }
474
475 /// Drops `id` from the type-index bucket `key` (already upper-cased),
476 /// and the bucket itself once it is empty: a type no entity has any
477 /// more must not linger in [`Model::type_histogram`] with a count of
478 /// zero, which a model rebuilt from the same entities would not list
479 /// (#106).
480 pub(crate) fn unindex(&mut self, key: &str, id: EntityId) {
481 if let Some(ids) = self.by_type.get_mut(key) {
482 ids.retain(|existing| *existing != id);
483 if ids.is_empty() {
484 self.by_type.remove(key);
485 }
486 }
487 }
488
489 pub(crate) fn order_mut(&mut self) -> &mut Vec<EntityId> {
490 &mut self.order
491 }
492
493 pub(crate) fn derived(&self) -> &Derived {
494 &self.derived
495 }
496
497 pub(crate) fn derived_mut(&mut self) -> &mut Derived {
498 &mut self.derived
499 }
500
501 // --- crate-internal seams for `mutation::{record, step, inverse}` ----
502
503 pub(crate) fn recording_len(&self) -> usize {
504 self.recording.0.len()
505 }
506
507 pub(crate) fn recording_is_empty(&self) -> bool {
508 self.recording.0.is_empty()
509 }
510
511 /// Keeps `step` in the innermost open recording.
512 pub(crate) fn record(&mut self, step: Step) {
513 if let Some(segment) = self.recording.0.last_mut() {
514 segment.steps.push(step);
515 }
516 }
517
518 pub(crate) fn recording_mut(&mut self) -> &mut Vec<crate::mutation::Segment> {
519 &mut self.recording.0
520 }
521
522 pub(crate) fn max_id(&self) -> u64 {
523 self.max_id
524 }
525
526 pub(crate) fn set_max_id(&mut self, max_id: u64) {
527 self.max_id = max_id;
528 }
529
530 /// Only `Model::preview` calls this, after putting back the exact state
531 /// `revision` named.
532 pub(crate) fn restore_revision(&mut self, revision: u64) {
533 self.revision = revision;
534 }
535
536 pub(crate) fn truncate_diagnostics(&mut self, len: usize) {
537 self.diagnostics.truncate(len);
538 }
539
540 pub(crate) fn entities_mut(&mut self) -> &mut AHashMap<EntityId, Slot> {
541 &mut self.entities
542 }
543
544 /// The header without the revision bump or the recording of
545 /// [`Model::header_mut`]; steps apply through it.
546 pub(crate) fn header_raw(&mut self) -> &mut Header {
547 &mut self.header
548 }
549
550 /// Where `id` sits in file order.
551 pub(crate) fn order_position(&self, id: EntityId) -> usize {
552 // From the end: undoing a batch removes what it appended, newest
553 // first, so the entry sits near the end.
554 self.order
555 .iter()
556 .rposition(|existing| *existing == id)
557 .expect("an entity in storage is in file order")
558 }
559
560 /// Where `id` sits in the type-index bucket `key` (already upper-cased).
561 pub(crate) fn bucket_position(&self, key: &str, id: EntityId) -> usize {
562 self.by_type
563 .get(key)
564 .and_then(|ids| ids.iter().rposition(|existing| *existing == id))
565 .expect("an entity in storage is in its type bucket")
566 }
567}