-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.js
More file actions
1251 lines (1052 loc) · 53.6 KB
/
main.js
File metadata and controls
1251 lines (1052 loc) · 53.6 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
// Particle Gravity Simulation with Gravitational Lensing
import * as THREE from 'three';
class ParticleGravitySimulator {
constructor() {
this.particles = [];
this.scene = null;
// Initialize mouse position tracking
this.mousePosition = new THREE.Vector2(0, 0);
// Draggable gravity centers (3 of them)
this.draggableCenters = [
{ position: new THREE.Vector2(200, 200), isDragging: false, dot: null, velocity: new THREE.Vector2(0, 0), gravityMode: true, prevPositions: [], accumulatedMass: 1.0 },
{ position: new THREE.Vector2(-200, 100), isDragging: false, dot: null, velocity: new THREE.Vector2(0, 0), gravityMode: true, prevPositions: [], accumulatedMass: 1.0 },
{ position: new THREE.Vector2(0, -200), isDragging: false, dot: null, velocity: new THREE.Vector2(0, 0), gravityMode: true, prevPositions: [], accumulatedMass: 1.0 }
];
// Mouse cursor visibility
this.mouseCursorDot = null;
this.mouseCursorVisible = false;
this.mouseHideTimeout = null;
this.mouseIsDown = false;
this.mouseAccumulatedMass = 1.0;
// Double-click detection for creating new pucks
this.lastClickTime = 0;
this.lastClickPosition = new THREE.Vector2(0, 0);
this.doubleClickThreshold = 300; // milliseconds
this.doubleClickDistanceThreshold = 20; // pixels
// Movement mode state
this.movementMode = 'WHEE'; // 'FIXED' or 'WHEE' - start with gravity enabled
this.hasInteracted = false;
// Store initial positions for reset
this.initialCenterPositions = [
new THREE.Vector2(200, 200),
new THREE.Vector2(-200, 100),
new THREE.Vector2(0, -200)
];
// Default configuration parameters with user's preferred settings
this.config = {
particleCount: 50000,
particleSize: 2.4,
particleColor: '#ffffff', // White light base color (not used with random colors)
particleOpacity: 0.61,
gravityStrength: 1.0,
lensingStrength: 2.0,
velocityDamping: 0.1,
initialSpeed: 5.0,
particleSpread: 800,
colorMode: 'uniform', // Not used with our custom coloring
colorByVelocity: false,
colorByDistance: false,
showLensingEffect: true,
showMouseGravity: true,
// Draggable gravity center parameters
draggableGravityStrength: 3.0,
showDraggableCenter: true,
// Prism effect parameters
prismEffect: true,
prismRadius: 50, // Smaller prism size (50)
prismStrength: 2.0,
prismDispersion: 3.0, // Maximum color dispersion strength
prismOpacity: 0.05, // Subtle prism outline
ringOpacity: 0, // Ring hidden by default
resetSimulation: () => this.resetParticles()
};
// Initialize the simulation
this.init();
this.setupGUI();
this.animate();
}
init() {
// Create the scene with a black background (for Dark Side of the Moon theme)
this.scene = new THREE.Scene();
this.scene.background = new THREE.Color(0x000000);
// Set up the camera - orthographic for true 2D view
const aspect = window.innerWidth / window.innerHeight;
const frustumSize = 800;
this.camera = new THREE.OrthographicCamera(
frustumSize * aspect / -2,
frustumSize * aspect / 2,
frustumSize / 2,
frustumSize / -2,
1,
2000
);
this.camera.position.z = 1000;
// Create the WebGL renderer with post-processing support
this.renderer = new THREE.WebGLRenderer({
canvas: document.getElementById('canvas'),
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
this.renderer.setPixelRatio(window.devicePixelRatio);
this.renderer.setSize(window.innerWidth, window.innerHeight);
// Handle window resize for orthographic camera
window.addEventListener('resize', () => {
const aspect = window.innerWidth / window.innerHeight;
const frustumSize = 800;
this.camera.left = frustumSize * aspect / -2;
this.camera.right = frustumSize * aspect / 2;
this.camera.top = frustumSize / 2;
this.camera.bottom = frustumSize / -2;
this.camera.updateProjectionMatrix();
this.renderer.setSize(window.innerWidth, window.innerHeight);
});
// Track mouse position for gravitational lensing
window.addEventListener('mousemove', (event) => {
const mouseWorld = this.screenToWorld(event.clientX, event.clientY);
this.mousePosition.copy(mouseWorld);
// Show mouse cursor dot and reset hide timer
this.showMouseCursor();
this.resetMouseHideTimer();
});
// Add touch event support for mobile devices
window.addEventListener('touchstart', (event) => {
const touch = event.touches[0];
const mouseWorld = this.screenToWorld(touch.clientX, touch.clientY);
this.mousePosition.copy(mouseWorld);
});
window.addEventListener('touchmove', (event) => {
const touch = event.touches[0];
const mouseWorld = this.screenToWorld(touch.clientX, touch.clientY);
this.mousePosition.copy(mouseWorld);
});
window.addEventListener('touchend', (event) => {
// Not resetting mousePosition allows the gravitational lensing
// to continue from the last touch position
});
// Mouse events for dragging the gravity center
window.addEventListener('mousedown', (event) => {
this.mouseIsDown = true;
this.handleDragStart(event);
});
window.addEventListener('mousemove', (event) => this.handleDragMove(event));
window.addEventListener('mouseup', () => {
this.mouseIsDown = false;
this.handleDragEnd();
});
// Touch events for dragging on mobile
window.addEventListener('touchstart', (event) => this.handleTouchStart(event), { passive: false });
window.addEventListener('touchmove', (event) => this.handleTouchMove(event), { passive: false });
window.addEventListener('touchend', () => this.handleDragEnd(), { passive: false });
// Initialize particles
this.createParticleSystem();
// Create the draggable gravity center visuals
this.createDraggableCenters();
// Create the mouse cursor dot
this.createMouseCursor();
}
createDraggableCenters() {
// Create a visible dot for each draggable gravity center
this.draggableCenters.forEach((center, index) => {
const dotGeometry = new THREE.CircleGeometry(8, 32);
const dotMaterial = new THREE.MeshBasicMaterial({
color: 0xff6600,
transparent: true,
opacity: 0
});
center.dot = new THREE.Mesh(dotGeometry, dotMaterial);
center.dot.position.set(center.position.x, center.position.y, 0);
this.scene.add(center.dot);
});
}
createMouseCursor() {
// Create a small dot to show the mouse cursor position
const dotGeometry = new THREE.CircleGeometry(5, 32);
const dotMaterial = new THREE.MeshBasicMaterial({
color: 0x00ffff,
transparent: true,
opacity: 0.6
});
this.mouseCursorDot = new THREE.Mesh(dotGeometry, dotMaterial);
this.mouseCursorDot.visible = false;
this.scene.add(this.mouseCursorDot);
}
showMouseCursor() {
if (this.mouseCursorDot) {
this.mouseCursorDot.visible = true;
this.mouseCursorVisible = true;
}
}
hideMouseCursor() {
if (this.mouseCursorDot) {
this.mouseCursorDot.visible = false;
this.mouseCursorVisible = false;
}
}
resetMouseHideTimer() {
// Clear existing timer
if (this.mouseHideTimeout) {
clearTimeout(this.mouseHideTimeout);
}
// Set new timer to hide cursor after 2 seconds
this.mouseHideTimeout = setTimeout(() => {
this.hideMouseCursor();
}, 2000);
}
handleDragStart(event) {
const mouseWorld = this.screenToWorld(event.clientX, event.clientY);
const currentTime = Date.now();
// Check for double-click to create new puck
const timeSinceLastClick = currentTime - this.lastClickTime;
const distanceFromLastClick = mouseWorld.distanceTo(this.lastClickPosition);
if (timeSinceLastClick < this.doubleClickThreshold && distanceFromLastClick < this.doubleClickDistanceThreshold) {
// Double-click detected - create new puck
this.createNewPuck(mouseWorld);
this.lastClickTime = 0; // Reset to prevent triple-click
return;
}
// Update last click info
this.lastClickTime = currentTime;
this.lastClickPosition.copy(mouseWorld);
// Check if click is within any draggable dot
for (let center of this.draggableCenters) {
const distance = center.position.distanceTo(mouseWorld);
if (distance < 20) {
center.isDragging = true;
return;
}
}
}
createNewPuck(position) {
// Create a new gravity center at the specified position
const newPuck = {
position: position.clone(),
isDragging: false,
dot: null,
velocity: new THREE.Vector2(0, 0),
gravityMode: true,
prevPositions: [],
accumulatedMass: 1.0
};
// Create invisible dot mesh
const dotGeometry = new THREE.CircleGeometry(8, 32);
const dotMaterial = new THREE.MeshBasicMaterial({
color: 0xff6600,
transparent: true,
opacity: 0 // Invisible
});
newPuck.dot = new THREE.Mesh(dotGeometry, dotMaterial);
newPuck.dot.position.set(position.x, position.y, 0);
this.scene.add(newPuck.dot);
// Add to the array
this.draggableCenters.push(newPuck);
console.log('Created new puck at', position.x.toFixed(0), position.y.toFixed(0), '- Total pucks:', this.draggableCenters.length);
}
handleDragMove(event) {
const mouseWorld = this.screenToWorld(event.clientX, event.clientY);
// Update position for whichever center is being dragged
for (let center of this.draggableCenters) {
if (center.isDragging) {
// Track previous positions for velocity calculation (more frames for smoother)
center.prevPositions.push(center.position.clone());
if (center.prevPositions.length > 10) {
center.prevPositions.shift(); // Keep last 10 positions for smooth averaging
}
// Smooth the position with exponential moving average to reduce jitter
if (center.prevPositions.length > 0) {
const smoothingFactor = 0.5; // Lower = smoother but more lag (was 0.3, now 0.5 for half friction)
const prevPos = center.prevPositions[center.prevPositions.length - 1];
const smoothedX = prevPos.x + (mouseWorld.x - prevPos.x) * smoothingFactor;
const smoothedY = prevPos.y + (mouseWorld.y - prevPos.y) * smoothingFactor;
center.position.set(smoothedX, smoothedY);
} else {
center.position.copy(mouseWorld);
}
center.gravityMode = false; // Disable gravity while dragging
this.updateDraggableCenterPosition(center);
}
}
}
handleDragEnd() {
// Calculate velocity and enable gravity mode for all centers
for (let center of this.draggableCenters) {
if (center.isDragging) {
// Calculate smoothed velocity from previous positions
if (center.prevPositions.length >= 3) {
const velocity = new THREE.Vector2(0, 0);
// Weighted average - more recent positions have more weight
let totalWeight = 0;
for (let i = 0; i < center.prevPositions.length; i++) {
const weight = (i + 1) / center.prevPositions.length; // Linear weighting
const delta = new THREE.Vector2().subVectors(
i === center.prevPositions.length - 1 ? center.position : center.prevPositions[i + 1],
center.prevPositions[i]
);
velocity.add(delta.multiplyScalar(weight));
totalWeight += weight;
}
// Average with weights and apply a much gentler multiplier
velocity.divideScalar(totalWeight);
velocity.multiplyScalar(0.4); // Even slower, more controlled throw (half of previous)
center.velocity.copy(velocity);
} else {
center.velocity.set(0, 0);
}
// Clear position history and enable gravity mode
center.prevPositions = [];
center.gravityMode = true;
center.isDragging = false;
}
}
}
handleTouchStart(event) {
if (event.touches.length === 1) {
const touch = event.touches[0];
const mouseWorld = this.screenToWorld(touch.clientX, touch.clientY);
// Activate WHEE mode on first interaction
if (!this.hasInteracted) {
this.hasInteracted = true;
this.movementMode = 'WHEE';
console.log('Movement mode: WHEE');
}
// Check if touch is within any draggable dot
for (let center of this.draggableCenters) {
const distance = center.position.distanceTo(mouseWorld);
if (distance < 20) {
center.isDragging = true;
event.preventDefault();
return;
}
}
}
}
handleTouchMove(event) {
if (event.touches.length === 1) {
const touch = event.touches[0];
const mouseWorld = this.screenToWorld(touch.clientX, touch.clientY);
// Update position for whichever center is being dragged
for (let center of this.draggableCenters) {
if (center.isDragging) {
// Track previous positions for velocity calculation (more frames for smoother)
center.prevPositions.push(center.position.clone());
if (center.prevPositions.length > 10) {
center.prevPositions.shift(); // Keep last 10 positions
}
// Smooth the position with exponential moving average to reduce touchpad jitter
if (center.prevPositions.length > 0) {
const smoothingFactor = 0.5; // Lower = smoother but more lag (was 0.3, now 0.5 for half friction)
const prevPos = center.prevPositions[center.prevPositions.length - 1];
const smoothedX = prevPos.x + (mouseWorld.x - prevPos.x) * smoothingFactor;
const smoothedY = prevPos.y + (mouseWorld.y - prevPos.y) * smoothingFactor;
center.position.set(smoothedX, smoothedY);
} else {
center.position.copy(mouseWorld);
}
center.gravityMode = false; // Disable gravity while dragging
this.updateDraggableCenterPosition(center);
event.preventDefault();
}
}
}
}
screenToWorld(screenX, screenY) {
// Convert screen coordinates to world coordinates
const aspect = window.innerWidth / window.innerHeight;
const frustumSize = 800;
const x = (screenX / window.innerWidth) * 2 - 1;
const y = -(screenY / window.innerHeight) * 2 + 1;
return new THREE.Vector2(
x * frustumSize * aspect / 2,
y * frustumSize / 2
);
}
updateDraggableCenterPosition(center) {
if (center.dot) {
center.dot.position.set(center.position.x, center.position.y, 0);
}
}
// New method to update prism and ring geometry when radius changes
updatePrismGeometry() {
// Clean up existing prism and ring meshes
if (this.prismMesh) {
this.scene.remove(this.prismMesh);
this.prismMesh.geometry.dispose();
this.prismMesh.material.dispose();
}
if (this.ringMesh) {
this.scene.remove(this.ringMesh);
this.ringMesh.geometry.dispose();
this.ringMesh.material.dispose();
}
// Create new prism geometry with current radius
const prismGeometry = new THREE.CircleGeometry(this.config.prismRadius, 64);
const prismMaterial = new THREE.MeshBasicMaterial({
color: 0x000000,
transparent: true,
opacity: this.config.prismOpacity,
side: THREE.DoubleSide
});
// Add a colorful ring to show the prism boundary
const ringGeometry = new THREE.RingGeometry(
this.config.prismRadius - 1.5,
this.config.prismRadius,
64
);
// Create a gradient texture for the ring
const ringCanvas = document.createElement('canvas');
ringCanvas.width = 128;
ringCanvas.height = 2;
const ctx = ringCanvas.getContext('2d');
const ringGradient = ctx.createLinearGradient(0, 0, ringCanvas.width, 0);
// Rainbow gradient
ringGradient.addColorStop(0, '#ff0000');
ringGradient.addColorStop(1/6, '#ff8800');
ringGradient.addColorStop(2/6, '#ffff00');
ringGradient.addColorStop(3/6, '#00ff00');
ringGradient.addColorStop(4/6, '#00ffff');
ringGradient.addColorStop(5/6, '#0000ff');
ringGradient.addColorStop(1, '#ff00ff');
ctx.fillStyle = ringGradient;
ctx.fillRect(0, 0, ringCanvas.width, ringCanvas.height);
const rainbowTexture = new THREE.CanvasTexture(ringCanvas);
rainbowTexture.wrapS = THREE.RepeatWrapping;
const ringMaterial = new THREE.MeshBasicMaterial({
map: rainbowTexture,
transparent: true,
opacity: this.config.ringOpacity,
side: THREE.DoubleSide
});
// Create both prism circle and rainbow ring
this.prismMesh = new THREE.Mesh(prismGeometry, prismMaterial);
this.scene.add(this.prismMesh);
// Add the rainbow ring
this.ringMesh = new THREE.Mesh(ringGeometry, ringMaterial);
this.scene.add(this.ringMesh);
}
createParticleSystem() {
// Clean up existing particle system if it exists
if (this.particleSystem) {
this.scene.remove(this.particleSystem);
this.particleSystem.geometry.dispose();
this.particleSystem.material.dispose();
}
// Create the central prism shape (visible when no particles are in it)
this.updatePrismGeometry();
// Create particle geometry
const geometry = new THREE.BufferGeometry();
const positions = new Float32Array(this.config.particleCount * 3);
const colors = new Float32Array(this.config.particleCount * 3);
const velocities = new Float32Array(this.config.particleCount * 3);
for (let i = 0; i < this.config.particleCount; i++) {
// Calculate the array index
const i3 = i * 3;
// Random position in a 2D circle - flat distribution
// Avoid placing too many particles directly in the prism
let radius, theta;
if (Math.random() < 0.7) {
// 70% of particles outside the prism or at the edge
radius = this.config.prismRadius * 0.5 + this.config.particleSpread * Math.sqrt(Math.random() * 0.8);
} else {
// 30% of particles inside the prism
radius = this.config.prismRadius * Math.sqrt(Math.random());
}
theta = Math.random() * Math.PI * 2;
positions[i3] = radius * Math.cos(theta); // x position
positions[i3 + 1] = radius * Math.sin(theta); // y position
positions[i3 + 2] = 0; // z is always 0 (flat 2D)
// Initial velocities (tangential to create orbital motion)
// Calculate position vector and perpendicular vector for orbital velocity
const px = positions[i3];
const py = positions[i3 + 1];
// Normalize the position vector
const dist = Math.sqrt(px * px + py * py);
if (dist > 0.1) {
// Calculate perpendicular vector (for orbital motion)
const perpX = -py / dist;
const perpY = px / dist;
// Apply orbital velocity with some randomization
const speed = this.config.initialSpeed * (0.8 + Math.random() * 0.4);
velocities[i3] = perpX * speed;
velocities[i3 + 1] = perpY * speed;
} else {
// Random velocity for particles near center
velocities[i3] = Math.random() * this.config.initialSpeed - this.config.initialSpeed/2;
velocities[i3 + 1] = Math.random() * this.config.initialSpeed - this.config.initialSpeed/2;
}
velocities[i3 + 2] = 0; // No z velocity for 2D
// Set pure, vibrant colors from across the spectrum (no pastels)
// More extreme pure colors for better dispersion visualization
let color;
// Choose from several approaches for broader color diversity
const colorMode = Math.floor(Math.random() * 3);
if (colorMode === 0) {
// Pure spectral colors (red, orange, yellow, green, blue, violet)
const hueOptions = [0, 0.05, 0.1, 0.2, 0.3, 0.45, 0.55, 0.6, 0.7, 0.75, 0.8, 0.85];
const randomHue = hueOptions[Math.floor(Math.random() * hueOptions.length)];
color = new THREE.Color();
color.setHSL(randomHue, 1.0, 0.5);
} else if (colorMode === 1) {
// RGB primaries and secondaries for maximum contrast
const pureColors = [
0xff0000, // Red
0x00ff00, // Green
0x0000ff, // Blue
0xffff00, // Yellow
0x00ffff, // Cyan
0xff00ff // Magenta
];
color = new THREE.Color(pureColors[Math.floor(Math.random() * pureColors.length)]);
} else {
// Full random but with full saturation
color = new THREE.Color();
color.setHSL(Math.random(), 1.0, 0.5);
}
colors[i3] = color.r;
colors[i3 + 1] = color.g;
colors[i3 + 2] = color.b;
}
// Store velocities for physics calculation
this.velocities = velocities;
// Set attributes for the geometry
geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
// Create particle material with simple circular point texture
const canvas = document.createElement('canvas');
canvas.width = 32;
canvas.height = 32;
const context = canvas.getContext('2d');
const gradient = context.createRadialGradient(16, 16, 0, 16, 16, 16);
gradient.addColorStop(0, 'rgba(255, 255, 255, 1)');
gradient.addColorStop(0.3, 'rgba(160, 255, 255, 0.8)');
gradient.addColorStop(0.7, 'rgba(80, 180, 255, 0.3)');
gradient.addColorStop(1, 'rgba(0, 0, 64, 0)');
context.fillStyle = gradient;
context.fillRect(0, 0, 32, 32);
const sprite = new THREE.CanvasTexture(canvas);
const material = new THREE.PointsMaterial({
size: this.config.particleSize,
vertexColors: true,
transparent: true,
opacity: this.config.particleOpacity,
blending: THREE.AdditiveBlending,
sizeAttenuation: true,
depthWrite: false,
map: sprite
});
// Create the particle system
this.particleSystem = new THREE.Points(geometry, material);
this.scene.add(this.particleSystem);
}
updateParticleColors() {
// We're no longer updating colors in animation loop
// All particles keep their initial random colors
// This simulates white light being split by the prism
// This function is now just a placeholder in case we need to re-enable color updating
// But we do still need to mark colors for update in case other code modifies them
this.particleSystem.geometry.attributes.color.needsUpdate = true;
}
updateDraggableCenterPhysics() {
// Only update physics in WHEE mode
if (this.movementMode !== 'WHEE') {
return;
}
// First, calculate accumulated mass for each center based on nearby particles
this.updateCenterMasses();
// Update physics for draggable centers in gravity mode
for (let center of this.draggableCenters) {
if (center.gravityMode && !center.isDragging) {
// Apply gravity from other draggable centers
for (let otherCenter of this.draggableCenters) {
if (otherCenter === center) continue;
const toOtherX = otherCenter.position.x - center.position.x;
const toOtherY = otherCenter.position.y - center.position.y;
const distance = Math.sqrt(toOtherX * toOtherX + toOtherY * toOtherY);
if (distance > 1.0) {
// Gravitational force scales with other center's mass
const massRatio = otherCenter.accumulatedMass / center.accumulatedMass;
const force = this.config.draggableGravityStrength * 0.01 * massRatio / Math.max(distance * 0.1, 0.5);
const norm = 1 / distance;
center.velocity.x += toOtherX * norm * force;
center.velocity.y += toOtherY * norm * force;
}
}
// Apply gravity from mouse cursor to orange centers
const toMouseX = this.mousePosition.x - center.position.x;
const toMouseY = this.mousePosition.y - center.position.y;
const mouseDistance = Math.sqrt(toMouseX * toMouseX + toMouseY * toMouseY);
if (mouseDistance > 1.0 && this.config.showMouseGravity) {
// Mouse gravity affects orange centers with 2x or 6x strength, scaled by mouse mass
const mouseStrengthMultiplier = this.mouseIsDown ? 6.0 : 2.0;
const mouseForce = (this.config.lensingStrength * 0.05 * this.mouseAccumulatedMass / Math.max(mouseDistance * 0.1, 0.5)) * mouseStrengthMultiplier;
const norm = 1 / mouseDistance;
center.velocity.x += toMouseX * norm * mouseForce;
center.velocity.y += toMouseY * norm * mouseForce;
}
// Apply much weaker central gravity (massive objects resist acceleration)
const toCenterX = -center.position.x;
const toCenterY = -center.position.y;
const centerDist = Math.sqrt(toCenterX * toCenterX + toCenterY * toCenterY);
if (centerDist > 1.0) {
const centralForce = 0.0005 * this.config.gravityStrength / (centerDist * centerDist);
center.velocity.x += toCenterX / centerDist * centralForce;
center.velocity.y += toCenterY / centerDist * centralForce;
}
// Much less damping - they maintain momentum like massive objects
center.velocity.multiplyScalar(0.995);
// Update position
center.position.add(center.velocity);
this.updateDraggableCenterPosition(center);
}
}
}
updateCenterMasses() {
// Count particles that are currently near each center and accumulate mass over time
const positions = this.particleSystem.geometry.attributes.position.array;
const captureRadius = 10; // Particles within 10 units count toward mass
// Update mass for draggable centers
for (let center of this.draggableCenters) {
let nearbyParticles = 0;
for (let i = 0; i < this.config.particleCount; i++) {
const i3 = i * 3;
const dx = positions[i3] - center.position.x;
const dy = positions[i3 + 1] - center.position.y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < captureRadius) {
nearbyParticles++;
}
}
// Accumulate mass permanently - never decays, only grows
// Each nearby particle adds a tiny bit of permanent mass
center.accumulatedMass += nearbyParticles * 0.00001;
}
// Update mass for mouse cursor
let mouseNearbyParticles = 0;
for (let i = 0; i < this.config.particleCount; i++) {
const i3 = i * 3;
const dx = positions[i3] - this.mousePosition.x;
const dy = positions[i3 + 1] - this.mousePosition.y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < captureRadius) {
mouseNearbyParticles++;
}
}
this.mouseAccumulatedMass += mouseNearbyParticles * 0.00001;
}
updateParticlePhysics() {
const positions = this.particleSystem.geometry.attributes.position.array;
const colors = this.particleSystem.geometry.attributes.color.array;
// Convert mouse position from normalized device coordinates to world space
const mouseWorld = new THREE.Vector3(
this.mousePosition.x * 400,
this.mousePosition.y * 400,
0
);
for (let i = 0; i < this.config.particleCount; i++) {
const i3 = i * 3;
// Current position vector - always in 2D plane
const particlePos = new THREE.Vector2(
positions[i3],
positions[i3 + 1]
);
// Apply weak gravity toward center of simulation (stable orbits)
if (this.config.gravityStrength > 0) {
// Weak central gravity for orbital stability
const toCenterX = -positions[i3];
const toCenterY = -positions[i3 + 1];
const centerDist = Math.sqrt(toCenterX * toCenterX + toCenterY * toCenterY);
if (centerDist > 1.0) {
const centralForce = 0.01 * this.config.gravityStrength / (centerDist * centerDist);
this.velocities[i3] += toCenterX / centerDist * centralForce;
this.velocities[i3 + 1] += toCenterY / centerDist * centralForce;
}
}
// Apply prism/lens effect in the center - DARK SIDE OF THE MOON
if (this.config.prismEffect) {
const toCenterX = -positions[i3];
const toCenterY = -positions[i3 + 1];
const centerDist = Math.sqrt(toCenterX * toCenterX + toCenterY * toCenterY);
// Get the particle's color components
const r = colors[i3];
const g = colors[i3 + 1];
const b = colors[i3 + 2];
// Calculate color-based dispersion within and around the prism radius
if (centerDist < this.config.prismRadius * 1.5) {
// Normalize direction vector
const dirX = toCenterX / centerDist;
const dirY = toCenterY / centerDist;
// Different force for each color component (red, green, blue)
// This simulates dispersion - red, green, and blue light bend differently
let dispersionForce;
if (centerDist < this.config.prismRadius) {
// Inside the prism radius - dispersive force pushing outward
// Force increases as particles get closer to edge
const normalizedDist = centerDist / this.config.prismRadius;
dispersionForce = this.config.prismStrength * normalizedDist;
// Keep original particle color inside prism
// We're not changing colors inside, just when they exit
} else {
// Outside but near the prism - lensing effect
// Force decreases with distance from the edge
const outsideDistance = centerDist - this.config.prismRadius;
const falloff = Math.max(0, 1 - outsideDistance / (this.config.prismRadius * 0.5));
dispersionForce = -this.config.prismStrength * 0.5 * falloff;
}
// MUCH stronger color-dependent dispersion for extreme prism effect
// Wavelength-dependent refraction index (physics-based)
const rForce = dispersionForce * (1.0 - this.config.prismDispersion * 0.6); // Red bends least
const gForce = dispersionForce * 1.1; // Green medium
const bForce = dispersionForce * (1.0 + this.config.prismDispersion * 0.8); // Blue bends most
// Exaggerate color separation based on color dominance
let dominantForce;
const colorSum = r + g + b;
// Find the dominant color component (RGB)
if (r > g * 1.5 && r > b * 1.5) {
// Strongly red dominant - much less bending
dominantForce = rForce * 0.5;
// Add perpendicular "rainbow" motion for stronger separation
// This creates a more dramatic spreading effect
const perpX = -dirY;
const perpY = dirX;
this.velocities[i3] += perpX * rForce * 0.3;
this.velocities[i3 + 1] += perpY * rForce * 0.3;
} else if (g > r * 1.5 && g > b * 1.5) {
// Strongly green dominant - medium bending
dominantForce = gForce * 0.8;
// No perpendicular motion for green - straight path
} else if (b > r * 1.5 && b > g * 1.5) {
// Strongly blue dominant - much more bending
dominantForce = bForce * 1.8;
// Add opposite perpendicular motion for blues
const perpX = dirY;
const perpY = -dirX;
this.velocities[i3] += perpX * bForce * 0.4;
this.velocities[i3 + 1] += perpY * bForce * 0.4;
} else {
// Mixed colors - weighted average based on RGB components
dominantForce = (r * rForce + g * gForce + b * bForce) / Math.max(0.1, colorSum);
}
// Apply primary force with random jitter
const jitter = (Math.random() * 0.3 - 0.15) * dispersionForce; // More randomness
this.velocities[i3] -= dirX * (dominantForce + jitter);
this.velocities[i3 + 1] -= dirY * (dominantForce + jitter);
}
}
// Apply gravity from all draggable centers (scaled by accumulated mass)
if (this.config.showDraggableCenter && this.config.draggableGravityStrength > 0) {
for (let center of this.draggableCenters) {
const toDraggableX = center.position.x - positions[i3];
const toDraggableY = center.position.y - positions[i3 + 1];
const draggableDistance = Math.sqrt(toDraggableX * toDraggableX + toDraggableY * toDraggableY);
if (draggableDistance > 0.1) {
// Apply gravitational force scaled by accumulated mass
const gravityForce = (this.config.draggableGravityStrength * center.accumulatedMass) / Math.max(draggableDistance * 0.1, 0.5);
// Normalize the direction vector
const norm = 1 / draggableDistance;
const dirX = toDraggableX * norm;
const dirY = toDraggableY * norm;
// Apply gravitational acceleration
this.velocities[i3] += dirX * gravityForce;
this.velocities[i3 + 1] += dirY * gravityForce;
}
}
}
// Create gravitational lensing effect around mouse position
// Mouse creates a gravitational well that bends particle paths
const toMouseX = this.mousePosition.x - positions[i3];
const toMouseY = this.mousePosition.y - positions[i3 + 1];
const mouseDistance = Math.sqrt(toMouseX * toMouseX + toMouseY * toMouseY);
if (mouseDistance > 0.1 && this.config.showMouseGravity) {
// Apply gravitational force around mouse cursor
let gravityForce = 0;
// Multiply mouse gravity: 2x base, 6x when mouse button is held down, scaled by accumulated mass
const mouseStrengthMultiplier = (this.mouseIsDown ? 6.0 : 2.0) * this.mouseAccumulatedMass;
if (this.config.showLensingEffect) {
// Apply lensing force - stronger when closer to mouse
gravityForce = (this.config.lensingStrength / Math.max(mouseDistance * 0.05, 0.1)) * mouseStrengthMultiplier;
}
if (this.config.gravityStrength > 0) {
// Add main gravity effect from mouse
gravityForce += (this.config.gravityStrength / Math.max(mouseDistance * 0.1, 0.5)) * mouseStrengthMultiplier;
}
// Normalize the direction vector
const norm = 1 / mouseDistance;
const dirX = toMouseX * norm;
const dirY = toMouseY * norm;
// Apply gravitational acceleration toward mouse
this.velocities[i3] += dirX * gravityForce;
this.velocities[i3 + 1] += dirY * gravityForce;
this.velocities[i3 + 2] = 0; // Keep z velocity at 0
}
// Apply velocity damping (simulates friction)
this.velocities[i3] *= this.config.velocityDamping;
this.velocities[i3 + 1] *= this.config.velocityDamping;
this.velocities[i3 + 2] *= this.config.velocityDamping;
// Update positions based on velocities - enforce 2D
positions[i3] += this.velocities[i3];
positions[i3 + 1] += this.velocities[i3 + 1];
positions[i3 + 2] = 0; // Keep z position at 0
// Boundary check - wrap particles that go too far away
const maxDistance = this.config.particleSpread * 2;
const distanceFromCenter = Math.sqrt(
positions[i3] * positions[i3] +
positions[i3 + 1] * positions[i3 + 1]
);
if (distanceFromCenter > maxDistance) {
// Option 1: Reset particle to a new position with orbital velocity
if (Math.random() < 0.3) {
// New position on a random point of the circle
const newRadius = this.config.particleSpread * Math.sqrt(Math.random());
const newAngle = Math.random() * Math.PI * 2;
// Set new position
positions[i3] = newRadius * Math.cos(newAngle);
positions[i3 + 1] = newRadius * Math.sin(newAngle);
// Calculate orbital velocity at this radius
const perpX = -positions[i3 + 1] / newRadius;
const perpY = positions[i3] / newRadius;
const speed = this.config.initialSpeed * (0.8 + Math.random() * 0.4);
// Set new velocity (orbital motion)
this.velocities[i3] = perpX * speed;
this.velocities[i3 + 1] = perpY * speed;
this.velocities[i3 + 2] = 0;
}
// Option 2: Bounce off an invisible boundary
else {
// Normalize the position vector to the edge
const factor = maxDistance / distanceFromCenter;
positions[i3] = positions[i3] * factor * 0.9;
positions[i3 + 1] = positions[i3 + 1] * factor * 0.9;
// Reflect velocity (bounce off the boundary)
const normalX = -positions[i3] / distanceFromCenter;
const normalY = -positions[i3 + 1] / distanceFromCenter;
// Calculate dot product of velocity and normal
const dot = this.velocities[i3] * normalX + this.velocities[i3 + 1] * normalY;
// Reflect velocity with some energy loss
this.velocities[i3] = (this.velocities[i3] - 2 * dot * normalX) * 0.5;
this.velocities[i3 + 1] = (this.velocities[i3 + 1] - 2 * dot * normalY) * 0.5;
}
}
}
// Mark the position attribute for update
this.particleSystem.geometry.attributes.position.needsUpdate = true;
}
resetParticles() {
// Recreate the particle system with current settings
this.createParticleSystem();
}
collapsePucks() {
// Complete reset: zero out all state and collapse everything to center
const collapseRadius = this.config.prismRadius * 0.05;
// Remove all dynamically created pucks (keep only the first 3)
const extraPucks = this.draggableCenters.slice(3);
for (let puck of extraPucks) {
if (puck.dot) {
this.scene.remove(puck.dot);
puck.dot.geometry.dispose();
puck.dot.material.dispose();
}