LABORATORY // EXPERIMENT_ACTIVE
MODULE: FIBONACCI_SPHERE
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fibonacci Sphere</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%);
}
#stage { position: absolute; inset: 0; z-index: 1; cursor: move; touch-action: none; }
#stage canvas { display: block; }
.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);
}
#controls {
position: absolute;
top: 16px;
left: 16px;
z-index: 10;
width: 300px;
max-height: calc(100vh - 32px);
display: flex;
flex-direction: column;
transition: opacity 0.25s ease, transform 0.25s ease;
}
#controls.is-hidden { opacity: 0; transform: translateX(-16px); pointer-events: none; }
#controls header {
padding: 14px 16px;
border-bottom: 1px solid var(--panel-border);
}
#controls h1 { font-size: 1rem; font-weight: 700; letter-spacing: 0.06em; margin-top: 2px; }
#controls .body {
padding: 14px 16px;
overflow-y: auto;
display: grid;
gap: 16px;
scrollbar-width: thin;
scrollbar-color: rgba(180, 160, 255, 0.3) transparent;
}
.group { display: grid; gap: 8px; }
.group-title { font-size: 0.62rem; letter-spacing: 0.26em; text-transform: uppercase; color: var(--text-dim); }
.row { display: flex; gap: 8px; align-items: center; }
.btn {
font-family: inherit;
font-size: 0.74rem;
color: var(--text);
background: rgba(180, 160, 255, 0.08);
border: 1px solid var(--panel-border);
border-radius: 9px;
padding: 7px 12px;
cursor: pointer;
transition: border-color 0.15s ease, background 0.15s ease;
}
.btn:hover { border-color: var(--accent); background: rgba(180, 160, 255, 0.14); }
.btn[disabled] { opacity: 0.4; cursor: not-allowed; }
.btn.is-on { border-color: var(--accent); background: var(--accent-soft); color: #fff; }
.btn.flex { flex: 1; }
.seg { display: flex; background: rgba(180, 160, 255, 0.06); border: 1px solid var(--panel-border); border-radius: 9px; padding: 3px; }
.seg button {
flex: 1;
font-family: inherit;
font-size: 0.7rem;
text-transform: capitalize;
color: var(--text-dim);
background: transparent;
border: 0;
border-radius: 6px;
padding: 5px 0;
cursor: pointer;
}
.seg button.is-active { background: var(--accent-soft); color: #fff; }
.slider-row { display: grid; gap: 4px; }
.slider-row .label { display: flex; justify-content: space-between; font-size: 0.68rem; color: var(--text-dim); }
.slider-row .label output { color: var(--text); }
input[type=range] {
-webkit-appearance: none;
appearance: none;
width: 100%;
height: 4px;
background: rgba(180, 160, 255, 0.18);
border-radius: 4px;
outline: none;
}
input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none;
width: 14px;
height: 14px;
border-radius: 50%;
background: var(--accent);
cursor: pointer;
box-shadow: 0 0 10px var(--accent-soft);
}
input[type=number] {
font-family: inherit;
font-size: 0.74rem;
width: 100%;
color: var(--text);
background: rgba(180, 160, 255, 0.06);
border: 1px solid var(--panel-border);
border-radius: 8px;
padding: 6px 8px;
outline: none;
}
input[type=number]:focus { border-color: var(--accent); }
input[type=color] {
width: 34px;
height: 28px;
border: 1px solid var(--panel-border);
border-radius: 8px;
background: transparent;
padding: 2px;
cursor: pointer;
}
#toggle-ui, #fs-btn {
position: absolute;
top: 16px;
right: 16px;
z-index: 20;
width: 36px;
height: 36px;
display: grid;
place-items: center;
font-size: 0.9rem;
border-radius: 50%;
padding: 0;
}
#fs-btn { top: 60px; }
#fs-btn.is-unavailable { display: none; }
body.is-dropping::before { filter: brightness(1.6); }
#toast {
position: absolute;
bottom: 24px;
left: 50%;
transform: translateX(-50%);
z-index: 30;
padding: 10px 22px;
font-size: 0.78rem;
opacity: 0;
pointer-events: none;
transition: opacity 0.4s ease;
}
#toast.is-active { opacity: 1; }
@media (max-width: 640px) {
#controls { width: calc(100vw - 64px); max-width: 300px; }
}
</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>
<div id="stage"></div>
<button id="toggle-ui" class="btn panel" type="button" aria-label="Toggle controls">⊟</button>
<button id="fs-btn" class="btn panel" type="button" aria-label="Toggle fullscreen">⛶</button>
<aside id="controls" class="panel">
<header>
<p class="kicker">Experiment</p>
<h1>Fibonacci Sphere</h1>
</header>
<div class="body">
<div class="group">
<p class="group-title">Audio Source</p>
<div class="row">
<button class="btn flex" id="demo-btn" type="button">✦ Demo</button>
<label class="btn flex" id="file-label">📁 <span id="file-name">Load Audio</span>
<input type="file" id="file-input" accept="audio/*" hidden>
</label>
<button class="btn" id="mic-btn" type="button">🎙</button>
<button class="btn" id="play-btn" type="button" disabled>▶</button>
</div>
<p class="group-title" style="text-transform:none;letter-spacing:0.04em">or drop an audio file anywhere</p>
</div>
<div class="group">
<p class="group-title">Presets</p>
<div class="row">
<button class="btn flex" data-preset="nebula" type="button">Nebula</button>
<button class="btn flex" data-preset="pulse" type="button">Pulse</button>
<button class="btn flex" data-preset="lattice" type="button">Lattice</button>
</div>
</div>
<div class="group">
<p class="group-title">Shape</p>
<div class="seg" id="shape-seg">
<button type="button" data-shape="sphere" class="is-active">sphere</button>
<button type="button" data-shape="cube">cube</button>
<button type="button" data-shape="torus">torus</button>
</div>
<div class="slider-row">
<div class="label"><span>Noise</span><output id="noise-out">0.50</output></div>
<input type="range" id="noise-range" min="0" max="2" step="0.05" value="0.5">
</div>
<div class="slider-row">
<div class="label"><span>Rotation</span><output id="rot-out">0.20</output></div>
<input type="range" id="rot-range" min="0" max="2" step="0.05" value="0.2">
</div>
</div>
<div class="group">
<p class="group-title">Visuals</p>
<div class="row">
<button class="btn flex" id="plexus-btn" type="button">Plexus: Off</button>
<button class="btn flex is-on" id="planets-btn" type="button">Planets: On</button>
</div>
<div class="row">
<button class="btn flex is-on" id="rainbow-btn" type="button">Rainbow: On</button>
<input type="color" id="color-input" value="#c8b0ff" aria-label="Base color">
</div>
<div class="row">
<div class="slider-row" style="flex:1">
<div class="label"><span>Points</span></div>
<input type="number" id="count-input" min="100" max="10000" step="100" value="1500">
</div>
<div class="slider-row" style="flex:1">
<div class="label"><span>Size</span></div>
<input type="number" id="size-input" min="0.1" max="3" step="0.1" value="0.5">
</div>
</div>
</div>
<div class="group">
<p class="group-title">Reactivity</p>
<div class="slider-row">
<div class="label"><span>Gain</span><output id="gain-out">2.0</output></div>
<input type="range" id="gain-range" min="0" max="5" step="0.1" value="2">
</div>
<div class="slider-row">
<div class="label"><span>Bass Boost</span><output id="bass-out">1.2</output></div>
<input type="range" id="bass-range" min="0" max="3" step="0.1" value="1.2">
</div>
</div>
</div>
</aside>
<div id="toast" class="panel"></div>
<script type="module">
import * as THREE from "three";
// ── Params (mutated directly by the controls) ─────────────
const params = {
pointCount: 1500,
radius: 15,
pointSize: 0.5,
rotationSpeed: 0.2,
isRainbow: true,
baseColor: "#c8b0ff",
shape: "sphere",
noiseStrength: 0.5,
noiseSpeed: 0.01,
showConnections: false,
showPlanets: true,
audioGain: 2.0,
bassBoost: 1.2
};
const clampNum = (v, min, max, fallback) => {
const n = Number(v);
if (!Number.isFinite(n)) return fallback;
return Math.max(min, Math.min(max, n));
};
// ── Toast ─────────────────────────────────────────────────
const toastEl = document.getElementById("toast");
let toastTimer = null;
const toast = (msg) => {
toastEl.textContent = msg;
toastEl.classList.add("is-active");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toastEl.classList.remove("is-active"), 2400);
};
// ── Scene ─────────────────────────────────────────────────
const stage = document.getElementById("stage");
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x06021a, 20, 120);
const camera = new THREE.PerspectiveCamera(50, innerWidth / innerHeight, 0.1, 1000);
camera.position.z = 50;
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, powerPreference: "high-performance" });
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 1.5));
stage.appendChild(renderer.domElement);
scene.add(new THREE.AmbientLight(0xffffff, 0.6));
const keyLight = new THREE.PointLight(0xc8b0ff, 120, 300);
keyLight.position.set(20, 20, 20);
scene.add(keyLight);
const fillLight = new THREE.PointLight(0x00e5ff, 60, 300);
fillLight.position.set(-20, -10, 20);
scene.add(fillLight);
const group = new THREE.Group();
scene.add(group);
// ── Glow texture ──────────────────────────────────────────
const glowTexture = (() => {
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);
})();
// ── Shape targets ─────────────────────────────────────────
const targets = { sphere: new Float32Array(0), cube: new Float32Array(0), torus: new Float32Array(0) };
let basePositions = new Float32Array(0);
const generateShapes = (count) => {
const sphere = new Float32Array(count * 3);
const cube = new Float32Array(count * 3);
const torus = new Float32Array(count * 3);
const colors = new Float32Array(count * 3);
const phi = Math.PI * (3 - Math.sqrt(5));
const colorObj = new THREE.Color(params.baseColor);
const tmp = new THREE.Color();
for (let i = 0; i < count; i++) {
const y = 1 - (i / (count - 1)) * 2;
const r = Math.sqrt(1 - y * y);
const theta = phi * i;
const sx = Math.cos(theta) * r;
const sz = Math.sin(theta) * r;
sphere[i * 3] = sx; sphere[i * 3 + 1] = y; sphere[i * 3 + 2] = sz;
const maxComp = Math.max(Math.abs(sx), Math.abs(y), Math.abs(sz));
if (maxComp > 0) {
cube[i * 3] = sx / maxComp; cube[i * 3 + 1] = y / maxComp; cube[i * 3 + 2] = sz / maxComp;
}
// Fibonacci lattice on the torus surface: main-ring angle is
// uniform, tube angle winds by the golden ratio so points
// cover the whole donut evenly instead of tracing one coil.
const u = (i / count) * Math.PI * 2;
const v = ((i * 0.61803398875) % 1) * Math.PI * 2;
torus[i * 3] = (0.8 + 0.4 * Math.cos(v)) * Math.cos(u);
torus[i * 3 + 1] = 0.4 * Math.sin(v);
torus[i * 3 + 2] = (0.8 + 0.4 * Math.cos(v)) * Math.sin(u);
if (params.isRainbow) {
tmp.setHSL(i / count, 0.8, 0.6);
colors[i * 3] = tmp.r; colors[i * 3 + 1] = tmp.g; colors[i * 3 + 2] = tmp.b;
} else {
colors[i * 3] = colorObj.r; colors[i * 3 + 1] = colorObj.g; colors[i * 3 + 2] = colorObj.b;
}
}
targets.sphere = sphere; targets.cube = cube; targets.torus = torus;
basePositions = new Float32Array(sphere);
return colors;
};
// ── Points & plexus ───────────────────────────────────────
const pointsMaterial = new THREE.PointsMaterial({
size: params.pointSize,
vertexColors: true,
map: glowTexture,
alphaTest: 0.01,
transparent: true,
opacity: 0.9,
blending: THREE.AdditiveBlending,
depthWrite: false
});
const linesMaterial = new THREE.LineBasicMaterial({
color: 0xc8b0ff, transparent: true, opacity: 0.15, blending: THREE.AdditiveBlending
});
let points = null;
let lines = null;
const buildGeometry = () => {
const count = params.pointCount;
const colors = generateShapes(count);
if (points) {
group.remove(points);
points.geometry.dispose();
}
if (lines) {
group.remove(lines);
lines.geometry.dispose();
}
const pGeometry = new THREE.BufferGeometry();
pGeometry.setAttribute("position", new THREE.BufferAttribute(new Float32Array(count * 3), 3));
pGeometry.setAttribute("color", new THREE.BufferAttribute(colors, 3));
points = new THREE.Points(pGeometry, pointsMaterial);
group.add(points);
const lGeometry = new THREE.BufferGeometry();
lGeometry.setAttribute("position", new THREE.BufferAttribute(new Float32Array(count * 2 * 3 * 2), 3));
lines = new THREE.LineSegments(lGeometry, linesMaterial);
lines.visible = false;
group.add(lines);
};
buildGeometry();
// ── Planet physics (instanced) ────────────────────────────
const MAX_PLANETS = 15;
const planetsData = [];
const planetsMesh = (() => {
const geometry = new THREE.IcosahedronGeometry(1, 2);
const material = new THREE.MeshStandardMaterial({ roughness: 0.1, metalness: 0.1, emissive: 0x221a3a, color: 0xffffff });
const mesh = new THREE.InstancedMesh(geometry, material, MAX_PLANETS);
mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
const dummy = new THREE.Object3D();
const color = new THREE.Color();
const palette = [0xc8b0ff, 0x00e5ff, 0xff6b35, 0x7dffb3];
for (let i = 0; i < MAX_PLANETS; i++) {
const rad = Math.random() * 0.8 + 0.5;
planetsData.push({
pos: new THREE.Vector3((Math.random() - 0.5) * 15, (Math.random() - 0.5) * 15, (Math.random() - 0.5) * 15),
vel: new THREE.Vector3((Math.random() - 0.5) * 0.2, (Math.random() - 0.5) * 0.2, (Math.random() - 0.5) * 0.2),
radius: rad,
mass: rad * 2
});
dummy.position.copy(planetsData[i].pos);
dummy.scale.setScalar(rad);
dummy.updateMatrix();
mesh.setMatrixAt(i, dummy.matrix);
color.set(palette[i % palette.length]).offsetHSL(0, 0, (Math.random() - 0.5) * 0.15);
mesh.setColorAt(i, color);
}
mesh.instanceColor.needsUpdate = true;
group.add(mesh);
return mesh;
})();
// ── Audio ─────────────────────────────────────────────────
let audioContext = null;
let analyser = null;
let dataArray = null;
let audioElement = null;
let micStream = null;
let micSource = null;
let isPlaying = false;
let audioMode = "none"; // none | file | mic
const ensureAudioContext = () => {
if (!audioContext) audioContext = new (window.AudioContext || window.webkitAudioContext)();
if (audioContext.state === "suspended") audioContext.resume();
return audioContext;
};
const makeAnalyser = () => {
const ctx = ensureAudioContext();
const a = ctx.createAnalyser();
a.fftSize = 2048;
a.smoothingTimeConstant = 0.8;
analyser = a;
dataArray = new Uint8Array(a.frequencyBinCount);
return a;
};
const stopMic = () => {
if (micStream) {
micStream.getTracks().forEach((t) => t.stop());
micStream = null;
}
if (micSource) { micSource.disconnect(); micSource = null; }
micBtn.classList.remove("is-on");
};
const fileInput = document.getElementById("file-input");
const fileName = document.getElementById("file-name");
const playBtn = document.getElementById("play-btn");
const micBtn = document.getElementById("mic-btn");
const demoBtn = document.getElementById("demo-btn");
// ── Generative demo loop (pentatonic arp + bass pulse + pad) ──
let demo = null;
const stopDemo = () => {
if (!demo) return;
clearInterval(demo.interval);
for (const osc of demo.padOscs) { try { osc.stop(); } catch { /* already stopped */ } }
demo.master.disconnect();
demo = null;
demoBtn.classList.remove("is-on");
demoBtn.textContent = "✦ Demo";
};
const startDemo = () => {
const ctx = ensureAudioContext();
stopMic();
if (audioElement && isPlaying) { audioElement.pause(); isPlaying = false; playBtn.textContent = "▶"; }
const a = makeAnalyser();
const master = ctx.createGain();
master.gain.value = 0.5;
master.connect(a);
a.connect(ctx.destination);
// Pad: two detuned saws through a slowly sweeping lowpass.
const filter = ctx.createBiquadFilter();
filter.type = "lowpass";
filter.frequency.value = 600;
const padGain = ctx.createGain();
padGain.gain.value = 0.045;
filter.connect(padGain).connect(master);
const padOscs = [110, 110.7].map((freq) => {
const osc = ctx.createOscillator();
osc.type = "sawtooth";
osc.frequency.value = freq;
osc.connect(filter);
osc.start();
return osc;
});
const lfo = ctx.createOscillator();
const lfoGain = ctx.createGain();
lfo.frequency.value = 0.08;
lfoGain.gain.value = 350;
lfo.connect(lfoGain).connect(filter.frequency);
lfo.start();
padOscs.push(lfo);
// Step sequencer: bass thump on even steps, arp note each step.
const scale = [220, 261.63, 293.66, 329.63, 392, 440];
let step = 0;
const interval = setInterval(() => {
const t = ctx.currentTime;
if (step % 2 === 0) {
const bass = ctx.createOscillator();
const bg = ctx.createGain();
bass.type = "sine";
bass.frequency.setValueAtTime(58, t);
bass.frequency.exponentialRampToValueAtTime(40, t + 0.25);
bg.gain.setValueAtTime(0.5, t);
bg.gain.exponentialRampToValueAtTime(0.001, t + 0.32);
bass.connect(bg).connect(master);
bass.start(t);
bass.stop(t + 0.32);
}
const arp = ctx.createOscillator();
const ag = ctx.createGain();
arp.type = "triangle";
const note = scale[(step * 3 + Math.floor(step / 8)) % scale.length];
arp.frequency.value = step % 8 < 4 ? note : note * 2;
ag.gain.setValueAtTime(0.07, t);
ag.gain.exponentialRampToValueAtTime(0.001, t + 0.22);
arp.connect(ag).connect(master);
arp.start(t);
arp.stop(t + 0.22);
step += 1;
}, 250);
demo = { master, interval, padOscs };
audioMode = "demo";
demoBtn.classList.add("is-on");
demoBtn.textContent = "✦ Demo On";
};
demoBtn.addEventListener("click", () => {
if (demo) {
stopDemo();
analyser = null; dataArray = null; audioMode = "none";
return;
}
startDemo();
});
const loadAudioFile = (file) => {
if (!file || !file.type.startsWith("audio/")) {
toast("That doesn't look like an audio file");
return;
}
stopMic();
stopDemo();
if (audioElement) { audioElement.pause(); audioElement.src = ""; audioElement = null; }
isPlaying = false;
const ctx = ensureAudioContext();
audioElement = new Audio(URL.createObjectURL(file));
audioElement.crossOrigin = "anonymous";
const source = ctx.createMediaElementSource(audioElement);
const a = makeAnalyser();
source.connect(a);
a.connect(ctx.destination);
audioElement.onended = () => { isPlaying = false; playBtn.textContent = "▶"; };
audioMode = "file";
fileName.textContent = file.name.length > 16 ? `${file.name.slice(0, 13)}…` : file.name;
playBtn.disabled = false;
playBtn.textContent = "▶";
};
document.getElementById("file-label").addEventListener("click", () => fileInput.click());
fileInput.addEventListener("change", () => {
loadAudioFile(fileInput.files && fileInput.files[0]);
});
// Drag & drop audio anywhere on the page.
document.body.addEventListener("dragover", (e) => {
e.preventDefault();
document.body.classList.add("is-dropping");
});
document.body.addEventListener("dragleave", () => document.body.classList.remove("is-dropping"));
document.body.addEventListener("drop", (e) => {
e.preventDefault();
document.body.classList.remove("is-dropping");
const file = e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0];
if (file) {
loadAudioFile(file);
if (audioElement) { audioElement.play(); isPlaying = true; playBtn.textContent = "⏸"; }
}
});
playBtn.addEventListener("click", () => {
if (!audioElement) return;
ensureAudioContext();
stopDemo();
if (isPlaying) { audioElement.pause(); isPlaying = false; playBtn.textContent = "▶"; }
else { audioElement.play(); isPlaying = true; playBtn.textContent = "⏸"; }
});
micBtn.addEventListener("click", async () => {
if (micStream) {
stopMic();
analyser = null; dataArray = null; audioMode = "none";
toast("Microphone off");
return;
}
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
stopDemo();
if (audioElement && isPlaying) { audioElement.pause(); isPlaying = false; playBtn.textContent = "▶"; }
const ctx = ensureAudioContext();
micStream = stream;
micSource = ctx.createMediaStreamSource(stream);
micSource.connect(makeAnalyser()); // analyser only — never to speakers
audioMode = "mic";
micBtn.classList.add("is-on");
toast("Listening to microphone");
} catch {
toast("Microphone unavailable — permission denied");
}
});
// ── Controls wiring ───────────────────────────────────────
const bindRange = (id, outId, key, fmt = (v) => v.toFixed(2)) => {
const input = document.getElementById(id);
const out = document.getElementById(outId);
input.addEventListener("input", () => {
params[key] = Number(input.value);
out.textContent = fmt(params[key]);
});
};
bindRange("noise-range", "noise-out", "noiseStrength");
bindRange("rot-range", "rot-out", "rotationSpeed");
bindRange("gain-range", "gain-out", "audioGain", (v) => v.toFixed(1));
bindRange("bass-range", "bass-out", "bassBoost", (v) => v.toFixed(1));
document.getElementById("shape-seg").addEventListener("click", (e) => {
const btn = e.target.closest("[data-shape]");
if (!btn) return;
params.shape = btn.dataset.shape;
for (const b of document.querySelectorAll("#shape-seg button")) b.classList.toggle("is-active", b === btn);
});
const toggleBtn = (id, key, label) => {
const btn = document.getElementById(id);
btn.addEventListener("click", () => {
params[key] = !params[key];
btn.classList.toggle("is-on", params[key]);
btn.textContent = `${label}: ${params[key] ? "On" : "Off"}`;
});
};
toggleBtn("plexus-btn", "showConnections", "Plexus");
toggleBtn("planets-btn", "showPlanets", "Planets");
const rainbowBtn = document.getElementById("rainbow-btn");
rainbowBtn.addEventListener("click", () => {
params.isRainbow = !params.isRainbow;
rainbowBtn.classList.toggle("is-on", params.isRainbow);
rainbowBtn.textContent = `Rainbow: ${params.isRainbow ? "On" : "Off"}`;
buildGeometry();
});
document.getElementById("color-input").addEventListener("input", (e) => {
params.baseColor = e.target.value;
if (!params.isRainbow) buildGeometry();
});
document.getElementById("count-input").addEventListener("change", (e) => {
params.pointCount = Math.round(clampNum(e.target.value, 100, 10000, 1500));
e.target.value = params.pointCount;
buildGeometry();
});
document.getElementById("size-input").addEventListener("change", (e) => {
params.pointSize = clampNum(e.target.value, 0.1, 3, 0.5);
e.target.value = params.pointSize;
pointsMaterial.size = params.pointSize;
});
const controlsEl = document.getElementById("controls");
const toggleUi = document.getElementById("toggle-ui");
toggleUi.addEventListener("click", () => {
const hidden = controlsEl.classList.toggle("is-hidden");
toggleUi.textContent = hidden ? "⊞" : "⊟";
});
// ── Fullscreen ────────────────────────────────────────────
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(() => toast("Fullscreen unavailable"));
});
// ── Presets ───────────────────────────────────────────────
const presets = {
nebula: {
shape: "sphere", isRainbow: false, baseColor: "#c8b0ff",
noiseStrength: 0.9, showConnections: false, showPlanets: true,
rotationSpeed: 0.35, pointSize: 0.6, audioGain: 2.0, bassBoost: 1.2
},
pulse: {
shape: "cube", isRainbow: true, baseColor: "#ff6b35",
noiseStrength: 0.15, showConnections: false, showPlanets: true,
rotationSpeed: 0.5, pointSize: 0.5, audioGain: 3.4, bassBoost: 2.0
},
lattice: {
shape: "torus", isRainbow: false, baseColor: "#00e5ff",
noiseStrength: 0.1, showConnections: true, showPlanets: false,
rotationSpeed: 0.25, pointSize: 0.4, audioGain: 2.0, bassBoost: 1.0
}
};
// Push current params back into every control.
const syncUI = () => {
const setRange = (id, outId, value, fmt = (v) => v.toFixed(2)) => {
document.getElementById(id).value = value;
document.getElementById(outId).textContent = fmt(value);
};
setRange("noise-range", "noise-out", params.noiseStrength);
setRange("rot-range", "rot-out", params.rotationSpeed);
setRange("gain-range", "gain-out", params.audioGain, (v) => v.toFixed(1));
setRange("bass-range", "bass-out", params.bassBoost, (v) => v.toFixed(1));
for (const b of document.querySelectorAll("#shape-seg button")) {
b.classList.toggle("is-active", b.dataset.shape === params.shape);
}
const syncToggle = (id, on, label) => {
const btn = document.getElementById(id);
btn.classList.toggle("is-on", on);
btn.textContent = `${label}: ${on ? "On" : "Off"}`;
};
syncToggle("plexus-btn", params.showConnections, "Plexus");
syncToggle("planets-btn", params.showPlanets, "Planets");
syncToggle("rainbow-btn", params.isRainbow, "Rainbow");
document.getElementById("color-input").value = params.baseColor;
document.getElementById("count-input").value = params.pointCount;
document.getElementById("size-input").value = params.pointSize;
};
for (const btn of document.querySelectorAll("[data-preset]")) {
btn.addEventListener("click", () => {
Object.assign(params, presets[btn.dataset.preset]);
pointsMaterial.size = params.pointSize;
syncUI();
buildGeometry();
toast(`Preset: ${btn.textContent}`);
});
}
// ── Pointer input: drag rotate + pinch zoom ───────────────
const activePointers = new Map();
let lastSingle = null;
let lastPinchDist = null;
const clampZoom = (z) => Math.max(5, Math.min(200, z));
stage.addEventListener("pointerdown", (e) => {
stage.setPointerCapture(e.pointerId);
activePointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
if (activePointers.size === 1) lastSingle = { x: e.clientX, y: e.clientY };
lastPinchDist = null;
});
stage.addEventListener("pointermove", (e) => {
if (!activePointers.has(e.pointerId)) return;
activePointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
const pts = [...activePointers.values()];
if (pts.length === 1 && lastSingle) {
const dx = e.clientX - lastSingle.x;
const dy = e.clientY - lastSingle.y;
const q = new THREE.Quaternion().setFromEuler(new THREE.Euler(dy * 0.005, dx * 0.005, 0, "XYZ"));
group.quaternion.multiplyQuaternions(q, group.quaternion);
lastSingle = { x: e.clientX, y: e.clientY };
} else if (pts.length === 2) {
const d = Math.hypot(pts[0].x - pts[1].x, pts[0].y - pts[1].y);
if (lastPinchDist !== null) {
camera.position.z = clampZoom(camera.position.z - (d - lastPinchDist) * 0.15);
}
lastPinchDist = d;
}
});
const endPointer = (e) => {
activePointers.delete(e.pointerId);
lastSingle = activePointers.size === 1 ? [...activePointers.values()][0] : null;
lastPinchDist = null;
};
stage.addEventListener("pointerup", endPointer);
stage.addEventListener("pointercancel", endPointer);
stage.addEventListener("wheel", (e) => {
camera.position.z = clampZoom(camera.position.z + e.deltaY * 0.1);
}, { passive: true });
// ── Animation loop ────────────────────────────────────────
const G = 0.005;
const dummy = new THREE.Object3D();
let time = 0;
const animate = () => {
requestAnimationFrame(animate);
time += 0.01;
if (activePointers.size === 0) {
group.rotation.y += params.rotationSpeed * 0.005;
group.rotation.x += params.rotationSpeed * 0.002;
}
// Audio
let bassScale = 0;
if (analyser && dataArray) {
analyser.getByteFrequencyData(dataArray);
let bassSum = 0;
const bassRange = Math.floor(dataArray.length * 0.05);
for (let b = 0; b < bassRange; b++) bassSum += dataArray[b];
bassScale = (bassSum / bassRange / 255) * params.bassBoost;
if (bassScale > 0.5) group.rotation.z += 0.02 * bassScale;
}
// Planets
planetsMesh.visible = params.showPlanets;
if (params.showPlanets) {
const containerScale = params.radius + bassScale * 5;
for (let i = 0; i < MAX_PLANETS; i++) {
const p = planetsData[i];
p.pos.add(p.vel);
if (params.shape === "cube") {
const limit = containerScale * 0.8;
for (const axis of ["x", "y", "z"]) {
if (Math.abs(p.pos[axis]) + p.radius > limit) {
p.vel[axis] *= -1;
p.pos[axis] = Math.sign(p.pos[axis]) * (limit - p.radius);
}
}
} else if (params.shape === "torus") {
const majorR = containerScale * 0.8;
const minorR = containerScale * 0.4;
const q = new THREE.Vector2(Math.hypot(p.pos.x, p.pos.z) - majorR, p.pos.y);
if (q.length() + p.radius > minorR) {
const angle = Math.atan2(p.pos.z, p.pos.x);
const tubeCenter = new THREE.Vector3(Math.cos(angle) * majorR, 0, Math.sin(angle) * majorR);
const normal = new THREE.Vector3().subVectors(p.pos, tubeCenter).normalize();
p.vel.reflect(normal);
p.pos.copy(tubeCenter).add(normal.multiplyScalar(minorR - p.radius - 0.1));
}
} else {
const distFromCenter = p.pos.length();
if (distFromCenter + p.radius > containerScale) {
const normal = p.pos.clone().normalize();
p.vel.reflect(normal);
p.pos.copy(normal.multiplyScalar(containerScale - p.radius));
}
}
for (let j = i + 1; j < MAX_PLANETS; j++) {
const p2 = planetsData[j];
const diff = new THREE.Vector3().subVectors(p2.pos, p.pos);
const d = diff.length();
const minDist = p.radius + p2.radius;
if (d > 0.1) {
const force = (G * p.mass * p2.mass) / (d * d);
const forceVec = diff.clone().normalize().multiplyScalar(force);
p.vel.add(forceVec.clone().divideScalar(p.mass));
p2.vel.sub(forceVec.clone().divideScalar(p2.mass));
}
if (d < minDist) {
const normal = diff.clone().normalize();
const push = normal.clone().multiplyScalar((minDist - d) * 0.5);
p.pos.sub(push);
p2.pos.add(push);
const relVel = new THREE.Vector3().subVectors(p.vel, p2.vel);
const speed = relVel.dot(normal);
if (speed < 0) {
const impulse = (2 * speed) / (p.mass + p2.mass);
const impulseVec = normal.multiplyScalar(impulse);
p.vel.sub(impulseVec.clone().multiplyScalar(p2.mass));
p2.vel.add(impulseVec.clone().multiplyScalar(p.mass));
}
}
}
if (bassScale > 0.2) {
p.vel.add(new THREE.Vector3((Math.random() - 0.5) * 0.01, (Math.random() - 0.5) * 0.01, (Math.random() - 0.5) * 0.01));
}
dummy.position.copy(p.pos);
dummy.scale.setScalar(p.radius);
dummy.updateMatrix();
planetsMesh.setMatrixAt(i, dummy.matrix);
}
planetsMesh.instanceMatrix.needsUpdate = true;
}
// Point morph + noise + audio displacement
if (points) {
const positions = points.geometry.attributes.position.array;
const count = points.geometry.attributes.position.count;
const targetBuffer = targets[params.shape] || targets.sphere;
const nAmp = params.noiseStrength;
for (let i = 0; i < count; i++) {
const idx = i * 3;
basePositions[idx] += (targetBuffer[idx] - basePositions[idx]) * 0.05;
basePositions[idx + 1] += (targetBuffer[idx + 1] - basePositions[idx + 1]) * 0.05;
basePositions[idx + 2] += (targetBuffer[idx + 2] - basePositions[idx + 2]) * 0.05;
const x = basePositions[idx];
const y = basePositions[idx + 1];
const z = basePositions[idx + 2];
const noise = Math.sin(x * 2 + time * params.noiseSpeed * 50)
* Math.cos(y * 2 + time * params.noiseSpeed * 50)
* Math.sin(z * 2 + time * params.noiseSpeed * 50);
let audioDisp = 0;
if (dataArray) {
const binIndex = Math.floor((i / count) * (dataArray.length / 2));
audioDisp = (dataArray[binIndex] / 255) * params.audioGain;
}
const totalScale = params.radius + bassScale * 2 + audioDisp * 3 + noise * nAmp * 2;
positions[idx] = x * totalScale;
positions[idx + 1] = y * totalScale;
positions[idx + 2] = z * totalScale;
}
points.geometry.attributes.position.needsUpdate = true;
// Plexus
lines.visible = params.showConnections;
if (params.showConnections) {
const lPositions = lines.geometry.attributes.position.array;
let lIdx = 0;
for (let i = 0; i < count - 2; i++) {
if (lIdx + 11 >= lPositions.length) break;
const p1x = positions[i * 3], p1y = positions[i * 3 + 1], p1z = positions[i * 3 + 2];
lPositions[lIdx++] = p1x; lPositions[lIdx++] = p1y; lPositions[lIdx++] = p1z;
lPositions[lIdx++] = positions[(i + 1) * 3]; lPositions[lIdx++] = positions[(i + 1) * 3 + 1]; lPositions[lIdx++] = positions[(i + 1) * 3 + 2];
if (i + 5 < count) {
lPositions[lIdx++] = p1x; lPositions[lIdx++] = p1y; lPositions[lIdx++] = p1z;
lPositions[lIdx++] = positions[(i + 5) * 3]; lPositions[lIdx++] = positions[(i + 5) * 3 + 1]; lPositions[lIdx++] = positions[(i + 5) * 3 + 2];
}
}
lines.geometry.attributes.position.needsUpdate = true;
}
}
renderer.render(scene, camera);
};
animate();
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
});
</script>
</body>
</html>