Skip to content
VibeCodeBench
Back to the app

The code

Lantern Cats by Claude Opus 5.5

Exactly as the AI wrote it. Shown as text, so nothing runs on this page.

index.html

works · auto-checked (Checked by an automated pass. Not hand-played yet.)50.1 KB · 1,042 lines · loads cdn.jsdelivr.net/npm/[email protected]/build/three.module.js, cdn.jsdelivr.net/npm/[email protected]/examples/jsm/
Download
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover">
<meta name="theme-color" content="#05060f">
<title>Lantern Cats · Festival Night</title>
<style>
*{box-sizing:border-box}
html,body{margin:0;height:100%;overflow:hidden;background:#05060f;touch-action:none;-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}
canvas{display:block;position:fixed;left:0;top:0;width:100%;height:100%;touch-action:none;outline:none}
#mute{position:fixed;top:calc(14px + env(safe-area-inset-top));right:calc(14px + env(safe-area-inset-right));width:64px;height:64px;border-radius:50%;border:2px solid rgba(255,214,160,.55);background:rgba(18,14,36,.55);color:#ffe0b0;display:flex;align-items:center;justify-content:center;padding:0;margin:0;cursor:pointer;z-index:5;touch-action:manipulation;-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px);box-shadow:0 0 18px rgba(255,170,90,.25)}
#mute:active{transform:scale(.94)}
#mute svg{width:30px;height:30px;pointer-events:none}
#hint{position:fixed;left:50%;bottom:calc(20px + env(safe-area-inset-bottom));transform:translateX(-50%);max-width:92vw;color:#ffe6c4;font:600 16px/1.35 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;background:rgba(18,14,36,.55);padding:12px 20px;border-radius:26px;text-align:center;pointer-events:none;transition:opacity 1.2s;z-index:4;text-shadow:0 1px 6px rgba(0,0,0,.6)}
#ghost{position:fixed;left:0;top:0;width:58px;height:58px;margin:-29px 0 0 -29px;border-radius:50%;border:3px solid rgba(255,244,225,.9);background:radial-gradient(circle,rgba(255,236,200,.45),rgba(255,200,140,0) 70%);box-shadow:0 0 20px rgba(255,200,140,.8);pointer-events:none;display:none;z-index:4}
</style>
</head>
<body>
<button id="mute" type="button" aria-label="Mute music">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3.5 9.5h3.8L12 5.5v13l-4.7-4H3.5z" fill="currentColor"/><g id="waves"><path d="M15.5 9a4.5 4.5 0 0 1 0 6"/><path d="M18.3 6.3a8.3 8.3 0 0 1 0 11.4"/></g><g id="cross" style="display:none"><path d="M16 9.5l5 5M21 9.5l-5 5"/></g></svg>
</button>
<div id="hint">Touch or drag — a cat will follow</div>
<div id="ghost"></div>
<script type="importmap">{"imports":{"three":"https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js","three/addons/":"https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/"}}</script>
<script type="module">
import * as THREE from 'three';
import { Reflector } from 'three/addons/objects/Reflector.js';

/* ---------------- utils ---------------- */
const $ = id => document.getElementById(id);
const hintEl = $('hint'), ghostEl = $('ghost'), muteBtn = $('mute');
const DEMO = location.hash === '#demo';
const SMALL = innerWidth < 700 || Math.min(innerWidth, innerHeight) < 500;
function mulberry32(a){ return function(){ a|=0; a=a+0x6D2B79F5|0; let t=Math.imul(a^a>>>15,1|a); t=t+Math.imul(t^t>>>7,61|t)^t; return ((t^t>>>14)>>>0)/4294967296; }; }
const rnd = mulberry32(7741);
const R = (a,b) => a + (b-a)*rnd();
const MR = (a,b) => a + (b-a)*Math.random();
const clamp = (x,a,b) => x<a?a:(x>b?b:x);
const lerp = (a,b,t) => a+(b-a)*t;
const sstep = x => x*x*(3-2*x);
const V3 = THREE.Vector3;
const UP = new V3(0,1,0), ZAX = new V3(0,0,1), ZERO = new V3();
const _a=new V3(), _b=new V3(), _d=new V3(), _e=new V3(), _f=new V3();
const t1=new V3(), t2=new V3(), t3=new V3(), t4=new V3(), t5=new V3();
const _q=new THREE.Quaternion(), _q2=new THREE.Quaternion(), _m=new THREE.Matrix4(), _s=new V3(), _col=new THREE.Color();
const WHITE = new THREE.Color('#ffffff');
let T = 0;

/* ---------------- setup ---------------- */
let renderer;
try { renderer = new THREE.WebGLRenderer({ antialias:true, powerPreference:'high-performance' }); }
catch(e){ hintEl.textContent = 'Sorry — WebGL is not available here.'; throw e; }
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.setClearColor(0x05060f);
document.body.prepend(renderer.domElement);
const canvas = renderer.domElement;
const scene = new THREE.Scene();
scene.fog = new THREE.FogExp2(0x161230, 0.011);
const camera = new THREE.PerspectiveCamera(50, innerWidth/innerHeight, 0.1, 600);
camera.position.set(0,5,32);

const U = { uScale:{ value:800 }, uTime:{ value:0 } };

/* ---------------- canvas textures & shared materials ---------------- */
function canvasTex(w,h,draw){ const c=document.createElement('canvas'); c.width=w; c.height=h; draw(c.getContext('2d'),w,h); const t=new THREE.CanvasTexture(c); t.colorSpace=THREE.SRGBColorSpace; return t; }
const paperTex = canvasTex(64,128,(g,w,h)=>{
  const gr=g.createLinearGradient(0,0,0,h);
  gr.addColorStop(0,'#7a5a40'); gr.addColorStop(.14,'#e2cfae'); gr.addColorStop(.5,'#fffaf0'); gr.addColorStop(.86,'#e2cfae'); gr.addColorStop(1,'#7a5a40');
  g.fillStyle=gr; g.fillRect(0,0,w,h);
  g.strokeStyle='rgba(110,80,50,.28)'; g.lineWidth=2;
  for(const f of [.3,.5,.7]){ g.beginPath(); g.moveTo(0,f*h); g.lineTo(w,f*h); g.stroke(); }
  g.globalAlpha=.07; g.fillStyle='#6b4a2a';
  for(let i=0;i<36;i++) g.fillRect(Math.random()*w,0,1,h);
});
const winTex = canvasTex(32,32,(g)=>{
  g.fillStyle='#fff'; g.fillRect(0,0,32,32);
  g.fillStyle='rgba(70,35,12,.7)'; g.fillRect(14,0,4,32); g.fillRect(0,14,32,4);
  g.strokeStyle='rgba(60,30,10,.85)'; g.lineWidth=4; g.strokeRect(0,0,32,32);
});
const moonTex = canvasTex(256,256,(g,w,h)=>{
  const gr=g.createRadialGradient(128,128,0,128,128,128);
  gr.addColorStop(0,'rgba(255,252,236,1)'); gr.addColorStop(.11,'rgba(255,246,222,1)'); gr.addColorStop(.135,'rgba(255,226,180,.38)');
  gr.addColorStop(.35,'rgba(170,150,220,.10)'); gr.addColorStop(1,'rgba(0,0,0,0)');
  g.fillStyle=gr; g.fillRect(0,0,w,h);
});

// glowing paper lantern shader (works for instanced and plain meshes)
function lanternMat(color, side){
  return new THREE.ShaderMaterial({
    uniforms:{ map:{ value:paperTex }, uColor:{ value:new THREE.Color(color) } },
    vertexShader:`
      uniform vec3 uColor;
      varying vec2 vUv; varying vec3 vN; varying vec3 vV; varying vec3 vC;
      void main(){
        mat4 m = modelMatrix;
        #ifdef USE_INSTANCING
          m = m * instanceMatrix;
        #endif
        vec4 wp = m * vec4(position,1.0);
        vN = normalize(mat3(m) * normal);
        vV = cameraPosition - wp.xyz;
        vUv = uv;
        vC = uColor;
        #ifdef USE_INSTANCING_COLOR
          vC *= instanceColor;
        #endif
        gl_Position = projectionMatrix * viewMatrix * wp;
      }`,
    fragmentShader:`
      uniform sampler2D map;
      varying vec2 vUv; varying vec3 vN; varying vec3 vV; varying vec3 vC;
      void main(){
        vec3 t = texture2D(map, vUv).rgb;
        float f = abs(dot(normalize(vN), normalize(vV)));
        vec3 c = vC * t * (0.35 + 0.85*f) + vC * 0.25 * pow(1.0 - f, 3.0);
        gl_FragColor = vec4(c, 1.0);
        #include <colorspace_fragment>
      }`,
    side: side || THREE.FrontSide
  });
}

// shared additive glow points
function pointsMat(tw){
  return new THREE.ShaderMaterial({
    uniforms:{ uScale:U.uScale, uTime:U.uTime, uTw:{ value:tw } },
    vertexShader:`
      attribute float aSize; attribute vec4 aColor;
      uniform float uScale; uniform float uTime; uniform float uTw;
      varying vec4 vC;
      void main(){
        vec4 mv = modelViewMatrix * vec4(position,1.0);
        gl_Position = projectionMatrix * mv;
        float tw = 1.0 - uTw * (0.45 + 0.45*sin(uTime*(1.3 + fract(position.x*7.13)*2.7) + position.z*3.1 + position.y*1.7));
        vC = vec4(aColor.rgb, aColor.a * tw);
        gl_PointSize = aColor.a <= 0.001 ? 0.0 : clamp(aSize * uScale / max(-mv.z, 0.1), 1.0, 300.0);
      }`,
    fragmentShader:`
      varying vec4 vC;
      void main(){
        vec2 p = gl_PointCoord*2.0 - 1.0;
        float d = dot(p,p);
        if (d > 1.0) discard;
        float a = exp(-d*7.0) + 0.25*(1.0-d)*(1.0-d);
        gl_FragColor = vec4(vC.rgb * a * vC.a, 1.0);
        #include <colorspace_fragment>
      }`,
    blending:THREE.AdditiveBlending, depthWrite:false, transparent:true
  });
}
function makePoints(n, tw){
  const g=new THREE.BufferGeometry();
  const P=new Float32Array(n*3), S=new Float32Array(n), C=new Float32Array(n*4);
  g.setAttribute('position', new THREE.BufferAttribute(P,3));
  g.setAttribute('aSize', new THREE.BufferAttribute(S,1));
  g.setAttribute('aColor', new THREE.BufferAttribute(C,4));
  const o=new THREE.Points(g, pointsMat(tw)); o.frustumCulled=false; scene.add(o);
  return { o, P, S, C, n,
    set(i,x,y,z,s,col,a){ P[i*3]=x; P[i*3+1]=y; P[i*3+2]=z; S[i]=s; C[i*4]=col.r; C[i*4+1]=col.g; C[i*4+2]=col.b; C[i*4+3]=a; },
    dirty(){ g.attributes.position.needsUpdate=true; g.attributes.aSize.needsUpdate=true; g.attributes.aColor.needsUpdate=true; } };
}

const latheProfile = [[0,-.5],[.6,-.5],[.8,-.43],[.94,-.27],[1,0],[.94,.27],[.8,.43],[.6,.5],[0,.5]].map(p=>new THREE.Vector2(p[0],p[1]));
const segGeo = new THREE.LatheGeometry(latheProfile, 14);

/* ---------------- sky ---------------- */
const sky = new THREE.Mesh(new THREE.SphereGeometry(300,32,16), new THREE.ShaderMaterial({
  side:THREE.BackSide, depthWrite:false,
  uniforms:{ top:{ value:new THREE.Color('#070a1f') }, mid:{ value:new THREE.Color('#141433') }, hor:{ value:new THREE.Color('#2b1d3d') } },
  vertexShader:`varying vec3 vD; void main(){ vD = position; gl_Position = projectionMatrix*modelViewMatrix*vec4(position,1.0); }`,
  fragmentShader:`uniform vec3 top; uniform vec3 mid; uniform vec3 hor; varying vec3 vD;
    void main(){ float h = abs(normalize(vD).y);
      vec3 c = mix(hor, mid, smoothstep(0.0,0.2,h)); c = mix(c, top, smoothstep(0.15,0.8,h));
      gl_FragColor = vec4(c,1.0);
      #include <colorspace_fragment>
    }`
}));
sky.renderOrder = -10; scene.add(sky);

const moon = new THREE.Sprite(new THREE.SpriteMaterial({ map:moonTex, fog:false, depthWrite:false, transparent:true, blending:THREE.AdditiveBlending }));
moon.position.set(-75,92,-230); moon.scale.set(80,80,1); scene.add(moon);

const NST = SMALL ? 450 : 700;
const stars = makePoints(NST, 1);
for (let i=0;i<NST;i++){
  const y = 0.06 + 0.94*Math.pow(rnd(),0.8), a = rnd()*Math.PI*2, r = Math.sqrt(1-y*y);
  _col.setHSL(0.58 + rnd()*0.12, 0.45, 0.85);
  stars.set(i, Math.cos(a)*r*280, y*280, Math.sin(a)*r*280, R(0.45,1.3), _col, R(0.4,1));
}
stars.dirty();

function mountains(z, base, amp, col, sd){
  const N=90, pos=[], idx=[];
  for (let i=0;i<=N;i++){
    const x = -430 + i*860/N;
    const y = base + amp*(0.55*Math.sin(x*0.012+sd) + 0.3*Math.sin(x*0.029+sd*2.1) + 0.15*Math.sin(x*0.071+sd*3.3));
    pos.push(x,y,z, x,-4,z);
  }
  for (let i=0;i<N;i++){ const a=i*2; idx.push(a,a+1,a+2, a+1,a+3,a+2); }
  const g=new THREE.BufferGeometry(); g.setAttribute('position', new THREE.Float32BufferAttribute(pos,3)); g.setIndex(idx);
  scene.add(new THREE.Mesh(g, new THREE.MeshBasicMaterial({ color:col, fog:false, side:THREE.DoubleSide })));
}
mountains(-215, 26, 16, '#1d1736', 1.7);
mountains(-175, 13, 9, '#120e24', 4.2);

/* ---------------- lights ---------------- */
scene.add(new THREE.HemisphereLight('#5d6cae', '#2a2030', 3.0));
const moonLight = new THREE.DirectionalLight('#9fb0ff', 1.0); moonLight.position.set(-60,90,-120); scene.add(moonLight);

/* ---------------- ground, banks, river ---------------- */
const farG = new THREE.Mesh(new THREE.PlaneGeometry(500,175), new THREE.MeshLambertMaterial({ color:'#1e1b28' }));
farG.rotation.x = -Math.PI/2; farG.position.set(0,0.5,-87.5); scene.add(farG);
const nearG = new THREE.Mesh(new THREE.PlaneGeometry(500,100), new THREE.MeshLambertMaterial({ color:'#17151f' }));
nearG.rotation.x = -Math.PI/2; nearG.position.set(0,0.5,66.2); scene.add(nearG);
const pathMat = new THREE.MeshLambertMaterial({ color:'#2e2a37' });
const street = new THREE.Mesh(new THREE.PlaneGeometry(6.4,26), pathMat); street.rotation.x=-Math.PI/2; street.position.set(0,0.53,-13); scene.add(street);
const prom = new THREE.Mesh(new THREE.PlaneGeometry(500,1.8), pathMat); prom.rotation.x=-Math.PI/2; prom.position.set(0,0.53,-0.95); scene.add(prom);
const edgeMat = new THREE.MeshLambertMaterial({ color:'#3a3646' });
for (const z of [-0.2, 16.2]){ const e=new THREE.Mesh(new THREE.BoxGeometry(500,0.9,0.5), edgeMat); e.position.set(0,0.1,z); scene.add(e); }

const WaterShader = {
  name:'LanternWater',
  uniforms:{ color:{ value:null }, tDiffuse:{ value:null }, textureMatrix:{ value:null }, time:{ value:0 } },
  vertexShader:`
    uniform mat4 textureMatrix;
    varying vec4 vUv; varying vec3 vW;
    #include <common>
    #include <logdepthbuf_pars_vertex>
    void main(){
      vUv = textureMatrix * vec4(position,1.0);
      vW = (modelMatrix * vec4(position,1.0)).xyz;
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);
      #include <logdepthbuf_vertex>
    }`,
  fragmentShader:`
    uniform vec3 color; uniform sampler2D tDiffuse; uniform float time;
    varying vec4 vUv; varying vec3 vW;
    #include <logdepthbuf_pars_fragment>
    void main(){
      #include <logdepthbuf_fragment>
      vec2 d = vec2(sin(vW.x*.9+time*1.3)+sin(vW.z*2.3-time*1.7), sin(vW.z*1.6+time))*.006;
      vec4 uv = vUv; uv.x += d.x*uv.w; uv.y += d.y*3.*uv.w;
      vec3 r = texture2DProj(tDiffuse, uv).rgb;
      float edge = smoothstep(0.0,1.6,vW.z) * smoothstep(16.0,14.4,vW.z);
      gl_FragColor = vec4(r*(.45+.17*edge) + vec3(.01,.02,.05), 1.0);
      #include <tonemapping_fragment>
      #include <colorspace_fragment>
    }`
};
const PR0 = renderer.getPixelRatio();
const water = new Reflector(new THREE.PlaneGeometry(220,16.2), {
  clipBias:0.003, color:0xffffff, shader:WaterShader,
  textureWidth:Math.max(2,Math.floor(innerWidth*PR0*0.5)), textureHeight:Math.max(2,Math.floor(innerHeight*PR0*0.5))
});
water.rotation.x = -Math.PI/2; water.position.set(0,0,8); scene.add(water);

/* ---------------- town & colliders ---------------- */
const colliders = [];
const houses = [];
for (const z0 of [-4,-11,-18]){
  let x = -46 + R(0,2);
  while (x < 46){
    const w=R(3,5), d=R(3,4.2);
    const h = R(3,7)*(z0===-4?0.8:1) + (z0===-18?0.6:0);
    if (Math.abs(x) - w/2 > 4.3) houses.push({ x, z:z0+R(-.4,.4), w, d, h });
    x += 6 + R(-1.5,1.5);
  }
}
for (const bx of [-46,-39,-32,32,39,46]) houses.push({ x:bx+R(-1,1), z:22.5+R(-1,1), w:R(3,5), d:R(3,4), h:R(3,5.5) });

const NH = houses.length;
const wallGeo = new THREE.BoxGeometry(1,1,1); wallGeo.translate(0,0.5,0);
const roofGeo = new THREE.BoxGeometry(1,1,1); roofGeo.rotateX(Math.PI/4);
const walls = new THREE.InstancedMesh(wallGeo, new THREE.MeshLambertMaterial(), NH);
const roofs = new THREE.InstancedMesh(roofGeo, new THREE.MeshLambertMaterial(), NH);
const WALLC = ['#8a7563','#7a6a5c','#6c6474','#94826b','#5e5868','#83695a'];
const ROOFC = ['#2c2a38','#3c2a2c','#28323a','#46302a','#33303c'];
const winList = [];
houses.forEach((h,i)=>{
  _m.compose(_a.set(h.x,0.5,h.z), _q.identity(), _s.set(h.w,h.h,h.d)); walls.setMatrixAt(i,_m);
  walls.setColorAt(i, _col.set(WALLC[Math.floor(rnd()*WALLC.length)]));
  const rh = h.d*R(0.32,0.5);
  _m.compose(_a.set(h.x,0.5+h.h,h.z), _q.identity(), _s.set(h.w+0.5, rh/0.7071, (h.d/2+0.35)/0.7071)); roofs.setMatrixAt(i,_m);
  roofs.setColorAt(i, _col.set(ROOFC[Math.floor(rnd()*ROOFC.length)]));
  h.top = 0.5+h.h+rh;
  colliders.push({ minX:h.x-h.w/2-0.25, maxX:h.x+h.w/2+0.25, minZ:h.z-h.d/2-0.35, maxZ:h.z+h.d/2+0.35, top:h.top });
  const sgn = h.z > 8 ? -1 : 1, fz = h.z + sgn*(h.d/2+0.02), ry = sgn>0 ? 0 : Math.PI;
  const nf = Math.max(1, Math.floor((h.h-0.5)/1.5)), nc = Math.max(1, Math.floor((h.w-0.4)/1.2));
  const doorC = rnd()<0.55 ? Math.floor(nc/2) : -1;
  for (let f=0; f<nf; f++) for (let c=0; c<nc; c++){
    const wx = h.x + (c+0.5-nc/2)*(h.w/nc);
    if (f===0 && c===doorC){ winList.push({ x:wx, y:0.5+0.75, z:fz, ry, sx:1.25, sy:1.9, lit:rnd()<0.8 }); continue; }
    winList.push({ x:wx, y:0.5+1.1+f*1.5, z:fz, ry, sx:1, sy:1, lit:rnd()<0.68 });
  }
  if (rnd()<0.5){ const sx = rnd()<0.5?-1:1; winList.push({ x:h.x+sx*(h.w/2+0.02), y:0.5+1.1+Math.floor(rnd()*nf)*1.5, z:h.z, ry:sx*Math.PI/2, sx:1, sy:1, lit:rnd()<0.6 }); }
});
scene.add(walls, roofs);

const hang = []; // hanging paper lanterns {p, c}
// pagoda closing the main street
const pagWall = new THREE.MeshLambertMaterial({ color:'#6e2b26' }), pagRoof = new THREE.MeshLambertMaterial({ color:'#2a2431' });
let py = 0.5;
for (let i=0;i<4;i++){
  const w = 6.4 - i*1.3, hh = 2.5 - i*0.15;
  const body = new THREE.Mesh(new THREE.BoxGeometry(w,hh,w), pagWall); body.position.set(0,py+hh/2,-24); scene.add(body);
  const roof = new THREE.Mesh(new THREE.ConeGeometry((w/2+1.3)*Math.SQRT2, 1.3, 4, 1), pagRoof);
  roof.rotation.y = Math.PI/4; roof.position.set(0,py+hh+0.5,-24); scene.add(roof);
  for (let k=-1;k<=1;k++) winList.push({ x:k*w*0.28, y:py+hh*0.5, z:-24+w/2+0.02, ry:0, sx:1.1, sy:1.2, lit:true });
  for (const sx of [-1,1]) for (const sz of [-1,1]) hang.push({ p:new V3(sx*(w/2+1.05), py+hh-0.45, -24+sz*(w/2+1.05)), c:'#ff5a3a' });
  py += hh + 0.75;
}
const spire = new THREE.Mesh(new THREE.CylinderGeometry(0.06,0.14,2.2,6), pagRoof); spire.position.set(0,py+0.6,-24); scene.add(spire);
colliders.push({ minX:-4.6, maxX:4.6, minZ:-28.6, maxZ:-19.4, top:py+1.7 });

// windows (instanced)
const wins = new THREE.InstancedMesh(new THREE.PlaneGeometry(0.55,0.75), new THREE.MeshBasicMaterial({ map:winTex }), winList.length);
const WINC = ['#ffcf7a','#ffb45e','#ffe2a6','#ff9e55'];
const staticGlow = [];
winList.forEach((w,i)=>{
  _q.setFromAxisAngle(UP, w.ry);
  _m.compose(_a.set(w.x,w.y,w.z), _q, _s.set(w.sx,w.sy,1)); wins.setMatrixAt(i,_m);
  const c = w.lit ? WINC[Math.floor(rnd()*WINC.length)] : '#16131f';
  wins.setColorAt(i, _col.set(c));
  if (w.lit) staticGlow.push({ x:w.x+Math.sin(w.ry)*0.3, y:w.y, z:w.z+Math.cos(w.ry)*0.3, s:1.5*w.sx, c, a:0.13 });
});
scene.add(wins);

/* ---------------- poles & light strings ---------------- */
const poles = [], wireS = [], bulbPos = [], wirePts = [];
function P(x,z,top){ poles.push({ x, z, top }); return new V3(x,top,z); }
function addString(a,b,sag){
  const L = a.distanceTo(b);
  const at = (t,out) => out.lerpVectors(a,b,t).setY(lerp(a.y,b.y,t) - 4*sag*t*(1-t));
  const n = Math.ceil(L/0.25);
  for (let i=0;i<n;i++){ at(i/n,_a); at((i+1)/n,_b); wirePts.push(_a.x,_a.y,_a.z,_b.x,_b.y,_b.z); }
  const ns = Math.max(2, Math.round(L/0.5));
  for (let i=0;i<=ns;i++) wireS.push(at(i/ns, new V3()));
  const nb = Math.round(L/0.7);
  for (let i=1;i<nb;i++){ at(i/nb,_a); bulbPos.push(_a.x,_a.y-0.07,_a.z); }
  const nl = Math.floor(L/2.6);
  const RC = ['#ff4a32','#ff6a2a','#ff3a4a','#ff7a3a'];
  for (let i=0;i<nl;i++){ at((i+0.5)/nl,_a); hang.push({ p:new V3(_a.x,_a.y-0.38,_a.z), c:RC[Math.floor(rnd()*RC.length)] }); }
}
for (const z of [-3,-8,-13]) addString(P(-3.7,z,R(7,8.4)), P(3.7,z,R(7,8.4)), R(0.8,1.2));
const PX = [-30,-20,-10,10,20,30];
const pp = PX.map(x => P(x,-0.9,R(6.6,7.6)));
for (let i=0;i<pp.length-1;i++) addString(pp[i], pp[i+1], i===2 ? 2.0 : R(1,1.4));
for (const sx of [-14,14]) addString(P(sx,-0.9,8.2), P(sx,17.2,7.6), 1.7);

const poleGeo = new THREE.CylinderGeometry(0.07,0.1,1,6); poleGeo.translate(0,0.5,0);
const poleMesh = new THREE.InstancedMesh(poleGeo, new THREE.MeshLambertMaterial({ color:'#3a2c30' }), poles.length);
poles.forEach((p,i)=>{
  _m.compose(_a.set(p.x,0.5,p.z), _q.identity(), _s.set(1,p.top-0.5+0.15,1)); poleMesh.setMatrixAt(i,_m);
  colliders.push({ minX:p.x-0.25, maxX:p.x+0.25, minZ:p.z-0.25, maxZ:p.z+0.25, top:p.top+0.2 });
});
scene.add(poleMesh);
const wg = new THREE.BufferGeometry(); wg.setAttribute('position', new THREE.Float32BufferAttribute(wirePts,3));
scene.add(new THREE.LineSegments(wg, new THREE.LineBasicMaterial({ color:'#4a3a40' })));

const NB = bulbPos.length/3;
const bulbs = makePoints(NB, 0.55);
const BC = ['#ffd890','#ffb066','#ff7a6a','#fff0c8','#ffc0e0','#ffd890','#ffb066','#a8e8ff'];
for (let i=0;i<NB;i++){ _col.set(BC[Math.floor(rnd()*BC.length)]); bulbs.set(i, bulbPos[i*3], bulbPos[i*3+1], bulbPos[i*3+2], 0.55, _col, 0.95); }
bulbs.dirty();

const hangMesh = new THREE.InstancedMesh(segGeo, lanternMat('#ffffff'), hang.length);
hang.forEach((h,i)=>{
  _m.compose(h.p, _q.identity(), _s.set(0.2,0.3,0.2)); hangMesh.setMatrixAt(i,_m);
  hangMesh.setColorAt(i, _col.set(h.c));
  staticGlow.push({ x:h.p.x, y:h.p.y, z:h.p.z, s:1.3, c:h.c, a:0.45 });
});
scene.add(hangMesh);
staticGlow.push({ x:0, y:py+1.8, z:-24, s:2.2, c:'#ffcf7a', a:0.6 });
const sGlow = makePoints(staticGlow.length, 0.12);
staticGlow.forEach((g,i)=>{ _col.set(g.c); sGlow.set(i, g.x, g.y, g.z, g.s, _col, g.a); });
sGlow.dirty();

/* ---------------- flight volume & waypoints ---------------- */
const VOL = { x0:-32, x1:32, y0:3, y1:18, z0:-32, z1:12 };
const WP = [[-24,3.8,8],[0,3.6,6],[22,4,9],[-10,4.2,3],[0,4.4,-5],[0,4.4,-16],[-9,6,-24],[9,6,-24],[0,15,-30],
  [-18,12,-11],[18,12,-8],[-28,13,-20],[28,13,-18],[14,15,3],[-6,16,-8],[27,6,5],[-30,5,6]].map(a=>new V3(a[0],a[1],a[2]));
for (const w of WP){
  for (let it=0; it<3; it++){
    for (const c of colliders) if (w.x>c.minX-1.6 && w.x<c.maxX+1.6 && w.z>c.minZ-1.6 && w.z<c.maxZ+1.6 && w.y<c.top+1.6) w.y = c.top+2.2;
    for (const s of wireS) if (w.distanceTo(s) < 2.2) w.y = (s.y-2.6 >= 3.4) ? s.y-2.6 : s.y+2.6;
  }
  w.y = clamp(w.y, 3.4, 17.5);
}

/* ---------------- lantern cats ---------------- */
const NSEG = 30, SP = 0.55, TS = 0.1, NTR = 200;
const segR = [];
for (let i=0;i<NSEG;i++){
  if (i<22){ const u=i/21; segR.push(0.62 - 0.2*u + 0.05*Math.sin(u*Math.PI)); }
  else { const k=(i-22)/7; segR.push(0.36 - 0.18*k); }
}
const follow = { cat:null, held:false, until:0, cx:0, cy:0, depth:20, target:new V3() };

function pushOut(p, c, rad){
  const dx=p.x-c.x, dy=p.y-c.y, dz=p.z-c.z, d2=dx*dx+dy*dy+dz*dz;
  if (d2 >= rad*rad) return;
  const d = Math.sqrt(d2);
  if (d < 1e-4){ p.y = c.y + rad; return; }
  const k = rad/d; p.set(c.x+dx*k, c.y+dy*k, c.z+dz*k);
}

class Cat {
  constructor(hex, eyeHex, start, dir, ph){
    this.color = new THREE.Color(hex); this.ph = ph;
    this.pos = start.clone(); this.vel = dir.clone().normalize().multiplyScalar(5); this.acc = new V3(); this.tgt = new V3();
    this.role = 'runner'; this.follow = false; this.slow = 0; this.wpi = 0; this.wpT = 99; this.bank = 0; this.other = null;
    this.trail = []; this.th = 0;
    const back = dir.clone().normalize().multiplyScalar(-TS);
    for (let k=0;k<NTR;k++) this.trail.push(start.clone().addScaledVector(back,k));
    this.seg = []; this.q = [];
    for (let i=0;i<NSEG;i++){ this.seg.push(new V3()); this.q.push(new THREE.Quaternion()); }
    this.computeSegments();
    // body
    this.mesh = new THREE.InstancedMesh(segGeo, lanternMat('#ffffff'), NSEG); this.mesh.frustumCulled = false;
    for (let i=0;i<NSEG;i++){ _m.compose(this.seg[i], _q.identity(), _s.set(segR[i],0.66,segR[i])); this.mesh.setMatrixAt(i,_m); this.mesh.setColorAt(i,this.color); }
    scene.add(this.mesh);
    this.glow = makePoints(NSEG+1, 0);
    // head
    const head = this.head = new THREE.Group(); head.position.copy(start); scene.add(head);
    const hm = lanternMat(this.color);
    const skull = new THREE.Mesh(new THREE.SphereGeometry(0.8,22,16), hm); skull.scale.set(1.05,0.92,1); head.add(skull);
    const muzzle = new THREE.Mesh(new THREE.SphereGeometry(0.3,16,12), lanternMat(this.color.clone().lerp(new THREE.Color('#fff4e0'),0.55)));
    muzzle.scale.set(1.3,0.85,1); muzzle.position.set(0,-0.2,0.6); head.add(muzzle);
    const nose = new THREE.Mesh(new THREE.SphereGeometry(0.085,10,8), new THREE.MeshBasicMaterial({ color:'#ff7d9c' }));
    nose.position.set(0,-0.07,0.86); head.add(nose);
    this.eyes = [];
    const eyeMat = new THREE.MeshBasicMaterial({ color:eyeHex }), pupilMat = new THREE.MeshBasicMaterial({ color:'#1a0f1e' });
    for (const sx of [-1,1]){
      const eg = new THREE.Group(); eg.position.set(sx*0.3,0.13,0.68); eg.rotation.y = sx*0.35;
      const e = new THREE.Mesh(new THREE.SphereGeometry(0.14,14,10), eyeMat); e.scale.set(1,1.15,0.55); eg.add(e);
      const pu = new THREE.Mesh(new THREE.BoxGeometry(0.045,0.2,0.04), pupilMat); pu.position.z = 0.07; eg.add(pu);
      head.add(eg); this.eyes.push(eg);
    }
    const earGeo = new THREE.ConeGeometry(0.27,0.58,4,1); earGeo.rotateY(Math.PI/4); earGeo.translate(0,0.29,0);
    const innerMat = new THREE.MeshBasicMaterial({ color:'#ff9fb4' });
    this.ears = [];
    for (const sx of [-1,1]){
      const e = new THREE.Mesh(earGeo, hm); e.position.set(sx*0.42,0.52,0.02); e.scale.set(1,1,0.6); e.rotation.set(-0.12,0,-sx*0.32);
      const inner = new THREE.Mesh(earGeo, innerMat); inner.scale.set(0.6,0.72,0.5); inner.position.set(0,0.02,0.1); e.add(inner);
      head.add(e); this.ears.push({ o:e, sx, t0:-10, next:Math.random()*3 });
    }
    const wGeo = new THREE.CylinderGeometry(0.013,0.006,0.9,4,1); wGeo.rotateZ(-Math.PI/2); wGeo.translate(0.45,0,0);
    const wMat = new THREE.MeshBasicMaterial({ color:'#fff3df', side:THREE.DoubleSide });
    this.whisk = [];
    for (const sx of [-1,1]) for (let k=0;k<3;k++){
      const w = new THREE.Mesh(wGeo, wMat); w.position.set(sx*0.26,-0.2+(k-1)*0.04,0.8); w.scale.x = sx; head.add(w);
      this.whisk.push({ o:w, sx, k });
    }
    this.wt0 = -10; this.wNext = 2; this.blink0 = -10; this.blinkNext = 2+Math.random()*3; this.tail0 = -10; this.tailNext = 3;
    this.light = new THREE.PointLight(this.color, 60, 18, 2); this.light.position.copy(start); scene.add(this.light);
  }
  get(k){ return this.trail[(this.th + k) % NTR]; }
  sampleAt(s, out){
    const n0 = this.get(0), d0 = this.pos.distanceTo(n0);
    if (s <= d0) return d0 > 1e-6 ? out.lerpVectors(this.pos, n0, s/d0) : out.copy(this.pos);
    const k = (s-d0)/TS, i = Math.floor(k);
    if (i >= NTR-1) return out.copy(this.get(NTR-1));
    return out.lerpVectors(this.get(i), this.get(i+1), k-i);
  }
  pushTrail(){
    const last = this.get(0);
    let d = this.pos.distanceTo(last);
    if (d < TS) return;
    t1.subVectors(this.pos, last).multiplyScalar(1/d);
    let cx=last.x, cy=last.y, cz=last.z, guard=0;
    while (d >= TS && guard++ < 400){
      cx += t1.x*TS; cy += t1.y*TS; cz += t1.z*TS;
      this.th = (this.th - 1 + NTR) % NTR; this.trail[this.th].set(cx,cy,cz); d -= TS;
    }
  }
  computeSegments(){ for (let i=0;i<NSEG;i++) this.sampleAt(0.7 + SP*i, this.seg[i]); }
  avoid(out){
    out.set(0,0,0);
    const L = t3.copy(this.pos).addScaledVector(this.vel, 0.6);
    for (let i=0;i<colliders.length;i++){
      const c = colliders[i];
      const qx = clamp(L.x,c.minX,c.maxX), qy = Math.min(L.y,c.top), qz = clamp(L.z,c.minZ,c.maxZ);
      const dx=L.x-qx, dy=L.y-qy, dz=L.z-qz, d2=dx*dx+dy*dy+dz*dz;
      if (d2 > 25) continue;
      const d = Math.sqrt(d2), s = 1-d/5, k = s*s*26;
      if (d < 1e-3){ out.y += 30; continue; }
      const up = L.y > c.top*0.55 ? 0.8 : 0.2;
      out.x += dx/d*k; out.y += (dy/d + up)*k; out.z += dz/d*k;
    }
    let best = 1e9, bw = null;
    for (let i=0;i<wireS.length;i++){
      const w = wireS[i], dx=L.x-w.x, dy=L.y-w.y, dz=L.z-w.z, d2=dx*dx+dy*dy+dz*dz;
      if (d2 < best){ best = d2; bw = w; }
    }
    if (bw && best < 12.25){
      const d = Math.sqrt(best), s = 1-d/3.5;
      out.y += (this.pos.y >= bw.y ? 1 : -1)*s*s*30;
      if (d > 1e-3){ out.x += (L.x-bw.x)/d*s*s*4; out.z += (L.z-bw.z)/d*s*s*4; }
    }
    const o = this.other, rng = (this.role==='chaser' && !this.follow) ? 2.2 : 4.2;
    for (let j=0;j<=NSEG;j+=2){
      const p = j>=NSEG ? o.pos : o.seg[j], rr = (j>=NSEG ? 0.8 : segR[j]) + rng;
      const dx=L.x-p.x, dy=L.y-p.y, dz=L.z-p.z, d2=dx*dx+dy*dy+dz*dz;
      if (d2 > rr*rr || d2 < 1e-6) continue;
      const d = Math.sqrt(d2), s = 1-d/rr, k = s*s*20;
      out.x += dx/d*k; out.y += dy/d*k; out.z += dz/d*k;
    }
    if (L.y < 4.6) out.y += (4.6-L.y)*7;
    if (L.y > 16.5) out.y -= (L.y-16.5)*7;
    if (L.x < -29) out.x += (-29-L.x)*5;
    if (L.x > 29) out.x -= (L.x-29)*5;
    if (L.z < -29.5) out.z += (-29.5-L.z)*5;
    if (L.z > 10) out.z -= (L.z-10)*5;
  }
  steer(dt, t){
    let speed; const tg = this.tgt;
    if (this.follow){ tg.copy(follow.target); speed = 9; }
    else if (this.role === 'runner'){
      this.wpT += dt;
      if (this.wpT > 6 || this.pos.distanceTo(WP[this.wpi]) < 3) pickWaypoint(this);
      tg.copy(WP[this.wpi]); speed = 6;
    } else { tg.copy(this.other.seg[NSEG-1]); tg.y += 1.5; speed = this.slow > 0 ? 4 : 7; }
    this.slow -= dt;
    t1.subVectors(tg, this.pos);
    const dist = t1.length(); t1.multiplyScalar(1/Math.max(dist,1e-3));
    const sp = speed * clamp(dist/4, 0.45, 1);
    const hs = Math.hypot(this.vel.x, this.vel.z) || 1;
    const sx = this.vel.z/hs, sz = -this.vel.x/hs;
    const wk = speed/6;
    const wl = Math.sin(3*t + this.ph)*5.5*wk, wv = Math.sin(1.9*t + this.ph*1.7)*2.0*wk;
    const acc = this.acc;
    acc.copy(t1).multiplyScalar(sp).sub(this.vel).multiplyScalar(2);
    acc.x += sx*wl; acc.z += sz*wl; acc.y += wv;
    this.avoid(t2); acc.add(t2);
    const am = acc.length(); if (am > 16) acc.multiplyScalar(16/am);
    this.vel.addScaledVector(acc, dt);
    const h2 = Math.hypot(this.vel.x, this.vel.z), mv = 0.75*h2;
    if (Math.abs(this.vel.y) > mv) this.vel.y = Math.sign(this.vel.y)*mv;
    const s = this.vel.length(), smax = Math.max(speed,6)*1.3;
    if (s > smax) this.vel.multiplyScalar(smax/s);
    else if (s < 2.5){
      if (Math.hypot(this.vel.x, this.vel.z) < 1e-3) this.vel.set(t1.x || 1, 0, t1.z);
      this.vel.setLength(2.5);
    }
  }
  constrain(p){
    const o = this.other;
    for (let it=0; it<2; it++){
      p.x = clamp(p.x,VOL.x0,VOL.x1); p.y = clamp(p.y,VOL.y0,VOL.y1); p.z = clamp(p.z,VOL.z0,VOL.z1);
      for (let i=0;i<colliders.length;i++){
        const c = colliders[i], m = 1.4, top = c.top+m;
        if (p.y >= top) continue;
        const x0=c.minX-m, x1=c.maxX+m, z0=c.minZ-m, z1=c.maxZ+m;
        if (p.x <= x0 || p.x >= x1 || p.z <= z0 || p.z >= z1) continue;
        const dl=p.x-x0, dr=x1-p.x, dn=p.z-z0, df=z1-p.z, du=(top-p.y)*0.7;
        const mn = Math.min(dl,dr,dn,df,du);
        if (mn===du) p.y = top; else if (mn===dl) p.x = x0; else if (mn===dr) p.x = x1; else if (mn===dn) p.z = z0; else p.z = z1;
      }
      for (let i=0;i<wireS.length;i++){
        const w = wireS[i], dx=p.x-w.x, dy=p.y-w.y, dz=p.z-w.z;
        if (dx*dx+dy*dy+dz*dz >= 1.69) continue;
        const ny = dy + (dy >= 0 ? 0.6 : -0.6), l = Math.sqrt(dx*dx+ny*ny+dz*dz) || 1;
        p.set(w.x+dx/l*1.3, w.y+ny/l*1.3, w.z+dz/l*1.3);
      }
      pushOut(p, o.pos, 2.2);
      for (let j=0;j<NSEG;j++) pushOut(p, o.seg[j], segR[j]+1.4);
      for (let j=10;j<NSEG;j++) pushOut(p, this.seg[j], segR[j]+1.4);
    }
  }
  move(dt){
    const n = Math.max(1, Math.ceil(this.vel.length()*dt/0.3)), h = dt/n;
    for (let k=0;k<n;k++){
      this.pos.addScaledVector(this.vel, h);
      t4.copy(this.pos);
      this.constrain(this.pos);
      t5.subVectors(this.pos, t4);
      const cl = t5.length();
      if (cl > 1e-6){ t5.multiplyScalar(1/cl); const vn = this.vel.dot(t5); if (vn < 0) this.vel.addScaledVector(t5, -vn); }
    }
    this.pushTrail();
    this.computeSegments();
  }
  visual(dt, t){
    const glow = this.glow;
    if (t > this.tailNext){ this.tail0 = t; this.tailNext = t + MR(3,6); }
    const tau = t - this.tail0, flick = 0.22*Math.exp(-4*tau)*Math.sin(16*tau);
    for (let i=0;i<NSEG;i++){
      const p = this.seg[i], prev = i===0 ? this.pos : this.seg[i-1], next = i===NSEG-1 ? p : this.seg[i+1];
      t4.subVectors(prev, next);
      const l = t4.length();
      if (l > 1e-5){ t4.multiplyScalar(1/l); this.q[i].setFromUnitVectors(UP, t4); }
      t5.copy(p);
      if (i >= NSEG-8){
        const k = i-(NSEG-9), f = (k/8)*(k/8), hl = Math.hypot(t4.x,t4.z) || 1;
        const lat = f*(0.3*Math.sin(4*t + this.ph) + flick);
        t5.x += (-t4.z/hl)*lat; t5.z += (t4.x/hl)*lat; t5.y += f*0.25;
      }
      const r = segR[i];
      _m.compose(t5, this.q[i], _s.set(r,0.66,r)); this.mesh.setMatrixAt(i,_m);
      const fl = (0.86 + 0.14*Math.sin(7*t + 1.3*i + this.ph)) * (0.9 + 0.12*Math.sin(3*t - 0.45*i));
      _col.copy(this.color).multiplyScalar(fl); this.mesh.setColorAt(i,_col);
      glow.set(i+1, t5.x, t5.y, t5.z, r*3, this.color, 0.2*fl);
    }
    this.mesh.instanceMatrix.needsUpdate = true;
    if (this.mesh.instanceColor) this.mesh.instanceColor.needsUpdate = true;
    // head orientation along velocity with banking
    this.head.position.copy(this.pos);
    t4.copy(this.vel).normalize();
    _m.lookAt(t4, ZERO, UP); _q.setFromRotationMatrix(_m);
    const hs = this.vel.length() || 1;
    const bt = clamp(-(this.vel.z*this.acc.x - this.vel.x*this.acc.z)/(hs*16), -0.5, 0.5);
    this.bank += (bt - this.bank)*(1 - Math.exp(-3*dt));
    _q2.setFromAxisAngle(ZAX, this.bank); _q.multiply(_q2);
    this.head.quaternion.slerp(_q, 1 - Math.exp(-8*dt));
    // ear twitches
    for (const e of this.ears){
      if (t > e.next){ e.t0 = t; e.next = t + MR(2,5); }
      const tt = t - e.t0, a = 0.5*Math.exp(-8*tt)*Math.sin(30*tt);
      e.o.rotation.z = -e.sx*0.32 - e.sx*a*0.8; e.o.rotation.x = -0.12 + a*0.5;
    }
    // whiskers sway and twitch
    if (t > this.wNext){ this.wt0 = t; this.wNext = t + MR(1.5,4); }
    const wt = t - this.wt0, wa = 0.3*Math.exp(-6*wt)*Math.sin(26*wt);
    for (const w of this.whisk){
      const sw = 0.06*Math.sin(2.3*t + w.k*1.4 + this.ph);
      w.o.rotation.set(0, w.sx*(0.3 + wa + sw*0.5), w.sx*((w.k-1)*0.2 + sw));
    }
    // blink
    if (t > this.blinkNext){ this.blink0 = t; this.blinkNext = t + MR(2.5,6); }
    const b = t - this.blink0, sy = b < 0.18 ? 0.12 + 0.88*Math.abs(b-0.09)/0.09 : 1;
    for (const e of this.eyes) e.scale.y = sy;
    this.light.position.copy(this.seg[2]);
    glow.set(0, this.pos.x, this.pos.y, this.pos.z, 3.6, this.color, 0.3);
    glow.dirty();
  }
}

function pickWaypoint(c){
  let best = -1e9, bi = c.wpi;
  for (let k=0;k<7;k++){
    const i = Math.floor(Math.random()*WP.length);
    if (i === c.wpi) continue;
    const w = WP[i], sc = w.distanceTo(c.other.pos) - 0.4*w.distanceTo(c.pos) + Math.random()*8;
    if (sc > best){ best = sc; bi = i; }
  }
  c.wpi = bi; c.wpT = 0;
}

const orange = new Cat('#ff8a2e', '#fff0a0', new V3(-10,6.5,10), new V3(1,0,0), 0.0);
const silver = new Cat('#c8d2e6', '#a8ffd8', new V3(10,4,6), new V3(1,0,0), 2.1);
orange.other = silver; silver.other = orange;
orange.role = 'chaser'; silver.role = 'runner';
const cats = [orange, silver];
pickWaypoint(silver);

/* ---------------- festival extras ---------------- */
// sky lanterns
const NSL = SMALL ? 30 : 50;
const slMesh = new THREE.InstancedMesh(new THREE.CylinderGeometry(0.34,0.26,0.62,10,1,true), lanternMat('#ffffff', THREE.DoubleSide), NSL);
slMesh.frustumCulled = false; scene.add(slMesh);
const slGlow = makePoints(NSL, 0);
const SLC = ['#ffb257','#ff9440','#ffd07a','#ff7a3a'].map(c=>new THREE.Color(c));
const sl = [];
function spawnSL(L, init){
  if (Math.random() < 0.55){ L.x = MR(-40,40); L.z = MR(1.5,14.5); L.y = MR(0.4,1.5); }
  else { const h = houses[Math.floor(Math.random()*houses.length)]; L.x = h.x; L.z = h.z; L.y = h.top + 0.4; }
  L.age = 0;
  if (init){ L.y = MR(1,44); L.age = 5; }
  L.vy = MR(0.6,1.2); L.ph = MR(0,6.28); L.c = SLC[Math.floor(Math.random()*SLC.length)]; L.s = MR(0.8,1.15);
}
for (let i=0;i<NSL;i++){ const L = {}; spawnSL(L,true); sl.push(L); slMesh.setColorAt(i, L.c); slMesh.setMatrixAt(i, _m.identity()); }
function burstLanterns(n){
  const idx = sl.map((L,i)=>i).sort((a,b)=>sl[b].y - sl[a].y).slice(0,n);
  for (const i of idx){ const L = sl[i]; spawnSL(L,false); L.x = MR(-14,14); L.z = MR(3,13); L.y = MR(0.4,2.2); L.vy = MR(1.0,1.5); }
}
function updateSkyLanterns(dt){
  for (let i=0;i<NSL;i++){
    const L = sl[i];
    L.age += dt; L.y += L.vy*dt;
    L.x += (0.22 + Math.sin(T*0.6 + L.ph)*0.25)*dt; L.z += Math.cos(T*0.45 + L.ph)*0.18*dt;
    if (L.y > 45) spawnSL(L,false);
    const fade = Math.min(1, L.age/2.5) * (1 - sstep(clamp((L.y-36)/9,0,1)));
    const sc = L.s*Math.max(fade,0.001);
    _q.setFromAxisAngle(ZAX, Math.sin(T*0.9 + L.ph)*0.08);
    _m.compose(_a.set(L.x,L.y,L.z), _q, _s.set(sc,sc,sc)); slMesh.setMatrixAt(i,_m);
    const fl = 0.85 + 0.15*Math.sin(T*9 + L.ph*5);
    slMesh.setColorAt(i, _col.copy(L.c).multiplyScalar(fl));
    slGlow.set(i, L.x, L.y-0.1, L.z, 2.6*L.s, L.c, 0.55*fl*fade);
  }
  slMesh.instanceMatrix.needsUpdate = true; slMesh.instanceColor.needsUpdate = true; slGlow.dirty();
}

// floating river lanterns
const NWL = 14;
const wlMesh = new THREE.InstancedMesh(segGeo, lanternMat('#ffffff'), NWL); wlMesh.frustumCulled = false; scene.add(wlMesh);
const wlGlow = makePoints(NWL, 0);
const wl = [];
for (let i=0;i<NWL;i++){ wl.push({ x:R(-60,60), z:R(2,14), ph:R(0,6), c:SLC[i%4] }); wlMesh.setColorAt(i, SLC[i%4]); wlMesh.setMatrixAt(i, _m.identity()); }
function updateWaterLanterns(dt){
  for (let i=0;i<NWL;i++){
    const L = wl[i];
    L.x += 0.35*dt; if (L.x > 60) L.x = -60;
    const y = 0.2 + 0.03*Math.sin(T*1.5 + L.ph);
    _q.setFromAxisAngle(ZAX, Math.sin(T*1.1 + L.ph)*0.06);
    _m.compose(_a.set(L.x,y,L.z), _q, _s.set(0.26,0.3,0.26)); wlMesh.setMatrixAt(i,_m);
    const fl = 0.85 + 0.15*Math.sin(T*8 + L.ph*3);
    wlMesh.setColorAt(i, _col.copy(L.c).multiplyScalar(fl));
    wlGlow.set(i, L.x, y+0.05, L.z, 1.8, L.c, 0.5*fl);
  }
  wlMesh.instanceMatrix.needsUpdate = true; wlMesh.instanceColor.needsUpdate = true; wlGlow.dirty();
}

// drifting sparks
const NSP = SMALL ? 150 : 250;
const spk = makePoints(NSP, 0);
const GOLD = [new THREE.Color('#ffd48a'), new THREE.Color('#ffae5c'), new THREE.Color('#fff1c9')];
const sparks = [];
let sparkCursor = 0;
function spawnSpark(s, init){
  s.age = 0; s.life = MR(3,6);
  if (Math.random() < 0.4){
    const c = cats[Math.random()<0.5 ? 0 : 1], j = Math.floor(Math.random()*NSEG), p = c.seg[j], r = segR[j];
    s.x = p.x+MR(-r,r); s.y = p.y+MR(-r,r); s.z = p.z+MR(-r,r);
    s.vx = c.vel.x*0.08 + MR(-.3,.3); s.vy = MR(0.1,0.6); s.vz = c.vel.z*0.08 + MR(-.3,.3);
    s.c.copy(c.color).lerp(WHITE, 0.45);
  } else {
    s.x = MR(-38,38); s.y = MR(0.8,15); s.z = MR(-22,16);
    s.vx = MR(-.2,.2); s.vy = MR(0,.4); s.vz = MR(-.2,.2);
    s.c.copy(GOLD[Math.floor(Math.random()*3)]);
  }
  s.sz = MR(0.22,0.42);
  if (init) s.age = Math.random()*s.life;
}
for (let i=0;i<NSP;i++){ const s = { c:new THREE.Color() }; spawnSpark(s,true); sparks.push(s); }
function burstSparks(p, col, n){
  for (let k=0;k<n;k++){
    const s = sparks[sparkCursor]; sparkCursor = (sparkCursor+1) % NSP;
    const a = Math.random()*6.283, b = Math.random()*2-1, r = Math.sqrt(1-b*b), v = MR(1.5,3.5);
    s.x = p.x; s.y = p.y; s.z = p.z; s.vx = Math.cos(a)*r*v; s.vy = b*v + 0.8; s.vz = Math.sin(a)*r*v;
    s.age = 0; s.life = MR(1.2,2.2); s.c.copy(col).lerp(WHITE,0.4); s.sz = MR(0.3,0.5);
  }
}
function updateSparks(dt){
  const dr = 1 - 0.6*dt;
  for (let i=0;i<NSP;i++){
    const s = sparks[i];
    s.age += dt;
    if (s.age >= s.life) spawnSpark(s,false);
    const ax = 0.25 + Math.sin(s.y*1.3 + T*0.9 + i)*0.5, ay = 0.08 + Math.cos(s.x*0.7 + T*1.1)*0.3, az = Math.sin(s.x*0.9 + s.z*0.5 + T)*0.4;
    s.vx = (s.vx + ax*dt)*dr; s.vy = (s.vy + ay*dt)*dr; s.vz = (s.vz + az*dt)*dr;
    s.x += s.vx*dt; s.y += s.vy*dt; s.z += s.vz*dt;
    if (s.y < 0.3){ s.y = 0.3; s.vy = Math.abs(s.vy); }
    const a = Math.sin(Math.PI*s.age/s.life)*(0.55 + 0.45*Math.sin(s.age*17 + i*3.1));
    spk.set(i, s.x, s.y, s.z, s.sz, s.c, Math.max(0,a)*0.9);
  }
  spk.dirty();
}

// finger target marker
const marker = makePoints(1, 0);
function updateMarker(){
  if (follow.cat){
    const p = follow.target; _col.copy(follow.cat.color).lerp(WHITE,0.5);
    marker.set(0, p.x, p.y, p.z, 1.6 + 0.4*Math.sin(T*6), _col, follow.held ? 0.9 : 0.5);
  } else marker.C[3] = 0;
  marker.dirty();
}

/* ---------------- chase roles ---------------- */
let roleT = 0;
function swapRoles(){
  const ru = cats[0].role === 'runner' ? cats[0] : cats[1], ch = ru.other;
  ru.role = 'chaser'; ru.slow = 1.5;
  ch.role = 'runner'; ch.wpT = 99;
  roleT = 0;
  burstSparks(ru.seg[NSEG-1], ch.color, 22);
}
function roles(dt){
  roleT += dt;
  const ch = cats[0].role === 'chaser' ? cats[0] : cats[1], ru = ch.other;
  if (roleT > 15 || (!ch.follow && roleT > 2 && ch.pos.distanceTo(ru.seg[NSEG-1]) < 3)) swapRoles();
}

/* ---------------- input ---------------- */
let hintHidden = false;
function hideHint(){ if (!hintHidden){ hintHidden = true; hintEl.style.opacity = '0'; } }
function pickCat(cx, cy){
  let best = 1e18, bc = cats[0];
  for (const c of cats){
    for (let j=-1;j<NSEG;j+=3){
      const p = j < 0 ? c.pos : c.seg[j];
      _e.copy(p).project(camera);
      if (_e.z > 1) continue;
      const sx = (_e.x+1)/2*innerWidth, sy = (1-_e.y)/2*innerHeight, d = (sx-cx)*(sx-cx) + (sy-cy)*(sy-cy);
      if (d < best){ best = d; bc = c; }
    }
  }
  return bc;
}
function updateFollowTarget(){
  _d.set(follow.cx/innerWidth*2-1, -(follow.cy/innerHeight)*2+1, 0.5).unproject(camera).sub(camera.position).normalize();
  camera.getWorldDirection(_f);
  const t = follow.depth / Math.max(_d.dot(_f), 0.15);
  const p = follow.target.copy(camera.position).addScaledVector(_d, t);
  p.x = clamp(p.x, VOL.x0+1, VOL.x1-1); p.y = clamp(p.y, VOL.y0+0.5, VOL.y1-0.5); p.z = clamp(p.z, VOL.z0+1, VOL.z1-1);
}
function inputDown(cx, cy){
  const c = pickCat(cx, cy);
  if (follow.cat && follow.cat !== c) follow.cat.follow = false;
  follow.cat = c; c.follow = true; follow.held = true; follow.cx = cx; follow.cy = cy;
  camera.getWorldDirection(_f);
  follow.depth = clamp(_d.subVectors(c.pos, camera.position).dot(_f), 12, 45);
  updateFollowTarget();
}
function inputMove(cx, cy){ follow.cx = cx; follow.cy = cy; }
function inputUp(){ if (follow.held){ follow.held = false; follow.until = T + 4; } }

let activeId = null;
canvas.addEventListener('pointerdown', e => {
  e.preventDefault();
  initAudio(); hideHint();
  if (activeId !== null) return;
  activeId = e.pointerId;
  try { canvas.setPointerCapture(e.pointerId); } catch(_){}
  inputDown(e.clientX, e.clientY);
});
canvas.addEventListener('pointermove', e => { if (e.pointerId === activeId) inputMove(e.clientX, e.clientY); });
function endPtr(e){ if (e.pointerId === activeId){ activeId = null; inputUp(); } }
canvas.addEventListener('pointerup', e => { endPtr(e); initAudio(); });
canvas.addEventListener('pointercancel', endPtr);
canvas.addEventListener('lostpointercapture', endPtr);
canvas.addEventListener('contextmenu', e => e.preventDefault());
window.addEventListener('touchend', () => { if (audioStarted) initAudio(); }, { passive:true });

/* ---------------- camera ---------------- */
const KEYS = [[0,4,30, 0,7,-6],[-16,3,22, 4,8,-4],[10,9,24, -4,6,-8],[2,2.2,19, 0,9,-10],[-6,7,27, 6,7,-12]];
const DKEYS = [[0,6,32, 0,7,-8],[-10,4.5,25, 0,7,-7],[7,3.5,21, -2,7,-8],[2,1.8,18.4, 0,7.5,-10],[-5,11,28.5, 0,6,-10]];
const DTIMES = [0,5,11,15,20];
const camPos = new V3(), keyPos = new V3(), keyLook = new V3(), lookSm = new V3(0,7,-6);
let camT = 0, camInit = false;
function keyAt(t, dm){
  let A, B, u;
  if (dm){
    const d = t % 20; let i = 0;
    while (i < 3 && d >= DTIMES[i+1]) i++;
    A = DKEYS[i]; B = DKEYS[i+1]; u = (d - DTIMES[i])/(DTIMES[i+1] - DTIMES[i]);
  } else {
    const f = t/14, i = Math.floor(f) % KEYS.length;
    A = KEYS[i]; B = KEYS[(i+1) % KEYS.length]; u = f - Math.floor(f);
  }
  u = sstep(clamp(u,0,1));
  keyPos.set(lerp(A[0],B[0],u), lerp(A[1],B[1],u), lerp(A[2],B[2],u));
  keyLook.set(lerp(A[3],B[3],u), lerp(A[4],B[4],u), lerp(A[5],B[5],u));
}
function updateCamera(dt){
  camT += dt;
  keyAt(demo ? demoT : camT, demo);
  const portrait = innerWidth < innerHeight;
  if (portrait){ keyPos.z += 4; keyPos.y += 1; }
  _a.addVectors(cats[0].pos, cats[1].pos).multiplyScalar(0.5);
  _b.copy(keyLook).lerp(_a, portrait ? 0.6 : 0.35);
  if (!camInit){ camPos.copy(keyPos); lookSm.copy(_b); camInit = true; }
  camPos.lerp(keyPos, 1 - Math.exp(-1.5*dt));
  lookSm.lerp(_b, 1 - Math.exp(-0.8*dt));
  camera.position.copy(camPos);
  camera.position.x += Math.sin(T*0.31)*0.35; camera.position.y += Math.sin(T*0.47)*0.2; camera.position.z += Math.sin(T*0.23)*0.3;
  camera.lookAt(lookSm);
  camera.updateMatrixWorld();
}

/* ---------------- melody (Web Audio) ---------------- */
let AC = null, master = null, send = null, audioStarted = false, nextT = 0, step = 0;
let muted = false;
try { muted = localStorage.getItem('lanternCats.muted') === '1'; } catch(e){}
const VOL_ON = 0.3;
const SEQ = [74,0,76,78,81,0,78,76,74,0,71,0,69,0,0,0, 71,0,74,76,78,0,76,74,71,0,69,71,74,0,0,0,
             81,0,83,81,78,0,76,0,74,76,78,0,76,0,0,0, 74,0,71,69,66,0,69,0,71,0,69,66,62,0,0,0];
const EI = 60/76/2;
const mtof = m => 440*Math.pow(2,(m-69)/12);
function initAudio(){
  audioStarted = true;
  try {
    if (!AC){
      const Ctx = window.AudioContext || window.webkitAudioContext;
      if (!Ctx) return;
      AC = new Ctx();
      master = AC.createGain(); master.gain.value = muted ? 0 : VOL_ON;
      const comp = AC.createDynamicsCompressor(); comp.threshold.value = -16; comp.ratio.value = 3;
      master.connect(comp); comp.connect(AC.destination);
      send = AC.createGain(); send.gain.value = 1;
      const dl = AC.createDelay(1.5); dl.delayTime.value = 0.39;
      const fb = AC.createGain(); fb.gain.value = 0.35;
      const lp = AC.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = 2500;
      const wet = AC.createGain(); wet.gain.value = 0.4;
      send.connect(dl); dl.connect(lp); lp.connect(fb); fb.connect(dl); lp.connect(wet); wet.connect(master);
      nextT = AC.currentTime + 0.12; step = 0;
      setInterval(sched, 50);
    }
    if (AC.state !== 'running') AC.resume();
  } catch(e){}
}
function lead(f, t){
  const o = AC.createOscillator(); o.type = 'triangle'; o.frequency.value = f;
  const o2 = AC.createOscillator(); o2.type = 'sine'; o2.frequency.value = f*2;
  const g = AC.createGain(), g2 = AC.createGain(); g2.gain.value = 0.18;
  const lfo = AC.createOscillator(); lfo.frequency.value = 5.2;
  const lg = AC.createGain(); lg.gain.value = 7;
  lfo.connect(lg); lg.connect(o.detune); lg.connect(o2.detune);
  g.gain.setValueAtTime(0.0001, t); g.gain.linearRampToValueAtTime(0.5, t+0.02); g.gain.exponentialRampToValueAtTime(0.0001, t+1.4);
  o.connect(g); o2.connect(g2); g2.connect(g); g.connect(master); g.connect(send);
  o.start(t); o2.start(t); lfo.start(t); o.stop(t+1.5); o2.stop(t+1.5); lfo.stop(t+1.5);
}
function drone(f, t, dur){
  const g = AC.createGain();
  g.gain.setValueAtTime(0.0001, t); g.gain.linearRampToValueAtTime(0.12, t+1.2);
  g.gain.setValueAtTime(0.12, t+dur-0.4); g.gain.linearRampToValueAtTime(0.0001, t+dur+0.8);
  g.connect(master);
  for (const [m,a] of [[1,1],[1.5,0.35]]){
    const o = AC.createOscillator(); o.type = 'sine'; o.frequency.value = f*m;
    const og = AC.createGain(); og.gain.value = a; o.connect(og); og.connect(g);
    o.start(t); o.stop(t+dur+0.9);
  }
}
function chime(f, t){
  for (const [m,a,d] of [[1,0.12,2.8],[2.76,0.06,1.6],[5.4,0.02,0.9]]){
    const o = AC.createOscillator(); o.type = 'sine'; o.frequency.value = f*m;
    const g = AC.createGain();
    g.gain.setValueAtTime(0.0001, t); g.gain.linearRampToValueAtTime(a, t+0.005); g.gain.exponentialRampToValueAtTime(0.0001, t+d);
    o.connect(g); g.connect(master); g.connect(send);
    o.start(t); o.stop(t+d+0.1);
  }
}
function sched(){
  if (!AC || AC.state !== 'running') return;
  const now = AC.currentTime;
  if (nextT < now - 0.05) nextT = now + 0.05;
  while (nextT < now + 0.25){
    const s = step % 64;
    if (!muted){
      try {
        const m = SEQ[s]; if (m) lead(mtof(m), nextT);
        if (s % 16 === 0) drone(mtof((s/16) % 2 ? 45 : 38), nextT, EI*16);
        if (s % 32 === 0) chime(mtof(s === 0 ? 86 : 81), nextT);
      } catch(e){}
    }
    nextT += EI; step++;
  }
}
function updateMuteIcon(){
  $('waves').style.display = muted ? 'none' : '';
  $('cross').style.display = muted ? '' : 'none';
  muteBtn.setAttribute('aria-label', muted ? 'Unmute music' : 'Mute music');
}
function setMuted(m){
  muted = m;
  try { localStorage.setItem('lanternCats.muted', m ? '1' : '0'); } catch(e){}
  if (AC && master) master.gain.setTargetAtTime(m ? 0 : VOL_ON, AC.currentTime, 0.08);
  updateMuteIcon();
}
muteBtn.addEventListener('pointerdown', e => { e.stopPropagation(); });
muteBtn.addEventListener('click', e => {
  e.stopPropagation(); e.preventDefault();
  const was = audioStarted;
  initAudio(); hideHint();
  if (!was && !muted) return; // first press just starts the music
  setMuted(!muted);
});
updateMuteIcon();

/* ---------------- #demo loop ---------------- */
let demo = DEMO, demoT = 0, demoDown = false, lastD = 0;
if (demo) hintEl.textContent = 'Demo — touch anywhere to play';
function demoUpdate(dt){
  demoT += dt;
  const d = demoT % 20;
  if (d < lastD) lastD = -1;
  const cr = x => lastD < x && d >= x;
  if (d >= 5 && d < 11){
    const s = (d-5)/6*Math.PI*2;
    _e.set(10*Math.sin(s), 6.5 + 2.4*Math.sin(2*s), -6).project(camera);
    const cx = (_e.x+1)/2*innerWidth, cy = (1-_e.y)/2*innerHeight;
    if (!demoDown){ demoDown = true; inputDown(cx, cy); } else inputMove(cx, cy);
    ghostEl.style.display = 'block';
    ghostEl.style.transform = 'translate(' + cx.toFixed(1) + 'px,' + cy.toFixed(1) + 'px)';
  } else if (demoDown){ demoDown = false; inputUp(); ghostEl.style.display = 'none'; }
  if (cr(12.5)) swapRoles();
  if (cr(15.2)) burstLanterns(15);
  lastD = d;
}
function endDemo(){
  if (!demo) return;
  demo = false; ghostEl.style.display = 'none';
  if (demoDown){ demoDown = false; inputUp(); }
  camT = 0;
  hintEl.textContent = 'Touch or drag — a cat will follow';
}
window.addEventListener('pointerdown', () => { if (demo) endDemo(); }, true);

/* ---------------- resize & loop ---------------- */
function resize(){
  const w = innerWidth, h = innerHeight, asp = w/h;
  renderer.setSize(w, h);
  camera.aspect = asp;
  camera.fov = asp < 1 ? Math.min(78, 50 + (1-asp)*45) : 50;
  camera.updateProjectionMatrix();
  const pr = renderer.getPixelRatio();
  water.getRenderTarget().setSize(Math.max(2, Math.floor(w*pr*0.5)), Math.max(2, Math.floor(h*pr*0.5)));
  U.uScale.value = h*pr/(2*Math.tan(camera.fov*Math.PI/360));
}
window.addEventListener('resize', resize);
window.addEventListener('orientationchange', () => setTimeout(resize, 200));
resize();
if (!demo) setTimeout(hideHint, 15000);

const clock = new THREE.Clock();
function frame(){
  requestAnimationFrame(frame);
  const dt = Math.min(clock.getDelta(), 0.05);
  T += dt;
  U.uTime.value = T;
  water.material.uniforms.time.value = T;
  if (demo) demoUpdate(dt);
  updateCamera(dt);
  if (follow.cat){
    if (follow.held) updateFollowTarget();
    else if (T > follow.until){ follow.cat.follow = false; follow.cat = null; }
  }
  for (const c of cats){ c.steer(dt, T); c.move(dt); }
  roles(dt);
  for (const c of cats) c.visual(dt, T);
  updateMarker();
  updateSkyLanterns(dt);
  updateWaterLanterns(dt);
  updateSparks(dt);
  renderer.render(scene, camera);
}
frame();
</script>
</body>
</html>