Back to The Bathyal Post
SOURCE / PINNED RELEASE

Made of little things.

The Bathyal Post

Release
fa6ce530b9f3…
Author-recorded commit
b255b3c9fd49…
License
LICENSE
Author’s source reference
nostr://npub182jczunncwe0jn6frpqwq3e0qjws7yqqnc3auccqv9nte2dnd63scjm4rf/wss%3A%2F%2Fgit.napplet.soy%2F/n-55c50b9a042

Archive hash verified: 03cf62191e7476c5…. The source-to-build association is the author’s claim; it has not been independently rebuilt.

src/chart.ts
/// <reference types="vite/client" />
import plateUrl from './art/specimens.webp?inline';

/** The engraved chart and the bell share CSS-pixel coordinates. Soundings and
 * passage costs belong to the voyage; this renderer only presents its map. */
export type StationId = 'buoy' | 'medusa' | 'vent' | 'wreck' | 'whale' | 'garden' | 'trench';
export type ChartPulse = 'delivery' | 'danger' | 'repair' | 'sonar';
export interface ChartState {
  current: StationId;
  selected: StationId | null;
  reachable: readonly StationId[];
  routes: readonly (readonly [StationId, StationId])[];
  course?: readonly StationId[];
  labels: Partial<Record<StationId, string>>;
  depths?: Partial<Record<StationId, number>>;
  letters?: readonly StationId[];
  visited?: readonly StationId[];
  danger?: boolean;
  hunted?: StationId | null;
  reducedMotion?: boolean;
}

type Brush = CanvasRenderingContext2D;
interface Point {
  x: number;
  y: number;
}
interface Specimen {
  id: StationId;
  x: number;
  y: number;
  mobileX: number;
  mobileY: number;
  extent: number;
  draw: (g: Brush) => void;
}
const TAU = 2 * Math.PI;
const ink = '#09232b';
const vermilion = '#ff9874';
const ivory = '#f4e6c9';
const brass = '#e6bf83';
const clamp = (n: number, a: number, b: number) => Math.min(b, Math.max(a, n));

function randomSource(seed: number) {
  let state = seed >>> 0;
  return () => {
    state = (Math.imul(1664525, state) + 1013904223) >>> 0;
    return state / 4294967296;
  };
}

function path(g: Brush, d: string, fill: string | null, stroke?: string, width = 1) {
  const p = new Path2D(d);
  if (fill) {
    g.fillStyle = fill;
    g.fill(p);
  }
  if (stroke) {
    g.strokeStyle = stroke;
    g.lineWidth = width;
    g.stroke(p);
  }
  return p;
}

function line(g: Brush, points: number[], color: string, width = 1) {
  g.beginPath();
  g.moveTo(points[0], points[1]);
  for (let i = 2; i < points.length; i += 2) g.lineTo(points[i], points[i + 1]);
  g.strokeStyle = color;
  g.lineWidth = width;
  g.stroke();
}

function ellipse(
  g: Brush,
  x: number,
  y: number,
  rx: number,
  ry: number,
  fill: string | null,
  stroke?: string,
  width = 1
) {
  g.beginPath();
  g.ellipse(x, y, rx, ry, 0, 0, TAU);
  if (fill) {
    g.fillStyle = fill;
    g.fill();
  }
  if (stroke) {
    g.strokeStyle = stroke;
    g.lineWidth = width;
    g.stroke();
  }
}

function glow(g: Brush, x: number, y: number, radius: number, color: string) {
  const gradient = g.createRadialGradient(x, y, 0, x, y, radius);
  gradient.addColorStop(0, color);
  gradient.addColorStop(1, 'rgba(0,0,0,0)');
  g.fillStyle = gradient;
  g.fillRect(x - radius, y - radius, radius * 2, radius * 2);
}

// Form lines follow the animals' anatomy as on an intaglio plate.
function whale(g: Brush) {
  g.save();
  g.rotate(-0.065);
  path(
    g,
    'M44 -4 Q59 -11 66 -26 Q64 -15 70 -15 Q79 -19 88 -18 Q77 -8 65 -6 Q57 0 46 3Z',
    '#39616a',
    '#8caeaa',
    0.95
  );
  path(g, 'M62 -9 Q66 -16 66 -21 M66 -9 Q75 -15 82 -16 M65 -7 Q73 -11 79 -12', null, '#91aaa4', 0.65);
  const body = path(
    g,
    'M-72 -9 Q-72 -18 -58 -20 C-38 -24 -7 -17 10 -14 Q22 -13 29 -20 L32 -12 Q42 -10 53 -13 Q61 -16 64 -14 Q54 -8 48 -4 C34 4 17 9 -1 12 C-12 18 -33 21 -49 15 Q-60 12 -67 8 Q-73 4 -72 -9Z',
    '#42727a',
    '#a2c5ba',
    1.35
  );
  g.save();
  g.clip(body);
  const water = g.createLinearGradient(0, -23, 0, 18);
  water.addColorStop(0, '#6e9691');
  water.addColorStop(0.35, '#44747b');
  water.addColorStop(0.66, '#2a515c');
  water.addColorStop(1, '#a3c1a8');
  g.fillStyle = water;
  g.fillRect(-76, -27, 155, 55);
  for (let i = 0; i < 17; i++) {
    const y = -24 + i * 2.9;
    path(
      g,
      `M-77 ${y} Q-56 ${y - 4} -38 ${y + 0.4} T-4 ${y + 1} Q26 ${y + 2} 64 ${y - 11}`,
      null,
      i % 3 === 0 ? '#aac9b66b' : '#173f4c91',
      0.65
    );
  }
  const rand = randomSource(7410);
  for (let i = 0; i < 460; i++) {
    const x = -75 + rand() * 141,
      y = rand() * 47 - 23;
    line(g, [x, y, x + rand() * 1.5 + 0.4, y + rand() * 0.7], i % 3 ? '#c3cfb750' : '#152f3d60', 0.49);
  }
  g.restore();
  path(g, 'M-67 5 C-59 9 -47 9 -37 8 Q-32 8 -29 5 M-59 11 Q-47 14 -39 12', null, '#193f4b', 1.25);
  path(g, 'M-50 13 Q-32 23 -18 15 M-47 11 Q-31 20 -20 14', null, '#c1cbb2', 0.75);
  path(g, 'M-17 7 C-17 15 -8 26 -1 28 Q1 22 -4 16 Q-8 11 -8 7', '#3a666f', '#a4beb2', 1);
  path(g, 'M-14 11 Q-11 18 -3 24 M-10 11 Q-7 16 -4 18', null, '#91aaa4', 0.7);
  ellipse(g, -37, 4.2, 3.2, 2.2, '#193943', '#afc3aa', 0.65);
  ellipse(g, -37.7, 3.5, 0.9, 0.77, '#f5eaca');
  path(g, 'M-56 -16 Q-52 -19 -47 -17 M-54 -20 Q-54 -23 -58 -24', null, '#d1d6bc', 0.72);
  g.restore();
}

function jelly(g: Brush) {
  const rand = randomSource(362);
  glow(g, 0, -10, 47, '#74c9c537');
  for (let i = 0; i < 20; i++) {
    const x = -27 + i * 2.8;
    const bottom = 10 + rand() * 28 + Math.cos((i - 9.5) * 0.14) * 11;
    const warp = rand() * 10;
    path(
      g,
      `M${x} -5 C${x + 7} 0 ${x + warp - 9} 8 ${x + warp - 5} 14 S${x + warp + 3} ${bottom - 5} ${x + warp - 8} ${bottom}`,
      null,
      i % 3 ? '#96d3c5c2' : '#e0dfb9cd',
      i % 5 ? 0.73 : 1.25
    );
  }
  for (const x of [-13, -5, 6, 13]) {
    const p = new Path2D();
    p.moveTo(x, -7);
    for (let i = 0; i < 33; i++) {
      const y = i * 1.3 - 6,
        jog = 3.7 * Math.sin(i * 0.42 + x) + 2.0 * Math.cos(i * 1.88);
      p.lineTo(x + jog - i * 0.11, y);
    }
    g.strokeStyle = '#6eaba7';
    g.lineWidth = 3.2;
    g.stroke(p);
    g.strokeStyle = '#d9debb';
    g.lineWidth = 0.75;
    g.stroke(p);
  }
  const crown = path(
    g,
    'M-32 -7 C-31 -25 -20 -39 -3 -40 C13 -41 29 -26 32 -9 Q29 -4 26 -8 Q23 -3 20 -7 Q16 -2 12 -6 Q7 -1 3 -6 Q-1 -1 -6 -5 Q-10 -1 -14 -6 Q-19 -2 -22 -7 Q-29 -3 -32 -7Z',
    '#70a8a5',
    '#daeccd',
    1.25
  );
  g.save();
  g.clip(crown);
  const shading = g.createLinearGradient(0, -40, 0, -5);
  shading.addColorStop(0, '#e0e8c7');
  shading.addColorStop(0.3, '#9ec9b5');
  shading.addColorStop(0.74, '#426f7b');
  shading.addColorStop(1, '#99b7a7');
  g.fillStyle = shading;
  g.fillRect(-35, -42, 71, 42);
  for (let i = -9; i <= 9; i++) {
    const x = i * 3.5;
    path(
      g,
      `M-2 -39 Q${x * 0.82} -35 ${x} -9 Q${x} -5 ${x - 1} -3`,
      null,
      i % 2 ? '#f4f0c9ca' : '#477982',
      0.73
    );
  }
  for (let i = 0; i < 3; i++)
    path(
      g,
      `M-34 ${-10 - i * 2} Q-14 ${-15 - i * 2.6} 0 ${-12 - i * 2} T33 ${-11 - i * 2}`,
      null,
      '#d8e7c9b0',
      0.65
    );
  for (let i = 0; i < 175; i++) {
    const x = -33 + rand() * 67,
      y = -39 + rand() * 32;
    ellipse(g, x, y, 0.55, 0.38, i % 2 ? '#edf0ce9e' : '#365b7066');
  }
  g.restore();
}

function buoy(g: Brush) {
  // A tiny surface post with a pennant, catwalk and iron lattice legs.
  path(g, 'M-21 -2 Q-1 2 18 -2 L13 5 Q0 9 -17 5Z', '#647977', '#c6c7ac', 0.95);
  line(g, [-22, -3, 20, -3], '#d9d7b6', 1.4);
  path(g, 'M-8 -4 L-4 -23 L2 -23 L8 -4 Z', '#476169', '#bac5b0', 0.9);
  path(g, 'M-6 -6 L2 -19 L-3 -16 L5 -6 M-5 -11 L4 -11 M-4 -16 L3 -16', null, '#b7bda7', 0.75);
  path(g, 'M-5 -23 L-4 -31 L3 -31 L3 -23Z', '#e2c987', '#b8c8b5', 0.8);
  path(g, 'M-7 -31 L-1 -36 L5 -31Z', '#677971', '#cacfb7', 0.8);
  line(g, [-1, -35, -1, -53], '#d9ccb0', 0.95);
  path(g, 'M0 -51 C4 -52 7 -46 15 -49 L11 -43 Q5 -42 0 -45Z', '#ce765c', '#e89e78', 0.75);
  path(g, 'M-19 -2 L-19 -8 L-10 -8 L-10 -3 M11 -3 L11 -8 L17 -8 L17 -3', null, '#b7c3af', 0.87);
  for (let j = 0; j < 5; j++)
    path(
      g,
      `M${-28 + j * 1.7} ${5 + j * 2.2} Q-16 ${7 + j * 2} -6 ${5 + j * 1.9} T${26 - j * 3} ${6 + j * 1.9}`,
      null,
      '#9cc0b068',
      0.65
    );
  glow(g, -0.5, -27, 12, '#ffe6a54f');
}

function vent(g: Brush) {
  const rand = randomSource(371);
  for (let i = 0; i < 19; i++) {
    const x = rand() * 32 - 16,
      y = rand() * 25 - 48;
    path(g, `M${x} ${y + 8} q-8 -5 -2 -12 t-1 -11`, null, '#9dc0b64d', 0.75);
  }
  const chimney = (x: number, h: number, w: number) => {
    path(
      g,
      `M${x - w * 1.6} 8 Q${x - w * 0.8} 3 ${x - w * 0.65} ${-h * 0.35} L${x - w * 0.5} ${-h} Q${x} ${-h - 2} ${x + w * 0.47} ${-h + 1} L${x + w * 0.45} ${-h * 0.53} Q${x + w * 0.46} -4 ${x + w * 1.4} 7Z`,
      '#436971',
      '#99b1a5',
      0.9
    );
    for (let i = 0; i < Math.floor(h / 2.4); i++) {
      const p = i * 2.35;
      line(
        g,
        [x - w * (0.55 + 0.5 * (p / h) ** 2), -h + p + 1, x - 0.8, -h + p + 2.3, x + w * 0.39, -h + p + 1.3],
        '#83958a',
        0.55
      );
    }
    ellipse(g, x, -h, w * 0.5, 1.8, '#243c46', '#d0c69e', 0.9);
    glow(g, x, -h, 7, '#deb67934');
  };
  chimney(-17, 17, 6);
  chimney(10, 28, 7);
  chimney(-3, 36, 8);
  chimney(21, 13, 5);
  path(g, 'M-33 10 Q-22 2 -16 5 T-2 6 L9 3 L19 5 Q28 4 34 10Z', '#35565e', '#8ba69a', 0.7);
}

function wreck(g: Brush) {
  g.save();
  g.rotate(-0.12);
  const hull = path(
    g,
    'M-39 -9 Q-7 -4 39 -10 L31 4 L20 11 L-18 12 Q-33 7 -39 -9Z',
    '#4d625f',
    '#c5b69a',
    1.05
  );
  g.save();
  g.clip(hull);
  for (let j = 0; j < 8; j++)
    path(g, `M-43 ${-8 + 3 * j} Q-6 ${2 + 3 * j} 41 ${-10 + 3 * j}`, null, '#b8ad8b', 0.8);
  for (let i = 0; i < 9; i++) line(g, [-39 + i * 9, -12, -32 + i * 8, 14], '#30474b', 1.4);
  g.restore();
  path(
    g,
    'M-28 -6 L-30 -31 L-27 -34 L-26 -6 M4 -6 L4 -43 L6 -42 L6 -5 M-3 -32 L17 -35 M-35 -22 L-18 -25',
    null,
    '#c2b695',
    1.18
  );
  path(
    g,
    'M5 -39 Q-6 -18 -26 -7 M5 -39 Q17 -18 33 -11 M-29 -30 Q-23 -17 -12 -8 M-29 -28 L-38 -8 M17 -35 L26 -11',
    null,
    '#96a896',
    0.74
  );
  path(g, 'M3 -32 Q-1 -22 -5 -19 L-1 -20 L1 -17 L3 -19 L7 -17 Q4 -24 6 -33Z', '#859188', '#c1bca1', 0.68);
  line(g, [-40, -10, -45, -19], '#c2bb9f', 0.85);
  g.restore();
}

function garden(g: Brush) {
  const rand = randomSource(61);
  for (let i = 0; i < 15; i++) {
    const root = -30 + i * 4.2,
      h = 16 + rand() * 27,
      bend = root * 0.25 + rand() * 6 - 3;
    const stalk = (t: number) => ({ x: root + bend * t * t + 1.1 * Math.sin(t * 4), y: 6 - h * t });
    const p = new Path2D();
    p.moveTo(root, 6);
    const tone = i % 3 === 0 ? '#d4bc90' : i % 3 === 1 ? '#90c7aa' : '#70a9a5';
    for (let j = 1; j <= 16; j++) {
      const t = j / 16,
        a = stalk(t);
      p.lineTo(a.x, a.y);
      const sz = Math.sin(Math.PI * t * 0.99) ** 0.6 * (2.8 + h * 0.075);
      for (const sign of [-1, 1]) {
        const length = sz * (0.65 + rand() * 0.5);
        path(
          g,
          `M${a.x} ${a.y} q${sign * length * 0.72} ${-length * 0.13} ${sign * length} ${-length * 0.95}`,
          null,
          tone,
          0.64
        );
      }
    }
    g.strokeStyle = tone;
    g.lineWidth = 0.78;
    g.stroke(p);
    const tip = stalk(1);
    ellipse(g, tip.x, tip.y, 0.85, 1.05, '#e4e8b9');
  }
  path(g, 'M-34 7 Q-23 2 -13 6 Q-3 3 5 6 T31 7', null, '#b3b89b', 1);
}

function angler(g: Brush) {
  path(
    g,
    'M-20 -6 C-8 -21 10 -21 19 -11 L33 -15 L29 -7 L34 -2 L20 -3 C15 5 4 11 -8 7 Q-15 6 -21 1 L-27 -7 L-20 -4Z',
    '#32525c',
    '#93a99e',
    1
  );
  path(g, 'M-17 -12 C-26 -29 -37 -24 -36 -14', null, '#becab1', 1);
  glow(g, -36, -14, 12, '#9fedcf69');
  ellipse(g, -36, -14, 2.15, 2.45, '#cde8be');
  for (let i = 0; i < 6; i++)
    line(
      g,
      [-24 + i * 1.8, -4 + i * 0.5, -22 + i * 1.8, 0.2 + i * 0.45, -20 + i * 1.3, -2.4 + i * 0.4],
      '#d4c6a3',
      0.52
    );
  for (let i = 0; i < 7; i++) path(g, `M${-3 + i * 2.3} -14 q7 10 -2 19`, null, '#738c86', 0.56);
  path(g, 'M-4 2 Q-3 10 4 12 L5 8 L2 2', '#54797a', '#8dac9e', 0.8);
  ellipse(g, -14, -9, 2, 2, '#dbd9b4');
  ellipse(g, -14.3, -9.2, 0.95, 1, '#27414b');
}

const specimens: readonly Specimen[] = [
  { id: 'buoy', x: 0.145, y: 0.235, mobileX: 0.2, mobileY: 0.25, extent: 27, draw: buoy },
  { id: 'medusa', x: 0.445, y: 0.31, mobileX: 0.49, mobileY: 0.425, extent: 37, draw: jelly },
  { id: 'whale', x: 0.79, y: 0.265, mobileX: 0.77, mobileY: 0.225, extent: 79, draw: whale },
  { id: 'vent', x: 0.175, y: 0.615, mobileX: 0.175, mobileY: 0.585, extent: 33, draw: vent },
  { id: 'wreck', x: 0.54, y: 0.605, mobileX: 0.77, mobileY: 0.595, extent: 42, draw: wreck },
  { id: 'garden', x: 0.8, y: 0.79, mobileX: 0.72, mobileY: 0.805, extent: 35, draw: garden },
  { id: 'trench', x: 0.4, y: 0.845, mobileX: 0.265, mobileY: 0.82, extent: 39, draw: angler },
];

function drawBell(g: Brush) {
  // Hand riveted bell, counterweight shoes, Fresnel eye and a travelling light.
  glow(g, 0, -1, 37, '#e7ac6b3f');
  path(g, 'M10 -1 L59 -15 Q64 0 59 13 L10 3Z', '#e8d0a110');
  path(g, 'M-9 7 L-10 13 L-7 14 L-5 8 M6 8 L7 13 L11 13 L10 7', '#5d6260', '#c9a787', 0.8);
  ellipse(g, 0, -14, 3.4, 3.8, null, '#d4a771', 1.7);
  const bell = path(
    g,
    'M-13 6 L-12 -3 Q-11 -13 -2 -15 Q6 -16 11 -9 L13 -1 L14 7 Q0 12 -13 6Z',
    '#d97547',
    '#ffe2ad',
    1.2
  );
  g.save();
  g.clip(bell);
  const paint = g.createLinearGradient(-13, -3, 14, 1);
  paint.addColorStop(0, '#844432');
  paint.addColorStop(0.23, '#d57750');
  paint.addColorStop(0.48, '#f1ad70');
  paint.addColorStop(0.7, '#d17a48');
  paint.addColorStop(1, '#875235');
  g.fillStyle = paint;
  g.fillRect(-16, -19, 33, 32);
  path(g, 'M-9 8 Q-12 -6 -4 -14 M8 7 Q10 -6 3 -14', null, '#9b5f44', 0.75);
  for (let j = 0; j < 5; j++) line(g, [-10, -4 + j * 2.1, -6, -4.8 + j * 2.1], '#f1bd86', 0.6);
  g.restore();
  ellipse(g, 1, -3, 5.8, 6.1, '#81593e', '#ffe1b2', 1.15);
  ellipse(g, 1, -3, 4.1, 4.35, '#285862', '#6e604e', 0.85);
  path(g, 'M-1.7 -3.7 Q-1.1 -6.8 1 -6.9', null, '#d2f1d1', 1.05);
  path(g, 'M-13 4 Q0 7 13 4 L15 8 Q0 13 -15 8Z', '#845b42', '#eeb980', 1.0);
  for (let i = 0; i < 6; i++) ellipse(g, -10 + i * 4, 7.8 + Math.sin(i * 0.65), 0.65, 0.65, '#ffdbac');
  ellipse(g, 12, -1, 2, 3.6, '#ffe4a1', '#9e7349', 0.7);
}

function relief(x: number, y: number) {
  const u = x + 0.018 * Math.sin(y * 19 + x * 8) + 0.008 * Math.sin(y * 40 - x * 17);
  const v = y + 0.018 * Math.sin(x * 24 + y * 7) + 0.008 * Math.cos(x * 49 + y * 13);
  // Two opposing shelves and the split lip of the trench. Their ridges fade into open water.
  const west = (0.09 + 0.075 * Math.sin(v * 6 + 0.8) + 0.022 * Math.sin(v * 14) - u) * 2.5;
  const east = (u - 0.94 + 0.075 * Math.sin(v * 5.2 - 1.8) + 0.03 * Math.cos(v * 14)) * 2.8;
  const floor = (v - 0.98 + 0.11 * Math.cos(u * 8.2 + 0.7) + 0.055 * Math.sin(u * 16)) * 1.85;
  const island = -0.2 + 0.15 * Math.exp(-(((u - 0.55) / 0.13) ** 2 + ((v - 0.61) / 0.1) ** 2));
  return Math.max(west, east, floor, island);
}

function makeSeabed(g: Brush, w: number, h: number) {
  const rand = randomSource(48162);
  const shade = document.createElement('canvas');
  shade.width = Math.max(1, Math.ceil(w / 1.75));
  shade.height = Math.max(1, Math.ceil(h / 1.75));
  const bg = shade.getContext('2d')!;
  const tile = bg.createImageData(shade.width, shade.height);
  for (let j = 0; j < shade.height; j++) {
    const y = j / shade.height;
    for (let i = 0; i < shade.width; i++) {
      const x = i / shade.width,
        idx = (j * shade.width + i) * 4;
      const z = relief(x, y);
      const raised = clamp((z + 0.12) * 2.8, 0, 0.94);
      const light = clamp((0.95 - y) * 0.62 + 0.25 * Math.sin(x * 4 + 0.1) - 0.1, 0, 1);
      const speck = (rand() - 0.5) * 5.4;
      tile.data[idx] = 8 + raised * 11 + light * 9 + speck;
      tile.data[idx + 1] = 30 + raised * 31 + light * 24 + speck;
      tile.data[idx + 2] = 38 + raised * 28 + light * 18 + speck;
      tile.data[idx + 3] = 255;
    }
  }
  bg.putImageData(tile, 0, 0);
  g.drawImage(shade, 0, 0, w, h);

  // Fine grid lets the same relief be printed crisply at every frame size.
  const cell = clamp(Math.min(w, h) / 99, 3, 7);
  const cols = Math.ceil(w / cell) + 1,
    rows = Math.ceil(h / cell) + 1;
  const heights = new Float32Array(cols * rows);
  for (let j = 0; j < rows; j++)
    for (let i = 0; i < cols; i++) heights[j * cols + i] = relief((i * cell) / w, (j * cell) / h);
  const paths = Array.from({ length: 56 }, () => new Path2D());
  const first = -0.17,
    heightStep = 0.0108;
  for (let j = 0; j < rows - 1; j++)
    for (let i = 0; i < cols - 1; i++) {
      const a = heights[j * cols + i],
        b = heights[j * cols + i + 1],
        c = heights[(j + 1) * cols + i + 1],
        d = heights[(j + 1) * cols + i];
      const low = Math.max(0, Math.ceil((Math.min(a, b, c, d) - first) / heightStep));
      const high = Math.min(paths.length - 1, Math.floor((Math.max(a, b, c, d) - first) / heightStep));
      for (let k = low; k <= high; k++) {
        const z = first + k * heightStep,
          pts: number[] = [];
        if (a > z !== b > z) pts.push(i + (z - a) / (b - a), j);
        if (b > z !== c > z) pts.push(i + 1, j + (z - b) / (c - b));
        if (c > z !== d > z) pts.push(i + (z - d) / (c - d), j + 1);
        if (a > z !== d > z) pts.push(i, j + (z - a) / (d - a));
        for (let p = 0; p + 3 < pts.length; p += 4) {
          paths[k].moveTo(pts[p] * cell, pts[p + 1] * cell);
          paths[k].lineTo(pts[p + 2] * cell, pts[p + 3] * cell);
        }
      }
    }
  paths.forEach((p, k) => {
    const major = k % 5 === 0;
    const opacity = (major ? 0.4 : 0.22) * clamp((k + 1) / 10, 0.19, 1);
    g.lineWidth = major ? 1.05 : 0.72;
    g.strokeStyle = `rgba(151,193,166,${opacity})`;
    g.stroke(p);
  });

  for (let j = 0; j < Math.min(12500, (w * h) / 53); j++) {
    const x = rand() * w,
      y = rand() * h;
    const z = relief(x / w, y / h);
    if (z < -0.13 && rand() < 0.82) continue;
    const length = z > -0.01 ? 1.7 : 1;
    const c = rand() > 0.52 ? '#c8d5b12d' : '#0619224b';
    line(g, [x, y, x + rand() * length * 0.7, y - rand() * length], c, 0.7);
  }
}

function kelp(g: Brush, x: number, y: number, size: number, seed: number) {
  const rand = randomSource(seed);
  g.save();
  g.translate(x, y);
  g.scale(size, size);
  for (let plant = 0; plant < 8; plant++) {
    const root = rand() * 28 - 14,
      height = 14 + rand() * 35,
      lean = rand() * 15 - 7.5,
      phase = rand() * 3;
    const pos = (t: number) => ({ x: root + Math.sin(phase + t * 4) * t * 5.3 + lean * t, y: -height * t });
    const stem = new Path2D();
    stem.moveTo(root, 0);
    for (let j = 1; j <= 15; j++) {
      const t = j / 15,
        a = pos(t);
      stem.lineTo(a.x, a.y);
      if (j % 2 === 1) {
        const side = j % 4 === 1 ? 1 : -1,
          span = (5 + rand() * 5) * (1 - t * 0.7);
        path(
          g,
          `M${a.x} ${a.y} q${side * span * 0.2} -6 ${side * span} ${-span * 1.7} q${side * 2} ${span * 0.78} ${-side * span} ${span * 1.7}`,
          '#63887b44',
          '#83a69a55',
          0.55
        );
      }
    }
    g.strokeStyle = '#9bb6a273';
    g.lineWidth = 0.7;
    g.stroke(stem);
  }
  g.restore();
}

function gridAndSea(g: Brush, w: number, h: number) {
  const short = w < 520 || h < 320,
    tick = short ? 32 : 48;
  let row = 0;
  for (let y = tick / 2; y < h; y += tick, row++) {
    if (!short && row % 2 === 1) {
      g.setLineDash([1, 6]);
      line(g, [0, y, w, y], '#a8c6b41b', 0.75);
      g.setLineDash([]);
    }
    for (let x = tick * 0.68; x < w; x += tick) {
      line(g, [x - 2, y, x + 2, y], '#a7c8b536', 0.7);
      line(g, [x, y - 2, x, y + 2], '#a7c8b536', 0.7);
    }
    line(g, [2, y, short ? 6 : 9, y], '#b2c2ae77', 0.8);
    line(g, [w - 6, y, w - 1, y], '#b2c2ae5b', 0.8);
  }
  for (let x = tick * 0.68; x < w; x += tick) {
    line(g, [x, 1, x, 5], '#b2c2ae55', 0.8);
    line(g, [x, h - 5, x, h - 1], '#b2c2ae55', 0.8);
  }
  const u = clamp(Math.min(w / 680, h / 350), 0.62, 1.75);
  kelp(g, w * 0.063, h * 0.81, u, 61);
  kelp(g, w * 0.94, h * 0.71, u * 0.83, 263);
  kelp(g, w * 0.138, h * 0.961, u * 0.78, 284);
  if (w > 510) {
    kelp(g, w * 0.979, h * 0.42, u * 0.66, 116);
    kelp(g, w * 0.84, h * 1.032, u * 0.76, 212);
  }
  if (w >= 600 && h >= 290) {
    g.save();
    g.font = '9px ui-monospace, monospace';
    g.fillStyle = '#abc3aa8c';
    for (let i = 1; i < 5; i++) {
      const y = (h * 0.9 * i) / 5 + h * 0.06;
      g.save();
      g.translate(12, y);
      g.rotate(-Math.PI / 2);
      g.textAlign = 'center';
      g.fillText(`${i * 250} m`, 0, 0);
      g.restore();
    }
    g.restore();
  }
}

function makeLayer(w: number, h: number, pixelRatio: number, paint: (g: Brush) => void) {
  const layer = document.createElement('canvas');
  layer.width = Math.max(1, Math.round(w * pixelRatio));
  layer.height = Math.max(1, Math.round(h * pixelRatio));
  const g = layer.getContext('2d')!;
  g.scale(layer.width / w, layer.height / h);
  g.lineCap = 'round';
  g.lineJoin = 'round';
  paint(g);
  return layer;
}

const neutralLabels: Record<StationId, string> = {
  buoy: 'Post Buoy',
  medusa: 'Bell Medusa',
  vent: 'Breathing Vent',
  wreck: 'Postal Wreck',
  whale: 'Choir Whale',
  garden: 'Lamp Garden',
  trench: 'Trench Mouth',
};

interface RouteArc {
  a: Point;
  b: Point;
  c: Point;
}
function curve(a: Point, b: Point): RouteArc {
  const dx = b.x - a.x,
    dy = b.y - a.y;
  const sign = dx > 0 || (dx === 0 && dy > 0) ? 1 : -1;
  return { a, b, c: { x: (a.x + b.x) * 0.5 + dy * 0.095 * sign, y: (a.y + b.y) * 0.5 - dx * 0.095 * sign } };
}
function along({ a, b, c }: RouteArc, t: number) {
  const s = 1 - t;
  return { x: s * s * a.x + 2 * s * t * c.x + t * t * b.x, y: s * s * a.y + 2 * s * t * c.y + t * t * b.y };
}
function trace(g: Brush, route: RouteArc) {
  g.beginPath();
  g.moveTo(route.a.x, route.a.y);
  g.quadraticCurveTo(route.c.x, route.c.y, route.b.x, route.b.y);
}

type LabelSize = { x: number; y: number; width: number; height: number };
interface Movement {
  from: StationId;
  to: StationId;
  start: number;
}
interface Burst {
  kind: ChartPulse;
  start: number;
  at: StationId;
}

type Engravings = Partial<Record<StationId, HTMLCanvasElement>>;

// Isolate the engraved ink from the paper used for the four letter illustrations.
// The cream paper recedes into transparent water. Each silhouette is printed in
// its own phosphorescent ink, retaining the hatch spacing of the original plate.
async function inkPlates(): Promise<Engravings> {
  const plate = new Image();
  plate.src = plateUrl;
  await plate.decode();
  const result: Engravings = {};
  const cells: [StationId, number, number, number[]][] = [
    ['medusa', 0, 0, [166, 220, 193]],
    ['whale', 1, 0, [158, 197, 191]],
    ['garden', 0, 1, [169, 195, 155]],
    ['trench', 1, 1, [159, 163, 174]],
  ];
  for (const [id, col, row, color] of cells) {
    const image = document.createElement('canvas');
    const cellW = plate.naturalWidth / 2,
      cellH = plate.naturalHeight / 2;
    image.width = Math.min(cellW, 480);
    image.height = Math.min(cellH, 480);
    const ctx = image.getContext('2d', { willReadFrequently: true })!;
    ctx.drawImage(
      plate,
      col * cellW + 2,
      row * cellH + 2,
      cellW - 4,
      cellH - 4,
      0,
      0,
      image.width,
      image.height
    );
    const pixels = ctx.getImageData(0, 0, image.width, image.height),
      data = pixels.data;
    for (let y = 0; y < image.height; y++)
      for (let x = 0; x < image.width; x++) {
        const i = (y * image.width + x) * 4;
        const red = data[i],
          green = data[i + 1];
        const amount = Math.max((234 - red) / 201, (199 - green) / 172);
        const density = clamp((amount - 0.075) * 1.7, 0, 1);
        const fade = clamp(Math.min(x, y, image.width - 1 - x, image.height - 1 - y) / 7, 0, 1);
        const highlight = 0.72 + 0.37 * Math.sqrt(density);
        data[i] = color[0] * highlight;
        data[i + 1] = color[1] * highlight;
        data[i + 2] = color[2] * highlight;
        data[i + 3] = Math.round(255 * clamp(density ** 0.72, 0, 1) * fade);
      }
    ctx.putImageData(pixels, 0, 0);
    result[id] = image;
  }
  return result;
}

export class BathyalChart {
  private readonly g: Brush;
  private readonly observer: ResizeObserver;
  private visibilityObserver: IntersectionObserver | null = null;
  private readonly abort = new AbortController();
  private readonly motionQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
  private state: ChartState = {
    current: 'buoy',
    selected: 'medusa',
    reachable: ['medusa', 'vent'],
    routes: [
      ['buoy', 'medusa'],
      ['buoy', 'vent'],
    ],
    labels: {},
  };
  private readonly illustrations = new Map<StationId, HTMLCanvasElement>();
  private readonly snow: { x: number; y: number; size: number; speed: number; phase: number }[] = [];
  private readonly labels = new Map<StationId, LabelSize>();
  private engravings: Engravings = {};
  private bg: HTMLCanvasElement | null = null;
  private width = 0;
  private height = 0;
  private ratio = 1;
  private unit = 1;
  private positions = {} as Record<StationId, Point>;
  private move: Movement | null = null;
  private burst: Burst | null = null;
  private hover: StationId | null = null;
  private pointerStart: Point | null = null;
  private raf = 0;
  private lastFrame = -Infinity;
  private shown = true;
  private initialized = false;
  private disposed = false;

  constructor(
    private readonly canvas: HTMLCanvasElement,
    private readonly select: (id: StationId) => void
  ) {
    this.g = canvas.getContext('2d', { alpha: false })!;
    const signal = this.abort.signal;
    const rand = randomSource(3944);
    for (let i = 0; i < 128; i++)
      this.snow.push({
        x: rand(),
        y: rand(),
        size: rand() * 0.8 + 0.2,
        speed: rand() * 0.6 + 0.4,
        phase: rand() * TAU,
      });
    this.observer = new ResizeObserver(() => this.resize());
    this.observer.observe(canvas);
    this.canvas.style.contentVisibility = 'auto';
    // The canvas is explicitly sized by its frame, and supplies its intrinsic
    // placeholder only while the rendering subtree is skipped.
    this.canvas.style.containIntrinsicSize = 'auto 300px auto 240px';
    if ('oncontentvisibilityautostatechange' in canvas) {
      canvas.addEventListener(
        'contentvisibilityautostatechange',
        (event) => {
          this.shown = !(event as Event & { skipped: boolean }).skipped;
          this.wake();
        },
        { signal }
      );
    } else if (typeof IntersectionObserver !== 'undefined') {
      this.visibilityObserver = new IntersectionObserver(([entry]) => {
        this.shown = entry.isIntersecting;
        this.wake();
      });
      this.visibilityObserver.observe(canvas);
    }
    document.addEventListener('visibilitychange', () => this.wake(), { signal });
    this.motionQuery.addEventListener('change', () => this.wake(), { signal });
    canvas.addEventListener(
      'pointerdown',
      (event) => {
        this.pointerStart = { x: event.clientX, y: event.clientY };
      },
      { signal }
    );
    canvas.addEventListener(
      'pointercancel',
      () => {
        this.pointerStart = null;
      },
      { signal }
    );
    canvas.addEventListener(
      'pointerup',
      (event) => {
        const start = this.pointerStart;
        this.pointerStart = null;
        if (!start || Math.hypot(start.x - event.clientX, start.y - event.clientY) > 12 || event.button !== 0)
          return;
        const id = this.hit(event);
        if (id) this.select(id);
      },
      { signal }
    );
    canvas.addEventListener(
      'pointermove',
      (event) => {
        if (event.pointerType === 'touch') return;
        const hit = this.hit(event);
        if (hit === this.hover) return;
        this.hover = hit;
        canvas.style.cursor = hit ? 'pointer' : 'default';
        this.wake();
      },
      { signal }
    );
    canvas.addEventListener(
      'pointerleave',
      () => {
        this.hover = null;
        canvas.style.cursor = 'default';
        this.wake();
      },
      { signal }
    );
    this.resize();
    void inkPlates()
      .then((art) => {
        if (this.disposed) return;
        this.engravings = art;
        this.prepareIllustrations();
        this.wake();
      })
      .catch(() => {
        /* The hand-drawn vector plates also work in image-restricted frames. */
      });
  }

  update(state: ChartState) {
    const changed = this.initialized && state.current !== this.state.current;
    if (changed) {
      this.move = { from: this.state.current, to: state.current, start: performance.now() };
      this.burst = null;
    }
    this.state = state;
    this.initialized = true;
    this.wake();
  }

  pulse(kind: ChartPulse) {
    const now = performance.now();
    const approach = this.move && !this.reduced ? this.move.start + 720 : now;
    this.burst = { kind, start: Math.max(now, approach), at: this.state.current };
    this.wake();
  }

  dispose() {
    this.disposed = true;
    cancelAnimationFrame(this.raf);
    this.abort.abort();
    this.observer.disconnect();
    this.visibilityObserver?.disconnect();
    this.illustrations.clear();
    this.bg = null;
  }

  private get reduced() {
    return this.state.reducedMotion || this.motionQuery.matches;
  }

  private resize() {
    if (this.disposed) return;
    const box = this.canvas.getBoundingClientRect();
    const w = Math.round(box.width),
      h = Math.round(box.height);
    const ratio = clamp(window.devicePixelRatio || 1, 1, 2);
    if (w === this.width && h === this.height && ratio === this.ratio) return;
    this.width = w;
    this.height = h;
    this.ratio = ratio;
    if (w < 1 || h < 1) return;
    this.canvas.width = Math.round(w * ratio);
    this.canvas.height = Math.round(h * ratio);
    const mobile = w / h < 1.25;
    const compactWidth = mobile ? 475 : 840,
      compactHeight = mobile ? 490 : 400;
    this.unit = clamp(Math.min(w / compactWidth, h / compactHeight) * 1.18, 0.4, 2);
    for (const p of specimens) {
      this.positions[p.id] = { x: (mobile ? p.mobileX : p.x) * w, y: (mobile ? p.mobileY : p.y) * h };
    }
    // The host-facing location button sits above the northwest corner of the plate.
    // Leave its entire footprint clear even when the shortest chart keeps a wide layout.
    this.positions.buoy.y = Math.max(this.positions.buoy.y, 41 + 55 * this.unit);
    this.bg = makeLayer(w, h, ratio, (g) => {
      makeSeabed(g, w, h);
      gridAndSea(g, w, h);
    });
    this.prepareIllustrations();
    this.wake();
  }

  private prepareIllustrations() {
    const scale = clamp(Math.max(this.unit, 1) * this.ratio, 1.5, 3.3);
    for (const animal of specimens) {
      const drawing = this.engravings[animal.id];
      const sprite = makeLayer(188, 130, scale, (g) => {
        g.translate(94, 83);
        if (!drawing) {
          animal.draw(g);
          return;
        }
        switch (animal.id) {
          case 'whale':
            g.translate(0, -5);
            g.rotate(0.53);
            g.drawImage(drawing, -67, -67, 134, 134);
            break;
          case 'medusa':
            glow(g, 0, -17, 43, '#81d6c03e');
            g.drawImage(drawing, -36, -47, 72, 79);
            break;
          case 'garden':
            g.drawImage(drawing, -38, -49, 76, 71);
            break;
          case 'trench':
            g.drawImage(drawing, -43, -40, 86, 77);
            break;
        }
      });
      this.illustrations.set(animal.id, sprite);
    }
  }

  private wake() {
    if (this.disposed) return;
    if (this.raf) cancelAnimationFrame(this.raf);
    this.raf = 0;
    if (!this.shown || document.hidden || !this.bg || !this.width || !this.height) return;
    this.lastFrame = -Infinity;
    this.raf = requestAnimationFrame(this.frame);
  }

  private frame = (now: number) => {
    this.raf = 0;
    if (this.disposed || !this.shown || document.hidden || !this.bg) return;
    if (now - this.lastFrame >= 1000 / 30 - 0.8) {
      this.draw(now);
      this.lastFrame = now;
    }
    if (!this.reduced || this.move || this.burst) this.raf = requestAnimationFrame(this.frame);
  };

  private hit(event: PointerEvent) {
    if (!this.bg) return null;
    const rect = this.canvas.getBoundingClientRect(),
      x = event.clientX - rect.left,
      y = event.clientY - rect.top;
    let best: StationId | null = null,
      bestCost = Infinity;
    for (const animal of specimens) {
      const p = this.positions[animal.id],
        label = this.labels.get(animal.id);
      if (
        label &&
        x >= label.x - 4 &&
        x <= label.x + label.width + 4 &&
        y >= label.y &&
        y <= label.y + label.height + 4
      )
        return animal.id;
      const offset = this.spriteOffset(animal.id);
      const dist = Math.hypot(x - p.x, y - p.y);
      const artDist = Math.hypot(
        (x - p.x - offset.x * this.unit) / Math.max(20, animal.extent * this.unit),
        (y - p.y - offset.y * this.unit) / Math.max(23, 30 * this.unit)
      );
      const cost = Math.min(dist / Math.max(24, 16 * this.unit), artDist);
      if (cost < 1 && cost < bestCost) {
        best = animal.id;
        bestCost = cost;
      }
    }
    return best;
  }

  private spriteOffset(id: StationId): Point {
    switch (id) {
      case 'buoy':
        return { x: -17, y: -3 };
      case 'medusa':
        return { x: 8, y: -43 };
      case 'whale':
        return { x: -1, y: -38 };
      case 'garden':
        return { x: 1, y: -32 };
      case 'trench':
        return { x: 0, y: -37 };
      case 'vent':
        return { x: -3, y: -12 };
      case 'wreck':
        return { x: 0, y: -15 };
    }
  }

  private draw(now: number) {
    const g = this.g,
      w = this.width,
      h = this.height,
      u = this.unit,
      s = this.state;
    const t = this.reduced ? 0 : now * 0.001;
    g.setTransform(this.canvas.width / w, 0, 0, this.canvas.height / h, 0, 0);
    g.clearRect(0, 0, w, h);
    g.save();
    const since = this.burst ? (now - this.burst.start) / 1000 : 5;
    if (this.burst?.kind === 'danger' && since >= 0 && since < 0.4 && !this.reduced) {
      g.translate(
        Math.sin(since * 67) * 2.8 * (1 - since / 0.4),
        Math.sin(since * 48) * 1.8 * (1 - since / 0.4)
      );
    }
    g.drawImage(this.bg!, 0, 0, w, h);
    this.drawWater(g, t);
    if (s.hunted) this.drawListener(g, this.positions[s.hunted], t);
    const direct = s.selected && s.reachable.includes(s.selected) ? [s.selected] : [];
    const stops = [s.current, ...(s.course ?? direct)];
    const plotted = stops.slice(1).map((to, i) => ({ from: stops[i], to }));
    for (const [a, b] of s.routes) {
      const next = a === s.current || b === s.current;
      if (plotted.some(({ from, to }) => (from === a && to === b) || (from === b && to === a))) continue;
      const route = curve(this.positions[a], this.positions[b]);
      g.setLineDash(next ? [5, 4] : [2.4, 4.1]);
      trace(g, route);
      g.strokeStyle = next ? '#d1d9bcca' : '#a9c7bc9c';
      g.lineWidth = next ? 1.65 : 1.15;
      g.stroke();
    }
    g.setLineDash([]);
    for (const [i, leg] of plotted.entries()) {
      const route = curve(this.positions[leg.from], this.positions[leg.to]);
      this.drawCourse(g, route, t, i === 0);
    }
    for (const [index, animal] of specimens.entries()) {
      const p = this.positions[animal.id],
        offset = this.spriteOffset(animal.id),
        sprite = this.illustrations.get(animal.id);
      if (!sprite) continue;
      const living = ['whale', 'medusa', 'trench'].includes(animal.id);
      const bob = living ? Math.sin(t * 0.58 + index) * 1.6 * u : 0;
      g.save();
      g.translate(p.x + offset.x * u, p.y + offset.y * u + bob);
      if (living && !this.reduced) g.rotate(Math.sin(t * 0.41 + index) * 0.012);
      if (animal.id === 'medusa' && !this.reduced) {
        const pulse = Math.sin(t * 1.3);
        g.scale(1 + 0.026 * pulse, 1 - 0.019 * pulse);
      }
      g.globalAlpha =
        animal.id === s.selected || s.reachable.includes(animal.id) || s.letters?.includes(animal.id)
          ? 1
          : 0.83;
      g.drawImage(sprite, -94 * u, -83 * u, 188 * u, 130 * u);
      g.restore();
    }
    let bellPt = this.positions[s.current];
    let bearing = 0,
      travel = 0;
    if (this.move) {
      const elapsed = now - this.move.start;
      const impactPause = this.burst?.kind === 'danger' ? clamp(elapsed - 720, 0, 95) : 0;
      const phase = this.reduced ? 1 : clamp((elapsed - impactPause) / 915, 0, 1);
      const route = curve(this.positions[this.move.from], this.positions[this.move.to]);
      const k = phase * phase * (3 - 2 * phase);
      bellPt = along(route, k);
      travel = Math.sin(Math.PI * k);
      bearing = route.b.x - route.a.x > 0 ? 1 : -1;
      if (phase >= 1) this.move = null;
    }
    for (const animal of specimens) this.drawStation(g, animal.id, t);
    if (s.danger) {
      const rippling = this.reduced ? 0.5 : (t * 0.55) % 1;
      const r = (19 + rippling * 24) * u;
      g.beginPath();
      g.ellipse(bellPt.x, bellPt.y, r, r * 0.63, 0, Math.PI * 0.14, Math.PI * 0.87);
      g.strokeStyle = `rgba(252,152,111,${0.63 * (1 - rippling)})`;
      g.lineWidth = 1.4;
      g.stroke();
    }
    this.drawBellAt(g, bellPt, bearing, travel, t);
    if (this.burst) {
      if (since >= 0) this.drawBurst(g, this.positions[this.burst.at], this.burst.kind, since);
      if (since >= 1.5) this.burst = null;
    }
    g.restore();
  }

  private drawListener(g: Brush, station: Point, t: number) {
    const u = clamp(this.unit, 0.65, 1.55);
    const facing = station.x < this.width * 0.5 ? 1 : -1;
    // Its body remains outside the sounding. A crescent eye and concentric
    // wakes travel with the hunted mooring when the watch changes.
    g.save();
    g.translate(station.x + facing * 27 * u, station.y + 5 * u);
    g.scale(u * facing, u);
    for (let i = 0; i < 3; i++) {
      const drift = this.reduced ? 0.5 : (t * 0.36 + i / 3) % 1;
      const radius = 9 + drift * 14;
      g.beginPath();
      g.arc(0, 0, radius, -0.79, 0.79);
      g.strokeStyle = `rgba(236,153,122,${0.57 * (1 - drift)})`;
      g.lineWidth = 0.9;
      g.stroke();
    }
    path(g, 'M-6 0 Q-1 -5 6 0 Q0 5 -6 0Z', '#173139', '#e79c7b', 1);
    ellipse(g, 0, 0, 1.3, 2.1, '#f2b588');
    g.restore();
  }

  private drawCourse(g: Brush, route: RouteArc, t: number, nextLeg: boolean) {
    const u = this.unit;
    trace(g, route);
    g.strokeStyle = '#152a2ad9';
    g.lineWidth = 4.4;
    g.stroke();
    trace(g, route);
    g.strokeStyle = nextLeg ? '#f4a077' : '#eba784a8';
    g.lineWidth = nextLeg ? 1.7 : 1.3;
    g.setLineDash(nextLeg ? [5, 4] : [2.3, 5]);
    g.lineDashOffset = -t * 6;
    g.stroke();
    g.lineDashOffset = 0;
    g.setLineDash([]);
    const a = along(route, 0.55),
      b = along(route, 0.56),
      angle = Math.atan2(b.y - a.y, b.x - a.x);
    g.save();
    g.translate(a.x, a.y);
    g.rotate(angle);
    const r = clamp(u * 4, 3, 6);
    path(g, `M${-r} ${-r} L${r * 1.3} 0 L${-r} ${r} L${-r * 0.48} 0Z`, vermilion, ink, 0.9);
    g.restore();
  }

  private drawWater(g: Brush, t: number) {
    const w = this.width,
      h = this.height;
    const count = Math.min(this.snow.length, Math.round((w * h) / 3300));
    for (let i = 0; i < count; i++) {
      const p = this.snow[i];
      const x = (p.x * w + Math.sin(t * 0.2 + p.phase) * 4 + t * 0.85 * p.speed) % w;
      const y = (p.y * h + t * 1.55 * p.speed) % h;
      const alpha = 0.25 + 0.34 * (0.5 + 0.5 * Math.sin(t * 0.8 + p.phase));
      g.fillStyle = `rgba(195,215,186,${alpha})`;
      g.beginPath();
      g.arc(x, y, Math.max(0.33, p.size * this.unit * 0.76), 0, TAU);
      g.fill();
    }
    const u = this.unit;
    if (w >= 500 && h >= 280) {
      // Three glass squid hold station in the middle water. Their mantles contract
      // in sequence and their trailing arms drift a little behind each jet.
      for (const [i, specimen] of [
        [0.645, 0.45, 0.85],
        [0.679, 0.442, 0.64],
        [0.674, 0.479, 0.5],
      ].entries()) {
        const phase = t * 1.05 + i * 1.9;
        g.save();
        g.translate(
          w * specimen[0] + (Math.sin(t * 0.19) * 7 + Math.sin(phase) * 1.5) * u,
          h * specimen[1] + Math.sin(t * 0.46 + i) * 2.5 * u
        );
        const scale = specimen[2] * u;
        g.scale(scale, scale);
        g.rotate(-0.2 + Math.sin(t * 0.36 + i) * 0.06);
        path(
          g,
          'M-5 -1 Q-8 -5 -3 -4 Q6 -7 13 -4 Q15 -3 17 -1 Q14 1 10 2 Q4 5 -4 3 Q-7 3 -5 -1Z',
          '#739a91a3',
          '#b6cbb594',
          0.82
        );
        path(g, 'M10 -4 Q12 -8 15 -7 L17 -1 Q21 1 19 3 Q15 4 10 2', '#84a69a6e', '#a9c8b78c', 0.63);
        path(g, 'M-1 -2 Q6 -5 12 -3 M0 1 Q6 2 11 0', null, '#d1d4b993', 0.57);
        ellipse(g, -6, 0.1, 2.4, 2.25, '#769c8f', '#b0c9b6', 0.62);
        ellipse(g, -6.8, -0.2, 0.9, 0.95, '#25444d', '#b1c4ad', 0.45);
        for (let arm = 0; arm < 4; arm++) {
          const wave = Math.sin(phase + arm * 0.35) * 2;
          path(
            g,
            `M-7 1 Q-11 ${arm - 2} -14 ${arm - 3 + wave} T${-20 - arm * 1.4} ${arm - 3 - wave}`,
            null,
            '#a5c5b4a8',
            0.61
          );
        }
        g.restore();
      }
    }
    const shoals = [
      { x: 0.68, y: 0.42, n: w >= 500 ? 0 : 5 },
      { x: 0.33, y: 0.49, n: 5 },
      { x: 0.86, y: 0.64, n: 5 },
    ];
    for (const [s, school] of shoals.entries()) {
      for (let i = 0; i < school.n; i++) {
        const drift = Math.sin(t * 0.14 + s) * 12,
          x = w * school.x + (i % 4) * 5.6 * u + drift * u;
        const y = h * school.y + (((i * 13) % 10) - 4 + Math.sin(t * 0.65 + i * 0.8) * 1.2) * u;
        g.save();
        g.translate(x, y);
        g.scale(u * (s % 2 ? -1 : 1), u);
        path(g, 'M-2.6 0 Q-.4 -1.8 2.3 -.25 Q2.9 .8 -.1 1 L-2.7 .3 L-4 1.35 L-4 -1.1Z', '#afc4aa8c');
        g.restore();
      }
    }
  }

  private drawStation(g: Brush, id: StationId, t: number) {
    const p = this.positions[id],
      s = this.state;
    const sel = s.selected === id,
      here = s.current === id,
      reachable = s.reachable.includes(id);
    const letter = s.letters?.includes(id),
      visited = s.visited?.includes(id);
    const signal = sel ? vermilion : here ? brass : reachable ? '#d0debe' : '#a8c7b8';
    const u = clamp(this.unit, 0.72, 1.55),
      r = (sel ? 9 : here ? 7 : 5.7) * u;
    if (sel || this.hover === id) {
      const pulse = this.reduced ? 0.7 : (Math.sin(t * 2.6) + 1) * 0.5;
      ellipse(
        g,
        p.x,
        p.y,
        r + 3.5 + pulse * 2,
        r + 3.5 + pulse * 2,
        null,
        sel ? '#f49b727a' : '#cfddc38e',
        0.85
      );
      if (sel) {
        for (let i = 0; i < 4; i++) {
          const a = Math.PI * 0.5 * i;
          line(
            g,
            [
              p.x + Math.cos(a) * (r + 3),
              p.y + Math.sin(a) * (r + 3),
              p.x + Math.cos(a) * (r + 7.2),
              p.y + Math.sin(a) * (r + 7.2),
            ],
            signal,
            1.12
          );
        }
      }
    }
    ellipse(g, p.x, p.y, r, r, ink, signal, sel ? 1.7 : 1.15);
    if (letter) {
      const ew = (sel ? 4.6 : 3.45) * u,
        eh = ew * 0.68;
      g.fillStyle = signal;
      g.fillRect(p.x - ew, p.y - eh, ew * 2, eh * 2);
      line(g, [p.x - ew, p.y - eh, p.x, p.y + 0.7 * u, p.x + ew, p.y - eh], ink, 0.8 * u);
    } else if (visited || here) {
      ellipse(g, p.x, p.y, Math.max(1.6, r * 0.39), Math.max(1.6, r * 0.39), signal);
    } else {
      const rr = r * 0.4;
      path(g, `M${p.x} ${p.y - rr} l${rr} ${rr} l${-rr} ${rr} l${-rr} ${-rr}Z`, signal);
    }

    const compact = this.width < 510 || this.height < 310;
    const size = clamp(
      Math.min(this.width / (compact ? 29 : 54), this.height / 25),
      compact ? 10.7 : 12.3,
      18
    );
    g.font = `${sel ? 'bold ' : ''}${size}px Georgia, "Times New Roman", serif`;
    g.textBaseline = 'alphabetic';
    g.textAlign = 'center';
    const name = s.labels[id] || neutralLabels[id],
      tw = g.measureText(name).width;
    const textX = clamp(p.x, tw * 0.5 + 5, this.width - tw * 0.5 - 5);
    const top = p.y + r + 4;
    const textY = top + size;
    g.lineJoin = 'round';
    g.lineWidth = 4.2;
    g.strokeStyle = '#0b2631eb';
    g.strokeText(name, textX, textY);
    g.fillStyle = sel ? '#ffd2ad' : here ? ivory : '#dbdfc8';
    g.fillText(name, textX, textY);
    let hitHeight = size + 3;
    const depth = s.depths?.[id];
    if (this.width >= 480 && this.height >= 315 && typeof depth === 'number') {
      const fontSize = clamp(size * 0.61, 8.3, 10.2);
      g.font = `${fontSize}px ui-monospace, Menlo, monospace`;
      const depthLabel = depth.toLocaleString('en-US') + ' m';
      g.lineWidth = 3;
      g.strokeText(depthLabel, textX, textY + fontSize + 3);
      g.fillStyle = sel ? '#ebba97' : '#a8c3b5';
      g.fillText(depthLabel, textX, textY + fontSize + 3);
      hitHeight += fontSize + 3;
    }
    this.labels.set(id, { x: textX - tw * 0.5, y: top, width: tw, height: hitHeight });
  }

  private drawBellAt(g: Brush, p: Point, bearing: number, travel: number, t: number) {
    const u = clamp(this.unit, 0.59, 1.7);
    const bob = this.reduced ? 0 : Math.sin(t * 1.25) * 1.2;
    const x = p.x + u * 16 * (1 - travel),
      y = p.y - u * (15 + travel * 4) + bob * u;
    g.save();
    g.translate(x, y);
    if (travel > 0.05) {
      g.strokeStyle = '#cdd8b689';
      g.lineWidth = 0.7;
      for (let i = 0; i < 9; i++) {
        const f = (t * 1.09 + i * 0.111) % 1,
          xx = -bearing * (14 + f * 27) * u,
          yy = (-3 - Math.sin(Math.PI * f) * 4 - (i % 3) * 2) * u;
        ellipse(
          g,
          xx,
          yy,
          (0.8 + (1 - f) * 0.6) * u,
          (0.8 + (1 - f) * 0.6) * u,
          null,
          `rgba(194,218,190,${0.65 * (1 - f)})`,
          0.65
        );
      }
    }
    g.rotate(travel * bearing * 0.11 + (this.reduced ? 0 : Math.sin(t * 0.51) * 0.025));
    g.scale(u * (bearing < 0 ? -1 : 1), u);
    path(g, 'M0 -17 C-1 -22 -8 -23 -9 -29 Q-10 -32 -8 -35', null, '#c9c4a47a', 0.9);
    drawBell(g);
    g.restore();
  }

  private drawBurst(g: Brush, p: Point, kind: ChartPulse, seconds: number) {
    const n = clamp(seconds / 1.5, 0, 1),
      ease = 1 - (1 - n) ** 2;
    const tint = kind === 'danger' ? '255,124,93' : kind === 'delivery' ? '255,202,125' : '168,224,193';
    g.save();
    const u = clamp(this.unit, 0.7, 1.7);
    if (!this.reduced) {
      if (kind === 'delivery') {
        // A sealed reply flutters upward into its recipient's engraving.
        g.save();
        g.translate(p.x + Math.sin(n * Math.PI) * 9 * u, p.y - (6 + ease * 42) * u);
        g.rotate(Math.sin(n * Math.PI * 2) * 0.24);
        g.scale(u * (1 - n * 0.4), u * (1 - n * 0.4));
        g.globalAlpha = Math.min(1, (1 - n) * 2.5);
        path(g, 'M-9 -6 H9 V6 H-9 Z', '#efe1b9', '#8c765c', 0.95);
        path(g, 'M-9 -6 L0 1 L9 -6 M-9 6 L-2 -.2 M9 6 L2 -.2', null, '#746d59', 0.8);
        ellipse(g, 0, 0.8, 1.7, 1.7, '#ba6548');
        g.restore();
      }
      for (let j = 0; j < 2; j++) {
        const r = (14 + ease * (j === 0 ? 46 : 31)) * u;
        ellipse(g, p.x, p.y, r, r, null, `rgba(${tint},${(1 - n) * 0.57})`, j === 0 ? 1.5 : 0.7);
      }
      const rand = randomSource(kind === 'danger' ? 165 : 741);
      for (let j = 0; j < 20; j++) {
        const a = rand() * TAU,
          dist = (12 + (16 + rand() * 27) * ease) * u;
        const x = p.x + Math.cos(a) * dist,
          y = p.y + Math.sin(a) * dist - n * 6;
        line(
          g,
          [x, y, x + Math.cos(a) * (2 + 3 * (1 - n)), y + Math.sin(a) * (2 + 3 * (1 - n))],
          `rgba(${tint},${(1 - n) * 0.86})`,
          1
        );
      }
    } else {
      ellipse(g, p.x, p.y, 15 * u, 15 * u, null, `rgba(${tint},${(1 - n) * 0.8})`, 2);
    }
    g.restore();
  }
}