"use strict";
/* ---------- Fixed decision tables: no AI at runtime ---------- */
const GOALS = {
relax: {label:"Relax", target:10, slow:.20, dim:.30, hue:192, sat:52, light:58, react:1.0, rot:1.0},
sleep: {label:"Sleep", target:12, slow:.35, dim:.80, hue:22, sat:58, light:40, react:.5, rot:.6},
trance: {label:"Trance", target:6.5, slow:0, dim:0, hue:262, sat:62, light:62, react:1.2, rot:1.5}
};
const GENRES = {
ambient: {label:"Ambient", hue:0, react:.15, rot:.70},
classical: {label:"Classical", hue:18, react:.25, rot:.80},
lofi: {label:"Lo-fi", hue:-14, react:.30, rot:.90},
jazz: {label:"Jazz", hue:40, react:.28, rot:.90},
pop: {label:"Pop / Rock", hue:-28, react:.32, rot:1.10},
electronic: {label:"Electronic", hue:30, react:.40, rot:1.25}
};
const SCENES = {spiral:"Spiral", breath:"Breath", rings:"Tunnel", tide:"Tide", mandala:"Mandala"};
const SCENE_TABLE = {
relax: {ambient:"breath", classical:"breath", lofi:"rings", jazz:"mandala", pop:"rings", electronic:"mandala"},
sleep: {ambient:"tide", classical:"tide", lofi:"breath", jazz:"tide", pop:"breath", electronic:"breath"},
trance: {ambient:"rings", classical:"mandala", lofi:"spiral", jazz:"mandala", pop:"spiral", electronic:"spiral"}
};
const TIMES = [10, 15, 20, 30, 45];
const DRUM_HZ = 4.25, SETTLE = 120, RETURN = 45;
const S = {goal:"relax", genre:"auto", scene:"auto", minutes:20, track:null, running:false, started:false, elapsed:0, vol:.7, drum:.6};
let P = {};
/* ---------- Track analysis: tempo, beat clarity, brightness ---------- */
function analyse(ch0, ch1, sr){
const len = ch0.length;
const segLen = Math.min(len, Math.floor(sr * 45));
const start = Math.floor((len - segLen) / 2);
const hop = 512, n = Math.floor(segLen / hop);
const out = {bpm:60, clarity:0, bright:.4, steady:false};
if (n < 200) return out;
const env = new Float32Array(n);
let zc = 0, prev = 0;
for (let i = 0; i < n; i++){
let s = 0; const o = start + i * hop;
for (let j = 0; j < hop; j++){
const v = ch1 ? (ch0[o+j] + ch1[o+j]) * .5 : ch0[o+j];
s += v * v;
if ((v >= 0) !== (prev >= 0)) zc++;
prev = v;
}
env[i] = Math.sqrt(s / hop);
}
const zcr = zc / (n * hop / sr);
out.bright = Math.max(0, Math.min(1, (Math.log(Math.max(zcr, 1)) - Math.log(300)) / (Math.log(4500) - Math.log(300))));
const flux = new Float32Array(n); let mean = 0;
for (let i = 1; i < n; i++){ const d = env[i] - env[i-1]; flux[i] = d > 0 ? d : 0; mean += flux[i]; }
mean /= n; let ac0 = 0;
for (let i = 0; i < n; i++){ flux[i] -= mean; ac0 += flux[i] * flux[i]; }
if (ac0 <= 1e-12) return out;
// A held tone has almost no onsets: don't read a beat into its ripple.
let envMean = 0; for (let i = 0; i < n; i++) envMean += env[i]; envMean /= n;
const onset = Math.sqrt(ac0 / n) / Math.max(envMean, 1e-9);
const fps = sr / hop;
const lagMin = Math.floor(fps * 60 / 180), lagMax = Math.ceil(fps * 60 / 50);
const ac = new Float32Array(lagMax + 2);
let best = -1, bestScore = -1e9;
for (let lag = lagMin - 1; lag <= lagMax + 1; lag++){
let s = 0;
for (let i = 0; i + lag < n; i++) s += flux[i] * flux[i + lag];
ac[lag] = s / ac0;
if (lag < lagMin || lag > lagMax) continue;
const bpm = 60 * fps / lag;
const w = Math.exp(-.5 * Math.pow(Math.log2(bpm / 100) / .9, 2));
if (ac[lag] * w > bestScore){ bestScore = ac[lag] * w; best = lag; }
}
const a = ac[best-1], b = ac[best], c = ac[best+1];
const den = a - 2*b + c;
const off = Math.abs(den) > 1e-9 ? Math.max(-.5, Math.min(.5, .5 * (a - c) / den)) : 0;
out.clarity = Math.max(0, b);
out.steady = out.clarity >= .08 && onset >= .1;
if (!out.steady) out.clarity = Math.min(out.clarity, .07);
out.bpm = out.steady ? Math.round(60 * fps / (best + off)) : 60;
return out;
}
function guessGenre(t){
if (t.clarity < .12) return t.bright < .35 ? "ambient" : "classical";
if (t.bpm < 100 && t.bright < .45) return "lofi";
if (t.clarity > .3 && t.bpm >= 110) return "electronic";
return "pop";
}
/* ---------- Turn goal + genre + track into animation parameters ---------- */
function derive(){
const g = GOALS[S.goal];
if (S.goal === "trance" && S.minutes < 15) S.minutes = 15;
const genre = S.genre === "auto" ? (S.track ? S.track.genre : "ambient") : S.genre;
const G = GENRES[genre];
const bpm = S.track ? S.track.bpm : 60;
const beat = 60 / bpm;
const k = Math.max(1, Math.min(6, Math.round(Math.log2(g.target / beat))));
const beats = Math.pow(2, k);
const sleepy = S.goal === "sleep";
const bright = S.track ? S.track.bright : .4;
P = {
genre, bpm, beats, period: beat * beats,
scene: S.scene === "auto" ? SCENE_TABLE[S.goal][genre] : S.scene,
hue: g.hue + G.hue * (sleepy ? .35 : 1) + (bright - .5) * 30 * (sleepy ? .3 : 1),
sat: g.sat, light: g.light, react: G.react * g.react, rot: G.rot * g.rot, slow: g.slow, dim: g.dim
};
document.documentElement.style.setProperty("--accent", `hsl(${Math.round(P.hue)} 48% 72%)`);
renderRead(); renderChips(); syncDrum();
$("drumRow").style.display = S.goal === "trance" ? "flex" : "none";
}
/* ---------- Controls ---------- */
const $ = id => document.getElementById(id);
function chipRow(el, items, get, set){
el.innerHTML = "";
items.forEach(([val, text]) => {
const b = document.createElement("button");
b.className = "chip"; b.type = "button"; b.dataset.val = val; b.textContent = text;
b.addEventListener("click", () => { set(val); derive(); });
el.appendChild(b);
});
el._get = get;
}
function renderChips(){
for (const id of ["goalChips","genreChips","sceneChips","timeChips"]){
const el = $(id);
for (const b of el.children){
b.setAttribute("aria-pressed", String(b.dataset.val === String(el._get())));
if (id === "genreChips" && b.dataset.val === "auto")
b.textContent = S.genre === "auto" && S.track ? "Auto: " + GENRES[P.genre].label : "Auto";
if (id === "sceneChips" && b.dataset.val === "auto")
b.textContent = S.scene === "auto" ? "Auto: " + SCENES[P.scene] : "Auto";
}
}
$("tones").setAttribute("aria-pressed", String(!S.track));
}
function renderRead(msg){
const el = $("read");
if (msg){ el.innerHTML = ""; const s = document.createElement("span"); s.textContent = msg; el.appendChild(s); return; }
const t = S.track;
const src = t
? `${t.steady ? t.bpm + " BPM" : "No steady beat"} · ${t.bright < .35 ? "dark tone" : t.bright < .6 ? "balanced tone" : "bright tone"} · ${t.clarity > .3 ? "strong pulse" : t.clarity >= .08 ? "soft pulse" : "pacing at 60 BPM"}`
: `Built-in tones · 60 BPM`;
const slow = Math.round(P.slow * 100);
if (S.goal === "trance"){
el.innerHTML = `
${src}
Steady drum at ${DRUM_HZ} beats a second for ${S.minutes} min, no slowing. The screen dims after 2 min so you can close your eyes. Use headphones.`;
} else
el.innerHTML = `${src}
${SCENES[P.scene]} scene, one cycle every ${P.beats} beats (${P.period.toFixed(1)} s), slowing ${slow}% across ${S.minutes} min`;
if (t){ const n = document.createElement("span"); n.textContent = t.name; el.appendChild(n); }
}
chipRow($("goalChips"), Object.entries(GOALS).map(([k,v]) => [k, v.label]), () => S.goal, v => S.goal = v);
chipRow($("genreChips"), [["auto","Auto"]].concat(Object.entries(GENRES).map(([k,v]) => [k, v.label])), () => S.genre, v => S.genre = v);
chipRow($("sceneChips"), [["auto","Auto"]].concat(Object.entries(SCENES)), () => S.scene, v => S.scene = v);
chipRow($("timeChips"), TIMES.map(m => [m, m + " min"]), () => S.minutes, v => S.minutes = Number(v));
/* ---------- Audio ---------- */
let ac = null, master = null, analyser = null, fd = null, nodes = [];
function ensureCtx(){
if (ac) return true;
const C = window.AudioContext || window.webkitAudioContext;
if (!C) return false;
ac = new C();
master = ac.createGain(); master.gain.value = S.vol;
analyser = ac.createAnalyser(); analyser.fftSize = 1024; analyser.smoothingTimeConstant = .85;
master.connect(analyser); analyser.connect(ac.destination);
fd = new Uint8Array(analyser.frequencyBinCount);
return true;
}
function stopNodes(){
nodes.forEach(n => { try { n.stop(); } catch(e){} try { n.disconnect(); } catch(e){} });
nodes = [];
}
function startSound(){
stopNodes();
if (S.track){
const src = ac.createBufferSource();
src.buffer = S.track.buffer; src.loop = true; src.connect(master); src.start();
nodes.push(src);
} else {
// Soft open-fifth drone that swells once per visual cycle.
const lp = ac.createBiquadFilter(); lp.type = "lowpass"; lp.frequency.value = 700;
const pad = ac.createGain(); pad.gain.value = .5;
const lfo = ac.createOscillator(); lfo.frequency.value = 1 / P.period;
const depth = ac.createGain(); depth.gain.value = .22;
lfo.connect(depth); depth.connect(pad.gain); lfo.start();
[[98,.30],[98.4,.22],[146.83,.20],[196,.12],[293.66,.05]].forEach(([f, g]) => {
const o = ac.createOscillator(); o.type = "sine"; o.frequency.value = f;
const og = ac.createGain(); og.gain.value = g;
o.connect(og); og.connect(lp); o.start(); nodes.push(o);
});
lp.connect(pad); pad.connect(master); nodes.push(lfo);
}
}
// Trance drum: a low, near-steady pulse with slight human timing variation.
let drumBus = null, drumTimer = 0, nextHit = 0;
function gauss(){ return Math.max(-2, Math.min(2, Math.sqrt(-2 * Math.log(1 - Math.random())) * Math.cos(6.2832 * Math.random()))); }
function hit(t){
const o = ac.createOscillator(), g = ac.createGain();
o.type = "sine"; o.frequency.setValueAtTime(95, t); o.frequency.exponentialRampToValueAtTime(52, t + .09);
g.gain.setValueAtTime(.0001, t); g.gain.exponentialRampToValueAtTime(.9, t + .005); g.gain.exponentialRampToValueAtTime(.0005, t + .17);
o.connect(g); g.connect(drumBus); o.start(t); o.stop(t + .2);
}
function schedDrum(){
if (!ac || !drumBus || !S.running) return;
const now = ac.currentTime, left = S.minutes * 60 - RETURN - S.elapsed;
if (nextHit < now) nextHit = now + .05;
while (nextHit < now + 1.5 && nextHit < now + left){ hit(Math.max(now, nextHit + gauss() * .0067)); nextHit += 1 / DRUM_HZ; }
}
function stopDrum(){
clearInterval(drumTimer); drumTimer = 0;
if (drumBus){ try { drumBus.disconnect(); } catch(e){} drumBus = null; }
}
function syncDrum(){
const want = S.started && S.goal === "trance" && ac;
if (want && !drumTimer){
drumBus = ac.createGain(); drumBus.gain.value = S.vol * S.drum; drumBus.connect(ac.destination);
nextHit = ac.currentTime + .15; drumTimer = setInterval(schedDrum, 100);
} else if (!want && drumTimer) stopDrum();
}
let cueText = null;
function cue(text){
if (text === cueText) return; cueText = text;
const el = $("cue");
if (text){ el.textContent = text; el.classList.add("on"); } else el.classList.remove("on");
}
function decode(buf){
return new Promise((res, rej) => {
const p = ac.decodeAudioData(buf, res, rej);
if (p && p.catch) p.catch(rej);
});
}
function readFile(file){
if (file.arrayBuffer) return file.arrayBuffer();
return new Promise((res, rej) => { const r = new FileReader(); r.onload = () => res(r.result); r.onerror = rej; r.readAsArrayBuffer(file); });
}
$("file").addEventListener("change", async e => {
const file = e.target.files && e.target.files[0];
if (!file) return;
if (!ensureCtx()){ renderRead("This browser can't play audio here. The built-in visuals still run."); return; }
const wasRunning = S.running;
if (wasRunning) pause();
renderRead("Listening to the track…");
try {
const buffer = await decode(await readFile(file));
const a = analyse(buffer.getChannelData(0), buffer.numberOfChannels > 1 ? buffer.getChannelData(1) : null, buffer.sampleRate);
S.track = Object.assign(a, {buffer, name: file.name.replace(/\.[^.]+$/, "")});
S.track.genre = guessGenre(S.track);
derive();
if (S.started){ startSound(); if (wasRunning) resume(); }
} catch (err){
renderRead("Couldn't read that file. Try an MP3, M4A or WAV.");
if (wasRunning) resume();
}
e.target.value = "";
});
$("tones").addEventListener("click", () => {
S.track = null; derive();
if (S.started) startSound();
});
$("vol").addEventListener("input", e => { S.vol = e.target.value / 100; });
$("drumVol").addEventListener("input", e => { S.drum = e.target.value / 100; });
/* ---------- Session ---------- */
let wake = null, hideTimer = 0;
function begin(){
if (ensureCtx()){
try { ac.resume(); } catch(e){}
startSound();
}
S.started = true; S.running = true; S.elapsed = 0;
syncDrum(); afterToggle();
}
function pause(){ S.running = false; if (ac) try { ac.suspend(); } catch(e){} afterToggle(); }
function resume(){ S.running = true; if (ac) try { ac.resume(); } catch(e){} afterToggle(); }
function reset(){
S.running = false; S.started = false; S.elapsed = 0;
stopNodes(); stopDrum(); if (ac) try { ac.resume(); } catch(e){}
$("end").classList.remove("on");
afterToggle(); showSheet();
}
function afterToggle(){
$("go").textContent = !S.started ? "Begin" : S.running ? "Pause" : "Resume";
if (S.running){
try { if (navigator.wakeLock) navigator.wakeLock.request("screen").then(w => wake = w).catch(() => {}); } catch(e){}
armHide();
} else {
clearTimeout(hideTimer);
if (wake){ try { wake.release(); } catch(e){} wake = null; }
}
}
function armHide(){
clearTimeout(hideTimer);
if (S.running) hideTimer = setTimeout(() => {
$("sheet").classList.add("away");
$("hint").classList.add("on"); setTimeout(() => $("hint").classList.remove("on"), 3500);
}, 6000);
}
function showSheet(){ $("sheet").classList.remove("away"); armHide(); }
$("go").addEventListener("click", () => { !S.started ? begin() : S.running ? pause() : resume(); });
$("reset").addEventListener("click", reset);
$("sheet").addEventListener("pointerdown", armHide);
$("stage").addEventListener("click", () => { $("sheet").classList.contains("away") ? showSheet() : (S.running && $("sheet").classList.add("away")); });
$("end").addEventListener("click", reset);
const fsEl = document.documentElement;
if (!fsEl.requestFullscreen) $("full").style.display = "none";
$("full").addEventListener("click", () => {
try {
const p = document.fullscreenElement ? document.exitFullscreen() : fsEl.requestFullscreen();
if (p && p.catch) p.catch(() => {});
} catch(e){}
});
/* ---------- Drawing ---------- */
const cv = $("stage"), ctx = cv.getContext("2d");
let W = 0, H = 0, DPR = 1;
function resize(){
DPR = Math.min(2, window.devicePixelRatio || 1);
W = cv.clientWidth; H = cv.clientHeight;
cv.width = Math.round(W * DPR); cv.height = Math.round(H * DPR);
}
window.addEventListener("resize", resize);
const hsl = (h, s, l, a) => `hsla(${h},${s}%,${l}%,${a})`;
// Inhale 40%, exhale 60%: the long exhale is what settles people.
function breathCurve(p){ return p < .4 ? .5 - .5 * Math.cos(Math.PI * p / .4) : .5 + .5 * Math.cos(Math.PI * (p - .4) / .6); }
const draw = {
breath(c){
const r = c.Rmin * (.2 + .2 * c.b + .05 * c.a);
for (let j = 4; j >= 1; j--){
ctx.beginPath(); ctx.arc(c.cx, c.cy, r * (1.25 + .42 * j) , 0, 6.2832);
ctx.strokeStyle = hsl(c.hue, c.sat, c.light, .16 * (1 - j / 5) * (.4 + .6 * c.b));
ctx.lineWidth = 1.5; ctx.stroke();
}
const g = ctx.createRadialGradient(c.cx, c.cy, 0, c.cx, c.cy, r * 2.4);
g.addColorStop(0, hsl(c.hue, c.sat, c.light + 14, .95));
g.addColorStop(.38, hsl(c.hue, c.sat, c.light, .55));
g.addColorStop(1, hsl(c.hue + 20, c.sat, c.light - 20, 0));
ctx.fillStyle = g; ctx.beginPath(); ctx.arc(c.cx, c.cy, r * 2.4, 0, 6.2832); ctx.fill();
},
spiral(c){
const arms = 3, turns = 2.6, seg = 140, R = c.Rmax * 1.1;
const half = (Math.PI / arms) * (.42 + .1 * c.b + .12 * c.a);
const g = ctx.createRadialGradient(c.cx, c.cy, 0, c.cx, c.cy, R);
g.addColorStop(0, hsl(c.hue, c.sat, c.light - 28, .2));
g.addColorStop(.45, hsl(c.hue + 12, c.sat, c.light - 10, .8));
g.addColorStop(1, hsl(c.hue + 26, c.sat, c.light, .9));
ctx.fillStyle = g;
for (let a = 0; a < arms; a++){
const base = c.rot + a * 6.2832 / arms;
ctx.beginPath();
for (let i = 0; i <= seg; i++){
const u = i / seg, r = R * Math.pow(u, 1.35), th = turns * 6.2832 * u + base - half;
ctx.lineTo(c.cx + r * Math.cos(th), c.cy + r * Math.sin(th));
}
for (let i = seg; i >= 0; i--){
const u = i / seg, r = R * Math.pow(u, 1.35), th = turns * 6.2832 * u + base + half;
ctx.lineTo(c.cx + r * Math.cos(th), c.cy + r * Math.sin(th));
}
ctx.closePath(); ctx.fill();
}
glow(c, .16);
},
rings(c){
const N = 14, frac = (c.rot * 1.4) % 1;
for (let i = 0; i < N; i++){
const u = ((i - frac + N) % N) / N, r = c.Rmax * 1.05 * Math.pow(u, 1.8);
if (r < 2) continue;
ctx.beginPath(); ctx.arc(c.cx, c.cy, r, 0, 6.2832);
ctx.lineWidth = 1 + r * .04 * (1 + .5 * c.b + c.a);
ctx.strokeStyle = hsl(c.hue + 30 * u, c.sat, c.light - 8 + 10 * c.b, Math.pow(Math.sin(Math.PI * u), .8) * .8);
ctx.stroke();
}
glow(c, .2);
},
tide(c){
const moon = ctx.createRadialGradient(c.cx, H * .24, 0, c.cx, H * .24, c.Rmin * .7);
moon.addColorStop(0, hsl(c.hue + 10, c.sat, c.light + 8, .35 + .2 * c.b));
moon.addColorStop(1, hsl(c.hue, c.sat, c.light, 0));
ctx.fillStyle = moon; ctx.fillRect(0, 0, W, H);
const L = 6, t = c.rot * 1.6;
for (let i = 0; i < L; i++){
const base = H * (.42 + .1 * i), A = H * .03 * (.7 + .6 * c.b + c.a) * (1 + i * .15);
const k1 = 6.2832 / (W * (1.5 - .12 * i)), k2 = 6.2832 / (W * .55);
ctx.beginPath(); ctx.moveTo(0, H);
for (let x = 0; x <= W + 12; x += 12)
ctx.lineTo(x, base + A * Math.sin(x * k1 + t * (.5 + .13 * i) + i * 1.7) + A * .35 * Math.sin(x * k2 - t * .4 + i));
ctx.lineTo(W, H); ctx.closePath();
ctx.fillStyle = hsl(c.hue - 4 * i, c.sat, c.light - 26 + 3 * i, .34);
ctx.fill();
}
},
mandala(c){
const layers = [[1.5, 5, .35], [.98, 6, -.6], [.68, 8, 1], [.4, 12, -1.5]];
ctx.globalCompositeOperation = "lighter";
layers.forEach(([scale, n, spin], li) => {
const Rl = c.Rmin * scale * (.88 + .12 * c.b + .1 * c.a), rot = c.rot * spin;
ctx.beginPath();
for (let i = 0; i <= 240; i++){
const th = i / 240 * 6.2832, r = Rl * (.62 + .38 * Math.cos(n * th));
const x = c.cx + r * Math.cos(th + rot), y = c.cy + r * Math.sin(th + rot);
i ? ctx.lineTo(x, y) : ctx.moveTo(x, y);
}
ctx.closePath();
ctx.fillStyle = hsl(c.hue + 14 * li, c.sat, c.light - 22, .1);
ctx.strokeStyle = hsl(c.hue + 14 * li, c.sat, c.light, .5);
ctx.lineWidth = 1.5; ctx.fill(); ctx.stroke();
});
ctx.globalCompositeOperation = "source-over";
glow(c, .14);
}
};
function glow(c, size){
const r = c.Rmin * size * (1 + .5 * c.b);
const g = ctx.createRadialGradient(c.cx, c.cy, 0, c.cx, c.cy, r);
g.addColorStop(0, hsl(c.hue, c.sat, c.light + 20, .9));
g.addColorStop(1, hsl(c.hue, c.sat, c.light, 0));
ctx.fillStyle = g; ctx.beginPath(); ctx.arc(c.cx, c.cy, r, 0, 6.2832); ctx.fill();
}
/* ---------- Frame loop ---------- */
const reduced = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
let last = performance.now(), phase = 0, rot = 0, bass = 0, sceneNow = null, sceneFade = 1;
const cur = {hue:192, period:8, react:.15, rot:.7, sat:52, light:58};
function frame(now){
requestAnimationFrame(frame);
const dt = Math.min(.1, (now - last) / 1000); last = now;
if (!W || cv.clientWidth !== W || cv.clientHeight !== H) resize();
if (S.running) S.elapsed += dt;
const total = S.minutes * 60, p = Math.min(1, S.elapsed / total);
const ease = p * p * (3 - 2 * p);
const k = 1 - Math.exp(-dt * 1.5);
for (const key in cur) cur[key] += (P[key] - cur[key]) * k;
// Sleep sessions fade sound and light to nothing over the last 90 seconds.
let endFade = 1;
if (S.goal === "sleep" && S.started) endFade = Math.max(0, Math.min(1, (total - S.elapsed) / 90));
if (master) master.gain.value = S.vol * endFade;
if (S.goal === "sleep" && S.running && p >= 1){
S.running = false; stopNodes(); afterToggle();
$("sheet").classList.add("away"); $("end").classList.add("on");
}
// Trance arc: settle with the visuals, go dark for eyes-closed listening, then a clear return.
let tranceLight = 1;
if (S.goal === "trance" && S.started){
const e = S.elapsed, back = total - RETURN;
if (e >= back) tranceLight = .06 + .94 * Math.min(1, (e - back) / (RETURN - 10));
else if (e >= SETTLE) tranceLight = 1 - .94 * Math.min(1, (e - SETTLE) / 30);
cue(e < 14 ? "Headphones on. Let the drum carry you. There is nothing to follow or figure out."
: e >= SETTLE - 15 && e < SETTLE + 20 ? "Close your eyes."
: e >= back ? "The drum has stopped. Come back slowly and open your eyes." : "");
if (drumBus) drumBus.gain.value = S.vol * S.drum;
if (S.running && p >= 1){ reset(); renderRead("Session complete."); }
} else cue("");
// Loudness in the low end, smoothed over about half a second so nothing can flicker.
let b = 0;
if (analyser && S.running){
analyser.getByteFrequencyData(fd);
const nb = Math.max(2, Math.round(160 / (ac.sampleRate / analyser.fftSize)));
for (let i = 1; i <= nb; i++) b += fd[i];
b /= nb * 255;
}
bass += (b - bass) * (1 - Math.exp(-dt / .5));
const moving = S.running || (!reduced && !S.started) || (S.started && !reduced);
if (moving){
const stretch = 1 + P.slow * ease;
phase = (phase + dt / (cur.period * stretch)) % 1;
rot += dt * cur.rot * .25 / stretch;
}
if (sceneNow === null) sceneNow = P.scene;
if (sceneNow !== P.scene){ sceneFade -= dt * 2; if (sceneFade <= 0){ sceneFade = 0; sceneNow = P.scene; } }
else sceneFade = Math.min(1, sceneFade + dt * 1.2);
ctx.setTransform(DPR, 0, 0, DPR, 0, 0);
ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over";
ctx.fillStyle = "#05060a"; ctx.fillRect(0, 0, W, H);
draw[sceneNow]({
cx: W / 2, cy: H / 2, Rmin: Math.min(W, H) / 2, Rmax: Math.hypot(W, H) / 2,
b: breathCurve(phase), a: Math.min(.5, bass * cur.react * 1.6), rot,
hue: cur.hue, sat: cur.sat, light: cur.light
});
const v = ctx.createRadialGradient(W/2, H/2, Math.min(W, H) * .3, W/2, H/2, Math.hypot(W, H) / 2);
v.addColorStop(0, "rgba(0,0,0,0)"); v.addColorStop(1, "rgba(0,0,0,.6)");
ctx.fillStyle = v; ctx.fillRect(0, 0, W, H);
const lightLeft = (1 - P.dim * ease) * sceneFade * endFade * tranceLight;
if (lightLeft < 1){ ctx.fillStyle = `rgba(0,0,0,${1 - lightLeft})`; ctx.fillRect(0, 0, W, H); }
}
derive();
Object.assign(cur, {hue:P.hue, period:P.period, react:P.react, rot:P.rot, sat:P.sat, light:P.light});
resize();
requestAnimationFrame(frame);