Back to lava88
SOURCE / PINNED RELEASE

Made of little things.

lava88

Release
76b39502bdd3…
Author-recorded commit
Not provided
License
Check the original source
Author’s source link
Open external source ↗May change independently of this release

The hash-verified playable HTML, which may contain bundled or minified code. This view does not execute it.

index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Lava lamp</title>
<style>
  html, body { width:100%; height:100%; margin:0; overflow:hidden; }
  canvas { display:block; width:100%; height:100%; }
</style>
</head>
<body>
<canvas aria-label="Lava lamp"></canvas>
<script>
  let canvas = document.querySelector('canvas');
  const reduced = matchMedia('(prefers-reduced-motion: reduce)');
  const darkMode = matchMedia('(prefers-color-scheme: dark)');
  const clamp = (v, a = 0, b = 1) => Math.max(a, Math.min(b, v));
  const ease = (v) => { v = clamp(v); return v * v * (3 - 2 * v); };
  const smoother = (v) => { v = clamp(v); return v*v*v*(v*(v*6-15)+10); };
  const random = (a, b) => a + Math.random() * (b - a);
  const mix = (a, b, t) => a + (b - a) * t;
  const blend = (a, b, t) => a.map((v, i) => mix(v, b[i], t));
  const rgb = (hex) => [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16) / 255);
  let palette, shellTheme;
  function theme(value) {
    if (value?.colors && ['background', 'primary', 'seal'].every(k => /^#[0-9a-f]{6}$/i.test(value.colors[k] || ''))) {
      shellTheme = value.colors;
    }
    const { background, primary, seal } = shellTheme ?? (darkMode.matches
      ? { background:'#1a1d21', primary:'#8fb4e3', seal:'#ec6a4f' }
      : { background:'#fdfcf9', primary:'#27598c', seal:'#d2432c' });
    const paper = rgb(background);
    const dark = paper[0] * .213 + paper[1] * .715 + paper[2] * .072 < .5;
    palette = [paper,
      blend(rgb(dark ? '#221928' : '#ded6d3'), rgb(primary), .07),
      rgb(dark ? '#8d472b' : '#ffe2af'),
      blend(rgb(dark ? '#b12c21' : '#b03922'), rgb(seal), .22),
      blend(rgb(dark ? '#ffb63b' : '#f6a329'), rgb(seal), .09),
      rgb(dark ? '#ffe4a0' : '#fff0bc')];
  }
  theme();
  darkMode.addEventListener('change', () => theme());
  window.napplet?.theme?.get().then(theme, () => {});
  window.napplet?.theme?.onChanged(theme);

  // Material parcels exchange wax with a hot reservoir. Temperature reverses
  // buoyancy at the ceiling; drag, wall pressure and changing drift keep paths
  // continuous. Overlapping implicit surfaces fuse and pinch apart.
  const blobs = [];
  let time = 0, nextBirth = 2, pool = 1, aspect = 1;
  function parcel(phase, x, y) {
    return { phase, x, y, vx:0, vy:phase === 'rise' ? -.033 : phase === 'fall' ? .026 : 0,
      age:0, heat:phase === 'fall' ? .14 : .98, mass:random(.72, 1.26),
      radius:random(.112, .157), lift:random(.035, .059), fall:random(.027, .047),
      duration:random(3.8, 6.5), drift:random(-.018, .018), wander:random(2, 7),
      tilt:random(-.24, .24), targetTilt:random(-.36, .36), shape:random(.86, 1.15), targetShape:random(.78, 1.25), lane:x };
  }
  blobs.push(parcel('rise', .38, .46), parcel('fall', .72, .30), parcel('rise', .65, .79));
  for (const b of blobs) b.age = 4; // Already detached when the lamp opens.
  function radii(b) {
    const growth = b.phase === 'feed' ? ease(b.age / b.duration)
      : b.phase === 'drain' ? 1 - ease(b.age / b.duration) : 1;
    const r = b.radius * Math.sqrt(b.mass) * Math.sqrt(Math.max(.001, growth));
    const stretch = clamp(b.shape + clamp(b.vy * 14, -.18, .62) - .36 * ease((.19 - b.y) / .14), .72, 1.75);
    return [r * Math.min(1, 1 / aspect) / Math.sqrt(stretch), r * Math.min(1, aspect) * Math.sqrt(stretch)];
  }
  function advance(dt) {
    time += dt;
    nextBirth -= dt;
    if (nextBirth <= 0 && blobs.length < (aspect > 1.25 ? 8 : 6) && pool > .42) {
      let x = random(.20, .80);
      // Prefer an unoccupied inlet rather than emitting into an existing neck.
      for (let tries = 0; tries < 5 && blobs.some(b => b.y > .72 && Math.abs(b.x - x) < .22); tries++) x = random(.20, .80);
      const b = parcel('feed', x, .985);
      blobs.push(b);
      nextBirth = random(5.8, 10.4);
    }
    let occupied = 0;
    for (const b of blobs) {
      b.age += dt;
      b.wander -= dt;
      if (b.wander <= 0) {
        b.drift = random(-.026, .026);
        b.targetShape = random(.74, 1.30); b.targetTilt = random(-.4, .4);
        b.wander = random(3.4, 8.5);
      }
      b.shape += (b.targetShape - b.shape) * dt * .18;
      b.tilt += (b.targetTilt - b.tilt) * dt * .21;
      const [rx, ry] = radii(b);
      const ceiling = .009 + ry * .60;
      let vy = 0, heat = .96;
      if (b.phase === 'feed') {
        vy = -.028 * ease(b.age / 2);
        if (b.age >= b.duration) { b.phase = 'rise'; b.age = 0; }
      } else if (b.phase === 'rise') {
        vy = -b.lift * clamp((b.y - ceiling) / .075, .14, 1);
        if (b.y < ceiling + .043) { b.phase = 'cool'; b.age = 0; }
      } else if (b.phase === 'cool') {
        heat = .06;
        vy = mix(-.017, b.fall, ease((.57 - b.heat) / .32));
        if (b.heat < .28) { b.phase = 'fall'; b.age = 0; b.lane = clamp(b.x + (b.x < .5 ? .32 : -.32), .16, .84); }
      } else if (b.phase === 'fall') {
        heat = .14 + .28 * ease((b.y - .75) / .25);
        vy = b.fall * clamp((.97 - b.y) / .12, .35, 1);
        if (b.y > .92) { b.phase = 'drain'; b.age = 0; b.duration = random(3.2, 5.5); }
      } else {
        heat = .98;
        vy = .019;
      }
      b.heat += (heat - b.heat) * Math.min(1, dt * (b.phase === 'cool' ? .19 : .12));
      const wall = .025 + rx * .92;
      let vx = b.drift + (b.lane - b.x) * .065;
      vx += Math.max(0, wall + .06 - b.x) * .7 - Math.max(0, b.x - (1 - wall - .06)) * .7;
      vy += Math.max(0, ceiling - b.y) * 1.2;
      b.vx += (vx - b.vx) * dt * .65;
      b.vy += (vy - b.vy) * dt * .85;
      b.x = clamp(b.x + b.vx * dt, .025, .975);
      b.y = clamp(b.y + b.vy * dt, .015, 1.075);
      occupied += b.mass * (b.phase === 'feed' ? ease(b.age / b.duration) : b.phase === 'drain' ? 1 - ease(b.age / b.duration) : 1);
    }
    for (let i = blobs.length - 1; i >= 0; i--) if (blobs[i].phase === 'drain' && blobs[i].age >= blobs[i].duration) blobs.splice(i, 1);
    pool += (clamp(1.28 - occupied * .105, .34, 1) - pool) * dt * .9;
  }

  // A bounded, compact-support field; the same wax is rendered by both paths.
  let fw, fh, field, warmth, reservoir, pixels;
  const threshold = .55;
  function splat(cx, cy, rx, ry, power, heat, lean = 0, taper = 0, bend = 0) {
    rx = Math.max(.003, rx); ry = Math.max(.003, ry);
    // Conservative bounds contain the *entire* warped kernel, including its tail.
    const bound = rx * (1 + Math.abs(lean) + Math.abs(taper) + Math.abs(bend));
    const left = Math.max(0, Math.floor((cx - bound) * fw));
    const right = Math.min(fw, Math.ceil((cx + bound) * fw));
    const top = Math.max(0, Math.floor((cy - ry) * fh));
    const bottom = Math.min(fh, Math.ceil((cy + ry) * fh));
    for (let y = top; y < bottom; y++) {
      const dy = ((y + .5) / fh - cy) / ry;
      const limit = 1 - dy * dy;
      if (limit <= 0) continue;
      const shift = lean * dy + bend * (dy*dy - .22);
      const invWidth = 1 / (1 + taper * dy);
      for (let x = left, i = y * fw + left; x < right; x++, i++) {
        const dx = (((x + .5) / fw - cx) / rx - shift) * invWidth;
        const v = limit - dx * dx;
        if (v > 0) {
          // C2 support: value, slope and curvature all vanish at the boundary.
          // Submerged parcels lose their separate surface as they enter the reservoir.
          const f = power * v*v*v * (1 - smoother((reservoir[i] - .72) / .38));
          field[i] += f; warmth[i] += f * heat;
        }
      }
    }
  }
  function sample() {
    field.fill(0); warmth.fill(0); reservoir.fill(0);
    // The reservoir surface gently changes shape and height as wax leaves/returns.
    for (let x = 0; x < fw; x++) {
      const u = (x + .5) / fw;
      const surface = .965 - .061 * pool + .012 * Math.cos(u * 9 + time * .17)
        + .008 * Math.cos(u * 16 - time * .11);
      const depth = .085 * Math.min(1, aspect + .45);
      for (let y = Math.max(0, Math.floor((surface - depth) * fh)); y < fh; y++) {
        const v = 2 * threshold * smoother(.5 + ((y + .5) / fh - surface) / (2 * depth));
        const i = y*fw+x;
        field[i] = reservoir[i] = v; warmth[i] = v * .99;
      }
    }
    for (const b of blobs) {
      const [rx, ry] = radii(b);
      const lean = clamp(b.tilt + b.vx * 9, -.48, .48);
      const rising = ease(-b.vy * 25), sinking = ease(b.vy * 25);
      const wobble = .15 * Math.sin(time * .34 + b.lane * 11 + b.tilt * 2);
      const taper = -.43 * rising + .27 * sinking + wobble;
      // A broad, smoothly vanishing kernel with bent, tapered cross-sections.
      splat(b.x, b.y, rx * 2.38, ry * 2.38, 1.07, b.heat, lean, taper, wobble + .18*b.tilt);
      splat(b.x - lean * rx * .65, b.y + ry * .28, rx * 1.6, ry * 1.6, .24, b.heat, lean, taper);
      // Wax spreading into the reservoir has a wide lower shoulder, not
      // a separate sphere; it also bridges small gaps at the pool junction.
      const spread = smoother((b.y + ry - .84) / .16);
      if (spread > 0) splat(b.x, b.y + ry*.65, rx*2.55, ry*1.65, .48*spread,
        mix(b.heat,.98,spread*.5), lean*.5);
      if (b.phase === 'feed' || b.phase === 'rise' && b.age < 2.8) {
        const neck = b.phase === 'feed' ? ease(b.age / 1.7) : 1 - ease(b.age / 2.8);
        const gap = .97 - b.y;
        if (gap > 0) splat(b.x, b.y + gap * .61, rx * (.34 + .36 * neck), gap * .95 + ry * .25,
          1.06 * neck, .98, lean * .4);
      }
    }
  }

  function gpu() {
    const gl = canvas.getContext('webgl2', { alpha:false, antialias:false, powerPreference:'low-power' });
    if (!gl) return;
    const debug = gl.getExtension('WEBGL_debug_renderer_info');
    const renderer = debug ? gl.getParameter(debug.UNMASKED_RENDERER_WEBGL) : '';
    const softwareGL = /swiftshader|llvmpipe|software rasterizer|softpipe/i.test(renderer);
    function shader(type, code) {
      const s = gl.createShader(type); gl.shaderSource(s, code); gl.compileShader(s);
      if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw Error(gl.getShaderInfoLog(s));
      return s;
    }
    const vs = shader(gl.VERTEX_SHADER, `#version 300 es
      out vec2 uv;
      void main() {
        vec2 c = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2);
        uv = vec2(c.x, 1.0-c.y); gl_Position = vec4(2.0*c-1.0,0,1);
      }`);
    const fs = shader(gl.FRAGMENT_SHADER, `#version 300 es
      precision highp float;
      uniform sampler2D wax;
      uniform vec3 colors[6];
      uniform vec2 size;
      in vec2 uv;
      out vec4 color;
      // Cubic B-spline reconstruction uses four bilinear texture reads. Unlike
      // a raw bilinear normal, it remains smooth across the field's grid cells.
      vec4 smoothField(vec2 p) {
        vec2 dim = vec2(textureSize(wax,0)), t = p*dim-.5;
        vec2 cell = floor(t), a = fract(t), b = 1.-a;
        vec2 w0 = b*b*b/6., w3 = a*a*a/6.;
        vec2 w1 = (3.*a*a*a-6.*a*a+4.)/6., w2 = 1.-w0-w1-w3;
        vec2 g0 = w0+w1, g1 = w2+w3;
        vec2 l = (cell-.5+w1/g0)/dim, h = (cell+1.5+w3/g1)/dim;
        return mix(mix(texture(wax,l),texture(wax,vec2(h.x,l.y)),g1.x),
          mix(texture(wax,vec2(l.x,h.y)),texture(wax,h),g1.x),g1.y);
      }
      float sq(float x) { return x*x; }
      void main() {
        vec2 p = uv;
        vec2 wall = min(p,1.-p)*size/min(size.x,size.y);
        vec3 paper=colors[0], cold=colors[1], hot=colors[2], ember=colors[3], gold=colors[4], shine=colors[5];
        float cone = (p.x-.5)/(0.36+.40*(1.-p.y));
        float lamp = exp(-sq(cone)*1.5-sq((p.y-1.03)*1.9));
        vec3 liquid = mix(mix(paper,cold,.90),hot,clamp(lamp*.88+.055*p.y,0.,1.));
        vec4 sampleValue = smoothField(p);
        float v = dot(sampleValue.rg,vec2(4.,4./255.));
        float heat = clamp(4.*sampleValue.b/max(v,.05),0.,1.);
        float aa = max(fwidth(v)*.64,.0015);
        float edge = smoothstep(.55-aa,.55+aa,v);
        float thickness = 1.-exp(-max(v-.55,0.)*2.2);
        float poolBody = smoothstep(.53,.96,sampleValue.a);
        vec2 g = vec2(dFdx(v),-dFdy(v))*size.y*(1.-.85*poolBody);
        vec3 n = normalize(vec3(-g*.043, .85+1.8*thickness));
        float lower = smoothstep(-.55,.70,n.y);
        float spec = pow(max(0.,dot(n,normalize(vec3(-.47,-.35,1.)))),23.);
        // Transmission lights the core and lower shoulder; thin wax transmits
        // more light than the dense red body, producing a luminous neck and rim.
        float energy = clamp(.26+.56*lamp+.16*heat,0.,1.);
        float core = smoothstep(.04,.55,thickness);
        float transmitted = energy*(.45+.55*lower)*(.65+.35*core);
        vec3 body = mix(ember,gold,clamp(.06+.45*heat+.61*transmitted,0.,1.));
        vec3 material = body*(.79+.40*transmitted);
        float thin = 1.-smoothstep(.035,.62,thickness);
        material = mix(material,mix(gold,shine,.41+.24*lamp),thin*energy*(.30+.57*lower));
        material = mix(material,gold,core*transmitted*.40);
        material += shine*(spec*.060+core*transmitted*.13);

        liquid += gold*exp(-max(0.,.55-v)*14.)*(.024+.055*energy)*(1.-edge);
        vec3 scene = mix(liquid,material,edge);
        // The tile itself is the vessel; no inner frame, only optical falloff at its walls.
        float side = exp(-wall.x*95.);
        scene = mix(scene,shine,side*.045*(1.-p.x));
        scene *= 1.-.055*exp(-min(wall.x,wall.y)*70.);
        float noise = fract(52.9829189*fract(dot(floor(gl_FragCoord.xy),vec2(.06711056,.00583715))))-.5;
        color = vec4(scene+noise/255.,1.);
      }`);
    const program = gl.createProgram(); gl.attachShader(program, vs); gl.attachShader(program, fs); gl.linkProgram(program);
    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) throw Error(gl.getProgramInfoLog(program));
    gl.deleteShader(vs); gl.deleteShader(fs); gl.useProgram(program);
    const colors = gl.getUniformLocation(program, 'colors[0]'), size = gl.getUniformLocation(program, 'size');
    const tex = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, tex);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
    gl.disable(gl.DITHER);
    let fence;
    return {
      softwareGL,
      ready() {
        if (!fence) return true;
        const state = gl.clientWaitSync(fence, 0, 0);
        if (state === gl.TIMEOUT_EXPIRED) return false;
        gl.deleteSync(fence); fence = null; return true;
      },
      resize(w, h) {
        if (fence) { gl.deleteSync(fence); fence = null; }
        canvas.width = w; canvas.height = h; gl.viewport(0, 0, w, h);
        gl.uniform2f(size, w, h);
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, fw, fh, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
      },
      draw() {
        for (let i = 0, j = 0; i < field.length; i++, j += 4) {
          const v = Math.min(4, field[i]) * 63.75;
          pixels[j] = Math.floor(v); pixels[j+1] = Math.round((v % 1) * 255);
          pixels[j+2] = Math.round(Math.min(4, warmth[i])*63.75);
          pixels[j+3] = Math.round(clamp(reservoir[i]/(2*threshold))*255);
        }
        gl.uniform3fv(colors, palette.flat());
        gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, fw, fh, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
        gl.drawArrays(gl.TRIANGLES, 0, 3);
        if (fence) gl.deleteSync(fence);
        fence = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0); gl.flush();
      },
    };
  }
  function software() {
    const ctx = canvas.getContext('2d', { alpha:false });
    const low = document.createElement('canvas'), source = low.getContext('2d');
    let image;
    return {
      resize(w, h) {
        canvas.width = w; canvas.height = h; low.width = fw; low.height = fh;
        image = source.createImageData(fw, fh);
      },
      draw() {
        const [paper, cold, hot, ember, gold, shine] = palette;
        for (let y = 0, i = 0; y < fh; y++) for (let x = 0; x < fw; x++, i++) {
          const u = (x + .5) / fw, v = (y + .5) / fh;
          const lamp = Math.exp(-1.5*((u-.5)/(.36+.40*(1-v)))**2-((v-1.03)*1.9)**2);
          const f = field[i], heat = warmth[i] / Math.max(.0001, f);
          const dx = field[y*fw+Math.min(x+1,fw-1)]-field[y*fw+Math.max(x-1,0)];
          const dy = field[Math.min(y+1,fh-1)*fw+x]-field[Math.max(y-1,0)*fw+x];
          const edge = ease((f-threshold+.04)/.08), thick = ease((f-threshold)*3);
          const energy = clamp(.26+.56*lamp+.16*heat), lower = clamp(.5-dy*3);
          const glow = energy*(.45+.55*lower), poolBody = ease((reservoir[i]/(2*threshold)-.53)/.43);
          for (let c = 0; c < 3; c++) {
            const liquid = mix(mix(paper[c],cold[c],.90),hot[c],lamp*.88+.055*v);
            const body = mix(ember[c],gold[c],clamp(.06+.45*heat+.61*glow))*(.79+.40*glow);
            const wax = mix(body,mix(gold[c],shine[c],.37+.24*lamp),(1-thick)*energy*(.30+.57*lower));
            image.data[i*4+c] = 255 * mix(liquid,mix(wax,body,poolBody*.35),edge);
          }
          image.data[i*4+3] = 255;
        }
        source.putImageData(image,0,0);
        ctx.drawImage(low,0,0,canvas.width,canvas.height);
      },
    };
  }
  let output, accelerated = false, observer, quality = 1, frame = 0, last = 0, cost = 0, slow = 0;
  function fallback() {
    observer?.unobserve(canvas);
    const fresh = canvas.cloneNode(); canvas.replaceWith(fresh); canvas = fresh;
    accelerated = false; output = software(); observer?.observe(canvas);
  }
  try { output = gpu(); accelerated = !!output; } catch { /* A fresh canvas can use 2D. */ }
  if (!output) fallback();
  canvas.addEventListener('webglcontextlost', event => { event.preventDefault(); fallback(); resize(); });
  function resize() {
    const w = canvas.clientWidth, h = canvas.clientHeight;
    if (!w || !h) return;
    aspect = w / h;
    const grid = Math.min(1, (accelerated ? 360 : 200) * quality / Math.max(w,h));
    fw = Math.max(16, Math.round(w*grid)); fh = Math.max(16, Math.round(h*grid));
    field = new Float32Array(fw*fh); warmth = new Float32Array(fw*fh); reservoir = new Float32Array(fw*fh); pixels = new Uint8Array(fw*fh*4);
    const fast = accelerated && !output.softwareGL;
    const scale = Math.min(devicePixelRatio, (fast ? 1920 : 600)*quality/Math.max(w,h),
      Math.sqrt((fast ? 2073600 : 180000)*quality/(w*h)));
    output.resize(Math.max(1,Math.round(w*scale)),Math.max(1,Math.round(h*scale)));
    if (!document.hidden) { sample(); output.draw(); }
  }
  function step(now) {
    const interval = reduced.matches ? 125 : 1000 / (accelerated && !output.softwareGL ? 30 : 15);
    if (field && (!last || now-last >= interval-.5)) {
      if (output.ready && !output.ready()) {
        if (++slow > 16 && quality > .55) { quality *= .8; slow = 0; resize(); }
        frame = requestAnimationFrame(step); return;
      }
      const dt = last ? Math.min(.12,(now-last)/1000)*(reduced.matches ? .18 : 1) : 0;
      last = now;
      const start = performance.now();
      for (let remaining = dt; remaining > 0;) { const part = Math.min(remaining,1/60); advance(part); remaining -= part; }
      sample(); output.draw();
      cost = mix(cost,performance.now()-start,.08);
      slow = cost > interval*.42 ? slow+1 : Math.max(0,slow-1);
      if (slow > 32 && quality > .55) { quality *= .8; slow = 0; resize(); }
    }
    frame = requestAnimationFrame(step);
  }
  function visibility() {
    cancelAnimationFrame(frame); last = 0;
    if (!document.hidden) frame = requestAnimationFrame(step);
  }
  observer = new ResizeObserver(resize); observer.observe(canvas);
  document.addEventListener('visibilitychange',visibility);
  resize(); visibility();
</script>
</body>
</html>