-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
1735 lines (1473 loc) · 64.2 KB
/
script.js
File metadata and controls
1735 lines (1473 loc) · 64.2 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
// Shipping Container Tracker - Main Application
class ContainerTracker {
constructor() {
this.scene = null;
this.camera = null;
this.renderer = null;
this.controls = null;
this.globe = null;
this.ship = null;
this.shipMarker = null;
this.isPlaying = true;
this.currentJourneyIndex = 0;
this.journeyData = null;
this.milestones = [];
this.currentMilestone = 0;
this.currentMode = 'globe';
this.textures = {};
this.flatMapMesh = null;
this.followShip = false; // Whether to automatically follow ship position
// Leaflet (2D map) state
this.leafletMap = null;
this.leafletMarker = null;
this.leafletRoute = null;
this.leafletStartMarker = null;
this.leafletEndMarker = null;
// Shared current position
this.currentPosition = null;
// WorldWind state (globe only)
this.wwd = null;
// High-quality texture URLs (fallback to procedural if unavailable)
this.textureUrls = {
earth: 'https://raw.githubusercontent.com/fernandojsg/threejs-360-earth/master/img/2_no_clouds_4k.jpg',
bump: 'https://raw.githubusercontent.com/fernandojsg/threejs-360-earth/master/img/elev_bump_4k.jpg',
specular: 'https://raw.githubusercontent.com/fernandojsg/threejs-360-earth/master/img/water_4k.png',
clouds: 'https://raw.githubusercontent.com/fernandojsg/threejs-360-earth/master/img/fair_clouds_4k.png',
stars: 'https://raw.githubusercontent.com/fernandojsg/threejs-360-earth/master/img/galaxy_starfield.png'
};
this.init();
}
initWorldWind() {
console.log('Initializing WorldWind...');
if (!window.WorldWind) {
console.error('WorldWind library not loaded');
return;
}
const canvasId = 'ww-canvas';
const canvas = document.getElementById(canvasId);
if (!canvas) {
console.error('WorldWind canvas not found:', canvasId);
return;
}
console.log('Canvas found, creating WorldWindow...');
try {
this.wwd = new WorldWind.WorldWindow(canvasId);
console.log('WorldWindow created successfully');
// Ensure canvas is properly sized
const container = canvas.parentElement;
if (container) {
canvas.width = container.clientWidth;
canvas.height = container.clientHeight;
console.log('Canvas sized:', canvas.width, 'x', canvas.height);
}
// Set up proper navigation controls
this.wwd.navigator.range = 20000000; // 20,000km altitude for good overview
this.wwd.navigator.tilt = 0; // Start with no tilt
this.wwd.navigator.heading = 0; // Start with no rotation
console.log('Navigation controls set');
} catch (e) {
console.error('Failed to initialize WorldWind:', e);
return;
}
// Use basic layers first to test
console.log('Adding basic layers...');
try {
// Add basic Blue Marble layer first
const bmngLayer = new WorldWind.BMNGLayer();
this.wwd.addLayer(bmngLayer);
console.log('Added BMNG layer');
// Add controls
const compassLayer = new WorldWind.CompassLayer();
this.wwd.addLayer(compassLayer);
console.log('Added Compass layer');
const viewControlsLayer = new WorldWind.ViewControlsLayer(this.wwd);
this.wwd.addLayer(viewControlsLayer);
console.log('Added ViewControls layer');
} catch (e) {
console.error('Error adding layers:', e);
}
// Add ship layer for WorldWind
console.log('Creating ship layer...');
this.wwShipLayer = new WorldWind.RenderableLayer("Ship");
this.wwd.addLayer(this.wwShipLayer);
// Create ship placemark
const shipAttributes = new WorldWind.PlacemarkAttributes(null);
shipAttributes.imageSource = "data:image/svg+xml;base64," + btoa('<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24"><path fill="#ff6b35" d="M2 13h2l2 3h8l2-3h2l-2 5H4z"/><path fill="#ffffff" d="M7 12h2v-2H7zm3 0h2V9h-2zm3 0h2V8h-2z"/></svg>');
shipAttributes.imageScale = 1.5;
shipAttributes.imageOffset = new WorldWind.Offset(WorldWind.OFFSET_FRACTION, 0.5, WorldWind.OFFSET_FRACTION, 0.5);
const start = this.currentPosition || this.journeyData.currentPosition || {lat: 0, lng: 0};
this.wwShip = new WorldWind.Placemark(new WorldWind.Position(start.lat, start.lng, 0), true, shipAttributes);
this.wwShip.label = "MV Ocean Explorer";
this.wwShipLayer.addRenderable(this.wwShip);
console.log('Ship placemark created at:', start.lat, start.lng);
// Create ship trail
this.wwTrail = new WorldWind.Path([]);
this.wwTrail.altitudeMode = WorldWind.CLAMP_TO_GROUND;
this.wwTrail.attributes = new WorldWind.ShapeAttributes(null);
this.wwTrail.attributes.outlineColor = WorldWind.Color.CYAN;
this.wwTrail.attributes.outlineWidth = 3;
this.wwTrail.attributes.drawOutline = true;
this.wwTrail.attributes.drawInterior = false;
this.wwShipLayer.addRenderable(this.wwTrail);
// Set initial view to show the whole Earth (no automatic ship following)
console.log('Setting initial view to show whole Earth...');
// Don't automatically fly to ship position - let user explore freely
// Add a simple test shape to see if WorldWind is working
console.log('Adding test shape...');
try {
const testShape = new WorldWind.SurfaceCircle(
new WorldWind.Location(0, 0), // Center of Earth
1000000 // 1000km radius
);
testShape.attributes = new WorldWind.ShapeAttributes(null);
testShape.attributes.outlineColor = WorldWind.Color.RED;
testShape.attributes.outlineWidth = 5;
testShape.attributes.drawOutline = true;
testShape.attributes.drawInterior = false;
this.wwShipLayer.addRenderable(testShape);
console.log('Test shape added');
} catch (e) {
console.error('Error adding test shape:', e);
}
// Force a redraw
console.log('Forcing redraw...');
this.wwd.redraw();
// Handle window resize for WorldWind
window.addEventListener('resize', () => {
if (this.wwd && document.getElementById('ww-canvas').style.display !== 'none') {
const canvas = document.getElementById('ww-canvas');
const container = canvas.parentElement;
if (container) {
canvas.width = container.clientWidth;
canvas.height = container.clientHeight;
}
this.wwd.redraw();
}
});
}
async init() {
await this.loadJourneyData();
this.setupEventListeners();
this.setupUI();
// Initialize WorldWind first as the primary globe
this.initWorldWind();
// Initialize Three.js but keep it hidden
await this.loadTextures();
this.setupThreeJS();
this.createGlobe();
this.createShip();
// Show WorldWind globe by default
this.showGlobeMode();
this.hideLoadingScreen();
this.startJourney();
}
async loadJourneyData() {
// Simulated journey data - in a real app, this would come from maritime APIs
this.journeyData = {
ship: {
name: "MV Ocean Explorer",
imo: "9876543",
type: "Container Ship",
length: "366m",
width: "51m"
},
route: [
{ lat: 35.6228, lng: 139.7710, name: "Tokyo Port (Oi)", time: "2024-01-01T00:00:00Z", milestone: "Departure" },
{ lat: 35.0951, lng: 129.0390, name: "Busan Port", time: "2024-01-02T12:00:00Z", milestone: "First Stop" },
{ lat: 22.3035, lng: 114.1809, name: "Hong Kong Port", time: "2024-01-04T08:00:00Z", milestone: "Major Hub" },
{ lat: 1.2644, lng: 103.8400, name: "Singapore Port", time: "2024-01-06T14:00:00Z", milestone: "Southeast Asia" },
// Sea waypoints to avoid land crossings
{ lat: 2.5, lng: 101.0, name: "Malacca Strait" },
{ lat: 8.5, lng: 95.0, name: "Andaman Sea" },
{ lat: 5.0, lng: 79.0, name: "South of Sri Lanka" },
{ lat: -15.0, lng: 70.0, name: "Central Indian Ocean" },
{ lat: -28.0, lng: 50.0, name: "SW Indian Ocean" },
{ lat: -36.0, lng: 20.0, name: "Off Cape Agulhas" },
{ lat: -32.0, lng: 10.0, name: "South Atlantic" },
{ lat: -22.0, lng: 5.0, name: "Off Namibia" },
{ lat: 0.0, lng: 0.0, name: "Gulf of Guinea" },
{ lat: 10.0, lng: -10.0, name: "Off West Africa" },
{ lat: 46.0, lng: -6.0, name: "Bay of Biscay" },
{ lat: 50.5, lng: 0.0, name: "English Channel" },
{ lat: 51.4631, lng: 0.3336, name: "Port of Tilbury (London)", time: "2024-01-22T12:00:00Z", milestone: "Final Destination" }
],
currentPosition: { lat: 35.6762, lng: 139.6503 },
speed: 18.5,
course: 180,
eta: "2024-01-22T12:00:00Z"
};
this.milestones = this.journeyData.route.filter(point => point.milestone);
}
async loadTextures() {
const loader = new THREE.TextureLoader();
try {
const [earth, bump, specular, clouds, stars] = await Promise.all([
loader.loadAsync(this.textureUrls.earth),
loader.loadAsync(this.textureUrls.bump),
loader.loadAsync(this.textureUrls.specular),
loader.loadAsync(this.textureUrls.clouds),
loader.loadAsync(this.textureUrls.stars)
]);
this.textures.earth = earth;
this.textures.bump = bump;
this.textures.specular = specular;
this.textures.clouds = clouds;
this.textures.stars = stars;
// Improve sampling
[earth, bump, specular, clouds, stars].forEach(t => {
t.anisotropy = 8;
});
} catch (e) {
// Fallback to procedural textures if CDN fails
this.textures.earth = this.createEarthTexture();
this.textures.clouds = this.createCloudTexture();
this.textures.night = this.createNightTexture();
this.textures.bump = this.createBumpTexture();
}
}
createEarthTexture() {
const canvas = document.createElement('canvas');
canvas.width = 1024;
canvas.height = 512;
const ctx = canvas.getContext('2d');
// Create a simple Earth-like texture with continents
const gradient = ctx.createLinearGradient(0, 0, 0, 512);
gradient.addColorStop(0, '#87CEEB'); // Sky blue
gradient.addColorStop(0.3, '#4682B4'); // Steel blue
gradient.addColorStop(0.7, '#4682B4'); // Steel blue
gradient.addColorStop(1, '#191970'); // Midnight blue
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 1024, 512);
// Add continents
ctx.fillStyle = '#228B22'; // Forest green
this.drawContinent(ctx, 200, 100, 150, 80, 'North America');
this.drawContinent(ctx, 400, 200, 120, 100, 'Europe');
this.drawContinent(ctx, 600, 150, 100, 90, 'Asia');
this.drawContinent(ctx, 300, 300, 180, 120, 'Africa');
this.drawContinent(ctx, 700, 350, 150, 100, 'Australia');
this.drawContinent(ctx, 150, 400, 200, 80, 'South America');
const texture = new THREE.CanvasTexture(canvas);
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.ClampToEdgeWrapping;
return texture;
}
drawContinent(ctx, x, y, width, height, name) {
ctx.beginPath();
ctx.ellipse(x, y, width/2, height/2, 0, 0, 2 * Math.PI);
ctx.fill();
// Add some variation
ctx.fillStyle = '#32CD32'; // Lime green
ctx.beginPath();
ctx.ellipse(x + width/4, y - height/4, width/4, height/4, 0, 0, 2 * Math.PI);
ctx.fill();
ctx.fillStyle = '#228B22'; // Reset to forest green
}
createCloudTexture() {
const canvas = document.createElement('canvas');
canvas.width = 1024;
canvas.height = 512;
const ctx = canvas.getContext('2d');
// Create cloud pattern
ctx.fillStyle = 'rgba(255, 255, 255, 0.3)';
for (let i = 0; i < 50; i++) {
const x = Math.random() * 1024;
const y = Math.random() * 512;
const size = Math.random() * 100 + 50;
ctx.beginPath();
ctx.arc(x, y, size, 0, 2 * Math.PI);
ctx.fill();
}
const texture = new THREE.CanvasTexture(canvas);
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.ClampToEdgeWrapping;
return texture;
}
createNightTexture() {
const canvas = document.createElement('canvas');
canvas.width = 1024;
canvas.height = 512;
const ctx = canvas.getContext('2d');
// Dark background
ctx.fillStyle = '#000011';
ctx.fillRect(0, 0, 1024, 512);
// Add city lights
ctx.fillStyle = '#FFFF00';
for (let i = 0; i < 200; i++) {
const x = Math.random() * 1024;
const y = Math.random() * 512;
const size = Math.random() * 3 + 1;
ctx.beginPath();
ctx.arc(x, y, size, 0, 2 * Math.PI);
ctx.fill();
}
const texture = new THREE.CanvasTexture(canvas);
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.ClampToEdgeWrapping;
return texture;
}
createBumpTexture() {
const canvas = document.createElement('canvas');
canvas.width = 1024;
canvas.height = 512;
const ctx = canvas.getContext('2d');
// Create height map
const gradient = ctx.createLinearGradient(0, 0, 0, 512);
gradient.addColorStop(0, '#808080');
gradient.addColorStop(0.5, '#404040');
gradient.addColorStop(1, '#808080');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 1024, 512);
// Add mountain ranges
ctx.fillStyle = '#FFFFFF';
for (let i = 0; i < 20; i++) {
const x = Math.random() * 1024;
const y = Math.random() * 512;
const width = Math.random() * 200 + 50;
const height = Math.random() * 20 + 10;
ctx.fillRect(x, y, width, height);
}
const texture = new THREE.CanvasTexture(canvas);
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.ClampToEdgeWrapping;
return texture;
}
setupThreeJS() {
const canvas = document.getElementById('globe-canvas');
const container = canvas.parentElement;
// Scene
this.scene = new THREE.Scene();
this.scene.background = new THREE.Color(0x000011);
this.scene.fog = new THREE.Fog(0x000011, 2, 8);
// Camera
this.camera = new THREE.PerspectiveCamera(
60,
container.clientWidth / container.clientHeight,
0.01,
1000
);
this.camera.position.set(0, 0, 4);
// Renderer with enhanced settings
this.renderer = new THREE.WebGLRenderer({
canvas: canvas,
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
const initialWidth = container.clientWidth || container.offsetWidth || window.innerWidth;
const initialHeight = container.clientHeight || container.offsetHeight || window.innerHeight;
this.renderer.setSize(initialWidth, initialHeight);
this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
this.renderer.shadowMap.enabled = true;
this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
this.renderer.toneMappingExposure = 1.2;
this.renderer.outputEncoding = THREE.sRGBEncoding;
// Enhanced Controls
this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement);
this.controls.enableDamping = true;
this.controls.dampingFactor = 0.05;
this.controls.enableZoom = true;
this.controls.enablePan = false;
this.controls.minDistance = 1.8;
this.controls.maxDistance = 8;
this.controls.maxPolarAngle = Math.PI * 0.8;
this.controls.autoRotate = true;
this.controls.autoRotateSpeed = 0.5;
// Advanced Lighting Setup
this.setupAdvancedLighting();
// Handle window resize
window.addEventListener('resize', () => this.onWindowResize());
}
setupAdvancedLighting() {
// Ambient light for overall illumination
const ambientLight = new THREE.AmbientLight(0x404080, 0.3);
this.scene.add(ambientLight);
// Main directional light (sun)
const sunLight = new THREE.DirectionalLight(0xffffff, 1.5);
sunLight.position.set(10, 10, 5);
sunLight.castShadow = true;
sunLight.shadow.mapSize.width = 2048;
sunLight.shadow.mapSize.height = 2048;
sunLight.shadow.camera.near = 0.5;
sunLight.shadow.camera.far = 50;
sunLight.shadow.camera.left = -10;
sunLight.shadow.camera.right = 10;
sunLight.shadow.camera.top = 10;
sunLight.shadow.camera.bottom = -10;
this.scene.add(sunLight);
// Rim light for atmosphere
const rimLight = new THREE.DirectionalLight(0x00bcd4, 0.8);
rimLight.position.set(-5, 0, -5);
this.scene.add(rimLight);
// Point light for ship illumination
this.shipLight = new THREE.PointLight(0x00bcd4, 2, 3);
this.shipLight.position.set(0, 0, 1.02);
this.scene.add(this.shipLight);
// Hemisphere light for natural sky/ground lighting
const hemisphereLight = new THREE.HemisphereLight(0x87CEEB, 0x362d1d, 0.4);
this.scene.add(hemisphereLight);
}
createGlobe() {
// Create Earth geometry with higher detail
const geometry = new THREE.SphereGeometry(1, 128, 128);
// Create advanced Earth material with high-quality textures
const material = new THREE.MeshPhongMaterial({
map: this.textures.earth,
bumpMap: this.textures.bump,
bumpScale: 0.04,
specularMap: this.textures.specular,
specular: new THREE.Color(0x333333),
shininess: 25
});
this.globe = new THREE.Mesh(geometry, material);
this.globe.receiveShadow = true;
this.globe.castShadow = true;
this.scene.add(this.globe);
// Add multiple atmosphere layers for depth
this.createAtmosphereLayers();
// Add ocean shimmer ring (subtle)
this.createOceanWaves();
// Add clouds layer with texture
this.createClouds();
// Add skydome starfield
this.createSkyDome();
// Add orbital rings
this.createOrbitalRings();
}
createAtmosphereLayers() {
// Outer atmosphere
const outerAtmosphereGeometry = new THREE.SphereGeometry(1.08, 32, 32);
const outerAtmosphereMaterial = new THREE.MeshBasicMaterial({
color: 0x4fc3f7,
transparent: true,
opacity: 0.06,
side: THREE.BackSide,
blending: THREE.AdditiveBlending,
depthWrite: false
});
const outerAtmosphere = new THREE.Mesh(outerAtmosphereGeometry, outerAtmosphereMaterial);
this.scene.add(outerAtmosphere);
// Inner atmosphere
const innerAtmosphereGeometry = new THREE.SphereGeometry(1.03, 32, 32);
const innerAtmosphereMaterial = new THREE.MeshBasicMaterial({
color: 0x00bcd4,
transparent: true,
opacity: 0.04,
side: THREE.BackSide,
blending: THREE.AdditiveBlending,
depthWrite: false
});
const innerAtmosphere = new THREE.Mesh(innerAtmosphereGeometry, innerAtmosphereMaterial);
this.scene.add(innerAtmosphere);
}
createOceanWaves() {
const waveGeometry = new THREE.SphereGeometry(1.001, 64, 64);
const waveMaterial = new THREE.MeshPhongMaterial({
color: 0x0066cc,
transparent: true,
opacity: 0.3,
side: THREE.FrontSide
});
this.waveMesh = new THREE.Mesh(waveGeometry, waveMaterial);
this.scene.add(this.waveMesh);
}
createClouds() {
const cloudGeometry = new THREE.SphereGeometry(1.01, 64, 64);
const cloudMaterial = new THREE.MeshLambertMaterial({
map: this.textures.clouds,
transparent: true,
opacity: 0.35,
depthWrite: false
});
this.cloudMesh = new THREE.Mesh(cloudGeometry, cloudMaterial);
this.cloudMesh.renderOrder = 2;
this.scene.add(this.cloudMesh);
}
createOrbitalRings() {
// Create orbital rings around the globe
const ringGeometry = new THREE.RingGeometry(1.2, 1.25, 64);
const ringMaterial = new THREE.MeshBasicMaterial({
color: 0x00bcd4,
transparent: true,
opacity: 0.1,
side: THREE.DoubleSide
});
this.orbitalRing = new THREE.Mesh(ringGeometry, ringMaterial);
this.orbitalRing.rotation.x = Math.PI / 2;
this.scene.add(this.orbitalRing);
}
createSkyDome() {
if (!this.textures.stars) return;
const skyGeo = new THREE.SphereGeometry(50, 32, 32);
const skyMat = new THREE.MeshBasicMaterial({
map: this.textures.stars,
side: THREE.BackSide,
depthWrite: false
});
const sky = new THREE.Mesh(skyGeo, skyMat);
sky.renderOrder = 0;
this.scene.add(sky);
}
createNebula() {
const nebulaGeometry = new THREE.SphereGeometry(25, 32, 32);
const nebulaMaterial = new THREE.MeshBasicMaterial({
color: 0x4400aa,
transparent: true,
opacity: 0.02,
side: THREE.BackSide
});
const nebula = new THREE.Mesh(nebulaGeometry, nebulaMaterial);
this.scene.add(nebula);
}
createShip() {
// Create detailed ship model
this.ship = new THREE.Group();
// Ship hull
const hullGeometry = new THREE.BoxGeometry(0.03, 0.015, 0.08);
const hullMaterial = new THREE.MeshPhongMaterial({
color: 0xff6b35,
shininess: 150,
specular: 0x333333
});
const hull = new THREE.Mesh(hullGeometry, hullMaterial);
hull.castShadow = true;
this.ship.add(hull);
// Ship deck
const deckGeometry = new THREE.BoxGeometry(0.025, 0.005, 0.06);
const deckMaterial = new THREE.MeshPhongMaterial({
color: 0x2c3e50,
shininess: 100
});
const deck = new THREE.Mesh(deckGeometry, deckMaterial);
deck.position.y = 0.01;
this.ship.add(deck);
// Ship containers (simplified)
for (let i = 0; i < 3; i++) {
const containerGeometry = new THREE.BoxGeometry(0.02, 0.02, 0.02);
const containerMaterial = new THREE.MeshPhongMaterial({
color: 0x3498db,
shininess: 80
});
const container = new THREE.Mesh(containerGeometry, containerMaterial);
container.position.set(0, 0.02 + i * 0.025, -0.02 + i * 0.01);
container.castShadow = true;
this.ship.add(container);
}
// Ship lights
const lightGeometry = new THREE.SphereGeometry(0.003, 8, 8);
const lightMaterial = new THREE.MeshBasicMaterial({
color: 0xffff00,
emissive: 0xffff00
});
const portLight = new THREE.Mesh(lightGeometry, lightMaterial);
portLight.position.set(-0.012, 0.01, 0.03);
this.ship.add(portLight);
const starboardLight = new THREE.Mesh(lightGeometry, lightMaterial);
starboardLight.position.set(0.012, 0.01, 0.03);
this.ship.add(starboardLight);
this.ship.position.set(0, 0, 1.02);
this.scene.add(this.ship);
// Create enhanced ship trail with particles
this.createShipTrail();
// Create wake effect
this.createWakeEffect();
}
createShipTrail() {
const trailGeometry = new THREE.BufferGeometry();
const trailMaterial = new THREE.LineBasicMaterial({
color: 0x00bcd4,
transparent: true,
opacity: 0.8,
linewidth: 2
});
this.shipTrail = new THREE.Line(trailGeometry, trailMaterial);
this.scene.add(this.shipTrail);
// Create particle trail
const particleCount = 50;
const particleGeometry = new THREE.BufferGeometry();
const particlePositions = new Float32Array(particleCount * 3);
const particleColors = new Float32Array(particleCount * 3);
const particleSizes = new Float32Array(particleCount);
for (let i = 0; i < particleCount; i++) {
const i3 = i * 3;
particlePositions[i3] = 0;
particlePositions[i3 + 1] = 0;
particlePositions[i3 + 2] = 0;
particleColors[i3] = 0.0; // R
particleColors[i3 + 1] = 0.7; // G
particleColors[i3 + 2] = 1.0; // B
particleSizes[i] = Math.random() * 0.01 + 0.005;
}
particleGeometry.setAttribute('position', new THREE.BufferAttribute(particlePositions, 3));
particleGeometry.setAttribute('color', new THREE.BufferAttribute(particleColors, 3));
particleGeometry.setAttribute('size', new THREE.BufferAttribute(particleSizes, 1));
const particleMaterial = new THREE.PointsMaterial({
size: 0.01,
transparent: true,
opacity: 0.6,
vertexColors: true,
sizeAttenuation: true
});
this.shipParticles = new THREE.Points(particleGeometry, particleMaterial);
this.scene.add(this.shipParticles);
}
createWakeEffect() {
// Create wake rings behind the ship
const wakeGeometry = new THREE.RingGeometry(0.01, 0.05, 16);
const wakeMaterial = new THREE.MeshBasicMaterial({
color: 0x00bcd4,
transparent: true,
opacity: 0.3,
side: THREE.DoubleSide
});
this.wakeRing = new THREE.Mesh(wakeGeometry, wakeMaterial);
this.wakeRing.rotation.x = Math.PI / 2;
this.scene.add(this.wakeRing);
}
setupEventListeners() {
// Play/Pause button
document.getElementById('playPauseBtn').addEventListener('click', () => {
this.togglePlayPause();
});
// Reset button
document.getElementById('resetBtn').addEventListener('click', () => {
this.resetJourney();
});
// Fullscreen button
document.getElementById('fullscreenBtn').addEventListener('click', () => {
this.toggleFullscreen();
});
// Map mode buttons
document.querySelectorAll('.mode-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
const mode = e.currentTarget.dataset.mode;
if (mode) this.switchMapMode(mode);
});
});
// Start Live button
const startLiveBtn = document.getElementById('startLiveBtn');
if (startLiveBtn) {
startLiveBtn.addEventListener('click', () => {
const mmsi = (document.getElementById('mmsiInput')?.value || '').trim();
this.startLiveStream(mmsi);
});
}
// Globe zoom controls (WorldWind or Three.js fallback)
const zoomInBtn = document.getElementById('zoomInBtn');
const zoomOutBtn = document.getElementById('zoomOutBtn');
if (zoomInBtn && zoomOutBtn) {
zoomInBtn.addEventListener('click', () => this.zoomGlobe(1));
zoomOutBtn.addEventListener('click', () => this.zoomGlobe(-1));
}
// Follow ship button
const followShipBtn = document.getElementById('followShipBtn');
if (followShipBtn) {
followShipBtn.addEventListener('click', () => {
this.toggleFollowShip();
});
}
// Modal close
document.getElementById('closeModal').addEventListener('click', () => {
this.closeModal();
});
// Click outside modal to close
window.addEventListener('click', (event) => {
const modal = document.getElementById('milestoneModal');
if (event.target === modal) {
this.closeModal();
}
});
}
zoomGlobe(direction) {
// If WorldWind is active
const wwCanvas = document.getElementById('ww-canvas');
if (wwCanvas && wwCanvas.style.display !== 'none' && this.wwd) {
const nav = this.wwd.navigator; // has range (zoom) in meters
const factor = direction > 0 ? 0.7 : 1.3; // zoom in or out
nav.range = Math.max(100000, Math.min(5e7, nav.range * factor));
this.wwd.redraw();
return;
}
// Three.js fallback
const delta = direction > 0 ? -0.3 : 0.3;
const newZ = THREE.MathUtils.clamp(this.camera.position.z + delta, 1.8, 8);
this.camera.position.z = newZ;
}
toggleFollowShip() {
this.followShip = !this.followShip;
const followBtn = document.getElementById('followShipBtn');
if (this.followShip) {
followBtn.classList.add('active');
followBtn.title = 'Stop Following Ship';
// If ship position exists, fly to it
if (this.currentPosition && this.wwd) {
const goTo = new WorldWind.GoToAnimator(this.wwd);
goTo.goTo(new WorldWind.Location(this.currentPosition.lat, this.currentPosition.lng, 1000000));
}
} else {
followBtn.classList.remove('active');
followBtn.title = 'Follow Ship';
}
}
startLiveStream(mmsi) {
try {
if (this.eventSource) {
this.eventSource.close();
this.eventSource = null;
}
} catch {}
const url = `/api/ship/stream${mmsi ? `?mmsi=${encodeURIComponent(mmsi)}` : ''}`;
const es = new EventSource(url);
this.eventSource = es;
// If a known MMSI is provided, switch the planned route and rebuild UI
if (mmsi) {
this.setRouteForMMSI(mmsi);
// setRouteForMMSI now handles all the reset logic, just need to update Leaflet
if (this.leafletMap) {
this.rebuildLeafletRoute();
this.updateStartEndMarkers();
}
}
es.onmessage = (ev) => {
try {
const data = JSON.parse(ev.data);
if (data.type === 'position' && typeof data.lat === 'number' && typeof data.lng === 'number') {
// Update UI stats
if (typeof data.speed === 'number') this.journeyData.speed = data.speed;
if (typeof data.course === 'number') this.journeyData.course = data.course;
// Move ship to new live position
this.updateShipPosition({ lat: data.lat, lng: data.lng });
}
} catch {}
};
es.onerror = () => {
// Keep connection attempts minimal; SSE will auto-reconnect.
};
}
// Hardcoded MMSI → route presets (realistic corridors over water)
setRouteForMMSI(mmsi) {
const presets = {
// Hamburg → Gibraltar → Suez → Singapore → Shanghai
'211331640': [
{ lat: 53.5461, lng: 9.9662, name: 'Hamburg', milestone: 'Journey Begins' },
{ lat: 51.0, lng: 2.0, name: 'North Sea' },
{ lat: 48.7, lng: -4.5, name: 'Off Brest' },
{ lat: 36.0, lng: -5.5, name: 'Strait of Gibraltar', milestone: 'Mediterranean Entry' },
{ lat: 31.2, lng: 32.3, name: 'Port Said (Suez North)' },
{ lat: 29.9, lng: 32.55, name: 'Suez Canal', milestone: 'Canal Transit' },
{ lat: 12.5, lng: 43.2, name: 'Bab-el-Mandeb' },
{ lat: 15.0, lng: 46.0, name: 'Gulf of Aden' },
{ lat: 9.0, lng: 70.0, name: 'Arabian Sea' },
{ lat: 5.0, lng: 90.0, name: 'Bay of Bengal' },
{ lat: 1.26, lng: 103.84, name: 'Singapore', milestone: 'Major Hub' },
{ lat: 10.0, lng: 112.0, name: 'South China Sea' },
{ lat: 22.5, lng: 120.5, name: 'Taiwan Strait' },
{ lat: 31.2304, lng: 121.4737, name: 'Shanghai', milestone: 'Final Destination' }
],
// LA → Panama Canal → Miami → New York (US MMSI range 366-369)
'366982000': [
{ lat: 33.7329, lng: -118.2710, name: 'Port of LA', milestone: 'Journey Begins' },
{ lat: 25.0, lng: -112.0, name: 'Off Baja' },
{ lat: 8.95, lng: -79.55, name: 'Panama Canal (Pacific)' },
{ lat: 9.35, lng: -79.9, name: 'Panama Canal (Atlantic)', milestone: 'Canal Transit' },
{ lat: 20.0, lng: -78.0, name: 'Caribbean Sea' },
{ lat: 25.7781, lng: -80.1794, name: 'PortMiami', milestone: 'Major Hub' },
{ lat: 31.0, lng: -76.0, name: 'Off Carolinas' },
{ lat: 40.6711, lng: -74.0456, name: 'Port of NY/NJ', milestone: 'Final Destination' }
],
// Default (Tokyo → Busan → Hong Kong → Singapore → Cape → London)
'DEFAULT': [
{ lat: 35.6228, lng: 139.7710, name: 'Tokyo Port (Oi)', milestone: 'Journey Begins' },
{ lat: 35.0951, lng: 129.0390, name: 'Busan Port', milestone: 'First Stop' },
{ lat: 22.3035, lng: 114.1809, name: 'Hong Kong Port', milestone: 'Major Hub' },
{ lat: 1.2644, lng: 103.8400, name: 'Singapore Port', milestone: 'Southeast Gateway' },
{ lat: -15.0, lng: 70.0, name: 'Central Indian Ocean' },
{ lat: -36.0, lng: 20.0, name: 'Off Cape Agulhas', milestone: 'Rounding Africa' },
{ lat: -32.0, lng: 10.0, name: 'South Atlantic' },
{ lat: -22.0, lng: 5.0, name: 'Off Namibia' },
{ lat: 0.0, lng: 0.0, name: 'Gulf of Guinea' },
{ lat: 10.0, lng: -10.0, name: 'Off West Africa' },
{ lat: 46.0, lng: -6.0, name: 'Bay of Biscay' },
{ lat: 50.5, lng: 0.0, name: 'English Channel' },
{ lat: 51.4631, lng: 0.3336, name: 'Port of Tilbury (London)', milestone: 'Final Destination' }
]
};
const route = presets[mmsi] || presets['DEFAULT'];
if (route && route.length) {
// Update the route
this.journeyData.route = route;
this.journeyData.ship.mmsi = mmsi;
// Reset journey to the beginning of the new route
this.currentJourneyIndex = 0;
this.isPlaying = true;
// Move ship to the start of the new route
const startPoint = route[0];
this.currentPosition = startPoint;
this.updateShipPosition(startPoint);
// Update UI elements
this.updateProgress(0);
this.createTimeline();
this.updateTimeline();
// Update play button
document.getElementById('playPauseBtn').textContent = '⏸️ Pause';
// Start the journey from the beginning
this.startShipMovement();
}
}
rebuildLeafletRoute() {
if (!this.leafletMap) return;
if (this.leafletRoute) {
try { this.leafletMap.removeLayer(this.leafletRoute); } catch (_) {}
this.leafletRoute = null;
}
const route = this.journeyData?.route || [];
const densify = (a, b, steps = 96) => {
const pts = [];
for (let i = 0; i <= steps; i++) {
const t = i / steps;
const lat = a.lat + (b.lat - a.lat) * t;
const lng = a.lng + (b.lng - a.lng) * t;
pts.push([lat, lng]);
}
return pts;
};
let latlngs = [];
for (let i = 0; i < route.length - 1; i++) {
latlngs = latlngs.concat(densify(route[i], route[i + 1]));
}
if (window.L && L.polyline && window.antPath) {
this.leafletRoute = window.antPath(latlngs, {
paused: false,
reverse: false,
delay: 1200,
dashArray: [15, 25],
weight: 4,
color: '#00bcd4',
pulseColor: '#4fc3f7',
opacity: 0.9
}).addTo(this.leafletMap);
} else {
this.leafletRoute = L.polyline(latlngs, { color: '#00bcd4', weight: 4, opacity: 0.9 }).addTo(this.leafletMap);
}
if (latlngs.length) this.leafletMap.fitBounds(this.leafletRoute.getBounds(), { padding: [30, 30] });
}
setupUI() {
// Update ship info
document.getElementById('shipName').textContent = this.journeyData.ship.name;
// Create timeline
this.createTimeline();
// Update initial position
this.updateShipPosition(this.journeyData.currentPosition);
}
createTimeline() {
const timeline = document.getElementById('timeline');
timeline.innerHTML = '';
this.journeyData.route.forEach((point, index) => {
const timelineItem = document.createElement('div');
timelineItem.className = 'timeline-item';
if (index === 0) timelineItem.classList.add('current');