Custom Code Experiment •
Skoodu
Source Code View HTML / CSS / JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">
<title>OwnZones</title>
<meta name="theme-color" content="#cbccd0">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="OwnZones">
<meta name="apple-mobile-web-app-status-bar-style" content="default">
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' fill='%23cbccd0'/%3E%3Cg fill='none' stroke='%23fff' stroke-width='1.6'%3E%3Crect x='4' y='4' width='6' height='6'/%3E%3Crect x='13' y='4' width='6' height='6'/%3E%3Crect x='22' y='4' width='6' height='6'/%3E%3Crect x='4' y='13' width='6' height='6'/%3E%3Crect x='22' y='13' width='6' height='6'/%3E%3Crect x='4' y='22' width='6' height='6'/%3E%3Crect x='13' y='22' width='6' height='6'/%3E%3Crect x='22' y='22' width='6' height='6'/%3E%3C/g%3E%3Cpath d='M13 13h6l3 6h-6z' fill='none' stroke='%23141414' stroke-width='1.6'/%3E%3C/svg%3E">
<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=Courier+Prime:wght@400;700&family=Syne:wght@700&display=swap" rel="stylesheet">
<style>
:root {
--bg: #cbccd0;
--chalk: #ffffff;
--ink: #141414;
--soft: #55575c;
--muted: #808287;
--pad-x: 96px;
--pad-y: 80px;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
:root {
padding-top: env(safe-area-inset-top, 0px);
padding-bottom: env(safe-area-inset-bottom, 0px);
}
html, body { height: 100%; }
body {
background: var(--bg);
overflow: hidden;
color: var(--ink);
font-family: 'Courier Prime', 'Courier New', Courier, ui-monospace, monospace;
-webkit-tap-highlight-color: transparent;
touch-action: none;
overscroll-behavior: none;
user-select: none; -webkit-user-select: none;
}
html { overscroll-behavior: none; }
body::before {
content: '';
position: fixed; inset: 0;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)' opacity='0.05'/%3E%3C/svg%3E");
pointer-events: none; z-index: 100; opacity: 0.6;
}
.wordmark {
position: fixed;
top: calc(var(--pad-y) + env(safe-area-inset-top, 0px));
left: var(--pad-x);
font-family: 'Syne', 'Arial Black', 'Helvetica Neue', Arial, sans-serif;
font-weight: 700; font-size: 14px; letter-spacing: 0.06em;
z-index: 7;
}
.sound {
position: fixed;
left: calc(var(--pad-x) - 6px);
bottom: calc(var(--pad-y) - 6px + env(safe-area-inset-bottom, 0px));
display: flex; align-items: center; gap: 10px;
background: none; border: 0; padding: 6px;
font: inherit; font-size: 12px; color: var(--soft);
cursor: pointer; z-index: 7;
}
.sound i { width: 8px; height: 8px; flex: none; border: 1px solid var(--ink); }
.sound.on i { background: var(--ink); }
.sound:focus-visible { outline: 1px dashed var(--ink); outline-offset: 2px; }
.songs {
position: fixed;
top: calc(var(--pad-y) - 5px + env(safe-area-inset-top, 0px));
right: calc(var(--pad-x) - 6px);
display: flex; flex-direction: column; align-items: flex-end;
z-index: 7;
}
.songs button {
display: flex; align-items: center; gap: 10px;
background: none; border: 0; padding: 2px 6px;
font: inherit; font-size: 12px; line-height: 1.4;
color: var(--muted); cursor: pointer;
}
.songs button i { width: 6px; height: 6px; border: 1px solid currentColor; flex: none; }
.songs button:hover { color: var(--ink); }
.songs button[aria-current="true"] { color: var(--ink); }
.songs button[aria-current="true"] i { background: var(--ink); border-color: var(--ink); }
.songs button:focus-visible { outline: 1px dashed var(--ink); outline-offset: 1px; }
.songs button .name { margin-left: -2px; }
html.compact .songs { display: none; }
html.compact .sound {
top: calc(var(--pad-y) - 7px + env(safe-area-inset-top, 0px)); bottom: auto;
left: auto; right: calc(var(--pad-x) - 6px);
}
html.tight .hint { display: none; }
html.single .songs, html.single .nav-hint { display: none !important; }
html.single .transport .step { visibility: hidden; }
.wordmark, .hint, .play-word, #soundLabel { display: none !important; }
.transport .now { cursor: default; }
.transport {
position: fixed; left: 50%; top: 0; z-index: 8;
transform: translate(-50%, -50%);
display: flex; align-items: center; gap: 2px;
max-width: calc(100vw - 12px);
}
.transport button {
background: none; border: 0; font: inherit; color: var(--ink);
cursor: pointer; touch-action: manipulation;
}
.transport .now {
min-height: 44px; min-width: 0; padding: 3px 10px;
display: flex; flex-direction: column; align-items: center; justify-content: center;
}
.transport .now .main, .transport .now .sub { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.transport .now .main { font-size: 15px; line-height: 20px; }
.transport .now .sub { font-size: 11.5px; line-height: 15px; color: var(--soft); }
.transport .step { flex: none; }
.transport .step {
width: 44px; height: 44px; display: grid; place-items: center;
opacity: 0.5; transition: opacity 0.15s ease;
}
.transport .step:hover, .transport .step:active { opacity: 1; }
.transport .step svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 1.4; }
.transport button:focus-visible { outline: 1px dashed var(--ink); outline-offset: -2px; }
.sheet {
position: fixed; inset: 0; z-index: 60;
display: flex; align-items: center; justify-content: center;
padding: calc(24px + env(safe-area-inset-top, 0px)) 22px calc(24px + env(safe-area-inset-bottom, 0px));
background: rgba(203, 204, 208, 0.95);
-webkit-backdrop-filter: blur(8px); backdrop-filter: blur(8px);
}
.sheet[hidden] { display: none; }
.sheet-panel { width: min(440px, 100%); max-height: 100%; overflow-y: auto; -webkit-overflow-scrolling: touch; touch-action: pan-y; }
.sheet-title {
font-family: 'Syne', 'Arial Black', 'Helvetica Neue', Arial, sans-serif;
font-weight: 700; font-size: 14px; letter-spacing: 0.06em; margin-bottom: 16px;
}
.sheet-list { list-style: none; border-top: 1px solid var(--chalk); }
.sheet-list button {
width: 100%; min-height: 54px; padding: 6px 4px;
display: flex; align-items: center; gap: 14px;
background: none; border: 0; border-bottom: 1px solid var(--chalk);
font: inherit; font-size: 16px; color: var(--soft); text-align: left; cursor: pointer;
}
.sheet-list button i { width: 8px; height: 8px; border: 1px solid currentColor; flex: none; }
.sheet-list .num { font-size: 12px; color: var(--muted); width: 20px; flex: none; }
.sheet-list .what { display: flex; flex-direction: column; gap: 2px; }
.sheet-list .meta { font-size: 11px; color: var(--muted); }
.sheet-list button[aria-current="true"] { color: var(--ink); }
.sheet-list button[aria-current="true"] i { background: var(--ink); border-color: var(--ink); }
.sheet-list button:focus-visible, .sheet-close:focus-visible { outline: 1px dashed var(--ink); outline-offset: -2px; }
.sheet-help { margin-top: 14px; font-size: 11.5px; line-height: 1.6; color: var(--muted); }
.sheet-help span { display: block; }
.sheet-help .touch { display: none; }
@media (hover: none) { .sheet-help .keys { display: none; } .sheet-help .touch { display: block; } }
.sheet-close {
margin-top: 14px; min-height: 44px; padding: 0 10px;
background: none; border: 0; font: inherit; font-size: 13px; color: var(--soft); cursor: pointer;
}
.hint {
position: fixed;
right: var(--pad-x);
bottom: calc(var(--pad-y) + env(safe-area-inset-bottom, 0px));
font-size: 12px; line-height: 1.5; color: var(--muted);
text-align: right;
z-index: 7;
}
.hint span { display: block; }
.hint .touch { display: none; }
@media (hover: none) { .hint .keys { display: none; } .hint .touch { display: block; } }
#stage {
position: fixed; inset: 0; width: 100%; height: 100%;
overflow: visible; touch-action: none; display: block; z-index: 2;
}
.tile { fill: none; stroke: var(--chalk); stroke-width: 1.5; stroke-linejoin: miter; }
.ghost { fill: none; stroke: var(--chalk); stroke-width: 1; stroke-dasharray: 2 4; opacity: 0; }
.mark { fill: none; stroke: var(--ink); stroke-width: 1; opacity: 0.3; }
.hit { fill: transparent; stroke: none; cursor: pointer; outline: none; }
.hit:focus-visible { stroke: var(--ink); stroke-width: 1; stroke-dasharray: 2 3; }
.play-base { fill: none; stroke: var(--chalk); stroke-width: 1.5; opacity: 0; }
.play-trace { fill: none; stroke: var(--ink); stroke-width: 2; }
#stage.playing .play-base { opacity: 1; }
.play-word {
font-family: 'Courier Prime', 'Courier New', Courier, ui-monospace, monospace;
font-size: 13px; fill: var(--ink); text-anchor: middle; pointer-events: none;
}
.lead { stroke: var(--ink); stroke-width: 1; visibility: hidden; }
.play-icon { fill: var(--ink); stroke: none; pointer-events: none; display: none; }
.ring { fill: none; stroke: var(--ink); stroke-width: 1; pointer-events: none; }
.note {
position: fixed; z-index: 6; pointer-events: none;
font-size: 15px; line-height: 20px; margin-top: -10px;
white-space: nowrap;
}
.note .sub { display: block; font-size: 11.5px; line-height: 15px; color: var(--soft); }
.note.right { text-align: right; }
.callout {
position: fixed; left: 0; top: 0; z-index: 6;
margin-top: -9px;
font-size: 13px; line-height: 18px; white-space: nowrap;
pointer-events: none; visibility: hidden;
will-change: transform, opacity;
}
.note.center { text-align: center; transform: translateX(-50%); }
</style>
</head>
<body>
<p class="wordmark">OwnZones</p>
<nav class="songs" id="songs" aria-label="Songs"></nav>
<svg id="stage" xmlns="http://www.w3.org/2000/svg" aria-label="Tile instrument">
<g id="ghosts"></g>
<g id="marks"></g>
<g id="tiles"></g>
<g id="rings"></g>
<g id="play"></g>
<g id="leads"></g>
<g id="hits"></g>
</svg>
<div class="transport" id="transport">
<button class="step" id="prevTrack" type="button" aria-label="Previous track"><svg viewBox="0 0 14 14" aria-hidden="true"><path d="M9 2 L4 7 L9 12"/></svg></button>
<button class="now" id="trackNow" type="button" aria-haspopup="dialog" aria-label="Show all tracks"><span class="main" id="statusMain"></span><span class="sub" id="statusSub"></span></button>
<button class="step" id="nextTrack" type="button" aria-label="Next track"><svg viewBox="0 0 14 14" aria-hidden="true"><path d="M5 2 L10 7 L5 12"/></svg></button>
</div>
<div class="sheet" id="sheet" hidden>
<div class="sheet-panel" role="dialog" aria-modal="true" aria-labelledby="sheetTitle">
<p class="sheet-title" id="sheetTitle">OwnZones</p>
<ol class="sheet-list" id="sheetList"></ol>
<p class="sheet-help">
<span class="keys">hover.tiles.to.play</span><span class="keys">space.plays.and.stops</span><span class="keys nav-hint">arrow.keys.change.track</span>
<span class="touch">slide.across.tiles.to.play</span><span class="touch">tap.play.in.the.centre</span><span class="touch nav-hint">swipe.to.change.track</span>
</p>
<button class="sheet-close" id="sheetClose" type="button">close</button>
</div>
</div>
<div id="callouts" aria-hidden="true"></div>
<button class="sound" id="soundBtn" type="button" aria-pressed="false"><i aria-hidden="true"></i><span id="soundLabel">click.to.wake.audio</span></button>
<p class="hint"><span id="hintTiles">hover.any.tile</span><span class="keys" id="hintSpace">press.space.to.play</span><span class="keys nav-hint">arrow.keys.change.track</span><span class="touch nav-hint">swipe.to.change.track</span></p>
<script>
let audioCtx = null;
let audioReady = false;
let muted = false;
const MASTER_LEVEL = 0.88;
function getCtx() {
if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
return audioCtx;
}
const rooms = new Map();
function impulse(ctx, seconds, shape, tone = 1) {
const len = Math.floor(ctx.sampleRate * seconds);
const buf = ctx.createBuffer(2, len, ctx.sampleRate);
for (let ch = 0; ch < 2; ch++) {
const d = buf.getChannelData(ch);
let smooth = 0;
for (let i = 0; i < len; i++) {
smooth += tone * ((Math.random() * 2 - 1) - smooth);
d[i] = smooth * Math.pow(1 - i / len, shape) * (tone < 1 ? 1.6 : 1);
}
}
return buf;
}
function roomFor(song) {
if (!song.room) return getMaster();
let input = rooms.get(song);
if (!input) {
const ctx = getCtx();
input = ctx.createGain();
const conv = ctx.createConvolver(), wet = ctx.createGain();
conv.buffer = impulse(ctx, song.room.seconds, song.room.shape, song.room.tone);
wet.gain.value = song.room.wet;
input.connect(getMaster());
input.connect(conv); conv.connect(wet); wet.connect(getMaster());
rooms.set(song, input);
}
return input;
}
function getMaster() {
const ctx = getCtx();
if (!getMaster._node) {
const lim = ctx.createDynamicsCompressor();
lim.threshold.value = -6;
lim.knee.value = 3;
lim.ratio.value = 12;
lim.attack.value = 0.001;
lim.release.value = 0.1;
const out = ctx.createGain();
out.gain.value = muted ? 0 : MASTER_LEVEL;
lim.connect(out); out.connect(ctx.destination);
getMaster._node = lim;
getMaster._out = out;
}
return getMaster._node;
}
const noiseCache = new WeakMap();
function noiseSource(ctx) {
let buf = noiseCache.get(ctx);
if (!buf) {
buf = ctx.createBuffer(1, ctx.sampleRate * 2, ctx.sampleRate);
const d = buf.getChannelData(0);
for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
noiseCache.set(ctx, buf);
}
const src = ctx.createBufferSource();
src.buffer = buf;
return src;
}
function decay(ctx, t, peak, len) {
const g = ctx.createGain();
g.gain.value = 0;
g.gain.setValueAtTime(peak, t);
g.gain.exponentialRampToValueAtTime(0.001, t + len);
return g;
}
function toneHit(ctx, out, t, { type = 'sine', freq, to, glide = 0, peak, len }) {
const o = ctx.createOscillator();
o.type = type;
o.frequency.setValueAtTime(freq, t);
if (to) o.frequency.exponentialRampToValueAtTime(to, t + glide);
const g = decay(ctx, t, peak, len);
o.connect(g); g.connect(out);
o.start(t); o.stop(t + len + 0.03);
}
function noiseHit(ctx, out, t, { type, freq, Q = 1, peak, len }) {
const src = noiseSource(ctx);
const f = ctx.createBiquadFilter();
f.type = type; f.frequency.value = freq; f.Q.value = Q;
const g = decay(ctx, t, peak, len);
src.connect(f); f.connect(g); g.connect(out);
src.start(t, Math.random() * Math.max(0, 1.9 - len));
src.stop(t + len + 0.03);
}
const hat = (cut, len, peak) => (ctx, out, t) => noiseHit(ctx, out, t, { type: 'highpass', freq: cut, peak, len });
function echoes(voice, repeats, spacing, fall) {
return (ctx, out, t) => {
for (let k = 0; k <= repeats; k++) {
let dest = out;
if (k > 0) {
const g = ctx.createGain(), lp = ctx.createBiquadFilter();
g.gain.value = Math.pow(fall, k);
lp.type = 'lowpass'; lp.frequency.value = 5000 / (k + 0.5);
g.connect(lp); lp.connect(out);
dest = g;
}
voice(ctx, dest, t + k * spacing);
}
};
}
function swell(ctx, t, peak, attack, hold, release) {
const g = ctx.createGain();
g.gain.value = 0;
g.gain.setValueAtTime(0, t);
g.gain.linearRampToValueAtTime(peak, t + attack);
g.gain.setValueAtTime(peak, t + attack + hold);
g.gain.exponentialRampToValueAtTime(0.001, t + attack + hold + release);
return g;
}
function noiseBed(ctx, t, filter, g, stopAt) {
const src = noiseSource(ctx);
src.loop = true;
src.connect(filter); filter.connect(g);
src.start(t, Math.random() * 1.5); src.stop(stopAt);
}
const dnb = {
kickPunch: (ctx, out, t) => {
toneHit(ctx, out, t, { freq: 160, to: 45, glide: 0.08, peak: 0.9, len: 0.28 });
noiseHit(ctx, out, t, { type: 'highpass', freq: 3000, peak: 0.2, len: 0.012 });
},
kickSub: (ctx, out, t) => toneHit(ctx, out, t, { freq: 70, to: 35, glide: 0.2, peak: 0.8, len: 0.5 }),
};
const crushCurves = {};
function crushCurve(levels) {
if (!crushCurves[levels]) {
const n = 1024, c = new Float32Array(n + 1);
for (let i = 0; i <= n; i++) { const x = i / n * 2 - 1; c[i] = Math.round(x * levels) / levels; }
crushCurves[levels] = c;
}
return crushCurves[levels];
}
function crusher(ctx, levels) {
const w = ctx.createWaveShaper();
w.curve = crushCurve(levels);
return w;
}
const idm = {
stutter: (ctx, out, t) => {
let ti = t;
for (let i = 0; i < 9; i++) {
noiseHit(ctx, out, ti, { type: 'bandpass', freq: 1800, Q: 2, peak: 0.25, len: 0.02 });
toneHit(ctx, out, ti, { type: 'square', freq: 440, peak: 0.06, len: 0.02 });
ti += 0.06 * Math.pow(0.82, i);
}
},
};
const crushed = (voice, levels) => (ctx, out, t) => {
const cr = crusher(ctx, levels);
cr.connect(out);
voice(ctx, cr, t);
};
const subTone = freq => (ctx, out, t) => {
const g = swell(ctx, t, 0.5, 0.01, 0.3, 0.5);
g.connect(out);
const o = ctx.createOscillator();
o.type = 'sine'; o.frequency.value = freq;
o.connect(g); o.start(t); o.stop(t + 0.85);
};
function fmHit(ctx, out, t, { freq, to, glide = 0, ratio, index, indexTo = 1, indexTime, peak, len }) {
const car = ctx.createOscillator(), mod = ctx.createOscillator(), idx = ctx.createGain(), g = decay(ctx, t, peak, len);
car.frequency.setValueAtTime(freq, t);
mod.frequency.setValueAtTime(freq * ratio, t);
if (to) {
car.frequency.exponentialRampToValueAtTime(to, t + glide);
mod.frequency.exponentialRampToValueAtTime(to * ratio, t + glide);
}
idx.gain.setValueAtTime(index, t);
idx.gain.exponentialRampToValueAtTime(Math.max(1, indexTo), t + (indexTime || len));
mod.connect(idx); idx.connect(car.frequency); car.connect(g); g.connect(out);
car.start(t); mod.start(t); car.stop(t + len + 0.03); mod.stop(t + len + 0.03);
}
const fm = opts => (ctx, out, t) => fmHit(ctx, out, t, opts);
const coldPad = freqs => (ctx, out, t) => {
const lp = ctx.createBiquadFilter(), g = swell(ctx, t, 0.14, 2, 2, 2.5);
lp.type = 'lowpass'; lp.Q.value = 2;
lp.frequency.setValueAtTime(400, t);
lp.frequency.linearRampToValueAtTime(1600, t + 3);
lp.frequency.linearRampToValueAtTime(500, t + 6);
lp.connect(g); g.connect(out);
freqs.forEach(freq => [['sine', -6], ['triangle', 6]].forEach(([type, det]) => {
const o = ctx.createOscillator(), og = ctx.createGain();
o.type = type; o.frequency.value = freq; o.detune.value = det;
og.gain.value = 0.35;
o.connect(og); og.connect(lp);
o.start(t); o.stop(t + 6.6);
}));
};
const rule = {
grainCloud: (ctx, out, t) => {
for (let i = 0; i < 30; i++) {
fmHit(ctx, out, t + Math.random() * 1.2, { freq: 800 + Math.random() * 2800, ratio: 1 + Math.random() * 3, index: 1500, indexTo: 50, peak: 0.05, len: 0.03 });
}
},
dataBurst: (ctx, out, t) => {
for (let i = 0; i < 16; i++) {
fmHit(ctx, out, t + i * 0.03, { freq: 800 + Math.random() * 3200, ratio: pickFrom([1, 1.5, 2, 3.5]), index: 1200, indexTo: 50, peak: 0.08, len: 0.02 });
}
},
formantShift: (ctx, out, t) => {
const src = ctx.createOscillator();
src.type = 'sawtooth'; src.frequency.value = 130.81;
const g = swell(ctx, t, 0.25, 0.2, 1.0, 0.4);
g.connect(out);
[[[800, 300, 350], 8], [[1200, 2300, 800], 10]].forEach(([path, Q]) => {
const bp = ctx.createBiquadFilter();
bp.type = 'bandpass'; bp.Q.value = Q;
bp.frequency.setValueAtTime(path[0], t);
bp.frequency.linearRampToValueAtTime(path[1], t + 0.75);
bp.frequency.linearRampToValueAtTime(path[2], t + 1.5);
src.connect(bp); bp.connect(g);
});
src.start(t); src.stop(t + 1.65);
},
hatRing: (ctx, out, t) => {
const a = ctx.createOscillator(), b = ctx.createOscillator(), ring = ctx.createGain(), hp = ctx.createBiquadFilter(), g = decay(ctx, t, 0.25, 0.08);
a.type = 'square'; a.frequency.value = 540;
b.type = 'square'; b.frequency.value = 800;
ring.gain.value = 0;
b.connect(ring.gain); a.connect(ring);
hp.type = 'highpass'; hp.frequency.value = 4000;
ring.connect(hp); hp.connect(g); g.connect(out);
a.start(t); b.start(t); a.stop(t + 0.1); b.stop(t + 0.1);
},
snareGate: (ctx, out, t) => {
const bp = ctx.createBiquadFilter(), g = swell(ctx, t, 0.35, 0.002, 0.07, 0.01);
bp.type = 'bandpass'; bp.frequency.value = 2200;
g.connect(out);
noiseBed(ctx, t, bp, g, t + 0.1);
toneHit(ctx, out, t, { freq: 200, peak: 0.2, len: 0.06 });
},
clapDigital: (ctx, out, t) => {
const cr = crusher(ctx, 6);
cr.connect(out);
for (let i = 0; i < 4; i++) noiseHit(ctx, cr, t + i * 0.008, { type: 'bandpass', freq: 1500, peak: 0.35, len: 0.012 });
},
crunch: (ctx, out, t) => {
const src = noiseSource(ctx), cr = crusher(ctx, 3), bp = ctx.createBiquadFilter(), g = decay(ctx, t, 0.45, 0.06);
bp.type = 'bandpass'; bp.frequency.value = 900;
src.connect(cr); cr.connect(bp); bp.connect(g); g.connect(out);
src.start(t, Math.random()); src.stop(t + 0.08);
},
buzz: (ctx, out, t) => {
const o = ctx.createOscillator(), cr = crusher(ctx, 4), bp = ctx.createBiquadFilter(), g = decay(ctx, t, 0.3, 0.15);
o.type = 'square'; o.frequency.value = 55;
bp.type = 'bandpass'; bp.frequency.value = 700;
o.connect(cr); cr.connect(bp); bp.connect(g); g.connect(out);
o.start(t); o.stop(t + 0.18);
},
reverseFm: (ctx, out, t) => {
const car = ctx.createOscillator(), mod = ctx.createOscillator(), idx = ctx.createGain(), g = ctx.createGain();
car.frequency.value = 440; mod.frequency.value = 440 * 1.414; idx.gain.value = 900;
g.gain.value = 0;
g.gain.setValueAtTime(0.001, t);
g.gain.exponentialRampToValueAtTime(0.25, t + 0.5);
g.gain.linearRampToValueAtTime(0, t + 0.52);
mod.connect(idx); idx.connect(car.frequency); car.connect(g); g.connect(out);
car.start(t); mod.start(t); car.stop(t + 0.55); mod.stop(t + 0.55);
},
};
function pickFrom(list) { return list[Math.floor(Math.random() * list.length)]; }
const fmStab = freqs => (ctx, out, t) => {
const lp = ctx.createBiquadFilter();
lp.type = 'lowpass'; lp.frequency.value = 5000;
lp.connect(out);
freqs.forEach(freq => fmHit(ctx, lp, t, { freq, ratio: 2, index: freq * 3, indexTo: 1, indexTime: 0.1, peak: 0.16, len: 0.22 }));
};
const fmSnare = (ctx, out, t) => {
fmHit(ctx, out, t, { freq: 180, ratio: 7.3, index: 2000, indexTo: 100, indexTime: 0.15, peak: 0.35, len: 0.18 });
noiseHit(ctx, out, t, { type: 'highpass', freq: 3000, peak: 0.2, len: 0.1 });
};
const R30_STEP = 60 / 172 / 4;
const chime = freq => echoes(fm({ freq, ratio: 1.4, index: freq * 2.5, indexTo: 1, indexTime: 0.4, peak: 0.22, len: 1.0 }), 1, 3 * R30_STEP, 0.35);
const fmGrowl = freq => (ctx, out, t) => {
const car = ctx.createOscillator(), mod = ctx.createOscillator(), idx = ctx.createGain();
const lfo = ctx.createOscillator(), lfoDepth = ctx.createGain();
car.frequency.value = freq * 2; mod.frequency.value = freq * 2;
idx.gain.value = freq * 4;
lfo.frequency.value = 1 / R30_STEP;
lfoDepth.gain.value = freq * 3.6;
lfo.connect(lfoDepth); lfoDepth.connect(idx.gain);
mod.connect(idx); idx.connect(car.frequency);
const cr = crusher(ctx, 16), lp = ctx.createBiquadFilter(), g = decay(ctx, t, 0.22, 0.45);
lp.type = 'lowpass'; lp.frequency.value = 1600;
car.connect(cr); cr.connect(lp); lp.connect(g); g.connect(out);
const sub = ctx.createOscillator(), sg = decay(ctx, t, 0.3, 0.5);
sub.type = 'sine'; sub.frequency.value = freq;
sub.connect(sg); sg.connect(out);
[car, mod, lfo, sub].forEach(o => { o.start(t); o.stop(t + 0.55); });
};
const fmHoover = (ctx, out, t) => {
const lp = ctx.createBiquadFilter(), g = swell(ctx, t, 0.12, 0.05, 0.4, 0.5);
lp.type = 'lowpass'; lp.frequency.value = 2500;
lp.connect(g); g.connect(out);
[146.83, 174.61, 207.65, 246.94].forEach(freq => [-15, 15].forEach(det => {
const car = ctx.createOscillator(), mod = ctx.createOscillator(), idx = ctx.createGain(), og = ctx.createGain();
car.frequency.setValueAtTime(freq * 0.7, t); car.frequency.exponentialRampToValueAtTime(freq, t + 0.15);
mod.frequency.setValueAtTime(freq * 0.7, t); mod.frequency.exponentialRampToValueAtTime(freq, t + 0.15);
car.detune.value = det; mod.detune.value = det;
idx.gain.value = freq * 1.5;
og.gain.value = 0.5;
mod.connect(idx); idx.connect(car.frequency); car.connect(og); og.connect(lp);
car.start(t); mod.start(t); car.stop(t + 1.0); mod.stop(t + 1.0);
}));
};
const harmonicPad = (base, harmonics, peak) => (ctx, out, t) => {
const g = swell(ctx, t, peak, 1.2, 1.8, 2.2);
g.connect(out);
harmonics.forEach(h => {
const o = ctx.createOscillator();
o.type = 'sine'; o.frequency.value = base * h;
o.connect(g); o.start(t); o.stop(t + 5.3);
});
};
const r30 = {
bitRain: (ctx, out, t) => {
const cr = crusher(ctx, 5);
cr.connect(out);
for (let i = 0; i < 40; i++) {
noiseHit(ctx, cr, t + Math.random() * 1.5, { type: 'bandpass', freq: 1500 + Math.random() * 6000, Q: 2, peak: 0.35, len: 0.008 });
}
},
gear: (ctx, out, t) => {
let ti = t;
for (let i = 0; i < 8; i++) {
fmHit(ctx, out, ti, { freq: 2400 + i * 100, ratio: 2.2, index: 1500, indexTo: 30, peak: 0.2, len: 0.012 });
ti += 0.05 * Math.pow(0.85, i);
}
},
};
const KIT_RULE30 = {
1: [
['chime.d4', 293.66], ['chime.e♭4', 311.13], ['chime.f4', 349.23], ['chime.f♯4', 369.99],
['chime.g♯4', 415.3], ['chime.a4', 440.0], ['chime.b4', 493.88], ['chime.c5', 523.25],
].map(([id, freq]) => [id, chime(freq), { vel: 0.85, look: ['shear', 'echo'] }]),
2: [
['growl.g♯1', fmGrowl(51.91), { look: ['fold', 'pulse-small'], vel: 0.8, hit: { push: 80, twirl: 1.5 } }],
['growl.a1', fmGrowl(55.0), { look: ['fold', 'pulse-small'], vel: 0.8, hit: { push: 80, twirl: 1.5 } }],
['growl.b1', fmGrowl(61.74), { look: ['fold', 'pulse-small'], vel: 0.8, hit: { push: 80, twirl: 1.5 } }],
['growl.d2', fmGrowl(73.42), { look: ['fold', 'pulse-small'], vel: 0.8, hit: { push: 80, twirl: 1.5 } }],
['growl.e♭2', fmGrowl(77.78), { look: ['fold', 'pulse-small'], vel: 0.8, hit: { push: 80, twirl: 1.5 } }],
['growl.f2', fmGrowl(87.31), { look: ['fold', 'pulse-small'], vel: 0.8, hit: { push: 80, twirl: 1.5 } }],
['sub.d2', subTone(73.42), { look: ['pulse-big', 'fill'], hit: { push: 90 } }],
['hoover.dim', fmHoover, { look: ['flip', 'ring-big'], vel: 0.8, hit: { push: 60, reach: 500, lift: 50, swirl: 1, centre: true } }],
['stab.dim.d', fmStab([293.66, 349.23, 415.3, 493.88]), { look: ['flip', 'fill-small'], vel: 0.8, hit: { push: 110, reach: 280, scatter: true } }],
['stab.dim.e♭', fmStab([311.13, 369.99, 440.0, 523.25]), { look: ['flip', 'fill-small'], vel: 0.8, hit: { push: 110, reach: 280, scatter: true } }],
['data.burst', rule.dataBurst, { look: ['jitter-big'], vel: 0.8, hit: { push: 120, reach: 300, scatter: true } }],
['grain.cloud', rule.grainCloud, { look: ['jitter', 'ring'], vel: 0.8, hit: { push: 40, reach: 400, scatter: true } }],
['formant.shift', rule.formantShift, { look: ['spin-big'], vel: 0.8, hit: { push: 60, reach: 350, swirl: -1, centre: true } }],
['bit.rain', r30.bitRain, { look: ['jitter'], vel: 0.8, hit: { push: 50, reach: 400, scatter: true } }],
['cold.pad.d', coldPad([146.83, 174.61, 207.65, 246.94]), { look: ['breathe'], hit: { push: 12, lift: 40 } }],
['glass.pad', harmonicPad(146.83, [5, 7, 9, 11], 0.05), { look: ['breathe', 'ring'], hit: { push: 10, lift: 40 } }],
],
3: [
['kick.fm', fm({ freq: 90, to: 45, glide: 0.08, ratio: 1.6, index: 400, indexTo: 1, indexTime: 0.05, peak: 0.6, len: 0.3 }), { look: ['pulse', 'fill-small'], vel: 0.8, hit: { push: 160 } }],
['hat.fm1', fm({ freq: 7000, ratio: 1.43, index: 6000, peak: 0.3, len: 0.04 }), { look: ['jitter-small'], vel: 0.5 }],
['clang.2', fm({ freq: 587.33, ratio: 2.76, index: 1500, indexTo: 20, indexTime: 0.4, peak: 0.3, len: 0.6 }), { look: ['flip', 'fill'], vel: 0.7, hit: { push: 140, reach: 260, scatter: true } }],
['snare.fm', fmSnare, { look: ['squash', 'shrink-small'], vel: 0.85, hit: { push: -95 } }],
['gear', r30.gear, { look: ['spin-big'], vel: 0.7, hit: { push: 30, reach: 300, twirl: 7 } }],
['hat.fm2', fm({ freq: 5200, ratio: 2.71, index: 5000, peak: 0.3, len: 0.06 }), { look: ['jitter-small'], vel: 0.5 }],
['kick.punch', dnb.kickPunch, { look: ['pulse', 'fill'], vel: 0.72, hit: { push: 170 } }],
['hat.noise', hat(9000, 0.03, 0.35), { look: ['jitter-small'], vel: 0.5 }],
['rim.fm', fm({ freq: 1400, ratio: 2.3, index: 1500, indexTo: 10, indexTime: 0.02, peak: 0.32, len: 0.03 }), { look: ['squash-small'], vel: 0.6, hit: { push: -30 } }],
['snare.gate', rule.snareGate, { look: ['squash'], vel: 0.8, hit: { push: -80 } }],
['crunch', rule.crunch, { look: ['jitter-big', 'fill'], vel: 0.8, hit: { push: 250, reach: 210, scatter: true } }],
['hat.ring', rule.hatRing, { look: ['spin-small'], vel: 0.5, hit: { push: 20, reach: 180, scatter: true } }],
['kick.sub', dnb.kickSub, { look: ['pulse-big', 'fill'], vel: 0.85, hit: { push: 150 } }],
['ride.fm', (ctx, out, t) => {
fmHit(ctx, out, t, { freq: 3200, ratio: 1.47, index: 3000, indexTo: 200, peak: 0.1, len: 0.8 });
noiseHit(ctx, out, t, { type: 'highpass', freq: 7000, peak: 0.06, len: 0.4 });
}, { look: ['shear-small', 'ring-small'], vel: 0.5 }],
['buzz', rule.buzz, { look: ['jitter'], vel: 0.7, hit: { push: 90, reach: 260, scatter: true } }],
['clap.digital', rule.clapDigital, { look: ['squash', 'jitter'], vel: 0.7, hit: { push: 100, reach: 240, scatter: true } }],
['zap.fm', fm({ freq: 3000, to: 200, glide: 0.08, ratio: 1.5, index: 2000, indexTo: 100, peak: 0.2, len: 0.1 }), { look: ['shear', 'spin-small'], vel: 0.6, hit: { plane: [-1, 0], push: 90 } }],
['click.sample', (ctx, out, t) => noiseHit(ctx, out, t, { type: 'highpass', freq: 12000, peak: 0.6, len: 0.002 }), { look: ['jitter-small'], vel: 0.6, hit: { push: 40, reach: 150, scatter: true } }],
['clang.big', fm({ freq: 196.0, ratio: 1.414, index: 1800, indexTo: 20, indexTime: 0.8, peak: 0.42, len: 1.3 }), { look: ['fill-long', 'pulse-big', 'ring-big'], vel: 0.8, hit: { push: 440, reach: 380 } }],
['snare.ghost', fm({ freq: 220, ratio: 6.1, index: 1200, indexTo: 50, peak: 0.12, len: 0.05 }), { look: ['squash-small'], vel: 0.5, hit: { push: -15 } }],
['stutter', idm.stutter, { look: ['jitter-big', 'spin'], vel: 0.6, hit: { push: 70, reach: 400, spin: 3, scatter: true } }],
['snare.crush', crushed(fmSnare, 4), { look: ['squash-small', 'jitter'], vel: 0.75, hit: { push: 110, reach: 220, scatter: true } }],
['reverse.fm', rule.reverseFm, { look: ['shrink-big'], vel: 0.8, hit: { push: -130, reach: 400 } }],
['tine', fm({ freq: 2349, ratio: 3.5, index: 3000, indexTo: 5, indexTime: 0.1, peak: 0.22, len: 0.4 }), { look: ['ring', 'shear-small'], vel: 0.6, hit: { push: 15 } }],
],
};
function playSound(id) {
if (!audioReady) return;
const tile = TILE[id];
if (!tile) return;
try {
const ctx = getCtx();
if (ctx.state === 'suspended') ctx.resume();
tile.voice(ctx, roomFor(cur), ctx.currentTime);
} catch (e) { }
}
function makeWriter(velOf) {
const events = [], sections = [];
let cursor = 0;
const vel = id => velOf[id];
const hit = (bar, step, id, len = 1, v) => events.push({ at: bar * 16 + step, id, len, v });
const grid = (bar, id, pattern, v) => [...pattern].forEach((c, i) => {
if (c === 'x') hit(bar, i, id, 1, v);
if (c === 'o') hit(bar, i, id, 1, (v ?? vel(id)) * 0.5);
});
const line = (bar, notes) => notes.forEach(([step, id, len, v]) => hit(bar, step, id, len, v));
const section = (name, bars, fn) => {
sections.push({ name, from: cursor, to: cursor + bars });
for (let k = 0; k < bars; k++) fn(cursor + k, k);
cursor += bars;
};
const chaser = list => {
let turn = 0;
return (bar, pattern, v) => [...pattern].forEach((c, i) => {
if (c === '.') return;
const id = list[turn++ % list.length];
hit(bar, i, id, 1, c === 'o' ? (v ?? vel(id)) * 0.5 : v);
});
};
const ratchet = (bar, step, id, n, span, v0, v1) => {
for (let i = 0; i < n; i++) hit(bar, step + span * i / n, id, 1, v0 + (v1 - v0) * (n > 1 ? i / (n - 1) : 1));
};
const cycle = (bar, id, period, offset, v) => {
for (let st = 0; st < 16; st++) if ((bar * 16 + st - offset) % period === 0) hit(bar, st, id, 1, v);
};
const seeded = start => {
let seed = start;
const rng = () => {
seed = (seed + 0x6D2B79F5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
return { rng, pick: list => list[Math.floor(rng() * list.length)], chance: p => rng() < p };
};
const euclidPattern = (k, n) => Array.from({ length: n }, (_, i) => Math.floor((i + 1) * k / n) - Math.floor(i * k / n) === 1);
const turns = new Map();
const nextOf = list => { const i = (turns.get(list) ?? -1) + 1; turns.set(list, i); return list[i % list.length]; };
const euclid = (bar, ids, k, n, rot, v, lean = 0) => {
const pat = euclidPattern(k, n), list = Array.isArray(ids) ? ids : [ids];
for (let st = 0; st < 16; st++) {
if (pat[((bar * 16 + st + rot) % n + n) % n]) hit(bar, st + (st % 2 ? lean : 0), nextOf(list), 1, v);
}
};
const automaton = rng => {
let cells = Array(16).fill(0);
cells[8] = 1;
return {
evolve(r) {
cells = cells.map((_, i) => (r >> ((cells[(i + 15) % 16] << 2) | (cells[i] << 1) | cells[(i + 1) % 16])) & 1);
if (!cells.some(Boolean)) { cells = cells.map(() => (rng() < 0.2 ? 1 : 0)); cells[Math.floor(rng() * 16)] = 1; }
},
hits(bar, list, v, every = 1) {
cells.forEach((on, st) => {
if (on && st % every === 0) hit(bar, st, list[(Math.floor(st / 2) + bar) % list.length], 1, v * (0.6 + 0.4 * rng()));
});
},
};
};
return {
hit, grid, line, section, chaser, vel, ratchet, cycle, seeded, euclid, automaton,
done: () => ({ events: events.sort((a, b) => a.at - b.at), sections, bars: cursor }),
};
}
const SONGS = [
{
title: 'Skoodu', meta: 'octatonic on d, 172 bpm, generative half-time', bpm: 172, swing: 0, tail: 2.5,
room: { seconds: 1.8, shape: 3, wet: 0.15, tone: 0.45 },
kit: KIT_RULE30,
write({ hit, grid, line, section, ratchet, seeded, euclid, automaton }) {
const { rng, pick, chance } = seeded(30);
const ca = automaton(rng);
const CHIMES = ['chime.d4', 'chime.e♭4', 'chime.f4', 'chime.f♯4', 'chime.g♯4', 'chime.a4', 'chime.b4', 'chime.c5'];
let chimeTurn = 0;
const chimes = (b, period, stride, v, offset = 0) => {
for (let st = 0; st < 16; st++) if ((b * 16 + st - offset) % period === 0) hit(b, st, CHIMES[(chimeTurn++ * stride) % 8], 2, v);
};
const gene = [0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0];
const mutate = n => {
for (let i = 0; i < n; i++) { const j = 1 + Math.floor(rng() * 15); if (j !== 8) gene[j] ^= 1; }
};
const ghosts = (b, v) => gene.forEach((on, st) => { if (on) hit(b, st, 'snare.ghost', 1, v * (0.6 + 0.4 * rng())); });
const ROOTS = ['growl.d2', 'growl.f2', 'growl.g♯1', 'growl.b1'];
const PASS = { 'growl.d2': 'growl.e♭2', 'growl.f2': 'growl.e♭2', 'growl.g♯1': 'growl.a1', 'growl.b1': 'growl.a1' };
const GROWLS = ['......x...x.x...', '...x....x....x..', '......x..x....x.', '..x.....x.x.....'];
const bassBar = (b, k, v, turn = 0) => {
const root = ROOTS[(Math.floor(k / 2) + turn) % 4];
hit(b, 0, root, 6, v);
[...pick(GROWLS)].forEach((c, st) => { if (c === 'x') hit(b, st, chance(0.35) ? PASS[root] : root, 2, v); });
};
const pads = (b, k, v) => { if (k % 4 === 0) hit(b, 0, k % 8 === 0 ? 'cold.pad.d' : 'glass.pad', 24, v); };
const stabs = (b, k, v) => {
const id = k % 4 < 2 ? 'stab.dim.d' : 'stab.dim.e♭';
hit(b, 6, id, 1, v);
if (chance(0.4)) hit(b, 11, id, 1, v * 0.7);
};
const HATS = ['hat.fm1', 'hat.fm2', 'hat.noise'];
const METAL = ['clang.2', 'tine', 'rim.fm', 'click.sample'];
const TICKS = ['click.sample', 'tine'];
const half = (b, k, heat, rule = 30) => {
grid(b, 'kick.punch', pick(['x...............', 'x.........x.....', 'x......x........']));
hit(b, 8, 'snare.fm');
mutate(1 + Math.round(heat * 2));
ghosts(b, 0.5);
euclid(b, HATS, 5 + (k % 4), 16, k, 0.45);
ca.evolve(rule);
ca.hits(b, METAL, 0.45 * (0.5 + heat), heat > 0.6 ? 1 : 2);
if (k % 4 === 3) ratchet(b, pick([12, 14]), 'snare.crush', pick([4, 6]), 2, 0.3, 0.85);
};
const double = (b, k, heat, rule = 30) => {
grid(b, 'kick.punch', 'x.........x.....');
if (chance(0.5)) euclid(b, 'kick.fm', 2, 16, k * 5 + 3, 0.7);
grid(b, 'snare.fm', '....x.......x...');
if (heat > 0.6) hit(b, 12, 'clap.digital', 1, 0.6);
mutate(2);
ghosts(b, 0.45);
euclid(b, HATS, 9 + (k % 4), 16, k * 2, 0.45);
ca.evolve(rule);
ca.hits(b, METAL, 0.5 * (0.5 + heat), heat > 0.7 ? 1 : 2);
if (k % 4 === 3) ratchet(b, pick([12, 14]), 'snare.crush', pick([6, 8]), 2, 0.3, 0.95);
};
section('seed', 8, (b, k) => {
if (k === 0) hit(b, 0, 'glass.pad', 24, 0.8);
if (k === 4) hit(b, 0, 'cold.pad.d', 24, 0.8);
chimes(b, 11, 3, 0.5);
euclid(b, TICKS, 3, 13, k, 0.35);
if (k === 1) hit(b, 4, 'bit.rain', 12);
if (k === 3) hit(b, 8, 'gear');
if (k >= 4) {
grid(b, 'kick.sub', 'x...............', 0.7);
grid(b, 'snare.gate', '........x.......', 0.6);
euclid(b, HATS, 4, 12, k, 0.35);
}
if (k === 6) hit(b, 0, 'grain.cloud', 8);
if (k === 7) {
line(b, [[0,'data.burst',4], [10,'reverse.fm',6]]);
ratchet(b, 12, 'snare.crush', 8, 4, 0.3, 1);
}
});
section('halftime', 16, (b, k) => {
if (k === 0) line(b, [[0,'clang.big',8], [0,'kick.sub',4], [0,'crunch']]);
half(b, k, k < 8 ? 0.35 : 0.6);
bassBar(b, k);
pads(b, k, 0.5);
if (k < 8) chimes(b, 2, 3, 0.5); else { stabs(b, k, 0.7); chimes(b, 3, 5, 0.45); }
if (k === 4) hit(b, 0, 'formant.shift', 12);
if (k === 6 || k === 14) hit(b, 12, 'gear');
if (k === 8) hit(b, 0, 'hoover.dim', 8);
if (k === 10) hit(b, 8, 'data.burst', 4);
if (k === 12) hit(b, 0, 'sub.d2', 16);
if (k % 2 === 1) hit(b, 14, 'hat.ring', 1, 0.5);
if (k === 15) hit(b, 10, 'reverse.fm', 6);
});
section('cascade', 8, (b, k) => {
if (k % 2 === 0) line(b, [[0,'sub.d2',16,0.8], [0,'kick.sub',1,0.7]]);
if (k === 0) hit(b, 0, 'cold.pad.d', 24, 0.8);
if (k === 4) hit(b, 0, 'glass.pad', 24, 0.8);
hit(b, 8, 'snare.gate', 1, 0.5);
ca.evolve(30);
ca.hits(b, ['clang.2', 'tine', 'rim.fm', 'click.sample', 'gear', 'stutter'], 0.4);
euclid(b, HATS, 5, 13, k, 0.3);
chimes(b, 3, 5, 0.55);
if (k === 1) hit(b, 0, 'bit.rain', 12);
if (k === 3) hit(b, 4, 'grain.cloud', 8);
if (k === 5) hit(b, 0, 'formant.shift', 12);
if (k === 7) hit(b, 8, 'stutter', 4);
});
section('build', 4, (b, k) => {
grid(b, 'kick.punch', 'x...x...x...x...', 0.8);
euclid(b, 'snare.gate', [4, 6, 8, 12][k], 16, 0, 0.4 + 0.15 * k);
if (k === 0 || k === 2) hit(b, 0, 'growl.d2', 8, 0.8);
chimes(b, 4 - (k >> 1), 3, 0.5);
if (k === 1) hit(b, 0, 'hoover.dim', 8, 0.8);
if (k === 3) { ratchet(b, 12, 'snare.crush', 8, 4, 0.4, 1); hit(b, 10, 'reverse.fm', 6); }
});
section('doubletime', 16, (b, k) => {
const heat = 0.6 + 0.4 * k / 15;
if (k === 0) line(b, [[0,'clang.big',8], [0,'kick.sub',4], [0,'crunch']]);
if (k === 8) hit(b, 0, 'crunch');
double(b, k, heat);
bassBar(b, k);
pads(b, k, 0.45);
grid(b, 'ride.fm', 'x...x...x...x...', 0.4);
if (k < 8) { stabs(b, k, 0.7); chimes(b, 3, 5, 0.45); } else chimes(b, 2, 3, 0.5);
if (k === 4 || k === 12) hit(b, 0, 'hoover.dim', 8);
if (k === 2 || k === 10) hit(b, 4, 'zap.fm');
if (k % 4 === 1) hit(b, 10, 'buzz', 2);
if (k === 6 || k === 14) hit(b, 12, 'gear');
if (k === 9) hit(b, 8, 'data.burst', 4);
if (k % 2 === 1) hit(b, 14, 'hat.ring', 1, 0.5);
});
section('drift', 24, (b, k) => {
if (k % 8 === 0) hit(b, 0, 'cold.pad.d', 24, 0.7);
if (k % 8 === 4) hit(b, 0, 'glass.pad', 24, 0.75);
if (k % 4 === 0) hit(b, 0, 'sub.d2', 16, 0.6);
chimes(b, k < 12 ? 5 : 3, k < 12 ? 3 : 5, 0.5);
ca.evolve(90);
ca.hits(b, ['tine', 'click.sample', 'rim.fm'], 0.3, 2);
euclid(b, HATS, 3, 13, k, 0.25);
if (k % 6 === 2) hit(b, 0, 'bit.rain', 12, 0.6);
if (k === 4 || k === 16) hit(b, 0, 'hoover.dim', 8, 0.6);
if (k === 8 || k === 20) hit(b, 8, 'gear');
if (k === 10) hit(b, 0, 'formant.shift', 12);
if (k === 14) hit(b, 4, 'grain.cloud', 8);
if (k >= 16) { grid(b, 'kick.sub', 'x...............', 0.55); hit(b, 8, 'snare.gate', 1, 0.45); }
if (k === 23) { hit(b, 10, 'reverse.fm', 6); ratchet(b, 12, 'snare.crush', 6, 4, 0.3, 0.8); }
});
section('mutation', 24, (b, k) => {
if (k === 0) line(b, [[0,'clang.2'], [0,'kick.sub',4]]);
half(b, k, 0.45 + 0.35 * k / 23, k % 8 < 4 ? 30 : 110);
mutate(1);
bassBar(b, k, 1, 1);
pads(b, k, 0.45);
if (k % 8 < 4) chimes(b, 2, 5, 0.45); else { stabs(b, k, 0.65); chimes(b, 3, 7, 0.4); }
if (k % 8 === 6) hit(b, 12, 'gear');
if (k === 8 || k === 20) hit(b, 0, 'hoover.dim', 8);
if (k === 12) hit(b, 8, 'data.burst', 4);
if (k % 4 === 3) hit(b, 15, 'zap.fm', 1, 0.5);
if (k === 16) hit(b, 0, 'crunch');
if (k % 2 === 1) hit(b, 14, 'hat.ring', 1, 0.5);
});
section('lift', 8, (b, k) => {
grid(b, 'kick.punch', k < 4 ? 'x.......x.......' : 'x...x...x...x...', 0.8);
euclid(b, 'snare.gate', [2, 3, 4, 5, 6, 8, 10, 12][k], 16, 0, 0.35 + 0.08 * k);
if (k % 2 === 0) hit(b, 0, 'growl.d2', 8, 0.7);
chimes(b, 4 - Math.floor(k / 3), 3, 0.5);
euclid(b, HATS, 4 + k, 16, k, 0.35);
if (k === 2) hit(b, 0, 'bit.rain', 12, 0.6);
if (k === 4) hit(b, 0, 'hoover.dim', 8, 0.8);
if (k === 6) hit(b, 0, 'data.burst', 4);
if (k === 7) { ratchet(b, 8, 'snare.crush', 12, 8, 0.35, 1); hit(b, 10, 'reverse.fm', 6); }
});
section('doubletime.ii', 32, (b, k) => {
const heat = 0.65 + 0.35 * Math.min(1, k / 24);
if (k === 0 || k === 16) line(b, [[0,'clang.big',8], [0,'kick.sub',4], [0,'crunch']]);
if (k === 8 || k === 24) hit(b, 0, 'crunch');
double(b, k, heat, k % 8 < 4 ? 30 : 110);
bassBar(b, k, 1, k < 16 ? 1 : 2);
pads(b, k, 0.45);
grid(b, 'ride.fm', k < 16 ? 'x...x...x...x...' : 'x.x.x.x.x.x.x.x.', 0.35);
const phase = Math.floor(k / 8);
if (phase === 0) chimes(b, 2, 3, 0.5);
if (phase === 1) { stabs(b, k, 0.7); chimes(b, 3, 5, 0.45); }
if (phase === 2) chimes(b, 2, 7, 0.5);
if (phase === 3) { stabs(b, k, 0.75); chimes(b, 2, 5, 0.5); }
if (k % 8 === 4) hit(b, 0, 'hoover.dim', 8);
if (k % 4 === 1) hit(b, 10, 'buzz', 2);
if (k % 8 === 2) hit(b, 4, 'zap.fm');
if (k % 8 === 6) hit(b, 12, 'gear');
if (k === 12 || k === 28) hit(b, 0, 'formant.shift', 12);
if (k === 20) hit(b, 8, 'data.burst', 4);
if (k % 2 === 1) hit(b, 14, 'hat.ring', 1, 0.5);
if (k === 31) hit(b, 10, 'reverse.fm', 6);
});
section('cascade.ii', 16, (b, k) => {
if (k % 2 === 0) line(b, [[0,'sub.d2',16,0.75], [0,'kick.sub',1,0.7]]);
if (k % 8 === 0) hit(b, 0, k === 0 ? 'glass.pad' : 'cold.pad.d', 24, 0.8);
hit(b, 8, 'snare.gate', 1, 0.5);
ca.evolve(k % 2 ? 90 : 30);
ca.hits(b, ['clang.2', 'tine', 'rim.fm', 'click.sample', 'gear', 'stutter'], 0.4);
euclid(b, HATS, 5 + (k % 3), 13, k, 0.3);
chimes(b, 3, k < 8 ? 5 : 7, 0.5);
if (k >= 8) bassBar(b, k, 0.6, 2);
if (k === 3) hit(b, 0, 'bit.rain', 12);
if (k === 6) hit(b, 0, 'formant.shift', 12);
if (k === 10) hit(b, 4, 'grain.cloud', 8);
if (k === 12) hit(b, 0, 'hoover.dim', 8, 0.7);
if (k === 15) { hit(b, 8, 'stutter', 4); ratchet(b, 12, 'snare.crush', 8, 4, 0.4, 1); }
});
section('gap', 1, b => {
line(b, [[0,'stutter',4,0.6], [8,'reverse.fm',6], [8,'data.burst',4,0.5]]);
});
section('final.run', 24, (b, k) => {
const heat = k < 20 ? 1 : 1 - (k - 19) * 0.15;
if (k === 0) line(b, [[0,'clang.big',8], [0,'kick.sub',4], [0,'crunch'], [0,'hoover.dim',8]]);
if (k === 12) hit(b, 0, 'crunch');
double(b, k, heat, 30);
bassBar(b, k);
pads(b, k, 0.5);
grid(b, 'ride.fm', 'x.x.x.x.x.x.x.x.', 0.35);
if (k < 8) { stabs(b, k, 0.75); chimes(b, 2, 3, 0.5); }
else if (k < 16) chimes(b, 2, 5, 0.55);
else { stabs(b, k, 0.6); chimes(b, 2, 7, 0.5); }
if (k % 8 === 4) hit(b, 0, 'hoover.dim', 8);
if (k % 4 === 1) hit(b, 10, 'buzz', 2);
if (k % 4 === 2) hit(b, 4, 'zap.fm');
if (k % 8 === 6) hit(b, 12, 'gear');
if (k === 10) hit(b, 8, 'data.burst', 4);
if (k === 18) hit(b, 0, 'formant.shift', 12);
if (k % 2 === 1) hit(b, 14, 'hat.ring', 1, 0.5);
if (k === 23) hit(b, 10, 'reverse.fm', 6);
});
section('decay', 8, (b, k) => {
if (k < 4) { half(b, k, 0.35 - k * 0.07); bassBar(b, k, 0.8); }
if (k === 0) hit(b, 0, 'cold.pad.d', 24, 0.7);
if (k === 4) hit(b, 0, 'glass.pad', 24, 0.7);
if (k >= 4) {
chimes(b, 4 + (k - 4), 3, 0.5 - (k - 4) * 0.06);
euclid(b, TICKS, 3, 11, k, 0.35);
}
if (k === 5) hit(b, 0, 'bit.rain', 12, 0.6);
if (k === 7) line(b, [[0,'gear',1,0.7], [8,'chime.d4',8,0.6]]);
});
},
},
];
SONGS.forEach(song => {
song.velOf = {};
for (const k of [1, 2, 3]) song.kit[k].forEach(([id, , opts = {}]) => { song.velOf[id] = opts.vel ?? 1; });
const w = makeWriter(song.velOf);
song.write(w);
Object.assign(song, w.done());
song.step = 60 / song.bpm / 4;
song.barLen = song.step * 16;
song.length = song.bars * song.barLen;
});
let cur = SONGS[0];
const timeOf = (song, at) => (at + (Number.isInteger(at) && at % 2 === 1 ? song.swing : 0)) * song.step;
const N = 7, MID = 3;
const CELL = 64, GAP = 8, PITCH = CELL + GAP, HALF = CELL / 2;
const GRID_HALF = (N * PITCH - GAP) / 2;
const SHEAR_MAX = 0.82 * CELL;
const FOCAL = 1000;
const WAVE_SPEED = 1100;
const BREAK_FORCE = 165;
const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)').matches;
const touchy = matchMedia('(hover: none)').matches;
const MOTION = reduceMotion ? 0.3 : 1;
const NS = 'http://www.w3.org/2000/svg';
const $ = id => document.getElementById(id);
function svgEl(tag, attrs, parent) {
const n = document.createElementNS(NS, tag);
for (const k in attrs) n.setAttribute(k, attrs[k]);
if (parent) parent.appendChild(n);
return n;
}
function setRect(el, x, y, w, h) {
el.setAttribute('x', x.toFixed(1)); el.setAttribute('y', y.toFixed(1));
el.setAttribute('width', w.toFixed(1)); el.setAttribute('height', h.toFixed(1));
}
const rand = (a, b) => a + Math.random() * (b - a);
const sign = () => (Math.random() < 0.5 ? -1 : 1);
function ringCells(k) {
const cells = [], lo = MID - k, hi = MID + k;
for (let c = lo; c <= hi; c++) cells.push([lo, c]);
for (let r = lo + 1; r <= hi; r++) cells.push([r, hi]);
for (let c = hi - 1; c >= lo; c--) cells.push([hi, c]);
for (let r = hi - 1; r > lo; r--) cells.push([r, lo]);
return cells;
}
const stageEl = $('stage');
const ghostsG = $('ghosts'), marksG = $('marks'), tilesG = $('tiles'), playG = $('play'), hitsG = $('hits');
const leadsG = $('leads'), calloutsEl = $('callouts');
const tiles = [];
const TILE = {};
const ringOrder = { 1: [], 2: [], 3: [] };
for (let k = 1; k <= 3; k++) {
ringCells(k).forEach(([r, c]) => {
const t = {
id: '', voice: null, vel: 1, hitDef: null,
r, c, ring: k,
hx: (c - MID) * PITCH, hy: (r - MID) * PITCH,
ghost: svgEl('rect', { class: 'ghost' }, ghostsG),
poly: svgEl('polygon', { class: 'tile' }, tilesG),
hit: svgEl('rect', {
class: 'hit', tabindex: 0, role: 'button', 'data-tile': tiles.length,
}, hitsG),
dx: 0, dy: 0, z: 0, vx: 0, vy: 0, vz: 0,
rx: 0, ry: 0, rz: 0, wx: 0, wy: 0, wz: 0,
shear: 0, vs: 0, amp: 0, ink: 0,
loose: false, looseSince: 0, recallUntil: 0,
manual: false, keyUntil: 0, songUntil: -1, lastSound: 0,
sc: 0, vsc: 0, sq: 0, vsq: 0, jit: 0, fillv: 0, fillTau: 0.25, look: ['shear'],
resting: true, pts: [[0, 0], [0, 0], [0, 0], [0, 0]],
glow: 0, shown: false, lx: 0, ly: 0, tx: 0, ty: 0, w: 0, side: '', row: null,
note: Object.assign(document.createElement('p'), { className: 'callout' }),
line: svgEl('line', { class: 'lead' }, leadsG),
};
calloutsEl.appendChild(t.note);
tiles.push(t);
ringOrder[k].push(t);
});
}
function applyKit(song) {
for (const k of [1, 2, 3]) ringOrder[k].forEach((t, i) => {
const [id, voice, opts = {}] = song.kit[k][i];
Object.assign(t, { id, voice, vel: opts.vel ?? 1, hitDef: opts.hit || null, look: opts.look || ['shear'] });
t.note.textContent = id;
t.hit.setAttribute('aria-label', `Play ${id}`);
});
for (const key in TILE) delete TILE[key];
for (const t of tiles) TILE[t.id] = t;
}
applyKit(cur);
const tileAtCell = (r, c) => tiles.find(t => t.r === r && t.c === c);
const playBase = svgEl('rect', { class: 'play-base' }, playG);
const playTrace = svgEl('rect', { class: 'play-trace' }, playG);
const playWord = svgEl('text', { class: 'play-word' }, playG);
playWord.textContent = 'play';
const playIcon = svgEl('path', { class: 'play-icon' }, playG);
const playHit = svgEl('rect', {
class: 'hit', tabindex: 0, role: 'button', 'data-play': '1',
}, hitsG);
const waves = [];
function emitWave(w) {
if (reduceMotion) return;
w.t0 = performance.now() / 1000;
waves.push(w);
wake();
}
function applyWaves(nowS, prevS, nowMs) {
for (let i = waves.length - 1; i >= 0; i--) {
const w = waves[i];
const r0 = (prevS - w.t0) * WAVE_SPEED, r1 = (nowS - w.t0) * WAVE_SPEED;
for (const t of tiles) {
if (t === w.src) continue;
let d, ux, uy;
if (w.plane) {
d = (t.hx - w.x) * w.plane[0] + (t.hy - w.y) * w.plane[1];
ux = w.plane[0]; uy = w.plane[1];
} else {
const ex = t.hx - w.x, ey = t.hy - w.y;
d = Math.hypot(ex, ey);
if (d < 1) continue;
ux = ex / d; uy = ey / d;
}
if (d <= r0 || d > r1) continue;
if (w.scatter) { const a = rand(0, Math.PI * 2); ux = Math.cos(a); uy = Math.sin(a); }
if (w.swirl) { const sx = -uy * Math.sign(w.swirl), sy = ux * Math.sign(w.swirl); ux = sx; uy = sy; }
const imp = w.push * (w.plane ? 1 : Math.exp(-d / w.reach));
t.vx += ux * imp; t.vy += uy * imp;
t.wy += ux * imp * 0.01; t.wx -= uy * imp * 0.01;
t.vs += imp * 0.3;
if (w.lift) t.vz += w.lift * rand(0.5, 1);
if (w.spin) { t.wy += w.spin; t.wx += w.spin * 0.35; }
if (w.twirl) t.wz += w.twirl * (w.plane ? 1 : Math.exp(-d / w.reach));
if (!t.loose && Math.abs(imp) > BREAK_FORCE) breakLoose(t, Math.abs(imp), ux, uy, nowMs);
t.resting = false;
}
if (r0 > 1000) waves.splice(i, 1);
}
}
function breakLoose(t, force, ux, uy, nowMs) {
t.loose = true;
t.looseSince = nowMs;
t.vx += ux * force * 0.4; t.vy += uy * force * 0.4;
t.vz += force * rand(0.3, 0.8);
t.wx += sign() * force * rand(0.01, 0.025);
t.wy += sign() * force * rand(0.01, 0.025);
t.wz += sign() * force * rand(0.003, 0.008);
}
const LOOKS = {
shear: (t, g, k) => { t.amp = SHEAR_MAX * g * k * MOTION; t.vs += t.amp * 12; },
pulse: (t, g, k) => { t.vsc += 4.5 * g * k * MOTION; },
shrink: (t, g, k) => { t.vsc -= 4 * g * k * MOTION; },
squash: (t, g, k) => { t.vsq += 6.5 * g * k * MOTION; },
flip: (t, g, k) => { t.wy += 15 * g * k * MOTION * sign(); },
fold: (t, g, k) => { t.wx += 7 * g * k * MOTION * sign(); },
spin: (t, g, k) => { t.wz += 11 * g * k * MOTION * sign(); },
jitter: (t, g, k) => { if (!reduceMotion) t.jit = Math.max(t.jit, 5 * g * k); },
fill: (t, g, k, size) => {
t.fillv = Math.max(t.fillv, Math.min(0.9, 0.7 * g * k));
t.fillTau = size === 'long' ? 0.9 : 0.25;
},
breathe: (t, g) => { t.wx += 2.5 * sign() * MOTION; t.fillv = Math.max(t.fillv, 0.22 * g); t.fillTau = 1.6; },
ring: (t, g, k) => spawnRing(t, 0, k, g),
echo: (t, g) => { spawnRing(t, 0, 1, g); spawnRing(t, 3 * cur.step * 1000, 1, g * 0.7); },
};
function strike(t, gain) {
const g = Math.min(1, Math.max(0.35, gain));
t.amp = 0;
t.ink = 1;
t.resting = false;
tilesG.appendChild(t.poly);
for (const look of t.look) {
const [name, size] = look.split('-');
const k = size === 'small' ? 0.5 : size === 'big' ? 1.6 : 1;
(LOOKS[name] || LOOKS.shear)(t, g, k, size);
}
const h = t.hitDef;
if (h) {
const k = gain / t.vel;
if (h.plane) {
emitWave({ plane: h.plane, x: -h.plane[0] * 320, y: -h.plane[1] * 320, push: h.push * k, lift: h.lift });
} else {
emitWave({ x: h.centre ? 0 : t.hx, y: h.centre ? 0 : t.hy, push: h.push * k, reach: h.reach || 420, lift: h.lift,
scatter: h.scatter, swirl: h.swirl, spin: h.spin, twirl: h.twirl, src: h.centre ? null : t });
}
}
wake();
}
const ringsG = $('rings');
const ringPool = [], rings = [];
function spawnRing(t, delayMs, k, g) {
if (rings.length > 60) return;
const el = ringPool.pop() || svgEl('polygon', { class: 'ring' }, ringsG);
el.style.display = 'none';
rings.push({
el, cx: (t.pts[0][0] + t.pts[2][0]) / 2, cy: (t.pts[0][1] + t.pts[2][1]) / 2, rz: t.rz,
start: performance.now() + delayMs, life: 520 * (0.7 + 0.3 * k), grow: 1.4 * k, peak: 0.55 * g, half: HALF * S,
});
wake();
}
function stepRings(nowMs) {
for (let i = rings.length - 1; i >= 0; i--) {
const r = rings[i], p = (nowMs - r.start) / r.life;
if (p < 0) continue;
if (p >= 1) { r.el.style.display = 'none'; ringPool.push(r.el); rings.splice(i, 1); continue; }
const h = r.half * (1 + r.grow * (1 - (1 - p) * (1 - p)));
const c = Math.cos(r.rz), sn = Math.sin(r.rz);
r.el.setAttribute('points', CORNERS.map(([x, y]) => {
const lx = x / HALF * h, ly = y / HALF * h;
return `${(r.cx + lx * c - ly * sn).toFixed(1)},${(r.cy + lx * sn + ly * c).toFixed(1)}`;
}).join(' '));
r.el.style.display = '';
r.el.style.opacity = (r.peak * (1 - p)).toFixed(3);
}
return rings.length > 0;
}
const COOLDOWN = 90;
function soundTile(t) {
const now = performance.now();
if (now - t.lastSound < COOLDOWN) return;
t.lastSound = now;
playSound(t.id);
}
let S = 1, CX = 0, CY = 0, wide = true, playPerimeter = 4 * CELL;
const CORNERS = [[-HALF, -HALF], [HALF, -HALF], [HALF, HALF], [-HALF, HALF]];
function drawTile(t) {
const cz = Math.cos(t.rz), sz = Math.sin(t.rz);
const cxr = Math.cos(t.rx), sxr = Math.sin(t.rx);
const cyr = Math.cos(t.ry), syr = Math.sin(t.ry);
const sx = 1 + t.sc + t.sq * 0.6, sy = 1 + t.sc - t.sq;
const jx = t.jit ? (Math.random() * 2 - 1) * t.jit : 0, jy = t.jit ? (Math.random() * 2 - 1) * t.jit : 0;
let attr = '';
for (let i = 0; i < 4; i++) {
const lx = CORNERS[i][0] * sx, ly = CORNERS[i][1] * sy;
const x = lx + t.shear * (ly / CELL), y = ly;
const x1 = x * cz - y * sz, y1 = x * sz + y * cz;
const y2 = y1 * cxr, z2 = y1 * sxr;
const x3 = x1 * cyr + z2 * syr, z3 = -x1 * syr + z2 * cyr;
const wx = t.hx + t.dx + jx + x3, wy = t.hy + t.dy + jy + y2, wz = t.z + z3;
const p = FOCAL / Math.max(150, FOCAL - wz);
const X = CX + wx * p * S, Y = CY + wy * p * S;
t.pts[i][0] = X; t.pts[i][1] = Y;
attr += `${X.toFixed(1)},${Y.toFixed(1)} `;
}
t.poly.setAttribute('points', attr);
const c = Math.round(255 - 235 * t.ink);
t.poly.style.stroke = `rgb(${c},${c},${c})`;
t.poly.style.strokeWidth = (1.5 + 0.6 * t.ink).toFixed(2);
t.poly.style.fill = t.fillv > 0.01 ? `rgba(20, 20, 20, ${(t.fillv * 0.85).toFixed(3)})` : 'none';
const disp = Math.hypot(t.dx, t.dy) + Math.abs(t.z) * 0.3 + (Math.abs(t.rx) + Math.abs(t.ry) + Math.abs(t.rz)) * 30;
t.ghost.style.opacity = Math.min(0.75, Math.max(0, (disp - 8) / 45)).toFixed(2);
}
const transportEl = $('transport');
const statusMain = $('statusMain'), statusSub = $('statusSub');
const hintTiles = $('hintTiles');
const SLOT = 19;
const geo = { left: 0, right: 0, top: { left: 0, right: 0 }, bottom: 0, gridTop: 0, gridBottom: 0, minX: 0, maxX: 0, topRows: 3 };
function idleSoundText() {
if (!audioReady) return touchy ? 'tap.once.to.wake' : 'click.once.then.hover';
return touchy ? 'slide.across.tiles' : 'hover.any.tile';
}
function setLine(line, x1, y1, x2, y2) {
line.setAttribute('x1', x1.toFixed(1)); line.setAttribute('y1', y1.toFixed(1));
line.setAttribute('x2', x2.toFixed(1)); line.setAttribute('y2', y2.toFixed(1));
}
function placeNote(el, x, y, align) {
el.classList.toggle('right', align === 'right');
el.classList.toggle('center', align === 'center');
el.style.top = `${y}px`;
if (align === 'right') { el.style.right = `${window.innerWidth - x}px`; el.style.left = 'auto'; }
else { el.style.left = `${x}px`; el.style.right = 'auto'; }
}
const centreX = t => (t.pts[0][0] + t.pts[1][0] + t.pts[2][0] + t.pts[3][0]) / 4;
const centreY = t => (t.pts[0][1] + t.pts[1][1] + t.pts[2][1] + t.pts[3][1]) / 4;
function anchorOn(t, ax, ay) {
let best = t.pts[0], bd = Infinity;
for (let i = 0; i < 4; i++) {
const a = t.pts[i], b = t.pts[(i + 1) % 4];
for (const p of [a, [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2]]) {
const d = (p[0] - ax) ** 2 + (p[1] - ay) ** 2;
if (d < bd) { bd = d; best = p; }
}
}
return best;
}
function placeColumn(list, side) {
const top = geo.top[side];
list.forEach(t => { t.want = Math.min(geo.bottom, Math.max(top, centreY(t))); });
list.sort((a, b) => (a.shown ? a.ly : a.want) - (b.shown ? b.ly : b.want));
let y = -Infinity;
for (const t of list) { t.ty = Math.max(t.want, y + SLOT); y = t.ty; }
let limit = geo.bottom;
for (let i = list.length - 1; i >= 0; i--) { list[i].ty = Math.min(list[i].ty, limit); limit = list[i].ty - SLOT; }
for (const t of list) t.tx = Math.max(4, Math.min(window.innerWidth - 4 - t.w, side === 'left' ? geo.left - t.w : geo.right));
}
function packRow(row) {
let cursor = geo.minX;
for (const t of row) { t.tx = Math.max(t.want - t.w / 2, cursor); cursor = t.tx + t.w + 10; }
let limit = geo.maxX;
for (let i = row.length - 1; i >= 0; i--) { row[i].tx = Math.min(row[i].tx, limit - row[i].w); limit = row[i].tx - 10; }
let floor = geo.minX;
for (const t of row) { t.tx = Math.max(t.tx, floor); floor = t.tx + t.w + 10; }
}
function placeRows(list, side) {
list.forEach(t => { t.want = centreX(t); });
const rows = [[], [], []];
const room = geo.maxX - geo.minX;
const used = r => rows[r].reduce((sum, t) => sum + t.w + 10, 0);
for (const t of list) if (t.shown && t.row != null) rows[t.row].push(t);
for (const t of list) {
if (t.shown && t.row != null) continue;
const lastRow = (side === 'top' ? geo.topRows : 3) - 1;
let r = 0;
while (r < lastRow && used(r) + t.w + 10 > room) r++;
t.row = r;
rows[r].push(t);
}
rows.forEach((row, r) => {
row.sort((a, b) => (a.shown ? a.lx + a.w / 2 : a.want) - (b.shown ? b.lx + b.w / 2 : b.want));
packRow(row);
const y = side === 'top' ? geo.gridTop - 24 - r * 20 : geo.gridBottom + 24 + r * 20;
row.forEach(t => { t.ty = y; });
});
}
function drawCallout(t) {
t.note.style.transform = `translate(${t.lx.toFixed(1)}px, ${t.ly.toFixed(1)}px)`;
const o = Math.min(1, t.glow * 1.6);
t.note.style.opacity = o.toFixed(2);
let ex, ey;
if (t.side === 'left') { ex = t.lx + t.w + 8; ey = t.ly; }
else if (t.side === 'right') { ex = t.lx - 8; ey = t.ly; }
else if (t.side === 'top') { ex = t.lx + t.w / 2; ey = t.ly + 10; }
else { ex = t.lx + t.w / 2; ey = t.ly - 11; }
const [sx, sy] = anchorOn(t, ex, ey);
setLine(t.line, sx, sy, ex, ey);
t.line.style.opacity = (0.55 * o).toFixed(2);
}
function stepCallouts(dt) {
const k = 1 - Math.exp(-dt / 0.03);
const groups = {};
for (const t of tiles) {
if (t.glow > 0.03) (groups[t.side] ||= []).push(t);
else if (t.shown) {
t.shown = false;
t.row = null;
t.note.style.visibility = 'hidden';
t.line.style.visibility = 'hidden';
}
}
let moving = false;
for (const side in groups) {
const list = groups[side];
if (wide) placeColumn(list, side); else placeRows(list, side);
for (const t of list) {
if (!t.shown) {
t.shown = true;
t.lx = t.tx; t.ly = t.ty;
t.note.style.visibility = 'visible';
t.line.style.visibility = 'visible';
} else {
t.lx += (t.tx - t.lx) * k;
t.ly += (t.ty - t.ly) * k;
}
if (Math.abs(t.tx - t.lx) > 0.3 || Math.abs(t.ty - t.ly) > 0.3) moving = true;
drawCallout(t);
}
}
return moving;
}
function measureCallouts() {
for (const t of tiles) t.w = t.note.offsetWidth;
}
let rafId = null, lastFrame = 0, lastWaveTime = 0;
const visualQueue = [];
function wake() {
if (rafId) return;
lastFrame = performance.now();
lastWaveTime = lastFrame / 1000;
rafId = requestAnimationFrame(frame);
}
function spring(t, p, v, w, z, h) {
t[v] += (-w * w * t[p] - 2 * z * w * t[v]) * h;
t[p] += t[v] * h;
}
function stepTile(t, dt, audioNow, nowMs) {
const held = t.manual || nowMs < t.keyUntil || audioNow < t.songUntil;
if (t.resting && !held) return false;
if (t.loose && nowMs - t.looseSince > 700) {
const near = Math.hypot(t.dx, t.dy) < 10 && Math.abs(t.z) < 12 && Math.hypot(t.vx, t.vy) < 40
&& Math.abs(t.rx) + Math.abs(t.ry) + Math.abs(t.rz) < 0.25;
const tooLong = nowMs - t.looseSince > 9000;
if (near || tooLong) { t.loose = false; if (tooLong) t.recallUntil = nowMs + 900; }
}
const recalling = nowMs < t.recallUntil;
const pw = t.loose ? 1.8 : recalling ? 6 : 13, pz = t.loose ? 0.35 : recalling ? 0.8 : 0.32;
const aw = t.loose ? 1.3 : recalling ? 5 : 11, az = t.loose ? 0.35 : recalling ? 0.8 : 0.45;
const sw = held ? 38 : 15, sz = held ? 0.62 : 0.4;
const n = Math.max(1, Math.ceil(dt * 240)), h = dt / n;
for (let i = 0; i < n; i++) {
spring(t, 'dx', 'vx', pw, pz, h);
spring(t, 'dy', 'vy', pw, pz, h);
spring(t, 'z', 'vz', pw, pz, h);
spring(t, 'rx', 'wx', aw, az, h);
spring(t, 'ry', 'wy', aw, az, h);
spring(t, 'rz', 'wz', aw, az, h);
spring(t, 'sc', 'vsc', 16, 0.28, h);
spring(t, 'sq', 'vsq', 20, 0.3, h);
const target = held ? t.amp : 0;
t.vs += (sw * sw * (target - t.shear) - 2 * sz * sw * t.vs) * h;
t.shear += t.vs * h;
}
t.ink = held ? 1 : t.ink * Math.exp(-dt / 0.09);
t.glow = held ? 1 : t.glow * Math.exp(-dt / 0.22);
t.jit *= Math.exp(-dt / 0.12);
t.fillv *= Math.exp(-dt / t.fillTau);
if (!held && !t.loose && !recalling && t.glow < 0.03
&& Math.abs(t.dx) < 0.05 && Math.abs(t.dy) < 0.05 && Math.abs(t.z) < 0.05
&& Math.abs(t.vx) < 0.5 && Math.abs(t.vy) < 0.5 && Math.abs(t.vz) < 0.5
&& Math.abs(t.rx) < 5e-4 && Math.abs(t.ry) < 5e-4 && Math.abs(t.rz) < 5e-4
&& Math.abs(t.wx) < 5e-3 && Math.abs(t.wy) < 5e-3 && Math.abs(t.wz) < 5e-3
&& Math.abs(t.shear) < 0.05 && Math.abs(t.vs) < 0.5 && t.ink < 0.01
&& Math.abs(t.sc) < 0.002 && Math.abs(t.vsc) < 0.02 && Math.abs(t.sq) < 0.002 && Math.abs(t.vsq) < 0.02
&& t.jit < 0.05 && t.fillv < 0.01) {
t.dx = t.dy = t.z = t.vx = t.vy = t.vz = 0;
t.rx = t.ry = t.rz = t.wx = t.wy = t.wz = 0;
t.shear = t.vs = t.ink = t.glow = 0;
t.sc = t.vsc = t.sq = t.vsq = t.jit = t.fillv = 0;
t.resting = true;
} else {
t.resting = false;
}
drawTile(t);
return !t.resting;
}
function frame(nowMs) {
const dt = Math.min(0.05, Math.max(0.001, (nowMs - lastFrame) / 1000));
lastFrame = nowMs;
const nowS = nowMs / 1000;
const audioNow = audioCtx ? audioCtx.currentTime - outputLatency(audioCtx) : 0;
while (visualQueue.length && visualQueue[0].t <= audioNow) {
const v = visualQueue.shift();
if (audioNow > v.until) continue;
v.tile.songUntil = v.until;
strike(v.tile, v.gain);
}
applyWaves(nowS, lastWaveTime, nowMs);
lastWaveTime = nowS;
let busy = waves.length > 0;
for (const t of tiles) busy = stepTile(t, dt, audioNow, nowMs) || busy;
busy = stepRings(nowMs) || busy;
busy = stepCallouts(dt) || busy;
if (player.playing) { updateReadout(audioNow); busy = true; }
if (visualQueue.length) busy = true;
rafId = busy ? requestAnimationFrame(frame) : null;
}
let manualTile = null;
let pressing = false;
function tileAt(clientX, clientY) {
const el = document.elementFromPoint(clientX, clientY);
const idx = el && el.getAttribute && el.getAttribute('data-tile');
return idx != null ? tiles[+idx] : null;
}
function playByHand(t) {
strike(t, t.vel);
soundTile(t);
}
function setManual(t) {
if (t === manualTile) return;
if (manualTile) manualTile.manual = false;
manualTile = t;
if (t) { t.manual = true; playByHand(t); }
wake();
}
function track(e) {
if (e.pointerType === 'mouse' || pressing) setManual(tileAt(e.clientX, e.clientY));
}
stageEl.addEventListener('pointerdown', e => {
unlockAudio();
if (e.pointerType !== 'mouse') {
pressing = true;
if (e.target.hasPointerCapture && e.target.hasPointerCapture(e.pointerId)) {
e.target.releasePointerCapture(e.pointerId);
}
}
track(e);
});
stageEl.addEventListener('pointermove', track);
['pointerup', 'pointercancel'].forEach(type => stageEl.addEventListener(type, e => {
if (e.pointerType !== 'mouse') { pressing = false; setManual(null); }
}));
stageEl.addEventListener('pointerleave', () => { pressing = false; setManual(null); });
hitsG.addEventListener('keydown', e => {
if (e.key !== 'Enter' && e.key !== ' ') return;
const idx = e.target.getAttribute('data-tile');
if (idx == null) return;
e.preventDefault();
const t = tiles[+idx];
t.keyUntil = performance.now() + 220;
playByHand(t);
});
const soundBtn = $('soundBtn'), soundLabel = $('soundLabel');
let wakingPress = false;
function refreshSoundStatus() {
soundLabel.textContent = !audioReady ? (touchy ? 'tap.to.wake.audio' : 'click.to.wake.audio') : muted ? 'sound.off' : 'sound.on';
soundBtn.classList.toggle('on', audioReady && !muted);
soundBtn.setAttribute('aria-pressed', String(audioReady && !muted));
}
let silentClip = null;
function startSilentClip() {
try {
if (!silentClip) {
silentClip = new Audio('data:audio/wav;base64,UklGRkQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YSAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgA==');
silentClip.loop = true;
silentClip.setAttribute('playsinline', '');
}
const p = silentClip.play();
if (p && p.catch) p.catch(() => {});
} catch (e) { }
}
function unlockAudio() {
if (audioReady) return;
const ctx = getCtx();
getMaster();
if (ctx.state === 'suspended') ctx.resume();
startSilentClip();
audioReady = true;
refreshSoundStatus();
hintTiles.textContent = idleSoundText();
}
['pointerdown', 'touchstart', 'keydown'].forEach(evt =>
document.addEventListener(evt, unlockAudio, { passive: true })
);
['pointerdown', 'keydown'].forEach(evt => soundBtn.addEventListener(evt, () => { wakingPress = !audioReady; }));
soundBtn.addEventListener('click', () => {
if (wakingPress) { wakingPress = false; return; }
muted = !muted;
getMaster._out.gain.setTargetAtTime(muted ? 0 : MASTER_LEVEL, getCtx().currentTime, 0.02);
refreshSoundStatus();
});
const hintSpace = $('hintSpace');
const player = { playing: false, starting: false, startTime: 0, endTime: 0, idx: 0, bus: null, timer: null };
const fmt = s => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;
function outputLatency(ctx) {
return Math.min(0.2, (ctx.outputLatency || 0) + (ctx.baseLatency || 0));
}
function scheduleAhead() {
const ctx = getCtx();
const horizon = ctx.currentTime + (document.hidden ? 1.5 : 0.15);
while (player.idx < cur.events.length) {
const ev = cur.events[player.idx];
const t = player.startTime + timeOf(cur, ev.at);
if (t > horizon) break;
player.idx++;
const tile = TILE[ev.id];
const gain = ev.v ?? tile.vel;
const out = ctx.createGain();
out.gain.value = gain;
out.connect(player.bus);
tile.voice(ctx, out, t);
visualQueue.push({ t, tile, gain, until: t + Math.max(0.11, ev.len * cur.step - 0.03) });
}
if (player.idx >= cur.events.length && ctx.currentTime >= player.endTime) finish();
}
let lastReadout = '';
function updateReadout(audioNow) {
const elapsed = Math.min(cur.length, Math.max(0, audioNow - player.startTime));
const bar = Math.min(cur.bars - 1, Math.floor(elapsed / cur.barLen));
const sec = cur.sections.find(s => bar >= s.from && bar < s.to);
const text = `${sec.name}|${fmt(elapsed)} / ${fmt(cur.length)}`;
if (text !== lastReadout) {
lastReadout = text;
statusMain.textContent = cur.title;
statusSub.textContent = `${sec.name} ${fmt(elapsed)} / ${fmt(cur.length)}`;
}
playTrace.style.strokeDasharray = `${(elapsed / cur.length * playPerimeter).toFixed(2)} ${playPerimeter.toFixed(2)}`;
}
function drawPlayIcon() {
const r = Math.max(3, HALF * S * 0.32), on = stageEl.classList.contains('playing');
playIcon.setAttribute('d', on
? `M${CX - r * 0.8} ${CY - r * 0.8}h${r * 1.6}v${r * 1.6}h${-r * 1.6}z`
: `M${CX - r * 0.7} ${CY - r}L${CX + r} ${CY}L${CX - r * 0.7} ${CY + r}z`);
}
function setPlayingUI(on) {
stageEl.classList.toggle('playing', on);
playWord.textContent = on ? 'stop' : 'play';
drawPlayIcon();
playHit.setAttribute('aria-label', on ? `Stop ${cur.title}` : `Play ${cur.title}`);
hintSpace.textContent = on ? 'press.space.to.stop' : 'press.space.to.play';
if (!on) {
statusMain.textContent = cur.title;
statusSub.textContent = `${cur.bpm} bpm, ${fmt(cur.length)}`;
playTrace.style.strokeDasharray = '';
lastReadout = '';
}
}
async function play() {
if (player.playing || player.starting) return;
player.starting = true;
unlockAudio();
const ctx = getCtx();
try { if (ctx.state !== 'running') await ctx.resume(); } catch (e) { }
player.starting = false;
player.bus = ctx.createGain();
player.bus.gain.value = 0.9;
player.bus.connect(roomFor(cur));
player.startTime = ctx.currentTime + 0.12;
player.endTime = player.startTime + cur.length + cur.tail;
player.idx = 0;
player.playing = true;
holdScreen(true);
setPlayingUI(true);
scheduleAhead();
player.timer = setInterval(scheduleAhead, 25);
wake();
}
let wakeLock = null;
async function holdScreen(on) {
try {
if (on && !wakeLock && 'wakeLock' in navigator) {
wakeLock = await navigator.wakeLock.request('screen');
wakeLock.addEventListener('release', () => { wakeLock = null; });
} else if (!on && wakeLock) {
await wakeLock.release();
wakeLock = null;
}
} catch (e) { wakeLock = null; }
}
document.addEventListener('visibilitychange', () => {
if (document.hidden) { if (silentClip) silentClip.pause(); return; }
if (audioReady) {
startSilentClip();
if (audioCtx && audioCtx.state !== 'running') audioCtx.resume();
}
if (player.playing) holdScreen(true);
});
function halt() {
holdScreen(false);
clearInterval(player.timer);
player.timer = null;
player.playing = false;
}
function stop() {
if (!player.playing) return;
halt();
const bus = player.bus;
bus.gain.setTargetAtTime(0, getCtx().currentTime, 0.02);
setTimeout(() => bus.disconnect(), 400);
visualQueue.length = 0;
tiles.forEach(t => { t.songUntil = -1; });
setPlayingUI(false);
wake();
}
function finish() {
halt();
const bus = player.bus;
setTimeout(() => bus.disconnect(), 1500);
setPlayingUI(false);
}
function toggle() { player.playing ? stop() : play(); }
const songsNav = $('songs');
SONGS.forEach((song, i) => {
const b = document.createElement('button');
b.type = 'button';
b.innerHTML = `<i aria-hidden="true"></i><span>${String(i + 1).padStart(2, '0')}</span><span class="name">${song.title}</span>`;
b.setAttribute('aria-label', song.title);
b.addEventListener('click', () => selectSong(i));
songsNav.appendChild(b);
});
function refreshNav() {
[...songsNav.children].forEach((b, i) => b.setAttribute('aria-current', String(SONGS[i] === cur)));
if (typeof sheetList !== 'undefined') [...sheetList.querySelectorAll('button')].forEach((b, i) => b.setAttribute('aria-current', String(SONGS[i] === cur)));
document.title = `${cur.title} · OwnZones`;
}
const sheetEl = $('sheet'), sheetList = $('sheetList');
SONGS.forEach((song, i) => {
const li = document.createElement('li'), b = document.createElement('button');
b.type = 'button';
b.innerHTML = `<i aria-hidden="true"></i><span class="num">${String(i + 1).padStart(2, '0')}</span>`
+ `<span class="what"><span>${song.title}</span><span class="meta">${song.meta}, ${fmt(song.length)}</span></span>`;
b.addEventListener('click', () => { selectSong(i); closeSheet(); });
li.appendChild(b); sheetList.appendChild(li);
});
let sheetOpener = null;
function openSheet() {
sheetOpener = document.activeElement;
sheetEl.hidden = false;
const current = sheetList.querySelector('[aria-current="true"]') || sheetList.querySelector('button');
current.focus();
}
function closeSheet() {
if (sheetEl.hidden) return;
sheetEl.hidden = true;
if (sheetOpener && sheetOpener.focus) sheetOpener.focus();
}
$('sheetClose').addEventListener('click', closeSheet);
sheetEl.addEventListener('click', e => { if (e.target === sheetEl) closeSheet(); });
document.addEventListener('keydown', e => { if (e.key === 'Escape') closeSheet(); });
const stepTrack = d => selectSong(SONGS.indexOf(cur) + d);
document.documentElement.classList.toggle('single', SONGS.length < 2);
if (SONGS.length < 2) $('trackNow').setAttribute('aria-label', 'Track details and instructions');
$('prevTrack').addEventListener('click', () => stepTrack(-1));
$('nextTrack').addEventListener('click', () => stepTrack(1));
let swipe = null, lastSwipe = 0;
const swipedRecently = () => performance.now() - lastSwipe < 400;
document.addEventListener('pointerdown', e => {
swipe = null;
if (e.pointerType === 'mouse' || !sheetEl.hidden) return;
if (tileAt(e.clientX, e.clientY) || (e.target.closest && e.target.closest('[data-play], .sound, .step'))) return;
swipe = { x: e.clientX, y: e.clientY, t: performance.now() };
}, { passive: true });
document.addEventListener('pointerup', e => {
if (!swipe) return;
const dx = e.clientX - swipe.x, dy = e.clientY - swipe.y, dt = performance.now() - swipe.t;
swipe = null;
if (Math.abs(dx) > 60 && Math.abs(dx) > 2 * Math.abs(dy) && dt < 700) {
lastSwipe = performance.now();
stepTrack(dx < 0 ? 1 : -1);
}
}, { passive: true });
function selectSong(i) {
const next = SONGS[(i + SONGS.length) % SONGS.length];
if (next === cur) return;
const resume = player.playing;
if (player.playing) stop();
cur = next;
applyKit(cur);
measureCallouts();
refreshNav();
setPlayingUI(false);
emitWave({ x: 0, y: 0, push: 0, reach: 420, spin: 6, lift: 30 });
wake();
if (resume) play();
}
document.addEventListener('keydown', e => {
if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return;
e.preventDefault();
selectSong(SONGS.indexOf(cur) + (e.key === 'ArrowRight' ? 1 : -1));
});
playHit.addEventListener('click', toggle);
playHit.addEventListener('keydown', e => {
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggle(); }
});
document.addEventListener('keydown', e => {
if (e.code !== 'Space' || e.repeat) return;
if (e.target.closest && e.target.closest('.hit, button')) return;
e.preventDefault();
toggle();
});
const rootEl = document.documentElement;
const hintEl = document.querySelector('.hint'), wordmarkEl = document.querySelector('.wordmark');
const smallOrTouch = matchMedia('(max-width: 759px), (max-height: 560px), (pointer: coarse)');
const force = { compact: false, tight: false };
function layout() {
const vw = window.innerWidth, vh = window.innerHeight;
const gw = 2 * GRID_HALF;
const tight = force.tight || vw < 640 || vh < 440;
rootEl.classList.toggle('tight', tight);
const hintRoom = tight ? 0 : hintEl.offsetHeight + 12;
const padYR = Math.max(12, Math.min(40, vh * 0.035));
const aboveR = padYR + 105;
const belowR = 122 + hintRoom + padYR;
const SR = Math.min((vw - 40) / gw, (vh / 2 - Math.max(aboveR, belowR)) / GRID_HALF, 1.1);
const padXC = Math.max(14, Math.min(96, vw * 0.06)), padYC = Math.max(12, Math.min(80, vh * 0.07));
const col = Math.min(220, Math.max(130, vw * 0.17));
const SC = Math.min((vw - 2 * padXC - 2 * col) / gw, (vh / 2 - (padYC + 58)) / GRID_HALF, 1.25);
wide = SC >= SR;
const compact = force.compact || smallOrTouch.matches || !wide;
rootEl.classList.toggle('compact', compact);
const padX = wide ? padXC : Math.max(14, Math.min(40, vw * 0.05));
const padY = wide ? padYC : padYR;
rootEl.style.setProperty('--pad-x', `${padX}px`);
rootEl.style.setProperty('--pad-y', `${padY}px`);
stageEl.setAttribute('viewBox', `0 0 ${vw} ${vh}`);
CX = vw / 2; CY = vh / 2;
S = Math.max(0.2, wide ? SC : SR);
const g = GRID_HALF * S, h = HALF * S, cell = CELL * S, pitch = PITCH * S;
for (const t of tiles) {
const x = CX + t.hx * S, y = CY + t.hy * S;
setRect(t.ghost, x - h, y - h, cell, cell);
setRect(t.hit, x - pitch / 2, y - pitch / 2, pitch, pitch);
}
setRect(playBase, CX - h, CY - h, cell, cell);
setRect(playTrace, CX - h, CY - h, cell, cell);
setRect(playHit, CX - pitch / 2, CY - pitch / 2, pitch, pitch);
playWord.setAttribute('x', CX.toFixed(1));
playWord.setAttribute('y', (CY + 4.5).toFixed(1));
const tiny = true;
playWord.style.display = tiny ? 'none' : '';
playIcon.style.display = tiny ? 'block' : 'none';
drawPlayIcon();
playPerimeter = 4 * cell;
marksG.innerHTML = '';
const m = g + (wide ? 16 : 11), arm = wide ? 5 : 4;
for (const [sx, sy] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) {
const x = CX + sx * m, y = CY + sy * m;
svgEl('path', { class: 'mark', d: `M${x - arm} ${y}H${x + arm}M${x} ${y - arm}V${y + arm}` }, marksG);
}
transportEl.style.top = `${wide ? CY + g + 36 : CY + g + 100}px`;
const navBottom = compact ? 0 : songsNav.getBoundingClientRect().bottom;
const soundBottom = compact ? soundBtn.getBoundingClientRect().bottom : 0;
const topBar = Math.max(wordmarkEl.getBoundingClientRect().bottom, soundBottom, navBottom);
Object.assign(geo, {
left: CX - g - 48, right: CX + g + 48,
top: { left: Math.max(padY + 20, wordmarkEl.getBoundingClientRect().bottom + 16), right: Math.max(padY + 34, navBottom + 16, soundBottom + 16) },
bottom: vh - padY - 34,
gridTop: CY - g, gridBottom: CY + g,
minX: 8, maxX: vw - 8,
});
geo.topRows = Math.max(1, Math.min(3, Math.floor((CY - g - 24 - (topBar + 10)) / 20) + 1));
for (const t of tiles) {
t.side = wide ? (t.hx < 0 || (t.hx === 0 && t.hy > 0) ? 'left' : 'right')
: (t.hy < 0 || (t.hy === 0 && t.hx < 0) ? 'top' : 'bottom');
t.shown = false; t.row = null;
}
measureCallouts();
tiles.forEach(drawTile);
stepCallouts(0);
}
function collisions() {
const box = el => el.getBoundingClientRect();
const shown = el => getComputedStyle(el).display !== 'none';
const hit = (a, b) => a.left < b.right - 1 && b.left < a.right - 1 && a.top < b.bottom - 1 && b.top < a.bottom - 1;
const g = GRID_HALF * S;
const grid = { left: CX - g, top: CY - g, right: CX + g, bottom: CY + g };
const tr = box(transportEl), sound = box(soundBtn), word = box(wordmarkEl);
const needs = { compact: false, tight: false };
if (shown(hintEl)) {
const hint = box(hintEl);
if (hit(hint, tr) || hit(hint, sound) || hit(hint, grid) || hit(hint, word)) needs.tight = true;
}
if (hit(sound, tr) || hit(sound, grid) || hit(sound, word)) needs.compact = true;
if (shown(songsNav)) {
const nav = box(songsNav);
if (hit(nav, grid) || hit(nav, tr) || hit(nav, word) || nav.bottom > window.innerHeight) needs.compact = true;
}
return needs;
}
function relayout() {
force.compact = false; force.tight = false;
layout();
for (let pass = 0; pass < 3; pass++) {
const needs = collisions();
if (!needs.compact && !needs.tight) break;
force.compact = force.compact || needs.compact;
force.tight = force.tight || needs.tight;
layout();
}
}
hintTiles.textContent = idleSoundText();
refreshSoundStatus();
refreshNav();
setPlayingUI(false);
relayout();
window.addEventListener('resize', relayout);
window.addEventListener('orientationchange', () => setTimeout(relayout, 120));
if (document.fonts && document.fonts.ready) document.fonts.ready.then(relayout);
</script>
</body>
</html>