Back to Gem Warden
SOURCE / PINNED RELEASE

Made of little things.

Gem Warden

Release
d7ee3a74bdb5…
Author-recorded commit
1bfb3fd0904c…
License
LICENSE
Author’s source reference
nostr://npub1eg5pfnws6tg6rtp33tugpppqtv5u05crmf983qp438cdycwzngys0gxzcs/wss%3A%2F%2Fgit.napplet.soy%2F/n-3929629ef1d

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

src/fx.ts
// Particles, shockwaves, lightning, screen shake and flashes. Purely visual:
// nothing here feeds back into the game rules.
//
// Two spaces share one particle pool. Field effects live in tile units, so
// they survive a resize and run on game time (they freeze when the game is
// paused). Interface effects live in CSS pixels and run on real time.

export const FIELD = 0;
export const UI = 1;
export type Space = typeof FIELD | typeof UI;

/** Maps a space's units to canvas pixels: origin and pixels per unit. */
export interface View {
  ctx: CanvasRenderingContext2D;
  ox: number;
  oy: number;
  unit: number;
}

const SPARK = 0;
const GLOW = 1;
const SHARD = 2;
const RING = 3;
const TEXT = 4;
const MOTE = 5;
const BOLT = 6;
const BUBBLE = 7;
const STAR = 8;

interface Particle {
  kind: number;
  space: Space;
  x: number;
  y: number;
  vx: number;
  vy: number;
  life: number;
  max: number;
  /** Seconds before it appears. */
  delay: number;
  color: string;
  /** In the space's units. */
  size: number;
  gravity: number;
  /** Share of the velocity kept after one sixtieth of a second. */
  drag: number;
  rot: number;
  spin: number;
  text?: string;
  /** Rings grow from `size` to this radius; bolts and motes end here. */
  r1: number;
  tx: number;
  ty: number;
  arrive?: () => void;
  /** A field particle that keeps real time, so it plays out during a pause. */
  real: boolean;
}

let particles: Particle[] = [];
let timers: { t: number; fn: () => void }[] = [];
let shakeAmount = 0;
let shakeX = 0;
let shakeY = 0;
let flashColor = '#fff';
let flashAlpha = 0;
let emitReal = false;

/** Field effects emitted inside fn keep real time: for what the player does
 *  while paused, like building or combining, which should not hang frozen. */
export function realTime(fn: () => void): void {
  emitReal = true;
  try {
    fn();
  } finally {
    emitReal = false;
  }
}

/** Particle budget: 1 full, lower on slow devices or with reduced motion. */
export let quality = 1;
/** With reduced motion there is no shake and no full-field flash. */
export let calm = false;

export function setQuality(q: number, reducedMotion: boolean): void {
  quality = q;
  calm = reducedMotion;
}

/** A particle count scaled by the budget, never below one. */
export function amount(n: number): number {
  return Math.max(1, Math.round(n * quality));
}

export function clear(): void {
  particles = [];
  timers = [];
  shakeAmount = 0;
  flashAlpha = 0;
}

export function count(): number {
  return particles.length;
}

function add(p: Partial<Particle> & { kind: number; space: Space; x: number; y: number; life: number; color: string; size: number }): Particle {
  const q: Particle = { vx: 0, vy: 0, max: p.life, delay: 0, gravity: 0, drag: 1, rot: 0, spin: 0, r1: 0, tx: 0, ty: 0, real: emitReal, ...p };
  q.max = q.life;
  particles.push(q);
  return q;
}

export interface BurstOpts {
  /** Outward speed, in units per second. */
  speed: number;
  life: number;
  size: number;
  gravity?: number;
  drag?: number;
  /** Pull the burst towards one direction (radians) within a spread. */
  angle?: number;
  spread?: number;
  /** Start this far from the centre. */
  radius?: number;
  delay?: number;
}

/** Bright streaks flying out from a point. */
export function sparks(space: Space, x: number, y: number, n: number, color: string, o: BurstOpts): void {
  for (let i = 0; i < amount(n); i++) {
    const a = o.angle === undefined ? Math.random() * Math.PI * 2 : o.angle + (Math.random() - 0.5) * (o.spread ?? 1);
    const v = o.speed * (0.35 + Math.random() * 0.9);
    const r = o.radius ?? 0;
    add({
      kind: SPARK,
      space,
      x: x + Math.cos(a) * r,
      y: y + Math.sin(a) * r,
      vx: Math.cos(a) * v,
      vy: Math.sin(a) * v,
      life: o.life * (0.6 + Math.random() * 0.7),
      color,
      size: o.size * (0.6 + Math.random() * 0.8),
      gravity: o.gravity ?? 0,
      drag: o.drag ?? 0.93,
      delay: o.delay ?? 0,
    });
  }
}

/** Sparks that start on a circle and rush to its centre. */
export function implode(space: Space, x: number, y: number, n: number, color: string, radius: number, life: number, size: number): void {
  for (let i = 0; i < amount(n); i++) {
    const a = Math.random() * Math.PI * 2;
    const r = radius * (0.7 + Math.random() * 0.5);
    add({ kind: SPARK, space, x: x + Math.cos(a) * r, y: y + Math.sin(a) * r, vx: (-Math.cos(a) * r) / life, vy: (-Math.sin(a) * r) / life, life, color, size, drag: 1 });
  }
}

/** Tumbling solid fragments that fall. */
export function shards(space: Space, x: number, y: number, n: number, color: string, o: BurstOpts): void {
  for (let i = 0; i < amount(n); i++) {
    const a = Math.random() * Math.PI * 2;
    const v = o.speed * (0.3 + Math.random());
    add({
      kind: SHARD,
      space,
      x,
      y,
      vx: Math.cos(a) * v,
      vy: Math.sin(a) * v - o.speed * 0.3,
      life: o.life * (0.6 + Math.random() * 0.7),
      color,
      size: o.size * (0.5 + Math.random()),
      gravity: o.gravity ?? 0,
      drag: o.drag ?? 0.95,
      rot: Math.random() * 6.28,
      spin: (Math.random() - 0.5) * 16,
    });
  }
}

/** A soft light that swells and fades. */
export function glow(space: Space, x: number, y: number, size: number, life: number, color: string, delay = 0): void {
  add({ kind: GLOW, space, x, y, life, color, size, delay });
}

/** A shockwave ring growing from r0 to r1. */
export function ring(space: Space, x: number, y: number, r0: number, r1: number, life: number, color: string, width: number, delay = 0): void {
  add({ kind: RING, space, x, y, life, color, size: r0, r1, tx: width, delay });
}

export function floatText(space: Space, x: number, y: number, text: string, color: string, size: number, life: number, vy: number): void {
  add({ kind: TEXT, space, x, y, vy, life, color, size, text });
}

/** A light that homes in on a target and reports its arrival. */
export function mote(space: Space, x: number, y: number, tx: number, ty: number, color: string, size: number, kick: number, arrive?: () => void, delay = 0): void {
  if (particles.length > 900) {
    arrive?.();
    return;
  }
  const a = Math.random() * Math.PI * 2;
  add({ kind: MOTE, space, x, y, vx: Math.cos(a) * kick, vy: Math.sin(a) * kick, tx, ty, life: 2.2, color, size, arrive, delay });
}

/** A jagged bolt of lightning between two points. */
export function bolt(space: Space, x: number, y: number, x2: number, y2: number, color: string, life: number, width: number): void {
  add({ kind: BOLT, space, x, y, tx: x2, ty: y2, life, color, size: width });
}

export function bubble(space: Space, x: number, y: number, color: string, size: number, life: number, vy: number): void {
  add({ kind: BUBBLE, space, x, y, vx: (Math.random() - 0.5) * 0.3, vy, life, color, size });
}

/** A four-pointed glint. */
export function star(space: Space, x: number, y: number, size: number, life: number, color: string, delay = 0): void {
  add({ kind: STAR, space, x, y, life, color, size, rot: Math.random() * 0.6, spin: 1.5, delay });
}

export function shake(amountTiles: number): void {
  if (calm) return;
  shakeAmount = Math.min(0.6, Math.max(shakeAmount, amountTiles));
}

export function flash(color: string, alpha: number): void {
  if (calm) return;
  if (alpha >= flashAlpha) {
    flashColor = color;
    flashAlpha = alpha;
  }
}

/** Runs fn after a delay on real time. */
export function after(delay: number, fn: () => void): void {
  timers.push({ t: delay, fn });
}

/** dtField is game time (zero while paused); dtUi is real time. */
export function update(dtField: number, dtUi: number): void {
  shakeAmount *= Math.exp(-dtUi * 8);
  if (shakeAmount < 0.004) shakeAmount = 0;
  shakeX = (Math.random() * 2 - 1) * shakeAmount;
  shakeY = (Math.random() * 2 - 1) * shakeAmount;
  flashAlpha = Math.max(0, flashAlpha - dtUi * 2.6);

  if (timers.length) {
    const due = timers.filter((t) => (t.t -= dtUi) <= 0);
    timers = timers.filter((t) => t.t > 0);
    for (const t of due) t.fn();
  }

  let alive = 0;
  for (const p of particles) {
    const dt = p.space === FIELD && !p.real ? dtField : dtUi;
    if (dt <= 0) {
      particles[alive++] = p;
      continue;
    }
    if (p.delay > 0) {
      p.delay -= dt;
      particles[alive++] = p;
      continue;
    }
    p.life -= dt;
    if (p.kind === MOTE) {
      const dx = p.tx - p.x;
      const dy = p.ty - p.y;
      const d = Math.hypot(dx, dy) || 0.001;
      const age = p.max - p.life;
      // Drifts on its kick at first, then steers ever harder at the target.
      const want = (p.space === FIELD ? 5 : 260) * (0.4 + age * 5);
      const steer = Math.min(1, dt * (2 + age * 14));
      p.vx += ((dx / d) * want - p.vx) * steer;
      p.vy += ((dy / d) * want - p.vy) * steer;
      const move = Math.hypot(p.vx, p.vy) * dt;
      if (d <= Math.max(move, p.space === FIELD ? 0.2 : 8) || p.life <= 0) {
        p.arrive?.();
        continue;
      }
    } else if (p.life <= 0) continue;
    const k = Math.pow(p.drag, dt * 60);
    p.vx *= k;
    p.vy = p.vy * k + p.gravity * dt;
    p.x += p.vx * dt;
    p.y += p.vy * dt;
    p.rot += p.spin * dt;
    particles[alive++] = p;
  }
  particles.length = alive;
  // Under pressure the oldest plain particles go first; texts and motes carry meaning.
  const cap = Math.round(300 + 700 * quality);
  if (particles.length > cap) {
    let drop = particles.length - cap;
    particles = particles.filter((p) => p.kind === TEXT || p.kind === MOTE || drop-- <= 0);
  }
}

// ------------------------------------------------------------------ drawing

const sprites = new Map<string, HTMLCanvasElement>();

/** A soft round light in one colour with a white-hot core, drawn once and reused. */
function sprite(color: string): HTMLCanvasElement {
  let s = sprites.get(color);
  if (s) return s;
  if (sprites.size > 120) sprites.clear();
  const n = 64;
  s = document.createElement('canvas');
  s.width = n;
  s.height = n;
  const c = s.getContext('2d') as CanvasRenderingContext2D;
  const g = c.createRadialGradient(n / 2, n / 2, 0, n / 2, n / 2, n / 2);
  g.addColorStop(0, 'rgba(255,255,255,1)');
  g.addColorStop(0.3, 'rgba(255,255,255,0.5)');
  g.addColorStop(0.6, 'rgba(255,255,255,0.14)');
  g.addColorStop(1, 'rgba(255,255,255,0)');
  c.fillStyle = g;
  c.fillRect(0, 0, n, n);
  c.globalCompositeOperation = 'source-in';
  c.fillStyle = color;
  c.fillRect(0, 0, n, n);
  c.globalCompositeOperation = 'source-over';
  const w = c.createRadialGradient(n / 2, n / 2, 0, n / 2, n / 2, n * 0.2);
  w.addColorStop(0, 'rgba(255,255,255,0.85)');
  w.addColorStop(1, 'rgba(255,255,255,0)');
  c.fillStyle = w;
  c.fillRect(0, 0, n, n);
  sprites.set(color, s);
  return s;
}

/** Draws a light of the given pixel radius, adding to what is beneath. */
export function light(ctx: CanvasRenderingContext2D, x: number, y: number, radius: number, color: string, alpha: number): void {
  if (alpha <= 0.003 || radius <= 0.3) return;
  const op = ctx.globalCompositeOperation;
  const ga = ctx.globalAlpha;
  ctx.globalCompositeOperation = 'lighter';
  ctx.globalAlpha = Math.min(1, alpha) * ga;
  ctx.drawImage(sprite(color), x - radius, y - radius, radius * 2, radius * 2);
  ctx.globalAlpha = ga;
  ctx.globalCompositeOperation = op;
}

/** A four-pointed glint centred on a point; `k` runs 0 to 1 over its life. */
export function glint(ctx: CanvasRenderingContext2D, x: number, y: number, radius: number, k: number, color: string, rot = 0): void {
  const s = Math.sin(Math.PI * Math.max(0, Math.min(1, k)));
  if (s <= 0.02) return;
  const op = ctx.globalCompositeOperation;
  ctx.save();
  ctx.globalCompositeOperation = 'lighter';
  ctx.translate(x, y);
  ctx.rotate(rot);
  ctx.globalAlpha *= s;
  ctx.fillStyle = color;
  const r = radius * s;
  const w = r * 0.09;
  ctx.beginPath();
  ctx.moveTo(0, -r);
  ctx.lineTo(w, -w);
  ctx.lineTo(r, 0);
  ctx.lineTo(w, w);
  ctx.lineTo(0, r);
  ctx.lineTo(-w, w);
  ctx.lineTo(-r, 0);
  ctx.lineTo(-w, -w);
  ctx.closePath();
  ctx.fill();
  ctx.restore();
  ctx.globalCompositeOperation = op;
}

/** A jagged line between two pixel points, redrawn at random every frame. */
export function lightning(ctx: CanvasRenderingContext2D, x1: number, y1: number, x2: number, y2: number, color: string, width: number, alpha: number): void {
  const dx = x2 - x1;
  const dy = y2 - y1;
  const d = Math.hypot(dx, dy);
  if (d < 1) return;
  const nx = -dy / d;
  const ny = dx / d;
  const steps = Math.max(3, Math.min(9, Math.round(d / 14)));
  ctx.beginPath();
  ctx.moveTo(x1, y1);
  for (let i = 1; i < steps; i++) {
    const f = i / steps;
    const off = (Math.random() - 0.5) * d * 0.22 * Math.sin(Math.PI * f);
    ctx.lineTo(x1 + dx * f + nx * off, y1 + dy * f + ny * off);
  }
  ctx.lineTo(x2, y2);
  const op = ctx.globalCompositeOperation;
  const ga = ctx.globalAlpha;
  ctx.globalCompositeOperation = 'lighter';
  ctx.lineJoin = 'round';
  ctx.lineCap = 'round';
  ctx.globalAlpha = ga * alpha * 0.55;
  ctx.strokeStyle = color;
  ctx.lineWidth = width * 3;
  ctx.stroke();
  ctx.globalAlpha = ga * alpha;
  ctx.strokeStyle = '#ffffff';
  ctx.lineWidth = Math.max(1, width);
  ctx.stroke();
  ctx.globalAlpha = ga;
  ctx.globalCompositeOperation = op;
}

/** The current shake offset in tiles. */
export function shakeOffset(): [number, number] {
  return [shakeX, shakeY];
}

/** The full-field flash still showing, if any. */
export function flashNow(): { color: string; alpha: number } | null {
  return flashAlpha > 0.01 ? { color: flashColor, alpha: flashAlpha } : null;
}

export function draw(v: View, space: Space, font: string): void {
  const ctx = v.ctx;
  const u = v.unit;
  ctx.save();
  ctx.lineCap = 'round';
  for (const p of particles) {
    if (p.space !== space || p.delay > 0) continue;
    const a = Math.max(0, Math.min(1, p.life / p.max));
    const x = v.ox + p.x * u;
    const y = v.oy + p.y * u;
    switch (p.kind) {
      case SPARK: {
        ctx.globalCompositeOperation = 'lighter';
        ctx.globalAlpha = a;
        ctx.strokeStyle = p.color;
        ctx.lineWidth = Math.max(1, p.size * u * (0.4 + 0.6 * a));
        const tail = 0.045 * u;
        ctx.beginPath();
        ctx.moveTo(x, y);
        ctx.lineTo(x - p.vx * tail - 0.01, y - p.vy * tail);
        ctx.stroke();
        break;
      }
      case GLOW:
        ctx.globalAlpha = 1;
        light(ctx, x, y, p.size * u * (0.5 + 0.9 * (1 - a)), p.color, a * a);
        break;
      case SHARD: {
        ctx.globalCompositeOperation = 'source-over';
        ctx.globalAlpha = Math.min(1, a * 1.6);
        ctx.fillStyle = p.color;
        const s = Math.max(1.2, p.size * u);
        const c = Math.cos(p.rot);
        const sn = Math.sin(p.rot);
        ctx.beginPath();
        ctx.moveTo(x + c * s, y + sn * s);
        ctx.lineTo(x - c * s * 0.6 - sn * s * 0.7, y - sn * s * 0.6 + c * s * 0.7);
        ctx.lineTo(x - c * s * 0.6 + sn * s * 0.5, y - sn * s * 0.6 - c * s * 0.5);
        ctx.closePath();
        ctx.fill();
        break;
      }
      case RING: {
        const e = 1 - a * a * a;
        ctx.globalCompositeOperation = 'lighter';
        ctx.globalAlpha = a;
        ctx.strokeStyle = p.color;
        ctx.lineWidth = Math.max(1, p.tx * u * a);
        ctx.beginPath();
        ctx.arc(x, y, Math.max(0.5, (p.size + (p.r1 - p.size) * e) * u), 0, Math.PI * 2);
        ctx.stroke();
        break;
      }
      case TEXT: {
        ctx.globalCompositeOperation = 'source-over';
        ctx.globalAlpha = Math.min(1, a * 2.2);
        // Pops in large, then settles.
        const pop = 1 + 0.6 * Math.max(0, (a - 0.82) / 0.18);
        ctx.font = `800 ${p.size * u * pop}px ${font}`;
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.lineWidth = 3;
        ctx.strokeStyle = '#000';
        ctx.strokeText(p.text as string, x, y);
        ctx.fillStyle = p.color;
        ctx.fillText(p.text as string, x, y);
        break;
      }
      case MOTE: {
        ctx.globalCompositeOperation = 'lighter';
        ctx.globalAlpha = 0.7;
        ctx.strokeStyle = p.color;
        ctx.lineWidth = Math.max(1, p.size * u * 0.45);
        ctx.beginPath();
        ctx.moveTo(x, y);
        ctx.lineTo(x - p.vx * 0.05 * u, y - p.vy * 0.05 * u);
        ctx.stroke();
        ctx.globalAlpha = 1;
        light(ctx, x, y, p.size * u * 1.6, p.color, 0.95);
        break;
      }
      case BOLT:
        ctx.globalAlpha = 1;
        lightning(ctx, x, y, v.ox + p.tx * u, v.oy + p.ty * u, p.color, Math.max(1, p.size * u), a);
        break;
      case BUBBLE: {
        ctx.globalCompositeOperation = 'source-over';
        ctx.globalAlpha = a * 0.85;
        ctx.strokeStyle = p.color;
        ctx.lineWidth = 1;
        ctx.beginPath();
        ctx.arc(x, y, Math.max(1, p.size * u * (0.5 + 0.7 * (1 - a))), 0, Math.PI * 2);
        ctx.stroke();
        break;
      }
      case STAR:
        ctx.globalAlpha = 1;
        glint(ctx, x, y, p.size * u, 1 - a, p.color, p.rot);
        break;
    }
  }
  ctx.restore();
}