Skip to main content

ifc_lite_processing/
shard_classes.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//! Per-record prepass classification for the sharded scan (split from
6//! `parallel_scan.rs` — the byte-identical shard/stitch protocol lives there;
7//! this module owns the class codes and the classified scan variant the
8//! browser's sharded pre-pass consumes).
9
10use crate::parallel_scan::ShardRecords;
11use ifc_lite_core::EntityScanner;
12
13/// Per-record prepass class emitted by [`scan_shard_classified`].
14///
15/// Only the codes a downstream consumer needs are defined; everything else is
16/// [`PREPASS_CLASS_NONE`]. Classification happens AT SCAN TIME from the same
17/// `type_name` string the serial pre-pass matches on, so a consumer that
18/// filters records by class reproduces the serial pre-pass's span collection
19/// byte-for-byte (same keyword compare, same file order).
20pub const PREPASS_CLASS_NONE: u8 = 0;
21/// `IFCSTYLEDITEM` — the styled-item spans the pre-pass resolver classifies
22/// into orphan (material appearance) vs geometry-attached styles.
23pub const PREPASS_CLASS_STYLED_ITEM: u8 = 4;
24/// `IFCINDEXEDCOLOURMAP` (#663/#858).
25pub const PREPASS_CLASS_INDEXED_COLOUR_MAP: u8 = 5;
26/// `IFCMATERIALDEFINITIONREPRESENTATION` (#407).
27pub const PREPASS_CLASS_MATERIAL_DEF_REPR: u8 = 6;
28/// `IFCRELASSOCIATESMATERIAL` (#407).
29pub const PREPASS_CLASS_REL_ASSOCIATES_MATERIAL: u8 = 7;
30/// `IFCRELVOIDSELEMENT`.
31pub const PREPASS_CLASS_REL_VOIDS: u8 = 8;
32/// `IFCRELFILLSELEMENT`.
33pub const PREPASS_CLASS_REL_FILLS: u8 = 9;
34/// `IFCRELAGGREGATES`.
35pub const PREPASS_CLASS_REL_AGGREGATES: u8 = 10;
36/// `IFCPROJECT`.
37pub const PREPASS_CLASS_PROJECT: u8 = 2;
38/// `IFCSITE` (also a geometry job — the pre-pass buffers it like one).
39pub const PREPASS_CLASS_SITE: u8 = 3;
40/// `IFCMATERIALLAYERSET` / `IFCMATERIALLAYERSETUSAGE` (arms the layer index).
41pub const PREPASS_CLASS_MATERIAL_LAYER_SET: u8 = 13;
42/// FLAG bit: geometry-bearing entity (`has_geometry_by_name`) — a pre-pass
43/// geometry job. Composes with the named codes' nibble range (2..=13) and
44/// with [`PREPASS_CLASS_FLAG_TYPE_CANDIDATE`].
45pub const PREPASS_CLASS_FLAG_GEOMETRY_JOB: u8 = 0x80;
46/// FLAG bit: `IfcTypeProduct` subtype candidate (name ends TYPE/STYLE) for the
47/// #957 orphan type-geometry pass.
48pub const PREPASS_CLASS_FLAG_TYPE_CANDIDATE: u8 = 0x40;
49/// `IFCMAPPEDITEM` (#957/#1623 repmap plans).
50pub const PREPASS_CLASS_MAPPED_ITEM: u8 = 11;
51/// `IFCRELDEFINESBYTYPE` (#957 instantiated-type ids).
52pub const PREPASS_CLASS_REL_DEFINES_BY_TYPE: u8 = 12;
53/// Mask extracting the named-arm code from a class byte (drops the flag bits).
54pub const PREPASS_CLASS_CODE_MASK: u8 = 0x3F;
55
56/// [`scan_shard`] plus a parallel per-record class column (see the
57/// `PREPASS_CLASS_*` codes). Same records, same handoff; the class byte lets
58/// the browser host extract pre-pass span lists (today: styled items) from the
59/// stitched shard columns WITHOUT waiting for the serial pre-pass scan.
60pub fn scan_shard_classified(
61    content: &[u8],
62    range_start: usize,
63    range_end: usize,
64) -> (ShardRecords, Vec<u8>, Option<usize>) {
65    let mut scanner = if range_start == 0 {
66        EntityScanner::new(content)
67    } else {
68        EntityScanner::new_at(content, range_start)
69    };
70    let mut records = Vec::new();
71    let mut classes = Vec::new();
72    let mut handoff = None;
73    while let Some((id, type_name, start, entity_end)) = scanner.next_entity() {
74        if start >= range_end {
75            handoff = Some(start);
76            break;
77        }
78        records.push((id, start, entity_end));
79        classes.push(classify_type_name_with_content(
80            type_name,
81            &content[start..entity_end],
82        ));
83    }
84    (records, classes, handoff)
85}
86
87/// [`classify_type_name`] plus the #1910 instance-level exception: a spatial
88/// container `has_geometry_by_name` blocks by name (`IfcBuilding` et al.) is
89/// still classified as a geometry job when THIS instance's `Representation`
90/// attribute (index 6) is exceptionally non-null -- mirrors the identical
91/// exception applied to the serial scan loop
92/// (`rust/wasm-bindings/src/api/gpu_meshes/prepass.rs`) and the streaming
93/// processor (`rust/processing/src/processor/mod.rs`), so all three
94/// discovery paths agree on what counts as geometry. `entity_bytes` is the
95/// full `#id=KEYWORD(...)` span for this record.
96pub fn classify_type_name_with_content(type_name: &str, entity_bytes: &[u8]) -> u8 {
97    let mut class = classify_type_name(type_name);
98    if class & PREPASS_CLASS_FLAG_GEOMETRY_JOB == 0
99        && ifc_lite_core::is_representationless_spatial_container_by_name(type_name)
100        && ifc_lite_core::nth_attribute_is_present(entity_bytes, 6)
101    {
102        class |= PREPASS_CLASS_FLAG_GEOMETRY_JOB;
103    }
104    class
105}
106
107/// Classify a scanned STEP keyword into the prepass class byte: a named-arm
108/// code for the exact keywords the serial pre-pass matches, plus the
109/// geometry-job / type-candidate FLAG bits from the same helpers it calls
110/// (`has_geometry_by_name`, `IfcType::is_subtype_of`). Byte-identical span
111/// collection and job discovery follow from using the identical predicates at
112/// scan time.
113///
114/// Deliberately name-only (cannot see the entity bytes) -- the #1910
115/// instance-level exception lives one layer up, in
116/// [`classify_type_name_with_content`], which is what [`scan_shard_classified`]
117/// actually calls. Kept as a separate function (rather than inlining) so
118/// every other named/flag arm here stays byte-identical to what it was
119/// before #1910 -- the only new code path is the explicit OR-in above.
120pub fn classify_type_name(type_name: &str) -> u8 {
121    use ifc_lite_core::{has_geometry_by_name, type_product_ifc_type};
122    let named = match type_name {
123        "IFCPROJECT" => PREPASS_CLASS_PROJECT,
124        "IFCSITE" => return PREPASS_CLASS_SITE, // site is job + site-record; flags implied
125        "IFCSTYLEDITEM" => PREPASS_CLASS_STYLED_ITEM,
126        "IFCINDEXEDCOLOURMAP" => PREPASS_CLASS_INDEXED_COLOUR_MAP,
127        "IFCMATERIALDEFINITIONREPRESENTATION" => PREPASS_CLASS_MATERIAL_DEF_REPR,
128        "IFCRELASSOCIATESMATERIAL" => PREPASS_CLASS_REL_ASSOCIATES_MATERIAL,
129        "IFCRELVOIDSELEMENT" => PREPASS_CLASS_REL_VOIDS,
130        "IFCRELFILLSELEMENT" => PREPASS_CLASS_REL_FILLS,
131        "IFCRELAGGREGATES" => PREPASS_CLASS_REL_AGGREGATES,
132        "IFCMAPPEDITEM" => PREPASS_CLASS_MAPPED_ITEM,
133        "IFCRELDEFINESBYTYPE" => PREPASS_CLASS_REL_DEFINES_BY_TYPE,
134        "IFCMATERIALLAYERSET" | "IFCMATERIALLAYERSETUSAGE" => PREPASS_CLASS_MATERIAL_LAYER_SET,
135        _ => PREPASS_CLASS_NONE,
136    };
137    if named != PREPASS_CLASS_NONE {
138        // The named keywords are mutually exclusive with the flag predicates in
139        // the serial match (its arms return before the `_` arm runs them).
140        return named;
141    }
142    let mut class = PREPASS_CLASS_NONE;
143    if type_product_ifc_type(type_name).is_some() {
144        class |= PREPASS_CLASS_FLAG_TYPE_CANDIDATE;
145    }
146    if has_geometry_by_name(type_name) {
147        class |= PREPASS_CLASS_FLAG_GEOMETRY_JOB;
148    }
149    class
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155
156    /// The type-candidate check ORs two independent suffix tests
157    /// (`ends_with("TYPE")` and `ends_with("STYLE")`) before confirming the
158    /// resolved `IfcType` is a subtype of `IfcTypeProduct`. Pin that the TYPE
159    /// arm alone is load-bearing: `IFCWALLTYPE` (a real `IfcTypeProduct`
160    /// subtype) must set the flag even though it does NOT end in "STYLE", so a
161    /// mutation that drops the `ends_with("TYPE")` disjunct and keeps only the
162    /// STYLE check would misclassify it and lose #957's orphan type-geometry
163    /// pass for every walltype-shaped keyword.
164    #[test]
165    fn type_suffix_sets_type_candidate_flag() {
166        let class = classify_type_name("IFCWALLTYPE");
167        assert_eq!(
168            class & PREPASS_CLASS_FLAG_TYPE_CANDIDATE,
169            PREPASS_CLASS_FLAG_TYPE_CANDIDATE,
170            "IFCWALLTYPE is an IfcTypeProduct subtype ending in TYPE, not STYLE — \
171             it must set the type-candidate flag via the TYPE arm alone"
172        );
173    }
174
175    /// The STYLE arm is deliberately distinct from the TYPE arm: a keyword
176    /// ending in "STYLE" that is NOT an `IfcTypeProduct` subtype (`IFCSURFACESTYLE`
177    /// is an `IfcPresentationStyle`) must NOT set the flag. Combined with
178    /// `type_suffix_sets_type_candidate_flag` above, this pins that the two
179    /// suffix checks gate genuinely different keyword sets rather than one
180    /// subsuming the other.
181    #[test]
182    fn style_suffix_without_type_product_subtype_does_not_set_flag() {
183        let class = classify_type_name("IFCSURFACESTYLE");
184        assert_eq!(
185            class & PREPASS_CLASS_FLAG_TYPE_CANDIDATE,
186            0,
187            "IFCSURFACESTYLE is not an IfcTypeProduct subtype, so the type-candidate \
188             flag must stay clear even though the name ends in STYLE"
189        );
190    }
191
192    /// Pins every named-arm keyword to its own distinct class code. The two
193    /// tests above cover only the TYPE/STYLE suffix flag; nothing asserted
194    /// the named-arm lookup table itself, so this is a textbook lookup-table
195    /// vacuity: any two of the 12 named arms could be swapped
196    /// (e.g. `IFCRELVOIDSELEMENT` ↔ `IFCRELFILLSELEMENT`) and the full suite
197    /// stayed green. A wrong class here means the sharded pre-pass hands the
198    /// browser host the wrong span list for a record (voids treated as
199    /// fills, materials treated as aggregates, etc.), silently diverging
200    /// from the serial pre-pass it must reproduce byte-for-byte.
201    #[test]
202    fn classify_type_name_pins_every_named_arm_to_a_distinct_code() {
203        let cases = [
204            ("IFCPROJECT", PREPASS_CLASS_PROJECT),
205            ("IFCSITE", PREPASS_CLASS_SITE),
206            ("IFCSTYLEDITEM", PREPASS_CLASS_STYLED_ITEM),
207            ("IFCINDEXEDCOLOURMAP", PREPASS_CLASS_INDEXED_COLOUR_MAP),
208            ("IFCMATERIALDEFINITIONREPRESENTATION", PREPASS_CLASS_MATERIAL_DEF_REPR),
209            ("IFCRELASSOCIATESMATERIAL", PREPASS_CLASS_REL_ASSOCIATES_MATERIAL),
210            ("IFCRELVOIDSELEMENT", PREPASS_CLASS_REL_VOIDS),
211            ("IFCRELFILLSELEMENT", PREPASS_CLASS_REL_FILLS),
212            ("IFCRELAGGREGATES", PREPASS_CLASS_REL_AGGREGATES),
213            ("IFCMAPPEDITEM", PREPASS_CLASS_MAPPED_ITEM),
214            ("IFCRELDEFINESBYTYPE", PREPASS_CLASS_REL_DEFINES_BY_TYPE),
215            ("IFCMATERIALLAYERSET", PREPASS_CLASS_MATERIAL_LAYER_SET),
216            ("IFCMATERIALLAYERSETUSAGE", PREPASS_CLASS_MATERIAL_LAYER_SET),
217        ];
218        for (keyword, expected) in cases {
219            assert_eq!(
220                classify_type_name(keyword),
221                expected,
222                "{keyword} classified as {} not {expected}",
223                classify_type_name(keyword)
224            );
225        }
226
227        // Golden totals: every expected code above (except the two that
228        // intentionally share MATERIAL_LAYER_SET) is pairwise distinct, so a
229        // swap between any two arms is caught by the per-case assertion —
230        // not just an aggregate that a swap could still satisfy.
231        let distinct_codes: std::collections::HashSet<u8> =
232            cases.iter().map(|(_, c)| *c).collect();
233        assert_eq!(distinct_codes.len(), 12, "expected 12 distinct codes across 13 keywords (2 share MATERIAL_LAYER_SET)");
234
235        // An unrecognised keyword with no geometry/type-candidate signal is NONE.
236        assert_eq!(classify_type_name("IFCUNKNOWNTHING"), PREPASS_CLASS_NONE);
237    }
238}