Skip to content
Charts55Components12Visuals14ASCII45
GitHubGet startedGet started
All ASCIIKoi pondWater
PreviousNext: Jellyfish

Hold still and they drift over; move fast and they scatter. Click to feed them.

Koi pond

Water

Koi gliding under lily pads, on water that really ripples.

Customize 6

4
3
1.00
14px
1.00
Install & copy sourceInstall & copy sourceSee propsSee props7

Live code

As tuned above.

Every control in the inspector updates this snippet directly. Defaults are omitted to keep your markup minimal.

hero.tsx

import { AsciiKoi } from '@/components/lilt/ascii/scenes/ascii-koi';

export function Hero() {
  return (
    <section style={{ height: 560 }}>
      <AsciiKoi />
    </section>
  );
}

Installation8

Source you own.

This is source, not a package: the shadcn CLI copies it into your project with the shared pieces it needs. Its only dependency is React.

$npx shadcn@latest add https://liltui.vercel.app/r/koi.json
components/lilt/ascii/scenes/ascii-koi.tsx

ascii-koi.tsx

'use client';

import { AsciiCanvas, useSceneProps, type SceneProps } from '../react/ascii-canvas';
import { createKoi, type KoiOptions } from './koi';

/** A koi pond from above: patterned koi under lily pads, rippling water, food on click. */
export function AsciiKoi(props: SceneProps<KoiOptions>) {
  return <AsciiCanvas {...useSceneProps(props, createKoi)} />;
}
components/lilt/ascii/scenes/koi.ts

koi.ts

import { ramp, stroke } from '../engine/glyphs';
import { approach, clamp, hash3, noise3, smoothstep } from '../engine/noise';
import { DOT, type GlyphSurface } from '../engine/surface';
import type { AsciiGrid, AsciiPointer, AsciiScene } from '../engine/types';

export interface KoiOptions {
  /** How many koi. Default 4. */
  count?: number;
  /** How many lily pads float on the pond. Default 3. */
  pads?: number;
  /** Size of the koi, relative to the pond. Default 1. */
  size?: number;
}

const WHITE = 0;
const RED = 1;
const BLACK = 2;
const GOLD = 3;
const SLATE = 4;
const WATER = 5;
const LEAF = 6;
const LEAF_DARK = 7;
const FOOD = 8;
/** The dark of deep water, for glyphs cut into solid blocks. */
const DEEP = 9;

/** Koi varieties, as their base colour and how their patches fall. */
type Variety = 'kohaku' | 'showa' | 'yamabuki' | 'asagi';
const VARIETIES: Variety[] = ['kohaku', 'showa', 'yamabuki', 'kohaku', 'asagi'];

const NODES = 16;
// Glyphs cut into the scales: sparse where the light catches them, dense in shadow.
const SCALES = '.:-=+*#';
const EDGE = '.:';
/** Light falls from the upper left and above: x, y (down) and z (toward the viewer). */
const LIGHT = [-0.45, -0.55, 0.7].map((v, _, a) => v / Math.hypot(...a));

interface Koi {
  nodes: Float32Array;
  length: number;
  heading: number;
  speed: number;
  phase: number;
  wander: number;
  variety: Variety;
  seed: number;
  /** A burst of speed after eating or a fright, easing away. */
  dash: number;
}

interface Pad {
  x: number;
  y: number;
  r: number;
  notch: number;
  spin: number;
  seed: number;
}

interface Pellet {
  x: number;
  y: number;
  age: number;
}

/**
 * How much of a cell a shape covers, from its signed distance in square units. Cells are about
 * twice as tall as wide, so the soft band is a little over a cell: edges step down through lighter
 * glyphs instead of ending in a hard staircase.
 */
const coverage = (d: number) => clamp(0.5 - d / 1.3, 0, 1);

/**
 * A koi pond seen from above. Each koi is a jointed body that bends as it swims: a blunt head,
 * deep shoulders, a narrow stem and a forked tail of fine rays, patterned as its own fish. The
 * water is a wave simulation, so wakes, splashes and the pointer all ripple it. Koi drift up to a
 * still pointer, as they do at the edge of a pond, and scatter from a quick one. A click scatters
 * food, and they come to eat it.
 */
export function createKoi(options: KoiOptions = {}): AsciiScene {
  const count = clamp(Math.round(options.count ?? 4), 1, 24);
  const padCount = clamp(Math.round(options.pads ?? 3), 0, 12);
  const sizeScale = options.size ?? 1;
  let grid: AsciiGrid = { cols: 0, rows: 0, aspect: 2 };
  let width = 0;
  let height = 0;
  let wave = new Float32Array(0);
  let last = new Float32Array(0);
  let cover = new Uint8Array(0);
  /** Cells under a lily pad this frame: koi swim beneath them. */
  let padMask = new Uint8Array(0);
  const fish: Koi[] = [];
  const pads: Pad[] = [];
  const food: Pellet[] = [];
  let time = 0;
  let px = 0;
  let py = 0;
  let pointerSpeed = 0;
  let pointerActive = false;
  // Spine with the swimming wave applied, reused each frame.
  const spine = new Float32Array(NODES * 2);

  const cellOf = (x: number, y: number) => {
    const col = Math.floor(x);
    const row = Math.floor(y / grid.aspect);
    if (col < 1 || row < 1 || col >= grid.cols - 1 || row >= grid.rows - 1) return -1;
    return row * grid.cols + col;
  };

  /** Pushes the water down at a point: a ripple starts there. */
  function disturb(x: number, y: number, amount: number) {
    const i = cellOf(x, y);
    if (i >= 0) wave[i] = wave[i]! - amount;
  }

  function populate() {
    fish.length = 0;
    pads.length = 0;
    food.length = 0;
    const base = Math.min(width, height) * 0.5 * sizeScale;
    for (let k = 0; k < count; k++) {
      const length = base * (0.8 + 0.4 * hash3(k, 1, 9));
      const heading = Math.random() * Math.PI * 2;
      const x = width * (0.15 + 0.7 * Math.random());
      const y = height * (0.15 + 0.7 * Math.random());
      const nodes = new Float32Array(NODES * 2);
      for (let i = 0; i < NODES; i++) {
        nodes[i * 2] = x - Math.cos(heading) * (length / (NODES - 1)) * i;
        nodes[i * 2 + 1] = y - Math.sin(heading) * (length / (NODES - 1)) * i;
      }
      fish.push({
        nodes,
        length,
        heading,
        speed: 4,
        phase: Math.random() * 10,
        wander: heading,
        variety: VARIETIES[k % VARIETIES.length]!,
        seed: k * 7.31 + 3,
        dash: 0,
      });
    }
    for (let k = 0; k < padCount; k++) {
      // Of a handful of spots, the one furthest from the pads already floating.
      let x = 0;
      let y = 0;
      let room = -1;
      for (let t = 0; t < 12; t++) {
        const cx = width * (0.1 + 0.8 * hash3(k, t, 4));
        const cy = height * (0.1 + 0.8 * hash3(k, t, 5));
        let near = Infinity;
        for (const pad of pads) near = Math.min(near, Math.hypot(pad.x - cx, pad.y - cy));
        if (near > room) {
          room = near;
          x = cx;
          y = cy;
        }
      }
      pads.push({
        x,
        y,
        r: Math.min(width, height) * (0.075 + 0.035 * hash3(k, 6, 1)),
        notch: hash3(k, 7, 1) * Math.PI * 2,
        spin: (hash3(k, 8, 1) - 0.5) * 0.04,
        seed: k,
      });
    }
  }

  function steer(koi: Koi, dt: number) {
    const hx = koi.nodes[0]!;
    const hy = koi.nodes[1]!;
    koi.wander += (noise3(koi.seed, time * 0.25, 1) - 0.5) * 2.4 * dt;
    let dx = Math.cos(koi.wander);
    let dy = Math.sin(koi.wander);
    let cruise = 4.5;

    // Keep to the pond, turning well before the edge.
    const margin = koi.length * 0.7;
    if (hx < margin) dx += ((margin - hx) / margin) * 2.5;
    if (hx > width - margin) dx -= ((hx - width + margin) / margin) * 2.5;
    if (hy < margin) dy += ((margin - hy) / margin) * 2.5;
    if (hy > height - margin) dy -= ((hy - height + margin) / margin) * 2.5;

    // Give each other room: steer clear of every part of another koi's body, not only its middle,
    // so they pass alongside rather than through one another.
    for (const other of fish) {
      if (other === koi) continue;
      const room = koi.length * 0.12 + other.length * 0.2;
      for (let i = 0; i < NODES; i += 3) {
        const ox = hx - other.nodes[i * 2]!;
        const oy = hy - other.nodes[i * 2 + 1]!;
        const d = Math.hypot(ox, oy);
        if (d < room && d > 1e-3) {
          dx += (ox / d) * (1 - d / room) * 3;
          dy += (oy / d) * (1 - d / room) * 3;
        }
      }
    }

    // Food draws them in; the nearest pellet wins.
    let best: Pellet | null = null;
    let bestD = Math.min(width, height) * 0.8;
    for (const pellet of food) {
      const d = Math.hypot(pellet.x - hx, pellet.y - hy);
      if (d < bestD) {
        bestD = d;
        best = pellet;
      }
    }
    if (best) {
      dx += ((best.x - hx) / (bestD + 1e-3)) * 3;
      dy += ((best.y - hy) / (bestD + 1e-3)) * 3;
      cruise = 8;
      if (bestD < koi.length * 0.08 + 1) {
        food.splice(food.indexOf(best), 1);
        disturb(best.x, best.y, 2.2);
        koi.dash = 1;
      }
    } else if (pointerActive) {
      const ox = px - hx;
      const oy = py - hy;
      const d = Math.hypot(ox, oy);
      if (pointerSpeed > 40 && d < koi.length * 0.9) {
        // A quick hand over the water: dart away.
        dx -= (ox / d) * 4;
        dy -= (oy / d) * 4;
        koi.dash = 1;
      } else if (pointerSpeed < 8 && d < Math.min(width, height) * 0.6 && d > koi.length * 0.25) {
        // A still hand at the edge of the pond: drift up and wait.
        dx += (ox / d) * 1.2;
        dy += (oy / d) * 1.2;
        cruise = 3;
      }
    }

    const want = Math.atan2(dy, dx);
    let turn = want - koi.heading;
    turn = Math.atan2(Math.sin(turn), Math.cos(turn));
    const maxTurn = (1.3 + koi.dash * 2.2) * dt;
    koi.heading += clamp(turn, -maxTurn, maxTurn);
    koi.wander = approach(koi.wander, koi.heading, 0.6, dt);
    koi.dash = approach(koi.dash, 0, 1.4, dt);
    koi.speed = approach(koi.speed, cruise + koi.dash * 10, 2, dt);
  }

  function swim(koi: Koi, dt: number) {
    const { nodes } = koi;
    nodes[0] = nodes[0]! + Math.cos(koi.heading) * koi.speed * dt;
    nodes[1] = nodes[1]! + Math.sin(koi.heading) * koi.speed * dt;
    const seg = koi.length / (NODES - 1);
    for (let i = 1; i < NODES; i++) {
      const dx = nodes[i * 2]! - nodes[(i - 1) * 2]!;
      const dy = nodes[i * 2 + 1]! - nodes[(i - 1) * 2 + 1]!;
      const d = Math.hypot(dx, dy) || 1;
      nodes[i * 2] = nodes[(i - 1) * 2]! + (dx / d) * seg;
      nodes[i * 2 + 1] = nodes[(i - 1) * 2 + 1]! + (dy / d) * seg;
    }
    koi.phase += dt * (2 + koi.speed * 0.45);
    // The tail sweeps the water as it beats.
    const tail = (NODES - 1) * 2;
    disturb(nodes[tail]!, nodes[tail + 1]!, Math.sin(koi.phase) * 0.12 * (0.4 + koi.speed / 8));
  }

  /** The spine as drawn: the swimming wave bends the back half of the body. */
  function bend(koi: Koi) {
    const { nodes, length } = koi;
    for (let i = 0; i < NODES; i++) {
      const s = i / (NODES - 1);
      const a = Math.max(0, i - 1);
      const b = Math.min(NODES - 1, i + 1);
      const tx = nodes[b * 2]! - nodes[a * 2]!;
      const ty = nodes[b * 2 + 1]! - nodes[a * 2 + 1]!;
      const tl = Math.hypot(tx, ty) || 1;
      const sway = Math.sin(koi.phase - s * 4.2) * Math.pow(s, 1.8) * length * 0.06;
      spine[i * 2] = nodes[i * 2]! - (ty / tl) * sway;
      spine[i * 2 + 1] = nodes[i * 2 + 1]! + (tx / tl) * sway;
    }
  }

  /** Half the body's width at a point along it, as a share of its length. */
  function halfWidth(s: number) {
    // A round, blunt head...
    if (s < 0.1) return 0.105 * Math.sqrt(Math.max(0, 1 - Math.pow((0.1 - s) / 0.1, 2)));
    // ...deep shoulders...
    if (s < 0.3) return 0.105 + 0.025 * smoothstep(0.1, 0.3, s);
    // ...and a long taper to a narrow stem.
    return 0.03 + 0.1 * Math.pow(1 - smoothstep(0.3, 1, s), 1.15);
  }

  function colourOf(koi: Koi, s: number, across: number): number {
    // Large, soft-edged patches, as on a real koi.
    const n1 = noise3(s * 3.2 + koi.seed, across * 0.9, koi.seed);
    const n2 = noise3(s * 4 - koi.seed, across * 1.1 + 4, koi.seed * 2);
    switch (koi.variety) {
      case 'kohaku':
        // A red cap on the head is the classic mark.
        if (s > 0.03 && s < 0.17 && Math.abs(across) < 0.75) return RED;
        return n1 > 0.5 && s > 0.22 && s < 0.85 ? RED : WHITE;
      case 'showa':
        if (n2 > 0.62) return WHITE;
        return n1 > 0.46 ? RED : BLACK;
      case 'yamabuki':
        return GOLD;
      case 'asagi':
        return Math.abs(across) > 0.7 || s < 0.08 ? RED : SLATE;
    }
  }

  /** Fins carry the body's lightest colour. */
  function finTone(koi: Koi) {
    return koi.variety === 'yamabuki' ? GOLD : koi.variety === 'asagi' ? SLATE : WHITE;
  }

  function drawKoi(surface: GlyphSurface, koi: Koi) {
    bend(koi);
    const { length } = koi;
    const { aspect, cols, rows } = grid;
    const n = NODES - 1;
    // The tail hangs off the narrow stem and swings further round than the body, like silk.
    const ex = spine[n * 2]! - spine[(n - 1) * 2]!;
    const ey = spine[n * 2 + 1]! - spine[(n - 1) * 2 + 1]!;
    const el = Math.hypot(ex, ey) || 1;
    const flick = Math.sin(koi.phase - 4.6) * 0.45;
    const tx = (ex / el) * Math.cos(flick) - (ey / el) * Math.sin(flick);
    const ty = (ex / el) * Math.sin(flick) + (ey / el) * Math.cos(flick);
    const tailX = spine[n * 2]! - tx * length * 0.03;
    const tailY = spine[n * 2 + 1]! - ty * length * 0.03;
    const tailLen = length * 0.3;
    const tailSpread = length * 0.13;
    // Pectoral fins, set just behind the head, flapping a little out of time with each other.
    const finS = 0.24;
    const fk = Math.round(finS * n);
    const bx = spine[(fk + 1) * 2]! - spine[(fk - 1) * 2]!;
    const by = spine[(fk + 1) * 2 + 1]! - spine[(fk - 1) * 2 + 1]!;
    const bl = Math.hypot(bx, by) || 1;
    // Backward along the body.
    const back = Math.atan2(-by, -bx);
    const finLen = length * 0.17;
    const root = halfWidth(finS) * length * 0.8;
    const fins = [1, -1].map((side) => {
      const flap = Math.sin(koi.phase * 0.5 + (side > 0 ? 0 : 1.7));
      return {
        x: spine[fk * 2]! - (by / bl) * side * root,
        y: spine[fk * 2 + 1]! + (bx / bl) * side * root,
        angle: back - side * (1 + 0.25 * flap),
      };
    });

    let minX = Infinity;
    let maxX = -Infinity;
    let minY = Infinity;
    let maxY = -Infinity;
    for (let i = 0; i < NODES; i++) {
      minX = Math.min(minX, spine[i * 2]!);
      maxX = Math.max(maxX, spine[i * 2]!);
      minY = Math.min(minY, spine[i * 2 + 1]!);
      maxY = Math.max(maxY, spine[i * 2 + 1]!);
    }
    const reach = length * 0.36;
    const c0 = Math.max(0, Math.floor(minX - reach));
    const c1 = Math.min(cols - 1, Math.ceil(maxX + reach));
    const r0 = Math.max(0, Math.floor((minY - reach) / aspect));
    const r1 = Math.min(rows - 1, Math.ceil((maxY + reach) / aspect));
    const fin = finTone(koi);

    for (let row = r0; row <= r1; row++) {
      const y = (row + 0.5) * aspect;
      for (let col = c0; col <= c1; col++) {
        const x = col + 0.5;
        const i = row * cols + col;
        if (padMask[i]) continue;
        // Nearest point on the spine: how far along (s) and how far to the side (v).
        let bestD = Infinity;
        let bestS = 0;
        let bestV = 0;
        let nx = 0;
        let ny = 0;
        for (let k = 0; k < n; k++) {
          const ax = spine[k * 2]!;
          const ay = spine[k * 2 + 1]!;
          const sx = spine[(k + 1) * 2]! - ax;
          const sy = spine[(k + 1) * 2 + 1]! - ay;
          const len2 = sx * sx + sy * sy || 1;
          const t = clamp(((x - ax) * sx + (y - ay) * sy) / len2, 0, 1);
          const qx = ax + sx * t - x;
          const qy = ay + sy * t - y;
          const d = qx * qx + qy * qy;
          if (d < bestD) {
            bestD = d;
            bestS = (k + t) / n;
            bestV = Math.sign(sx * (y - ay) - sy * (x - ax)) * Math.sqrt(d);
            nx = -sy;
            ny = sx;
          }
        }
        const hw = halfWidth(bestS) * length;
        const body = coverage(Math.abs(bestV) - hw);
        if (body > 0.05) {
          const across = clamp(bestV / Math.max(hw, 0.5), -1, 1);
          // The body is a rounded back lit from one side: one flank catches the light, the other
          // falls into shadow, and a sheen runs along the ridge.
          const nl = Math.hypot(nx, ny) || 1;
          const round = Math.sqrt(1 - across * across);
          const lit =
            ((nx / nl) * across * LIGHT[0]! + (ny / nl) * across * LIGHT[1]! + round * LIGHT[2]!) *
              0.5 +
            0.5;
          const light = smoothstep(0.25, 0.95, lit);
          const tone = colourOf(koi, bestS, across);
          cover[i] = 1;
          if (body < 0.55) {
            // The soft edge of the silhouette: a light glyph, no block.
            surface.put(col, row, ramp(EDGE, body * 2), tone, 0.35 + 0.6 * light);
            continue;
          }
          surface.fill(col, row, tone, 0.4 + 0.6 * light);
          // The sheen along the back is left clean; scales show where the light falls away.
          if (light < 0.8) surface.put(col, row, ramp(SCALES, 1 - light), DEEP, 0.4 + 0.4 * light);
          continue;
        }

        // The tail: a fan of fine rays from the stem, its trailing edge forked into two lobes.
        const dx = x - tailX;
        const dy = y - tailY;
        const along = dx * tx + dy * ty;
        if (along > 0 && along < tailLen * 1.05) {
          const side = Math.abs(-dx * ty + dy * tx);
          const k = along / tailLen;
          const spread = length * 0.025 + tailSpread * Math.pow(k, 0.8);
          // The fork: the middle of the trailing edge falls short of the lobes' tips.
          const tip = tailLen * (0.62 + 0.38 * Math.min(1, (side / tailSpread) * 1.1));
          const c = Math.min(coverage(side - spread), coverage(along - tip));
          if (c > 0.1) {
            // A sheer membrane with rays running through it.
            // Sheer, fading toward its edge, with fine rays running through it.
            const ray = Math.abs(Math.sin(Math.atan2(side, along) * 7)) < 0.4;
            surface.put(
              col,
              row,
              ray && c > 0.5 ? stroke(dx, dy) : ramp(EDGE, c * 2),
              fin,
              (0.3 + 0.5 * (1 - k)) * (0.4 + 0.6 * c),
            );
            cover[i] = 1;
            continue;
          }
        }

        for (const f of fins) {
          const ox = x - f.x;
          const oy = y - f.y;
          const r = Math.hypot(ox, oy);
          if (r > finLen * 1.1) continue;
          let off = Math.atan2(oy, ox) - f.angle;
          off = Math.atan2(Math.sin(off), Math.cos(off));
          // A rounded paddle, swept back along the body.
          const reachAt = finLen * Math.sqrt(Math.max(0, 1 - Math.pow(off / 0.5, 2)));
          const c = coverage(r - reachAt);
          if (c > 0.1) {
            const ray = Math.abs(Math.sin(off * 6)) < 0.45;
            surface.put(
              col,
              row,
              ray && c > 0.5 ? stroke(ox, oy) : ramp(EDGE, c * 2),
              fin,
              (0.3 + 0.45 * (1 - r / finLen)) * (0.4 + 0.6 * c),
            );
            cover[i] = 1;
            break;
          }
        }
      }
    }
  }

  /** One dark cell each side of the head, where the eyes sit wide apart. */
  function drawEyes(surface: GlyphSurface, koi: Koi) {
    const at = 0.07 * (NODES - 1);
    const k = Math.floor(at);
    const t = at - k;
    const x = spine[k * 2]! + (spine[(k + 1) * 2]! - spine[k * 2]!) * t;
    const y = spine[k * 2 + 1]! + (spine[(k + 1) * 2 + 1]! - spine[k * 2 + 1]!) * t;
    const dx = spine[(k + 1) * 2]! - spine[k * 2]!;
    const dy = spine[(k + 1) * 2 + 1]! - spine[k * 2 + 1]!;
    const d = Math.hypot(dx, dy) || 1;
    const out = halfWidth(0.07) * koi.length * 0.6;
    for (const side of [1, -1]) {
      const col = Math.floor(x - (dy / d) * side * out);
      const row = Math.floor((y + (dx / d) * side * out) / grid.aspect);
      if (col < 0 || row < 0 || col >= grid.cols || row >= grid.rows) continue;
      if (padMask[row * grid.cols + col]) continue;
      surface.fill(col, row, DEEP, 1);
      surface.put(col, row, DOT, WHITE, 0.5);
    }
  }

  function drawPads(surface: GlyphSurface) {
    const { cols, rows, aspect } = grid;
    for (const pad of pads) {
      const r0 = Math.max(0, Math.floor((pad.y - pad.r - 1) / aspect));
      const r1 = Math.min(rows - 1, Math.ceil((pad.y + pad.r + 1) / aspect));
      const c0 = Math.max(0, Math.floor(pad.x - pad.r - 1));
      const c1 = Math.min(cols - 1, Math.ceil(pad.x + pad.r + 1));
      const turn = pad.notch + time * pad.spin;
      for (let row = r0; row <= r1; row++) {
        for (let col = c0; col <= c1; col++) {
          const dx = col + 0.5 - pad.x;
          const dy = (row + 0.5) * aspect - pad.y;
          const d = Math.hypot(dx, dy);
          let c = coverage(d - pad.r);
          if (c <= 0.1) continue;
          let off = Math.atan2(dy, dx) - turn;
          off = Math.atan2(Math.sin(off), Math.cos(off));
          // The notch: a wedge cut to the centre.
          c = Math.min(c, coverage((Math.abs(off) - 0.22) * -d));
          if (c <= 0.1) continue;
          cover[row * cols + col] = 1;
          // Veins radiate from the centre; the leaf is lit a touch more toward its middle.
          const vein = Math.abs(Math.sin(off * 3.5)) < 0.12 && d > pad.r * 0.2 && d < pad.r - 1;
          const lit = 1 - (d / pad.r) * 0.35;
          if (c < 0.55) {
            surface.put(col, row, ramp(EDGE, c * 2), LEAF, 0.7);
            continue;
          }
          surface.fill(col, row, LEAF_DARK, 0.3 + 0.3 * lit);
          if (vein) surface.put(col, row, stroke(dx, dy), LEAF, 0.45);
        }
      }
    }
  }

  function drawWater(surface: GlyphSurface) {
    const { cols, rows } = grid;
    for (let row = 1; row < rows - 1; row++) {
      for (let col = 1; col < cols - 1; col++) {
        const i = row * cols + col;
        if (cover[i]) continue;
        // Light catches the slopes of the ripples.
        const gx = wave[i + 1]! - wave[i - 1]!;
        const gy = wave[i + cols]! - wave[i - cols]!;
        const lit = gx * 0.8 - gy * 0.6;
        const a = Math.abs(lit);
        if (a > 0.05) {
          surface.put(
            col,
            row,
            a > 0.4 ? '~' : a > 0.18 ? '-' : '.',
            WATER,
            clamp(0.25 + a * 1.4, 0, 1),
          );
          continue;
        }
        // Still water: faint flecks of light that drift and fade.
        const fleck = hash3(col, row, 21);
        if (fleck < 0.04) {
          const glint = noise3(col * 0.12, row * 0.2, time * 0.3);
          if (glint > 0.55) surface.put(col, row, DOT, WATER, (glint - 0.55) * 1.6);
        }
      }
    }
  }

  function propagate() {
    // A wave equation with true distances: cells are taller than they are wide.
    const { cols, rows, aspect } = grid;
    const cx = 0.45;
    const cy = 0.45 / (aspect * aspect);
    for (let row = 1; row < rows - 1; row++) {
      for (let col = 1; col < cols - 1; col++) {
        const i = row * cols + col;
        const h = wave[i]!;
        const next =
          2 * h -
          last[i]! +
          cx * (wave[i - 1]! + wave[i + 1]! - 2 * h) +
          cy * (wave[i - cols]! + wave[i + cols]! - 2 * h);
        last[i] = next * 0.985;
      }
    }
    [wave, last] = [last, wave];
  }

  return {
    palette: [
      '#f4efe6',
      '#ff5a36',
      '#3d414f',
      '#f4b53f',
      '#86a0c8',
      '#5f8fd6',
      '#7cc47f',
      '#2f6b45',
      '#e9b25b',
      '#0b0c10',
    ],
    lineHeight: 0.9,
    settle: 3,
    resize(next) {
      grid = next;
      width = grid.cols;
      height = grid.rows * grid.aspect;
      wave = new Float32Array(grid.cols * grid.rows);
      last = new Float32Array(grid.cols * grid.rows);
      cover = new Uint8Array(grid.cols * grid.rows);
      padMask = new Uint8Array(grid.cols * grid.rows);
      populate();
    },
    step(dt, pointer: AsciiPointer) {
      if (!grid.cols) return;
      time += dt;
      const nx = pointer.x;
      const ny = pointer.y * grid.aspect;
      const moved = pointerActive && pointer.active ? Math.hypot(nx - px, ny - py) / dt : 0;
      pointerSpeed = approach(pointerSpeed, moved, 10, dt);
      pointerActive = pointer.active;
      if (pointer.active && moved > 2) disturb(nx, ny, Math.min(0.6, moved * 0.004));
      px = nx;
      py = ny;

      for (const koi of fish) {
        steer(koi, dt);
        swim(koi, dt);
      }
      for (let k = food.length - 1; k >= 0; k--) {
        food[k]!.age += dt;
        if (food[k]!.age > 9) food.splice(k, 1);
      }
      for (const pad of pads) {
        // Pads drift on the pond's slow current.
        pad.x += (noise3(pad.seed, time * 0.05, 3) - 0.5) * 0.4 * dt;
        pad.y += (noise3(pad.seed, time * 0.05, 8) - 0.5) * 0.4 * dt;
      }
      propagate();
    },
    press(x, y) {
      const cx = x;
      const cy = y * grid.aspect;
      disturb(cx, cy, 3);
      for (let k = 0; k < 6; k++) {
        food.push({ x: cx + (Math.random() - 0.5) * 7, y: cy + (Math.random() - 0.5) * 7, age: 0 });
      }
    },
    draw(surface: GlyphSurface) {
      cover.fill(0);
      // Pads float above the koi, so they claim their cells first.
      drawPads(surface);
      padMask.set(cover);
      for (const koi of fish) {
        drawKoi(surface, koi);
        drawEyes(surface, koi);
      }
      for (const pellet of food) {
        const fade = 1 - pellet.age / 9;
        const col = Math.floor(pellet.x);
        const row = Math.floor(pellet.y / grid.aspect);
        if (!padMask[row * grid.cols + col]) surface.put(col, row, 'o', FOOD, fade);
      }
      drawWater(surface);
    },
  };
}
components/lilt/ascii/engine/stage.tsascii-canvas

stage.ts

import { GlyphSurface, LEVELS } from './surface';
import type { AsciiPointer, AsciiScene } from './types';

const STEP = 1 / 60;
const MAX_STEPS = 8;
const FALLBACK_FONT = 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace';

export interface AsciiStageOptions {
  /** Font size of each cell in CSS pixels. Smaller cells give finer pictures. Default 14. */
  cellSize?: number;
  /** Follow the pointer and answer clicks. Default true. */
  interactive?: boolean;
  /** How fast the scene's clock runs: 0.5 is half speed, 2 is double. Default 1. */
  speed?: number;
}

/**
 * Runs a scene on a canvas: a fixed-step clock, resizing, pointer input, pausing while off screen
 * or in a hidden tab, a single still frame for reduced motion, and repainting when the font or the
 * page theme changes. The canvas's CSS `font-family` and `color` set the type and the ink.
 */
export class AsciiStage {
  private ctx: CanvasRenderingContext2D;
  private surface = new GlyphSurface();
  private styles: string[] = [];
  private pointer: AsciiPointer = { x: 0, y: 0, active: false };
  private cellSize: number;
  private interactive: boolean;
  private speed: number;
  private font = '';
  private cw = 8;
  /** Whether every glyph advances one cell, so rows can be painted as strings. */
  private mono = true;
  private ch = 18;
  private raf = 0;
  private last = 0;
  private acc = 0;
  private time = 0;
  private onScreen = true;
  private disposed = false;
  private reducedMotion: MediaQueryList;
  private resizeObserver: ResizeObserver;
  /** The grid the scene was last sized to. */
  private grid = '';
  private intersectionObserver: IntersectionObserver;
  private themeObserver: MutationObserver;

  constructor(
    private canvas: HTMLCanvasElement,
    private scene: AsciiScene,
    options: AsciiStageOptions = {},
  ) {
    const ctx = canvas.getContext('2d');
    if (!ctx) throw new Error('AsciiStage needs a 2D canvas context.');
    this.ctx = ctx;
    this.cellSize = options.cellSize ?? 14;
    this.interactive = options.interactive ?? true;
    this.speed = options.speed ?? 1;
    this.reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');

    this.resizeObserver = new ResizeObserver(() => this.resize());
    this.resizeObserver.observe(canvas);
    this.intersectionObserver = new IntersectionObserver(([entry]) => {
      this.onScreen = entry?.isIntersecting ?? true;
      this.schedule();
    });
    this.intersectionObserver.observe(canvas);
    // Theme switches usually flip a class or attribute on the root; the ink follows.
    this.themeObserver = new MutationObserver(() => this.restyle());
    this.themeObserver.observe(document.documentElement, {
      attributes: true,
      attributeFilter: ['class', 'style', 'data-theme'],
    });

    this.reducedMotion.addEventListener('change', this.schedule);
    document.addEventListener('visibilitychange', this.schedule);
    window.addEventListener('pointermove', this.onPointerMove, { passive: true });
    window.addEventListener('pointerdown', this.onPointerDown, { passive: true });
    document.documentElement.addEventListener('pointerleave', this.onPointerLeave);
    window.addEventListener('blur', this.onPointerLeave);

    this.resize();
    // Canvas text never asks for a webfont, so measure again once the page's fonts arrive.
    document.fonts?.ready.then(() => {
      if (this.disposed) return;
      this.resize();
    });
    this.schedule();
  }

  destroy() {
    this.disposed = true;
    cancelAnimationFrame(this.raf);
    this.resizeObserver.disconnect();
    this.intersectionObserver.disconnect();
    this.themeObserver.disconnect();
    this.reducedMotion.removeEventListener('change', this.schedule);
    document.removeEventListener('visibilitychange', this.schedule);
    window.removeEventListener('pointermove', this.onPointerMove);
    window.removeEventListener('pointerdown', this.onPointerDown);
    document.documentElement.removeEventListener('pointerleave', this.onPointerLeave);
    window.removeEventListener('blur', this.onPointerLeave);
  }

  /** Changes the stage's options in place, keeping the scene's world as it is. */
  configure(options: AsciiStageOptions) {
    this.speed = options.speed ?? this.speed;
    if (options.interactive !== undefined) {
      this.interactive = options.interactive;
      if (!this.interactive) this.pointer.active = false;
    }
    if (options.cellSize !== undefined && options.cellSize !== this.cellSize) {
      this.cellSize = options.cellSize;
      this.resize();
    }
  }

  /** Reads the canvas's `color` again, after the ink was changed by something other than a theme. */
  refresh() {
    this.restyle();
  }

  private get still() {
    return this.reducedMotion.matches;
  }

  private resize() {
    const rect = this.canvas.getBoundingClientRect();
    if (rect.width < 1 || rect.height < 1) return;
    const dpr = Math.min(window.devicePixelRatio || 1, 2);
    this.canvas.width = Math.round(rect.width * dpr);
    this.canvas.height = Math.round(rect.height * dpr);

    const family = getComputedStyle(this.canvas).fontFamily || FALLBACK_FONT;
    this.font = `500 ${this.cellSize}px ${family}, ${FALLBACK_FONT}`;
    const { ctx } = this;
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    ctx.font = this.font;
    this.cw = Math.max(4, ctx.measureText('M').width);
    this.mono = Math.abs(ctx.measureText('i').width - this.cw) < 0.01;
    this.ch = Math.round(this.cellSize * (this.scene.lineHeight ?? 1.25));

    const cols = Math.ceil(rect.width / this.cw);
    const rows = Math.ceil(rect.height / this.ch);
    this.surface.resize(cols, rows);
    // Fonts arriving or a pixel of layout can measure the same grid again; the scene keeps its world.
    const grid = `${cols}x${rows}x${this.ch / this.cw}`;
    if (grid !== this.grid) {
      this.grid = grid;
      this.scene.resize({ cols, rows, aspect: this.ch / this.cw });
    }
    this.restyle();
  }

  /** Resolves the palette to fill styles, one per colour and opacity step. */
  private restyle() {
    const { ctx } = this;
    const ink = getComputedStyle(this.canvas).color;
    this.styles = this.scene.palette.flatMap((colour) => {
      ctx.fillStyle = '#000';
      ctx.fillStyle = colour === 'ink' ? ink : colour;
      const [r, g, b] = parseColour(String(ctx.fillStyle));
      return Array.from({ length: LEVELS }, (_, i) => `rgba(${r},${g},${b},${(i + 1) / LEVELS})`);
    });
    if (this.still) this.drawStill();
  }

  private schedule = () => {
    cancelAnimationFrame(this.raf);
    if (this.disposed) return;
    if (this.still) {
      this.drawStill();
      return;
    }
    if (!this.onScreen || document.hidden) return;
    this.last = performance.now();
    this.raf = requestAnimationFrame(this.frame);
  };

  private frame = (now: number) => {
    const dt = Math.min(0.1, (now - this.last) / 1000) * this.speed;
    this.last = now;
    this.acc += dt;
    let steps = 0;
    while (this.acc >= STEP && steps < MAX_STEPS) {
      this.scene.step(STEP, this.pointer);
      this.time += STEP;
      this.acc -= STEP;
      steps++;
    }
    if (steps === MAX_STEPS) this.acc = 0;
    this.paint();
    this.raf = requestAnimationFrame(this.frame);
  };

  /** Lets the scene settle without the pointer, then shows that one frame. */
  private drawStill() {
    const settle = this.scene.settle ?? 3;
    const idle: AsciiPointer = { x: 0, y: 0, active: false };
    while (this.time < settle) {
      this.scene.step(STEP, idle);
      this.time += STEP;
    }
    this.paint();
  }

  private paint() {
    const { ctx, canvas, surface } = this;
    ctx.save();
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.restore();
    ctx.font = this.font;
    ctx.textBaseline = 'middle';
    surface.clear();
    this.scene.draw(surface);
    surface.paint(ctx, this.styles, this.cw, this.ch, this.mono);
  }

  private toCells(e: PointerEvent) {
    const rect = this.canvas.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    const inside = x >= 0 && y >= 0 && x <= rect.width && y <= rect.height;
    return { x: x / this.cw, y: y / this.ch, inside };
  }

  private onPointerMove = (e: PointerEvent) => {
    if (!this.interactive) return;
    const { x, y, inside } = this.toCells(e);
    this.pointer.x = x;
    this.pointer.y = y;
    // A finger has no hover; it only presses.
    this.pointer.active = inside && e.pointerType !== 'touch';
  };

  private onPointerDown = (e: PointerEvent) => {
    const { x, y, inside } = this.toCells(e);
    if (!inside || this.still || !this.interactive) return;
    this.scene.press?.(x, y);
  };

  private onPointerLeave = () => {
    this.pointer.active = false;
  };
}

/** Reads the `#rrggbb` or `rgba(r, g, b, a)` a canvas reports back for any CSS colour. */
function parseColour(value: string): [number, number, number] {
  if (value.startsWith('#')) {
    const n = parseInt(value.slice(1, 7), 16);
    return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
  }
  const parts = value.match(/[\d.]+/g)?.map(Number) ?? [];
  return [parts[0] ?? 0, parts[1] ?? 0, parts[2] ?? 0];
}
components/lilt/ascii/react/ascii-canvas.tsxascii-canvas

ascii-canvas.tsx

'use client';

import { useEffect, useRef, type CSSProperties } from 'react';
import { AsciiStage } from '../engine/stage';
import type { AsciiScene } from '../engine/types';

export interface AsciiCanvasProps {
  /** Builds the scene. Called again only when `sceneKey` changes. */
  scene: () => AsciiScene;
  /** Changes when the scene should be rebuilt, such as a JSON string of its options. */
  sceneKey?: string;
  /** Font size of each cell in CSS pixels. Default 14. */
  cellSize?: number;
  /** Follow the pointer and answer clicks. Default true. */
  interactive?: boolean;
  /** How fast the scene's clock runs: 0.5 is half speed, 2 is double. Default 1. */
  speed?: number;
  /**
   * Describes the picture for screen readers. Without one the canvas is decorative and hidden
   * from assistive technology, which suits a background.
   */
  label?: string;
  className?: string;
  style?: CSSProperties;
}

/**
 * A canvas that runs an ASCII scene. It fills its parent; give the parent a size. Set the type
 * with CSS `font-family` (a monospace face) and the ink with `color`.
 */
export function AsciiCanvas({
  scene,
  sceneKey,
  cellSize,
  interactive,
  speed,
  label,
  className,
  style,
}: AsciiCanvasProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const stageRef = useRef<AsciiStage | null>(null);
  const latest = useRef({ scene, cellSize, interactive, speed });
  latest.current = { scene, cellSize, interactive, speed };

  // A new scene starts a new world; everything else is tuned on the running stage.
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const { scene: build, ...options } = latest.current;
    const stage = new AsciiStage(canvas, build(), options);
    stageRef.current = stage;
    return () => {
      stage.destroy();
      stageRef.current = null;
    };
  }, [sceneKey]);

  useEffect(() => {
    stageRef.current?.configure({ cellSize, interactive, speed });
  }, [cellSize, interactive, speed]);

  const ink = style?.color;
  useEffect(() => {
    stageRef.current?.refresh();
  }, [ink]);

  return (
    <canvas
      ref={canvasRef}
      className={className ? `lilt-ascii ${className}` : 'lilt-ascii'}
      style={{ display: 'block', width: '100%', height: '100%', ...style }}
      {...(label ? { role: 'img', 'aria-label': label } : { 'aria-hidden': true })}
    />
  );
}

export type SceneProps<Options> = Options & Omit<AsciiCanvasProps, 'scene' | 'sceneKey'>;

/** Splits a scene's own options from the canvas props. */
export function useSceneProps<Options extends object>(
  props: SceneProps<Options>,
  create: (options: Options) => AsciiScene,
): AsciiCanvasProps {
  const { cellSize, interactive, speed, label, className, style, ...options } = props;
  return {
    scene: () => create(options as Options),
    sceneKey: JSON.stringify(options),
    cellSize,
    interactive,
    speed,
    label,
    className,
    style,
  };
}
components/lilt/ascii/engine/noise.tsascii-engine

noise.ts

/** A stable pseudo-random number in [0, 1) for an integer lattice point. */
export function hash3(x: number, y: number, z: number): number {
  let h =
    Math.imul(x | 0, 0x27d4eb2d) ^ Math.imul(y | 0, 0x165667b1) ^ Math.imul(z | 0, 0x9e3779b1);
  h = Math.imul(h ^ (h >>> 15), 0x85ebca6b);
  h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35);
  return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
}

const fade = (t: number) => t * t * (3 - 2 * t);
const mix = (a: number, b: number, t: number) => a + (b - a) * t;

/** Smooth value noise in [0, 1). */
export function noise3(x: number, y: number, z: number): number {
  const xi = Math.floor(x);
  const yi = Math.floor(y);
  const zi = Math.floor(z);
  const u = fade(x - xi);
  const v = fade(y - yi);
  const w = fade(z - zi);
  const a = mix(hash3(xi, yi, zi), hash3(xi + 1, yi, zi), u);
  const b = mix(hash3(xi, yi + 1, zi), hash3(xi + 1, yi + 1, zi), u);
  const c = mix(hash3(xi, yi, zi + 1), hash3(xi + 1, yi, zi + 1), u);
  const d = mix(hash3(xi, yi + 1, zi + 1), hash3(xi + 1, yi + 1, zi + 1), u);
  return mix(mix(a, b, v), mix(c, d, v), w);
}

/** Layered noise in [0, 1): each octave doubles the detail and halves the weight. */
export function fbm3(x: number, y: number, z: number, octaves = 4): number {
  let sum = 0;
  let weight = 0.5;
  let total = 0;
  for (let i = 0; i < octaves; i++) {
    sum += noise3(x, y, z) * weight;
    total += weight;
    weight *= 0.5;
    x *= 2.03;
    y *= 2.03;
    z *= 2.03;
  }
  return sum / total;
}

export const clamp = (value: number, min: number, max: number) =>
  value < min ? min : value > max ? max : value;

export const smoothstep = (edge0: number, edge1: number, x: number) => {
  const t = clamp((x - edge0) / (edge1 - edge0), 0, 1);
  return t * t * (3 - 2 * t);
};

/** Frame-rate independent easing toward a target: `rate` is the share closed per second. */
export const approach = (current: number, target: number, rate: number, dt: number) =>
  target + (current - target) * Math.exp(-rate * dt);
components/lilt/ascii/engine/glyphs.tsascii-engine

glyphs.ts

import { clamp } from './noise';

/** The glyph a share of the way along a ramp of glyphs, sparse to dense. */
export function ramp(glyphs: string, value: number): string {
  return glyphs[clamp(Math.floor(value * glyphs.length), 0, glyphs.length - 1)]!;
}

/**
 * The stroke that best follows a direction on screen. `dx` and `dy` are in square units (cell
 * widths), y down. Used for tentacles, grass and anything else drawn as a line of type.
 */
export function stroke(dx: number, dy: number): string {
  const angle = Math.atan2(dy, dx);
  // Fold to [0, π): a stroke has no direction.
  const a = angle < 0 ? angle + Math.PI : angle;
  if (a < Math.PI / 8 || a >= (Math.PI * 7) / 8) return '-';
  if (a < (Math.PI * 3) / 8) return '\\';
  if (a < (Math.PI * 5) / 8) return '|';
  return '/';
}
components/lilt/ascii/engine/surface.tsascii-engine

surface.ts

/** Opacity steps per colour. Cells sharing a colour and step are painted with one fill style. */
export const LEVELS = 8;

/** A glyph code for a small solid square: crisper than a full stop at every font size. */
export const DOT = 1;

/**
 * One frame of type: a glyph, colour and opacity per cell, and optionally a solid block behind it.
 * Scenes write into it; the stage paints it in batches, one fill style per colour and opacity, so a
 * full screen costs a few dozen style changes rather than thousands.
 */
export class GlyphSurface {
  cols = 0;
  rows = 0;
  glyph = new Uint16Array(0);
  tone = new Uint8Array(0);
  level = new Uint8Array(0);
  /** The block behind each cell: its colour, and its opacity step, 0 for none. */
  blockTone = new Uint8Array(0);
  blockLevel = new Uint8Array(0);
  private order = new Int32Array(0);
  private counts = new Int32Array(0);
  private starts = new Int32Array(0);

  resize(cols: number, rows: number) {
    this.cols = cols;
    this.rows = rows;
    const size = cols * rows;
    this.glyph = new Uint16Array(size);
    this.tone = new Uint8Array(size);
    this.level = new Uint8Array(size);
    this.blockTone = new Uint8Array(size);
    this.blockLevel = new Uint8Array(size);
    this.order = new Int32Array(size);
  }

  clear() {
    this.glyph.fill(0);
    this.blockLevel.fill(0);
  }

  /**
   * Writes a glyph; later writes replace earlier ones, so draw back to front. `glyph` is a
   * character, a char code, or `DOT`. Opacity at or below zero leaves the cell untouched.
   */
  put(col: number, row: number, glyph: string | number, tone: number, opacity = 1) {
    col = Math.floor(col);
    row = Math.floor(row);
    if (col < 0 || row < 0 || col >= this.cols || row >= this.rows || opacity <= 0) return;
    const i = row * this.cols + col;
    this.glyph[i] = typeof glyph === 'number' ? glyph : glyph.charCodeAt(0);
    this.tone[i] = tone;
    this.level[i] = Math.min(LEVELS, Math.ceil(opacity * LEVELS));
  }

  /**
   * Fills a cell with a solid block of colour, painted behind its glyph. Solid shapes read as one
   * mass this way, with a glyph cut into each block, the way a mosaic does. Opacity at or below
   * zero removes the block.
   */
  fill(col: number, row: number, tone: number, opacity = 1) {
    col = Math.floor(col);
    row = Math.floor(row);
    if (col < 0 || row < 0 || col >= this.cols || row >= this.rows) return;
    const i = row * this.cols + col;
    this.blockTone[i] = tone;
    this.blockLevel[i] = opacity <= 0 ? 0 : Math.min(LEVELS, Math.ceil(opacity * LEVELS));
  }

  /** True when a cell already holds a glyph or a block this frame. */
  filled(col: number, row: number) {
    col = Math.floor(col);
    row = Math.floor(row);
    if (col < 0 || row < 0 || col >= this.cols || row >= this.rows) return false;
    const i = row * this.cols + col;
    return this.glyph[i] !== 0 || this.blockLevel[i] !== 0;
  }

  /**
   * Sorts cells into buckets of one fill style each, by counting: `bucketOf` gives a cell's bucket,
   * or -1 to skip it. Leaves the cells in `order` and returns how many fall in each bucket.
   */
  private sort(buckets: number, bucketOf: (i: number) => number) {
    if (this.counts.length !== buckets) {
      this.counts = new Int32Array(buckets);
      this.starts = new Int32Array(buckets);
    }
    const { order, counts, starts } = this;
    counts.fill(0);
    const n = this.glyph.length;
    for (let i = 0; i < n; i++) {
      const b = bucketOf(i);
      if (b >= 0 && b < buckets) counts[b]++;
    }
    let sum = 0;
    for (let b = 0; b < buckets; b++) {
      starts[b] = sum;
      sum += counts[b]!;
    }
    for (let i = 0; i < n; i++) {
      const b = bucketOf(i);
      if (b >= 0 && b < buckets) order[starts[b]!++] = i;
    }
    return counts;
  }

  /**
   * Paints the frame. `styles[tone * LEVELS + level - 1]` is the fill style for each bucket.
   * With a monospace font, each bucket's glyphs on a row go out as one string with spaces in the
   * gaps: a canvas pays per text call far more than per glyph, so this is many times faster.
   */
  paint(
    ctx: CanvasRenderingContext2D,
    styles: readonly string[],
    cw: number,
    ch: number,
    mono = true,
  ) {
    const buckets = styles.length;
    const { glyph, tone, level, blockTone, blockLevel, order, cols } = this;

    // Blocks first, each inset a pixel so the grid of type still shows between them.
    let counts = this.sort(buckets, (i) =>
      blockLevel[i] ? blockTone[i]! * LEVELS + blockLevel[i]! - 1 : -1,
    );
    let k = 0;
    for (let b = 0; b < buckets; b++) {
      const count = counts[b]!;
      if (!count) continue;
      ctx.fillStyle = styles[b]!;
      for (const end = k + count; k < end; k++) {
        const i = order[k]!;
        const col = i % cols;
        const row = (i - col) / cols;
        ctx.fillRect(col * cw + 0.5, row * ch + 0.5, cw - 1, ch - 1);
      }
    }

    counts = this.sort(buckets, (i) => (glyph[i] ? tone[i]! * LEVELS + level[i]! - 1 : -1));
    const dot = Math.max(1.5, Math.round(cw * 0.22));
    ctx.textAlign = mono ? 'left' : 'center';
    k = 0;
    for (let b = 0; b < buckets; b++) {
      const count = counts[b];
      if (!count) continue;
      ctx.fillStyle = styles[b]!;
      // A run of text on one row: where it starts, and its characters so far.
      let runRow = -1;
      let runCol = 0;
      let lastCol = 0;
      let run = '';
      for (const end = k + count; k < end; k++) {
        const i = order[k]!;
        const col = i % cols;
        const row = (i - col) / cols;
        const code = glyph[i]!;
        if (code === DOT) {
          ctx.fillRect(col * cw + cw / 2 - dot / 2, row * ch + ch / 2 - dot / 2, dot, dot);
          continue;
        }
        if (!mono) {
          ctx.fillText(String.fromCharCode(code), col * cw + cw / 2, row * ch + ch / 2);
          continue;
        }
        if (row !== runRow) {
          if (run) ctx.fillText(run, runCol * cw, runRow * ch + ch / 2);
          runRow = row;
          runCol = col;
          run = '';
        } else {
          run += ' '.repeat(col - lastCol - 1);
        }
        run += String.fromCharCode(code);
        lastCol = col;
      }
      if (run) ctx.fillText(run, runCol * cw, runRow * ch + ch / 2);
    }
  }
}
components/lilt/ascii/engine/types.tsascii-engine

types.ts

import type { GlyphSurface } from './surface';

/** The character grid a scene draws into. Positions are in cells; `aspect` is cell height over width. */
export interface AsciiGrid {
  cols: number;
  rows: number;
  aspect: number;
}

export interface AsciiPointer {
  /** Column under the pointer, fractional. */
  x: number;
  /** Row under the pointer, fractional. */
  y: number;
  /** False when the pointer is outside the canvas or is a finger that lifted. */
  active: boolean;
}

/**
 * A living picture made of type. The stage owns the canvas, the clock and input; a scene owns its
 * world. `step` runs on a fixed 60 Hz clock and `draw` writes the current frame into the surface.
 */
export interface AsciiScene {
  /**
   * The scene's colours, addressed by index from `draw`. Any CSS colour works; `ink` is the
   * canvas's own text colour, so a scene can follow the page's light or dark theme.
   */
  readonly palette: readonly string[];
  resize(grid: AsciiGrid): void;
  step(dt: number, pointer: AsciiPointer): void;
  draw(surface: GlyphSurface): void;
  /** A click or tap at a cell. */
  press?(x: number, y: number): void;
  /**
   * Height of a row as a multiple of the font size. Default 1.25. Scenes made of solid shapes ask
   * for tighter rows, closer to square cells, so a body lying sideways still spans several rows.
   */
  readonly lineHeight?: number;
  /** Seconds to run before showing a single still frame when the reader prefers reduced motion. */
  readonly settle?: number;
}

Usage

How it behaves.

The scene fills its parent, so give the parent a size. The canvas takes its type from CSS font-family and its ink from color. It pauses off screen and in hidden tabs, and shows one still frame when the reader prefers reduced motion.

Props7

Every option.

Pass these directly to AsciiKoi.

PropTypeDefaultWhat it does
countnumber4How many koi.
padsnumber3How many lily pads float on the pond.
sizenumber1Size of the koi, relative to the pond.
cellSizenumber14Font size of each cell in pixels. Smaller cells draw a finer picture.
speednumber1How fast the clock runs: 0.5 is half speed, 2 is double.
interactivebooleantrueFollow the pointer and answer clicks.
labelstring—Describes the picture for screen readers. Without one it is a hidden background.
Previous sceneRainNext sceneJellyfish

Ready when your data is. Start with one install.

Install a package, import the stylesheet once, and drop in a card or a scene.

Read the guideRead the guideView on GitHubView on GitHub
ChartsAll chartsAll chartsFinanceFinanceCustomizeCustomizeFeaturesFeatures
ComponentsAll componentsAll componentsAIAIStatusStatusActionsActionsDataData
VisualsAll visualsAll visualsAIAIDataDataSecuritySecurityProductProduct
ASCIIAll scenesAll scenesTextTextInterfaceInterfaceBackgroundsBackgroundsMediaMediaDataData
DocsGetting startedGetting startedAPI referenceAPI referenceMotion & accessibilityMotion & accessibilityllms.txtllms.txt
React components with a little lilt.GitHubGitHubnpmnpm