s23dr
hoho22k
research-only
non-commercial
File size: 56,949 Bytes
2c43fda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac5a5b5
 
2c43fda
ac5a5b5
 
2c43fda
 
 
ac5a5b5
 
2c43fda
ac5a5b5
2c43fda
ac5a5b5
 
2c43fda
 
ac5a5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c43fda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac5a5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c43fda
 
 
ac5a5b5
2c43fda
 
 
ac5a5b5
2c43fda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac5a5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c43fda
 
 
ac5a5b5
2c43fda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac5a5b5
 
2c43fda
ac5a5b5
 
 
 
 
2c43fda
ac5a5b5
 
 
2c43fda
ac5a5b5
 
 
 
2c43fda
ac5a5b5
 
 
 
 
 
 
 
 
 
2c43fda
ac5a5b5
 
 
2c43fda
ac5a5b5
 
 
 
 
 
 
 
2c43fda
ac5a5b5
 
 
 
 
 
 
 
2c43fda
 
ac5a5b5
 
2c43fda
 
ac5a5b5
 
 
 
 
 
 
 
 
 
2c43fda
 
ac5a5b5
 
2c43fda
 
ac5a5b5
 
 
 
 
2c43fda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac5a5b5
2c43fda
 
 
ac5a5b5
 
 
2c43fda
 
 
 
 
 
ac5a5b5
2c43fda
ac5a5b5
 
 
 
 
2c43fda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac5a5b5
2c43fda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac5a5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c43fda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac5a5b5
 
2c43fda
ac5a5b5
2c43fda
ac5a5b5
 
 
 
 
 
 
2c43fda
 
ac5a5b5
2c43fda
 
ac5a5b5
2c43fda
 
 
 
ac5a5b5
 
 
2c43fda
ac5a5b5
2c43fda
 
 
 
ac5a5b5
 
 
 
2c43fda
 
 
ac5a5b5
 
 
2c43fda
ac5a5b5
 
 
 
 
2c43fda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac5a5b5
2c43fda
 
 
 
 
 
 
 
 
 
 
 
 
 
932f501
2c43fda
ac5a5b5
 
932f501
 
2c43fda
932f501
ac5a5b5
 
 
2c43fda
932f501
ac5a5b5
932f501
ac5a5b5
 
2c43fda
 
 
 
 
932f501
2c43fda
932f501
ac5a5b5
 
2c43fda
 
932f501
 
 
 
 
 
 
 
2c43fda
ac5a5b5
 
 
 
2c43fda
ac5a5b5
 
 
2c43fda
ac5a5b5
 
 
 
 
 
 
 
 
2c43fda
 
ac5a5b5
 
 
 
 
 
 
932f501
 
 
 
ac5a5b5
 
932f501
 
 
 
 
 
2c43fda
ac5a5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
932f501
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac5a5b5
932f501
 
 
ac5a5b5
 
932f501
 
 
 
 
2c43fda
ac5a5b5
 
2c43fda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
932f501
 
 
2c43fda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac5a5b5
 
 
2c43fda
 
 
 
 
 
 
 
 
 
 
 
 
 
932f501
 
 
ac5a5b5
 
932f501
 
2c43fda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
932f501
 
 
 
 
ac5a5b5
2c43fda
 
932f501
2c43fda
 
 
 
 
 
 
ac5a5b5
 
 
2c43fda
 
ac5a5b5
2c43fda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
932f501
2c43fda
 
 
 
 
 
 
 
 
 
 
 
 
932f501
 
 
 
 
 
 
 
 
ac5a5b5
932f501
 
 
 
 
 
2c43fda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Scene feature point cloud builder from raw HoHo dataset samples.

V10 cache layout (additions over v7):
  - per-point RGB feature `scene_rgb` (uint8, 0..255):
      * COLMAP points use `point3D.color` from the COLMAP record
      * depth-unprojected points inherit the colour of their nearest COLMAP
        neighbour in raw-world space (no raw images are released)
      * camera tokens use a sentinel (0, 0, 0)
  - metric voxel downsampling across ALL candidate points (COLMAP + depth +
    camera) before the Tier-1/Tier-2 budget cap. At most one random point is
    kept per `voxel_size_m`-side voxel in raw world coordinates. Set
    `voxel_size_m <= 0` to disable.

Inherited from v7:
  - robust normalisation (median centre + P95 scale on COLMAP+camera union)
  - bbox_R kept identity (random yaw is applied as data augmentation in the loader)
  - separate per-point geometric and semantic confidence channels
  - soft top-2 gestalt labels (`scene_gestalt_ids`/`scene_gestalt_id2` + `scene_gestalt_w1`)
  - 3x3 majority gestalt/ADE projection on COLMAP points
  - fixed split: 4096 COLMAP/camera tokens + 4096 depth-unprojected tokens
  - camera tokens live only in the COLMAP half (type=2, Tier 0)
  - Tier 1 structural Gestalt classes are preferred before weaker Tier 2 classes
  - Tier 2 points require an ADE house/foreground label
  - hard skip on empty COLMAP / missing cam metadata / ambiguous image matches
"""
import ctypes
import functools
import io
import zipfile
from dataclasses import dataclass
from typing import Optional, Tuple

import numpy as np
import pyarrow as pa
import pyarrow.compute as pc
from PIL import Image
from scipy.spatial import cKDTree

from hoho2025.color_mappings import ade20k_color_mapping as _HOHO_ADE_COLORS
from hoho2025.example_solutions import fit_scale_robust_median
from color_mappings import ade20k_color_mapping, gestalt_color_mapping


# ------------------------------------------------------------------
# COLMAP text reconstruction (colmap.zip bytes) -> plain NumPy arrays
# ------------------------------------------------------------------
# pycolmap keeps points3D / images in std::unordered_map (libstdc++), and the
# baseline iterates them in that map's order: downstream RNG picks, the
# sparse-depth "last write wins" splat and the voxel tie-breaks depend on it.
# We parse the text files in file (= insertion) order and reproduce the
# map's iteration order with the libstdc++ bucket rules; the rehash policy
# itself (bucket counts) is called from the loaded libstdc++.

class _RehashPolicy(ctypes.Structure):  # std::__detail::_Prime_rehash_policy
    _fields_ = [("max_load_factor", ctypes.c_float), ("next_resize", ctypes.c_size_t)]


class _NeedRehash(ctypes.Structure):  # std::pair<bool, std::size_t>
    _fields_ = [("rehash", ctypes.c_bool), ("n_bkt", ctypes.c_size_t)]


@functools.cache
def _need_rehash():
    """libstdc++ ``_Prime_rehash_policy::_M_need_rehash``; looked up on first use of order="pycolmap"."""
    fn = ctypes.CDLL("libstdc++.so.6")._ZNKSt8__detail20_Prime_rehash_policy14_M_need_rehashEmmm
    fn.restype = _NeedRehash
    fn.argtypes = [ctypes.POINTER(_RehashPolicy), ctypes.c_size_t, ctypes.c_size_t, ctypes.c_size_t]
    return fn


def _unordered_map_order(keys: np.ndarray) -> np.ndarray:
    """Permutation of `keys` (given in insertion order) into the iteration order of a
    libstdc++ ``std::unordered_map`` with identity hash filled by one emplace per key.

    Between two rehashes the bucket list is fully described by node timestamps
    (rehash walk position, then insertion order): a node landing in an empty bucket
    is pushed to the global front, otherwise to the front of its bucket's group. So
    groups are ordered by creation time descending and nodes inside a group by
    timestamp descending.
    """
    keys = np.asarray(keys, dtype=np.int64)
    policy = _RehashPolicy(1.0, 0)
    order = np.zeros(0, dtype=np.int64)
    n_bkt, n_elt = 1, 0
    while n_elt < len(keys):  # here n_elt + 1 > policy.next_resize, so the policy is consulted
        res = _need_rehash()(ctypes.byref(policy), n_bkt, n_elt, 1)
        assert res.rehash, "libstdc++ grew next_resize without a rehash; order emulation does not cover this"
        n_bkt = res.n_bkt
        stop = min(len(keys), policy.next_resize)
        nodes = np.concatenate([order, np.arange(n_elt, stop)])
        _, first, inv = np.unique(keys[nodes] % n_bkt, return_index=True, return_inverse=True)
        order = nodes[np.lexsort((-np.arange(len(nodes)), -first[inv]))]
        n_elt = stop
    return order


@dataclass
class ColmapCamera:
    camera_id: int
    model: str
    width: int
    height: int
    params: np.ndarray  # float64

    # COLMAP focal / principal-point parameter indices per camera model.
    _FOCAL_PP = {
        "SIMPLE_PINHOLE": (0, 0, 1, 2), "PINHOLE": (0, 1, 2, 3),
        "SIMPLE_RADIAL": (0, 0, 1, 2), "RADIAL": (0, 0, 1, 2),
        "OPENCV": (0, 1, 2, 3), "FULL_OPENCV": (0, 1, 2, 3),
    }

    def calibration_matrix(self) -> np.ndarray:
        fx, fy, cx, cy = (self.params[j] for j in self._FOCAL_PP[self.model])
        return np.array([[fx, 0.0, cx], [0.0, fy, cy], [0.0, 0.0, 1.0]], dtype=np.float64)


@dataclass
class ColmapImage:
    image_id: int
    name: str
    camera_id: int
    R: np.ndarray  # (3, 3) float64 cam_from_world rotation
    t: np.ndarray  # (3,) float64 cam_from_world translation


@dataclass
class ColmapRec:
    """Picklable stand-in for the parts of ``pycolmap.Reconstruction`` used here.

    Point arrays are in pycolmap's ``points3D`` iteration order; ``images`` is a dict
    in pycolmap's ``images`` iteration order and ``observed[j]`` is the boolean mask of
    points whose track contains the j-th image (== pycolmap ``Image.has_point3D``).
    """
    point_ids: np.ndarray  # (N,) int64
    xyz: np.ndarray        # (N, 3) float64
    rgb: np.ndarray        # (N, 3) uint8
    error: np.ndarray      # (N,) float64
    track_len: np.ndarray  # (N,) int64
    observed: np.ndarray   # (n_images, N) bool
    images: dict
    cameras: dict

    def observed_mask(self, image_id: int) -> np.ndarray:
        return self.observed[list(self.images).index(image_id)]

    def num_points3D(self) -> int:  # pycolmap.Reconstruction API (read by tools/infer_bench.py)
        return len(self.point_ids)

    def num_images(self) -> int:
        return len(self.images)


def _quat_to_rotmat(qw: float, qx: float, qy: float, qz: float) -> np.ndarray:
    """Eigen ``Quaterniond::toRotationMatrix`` with the same float64 operation order."""
    tx, ty, tz = 2.0 * qx, 2.0 * qy, 2.0 * qz
    twx, twy, twz = tx * qw, ty * qw, tz * qw
    txx, txy, txz = tx * qx, ty * qx, tz * qx
    tyy, tyz, tzz = ty * qy, tz * qy, tz * qz
    return np.array([
        [1.0 - (tyy + tzz), txy - twz, txz + twy],
        [txy + twz, 1.0 - (txx + tzz), tyz - twx],
        [txz - twy, tyz + twx, 1.0 - (txx + tyy)],
    ], dtype=np.float64)


def _header_end(buf: bytes) -> int:
    """Offset of the first line after the leading '#' comment lines."""
    pos = 0
    while buf.startswith(b"#", pos):
        pos = buf.index(b"\n", pos) + 1
    return pos


def _cast_tokens(buf: bytes, start: np.ndarray, end: np.ndarray, dtype) -> np.ndarray:
    """Parse the tokens buf[start[i]:end[i]] (ascending, disjoint) as `dtype` (pa.int64() /
    pa.float64()). Arrow's string cast parses floats with fast_float, i.e. correctly rounded,
    the same doubles COLMAP's own parser produces; malformed tokens raise."""
    off = np.empty(2 * len(start), dtype=np.int32)  # values alternate token / gap to the next token
    off[0::2], off[1::2] = start, end
    arr = pa.StringArray.from_buffers(max(len(off) - 1, 0), pa.py_buffer(off), pa.py_buffer(buf))
    return pc.cast(pc.take(arr, np.arange(0, len(off) - 1, 2)), dtype).to_numpy()


def _parse_points3D(buf: bytes):
    """points3D.txt -> (ids, xyz, rgb, error, track_len, obs_point, obs_image) in file order,
    obs_* listing every track element (point index, image id).

    Expects COLMAP's writer format (single spaces, '\\n' after every line); anything else
    fails an assertion or the token cast.
    """
    pos = _header_end(buf)
    if pos == len(buf):  # no points
        z = np.zeros(0, dtype=np.int64)
        return z, np.zeros((0, 3)), np.zeros((0, 3), dtype=np.uint8), np.zeros(0), z, z, z
    assert buf.endswith(b"\n"), "points3D.txt must end with a newline"
    b = np.frombuffer(buf, dtype=np.uint8)
    is_nl = b == 10
    sep = pos + np.flatnonzero(is_nl[pos:] | (b[pos:] == 32))
    tok_start = np.concatenate([[pos], sep[:-1] + 1])
    assert (sep > tok_start).all(), "empty token in points3D.txt"
    line_last = np.flatnonzero(is_nl[sep])
    line_first = np.concatenate([[0], line_last[:-1] + 1])
    n_tok = line_last - line_first + 1
    assert ((n_tok >= 8) & ((n_tok - 8) % 2 == 0)).all(), "malformed points3D.txt line"
    track_len = (n_tok - 8) // 2
    obs_point = np.repeat(np.arange(len(line_first)), track_len)
    k = np.arange(len(obs_point)) - np.repeat(np.cumsum(track_len) - track_len, track_len)

    # token index sets, each ascending: [ID R G B], [X Y Z ERROR], track IMAGE_IDs
    cast = lambda tok, dtype: _cast_tokens(buf, tok_start[tok], sep[tok], dtype)
    n = len(line_first)
    head = cast((line_first[:, None] + [0, 4, 5, 6]).ravel(), pa.int64()).reshape(n, 4)
    vals = cast((line_first[:, None] + [1, 2, 3, 7]).ravel(), pa.float64()).reshape(n, 4)
    obs_image = cast(line_first[obs_point] + 8 + 2 * k, pa.int64())
    assert ((head[:, 1:] >= 0) & (head[:, 1:] <= 255)).all()
    return head[:, 0], vals[:, :3], head[:, 1:].astype(np.uint8), vals[:, 3], track_len, obs_point, obs_image


def _image_header_lines(buf: bytes) -> list[bytes]:
    """images.txt: the first line of every image (the second one lists its POINTS2D)."""
    pos, out = _header_end(buf), []
    while pos < len(buf):
        end = buf.index(b"\n", pos)
        out.append(buf[pos:end])
        nl = buf.find(b"\n", end + 1)
        pos = len(buf) if nl < 0 else nl + 1
    return out


COLMAP_ORDERS = ("pycolmap", "file")


def read_colmap_zip(colmap_bytes: bytes, order: str) -> ColmapRec:
    """Drop-in for hoho2025 ``read_colmap_rec`` returning a picklable :class:`ColmapRec`.

    ``order`` sets the point / image order of the record, which downstream RNG picks,
    tie-breaks and the sparse-depth splat follow:
      - "pycolmap": pycolmap's libstdc++ hash-map iteration order (bit-identical to the
        released pipeline; needs libstdc++ at runtime);
      - "file": points3D.txt / images.txt file order (portable).
    """
    if order not in COLMAP_ORDERS:
        raise ValueError(f"order must be one of {COLMAP_ORDERS}, got {order!r}")
    map_order = _unordered_map_order if order == "pycolmap" else lambda keys: np.arange(len(keys))
    with zipfile.ZipFile(io.BytesIO(colmap_bytes)) as zf:
        files = {name: zf.read(name) for name in ("cameras.txt", "images.txt", "points3D.txt")}

    cameras = {}
    cam_buf = files["cameras.txt"]
    for line in cam_buf[_header_end(cam_buf):].split(b"\n"):
        if line:
            tok = line.split()
            cameras[int(tok[0])] = ColmapCamera(
                int(tok[0]), tok[1].decode(), int(tok[2]), int(tok[3]),
                np.array([float(x) for x in tok[4:]], dtype=np.float64),
            )

    images = []
    for line in _image_header_lines(files["images.txt"]):
        tok = line.split()
        assert len(tok) == 10, "image names with spaces are not supported"
        q = [float(x) for x in tok[1:5]]
        images.append(ColmapImage(
            int(tok[0]), tok[9].decode(), int(tok[8]),
            _quat_to_rotmat(*q), np.array([float(x) for x in tok[5:8]], dtype=np.float64),
        ))
    images = [images[i] for i in map_order(np.array([im.image_id for im in images], dtype=np.int64))]

    ids, xyz, rgb, err, tlen, obs_point, obs_image = _parse_points3D(files["points3D.txt"])
    perm = map_order(ids)
    row_of = np.empty_like(perm)
    row_of[perm] = np.arange(len(perm))
    # Track elements -> (image, point) mask. Elements naming an image absent from
    # images.txt cannot be queried through any image, as with pycolmap.
    image_ids = np.array([im.image_id for im in images], dtype=np.int64)
    by_id = np.argsort(image_ids)
    j = np.minimum(np.searchsorted(image_ids[by_id], obs_image), len(image_ids) - 1)
    known = image_ids[by_id][j] == obs_image
    observed = np.zeros((len(images), len(ids)), dtype=bool)
    observed[by_id[j[known]], row_of[obs_point[known]]] = True
    return ColmapRec(
        point_ids=ids[perm], xyz=xyz[perm], rgb=rgb[perm], error=err[perm], track_len=tlen[perm],
        observed=observed, images={im.image_id: im for im in images}, cameras=cameras,
    )

# ------------------------------------------------------------------
# Gestalt / ADE20K palette — packed int32 LUTs built once at import time.
# ------------------------------------------------------------------
GESTALT_CLASSES = list(gestalt_color_mapping.keys())  # 28 classes, order = ID
ADE20K_CLASSES = list(ade20k_color_mapping.keys())


def _build_palette_lut(color_mapping, start_id: int = 0):
    """Return (packed_sorted, ids_sorted) arrays for searchsorted lookup."""
    colors = np.array([rgb for _, rgb in color_mapping.items()], dtype=np.int32)
    packed = (colors[:, 0] << 16) | (colors[:, 1] << 8) | colors[:, 2]
    ids = np.arange(start_id, start_id + len(packed), dtype=np.int64)
    order = np.argsort(packed)
    return packed[order], ids[order]


_GESTALT_PACKED_S, _GESTALT_IDS_S = _build_palette_lut(gestalt_color_mapping, start_id=0)
_ADE_PACKED_S, _ADE_IDS_S = _build_palette_lut(ade20k_color_mapping, start_id=1)


# Class-id lookup: an RGB pixel's key is the little-endian uint32 of its bytes masked
# to 24 bits (R | G << 8 | B << 16); a dense 2^24 uint8 table maps key -> class id.

def _rgb_key(rgb: np.ndarray) -> np.ndarray:
    """(..., 3) uint8 -> (...) int64 key R | G << 8 | B << 16."""
    rgb = rgb.astype(np.int64)
    return rgb[..., 0] | (rgb[..., 1] << 8) | (rgb[..., 2] << 16)


def _rgb_key_view(rgb: np.ndarray) -> np.ndarray:
    """Flat (H*W,) uint32 view whose low 24 bits are the pixel keys (top byte = next pixel's R)."""
    buf = np.empty(rgb.size + 1, dtype=np.uint8)  # one pad byte for the last pixel's 4-byte read
    buf[:-1] = rgb.reshape(-1)
    return np.ndarray((rgb.size // 3,), dtype="<u4", buffer=buf, strides=(3,))


def _palette_lut(packed_sorted: np.ndarray, ids_sorted: np.ndarray) -> np.ndarray:
    """Key -> class-id table (0 = colour not in the palette). A colour listed twice maps
    to the id at its leftmost sorted position, which the former searchsorted lookup returned."""
    assert ids_sorted.max() < 256
    uniq, first = np.unique(packed_sorted, return_index=True)
    lut = np.zeros(1 << 24, dtype=np.uint8)
    lut[_rgb_key(np.stack([uniq >> 16, (uniq >> 8) & 255, uniq & 255], axis=1))] = ids_sorted[first]
    return lut


_GESTALT_LUT = _palette_lut(_GESTALT_PACKED_S, _GESTALT_IDS_S)
_ADE_LUT = _palette_lut(_ADE_PACKED_S, _ADE_IDS_S)


def _img_ids(rgb: np.ndarray, lut: np.ndarray) -> np.ndarray:
    """(H, W) uint8 class-id map of an RGB label image."""
    return lut[_rgb_key_view(rgb) & 0xFFFFFF].reshape(rgb.shape[:2])


def gestalt_img_to_ids(gest_np: np.ndarray) -> np.ndarray:
    return _img_ids(np.ascontiguousarray(gest_np, dtype=np.uint8), _GESTALT_LUT).astype(np.int64)


def ade20k_img_to_ids(ade_np: np.ndarray) -> np.ndarray:
    return _img_ids(np.ascontiguousarray(ade_np, dtype=np.uint8), _ADE_LUT).astype(np.int64)


def _ids_from_names(names: tuple[str, ...], all_names: list[str], start_id: int = 0) -> frozenset:
    return frozenset(start_id + all_names.index(name) for name in names if name in all_names)


# Gestalt classes used in the fixed-budget scene cache.  The user-facing
# "flashing_end" and "transition line" names correspond to palette keys
# "flashing_end_point" and "transition_line" in this codebase.
GESTALT_TIER1_NAMES = (
    "apex",
    "eave_end_point",
    "flashing_end_point",
    "eave",
    "ridge",
    "rake",
    "valley",
)
GESTALT_TIER2_NAMES = (
    "ground_line",
    "flashing",
    "step_flashing",
    "hip",
    "fascia",
    "transition_line",
)

TIER1_GESTALT_IDS: frozenset = _ids_from_names(GESTALT_TIER1_NAMES, GESTALT_CLASSES)
TIER2_GESTALT_IDS: frozenset = _ids_from_names(GESTALT_TIER2_NAMES, GESTALT_CLASSES)
PRIORITY_GESTALT_IDS: frozenset = TIER1_GESTALT_IDS | TIER2_GESTALT_IDS

_TIER1_GESTALT_ARR = np.array(sorted(TIER1_GESTALT_IDS), dtype=np.int64)
_TIER2_GESTALT_ARR = np.array(sorted(TIER2_GESTALT_IDS), dtype=np.int64)
_PRIORITY_GESTALT_ARR = np.array(sorted(PRIORITY_GESTALT_IDS), dtype=np.int64)

ADE_HOUSE_FOREGROUND_NAMES = (
    "wall",
    "building;edifice",
    "windowpane;window",
    "door;double;door",
    "house",
    "column;pillar",
    "skyscraper",
    "stairs;steps",
)
ADE_HOUSE_FOREGROUND_IDS: frozenset = _ids_from_names(
    ADE_HOUSE_FOREGROUND_NAMES, ADE20K_CLASSES, start_id=1,
)


def _id_table(ids) -> np.ndarray:
    """Boolean membership table over class ids 0..255 (== np.isin on id maps)."""
    table = np.zeros(256, dtype=bool)
    table[np.asarray(sorted(ids), dtype=np.int64)] = True
    return table


_TIER1_BY_ID = _id_table(TIER1_GESTALT_IDS)
_TIER2_BY_ID = _id_table(TIER2_GESTALT_IDS)
_HOUSE_FG_BY_ID = _id_table(ADE_HOUSE_FOREGROUND_IDS)

# hoho2025 ``get_house_mask`` (depth-scale fitting) matches these five ADE colours
# from hoho's own palette. The mask is a function of our ADE id map only if every
# palette colour's id determines its membership; checked here once.
_ADE_KEYS = _rgb_key(np.array(list(ade20k_color_mapping.values()), dtype=np.uint8))
_HOHO_HOUSE_KEYS = _rgb_key(np.array([_HOHO_ADE_COLORS[c] for c in (
    "wall", "house", "building;edifice", "door;double;door", "windowpane;window")], dtype=np.uint8))
_HOHO_HOUSE_BY_ID = _id_table(_ADE_LUT[_HOHO_HOUSE_KEYS].tolist())
assert not _HOHO_HOUSE_BY_ID[0] and np.array_equal(
    _HOHO_HOUSE_BY_ID[_ADE_LUT[_ADE_KEYS]], np.isin(_ADE_KEYS, _HOHO_HOUSE_KEYS))


def _ade_house_foreground_mask(ade_ids: np.ndarray) -> np.ndarray:
    return _HOUSE_FG_BY_ID[ade_ids]


# ------------------------------------------------------------------
# Image decode + COLMAP plumbing
# ------------------------------------------------------------------

def _image_to_rgb_array(img_like) -> np.ndarray:
    if isinstance(img_like, np.ndarray):
        arr = img_like
    elif isinstance(img_like, dict) and img_like.get("bytes") is not None:
        arr = np.array(Image.open(io.BytesIO(img_like["bytes"])).convert("RGB"))
    elif hasattr(img_like, "convert"):
        arr = np.array(img_like.convert("RGB"))
    else:
        arr = np.array(img_like)

    if arr.ndim == 2:
        arr = np.repeat(arr[..., None], 3, axis=-1)
    if arr.shape[-1] > 3:
        arr = arr[..., :3]
    return arr.astype(np.uint8, copy=False)


def _image_to_pil(img_like):
    """Decode image-like dataset values while preserving depth image modes."""
    if isinstance(img_like, Image.Image):
        return img_like
    if isinstance(img_like, dict) and img_like.get("bytes") is not None:
        img = Image.open(io.BytesIO(img_like["bytes"]))
        img.load()
        return img
    if isinstance(img_like, np.ndarray):
        return Image.fromarray(img_like)
    return img_like


class SampleImages:
    """Per-sample image access; every image is decoded and converted at most once.

    Accepts the dataset's values: PIL image, ``{"bytes": png}`` or a decoded ndarray
    ((H, W, 3) uint8 for gestalt / ADE, ``np.asarray(pil)`` for depth). PIL label images
    must be mode RGB (the hoho2025 house mask reads their raw array); their pixel keys
    come straight from PIL's 4-byte pixel storage (``tobytes("raw", "RGBX")``).
    """

    def __init__(self, sample: dict):
        self.sample = sample
        self._memo: dict = {}

    def _get(self, key, make):
        if key not in self._memo:
            self._memo[key] = make()
        return self._memo[key]

    def label(self, kind: str, i: int):
        """Gestalt / ADE image as PIL (mode RGB) or (H, W, 3) uint8 ndarray; None if missing."""
        def make():
            v = self.sample[kind][i]
            if v is None or isinstance(v, np.ndarray):
                return v
            img = _image_to_pil(v)
            assert img.mode == "RGB", f"{kind} image {i} has mode {img.mode}, expected RGB"
            return img
        return self._get((kind, i), make)

    def shape(self, kind: str, i: int) -> tuple[int, int]:
        v = self.label(kind, i)
        return v.shape[:2] if isinstance(v, np.ndarray) else v.size[::-1]

    def keys(self, kind: str, i: int) -> np.ndarray:
        """(H*W,) uint32 pixel keys; the low 24 bits are R | G << 8 | B << 16."""
        def make():
            v = self.label(kind, i)
            if isinstance(v, np.ndarray):
                return _rgb_key_view(v)
            return np.frombuffer(v.tobytes("raw", "RGBX"), dtype="<u4")
        return self._get((kind + "_keys", i), make)

    def ids(self, kind: str, i: int) -> np.ndarray:
        """Full-resolution (H, W) uint8 class-id map of a gestalt / ADE image."""
        lut = _GESTALT_LUT if kind == "gestalt" else _ADE_LUT
        return self._get((kind + "_ids", i),
                         lambda: lut[self.keys(kind, i) & 0xFFFFFF].reshape(self.shape(kind, i)))

    def depth(self, i: int) -> np.ndarray:
        return self._get(("depth", i), lambda: np.asarray(_image_to_pil(self.sample["depth"][i])))


def _camera_for_image(colmap_rec: ColmapRec, col_img: ColmapImage) -> ColmapCamera:
    return colmap_rec.cameras[col_img.camera_id]


def _cam_matrix_from_image(img: ColmapImage):
    """(R, t) float64 copies, as hoho2025 ``_cam_matrix_from_image`` returns them."""
    return np.array(img.R, dtype=np.float64), np.array(img.t, dtype=np.float64)


# ------------------------------------------------------------------
# COLMAP point + confidence extraction
# ------------------------------------------------------------------

def colmap_points_full(colmap_rec: ColmapRec):
    """Return (ids, xyz, track_len, reproj_err, rgb) for all COLMAP 3D points.

    `xyz`, `track_len`, `reproj_err` are float32; `rgb` is uint8 (N, 3) from each
    point's COLMAP colour.
    """
    return (
        colmap_rec.point_ids,
        colmap_rec.xyz.astype(np.float32),
        colmap_rec.track_len.astype(np.float32),
        colmap_rec.error.astype(np.float32),
        colmap_rec.rgb,
    )


def voxel_downsample_indices(
    xyz: np.ndarray,
    voxel_size: float,
    rng: np.random.Generator,
) -> np.ndarray:
    """Return indices into `xyz` keeping one random point per metric voxel.

    Voxel edges are aligned to a grid of side `voxel_size` in the same units
    as `xyz` (raw COLMAP world space). When `voxel_size <= 0` the function
    returns a permutation of all indices (no-op).
    """
    n = len(xyz)
    if n == 0 or voxel_size <= 0:
        return np.arange(n, dtype=np.int64)

    keys = np.floor(xyz / voxel_size).astype(np.int64)
    # lexsort by (z, y, x) so groups of identical voxel keys are contiguous
    order = np.lexsort(keys.T[::-1])
    keys_sorted = keys[order]

    diff = np.any(keys_sorted[1:] != keys_sorted[:-1], axis=1)
    starts = np.concatenate([[0], np.where(diff)[0] + 1])
    ends = np.concatenate([starts[1:], [n]])
    sizes = ends - starts
    offsets = rng.integers(0, sizes)  # one random pick per voxel
    return order[starts + offsets].astype(np.int64, copy=False)


def nearest_colmap_rgb(
    query_xyz: np.ndarray,
    colmap_xyz: np.ndarray,
    colmap_rgb: np.ndarray,
    tree: Optional[cKDTree] = None,
) -> np.ndarray:
    """For each query point, return the RGB of its nearest COLMAP neighbour.

    All-zero RGB when COLMAP is empty. ``tree`` is a prebuilt
    ``cKDTree(colmap_xyz.astype(float32))`` (stage-1 cache); results are
    per-query and identical to building the tree here.
    """
    n_q = len(query_xyz)
    if n_q == 0:
        return np.zeros((0, 3), dtype=np.uint8)
    if len(colmap_xyz) == 0:
        return np.zeros((n_q, 3), dtype=np.uint8)
    if tree is None:
        tree = cKDTree(colmap_xyz.astype(np.float32, copy=False))
    _, idx = tree.query(query_xyz.astype(np.float32, copy=False), k=1)
    return colmap_rgb[np.asarray(idx, dtype=np.int64).reshape(-1)]


def colmap_camera_centers(colmap_rec: ColmapRec) -> np.ndarray:
    centers = []
    for img in colmap_rec.images.values():
        R, t = _cam_matrix_from_image(img)
        centers.append(R.T @ (-t))
    if not centers:
        return np.zeros((0, 3), dtype=np.float32)
    return np.array(centers, dtype=np.float32)


# ------------------------------------------------------------------
# Robust normalisation (no yaw alignment — that's a training augmentation now)
# ------------------------------------------------------------------

def _robust_norm_params(colmap_xyz: np.ndarray, cam_centers: np.ndarray):
    """Return (center, scale) for the scene. Rotation is identity by design."""
    pts = []
    if colmap_xyz.size:
        pts.append(colmap_xyz)
    if cam_centers.size:
        pts.append(cam_centers)
    pts = np.concatenate(pts, axis=0).astype(np.float64)

    center = np.median(pts, axis=0).astype(np.float32)
    d = np.linalg.norm(pts - center, axis=1)
    scale = float(max(np.percentile(d, 95.0), 1e-3))
    return center, scale


def _normalise(pts: np.ndarray, center: np.ndarray, scale: float) -> np.ndarray:
    return ((pts - center) / scale).astype(np.float32)


# ------------------------------------------------------------------
# Multi-view semantic projection (3x3 majority + soft top-2 + sem confidence)
# ------------------------------------------------------------------

def _project_to_pixel(pts: np.ndarray, col_img, cam):
    """Project (N, 3) world points to pixel space of a single camera."""
    cam_w, cam_h = cam.width, cam.height
    if cam_w <= 0 or cam_h <= 0:
        return None

    R, t = _cam_matrix_from_image(col_img)
    p_cam = pts.astype(np.float64) @ R.T + t[None]
    z = p_cam[:, 2]
    in_front = z > 1e-8
    if not in_front.any():
        return None

    K = cam.calibration_matrix()
    u_proj = p_cam[:, 0] / np.maximum(z, 1e-8) * K[0, 0] + K[0, 2]
    v_proj = p_cam[:, 1] / np.maximum(z, 1e-8) * K[1, 1] + K[1, 2]
    return u_proj, v_proj, in_front, float(cam_w), float(cam_h)


_NB_DV = np.repeat(np.arange(-1, 2), 3)
_NB_DU = np.tile(np.arange(-1, 2), 3)


def _votes_3x3(keys: np.ndarray, H: int, W: int, vi: np.ndarray, ui: np.ndarray, lut: np.ndarray):
    """(point index, class id) of every in-bounds pixel of the 3x3 neighbourhoods at (vi, ui);
    `keys` are the image's flat pixel keys; (vi, ui) lie inside the image."""
    border = (vi == 0) | (vi == H - 1) | (ui == 0) | (ui == W - 1)
    inner = np.flatnonzero(~border)
    p = np.repeat(inner, 9)
    flat = ((vi[inner] * W + ui[inner])[:, None] + (_NB_DV * W + _NB_DU)).ravel()
    if border.any():  # these neighbourhoods leave the image: keep their in-bounds pixels
        b = np.flatnonzero(border)
        v2 = vi[b, None] + _NB_DV
        u2 = ui[b, None] + _NB_DU
        ok = (v2 >= 0) & (v2 < H) & (u2 >= 0) & (u2 < W)
        p = np.concatenate([p, np.repeat(b, 9)[ok.ravel()]])
        flat = np.concatenate([flat, (v2 * W + u2)[ok]])
    return p, lut[keys[flat] & 0xFFFFFF]


def _vote_counts(rows: np.ndarray, cls: np.ndarray, n_points: int, n_classes: int) -> np.ndarray:
    """(n_points, n_classes) int64 vote histogram."""
    return np.bincount(rows * n_classes + cls, minlength=n_points * n_classes).reshape(n_points, n_classes)


def _vote_argmax(rows: np.ndarray, cls: np.ndarray, n_points: int) -> np.ndarray:
    """Per-point ``argmax`` of the class vote histogram (0 without votes), histogram
    restricted to the classes present (absent classes have count 0 < max)."""
    present = np.zeros(256, dtype=bool)
    present[cls] = True
    classes = np.flatnonzero(present)
    if classes.size == 0:
        return np.zeros(n_points, dtype=np.int64)
    counts = _vote_counts(rows, (np.cumsum(present) - 1)[cls], n_points, classes.size)
    return np.where(counts.any(axis=1), classes[counts.argmax(axis=1)], 0)


def _resolve_colmap_image(colmap_by_name: dict, img_id: str):
    """Return the COLMAP image whose name matches img_id."""
    exact = colmap_by_name.get(img_id)
    if exact is not None:
        return exact
    matches = [v for k, v in colmap_by_name.items() if img_id in k]
    if len(matches) == 1:
        return matches[0]
    return None


def project_semantics_to_colmap_points(
    sample: dict,
    colmap_rec: ColmapRec,
    point_rows: np.ndarray,
    point_xyz: np.ndarray,
    images: Optional[SampleImages] = None,
) -> dict:
    """Vote projected Gestalt/ADE labels onto selected COLMAP 3D points (3x3).

    ``point_rows`` index the selected points in ``colmap_rec``'s point arrays and
    ``point_xyz`` (float32) are their coordinates.
    """
    if images is None:
        images = SampleImages(sample)
    n_points = len(point_xyz)
    n_g = len(GESTALT_CLASSES)
    votes = {"gestalt": ([], []), "ade": ([], [])}
    colmap_by_name = {col_img.name: col_img for col_img in colmap_rec.images.values()}

    for i, img_id in enumerate(sample["image_ids"]):
        col_img = _resolve_colmap_image(colmap_by_name, img_id)
        if col_img is None:
            continue

        obs_idx = np.flatnonzero(colmap_rec.observed_mask(col_img.image_id)[point_rows])
        if obs_idx.size == 0:  # as the former pycolmap has_point3D path: no observed point -> use all
            obs_idx = np.arange(n_points)

        proj = _project_to_pixel(point_xyz[obs_idx], col_img, _camera_for_image(colmap_rec, col_img))
        if proj is None:
            continue
        u_proj, v_proj, in_front, cam_w, cam_h = proj

        for kind, lut in (("gestalt", _GESTALT_LUT), ("ade", _ADE_LUT)):
            if images.label(kind, i) is None:
                continue
            H, W = images.shape(kind, i)
            u = np.rint(u_proj * (W / cam_w)).astype(np.int64)
            v = np.rint(v_proj * (H / cam_h)).astype(np.int64)
            ok = in_front & (u >= 0) & (u < W) & (v >= 0) & (v < H)
            p, cls = _votes_3x3(images.keys(kind, i), H, W, v[ok], u[ok], lut)
            votes[kind][0].append(obs_idx[ok][p])
            votes[kind][1].append(cls)

    (g_rows, g_cls), (a_rows, a_cls) = (
        (np.concatenate(r) if r else np.zeros(0, np.int64), np.concatenate(c) if c else np.zeros(0, np.uint8))
        for r, c in (votes["gestalt"], votes["ade"])
    )
    gestalt_counts = _vote_counts(g_rows, g_cls, n_points, n_g)
    gest_total = gestalt_counts.sum(axis=1)
    has_vote = gest_total > 0

    top1 = np.argmax(gestalt_counts, axis=1)
    counts2 = gestalt_counts.copy()
    counts2[np.arange(n_points), top1] = 0
    top2 = np.argmax(counts2, axis=1)
    has_second = counts2[np.arange(n_points), top2] > 0

    gest_id1 = np.where(has_vote, top1, -1).astype(np.int64)
    gest_id2 = np.where(has_vote & has_second, top2, -1).astype(np.int64)

    top1_count = gestalt_counts[np.arange(n_points), top1].astype(np.float32)
    gest_w1 = np.where(
        has_vote,
        top1_count / np.maximum(gest_total.astype(np.float32), 1.0),
        1.0,
    ).astype(np.float32)

    ade_ids = _vote_argmax(a_rows, a_cls, n_points)

    return {
        "gestalt_id1": gest_id1,
        "gestalt_id2": gest_id2,
        "gestalt_w1": gest_w1,
        "ade_ids": ade_ids,
        "gest_top1_count": top1_count,
    }


# ------------------------------------------------------------------
# Tier-targeted depth unprojection (single-pixel labels)
# ------------------------------------------------------------------

def fit_depth_label_cache(
    sample: dict,
    colmap_rec: ColmapRec,
    images: Optional[SampleImages] = None,
) -> list[dict]:
    """Per-image preprocessing cache shared by stage-1 and stage-2 builders.

    For each image with valid depth fitting, returns the fitted depth map plus
    the gestalt + ADE class-id maps (uint8) at the depth resolution and the
    K/R/t needed to unproject pixels into world space. Reproduces hoho2025
    ``get_fitted_dense_depth`` on the bulk COLMAP arrays.

    Stage 1's ``unproject_depth_tiered`` and stage 2's hull-cropped depth
    extractor both consume this cache, avoiding a second depth fit and decode.
    """
    if images is None:
        images = SampleImages(sample)
    K_mats = np.array(sample["K"])
    R_mats = np.array(sample["R"])
    t_vecs = np.array(sample["t"])
    if t_vecs.ndim == 3:
        t_vecs = t_vecs[:, :, 0]
    pose_only = list(sample.get("pose_only_in_colmap", [False] * len(sample["image_ids"])))

    out: list[dict] = []
    for i, img_id in enumerate(sample["image_ids"]):
        if pose_only[i] or sample["depth"][i] is None:
            continue
        Ki = K_mats[i]
        if Ki.shape != (3, 3) or Ki[0, 0] == 0:
            continue
        Ri = R_mats[i]
        ti = t_vecs[i]
        if not (np.isfinite(Ki).all() and np.isfinite(Ri).all() and np.isfinite(ti).all()):
            continue
        fx, fy = float(Ki[0, 0]), float(Ki[1, 1])
        if abs(fx) < 1e-6 or abs(fy) < 1e-6:
            continue
        # hoho2025 get_fitted_dense_depth: sparse COLMAP depth of the FIRST image (map
        # order) whose name contains img_id; no image / no observed point -> not found.
        col_img = next((im for im in colmap_rec.images.values() if img_id in im.name), None)
        if col_img is None:
            continue
        depth_np = images.depth(i) / 1000.
        depth_sparse = _sparse_depth(colmap_rec, col_img, depth_np.shape)
        if depth_sparse is None:
            continue
        # Its house mask comes from the ADE image; a missing ADE image or one whose size
        # differs from the depth map raised inside the former try/except -> image skipped.
        if sample["ade"][i] is None:
            continue
        ade_ids = images.ids("ade", i)
        if ade_ids.shape != depth_np.shape:
            continue
        _, depth_fitted = fit_scale_robust_median(
            depth_np, depth_sparse, validity_mask=_HOHO_HOUSE_BY_ID[ade_ids])

        H, W = depth_fitted.shape
        gest = images.label("gestalt", i)
        if gest is None:
            gest_ids = None
        elif images.shape("gestalt", i) == (H, W):
            gest_ids = images.ids("gestalt", i)
        else:
            gest_ids = _img_ids(np.asarray(_image_to_pil(gest).resize((W, H), Image.NEAREST)), _GESTALT_LUT)
        out.append({
            "i":             int(i),
            "img_id":        img_id,
            "depth_fitted":  depth_fitted,
            "gest_ids":      gest_ids,   # uint8 class-id maps at depth resolution
            "ade_ids":       ade_ids,
            "Ki":            Ki.astype(np.float32, copy=False),
            "Ri":            Ri.astype(np.float32, copy=False),
            "ti":            ti.astype(np.float32, copy=False),
        })
    return out


def _sparse_depth(colmap_rec: ColmapRec, col_img: ColmapImage, shape) -> Optional[np.ndarray]:
    """hoho2025 ``get_sparse_depth`` on the bulk arrays (same projection, rounding and
    last-write-wins splat in points3D map order); None when the image observes no point."""
    rows = np.flatnonzero(colmap_rec.observed_mask(col_img.image_id))
    if rows.size == 0:
        return None
    H, W = shape
    R, t = _cam_matrix_from_image(col_img)
    K = _camera_for_image(colmap_rec, col_img).calibration_matrix()
    p_cam = (colmap_rec.xyz[rows] @ R.T) + t
    p_cam = p_cam[p_cam[:, 2] > 0]
    z = p_cam[:, 2]
    u_i = np.round(p_cam[:, 0] / z * K[0, 0] + K[0, 2]).astype(int)
    v_i = np.round(p_cam[:, 1] / z * K[1, 1] + K[1, 2]).astype(int)
    ok = (u_i >= 0) & (u_i < W) & (v_i >= 0) & (v_i < H)
    depth_out = np.zeros((H, W), dtype=np.float32)
    depth_out[v_i[ok], u_i[ok]] = z[ok]
    return depth_out


def unproject_depth_tiered(
    sample: dict,
    colmap_rec,
    n_per_image: int = 4096,
    rng: Optional[np.random.Generator] = None,
    depth_cache: Optional[list[dict]] = None,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
    """Unproject Tier 1/2 Gestalt pixels. Returns (xyz, gestalt_ids, ade_ids, conf).

    Uses a single-pixel sample (no 3x3 voting): the pixel's own Gestalt/ADE IDs
    become the point labels. Tier 2 pixels are accepted only where ADE maps to
    the house/foreground subset, mirroring COLMAP token selection.

    When ``depth_cache`` (built by :func:`fit_depth_label_cache`) is supplied,
    the per-image PIL decode + Metric3Dv2 fitting is skipped — entries are
    consumed directly. Otherwise we build the cache implicitly.
    """
    if rng is None:
        rng = np.random.default_rng()

    if depth_cache is None:
        depth_cache = fit_depth_label_cache(sample, colmap_rec)

    all_xyz, all_gids, all_ade, all_conf = [], [], [], []

    for entry in depth_cache:
        if entry["gest_ids"] is None:
            # Stage 1's tier filter needs both gestalt and ADE labels per pixel.
            continue
        depth_fitted = entry["depth_fitted"]
        gid_map      = entry["gest_ids"]
        ade_id_map   = entry["ade_ids"]
        Ki           = entry["Ki"]
        Ri           = entry["Ri"]
        ti           = entry["ti"]

        H, W = depth_fitted.shape
        valid_depth = depth_fitted > 0.1
        tier1_mask = _TIER1_BY_ID[gid_map] & valid_depth
        tier2_mask = _TIER2_BY_ID[gid_map] & valid_depth & _HOUSE_FG_BY_ID[ade_id_map]

        def _sample_flat(mask: np.ndarray, budget: int) -> np.ndarray:
            if budget <= 0:
                return np.zeros(0, dtype=np.int64)
            flat = np.flatnonzero(mask.ravel())
            if flat.size > budget:
                flat = rng.choice(flat, budget, replace=False)
            return flat.astype(np.int64, copy=False)

        tier1_flat = _sample_flat(tier1_mask, n_per_image)
        tier2_flat = _sample_flat(tier2_mask, n_per_image - len(tier1_flat))
        if tier1_flat.size == 0 and tier2_flat.size == 0:
            continue

        sel = np.concatenate([tier1_flat, tier2_flat], axis=0)
        ys = (sel // W).astype(np.int64)
        xs = (sel %  W).astype(np.int64)
        depths = depth_fitted[ys, xs]

        fx, fy = Ki[0, 0], Ki[1, 1]
        cx, cy = Ki[0, 2], Ki[1, 2]
        x_cam = ((xs - cx) / fx) * depths
        y_cam = ((ys - cy) / fy) * depths
        z_cam = depths
        pts_cam = np.stack([x_cam, y_cam, z_cam], axis=1)
        pts_world = (pts_cam - ti[None]) @ Ri

        gids = gid_map[ys, xs].astype(np.int64)
        ade_ids_arr = ade_id_map[ys, xs].astype(np.int64)

        conf = np.clip(2.0 / np.maximum(depths, 0.5), 0.0, 1.0).astype(np.float32)

        all_xyz.append(pts_world.astype(np.float32))
        all_gids.append(gids)
        all_ade.append(ade_ids_arr.astype(np.int64))
        all_conf.append(conf)

    if not all_xyz:
        return (
            np.zeros((0, 3), dtype=np.float32),
            np.zeros(0, dtype=np.int64),
            np.zeros(0, dtype=np.int64),
            np.zeros(0, dtype=np.float32),
        )

    return (
        np.concatenate(all_xyz, axis=0),
        np.concatenate(all_gids, axis=0),
        np.concatenate(all_ade, axis=0),
        np.concatenate(all_conf, axis=0),
    )


# ------------------------------------------------------------------
# Main scene-input builder
# ------------------------------------------------------------------

def _colmap_geom_conf(track_len: np.ndarray, reproj_err: np.ndarray) -> np.ndarray:
    """Geometric confidence of a COLMAP point in [0, 1]."""
    tl = np.clip(track_len / 5.0, 0.0, 1.0)
    er = np.exp(-np.maximum(reproj_err, 0.0) / 2.0)
    return (tl * er).astype(np.float32)


def build_scene_input(
    sample: dict,
    n_pts: int = 8192,
    use_depth: bool = True,
    n_depth_per_image: int = 4096,
    voxel_size_m: float = 0.0,
    rng: Optional[np.random.Generator] = None,
    colmap_sem: Optional[dict] = None,
    depth_cache: Optional[list[dict]] = None,
    return_cache: bool = False,
) -> dict:
    """Build a fixed-size scene feature point cloud from one dataset sample.

    `n_pts` is split in half by provenance (default 8192 = 4096 + 4096):
    the first half is COLMAP/camera tokens, the second half is depth-unprojected
    tokens. If a scene cannot supply enough points for either half, that half is
    padded by resampling from the points already selected for the same half.

    `voxel_size_m` (metres in raw world space) thins the candidate pool before
    the budget cap: COLMAP, depth and camera candidates are jointly voxelised
    and at most one random point per voxel survives. Set to 0 to disable.

    Tier order:
        COLMAP half:
            T0  camera centres                              (type=2)
            T1  apex/eave_end/flashing_end/eave/ridge/rake/valley
            T2  ground_line/flashing/step_flashing/hip/fascia/transition_line
                only when ADE is house/foreground
        Depth half:
            T1  same structural Gestalt classes             (type=1)
            T2  same weak Gestalt classes with house/foreground ADE
    """
    if rng is None:
        rng = np.random.default_rng()

    colmap_rec = sample["colmap"]
    if not isinstance(colmap_rec, ColmapRec):
        raise TypeError(f"sample['colmap'] must be a ColmapRec from read_colmap_zip, got {type(colmap_rec)}")
    images = SampleImages(sample)

    colmap_pids, colmap_xyz, colmap_tlen, colmap_err, colmap_rgb = colmap_points_full(colmap_rec)
    cam_centers = colmap_camera_centers(colmap_rec)

    if len(colmap_xyz) == 0:
        raise ValueError("scene has no COLMAP 3D points — cannot build scene input")

    bbox_center, bbox_scale = _robust_norm_params(colmap_xyz, cam_centers)
    bbox_R = np.eye(3, dtype=np.float32)  # identity by design (yaw is augmentation)

    def norm(pts: np.ndarray) -> np.ndarray:
        return _normalise(pts, bbox_center, bbox_scale)

    # ---- COLMAP semantic projection ----------------------------------------
    # Reuse a precomputed semantic projection when one is supplied — the
    # 3x3-voting pass is the dominant per-sample cost in stage-1 preprocess.
    if colmap_sem is None:
        sem = project_semantics_to_colmap_points(
            sample, colmap_rec, np.arange(len(colmap_xyz)), colmap_xyz, images)
    else:
        sem = colmap_sem
    all_g1  = sem["gestalt_id1"]
    all_g2  = sem["gestalt_id2"]
    all_w1  = sem["gestalt_w1"]
    all_ade = sem["ade_ids"]
    top1_count = sem["gest_top1_count"]

    geom_conf_all = _colmap_geom_conf(colmap_tlen, colmap_err)
    sem_conf_all  = np.clip(top1_count / 5.0, 0.0, 1.0).astype(np.float32)

    colmap_budget = n_pts // 2
    depth_budget = n_pts - colmap_budget

    tier1_mask = np.isin(all_g1, _TIER1_GESTALT_ARR)
    tier2_mask = np.isin(all_g1, _TIER2_GESTALT_ARR) & _ade_house_foreground_mask(all_ade)

    # ---- Depth unprojection (once) + nearest-COLMAP RGB --------------------
    if use_depth:
        # Build the per-image depth cache up here (instead of letting
        # unproject_depth_tiered build it internally) so we can capture it
        # for `return_cache=True` — otherwise stage 2 would redo Metric3Dv2
        # depth fitting per image, defeating the shared-compute refactor.
        if depth_cache is None:
            depth_cache = fit_depth_label_cache(sample, colmap_rec, images)
        d_xyz, d_gids, d_ade, d_conf = unproject_depth_tiered(
            sample, colmap_rec, n_per_image=n_depth_per_image, rng=rng,
            depth_cache=depth_cache,
        )
    else:
        d_xyz = np.zeros((0, 3), dtype=np.float32)
        d_gids = np.zeros(0, dtype=np.int64)
        d_ade = np.zeros(0, dtype=np.int64)
        d_conf = np.zeros(0, dtype=np.float32)

    # Build the COLMAP KDTree once (also handed to stage 2 via the cache); only
    # query for depth points that survive tier + voxel + budget selection.
    colmap_kd = cKDTree(colmap_xyz)

    def _depth_rgb_for(sel: np.ndarray) -> np.ndarray:
        return nearest_colmap_rgb(d_xyz[sel], colmap_xyz, colmap_rgb, tree=colmap_kd)

    cam_rgb = np.zeros((len(cam_centers), 3), dtype=np.uint8)

    # ---- Joint voxel downsampling -----------------------------------------
    # Voxelise COLMAP + depth + camera candidates together in raw world space.
    # The kept-mask is sliced back per provenance and intersected with tier
    # masks below, so each Tier-1/Tier-2 selection picks from voxel survivors.
    if voxel_size_m and voxel_size_m > 0.0 and (len(colmap_xyz) + len(d_xyz) + len(cam_centers)) > 0:
        union_xyz = np.concatenate(
            [colmap_xyz, d_xyz, cam_centers.astype(np.float32, copy=False)], axis=0
        )
        keep_global = voxel_downsample_indices(union_xyz, float(voxel_size_m), rng)
        kept_flags = np.zeros(len(union_xyz), dtype=bool)
        kept_flags[keep_global] = True
        n_c = len(colmap_xyz)
        n_d = len(d_xyz)
        colmap_voxel_keep = kept_flags[:n_c]
        depth_voxel_keep = kept_flags[n_c : n_c + n_d]
        cam_voxel_keep = kept_flags[n_c + n_d :]
    else:
        colmap_voxel_keep = np.ones(len(colmap_xyz), dtype=bool)
        depth_voxel_keep = np.ones(len(d_xyz), dtype=bool)
        cam_voxel_keep = np.ones(len(cam_centers), dtype=bool)

    def _pick(mask: np.ndarray, budget: int) -> np.ndarray:
        if budget <= 0:
            return np.zeros(0, dtype=np.int64)
        idx = np.flatnonzero(mask)
        if len(idx) > budget:
            idx = rng.choice(idx, budget, replace=False)
        return idx.astype(np.int64, copy=False)

    def _empty_arrays(n: int = 0) -> tuple:
        return (
            np.zeros((n, 3), dtype=np.float32),   # 0: xyz
            np.zeros(n, dtype=np.int64),           # 1: type_id
            np.full(n, -1, dtype=np.int64),        # 2: gestalt_id1
            np.full(n, -1, dtype=np.int64),        # 3: gestalt_id2
            np.ones(n, dtype=np.float32),          # 4: gestalt_w1
            np.zeros(n, dtype=np.int64),           # 5: ade_id
            np.zeros(n, dtype=np.float32),         # 6: geom_conf
            np.zeros(n, dtype=np.float32),         # 7: sem_conf
            np.zeros((n, 3), dtype=np.uint8),      # 8: rgb
        )

    _N_FIELDS = 9

    def _concat(parts: list[tuple]) -> tuple:
        if not parts:
            return _empty_arrays(0)
        return tuple(np.concatenate([p[i] for p in parts], axis=0) for i in range(_N_FIELDS))

    def _take(arrs: tuple, idx: np.ndarray) -> tuple:
        return tuple(a[idx] for a in arrs)

    def _pad_or_trim(arrs: tuple, budget: int, fallback: Optional[tuple] = None) -> tuple:
        if budget <= 0:
            return _empty_arrays(0)
        n = len(arrs[0])
        if n == 0 and fallback is not None and len(fallback[0]) > 0:
            n_fallback = len(fallback[0])
            idx = rng.choice(n_fallback, budget, replace=n_fallback < budget)
            return _take(fallback, idx)
        if n == 0:
            return _empty_arrays(budget)
        if n > budget:
            idx = rng.choice(n, budget, replace=False)
            return _take(arrs, idx)
        if n < budget:
            pad = rng.choice(n, budget - n, replace=True)
            return tuple(np.concatenate([a, a[pad]], axis=0) for a in arrs)
        return arrs

    def _camera_arrays(sel: np.ndarray) -> tuple:
        n = len(sel)
        return (
            norm(cam_centers[sel]),
            np.full(n, 2, dtype=np.int64),
            np.full(n, -1, dtype=np.int64),
            np.full(n, -1, dtype=np.int64),
            np.ones(n, dtype=np.float32),
            np.zeros(n, dtype=np.int64),
            np.ones(n, dtype=np.float32),
            np.ones(n, dtype=np.float32),
            cam_rgb[sel],
        )

    def _colmap_arrays(sel: np.ndarray) -> tuple:
        n = len(sel)
        if n == 0:
            return _empty_arrays(0)
        return (
            norm(colmap_xyz[sel]),
            np.zeros(n, dtype=np.int64),
            all_g1[sel],
            all_g2[sel],
            all_w1[sel],
            all_ade[sel],
            geom_conf_all[sel],
            sem_conf_all[sel],
            colmap_rgb[sel],
        )

    def _depth_arrays(sel: np.ndarray) -> tuple:
        n = len(sel)
        if n == 0:
            return _empty_arrays(0)
        return (
            norm(d_xyz[sel]),
            np.full(n, 1, dtype=np.int64),
            d_gids[sel],
            np.full(n, -1, dtype=np.int64),
            np.ones(n, dtype=np.float32),
            d_ade[sel],
            d_conf[sel],
            np.ones(n, dtype=np.float32),
            _depth_rgb_for(sel),
        )

    # ---- COLMAP half: T0 cameras, then Tier 1, then Tier 2, then random fill
    col_parts: list[tuple] = []
    remaining_col = colmap_budget
    picked_colmap = np.zeros(len(colmap_xyz), dtype=bool)
    cam_eligible = np.flatnonzero(cam_voxel_keep)
    if remaining_col > 0 and len(cam_eligible) > 0:
        n_cam = min(len(cam_eligible), remaining_col)
        sel = (
            rng.choice(cam_eligible, n_cam, replace=False)
            if len(cam_eligible) > n_cam else cam_eligible
        )
        col_parts.append(_camera_arrays(sel.astype(np.int64, copy=False)))
        remaining_col -= n_cam

    if remaining_col > 0:
        sel = _pick(tier1_mask & colmap_voxel_keep & ~picked_colmap, remaining_col)
        col_parts.append(_colmap_arrays(sel))
        picked_colmap[sel] = True
        remaining_col -= len(sel)

    if remaining_col > 0:
        sel = _pick(tier2_mask & colmap_voxel_keep & ~picked_colmap, remaining_col)
        col_parts.append(_colmap_arrays(sel))
        picked_colmap[sel] = True
        remaining_col -= len(sel)

    # Fill whatever is left from ordinary COLMAP points (still voxel-thinned).
    if remaining_col > 0:
        sel = _pick(colmap_voxel_keep & ~picked_colmap, remaining_col)
        col_parts.append(_colmap_arrays(sel))
        picked_colmap[sel] = True
        remaining_col -= len(sel)

    col_arrays = _pad_or_trim(_concat(col_parts), colmap_budget)

    # ---- Depth half: Tier 1, then Tier 2 ------------------------------------
    depth_parts: list[tuple] = []
    if depth_budget > 0 and use_depth and len(d_xyz) > 0:
        d_tier1 = np.isin(d_gids, _TIER1_GESTALT_ARR) & depth_voxel_keep
        d_tier2 = (
            np.isin(d_gids, _TIER2_GESTALT_ARR)
            & _ade_house_foreground_mask(d_ade)
            & depth_voxel_keep
        )

        remaining_depth = depth_budget
        sel = _pick(d_tier1, remaining_depth)
        depth_parts.append(_depth_arrays(sel))
        remaining_depth -= len(sel)

        if remaining_depth > 0:
            sel = _pick(d_tier2, remaining_depth)
            depth_parts.append(_depth_arrays(sel))

    depth_arrays = _pad_or_trim(_concat(depth_parts), depth_budget, fallback=col_arrays)

    all_xyz       = np.concatenate([col_arrays[0], depth_arrays[0]], axis=0)
    all_type      = np.concatenate([col_arrays[1], depth_arrays[1]], axis=0)
    all_g1        = np.concatenate([col_arrays[2], depth_arrays[2]], axis=0)
    all_g2        = np.concatenate([col_arrays[3], depth_arrays[3]], axis=0)
    all_w1        = np.concatenate([col_arrays[4], depth_arrays[4]], axis=0)
    all_ade       = np.concatenate([col_arrays[5], depth_arrays[5]], axis=0)
    all_geom_conf = np.concatenate([col_arrays[6], depth_arrays[6]], axis=0)
    all_sem_conf  = np.concatenate([col_arrays[7], depth_arrays[7]], axis=0)
    all_rgb       = np.concatenate([col_arrays[8], depth_arrays[8]], axis=0)

    out = {
        "scene_xyz": all_xyz,
        "scene_type_ids": all_type,
        "scene_gestalt_ids": all_g1,
        "scene_gestalt_id2": all_g2,
        "scene_gestalt_w1": all_w1,
        "scene_ade_ids": all_ade,
        "scene_geom_conf": all_geom_conf.astype(np.float32),
        "scene_sem_conf":  all_sem_conf.astype(np.float32),
        "scene_rgb": all_rgb.astype(np.uint8),
        "bbox_center": bbox_center.astype(np.float32),
        "bbox_scale": float(bbox_scale),
        "bbox_R": bbox_R,
    }
    if return_cache:
        out["_cache"] = {
            "colmap": {
                "pids":      colmap_pids,
                "xyz":       colmap_xyz,
                "rgb":       colmap_rgb,
                "track_len": colmap_tlen,
                "reproj_err": colmap_err,
                "sem":       sem,
                "kdtree":    colmap_kd,
            },
            # Either the cache passed in, or the one built above for use_depth.
            # None only when use_depth=False (then stage 2 has no depth to share).
            "depth": depth_cache,
        }
    return out


# ------------------------------------------------------------------
# GT vertex builder
# ------------------------------------------------------------------

# ------------------------------------------------------------------
# V11 chimney filter — drop small connected components from GT
# ------------------------------------------------------------------

def _polygon_xy_area(verts_xy: np.ndarray) -> float:
    """Shoelace area of the convex polygon formed by 1..4 XY points.

    Vertices are first sorted by polar angle around their centroid so the
    polygon is non-self-intersecting. For < 3 points the area is zero.
    """
    n = len(verts_xy)
    if n < 3:
        return 0.0
    xy = verts_xy.astype(np.float64, copy=False)
    c = xy.mean(axis=0)
    ang = np.arctan2(xy[:, 1] - c[1], xy[:, 0] - c[0])
    order = np.argsort(ang)
    p = xy[order]
    x, y = p[:, 0], p[:, 1]
    return 0.5 * float(abs(np.dot(x, np.roll(y, -1)) - np.dot(y, np.roll(x, -1))))


def filter_small_components(
    wf_vertices: np.ndarray,
    wf_edges: np.ndarray,
    max_verts_per_cc: int = 4,
    max_area_m2: float = 5.0,
) -> Tuple[np.ndarray, np.ndarray]:
    """Mark vertices/edges belonging to small connected components for removal.

    Operates on RAW (un-normalised, metric) coordinates. A connected component
    is removed iff it has at most ``max_verts_per_cc`` vertices AND its XY
    footprint area is strictly less than ``max_area_m2`` square metres.

    Args:
        wf_vertices: (N, 3) world-space GT vertices.
        wf_edges:    (M, 2) edges as vertex-index pairs.

    Returns:
        (keep_v, keep_e): boolean masks of length N and M respectively. True
        means "retain" (not a chimney).
    """
    n = int(len(wf_vertices))
    m = int(len(wf_edges))
    if n == 0:
        return np.ones(0, dtype=bool), np.ones(m, dtype=bool)

    parent = np.arange(n, dtype=np.int64)

    def find(i: int) -> int:
        while parent[i] != i:
            parent[i] = parent[parent[i]]
            i = parent[i]
        return i

    if m > 0:
        edges_int = np.asarray(wf_edges, dtype=np.int64)
        valid_e = (
            (edges_int[:, 0] >= 0)
            & (edges_int[:, 1] >= 0)
            & (edges_int[:, 0] < n)
            & (edges_int[:, 1] < n)
        )
        for a, b in edges_int[valid_e]:
            ra, rb = find(int(a)), find(int(b))
            if ra != rb:
                parent[ra] = rb
    else:
        edges_int = np.zeros((0, 2), dtype=np.int64)
        valid_e = np.zeros(0, dtype=bool)

    roots = np.array([find(i) for i in range(n)], dtype=np.int64)

    keep_v = np.ones(n, dtype=bool)
    pts = np.asarray(wf_vertices, dtype=np.float32)
    for root in np.unique(roots):
        idx = np.where(roots == root)[0]
        if len(idx) <= max_verts_per_cc:
            area = _polygon_xy_area(pts[idx, :2])
            if area < max_area_m2:
                keep_v[idx] = False

    if m == 0:
        return keep_v, np.ones(0, dtype=bool)
    a = edges_int[:, 0].clip(0, n - 1)
    b = edges_int[:, 1].clip(0, n - 1)
    keep_e = valid_e & keep_v[a] & keep_v[b]
    return keep_v, keep_e


def build_gt_verts(
    sample: dict,
    bbox_center: np.ndarray,
    bbox_scale: float,
    k_verts: int = 64,
) -> np.ndarray:
    """Build padded GT vertex tensor of shape (K, 4) in normalised coords.

    Column 3 is the validity flag: +1 for real vertex, -1 for padding.
    No yaw rotation is applied here — the dataloader applies a random rotation
    to both `scene_xyz` and `verts_gt[:, :3]` per epoch.
    """
    verts = np.array(sample["wf_vertices"], dtype=np.float32)
    n_real = min(len(verts), k_verts)

    assert n_real > 0, "scene has zero GT vertices"

    out = np.zeros((k_verts, 4), dtype=np.float32)
    verts_norm = (verts[:n_real] - bbox_center) / bbox_scale
    out[:n_real, :3] = verts_norm.astype(np.float32)
    out[:n_real, 3] = 1.0
    out[n_real:, 3] = -1.0
    return out