File size: 50,980 Bytes
966b234
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Spatial helpers: build places to the contract's measured dimensions and report where things are.
//
// The video contract records numeric camera rigs per shot (lens, height, distance, azimuth, pitch)
// and place dimensions (road lanes and widths, frontage setbacks, vehicle interiors). Builders that
// guess these get the space wrong, so this module turns the numbers into a camera pose and simple,
// correctly sized geometry, and publishes a scene probe the replay records so the review can
// compare measured positions with the source video instead of eyeballing frames.
//
// Conventions (shared spec v1): metres, +Y up, -Z forward, X right. Screen coordinates are
// normalised to the viewport (x 0 = left .. 1 = right, y 0 = top .. 1 = bottom). Angles in degrees.
// Headings and yaw: 0 = -Z, positive turns right. Pitch: negative looks down. Roll: positive turns
// the camera counter-clockwise, so the horizon tilts clockwise on screen.
//
// Every import goes through ./three.js, which the installer points at the game's own three.js so
// this module and the game share one module instance. No DOM use except captureTopDown, which
// reads the renderer's canvas. See README.md next to this file.

import * as THREE from './three.js';

const DEG = Math.PI / 180;
const UP = new THREE.Vector3(0, 1, 0);

const finite = (value) => typeof value === 'number' && Number.isFinite(value);
const num = (value, fallback) => (finite(value) ? value : fallback);
const round = (value, digits = 4) => (finite(value) ? Number(value.toFixed(digits)) : null);

/** [x, y, z], {x, y, z} or a Vector3 -> new Vector3 (missing parts 0). */
function toVector(value, target = new THREE.Vector3()) {
  if (!value) return target.set(0, 0, 0);
  if (Array.isArray(value)) return target.set(num(value[0], 0), num(value[1], 0), num(value[2], 0));
  return target.set(num(value.x, 0), num(value.y, 0), num(value.z, 0));
}

/** Wrap an angle in degrees to (-180, 180]. */
function wrapDegrees(angle) {
  const wrapped = ((angle + 180) % 360 + 360) % 360 - 180;
  return wrapped === -180 ? 180 : wrapped;
}

// ---------------------------------------------------------------------------------------------
// Camera rigs (spec §1)
// ---------------------------------------------------------------------------------------------

const RIG_NUMBERS = ['hfov_deg', 'height_m', 'distance_m', 'horizon_y'];
const RIG_ANGLES = ['azimuth_deg', 'pitch_deg', 'roll_deg'];

/**
 * The rig at clip time ``t`` with its keyframes resolved, as a flat rig without ``keyframes``.
 *
 * Each keyframe holds the previous state's fields it does not name. Numbers interpolate linearly
 * between keyframes, angles along the shortest arc, ``subject_box`` per coordinate; other fields
 * (subject, confidence, ...) step. The base rig is the state at ``start`` (the shot's
 * ``start_seconds``); without ``start`` it holds until the first keyframe.
 */
export function rigAt(rig, t, { start } = {}) {
  if (!rig || typeof rig !== 'object') return {};
  const { keyframes, ...base } = rig;
  const frames = (Array.isArray(keyframes) ? keyframes : [])
    .filter((frame) => frame && finite(frame.t))
    .sort((a, b) => a.t - b.t);
  if (!frames.length || !finite(t)) return base;
  // Cumulative states: every keyframe carries the fields it inherited.
  const states = [];
  let previous = base;
  for (const { t: time, ...fields } of frames) {
    previous = { ...previous, ...fields };
    states.push({ time, state: previous });
  }
  const anchor = finite(start) && start < frames[0].t ? [{ time: start, state: base }] : [];
  const timeline = [...anchor, ...states];
  if (t <= timeline[0].time) return t < frames[0].t && !anchor.length ? base : { ...timeline[0].state };
  const last = timeline[timeline.length - 1];
  if (t >= last.time) return { ...last.state };
  let index = 0;
  while (timeline[index + 1].time < t) index += 1;
  const a = timeline[index], b = timeline[index + 1];
  const f = (t - a.time) / (b.time - a.time);
  const out = { ...a.state };
  for (const key of RIG_NUMBERS) {
    if (finite(a.state[key]) && finite(b.state[key])) out[key] = a.state[key] + (b.state[key] - a.state[key]) * f;
  }
  for (const key of RIG_ANGLES) {
    if (finite(a.state[key]) && finite(b.state[key])) {
      const angle = a.state[key] + wrapDegrees(b.state[key] - a.state[key]) * f;
      out[key] = key === 'azimuth_deg' ? ((angle % 360) + 360) % 360 : wrapDegrees(angle);
    }
  }
  const boxA = a.state.subject_box, boxB = b.state.subject_box;
  if (Array.isArray(boxA) && Array.isArray(boxB) && boxA.length === 4 && boxB.length === 4) {
    out.subject_box = boxA.map((value, i) => value + (boxB[i] - value) * f);
  }
  return out;
}

const _box = new THREE.Box3();
const _centre = new THREE.Vector3();
const _forward = new THREE.Vector3();
const _right = new THREE.Vector3();
const _offset = new THREE.Vector3();
const _position = new THREE.Vector3();
const _quaternion = new THREE.Quaternion();
const _euler = new THREE.Euler(0, 0, 0, 'YXZ');

function groundAt(ground, x, z) {
  return typeof ground === 'function' ? num(ground(x, z), 0) : num(ground, 0);
}

/**
 * Place and aim ``camera`` (a PerspectiveCamera) from a spec-§1 rig around ``subject``.
 *
 * ``subject`` is an Object3D (or a Vector3 position). Its centre is the centre of its world bounding
 * box (its world position when it has no geometry); its facing is ``subjectForward`` (subject-local,
 * default -Z; pass (0, 0, 1) for models authored facing +Z) flattened to the ground plane.
 * ``ground`` is the ground height, a number or ``(x, z) => y``. Pass a rig from ``rigAt`` when it
 * has keyframes.
 *
 * - ``azimuth_deg``: 0 behind the subject looking the way it faces, 90 on its right, 180 in front.
 * - ``height_m``: camera height above the ground under it. With ``distance_m`` the horizontal
 *   offset is solved so the 3D distance to the subject centre equals ``distance_m`` (the camera
 *   sits straight above when the height alone exceeds it). Without a height the camera sits on a
 *   sphere of ``distance_m`` at the elevation that ``pitch_deg`` implies.
 * - ``pitch_deg``: when absent, the camera looks at the subject centre. The camera always faces
 *   the subject horizontally; ``roll_deg`` turns it about its view axis.
 * - ``hfov_deg`` sets the vertical ``fov`` through ``camera.aspect``.
 */
export function placeShotCamera(camera, subject, rig = {}, { ground = 0, subjectForward = new THREE.Vector3(0, 0, -1) } = {}) {
  rig = rig || {};
  if (subject && subject.isObject3D) {
    subject.updateWorldMatrix(true, true);
    _box.setFromObject(subject, false);
    if (_box.isEmpty()) subject.getWorldPosition(_centre);
    else _box.getCenter(_centre);
    subject.getWorldQuaternion(_quaternion);
    _forward.copy(subjectForward).applyQuaternion(_quaternion);
  } else {
    toVector(subject, _centre);
    _forward.copy(subjectForward);
  }
  _forward.y = 0;
  if (_forward.lengthSq() < 1e-10) _forward.set(0, 0, -1);
  _forward.normalize();
  _right.crossVectors(_forward, UP).normalize();

  // Horizontal direction from the subject to the camera.
  const azimuth = num(rig.azimuth_deg, 0) * DEG;
  _offset.copy(_forward).multiplyScalar(-Math.cos(azimuth)).addScaledVector(_right, Math.sin(azimuth));

  const pitch = finite(rig.pitch_deg) ? rig.pitch_deg * DEG : null;
  let horizontal, y;
  if (finite(rig.height_m)) {
    // Solve against the ground under the subject, then set the final height from the ground
    // under the camera (they differ only on slopes).
    const rise = groundAt(ground, _centre.x, _centre.z) + rig.height_m - _centre.y;
    if (finite(rig.distance_m)) horizontal = Math.sqrt(Math.max(rig.distance_m ** 2 - rise ** 2, 0));
    else if (pitch !== null && pitch < -1e-3 && rise > 0) horizontal = rise / Math.tan(-pitch);
    else horizontal = 6;
    _position.copy(_centre).addScaledVector(_offset, horizontal);
    y = groundAt(ground, _position.x, _position.z) + rig.height_m;
  } else {
    const distance = num(rig.distance_m, 6);
    const elevation = pitch === null ? 0 : -pitch; // looking down by p means sitting p above
    horizontal = distance * Math.cos(elevation);
    _position.copy(_centre).addScaledVector(_offset, horizontal);
    y = _centre.y + distance * Math.sin(elevation);
  }
  _position.y = y;

  // Aim: face the subject horizontally (the offset reversed), pitch as given or at its centre.
  const yaw = horizontal > 1e-6 ? Math.atan2(_offset.x, _offset.z) : Math.atan2(-_forward.x, -_forward.z);
  const lookPitch = pitch !== null ? pitch : Math.atan2(_centre.y - y, Math.max(horizontal, 1e-6));
  _euler.set(lookPitch, yaw, num(rig.roll_deg, 0) * DEG, 'YXZ');
  _quaternion.setFromEuler(_euler);

  if (camera.parent) {
    camera.parent.updateWorldMatrix(true, false);
    camera.position.copy(camera.parent.worldToLocal(_position.clone()));
    camera.quaternion.copy(camera.parent.getWorldQuaternion(new THREE.Quaternion()).invert().multiply(_quaternion));
  } else {
    camera.position.copy(_position);
    camera.quaternion.copy(_quaternion);
  }
  if (finite(rig.hfov_deg) && camera.isPerspectiveCamera) {
    const aspect = num(camera.aspect, 1) || 1;
    camera.fov = 2 * Math.atan(Math.tan((rig.hfov_deg * DEG) / 2) / aspect) / DEG;
  }
  if (camera.updateProjectionMatrix) camera.updateProjectionMatrix();
  camera.updateMatrixWorld(true);
  return camera;
}

// ---------------------------------------------------------------------------------------------
// Scene probe (spec §3)
// ---------------------------------------------------------------------------------------------

/** Tag ``object`` with its contract type (and instance) so the scene probe reports it. */
export function tagObject(object, typeId, instanceId) {
  object.userData.gbbTypeId = String(typeId);
  if (instanceId !== undefined && instanceId !== null) object.userData.gbbInstanceId = String(instanceId);
  return object;
}

// Box edges as corner index pairs; corner bit 0 = x max, bit 1 = y max, bit 2 = z max.
const EDGES = [[0, 1], [2, 3], [4, 5], [6, 7], [0, 2], [1, 3], [4, 6], [5, 7], [0, 4], [1, 5], [2, 6], [3, 7]];

/**
 * Projects objects' bounding boxes for the probe. Local boxes (the object and its descendants in
 * the object's own frame) are cached, so each probe call costs 8 corner transforms per object.
 * The cache refreshes when an object's child count changes or on ``invalidate(object)``.
 */
class BoxProjector {
  constructor() {
    this.local = new WeakMap();
    this.corners = Array.from({ length: 8 }, () => new THREE.Vector3());
    this.front = new Array(8).fill(false);
    this.point = new THREE.Vector3();
    this.inverse = new THREE.Matrix4();
    this.relative = new THREE.Matrix4();
    this.child = new THREE.Box3();
    this.crossing = new THREE.Vector3();
  }

  invalidate(object) {
    if (object) this.local.delete(object);
    else this.local = new WeakMap();
  }

  localBox(object) {
    const cached = this.local.get(object);
    if (cached && cached.children === object.children.length) return cached.box;
    // The hierarchy's box in the object's frame: each geometry's box through child -> object.
    object.updateMatrixWorld(true);
    const box = new THREE.Box3();
    this.inverse.copy(object.matrixWorld).invert();
    object.traverse((node) => {
      let bounds = null;
      if (node.isInstancedMesh) {
        if (!node.boundingBox) node.computeBoundingBox();
        bounds = node.boundingBox;
      } else if (node.geometry) {
        if (!node.geometry.boundingBox) node.geometry.computeBoundingBox();
        bounds = node.geometry.boundingBox;
      }
      if (!bounds || bounds.isEmpty()) return;
      this.relative.multiplyMatrices(this.inverse, node.matrixWorld);
      box.union(this.child.copy(bounds).applyMatrix4(this.relative));
    });
    if (box.isEmpty()) box.set(new THREE.Vector3(), new THREE.Vector3()); // a tagged empty is a point
    this.local.set(object, { box, children: object.children.length });
    return box;
  }

  /**
   * Normalised, viewport-clipped screen box of ``object`` (written to ``out``) and its centre's
   * distance from the camera, or null when the box is behind the camera or off screen.
   * Corners behind the near plane are replaced by the box edges' crossings of it, so boxes that
   * straddle the camera stay correct.
   */
  project(object, camera, viewInverse, cameraPosition, out) {
    object.updateWorldMatrix(true, false);
    const box = this.localBox(object);
    const { corners, front, point } = this;
    const near = -Math.max(num(camera.near, 0.1), 1e-4);
    this.relative.multiplyMatrices(viewInverse, object.matrixWorld);
    let inFront = 0;
    for (let i = 0; i < 8; i += 1) {
      corners[i].set(i & 1 ? box.max.x : box.min.x, i & 2 ? box.max.y : box.min.y, i & 4 ? box.max.z : box.min.z)
        .applyMatrix4(this.relative);
      front[i] = corners[i].z <= near;
      if (front[i]) inFront += 1;
    }
    if (!inFront) return null;
    let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
    const add = (p) => {
      point.copy(p).applyMatrix4(camera.projectionMatrix);
      if (point.x < x0) x0 = point.x;
      if (point.x > x1) x1 = point.x;
      if (point.y < y0) y0 = point.y;
      if (point.y > y1) y1 = point.y;
    };
    for (let i = 0; i < 8; i += 1) if (front[i]) add(corners[i]);
    if (inFront < 8) {
      for (const [a, b] of EDGES) {
        if (front[a] === front[b]) continue;
        const f = (near - corners[a].z) / (corners[b].z - corners[a].z);
        add(this.crossing.copy(corners[a]).lerp(corners[b], f));
      }
    }
    if (x1 < -1 || x0 > 1 || y1 < -1 || y0 > 1) return null;
    // NDC (y up) -> normalised screen (y down), clipped to the viewport.
    const clip = (v) => Math.min(Math.max(v, -1), 1);
    out[0] = (clip(x0) + 1) / 2;
    out[1] = (1 - clip(y1)) / 2;
    out[2] = (clip(x1) + 1) / 2;
    out[3] = (1 - clip(y0)) / 2;
    point.copy(box.min).add(box.max).multiplyScalar(0.5).applyMatrix4(object.matrixWorld);
    return point.distanceTo(cameraPosition);
  }
}

function collectTagged(root, list) {
  // Invisible subtrees are not on screen; tagged objects inside tagged objects are reported too.
  if (!root || root.visible === false) return list;
  if (root.userData && root.userData.gbbTypeId) list.push(root);
  const children = root.children;
  for (let i = 0; i < children.length; i += 1) collectTagged(children[i], list);
  return list;
}

const _view = new THREE.Vector3();
const _a = new THREE.Vector3();
const _b = new THREE.Vector3();

/**
 * Where the horizon (the plane y = camera.y at infinity) crosses the frame's centre column,
 * normalised; null when the camera looks straight up/down or the horizon is off screen.
 */
function horizonY(camera, position, viewInverse) {
  camera.getWorldDirection(_forward);
  _forward.y = 0;
  if (_forward.lengthSq() < 1e-8) return null;
  _forward.normalize();
  _right.crossVectors(_forward, UP);
  const far = 1e6;
  const project = (direction, target) => {
    target.copy(position).addScaledVector(direction, far).applyMatrix4(viewInverse);
    if (target.z >= 0) return null;
    return target.applyMatrix4(camera.projectionMatrix);
  };
  const a = project(_forward, _a);
  if (!a) return null;
  // A second point on the horizon gives its slope under roll; evaluate the line at x = 0 (centre).
  const b = project(_view.copy(_forward).addScaledVector(_right, 0.25).normalize(), _b);
  let y = a.y;
  if (b && Math.abs(b.x - a.x) > 1e-9) y = a.y + (b.y - a.y) * (0 - a.x) / (b.x - a.x);
  if (!finite(y) || y < -1 || y > 1) return null;
  return (1 - y) / 2;
}

/**
 * Define ``window.__gbbSceneProbe`` (on ``globalThis``) returning the spec-§3 record:
 * ``{shot, camera: {hfov_deg, position, height_m, yaw_deg, pitch_deg, roll_deg, horizon_y},
 *   objects: [{type_id, instance_id, box, distance_m, visible}]}``.
 *
 * Objects are those tagged with ``tagObject`` (``userData.gbbTypeId``). Pass ``camera`` or
 * ``getCamera`` (when the game switches cameras), ``getShot`` for the current trailer shot id and
 * ``groundHeightAt(x, z)`` for the ground under the camera (default 0). A game the player walks through
 * also passes ``getPlace``: ``() => ({id, origin: [x, y, z], yaw_deg})`` for the contract place the
 * camera is in and where that place's frame sits in the world (its origin, and the heading its -Z axis
 * points along, clockwise from world -Z); the record then carries ``camera.place: {id, x_m, z_m,
 * yaw_deg}``, the camera in the place's own frame, which the review checks against the contract's
 * ``route``, and ``shot`` defaults to the place id. The probe never throws: it
 * returns ``{error}`` instead. Returns the probe function, with ``probe.invalidate(object?)`` to
 * drop cached bounds after replacing an object's geometry.
 *
 * A game rendering in a worker calls the returned function there and posts the result to the page,
 * whose own ``window.__gbbSceneProbe`` returns the latest one.
 */
export function installSceneProbe({ camera, getCamera, scene, getShot, getPlace, groundHeightAt, target = globalThis } = {}) {
  const projector = new BoxProjector();
  const viewInverse = new THREE.Matrix4();
  const position = new THREE.Vector3();
  const quaternion = new THREE.Quaternion();
  const euler = new THREE.Euler(0, 0, 0, 'YXZ');
  const screen = [0, 0, 0, 0];
  const tagged = [];

  const probe = () => {
    try {
      const cam = getCamera ? getCamera() : camera;
      if (!cam || !scene) return { error: 'no camera or scene' };
      cam.updateWorldMatrix(true, false);
      viewInverse.copy(cam.matrixWorld).invert();
      cam.getWorldPosition(position);
      cam.getWorldQuaternion(quaternion);
      euler.setFromQuaternion(quaternion, 'YXZ');
      const aspect = num(cam.aspect, 1) || 1;
      const hfov = cam.isPerspectiveCamera
        ? 2 * Math.atan((Math.tan((cam.fov * DEG) / 2) / (num(cam.zoom, 1) || 1)) * aspect) / DEG : null;
      let ground = 0;
      if (groundHeightAt) {
        try { ground = num(groundHeightAt(position.x, position.z), 0); } catch { ground = 0; }
      }
      let horizon = null;
      try { horizon = horizonY(cam, position, viewInverse); } catch { horizon = null; }

      const objects = [];
      tagged.length = 0;
      collectTagged(scene, tagged);
      for (const object of tagged) {
        try {
          const distance = projector.project(object, cam, viewInverse, position, screen);
          if (distance === null) continue;
          const entry = { type_id: object.userData.gbbTypeId };
          if (object.userData.gbbInstanceId) entry.instance_id = object.userData.gbbInstanceId;
          entry.box = screen.map((v) => round(v));
          entry.distance_m = round(distance, 2);
          entry.visible = true;
          objects.push(entry);
        } catch {
          // One malformed object must not cost the whole record.
        }
      }
      let shot = null;
      if (getShot) {
        try { shot = getShot() ?? null; } catch { shot = null; }
      }
      let place = null;
      if (getPlace) {
        try {
          const spec = getPlace();
          if (spec && spec.id != null) {
            const origin = toVector(spec.origin);
            const heading = num(spec.yaw_deg, 0) * DEG;
            const dx = position.x - origin.x, dz = position.z - origin.z;
            place = {
              id: String(spec.id),
              x_m: round(dx * Math.cos(heading) + dz * Math.sin(heading), 3),
              z_m: round(-dx * Math.sin(heading) + dz * Math.cos(heading), 3),
              yaw_deg: round(wrapDegrees(-euler.y / DEG - num(spec.yaw_deg, 0)), 2),
            };
            if (shot === null) shot = place.id;
          }
        } catch { place = null; }
      }
      return {
        shot,
        camera: {
          ...(place ? { place } : {}),
          hfov_deg: round(hfov, 2),
          position: [round(position.x, 3), round(position.y, 3), round(position.z, 3)],
          height_m: round(position.y - ground, 3),
          yaw_deg: round(wrapDegrees(-euler.y / DEG), 2),
          pitch_deg: round(euler.x / DEG, 2),
          roll_deg: round(euler.z / DEG, 2),
          horizon_y: horizon === null ? null : round(horizon),
        },
        objects,
      };
    } catch (error) {
      return { error: String((error && error.message) || error) };
    }
  };
  probe.invalidate = (object) => projector.invalidate(object);
  if (target) target.__gbbSceneProbe = probe;
  return probe;
}

// ---------------------------------------------------------------------------------------------
// Places (spec §2): roads, frontage, vehicle interiors
// ---------------------------------------------------------------------------------------------

const MATERIALS = {
  asphalt: { color: 0x3b3b3d, roughness: 0.92 },
  marking: { color: 0xeeeeea, roughness: 0.7 },
  concrete: { color: 0xb5b2aa, roughness: 0.85 },
  kerb: { color: 0xc9c6bf, roughness: 0.8 },
  sidewalk: { color: 0x9e9b95, roughness: 0.9 },
  grass: { color: 0x56783d, roughness: 1 },
  metal: { color: 0x8c9196, roughness: 0.45, metalness: 0.8 },
  building: { color: 0xa9a49a, roughness: 0.85 },
  tower: { color: 0x8d97a1, roughness: 0.4, metalness: 0.3 },
  fence: { color: 0x6d6a64, roughness: 0.7, metalness: 0.4 },
  hedge: { color: 0x3f5f2e, roughness: 1 },
  water: { color: 0x2d4f63, roughness: 0.15 },
  trim: { color: 0x2b2b2e, roughness: 0.8 },
  seat: { color: 0x3a3a40, roughness: 0.95 },
  dash: { color: 0x1f1f22, roughness: 0.7 },
  wall: { color: 0x8f8d86, roughness: 0.9 },
  floor: { color: 0x5b5a57, roughness: 0.95 },
  ceiling: { color: 0x77756f, roughness: 0.95 },
};

/** A fresh MeshStandardMaterial per call so games can replace or tint each independently. */
function material(kind) {
  return new THREE.MeshStandardMaterial({ ...MATERIALS[kind] });
}

function mesh(name, geometry, kind) {
  const result = new THREE.Mesh(geometry, typeof kind === 'string' ? material(kind) : kind);
  result.name = name;
  return result;
}

const CURVE_RADIUS = { straight: 0, gentle_left: -500, gentle_right: 500, sharp_left: -80, sharp_right: 80 };

/** Signed curvature (1/m, positive turns right) of a road block. ``radius_m`` overrides the preset. */
function curvatureOf(road) {
  const sign = /left/.test(String(road.curvature || '')) ? -1 : 1;
  if (finite(road.radius_m) && road.radius_m > 0 && road.curvature && road.curvature !== 'straight') {
    return sign / road.radius_m;
  }
  const radius = CURVE_RADIUS[road.curvature] || 0;
  return radius ? 1 / radius : 0;
}

/**
 * Centre-line frame ``s`` metres along a road block from its start: ``position`` (with
 * ``offset`` metres to the right applied), ``right`` (horizontal unit vector) and ``heading_deg``
 * (0 = -Z, positive right). Curves are constant-radius arcs; ``grade_pct`` raises the surface
 * linearly. Use it to place vehicles and props along curved or sloped roads.
 */
export function roadFrameAt(road, s, offset = 0) {
  const k = curvatureOf(road || {});
  const theta = k * s;
  const x = Math.abs(k) > 1e-12 ? (1 - Math.cos(theta)) / k : 0;
  const z = Math.abs(k) > 1e-12 ? -Math.sin(theta) / k : -s;
  const right = new THREE.Vector3(Math.cos(theta), 0, Math.sin(theta));
  const position = new THREE.Vector3(x, (num(road && road.grade_pct, 0) / 100) * s, z).addScaledVector(right, offset);
  return { position, right, heading_deg: theta / DEG };
}

/**
 * Sweep a cross-section along the road. ``profile`` is a list of [x, y] (x to the right of the
 * centre line); each consecutive pair becomes a strip with its own vertices so edges stay crisp.
 * ``segments`` are [s0, s1] intervals (one per strip run, e.g. a dash).
 */
function sweep(road, profile, segments, step) {
  const positions = [];
  const indices = [];
  const pairs = [];
  for (let i = 0; i + 1 < profile.length; i += 1) pairs.push([profile[i], profile[i + 1]]);
  for (const [s0, s1] of segments) {
    const count = Math.max(1, Math.ceil((s1 - s0) / step));
    for (const [[ax, ay], [bx, by]] of pairs) {
      const base = positions.length / 3;
      for (let i = 0; i <= count; i += 1) {
        const s = s0 + ((s1 - s0) * i) / count;
        const a = roadFrameAt(road, s, ax).position;
        const b = roadFrameAt(road, s, bx).position;
        positions.push(a.x, a.y + ay, a.z, b.x, b.y + by, b.z);
      }
      // Profiles run left to right / bottom to top so faces point up or outward (CCW from outside).
      for (let i = 0; i < count; i += 1) {
        const p = base + i * 2;
        indices.push(p, p + 1, p + 2, p + 1, p + 3, p + 2);
      }
    }
  }
  const geometry = new THREE.BufferGeometry();
  geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
  geometry.setIndex(indices);
  geometry.computeVertexNormals();
  return geometry;
}

/** Closed box profile [x0..x1] x [y0..y1]: left side, top, right side (bottom and ends open). */
const boxProfile = (x0, x1, y0, y1) => [[x0, y0], [x0, y1], [x1, y1], [x1, y0]];
const flat = (x0, x1, y = 0) => [[x0, y], [x1, y]];

/** Widths of a road block's cross-section, with defaults for missing fields. */
export function roadLayout(road = {}) {
  const lanes = Math.max(1, Math.round(num(road.lanes, 2)));
  const laneWidth = num(road.lane_width_m, 3.5);
  const shoulder = Math.max(0, num(road.shoulder_m, 0));
  const sidewalk = Math.max(0, num(road.sidewalk_m, 0));
  const medianKind = (road.median && road.median.kind) || 'none';
  const median = medianKind === 'none' ? 0 : Math.max(0, num(road.median && road.median.width_m, 0.8));
  const carriageway = lanes * laneWidth + 2 * shoulder + median;
  return { lanes, laneWidth, shoulder, sidewalk, medianKind, median, carriageway, width: carriageway + 2 * sidewalk };
}

/**
 * A road from a spec-§2 ``road`` block as a THREE.Group. Origin at the start of the centre line on
 * the road surface, running toward -Z. Cross-section, left to right: sidewalk (with kerb),
 * shoulder, oncoming lanes, median, forward lanes, shoulder, sidewalk; total width
 * ``lanes * lane_width_m + 2 * shoulder_m + median.width_m + 2 * sidewalk_m``. Two-way unless
 * ``oneway: true`` (right-hand traffic: the right half runs forward). An elevated road keeps its
 * surface at y = 0 and adds a deck, parapets and piers down to the ground at
 * ``-deck_height_m`` (default 8). Curvature presets are arcs of 500 m (gentle) and 80 m (sharp)
 * radius unless ``radius_m`` is given.
 *
 * ``group.userData``: ``lanes`` (lane centre x offsets, left to right), ``laneDirections``
 * ('oncoming' | 'forward'), ``width_m``, ``carriageway_m``, ``length_m``, ``ground_y``.
 */
export function buildRoad(spec = {}) {
  const road = spec.road && typeof spec.road === 'object' ? spec.road : spec;
  const layout = roadLayout(road);
  const { lanes, laneWidth, shoulder, sidewalk, medianKind, median, carriageway, width } = layout;
  const length = Math.max(1, num(road.length_m, 200));
  const step = curvatureOf(road) ? 4 : length; // straight roads need only their two ends
  const whole = [[0, length]];
  const group = new THREE.Group();
  group.name = 'road';

  const half = carriageway / 2;
  const oneway = road.oneway === true;
  const leftLanes = oneway ? 0 : Math.floor(lanes / 2);
  const medianX0 = -half + shoulder + leftLanes * laneWidth;
  const laneCentres = [];
  const laneDirections = [];
  for (let i = 0; i < lanes; i += 1) {
    const x = -half + shoulder + (i + 0.5) * laneWidth + (i >= leftLanes ? median : 0);
    laneCentres.push(x);
    laneDirections.push(i < leftLanes ? 'oncoming' : 'forward');
  }

  group.add(mesh('road.asphalt', sweep(road, flat(-half, half), whole, step), 'asphalt'));

  // Markings sit 1 cm above the asphalt to avoid z-fighting; 15 cm wide.
  const lift = 0.01, line = 0.15;
  const solid = [];
  const dashed = [];
  const edgeLeft = -half + shoulder, edgeRight = half - shoulder;
  solid.push(edgeLeft + line / 2, edgeRight - line / 2);
  if (median > 0) solid.push(medianX0 + line / 2, medianX0 + median - line / 2);
  for (let i = 1; i < lanes; i += 1) {
    const x = -half + shoulder + i * laneWidth + (i >= leftLanes ? median : 0);
    if (i === leftLanes) {
      if (median === 0) solid.push(x - line, x + line); // two-way without a median: double line
    } else {
      dashed.push(x);
    }
  }
  const strips = (xs, segments) => {
    const geometries = xs.map((x) => sweep(road, flat(x - line / 2, x + line / 2, lift), segments, step));
    return mergeGeometries(geometries);
  };
  group.add(mesh('road.markings.solid', strips(solid, whole), 'marking'));
  if (dashed.length) {
    const dashes = []; // 3 m dash, 9 m gap
    for (let s = 1; s + 3 <= length; s += 12) dashes.push([s, s + 3]);
    if (dashes.length) group.add(mesh('road.markings.dashed', strips(dashed, dashes), 'marking'));
  }

  if (medianKind === 'concrete_barrier' && median > 0) {
    const barrier = Math.min(median, 0.8);
    const centre = medianX0 + median / 2;
    group.add(mesh('road.median.barrier', sweep(road, boxProfile(centre - barrier / 2, centre + barrier / 2, 0, 0.9), whole, step), 'concrete'));
  } else if (medianKind === 'grass' && median > 0) {
    group.add(mesh('road.median.grass', sweep(road, boxProfile(medianX0, medianX0 + median, 0, 0.15), whole, step), 'grass'));
  }

  // Sidewalks: a 15 cm raised slab whose road-side face is the kerb, with a lighter kerb stone.
  for (const [side, x0, x1] of [['left', -width / 2, -half], ['right', half, width / 2]]) {
    if (sidewalk <= 0) continue;
    group.add(mesh(`road.sidewalk.${side}`, sweep(road, boxProfile(x0, x1, 0, 0.15), whole, step), 'sidewalk'));
    const kerbX = side === 'left' ? x1 - 0.2 : x0;
    group.add(mesh(`road.kerb.${side}`, sweep(road, boxProfile(kerbX, kerbX + 0.2, 0, 0.16), whole, step), 'kerb'));
  }

  let groundY = 0;
  if (road.elevated) {
    const deckHeight = Math.max(1, num(road.deck_height_m, 8));
    const thickness = 1.2;
    groundY = -deckHeight;
    // Deck slab: right side, underside, left side (the top is the road surface).
    group.add(mesh('road.deck', sweep(road, [[width / 2, 0], [width / 2, -thickness], [-width / 2, -thickness], [-width / 2, 0]], whole, step), 'concrete'));
    for (const [side, x0] of [['left', -width / 2], ['right', width / 2 - 0.3]]) {
      group.add(mesh(`road.railing.${side}`, sweep(road, boxProfile(x0, x0 + 0.3, 0, 0.85), whole, step), 'concrete'));
      group.add(mesh(`road.railing.${side}.rail`, sweep(road, boxProfile(x0 + 0.1, x0 + 0.2, 0.85, 1.1), whole, step), 'metal'));
    }
    // Piers every 30 m: one instanced box, from the ground to the deck underside.
    const spacing = 30;
    const count = Math.max(1, Math.floor(length / spacing) + 1);
    const pierHeight = deckHeight - thickness;
    const pierWidth = Math.min(width * 0.6, 6);
    const pier = new THREE.InstancedMesh(new THREE.BoxGeometry(1, 1, 1), material('concrete'), count);
    pier.name = 'road.piers';
    const matrix = new THREE.Matrix4();
    for (let i = 0; i < count; i += 1) {
      const frame = roadFrameAt(road, Math.min(i * spacing + 5, length - 1));
      matrix.compose(
        new THREE.Vector3(frame.position.x, frame.position.y - thickness - pierHeight / 2, frame.position.z),
        new THREE.Quaternion().setFromAxisAngle(UP, -frame.heading_deg * DEG),
        new THREE.Vector3(pierWidth, pierHeight, 1.5),
      );
      pier.setMatrixAt(i, matrix);
    }
    pier.computeBoundingBox();
    group.add(pier);
  }

  group.userData = {
    lanes: laneCentres, laneDirections, width_m: width, carriageway_m: carriageway, length_m: length,
    ground_y: groundY, curvature: road.curvature || 'straight', grade_pct: num(road.grade_pct, 0),
  };
  return group;
}

/** Concatenate indexed position-only geometries (sweep output) into one draw call. */
function mergeGeometries(geometries) {
  const positions = [];
  const indices = [];
  for (const geometry of geometries) {
    const offset = positions.length / 3;
    positions.push(...geometry.getAttribute('position').array);
    for (const index of geometry.getIndex().array) indices.push(index + offset);
    geometry.dispose();
  }
  const merged = new THREE.BufferGeometry();
  merged.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
  merged.setIndex(indices);
  merged.computeVertexNormals();
  return merged;
}

/** Deterministic 0..1 sequence so a place rebuilds identically every load. */
function random(seed) {
  let state = seed >>> 0 || 1;
  return () => {
    state = (state * 1664525 + 1013904223) >>> 0;
    return state / 4294967296;
  };
}

const FRONTAGE = {
  towers: { material: 'tower', depth: 22, spacing: 30, fill: 0.75, storey: 3.4, height: 60 },
  low_rise: { material: 'building', depth: 12, spacing: 15, fill: 0.85, storey: 3.1, height: 9 },
};

/**
 * Buildings, fences, hedges and water beside a road from spec-§2 ``frontage`` blocks.
 *
 * ``setback_m`` is measured from the road's outer edge (``road`` gives the edge, its curvature and
 * grade; otherwise the edge is at x = +/-``edge_m``, default 0) to the front face. ``spacing_m``
 * is centre to centre; heights come from ``height_m`` or ``storeys`` and vary +/-20 % between
 * towers. Ground level follows the road's grade and ``ground_y`` (below an elevated deck).
 */
export function buildFrontage(spec, { length_m = 200, road = null, edge_m, seed = 7 } = {}) {
  const blocks = (Array.isArray(spec) ? spec : spec && Array.isArray(spec.frontage) ? spec.frontage : [spec])
    .filter((block) => block && typeof block === 'object');
  const roadBlock = road && road.road ? road.road : road || {};
  const edge = finite(edge_m) ? edge_m : road ? roadLayout(roadBlock).width / 2 : 0;
  const groundY = roadBlock.elevated ? -Math.max(1, num(roadBlock.deck_height_m, 8)) : 0;
  const length = Math.max(1, num(length_m, num(roadBlock.length_m, 200)));
  const group = new THREE.Group();
  group.name = 'frontage';
  const rand = random(seed);
  const matrix = new THREE.Matrix4();
  const rotation = new THREE.Quaternion();
  const unitBox = new THREE.BoxGeometry(1, 1, 1).translate(0, 0.5, 0); // base at y = 0
  const step = curvatureOf(roadBlock) ? 4 : length;

  blocks.forEach((block, index) => {
    const side = block.side === 'left' ? -1 : 1;
    const sideName = side < 0 ? 'left' : 'right';
    const kind = block.kind || 'open';
    const setback = Math.max(0, num(block.setback_m, 5));
    const name = `frontage.${sideName}.${kind}.${index}`;
    if (FRONTAGE[kind]) {
      const preset = FRONTAGE[kind];
      const spacing = Math.max(2, num(block.spacing_m, preset.spacing));
      const baseHeight = num(block.height_m, finite(block.storeys) ? block.storeys * preset.storey : preset.height);
      const count = Math.max(1, Math.floor(length / spacing));
      const buildings = new THREE.InstancedMesh(unitBox, material(preset.material), count);
      buildings.name = name;
      for (let i = 0; i < count; i += 1) {
        const s = (i + 0.5) * spacing;
        const height = kind === 'towers' ? baseHeight * (0.8 + 0.4 * rand()) : baseHeight;
        const frame = roadFrameAt(roadBlock, s, side * (edge + setback + preset.depth / 2));
        rotation.setFromAxisAngle(UP, -frame.heading_deg * DEG);
        matrix.compose(
          frame.position.setY(frame.position.y + groundY), rotation,
          new THREE.Vector3(preset.depth, height, spacing * preset.fill), // X across the road, Z along it
        );
        buildings.setMatrixAt(i, matrix);
      }
      buildings.computeBoundingBox();
      group.add(buildings);
    } else if (kind === 'fence' || kind === 'hedge') {
      const thickness = kind === 'fence' ? 0.06 : 1.0;
      const height = num(block.height_m, kind === 'fence' ? 1.8 : 1.5);
      const x = side * (edge + setback + thickness / 2);
      const geometry = sweep(roadBlock, boxProfile(x - thickness / 2, x + thickness / 2, groundY, groundY + height), [[0, length]], step);
      group.add(mesh(name, geometry, kind));
    } else if (kind === 'water') {
      const near = side * (edge + setback), far = side * (edge + setback + 400);
      const geometry = sweep(roadBlock, flat(Math.min(near, far), Math.max(near, far), groundY - 1), [[0, length]], step);
      group.add(mesh(name, geometry, 'water'));
    }
  });
  group.userData = { edge_m: edge, length_m: length };
  return group;
}

/**
 * A simple car interior shell from a spec-§2 ``interior`` block, as a THREE.Group.
 *
 * Origin: the cabin's centre in plan (x = centre line, z = halfway along ``length_m``) at floor
 * level; -Z points to the windshield, X to the right. Mount coordinates in ``camera_mounts`` use
 * this frame: a floor origin is the one the spec's example fits (a 1.1 m dash mount inside a
 * 1.15 m cabin). Seat cushions are at ``userData.hip_y``.
 *
 * Parts: floor, roof, lower side panels, firewall and dashboard, rear panel, A/B/C pillars, seat
 * rows (two seats in front, a bench behind). The windshield, side and rear windows are openings
 * between the beltline and the roof. ``userData.mounts`` maps mount id -> {position, look_at}
 * (Vector3s, cabin frame), and each mount is also a child Object3D named ``mount.<id>`` oriented to
 * its ``look_at``: ``mount.add(camera)`` puts a camera there looking the right way.
 */
export function buildCabin(interior = {}) {
  const spec = interior.interior && typeof interior.interior === 'object' ? interior.interior : interior;
  const W = Math.max(0.8, num(spec.width_m, 1.45));
  const L = Math.max(1.2, num(spec.length_m, 2.6));
  const H = Math.max(0.8, num(spec.height_m, 1.15));
  const rows = Math.max(1, Math.round(num(spec.seat_rows, 2)));
  const t = 0.04; // panel thickness
  const belt = H * 0.62; // beltline: bottom of the windows
  const hip = H * 0.28; // seat cushion top
  const front = -L / 2, back = L / 2;
  const rake = Math.min(0.7, L * 0.22); // windshield runs back by this much from base to top
  const group = new THREE.Group();
  group.name = 'cabin';

  const box = (name, kind, w, h, d, x, y, z) => {
    const part = mesh(name, new THREE.BoxGeometry(w, h, d), kind);
    part.position.set(x, y, z);
    group.add(part);
    return part;
  };
  box('cabin.floor', 'trim', W, t, L, 0, -t / 2, 0);
  box('cabin.roof', 'trim', W, t, L - rake, 0, H + t / 2, (front + rake + back) / 2);
  for (const [side, x] of [['left', -W / 2 - t / 2], ['right', W / 2 + t / 2]]) {
    box(`cabin.side.${side}`, 'trim', t, belt, L, x, belt / 2, 0);
  }
  box('cabin.firewall', 'trim', W, belt, t, 0, belt / 2, front - t / 2);
  box('cabin.rear', 'trim', W, belt, t, 0, belt / 2, back + t / 2);
  const dashDepth = Math.min(0.55, L * 0.2);
  box('cabin.dashboard', 'dash', W, 0.18, dashDepth, 0, belt + 0.02 - 0.09, front + dashDepth / 2);

  // Pillars: A raked from the dash corners to the roof's front edge; B behind the front row; C at the back.
  const pillar = 0.08;
  const aLength = Math.hypot(rake, H - belt);
  for (const [side, x] of [['left', -W / 2 + pillar / 2], ['right', W / 2 - pillar / 2]]) {
    const a = box(`cabin.pillar.a.${side}`, 'trim', pillar, aLength, pillar, x, (belt + H) / 2, front + rake / 2);
    a.rotation.x = Math.atan2(rake, H - belt); // top leans back toward +Z
    if (rows > 1) box(`cabin.pillar.b.${side}`, 'trim', pillar, H - belt, pillar, x, (belt + H) / 2, front + L * 0.48);
    box(`cabin.pillar.c.${side}`, 'trim', pillar * 1.5, H - belt, pillar * 1.5, x, (belt + H) / 2, back - pillar * 0.75);
  }

  // Seats: rows spread from just behind the dash to the back; front row has two seats.
  const rowSpan = (L - dashDepth - 0.5) / rows;
  const seatDepth = Math.min(0.55, rowSpan * 0.6);
  const back_h = Math.min(H - hip - 0.15, 0.65);
  for (let r = 0; r < rows; r += 1) {
    const z = front + dashDepth + 0.45 + r * rowSpan + seatDepth / 2;
    const seats = r === 0 && W > 1.1 ? [[-W / 4, W / 2 - 0.2], [W / 4, W / 2 - 0.2]] : [[0, W - 0.2]];
    seats.forEach(([x, w], i) => {
      const label = seats.length > 1 ? (i === 0 ? 'left' : 'right') : 'bench';
      box(`cabin.seat.${r}.${label}`, 'seat', w, hip, seatDepth, x, hip / 2, z);
      const rest = box(`cabin.seat.${r}.${label}.back`, 'seat', w, back_h, 0.12, x, hip + back_h / 2, z + seatDepth / 2);
      rest.rotation.x = 0.18; // reclined
    });
  }

  const mounts = {};
  const up = new THREE.Vector3(0, 1, 0);
  const rotation = new THREE.Matrix4();
  for (const spot of Array.isArray(spec.camera_mounts) ? spec.camera_mounts : []) {
    if (!spot || !spot.id) continue;
    const position = new THREE.Vector3(num(spot.x, 0), num(spot.y, hip + 0.7), num(spot.z, 0));
    const lookAt = Array.isArray(spot.look_at) ? toVector(spot.look_at) : position.clone().add(new THREE.Vector3(0, 0, -1));
    mounts[spot.id] = { position, look_at: lookAt };
    const anchor = new THREE.Object3D();
    anchor.name = `mount.${spot.id}`;
    anchor.position.copy(position);
    // Matrix4.lookAt points -Z at the target, as a camera looks.
    anchor.quaternion.setFromRotationMatrix(rotation.lookAt(position, lookAt, up));
    group.add(anchor);
  }
  group.userData = { width_m: W, length_m: L, height_m: H, hip_y: hip, beltline_y: belt, mounts };
  return group;
}

// ---------------------------------------------------------------------------------------------
// Top-down capture
// ---------------------------------------------------------------------------------------------

/**
 * An orthographic top-down render of ``scene`` as a PNG data URL, -Z (forward) at the top of the
 * image. ``centre`` is [x, y, z] (or a Vector3), ``size_m`` the square's side. Renders through the
 * renderer's own canvas at ``pixels`` square and restores its size, pixel ratio, render target and
 * the scene's fog; the canvas stays blank until the game's next frame. Returns null when the
 * canvas has no ``toDataURL`` (OffscreenCanvas) or anything fails.
 */
// Rooms -------------------------------------------------------------------------------------

const ON_WALL_M = 0.6; // an opening this close to a room's wall line is cut into that wall

function roomSpecs(place) {
  return (Array.isArray(place.rooms) ? place.rooms : []).filter((room) => room && room.id
    && [room.x_m, room.z_m, room.width_m, room.length_m].every(finite) && room.width_m > 0 && room.length_m > 0);
}

/** A place point in a room's own axes (centre 0, 0). yaw_deg is a heading: clockwise seen from above. */
function roomLocal(room, x, z) {
  const yaw = num(room.yaw_deg, 0) * DEG;
  const dx = x - room.x_m, dz = z - room.z_m;
  return [dx * Math.cos(yaw) + dz * Math.sin(yaw), -dx * Math.sin(yaw) + dz * Math.cos(yaw)];
}

function roomWorld(room, lx, lz) {
  const yaw = num(room.yaw_deg, 0) * DEG;
  return [room.x_m + lx * Math.cos(yaw) - lz * Math.sin(yaw), room.z_m + lx * Math.sin(yaw) + lz * Math.cos(yaw)];
}

/** The id of the room containing a place point (within `margin` metres of its walls), or null. */
export function roomAt(place = {}, x = 0, z = 0, margin = 0) {
  for (const room of roomSpecs(place)) {
    const [lx, lz] = roomLocal(room, x, z);
    if (Math.abs(lx) <= room.width_m / 2 + margin && Math.abs(lz) <= room.length_m / 2 + margin) return String(room.id);
  }
  return null;
}

/**
 * The rooms of a contract `rooms` place, built to size: floors, ceilings and walls with every opening
 * cut out (a lintel above a door, a sill below a window). The group is in the place frame (origin where
 * the player enters, -Z the way they first face); position and rotate the group to put the place in your
 * world. Each room is a child group `room.<id>`; parts are named `room.<id>.floor|ceiling|wall.<side>.<n>`.
 *
 * group.userData: {segments: [{x0, z0, x1, z1, room}] solid wall lines in the place frame (for
 * resolveWalls and your own ray casts), rooms: {id: spec}, openings: [spec]}.
 *
 * Walls sit inside each room's outline (`wall_m` thick), so two rooms that share a wall get two walls back
 * to back and the room's clear size is the contract's size minus the wall thickness on each side.
 */
export function buildRooms(place = {}, { wall_m = 0.12, door_height_m = 2.1, sill_m = 0.9, ceilings = true } = {}) {
  const group = new THREE.Group();
  group.name = `rooms.${place.id || 'place'}`;
  const openings = (Array.isArray(place.openings) ? place.openings : []).filter((o) => o
    && [o.x_m, o.z_m, o.width_m].every(finite) && o.width_m > 0);
  const segments = [];
  const rooms = {};
  for (const room of roomSpecs(place)) {
    const id = String(room.id);
    rooms[id] = room;
    const W = room.width_m, L = room.length_m, H = Math.max(1.6, num(room.height_m, 2.8));
    const node = new THREE.Group();
    node.name = `room.${id}`;
    node.position.set(room.x_m, num(room.floor_y_m, 0), room.z_m);
    node.rotation.y = -num(room.yaw_deg, 0) * DEG;
    const add = (name, kind, w, h, d, x, y, z) => {
      const part = mesh(name, new THREE.BoxGeometry(w, h, d), kind);
      part.position.set(x, y, z);
      part.receiveShadow = true;
      node.add(part);
      return part;
    };
    add(`room.${id}.floor`, 'floor', W, 0.1, L, 0, -0.05, 0);
    if (ceilings) add(`room.${id}.ceiling`, 'ceiling', W, 0.1, L, 0, H + 0.05, 0);
    // Sides run corner to corner; (nx, nz) points into the room.
    const sides = [
      ['north', -W / 2, -L / 2, 1, 0, W, 0, 1], ['east', W / 2, -L / 2, 0, 1, L, -1, 0],
      ['south', W / 2, L / 2, -1, 0, W, 0, -1], ['west', -W / 2, L / 2, 0, -1, L, 1, 0],
    ];
    for (const [side, ax, az, ux, uz, length, nx, nz] of sides) {
      const gaps = [];
      for (const opening of openings) {
        const [lx, lz] = roomLocal(room, opening.x_m, opening.z_m);
        const along = (lx - ax) * ux + (lz - az) * uz;
        const across = Math.abs((lx - ax) * nx + (lz - az) * nz);
        const half = opening.width_m / 2;
        if (across <= ON_WALL_M && along > -half && along < length + half) {
          const window = opening.kind === 'window';
          gaps.push({ from: Math.max(0, along - half), to: Math.min(length, along + half),
            bottom: window ? num(opening.sill_m, sill_m) : 0,
            top: Math.min(H, (window ? num(opening.sill_m, sill_m) : 0) + num(opening.height_m, window ? 1.2 : door_height_m)) });
        }
      }
      gaps.sort((a, b) => a.from - b.from);
      let cursor = 0, index = 0;
      const wall = (from, to, bottom, top) => {
        if (to - from < 1e-3 || top - bottom < 1e-3) return;
        const mid = (from + to) / 2;
        const x = ax + ux * mid + nx * wall_m / 2, z = az + uz * mid + nz * wall_m / 2;
        add(`room.${id}.wall.${side}.${index}`, 'wall', ux ? to - from : wall_m, top - bottom, uz ? to - from : wall_m,
          x, (bottom + top) / 2, z);
        index += 1;
      };
      const solid = (from, to) => {
        if (to - from < 1e-3) return;
        wall(from, to, 0, H);
        const [x0, z0] = roomWorld(room, ax + ux * from, az + uz * from);
        const [x1, z1] = roomWorld(room, ax + ux * to, az + uz * to);
        segments.push({ x0, z0, x1, z1, room: id });
      };
      for (const gap of gaps) {
        solid(cursor, gap.from);
        if (gap.to > Math.max(cursor, gap.from)) {
          wall(Math.max(cursor, gap.from), gap.to, gap.top, H); // lintel
          wall(Math.max(cursor, gap.from), gap.to, 0, gap.bottom); // sill (windows)
        }
        cursor = Math.max(cursor, gap.to);
      }
      solid(cursor, length);
    }
    group.add(node);
  }
  group.userData = { segments, rooms, openings };
  return group;
}

/**
 * Keep a walker out of the walls: moves `position` (anything with x and z, in the place frame) so a circle
 * of `radius` around it clears every wall segment of `rooms` (a buildRooms group or its segments array).
 * Call it after each movement step; returns true when the position was pushed.
 */
export function resolveWalls(rooms, position, radius = 0.35) {
  const segments = Array.isArray(rooms) ? rooms : (rooms && rooms.userData && rooms.userData.segments) || [];
  let pushed = false;
  for (let pass = 0; pass < 3; pass += 1) {
    let moved = false;
    for (const s of segments) {
      const ex = s.x1 - s.x0, ez = s.z1 - s.z0;
      const span = ex * ex + ez * ez;
      const k = span > 0 ? Math.min(1, Math.max(0, ((position.x - s.x0) * ex + (position.z - s.z0) * ez) / span)) : 0;
      const dx = position.x - (s.x0 + ex * k), dz = position.z - (s.z0 + ez * k);
      const distance = Math.hypot(dx, dz);
      if (distance < radius) {
        // On the line exactly: push along the wall's normal.
        const [px, pz] = distance > 1e-6 ? [dx / distance, dz / distance] : [-ez / Math.sqrt(span || 1), ex / Math.sqrt(span || 1)];
        position.x += px * (radius - distance);
        position.z += pz * (radius - distance);
        moved = true;
      }
    }
    pushed = pushed || moved;
    if (!moved) break;
  }
  return pushed;
}

export function captureTopDown(renderer, scene, { centre = [0, 0, 0], size_m = 120, pixels = 512 } = {}) {
  const canvas = renderer && renderer.domElement;
  if (!canvas || typeof canvas.toDataURL !== 'function' || !scene) return null;
  const size = renderer.getSize(new THREE.Vector2());
  const ratio = renderer.getPixelRatio();
  const target = renderer.getRenderTarget();
  const fog = scene.fog;
  const half = Math.max(1, num(size_m, 120)) / 2;
  const at = toVector(centre);
  const camera = new THREE.OrthographicCamera(-half, half, half, -half, 0.1, 5000);
  camera.position.set(at.x, at.y + 1000, at.z);
  camera.up.set(0, 0, -1);
  camera.lookAt(at.x, at.y, at.z);
  camera.updateMatrixWorld(true);
  let url = null;
  try {
    scene.fog = null; // fog would swallow everything from 1 km up
    renderer.setRenderTarget(null);
    renderer.setPixelRatio(1);
    renderer.setSize(pixels, pixels, false);
    renderer.render(scene, camera);
    url = canvas.toDataURL('image/png'); // same task as the render, so no preserveDrawingBuffer needed
  } catch {
    url = null;
  } finally {
    scene.fog = fog;
    renderer.setPixelRatio(ratio);
    renderer.setSize(size.x, size.y, false);
    renderer.setRenderTarget(target);
  }
  return url;
}

/**
 * Define ``window.__gbbTopDown(opts)`` (on ``globalThis``) returning ``captureTopDown``'s data URL
 * for a review tool. ``opts``: ``centre``, ``size_m``, ``pixels``; the default centre is
 * ``getCentre()`` (e.g. the player's position) or the origin. Never throws: returns null.
 */
export function installTopDownProbe({ renderer, scene, getCentre, size_m = 120, pixels = 512, target = globalThis } = {}) {
  const capture = (opts = {}) => {
    try {
      const centre = opts.centre ?? (getCentre ? getCentre() : [0, 0, 0]);
      return captureTopDown(renderer, scene, {
        centre, size_m: num(opts.size_m, size_m), pixels: Math.round(num(opts.pixels, pixels)),
      });
    } catch {
      return null;
    }
  };
  if (target) target.__gbbTopDown = capture;
  return capture;
}