-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
821 lines (699 loc) · 34.7 KB
/
Copy pathindex.html
File metadata and controls
821 lines (699 loc) · 34.7 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NeonFlux - Interactive WebGL Particle System</title>
<!-- SEO & Metadata -->
<meta name="description" content="NeonFlux: An interactive WebGL experience controlled by hand gestures. Manipulate particles with your fingertips.">
<meta name="author" content="Eugene Wang">
<!-- Open Graph / Facebook -->
<meta property="og:type" content="website">
<meta property="og:url" content="https://neonflux.eugene.tw/">
<meta property="og:title" content="NeonFlux - Interactive WebGL Particle System">
<meta property="og:description" content="Experience the future of interaction. Control neon particles in real-time using hand gestures directly in your browser.">
<meta property="og:image" content="https://neonflux.eugene.tw/og-image.jpg">
<!-- Twitter -->
<meta property="twitter:card" content="summary_large_image">
<meta property="twitter:url" content="https://neonflux.eugene.tw/">
<meta property="twitter:title" content="NeonFlux - Interactive WebGL Particle System">
<meta property="twitter:description" content="Experience the future of interaction. Control neon particles in real-time using hand gestures directly in your browser.">
<meta property="twitter:image" content="https://neonflux.eugene.tw/og-image.jpg">
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&display=swap" rel="stylesheet">
<!-- Three.js -->
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/[email protected]/build/three.module.js",
"three/addons/": "https://unpkg.com/[email protected]/examples/jsm/",
"@mediapipe/tasks-vision": "https://cdn.jsdelivr.net/npm/@mediapipe/[email protected]/+esm"
}
}
</script>
<style>
body {
margin: 0;
overflow: hidden;
background-color: #000;
font-family: 'Orbitron', sans-serif;
user-select: none;
}
/* Scanlines */
#scanlines {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: linear-gradient(
to bottom,
rgba(255,255,255,0),
rgba(255,255,255,0) 50%,
rgba(0,0,0,0.2) 50%,
rgba(0,0,0,0.2)
);
background-size: 100% 4px;
opacity: 0.35;
pointer-events: none;
z-index: 10;
}
/* Vignette */
#vignette {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: radial-gradient(circle, transparent 50%, rgba(0,0,0,0.8) 100%);
pointer-events: none;
z-index: 11;
}
/* HUD */
.hud-panel {
position: absolute;
color: #0ff;
text-shadow: 0 0 5px #0ff;
font-size: 14px;
z-index: 12;
pointer-events: none;
}
#hud-tl { top: 20px; left: 20px; text-align: left; }
#hud-tr { top: 20px; right: 20px; text-align: right; }
#hud-bl { bottom: 20px; left: 20px; text-align: left; }
#hud-br { bottom: 20px; right: 20px; text-align: right; }
.label {
color: #0088aa;
font-size: 10px;
text-transform: uppercase;
}
.value {
font-weight: bold;
font-size: 16px;
}
/* Video Input (Background) */
#webcam {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
z-index: 0;
transform: scaleX(-1); /* Mirror effect */
}
/* Canvas needs to be above video */
canvas {
position: absolute;
top: 0;
left: 0;
z-index: 5;
pointer-events: none;
}
</style>
</head>
<body>
<div id="scanlines"></div>
<div id="vignette"></div>
<!-- HUD -->
<div id="hud-tl" class="hud-panel">
<div class="label">System Status</div>
<div class="value">ONLINE</div>
<div class="label" style="margin-top:10px;">FPS</div>
<div class="value" id="fps-display">0</div>
</div>
<div id="hud-tr" class="hud-panel">
<div class="label">Particle Count</div>
<div class="value">12,000</div>
<div class="label" style="margin-top:10px;">Mode</div>
<div class="value" id="mode-display">IDLE</div>
</div>
<div id="hud-bl" class="hud-panel">
<div class="label">Left Hand</div>
<div class="value" id="lh-status">NOT DETECTED</div>
<div class="value" id="lh-gesture" style="font-size:12px; color:#fff;">-</div>
</div>
<div id="hud-br" class="hud-panel">
<div class="label">Right Hand</div>
<div class="value" id="rh-status">NOT DETECTED</div>
<div class="value" id="rh-action" style="font-size:12px; color:#fff;">-</div>
</div>
<!-- Settings Panel -->
<div id="settings-panel" style="position: absolute; bottom: 80px; left: 20px; z-index: 20; background: rgba(0, 0, 0, 0.7); border: 1px solid #0ff; color: #fff; font-family: 'Orbitron', sans-serif; transition: 0.3s; width: 140px;">
<div style="background: rgba(0, 255, 255, 0.1); padding: 5px 10px; cursor: pointer; display: flex; justify-content: space-between; align-items: center;" onclick="toggleSettings()">
<span style="color: #0ff; font-size: 12px;">SETTINGS</span>
<span id="settings-toggle-icon" style="color: #0ff; font-size: 12px;">▼</span>
</div>
<div id="settings-content" style="padding: 10px; display: block; max-height: 300px; overflow-y: auto;">
<div style="color: #0ff; font-size: 11px; font-weight: bold; margin-bottom: 5px; border-bottom: 1px solid #0ff;">LEFT HAND</div>
<div style="margin-bottom: 5px;">
<label style="font-size: 10px; color: #0088aa;">1 FINGER:</label>
<input type="text" id="text-1" value="First" style="background: transparent; border: 1px solid #0088aa; color: #fff; width: 100%; padding: 2px; box-sizing: border-box;">
</div>
<div style="margin-bottom: 5px;">
<label style="font-size: 10px; color: #0088aa;">2 FINGERS:</label>
<input type="text" id="text-2" value="Second" style="background: transparent; border: 1px solid #0088aa; color: #fff; width: 100%; padding: 2px; box-sizing: border-box;">
</div>
<div style="margin-bottom: 5px;">
<label style="font-size: 10px; color: #0088aa;">3 FINGERS:</label>
<input type="text" id="text-3" value="Third" style="background: transparent; border: 1px solid #0088aa; color: #fff; width: 100%; padding: 2px; box-sizing: border-box;">
</div>
<div style="margin-bottom: 5px;">
<label style="font-size: 10px; color: #0088aa;">4 FINGERS:</label>
<input type="text" id="text-4" value="Fourth" style="background: transparent; border: 1px solid #0088aa; color: #fff; width: 100%; padding: 2px; box-sizing: border-box;">
</div>
<div style="margin-bottom: 5px;">
<label style="font-size: 10px; color: #0088aa;">5 FINGERS:</label>
<input type="text" id="text-5" value="Bye" style="background: transparent; border: 1px solid #0088aa; color: #fff; width: 100%; padding: 2px; box-sizing: border-box;">
</div>
<div style="color: #0ff; font-size: 11px; font-weight: bold; margin-top: 15px; margin-bottom: 5px; border-bottom: 1px solid #0ff;">RIGHT HAND</div>
<div style="margin-bottom: 5px;">
<label style="font-size: 10px; color: #0088aa;">1 FINGER:</label>
<input type="text" id="text-6" value="First" style="background: transparent; border: 1px solid #0088aa; color: #fff; width: 100%; padding: 2px; box-sizing: border-box;">
</div>
<div style="margin-bottom: 5px;">
<label style="font-size: 10px; color: #0088aa;">2 FINGERS:</label>
<input type="text" id="text-7" value="Second" style="background: transparent; border: 1px solid #0088aa; color: #fff; width: 100%; padding: 2px; box-sizing: border-box;">
</div>
<div style="margin-bottom: 5px;">
<label style="font-size: 10px; color: #0088aa;">3 FINGERS:</label>
<input type="text" id="text-8" value="Third" style="background: transparent; border: 1px solid #0088aa; color: #fff; width: 100%; padding: 2px; box-sizing: border-box;">
</div>
<div style="margin-bottom: 5px;">
<label style="font-size: 10px; color: #0088aa;">4 FINGERS:</label>
<input type="text" id="text-9" value="Fourth" style="background: transparent; border: 1px solid #0088aa; color: #fff; width: 100%; padding: 2px; box-sizing: border-box;">
</div>
<div style="margin-bottom: 5px;">
<label style="font-size: 10px; color: #0088aa;">5 FINGERS:</label>
<input type="text" id="text-10" value="Bye" style="background: transparent; border: 1px solid #0088aa; color: #fff; width: 100%; padding: 2px; box-sizing: border-box;">
</div>
<div style="color: #0ff; font-size: 11px; font-weight: bold; margin-top: 15px; margin-bottom: 5px; border-bottom: 1px solid #0ff;">EFFECTS</div>
<div style="margin-bottom: 5px;">
<label style="font-size: 10px; color: #0088aa;">THEME TEXT:</label>
<input type="text" id="theme-text" value="Screen Interaction System" style="background: transparent; border: 1px solid #0088aa; color: #fff; width: 100%; padding: 2px; box-sizing: border-box;">
</div>
<div style="display: flex; align-items: center; gap: 6px; margin-bottom: 5px;">
<input type="checkbox" id="scanlines-toggle" checked onchange="setScanlinesEnabled(this.checked)">
<label for="scanlines-toggle" style="font-size: 10px; color: #0088aa;">SCANLINES</label>
</div>
<button onclick="updateCustomText()" style="background: #0088aa; color: #000; border: none; padding: 5px 10px; font-family: 'Orbitron', sans-serif; cursor: pointer; margin-top: 5px; width: 100%;">UPDATE</button>
</div>
</div>
<video id="webcam" autoplay playsinline></video>
<script type="module">
import * as THREE from 'three';
import { FilesetResolver, HandLandmarker } from '@mediapipe/tasks-vision';
// --- Configuration ---
const PARTICLE_COUNT = 50000;
const PARTICLE_SIZE = 3.0;
const LERP_FACTOR = 0.24;
const TEXT_CANVAS_WIDTH = 1400;
const TEXT_CANVAS_HEIGHT = 520;
const TEXT_SAMPLE_STEP = 3;
// Colors
const COLOR_NEON_BLUE = new THREE.Color(0x00FFFF);
const COLOR_NEON_YELLOW = new THREE.Color(0xFFFF00);
const COLOR_NEON_PINK = new THREE.Color(0xFF00FF);
const COLOR_NEON_GREEN = new THREE.Color(0x00FF88);
const COLOR_ORANGE = new THREE.Color(0xFF8800);
// --- State ---
let width = window.innerWidth;
let height = window.innerHeight;
let particlesData = []; // Store { bx, by, bz } (base/target pos)
// Dynamic Text State
const gestureText = {
1: "First", // L1
2: "Second", // L2
3: "Third", // L3
4: "Fourth", // L4
5: "Bye", // L5
6: "First", // R1
7: "Second", // R2
8: "Third", // R3
9: "Fourth", // R4
10: "Bye" // R5
};
let themeText = "Screen Interaction System";
// ... existing code ...
// Expose function to window for button click
window.updateCustomText = function() {
const inputs = [];
for(let i=1; i<=10; i++) {
const el = document.getElementById('text-' + i);
if(el) {
const val = el.value;
if(val) gestureText[i] = val;
inputs.push(val);
}
}
const themeInput = document.getElementById('theme-text');
if (themeInput && themeInput.value) {
themeText = themeInput.value;
inputs.push(themeText);
}
// Re-generate caches
inputs.forEach(str => {
if(str && !textCache[str]) {
textCache[str] = generateTextCoordinates(str);
}
});
console.log("System Updated", gestureText);
};
window.toggleSettings = function() {
const content = document.getElementById('settings-content');
const icon = document.getElementById('settings-toggle-icon');
if (content.style.display === 'none') {
content.style.display = 'block';
icon.innerText = '▼';
} else {
content.style.display = 'none';
icon.innerText = '▲';
}
};
const scanlinesEl = document.getElementById('scanlines');
let scanlinesEnabled = true;
window.setScanlinesEnabled = function(enabled) {
scanlinesEnabled = Boolean(enabled);
if (scanlinesEl) {
scanlinesEl.style.display = scanlinesEnabled ? 'block' : 'none';
}
};
window.setScanlinesEnabled(scanlinesEnabled);
let handLandmarker = undefined;
let video = document.getElementById('webcam');
let lastVideoTime = -1;
let lhDetected = false;
let rhDetected = false;
// Gestures
let lhFingers = 0;
let rhFingers = 0;
let rhOpen = false;
// Visual State
let currentTargetShape = 'idle'; // 'text', 'catch', 'nebula', 'sphere', 'idle'
let currentText = "First";
let targetColor = COLOR_NEON_BLUE;
let scatterPos = new THREE.Vector3(9999, 9999, 0); // Right hand scatter center
let isDualCombo = false;
let leftHandPalmPos = new THREE.Vector3(0,0,0);
// Dynamic Appearance
let currentSize = 2.4; // Start with default
let currentOpacity = 1.0;
const TARGET_SIZE_IDLE = 1.0;
const TARGET_SIZE_ACTIVE = 8.0;
const TARGET_OPACITY_IDLE = 0.3;
const TARGET_OPACITY_ACTIVE = 1.0;
// FPS
let lastTime = performance.now();
let frameCount = 0;
// --- Three.js Init ---
const scene = new THREE.Scene();
// Perspective camera for 3D feel
const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 2000);
camera.position.z = 800;
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setSize(width, height);
renderer.setPixelRatio(window.devicePixelRatio);
document.body.appendChild(renderer.domElement);
// --- Particles ---
const geometry = new THREE.BufferGeometry();
const positions = new Float32Array(PARTICLE_COUNT * 3);
const colors = new Float32Array(PARTICLE_COUNT * 3);
// Initial random positions
for (let i = 0; i < PARTICLE_COUNT; i++) {
positions[i * 3] = (Math.random() - 0.5) * 2000;
positions[i * 3 + 1] = (Math.random() - 0.5) * 1000;
positions[i * 3 + 2] = (Math.random() - 0.5) * 1000;
// Base data for animation
particlesData.push({
tx: 0, ty: 0, tz: 0, // Target position
vx: 0, vy: 0, vz: 0, // Velocity (unused mostly due to direct lerp, but good for physics)
phase: Math.random() * Math.PI * 2 // For random motions
});
// Init color white
colors[i * 3] = 1;
colors[i * 3 + 1] = 1;
colors[i * 3 + 2] = 1;
}
geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
// Create texture for soft glow
const canvas = document.createElement('canvas');
canvas.width = 32;
canvas.height = 32;
const ctx = canvas.getContext('2d');
const grad = ctx.createRadialGradient(16,16,0,16,16,16);
grad.addColorStop(0, 'rgba(255,255,255,1)');
grad.addColorStop(1, 'rgba(255,255,255,0)');
ctx.fillStyle = grad;
ctx.fillRect(0,0,32,32);
const texture = new THREE.CanvasTexture(canvas);
const material = new THREE.PointsMaterial({
size: PARTICLE_SIZE,
map: texture,
vertexColors: true,
blending: THREE.AdditiveBlending,
depthWrite: false,
transparent: true,
opacity: 1.0
});
const particles = new THREE.Points(geometry, material);
scene.add(particles);
// --- Text Generation ---
function generateTextCoordinates(str) {
const tCanvas = document.createElement('canvas');
tCanvas.width = TEXT_CANVAS_WIDTH;
tCanvas.height = TEXT_CANVAS_HEIGHT;
const tCtx = tCanvas.getContext('2d', {willReadFrequently: true});
tCtx.fillStyle = '#000000';
tCtx.fillRect(0, 0, tCanvas.width, tCanvas.height);
// Auto-fit Logic
let fontSize = 220;
tCtx.font = `bold ${fontSize}px "Arial", sans-serif`;
const measure = tCtx.measureText(str);
if (measure.width > 800) {
const ratio = 800 / measure.width;
fontSize = Math.floor(fontSize * ratio);
tCtx.font = `bold ${fontSize}px "Arial", sans-serif`;
}
tCtx.fillStyle = '#ffffff';
tCtx.textAlign = 'center';
tCtx.textBaseline = 'middle';
tCtx.fillText(str, tCanvas.width/2, tCanvas.height/2);
const imageData = tCtx.getImageData(0, 0, tCanvas.width, tCanvas.height);
const data = imageData.data;
const coords = [];
// Scan
for(let y=0; y<tCanvas.height; y+=TEXT_SAMPLE_STEP) {
for(let x=0; x<tCanvas.width; x+=TEXT_SAMPLE_STEP) {
const alpha = data[(y*tCanvas.width + x)*4]; // R channel check
if(alpha > 128) {
coords.push({
x: (x - tCanvas.width/2) * 1.6, // Scale up
y: -(y - tCanvas.height/2) * 1.6,
z: 0
});
}
}
}
return coords;
}
let textCoords = generateTextCoordinates("Hello");
// --- MediaPipe Setup ---
async function setupMediaPipe() {
try {
console.log("Starting MediaPipe setup...");
const vision = await FilesetResolver.forVisionTasks(
"https://cdn.jsdelivr.net/npm/@mediapipe/[email protected]/wasm"
);
handLandmarker = await HandLandmarker.createFromOptions(vision, {
baseOptions: {
modelAssetPath: `https://storage.googleapis.com/mediapipe-models/hand_landmarker/hand_landmarker/float16/1/hand_landmarker.task`,
delegate: "GPU"
},
runningMode: "VIDEO",
numHands: 2
});
console.log("HandLandmarker created.");
// Start webcam
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: { width: 1280, height: 720 } })
.then((stream) => {
video.srcObject = stream;
console.log("Camera stream started.");
})
.catch((err) => {
console.error("Camera access error:", err);
alert("無法開啟攝影機: " + err.message + "\n請確認是否允許權限,或是否使用 HTTPS/localhost。");
});
} else {
console.error("navigator.mediaDevices is undefined. Secure context might be required.");
alert("瀏覽器不支援此環境開啟攝影機。\n請嘗試使用 localhost 或 HTTPS 連線。\n(http://webgl.test 可能被視為不安全)");
}
} catch (e) {
console.error("MediaPipe Init Error:", e);
alert("MediaPipe 初始化失敗: " + e.message);
}
}
setupMediaPipe();
// --- Logic Loop ---
function updateLogic() {
// Check Camera
if (video.currentTime !== lastVideoTime && handLandmarker && video.videoWidth > 0 && video.videoHeight > 0) {
let startTimeMs = performance.now();
const detections = handLandmarker.detectForVideo(video, startTimeMs);
lastVideoTime = video.currentTime;
processHands(detections);
}
// State Machine for Particles
assignParticleTargets();
}
function countFingers(landmarks) {
// Simple logic: y of tip < y of pip (screen coordinates, y is down? No in MP y is normalized 0-1 down)
// MP: 0=wrist, 4=thumb_tip, 8=index_tip, 12=middle_tip, 16=ring_tip, 20=pinky_tip
// PIPs: 3, 6, 10, 14, 18
// Note: Thumb is tricky, use x distance for thumb? simplified: tip vs mcp
let count = 0;
const tips = [8, 12, 16, 20];
const pips = [6, 10, 14, 18]; // Using PIP or MCP
// Non-thumb fingers
for(let i=0; i<4; i++) {
if(landmarks[tips[i]].y < landmarks[pips[i]].y) count++;
}
// Thumb (based on x relative to wrist for simplicity, or tip vs mcp)
// Assuming right hand rules might differ, for now generic check
// A simple robust check: dist(tip, wrist) > dist(IP, wrist)
// Let's use simpler y check or x check depending on hand side?
// Fallback: mostly vertical hand assumed.
if(landmarks[4].y < landmarks[3].y) count++;
return count;
}
function processHands(results) {
lhDetected = false;
rhDetected = false;
if (results.landmarks) {
for (let i = 0; i < results.landmarks.length; i++) {
const landmarks = results.landmarks[i];
const handedness = results.handednesses[i][0].categoryName;
if (handedness === "Left") {
lhDetected = true;
lhFingers = countFingers(landmarks);
const palm = landmarks[0];
leftHandPalmPos.set(
(1.0 - palm.x - 0.5) * width * 1.5,
-(palm.y - 0.5) * height * 1.5,
0
);
document.getElementById('lh-status').innerText = "ACTIVE";
document.getElementById('lh-status').style.color = '#0f0';
document.getElementById('lh-gesture').innerText = `Fingers: ${lhFingers}`;
} else if (handedness === "Right") {
rhDetected = true;
rhFingers = countFingers(landmarks);
document.getElementById('rh-status').innerText = "ACTIVE";
document.getElementById('rh-status').style.color = '#0f0';
document.getElementById('rh-action').innerText = `Fingers: ${rhFingers}`;
}
}
}
if(!lhDetected) {
document.getElementById('lh-status').innerText = "searching...";
document.getElementById('lh-status').style.color = '#555';
lhFingers = 0;
}
if(!rhDetected) {
document.getElementById('rh-status').innerText = "searching...";
document.getElementById('rh-status').style.color = '#555';
rhFingers = 0;
}
// Decide Global Mode
// Priority: Dual Combo > Left Hand > Right Hand > Idle
if (lhDetected && rhDetected && lhFingers === 5 && rhFingers === 5) {
isDualCombo = true;
currentTargetShape = 'text';
currentText = themeText;
targetColor = COLOR_ORANGE;
document.getElementById('mode-display').innerText = "THEME";
document.getElementById('mode-display').style.color = "#FF8800";
} else {
isDualCombo = false;
if (lhFingers > 0 && lhFingers <= 5) {
currentTargetShape = 'text';
currentText = gestureText[lhFingers];
if(lhFingers===5) targetColor = COLOR_ORANGE;
else if(lhFingers===4) targetColor = COLOR_NEON_GREEN;
else if(lhFingers===3) targetColor = COLOR_NEON_PINK;
else if(lhFingers===2) targetColor = COLOR_NEON_YELLOW;
else targetColor = COLOR_NEON_BLUE;
document.getElementById('mode-display').innerText = "LH TEXT";
document.getElementById('mode-display').style.color = "#00ff88";
} else if (rhFingers > 0 && rhFingers <= 5) {
currentTargetShape = 'text';
currentText = gestureText[5 + rhFingers]; // Map 6-10
if(rhFingers===5) targetColor = COLOR_ORANGE;
else if(rhFingers===4) targetColor = COLOR_NEON_GREEN;
else if(rhFingers===3) targetColor = COLOR_NEON_PINK;
else if(rhFingers===2) targetColor = COLOR_NEON_YELLOW;
else targetColor = COLOR_NEON_BLUE;
document.getElementById('mode-display').innerText = "RH TEXT";
document.getElementById('mode-display').style.color = "#0088ff";
} else {
currentTargetShape = 'idle';
document.getElementById('mode-display').innerText = "IDLE";
document.getElementById('mode-display').style.color = "#555";
}
}
}
function assignParticleTargets() {
// Re-generate text points if needed (optimization: cache these)
// For now, simpler caching check
if (currentTargetShape === 'text') {
// If text changed, regen
// But we store currentText.
// We'll regenerate every frame or check dirty flag?
// Let's just regen for simplicity or memoize if slow.
// Optimization: Just do it once when `currentText` changes.
}
}
// --- Pre-calculate Text ---
const textCache = {};
const phrases = ["First", "Second", "Third", "Fourth", "Bye", themeText];
// Generate immediately
phrases.forEach(str => {
textCache[str] = generateTextCoordinates(str);
});
// --- Animation Loop ---
function animate() {
requestAnimationFrame(animate);
// FPS
frameCount++;
const now = performance.now();
if (now - lastTime >= 1000) {
document.getElementById('fps-display').innerText = frameCount;
frameCount = 0;
lastTime = now;
}
updateLogic();
// --- Dynamic Style Update ---
const isHandActive = lhDetected || rhDetected;
const targetSize = isHandActive ? TARGET_SIZE_ACTIVE : TARGET_SIZE_IDLE;
const targetOpacity = isHandActive ? TARGET_OPACITY_ACTIVE : TARGET_OPACITY_IDLE;
// Lerp
currentSize += (targetSize - currentSize) * 0.1;
currentOpacity += (targetOpacity - currentOpacity) * 0.1;
material.size = currentSize;
material.opacity = currentOpacity;
const posAttr = geometry.attributes.position;
const colAttr = geometry.attributes.color;
const time = Date.now() * 0.001;
let targetPoints = [];
if (currentTargetShape === 'text') {
// Use cached
targetPoints = textCache[currentText] || [];
}
for (let i = 0; i < PARTICLE_COUNT; i++) {
let px = posAttr.getX(i);
let py = posAttr.getY(i);
let pz = posAttr.getZ(i);
let tx, ty, tz;
let r, g, b;
// --- 1. Determine Target ---
if (currentTargetShape === 'text') {
if (targetPoints.length > 0) {
const pIndex = i % targetPoints.length;
const tp = targetPoints[pIndex];
tx = tp.x;
ty = tp.y;
tz = tp.z;
tx += Math.sin(time + ieee_random(i)*10) * 0.6; // Jitter
} else {
// Fallback
tx = px; ty = py; tz = pz;
}
r = targetColor.r; g = targetColor.g; b = targetColor.b;
} else if (currentTargetShape === 'nebula') {
const data = particlesData[i];
tx = Math.sin(time * 0.2 + data.phase) * width * 0.5;
ty = Math.cos(time * 0.1 + data.phase) * height * 0.5;
tz = Math.sin(time * 0.3 + px*0.01) * 200;
// Ripple Effect (Sine wave around Right Hand)
// If Right hand is detected & Open
if (rhDetected && rhOpen) {
const dx = tx - scatterPos.x;
const dy = ty - scatterPos.y;
const dist = Math.sqrt(dx*dx + dy*dy);
// Ripple formula: Z offset based on sin(dist - time)
// Only affect if close-ish or global? User said "Hand swipe produces Ripple"
// Let's make it global but centralized on hand
if (dist < 600) {
const ripple = Math.sin(dist * 0.05 - time * 10) * 50 * Math.exp(-dist * 0.005);
tz += ripple;
}
}
r = 0.2; g = 0.6; b = 1.0;
} else if (currentTargetShape === 'sphere') {
const offset = 2 / PARTICLE_COUNT;
const inc = Math.PI * (3 - Math.sqrt(5));
const y = ((i * offset) - 1) + (offset / 2);
const rDist = Math.sqrt(1 - Math.pow(y, 2));
const phi = ((i + 1) % PARTICLE_COUNT) * inc;
const radius = 200;
// Rotating
const rotSpeed = time * 3;
let sx = Math.cos(phi + rotSpeed) * rDist;
let sz = Math.sin(phi + rotSpeed) * rDist;
let sy = y;
tx = leftHandPalmPos.x + sx * radius;
ty = leftHandPalmPos.y + sy * radius;
tz = leftHandPalmPos.z + sz * radius;
// Jumping Effect check? "Bouncing trajectory"
// Done via simple lerp for now, maybe add noise to path?
// To strictly follow "Jumping trajectory", we'd need bezier.
// But lerp 0.16 is fast. Let's add some vertical noise if far.
r = 1.0; g = 0.6; b = 0.0; // Orange
if (i % 30 === 0) { r=0.1; g=0.1; b=0.1; } // Texture lines
} else if (currentTargetShape === 'idle') {
// Random float
const data = particlesData[i];
tx = Math.sin(time * 0.1 + data.phase) * width * 0.6;
ty = Math.cos(time * 0.15 + data.phase) * height * 0.6;
tz = Math.sin(time * 0.1 + i*0.01) * 200;
r=0.2; g=0.2; b=0.2;
}
// --- 2. Physics Update (Lerp) ---
px += (tx - px) * LERP_FACTOR;
py += (ty - py) * LERP_FACTOR;
pz += (tz - pz) * LERP_FACTOR;
// --- 3. Scatter Interaction (Right Hand - Closed) ---
if (!isDualCombo && rhDetected && !rhOpen) {
const dx = px - scatterPos.x;
const dy = py - scatterPos.y;
const dist = Math.sqrt(dx*dx + dy*dy);
if (dist < 200) {
const angle = Math.atan2(dy, dx);
const force = (200 - dist) * 0.8; // Stronger push
px += Math.cos(angle) * force;
py += Math.sin(angle) * force;
}
}
posAttr.setXYZ(i, px, py, pz);
colAttr.setXYZ(i, r, g, b);
}
posAttr.needsUpdate = true;
colAttr.needsUpdate = true;
renderer.render(scene, camera);
}
// Helper
function ieee_random(n) { return Math.sin(n) * 10000 - Math.floor(Math.sin(n) * 10000); }
// Start
animate();
// Handle Resize
window.addEventListener('resize', () => {
width = window.innerWidth;
height = window.innerHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
});
</script>
</body>
</html>