-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
283 lines (255 loc) · 11.4 KB
/
Copy pathscript.js
File metadata and controls
283 lines (255 loc) · 11.4 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
import * as THREE from 'three';
// ___1. SETTINGS & CONFIG___
//how many dots/particles exist in the 3D scene. Change to `5000` = fewer dots, runs faster. Change to `100000` = more dots, looks denser but slows down.
const numParticles = 25000;
//which shape is currently showing
let currentTemplateIndex = 0;
//Create one THREE.Clock instance for tracking elapsed time in animations
const clock = new THREE.Clock();
let isPinching = false;//Tracks whether your fingers are currently pinching
let lastHandX = 0;//Stores where your hand was **in the previous frame**.
let vortexSpeed = 0;//How much the particles are currently spinning/twisting.
// ___2. THE IMAGE SCANNER (THE "PHACE TRIC")____
const faceImage = new Image();//creates empty image container
faceImage.src = 'face.jpg'; // Make sure you have face.jpg in your folder!
let imageCoords = [];//array that will gather all the coordinates of the bright found pixels
faceImage.onload = () => {//when the image finishes loading, run this function
const tempCanvas = document.createElement('canvas');//canvas It exists only in memory as a tool to read pixel data
const tempCtx = tempCanvas.getContext('2d');
tempCanvas.width = 128;
tempCanvas.height = 128;
tempCtx.drawImage(faceImage, 0, 0, 128, 128);//Draws `faceImage` onto `tempCanvas`, scaled to fit 128×128.
const data = tempCtx.getImageData(0, 0, 128, 128).data;
// Scan the image for bright pixels
for (let y = 0; y < 128; y++) {
for (let x = 0; x < 128; x++) {
const i = (y * 128 + x) * 4;//This converts **image pixel coordinates** → **Three.js world coordinates**.
const brightness = (data[i] + data[i+1] + data[i+2]) / 3;
if (brightness > 50) {
imageCoords.push({
x: (x - 64) * 0.25,//64 is the CENTER of the image
y: (64 - y) * 0.25//0.25 is a magic number chose by experimenting
});
}
}
}
console.log("Image Processed! Particles found: " + imageCoords.length);
};
//particles scatter slightly in front/behind the face plane gives the face shape a tiny 3D depth instead of being perfectly flat
function getFaceCoordinates(vec) {
if (imageCoords.length > 0) {
const p = imageCoords[Math.floor(Math.random() * imageCoords.length)];
vec.set(p.x, p.y, (Math.random() - 0.5) * 2);
} else {
// Fallback if image isn't loaded
vec.set((Math.random() - 0.5) * 10, (Math.random() - 0.5) * 10, 0);
}
}
// --- 3. MATHEMATICAL SHAPE GENERATORS ---
// This object contains functions that generate coordinates
const generators = {
sphere: (v) => {
const r = 6;//Radius = distance from center (0,0,0) to every particle.
const theta = Math.random() * Math.PI * 2;//longitude:θ rotates around the globe
const phi = Math.acos(2 * Math.random() - 1);//latitude:φ moves up and down
v.set(r * Math.sin(phi) * Math.cos(theta), r * Math.sin(phi) * Math.sin(theta), r * Math.cos(phi));//Computer graphics use cartesian coordinates,But sphere math uses angles.
},
saturn: (v) => {
if (Math.random() > 0.4) {
// The Planet (Sphere)
const r = 5;
const theta = Math.random() * Math.PI * 2;
const phi = Math.acos(2 * Math.random() - 1);
v.set(r * Math.sin(phi) * Math.cos(theta), r * Math.sin(phi) * Math.sin(theta), r * Math.cos(phi));
} else {
// The Ring
const inner = 7;
const outer = 11;
const r = inner + Math.random() * (outer - inner);
const theta = Math.random() * Math.PI * 2;
v.set(Math.cos(theta) * r, (Math.random() - 0.5) * 0.5, Math.sin(theta) * r);
}
},
star: (v) => {
// Simple 5-point 3D star logic
const l = (Math.random() > 0.5 ? 12 : 5) * Math.random();
const t = Math.random() * Math.PI * 2;
const p = Math.random() * Math.PI;
if (Math.random() > 0.2) {
// Spikes
const branch = Math.floor(Math.random() * 5);
const angle = (branch / 5) * Math.PI * 2;
const len = Math.random() * 15;
v.set(Math.cos(angle) * len, Math.sin(angle) * len, (Math.random() - 0.5) * 2);
} else {
// Core
v.set((Math.random()-0.5)*4, (Math.random()-0.5)*4, (Math.random()-0.5)*4);
}
},
galaxy: (v) => {
const angle = Math.random() * Math.PI * 2;
const radius = Math.random() * 15;
const spin = radius * 0.8;
v.set(Math.cos(angle + spin) * radius, (Math.random() - 0.5) * (3.0 / (radius + 1.0)), Math.sin(angle + spin) * radius);
},
fireworks: (v) => {
const r = 12 + Math.random() * 8;
const theta = Math.random() * Math.PI * 2;
const phi = Math.random() * Math.PI;
v.set(r * Math.sin(phi) * Math.cos(theta), r * Math.sin(phi) * Math.sin(theta), r * Math.cos(phi));
if(Math.random() > 0.85) v.multiplyScalar(0.05);
},
heart: (v) => {
const t = Math.random() * 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);
v.set(x * 0.4, y * 0.4, (Math.random() - 0.5) * 3);
},
dna: (v) => {
const height = (Math.random() - 0.5) * 20;
const strand = Math.random() > 0.5 ? 0 : Math.PI;
const angle = height * 0.8 + strand;
const radius = 3;
const x = Math.cos(angle) * radius;
const z = Math.sin(angle) * radius;
if (Math.random() > 0.9) {
const lerp = Math.random();
v.set(x * lerp, height, z * lerp);
} else {
v.set(x, height, z);
}
},
face: (v) => { getFaceCoordinates(v); }
};
const templateNames = Object.keys(generators);
// --- 4. THREE.JS INITIALIZATION ---
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 30;
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
document.body.appendChild(renderer.domElement);//the browser’s DOM object.
//Geometry Setup
const geometry = new THREE.BufferGeometry();//fast GPU memory storage for particles.
const posA = new Float32Array(numParticles * 3);
const posB = new Float32Array(numParticles * 3);
const vec = new THREE.Vector3();//a 3D point (x, y, z)
for (let i = 0; i < numParticles; i++) {
generators.sphere(vec); vec.toArray(posA, i * 3);
generators.galaxy(vec); vec.toArray(posB, i * 3);
}
geometry.setAttribute('position', new THREE.BufferAttribute(posA, 3));
geometry.setAttribute('targetPosition', new THREE.BufferAttribute(posB, 3));
const material = new THREE.ShaderMaterial({
uniforms: {
uTime: { value: 0 },
uProgress: { value: 0 },
uExpansion: { value: 1.0 },
uColor: { value: new THREE.Color(0x00ffcc) },
uVortex: { value: 0.0 }
},
vertexShader: `
attribute vec3 targetPosition;
uniform float uTime;
uniform float uProgress;
uniform float uExpansion;
uniform float uVortex;
void main() {
vec3 mixedPos = mix(position, targetPosition, uProgress);
// Vortex Rotation Math
float angle = uVortex * length(mixedPos.xz) * 0.5;
float s = sin(angle);
float c = cos(angle);
mat2 rot = mat2(c, -s, s, c);
mixedPos.xz = rot * mixedPos.xz;
vec3 finalPos = mixedPos * uExpansion;
vec4 mvPosition = modelViewMatrix * vec4(finalPos, 1.0);
gl_PointSize = 3.5 * (25.0 / -mvPosition.z);
gl_Position = projectionMatrix * mvPosition;
}
`,
fragmentShader: `
uniform vec3 uColor;
void main() {
float d = length(gl_PointCoord - vec2(0.5));
if (d > 0.5) discard;
gl_FragColor = vec4(uColor, 1.0 - (d * 2.0));
}
`,
transparent: true,
blending: THREE.AdditiveBlending,
depthWrite: false
});
//This is one GPU draw call.
// The GPU reads:
//position (start)
//targetPosition (end)
//uniforms (uProgress, uExpansion, uVortex)
//and runs the vertex shader for every particle — but all in one pass
//const points = new THREE.Points(geometry, material);
//scene.add(points);
// --- 5. CYCLE FUNCTION ---
function cycleShapes() {
const nextIndex = (currentTemplateIndex + 1) % templateNames.length;
const nextGen = generators[templateNames[nextIndex]];
geometry.attributes.position.array.set(geometry.attributes.targetPosition.array);
geometry.attributes.position.needsUpdate = true;
const targetArray = geometry.attributes.targetPosition.array;
for (let i = 0; i < numParticles; i++) {
nextGen(vec); vec.toArray(targetArray, i * 3);
}
geometry.attributes.targetPosition.needsUpdate = true;
material.uniforms.uProgress.value = 0;
currentTemplateIndex = nextIndex;
const label = document.getElementById('shape-name');
if(label) label.innerText = templateNames[currentTemplateIndex].toUpperCase();
}
// --- 6. AI HAND TRACKING (media pipe)---
const videoElement = document.getElementById('webcam');
const hands = new window.Hands({
locateFile: (file) => `https://cdn.jsdelivr.net/npm/@mediapipe/hands/${file}`
});
hands.setOptions({ maxNumHands: 1, modelComplexity: 1, minDetectionConfidence: 0.6 });
hands.onResults((results) => {
const loading = document.getElementById('loading');
if(loading) loading.style.display = 'none';
if (results.multiHandLandmarks && results.multiHandLandmarks.length > 0) {
const hand = results.multiHandLandmarks[0];
// Vortex Speed Calculation
const currentX = hand[8].x;
const velocity = Math.abs(currentX - lastHandX) * 18.0;
vortexSpeed = THREE.MathUtils.lerp(vortexSpeed, velocity, 0.1);
material.uniforms.uVortex.value = vortexSpeed;
lastHandX = currentX;
// Pinch logic
const dist = Math.hypot(hand[4].x - hand[8].x, hand[4].y - hand[8].y);
material.uniforms.uExpansion.value = THREE.MathUtils.mapLinear(dist, 0.05, 0.35, 0.5, 4.0);
material.uniforms.uColor.value.setHSL(hand[8].x, 0.8, 0.5);
if (dist < 0.05) {
isPinching = true;
} else if (isPinching && dist > 0.1) {
isPinching = false;
cycleShapes();
}
}
});
const cam = new window.Camera(videoElement, {
onFrame: async () => { await hands.send({ image: videoElement }); },
width: 640, height: 480
});
cam.start();
// --- 7. ANIMATE ---
function animate() {
requestAnimationFrame(animate);
material.uniforms.uProgress.value = THREE.MathUtils.lerp(material.uniforms.uProgress.value, 1, 0.03);
material.uniforms.uTime.value = clock.getElapsedTime();
points.rotation.y += 0.0015;
renderer.render(scene, camera);
}
animate();
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});