File size: 35,382 Bytes
719b488
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Convert raw 3D-FRONT house JSON into room-level JSONL.

Reads only ``data/3D-FRONT/*.json``. Of the four bulk geometry arrays, which are
16 GB of the 17 GB input, mesh ``xyz`` derives room_boundary, room_height and
openings; Window and WallInner ``faces`` identify indoor window profiles.
Normal and uv are not used, and no source geometry array is published.
No texture or asset model is loaded, and no geometry library
is used: the room boundary is the convex hull of the floor mesh vertices,
computed with a plain-stdlib monotone chain.

Every published field is either one of the collection schema fields or a source
field the schema does not cover, kept verbatim under ``source_fields``. Nothing
is estimated, inferred or learned: a field the source does not state is null.

Source is metre, Y-up, house-global with identity scene/room/mesh transforms.
Output is metre, Z-up, house-global: ``[x, y, z] -> [x, -z, y]``.

Usage:
    python kits/convert_3dfront.py --data-dir data --out 3dfront.jsonl
"""

from __future__ import annotations

import argparse
import json
import math
import os
import re
import sys
from collections import Counter, defaultdict
from pathlib import Path

# --------------------------------------------------------------------------
# Fixed contract constants
# --------------------------------------------------------------------------

COORDINATE_SYSTEM = (
    "meter; right-handed; Z-up; source [x,y,z] -> [x,-z,y]; house-global origin; "
    "furniture position is the source asset origin; room_boundary is the convex "
    "hull of the floor mesh vertices. The merged view and the per-room view keep "
    "the same house-global coordinates."
)

# scene.room[].type normalised the way the collection already normalises this
# exact vocabulary -- IL3D_exported/aggregate_scenes.py:22-41. One source field,
# one transform; see normalise_room_type for the rule applied outside the table.
ROOM_TYPES = {
    "Aisle": "aisle",
    "Balcony": "balcony",
    "BathRoom": "bathroom",
    "BedRoom": "bedroom",
    "CloakRoom": "cloakroom",
    "DiningRoom": "dining room",
    "ElderlyRoom": "elderly room",
    "Garage": "garage",
    "KidsRoom": "kids room",
    "Kitchen": "kitchen",
    "LaundryRoom": "laundry room",
    "Library": "library",
    "LivingDiningRoom": "living dining room",
    "LivingRoom": "living room",
    "OfficeRoom": "office",
    "OtherRoom": "other room",
    "RecreationRoom": "recreation room",
    "StorageRoom": "storage room",
}
# IL3D's table verbatim, nothing appended. The types 3D-FRONT adds (MasterBedroom,
# SecondBathroom, Corridor, Terrace ...) are not listed because the split rule in
# normalise_room_type already lands on exactly the same strings.

LICENSE_TAG = (
    "3D-FRONT Data Sets Use License Agreement 2020-06-18 "
    "(scientific research only, non-commercial)"
)

CORE_OPENING_TYPES = ("Door", "Window", "BayWindow")
# Source-coordinate precision for boundary matching; the extra term covers
# floating-point subtraction at the 0.00001 m threshold. Output vertices stay raw.
WINDOW_MATCH_TOLERANCE = 1e-5 + 1e-12

# --------------------------------------------------------------------------
# Geometry helpers (standard library only)
# --------------------------------------------------------------------------


def normalise_room_type(raw):
    """IL3D's table, and IL3D's own rule for the values it does not carry.

    il3d_agg.py:279 is ROOM_TYPES.get(x, x.lower()). The table's entries show the
    rule behind it: split the camel case into words and lower-case them
    (DiningRoom -> "dining room", LivingDiningRoom -> "living dining room"),
    except where the halves form one standard English word, which the table
    already pins (BathRoom -> "bathroom", CloakRoom -> "cloakroom"). Applying that
    split to a value the table does not carry is the same rule, not a new one:
    the source writes its compound words without an internal capital
    (MasterBedroom, never MasterBedRoom), so the split lands on "master bedroom"
    and single words like Hallway come through untouched.
    """
    if not isinstance(raw, str) or not raw.strip():
        return None
    if raw in ROOM_TYPES:
        return ROOM_TYPES[raw]
    words = re.findall(r"[A-Z][a-z]*|[a-z]+|\d+", raw, re.ASCII)
    return " ".join(words).lower() if words else raw.lower()


def convex_hull(points):
    """Monotone chain hull. Collinear points are dropped (cross <= 1e-12).

    De-duplication and sorting happen on the un-rounded floats; rounding is
    applied only when the boundary is written out. Returns lower[:-1] + upper[:-1]
    starting at the lexicographically smallest vertex.
    """
    pts = sorted(set(points))
    if len(pts) <= 2:
        return pts

    def cross(o, a, b):
        return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])

    lower = []
    for p in pts:
        while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 1e-12:
            lower.pop()
        lower.append(p)
    upper = []
    for p in reversed(pts):
        while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 1e-12:
            upper.pop()
        upper.append(p)
    return lower[:-1] + upper[:-1]


def finite_vector(value, length):
    return (
        isinstance(value, list)
        and len(value) == length
        and all(isinstance(v, (int, float)) and math.isfinite(float(v)) for v in value)
    )


def sanitize_json(value, path=""):
    """Replace non-finite floats with null and return their source paths.

    Copied from IL3D_exported/aggregate_scenes.py. Raw source values kept in
    source_fields must stay JSON-compliant because the writer uses
    allow_nan=False, and a single NaN anywhere would otherwise abort the run at
    write time. It has never fired: the 1,215 non-finite values 3D-FRONT carries
    are all at scene.room[].children[].pos[], which finite_vector rejects long
    before this, so nonfinite_source_values is expected to stay 0. It is kept as
    the guard on the paths sanitize_json does cover, not as a live counter.
    """
    bad = []
    if isinstance(value, float) and not math.isfinite(value):
        return None, [path]
    if isinstance(value, list):
        result = []
        for index, item in enumerate(value):
            cleaned, found = sanitize_json(item, f"{path}[{index}]")
            result.append(cleaned)
            bad.extend(found)
        return result, bad
    if isinstance(value, dict):
        result = {}
        for key, item in value.items():
            child = f"{path}.{key}" if path else key
            cleaned, found = sanitize_json(item, child)
            result[key] = cleaned
            bad.extend(found)
        return result, bad
    return value, bad


def quaternion_matrix_zup(rot):
    """Source quaternion [x, y, z, w] -> Z-up rotation matrix.

    The source frame is Y-up. The change of basis is C = Rx(+90 deg), applied as
    R_zup = C @ R_source @ C.T, which preserves handedness (a bare Y/Z swap
    would introduce a reflection).
    """
    x, y, z, w = (float(v) for v in rot)
    norm = math.sqrt(x * x + y * y + z * z + w * w)
    if norm <= 0.0 or not math.isfinite(norm):
        return None
    x, y, z, w = x / norm, y / norm, z / norm, w / norm
    r = [
        [1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
        [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
        [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)],
    ]
    # C = Rx(+90): (x, y, z) -> (x, -z, y)
    c = [[1.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]]
    ct = [[c[j][i] for j in range(3)] for i in range(3)]
    cr = [[sum(c[i][k] * r[k][j] for k in range(3)) for j in range(3)] for i in range(3)]
    return [[sum(cr[i][k] * ct[k][j] for k in range(3)) for j in range(3)] for i in range(3)]


def yaw_and_tilt(matrix):
    """Yaw about the output +Z and a tilt flag. Mirrors IL3D yaw_and_tilt()."""
    horizontal = math.hypot(matrix[0][0], matrix[1][0])
    yaw = None
    if horizontal > 1e-8:
        yaw = math.degrees(math.atan2(matrix[1][0], matrix[0][0]))
        yaw = ((yaw + 180.0) % 360.0) - 180.0
        yaw = round(yaw, 6)
    up = [matrix[i][2] for i in range(3)]
    has_tilt = math.sqrt(up[0] ** 2 + up[1] ** 2 + (up[2] - 1.0) ** 2) > 1e-4
    return yaw, has_tilt


def to_zup_point(vec):
    """Source [x, y, z] -> output {x, y, z} with y_out = -z_src, z_out = y_src."""
    return {
        "x": round(float(vec[0]), 6),
        "y": round(-float(vec[2]), 6),
        "z": round(float(vec[1]), 6),
    }


def mesh_vertices(mesh):
    xyz = mesh.get("xyz") or []
    return [
        (float(xyz[i]), float(xyz[i + 1]), float(xyz[i + 2]))
        for i in range(0, len(xyz) - 2, 3)
    ]


# --------------------------------------------------------------------------
# Field resolution
# --------------------------------------------------------------------------


def resolve_category(defn):
    """furniture[].category, or null.

    One field. model_info.json belongs to 3D-FUTURE, not to this source, and
    where both exist they disagree on 865 of 2,220 sampled placements -- they are
    not the same statement about the object. Parsing a category out of
    furniture[].title would be a third statement again.
    """
    return (defn or {}).get("category") or None


def resolve_size(child, defn):
    """(furniture[].size union the flat furniture[].bbox) x children[].scale.

    The source states no ready-made metric extent for a placement: the asset
    record carries the extent, the placement carries the scale. size and the flat
    form of bbox are the same quantity under two key names -- over the 2,387
    furniture definitions carrying both (150 houses) they are identical to the
    last digit, zero exceptions -- so reading either one is reading one source,
    not falling back from one to another. The nested form [[x, z, y]] is a different encoding with
    a different axis order; it is not read here and stays verbatim in
    source_fields.bbox.

    Axis order is IL3D's: width = x, length = z, height = y
    (il3d_agg.py:221-227). Scaling the asset extent by the placement's own scale
    follows MetaScenes aggregate_scenes.py:89-98.
    """
    base = None
    for key in ("size", "bbox"):
        value = (defn or {}).get(key)
        if finite_vector(value, 3):
            base = [float(v) for v in value]
            break
    if base is None:
        return None
    scale = child.get("scale")
    if not finite_vector(scale, 3):
        return None
    dims = [base[i] * abs(float(scale[i])) for i in range(3)]
    if any((not math.isfinite(d)) or d <= 0.0 for d in dims):
        return None
    size = {
        "width": round(dims[0], 6),
        "length": round(dims[2], 6),
        "height": round(dims[1], 6),
    }
    # The guard above runs on the raw extents; an extent below 5e-7 is positive
    # there but rounds to 0.0 at six decimals, so it is re-checked on the values
    # actually published.
    if any(v <= 0.0 for v in size.values()):
        return None
    return size


def group_openings(meshes, counters, mesh_type):
    """Group same-type meshes by their rounded XY convex hull footprint.

    One raw mesh is not one opening: the common pattern is a vertical body plus
    a zero-height cap sharing the same footprint. Grouping key and footprint are
    both computed in output XY, so the key is stable across runs.

    A mesh with fewer than four distinct rounded XY points cannot describe an
    opening footprint and is discarded *before* grouping, not filtered out of
    the groups afterwards, counted as opening_<type>_few_points. Only the three
    types with a schema slot reach this function.
    """
    groups = {}
    for mesh in meshes:
        verts = mesh_vertices(mesh)
        if not verts:
            continue
        xy = [(round(v[0], 3), round(-v[2], 3)) for v in verts]
        if len(set(xy)) < 4:
            counters[f"opening_{mesh_type}_few_points"] += 1
            continue
        hull = convex_hull(xy)
        if not hull:
            continue
        key = tuple(hull)
        entry = groups.setdefault(
            key, {"hull": hull, "bottom": math.inf, "top": -math.inf}
        )
        if mesh_type == "Window":
            entry.setdefault("meshes", []).append(mesh)
        for v in verts:
            entry["bottom"] = min(entry["bottom"], v[1])
            entry["top"] = max(entry["top"], v[1])
    return list(groups.values())


def same_point(a, b):
    return all(abs(a[i] - b[i]) <= WINDOW_MATCH_TOLERANCE for i in range(3))


def boundary_loops(mesh, material_seams=False):
    """Follow source triangle boundaries, joining vertices at source precision."""
    representatives, vertices = [], []
    for point in mesh_vertices(mesh):
        representative = next((p for p in representatives if same_point(point, p)), None)
        if representative is None:
            representative = point
            representatives.append(point)
        vertices.append(representative)
    edges = Counter()
    faces = mesh["faces"]
    for i in range(0, len(faces), 3):
        a, b, c = (vertices[j] for j in faces[i:i + 3])
        for u, v in ((a, b), (b, c), (c, a)):
            if u != v:
                edges[tuple(sorted((u, v)))] += 1
    if material_seams:
        # Material seams can be one long edge on one side and several short
        # edges on the other. Split only at existing source boundary vertices.
        boundary = [edge for edge, count in edges.items() if count == 1]
        points = {p for edge in boundary for p in edge}
        edges = Counter()
        for a, b in boundary:
            direction = [b[i] - a[i] for i in range(3)]
            length2 = sum(d*d for d in direction)
            cuts = [(0, a), (1, b)]
            for p in points:
                t = sum((p[i] - a[i])*direction[i] for i in range(3)) / length2
                if 0 < t < 1 and same_point(p, tuple(a[i] + t*direction[i] for i in range(3))):
                    cuts.append((t, p))
            ordered = [p for _, p in sorted(cuts)]
            edges.update(tuple(sorted(edge)) for edge in zip(ordered, ordered[1:]))
    adjacency = defaultdict(set)
    for (u, v), count in edges.items():
        if count == 1:
            adjacency[u].add(v)
            adjacency[v].add(u)
    if any(len(neighbors) != 2 for neighbors in adjacency.values()):
        raise ValueError(f"non-closed boundary: mesh {mesh['uid']}")
    remaining, loops = set(adjacency), []
    while remaining:
        start = min(remaining)
        loop = [start]
        previous, current = start, min(adjacency[start])
        while current != start:
            loop.append(current)
            previous, current = current, next(v for v in adjacency[current] if v != previous)
        remaining.difference_update(loop)
        loops.append(loop)
    return loops


def vertical_loop_area(loop):
    """Projected area of a vertical loop, allowing source-coordinate precision."""
    origin = loop[0]
    far = max(loop, key=lambda p: math.hypot(p[0] - origin[0], p[2] - origin[2]))
    dx, dz = far[0] - origin[0], far[2] - origin[2]
    span = math.hypot(dx, dz)
    if span == 0:
        return None
    if any(abs(dx * (p[2] - origin[2]) - dz * (p[0] - origin[0]))
           > WINDOW_MATCH_TOLERANCE * span for p in loop):
        return None
    # Project onto the vertical plane's larger axis component.
    horizontal = 0 if abs(dx) >= abs(dz) else 2
    return abs(sum(a[horizontal]*b[1] - b[horizontal]*a[1]
                   for a, b in zip(loop, loop[1:] + loop[:1]))) / 2


def floor_boundary_chains(loop, floor_y):
    """Source chains whose two original endpoints lie at the same floor height."""
    cuts = [i for i, a in enumerate(loop)
            if any(abs(a[1] - y) <= WINDOW_MATCH_TOLERANCE
                   and abs(loop[(i + 1) % len(loop)][1] - y) <= WINDOW_MATCH_TOLERANCE
                   for y in floor_y)]
    for i, j in zip(cuts, cuts[1:] + cuts[:1]):
        count = (j - i) % len(loop) or len(loop)
        chain = [loop[k % len(loop)] for k in range(i + 1, i + count + 1)]
        if (len(chain) >= 3 and vertical_loop_area(chain)
                and any(abs(chain[0][1] - y) <= WINDOW_MATCH_TOLERANCE
                        and abs(chain[-1][1] - y) <= WINDOW_MATCH_TOLERANCE for y in floor_y)):
            yield chain


def join_material_parts(parts):
    """Assemble a source constructid without changing its coordinates or faces."""
    xyz, faces = [], []
    for mesh in parts:
        offset = len(xyz) // 3
        faces.extend(i + offset for i in mesh["faces"])
        xyz.extend(mesh["xyz"])
    return {"uid": [mesh["uid"] for mesh in parts], "xyz": xyz, "faces": faces}


def on_indoor_face(loop, walls):
    """A source WallInner triangle defines the plane; no plane is fitted."""
    for wall in walls:
        vertices = mesh_vertices(wall)
        for i in range(0, len(wall["faces"]), 3):
            a, b, c = (vertices[j] for j in wall["faces"][i:i + 3])
            u, v = [b[k] - a[k] for k in range(3)], [c[k] - a[k] for k in range(3)]
            normal = [u[1]*v[2] - u[2]*v[1], u[2]*v[0] - u[0]*v[2], u[0]*v[1] - u[1]*v[0]]
            length = math.sqrt(sum(n*n for n in normal))
            if length and all(abs(sum((p[k] - a[k])*normal[k] for k in range(3)))
                              <= WINDOW_MATCH_TOLERANCE * length for p in loop):
                return True
    return False


def indoor_window(group, walls, floor_y, where, window_meshes):
    """PROJECT DECISION: a unique source window outline on a WallInner plane."""
    matches = []
    material_groups = {}
    for mesh in group["meshes"]:
        cid = mesh.get("constructid")
        material_groups[cid if cid is not None else mesh["uid"]] = (
            [m for m in window_meshes if m.get("constructid") == cid] if cid is not None else [mesh])
    for parts in material_groups.values():
        split = len(parts) > 1
        mesh = join_material_parts(parts) if split else parts[0]
        for loop in boundary_loops(mesh, material_seams=split):
            area = vertical_loop_area(loop)
            profiles = [loop] if area else floor_boundary_chains(loop, floor_y)
            matches.extend(profile for profile in profiles if on_indoor_face(profile, walls))
    if len(matches) != 1:
        raise ValueError(f"{where}: Window meshes {[m['uid'] for m in group['meshes']]} "
                         f"have {len(matches)} indoor boundary matches (expected 1)")
    points = [(p[0], -p[2], p[1]) for p in matches[0]]
    xs, ys, zs = zip(*points)
    return {
        "opening_type": "Window",
        "wall_id": None,
        "position": {"x": round((min(xs) + max(xs)) / 2, 6),
                     "y": round((min(ys) + max(ys)) / 2, 6),
                     "z": round((min(zs) + max(zs)) / 2, 6)},
        "width": round(max(max(xs) - min(xs), max(ys) - min(ys)), 6),
        "height": round(max(zs) - min(zs), 6),
        "sill_height": round(min(zs), 6),
        "profile": [[round(v, 6) for v in p] for p in points],
    }


def opening_object(group, mesh_type):
    """One opening, measured the way InteriorGS measures one.

    position is the profile AABB midpoint, width its larger horizontal extent,
    sill_height the profile bottom -- interiorgs_agg.py:165-182. Every published
    opening is measured this way; there is no second method for the ones that
    happen to be rectangular.

    interiorgs_agg.py:182 writes sill_height only for a window
    (``bottom_z if raw.get("type") == "WINDOW" else None``); a door has no sill.
    """
    hull = group["hull"]
    xs = [p[0] for p in hull]
    ys = [p[1] for p in hull]
    return {
        "opening_type": mesh_type,
        "wall_id": None,
        "position": {
            "x": round((min(xs) + max(xs)) / 2.0, 6),
            "y": round((min(ys) + max(ys)) / 2.0, 6),
            "z": round((group["bottom"] + group["top"]) / 2.0, 6),
        },
        "width": round(max(max(xs) - min(xs), max(ys) - min(ys)), 6),
        "height": round(group["top"] - group["bottom"], 6),
        "sill_height": None if mesh_type == "Door" else round(group["bottom"], 6),
        "profile": [[round(p[0], 6), round(p[1], 6)] for p in hull],
    }


def furniture_record(house_uid, child, defn, counters):
    category = resolve_category(defn)
    size = resolve_size(child, defn)

    pos = child.get("pos")
    position = to_zup_point(pos) if finite_vector(pos, 3) else None
    if position is None:
        counters["position_null"] += 1

    rot = child.get("rot")
    matrix = quaternion_matrix_zup(rot) if finite_vector(rot, 4) else None
    if matrix is None:
        # Unstated orientation, not a tilted one: counted apart from tilt/no_tilt.
        # The record cannot tell the two apart (a tilted placement with undefined
        # yaw writes the same {null, null, null}); only the counters can.
        rotation = {"x": None, "y": None, "z": None}
        counters["rotation_unusable"] += 1
    else:
        yaw, has_tilt = yaw_and_tilt(matrix)
        # A tilted placement has no faithful (x, y) in degrees about the output
        # axes, so those two are null rather than an invented value -- IL3D
        # aggregate_scenes.py:245.
        rotation = {"x": None if has_tilt else 0.0,
                    "y": None if has_tilt else 0.0,
                    "z": yaw}
        counters["tilt" if has_tilt else "no_tilt"] += 1
        if has_tilt and yaw is None:
            counters["tilt_yaw_undefined"] += 1
    counters["resolved" if defn is not None else "orphan"] += 1
    counters["category_null" if category is None else "category_set"] += 1
    counters["size_null" if size is None else "size_set"] += 1

    # Only source fields that say something about the layout and that no schema
    # field consumed. The rest was consumed above (pos, rot, scale, instanceid,
    # category and the flat size/bbox), or is a reference key (uid, ref, aid), or
    # is appearance (material, uv_override, components).
    #
    # bbox appears here only in its nested form: the flat form fed furniture_size,
    # the nested one carries a different axis order and was not read.
    bbox = (defn or {}).get("bbox")
    nested_bbox = bbox if (isinstance(bbox, list) and bbox
                           and isinstance(bbox[0], list)) else None
    source_fields, bad = sanitize_json({
        "jid": (defn or {}).get("jid"),
        "title": (defn or {}).get("title"),
        "bbox": nested_bbox,
        "sourceCategoryId": (defn or {}).get("sourceCategoryId"),
        "valid": (defn or {}).get("valid"),
        "replace_bbox": child.get("replace_bbox"),
        "parentJid": child.get("parentJid"),
    })
    counters["nonfinite_source_values"] += len(bad)

    return {
        "furniture_category": category,
        "furniture_instance_id": f"3dfront_{house_uid}::{child.get('instanceid')}",
        "furniture_position": position,
        "furniture_rotation": rotation,
        "furniture_size": size,
        "source_fields": source_fields,
    }


def room_record(house_uid, room_index, room, ctx, counters):
    source_room_id = room.get("instanceid")
    room_id = f"room_{room_index}"

    floors, ceilings, openings = [], [], defaultdict(list)
    furniture_children, ref_meshes = [], []
    for child in room.get("children", []):
        instanceid = child.get("instanceid") or ""
        if instanceid.startswith("furniture/"):
            furniture_children.append(child)
            continue
        mesh = ctx["mesh_by_uid"].get(child.get("ref"))
        if mesh is None:
            continue
        ref_meshes.append(mesh)
        mtype = mesh.get("type")
        if mtype == "Floor":
            floors.append(mesh)
        elif mtype == "Ceiling":
            ceilings.append(mesh)
        elif mtype in CORE_OPENING_TYPES:
            openings[mtype].append(mesh)

    # ---- boundary: convex hull of every floor mesh vertex -----------------
    # room_boundary_type says exactly what this is. The hull fills in concave
    # rooms, so it is not called a polygon.
    floor_xy, floor_y = [], []
    for mesh in floors:
        verts = mesh_vertices(mesh)
        floor_xy.extend((v[0], -v[2]) for v in verts)
        floor_y.extend(v[1] for v in verts)
    hull = convex_hull(floor_xy) if floor_xy else []
    if len(hull) >= 3:
        boundary = [[round(p[0], 6), round(p[1], 6)] for p in hull]
        boundary_type = "floor_mesh_convex_hull"
        counters["boundary_hull"] += 1
    else:
        boundary, boundary_type = None, None
        counters["boundary_null_degenerate" if floors else "boundary_null_no_floor"] += 1

    # ---- area: whatever the source states, else null -----------------------
    # scene.room[].size is the room area in m2 (LivingDiningRoom 36.87, Kitchen
    # 2.35 ...). 33,116 rooms state a positive value, 4,695 state 0 and 18,318
    # carry no size key at all. Only a stated positive value is published: a
    # stated 0 is the source denying the room an area, a missing key states
    # nothing, and root README:99 says a field the source does not give is null,
    # never an estimate. No area is computed from geometry.
    source_area = room.get("size")
    stated = (isinstance(source_area, (int, float)) and not isinstance(source_area, bool)
              and math.isfinite(source_area))
    # Rounded first, then tested: an area below 5e-7 is positive raw but 0.0 at
    # six decimals. Same re-check resolve_size makes.
    room_area = round(float(source_area), 6) if stated else None
    if room_area is not None and room_area <= 0:
        room_area = None
    if room_area is not None:
        counters["area_source_size"] += 1
    else:
        counters["area_null_zero" if stated else "area_null_absent"] += 1

    # ---- height: floor-to-ceiling clearance from the two mesh types ---------
    # PROJECT DECISION, no precedent: no sibling source ships Floor and Ceiling
    # meshes, so no sibling export derives a height this way. Marked as uncited.
    # 49,799 rooms (88.72%) carry both a Floor and a Ceiling mesh; the rest are
    # null. Cross-checked against the Y-span of the Wall meshes: 96.47% agree to
    # within 1 mm, median difference 0.
    ceiling_y = [v[1] for mesh in ceilings for v in mesh_vertices(mesh)]
    room_height = None
    if floor_y and ceiling_y:
        single_floor = max(floor_y) - min(floor_y) <= 1e-6
        single_ceiling = max(ceiling_y) - min(ceiling_y) <= 1e-6
        if not (single_floor and single_ceiling):
            counters["height_multi_level_surface"] += 1
        else:
            # Rounded first, then tested, like room_area_m2 and resolve_size.
            height = round(max(ceiling_y) - min(floor_y), 4)
            if height > 0:
                room_height = height
            else:
                counters["height_non_positive"] += 1
    if room_height is None:
        counters["height_null"] += 1

    # ---- openings ---------------------------------------------------------
    # Only Door / Window / BayWindow have a schema slot. Hole and Pocket meshes
    # are not reshaped into anything: their geometry is not published, and the
    # only trace they leave is their type string in source_fields.mesh_types.
    doors, windows = [], []
    for mtype in CORE_OPENING_TYPES:
        for group in group_openings(openings.get(mtype, []), counters, mtype):
            obj = opening_object(group, mtype)
            if obj["height"] <= 0:
                counters[f"opening_{mtype}_non_positive_height"] += 1
                continue
            if len(obj["profile"]) < 4:
                counters[f"opening_{mtype}_group_hull_under_four"] += 1
                continue
            if mtype == "Window":
                try:
                    obj = indoor_window(group, [m for m in ref_meshes if m.get("type") == "WallInner"],
                                        floor_y, f"{house_uid}/{source_room_id}", openings.get("Window", []))
                except ValueError:
                    # Approved best effort: retain this opening's original
                    # representation rather than stop the full conversion.
                    counters["opening_Window_original_retained"] += 1
            counters[f"opening_{mtype}_published"] += 1
            (doors if mtype == "Door" else windows).append(obj)

    # ---- furniture --------------------------------------------------------
    # Doors and windows exist in the source twice: as meshes and as furniture
    # placements. Neither representation is dropped and nothing is deduplicated,
    # so furniture_quantity includes door and window placements.
    furniture = [
        furniture_record(house_uid, child,
                         ctx["furniture_by_uid"].get(child.get("ref")), counters)
        for child in furniture_children
    ]

    # Only source fields that say something about the layout and that no schema
    # field consumed. Matched by roomId: over 1,430 entries in 201 houses, 97.1%
    # name a room that exists, against 50.9% whose ref resolves against
    # furniture[].uid and 29.0% against mesh[].uid. ref is not kept -- it points
    # at uids this export does not publish, and it is a list (415 of the 1,430
    # carry three). Consequence: a room's n {dir, type} pairs cannot be matched
    # to its published door objects. That correspondence is lost.
    extension_door = [
        {"dir": entry.get("dir"), "type": entry.get("type")}
        for entry in ctx["extension_by_room"].get(source_room_id, [])
    ]

    return {
        "room_id": room_id,
        "room_index": room_index,
        "room_type": normalise_room_type(room.get("type")),
        "room_type_source": "source.scene.room[].type",
        "room_boundary": boundary,
        "room_boundary_type": boundary_type,
        "room_area_m2": room_area,
        "room_height": room_height,
        "coordinate_system": COORDINATE_SYSTEM,
        "doors": doors,
        "windows": windows,
        "furniture_quantity": len(furniture),
        "furniture": furniture,
        "source_fields": {
            "extension_door": extension_door,
            # Which construction elements this room is made of. The schema
            # consumed Floor/Ceiling/opening geometry and the WallInner window
            # interior planes; the type strings themselves it did not.
            "mesh_types": [mesh.get("type") for mesh in ref_meshes],
            "scene_boundingBox": ctx["scene_bounding_box"],
        },
    }


# --------------------------------------------------------------------------
# House level
# --------------------------------------------------------------------------


def load_json(path):
    with open(path, encoding="utf-8") as handle:
        return json.load(handle)


def house_context(data, counters):
    mesh_by_uid = {}
    for mesh in data.get("mesh", []):
        uid = mesh.get("uid")
        if uid is not None:
            mesh_by_uid[uid] = mesh

    furniture_by_uid = {}
    for defn in data.get("furniture", []):
        uid = defn.get("uid")
        if uid is None:
            continue
        counters["furniture_definitions_raw"] += 1
        existing = furniture_by_uid.get(uid)
        if existing is None:
            furniture_by_uid[uid] = defn
        else:
            counters["furniture_definitions_extra"] += 1
            if existing != defn:
                counters["furniture_definitions_conflicting"] += 1

    rooms = (data.get("scene") or {}).get("room", []) or []
    room_ids = {room.get("instanceid") for room in rooms}
    extension_by_room = defaultdict(list)
    for entry in (data.get("extension") or {}).get("door", []) or []:
        room_id = entry.get("roomId")
        if room_id in room_ids:
            extension_by_room[room_id].append(entry)
        else:
            counters["extension_door_unassigned"] += 1

    bounding_box, bad = sanitize_json((data.get("scene") or {}).get("boundingBox"))
    counters["nonfinite_source_values"] += len(bad)

    return {
        "mesh_by_uid": mesh_by_uid,
        "furniture_by_uid": furniture_by_uid,
        "extension_by_room": extension_by_room,
        "scene_bounding_box": bounding_box,
    }


def house_records(path, counters):
    data = load_json(path)
    house_uid = data.get("uid")
    if house_uid != path.stem:
        counters["uid_stem_mismatch"] += 1
    ctx = house_context(data, counters)
    rooms = (data.get("scene") or {}).get("room", []) or []
    # Provenance carries where the record came from and under what licence, the
    # way the collection does it -- s3d_unify.py:148-153 (source_house_id /
    # source_room_id / split / license_tag) with source_file in place of split,
    # since 3D-FRONT publishes no official split.
    provenance = {
        "source_file": path.name,
        "source_house_id": house_uid,
        "source_room_id": None,
        "license_tag": LICENSE_TAG,
    }
    records = []
    for room_index, room in enumerate(rooms):
        counters["rooms"] += 1
        built = room_record(house_uid, room_index, room, ctx, counters)
        counters["furniture_placements"] += built["furniture_quantity"]
        records.append({
            "sample_id": f"3dfront_{house_uid}::{built['room_id']}",
            "house_uid": house_uid,
            "room_index": room_index,
            "room": built,
            "provenance": dict(provenance, source_room_id=room.get("instanceid")),
        })
    return records


def atomic_write_lines(path, lines_iter):
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_suffix(path.suffix + ".part")
    with open(tmp, "w", encoding="utf-8") as handle:
        for line in lines_iter:
            handle.write(line)
            handle.write("\n")
        handle.flush()
        os.fsync(handle.fileno())
    os.replace(tmp, path)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--data-dir", type=Path, default=Path("data"))
    parser.add_argument("--out", type=Path, default=Path("3dfront.jsonl"))
    parser.add_argument("--limit", type=int, default=None,
                        help="convert only the first N houses (smoke test)")
    args = parser.parse_args()

    house_dir = args.data_dir / "3D-FRONT"
    files = sorted(house_dir.glob("*.json"))
    if not files:
        raise SystemExit(f"no house JSON under {house_dir}")
    # `is not None`, not a truth test: `if args.limit:` reads --limit 0 as
    # "no limit" and starts a full run off a typo.
    if args.limit is not None:
        files = files[: args.limit]

    counters = Counter()
    print(f"converting {len(files)} houses -> {args.out}", file=sys.stderr)

    def lines():
        for index, path in enumerate(files, 1):
            counters["houses"] += 1
            for record in house_records(path, counters):
                yield json.dumps(record, ensure_ascii=False, allow_nan=False,
                                 sort_keys=False)
            if index % 500 == 0:
                print(f"  {index}/{len(files)}", file=sys.stderr, flush=True)

    atomic_write_lines(args.out, lines())
    print(json.dumps(dict(sorted(counters.items())), ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()