Skip to content
VibeCodeBench
Back to the app

The code

Cat Island by Gemini 4 Hydrogen

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.)99.0 KB · 2,868 lines · loads cdn.jsdelivr.net/npm/[email protected]/build/three.min.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, viewport-fit=cover">
<title>Whisker Isle — Pixel Cat Town</title>
<style>
  :root {
    --px-bg: rgba(31, 25, 42, 0.86);
    --px-bg-solid: #231d30;
    --px-border: #120d1a;
    --px-highlight: #574870;
    --px-text: #fff7e6;
    --px-muted: #c8bdd6;
    --px-gold: #ffcf54;
    --px-gold-dark: #c78b22;
    --px-sunset: #ff8a5c;
    --px-night: #7ea8ff;
    --px-day: #6fd3ff;
  }

  * {
    box-sizing: border-box;
    -webkit-tap-highlight-color: transparent;
  }

  html, body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    background: #1a243d;
    user-select: none;
    -webkit-user-select: none;
    touch-action: none;
    font-family: 'Courier New', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
    color: var(--px-text);
  }

  #view {
    position: fixed;
    inset: 0;
    width: 100%;
    height: 100%;
    display: block;
    image-rendering: pixelated;
    image-rendering: crisp-edges;
    touch-action: none;
    cursor: grab;
  }

  #view:active {
    cursor: grabbing;
  }

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

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

  .px-card {
    pointer-events: auto;
    background: var(--px-bg);
    border: 3px solid var(--px-border);
    box-shadow:
      inset 0 2px 0 rgba(255, 255, 255, 0.14),
      0 4px 0 var(--px-border);
    padding: 8px 12px;
    border-radius: 4px;
    display: inline-flex;
    align-items: center;
    gap: 8px;
  }

  .brand {
    font-weight: 700;
    font-size: 14px;
    letter-spacing: 0.5px;
    text-shadow: 2px 2px 0 var(--px-border);
    white-space: nowrap;
  }

  .brand small {
    display: block;
    font-size: 11px;
    font-weight: 400;
    color: var(--px-muted);
    margin-top: 2px;
  }

  .top-actions {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .demo-pill {
    pointer-events: auto;
    background: #3b2a54;
    border: 3px solid var(--px-border);
    box-shadow: 0 4px 0 var(--px-border);
    color: var(--px-gold);
    font-size: 11px;
    font-weight: 700;
    letter-spacing: 0.6px;
    padding: 8px 10px;
    border-radius: 4px;
    text-shadow: 1px 1px 0 var(--px-border);
    animation: pulseDemo 1.8s ease-in-out infinite;
    display: none;
  }

  .demo-pill.active {
    display: inline-flex;
    align-items: center;
    gap: 6px;
  }

  @keyframes pulseDemo {
    0%, 100% { transform: translateY(0); }
    50% { transform: translateY(-2px); }
  }

  .icon-btn {
    pointer-events: auto;
    min-width: 44px;
    min-height: 44px;
    padding: 0 10px;
    background: var(--px-bg);
    border: 3px solid var(--px-border);
    box-shadow:
      inset 0 2px 0 rgba(255, 255, 255, 0.14),
      0 4px 0 var(--px-border);
    border-radius: 4px;
    color: var(--px-text);
    font-family: inherit;
    font-size: 16px;
    font-weight: 700;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    justify-content: center;
  }

  .icon-btn:active {
    transform: translateY(2px);
    box-shadow: inset 0 2px 0 rgba(255, 255, 255, 0.1), 0 2px 0 var(--px-border);
  }

  .bottom-stack {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
  }

  .follow-bar {
    pointer-events: auto;
    background: var(--px-bg);
    border: 3px solid var(--px-border);
    box-shadow:
      inset 0 2px 0 rgba(255, 255, 255, 0.14),
      0 4px 0 var(--px-border);
    border-radius: 4px;
    padding: 6px 10px;
    display: inline-flex;
    align-items: center;
    gap: 10px;
    max-width: min(94vw, 460px);
    font-size: 12px;
    line-height: 1.25;
  }

  .follow-bar.idle {
    pointer-events: none;
    color: var(--px-muted);
    padding: 6px 12px;
    font-size: 11px;
  }

  .cat-swatch {
    width: 18px;
    height: 18px;
    border: 2px solid var(--px-border);
    border-radius: 2px;
    flex-shrink: 0;
  }

  .follow-meta {
    display: flex;
    flex-direction: column;
    min-width: 0;
  }

  .follow-name {
    font-weight: 700;
    font-size: 13px;
    color: var(--px-gold);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .follow-state {
    font-size: 11px;
    color: var(--px-text);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .unfollow-btn {
    pointer-events: auto;
    min-height: 44px;
    padding: 0 12px;
    background: #4d3d68;
    border: 3px solid var(--px-border);
    box-shadow: inset 0 2px 0 rgba(255, 255, 255, 0.16), 0 3px 0 var(--px-border);
    border-radius: 4px;
    color: var(--px-text);
    font-family: inherit;
    font-size: 12px;
    font-weight: 700;
    cursor: pointer;
    flex-shrink: 0;
  }

  .unfollow-btn:active {
    transform: translateY(2px);
    box-shadow: 0 1px 0 var(--px-border);
  }

  .time-bar {
    pointer-events: auto;
    display: inline-flex;
    gap: 8px;
    background: rgba(18, 13, 26, 0.72);
    padding: 6px;
    border-radius: 6px;
    border: 3px solid var(--px-border);
    box-shadow: 0 4px 0 var(--px-border);
  }

  .time-btn {
    min-height: 46px;
    min-width: 92px;
    padding: 8px 14px;
    border: 3px solid var(--px-border);
    border-radius: 4px;
    background: #332a47;
    color: var(--px-text);
    font-family: inherit;
    font-size: 14px;
    font-weight: 700;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    box-shadow:
      inset 0 2px 0 rgba(255, 255, 255, 0.14),
      0 4px 0 var(--px-border);
    text-shadow: 1px 1px 0 var(--px-border);
    transition: background-color 0.15s ease, transform 0.08s ease;
  }

  .time-btn:active {
    transform: translateY(2px);
    box-shadow: 0 2px 0 var(--px-border);
  }

  .time-btn.active[data-time="day"] {
    background: #3580c2;
    color: #fffbe6;
    box-shadow: inset 0 2px 0 #8bd6ff, 0 2px 0 var(--px-border);
    transform: translateY(2px);
  }

  .time-btn.active[data-time="sunset"] {
    background: #cf5c42;
    color: #fff5df;
    box-shadow: inset 0 2px 0 #ffbd87, 0 2px 0 var(--px-border);
    transform: translateY(2px);
  }

  .time-btn.active[data-time="night"] {
    background: #3a4285;
    color: #ffe999;
    box-shadow: inset 0 2px 0 #8aa0ff, 0 2px 0 var(--px-border);
    transform: translateY(2px);
  }

  #fallback {
    position: fixed;
    inset: 0;
    display: none;
    align-items: center;
    justify-content: center;
    padding: 24px;
    text-align: center;
    background: #1d2238;
    color: #fff7e6;
    z-index: 50;
  }

  @media (max-width: 520px) {
    .brand {
      font-size: 13px;
    }
    .brand small {
      display: none;
    }
    .time-bar {
      gap: 6px;
      padding: 5px;
    }
    .time-btn {
      min-width: 80px;
      padding: 8px 10px;
      font-size: 13px;
    }
  }
</style>
</head>
<body>
<canvas id="view"></canvas>

<div class="hud">
  <div class="top-row">
    <div class="px-card">
      <div class="brand">
        🐾 Whisker Isle
        <small>Cat-Run Floating Town</small>
      </div>
    </div>
    <div class="top-actions">
      <div id="demo-pill" class="demo-pill">🎬 AUTO TOUR · TAP TO EXIT</div>
      <button id="btn-sound" class="icon-btn" type="button" aria-label="Toggle Sound" title="Toggle Sound">🔇</button>
    </div>
  </div>

  <div class="bottom-stack">
    <div id="follow-bar" class="follow-bar idle">
      Drag to spin · Pinch/scroll to zoom · Tap a cat to follow
    </div>
    <div class="time-bar" role="group" aria-label="Time of day">
      <button class="time-btn active" type="button" data-time="day">☀ Day</button>
      <button class="time-btn" type="button" data-time="sunset">🌅 Sunset</button>
      <button class="time-btn" type="button" data-time="night">🌙 Night</button>
    </div>
  </div>
</div>

<div id="fallback">
  <div class="px-card" style="flex-direction:column;max-width:340px;">
    <strong>Unable to load 3D engine</strong>
    <span style="font-size:12px;color:#c8bdd6;">Please check connection to cdn.jsdelivr.net for Three.js and reload.</span>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/three.min.js"></script>
<script>
(function () {
  'use strict';

  if (typeof THREE === 'undefined') {
    document.getElementById('fallback').style.display = 'flex';
    return;
  }

  /* =========================
     1. TINY PIXEL SOUND SYNTH
     ========================= */
  var audioCtx = null;
  var soundEnabled = false;
  var btnSound = document.getElementById('btn-sound');

  function ensureAudio() {
    if (!soundEnabled) return null;
    try {
      if (!audioCtx) {
        var Ctx = window.AudioContext || window.webkitAudioContext;
        if (Ctx) audioCtx = new Ctx();
      }
      if (audioCtx && audioCtx.state === 'suspended') {
        audioCtx.resume();
      }
      return audioCtx;
    } catch (e) {
      return null;
    }
  }

  function playTone(freqStart, freqEnd, duration, type, gainVal) {
    var ctx = ensureAudio();
    if (!ctx) return;
    try {
      var now = ctx.currentTime;
      var osc = ctx.createOscillator();
      var g = ctx.createGain();
      osc.type = type || 'triangle';
      osc.frequency.setValueAtTime(freqStart, now);
      osc.frequency.exponentialRampToValueAtTime(Math.max(40, freqEnd), now + duration);
      g.gain.setValueAtTime(gainVal || 0.06, now);
      g.gain.exponentialRampToValueAtTime(0.001, now + duration);
      osc.connect(g);
      g.connect(ctx.destination);
      osc.start(now);
      osc.stop(now + duration + 0.02);
    } catch (e) {}
  }

  function playMeow(pitch) {
    var p = pitch || 520;
    playTone(p * 0.85, p * 1.28, 0.11, 'triangle', 0.065);
    setTimeout(function () {
      playTone(p * 1.24, p * 0.88, 0.15, 'triangle', 0.05);
    }, 90);
  }

  function playChime(mode) {
    if (mode === 'day') playTone(523, 784, 0.16, 'sine', 0.05);
    else if (mode === 'sunset') playTone(440, 587, 0.2, 'sine', 0.05);
    else playTone(392, 294, 0.24, 'sine', 0.05);
  }

  btnSound.addEventListener('click', function () {
    soundEnabled = !soundEnabled;
    btnSound.textContent = soundEnabled ? '🔊' : '🔇';
    if (soundEnabled) playMeow(580);
  });

  /* =========================
     2. SCENE & RENDERER SETUP
     ========================= */
  var canvas = document.getElementById('view');
  var renderer = new THREE.WebGLRenderer({
    canvas: canvas,
    antialias: false,
    powerPreference: 'high-performance'
  });
  renderer.shadowMap.enabled = true;
  renderer.shadowMap.type = THREE.BasicShadowMap;
  renderer.setPixelRatio(1);

  var scene = new THREE.Scene();
  scene.fog = new THREE.FogExp2(0x9bd7ff, 0.012);

  var camera = new THREE.PerspectiveCamera(38, 1, 0.3, 180);

  function handleResize() {
    var w = window.innerWidth || 640;
    var h = window.innerHeight || 480;
    var minDim = Math.min(w, h);
    var pxScale = minDim >= 980 ? 3 : (minDim >= 460 ? 2 : 1);
    var rw = Math.max(180, Math.floor(w / pxScale));
    var rh = Math.max(180, Math.floor(h / pxScale));
    renderer.setSize(rw, rh, false);
    camera.aspect = w / h;
    camera.fov = (w / h) < 0.85 ? 46 : 38;
    camera.updateProjectionMatrix();
  }
  handleResize();
  window.addEventListener('resize', handleResize);

  /* =========================
     3. PIXEL-ART TEXTURES
     ========================= */
  function createPixelCanvas(w, h, drawFn) {
    var c = document.createElement('canvas');
    c.width = w;
    c.height = h;
    var ctx = c.getContext('2d');
    ctx.imageSmoothingEnabled = false;
    drawFn(ctx, w, h);
    var tex = new THREE.CanvasTexture(c);
    tex.magFilter = THREE.NearestFilter;
    tex.minFilter = THREE.NearestFilter;
    tex.generateMipmaps = false;
    tex.needsUpdate = true;
    return tex;
  }

  function cloneTiledTex(baseTex, rx, ry) {
    var t = baseTex.clone();
    t.wrapS = THREE.RepeatWrapping;
    t.wrapT = THREE.RepeatWrapping;
    t.repeat.set(rx, ry);
    t.magFilter = THREE.NearestFilter;
    t.minFilter = THREE.NearestFilter;
    t.generateMipmaps = false;
    t.needsUpdate = true;
    return t;
  }

  function seededRand(seed) {
    var s = seed % 2147483647;
    if (s <= 0) s += 2147483646;
    return function () {
      s = (s * 16807) % 2147483647;
      return (s - 1) / 2147483646;
    };
  }

  var TEX = {};

  TEX.grassTop = createPixelCanvas(16, 16, function (ctx) {
    var r = seededRand(11);
    var cols = ['#66b948', '#5eab41', '#74c652', '#7fd15b', '#579f3c'];
    for (var y = 0; y < 16; y++) {
      for (var x = 0; x < 16; x++) {
        ctx.fillStyle = cols[Math.floor(r() * cols.length)];
        ctx.fillRect(x, y, 1, 1);
      }
    }
    ctx.fillStyle = '#97e36e';
    ctx.fillRect(3, 4, 1, 1);
    ctx.fillRect(11, 12, 1, 1);
    ctx.fillRect(7, 2, 1, 1);
  });

  TEX.grassSide = createPixelCanvas(16, 16, function (ctx) {
    var r = seededRand(23);
    var dirt = ['#8a5738', '#794a2e', '#996543', '#6c4128'];
    for (var y = 0; y < 16; y++) {
      for (var x = 0; x < 16; x++) {
        ctx.fillStyle = dirt[Math.floor(r() * dirt.length)];
        ctx.fillRect(x, y, 1, 1);
      }
    }
    var drip = [4, 5, 3, 4, 6, 4, 3, 5, 4, 3, 4, 6, 5, 3, 4, 5];
    for (var x2 = 0; x2 < 16; x2++) {
      for (var y2 = 0; y2 < drip[x2]; y2++) {
        ctx.fillStyle = y2 === drip[x2] - 1 ? '#4d9335' : (y2 < 2 ? '#6ec44d' : '#5cae3f');
        ctx.fillRect(x2, y2, 1, 1);
      }
    }
  });

  TEX.cliffRock = createPixelCanvas(16, 16, function (ctx) {
    var r = seededRand(37);
    var stones = ['#797884', '#696874', '#8b8a96', '#5a5964'];
    for (var y = 0; y < 16; y++) {
      for (var x = 0; x < 16; x++) {
        ctx.fillStyle = stones[Math.floor(r() * stones.length)];
        ctx.fillRect(x, y, 1, 1);
      }
    }
    ctx.fillStyle = '#53525d';
    ctx.fillRect(0, 5, 16, 1);
    ctx.fillRect(0, 12, 16, 1);
    ctx.fillRect(6, 0, 1, 6);
    ctx.fillRect(11, 6, 1, 6);
  });

  TEX.cobble = createPixelCanvas(16, 16, function (ctx) {
    ctx.fillStyle = '#827a72';
    ctx.fillRect(0, 0, 16, 16);
    var pavers = [
      [1, 1, 6, 6, '#c2b9aa'], [8, 1, 7, 5, '#b4ab9c'],
      [1, 8, 5, 7, '#afa697'], [7, 7, 8, 8, '#c7beb0'],
      [2, 2, 4, 4, '#d1c8ba'], [9, 8, 5, 5, '#d4cbbd']
    ];
    for (var i = 0; i < pavers.length; i++) {
      var p = pavers[i];
      ctx.fillStyle = p[4];
      ctx.fillRect(p[0], p[1], p[2], p[3]);
    }
  });

  TEX.pawCobble = createPixelCanvas(16, 16, function (ctx) {
    ctx.fillStyle = '#bcb3a4';
    ctx.fillRect(0, 0, 16, 16);
    ctx.fillStyle = '#999082';
    ctx.fillRect(0, 0, 16, 1);
    ctx.fillRect(0, 0, 1, 16);
    // Cute pixel paw print mosaic
    ctx.fillStyle = '#7b7166';
    ctx.fillRect(5, 8, 6, 5);
    ctx.fillRect(6, 7, 4, 1);
    ctx.fillRect(3, 5, 2, 2);
    ctx.fillRect(6, 3, 2, 3);
    ctx.fillRect(9, 3, 2, 3);
    ctx.fillRect(11, 5, 2, 2);
  });

  TEX.sand = createPixelCanvas(16, 16, function (ctx) {
    var r = seededRand(55);
    var cols = ['#dfd0a1', '#d4c392', '#e8dab0', '#c7b584'];
    for (var y = 0; y < 16; y++) {
      for (var x = 0; x < 16; x++) {
        ctx.fillStyle = cols[Math.floor(r() * cols.length)];
        ctx.fillRect(x, y, 1, 1);
      }
    }
  });

  TEX.wood = createPixelCanvas(16, 16, function (ctx) {
    var r = seededRand(61);
    var cols = ['#9f693e', '#925f36', '#ad7447', '#83542f'];
    for (var y = 0; y < 16; y++) {
      for (var x = 0; x < 16; x++) {
        ctx.fillStyle = (y % 4 === 0) ? '#6e4526' : cols[Math.floor(r() * cols.length)];
        ctx.fillRect(x, y, 1, 1);
      }
    }
  });

  TEX.bark = createPixelCanvas(16, 16, function (ctx) {
    var r = seededRand(71);
    var cols = ['#6d452c', '#5c3923', '#7c5136'];
    for (var y = 0; y < 16; y++) {
      for (var x = 0; x < 16; x++) {
        ctx.fillStyle = (x % 4 === 0 && r() > 0.35) ? '#492c1a' : cols[Math.floor(r() * cols.length)];
        ctx.fillRect(x, y, 1, 1);
      }
    }
  });

  TEX.leavesGreen = createPixelCanvas(16, 16, function (ctx) {
    var r = seededRand(83);
    var cols = ['#4a9e42', '#3d8937', '#5cb34d', '#6cc458'];
    for (var y = 0; y < 16; y++) {
      for (var x = 0; x < 16; x++) {
        ctx.fillStyle = cols[Math.floor(r() * cols.length)];
        ctx.fillRect(x, y, 1, 1);
      }
    }
  });

  TEX.leavesPink = createPixelCanvas(16, 16, function (ctx) {
    var r = seededRand(97);
    var cols = ['#f49ab6', '#e782a4', '#ffb7ce', '#ffd5e3'];
    for (var y = 0; y < 16; y++) {
      for (var x = 0; x < 16; x++) {
        ctx.fillStyle = cols[Math.floor(r() * cols.length)];
        ctx.fillRect(x, y, 1, 1);
      }
    }
  });

  TEX.water = createPixelCanvas(16, 16, function (ctx) {
    ctx.fillStyle = '#39a7cc';
    ctx.fillRect(0, 0, 16, 16);
    ctx.fillStyle = '#4bbce0';
    ctx.fillRect(1, 2, 5, 1);
    ctx.fillRect(9, 6, 5, 1);
    ctx.fillRect(3, 11, 6, 1);
    ctx.fillRect(11, 14, 4, 1);
    ctx.fillStyle = '#8ae6f8';
    ctx.fillRect(2, 2, 2, 1);
    ctx.fillRect(10, 6, 2, 1);
    ctx.fillRect(5, 11, 2, 1);
  });

  function makeRoofTex(c1, c2, c3) {
    return createPixelCanvas(16, 16, function (ctx) {
      for (var y = 0; y < 16; y++) {
        var row = Math.floor(y / 4);
        var off = (row % 2) * 2;
        for (var x = 0; x < 16; x++) {
          var edge = (y % 4 === 3) || ((x + off) % 4 === 0);
          ctx.fillStyle = edge ? c3 : ((x + y) % 5 === 0 ? c2 : c1);
          ctx.fillRect(x, y, 1, 1);
        }
      }
    });
  }

  TEX.roofTerra = makeRoofTex('#d4603a', '#e3734b', '#ab4223');
  TEX.roofSlate = makeRoofTex('#4b6d91', '#5c81a6', '#354f6c');
  TEX.roofHoney = makeRoofTex('#d99b38', '#e8ac48', '#b07822');

  function makeWallTex(base, shade, trim) {
    return createPixelCanvas(16, 16, function (ctx) {
      var r = seededRand(109);
      for (var y = 0; y < 16; y++) {
        for (var x = 0; x < 16; x++) {
          ctx.fillStyle = r() > 0.85 ? shade : base;
          ctx.fillRect(x, y, 1, 1);
        }
      }
      ctx.fillStyle = trim;
      ctx.fillRect(0, 0, 16, 2);
      ctx.fillRect(0, 14, 16, 2);
      ctx.fillRect(0, 0, 2, 16);
      ctx.fillRect(14, 0, 2, 16);
    });
  }

  TEX.wallCream = makeWallTex('#f6ebd8', '#eadcc4', '#865735');
  TEX.wallButter = makeWallTex('#f7e09e', '#ecd084', '#7a4e2d');
  TEX.wallSky = makeWallTex('#d9ece2', '#c8ded3', '#5c726d');

  function makeAwningTex(stripeA, stripeB) {
    return createPixelCanvas(16, 16, function (ctx) {
      for (var x = 0; x < 16; x++) {
        var isA = Math.floor(x / 4) % 2 === 0;
        ctx.fillStyle = isA ? stripeA : stripeB;
        ctx.fillRect(x, 0, 1, 16);
      }
      ctx.fillStyle = 'rgba(0,0,0,0.16)';
      ctx.fillRect(0, 13, 16, 3);
    });
  }

  TEX.awningRed = makeAwningTex('#e54944', '#fff5e1');
  TEX.awningBlue = makeAwningTex('#338ec9', '#fff5e1');

  TEX.windowDay = createPixelCanvas(16, 16, function (ctx) {
    ctx.fillStyle = '#5c3923';
    ctx.fillRect(0, 0, 16, 16);
    ctx.fillStyle = '#7fb5cf';
    ctx.fillRect(2, 2, 5, 5);
    ctx.fillRect(9, 2, 5, 5);
    ctx.fillRect(2, 9, 5, 5);
    ctx.fillRect(9, 9, 5, 5);
    ctx.fillStyle = '#b4e1f5';
    ctx.fillRect(3, 3, 2, 2);
    ctx.fillRect(10, 3, 2, 2);
    ctx.fillRect(3, 10, 2, 1);
  });

  TEX.windowGlow = createPixelCanvas(16, 16, function (ctx) {
    ctx.fillStyle = '#000000';
    ctx.fillRect(0, 0, 16, 16);
    ctx.fillStyle = '#ffe585';
    ctx.fillRect(2, 2, 5, 5);
    ctx.fillRect(9, 2, 5, 5);
    ctx.fillRect(2, 9, 5, 5);
    ctx.fillRect(9, 9, 5, 5);
    ctx.fillStyle = '#ffffff';
    ctx.fillRect(3, 3, 3, 3);
    ctx.fillRect(10, 3, 3, 3);
    ctx.fillRect(3, 10, 3, 3);
    ctx.fillRect(10, 10, 3, 3);
  });

  TEX.door = createPixelCanvas(16, 16, function (ctx) {
    ctx.fillStyle = '#6d4124';
    ctx.fillRect(0, 0, 16, 16);
    ctx.fillStyle = '#8c5532';
    ctx.fillRect(2, 2, 12, 14);
    ctx.fillStyle = '#59331a';
    ctx.fillRect(7, 2, 2, 14);
    ctx.fillStyle = '#ffcf54';
    ctx.fillRect(5, 8, 2, 2);
    ctx.fillRect(9, 8, 2, 2);
  });

  TEX.yarnBase = createPixelCanvas(16, 16, function (ctx) {
    ctx.fillStyle = '#ececec';
    ctx.fillRect(0, 0, 16, 16);
    for (var i = 0; i < 16; i++) {
      ctx.fillStyle = '#c8c8c8';
      ctx.fillRect(i, (i * 2) % 16, 2, 1);
      ctx.fillRect((15 - i), (i * 2 + 5) % 16, 2, 1);
      ctx.fillStyle = '#ffffff';
      ctx.fillRect(i, (i * 2 + 1) % 16, 1, 1);
      ctx.fillRect((15 - i), (i * 2 + 6) % 16, 1, 1);
      ctx.fillStyle = '#a8a8a8';
      ctx.fillRect((i + 4) % 16, (i + 2) % 16, 1, 1);
    }
  });

  TEX.fishCrate = createPixelCanvas(16, 16, function (ctx) {
    ctx.fillStyle = '#734a2b';
    ctx.fillRect(0, 0, 16, 16);
    ctx.fillStyle = '#b9e3f5';
    ctx.fillRect(2, 2, 12, 12);
    // Silver, blue, coral pixel fish packed on ice
    ctx.fillStyle = '#5da8d9';
    ctx.fillRect(3, 4, 6, 3);
    ctx.fillRect(9, 3, 2, 5);
    ctx.fillStyle = '#ff8a54';
    ctx.fillRect(5, 9, 6, 3);
    ctx.fillRect(3, 8, 2, 5);
    ctx.fillStyle = '#eef8ff';
    ctx.fillRect(4, 5, 2, 1);
    ctx.fillRect(8, 10, 2, 1);
  });

  TEX.fishSign = createPixelCanvas(16, 16, function (ctx) {
    ctx.fillStyle = '#316a99';
    ctx.fillRect(0, 0, 16, 16);
    ctx.fillStyle = '#fff3d6';
    ctx.fillRect(1, 1, 14, 1);
    ctx.fillRect(1, 14, 14, 1);
    ctx.fillRect(1, 1, 1, 14);
    ctx.fillRect(14, 1, 1, 14);
    // Pixel fish icon
    ctx.fillStyle = '#ffcf54';
    ctx.fillRect(5, 6, 6, 4);
    ctx.fillRect(4, 7, 1, 2);
    ctx.fillRect(11, 5, 2, 6);
    ctx.fillStyle = '#1d2d44';
    ctx.fillRect(5, 7, 1, 1);
  });

  TEX.clockFace = createPixelCanvas(16, 16, function (ctx) {
    ctx.fillStyle = '#5c3923';
    ctx.fillRect(0, 0, 16, 16);
    ctx.fillStyle = '#fff6de';
    ctx.fillRect(2, 2, 12, 12);
    ctx.fillStyle = '#241c2c';
    ctx.fillRect(7, 4, 2, 5);
    ctx.fillRect(7, 7, 4, 2);
  });

  // Floating sprite icons
  TEX.iconSleep = createPixelCanvas(16, 16, function (ctx) {
    ctx.fillStyle = '#ffffff';
    ctx.fillRect(3, 3, 6, 2);
    ctx.fillRect(7, 5, 2, 2);
    ctx.fillRect(5, 7, 2, 2);
    ctx.fillRect(3, 9, 6, 2);
    ctx.fillStyle = '#a3d9ff';
    ctx.fillRect(10, 1, 4, 1);
    ctx.fillRect(12, 2, 1, 1);
    ctx.fillRect(10, 3, 4, 1);
  });

  TEX.iconFish = createPixelCanvas(16, 16, function (ctx) {
    ctx.fillStyle = '#62c4ff';
    ctx.fillRect(3, 6, 7, 4);
    ctx.fillRect(2, 7, 1, 2);
    ctx.fillRect(10, 5, 3, 6);
    ctx.fillStyle = '#ffffff';
    ctx.fillRect(4, 7, 1, 1);
    ctx.fillStyle = '#22334d';
    ctx.fillRect(5, 7, 1, 1);
  });

  TEX.iconHeart = createPixelCanvas(16, 16, function (ctx) {
    ctx.fillStyle = '#ff6b8b';
    ctx.fillRect(3, 4, 4, 3);
    ctx.fillRect(9, 4, 4, 3);
    ctx.fillRect(4, 7, 8, 3);
    ctx.fillRect(6, 10, 4, 2);
    ctx.fillRect(7, 12, 2, 1);
    ctx.fillStyle = '#ffb8ca';
    ctx.fillRect(4, 5, 2, 1);
  });

  TEX.iconNote = createPixelCanvas(16, 16, function (ctx) {
    ctx.fillStyle = '#ffdf5e';
    ctx.fillRect(6, 3, 6, 2);
    ctx.fillRect(6, 5, 2, 7);
    ctx.fillRect(10, 5, 2, 6);
    ctx.fillRect(4, 10, 4, 3);
    ctx.fillRect(8, 9, 4, 3);
  });

  /* =========================
     4. SKY DOME & LIGHTING
     ========================= */
  var skyUniforms = {
    uTop: { value: new THREE.Color(0x3a8be0) },
    uMid: { value: new THREE.Color(0x6ebdf7) },
    uHoriz: { value: new THREE.Color(0xc5ecff) },
    uBot: { value: new THREE.Color(0x7cc0ed) },
    uNight: { value: 0.0 },
    uTime: { value: 0.0 }
  };

  var skyMat = new THREE.ShaderMaterial({
    uniforms: skyUniforms,
    side: THREE.BackSide,
    depthWrite: false,
    fog: false,
    vertexShader: [
      'varying vec3 vDir;',
      'void main() {',
      '  vDir = position;',
      '  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
      '}'
    ].join('\n'),
    fragmentShader: [
      'uniform vec3 uTop;',
      'uniform vec3 uMid;',
      'uniform vec3 uHoriz;',
      'uniform vec3 uBot;',
      'uniform float uNight;',
      'uniform float uTime;',
      'varying vec3 vDir;',
      'float hash(vec3 p) {',
      '  p = fract(p * 0.3183099 + 0.1);',
      '  p *= 17.0;',
      '  return fract(p.x * p.y * p.z * (p.x + p.y + p.z));',
      '}',
      'void main() {',
      '  vec3 d = normalize(vDir);',
      '  float y = d.y;',
      '  float qy = floor(y * 34.0) / 34.0;',
      '  vec3 col;',
      '  if (qy >= 0.35) {',
      '    col = mix(uMid, uTop, clamp((qy - 0.35) / 0.65, 0.0, 1.0));',
      '  } else if (qy >= 0.0) {',
      '    col = mix(uHoriz, uMid, clamp(qy / 0.35, 0.0, 1.0));',
      '  } else {',
      '    col = mix(uHoriz, uBot, clamp(-qy / 0.65, 0.0, 1.0));',
      '  }',
      '  if (y > 0.04 && uNight > 0.01) {',
      '    vec3 cell = floor(d * 88.0);',
      '    float h = hash(cell);',
      '    if (h > 0.9915) {',
      '      float tw = 0.55 + 0.45 * sin(uTime * 3.0 + h * 140.0);',
      '      float fade = smoothstep(0.04, 0.25, y);',
      '      vec3 starCol = mix(vec3(0.84, 0.92, 1.0), vec3(1.0, 0.94, 0.7), fract(h * 63.7));',
      '      col = mix(col, starCol, uNight * tw * fade);',
      '    }',
      '  }',
      '  gl_FragColor = vec4(col, 1.0);',
      '}'
    ].join('\n')
  });

  var skyDome = new THREE.Mesh(new THREE.SphereGeometry(95, 24, 16), skyMat);
  scene.add(skyDome);

  // Chunky pixel Sun and Crescent Moon
  var sunGroup = new THREE.Group();
  var sunMat = new THREE.MeshBasicMaterial({ color: 0xffe478, fog: false });
  var sunCore = new THREE.Mesh(new THREE.BoxGeometry(3.2, 3.2, 3.2), sunMat);
  var sunHaloMat = new THREE.MeshBasicMaterial({ color: 0xfff3b5, transparent: true, opacity: 0.45, fog: false });
  var sunHalo = new THREE.Mesh(new THREE.BoxGeometry(4.4, 4.4, 4.4), sunHaloMat);
  sunGroup.add(sunCore, sunHalo);
  scene.add(sunGroup);

  var moonGroup = new THREE.Group();
  var moonMat = new THREE.MeshBasicMaterial({ color: 0xf7f2d0, fog: false });
  var moonCraters = new THREE.MeshBasicMaterial({ color: 0xd8d2aa, fog: false });
  var mMain = new THREE.Mesh(new THREE.BoxGeometry(2.6, 2.6, 2.6), moonMat);
  var mTop = new THREE.Mesh(new THREE.BoxGeometry(1.8, 0.7, 2.2), moonMat);
  mTop.position.set(0.4, 1.3, 0);
  var mBot = new THREE.Mesh(new THREE.BoxGeometry(1.8, 0.7, 2.2), moonMat);
  mBot.position.set(0.4, -1.3, 0);
  var mDet = new THREE.Mesh(new THREE.BoxGeometry(0.9, 0.9, 2.7), moonCraters);
  mDet.position.set(-0.4, 0.3, 0);
  moonGroup.add(mMain, mTop, mBot, mDet);
  scene.add(moonGroup);

  // Lights
  var hemiLight = new THREE.HemisphereLight(0xbbe6ff, 0x5c7c48, 0.85);
  scene.add(hemiLight);

  var dirLight = new THREE.DirectionalLight(0xfff6dd, 1.15);
  dirLight.position.set(14, 22, 12);
  dirLight.castShadow = true;
  dirLight.shadow.mapSize.set(1024, 1024);
  dirLight.shadow.camera.left = -13;
  dirLight.shadow.camera.right = 13;
  dirLight.shadow.camera.top = 13;
  dirLight.shadow.camera.bottom = -13;
  dirLight.shadow.camera.near = 2;
  dirLight.shadow.camera.far = 60;
  dirLight.shadow.bias = -0.0015;
  dirLight.shadow.normalBias = 0.04;
  scene.add(dirLight);

  var nightPointLights = [];
  function addLanternLight(x, y, z) {
    var pl = new THREE.PointLight(0xffad42, 0, 7.8, 1.4);
    pl.position.set(x, y, z);
    scene.add(pl);
    nightPointLights.push(pl);
    return pl;
  }

  /* =========================
     5. ISLAND TERRAIN BUILDER
     ========================= */
  var islandGroup = new THREE.Group();
  scene.add(islandGroup);

  var matGrassTop = new THREE.MeshLambertMaterial({ map: TEX.grassTop });
  var matGrassSide = new THREE.MeshLambertMaterial({ map: TEX.grassSide });
  var matDirt = new THREE.MeshLambertMaterial({ color: 0x7c4d30 });
  var matCliff = new THREE.MeshLambertMaterial({ map: TEX.cliffRock });
  var matCobble = new THREE.MeshLambertMaterial({ map: TEX.cobble });
  var matPawCobble = new THREE.MeshLambertMaterial({ map: TEX.pawCobble });
  var matSand = new THREE.MeshLambertMaterial({ map: TEX.sand });

  var grassCubeMats = [matGrassSide, matGrassSide, matGrassTop, matDirt, matGrassSide, matGrassSide];
  var cobbleCubeMats = [matCliff, matCliff, matCobble, matDirt, matCliff, matCliff];
  var pawCubeMats = [matCliff, matCliff, matPawCobble, matDirt, matCliff, matCliff];
  var sandCubeMats = [matDirt, matDirt, matSand, matDirt, matDirt, matDirt];

  var unitBox = new THREE.BoxGeometry(1, 1, 1);

  function addBox(parent, w, h, d, x, y, z, mat, castShadow, receiveShadow) {
    var m = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), mat);
    m.position.set(x, y, z);
    if (castShadow) m.castShadow = true;
    if (receiveShadow !== false) m.receiveShadow = true;
    parent.add(m);
    return m;
  }

  function isInPond(gx, gz) {
    // Organic pinched pond in SE quadrant (x: 3..8, z: 0..5)
    if (gx === 5 && gz === 2) return true;
    var dx = (gx - 5.3) / 2.75;
    var dz = (gz - 2.4) / 3.15;
    var pinch = (gz === 2) ? 0.25 : 0;
    return (dx * dx + dz * dz + pinch) < 0.96;
  }

  function isNWterrace(gx, gz) {
    return gx >= -8 && gx <= -1 && gz >= -8 && gz <= -2;
  }

  function isCobblePath(gx, gz) {
    // Central Plaza
    if (gx >= -2 && gx <= 2 && gz >= -2 && gz <= 2) return true;
    // Market square paths
    if (gx >= -6 && gx <= -1 && gz >= 1 && gz <= 7) {
      if (gz >= 2 && gz <= 5) return true;
      if (gx === -3 && gz <= 7) return true;
    }
    // Bridge west approach
    if (gz === 2 && (gx === 2 || gx === 3 || gx === 8)) return true;
    // Terrace paths
    if (gx >= -6 && gx <= -2 && gz >= -4 && gz <= -2) return true;
    if (gx === -2 && gz === -1) return true;
    return false;
  }

  function isInsideIsland(gx, gz) {
    // Organic rounded diamond-circle ~10 radius
    var r2 = (gx * gx) / 96 + (gz * gz) / 94;
    var wobble = Math.sin(gx * 0.7 + gz * 0.5) * 0.08 + Math.cos(gx * 0.4 - gz * 0.9) * 0.06;
    if (gx >= -8 && gx <= 8 && gz >= -7 && gz <= 7 && r2 < 0.98) return true;
    return (r2 + wobble) < 0.88;
  }

  // Generate voxel terrain columns
  var cliffRand = seededRand(404);
  for (var gx = -10; gx <= 10; gx++) {
    for (var gz = -10; gz <= 10; gz++) {
      if (!isInsideIsland(gx, gz)) continue;

      var pond = isInPond(gx, gz);
      var nw = isNWterrace(gx, gz);
      var cobble = isCobblePath(gx, gz);

      // Waterfall notch at east rim of pond (8, 4)
      var wfNotch = (gx === 8 && gz === 4);

      var topY = 0;
      if (pond) topY = -0.85;
      else if (wfNotch) topY = -0.35;
      else if (nw) topY = 0.75;

      // Top terrain block
      var topMesh;
      if (pond || wfNotch) {
        topMesh = new THREE.Mesh(unitBox, sandCubeMats);
        topMesh.position.set(gx, topY - 0.5, gz);
      } else if (gx === 0 && gz === 0) {
        topMesh = new THREE.Mesh(unitBox, pawCubeMats);
        topMesh.position.set(gx, topY - 0.5, gz);
      } else if (cobble) {
        topMesh = new THREE.Mesh(unitBox, cobbleCubeMats);
        topMesh.position.set(gx, topY - 0.5, gz);
      } else {
        topMesh = new THREE.Mesh(unitBox, grassCubeMats);
        topMesh.position.set(gx, topY - 0.5, gz);
      }
      topMesh.receiveShadow = true;
      topMesh.castShadow = true;
      islandGroup.add(topMesh);

      // Stone underside taper (stalactite floating island bottom)
      var distNorm = Math.sqrt(gx * gx + gz * gz) / 10.2;
      var depth = Math.max(1.2, (1.0 - distNorm * 0.78) * 6.4 + (cliffRand() * 2.1));
      if (nw) depth += 0.75;
      var rockHeight = Math.max(0.8, depth - 0.6);
      var rockMesh = new THREE.Mesh(
        new THREE.BoxGeometry(1, rockHeight, 1),
        matCliff
      );
      rockMesh.position.set(gx, topY - 1.0 - rockHeight * 0.5, gz);
      rockMesh.receiveShadow = true;
      islandGroup.add(rockMesh);
    }
  }

  // Central spire tip beneath island + floating mini rocklets
  addBox(islandGroup, 2.2, 2.6, 2.2, 0, -7.8, 0, matCliff, false, true);
  addBox(islandGroup, 1.1, 2.0, 1.1, 0.2, -9.6, -0.2, matCliff, false, false);

  var miniIslets = [];
  var isletCoords = [
    [-11.5, -3.4, -4.5, 1.2],
    [11.2, -4.2, -2.5, 1.0],
    [-8.5, -5.8, 9.2, 0.9],
    [9.4, -6.2, 7.8, 1.1]
  ];
  for (var ii = 0; ii < isletCoords.length; ii++) {
    var ic = isletCoords[ii];
    var ig = new THREE.Group();
    ig.position.set(ic[0], ic[1], ic[2]);
    addBox(ig, ic[3], 0.45, ic[3], 0, 0, 0, grassCubeMats, false, true);
    addBox(ig, ic[3] * 0.75, ic[3] * 0.9, ic[3] * 0.75, 0, -0.6, 0, matCliff, false, false);
    islandGroup.add(ig);
    miniIslets.push({ group: ig, baseY: ic[1], phase: ii * 1.7 });
  }

  // Hanging pixel vines along cliff edges
  var matVine = new THREE.MeshLambertMaterial({ color: 0x4ca142 });
  var vineSpots = [[-9.4, -0.8, 2.0, 2.4], [-5.0, -0.8, 9.1, 1.9], [4.0, -0.8, -8.9, 2.6], [8.8, -0.8, -1.0, 2.2], [-8.8, 0.1, -6.0, 2.3]];
  for (var vi = 0; vi < vineSpots.length; vi++) {
    var vs = vineSpots[vi];
    addBox(islandGroup, 0.24, vs[3], 0.24, vs[0], vs[1] - vs[3] * 0.5, vs[2], matVine, false, false);
  }

  // Stone stairs connecting Plaza (y=0) to NW Terrace (y=0.75)
  addBox(islandGroup, 1.9, 0.38, 0.65, -2.1, 0.19, -0.85, matCobble, true, true);
  addBox(islandGroup, 1.9, 0.75, 0.65, -2.1, 0.375, -1.45, matCobble, true, true);

  // Pond Animated Water + Koi Fish + Lily Pads + Reeds + Waterfall
  var waterTex = cloneTiledTex(TEX.water, 4, 4);
  var waterMat = new THREE.MeshPhongMaterial({
    map: waterTex,
    color: 0x52c8e8,
    shininess: 70,
    transparent: true,
    opacity: 0.78
  });
  var pondWater = new THREE.Mesh(new THREE.BoxGeometry(5.3, 0.16, 6.2), waterMat);
  pondWater.position.set(5.3, -0.22, 2.4);
  pondWater.receiveShadow = true;
  islandGroup.add(pondWater);

  // Waterfall spilling over SE pond edge (x=8.2, z=4.0)
  var waterfallTex = cloneTiledTex(TEX.water, 1, 5);
  var waterfallMat = new THREE.MeshBasicMaterial({
    map: waterfallTex,
    color: 0x7ae2ff,
    transparent: true,
    opacity: 0.82
  });
  var waterfallLip = new THREE.Mesh(new THREE.BoxGeometry(1.1, 0.18, 1.0), waterfallMat);
  waterfallLip.position.set(8.0, -0.22, 4.0);
  islandGroup.add(waterfallLip);

  var waterfallStream = new THREE.Mesh(new THREE.BoxGeometry(0.32, 6.5, 0.95), waterfallMat);
  waterfallStream.position.set(8.62, -3.45, 4.0);
  islandGroup.add(waterfallStream);

  var mistCubes = [];
  var matMist = new THREE.MeshBasicMaterial({ color: 0xe6fbff, transparent: true, opacity: 0.7 });
  for (var mi = 0; mi < 8; mi++) {
    var mc = new THREE.Mesh(new THREE.BoxGeometry(0.34, 0.34, 0.34), matMist);
    mc.position.set(8.6 + (mi % 2) * 0.25, -6.5, 3.65 + (mi % 3) * 0.32);
    islandGroup.add(mc);
    mistCubes.push({ mesh: mc, phase: mi * 0.85, baseZ: 3.65 + (mi % 3) * 0.32 });
  }

  // Lily pads & pixel lotus buds
  var matLily = new THREE.MeshLambertMaterial({ color: 0x59b848 });
  var matLotus = new THREE.MeshLambertMaterial({ color: 0xff8bb4 });
  var lilyCoords = [[4.2, 0.8], [6.4, 0.5], [4.5, 4.0], [6.6, 3.8]];
  for (var li = 0; li < lilyCoords.length; li++) {
    var lc = lilyCoords[li];
    addBox(islandGroup, 0.62, 0.08, 0.62, lc[0], -0.11, lc[1], matLily, false, true);
    if (li % 2 === 0) {
      addBox(islandGroup, 0.22, 0.18, 0.22, lc[0] + 0.08, -0.02, lc[1], matLotus, false, false);
    }
  }

  // Shoreline reeds
  var matReed = new THREE.MeshLambertMaterial({ color: 0x4b943b });
  var matCattail = new THREE.MeshLambertMaterial({ color: 0x734427 });
  var reedSpots = [[2.7, 0.4], [2.9, 4.6], [7.4, 0.4], [7.5, 5.0]];
  for (var ri = 0; ri < reedSpots.length; ri++) {
    var rs = reedSpots[ri];
    addBox(islandGroup, 0.1, 0.75, 0.1, rs[0], 0.3, rs[1], matReed, true, false);
    addBox(islandGroup, 0.14, 0.25, 0.14, rs[0], 0.68, rs[1], matCattail, false, false);
    addBox(islandGroup, 0.1, 0.55, 0.1, rs[0] + 0.16, 0.2, rs[1] + 0.1, matReed, true, false);
  }

  // Koi fish swimming inside pond
  var koiFish = [];
  var koiColors = [0xff773b, 0xfff5e0, 0xffaa33];
  for (var ki = 0; ki < 3; ki++) {
    var kg = new THREE.Group();
    var km = new THREE.MeshLambertMaterial({ color: koiColors[ki] });
    addBox(kg, 0.16, 0.12, 0.34, 0, 0, 0, km, false, false);
    addBox(kg, 0.12, 0.1, 0.12, 0, 0, -0.22, km, false, false);
    islandGroup.add(kg);
    koiFish.push({
      group: kg,
      cx: 5.2,
      cz: ki === 0 ? 0.6 : 3.9,
      rx: 1.15,
      rz: 0.72,
      speed: 0.7 + ki * 0.22,
      phase: ki * 2.1
    });
  }

  /* =========================
     6. BRIDGE, BUILDINGS & PROPS
     ========================= */
  var matWood = new THREE.MeshLambertMaterial({ map: TEX.wood });
  var matBark = new THREE.MeshLambertMaterial({ map: TEX.bark });
  var matLeafGreen = new THREE.MeshLambertMaterial({ map: TEX.leavesGreen });
  var matLeafPink = new THREE.MeshLambertMaterial({ map: TEX.leavesPink });

  // Shared glowing materials (animated between Day/Sunset/Night!)
  var windowMat = new THREE.MeshLambertMaterial({
    map: TEX.windowDay,
    emissive: new THREE.Color(0xffc34d),
    emissiveMap: TEX.windowGlow,
    emissiveIntensity: 0.0
  });

  var lanternGlowMat = new THREE.MeshLambertMaterial({
    color: 0xffecc7,
    emissive: new THREE.Color(0xffa733),
    emissiveIntensity: 0.05
  });

  var matDarkIron = new THREE.MeshLambertMaterial({ color: 0x2a2433 });
  var matWhiteFence = new THREE.MeshLambertMaterial({ color: 0xf4ecd8 });

  // Helper: Small Arched Bridge profile
  function getBridgeY(x) {
    // Spans x = 2.6 to 7.6 (center 5.1)
    if (x <= 2.6 || x >= 7.6) return 0.0;
    var u = (x - 5.1) / 2.5;
    return 0.64 * (1 - u * u) + 0.08;
  }

  // Build Small Arched Wooden Bridge at z = 2.0
  var bridgeGroup = new THREE.Group();
  islandGroup.add(bridgeGroup);
  var plankCount = 13;
  for (var pi = 0; pi < plankCount; pi++) {
    var px = 2.7 + (pi / (plankCount - 1)) * 4.8;
    var py = getBridgeY(px);
    addBox(bridgeGroup, 0.36, 0.14, 1.35, px, py - 0.07, 2.0, matWood, true, true);
  }
  // Bridge posts & handrails
  var postXs = [2.75, 3.9, 5.1, 6.3, 7.45];
  for (var pIdx = 0; pIdx < postXs.length; pIdx++) {
    var bpx = postXs[pIdx];
    var bpy = getBridgeY(bpx);
    addBox(bridgeGroup, 0.16, 0.72, 0.16, bpx, bpy + 0.32, 1.38, matBark, true, true);
    addBox(bridgeGroup, 0.16, 0.72, 0.16, bpx, bpy + 0.32, 2.62, matBark, true, true);
  }
  // Stepped handrails
  for (var hi = 0; hi < postXs.length - 1; hi++) {
    var x1 = postXs[hi], x2 = postXs[hi + 1];
    var xm = (x1 + x2) * 0.5;
    var ym = (getBridgeY(x1) + getBridgeY(x2)) * 0.5 + 0.56;
    var dx = x2 - x1, dy = getBridgeY(x2) - getBridgeY(x1);
    var railLen = Math.sqrt(dx * dx + dy * dy) + 0.08;
    var angle = Math.atan2(dy, dx);
    var r1 = addBox(bridgeGroup, railLen, 0.1, 0.1, xm, ym, 1.38, matWood, true, true);
    r1.rotation.z = angle;
    var r2 = addBox(bridgeGroup, railLen, 0.1, 0.1, xm, ym, 2.62, matWood, true, true);
    r2.rotation.z = angle;
  }

  // Helper: Street Lantern
  function addLantern(x, baseY, z, withLight) {
    var lg = new THREE.Group();
    lg.position.set(x, baseY, z);
    addBox(lg, 0.18, 1.15, 0.18, 0, 0.57, 0, matDarkIron, true, true);
    addBox(lg, 0.36, 0.36, 0.36, 0, 1.25, 0, lanternGlowMat, false, false);
    addBox(lg, 0.48, 0.14, 0.48, 0, 1.48, 0, matDarkIron, true, false);
    addBox(lg, 0.2, 0.14, 0.2, 0, 1.6, 0, matDarkIron, true, false);
    islandGroup.add(lg);
    if (withLight) addLanternLight(x, baseY + 1.4, z);
  }

  // Place street & bridge lanterns
  addLantern(-1.6, 0, 1.4, true);
  addLantern(1.7, 0, -1.6, true);
  addLantern(2.75, getBridgeY(2.75) + 0.65, 1.38, false);
  addLantern(7.45, getBridgeY(7.45) + 0.65, 2.62, true);
  addLantern(-4.5, 0.75, -2.2, true);
  addLantern(-3.0, 0, 4.3, true);
  addLantern(4.5, 0, -3.5, true);
  addLantern(1.4, 0, 2.6, false);

  // Chimney smoke puffs tracker
  var smokePuffs = [];
  var matSmoke = new THREE.MeshBasicMaterial({ color: 0xf4f2f7, transparent: true, opacity: 0.65 });

  function addChimneySmoke(x, y, z) {
    for (var si = 0; si < 3; si++) {
      var sm = new THREE.Mesh(new THREE.BoxGeometry(0.26, 0.26, 0.26), matSmoke.clone());
      sm.position.set(x, y + si * 0.45, z);
      islandGroup.add(sm);
      smokePuffs.push({ mesh: sm, bx: x, by: y, bz: z, phase: si * 1.1 });
    }
  }

  // 6a. Town Hall (NW Terrace: -4.8, -5.6, y = 0.75)
  (function buildTownHall() {
    var th = new THREE.Group();
    th.position.set(-4.8, 0.75, -5.6);
    var wallMat = new THREE.MeshLambertMaterial({ map: cloneTiledTex(TEX.wallCream, 2, 1.5) });
    var roofMat = new THREE.MeshLambertMaterial({ map: cloneTiledTex(TEX.roofTerra, 2.5, 1.5) });
    var doorMat = new THREE.MeshLambertMaterial({ map: TEX.door });

    // Main hall body
    addBox(th, 3.4, 2.0, 2.6, 0, 1.0, 0, wallMat, true, true);
    // Sunny flat front porch roof terrace (Cat naps here!)
    addBox(th, 2.4, 0.24, 1.35, 0, 1.55, 1.65, roofMat, true, true);
    addBox(th, 0.22, 1.45, 0.22, -1.0, 0.72, 2.15, matWood, true, true);
    addBox(th, 0.22, 1.45, 0.22, 1.0, 0.72, 2.15, matWood, true, true);
    // Double doors
    addBox(th, 0.9, 1.1, 0.1, 0, 0.55, 1.32, doorMat, false, true);
    // Glowing windows
    addBox(th, 0.65, 0.65, 0.1, -1.1, 1.05, 1.32, windowMat, false, false);
    addBox(th, 0.65, 0.65, 0.1, 1.1, 1.05, 1.32, windowMat, false, false);
    addBox(th, 0.1, 0.65, 0.65, 1.72, 1.05, 0, windowMat, false, false);
    addBox(th, 0.1, 0.65, 0.65, -1.72, 1.05, 0, windowMat, false, false);
    // Stepped pitched roof
    addBox(th, 3.8, 0.45, 3.0, 0, 2.22, 0, roofMat, true, true);
    addBox(th, 3.3, 0.45, 2.2, 0, 2.66, 0, roofMat, true, true);
    addBox(th, 2.8, 0.4, 1.4, 0, 3.08, 0, roofMat, true, true);
    // Clock & Cat-Ear Bell Tower
    addBox(th, 1.25, 1.25, 1.25, 0, 3.65, 0.1, wallMat, true, true);
    var clockMat = new THREE.MeshLambertMaterial({ map: TEX.clockFace });
    addBox(th, 0.65, 0.65, 0.1, 0, 3.65, 0.74, clockMat, false, false);
    addBox(th, 1.45, 0.35, 1.45, 0, 4.42, 0.1, roofMat, true, true);
    // Cute cat-ear roof finials!
    addBox(th, 0.36, 0.42, 0.36, -0.45, 4.78, 0.1, roofMat, true, true);
    addBox(th, 0.36, 0.42, 0.36, 0.45, 4.78, 0.1, roofMat, true, true);

    islandGroup.add(th);
  })();

  // 6b. Sunny Bakery / Cottage A (NW Terrace: -7.2, -2.2, y = 0.75)
  (function buildCottageA() {
    var c = new THREE.Group();
    c.position.set(-7.2, 0.75, -2.2);
    var wallMat = new THREE.MeshLambertMaterial({ map: cloneTiledTex(TEX.wallButter, 1.5, 1.2) });
    var roofMat = new THREE.MeshLambertMaterial({ map: cloneTiledTex(TEX.roofTerra, 2, 1.5) });
    var doorMat = new THREE.MeshLambertMaterial({ map: TEX.door });

    addBox(c, 2.3, 1.7, 2.3, 0, 0.85, 0, wallMat, true, true);
    addBox(c, 0.1, 0.95, 0.7, 1.16, 0.48, 0, doorMat, false, true);
    addBox(c, 0.1, 0.6, 0.6, 1.16, 1.05, 0.65, windowMat, false, false);
    addBox(c, 0.6, 0.6, 0.1, 0, 0.95, 1.16, windowMat, false, false);
    addBox(c, 0.6, 0.6, 0.1, 0, 0.95, -1.16, windowMat, false, false);

    // Stepped sunny terracotta roof (flat top at local y = 2.68 where Sunny naps!)
    addBox(c, 2.7, 0.36, 2.7, 0, 1.88, 0, roofMat, true, true);
    addBox(c, 2.1, 0.36, 2.1, 0, 2.24, 0, roofMat, true, true);
    addBox(c, 1.55, 0.28, 1.55, 0, 2.55, 0, roofMat, true, true);
    // Chimney
    addBox(c, 0.45, 0.9, 0.45, -0.65, 2.75, -0.55, matCliff, true, true);
    addChimneySmoke(-7.85, 4.05, -2.75);

    islandGroup.add(c);
  })();

  // 6c. Blue-Roof Cottage B (NW Terrace: -1.4, -6.8, y = 0.75)
  (function buildCottageB() {
    var c = new THREE.Group();
    c.position.set(-1.4, 0.75, -6.8);
    var wallMat = new THREE.MeshLambertMaterial({ map: cloneTiledTex(TEX.wallSky, 1.5, 1.2) });
    var roofMat = new THREE.MeshLambertMaterial({ map: cloneTiledTex(TEX.roofSlate, 2, 1.5) });
    var doorMat = new THREE.MeshLambertMaterial({ map: TEX.door });

    addBox(c, 2.2, 1.65, 2.1, 0, 0.82, 0, wallMat, true, true);
    addBox(c, 0.68, 0.92, 0.1, -0.38, 0.46, 1.06, doorMat, false, true);
    addBox(c, 0.58, 0.58, 0.1, 0.48, 0.95, 1.06, windowMat, false, false);
    addBox(c, 0.1, 0.58, 0.58, 1.11, 0.95, 0, windowMat, false, false);

    // Stepped slate-blue roof (flat upper roof platform at local y = 2.55 where Mittens naps!)
    addBox(c, 2.6, 0.35, 2.5, 0, 1.82, 0, roofMat, true, true);
    addBox(c, 2.0, 0.35, 1.9, 0, 2.17, 0, roofMat, true, true);
    addBox(c, 1.45, 0.26, 1.4, 0, 2.46, 0, roofMat, true, true);
    addBox(c, 0.42, 0.75, 0.42, 0.55, 2.65, -0.4, matCliff, true, true);
    addChimneySmoke(-0.85, 3.85, -7.2);

    islandGroup.add(c);
  })();

  // 6d. Fish Market District (SW Quadrant, y = 0)
  (function buildFishMarket() {
    // Fishmonger cottage at (-7.2, 4.2)
    var fc = new THREE.Group();
    fc.position.set(-7.2, 0, 4.2);
    var wallMat = new THREE.MeshLambertMaterial({ map: cloneTiledTex(TEX.wallCream, 1.5, 1.2) });
    var roofMat = new THREE.MeshLambertMaterial({ map: cloneTiledTex(TEX.roofHoney, 2, 1.5) });
    var doorMat = new THREE.MeshLambertMaterial({ map: TEX.door });
    addBox(fc, 2.2, 1.7, 2.4, 0, 0.85, 0, wallMat, true, true);
    addBox(fc, 0.1, 0.95, 0.7, 1.11, 0.48, 0.35, doorMat, false, true);
    addBox(fc, 0.1, 0.6, 0.6, 1.11, 1.0, -0.55, windowMat, false, false);
    addBox(fc, 0.6, 0.6, 0.1, 0, 0.98, 1.21, windowMat, false, false);
    addBox(fc, 2.6, 0.35, 2.8, 0, 1.88, 0, roofMat, true, true);
    addBox(fc, 2.0, 0.35, 2.2, 0, 2.23, 0, roofMat, true, true);
    addBox(fc, 1.3, 0.3, 1.6, 0, 2.53, 0, roofMat, true, true);
    islandGroup.add(fc);

    // Helper: Striped Awning Market Stall
    function makeMarketStall(x, z, rotY, awningTex) {
      var st = new THREE.Group();
      st.position.set(x, 0, z);
      st.rotation.y = rotY;
      var awMat = new THREE.MeshLambertMaterial({ map: cloneTiledTex(awningTex, 2.2, 1) });
      var crateMat = new THREE.MeshLambertMaterial({ map: TEX.fishCrate });

      // Counter base + wooden posts
      addBox(st, 2.1, 0.78, 0.75, 0, 0.39, 0.22, matWood, true, true);
      addBox(st, 2.22, 0.12, 0.86, 0, 0.82, 0.22, matWood, true, true);
      addBox(st, 0.16, 2.0, 0.16, -0.95, 1.0, -0.35, matBark, true, true);
      addBox(st, 0.16, 2.0, 0.16, 0.95, 1.0, -0.35, matBark, true, true);
      addBox(st, 0.14, 1.75, 0.14, -0.95, 0.88, 0.55, matBark, true, true);
      addBox(st, 0.14, 1.75, 0.14, 0.95, 0.88, 0.55, matBark, true, true);

      // Stepped chunky striped pixel awning sloping forward!
      addBox(st, 2.4, 0.24, 0.58, 0, 2.05, -0.22, awMat, true, true);
      addBox(st, 2.4, 0.24, 0.58, 0, 1.88, 0.26, awMat, true, true);
      addBox(st, 2.4, 0.24, 0.56, 0, 1.72, 0.72, awMat, true, true);

      // Fish crates on counter & ice barrels alongside
      addBox(st, 0.62, 0.26, 0.48, -0.45, 0.98, 0.25, crateMat, true, true);
      addBox(st, 0.62, 0.26, 0.48, 0.42, 0.98, 0.25, crateMat, true, true);
      addBox(st, 0.52, 0.48, 0.45, 1.32, 0.24, 0.2, crateMat, true, true);

      islandGroup.add(st);
      return st;
    }

    var stall1 = makeMarketStall(-4.4, 2.2, 0, TEX.awningRed);
    // Hanging Fish Sign above main stall!
    var signMat = new THREE.MeshLambertMaterial({ map: TEX.fishSign });
    addBox(stall1, 0.75, 0.75, 0.12, 0, 2.55, -0.1, signMat, true, false);
    addBox(stall1, 0.12, 0.35, 0.12, -0.22, 2.2, -0.1, matDarkIron, false, false);
    addBox(stall1, 0.12, 0.35, 0.12, 0.22, 2.2, -0.1, matDarkIron, false, false);

    makeMarketStall(-3.2, 6.4, Math.PI, TEX.awningBlue);

    // Extra fish crate stack near market corner
    var cMat = new THREE.MeshLambertMaterial({ map: TEX.fishCrate });
    addBox(islandGroup, 0.6, 0.45, 0.6, -5.6, 0.225, 5.2, cMat, true, true);
    addBox(islandGroup, 0.52, 0.4, 0.52, -5.55, 0.65, 5.2, cMat, true, true);
  })();

  // 6e. Yarn Park (NE Quadrant, y = 0)
  var yarnBalls = [];
  (function buildYarnPark() {
    var yarnBaseTex = TEX.yarnBase;

    function addGiantYarnBall(x, z, r, hexColor) {
      var yg = new THREE.Group();
      yg.position.set(x, r * 0.92, z);
      var ym = new THREE.MeshLambertMaterial({ map: yarnBaseTex, color: hexColor });
      // Chunky 3-axis voxelized pixel sphere!
      addBox(yg, r * 1.42, r * 1.42, r * 1.42, 0, 0, 0, ym, true, true);
      addBox(yg, r * 1.75, r * 1.05, r * 1.05, 0, 0, 0, ym, true, true);
      addBox(yg, r * 1.05, r * 1.75, r * 1.05, 0, 0, 0, ym, true, true);
      addBox(yg, r * 1.05, r * 1.05, r * 1.75, 0, 0, 0, ym, true, true);
      // Trailing pixel yarn tail lying on the grass
      var strandMat = new THREE.MeshLambertMaterial({ color: hexColor });
      addBox(islandGroup, r * 0.9, 0.09, 0.11, x - r * 0.9, 0.05, z + r * 0.6, strandMat, false, true);
      addBox(islandGroup, 0.11, 0.09, r * 0.7, x - r * 1.35, 0.05, z + r * 0.9, strandMat, false, true);
      islandGroup.add(yg);
      yarnBalls.push({ group: yg, baseY: r * 0.92, x: x, z: z, wobble: 0 });
    }

    addGiantYarnBall(3.9, -5.2, 0.85, 0xff626b); // Giant Coral Red Yarn
    addGiantYarnBall(6.4, -3.5, 0.72, 0xffd24c); // Sunshine Gold Yarn
    addGiantYarnBall(6.0, -6.5, 0.76, 0x52b6f0); // Sky Blue Yarn
    addGiantYarnBall(2.4, -3.3, 0.60, 0xb985ff); // Lavender Yarn

    // White picket park fences along outer edge
    var fenceSpots = [
      [1.2, -7.8, 0], [2.4, -8.2, 0], [7.8, -5.8, Math.PI / 2], [7.8, -4.4, Math.PI / 2]
    ];
    for (var fi = 0; fi < fenceSpots.length; fi++) {
      var fs = fenceSpots[fi];
      var fg = new THREE.Group();
      fg.position.set(fs[0], 0, fs[1]);
      fg.rotation.y = fs[2];
      addBox(fg, 1.0, 0.1, 0.1, 0, 0.35, 0, matWhiteFence, true, true);
      addBox(fg, 0.12, 0.58, 0.12, -0.35, 0.29, 0, matWhiteFence, true, true);
      addBox(fg, 0.12, 0.58, 0.12, 0, 0.29, 0, matWhiteFence, true, true);
      addBox(fg, 0.12, 0.58, 0.12, 0.35, 0.29, 0, matWhiteFence, true, true);
      islandGroup.add(fg);
    }
  })();

  // 6f. Pixel Trees, Benches, Signpost & Flowers
  function addTree(x, baseY, z, isPink, scale) {
    var tg = new THREE.Group();
    tg.position.set(x, baseY, z);
    var s = scale || 1.0;
    addBox(tg, 0.45 * s, 1.45 * s, 0.45 * s, 0, 0.72 * s, 0, matBark, true, true);
    var lm = isPink ? matLeafPink : matLeafGreen;
    addBox(tg, 1.75 * s, 0.95 * s, 1.75 * s, 0, 1.8 * s, 0, lm, true, true);
    addBox(tg, 1.3 * s, 0.75 * s, 1.3 * s, 0.1 * s, 2.4 * s, -0.1 * s, lm, true, true);
    addBox(tg, 0.85 * s, 0.5 * s, 0.85 * s, 0, 2.85 * s, 0, lm, true, true);
    islandGroup.add(tg);
  }

  addTree(3.6, 0, -7.8, true, 1.05);
  addTree(7.8, 0, -5.0, true, 0.95);
  addTree(-7.6, 0.75, -5.8, false, 1.05);
  addTree(-5.2, 0, 7.2, false, 0.92);
  addTree(1.2, 0, 6.2, false, 0.98);
  addTree(7.8, 0, -0.9, true, 0.86);

  function addBench(x, baseY, z, rotY) {
    var bg = new THREE.Group();
    bg.position.set(x, baseY, z);
    bg.rotation.y = rotY;
    addBox(bg, 1.15, 0.12, 0.44, 0, 0.32, 0, matWood, true, true);
    addBox(bg, 1.15, 0.36, 0.1, 0, 0.55, -0.18, matWood, true, true);
    addBox(bg, 0.14, 0.32, 0.38, -0.45, 0.16, 0, matBark, true, true);
    addBox(bg, 0.14, 0.32, 0.38, 0.45, 0.16, 0, matBark, true, true);
    islandGroup.add(bg);
  }

  addBench(-1.6, 0, 0.4, Math.PI / 2);
  addBench(2.0, 0, -6.5, Math.PI / 4);
  addBench(7.9, 0, 1.0, -Math.PI / 2);

  // Flower tufts scattered around park & cottages
  var flowerPalette = [0xff6b8b, 0xffe259, 0x89d4ff, 0xffffff];
  var flowerSpots = [
    [1.8, 0, -2.5], [4.5, 0, -2.2], [7.2, 0, -2.5], [1.8, 0, 4.4],
    [-6.0, 0.75, -4.0], [-2.8, 0.75, -4.8], [-1.0, 0, 6.6], [3.2, 0, 6.5]
  ];
  for (var fli = 0; fli < flowerSpots.length; fli++) {
    var fl = flowerSpots[fli];
    var fMat = new THREE.MeshLambertMaterial({ color: flowerPalette[fli % flowerPalette.length] });
    addBox(islandGroup, 0.18, 0.12, 0.18, fl[0], fl[1] + 0.08, fl[2], matLeafGreen, false, false);
    addBox(islandGroup, 0.22, 0.14, 0.22, fl[0], fl[1] + 0.18, fl[2], fMat, false, false);
    addBox(islandGroup, 0.16, 0.12, 0.16, fl[0] + 0.25, fl[1] + 0.13, fl[2] + 0.15, fMat, false, false);
  }

  /* =========================
     7. CHUNKY CLOUDS, BUTTERFLIES, FIREFLIES
     ========================= */
  var cloudMaterials = [];
  var clouds = [];

  function createCloud(x, y, z, scale, speed) {
    var cg = new THREE.Group();
    cg.position.set(x, y, z);
    var cm = new THREE.MeshLambertMaterial({ color: 0xffffff });
    cloudMaterials.push(cm);
    addBox(cg, 3.2 * scale, 1.1 * scale, 2.0 * scale, 0, 0, 0, cm, false, false);
    addBox(cg, 2.0 * scale, 1.4 * scale, 1.6 * scale, -0.4 * scale, 0.35 * scale, 0.1 * scale, cm, false, false);
    addBox(cg, 1.8 * scale, 1.15 * scale, 1.5 * scale, 1.1 * scale, 0.15 * scale, -0.15 * scale, cm, false, false);
    addBox(cg, 1.5 * scale, 0.9 * scale, 1.4 * scale, -1.3 * scale, -0.05 * scale, 0.1 * scale, cm, false, false);
    scene.add(cg);
    clouds.push({ group: cg, baseY: y, speed: speed, phase: x * 0.4 + z * 0.2 });
  }

  // Clouds drifting below the island!
  createCloud(-18, -7.2, -8, 1.15, 0.65);
  createCloud(-4, -9.5, -14, 1.45, 0.48);
  createCloud(11, -7.8, -3, 1.1, 0.72);
  createCloud(-14, -10.8, 7, 1.55, 0.42);
  createCloud(3, -8.2, 10, 1.2, 0.62);
  createCloud(20, -11.4, 3, 1.4, 0.5);
  createCloud(-24, -8.8, 1, 1.25, 0.56);
  createCloud(15, -7.4, -13, 1.05, 0.68);
  createCloud(-7, -12.6, 17, 1.7, 0.36);
  createCloud(24, -9.8, 14, 1.35, 0.45);

  // Pixel Butterflies in Yarn Park & Plaza
  var butterflies = [];
  var bColors = [0xffde59, 0x70d6ff, 0xff85b3, 0xa8ff78, 0xffa652];
  for (var bi = 0; bi < 5; bi++) {
    var bg = new THREE.Group();
    var bMat = new THREE.MeshBasicMaterial({ color: bColors[bi], side: THREE.DoubleSide });
    var lw = new THREE.Mesh(new THREE.PlaneGeometry(0.24, 0.22), bMat);
    lw.position.set(-0.12, 0, 0);
    lw.rotation.x = -Math.PI / 2;
    var rw = new THREE.Mesh(new THREE.PlaneGeometry(0.24, 0.22), bMat);
    rw.position.set(0.12, 0, 0);
    rw.rotation.x = -Math.PI / 2;
    bg.add(lw, rw);
    var cx = bi < 3 ? 4.4 + (bi - 1) * 1.4 : (bi === 3 ? 0.6 : 2.8);
    var cz = bi < 3 ? -4.5 + (bi % 2) * 1.2 : (bi === 3 ? -0.4 : -2.6);
    bg.position.set(cx, 1.1, cz);
    islandGroup.add(bg);
    butterflies.push({
      group: bg,
      lw: lw,
      rw: rw,
      cx: cx,
      cz: cz,
      rx: 1.2,
      rz: 1.1,
      phase: bi * 1.4,
      speed: 1.1 + bi * 0.15
    });
  }

  // Nighttime fireflies
  var fireflies = [];
  var fireflyMat = new THREE.MeshBasicMaterial({ color: 0xeaff7b, transparent: true, opacity: 0.0 });
  var ffCoords = [
    [3.5, 1.2, 0.4], [6.8, 1.0, 4.2], [4.2, 1.1, -4.6], [6.2, 1.3, -5.8],
    [1.6, 1.1, -2.5], [3.0, 1.1, 3.8], [7.5, 1.0, 2.8], [-1.8, 1.2, 5.2]
  ];
  for (var ffi = 0; ffi < ffCoords.length; ffi++) {
    var ffc = ffCoords[ffi];
    var ffm = new THREE.Mesh(new THREE.BoxGeometry(0.12, 0.12, 0.12), fireflyMat);
    ffm.position.set(ffc[0], ffc[1], ffc[2]);
    islandGroup.add(ffm);
    fireflies.push({ mesh: ffm, bx: ffc[0], by: ffc[1], bz: ffc[2], phase: ffi * 1.3 });
  }

  /* =========================
     8. CHUNKY PIXEL CATS
     ========================= */
  var catFaceCache = {};
  function getCatFaceTex(cfg, sleepy) {
    var key = cfg.id + (sleepy ? '_sleep' : '_awake');
    if (catFaceCache[key]) return catFaceCache[key];
    var tex = createPixelCanvas(16, 16, function (ctx) {
      ctx.fillStyle = cfg.base;
      ctx.fillRect(0, 0, 16, 16);
      // Optional fur mask/patches
      if (cfg.pattern === 'tuxedo') {
        ctx.fillStyle = cfg.sec;
        ctx.fillRect(4, 10, 8, 6);
        ctx.fillRect(6, 8, 4, 3);
      } else if (cfg.pattern === 'siamese') {
        ctx.fillStyle = cfg.sec;
        ctx.fillRect(3, 5, 10, 9);
      } else if (cfg.pattern === 'calico') {
        ctx.fillStyle = cfg.sec;
        ctx.fillRect(0, 0, 7, 7);
        ctx.fillStyle = cfg.tri;
        ctx.fillRect(10, 1, 6, 6);
      } else if (cfg.pattern === 'tabby') {
        ctx.fillStyle = cfg.sec;
        ctx.fillRect(4, 1, 2, 3);
        ctx.fillRect(7, 1, 2, 4);
        ctx.fillRect(10, 1, 2, 3);
        ctx.fillRect(1, 8, 2, 1);
        ctx.fillRect(13, 8, 2, 1);
      } else if (cfg.pattern === 'bicolor') {
        ctx.fillStyle = cfg.sec;
        ctx.fillRect(5, 9, 6, 7);
        ctx.fillRect(7, 6, 2, 4);
      }

      // Eyes
      if (sleepy) {
        ctx.fillStyle = '#241c2c';
        ctx.fillRect(3, 8, 3, 1);
        ctx.fillRect(10, 8, 3, 1);
      } else {
        ctx.fillStyle = cfg.eye;
        ctx.fillRect(3, 6, 3, 3);
        ctx.fillRect(10, 6, 3, 3);
        ctx.fillStyle = '#181320';
        ctx.fillRect(4, 6, 1, 3);
        ctx.fillRect(11, 6, 1, 3);
        ctx.fillStyle = '#ffffff';
        ctx.fillRect(3, 6, 1, 1);
        ctx.fillRect(10, 6, 1, 1);
      }

      // Cute pink nose & whisker dots
      ctx.fillStyle = '#ff8ea4';
      ctx.fillRect(7, 10, 2, 1);
      ctx.fillStyle = '#3a2b38';
      ctx.fillRect(7, 11, 2, 1);
      ctx.fillRect(1, 11, 2, 1);
      ctx.fillRect(13, 11, 2, 1);
    });
    catFaceCache[key] = tex;
    return tex;
  }

  function getCatBodyTex(cfg) {
    return createPixelCanvas(16, 16, function (ctx) {
      ctx.fillStyle = cfg.base;
      ctx.fillRect(0, 0, 16, 16);
      if (cfg.pattern === 'tabby') {
        ctx.fillStyle = cfg.sec;
        ctx.fillRect(0, 3, 16, 2);
        ctx.fillRect(0, 8, 16, 2);
        ctx.fillRect(0, 13, 16, 2);
      } else if (cfg.pattern === 'tuxedo' || cfg.pattern === 'bicolor') {
        ctx.fillStyle = cfg.sec;
        ctx.fillRect(4, 9, 8, 7);
      } else if (cfg.pattern === 'calico') {
        ctx.fillStyle = cfg.sec;
        ctx.fillRect(2, 2, 6, 6);
        ctx.fillStyle = cfg.tri;
        ctx.fillRect(9, 7, 6, 6);
      } else if (cfg.pattern === 'siamese') {
        ctx.fillStyle = cfg.sec;
        ctx.fillRect(4, 12, 8, 4);
      }
      if (cfg.isMayor) {
        // Little red bow tie/sash accent on chest!
        ctx.fillStyle = '#e63b42';
        ctx.fillRect(5, 11, 6, 2);
        ctx.fillStyle = '#ffcf54';
        ctx.fillRect(7, 11, 2, 2);
      }
      if (cfg.apron) {
        // Blue fishmonger apron!
        ctx.fillStyle = '#3a88c8';
        ctx.fillRect(3, 6, 10, 9);
        ctx.fillStyle = '#eef8ff';
        ctx.fillRect(3, 6, 10, 1);
      }
    });
  }

  var catDefinitions = [
    { id: 'mayor', name: 'Mayor Marmalade', role: 'Town Mayor', swatch: '#f58b38', base: '#f58b38', sec: '#cc6018', eye: '#4ec45a', pattern: 'tabby', isMayor: true, kind: 'mayor', startNode: 'plaza_c' },
    { id: 'cod', name: 'Captain Cod', role: 'Fishmonger', swatch: '#5282ad', base: '#f2ead9', sec: '#5282ad', eye: '#ffc742', pattern: 'bicolor', apron: true, kind: 'shopkeeper', pos: [-4.4, 0, 1.55], rotY: 0 },
    { id: 'sunny', name: 'Sunny', role: 'Rooftop Napper', swatch: '#f7a554', base: '#fff5e4', sec: '#f08637', tri: '#3c343d', eye: '#60bd5a', pattern: 'calico', kind: 'rooftop', roofPos: [-7.2, 3.44, -2.2], roofRot: 0.9 },
    { id: 'croissant', name: 'Croissant', role: 'Hall Terrace Napper', swatch: '#f3be72', base: '#f3be72', sec: '#d69442', eye: '#57ba5c', pattern: 'tabby', kind: 'rooftop', roofPos: [-4.8, 2.42, -3.95], roofRot: 0.25 },
    { id: 'mittens', name: 'Mittens', role: 'Blue-Roof Napper', swatch: '#2e2b38', base: '#2e2b38', sec: '#fff7eb', eye: '#ffcb47', pattern: 'tuxedo', kind: 'rooftop', roofPos: [-1.4, 3.34, -6.8], roofRot: -0.4 },
    { id: 'mochi', name: 'Mochi', role: 'Yarn Enthusiast', swatch: '#fff6eb', base: '#fff6eb', sec: '#f2c1b4', eye: '#6bc4ff', pattern: 'solid', kind: 'town', startNode: 'yarn_1' },
    { id: 'biscuit', name: 'Biscuit', role: 'Plaza Stroller', swatch: '#df9c62', base: '#df9c62', sec: '#fff2df', eye: '#70c45c', pattern: 'bicolor', kind: 'town', startNode: 'plaza_w' },
    { id: 'olive', name: 'Olive', role: 'Bridge Crosser', swatch: '#7e8394', base: '#7e8394', sec: '#575c6b', eye: '#a6e04f', pattern: 'tabby', kind: 'town', startNode: 'bridge_m' },
    { id: 'cleo', name: 'Cleo', role: 'Siamese Connoisseur', swatch: '#f3e5cc', base: '#f3e5cc', sec: '#543c32', eye: '#59bfff', pattern: 'siamese', kind: 'town', startNode: 'stall_1' },
    { id: 'pepper', name: 'Pepper', role: 'Midnight Shadow', swatch: '#272430', base: '#272430', sec: '#3a3547', eye: '#ffdf4d', pattern: 'solid', kind: 'town', startNode: 'plaza_n' },
    { id: 'jasper', name: 'Jasper', role: 'Butterfly Chaser', swatch: '#e87946', base: '#e87946', sec: '#fff3e2', eye: '#62cc62', pattern: 'bicolor', kind: 'town', startNode: 'yarn_2' },
    { id: 'nori', name: 'Nori', role: 'Market Regular', swatch: '#3d3c4a', base: '#3d3c4a', sec: '#f5efe2', eye: '#70d47b', pattern: 'tuxedo', kind: 'town', startNode: 'stall_2' },
    { id: 'clover', name: 'Clover', role: 'Lakeside Dreamer', swatch: '#e7c392', base: '#e7c392', sec: '#c2925b', eye: '#68c962', pattern: 'tabby', kind: 'town', startNode: 'pond_e' }
  ];

  // Connected Town Waypoint Graph (verified clear of obstacles & water!)
  var NODES = {
    plaza_c: { x: 0.0, y: 0.0, z: 0.2, links: ['plaza_w', 'plaza_n', 'plaza_s', 'yarn_enter', 'bridge_w'] },
    plaza_w: { x: -2.0, y: 0.0, z: 0.1, links: ['plaza_c', 'stairs_top', 'market_entry'] },
    plaza_n: { x: 0.2, y: 0.0, z: -1.6, links: ['plaza_c', 'yarn_enter'] },
    plaza_s: { x: -0.4, y: 0.0, z: 2.2, links: ['plaza_c', 'bridge_w', 'market_mid'] },
    stairs_top: { x: -2.1, y: 0.75, z: -2.1, links: ['plaza_w', 'hall_front', 'cottage_b'] },
    hall_front: { x: -4.8, y: 0.75, z: -2.8, links: ['stairs_top', 'cottage_a', 'cottage_b'] },
    cottage_a: { x: -5.4, y: 0.75, z: -2.0, links: ['hall_front'] },
    cottage_b: { x: -2.2, y: 0.75, z: -4.6, links: ['stairs_top', 'hall_front'] },
    market_entry: { x: -2.8, y: 0.0, z: 1.6, links: ['plaza_w', 'stall_1', 'market_mid'] },
    market_mid: { x: -2.4, y: 0.0, z: 4.0, links: ['plaza_s', 'market_entry', 'stall_1', 'stall_2', 'fish_alley'] },
    stall_1: { x: -4.4, y: 0.0, z: 3.4, links: ['market_entry', 'market_mid', 'fish_alley'], shopLook: -Math.PI },
    stall_2: { x: -3.2, y: 0.0, z: 5.1, links: ['market_mid', 'fish_alley'], shopLook: 0 },
    fish_alley: { x: -5.2, y: 0.0, z: 4.5, links: ['market_mid', 'stall_1', 'stall_2'] },
    yarn_enter: { x: 1.8, y: 0.0, z: -1.8, links: ['plaza_c', 'plaza_n', 'yarn_1', 'yarn_4'] },
    yarn_1: { x: 3.1, y: 0.0, z: -4.1, links: ['yarn_enter', 'yarn_2', 'yarn_3', 'yarn_4'], yarnIdx: 0 },
    yarn_2: { x: 5.3, y: 0.0, z: -3.7, links: ['yarn_1', 'yarn_3', 'yarn_4'], yarnIdx: 1 },
    yarn_3: { x: 5.0, y: 0.0, z: -5.7, links: ['yarn_1', 'yarn_2'], yarnIdx: 2 },
    yarn_4: { x: 3.2, y: 0.0, z: -2.5, links: ['yarn_enter', 'yarn_1', 'yarn_2'], yarnIdx: 3 },
    bridge_w: { x: 2.3, y: 0.0, z: 2.0, links: ['plaza_c', 'plaza_s', 'bridge_m'] },
    bridge_m: { x: 5.1, y: getBridgeY(5.1), z: 2.0, links: ['bridge_w', 'bridge_e'], isBridge: true },
    bridge_e: { x: 7.9, y: 0.0, z: 2.0, links: ['bridge_m', 'pond_e', 'pond_se'] },
    pond_e: { x: 8.1, y: 0.0, z: 0.2, links: ['bridge_e'] },
    pond_se: { x: 7.7, y: 0.0, z: 3.1, links: ['bridge_e'] }
  };

  var cats = [];
  var catHitTargets = [];

  function buildCat(cfg) {
    var root = new THREE.Group();
    var awakeFace = getCatFaceTex(cfg, false);
    var sleepFace = getCatFaceTex(cfg, true);
    var bodyTex = getCatBodyTex(cfg);

    var furMat = new THREE.MeshLambertMaterial({ color: cfg.base });
    var bodyMat = new THREE.MeshLambertMaterial({ map: bodyTex });
    var earInnerMat = new THREE.MeshLambertMaterial({ color: 0xffa6bc });
    var secMat = new THREE.MeshLambertMaterial({ color: cfg.sec });
    var headFrontMat = new THREE.MeshLambertMaterial({ map: awakeFace });
    var headMats = [furMat, furMat, furMat, furMat, headFrontMat, furMat];

    // Body pivot
    var bodyGroup = new THREE.Group();
    bodyGroup.position.set(0, 0.30, 0);
    root.add(bodyGroup);

    var torso = addBox(bodyGroup, 0.38, 0.30, 0.56, 0, 0, 0, bodyMat, true, true);

    // Head pivot
    var headGroup = new THREE.Group();
    headGroup.position.set(0, 0.22, 0.28);
    bodyGroup.add(headGroup);

    addBox(headGroup, 0.40, 0.34, 0.36, 0, 0.08, 0.06, headMats, true, true);
    // Cute nose voxel
    addBox(headGroup, 0.08, 0.06, 0.05, 0, 0.04, 0.25, earInnerMat, false, false);
    // Chunky pixel ears
    var earCol = cfg.pattern === 'siamese' ? secMat : furMat;
    addBox(headGroup, 0.12, 0.14, 0.10, -0.13, 0.31, 0.04, earCol, true, true);
    addBox(headGroup, 0.12, 0.14, 0.10, 0.13, 0.31, 0.04, earCol, true, true);
    addBox(headGroup, 0.06, 0.07, 0.04, -0.13, 0.29, 0.09, earInnerMat, false, false);
    addBox(headGroup, 0.06, 0.07, 0.04, 0.13, 0.29, 0.09, earInnerMat, false, false);

    // Mayor's tiny jaunty top hat!
    var hatGroup = null;
    if (cfg.isMayor) {
      hatGroup = new THREE.Group();
      hatGroup.position.set(0, 0.27, 0.06);
      hatGroup.rotation.z = -0.1;
      var hatBlack = new THREE.MeshLambertMaterial({ color: 0x221c2a });
      var hatGold = new THREE.MeshLambertMaterial({ color: 0xffcf54 });
      addBox(hatGroup, 0.34, 0.06, 0.34, 0, 0.02, 0, hatBlack, true, true);
      addBox(hatGroup, 0.24, 0.07, 0.24, 0, 0.08, 0, hatGold, true, true);
      addBox(hatGroup, 0.22, 0.18, 0.22, 0, 0.20, 0, hatBlack, true, true);
      headGroup.add(hatGroup);
    }

    // 4 Articulated Legs
    var legCol = cfg.pattern === 'siamese' ? secMat : (cfg.pattern === 'tuxedo' ? secMat : furMat);
    function makeLeg(lx, lz) {
      var lg = new THREE.Group();
      lg.position.set(lx, 0.18, lz);
      addBox(lg, 0.11, 0.19, 0.11, 0, -0.09, 0, legCol, true, true);
      root.add(lg);
      return lg;
    }
    var legFL = makeLeg(-0.11, 0.17);
    var legFR = makeLeg(0.11, 0.17);
    var legBL = makeLeg(-0.11, -0.18);
    var legBR = makeLeg(0.11, -0.18);

    // Articulated Tail
    var tailGroup = new THREE.Group();
    tailGroup.position.set(0, 0.06, -0.28);
    bodyGroup.add(tailGroup);
    var tailCol = cfg.pattern === 'siamese' ? secMat : furMat;
    addBox(tailGroup, 0.10, 0.10, 0.26, 0, 0.05, -0.11, tailCol, true, true);
    var tailTip = new THREE.Group();
    tailTip.position.set(0, 0.06, -0.22);
    tailGroup.add(tailTip);
    addBox(tailTip, 0.09, 0.22, 0.09, 0, 0.10, -0.02, tailCol, true, true);

    // Floating Sprite Bubble (Fish / Zzz / Heart / Note)
    var bubbleMat = new THREE.SpriteMaterial({ map: TEX.iconSleep, transparent: true, opacity: 0, depthWrite: false });
    var bubble = new THREE.Sprite(bubbleMat);
    bubble.position.set(0, 1.05, 0);
    bubble.scale.set(0.46, 0.46, 0.46);
    bubble.raycast = function () {};
    root.add(bubble);

    // Generous invisible touch/click collider!
    var hitMat = new THREE.MeshBasicMaterial({
      transparent: true,
      opacity: 0,
      depthWrite: false,
      colorWrite: false
    });
    var hitSphere = new THREE.Mesh(new THREE.SphereGeometry(0.76, 8, 6), hitMat);
    hitSphere.position.set(0, 0.42, 0);
    root.add(hitSphere);

    var catObj = {
      cfg: cfg,
      group: root,
      bodyGroup: bodyGroup,
      torso: torso,
      headGroup: headGroup,
      hatGroup: hatGroup,
      headFrontMat: headFrontMat,
      awakeFace: awakeFace,
      sleepFace: sleepFace,
      legFL: legFL, legFR: legFR, legBL: legBL, legBR: legBR,
      tailGroup: tailGroup,
      tailTip: tailTip,
      bubble: bubble,
      bubbleMat: bubbleMat,
      state: 'WALK',
      stateTimer: 2 + Math.random() * 4,
      animPhase: Math.random() * 10,
      fromNode: cfg.startNode || 'plaza_c',
      toNode: cfg.startNode || 'plaza_c',
      moveT: 1,
      speed: cfg.isMayor ? 1.15 : (1.05 + Math.random() * 0.35),
      chaseTarget: null,
      shopLook: 0,
      yarnIdx: -1,
      statusText: 'Exploring Town'
    };

    root.traverse(function (obj) {
      obj.userData.cat = catObj;
    });
    catHitTargets.push(root);

    // Initial placement
    if (cfg.kind === 'shopkeeper') {
      root.position.set(cfg.pos[0], cfg.pos[1], cfg.pos[2]);
      root.rotation.y = cfg.rotY;
      catObj.state = 'SHOPKEEP';
      catObj.statusText = 'Tending Fish Stall';
    } else if (cfg.kind === 'rooftop') {
      root.position.set(cfg.roofPos[0], cfg.roofPos[1], cfg.roofPos[2]);
      root.rotation.y = cfg.roofRot;
      catObj.state = 'SLEEP';
      catObj.stateTimer = 7 + Math.random() * 8;
      catObj.statusText = 'Napping in the Sun';
    } else {
      var sn = NODES[catObj.fromNode];
      root.position.set(sn.x, sn.y, sn.z);
      pickNextNode(catObj);
    }

    islandGroup.add(root);
    cats.push(catObj);
  }

  for (var ci = 0; ci < catDefinitions.length; ci++) {
    buildCat(catDefinitions[ci]);
  }

  function pickNextNode(cat) {
    var cur = NODES[cat.toNode];
    var links = cur.links;
    var candidates = [];
    for (var i = 0; i < links.length; i++) {
      if (links[i] !== cat.fromNode || links.length === 1) candidates.push(links[i]);
    }
    var nextKey = candidates[Math.floor(Math.random() * candidates.length)];
    cat.fromNode = cat.toNode;
    cat.toNode = nextKey;
    cat.moveT = 0;
  }

  function getEdgeHeight(fromKey, toKey, t, x) {
    var nA = NODES[fromKey];
    var nB = NODES[toKey];
    if (nA.isBridge || nB.isBridge) {
      return getBridgeY(x);
    }
    return nA.y + (nB.y - nA.y) * t;
  }

  function setCatBubble(cat, tex, show, bobTime) {
    if (show && tex) {
      if (cat.bubbleMat.map !== tex) cat.bubbleMat.map = tex;
      cat.bubbleMat.opacity = 0.92;
      cat.bubble.position.y = 0.98 + Math.sin(bobTime * 3.5) * 0.08;
    } else {
      cat.bubbleMat.opacity = 0;
    }
  }

  function lerpAngle(a, b, t) {
    var diff = ((b - a + Math.PI) % (Math.PI * 2)) - Math.PI;
    if (diff < -Math.PI) diff += Math.PI * 2;
    return a + diff * t;
  }

  function updateCat(cat, dt, elapsed) {
    cat.animPhase += dt;
    cat.stateTimer -= dt;

    var cfg = cat.cfg;
    var showBubble = false;
    var bubbleTex = null;
    var isSleeping = (cat.state === 'SLEEP');

    // Swap awake / sleeping face cleanly
    var targetFace = isSleeping ? cat.sleepFace : cat.awakeFace;
    if (cat.headFrontMat.map !== targetFace) {
      cat.headFrontMat.map = targetFace;
      cat.headFrontMat.needsUpdate = true;
    }

    // Reset default pose targets
    var bodyY = 0.30;
    var bodyPitch = 0;
    var headPitch = 0;
    var headYaw = 0;
    var headY = 0.22;
    var legScaleY = 1.0;
    var legSwing = 0;
    var tailPitch = 0.35;
    var tailYaw = Math.sin(elapsed * 2.4 + cat.animPhase) * 0.25;

    if (cfg.kind === 'shopkeeper') {
      // Captain Cod tends the main fish stall
      if (cat.stateTimer <= 0) {
        cat.state = cat.state === 'STRETCH' ? 'SHOPKEEP' : (Math.random() < 0.22 ? 'STRETCH' : 'SHOPKEEP');
        cat.stateTimer = cat.state === 'STRETCH' ? 2.6 : 5 + Math.random() * 5;
      }
      if (cat.state === 'STRETCH') {
        cat.statusText = 'Big Fishmonger Stretch';
        bodyPitch = 0.38;
        headY = 0.08;
        tailPitch = 1.25;
        tailYaw = 0;
      } else {
        cat.statusText = 'Selling Fresh Fish';
        bodyY = 0.30 + Math.abs(Math.sin(elapsed * 4.2)) * 0.03;
        headYaw = Math.sin(elapsed * 1.5) * 0.2;
        if (Math.random() < 0.005) cat.stateTimer = 0;
        showBubble = Math.sin(elapsed * 0.8) > 0.45;
        bubbleTex = TEX.iconFish;
      }
    } else if (cfg.kind === 'rooftop') {
      // Rooftop cats alternate between napping in sun & waking for a stretch
      if (cat.stateTimer <= 0) {
        if (cat.state === 'SLEEP') {
          cat.state = 'STRETCH';
          cat.stateTimer = 2.8;
          cat.statusText = 'Stretching on the Roof';
        } else if (cat.state === 'STRETCH') {
          cat.state = 'LOOK';
          cat.stateTimer = 3.2;
          cat.statusText = 'Sunbathing on Roof';
        } else {
          cat.state = 'SLEEP';
          cat.stateTimer = 9 + Math.random() * 9;
          cat.statusText = 'Napping on Roof';
        }
      }
      if (cat.state === 'SLEEP') {
        bodyY = 0.16 + Math.sin(elapsed * 2.0 + cat.animPhase) * 0.015;
        legScaleY = 0.15;
        headPitch = 0.25;
        headYaw = 0.35;
        headY = 0.12;
        tailPitch = -0.15;
        tailYaw = 0.95;
        showBubble = true;
        bubbleTex = TEX.iconSleep;
      } else if (cat.state === 'STRETCH') {
        bodyPitch = 0.38;
        headY = 0.08;
        tailPitch = 1.3;
        tailYaw = 0;
      } else {
        headYaw = Math.sin(elapsed * 1.8 + cat.animPhase) * 0.45;
      }
    } else {
      // Town cats & Mayor Marmalade
      if (cat.state === 'WALK') {
        var nA = NODES[cat.fromNode];
        var nB = NODES[cat.toNode];
        var dx = nB.x - nA.x;
        var dz = nB.z - nA.z;
        var segLen = Math.max(0.2, Math.sqrt(dx * dx + dz * dz));
        cat.moveT += (cat.speed * dt) / segLen;

        if (cat.moveT >= 1) {
          cat.moveT = 1;
          cat.group.position.set(nB.x, nB.y, nB.z);
          var arrived = cat.toNode;
          var roll = Math.random();

          // Context-sensitive town behaviors at landmarks!
          if ((arrived === 'stall_1' || arrived === 'stall_2') && roll < 0.65) {
            cat.state = 'SHOP';
            cat.stateTimer = 4.2 + Math.random() * 2.8;
            cat.shopLook = NODES[arrived].shopLook || 0;
            cat.statusText = 'Shopping for Fish';
          } else if (NODES[arrived].yarnIdx !== undefined && roll < 0.62) {
            cat.state = 'YARN';
            cat.yarnIdx = NODES[arrived].yarnIdx;
            cat.stateTimer = 3.6 + Math.random() * 2.4;
            cat.statusText = 'Playing with Giant Yarn';
          } else if (arrived === 'bridge_m' && roll < 0.4) {
            cat.state = 'LOOK';
            cat.stateTimer = 2.6;
            cat.statusText = 'Watching Koi in Pond';
          } else if (roll < 0.16 && !NODES[arrived].isBridge) {
            cat.state = 'SLEEP';
            cat.stateTimer = 6.5 + Math.random() * 5.0;
            cat.statusText = 'Curled Up Sleeping';
          } else if (roll < 0.32 && !NODES[arrived].isBridge) {
            cat.state = 'STRETCH';
            cat.stateTimer = 2.6;
            cat.statusText = 'Big Cat Stretch';
          } else if (!NODES[arrived].isBridge && roll < 0.50 && (arrived.indexOf('yarn') === 0 || arrived.indexOf('plaza') === 0)) {
            // Spot a butterfly to chase!
            var bf = butterflies[Math.floor(Math.random() * butterflies.length)];
            cat.chaseTarget = bf;
            cat.state = 'CHASE';
            cat.stateTimer = 3.8 + Math.random() * 1.8;
            cat.statusText = 'Chasing a Butterfly!';
          } else {
            cat.statusText = cfg.isMayor ? 'Inspecting Town' : (NODES[arrived].isBridge ? 'Crossing Pond Bridge' : 'Strolling Around');
            pickNextNode(cat);
          }
        } else {
          var cx = nA.x + dx * cat.moveT;
          var cz = nA.z + dz * cat.moveT;
          var cy = getEdgeHeight(cat.fromNode, cat.toNode, cat.moveT, cx);
          cat.group.position.set(cx, cy, cz);
          var targetRot = Math.atan2(dx, dz);
          cat.group.rotation.y = lerpAngle(cat.group.rotation.y, targetRot, Math.min(1, dt * 10));
          legSwing = Math.sin(elapsed * 11 + cat.animPhase) * 0.55;
          bodyY = 0.30 + Math.abs(Math.sin(elapsed * 11 + cat.animPhase)) * 0.03;
          tailPitch = 0.55;
          if (NODES[cat.toNode].isBridge || NODES[cat.fromNode].isBridge) {
            cat.statusText = 'Crossing the Bridge';
          }
        }
      } else if (cat.state === 'CHASE') {
        var btf = cat.chaseTarget;
        var bpos = btf.group.position;
        var curPos = cat.group.position;
        var cdx = bpos.x - curPos.x;
        var cdz = bpos.z - curPos.z;
        var dist = Math.sqrt(cdx * cdx + cdz * cdz);
        if (dist > 0.35) {
          var step = Math.min(dist, 2.2 * dt);
          var nx = curPos.x + (cdx / dist) * step;
          var nz = curPos.z + (cdz / dist) * step;
          // Keep chase safely out of pond/cliff
          if (!isInPond(Math.round(nx), Math.round(nz)) && Math.abs(nx) < 7.8 && Math.abs(nz) < 7.8 && !isNWterrace(Math.round(nx), Math.round(nz))) {
            curPos.x = nx;
            curPos.z = nz;
          }
          cat.group.rotation.y = lerpAngle(cat.group.rotation.y, Math.atan2(cdx, cdz), Math.min(1, dt * 14));
        }
        legSwing = Math.sin(elapsed * 17 + cat.animPhase) * 0.72;
        bodyY = 0.31 + Math.abs(Math.sin(elapsed * 9 + cat.animPhase)) * 0.14; // Playful pounce hops!
        headPitch = -0.25;
        tailPitch = 0.9;
        if (cat.stateTimer <= 0) {
          // Walk smoothly back onto node path
          cat.state = 'WALK';
          var home = NODES[cat.toNode];
          NODES['temp_' + cfg.id] = { x: curPos.x, y: 0, z: curPos.z, links: [cat.toNode] };
          cat.fromNode = 'temp_' + cfg.id;
          cat.moveT = 0;
          cat.statusText = 'Catching Breath';
        }
      } else if (cat.state === 'SHOP') {
        cat.group.rotation.y = lerpAngle(cat.group.rotation.y, cat.shopLook, Math.min(1, dt * 8));
        bodyY = 0.30 + Math.abs(Math.sin(elapsed * 6.5)) * 0.04;
        headPitch = Math.sin(elapsed * 5) * 0.12;
        tailPitch = 0.95;
        showBubble = true;
        bubbleTex = TEX.iconFish;
        if (cat.stateTimer <= 0) {
          cat.state = 'WALK';
          pickNextNode(cat);
        }
      } else if (cat.state === 'YARN') {
        var yb = yarnBalls[cat.yarnIdx];
        if (yb) {
          var ydx = yb.x - cat.group.position.x;
          var ydz = yb.z - cat.group.position.z;
          cat.group.rotation.y = lerpAngle(cat.group.rotation.y, Math.atan2(ydx, ydz), Math.min(1, dt * 8));
          yb.wobble = Math.max(yb.wobble, 0.25);
        }
        // Happy paw batting!
        cat.legFL.rotation.x = -0.9 + Math.sin(elapsed * 12) * 0.55;
        cat.legFR.rotation.x = -0.2;
        tailPitch = 0.85;
        showBubble = true;
        bubbleTex = TEX.iconNote;
        if (cat.stateTimer <= 0) {
          cat.state = 'WALK';
          pickNextNode(cat);
        }
      } else if (cat.state === 'STRETCH') {
        bodyPitch = 0.38;
        headY = 0.08;
        tailPitch = 1.3;
        tailYaw = 0;
        if (cat.stateTimer <= 0) {
          cat.state = 'WALK';
          pickNextNode(cat);
        }
      } else if (cat.state === 'SLEEP') {
        bodyY = 0.16 + Math.sin(elapsed * 2.0 + cat.animPhase) * 0.014;
        legScaleY = 0.14;
        headPitch = 0.24;
        headYaw = 0.36;
        headY = 0.12;
        tailPitch = -0.15;
        tailYaw = 0.95;
        showBubble = true;
        bubbleTex = TEX.iconSleep;
        if (cat.stateTimer <= 0) {
          cat.state = 'STRETCH';
          cat.stateTimer = 2.4;
          cat.statusText = 'Waking Up Stretch!';
        }
      } else if (cat.state === 'LOOK') {
        headYaw = Math.sin(elapsed * 2.2) * 0.5;
        if (cfg.isMayor) {
          showBubble = true;
          bubbleTex = TEX.iconHeart;
        }
        if (cat.stateTimer <= 0) {
          cat.state = 'WALK';
          pickNextNode(cat);
        }
      }
    }

    // Apply pose smoothly
    cat.bodyGroup.position.y = bodyY;
    cat.bodyGroup.rotation.x = bodyPitch;
    cat.headGroup.position.y = headY;
    cat.headGroup.rotation.x = headPitch;
    cat.headGroup.rotation.y = headYaw;
    if (cat.hatGroup) {
      cat.hatGroup.rotation.x = Math.sin(elapsed * 4 + cat.animPhase) * 0.04;
    }

    cat.legFL.scale.y = legScaleY;
    cat.legFR.scale.y = legScaleY;
    cat.legBL.scale.y = legScaleY;
    cat.legBR.scale.y = legScaleY;

    if (cat.state !== 'YARN') {
      cat.legFL.rotation.x = legSwing;
      cat.legBR.rotation.x = legSwing;
      cat.legFR.rotation.x = -legSwing;
      cat.legBL.rotation.x = -legSwing;
    } else {
      cat.legBL.rotation.x = 0;
      cat.legBR.rotation.x = 0;
    }

    cat.tailGroup.rotation.x = tailPitch;
    cat.tailGroup.rotation.y = tailYaw;

    setCatBubble(cat, bubbleTex, showBubble, elapsed);
  }

  /* =========================
     9. TIME OF DAY ENGINE
     ========================= */
  var THEMES = {
    day: {
      skyTop: new THREE.Color(0x3788dd),
      skyMid: new THREE.Color(0x70c0f8),
      skyHoriz: new THREE.Color(0xc9f0ff),
      skyBot: new THREE.Color(0x88cbef),
      fog: new THREE.Color(0xb6e7ff),
      fogDensity: 0.011,
      dirColor: new THREE.Color(0xfff6de),
      dirIntensity: 1.15,
      dirPos: new THREE.Vector3(14, 23, 12),
      hemiSky: new THREE.Color(0xc6e9ff),
      hemiGround: new THREE.Color(0x5b7c46),
      hemiIntensity: 0.85,
      cloudCol: new THREE.Color(0xffffff),
      nightFactor: 0.0,
      winGlow: 0.0,
      lanternGlow: 0.04,
      pointLight: 0.0,
      sunVis: 1.0,
      sunPos: new THREE.Vector3(24, 34, 18),
      sunCol: new THREE.Color(0xffe67a),
      moonVis: 0.0,
      moonPos: new THREE.Vector3(-24, -15, -18),
      firefly: 0.0
    },
    sunset: {
      skyTop: new THREE.Color(0x3f2d6d),
      skyMid: new THREE.Color(0xb84f6f),
      skyHoriz: new THREE.Color(0xff9d54),
      skyBot: new THREE.Color(0x6b3a69),
      fog: new THREE.Color(0xe68f68),
      fogDensity: 0.014,
      dirColor: new THREE.Color(0xff9e54),
      dirIntensity: 1.05,
      dirPos: new THREE.Vector3(-19, 10, -14),
      hemiSky: new THREE.Color(0xffa97a),
      hemiGround: new THREE.Color(0x4f3959),
      hemiIntensity: 0.72,
      cloudCol: new THREE.Color(0xffc9a8),
      nightFactor: 0.25,
      winGlow: 0.55,
      lanternGlow: 0.65,
      pointLight: 0.55,
      sunVis: 1.0,
      sunPos: new THREE.Vector3(-34, 9, -24),
      sunCol: new THREE.Color(0xff843b),
      moonVis: 0.45,
      moonPos: new THREE.Vector3(24, 18, 22),
      firefly: 0.25
    },
    night: {
      skyTop: new THREE.Color(0x0b1024),
      skyMid: new THREE.Color(0x161f42),
      skyHoriz: new THREE.Color(0x283361),
      skyBot: new THREE.Color(0x121936),
      fog: new THREE.Color(0x1d264d),
      fogDensity: 0.015,
      dirColor: new THREE.Color(0x88a8ff),
      dirIntensity: 0.48,
      dirPos: new THREE.Vector3(-13, 21, -11),
      hemiSky: new THREE.Color(0x3b4d8c),
      hemiGround: new THREE.Color(0x1b1d30),
      hemiIntensity: 0.46,
      cloudCol: new THREE.Color(0x525d88),
      nightFactor: 1.0,
      winGlow: 1.25,
      lanternGlow: 1.55,
      pointLight: 1.55,
      sunVis: 0.0,
      sunPos: new THREE.Vector3(-25, -18, -15),
      sunCol: new THREE.Color(0xff6b3b),
      moonVis: 1.0,
      moonPos: new THREE.Vector3(-20, 26, -18),
      firefly: 1.0
    }
  };

  var currentMode = 'day';
  var curState = {
    skyTop: THEMES.day.skyTop.clone(),
    skyMid: THEMES.day.skyMid.clone(),
    skyHoriz: THEMES.day.skyHoriz.clone(),
    skyBot: THEMES.day.skyBot.clone(),
    fog: THEMES.day.fog.clone(),
    fogDensity: THEMES.day.fogDensity,
    dirColor: THEMES.day.dirColor.clone(),
    dirIntensity: THEMES.day.dirIntensity,
    dirPos: THEMES.day.dirPos.clone(),
    hemiSky: THEMES.day.hemiSky.clone(),
    hemiGround: THEMES.day.hemiGround.clone(),
    hemiIntensity: THEMES.day.hemiIntensity,
    cloudCol: THEMES.day.cloudCol.clone(),
    nightFactor: THEMES.day.nightFactor,
    winGlow: THEMES.day.winGlow,
    lanternGlow: THEMES.day.lanternGlow,
    pointLight: THEMES.day.pointLight,
    sunVis: THEMES.day.sunVis,
    sunPos: THEMES.day.sunPos.clone(),
    sunCol: THEMES.day.sunCol.clone(),
    moonVis: THEMES.day.moonVis,
    moonPos: THEMES.day.moonPos.clone(),
    firefly: THEMES.day.firefly
  };

  var timeBtns = document.querySelectorAll('.time-btn');
  function setTimeOfDay(mode, silent) {
    if (!THEMES[mode] || currentMode === mode) return;
    currentMode = mode;
    for (var i = 0; i < timeBtns.length; i++) {
      timeBtns[i].classList.toggle('active', timeBtns[i].getAttribute('data-time') === mode);
    }
    if (!silent) playChime(mode);
  }

  for (var bi2 = 0; bi2 < timeBtns.length; bi2++) {
    (function (btn) {
      btn.addEventListener('click', function () {
        cancelDemo();
        setTimeOfDay(btn.getAttribute('data-time'), false);
      });
    })(timeBtns[bi2]);
  }

  function updateAtmosphere(dt, elapsed) {
    var tgt = THEMES[currentMode];
    var k = Math.min(1, dt * 2.8);

    curState.skyTop.lerp(tgt.skyTop, k);
    curState.skyMid.lerp(tgt.skyMid, k);
    curState.skyHoriz.lerp(tgt.skyHoriz, k);
    curState.skyBot.lerp(tgt.skyBot, k);
    curState.fog.lerp(tgt.fog, k);
    curState.fogDensity += (tgt.fogDensity - curState.fogDensity) * k;

    curState.dirColor.lerp(tgt.dirColor, k);
    curState.dirIntensity += (tgt.dirIntensity - curState.dirIntensity) * k;
    curState.dirPos.lerp(tgt.dirPos, k);

    curState.hemiSky.lerp(tgt.hemiSky, k);
    curState.hemiGround.lerp(tgt.hemiGround, k);
    curState.hemiIntensity += (tgt.hemiIntensity - curState.hemiIntensity) * k;

    curState.cloudCol.lerp(tgt.cloudCol, k);
    curState.nightFactor += (tgt.nightFactor - curState.nightFactor) * k;
    curState.winGlow += (tgt.winGlow - curState.winGlow) * k;
    curState.lanternGlow += (tgt.lanternGlow - curState.lanternGlow) * k;
    curState.pointLight += (tgt.pointLight - curState.pointLight) * k;
    curState.sunVis += (tgt.sunVis - curState.sunVis) * k;
    curState.sunPos.lerp(tgt.sunPos, k);
    curState.sunCol.lerp(tgt.sunCol, k);
    curState.moonVis += (tgt.moonVis - curState.moonVis) * k;
    curState.moonPos.lerp(tgt.moonPos, k);
    curState.firefly += (tgt.firefly - curState.firefly) * k;

    skyUniforms.uTop.value.copy(curState.skyTop);
    skyUniforms.uMid.value.copy(curState.skyMid);
    skyUniforms.uHoriz.value.copy(curState.skyHoriz);
    skyUniforms.uBot.value.copy(curState.skyBot);
    skyUniforms.uNight.value = curState.nightFactor;
    skyUniforms.uTime.value = elapsed;

    scene.fog.color.copy(curState.fog);
    scene.fog.density = curState.fogDensity;

    dirLight.color.copy(curState.dirColor);
    dirLight.intensity = curState.dirIntensity;
    dirLight.position.copy(curState.dirPos);

    hemiLight.color.copy(curState.hemiSky);
    hemiLight.groundColor.copy(curState.hemiGround);
    hemiLight.intensity = curState.hemiIntensity;

    windowMat.emissiveIntensity = curState.winGlow;
    lanternGlowMat.emissiveIntensity = curState.lanternGlow;

    for (var pi = 0; pi < nightPointLights.length; pi++) {
      var flicker = 1.0 + Math.sin(elapsed * 5.2 + pi * 1.9) * 0.08;
      nightPointLights[pi].intensity = curState.pointLight * flicker;
    }

    for (var ci2 = 0; ci2 < cloudMaterials.length; ci2++) {
      cloudMaterials[ci2].color.copy(curState.cloudCol);
    }

    sunGroup.position.copy(camera.position).add(curState.sunPos);
    sunGroup.visible = curState.sunVis > 0.05;
    sunGroup.scale.setScalar(Math.max(0.01, curState.sunVis));
    sunMat.color.copy(curState.sunCol);

    moonGroup.position.copy(camera.position).add(curState.moonPos);
    moonGroup.visible = curState.moonVis > 0.05;
    moonGroup.scale.setScalar(Math.max(0.01, curState.moonVis));
    moonGroup.lookAt(camera.position);

    fireflyMat.opacity = curState.firefly * (0.6 + 0.4 * Math.sin(elapsed * 3.8));
  }

  /* =========================
     10. CAMERA, ORBIT, PINCH, FOLLOW
     ========================= */
  var camState = {
    azimuth: 0.72,
    targetAzimuth: 0.72,
    polar: 1.02,
    targetPolar: 1.02,
    distance: 21.5,
    targetDistance: 21.5,
    lookAt: new THREE.Vector3(0, 0.35, 0),
    targetLookAt: new THREE.Vector3(0, 0.35, 0)
  };

  var followedCat = null;
  var followBar = document.getElementById('follow-bar');

  function updateFollowHUD() {
    if (!followedCat) {
      followBar.className = 'follow-bar idle';
      followBar.innerHTML = 'Drag to spin · Pinch/scroll to zoom · Tap a cat to follow';
      return;
    }
    followBar.className = 'follow-bar';
    followBar.innerHTML = '';

    var sw = document.createElement('div');
    sw.className = 'cat-swatch';
    sw.style.backgroundColor = followedCat.cfg.swatch;

    var meta = document.createElement('div');
    meta.className = 'follow-meta';

    var nm = document.createElement('div');
    nm.className = 'follow-name';
    nm.textContent = (followedCat.cfg.isMayor ? '👑 ' : '🐾 ') + followedCat.cfg.name + ' · ' + followedCat.cfg.role;

    var st = document.createElement('div');
    st.className = 'follow-state';
    st.id = 'follow-status-text';
    st.textContent = followedCat.statusText;

    meta.appendChild(nm);
    meta.appendChild(st);

    var btn = document.createElement('button');
    btn.className = 'unfollow-btn';
    btn.type = 'button';
    btn.textContent = '✕ Overview';
    btn.addEventListener('click', function () {
      cancelDemo();
      unfollowCat();
    });

    followBar.appendChild(sw);
    followBar.appendChild(meta);
    followBar.appendChild(btn);
  }

  function followCat(cat, silent) {
    followedCat = cat;
    if (camState.targetDistance > 11.5) {
      camState.targetDistance = 8.4;
    }
    if (!silent) playMeow(cat.cfg.isMayor ? 480 : 620);
    updateFollowHUD();
  }

  function unfollowCat() {
    followedCat = null;
    camState.targetLookAt.set(0, 0.35, 0);
    if (camState.targetDistance < 13) {
      camState.targetDistance = 21.0;
    }
    updateFollowHUD();
  }

  // Pointer & Pinch Input
  var activePointers = new Map();
  var downInfo = null;
  var prevPinchDist = 0;
  var raycaster = new THREE.Raycaster();

  function getPinchDist() {
    var pts = Array.from(activePointers.values());
    var dx = pts[0].x - pts[1].x;
    var dy = pts[0].y - pts[1].y;
    return Math.sqrt(dx * dx + dy * dy);
  }

  canvas.addEventListener('pointerdown', function (e) {
    cancelDemo();
    activePointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
    try { canvas.setPointerCapture(e.pointerId); } catch (err) {}

    if (activePointers.size === 1) {
      downInfo = {
        id: e.pointerId,
        startX: e.clientX,
        startY: e.clientY,
        lastX: e.clientX,
        lastY: e.clientY,
        moved: 0,
        time: performance.now(),
        wasMulti: false
      };
    } else if (activePointers.size === 2) {
      if (downInfo) downInfo.wasMulti = true;
      prevPinchDist = getPinchDist();
    }
  });

  canvas.addEventListener('pointermove', function (e) {
    if (!activePointers.has(e.pointerId)) return;
    activePointers.set(e.pointerId, { x: e.clientX, y: e.clientY });

    if (activePointers.size === 1 && downInfo && downInfo.id === e.pointerId && !downInfo.wasMulti) {
      var dx = e.clientX - downInfo.lastX;
      var dy = e.clientY - downInfo.lastY;
      downInfo.moved += Math.abs(dx) + Math.abs(dy);
      downInfo.lastX = e.clientX;
      downInfo.lastY = e.clientY;

      camState.targetAzimuth -= dx * 0.0082;
      camState.targetPolar = Math.max(0.28, Math.min(1.46, camState.targetPolar - dy * 0.0068));
    } else if (activePointers.size === 2) {
      var dist = getPinchDist();
      if (prevPinchDist > 0 && dist > 0) {
        var ratio = prevPinchDist / dist;
        camState.targetDistance = Math.max(5.0, Math.min(31.0, camState.targetDistance * ratio));
      }
      prevPinchDist = dist;
    }
  });

  function onPointerFinish(e) {
    var wasTap = false;
    var tapX = e.clientX, tapY = e.clientY;
    if (downInfo && downInfo.id === e.pointerId && !downInfo.wasMulti) {
      var dtTap = performance.now() - downInfo.time;
      if (downInfo.moved < 10 && dtTap < 380) {
        wasTap = true;
      }
    }
    activePointers.delete(e.pointerId);
    if (activePointers.size < 2) prevPinchDist = 0;
    if (activePointers.size === 0) downInfo = null;

    if (wasTap) {
      handleTap(tapX, tapY);
    }
  }

  canvas.addEventListener('pointerup', onPointerFinish);
  canvas.addEventListener('pointercancel', onPointerFinish);

  canvas.addEventListener('wheel', function (e) {
    e.preventDefault();
    cancelDemo();
    var factor = 1 + Math.sign(e.deltaY) * 0.09;
    camState.targetDistance = Math.max(5.0, Math.min(31.0, camState.targetDistance * factor));
  }, { passive: false });

  function handleTap(clientX, clientY) {
    var rect = canvas.getBoundingClientRect();
    var ndc = new THREE.Vector2(
      ((clientX - rect.left) / rect.width) * 2 - 1,
      -((clientY - rect.top) / rect.height) * 2 + 1
    );
    raycaster.setFromCamera(ndc, camera);
    var hits = raycaster.intersectObjects(catHitTargets, true);
    if (hits.length > 0) {
      var obj = hits[0].object;
      while (obj && !obj.userData.cat) obj = obj.parent;
      if (obj && obj.userData.cat) {
        followCat(obj.userData.cat, false);
        return;
      }
    }
    if (followedCat) {
      unfollowCat();
    }
  }

  /* =========================
     11. #DEMO 20s AUTO TOUR
     ========================= */
  var demoActive = false;
  var demoStartTime = 0;
  var demoPill = document.getElementById('demo-pill');
  var DEMO_DURATION = 20.0;

  try {
    var href = String(window.location.href || '');
    var hash = String(window.location.hash || '');
    if (hash.toLowerCase() === '#demo' || href.toLowerCase().slice(-5) === '#demo') {
      demoActive = true;
      demoPill.classList.add('active');
    }
  } catch (e) {}

  function cancelDemo() {
    if (!demoActive) return;
    demoActive = false;
    demoPill.classList.remove('active');
  }

  // Any real user touch / pointer / wheel ends #demo immediately
  window.addEventListener('pointerdown', cancelDemo, { capture: true, passive: true });
  window.addEventListener('touchstart', cancelDemo, { capture: true, passive: true });
  window.addEventListener('wheel', cancelDemo, { capture: true, passive: true });
  window.addEventListener('keydown', cancelDemo, { capture: true, passive: true });

  function findCatById(id) {
    for (var i = 0; i < cats.length; i++) {
      if (cats[i].cfg.id === id) return cats[i];
    }
    return cats[0];
  }

  function updateDemo(elapsed) {
    if (!demoActive) return;
    var t = (elapsed - demoStartTime) % DEMO_DURATION;

    if (t < 4.5) {
      // Phase 1 (0 - 4.5s): Bright Day Floating Island Overview & Clouds Below
      setTimeOfDay('day', true);
      if (followedCat) unfollowCat();
      camState.targetAzimuth = 0.55 + (t / 4.5) * 1.1;
      camState.targetPolar = 1.12;
      camState.targetDistance = 21.5;
      camState.targetLookAt.set(0, 0.2, 0);
    } else if (t < 9.5) {
      // Phase 2 (4.5 - 9.5s): Follow Mayor Marmalade & View Fish Market Striped Awnings
      setTimeOfDay('day', true);
      var mayor = findCatById('mayor');
      if (followedCat !== mayor) followCat(mayor, true);
      camState.targetAzimuth = 1.65 + ((t - 4.5) / 5.0) * 1.3;
      camState.targetPolar = 1.0;
      camState.targetDistance = 8.8;
    } else if (t < 14.0) {
      // Phase 3 (9.5 - 14.0s): Sunset Glow over Yarn Park & Small Pond Bridge
      setTimeOfDay('sunset', true);
      var mochi = findCatById('mochi');
      if (followedCat !== mochi) followCat(mochi, true);
      camState.targetAzimuth = 2.95 + ((t - 9.5) / 4.5) * 1.35;
      camState.targetPolar = 1.05;
      camState.targetDistance = 10.5;
    } else if (t < 18.2) {
      // Phase 4 (14.0 - 18.2s): Nighttime Glowing Windows & Lanterns + Rooftop Napper
      setTimeOfDay('night', true);
      var sunny = findCatById('sunny');
      if (followedCat !== sunny) followCat(sunny, true);
      camState.targetAzimuth = 4.3 + ((t - 14.0) / 4.2) * 1.1;
      camState.targetPolar = 0.98;
      camState.targetDistance = 8.6;
    } else {
      // Phase 5 (18.2 - 20.0s): Pull back smoothly over glowing island & clouds
      setTimeOfDay('night', true);
      if (followedCat) unfollowCat();
      camState.targetAzimuth = 5.4 + ((t - 18.2) / 1.8) * 1.43;
      camState.targetPolar = 1.1;
      camState.targetDistance = 21.5;
      camState.targetLookAt.set(0, 0.2, 0);
    }
  }

  /* =========================
     12. MAIN ANIMATION LOOP
     ========================= */
  var lastTime = performance.now();
  var elapsed = 0;
  var statusTick = 0;

  function animate(now) {
    requestAnimationFrame(animate);
    var dt = Math.min(0.05, Math.max(0.001, (now - lastTime) * 0.001));
    lastTime = now;
    elapsed += dt;

    if (demoActive) {
      updateDemo(elapsed);
    }

    // Subtle floating island bob
    islandGroup.position.y = Math.sin(elapsed * 0.9) * 0.14;
    for (var ii2 = 0; ii2 < miniIslets.length; ii2++) {
      var mi = miniIslets[ii2];
      mi.group.position.y = mi.baseY + Math.sin(elapsed * 1.4 + mi.phase) * 0.18;
    }

    // Animate water & waterfall scroll
    waterTex.offset.x = (elapsed * 0.07) % 1;
    waterTex.offset.y = (elapsed * 0.04) % 1;
    waterfallTex.offset.y = (elapsed * 0.85) % 1;

    // Waterfall mist bounce
    for (var mIdx = 0; mIdx < mistCubes.length; mIdx++) {
      var mc = mistCubes[mIdx];
      var mT = (elapsed * 1.6 + mc.phase) % 1;
      mc.mesh.position.y = -6.5 - mT * 1.3;
      mc.mesh.position.z = mc.baseZ + Math.sin(elapsed * 3 + mc.phase) * 0.18;
      mc.mesh.scale.setScalar(1.0 - mT * 0.65);
    }

    // Chimney smoke rising
    for (var si2 = 0; si2 < smokePuffs.length; si2++) {
      var sp = smokePuffs[si2];
      var st = (elapsed * 0.45 + sp.phase) % 1;
      sp.mesh.position.y = sp.by + st * 1.65;
      sp.mesh.position.x = sp.bx + Math.sin(elapsed * 1.5 + sp.phase) * 0.14;
      sp.mesh.scale.setScalar(0.75 + st * 0.85);
      sp.mesh.material.opacity = (1.0 - st) * 0.55;
    }

    // Koi fish swimming
    for (var ki2 = 0; ki2 < koiFish.length; ki2++) {
      var kf = koiFish[ki2];
      var ka = elapsed * kf.speed + kf.phase;
      var kx = kf.cx + Math.cos(ka) * kf.rx;
      var kz = kf.cz + Math.sin(ka * 1.2) * kf.rz;
      var dx = -Math.sin(ka) * kf.rx * kf.speed;
      var dz = Math.cos(ka * 1.2) * kf.rz * kf.speed * 1.2;
      kf.group.position.set(kx, -0.38, kz);
      kf.group.rotation.y = Math.atan2(dx, dz);
    }

    // Butterflies fluttering
    for (var bfi = 0; bfi < butterflies.length; bfi++) {
      var bf = butterflies[bfi];
      var ba = elapsed * bf.speed + bf.phase;
      var bx = bf.cx + Math.cos(ba) * bf.rx + Math.sin(ba * 2.1) * 0.35;
      var bz = bf.cz + Math.sin(ba * 1.3) * bf.rz;
      var by = 0.85 + Math.sin(elapsed * 3.4 + bf.phase) * 0.25;
      bf.group.position.set(bx, by, bz);
      var flap = Math.sin(elapsed * 22 + bf.phase) * 0.9;
      bf.lw.rotation.z = flap;
      bf.rw.rotation.z = -flap;
      bf.group.rotation.y = ba + Math.PI * 0.5;
    }

    // Fireflies at night
    for (var ffi2 = 0; ffi2 < fireflies.length; ffi2++) {
      var ff = fireflies[ffi2];
      ff.mesh.position.set(
        ff.bx + Math.sin(elapsed * 1.4 + ff.phase) * 0.45,
        ff.by + Math.cos(elapsed * 2.1 + ff.phase) * 0.28,
        ff.bz + Math.cos(elapsed * 1.2 + ff.phase) * 0.45
      );
    }

    // Giant Yarn Balls wobble when played with
    for (var ybi = 0; ybi < yarnBalls.length; ybi++) {
      var yb = yarnBalls[ybi];
      if (yb.wobble > 0.001) {
        yb.group.rotation.z = Math.sin(elapsed * 14) * yb.wobble;
        yb.group.rotation.x = Math.cos(elapsed * 11) * yb.wobble * 0.7;
        yb.wobble *= Math.max(0, 1 - dt * 2.5);
      } else {
        yb.group.rotation.z *= 0.9;
        yb.group.rotation.x *= 0.9;
      }
    }

    // Clouds drifting below the island!
    for (var cli = 0; cli < clouds.length; cli++) {
      var cl = clouds[cli];
      cl.group.position.x += cl.speed * dt;
      if (cl.group.position.x > 34) cl.group.position.x = -34;
      cl.group.position.y = cl.baseY + Math.sin(elapsed * 0.65 + cl.phase) * 0.22;
    }

    // Update all 13 cats
    for (var cti = 0; cti < cats.length; cti++) {
      updateCat(cats[cti], dt, elapsed);
    }

    // Update live follow status text periodically
    if (followedCat) {
      camState.targetLookAt.set(
        followedCat.group.position.x,
        followedCat.group.position.y + islandGroup.position.y + 0.52,
        followedCat.group.position.z
      );
      statusTick += dt;
      if (statusTick > 0.25) {
        statusTick = 0;
        var stEl = document.getElementById('follow-status-text');
        if (stEl && stEl.textContent !== followedCat.statusText) {
          stEl.textContent = followedCat.statusText;
        }
      }
    }

    // Smooth camera orbit & follow damping
    var camK = Math.min(1, dt * 7.5);
    camState.azimuth += (camState.targetAzimuth - camState.azimuth) * camK;
    camState.polar += (camState.targetPolar - camState.polar) * camK;
    camState.distance += (camState.targetDistance - camState.distance) * camK;
    camState.lookAt.lerp(camState.targetLookAt, Math.min(1, dt * 5.8));

    var sinP = Math.sin(camState.polar);
    camera.position.set(
      camState.lookAt.x + camState.distance * sinP * Math.sin(camState.azimuth),
      camState.lookAt.y + camState.distance * Math.cos(camState.polar),
      camState.lookAt.z + camState.distance * sinP * Math.cos(camState.azimuth)
    );
    camera.lookAt(camState.lookAt);

    skyDome.position.copy(camera.position);

    // Update day/sunset/night atmosphere
    updateAtmosphere(dt, elapsed);

    renderer.render(scene, camera);
  }

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