Lava lamp v1 · Antigravity CLI19.11.2026 03:57
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" /><meta name="theme-color" content="#0b0a12" /><title>Lava Lamp</title><style> *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; -webkit-tap-highlight-color: transparent; } html, body { width: 100%; height: 100%; overflow: hidden; background: #0b0a12; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; user-select: none; -webkit-user-select: none; touch-action: manipulation; } .stage { position: fixed; inset: 0; width: 100vw; height: 100dvh; overflow: hidden; } #bgCanvas, #fgCanvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; } #waxCanvas { position: absolute; display: block; cursor: pointer; } #fgCanvas { pointer-events: none; } /* Tactile inline desk rocker switch */ .switch-wrap { position: absolute; z-index: 10; transform: translate(-50%, -50%); touch-action: manipulation; } .lamp-switch { position: relative; display: flex; align-items: center; gap: 10px; padding: 8px 14px 9px 12px; min-width: 106px; height: 44px; border: 1px solid rgba(255, 255, 255, 0.08); border-bottom-color: rgba(0, 0, 0, 0.72); border-radius: 22px; background: linear-gradient(180deg, #2b2931 0%, #1b1920 55%, #121116 100%); box-shadow: 0 10px 20px rgba(0, 0, 0, 0.62), 0 3px 6px rgba(0, 0, 0, 0.55), inset 0 1px 0 rgba(255, 255, 255, 0.14), inset 0 -2px 3px rgba(0, 0, 0, 0.65); color: rgba(235, 228, 220, 0.72); cursor: pointer; outline: none; transition: transform 0.08s ease, box-shadow 0.25s ease, border-color 0.25s ease; } .lamp-switch:active { transform: translateY(1.5px) scale(0.985); box-shadow: 0 5px 12px rgba(0, 0, 0, 0.65), 0 1px 3px rgba(0, 0, 0, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.1), inset 0 -1px 2px rgba(0, 0, 0, 0.7); } .lamp-switch:focus-visible { box-shadow: 0 0 0 2px #0b0a12, 0 0 0 4px rgba(255, 160, 76, 0.85), 0 10px 20px rgba(0, 0, 0, 0.6); } .lamp-switch.is-on { border-color: rgba(255, 168, 92, 0.22); box-shadow: 0 10px 22px rgba(0, 0, 0, 0.58), 0 3px 8px rgba(0, 0, 0, 0.45), 0 0 18px rgba(255, 118, 42, 0.14), inset 0 1px 0 rgba(255, 214, 174, 0.2), inset 0 -2px 3px rgba(0, 0, 0, 0.65); } /* Pilot LED */ .switch-led { width: 7px; height: 7px; border-radius: 50%; flex-shrink: 0; background: radial-gradient(circle at 35% 35%, #514a48, #241f20); box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.8); transition: background 0.22s ease, box-shadow 0.22s ease; } .lamp-switch.is-on .switch-led { background: radial-gradient(circle at 35% 35%, #fff0c2 0%, #ff9b38 55%, #e84b18 100%); box-shadow: 0 0 6px rgba(255, 148, 48, 0.95), 0 0 14px rgba(255, 96, 28, 0.65); } /* Physical rocker slot */ .rocker-well { position: relative; width: 44px; height: 22px; border-radius: 11px; background: #0b0a0e; box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.92), 0 1px 0 rgba(255, 255, 255, 0.08); padding: 2px; flex-shrink: 0; } .rocker-paddle { position: relative; width: 100%; height: 100%; border-radius: 9px; display: flex; align-items: center; justify-content: space-between; padding: 0 7px; background: linear-gradient(90deg, #1b1920 0%, #2c2933 48%, #3c3846 100%); box-shadow: inset 1px 1px 1px rgba(255, 255, 255, 0.16), inset -2px 0 3px rgba(0, 0, 0, 0.65), -2px 1px 3px rgba(0, 0, 0, 0.55); transition: background 0.18s ease, box-shadow 0.18s ease; } .lamp-switch.is-on .rocker-paddle { background: linear-gradient(90deg, #433a42 0%, #312a31 52%, #1d191e 100%); box-shadow: inset -1px 1px 1px rgba(255, 200, 150, 0.2), inset 2px 0 3px rgba(0, 0, 0, 0.6), 2px 1px 3px rgba(0, 0, 0, 0.55); } .rocker-mark { font-size: 9px; font-weight: 700; line-height: 1; transition: color 0.18s ease, text-shadow 0.18s ease, opacity 0.18s ease; } .rocker-mark-o { color: rgba(220, 215, 215, 0.58); } .rocker-mark-i { color: rgba(220, 215, 215, 0.28); } .lamp-switch.is-on .rocker-mark-o { color: rgba(220, 215, 215, 0.24); } .lamp-switch.is-on .rocker-mark-i { color: #ffb86c; text-shadow: 0 0 6px rgba(255, 145, 56, 0.8); } .switch-label { font-size: 11px; font-weight: 600; letter-spacing: 0.1em; min-width: 24px; text-align: left; color: rgba(215, 208, 218, 0.52); transition: color 0.2s ease, text-shadow 0.2s ease; } .lamp-switch.is-on .switch-label { color: rgba(255, 218, 178, 0.92); text-shadow: 0 0 10px rgba(255, 130, 50, 0.45); } @media (max-width: 420px) { .lamp-switch { height: 44px; padding: 8px 13px 9px 11px; } }</style></head><body> <div class="stage" id="stage"> <canvas id="bgCanvas" aria-hidden="true"></canvas> <canvas id="waxCanvas" aria-label="Glass lava lamp with rising and falling wax blobs"></canvas> <canvas id="fgCanvas" aria-hidden="true"></canvas> <div class="switch-wrap" id="switchWrap"> <button type="button" id="powerSwitch" class="lamp-switch is-on" role="switch" aria-checked="true" aria-label="Turn lava lamp off or on" > <span class="switch-led" aria-hidden="true"></span> <span class="rocker-well" aria-hidden="true"> <span class="rocker-paddle"> <span class="rocker-mark rocker-mark-i">I</span> <span class="rocker-mark rocker-mark-o">O</span> </span> </span> <span class="switch-label" id="switchLabel">ON</span> </button> </div> </div><script>(() => { 'use strict'; /* ============================================================ * Constants & Shared Bottle Geometry * ============================================================ */ const MAX_BLOBS = 22; const BOTTLE_ASPECT = 0.42; // max belly width / glass height const CANVAS_ASPECT = 0.46; // slight horizontal margin for anti-aliased glass edge const HALF_W = BOTTLE_ASPECT * 0.5; // 0.21 const FLOOR_Y = 0.012; const LIQUID_TOP = 0.955; const MIN_BLOB_MASS = 0.00052; // r ~= 0.0228 const MAX_BLOB_MASS = 0.00465; // r ~= 0.0682 const MIN_SPLIT_MASS = 0.00205; // r ~= 0.0453 // Exact same contour function used by JS physics, Canvas 2D glass, and WebGL fragment shader function bottleHalfWidthNorm(y) { if (y <= 0.24) { const t = Math.max(0, Math.min(1, y / 0.24)); return 0.74 + 0.26 * Math.sin(t * 1.57079632679); } const t = Math.max(0, Math.min(1, (y - 0.24) / 0.76)); return 1.0 - 0.52 * Math.pow(t, 1.35); } function wallXAt(y) { return HALF_W * bottleHalfWidthNorm(y); } function clamp(v, lo, hi) { return v < lo ? lo : v > hi ? hi : v; } function lerp(a, b, t) { return a + (b - a) * t; } function smoothstep(edge0, edge1, x) { const t = clamp((x - edge0) / (edge1 - edge0), 0, 1); return t * t * (3 - 2 * t); } /* ============================================================ * DOM & Layout State * ============================================================ */ const bgCanvas = document.getElementById('bgCanvas'); const waxCanvas = document.getElementById('waxCanvas'); const fgCanvas = document.getElementById('fgCanvas'); const bgCtx = bgCanvas.getContext('2d', { alpha: false }); const fgCtx = fgCanvas.getContext('2d'); const switchWrap = document.getElementById('switchWrap'); const powerSwitch = document.getElementById('powerSwitch'); const switchLabel = document.getElementById('switchLabel'); let dpr = 1; let layout = {}; let woodPatternCanvas = null; let woodCacheKey = ''; /* ============================================================ * Subtle Synthesized Switch Click (Web Audio, zero external files) * ============================================================ */ let audioCtx = null; function playSwitchClick(turningOn) { try { const Ctx = window.AudioContext || window.webkitAudioContext; if (!Ctx) return; if (!audioCtx) audioCtx = new Ctx(); if (audioCtx.state === 'suspended') audioCtx.resume(); const now = audioCtx.currentTime; // Short filtered noise burst for tactile plastic rocker click const len = Math.floor(audioCtx.sampleRate * 0.016); const buf = audioCtx.createBuffer(1, len, audioCtx.sampleRate); const data = buf.getChannelData(0); for (let i = 0; i < len; i++) { const env = Math.exp(-i / (len * 0.24)); data[i] = (Math.random() * 2 - 1) * env; } const src = audioCtx.createBufferSource(); src.buffer = buf; const filter = audioCtx.createBiquadFilter(); filter.type = 'bandpass'; filter.frequency.value = turningOn ? 2350 : 1750; filter.Q.value = 1.6; const gain = audioCtx.createGain(); gain.gain.setValueAtTime(0.14, now); gain.gain.exponentialRampToValueAtTime(0.001, now + 0.016); src.connect(filter); filter.connect(gain); gain.connect(audioCtx.destination); src.start(now); } catch (_) { // Audio is purely optional } } /* ============================================================ * Procedural Walnut Wood Grain Offscreen Generator * ============================================================ */ function buildWoodCanvas(w, h) { const c = document.createElement('canvas'); c.width = Math.max(1, Math.round(w)); c.height = Math.max(1, Math.round(h)); const ctx = c.getContext('2d'); // Rich dark mid-century walnut base gradient (perspective depth) const baseGrad = ctx.createLinearGradient(0, 0, 0, h); baseGrad.addColorStop(0, '#171110'); baseGrad.addColorStop(0.18, '#231814'); baseGrad.addColorStop(0.76, '#2b1c16'); baseGrad.addColorStop(0.84, '#1b110d'); baseGrad.addColorStop(1, '#120b09'); ctx.fillStyle = baseGrad; ctx.fillRect(0, 0, w, h); // Subtle organic wood grain streaks const tableTopH = h * 0.80; ctx.save(); ctx.beginPath(); ctx.rect(0, 0, w, tableTopH); ctx.clip(); const grainCount = 46; for (let i = 0; i < grainCount; i++) { const yBase = (i / grainCount) * tableTopH; const isLight = i % 3 === 0; ctx.strokeStyle = isLight ? `rgba(110, 70, 44, ${0.045 + (i % 5) * 0.012})` : `rgba(8, 4, 3, ${0.12 + (i % 4) * 0.04})`; ctx.lineWidth = 0.8 + (i % 4) * 0.7; ctx.beginPath(); const waveAmp = 1.5 + (i % 5) * 1.1; const waveFreq = 0.004 + (i % 7) * 0.0012; const phase = i * 1.73; for (let x = 0; x <= w; x += 18) { const y = yBase + Math.sin(x * waveFreq + phase) * waveAmp + Math.sin(x * waveFreq * 2.3 + phase * 1.6) * (waveAmp * 0.35); if (x === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y); } ctx.stroke(); } // Fine wood pores ctx.fillStyle = 'rgba(0, 0, 0, 0.14)'; for (let i = 0; i < 160; i++) { const px = ((i * 197.3) % 1) * w; const py = ((i * 83.7) % 1) * tableTopH; const pw = 8 + (i % 19); ctx.fillRect(px, py, pw, 1); } // Front chamfered desk lip highlight const lipGrad = ctx.createLinearGradient(0, tableTopH - 3, 0, tableTopH + 4); lipGrad.addColorStop(0, 'rgba(255, 210, 175, 0)'); lipGrad.addColorStop(0.5, 'rgba(255, 200, 155, 0.11)'); lipGrad.addColorStop(1, 'rgba(0, 0, 0, 0.5)'); ctx.fillStyle = lipGrad; ctx.fillRect(0, tableTopH - 3, w, 7); ctx.restore(); return c; } /* ============================================================ * Lamp State & Wax Physics Engine * ============================================================ */ const state = { isOn: true, bulbGlow: 1.0, // fast optical bulb brightness (0..1) heaterPower: 1.0, // slightly slower thermal bath power (0..1) time: 0, avgWaxWarmth: 0.72, avgWaxY: 0.42, blobs: [], }; function createBlob(x, y, m, temp, vx = 0, vy = 0, cooldown = 0) { return { x, y, vx, vy, m, r: Math.sqrt(m), temp, stretch: 1.0, splitCooldown: cooldown, phase: Math.random() * Math.PI * 2, age: 0, }; } function initWarmBlobs() { state.blobs = [ // Bottom molten wax pool createBlob(-0.072, 0.055, 0.0029, 0.68, 0.004, 0.006, 1.2), createBlob( 0.005, 0.048, 0.0033, 0.78, -0.003, 0.018, 0.8), createBlob( 0.076, 0.058, 0.0027, 0.64, -0.005, 0.005, 1.5), // Rising warm plumes createBlob(-0.025, 0.20, 0.0026, 0.84, 0.006, 0.052, 2.0), createBlob( 0.048, 0.34, 0.0019, 0.76, -0.008, 0.044, 1.8), createBlob(-0.042, 0.52, 0.0028, 0.66, 0.005, 0.030, 1.0), // Upper cooling blobs createBlob( 0.028, 0.74, 0.0024, 0.44, 0.006, -0.016, 1.4), createBlob(-0.018, 0.86, 0.0017, 0.34, -0.004, -0.024, 1.6), // Descending cool blobs createBlob( 0.055, 0.61, 0.0016, 0.31, -0.005, -0.042, 1.5), createBlob(-0.068, 0.38, 0.0018, 0.36, 0.007, -0.036, 1.2), // Small drifting droplets createBlob( 0.012, 0.45, 0.0009, 0.72, -0.004, 0.048, 2.2), createBlob(-0.032, 0.68, 0.00085, 0.38, 0.005, -0.026, 2.0), ]; } function nudgeBlobsAt(normX, normY) { // Gentle physical jostle when user taps the glass const px = (normX - 0.5) * CANVAS_ASPECT; const py = 1.0 - normY; for (let i = 0; i < state.blobs.length; i++) { const b = state.blobs[i]; const dx = b.x - px; const dy = b.y - py; const d2 = dx * dx + dy * dy; const influence = Math.exp(-d2 / 0.038); const dist = Math.sqrt(d2) + 0.015; b.vx += (dx / dist) * 0.075 * influence; b.vy += (dy / dist) * 0.065 * influence + 0.022 * influence; } } function stepPhysics(dt) { const blobs = state.blobs; // Smooth optical bulb & thermal ramp const target = state.isOn ? 1.0 : 0.0; const bulbSpeed = state.isOn ? 3.8 : 2.3; const heatSpeed = state.isOn ? 0.58 : 0.46; state.bulbGlow += (target - state.bulbGlow) * (1 - Math.exp(-bulbSpeed * dt)); state.heaterPower += (target - state.heaterPower) * (1 - Math.exp(-heatSpeed * dt)); const heat = state.heaterPower; const tNow = state.time; // 1. Update temperature, buoyancy, convection, and drag for (let i = 0; i < blobs.length; i++) { const b = blobs[i]; b.age += dt; if (b.splitCooldown > 0) b.splitCooldown = Math.max(0, b.splitCooldown - dt); const wx = wallXAt(b.y); const radialFrac = clamp(Math.abs(b.x) / Math.max(wx, 0.01), 0, 1); // Thermal inertia: larger blobs heat/cool slightly slower const thermalRate = 1.0 / (0.62 + 7.2 * b.r); if (heat > 0.02) { // Bottom heating zone (strongest right over the central bulb) const centerBoost = 1.18 - 0.42 * radialFrac * radialFrac; const heating = heat * Math.exp(-b.y / 0.19) * 0.54 * centerBoost; // Top & wall cooling zone const topCool = 0.045 + 0.44 * smoothstep(0.48, 0.94, b.y) + 0.04 * radialFrac * radialFrac; // Ambient cool when heater is ramping down const ambientCool = (1.0 - heat) * 0.34; const dT = (heating * (1.08 - b.temp) - (topCool + ambientCool) * (b.temp + 0.04)) * thermalRate; b.temp = clamp(b.temp + dT * dt, 0.02, 1.0); // Subtle anti-stagnation nudge in the mid-zone so blobs never stall forever at neutral buoyancy if (heat > 0.65 && b.y > 0.25 && b.y < 0.72 && Math.abs(b.temp - 0.5) < 0.045 && Math.abs(b.vy) < 0.018) { b.temp += (b.vy >= 0 ? 0.055 : -0.055) * dt; } } else { // Lamp is OFF: smooth cooling toward room temp b.temp = Math.max(0.0, b.temp - (0.28 + 0.24 * b.temp) * thermalRate * dt); } // Buoyancy force: neutral at temp = 0.50 const neutralT = 0.50; const buoyancy = (b.temp - neutralT) * (0.44 + 0.14 * heat); // Extra gentle gravity settle when lamp is off so cooled wax rests heavily at the bottom const offGravity = (1.0 - heat) * -0.14; let ay = buoyancy + offGravity; // Rayleigh-Benard horizontal convection: // Warm rising wax drifts subtly toward warm center; cool upper wax drifts slightly outward let ax = 0; if (heat > 0.15) { if (b.temp > 0.54 && b.y < 0.65) { ax += -b.x * 0.18 * heat; } else if (b.temp < 0.46 && b.y > 0.52) { const sign = b.x >= 0 ? 1 : -1; ax += sign * 0.032 * heat * (1.0 - radialFrac); } // Subtle organic swirl turbulence const swirl = Math.sin(tNow * 0.65 + b.phase + b.y * 4.2); ax += swirl * 0.026 * heat; ay += Math.cos(tNow * 0.52 + b.phase * 1.3 + b.x * 8.0) * 0.014 * heat; } b.vx += ax * dt; b.vy += ay * dt; } // 2. Pairwise interactions: surface-tension attraction (for merging) or soft repulsion const mergePairs = []; const maxMassAllowed = state.isOn ? MAX_BLOB_MASS : 0.0041; const minBlobsAllowed = state.isOn ? 8 : 5; for (let i = 0; i < blobs.length; i++) { const bi = blobs[i]; for (let j = i + 1; j < blobs.length; j++) { const bj = blobs[j]; const dx = bj.x - bi.x; const dy = bj.y - bi.y; const distSq = dx * dx + dy * dy; const rSum = bi.r + bj.r; const range = rSum * 1.12; if (distSq > range * range) continue; const dist = Math.sqrt(distSq) + 1e-5; const nx = dx / dist; const ny = dy / dist; const combinedM = bi.m + bj.m; const tempDiff = Math.abs(bi.temp - bj.temp); const canMerge = bi.splitCooldown <= 0 && bj.splitCooldown <= 0 && combinedM <= maxMassAllowed && blobs.length > minBlobsAllowed && (tempDiff < 0.34 || !state.isOn); if (canMerge && dist < rSum * 0.94) { // Strong smooth surface tension pulling touching blobs together to fuse without popping const overlap = 1.0 - dist / (rSum * 0.94); const pull = (0.09 + 0.52 * overlap * overlap) * dt; const totalM = combinedM; bi.vx += nx * pull * (bj.m / totalM); bi.vy += ny * pull * (bj.m / totalM); bj.vx -= nx * pull * (bi.m / totalM); bj.vy -= ny * pull * (bi.m / totalM); // Blend temperatures slightly as their liquid necks connect const blend = 0.7 * overlap * dt; const avgT = (bi.temp * bi.m + bj.temp * bj.m) / totalM; bi.temp += (avgT - bi.temp) * blend; bj.temp += (avgT - bj.temp) * blend; // Collapse into single blob only once centers nearly coincide (mathematically pop-free!) if (dist < rSum * 0.22) { mergePairs.push([i, j]); } } else { // Non-merging pair: either too heavy or recently split const recentlySplit = bi.splitCooldown > 0 && bj.splitCooldown > 0; if (!recentlySplit && dist < rSum * 0.88) { const overlap = (rSum * 0.88 - dist) / rSum; const push = overlap * 0.52 * dt; const totalM = combinedM; bi.vx -= nx * push * (bj.m / totalM); bi.vy -= ny * push * (bj.m / totalM); bj.vx += nx * push * (bi.m / totalM); bj.vy += ny * push * (bi.m / totalM); } else if (recentlySplit && dist < rSum * 0.35 && bi.age > 0.25) { // Very gentle separation assist if a split pair drifts too slowly apart const push = 0.045 * dt; bi.vx -= nx * push; bi.vy -= ny * push; bj.vx += nx * push; bj.vy += ny * push; } } } } // 3. Execute merges (each blob participates in at most one merge per step) if (mergePairs.length > 0) { const merged = new Uint8Array(blobs.length); const toRemove = []; for (let k = 0; k < mergePairs.length; k++) { const [i, j] = mergePairs[k]; if (merged[i] || merged[j]) continue; if (blobs.length - toRemove.length <= minBlobsAllowed) break; const bi = blobs[i]; const bj = blobs[j]; const m = bi.m + bj.m; bi.x = (bi.x * bi.m + bj.x * bj.m) / m; bi.y = (bi.y * bi.m + bj.y * bj.m) / m; bi.vx = (bi.vx * bi.m + bj.vx * bj.m) / m; bi.vy = (bi.vy * bi.m + bj.vy * bj.m) / m; bi.temp = (bi.temp * bi.m + bj.temp * bj.m) / m; bi.stretch = (bi.stretch * bi.m + bj.stretch * bj.m) / m; bi.m = m; bi.r = Math.sqrt(m); bi.splitCooldown = 1.6; merged[i] = 1; merged[j] = 1; toRemove.push(j); } if (toRemove.length > 0) { toRemove.sort((a, b) => b - a); for (let k = 0; k < toRemove.length; k++) { blobs.splice(toRemove[k], 1); } } } // 4. Organic Thermal Splitting (exact mass conservation at coincident center -> zero pop!) if (heat > 0.32 && blobs.length < MAX_BLOBS - 1) { for (let i = blobs.length - 1; i >= 0; i--) { if (blobs.length >= MAX_BLOBS) break; const b = blobs[i]; if (b.splitCooldown > 0 || b.m < MIN_SPLIT_MASS) continue; let splitRate = 0; // Bottom dome pinch-off when heated if (b.y < 0.26 && b.temp > 0.54 && b.m > 0.0022) { splitRate = 0.24 * heat * (b.m / 0.0028); } // Large mid-bottle blob shearing apart else if (b.m > 0.0030 && b.y >= 0.20 && b.y <= 0.78) { splitRate = 0.22 * heat * (0.6 + Math.abs(b.vy) * 8.0); } // Cooling top blob shedding a sinking droplet else if (b.y > 0.68 && b.temp < 0.49 && b.m > 0.0023) { splitRate = 0.20 * heat; } if (splitRate > 0 && Math.random() < splitRate * dt) { const frac = 0.32 + Math.random() * 0.30; const mTop = b.m * frac; const mBot = b.m - mTop; if (mTop < MIN_BLOB_MASS || mBot < MIN_BLOB_MASS) continue; // Update original blob as lower/cooler daughter const origX = b.x; const origY = b.y; const origVx = b.vx; const origVy = b.vy; const origTemp = b.temp; const origStretch = b.stretch; const hKick = (Math.random() - 0.5) * 0.028; b.m = mBot; b.r = Math.sqrt(mBot); b.y = origY - 0.0012; b.temp = clamp(origTemp - 0.09, 0.05, 0.95); b.vx = origVx - hKick; b.vy = origVy - 0.028; b.splitCooldown = 3.8 + Math.random() * 1.4; b.age = 0; // Spawn upper/warmer daughter at essentially identical center const daughter = createBlob( origX + (Math.random() - 0.5) * 0.001, origY + 0.0012, mTop, clamp(origTemp + 0.12, 0.08, 1.0), origVx + hKick, origVy + 0.042, 3.8 + Math.random() * 1.4 ); daughter.stretch = origStretch; blobs.push(daughter); } } } // 5. Viscous fluid drag, integration, wall/floor/meniscus containment, and shape stretch const dragFactor = Math.exp(-2.35 * dt); let warmthSum = 0; let yMassSum = 0; let massTotal = 0; for (let i = 0; i < blobs.length; i++) { const b = blobs[i]; b.vx *= dragFactor; b.vy *= dragFactor; // Speed cap for calm hypnotic lava motion const speed = Math.hypot(b.vx, b.vy); const maxSpeed = 0.175; if (speed > maxSpeed) { const sc = maxSpeed / speed; b.vx *= sc; b.vy *= sc; } b.x += b.vx * dt; b.y += b.vy * dt; // Bottom floor containment (allows resting wax to spread cleanly across the base) const minY = FLOOR_Y + b.r * 0.52; if (b.y < minY) { const pen = minY - b.y; b.y = minY - pen * 0.15; if (b.vy < 0) b.vy *= -0.18; // Soft horizontal spreading when settling onto the bottom cup b.vx += Math.sin(b.phase + tNow * 0.3) * 0.01 * dt; } // Top liquid meniscus containment const maxY = LIQUID_TOP - b.r * 0.72; if (b.y > maxY) { const pen = b.y - maxY; b.y = maxY + pen * 0.12; if (b.vy > 0) b.vy *= -0.15; } // Curved glass wall containment const wx = wallXAt(clamp(b.y, 0, 1)); const maxX = Math.max(0.01, wx - b.r * 0.68); if (Math.abs(b.x) > maxX) { const sign = b.x >= 0 ? 1 : -1; const pen = Math.abs(b.x) - maxX; b.x = sign * (maxX + pen * 0.1); if (b.vx * sign > 0) b.vx *= -0.25; // Subtle inward slide along the tapered glass cone b.vx -= sign * 0.06 * dt; } // Subtle velocity-driven vertical teardrop elongation & floor flattening let targetStretch = 1.0 + clamp(Math.abs(b.vy) * 1.55, 0, 0.20); if (b.y < FLOOR_Y + b.r * 1.15 && Math.abs(b.vy) < 0.03) { // Resting blobs flatten softly against the bottom glass targetStretch = 0.86; } else if (b.y > LIQUID_TOP - b.r * 1.2 && Math.abs(b.vy) < 0.025) { targetStretch = 0.90; } b.stretch += (targetStretch - b.stretch) * (1 - Math.exp(-3.5 * dt)); warmthSum += b.temp * b.m; yMassSum += b.y * b.m; massTotal += b.m; } if (massTotal > 0) { state.avgWaxWarmth = warmthSum / massTotal; state.avgWaxY = yMassSum / massTotal; } } /* ============================================================ * WebGL1 Metaball & Glass Interior Renderer (with 2D Fallback) * ============================================================ */ let gl = null; let glProg = null; let glLocs = null; let useWebGL = false; let waxCtx2D = null; let fallbackBufCanvas = null; let fallbackBufCtx = null; let fallbackImgData = null; const uBlobsArr = new Float32Array(MAX_BLOBS * 4); const uStretchArr = new Float32Array(MAX_BLOBS); const VERT_SRC = ` attribute vec2 aPos; varying vec2 vUv; void main() { vUv = aPos * 0.5 + 0.5; gl_Position = vec4(aPos, 0.0, 1.0); } `; const FRAG_SRC = ` #ifdef GL_FRAGMENT_PRECISION_HIGH precision highp float; #else precision mediump float; #endif varying vec2 vUv; uniform vec2 uRes; uniform float uTime; uniform float uLight; uniform float uHeat; uniform int uCount; uniform vec4 uBlobs[${MAX_BLOBS}]; uniform float uStretch[${MAX_BLOBS}]; const float CANVAS_ASPECT = 0.46; const float HALF_W = 0.21; const float LIQUID_TOP = 0.955; float bottleHalfWidthNorm(float y) { if (y <= 0.24) { float t = clamp(y / 0.24, 0.0, 1.0); return 0.74 + 0.26 * sin(t * 1.5707963); } float t = clamp((y - 0.24) / 0.76, 0.0, 1.0); return 1.0 - 0.52 * pow(max(t, 0.00001), 1.35); } float hash21(vec2 p) { p = fract(p * vec2(123.34, 456.21)); p += dot(p, p + 45.32); return fract(p.x * p.y); } void main() { vec2 uv = vUv; vec2 p = vec2((uv.x - 0.5) * CANVAS_ASPECT, uv.y); float halfW = HALF_W * bottleHalfWidthNorm(uv.y); float dWall = abs(p.x) - halfW; float pxSize = CANVAS_ASPECT / max(uRes.x, 1.0); float aa = pxSize * 1.35; float bottleMask = 1.0 - smoothstep(-aa, aa, dWall); bottleMask *= smoothstep(0.0, 0.006, uv.y) * smoothstep(1.0, 0.994, uv.y); if (bottleMask <= 0.002) discard; // Cylindrical glass normal float nx = clamp(p.x / max(halfW, 0.001), -1.0, 1.0); float nz = sqrt(max(0.0, 1.0 - nx * nx)); float fresnel = pow(max(1.0 - nz, 0.0001), 2.6); // Meniscus curve (slightly raised by capillary action at glass walls) float meniscusY = LIQUID_TOP + 0.009 * pow(max(abs(nx), 0.0001), 2.2); float inLiquid = 1.0 - smoothstep(meniscusY - 0.004, meniscusY + 0.004, uv.y); // --- Liquid Background Color --- // Warm glowing fluid when ON vec3 liqHot = vec3(1.00, 0.54, 0.14); vec3 liqMid = vec3(0.46, 0.09, 0.30); vec3 liqTop = vec3(0.10, 0.04, 0.21); vec3 liqOn = mix(liqHot, liqMid, smoothstep(0.0, 0.36, uv.y)); liqOn = mix(liqOn, liqTop, smoothstep(0.32, 0.94, uv.y)); // Halogen bulb upward spotlight glow from bottom center float bulbDist = length(vec2(p.x * 1.45, uv.y + 0.05)); float bulbBeam = exp(-bulbDist * 3.1) * (0.55 + 0.45 * nz); liqOn += vec3(1.0, 0.68, 0.22) * bulbBeam * 0.85; // Depth shading inside curved glass cylinder liqOn *= (0.64 + 0.42 * nz); // Cool dim translucent glass fluid when OFF vec3 liqOff = mix(vec3(0.055, 0.045, 0.085), vec3(0.095, 0.085, 0.135), uv.y * 0.7 + 0.3 * nz); // Soft ambient room light from upper-left liqOff += vec3(0.05, 0.06, 0.09) * smoothstep(-0.2, 0.9, -nx) * (0.4 + 0.6 * uv.y); vec3 liquidCol = mix(liqOff, liqOn, uLight); // Lingering soft thermal warmth near the coil right after turning off liquidCol += vec3(0.55, 0.16, 0.06) * exp(-uv.y * 7.5) * uHeat * (1.0 - uLight) * 0.22; // Subtle drifting thermal micro-flecks inside warm liquid if (uLight > 0.05 && inLiquid > 0.1) { vec2 grid = vec2(p.x * 26.0, (uv.y - uTime * 0.022) * 26.0); vec2 cell = floor(grid); vec2 f = fract(grid) - 0.5; float h = hash21(cell); if (h > 0.88) { vec2 off = vec2(hash21(cell + 13.1) - 0.5, hash21(cell + 29.7) - 0.5) * 0.55; float speck = smoothstep(0.14, 0.02, length(f - off)); liquidCol += vec3(1.0, 0.76, 0.42) * speck * 0.10 * uLight * nz * (1.1 - uv.y * 0.7); } } // Air gap above meniscus vec3 airOn = vec3(0.13, 0.07, 0.18) * (0.65 + 0.45 * nz) + vec3(0.24, 0.11, 0.14) * fresnel; vec3 airOff = vec3(0.07, 0.07, 0.10) * (0.6 + 0.4 * nz); vec3 bgCol = mix(mix(airOff, airOn, uLight), liquidCol, inLiquid); // Luminous meniscus line (never pass negative base to pow!) float dm = (uv.y - meniscusY) / 0.0038; float meniscusLine = exp(-dm * dm); bgCol += mix(vec3(0.22, 0.24, 0.32), vec3(0.95, 0.55, 0.45), uLight) * meniscusLine * (0.35 + 0.55 * nz); // --- Wax Metaball Field & Analytical Gradient --- float field = 0.0; float weightedTemp = 0.0; vec2 grad = vec2(0.0); for (int i = 0; i < ${MAX_BLOBS}; i++) { if (i >= uCount) break; vec4 b = uBlobs[i]; float m = b.z; if (m <= 0.0) continue; float st = uStretch[i]; vec2 d = p - b.xy; vec2 ds = vec2(d.x * st, d.y / st); float denom = dot(ds, ds) + 0.00028; float w = m / denom; field += w; weightedTemp += w * b.w; grad += (-2.0 * w / denom) * vec2(ds.x * st, ds.y / st); } // Preserve raw field sum for unbiased temperature interpolation before inner wall clip float rawField = field; // Keep wax neatly inside inner glass wall & beneath liquid meniscus float innerWall = halfW - 0.007; float innerMask = (1.0 - smoothstep(innerWall - 0.006, innerWall + 0.002, abs(p.x))) * (1.0 - smoothstep(meniscusY - 0.016, meniscusY - 0.002, uv.y)); field *= innerMask; // Soft warm halo around wax blobs bleeding into surrounding liquid float glowHalo = smoothstep(0.32, 1.0, field) * (1.0 - smoothstep(0.96, 1.15, field)); bgCol += vec3(1.0, 0.40, 0.14) * glowHalo * 0.34 * uLight * inLiquid; // Anti-aliased wax surface mask float gradLen = length(grad); float edgeW = max(gradLen * pxSize * 1.25, 0.045); float waxAlpha = smoothstep(1.0 - edgeW, 1.0 + edgeW, field); vec3 col = bgCol; if (waxAlpha > 0.002) { float temp = clamp(weightedTemp / max(rawField, 0.0001), 0.0, 1.0); float depth = clamp((field - 1.0) / 1.85, 0.0, 1.0); float thinness = pow(max(1.0 - depth, 0.0001), 1.55); // 3D normal derived from metaball field gradient vec2 nXY = -grad / max(gradLen, 0.0001); vec3 N = normalize(vec3(nXY * (1.0 - depth * 0.72), 0.34 + depth * 1.15)); // --- Wax Shading When Lamp is ON --- // Temperature-mapped lava wax palette: cool deep ruby -> warm coral-crimson -> hot molten amber vec3 coolWax = vec3(0.68, 0.07, 0.24); vec3 midWax = vec3(0.98, 0.22, 0.13); vec3 hotWax = vec3(1.00, 0.64, 0.08); vec3 waxBaseOn = mix(coolWax, midWax, smoothstep(0.12, 0.60, temp)); waxBaseOn = mix(waxBaseOn, hotWax, smoothstep(0.55, 0.96, temp)); // Bottom bulb directional lighting (undersides glow hot orange-gold) vec3 Lbulb = normalize(vec3(-p.x * 0.9, -0.14 - uv.y, 0.42)); float wrapDiff = clamp(dot(N, Lbulb) * 0.58 + 0.48, 0.0, 1.0); float bulbFalloff = exp(-uv.y * 1.05) * 1.15 + 0.28; // Subsurface scattering: thin stretched necks & blob rims glow brighter vec3 sssCol = mix(vec3(1.0, 0.48, 0.16), vec3(1.0, 0.86, 0.34), temp * 0.65 + (1.0 - uv.y) * 0.35); vec3 sss = sssCol * thinness * bulbFalloff * (0.58 + 0.48 * temp); // Soft glossy specular from bulb + subtle upper-left room highlight vec3 V = vec3(0.0, 0.0, 1.0); vec3 Hbulb = normalize(Lbulb + V); float specBulb = pow(max(dot(N, Hbulb), 0.0001), 18.0) * 0.35 * bulbFalloff; vec3 Lroom = normalize(vec3(-0.62, 0.65, 0.82)); vec3 Hroom = normalize(Lroom + V); float specRoom = pow(max(dot(N, Hroom), 0.0001), 26.0) * 0.22; // Warm core richness vec3 waxOn = waxBaseOn * (0.42 + 0.72 * wrapDiff * bulbFalloff) + sss + vec3(1.0, 0.82, 0.48) * specBulb + vec3(1.0, 0.92, 0.90) * specRoom; // Bottom incandescent bounce right on the floor waxOn += vec3(1.0, 0.76, 0.24) * exp(-uv.y * 7.0) * 0.42; // --- Wax Shading When Lamp is OFF (cool matte waxy coral-berry in dim room) --- float roomDiff = clamp(dot(N, Lroom) * 0.55 + 0.45, 0.0, 1.0); vec3 waxOff = vec3(0.32, 0.10, 0.16) * (0.45 + 0.75 * roomDiff) + vec3(0.24, 0.22, 0.30) * pow(max(dot(N, Hroom), 0.0001), 20.0) * 0.28 + vec3(0.14, 0.08, 0.14) * thinness * 0.3; vec3 waxCol = mix(waxOff, waxOn, uLight); // Subtle cylindrical glass attenuation near edges waxCol *= (0.80 + 0.22 * nz); // Soft inner rim blending so wax looks submerged in tinted liquid float glassSubmerge = 0.08 + 0.14 * (1.0 - nz); waxCol = mix(waxCol, liquidCol * 1.15, glassSubmerge * 0.55); col = mix(bgCol, waxCol, waxAlpha); } // Curved glass wall internal rim reflection & refraction tint vec3 rimOn = mix(vec3(1.0, 0.62, 0.30), vec3(0.65, 0.35, 0.82), smoothstep(0.1, 0.85, uv.y)); vec3 rimOff = vec3(0.26, 0.29, 0.38); col += mix(rimOff, rimOn, uLight) * fresnel * (0.42 + 0.25 * uLight); // Warm glow escaping upward right at the bottom metal collar float collarGlow = exp(-uv.y * 22.0) * (0.5 + 0.5 * nz); col += vec3(1.0, 0.75, 0.32) * collarGlow * 0.55 * uLight; // Subtle cap shadow at very top of glass float capShadow = smoothstep(0.96, 1.0, uv.y); col *= (1.0 - 0.48 * capShadow); // Soft tone mapping so incandescent hot spots stay creamy and lush col = col / (1.0 + col * 0.26); gl_FragColor = vec4(col * bottleMask, bottleMask); } `; function initWebGL() { try { gl = waxCanvas.getContext('webgl', { alpha: true, premultipliedAlpha: true, antialias: false, depth: false, stencil: false, powerPreference: 'high-performance', }) || waxCanvas.getContext('experimental-webgl', { alpha: true, depth: false }); if (!gl) return false; const compile = (type, src) => { const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s); if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) { gl.deleteShader(s); return null; } return s; }; const vs = compile(gl.VERTEX_SHADER, VERT_SRC); const fs = compile(gl.FRAGMENT_SHADER, FRAG_SRC); if (!vs || !fs) return false; glProg = gl.createProgram(); gl.attachShader(glProg, vs); gl.attachShader(glProg, fs); gl.linkProgram(glProg); if (!gl.getProgramParameter(glProg, gl.LINK_STATUS)) return false; const buf = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buf); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ -1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1, ]), gl.STATIC_DRAW); const aPos = gl.getAttribLocation(glProg, 'aPos'); gl.enableVertexAttribArray(aPos); gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0); glLocs = { uRes: gl.getUniformLocation(glProg, 'uRes'), uTime: gl.getUniformLocation(glProg, 'uTime'), uLight: gl.getUniformLocation(glProg, 'uLight'), uHeat: gl.getUniformLocation(glProg, 'uHeat'), uCount: gl.getUniformLocation(glProg, 'uCount'), uBlobs: gl.getUniformLocation(glProg, 'uBlobs[0]'), uStretch: gl.getUniformLocation(glProg, 'uStretch[0]'), }; gl.useProgram(glProg); gl.disable(gl.DEPTH_TEST); gl.clearColor(0, 0, 0, 0); return true; } catch (_) { return false; } } function initFallback2D() { waxCtx2D = waxCanvas.getContext('2d'); fallbackBufCanvas = document.createElement('canvas'); fallbackBufCanvas.width = 92; fallbackBufCanvas.height = 200; fallbackBufCtx = fallbackBufCanvas.getContext('2d'); fallbackImgData = fallbackBufCtx.createImageData(92, 200); } function renderWaxWebGL() { const blobs = state.blobs; const count = Math.min(blobs.length, MAX_BLOBS); for (let i = 0; i < count; i++) { const b = blobs[i]; const o = i * 4; uBlobsArr[o] = b.x; uBlobsArr[o + 1] = b.y; uBlobsArr[o + 2] = b.m; uBlobsArr[o + 3] = b.temp; uStretchArr[i] = b.stretch; } gl.viewport(0, 0, waxCanvas.width, waxCanvas.height); gl.clear(gl.COLOR_BUFFER_BIT); gl.uniform2f(glLocs.uRes, waxCanvas.width, waxCanvas.height); gl.uniform1f(glLocs.uTime, state.time); gl.uniform1f(glLocs.uLight, state.bulbGlow); gl.uniform1f(glLocs.uHeat, state.heaterPower); gl.uniform1i(glLocs.uCount, count); gl.uniform4fv(glLocs.uBlobs, uBlobsArr); gl.uniform1fv(glLocs.uStretch, uStretchArr); gl.drawArrays(gl.TRIANGLES, 0, 6); } function renderWaxFallback2D() { const bw = fallbackBufCanvas.width; const bh = fallbackBufCanvas.height; const data = fallbackImgData.data; const blobs = state.blobs; const count = blobs.length; const light = state.bulbGlow; for (let py = 0; py < bh; py++) { const y = 1.0 - (py + 0.5) / bh; const halfW = HALF_W * bottleHalfWidthNorm(y); const inLiq = y <= LIQUID_TOP; for (let px = 0; px < bw; px++) { const idx = (py * bw + px) * 4; const x = ((px + 0.5) / bw - 0.5) * CANVAS_ASPECT; if (Math.abs(x) > halfW) { data[idx + 3] = 0; continue; } const nx = x / halfW; const nz = Math.sqrt(Math.max(0, 1 - nx * nx)); // Liquid background let r, g, b; if (inLiq) { const rOn = lerp(245, lerp(110, 26, y), smoothstep(0, 0.45, y)); const gOn = lerp(135, lerp(22, 10, y), smoothstep(0, 0.45, y)); const bOn = lerp(35, lerp(76, 54, y), smoothstep(0, 0.45, y)); const dim = 0.65 + 0.35 * nz; r = lerp(18 + 14 * nz, rOn * dim, light); g = lerp(16 + 12 * nz, gOn * dim, light); b = lerp(26 + 18 * nz, bOn * dim, light); } else { r = lerp(20, 38, light); g = lerp(20, 22, light); b = lerp(28, 48, light); } // Metaball evaluation let field = 0; let wTemp = 0; let gx = 0; let gy = 0; if (inLiq && Math.abs(x) < halfW - 0.005) { for (let i = 0; i < count; i++) { const bl = blobs[i]; const dx = (x - bl.x) * bl.stretch; const dy = (y - bl.y) / bl.stretch; const denom = dx * dx + dy * dy + 0.00028; const w = bl.m / denom; field += w; wTemp += w * bl.temp; const k = -2 * w / denom; gx += k * dx * bl.stretch; gy += k * dy / bl.stretch; } } if (field > 0.92) { const alpha = clamp((field - 0.92) / 0.16, 0, 1); const temp = wTemp / field; const depth = clamp((field - 1.0) / 1.8, 0, 1); const thin = Math.pow(1 - depth, 1.5); const gLen = Math.hypot(gx, gy) + 1e-4; const ny = -gy / gLen; const bulbShade = clamp(0.55 - ny * 0.42, 0.15, 1.0) * (Math.exp(-y * 1.1) * 1.0 + 0.35); const wrOn = lerp(175, 255, temp) * bulbShade + 255 * thin * 0.42 * (1.1 - y * 0.5); const wgOn = lerp(22, 165, temp) * bulbShade + 185 * thin * 0.42 * (1.1 - y * 0.5); const wbOn = lerp(60, 26, temp) * bulbShade + 60 * thin * 0.3; const wrOff = 78 * (0.65 + 0.35 * depth); const wgOff = 28 * (0.65 + 0.35 * depth); const wbOff = 44 * (0.65 + 0.35 * depth); const wr = clamp(lerp(wrOff, wrOn, light), 0, 255); const wg = clamp(lerp(wgOff, wgOn, light), 0, 255); const wb = clamp(lerp(wbOff, wbOn, light), 0, 255); r = lerp(r, wr, alpha); g = lerp(g, wg, alpha); b = lerp(b, wb, alpha); } data[idx] = clamp(r, 0, 255); data[idx + 1] = clamp(g, 0, 255); data[idx + 2] = clamp(b, 0, 255); data[idx + 3] = 255; } } fallbackBufCtx.putImageData(fallbackImgData, 0, 0); waxCtx2D.clearRect(0, 0, waxCanvas.width, waxCanvas.height); waxCtx2D.imageSmoothingEnabled = true; waxCtx2D.drawImage(fallbackBufCanvas, 0, 0, waxCanvas.width, waxCanvas.height); } /* ============================================================ * Responsive Layout Computation (Phone Portrait, Landscape, Desktop) * ============================================================ */ function computeLayout() { const vw = window.innerWidth; const vh = window.innerHeight; dpr = Math.min(window.devicePixelRatio || 1, 2); const isPortraitPhone = vw < 540 && vh > vw; // Desk plane & lamp base stance const deskTopY = Math.round(isPortraitPhone ? vh * 0.735 : vh * 0.765); const baseBottomY = Math.round(isPortraitPhone ? vh * 0.805 : vh * 0.852); const topMargin = Math.max(18, Math.round(vh * 0.052)); // Lamp total height = cap(0.165) + glass(1.00) + base(0.42) = 1.585 * glassH const maxLampH = Math.max(180, baseBottomY - topMargin); const widthConstrainedH = (vw * (isPortraitPhone ? 0.50 : 0.42)) / BOTTLE_ASPECT * 1.585; const lampH = Math.min(maxLampH, widthConstrainedH); const glassH = Math.round(lampH / 1.585); const bellyW = glassH * BOTTLE_ASPECT; const glassBoxW = Math.round(glassH * CANVAS_ASPECT); const capH = Math.round(glassH * 0.165); const baseH = Math.round(glassH * 0.42); const cx = Math.round(vw * 0.5); const glassBottomY = baseBottomY - baseH; const glassTopY = glassBottomY - glassH; const glassLeftX = Math.round(cx - glassBoxW * 0.5); const baseTopHalfW = bellyW * 0.5 * 0.76; const baseWaistHalfW = bellyW * 0.5 * 0.49; const baseBottomHalfW = bellyW * 0.5 * 1.05; // Tactile inline power switch position on the desk let switchX, switchY; if (isPortraitPhone) { // Comfortably centered-slightly-right on the desk foreground for thumb reach const spaceBelow = vh - baseBottomY; switchX = Math.round(cx); switchY = Math.round(baseBottomY + Math.min(spaceBelow * 0.52, Math.max(46, spaceBelow - 44))); } else { const offset = Math.min(138, Math.max(82, baseBottomHalfW + 78)); switchX = Math.round(Math.min(vw - 74, cx + offset)); switchY = Math.round(baseBottomY - 8); } layout = { vw, vh, dpr, isPortraitPhone, cx, deskTopY, baseBottomY, glassH, glassBoxW, glassLeftX, glassTopY, glassBottomY, bellyW, capH, baseH, baseTopHalfW, baseWaistHalfW, baseBottomHalfW, switchX, switchY, }; // Size canvases cleanly bgCanvas.width = Math.round(vw * dpr); bgCanvas.height = Math.round(vh * dpr); fgCanvas.width = Math.round(vw * dpr); fgCanvas.height = Math.round(vh * dpr); waxCanvas.style.left = `${glassLeftX}px`; waxCanvas.style.top = `${glassTopY}px`; waxCanvas.style.width = `${glassBoxW}px`; waxCanvas.style.height = `${glassH}px`; waxCanvas.width = Math.max(1, Math.round(glassBoxW * dpr)); waxCanvas.height = Math.max(1, Math.round(glassH * dpr)); // Position switch on desk switchWrap.style.left = `${switchX}px`; switchWrap.style.top = `${switchY}px`; // Rebuild cached wood grain only when desk dimensions change const deskH = vh - deskTopY; const cacheKey = `${vw}x${deskH}`; if (cacheKey !== woodCacheKey) { woodCacheKey = cacheKey; woodPatternCanvas = buildWoodCanvas(vw, deskH); } } /* ============================================================ * Helper: Trace Exact Glass Bottle Path in Screen Coords * ============================================================ */ function traceBottlePath(ctx, insetPx = 0) { const { cx, glassTopY, glassH, bellyW } = layout; const steps = 40; const maxHalf = bellyW * 0.5; ctx.beginPath(); // Right contour top -> bottom for (let i = 0; i <= steps; i++) { const yNorm = 1.0 - i / steps; const py = glassTopY + (1.0 - yNorm) * glassH; const hw = Math.max(2, maxHalf * bottleHalfWidthNorm(yNorm) - insetPx); const px = cx + hw; if (i === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py); } // Left contour bottom -> top for (let i = 0; i <= steps; i++) { const yNorm = i / steps; const py = glassTopY + (1.0 - yNorm) * glassH; const hw = Math.max(2, maxHalf * bottleHalfWidthNorm(yNorm) - insetPx); ctx.lineTo(cx - hw, py); } ctx.closePath(); } /* ============================================================ * Background Scene Renderer (Wall Glow, Desk, Cord, Metal Base) * ============================================================ */ function renderBackground() { const ctx = bgCtx; const { vw, vh, dpr, cx, deskTopY, baseBottomY, glassTopY, glassBottomY, glassH, bellyW, baseH, baseTopHalfW, baseWaistHalfW, baseBottomHalfW, switchX, switchY, isPortraitPhone, } = layout; const light = state.bulbGlow; const pulse = 0.96 + 0.04 * Math.sin(state.time * 1.15) + 0.04 * (state.avgWaxWarmth - 0.5); const L = light * pulse; ctx.save(); ctx.scale(dpr, dpr); // 1. Evening Room Wall const wallGrad = ctx.createLinearGradient(0, 0, 0, deskTopY); wallGrad.addColorStop(0, '#090910'); wallGrad.addColorStop(0.65, '#100f1a'); wallGrad.addColorStop(1, '#16131f'); ctx.fillStyle = wallGrad; ctx.fillRect(0, 0, vw, deskTopY + 2); // Warm wall glow halo cast behind the glowing glass bottle if (L > 0.005) { const haloY = glassTopY + glassH * (0.58 - state.avgWaxY * 0.14); const haloR = Math.max(glassH * 0.92, bellyW * 2.15); const outerHalo = ctx.createRadialGradient(cx, haloY, bellyW * 0.1, cx, haloY, haloR); outerHalo.addColorStop(0, `rgba(255, 112, 42, ${0.30 * L})`); outerHalo.addColorStop(0.32, `rgba(218, 46, 86, ${0.18 * L})`); outerHalo.addColorStop(0.66, `rgba(98, 28, 92, ${0.08 * L})`); outerHalo.addColorStop(1, 'rgba(18, 12, 28, 0)'); ctx.fillStyle = outerHalo; ctx.fillRect(0, 0, vw, deskTopY + 2); // Tighter amber glow near the lower belly const lowerHalo = ctx.createRadialGradient(cx, glassBottomY - glassH * 0.16, 4, cx, glassBottomY - glassH * 0.16, bellyW * 1.55); lowerHalo.addColorStop(0, `rgba(255, 168, 68, ${0.28 * L})`); lowerHalo.addColorStop(0.55, `rgba(235, 76, 38, ${0.10 * L})`); lowerHalo.addColorStop(1, 'rgba(235, 76, 38, 0)'); ctx.fillStyle = lowerHalo; ctx.fillRect(0, 0, vw, deskTopY + 2); } // Subtle wall horizon shadow where desk meets wall const wallSeam = ctx.createLinearGradient(0, deskTopY - 22, 0, deskTopY); wallSeam.addColorStop(0, 'rgba(0,0,0,0)'); wallSeam.addColorStop(1, 'rgba(0,0,0,0.52)'); ctx.fillStyle = wallSeam; ctx.fillRect(0, deskTopY - 22, vw, 22); // 2. Wooden Desk Surface if (woodPatternCanvas) { ctx.drawImage(woodPatternCanvas, 0, deskTopY, vw, vh - deskTopY); } // Warm light pool spilled across the polished walnut desk when ON if (L > 0.005) { const deskSurfaceH = (vh - deskTopY) * 0.80; ctx.save(); ctx.beginPath(); ctx.rect(0, deskTopY, vw, deskSurfaceH); ctx.clip(); // Elliptical glow pool on tabletop ctx.save(); ctx.translate(cx, baseBottomY - 6); ctx.scale(1.0, 0.34); const poolR = Math.max(bellyW * 2.5, vw * 0.38); const deskPool = ctx.createRadialGradient(0, 0, baseBottomHalfW * 0.6, 0, 0, poolR); deskPool.addColorStop(0, `rgba(255, 152, 62, ${0.38 * L})`); deskPool.addColorStop(0.35, `rgba(225, 74, 48, ${0.20 * L})`); deskPool.addColorStop(0.7, `rgba(128, 32, 62, ${0.08 * L})`); deskPool.addColorStop(1, 'rgba(0, 0, 0, 0)'); ctx.fillStyle = deskPool; ctx.beginPath(); ctx.arc(0, 0, poolR, 0, Math.PI * 2); ctx.fill(); ctx.restore(); // Subtle glossy wood reflection shimmering below base const reflGrad = ctx.createRadialGradient(cx, baseBottomY + 12, 4, cx, baseBottomY + 18, baseBottomHalfW * 1.9); reflGrad.addColorStop(0, `rgba(255, 178, 96, ${0.20 * L})`); reflGrad.addColorStop(0.6, `rgba(230, 84, 52, ${0.07 * L})`); reflGrad.addColorStop(1, 'rgba(0,0,0,0)'); ctx.fillStyle = reflGrad; ctx.fillRect(cx - baseBottomHalfW * 2.2, deskTopY, baseBottomHalfW * 4.4, deskSurfaceH); ctx.restore(); } // 3. Braided Power Cord on Desk (Base -> Switch -> Right Desk Edge) drawPowerCord(ctx, L, isPortraitPhone, cx, baseBottomY, baseBottomHalfW, switchX, switchY, vw, deskTopY); // 4. Grounding Contact Shadow Beneath Lamp Base ctx.save(); ctx.translate(cx, baseBottomY + 2); ctx.scale(1.0, 0.24); const shGrad = ctx.createRadialGradient(0, 0, baseBottomHalfW * 0.25, 0, 0, baseBottomHalfW * 1.48); shGrad.addColorStop(0, 'rgba(0, 0, 0, 0.85)'); shGrad.addColorStop(0.68, 'rgba(0, 0, 0, 0.56)'); shGrad.addColorStop(1, 'rgba(0, 0, 0, 0)'); ctx.fillStyle = shGrad; ctx.beginPath(); ctx.arc(0, 0, baseBottomHalfW * 1.48, 0, Math.PI * 2); ctx.fill(); ctx.restore(); // 5. Spun Brushed-Metal Hourglass Base drawMetalBase(ctx, L, cx, glassBottomY, baseBottomY, baseH, baseTopHalfW, baseWaistHalfW, baseBottomHalfW); ctx.restore(); } function drawPowerCord(ctx, L, isPortraitPhone, cx, baseBottomY, baseBottomHalfW, switchX, switchY, vw, deskTopY) { const startX = cx + baseBottomHalfW * 0.74; const startY = baseBottomY - 6; ctx.save(); ctx.lineCap = 'round'; const drawPath = (offsetY) => { ctx.beginPath(); if (isPortraitPhone) { // Cord loops cleanly from right-rear of base around to the front desk switch, then trails off right const c1x = startX + 38; const c1y = startY + 2 + offsetY; const c2x = switchX + 66; const c2y = switchY - 4 + offsetY; ctx.moveTo(startX, startY + offsetY); ctx.bezierCurveTo(c1x, c1y, c2x, c2y, switchX + 36, switchY + offsetY); // Trailing cord from left of switch curving smoothly behind/off right edge ctx.moveTo(switchX - 42, switchY + offsetY); ctx.bezierCurveTo(switchX - 96, switchY + 4 + offsetY, cx - baseBottomHalfW * 1.6, baseBottomY - 12 + offsetY, -10, deskTopY + 12 + offsetY); } else { // Cord flows naturally from back-right of base into left of inline switch, then off right desk edge ctx.moveTo(startX, startY + offsetY); ctx.bezierCurveTo( startX + 26, startY + 8 + offsetY, switchX - 66, switchY + 6 + offsetY, switchX - 40, switchY + offsetY ); ctx.moveTo(switchX + 42, switchY + offsetY); ctx.bezierCurveTo( switchX + 100, switchY - 2 + offsetY, vw - 40, deskTopY + 24 + offsetY, vw + 12, deskTopY + 16 + offsetY ); } }; // Soft shadow on wood drawPath(4.5); ctx.strokeStyle = 'rgba(0, 0, 0, 0.56)'; ctx.lineWidth = 6.5; ctx.stroke(); // Matte dark cord body drawPath(0); ctx.strokeStyle = '#18161b'; ctx.lineWidth = 4.4; ctx.stroke(); // Subtle top sheen catching lamp light drawPath(-1.0); ctx.strokeStyle = L > 0.05 ? `rgba(185, 130, 96, ${0.14 + 0.16 * L})` : 'rgba(130, 135, 155, 0.14)'; ctx.lineWidth = 1.2; ctx.stroke(); ctx.restore(); } function drawMetalBase(ctx, L, cx, topY, bottomY, baseH, topHW, waistHW, botHW) { const waistY = topY + baseH * 0.36; const traceBase = () => { ctx.beginPath(); // Top collar rim ctx.moveTo(cx - topHW, topY); ctx.lineTo(cx + topHW, topY); // Right upper cone down to narrow waist ctx.bezierCurveTo( cx + topHW * 0.94, topY + baseH * 0.16, cx + waistHW * 1.06, waistY - baseH * 0.08, cx + waistHW, waistY ); // Right lower skirt flaring to desk ctx.bezierCurveTo( cx + waistHW * 1.02, waistY + baseH * 0.14, cx + botHW * 0.92, bottomY - baseH * 0.22, cx + botHW, bottomY - 4 ); // Rounded bottom ellipse lip sitting on desk ctx.quadraticCurveTo(cx + botHW, bottomY + 1, cx + botHW - 5, bottomY + 2); ctx.quadraticCurveTo(cx, bottomY + 7, cx - botHW + 5, bottomY + 2); ctx.quadraticCurveTo(cx - botHW, bottomY + 1, cx - botHW, bottomY - 4); // Left lower skirt up to waist ctx.bezierCurveTo( cx - botHW * 0.92, bottomY - baseH * 0.22, cx - waistHW * 1.02, waistY + baseH * 0.14, cx - waistHW, waistY ); // Left upper cone up to collar ctx.bezierCurveTo( cx - waistHW * 1.06, waistY - baseH * 0.08, cx - topHW * 0.94, topY + baseH * 0.16, cx - topHW, topY ); ctx.closePath(); }; ctx.save(); traceBase(); // Brushed satin silver-pewter metallic horizontal gradient const metalGrad = ctx.createLinearGradient(cx - botHW, topY, cx + botHW, topY); const warmR = lerp(0, 38, L); const warmG = lerp(0, 14, L); const rgb = (r, g, b) => `rgb(${Math.round(r)}, ${Math.round(g)}, ${Math.round(b)})`; metalGrad.addColorStop(0.00, rgb(26 + warmR * 0.2, 27 + warmG * 0.2, 34)); metalGrad.addColorStop(0.16, rgb(78 + warmR * 0.5, 80 + warmG * 0.4, 92)); metalGrad.addColorStop(0.32, rgb(178 + warmR * 0.7, 180 + warmG * 0.6, 192)); metalGrad.addColorStop(0.41, rgb(224 + warmR * 0.6, 222 + warmG * 0.5, 230)); metalGrad.addColorStop(0.54, rgb(112 + warmR * 0.5, 112 + warmG * 0.4, 124)); metalGrad.addColorStop(0.76, rgb(44 + warmR * 0.3, 44 + warmG * 0.2, 54)); metalGrad.addColorStop(0.92, rgb(84 + warmR * 0.4, 78 + warmG * 0.3, 88)); metalGrad.addColorStop(1.00, rgb(28 + warmR * 0.2, 28 + warmG * 0.1, 35)); ctx.fillStyle = metalGrad; ctx.fill(); ctx.clip(); // Vertical waist crease shadow & subtle specular shift const vShade = ctx.createLinearGradient(0, topY, 0, bottomY); vShade.addColorStop(0.00, 'rgba(0, 0, 0, 0.25)'); vShade.addColorStop(0.28, 'rgba(0, 0, 0, 0.36)'); vShade.addColorStop(0.37, 'rgba(255, 255, 255, 0.14)'); vShade.addColorStop(0.55, 'rgba(0, 0, 0, 0.06)'); vShade.addColorStop(0.90, 'rgba(0, 0, 0, 0.18)'); vShade.addColorStop(1.00, 'rgba(0, 0, 0, 0.52)'); ctx.fillStyle = vShade; ctx.fillRect(cx - botHW - 4, topY, botHW * 2 + 8, baseH + 10); // Warm orange-amber bounce light on the upper cup from the glowing glass above if (L > 0.01) { const collarBounce = ctx.createLinearGradient(0, topY, 0, topY + baseH * 0.36); collarBounce.addColorStop(0, `rgba(255, 165, 72, ${0.46 * L})`); collarBounce.addColorStop(0.45, `rgba(235, 92, 38, ${0.16 * L})`); collarBounce.addColorStop(1, 'rgba(235, 92, 38, 0)'); ctx.fillStyle = collarBounce; ctx.fillRect(cx - topHW - 4, topY, topHW * 2 + 8, baseH * 0.4); // Warm reflection on the lower skirt from the lit desk const deskBounce = ctx.createLinearGradient(0, bottomY - baseH * 0.35, 0, bottomY + 6); deskBounce.addColorStop(0, 'rgba(255, 128, 52, 0)'); deskBounce.addColorStop(1, `rgba(255, 134, 58, ${0.26 * L})`); ctx.fillStyle = deskBounce; ctx.fillRect(cx - botHW - 4, bottomY - baseH * 0.35, botHW * 2 + 8, baseH * 0.42); } // Crisp horizontal spun-metal lathe line at waist ctx.strokeStyle = 'rgba(255, 255, 255, 0.12)'; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(cx - waistHW, waistY); ctx.lineTo(cx + waistHW, waistY); ctx.stroke(); ctx.restore(); } /* ============================================================ * Foreground Renderer (Glass Speculars, Collar Lip & Metal Cap) * ============================================================ */ function renderForeground() { const ctx = fgCtx; const { vw, vh, dpr, cx, glassTopY, glassBottomY, glassH, bellyW, capH, baseTopHalfW, } = layout; const L = state.bulbGlow; ctx.save(); ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, vw, vh); // 1. Glass Bottle Specular Highlights & Reflections (clipped to exact bottle) ctx.save(); traceBottlePath(ctx, 0.5); ctx.clip(); const maxHalf = bellyW * 0.5; const steps = 36; // Primary left curved window highlight (tracks exact bottle silhouette!) ctx.beginPath(); for (let i = 0; i <= steps; i++) { const yNorm = 0.04 + (i / steps) * 0.91; const py = glassTopY + (1.0 - yNorm) * glassH; const hw = maxHalf * bottleHalfWidthNorm(yNorm); const px = cx - hw * 0.72; if (i === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py); } for (let i = steps; i >= 0; i--) { const yNorm = 0.04 + (i / steps) * 0.91; const py = glassTopY + (1.0 - yNorm) * glassH; const hw = maxHalf * bottleHalfWidthNorm(yNorm); const px = cx - hw * 0.54; ctx.lineTo(px, py); } ctx.closePath(); const leftSpec = ctx.createLinearGradient(cx - maxHalf, glassTopY, cx - maxHalf * 0.4, glassBottomY); leftSpec.addColorStop(0, `rgba(255, 255, 255, ${0.14 + 0.08 * L})`); leftSpec.addColorStop(0.35, `rgba(255, 248, 242, ${0.22 + 0.12 * L})`); leftSpec.addColorStop(0.75, `rgba(255, 238, 224, ${0.16 + 0.10 * L})`); leftSpec.addColorStop(1, `rgba(255, 220, 190, ${0.05 + 0.06 * L})`); ctx.fillStyle = leftSpec; ctx.fill(); // Crisp thin razor specular thread along left edge ctx.beginPath(); for (let i = 0; i <= steps; i++) { const yNorm = 0.05 + (i / steps) * 0.89; const py = glassTopY + (1.0 - yNorm) * glassH; const hw = maxHalf * bottleHalfWidthNorm(yNorm); const px = cx - hw * 0.82; if (i === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py); } ctx.strokeStyle = `rgba(255, 255, 255, ${0.24 + 0.18 * L})`; ctx.lineWidth = Math.max(1.2, bellyW * 0.013); ctx.lineCap = 'round'; ctx.stroke(); // Softer secondary rim highlight on right glass edge ctx.beginPath(); for (let i = 0; i <= steps; i++) { const yNorm = 0.06 + (i / steps) * 0.88; const py = glassTopY + (1.0 - yNorm) * glassH; const hw = maxHalf * bottleHalfWidthNorm(yNorm); const px = cx + hw * 0.83; if (i === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py); } ctx.strokeStyle = L > 0.05 ? `rgba(255, 212, 184, ${0.12 + 0.16 * L})` : 'rgba(180, 195, 225, 0.13)'; ctx.lineWidth = Math.max(1.2, bellyW * 0.014); ctx.stroke(); ctx.restore(); // Subtle crisp glass outer outline traceBottlePath(ctx, 0.25); ctx.strokeStyle = L > 0.05 ? `rgba(255, 225, 200, ${0.10 + 0.14 * L})` : 'rgba(190, 200, 225, 0.12)'; ctx.lineWidth = 1; ctx.stroke(); // 2. Overlapping Base Collar Lip + Subtle Glowing Vent Line const collarW = baseTopHalfW + 1.5; if (L > 0.02) { // Warm halogen light peeking right at the glass-to-metal collar seam const seamGlow = ctx.createLinearGradient(cx - collarW, glassBottomY, cx + collarW, glassBottomY); seamGlow.addColorStop(0, 'rgba(255, 160, 64, 0)'); seamGlow.addColorStop(0.22, `rgba(255, 178, 78, ${0.65 * L})`); seamGlow.addColorStop(0.5, `rgba(255, 226, 145, ${0.95 * L})`); seamGlow.addColorStop(0.78, `rgba(255, 178, 78, ${0.65 * L})`); seamGlow.addColorStop(1, 'rgba(255, 160, 64, 0)'); ctx.strokeStyle = seamGlow; ctx.lineWidth = 2.6; ctx.beginPath(); ctx.moveTo(cx - collarW * 0.95, glassBottomY - 0.5); ctx.quadraticCurveTo(cx, glassBottomY + 2.2, cx + collarW * 0.95, glassBottomY - 0.5); ctx.stroke(); } // Metal collar front rim bevel overlapping the very bottom of glass ctx.beginPath(); ctx.moveTo(cx - collarW, glassBottomY + 1); ctx.quadraticCurveTo(cx, glassBottomY + 4.5, cx + collarW, glassBottomY + 1); ctx.lineTo(cx + collarW * 0.99, glassBottomY + 5); ctx.quadraticCurveTo(cx, glassBottomY + 8.5, cx - collarW * 0.99, glassBottomY + 5); ctx.closePath(); const lipGrad = ctx.createLinearGradient(cx - collarW, glassBottomY, cx + collarW, glassBottomY); lipGrad.addColorStop(0, '#22222b'); lipGrad.addColorStop(0.36, '#c8cad6'); lipGrad.addColorStop(0.68, '#464552'); lipGrad.addColorStop(1, '#202028'); ctx.fillStyle = lipGrad; ctx.fill(); // 3. Matching Brushed-Metal Tapered Cap Crowning the Glass drawMetalCap(ctx, L, cx, glassTopY, capH, bellyW); ctx.restore(); } function drawMetalCap(ctx, L, cx, glassTopY, capH, bellyW) { const botHW = bellyW * 0.5 * 0.505; const topHW = bellyW * 0.5 * 0.36; const capBottomY = glassTopY + 5; // overlaps top of glass cleanly const capTopY = capBottomY - capH; const rCorner = Math.max(3, capH * 0.11); ctx.save(); ctx.beginPath(); ctx.moveTo(cx - botHW, capBottomY); ctx.lineTo(cx - topHW, capTopY + rCorner); ctx.quadraticCurveTo(cx - topHW + 1, capTopY, cx - topHW + rCorner, capTopY); ctx.lineTo(cx + topHW - rCorner, capTopY); ctx.quadraticCurveTo(cx + topHW - 1, capTopY, cx + topHW, capTopY + rCorner); ctx.lineTo(cx + botHW, capBottomY); ctx.quadraticCurveTo(cx, capBottomY + 3.8, cx - botHW, capBottomY); ctx.closePath(); const warmR = lerp(0, 24, L); const warmG = lerp(0, 10, L); const rgb = (r, g, b) => `rgb(${Math.round(r)}, ${Math.round(g)}, ${Math.round(b)})`; const capGrad = ctx.createLinearGradient(cx - botHW, capTopY, cx + botHW, capTopY); capGrad.addColorStop(0.00, rgb(26 + warmR * 0.2, 27 + warmG * 0.2, 34)); capGrad.addColorStop(0.18, rgb(84 + warmR * 0.4, 86 + warmG * 0.3, 98)); capGrad.addColorStop(0.35, rgb(198 + warmR * 0.5, 198 + warmG * 0.4, 210)); capGrad.addColorStop(0.45, rgb(226 + warmR * 0.4, 225 + warmG * 0.3, 235)); capGrad.addColorStop(0.60, rgb(102 + warmR * 0.4, 102 + warmG * 0.3, 115)); capGrad.addColorStop(0.82, rgb(44 + warmR * 0.2, 44 + warmG * 0.2, 54)); capGrad.addColorStop(1.00, rgb(30 + warmR * 0.1, 30 + warmG * 0.1, 38)); ctx.fillStyle = capGrad; ctx.fill(); ctx.clip(); // Top crown sheen const topSheen = ctx.createLinearGradient(0, capTopY, 0, capTopY + capH * 0.22); topSheen.addColorStop(0, 'rgba(255, 255, 255, 0.28)'); topSheen.addColorStop(1, 'rgba(255, 255, 255, 0)'); ctx.fillStyle = topSheen; ctx.fillRect(cx - botHW, capTopY, botHW * 2, capH * 0.25); // Subtle glowing liquid reflection on underside rim of cap if (L > 0.02) { const capBounce = ctx.createLinearGradient(0, capBottomY - capH * 0.34, 0, capBottomY + 4); capBounce.addColorStop(0, 'rgba(200, 70, 120, 0)'); capBounce.addColorStop(1, `rgba(225, 92, 118, ${0.28 * L})`); ctx.fillStyle = capBounce; ctx.fillRect(cx - botHW, capBottomY - capH * 0.34, botHW * 2, capH * 0.38); } // Lower cap rim shadow edge ctx.strokeStyle = 'rgba(0, 0, 0, 0.55)'; ctx.lineWidth = 1.4; ctx.beginPath(); ctx.moveTo(cx - botHW, capBottomY); ctx.quadraticCurveTo(cx, capBottomY + 3.8, cx + botHW, capBottomY); ctx.stroke(); ctx.restore(); } /* ============================================================ * Switch & Glass Interactions * ============================================================ */ function toggleLamp() { state.isOn = !state.isOn; powerSwitch.classList.toggle('is-on', state.isOn); powerSwitch.setAttribute('aria-checked', String(state.isOn)); switchLabel.textContent = state.isOn ? 'ON' : 'OFF'; playSwitchClick(state.isOn); } powerSwitch.addEventListener('click', toggleLamp); // Keyboard shortcut: 'P' toggles power when not focused on button window.addEventListener('keydown', (e) => { if (e.key === 'p' || e.key === 'P') { toggleLamp(); } }); // Gentle tap/click on the glass bottle jostles the wax inside waxCanvas.addEventListener('pointerdown', (e) => { const rect = waxCanvas.getBoundingClientRect(); const nx = (e.clientX - rect.left) / rect.width; const ny = (e.clientY - rect.top) / rect.height; nudgeBlobsAt(nx, ny); }); /* ============================================================ * Main 60 FPS Animation Loop * ============================================================ */ let lastFrameTime = performance.now(); let lastRenderedFgLight = -1; let fgDirty = true; function frame(now) { const rawDt = (now - lastFrameTime) * 0.001; lastFrameTime = now; const dt = Math.min(Math.max(rawDt, 0.001), 0.05); state.time += dt; // Substep physics if frame delta is slightly large for rock-solid smoothness if (dt > 0.025) { stepPhysics(dt * 0.5); stepPhysics(dt * 0.5); } else { stepPhysics(dt); } // Render background (live desk light pool + wall halo) renderBackground(); // Render glowing bottle interior & wax metaballs if (useWebGL) { renderWaxWebGL(); } else { renderWaxFallback2D(); } // Redraw foreground glass reflections & cap only when light level changes or resized if (fgDirty || Math.abs(state.bulbGlow - lastRenderedFgLight) > 0.002) { renderForeground(); lastRenderedFgLight = state.bulbGlow; fgDirty = false; } requestAnimationFrame(frame); } /* ============================================================ * Bootstrap * ============================================================ */ initWarmBlobs(); useWebGL = initWebGL(); if (!useWebGL) { initFallback2D(); } computeLayout(); fgDirty = true; let resizeTimer = 0; window.addEventListener('resize', () => { computeLayout(); fgDirty = true; clearTimeout(resizeTimer); resizeTimer = setTimeout(() => { computeLayout(); fgDirty = true; }, 120); }); // Handle WebGL context loss gracefully waxCanvas.addEventListener('webglcontextlost', (e) => { e.preventDefault(); }); waxCanvas.addEventListener('webglcontextrestored', () => { useWebGL = initWebGL(); if (!useWebGL && !waxCtx2D) initFallback2D(); computeLayout(); fgDirty = true; }); requestAnimationFrame(frame);})();</script></body></html>