BREP_render 0.4.0

BREP Rust rendering engine: kernel-fed scene store + wgpu renderer (headless artifact, desktop window, and wasm canvas shells).
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
use super::*;

// ===========================================================================
// Import / export — the file-interchange lane (the ONE platform exception).
// STEP/IGES are text; STL/OBJ bytes are submitted to the background runner for
// RANSAC reconstruction, then return as validated STEP for IMPORT3D. Exports
// collect the CURRENT model's resident solids and serialize them.
// ===========================================================================
impl EngineState {
    /// Import an STL triangle mesh through topology-aware RANSAC recognition.
    /// Unsupported regions remain as validated facets, so every repairable
    /// source triangle reaches the resulting CAD body.
    pub fn import_stl_feature(&mut self, bytes: &[u8]) -> Result<String, String> {
        self.submit_mesh_import(crate::runner::MeshImportFormat::Stl, bytes.to_vec())
    }

    /// Import a Wavefront OBJ mesh through the same RANSAC reconstruction path.
    pub fn import_obj_feature(&mut self, text: &str) -> Result<String, String> {
        self.import_obj_bytes_feature(text.as_bytes())
    }

    /// Byte-oriented OBJ entry used by the picker so decoding also stays on the
    /// background runner with parsing and reconstruction.
    pub fn import_obj_bytes_feature(&mut self, bytes: &[u8]) -> Result<String, String> {
        self.submit_mesh_import(crate::runner::MeshImportFormat::Obj, bytes.to_vec())
    }

    fn submit_mesh_import(
        &mut self,
        format: crate::runner::MeshImportFormat,
        bytes: Vec<u8>,
    ) -> Result<String, String> {
        let id = self.submit_mesh_reconstruction(
            format, bytes, Default::default(), MeshImportDestination::Document,
        )?;
        Ok(serde_json::json!({ "meshImport": "submitted", "id": id }).to_string())
    }

    /// Reconstruct without editing history. The caller owns confirmation and
    /// can inspect the exact STEP and diagnostics returned by `take_mesh_preview`.
    pub fn reconstruct_mesh_preview(
        &mut self,
        format: crate::runner::MeshImportFormat,
        bytes: Vec<u8>,
        options: crate::runner::StlConversionOptions,
    ) -> Result<u64, String> {
        self.submit_mesh_reconstruction(format, bytes, options, MeshImportDestination::Preview)
    }

    pub fn take_mesh_preview(&mut self) -> Option<crate::runner::MeshImportReply> {
        self.mesh_preview_results.pop_front()
    }

    fn submit_mesh_reconstruction(
        &mut self,
        format: crate::runner::MeshImportFormat,
        bytes: Vec<u8>,
        options: crate::runner::StlConversionOptions,
        destination: MeshImportDestination,
    ) -> Result<u64, String> {
        if bytes.is_empty() {
            return Err("mesh import failed: file is empty".into());
        }
        let id = self.next_mesh_import_id;
        self.next_mesh_import_id = self.next_mesh_import_id.wrapping_add(1);
        self.pending_mesh_imports.insert(id, destination);
        self.runner.submit_mesh_import(crate::runner::MeshImportRequest {
            id, format, bytes, options,
        });
        self.pump();
        Ok(id)
    }

    /// Import a STEP document into the model: append an `IMPORT3D` feature whose
    /// `inputParams.stepText` is the raw ISO-10303-21 text (the exact headless
    /// source the kernel importer reads — no `fileToImport` data-URL marshaling
    /// needed), mint it a persistent-counter id, roll to it, and rebuild. Returns the
    /// build report JSON (imported bodies + any per-feature error). A non-STEP
    /// payload is refused up front so a bad upload never leaves a dead feature.
    pub fn import_step_feature(&mut self, step_text: &str) -> Result<String, String> {
        if !step_text.contains("ISO-10303-21") {
            return Err("not a STEP file (missing the ISO-10303-21 header)".into());
        }
        let id = self.next_feature_id(&crate::features::feature_short_name("IMPORT3D"));
        let feature = serde_json::json!({
            "type": "IMPORT3D",
            "inputParams": { "id": id, "stepText": step_text },
            "persistentData": {},
        });
        // The file's AP242 PMI, lifted ONCE into the document's pmi block with
        // references naming the faces / edges / vertices the feature will stamp
        // (the STEP text is never re-read for it). Read BEFORE the add so the
        // add's undo checkpoint precedes both writes: one undo removes the
        // feature and its PMI together.
        let lifted = brep_kernel::read_step_pmi(step_text, &id).unwrap_or(None);
        // Frame the imported body once the (possibly async) run lands — see
        // [`EngineState::pending_fit`]. An immediate fit here would frame the still
        // empty scene under a background runner (native thread / wasm worker).
        self.pending_fit = true;
        let report = self.add_feature(&feature.to_string());
        if let Some(lifted) = lifted {
            self.pmi_merge_imported(lifted);
        }
        report
    }

    /// Export the CURRENT model's resident solids to an ISO-10303-21 STEP
    /// document. Collects the resident handles of the rolled-to model (a warm
    /// re-run of the same prefix the display scene was built from — see
    /// [`crate::pipeline::resident_solid_handles`]) and hands them to the kernel's
    /// [`brep_kernel::export_step_handles`], so the exact NURBS topology is
    /// serialized (never the display mesh). Errs clearly when the model is empty.
    pub fn export_step_text(&mut self) -> Result<String, String> {
        self.export_step_text_named("Part")
    }

    /// [`Self::export_step_text`] with the document's own name, which becomes
    /// the root `PRODUCT`'s name (and the file's `FILE_NAME`).
    ///
    /// A document with ASSEMBLY COMPONENTS takes the STRUCTURED lane: each
    /// parts-library entry is written once as its own product, in its own local
    /// frame, and every instance becomes a `NEXT_ASSEMBLY_USAGE_OCCURRENCE`
    /// carrying its pose — nested sub-assemblies included. Without components
    /// the flat single-product writer is used, exactly as before.
    pub fn export_step_text_named(&mut self, document_name: &str) -> Result<String, String> {
        // BEFORE the resident re-run below: the sync executes the history too,
        // and it is the live component projection (post-solve poses) that the
        // structured lane places instances by.
        self.ensure_assembly_synced();
        let request: HistoryRequest = serde_json::from_value(self.history.prefix_request())
            .map_err(|e| format!("export STEP: history request: {e}"))?;
        let named = crate::pipeline::resident_solid_handles(&request);
        if named.is_empty() {
            return Err("nothing to export: the model has no solids".into());
        }
        // The document's PMI rides along as AP242 semantic PMI + saved views,
        // resolved against the same resident solids the file is written from
        // (the warm re-run above left the tail's report on this thread).
        let report = request
            .pmi
            .as_ref()
            .map(|_| brep_kernel::execute_history(&request).pmi)
            .flatten();
        let pmi = match (request.pmi.as_ref(), report.as_ref()) {
            (Some(state), Some(report)) => Some(brep_kernel::StepPmi { state, report }),
            _ => None,
        };
        if self.assembly_components.is_empty() {
            return brep_kernel::export_step_named_handles(
                &named,
                document_name,
                "MM",
                "",
                pmi.as_ref(),
            )
            .map(|report| report.text);
        }
        let components: Vec<(String, String, brep_kernel::Mat4)> = self
            .assembly_components
            .iter()
            .map(|record| {
                (
                    record.id.clone(),
                    record.part_name.clone(),
                    record.transform.elements,
                )
            })
            .collect();
        brep_kernel::export_step_assembly_handles(
            document_name,
            &named,
            &components,
            "MM",
            "",
            pmi.as_ref(),
        )
        .map(|report| report.text)
    }

    /// Resident handle of the part's target sheet-metal body for a flat-pattern
    /// export. Enumerates the current resident solids (a warm re-run of the same
    /// prefix the display scene was built from, like the STEP lane) and keeps the
    /// ones carrying a sheet-metal tree; uses the SELECTED sheet-metal body if the
    /// selection names exactly one, else the SOLE sheet-metal body (the same
    /// auto-target SM.CUTOUT uses). Errs with the exact `"no sheet-metal body in
    /// the part"` when there is none, and loudly when several are ambiguous.
    fn flat_pattern_target_handle(&self) -> Result<u32, String> {
        let request: HistoryRequest = serde_json::from_value(self.history.prefix_request())
            .map_err(|e| format!("export flat pattern: history request: {e}"))?;
        let sheet_metal: Vec<(String, u32)> = crate::pipeline::resident_solid_handles(&request)
            .into_iter()
            .filter(|(_, handle)| brep_kernel::is_sheet_metal_handle(*handle))
            .collect();
        if sheet_metal.is_empty() {
            return Err("no sheet-metal body in the part".into());
        }
        // Prefer a selected sheet-metal body when the selection names exactly one.
        let selected: Vec<u32> = sheet_metal
            .iter()
            .filter(|(name, _)| self.emphasis.selected_solids.contains(name))
            .map(|(_, handle)| *handle)
            .collect();
        if let [handle] = selected.as_slice() {
            return Ok(*handle);
        }
        match sheet_metal.as_slice() {
            [(_, handle)] => Ok(*handle),
            _ => Err(
                "several sheet-metal bodies in the part — select the one to export".into(),
            ),
        }
    }

    /// Export the part's sheet-metal FLAT PATTERN (the unfold) as a DXF (R12
    /// ASCII) 2D vector document. Runs the unfold TRANSIENTLY off the target
    /// body's resident tree — no feature is added and history is not mutated. Errs
    /// (`"no sheet-metal body in the part"`) when the part carries no sheet metal.
    pub fn export_flat_pattern_dxf(&self) -> Result<String, String> {
        brep_kernel::flat_pattern_dxf(self.flat_pattern_target_handle()?)
    }

    /// Export the part's sheet-metal flat pattern as an SVG — the DXF sibling of
    /// [`Self::export_flat_pattern_dxf`].
    pub fn export_flat_pattern_svg(&self) -> Result<String, String> {
        brep_kernel::flat_pattern_svg(self.flat_pattern_target_handle()?)
    }

    /// Import an IGES document into the model: append an `IMPORT3D` feature whose
    /// `inputParams.igesText` is the raw IGES text (the kernel importer reads it
    /// via [`brep_kernel::import_iges`]), mint an id, roll to it, and rebuild.
    /// Refuses a non-IGES payload up front so a bad upload never leaves a dead
    /// feature.
    pub fn import_iges_feature(&mut self, iges_text: &str) -> Result<String, String> {
        if iges_text.contains("ISO-10303-21") {
            return Err("not an IGES file (this looks like a STEP document)".into());
        }
        // IGES records carry an S/G/D/P/T section letter in column 73.
        let looks_like_iges = iges_text.lines().any(|line| {
            matches!(line.chars().nth(72), Some('S' | 'G' | 'D' | 'P' | 'T'))
        });
        if !looks_like_iges {
            return Err("not an IGES file (no S/G/D/P/T section records found)".into());
        }
        let id = self.next_feature_id(&crate::features::feature_short_name("IMPORT3D"));
        let feature = serde_json::json!({
            "type": "IMPORT3D",
            "inputParams": { "id": id, "igesText": iges_text },
            "persistentData": {},
        });
        // Frame the imported body once the (possibly async) run lands — see
        // [`EngineState::pending_fit`] (mirrors the STEP lane above).
        self.pending_fit = true;
        self.add_feature(&feature.to_string())
    }

    /// Export the CURRENT model's resident solids to an IGES 5.3 document of
    /// trimmed NURBS surfaces — the IGES analogue of [`Self::export_step_text`],
    /// handing the resident handles to [`brep_kernel::export_iges_handles`].
    pub fn export_iges_text(&self) -> Result<String, String> {
        let request: HistoryRequest = serde_json::from_value(self.history.prefix_request())
            .map_err(|e| format!("export IGES: history request: {e}"))?;
        let handles: Vec<u32> = crate::pipeline::resident_solid_handles(&request)
            .into_iter()
            .map(|(_, handle)| handle)
            .collect();
        if handles.is_empty() {
            return Err("nothing to export: the model has no solids".into());
        }
        brep_kernel::export_iges_handles(&handles, "Part", "MM", "")
    }

    /// Export the CURRENT display scene to an ASCII STL string (one `solid` with a
    /// per-triangle geometric normal for every mesh triangle of every displayed
    /// solid). STL is a triangle-soup format with no multi-body concept, so all
    /// solids fold into a single `solid brep … endsolid brep`. String-shaped so it
    /// crosses the same string `ModelStore` seam the STEP lane uses. Errs when the
    /// scene has no triangles.
    pub fn export_stl_text(&self) -> Result<String, String> {
        let mut out = String::from("solid brep\n");
        let mut triangles = 0usize;
        for solid in self.scene.solids() {
            let positions = &solid.mesh.positions;
            for tri in solid.mesh.indices.chunks_exact(3) {
                let a = positions[tri[0] as usize];
                let b = positions[tri[1] as usize];
                let c = positions[tri[2] as usize];
                let normal = triangle_normal(a, b, c);
                out.push_str(&format!(
                    "  facet normal {} {} {}\n    outer loop\n",
                    normal[0], normal[1], normal[2]
                ));
                for v in [a, b, c] {
                    out.push_str(&format!("      vertex {} {} {}\n", v[0], v[1], v[2]));
                }
                out.push_str("    endloop\n  endfacet\n");
                triangles += 1;
            }
        }
        out.push_str("endsolid brep\n");
        if triangles == 0 {
            return Err("nothing to export: the scene has no triangles".into());
        }
        Ok(out)
    }
}

/// Unit (or zero, for a degenerate triangle) geometric normal of triangle
/// `(a, b, c)` — the per-facet normal an ASCII STL record carries.
fn triangle_normal(a: [f32; 3], b: [f32; 3], c: [f32; 3]) -> [f32; 3] {
    let u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
    let v = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
    let n = [
        u[1] * v[2] - u[2] * v[1],
        u[2] * v[0] - u[0] * v[2],
        u[0] * v[1] - u[1] * v[0],
    ];
    let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
    if len > 0.0 {
        [n[0] / len, n[1] / len, n[2] / len]
    } else {
        [0.0, 0.0, 0.0]
    }
}

// ===========================================================================
// STRUCTURED STEP import — the assembly lane (kernel-plan
// `step-assembly-import.md` §3.7).
//
// The flat lane above (`import_step_feature`) appends ONE IMPORT3D holding the
// raw Part-21 text and lets the kernel bake every occurrence's world transform
// into its own body: N bodies, no parts, no tree. This lane keeps the structure
// instead — each unique geometry-bearing PRODUCT_DEFINITION becomes ONE
// parts-library entry holding a NATIVE payload (`nativeBrep`, no STEP text
// anywhere past this door), and each occurrence of it becomes an ACOMP instance
// carrying the composed world pose. Six bolts are then one entry × six
// instances, which is what makes the BOM, the structure tree, per-component
// selection and constraints work on imported geometry.
//
// # FLAT or NESTED — the user's choice, both correct
//
// [`StepAssemblyImport::nested`] picks between two shapes of the same geometry
// (kernel-plan §3.3):
//
// - **Flat** flattens the occurrence tree to its geometry-bearing leaves: one
//   ACOMP per leaf occurrence, each carrying the COMPOSED world pose. Every
//   part is stored once for the whole document.
// - **Nested** keeps the tree: each assembly-node product becomes a part
//   document that itself carries `{partsLibrary, features: [ACOMP…,
//   IMPORT3D…]}`, built bottom-up by the same recursive builder, and the
//   parent gets ONE ACOMP per sub-assembly occurrence. Build-spec §2.2's
//   rigid nesting — the sub-assembly arrives already-solved and moves as one
//   component, the live `ComponentMap` stays flat, and the structure tree
//   expands it read-only from the namespace chain (`ACOMP2:ACOMP1:…`).
//
// Neither is the deprecated one. Nested shows the real tree; flat is the right
// answer for a deep or pathological file, and it stores a part reused at two
// levels ONCE, where nesting stores it once PER LEVEL (build-spec §2.2). For a
// depth-1 tree the two lanes produce byte-identical documents — the cheapest
// correctness check there is, and `nested_matches_flat_for_a_depth_one_tree`
// asserts exactly it.
//
// # PROBE then CONSUME — because the parse is the expensive half
//
// The app must know the counts BEFORE it can offer the choice ("7 parts, 23
// instances — import as assembly or as bodies?"), and re-reading multi-MB
// Part-21 text after the user clicks would pay the file's single most expensive
// cost twice. So [`EngineState::probe_step_assembly`] performs the ONE parse and
// stashes the [`brep_kernel::StepAssembly`] in
// [`EngineState::pending_step_assembly`];
// [`EngineState::import_probed_step_assembly`] TAKES it. Cancel
// ([`EngineState::discard_probed_step_assembly`]), a second probe, and a
// document switch all drop it, so a user who cancels three imports is holding
// zero parsed assemblies — a real consideration, since the stash keeps every
// product's solids resident for as long as the dialog is open.
//
// # ONE rebuild for the whole import
//
// `add_feature` re-runs the entire history per call, so appending N instances
// through it is O(N²). This lane appends them all through
// [`EngineState::add_features`] — one push batch, one rebuild, one undo step.
// (Not `set_history_json`: that is the document-SWITCH path, which clears the
// kernel history cache and resets the runner's delta baseline.)
//
// # Fallback, never a silent zero
//
// No structure at all, or every geometry-bearing product failing to encode, both
// end at today's flat lane. "A successful import that produces zero components"
// is a failure wearing a result's clothes, so the zero-component case is an
// `Err` for the dialog-driven entry point (the app owns the file text and re-runs
// the flat import) and an automatic fall-back for the text-taking convenience.
// ===========================================================================

/// What the import dialog needs to describe a STEP file's structure — counts
/// only, so the probe can answer without building anything.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StepAssemblyProbe {
    /// Unique geometry-bearing products → parts-library entries. The floor, not
    /// the final count: a non-rigid occurrence bakes its own extra entry (§3.4).
    pub parts: usize,
    /// Geometry-bearing occurrences → ACOMP instance features.
    pub instances: usize,
    /// Longest root→node chain of occurrences. `1` is a flat assembly; `> 1`
    /// means sub-assemblies exist, so [`StepAssemblyImport::nested`] changes
    /// the shape of the result and the dialog's choice is worth offering.
    pub nested_depth: usize,
}

/// The choices the import dialog collects.
#[derive(Debug, Clone, Copy, Default)]
pub struct StepAssemblyImport {
    /// Build nested rigid sub-assembly documents (kernel-plan §3.3 Phase 2)
    /// instead of flattening the tree to its leaf occurrences.
    ///
    /// `false` (the `Default`) is the flat lane, byte-for-byte unchanged. On a
    /// depth-1 tree the two produce the same document, so this flag only ever
    /// matters for a file that really has sub-assemblies.
    pub nested: bool,
}

/// What an import did — the numbers the status line and notice report.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct StepAssemblyReport {
    /// Parts-library entries this import added or reused — the entries of the
    /// USER'S document. On a nested import that is the top level only: a
    /// sub-assembly's own entries live in ITS document's library, which the
    /// parent never sees.
    pub parts: usize,
    /// ACOMP instance features appended to the user's document. Nested: one per
    /// ROOT-level occurrence (a sub-assembly is one component, per build-spec
    /// §2.2), not one per leaf body.
    pub instances: usize,
    /// Occurrences whose non-rigid factor was baked into a distinct part
    /// (§3.4), summed over every level a nested import built.
    pub baked_nonrigid: usize,
    /// Products (or baked non-rigid variants of one) that did not encode to a
    /// payload — skipped and counted, never fatal: the importer's
    /// graceful-degradation contract, carried up to this altitude. Summed over
    /// every level a nested import built.
    pub failed_products: usize,
    /// The first thing that went wrong, from the kernel's body-build errors or
    /// this lane's own encode failures.
    pub first_error: Option<String>,
    /// The structured lane did not run: the file carries no usable structure, or
    /// nothing in it encoded, so the bodies were imported through the flat lane
    /// exactly as before. Only ever `true` from [`EngineState::import_step_assembly`],
    /// which holds the text; the dialog-driven entry point returns `Err` instead
    /// and lets its caller re-run the flat import it already has the text for.
    pub flat_fallback: bool,
}

/// The outcome of consuming a parsed assembly, before it is shaped into either
/// an `Err` (dialog lane) or a flat fallback (text lane) — so neither has to
/// recognise "nothing imported" by matching an error string.
enum Consumed {
    Imported(StepAssemblyReport),
    /// Every geometry-bearing product failed to encode: no components, so this
    /// is not an import.
    NoComponents {
        failed_products: usize,
        first_error: Option<String>,
    },
}

/// A row-major 4×4 affine, the shape `StepOccurrence::placement` and
/// `AffineTransform` both use.
type Mat4 = [f64; 16];

/// One node of the composed occurrence tree — a product at a world pose.
struct PlacedProduct {
    /// Index into `StepAssembly::products`.
    product: usize,
    /// Composed child-local → world transform.
    world: Mat4,
    /// Occurrence edges between a root and this node (`0` at a root).
    depth: usize,
    /// Every edge on the path here was rigid, so `world` IS a component pose.
    /// False means the non-rigid factor must be baked into the part (§3.4).
    rigid_path: bool,
}

/// A parts-library entry this import needs: a product, plus the bits of the
/// non-rigid factor baked into it (all-zero linear block ⇒ none). Two
/// occurrences of one product under DIFFERENT non-rigid factors are different
/// parts — never a wrong-handed reuse.
type PartKey = (usize, [u64; 9]);

/// The `PartKey` factor slot for a plain rigid instance.
const NO_FACTOR: [u64; 9] = [0; 9];

impl EngineState {
    /// Read a STEP file's product structure — THE parse of a structured import.
    /// Stashes the parsed assembly (with every product's solids) for
    /// [`Self::import_probed_step_assembly`] and returns the dialog's counts.
    ///
    /// `Ok(None)` = no usable structure (no NAUO edges, or none reaching built
    /// geometry): the caller imports through the flat
    /// [`Self::import_step_feature`] lane with the text it already holds, which
    /// is byte-for-byte today's behaviour. `Err` only for text that is not a
    /// Part 21 file at all — a BROKEN assembly degrades, it does not fail.
    ///
    /// Replaces any previously stashed assembly on EVERY outcome, `Ok(None)`
    /// included: a stale stash surviving a probe of a different file is how a
    /// consume silently imports the wrong one.
    pub fn probe_step_assembly(
        &mut self,
        step_text: &str,
    ) -> Result<Option<StepAssemblyProbe>, String> {
        let id = self.submit_step_probe(step_text);
        // Inline answers inside `submit`'s own pump; a background runner has
        // not answered yet and this call must not pretend it has.
        match self.take_step_probe() {
            Some((answered, outcome)) if answered == id => match outcome {
                super::StepProbeOutcome::Structure(probe) => Ok(Some(probe)),
                super::StepProbeOutcome::Flat => Ok(None),
                super::StepProbeOutcome::Failed(error) => Err(error),
            },
            _ => Err(
                "the STEP probe is still running on the background runner — use \
                 submit_step_probe / take_step_probe"
                    .into(),
            ),
        }
    }

    /// SUBMIT a STEP text to be probed for product structure on the runner
    /// (the parse builds every product's bodies: seconds for a real assembly,
    /// which is why it leaves the UI thread). The answer arrives through
    /// [`Self::take_step_probe`] under the returned id, after a later `pump`;
    /// a found structure is stashed for [`Self::import_probed_step_assembly`].
    /// Any earlier stash is dropped now — the probe REPLACES it on every
    /// outcome, so a stale parse can never be consumed for the wrong file.
    ///
    /// The structure test the parse would make is "any NEXT_ASSEMBLY_USAGE_
    /// OCCURRENCE entity" (`assembly_edges`), so a text with none cannot have
    /// structure and is answered `Flat` without a trip to the runner: a part
    /// file — the common upload — no longer pays a full parse only to be told
    /// to take the flat lane, where the worker parses it anyway. (The text
    /// test is a superset of the entity test: a stray mention in a comment
    /// merely runs the parse.)
    pub fn submit_step_probe(&mut self, step_text: &str) -> u64 {
        self.pending_step_assembly = None;
        let id = self.next_step_probe_id;
        self.next_step_probe_id = self.next_step_probe_id.wrapping_add(1);
        if !step_text.contains("NEXT_ASSEMBLY_USAGE_OCCURRENCE") {
            self.step_probe_results
                .push_back((id, super::StepProbeOutcome::Flat));
            return id;
        }
        self.pending_step_probes.insert(id);
        self.runner.submit_step_probe(crate::runner::StepProbeRequest {
            id,
            text: step_text.to_string(),
        });
        self.pump();
        id
    }

    /// The oldest answered probe, if any: its submission id and what it found.
    pub fn take_step_probe(&mut self) -> Option<(u64, super::StepProbeOutcome)> {
        self.step_probe_results.pop_front()
    }

    /// Whether a submitted probe has not been answered yet — the app keeps the
    /// frame loop alive (and the panel its "reading…" status) while it is.
    pub fn step_probes_pending(&self) -> bool {
        !self.pending_step_probes.is_empty()
    }

    /// Import the assembly [`Self::probe_step_assembly`] stashed: one
    /// parts-library entry per unique product, one ACOMP instance per
    /// occurrence, ONE rebuild. TAKES the stash, so a double-import is an error
    /// rather than a double-insert.
    ///
    /// `doc_name` names products the file left unnamed (`{doc_name}-part-{id}`).
    /// `opts.nested` chooses between the flat and nested shapes — see
    /// [`StepAssemblyImport::nested`]. Errs when nothing is stashed, and when
    /// every product failed to encode — the latter being the caller's cue to
    /// re-run the flat import with the file text it holds.
    /// `sink` receives every unique part document so the app can write it to
    /// the model store and hand back a real `sourceKey`; pass [`EmbeddedOnly`]
    /// to keep the parts embedded (what a caller with no store does).
    pub fn import_probed_step_assembly(
        &mut self,
        doc_name: &str,
        opts: StepAssemblyImport,
        sink: &mut dyn PartSink,
    ) -> Result<StepAssemblyReport, String> {
        let assembly = self.pending_step_assembly.take().ok_or_else(|| {
            "import STEP assembly: nothing probed (call probe_step_assembly first)".to_string()
        })?;
        match self.consume_step_assembly(assembly, doc_name, opts.nested, sink) {
            Consumed::Imported(report) => Ok(report),
            Consumed::NoComponents { first_error, .. } => Err(format!(
                "import STEP assembly: no part of the assembly could be built{}",
                first_error
                    .map(|error| format!(" ({error})"))
                    .unwrap_or_default()
            )),
        }
    }

    /// Drop a probed assembly and the solids it holds resident — the dialog's
    /// Cancel. Idempotent.
    pub fn discard_probed_step_assembly(&mut self) {
        self.pending_step_assembly = None;
    }

    /// Probe + consume in one call, falling back to the flat lane by itself —
    /// the HEADLESS/test entry point. The app uses the probe/consume pair
    /// instead, because it has a dialog between the two halves.
    ///
    /// Still exactly one parse: this is `probe_step_assembly` followed by the
    /// consume of what it stashed.
    ///
    /// Parts stay EMBEDDED here ([`EmbeddedOnly`]): this entry point has no
    /// store handle and no way to ask for a destination. The app uses the
    /// probe/consume pair with a real sink.
    pub fn import_step_assembly(
        &mut self,
        step_text: &str,
        doc_name: &str,
        opts: StepAssemblyImport,
    ) -> Result<StepAssemblyReport, String> {
        let structured = self.probe_step_assembly(step_text)?.is_some();
        let outcome = structured.then(|| {
            let assembly = self
                .pending_step_assembly
                .take()
                .expect("a Some probe stashed the assembly it counted");
            self.consume_step_assembly(assembly, doc_name, opts.nested, &mut EmbeddedOnly)
        });
        match outcome {
            Some(Consumed::Imported(report)) => Ok(report),
            // No structure, or a structure nothing built out of: import the
            // bodies exactly as the pre-assembly lane did.
            Some(Consumed::NoComponents {
                failed_products,
                first_error,
            }) => {
                self.import_step_feature(step_text)?;
                Ok(StepAssemblyReport {
                    failed_products,
                    first_error,
                    flat_fallback: true,
                    ..StepAssemblyReport::default()
                })
            }
            None => {
                self.import_step_feature(step_text)?;
                Ok(StepAssemblyReport {
                    flat_fallback: true,
                    ..StepAssemblyReport::default()
                })
            }
        }
    }

    /// The import itself (kernel-plan §3.7 steps 2-5), shared by both entry
    /// points so neither has to recognise "nothing imported" from an error
    /// string.
    fn consume_step_assembly(
        &mut self,
        assembly: brep_kernel::StepAssembly,
        doc_name: &str,
        nested: bool,
        sink: &mut dyn PartSink,
    ) -> Consumed {
        let mut first_error = assembly.first_error.clone();
        // ONE writer for the whole import, so identical content is written to
        // the store exactly once however many products or LEVELS share it.
        let mut writer = PartWriter::new(sink);

        // --- what to build ------------------------------------------------
        // One row per component the USER'S document gets, each naming the
        // library entry it needs. Flat walks the whole tree to its leaves;
        // nested stops at the root's own children and folds everything below
        // each of them into that child's part document.
        let plan = if nested {
            plan_nested(&assembly, doc_name, &mut first_error, &mut writer)
        } else {
            plan_flat(&assembly, &mut first_error)
        };
        let Plan {
            wanted,
            factors,
            documents,
            mut failed_products,
            baked_below_root,
        } = plan;

        // --- build the library entries -------------------------------------
        // In (pd_ref, factor) order so an import is deterministic regardless of
        // the tree's emit order, and ONCE per key however many instances use it.
        let mut keys: Vec<PartKey> = wanted.iter().map(|(key, _)| *key).collect();
        keys.sort_unstable();
        keys.dedup();
        let mut entry_names: std::collections::HashMap<PartKey, String> =
            std::collections::HashMap::new();
        {
            // THE metadata bracket. `native_import_payload` seals whatever record
            // this thread's scene-metadata store holds for each name it stamps —
            // right for a snapshot of the live scene, catastrophic here: a new
            // part whose stamped face names collide with names already in THIS
            // document would silently carry the current document's metadata.
            // Scoped to the encode alone; the rebuild below stamps records the
            // document must keep, and this guard's drop would discard them.
            //
            // The nested lane's payloads are encoded inside `plan_nested`,
            // which holds a bracket of its own for exactly the same reason.
            let _isolation = brep_kernel::IsolatedSceneMetadata::begin();
            for key in &keys {
                // Nested pre-built the whole document (a sub-assembly's is a
                // recursive `{partsLibrary, features}`); flat builds the §3.2
                // native part document right here.
                let built = match documents.get(key) {
                    Some((name, document)) => install_part(name, document, &mut writer),
                    None => {
                        let product = assembly
                            .products
                            .iter()
                            .find(|product| product.pd_ref == key.0)
                            .expect("every key names a product of this assembly");
                        build_library_entry(product, factors.get(key), doc_name, &mut writer)
                    }
                };
                match built {
                    Ok(name) => {
                        entry_names.insert(*key, name);
                    }
                    Err(error) => {
                        failed_products += 1;
                        note(&mut first_error, error);
                    }
                }
            }
        }
        if entry_names.is_empty() {
            return Consumed::NoComponents {
                failed_products,
                first_error,
            };
        }

        // --- append every instance in ONE history mutation -----------------
        // `insert_component`'s rule, verbatim: ground the FIRST component only
        // when the document has none yet. Grounding a second one over-constrains
        // the next solve.
        let mut ground_next = !(0..self.history.len()).any(|index| {
            matches!(
                self.history.feature_type(index).as_deref(),
                Some("ACOMP") | Some("ASSEMBLY COMPONENT")
            )
        });
        let mut features: Vec<serde_json::Value> = Vec::with_capacity(wanted.len());
        let mut baked_nonrigid = 0usize;
        for (key, pose) in &wanted {
            let Some(part_name) = entry_names.get(key) else {
                continue; // this product failed to encode; counted above
            };
            let transform = match brep_kernel::AffineTransform::new(*pose) {
                Ok(transform) => transform,
                Err(error) => {
                    note(&mut first_error, format!("occurrence pose: {error}"));
                    continue;
                }
            };
            if key.1 != NO_FACTOR {
                baked_nonrigid += 1;
            }
            features.push(serde_json::json!({
                "type": "ACOMP",
                "inputParams": {
                    "id": self.history.next_feature_id("ACOMP"),
                    "partName": part_name,
                    "transform": brep_kernel::transform_to_pose_params(&transform),
                    "isFixed": ground_next,
                },
                "persistentData": {}
            }));
            ground_next = false;
        }
        if features.is_empty() {
            return Consumed::NoComponents {
                failed_products,
                first_error,
            };
        }

        // The library block must ride the request so the display runner ingests
        // the new entries on the very next run (as `insert_component` does).
        // Written only now that there are components to reference them, so an
        // import that produced nothing leaves the document untouched.
        if let Ok(library) =
            serde_json::from_str::<serde_json::Value>(&brep_kernel::parts_library_json())
        {
            self.history.set_parts_library(library);
        }
        // Frame the assembly once the (possibly async) run lands — see
        // [`EngineState::pending_fit`], same reasoning as `import_step_feature`.
        self.pending_fit = true;
        let instances = features.len();
        let baked_nonrigid = baked_nonrigid + baked_below_root;
        self.add_features(&features);
        Consumed::Imported(StepAssemblyReport {
            // DISTINCT entries, not distinct keys: `add_part_to_library` reuses
            // an entry whose content already matches, so two products that are
            // the same geometry collapse to one part (§3.5's free content dedup).
            parts: entry_names
                .values()
                .collect::<std::collections::HashSet<_>>()
                .len(),
            instances,
            baked_nonrigid,
            failed_products,
            first_error,
            flat_fallback: false,
        })
    }
}

/// What one import decided to build, before any of it is installed: the rows
/// the user's document gets, and whatever each lane needed to work out on the
/// way there.
#[derive(Default)]
struct Plan {
    /// One row per component of the USER'S document, in emit order.
    wanted: Vec<(PartKey, Mat4)>,
    /// FLAT only: the non-rigid factor a key's part must bake (§3.4). The
    /// nested lane bakes inside its own builder and hands the finished document
    /// over in `documents` instead.
    factors: std::collections::HashMap<PartKey, Mat4>,
    /// NESTED only: `(entry name, part document)` per key, already built — a
    /// leaf's §3.2 native document, or a sub-assembly's recursive
    /// `{partsLibrary, features}`.
    documents: std::collections::HashMap<PartKey, (String, serde_json::Value)>,
    /// Products that did not encode while planning (nested builds payloads
    /// during the plan; flat builds them during the install).
    failed_products: usize,
    /// Non-rigid occurrences baked BELOW the root — nested only, since the flat
    /// lane has no below-the-root and counts its bakes at install time.
    baked_below_root: usize,
}

/// **FLAT** (kernel-plan §3.3 Phase 1): flatten the occurrence tree to its
/// geometry-bearing nodes, each carrying the COMPOSED world pose. Byte-for-byte
/// the lane A6 shipped.
fn plan_flat(assembly: &brep_kernel::StepAssembly, first_error: &mut Option<String>) -> Plan {
    let mut plan = Plan::default();
    for placed in &compose_world_occurrences(assembly) {
        let product = &assembly.products[placed.product];
        if product.bodies.is_empty() {
            continue; // a pure assembly node contributes structure, not a component
        }
        let (key, pose) = if placed.rigid_path {
            ((product.pd_ref, NO_FACTOR), placed.world)
        } else {
            // §3.4: world = rigid · factor. Bake `factor` into a distinct part
            // and give the instance the rigid residue, so a mirrored instance
            // never lands on its unmirrored twin.
            match split_rigid(&placed.world) {
                // Non-rigid edges that cancel out along the path leave an
                // identity factor: that is an ordinary instance of the ordinary
                // part, not a bake.
                Ok((rigid, factor)) if is_identity(&factor) => {
                    ((product.pd_ref, NO_FACTOR), rigid)
                }
                Ok((rigid, factor)) => {
                    let key = (product.pd_ref, factor_key(&factor));
                    plan.factors.insert(key, factor);
                    (key, rigid)
                }
                Err(error) => {
                    note(first_error, error);
                    continue;
                }
            }
        };
        plan.wanted.push((key, pose));
    }
    plan
}

/// **NESTED** (kernel-plan §3.3 Phase 2): the live document plays the ROOT, so
/// it gets one component per root-level row and nothing deeper —
///
/// - a root's OWN bodies become a leaf part at identity (exactly the flat
///   lane's treatment of interior geometry at the root), and
/// - each root-child occurrence becomes ONE component: a leaf part when the
///   child has no children of its own, else a rigid sub-assembly whose part
///   document carries its own `partsLibrary` and its own ACOMPs.
///
/// Emit order matches [`plan_flat`]'s DFS pre-order — root before its children,
/// children by ascending `nauo_ref` — which is what makes the two lanes produce
/// the SAME document for a depth-1 tree.
fn plan_nested(
    assembly: &brep_kernel::StepAssembly,
    doc_name: &str,
    first_error: &mut Option<String>,
    writer: &mut PartWriter<'_>,
) -> Plan {
    // The same bracket the install loop holds, for the same reason: every
    // payload this builder encodes (at every level) must see an empty ambient
    // scene-metadata store, or a nested leaf whose stamped face names collide
    // with the live document's silently inherits the live document's records.
    let _isolation = brep_kernel::IsolatedSceneMetadata::begin();
    let mut build = NestedBuild {
        assembly,
        doc_name,
        writer,
        memo: std::collections::HashMap::new(),
        factors: std::collections::HashMap::new(),
        entries: 0,
        bytes: 0,
        failed_products: 0,
        baked_nonrigid: 0,
        first_error: None,
    };
    let mut plan = Plan::default();
    for &root in &assembly.roots {
        let mut rows: Vec<(DocKey, Mat4)> = Vec::new();
        // The root's OWN bodies become a leaf part at identity — exactly the
        // flat lane's treatment, and the reason a depth-1 tree comes out the
        // same either way.
        if !assembly.products[root].bodies.is_empty() {
            rows.push((
                DocKey::Leaf((assembly.products[root].pd_ref, NO_FACTOR)),
                MAT4_IDENTITY,
            ));
        }
        // Root-level bakes are counted by the install loop's own pass over
        // `wanted` (they are ordinary top-level rows); only bakes BELOW the root
        // — which never become rows of the user's document — are counted here.
        let mut root_level_bakes = 0usize;
        build.place_children(root, &[root], &mut rows, &mut root_level_bakes);
        for (key, pose) in rows {
            let part = match build.document(key, &mut vec![root]) {
                Ok(Some(document)) => document,
                // A subtree with no geometry anywhere places nothing — the flat
                // lane says the same thing by emitting no component for it.
                Ok(None) => continue,
                Err(error) => {
                    build.failed_products += 1;
                    note(&mut build.first_error, error);
                    continue;
                }
            };
            let part_key = key.part_key(assembly);
            plan.documents.insert(part_key, part);
            plan.wanted.push((part_key, pose));
        }
    }
    plan.failed_products = build.failed_products;
    plan.baked_below_root = build.baked_nonrigid;
    if let Some(error) = build.first_error {
        note(first_error, error);
    }
    plan
}

/// How deep the recursive builder will go before it refuses. `read_step_assembly`
/// guards cycles inside its own walk and [`NestedBuild::document`] guards them
/// again along the recursion path, so this is the SECOND line: a malformed file
/// that is merely pathologically deep (rather than cyclic) must not run the
/// native stack out. Sixty-four levels of embedded documents is already far past
/// anything a real CAD assembly carries — and each level embeds the whole
/// subtree below it, so the document would be unusable long before then.
const MAX_NESTED_DEPTH: usize = 64;

/// How many DISTINCT part documents a nested import may build. Bounds the
/// builder's work; it does NOT bound the result's size — see
/// [`MAX_NESTED_BYTES`], which is the guard that matters.
const MAX_NESTED_ENTRIES: usize = 10_000;

/// How many bytes of part document a nested import may EMBED, summed over every
/// `partsLibrary` entry it writes at every level.
///
/// This is the guard neither the depth cap nor the entry count provides. A
/// product reachable at many different depths is stored once PER LEVEL
/// (build-spec §2.2) — the memo builds its document once, but each parent
/// embeds a COPY, so a diamond-shaped structure well inside the depth cap can
/// still multiply out geometrically. Charging the embedded bytes is the only
/// place that multiplication is visible, so it is charged where it happens.
const MAX_NESTED_BYTES: usize = 256 * 1024 * 1024;

/// What a nested part document is memoised under. A product is either a leaf
/// (no occurrence children) or an assembly node, never both, so the two
/// variants can never name the same product — except at a ROOT, whose own
/// bodies become a leaf part while the root itself is an assembly node. That
/// case is exactly why this is an enum and not a bare [`PartKey`].
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
enum DocKey {
    /// A geometry-bearing product placed as a part: `(pd_ref, baked factor)`.
    Leaf(PartKey),
    /// A product placed as a rigid sub-assembly, by index into `products`.
    Assembly(usize),
}

impl DocKey {
    /// The parts-library identity this document is stored under. Always keyed on
    /// the `pd_ref` (never the product INDEX, which lives in a different number
    /// space and would collide with some other product's `pd_ref`). An assembly
    /// node never carries a baked factor — a non-rigid edge into one is skipped,
    /// see [`NestedBuild::place_children`] — so `NO_FACTOR` is exact.
    fn part_key(self, assembly: &brep_kernel::StepAssembly) -> PartKey {
        match self {
            DocKey::Leaf(key) => key,
            DocKey::Assembly(product) => (assembly.products[product].pd_ref, NO_FACTOR),
        }
    }
}

/// The recursive builder behind [`plan_nested`]: turns one product into the part
/// document that represents it, bottom-up, memoised so a product reached from
/// several parents is built ONCE however many places embed it.
struct NestedBuild<'a, 'w> {
    assembly: &'a brep_kernel::StepAssembly,
    doc_name: &'a str,
    /// Where a CHILD library entry's document is written, shared with the
    /// top-level install loop so one part is one file at every level.
    writer: &'a mut PartWriter<'w>,
    /// `None` = this subtree carries no geometry at all, so nothing places it.
    memo: std::collections::HashMap<DocKey, Option<(String, serde_json::Value)>>,
    /// The non-rigid factor behind every baked [`DocKey::Leaf`] key, so the
    /// builder never has to reconstruct a matrix out of its own hash key.
    factors: std::collections::HashMap<PartKey, Mat4>,
    entries: usize,
    /// Bytes of part document embedded so far — the [`MAX_NESTED_BYTES`] charge.
    bytes: usize,
    failed_products: usize,
    baked_nonrigid: usize,
    first_error: Option<String>,
}

impl NestedBuild<'_, '_> {
    /// The part document for `key`, built once and reused. `ancestors` is the
    /// recursion path — the cycle guard, and the depth the cap is measured on.
    ///
    /// A cyclic file gets ONE deterministic truncation: the memo keeps whichever
    /// path reached a node first, and that path's skipped back-edge is the one
    /// every embedding sees. Deterministic and finite is the whole contract for
    /// input that is malformed by construction.
    fn document(
        &mut self,
        key: DocKey,
        ancestors: &mut Vec<usize>,
    ) -> Result<Option<(String, serde_json::Value)>, String> {
        if let Some(hit) = self.memo.get(&key) {
            return Ok(hit.clone());
        }
        if ancestors.len() >= MAX_NESTED_DEPTH {
            return Err(format!(
                "nested import: sub-assembly nesting deeper than {MAX_NESTED_DEPTH} levels \
                 (import as bodies, or import flat)"
            ));
        }
        let built = match key {
            DocKey::Leaf(part) => self.leaf_document(part),
            DocKey::Assembly(product) => {
                ancestors.push(product);
                let built = self.assembly_document(product, ancestors);
                ancestors.pop();
                built
            }
        }?;
        self.memo.insert(key, built.clone());
        Ok(built)
    }

    /// A geometry-bearing product as the §3.2 part document — the same one the
    /// flat lane installs, built by the same helper, so a depth-1 nested import
    /// and a flat one store byte-identical entries.
    fn leaf_document(
        &mut self,
        key: PartKey,
    ) -> Result<Option<(String, serde_json::Value)>, String> {
        let product = self
            .assembly
            .products
            .iter()
            .find(|product| product.pd_ref == key.0)
            .expect("every key names a product of this assembly");
        if product.bodies.is_empty() {
            return Ok(None);
        }
        let factor = self.factors.get(&key).copied();
        self.spend_entry()?;
        native_part_document(product, factor.as_ref(), self.doc_name).map(Some)
    }

    /// An assembly-node product as a rigid sub-assembly document: its OWN bodies
    /// as plain native IMPORT3D features (the interior-node geometry Phase 1
    /// could only make a SIBLING of its own children), one ACOMP per child
    /// occurrence, and the children's documents in this level's own
    /// `partsLibrary`.
    ///
    /// The entries carry NO snapshot. An entry with an unreadable snapshot heals
    /// from its embedded document (`assembly_component.rs`'s SELF-HEAL lane),
    /// and for a native part that heal is a decode + re-encode — so the level
    /// above bakes this whole subtree into ITS snapshot on insert, and these
    /// inner caches would only ever be rebuilt to be thrown away. Kernel-plan §6
    /// names this exact economy ("omit the persisted snapshot for an entry whose
    /// document is a single native IMPORT3D"); nesting is where it pays, because
    /// otherwise every level stores the level below it twice.
    fn assembly_document(
        &mut self,
        product: usize,
        ancestors: &mut Vec<usize>,
    ) -> Result<Option<(String, serde_json::Value)>, String> {
        let node = &self.assembly.products[product];
        let mut library = serde_json::Map::new();
        let mut features: Vec<serde_json::Value> = Vec::new();

        // The node's own bodies first, matching the flat lane's "a node before
        // its children" emit order.
        if !node.bodies.is_empty() {
            let payload = brep_kernel::native_import_payload_with_appearance(
                "IMPORT3D1",
                &node.bodies,
                &node.appearances,
            )
            .map_err(|error| format!("part '{}': {error}", part_name(node, self.doc_name)))?;
            features.push(serde_json::json!({
                "type": "IMPORT3D",
                "inputParams": { "id": "IMPORT3D1", "nativeBrep": payload },
                "persistentData": {},
            }));
        }

        // One ACOMP per child occurrence, children by ascending `nauo_ref`.
        let mut rows: Vec<(DocKey, Mat4)> = Vec::new();
        let mut bakes = 0usize;
        self.place_children(product, ancestors, &mut rows, &mut bakes);
        self.baked_nonrigid += bakes;
        let mut names: std::collections::HashMap<DocKey, String> =
            std::collections::HashMap::new();
        // `add_part_to_library`'s content reuse, applied to this level's block:
        // two products that are the SAME geometry collapse to one entry (§3.5's
        // free dedup), and every instance of either references it.
        let mut by_signature: std::collections::HashMap<String, String> =
            std::collections::HashMap::new();
        let mut components = 0usize;
        for (key, pose) in rows {
            let name = match names.get(&key) {
                Some(name) => name.clone(),
                None => {
                    let built = match self.document(key, ancestors) {
                        Ok(Some(built)) => built,
                        Ok(None) => continue,
                        Err(error) => {
                            self.failed_products += 1;
                            note(&mut self.first_error, error);
                            continue;
                        }
                    };
                    let serialized = built.1.to_string();
                    let signature = document_signature(&serialized);
                    let name = match by_signature.get(&signature) {
                        Some(name) => name.clone(),
                        None => {
                            // Charged HERE, at the embedding, because that is
                            // where a product stored once per level multiplies.
                            self.spend_bytes(serialized.len())?;
                            // Unique WITHIN this level's library — parent and
                            // child libraries are independent (build-spec §2.2),
                            // so a name taken upstairs is free down here.
                            let name = unique_entry_name(&library, &built.0);
                            // A nested child is a part like any other: it gets
                            // its own store document and a REAL sourceKey, so
                            // Open Part and update-components work the same way
                            // however deep it sits.
                            let source_key =
                                self.writer.key_for(&name, &serialized, &signature);
                            library.insert(
                                name.clone(),
                                serde_json::json!({
                                    "sourceKey": source_key,
                                    "sourceSignature": signature.clone(),
                                    "document": built.1,
                                    "snapshot": "",
                                }),
                            );
                            by_signature.insert(signature, name.clone());
                            name
                        }
                    };
                    names.insert(key, name.clone());
                    name
                }
            };
            let Ok(transform) = brep_kernel::AffineTransform::new(pose) else {
                note(
                    &mut self.first_error,
                    format!("sub-assembly '{name}': occurrence pose is not an affine"),
                );
                continue;
            };
            components += 1;
            features.push(serde_json::json!({
                "type": "ACOMP",
                "inputParams": {
                    // Its OWN counter, so the ids read `ACOMP1..n` whether or
                    // not this node also owns bodies. (The id must match
                    // `ACOMP<digits>`: it IS the namespace prefix.)
                    "id": format!("ACOMP{components}"),
                    "partName": name,
                    "transform": brep_kernel::transform_to_pose_params(&transform),
                    // Written EXPLICITLY rather than left to the kernel's
                    // auto-ground rule, which keys on ABSENCE: the first
                    // component of an assembly is grounded, and every other one
                    // must not be, or the next solve is over-constrained.
                    "isFixed": components == 1,
                },
                "persistentData": {},
            }));
        }

        // A node whose whole subtree failed to produce geometry places nothing.
        // Returning `None` rather than a feature-less document matters: an empty
        // document is a hard error inside `add_part_to_library`, which would turn
        // "there was nothing here" into "the import failed".
        if features.is_empty() {
            return Ok(None);
        }
        self.spend_entry()?;
        Ok(Some((
            part_name(node, self.doc_name),
            serde_json::json!({ "partsLibrary": library, "features": features }),
        )))
    }

    /// The child occurrences of `product`, as `(document key, pose)` rows in the
    /// kernel walk's order — ascending `nauo_ref`, with the same ancestor cycle
    /// guard. The pose is the occurrence's own child→parent placement: nesting
    /// is precisely what stops it having to be composed.
    fn place_children(
        &mut self,
        product: usize,
        ancestors: &[usize],
        rows: &mut Vec<(DocKey, Mat4)>,
        bakes: &mut usize,
    ) {
        let mut children: Vec<&brep_kernel::StepOccurrence> = self
            .assembly
            .occurrences
            .iter()
            .filter(|occurrence| occurrence.parent == product)
            .collect();
        children.sort_by_key(|occurrence| occurrence.nauo_ref);
        for occurrence in children {
            if ancestors.contains(&occurrence.child) {
                note(
                    &mut self.first_error,
                    format!(
                        "occurrence #{} closes a cycle in the product structure and was skipped",
                        occurrence.nauo_ref
                    ),
                );
                continue;
            }
            let child = &self.assembly.products[occurrence.child];
            let is_assembly = self
                .assembly
                .occurrences
                .iter()
                .any(|edge| edge.parent == occurrence.child);
            if occurrence.rigid {
                let key = if is_assembly {
                    DocKey::Assembly(occurrence.child)
                } else {
                    DocKey::Leaf((child.pd_ref, NO_FACTOR))
                };
                rows.push((key, occurrence.placement));
                continue;
            }
            // §3.4 on a single edge: a leaf bakes its non-rigid factor into its
            // own part, exactly as the flat lane does with the composed pose.
            match split_rigid(&occurrence.placement) {
                Ok((rigid, factor)) if is_identity(&factor) => {
                    let key = if is_assembly {
                        DocKey::Assembly(occurrence.child)
                    } else {
                        DocKey::Leaf((child.pd_ref, NO_FACTOR))
                    };
                    rows.push((key, rigid));
                }
                // A mirrored/scaled SUB-ASSEMBLY would have to push its factor
                // down through a whole document tree, rewriting every level's
                // poses. Nothing in the corpus does it, and a wrong answer here
                // would be a silently mis-handed assembly: skip and say so, so
                // the user can re-import flat (which bakes it correctly).
                Ok(_) if is_assembly => {
                    note(
                        &mut self.first_error,
                        format!(
                            "occurrence #{} places sub-assembly '{}' with a non-rigid transform, \
                             which a nested import cannot represent — import flat instead",
                            occurrence.nauo_ref,
                            part_name(child, self.doc_name)
                        ),
                    );
                }
                Ok((rigid, factor)) => {
                    *bakes += 1;
                    let key = (child.pd_ref, factor_key(&factor));
                    self.factors.insert(key, factor);
                    rows.push((DocKey::Leaf(key), rigid));
                }
                Err(error) => note(&mut self.first_error, error),
            }
        }
    }

    /// Charge one built part document against [`MAX_NESTED_ENTRIES`].
    fn spend_entry(&mut self) -> Result<(), String> {
        self.entries += 1;
        if self.entries > MAX_NESTED_ENTRIES {
            return Err(format!(
                "nested import: more than {MAX_NESTED_ENTRIES} distinct parts \
                 (import as bodies, or import flat)"
            ));
        }
        Ok(())
    }

    /// Charge one embedded part document against [`MAX_NESTED_BYTES`].
    fn spend_bytes(&mut self, bytes: usize) -> Result<(), String> {
        self.bytes = self.bytes.saturating_add(bytes);
        if self.bytes > MAX_NESTED_BYTES {
            return Err(format!(
                "nested import: the embedded sub-assembly documents exceed \
                 {} MB (import as bodies, or import flat)",
                MAX_NESTED_BYTES / (1024 * 1024)
            ));
        }
        Ok(())
    }
}

/// A part name not yet used in THIS level's library: `requested`, else
/// `requested-2`, `requested-3`, … — the kernel `parts_library::unique_name`
/// convention, applied to an embedded block the kernel never sees inserted.
fn unique_entry_name(library: &serde_json::Map<String, serde_json::Value>, requested: &str) -> String {
    if !library.contains_key(requested) {
        return requested.to_string();
    }
    (2..)
        .map(|counter| format!("{requested}-{counter}"))
        .find(|candidate| !library.contains_key(candidate))
        .expect("the counter loop is unbounded")
}

/// Keep the FIRST thing that went wrong (the report carries one, and the first
/// is the one that explains the rest).
fn note(slot: &mut Option<String>, error: String) {
    if slot.is_none() {
        *slot = Some(error);
    }
}

/// Encode one product as a parts-library entry and return the EFFECTIVE entry
/// name the instances must reference (`add_part_to_library` disambiguates a name
/// clash and REUSES an entry with identical content, which is where cross-import
/// dedup comes from).
///
/// `factor`, when present, is the non-rigid part of an occurrence's placement:
/// applied to the geometry HERE, so the instance can carry a rigid pose (§3.4).
fn build_library_entry(
    product: &brep_kernel::StepProduct,
    factor: Option<&Mat4>,
    doc_name: &str,
    writer: &mut PartWriter<'_>,
) -> Result<String, String> {
    let (name, document) = native_part_document(product, factor, doc_name)?;
    install_part(&name, &document, writer)
}

/// The §3.2 part document for one product's OWN bodies: ONE IMPORT3D whose only
/// input is the native payload, plus the library name it wants. No STEP text is
/// stored anywhere — a rebuild of this part is a base64 decode, not a re-parse.
///
/// `factor`, when present, is the non-rigid part of an occurrence's placement:
/// applied to the geometry HERE, so the instance can carry a rigid pose (§3.4).
///
/// Split out from [`build_library_entry`] because the nested lane needs the
/// DOCUMENT before it installs anything — a leaf's document is embedded in its
/// parent's `partsLibrary`, where there is no `add_part_to_library` to call.
/// One producer, so a leaf part is byte-identical however deep it lands.
fn native_part_document(
    product: &brep_kernel::StepProduct,
    factor: Option<&Mat4>,
    doc_name: &str,
) -> Result<(String, serde_json::Value), String> {
    let mut name = part_name(product, doc_name);
    let bodies = match factor {
        None => product.bodies.clone(),
        Some(factor) => {
            let transform = brep_kernel::AffineTransform::new(*factor)
                .map_err(|error| format!("part '{name}': non-rigid factor: {error}"))?;
            let mirrored = transform.determinant3() < 0.0;
            name.push_str(if mirrored { " (mirrored)" } else { " (scaled)" });
            product
                .bodies
                .iter()
                .map(|body| {
                    // A mirror MUST reverse orientation or `transform_brep`
                    // refuses it (an unreversed reflection inverts the solid).
                    brep_kernel::transform_brep(body, transform, mirrored)
                        .map_err(|error| format!("part '{name}': {error}"))
                })
                .collect::<Result<Vec<_>, _>>()?
        }
    };
    // The product's STEP colours ride into the payload with the geometry (the
    // snapshot captures the records the stamp writes), so a coloured part keeps
    // its colour through the parts library and every reload.
    let payload = brep_kernel::native_import_payload_with_appearance(
        "IMPORT3D1",
        &bodies,
        &product.appearances,
    )
    .map_err(|error| format!("part '{name}': {error}"))?;
    let document = serde_json::json!({
        "features": [{
            "type": "IMPORT3D",
            "inputParams": { "id": "IMPORT3D1", "nativeBrep": payload },
            "persistentData": {},
        }]
    });
    Ok((name, document))
}

/// Install a part document as a parts-library entry of the OPEN document and
/// return the EFFECTIVE entry name the instances must reference
/// (`add_part_to_library` disambiguates a name clash and REUSES an entry with
/// identical content, which is where cross-import dedup comes from).
///
/// The `sourceKey` comes from the [`PartSink`]: an imported part is written to
/// the store as its own document and carries a REAL key, exactly like a part
/// inserted from the parts library, so there is no second kind of part. A sink
/// that declines (no store, or a failed write) yields `""` — the embedded-only
/// entry this lane used to produce unconditionally, and the case
/// `UpdateComponents` already skips.
fn install_part(
    name: &str,
    document: &serde_json::Value,
    writer: &mut PartWriter<'_>,
) -> Result<String, String> {
    let document = document.to_string();
    let signature = document_signature(&document);
    let source_key = writer.key_for(name, &document, &signature);
    brep_kernel::add_part_to_library(name, &source_key, &signature, &document)
        .map_err(|error| format!("part '{name}': {error:?}"))
}

/// Where an imported assembly's unique parts are written, so each becomes a
/// document in its own right rather than a payload embedded in one assembly.
///
/// A trait, and not a `&dyn ModelStore`, because the store lives in `BREP_app`
/// and this crate is BELOW it — `BREP_app` depends on `BREP_render`, so naming
/// the store here would be a dependency cycle. The import therefore asks for a
/// key and the app answers with one, which is also what keeps the destination
/// (and any prompt for it) entirely the app's business.
pub trait PartSink {
    /// Store `document_json` under a name derived from `part_name` and return
    /// the stable key it can be read back by. `None` declines — no store, or a
    /// write that failed — and the entry stays embedded-only.
    fn store_part(&mut self, part_name: &str, document_json: &str) -> Option<String>;
}

/// The sink that stores nothing: every entry stays embedded-only. The default
/// for headless callers and tests, which have no store to write to.
pub struct EmbeddedOnly;

impl PartSink for EmbeddedOnly {
    fn store_part(&mut self, _part_name: &str, _document_json: &str) -> Option<String> {
        None
    }
}

/// A [`PartSink`] plus the CONTENT DEDUP that must ride with it.
///
/// `add_part_to_library` reuses an entry whose `(sourceKey, sourceSignature)`
/// both match, which is where §3.5's free dedup came from while every imported
/// part carried the same empty key. Give each part its own key and that reuse
/// stops: the same product under two `PRODUCT_DEFINITION`s would become two
/// entries AND two identical files.
///
/// So the dedup moves in front of the write, keyed on the document signature
/// alone. Identical content is written ONCE and every occurrence of it gets the
/// SAME key — which then makes `add_part_to_library`'s own `(key, signature)`
/// reuse fire exactly as before. Dedup ACROSS imports keeps working for the
/// same reason: a re-import derives the same file name, so the same key and
/// signature come back and the resident entry is reused.
struct PartWriter<'a> {
    sink: &'a mut dyn PartSink,
    by_signature: std::collections::HashMap<String, String>,
}

impl<'a> PartWriter<'a> {
    fn new(sink: &'a mut dyn PartSink) -> Self {
        Self {
            sink,
            by_signature: std::collections::HashMap::new(),
        }
    }

    /// The `sourceKey` for a part with this content — writing it exactly once
    /// however many products share it.
    fn key_for(&mut self, name: &str, document_json: &str, signature: &str) -> String {
        if let Some(key) = self.by_signature.get(signature) {
            return key.clone();
        }
        let key = self
            .sink
            .store_part(name, document_json)
            .unwrap_or_default();
        self.by_signature.insert(signature.to_string(), key.clone());
        key
    }
}

/// The library name for a product: its `PRODUCT.name`, else a stem built from
/// the imported document's name so an unnamed product is still identifiable.
fn part_name(product: &brep_kernel::StepProduct, doc_name: &str) -> String {
    let named = product.name.trim();
    if !named.is_empty() {
        return named.to_string();
    }
    match doc_name.trim() {
        "" => format!("part-{}", product.pd_ref),
        stem => format!("{stem}-part-{}", product.pd_ref),
    }
}

/// The dialog's counts, taken from the SAME walk the import runs, so the numbers
/// the user was shown are the numbers they get (bar an encode failure, and bar
/// the extra entry a non-rigid occurrence bakes).
pub(super) fn probe_counts(assembly: &brep_kernel::StepAssembly) -> StepAssemblyProbe {
    let mut parts = std::collections::HashSet::new();
    let mut instances = 0usize;
    let mut nested_depth = 0usize;
    for placed in compose_world_occurrences(assembly) {
        let product = &assembly.products[placed.product];
        if product.bodies.is_empty() {
            continue;
        }
        parts.insert(product.pd_ref);
        instances += 1;
        nested_depth = nested_depth.max(placed.depth);
    }
    StepAssemblyProbe {
        parts: parts.len(),
        instances,
        nested_depth,
    }
}

/// Depth-first from the roots, composing each occurrence's child→parent
/// placement into a world transform — the consumer half of `read_step_assembly`,
/// which deliberately transforms nothing.
///
/// Emit order, child ordering (by `nauo_ref`) and the ancestor cycle guard mirror
/// the kernel's own `walk_occurrences`, which is what makes the components this
/// lane produces the same solids, in the same order, as the flat lane's — the
/// kernel asserts that equivalence BIT-for-bit
/// (`step_import/tests/assembly_structure.rs`), and
/// `structured_import_matches_the_flat_lane_geometry` below re-asserts it from
/// this side, where a divergence would actually land.
fn compose_world_occurrences(assembly: &brep_kernel::StepAssembly) -> Vec<PlacedProduct> {
    struct Node {
        placed: PlacedProduct,
        ancestors: Vec<usize>,
    }
    let mut out = Vec::new();
    let mut stack: Vec<Node> = assembly
        .roots
        .iter()
        .rev()
        .map(|&product| Node {
            placed: PlacedProduct {
                product,
                world: MAT4_IDENTITY,
                depth: 0,
                rigid_path: true,
            },
            ancestors: vec![product],
        })
        .collect();
    while let Some(node) = stack.pop() {
        let (product, world, depth, rigid_path) = (
            node.placed.product,
            node.placed.world,
            node.placed.depth,
            node.placed.rigid_path,
        );
        out.push(node.placed);
        let mut children: Vec<&brep_kernel::StepOccurrence> = assembly
            .occurrences
            .iter()
            .filter(|occurrence| occurrence.parent == product)
            .collect();
        children.sort_by_key(|occurrence| occurrence.nauo_ref);
        for occurrence in children.into_iter().rev() {
            if node.ancestors.contains(&occurrence.child) {
                continue; // the cycle guard the kernel's walk applies
            }
            let mut ancestors = node.ancestors.clone();
            ancestors.push(occurrence.child);
            stack.push(Node {
                placed: PlacedProduct {
                    product: occurrence.child,
                    world: mat4_mul(&world, &occurrence.placement),
                    depth: depth + 1,
                    // The kernel's per-edge rigidity flag, carried down the path:
                    // a composed pose is a component pose only when every edge
                    // on the way to it was one.
                    rigid_path: rigid_path && occurrence.rigid,
                },
                ancestors,
            });
        }
    }
    out
}

const MAT4_IDENTITY: Mat4 = [
    1.0, 0.0, 0.0, 0.0, //
    0.0, 1.0, 0.0, 0.0, //
    0.0, 0.0, 1.0, 0.0, //
    0.0, 0.0, 0.0, 1.0,
];

/// Row-major 4×4 product `a · b`.
fn mat4_mul(a: &Mat4, b: &Mat4) -> Mat4 {
    let mut out = [0.0; 16];
    for row in 0..4 {
        for column in 0..4 {
            out[row * 4 + column] = (0..4)
                .map(|k| a[row * 4 + k] * b[k * 4 + column])
                .sum();
        }
    }
    out
}

/// Split a non-rigid world placement into `world = rigid · factor`, where
/// `rigid` is a component pose (rotation + translation, det +1) and `factor` is
/// a purely linear residue carrying the mirror/scale/shear.
///
/// Gram-Schmidt on the linear block's columns gives `A = Q·U` with `U` upper
/// triangular and positively-diagonalled; when `Q` came out left-handed the pair
/// is re-signed through `D = diag(-1, 1, 1)` (`Q' = Q·D`, `U' = D·U`, still
/// `Q'U' = A`) so the ROTATION is a rotation and the reflection rides in the
/// factor. A mirror composed with a rotation therefore yields the same factor
/// whatever the rotation, which keeps every such instance on ONE baked part.
fn split_rigid(world: &Mat4) -> Result<(Mat4, Mat4), String> {
    let column = |index: usize| [world[index], world[4 + index], world[8 + index]];
    let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
    let axpy = |a: [f64; 3], scale: f64, b: [f64; 3]| {
        [a[0] - scale * b[0], a[1] - scale * b[1], a[2] - scale * b[2]]
    };
    let (a1, a2, a3) = (column(0), column(1), column(2));

    let r11 = dot(a1, a1).sqrt();
    let mut q1 = normalize(a1, r11)?;
    let r12 = dot(q1, a2);
    let v2 = axpy(a2, r12, q1);
    let r22 = dot(v2, v2).sqrt();
    let q2 = normalize(v2, r22)?;
    let r13 = dot(q1, a3);
    let r23 = dot(q2, a3);
    let v3 = axpy(axpy(a3, r13, q1), r23, q2);
    let r33 = dot(v3, v3).sqrt();
    let q3 = normalize(v3, r33)?;

    // det Q = q1 · (q2 × q3); -1 means Q is a reflection, not a rotation.
    let cross = [
        q2[1] * q3[2] - q2[2] * q3[1],
        q2[2] * q3[0] - q2[0] * q3[2],
        q2[0] * q3[1] - q2[1] * q3[0],
    ];
    let (mut r11, mut r12, mut r13) = (r11, r12, r13);
    if dot(q1, cross) < 0.0 {
        q1 = [-q1[0], -q1[1], -q1[2]];
        r11 = -r11;
        r12 = -r12;
        r13 = -r13;
    }
    let rigid = [
        q1[0], q2[0], q3[0], world[3], //
        q1[1], q2[1], q3[1], world[7], //
        q1[2], q2[2], q3[2], world[11], //
        0.0, 0.0, 0.0, 1.0,
    ];
    let factor = [
        r11, r12, r13, 0.0, //
        0.0, r22, r23, 0.0, //
        0.0, 0.0, r33, 0.0, //
        0.0, 0.0, 0.0, 1.0,
    ];
    Ok((rigid, factor))
}

/// Unit vector, or a clear error for the degenerate column a near-singular
/// placement produces (skipped and counted, never fatal).
fn normalize(vector: [f64; 3], length: f64) -> Result<[f64; 3], String> {
    if !(length > 1e-12) || !length.is_finite() {
        return Err("occurrence placement is singular (a degenerate axis)".into());
    }
    Ok([vector[0] / length, vector[1] / length, vector[2] / length])
}

/// Is this affine the identity to 1e-9 — the tolerance the kernel's own
/// rigidity gate uses?
fn is_identity(matrix: &Mat4) -> bool {
    matrix
        .iter()
        .zip(MAT4_IDENTITY.iter())
        .all(|(value, want)| (value - want).abs() <= 1e-9)
}

/// The linear block of a baked factor as an exact bit key — two occurrences
/// share a baked part only when their factor is bit-identical, so a wrong-handed
/// reuse is not reachable through rounding.
fn factor_key(factor: &Mat4) -> [u64; 9] {
    let mut key = [0u64; 9];
    for (slot, index) in key.iter_mut().zip([0, 1, 2, 4, 5, 6, 8, 9, 10]) {
        *slot = factor[index].to_bits();
    }
    key
}

// BREP private tests: 442bc619b216060d