-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1691 lines (1582 loc) · 66.5 KB
/
Copy pathapp.js
File metadata and controls
1691 lines (1582 loc) · 66.5 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
/* =========================================================
GLOBO INTERATIVO // VISUALIZAÇÃO PLANETÁRIA EM TEMPO REAL
Globo 3D + satélites + arcos + cabos + dia/noite + dossiês
========================================================= */
import * as solar from "solar-calculator";
const THREE = window.THREE;
if (!THREE) throw new Error("Three.js não carregado.");
const COUNTRIES_URL =
"https://raw.githubusercontent.com/vasturiano/globe.gl/master/example/datasets/ne_110m_admin_0_countries.geojson";
const META_URL = "https://raw.githubusercontent.com/mledoze/countries/master/countries.json";
const TZ_URL =
"https://raw.githubusercontent.com/dr5hn/countries-states-cities-database/master/json/countries.json";
const IMG = "https://unpkg.com/three-globe/example/img/";
const TEX_DAY = IMG + "earth-blue-marble.jpg";
const TEX_NIGHT = IMG + "earth-night.jpg";
const TEX_SHADER_DAY = "/img/earth-day.jpg";
const TEX_SHADER_NIGHT = "/img/earth-night.jpg";
const LABEL_FONT_URL =
"https://cdn.jsdelivr.net/npm/@compai/font-roboto/data/typefaces/normal-400.json";
const el = (id) => document.getElementById(id);
const DEG = Math.PI / 180;
const nf = new Intl.NumberFormat("pt-BR");
/* ---------- Boot sequence ---------- */
const bootLines = [
"[ GLOBO INTERATIVO · NÚCLEO v3.0 ] inicializando ...",
"> montando /dev/orbital0 ................... OK",
"> calibrando matriz giroscópica ........... OK",
"> uplink com constelação [GX-9] ........... OK",
"> sincronizando relógio solar (UTC) ....... OK",
"> carregando fronteiras vetoriais ......... OK",
"> implantando malha de satélites (LEO/MEO) OK",
"> mapeando malha de cabos submarinos ...... OK",
"> conectando feeds estatísticos ........... OK",
"> render pipeline (WebGL2) ................ OK",
"> TERMINAL PLANETÁRIO ONLINE",
];
(function runBoot() {
const out = el("bootText");
let i = 0;
const tick = () => {
if (i < bootLines.length) {
out.textContent += bootLines[i++] + "\n";
setTimeout(tick, 180 + Math.random() * 150);
} else {
setTimeout(() => el("boot").classList.add("hidden"), 450);
}
};
tick();
})();
/* ---------- Live UTC clock ---------- */
setInterval(() => {
el("utcClock").textContent = new Date().toISOString().slice(11, 19) + " UTC";
}, 1000);
/* ---------- Telemetry / code stream ---------- */
const stream = el("codeStream");
const hex = (n) =>
Array.from({ length: n }, () => Math.floor(Math.random() * 16).toString(16))
.join("")
.toUpperCase();
const rnd = (a, b, d = 0) => (a + Math.random() * (b - a)).toFixed(d);
const logTemplates = [
() => `<span class="k">sat</span>.track(<span class="v">0x${hex(4)}</span>) → <span class="ok">LOCKED</span>`,
() => `vec[<span class="v">${rnd(-180,180,3)}</span>,<span class="v">${rnd(-90,90,3)}</span>] dx=<span class="v">${rnd(0,9,2)}</span>`,
() => `<span class="k">orbit</span>.alt=<span class="v">${rnd(540,1200,1)}</span>km incl=<span class="v">${rnd(0,98,1)}</span>°`,
() => `frame ${hex(6)} crc=<span class="ok">PASS</span>`,
() => `<span class="k">scan</span> setor ${hex(2)} :: ${rnd(0,100,0)}% concluído`,
() => `térmico ${rnd(-60,42,1)}°C fluxo=<span class="v">${rnd(0,9,3)}</span>`,
() => `pkt ${hex(8)} → nó relay <span class="v">${rnd(1,64,0)}</span>`,
() => `<span class="k">cable</span>.bgp peer ${hex(2)} ........ <span class="ok">UP</span>`,
() => `anomalia q=<span class="err">${rnd(0,3,2)}</span> filtrada`,
() => `gnss fix=<span class="ok">3D</span> sats=<span class="v">${rnd(8,22,0)}</span>`,
];
function pushLog(html) {
const div = document.createElement("div");
div.className = "ln";
div.innerHTML = `<span style="opacity:.4">${new Date()
.toISOString()
.slice(11, 23)}</span> ${html}`;
stream.appendChild(div);
while (stream.children.length > 60) stream.removeChild(stream.firstChild);
stream.scrollTop = stream.scrollHeight;
}
let telemetryTimer = null;
function tickTelemetry() {
pushLog(logTemplates[Math.floor(Math.random() * logTemplates.length)]());
}
function setTelemetry(on) {
state.telemetry = on;
syncTelemetryUI();
}
function syncTelemetryUI() {
const on = state.telemetry && !isMobileLayout();
const panel = el("telemetryPanel");
if (panel) panel.hidden = !on;
setToggleUI("telemetry", on);
if (on) {
if (!telemetryTimer) telemetryTimer = setInterval(tickTelemetry, 460);
} else if (telemetryTimer) {
clearInterval(telemetryTimer);
telemetryTimer = null;
}
}
/* =========================================================
GEO HELPERS
========================================================= */
const fmtPop = (n) =>
!n || n < 0
? "—"
: n >= 1e9
? (n / 1e9).toFixed(2) + " B"
: n >= 1e6
? (n / 1e6).toFixed(1) + " M"
: (n / 1e3).toFixed(0) + " K";
function mainRing(geometry) {
if (geometry.type === "Polygon") return geometry.coordinates[0];
let best = [];
for (const poly of geometry.coordinates) {
if (poly[0] && poly[0].length > best.length) best = poly[0];
}
return best;
}
function sphericalCentroid(ring) {
let x = 0, y = 0, z = 0;
for (const [lng, lat] of ring) {
const la = lat * DEG, lo = lng * DEG;
x += Math.cos(la) * Math.cos(lo);
y += Math.cos(la) * Math.sin(lo);
z += Math.sin(la);
}
const n = ring.length || 1;
x /= n; y /= n; z /= n;
return {
lat: Math.atan2(z, Math.sqrt(x * x + y * y)) / DEG,
lng: Math.atan2(y, x) / DEG,
};
}
function greatCircle(a, b, steps = 32) {
const toVec = (p) => {
const la = p[0] * DEG, lo = p[1] * DEG;
return new THREE.Vector3(
Math.cos(la) * Math.cos(lo),
Math.cos(la) * Math.sin(lo),
Math.sin(la)
);
};
const va = toVec(a), vb = toVec(b);
const omega = Math.acos(THREE.MathUtils.clamp(va.dot(vb), -1, 1));
const pts = [];
for (let i = 0; i <= steps; i++) {
const t = i / steps;
let v;
if (omega < 1e-6) v = va.clone();
else {
const s1 = Math.sin((1 - t) * omega) / Math.sin(omega);
const s2 = Math.sin(t * omega) / Math.sin(omega);
v = va.clone().multiplyScalar(s1).add(vb.clone().multiplyScalar(s2));
}
v.normalize();
pts.push([
Math.asin(THREE.MathUtils.clamp(v.z, -1, 1)) / DEG,
Math.atan2(v.y, v.x) / DEG,
]);
}
return pts;
}
// classificação climática aproximada pela latitude
function climateOf(lat) {
const a = Math.abs(lat);
if (a < 10) return "Equatorial / Tropical úmido";
if (a < 23.5) return "Tropical";
if (a < 35) return "Subtropical / Árido";
if (a < 55) return "Temperado";
if (a < 66.5) return "Frio / Boreal";
return "Polar";
}
// posição solar precisa (globe.gl official + solar-calculator)
function sunPosAt(dt = Date.now()) {
const day = new Date(+dt).setUTCHours(0, 0, 0, 0);
const t = solar.century(dt);
const lng = (day - dt) / 864e5 * 360 - 180 - solar.equationOfTime(t) / 4;
return { lng, lat: solar.declination(t) };
}
function subsolarPoint(date = new Date()) {
return sunPosAt(+date);
}
// distância Terra-Sol aprox (órbita elíptica) em km
function earthSunDistance(date = new Date()) {
const yStart = Date.UTC(date.getUTCFullYear(), 0, 0);
const doy = (date - yStart) / 86400000;
return 149.6e6 * (1 - 0.0167 * Math.cos((360 / 365) * (doy - 4) * DEG));
}
/* =========================================================
DADOS: cidades, arcos, cabos, satélites
========================================================= */
const CITIES = {
nyc: [40.71, -74.01], lon: [51.51, -0.13], tky: [35.68, 139.69],
sgp: [1.35, 103.82], syd: [-33.87, 151.21], sao: [-23.55, -46.63],
dxb: [25.2, 55.27], mum: [19.08, 72.88], fra: [50.11, 8.68],
lax: [34.05, -118.24], hkg: [22.32, 114.17], mow: [55.75, 37.62],
cai: [30.04, 31.24], jnb: [-26.2, 28.04], los: [6.52, 3.38],
par: [48.85, 2.35], yto: [43.65, -79.38], mex: [19.43, -99.13],
bue: [-34.6, -58.38], sel: [37.57, 126.98], jkt: [-6.21, 106.85],
ist: [41.01, 28.98], nbo: [-1.29, 36.82], sfo: [37.77, -122.42],
ams: [52.37, 4.9],
};
const CK = Object.keys(CITIES);
function buildArcs(n = 24) {
const arcs = [];
for (let i = 0; i < n; i++) {
let a = CK[Math.floor(Math.random() * CK.length)];
let b = CK[Math.floor(Math.random() * CK.length)];
while (b === a) b = CK[Math.floor(Math.random() * CK.length)];
arcs.push({
startLat: CITIES[a][0], startLng: CITIES[a][1],
endLat: CITIES[b][0], endLng: CITIES[b][1],
dashTime: 2500 + Math.random() * 3500,
});
}
return arcs;
}
const CABLES_URL = "/data/cable-geo.json"; // TeleGeography · submarinecablemap.com (CC BY-NC-SA 3.0)
function cableGeoToPaths(geojson) {
const paths = [];
for (const { geometry, properties } of geojson.features || []) {
if (!geometry?.coordinates) continue;
const segments = geometry.type === "MultiLineString"
? geometry.coordinates
: geometry.type === "LineString"
? [geometry.coordinates]
: [];
for (const coords of segments) {
const points = coords.map(([lng, lat]) => [lat, lng, 0.002]);
if (points.length >= 2) paths.push({ points, name: properties?.name || "" });
}
}
return paths;
}
function loadSubmarineCables() {
return fetch(CABLES_URL)
.then((r) => {
if (!r.ok) throw new Error(String(r.status));
return r.json();
})
.then((geo) => {
CABLES = cableGeoToPaths(geo);
if (state.cables) world.pathsData(CABLES);
pushLog(`<span class="k">cables</span> ${CABLES.length} rotas · TeleGeography <span class="ok">OK</span>`);
})
.catch((err) => {
pushLog(`<span class="err">cables: falha ao carregar (${err})</span>`);
});
}
function buildSats(n = 18) {
const sats = [];
for (let i = 0; i < n; i++) {
const comm = Math.random() < 0.3;
sats.push({
alt: comm ? 0.55 + Math.random() * 0.25 : 0.18 + Math.random() * 0.22,
incl: (Math.random() * 2 - 1) * (35 + Math.random() * 45),
raan: Math.random() * 360,
phase: Math.random() * Math.PI * 2,
speed: (comm ? 0.05 : 0.12) + Math.random() * 0.08,
color: comm ? "#ffb454" : "#46e6ff",
lat: 0, lng: 0,
});
}
return sats;
}
function makeSatObject(color) {
const g = new THREE.Group();
const body = new THREE.Mesh(
new THREE.OctahedronGeometry(1.4, 0),
new THREE.MeshLambertMaterial({ color, emissive: color, emissiveIntensity: 0.85 })
);
g.add(body);
const panelMat = new THREE.MeshLambertMaterial({
color: "#0a2230", emissive: "#0a3344", emissiveIntensity: 0.4,
});
const pL = new THREE.Mesh(new THREE.BoxGeometry(3.4, 0.15, 1.3), panelMat);
pL.position.x = -2.6;
const pR = pL.clone();
pR.position.x = 2.6;
g.add(pL, pR);
g.add(new THREE.Mesh(
new THREE.SphereGeometry(2.4, 12, 12),
new THREE.MeshBasicMaterial({ color, transparent: true, opacity: 0.12 })
));
return g;
}
/* =========================================================
CAMADA FUSOS HORÁRIOS — meridianos + rótulos UTC (Three.js, não-interativo)
========================================================= */
const TZ_STEP = 15;
const TZ_BANDS = [];
let tzMeridiansGroup = null;
let tropicsGroup = null;
let lastTzLabelMin = -1;
const NO_RAYCAST = () => {};
/* Acima do polígono em hover/seleção (0.06) para linhas ficarem sempre visíveis */
const GRID_LINE_ALT = 0.075;
const GRID_LABEL_ALT = 0.085;
const GRID_RENDER_ORDER = 20;
const TROPIC_LAT = 23.436;
const TROPIC_LINES = [
{ lat: 0, opacity: 0.95, name: "EQUADOR", lng: -30 },
{ lat: TROPIC_LAT, opacity: 0.82, name: "TRÓPICO DE CÂNCER", lng: 45 },
{ lat: -TROPIC_LAT, opacity: 0.82, name: "TRÓPICO DE CAPRICÓRNIO", lng: -120 },
];
const TROPIC_LABEL_COLORS = {
stroke: "rgba(70,230,255,0.7)",
fill: "#46e6ff",
};
(function buildTzBands() {
for (let i = 0; i < 24; i++) {
const lngW = -180 + i * TZ_STEP;
const centerLng = lngW + TZ_STEP / 2;
TZ_BANDS.push({ centerLng, offsetH: centerLng / 15 });
}
})();
function formatUtcOffset(h) {
const hi = Math.round(h);
if (hi === 0) return "UTC+0";
return hi > 0 ? `UTC+${hi}` : `UTC${hi}`;
}
function timeAtOffsetHours(h, now = Date.now()) {
const utc = now + new Date().getTimezoneOffset() * 60000;
return new Intl.DateTimeFormat("pt-BR", {
hour: "2-digit", minute: "2-digit", hour12: false,
}).format(new Date(utc + Math.round(h) * 3600000));
}
function tzLabelText(band, now = Date.now()) {
const h = Math.round(band.offsetH);
return `${formatUtcOffset(h)}: ${timeAtOffsetHours(h, now)}`;
}
const TZ_LABEL_FONT = '600 17px "Share Tech Mono", monospace';
const TZ_LABEL_PAD_X = 16;
const TZ_LABEL_H = 38;
const TZ_LABEL_SCALE_H = 2.15;
function paintGridLabelSprite(sprite, text, { stroke, fill }) {
const canvas = sprite.userData._canvas;
const ctx = canvas.getContext("2d");
ctx.font = TZ_LABEL_FONT;
const textW = Math.ceil(ctx.measureText(text).width);
const needW = Math.max(textW + TZ_LABEL_PAD_X * 2, 72);
if (canvas.width !== needW || canvas.height !== TZ_LABEL_H) {
canvas.width = needW;
canvas.height = TZ_LABEL_H;
sprite.userData._texture.dispose();
const tex = new THREE.CanvasTexture(canvas);
tex.minFilter = THREE.LinearFilter;
tex.magFilter = THREE.LinearFilter;
sprite.userData._texture = tex;
sprite.material.map = tex;
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "rgba(3,12,18,0.92)";
ctx.strokeStyle = stroke;
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.roundRect(2, 2, canvas.width - 4, canvas.height - 4, 4);
ctx.fill();
ctx.stroke();
ctx.font = TZ_LABEL_FONT;
ctx.fillStyle = fill;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, canvas.width / 2, canvas.height / 2);
sprite.userData._texture.needsUpdate = true;
const aspect = canvas.width / canvas.height;
sprite.scale.set(aspect * TZ_LABEL_SCALE_H, TZ_LABEL_SCALE_H, 1);
}
function paintTzLabelSprite(sprite, text) {
paintGridLabelSprite(sprite, text, {
stroke: "rgba(255,180,84,0.7)",
fill: "#ffb454",
});
}
function makeGridLabelSprite(text, colors) {
const canvas = document.createElement("canvas");
canvas.width = 1;
canvas.height = TZ_LABEL_H;
const texture = new THREE.CanvasTexture(canvas);
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture, transparent: true, depthTest: true, depthWrite: false,
});
const sprite = new THREE.Sprite(material);
sprite.renderOrder = GRID_RENDER_ORDER + 2;
sprite.raycast = NO_RAYCAST;
sprite.userData._canvas = canvas;
sprite.userData._texture = texture;
paintGridLabelSprite(sprite, text, colors);
return sprite;
}
function makeTzLabelSprite(text) {
return makeGridLabelSprite(text, {
stroke: "rgba(255,180,84,0.7)",
fill: "#ffb454",
});
}
function meridianPositions(lng, alt = GRID_LINE_ALT) {
const positions = [];
for (let lat = -85; lat <= 85; lat += 4) {
const { x, y, z } = world.getCoords(lat, lng, alt);
positions.push(x, y, z);
}
return positions;
}
function parallelPositions(lat, alt = GRID_LINE_ALT) {
const positions = [];
for (let lng = -180; lng <= 180; lng += 4) {
const { x, y, z } = world.getCoords(lat, lng, alt);
positions.push(x, y, z);
}
return positions;
}
function addGlobeLine(group, positions, color, opacity = 0.88) {
const geo = new THREE.BufferGeometry();
geo.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
const line = new THREE.Line(geo, new THREE.LineBasicMaterial({
color, transparent: true, opacity,
depthTest: true, depthWrite: false,
}));
line.frustumCulled = false;
line.renderOrder = GRID_RENDER_ORDER;
line.raycast = NO_RAYCAST;
group.add(line);
}
function buildTzMeridiansGroup() {
const group = new THREE.Group();
group.name = "tzMeridians";
group.renderOrder = GRID_RENDER_ORDER;
group.raycast = NO_RAYCAST;
for (let lng = -180; lng <= 180; lng += TZ_STEP) {
addGlobeLine(group, meridianPositions(lng), 0xffb454);
}
const labelsGroup = new THREE.Group();
labelsGroup.name = "tzLabels";
labelsGroup.raycast = NO_RAYCAST;
const now = Date.now();
for (const band of TZ_BANDS) {
const sprite = makeTzLabelSprite(tzLabelText(band, now));
sprite.userData.tzBand = band;
const { x, y, z } = world.getCoords(14, band.centerLng, GRID_LABEL_ALT);
sprite.position.set(x, y, z);
labelsGroup.add(sprite);
}
group.add(labelsGroup);
group.userData.labelsGroup = labelsGroup;
group.visible = false;
return group;
}
function buildTropicsGroup() {
const group = new THREE.Group();
group.name = "tropics";
group.renderOrder = GRID_RENDER_ORDER;
group.raycast = NO_RAYCAST;
const labelsGroup = new THREE.Group();
labelsGroup.name = "tropicLabels";
labelsGroup.raycast = NO_RAYCAST;
for (const { lat, opacity, name, lng } of TROPIC_LINES) {
addGlobeLine(group, parallelPositions(lat), 0x46e6ff, opacity);
const sprite = makeGridLabelSprite(name, TROPIC_LABEL_COLORS);
const { x, y, z } = world.getCoords(lat, lng, GRID_LABEL_ALT);
sprite.position.set(x, y, z);
labelsGroup.add(sprite);
}
group.add(labelsGroup);
group.visible = false;
return group;
}
function updateTzLabelSprites(now = Date.now()) {
if (!tzMeridiansGroup || !state.tz) return;
const labelsGroup = tzMeridiansGroup.userData.labelsGroup;
if (!labelsGroup) return;
for (const sprite of labelsGroup.children) {
paintTzLabelSprite(sprite, tzLabelText(sprite.userData.tzBand, now));
}
}
function setTzMeridians(on) {
if (!tzMeridiansGroup) return;
tzMeridiansGroup.visible = on;
if (on) updateTzLabelSprites();
}
function setTropics(on) {
if (!tropicsGroup) return;
tropicsGroup.visible = on;
}
function polygonDataset() {
return FEATURES;
}
function activePaths() {
return state.cables ? CABLES : [];
}
function activeLabels() {
const out = [];
if (state.labels) out.push(...LABELS);
if (state.oceans) out.push(...OCEAN_LABELS);
return out;
}
function polygonStrokeColorFn() {
return state.borders ? "#46e6ff" : "rgba(0,0,0,0)";
}
const OCEAN_LABELS = [
{ lat: 0, lng: -145, text: "OCEANO PACÍFICO", kind: "ocean" },
{ lat: 8, lng: -42, text: "OCEANO ATLÂNTICO", kind: "ocean" },
{ lat: -22, lng: 82, text: "OCEANO ÍNDICO", kind: "ocean" },
{ lat: 72, lng: -30, text: "OCEANO ÁRTICO", kind: "ocean" },
{ lat: -62, lng: 0, text: "OCEANO ANTÁRTICO", kind: "ocean" },
];
/* =========================================================
SHADER DIA/NOITE (oficial globe.gl + solar-calculator)
========================================================= */
const DAY_NIGHT_SHADER = {
vertexShader: `
varying vec3 vNormal;
varying vec2 vUv;
void main() {
vNormal = normalize(normalMatrix * normal);
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
#define PI 3.141592653589793
uniform sampler2D dayTexture;
uniform sampler2D nightTexture;
uniform vec2 sunPosition;
uniform vec2 globeRotation;
varying vec3 vNormal;
varying vec2 vUv;
float toRad(in float a) { return a * PI / 180.0; }
vec3 Polar2Cartesian(in vec2 c) {
float theta = toRad(90.0 - c.x);
float phi = toRad(90.0 - c.y);
return vec3(sin(phi) * cos(theta), cos(phi), sin(phi) * sin(theta));
}
void main() {
float invLon = toRad(globeRotation.x);
float invLat = -toRad(globeRotation.y);
mat3 rotX = mat3(1,0,0, 0,cos(invLat),-sin(invLat), 0,sin(invLat),cos(invLat));
mat3 rotY = mat3(cos(invLon),0,sin(invLon), 0,1,0, -sin(invLon),0,cos(invLon));
vec3 sunDir = rotX * rotY * Polar2Cartesian(sunPosition);
float intensity = dot(normalize(vNormal), normalize(sunDir));
vec4 dayColor = texture2D(dayTexture, vUv);
vec4 nightColor = texture2D(nightTexture, vUv);
float blend = smoothstep(-0.1, 0.1, intensity);
gl_FragColor = mix(nightColor, dayColor, blend);
}
`,
};
let dayNightMaterial = null;
let dayNightReady = false;
const texLoader = new THREE.TextureLoader();
texLoader.setCrossOrigin("anonymous");
Promise.all([
texLoader.loadAsync(TEX_SHADER_DAY),
texLoader.loadAsync(TEX_SHADER_NIGHT),
]).then(([dayTex, nightTex]) => {
if ("SRGBColorSpace" in THREE) {
dayTex.colorSpace = THREE.SRGBColorSpace;
nightTex.colorSpace = THREE.SRGBColorSpace;
}
dayNightMaterial = new THREE.ShaderMaterial({
uniforms: {
dayTexture: { value: dayTex },
nightTexture: { value: nightTex },
sunPosition: { value: new THREE.Vector2() },
globeRotation: { value: new THREE.Vector2() },
},
vertexShader: DAY_NIGHT_SHADER.vertexShader,
fragmentShader: DAY_NIGHT_SHADER.fragmentShader,
toneMapped: false,
});
dayNightReady = true;
if (state.daynight) setDayNight(true);
pushLog(`<span class="k">shader</span> texturas dia/noite ........ <span class="ok">OK</span>`);
}).catch(() => pushLog(`<span class="err">shader: falha ao carregar texturas</span>`));
function updateDayNightUniforms(dt = Date.now()) {
if (!dayNightMaterial) return;
const sp = sunPosAt(dt);
dayNightMaterial.uniforms.sunPosition.value.set(sp.lng, sp.lat);
}
/* =========================================================
GLOBO
========================================================= */
const state = {
telemetry: true,
night: false, daynight: false, rotate: true, borders: false,
labels: false, oceans: false, sats: false, arcs: false, cables: false, tz: false, tropics: false,
};
let FEATURES = [], LABELS = [], ARCS = [], CABLES = [], SATS = [];
let hoverD = null, selectedD = null;
const capColor = (d) =>
d === selectedD ? "rgba(93,255,155,0.55)"
: d === hoverD ? "rgba(70,230,255,0.40)"
: (state.night || state.daynight) ? "rgba(70,230,255,0.04)" : "rgba(70,230,255,0.06)";
const altOf = (d) => (d === hoverD || d === selectedD ? 0.06 : 0.008);
const refreshPolys = () => world
.polygonsData(polygonDataset())
.polygonAltitude(altOf)
.polygonCapColor(capColor)
.polygonStrokeColor(polygonStrokeColorFn);
const world = Globe()(el("globeViz"))
.backgroundColor("rgba(0,0,0,0)")
.globeImageUrl(TEX_DAY)
.bumpImageUrl(IMG + "earth-topology.png")
.showAtmosphere(true)
.atmosphereColor("#46e6ff")
.atmosphereAltitude(0.22)
.arcStartLat((d) => d.startLat).arcStartLng((d) => d.startLng)
.arcEndLat((d) => d.endLat).arcEndLng((d) => d.endLng)
.arcColor(() => ["rgba(70,230,255,0.05)", "rgba(93,255,155,0.95)"])
.arcStroke(0.45).arcDashLength(0.4).arcDashGap(0.18)
.arcDashAnimateTime((d) => d.dashTime).arcsTransitionDuration(0)
.pathPoints((d) => d.points)
.pathPointLat((p) => p[0]).pathPointLng((p) => p[1]).pathPointAlt((p) => p[2])
.pathColor(() => ["rgba(255,180,84,0.15)", "rgba(255,180,84,0.9)"])
.pathStroke(1.1).pathDashLength(0.25).pathDashGap(0.12)
.pathDashAnimateTime(9000).pathTransitionDuration(0)
.objectLat((d) => d.lat).objectLng((d) => d.lng).objectAltitude((d) => d.alt)
.objectThreeObject((d) => makeSatObject(d.color))
.labelLat((d) => d.lat).labelLng((d) => d.lng).labelText((d) => d.text)
.labelSize((d) => (d.kind === "ocean" ? 0.38 : 0.42))
.labelDotRadius((d) => (d.kind === "ocean" ? 0 : 0.18))
.labelColor((d) => (d.kind === "ocean" ? "rgba(70,230,255,0.72)" : "rgba(154,243,255,0.85)"))
.labelResolution(2).labelAltitude(0.012).labelsTransitionDuration(0)
.onGlobeReady(() => {
tzMeridiansGroup = buildTzMeridiansGroup();
tropicsGroup = buildTropicsGroup();
world.scene().add(tzMeridiansGroup);
world.scene().add(tropicsGroup);
tzMeridiansGroup.visible = state.tz;
tropicsGroup.visible = state.tropics;
})
.onGlobeClick(() => deselect());
function applyLabelFont(font) {
world.labelTypeFace(font);
world.labelsData(activeLabels());
}
fetch(LABEL_FONT_URL)
.then((r) => r.json())
.then((font) => {
applyLabelFont(font);
pushLog(`<span class="k">font</span> Roboto · acentos PT-BR <span class="ok">OK</span>`);
})
.catch((err) =>
pushLog(`<span class="warn">fonte labels: fallback ASCII (${err})</span>`)
);
function syncDayNightRotation() {
if (!state.daynight || !dayNightMaterial) return;
const pov = world.pointOfView();
dayNightMaterial.uniforms.globeRotation.value.set(pov.lng, pov.lat);
}
const defaultGlobeMaterial = world.globeMaterial();
world.onZoom(({ lng, lat }) => {
if (state.daynight && dayNightMaterial)
dayNightMaterial.uniforms.globeRotation.value.set(lng, lat);
});
ARCS = buildArcs();
SATS = buildSats();
loadSubmarineCables();
/* ---------- Carrega países ---------- */
fetch(COUNTRIES_URL)
.then((r) => r.json())
.then(({ features }) => {
FEATURES = features;
el("trackCount").textContent = String(features.length).padStart(3, "0");
features.forEach((f) => {
f.properties.__c = sphericalCentroid(mainRing(f.geometry));
});
LABELS = features.map((f) => ({
lat: f.properties.__c.lat,
lng: f.properties.__c.lng,
text: ptName(f.properties).toUpperCase(),
}));
world
.polygonsData(polygonDataset())
.polygonAltitude(altOf)
.polygonCapColor(capColor)
.polygonSideColor(() => "rgba(70,230,255,0.12)")
.polygonStrokeColor(polygonStrokeColorFn)
.polygonLabel(({ properties: p }) => `
<div style="font-family:'Share Tech Mono',monospace;background:rgba(3,12,18,.92);
border:1px solid rgba(70,230,255,.4);padding:6px 10px;color:#9af3ff;
box-shadow:0 0 14px rgba(70,230,255,.3);letter-spacing:.04em">
<b style="color:#46e6ff">${ptName(p)}</b><br/>
<span style="opacity:.7">ISO ${p.ISO_A2 || "--"} · POP ${fmtPop(p.POP_EST)}</span><br/>
<span style="opacity:.55">LAT ${p.__c.lat.toFixed(2)} · LON ${p.__c.lng.toFixed(2)}</span>
</div>`)
.onPolygonHover((d) => {
hoverD = d;
el("screen").style.cursor = d ? "pointer" : "default";
refreshPolys();
if (d && !selectedD) showCountryQuick(d.properties);
else if (!d && !selectedD) showEarth();
})
.onPolygonClick((d) => {
if (!d) return deselect();
selectedD = d;
refreshPolys();
showCountryFull(d.properties);
world.pointOfView(
{ lat: d.properties.__c.lat, lng: d.properties.__c.lng, altitude: 1.4 },
900
);
});
buildSearchIndex();
applyAll();
syncAllToggles();
showEarth();
})
.catch((err) =>
pushLog(`<span class="err">ERRO: falha ao carregar fronteiras (${err})</span>`)
);
function deselect() {
if (!selectedD && !hoverD) return;
selectedD = null;
hoverD = null;
refreshPolys();
showEarth();
const si = el("globeSearchInput");
if (si && document.activeElement !== si) si.value = "";
}
/* =========================================================
BUSCA DE PAÍSES
========================================================= */
const CONTINENT_PT = {
Africa: "África",
Europe: "Europa",
Asia: "Ásia",
"North America": "América do Norte",
"South America": "América do Sul",
Oceania: "Oceania",
Antarctica: "Antártica",
};
const CONTINENT_ORDER = [
"África", "América do Sul", "América do Norte", "Ásia", "Europa", "Oceania", "Antártica",
];
let searchGroups = [];
function normSearch(s) {
return String(s)
.toLocaleLowerCase("pt-BR")
.normalize("NFD")
.replace(/\p{M}/gu, "");
}
function buildSearchIndex() {
const map = new Map();
for (const f of FEATURES) {
const p = f.properties;
const name = ptName(p);
const continent = CONTINENT_PT[p.CONTINENT] || p.CONTINENT || "Outros";
if (!map.has(continent)) map.set(continent, []);
map.get(continent).push({
f, name, iso: (p.ISO_A2 || "").toLowerCase(), nameFold: normSearch(name),
});
}
const sortItems = (items) =>
items.sort((a, b) => a.name.localeCompare(b.name, "pt-BR"));
searchGroups = CONTINENT_ORDER.filter((c) => map.has(c)).map((c) => ({
continent: c,
items: sortItems(map.get(c)),
}));
for (const [c, items] of map) {
if (!CONTINENT_ORDER.includes(c))
searchGroups.push({ continent: c, items: sortItems(items) });
}
}
function renderSearchDrop(query = "") {
const list = el("globeSearchList");
const q = normSearch(query.trim());
list.innerHTML = "";
let hasAny = false;
for (const g of searchGroups) {
const filtered = q
? g.items.filter(
(i) => i.nameFold.includes(q) || i.iso.includes(q)
)
: g.items;
if (!filtered.length) continue;
hasAny = true;
const hdr = document.createElement("div");
hdr.className = "search-dock__continent";
hdr.textContent = g.continent;
list.appendChild(hdr);
for (const item of filtered) {
const btn = document.createElement("button");
btn.type = "button";
btn.className = "search-dock__item";
btn.textContent = item.name;
btn.addEventListener("mousedown", (e) => e.preventDefault());
btn.addEventListener("click", () => selectCountryFromSearch(item.f));
list.appendChild(btn);
}
}
if (!hasAny) {
const empty = document.createElement("div");
empty.className = "search-dock__empty";
empty.textContent = "Nenhum país encontrado";
list.appendChild(empty);
}
}
function openSearchDrop() {
el("globeSearchDrop").hidden = false;
renderSearchDrop(el("globeSearchInput").value);
}
function closeSearchDrop() {
el("globeSearchDrop").hidden = true;
}
function selectCountryFromSearch(f) {
selectedD = f;
hoverD = null;
refreshPolys();
showCountryFull(f.properties);
world.pointOfView(
{ lat: f.properties.__c.lat, lng: f.properties.__c.lng, altitude: 1.4 },
900
);
el("globeSearchInput").value = ptName(f.properties);
closeSearchDrop();
}
(function setupCountrySearch() {
const input = el("globeSearchInput");
const wrap = el("globeSearchWrap");
if (!input || !wrap) return;
const unlockInput = () => input.removeAttribute("readonly");
input.addEventListener("focus", unlockInput);
input.addEventListener("mousedown", unlockInput);
input.addEventListener("touchstart", unlockInput, { passive: true });
input.addEventListener("focus", openSearchDrop);
input.addEventListener("click", openSearchDrop);
input.addEventListener("input", () => {
openSearchDrop();
renderSearchDrop(input.value);
});
input.addEventListener("keydown", (e) => {
if (e.key === "Escape") {
closeSearchDrop();
input.blur();
}
});
document.addEventListener("click", (e) => {
if (!wrap.contains(e.target)) closeSearchDrop();
});
})();
/* =========================================================
POPULAÇÃO EM TEMPO REAL (modelo + âncora via API)
========================================================= */
const BIRTHS_YR = 134_000_000, DEATHS_YR = 61_000_000, SEC_YR = 31_557_600;
const NPS = (BIRTHS_YR - DEATHS_YR) / SEC_YR;
let POP_ANCHOR = { value: 8_092_000_000, t: Date.UTC(2025, 0, 1) };
const worldPopNow = (now = Date.now()) =>
POP_ANCHOR.value + (NPS * (now - POP_ANCHOR.t)) / 1000;
const startOfUTCDay = (now) => {
const d = new Date(now);
return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());
};
function countryRates(pop) {
const wp = worldPopNow();
return { bps: (pop * (BIRTHS_YR / wp)) / SEC_YR, dps: (pop * (DEATHS_YR / wp)) / SEC_YR };
}
function fetchT(url, ms = 9000) {
const ac = new AbortController();
const id = setTimeout(() => ac.abort(), ms);
return fetch(url, { signal: ac.signal }).finally(() => clearTimeout(id));
}
// nomes PT-BR (gist) + metadados (mledoze/countries.json)
const PT_NAMES = {}, PT_GENT = {};
const META_INDEX = { byA2: {}, byA3: {} };
const TZ_INDEX = { byA2: {} };
function tzOffsetMinutes(zoneName, date = new Date()) {
const utc = new Date(date.toLocaleString("en-US", { timeZone: "UTC" }));
const local = new Date(date.toLocaleString("en-US", { timeZone: zoneName }));
return Math.round((local - utc) / 60000);
}
function fmtUtcOffset(minutes) {
const sign = minutes >= 0 ? "+" : "-";
const abs = Math.abs(minutes);
const h = Math.floor(abs / 60);
const m = abs % 60;
if (!m) return `UTC ${sign}${h}`;
return `UTC ${sign}${h}:${String(m).padStart(2, "0")}`;
}
function formatLocalTime(zoneName, date = new Date()) {
return new Intl.DateTimeFormat("pt-BR", {
timeZone: zoneName,
hour: "2-digit",
minute: "2-digit",
hour12: false,
}).format(date);
}
function formatCountryTimezones(iso2, now = Date.now()) {
const zones = TZ_INDEX.byA2[iso2];
if (!zones?.length) return "—";
const date = new Date(now);
const byOffset = new Map();
for (const z of zones) {
const zone = z.zoneName;
if (!zone) continue;
try {
const off = tzOffsetMinutes(zone, date);
if (!byOffset.has(off)) {
byOffset.set(off, formatLocalTime(zone, date));
}
} catch (e) {}
}
if (!byOffset.size) return "—";
return [...byOffset.entries()]
.sort((a, b) => b[0] - a[0])
.map(([off, time]) => `${fmtUtcOffset(off)}: ${time}`)
.join(", ");
}
function refreshCountryTz() {
if (liveCtx?.type !== "country" || !liveCtx.iso2) return;
const tz = el("ccTz");
if (tz) tz.textContent = formatCountryTimezones(liveCtx.iso2);
}
(async () => {
try {
const pt = await (await fetchT("pt-countries.json", 8000)).json();