-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPrototype.html
More file actions
712 lines (616 loc) · 29 KB
/
Prototype.html
File metadata and controls
712 lines (616 loc) · 29 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hand Gesture Particle & Shape Morph</title>
<style>
body { margin: 0; overflow: hidden; background: #000; font-family: sans-serif; }
#video-container {
position: absolute;
bottom: 10px;
left: 10px;
width: 260px;
height: 220px;
border: 2px solid white;
transform: scaleX(-1);
border-radius: 8px;
overflow: hidden;
cursor: move;
user-select: none;
transition: border-color 0.2s;
}
#video-container:hover { border-color: #00ffcc; }
#video-container.dragging { border-color: #ff00ff; cursor: grabbing; }
#ui { position: absolute; top: 20px; left: 20px; color: white; pointer-events: none; text-shadow: 2px 2px 4px rgba(0,0,0,0.5); }
.label { font-size: 12px; opacity: 0.7; }
.gesture-name { font-size: 24px; font-weight: bold; color: #00ffcc; }
.mode-indicator { font-size: 18px; font-weight: bold; color: #ff00ff; margin-top: 10px; }
.mode-particles { color: #00ffcc; }
.mode-shapes { color: #ff6b6b; }
.debug { font-size: 11px; opacity: 0.5; margin-top: 5px; }
</style>
</head>
<body>
<div id="ui">
<div class="label">CURRENT MODE</div>
<div id="mode-display" class="mode-indicator mode-particles">PARTICLES MODE</div>
<div class="label" style="margin-top:10px">CURRENT SHAPE</div>
<div id="shape-display" class="gesture-name">Initializing...</div>
<div class="label" style="margin-top:10px">CONTROLS</div>
<div style="font-size: 14px">
<strong>Peace Sign (✌):</strong> Switch Mode<br>
<strong>Pinch:</strong> Change Shape<br>
<strong>Open Palm:</strong> Expand/Scale<br>
<strong>Move Hand:</strong> Translate<br>
<strong>Tilt Hand:</strong> Rotate (Shapes Mode)
</div>
<div id="debug-info" class="debug"></div>
</div>
<div id="video-container">
<video id="webcam" autoplay playsinline></video>
</div>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.160.0/build/three.module.js",
"three/addons/": "https://unpkg.com/three@0.160.0/examples/jsm/"
}
}
</script>
<script type="module">
import * as THREE from 'three';
// --- Configuration ---
const PARTICLE_COUNT = 15000;
const SHAPES = ['CUBE', 'SPHERE', 'PYRAMID', 'CYLINDER', 'HEART', 'SATURN', 'FLOWER', 'EXPLOSION'];
let currentShapeIndex = 0;
let currentMode = 'PARTICLES'; // 'PARTICLES' or 'SHAPES'
// --- State Management ---
const state = {
targetPositions: new Float32Array(PARTICLE_COUNT * 3),
handPresent: false,
handX: 0, handY: 0, handZ: 0,
handRotX: 0, handRotY: 0,
pinchIntensity: 0,
expansion: 1.0,
morphProgress: 1.0,
objectScale: 1.0,
objectRotX: 0,
objectRotY: 0,
objectPosX: 0,
objectPosY: 0
};
// --- Three.js Setup ---
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
document.body.appendChild(renderer.domElement);
// --- Custom Shader Material (Particles) ---
const vertexShader = `
uniform float uTime;
uniform float uMorph;
uniform float uExpansion;
uniform vec3 uHandPos;
attribute vec3 targetPos;
attribute vec3 color;
varying vec3 vColor;
void main() {
vColor = color;
vec3 pos = mix(position, targetPos, uMorph);
float dist = distance(pos, uHandPos);
float influence = smoothstep(2.0, 0.0, dist);
pos += normalize(pos - uHandPos) * influence * uExpansion;
vec4 mvPosition = modelViewMatrix * vec4(pos, 1.0);
gl_PointSize = (20.0 / -mvPosition.z) * (1.0 + influence);
gl_Position = projectionMatrix * mvPosition;
}
`;
const fragmentShader = `
varying vec3 vColor;
void main() {
float dist = distance(gl_PointCoord, vec2(0.5));
if (dist > 0.5) discard;
float alpha = 1.0 - smoothstep(0.4, 0.5, dist);
gl_FragColor = vec4(vColor, alpha);
}
`;
// --- Particle System ---
const geometry = new THREE.BufferGeometry();
const positions = new Float32Array(PARTICLE_COUNT * 3);
const targetPositions = new Float32Array(PARTICLE_COUNT * 3);
const colors = new Float32Array(PARTICLE_COUNT * 3);
for (let i = 0; i < PARTICLE_COUNT; i++) {
positions[i * 3] = (Math.random() - 0.5) * 10;
positions[i * 3 + 1] = (Math.random() - 0.5) * 10;
positions[i * 3 + 2] = (Math.random() - 0.5) * 10;
colors[i * 3] = Math.random();
colors[i * 3 + 1] = Math.random();
colors[i * 3 + 2] = 0.8 + Math.random() * 0.2;
}
geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry.setAttribute('targetPos', new THREE.BufferAttribute(targetPositions, 3));
geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
const material = new THREE.ShaderMaterial({
vertexShader,
fragmentShader,
uniforms: {
uTime: { value: 0 },
uMorph: { value: 0 },
uExpansion: { value: 0 },
uHandPos: { value: new THREE.Vector3() }
},
transparent: true,
blending: THREE.AdditiveBlending,
depthWrite: false
});
const particleSystem = new THREE.Points(geometry, material);
scene.add(particleSystem);
// --- Solid Mesh System ---
let currentMesh = null;
const meshMaterial = new THREE.MeshPhongMaterial({
color: 0x00ffcc,
emissive: 0x002244,
shininess: 100,
transparent: true,
opacity: 0.95,
flatShading: false
});
// Enhanced lighting setup
const ambientLight = new THREE.AmbientLight(0xffffff, 0.4);
scene.add(ambientLight);
const mainLight = new THREE.DirectionalLight(0xffffff, 0.8);
mainLight.position.set(5, 5, 5);
scene.add(mainLight);
const fillLight = new THREE.DirectionalLight(0x4488ff, 0.3);
fillLight.position.set(-5, 0, -5);
scene.add(fillLight);
const backLight = new THREE.PointLight(0xff88cc, 0.5);
backLight.position.set(0, -5, -5);
scene.add(backLight);
function createMesh(shapeType) {
if (currentMesh) {
scene.remove(currentMesh);
}
let geometry;
if (shapeType === 'CUBE') {
geometry = new THREE.BoxGeometry(2.5, 2.5, 2.5);
}
else if (shapeType === 'SPHERE') {
geometry = new THREE.SphereGeometry(1.8, 32, 32);
}
else if (shapeType === 'PYRAMID') {
geometry = new THREE.ConeGeometry(2, 3, 4);
}
else if (shapeType === 'CYLINDER') {
geometry = new THREE.CylinderGeometry(1.5, 1.5, 3, 32);
}
else if (shapeType === 'HEART') {
const shape = new THREE.Shape();
const x = 0, y = 0;
shape.moveTo(x + 0, y + 0);
shape.bezierCurveTo(x + 0, y - 0.3, x - 0.6, y - 0.3, x - 0.6, y + 0);
shape.bezierCurveTo(x - 0.6, y + 0.3, x - 0.3, y + 0.6, x + 0, y + 1);
shape.bezierCurveTo(x + 0.3, y + 0.6, x + 0.6, y + 0.3, x + 0.6, y + 0);
shape.bezierCurveTo(x + 0.6, y - 0.3, x + 0, y - 0.3, x + 0, y + 0);
const extrudeSettings = { depth: 0.4, bevelEnabled: true, bevelThickness: 0.1, bevelSize: 0.1 };
geometry = new THREE.ExtrudeGeometry(shape, extrudeSettings);
geometry.scale(3, 3, 3);
}
else if (shapeType === 'SATURN') {
const group = new THREE.Group();
const sphere = new THREE.Mesh(
new THREE.SphereGeometry(1.5, 32, 32),
meshMaterial
);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(2.5, 0.15, 16, 100),
meshMaterial
);
ring.rotation.x = Math.PI / 2.3;
group.add(sphere);
group.add(ring);
currentMesh = group;
scene.add(currentMesh);
return;
}
else if (shapeType === 'FLOWER') {
const group = new THREE.Group();
for (let i = 0; i < 8; i++) {
const petal = new THREE.Mesh(
new THREE.SphereGeometry(0.5, 16, 16),
meshMaterial
);
const angle = (i / 8) * Math.PI * 2;
petal.position.x = Math.cos(angle) * 1.5;
petal.position.y = Math.sin(angle) * 1.5;
petal.scale.set(1, 2, 0.5);
group.add(petal);
}
const center = new THREE.Mesh(
new THREE.SphereGeometry(0.7, 16, 16),
new THREE.MeshPhongMaterial({ color: 0xffff00, emissive: 0xaa8800 })
);
group.add(center);
currentMesh = group;
scene.add(currentMesh);
return;
}
else { // EXPLOSION (Spiky ball)
geometry = new THREE.IcosahedronGeometry(2, 1);
const posAttr = geometry.attributes.position;
for (let i = 0; i < posAttr.count; i++) {
const x = posAttr.getX(i);
const y = posAttr.getY(i);
const z = posAttr.getZ(i);
const length = Math.sqrt(x*x + y*y + z*z);
const scale = 1 + Math.random() * 0.5;
posAttr.setXYZ(i, x/length * scale * 2, y/length * scale * 2, z/length * scale * 2);
}
}
currentMesh = new THREE.Mesh(geometry, meshMaterial);
scene.add(currentMesh);
}
// --- Shape Math (Particles) ---
function setParticleShape(shapeType) {
const posAttr = geometry.attributes.position;
const tarAttr = geometry.attributes.targetPos;
for(let i=0; i<PARTICLE_COUNT*3; i++) {
posAttr.array[i] = tarAttr.array[i];
}
posAttr.needsUpdate = true;
state.morphProgress = 0;
for (let i = 0; i < PARTICLE_COUNT; i++) {
const i3 = i * 3;
let x, y, z;
if (shapeType === 'CUBE') {
// Random points on cube surface
const face = Math.floor(Math.random() * 6);
const u = Math.random() * 2 - 1;
const v = Math.random() * 2 - 1;
if (face === 0) { x = 2; y = u * 2; z = v * 2; }
else if (face === 1) { x = -2; y = u * 2; z = v * 2; }
else if (face === 2) { x = u * 2; y = 2; z = v * 2; }
else if (face === 3) { x = u * 2; y = -2; z = v * 2; }
else if (face === 4) { x = u * 2; y = v * 2; z = 2; }
else { x = u * 2; y = v * 2; z = -2; }
}
else if (shapeType === 'SPHERE') {
const phi = Math.acos(-1 + (2 * i) / PARTICLE_COUNT);
const theta = Math.sqrt(PARTICLE_COUNT * Math.PI) * phi;
x = 2 * Math.cos(theta) * Math.sin(phi);
y = 2 * Math.sin(theta) * Math.sin(phi);
z = 2 * Math.cos(phi);
}
else if (shapeType === 'PYRAMID') {
if (Math.random() > 0.2) {
// Points on pyramid sides
const side = Math.floor(Math.random() * 4);
const h = Math.random();
const r = (1 - h) * 2;
const angle = (side / 4) * Math.PI * 2 + (Math.random() * Math.PI / 2);
x = Math.cos(angle) * r;
y = h * 3 - 1.5;
z = Math.sin(angle) * r;
} else {
// Points on base
const angle = Math.random() * Math.PI * 2;
const r = Math.random() * 2;
x = Math.cos(angle) * r;
y = -1.5;
z = Math.sin(angle) * r;
}
}
else if (shapeType === 'CYLINDER') {
const angle = Math.random() * Math.PI * 2;
const r = 1.5;
x = Math.cos(angle) * r;
y = (Math.random() - 0.5) * 3;
z = Math.sin(angle) * r;
}
else if (shapeType === 'HEART') {
const t = (i / PARTICLE_COUNT) * Math.PI * 2;
x = 0.15 * (16 * Math.pow(Math.sin(t), 3));
y = 0.15 * (13 * Math.cos(t) - 5 * Math.cos(2*t) - 2 * Math.cos(3*t) - Math.cos(4*t));
z = (Math.random() - 0.5) * 0.5;
}
else if (shapeType === 'SATURN') {
if (i < PARTICLE_COUNT * 0.6) {
const phi = Math.random() * Math.PI * 2;
const theta = Math.random() * Math.PI;
x = Math.cos(phi) * Math.sin(theta) * 1.5;
y = Math.sin(phi) * Math.sin(theta) * 1.5;
z = Math.cos(theta) * 1.5;
} else {
const r = 2.0 + Math.random() * 0.8;
const angle = Math.random() * Math.PI * 2;
x = Math.cos(angle) * r;
y = Math.sin(angle) * r;
z = (Math.random() - 0.5) * 0.1;
}
}
else if (shapeType === 'FLOWER') {
const t = (i / PARTICLE_COUNT) * Math.PI * 20;
const r = 2 * Math.cos(4 * t);
x = r * Math.cos(t);
y = r * Math.sin(t);
z = (Math.random() - 0.5) * 0.5;
}
else { // Explosion
x = (Math.random() - 0.5) * 10;
y = (Math.random() - 0.5) * 10;
z = (Math.random() - 0.5) * 10;
}
tarAttr.array[i3] = x;
tarAttr.array[i3 + 1] = y;
tarAttr.array[i3 + 2] = z;
}
tarAttr.needsUpdate = true;
}
function setShape(shapeType) {
if (currentMode === 'PARTICLES') {
setParticleShape(shapeType);
} else {
createMesh(shapeType);
}
document.getElementById('shape-display').innerText = shapeType;
}
function switchMode() {
currentMode = currentMode === 'PARTICLES' ? 'SHAPES' : 'PARTICLES';
const modeDisplay = document.getElementById('mode-display');
if (currentMode === 'PARTICLES') {
modeDisplay.innerText = 'PARTICLES MODE';
modeDisplay.className = 'mode-indicator mode-particles';
particleSystem.visible = true;
if (currentMesh) currentMesh.visible = false;
} else {
modeDisplay.innerText = 'SHAPES MODE';
modeDisplay.className = 'mode-indicator mode-shapes';
particleSystem.visible = false;
createMesh(SHAPES[currentShapeIndex]);
if (currentMesh) currentMesh.visible = true;
}
}
// Initialize
setShape(SHAPES[0]);
// --- MediaPipe Hand Tracking ---
import { HandLandmarker, FilesetResolver } from "https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.0";
let handLandmarker;
async function initHandTracking() {
const vision = await FilesetResolver.forVisionTasks("https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.0/wasm");
handLandmarker = await HandLandmarker.createFromOptions(vision, {
baseOptions: { modelAssetPath: `https://storage.googleapis.com/mediapipe-models/hand_landmarker/hand_landmarker/float16/1/hand_landmarker.task` },
runningMode: "VIDEO",
numHands: 1
});
startCamera();
}
async function startCamera() {
const video = document.getElementById('webcam');
const stream = await navigator.mediaDevices.getUserMedia({ video: true });
video.srcObject = stream;
video.addEventListener('loadeddata', predictWebcam);
}
let lastPinch = false;
let lastPeace = false;
// Gesture stabilization buffers
const gestureBuffer = {
pinch: [],
peace: [],
bufferSize: 5,
threshold: 0.6 // 60% of frames must detect gesture
};
function addToBuffer(buffer, value) {
buffer.push(value);
if (buffer.length > gestureBuffer.bufferSize) {
buffer.shift();
}
}
function isGestureStable(buffer) {
if (buffer.length < gestureBuffer.bufferSize) return false;
const trueCount = buffer.filter(v => v).length;
return (trueCount / buffer.length) >= gestureBuffer.threshold;
}
function detectPeaceSign(hand) {
// Index and middle finger extended, others closed
const indexTip = hand[8].y;
const indexBase = hand[5].y;
const middleTip = hand[12].y;
const middleBase = hand[9].y;
const ringTip = hand[16].y;
const ringBase = hand[13].y;
const pinkyTip = hand[20].y;
const pinkyBase = hand[17].y;
const thumbTip = hand[4].y;
const thumbBase = hand[2].y;
// Check if index and middle are extended (tips below base in y)
const indexExtended = indexTip < indexBase - 0.08;
const middleExtended = middleTip < middleBase - 0.08;
// Check if ring and pinky are NOT extended (more strict)
const ringClosed = ringTip > ringBase - 0.02;
const pinkyClosed = pinkyTip > pinkyBase - 0.02;
// Thumb should be somewhat closed
const thumbNotExtended = thumbTip > thumbBase - 0.05;
// Also check finger separation (peace fingers should be apart)
const fingerSeparation = Math.abs(hand[8].x - hand[12].x);
const separated = fingerSeparation > 0.03;
return indexExtended && middleExtended && ringClosed && pinkyClosed && thumbNotExtended && separated;
}
function detectPinch(hand) {
// Distance between thumb tip and index tip
const thumbTip = hand[4];
const indexTip = hand[8];
const dist = Math.hypot(thumbTip.x - indexTip.x, thumbTip.y - indexTip.y, thumbTip.z - indexTip.z);
// Also check if other fingers are extended (open palm = not pinching)
const middleTip = hand[12].y;
const middleBase = hand[9].y;
const middleExtended = middleTip < middleBase - 0.05;
// Pinch should be close AND middle finger shouldn't be fully extended
return dist < 0.06 && !middleExtended;
}
function getHandSpread(hand) {
// More robust spread calculation using multiple finger pairs
const thumbPinky = Math.hypot(hand[4].x - hand[20].x, hand[4].y - hand[20].y);
const thumbIndex = Math.hypot(hand[4].x - hand[8].x, hand[4].y - hand[8].y);
const indexPinky = Math.hypot(hand[8].x - hand[20].x, hand[8].y - hand[20].y);
// Average of multiple measurements for stability
return (thumbPinky + thumbIndex * 0.7 + indexPinky * 0.5) / 2.2;
}
async function predictWebcam() {
const video = document.getElementById('webcam');
let results = handLandmarker.detectForVideo(video, performance.now());
if (results.landmarks && results.landmarks.length > 0) {
const hand = results.landmarks[0];
// Map hand coordinates
state.handX = (hand[9].x - 0.5) * -10;
state.handY = (hand[9].y - 0.5) * -10;
state.handZ = (hand[9].z) * 10;
// Calculate hand rotation based on wrist to middle finger
const dx = hand[9].x - hand[0].x;
const dy = hand[9].y - hand[0].y;
state.handRotY = Math.atan2(dx, dy);
state.handRotX = (hand[9].z - hand[0].z) * 5;
// Detect gestures with buffering for stability
const peaceDetected = detectPeaceSign(hand);
const pinchDetected = detectPinch(hand);
addToBuffer(gestureBuffer.peace, peaceDetected);
addToBuffer(gestureBuffer.pinch, pinchDetected);
const isPeaceStable = isGestureStable(gestureBuffer.peace);
const isPinchStable = isGestureStable(gestureBuffer.pinch);
// Debug info
document.getElementById('debug-info').innerHTML =
`Peace: ${peaceDetected ? '✓' : '✗'} (${isPeaceStable ? 'STABLE' : 'unstable'})<br>` +
`Pinch: ${pinchDetected ? '✓' : '✗'} (${isPinchStable ? 'STABLE' : 'unstable'})`;
// Peace sign detection (mode switch) - only trigger on stable gesture
if (isPeaceStable && !lastPeace) {
switchMode();
}
lastPeace = isPeaceStable;
// Pinch Detection (shape change) - only trigger on stable gesture
if (isPinchStable && !lastPinch) {
currentShapeIndex = (currentShapeIndex + 1) % SHAPES.length;
setShape(SHAPES[currentShapeIndex]);
}
lastPinch = isPinchStable;
// Expansion/Scale (hand spread) - using improved calculation
const spread = getHandSpread(hand);
state.expansion = spread * 5;
state.objectScale = Math.max(0.3, spread * 3);
// Position
state.objectPosX = state.handX;
state.objectPosY = state.handY;
// Rotation
state.objectRotX = state.handRotX;
state.objectRotY = state.handRotY;
state.handPresent = true;
} else {
state.handPresent = false;
// Clear buffers when hand is not detected
gestureBuffer.pinch = [];
gestureBuffer.peace = [];
}
requestAnimationFrame(predictWebcam);
}
// --- Animation Loop ---
function animate() {
requestAnimationFrame(animate);
material.uniforms.uTime.value = performance.now() * 0.001;
if (currentMode === 'PARTICLES') {
if (state.morphProgress < 1.0) {
state.morphProgress += 0.02;
material.uniforms.uMorph.value = state.morphProgress;
}
if (state.handPresent) {
material.uniforms.uHandPos.value.lerp(new THREE.Vector3(state.handX, state.handY, 0), 0.1);
material.uniforms.uExpansion.value = THREE.MathUtils.lerp(material.uniforms.uExpansion.value, state.expansion, 0.1);
} else {
material.uniforms.uExpansion.value *= 0.95;
}
particleSystem.rotation.y += 0.002;
particleSystem.rotation.x += 0.001;
}
else if (currentMode === 'SHAPES' && currentMesh) {
if (state.handPresent) {
// Smooth position tracking
currentMesh.position.x = THREE.MathUtils.lerp(currentMesh.position.x, state.objectPosX * 0.5, 0.1);
currentMesh.position.y = THREE.MathUtils.lerp(currentMesh.position.y, state.objectPosY * 0.5, 0.1);
// Smooth rotation based on hand tilt
currentMesh.rotation.y = THREE.MathUtils.lerp(currentMesh.rotation.y, state.objectRotY, 0.1);
currentMesh.rotation.x = THREE.MathUtils.lerp(currentMesh.rotation.x, state.objectRotX, 0.1);
// Smooth scale
const targetScale = state.objectScale;
currentMesh.scale.setScalar(THREE.MathUtils.lerp(currentMesh.scale.x, targetScale, 0.1));
} else {
// Idle rotation when no hand
currentMesh.rotation.y += 0.005;
currentMesh.rotation.x += 0.003;
}
}
renderer.render(scene, camera);
}
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
// --- Draggable Video Container ---
const videoContainer = document.getElementById('video-container');
let isDragging = false;
let dragOffset = { x: 0, y: 0 };
videoContainer.addEventListener('mousedown', (e) => {
isDragging = true;
videoContainer.classList.add('dragging');
dragOffset.x = e.clientX - videoContainer.offsetLeft;
dragOffset.y = e.clientY - videoContainer.offsetTop;
e.preventDefault();
});
document.addEventListener('mousemove', (e) => {
if (!isDragging) return;
let newX = e.clientX - dragOffset.x;
let newY = e.clientY - dragOffset.y;
// Keep within viewport bounds
newX = Math.max(0, Math.min(newX, window.innerWidth - videoContainer.offsetWidth));
newY = Math.max(0, Math.min(newY, window.innerHeight - videoContainer.offsetHeight));
videoContainer.style.left = newX + 'px';
videoContainer.style.top = newY + 'px';
videoContainer.style.bottom = 'auto';
});
document.addEventListener('mouseup', () => {
if (isDragging) {
isDragging = false;
videoContainer.classList.remove('dragging');
}
});
// Touch support for mobile
videoContainer.addEventListener('touchstart', (e) => {
isDragging = true;
videoContainer.classList.add('dragging');
const touch = e.touches[0];
dragOffset.x = touch.clientX - videoContainer.offsetLeft;
dragOffset.y = touch.clientY - videoContainer.offsetTop;
e.preventDefault();
});
document.addEventListener('touchmove', (e) => {
if (!isDragging) return;
const touch = e.touches[0];
let newX = touch.clientX - dragOffset.x;
let newY = touch.clientY - dragOffset.y;
newX = Math.max(0, Math.min(newX, window.innerWidth - videoContainer.offsetWidth));
newY = Math.max(0, Math.min(newY, window.innerHeight - videoContainer.offsetHeight));
videoContainer.style.left = newX + 'px';
videoContainer.style.top = newY + 'px';
videoContainer.style.bottom = 'auto';
});
document.addEventListener('touchend', () => {
if (isDragging) {
isDragging = false;
videoContainer.classList.remove('dragging');
}
});
initHandTracking();
animate();
</script>
</body>
</html>