رفتن به محتواCREATIVE·CODE·ART
0.25
1.5
1
0
p5.js

Eye of the Storm

A glass sphere around a disc of broken terrain that moves to a beat you program. Kick lifts the mountains, snare ripples to the edge, and at the peak a sphere of particles forms above the black pit. Drag to orbit, scroll to zoom, FX for filters.

مجوز: CC BY-NC-SA 4.0: ریمیکس با ذکر نام، غیرتجاری، با همین مجوز

دیدن کد
const TRACKS = ['KICK', 'SNARE', 'HAT', 'BASS'];
const STEPS = 16;
let pattern = [
  [1,0,0,0, 1,0,0,0, 1,0,0,0, 1,0,1,1],
  [0,0,0,0, 1,0,0,0, 0,0,0,0, 1,0,1,1],
  [1,0,1,0, 1,0,1,1, 1,0,1,0, 1,1,1,1],
  [1,0,0,1, 0,0,1,0, 1,0,0,1, 1,0,1,1],
];
const BASS_NOTES = [41.2, 41.2, 49, 41.2, 55, 41.2, 49, 36.7, 41.2, 41.2, 49, 41.2, 55, 61.7, 55, 49];
let bpm = 112;

let actx = null, master = null, noiseBuf = null, soundOn = false;
let step = 0, nextTime = 0, events = [], curStep = 0;
let env = [0, 0, 0, 0], snareAge = 9, intensity = 0, appear = 0;
let lastFrame = 0, spin = 0;
let zoom = 1;
let yaw = 0, pitch = 0, vYaw = 0, vPitch = 0, dragging = false;

function P(name, def) {
  return (typeof params !== 'undefined' && params && params[name] !== undefined) ? params[name] : def;
}

let discShader, shellShader, postShader, fb, R, particles = [];
let fx = 0, fxBtn;
const FX_NAMES = ['NONE', 'FILM', 'DITHER', 'CRT'];
let cells = [], soundBtn, bpmLabel, sparks = [];

const NOISE_GLSL = `
float hash(vec3 p){p=fract(p*0.3183099+0.1);p*=17.0;return fract(p.x*p.y*p.z*(p.x+p.y+p.z));}
float noise(vec3 x){vec3 i=floor(x);vec3 f=fract(x);f=f*f*(3.0-2.0*f);
return mix(mix(mix(hash(i),hash(i+vec3(1,0,0)),f.x),mix(hash(i+vec3(0,1,0)),hash(i+vec3(1,1,0)),f.x),f.y),
mix(mix(hash(i+vec3(0,0,1)),hash(i+vec3(1,0,1)),f.x),mix(hash(i+vec3(0,1,1)),hash(i+vec3(1,1,1)),f.x),f.y),f.z);}
float fbm(vec3 p){float v=0.0,a=0.5;for(int i=0;i<4;i++){v+=a*noise(p);p=p*2.03+vec3(1.7,9.2,3.1);a*=0.5;}return v;}
`;

const POST_VERT = `
precision highp float;
attribute vec3 aPosition;
attribute vec2 aTexCoord;
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
varying vec2 vUv;
void main(){
  vUv=aTexCoord;
  gl_Position=uProjectionMatrix*uModelViewMatrix*vec4(aPosition,1.0);
}`;

const POST_FRAG = `
precision highp float;
uniform sampler2D uTex;
uniform vec2 uRes;
uniform float uTime;
uniform float uMode;
uniform float uKick;
varying vec2 vUv;
float h21(vec2 p){p=fract(p*vec2(123.34,456.21));p+=dot(p,p+45.32);return fract(p.x*p.y);}
float bayer2(vec2 a){a=floor(a);return fract(dot(a,vec2(0.5,a.y*0.75)));}
float bayer4(vec2 a){return bayer2(0.5*a)*0.25+bayer2(a);}
float bayer8(vec2 a){return bayer4(0.5*a)*0.25+bayer2(a);}
void main(){
  vec2 uv=vUv;
  vec3 col;
  if(uMode<1.5){
    vec2 d=(uv-0.5)*0.0035*(1.0+2.0*uKick);
    col=vec3(texture2D(uTex,uv+d).r,texture2D(uTex,uv).g,texture2D(uTex,uv-d).b);
    float g=h21(gl_FragCoord.xy+fract(uTime*37.0)*100.0)-0.5;
    col+=g*0.09;
    col=pow(max(col,0.0),vec3(0.95,1.0,1.06));
    col=col*1.08+vec3(0.02,0.015,0.01);
    col*=smoothstep(1.05,0.35,length((uv-0.5)*vec2(uRes.x/uRes.y,1.0)));
  } else if(uMode<2.5){
    float px=2.0;
    vec2 cell=floor(uv*uRes/px);
    vec2 suv=(cell+0.5)*px/uRes;
    vec3 c=texture2D(uTex,suv).rgb;
    float l=dot(c,vec3(0.299,0.587,0.114));
    l=pow(l,0.8)*1.35;
    float th=bayer8(cell);
    vec3 dark=vec3(0.03,0.06,0.065);
    vec3 mid=vec3(0.16,0.3,0.31);
    vec3 lite=vec3(0.93,0.86,0.79);
    col= l*2.0<th+0.02 ? dark : (l*2.0<1.0+th ? mid : lite);
  } else {
    vec2 cc=uv-0.5;
    float r2=dot(cc,cc);
    vec2 buv=0.5+cc*(1.0+0.18*r2);
    if(buv.x<0.0||buv.x>1.0||buv.y<0.0||buv.y>1.0){gl_FragColor=vec4(0.0,0.0,0.0,1.0);return;}
    float sh=1.5/uRes.x*(1.0+3.0*uKick);
    col=vec3(texture2D(uTex,buv+vec2(sh,0.0)).r,texture2D(uTex,buv).g,texture2D(uTex,buv-vec2(sh,0.0)).b);
    vec3 glow=(texture2D(uTex,buv+vec2(0.004,0.0)).rgb+texture2D(uTex,buv-vec2(0.004,0.0)).rgb+texture2D(uTex,buv+vec2(0.0,0.004)).rgb+texture2D(uTex,buv-vec2(0.0,0.004)).rgb)*0.25;
    col+=glow*0.35;
    float line=0.62+0.38*sin(gl_FragCoord.y*3.14159*0.5);
    col*=line;
    float mask=mod(floor(gl_FragCoord.x),3.0);
    col*=vec3(mask==0.0?1.15:0.9,mask==1.0?1.15:0.9,mask==2.0?1.15:0.9);
    col*=0.95+0.05*sin(uTime*60.0);
    col*=smoothstep(0.75,0.35,length(cc*vec2(1.0,1.15)));
    col*=1.25;
  }
  gl_FragColor=vec4(col,1.0);
}`;

const DISC_VERT = `
precision highp float;
attribute vec3 aPosition;
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
uniform mat3 uNormalMatrix;
uniform float uTime, uKick, uSnare, uSnareAge, uHat, uBass;
varying vec3 vN;
varying vec3 vPos;
varying float vH;
varying float vR;
${NOISE_GLSL}
float heightAt(vec2 p){
  float r=length(p);
  float t=uTime*0.12;
  float wPit=1.0-smoothstep(0.34,0.42,r);
  float wSmall=smoothstep(0.34,0.42,r)*(1.0-smoothstep(0.5,0.57,r));
  float wBig=smoothstep(0.5,0.58,r)*(1.0-smoothstep(0.72,0.82,r));
  float wOut=smoothstep(0.72,0.82,r)*(1.0-smoothstep(0.92,1.0,r));
  float pit=-0.09*(1.0+0.7*uBass)+0.035*fbm(vec3(p*8.0,t*1.3));
  float clump=smoothstep(0.42,0.8,fbm(vec3(p*15.0,t*1.5)));
  float small=0.008+0.03*clump*(1.0+1.8*uHat)+0.01*fbm(vec3(p*30.0,t));
  float m=smoothstep(0.35,0.8,fbm(vec3(p*6.0,t)));
  float big=(0.015+0.03*m+0.07*m*clump+0.02*clump)*(1.0+1.4*uKick);
  float flu=0.02*fbm(vec3(p*14.0,t*1.6))+0.04*clump*smoothstep(0.2,0.65,fbm(vec3(p*5.0,-t)));
  flu+=exp(-pow((r-(0.76+uSnareAge*0.6))*14.0,2.0))*uSnare*0.05;
  float rough=0.012*fbm(vec3(p*38.0,t*0.7))*smoothstep(0.32,0.42,r)*(1.0-smoothstep(0.92,1.0,r));
  return wPit*pit+wSmall*small+wBig*big+wOut*flu+rough;
}
void main(){
  vec2 p=aPosition.xy*2.0;
  float h=heightAt(p);
  float e=0.004;
  float hx=heightAt(p+vec2(e,0.0));
  float hy=heightAt(p+vec2(0.0,e));
  vec3 n=normalize(vec3(-(hx-h)/e,-(hy-h)/e,1.0));
  vec4 mv=uModelViewMatrix*vec4(aPosition.xy,h*0.5,1.0);
  vN=normalize(uNormalMatrix*n);
  vPos=mv.xyz;
  vH=h;
  vR=length(p);
  gl_Position=uProjectionMatrix*mv;
}`;

const DISC_FRAG = `
precision highp float;
uniform vec3 uLight;
uniform float uBass;
varying vec3 vN;
varying vec3 vPos;
varying float vH;
varying float vR;
void main(){
  if(vR>1.0) discard;
  vec3 n=normalize(vN);
  float dif=clamp(dot(n,uLight),0.0,1.0);
  vec3 teal=vec3(0.10,0.17,0.17);
  vec3 cream=vec3(0.92,0.86,0.80);
  float peak=smoothstep(0.025,0.08,vH)*smoothstep(0.15,0.6,dif);
  vec3 alb=mix(teal,cream,peak);
  vec3 col=alb*(0.08+1.25*dif*dif);
  col*=1.0-0.94*(1.0-smoothstep(0.26,0.42,vR));
  col*=1.0-smoothstep(0.9,1.0,vR)*0.8;
  gl_FragColor=vec4(col,1.0);
}`;

const SHELL_VERT = `
precision highp float;
attribute vec3 aPosition;
attribute vec3 aNormal;
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
uniform mat3 uNormalMatrix;
varying vec3 vN;
varying vec3 vPos;
varying vec3 vObj;
void main(){
  vec4 mv=uModelViewMatrix*vec4(aPosition,1.0);
  vN=normalize(uNormalMatrix*aNormal);
  vPos=mv.xyz;
  vObj=aPosition;
  gl_Position=uProjectionMatrix*mv;
}`;

const SHELL_FRAG = `
precision highp float;
uniform vec3 uLight;
uniform float uGlow;
varying vec3 vN;
varying vec3 vPos;
varying vec3 vObj;
${NOISE_GLSL}
void main(){
  vec3 n=normalize(vN);
  vec3 v=normalize(-vPos);
  if(dot(n,v)<0.0) n=-n;
  float fres=pow(1.0-clamp(dot(n,v),0.0,1.0),2.5);
  float side=smoothstep(-0.15,0.75,dot(n,uLight));
  float spec=pow(max(dot(reflect(-uLight,n),v),0.0),24.0);
  float streak=fbm(vec3(normalize(vObj)*vec3(3.0,9.0,3.0)));
  float body=clamp(dot(n,uLight)*0.8+0.2,0.0,1.0);
  float a=side*(0.22*body+0.35*fres+0.12*spec+0.08*streak*fres)*(0.85+0.5*uGlow)+0.01;
  vec3 col=mix(vec3(0.18,0.30,0.31),vec3(0.6,0.75,0.76),spec);
  gl_FragColor=vec4(col*a,a);
}`;

function setup() {
  createCanvas(windowWidth, windowHeight, WEBGL);
  discShader = createShader(DISC_VERT, DISC_FRAG);
  shellShader = createShader(SHELL_VERT, SHELL_FRAG);
  postShader = createShader(POST_VERT, POST_FRAG);
  fb = createFramebuffer();
  const N = 1400, ga = PI * (3 - sqrt(5));
  for (let i = 0; i < N; i++) {
    const y = 1 - (i / (N - 1)) * 2, rr = sqrt(1 - y * y), th = ga * i;
    particles.push(createVector(cos(th) * rr, y, sin(th) * rr));
  }
  for (let i = 0; i < 420; i++) {
    const a = random(TWO_PI), r = 0.36 * sqrt(random());
    sparks.push({ x: cos(a) * r, z: sin(a) * r, y: random(0.02, 0.09), ph: random(TWO_PI), sp: random(2, 6) });
  }
  buildUI();
  cursor('grab');
  nextTime = performance.now() / 1000 + 0.05;
  setInterval(schedule, 25);
  lastFrame = millis();
}

function clockNow() {
  return soundOn ? actx.currentTime : performance.now() / 1000;
}

function schedule() {
  const sd = 60 / bpm / 4;
  while (nextTime < clockNow() + 0.12) {
    for (let tr = 0; tr < 4; tr++) {
      if (pattern[tr][step]) {
        events.push({ t: nextTime, tr, step });
        if (soundOn) playVoice(tr, nextTime, step);
      }
    }
    events.push({ t: nextTime, tr: -1, step });
    nextTime += sd;
    step = (step + 1) % STEPS;
  }
}

function draw() {
  const dt = min(0.05, (millis() - lastFrame) / 1000);
  lastFrame = millis();
  const t = millis() / 1000;
  R = min(width, height) * 0.36;

  schedule();
  const now = clockNow();
  while (events.length && events[0].t <= now) {
    const ev = events.shift();
    if (ev.tr < 0) { curStep = ev.step; continue; }
    env[ev.tr] = 1;
    if (ev.tr === 1) snareAge = 0;
  }
  const taus = [0.28, 0.22, 0.09, 0.35];
  for (let i = 0; i < 4; i++) env[i] *= exp(-dt / taus[i]);
  snareAge += dt;
  spin += dt * P('rotation', 0.25);

  const inst = 0.4 * env[0] + 0.25 * env[1] + 0.15 * env[2] + 0.25 * env[3];
  intensity = max(inst, intensity * exp(-dt / 1.6));
  const target = constrain(map(intensity, 0.62, 0.9, 0, 1), 0, 1);
  appear = lerp(appear, target, target > appear ? 0.06 : 0.015);

  fb.begin();
  background(0);
  const elev = 0.72, D = R * 3.15 * P('distance', 1) * zoom;
  camera(sin(t * 0.07) * R * 0.15, -sin(elev) * D, cos(elev) * D, 0, R * 0.3, R * 0.05, 0, 1, 0);
  perspective(0.75, width / height, R * 0.1, R * 60);

  const L = viewLight();

  if (!dragging) {
    yaw += vYaw;
    pitch += vPitch;
    vYaw *= 0.93;
    vPitch *= 0.93;
  }
  pitch = constrain(pitch, -1.2, 0.9);
  push();
  rotateX(pitch);
  rotateY(yaw);

  push();
  rotateY(spin);
  rotateX(HALF_PI);
  scale(R * 2);
  shader(discShader);
  discShader.setUniform('uTime', t);
  discShader.setUniform('uKick', env[0]);
  discShader.setUniform('uSnare', env[1]);
  discShader.setUniform('uSnareAge', snareAge);
  discShader.setUniform('uHat', env[2]);
  discShader.setUniform('uBass', env[3]);
  discShader.setUniform('uLight', L);
  noStroke();
  plane(1, 1, 280, 280);
  pop();
  resetShader();

  drawSparks(t);
  if (appear > 0.01) drawParticles(t);

  const gl = drawingContext;
  gl.depthMask(false);
  push();
  rotateY(spin);
  shader(shellShader);
  shellShader.setUniform('uLight', L);
  shellShader.setUniform('uGlow', env[3] * 0.5 + appear * 0.5);
  noStroke();
  sphere(R, 64, 48);
  pop();
  resetShader();
  gl.depthMask(true);
  pop();
  fb.end();

  background(0);
  if (fx === 0) {
    imageMode(CENTER);
    image(fb, 0, 0, width, height);
  } else {
    shader(postShader);
    postShader.setUniform('uTex', fb);
    postShader.setUniform('uRes', [width * pixelDensity(), height * pixelDensity()]);
    postShader.setUniform('uTime', t);
    postShader.setUniform('uMode', fx);
    postShader.setUniform('uKick', env[0]);
    noStroke();
    plane(width, height);
    resetShader();
  }

  updateUI();
}

function viewLight() {
  const l = createVector(-0.75, -0.45, 0.3).normalize();
  return [l.x, l.y, l.z];
}

function drawSparks(t) {
  push();
  rotateY(spin);
  strokeWeight(2);
  beginShape(POINTS);
  for (const s of sparks) {
    const tw = 0.5 + 0.5 * sin(t * s.sp + s.ph);
    const lift = s.y + 0.03 * env[3];
    stroke(255, 248, 235, 255 * tw * (0.5 + 0.5 * env[2]));
    vertex(s.x * R, -lift * R, s.z * R);
  }
  endShape();
  pop();
}

function drawParticles(t) {
  const base = R * (0.05 + 0.11 * appear) * (1 + 0.3 * env[0]) * P('coreSize', 1);
  const tw = P('twist', 0);
  push();
  translate(0, -R * (0.08 + 0.12 * appear), 0);
  rotateY(t * 0.5);
  stroke(255, 245, 230, 255 * appear);
  strokeWeight(1.5 + 2.5 * env[2] * appear);
  beginShape(POINTS);
  for (const d of particles) {
    const n = noise(d.x * 1.6 + t * 0.4, d.y * 1.6, d.z * 1.6 + env[1] * 2);
    const r = base * (0.8 + 0.5 * n + 0.25 * env[3] * sin(d.y * 9 + t * 4));
    const arm = sin(atan2(d.z, d.x) * 4 + d.y * tw * PI * (1 + 0.4 * env[1]) + t * 0.8);
    const rr = r * (1 + 0.28 * min(tw, 1) * arm);
    const a = tw * d.y * 0.6;
    const ca = cos(a), sa = sin(a);
    vertex((d.x * ca - d.z * sa) * rr, d.y * rr, (d.x * sa + d.z * ca) * rr);
  }
  endShape();
  pop();
}

function ensureAudio() {
  if (actx) return;
  actx = new (window.AudioContext || window.webkitAudioContext)();
  const comp = actx.createDynamicsCompressor();
  comp.threshold.value = -14;
  comp.ratio.value = 4;
  master = actx.createGain();
  master.gain.value = 0.8;
  master.connect(comp);
  comp.connect(actx.destination);
  noiseBuf = actx.createBuffer(1, actx.sampleRate, actx.sampleRate);
  const d = noiseBuf.getChannelData(0);
  for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
}

function toggleSound() {
  ensureAudio();
  soundOn = !soundOn;
  if (soundOn) {
    actx.resume();
    nextTime = actx.currentTime + 0.05;
  } else {
    nextTime = performance.now() / 1000 + 0.05;
  }
  events = [];
  soundBtn.textContent = soundOn ? 'SOUND ON' : 'SOUND OFF';
}

function playVoice(tr, t, s) {
  if (tr === 0) {
    const o = actx.createOscillator(), g = actx.createGain();
    o.frequency.setValueAtTime(150, t);
    o.frequency.exponentialRampToValueAtTime(42, t + 0.14);
    g.gain.setValueAtTime(1, t);
    g.gain.exponentialRampToValueAtTime(0.001, t + 0.45);
    o.connect(g); g.connect(master);
    o.start(t); o.stop(t + 0.5);
  } else if (tr === 1) {
    const n = actx.createBufferSource(), f = actx.createBiquadFilter(), g = actx.createGain();
    n.buffer = noiseBuf;
    f.type = 'highpass'; f.frequency.value = 1300;
    g.gain.setValueAtTime(0.55, t);
    g.gain.exponentialRampToValueAtTime(0.001, t + 0.2);
    n.connect(f); f.connect(g); g.connect(master);
    n.start(t); n.stop(t + 0.22);
    const o = actx.createOscillator(), og = actx.createGain();
    o.type = 'triangle'; o.frequency.value = 190;
    og.gain.setValueAtTime(0.35, t);
    og.gain.exponentialRampToValueAtTime(0.001, t + 0.1);
    o.connect(og); og.connect(master);
    o.start(t); o.stop(t + 0.12);
  } else if (tr === 2) {
    const n = actx.createBufferSource(), f = actx.createBiquadFilter(), g = actx.createGain();
    n.buffer = noiseBuf;
    f.type = 'highpass'; f.frequency.value = 7500;
    g.gain.setValueAtTime(0.22, t);
    g.gain.exponentialRampToValueAtTime(0.001, t + 0.05);
    n.connect(f); f.connect(g); g.connect(master);
    n.start(t); n.stop(t + 0.06);
  } else {
    const o = actx.createOscillator(), f = actx.createBiquadFilter(), g = actx.createGain();
    o.type = 'sawtooth'; o.frequency.value = BASS_NOTES[s];
    f.type = 'lowpass';
    f.frequency.setValueAtTime(900, t);
    f.frequency.exponentialRampToValueAtTime(140, t + 0.25);
    g.gain.setValueAtTime(0.45, t);
    g.gain.exponentialRampToValueAtTime(0.001, t + 0.32);
    o.connect(f); f.connect(g); g.connect(master);
    o.start(t); o.stop(t + 0.35);
  }
}

function buildUI() {
  const css = document.createElement('style');
  css.textContent = `
  .seq{position:fixed;left:50%;bottom:14px;transform:translateX(-50%);display:flex;flex-direction:column;gap:5px;
    padding:10px 12px;background:rgba(0,0,0,.55);border:1px solid rgba(160,200,200,.18);border-radius:8px;
    font:500 10px/1 ui-monospace,Menlo,Consolas,monospace;color:#9fb5b5;letter-spacing:.08em;user-select:none;z-index:5}
  .seq .row{display:flex;align-items:center;gap:4px}
  .seq .lab{width:42px}
  .seq .cell{width:clamp(12px,3.4vw,20px);height:clamp(12px,3.4vw,20px);border:1px solid rgba(160,200,200,.35);
    border-radius:3px;background:transparent;cursor:pointer;padding:0}
  .seq .cell.gap{margin-left:6px}
  .seq .cell.on{background:#ecdcc9;border-color:#ecdcc9}
  .seq .cell.now{box-shadow:0 0 0 1px #fff}
  .seq .ctl{display:flex;flex-wrap:wrap;gap:6px;align-items:center;margin-top:3px}
  .seq .fx{margin-left:auto;min-width:96px}
  .seq button.b{background:none;color:#cfe0e0;border:1px solid rgba(160,200,200,.35);border-radius:4px;
    font:inherit;padding:5px 8px;cursor:pointer}
  .seq button.b.main{color:#0b0e0f;background:#ecdcc9;border-color:#ecdcc9}`;
  document.head.appendChild(css);

  const box = document.createElement('div');
  box.className = 'seq';
  for (let tr = 0; tr < 4; tr++) {
    const row = document.createElement('div');
    row.className = 'row';
    const lab = document.createElement('span');
    lab.className = 'lab';
    lab.textContent = TRACKS[tr];
    row.appendChild(lab);
    cells[tr] = [];
    for (let s = 0; s < STEPS; s++) {
      const c = document.createElement('button');
      c.className = 'cell' + (s % 4 === 0 && s > 0 ? ' gap' : '');
      c.setAttribute('aria-label', TRACKS[tr] + ' step ' + (s + 1));
      c.onclick = () => { pattern[tr][s] = pattern[tr][s] ? 0 : 1; };
      row.appendChild(c);
      cells[tr][s] = c;
    }
    box.appendChild(row);
  }
  const ctl = document.createElement('div');
  ctl.className = 'ctl';
  soundBtn = mkBtn('SOUND OFF', toggleSound, 'main');
  const minus = mkBtn('-', () => { bpm = max(60, bpm - 4); });
  bpmLabel = document.createElement('span');
  const plus = mkBtn('+', () => { bpm = min(180, bpm + 4); });
  const rnd = mkBtn('RANDOM', () => {
    const dens = [0.35, 0.2, 0.55, 0.35];
    for (let tr = 0; tr < 4; tr++) for (let s = 0; s < STEPS; s++) pattern[tr][s] = random() < dens[tr] ? 1 : 0;
  });
  const clr = mkBtn('CLEAR', () => { for (const row of pattern) row.fill(0); });
  fxBtn = mkBtn('', () => { fx = (fx + 1) % FX_NAMES.length; });
  fxBtn.classList.add('fx');
  ctl.append(soundBtn, minus, bpmLabel, plus, rnd, clr, fxBtn);
  box.appendChild(ctl);
  document.body.appendChild(box);
}

function mkBtn(txt, fn, extra) {
  const b = document.createElement('button');
  b.className = 'b' + (extra ? ' ' + extra : '');
  b.textContent = txt;
  b.onclick = fn;
  return b;
}

function updateUI() {
  for (let tr = 0; tr < 4; tr++) for (let s = 0; s < STEPS; s++) {
    const c = cells[tr][s];
    const on = !!pattern[tr][s], now = s === curStep;
    if (c._on !== on) { c.classList.toggle('on', on); c._on = on; }
    if (c._now !== now) { c.classList.toggle('now', now); c._now = now; }
  }
  bpmLabel.textContent = bpm + ' BPM';
  fxBtn.textContent = 'FX: ' + FX_NAMES[fx];
  fxBtn.classList.toggle('main', fx !== 0);
}

function mousePressed(e) {
  dragging = !!(e && e.target && e.target.tagName === 'CANVAS');
  if (dragging) { vYaw = 0; vPitch = 0; cursor('grabbing'); }
}

function mouseDragged() {
  if (!dragging) return;
  const dx = (mouseX - pmouseX) * 0.006, dy = (mouseY - pmouseY) * 0.006;
  yaw += dx;
  pitch -= dy;
  vYaw = dx;
  vPitch = -dy;
  return false;
}

function mouseWheel(e) {
  if (!e || !e.target || e.target.tagName !== 'CANVAS') return;
  zoom = constrain(zoom * Math.exp(e.delta * 0.0012), 0.45, 3.5);
  return false;
}

function mouseReleased() {
  if (dragging) cursor('grab');
  dragging = false;
}

function keyPressed() {
  if (key === ' ') toggleSound();
  if (key === 'f' || key === 'F') fx = (fx + 1) % FX_NAMES.length;
}

function windowResized() {
  resizeCanvas(windowWidth, windowHeight);
}