Skip to content
VibeCodeBench
Back to the app

The code

Lantern Cats by Gemini 4 Neon

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.)130.1 KB · 3,876 lines · loads cdn.jsdelivr.net/npm/[email protected]/build/three.module.js
Download
<!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" />
<title>Lantern Cats — Festival Night</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: #060916;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
    color: #fff6e5;
    user-select: none;
    -webkit-user-select: none;
  }
  #scene-canvas {
    position: fixed;
    inset: 0;
    width: 100%;
    height: 100%;
    display: block;
    touch-action: none;
    cursor: grab;
  }
  #scene-canvas:active {
    cursor: grabbing;
  }

  .hud {
    position: fixed;
    inset: 0;
    pointer-events: none;
    z-index: 10;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: max(16px, env(safe-area-inset-top)) max(18px, env(safe-area-inset-right)) max(18px, env(safe-area-inset-bottom)) max(18px, env(safe-area-inset-left));
  }

  .top-row {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 12px;
  }

  .title-card {
    background: rgba(10, 14, 30, 0.42);
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 200, 128, 0.22);
    border-radius: 16px;
    padding: 10px 16px;
    box-shadow: 0 8px 28px rgba(0, 0, 0, 0.35);
    transition: opacity 1.4s ease;
  }
  .title-card.soft {
    opacity: 0.62;
  }
  .title-card h1 {
    font-size: clamp(16px, 2.4vw, 20px);
    font-weight: 600;
    letter-spacing: 0.04em;
    color: #ffe8c2;
    text-shadow: 0 0 14px rgba(255, 165, 70, 0.45);
  }
  .title-card p {
    margin-top: 3px;
    font-size: clamp(12px, 1.8vw, 13.5px);
    color: rgba(232, 236, 250, 0.82);
    letter-spacing: 0.01em;
  }

  .demo-pill {
    display: none;
    align-items: center;
    gap: 8px;
    background: rgba(255, 152, 64, 0.22);
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 198, 122, 0.45);
    border-radius: 999px;
    padding: 9px 16px;
    font-size: 13px;
    font-weight: 500;
    color: #ffebd0;
    letter-spacing: 0.02em;
    box-shadow: 0 6px 24px rgba(0, 0, 0, 0.3);
  }
  .demo-pill.visible {
    display: inline-flex;
  }
  .demo-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #ffb257;
    box-shadow: 0 0 10px #ffb257;
    animation: pulseDot 1.6s ease-in-out infinite;
  }
  @keyframes pulseDot {
    0%, 100% { transform: scale(0.85); opacity: 0.65; }
    50% { transform: scale(1.25); opacity: 1; }
  }

  .bottom-row {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    gap: 12px;
  }

  .status-pill {
    background: rgba(10, 14, 30, 0.48);
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 212, 155, 0.22);
    border-radius: 999px;
    padding: 10px 16px;
    font-size: 13.5px;
    color: rgba(255, 240, 218, 0.9);
    opacity: 0;
    transform: translateY(8px);
    transition: opacity 0.45s ease, transform 0.45s ease;
    pointer-events: none;
  }
  .status-pill.visible {
    opacity: 1;
    transform: translateY(0);
  }

  .audio-btn {
    pointer-events: auto;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    min-height: 54px;
    min-width: 138px;
    padding: 0 22px;
    border-radius: 999px;
    border: 1.5px solid rgba(255, 200, 128, 0.42);
    background: rgba(14, 20, 42, 0.72);
    backdrop-filter: blur(12px);
    -webkit-backdrop-filter: blur(12px);
    color: #fff2dc;
    font-size: 15.5px;
    font-weight: 600;
    letter-spacing: 0.02em;
    box-shadow: 0 8px 26px rgba(0, 0, 0, 0.42), inset 0 0 18px rgba(255, 162, 68, 0.14);
    cursor: pointer;
    touch-action: manipulation;
    transition: transform 0.15s ease, background 0.25s ease, border-color 0.25s ease, box-shadow 0.25s ease;
  }
  .audio-btn:active {
    transform: scale(0.95);
  }
  .audio-btn.playing {
    border-color: rgba(255, 198, 114, 0.72);
    background: rgba(34, 24, 48, 0.76);
    box-shadow: 0 8px 28px rgba(0, 0, 0, 0.45), 0 0 22px rgba(255, 162, 72, 0.26);
  }
  .audio-btn.muted {
    border-color: rgba(180, 196, 224, 0.3);
    background: rgba(12, 17, 34, 0.68);
    color: rgba(214, 224, 245, 0.78);
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.35);
  }
  .audio-btn svg {
    width: 22px;
    height: 22px;
    flex-shrink: 0;
  }

  .fallback-msg {
    display: none;
    position: fixed;
    inset: 0;
    align-items: center;
    justify-content: center;
    padding: 24px;
    text-align: center;
    background: #070b18;
    color: #ffe8c8;
    font-size: 16px;
    z-index: 50;
  }
  .fallback-msg.visible {
    display: flex;
  }
</style>
</head>
<body>
<canvas id="scene-canvas" aria-label="Lantern Cats Festival Night 3D Scene"></canvas>

<div class="hud">
  <div class="top-row">
    <div class="title-card" id="title-card">
      <h1>Lantern Cats</h1>
      <p>Touch or drag anywhere to call the nearest cat</p>
    </div>
    <div class="demo-pill" id="demo-pill">
      <span class="demo-dot"></span>
      <span>Demo · Touch anywhere to play</span>
    </div>
  </div>
  <div class="bottom-row">
    <div class="status-pill" id="status-pill"></div>
    <button type="button" class="audio-btn" id="audio-btn" aria-label="Toggle festival melody">
      <svg id="audio-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
        <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"></polygon>
        <path id="wave-1" d="M15.54 8.46a5 5 0 0 1 0 7.07"></path>
        <path id="wave-2" d="M19.07 4.93a10 10 0 0 1 0 14.14"></path>
        <line id="mute-slash" x1="22" y1="9" x2="16" y2="15" style="display:none;"></line>
        <line id="mute-slash2" x1="16" y1="9" x2="22" y2="15" style="display:none;"></line>
      </svg>
      <span id="audio-label">Play Melody</span>
    </button>
  </div>
</div>

<div class="fallback-msg" id="fallback-msg">
  WebGL is unavailable in this browser view. Please enable hardware acceleration or try a modern browser to watch the lantern cats fly.
</div>

<script type="module">
import * as THREE from 'https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js';

// ============================================================================
// SAFE INITIALIZATION & GLOBALS
// ============================================================================
const canvas = document.getElementById('scene-canvas');
const titleCard = document.getElementById('title-card');
const demoPill = document.getElementById('demo-pill');
const statusPill = document.getElementById('status-pill');
const audioBtn = document.getElementById('audio-btn');
const audioLabel = document.getElementById('audio-label');
const wave1 = document.getElementById('wave-1');
const wave2 = document.getElementById('wave-2');
const muteSlash1 = document.getElementById('mute-slash');
const muteSlash2 = document.getElementById('mute-slash2');
const fallbackMsg = document.getElementById('fallback-msg');

function checkDemoHash() {
  try {
    return window.location.hash === '#demo' || window.location.href.endsWith('#demo');
  } catch (_) {
    return false;
  }
}

let demoMode = checkDemoHash();
let demoTime = 0;
const DEMO_DURATION = 20.0;

if (demoMode) {
  demoPill.classList.add('visible');
}

setTimeout(() => {
  titleCard.classList.add('soft');
}, 6500);

let statusHideTimer = null;
function showStatus(text) {
  statusPill.textContent = text;
  statusPill.classList.add('visible');
  if (statusHideTimer) clearTimeout(statusHideTimer);
  statusHideTimer = setTimeout(() => {
    statusPill.classList.remove('visible');
  }, 2400);
}

// ============================================================================
// DETERMINISTIC PSEUDO-RANDOM (FOR CONSISTENT PICTURESQUE TOWN LAYOUT)
// ============================================================================
function mulberry32(seed) {
  let a = seed >>> 0;
  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 rand = mulberry32(20261122);

// ============================================================================
// RIVER & TERRAIN GEOMETRY FUNCTIONS
// ============================================================================
const WATER_Y = 0.0;
const QUAY_Y = 2.25;

function riverCenterX(z) {
  return Math.sin(z * 0.032) * 5.2 + Math.cos(z * 0.019) * 2.1;
}

function riverHalfWidth(z) {
  return 11.4 + Math.sin(z * 0.044 + 0.7) * 1.5;
}

function terrainHeightAt(x, z) {
  const cx = riverCenterX(z);
  const hw = riverHalfWidth(z);
  const distFromBank = Math.abs(x - cx) - hw;
  if (distFromBank <= 0) return WATER_Y;
  if (distFromBank < 12.0) {
    return QUAY_Y + (distFromBank / 12.0) * 0.65;
  }
  const hillT = distFromBank - 12.0;
  const ridge = Math.sin(z * 0.055 + x * 0.03) * 1.8 + Math.cos(z * 0.09 - x * 0.05) * 1.1;
  return QUAY_Y + 0.65 + Math.min(20.0, Math.pow(hillT * 0.14, 1.38) * 3.8) + Math.max(0, ridge * Math.min(1, hillT * 0.06));
}

// ============================================================================
// RENDERER, SCENE, CAMERAS & PLANAR REFLECTION TARGET
// ============================================================================
let renderer;
try {
  renderer = new THREE.WebGLRenderer({
    canvas,
    antialias: true,
    powerPreference: 'high-performance',
    alpha: false
  });
} catch (err) {
  fallbackMsg.classList.add('visible');
  throw err;
}

const initialW = window.innerWidth || 1280;
const initialH = window.innerHeight || 720;
const getDpr = () => Math.min(window.devicePixelRatio || 1, 2);

renderer.setPixelRatio(getDpr());
renderer.setSize(initialW, initialH, false);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.14;

const scene = new THREE.Scene();
const fogColor = new THREE.Color(0x0b1024);
scene.background = fogColor;
scene.fog = new THREE.FogExp2(0x0b1024, 0.0064);

function computeFov(w, h) {
  const aspect = w / Math.max(1, h);
  return aspect < 1.0 ? Math.min(68, 48 / Math.pow(aspect, 0.36)) : 46;
}

const mainCamera = new THREE.PerspectiveCamera(computeFov(initialW, initialH), initialW / Math.max(1, initialH), 0.3, 380);
const reflectCamera = new THREE.PerspectiveCamera(mainCamera.fov, mainCamera.aspect, mainCamera.near, mainCamera.far);

function createReflectSize(w, h) {
  const scale = Math.min(getDpr(), 1.5) * 0.56;
  return {
    rw: Math.max(256, Math.floor(w * scale)),
    rh: Math.max(256, Math.floor(h * scale))
  };
}
const { rw: initRW, rh: initRH } = createReflectSize(initialW, initialH);
const reflectRT = new THREE.WebGLRenderTarget(initRW, initRH, {
  minFilter: THREE.LinearFilter,
  magFilter: THREE.LinearFilter,
  format: THREE.RGBAFormat,
  type: THREE.UnsignedByteType,
  depthBuffer: true,
  stencilBuffer: false
});
reflectRT.texture.generateMipmaps = false;

// ============================================================================
// LIGHTING
// ============================================================================
const MOON_DIR = new THREE.Vector3(-0.20, 0.32, -0.925).normalize();

const hemiLight = new THREE.HemisphereLight(0x4b6aa8, 0x261a2c, 0.95);
scene.add(hemiLight);

const ambientLight = new THREE.AmbientLight(0x1f2848, 0.55);
scene.add(ambientLight);

const moonLight = new THREE.DirectionalLight(0xb8d0ff, 1.15);
moonLight.position.copy(MOON_DIR).multiplyScalar(120);
scene.add(moonLight);

// Warm town festival glow lights spaced along both banks
const townGlowPositions = [
  [-13, 6.5, -36], [14, 7.5, -28], [-12, 6.5, -14],
  [13, 6.5, -4], [-14, 6.5, 10], [13, 6.5, 22]
];
for (const [gx, gy, gz] of townGlowPositions) {
  const cx = riverCenterX(gz);
  const pl = new THREE.PointLight(0xff9944, 34, 38, 1.45);
  pl.position.set(cx + gx, gy, gz);
  scene.add(pl);
}

// ============================================================================
// PROCEDURAL CANVAS TEXTURES
// ============================================================================
function createGlowSpriteTexture() {
  const size = 128;
  const c = document.createElement('canvas');
  c.width = size;
  c.height = size;
  const ctx = c.getContext('2d');
  const g = ctx.createRadialGradient(size / 2, size / 2, 0, size / 2, size / 2, size / 2);
  g.addColorStop(0.0, 'rgba(255,255,255,1.0)');
  g.addColorStop(0.18, 'rgba(255,250,235,0.72)');
  g.addColorStop(0.45, 'rgba(255,235,200,0.22)');
  g.addColorStop(0.75, 'rgba(255,215,175,0.05)');
  g.addColorStop(1.0, 'rgba(255,215,175,0.0)');
  ctx.fillStyle = g;
  ctx.fillRect(0, 0, size, size);
  const tex = new THREE.CanvasTexture(c);
  tex.colorSpace = THREE.SRGBColorSpace;
  return tex;
}
const glowSpriteTex = createGlowSpriteTexture();

function drawWashiFibers(ctx, w, h, seed, tintLight, tintDark) {
  const r = mulberry32(seed);
  ctx.lineWidth = 1;
  for (let i = 0; i < 420; i++) {
    const x = r() * w;
    const y = r() * h;
    const len = 6 + r() * 20;
    const ang = r() * Math.PI * 2;
    ctx.strokeStyle = r() > 0.45 ? tintLight : tintDark;
    ctx.beginPath();
    ctx.moveTo(x, y);
    ctx.quadraticCurveTo(
      x + Math.cos(ang + 0.3) * len * 0.5,
      y + Math.sin(ang + 0.3) * len * 0.5,
      x + Math.cos(ang) * len,
      y + Math.sin(ang) * len
    );
    ctx.stroke();
  }
}

function createCatHeadTexture(isOrange) {
  const w = 512;
  const h = 256;
  const c = document.createElement('canvas');
  c.width = w;
  c.height = h;
  const ctx = c.getContext('2d');

  // Base paper gradient (lighter creamy/pearl lower cheeks & muzzle, richer crown)
  const bg = ctx.createLinearGradient(0, 0, 0, h);
  if (isOrange) {
    bg.addColorStop(0.0, '#e86814');
    bg.addColorStop(0.35, '#ff8e2b');
    bg.addColorStop(0.68, '#ffba66');
    bg.addColorStop(1.0, '#ffe4b8');
  } else {
    bg.addColorStop(0.0, '#8d9cb5');
    bg.addColorStop(0.35, '#b8c6db');
    bg.addColorStop(0.68, '#d9e3f2');
    bg.addColorStop(1.0, '#f2f6fc');
  }
  ctx.fillStyle = bg;
  ctx.fillRect(0, 0, w, h);

  drawWashiFibers(
    ctx, w, h, isOrange ? 101 : 202,
    'rgba(255,255,245,0.14)',
    isOrange ? 'rgba(130,45,8,0.10)' : 'rgba(55,68,94,0.11)'
  );

  const cx = w * 0.5;
  const cy = h * 0.52;

  // Soft pale cream/silver muzzle glow mask
  const muz = ctx.createRadialGradient(cx, cy + 20, 6, cx, cy + 20, 64);
  muz.addColorStop(0, isOrange ? 'rgba(255, 244, 222, 0.85)' : 'rgba(248, 252, 255, 0.88)');
  muz.addColorStop(0.6, isOrange ? 'rgba(255, 232, 195, 0.35)' : 'rgba(232, 240, 252, 0.35)');
  muz.addColorStop(1, 'rgba(255, 255, 255, 0)');
  ctx.fillStyle = muz;
  ctx.fillRect(cx - 80, cy - 50, 160, 125);

  // Tabby forehead "M" markings
  const stripeCol = isOrange ? 'rgba(166, 52, 8, 0.72)' : 'rgba(72, 84, 110, 0.72)';
  ctx.strokeStyle = stripeCol;
  ctx.lineCap = 'round';
  ctx.lineJoin = 'round';
  ctx.lineWidth = 7;

  // Center forehead stripes
  ctx.beginPath();
  ctx.moveTo(cx, cy - 82);
  ctx.lineTo(cx, cy - 44);
  ctx.stroke();

  for (const s of [-1, 1]) {
    ctx.lineWidth = 6.5;
    ctx.beginPath();
    ctx.moveTo(cx + s * 16, cy - 78);
    ctx.quadraticCurveTo(cx + s * 22, cy - 54, cx + s * 14, cy - 42);
    ctx.stroke();

    ctx.lineWidth = 5.5;
    ctx.beginPath();
    ctx.moveTo(cx + s * 32, cy - 68);
    ctx.quadraticCurveTo(cx + s * 42, cy - 46, cx + s * 30, cy - 35);
    ctx.stroke();

    // Cheek tabby stripes sweeping outward
    ctx.lineWidth = 5;
    for (let k = 0; k < 3; k++) {
      const yOff = -4 + k * 14;
      ctx.beginPath();
      ctx.moveTo(cx + s * 56, cy + yOff);
      ctx.quadraticCurveTo(cx + s * 86, cy + yOff + 5, cx + s * 114, cy + yOff - 2 + k * 3);
      ctx.stroke();
    }

    // Soft glowing rosy cheek blush
    const blush = ctx.createRadialGradient(cx + s * 48, cy + 16, 2, cx + s * 48, cy + 16, 22);
    blush.addColorStop(0, isOrange ? 'rgba(255, 96, 86, 0.42)' : 'rgba(222, 138, 178, 0.36)');
    blush.addColorStop(1, 'rgba(255, 110, 110, 0)');
    ctx.fillStyle = blush;
    ctx.beginPath();
    ctx.arc(cx + s * 48, cy + 16, 22, 0, Math.PI * 2);
    ctx.fill();
  }

  // Cute painted lantern-cat smile ("ω" mouth)
  ctx.strokeStyle = isOrange ? '#6b2009' : '#3a4358';
  ctx.lineWidth = 4.2;
  ctx.beginPath();
  ctx.moveTo(cx, cy + 15);
  ctx.lineTo(cx, cy + 24);
  ctx.stroke();
  ctx.beginPath();
  ctx.arc(cx - 10, cy + 25, 10, 0.15, Math.PI - 0.25);
  ctx.stroke();
  ctx.beginPath();
  ctx.arc(cx + 10, cy + 25, 10, 0.25, Math.PI - 0.15);
  ctx.stroke();

  // Back-of-head tabby stripes
  ctx.strokeStyle = isOrange ? 'rgba(166, 52, 8, 0.55)' : 'rgba(72, 84, 110, 0.55)';
  ctx.lineWidth = 8;
  for (let k = -1; k <= 1; k++) {
    ctx.beginPath();
    ctx.moveTo(w * 0.08, cy - 38 + k * 24);
    ctx.quadraticCurveTo(w * 0.0, cy - 30 + k * 24, w * 0.0, cy - 32 + k * 24);
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(w * 0.92, cy - 38 + k * 24);
    ctx.lineTo(w, cy - 32 + k * 24);
    ctx.stroke();
  }

  const tex = new THREE.CanvasTexture(c);
  tex.colorSpace = THREE.SRGBColorSpace;
  tex.wrapS = THREE.RepeatWrapping;
  tex.wrapT = THREE.ClampToEdgeWrapping;
  return tex;
}

function createCatBodyTexture(isOrange) {
  const w = 256;
  const h = 256;
  const c = document.createElement('canvas');
  c.width = w;
  c.height = h;
  const ctx = c.getContext('2d');

  // Horizontal (u) wraps around circumference: top-back is around u = 0.25/0.75 depending on rotation;
  // we paint symmetric tabby bands with lighter belly band
  const g = ctx.createLinearGradient(0, 0, w, 0);
  if (isOrange) {
    g.addColorStop(0.0, '#ff9836');
    g.addColorStop(0.25, '#e86812');
    g.addColorStop(0.5, '#ff9836');
    g.addColorStop(0.75, '#ffe0ad');
    g.addColorStop(1.0, '#ff9836');
  } else {
    g.addColorStop(0.0, '#bfcbe0');
    g.addColorStop(0.25, '#8c9bb5');
    g.addColorStop(0.5, '#bfcbe0');
    g.addColorStop(0.75, '#eff5fc');
    g.addColorStop(1.0, '#bfcbe0');
  }
  ctx.fillStyle = g;
  ctx.fillRect(0, 0, w, h);

  drawWashiFibers(
    ctx, w, h, isOrange ? 303 : 404,
    'rgba(255,255,245,0.16)',
    isOrange ? 'rgba(140,48,8,0.12)' : 'rgba(60,72,96,0.12)'
  );

  // Painted tabby bands along lantern middle
  ctx.fillStyle = isOrange ? 'rgba(176, 56, 10, 0.56)' : 'rgba(68, 82, 110, 0.54)';
  for (let k = 0; k < 2; k++) {
    const yCenter = h * (0.34 + k * 0.32);
    ctx.beginPath();
    ctx.ellipse(w * 0.25, yCenter, w * 0.24, 15, 0, 0, Math.PI * 2);
    ctx.fill();
  }

  // Subtle decorative gold/silver lantern trim near ends
  ctx.fillStyle = isOrange ? 'rgba(130, 42, 10, 0.45)' : 'rgba(62, 74, 100, 0.45)';
  ctx.fillRect(0, 0, w, 12);
  ctx.fillRect(0, h - 12, w, 12);

  const tex = new THREE.CanvasTexture(c);
  tex.colorSpace = THREE.SRGBColorSpace;
  tex.wrapS = THREE.RepeatWrapping;
  tex.wrapT = THREE.ClampToEdgeWrapping;
  return tex;
}

function createHouseTextures(variant) {
  const w = 256;
  const h = 256;
  const cMap = document.createElement('canvas');
  cMap.width = w;
  cMap.height = h;
  const ctx = cMap.getContext('2d');

  const cEmis = document.createElement('canvas');
  cEmis.width = w;
  cEmis.height = h;
  const ectx = cEmis.getContext('2d');

  // Warm plaster / cedar walls
  const plasterColors = ['#3c3330', '#423834', '#362e31', '#473c35'];
  const timberColor = '#211815';
  ctx.fillStyle = plasterColors[variant % plasterColors.length];
  ctx.fillRect(0, 0, w, h);

  ectx.fillStyle = '#000000';
  ectx.fillRect(0, 0, w, h);

  // Subtle wall grain
  const r = mulberry32(900 + variant * 37);
  for (let i = 0; i < 200; i++) {
    ctx.fillStyle = r() > 0.5 ? 'rgba(255,235,210,0.04)' : 'rgba(0,0,0,0.06)';
    ctx.fillRect(r() * w, r() * h, 4 + r() * 14, 2 + r() * 6);
  }

  // Timber frame posts & beams
  ctx.fillStyle = timberColor;
  ctx.fillRect(0, 0, w, 12);
  ctx.fillRect(0, h * 0.48, w, 10);
  ctx.fillRect(0, h - 14, w, 14);
  for (let x = 0; x <= w; x += 64) {
    ctx.fillRect(x - 5, 0, 10, h);
  }

  // Glowing shoji windows (2 rows x 2-3 panes)
  const rows = [
    { y: 26, wh: 82 },
    { y: 146, wh: 84 }
  ];
  const cols = [16, 86, 156];
  const winW = 54;

  for (let ri = 0; ri < rows.length; ri++) {
    const row = rows[ri];
    for (let ci = 0; ci < cols.length; ci++) {
      const lit = r() > 0.18;
      const wx = cols[ci];
      const wy = row.y;
      if (lit) {
        const warmShift = r();
        const wg = ctx.createLinearGradient(wx, wy, wx, wy + row.wh);
        const topC = warmShift > 0.5 ? '#ffca6b' : '#ffb85c';
        const botC = warmShift > 0.5 ? '#ff8b2e' : '#ff9838';
        wg.addColorStop(0, topC);
        wg.addColorStop(1, botC);
        ctx.fillStyle = wg;
        ctx.fillRect(wx, wy, winW, row.wh);

        const eg = ectx.createLinearGradient(wx, wy, wx, wy + row.wh);
        eg.addColorStop(0, topC);
        eg.addColorStop(1, botC);
        ectx.fillStyle = eg;
        ectx.fillRect(wx, wy, winW, row.wh);
      } else {
        ctx.fillStyle = '#1b1d2b';
        ctx.fillRect(wx, wy, winW, row.wh);
      }

      // Shoji lattice muntins
      ctx.fillStyle = '#261914';
      ectx.fillStyle = '#000000';
      ctx.strokeStyle = '#261914';
      ctx.lineWidth = 4;
      ctx.strokeRect(wx, wy, winW, row.wh);
      for (let gx = 1; gx <= 2; gx++) {
        const lx = wx + (winW / 3) * gx;
        ctx.fillRect(lx - 1.5, wy, 3, row.wh);
        ectx.fillRect(lx - 1.5, wy, 3, row.wh);
      }
      for (let gy = 1; gy <= 3; gy++) {
        const ly = wy + (row.wh / 4) * gy;
        ctx.fillRect(wx, ly - 1.5, winW, 3);
        ectx.fillRect(wx, ly - 1.5, winW, 3);
      }
    }
  }

  const map = new THREE.CanvasTexture(cMap);
  map.colorSpace = THREE.SRGBColorSpace;
  const emissiveMap = new THREE.CanvasTexture(cEmis);
  emissiveMap.colorSpace = THREE.SRGBColorSpace;
  return { map, emissiveMap };
}

function createRoofTileTexture() {
  const w = 256;
  const h = 256;
  const c = document.createElement('canvas');
  c.width = w;
  c.height = h;
  const ctx = c.getContext('2d');
  ctx.fillStyle = '#1c2438';
  ctx.fillRect(0, 0, w, h);

  const rows = 10;
  const cols = 8;
  const rh = h / rows;
  const cw = w / cols;
  for (let r = 0; r < rows; r++) {
    for (let col = 0; col < cols; col++) {
      const x = col * cw + (r % 2) * (cw * 0.5) - cw * 0.25;
      const y = r * rh;
      const g = ctx.createLinearGradient(x, y, x, y + rh);
      g.addColorStop(0, '#2a3652');
      g.addColorStop(0.75, '#192133');
      g.addColorStop(1, '#101624');
      ctx.fillStyle = g;
      ctx.beginPath();
      ctx.arc(x + cw * 0.5, y + rh * 0.25, cw * 0.52, 0, Math.PI, false);
      ctx.lineTo(x, y);
      ctx.closePath();
      ctx.fill();
      ctx.strokeStyle = 'rgba(130, 165, 220, 0.14)';
      ctx.lineWidth = 1.2;
      ctx.stroke();
    }
  }
  const tex = new THREE.CanvasTexture(c);
  tex.colorSpace = THREE.SRGBColorSpace;
  tex.wrapS = THREE.RepeatWrapping;
  tex.wrapT = THREE.RepeatWrapping;
  tex.repeat.set(2, 2);
  return tex;
}

function createStoneTexture() {
  const w = 256;
  const h = 128;
  const c = document.createElement('canvas');
  c.width = w;
  c.height = h;
  const ctx = c.getContext('2d');
  ctx.fillStyle = '#1a2030';
  ctx.fillRect(0, 0, w, h);
  const r = mulberry32(777);
  const rows = 4;
  const rh = h / rows;
  for (let row = 0; row < rows; row++) {
    let x = (row % 2) * -18;
    while (x < w) {
      const bw = 34 + r() * 26;
      const shade = 36 + Math.floor(r() * 24);
      ctx.fillStyle = `rgb(${shade}, ${shade + 5}, ${shade + 16})`;
      ctx.fillRect(x + 2, row * rh + 2, bw - 3, rh - 3);
      x += bw;
    }
  }
  const tex = new THREE.CanvasTexture(c);
  tex.colorSpace = THREE.SRGBColorSpace;
  tex.wrapS = THREE.RepeatWrapping;
  tex.wrapT = THREE.RepeatWrapping;
  tex.repeat.set(24, 1);
  return tex;
}

const roofTileTex = createRoofTileTexture();
const stoneTex = createStoneTexture();
const houseTextureVariants = [0, 1, 2, 3].map(createHouseTextures);

// ============================================================================
// SKY DOME, HARVEST MOON, STARS & DISTANT MOUNTAINS
// ============================================================================
const skyUniforms = {
  uTime: { value: 0 },
  uMoonDir: { value: MOON_DIR.clone() }
};

const skyMat = new THREE.ShaderMaterial({
  uniforms: skyUniforms,
  side: THREE.BackSide,
  depthWrite: false,
  fog: false,
  vertexShader: `
    varying vec3 vDir;
    void main() {
      vDir = normalize(position);
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
    }
  `,
  fragmentShader: `
    uniform float uTime;
    uniform vec3 uMoonDir;
    varying vec3 vDir;

    float hash(vec2 p) {
      return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453123);
    }
    float noise(vec2 p) {
      vec2 i = floor(p);
      vec2 f = fract(p);
      vec2 u = f * f * (3.0 - 2.0 * f);
      return mix(
        mix(hash(i + vec2(0.0, 0.0)), hash(i + vec2(1.0, 0.0)), u.x),
        mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), u.x),
        u.y
      );
    }

    void main() {
      vec3 d = normalize(vDir);
      float h = clamp(d.y, 0.0, 1.0);

      vec3 colHorizon = vec3(0.085, 0.068, 0.145);
      vec3 colMid     = vec3(0.022, 0.048, 0.135);
      vec3 colZenith  = vec3(0.007, 0.014, 0.046);

      vec3 col = mix(colHorizon, colMid, smoothstep(0.0, 0.34, h));
      col = mix(col, colZenith, smoothstep(0.24, 0.85, h));

      // Subtle warm festival haze near town horizon
      float warmGlow = exp(-h * 9.0) * (0.45 + 0.55 * max(0.0, -d.z * 0.5 + 0.5));
      col += vec3(0.14, 0.065, 0.038) * warmGlow * 0.55;

      // Soft nocturnal wispy clouds
      if (d.y > 0.02) {
        vec2 cuv = d.xz / (d.y + 0.24) * 1.4 + vec2(uTime * 0.008, uTime * 0.004);
        float c1 = noise(cuv);
        float c2 = noise(cuv * 2.3 + vec2(4.2, -1.7));
        float cloud = smoothstep(0.52, 0.86, c1 * 0.65 + c2 * 0.35) * smoothstep(0.02, 0.22, d.y) * smoothstep(0.92, 0.35, d.y);
        float moonLit = pow(max(dot(d, uMoonDir), 0.0), 4.0);
        col += mix(vec3(0.06, 0.09, 0.18), vec3(0.32, 0.36, 0.45), moonLit) * cloud * 0.36;
      }

      // Full harvest moon + atmospheric halo
      float mDot = max(dot(d, uMoonDir), 0.0);
      float moonDisc = smoothstep(0.9985, 0.99925, mDot);
      float moonCorona = pow(mDot, 160.0) * 0.85 + pow(mDot, 16.0) * 0.20 + pow(mDot, 4.5) * 0.06;
      vec3 moonColor = vec3(1.15, 1.08, 0.90);
      col += vec3(0.58, 0.66, 0.85) * moonCorona;
      col = mix(col, moonColor, moonDisc);

      gl_FragColor = vec4(col, 1.0);
      #include <tonemapping_fragment>
      #include <colorspace_fragment>
    }
  `
});

const skyDome = new THREE.Mesh(new THREE.SphereGeometry(260, 32, 24), skyMat);
scene.add(skyDome);

// Twinkling starfield (strictly above horizon so it reflects cleanly in the river)
const STAR_COUNT = 680;
const starPositions = new Float32Array(STAR_COUNT * 3);
const starColors = new Float32Array(STAR_COUNT * 3);
const starSizes = new Float32Array(STAR_COUNT);
const starPhases = new Float32Array(STAR_COUNT);

for (let i = 0; i < STAR_COUNT; i++) {
  const theta = rand() * Math.PI * 2;
  const elev = 0.09 + Math.pow(rand(), 0.72) * 1.42;
  const r = 215;
  starPositions[i * 3] = Math.cos(theta) * Math.cos(elev) * r;
  starPositions[i * 3 + 1] = Math.sin(elev) * r;
  starPositions[i * 3 + 2] = Math.sin(theta) * Math.cos(elev) * r;

  const tint = rand();
  const c = new THREE.Color().setHSL(
    tint > 0.7 ? 0.11 : (tint > 0.35 ? 0.60 : 0.56),
    tint > 0.7 ? 0.55 : 0.35,
    0.76 + rand() * 0.24
  );
  starColors[i * 3] = c.r;
  starColors[i * 3 + 1] = c.g;
  starColors[i * 3 + 2] = c.b;
  starSizes[i] = 1.4 + Math.pow(rand(), 2.2) * 3.8;
  starPhases[i] = rand() * Math.PI * 2;
}

const starGeo = new THREE.BufferGeometry();
starGeo.setAttribute('position', new THREE.BufferAttribute(starPositions, 3));
starGeo.setAttribute('aColor', new THREE.BufferAttribute(starColors, 3));
starGeo.setAttribute('aSize', new THREE.BufferAttribute(starSizes, 1));
starGeo.setAttribute('aPhase', new THREE.BufferAttribute(starPhases, 1));

const starUniforms = {
  uTime: { value: 0 },
  uPixelRatio: { value: getDpr() }
};
const starMat = new THREE.ShaderMaterial({
  uniforms: starUniforms,
  transparent: true,
  depthWrite: false,
  blending: THREE.AdditiveBlending,
  fog: false,
  vertexShader: `
    attribute vec3 aColor;
    attribute float aSize;
    attribute float aPhase;
    uniform float uTime;
    uniform float uPixelRatio;
    varying vec3 vColor;
    varying float vAlpha;
    void main() {
      vColor = aColor;
      float tw = 0.58 + 0.42 * sin(uTime * (1.2 + fract(aPhase) * 2.2) + aPhase * 6.28);
      vAlpha = tw;
      vec4 mv = modelViewMatrix * vec4(position, 1.0);
      gl_PointSize = clamp(aSize * uPixelRatio * (0.8 + 0.35 * tw), 1.5, 10.0);
      gl_Position = projectionMatrix * mv;
    }
  `,
  fragmentShader: `
    varying vec3 vColor;
    varying float vAlpha;
    void main() {
      float d = length(gl_PointCoord - 0.5) * 2.0;
      if (d > 1.0) discard;
      float glow = exp(-d * d * 4.5);
      gl_FragColor = vec4(vColor * glow * vAlpha, glow * vAlpha);
    }
  `
});
const stars = new THREE.Points(starGeo, starMat);
scene.add(stars);

// Distant misty mountain ring (base strictly at y = 0 so it reflects cleanly)
{
  const segs = 96;
  const positions = [];
  const indices = [];
  const radius = 148;
  for (let i = 0; i <= segs; i++) {
    const a = (i / segs) * Math.PI * 2;
    const x = Math.cos(a) * radius;
    const z = Math.sin(a) * radius;
    // Leave a lower river valley opening toward -Z and +Z
    const valleyDip = 0.42 + 0.58 * Math.pow(Math.abs(Math.cos(a)), 0.75);
    const h = (14.0 + Math.sin(a * 5.0 + 0.7) * 7.5 + Math.cos(a * 11.0) * 4.2 + Math.sin(a * 17.0) * 2.2) * valleyDip;
    positions.push(x, 0.0, z);
    positions.push(x, Math.max(4.5, h), z);
  }
  for (let i = 0; i < segs; i++) {
    const b0 = i * 2;
    const t0 = b0 + 1;
    const b1 = (i + 1) * 2;
    const t1 = b1 + 1;
    indices.push(b0, b1, t0, t0, b1, t1);
  }
  const mGeo = new THREE.BufferGeometry();
  mGeo.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
  mGeo.setIndex(indices);
  mGeo.computeVertexNormals();
  const mMat = new THREE.MeshBasicMaterial({
    color: 0x0b1228,
    side: THREE.DoubleSide
  });
  const mountains = new THREE.Mesh(mGeo, mMat);
  scene.add(mountains);
}

// ============================================================================
// RIVER SURFACE (CUSTOM PLANAR REFLECTION + SHIMMERING RIPPLES)
// ============================================================================
const waterUniforms = {
  uReflectTex: { value: reflectRT.texture },
  uTime: { value: 0 },
  uCatPos0: { value: new THREE.Vector3(0, 10, 0) },
  uCatPos1: { value: new THREE.Vector3(0, 10, 0) },
  uMoonDir: { value: MOON_DIR.clone() },
  uFogColor: { value: scene.fog.color },
  uFogDensity: { value: scene.fog.density }
};

const waterMat = new THREE.ShaderMaterial({
  uniforms: waterUniforms,
  vertexShader: `
    varying vec3 vWorldPos;
    varying vec4 vClipPos;
    void main() {
      vec4 wp = modelMatrix * vec4(position, 1.0);
      vWorldPos = wp.xyz;
      vClipPos = projectionMatrix * viewMatrix * wp;
      gl_Position = vClipPos;
    }
  `,
  fragmentShader: `
    uniform sampler2D uReflectTex;
    uniform float uTime;
    uniform vec3 uCatPos0;
    uniform vec3 uCatPos1;
    uniform vec3 uMoonDir;
    uniform vec3 uFogColor;
    uniform float uFogDensity;

    varying vec3 vWorldPos;
    varying vec4 vClipPos;

    void main() {
      vec2 screenUV = (vClipPos.xy / max(vClipPos.w, 0.0001)) * 0.5 + 0.5;
      vec2 baseReflUV = vec2(screenUV.x, 1.0 - screenUV.y);

      vec3 viewVec = cameraPosition - vWorldPos;
      float dist = length(viewVec);
      vec3 V = viewVec / max(dist, 0.001);

      vec2 p = vWorldPos.xz;
      float t = uTime;

      // Flowing nocturnal river ripples (gentle current along +Z)
      float dwdx =
        cos(p.x * 0.88 + p.y * 0.52 - t * 1.35) * 0.42 +
        cos(p.x * 1.78 - p.y * 1.18 - t * 2.05 + 1.4) * 0.44 +
        cos(p.x * 3.35 + p.y * 2.45 - t * 2.85 + 2.6) * 0.36 -
        sin(p.x * 0.45 - p.y * 1.85 - t * 1.05) * 0.16;

      float dwdz =
        cos(p.x * 0.88 + p.y * 0.52 - t * 1.35) * 0.25 -
        cos(p.x * 1.78 - p.y * 1.18 - t * 2.05 + 1.4) * 0.32 +
        cos(p.x * 3.35 + p.y * 2.45 - t * 2.85 + 2.6) * 0.30 +
        sin(p.x * 0.45 - p.y * 1.85 - t * 1.05) * 0.58;

      // Expanding delicate water rings when either cat swoops low over the river
      float hFade0 = clamp(1.0 - (uCatPos0.y - 2.2) / 9.5, 0.0, 1.0);
      vec2 d0 = p - uCatPos0.xz;
      float r0 = length(d0);
      float ring0 = sin(r0 * 2.6 - t * 5.2) * exp(-r0 * 0.19) * hFade0;
      dwdx += (d0.x / max(r0, 0.05)) * ring0 * 1.25;
      dwdz += (d0.y / max(r0, 0.05)) * ring0 * 1.25;

      float hFade1 = clamp(1.0 - (uCatPos1.y - 2.2) / 9.5, 0.0, 1.0);
      vec2 d1 = p - uCatPos1.xz;
      float r1 = length(d1);
      float ring1 = sin(r1 * 2.6 - t * 5.2) * exp(-r1 * 0.19) * hFade1;
      dwdx += (d1.x / max(r1, 0.05)) * ring1 * 1.25;
      dwdz += (d1.y / max(r1, 0.05)) * ring1 * 1.25;

      float distAtten = clamp(1.0 / (1.0 + dist * 0.016), 0.25, 1.0);
      vec2 offset = vec2(dwdx * 0.0095, dwdz * 0.0205) * distAtten;

      // Subtle vertical ripple shimmer multi-tap
      vec2 uv0 = clamp(baseReflUV + offset, vec2(0.003), vec2(0.997));
      vec2 uv1 = clamp(baseReflUV + offset * 1.4 + vec2(0.0, 0.007 * distAtten), vec2(0.003), vec2(0.997));
      vec2 uv2 = clamp(baseReflUV + offset * 0.6 - vec2(0.0, 0.007 * distAtten), vec2(0.003), vec2(0.997));

      vec3 refl =
        texture2D(uReflectTex, uv0).rgb * 0.56 +
        texture2D(uReflectTex, uv1).rgb * 0.22 +
        texture2D(uReflectTex, uv2).rgb * 0.22;

      vec3 N = normalize(vec3(-dwdx * 0.058, 1.0, -dwdz * 0.058));
      float ndv = max(dot(N, V), 0.0);
      float fresnel = mix(0.46, 0.96, pow(1.0 - ndv, 2.3));

      vec3 deepWater = vec3(0.006, 0.015, 0.036);

      // Moon shimmer path across ripples
      vec3 H = normalize(uMoonDir + V);
      float moonSpec = pow(max(dot(N, H), 0.0), 130.0) * 0.72 + pow(max(dot(N, H), 0.0), 28.0) * 0.08;

      vec3 col = mix(deepWater, refl * 1.12, fresnel);
      col += vec3(0.76, 0.85, 1.0) * moonSpec;

      // Subtle warm glow on water directly underneath low-flying cats
      float catGlow0 = exp(-r0 * r0 * 0.016) * hFade0 * 0.16;
      float catGlow1 = exp(-r1 * r1 * 0.016) * hFade1 * 0.14;
      col += vec3(1.0, 0.45, 0.10) * catGlow0 + vec3(0.60, 0.76, 1.0) * catGlow1;

      // Match exact scene FogExp2
      float fogFactor = 1.0 - exp(-pow(dist * uFogDensity, 2.0));
      col = mix(col, uFogColor, clamp(fogFactor, 0.0, 1.0));

      gl_FragColor = vec4(col, 1.0);
      #include <tonemapping_fragment>
      #include <colorspace_fragment>
    }
  `
});

const waterGeo = new THREE.PlaneGeometry(110, 290, 1, 1);
waterGeo.rotateX(-Math.PI / 2);
const waterMesh = new THREE.Mesh(waterGeo, waterMat);
waterMesh.position.set(0, WATER_Y, -10);
scene.add(waterMesh);

// ============================================================================
// WINDING RIVERBANKS, STONE QUAYS, TOWN HOUSES, BRIDGE, WILLOWS & LIGHT STRINGS
// ============================================================================
const obstacles = []; // Rotated boxes for houses, bridge, tall trees
const lightStringCurves = []; // Catenary curves for weaving avoidance

// Build sculpted left & right terrain banks + vertical stone embankments (strictly y >= 0)
{
  const zSegs = 90;
  const xSegs = 16;
  const zMin = -130;
  const zMax = 110;

  const bankMat = new THREE.MeshStandardMaterial({
    color: 0x18212b,
    roughness: 0.94,
    metalness: 0.04
  });
  const stoneMat = new THREE.MeshStandardMaterial({
    map: stoneTex,
    roughness: 0.88,
    metalness: 0.06
  });
  const woodRailMat = new THREE.MeshStandardMaterial({
    color: 0x3b261d,
    roughness: 0.85
  });

  for (const side of [-1, 1]) {
    // Bank terrain surface
    const pos = [];
    const uvs = [];
    const idx = [];
    for (let iz = 0; iz <= zSegs; iz++) {
      const tz = iz / zSegs;
      const z = THREE.MathUtils.lerp(zMin, zMax, tz);
      const cx = riverCenterX(z);
      const hw = riverHalfWidth(z);
      for (let ix = 0; ix <= xSegs; ix++) {
        const tx = ix / xSegs;
        const dist = Math.pow(tx, 1.55) * 76.0;
        const x = cx + side * (hw + dist);
        const y = dist < 0.001 ? QUAY_Y : terrainHeightAt(x, z);
        pos.push(x, y, z);
        uvs.push(tx * 6, tz * 14);
      }
    }
    const stride = xSegs + 1;
    for (let iz = 0; iz < zSegs; iz++) {
      for (let ix = 0; ix < xSegs; ix++) {
        const a = iz * stride + ix;
        const b = a + 1;
        const c = a + stride;
        const d = c + 1;
        if (side > 0) {
          idx.push(a, c, b, b, c, d);
        } else {
          idx.push(a, b, c, b, d, c);
        }
      }
    }
    const g = new THREE.BufferGeometry();
    g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
    g.setAttribute('uv', new THREE.Float32BufferAttribute(uvs, 2));
    g.setIndex(idx);
    g.computeVertexNormals();
    scene.add(new THREE.Mesh(g, bankMat));

    // Vertical stone embankment wall (y = 0 to QUAY_Y)
    const wPos = [];
    const wUvs = [];
    const wIdx = [];
    for (let iz = 0; iz <= zSegs; iz++) {
      const tz = iz / zSegs;
      const z = THREE.MathUtils.lerp(zMin, zMax, tz);
      const x = riverCenterX(z) + side * riverHalfWidth(z);
      wPos.push(x, 0.0, z);
      wUvs.push(tz, 0);
      wPos.push(x, QUAY_Y + 0.08, z);
      wUvs.push(tz, 1);
    }
    for (let iz = 0; iz < zSegs; iz++) {
      const a = iz * 2;
      const b = a + 1;
      const c = a + 2;
      const d = a + 3;
      if (side > 0) {
        wIdx.push(a, b, c, b, d, c);
      } else {
        wIdx.push(a, c, b, b, c, d);
      }
    }
    const wg = new THREE.BufferGeometry();
    wg.setAttribute('position', new THREE.Float32BufferAttribute(wPos, 3));
    wg.setAttribute('uv', new THREE.Float32BufferAttribute(wUvs, 2));
    wg.setIndex(wIdx);
    wg.computeVertexNormals();
    scene.add(new THREE.Mesh(wg, stoneMat));

    // Riverside stone bollard lanterns along the promenade
    const postGeo = new THREE.CylinderGeometry(0.14, 0.18, 1.35, 6);
    const bulbGeo = new THREE.SphereGeometry(0.22, 8, 8);
    const capGeo = new THREE.ConeGeometry(0.38, 0.26, 6);
    const lanternGlassMat = new THREE.MeshBasicMaterial({ color: 0xffc86c });

    for (let z = -66; z <= 56; z += 11.5) {
      if (Math.abs(z - (-18)) < 4.5) continue; // Bridge opening
      const x = riverCenterX(z) + side * (riverHalfWidth(z) + 0.7);
      const grp = new THREE.Group();
      grp.position.set(x, QUAY_Y, z);
      const p = new THREE.Mesh(postGeo, woodRailMat);
      p.position.y = 0.67;
      grp.add(p);
      const b = new THREE.Mesh(bulbGeo, lanternGlassMat);
      b.position.y = 1.48;
      grp.add(b);
      const cap = new THREE.Mesh(capGeo, woodRailMat);
      cap.position.y = 1.74;
      grp.add(cap);
      const halo = new THREE.Sprite(new THREE.SpriteMaterial({
        map: glowSpriteTex,
        color: 0xffa442,
        transparent: true,
        opacity: 0.62,
        blending: THREE.AdditiveBlending,
        depthWrite: false
      }));
      halo.position.y = 1.48;
      halo.scale.set(2.4, 2.4, 1);
      grp.add(halo);
      scene.add(grp);
    }
  }
}

// Helper: Curved traditional festival roof geometry (upturned eaves!)
function createCurvedRoofGeometry(width, depth, height) {
  const segX = 10;
  const segZ = 8;
  const geo = new THREE.BufferGeometry();
  const positions = [];
  const uvs = [];
  const indices = [];

  for (let iz = 0; iz <= segZ; iz++) {
    const vz = iz / segZ; // 0..1 along Z
    const zNorm = vz * 2 - 1; // -1..1
    for (let ix = 0; ix <= segX; ix++) {
      const ux = ix / segX; // 0..1 across X
      const xNorm = ux * 2 - 1; // -1..1

      // Concave East-Asian roof pitch peaking along Z ridge (xNorm = 0)
      const ax = Math.abs(xNorm);
      const az = Math.abs(zNorm);
      const ridgeSlope = Math.pow(1.0 - ax, 1.45);
      // Slight hipped taper near front/back + charming upturned corner eaves!
      const cornerFlare = Math.pow(ax, 2.2) * Math.pow(az, 2.0) * 0.34;
      const eaveLift = Math.pow(ax, 3.0) * 0.10;
      const y = (ridgeSlope * (1.0 - az * az * 0.18) + cornerFlare + eaveLift) * height;
      const flareExpand = 1.0 + Math.pow(ax, 2.2) * Math.pow(az, 2.0) * 0.14;

      positions.push(xNorm * (width * 0.5) * flareExpand, y, zNorm * (depth * 0.5) * flareExpand);
      uvs.push(ux * 2.0, vz * 2.0);
    }
  }
  const stride = segX + 1;
  for (let iz = 0; iz < segZ; iz++) {
    for (let ix = 0; ix < segX; ix++) {
      const a = iz * stride + ix;
      const b = a + 1;
      const c = a + stride;
      const d = c + 1;
      indices.push(a, c, b, b, c, d);
    }
  }
  geo.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
  geo.setAttribute('uv', new THREE.Float32BufferAttribute(uvs, 2));
  geo.setIndex(indices);
  geo.computeVertexNormals();
  return geo;
}

const roofMat = new THREE.MeshStandardMaterial({
  map: roofTileTex,
  color: 0x2a3654,
  roughness: 0.62,
  metalness: 0.16,
  side: THREE.DoubleSide
});
const trimWoodMat = new THREE.MeshStandardMaterial({ color: 0x2d1b15, roughness: 0.85 });
const redAccentMat = new THREE.MeshStandardMaterial({ color: 0x7a1f1c, roughness: 0.72 });
const eavesLanternMat = new THREE.MeshBasicMaterial({ color: 0xff6e32 });
const eavesLanternGeo = new THREE.SphereGeometry(0.32, 10, 8);
eavesLanternGeo.scale(0.82, 1.18, 0.82);

const roofAnchorsLeft = [];
const roofAnchorsRight = [];

function createFestivalHouse({ x, y, z, width, depth, wallH, roofH, rotY, variant, floors = 1, side = 0, registerAnchor = false }) {
  const grp = new THREE.Group();
  grp.position.set(x, y, z);
  grp.rotation.y = rotY;

  const texSet = houseTextureVariants[variant % houseTextureVariants.length];
  const wallMat = new THREE.MeshStandardMaterial({
    map: texSet.map,
    emissive: new THREE.Color(0xffb562),
    emissiveMap: texSet.emissiveMap,
    emissiveIntensity: 1.15,
    roughness: 0.82
  });

  // Foundation plinth extending cleanly down into hillside (but never below y = 0)
  const plinthH = Math.min(y - 0.1, 2.2);
  if (plinthH > 0.1) {
    const plinth = new THREE.Mesh(
      new THREE.BoxGeometry(width + 0.4, plinthH, depth + 0.4),
      trimWoodMat
    );
    plinth.position.y = -plinthH * 0.5;
    grp.add(plinth);
  }

  let curY = 0;
  let curW = width;
  let curD = depth;
  const floorH = wallH / floors;

  for (let f = 0; f < floors; f++) {
    const body = new THREE.Mesh(new THREE.BoxGeometry(curW, floorH, curD), wallMat);
    body.position.y = curY + floorH * 0.5;
    grp.add(body);

    // Eaves roof for every story (pagoda style when floors > 1)
    const isTop = f === floors - 1;
    const rH = isTop ? roofH : roofH * 0.52;
    const rGeo = createCurvedRoofGeometry(curW + 1.85, curD + 1.85, rH);
    const roof = new THREE.Mesh(rGeo, roofMat);
    roof.position.y = curY + floorH - 0.15;
    grp.add(roof);

    // Ridge beam ornament on top roof
    if (isTop) {
      const ridge = new THREE.Mesh(new THREE.BoxGeometry(0.32, 0.32, curD + 1.1), redAccentMat);
      ridge.position.y = curY + floorH + rH - 0.05;
      grp.add(ridge);
    }

    // Hanging red-orange eaves lanterns facing the river
    if (f === 0 && side !== 0) {
      const faceSign = -side; // Face river
      for (const zOff of [-curD * 0.34, curD * 0.34]) {
        const lan = new THREE.Mesh(eavesLanternGeo, eavesLanternMat);
        lan.position.set(faceSign * (curW * 0.5 + 0.55), floorH - 0.45, zOff);
        grp.add(lan);
      }
    }

    curY += floorH + (isTop ? rH : rH * 0.25);
    curW *= 0.78;
    curD *= 0.80;
  }

  scene.add(grp);

  // Register exact rotated bounding box obstacle (including generous roof eave margin!)
  const totalTopY = y + curY + 0.4;
  obstacles.push({
    cx: x,
    cz: z,
    cosA: Math.cos(rotY),
    sinA: Math.sin(rotY),
    hx: width * 0.5 + 1.15,
    hz: depth * 0.5 + 1.15,
    topY: totalTopY
  });

  if (registerAnchor) {
    // Roof corner facing the river for string lights
    const localAnchor = new THREE.Vector3(-side * (width * 0.5 + 0.75), wallH * 0.88 + 0.2, 0);
    localAnchor.applyAxisAngle(new THREE.Vector3(0, 1, 0), rotY);
    localAnchor.add(new THREE.Vector3(x, y, z));
    if (side < 0) roofAnchorsLeft.push(localAnchor);
    else roofAnchorsRight.push(localAnchor);
  }
}

// Place picturesque town houses on both banks (front row + terraced hillside row)
for (const side of [-1, 1]) {
  // Front row along the riverfront
  const frontZ = [-58, -46, -34, -6, 6, 18, 30, 42];
  for (let i = 0; i < frontZ.length; i++) {
    const z = frontZ[i] + (rand() - 0.5) * 2.2;
    const isPagoda = side === 1 && i === 2; // Tall 3-story landmark lantern pavilion!
    const width = isPagoda ? 7.2 : 5.4 + rand() * 2.1;
    const depth = isPagoda ? 7.2 : 5.8 + rand() * 2.5;
    const wallH = isPagoda ? 11.4 : 4.6 + rand() * 3.4;
    const roofH = isPagoda ? 3.8 : 2.3 + rand() * 1.1;
    const floors = isPagoda ? 3 : (wallH > 6.6 ? 2 : 1);

    const cx = riverCenterX(z);
    const hw = riverHalfWidth(z);
    const x = cx + side * (hw + 3.6 + width * 0.5 + rand() * 1.4);
    // Align house gently with river curve
    const slope = (riverCenterX(z + 2) - riverCenterX(z - 2)) / 4.0;
    const rotY = Math.atan(slope) + (rand() - 0.5) * 0.14;

    createFestivalHouse({
      x,
      y: QUAY_Y + 0.1,
      z,
      width,
      depth,
      wallH,
      roofH,
      rotY,
      variant: i + (side > 0 ? 2 : 0),
      floors,
      side,
      registerAnchor: true
    });
  }

  // Second row terraced higher behind the front row
  const backZ = [-52, -38, -22, -10, 4, 16, 28];
  for (let i = 0; i < backZ.length; i++) {
    const z = backZ[i] + (rand() - 0.5) * 3.0;
    const width = 6.2 + rand() * 2.4;
    const depth = 6.4 + rand() * 2.6;
    const wallH = 5.4 + rand() * 3.8;
    const roofH = 2.6 + rand() * 1.2;
    const cx = riverCenterX(z);
    const hw = riverHalfWidth(z);
    const x = cx + side * (hw + 14.5 + rand() * 3.5);
    const y = terrainHeightAt(x, z) - 0.2;
    const rotY = (rand() - 0.5) * 0.32;

    createFestivalHouse({
      x,
      y,
      z,
      width,
      depth,
      wallH,
      roofH,
      rotY,
      variant: i + 1,
      floors: wallH > 7.2 ? 2 : 1,
      side,
      registerAnchor: false
    });
  }
}

// ============================================================================
// ARCHED LANTERN FOOTBRIDGE & MOORED WOODEN BOAT
// ============================================================================
{
  const bz = -18;
  const bcx = riverCenterX(bz);
  const bhw = riverHalfWidth(bz);
  const span = bhw * 2 + 2.8;
  const bridgeGroup = new THREE.Group();
  bridgeGroup.position.set(bcx, 0, bz);

  const archCurvePts = [];
  const bridgeSegs = 24;
  for (let i = 0; i <= bridgeSegs; i++) {
    const t = i / bridgeSegs;
    const x = (t - 0.5) * span;
    const archY = QUAY_Y + Math.sin(t * Math.PI) * 3.05;
    archCurvePts.push(new THREE.Vector3(x, archY, 0));
  }

  // Wooden arched deck planks
  const deckWoodMat = new THREE.MeshStandardMaterial({ color: 0x45281e, roughness: 0.85 });
  const redWoodMat = new THREE.MeshStandardMaterial({ color: 0x8e2420, roughness: 0.68 });
  const lanternOrbMat = new THREE.MeshBasicMaterial({ color: 0xffcf7a });
  const postGeo = new THREE.CylinderGeometry(0.11, 0.13, 1.35, 6);
  const orbGeo = new THREE.SphereGeometry(0.24, 10, 8);

  for (let i = 0; i < bridgeSegs; i++) {
    const p0 = archCurvePts[i];
    const p1 = archCurvePts[i + 1];
    const mid = p0.clone().add(p1).multiplyScalar(0.5);
    const len = p0.distanceTo(p1) + 0.08;
    const angle = Math.atan2(p1.y - p0.y, p1.x - p0.x);

    const plank = new THREE.Mesh(new THREE.BoxGeometry(len, 0.36, 3.3), deckWoodMat);
    plank.position.copy(mid);
    plank.rotation.z = angle;
    bridgeGroup.add(plank);

    // Side rails
    for (const rz of [-1.55, 1.55]) {
      const rail = new THREE.Mesh(new THREE.BoxGeometry(len, 0.16, 0.16), redWoodMat);
      rail.position.set(mid.x, mid.y + 1.05, rz);
      rail.rotation.z = angle;
      bridgeGroup.add(rail);
    }

    // Lantern posts spaced across bridge
    if (i % 4 === 2) {
      for (const rz of [-1.55, 1.55]) {
        const post = new THREE.Mesh(postGeo, redWoodMat);
        post.position.set(p0.x, p0.y + 0.72, rz);
        bridgeGroup.add(post);

        const orb = new THREE.Mesh(orbGeo, lanternOrbMat);
        orb.position.set(p0.x, p0.y + 1.48, rz);
        bridgeGroup.add(orb);

        const spr = new THREE.Sprite(new THREE.SpriteMaterial({
          map: glowSpriteTex,
          color: 0xffa84c,
          transparent: true,
          opacity: 0.65,
          blending: THREE.AdditiveBlending,
          depthWrite: false
        }));
        spr.position.set(p0.x, p0.y + 1.48, rz);
        spr.scale.set(2.6, 2.6, 1);
        bridgeGroup.add(spr);
      }
    }
  }

  // Two arched support piers resting strictly at y = 0
  for (const px of [-bhw * 0.56, bhw * 0.56]) {
    const pier = new THREE.Mesh(new THREE.CylinderGeometry(0.32, 0.42, 4.1, 8), deckWoodMat);
    pier.position.set(px, 2.05, 0);
    bridgeGroup.add(pier);
  }

  scene.add(bridgeGroup);

  // Register bridge obstacle so cats glide cleanly above its lantern posts
  obstacles.push({
    cx: bcx,
    cz: bz,
    cosA: 1,
    sinA: 0,
    hx: span * 0.5,
    hz: 2.35,
    topY: QUAY_Y + 3.05 + 2.1
  });
}

// Gentle moored wooden festival boat on the water surface (strictly y >= 0.05)
const boatGroup = new THREE.Group();
{
  const bz = 14;
  const bx = riverCenterX(bz) - riverHalfWidth(bz) + 3.2;
  boatGroup.position.set(bx, 0.18, bz);
  boatGroup.rotation.y = 0.25;

  const hullGeo = new THREE.CylinderGeometry(0.95, 0.65, 4.6, 8, 1, false, 0, Math.PI);
  hullGeo.rotateZ(Math.PI / 2);
  hullGeo.rotateY(Math.PI / 2);
  hullGeo.scale(1.0, 0.55, 1.0);
  const hull = new THREE.Mesh(hullGeo, new THREE.MeshStandardMaterial({ color: 0x3b2319, roughness: 0.85, side: THREE.DoubleSide }));
  hull.position.y = 0.26;
  boatGroup.add(hull);

  // Tiny hanging bow lantern on the boat
  const pole = new THREE.Mesh(new THREE.CylinderGeometry(0.04, 0.04, 1.4, 6), trimWoodMat);
  pole.position.set(0, 0.85, 1.75);
  pole.rotation.x = 0.28;
  boatGroup.add(pole);

  const bLan = new THREE.Mesh(new THREE.SphereGeometry(0.22, 10, 8), new THREE.MeshBasicMaterial({ color: 0xffb85c }));
  bLan.position.set(0, 1.4, 2.05);
  boatGroup.add(bLan);

  const bHalo = new THREE.Sprite(new THREE.SpriteMaterial({
    map: glowSpriteTex,
    color: 0xff9a3c,
    transparent: true,
    opacity: 0.75,
    blending: THREE.AdditiveBlending,
    depthWrite: false
  }));
  bHalo.position.copy(bLan.position);
  bHalo.scale.set(2.4, 2.4, 1);
  boatGroup.add(bHalo);

  scene.add(boatGroup);
}

// ============================================================================
// WEEPING WILLOW TREES ALONG THE RIVERBANKS
// ============================================================================
const willowCanopies = [];
{
  const trunkMat = new THREE.MeshStandardMaterial({ color: 0x261d18, roughness: 0.92 });
  const leafMat = new THREE.MeshStandardMaterial({ color: 0x162b26, roughness: 0.88, side: THREE.DoubleSide });
  const willowSpots = [
    { side: -1, z: -25 }, { side: 1, z: -12 }, { side: -1, z: 12 },
    { side: 1, z: 24 }, { side: -1, z: -40 }, { side: 1, z: 36 }
  ];
  for (let i = 0; i < willowSpots.length; i++) {
    const { side, z } = willowSpots[i];
    const x = riverCenterX(z) + side * (riverHalfWidth(z) + 1.6);
    const tree = new THREE.Group();
    tree.position.set(x, QUAY_Y, z);

    const trunkH = 4.2 + rand() * 1.6;
    const trunk = new THREE.Mesh(new THREE.CylinderGeometry(0.22, 0.42, trunkH, 7), trunkMat);
    trunk.position.y = trunkH * 0.5;
    trunk.rotation.z = side * 0.16; // Lean gracefully toward the river
    tree.add(trunk);

    const canopy = new THREE.Group();
    canopy.position.set(-side * 0.7, trunkH - 0.2, 0);
    for (let b = 0; b < 7; b++) {
      const ang = (b / 7) * Math.PI * 2 + rand() * 0.4;
      const rad = 1.0 + rand() * 1.1;
      const frond = new THREE.Mesh(new THREE.ConeGeometry(0.85 + rand() * 0.5, 3.6 + rand() * 1.2, 6), leafMat);
      frond.position.set(Math.cos(ang) * rad, -0.5 + rand() * 0.8, Math.sin(ang) * rad);
      frond.rotation.z = Math.cos(ang) * 0.22;
      frond.rotation.x = Math.sin(ang) * 0.22;
      canopy.add(frond);
    }
    tree.add(canopy);
    willowCanopies.push({ grp: canopy, phase: i * 1.3 });
    scene.add(tree);

    obstacles.push({
      cx: x - side * 0.6,
      cz: z,
      cosA: 1,
      sinA: 0,
      hx: 2.3,
      hz: 2.3,
      topY: QUAY_Y + trunkH + 2.0
    });
  }
}

// ============================================================================
// STRINGS OF FESTIVAL LIGHTS (CATENARY GARLANDS ACROSS RIVER & ROOFTOPS)
// ============================================================================
const festoonLanternData = [];
const festoonLines = [];
{
  const wireMat = new THREE.LineBasicMaterial({ color: 0x2a2438, transparent: true, opacity: 0.72 });
  const pairs = [];

  // Cross-river strings connecting left and right rooftop anchors at varied heights & diagonals
  const count = Math.min(roofAnchorsLeft.length, roofAnchorsRight.length);
  for (let i = 0; i < count; i++) {
    const pA = roofAnchorsLeft[i].clone();
    const pB = roofAnchorsRight[i].clone();
    // Lift heights nicely so cats can weave both UNDER and OVER the strings!
    pA.y = Math.max(pA.y, 10.5 + (i % 3) * 2.1);
    pB.y = Math.max(pB.y, 10.5 + ((i + 1) % 3) * 2.1);
    pairs.push({ a: pA, b: pB, sag: 2.2 + (i % 2) * 0.9, bulbs: 13 });

    // Diagonal criss-cross strings on every other pair
    if (i + 1 < count && i % 2 === 0) {
      const pC = roofAnchorsRight[i + 1].clone();
      pC.y = Math.max(pC.y, 12.2 + (i % 2) * 1.8);
      pairs.push({ a: pA.clone().add(new THREE.Vector3(0, 1.3, 0)), b: pC, sag: 2.6, bulbs: 14 });
    }
  }

  // Palette of warm festival paper-string lanterns
  const palette = [
    new THREE.Color(0xff5e2b), // vermilion red-orange
    new THREE.Color(0xffad38), // lantern gold
    new THREE.Color(0xffdf8c), // warm ivory
    new THREE.Color(0xff7844), // persimmon
    new THREE.Color(0xffc052)  // amber
  ];

  for (let pi = 0; pi < pairs.length; pi++) {
    const { a, b, sag, bulbs } = pairs[pi];
    const pts = [];
    const samples = 24;
    for (let s = 0; s <= samples; s++) {
      const t = s / samples;
      const pt = new THREE.Vector3().lerpVectors(a, b, t);
      pt.y -= Math.sin(t * Math.PI) * sag;
      pts.push(pt);
    }

    const lineGeo = new THREE.BufferGeometry().setFromPoints(pts);
    const line = new THREE.Line(lineGeo, wireMat);
    scene.add(line);
    festoonLines.push({ line, a, b, sag, phase: pi * 0.95 });

    // Store mid-span samples so the flying cats weave cleanly over/under light strings!
    const avoidSamples = [];
    for (let s = 2; s < samples - 1; s += 2) {
      avoidSamples.push(pts[s].clone());
    }
    lightStringCurves.push(avoidSamples);

    for (let bi = 1; bi <= bulbs; bi++) {
      const t = bi / (bulbs + 1);
      const basePos = new THREE.Vector3().lerpVectors(a, b, t);
      basePos.y -= Math.sin(t * Math.PI) * sag + 0.28;
      festoonLanternData.push({
        basePos,
        sagFactor: Math.sin(t * Math.PI),
        phase: pi * 0.95 + bi * 0.4,
        color: palette[(pi + bi) % palette.length]
      });
    }
  }
}

// Instanced glowing festoon bulbs + additive halos
const festoonBulbGeo = new THREE.SphereGeometry(0.28, 10, 8);
festoonBulbGeo.scale(0.88, 1.15, 0.88);
const festoonBulbMat = new THREE.MeshBasicMaterial({ color: 0xffffff });
const festoonInstanced = new THREE.InstancedMesh(festoonBulbGeo, festoonBulbMat, festoonLanternData.length);
const festoonHaloPos = new Float32Array(festoonLanternData.length * 3);
const festoonHaloCol = new Float32Array(festoonLanternData.length * 3);
const dummyObj = new THREE.Object3D();

for (let i = 0; i < festoonLanternData.length; i++) {
  const d = festoonLanternData[i];
  dummyObj.position.copy(d.basePos);
  dummyObj.scale.set(1, 1, 1);
  dummyObj.updateMatrix();
  festoonInstanced.setMatrixAt(i, dummyObj.matrix);
  festoonInstanced.setColorAt(i, d.color);
  festoonHaloPos[i * 3] = d.basePos.x;
  festoonHaloPos[i * 3 + 1] = d.basePos.y;
  festoonHaloPos[i * 3 + 2] = d.basePos.z;
  festoonHaloCol[i * 3] = d.color.r;
  festoonHaloCol[i * 3 + 1] = d.color.g;
  festoonHaloCol[i * 3 + 2] = d.color.b;
}
festoonInstanced.instanceMatrix.needsUpdate = true;
if (festoonInstanced.instanceColor) festoonInstanced.instanceColor.needsUpdate = true;
scene.add(festoonInstanced);

const festoonHaloGeo = new THREE.BufferGeometry();
festoonHaloGeo.setAttribute('position', new THREE.BufferAttribute(festoonHaloPos, 3));
festoonHaloGeo.setAttribute('aColor', new THREE.BufferAttribute(festoonHaloCol, 3));
const festoonHaloUniforms = { uPixelRatio: { value: getDpr() } };
const festoonHaloMat = new THREE.ShaderMaterial({
  uniforms: festoonHaloUniforms,
  transparent: true,
  depthWrite: false,
  blending: THREE.AdditiveBlending,
  vertexShader: `
    attribute vec3 aColor;
    uniform float uPixelRatio;
    varying vec3 vColor;
    void main() {
      vColor = aColor;
      vec4 mv = modelViewMatrix * vec4(position, 1.0);
      gl_PointSize = clamp(uPixelRatio * (520.0 / max(-mv.z, 1.0)), 4.0, 44.0);
      gl_Position = projectionMatrix * mv;
    }
  `,
  fragmentShader: `
    varying vec3 vColor;
    void main() {
      float d = length(gl_PointCoord - 0.5) * 2.0;
      if (d > 1.0) discard;
      float g = exp(-d * d * 4.2) * 0.58;
      gl_FragColor = vec4(vColor * g, g);
    }
  `
});
const festoonHalos = new THREE.Points(festoonHaloGeo, festoonHaloMat);
scene.add(festoonHalos);

// ============================================================================
// FLOATING SKY LANTERNS (SMALL PAPER LANTERNS RISING INTO THE NIGHT)
// ============================================================================
const SKY_LANTERN_COUNT = 68;
const skyLanternProfile = [
  new THREE.Vector2(0.16, 0.0),
  new THREE.Vector2(0.28, 0.14),
  new THREE.Vector2(0.36, 0.42),
  new THREE.Vector2(0.33, 0.68),
  new THREE.Vector2(0.20, 0.84),
  new THREE.Vector2(0.02, 0.88)
];
const skyLanternGeo = new THREE.LatheGeometry(skyLanternProfile, 12);
const skyLanternMat = new THREE.ShaderMaterial({
  uniforms: { uTime: { value: 0 } },
  side: THREE.DoubleSide,
  vertexShader: `
    varying float vH;
    void main() {
      vH = clamp(position.y / 0.88, 0.0, 1.0);
      vec4 wp = modelMatrix * instanceMatrix * vec4(position, 1.0);
      gl_Position = projectionMatrix * viewMatrix * wp;
    }
  `,
  fragmentShader: `
    varying float vH;
    void main() {
      // Bright candle flame warmth at open base, amber paper near crown
      vec3 baseGlow = vec3(1.45, 0.92, 0.38);
      vec3 midPaper = vec3(1.05, 0.48, 0.14);
      vec3 topPaper = vec3(0.58, 0.18, 0.06);
      vec3 col = mix(baseGlow, midPaper, smoothstep(0.0, 0.52, vH));
      col = mix(col, topPaper, smoothstep(0.45, 1.0, vH));
      gl_FragColor = vec4(col, 1.0);
      #include <tonemapping_fragment>
      #include <colorspace_fragment>
    }
  `
});
const skyLanternInstanced = new THREE.InstancedMesh(skyLanternGeo, skyLanternMat, SKY_LANTERN_COUNT);
scene.add(skyLanternInstanced);

const skyLanterns = [];
const skyLanternFlamePos = new Float32Array(SKY_LANTERN_COUNT * 3);
const skyLanternFlamePhase = new Float32Array(SKY_LANTERN_COUNT);

function resetSkyLantern(item, randomY) {
  const z = -68 + rand() * 108;
  const cx = riverCenterX(z);
  const spread = (rand() - 0.5) * 58;
  item.x = cx + spread;
  item.z = z;
  item.y = randomY ? (3.5 + rand() * 46) : (3.2 + rand() * 4.5);
  item.vy = 0.68 + rand() * 0.72;
  item.swayAmp = 0.6 + rand() * 1.1;
  item.swayFreq = 0.35 + rand() * 0.45;
  item.phase = rand() * Math.PI * 2;
  item.scale = 0.72 + rand() * 0.56;
  item.driftZ = -0.25 + (rand() - 0.5) * 0.5;
}

for (let i = 0; i < SKY_LANTERN_COUNT; i++) {
  const item = {};
  resetSkyLantern(item, true);
  skyLanterns.push(item);
  skyLanternFlamePhase[i] = item.phase;
}

const skyLanternHaloGeo = new THREE.BufferGeometry();
skyLanternHaloGeo.setAttribute('position', new THREE.BufferAttribute(skyLanternFlamePos, 3));
skyLanternHaloGeo.setAttribute('aPhase', new THREE.BufferAttribute(skyLanternFlamePhase, 1));
const skyLanternHaloUniforms = {
  uTime: { value: 0 },
  uPixelRatio: { value: getDpr() }
};
const skyLanternHaloMat = new THREE.ShaderMaterial({
  uniforms: skyLanternHaloUniforms,
  transparent: true,
  depthWrite: false,
  blending: THREE.AdditiveBlending,
  vertexShader: `
    attribute float aPhase;
    uniform float uTime;
    uniform float uPixelRatio;
    varying float vFlicker;
    void main() {
      vFlicker = 0.84 + 0.16 * sin(uTime * 5.2 + aPhase * 3.0);
      vec4 mv = modelViewMatrix * vec4(position, 1.0);
      gl_PointSize = clamp(uPixelRatio * (680.0 / max(-mv.z, 1.0)) * vFlicker, 5.0, 56.0);
      gl_Position = projectionMatrix * mv;
    }
  `,
  fragmentShader: `
    varying float vFlicker;
    void main() {
      float d = length(gl_PointCoord - 0.5) * 2.0;
      if (d > 1.0) discard;
      float g = exp(-d * d * 3.8) * 0.52 * vFlicker;
      gl_FragColor = vec4(vec3(1.0, 0.56, 0.18) * g, g);
    }
  `
});
const skyLanternHalos = new THREE.Points(skyLanternHaloGeo, skyLanternHaloMat);
scene.add(skyLanternHalos);

// ============================================================================
// DRIFTING FESTIVAL SPARKS & CAT EMBER TRAILS
// ============================================================================
const AMBIENT_SPARKS = 420;
const sparkPos = new Float32Array(AMBIENT_SPARKS * 3);
const sparkColor = new Float32Array(AMBIENT_SPARKS * 3);
const sparkSize = new Float32Array(AMBIENT_SPARKS);
const sparkPhase = new Float32Array(AMBIENT_SPARKS);
const sparkVel = [];

for (let i = 0; i < AMBIENT_SPARKS; i++) {
  sparkPos[i * 3] = (rand() - 0.5) * 68;
  sparkPos[i * 3 + 1] = 0.8 + rand() * 30;
  sparkPos[i * 3 + 2] = -64 + rand() * 106;
  const warm = rand() > 0.22;
  const c = warm
    ? new THREE.Color().setHSL(0.06 + rand() * 0.06, 1.0, 0.65 + rand() * 0.25)
    : new THREE.Color().setHSL(0.58 + rand() * 0.05, 0.55, 0.82);
  sparkColor[i * 3] = c.r;
  sparkColor[i * 3 + 1] = c.g;
  sparkColor[i * 3 + 2] = c.b;
  sparkSize[i] = 1.6 + rand() * 2.8;
  sparkPhase[i] = rand() * Math.PI * 2;
  sparkVel.push({
    vx: (rand() - 0.5) * 0.85,
    vy: 0.45 + rand() * 1.15,
    vz: (rand() - 0.5) * 0.85
  });
}

const sparkGeo = new THREE.BufferGeometry();
sparkGeo.setAttribute('position', new THREE.BufferAttribute(sparkPos, 3));
sparkGeo.setAttribute('aColor', new THREE.BufferAttribute(sparkColor, 3));
sparkGeo.setAttribute('aSize', new THREE.BufferAttribute(sparkSize, 1));
sparkGeo.setAttribute('aPhase', new THREE.BufferAttribute(sparkPhase, 1));

const sparkUniforms = {
  uTime: { value: 0 },
  uPixelRatio: { value: getDpr() }
};
const sparkMat = new THREE.ShaderMaterial({
  uniforms: sparkUniforms,
  transparent: true,
  depthWrite: false,
  blending: THREE.AdditiveBlending,
  vertexShader: `
    attribute vec3 aColor;
    attribute float aSize;
    attribute float aPhase;
    uniform float uTime;
    uniform float uPixelRatio;
    varying vec3 vColor;
    varying float vAlpha;
    void main() {
      vColor = aColor;
      vAlpha = 0.45 + 0.55 * sin(uTime * 3.6 + aPhase * 4.0);
      vec4 mv = modelViewMatrix * vec4(position, 1.0);
      gl_PointSize = clamp(uPixelRatio * aSize * (180.0 / max(-mv.z, 1.0)), 1.8, 16.0);
      gl_Position = projectionMatrix * mv;
    }
  `,
  fragmentShader: `
    varying vec3 vColor;
    varying float vAlpha;
    void main() {
      float d = length(gl_PointCoord - 0.5) * 2.0;
      if (d > 1.0) discard;
      float g = exp(-d * d * 4.6) * vAlpha;
      gl_FragColor = vec4(vColor * g * 1.3, g);
    }
  `
});
const ambientSparksPoints = new THREE.Points(sparkGeo, sparkMat);
scene.add(ambientSparksPoints);

// Cat Trail Sparks Ring Buffer
const TRAIL_SPARKS = 180;
const tSparkPos = new Float32Array(TRAIL_SPARKS * 3);
const tSparkCol = new Float32Array(TRAIL_SPARKS * 3);
const tSparkLife = new Float32Array(TRAIL_SPARKS);
const tSparkVel = new Float32Array(TRAIL_SPARKS * 3);
let tSparkCursor = 0;

for (let i = 0; i < TRAIL_SPARKS; i++) {
  tSparkPos[i * 3 + 1] = 100;
  tSparkLife[i] = 0;
}

const tSparkGeo = new THREE.BufferGeometry();
tSparkGeo.setAttribute('position', new THREE.BufferAttribute(tSparkPos, 3));
tSparkGeo.setAttribute('aColor', new THREE.BufferAttribute(tSparkCol, 3));
tSparkGeo.setAttribute('aLife', new THREE.BufferAttribute(tSparkLife, 1));
const tSparkUniforms = { uPixelRatio: { value: getDpr() } };
const tSparkMat = new THREE.ShaderMaterial({
  uniforms: tSparkUniforms,
  transparent: true,
  depthWrite: false,
  blending: THREE.AdditiveBlending,
  vertexShader: `
    attribute vec3 aColor;
    attribute float aLife;
    uniform float uPixelRatio;
    varying vec3 vColor;
    varying float vLife;
    void main() {
      vColor = aColor;
      vLife = aLife;
      vec4 mv = modelViewMatrix * vec4(position, 1.0);
      gl_PointSize = clamp(uPixelRatio * (2.6 + 2.8 * aLife) * (190.0 / max(-mv.z, 1.0)), 1.5, 22.0);
      gl_Position = projectionMatrix * mv;
    }
  `,
  fragmentShader: `
    varying vec3 vColor;
    varying float vLife;
    void main() {
      if (vLife <= 0.01) discard;
      float d = length(gl_PointCoord - 0.5) * 2.0;
      if (d > 1.0) discard;
      float g = exp(-d * d * 4.0) * vLife;
      gl_FragColor = vec4(vColor * g * 1.35, g);
    }
  `
});
const trailSparksPoints = new THREE.Points(tSparkGeo, tSparkMat);
scene.add(trailSparksPoints);

function spawnTrailSpark(pos, isOrange) {
  const i = tSparkCursor;
  tSparkCursor = (tSparkCursor + 1) % TRAIL_SPARKS;
  tSparkPos[i * 3] = pos.x + (Math.random() - 0.5) * 0.65;
  tSparkPos[i * 3 + 1] = Math.max(0.5, pos.y + (Math.random() - 0.5) * 0.55);
  tSparkPos[i * 3 + 2] = pos.z + (Math.random() - 0.5) * 0.65;
  tSparkVel[i * 3] = (Math.random() - 0.5) * 1.1;
  tSparkVel[i * 3 + 1] = 0.5 + Math.random() * 1.1;
  tSparkVel[i * 3 + 2] = (Math.random() - 0.5) * 1.1;
  tSparkLife[i] = 0.85 + Math.random() * 0.25;
  if (isOrange) {
    tSparkCol[i * 3] = 1.0;
    tSparkCol[i * 3 + 1] = 0.62 + Math.random() * 0.28;
    tSparkCol[i * 3 + 2] = 0.18;
  } else {
    tSparkCol[i * 3] = 0.78;
    tSparkCol[i * 3 + 1] = 0.88 + Math.random() * 0.12;
    tSparkCol[i * 3 + 2] = 1.0;
  }
}

// ============================================================================
// PAPER-LANTERN CAT BUILDER & SHADER
// ============================================================================
function createLanternPaperMaterial({ map, baseColor, coreColor, rimColor, ribCount, isHead }) {
  return new THREE.ShaderMaterial({
    uniforms: {
      uMap: { value: map },
      uBaseColor: { value: new THREE.Color(baseColor) },
      uCoreColor: { value: new THREE.Color(coreColor) },
      uRimColor: { value: new THREE.Color(rimColor) },
      uRibCount: { value: ribCount },
      uIsHead: { value: isHead ? 1.0 : 0.0 },
      uTime: { value: 0 }
    },
    vertexShader: `
      varying vec2 vUv;
      varying vec3 vNormal;
      varying vec3 vViewDir;
      varying vec3 vWorldPos;
      void main() {
        vUv = uv;
        vec4 wp = modelMatrix * vec4(position, 1.0);
        vWorldPos = wp.xyz;
        vec4 mv = viewMatrix * wp;
        vNormal = normalize(normalMatrix * normal);
        vViewDir = normalize(-mv.xyz);
        gl_Position = projectionMatrix * mv;
      }
    `,
    fragmentShader: `
      uniform sampler2D uMap;
      uniform vec3 uBaseColor;
      uniform vec3 uCoreColor;
      uniform vec3 uRimColor;
      uniform float uRibCount;
      uniform float uIsHead;
      uniform float uTime;

      varying vec2 vUv;
      varying vec3 vNormal;
      varying vec3 vViewDir;
      varying vec3 vWorldPos;

      void main() {
        vec3 texCol = texture2D(uMap, vUv).rgb;
        vec3 N = normalize(vNormal);
        vec3 V = normalize(vViewDir);
        float ndv = abs(dot(N, V));

        // Gentle traveling candle glow along the paper lantern body
        float phase = vWorldPos.x * 0.25 + vWorldPos.z * 0.25;
        float flicker = 0.94 + 0.05 * sin(uTime * 4.8 + phase) + 0.025 * sin(uTime * 10.6 - phase * 1.7);

        // Bamboo lantern wire ribs & delicate paper accordion pleats
        float rib = 1.0;
        if (uRibCount > 0.5) {
          float wireRing = pow(abs(sin(vUv.y * 3.14159265 * uRibCount)), 16.0);
          float pleats = 0.055 * sin(vUv.x * 6.2831853 * 14.0);
          rib = (1.0 - 0.24 * wireRing) * (1.0 - pleats);
        }

        // Subsurface glowing lantern core (brighter center facing viewer, rich edges, luminous rim)
        vec3 paper = texCol * uBaseColor;
        float coreStrength = mix(0.76, 0.44, uIsHead);
        float core = pow(ndv, 1.25) * coreStrength;
        float rim = pow(1.0 - ndv, 2.5) * 0.62;

        vec3 col = mix(paper * 0.78, uCoreColor * (0.48 + 0.62 * texCol), core);
        col += paper * 0.44;
        col += uRimColor * rim;
        col *= rib * flicker;

        gl_FragColor = vec4(col, 1.0);
        #include <tonemapping_fragment>
        #include <colorspace_fragment>
      }
    `
  });
}

// Reusable scalloped paper lantern segment geometry oriented along +Z
const lanternSegProfile = [
  new THREE.Vector2(0.14, -0.49),
  new THREE.Vector2(0.46, -0.44),
  new THREE.Vector2(0.78, -0.28),
  new THREE.Vector2(0.95, -0.10),
  new THREE.Vector2(1.00, 0.00),
  new THREE.Vector2(0.95, 0.10),
  new THREE.Vector2(0.78, 0.28),
  new THREE.Vector2(0.46, 0.44),
  new THREE.Vector2(0.14, 0.49)
];
const sharedBodySegGeo = new THREE.LatheGeometry(lanternSegProfile, 16);
sharedBodySegGeo.rotateX(Math.PI / 2);

const sharedRingGeo = new THREE.TorusGeometry(0.56, 0.055, 6, 16);

// Cat head sculpted sphere (UV seam hidden at -Z, face centered at +Z u=0.5!)
function createCatHeadGeometry() {
  const geo = new THREE.SphereGeometry(1.0, 28, 22, -Math.PI / 2);
  const pos = geo.attributes.position;
  for (let i = 0; i < pos.count; i++) {
    let x = pos.getX(i);
    let y = pos.getY(i);
    let z = pos.getZ(i);
    // Soft feline lantern contour: wider rounded cheeks, gentle tapered snout, slightly flatter crown
    x *= 1.12;
    y *= 0.94;
    z *= 1.04;
    if (y < 0.05 && Math.abs(x) > 0.35) {
      x *= 1.06; // Plush cheeks
    }
    if (z > 0.45 && y < 0.15 && y > -0.45) {
      z += 0.12 * (1.0 - Math.min(1, Math.abs(x) * 1.4)); // Soft muzzle projection
    }
    pos.setXYZ(i, x, y, z);
  }
  geo.computeVertexNormals();
  return geo;
}
const sharedHeadGeo = createCatHeadGeometry();

// Sculpted pointed cat ear geometry (base at y = 0, tip at y = 0.96)
function createCatEarGeometry(scale = 1.0) {
  const geo = new THREE.ConeGeometry(0.44 * scale, 0.96 * scale, 6, 3);
  geo.scale(0.92, 1.0, 0.42);
  geo.translate(0, 0.45 * scale, 0);
  const pos = geo.attributes.position;
  for (let i = 0; i < pos.count; i++) {
    const y = pos.getY(i);
    const z = pos.getZ(i);
    // Subtle graceful forward cup
    pos.setZ(i, z + Math.pow(y / (0.96 * scale), 1.6) * 0.07 * scale);
  }
  geo.computeVertexNormals();
  return geo;
}
const sharedOuterEarGeo = createCatEarGeometry(1.0);
const sharedInnerEarGeo = createCatEarGeometry(0.68);

const catMaterialsToTick = [];

function createLanternCat(config) {
  const { name, isOrange, startPos, startDir } = config;
  const headTex = createCatHeadTexture(isOrange);
  const bodyTex = createCatBodyTexture(isOrange);

  const headMat = createLanternPaperMaterial({
    map: headTex,
    baseColor: isOrange ? 0xffae52 : 0xd5e2f5,
    coreColor: isOrange ? 0xffe49e : 0xf4f8ff,
    rimColor: isOrange ? 0xff7722 : 0x99bfff,
    ribCount: 0.0,
    isHead: true
  });
  const bodyMat = createLanternPaperMaterial({
    map: bodyTex,
    baseColor: isOrange ? 0xffa648 : 0xd0def2,
    coreColor: isOrange ? 0xffe69c : 0xf2f7ff,
    rimColor: isOrange ? 0xff6e1a : 0x8eb8ff,
    ribCount: 4.0,
    isHead: false
  });
  const earMat = createLanternPaperMaterial({
    map: bodyTex,
    baseColor: isOrange ? 0xff9438 : 0xc0d0e8,
    coreColor: isOrange ? 0xffd88a : 0xeaf2ff,
    rimColor: isOrange ? 0xff6b1c : 0x94bcff,
    ribCount: 0.0,
    isHead: true
  });
  catMaterialsToTick.push(headMat, bodyMat, earMat);

  const bambooMat = new THREE.MeshBasicMaterial({ color: isOrange ? 0x5c2208 : 0x3b4863 });
  const innerEarMat = new THREE.MeshBasicMaterial({ color: isOrange ? 0xffa696 : 0xe6c0dc });
  const eyeColor = isOrange ? 0x62f5a8 : 0xffc646;
  const eyeGlowMat = new THREE.MeshBasicMaterial({ color: eyeColor });
  const pupilMat = new THREE.MeshBasicMaterial({ color: 0x0b0c14 });
  const catchlightMat = new THREE.MeshBasicMaterial({ color: 0xffffff });
  const noseMat = new THREE.MeshBasicMaterial({ color: isOrange ? 0xff687a : 0x5e4c5c });
  const whiskerMat = new THREE.MeshBasicMaterial({ color: isOrange ? 0xfff0c4 : 0xeef6ff });
  const ribbonMat = new THREE.MeshBasicMaterial({ color: isOrange ? 0xc82228 : 0x266298 });
  const bellMat = new THREE.MeshStandardMaterial({
    color: isOrange ? 0xffd24c : 0xe6eefc,
    emissive: isOrange ? 0xff9d24 : 0x9ab8e8,
    emissiveIntensity: 0.55,
    roughness: 0.25,
    metalness: 0.75
  });

  // --- HEAD GROUP ---
  const headGroup = new THREE.Group();
  const headMesh = new THREE.Mesh(sharedHeadGeo, headMat);
  headGroup.add(headMesh);

  // Subtle decorative bamboo headband ring around neck base
  const neckCollar = new THREE.Mesh(new THREE.TorusGeometry(0.76, 0.11, 8, 20), ribbonMat);
  neckCollar.position.set(0, -0.22, -0.58);
  neckCollar.rotation.x = 0.22;
  headGroup.add(neckCollar);

  // Gleaming tiny festival bell beneath chin
  const bell = new THREE.Mesh(new THREE.SphereGeometry(0.18, 10, 8), bellMat);
  bell.position.set(0, -0.78, 0.18);
  headGroup.add(bell);

  // Sculpted 3D muzzle puffs & nose at +Z
  const cheekPuffGeo = new THREE.SphereGeometry(0.24, 10, 8);
  const cheekPuffMat = new THREE.MeshBasicMaterial({ color: isOrange ? 0xffe4b8 : 0xf2f7ff });
  for (const s of [-1, 1]) {
    const puff = new THREE.Mesh(cheekPuffGeo, cheekPuffMat);
    puff.position.set(s * 0.20, -0.17, 0.93);
    puff.scale.set(1.0, 0.78, 0.72);
    headGroup.add(puff);
  }
  const nose = new THREE.Mesh(new THREE.ConeGeometry(0.13, 0.16, 4), noseMat);
  nose.rotation.x = Math.PI;
  nose.rotation.y = Math.PI / 4;
  nose.position.set(0, -0.04, 1.09);
  headGroup.add(nose);

  // Expressive luminous eyes (with blink scaling pivots!)
  const eyePivots = [];
  const eyeGeo = new THREE.SphereGeometry(0.24, 14, 12);
  const pupilGeo = new THREE.SphereGeometry(0.14, 10, 10);
  const catchGeo = new THREE.SphereGeometry(0.055, 8, 8);

  for (const s of [-1, 1]) {
    const ep = new THREE.Group();
    ep.position.set(s * 0.44, 0.19, 0.88);
    ep.rotation.y = s * 0.34;
    ep.rotation.x = -0.06;

    const eyeball = new THREE.Mesh(eyeGeo, eyeGlowMat);
    eyeball.scale.set(1.06, 0.94, 0.56);
    ep.add(eyeball);

    const pupil = new THREE.Mesh(pupilGeo, pupilMat);
    pupil.position.set(0, 0, 0.08);
    pupil.scale.set(0.46, 1.05, 0.65);
    ep.add(pupil);

    const catchlight = new THREE.Mesh(catchGeo, catchlightMat);
    catchlight.position.set(s * 0.06, 0.07, 0.14);
    ep.add(catchlight);

    headGroup.add(ep);
    eyePivots.push(ep);
  }

  // Pointed lantern ears on flicking pivots
  const earPivots = [];
  for (const s of [-1, 1]) {
    const earPiv = new THREE.Group();
    earPiv.position.set(s * 0.56, 0.62, 0.06);
    earPiv.rotation.set(0.12, s * 0.16, -s * 0.36);

    const outer = new THREE.Mesh(sharedOuterEarGeo, earMat);
    earPiv.add(outer);

    const inner = new THREE.Mesh(sharedInnerEarGeo, innerEarMat);
    inner.position.set(0, 0.08, 0.11);
    earPiv.add(inner);

    headGroup.add(earPiv);
    earPivots.push({ pivot: earPiv, side: s, baseRotX: 0.12, baseRotY: s * 0.16, baseRotZ: -s * 0.36 });
  }

  // Long luminous curved whiskers on flicking pivots (3 per cheek)
  const whiskerPivots = [];
  for (const s of [-1, 1]) {
    const wp = new THREE.Group();
    wp.position.set(s * 0.52, -0.13, 0.78);
    const angles = [0.22, 0.0, -0.22];
    const lengths = [1.85, 2.15, 1.72];
    for (let wi = 0; wi < 3; wi++) {
      const len = lengths[wi];
      const ang = angles[wi];
      const curve = new THREE.CatmullRomCurve3([
        new THREE.Vector3(0, 0, 0),
        new THREE.Vector3(s * len * 0.52, Math.sin(ang) * len * 0.45 + 0.04, 0.12),
        new THREE.Vector3(s * len, Math.sin(ang) * len * 0.75 - 0.12, -0.28)
      ]);
      const wGeo = new THREE.TubeGeometry(curve, 10, 0.028, 5, false);
      wp.add(new THREE.Mesh(wGeo, whiskerMat));
    }
    headGroup.add(wp);
    whiskerPivots.push({ pivot: wp, side: s });
  }

  // Head warm halo + dynamic point light that illuminates passing rooftops
  const haloColor = isOrange ? 0xff8c2e : 0xa6c8ff;
  const headHalo = new THREE.Sprite(new THREE.SpriteMaterial({
    map: glowSpriteTex,
    color: haloColor,
    transparent: true,
    opacity: 0.78,
    blending: THREE.AdditiveBlending,
    depthWrite: false
  }));
  headHalo.scale.set(5.4, 5.4, 1);
  headGroup.add(headHalo);

  const headLight = new THREE.PointLight(isOrange ? 0xff8c2b : 0xb2d2ff, 44, 34, 1.45);
  headGroup.add(headLight);

  scene.add(headGroup);

  // --- BODY SEGMENTS (16 GLOWING PAPER LANTERN DRUMS) ---
  const BODY_COUNT = 16;
  const bodySegments = [];
  const pawGeo = new THREE.SphereGeometry(0.28, 10, 8);
  pawGeo.scale(0.85, 0.68, 1.25);

  for (let i = 0; i < BODY_COUNT; i++) {
    const t = i / (BODY_COUNT - 1);
    // Plump cat torso tapering gently toward rump
    let r;
    if (i === 0) r = 0.84;
    else if (t < 0.35) r = THREE.MathUtils.lerp(0.92, 0.98, t / 0.35);
    else r = THREE.MathUtils.lerp(0.98, 0.42, (t - 0.35) / 0.65);

    const segGrp = new THREE.Group();
    const lenScale = r * 1.18;
    const mesh = new THREE.Mesh(sharedBodySegGeo, bodyMat);
    mesh.scale.set(r * 0.96, r * 0.90, lenScale);
    segGrp.add(mesh);

    // Dark bamboo lantern end-ring accents
    const frontRing = new THREE.Mesh(sharedRingGeo, bambooMat);
    frontRing.scale.setScalar(r * 0.82);
    frontRing.position.z = lenScale * 0.41;
    segGrp.add(frontRing);

    // Cute tucked lantern paws on front chest (seg 1) and hind hips (seg 11)
    if (i === 1 || i === 11) {
      for (const s of [-1, 1]) {
        const paw = new THREE.Mesh(pawGeo, earMat);
        paw.position.set(s * r * 0.62, -r * 0.78, i === 1 ? 0.12 : -0.08);
        paw.rotation.x = i === 1 ? 0.35 : -0.35;
        segGrp.add(paw);
      }
    }

    // Soft glowing aura sprites on alternating segments
    if (i % 2 === 0) {
      const spr = new THREE.Sprite(new THREE.SpriteMaterial({
        map: glowSpriteTex,
        color: haloColor,
        transparent: true,
        opacity: 0.44 * (0.55 + 0.45 * r),
        blending: THREE.AdditiveBlending,
        depthWrite: false
      }));
      const hs = 3.2 + r * 2.2;
      spr.scale.set(hs, hs, 1);
      segGrp.add(spr);
    }

    // Secondary soft PointLight mid-body so the whole glowing chain lights up rooftops
    if (i === 6) {
      const midLight = new THREE.PointLight(isOrange ? 0xff7b22 : 0x9ec4ff, 26, 26, 1.5);
      segGrp.add(midLight);
    }

    scene.add(segGrp);
    bodySegments.push({
      group: segGrp,
      radius: r,
      spacing: i === 0 ? 1.18 : Math.max(0.62, (r + 0.16) * 0.92),
      pos: new THREE.Vector3()
    });
  }

  // --- EXPRESSIVE FLICKING TAIL (9 TAPERED GLOWING LANTERN SEGMENTS) ---
  const TAIL_COUNT = 9;
  const tailSegments = [];
  const tipGeo = new THREE.SphereGeometry(0.30, 10, 8);
  tipGeo.scale(0.85, 0.85, 1.35);

  for (let i = 0; i < TAIL_COUNT; i++) {
    const t = i / (TAIL_COUNT - 1);
    const r = i === TAIL_COUNT - 1 ? 0.30 : THREE.MathUtils.lerp(0.34, 0.17, t);
    const segGrp = new THREE.Group();
    if (i === TAIL_COUNT - 1) {
      // Fluffy glowing lantern brush tip!
      const tip = new THREE.Mesh(tipGeo, headMat);
      segGrp.add(tip);
      const tipHalo = new THREE.Sprite(new THREE.SpriteMaterial({
        map: glowSpriteTex,
        color: isOrange ? 0xffbd5c : 0xd6e8ff,
        transparent: true,
        opacity: 0.65,
        blending: THREE.AdditiveBlending,
        depthWrite: false
      }));
      tipHalo.scale.set(2.5, 2.5, 1);
      segGrp.add(tipHalo);
    } else {
      const m = new THREE.Mesh(sharedBodySegGeo, bodyMat);
      m.scale.set(r, r, r * 1.65);
      segGrp.add(m);
    }
    scene.add(segGrp);
    tailSegments.push({
      group: segGrp,
      radius: r,
      spacing: 0.56 - t * 0.08,
      pos: new THREE.Vector3()
    });
  }

  // --- PRE-POPULATE SMOOTH ARC-LENGTH TRAIL (NO FRAME-0 BUNCHING!) ---
  const TRAIL_STEP = 0.16;
  const MAX_TRAIL = 260;
  const trail = [];
  const dirNorm = startDir.clone().normalize();
  const sideVec = new THREE.Vector3(-dirNorm.z, 0, dirNorm.x).normalize();

  for (let k = 0; k < MAX_TRAIL; k++) {
    const back = k * TRAIL_STEP;
    const p = startPos.clone().addScaledVector(dirNorm, -back);
    p.addScaledVector(sideVec, Math.sin(back * 0.32) * 1.15);
    p.y += Math.cos(back * 0.28) * 0.55;
    trail.push(p);
  }

  const cat = {
    name,
    isOrange,
    headGroup,
    headPos: startPos.clone(),
    vel: dirNorm.clone().multiplyScalar(9.5),
    speed: 9.5,
    upVec: new THREE.Vector3(0, 1, 0),
    trail,
    trailStep: TRAIL_STEP,
    maxTrail: MAX_TRAIL,
    bodySegments,
    tailSegments,
    earPivots,
    whiskerPivots,
    eyePivots,
    wavePhase: isOrange ? 0.0 : Math.PI * 0.85,
    earFlickL: 0,
    earFlickR: 0,
    earFlickTimer: 0.8 + rand() * 1.4,
    whiskerFlick: 0,
    tailFlick: 0,
    tailFlickDir: 1,
    tailFlickTimer: 1.5 + rand() * 1.8,
    blinkTimer: 2.2 + rand() * 3.0,
    blinkVal: 0,
    sparkTimer: 0,
    waypointIdx: isOrange ? 0 : 4,
    followTimer: 0,
    followTarget: new THREE.Vector3(),
    allNodes: [] // Filled with head + body + tail references for fast inter-cat separation
  };

  cat.allNodes.push({ pos: cat.headPos, radius: 1.05, isHead: true });
  for (const s of bodySegments) cat.allNodes.push({ pos: s.pos, radius: s.radius, isHead: false });
  for (const t of tailSegments) cat.allNodes.push({ pos: t.pos, radius: t.radius, isHead: false });

  return cat;
}

const catOrange = createLanternCat({
  name: 'Orange Lantern Cat',
  isOrange: true,
  startPos: new THREE.Vector3(-4.2, 8.2, 7.0),
  startDir: new THREE.Vector3(0.25, 0.05, -1.0)
});

const catSilver = createLanternCat({
  name: 'Silver Lantern Cat',
  isOrange: false,
  startPos: new THREE.Vector3(4.6, 10.6, -2.5),
  startDir: new THREE.Vector3(-0.35, -0.08, -0.92)
});

const cats = [catOrange, catSilver];

// ============================================================================
// OBSTACLE AVOIDANCE & STRICT NON-INTERSECTION PHYSICS
// ============================================================================
const _tmpV1 = new THREE.Vector3();
const _tmpV2 = new THREE.Vector3();
const _tmpRight = new THREE.Vector3();
const _tmpUp = new THREE.Vector3();
const _tmpFwd = new THREE.Vector3();
const _tmpMat = new THREE.Matrix4();

function computeObstacleSteering(pos, vel, outForce) {
  outForce.set(0, 0, 0);
  const marginWarn = 4.2;

  // 1. Houses, bridge & trees (rotated box volumes)
  for (let i = 0; i < obstacles.length; i++) {
    const ob = obstacles[i];
    const dx = pos.x - ob.cx;
    const dz = pos.z - ob.cz;
    // Quick radial broadphase check
    const maxR = ob.hx + ob.hz + marginWarn + 1.5;
    if (dx * dx + dz * dz > maxR * maxR) continue;
    if (pos.y > ob.topY + marginWarn) continue;

    // World -> local rotated box coordinates
    const lx = dx * ob.cosA - dz * ob.sinA;
    const lz = dx * ob.sinA + dz * ob.cosA;

    const ex = ob.hx + marginWarn;
    const ez = ob.hz + marginWarn;
    const ey = ob.topY + marginWarn;

    if (Math.abs(lx) < ex && Math.abs(lz) < ez && pos.y < ey) {
      // Closest point on actual building box
      const clx = Math.max(-ob.hx, Math.min(ob.hx, lx));
      const clz = Math.max(-ob.hz, Math.min(ob.hz, lz));
      const cly = Math.max(0, Math.min(ob.topY, pos.y));

      const nlx = lx - clx;
      const nlz = lz - clz;
      const nly = pos.y - cly;
      const dist = Math.sqrt(nlx * nlx + nlz * nlz + nly * nly);
      const strength = Math.pow(Math.max(0, 1.0 - dist / marginWarn), 2.0) * 34.0;

      let wx, wy, wz;
      if (dist > 0.001) {
        // Convert local outward normal back to world
        const lnx = nlx / dist;
        const lnz = nlz / dist;
        wx = lnx * ob.cosA + lnz * ob.sinA;
        wz = -lnx * ob.sinA + lnz * ob.cosA;
        wy = nly / dist;
      } else {
        wx = 0;
        wy = 1;
        wz = 0;
      }
      outForce.x += wx * strength;
      outForce.y += (wy + 0.35) * strength; // Slight upward grace over rooftops
      outForce.z += wz * strength;

      // Gentle tangential swirl so cats curve gracefully around eaves instead of stalling
      const tangX = -wz;
      const tangZ = wx;
      const sign = (vel.x * tangX + vel.z * tangZ) >= 0 ? 1 : -1;
      outForce.x += tangX * sign * strength * 0.42;
      outForce.z += tangZ * sign * strength * 0.42;
    }
  }

  // 2. Light-string catenaries (weave cleanly over or under the garlands!)
  for (let ci = 0; ci < lightStringCurves.length; ci++) {
    const pts = lightStringCurves[ci];
    for (let pi = 0; pi < pts.length; pi++) {
      const sp = pts[pi];
      const dx = pos.x - sp.x;
      const dy = pos.y - sp.y;
      const dz = pos.z - sp.z;
      const d2 = dx * dx + dy * dy + dz * dz;
      if (d2 < 9.0 && d2 > 0.0001) {
        const d = Math.sqrt(d2);
        const f = Math.pow(1.0 - d / 3.0, 2.0) * 18.0;
        // Prefer vertical separation (duck smoothly under or glide over the string!)
        const yDir = dy >= 0 ? 1.0 : -1.0;
        outForce.x += (dx / d) * f * 0.45;
        outForce.y += yDir * f * 1.15;
        outForce.z += (dz / d) * f * 0.45;
      }
    }
  }

  // 3. Water / terrain floor cushion & upper sky ceiling
  const floorY = Math.max(WATER_Y + 3.0, terrainHeightAt(pos.x, pos.z) + 2.6);
  if (pos.y < floorY + 2.5) {
    const t = Math.max(0, 1.0 - (pos.y - floorY) / 2.5);
    outForce.y += t * t * 28.0;
  }
  if (pos.y > 23.0) {
    outForce.y -= (pos.y - 23.0) * 4.5;
  }

  // 4. Keep inside scenic valley bounds
  const rcx = riverCenterX(pos.z);
  const maxBank = riverHalfWidth(pos.z) + 17.0;
  if (Math.abs(pos.x - rcx) > maxBank) {
    outForce.x -= Math.sign(pos.x - rcx) * (Math.abs(pos.x - rcx) - maxBank) * 4.0;
  }
  if (pos.z < -56) outForce.z += (-56 - pos.z) * 4.2;
  if (pos.z > 36) outForce.z -= (pos.z - 36) * 4.2;
}

// Hard geometric push-out for a single 3D node against every house, bridge, tree, water & terrain
function enforceEnvironmentCollision(pos, radius) {
  const pad = radius + 0.42;

  for (let i = 0; i < obstacles.length; i++) {
    const ob = obstacles[i];
    const dx = pos.x - ob.cx;
    const dz = pos.z - ob.cz;
    const maxR = ob.hx + ob.hz + pad + 1.0;
    if (dx * dx + dz * dz > maxR * maxR) continue;
    if (pos.y >= ob.topY + pad) continue;

    let lx = dx * ob.cosA - dz * ob.sinA;
    let lz = dx * ob.sinA + dz * ob.cosA;
    const ex = ob.hx + pad;
    const ez = ob.hz + pad;
    const ey = ob.topY + pad;

    if (Math.abs(lx) < ex && Math.abs(lz) < ez && pos.y < ey) {
      const penX = ex - Math.abs(lx);
      const penZ = ez - Math.abs(lz);
      const penY = ey - pos.y;

      // Gently favor lifting over roofs when close to top
      if (penY <= penX * 1.25 && penY <= penZ * 1.25) {
        pos.y = ey;
      } else if (penX < penZ) {
        lx = lx >= 0 ? ex : -ex;
        pos.x = ob.cx + lx * ob.cosA + lz * ob.sinA;
        pos.z = ob.cz - lx * ob.sinA + lz * ob.cosA;
      } else {
        lz = lz >= 0 ? ez : -ez;
        pos.x = ob.cx + lx * ob.cosA + lz * ob.sinA;
        pos.z = ob.cz - lx * ob.sinA + lz * ob.cosA;
      }
    }
  }

  // Strictly above river water & ground terrain
  const minH = Math.max(WATER_Y + radius + 1.05, terrainHeightAt(pos.x, pos.z) + radius + 0.85);
  if (pos.y < minH) {
    pos.y = minH;
  }
}

// Hard non-intersection pass between ALL segments of Cat A and Cat B
function enforceInterCatSeparation(catA, catB) {
  const nodesA = catA.allNodes;
  const nodesB = catB.allNodes;
  const extraGap = 0.62;

  for (let i = 0; i < nodesA.length; i++) {
    const a = nodesA[i];
    for (let j = 0; j < nodesB.length; j++) {
      const b = nodesB[j];
      const dx = a.pos.x - b.pos.x;
      const dy = a.pos.y - b.pos.y;
      const dz = a.pos.z - b.pos.z;
      const minD = a.radius + b.radius + extraGap;
      const d2 = dx * dx + dy * dy + dz * dz;
      if (d2 < minD * minD) {
        let d = Math.sqrt(d2);
        let nx, ny, nz;
        if (d < 0.001) {
          nx = 0; ny = 1; nz = 0; d = 0.001;
        } else {
          nx = dx / d; ny = dy / d; nz = dz / d;
        }
        const push = (minD - d) * 0.52;
        a.pos.x += nx * push;
        a.pos.y += ny * push;
        a.pos.z += nz * push;
        b.pos.x -= nx * push;
        b.pos.y -= ny * push;
        b.pos.z -= nz * push;

        // If heads brush close, trigger playful ear/tail flicks & redirect velocities apart
        if (a.isHead) {
          const vn = catA.vel.x * nx + catA.vel.y * ny + catA.vel.z * nz;
          if (vn < 0) {
            catA.vel.x -= nx * vn * 1.2;
            catA.vel.y -= ny * vn * 1.2;
            catA.vel.z -= nz * vn * 1.2;
          }
          if (catA.earFlickL < 0.2) catA.earFlickL = 0.9;
        }
        if (b.isHead) {
          const vn = catB.vel.x * (-nx) + catB.vel.y * (-ny) + catB.vel.z * (-nz);
          if (vn < 0) {
            catB.vel.x += nx * vn * 1.2;
            catB.vel.y += ny * vn * 1.2;
            catB.vel.z += nz * vn * 1.2;
          }
          if (catB.earFlickR < 0.2) catB.earFlickR = 0.9;
        }
      }
    }
  }
}

// ============================================================================
// CHASE CHOREOGRAPHY & SCENIC WEAVING WAYPOINTS
// ============================================================================
const weaveWaypoints = [
  new THREE.Vector3(0, 6.2, 16),     // Low swoop over river reflecting brilliantly
  new THREE.Vector3(-12, 13.5, 4),   // Rise over west bank rooftops & light string
  new THREE.Vector3(6, 7.6, -8),     // Duck under mid-river string lights!
  new THREE.Vector3(-4, 15.5, -24),  // Soar gracefully over the arched lantern bridge
  new THREE.Vector3(14, 14.5, -36),  // Circle near the 3-story festival pagoda
  new THREE.Vector3(-7, 7.8, -42),   // Swoop low down the moonlit far river
  new THREE.Vector3(9, 13.8, -16),   // Weave back over the east riverfront eaves
  new THREE.Vector3(-5, 6.6, 2)      // Skim low over the glowing river bend
];

let chaserIndex = 0; // 0 = Orange chases Silver, 1 = Silver chases Orange
let roleSwapTimer = 10.5;

// ============================================================================
// INTERACTIVE TOUCH / DRAG LURE & VISUAL FIREFLY INDICATOR
// ============================================================================
const lureGroup = new THREE.Group();
const lureCore = new THREE.Mesh(
  new THREE.SphereGeometry(0.24, 12, 10),
  new THREE.MeshBasicMaterial({ color: 0xfff3cc, transparent: true, opacity: 0.95 })
);
lureGroup.add(lureCore);

const lureRing = new THREE.Mesh(
  new THREE.TorusGeometry(0.82, 0.045, 8, 28),
  new THREE.MeshBasicMaterial({ color: 0xffc66e, transparent: true, opacity: 0.65, blending: THREE.AdditiveBlending, depthWrite: false })
);
lureGroup.add(lureRing);

const lureHalo = new THREE.Sprite(new THREE.SpriteMaterial({
  map: glowSpriteTex,
  color: 0xffba5c,
  transparent: true,
  opacity: 0.85,
  blending: THREE.AdditiveBlending,
  depthWrite: false
}));
lureHalo.scale.set(4.2, 4.2, 1);
lureGroup.add(lureHalo);
lureGroup.visible = false;
scene.add(lureGroup);

const raycaster = new THREE.Raycaster();
const pointerNdc = new THREE.Vector2();
const dragPlane = new THREE.Plane();
const dragPlaneNormal = new THREE.Vector3();
const dragHitPoint = new THREE.Vector3();

let activePointerId = null;
let pointerDown = false;
let luredCatIndex = -1;
let lureOpacity = 0;
let dragPlaneDepth = 26;

function projectPointerTo3D(clientX, clientY, targetDepth) {
  const rect = canvas.getBoundingClientRect();
  pointerNdc.x = ((clientX - rect.left) / Math.max(1, rect.width)) * 2 - 1;
  pointerNdc.y = -((clientY - rect.top) / Math.max(1, rect.height)) * 2 + 1;

  raycaster.setFromCamera(pointerNdc, mainCamera);
  mainCamera.getWorldDirection(dragPlaneNormal);
  const planeCenter = mainCamera.position.clone().addScaledVector(dragPlaneNormal, targetDepth);
  dragPlane.setFromNormalAndCoplanarPoint(dragPlaneNormal, planeCenter);

  if (!raycaster.ray.intersectPlane(dragPlane, dragHitPoint)) {
    dragHitPoint.copy(planeCenter);
  }

  // Clamp lure nicely inside safe navigable festival airspace
  dragHitPoint.y = Math.max(3.4, Math.min(22.5, dragHitPoint.y));
  dragHitPoint.z = Math.max(-54, Math.min(34, dragHitPoint.z));
  const rcx = riverCenterX(dragHitPoint.z);
  const maxX = riverHalfWidth(dragHitPoint.z) + 15.0;
  dragHitPoint.x = Math.max(rcx - maxX, Math.min(rcx + maxX, dragHitPoint.x));

  // Push lure cleanly outside any house roof so cats never jam into a wall trying to reach it
  enforceEnvironmentCollision(dragHitPoint, 1.6);
  return dragHitPoint;
}

function findNearestCatScreenSpace(clientX, clientY) {
  const rect = canvas.getBoundingClientRect();
  const px = ((clientX - rect.left) / Math.max(1, rect.width)) * 2 - 1;
  const py = -((clientY - rect.top) / Math.max(1, rect.height)) * 2 + 1;

  let bestIdx = 0;
  let bestDist = Infinity;
  const proj = new THREE.Vector3();
  for (let i = 0; i < cats.length; i++) {
    proj.copy(cats[i].headPos).project(mainCamera);
    const dx = proj.x - px;
    const dy = proj.y - py;
    const d = dx * dx + dy * dy;
    if (d < bestDist) {
      bestDist = d;
      bestIdx = i;
    }
  }
  return bestIdx;
}

function endDemoMode() {
  if (!demoMode) return;
  demoMode = false;
  demoPill.classList.remove('visible');
  lureOpacity = 0;
  lureGroup.visible = false;
}

// ============================================================================
// PROCEDURAL SOFT FESTIVAL NIGHT MELODY (WEB AUDIO API)
// ============================================================================
class FestivalMelody {
  constructor() {
    this.ctx = null;
    this.masterGain = null;
    this.delayL = null;
    this.delayR = null;
    this.padGain = null;
    this.isMuted = false;
    this.isRunning = false;
    this.stepIndex = 0;
    this.nextNoteTime = 0;
    this.schedulerId = null;

    // Gentle D-major pentatonic festival night lullaby (16-step lyrical motif x 2 phrases)
    // Frequencies in Hz: D4=293.66, E4=329.63, F#4=369.99, A4=440.0, B4=493.88, D5=587.33, E5=659.25, F#5=739.99, A5=880.0
    this.melody = [
      587.33, 0,      659.25, 739.99,  880.00, 0,      739.99, 659.25,
      587.33, 493.88, 440.00, 0,       493.88, 587.33, 440.00, 0,
      587.33, 0,      739.99, 659.25,  587.33, 493.88, 440.00, 369.99,
      440.00, 493.88, 587.33, 0,       493.88, 0,      440.00, 0
    ];
    // Warm bass foundation per 4 steps (D3, B2, G2, A2, D3, F#2, G2, A2)
    this.bass = [146.83, 123.47, 98.00, 110.00, 146.83, 185.00, 196.00, 110.00];
    this.chimeScale = [587.33, 659.25, 739.99, 880.00, 987.77, 1174.66];
  }

  ensureContext() {
    if (this.ctx) return true;
    const AudioCtx = window.AudioContext || window.webkitAudioContext;
    if (!AudioCtx) return false;
    try {
      this.ctx = new AudioCtx();
      this.masterGain = this.ctx.createGain();
      this.masterGain.gain.value = 0.0001;
      this.masterGain.connect(this.ctx.destination);

      // Soft nocturnal stereo echo bus (low-passed warm reflections across the river)
      this.echoIn = this.ctx.createGain();
      this.echoFilter = this.ctx.createBiquadFilter();
      this.echoFilter.type = 'lowpass';
      this.echoFilter.frequency.value = 1450;

      this.delayL = this.ctx.createDelay(1.0);
      this.delayR = this.ctx.createDelay(1.0);
      this.delayL.delayTime.value = 0.39;
      this.delayR.delayTime.value = 0.54;

      const fbL = this.ctx.createGain();
      const fbR = this.ctx.createGain();
      fbL.gain.value = 0.30;
      fbR.gain.value = 0.28;

      const wetGain = this.ctx.createGain();
      wetGain.gain.value = 0.42;

      this.echoIn.connect(this.echoFilter);
      this.echoFilter.connect(this.delayL);
      this.echoFilter.connect(this.delayR);
      this.delayL.connect(fbL);
      fbL.connect(this.delayR);
      this.delayR.connect(fbR);
      fbR.connect(this.delayL);
      this.delayL.connect(wetGain);
      this.delayR.connect(wetGain);
      wetGain.connect(this.masterGain);

      this.dryBus = this.ctx.createGain();
      this.dryBus.gain.value = 0.78;
      this.dryBus.connect(this.masterGain);
      this.dryBus.connect(this.echoIn);

      return true;
    } catch (_) {
      return false;
    }
  }

  start() {
    if (!this.ensureContext()) return;
    if (this.ctx.state === 'suspended') {
      this.ctx.resume().then(() => {
        this.onResumed();
      }).catch(() => {});
    } else {
      this.onResumed();
    }
  }

  onResumed() {
    if (!this.ctx || this.ctx.state !== 'running') return;
    if (!this.isRunning) {
      this.isRunning = true;
      this.nextNoteTime = this.ctx.currentTime + 0.08;
      this.schedulerId = setInterval(() => this.schedule(), 80);
    }
    this.updateVolume();
    updateAudioButtonUI();
  }

  updateVolume() {
    if (!this.ctx || !this.masterGain) return;
    const now = this.ctx.currentTime;
    const target = this.isMuted ? 0.0001 : 0.36;
    this.masterGain.gain.cancelScheduledValues(now);
    this.masterGain.gain.setTargetAtTime(target, now, 0.08);
  }

  toggleMute() {
    if (!this.isRunning || !this.ctx || this.ctx.state !== 'running') {
      this.isMuted = false;
      this.start();
      updateAudioButtonUI();
      return;
    }
    this.isMuted = !this.isMuted;
    this.updateVolume();
    updateAudioButtonUI();
  }

  playKotoBell(freq, time, duration, volume = 0.24) {
    if (!this.ctx) return;
    const osc1 = this.ctx.createOscillator();
    const osc2 = this.ctx.createOscillator();
    const filt = this.ctx.createBiquadFilter();
    const env = this.ctx.createGain();

    osc1.type = 'sine';
    osc1.frequency.setValueAtTime(freq, time);
    osc2.type = 'triangle';
    osc2.frequency.setValueAtTime(freq * 2.0, time);

    const h2Gain = this.ctx.createGain();
    h2Gain.gain.setValueAtTime(0.18, time);
    h2Gain.gain.exponentialRampToValueAtTime(0.004, time + duration * 0.45);

    filt.type = 'lowpass';
    filt.frequency.setValueAtTime(2400, time);
    filt.frequency.exponentialRampToValueAtTime(680, time + duration);

    env.gain.setValueAtTime(0.0001, time);
    env.gain.linearRampToValueAtTime(volume, time + 0.018);
    env.gain.exponentialRampToValueAtTime(0.0004, time + duration);

    osc1.connect(filt);
    osc2.connect(h2Gain);
    h2Gain.connect(filt);
    filt.connect(env);
    env.connect(this.dryBus);

    osc1.start(time);
    osc2.start(time);
    osc1.stop(time + duration + 0.06);
    osc2.stop(time + duration + 0.06);
  }

  playWarmBass(freq, time, duration) {
    if (!this.ctx) return;
    const osc = this.ctx.createOscillator();
    const filt = this.ctx.createBiquadFilter();
    const env = this.ctx.createGain();

    osc.type = 'triangle';
    osc.frequency.setValueAtTime(freq, time);
    filt.type = 'lowpass';
    filt.frequency.setValueAtTime(420, time);

    env.gain.setValueAtTime(0.0001, time);
    env.gain.linearRampToValueAtTime(0.18, time + 0.14);
    env.gain.exponentialRampToValueAtTime(0.0005, time + duration);

    osc.connect(filt);
    filt.connect(env);
    env.connect(this.dryBus);

    osc.start(time);
    osc.stop(time + duration + 0.08);
  }

  playTouchChime(isOrange) {
    if (!this.ctx || this.ctx.state !== 'running' || this.isMuted) return;
    const now = this.ctx.currentTime + 0.01;
    const idx = isOrange ? (Math.floor(Math.random() * 3) + 1) : (Math.floor(Math.random() * 3) + 3);
    const f = this.chimeScale[idx % this.chimeScale.length];
    this.playKotoBell(f, now, 1.35, 0.14);
    this.playKotoBell(f * 1.5, now + 0.075, 1.15, 0.08);
  }

  schedule() {
    if (!this.ctx || this.ctx.state !== 'running') return;
    const stepDur = 0.44; // Dreamy ~68 BPM eighth-note pulse
    while (this.nextNoteTime < this.ctx.currentTime + 0.24) {
      const s = this.stepIndex % this.melody.length;
      const note = this.melody[s];

      if (note > 0) {
        // Occasional gentle octave shimmer or delicate grace note on repeat cycles
        const cycle = Math.floor(this.stepIndex / this.melody.length);
        const playFreq = (cycle % 2 === 1 && s % 8 === 4) ? note * 0.5 : note;
        this.playKotoBell(playFreq, this.nextNoteTime, 2.25, 0.22);

        // Delicate soft harmony fifth on accented phrases
        if (s % 8 === 0) {
          this.playKotoBell(note * 0.75, this.nextNoteTime + 0.04, 2.4, 0.09);
        }
      }

      if (s % 4 === 0) {
        const bFreq = this.bass[Math.floor(s / 4) % this.bass.length];
        this.playWarmBass(bFreq, this.nextNoteTime, 2.1);
      }

      this.nextNoteTime += stepDur;
      this.stepIndex++;
    }
  }
}

const melody = new FestivalMelody();

function updateAudioButtonUI() {
  const active = melody.isRunning && melody.ctx && melody.ctx.state === 'running' && !melody.isMuted;
  if (melody.isMuted) {
    audioBtn.classList.remove('playing');
    audioBtn.classList.add('muted');
    audioLabel.textContent = 'Muted';
    wave1.style.display = 'none';
    wave2.style.display = 'none';
    muteSlash1.style.display = '';
    muteSlash2.style.display = '';
  } else if (active) {
    audioBtn.classList.add('playing');
    audioBtn.classList.remove('muted');
    audioLabel.textContent = 'Mute';
    wave1.style.display = '';
    wave2.style.display = '';
    muteSlash1.style.display = 'none';
    muteSlash2.style.display = 'none';
  } else {
    audioBtn.classList.remove('playing', 'muted');
    audioLabel.textContent = 'Play Melody';
    wave1.style.display = '';
    wave2.style.display = 'none';
    muteSlash1.style.display = 'none';
    muteSlash2.style.display = 'none';
  }
}

// Attempt gentle auto-start if browser policy allows; otherwise unlocks seamlessly on first touch
melody.start();
updateAudioButtonUI();

audioBtn.addEventListener('pointerdown', (e) => {
  e.stopPropagation();
  if (e.isTrusted) endDemoMode();
});

audioBtn.addEventListener('click', (e) => {
  e.stopPropagation();
  if (e.isTrusted) endDemoMode();
  melody.toggleMute();
});

// ============================================================================
// POINTER / TOUCH INTERACTION HANDLERS (PHONE TOUCH + DESKTOP MOUSE)
// ============================================================================
canvas.addEventListener('pointerdown', (e) => {
  if (e.isTrusted) {
    endDemoMode();
    if (!melody.isMuted && (!melody.isRunning || (melody.ctx && melody.ctx.state !== 'running'))) {
      melody.start();
    }
  }

  activePointerId = e.pointerId;
  pointerDown = true;
  try { canvas.setPointerCapture(e.pointerId); } catch (_) {}

  // Pick nearest cat on screen!
  luredCatIndex = findNearestCatScreenSpace(e.clientX, e.clientY);
  const chosenCat = cats[luredCatIndex];

  // Set intuitive plane depth near the chosen cat's current distance from camera
  const camDist = mainCamera.position.distanceTo(chosenCat.headPos);
  dragPlaneDepth = Math.max(15, Math.min(40, camDist));

  const pt = projectPointerTo3D(e.clientX, e.clientY, dragPlaneDepth);
  chosenCat.followTarget.copy(pt);
  chosenCat.followTimer = 5.2; // Keeps following for a while even after a quick tap!

  // Instant joyful cat reaction: ear flick + whisker twitch + tail flick + soft chime
  chosenCat.earFlickL = 1.0;
  chosenCat.earFlickR = 0.85;
  chosenCat.whiskerFlick = 1.0;
  chosenCat.tailFlick = 1.0;
  chosenCat.tailFlickDir = Math.random() > 0.5 ? 1 : -1;
  melody.playTouchChime(chosenCat.isOrange);

  lureGroup.position.copy(pt);
  lureGroup.visible = true;
  lureOpacity = 1.0;
  lureHalo.material.color.setHex(chosenCat.isOrange ? 0xffa64d : 0xaad0ff);
  lureRing.material.color.setHex(chosenCat.isOrange ? 0xffbf6b : 0xbddcff);

  showStatus(chosenCat.isOrange ? 'Orange lantern cat is following you' : 'Silver lantern cat is following you');
});

canvas.addEventListener('pointermove', (e) => {
  if (!pointerDown || e.pointerId !== activePointerId || luredCatIndex < 0) return;
  const chosenCat = cats[luredCatIndex];
  const pt = projectPointerTo3D(e.clientX, e.clientY, dragPlaneDepth);
  chosenCat.followTarget.copy(pt);
  chosenCat.followTimer = 4.6;
  lureGroup.position.copy(pt);
  lureOpacity = 1.0;
});

function releasePointer(e) {
  if (e.pointerId !== activePointerId) return;
  pointerDown = false;
  activePointerId = null;
  try { canvas.releasePointerCapture(e.pointerId); } catch (_) {}
}
canvas.addEventListener('pointerup', releasePointer);
canvas.addEventListener('pointercancel', releasePointer);

window.addEventListener('keydown', (e) => {
  if (e.isTrusted) endDemoMode();
}, { passive: true });

window.addEventListener('hashchange', () => {
  if (checkDemoHash()) {
    demoMode = true;
    demoTime = 0;
    demoPill.classList.add('visible');
  } else {
    endDemoMode();
  }
});

// ============================================================================
// CINEMATIC SLOW FILM CAMERA
// ============================================================================
let filmTime = 0;
const camPosTarget = new THREE.Vector3(0, 7.2, 27);
const camLookTarget = new THREE.Vector3(0, 6.2, -14);
const camPosSmooth = new THREE.Vector3(0, 7.2, 27);
const camLookSmooth = new THREE.Vector3(0, 6.2, -14);

function updateCamera(dt) {
  if (demoMode) {
    // 20-second seamless periodic cinematic loop (C-infinity smooth at t = 0 and t = 20!)
    const theta = (demoTime / DEMO_DURATION) * Math.PI * 2;
    const cz = 22.5 + Math.cos(theta) * 8.5 - Math.sin(theta * 2) * 3.0;
    const cx = riverCenterX(cz) + Math.sin(theta) * 9.5;
    const cy = 6.8 + (0.5 - 0.5 * Math.cos(theta)) * 7.8 + Math.sin(theta * 2) * 1.1;

    camPosTarget.set(cx, cy, cz);

    const lookZ = -12.0 + Math.sin(theta) * 9.0;
    const lookX = riverCenterX(lookZ) + Math.sin(theta * 2) * 2.5;
    const lookY = 6.2 + (0.5 - 0.5 * Math.cos(theta)) * 3.2;

    // Subtle film operator tracking bias toward cats' midpoint
    const midX = (catOrange.headPos.x + catSilver.headPos.x) * 0.5;
    const midY = (catOrange.headPos.y + catSilver.headPos.y) * 0.5;
    const midZ = (catOrange.headPos.z + catSilver.headPos.z) * 0.5;

    camLookTarget.set(
      THREE.MathUtils.lerp(lookX, midX, 0.30),
      THREE.MathUtils.lerp(lookY, midY, 0.25),
      THREE.MathUtils.lerp(lookZ, midZ, 0.25)
    );
  } else {
    // Slow, unhurried film crane & river-gliding shots (slows gently while dragging)
    const speedMult = pointerDown ? 0.28 : 1.0;
    filmTime += dt * speedMult;

    const a = filmTime * 0.095;
    const b = filmTime * 0.058;
    const cz = 18.0 + Math.cos(a) * 13.5 + Math.sin(b) * 5.0;
    const cx = riverCenterX(cz) + Math.sin(a * 0.85) * 10.5;
    // Gently sweeps between low river reflection shots (~5.4) and high rooftop crane shots (~15.5)
    const cy = 9.2 + Math.sin(b * 1.15 - 0.6) * 4.4 + Math.cos(a * 0.6) * 1.4;

    camPosTarget.set(cx, Math.max(4.6, cy), cz);

    const lookZ = cz - 28.0 + Math.sin(b) * 5.0;
    const baseLookX = riverCenterX(lookZ);
    const baseLookY = 7.0 + Math.sin(b * 0.9) * 1.8;

    const midX = (catOrange.headPos.x + catSilver.headPos.x) * 0.5;
    const midY = (catOrange.headPos.y + catSilver.headPos.y) * 0.5;
    const midZ = (catOrange.headPos.z + catSilver.headPos.z) * 0.5;

    camLookTarget.set(
      THREE.MathUtils.lerp(baseLookX, midX, 0.32),
      THREE.MathUtils.lerp(baseLookY, midY, 0.26),
      THREE.MathUtils.lerp(lookZ, midZ, 0.26)
    );
  }

  const posLerp = 1.0 - Math.exp(-dt * 1.55);
  const lookLerp = 1.0 - Math.exp(-dt * 1.35);
  camPosSmooth.lerp(camPosTarget, posLerp);
  camLookSmooth.lerp(camLookTarget, lookLerp);

  // Never let camera dip into water or collide with a house
  const minCamY = Math.max(WATER_Y + 3.8, terrainHeightAt(camPosSmooth.x, camPosSmooth.z) + 2.2);
  if (camPosSmooth.y < minCamY) camPosSmooth.y = minCamY;

  mainCamera.position.copy(camPosSmooth);
  mainCamera.up.set(0, 1, 0);
  mainCamera.lookAt(camLookSmooth);
}

// ============================================================================
// CAT UPDATE: STEERING, CHASE, SMOOTH WAVES, COLLISION & FLICKING FEATURES
// ============================================================================
function orientObjectForward(obj, forward, preferredUp) {
  _tmpFwd.copy(forward);
  if (_tmpFwd.lengthSq() < 1e-6) _tmpFwd.set(0, 0, -1);
  else _tmpFwd.normalize();

  _tmpUp.copy(preferredUp);
  if (Math.abs(_tmpUp.dot(_tmpFwd)) > 0.98) {
    _tmpUp.set(1, 0, 0);
  }
  _tmpRight.crossVectors(_tmpUp, _tmpFwd).normalize();
  _tmpUp.crossVectors(_tmpFwd, _tmpRight).normalize();

  _tmpMat.makeBasis(_tmpRight, _tmpUp, _tmpFwd);
  obj.quaternion.setFromRotationMatrix(_tmpMat);
}

const _steer = new THREE.Vector3();
const _obsForce = new THREE.Vector3();
const _desired = new THREE.Vector3();

function updateCats(dt, elapsed) {
  // Periodic playful leader/chaser role swap
  roleSwapTimer -= dt;
  if (roleSwapTimer <= 0) {
    chaserIndex = 1 - chaserIndex;
    roleSwapTimer = 9.5 + Math.random() * 4.5;
  }

  // #demo hands-free virtual touch-follow showcase between t = 9.5s and t = 15.5s
  if (demoMode) {
    const demoFollowActive = demoTime >= 9.5 && demoTime <= 15.5;
    if (demoFollowActive) {
      const u = (demoTime - 9.5) / 6.0;
      const demoLureZ = THREE.MathUtils.lerp(6.0, -12.0, u);
      const demoLureX = riverCenterX(demoLureZ) + Math.sin(u * Math.PI * 2.0) * 8.5;
      const demoLureY = 7.2 + Math.sin(u * Math.PI) * 5.2;
      catOrange.followTarget.set(demoLureX, demoLureY, demoLureZ);
      enforceEnvironmentCollision(catOrange.followTarget, 1.6);
      catOrange.followTimer = 1.2;

      lureGroup.position.copy(catOrange.followTarget);
      lureGroup.visible = true;
      lureOpacity = Math.sin(u * Math.PI);
      lureHalo.material.color.setHex(0xffa64d);
      lureRing.material.color.setHex(0xffbf6b);
    } else if (demoTime < 9.5 || demoTime > 16.5) {
      lureOpacity = Math.max(0, lureOpacity - dt * 2.5);
    }
  } else {
    // Fade firefly lure smoothly after finger lift
    if (!pointerDown) {
      lureOpacity = Math.max(0, lureOpacity - dt * 0.75);
    }
  }

  // Animate firefly lure indicator
  if (lureOpacity > 0.01) {
    lureGroup.visible = true;
    lureRing.rotation.z = elapsed * 2.2;
    lureRing.rotation.x = Math.sin(elapsed * 1.7) * 0.5;
    const pulse = 0.92 + 0.14 * Math.sin(elapsed * 6.5);
    lureGroup.scale.setScalar(pulse * Math.min(1, lureOpacity * 1.4));
    lureCore.material.opacity = lureOpacity * 0.95;
    lureRing.material.opacity = lureOpacity * 0.65;
    lureHalo.material.opacity = lureOpacity * 0.85;
  } else {
    lureGroup.visible = false;
  }

  // --- 1. STEER AND ADVANCE EACH CAT'S HEAD ---
  for (let i = 0; i < cats.length; i++) {
    const cat = cats[i];
    const other = cats[1 - i];

    cat.wavePhase += dt * 4.4;
    if (cat.followTimer > 0) cat.followTimer = Math.max(0, cat.followTimer - dt);

    _steer.set(0, 0, 0);
    let targetSpeed = 9.8;

    if (cat.followTimer > 0) {
      // Following user's touch / finger!
      _desired.subVectors(cat.followTarget, cat.headPos);
      const dist = _desired.length();
      if (dist > 2.2) {
        _desired.normalize().multiplyScalar(15.5);
        _steer.add(_desired);
        targetSpeed = THREE.MathUtils.clamp(8.5 + dist * 0.35, 8.8, 13.8);
      } else {
        // Playfully orbit the finger point in a tight glowing loop instead of stalling!
        const tangent = _tmpV1.set(-_desired.z, 0.35, _desired.x);
        if (tangent.lengthSq() < 0.01) tangent.set(1, 0, 0);
        tangent.normalize().multiplyScalar(11.0);
        _steer.add(tangent);
        _steer.addScaledVector(_desired, 2.5);
        targetSpeed = 8.4;
      }
    } else if (i === chaserIndex) {
      // Active chase: aim slightly flanking/behind the leader's head so they corkscrew playfully!
      const otherDir = _tmpV1.copy(other.vel).normalize();
      const flank = _tmpV2.set(-otherDir.z, 0, otherDir.x).normalize();
      const sideSign = Math.sin(elapsed * 0.85) >= 0 ? 1 : -1;
      const aimPt = _desired.copy(other.headPos)
        .addScaledVector(otherDir, -2.4)
        .addScaledVector(flank, sideSign * 3.8);
      aimPt.y += Math.sin(elapsed * 1.4) * 1.6;

      _desired.subVectors(aimPt, cat.headPos);
      const dist = _desired.length();
      if (dist > 0.1) _desired.divideScalar(dist);
      _steer.addScaledVector(_desired, 12.0);
      targetSpeed = THREE.MathUtils.clamp(9.4 + dist * 0.16, 9.6, 13.2);

      // Playful "tag" triggers ear/tail flick & role swap!
      if (dist < 4.2 && roleSwapTimer < 6.5) {
        chaserIndex = 1 - chaserIndex;
        roleSwapTimer = 9.0 + Math.random() * 4.0;
        other.earFlickL = 1.0;
        other.tailFlick = 1.0;
        other.whiskerFlick = 0.9;
      }
    } else {
      // Leader weaves through scenic festival waypoints across river, light strings & rooftops!
      const wp = weaveWaypoints[cat.waypointIdx];
      // Add organic river-bend weaving offset
      _desired.set(
        wp.x + riverCenterX(wp.z) * 0.45 + Math.sin(elapsed * 0.7 + i) * 2.4,
        wp.y + Math.sin(elapsed * 1.15 + i * 2.0) * 1.6,
        wp.z
      );
      const toWp = _desired.sub(cat.headPos);
      const dist = toWp.length();
      if (dist < 6.5) {
        cat.waypointIdx = (cat.waypointIdx + 1) % weaveWaypoints.length;
        cat.tailFlick = 0.85;
        cat.tailFlickDir = Math.random() > 0.5 ? 1 : -1;
      }
      if (dist > 0.1) toWp.divideScalar(dist);
      _steer.addScaledVector(toWp, 11.5);
      targetSpeed = 10.6;
    }

    // Subtle organic serpentine flight weave in velocity
    const curDir = _tmpV1.copy(cat.vel).normalize();
    const curRight = _tmpV2.set(-curDir.z, 0, curDir.x);
    if (curRight.lengthSq() > 0.001) {
      curRight.normalize();
      _steer.addScaledVector(curRight, Math.sin(cat.wavePhase * 0.75) * 3.6);
    }
    _steer.y += Math.cos(cat.wavePhase * 0.55) * 1.9;

    // Proactive look-ahead obstacle avoidance (houses, rooftops, bridge, willows, light strings!)
    for (const lookDist of [0.0, 3.6, 7.2]) {
      const samplePos = _tmpV1.copy(cat.headPos).addScaledVector(curDir, lookDist);
      computeObstacleSteering(samplePos, cat.vel, _obsForce);
      const weight = lookDist === 0.0 ? 1.15 : (lookDist < 5 ? 0.9 : 0.55);
      _steer.addScaledVector(_obsForce, weight);
    }

    // Proactive inter-cat avoidance (sense other cat's head AND every body segment!)
    for (let j = 0; j < other.allNodes.length; j += 2) {
      const node = other.allNodes[j];
      const dx = cat.headPos.x - node.pos.x;
      const dy = cat.headPos.y - node.pos.y;
      const dz = cat.headPos.z - node.pos.z;
      const safeD = 5.4;
      const d2 = dx * dx + dy * dy + dz * dz;
      if (d2 < safeD * safeD && d2 > 0.001) {
        const d = Math.sqrt(d2);
        const f = Math.pow(1.0 - d / safeD, 2.0) * 32.0;
        _steer.x += (dx / d) * f;
        _steer.y += (dy / d) * f;
        _steer.z += (dz / d) * f;
        // Swirl tangentially so they spiral gracefully past each other!
        _steer.x += (-dz / d) * f * 0.45;
        _steer.z += (dx / d) * f * 0.45;
      }
    }

    // Integrate velocity smoothly
    cat.vel.addScaledVector(_steer, dt);
    cat.speed = THREE.MathUtils.lerp(cat.speed, targetSpeed, 1.0 - Math.exp(-dt * 2.5));

    // Clamp steep vertical pitch so cats always fly gracefully like swimming lanterns
    const spd = cat.vel.length();
    if (spd > 0.001) {
      cat.vel.multiplyScalar(cat.speed / spd);
    }
    const maxVy = cat.speed * 0.62;
    if (Math.abs(cat.vel.y) > maxVy) {
      cat.vel.y = Math.sign(cat.vel.y) * maxVy;
      cat.vel.normalize().multiplyScalar(cat.speed);
    }

    // Advance head position & enforce hard environment collision
    const prevHead = _tmpV1.copy(cat.headPos);
    cat.headPos.addScaledVector(cat.vel, dt);
    enforceEnvironmentCollision(cat.headPos, 1.05);

    // Push evenly-spaced arc-length samples into head trail
    const moved = cat.headPos.distanceTo(cat.trail[0]);
    if (moved >= cat.trailStep) {
      const steps = Math.min(12, Math.floor(moved / cat.trailStep));
      for (let s = 1; s <= steps; s++) {
        const frac = s / steps;
        const pt = new THREE.Vector3().lerpVectors(prevHead, cat.headPos, frac);
        cat.trail.unshift(pt);
      }
      if (cat.trail.length > cat.maxTrail) {
        cat.trail.length = cat.maxTrail;
      }
    } else {
      cat.trail[0].copy(cat.headPos);
    }

    // --- 2. PLACE BODY SEGMENTS ALONG SMOOTH WAVE TRAIL ---
    let accumDist = 0;
    let trailCursor = 0;
    let accumTrailDist = 0;

    function sampleTrailAt(targetDist, outVec) {
      while (trailCursor < cat.trail.length - 2) {
        const segD = cat.trail[trailCursor].distanceTo(cat.trail[trailCursor + 1]);
        if (accumTrailDist + segD >= targetDist) {
          const frac = segD > 0.0001 ? (targetDist - accumTrailDist) / segD : 0;
          outVec.lerpVectors(cat.trail[trailCursor], cat.trail[trailCursor + 1], frac);
          return;
        }
        accumTrailDist += segD;
        trailCursor++;
      }
      outVec.copy(cat.trail[cat.trail.length - 1]);
    }

    const headDir = _tmpV2.copy(cat.vel).normalize();
    const headSide = _tmpRight.set(-headDir.z, 0, headDir.x);
    if (headSide.lengthSq() < 0.001) headSide.set(1, 0, 0);
    else headSide.normalize();

    for (let si = 0; si < cat.bodySegments.length; si++) {
      const seg = cat.bodySegments[si];
      accumDist += seg.spacing;
      sampleTrailAt(accumDist, seg.pos);

      // Gentle smooth lantern-dragon undulation traveling down the body!
      const u = (si + 1) / cat.bodySegments.length;
      const waveAmp = 0.24 * Math.sin(u * Math.PI);
      const latWave = Math.sin(cat.wavePhase - si * 0.48) * waveAmp;
      const vertWave = Math.cos(cat.wavePhase * 0.85 - si * 0.42) * waveAmp * 0.65;
      seg.pos.x += headSide.x * latWave;
      seg.pos.z += headSide.z * latWave;
      seg.pos.y += vertWave;

      enforceEnvironmentCollision(seg.pos, seg.radius);
    }

    // --- 3. PLACE EXPRESSIVE FLICKING TAIL ---
    cat.tailFlickTimer -= dt;
    if (cat.tailFlickTimer <= 0) {
      cat.tailFlick = 1.0;
      cat.tailFlickDir = Math.random() > 0.5 ? 1 : -1;
      cat.tailFlickTimer = 2.0 + Math.random() * 2.6;
    }
    cat.tailFlick = Math.max(0, cat.tailFlick - dt * 1.85);
    const flickEase = Math.sin(cat.tailFlick * Math.PI); // Smooth snappy whip pulse!

    const lastBody = cat.bodySegments[cat.bodySegments.length - 1];
    const prevBody = cat.bodySegments[cat.bodySegments.length - 2];
    const tailBaseBack = _tmpV1.subVectors(lastBody.pos, prevBody.pos);
    if (tailBaseBack.lengthSq() < 0.0001) tailBaseBack.copy(headDir).negate();
    else tailBaseBack.normalize();

    const tailRight = _tmpRight.crossVectors(new THREE.Vector3(0, 1, 0), tailBaseBack);
    if (tailRight.lengthSq() < 0.001) tailRight.set(1, 0, 0);
    else tailRight.normalize();

    let prevTailPt = lastBody.pos;
    for (let ti = 0; ti < cat.tailSegments.length; ti++) {
      const tSeg = cat.tailSegments[ti];
      const u = (ti + 1) / cat.tailSegments.length;

      // Blend trail following with active curling & flicking cat tail!
      accumDist += tSeg.spacing;
      sampleTrailAt(accumDist, tSeg.pos);

      const continuousSway = Math.sin(elapsed * 3.8 + cat.wavePhase * 0.3 - ti * 0.55) * 0.58 * u;
      const whipSide = flickEase * cat.tailFlickDir * Math.sin(u * Math.PI * 1.15) * 1.85 * u;
      const whipLift = (0.35 + flickEase * 1.45) * Math.pow(u, 1.35);

      tSeg.pos.addScaledVector(tailRight, continuousSway + whipSide);
      tSeg.pos.y += whipLift;

      // Keep each tail joint cleanly connected to the previous one
      _tmpV2.subVectors(tSeg.pos, prevTailPt);
      const d = _tmpV2.length();
      if (d > 0.0001) {
        tSeg.pos.copy(prevTailPt).addScaledVector(_tmpV2, tSeg.spacing / d);
      }
      enforceEnvironmentCollision(tSeg.pos, tSeg.radius);
      prevTailPt = tSeg.pos;
    }

    // --- 4. ANIMATE EARS, WHISKERS & EYE BLINKS ---
    cat.earFlickTimer -= dt;
    if (cat.earFlickTimer <= 0) {
      const pick = Math.random();
      if (pick < 0.42) cat.earFlickL = 1.0;
      else if (pick < 0.84) cat.earFlickR = 1.0;
      else { cat.earFlickL = 1.0; cat.earFlickR = 0.9; }
      cat.whiskerFlick = Math.max(cat.whiskerFlick, 0.75);
      cat.earFlickTimer = 1.4 + Math.random() * 2.4;
    }
    cat.earFlickL = Math.max(0, cat.earFlickL - dt * 4.2);
    cat.earFlickR = Math.max(0, cat.earFlickR - dt * 4.2);
    cat.whiskerFlick = Math.max(0, cat.whiskerFlick - dt * 3.2);

    const earL = Math.sin(cat.earFlickL * Math.PI);
    const earR = Math.sin(cat.earFlickR * Math.PI);
    for (const ep of cat.earPivots) {
      const f = ep.side > 0 ? earL : earR;
      const subtleBreath = Math.sin(elapsed * 2.6 + ep.side + i) * 0.05;
      ep.pivot.rotation.x = ep.baseRotX - f * 0.48 + subtleBreath;
      ep.pivot.rotation.z = ep.baseRotZ - ep.side * f * 0.52;
    }

    const wFlick = Math.sin(cat.whiskerFlick * Math.PI * 2.0) * cat.whiskerFlick;
    for (const wp of cat.whiskerPivots) {
      const twitch = Math.sin(elapsed * 7.5 + wp.side * 1.4 + i) * 0.075 + wFlick * 0.28;
      wp.pivot.rotation.y = wp.side * twitch;
      wp.pivot.rotation.z = wp.side * (Math.cos(elapsed * 5.2 + i) * 0.06 + wFlick * 0.22);
    }

    // Occasional gentle cat eye blink
    cat.blinkTimer -= dt;
    if (cat.blinkTimer <= 0) {
      cat.blinkVal = 1.0;
      cat.blinkTimer = 3.2 + Math.random() * 4.5;
    }
    cat.blinkVal = Math.max(0, cat.blinkVal - dt * 5.5);
    const eyeScaleY = 1.0 - Math.sin(cat.blinkVal * Math.PI) * 0.88;
    for (const ep of cat.eyePivots) {
      ep.scale.y = eyeScaleY;
    }

    // Shed delicate glowing embers behind the flying lantern cats
    cat.sparkTimer += dt;
    if (cat.sparkTimer >= 0.065) {
      cat.sparkTimer = 0;
      const midSeg = cat.bodySegments[Math.floor(Math.random() * cat.bodySegments.length)];
      spawnTrailSpark(midSeg.pos, cat.isOrange);
      if (cat.tailFlick > 0.2) {
        spawnTrailSpark(cat.tailSegments[cat.tailSegments.length - 1].pos, cat.isOrange);
      }
    }
  }

  // --- 5. HARD INTER-CAT SEPARATION + DISTANCE RELAXATION PASS ---
  enforceInterCatSeparation(catOrange, catSilver);

  for (let i = 0; i < cats.length; i++) {
    const cat = cats[i];
    // Re-enforce environment & exact segment spacing so nothing stretches or clips
    enforceEnvironmentCollision(cat.headPos, 1.05);
    for (let iter = 0; iter < 2; iter++) {
      let prev = cat.headPos;
      for (let si = 0; si < cat.bodySegments.length; si++) {
        const seg = cat.bodySegments[si];
        _tmpV1.subVectors(seg.pos, prev);
        const d = _tmpV1.length();
        if (d > 0.0001) {
          seg.pos.copy(prev).addScaledVector(_tmpV1, seg.spacing / d);
        }
        enforceEnvironmentCollision(seg.pos, seg.radius);
        prev = seg.pos;
      }
      for (let ti = 0; ti < cat.tailSegments.length; ti++) {
        const tSeg = cat.tailSegments[ti];
        _tmpV1.subVectors(tSeg.pos, prev);
        const d = _tmpV1.length();
        if (d > 0.0001) {
          tSeg.pos.copy(prev).addScaledVector(_tmpV1, tSeg.spacing / d);
        }
        enforceEnvironmentCollision(tSeg.pos, tSeg.radius);
        prev = tSeg.pos;
      }
    }

    // --- 6. APPLY TRANSFORMS TO MESH GROUPS (WITH GRACEFUL BANKING ROLL!) ---
    const bankRoll = THREE.MathUtils.clamp(-cat.vel.x * 0.025, -0.32, 0.32);
    const upBanked = _tmpV2.set(Math.sin(bankRoll), Math.cos(bankRoll), 0);
    cat.headGroup.position.copy(cat.headPos);
    orientObjectForward(cat.headGroup, cat.vel, upBanked);

    for (let si = 0; si < cat.bodySegments.length; si++) {
      const seg = cat.bodySegments[si];
      const ahead = si === 0 ? cat.headPos : cat.bodySegments[si - 1].pos;
      const behind = si < cat.bodySegments.length - 1 ? cat.bodySegments[si + 1].pos : cat.tailSegments[0].pos;
      _tmpV1.subVectors(ahead, behind);
      seg.group.position.copy(seg.pos);
      orientObjectForward(seg.group, _tmpV1, upBanked);
    }

    for (let ti = 0; ti < cat.tailSegments.length; ti++) {
      const tSeg = cat.tailSegments[ti];
      const ahead = ti === 0 ? cat.bodySegments[cat.bodySegments.length - 1].pos : cat.tailSegments[ti - 1].pos;
      const behind = ti < cat.tailSegments.length - 1 ? cat.tailSegments[ti + 1].pos : null;
      if (behind) _tmpV1.subVectors(ahead, behind);
      else _tmpV1.subVectors(ahead, tSeg.pos);
      tSeg.group.position.copy(tSeg.pos);
      orientObjectForward(tSeg.group, _tmpV1, upBanked);
    }
  }

  // Feed cat head positions to water shader for low-swoop expanding ripples
  waterUniforms.uCatPos0.value.copy(catOrange.headPos);
  waterUniforms.uCatPos1.value.copy(catSilver.headPos);
}

// ============================================================================
// AMBIENT ANIMATION: FLOATING LANTERNS, SPARKS, FESTOON SWAY, WILLOWS & BOAT
// ============================================================================
function updateEnvironment(dt, elapsed) {
  // 1. Floating Sky Lanterns rising steadily into the starry sky
  for (let i = 0; i < SKY_LANTERN_COUNT; i++) {
    const it = skyLanterns[i];
    it.y += it.vy * dt;
    it.z += it.driftZ * dt;
    if (it.y > 54.0) {
      resetSkyLantern(it, false);
    }
    const swayX = Math.sin(elapsed * it.swayFreq + it.phase) * it.swayAmp;
    const swayZ = Math.cos(elapsed * it.swayFreq * 0.8 + it.phase) * it.swayAmp * 0.6;
    const px = it.x + swayX;
    const pz = it.z + swayZ;

    // Gentle scale-in at launch & scale-out high in sky
    const fadeIn = THREE.MathUtils.smoothstep(it.y, 3.0, 6.2);
    const fadeOut = 1.0 - THREE.MathUtils.smoothstep(it.y, 44.0, 54.0);
    const sc = it.scale * fadeIn * fadeOut;

    dummyObj.position.set(px, it.y, pz);
    dummyObj.rotation.set(
      Math.sin(elapsed * 0.9 + it.phase) * 0.08,
      elapsed * 0.25 + it.phase,
      Math.cos(elapsed * 0.8 + it.phase) * 0.08
    );
    dummyObj.scale.setScalar(Math.max(0.001, sc));
    dummyObj.updateMatrix();
    skyLanternInstanced.setMatrixAt(i, dummyObj.matrix);

    skyLanternFlamePos[i * 3] = px;
    skyLanternFlamePos[i * 3 + 1] = it.y + 0.22 * sc;
    skyLanternFlamePos[i * 3 + 2] = pz;
  }
  skyLanternInstanced.instanceMatrix.needsUpdate = true;
  skyLanternHaloGeo.attributes.position.needsUpdate = true;

  // 2. Gentle breeze sway on festoon light string lanterns
  for (let i = 0; i < festoonLanternData.length; i++) {
    const d = festoonLanternData[i];
    const sway = Math.sin(elapsed * 1.45 + d.phase) * 0.24 * d.sagFactor;
    const px = d.basePos.x + sway * 0.35;
    const py = d.basePos.y + Math.cos(elapsed * 1.45 + d.phase) * 0.05 * d.sagFactor;
    const pz = d.basePos.z + sway;

    dummyObj.position.set(px, py, pz);
    dummyObj.rotation.set(0, 0, sway * 0.3);
    dummyObj.scale.setScalar(1.0);
    dummyObj.updateMatrix();
    festoonInstanced.setMatrixAt(i, dummyObj.matrix);

    festoonHaloPos[i * 3] = px;
    festoonHaloPos[i * 3 + 1] = py;
    festoonHaloPos[i * 3 + 2] = pz;
  }
  festoonInstanced.instanceMatrix.needsUpdate = true;
  festoonHaloGeo.attributes.position.needsUpdate = true;

  // 3. Ambient drifting festival sparks
  for (let i = 0; i < AMBIENT_SPARKS; i++) {
    const v = sparkVel[i];
    const ph = sparkPhase[i];
    let x = sparkPos[i * 3] + (v.vx + Math.sin(elapsed * 0.9 + ph) * 0.65) * dt;
    let y = sparkPos[i * 3 + 1] + v.vy * dt;
    let z = sparkPos[i * 3 + 2] + (v.vz + Math.cos(elapsed * 0.75 + ph) * 0.55) * dt;
    if (y > 32.0) {
      y = 0.9 + Math.random() * 3.0;
      z = -60 + Math.random() * 98;
      x = riverCenterX(z) + (Math.random() - 0.5) * 52;
    }
    sparkPos[i * 3] = x;
    sparkPos[i * 3 + 1] = y;
    sparkPos[i * 3 + 2] = z;
  }
  sparkGeo.attributes.position.needsUpdate = true;

  // 4. Cat ember trail sparks
  for (let i = 0; i < TRAIL_SPARKS; i++) {
    if (tSparkLife[i] <= 0) continue;
    tSparkLife[i] = Math.max(0, tSparkLife[i] - dt * 0.58);
    tSparkPos[i * 3] += tSparkVel[i * 3] * dt;
    tSparkPos[i * 3 + 1] += tSparkVel[i * 3 + 1] * dt;
    tSparkPos[i * 3 + 2] += tSparkVel[i * 3 + 2] * dt;
    tSparkVel[i * 3] *= 0.985;
    tSparkVel[i * 3 + 2] *= 0.985;
  }
  tSparkGeo.attributes.position.needsUpdate = true;
  tSparkGeo.attributes.aLife.needsUpdate = true;

  // 5. Willow canopies & wooden boat gentle bobbing
  for (let i = 0; i < willowCanopies.length; i++) {
    const w = willowCanopies[i];
    w.grp.rotation.z = Math.sin(elapsed * 1.15 + w.phase) * 0.05;
    w.grp.rotation.x = Math.cos(elapsed * 0.92 + w.phase) * 0.04;
  }
  boatGroup.position.y = 0.17 + Math.sin(elapsed * 1.6) * 0.06;
  boatGroup.rotation.z = Math.sin(elapsed * 1.3) * 0.045;
  boatGroup.rotation.x = Math.cos(elapsed * 1.1) * 0.03;
}

// ============================================================================
// RESIZE HANDLER
// ============================================================================
function handleResize() {
  const w = window.innerWidth || 1280;
  const h = window.innerHeight || 720;
  const dpr = getDpr();

  renderer.setPixelRatio(dpr);
  renderer.setSize(w, h, false);

  mainCamera.fov = computeFov(w, h);
  mainCamera.aspect = w / Math.max(1, h);
  mainCamera.updateProjectionMatrix();

  reflectCamera.fov = mainCamera.fov;
  reflectCamera.aspect = mainCamera.aspect;
  reflectCamera.updateProjectionMatrix();

  const { rw, rh } = createReflectSize(w, h);
  reflectRT.setSize(rw, rh);

  starUniforms.uPixelRatio.value = dpr;
  festoonHaloUniforms.uPixelRatio.value = dpr;
  skyLanternHaloUniforms.uPixelRatio.value = dpr;
  sparkUniforms.uPixelRatio.value = dpr;
  tSparkUniforms.uPixelRatio.value = dpr;
}
window.addEventListener('resize', handleResize);

// ============================================================================
// MAIN ANIMATION LOOP (DUAL-PASS PLANAR RIVER REFLECTION + MAIN RENDER)
// ============================================================================
const clock = new THREE.Clock();
let elapsed = 0;

// Warm up one tick so initial cat segment transforms are placed before Frame 1 renders
updateCats(0.016, 0.016);
updateEnvironment(0.016, 0.016);
updateCamera(0.016);

function animate() {
  requestAnimationFrame(animate);

  const dt = Math.min(clock.getDelta(), 0.05);
  elapsed += dt;
  if (demoMode) {
    demoTime = (demoTime + dt) % DEMO_DURATION;
  }

  // Update shader clocks
  skyUniforms.uTime.value = elapsed;
  starUniforms.uTime.value = elapsed;
  waterUniforms.uTime.value = elapsed;
  skyLanternHaloUniforms.uTime.value = elapsed;
  sparkUniforms.uTime.value = elapsed;
  for (let i = 0; i < catMaterialsToTick.length; i++) {
    catMaterialsToTick[i].uniforms.uTime.value = elapsed;
  }

  // Step simulation & cinematic camera
  updateCats(dt, elapsed);
  updateEnvironment(dt, elapsed);
  updateCamera(dt);

  // --- PASS 1: RENDER LIVE PLANAR RIVER REFLECTION ---
  // Mirror camera across y = WATER_Y (0.0); all scene geometry sits at y >= 0!
  waterMesh.visible = false;
  reflectCamera.position.set(mainCamera.position.x, -mainCamera.position.y, mainCamera.position.z);
  reflectCamera.up.set(0, 1, 0);
  reflectCamera.lookAt(camLookSmooth.x, -camLookSmooth.y, camLookSmooth.z);
  reflectCamera.updateMatrixWorld();

  renderer.setRenderTarget(reflectRT);
  renderer.clear();
  renderer.render(scene, reflectCamera);

  // --- PASS 2: RENDER MAIN FESTIVAL NIGHT SCENE ---
  waterMesh.visible = true;
  renderer.setRenderTarget(null);
  renderer.render(scene, mainCamera);
}

animate();
</script>
</body>
</html>