File size: 45,955 Bytes
f8506a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Why does this orbit do that? — Gravity sandbox</title>
<style>
  :root {
    --bg: #07070f;
    --panel: #111120;
    --border: #27273a;
    --text: #e8e8f2;
    --dim: #8a8aa4;
    --accent: #6cf;
    --good: #4caf50;
    --bad: #ff5566;
    --warn: #ffb454;
    --star: #ffd257;
    --planet: #5ea8ff;
    --hole: #b47aff;
  }
  * { box-sizing: border-box; }
  body {
    margin: 0; background: var(--bg); color: var(--text);
    font-family: ui-sans-serif, system-ui, -apple-system, sans-serif;
    font-size: 14px; line-height: 1.55;
  }
  header { padding: 14px 22px; border-bottom: 1px solid var(--border); }
  header h1 { margin: 0 0 3px; font-size: 17px; font-weight: 600; }
  header p { margin: 0; color: var(--dim); font-size: 12.5px; max-width: 960px; }
  main {
    display: grid;
    grid-template-columns: minmax(0, 1.15fr) minmax(0, 1fr);
    gap: 14px; padding: 14px; max-width: 1480px; margin: 0 auto;
  }
  @media (max-width: 1000px) { main { grid-template-columns: 1fr; } }
  .panel {
    background: var(--panel); border: 1px solid var(--border);
    border-radius: 8px; overflow: hidden;
  }
  .panel-header {
    padding: 8px 12px; border-bottom: 1px solid var(--border);
    display: flex; align-items: center; justify-content: space-between;
    gap: 8px; flex-wrap: wrap;
  }
  .panel-header h2 {
    margin: 0; font-size: 11px; font-weight: 600;
    text-transform: uppercase; letter-spacing: 0.07em; color: var(--dim);
  }
  .toolrow { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; }
  button, select {
    background: #0d0d19; color: var(--text); border: 1px solid var(--border);
    border-radius: 4px; padding: 4px 9px; font-size: 11.5px; cursor: pointer;
    font-family: inherit;
  }
  button:hover { border-color: var(--accent); color: var(--accent); }
  button.on { border-color: var(--accent); color: var(--accent); background: rgba(102,204,255,0.10); }
  button:disabled { opacity: 0.4; cursor: default; }
  button:disabled:hover { border-color: var(--border); color: var(--text); }
  select:focus { outline: 1px solid var(--accent); }
  .canvas-wrap { position: relative; background: #04040a; line-height: 0; }
  canvas { display: block; width: 100%; height: auto; touch-action: none; }
  #stage { cursor: crosshair; }
  .badge {
    position: absolute; font-family: ui-monospace, monospace; font-size: 10.5px;
    color: var(--dim); background: rgba(0,0,0,0.55); padding: 3px 7px;
    border-radius: 4px; pointer-events: none;
  }
  #coordBadge { bottom: 8px; left: 8px; }
  #modeBadge { top: 8px; left: 8px; }
  #modeBadge.armed { color: var(--accent); border: 1px solid rgba(102,204,255,0.4); }

  .strip {
    display: grid; grid-template-columns: repeat(4, minmax(0,1fr));
    gap: 1px; background: var(--border); border-top: 1px solid var(--border);
  }
  .stat { background: var(--panel); padding: 7px 10px; }
  .stat .k { font-size: 9.5px; color: var(--dim); text-transform: uppercase; letter-spacing: 0.05em; }
  .stat .v { font-family: ui-monospace, monospace; font-size: 13px; color: var(--text); margin-top: 1px; }
  @media (max-width: 620px) { .strip { grid-template-columns: repeat(2, minmax(0,1fr)); } }

  #explanation { padding: 12px 15px; font-size: 12.5px; max-height: 560px; overflow-y: auto; }
  #explanation h3 { margin: 0 0 8px; font-size: 12.5px; color: var(--accent); font-weight: 600; }
  #explanation h4 { margin: 14px 0 4px; font-size: 11px; color: var(--dim); text-transform: uppercase; letter-spacing: 0.06em; }
  #explanation p { margin: 7px 0; }
  .verdict { padding: 7px 11px; border-radius: 4px; margin: 9px 0; font-weight: 600; font-size: 12.5px; }
  .verdict.bad { background: rgba(255,85,102,0.12); color: #ff8a99; border-left: 3px solid #ff5566; }
  .verdict.good { background: rgba(76,175,80,0.12); color: #8fdc92; border-left: 3px solid #4caf50; }
  .verdict.warn { background: rgba(255,180,84,0.12); color: #ffcf8a; border-left: 3px solid #ffb454; }
  .verdict.info { background: rgba(180,122,255,0.12); color: #d3b3ff; border-left: 3px solid #b47aff; }
  #explanation table { width: 100%; border-collapse: collapse; font-family: ui-monospace, monospace; font-size: 11px; margin: 7px 0; }
  #explanation th, #explanation td { text-align: left; padding: 3px 6px; border-bottom: 1px solid var(--border); }
  #explanation th { color: var(--dim); font-weight: 500; }
  .eq { font-family: ui-monospace, monospace; font-size: 12px; background: #0d0d19; border: 1px solid var(--border); border-radius: 4px; padding: 7px 10px; margin: 7px 0; line-height: 1.85; overflow-x: auto; }
  .note { color: var(--dim); font-size: 11.5px; border-top: 1px solid var(--border); padding-top: 9px; margin-top: 13px; line-height: 1.6; }
  .hint { padding: 8px 12px; font-size: 11px; color: var(--dim); border-top: 1px solid var(--border); background: rgba(255,255,255,0.02); line-height: 1.5; }
  .hint b { color: var(--text); }
  .legend { display: flex; gap: 11px; flex-wrap: wrap; font-size: 10.5px; color: var(--dim); align-items: center; }
  .legend span { display: inline-flex; align-items: center; gap: 4px; }
  .swatch { width: 9px; height: 9px; border-radius: 50%; display: inline-block; }
  kbd { background: #1c1c2c; border: 1px solid var(--border); border-radius: 3px; padding: 1px 5px; font-size: 10px; font-family: ui-monospace, monospace; }
  .slider-row { display: flex; align-items: center; gap: 7px; font-size: 10.5px; color: var(--dim); }
  input[type="range"] { width: 92px; accent-color: var(--accent); }
  .massval { font-family: ui-monospace, monospace; color: var(--text); min-width: 30px; display: inline-block; }
</style>
</head>
<body>
<header>
  <h1>Why does this orbit do that?</h1>
  <p>A gravitational sandbox. Place stars, planets and black holes. Watch the field, drop test particles, and read <i>why</i> the motion is what it is — Gauss's law on a probing ring, Kepler's closed orbits, the two-frequency resonance counter, and what changes when relativity flicks on near a black hole.</p>
</header>
<main>
  <div class="panel">
    <div class="panel-header">
      <h2>Space</h2>
      <div class="toolrow">
        <button id="btnStar" class="tool">+ Star</button>
        <button id="btnPlanet" class="tool">+ Planet</button>
        <button id="btnHole" class="tool">+ Black hole</button>
        <button id="btnClear">Clear</button>
      </div>
    </div>
    <div class="canvas-wrap">
      <canvas id="stage" width="720" height="620"></canvas>
      <div class="badge" id="modeBadge">select a body type, then click to place</div>
      <div class="badge" id="coordBadge">—</div>
    </div>
    <div class="toolrow" style="padding:8px 12px; border-top:1px solid var(--border);">
      <button id="btnParticle" class="tool on">+ Test particle</button>
      <button id="btnPause">Pause</button>
      <button id="btnReset">Reset sim</button>
      <button id="btnPreset">Load: Sun + planets</button>
      <button id="btnBinary">Load: binary + circumbinary</button>
      <button id="btnBH">Load: black hole + star</button>
      <span class="slider-row">mass <input type="range" id="massSlider" min="1" max="60" value="10"><span class="massval" id="massVal">10</span></span>
      <span class="slider-row">GR <input type="range" id="grSlider" min="0" max="1" step="0.05" value="0"><span class="massval" id="grVal">0.00</span></span>
    </div>
    <div class="legend" style="padding:0 12px 9px;">
      <span><i class="swatch" style="background:var(--star)"></i>star (source)</span>
      <span><i class="swatch" style="background:var(--planet)"></i>planet (light)</span>
      <span><i class="swatch" style="background:var(--hole)"></i>black hole (strong, GR)</span>
      <span><i class="swatch" style="background:#ff5566"></i>traced particle</span>
      <span>drag a body to move · drag empty space to pan · scroll to zoom</span>
    </div>
    <div class="strip">
      <div class="stat"><div class="k">Flux through ring</div><div class="v" id="s-flux">—</div></div>
      <div class="stat"><div class="k">Enclosed mass</div><div class="v" id="s-menc">—</div></div>
      <div class="stat"><div class="k">ω_r / ω_φ</div><div class="v" id="s-ratio">—</div></div>
      <div class="stat"><div class="k">predicted precession</div><div class="v" id="s-prec">—</div></div>
    </div>
  </div>
  <div class="panel">
    <div class="panel-header">
      <h2>Why — local analysis at the cursor</h2>
      <div class="toolrow">
        <button id="btnProbe" class="on">ring probe</button>
        <button id="btnField" class="on">field</button>
        <button id="btnStream" class="on">streamlines</button>
        <button id="btnTrace" class="on">trace orbits</button>
      </div>
    </div>
    <div id="explanation">
      <p style="color:var(--dim)">Place a body, then move the cursor over a ring to probe Gauss's law, or drop a test particle to watch its orbit.</p>
    </div>
  </div>
</main>

<script>
"use strict";

// ================================================================ constants
const W = 720, H = 620;
const G_CONST = 1.0;            // simulation gravitational constant
const SOFT2 = 0.02;             // softening^2 (keeps forces finite near a mass)
const DT = 0.0025;              // integrator step
const SUBS = 6;                 // substeps per frame

const stage = document.getElementById("stage");
const ctx = stage.getContext("2d");
const explanationEl = document.getElementById("explanation");
const coordBadge = document.getElementById("coordBadge");
const modeBadge = document.getElementById("modeBadge");

// ================================================================ state
let bodies = [];          // {x,y,vx,vy,m,type:'star'|'planet'|'hole'}
let particles = [];       // test particles {trail:[[x,y]...], x,y,vx,vy, apsisR, apsisF, cycles, radialCycles, prevR, ...}
let view = { xmin: -5, xmax: 5, ymin: -4.3, ymax: 4.3 };
const HOME_VIEW = { ...view };

let placing = "star";     // which body type the next click creates
let placingParticle = true; // tool: place test particles
let paused = false;
let newMass = 10;
let grMode = 0;           // 0..1 slider; 0 = pure Newton, 1 = strong relativistic correction
let cursor = null;
let dragBody = null;
let dragging = false, dragStart = null;

let showProbe = true, showField = true, showStream = true, showTrace = true;

const STAR_PRESET_M = 20;
const HOLE_PRESET_M = 55;
const PLANET_PRESET_M = 1.2;

// ================================================================ presets
function loadSunSystem() {
  bodies = [];
  particles = [];
  bodies.push({ x: 0, y: 0, vx: 0, vy: 0, m: STAR_PRESET_M, type: "star" });
  // a few planets on near-circular orbits, v = sqrt(GM/r)
  const Rs = [1.1, 1.8, 2.6, 3.5];
  const ts = [0, 0.9, -1.8, 2.4];
  Rs.forEach((r, i) => {
    const v = Math.sqrt(G_CONST * STAR_PRESET_M / r);
    bodies.push({
      x: r * Math.cos(ts[i]), y: r * Math.sin(ts[i]),
      vx: -v * Math.sin(ts[i]), vy: v * Math.cos(ts[i]),
      m: PLANET_PRESET_M * (1 + 0.3 * i), type: "planet",
    });
  });
  view = { xmin: -4.1, xmax: 4.1, ymin: -3.5, ymax: 3.5 };
  dropTestParticle(2.15, 0.0, "circular");
}

function loadBinary() {
  bodies = [];
  particles = [];
  const m = STAR_PRESET_M * 0.75, d = 1.2;
  const v = Math.sqrt(G_CONST * m / (2 * d));
  bodies.push({ x: -d / 2, y: 0, vx: 0, vy: -v, m, type: "star" });
  bodies.push({ x: d / 2, y: 0, vx: 0, vy: v, m, type: "star" });
  view = { xmin: -5.5, xmax: 5.5, ymin: -4.7, ymax: 4.7 };
  // circumbinary test particle
  const r = 4.0, M = 2 * m;
  const vc = Math.sqrt(G_CONST * M / r);
  dropTestParticle(r, 0, null, -vc);
}

function loadBlackHole() {
  bodies = [];
  particles = [];
  bodies.push({ x: 0, y: 0, vx: 0, vy: 0, m: HOLE_PRESET_M, type: "hole" });
  view = { xmin: -6, xmax: 6, ymin: -5.2, ymax: 5.2 };
  const r = 4.2, vc = Math.sqrt(G_CONST * HOLE_PRESET_M / r) * 0.72;
  dropTestParticle(r, 0, null, -vc);   // eccentric orbit -> precession visible
}

// ================================================================ physics
function accelAt(x, y, out) {
  let ax = 0, ay = 0;
  for (const b of bodies) {
    const dx = b.x - x, dy = b.y - y;
    const r2 = dx * dx + dy * dy + SOFT2;
    const r = Math.sqrt(r2);
    let a = G_CONST * b.m / r2;
    // relativistic-ish correction: strengthens the pull at small r, mimicking
    // the extra 1/r^3 term in the GR effective potential (perihelion advance)
    if (grMode > 0 && b.type === "hole") {
      const rs = 0.35 * (b.m / HOLE_PRESET_M);   // crude "Schwarzschild-ish" scale
      a *= (1 + grMode * 3 * rs / r);
    }
    ax += a * dx / r;
    ay += a * dy / r;
  }
  out.ax = ax; out.ay = ay;
  return out;
}

const _acc = { ax: 0, ay: 0 };
function accel(x, y) { return accelAt(x, y, _acc); }

function speedAt(x, y) { const a = accel(x, y); return Math.hypot(a.ax, a.ay); }

// vector field value F = acceleration (force per unit mass) -> we plot acceleration
function fieldAt(x, y) { const a = accel(x, y); return { f: a.ax, g: a.ay }; }

// ================================================================ flux (Gauss's law)
// outward flux of F through a circle of radius R centered at (cx,cy):
//   Phi = ∮ F·n dL  ≈ sum over samples of (F·r̂) * dL, n = outward normal
function fluxThroughRing(cx, cy, R, samples = 720) {
  let sum = 0;
  const dL = 2 * Math.PI * R / samples;
  for (let i = 0; i < samples; i++) {
    const t = 2 * Math.PI * i / samples;
    const nx = Math.cos(t), ny = Math.sin(t);
    const x = cx + R * nx, y = cy + R * ny;
    const F = fieldAt(x, y);
    sum += (F.f * nx + F.g * ny) * dL;
  }
  return sum;
}

function enclosedMass(cx, cy, R) {
  let M = 0;
  for (const b of bodies) {
    const d = Math.hypot(b.x - cx, b.y - cy);
    if (d <= R) M += b.m;
  }
  return M;
}

// circular speed for the total mass inside radius R
function circularSpeed(R, Menc, originX, originY) {
  const dx = 0; // we compute from actual enclosed mass
  return Math.sqrt(G_CONST * Menc / Math.max(R, 1e-6));
}

// ================================================================ integrator
function stepBodies() {
  // leapfrog on massive bodies (mutual gravity)
  const n = bodies.length;
  const ax = new Array(n).fill(0), ay = new Array(n).fill(0);
  for (let i = 0; i < n; i++) {
    for (let j = i + 1; j < n; j++) {
      const dx = bodies[j].x - bodies[i].x, dy = bodies[j].y - bodies[i].y;
      const r2 = dx * dx + dy * dy + SOFT2;
      const r = Math.sqrt(r2);
      const inv = 1 / (r2 * r);
      const fi = G_CONST * bodies[j].m * inv;
      const fj = G_CONST * bodies[i].m * inv;
      ax[i] += fi * dx; ay[i] += fi * dy;
      ax[j] -= fj * dx; ay[j] -= fj * dy;
    }
  }
  // GR correction for massive-body pairs involving a hole
  if (grMode > 0) {
    for (let i = 0; i < n; i++) {
      for (let j = 0; j < n; j++) {
        if (i === j) continue;
        if (bodies[j].type !== "hole") continue;
        const dx = bodies[j].x - bodies[i].x, dy = bodies[j].y - bodies[i].y;
        const r = Math.hypot(dx, dy) + 1e-6;
        const rs = 0.35 * (bodies[j].m / HOLE_PRESET_M);
        const extra = G_CONST * bodies[j].m * grMode * 3 * rs / (r * r * r);
        ax[i] += extra * dx; ay[i] += extra * dy;
      }
    }
  }
  for (let i = 0; i < n; i++) {
    bodies[i].vx += ax[i] * DT * 0.5;
    bodies[i].vy += ay[i] * DT * 0.5;
    bodies[i].x += bodies[i].vx * DT;
    bodies[i].y += bodies[i].vy * DT;
  }
  // recompute acceleration at new positions and finish the kick
  const ax2 = new Array(n).fill(0), ay2 = new Array(n).fill(0);
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < n; j++) {
      if (i === j) continue;
      const dx = bodies[j].x - bodies[i].x, dy = bodies[j].y - bodies[i].y;
      const r2 = dx * dx + dy * dy + SOFT2;
      const r = Math.sqrt(r2);
      ax2[i] += G_CONST * bodies[j].m * dx / (r2 * r);
      ay2[i] += G_CONST * bodies[j].m * dy / (r2 * r);
    }
  }
  if (grMode > 0) {
    for (let i = 0; i < n; i++) {
      for (let j = 0; j < n; j++) {
        if (i === j || bodies[j].type !== "hole") continue;
        const dx = bodies[j].x - bodies[i].x, dy = bodies[j].y - bodies[i].y;
        const r = Math.hypot(dx, dy) + 1e-6;
        const rs = 0.35 * (bodies[j].m / HOLE_PRESET_M);
        const ex = G_CONST * bodies[j].m * grMode * 3 * rs / (r * r * r);
        ax2[i] += ex * dx; ay2[i] += ex * dy;
      }
    }
  }
  for (let i = 0; i < n; i++) {
    bodies[i].vx += ax2[i] * DT * 0.5;
    bodies[i].vy += ay2[i] * DT * 0.5;
  }
}

function stepParticles() {
  for (const p of particles) {
    // leapfrog
    let a = accel(p.x, p.y);
    p.vx += a.ax * DT * 0.5; p.vy += a.ay * DT * 0.5;
    p.x += p.vx * DT; p.y += p.vy * DT;
    a = accel(p.x, p.y);
    p.vx += a.ax * DT * 0.5; p.vy += a.ay * DT * 0.5;

    // trail
    p.trail.push([p.x, p.y]);
    if (p.trail.length > 1400) p.trail.shift();

    // ---- resonance bookkeeping: count radial & angular cycles about the
    //      dominant mass (the heaviest body)
    const host = heaviestBody();
    if (host) {
      const dx = p.x - host.x, dy = p.y - host.y;
      const r = Math.hypot(dx, dy);
      const th = Math.atan2(dy, dx);
      if (p.prevTheta === undefined) { p.prevTheta = th; p.prevR = r; }
      // angular winding
      let dth = th - p.prevTheta;
      while (dth > Math.PI) dth -= 2 * Math.PI;
      while (dth < -Math.PI) dth += 2 * Math.PI;
      p.angleTotal = (p.angleTotal || 0) + dth;
      p.prevTheta = th;
      p.phiCycles = Math.abs(p.angleTotal) / (2 * Math.PI);
      // radial turning points
      const drdt = (r - p.prevR);
      if (p.lastDrdt !== undefined && Math.sign(drdt) !== Math.sign(p.lastDrdt)) {
        p.radialTurns = (p.radialTurns || 0) + 1;
      }
      p.lastDrdt = drdt;
      p.prevR = r;
      p.radialCycles = (p.radialTurns || 0) / 2;
      p.radius = r;
      p.hostDist = r;
      if (r > p.far) p.far = r;
      if (r < p.near) p.near = r;
    }
  }
  // cull particles that have flown far away
  particles = particles.filter(p => p.trail[p.trail.length - 1] &&
    Math.hypot(p.x, p.y) < 60);
}

function heaviestBody() {
  let best = null;
  for (const b of bodies) if (!best || b.m > best.m) best = b;
  return best;
}

function dropTestParticle(x, y, kind, vyOverride) {
  const host = heaviestBody();
  let vx = 0, vy = 0;
  if (host) {
    const dx = x - host.x, dy = y - host.y;
    const r = Math.hypot(dx, dy) + 1e-9;
    const Menc = totalMassInside(host.x, host.y, r);
    const vc = Math.sqrt(G_CONST * Math.max(Menc, 1e-9) / r);
    // perpendicular (circular) velocity
    vx = -dy / r * vc; vy = dx / r * vc;
    // small radial nudge so apoapsis/periapsis differ (visible ellipse)
    const nudge = 0.0;
    vx += dx / r * vc * nudge; vy += dy / r * vc * nudge;
  }
  if (vyOverride !== undefined && vyOverride !== null) { vy = vyOverride; }
  particles.push({
    x, y, vx, vy, trail: [[x, y]],
    near: Infinity, far: 0,
    radialTurns: 0, angleTotal: 0, hostDist: 0,
  });
}

function totalMassInside(cx, cy, R) {
  let M = 0;
  for (const b of bodies) if (Math.hypot(b.x - cx, b.y - cy) <= R) M += b.m;
  return M;
}

// ================================================================ drawing
function toPx(x, y) {
  return {
    sx: (x - view.xmin) / (view.xmax - view.xmin) * W,
    sy: (view.ymax - y) / (view.ymax - view.ymin) * H,
  };
}
function toWorld(sx, sy) {
  return {
    x: view.xmin + (sx / W) * (view.xmax - view.xmin),
    y: view.ymax - (sy / H) * (view.ymax - view.ymin),
  };
}

const PAL = [
  [8, 8, 20], [14, 20, 48], [26, 44, 96], [48, 84, 160],
  [92, 140, 220], [170, 208, 255], [255, 255, 255],
  [255, 236, 170], [255, 190, 90], [240, 120, 30], [170, 40, 10],
];
function lerp(a, b, t) { return a + (b - a) * t; }
function palColor(u) {
  u = Math.max(0, Math.min(1, u));
  const n = PAL.length - 1, x = u * n, i = Math.floor(x), f = x - i;
  const c0 = PAL[i], c1 = PAL[Math.min(n, i + 1)];
  return [Math.round(lerp(c0[0], c1[0], f)), Math.round(lerp(c0[1], c1[1], f)), Math.round(lerp(c0[2], c1[2], f))];
}

function bodyRadius(b) {
  if (b.type === "hole") return 7 + Math.sqrt(b.m) * 0.55;
  if (b.type === "star") return 5 + Math.sqrt(b.m) * 0.55;
  return 3.2 + Math.sqrt(b.m) * 0.7;
}
function bodyColor(b) {
  if (b.type === "hole") return "#b47aff";
  if (b.type === "star") return "#ffd257";
  return "#5ea8ff";
}

function drawFieldLayer() {
  // coarse magnitude/potential shading, drawn to an offscreen buffer
  const off = document.createElement("canvas");
  off.width = W; off.height = H;
  const octx = off.getContext("2d");
  const img = octx.createImageData(W, H);
  const data = img.data;

  // find max |accel| sampled for normalization
  let maxA = 0;
  const N = 60;
  for (let i = 0; i <= N; i++) for (let j = 0; j <= N; j++) {
    const w = toWorld(i / N * W, j / N * H);
    const s = speedAt(w.x, w.y);
    if (isFinite(s) && s > maxA) maxA = s;
  }
  if (maxA === 0) maxA = 1;
  const lmax = Math.log(1 + maxA);

  for (let py = 0; py < H; py += 3) {
    for (let px = 0; px < W; px += 3) {
      const w = toWorld(px, py);
      const s = speedAt(w.x, w.y);
      const u = maxA > 0 ? Math.log(1 + s) / lmax : 0;
      const c = palColor(u * 0.85);
      for (let dy = 0; dy < 3 && py + dy < H; dy++) {
        for (let dx = 0; dx < 3 && px + dx < W; dx++) {
          const idx = ((py + dy) * W + px + dx) * 4;
          data[idx] = c[0]; data[idx + 1] = c[1]; data[idx + 2] = c[2]; data[idx + 3] = 255;
        }
      }
    }
  }
  octx.putImageData(img, 0, 0);
  ctx.drawImage(off, 0, 0);
}

function drawGlyphs() {
  const n = 26;
  const cell = Math.min(W / n, H / n);
  const cols = Math.ceil(W / cell), rows = Math.ceil(H / cell);
  const maxLen = cell * 0.8;
  let amax = 1e-9;
  const cells = [];
  for (let i = 0; i < cols; i++) for (let j = 0; j < rows; j++) {
    const sx = (i + 0.5) * cell, sy = (j + 0.5) * cell;
    const w = toWorld(sx, sy);
    const F = fieldAt(w.x, w.y);
    const m = Math.hypot(F.f, F.g);
    cells.push({ sx, sy, F, m });
    if (isFinite(m) && m > amax) amax = m;
  }
  for (const c of cells) {
    if (!isFinite(c.m) || c.m < 1e-7) continue;
    const ang = Math.atan2(c.F.g, c.F.f);
    const u = Math.pow(c.m / amax, 0.32);
    const L = maxLen * u;
    const ux = Math.cos(ang), uy = -Math.sin(ang); // screen y is flipped
    const x0 = c.sx - ux * L * 0.5, y0 = c.sy - uy * L * 0.5;
    const x1 = c.sx + ux * L * 0.5, y1 = c.sy + uy * L * 0.5;

    // direction hue + magnitude brightness, matching the vector plotter
    let hue = ang * 180 / Math.PI; if (hue < 0) hue += 360;
    const light = 32 + 40 * u, sat = 65 + 25 * u;
    ctx.strokeStyle = `hsla(${hue}, ${sat}%, ${light}%, 0.85)`;
    ctx.fillStyle = ctx.strokeStyle;
    ctx.lineWidth = 1.2;
    const dx = x1 - x0, dy = y1 - y0, len = Math.hypot(dx, dy);
    if (len < 2) continue;
    const vx = dx / len, vy = dy / len;
    const head = Math.min(6, 2.4 + len * 0.22);
    ctx.beginPath(); ctx.moveTo(x0, y0); ctx.lineTo(x1 - vx * head * 0.7, y1 - vy * head * 0.7); ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(x1, y1);
    ctx.lineTo(x1 - vx * head - vy * head * 0.5, y1 - vy * head + vx * head * 0.5);
    ctx.lineTo(x1 - vx * head + vy * head * 0.5, y1 - vy * head - vx * head * 0.5);
    ctx.closePath(); ctx.fill();
  }
}

function traceStreamline(x0, y0, dir, color) {
  let x = x0, y = y0;
  const pts = [];
  for (let i = 0; i < 260; i++) {
    const a = accel(x, y);
    const m = Math.hypot(a.ax, a.ay);
    if (m < 1e-9) break;
    const step = 0.035;
    x += (a.ax / m) * step * dir;
    y += (a.ay / m) * step * dir;
    pts.push(toPx(x, y));
    if (x < view.xmin - 1 || x > view.xmax + 1 || y < view.ymin - 1 || y > view.ymax + 1) break;
  }
  if (pts.length < 2) return;
  ctx.strokeStyle = color; ctx.lineWidth = 1.2;
  ctx.beginPath(); ctx.moveTo(pts[0].sx, pts[0].sy);
  for (let i = 1; i < pts.length; i++) ctx.lineTo(pts[i].sx, pts[i].sy);
  ctx.stroke();
}

function drawBodies() {
  for (const b of bodies) {
    const p = toPx(b.x, b.y);
    const R = bodyRadius(b);
    const col = bodyColor(b);
    if (b.type === "hole") {
      // accretion-ish glow
      const g = ctx.createRadialGradient(p.sx, p.sy, R * 0.4, p.sx, p.sy, R * 3.2);
      g.addColorStop(0, "rgba(180,122,255,0.55)");
      g.addColorStop(1, "rgba(180,122,255,0)");
      ctx.fillStyle = g;
      ctx.beginPath(); ctx.arc(p.sx, p.sy, R * 3.2, 0, 2 * Math.PI); ctx.fill();
      ctx.fillStyle = "#0a0612";
      ctx.beginPath(); ctx.arc(p.sx, p.sy, R, 0, 2 * Math.PI); ctx.fill();
      ctx.strokeStyle = col; ctx.lineWidth = 2;
      ctx.beginPath(); ctx.arc(p.sx, p.sy, R, 0, 2 * Math.PI); ctx.stroke();
      ctx.strokeStyle = "rgba(180,122,255,0.35)"; ctx.lineWidth = 1;
      ctx.beginPath(); ctx.arc(p.sx, p.sy, R * 1.55, 0, 2 * Math.PI); ctx.stroke();
    } else {
      if (b.type === "star") {
        const g = ctx.createRadialGradient(p.sx, p.sy, R * 0.3, p.sx, p.sy, R * 3.5);
        g.addColorStop(0, "rgba(255,210,87,0.55)");
        g.addColorStop(1, "rgba(255,160,40,0)");
        ctx.fillStyle = g;
        ctx.beginPath(); ctx.arc(p.sx, p.sy, R * 3.5, 0, 2 * Math.PI); ctx.fill();
      }
      ctx.fillStyle = col;
      ctx.beginPath(); ctx.arc(p.sx, p.sy, R, 0, 2 * Math.PI); ctx.fill();
      ctx.strokeStyle = "rgba(255,255,255,0.55)"; ctx.lineWidth = 1;
      ctx.stroke();
    }
    // mass label
    ctx.fillStyle = "rgba(255,255,255,0.6)";
    ctx.font = "9.5px ui-monospace, monospace";
    ctx.fillText("m=" + b.m.toFixed(1), p.sx + R + 4, p.sy + 3);
  }
}

function drawParticles() {
  for (const p of particles) {
    const tr = p.trail;
    if (tr.length > 1) {
      ctx.strokeStyle = "rgba(255,85,102,0.75)";
      ctx.lineWidth = 1.3;
      ctx.beginPath();
      const s0 = toPx(tr[0][0], tr[0][1]);
      ctx.moveTo(s0.sx, s0.sy);
      for (let i = 1; i < tr.length; i++) {
        const s = toPx(tr[i][0], tr[i][1]);
        ctx.lineTo(s.sx, s.sy);
      }
      ctx.stroke();
    }
    const s = toPx(p.x, p.y);
    // velocity arrow
    const sp = Math.hypot(p.vx, p.vy);
    if (sp > 1e-6) {
      const ux = p.vx / sp, uy = -p.vy / sp;
      const L = 12 + 8 * Math.log(1 + sp);
      ctx.strokeStyle = "#ff8a99"; ctx.lineWidth = 1.6;
      ctx.beginPath(); ctx.moveTo(s.sx, s.sy); ctx.lineTo(s.sx + ux * L, s.sy + uy * L); ctx.stroke();
    }
    ctx.fillStyle = "#ff5566";
    ctx.beginPath(); ctx.arc(s.sx, s.sy, 3.4, 0, 2 * Math.PI); ctx.fill();
    ctx.strokeStyle = "#fff"; ctx.lineWidth = 1; ctx.stroke();
  }
}

// ---- ring probe (Gauss's law visual)
function drawRingProbe(cx, cy, R) {
  const p = toPx(cx, cy);
  const rpx = R / (view.xmax - view.xmin) * W;

  // the ring itself
  ctx.strokeStyle = "rgba(108,204,255,0.55)";
  ctx.lineWidth = 1.4;
  ctx.setLineDash([6, 5]);
  ctx.beginPath(); ctx.arc(p.sx, p.sy, rpx, 0, 2 * Math.PI); ctx.stroke();
  ctx.setLineDash([]);

  // sample arrows along the ring: outward normal component
  const samples = 48;
  let fluxSum = 0;
  const dL = 2 * Math.PI * R / samples;
  let maxN = 1e-9;
  const vals = [];
  for (let i = 0; i < samples; i++) {
    const t = 2 * Math.PI * i / samples;
    const nx = Math.cos(t), ny = Math.sin(t);
    const x = cx + R * nx, y = cy + R * ny;
    const F = fieldAt(x, y);
    const ncomp = F.f * nx + F.g * ny;
    fluxSum += ncomp * dL;
    vals.push({ t, nx, ny, ncomp, F });
    if (Math.abs(ncomp) > maxN) maxN = Math.abs(ncomp);
  }

  const Menc = enclosedMass(cx, cy, R);
  const predicted = -2 * Math.PI * G_CONST * Menc;  // in 2D, flux of a 1/r field = -2πG M
  const consistent = Math.abs(fluxSum - predicted) < 0.25 * Math.max(1, Math.abs(predicted));

  for (const v of vals) {
    const x = cx + R * v.nx, y = cy + R * v.ny;
    const q = toPx(x, y);
    const u = Math.abs(v.ncomp) / maxN;
    const L = 4 + 13 * u;
    const inward = v.ncomp < 0;
    const ux = inward ? -v.nx : v.nx;   // draw along sign of normal component
    const uy = inward ? -v.ny : v.ny;
    ctx.strokeStyle = inward ? "rgba(108,204,255,0.85)" : "rgba(76,175,80,0.9)";
    ctx.lineWidth = 1.3;
    const sx = q.sx, sy = -q.sy + 0; // (already screen coords)
    const syy = q.sy;
    ctx.beginPath();
    ctx.moveTo(sx, syy);
    ctx.lineTo(sx + ux * L, syy - uy * L);
    ctx.stroke();
    // little arrowhead
    const hx = sx + ux * L, hy = syy - uy * L;
    ctx.beginPath();
    ctx.moveTo(hx, hy);
    ctx.lineTo(hx - ux * 3 - uy * 2, hy + uy * 3 - ux * 2);
    ctx.lineTo(hx - ux * 3 + uy * 2, hy + uy * 3 + ux * 2);
    ctx.closePath(); ctx.fillStyle = ctx.strokeStyle; ctx.fill();
  }

  // center dot
  ctx.fillStyle = "#6cf";
  ctx.beginPath(); ctx.arc(p.sx, p.sy, 2.6, 0, 2 * Math.PI); ctx.fill();

  return { flux: fluxSum, Menc, predicted, consistent, R, cx, cy };
}

// ================================================================ render
let lastProbe = null;

function render() {
  ctx.fillStyle = "#04040a";
  ctx.fillRect(0, 0, W, H);

  if (showField) { drawFieldLayer(); drawGlyphs(); }

  if (showStream && cursor) {
    // faint streamlines through the cursor
    traceStreamline(cursor.x, cursor.y, 1, "rgba(108,204,255,0.28)");
    traceStreamline(cursor.x, cursor.y, -1, "rgba(108,204,255,0.16)");
  }

  drawBodies();
  if (showTrace) drawParticles();

  if (showProbe && cursor) {
    const host = heaviestBody();
    if (host) {
      const R = Math.hypot(cursor.x - host.x, cursor.y - host.y);
      if (R > 0.15) lastProbe = drawRingProbe(host.x, host.y, R);
      else lastProbe = null;
    }
    // crosshair
    const c = toPx(cursor.x, cursor.y);
    ctx.strokeStyle = "rgba(255,255,255,0.75)";
    ctx.lineWidth = 1;
    ctx.beginPath();
    ctx.moveTo(c.sx - 12, c.sy); ctx.lineTo(c.sx - 4, c.sy);
    ctx.moveTo(c.sx + 4, c.sy); ctx.lineTo(c.sx + 12, c.sy);
    ctx.moveTo(c.sx, c.sy - 12); ctx.lineTo(c.sx, c.sy - 4);
    ctx.moveTo(c.sx, c.sy + 4); ctx.lineTo(c.sx, c.sy + 12);
    ctx.stroke();
  }
}

// ================================================================ explanation
function fmt(x, d = 3) {
  if (!isFinite(x)) return "∞";
  if (Math.abs(x) < 1e-10) return "0";
  if (Math.abs(x) >= 1e4 || Math.abs(x) < 1e-3) return x.toExponential(2);
  return x.toFixed(d);
}

function buildExplanation() {
  let html = "";

  // ---- part 1: the local field at the cursor
  if (cursor) {
    const F = fieldAt(cursor.x, cursor.y);
    const mag = Math.hypot(F.f, F.g);
    const ang = Math.atan2(F.g, F.f) * 180 / Math.PI;
    html += `<h4>At the cursor (${fmt(cursor.x, 2)}, ${fmt(cursor.y, 2)})</h4>`;
    html += `<p>Acceleration <b>g = (${fmt(F.f, 3)}, ${fmt(F.g, 3)})</b>, magnitude <b>${fmt(mag, 3)}</b>, pointing ${ang.toFixed(1)}°.</p>`;
    if (mag > 1e-9) {
      // compare to closest body's inverse-square prediction
      let best = null, bestD = Infinity;
      for (const b of bodies) {
        const d = Math.hypot(b.x - cursor.x, b.y - cursor.y);
        if (d < bestD) { bestD = d; best = b; }
      }
      if (best && bestD > 0.05) {
        const pred = G_CONST * best.m / (bestD * bestD);
        const ratio = mag / pred;
        html += `<p>The nearest body (m = ${fmt(best.m, 2)}, ${fmt(bestD, 3)} away) alone would give ${fmt(pred, 3)}. The actual value is <b>${fmt(ratio, 3)}×</b> that — ${
          ratio > 1.03 ? "the <i>other</i> bodies add to the pull here, so the field is stronger than one mass predicts."
          : ratio < 0.97 ? "other bodies pull the other way, reducing the net force."
          : "close to a single-mass field; other bodies roughly cancel here."
        }</p>`;
      }
    }
    html += `<div class="eq">g(r) = Σ G mᵢ (rᵢ − r) / |rᵢ − r|³</div>`;
  } else {
    html += `<p style="color:var(--dim)">Move the cursor over the space to inspect the field.</p>`;
  }

  // ---- part 2: Gauss's law ring probe
  if (lastProbe) {
    const P = lastProbe;
    html += `<h4>Gauss's law on the ring you drew</h4>`;
    html += `<p>Ring of radius R = ${fmt(P.R, 3)} around the dominant mass.</p>`;
    html += `<div class="verdict ${P.consistent ? "good" : "warn"}">Outward flux Φ = ${fmt(P.flux, 3)} &nbsp;vs&nbsp; −2πG·M<sub>enc</sub> = ${fmt(P.predicted, 3)} — ${P.consistent ? "consistent with Gauss's law" : "differing (mass outside the ring, or softening)"}</div>`;
    html += `<p><b>M<sub>enc</sub></b> = ${fmt(P.Menc, 3)} (total mass strictly inside the ring). The cyan arrows on the ring are the inward normal component of the field; the green ones would be outward. Their integral is the flux.</p>`;
    html += `<p>Notice: if you grow the ring through empty space, <b>Φ stays constant</b> — that is the 2D Gauss law, and it is the reason the <i>field</i> falls like 1/r while the <i>flux</i> does not fall at all. In 3D the same argument gives 1/r². The inverse-square law is not an extra assumption; it is what “flux is conserved” forces.</p>`;
  } else if (cursor) {
    html += `<h4>Gauss's law</h4><p style="color:var(--dim)">Move the cursor between 0.2 and a few units from a mass to draw the flux ring.</p>`;
  }

  // ---- part 3: the strongest particle's orbital clock ratio
  let p = null;
  for (const q of particles) if (!p || q.trail.length > p.trail.length) p = q;
  if (p && p.phiCycles > 0.12) {
    const ratio = p.radialCycles / p.phiCycles;
    html += `<h4>The orbit's two clocks (resonance counter)</h4>`;
    html += `<p>This particle has completed <b>${P.num}${""}</b></p>`;
    html += `<table>
      <tr><th>quantity</th><th>value</th><th>meaning</th></tr>
      <tr><td>ω_φ cycles</td><td>${fmt(p.phiCycles, 3)}</td><td>angle wound around the host</td></tr>
      <tr><td>ω_r cycles</td><td>${fmt(p.radialCycles, 3)}</td><td>radial in/out cycles</td></tr>
      <tr><td>ratio ω_r/ω_φ</td><td><b>${fmt(ratio, 4)}</b></td><td>${ratio > 0.97 && ratio < 1.03 ? "1:1 — orbit is CLOSED (Kepler degeneracy)" : "≠1 — orbit precesses into a rosette"}</td></tr>
      <tr><td>periapsis</td><td>${fmt(p.near, 3)}</td><td>closest approach</td></tr>
      <tr><td>apoapsis</td><td>${fmt(p.far, 3)}</td><td>farthest point</td></tr>
    </table>`;
    html += `<div class="verdict ${ratio > 0.97 && ratio < 1.03 ? "good" : "info"}">${ratio > 0.97 && ratio < 1.03
      ? "The two frequencies are locking at exactly 1:1 — this is the hidden symmetry (the Runge–Lenz vector) that makes Kepler orbits close."
      : "ω_r ≠ ω_φ, so the ellipse's axis rotates a little each turn — this is orbital precession, the same effect seen as Mercury's perihelion advance."}</div>`;
    html += `<p><b>Why 1:1 is special.</b> For a pure 1/r² force, the radial and angular clocks tick at the same rate — an accident of the force law that gives a conserved Runge–Lenz vector (a hidden extra symmetry). Break it — add GR near a black hole, or a third body — and the ratio drifts from 1. That drift <i>is</i> precession. In this sim, push the <code>GR</code> slider up with a black hole present and watch the ratio move away from 1.</p>`;
  }

  // ---- part 4: resonance / stability of the whole configuration
  if (particles.length && bodies.length > 1) {
    const host = heaviestBody();
    const Menc = totalMassInside(host.x, host.y, 1e9);
    html += `<h4>Is this system resonantly stable?</h4>`;
    if (bodies.length === 2) {
      const m1 = bodies[0].m, m2 = bodies[1].m;
      const ratioM = Math.max(m1, m2) / Math.min(m1, m2);
      html += `<p>Two-body system with mass ratio ${fmt(ratioM, 2)}. A two-body orbit has only one meaningful clock pair, so its ω_r/ω_φ is fixed by geometry: 1:1 for the pure 1/r² law. There is no internal resonance to lock or unlock until you add a third body.</p>`;
    } else {
      html += `<p>You have ${bodies.length} massive bodies. Mean-motion resonances occur when their orbital periods form simple integer ratios, e.g. period ratio ${fmt(1, 2)} ↔ 2:1. Circular restricted three-body resonances would show as the test particle's ω_r/ω_φ clinging to a rational value. Watch the ratio in the table above after you load the <i>binary</i> preset — the circumbinary particle's ratio will wander depending on how near it sits to a lock.</p>`;
    }
  }

  html += `<div class="note"><b>What this sim does and does not model.</b> It solves Newtonian N-body gravity with a softening length (so forces stay finite at the centre of a mass). The "GR" slider is a <i>cartoon</i>: it adds a small 1/r³ extra attraction near black holes, which produces the right qualitative perihelion advance, not the exact Schwarzschild value — real GR gives a perihelion shift of 6πGM/(c²a(1−e²)) per orbit. Nothing here integrates null geodesics or the black-hole shadow.</div>`;
  return html;
}

function updateReadout() {
  if (lastProbe) {
    document.getElementById("s-flux").textContent = fmt(lastProbe.flux, 3);
    document.getElementById("s-menc").textContent = fmt(lastProbe.Menc, 3);
  } else {
    document.getElementById("s-flux").textContent = "—";
    document.getElementById("s-menc").textContent = "—";
  }
  let p = null;
  for (const q of particles) if (!p || q.trail.length > p.trail.length) p = q;
  if (p && p.phiCycles > 0.12) {
    const ratio = p.radialCycles / p.phiCycles;
    document.getElementById("s-ratio").textContent = fmt(ratio, 4);
    const drift = Math.abs(1 - ratio);
    document.getElementById("s-prec").textContent = drift < 0.02 ? "none" : (drift * 360).toFixed(1) + "° / orbit";
  } else {
    document.getElementById("s-ratio").textContent = "—";
    document.getElementById("s-prec").textContent = "—";
  }
}

// ================================================================ interaction
stage.addEventListener("mousemove", (e) => {
  const rect = stage.getBoundingClientRect();
  const sx = (e.clientX - rect.left) / rect.width * W;
  const sy = (e.clientY - rect.top) / rect.height * H;
  const w = toWorld(sx, sy);

  if (dragBody) {
    dragBody.x = w.x; dragBody.y = w.y;
    render();
    return;
  }
  if (dragging) {
    const dx = (e.clientX - dragStart.x) / rect.width * (dragStart.view.xmax - dragStart.view.xmin);
    const dy = (e.clientY - dragStart.y) / rect.height * (dragStart.view.ymax - dragStart.view.ymin);
    view.xmin = dragStart.view.xmin - dx;
    view.xmax = dragStart.view.xmax - dx;
    view.ymin = dragStart.view.ymin + dy;
    view.ymax = dragStart.view.ymax + dy;
    render();
    return;
  }
  cursor = w;
  coordBadge.textContent = `(${w.x.toFixed(3)}, ${w.y.toFixed(3)})`;
  render();
  explanationEl.innerHTML = buildExplanation();
  updateReadout();
});

stage.addEventListener("mouseleave", () => { cursor = null; });

stage.addEventListener("mousedown", (e) => {
  const rect = stage.getBoundingClientRect();
  const sx = (e.clientX - rect.left) / rect.width * W;
  const sy = (e.clientY - rect.top) / rect.height * H;
  const w = toWorld(sx, sy);

  // grab a body if clicked near one
  let grabbed = null;
  for (const b of bodies) {
    const p = toPx(b.x, b.y);
    if (Math.hypot(p.sx - sx, p.sy - sy) < bodyRadius(b) + 8) { grabbed = b; break; }
  }
  if (grabbed) { dragBody = grabbed; return; }

  if (placingParticle) {
    dropTestParticle(w.x, w.y, null);
    render();
    explanationEl.innerHTML = buildExplanation();
  } else {
    // place a new body
    let m = newMass;
    if (placing === "star") m = Math.max(4, newMass * 1.6);
    if (placing === "planet") m = Math.max(0.4, newMass * 0.12);
    if (placing === "hole") m = Math.max(20, newMass * 4.2);
    const b = { x: w.x, y: w.y, vx: 0, vy: 0, m, type: placing };
    // give it a sensible circular velocity about the existing mass
    const host = heaviestBody();
    if (host && (host.x !== w.x || host.y !== w.y)) {
      const dx = w.x - host.x, dy = w.y - host.y, r = Math.hypot(dx, dy);
      const Menc = totalMassInside(host.x, host.y, r);
      const vc = Math.sqrt(G_CONST * Math.max(Menc, 1e-9) / Math.max(r, 0.2));
      b.vx = -dy / r * vc; b.vy = dx / r * vc;
    }
    bodies.push(b);
    render();
  }
});

window.addEventListener("mousemove", (e) => {
  if (!dragging) return;
});

stage.addEventListener("mouseup", () => { dragBody = null; dragging = false; });
window.addEventListener("mouseup", () => { dragBody = null; dragging = false; });

stage.addEventListener("dblclick", () => {
  view = { ...HOME_VIEW };
  render();
});

stage.addEventListener("wheel", (e) => {
  e.preventDefault();
  const rect = stage.getBoundingClientRect();
  const pxFrac = (e.clientX - rect.left) / rect.width;
  const pyFrac = (e.clientY - rect.top) / rect.height;
  const cx = view.xmin + pxFrac * (view.xmax - view.xmin);
  const cy = view.ymax - pyFrac * (view.ymax - view.ymin);
  const factor = e.deltaY < 0 ? 0.82 : 1.22;
  const nw = (view.xmax - view.xmin) * factor;
  const nh = (view.ymax - view.ymin) * factor;
  view.xmin = cx - pxFrac * nw; view.xmax = view.xmin + nw;
  view.ymax = cy + pyFrac * nh; view.ymin = view.ymax - nh;
  render();
}, { passive: false });

// pan with drag in empty space
stage.addEventListener("mousedown", (e) => {
  // handled above; if no body grabbed and not placing, start a pan
}, false);
// re-implement pan cleanly: use right region — we detect empty drag on mousemove via flag
stage.addEventListener("mousedown", (e) => {
  const rect = stage.getBoundingClientRect();
  const sx = (e.clientX - rect.left) / rect.width * W;
  const sy = (e.clientY - rect.top) / rect.height * H;
  let overBody = false;
  for (const b of bodies) {
    const p = toPx(b.x, b.y);
    if (Math.hypot(p.sx - sx, p.sy - sy) < bodyRadius(b) + 8) { overBody = true; break; }
  }
  if (!overBody && !placingParticle) {
    dragging = true;
    dragStart = { x: e.clientX, y: e.clientY, view: { ...view } };
  }
});

// ================================================================ tools
function setTool(btn, active) {
  btn.classList.toggle("on", active);
}
const toolButtons = ["btnStar", "btnPlanet", "btnHole", "btnParticle"];
function selectTool(which) {
  placingParticle = (which === "particle");
  if (!placingParticle) placing = which;
  document.getElementById("btnStar").classList.toggle("on", which === "star");
  document.getElementById("btnPlanet").classList.toggle("on", which === "planet");
  document.getElementById("btnHole").classList.toggle("on", which === "hole");
  document.getElementById("btnParticle").classList.toggle("on", which === "particle");
  modeBadge.textContent = placingParticle
    ? "click to drop a test particle"
    : "click to place a " + which;
  modeBadge.classList.toggle("armed", true);
}
document.getElementById("btnStar").addEventListener("click", () => selectTool("star"));
document.getElementById("btnPlanet").addEventListener("click", () => selectTool("planet"));
document.getElementById("btnHole").addEventListener("click", () => selectTool("hole"));
document.getElementById("btnParticle").addEventListener("click", () => selectTool("particle"));

document.getElementById("btnClear").addEventListener("click", () => {
  bodies = []; particles = [];
  render(); explanationEl.innerHTML = '<p style="color:var(--dim)">Cleared. Place a body to begin.</p>';
});
document.getElementById("btnPause").addEventListener("click", (e) => {
  paused = !paused;
  e.target.textContent = paused ? "Resume" : "Pause";
  e.target.classList.toggle("on", paused);
});
document.getElementById("btnReset").addEventListener("click", () => {
  particles = [];
  // re-seed a circular particle around the heaviest body
  const host = heaviestBody();
  if (host) dropTestParticle(host.x + 2.2, host.y, null);
  render();
});
document.getElementById("btnPreset").addEventListener("click", () => { loadSunSystem(); render(); });
document.getElementById("btnBinary").addEventListener("click", () => { loadBinary(); render(); });
document.getElementById("btnBH").addEventListener("click", () => { loadBlackHole(); render(); });

document.getElementById("massSlider").addEventListener("input", (e) => {
  newMass = Number(e.target.value);
  document.getElementById("massVal").textContent = e.target.value;
});
document.getElementById("grSlider").addEventListener("input", (e) => {
  grMode = Number(e.target.value);
  document.getElementById("grVal").textContent = grMode.toFixed(2);
});

// overlay toggles
function toggleBtn(id, setter, getter) {
  const b = document.getElementById(id);
  b.addEventListener("click", () => {
    setter(!getter());
    b.classList.toggle("on", getter());
    render();
  });
}
let probeOn = true, fieldOn = true, streamOn = true, traceOn = true;
document.getElementById("btnProbe").addEventListener("click", (e) => {
  probeOn = !probeOn; showProbe = probeOn; e.target.classList.toggle("on", probeOn); render();
});
document.getElementById("btnField").addEventListener("click", (e) => {
  fieldOn = !fieldOn; showField = fieldOn; e.target.classList.toggle("on", fieldOn); render();
});
document.getElementById("btnStream").addEventListener("click", (e) => {
  streamOn = !streamOn; showStream = streamOn; e.target.classList.toggle("on", streamOn); render();
});
document.getElementById("btnTrace").addEventListener("click", (e) => {
  traceOn = !traceOn; showTrace = traceOn; e.target.classList.toggle("on", traceOn); render();
});

// ================================================================ main loop
let frame = 0;
function loop() {
  if (!paused) {
    for (let s = 0; s < SUBS; s++) { stepBodies(); stepParticles(); }
    frame++;
  }
  render();
  if (cursor) {
    explanationEl.innerHTML = buildExplanation();
  }
  updateReadout();
  requestAnimationFrame(loop);
}

// ================================================================ init
loadSunSystem();
selectTool("particle");
render();
explanationEl.innerHTML = buildExplanation();
requestAnimationFrame(loop);
</script>
</body>
</html>