Repository navigation
Expand file tree
/
Copy pathIndex.html
More file actions
378 lines (326 loc) · 13.7 KB
/
Copy pathIndex.html
File metadata and controls
378 lines (326 loc) · 13.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Hand-Controlled Particle System</title>
<style>
body { margin: 0; overflow: hidden; background-color: #000; font-family: sans-serif; }
canvas { display: block; }
#video-container {
position: absolute;
bottom: 10px;
left: 10px;
width: 160px;
height: 120px;
border: 2px solid #333;
z-index: 10;
opacity: 0.7;
transform: scaleX(-1); /* Mirror the video */
}
video { width: 100%; height: 100%; object-fit: cover; }
#ui {
position: absolute;
top: 20px;
left: 20px;
color: #00ffcc;
pointer-events: none;
z-index: 10;
text-shadow: 0 0 5px #00ffcc;
}
h1 { font-size: 1.5rem; margin: 0; }
p { font-size: 0.9rem; margin-top: 5px; opacity: 0.8; }
.instruction { color: white; background: rgba(0,0,0,0.5); padding: 5px; border-radius: 4px; margin-top: 5px; display: inline-block;}
</style>
<!-- Import Three.js and MediaPipe -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@mediapipe/camera_utils/camera_utils.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@mediapipe/control_utils/control_utils.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@mediapipe/drawing_utils/drawing_utils.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@mediapipe/hands/hands.js" crossorigin="anonymous"></script>
</head>
<body>
<div id="ui">
<h1>Interactive Particle Morphing</h1>
<div class="instruction">🖐 Move Hand: Rotate/Position</div><br>
<div class="instruction">👌 Pinch (Thumb+Index): Change Shape</div><br>
<div class="instruction">✊ Fist: Collapse | ✋ Open: Expand</div>
<p id="status">Loading AI Model...</p>
</div>
<!-- Hidden video element for MediaPipe -->
<div id="video-container">
<video class="input_video"></video>
</div>
<script>
// ==========================================
// 1. THREE.JS SETUP
// ==========================================
const scene = new THREE.Scene();
// Add subtle fog for depth
scene.fog = new THREE.FogExp2(0x000000, 0.002);
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 30;
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
document.body.appendChild(renderer.domElement);
// ==========================================
// 2. PARTICLE SYSTEM ENGINE
// ==========================================
const PARTICLE_COUNT = 12000;
const geometry = new THREE.BufferGeometry();
// Arrays for buffer attributes
const positions = new Float32Array(PARTICLE_COUNT * 3);
const colors = new Float32Array(PARTICLE_COUNT * 3);
const targetPositions = new Float32Array(PARTICLE_COUNT * 3); // Where particles want to go
// Initialize random positions
for (let i = 0; i < PARTICLE_COUNT * 3; i++) {
positions[i] = (Math.random() - 0.5) * 100;
colors[i] = 1.0;
targetPositions[i] = positions[i];
}
geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
// Create a generated texture for the particle (glow dot)
const getSprite = () => {
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.2, 'rgba(255,255,255,0.8)');
gradient.addColorStop(0.5, 'rgba(255,255,255,0.2)');
gradient.addColorStop(1, 'rgba(0,0,0,0)');
context.fillStyle = gradient;
context.fillRect(0, 0, 32, 32);
const texture = new THREE.Texture(canvas);
texture.needsUpdate = true;
return texture;
};
const material = new THREE.PointsMaterial({
size: 0.6,
vertexColors: true,
map: getSprite(),
blending: THREE.AdditiveBlending,
depthWrite: false,
transparent: true
});
const particles = new THREE.Points(geometry, material);
scene.add(particles);
// ==========================================
// 3. SHAPE GENERATORS
// ==========================================
const shapes = ['sphere', 'heart', 'saturn', 'flower', 'torus'];
let currentShapeIndex = 0;
function getPointOnSphere(i) {
const phi = Math.acos(-1 + (2 * i) / PARTICLE_COUNT);
const theta = Math.sqrt(PARTICLE_COUNT * Math.PI) * phi;
const r = 10;
return {
x: r * Math.cos(theta) * Math.sin(phi),
y: r * Math.sin(theta) * Math.sin(phi),
z: r * Math.cos(phi),
r: 0.2, g: 0.6, b: 1.0 // Blueish
};
}
function getPointOnHeart(i) {
// Parametric heart equation
const t = (i / PARTICLE_COUNT) * Math.PI * 2;
const x = 16 * Math.pow(Math.sin(t), 3);
const y = 13 * Math.cos(t) - 5 * Math.cos(2*t) - 2 * Math.cos(3*t) - Math.cos(4*t);
// Add some depth volume
const z = (Math.random() - 0.5) * 4;
const scale = 0.6;
return {
x: x * scale, y: y * scale, z: z,
r: 1.0, g: 0.1, b: 0.3 // Red/Pink
};
}
function getPointOnSaturn(i) {
const ratio = 0.7; // 70% planet, 30% rings
const isPlanet = i < PARTICLE_COUNT * ratio;
if (isPlanet) {
const idx = i;
const phi = Math.acos(-1 + (2 * idx) / (PARTICLE_COUNT*ratio));
const theta = Math.sqrt((PARTICLE_COUNT*ratio) * Math.PI) * phi;
const r = 6;
return {
x: r * Math.cos(theta) * Math.sin(phi),
y: r * Math.sin(theta) * Math.sin(phi),
z: r * Math.cos(phi),
r: 0.9, g: 0.8, b: 0.5 // Gold
};
} else {
// Ring
const idx = i - PARTICLE_COUNT * ratio;
const angle = (idx / (PARTICLE_COUNT * (1-ratio))) * Math.PI * 2 * 5; // multiple loops
const radius = 9 + Math.random() * 4;
return {
x: radius * Math.cos(angle),
y: (Math.random()-0.5), // Flattened y
z: radius * Math.sin(angle),
r: 0.6, g: 0.6, b: 0.7
};
}
}
function getPointOnFlower(i) {
const theta = (i / PARTICLE_COUNT) * Math.PI * 100; // lots of winding
// Rose curve: r = cos(k * theta)
const k = 4;
const r = 12 * Math.cos(k * theta);
const x = r * Math.cos(theta);
const y = r * Math.sin(theta);
const z = (Math.random() - 0.5) * 5;
return {
x: x, y: y, z: z,
r: 0.8, g: 0.2, b: 1.0 // Purple
};
}
function getPointOnTorus(i) {
const u = Math.random() * Math.PI * 2;
const v = Math.random() * Math.PI * 2;
const R = 8; const r = 3;
const x = (R + r * Math.cos(v)) * Math.cos(u);
const y = (R + r * Math.cos(v)) * Math.sin(u);
const z = r * Math.sin(v);
return {
x: x, y: y, z: z,
r: 0.0, g: 1.0, b: 0.5 // Teal
};
}
// Function to calculate all target positions based on current shape
function setTargetShape(shapeName) {
const colorAttr = particles.geometry.attributes.color;
for (let i = 0; i < PARTICLE_COUNT; i++) {
let p;
if(shapeName === 'sphere') p = getPointOnSphere(i);
else if(shapeName === 'heart') p = getPointOnHeart(i);
else if(shapeName === 'saturn') p = getPointOnSaturn(i);
else if(shapeName === 'flower') p = getPointOnFlower(i);
else p = getPointOnTorus(i);
// Store target
targetPositions[i * 3] = p.x;
targetPositions[i * 3 + 1] = p.y;
targetPositions[i * 3 + 2] = p.z;
// Update colors immediately for effect
colorAttr.setXYZ(i, p.r, p.g, p.b);
}
colorAttr.needsUpdate = true;
}
// Initial shape
setTargetShape(shapes[0]);
// ==========================================
// 4. MEDIAPIPE HAND TRACKING
// ==========================================
const videoElement = document.getElementsByClassName('input_video')[0];
const statusText = document.getElementById('status');
let handX = 0, handY = 0;
let isPinching = false;
let isFist = false;
let lastPinchTime = 0;
function onResults(results) {
statusText.innerText = "System Active";
statusText.style.color = "#0f0";
if (results.multiHandLandmarks && results.multiHandLandmarks.length > 0) {
const landmarks = results.multiHandLandmarks[0];
// 1. Position Tracking (Index Finger Tip - Landmark 8)
const x = landmarks[8].x;
const y = landmarks[8].y;
// Map 0..1 to -1..1 range for Three.js logic
// Note: MediaPipe x is mirrored relative to ThreeJS usually, but we want interaction to feel natural
handX = (0.5 - x) * 2;
handY = (0.5 - y) * 2;
// 2. Pinch Detection (Thumb Tip 4 vs Index Tip 8)
const dx = landmarks[8].x - landmarks[4].x;
const dy = landmarks[8].y - landmarks[4].y;
const dz = landmarks[8].z - landmarks[4].z; // z is roughly estimated
const distance = Math.sqrt(dx*dx + dy*dy + dz*dz);
if (distance < 0.05) {
if (!isPinching && Date.now() - lastPinchTime > 500) {
// Trigger Shape Switch
currentShapeIndex = (currentShapeIndex + 1) % shapes.length;
setTargetShape(shapes[currentShapeIndex]);
lastPinchTime = Date.now();
}
isPinching = true;
} else {
isPinching = false;
}
// 3. Fist Detection (Tip of fingers vs Wrist/Palm)
// Simple check: Is index tip (8) close to wrist (0)?
const dFist = Math.sqrt(
Math.pow(landmarks[8].x - landmarks[0].x, 2) +
Math.pow(landmarks[8].y - landmarks[0].y, 2)
);
isFist = (dFist < 0.3); // Threshold for fist
}
}
const hands = new Hands({locateFile: (file) => {
return `https://cdn.jsdelivr.net/npm/@mediapipe/hands/${file}`;
}});
hands.setOptions({
maxNumHands: 1,
modelComplexity: 1,
minDetectionConfidence: 0.5,
minTrackingConfidence: 0.5
});
hands.onResults(onResults);
const cameraUtils = new Camera(videoElement, {
onFrame: async () => {
await hands.send({image: videoElement});
},
width: 320,
height: 240
});
cameraUtils.start();
// ==========================================
// 5. ANIMATION LOOP
// ==========================================
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const time = clock.getElapsedTime();
const positionsAttribute = particles.geometry.attributes.position;
const currentPositions = positionsAttribute.array;
// Interaction Logic
// Map hand X/Y to scene rotation and scale
const targetRotationX = handY * 1;
const targetRotationY = handX * 1;
// Smooth rotation
particles.rotation.x += (targetRotationX - particles.rotation.x) * 0.1;
particles.rotation.y += (targetRotationY - particles.rotation.y) * 0.1;
// Expansion/Contraction Logic
let expansionFactor = 1.0;
if(isFist) expansionFactor = 0.1; // Implode
else if(isPinching) expansionFactor = 1.2; // Slight grow on pinch
else expansionFactor = 1.5; // Normal open hand state (slightly expanded)
for (let i = 0; i < PARTICLE_COUNT; i++) {
const ix = i * 3;
const iy = i * 3 + 1;
const iz = i * 3 + 2;
// Get target
let tx = targetPositions[ix] * expansionFactor;
let ty = targetPositions[iy] * expansionFactor;
let tz = targetPositions[iz] * expansionFactor;
// Add dynamic noise (drifting particles)
const noise = Math.sin(time + i) * 0.05;
// Linear Interpolation (Lerp) current pos to target pos
// Speed depends on state
const speed = isFist ? 0.2 : 0.05;
currentPositions[ix] += (tx - currentPositions[ix]) * speed + noise;
currentPositions[iy] += (ty - currentPositions[iy]) * speed + noise;
currentPositions[iz] += (tz - currentPositions[iz]) * speed + noise;
}
positionsAttribute.needsUpdate = true;
renderer.render(scene, camera);
}
// Handle Window Resize
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
animate();
</script>
</body>
</html>