Skip to content
VibeCodeBench
Back to the app

The code

Lantern Cats by GPT-6.2 Sol

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.)70.5 KB · 2,003 lines · no libraries
Download
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="theme-color" content="#080e1c">
<title>Lantern Tide</title>
<style>
  :root {
    color-scheme: dark;
    --ink: #fff4df;
    --muted: #c8cccf;
    --gold: #ffcd95;
    --inset: clamp(20px, 3.5vw, 60px);
    --top: clamp(22px, 4.5vh, 48px);
    font: 14px/1.35 system-ui, -apple-system, "Segoe UI", sans-serif;
  }
  * { box-sizing: border-box; }
  html, body { margin: 0; width: 100%; height: 100%; overflow: hidden; background: #080e1c; }
  body { color: var(--ink); overscroll-behavior: none; }
  #festival, .lens { position: fixed; inset: 0; width: 100%; height: 100%; }
  #festival { display: block; touch-action: none; cursor: grab; }
  #festival:active { cursor: grabbing; }
  .lens {
    pointer-events: none;
    background:
      linear-gradient(0deg, rgba(4, 8, 17, .66), transparent 19%),
      radial-gradient(ellipse at 51% 47%, transparent 43%, rgba(3, 7, 18, .35) 100%);
  }
  .masthead {
    position: fixed;
    top: calc(var(--top) + env(safe-area-inset-top));
    left: calc(var(--inset) + env(safe-area-inset-left));
    pointer-events: none;
    user-select: none;
  }
  .festival-mark {
    display: flex;
    align-items: center;
    gap: 10px;
    color: var(--gold);
    font-size: 10px;
    font-weight: 620;
    letter-spacing: .26em;
    text-transform: uppercase;
  }
  .festival-mark svg { width: 18px; height: 25px; }
  h1 {
    margin: 8px 0 0;
    font: 400 clamp(46px, 5.5vw, 88px)/.95 "Iowan Old Style", Baskerville, Georgia, serif;
    letter-spacing: -.071em;
    text-shadow: 0 4px 36px #060c18;
  }
  h1 em { color: var(--gold); font-weight: 400; letter-spacing: -.082em; }
  .sound {
    position: fixed;
    top: calc(var(--top) + env(safe-area-inset-top));
    right: calc(var(--inset) + env(safe-area-inset-right));
  }
  .dock {
    position: fixed;
    bottom: calc(clamp(18px, 3.7vh, 38px) + env(safe-area-inset-bottom));
    left: calc(var(--inset) + env(safe-area-inset-left));
    right: calc(var(--inset) + env(safe-area-inset-right));
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    pointer-events: none;
  }
  .pill, .hint {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 9px;
    min-height: 48px;
    padding: 0 15px;
    border: 1px solid rgba(224, 230, 244, .19);
    border-radius: 50px;
    background: rgba(9, 17, 30, .77);
    box-shadow: inset 0 1px rgba(255, 255, 255, .05), 0 6px 24px rgba(1, 5, 13, .28);
    -webkit-backdrop-filter: blur(12px);
    backdrop-filter: blur(12px);
    white-space: nowrap;
    font-family: inherit;
    font-size: 12px;
    font-weight: 570;
    letter-spacing: .015em;
  }
  .pill { color: var(--ink); cursor: pointer; pointer-events: auto; touch-action: manipulation; }
  .pill:focus-visible { outline: 2px solid var(--gold); outline-offset: 4px; }
  .pill:active { background: #243044; }
  .pill[aria-pressed="true"] { color: var(--gold); border-color: rgba(255, 205, 149, .4); }
  .pill svg, .hint svg { width: 18px; height: 18px; flex: none; }
  .hint { color: var(--muted); }
  .hint svg { color: var(--gold); }
  .hint.silver svg { color: #d4edfc; }
  .hint.amber, .hint.silver { color: var(--ink); }
  .sound .playing, .demo .stop { display: none; }
  .sound[aria-pressed="true"] .playing, .demo[aria-pressed="true"] .stop { display: inline; }
  .sound[aria-pressed="true"] .quiet, .demo[aria-pressed="true"] .play { display: none; }
  @media (hover: hover) {
    .pill:hover { border-color: rgba(255, 222, 181, .58); background: rgba(22, 32, 49, .92); }
  }
  @media (max-width: 520px) {
    .pill, .hint { padding: 0 12px; gap: 7px; font-size: 11px; }
    .festival-mark { font-size: 9px; gap: 7px; }
    .festival-mark svg { width: 15px; height: 21px; }
    h1 { margin-top: 10px; }
  }
  @media (max-width: 340px) {
    :root { --inset: 12px; }
    h1 { font-size: 40px; }
    .pill, .hint { padding-inline: 10px; }
  }
</style>
</head>
<body>
<canvas id="festival" role="img" aria-label="An amber and a silver paper lantern cat fly over a riverside town at night."></canvas>
<div class="lens" aria-hidden="true"></div>
<header class="masthead">
  <div class="festival-mark">
    <svg viewBox="0 0 18 25" fill="none" stroke="currentColor" stroke-width="1.1" aria-hidden="true">
      <path d="M9 0v4m-4 1h8l3 4v7l-3 4H5l-3-4V9l3-4Zm0 1c-2 5-2 9 0 13m4-13c2 5 2 9 0 13M9 6v13m0 2v4m-2-3h4"/>
    </svg>
    <span>River festival</span>
  </div>
  <h1>Lantern <em>Tide</em></h1>
</header>
<button class="pill sound" type="button" aria-pressed="false" aria-label="Unmute melody">
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
    <path d="M4 9v6h4l5 4V5L8 9H4Z"/>
    <path class="quiet" d="m17 10 4 4m0-4-4 4"/>
    <path class="playing" d="M16 9a4 4 0 0 1 0 6m3-8a7 7 0 0 1 0 10"/>
  </svg>
  <span>Sound off</span>
</button>
<div class="dock">
  <div class="hint" role="status">
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
      <path d="M10 7a4 4 0 0 1 6 3m-8 1a5 5 0 1 1 9-4M19 16l-5-5-2 9 2.7-2.7L19 16Z"/>
      <path d="M5 7H3m4-4V1"/>
    </svg>
    <span>Drag to guide a cat</span>
  </div>
  <button class="pill demo" type="button" aria-pressed="false">
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.55" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
      <path class="play" d="m9 5 11 7-11 7V5Z"/>
      <path class="stop" d="M7 7h10v10H7z"/>
    </svg>
    <span>Play demo</span>
  </button>
</div>

<script>
(() => {
  'use strict';

  const canvas = document.querySelector('#festival');
  const screen = canvas.getContext('2d', { alpha: false });
  const soundButton = document.querySelector('.sound');
  const demoButton = document.querySelector('.demo');
  const hint = document.querySelector('.hint');
  const hintText = hint.querySelector('span');
  const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)');
  const TAU = Math.PI * 2;
  const H = 900;
  const bodyEnd = 24;
  const tailEnd = 32;

  const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
  const mix = (a, b, t) => a + (b - a) * t;
  const mod = (x, n) => (x % n + n) % n;
  const smooth = x => {
    const u = clamp(x, 0, 1);
    return u * u * (3 - 2 * u);
  };

  function random(seed) {
    return () => {
      seed = (seed + 0x6D2B79F5) | 0;
      let z = Math.imul(seed ^ seed >>> 15, 1 | seed);
      z ^= z + Math.imul(z ^ z >>> 7, 61 | z);
      return ((z ^ z >>> 14) >>> 0) / 4294967296;
    };
  }

  function bitmap(w, h, scale = 1) {
    const image = document.createElement('canvas');
    image.width = Math.max(1, Math.ceil(w * scale));
    image.height = Math.max(1, Math.ceil(h * scale));
    const g = image.getContext('2d');
    g.setTransform(image.width / w, 0, 0, image.height / h, 0, 0);
    return { image, g };
  }

  function glowMap(rgb) {
    const { image, g } = bitmap(96, 96);
    const halo = g.createRadialGradient(48, 48, 0, 48, 48, 48);
    halo.addColorStop(0, 'rgba(' + rgb + ',.77)');
    halo.addColorStop(.18, 'rgba(' + rgb + ',.43)');
    halo.addColorStop(.48, 'rgba(' + rgb + ',.13)');
    halo.addColorStop(1, 'rgba(' + rgb + ',0)');
    g.fillStyle = halo;
    g.fillRect(0, 0, 96, 96);
    return image;
  }

  function glow(g, map, x, y, rx, ry, alpha) {
    const saved = g.globalAlpha;
    g.globalAlpha = saved * clamp(alpha, 0, 1);
    g.drawImage(map, x - rx, y - ry, 2 * rx, 2 * ry);
    g.globalAlpha = saved;
  }

  function dot(g, x, y, radius, color) {
    g.fillStyle = color;
    g.beginPath();
    g.arc(x, y, radius, 0, TAU);
    g.fill();
  }

  const warmHalo = glowMap('255,153,75');
  const redHalo = glowMap('255,92,57');
  const blueHalo = glowMap('151,205,242');
  const moonHalo = glowMap('242,204,147');
  const catColors = [
    {
      name: 'Amber', tone: 'amber', halo: warmHalo,
      pale: '#ffedbc', light: '#ffcf82', middle: '#ed8c46', shade: '#ae4629',
      rim: '#783723', seam: '#ffd899', band: '#bb582f', ink: '#442936',
      iris: '#f6b05c', whisker: '#ffe1a8', paw: '#bc5833'
    },
    {
      name: 'Silver', tone: 'silver', halo: blueHalo,
      pale: '#fbf6e8', light: '#d8e8e9', middle: '#a6becd', shade: '#60798e',
      rim: '#324b60', seam: '#edf5ed', band: '#738fa5', ink: '#243448',
      iris: '#aee0df', whisker: '#e1f4f3', paw: '#6e899e'
    }
  ];

  let W = 1440, unit = 1, narrow = 0, houseUnit = 1, pixels = 1;
  let backing, stage, water, waterside, reflectionLights = [];
  let garlands = [], floaters = [], sparks = [], currents = [];
  let rail, cats = [], spacings = [], radii = [];
  let time = 0, elapsedDemo = location.hash === '#demo' ? 0 : null;
  let gesture = null, pointer = null, needsResize = true;
  let camera = { zoom: 1, x: 0, y: 0 };

  function roofLimit(x) {
    return 559 - 97 * Math.pow(Math.abs(2 * clamp(x / W, 0, 1) - 1), 1.7);
  }

  function fitToSky(point, radius) {
    const edge = radius + 9 * unit;
    point.x = clamp(point.x, edge, W - edge);
    point.y = clamp(point.y, 156 + 73 * narrow + radius, roofLimit(point.x) - radius);
    return point;
  }

  function shore(y, side) {
    const t = Math.max(0, (y - 594) / 306);
    const center = .514 + .012 * t - .038 * Math.sin(t * Math.PI);
    const width = .034 + .335 * Math.pow(t, .88);
    const stones = .0015 * Math.sin(y * .061 + side);
    return W * (center + side * (width + stones));
  }

  function channelPath() {
    const path = new Path2D();
    path.moveTo(shore(594, -1), 594);
    for (let y = 597; y <= H + 6; y += 3) path.lineTo(shore(y, -1), y);
    for (let y = H + 6; y >= 594; y -= 3) path.lineTo(shore(y, 1), y);
    path.closePath();
    return path;
  }

  function sky(g, rng) {
    const backdrop = g.createLinearGradient(0, 0, 0, H);
    backdrop.addColorStop(0, '#080e1e');
    backdrop.addColorStop(.28, '#101b32');
    backdrop.addColorStop(.53, '#23394a');
    backdrop.addColorStop(.665, '#334a54');
    backdrop.addColorStop(1, '#0a1622');
    g.fillStyle = backdrop;
    g.fillRect(0, 0, W, H);
    glow(g, blueHalo, W * .49, 342, W * .6, 365, .16);
    glow(g, moonHalo, W * .62, 553, W * .46, 106, .23);
    glow(g, redHalo, W * .23, 565, W * .27, 92, .16);

    for (let i = 0; i < 6600; i++) {
      const x = rng() * W;
      const y = rng() * 600;
      const a = rng() * .044;
      g.fillStyle = i % 3 ? 'rgba(223,230,237,' + a + ')' : 'rgba(0,5,14,' + a + ')';
      g.fillRect(x, y, .55 + rng() * 1.8, .55 + rng() * .75);
    }

    const starCount = Math.round(115 + W / 13);
    for (let i = 0; i < starCount; i++) {
      const x = rng() * W;
      const y = 17 + Math.pow(rng(), 1.42) * 480;
      const fade = 1 - y / 630;
      const radius = (.38 + Math.pow(rng(), 4) * 1.25) * Math.max(.72, unit);
      g.globalAlpha = (.13 + rng() * .61) * fade;
      dot(g, x, y, radius, i % 4 ? '#e3e7e4' : '#ffd5aa');
      if (radius > 1.1) glow(g, blueHalo, x, y, radius * 6, radius * 6, .53);
    }
    g.globalAlpha = 1;

    const moonX = W * mix(.786, .789, narrow);
    const moonY = mix(152, 216, narrow);
    const moonR = 47 * unit;
    glow(g, moonHalo, moonX, moonY, moonR * 3.7, moonR * 3.7, .76);
    glow(g, blueHalo, moonX, moonY, moonR * 5.4, moonR * 4.7, .16);
    g.save();
    g.translate(moonX, moonY);
    g.scale(moonR, moonR);
    dot(g, 0, 0, 1, 'rgba(224,203,167,.041)');
    g.strokeStyle = 'rgba(248,217,174,.18)';
    g.lineWidth = .014;
    g.beginPath();
    g.arc(0, 0, 1, 0, TAU);
    g.stroke();
    const crescent = new Path2D();
    crescent.moveTo(.18, -.983);
    crescent.bezierCurveTo(-.49, -1.13, -1.05, -.55, -.994, .11);
    crescent.bezierCurveTo(-.92, .86, -.13, 1.28, .51, .85);
    crescent.bezierCurveTo(.72, .72, .885, .49, .955, .292);
    crescent.bezierCurveTo(.36, .66, -.236, .31, -.285, -.261);
    crescent.bezierCurveTo(-.32, -.565, -.125, -.858, .18, -.983);
    g.clip(crescent);
    const light = g.createLinearGradient(-.95, -.7, .6, .86);
    light.addColorStop(0, '#ffedc4');
    light.addColorStop(.67, '#f7d9a1');
    light.addColorStop(1, '#e6af79');
    g.fillStyle = light;
    g.fillRect(-1.1, -1.1, 2.2, 2.2);
    for (let i = 0; i < 220; i++) {
      dot(g, rng() * 2 - 1, rng() * 2 - 1, .005 + rng() * .038,
        i % 3 ? 'rgba(148,95,79,.055)' : 'rgba(255,248,221,.23)');
    }
    g.restore();

    for (const [x, y, r] of [[.88, .142, 6], [.68, .123, 4], [.57, .214, 4.5], [.31, .199, 3.5]]) {
      const Y = y * H + narrow * 31;
      const X = x * W;
      const R = r * Math.max(.68, unit);
      glow(g, moonHalo, X, Y, R * 3.2, R * 3.2, .42);
      g.fillStyle = '#ede3ce';
      g.beginPath();
      g.moveTo(X, Y - R);
      g.quadraticCurveTo(X + .65, Y - .7, X + R * .67, Y);
      g.quadraticCurveTo(X + .65, Y + .7, X, Y + R);
      g.quadraticCurveTo(X - .65, Y + .7, X - R * .67, Y);
      g.quadraticCurveTo(X - .65, Y - .7, X, Y - R);
      g.fill();
    }

    for (const cloud of [
      [.11, .236, .23, .32], [.65, .198, .24, .47], [.90, .282, .16, .40],
      [.14, .403, .33, .37], [.67, .428, .39, .43], [.44, .361, .25, .17]
    ]) {
      const [u, v, width, strength] = cloud;
      const x = W * u;
      const y = H * v + narrow * 12;
      const span = W * width;
      glow(g, blueHalo, x, y, span * .81, 23 * unit, strength * .27);
      for (let i = 0; i < 18; i++) {
        const offset = rng() - .5;
        const height = (rng() - .5) * 26 * unit;
        const length = span * (.12 + rng() * .55);
        const start = x + span * offset - length / 2;
        const shade = g.createLinearGradient(start, 0, start + length, 0);
        shade.addColorStop(0, 'rgba(133,165,190,0)');
        shade.addColorStop(.52, 'rgba(153,180,200,' + (strength * (.025 + rng() * .12)) + ')');
        shade.addColorStop(1, 'rgba(133,165,190,0)');
        g.strokeStyle = shade;
        g.lineWidth = .45 + rng() * 1.5;
        g.beginPath();
        g.moveTo(start, y + height + 4 * unit);
        g.bezierCurveTo(start + length * .34, y + height - 8 * unit,
          start + length * .54, y + height + 3 * unit, start + length, y + height - 2 * unit);
        g.stroke();
      }
    }
  }

  function mountains(g, rng) {
    const layers = [
      { base: 550, amp: 142, tones: ['#344357', '#2f4558', '#314955'], phase: .65 },
      { base: 574, amp: 130, tones: ['#283a50', '#273e52', '#304957'], phase: 2.2 },
      { base: 596, amp: 94, tones: ['#1b2d42', '#263e51', '#2c4553'], phase: 3.3 }
    ];
    for (const layer of layers) {
      const profile = [];
      const mountain = g.createLinearGradient(0, 384, 0, 619);
      mountain.addColorStop(0, layer.tones[0]);
      mountain.addColorStop(.61, layer.tones[1]);
      mountain.addColorStop(1, layer.tones[2]);
      g.beginPath();
      for (let i = 0; i <= 156; i++) {
        const u = i / 156;
        const valley = .17 + .83 * Math.pow(Math.abs(2 * u - 1), .75);
        const contour = .54 + .2 * Math.sin(u * 19 + layer.phase) + .15 * Math.cos(u * 32 + layer.phase * 2)
          + .087 * Math.sin(u * 54 + layer.phase) + .022 * Math.sin(u * 151 + layer.phase);
        const y = layer.base - layer.amp * valley * contour;
        profile.push(y);
        if (i === 0) g.moveTo(0, y);
        else g.lineTo(u * W, y);
      }
      g.lineTo(W, 665);
      g.lineTo(0, 665);
      g.closePath();
      g.fillStyle = mountain;
      g.fill();
      g.save();
      g.clip();
      for (let i = 0; i < 380; i++) {
        const t = rng();
        const x = t * W;
        const y = profile[Math.min(156, Math.round(t * 156))] + 3 + rng() * 59;
        g.strokeStyle = i % 3 ? 'rgba(150,177,185,.045)' : 'rgba(5,16,30,.07)';
        g.lineWidth = .5 + rng();
        g.beginPath();
        g.moveTo(x, y);
        g.lineTo(x + (rng() - .67) * 25 * houseUnit, y + rng() * 9);
        g.stroke();
      }
      glow(g, blueHalo, W * .56, layer.base - 9, W * .49, 74, .13);
      g.restore();
    }
  }

  const houseTones = [
    { wall: '#352a31', shade: '#171b28', beam: '#171722', tile: '#34404b', edge: '#5b6269' },
    { wall: '#38363b', shade: '#1c2532', beam: '#141c26', tile: '#344754', edge: '#5d7480' },
    { wall: '#42312f', shade: '#20232b', beam: '#241a23', tile: '#3c414a', edge: '#666371' },
    { wall: '#2d3035', shade: '#161d29', beam: '#131a23', tile: '#2b3c4b', edge: '#536776' }
  ];

  function roof(g, x, y, width, depth, tone, detail) {
    const half = width * .5;
    function edge(u, v) {
      const a = Math.abs(u);
      const top = .025 + .83 * Math.pow(a, 1.7) - .24 * Math.pow(Math.max(0, (a - .73) / .27), 2);
      const bottom = 1.05 - .22 * Math.pow(a, 3);
      return y + mix(top, bottom, v) * depth;
    }
    const shape = new Path2D();
    for (let i = 0; i <= 24; i++) {
      const u = i / 12 - 1;
      if (i === 0) shape.moveTo(x + half * u, edge(u, 0));
      else shape.lineTo(x + half * u, edge(u, 0));
    }
    for (let i = 24; i >= 0; i--) {
      const u = i / 12 - 1;
      shape.lineTo(x + half * u, edge(u, 1));
    }
    shape.closePath();

    const tiles = g.createLinearGradient(0, y, 0, y + depth * 1.12);
    tiles.addColorStop(0, tone.tile);
    tiles.addColorStop(.58, '#182633');
    tiles.addColorStop(1, '#101824');
    g.fillStyle = tiles;
    g.fill(shape);
    if (detail) {
      g.save();
      g.clip(shape);
      for (let i = 0, n = Math.ceil(width / (7.8 * unit)); i <= n; i++) {
        const u = 2 * i / n - 1;
        g.lineWidth = Math.max(.55, .86 * unit);
        g.strokeStyle = i % 3 === 0 ? 'rgba(123,157,175,.21)' : 'rgba(103,133,149,.13)';
        g.beginPath();
        g.moveTo(x + u * half * .96, edge(u, 0) - 1);
        g.quadraticCurveTo(x + u * half * .98, edge(u, .53), x + u * half, edge(u, 1));
        g.stroke();
      }
      for (const v of [.38, .7, .91]) {
        g.lineWidth = Math.max(.5, .74 * unit);
        g.strokeStyle = v === .91 ? 'rgba(115,131,146,.24)' : 'rgba(3,12,21,.54)';
        g.beginPath();
        for (let i = 0; i <= 24; i++) {
          const u = i / 12 - 1;
          if (i === 0) g.moveTo(x + half * u, edge(u, v));
          else g.lineTo(x + half * u, edge(u, v));
        }
        g.stroke();
      }
      g.restore();
    }

    g.lineCap = 'round';
    g.lineJoin = 'round';
    g.strokeStyle = tone.edge;
    g.lineWidth = Math.max(.7, 1.25 * unit);
    g.beginPath();
    for (let i = 0; i <= 24; i++) {
      const u = i / 12 - 1;
      if (i === 0) g.moveTo(x + half * u, edge(u, 0));
      else g.lineTo(x + half * u, edge(u, 0));
    }
    g.stroke();
    g.strokeStyle = '#0e1520';
    g.lineWidth = Math.max(1, 2.3 * unit);
    g.beginPath();
    g.moveTo(x - half, edge(-1, 1) - .8 * unit);
    g.quadraticCurveTo(x - half * .32, edge(0, 1) + 2 * unit, x, edge(0, 1));
    g.quadraticCurveTo(x + half * .63, edge(0, 1) + unit, x + half, edge(1, 1) - .9 * unit);
    g.stroke();
  }

  function windowLight(g, x, y, w, h, lit, color, detail) {
    if (lit) glow(g, color === 1 ? redHalo : warmHalo, x, y, w * 2.7, h * 1.3, detail ? .55 : .38);
    g.fillStyle = '#131824';
    g.fillRect(x - w / 2 - 1.2 * unit, y - h / 2 - 1.45 * unit, w + 2.4 * unit, h + 2.9 * unit);
    if (lit) {
      const panes = g.createLinearGradient(0, y - h / 2, 0, y + h / 2);
      panes.addColorStop(0, color === 1 ? '#e78e53' : '#d49658');
      panes.addColorStop(.46, color === 1 ? '#ffb779' : '#ffe0a0');
      panes.addColorStop(1, color === 1 ? '#b65641' : '#bb7647');
      g.fillStyle = panes;
    } else {
      g.fillStyle = '#313846';
    }
    g.fillRect(x - w / 2, y - h / 2, w, h);
    if (detail) {
      g.strokeStyle = lit ? 'rgba(102,55,47,.88)' : '#1b2431';
      g.lineWidth = Math.max(.63, .9 * unit);
      g.beginPath();
      g.moveTo(x - w * .19, y - h / 2);
      g.lineTo(x - w * .19, y + h / 2);
      g.moveTo(x + w * .19, y - h / 2);
      g.lineTo(x + w * .19, y + h / 2);
      g.moveTo(x - w / 2, y - h * .08);
      g.lineTo(x + w / 2, y - h * .08);
      g.stroke();
      g.fillStyle = lit ? '#a7684b' : '#424957';
      g.fillRect(x - w * .57, y + h / 2, w * 1.14, 1.25 * unit);
    }
  }

  function house(g, spec, rng) {
    const [where, designedWidth, base, suggestedPeak, floors, variant] = spec;
    const x = W * where;
    const w = designedWidth * houseUnit;
    const peak = Math.max(suggestedPeak, roofLimit(x - w * .53) + 7, roofLimit(x + w * .53) + 7);
    const depth = Math.min((base - peak) * .34, (22 + designedWidth * .117) * unit);
    if (depth < 4) return;
    const eave = peak + depth * .9;
    const left = x - w * .39;
    const front = x + w * .29;
    const right = x + w * .40;
    const detail = designedWidth >= 55;
    const tone = houseTones[variant % houseTones.length];
    const wall = g.createLinearGradient(0, eave, 0, base);
    wall.addColorStop(0, tone.shade);
    wall.addColorStop(.52, tone.wall);
    wall.addColorStop(1, '#111b27');
    g.fillStyle = wall;
    g.beginPath();
    g.moveTo(left, eave);
    g.lineTo(front, eave - depth * .055);
    g.lineTo(front, base);
    g.lineTo(left, base + 2 * unit);
    g.closePath();
    g.fill();
    g.fillStyle = tone.shade;
    g.beginPath();
    g.moveTo(front, eave - depth * .055);
    g.lineTo(right, eave - depth * .13);
    g.lineTo(right, base - depth * .23);
    g.lineTo(front, base);
    g.closePath();
    g.fill();

    const step = (base - eave) / floors;
    const span = front - left;
    const cols = clamp(Math.floor(span / (19 * unit)), 2, 5);
    const cell = span / cols;
    g.strokeStyle = tone.beam;
    g.lineWidth = Math.max(.65, 2.5 * unit);
    for (let level = 0; level <= floors; level++) {
      const y = eave + step * level;
      g.beginPath();
      g.moveTo(left, y);
      g.lineTo(front, y - 1.2 * unit);
      g.lineTo(right, y - depth * .18);
      g.stroke();
    }
    for (let col = 0; col <= cols; col++) {
      const X = left + cell * col;
      g.beginPath();
      g.moveTo(X, eave);
      g.lineTo(X, base);
      g.stroke();
    }
    for (let level = 0; level < floors; level++) {
      const y = eave + step * (level + .49);
      for (let col = 0; col < cols; col++) {
        const lit = rng() > .23;
        const cx = left + cell * (col + .5);
        const width = cell * (.57 + rng() * .10);
        const height = Math.min(step * .53, width * 1.46);
        windowLight(g, cx, y, width, height, lit, (col + level + variant) % 4 === 0 ? 1 : 0, detail);
      }
      if (detail && w > 45 * unit) {
        windowLight(g, (front + right) / 2, y - 3 * unit, (right - front) * .38, step * .43,
          rng() > .59, 1, true);
      }
    }

    if (detail) {
      g.fillStyle = 'rgba(150,124,133,.12)';
      for (let i = 0; i < 36; i++) {
        g.fillRect(left + rng() * span, eave + rng() * (base - eave), (1 + rng() * 6) * unit, .55 * unit);
      }
      if (floors > 1 && designedWidth > 95) {
        roof(g, x - w * .05, eave + step - 6 * unit, w * .8, 8 * unit, tone, true);
      }
      if (designedWidth > 89) {
        const lampY = base - step * .78;
        hangingLamp(g, left + 3 * unit, lampY, 5.3 * unit, 1, -.09, .9);
        hangingLamp(g, front - 3 * unit, lampY, 5.3 * unit, 1, .06, .83);
      }
    }

    roof(g, x, peak, w, depth, tone, detail);
    if (designedWidth > 85) {
      g.strokeStyle = tone.edge;
      g.lineWidth = 1.25 * unit;
      g.beginPath();
      g.moveTo(x - 9 * houseUnit, peak + 3 * unit);
      g.quadraticCurveTo(x, peak - 5 * unit, x + 9 * houseUnit, peak + 3 * unit);
      g.moveTo(x, peak - 1 * unit);
      g.lineTo(x, peak - 6 * unit);
      g.stroke();
    }
  }

  function pagoda(g, xRatio, peak, base, width) {
    const x = W * xRatio;
    const w = width * houseUnit;
    const theme = houseTones[1];
    const top = Math.max(peak, roofLimit(x - .55 * w) + 10, roofLimit(x + .55 * w) + 10);
    const per = (base - top) / 3;
    for (let i = 2; i >= 0; i--) {
      const y = top + i * per;
      const span = w * (.49 + .24 * i);
      g.fillStyle = i % 2 ? '#302a32' : '#292b36';
      g.fillRect(x - span * .35, y + .45 * per, span * .7, per * .71);
      for (const j of [-1, 0, 1]) {
        windowLight(g, x + j * span * .21, y + .77 * per, span * .145, per * .29, true, i % 2, true);
      }
      roof(g, x, y, span, per * .58, theme, true);
    }
    g.strokeStyle = '#8d7c77';
    g.lineWidth = 1.2 * unit;
    g.beginPath();
    g.moveTo(x, top + 2 * unit);
    g.lineTo(x, top - 17 * unit);
    g.moveTo(x - 3 * unit, top - 6 * unit);
    g.lineTo(x + 3 * unit, top - 6 * unit);
    g.stroke();
    dot(g, x, top - 14 * unit, 1.6 * unit, '#e0ab73');
  }

  function cypress(g, x, y, h, opacity, rng) {
    g.save();
    g.globalAlpha = opacity;
    g.fillStyle = '#132432';
    g.beginPath();
    g.moveTo(x + h * .026, y);
    g.lineTo(x + h * .02, y - h);
    g.lineTo(x - h * .024, y);
    g.closePath();
    g.fill();
    for (let i = 0; i < 12; i++) {
      const u = (i + 1) / 13;
      const reach = h * u * (.15 + rng() * .09);
      const height = y - h * (1 - u);
      g.beginPath();
      g.moveTo(x, height - h * .16);
      g.quadraticCurveTo(x + reach * .42, height - h * .05, x + reach, height + h * .07);
      g.quadraticCurveTo(x, height + h * .022, x - reach * (.66 + rng() * .45), height + h * .09);
      g.quadraticCurveTo(x - reach * .43, height - h * .03, x, height - h * .16);
      g.fill();
    }
    g.restore();
  }

  function land(g, rng) {
    const ground = g.createLinearGradient(0, 548, 0, H);
    ground.addColorStop(0, '#263a46');
    ground.addColorStop(.49, '#152532');
    ground.addColorStop(1, '#0a1521');
    g.fillStyle = ground;
    g.beginPath();
    g.moveTo(0, 554);
    g.bezierCurveTo(W * .29, 563, W * .34, 580, W * .47, 594);
    g.bezierCurveTo(W * .63, 580, W * .82, 549, W, 553);
    g.lineTo(W, H);
    g.lineTo(0, H);
    g.closePath();
    g.fill();

    for (const side of [-1, 1]) {
      for (let i = 0; i < 23; i++) {
        const u = rng() * .44;
        const x = W * (side === -1 ? u : 1 - u);
        cypress(g, x, 591 + rng() * 29, (13 + rng() * 54) * unit, .6 + rng() * .3, rng);
      }
      for (let i = 0; i < 14; i++) {
        const u = .032 + i * .0313 + (rng() - .5) * .018;
        const peak = 524 + rng() * 55;
        house(g, [side === -1 ? u : 1 - u, 27 + rng() * 48, 593 + rng() * 38, peak, 1, i], rng);
      }
    }

    const backRow = [
      [-.002, 106, 652, 536, 2, 2], [.070, 108, 658, 549, 2, 0], [.143, 118, 668, 550, 2, 3],
      [.217, 98, 648, 548, 2, 1], [.280, 99, 670, 560, 2, 2], [.345, 77, 639, 552, 2, 0],
      [.397, 75, 627, 555, 1, 3], [.444, 60, 610, 559, 1, 2],
      [.572, 65, 619, 549, 1, 0], [.622, 89, 645, 545, 2, 2], [.683, 102, 650, 552, 2, 3],
      [.751, 112, 670, 531, 2, 1], [.824, 104, 674, 529, 2, 2], [.903, 115, 675, 547, 2, 3],
      [.980, 126, 663, 532, 2, 0]
    ];
    backRow.sort((a, b) => a[2] - b[2]).forEach(spec => house(g, spec, rng));
    pagoda(g, .154, 488, 622, 125);
    pagoda(g, .855, 484, 629, 133);

    for (const side of [-1, 1]) {
      const row = side === -1 ?
        [[.325,109,699,573,2,2],[.253,120,733,587,2,1],[.173,142,774,584,2,0],
         [.087,165,817,600,2,2],[-.025,222,876,611,3,3]] :
        [[.665,91,692,562,2,1],[.721,119,726,584,2,2],[.793,133,769,587,2,3],
         [.876,174,823,596,2,2],[.983,221,883,606,3,0]];
      for (const spec of row) house(g, spec, rng);
    }

    for (const side of [-1, 1]) {
      for (let y = 633; y <= 900; y += 5 + rng() * 7) {
        const x = shore(y, side) + side * (4 + rng() * 29) * unit;
        g.strokeStyle = rng() > .46 ? 'rgba(103,114,129,.17)' : 'rgba(6,15,25,.48)';
        g.lineWidth = .7 + rng() * 2.1 * unit;
        g.beginPath();
        g.moveTo(x, y);
        g.lineTo(x + side * (8 + rng() * 25) * unit, y + rng() * 3);
        g.stroke();
      }
    }
  }

  function makeLamp(tint) {
    const { image, g } = bitmap(48, 65, 2);
    g.translate(24, 29);
    g.strokeStyle = '#40333c';
    g.lineWidth = 1.35;
    g.beginPath();
    g.moveTo(0, -28);
    g.lineTo(0, -16);
    g.moveTo(0, 14);
    g.lineTo(0, 29);
    g.stroke();
    const paper = new Path2D();
    paper.moveTo(-7.8, -15.8);
    paper.bezierCurveTo(-14.3, -12.3, -15.6, 8.2, -8, 14);
    paper.quadraticCurveTo(0, 17, 8, 14);
    paper.bezierCurveTo(15.6, 8.2, 14.3, -12.3, 7.8, -15.8);
    paper.closePath();
    const light = g.createRadialGradient(-2, 5, 0, 0, 1, 17);
    light.addColorStop(0, '#fff2ba');
    light.addColorStop(.35, tint ? '#ffbc6b' : '#ffe0a1');
    light.addColorStop(.77, tint ? '#ed7550' : '#eea054');
    light.addColorStop(1, tint ? '#a13b35' : '#a4553b');
    g.fillStyle = light;
    g.fill(paper);
    g.strokeStyle = tint ? '#c26046' : '#cb8550';
    g.lineWidth = 1.2;
    g.stroke(paper);
    g.strokeStyle = tint ? 'rgba(151,57,40,.58)' : 'rgba(159,84,49,.49)';
    g.lineWidth = .9;
    for (const x of [-8, -4, 4, 8]) {
      g.beginPath();
      g.moveTo(x * .57, -14);
      g.bezierCurveTo(x * 1.7, -9, x * 1.7, 7, x * .56, 14);
      g.stroke();
    }
    g.fillStyle = '#643a39';
    g.fillRect(-7.1, -17.4, 14.2, 2.5);
    g.fillRect(-6.9, 14, 13.8, 2.25);
    g.fillStyle = '#f7be77';
    g.fillRect(-4.2, 16.1, 8.4, 1.35);
    g.strokeStyle = tint ? '#c76d45' : '#ce9357';
    g.beginPath();
    g.moveTo(0, 17);
    g.lineTo(0, 22);
    g.moveTo(-.7, 23);
    g.lineTo(-1.3, 27);
    g.moveTo(.6, 23);
    g.lineTo(1.4, 27);
    g.stroke();
    return image;
  }

  const lampArt = [makeLamp(0), makeLamp(1)];

  function hangingLamp(g, x, y, size, color, swing, alpha, floating = false) {
    if (alpha <= 0) return;
    g.save();
    g.globalAlpha *= alpha;
    glow(g, color ? redHalo : warmHalo, x, y, size * 4.1, size * 4.2, .92);
    g.translate(x, y);
    g.rotate(swing);
    const k = size / 14;
    if (floating) {
      g.drawImage(lampArt[color], 0, 19, 96, 77, -24 * k, -19.5 * k, 48 * k, 38.5 * k);
    } else {
      g.drawImage(lampArt[color], -24 * k, -29 * k, 48 * k, 65 * k);
    }
    g.restore();
  }

  function makeGarlands() {
    const specs = [
      [-.025, 447, .262, 563, 43, false],
      [.733, 565, 1.035, 431, 47, false],
      [.325, 562, .675, 553, 27, false],
      [-.043, 558, .324, 641, 41, true],
      [.685, 636, 1.043, 546, 48, true]
    ];
    return specs.map(([a, y1, b, y2, sag, front], i) => {
      const x1 = a * W, x2 = b * W;
      return { x1, x2, y1, y2, sag, front, seed: i, count: Math.max(6, Math.round((x2 - x1) / (20 * unit))) };
    });
  }

  function strings(g, front) {
    for (const line of garlands) {
      if (line.front !== front) continue;
      const { x1, x2, y1, y2, sag, seed, count } = line;
      g.strokeStyle = front ? 'rgba(110,104,104,.62)' : 'rgba(95,104,119,.60)';
      g.lineWidth = Math.max(.65, unit * (front ? 1.24 : .8));
      g.beginPath();
      g.moveTo(x1, y1);
      g.quadraticCurveTo((x1 + x2) / 2, (y1 + y2) / 2 + 2 * sag, x2, y2);
      g.stroke();
      for (let i = 1; i < count; i++) {
        const u = i / count;
        const x = mix(x1, x2, u);
        const y = mix(y1, y2, u) + 4 * sag * u * (1 - u);
        const phase = i * 1.79 + seed * 3.67;
        const flicker = .82 + .15 * Math.sin(time * 1.85 + phase);
        if ((i + seed) % 4 === (front ? 2 : 1)) {
          const size = unit * (front ? 8.2 : 5.6);
          hangingLamp(g, x, y + size * 1.74, size, (i + seed) % 3 ? 1 : 0,
            Math.sin(time * 1.27 + phase) * .12, flicker);
        } else {
          const size = unit * (front ? 1.8 : 1.32);
          glow(g, warmHalo, x, y + 3 * unit, size * 6.5, size * 6.5, .9 * flicker);
          dot(g, x, y + 3 * unit, size, (i + seed) % 3 ? '#ffcc91' : '#ffab73');
        }
      }
    }
  }

  function makeAir(rng) {
    garlands = makeGarlands();
    floaters = [
      [.123, 366, 11.4], [.922, 317, 10.5], [.283, 342, 5.1], [.696, 380, 5.6],
      [.811, 451, 7.0], [.208, 491, 8.6], [.527, 527, 4.8], [.642, 510, 7.1],
      [.092, 521, 7.9], [.387, 175, 3.9], [.882, 234, 3.8], [.477, 383, 4.35],
      [.075, 256, 4.8], [.976, 445, 6.3], [.337, 528, 5.8], [.578, 143, 3.4]
    ].map(([x, y, size], i) => ({ x, y, size, warm: i % 3 ? 1 : 0, phase: rng() * TAU, rate: 6 + rng() * 7 }));
    sparks = Array.from({ length: Math.round(95 + W / 24) }, () => ({
      x: rng(), y: rng(), phase: rng() * TAU, rate: 9 + rng() * 25,
      radius: .38 + Math.pow(rng(), 2) * 1.65, bright: .27 + rng() * .67
    }));
    currents = Array.from({ length: Math.round(90 + W / 14) }, () => ({
      x: rng(), y: rng(), size: .12 + rng() * .88, phase: rng() * TAU, tone: rng()
    }));
  }

  function airborne(g) {
    for (const f of floaters) {
      const rawY = mod(f.y + 30 * narrow - time * f.rate - 88, 535) + 88;
      const alpha = smooth((rawY - 88) / 44) * smooth((623 - rawY) / 44);
      const x = f.x * W + (8 * Math.sin(time * .45 + f.phase) + 3 * Math.sin(time + f.phase)) * unit;
      hangingLamp(g, x, rawY, Math.max(.62, unit) * f.size, f.warm,
        Math.sin(time * .94 + f.phase) * .15, alpha * .86, true);
    }
    for (const s of sparks) {
      const y = mod(s.y * 486 - time * s.rate, 486) + 147;
      const fade = smooth((y - 147) / 56) * smooth((633 - y) / 54);
      const x = mod(s.x * W + time * (5 + 4 * Math.cos(s.phase)) + Math.sin(time * .7 + s.phase) * 10 * unit, W);
      const a = fade * s.bright * (.65 + .35 * Math.sin(time * 2.1 + s.phase));
      g.globalAlpha = a;
      if (s.radius > 1) glow(g, warmHalo, x, y, s.radius * 6, s.radius * 6, .67);
      dot(g, x, y, s.radius * Math.max(.58, unit), s.phase > 4.7 ? '#c4e4ed' : '#ffc482');
    }
    g.globalAlpha = 1;
  }

  function makeSegment(color, style) {
    const { image, g } = bitmap(74, 102, 2);
    const rng = random(601 + style * 37);
    g.translate(37, 51);
    const shell = new Path2D();
    shell.moveTo(-27, -33);
    shell.bezierCurveTo(-19, -45, 20, -45, 27, -33);
    shell.bezierCurveTo(32.5, -16, 33, 14, 27, 33);
    shell.bezierCurveTo(17, 45, -19, 45, -27, 33);
    shell.bezierCurveTo(-33, 15, -32, -16, -27, -33);
    shell.closePath();
    const light = g.createLinearGradient(-2, -43, 0, 44);
    light.addColorStop(0, color.middle);
    light.addColorStop(.21, color.light);
    light.addColorStop(.42, color.pale);
    light.addColorStop(.62, color.light);
    light.addColorStop(.83, color.middle);
    light.addColorStop(1, color.shade);
    g.fillStyle = light;
    g.fill(shell);
    g.save();
    g.clip(shell);
    const seam = g.createLinearGradient(-32, 0, 32, 0);
    seam.addColorStop(0, color.shade);
    seam.addColorStop(.22, 'rgba(55,38,55,0)');
    seam.addColorStop(.77, 'rgba(55,38,55,0)');
    seam.addColorStop(1, color.shade);
    g.globalAlpha = .57;
    g.fillStyle = seam;
    g.fillRect(-35, -48, 70, 96);
    g.globalAlpha = 1;
    for (let i = 0; i < 410; i++) {
      const x = rng() * 67 - 33.5, y = rng() * 88 - 44;
      g.strokeStyle = i % 3 ? 'rgba(80,55,49,.09)' : 'rgba(255,250,222,.34)';
      g.lineWidth = rng() * .85 + .2;
      g.beginPath();
      g.moveTo(x, y);
      g.lineTo(x + rng() * 2 - 1, y + rng() * 4);
      g.stroke();
    }
    g.strokeStyle = color.band;
    g.globalAlpha = .29;
    g.lineWidth = .95;
    for (const x of [-18, -8, 9, 19]) {
      g.beginPath();
      g.moveTo(x * .7, -40);
      g.bezierCurveTo(x * 1.14, -15, x * 1.14, 16, x * .73, 41);
      g.stroke();
    }
    if (style === 1) {
      g.globalAlpha = .22;
      g.strokeStyle = color.shade;
      g.lineWidth = 1.5;
      for (const y of [-15, 5, 25]) {
        g.beginPath();
        g.moveTo(-22, y + 7);
        g.bezierCurveTo(-9, y - 6, -7, y - 6, 3, y + 1);
        g.quadraticCurveTo(12, y + 8, 22, y);
        g.stroke();
      }
    }
    g.restore();
    g.strokeStyle = color.rim;
    g.lineWidth = 1.55;
    g.stroke(shell);
    g.strokeStyle = color.seam;
    g.lineWidth = 1.6;
    g.globalAlpha = .66;
    g.beginPath();
    g.moveTo(-23, -33);
    g.bezierCurveTo(-28, -13, -28, 14, -23, 32);
    g.moveTo(23, -33);
    g.bezierCurveTo(28, -13, 28, 14, 23, 32);
    g.stroke();
    return image;
  }

  function makeFace(c) {
    const { image, g } = bitmap(112, 96, 2);
    g.translate(56, 46);
    const mask = new Path2D();
    mask.moveTo(-38, -17);
    mask.bezierCurveTo(-29, -32, -13, -34, 0, -34);
    mask.bezierCurveTo(15, -34, 31, -30, 38, -17);
    mask.bezierCurveTo(46, -6, 46, 13, 35, 24);
    mask.bezierCurveTo(25, 34, 9, 37, 0, 35);
    mask.bezierCurveTo(-12, 37, -30, 31, -38, 22);
    mask.bezierCurveTo(-47, 10, -46, -6, -38, -17);
    mask.closePath();

    g.fillStyle = c.rim;
    g.lineWidth = 4.2;
    g.strokeStyle = c.rim;
    g.stroke(mask);
    const paper = g.createLinearGradient(-13, -36, 16, 36);
    paper.addColorStop(0, c.middle);
    paper.addColorStop(.37, c.light);
    paper.addColorStop(.66, c.pale);
    paper.addColorStop(1, c.middle);
    g.fillStyle = paper;
    g.fill(mask);
    g.save();
    g.clip(mask);
    const yarn = random(7281);
    for (let i = 0; i < 900; i++) {
      const x = yarn() * 88 - 44, y = yarn() * 72 - 36;
      g.strokeStyle = i % 4 ? 'rgba(83,56,54,.10)' : 'rgba(255,249,219,.41)';
      g.lineWidth = .18 + yarn() * .68;
      g.beginPath();
      g.moveTo(x, y);
      g.lineTo(x + yarn() * 4 - 2.3, y + yarn() * 2);
      g.stroke();
    }
    g.strokeStyle = c.seam;
    g.globalAlpha = .45;
    g.lineWidth = .85;
    g.beginPath();
    g.moveTo(-31, -26);
    g.bezierCurveTo(-25, -8, -33, 14, -23, 32);
    g.moveTo(30, -26);
    g.bezierCurveTo(25, -8, 31, 16, 24, 33);
    g.stroke();

    g.fillStyle = c.band;
    g.globalAlpha = .68;
    g.beginPath();
    g.moveTo(-4, -34);
    g.quadraticCurveTo(-7, -23, 1, -14);
    g.quadraticCurveTo(6, -24, 5, -34);
    g.closePath();
    g.moveTo(-22, -33);
    g.quadraticCurveTo(-18, -23, -10, -19);
    g.quadraticCurveTo(-11, -30, -15, -34);
    g.closePath();
    g.moveTo(22, -33);
    g.quadraticCurveTo(17, -23, 11, -20);
    g.quadraticCurveTo(12, -30, 15, -34);
    g.fill();
    for (const side of [-1, 1]) {
      g.save();
      g.scale(side, 1);
      g.beginPath();
      g.moveTo(46, -2);
      g.quadraticCurveTo(37, 0, 31, 4);
      g.quadraticCurveTo(39, 5, 46, 4);
      g.moveTo(46, 11);
      g.quadraticCurveTo(36, 12, 32, 17);
      g.quadraticCurveTo(40, 17, 46, 17);
      g.fill();
      g.restore();
    }
    g.restore();
    g.strokeStyle = c.seam;
    g.lineWidth = .95;
    g.globalAlpha = .75;
    g.stroke(mask);
    return image;
  }

  for (const color of catColors) {
    color.panels = [makeSegment(color, 0), makeSegment(color, 1)];
    color.face = makeFace(color);
  }

  function ear(g, c, side, flick) {
    g.save();
    g.translate(side * 24, -23);
    g.rotate(side * flick);
    g.scale(side, 1);
    const triangle = new Path2D();
    triangle.moveTo(-14, 8);
    triangle.quadraticCurveTo(-5, -11, 11, -32);
    triangle.quadraticCurveTo(14, -36, 16, -30);
    triangle.quadraticCurveTo(21, -10, 14, 10);
    triangle.quadraticCurveTo(2, 14, -14, 8);
    const lamp = g.createLinearGradient(-6, 8, 15, -33);
    lamp.addColorStop(0, c.middle);
    lamp.addColorStop(.56, c.light);
    lamp.addColorStop(1, c.pale);
    g.fillStyle = lamp;
    g.fill(triangle);
    g.strokeStyle = c.rim;
    g.lineWidth = 1.65;
    g.stroke(triangle);
    g.fillStyle = c.shade;
    g.globalAlpha = .65;
    g.beginPath();
    g.moveTo(-5, 5);
    g.quadraticCurveTo(2, -11, 12, -23);
    g.quadraticCurveTo(16, -9, 10, 6);
    g.closePath();
    g.fill();
    g.strokeStyle = c.seam;
    g.lineWidth = .8;
    g.beginPath();
    g.moveTo(-7, 5);
    g.lineTo(12, -23);
    g.stroke();
    g.restore();
  }

  function face(g, cat) {
    const c = cat.color;
    const p = cat.nodes[0];
    const bob = Math.sin(time * 3.1 + cat.seed);
    const k = cat.look;
    g.save();
    g.translate(p.x, p.y);
    g.rotate(cat.tilt);
    g.scale(unit, unit);
    ear(g, c, -1, .025 + bob * .086);
    ear(g, c, 1, -.012 + Math.sin(time * 3.8 + cat.seed + 1.2) * .091);
    g.drawImage(c.face, -56, -46, 112, 96);

    g.save();
    g.translate(k * 6.4, .1);
    const blinkPhase = mod(time + cat.seed * 1.1, 5.3 + cat.seed * .21);
    const blink = blinkPhase < .22 ? Math.max(.12, Math.abs(blinkPhase - .11) / .11) : 1;
    for (const side of [-1, 1]) {
      g.save();
      g.translate(side * 15.4, -3.1 + side * k * 1.3);
      g.rotate(side * -.14);
      g.scale(1 + side * k * .12, blink);
      g.fillStyle = c.ink;
      g.beginPath();
      g.moveTo(-8.9, -.45);
      g.quadraticCurveTo(-1.3, -8.2, 8.4, -1.2);
      g.quadraticCurveTo(4.6, 4.4, -.9, 4.6);
      g.quadraticCurveTo(-6.9, 3.9, -8.9, -.45);
      g.fill();
      if (blink > .39) {
        g.fillStyle = c.iris;
        g.beginPath();
        g.ellipse(k * 2.6, -.5, 3.7, 3.9, 0, 0, TAU);
        g.fill();
        g.fillStyle = c.ink;
        g.beginPath();
        g.ellipse(k * 3.05 + .45, -.48, 1.65, 3.45, 0, 0, TAU);
        g.fill();
        dot(g, k * 3 - 1, -2, 1.12, '#fffae4');
      }
      g.restore();
    }
    g.fillStyle = c.ink;
    g.beginPath();
    g.moveTo(-5.1, 8.3);
    g.quadraticCurveTo(0, 6.4, 5.1, 8.3);
    g.quadraticCurveTo(2.1, 13.1, 0, 13.5);
    g.quadraticCurveTo(-2.4, 13.1, -5.1, 8.3);
    g.fill();
    g.strokeStyle = c.ink;
    g.lineCap = 'round';
    g.lineWidth = 1.25;
    g.beginPath();
    g.moveTo(0, 12.2);
    g.lineTo(0, 16);
    g.moveTo(-8.8, 16);
    g.quadraticCurveTo(-4.9, 20.6, 0, 16);
    g.quadraticCurveTo(4.9, 20.6, 8.8, 16);
    g.stroke();
    g.restore();

    for (const side of [-1, 1]) {
      const sway = Math.sin(time * 4 + cat.seed + side);
      g.save();
      g.scale(side, 1);
      dot(g, 23, 11, .94, c.shade);
      dot(g, 26, 15, .74, c.shade);
      dot(g, 22, 16, .67, c.shade);
      for (let i = 0; i < 3; i++) {
        const startY = 11 + i * 2.9;
        const toY = -1 + 10.9 * i + sway * (2 + i);
        const end = 69 - i * 3 + k * side * 4;
        g.beginPath();
        g.moveTo(27, startY);
        g.quadraticCurveTo(50, startY - 11 + i * 5, end, toY);
        g.strokeStyle = c.rim;
        g.globalAlpha = .39;
        g.lineWidth = 2.25;
        g.stroke();
        g.strokeStyle = c.whisker;
        g.globalAlpha = .89;
        g.lineWidth = 1.07;
        g.stroke();
      }
      g.restore();
    }
    g.restore();
  }

  function bodyRadius(i) {
    if (i === 0) return 46 * unit;
    if (i <= bodyEnd) return unit * mix(22.6, 12, Math.pow((i - 1) / (bodyEnd - 1), 1.36));
    return unit * mix(11, 2.2, Math.pow((i - bodyEnd) / (tailEnd - bodyEnd), .88));
  }

  function paw(g, cat, i, shift) {
    const p = cat.nodes[i];
    const c = cat.color;
    const step = Math.sin(time * 3.3 + shift + cat.seed);
    g.save();
    g.translate(p.x + (2 * step + shift * cat.look) * unit, p.y + bodyRadius(i) * .76);
    g.rotate(.26 * step - cat.look * .29);
    const s = unit * (i < 8 ? 1 : .8);
    g.scale(s, s);
    const foot = g.createLinearGradient(0, -5, 0, 17);
    foot.addColorStop(0, c.paw);
    foot.addColorStop(1, c.light);
    g.fillStyle = foot;
    g.strokeStyle = c.rim;
    g.lineWidth = 1;
    g.beginPath();
    g.moveTo(-6.3, -4);
    g.bezierCurveTo(-3, -8, 4, -7, 6.3, -3.5);
    g.bezierCurveTo(8.9, 3, 9, 11.5, 5, 14);
    g.bezierCurveTo(1.9, 17, -6, 16, -7.2, 12.2);
    g.quadraticCurveTo(-9, 4.8, -6.3, -4);
    g.fill();
    g.stroke();
    g.strokeStyle = c.band;
    g.beginPath();
    g.moveTo(-2.9, 11);
    g.lineTo(-2.7, 15);
    g.moveTo(1.8, 11);
    g.lineTo(2, 15);
    g.stroke();
    g.restore();
  }

  function lanternCat(g, cat) {
    const nodes = cat.nodes;
    const c = cat.color;
    const start = nodes[0];
    g.save();
    g.globalCompositeOperation = 'screen';
    for (let i = bodyEnd + 4; i > 0; i -= 2) {
      const r = bodyRadius(i);
      glow(g, c.halo, nodes[i].x, nodes[i].y, r * 3.66, r * 3.4, .45);
    }
    glow(g, c.halo, start.x, start.y, 108 * unit, 102 * unit, .68);
    g.restore();

    g.lineCap = 'round';
    for (let i = tailEnd; i >= 2; i--) {
      const a = nodes[i - 1], b = nodes[i];
      g.strokeStyle = c.shade;
      g.lineWidth = 1.51 * bodyRadius(i);
      g.beginPath();
      g.moveTo(a.x, a.y);
      g.lineTo(b.x, b.y);
      g.stroke();
    }
    paw(g, cat, 19, -3);
    paw(g, cat, 17, 2);
    paw(g, cat, 5, -5);
    paw(g, cat, 3, 5);
    for (let i = tailEnd; i >= 1; i--) {
      const p = nodes[i], a = nodes[i - 1], b = nodes[Math.min(tailEnd, i + 1)];
      const r = bodyRadius(i);
      const length = i === 1 ? spacings[2] - spacings[1] : spacings[i] - spacings[i - 1];
      const angle = Math.atan2(a.y - b.y, a.x - b.x);
      g.save();
      g.translate(p.x, p.y);
      g.rotate(angle);
      const width = length * (i > bodyEnd ? 1.29 : 1.33);
      g.drawImage(c.panels[i % 5 === 2 ? 1 : 0], -width / 2, -r * 1.205, width, r * 2.41);
      g.restore();
    }
    const tip = nodes[tailEnd], behind = nodes[tailEnd - 1];
    const a = Math.atan2(tip.y - behind.y, tip.x - behind.x);
    g.save();
    g.translate(tip.x, tip.y);
    g.rotate(a);
    g.scale(unit, unit);
    g.fillStyle = c.light;
    g.strokeStyle = c.seam;
    g.lineWidth = .85;
    g.beginPath();
    g.moveTo(-4, -2.1);
    g.quadraticCurveTo(1.6, -4.7, 9, 1.6);
    g.quadraticCurveTo(2, 4, -4, 2.5);
    g.closePath();
    g.fill();
    g.stroke();
    g.restore();
    face(g, cat);
  }

  function makeRail() {
    const keys = [
      [.131, 394], [.176, 309], [.274, 278], [.390, 243], [.513, 264],
      [.643, 277], [.753, 247], [.844, 272], [.885, 350], [.833, 424],
      [.742, 437], [.634, 479], [.517, 497], [.406, 477], [.311, 456],
      [.214, 467], [.145, 455]
    ].map(([x, y]) => ({ x: W * x, y: y + narrow * Math.max(0, (424 - y) * .32) }));
    const dots = [{ x: keys[0].x, y: keys[0].y, d: 0 }];
    const marks = [];
    let length = 0;
    const n = keys.length;
    function spline(a, b, c, d, t) {
      const q = t * t;
      return .5 * (2 * b + (-a + c) * t + (2 * a - 5 * b + 4 * c - d) * q
        + (-a + 3 * b - 3 * c + d) * q * t);
    }
    for (let i = 0; i < n; i++) {
      marks.push(length);
      const a = keys[(i - 1 + n) % n], b = keys[i], c = keys[(i + 1) % n], d = keys[(i + 2) % n];
      for (let frame = 1; frame <= 20; frame++) {
        const t = frame / 20;
        const x = spline(a.x, b.x, c.x, d.x, t);
        const y = spline(a.y, b.y, c.y, d.y, t);
        const prev = dots[dots.length - 1];
        length += Math.hypot(x - prev.x, y - prev.y);
        dots.push({ x, y, d: length });
      }
    }
    return { dots, marks, length, pace: length / 20 };
  }

  function railAt(distance) {
    const d = mod(distance, rail.length);
    const dots = rail.dots;
    let lo = 0, hi = dots.length - 1;
    while (hi - lo > 1) {
      const m = (lo + hi) >> 1;
      if (dots[m].d > d) hi = m;
      else lo = m;
    }
    const a = dots[lo], b = dots[hi];
    const f = (d - a.d) / Math.max(.001, b.d - a.d);
    return { x: mix(a.x, b.x, f), y: mix(a.y, b.y, f) };
  }

  function route(cat, lead = 0) {
    return railAt(rail.pace * (time + lead) + cat.offset + 8 * unit * Math.sin(time * .89 + cat.seed));
  }

  function traceBody(cat, head, dt) {
    const trace = cat.trace;
    let cursor = trace.length - 1;
    let prev = trace[cursor];
    const distance = prev.d + Math.hypot(head.x - prev.x, head.y - prev.y);
    let next = { x: head.x, y: head.y, d: distance };
    const nodes = [head];
    const blend = dt ? 1 - Math.exp(-dt * 16) : 1;

    for (let i = 1; i <= tailEnd; i++) {
      const at = distance - spacings[i];
      while (prev.d > at && cursor > 0) {
        next = prev;
        prev = trace[--cursor];
      }
      const f = clamp((at - prev.d) / Math.max(.001, next.d - prev.d), 0, 1);
      const dx = next.x - prev.x, dy = next.y - prev.y;
      const norm = Math.hypot(dx, dy) || 1;
      const flare = Math.max(0, (i - bodyEnd) / (tailEnd - bodyEnd));
      const amplitude = (9.5 * Math.sin(i * Math.PI / (tailEnd + 3)) + flare * 21) * unit;
      const wiggle = amplitude * Math.sin(time * (2.75 + flare) - i * .49 + cat.seed);
      const pill = {
        x: mix(prev.x, next.x, f) - dy / norm * wiggle,
        y: mix(prev.y, next.y, f) + dx / norm * wiggle
      };
      if (cat.nodes) {
        pill.x = mix(cat.nodes[i].x, pill.x, blend);
        pill.y = mix(cat.nodes[i].y, pill.y, blend);
      }
      nodes.push(fitToSky(pill, radii[i]));
    }
    return nodes;
  }

  function separated(a, b) {
    for (let i = 0; i < a.length; i++) {
      for (let j = 0; j < b.length; j++) {
        const r = radii[i] + radii[j];
        const x = a[i].x - b[j].x, y = a[i].y - b[j].y;
        if (x * x + y * y < r * r) return false;
      }
    }
    return true;
  }

  function separate(a, b, priority, passes) {
    for (let pass = 0; pass < passes; pass++) {
      let adjusted = false;
      for (let i = 0; i < a.length; i++) {
        const A = a[i];
        for (let j = 0; j < b.length; j++) {
          const B = b[j];
          const reach = radii[i] + radii[j] + .72 * unit;
          const x = A.x - B.x, y = A.y - B.y;
          const square = x * x + y * y;
          if (square >= reach * reach) continue;
          const distance = Math.sqrt(square);
          const nx = distance > .001 ? x / distance : 0;
          const ny = distance > .001 ? y / distance : -1;
          const shift = reach - distance;
          const iMass = (i === 0 ? .72 : 1) * (priority === 0 ? .71 : 1);
          const jMass = (j === 0 ? .72 : 1) * (priority === 1 ? .71 : 1);
          const p = iMass / (iMass + jMass);
          A.x += nx * shift * p;
          A.y += ny * shift * p;
          B.x -= nx * shift * (1 - p);
          B.y -= ny * shift * (1 - p);
          adjusted = true;
        }
      }
      if (!adjusted) return;
      for (const list of [a, b]) list.forEach((node, i) => fitToSky(node, radii[i]));
    }
  }

  function restrainedStep(drafts) {
    for (const amount of [.5, .25, .125, .0625]) {
      const eased = drafts.map((list, k) => list.map((p, i) => {
        const old = cats[k].nodes[i];
        return fitToSky({ x: mix(old.x, p.x, amount), y: mix(old.y, p.y, amount) }, radii[i]);
      }));
      if (separated(eased[0], eased[1])) return eased;
    }
    return cats.map(cat => cat.nodes);
  }

  function setupCats() {
    rail = makeRail();
    spacings = [0];
    radii = [56 * unit];
    for (let i = 1; i <= tailEnd; i++) {
      const gap = i === 1 ? 29 : i <= bodyEnd ? 18.5 : mix(15, 8, (i - bodyEnd) / (tailEnd - bodyEnd));
      spacings.push(spacings[i - 1] + gap * unit);
      radii.push(bodyRadius(i) + (i > bodyEnd ? 3.1 : 3.8) * unit);
    }

    cats = catColors.map((color, i) => {
      const seed = i * 2.8 + .72;
      const offset = rail.marks[i === 0 ? 5 : 13];
      const origin = offset + time * rail.pace;
      const cat = { color, seed, offset, trace: [], vx: 0, vy: 0, look: i === 0 ? .78 : -.78, tilt: 0 };
      for (let d = -spacings[tailEnd] - 125 * unit; d < 0; d += 4 * unit) {
        const p = fitToSky(railAt(origin + d), radii[0]);
        cat.trace.push({ x: p.x, y: p.y, d });
      }
      const head = fitToSky(railAt(origin), radii[0]);
      cat.trace.push({ x: head.x, y: head.y, d: 0 });
      cat.nodes = traceBody(cat, head, 0);
      return cat;
    });
    separate(cats[0].nodes, cats[1].nodes, -1, 16);
  }

  function target() {
    if (gesture && (pointer !== null || time < gesture.until)) return gesture;
    if (gesture) gesture = null;
    if (elapsedDemo === null) return null;
    const phase = mod(time - elapsedDemo, 20);
    let id, u;
    if (phase >= 4.5 && phase < 8.8) {
      id = 0;
      u = (phase - 4.5) / 4.3;
    } else if (phase >= 12.3 && phase < 16.6) {
      id = 1;
      u = (phase - 12.3) / 4.3;
    } else {
      return null;
    }
    const ahead = route(cats[id], .27);
    const lift = Math.sin(Math.PI * u);
    return {
      id, demo: true, x: clamp(ahead.x + Math.sin(u * TAU) * 64 * unit * lift, .11 * W, .89 * W),
      y: ahead.y + lift * unit * (id === 0 ? -88 : 65)
    };
  }

  function steer(cat, other, guide, dt) {
    const head = cat.nodes[0];
    let goal = route(cat, .21);
    if (guide) {
      const distance = Math.hypot(head.x - guide.x, head.y - guide.y);
      const drift = guide.demo ? 0 : (1 - smooth(distance / (116 * unit))) * 26 * unit;
      goal = {
        x: guide.x + Math.cos(time * 1.75 + cat.seed) * drift,
        y: guide.y + Math.sin(time * 1.75 + cat.seed) * drift * .77
      };
    }
    fitToSky(goal, radii[0]);
    const maxSpeed = guide ? Math.max(rail.pace * 1.68, 202 * unit) : Math.max(85 * unit, rail.pace * 1.55);
    let vx = (goal.x - head.x) * (guide ? 3.62 : 5.05);
    let vy = (goal.y - head.y) * (guide ? 3.62 : 5.05);
    const raw = Math.hypot(vx, vy);
    if (raw > maxSpeed) {
      vx *= maxSpeed / raw;
      vy *= maxSpeed / raw;
    }

    const lookX = head.x + vx * .14;
    const lookY = head.y + vy * .14;
    let pressure = 0, nx = 0, ny = 0;
    for (let i = 0; i < other.nodes.length; i += 2) {
      const dx = lookX - other.nodes[i].x, dy = lookY - other.nodes[i].y;
      const distance = Math.hypot(dx, dy);
      const cushion = radii[0] + radii[i] + 20 * unit;
      const overlap = 1 - distance / cushion;
      if (overlap > pressure && distance > .01) {
        pressure = overlap;
        nx = dx / distance;
        ny = dy / distance;
      }
    }
    if (pressure) {
      const turn = vx * -ny + vy * nx >= 0 ? 1 : -1;
      const lift = 142 * unit * pressure;
      vx += lift * (nx - turn * ny * .9);
      vy += lift * (ny + turn * nx * .9);
    }
    const ease = 1 - Math.exp(-dt * (guide ? 7.2 : 10));
    cat.vx = mix(cat.vx, vx, ease);
    cat.vy = mix(cat.vy, vy, ease);
    return fitToSky({ x: head.x + cat.vx * dt, y: head.y + cat.vy * dt }, radii[0]);
  }

  function advance(dt) {
    time += dt;
    const guide = target();
    const drafts = cats.map((cat, i) => traceBody(cat, steer(cat, cats[1 - i], guide?.id === i ? guide : null, dt), dt));
    separate(drafts[0], drafts[1], guide ? guide.id : -1, 6);
    const poses = separated(drafts[0], drafts[1]) ? drafts : restrainedStep(drafts);
    for (let i = 0; i < cats.length; i++) {
      const cat = cats[i], head = poses[i][0], old = cat.nodes[0];
      const dx = head.x - old.x, dy = head.y - old.y;
      const look = clamp(dx / Math.max(.5 * unit, Math.hypot(dx, dy)), -1, 1);
      const ease = 1 - Math.exp(-dt * 6.8);
      cat.look = mix(cat.look, look, ease);
      cat.tilt = mix(cat.tilt, clamp(dy / (Math.max(1, rail.pace) * dt) * .255, -.29, .29)
        + Math.sin(time * 2.6 + cat.seed) * .052, ease);
      cat.nodes = poses[i];
      const last = cat.trace[cat.trace.length - 1];
      const travel = Math.hypot(head.x - last.x, head.y - last.y);
      if (travel >= 2.5 * unit) {
        const distance = last.d + travel;
        cat.trace.push({ x: head.x, y: head.y, d: distance });
        const cutoff = distance - spacings[tailEnd] - 93 * unit;
        let oldest = 0;
        while (oldest + 2 < cat.trace.length && cat.trace[oldest + 1].d < cutoff) oldest++;
        if (oldest) cat.trace.splice(0, oldest);
      }
    }
  }

  function pierAndBridge(g, rng) {
    reflectionLights = [];
    for (const side of [-1, 1]) {
      g.beginPath();
      g.moveTo(shore(610, side), 610);
      for (let y = 614; y < H + 6; y += 3) g.lineTo(shore(y, side), y);
      for (let y = H + 6; y >= 610; y -= 3) g.lineTo(shore(y, side) + side * unit * (5 + (y - 610) * .054), y - 2);
      g.closePath();
      g.fillStyle = '#293440';
      g.fill();
      g.beginPath();
      g.moveTo(shore(618, side) + side * 2 * unit, 618);
      for (let y = 622; y <= H + 6; y += 3) g.lineTo(shore(y, side) + side * (2 + (y - 610) * .011) * unit, y);
      g.strokeStyle = 'rgba(169,157,151,.47)';
      g.lineWidth = unit;
      g.stroke();
      for (let y = 624; y < H; y += 4.4 + rng() * 5.4) {
        const x = shore(y, side);
        g.strokeStyle = rng() > .47 ? '#46505b' : '#1a2635';
        g.lineWidth = .8 * unit;
        g.beginPath();
        g.moveTo(x, y);
        g.lineTo(x + side * (3 + .046 * (y - 610)) * unit, y - 2.1 * unit);
        g.stroke();
      }
      for (const [i, y] of [653, 703, 755, 811, 878].entries()) {
        const x = shore(y, side) + 9 * side * unit;
        const h = (18 + i * 4.5) * unit;
        g.strokeStyle = '#111c29';
        g.lineWidth = (2 + i * .22) * unit;
        g.beginPath();
        g.moveTo(x, y + 3 * unit);
        g.lineTo(x, y - h);
        g.lineTo(x - 5 * side * unit, y - h);
        g.stroke();
        hangingLamp(g, x - 5 * side * unit, y - h + 6 * unit, (3.5 + i * .61) * unit, i % 2, .04 * side, .88);
        reflectionLights.push({ x: x - 5 * side * unit, y, side, heat: i % 2, reach: 25 + i * 9, phase: rng() * TAU });
      }
    }

    const x = W * .514, half = Math.min(.088 * W, 129 * unit);
    const deck = u => 615 - 32 * (1 - u * u);
    const span = new Path2D();
    span.moveTo(x - half, 614);
    span.quadraticCurveTo(x, 551.5, x + half, 614);
    span.lineTo(x + half, 634);
    span.lineTo(x + half * .72, 631);
    span.bezierCurveTo(x + half * .48, 582, x - half * .48, 582, x - half * .72, 631);
    span.lineTo(x - half, 635);
    span.closePath();
    const arch = g.createLinearGradient(0, 582, 0, 634);
    arch.addColorStop(0, '#5a4d50');
    arch.addColorStop(.53, '#3d3f4c');
    arch.addColorStop(1, '#202f3d');
    g.fillStyle = arch;
    g.fill(span);
    g.save();
    g.clip(span);
    g.strokeStyle = 'rgba(182,147,128,.25)';
    g.lineWidth = .82 * unit;
    for (let j = 0; j < 4; j++) {
      g.beginPath();
      const y = 5 + j * 5.5;
      g.moveTo(x - half, 613 + y);
      g.quadraticCurveTo(x, 553 + y, x + half, 613 + y);
      g.stroke();
    }
    for (let j = -9; j <= 9; j++) {
      const u = j / 9;
      g.beginPath();
      g.moveTo(x + u * half, deck(u) + 4);
      g.lineTo(x + u * half * 1.03, deck(u) + 26);
      g.stroke();
    }
    g.restore();
    g.strokeStyle = '#90766e';
    g.lineWidth = Math.max(.9, unit * 1.4);
    g.beginPath();
    g.moveTo(x - half, 611);
    g.quadraticCurveTo(x, 550, x + half, 611);
    g.stroke();
    g.strokeStyle = '#a0715f';
    g.lineWidth = Math.max(.85, unit * 2.2);
    g.beginPath();
    g.moveTo(x - half, 604 - 12 * unit);
    g.quadraticCurveTo(x, 555 - 14 * unit, x + half, 604 - 12 * unit);
    g.stroke();
    for (let j = -6; j <= 6; j++) {
      const u = j / 6;
      const px = x + half * u;
      const py = 583 + 24 * u * u;
      const top = 579 + 25 * u * u - 13 * unit;
      g.strokeStyle = j % 2 ? '#684a48' : '#93634e';
      g.lineWidth = (j % 2 ? 1.3 : 2.3) * unit;
      g.beginPath();
      g.moveTo(px, py);
      g.lineTo(px, top);
      g.stroke();
      if (j % 3 === 0) {
        hangingLamp(g, px, top + 6.4 * unit, 3.7 * unit, 0, 0, .94);
        reflectionLights.push({ x: px, y: 621, side: 0, heat: 0, reach: 32, phase: rng() * TAU });
      }
    }
  }

  function createWorld() {
    const quality = clamp(pixels * canvas.clientHeight / H, .9, 1.25);
    backing = bitmap(W, H, quality);
    stage = bitmap(W, H, quality);
    waterside = bitmap(W, H, quality);
    const rng = random(320241);
    sky(backing.g, rng);
    mountains(backing.g, rng);
    land(backing.g, rng);
    pierAndBridge(waterside.g, rng);
    water = channelPath();
    makeAir(rng);
  }

  function river(g) {
    g.save();
    g.clip(water);
    const base = g.createLinearGradient(0, 594, 0, 900);
    base.addColorStop(0, '#1b303e');
    base.addColorStop(.4, '#132e3d');
    base.addColorStop(.76, '#102636');
    base.addColorStop(1, '#071622');
    g.fillStyle = base;
    g.fillRect(0, 594, W, 310);
    const reflected = stage.image;
    const sourceScale = reflected.height / H;
    const dy = narrow > .72 ? 2.65 : 2.28;
    for (let y = 596; y < H + 2; y += dy) {
      const depth = (y - 594) / 306;
      const a = Math.sin(y * .129 - time * 2.3);
      const b = Math.sin(y * .292 + time * 2.1);
      const c = Math.sin(y * .061 - time * 1.2);
      const xShift = (4.3 * a + 5.6 * b + 7.5 * c) * (.36 + depth * 1.37) * unit;
      const sampleY = 604 - (y - 596) * 1.58 + (a * 1.15 + b * .7) * (.4 + depth);
      const stretch = .84 + .066 * depth + c * .009;
      const x = (W * .5) * (1 - stretch) + xShift + W * .016 * depth;
      g.globalAlpha = (.48 + .19 * b + .125 * c) * (1 - depth * .26);
      g.drawImage(reflected, 0, sampleY * sourceScale, reflected.width, 3.15 * sourceScale,
        x, y, W * stretch, dy + .53);
    }
    g.globalAlpha = 1;
    const depthShade = g.createLinearGradient(0, 595, 0, H);
    depthShade.addColorStop(0, 'rgba(14,41,53,.22)');
    depthShade.addColorStop(.73, 'rgba(8,25,39,.08)');
    depthShade.addColorStop(1, 'rgba(4,17,29,.30)');
    g.fillStyle = depthShade;
    g.fillRect(0, 594, W, 306);
    g.lineCap = 'round';
    for (const ripple of currents) {
      const depth = Math.pow(ripple.y, .83);
      const y = 601 + depth * 301;
      const left = shore(y, -1), right = shore(y, 1);
      const x = mix(left, right, ripple.x) + Math.sin(time * .67 + ripple.phase) * (1 + 7.5 * depth) * unit;
      const length = (3 + 46 * depth) * ripple.size * unit;
      const light = (.5 + .5 * Math.sin(time * 1.32 + ripple.phase)) * ripple.size;
      g.strokeStyle = ripple.tone > .83 ? 'rgba(247,169,113,' + (.032 + .19 * light) + ')' :
        'rgba(143,193,213,' + (.023 + .16 * light) + ')';
      g.lineWidth = .6 + depth * ripple.size;
      g.beginPath();
      g.moveTo(x - length * .52, y);
      g.quadraticCurveTo(x, y - .7 * depth, x + length * .48, y);
      g.stroke();
    }
    for (const light of reflectionLights) {
      for (let j = 0; j < 12; j++) {
        const u = j / 12;
        const y = light.y + 4 + u * light.reach;
        const drift = Math.sin(y * .194 - time * 2.31 + light.phase) + .52 * Math.cos(y * .41 + time * 1.7);
        const middle = light.side ? shore(y, light.side) - light.side * (5 + 13 * u) * unit : light.x;
        const x = middle + (3 + 6 * u) * drift * unit;
        const l = (2.9 + 16 * u) * (1 + .31 * drift) * unit;
        const a = (1 - u) * (.31 + .23 * drift);
        g.strokeStyle = light.heat ? 'rgba(255,127,79,' + clamp(a, 0, .6) + ')' :
          'rgba(255,198,126,' + clamp(a, 0, .6) + ')';
        g.lineWidth = (.84 + u * 1.04) * unit;
        g.beginPath();
        g.moveTo(x - l / 2, y);
        g.lineTo(x + l / 2, y + .3);
        g.stroke();
      }
    }
    g.restore();
  }

  function guideMark(g, guide) {
    if (!guide) return;
    const c = cats[guide.id].color;
    const p = { x: guide.x, y: guide.y };
    const alpha = guide.demo || pointer !== null ? .78 : smooth((guide.until - time) / .85) * .58;
    const radius = Math.max(11, 16 * unit) + Math.sin(time * 4.9) * 2.5 * unit;
    const ring = time * .52;
    g.save();
    g.globalAlpha = alpha;
    g.lineWidth = 1.2;
    g.lineCap = 'round';
    g.strokeStyle = c.whisker;
    for (let i = 0; i < 4; i++) {
      g.beginPath();
      g.arc(p.x, p.y, radius, i * Math.PI / 2 + ring, i * Math.PI / 2 + ring + .85);
      g.stroke();
    }
    glow(g, c.halo, p.x, p.y, radius * 2.1, radius * 2.1, .58);
    dot(g, p.x, p.y, 2.3 * Math.max(.7, unit), c.pale);
    g.restore();
  }

  function paint() {
    const g = stage.g;
    g.drawImage(backing.image, 0, 0, W, H);
    strings(g, false);
    airborne(g);
    lanternCat(g, cats[0]);
    lanternCat(g, cats[1]);
    strings(g, true);
    g.drawImage(waterside.image, 0, 0, W, H);

    const motion = reducedMotion.matches ? .36 : 1;
    const sweep = time * TAU / 20;
    const zoom = 1.027 + motion * (.015 + .01 * Math.cos(sweep));
    const x = Math.sin(sweep) * Math.min(20 * unit, W * .012) * motion;
    const y = Math.sin(sweep * .5 + .64) * 7.5 * motion;
    camera = { zoom, x: (1 - zoom) * W / 2 + x, y: (1 - zoom) * H / 2 + y };
    const s = canvas.height / H;
    screen.setTransform(s * camera.zoom, 0, 0, s * camera.zoom, s * camera.x, s * camera.y);
    screen.drawImage(stage.image, 0, 0, W, H);
    river(screen);
    screen.drawImage(waterside.image, 0, 0, W, H);
    const guide = target();
    guideMark(screen, guide);
    updateHud(guide);
  }

  function updateHud(guide) {
    const color = guide ? cats[guide.id].color : null;
    const message = color ? color.name + ' is following' : elapsedDemo !== null ? 'Demo playing' : 'Drag to guide a cat';
    if (hintText.textContent !== message) {
      hintText.textContent = message;
      hint.className = color ? 'hint ' + color.tone : 'hint';
    }
  }

  function setDemo(on) {
    elapsedDemo = on ? time : null;
    demoButton.setAttribute('aria-pressed', String(on));
    demoButton.querySelector('span').textContent = on ? 'Stop demo' : 'Play demo';
    if (on) gesture = null;
  }

  function clientPoint(event) {
    const box = canvas.getBoundingClientRect();
    return {
      x: ((event.clientX - box.left) / box.width * W - camera.x) / camera.zoom,
      y: ((event.clientY - box.top) / box.height * H - camera.y) / camera.zoom
    };
  }

  document.addEventListener('pointerdown', event => {
    if (event.target.closest('.demo')) return;
    if (elapsedDemo !== null) setDemo(false);
  }, true);

  canvas.addEventListener('pointerdown', event => {
    if (pointer !== null || (event.pointerType === 'mouse' && event.button !== 0) || !cats.length) return;
    const p = clientPoint(event);
    let id = 0, best = Infinity;
    for (let i = 0; i < cats.length; i++) {
      cats[i].nodes.forEach((node, j) => {
        const d = Math.hypot(node.x - p.x, node.y - p.y) - bodyRadius(j) * .48;
        if (d < best) {
          best = d;
          id = i;
        }
      });
    }
    pointer = event.pointerId;
    gesture = { x: p.x, y: p.y, id, until: time + 3.65, demo: false };
    canvas.setPointerCapture(event.pointerId);
  });

  canvas.addEventListener('pointermove', event => {
    if (event.pointerId !== pointer || !gesture) return;
    const p = clientPoint(event);
    gesture.x = p.x;
    gesture.y = p.y;
  });

  function release(event) {
    if (event.pointerId !== pointer) return;
    pointer = null;
    if (gesture) gesture.until = time + 3.65;
  }
  canvas.addEventListener('pointerup', release);
  canvas.addEventListener('pointercancel', release);
  canvas.addEventListener('lostpointercapture', release);
  demoButton.addEventListener('click', () => setDemo(elapsedDemo === null));
  window.addEventListener('hashchange', () => setDemo(location.hash === '#demo'));
  setDemo(elapsedDemo !== null);

  let audio = null, soundOn = false;
  const melody = [69, null, 71, 73, null, 76, 73, null, 71, null, 69, 66, null, 64, 66, null,
                  69, null, 73, 76, null, 78, 76, null, 73, 71, null, 69, 66, null, 64, null];
  const bass = [50, 45, 47, 43];

  function instrument() {
    const Audio = window.AudioContext || window.webkitAudioContext;
    if (!Audio) throw new Error('Web Audio unavailable');
    const context = new Audio();
    const master = context.createGain();
    const filter = context.createBiquadFilter();
    const delay = context.createDelay(.8);
    const echo = context.createGain();
    const feedback = context.createGain();
    delay.delayTime.value = .32;
    filter.type = 'lowpass';
    filter.frequency.value = 2710;
    master.gain.value = .0001;
    echo.gain.value = .23;
    feedback.gain.value = .25;
    filter.connect(master);
    filter.connect(delay);
    delay.connect(echo);
    echo.connect(master);
    delay.connect(feedback);
    feedback.connect(delay);
    master.connect(context.destination);
    return { context, master, filter, schedule: null, next: 0, index: 0 };
  }

  function note(midi, when, volume, duration, bassNote) {
    const ctx = audio.context;
    const fundamental = 440 * Math.pow(2, (midi - 69) / 12);
    const overtones = bassNote ? [1, 2] : [1, 2.003, 3.011];
    overtones.forEach((multiple, index) => {
      const oscillator = ctx.createOscillator();
      const amplitude = ctx.createGain();
      const end = when + duration * (index ? .64 : 1);
      oscillator.type = bassNote && index === 0 ? 'triangle' : 'sine';
      oscillator.frequency.value = fundamental * multiple;
      amplitude.gain.setValueAtTime(.0001, when);
      amplitude.gain.exponentialRampToValueAtTime(volume * (index === 0 ? 1 : index === 1 ? .23 : .071),
        when + (bassNote ? .086 : .023));
      amplitude.gain.exponentialRampToValueAtTime(.0001, end);
      oscillator.connect(amplitude);
      amplitude.connect(audio.filter);
      oscillator.start(when);
      oscillator.stop(end + .04);
    });
  }

  function scheduleMusic() {
    if (!audio || !soundOn || document.hidden || audio.context.state !== 'running') return;
    const now = audio.context.currentTime;
    if (audio.next < now) audio.next = now + .045;
    while (audio.next < now + .21) {
      const i = audio.index % melody.length;
      const when = audio.next;
      if (i % 8 === 0) {
        const low = bass[i / 8];
        note(low, when, .103, 2.7, true);
        note(low + 12, when + .11, .042, 1.84, true);
      } else if (i % 8 === 4) {
        note(bass[Math.floor(i / 8)] + 19, when, .043, 1.51, true);
      }
      const pitch = melody[i];
      if (pitch !== null) note(pitch, when, i % 4 === 0 ? .148 : .103, i % 2 ? .98 : 1.28, false);
      audio.index++;
      audio.next += i % 2 ? .419 : .439;
    }
  }

  function musicState() {
    if (!audio) return;
    const audible = soundOn && !document.hidden && audio.context.state === 'running';
    audio.master.gain.setTargetAtTime(audible ? .25 : .0001, audio.context.currentTime, .095);
    if (audible && audio.schedule === null) {
      scheduleMusic();
      audio.schedule = setInterval(scheduleMusic, 95);
    }
    if (!audible && audio.schedule !== null) {
      clearInterval(audio.schedule);
      audio.schedule = null;
    }
  }

  function soundHud(unavailable = false) {
    soundButton.setAttribute('aria-pressed', String(soundOn));
    soundButton.setAttribute('aria-label', soundOn ? 'Mute melody' : 'Unmute melody');
    soundButton.querySelector('span').textContent = unavailable ? 'Sound unavailable' : soundOn ? 'Sound on' : 'Sound off';
  }

  soundButton.addEventListener('click', async () => {
    if (soundOn) {
      soundOn = false;
      soundHud();
      musicState();
      return;
    }
    try {
      if (!audio) audio = instrument();
      soundOn = true;
      soundHud();
      await audio.context.resume();
      musicState();
    } catch {
      soundOn = false;
      soundHud(true);
      musicState();
    }
  });
  document.addEventListener('visibilitychange', musicState);

  function resize() {
    const box = canvas.getBoundingClientRect();
    const width = Math.max(1, box.width), height = Math.max(1, box.height);
    pixels = Math.min(window.devicePixelRatio || 1, 1.75, Math.sqrt(3250000 / (width * height)));
    canvas.width = Math.max(1, Math.round(width * pixels));
    canvas.height = Math.max(1, Math.round(height * pixels));
    W = H * canvas.width / canvas.height;
    narrow = clamp((920 - W) / 520, 0, 1);
    unit = clamp(Math.sqrt(W / 1440), .38, 1.23) * Math.min(1, W / 330);
    houseUnit = clamp(W / 1440 * (1 + .34 * narrow), .19, 1.29);
    createWorld();
    setupCats();
    gesture = null;
    pointer = null;
    needsResize = false;
  }

  window.addEventListener('resize', () => { needsResize = true; });
  let lastFrame = performance.now();
  function frame(now) {
    if (needsResize) resize();
    const dt = clamp((now - lastFrame) / 1000, 0, .045);
    lastFrame = now;
    if (dt > 0) {
      const steps = Math.ceil(dt / (1 / 58));
      for (let i = 0; i < steps; i++) advance(dt / steps);
    }
    paint();
    requestAnimationFrame(frame);
  }
  requestAnimationFrame(frame);
})();
</script>
</body>
</html>