LABORATORY // EXPERIMENT_ACTIVE
MODULE: CELESTIAL_HAND_CONTROL
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>Celestial Hand Control</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Sora:wght@300;400;600;700&display=swap" rel="stylesheet">
<style>
:root {
--accent: #c8b0ff;
--accent-soft: rgba(200, 176, 255, 0.2);
--cyan: #00e5ff;
--orange: #ff6b35;
--mint: #7dffb3;
--panel-bg: rgba(10, 6, 28, 0.82);
--panel-border: rgba(180, 160, 255, 0.25);
--text: #e8e2ff;
--text-dim: rgba(232, 226, 255, 0.6);
}
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body { width: 100%; height: 100%; overflow: hidden; }
body {
background: #06021a;
color: var(--text);
font-family: "Sora", sans-serif;
user-select: none;
-webkit-user-select: none;
}
body::before {
content: "";
position: fixed;
inset: 0;
z-index: 0;
background:
radial-gradient(ellipse at 70% 20%, rgba(90, 16, 64, 0.35), transparent 55%),
radial-gradient(ellipse at 20% 80%, rgba(12, 56, 88, 0.3), transparent 55%),
radial-gradient(ellipse at 50% 50%, rgba(58, 24, 104, 0.25), transparent 65%),
#06021a;
}
body::after {
content: "";
position: fixed;
inset: 0;
z-index: 50;
pointer-events: none;
background: radial-gradient(ellipse at center, transparent 58%, rgba(2, 1, 8, 0.45) 100%);
}
canvas { display: block; }
#stage { position: absolute; inset: 0; z-index: 1; }
.panel {
background: var(--panel-bg);
border: 1px solid var(--panel-border);
border-radius: 14px;
backdrop-filter: blur(10px);
}
.kicker {
font-size: 0.68rem;
letter-spacing: 0.32em;
text-transform: uppercase;
color: var(--accent);
}
#ui-layer {
position: absolute;
top: 16px;
left: 16px;
z-index: 10;
pointer-events: none;
padding: 14px 18px;
max-width: 320px;
}
h1 { font-size: 1.05rem; font-weight: 700; letter-spacing: 0.06em; margin-top: 2px; }
#ui-layer p { font-size: 0.76rem; color: var(--text-dim); margin-top: 6px; }
#input-video {
position: absolute;
top: 0; left: 0;
width: 1px; height: 1px;
opacity: 0;
pointer-events: none;
}
.camera-feed {
position: absolute;
bottom: 92px;
right: 16px;
width: 160px;
height: 120px;
border-radius: 12px;
border: 1px solid var(--accent);
overflow: hidden;
z-index: 20;
transform: scaleX(-1);
background: #0a0620;
display: none;
box-shadow: 0 0 20px var(--accent-soft);
}
#cam-canvas { width: 100%; height: 100%; }
.controls-container {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
z-index: 20;
width: 92%;
max-width: 560px;
}
.sliders {
display: flex;
align-items: center;
gap: 12px;
padding: 9px 18px;
pointer-events: auto;
}
label { font-size: 0.7rem; color: var(--accent); letter-spacing: 0.08em; text-transform: uppercase; }
input[type=range] {
-webkit-appearance: none;
appearance: none;
width: 150px;
height: 4px;
background: rgba(180, 160, 255, 0.18);
border-radius: 4px;
outline: none;
}
input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none;
width: 15px;
height: 15px;
border-radius: 50%;
background: var(--accent);
cursor: pointer;
box-shadow: 0 0 10px var(--accent-soft);
}
.controls { display: flex; gap: 12px; align-items: center; }
.btn {
font-family: inherit;
font-size: 0.76rem;
color: var(--text);
background: var(--panel-bg);
border: 1px solid var(--panel-border);
border-radius: 24px;
padding: 9px 22px;
cursor: pointer;
backdrop-filter: blur(8px);
letter-spacing: 0.06em;
text-transform: uppercase;
transition: border-color 0.2s ease, box-shadow 0.2s ease;
pointer-events: auto;
display: flex;
align-items: center;
gap: 8px;
}
.btn:hover { border-color: var(--accent); box-shadow: 0 0 16px var(--accent-soft); }
.btn.is-active { border-color: var(--orange); color: #ffd0b8; }
#gesture-guide {
position: absolute;
top: 16px;
right: 16px;
z-index: 10;
text-align: right;
padding: 12px 12px;
max-height: 78vh;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 4px;
}
.guide-hint {
font-size: 0.62rem;
letter-spacing: 0.14em;
text-transform: uppercase;
color: var(--text-dim);
padding: 2px 8px 6px;
}
.guide-item {
font-family: inherit;
font-size: 0.74rem;
display: flex;
align-items: center;
justify-content: flex-end;
gap: 10px;
color: var(--text-dim);
background: transparent;
border: 1px solid transparent;
border-radius: 9px;
padding: 5px 8px;
cursor: pointer;
transition: border-color 0.15s ease, background 0.15s ease, color 0.15s ease;
}
.guide-item:hover { border-color: var(--panel-border); background: rgba(180, 160, 255, 0.08); color: var(--text); }
.guide-item.is-current { border-color: var(--accent); color: var(--text); background: var(--accent-soft); }
.hotkey {
font-size: 0.62rem;
color: var(--text-dim);
border: 1px solid var(--panel-border);
border-radius: 4px;
padding: 1px 5px;
}
#formation-chip {
position: absolute;
bottom: 92px;
left: 16px;
z-index: 10;
display: flex;
align-items: baseline;
gap: 10px;
padding: 9px 16px;
pointer-events: none;
}
#formation-name { font-size: 0.86rem; font-weight: 600; letter-spacing: 0.08em; }
#fs-btn {
position: absolute;
bottom: 20px;
right: 16px;
z-index: 20;
width: 38px;
height: 38px;
display: grid;
place-items: center;
border-radius: 50%;
padding: 0;
}
#fs-btn.is-unavailable { display: none; }
.key {
font-weight: 600;
color: var(--accent);
background: rgba(180, 160, 255, 0.1);
border: 1px solid var(--panel-border);
padding: 2px 9px;
border-radius: 6px;
}
#guide-toggle {
position: absolute;
top: 16px;
right: 16px;
z-index: 11;
width: 36px;
height: 36px;
display: none;
place-items: center;
border-radius: 50%;
padding: 0;
}
@media (max-width: 720px) {
#guide-toggle { display: grid; }
#gesture-guide { display: none; top: 60px; }
#gesture-guide.is-open { display: block; }
#ui-layer { max-width: 230px; }
}
#toast {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 18px 36px;
font-size: 1.2rem;
letter-spacing: 0.08em;
opacity: 0;
pointer-events: none;
transition: opacity 0.5s, transform 0.5s;
z-index: 100;
text-align: center;
box-shadow: 0 0 30px var(--accent-soft);
}
#loader {
position: fixed;
inset: 0;
background: #06021a;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
z-index: 1000;
transition: opacity 1s;
}
#loading-text { font-size: 0.78rem; letter-spacing: 0.2em; text-transform: uppercase; color: var(--text-dim); }
.spinner {
width: 44px;
height: 44px;
border: 2px solid rgba(180, 160, 255, 0.25);
border-radius: 50%;
border-top-color: var(--accent);
animation: spin 1s ease-in-out infinite;
margin-bottom: 18px;
}
.spinner.inline {
width: 14px;
height: 14px;
border-width: 2px;
margin: 0;
display: inline-block;
}
@keyframes spin { to { transform: rotate(360deg); } }
</style>
<script type="importmap">
{ "imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/"
} }
</script>
</head>
<body data-modern="1">
<div id="loader">
<div class="spinner"></div>
<div id="loading-text">Initializing universe…</div>
</div>
<div id="stage"></div>
<div id="ui-layer" class="panel">
<p class="kicker">Experiment</p>
<h1>Celestial Hand Control</h1>
<p>Use your webcam to shape the cosmos.</p>
</div>
<button id="guide-toggle" class="btn panel" type="button" aria-label="Toggle gesture guide">?</button>
<div id="gesture-guide" class="panel">
<p class="guide-hint">Click, press 1–8, or gesture on camera</p>
<button class="guide-item" type="button" data-formation="sphere"><span class="hotkey">1</span><span class="key">Fist ✊</span> Solar Sphere</button>
<button class="guide-item" type="button" data-formation="sagittarius"><span class="hotkey">2</span><span class="key">Point ☝️</span> Sagittarius</button>
<button class="guide-item" type="button" data-formation="galaxy"><span class="hotkey">3</span><span class="key">Open Palm ✋</span> Galaxy</button>
<button class="guide-item" type="button" data-formation="taurus"><span class="hotkey">4</span><span class="key">Peace ✌️</span> Taurus</button>
<button class="guide-item" type="button" data-formation="orion"><span class="hotkey">5</span><span class="key">Rock On 🤘</span> Orion</button>
<button class="guide-item" type="button" data-formation="cassiopeia"><span class="hotkey">6</span><span class="key">Three 🖖</span> Cassiopeia</button>
<button class="guide-item" type="button" data-formation="blackhole"><span class="hotkey">7</span><span class="key">OK Sign 👌</span> Black Hole</button>
<button class="guide-item" type="button" data-formation="bigbang"><span class="hotkey">8</span><span class="key">Apart 🙌</span> Big Bang</button>
</div>
<div id="formation-chip" class="panel"><span class="kicker">Formation</span><span id="formation-name">Universe</span></div>
<button id="fs-btn" class="btn panel" type="button" aria-label="Toggle fullscreen">⛶</button>
<div id="toast" class="panel">Formation Detected</div>
<video id="input-video" playsinline></video>
<div class="camera-feed" id="camera-feed">
<canvas id="cam-canvas" width="160" height="120"></canvas>
</div>
<div class="controls-container">
<div class="sliders panel">
<label for="size-slider">Particle Size</label>
<input type="range" id="size-slider" min="0.1" max="5.0" step="0.1" value="1.5">
</div>
<div class="controls">
<button id="cam-btn" class="btn" type="button"><span>📷</span> Enable Camera</button>
<button id="reset-btn" class="btn" type="button">Reset</button>
</div>
</div>
<script type="module">
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
/**
* INTERNAL TWEEN IMPLEMENTATION
*/
const TWEEN = {
tweens: [],
removeAll() { this.tweens = []; },
add(tween) { this.tweens.push(tween); },
update(time) {
if (this.tweens.length === 0) return false;
let i = 0;
time = time !== undefined ? time : performance.now();
while (i < this.tweens.length) {
if (this.tweens[i].update(time)) i++;
else this.tweens.splice(i, 1);
}
return true;
},
Easing: {
Exponential: {
InOut(k) {
if (k === 0) return 0;
if (k === 1) return 1;
if ((k *= 2) < 1) return 0.5 * Math.pow(1024, k - 1);
return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
},
Out(k) { return k === 1 ? 1 : 1 - Math.pow(2, -10 * k); }
},
Elastic: {
Out(k) {
if (k === 0) return 0;
if (k === 1) return 1;
return Math.pow(2, -10 * k) * Math.sin((k * 10 - 0.75) * (2 * Math.PI) / 0.3) + 1;
}
}
}
};
class Tween {
constructor(object) {
this.object = object;
this.valuesStart = {};
this.valuesEnd = {};
this.duration = 1000;
this.startTime = null;
this.easingFunction = TWEEN.Easing.Exponential.InOut;
this.onUpdateCallback = null;
}
to(properties, duration) {
this.valuesEnd = properties;
if (duration !== undefined) this.duration = duration;
return this;
}
easing(easing) { this.easingFunction = easing; return this; }
onUpdate(callback) { this.onUpdateCallback = callback; return this; }
start(time) {
this.startTime = time !== undefined ? time : performance.now();
for (const property in this.valuesEnd) {
this.valuesStart[property] = parseFloat(this.object[property]);
}
TWEEN.add(this);
return this;
}
update(time) {
if (time < this.startTime) return true;
let elapsed = (time - this.startTime) / this.duration;
elapsed = elapsed > 1 ? 1 : elapsed;
const value = this.easingFunction(elapsed);
for (const property in this.valuesEnd) {
const start = this.valuesStart[property];
const end = this.valuesEnd[property];
this.object[property] = start + (end - start) * value;
}
if (this.onUpdateCallback) this.onUpdateCallback(this.object);
return elapsed < 1;
}
}
TWEEN.Tween = Tween;
/**
* APPLICATION CONFIG
*/
const CONFIG = {
particleCount: 8000,
baseSize: 1.5
};
let scene, camera, renderer, controls;
let particles, geometry, material;
const targets = {
universe: [], sphere: [], galaxy: [], sagittarius: [],
bigbang: [], taurus: [], orion: [], cassiopeia: [], blackhole: []
};
let currentShape = "universe";
const toast = document.getElementById("toast");
const sizeSlider = document.getElementById("size-slider");
// Hand tracking state
let landmarker = null;
let isCameraActive = false;
let handDistanceHistory = [];
let lastVideoTime = -1;
init();
animate();
function init() {
scene = new THREE.Scene();
scene.fog = new THREE.FogExp2(0x06021a, 0.0012);
camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 3000);
camera.position.z = 400;
renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 1.5));
renderer.setSize(innerWidth, innerHeight);
document.getElementById("stage").appendChild(renderer.domElement);
controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
controls.autoRotate = true;
controls.autoRotateSpeed = 0.3;
scene.add(new THREE.AmbientLight(0xffffff, 0.5));
createParticles();
sizeSlider.addEventListener("input", (e) => {
if (material && material.uniforms) {
material.uniforms.globalScale.value = parseFloat(e.target.value);
}
});
document.getElementById("cam-btn").addEventListener("click", toggleCamera);
document.getElementById("reset-btn").addEventListener("click", resetUniverse);
const guide = document.getElementById("gesture-guide");
document.getElementById("guide-toggle").addEventListener("click", () => {
guide.classList.toggle("is-open");
});
// Formations are clickable and keyboard-driven — the camera is
// the magic path, not the only path.
const formationButtons = [...document.querySelectorAll("[data-formation]")];
for (const btn of formationButtons) {
btn.addEventListener("click", () => triggerFormationByName(btn.dataset.formation));
}
window.addEventListener("keydown", (e) => {
const idx = Number(e.key) - 1;
if (idx >= 0 && idx < formationButtons.length) {
triggerFormationByName(formationButtons[idx].dataset.formation);
}
});
const fsBtn = document.getElementById("fs-btn");
if (!document.fullscreenEnabled) fsBtn.classList.add("is-unavailable");
fsBtn.addEventListener("click", () => {
if (document.fullscreenElement) document.exitFullscreen();
else document.documentElement.requestFullscreen().catch(() => showToast("Fullscreen unavailable"));
});
window.addEventListener("resize", onWindowResize, false);
setTimeout(() => {
const loader = document.getElementById("loader");
if (loader) {
loader.style.opacity = "0";
setTimeout(() => loader.remove(), 1000);
}
}, 1000);
}
// --- PARTICLE SYSTEMS ---
function createParticles() {
geometry = new THREE.BufferGeometry();
const positions = [];
const colors = [];
const sizes = [];
const colorObj = new THREE.Color();
// Element types, retinted to the site palette.
const elements = [
{ type: "stardust", r: 0.7, sizeMin: 0.5, sizeMax: 2.0, colors: [0xc8b0ff, 0x00e5ff, 0x5f2c82, 0x7dffb3] },
{ type: "star", r: 0.25, sizeMin: 3.0, sizeMax: 6.0, colors: [0xffffff, 0xffeebb, 0xffd700] },
{ type: "giant", r: 0.05, sizeMin: 8.0, sizeMax: 15.0, colors: [0xff6b35, 0xff416c, 0xff8c00] }
];
for (let i = 0; i < CONFIG.particleCount; i++) {
const x = (Math.random() * 2 - 1) * 800;
const y = (Math.random() * 2 - 1) * 800;
const z = (Math.random() * 2 - 1) * 800;
positions.push(x, y, z);
targets.universe.push(new THREE.Vector3(x, y, z));
targets.bigbang.push(new THREE.Vector3(0, 0, 0));
const rand = Math.random();
let type;
if (rand < elements[0].r) type = elements[0];
else if (rand < elements[0].r + elements[1].r) type = elements[1];
else type = elements[2];
colorObj.setHex(type.colors[Math.floor(Math.random() * type.colors.length)]);
colors.push(colorObj.r, colorObj.g, colorObj.b);
sizes.push(type.sizeMin + Math.random() * (type.sizeMax - type.sizeMin));
}
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
geometry.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3));
geometry.setAttribute("size", new THREE.Float32BufferAttribute(sizes, 1));
material = new THREE.ShaderMaterial({
uniforms: {
pointTexture: { value: getStarTexture() },
globalScale: { value: parseFloat(sizeSlider.value) }
},
vertexShader: `
attribute float size;
varying vec3 vColor;
uniform float globalScale;
void main() {
vColor = color;
vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
gl_PointSize = size * globalScale * ( 300.0 / -mvPosition.z );
gl_Position = projectionMatrix * mvPosition;
}
`,
fragmentShader: `
uniform sampler2D pointTexture;
varying vec3 vColor;
void main() {
gl_FragColor = vec4( vColor, 1.0 );
gl_FragColor = gl_FragColor * texture2D( pointTexture, gl_PointCoord );
if ( gl_FragColor.a < 0.1 ) discard;
}
`,
blending: THREE.AdditiveBlending,
depthWrite: false,
transparent: true,
vertexColors: true
});
particles = new THREE.Points(geometry, material);
scene.add(particles);
calculateShapes();
}
function getStarTexture() {
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(0.2, "rgba(255,255,255,0.8)");
grad.addColorStop(0.5, "rgba(255,255,255,0.2)");
grad.addColorStop(1, "rgba(0,0,0,0)");
ctx.fillStyle = grad;
ctx.fillRect(0, 0, 32, 32);
return new THREE.CanvasTexture(canvas);
}
function calculateShapes() {
const fillPoints = (targetArr, p1, p2, count) => {
for (let k = 0; k < count; k++) {
const v = new THREE.Vector3().lerpVectors(p1, p2, Math.random());
v.x += (Math.random() - 0.5) * 15;
v.y += (Math.random() - 0.5) * 15;
v.z += (Math.random() - 0.5) * 15;
targetArr.push(v);
}
};
// 1. Sphere
for (let i = 0; i < CONFIG.particleCount; i++) {
const phi = Math.acos(-1 + (2 * i) / CONFIG.particleCount);
const theta = Math.sqrt(CONFIG.particleCount * Math.PI) * phi;
const v = new THREE.Vector3();
v.setFromSphericalCoords(300, phi, theta);
targets.sphere.push(v);
}
// 2. Galaxy
for (let i = 0; i < CONFIG.particleCount; i++) {
const angle = i * 0.05;
const r = i * 0.12;
const armOffset = (i % 3) * (Math.PI * 2 / 3);
targets.galaxy.push(new THREE.Vector3(
Math.cos(angle + armOffset) * r * 2.5,
(Math.random() - 0.5) * 60,
Math.sin(angle + armOffset) * r * 2.5
));
}
// 3. Sagittarius
const sagPoints = [
new THREE.Vector3(0, 0, 0), new THREE.Vector3(50, 40, 0),
new THREE.Vector3(30, 80, 0), new THREE.Vector3(-40, 30, 0),
new THREE.Vector3(80, 50, 0), new THREE.Vector3(-60, 100, 0),
new THREE.Vector3(-80, 60, 0), new THREE.Vector3(120, 50, 0)
].map((v) => v.multiplyScalar(3.5));
for (let i = 0; i < CONFIG.particleCount; i++) {
const idx = i % sagPoints.length;
const p1 = sagPoints[idx];
const p2 = sagPoints[(idx + 1) % sagPoints.length];
if (Math.random() > 0.4) {
targets.sagittarius.push(new THREE.Vector3(
p1.x + (Math.random() - 0.5) * 60,
p1.y + (Math.random() - 0.5) * 60,
p1.z + (Math.random() - 0.5) * 60
));
} else {
const mixed = new THREE.Vector3().lerpVectors(p1, p2, Math.random());
mixed.x += (Math.random() - 0.5) * 10;
mixed.y += (Math.random() - 0.5) * 10;
mixed.z += (Math.random() - 0.5) * 10;
targets.sagittarius.push(mixed);
}
}
// 4. Taurus (V shape)
const taurusCenter = new THREE.Vector3(0, -50, 0);
const hornLeft = new THREE.Vector3(-150, 150, 0);
const hornRight = new THREE.Vector3(150, 150, 0);
const taurusArr = [];
fillPoints(taurusArr, taurusCenter, hornLeft, CONFIG.particleCount / 2);
fillPoints(taurusArr, taurusCenter, hornRight, CONFIG.particleCount / 2);
for (let i = 0; i < CONFIG.particleCount; i++) {
targets.taurus.push(taurusArr[i % taurusArr.length]);
}
// 5. Orion
const shoulderL = new THREE.Vector3(-100, 150, 0);
const shoulderR = new THREE.Vector3(100, 150, 0);
const beltL = new THREE.Vector3(-30, 0, 0);
const beltR = new THREE.Vector3(30, 0, 0);
const kneeL = new THREE.Vector3(-80, -150, 0);
const kneeR = new THREE.Vector3(80, -150, 0);
const orionArr = [];
const orionPairs = [
[shoulderL, beltL], [shoulderR, beltR],
[beltL, kneeL], [beltR, kneeR],
[beltL, beltR],
[shoulderL, new THREE.Vector3(-130, 200, 0)],
[shoulderR, new THREE.Vector3(150, 150, 0)]
];
orionPairs.forEach((pair) => {
fillPoints(orionArr, pair[0], pair[1], Math.ceil(CONFIG.particleCount / orionPairs.length));
});
for (let i = 0; i < CONFIG.particleCount; i++) {
targets.orion.push(orionArr[i % orionArr.length]);
}
// 6. Cassiopeia (W shape)
const cassPoints = [
new THREE.Vector3(-150, 100, 0),
new THREE.Vector3(-75, -50, 0),
new THREE.Vector3(0, 50, 0),
new THREE.Vector3(75, -50, 0),
new THREE.Vector3(150, 100, 0)
];
const cassArr = [];
for (let i = 0; i < cassPoints.length - 1; i++) {
fillPoints(cassArr, cassPoints[i], cassPoints[i + 1], Math.ceil(CONFIG.particleCount / 4));
}
for (let i = 0; i < CONFIG.particleCount; i++) {
targets.cassiopeia.push(cassArr[i % cassArr.length]);
}
// 7. Black hole (accretion disk)
for (let i = 0; i < CONFIG.particleCount; i++) {
const angle = Math.random() * Math.PI * 2;
const r = 120 + Math.random() * 250;
targets.blackhole.push(new THREE.Vector3(
Math.cos(angle) * r,
(Math.random() - 0.5) * (4000 / r),
Math.sin(angle) * r
));
}
}
// --- COMPUTER VISION (MediaPipe tasks-vision) ---
const videoElement = document.getElementById("input-video");
const camBtn = document.getElementById("cam-btn");
const feedContainer = document.getElementById("camera-feed");
const camCanvas = document.getElementById("cam-canvas");
const camCtx = camCanvas.getContext("2d");
const CAM_IDLE_HTML = "<span>📷</span> Enable Camera";
const resetCamButton = () => {
camBtn.innerHTML = CAM_IDLE_HTML;
camBtn.classList.remove("is-active");
};
const loadLandmarker = async () => {
if (landmarker) return landmarker;
const { HandLandmarker, FilesetResolver } = await import("https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.18/+esm");
const vision = await FilesetResolver.forVisionTasks("https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.18/wasm");
landmarker = 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
});
return landmarker;
};
async function toggleCamera() {
if (isCameraActive) {
isCameraActive = false;
if (videoElement.srcObject) {
videoElement.srcObject.getTracks().forEach((t) => t.stop());
videoElement.srcObject = null;
}
resetCamButton();
feedContainer.style.display = "none";
controls.enabled = true;
return;
}
camBtn.innerHTML = '<span class="spinner inline"></span> Loading AI…';
try {
await loadLandmarker();
} catch (err) {
console.warn("hand landmarker failed to load", err);
resetCamButton();
showToast("Hand-tracking model failed to load");
return;
}
let stream;
try {
stream = await navigator.mediaDevices.getUserMedia({ video: { width: 640, height: 480 } });
} catch {
resetCamButton();
showToast("Camera unavailable — permission denied");
return;
}
videoElement.srcObject = stream;
await videoElement.play();
isCameraActive = true;
camBtn.innerHTML = "🔴 Stop Camera";
camBtn.classList.add("is-active");
feedContainer.style.display = "block";
const detectLoop = () => {
if (!isCameraActive) return;
if (videoElement.currentTime !== lastVideoTime && videoElement.videoWidth > 0) {
lastVideoTime = videoElement.currentTime;
const result = landmarker.detectForVideo(videoElement, performance.now());
drawPreview(result.landmarks);
if (result.landmarks && result.landmarks.length > 0) {
detectGesture(result.landmarks);
}
}
if (videoElement.requestVideoFrameCallback) {
videoElement.requestVideoFrameCallback(detectLoop);
} else {
requestAnimationFrame(detectLoop);
}
};
detectLoop();
}
// 21-landmark hand topology connections.
const HAND_CONNECTIONS = [
[0, 1], [1, 2], [2, 3], [3, 4],
[0, 5], [5, 6], [6, 7], [7, 8],
[5, 9], [9, 10], [10, 11], [11, 12],
[9, 13], [13, 14], [14, 15], [15, 16],
[13, 17], [17, 18], [18, 19], [19, 20], [0, 17]
];
function drawPreview(allLandmarks) {
const w = camCanvas.width;
const h = camCanvas.height;
camCtx.drawImage(videoElement, 0, 0, w, h);
if (!allLandmarks) return;
for (const lm of allLandmarks) {
camCtx.strokeStyle = "#c8b0ff";
camCtx.lineWidth = 2;
for (const [a, b] of HAND_CONNECTIONS) {
camCtx.beginPath();
camCtx.moveTo(lm[a].x * w, lm[a].y * h);
camCtx.lineTo(lm[b].x * w, lm[b].y * h);
camCtx.stroke();
}
camCtx.fillStyle = "#00e5ff";
for (const p of lm) {
camCtx.beginPath();
camCtx.arc(p.x * w, p.y * h, 2, 0, Math.PI * 2);
camCtx.fill();
}
}
}
function detectGesture(allLandmarks) {
if (!allLandmarks || allLandmarks.length === 0) return;
const hand1 = allLandmarks[0];
const hand2 = allLandmarks.length > 1 ? allLandmarks[1] : null;
// 1. ZOOM (hand size drives camera distance)
const size = dist(hand1[0], hand1[5]);
const targetCamZ = 1200 - (size * 4000);
camera.position.z += (THREE.MathUtils.clamp(targetCamZ, 100, 1000) - camera.position.z) * 0.05;
// 2. TWO HANDS: Big Bang (hands flying apart)
if (hand2) {
const d = dist(hand1[9], hand2[9]);
handDistanceHistory.push({ d, t: performance.now() });
if (handDistanceHistory.length > 10) handDistanceHistory.shift();
if (handDistanceHistory.length >= 5) {
const oldest = handDistanceHistory[0];
const newest = handDistanceHistory[handDistanceHistory.length - 1];
const vel = (newest.d - oldest.d) / (newest.t - oldest.t);
if (vel > 0.0005 && d > 0.4 && currentShape !== "bigbang") {
triggerFormation("bigbang", targets.universe);
showToast("💥 BIG BANG 💥");
return;
}
}
}
// 3. SINGLE-HAND GESTURES
// MediaPipe Y grows downward: tip above pip means the finger is up.
const isIndexUp = (lm) => lm[8].y < lm[6].y;
const isMiddleUp = (lm) => lm[12].y < lm[10].y;
const isRingUp = (lm) => lm[16].y < lm[14].y;
const isPinkyUp = (lm) => lm[20].y < lm[18].y;
const isFist = !isIndexUp(hand1) && !isMiddleUp(hand1) && !isRingUp(hand1) && !isPinkyUp(hand1);
const isPointing = isIndexUp(hand1) && !isMiddleUp(hand1) && !isRingUp(hand1) && !isPinkyUp(hand1);
const isOpenPalm = isIndexUp(hand1) && isMiddleUp(hand1) && isRingUp(hand1) && isPinkyUp(hand1);
const isPeace = isIndexUp(hand1) && isMiddleUp(hand1) && !isRingUp(hand1) && !isPinkyUp(hand1);
const isRock = isIndexUp(hand1) && !isMiddleUp(hand1) && !isRingUp(hand1) && isPinkyUp(hand1);
const isThree = isIndexUp(hand1) && isMiddleUp(hand1) && isRingUp(hand1) && !isPinkyUp(hand1);
const dOk = dist(hand1[8], hand1[4]);
const isOk = dOk < 0.05 && isMiddleUp(hand1) && isRingUp(hand1);
if (isOk && currentShape !== "blackhole") {
triggerFormation("blackhole", targets.blackhole);
showToast("Black Hole ⚫");
} else if (isRock && currentShape !== "orion") {
triggerFormation("orion", targets.orion);
showToast("Orion Hunter 🏹");
} else if (isPeace && currentShape !== "taurus") {
triggerFormation("taurus", targets.taurus);
showToast("Taurus Bull 🐂");
} else if (isThree && currentShape !== "cassiopeia") {
triggerFormation("cassiopeia", targets.cassiopeia);
showToast("Cassiopeia 👑");
} else if (isFist && currentShape !== "sphere") {
triggerFormation("sphere", targets.sphere);
showToast("Solar Sphere ☀️");
} else if (isPointing && currentShape !== "sagittarius") {
triggerFormation("sagittarius", targets.sagittarius);
showToast("Sagittarius 🏹");
} else if (isOpenPalm && currentShape !== "galaxy" && !hand2) {
triggerFormation("galaxy", targets.galaxy);
showToast("Galaxy Spiral 🌀");
}
}
function dist(p1, p2) {
return Math.hypot(p1.x - p2.x, p1.y - p2.y);
}
// --- ANIMATION & LOGIC ---
const FORMATION_LABELS = {
universe: "Universe", sphere: "Solar Sphere", sagittarius: "Sagittarius",
galaxy: "Galaxy Spiral", taurus: "Taurus Bull", orion: "Orion Hunter",
cassiopeia: "Cassiopeia", blackhole: "Black Hole", bigbang: "Big Bang"
};
const FORMATION_TOASTS = {
sphere: "Solar Sphere ☀️", sagittarius: "Sagittarius 🏹", galaxy: "Galaxy Spiral 🌀",
taurus: "Taurus Bull 🐂", orion: "Orion Hunter 🏹", cassiopeia: "Cassiopeia 👑",
blackhole: "Black Hole ⚫", bigbang: "💥 BIG BANG 💥"
};
function triggerFormationByName(name) {
if (currentShape === name && name !== "bigbang") return;
triggerFormation(name, targets[name === "bigbang" ? "universe" : name]);
showToast(FORMATION_TOASTS[name] || FORMATION_LABELS[name]);
}
function updateFormationChip() {
document.getElementById("formation-name").textContent = FORMATION_LABELS[currentShape] || currentShape;
for (const btn of document.querySelectorAll("[data-formation]")) {
btn.classList.toggle("is-current", btn.dataset.formation === currentShape);
}
}
function triggerFormation(name, targetSet) {
currentShape = name;
updateFormationChip();
if (name === "bigbang") {
transformTo(targets.bigbang, 500);
setTimeout(() => {
transformTo(targets.universe, 300, TWEEN.Easing.Exponential.Out);
currentShape = "universe";
updateFormationChip();
}, 600);
} else if (name === "blackhole") {
transformTo(targetSet, 2000, TWEEN.Easing.Elastic.Out);
} else {
transformTo(targetSet, 1500);
}
}
function transformTo(targetSet, duration, easing) {
TWEEN.removeAll();
const positions = particles.geometry.attributes.position.array;
const ease = easing || TWEEN.Easing.Exponential.InOut;
for (let i = 0; i < CONFIG.particleCount; i++) {
const target = targetSet[i];
const offset = i * 3;
const current = { x: positions[offset], y: positions[offset + 1], z: positions[offset + 2] };
new TWEEN.Tween(current)
.to({ x: target.x, y: target.y, z: target.z }, Math.random() * duration + duration)
.easing(ease)
.onUpdate(() => {
positions[offset] = current.x;
positions[offset + 1] = current.y;
positions[offset + 2] = current.z;
})
.start();
}
}
function resetUniverse() {
triggerFormation("universe", targets.universe);
showToast("Universe Reset");
}
let toastTimer = null;
function showToast(msg) {
toast.innerText = msg;
toast.style.opacity = "1";
toast.style.transform = "translate(-50%, -50%) scale(1.08)";
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
toast.style.opacity = "0";
toast.style.transform = "translate(-50%, -50%) scale(1)";
}, 2500);
}
function onWindowResize() {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
}
function animate() {
requestAnimationFrame(animate);
TWEEN.update();
if (!isCameraActive) controls.update();
if (particles) {
particles.rotation.y += 0.0005;
particles.geometry.attributes.position.needsUpdate = true;
}
renderer.render(scene, camera);
}
</script>
</body>
</html>