File size: 42,158 Bytes
c40323b
 
 
 
 
 
 
e5c56d3
 
 
 
 
 
0c57009
 
 
 
e5c56d3
c40323b
 
 
 
 
 
 
d8a4502
8f53ca3
0c57009
 
c40323b
0c57009
e5c56d3
 
 
0c57009
 
 
e5c56d3
0c57009
4bcabcd
e5c56d3
4bcabcd
e5c56d3
4bcabcd
e5c56d3
 
 
 
0c57009
 
 
e5c56d3
0c57009
e5c56d3
d97b165
0c57009
e5c56d3
0c57009
e5c56d3
 
 
0c57009
 
 
 
 
 
 
 
e5c56d3
 
 
 
 
 
 
 
 
 
c40323b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c57009
e5c56d3
 
 
 
 
 
4bcabcd
 
e5c56d3
4bcabcd
 
e5c56d3
 
 
 
 
 
 
 
 
 
 
 
 
c40323b
af724e7
 
 
035d7e4
af724e7
 
 
 
 
0c57009
af724e7
0c57009
 
 
 
 
e5c56d3
0c57009
e5c56d3
 
 
 
0c57009
e5c56d3
af724e7
 
0c57009
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af724e7
 
c40323b
0c57009
 
 
 
d97b165
0c57009
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e5c56d3
 
 
0c57009
 
 
e5c56d3
 
 
 
 
 
 
 
 
 
 
 
0c57009
e5c56d3
0c57009
e5c56d3
 
 
 
0c57009
e5c56d3
 
 
 
4bcabcd
 
 
 
e5c56d3
 
4bcabcd
 
 
 
 
e5c56d3
 
4bcabcd
 
 
 
 
 
e5c56d3
 
 
 
 
 
 
4bcabcd
e5c56d3
 
 
 
d97b165
0c57009
 
 
 
 
 
 
 
 
e5c56d3
 
 
 
0c57009
d97b165
e5c56d3
 
 
 
 
 
 
 
0c57009
 
e5c56d3
 
0c57009
 
e5c56d3
 
0c57009
e5c56d3
 
 
 
 
 
 
 
 
0c57009
e5c56d3
0c57009
 
e5c56d3
 
 
 
 
0c57009
 
 
 
 
 
 
 
e5c56d3
 
0c57009
 
e5c56d3
0c57009
e5c56d3
 
0c57009
 
 
 
 
 
e5c56d3
 
 
 
 
0c57009
 
e5c56d3
4bcabcd
0c57009
4bcabcd
 
0c57009
 
 
 
e5c56d3
0c57009
 
 
 
 
 
 
4bcabcd
 
 
0c57009
 
 
 
 
 
 
 
 
 
 
 
e5c56d3
 
 
 
 
 
 
 
 
0c57009
 
 
 
 
 
e5c56d3
d8a4502
0c57009
 
 
 
e5c56d3
 
 
 
 
0c57009
 
 
e5c56d3
 
 
 
 
0c57009
e5c56d3
 
 
 
0c57009
e5c56d3
 
 
0c57009
e5c56d3
0c57009
 
 
 
e5c56d3
0c57009
 
 
 
e5c56d3
 
 
 
 
 
 
0c57009
e5c56d3
 
 
 
 
 
0c57009
e5c56d3
 
0c57009
 
 
 
 
 
 
 
 
 
 
 
e5c56d3
 
d8a4502
 
 
 
 
 
 
 
 
 
c40323b
e5c56d3
c40323b
 
e5c56d3
 
c40323b
0c57009
d8a4502
e5c56d3
 
 
 
0c57009
c40323b
 
 
 
 
 
 
e5c56d3
 
 
c44ce0b
0c57009
e5c56d3
 
 
0c57009
e5c56d3
 
c40323b
 
 
d8a4502
e5c56d3
c40323b
 
 
4bcabcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c40323b
 
e5c56d3
4bcabcd
 
 
e5c56d3
 
 
 
4bcabcd
c40323b
 
 
 
 
 
 
 
 
 
 
 
4bcabcd
c40323b
 
 
 
 
 
 
 
 
 
4bcabcd
 
0c57009
4bcabcd
 
 
 
 
 
 
 
c40323b
 
 
e5c56d3
 
 
 
c40323b
e5c56d3
 
 
4bcabcd
 
 
 
 
 
 
 
 
 
c40323b
0c57009
 
 
 
 
 
 
 
 
 
 
 
 
e5c56d3
 
 
 
 
 
c40323b
e5c56d3
 
0c57009
 
c40323b
 
e5c56d3
0c57009
 
e5c56d3
c40323b
e5c56d3
 
0c57009
 
 
 
 
 
 
e5c56d3
c40323b
e5c56d3
 
0c57009
4bcabcd
 
 
0c57009
 
 
 
e5c56d3
0c57009
 
e5c56d3
 
 
 
0c57009
e5c56d3
 
c40323b
e5c56d3
0c57009
e5c56d3
 
c40323b
e5c56d3
0c57009
 
e5c56d3
0c57009
e5c56d3
0c57009
 
 
 
 
 
e5c56d3
 
 
c40323b
0c57009
e5c56d3
c40323b
 
e5c56d3
 
 
0c57009
e5c56d3
c40323b
 
 
 
e5c56d3
c40323b
 
 
 
 
 
 
0c57009
 
 
c40323b
4bcabcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c40323b
 
4bcabcd
c40323b
d97b165
 
c40323b
 
0c57009
c40323b
 
 
 
 
 
 
 
 
 
 
 
 
0c57009
 
e5c56d3
 
 
0c57009
c40323b
 
 
 
e5c56d3
c40323b
 
 
0c57009
c40323b
 
0c57009
c40323b
0c57009
 
 
 
c40323b
 
0c57009
c40323b
 
 
 
 
0c57009
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c40323b
 
 
 
0c57009
 
 
 
c40323b
 
 
 
 
 
0c57009
c40323b
 
 
 
 
0c57009
c40323b
 
 
 
 
 
 
0c57009
 
c40323b
 
 
 
 
0c57009
c40323b
 
 
 
 
 
 
 
 
 
 
 
e5c56d3
c40323b
 
0c57009
c40323b
 
 
e5c56d3
c40323b
 
 
 
4bcabcd
 
 
 
0c57009
4bcabcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c57009
 
 
 
 
 
 
 
 
 
4bcabcd
0c57009
4bcabcd
 
0c57009
 
 
4bcabcd
 
 
 
 
 
 
0c57009
4bcabcd
 
 
 
0c57009
 
 
4bcabcd
 
 
0c57009
 
 
 
 
 
c40323b
e5c56d3
c40323b
e5c56d3
 
 
 
 
 
 
 
 
 
 
 
 
4bcabcd
 
 
 
 
 
e5c56d3
0c57009
 
e5c56d3
 
0c57009
 
 
 
e5c56d3
0c57009
e5c56d3
 
0c57009
 
 
 
 
e5c56d3
0c57009
 
e5c56d3
0c57009
 
 
 
 
 
 
 
 
 
 
e5c56d3
0c57009
 
e5c56d3
 
 
0c57009
 
e5c56d3
 
0c57009
 
e5c56d3
4bcabcd
e5c56d3
 
0c57009
e5c56d3
 
0c57009
e5c56d3
0c57009
e5c56d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bcabcd
 
 
0c57009
c40323b
af724e7
c40323b
 
 
 
 
 
e5c56d3
 
 
0c57009
 
 
e5c56d3
 
 
 
 
c40323b
0c57009
 
 
 
e5c56d3
4bcabcd
0c57009
 
 
 
 
 
 
4bcabcd
e5c56d3
c40323b
4bcabcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c40323b
0c57009
 
 
 
 
 
 
 
e5c56d3
 
 
 
 
 
 
 
 
 
0c57009
c40323b
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
;(function () {
  'use strict'

  function $(id) {
    return document.getElementById(id)
  }

  function svgEl(tag, attrs) {
    var el = document.createElementNS('http://www.w3.org/2000/svg', tag)
    if (attrs) for (var k in attrs) el.setAttribute(k, attrs[k])
    return el
  }

  function rgba(triplet, alpha) {
    return 'rgba(' + triplet + ',' + alpha + ')'
  }

  var svg = null
  var wrap = null
  var W = 0
  var H = 0
  var camCX = 0
  var camCY = 0
  var SCALE = 0
  var zoomLevel = 1.0
  /** World km from camera to farthest canvas corner when zoom label = 100%; +/- zoom scales this radius. */
  var BASE_VIEW_RADIUS_KM = 1.5
  /** Keeps map labels readable vs panel type (~15% bump; pair with .coastal-surveillance-sim font-size). */
  var MAP_LABEL_SCALE = 1.15

  var worldG = null
  var bgSky = null
  var bgSea = null
  var horizLine = null
  var ringsG = null
  var compassG = null
  var zonesG = null

  var dynamicCamG = null
  var rearCamG = null
  var coneEl = null
  var coneRearEl = null
  var camPointer = null
  var camPointerRear = null
  var camDot = null
  var camCorners = []
  var boatG = null
  var boatHalo = null
  var boatIconG = null
  var boatIconScaleG = null
  var boatHull = null
  var trajLine = null
  var boatTrail = null
  var bearingLine = null

  var anchorSOuter = null
  var anchorS = null
  var anchorEOuter = null
  var anchorE = null
  var anchorSLabel = null
  var anchorELabel = null

  var trailFlat = []
  var TRAIL_CAP = 100
  var TRAIL_MIN_DIST = 0.0028
  /** Min blind+detected metres before showing blind share (avoids noisy % on tiny streaks). */
  var MIN_BLIND_SHARE_M = 10
  var lastTrailIconAngle = NaN

  var FONT_SANS = 'Saira Condensed, Arial Narrow, Arial, sans-serif'
  var statCache = {}

  var lastTrackSx = NaN
  var lastTrackSy = NaN
  var lastTrackEx = NaN
  var lastTrackEy = NaN
  var lastDrawScale = NaN
  var prevInFov = null

  var boatStart = { x: 0.0, y: 1.0 }
  var boatEnd = { x: 0.0, y: 0.15 }
  var dragging = null
  var camHeading = 0
  var boatT = 0
  var boatDir = 1
  var lastTime = null

  var prevVisible = null
  var detectedStreak = 0
  var blindStreak = 0
  var lastDetectedStreak = 0
  var lastBlindStreak = 0
  var prevDetectedStreak = 0
  var prevBlindStreak = 0

  var lastPinchDist = null
  var running = false
  var camDir = -1

  var inpFov = null
  var inpFrontSpeed = null
  var inpBackSpeed = null
  var inpFrontArc = null
  var inpBoatSpeed = null
  var inpFov2 = null
  var inpCam2Offset = null

  /** Invalidated when FOV / camera count / scale changes cone geometry. */
  var cachedConeGeomKey = ''

  var lastDrawBx = NaN
  var lastDrawBy = NaN

  var hitL = 0
  var hitT = 0
  var hitSx = 1
  var hitSy = 1

  var resizeRaf = 0
  var panelStatsRaf = 0
  var panelStatsPayload = null
  var zoomVisualRaf = 0

  var C = {
    p: '', d: '', s: '', w: '', s1: '', s2: '',
    pr: '', dr: '', sr: '', wr: '',
    pc: '', dc: '', sc: '', wc: '', hi: '', lo: '',
  }

  var systemQuery = window.matchMedia('(prefers-color-scheme: light)')

  function loadColors() {
    var cs = getComputedStyle(document.querySelector('.coastal-surveillance-sim'))
    function v(n) { return cs.getPropertyValue(n).trim() }
    C.p = v('--primary'); C.d = v('--danger'); C.s = v('--success'); C.w = v('--warning')
    C.s1 = v('--surface-1'); C.s2 = v('--surface-2')
    C.pr = v('--primary-rgb'); C.dr = v('--danger-rgb'); C.sr = v('--success-rgb'); C.wr = v('--warning-rgb')
    C.pc = v('--primary-content'); C.dc = v('--danger-content'); C.sc = v('--success-content'); C.wc = v('--warning-content')
    C.hi = v('--content-hi'); C.lo = v('--content-lo')
    if (horizLine) horizLine.setAttribute('stroke', rgba(C.pr, 0.4))
    if (zoomVisualRaf) { cancelAnimationFrame(zoomVisualRaf); zoomVisualRaf = 0 }
    buildWorldElements()
    buildZones()
    prevInFov = null
    syncThemedSceneStrokes()
    if (panelStatsRaf) { cancelAnimationFrame(panelStatsRaf); panelStatsRaf = 0 }
    panelStatsPayload = null
  }

  function initTheme() {
    var btns = document.querySelectorAll('.theme-btn')
    function applyTheme(pref) {
      var sim = document.querySelector('.coastal-surveillance-sim')
      sim.dataset.theme = pref === 'system' ? (systemQuery.matches ? 'light' : 'dark') : pref
      loadColors()
      for (var i = 0; i < btns.length; i++)
        btns[i].classList.toggle('active', btns[i].dataset.themeVal === pref)
    }
    applyTheme(localStorage.getItem('theme') || 'system')
    systemQuery.addEventListener('change', function () {
      if (localStorage.getItem('theme') === 'system') applyTheme('system')
    })
    for (var j = 0; j < btns.length; j++)
      btns[j].addEventListener('click', function () {
        localStorage.setItem('theme', this.dataset.themeVal)
        applyTheme(this.dataset.themeVal)
      })
  }

  function resetStreaks() {
    detectedStreak = blindStreak = lastDetectedStreak = lastBlindStreak = 0
    prevDetectedStreak = prevBlindStreak = prevVisible = null
  }


  function clearTrail(resetIconAngle) {
    trailFlat.length = 0
    if (resetIconAngle !== false) lastTrailIconAngle = NaN
    if (boatTrail) boatTrail.setAttribute('points', '')
  }

  function flushTrailPoly() {
    if (!boatTrail || !trailFlat.length) return
    var s = trailFlat[0] + ',' + trailFlat[1]
    for (var i = 2; i < trailFlat.length; i += 2)
      s += ' ' + trailFlat[i] + ',' + trailFlat[i + 1]
    boatTrail.setAttribute('points', s)
  }

  function appendTrail(bx, by) {
    var m = trailFlat.length
    if (m >= 2) {
      var lx = trailFlat[m - 2]
      var ly = trailFlat[m - 1]
      if (Math.hypot(bx - lx, by - ly) < TRAIL_MIN_DIST) return
    }
    trailFlat.push(bx, by)
    while (trailFlat.length > TRAIL_CAP * 2) {
      trailFlat.shift()
      trailFlat.shift()
    }
    flushTrailPoly()
  }

  function sectorPath(fromDeg, toDeg, R, maxSteps) {
    var span = ((toDeg - fromDeg) + 360) % 360
    var steps = Math.ceil(span / 2)
    steps = maxSteps != null && maxSteps > 0
      ? Math.max(4, Math.min(maxSteps, Math.max(steps, 4)))
      : Math.max(64, steps)
    var d = 'M 0 0'
    for (var i = 0; i <= steps; i++) {
      var deg = fromDeg + (span / steps) * i
      var rad = deg * Math.PI / 180
      d += ' L ' + (Math.sin(rad) * R) + ' ' + (Math.cos(rad) * R)
    }
    return d + ' Z'
  }

  function zoneFillRadiusWorld() {
    if (SCALE === 0) return 0.1
    function distWorld(px, py) {
      return Math.hypot((px - camCX) / SCALE, (camCY - py) / SCALE)
    }
    return Math.max(Math.max(distWorld(0, 0), distWorld(W, 0), distWorld(W, H), distWorld(0, H)) * 1.08, 0.04)
  }

  function coneRadiusWorld() {
    if (SCALE === 0) return 0.1
    return Math.max(zoneFillRadiusWorld(), Math.hypot(W, H) / SCALE * 1.12)
  }

  function syncConeAndPointerShape(p) {
    if (!coneEl || SCALE === 0) return
    var q = p || getParams()
    var fov1 = q.fov
    var fov2 = q.fov2
    var two = q.twoCam
    var R = coneRadiusWorld()
    var ptrLen = 32 / SCALE
    var key = [fov1, fov2, two ? 1 : 0, R.toFixed(8), ptrLen.toExponential(10)].join('|')
    if (key === cachedConeGeomKey) return
    cachedConeGeomKey = key
    var half1 = fov1 / 2
    coneEl.setAttribute('d', sectorPath(-half1, half1, R, 22))
    camPointer.setAttribute('x2', 0)
    camPointer.setAttribute('y2', ptrLen)
    if (coneRearEl && camPointerRear) {
      var half2 = fov2 / 2
      coneRearEl.setAttribute('d', sectorPath(-half2, half2, R, 22))
      camPointerRear.setAttribute('x2', 0)
      camPointerRear.setAttribute('y2', ptrLen)
    }
  }

  function syncThemedSceneStrokes() {
    if (!coneEl) return
    coneEl.setAttribute('fill', rgba(C.pr, 0.12))
    coneEl.setAttribute('stroke', rgba(C.pr, 0.6))
    camPointer.setAttribute('stroke', rgba(C.pr, 0.9))
    /* Secondary FOV colors updated per frame in draw() for current layout. */
    camDot.setAttribute('fill', C.p)
    camDot.setAttribute('stroke', rgba(C.pr, 0.5))
    trajLine.setAttribute('stroke', rgba(C.dr, 0.25))
    bearingLine.setAttribute('stroke', rgba(C.dr, 0.12))
    if (boatTrail) boatTrail.setAttribute('stroke', rgba(C.dr, 0.55))
    for (var i = 0; i < 4; i++) camCorners[i].setAttribute('stroke', rgba(C.pr, 0.5))
    anchorSOuter.setAttribute('stroke', rgba(C.dr, 0.72))
    anchorS.setAttribute('fill', rgba(C.dr, 0.52))
    anchorS.setAttribute('stroke', rgba(C.dr, 0.45))
    anchorEOuter.setAttribute('stroke', rgba(C.wr, 0.72))
    anchorE.setAttribute('fill', rgba(C.wr, 0.48))
    anchorE.setAttribute('stroke', rgba(C.wr, 0.42))
    anchorSLabel.setAttribute('fill', rgba(C.dr, 0.88))
    anchorELabel.setAttribute('fill', rgba(C.wr, 0.88))
  }

  function updateTrackSvgGeomIfNeeded() {
    if (boatStart.x === lastTrackSx && boatStart.y === lastTrackSy &&
        boatEnd.x === lastTrackEx && boatEnd.y === lastTrackEy) return
    if (!isNaN(lastTrackSx)) clearTrail()
    lastTrackSx = boatStart.x
    lastTrackSy = boatStart.y
    lastTrackEx = boatEnd.x
    lastTrackEy = boatEnd.y
    trajLine.setAttribute('x1', boatStart.x)
    trajLine.setAttribute('y1', boatStart.y)
    trajLine.setAttribute('x2', boatEnd.x)
    trajLine.setAttribute('y2', boatEnd.y)
    anchorSOuter.setAttribute('cx', boatStart.x)
    anchorSOuter.setAttribute('cy', boatStart.y)
    anchorS.setAttribute('cx', boatStart.x)
    anchorS.setAttribute('cy', boatStart.y)
    anchorEOuter.setAttribute('cx', boatEnd.x)
    anchorEOuter.setAttribute('cy', boatEnd.y)
    anchorE.setAttribute('cx', boatEnd.x)
    anchorE.setAttribute('cy', boatEnd.y)
    var syOff = 14 * MAP_LABEL_SCALE / SCALE
    anchorSLabel.setAttribute('x', boatStart.x)
    anchorSLabel.setAttribute('y', -(boatStart.y - syOff))
    anchorELabel.setAttribute('x', boatEnd.x)
    anchorELabel.setAttribute('y', -(boatEnd.y - syOff))
  }

  function updateScaleOnlySvgGeom() {
    var cr = 8 / SCALE
    var cornerPx = 14 / SCALE
    camDot.setAttribute('r', cr)
    for (var ci = 0; ci < 4; ci++) {
      var wx = (ci === 0 || ci === 3 ? -1 : 1) * cornerPx
      var wy = (ci < 2 ? 1 : -1) * cornerPx
      camCorners[ci].setAttribute('x1', wx * 0.4)
      camCorners[ci].setAttribute('y1', wy * 0.4)
      camCorners[ci].setAttribute('x2', wx)
      camCorners[ci].setAttribute('y2', wy)
    }
    var rHit = 6 / SCALE
    var rRing = 10 / SCALE
    anchorS.setAttribute('r', rHit)
    anchorSOuter.setAttribute('r', rRing)
    anchorE.setAttribute('r', rHit)
    anchorEOuter.setAttribute('r', rRing)
    boatHalo.setAttribute('r', 22 / SCALE)
    var fsA = 11 * MAP_LABEL_SCALE / SCALE
    anchorSLabel.setAttribute('font-size', fsA)
    anchorELabel.setAttribute('font-size', fsA)
    var iconPx = 15 / SCALE
    boatIconScaleG.setAttribute('transform', 'scale(' + iconPx + ')')
    syncConeAndPointerShape(null)
    lastTrackSx = NaN
  }

  function buildLineZone(x1, y1, x2, y2) {
    return svgEl('line', {
      x1: x1, y1: y1, x2: x2, y2: y2,
      stroke: rgba(C.pr, 0.5), 'stroke-width': 1, 'stroke-dasharray': '5 5',
      'vector-effect': 'non-scaling-stroke',
    })
  }

  function buildZones() {
    if (!zonesG || SCALE === 0) return
    while (zonesG.firstChild) zonesG.removeChild(zonesG.firstChild)
    var frontArc = +inpFrontArc.value
    var fh = frontArc / 2
    var R = zoneFillRadiusWorld()
    var oscillate = isOscillatePan()
    zonesG.appendChild(svgEl('path', { d: sectorPath(-fh, fh, R), fill: rgba(C.pr, 0.07), stroke: 'none' }))
    var backFill = oscillate ? rgba(C.dr, 0.022) : rgba(C.dr, 0.06)
    zonesG.appendChild(svgEl('path', { d: sectorPath(fh, 360 - fh, R), fill: backFill, stroke: 'none' }))
    var e1r = (-fh) * Math.PI / 180
    var e2r = fh * Math.PI / 180
    zonesG.appendChild(buildLineZone(0, 0, Math.sin(e1r) * R, Math.cos(e1r) * R))
    zonesG.appendChild(buildLineZone(0, 0, Math.sin(e2r) * R, Math.cos(e2r) * R))
    var labelR = 80 / SCALE
    var fs = 11 * MAP_LABEL_SCALE / SCALE
    var tf = svgEl('text', { x: 0, y: -labelR, transform: 'scale(1,-1)',
      fill: C.pc, 'font-size': fs, 'font-family': FONT_SANS, 'text-anchor': 'middle' })
    tf.textContent = 'FRONT ' + frontArc + '\u00b0'
    zonesG.appendChild(tf)
    var tb = svgEl('text', { x: 0, y: 18 * MAP_LABEL_SCALE / SCALE, transform: 'scale(1,-1)',
      fill: C.dc, 'font-size': fs, 'font-family': FONT_SANS, 'text-anchor': 'middle' })
    tb.textContent = oscillate
      ? ('OUTSIDE SWEEP ' + (360 - frontArc) + '\u00b0')
      : ('BACK ' + (360 - frontArc) + '\u00b0')
    zonesG.appendChild(tb)
    var edgeTxt = '\u00b1' + fh.toFixed(0) + '\u00b0'
    for (var ei = 0; ei < 2; ei++) {
      var rad = ei ? e2r : e1r
      var tx = svgEl('text', {
        x: Math.sin(rad) * labelR, y: -(Math.cos(rad) * labelR),
        transform: 'scale(1,-1)', fill: C.lo,
        'font-size': fs, 'font-family': FONT_SANS, 'text-anchor': 'middle',
      })
      tx.textContent = edgeTxt
      zonesG.appendChild(tx)
    }
  }

  function fmtDist(d) {
    return d < 1 ? Math.round(d * 1000) + 'm' : d.toFixed(d < 10 ? 2 : 1).replace(/\.0+$/, '') + 'km'
  }

  function buildWorldElements() {
    if (!ringsG || !compassG || SCALE === 0) return
    while (ringsG.firstChild) ringsG.removeChild(ringsG.firstChild)
    var nice = [0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.0, 5.0]
    var ringInterval = nice[0]
    for (var i = 0; i < nice.length; i++) {
      var px = nice[i] * SCALE
      if (px >= 100 && px <= 240) { ringInterval = nice[i]; break }
      if (px < 100) ringInterval = nice[i]
    }
    var maxDist = viewportMaxCornerPx() / SCALE
    var maxRing = Math.ceil(maxDist / ringInterval) + 1
    var fs = 12 * MAP_LABEL_SCALE / SCALE
    var tw = 5 / SCALE
    for (var ri = 1; ri <= maxRing; ri++) {
      var r = ri * ringInterval
      ringsG.appendChild(svgEl('circle', { cx: 0, cy: 0, r: r, fill: 'none',
        stroke: rgba(C.pr, 0.25), 'stroke-width': 0.5, 'vector-effect': 'non-scaling-stroke' }))
      ringsG.appendChild(svgEl('line', { x1: -tw, y1: r, x2: tw, y2: r,
        stroke: rgba(C.pr, 0.7), 'stroke-width': 1, 'vector-effect': 'non-scaling-stroke' }))
      var lbl = svgEl('text', { x: 8 * MAP_LABEL_SCALE / SCALE, y: -r, transform: 'scale(1,-1)',
        fill: C.pc, 'font-size': fs, 'font-family': FONT_SANS })
      lbl.textContent = fmtDist(r)
      ringsG.appendChild(lbl)
    }

    while (compassG.firstChild) compassG.removeChild(compassG.firstChild)
    var compassR = Math.min(camCX * 0.88, camCY * 0.92) / SCALE
    var fsC = 11 * MAP_LABEL_SCALE / SCALE
    compassG.appendChild(svgEl('line', { x1: 0, y1: 0, x2: 0, y2: compassR + 20 / SCALE,
      stroke: rgba(C.pr, 0.2), 'stroke-width': 0.5, 'stroke-dasharray': (4 / SCALE) + ' ' + (4 / SCALE),
      'vector-effect': 'non-scaling-stroke' }))
    for (var deg = 0; deg < 360; deg += 10) {
      var maj = deg % 30 === 0
      var rad = deg * Math.PI / 180
      var wx0 = Math.sin(rad) * compassR
      var wy0 = Math.cos(rad) * compassR
      var tlen = (maj ? 8 : 4) / SCALE
      compassG.appendChild(svgEl('line', {
        x1: wx0, y1: wy0, x2: Math.sin(rad) * (compassR + tlen), y2: Math.cos(rad) * (compassR + tlen),
        stroke: rgba(C.pr, maj ? 0.65 : 0.35),
        'stroke-width': maj ? 1 : 0.5,
        'vector-effect': 'non-scaling-stroke',
      }))
      if (maj) {
        var lr = compassR + (8 + 10) * MAP_LABEL_SCALE / SCALE
        var t = svgEl('text', { x: Math.sin(rad) * lr, y: -Math.cos(rad) * lr, transform: 'scale(1,-1)',
          fill: C.lo, 'font-size': fsC, 'font-family': FONT_SANS, 'text-anchor': 'middle', 'dominant-baseline': 'middle' })
        t.textContent = deg + '\u00b0'
        compassG.appendChild(t)
      }
    }
  }

  function updateWorldTransform() {
    if (worldG) worldG.setAttribute('transform',
      'translate(' + camCX + ',' + camCY + ') scale(' + SCALE + ',' + (-SCALE) + ')')
  }

  function refreshSvgHitBox() {
    if (!svg || W <= 0 || H <= 0) return
    var r = svg.getBoundingClientRect()
    if (r.width < 1 || r.height < 1) return
    hitL = r.left
    hitT = r.top
    hitSx = W / r.width
    hitSy = H / r.height
  }

  function rebuildWorldSvg() {
    buildWorldElements()
    buildZones()
    if (coneEl && SCALE > 0) {
      updateScaleOnlySvgGeom()
      lastDrawScale = SCALE
    }
    refreshSvgHitBox()
  }

  function viewportMaxCornerPx() {
    if (W <= 0 || H <= 0) return 1
    return Math.max(
      Math.hypot(camCX, camCY),
      Math.hypot(W - camCX, camCY),
      Math.hypot(camCX, H - camCY),
      Math.hypot(W - camCX, H - camCY)
    )
  }

  function resize() {
    if (!svg || !wrap) return
    W = wrap.clientWidth
    H = wrap.clientHeight
    svg.setAttribute('width', W)
    svg.setAttribute('height', H)
    camCX = W / 2
    camCY = H * 0.9
    SCALE = viewportMaxCornerPx() / BASE_VIEW_RADIUS_KM * zoomLevel
    updateWorldTransform()
    if (bgSky) { bgSky.setAttribute('width', W); bgSky.setAttribute('height', camCY) }
    if (bgSea) { bgSea.setAttribute('y', camCY); bgSea.setAttribute('width', W); bgSea.setAttribute('height', H - camCY) }
    if (horizLine) { horizLine.setAttribute('x2', W); horizLine.setAttribute('y1', camCY); horizLine.setAttribute('y2', camCY) }
    rebuildWorldSvg()
  }

  function updateZoomLabel() {
    var el = $('zoom-label')
    if (el) el.textContent = Math.round(zoomLevel * 100) + '%'
  }

  function flushZoomVisuals() {
    zoomVisualRaf = 0
    if (!svg || SCALE <= 0) return
    updateWorldTransform()
    rebuildWorldSvg()
  }

  function scheduleZoomVisuals() {
    if (!zoomVisualRaf) zoomVisualRaf = requestAnimationFrame(flushZoomVisuals)
  }

  function applyZoom(delta) {
    var factor = delta > 0 ? 1.12 : 1 / 1.12
    zoomLevel = Math.max(0.3, Math.min(8, zoomLevel * factor))
    SCALE = viewportMaxCornerPx() / BASE_VIEW_RADIUS_KM * zoomLevel
    scheduleZoomVisuals()
    updateZoomLabel()
  }

  function isTwoCam() {
    var el = document.querySelector('input[name="camera-count"]:checked')
    return !!(el && el.value === '2')
  }

  function isOscillatePan() {
    var el = document.querySelector('input[name="pan-mode"]:checked')
    return !!(el && el.value === 'oscillate')
  }

  function normHeading180(deg) {
    var h = ((deg % 360) + 360) % 360
    if (h > 180) h -= 360
    return h
  }

  /** In Front arc pan mode with two cameras: headings where both boresights lie in the front sector. */
  function oscillationHeadingBounds(p) {
    var fh = p.frontArc / 2
    if (!p.panOscillate || !p.twoCam) return { lo: -fh, hi: fh }
    var off = p.cam2Offset
    var n = Math.max(120, Math.ceil(4 * fh))
    var runs = []
    var s = -1
    for (var i = 0; i <= n; i++) {
      var t = -fh + (2 * fh) * (i / n)
      var ok = Math.abs(normHeading180(t)) <= fh + 1e-9 && Math.abs(normHeading180(t + off)) <= fh + 1e-9
      if (ok && s < 0) s = i
      if (!ok && s >= 0) {
        runs.push({
          lo: -fh + (2 * fh) * (s / n),
          hi: -fh + (2 * fh) * ((i - 1) / n),
        })
        s = -1
      }
    }
    if (s >= 0) runs.push({ lo: -fh + (2 * fh) * (s / n), hi: fh })
    if (!runs.length) return { lo: -fh, hi: fh }
    var h = normHeading180(camHeading)
    var pick = null
    for (var r = 0; r < runs.length; r++) {
      if (h >= runs[r].lo - 1e-6 && h <= runs[r].hi + 1e-6) { pick = runs[r]; break }
    }
    if (!pick) {
      pick = runs[0]
      for (var r2 = 1; r2 < runs.length; r2++) {
        if (runs[r2].hi - runs[r2].lo > pick.hi - pick.lo) pick = runs[r2]
      }
    }
    return { lo: pick.lo, hi: pick.hi }
  }

  function clampHeadingToFrontArcIfOscillating() {
    if (!isOscillatePan() || !inpFrontArc) return
    var p = getParams()
    var b = oscillationHeadingBounds(p)
    if (camHeading > b.hi) camHeading = b.hi
    if (camHeading < b.lo) camHeading = b.lo
  }

  function syncPanModeUi() {
    var labels = document.querySelectorAll('.pan-mode-btn')
    for (var i = 0; i < labels.length; i++) {
      var inp = labels[i].querySelector('input[name="pan-mode"]')
      labels[i].classList.toggle('cam-layout-btn--active', !!(inp && inp.checked))
    }
    var backWrap = $('ctrl-back-speed')
    var backInp = $('input-back-speed')
    var osc = isOscillatePan()
    if (backWrap) backWrap.classList.toggle('ctrl--muted', osc)
    if (backInp) {
      backInp.disabled = osc
      backInp.setAttribute('aria-disabled', osc ? 'true' : 'false')
    }
    buildZones()
  }

  function syncCameraCountUi() {
    var labels = document.querySelectorAll('.cam-count-btn')
    for (var i = 0; i < labels.length; i++) {
      var inp = labels[i].querySelector('input[name="camera-count"]')
      labels[i].classList.toggle('cam-layout-btn--active', !!(inp && inp.checked))
    }
    var two = isTwoCam()
    var row2 = $('camera-panel-cam2-row')
    if (row2) row2.classList.toggle('camera-panel__row--muted', !two)
    if (inpFov2) {
      inpFov2.disabled = !two
      inpFov2.setAttribute('aria-disabled', two ? 'false' : 'true')
    }
    if (inpCam2Offset) {
      inpCam2Offset.disabled = !two
      inpCam2Offset.setAttribute('aria-disabled', two ? 'false' : 'true')
    }
  }

  function getParams() {
    return {
      fov: +inpFov.value,
      fov2: inpFov2 ? +inpFov2.value : 18,
      cam2Offset: inpCam2Offset ? +inpCam2Offset.value : 180,
      twoCam: isTwoCam(),
      frontSpeed: +inpFrontSpeed.value,
      backSpeed: +inpBackSpeed.value,
      frontArc: +inpFrontArc.value,
      boatSpeed: +inpBoatSpeed.value,
      panOscillate: isOscillatePan(),
    }
  }

  function worldToCanvas(wx, wy) {
    return { x: camCX + wx * SCALE, y: camCY - wy * SCALE }
  }

  function canvasToWorld(cx, cy) {
    return { x: (cx - camCX) / SCALE, y: (camCY - cy) / SCALE }
  }

  function isFront(heading, arc) {
    return Math.abs(normHeading180(heading)) <= arc / 2
  }

  function setDir(d) {
    camDir = d
    var cw = $('dir-cw')
    var ccw = $('dir-ccw')
    if (cw) cw.classList.toggle('active', d === 1)
    if (ccw) ccw.classList.toggle('active', d === -1)
  }

  function isBoatVisible(bx, by, heading, p) {
    if (by <= -0.05) return false
    var boatB = (Math.atan2(bx, by) * 180) / Math.PI
    function inCone(hDeg, halfFovDeg) {
      /* Cone uses rotate(hDeg) inside worldG scale(S,-S); match camera visibility. */
      var rel = (((boatB + hDeg + 540) % 360) - 180)
      return Math.abs(rel) <= halfFovDeg
    }
    if (inCone(heading, p.fov / 2)) return true
    if (p.twoCam && inCone(heading + p.cam2Offset, p.fov2 / 2)) return true
    return false
  }

  function draw(p, bx, by, inFov) {
    if (!coneEl || SCALE === 0) return
    if (SCALE !== lastDrawScale) {
      lastDrawScale = SCALE
      updateScaleOnlySvgGeom()
    }
    updateTrackSvgGeomIfNeeded()
    syncConeAndPointerShape(p)
    dynamicCamG.setAttribute('transform', 'rotate(' + camHeading + ')')
    if (rearCamG && coneRearEl && camPointerRear) {
      if (!p.twoCam) rearCamG.setAttribute('display', 'none')
      else {
        rearCamG.removeAttribute('display')
        rearCamG.setAttribute('transform', 'rotate(' + (camHeading + p.cam2Offset) + ')')
        coneRearEl.setAttribute('fill', rgba(C.wr, 0.1))
        coneRearEl.setAttribute('stroke', rgba(C.wr, 0.55))
        camPointerRear.setAttribute('stroke', rgba(C.wr, 0.85))
      }
    }

    var segX = boatEnd.x - boatStart.x
    var segY = boatEnd.y - boatStart.y
    var udx = segX * boatDir
    var udy = segY * boatDir
    var pl = Math.hypot(segX, segY)
    /* Bow is drawn along +icon Y (world north). worldG uses scale(S,-S), so screen dir ∝ (udx,-udy). */
    var iconAngle = 0
    if (pl > 1e-5) {
      iconAngle = (Math.atan2(udy, udx) * 180) / Math.PI - 90
      lastTrailIconAngle = iconAngle
    } else if (!isNaN(lastTrailIconAngle)) iconAngle = lastTrailIconAngle
    boatIconG.setAttribute('transform', 'rotate(' + iconAngle + ')')

    if (bx !== lastDrawBx || by !== lastDrawBy) {
      lastDrawBx = bx
      lastDrawBy = by
      bearingLine.setAttribute('x2', bx)
      bearingLine.setAttribute('y2', by)
      boatG.setAttribute('transform', 'translate(' + bx + ',' + by + ')')
    }
    if (prevInFov !== inFov) {
      prevInFov = inFov
      boatHull.setAttribute('fill', inFov ? C.s : C.d)
      boatHull.setAttribute('stroke', inFov ? rgba(C.sr, 0.9) : rgba(C.dr, 0.85))
    }
    if (inFov) {
      boatHalo.setAttribute('display', '')
      boatHalo.setAttribute('fill', rgba(C.sr, 0.14))
    } else boatHalo.setAttribute('display', 'none')
  }

  function schedulePanelStats(p, bx, by, inFov) {
    panelStatsPayload = { p: p, bx: bx, by: by, inFov: inFov }
    if (!panelStatsRaf) panelStatsRaf = requestAnimationFrame(function () {
      panelStatsRaf = 0
      if (!panelStatsPayload) return
      var q = panelStatsPayload
      panelStatsPayload = null
      updateStats(q.p, q.bx, q.by, q.inFov)
    })
  }

  function updateStats(p, bx, by, inFov) {
    var c = statCache
    var dist = Math.hypot(bx, by)
    var st = p.panOscillate
      ? (2 * p.frontArc / p.frontSpeed)
      : (p.frontArc / p.frontSpeed + (360 - p.frontArc) / p.backSpeed)

    function u(el, k, s) {
      if (el && c[k] !== s) { el.textContent = s; c[k] = s }
    }

    u(c.elScan, 'lastScan', st.toFixed(1) + 's')
    u(c.elDist, 'lastDist', (dist * 1000).toFixed(0) + 'm')

    var travelM = (inFov ? detectedStreak : lastDetectedStreak).toFixed(1) + 'm'
    var blindM = (!inFov ? blindStreak : lastBlindStreak).toFixed(1) + 'm'
    if (c.elTravel) {
      u(c.elTravel, 'lastTravel', travelM)
      var to = inFov ? '1' : '0.5'
      if (c.lastTravelOp !== to) { c.elTravel.style.opacity = to; c.lastTravelOp = to }
    }
    if (c.elBlind) {
      u(c.elBlind, 'lastBlind', blindM)
      var bo = !inFov ? '1' : '0.5'
      if (c.lastBlindOp !== bo) { c.elBlind.style.opacity = bo; c.lastBlindOp = bo }
    }

    u(c.elTravelPrev, 'lastTravelPrev', prevDetectedStreak > 0 ? 'prev: ' + prevDetectedStreak.toFixed(1) + 'm' : 'prev: —')
    u(c.elBlindPrev, 'lastBlindPrev', prevBlindStreak > 0 ? 'prev: ' + prevBlindStreak.toFixed(1) + 'm' : 'prev: —')

    var prevTotalM = prevDetectedStreak + prevBlindStreak
    if (c.elRisk && c.elRiskBar) {
      if (prevTotalM >= MIN_BLIND_SHARE_M) {
        var share = (prevBlindStreak / prevTotalM) * 100
        var shareT = share.toFixed(0) + '%'
        var col = share > 66 ? 'var(--danger)' : share > 33 ? 'var(--warning)' : 'var(--success)'
        var w = share + '%'
        u(c.elRisk, 'lastRiskT', shareT)
        if (c.lastRiskCol !== col) { c.elRisk.style.color = col; c.lastRiskCol = col }
        if (c.lastRiskW !== w) { c.elRiskBar.style.width = w; c.lastRiskW = w }
        if (c.lastRiskBg !== col) { c.elRiskBar.style.background = col; c.lastRiskBg = col }
      } else {
        u(c.elRisk, 'lastRiskT', '—')
        if (c.lastRiskW !== '0%') { c.elRiskBar.style.width = '0%'; c.lastRiskW = '0%' }
      }
    }
    var vis = inFov ? 'YES' : 'NO'
    var visCls = 'val ' + (inFov ? 'active' : 'inactive')
    if (c.elVis) {
      u(c.elVis, 'lastVis', vis)
      if (c.lastVisCls !== visCls) { c.elVis.className = visCls; c.lastVisCls = visCls }
    }
  }

  function animate(ts) {
    if (!running || !svg) return
    if (lastTime === null) lastTime = ts
    var dt = Math.min((ts - lastTime) / 1000, 0.1)
    lastTime = ts
    var p = getParams()
    var boatKmS = p.boatSpeed * 0.000514
    var pathLen = Math.hypot(boatEnd.x - boatStart.x, boatEnd.y - boatStart.y)
    if (pathLen > 0.001) {
      boatT += boatDir * (boatKmS * dt) / pathLen
      if (boatT >= 1) { boatT = 1; boatDir = -1 }
      if (boatT <= 0) { boatT = 0; boatDir = 1 }
    }
    if (p.panOscillate) {
      var ob = oscillationHeadingBounds(p)
      camHeading -= camDir * p.frontSpeed * dt
      if (camHeading > ob.hi) {
        camHeading = ob.hi
        camDir = 1
      } else if (camHeading < ob.lo) {
        camHeading = ob.lo
        camDir = -1
      }
    } else {
      var speed = isFront(camHeading, p.frontArc) ? p.frontSpeed : p.backSpeed
      camHeading -= camDir * speed * dt
      if (camHeading >= 180) camHeading -= 360
      if (camHeading < -180) camHeading += 360
    }
    var bx = boatStart.x + (boatEnd.x - boatStart.x) * boatT
    var by = boatStart.y + (boatEnd.y - boatStart.y) * boatT
    var visible = isBoatVisible(bx, by, camHeading, p)
    var distThisFrame = p.boatSpeed * 0.514 * dt
    if (coneEl && SCALE > 0 && pathLen > 0.001 && !visible) appendTrail(bx, by)

    if (prevVisible !== null && visible !== prevVisible) {
      if (visible) {
        clearTrail(false)
        prevBlindStreak = blindStreak
        lastBlindStreak = blindStreak
        blindStreak = 0
      } else {
        prevDetectedStreak = detectedStreak
        lastDetectedStreak = detectedStreak
        detectedStreak = 0
      }
    }
    if (visible) detectedStreak += distThisFrame
    else blindStreak += distThisFrame
    prevVisible = visible

    if (!coneEl || SCALE === 0) updateStats(p, bx, by, visible)
    else {
      draw(p, bx, by, visible)
      schedulePanelStats(p, bx, by, visible)
    }
    if (running) requestAnimationFrame(animate)
  }

  function getCanvasXY(e) {
    var src = 'touches' in e && e.touches.length ? e.touches[0] : e
    return { x: (src.clientX - hitL) * hitSx, y: (src.clientY - hitT) * hitSy }
  }

  function onResize() {
    if (!resizeRaf) resizeRaf = requestAnimationFrame(function () { resizeRaf = 0; resize() })
  }

  function tryDragStart(e, thresh) {
    var pt = getCanvasXY(e)
    var s = worldToCanvas(boatStart.x, boatStart.y)
    var end = worldToCanvas(boatEnd.x, boatEnd.y)
    if (Math.hypot(pt.x - s.x, pt.y - s.y) < thresh) dragging = 'start'
    else if (Math.hypot(pt.x - end.x, pt.y - end.y) < thresh) dragging = 'end'
  }

  function dragToWorld(e) {
    var pt = getCanvasXY(e)
    var w = canvasToWorld(pt.x, pt.y)
    w.y = Math.max(0.05, Math.min(1.3, w.y))
    w.x = Math.max(-1.4, Math.min(1.4, w.x))
    if (dragging === 'start') boatStart = w
    else if (dragging === 'end') boatEnd = w
  }

  function onMouseDown(e) {
    lastPointerEv = e
    tryDragStart(e, 26)
    updateSvgCursor(e)
  }

  var CURSOR_NEAR = 30
  var lastPointerEv = null

  function updateSvgCursor(e) {
    if (!svg || !SCALE) return
    if (dragging) {
      svg.style.cursor = 'grabbing'
      return
    }
    var pt = getCanvasXY(e)
    var s = worldToCanvas(boatStart.x, boatStart.y)
    var end = worldToCanvas(boatEnd.x, boatEnd.y)
    if (Math.hypot(pt.x - s.x, pt.y - s.y) < CURSOR_NEAR ||
        Math.hypot(pt.x - end.x, pt.y - end.y) < CURSOR_NEAR)
      svg.style.cursor = 'grab'
    else svg.style.cursor = ''
  }

  function onMouseMove(e) {
    lastPointerEv = e
    if (dragging) dragToWorld(e)
    updateSvgCursor(e)
  }

  function onMouseUp() {
    dragging = null
    if (svg) {
      if (lastPointerEv) updateSvgCursor(lastPointerEv)
      else svg.style.cursor = ''
    }
  }

  function onTouchStart(e) {
    if (e.touches.length === 2) {
      lastPinchDist = Math.hypot(
        e.touches[0].clientX - e.touches[1].clientX,
        e.touches[0].clientY - e.touches[1].clientY)
      dragging = null
      return
    }
    if (e.touches.length !== 1) return
    e.preventDefault()
    tryDragStart(e, 34)
  }

  function onTouchMove(e) {
    if (e.touches.length === 2 && lastPinchDist !== null) {
      e.preventDefault()
      var dist = Math.hypot(
        e.touches[0].clientX - e.touches[1].clientX,
        e.touches[0].clientY - e.touches[1].clientY)
      applyZoom(dist - lastPinchDist)
      lastPinchDist = dist
      return
    }
    if (!dragging) return
    e.preventDefault()
    dragToWorld(e)
  }

  function onTouchEnd(e) {
    dragging = null
    if (e.touches.length < 2) lastPinchDist = null
  }

  function onWheel(e) {
    e.preventDefault()
    applyZoom(-e.deltaY)
  }

  function bindRange(id, valSpanId, onInput) {
    var input = $(id)
    var span = valSpanId ? $(valSpanId) : null
    function sync() { if (span) span.textContent = input.value }
    input.addEventListener('input', function () {
      sync()
      resetStreaks()
      if (onInput) onInput()
    })
    sync()
  }

  /**
   * Presets: twoCam, panMode full360|oscillate, fov / fov2 / cam2Offset, front arc, speeds.
   * Front arc and speeds are degrees; FOVs are degrees (slider scale).
   */
  var CAMERA_PRESETS = {
    vos1: {
      twoCam: false,
      fov: 18, fov2: 18, cam2Offset: 180,
      frontArc: 180, panMode: 'full360',
      backSpeed: 60, frontSpeed: 6,
    },
    prop1: {
      twoCam: false,
      fov: 18, fov2: 18, cam2Offset: 180,
      frontArc: 160, panMode: 'full360',
      backSpeed: 120, frontSpeed: 7,
    },
    prop2: {
      twoCam: true,
      fov: 18, fov2: 50, cam2Offset: 0,
      frontArc: 150, panMode: 'full360',
      backSpeed: 120, frontSpeed: 8,
    },
    prop3: {
      twoCam: true,
      fov: 18, fov2: 18, cam2Offset: 90,
      frontArc: 180, panMode: 'oscillate',
      backSpeed: 120, frontSpeed: 7,
    },
  }

  function setRadioChecked(name, value) {
    var el = document.querySelector('input[name="' + name + '"][value="' + value + '"]')
    if (el) el.checked = true
  }

  function clearPresetDropdown() {
    var sel = $('camera-preset')
    if (sel) sel.value = ''
  }

  function applyCameraPreset(key) {
    var p = CAMERA_PRESETS[key]
    if (!p || !inpFov) return

    inpFov.value = String(p.fov)
    if (inpFov2) inpFov2.value = String(p.fov2)
    if (inpCam2Offset) inpCam2Offset.value = String(p.cam2Offset)
    inpFrontSpeed.value = String(p.frontSpeed)
    inpBackSpeed.value = String(p.backSpeed)
    inpFrontArc.value = String(p.frontArc)

    setRadioChecked('camera-count', p.twoCam ? '2' : '1')
    setRadioChecked('pan-mode', p.panMode === 'oscillate' ? 'oscillate' : 'full360')

    syncCameraCountUi()
    syncPanModeUi()

    $('val-fov').textContent = inpFov.value
    var vf2 = $('val-fov-2')
    if (vf2 && inpFov2) vf2.textContent = inpFov2.value
    var vo = $('val-cam2-offset')
    if (vo && inpCam2Offset) vo.textContent = inpCam2Offset.value
    $('val-front-speed').textContent = inpFrontSpeed.value
    $('val-back-speed').textContent = inpBackSpeed.value
    $('val-front-arc').textContent = inpFrontArc.value

    cachedConeGeomKey = ''
    clampHeadingToFrontArcIfOscillating()
    resetStreaks()
    buildZones()
    var sel = $('camera-preset')
    if (sel) sel.value = key
  }

  function init() {
    svg = $('c')
    wrap = $('canvas-wrap')
    if (!svg || !wrap) return

    bgSky = svgEl('rect', { x: 0, y: 0, fill: 'var(--surface-1)' })
    bgSea = svgEl('rect', { x: 0, y: 0, fill: 'var(--surface-2)' })
    horizLine = svgEl('line', { x1: 0, 'stroke-dasharray': '6 4' })
    ringsG = svgEl('g', { id: 'rings' })
    compassG = svgEl('g', { id: 'compass' })
    zonesG = svgEl('g', { id: 'zones' })
    worldG = svgEl('g', { id: 'world' })
    worldG.appendChild(compassG)
    worldG.appendChild(zonesG)
    worldG.appendChild(ringsG)

    rearCamG = svgEl('g', { id: 'dynamic-cam-rear', display: 'none' })
    coneRearEl = svgEl('path', { 'stroke-linejoin': 'round', 'stroke-width': 1, 'vector-effect': 'non-scaling-stroke' })
    camPointerRear = svgEl('line', { x1: 0, y1: 0, x2: 0, y2: 0.1, 'stroke-width': 1.5, 'vector-effect': 'non-scaling-stroke' })
    rearCamG.appendChild(coneRearEl)
    rearCamG.appendChild(camPointerRear)

    dynamicCamG = svgEl('g', { id: 'dynamic-cam' })
    coneEl = svgEl('path', { 'stroke-linejoin': 'round', 'stroke-width': 1, 'vector-effect': 'non-scaling-stroke' })
    camPointer = svgEl('line', { x1: 0, y1: 0, x2: 0, y2: 0.1, 'stroke-width': 1.5, 'vector-effect': 'non-scaling-stroke' })
    dynamicCamG.appendChild(coneEl)
    dynamicCamG.appendChild(camPointer)
    trajLine = svgEl('line', { 'stroke-width': 1, 'stroke-dasharray': '4 3', 'vector-effect': 'non-scaling-stroke' })
    boatTrail = svgEl('polyline', {
      fill: 'none', 'stroke-width': 2, 'stroke-linecap': 'round', 'stroke-linejoin': 'round',
      'vector-effect': 'non-scaling-stroke',
    })
    bearingLine = svgEl('line', { x1: 0, y1: 0, 'stroke-width': 0.5, 'vector-effect': 'non-scaling-stroke' })
    boatG = svgEl('g', { id: 'boat-layer' })
    boatHalo = svgEl('circle', { cx: 0, cy: 0, stroke: 'none' })
    boatIconG = svgEl('g')
    boatIconScaleG = svgEl('g')
    boatHull = svgEl('path', {
      d: 'M 0 1.05 L 0.38 0.22 L 0.26 -0.72 L -0.26 -0.72 L -0.38 0.22 Z',
      'stroke-width': 1.2, 'stroke-linejoin': 'round', 'vector-effect': 'non-scaling-stroke',
    })
    boatIconScaleG.appendChild(boatHull)
    boatIconG.appendChild(boatIconScaleG)
    boatG.appendChild(boatHalo)
    boatG.appendChild(boatIconG)
    anchorSOuter = svgEl('circle', {
      class: 'drag-anchor-ring drag-anchor-ring--start',
      fill: 'none', 'stroke-width': 2.5, 'vector-effect': 'non-scaling-stroke',
    })
    anchorS = svgEl('circle', { class: 'drag-anchor-core drag-anchor-core--start', 'stroke-width': 1.5, 'vector-effect': 'non-scaling-stroke' })
    anchorEOuter = svgEl('circle', {
      class: 'drag-anchor-ring drag-anchor-ring--end',
      fill: 'none', 'stroke-width': 2.5, 'vector-effect': 'non-scaling-stroke',
    })
    anchorE = svgEl('circle', { class: 'drag-anchor-core drag-anchor-core--end', 'stroke-width': 1.5, 'vector-effect': 'non-scaling-stroke' })
    anchorSLabel = svgEl('text', {
      class: 'drag-anchor-label',
      'text-anchor': 'middle', 'dominant-baseline': 'middle', transform: 'scale(1,-1)', 'font-family': FONT_SANS,
    })
    anchorSLabel.textContent = 'S'
    anchorELabel = svgEl('text', {
      class: 'drag-anchor-label drag-anchor-label--end',
      'text-anchor': 'middle', 'dominant-baseline': 'middle', transform: 'scale(1,-1)', 'font-family': FONT_SANS,
    })
    anchorELabel.textContent = 'E'
    camDot = svgEl('circle', { cx: 0, cy: 0, 'stroke-width': 1.5, 'vector-effect': 'non-scaling-stroke' })
    for (var ci = 0; ci < 4; ci++) camCorners.push(svgEl('line', { 'stroke-width': 1, 'vector-effect': 'non-scaling-stroke' }))

    worldG.appendChild(rearCamG)
    worldG.appendChild(dynamicCamG)
    worldG.appendChild(trajLine)
    worldG.appendChild(boatTrail)
    worldG.appendChild(bearingLine)
    worldG.appendChild(boatG)
    worldG.appendChild(anchorSOuter)
    worldG.appendChild(anchorS)
    worldG.appendChild(anchorEOuter)
    worldG.appendChild(anchorE)
    worldG.appendChild(anchorSLabel)
    worldG.appendChild(anchorELabel)
    worldG.appendChild(camDot)
    for (var cj = 0; cj < 4; cj++) worldG.appendChild(camCorners[cj])

    svg.appendChild(bgSky)
    svg.appendChild(bgSea)
    svg.appendChild(horizLine)
    svg.appendChild(worldG)

    inpFov = $('input-fov')
    inpFrontSpeed = $('input-front-speed')
    inpBackSpeed = $('input-back-speed')
    inpFrontArc = $('input-front-arc')
    inpBoatSpeed = $('input-boat-speed')
    inpFov2 = $('input-fov-2')
    inpCam2Offset = $('input-cam2-offset')
    cachedConeGeomKey = ''
    lastDrawBx = lastDrawBy = NaN

    initTheme()
    running = true
    resize()
    updateZoomLabel()
    setDir(-1)
    window.addEventListener('resize', onResize)

    svg.addEventListener('mousedown', onMouseDown)
    svg.addEventListener('mousemove', onMouseMove)
    svg.addEventListener('mouseup', onMouseUp)
    svg.addEventListener('mouseleave', function () {
      if (!dragging) svg.style.cursor = ''
    })
    svg.addEventListener('touchstart', onTouchStart, { passive: false })
    svg.addEventListener('touchmove', onTouchMove, { passive: false })
    svg.addEventListener('touchend', onTouchEnd)
    svg.addEventListener('touchcancel', onTouchEnd)
    svg.addEventListener('wheel', onWheel, { passive: false })

    $('zoom-out').addEventListener('click', function () { applyZoom(-1) })
    $('zoom-in').addEventListener('click', function () { applyZoom(1) })
    $('dir-cw').addEventListener('click', function () { setDir(1) })
    $('dir-ccw').addEventListener('click', function () { setDir(-1) })
    bindRange('input-fov', 'val-fov', function () {
      cachedConeGeomKey = ''
      clearPresetDropdown()
    })
    bindRange('input-front-speed', 'val-front-speed', clearPresetDropdown)
    bindRange('input-back-speed', 'val-back-speed', clearPresetDropdown)
    bindRange('input-front-arc', 'val-front-arc', function () {
      clearPresetDropdown()
      buildZones()
      clampHeadingToFrontArcIfOscillating()
    })
    bindRange('input-boat-speed', 'val-boat-speed')
    bindRange('input-fov-2', 'val-fov-2', function () {
      cachedConeGeomKey = ''
      clearPresetDropdown()
    })
    bindRange('input-cam2-offset', 'val-cam2-offset', function () {
      cachedConeGeomKey = ''
      clearPresetDropdown()
      clampHeadingToFrontArcIfOscillating()
    })

    var countRadios = document.querySelectorAll('input[name="camera-count"]')
    syncCameraCountUi()
    for (var lr = 0; lr < countRadios.length; lr++) {
      countRadios[lr].addEventListener('change', function () {
        syncCameraCountUi()
        clampHeadingToFrontArcIfOscillating()
        resetStreaks()
        cachedConeGeomKey = ''
      })
    }

    var panRadios = document.querySelectorAll('input[name="pan-mode"]')
    syncPanModeUi()
    for (var pr = 0; pr < panRadios.length; pr++) {
      panRadios[pr].addEventListener('change', function () {
        syncPanModeUi()
        clampHeadingToFrontArcIfOscillating()
        resetStreaks()
        cachedConeGeomKey = ''
      })
    }

    var presetSelect = $('camera-preset')
    if (presetSelect) {
      presetSelect.addEventListener('change', function () {
        var k = presetSelect.value
        if (k) applyCameraPreset(k)
      })
    }

    statCache.elScan = $('st-scan')
    statCache.elDist = $('st-dist')
    statCache.elTravel = $('st-travel')
    statCache.elBlind = $('st-blind')
    statCache.elTravelPrev = $('st-travel-prev')
    statCache.elBlindPrev = $('st-blind-prev')
    statCache.elRisk = $('st-risk')
    statCache.elRiskBar = $('st-risk-bar')
    statCache.elVis = $('st-vis')

    requestAnimationFrame(animate)
  }

  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init)
  else init()
})()