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/route-editor.ts
import { HALF } from './game/world.js';
import type { RoadGraph } from './game/traffic.js';
import { RaceRoute, snapToRoad, type RoutePoint } from './game/race.js';

/**
 * The race planner: the map's roads, zoomable and draggable, with the race line drawn on
 * them from a start flag to a finish flag. Drag a flag (or a waypoint) to move it, or grab
 * the line anywhere to pull out a new waypoint there; when you let go it snaps onto the
 * nearest road and the line re-routes along the roads. Drag empty map to pan, scroll or
 * pinch to zoom; double-click (or long-press) a waypoint to take it out.
 */

const HIT = 16;
const MIN_ROUTE = 400;

interface View {
  /** World point at the middle of the canvas, and pixels per metre. */
  cx: number;
  cz: number;
  scale: number;
}

type Grab =
  | { kind: 'point'; index: number; x: number; z: number; moved: boolean }
  | { kind: 'pan'; sx: number; sy: number; cx: number; cz: number }
  | { kind: 'pinch'; d0: number; s0: number; mx: number; my: number; cx: number; cz: number };

export class RouteEditor {
  private way: RoutePoint[] = [];
  route: RaceRoute | null = null;
  loop = false;
  private view: View = { cx: 0, cz: 0, scale: 0.6 };
  private grab: Grab | null = null;
  private readonly pointers = new Map<number, { x: number; y: number }>();
  private graph: RoadGraph | null = null;
  private map: HTMLCanvasElement | null = null;
  private lastTap = { t: 0, index: -1 };
  private pressTimer = 0;
  /** Told when the route changes (to show its length, enable Start). */
  onChange: () => void = () => undefined;

  constructor(private readonly canvas: HTMLCanvasElement) {
    canvas.addEventListener('pointerdown', (e) => this.down(e));
    canvas.addEventListener('pointermove', (e) => this.move(e));
    canvas.addEventListener('pointerup', (e) => this.up(e));
    canvas.addEventListener('pointercancel', (e) => this.up(e));
    canvas.addEventListener('wheel', (e) => {
      e.preventDefault();
      const r = canvas.getBoundingClientRect();
      this.zoomAt(e.clientX - r.left, e.clientY - r.top, Math.exp(-e.deltaY * 0.0015));
    }, { passive: false });
    canvas.addEventListener('contextmenu', (e) => e.preventDefault());
    new ResizeObserver(() => this.draw()).observe(canvas);
  }

  /** Open the planner on a map: its roads, its picture, and the waypoints to start from. */
  open(graph: RoadGraph, map: HTMLCanvasElement, way: RoutePoint[], loop: boolean): void {
    this.graph = graph;
    this.map = map;
    this.way = way.map((p) => ({ ...p }));
    this.loop = loop;
    this.rebuild();
    this.fit();
  }

  get waypoints(): RoutePoint[] {
    return this.way.map((p) => ({ ...p }));
  }

  /** Long enough to race? */
  get valid(): boolean {
    return !!this.route && this.route.len >= MIN_ROUTE;
  }

  setLoop(loop: boolean): void {
    this.loop = loop;
    this.rebuild();
  }

  setWaypoints(way: RoutePoint[], fit = true): void {
    this.way = way.map((p) => ({ ...p }));
    this.rebuild();
    if (fit) this.fit();
  }

  /** Zoom in or out about the middle (the +/− buttons). */
  zoom(k: number): void {
    const r = this.canvas.getBoundingClientRect();
    this.zoomAt(r.width / 2, r.height / 2, k);
  }

  /** Frame the whole route. */
  fit(): void {
    const r = this.canvas.getBoundingClientRect();
    const pts = this.route?.pts ?? this.way;
    if (!pts.length || !r.width) return;
    let x0 = Infinity, x1 = -Infinity, z0 = Infinity, z1 = -Infinity;
    for (const p of pts) {
      x0 = Math.min(x0, p.x);
      x1 = Math.max(x1, p.x);
      z0 = Math.min(z0, p.z);
      z1 = Math.max(z1, p.z);
    }
    // Leave room for the panels over the map: the heading at the top, the bar at the bottom.
    const panel = (sel: string) => {
      const e = this.canvas.parentElement?.querySelector<HTMLElement>(sel);
      return e && e.offsetParent ? e.offsetHeight + 16 : 16;
    };
    const top = Math.max(panel('.planner-top'), 60);
    const bottom = panel('.planner-bar');
    const side = Math.min(64, r.width * 0.12);
    const w = Math.max(80, r.width - side * 2);
    const h = Math.max(80, r.height - top - bottom);
    this.view.scale = this.clampScale(Math.min(w / (x1 - x0 + 60), h / (z1 - z0 + 60)));
    this.view.cx = (x0 + x1) / 2;
    // Centre it in the space between the panels.
    this.view.cz = (z0 + z1) / 2 - (top - bottom) / 2 / this.view.scale;
    this.draw();
  }

  private clampScale(s: number): number {
    const r = this.canvas.getBoundingClientRect();
    // (Out far enough to see the whole map, whichever way it's longer.)
    const span = this.map ? Math.max(this.map.width, this.map.height) * 2 : HALF * 2;
    const min = Math.min(r.width, r.height) / (span * 1.1);
    return Math.max(min, Math.min(6, s));
  }

  private zoomAt(sx: number, sy: number, k: number): void {
    const before = this.toWorld(sx, sy);
    this.view.scale = this.clampScale(this.view.scale * k);
    const after = this.toWorld(sx, sy);
    this.view.cx += before.x - after.x;
    this.view.cz += before.z - after.z;
    this.draw();
  }

  private toWorld(sx: number, sy: number): { x: number; z: number } {
    const r = this.canvas.getBoundingClientRect();
    return { x: this.view.cx + (sx - r.width / 2) / this.view.scale, z: this.view.cz + (sy - r.height / 2) / this.view.scale };
  }

  private toScreen(x: number, z: number): { x: number; y: number } {
    const r = this.canvas.getBoundingClientRect();
    return { x: (x - this.view.cx) * this.view.scale + r.width / 2, y: (z - this.view.cz) * this.view.scale + r.height / 2 };
  }

  private rebuild(): void {
    this.route = this.graph ? RaceRoute.build(this.graph, this.way, this.loop) : null;
    this.draw();
    this.onChange();
  }

  // ---- Pointer handling ---------------------------------------------------------------

  private local(e: PointerEvent): { x: number; y: number } {
    const r = this.canvas.getBoundingClientRect();
    return { x: e.clientX - r.left, y: e.clientY - r.top };
  }

  private down(e: PointerEvent): void {
    this.canvas.setPointerCapture(e.pointerId);
    const p = this.local(e);
    this.pointers.set(e.pointerId, p);
    if (this.pointers.size === 2) {
      // Two fingers: pinch to zoom (and pan with them).
      const [a, b] = [...this.pointers.values()] as [{ x: number; y: number }, { x: number; y: number }];
      const m = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
      this.grab = { kind: 'pinch', d0: Math.hypot(a.x - b.x, a.y - b.y), s0: this.view.scale, mx: m.x, my: m.y, cx: this.view.cx, cz: this.view.cz };
      clearTimeout(this.pressTimer);
      return;
    }
    if (e.button === 2 || e.button === 1) {
      this.grab = { kind: 'pan', sx: p.x, sy: p.y, cx: this.view.cx, cz: this.view.cz };
      return;
    }
    // A waypoint under the pointer?
    const hit = this.pointAt(p.x, p.y);
    if (hit >= 0) {
      const w = this.way[hit]!;
      this.grab = { kind: 'point', index: hit, x: w.x, z: w.z, moved: false };
      // A double tap, or a long press, takes out a waypoint between the flags.
      const now = performance.now();
      if (this.lastTap.index === hit && now - this.lastTap.t < 350) this.remove(hit);
      this.lastTap = { t: now, index: hit };
      clearTimeout(this.pressTimer);
      this.pressTimer = window.setTimeout(() => {
        if (this.grab?.kind === 'point' && !this.grab.moved) this.remove(this.grab.index);
      }, 650);
      return;
    }
    // On the line: pull a new waypoint out of it.
    const leg = this.legAt(p.x, p.y);
    if (leg >= 0) {
      const w = this.toWorld(p.x, p.y);
      this.way.splice(leg + 1, 0, { x: w.x, z: w.z, edge: -1, t: 0 });
      this.grab = { kind: 'point', index: leg + 1, x: w.x, z: w.z, moved: true };
      this.draw();
      return;
    }
    this.grab = { kind: 'pan', sx: p.x, sy: p.y, cx: this.view.cx, cz: this.view.cz };
  }

  private move(e: PointerEvent): void {
    if (!this.pointers.has(e.pointerId)) {
      this.canvas.style.cursor = this.pointAt(this.local(e).x, this.local(e).y) >= 0 ? 'grab' : this.legAt(this.local(e).x, this.local(e).y) >= 0 ? 'copy' : 'default';
      return;
    }
    const p = this.local(e);
    this.pointers.set(e.pointerId, p);
    const g = this.grab;
    if (!g) return;
    if (g.kind === 'pinch' && this.pointers.size >= 2) {
      const [a, b] = [...this.pointers.values()] as [{ x: number; y: number }, { x: number; y: number }];
      const m = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
      this.view.scale = this.clampScale(g.s0 * (Math.hypot(a.x - b.x, a.y - b.y) / g.d0));
      // Keep the world point that was under the fingers' midpoint under it.
      const r = this.canvas.getBoundingClientRect();
      const wx = g.cx + (g.mx - r.width / 2) / g.s0;
      const wz = g.cz + (g.my - r.height / 2) / g.s0;
      this.view.cx = wx - (m.x - r.width / 2) / this.view.scale;
      this.view.cz = wz - (m.y - r.height / 2) / this.view.scale;
      this.draw();
    } else if (g.kind === 'pan') {
      this.view.cx = g.cx - (p.x - g.sx) / this.view.scale;
      this.view.cz = g.cz - (p.y - g.sy) / this.view.scale;
      this.draw();
    } else if (g.kind === 'point') {
      const w = this.toWorld(p.x, p.y);
      const pt = this.way[g.index]!;
      if (Math.hypot(w.x - pt.x, w.z - pt.z) * this.view.scale > 3) {
        g.moved = true;
        clearTimeout(this.pressTimer);
      }
      pt.x = w.x;
      pt.z = w.z;
      this.draw();
    }
  }

  private up(e: PointerEvent): void {
    this.pointers.delete(e.pointerId);
    clearTimeout(this.pressTimer);
    const g = this.grab;
    if (this.pointers.size > 0) {
      // A finger lifted from a pinch: carry on panning with the other.
      const [q] = [...this.pointers.values()] as [{ x: number; y: number }];
      this.grab = { kind: 'pan', sx: q.x, sy: q.y, cx: this.view.cx, cz: this.view.cz };
      return;
    }
    this.grab = null;
    if (g?.kind === 'point' && this.graph && this.way[g.index]) {
      // Let go: onto the nearest road, and the line re-routes.
      const pt = this.way[g.index]!;
      this.way[g.index] = snapToRoad(this.graph, pt.x, pt.z);
      this.rebuild();
    }
  }

  private remove(index: number): void {
    // The start and finish flags stay; waypoints between can go.
    if (index <= 0 || index >= this.way.length - 1) return;
    this.way.splice(index, 1);
    this.grab = null;
    this.rebuild();
  }

  /** The waypoint under a screen point (-1 if none), the flags winning over waypoints. */
  private pointAt(sx: number, sy: number): number {
    let best = -1;
    let bd = HIT;
    this.way.forEach((w, i) => {
      const p = this.toScreen(w.x, w.z);
      const d = Math.hypot(p.x - sx, p.y - sy) - (i === 0 || i === this.way.length - 1 ? 4 : 0);
      if (d < bd) {
        bd = d;
        best = i;
      }
    });
    return best;
  }

  /** Which leg of the route is under a screen point (-1 if none). */
  private legAt(sx: number, sy: number): number {
    const route = this.route;
    if (!route) return -1;
    let best = -1;
    let bd = 10;
    for (let i = 0; i + 1 < route.pts.length; i++) {
      const a = this.toScreen(route.pts[i]!.x, route.pts[i]!.z);
      const b = this.toScreen(route.pts[i + 1]!.x, route.pts[i + 1]!.z);
      const vx = b.x - a.x;
      const vy = b.y - a.y;
      const l2 = vx * vx + vy * vy || 1;
      const t = Math.max(0, Math.min(1, ((sx - a.x) * vx + (sy - a.y) * vy) / l2));
      const d = Math.hypot(sx - (a.x + vx * t), sy - (a.y + vy * t));
      if (d < bd) {
        bd = d;
        best = route.legOf[i]!;
      }
    }
    return best;
  }

  // ---- Drawing --------------------------------------------------------------------------

  draw(): void {
    const c = this.canvas;
    const r = c.getBoundingClientRect();
    if (!r.width || !r.height) return;
    const dpr = Math.min(2, window.devicePixelRatio || 1);
    if (c.width !== Math.round(r.width * dpr) || c.height !== Math.round(r.height * dpr)) {
      c.width = Math.round(r.width * dpr);
      c.height = Math.round(r.height * dpr);
    }
    const g = c.getContext('2d')!;
    g.setTransform(dpr, 0, 0, dpr, 0, 0);
    g.fillStyle = '#4f7a35';
    g.fillRect(0, 0, r.width, r.height);
    // The map picture: 2 m per pixel, its corner at (-HALF, -HALF).
    if (this.map) {
      const o = this.toScreen(-HALF, -HALF);
      g.imageSmoothingEnabled = this.view.scale < 1.2;
      g.drawImage(this.map, o.x, o.y, this.map.width * 2 * this.view.scale, this.map.height * 2 * this.view.scale);
    }
    const route = this.route;
    // The line along the roads: a dark edge, then the line, with arrows to show the way.
    if (route && route.pts.length > 1) {
      const path = () => {
        g.beginPath();
        route.pts.forEach((p, i) => {
          const s = this.toScreen(p.x, p.z);
          if (i === 0) g.moveTo(s.x, s.y);
          else g.lineTo(s.x, s.y);
        });
        if (route.loop) g.closePath();
      };
      g.lineJoin = 'round';
      g.lineCap = 'round';
      const w = Math.max(5, Math.min(14, this.view.scale * 7));
      path();
      g.strokeStyle = 'rgba(27,33,64,0.9)';
      g.lineWidth = w + 4;
      g.stroke();
      path();
      g.strokeStyle = this.valid ? '#ffc93c' : '#ff8a6a';
      g.lineWidth = w;
      g.stroke();
      // Arrows every so often along it.
      const every = Math.max(60, 90 / this.view.scale);
      const q = { x: 0, z: 0, tx: 0, tz: 1, hw: 4 };
      g.fillStyle = 'rgba(27,33,64,0.85)';
      for (let s = every / 2; s < route.len; s += every) {
        route.at(s, q);
        const p = this.toScreen(q.x, q.z);
        const a = Math.atan2(q.tz, q.tx);
        const k = w * 0.55;
        g.beginPath();
        g.moveTo(p.x + Math.cos(a) * k, p.y + Math.sin(a) * k);
        g.lineTo(p.x + Math.cos(a + 2.4) * k, p.y + Math.sin(a + 2.4) * k);
        g.lineTo(p.x + Math.cos(a - 2.4) * k, p.y + Math.sin(a - 2.4) * k);
        g.closePath();
        g.fill();
      }
    }
    // While a waypoint is being dragged: dashed lines from its neighbours to where it is.
    if (this.grab?.kind === 'point') {
      const i = this.grab.index;
      g.setLineDash([6, 6]);
      g.strokeStyle = '#fff7ea';
      g.lineWidth = 2;
      for (const j of [i - 1, i + 1]) {
        const k = this.loop ? (j + this.way.length) % this.way.length : j;
        const n = this.way[k];
        if (!n || k === i) continue;
        const a = this.toScreen(n.x, n.z);
        const b = this.toScreen(this.way[i]!.x, this.way[i]!.z);
        g.beginPath();
        g.moveTo(a.x, a.y);
        g.lineTo(b.x, b.y);
        g.stroke();
      }
      g.setLineDash([]);
    }
    // Waypoints, then the flags on top.
    const flag = (x: number, z: number, label: string, fill: string) => {
      const p = this.toScreen(x, z);
      g.beginPath();
      g.arc(p.x, p.y, 13, 0, Math.PI * 2);
      g.fillStyle = fill;
      g.fill();
      g.lineWidth = 3;
      g.strokeStyle = '#1b2140';
      g.stroke();
      g.fillStyle = '#1b2140';
      g.font = 'italic 900 13px "Arial Black", Impact, sans-serif';
      g.textAlign = 'center';
      g.textBaseline = 'middle';
      g.fillText(label, p.x, p.y + 1);
    };
    this.way.forEach((w, i) => {
      if (i === 0 || i === this.way.length - 1) return;
      const p = this.toScreen(w.x, w.z);
      g.beginPath();
      g.arc(p.x, p.y, 8, 0, Math.PI * 2);
      g.fillStyle = '#fff7ea';
      g.fill();
      g.lineWidth = 3;
      g.strokeStyle = '#1b2140';
      g.stroke();
    });
    const last = this.way[this.way.length - 1];
    if (last && !this.loop) flag(last.x, last.z, 'F', '#fff7ea');
    else if (last && this.way.length > 1) {
      const p = this.toScreen(last.x, last.z);
      g.beginPath();
      g.arc(p.x, p.y, 8, 0, Math.PI * 2);
      g.fillStyle = '#fff7ea';
      g.fill();
      g.lineWidth = 3;
      g.strokeStyle = '#1b2140';
      g.stroke();
    }
    const first = this.way[0];
    if (first) flag(first.x, first.z, this.loop ? 'S/F' : 'S', '#2fc9a0');
  }
}