Skip to main content

ifc_lite_processing/symbolic/
mod.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Canonical 2D symbol extraction shared between the HTTP server and the
6//! browser-side WASM bindings (issue #843 follow-up — full parity work).
7//!
8//! Walks an IFC once, extracts every symbolic primitive the renderer
9//! understands (polylines, circles, texts, fill areas, grid axes +
10//! bubbles), and returns pure-Rust serializable types. The browser path
11//! in `rust/wasm-bindings/src/api/symbolic.rs` wraps the result into its
12//! `wasm_bindgen` collection at the FFI boundary; the server path
13//! serializes the same data structures directly via serde.
14//!
15//! Primitive coverage matches the wasm pipeline that ships to production:
16//!
17//! - `IfcPolyline`, `IfcIndexedPolyCurve` → [`SymbolicPolyline`].
18//! - `IfcCircle` → [`SymbolicCircle`] (full circle).
19//! - `IfcEllipse` → [`SymbolicPolyline`] (64-segment tessellation).
20//! - `IfcTrimmedCurve` on `IfcCircle` → [`SymbolicPolyline`] (arc with
21//!   `PLANEANGLEUNIT` scaling, sense agreement, wrap-around). Near-
22//!   collinear arcs (large radius, small sagitta) collapse to a line.
23//! - `IfcCompositeCurve` → recurses into segments.
24//! - `IfcGeometricSet` / `IfcGeometricCurveSet` → recurses into elements.
25//! - `IfcMappedItem` → recurses into the mapped representation with
26//!   `MappingOrigin` + `MappingTarget` transform composition.
27//! - `IfcTextLiteral` / `IfcTextLiteralWithExtent` → [`SymbolicText`]
28//!   with placement composition, `BoxAlignment`, glyph cap height
29//!   derived from the extent box, colour via `IfcStyledItem` →
30//!   `IfcTextStyle`.
31//! - `IfcAnnotationFillArea` → [`SymbolicFillArea`] with outer ring,
32//!   optional hole rings, colour via `IfcStyledItem` → `IfcFillAreaStyle`.
33//! - `IfcGrid` → [`SymbolicPolyline`] (axis lines) + two [`SymbolicText`]
34//!   bubbles per axis end (outline glyph + tag text).
35//!
36//! Coordinate handling matches the wasm pipeline:
37//!
38//! - Per-product `ObjectPlacement` is resolved through the
39//!   `IfcLocalPlacement` chain; symbolic uses a 2D
40//!   translation-plus-rotation accumulation that intentionally diverges
41//!   from the 3D geometry router so floor-plan annotations aren't
42//!   distorted by parent rotations.
43//! - Per-representation `ContextOfItems.WorldCoordinateSystem` is
44//!   composed in when present (Plan reps occasionally use a different
45//!   WCS than Body).
46//! - RTC offset is auto-detected from the first geometry-bearing
47//!   element and subtracted alongside the mesh pipeline.
48//! - The Y-axis is flipped (`y → -y + rtc_z`) to match the renderer's
49//!   section-cut coordinate convention.
50//!
51//! Style resolution:
52//!
53//! - A reverse index from styled-representation-item id to concrete
54//!   style refs is built up-front in O(n), unwrapping the deprecated
55//!   `IfcPresentationStyleAssignment` so downstream resolvers don't
56//!   need to know about it.
57//! - Text colour walks `IfcTextStyle.TextCharacterAppearance` →
58//!   `IfcTextStyleForDefinedFont.Colour` → `IfcColourRgb`.
59//! - Fill colour walks `IfcFillAreaStyle.FillStyles` → first
60//!   `IfcColourRgb`; hatching / tile fills are recognised but use a
61//!   default fill colour.
62
63
64use ifc_lite_core::{build_entity_index, EntityDecoder, EntityScanner, IfcType};
65
66mod color;
67mod fill;
68mod grid;
69mod items;
70mod primitives;
71mod text;
72mod transform;
73mod trimmed_curve;
74
75pub use primitives::{
76    SymbolicCircle, SymbolicData, SymbolicFillArea, SymbolicGridAxis, SymbolicPolyline, SymbolicText,
77};
78
79use color::build_styled_item_index;
80use grid::extract_grid;
81use items::extract_symbolic_item;
82use transform::{compose_transforms, parse_axis2_placement_2d, resolve_object_placement, Transform2D};
83
84// ────────────────────────────────────────────────────────────────────────────
85// Top-level extraction. Mirror of the wasm `parse_symbolic_representations`
86// scanner loop. Both paths feed the same `extract_*` helpers below so the
87// server and browser produce bit-identical symbol streams.
88// ────────────────────────────────────────────────────────────────────────────
89
90/// Scan an IFC file for `IfcGrid` and any product carrying a Plan /
91/// Annotation / FootPrint / Axis representation, and return the full
92/// symbolic primitive collection. Pure-Rust (no `wasm_bindgen`), so it
93/// works inside the HTTP server.
94pub fn extract_symbolic_data<T>(content: &T) -> SymbolicData
95where
96    T: AsRef<[u8]> + ?Sized,
97{
98    let content = content.as_ref();
99    let entity_index = build_entity_index(content);
100    let mut decoder = EntityDecoder::with_index(content, entity_index);
101
102    // Reuse the geometry router for both unit-scale and the RTC offset.
103    let router = ifc_lite_geometry::GeometryRouter::with_units(content, &mut decoder);
104    let unit_scale = router.unit_scale() as f32;
105
106    // RTC offset detection matches the wasm path so the symbolic stream
107    // aligns with the mesh stream. The threshold (>10 km) is empirical —
108    // anything smaller is local-coord territory where RTC subtraction
109    // would shift things off-screen.
110    let rtc_offset = router.detect_rtc_offset_from_first_element(content, &mut decoder);
111    let needs_rtc = rtc_offset.0.abs() > 10_000.0
112        || rtc_offset.1.abs() > 10_000.0
113        || rtc_offset.2.abs() > 10_000.0;
114    let rtc_x = if needs_rtc { rtc_offset.0 as f32 } else { 0.0 };
115    let rtc_z = if needs_rtc { rtc_offset.2 as f32 } else { 0.0 };
116
117    // Pre-pass: build a reverse index from "styled representation-item id"
118    // to "list of style refs". Walked once at parse start (O(n)) so per-
119    // item colour lookup is O(1) later. See `resolve_color_via_styles()`
120    // for the chain (deprecated IfcPresentationStyleAssignment unwrap +
121    // IfcFillAreaStyle → IfcColourRgb).
122    let styled_items = build_styled_item_index(content, &mut decoder);
123
124    let mut out = SymbolicData::default();
125    let mut scanner = EntityScanner::new(content);
126
127    while let Some((id, type_name, start, end)) = scanner.next_entity() {
128        let is_grid = type_name == "IFCGRID";
129        if !is_grid && !ifc_lite_core::has_geometry_by_name(type_name) {
130            // IfcGrid isn't in `has_geometry_by_name` (it's not a building
131            // element) but carries axis curves that we render as symbolic
132            // lines + bubbles + tags.
133            continue;
134        }
135        let Ok(entity) = decoder.decode_at_with_id(id, start, end) else {
136            continue;
137        };
138
139        if is_grid {
140            let grid_transform = resolve_object_placement(&entity, &mut decoder, unit_scale);
141            extract_grid(
142                &entity,
143                id,
144                &mut decoder,
145                unit_scale,
146                &grid_transform,
147                rtc_x,
148                rtc_z,
149                &mut out,
150            );
151            continue;
152        }
153
154        // Standard representation walk: IfcProductDefinitionShape → Plan /
155        // Annotation / FootPrint / Axis IfcShapeRepresentation → items.
156        let Some(representation_attr) = entity.get(6) else {
157            continue;
158        };
159        if representation_attr.is_null() {
160            continue;
161        }
162        let Ok(Some(representation)) = decoder.resolve_ref(representation_attr) else {
163            continue;
164        };
165        let Some(reps_attr) = representation.get(2) else {
166            continue;
167        };
168        let Ok(representations) = decoder.resolve_ref_list(reps_attr) else {
169            continue;
170        };
171
172        let ifc_type_name = entity.ifc_type.name().to_string();
173
174        for shape_rep in representations {
175            if shape_rep.ifc_type != IfcType::IfcShapeRepresentation {
176                continue;
177            }
178            let rep_identifier = shape_rep
179                .get(1)
180                .and_then(|a| a.as_string())
181                .unwrap_or("")
182                .to_string();
183            if !matches!(
184                rep_identifier.as_str(),
185                "Plan" | "Annotation" | "FootPrint" | "Axis"
186            ) {
187                continue;
188            }
189
190            // ObjectPlacement transform for this entity (translations
191            // accumulated directly, rotations accumulated to orient symbols).
192            let placement_transform = resolve_object_placement(&entity, &mut decoder, unit_scale);
193
194            // ContextOfItems WCS: some Plan reps use a different coord
195            // system than Body. Compose it in when present and non-trivial.
196            // `ContextOfItems` (IfcRepresentation attr 0) and
197            // `WorldCoordinateSystem` (IfcGeometricRepresentationContext
198            // attr 4) are both MANDATORY, so a dangling ref or absent
199            // attribute is malformed data, not a legitimate default —
200            // `unresolved()` per #2352's convention. A resolved
201            // `IfcGeometricRepresentationSubContext`, in contrast, derives
202            // its WCS from `ParentContext` and legitimately does not store
203            // one inline, so it alone stays `identity()`.
204            let context_transform = match shape_rep.get_ref(0) {
205                Some(context_ref) => match decoder.decode_by_id(context_ref) {
206                    Ok(context) if context.ifc_type == IfcType::IfcGeometricRepresentationContext => {
207                        match context.get_ref(4) {
208                            Some(wcs_ref) => match decoder.decode_by_id(wcs_ref) {
209                                Ok(wcs) => parse_axis2_placement_2d(&wcs, &mut decoder, unit_scale),
210                                Err(_) => Transform2D::unresolved(),
211                            },
212                            None => Transform2D::unresolved(),
213                        }
214                    }
215                    // SubContext inherits WCS from ParentContext — legitimately
216                    // has none inline (the wasm pipeline does the same).
217                    Ok(context) if context.ifc_type == IfcType::IfcGeometricRepresentationSubContext => {
218                        Transform2D::identity()
219                    }
220                    // Dangling context_ref, or a ref resolving to neither
221                    // Context nor SubContext: malformed data.
222                    _ => Transform2D::unresolved(),
223                },
224                None => Transform2D::unresolved(),
225            };
226            let combined_transform = if context_transform.tx.abs() > 0.001
227                || context_transform.ty.abs() > 0.001
228                || context_transform.tz.abs() > 0.001
229                || (context_transform.m00 - 1.0).abs() > 0.0001
230                || context_transform.m01.abs() > 0.0001
231                || context_transform.m10.abs() > 0.0001
232                || (context_transform.m11 - 1.0).abs() > 0.0001
233                || context_transform.tz.is_nan()
234            {
235                compose_transforms(&context_transform, &placement_transform)
236            } else {
237                placement_transform
238            };
239
240            let Some(items_attr) = shape_rep.get(3) else {
241                continue;
242            };
243            let Ok(items) = decoder.resolve_ref_list(items_attr) else {
244                continue;
245            };
246            for item in items {
247                extract_symbolic_item(
248                    &item,
249                    &mut decoder,
250                    id,
251                    &ifc_type_name,
252                    &rep_identifier,
253                    unit_scale,
254                    &combined_transform,
255                    rtc_x,
256                    rtc_z,
257                    &styled_items,
258                    &mut out,
259                );
260            }
261        }
262    }
263
264    out
265}