-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
972 lines (821 loc) · 37 KB
/
Copy pathscript.js
File metadata and controls
972 lines (821 loc) · 37 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
class SolarSystem {
constructor() {
console.log('SolarSystem constructor called');
this.scene = null;
this.camera = null;
this.renderer = null;
this.controls = null;
this.planets = [];
this.sun = null;
this.clock = new THREE.Clock();
this.paused = false;
this.isDarkTheme = true;
this.masterSpeed = 1.0;
this.raycaster = new THREE.Raycaster();
this.mouse = new THREE.Vector2();
this.selectedPlanet = null;
this.orbitLines = [];
this.asteroidBelt = null;
// Initialize texture loader
this.textureLoader = new THREE.TextureLoader();
console.log('Setting up planet data...');
this.planetData = [
{ name: 'Mercury', distance: 8, size: 0.4, color: 0x8C7853, speed: 4.15, tilt: 0.1, texture: 'assests/2k_mercury.png', type: 'rocky' },
{ name: 'Venus', distance: 12, size: 0.9, color: 0xFFC649, speed: 1.62, tilt: 177.4, texture: 'assests/2k_venus_surface.png', type: 'rocky' },
{ name: 'Earth', distance: 16, size: 1.0, color: 0x6B93D6, speed: 1.0, tilt: 23.4, texture: 'assests/2k_earth_daymap.png', type: 'rocky' },
{ name: 'Mars', distance: 20, size: 0.5, color: 0xC1440E, speed: 0.53, tilt: 25.2, texture: 'assests/2k_mars.png', type: 'rocky' },
{ name: 'Jupiter', distance: 28, size: 2.2, color: 0xD8CA9D, speed: 0.084, tilt: 3.1, texture: 'assests/2k_jupiter.png', type: 'gas' },
{ name: 'Saturn', distance: 36, size: 1.9, color: 0xFAD5A5, speed: 0.034, tilt: 26.7, texture: 'assests/2k_saturn.png', type: 'gas' },
{ name: 'Uranus', distance: 44, size: 1.6, color: 0x4FD0E7, speed: 0.012, tilt: 97.8, texture: 'assests/2k_uranus.png', type: 'ice' },
{ name: 'Neptune', distance: 52, size: 1.5, color: 0x4B70DD, speed: 0.006, tilt: 28.3, texture: 'assests/2k_neptune.png', type: 'ice' }
];
console.log('Calling init...');
this.init();
console.log('Calling setupEventListeners...');
this.setupEventListeners();
// Make the solar system available globally for UI integration
window.solarSystem = this;
}
init() {
console.log('Initializing Three.js scene...');
// Scene setup
this.scene = new THREE.Scene();
// Load realistic space background
const spaceTexture = this.textureLoader.load('assests/2k_stars_milky_way.jpg');
this.scene.background = spaceTexture;
console.log('Scene created');
// Camera setup
this.camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
this.camera.position.set(0, 15, 25); // Move camera closer
this.camera.lookAt(0, 0, 0);
console.log('Camera created at position:', this.camera.position);
console.log('Camera looking at:', new THREE.Vector3(0, 0, 0));
// Renderer setup
const canvas = document.getElementById('solar-system');
console.log('Canvas element:', canvas);
if (!canvas) {
throw new Error('Canvas element not found!');
}
this.renderer = new THREE.WebGLRenderer({
canvas: canvas,
antialias: true,
alpha: true
});
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.renderer.shadowMap.enabled = true;
this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
this.renderer.setPixelRatio(window.devicePixelRatio);
console.log('Renderer created with size:', window.innerWidth, 'x', window.innerHeight);
console.log('Canvas style after renderer setup:', canvas.style.cssText);
this.setupControls();
console.log('Creating stars...');
this.createEnhancedStars();
console.log('Creating sun...');
this.createEnhancedSun();
console.log('Creating planets...');
this.createEnhancedPlanets();
console.log('Creating asteroid belt...');
this.createAsteroidBelt();
console.log('Setting up UI...');
this.setupUI();
console.log('Setting up lighting...');
this.setupEnhancedLighting();
console.log('Initializing tooltips...');
this.initializeTooltips();
console.log('Hiding loading indicator...');
this.hideLoadingIndicator();
console.log('Starting animation...');
this.animate();
console.log('Init complete!');
}
addTestCube() {
const geometry = new THREE.BoxGeometry(5, 5, 5);
const material = new THREE.MeshLambertMaterial({
color: 0x00ff00,
emissive: 0x00ff00,
emissiveIntensity: 0.5
});
const cube = new THREE.Mesh(geometry, material);
cube.position.set(10, 0, 0);
this.scene.add(cube);
console.log('Test cube added at position (10, 0, 0)');
}
hideLoadingIndicator() {
const loadingIndicator = document.querySelector('.loading-indicator');
if (loadingIndicator) {
loadingIndicator.style.display = 'none';
console.log('Loading indicator hidden');
} else {
console.log('Loading indicator not found');
}
// Also try to hide by ID in case it exists
const loadingById = document.getElementById('loading-indicator');
if (loadingById) {
loadingById.style.display = 'none';
console.log('Loading indicator (by ID) hidden');
}
}
setupControls() {
// Enhanced orbit controls implementation with improved camera movement
let isMouseDown = false;
let mouseX = 0;
let mouseY = 0;
let targetX = 0;
let targetY = 0;
let windowHalfX = window.innerWidth / 2;
let windowHalfY = window.innerHeight / 2;
const canvas = this.renderer.domElement;
canvas.addEventListener('mousedown', (e) => {
isMouseDown = true;
mouseX = e.clientX - windowHalfX;
mouseY = e.clientY - windowHalfY;
});
canvas.addEventListener('mousemove', (e) => {
if (isMouseDown) {
targetX = (mouseX - (e.clientX - windowHalfX)) * 0.01; // Increased sensitivity
targetY = (mouseY - (e.clientY - windowHalfY)) * 0.01;
// Smooth camera rotation around the solar system
const spherical = new THREE.Spherical();
spherical.setFromVector3(this.camera.position);
spherical.theta += targetX;
spherical.phi += targetY;
spherical.phi = Math.max(0.1, Math.min(Math.PI - 0.1, spherical.phi));
this.camera.position.setFromSpherical(spherical);
this.camera.lookAt(0, 0, 0);
}
// Update mouse position for raycasting
this.mouse.x = (e.clientX / window.innerWidth) * 2 - 1;
this.mouse.y = -(e.clientY / window.innerHeight) * 2 + 1;
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
});
canvas.addEventListener('wheel', (e) => {
e.preventDefault();
const scale = e.deltaY > 0 ? 1.1 : 0.9;
this.camera.position.multiplyScalar(scale);
this.camera.position.clampLength(5, 300); // Allow closer and farther views
});
// Click to select planets
canvas.addEventListener('click', (e) => {
this.handlePlanetSelection();
});
// Enhanced touch controls for mobile
let touchStartX = 0;
let touchStartY = 0;
let touchDistance = 0;
canvas.addEventListener('touchstart', (e) => {
e.preventDefault();
if (e.touches.length === 1) {
const touch = e.touches[0];
touchStartX = touch.clientX;
touchStartY = touch.clientY;
} else if (e.touches.length === 2) {
const touch1 = e.touches[0];
const touch2 = e.touches[1];
touchDistance = Math.sqrt(
Math.pow(touch2.clientX - touch1.clientX, 2) +
Math.pow(touch2.clientY - touch1.clientY, 2)
);
}
});
canvas.addEventListener('touchmove', (e) => {
e.preventDefault();
if (e.touches.length === 1) {
const touch = e.touches[0];
const deltaX = (touchStartX - touch.clientX) * 0.02;
const deltaY = (touchStartY - touch.clientY) * 0.02;
const spherical = new THREE.Spherical();
spherical.setFromVector3(this.camera.position);
spherical.theta += deltaX;
spherical.phi += deltaY;
spherical.phi = Math.max(0.1, Math.min(Math.PI - 0.1, spherical.phi));
this.camera.position.setFromSpherical(spherical);
this.camera.lookAt(0, 0, 0);
touchStartX = touch.clientX;
touchStartY = touch.clientY;
} else if (e.touches.length === 2) {
const touch1 = e.touches[0];
const touch2 = e.touches[1];
const currentDistance = Math.sqrt(
Math.pow(touch2.clientX - touch1.clientX, 2) +
Math.pow(touch2.clientY - touch1.clientY, 2)
);
if (touchDistance > 0) {
const scale = touchDistance / currentDistance;
this.camera.position.multiplyScalar(scale);
this.camera.position.clampLength(5, 300);
}
touchDistance = currentDistance;
}
});
}
createEnhancedStars() {
// Create multiple star fields for depth
const starFields = [
{ count: 1000, distance: 300, size: 0.5, opacity: 0.8 },
{ count: 800, distance: 200, size: 0.3, opacity: 0.6 },
{ count: 600, distance: 100, size: 0.2, opacity: 0.4 }
];
starFields.forEach(field => {
const starGeometry = new THREE.BufferGeometry();
const positions = new Float32Array(field.count * 3);
const colors = new Float32Array(field.count * 3);
const sizes = new Float32Array(field.count);
for (let i = 0; i < field.count; i++) {
const i3 = i * 3;
// Position
positions[i3] = (Math.random() - 0.5) * field.distance;
positions[i3 + 1] = (Math.random() - 0.5) * field.distance;
positions[i3 + 2] = (Math.random() - 0.5) * field.distance;
// Color variation
const colorVariation = 0.5 + Math.random() * 0.5;
colors[i3] = colorVariation;
colors[i3 + 1] = colorVariation;
colors[i3 + 2] = colorVariation;
// Size variation
sizes[i] = field.size * (0.5 + Math.random() * 0.5);
}
starGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
starGeometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
starGeometry.setAttribute('size', new THREE.BufferAttribute(sizes, 1));
const starMaterial = new THREE.PointsMaterial({
size: field.size,
transparent: true,
opacity: field.opacity,
vertexColors: true,
blending: THREE.AdditiveBlending,
sizeAttenuation: false
});
const stars = new THREE.Points(starGeometry, starMaterial);
this.scene.add(stars);
});
}
createEnhancedSun() {
// Main sun sphere - Made much larger for realism
const sunGeometry = new THREE.SphereGeometry(5, 64, 32); // Increased from 3 to 5
const sunMaterial = new THREE.MeshLambertMaterial({
color: 0xFFD700,
emissive: 0xFFD700,
emissiveIntensity: 1.0
});
this.sun = new THREE.Mesh(sunGeometry, sunMaterial);
this.sun.name = 'Sun';
this.sun.position.set(0, 0, 0); // Explicitly set position
this.scene.add(this.sun);
console.log('Sun created and added to scene at position:', this.sun.position);
// Enhanced sun corona layers - Scaled proportionally
const coronaLayers = [
{ size: 5.5, opacity: 0.4, color: 0xFFD700 },
{ size: 6.0, opacity: 0.2, color: 0xFFA500 },
{ size: 6.5, opacity: 0.1, color: 0xFF4500 }
];
coronaLayers.forEach(layer => {
const coronaGeometry = new THREE.SphereGeometry(layer.size, 32, 16);
const coronaMaterial = new THREE.MeshBasicMaterial({
color: layer.color,
transparent: true,
opacity: layer.opacity,
blending: THREE.AdditiveBlending
});
const corona = new THREE.Mesh(coronaGeometry, coronaMaterial);
this.sun.add(corona);
});
// Sun flare particles - Increased range
const flareGeometry = new THREE.BufferGeometry();
const flarePositions = new Float32Array(100 * 3);
const flareSizes = new Float32Array(100);
for (let i = 0; i < 100; i++) {
const i3 = i * 3;
const radius = 6 + Math.random() * 3; // Increased from 4 + 2 to 6 + 3
const theta = Math.random() * Math.PI * 2;
const phi = Math.random() * Math.PI;
flarePositions[i3] = radius * Math.sin(phi) * Math.cos(theta);
flarePositions[i3 + 1] = radius * Math.sin(phi) * Math.sin(theta);
flarePositions[i3 + 2] = radius * Math.cos(phi);
flareSizes[i] = Math.random() * 0.15 + 0.1; // Slightly bigger flares
}
flareGeometry.setAttribute('position', new THREE.BufferAttribute(flarePositions, 3));
flareGeometry.setAttribute('size', new THREE.BufferAttribute(flareSizes, 1));
const flareMaterial = new THREE.PointsMaterial({
color: 0xFFD700,
size: 0.15,
transparent: true,
opacity: 0.6,
blending: THREE.AdditiveBlending
});
const flares = new THREE.Points(flareGeometry, flareMaterial);
this.sun.add(flares);
}
createEnhancedPlanets() {
this.planetData.forEach((data, index) => {
// Enhanced planet geometry with more detail
const planetGeometry = new THREE.SphereGeometry(data.size, 64, 32);
// Create realistic materials based on planet type and textures
let planetMaterial;
if (data.texture) {
const planetTexture = this.textureLoader.load(data.texture);
// Ensure correct color space for accurate lighting (Three.js r152+)
if (planetTexture.colorSpace !== undefined) {
planetTexture.colorSpace = THREE.SRGBColorSpace;
} else {
planetTexture.encoding = THREE.sRGBEncoding;
}
planetTexture.wrapS = THREE.RepeatWrapping;
planetTexture.wrapT = THREE.RepeatWrapping;
planetTexture.minFilter = THREE.LinearFilter;
planetTexture.magFilter = THREE.LinearFilter;
// Use MeshBasicMaterial to ensure planet is always fully visible (no black side)
planetMaterial = new THREE.MeshBasicMaterial({
map: planetTexture,
color: 0xffffff
});
} else {
// Fallback to enhanced colored materials for planets without textures (Jupiter)
if (data.type === 'rocky') {
planetMaterial = new THREE.MeshLambertMaterial({
color: data.color,
// Ensure rocky planets without textures are well-lit
emissive: new THREE.Color(data.color).multiplyScalar(0.15),
emissiveIntensity: 0.1
});
} else if (data.type === 'gas') {
planetMaterial = new THREE.MeshLambertMaterial({
color: data.color,
// Gas giants should be bright and vibrant
emissive: new THREE.Color(data.color).multiplyScalar(0.4),
emissiveIntensity: 0.25
});
} else if (data.type === 'ice') {
planetMaterial = new THREE.MeshLambertMaterial({
color: data.color,
// Ice giants should have reflective glow
emissive: new THREE.Color(data.color).multiplyScalar(0.2),
emissiveIntensity: 0.15
});
}
}
const planet = new THREE.Mesh(planetGeometry, planetMaterial);
planet.name = data.name;
planet.userData = {
...data,
angle: Math.random() * Math.PI * 2,
originalSpeed: data.speed,
currentSpeed: data.speed,
orbitRadius: data.distance
};
// Set initial position
planet.position.x = Math.cos(planet.userData.angle) * data.distance;
planet.position.z = Math.sin(planet.userData.angle) * data.distance;
// Add planet tilt
planet.rotation.z = THREE.MathUtils.degToRad(data.tilt);
// Enable shadows
planet.castShadow = true;
planet.receiveShadow = true;
// Create enhanced orbit visualization
const orbitGeometry = new THREE.RingGeometry(data.distance - 0.1, data.distance + 0.1, 64);
const orbitMaterial = new THREE.MeshBasicMaterial({
color: 0x444444,
transparent: true,
opacity: 0.2,
side: THREE.DoubleSide
});
const orbit = new THREE.Mesh(orbitGeometry, orbitMaterial);
orbit.rotation.x = -Math.PI / 2;
this.scene.add(orbit);
this.orbitLines.push(orbit);
// Add atmospheric glow for gas giants
if (data.type === 'gas') {
const glowGeometry = new THREE.SphereGeometry(data.size * 1.1, 32, 16);
const glowMaterial = new THREE.MeshBasicMaterial({
color: data.color,
transparent: true,
opacity: 0.3,
blending: THREE.AdditiveBlending
});
const glow = new THREE.Mesh(glowGeometry, glowMaterial);
planet.add(glow);
}
// Add Saturn's rings
if (data.name === 'Saturn') {
const ringGeometry = new THREE.RingGeometry(data.size * 1.2, data.size * 2.0, 64);
const ringMaterial = new THREE.MeshLambertMaterial({
color: 0xCCCCCC,
transparent: true,
opacity: 0.7,
side: THREE.DoubleSide
});
const rings = new THREE.Mesh(ringGeometry, ringMaterial);
rings.rotation.x = -Math.PI / 2;
rings.rotation.z = THREE.MathUtils.degToRad(26.7); // Saturn's ring tilt
planet.add(rings);
}
// Add Earth's moon
if (data.name === 'Earth') {
const moonGeometry = new THREE.SphereGeometry(0.27, 32, 16);
const moonMaterial = new THREE.MeshPhongMaterial({
color: 0x888888,
shininess: 5,
specular: 0x111111
});
const moon = new THREE.Mesh(moonGeometry, moonMaterial);
moon.position.set(2, 0, 0);
moon.name = 'Moon';
moon.castShadow = true;
moon.receiveShadow = true;
planet.add(moon);
}
// Add moons to Jupiter
if (data.name === 'Jupiter') {
const moonNames = ['Io', 'Europa', 'Ganymede', 'Callisto'];
const moonDistances = [2.5, 3.0, 3.5, 4.0];
const moonSizes = [0.1, 0.09, 0.15, 0.13];
const moonColors = [0xFFFF99, 0xCCCCFF, 0x999999, 0x666666];
moonNames.forEach((moonName, i) => {
const moonGeometry = new THREE.SphereGeometry(moonSizes[i], 16, 12);
const moonMaterial = new THREE.MeshPhongMaterial({
color: moonColors[i],
shininess: 10
});
const moon = new THREE.Mesh(moonGeometry, moonMaterial);
moon.position.set(moonDistances[i], 0, 0);
moon.name = moonName;
moon.castShadow = true;
moon.receiveShadow = true;
planet.add(moon);
});
}
this.scene.add(planet);
this.planets.push(planet);
console.log(`Planet ${data.name} created at position:`, planet.position);
});
}
createAsteroidBelt() {
const asteroidCount = 500;
const asteroidGeometry = new THREE.BufferGeometry();
const positions = new Float32Array(asteroidCount * 3);
const colors = new Float32Array(asteroidCount * 3);
const sizes = new Float32Array(asteroidCount);
for (let i = 0; i < asteroidCount; i++) {
const i3 = i * 3;
const radius = 22 + Math.random() * 4;
const angle = Math.random() * Math.PI * 2;
const height = (Math.random() - 0.5) * 2;
positions[i3] = Math.cos(angle) * radius;
positions[i3 + 1] = height;
positions[i3 + 2] = Math.sin(angle) * radius;
const gray = 0.3 + Math.random() * 0.4;
colors[i3] = gray;
colors[i3 + 1] = gray;
colors[i3 + 2] = gray;
sizes[i] = Math.random() * 0.05 + 0.02;
}
asteroidGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
asteroidGeometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
asteroidGeometry.setAttribute('size', new THREE.BufferAttribute(sizes, 1));
const asteroidMaterial = new THREE.PointsMaterial({
size: 0.05,
transparent: true,
vertexColors: true,
opacity: 0.8
});
this.asteroidBelt = new THREE.Points(asteroidGeometry, asteroidMaterial);
this.scene.add(this.asteroidBelt);
}
setupEnhancedLighting() {
// Strong ambient light specifically to eliminate dark spots on planet surfaces
const ambientLight = new THREE.AmbientLight(0xffffff, 1.8);
this.scene.add(ambientLight);
// Main sun light - reduced intensity since we're using more ambient light
const sunLight = new THREE.PointLight(0xFFFFFF, 2.5, 400);
sunLight.position.set(0, 0, 0);
sunLight.castShadow = false;
this.scene.add(sunLight);
// Multiple directional lights to ensure planet surfaces are well-lit from all angles
const directionalLight1 = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight1.position.set(50, 50, 50);
this.scene.add(directionalLight1);
const directionalLight2 = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight2.position.set(-50, 50, -50);
this.scene.add(directionalLight2);
const directionalLight3 = new THREE.DirectionalLight(0xffffff, 0.6);
directionalLight3.position.set(0, -50, 0);
this.scene.add(directionalLight3);
// Hemisphere light for even more uniform lighting
const hemisphereLight = new THREE.HemisphereLight(0xffffff, 0x888888, 1.0);
this.scene.add(hemisphereLight);
// After this.scene.add(hemisphereLight); in setupEnhancedLighting, add a camera-following fill light
this.cameraFillLight = new THREE.PointLight(0xffffff, 0.25, 1000);
this.scene.add(this.cameraFillLight);
console.log('Enhanced lighting setup complete - optimized to eliminate planet surface dark spots');
}
setupUI() {
// Legacy UI setup - now handled by ui-controls.js
// This method is kept for compatibility but functionality is moved to the new UI system
// Setup event listeners for the new UI elements
this.setupNewUIEventListeners();
}
setupNewUIEventListeners() {
// Master speed control
const masterSpeedSlider = document.getElementById('masterSpeed');
const masterSpeedValue = document.getElementById('masterSpeedValue');
if (masterSpeedSlider && masterSpeedValue) {
masterSpeedSlider.addEventListener('input', (e) => {
this.masterSpeed = parseFloat(e.target.value);
masterSpeedValue.textContent = `${this.masterSpeed.toFixed(1)}x`;
});
}
// Pause/Play button
const pauseBtn = document.getElementById('pauseBtn');
if (pauseBtn) {
pauseBtn.addEventListener('click', () => {
this.paused = !this.paused;
const icon = pauseBtn.querySelector('i');
const text = pauseBtn.querySelector('span');
if (this.paused) {
icon.className = 'fas fa-play';
text.textContent = 'Play';
pauseBtn.classList.remove('primary');
} else {
icon.className = 'fas fa-pause';
text.textContent = 'Pause';
pauseBtn.classList.add('primary');
}
});
}
// Reset button
const resetBtn = document.getElementById('resetBtn');
if (resetBtn) {
resetBtn.addEventListener('click', () => {
this.resetSimulation();
});
}
// Theme toggle button
const themeBtn = document.getElementById('themeBtn');
if (themeBtn) {
themeBtn.addEventListener('click', () => {
this.toggleTheme();
const icon = themeBtn.querySelector('i');
const text = themeBtn.querySelector('span');
if (this.isDarkTheme) {
icon.className = 'fas fa-sun';
text.textContent = 'Light Theme';
} else {
icon.className = 'fas fa-moon';
text.textContent = 'Dark Theme';
}
});
}
}
setupEventListeners() {
// Window resize
window.addEventListener('resize', () => {
this.onWindowResize();
});
// Mouse events for planet interaction
const canvas = this.renderer.domElement;
canvas.addEventListener('click', (event) => {
// Calculate mouse position in normalized device coordinates
const rect = canvas.getBoundingClientRect();
this.mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
this.mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
this.handlePlanetSelection();
});
// Mouse move for tooltips
canvas.addEventListener('mousemove', (event) => {
const rect = canvas.getBoundingClientRect();
this.mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
this.mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
this.updateTooltip(event.clientX, event.clientY);
});
}
initializeTooltips() {
this.tooltip = document.createElement('div');
this.tooltip.className = 'tooltip';
this.tooltip.style.display = 'none';
document.body.appendChild(this.tooltip);
}
handlePlanetSelection() {
this.raycaster.setFromCamera(this.mouse, this.camera);
const intersects = this.raycaster.intersectObjects([...this.planets, this.sun]);
if (intersects.length > 0) {
const selectedObject = intersects[0].object;
this.selectedPlanet = selectedObject;
this.handlePlanetClick(selectedObject);
this.highlightPlanet(selectedObject);
} else {
this.clearSelection();
}
}
showPlanetInfo(planet) {
// Use the new UI system instead of direct DOM access
if (window.solarSystemUI) {
const planetData = {
name: planet.name,
distance: planet.userData ? `${planet.userData.distance} AU` : 'Unknown',
period: planet.userData ? `${(1/planet.userData.speed).toFixed(1)} Earth years` : 'Unknown',
diameter: planet.userData ? `${(planet.userData.size * 2).toFixed(1)} Earth diameters` : 'Unknown'
};
window.solarSystemUI.showPlanetInfo(planetData);
}
}
getPlanetType(name) {
const types = {
'Mercury': 'Terrestrial',
'Venus': 'Terrestrial',
'Earth': 'Terrestrial',
'Mars': 'Terrestrial',
'Jupiter': 'Gas Giant',
'Saturn': 'Gas Giant',
'Uranus': 'Ice Giant',
'Neptune': 'Ice Giant'
};
return types[name] || 'Unknown';
}
highlightPlanet(planet) {
// Remove previous highlights
this.planets.forEach(p => {
p.children.forEach(child => {
if (child.name === 'highlight') {
p.remove(child);
}
});
});
// Add highlight to selected planet
if (planet !== this.sun) {
const highlightGeometry = new THREE.SphereGeometry(planet.userData.size * 1.2, 32, 16);
const highlightMaterial = new THREE.MeshBasicMaterial({
color: 0xFFFFFF,
transparent: true,
opacity: 0.3,
blending: THREE.AdditiveBlending
});
const highlight = new THREE.Mesh(highlightGeometry, highlightMaterial);
highlight.name = 'highlight';
planet.add(highlight);
}
}
clearSelection() {
this.selectedPlanet = null;
// Use the new UI system instead of direct DOM access
if (window.solarSystemUI) {
window.solarSystemUI.hidePlanetInfo();
}
// Remove all highlights
this.planets.forEach(p => {
p.children.forEach(child => {
if (child.name === 'highlight') {
p.remove(child);
}
});
});
}
resetSimulation() {
// Reset planet positions
this.planets.forEach(planet => {
planet.userData.angle = Math.random() * Math.PI * 2;
planet.position.x = Math.cos(planet.userData.angle) * planet.userData.distance;
planet.position.z = Math.sin(planet.userData.angle) * planet.userData.distance;
});
// Reset camera
this.camera.position.set(0, 30, 40);
this.camera.lookAt(0, 0, 0);
// Reset controls
this.masterSpeed = 1.0;
document.getElementById('speed-slider').value = 1.0;
document.getElementById('speed-value').textContent = '1.0x';
this.paused = false;
document.getElementById('play-pause-btn').textContent = '⏸️ Pause';
this.clearSelection();
}
toggleTheme() {
this.isDarkTheme = !this.isDarkTheme;
const themeBtn = document.getElementById('theme-toggle');
if (this.isDarkTheme) {
this.scene.background = new THREE.Color(0x000511);
themeBtn.textContent = '🌞 Light Theme';
} else {
this.scene.background = new THREE.Color(0x87CEEB);
themeBtn.textContent = '🌙 Dark Theme';
}
}
onWindowResize() {
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize(window.innerWidth, window.innerHeight);
}
updateFPS() {
// FPS counter disabled to avoid errors with missing DOM elements
// const fps = Math.round(1 / this.clock.getDelta());
// console.log('FPS:', fps);
}
animate() {
requestAnimationFrame(() => this.animate());
if (!this.paused) {
const delta = this.clock.getDelta();
// Animate sun
if (this.sun) {
this.sun.rotation.y += delta * 0.5;
}
// Animate planets
this.planets.forEach(planet => {
// Orbital motion
planet.userData.angle += delta * planet.userData.speed * this.masterSpeed * 0.1;
planet.position.x = Math.cos(planet.userData.angle) * planet.userData.distance;
planet.position.z = Math.sin(planet.userData.angle) * planet.userData.distance;
// Planet rotation
planet.rotation.y += delta * 2;
// Animate moon for Earth
if (planet.name === 'Earth') {
const moon = planet.children.find(child => child.name === 'Moon');
if (moon) {
moon.position.x = Math.cos(Date.now() * 0.005) * 2;
moon.position.z = Math.sin(Date.now() * 0.005) * 2;
}
}
});
// Animate asteroid belt
if (this.asteroidBelt) {
this.asteroidBelt.rotation.y += delta * 0.1;
}
}
// Update FPS counter
// this.updateFPS(); // Commented out to avoid errors
// Render the scene
if (this.renderer && this.scene && this.camera) {
this.renderer.render(this.scene, this.camera);
// Log scene info every 60 frames (about once per second)
if (Math.floor(Date.now() / 1000) % 2 === 0 && Date.now() % 100 < 50) {
console.log(`Scene has ${this.scene.children.length} objects, Camera at:`, this.camera.position);
}
} else {
console.log('Renderer, scene, or camera not ready for rendering');
}
// In animate(), after requestAnimationFrame and before rendering, update the fill light position
if (this.cameraFillLight) {
this.cameraFillLight.position.copy(this.camera.position);
}
}
// UI Integration Methods
toggleOrbits(show) {
this.orbitLines.forEach(orbit => {
orbit.visible = show;
});
}
toggleAsteroids(show) {
if (this.asteroidBelt) {
this.asteroidBelt.visible = show;
}
}
toggleLabels(show) {
// This would be implemented when planet labels are added
console.log('Toggle labels:', show);
}
showPlanetInfoUI(planetData) {
// Interface with the new UI
if (window.solarSystemUI) {
window.solarSystemUI.showPlanetInfo(planetData);
}
}
// Enhanced planet click handling
handlePlanetClick(planet) {
const planetInfo = {
name: planet.name,
distance: planet.userData ? `${planet.userData.distance} AU` : 'Unknown',
period: planet.userData ? `${(1/planet.userData.speed).toFixed(1)} Earth years` : 'Unknown',
diameter: planet.userData ? `${(planet.userData.size * 2).toFixed(1)} Earth diameters` : 'Unknown'
};
this.showPlanetInfoUI(planetInfo);
}
// Tooltip functionality
updateTooltip(mouseX, mouseY) {
this.raycaster.setFromCamera(this.mouse, this.camera);
const intersects = this.raycaster.intersectObjects([...this.planets, this.sun]);
if (intersects.length > 0 && window.solarSystemUI) {
const object = intersects[0].object;
window.solarSystemUI.showTooltip(object.name, mouseX + 10, mouseY - 10);
} else if (window.solarSystemUI) {
window.solarSystemUI.hideTooltip();
}
}
}
// Initialize the solar system when the page loads
document.addEventListener('DOMContentLoaded', () => {
console.log('DOM loaded, initializing solar system...');
try {
const solarSystem = new SolarSystem();
console.log('Solar system initialized successfully');
} catch (error) {
console.error('Error initializing solar system:', error);
// Hide loading indicator if there's an error
const loadingIndicator = document.getElementById('loading-indicator');
if (loadingIndicator) {
loadingIndicator.innerHTML = '<div class="loading-icon">❌</div><div>Error loading solar system</div>';
}
}
});