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/game/garage.ts
import * as THREE from 'three';
import { RoomEnvironment } from 'three/examples/jsm/environments/RoomEnvironment.js';
import type { Car } from './car.js';

/**
 * The paint shop's studio: the player's car on a turntable under soft lights, away from
 * the town (it's moved in while the shop is open, and back after), with an orbiting
 * camera and picking for the brush.
 */

/** Where a pick landed, in the car body's frame. */
export interface Pick {
  point: THREE.Vector3;
  normal: THREE.Vector3;
  /** On the paint (not the glass, the wheels, the lights or the trim). */
  paint: boolean;
  /** Off the paint: the colour of the part it's on (sRGB). */
  color?: number;
}

export const GARAGE_VIEWS = {
  front: [0, 0.18],
  back: [Math.PI, 0.18],
  left: [Math.PI / 2, 0.12],
  right: [-Math.PI / 2, 0.12],
  top: [0.0001, 1.45],
} as const;
export type GarageView = keyof typeof GARAGE_VIEWS;

export class Garage {
  readonly scene = new THREE.Scene();
  readonly camera = new THREE.PerspectiveCamera(40, 1, 0.1, 120);
  yaw = 0.75;
  pitch = 0.32;
  dist = 8;
  private aimYaw = this.yaw;
  private aimPitch = this.pitch;
  /** Zoomed in (under 1) or out from where the car just fits the open part of the view. */
  private aimZoom = 1;
  /** The part of the view not under the paint shop's panels (CSS px from the view's corner), where the car's framed. */
  private openArea: { x: number; y: number; w: number; h: number } | null = null;
  private readonly target = new THREE.Vector3(0, 0.72, 0);
  private readonly raycaster = new THREE.Raycaster();
  private saved: { parent: THREE.Object3D | null; pos: THREE.Vector3; quat: THREE.Quaternion } | null = null;
  private envMade = false;
  /** The outline round the selected shape, and the ring showing the brush where it'd paint (both in the body's frame). */
  private readonly marker: THREE.LineLoop;
  private readonly cursor: THREE.Mesh;
  /** The same, mirrored down the middle of the car (when the shop's mirroring). */
  private readonly markerTwin: THREE.LineLoop;
  private readonly cursorTwin: THREE.Mesh;
  private readonly markerAt = new THREE.Matrix4();
  private readonly cursorAt = new THREE.Matrix4();
  private body: THREE.Object3D | null = null;

  constructor() {
    this.scene.background = new THREE.Color(0x1f2438);
    this.scene.fog = new THREE.Fog(0x1f2438, 14, 40);
    const floor = new THREE.Mesh(new THREE.CircleGeometry(5.2, 64), new THREE.MeshStandardMaterial({ color: 0x2c3350, roughness: 0.85 }));
    floor.rotation.x = -Math.PI / 2;
    floor.receiveShadow = true;
    this.scene.add(floor);
    const ring = new THREE.Mesh(new THREE.RingGeometry(5.2, 5.35, 64), new THREE.MeshBasicMaterial({ color: 0xffc93c }));
    ring.rotation.x = -Math.PI / 2;
    ring.position.y = 0.002;
    this.scene.add(ring);
    this.scene.add(new THREE.HemisphereLight(0xeef2ff, 0x3a3550, 1.1));
    const key = new THREE.DirectionalLight(0xfff4e4, 2.4);
    key.position.set(4, 8, 5);
    key.castShadow = true;
    key.shadow.mapSize.set(1024, 1024);
    const sc = key.shadow.camera;
    sc.left = sc.bottom = -3.5;
    sc.right = sc.top = 3.5;
    sc.near = 1;
    sc.far = 20;
    key.shadow.bias = -0.0005;
    this.scene.add(key);
    const rim = new THREE.DirectionalLight(0xbcd2ff, 0.9);
    rim.position.set(-6, 4, -5);
    this.scene.add(rim);
    const outline = new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(-0.5, -0.5, 0), new THREE.Vector3(0.5, -0.5, 0), new THREE.Vector3(0.5, 0.5, 0), new THREE.Vector3(-0.5, 0.5, 0)]);
    this.marker = new THREE.LineLoop(outline, new THREE.LineBasicMaterial({ color: 0xffc93c, depthTest: false, transparent: true }));
    this.cursor = new THREE.Mesh(new THREE.RingGeometry(0.93, 1, 48), new THREE.MeshBasicMaterial({ color: 0xffffff, depthTest: false, transparent: true, opacity: 0.85, side: THREE.DoubleSide }));
    this.markerTwin = this.marker.clone();
    this.cursorTwin = this.cursor.clone();
    for (const o of [this.marker, this.cursor, this.markerTwin, this.cursorTwin]) {
      o.matrixAutoUpdate = false;
      o.visible = false;
      o.renderOrder = 10;
      this.scene.add(o);
    }
  }

  /** Outline a shape (its centre, axes across, along and out, and size), or nothing; twin: its mirror image too. */
  mark(at: { c: THREE.Vector3; u: THREE.Vector3; v: THREE.Vector3; n: THREE.Vector3; w: number; l: number } | null, twin = false): void {
    this.marker.visible = !!at;
    this.markerTwin.visible = !!at && twin;
    if (at) this.markerAt.makeBasis(at.u.clone().multiplyScalar(at.w), at.v.clone().multiplyScalar(at.l), at.n).setPosition(at.c.clone().addScaledVector(at.n, 0.01));
  }

  /** Show the brush (radius r, m) on the body at point p facing n, or hide it; twin: where its mirror image paints too. */
  brush(p: THREE.Vector3 | null, n?: THREE.Vector3, r = 0, twin = false): void {
    this.cursor.visible = !!p;
    this.cursorTwin.visible = !!p && twin;
    if (!p || !n) return;
    const q = new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 0, 1), n);
    this.cursorAt.compose(p.clone().addScaledVector(n, 0.004), q, new THREE.Vector3(r, r, r));
  }

  /** Bring the car in (on the turntable, facing forward). */
  open(car: Car, renderer: THREE.WebGLRenderer): void {
    if (!this.envMade) {
      // Soft studio reflections in the paint and glass.
      const pm = new THREE.PMREMGenerator(renderer);
      this.scene.environment = pm.fromScene(new RoomEnvironment(), 0.04).texture;
      this.scene.environmentIntensity = 0.55;
      pm.dispose();
      this.envMade = true;
    }
    const r = car.root;
    this.saved = { parent: r.parent, pos: r.position.clone(), quat: r.quaternion.clone() };
    r.position.set(0, 0, 0);
    r.quaternion.identity();
    this.scene.add(r);
    this.body = car.body;
  }

  /** Put the car back where it was. */
  close(car: Car): void {
    const s = this.saved;
    if (!s) return;
    const r = car.root;
    r.position.copy(s.pos);
    r.quaternion.copy(s.quat);
    if (s.parent) s.parent.add(r);
    else r.removeFromParent();
    this.saved = null;
    this.body = null;
    this.mark(null);
    this.brush(null);
    this.markerTwin.visible = this.cursorTwin.visible = false;
  }

  orbit(dx: number, dy: number): void {
    this.aimYaw -= dx * 0.008;
    this.aimPitch = Math.max(-0.05, Math.min(1.5, this.aimPitch + dy * 0.006));
  }

  zoom(f: number): void {
    this.aimZoom = Math.max(0.4, Math.min(2, this.aimZoom * f));
  }

  /** Frame the car in this part of the view (CSS px), or the whole of it (null). */
  frame(open: { x: number; y: number; w: number; h: number } | null): void {
    this.openArea = open;
  }

  view(v: GarageView): void {
    const [yaw, pitch] = GARAGE_VIEWS[v];
    // The short way round.
    this.aimYaw = this.aimYaw + Math.atan2(Math.sin(yaw - this.aimYaw), Math.cos(yaw - this.aimYaw));
    this.aimPitch = pitch;
    this.aimZoom = 1;
  }

  render(renderer: THREE.WebGLRenderer, dt: number): void {
    const k = 1 - Math.exp(-12 * dt);
    this.yaw += (this.aimYaw - this.yaw) * k;
    this.pitch += (this.aimPitch - this.pitch) * k;
    const size = renderer.getSize(new THREE.Vector2());
    const W = Math.max(1, size.x);
    const H = Math.max(1, size.y);
    const o = this.openArea && this.openArea.w > 40 && this.openArea.h > 40 ? this.openArea : { x: 0, y: 0, w: W, h: H };
    // The view centred on the open part (the rest is the same view, run on under the panels).
    const cam = this.camera;
    cam.aspect = W / H;
    cam.setViewOffset(W, H, W / 2 - (o.x + o.w / 2), H / 2 - (o.y + o.h / 2), W, H);
    // Back far enough for the car to fit it: its length across, and its height (or its length, from above) up and down.
    const t = Math.tan(THREE.MathUtils.degToRad(cam.fov / 2));
    const across = 2.6 / ((o.w / H) * t);
    const up = (1.5 + 1.1 * Math.sin(Math.max(0, this.pitch))) / ((o.h / H) * t);
    const want = Math.max(3.2, (Math.max(across, up) + 1.2) * this.aimZoom);
    this.dist += (want - this.dist) * k;
    const cp = Math.cos(this.pitch);
    this.camera.position.set(Math.sin(this.yaw) * cp, Math.sin(this.pitch), Math.cos(this.yaw) * cp).multiplyScalar(this.dist).add(this.target);
    this.camera.lookAt(this.target);
    if (this.body) {
      this.body.updateWorldMatrix(true, false);
      this.marker.matrix.multiplyMatrices(this.body.matrixWorld, this.markerAt);
      this.cursor.matrix.multiplyMatrices(this.body.matrixWorld, this.cursorAt);
      // (The mirror images: reflected across the body's middle, x to -x.)
      const flip = new THREE.Matrix4().makeScale(-1, 1, 1);
      this.markerTwin.matrix.copy(this.body.matrixWorld).multiply(flip).multiply(this.markerAt);
      this.cursorTwin.matrix.copy(this.body.matrixWorld).multiply(flip).multiply(this.cursorAt);
      for (const o of [this.marker, this.cursor, this.markerTwin, this.cursorTwin]) o.matrixWorld.copy(o.matrix);
    }
    renderer.setRenderTarget(null);
    renderer.shadowMap.needsUpdate = true;
    renderer.render(this.scene, this.camera);
  }

  /**
   * A picture of the car as it is now (for a saved design's thumbnail): w by h, from in
   * front and to its left, as a data URL. The view and the brush ring and outlines aren't touched.
   */
  snapshot(renderer: THREE.WebGLRenderer, w: number, h: number): string {
    const rt = new THREE.WebGLRenderTarget(w, h, { samples: 4 });
    // (Stored as sRGB, so the picture comes out as the screen shows it.)
    rt.texture.colorSpace = THREE.SRGBColorSpace;
    // (Close in on its left side, a little from the front: where most of a design shows.)
    const cam = new THREE.PerspectiveCamera(26, w / h, 0.1, 60);
    cam.position.set(6.1, 1.8, 2.9);
    cam.lookAt(0, 0.62, 0.05);
    const hidden = [this.marker, this.cursor, this.markerTwin, this.cursorTwin].filter((o) => o.visible);
    for (const o of hidden) o.visible = false;
    const target = renderer.getRenderTarget();
    renderer.setRenderTarget(rt);
    renderer.shadowMap.needsUpdate = true;
    renderer.render(this.scene, cam);
    const px = new Uint8Array(w * h * 4);
    renderer.readRenderTargetPixels(rt, 0, 0, w, h, px);
    renderer.setRenderTarget(target);
    for (const o of hidden) o.visible = true;
    rt.dispose();
    // (The render target's rows run bottom up.)
    const c = document.createElement('canvas');
    c.width = w;
    c.height = h;
    const g = c.getContext('2d')!;
    const img = g.createImageData(w, h);
    for (let y = 0; y < h; y++) img.data.set(px.subarray((h - 1 - y) * w * 4, (h - y) * w * 4), y * w * 4);
    g.putImageData(img, 0, 0);
    return c.toDataURL('image/png');
  }

  /** What's under a point of the view (-1 to 1 each way), on the car. */
  pick(car: Car, x: number, y: number): Pick | null {
    this.camera.updateMatrixWorld();
    this.raycaster.setFromCamera(new THREE.Vector2(x, y), this.camera);
    car.root.updateMatrixWorld(true);
    const hits = this.raycaster.intersectObject(car.root, true);
    const paint = new Set<THREE.Object3D>(car.paintMeshes);
    const seen = hits.filter((h) => h.face && shown(h.object));
    // A thin strip on the paint (a shut line, a handle, a vent): the paint under it, so a line goes on across it.
    const under = seen.findIndex((h) => paint.has(h.object));
    if (under > 0 && seen[under]!.distance - seen[0]!.distance < 0.025) seen.splice(0, under);
    const h = seen[0];
    if (!h) return null;
    const inv = new THREE.Matrix4().copy(car.body.matrixWorld).invert();
    const point = h.point.clone().applyMatrix4(inv);
    const nm = new THREE.Matrix3().getNormalMatrix(h.object.matrixWorld);
    const normal = h.face!.normal.clone().applyMatrix3(nm).transformDirection(inv).normalize();
    // (The face towards the camera.)
    if (normal.dot(this.raycaster.ray.direction.clone().transformDirection(inv)) > 0) normal.negate();
    const m = (h.object as THREE.Mesh).material;
    const mat = (Array.isArray(m) ? m[0] : m) as THREE.MeshStandardMaterial | undefined;
    return { point, normal, paint: paint.has(h.object), color: mat?.color ? mat.color.getHex() : undefined };
  }
}

function shown(o: THREE.Object3D | null): boolean {
  for (; o; o = o.parent) if (!o.visible) return false;
  return true;
}