ifc-lite-geometry 9.4.0

Geometry processing and mesh generation for IFC models
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

//! Split out of `router/diagnostics.rs` (module-size ratchet, #C1): the
//! `GeometryDiagnostics` contract tests, including the serde camelCase
//! key-stability guard that pins the JSON shape crossing the wasm boundary.

use super::*;
use crate::diagnostics::{BoolFailure, BoolFailureReason, BoolOp};
use crate::rect_fast::RectFastStats;

#[test]
fn aggregate_empty_is_all_zero() {
    let d = aggregate_diagnostics(
        ClassificationStats::default(),
        &FxHashMap::default(),
        &FxHashMap::default(),
        RectFastStats::default(),
        16,
        0,
        &FxHashMap::default(),
    );
    assert_eq!(d.total_csg_failures, 0);
    assert_eq!(d.total_unsupported_items, 0);
    assert!(d.unsupported_items_by_type.is_empty());
    assert_eq!(d.products_with_failures, 0);
    assert!(d.failures_by_reason.is_empty());
    assert!(d.worst_hosts.is_empty());
    assert!(!d.has_issues());
}

#[test]
fn aggregate_summarizes_failures_hosts_classification_and_silent_noops() {
    let mut csg: FxHashMap<u32, Vec<BoolFailure>> = FxHashMap::default();
    csg.insert(
        5,
        vec![BoolFailure::new(BoolOp::Difference, BoolFailureReason::DifferenceEmptiedHost)],
    );
    csg.insert(
        7,
        vec![
            BoolFailure::new(BoolOp::Difference, BoolFailureReason::DifferenceEmptiedHost),
            BoolFailure::new(BoolOp::Difference, BoolFailureReason::KernelOutputInvalid),
        ],
    );

    let mut hosts: FxHashMap<u32, HostOpeningDiagnostic> = FxHashMap::default();
    // A FAILED host (also unchanged tris) — must NOT be counted as a silent
    // no-op because it recorded an explicit failure.
    hosts.insert(
        7,
        HostOpeningDiagnostic {
            host_type: "IfcWallStandardCase".into(),
            csg_failure_count: 2,
            first_failure_label: Some("DifferenceEmptiedHost".into()),
            tris_before: Some(120),
            tris_after: Some(120),
            rect_boxes_processed: 1,
            host_bounds: Some(((0.0, 0.0, 0.0), (1.0, 2.0, 3.0))),
            ..Default::default()
        },
    );
    // A TRUE silent no-op host: rect cutters ran, tris unchanged, NO failure.
    hosts.insert(
        9,
        HostOpeningDiagnostic {
            host_type: "IfcSlab".into(),
            csg_failure_count: 0,
            tris_before: Some(50),
            tris_after: Some(50),
            rect_boxes_processed: 2,
            ..Default::default()
        },
    );

    let cls = ClassificationStats { rectangular: 3, diagonal: 1, non_rectangular: 0 };
    let rf = RectFastStats { fired: 2, openings_cut: 4, ..Default::default() };

    let d = aggregate_diagnostics(cls, &csg, &hosts, rf, 16, 0, &FxHashMap::default());
    assert_eq!(d.total_csg_failures, 3);
    assert_eq!(d.products_with_failures, 2);
    assert_eq!(d.hosts_with_openings, 2);
    assert_eq!(d.classification.total, 4);
    assert_eq!(d.classification.rectangular, 3);
    // Only host 9 (clean, unchanged tris) counts; host 7 failed, so it is NOT
    // a silent no-op.
    assert_eq!(d.silent_no_ops, 1);
    assert_eq!(d.rect_fast.fired, 2);
    // Sorted desc by count: DifferenceEmptiedHost=2 then KernelOutputInvalid=1.
    assert_eq!(d.failures_by_reason[0].reason, "DifferenceEmptiedHost");
    assert_eq!(d.failures_by_reason[0].count, 2);
    assert_eq!(d.worst_hosts.len(), 1);
    assert_eq!(d.worst_hosts[0].product_id, 7);
    assert_eq!(d.worst_hosts[0].csg_failures, 2);
    // bbox/triangle_count (#C1) thread through from the host diagnostic's
    // captured cut effect (tris_after wins over tris_before when both are set).
    let bbox = d.worst_hosts[0].bbox.expect("host_bounds captured");
    assert_eq!(bbox.min, [0.0, 0.0, 0.0]);
    assert_eq!(bbox.max, [1.0, 2.0, 3.0]);
    assert_eq!(d.worst_hosts[0].triangle_count, Some(120));
    assert!(d.has_issues());
}

#[test]
fn worst_host_triangle_count_falls_back_to_tris_before_when_no_cut_ran() {
    // A host that failed before any void cut effect was recorded (tris_after
    // never set) should still report tris_before — the un-cut mesh is what
    // actually renders in that case.
    let mut hosts: FxHashMap<u32, HostOpeningDiagnostic> = FxHashMap::default();
    hosts.insert(
        3,
        HostOpeningDiagnostic {
            host_type: "IfcSlab".into(),
            csg_failure_count: 1,
            first_failure_label: Some("EmptyOperand".into()),
            tris_before: Some(80),
            tris_after: None,
            ..Default::default()
        },
    );
    let mut csg: FxHashMap<u32, Vec<BoolFailure>> = FxHashMap::default();
    csg.insert(3, vec![BoolFailure::new(BoolOp::Difference, BoolFailureReason::EmptyOperand)]);
    let d = aggregate_diagnostics(
        ClassificationStats::default(),
        &csg,
        &hosts,
        RectFastStats::default(),
        16,
        0,
        &FxHashMap::default(),
    );
    assert_eq!(d.worst_hosts[0].triangle_count, Some(80));
    assert!(d.worst_hosts[0].bbox.is_none());
}

#[test]
fn serializes_camelcase_keys_matching_the_ts_contract() {
    // Guard the serde rename_all against drift from the @ifc-lite/geometry
    // GeometryDiagnostics TS interface. The wasm getter uses the same renames
    // via serde-wasm-bindgen, so this JSON key set is what crosses to JS.
    let mut hosts: FxHashMap<u32, HostOpeningDiagnostic> = FxHashMap::default();
    hosts.insert(
        7,
        HostOpeningDiagnostic {
            host_type: "IfcWall".into(),
            csg_failure_count: 1,
            first_failure_label: Some("KernelError".into()),
            tris_before: Some(40),
            tris_after: Some(36),
            host_bounds: Some(((-1.0, -1.0, 0.0), (1.0, 1.0, 3.0))),
            ..Default::default()
        },
    );
    let mut csg: FxHashMap<u32, Vec<BoolFailure>> = FxHashMap::default();
    csg.insert(7, vec![BoolFailure::new(BoolOp::Difference, BoolFailureReason::KernelOutputInvalid)]);
    let mut unsupported: FxHashMap<String, u64> = FxHashMap::default();
    unsupported.insert("IfcSectionedSpine".to_string(), 3);
    let d = aggregate_diagnostics(
        ClassificationStats { rectangular: 1, ..Default::default() },
        &csg,
        &hosts,
        RectFastStats::default(),
        16,
        0,
        &unsupported,
    );
    assert_eq!(d.total_unsupported_items, 3);
    assert_eq!(d.unsupported_items_by_type[0].reason, "IfcSectionedSpine");
    assert_eq!(d.unsupported_items_by_type[0].count, 3);
    let v = serde_json::to_value(&d).expect("serializes");
    for key in [
        "totalCsgFailures",
        "productsWithFailures",
        "hostsWithOpenings",
        "classification",
        "failuresByReason",
        "silentNoOps",
        "rectFast",
        "worstHosts",
        "oversizedRefDrops",
        "totalUnsupportedItems",
        "unsupportedItemsByType",
    ] {
        assert!(v.get(key).is_some(), "missing top-level key {key}");
    }
    assert!(v["classification"].get("nonRectangular").is_some());
    assert!(v["rectFast"].get("deferHostNotBox").is_some());
    let wh = &v["worstHosts"][0];
    for key in [
        "productId",
        "ifcType",
        "openings",
        "csgFailures",
        "firstFailureLabel",
        "bbox",
        "triangleCount",
    ] {
        assert!(wh.get(key).is_some(), "missing worstHosts key {key}");
    }
    assert!(wh["bbox"].get("min").is_some() && wh["bbox"].get("max").is_some());
    let fr = &v["failuresByReason"][0];
    assert!(fr.get("reason").is_some() && fr.get("count").is_some());
}

/// RED for issue #3752: `oversized_ref_drops` must pass through
/// `aggregate_diagnostics` unchanged and must NOT be swallowed by
/// `is_empty`'s all-zero gate — a model whose ONLY diagnostic-worthy event is
/// a refused oversized reference must still be surfaced, not suppressed.
#[test]
fn oversized_ref_drops_passes_through_and_defeats_is_empty() {
    let d = aggregate_diagnostics(
        ClassificationStats::default(),
        &FxHashMap::default(),
        &FxHashMap::default(),
        RectFastStats::default(),
        16,
        3,
        &FxHashMap::default(),
    );
    assert_eq!(d.oversized_ref_drops, 3);
    assert!(
        !d.is_empty(),
        "a nonzero oversized_ref_drops must defeat is_empty so the diagnostics object is attached"
    );
}

/// Control: zero refusals is genuinely empty (all other fields already zero).
#[test]
fn zero_oversized_ref_drops_stays_empty() {
    let d = aggregate_diagnostics(
        ClassificationStats::default(),
        &FxHashMap::default(),
        &FxHashMap::default(),
        RectFastStats::default(),
        16,
        0,
        &FxHashMap::default(),
    );
    assert!(d.is_empty());
}

#[test]
fn schema_version_round_trips_and_defaults() {
    let d = GeometryDiagnostics::default();
    assert_eq!(d.schema_version, GEOMETRY_DIAGNOSTICS_SCHEMA_VERSION);
    let json = serde_json::to_string(&d).unwrap();
    assert!(json.contains("\"schemaVersion\":3"), "serialized unconditionally: {json}");
    let back: GeometryDiagnostics = serde_json::from_str(&json).unwrap();
    assert_eq!(back.schema_version, GEOMETRY_DIAGNOSTICS_SCHEMA_VERSION);
    // A pre-versioned producer (field absent) deserializes to 0, distinguishable.
    let legacy: GeometryDiagnostics =
        serde_json::from_str(&json.replace("\"schemaVersion\":3,", "")).unwrap();
    assert_eq!(legacy.schema_version, 0);
}

/// A `WorstHost` field the TypeScript mirrors declare as `field?: T` must be
/// ABSENT from the JSON when it is `None`, not present as an explicit `null`.
///
/// The two are different wire states and `?:` means absent: an HTTP consumer
/// doing `if (h.triangleCount !== undefined) h.triangleCount.toLocaleString()`
/// typechecks and then throws on a `null`. The wasm boundary hid this because
/// `serde_wasm_bindgen` writes `None` as `undefined`; `serde_json`, which is
/// what the server response goes through, writes it as `null`.
///
/// Both directions are asserted, so "always skip" fails this test too.
#[test]
fn worst_host_optional_fields_are_omitted_when_none_and_present_when_some() {
    let none = WorstHost {
        product_id: 1,
        ifc_type: "IfcWall".to_string(),
        openings: 2,
        csg_failures: 1,
        first_failure_label: None,
        bbox: None,
        triangle_count: None,
    };
    let obj = serde_json::to_value(&none).unwrap();
    let obj = obj.as_object().expect("serializes to a JSON object");
    for key in ["firstFailureLabel", "bbox", "triangleCount"] {
        assert!(
            !obj.contains_key(key),
            "`{key}` must be absent when None, not null: {obj:?}"
        );
    }

    let some = WorstHost {
        first_failure_label: Some("difference_emptied_host".to_string()),
        bbox: Some(HostBbox { min: [0.0, 0.0, 0.0], max: [1.0, 2.0, 3.0] }),
        triangle_count: Some(42),
        ..none
    };
    let obj = serde_json::to_value(&some).unwrap();
    let obj = obj.as_object().expect("serializes to a JSON object");
    for key in ["firstFailureLabel", "bbox", "triangleCount"] {
        assert!(
            obj.contains_key(key),
            "`{key}` must be present when Some: {obj:?}"
        );
    }
    assert_eq!(obj["triangleCount"], serde_json::json!(42));

    // A legacy payload that still writes explicit nulls stays readable.
    let legacy = serde_json::json!({
        "productId": 1, "ifcType": "IfcWall", "openings": 2, "csgFailures": 1,
        "firstFailureLabel": null, "bbox": null, "triangleCount": null,
    });
    let back: WorstHost = serde_json::from_value(legacy).unwrap();
    assert!(back.bbox.is_none() && back.triangle_count.is_none());
}

#[test]
fn the_unattributed_bucket_counts_in_the_totals_but_is_not_a_product() {
    // One real host plus one record swept in with no owner (a boolean
    // processor's own log, or PENDING_MAPPED_BOOL_FAILURES). Id 0 is not a
    // valid express id, so reporting it as a product would tell the user
    // "2 products failed" for a model where one product failed and one failure
    // has an unknown owner.
    let mut csg: FxHashMap<u32, Vec<BoolFailure>> = FxHashMap::default();
    csg.insert(
        42,
        vec![BoolFailure::new(BoolOp::Difference, BoolFailureReason::DifferenceEmptiedHost)],
    );
    csg.insert(
        UNATTRIBUTED_PRODUCT_ID,
        vec![BoolFailure::new(
            BoolOp::Unknown,
            BoolFailureReason::UnsupportedOperand("IfcSectionedSpine".to_string()),
        )],
    );

    let d = aggregate_diagnostics(
        ClassificationStats::default(),
        &csg,
        &FxHashMap::default(),
        RectFastStats::default(),
        16,
        0,
        &FxHashMap::default(),
    );

    assert_eq!(d.products_with_failures, 1, "the synthetic bucket is not a product");
    assert_eq!(d.total_csg_failures, 2, "but its records still count as failures");
    let reasons: Vec<&str> = d.failures_by_reason.iter().map(|r| r.reason.as_str()).collect();
    assert!(
        reasons.contains(&"UnsupportedOperand"),
        "and still appear in the reason breakdown: {reasons:?}"
    );
}

#[test]
fn an_unattributed_only_pass_reports_zero_products_and_still_has_issues() {
    // The boundary the count must not round the wrong way: failures exist, no
    // product owns them. `has_issues` must still fire, or the pass would look
    // clean to every caller that gates on it.
    let mut csg: FxHashMap<u32, Vec<BoolFailure>> = FxHashMap::default();
    csg.insert(
        UNATTRIBUTED_PRODUCT_ID,
        vec![BoolFailure::new(BoolOp::Union, BoolFailureReason::EmptyOperand)],
    );
    let d = aggregate_diagnostics(
        ClassificationStats::default(),
        &csg,
        &FxHashMap::default(),
        RectFastStats::default(),
        16,
        0,
        &FxHashMap::default(),
    );
    assert_eq!(d.products_with_failures, 0);
    assert_eq!(d.total_csg_failures, 1);
    assert!(d.has_issues(), "an unowned failure is still a failure");
    assert!(!d.is_empty(), "and must not be skipped as an empty diagnostic");
}

/// RED for the #3691 counter, mirroring #3752's pair above: a model whose ONLY
/// diagnostic-worthy event is a dropped representation item must still be
/// surfaced. `is_empty()` gates whether `processor/mod.rs` attaches the
/// diagnostics object at all — `(!diag.is_empty()).then_some(diag)` — so
/// deleting the `total_unsupported_items == 0` arm does not merely loosen a
/// predicate, it throws the whole object away on exactly the models this
/// counter was added for. Nothing failed when that arm was deleted.
#[test]
fn unsupported_items_pass_through_and_defeat_is_empty() {
    let mut unsupported: FxHashMap<String, u64> = FxHashMap::default();
    unsupported.insert("IfcGeometricSet".to_string(), 2);
    let d = aggregate_diagnostics(
        ClassificationStats::default(),
        &FxHashMap::default(),
        &FxHashMap::default(),
        RectFastStats::default(),
        16,
        0,
        &unsupported,
    );
    assert_eq!(d.total_unsupported_items, 2);
    assert_eq!(d.unsupported_items_by_type[0].reason, "IfcGeometricSet");
    assert!(
        !d.is_empty(),
        "a nonzero total_unsupported_items must defeat is_empty, or processor/mod.rs drops the \
         diagnostics object and the drop is invisible again"
    );
}

/// Control: no dropped items is genuinely empty, so the arm above cannot be
/// satisfied by making `is_empty` always false.
#[test]
fn zero_unsupported_items_stays_empty() {
    let d = aggregate_diagnostics(
        ClassificationStats::default(),
        &FxHashMap::default(),
        &FxHashMap::default(),
        RectFastStats::default(),
        16,
        0,
        &FxHashMap::default(),
    );
    assert!(d.is_empty());
}