Back to Drift City
SOURCE / PINNED RELEASE

Made of little things.

Drift City

Release
098731aa0f0f…
Author-recorded commit
2822ea0a4f5b…
License
LICENSE
Author’s source reference
nostr://npub12lm3rxsva8kfempyjkxupt09e02n3fezurkyadyqfejdc5e0r2kscqty6r/wss%3A%2F%2Fgit.napplet.soy%2F/n-a4c0039c855

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

src/hud.ts
import type { Car } from './game/car.js';
import { CAR_SPEED } from './game/car.js';
import type { DriftState } from './game/game.js';
import { HALF } from './game/world.js';
import { raceTime, type RaceInfo, type RaceRoute } from './game/race.js';

function el<T extends HTMLElement>(selector: string): T {
  const found = document.querySelector<T>(selector);
  if (!found) throw new Error(`Missing element ${selector}`);
  return found;
}

const fmt = new Intl.NumberFormat('en-US');

/** The drift score, speedometer, minimap and score pop-ups over the game. */
export class Hud {
  private readonly root = el<HTMLElement>('#hud');
  private readonly drift = el<HTMLElement>('#drift');
  private readonly pts = el<HTMLElement>('#pts');
  private readonly mult = el<HTMLElement>('#mult');
  private readonly multBar = el<HTMLElement>('#multBar');
  private readonly angle = el<HTMLElement>('#angle');
  private readonly total = el<HTMLElement>('#total');
  private readonly best = el<HTMLElement>('#best');
  private readonly speed = el<HTMLElement>('#speed');
  private readonly unit = el<HTMLElement>('#unit');
  private readonly speedBar = el<HTMLElement>('#speedBar');
  private readonly popups = el<HTMLElement>('#popups');
  private readonly minimap = el<HTMLCanvasElement>('#minimap');
  private readonly mapCtx = this.minimap.getContext('2d')!;
  private readonly raceHud = el<HTMLElement>('#raceHud');
  private readonly racePos = el<HTMLElement>('#racePos');
  private readonly raceOf = el<HTMLElement>('#raceOf');
  private readonly raceLap = el<HTMLElement>('#raceLap');
  private readonly raceTimeEl = el<HTMLElement>('#raceTime');
  private readonly raceNote = el<HTMLElement>('#raceNote');
  private readonly countdownEl = el<HTMLElement>('#countdown');
  private route: RaceRoute | null = null;
  /** Other cars to mark on the minimap (race rivals): where, which way, what paint. */
  private others: { x: number; z: number; yaw: number; color: string }[] = [];
  private countdownTimer = 0;
  private mph = false;
  private shown = { pts: -1, mult: -1, total: -1, best: -1, speed: -1 };

  constructor(private map: HTMLCanvasElement) {}

  /** Show another map's picture in the minimap. */
  setMap(map: HTMLCanvasElement): void {
    this.map = map;
  }

  /** The race route to draw on the minimap (null: none). */
  setRoute(route: RaceRoute | null): void {
    this.route = route;
  }

  /** The race rivals to show on the minimap (none outside a race). */
  setOthers(others: { x: number; z: number; yaw: number; color: string }[]): void {
    this.others = others;
  }

  /** The race panel: position, lap and clock (hidden with no race on). */
  updateRace(info: RaceInfo | null): void {
    this.raceHud.hidden = !info;
    this.raceNote.hidden = !info?.offRoute;
    if (!info) return;
    this.racePos.textContent = String(info.position);
    this.raceOf.textContent = `/${info.of}`;
    this.raceLap.textContent = info.laps > 1 ? `Lap ${info.lap}/${info.laps}` : `${(info.toGo / 1000).toFixed(1)} km to go`;
    this.raceTimeEl.textContent = raceTime(info.time);
  }

  /** A big word in the middle of the screen for a moment: 3, 2, 1, GO. */
  bigText(text: string, ms = 900): void {
    clearTimeout(this.countdownTimer);
    const c = this.countdownEl;
    c.hidden = false;
    c.textContent = text;
    c.classList.remove('pop');
    void c.offsetWidth;
    c.classList.add('pop');
    this.countdownTimer = window.setTimeout(() => (c.hidden = true), ms);
  }

  set visible(v: boolean) {
    this.root.hidden = !v;
  }

  setMph(v: boolean): void {
    this.mph = v;
    this.unit.textContent = v ? 'mph' : 'km/h';
    this.shown.speed = -1;
  }

  update(st: DriftState, car: Car): void {
    const pts = Math.round(st.points);
    if (pts !== this.shown.pts) this.pts.textContent = fmt.format((this.shown.pts = pts));
    if (st.mult !== this.shown.mult) this.mult.textContent = `×${(this.shown.mult = st.mult)}`;
    this.multBar.style.transform = `scaleX(${st.points > 0 ? st.multProgress : 0})`;
    this.drift.classList.toggle('live', st.points > 0);
    this.drift.classList.toggle('sliding', st.drifting || st.air > 0.15);
    // The meter drains while the drift is waiting to be banked.
    this.drift.style.setProperty('--grace', String(st.grace / 1.4));
    this.angle.textContent = st.air > 0.15 ? `AIR ${st.air.toFixed(1)}s` : st.drifting ? `${Math.round((st.angle * 180) / Math.PI)}°` : '';
    if (st.total !== this.shown.total) this.total.textContent = fmt.format((this.shown.total = st.total));
    if (st.best !== this.shown.best) this.best.textContent = fmt.format((this.shown.best = st.best));
    const speed = Math.round(st.speed * (this.mph ? 2.237 : 3.6));
    if (speed !== this.shown.speed) this.speed.textContent = String((this.shown.speed = speed));
    this.speedBar.style.transform = `scaleX(${Math.min(1, st.speed / CAR_SPEED)})`;
    if (this.minimap.offsetParent) this.drawMap(car);
  }

  /** A floating score message in the middle of the screen. */
  popup(text: string, kind: 'bank' | 'best' | 'lost' | 'smash'): void {
    const p = document.createElement('div');
    p.className = `popup popup-${kind}`;
    p.textContent = text;
    this.popups.append(p);
    while (this.popups.children.length > 3) this.popups.firstElementChild?.remove();
    p.addEventListener('animationend', () => p.remove());
  }

  private drawMap(car: Car): void {
    const c = this.minimap;
    const css = c.clientWidth;
    const dpr = Math.min(2, window.devicePixelRatio || 1);
    const size = Math.round(css * dpr);
    if (c.width !== size) c.width = c.height = size;
    const g = this.mapCtx;
    const r = size / 2;
    // 260 m from the car to the rim; the map picture is 2 m per pixel.
    const scale = r / 130;
    g.clearRect(0, 0, size, size);
    g.save();
    g.beginPath();
    g.arc(r, r, r - 1, 0, Math.PI * 2);
    g.clip();
    g.fillStyle = '#5d8a3c';
    g.fillRect(0, 0, size, size);
    g.translate(r, r);
    // Heading points up the minimap.
    g.rotate(-Math.PI / 2 - Math.atan2(Math.cos(car.yaw), Math.sin(car.yaw)));
    g.scale(scale, scale);
    g.drawImage(this.map, -(car.pos.x + HALF) / 2, -(car.pos.z + HALF) / 2);
    if (this.route) {
      // The race route over the roads, in the map picture's pixels (2 m each).
      g.beginPath();
      this.route.pts.forEach((p, i) => {
        const x = (p.x - car.pos.x) / 2;
        const y = (p.z - car.pos.z) / 2;
        if (i === 0) g.moveTo(x, y);
        else g.lineTo(x, y);
      });
      if (this.route.loop) g.closePath();
      g.lineJoin = 'round';
      g.lineCap = 'round';
      g.strokeStyle = 'rgba(27,33,64,0.85)';
      g.lineWidth = 9 / scale;
      g.stroke();
      g.strokeStyle = '#ffc93c';
      g.lineWidth = 5 / scale;
      g.stroke();
    }
    g.restore();
    // The rivals: arrows in their paint, pointing the way they're heading; off the edge
    // of the map, pinned to its rim so you can see which way they are.
    const turn = -Math.PI / 2 - Math.atan2(Math.cos(car.yaw), Math.sin(car.yaw));
    const cos = Math.cos(turn);
    const sin = Math.sin(turn);
    for (const o of this.others) {
      const dx = ((o.x - car.pos.x) / 2) * scale;
      const dz = ((o.z - car.pos.z) / 2) * scale;
      let x = dx * cos - dz * sin;
      let y = dx * sin + dz * cos;
      const d = Math.hypot(x, y);
      const rim = r - 7 * dpr;
      const out = d > rim;
      if (out) {
        x *= rim / d;
        y *= rim / d;
      }
      const hx = Math.sin(o.yaw) * cos - Math.cos(o.yaw) * sin;
      const hy = Math.sin(o.yaw) * sin + Math.cos(o.yaw) * cos;
      const a = Math.atan2(hy, hx);
      const k = (out ? 4.5 : 6) * dpr;
      g.save();
      g.translate(r + x, r + y);
      g.rotate(a + Math.PI / 2);
      g.globalAlpha = out ? 0.75 : 1;
      g.fillStyle = o.color;
      g.strokeStyle = '#1b2140';
      g.lineWidth = 1.5 * dpr;
      g.beginPath();
      g.moveTo(0, -1.4 * k);
      g.lineTo(k, 1.2 * k);
      g.lineTo(0, 0.6 * k);
      g.lineTo(-k, 1.2 * k);
      g.closePath();
      g.fill();
      g.stroke();
      g.restore();
    }
    // The car.
    g.fillStyle = '#ff4f5e';
    g.strokeStyle = '#ffffff';
    g.lineWidth = 1.5 * dpr;
    g.beginPath();
    g.moveTo(r, r - 7 * dpr);
    g.lineTo(r + 5 * dpr, r + 6 * dpr);
    g.lineTo(r, r + 3 * dpr);
    g.lineTo(r - 5 * dpr, r + 6 * dpr);
    g.closePath();
    g.fill();
    g.stroke();
  }
}

export { fmt };