-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplanetclock.js
More file actions
4884 lines (4565 loc) · 179 KB
/
planetclock.js
File metadata and controls
4884 lines (4565 loc) · 179 KB
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
/**
* @file PlanetClock class creates an interactive geocentric digital orrery.
* @author David H. Munro
* @copyright David H. Munro 2022
* @license MIT
*
* This script depends on ephemeris.js and d3.
* The required externals are:
* d3 from d3
* dayOfDate, dateOfDay, directionOf, timeSunAt, eclipticOrientation
* from ephemeris.js
*/
/* see https://www.cantab.net/users/davidasher/orrery/zodiac.html
* for coordinates of constellations of the Zodiac:
* pisces 28.687 aries 53.417 taurus 90.140 gemini 117.988 cancer 138.038
* leo 173.851 virgo 217.810 libra 241.047 scorpio+ophiuchus 266.238
* sagittarius 299.656 capricorn 327.488 aquarius 351.650 pisces
* Astrological dates (match positions in about year 0):
* Aries 20/Mar-19/Apr Taurus 20/Apr-20/May Gemini 21/May-20/Jun
* Cancer 21/Jun-21/Jul Leo 22/Jul-22/Aug Virgo 23/Aug-22/Sep
* Libra 23/Sep-22/Oct Scorpio 23/Oct-21/Nov Sagittarius 22/Nov-20/Dec
* Capricorn 21/Dec-19/Jan Aquarius 20/Jan-17/Feb Pisces 18/Feb-19/March
*/
class PlanetClock {
static #width = 750; // just a convenient number, svg will scale
static #height = PlanetClock.#width;
static #rOuter = PlanetClock.#width * 0.5 - 20;
static #rInner = PlanetClock.#rOuter * 0.71;
constructor(d3Parent, initYear=2022) {
let [width, height] = [PlanetClock.#width, PlanetClock.#height];
this.svg = d3Parent.append("svg")
.attr("xmlns", "http://www.w3.org/2000/svg")
.attr("xmlns:xlink", "http://www.w3.org/1999/xlink")
.attr("class", "PlanetClock")
.attr("viewBox", [-width/2, -height/2, width, height])
.attr("text-anchor", "middle")
.attr("font-family", "'Merriweather Sans', sans-serif")
.attr("font-weight", "bold")
.attr("font-size", 12)
.attr("stroke-linejoin", "round")
.attr("stroke-linecap", "round");
let [rInner, rOuter] = [PlanetClock.#rInner, PlanetClock.#rOuter];
this.disabled = false; // set true to disable controls
let initDay = new Date("Jan 1 2000 12:00 GMT"); // J2000 time origin
initDay.setUTCFullYear(initYear);
// begin at vernal equinox
this.dayNow = timeSunAt(1.0, 0.0, dayOfDate(initDay));
// jan feb mar apr may jun jul aug sep oct nov dec
let nday = [0, 31, 28.256366, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
this.eperiod = 0;
this.tMonth = nday.map(dt => this.eperiod += dt);
this.updateMonths();
// night sky ring
let nightSky = this.svg.append("g").call(
g => {
appendCircle(g, rInner, "#ddd", 0);
appendCircle(g, 0.5*(rOuter + rInner), "#000", rOuter - rInner);
});
// Zodiac constellations
let zodiac = [28.687, 53.417, 90.140, 117.988, 138.038, 173.851,
217.810, 241.047, 266.238, 299.656, 327.488, 351.650];
let zodiacNames = ["Ari", "Tau", "Gem", "Cnc", "Leo", "Vir", "Lib",
"Sco", "Sgr", "Cap", "Aqr", "Psc"];
zodiac = zodiac.map(
(a, i) => [Math.cos(a*Math.PI/180), Math.sin(a*Math.PI/180), i]);
zodiacNames = zodiac.map(
([x, y], i) => {
let [u, v] = zodiac[(i + 1) % 12];
u += x;
v += y;
let r = Math.sqrt(u**2 + v**2);
u /= r;
v /= r;
return [u, v, zodiacNames[i]];
});
this.zodiac = this.svg.append("g").call(
g => {
let rBar = 0.5*(rInner + rOuter);
g.selectAll("g")
.data(zodiac)
.join("g")
.call(g => g.append("line")
.attr("stroke", "#575")
.attr("stroke-width", 2)
.attr("stroke-dasharray", "5, 5")
.attr("x1", d => rInner*d[0])
.attr("y1", d => -rInner*d[1])
.attr("x2", d => 1.03*rOuter*d[0])
.attr("y2", d => -1.03*rOuter*d[1]))
.call(g => appendText(
g, 0, "#575", false,
d => rBar*zodiacNames[d[2]][0], d => -rBar*zodiacNames[d[2]][1],
d => zodiacNames[d[2]][2]).attr("dy", "0.35em"));
});
// day sky wedge is dynamic element needing updates to transform property
this.daySky = nightSky.append("g").call(
g => {
g.append("path").call(
p => {
let pio12 = Math.PI / 12;
let [cpio12, spio12] = [Math.cos(pio12), Math.sin(pio12)];
let d3p = d3.path();
d3p.moveTo(1.005*rOuter*cpio12, -1.005*rOuter*spio12);
d3p.arc(0., 0., 1.005*rOuter, -pio12, pio12);
d3p.lineTo(0.995*rInner*cpio12, 0.995*rInner*spio12);
d3p.arc(0., 0., 0.995*rInner, pio12, -pio12, true);
d3p.closePath();
p.style("stroke", "none")
.style("fill", "#bdf")
.attr("d", d3p);
});
let rcen = 0.5*(rOuter + rInner);
appendText(g, 20, "#94c6ff", false, rcen, 0, "evening")
.attr("dy", "0.35em")
.attr("transform", "rotate(-12)")
.clone(true)
.attr("x", -rcen)
.text("morning")
.attr("transform", "rotate(192)");
});
this.daySky.attr("transform", "rotate(0)"); // degrees clockwise :(
this.svg.append("g").call(
g => {
// grid tick marks and labels for night sky ring (and atop daySky!)
let rTick = 0.97 * rInner;
let rText = 0.90 * rInner;
let ticks = [0, 30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330]
.map(t => [Math.cos(t*Math.PI/180.), -Math.sin(t*Math.PI/180.), t]);
g.selectAll("g")
.data(ticks)
.join("g")
.call(g => g.append("line")
.style("stroke", "#555")
.style("stroke-width", 2)
.attr("x1", d => rTick*d[0])
.attr("y1", d => rTick*d[1])
.attr("x2", d => rOuter*d[0])
.attr("y2", d => rOuter*d[1]))
.call(g => appendText(
g, 0, "#000", false, d => rText*d[0], d => rText*d[1],
d => `${d[2]}°`).attr("dy", "0.35em"));
});
this.svg.append("g").call(
g => {
// circular grid lines at 0, +-5 degrees, +-9 degrees full scale
let rcen = 0.5 * (rInner + rOuter);
let dr5 = 0.5 * (rOuter - rInner) * (5. / 9.);
g.selectAll("g")
.data([[-5, rcen-dr5], [0, rcen], [5, rcen+dr5]])
.join("g")
.call(g => appendCircle(g, d => d[1], "#555", 2))
// first draw blodges to blot out grid lines underneath
.call(g => appendText(g, 0, "", false, 0, d => -d[1],
d => `${d[0]}°`)
.attr("dy", "0.35em")
.style("fill", "none")
.style("stroke", "#000")
.style("stroke-width", 6)
.clone(true)
.attr("y", d => d[1]))
// then put the text on top of blodges
.call(g => appendText(g, 0, "#fff", false, 0, d => -d[1],
d => `${d[0]}°`)
.attr("dy", "0.35em")
.clone(true)
.attr("y", d => d[1]));
});
// Otherwise callback will not have correct this when triggered.
let yearSetter = () => this.setYear();
let sunDragger = (event, d) => this.dragSun(event, d);
let handToggler = ["mercury", "venus", "mars", "jupiter", "saturn"].map(
p => (() => this.setHandVisibility(p)));
// Year indicator
this.centerGroup = this.svg.append("g").call(
g => {
g.append("rect").call(
r => buttonBox(r, -40, -0.50*rInner - 25.5, 80, 32, yearSetter));
this.yearText = g.append("text").call(
t => buttonText(t, 0, -0.50*rInner - 1,
dateOfDay(this.dayNow).getUTCFullYear(), 24,
yearSetter));
this.dateText = appendText(g, 20, "", false, 0, -0.5*rInner + 29,
this.getDateText(this.dayNow));
});
this.prevDayYear = [this.dayNow, dateOfDay(this.dayNow).getUTCFullYear()];
// Moon Button
this.moonButton = this.svg.append("g").attr("display", "none").call(
g => {
let moonToggler = () => this.toggleMoon();
// let xy0 = -0.5 * width;
let [x0, y0] = [0, -50]; // [xy0 + 78, xy0 + 60];
g.append("rect").call(
r => buttonBox(r, x0 - 68, y0 - 20, 136, 26, moonToggler));
this.moonText = g.append("text").call(
t => buttonText(t, x0, y0, "Show Moon", 20, moonToggler));
});
// Planet legend
this.planetHandVisibility = {
mercury: "hidden", venus: "hidden", mars: "hidden",
jupiter: "hidden", saturn: "hidden"};
this.planetColors = {mercury: "#f0f", venus: "#fff", mars: "#f00",
jupiter: "#0f0", saturn: "#ff0", earth: "#00f",
sun: "#fc0"};
this.svg.append("g").call(
g => {
let xdots = -30;
let ytop = 0.20 * rInner;
g.append("rect")
.attr("x", xdots - 10)
.attr("y", ytop - 20)
.attr("height", 130)
.attr("width", 20)
.attr("rx", 5)
.style("fill", "#000")
.style("stroke", "none");
appendCircle(g, 8, this.planetColors.sun, 0, xdots, ytop - 5);
appendText(g, 14, "", false, xdots + 15, ytop, "Sun")
.attr("text-anchor", "start");
["mercury", "venus", "mars", "jupiter", "saturn"].forEach(
(p, i) => {
let planet = p[0].toUpperCase() + p.substring(1);
appendCircle(g, 4, "#0000", 12, xdots, ytop + 15 + 20*i)
.attr("fill", this.planetColors[p])
.style("cursor", "pointer")
.on("click", handToggler[i]);
appendText(g, 14, "", true, xdots + 15, ytop + 20 + 20*i, planet)
.attr("text-anchor", "start")
.on("click", handToggler[i]);
});
appendText(g, 14, "", false, 0, 20, "Earth");
});
// Month dial
function addMonthDial(svg, months) {
// months clock dial ring background
svg.append("g").call(
g => {
appendCircle(g, 0.75*rInner, "#f8f8f8", 0.12*rInner);
appendCircle(g, 0.69*rInner, "#000", 2);
appendCircle(g, 0.81*rInner, "#000", 2);
});
// month labels and radial separators
return svg.append("g").call(
g => g.selectAll("g")
.data(months)
.join("g")
.call(g => g.append("line")
.attr("stroke", "#000")
.attr("stroke-width", 2)
.attr("x1", d => 0.69*rInner*d[0][0])
.attr("y1", d => 0.69*rInner*d[0][1])
.attr("x2", d => 0.81*rInner*d[0][0])
.attr("y2", d => 0.81*rInner*d[0][1]))
.call(g => appendText(g, 0, "#000", false,
d => 0.75*rInner*d[1][0],
d => 0.75*rInner*d[1][1],
d => d[2]).attr("dy", "0.35em")));
}
// Sun position and clock hand
function addSunHand(svg, color) {
return svg.append("g").call(
g => {
g.append("line")
.style("pointer-events", "none")
.attr("stroke", color)
.attr("stroke-width", 3)
.attr("x1", 0.).attr("y1", 0.)
.attr("x2", rOuter).attr("y2", 0.)
.clone(true)
.attr("opacity", 0.4)
.attr("x1", -rOuter).attr("y1", 0.)
.attr("x2", -0.81*rInner).attr("y2", 0.)
.clone(true)
.attr("x1", -0.69*rInner).attr("y1", 0.)
.attr("x2", 0.).attr("y2", 0.);
appendCircle(g, 8, color, 0, 0.5*(rInner+rOuter), 0);
g.append("rect")
.style("pointer-events", "all")
.style("cursor", "pointer")
.style("fill", "none")
.style("stroke", "none")
.attr("x", rInner)
.attr("y", -(rOuter-rInner)/4)
.attr("height", (rOuter-rInner)/2)
.attr("width", rOuter-rInner);
g.attr("transform", "rotate(0)") // degrees clockwise
.call(d3.drag().on("drag", sunDragger))
.on("touchmove", sunDragger);
});
}
// Optional Moon marker
this.moonGroup = this.svg.append("g");
this.moonMarker = null;
// Planet positions
this.planetMarkers = new Array(5);
this.planetHands = new Array(5);
this.epiMarkers = new Array(3);
this.epiHands = new Array(3);
let planetGroup = this.svg.append("g");
let rcen = 0.5*(rInner + rOuter);
let dr = 0.5*(rOuter - rInner);
["mercury", "venus", "mars", "jupiter", "saturn"].forEach(
(p, i) => {
let [xp, yp, lat] = directionOf(p, this.dayNow);
let r = rcen + dr * lat * 20./Math.PI;
this.planetMarkers[i] = appendCircle(
planetGroup, 4, this.planetColors[p], 0, r*xp, -r*yp)
.style("pointer-events", "none");
this.planetHands[i] = planetGroup.append("line")
.style("pointer-events", "none")
.attr("visibility", this.planetHandVisibility[p])
.attr("stroke", this.planetColors[p])
.attr("stroke-width", 3)
.attr("x1", 0.)
.attr("y1", 0.)
.attr("x2", r*xp)
.attr("y2", -r*yp);
if (i > 1) {
this.epiMarkers[i-2] = this.planetMarkers[i].clone(true)
.attr("visibility", "hidden")
.attr("opacity", 0.4);
this.epiHands[i-2] = this.planetHands[i].clone(true)
.attr("visibility", "hidden")
.attr("opacity", 0.4);
}
});
// Put month dial on top of planets hands, below sun hand.
this.monthSel = addMonthDial(this.svg, this.months);
this.sunHand = addSunHand(this.svg, this.planetColors.sun);
appendCircle(this.svg, 4, this.planetColors.earth); // earth at center
// Animation controls
this.speeds = [0.6, 1.4, 3];
let arrowr = d3.path();
arrowr.moveTo(-10, rOuter + 20);
arrowr.lineTo(-10, rOuter + 80);
arrowr.lineTo(20, rOuter + 50);
arrowr.closePath();
let arrowl = d3.path();
arrowl.moveTo(10, rOuter + 20);
arrowl.lineTo(10, rOuter + 80);
arrowl.lineTo(-20, rOuter + 50);
arrowl.closePath();
this.svg.append("path")
.style("cursor", "pointer")
.attr("fill", "#fdf8e0")
.attr("stroke", "#000")
.attr("stroke-width", 2)
.attr("d", arrowr)
.attr("transform", "rotate(-35)")
.on("mousedown touchstart", (event, d) => this.startAnimation(false, 0))
.clone(true)
.attr("transform", "rotate(-45)")
.on("mousedown touchstart", (event, d) => this.startAnimation(false, -1))
.clone(true)
.attr("transform", "rotate(-55)")
.on("mousedown touchstart", (event, d) => this.startAnimation(false, -2))
.clone(true)
.attr("d", arrowl)
.attr("transform", "rotate(35)")
.on("mousedown touchstart", (event, d) => this.startAnimation(true, 0))
.clone(true)
.attr("transform", "rotate(45)")
.on("mousedown touchstart", (event, d) => this.startAnimation(true, -1))
.clone(true)
.attr("transform", "rotate(55)")
.on("mousedown touchstart", (event, d) => this.startAnimation(true, -2));
this.svg.on("mouseup mouseleave touchend",
(event, d) => this.stopAnimation());
}
turnOnMoon() {
if (this.moonMarker == null) {
this.moonMarker = appendCircle(this.moonGroup, 6, "#fff")
.attr("style", "pointer-events: none;");
this.speeds = [0.1, 0.3, 1];
this.updateMoon();
}
}
turnOffMoon() {
if (this.moonMarker != null) {
this.moonMarker.remove();
this.moonMarker = null;
this.speeds = [0.6, 1.4, 3];
}
}
toggleMoon() {
if (this.disabled || this.elapsed) return;
if (this.moonMarker == null) {
this.turnOnMoon();
this.moonText.text("Hide Moon");
} else {
this.turnOffMoon();
this.moonText.text("Show Moon");
}
}
hasZodiac(yes) {
if (yes) {
this.zodiac.attr("display", null);
} else {
this.zodiac.attr("display", "none");
}
}
hasMoonButton(yes) {
if (yes) {
this.moonButton.attr("display", null);
} else {
this.moonButton.attr("display", "none");
}
this.turnOffMoon();
}
updateMoon() {
if (this.moonMarker == null) {
return;
}
let [rInner, rOuter] = [PlanetClock.#rInner, PlanetClock.#rOuter];
let rcen = 0.5*(rInner + rOuter);
let dr = 0.5*(rOuter - rInner);
let [xp, yp, lat] = ssSchlyter.moon(this.dayNow);
let r = rcen + dr * lat * 20./Math.PI;
this.moonMarker.attr("cx", r*xp).attr("cy", -r*yp);
}
dragSun(event, d) {
if (this.disabled) return;
let [x, y] = [event.x+1.e-20, event.y];
let theta = Math.atan2(y, x) * 180. / Math.PI
this.sunHand.attr("transform", `rotate(${theta})`);
this.daySky.attr("transform", `rotate(${theta})`);
this.dayNow = timeSunAt(x, -y, this.dayNow); // update current day
this.updatePlanets();
this.updateMoon();
this.updateYear();
this.updateElapsed(false);
this.dateText.text(this.getDateText(this.dayNow));
}
goToDay(day) {
let [x, y] = directionOf("sun", day);
let theta = Math.atan2(-y, x) * 180. / Math.PI
this.sunHand.attr("transform", `rotate(${theta})`);
this.daySky.attr("transform", `rotate(${theta})`);
this.dayNow = day; // update current day
this.updatePlanets();
this.updateMoon();
this.updateYear();
this.updateElapsed(false);
this.dateText.text(this.getDateText(this.dayNow));
}
animateTo(day, step=3) { // 3 is slow, 6 fast, 12 very fast
this.stopAnimation();
day = parseFloat(day);
if (isNaN(day)) {
return;
}
step = parseFloat(step);
if (isNaN(step) || step <= 0) {
return;
}
this.dayStep = step;
this.dayStop = day;
// set timer makes callbacks at 60 frames/sec (use d3.interval for slower)
this.dayTimer = d3.timer(() => this.stepDay());
}
startAnimation(backward, step=3) {
if (this.disabled) return;
if (step <= 0) {
step = this.speeds[-step];
}
this.animateTo(this.dayNow + (backward? -1.0e7 : 1.0e7), step);
}
stopAnimation() {
if (this.dayTimer) {
this.dayTimer.stop();
delete this.dayTimer;
}
}
stepDay() {
let day = this.dayNow;
let nextDay;
if (day <= this.dayStop) {
nextDay = day + this.dayStep;
if (nextDay > this.dayStop) {
this.dayTimer.stop();
delete this.dayTimer;
nextDay = this.dayStop;
}
} else {
nextDay = day - this.dayStep;
if (nextDay < this.dayStop) {
this.dayTimer.stop();
delete this.dayTimer;
nextDay = this.dayStop;
}
}
this.goToDay(nextDay);
}
getDateText(day) {
let date = dateOfDay(day - 0.5); // month ring set to UTC noon Jan 1
let month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"][date.getUTCMonth()];
return `${month} ${(" "+date.getUTCDate()).slice(2)}`;
}
setYear() {
if (this.disabled) return;
let dateNow = dateOfDay(this.dayNow);
let yearNow = dateNow.getUTCFullYear();
let year = parseInt(prompt("Jump to Year:", yearNow.toString()));
if (!isNaN(year) && year != yearNow) {
if (year > 3000) {
year = 3000;
} else if (year < -3000) {
year = -3000;
}
dateNow.setUTCFullYear(year);
let newDay = dayOfDate(dateNow);
let [xp, yp] = directionOf("sun", this.dayNow);
let theta = Math.atan2(-yp, xp) * 180./Math.PI;
this.dayNow = timeSunAt(xp, yp, newDay); // update current day
this.sunHand.attr("transform", `rotate(${theta})`);
this.daySky.attr("transform", `rotate(${theta})`);
this.updatePlanets();
this.updateYear();
this.updateElapsed(true, true);
}
}
updateYear() {
let year = dateOfDay(this.dayNow).getUTCFullYear();
if (this.prevDayYear[1] === year) return;
this.yearText.text(year);
this.dateText.text(this.getDateText(this.dayNow));
this.prevDayYear[1] = year;
let change = (this.dayNow - this.prevDayYear[0]) / 365.25;
if (change < -10 || change > 10) {
// after ten years, update the tAxis for precession of equinoxes
this.updateMonths();
this.prevDayYear[0] = this.dayNow;
let rInner = PlanetClock.#rInner;
this.monthSel.selectAll("g").nodes().forEach((grp, i) => {
let [xy, xyc, name] = this.months[i];
let sel = d3.select(grp);
sel.select("text")
.attr("x", 0.75*rInner*xyc[0])
.attr("y", 0.75*rInner*xyc[1]);
sel.select("line")
.attr("x1", d => 0.69*rInner*xy[0])
.attr("y1", d => 0.69*rInner*xy[1])
.attr("x2", d => 0.81*rInner*xy[0])
.attr("y2", d => 0.81*rInner*xy[1]);
});
}
}
updateMonths() {
let jan1 = new Date("Jan 1 2000 12:00 GMT"); // J2000 time origin
jan1.setUTCFullYear(dateOfDay(this.dayNow).getUTCFullYear());
jan1 = dayOfDate(jan1);
let xyl = this.tMonth.map(d => directionOf("sun", jan1+d));
let lon = xyl.map(x => Math.atan2(x[1], x[0]) * 180./Math.PI);
let moxy = xyl.map(([x, y], i, a) => (i<a.length-1)?
[0.5*(x+a[i+1][0]), 0.5*(y+a[i+1][1])] : [0, 1]);
this.months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"].map(
(name, i) => {
let [x0, y0] = xyl[i]; // already a unit vector
let [xm, ym] = moxy[i]; // need to normalize this
let rm = Math.sqrt(xm*xm + ym*ym);
[xm, ym] = [xm/rm, ym/rm];
// Both y0 and ym are in ecliptic coordinates,
// which have opposite sign from the SVG y-direction.
return [[x0, -y0], [xm, -ym], name];
});
}
updatePlanets() {
let rcen = 0.5*(PlanetClock.#rInner + PlanetClock.#rOuter);
let dr = 0.5*(PlanetClock.#rOuter - PlanetClock.#rInner);
["mercury", "venus", "mars", "jupiter", "saturn"].forEach(
(p, i) => {
let [xp, yp, lat] = directionOf(p, this.dayNow);
let r = rcen + dr * lat * 20./Math.PI;
this.planetMarkers[i].attr("cx", r*xp).attr("cy", -r*yp)
this.planetHands[i].attr("x2", r*xp).attr("y2", -r*yp);
if (this.showEpiMarkers) {
["mars", "jupiter", "saturn"].forEach(
(p, i) => {
if (this.planetHandVisibility[p] == "hidden") return;
let [xp, yp, zp] = positionOf(p, this.dayNow);
let rp = Math.sqrt(xp**2 + yp**2);
let lat = Math.atan(zp / rp);
let r = rcen + dr * lat * 20./Math.PI;
[xp, yp] = [xp/rp, yp/rp];
this.epiMarkers[i].attr("cx", r*xp).attr("cy", -r*yp)
this.epiHands[i].attr("x2", r*xp).attr("y2", -r*yp);
});
}
});
this.slaves.forEach(s => s(this));
}
setHandVisibility(planet, on) {
let planets = ["mercury", "venus", "mars", "jupiter", "saturn"];
let i = planets.indexOf(planet);
if (i < 0) {
return;
}
if (typeof on == "undefined") { // toggle visibility
on = (this.planetHandVisibility[planet] === "hidden");
}
let visibility = on? "visible" : "hidden";
this.planetHandVisibility[planet] = visibility;
this.planetHands[i].attr("visibility", visibility);
if (this.showEpiMarkers) {
this.updatePlanets();
["mars", "jupiter", "saturn"].forEach(
(p, i) => {
const v = this.planetHandVisibility[p];
this.epiMarkers[i].attr("visibility", v);
this.epiHands[i].attr("visibility", v);
});
}
this.slaves.forEach(s => s(this));
}
addSlave(callback) {
this.slaves.push(callback);
callback(this);
}
removeSlave(callback) {
const i = this.slaves.index(callback);
if (i > -1) {
this.slaves.splice(i, 1);
}
}
slaves = [];
addElapsed(updateCallback) {
if (this.elapsed) {
this.removeElapsed(true);
}
this.hasMoonButton(false);
let yElapsed = -0.25*PlanetClock.#rInner;
let resetElapsed = () => this.updateElapsed(true);
if (this.elapsed0 === undefined) {
this.elapsed0 = this.dayNow;
} else if (this.elapsed0 != this.dayNow) {
this.goToDay(this.elapsed0);
}
this.elapsed = this.centerGroup.append("g").call(
g => {
appendText(g, 20, "", false, 0, yElapsed,
`${(this.dayNow - this.elapsed0).toFixed(2)} days`);
g.append("g").call(
gg => {
let date = dateOfDay(this.elapsed0);
let ymd = `${date.getUTCFullYear()} `;
ymd += `${this.getDateText(this.elapsed0)} `;
ymd += `${("0"+date.getUTCHours()).slice(-2)}`;
ymd += `:${("0"+date.getUTCMinutes()).slice(-2)}`;
appendText(gg, 20, "", false, 115-40, yElapsed + 29, "from " + ymd)
.attr("text-anchor", "end");
gg.append("rect").call(
rect => buttonBox(rect, 115-35, yElapsed + 8, 70, 28,
resetElapsed));
gg.append("text").call(
t => buttonText(t, 115, yElapsed + 29, "Reset", 20,
resetElapsed));
});
});
if (updateCallback) {
this.elapsedUpdater = updateCallback;
}
}
removeElapsed(fromAdd=false) {
if (this.elapsed) {
let day = this.elapsed0;
this.elapsed.remove();
delete this.elapsed;
delete this.elapsedUpdater;
if (!fromAdd && day !== undefined) {
this.goToDay(day);
}
}
}
updateElapsed(reset, fromSetYear=false) {
if (this.elapsed) {
if (reset) {
if (this.disabled) return;
this.elapsed0 = this.dayNow;
let date = dateOfDay(this.elapsed0);
let ymd = `${date.getUTCFullYear()} `;
ymd += `${this.getDateText(this.elapsed0)} `;
ymd += `${("0"+date.getUTCHours()).slice(-2)}`;
ymd += `:${("0"+date.getUTCMinutes()).slice(-2)}`;
this.elapsed.select("g").select("text").text("from " + ymd);
}
this.elapsed.select("text").text(
`${(this.dayNow - this.elapsed0).toFixed(2)} days`);
if (this.elapsedUpdater) {
this.elapsedUpdater(reset, fromSetYear);
}
}
}
epicycleMarkers(on) {
if (!on) {
this.showEpiMarkers = false;
["mars", "jupiter", "saturn"].forEach(
(p, i) => {
this.epiMarkers[i].attr("visibility", "hidden");
this.epiHands[i].attr("visibility", "hidden");
});
} else {
this.showEpiMarkers = true;
this.updatePlanets();
["mars", "jupiter", "saturn"].forEach(
(p, i) => {
const v = this.planetHandVisibility[p];
this.epiMarkers[i].attr("visibility", v);
this.epiHands[i].attr("visibility", v);
});
}
}
}
class OrbitView {
static #width = 750;
static #height = OrbitView.#width;
constructor(d3Parent, clock) {
let [width, height] = [OrbitView.#width, OrbitView.#height];
this.svg = d3Parent.append("svg")
.attr("xmlns", "http://www.w3.org/2000/svg")
.attr("xmlns:xlink", "http://www.w3.org/1999/xlink")
.attr("class", "OrbitView")
.attr("viewBox", [-width/2, -height/2, width, height])
.style("display", "block")
.style("margin", "20px") // padding does not work for SVG?
.style("background-color", "#aaa")
.attr("text-anchor", "middle")
.attr("font-family", "'Merriweather Sans', sans-serif")
.attr("font-weight", "bold")
.attr("font-size", 12)
.attr("stroke-linejoin", "round")
.attr("stroke-linecap", "round");
this.clock = clock;
this.updateOrigin = () => this.heliocentric();
// aphelions: Mars 1.6660 au, Jupiter 5.4570 au, Saturn 10.1238 au
// zoom factors are a bit more than twice these (plus 1 au for geocentric)
this.zoomFactor = [3.6, 5.5, 14, 23];
this.zoomFactor = this.zoomFactor.map(s => 0.01*width/s);
this.zoomLevel = 0;
let scale = this.zoomFactor[this.zoomLevel];
zoomButtons(width, this, this.svg);
let gap = 0.01*width; // matches gap in zoomButtons
let originCycler = () => this.cycleOrigin();
this.svg.append("rect").call(
rect => buttonBox(rect, width/2 - 150 - gap, -height/2 + gap, 150, 28,
originCycler));
this.originText = this.svg.append("text").call(
t => buttonText(t, width/2 - 82, -height/2 + gap + 20, "heliocentric", 20,
originCycler));
this.currentOrigin = "heliocentric";
// Crosshairs
this.svg.append("line")
.style("pointer-events", "none")
.attr("stroke", "#888").attr("stroke-width", 1)
.attr("x1", -width/2).attr("y1", 0).attr("x2", width/2).attr("y2", 0)
.clone(true)
.attr("x1", 0).attr("y1", -height/2).attr("x2", 0).attr("y2", height/2)
/* Warning:
All paths and (x, y) coordinates are multiplied by 100 here to
avoid bizarre huge pixellation caused by translate() transform
in the geocentric view. While dragging the sun around, the
OrbitView displays the blurred pixelated drawing, but when you
stop and click on the OrbitView SVG, it redraws as expected.
The effect is worse at high magnification, which suggested the
coordinate scaling might be a solution - some renderer appears
to be dropping the non-integer part of coordinate values.
*/
// Planet positions
this.planetMarkers = new Array(7);
this.planetHands = new Array(6);
this.planetOrbits = new Array(6);
this.planetHands = new Array(6);
this.planetRadii = new Array(5);
// Note that translate() happens before scale()
this.planetGroup = this.svg.append("g")
.style("pointer-events", "none")
.attr("transform", `scale(${scale}) translate(0, 0)`);
this.getOrbit = (p, i, t0) => {
// Periods come from orbitParams near year 2000.
const period = [87.969, 224.701, 686.980, 4332.817,
10755.884, 365.25637]; // J2000 sidereal years (days)
let d3p = d3.path();
let dt = period[i] * 0.01;
let t = t0;
let [x, y] = positionOf(p, t);
d3p.moveTo(100*x, -100*y);
for (let j = 1 ; j < 100 ; j += 1) {
t += dt;
[x, y] = positionOf(p, t);
d3p.lineTo(100*x, -100*y);
}
d3p.closePath()
if (i == 0) this.orbitalEpoch = t0;
return d3p;
}
["mercury", "venus", "mars", "jupiter", "saturn", "earth"].forEach(
(p, i) => {
this.planetOrbits[i] = this.planetGroup.append("path")
.style("stroke", clock.planetColors[p])
.style("stroke-width", 5/scale)
.style("fill", "none")
.attr("opacity", 0.2)
.attr("d", this.getOrbit(p, i, this.clock.dayNow));
if (i < 5) {
this.planetRadii[i] = this.planetGroup.append("line")
.attr("opacity", 0.2)
.attr("stroke", clock.planetColors[p])
.attr("stroke-width", 5/scale)
.attr("x1", 0).attr("y1", 0);
}
}
);
this.planetOrbits[5]
.attr("id", "orbit-view-sun")
.attr("transform", "rotate(0)");
this.epicycleCircles = this.planetGroup.append("g");
let [xe, ye] = positionOf("earth", clock.dayNow);
["mercury", "venus", "mars", "jupiter", "saturn"].forEach(
(p, i) => {
let [x, y] = positionOf(p, clock.dayNow);
this.planetMarkers[i] = appendCircle(
this.planetGroup, 4/scale, clock.planetColors[p], 0, 100*x, -100*y);
this.planetHands[i] = this.planetGroup.append("line")
.attr("visibility", clock.planetHandVisibility[p])
.attr("stroke", clock.planetColors[p])
.attr("stroke-width", 3/scale)
.attr("x1", 100*xe).attr("y1", -100*ye)
.attr("x2", 100*x).attr("y2", -100*y);
this.planetRadii[i].attr("x2", 100*x).attr("y2", -100*y);
});
this.planetHands[5] = this.planetGroup.append("line") // Earth-Sun line
.attr("stroke", clock.planetColors.sun)
.attr("stroke-width", 3/scale)
.attr("x1", 0).attr("y1", 0)
.attr("x2", 100*xe).attr("y2", -100*ye);
this.planetMarkers[5] = appendCircle( // Earth
this.planetGroup, 4/scale, clock.planetColors.earth, 0, 100*xe, -100*ye);
this.planetMarkers[6] = appendCircle( // Sun
this.planetGroup, 8/scale, clock.planetColors.sun, 0, 0, 0);
this.clock.addSlave(() => this.update());
}
update() {
if (this.svg.node().parentElement.style.display == "none") return;
this.updateOrigin();
let t0 = this.clock.dayNow;
let newEpoch = Math.abs(t0 - this.orbitalEpoch) > 200*365.256355;
let [xe, ye] = positionOf("earth", t0);
["mercury", "venus", "mars", "jupiter", "saturn"].forEach(
(p, i) => {
let [x, y] = positionOf(p, t0);
if (newEpoch) {
this.planetOrbits[i].attr("d", this.getOrbit(p, i, t0));
}
this.planetMarkers[i].attr("cx", 100*x).attr("cy", -100*y);
this.planetHands[i]
.attr("visibility", this.clock.planetHandVisibility[p])
.attr("x1", 100*xe).attr("y1", -100*ye)
.attr("x2", 100*x).attr("y2", -100*y);
this.planetRadii[i].attr("x2", 100*x).attr("y2", -100*y);
});
this.planetHands[5].attr("x2", 100*xe).attr("y2", -100*ye);
this.planetMarkers[5].attr("cx", 100*xe).attr("cy", -100*ye);
}
setOrigin(sys) {
if (sys == "heliocentric") {
this.clock.epicycleMarkers(false);
this.updateOrigin = () => this.heliocentric();
let scale = this.zoomFactor[this.zoomLevel];
this.planetGroup.attr("transform", `scale(${scale})`);
this.planetOrbits[5].attr("transform", "rotate(0)");
this.planetOrbits[5].style("stroke", this.clock.planetColors.earth);
[2, 3, 4].forEach(i => {
this.planetOrbits[i].attr("transform", null);
this.planetRadii[i].attr("transform", null);
});
this.epicycleCircles.selectAll("*").remove();
} else if (sys == "geocentric") {
this.clock.epicycleMarkers(false);
this.updateOrigin = () => this.geocentric();
this.planetOrbits[5].style("stroke", this.clock.planetColors.sun);
} else if (sys == "epicycles") {
this.clock.epicycleMarkers(true);
this.updateOrigin = () => this.epicycles();
this.planetOrbits[5].style("stroke", this.clock.planetColors.sun);
["mars", "jupiter", "saturn"].forEach(
p => this.epicycleCircles
.append(() => this.planetHands[5].clone(true).node())
.attr("stroke", this.clock.planetColors.sun)
.attr("opacity", 0.2));
this.epicycleCircles.selectAll("path")
.data([2, 3, 4])
.join("path")
.attr("fill", "none")
.attr("stroke", this.clock.planetColors.sun)
.attr("opacity", 0.2)
.attr("d", this.planetOrbits[5].attr("d"));
}
this.update();
}
cycleOrigin() {
if (this.currentOrigin == "heliocentric") {
this.currentOrigin = "geocentric";
this.originText.text("geocentric");
} else if (this.currentOrigin == "geocentric") {
this.currentOrigin = "epicycles";
this.originText.text("epicycles");
} else if (this.currentOrigin == "epicycles") {
this.currentOrigin = "heliocentric";
this.originText.text("heliocentric");
}
this.setOrigin(this.currentOrigin);
}
activate(on) {
if (on) this.clock.removeElapsed();
}
zoomer(inout) {
let znow = this.zoomLevel;
if (inout == 0) {
if (znow > 2) return;
znow += 1;
} else {
if (znow < 1) return;
znow -= 1;
}
this.zoomLevel = znow;
let scale = this.zoomFactor[znow];
this.planetOrbits.forEach(
orbit => orbit.style("stroke-width", 5/scale));
this.planetRadii.forEach(
orbit => orbit.style("stroke-width", 5/scale));
this.planetHands.forEach(
hand => hand.attr("stroke-width", 3/scale));
this.planetMarkers.slice(0,6).forEach(
hand => hand.attr("r", 4/scale));
this.planetMarkers[6].attr("r", 8/scale);
if (this.updateOrigin()) {
this.planetGroup