-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
894 lines (750 loc) · 26.9 KB
/
script.js
File metadata and controls
894 lines (750 loc) · 26.9 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
/*
THE~GRID MANIFESTATION~STATION
Copyright (c) 2024
Licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
See LICENSE file for details
*/
// =============================================================================
// CONFIGURATION CONSTANTS
// =============================================================================
const GRID_CONFIG = {
altitude: 0.05,
latDivisions: 12,
lngDivisions: 24,
tolerance: 0.1,
};
const VISUAL_CONFIG = {
pointColor: "#F8ED43",
pointRadius: 0.2,
arcStroke: 0.1,
arcDashLength: 0.05, // Length of dashed segments
arcDashGap: 0.02, // Spacing between segments
backgroundColor: "#A1A39A",
atmosphereColor: "#F8ED43",
atmosphereAltitude: 0.5,
};
// Configuration for user geolocation
const USER_LOCATION_CONFIG = {
color: "#F8ED43", // Yellow
radius: 0.8,
altitude: 0.05,
};
// Configuration for other online users (using particle system)
const OTHER_USERS_CONFIG = {
color: "#F8ED43", // Yellow
size: 1, // Size for particle system
altitude: 0.025,
numberOfUsers: 10000,
};
// Configuration for zoom levels and breathing
const ZOOM_CONFIG = {
initialDistance: 400, // Initial camera distance
minDistance: 200, // Minimum zoom (closer)
maxDistance: 1000, // Maximum zoom (further)
breathingAmplitude: 0.5, // Breathing animation amplitude (80% variation)
transitionDuration: 1000, // Transition duration between zoom levels (ms)
// Pre-breathing countdown configuration
preBreathingCountdown: {
stepDuration: 2000, // 2 seconds per step (in milliseconds)
steps: [
{ number: "3", text: "Sit in a comfortable position" },
{ number: "2", text: "Try to be not disturbed" },
{ number: "1", text: "And breathe" },
],
},
// Breathing timing in seconds
breathingTiming: {
inspire: 4, // Inspiration in seconds
pause: 2, // Pause/retention in seconds
expire: 6, // Expiration in seconds
},
pauseMicroAmplitude: 0.005, // Mini amplitude for pause animation (2% variation)
};
// =============================================================================
// CORE CLASSES
// =============================================================================
class PopulatedUsersGenerator {
constructor(config = OTHER_USERS_CONFIG) {
this.config = config;
this.populatedAreas = null;
}
async loadPopulatedAreas() {
try {
const response = await fetch("./data/populated_areas.geojson");
const data = await response.json();
this.populatedAreas = data.features;
console.log(`🌍 ${this.populatedAreas.length} populated areas loaded`);
} catch (error) {
console.error("Error loading populated areas:", error);
// Fallback to random generation
this.populatedAreas = null;
}
}
async generate() {
// Load populated areas if not already done
if (!this.populatedAreas) {
await this.loadPopulatedAreas();
}
const users = [];
// If data couldn't be loaded, use random method
if (!this.populatedAreas) {
return this.generateRandomUsers();
}
// Generate users in populated areas according to their weight
for (let i = 0; i < this.config.numberOfUsers; i++) {
const coordinates = this.generateCoordinatesInPopulatedArea();
users.push({
lat: coordinates.lat,
lng: coordinates.lng,
altitude: this.config.altitude,
id: `populated_user_${i}`,
});
}
console.log(
`👥 ${users.length} simulated users generated in populated areas`
);
return users;
}
generateCoordinatesInPopulatedArea() {
// Select an area according to its population weight
const area = this.selectWeightedArea();
// Generate a random point in this area, avoiding borders
return this.generatePointInPolygonCenter(area.geometry.coordinates[0]);
}
selectWeightedArea() {
// Create array with repetition according to weight
const weightedAreas = [];
this.populatedAreas.forEach((area) => {
const weight = Math.round(area.properties.weight * 100);
for (let i = 0; i < weight; i++) {
weightedAreas.push(area);
}
});
// Weighted random selection
return weightedAreas[Math.floor(Math.random() * weightedAreas.length)];
}
generatePointInPolygonCenter(coordinates) {
// Find the geographic center of the polygon
const lats = coordinates.map((coord) => coord[1]);
const lngs = coordinates.map((coord) => coord[0]);
const centerLat = lats.reduce((sum, lat) => sum + lat, 0) / lats.length;
const centerLng = lngs.reduce((sum, lng) => sum + lng, 0) / lngs.length;
// Calculate area size to determine maximum radius
const latRange = Math.max(...lats) - Math.min(...lats);
const lngRange = Math.max(...lngs) - Math.min(...lngs);
const maxRadius = Math.min(latRange, lngRange) * 0.4; // 40% of area size
// Generate point with radial distribution from center
const { lat, lng } = this.generateRadialPoint(
centerLat,
centerLng,
maxRadius
);
return { lat, lng };
}
// Gaussian distribution to concentrate points towards area centers
gaussianRandom(min, max, concentration = 0.3) {
const center = (min + max) / 2;
const range = max - min;
// Box-Muller transform for gaussian distribution
const u1 = Math.random();
const u2 = Math.random();
const gaussian = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
// Apply concentration and limits
const value = center + gaussian * range * concentration;
return Math.max(min, Math.min(max, value));
}
// New method for radial distribution from a center
generateRadialPoint(centerLat, centerLng, maxRadius) {
// Mix of radial distribution and random noise for more natural look
const useRadial = Math.random() < 0.7; // 70% radial, 30% random
if (useRadial) {
// Radial distribution with angle variation
const baseAngle = Math.random() * 2 * Math.PI;
const angleVariation = (Math.random() - 0.5) * Math.PI * 0.3; // ±27° variation
const angle = baseAngle + angleVariation;
// Radius with more variation and less strict concentration
const radiusRandom1 = Math.random();
const radiusRandom2 = Math.random();
// Average of two random values for smoother distribution
const normalizedRadius = (radiusRandom1 + radiusRandom2) / 2;
const radiusVariation = 1 + (Math.random() - 0.5) * 0.4; // ±20% variation
const radius = normalizedRadius * maxRadius * radiusVariation;
// Convert to coordinates with additional noise
const deltaLat =
radius * Math.cos(angle) + (Math.random() - 0.5) * maxRadius * 0.1;
const deltaLng =
radius * Math.sin(angle) + (Math.random() - 0.5) * maxRadius * 0.1;
// Adjustment for spherical projection
const correctedDeltaLng =
deltaLng / Math.cos((centerLat * Math.PI) / 180);
return {
lat: centerLat + deltaLat,
lng: centerLng + correctedDeltaLng,
};
} else {
// Completely random distribution in a square around center
const randomLat = centerLat + (Math.random() - 0.5) * maxRadius * 2;
const randomLng = centerLng + (Math.random() - 0.5) * maxRadius * 2;
return {
lat: randomLat,
lng: randomLng,
};
}
}
// New method for gaussian distribution around a central point
gaussianRandomAroundPoint(center, diffusionRadius) {
// Box-Muller transform for gaussian distribution
const u1 = Math.random();
const u2 = Math.random();
const gaussian = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
// Apply very concentrated diffusion around center to avoid borders
const offset = gaussian * diffusionRadius * 0.5; // High concentration (0.5 instead of 0.3)
return center + offset;
}
// Fallback method if geographic data fails to load
generateRandomUsers() {
const users = [];
for (let i = 0; i < this.config.numberOfUsers; i++) {
const lat = Math.asin(2 * Math.random() - 1) * (180 / Math.PI);
const lng = (Math.random() - 0.5) * 360;
users.push({
lat,
lng,
altitude: this.config.altitude,
id: `random_user_${i}`,
});
}
console.log(
`👥 ${users.length} simulated users generated randomly (fallback)`
);
return users;
}
}
class TriangularGridGenerator {
constructor(config = GRID_CONFIG) {
this.config = config;
this.points = [];
this.arcs = [];
}
generate() {
this.createPoles();
this.createGridPoints();
this.createLatitudeLines();
this.createMeridians();
this.createDiagonals();
return {
points: this.points,
arcs: this.arcs,
};
}
createPoles() {
this.points.push(
{
lat: 90,
lng: 0,
id: "north_pole",
altitude: this.config.altitude,
},
{
lat: -90,
lng: 0,
id: "south_pole",
altitude: this.config.altitude,
}
);
}
createGridPoints() {
for (let latStep = 1; latStep < this.config.latDivisions; latStep++) {
const lat = -90 + (latStep * 180) / this.config.latDivisions;
for (let lngStep = 0; lngStep < this.config.lngDivisions; lngStep++) {
const lng = -180 + (lngStep * 360) / this.config.lngDivisions;
this.points.push({
lat,
lng,
id: `${latStep}_${lngStep}`,
altitude: this.config.altitude,
});
}
}
}
createLatitudeLines() {
for (let latStep = 1; latStep < this.config.latDivisions; latStep++) {
const lat = -90 + (latStep * 180) / this.config.latDivisions;
for (let lngStep = 0; lngStep < this.config.lngDivisions; lngStep++) {
const lng1 = -180 + (lngStep * 360) / this.config.lngDivisions;
const lng2 =
-180 +
(((lngStep + 1) % this.config.lngDivisions) * 360) /
this.config.lngDivisions;
const p1 = this.findPoint(lat, lng1);
const p2 = this.findPoint(lat, lng2);
this.addArc(p1, p2);
}
}
}
createMeridians() {
for (let lngStep = 0; lngStep < this.config.lngDivisions; lngStep++) {
const lng = -180 + (lngStep * 360) / this.config.lngDivisions;
this.connectPoleToMeridian("north", lng);
this.connectMeridianPoints(lng);
this.connectPoleToMeridian("south", lng);
}
}
connectPoleToMeridian(pole, lng) {
const polePoint = this.points.find((p) => p.id === `${pole}_pole`);
if (pole === "north") {
const firstPoint = this.findPoint(
-90 + ((this.config.latDivisions - 1) * 180) / this.config.latDivisions,
lng
);
this.addArc(polePoint, firstPoint);
} else {
const lastPoint = this.findPoint(
-90 + (1 * 180) / this.config.latDivisions,
lng
);
this.addArc(lastPoint, polePoint);
}
}
connectMeridianPoints(lng) {
for (let latStep = 1; latStep < this.config.latDivisions - 1; latStep++) {
const lat1 = -90 + (latStep * 180) / this.config.latDivisions;
const lat2 = -90 + ((latStep + 1) * 180) / this.config.latDivisions;
const p1 = this.findPoint(lat1, lng);
const p2 = this.findPoint(lat2, lng);
this.addArc(p1, p2);
}
}
createDiagonals() {
for (let latStep = 1; latStep < this.config.latDivisions - 1; latStep++) {
const lat1 = -90 + (latStep * 180) / this.config.latDivisions;
const lat2 = -90 + ((latStep + 1) * 180) / this.config.latDivisions;
for (let lngStep = 0; lngStep < this.config.lngDivisions; lngStep++) {
const lng1 = -180 + (lngStep * 360) / this.config.lngDivisions;
const lng2 =
-180 +
(((lngStep + 1) % this.config.lngDivisions) * 360) /
this.config.lngDivisions;
const p1 = this.findPoint(lat1, lng1);
const p2 = this.findPoint(lat2, lng2);
const p3 = this.findPoint(lat1, lng2);
const p4 = this.findPoint(lat2, lng1);
this.addArc(p1, p2);
this.addArc(p3, p4);
}
}
}
findPoint(lat, lng) {
return this.points.find(
(p) =>
Math.abs(p.lat - lat) < this.config.tolerance &&
Math.abs(p.lng - lng) < this.config.tolerance
);
}
addArc(p1, p2) {
if (p1 && p2) {
this.arcs.push({
startLat: p1.lat,
startLng: p1.lng,
endLat: p2.lat,
endLng: p2.lng,
altitude: this.config.altitude,
});
}
}
}
class UserLocationManager {
constructor() {
this.userLocation = null;
this.isLocationSupported = "geolocation" in navigator;
}
async getUserLocation() {
if (!this.isLocationSupported) {
console.warn("🌍 Geolocation not supported by this browser");
return null;
}
return new Promise((resolve, reject) => {
const options = {
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 300000, // 5 minutes
};
navigator.geolocation.getCurrentPosition(
(position) => {
const location = {
lat: position.coords.latitude,
lng: position.coords.longitude,
accuracy: position.coords.accuracy,
id: "user_location",
isUserLocation: true, // Flag to identify user position
};
this.userLocation = location;
console.log(
`🎯 User position found: ${location.lat.toFixed(
4
)}, ${location.lng.toFixed(4)} (accuracy: ${location.accuracy}m)`
);
resolve([location]);
},
(error) => {
let errorMessage = "";
switch (error.code) {
case error.PERMISSION_DENIED:
errorMessage = "Geolocation permission denied by user";
break;
case error.POSITION_UNAVAILABLE:
errorMessage = "Position information unavailable";
break;
case error.TIMEOUT:
errorMessage = "Geolocation timeout exceeded";
break;
default:
errorMessage = "Unknown geolocation error";
break;
}
console.warn(`🌍 ${errorMessage}`);
reject(error);
},
options
);
});
}
async initializeLocation(globe, gridData) {
try {
const userLocationData = await this.getUserLocation();
if (userLocationData && userLocationData.length > 0) {
// Combine only grid + current user (other users are particles)
const allPoints = [...gridData.points, ...userLocationData];
// Update globe with points (grid + user)
globe.pointsData(allPoints);
// Center view on user position
globe.pointOfView(
{
lat: userLocationData[0].lat,
lng: userLocationData[0].lng,
altitude: ZOOM_CONFIG.initialDistance / 100, // Convert distance to altitude for pointOfView
},
2000
);
return userLocationData;
}
} catch (error) {
console.error("Error initializing geolocation:", error);
}
return [];
}
}
// =============================================================================
// ANIMATION & INTERACTION SYSTEM
// =============================================================================
let globeInstance = null;
let isBreathingMode = false;
let breathingAnimationId = null;
let zoomTransitionId = null;
let originalCountdownContent = null;
let preBreathingCountdownId = null;
function easeInOutQuad(t) {
return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
}
function startPreBreathingCountdown(onComplete) {
if (preBreathingCountdownId) {
clearTimeout(preBreathingCountdownId);
}
const countdownSteps = ZOOM_CONFIG.preBreathingCountdown.steps;
const stepDuration = ZOOM_CONFIG.preBreathingCountdown.stepDuration;
let currentStep = 0;
// Get header elements
const h1Element = document.querySelector("h1");
const h2Element = document.querySelector("h2");
// Save original content
let originalH1Content = null;
let originalH2Content = null;
if (h1Element && originalH1Content === null) {
originalH1Content = h1Element.textContent;
}
if (h2Element && originalH2Content === null) {
originalH2Content = h2Element.textContent;
}
function showNextStep() {
if (currentStep >= countdownSteps.length) {
// Countdown finished, start breathing animation
if (onComplete) onComplete();
return;
}
const step = countdownSteps[currentStep];
// Update header elements with countdown content
if (h1Element) {
h1Element.textContent = step.number;
}
if (h2Element) {
h2Element.textContent = step.text;
}
currentStep++;
preBreathingCountdownId = setTimeout(showNextStep, stepDuration);
}
// Store original content for restoration
window.originalH1Content = originalH1Content;
window.originalH2Content = originalH2Content;
// Start the countdown
showNextStep();
}
function animateZoomTransition(fromDistance, toDistance, duration, onComplete) {
if (!globeInstance) return;
if (zoomTransitionId) {
cancelAnimationFrame(zoomTransitionId);
}
const controls = globeInstance.controls();
const startTime = performance.now();
function animateZoom(currentTime) {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
// Use easing for smooth transition
const easedProgress = easeInOutQuad(progress);
const currentDistance =
fromDistance + (toDistance - fromDistance) * easedProgress;
// Apply new distance
const direction = controls.object.position.clone().normalize();
controls.object.position.copy(direction.multiplyScalar(currentDistance));
controls.update();
if (progress < 1) {
zoomTransitionId = requestAnimationFrame(animateZoom);
} else {
zoomTransitionId = null;
if (onComplete) onComplete();
}
}
zoomTransitionId = requestAnimationFrame(animateZoom);
}
function startBreathingAnimation() {
if (!globeInstance || breathingAnimationId) return;
// Replace manifestation header text during breathing
const manifestationHeader = document.getElementById("manifestation-header");
if (manifestationHeader) {
manifestationHeader.textContent = "HERE~NOW";
}
const controls = globeInstance.controls();
// Use maxDistance as base for breathing animation
const baseDistance = ZOOM_CONFIG.maxDistance;
const breathAmplitude = baseDistance * ZOOM_CONFIG.breathingAmplitude;
let startTime = performance.now();
// Calculate durations in milliseconds from configuration
const inspireDuration = ZOOM_CONFIG.breathingTiming.inspire * 1000;
const pauseDuration = ZOOM_CONFIG.breathingTiming.pause * 1000;
const expireDuration = ZOOM_CONFIG.breathingTiming.expire * 1000;
const cycleDuration = inspireDuration + pauseDuration + expireDuration;
console.log(
`🫁 Breathing cycle: ${ZOOM_CONFIG.breathingTiming.inspire}s-${
ZOOM_CONFIG.breathingTiming.pause
}s-${ZOOM_CONFIG.breathingTiming.expire}s (amplitude: ${
ZOOM_CONFIG.breathingAmplitude * 100
}%)`
);
function animateBreathing(currentTime) {
if (!isBreathingMode) return;
const elapsed = (currentTime - startTime) % cycleDuration;
let progress = 0;
// Determine current phase and update display
let currentPhase = "";
if (elapsed <= inspireDuration) {
// Inspiration phase - get closer
progress = easeInOutQuad(elapsed / inspireDuration);
currentPhase = "INHALE";
} else if (elapsed <= inspireDuration + pauseDuration) {
// Retention phase with mini animation
const pauseElapsed = elapsed - inspireDuration;
const pauseProgress = pauseElapsed / pauseDuration;
// Mini oscillation during pause (fast 0.5 second cycle)
const microCycle = (pauseElapsed % 500) / 500; // 0.5s cycle
const microVariation =
Math.sin(microCycle * Math.PI * 2) * ZOOM_CONFIG.pauseMicroAmplitude;
progress = 1 + microVariation;
currentPhase = "PAUSE";
} else {
// Expiration phase - move away
const expireElapsed = elapsed - inspireDuration - pauseDuration;
progress = 1 - easeInOutQuad(expireElapsed / expireDuration);
currentPhase = "EXHALE";
}
// Update breathing phase display
updateBreathingDisplay(currentPhase);
// Adjust camera distance (inspiration = get closer to globe)
const currentDistance = baseDistance - breathAmplitude * progress;
const direction = controls.object.position.clone().normalize();
controls.object.position.copy(direction.multiplyScalar(currentDistance));
controls.update();
breathingAnimationId = requestAnimationFrame(animateBreathing);
}
breathingAnimationId = requestAnimationFrame(animateBreathing);
}
function updateBreathingDisplay(phase) {
const timeDisplay = document.getElementById("time-display");
if (timeDisplay) {
// Save original content the first time
if (originalCountdownContent === null) {
originalCountdownContent = timeDisplay.textContent;
}
timeDisplay.textContent = phase;
}
}
function restoreCountdownDisplay() {
const timeDisplay = document.getElementById("time-display");
if (timeDisplay && originalCountdownContent !== null) {
// Don't restore original content as countdown continues
// Let countdown script naturally resume control
originalCountdownContent = null;
}
}
function stopBreathingAnimation() {
if (breathingAnimationId) {
cancelAnimationFrame(breathingAnimationId);
breathingAnimationId = null;
}
// Stop countdown if it's running
if (preBreathingCountdownId) {
clearTimeout(preBreathingCountdownId);
preBreathingCountdownId = null;
}
// Restore original header content
const h1Element = document.querySelector("h1");
const h2Element = document.querySelector("h2");
if (h1Element && window.originalH1Content) {
h1Element.textContent = window.originalH1Content;
}
if (h2Element && window.originalH2Content) {
h2Element.textContent = window.originalH2Content;
}
// Restore manifestation header text when breathing stops
const manifestationHeader = document.getElementById("manifestation-header");
if (manifestationHeader) {
manifestationHeader.textContent = "NEXT~MANIFESTATION~IN";
}
// Restore countdown display
restoreCountdownDisplay();
// Return to normal distance
if (globeInstance) {
const controls = globeInstance.controls();
const baseDistance = ZOOM_CONFIG.initialDistance;
const direction = controls.object.position.clone().normalize();
controls.object.position.copy(direction.multiplyScalar(baseDistance));
controls.update();
}
}
function toggleGlobeMode() {
if (!globeInstance) return;
const controls = globeInstance.controls();
const currentDistance = controls.object.position.length();
if (isBreathingMode) {
// Return to rotation mode with transition
isBreathingMode = false;
stopBreathingAnimation();
// Smooth transition to initial distance
animateZoomTransition(
currentDistance,
ZOOM_CONFIG.initialDistance,
ZOOM_CONFIG.transitionDuration,
() => {
controls.autoRotate = true;
controls.autoRotateSpeed = 0.5;
}
);
} else {
// Breathing mode with transition to maxDistance
isBreathingMode = true;
controls.autoRotate = false;
// Smooth transition to maximum distance then start countdown before breathing
animateZoomTransition(
currentDistance,
ZOOM_CONFIG.maxDistance,
ZOOM_CONFIG.transitionDuration,
() => {
// Start the pre-breathing countdown, then breathing animation
startPreBreathingCountdown(() => {
startBreathingAnimation();
});
}
);
}
}
// =============================================================================
// GLOBE SETUP & RENDERING
// =============================================================================
function createGlobe(gridData, userLocationData = [], otherUsersData = []) {
const globe = Globe()(document.getElementById("globeViz"))
.globeImageUrl("./img/earth-bi.jpg")
.backgroundImageUrl("./img/night-sky.png")
.backgroundColor(VISUAL_CONFIG.backgroundColor)
.atmosphereColor(VISUAL_CONFIG.atmosphereColor)
.atmosphereAltitude(VISUAL_CONFIG.atmosphereAltitude)
.width(window.innerWidth)
.height(window.innerHeight)
// Grid points + main user only (Points Layer)
.pointsData([...gridData.points, ...userLocationData])
.pointColor((d) =>
d.isUserLocation ? USER_LOCATION_CONFIG.color : VISUAL_CONFIG.pointColor
)
.pointRadius((d) =>
d.isUserLocation ? USER_LOCATION_CONFIG.radius : VISUAL_CONFIG.pointRadius
)
.pointAltitude((d) =>
d.isUserLocation ? USER_LOCATION_CONFIG.altitude : 0
)
.pointResolution(12)
// Grid arcs
.arcsData(gridData.arcs)
.arcColor(() => VISUAL_CONFIG.pointColor)
.arcAltitude((d) => d.altitude)
.arcStroke(VISUAL_CONFIG.arcStroke)
.arcDashLength(VISUAL_CONFIG.arcDashLength)
.arcDashGap(VISUAL_CONFIG.arcDashGap)
// Other users (uses optimized particle system)
.particlesData([otherUsersData]) // Wrap in array as particlesData expects array of sets
.particlesList((d) => d) // Return particles directly
.particleLat("lat")
.particleLng("lng")
.particleAltitude("altitude")
.particlesSize(OTHER_USERS_CONFIG.size)
.particlesSizeAttenuation(true)
.particlesColor(() => OTHER_USERS_CONFIG.color);
// Configure tilt and rotation via controls
const controls = globe.controls();
// Tilt globe 23.5 degrees by adjusting camera position
controls.object.position.set(0, 0, ZOOM_CONFIG.initialDistance);
controls.object.up.set(
Math.sin((23.5 * Math.PI) / 180),
Math.cos((23.5 * Math.PI) / 180),
0
);
// Configure zoom limits
controls.minDistance = ZOOM_CONFIG.minDistance;
controls.maxDistance = ZOOM_CONFIG.maxDistance;
controls.update();
// Enable automatic rotation by default
controls.autoRotate = true;
controls.autoRotateSpeed = 0.5;
controls.enableDamping = true;
controls.dampingFactor = 0.05;
// Store global instance
globeInstance = globe;
return globe;
}
// =============================================================================
// APPLICATION INITIALIZATION
// =============================================================================
async function initializeGlobe() {
const gridGenerator = new TriangularGridGenerator();
const gridData = gridGenerator.generate();
// Generate simulated users in populated areas
const usersGenerator = new PopulatedUsersGenerator();
const otherUsers = await usersGenerator.generate();
// Create globe with grid (points) and other users (particles)
const world = createGlobe(gridData, [], otherUsers);
// Initialize user geolocation
const locationManager = new UserLocationManager();
locationManager.initializeLocation(world, gridData);
// Add click event on heart button
const heartButton = document.getElementById("heart-button");
if (heartButton) {
heartButton.addEventListener("click", toggleGlobeMode);
}
}
initializeGlobe();