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/paint-designs.ts
import { storage } from '@napplet/sdk';
import { SHAPES, type PaintOp, type Shape, type ShapeKind, type Stroke } from './game/car-paint.js';
import type { Online } from './online.js';

/**
 * Saved car designs: each its base colour and the list of marks painted on it (strokes
 * and shapes, so it stays editable), kept in the napplet's storage under the account.
 *
 * Packed small: the stroke points in millimetres (and their normals in ten-thousandths)
 * as 16-bit numbers, each point a step from the last, then the lot deflated and in
 * base64. Storage holds 512 KB for the whole game, so the paint shop shows how much
 * is used.
 */

export interface Design {
  id: string;
  name: string;
  /** sRGB. */
  base: number;
  ops: PaintOp[];
}

export interface DesignInfo {
  id: string;
  name: string;
  base: number;
  /** Stored size, bytes. */
  bytes: number;
}

/** The napplet's storage, bytes. */
export const STORAGE_BUDGET = 512 * 1024;
const MAX_OPS = 4000;

const enc = new TextEncoder();
const byteSize = (s: string) => enc.encode(s).length;

function toBase64(bytes: Uint8Array): string {
  let s = '';
  for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
  return btoa(s);
}

function fromBase64(s: string): Uint8Array {
  const bin = atob(s);
  const out = new Uint8Array(bin.length);
  for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
  return out;
}

async function pipe(bytes: Uint8Array, stream: CompressionStream | DecompressionStream): Promise<Uint8Array> {
  const out = new Response(new Blob([bytes as BlobPart]).stream().pipeThrough(stream));
  return new Uint8Array(await out.arrayBuffer());
}

/** A stroke's points: millimetres and ten-thousandths, each point's position as a step from the last. */
function packPoints(pts: number[]): string {
  const q = new Int16Array(pts.length);
  let px = 0;
  let py = 0;
  let pz = 0;
  for (let i = 0; i < pts.length; i += 6) {
    const x = Math.round(pts[i]! * 1000);
    const y = Math.round(pts[i + 1]! * 1000);
    const z = Math.round(pts[i + 2]! * 1000);
    q[i] = x - px;
    q[i + 1] = y - py;
    q[i + 2] = z - pz;
    [px, py, pz] = [x, y, z];
    for (let k = 3; k < 6; k++) q[i + k] = Math.round(Math.max(-1, Math.min(1, pts[i + k]!)) * 10000);
  }
  return toBase64(new Uint8Array(q.buffer));
}

function unpackPoints(s: string): number[] {
  const b = fromBase64(s);
  const q = new Int16Array(b.buffer, b.byteOffset, Math.floor(b.length / 2));
  const pts: number[] = [];
  let x = 0;
  let y = 0;
  let z = 0;
  for (let i = 0; i + 5 < q.length; i += 6) {
    x += q[i]!;
    y += q[i + 1]!;
    z += q[i + 2]!;
    pts.push(x / 1000, y / 1000, z / 1000, q[i + 3]! / 10000, q[i + 4]! / 10000, q[i + 5]! / 10000);
  }
  return pts;
}

/** Points as stored (rounded to the millimetre), so a stroke painted live matches it replayed. */
export function roundPoint(p: number[]): number[] {
  return p.map((v, i) => (i < 3 ? Math.round(v * 1000) / 1000 : Math.round(v * 10000) / 10000));
}

const num = (v: unknown, lo: number, hi: number, fallback: number) => (typeof v === 'number' && Number.isFinite(v) ? Math.max(lo, Math.min(hi, v)) : fallback);
const colour = (v: unknown) => (Number.isInteger(v) ? (v as number) & 0xffffff : 0xffffff);
const vec = (v: unknown): [number, number, number] | null => (Array.isArray(v) && v.length === 3 && v.every((x) => typeof x === 'number' && Number.isFinite(x) && Math.abs(x) < 10) ? (v as [number, number, number]) : null);

/** A design from its stored form, every value checked (it could be from an older version, or damaged). */
function parseDesign(raw: unknown): Design | null {
  const d = raw as { id?: unknown; name?: unknown; base?: unknown; ops?: unknown };
  if (!d || typeof d.id !== 'string' || !Array.isArray(d.ops)) return null;
  const ops: PaintOp[] = [];
  for (const o of d.ops.slice(0, MAX_OPS) as Record<string, unknown>[]) {
    if (o?.t === 'stroke' && typeof o.p === 'string') {
      const pts = unpackPoints(o.p);
      if (pts.length === 0) continue;
      ops.push({ t: 'stroke', color: colour(o.c), opacity: num(o.a, 0, 1, 1), size: num(o.r, 0.002, 1, 0.03), hard: num(o.h, 0, 1, 0.8), erase: o.e === 1, pts, ...(o.m === 1 ? { mirror: true } : {}) } satisfies Stroke);
    } else if (o?.t === 'shape' && SHAPES.includes(o.k as ShapeKind)) {
      const c = vec(o.at);
      const n = vec(o.n);
      if (!c || !n) continue;
      ops.push({ t: 'shape', kind: o.k as ShapeKind, color: colour(o.c), opacity: num(o.a, 0, 1, 1), w: num(o.w, 0.01, 5, 0.3), l: num(o.l, 0.01, 5, 0.3), rot: num(o.rot, -10, 10, 0), c, n, ...(o.m === 1 ? { mirror: true } : {}) } satisfies Shape);
    }
  }
  return { id: d.id.slice(0, 40), name: cleanTitle(typeof d.name === 'string' ? d.name : '') || 'Design', base: colour(d.base), ops };
}

function designJson(d: Design): string {
  const r3 = (v: number) => Math.round(v * 1000) / 1000;
  return JSON.stringify({
    v: 1,
    id: d.id,
    name: d.name,
    base: d.base,
    ops: d.ops.map((o) =>
      o.t === 'stroke'
        ? { t: 'stroke', c: o.color, a: r3(o.opacity), r: r3(o.size), h: r3(o.hard), e: o.erase ? 1 : 0, p: packPoints(o.pts), ...(o.mirror ? { m: 1 } : {}) }
        : { t: 'shape', k: o.kind, c: o.color, a: r3(o.opacity), w: r3(o.w), l: r3(o.l), rot: r3(o.rot), at: o.c.map(r3), n: o.n.map((v) => Math.round(v * 10000) / 10000), ...(o.mirror ? { m: 1 } : {}) },
    ),
  });
}

/** A design packed for storage: 'z1:' and deflated base64, or 'j1:' and plain JSON where the browser can't deflate. */
export async function packDesign(d: Design): Promise<string> {
  const json = designJson(d);
  if (typeof CompressionStream === 'undefined') return 'j1:' + json;
  return 'z1:' + toBase64(await pipe(enc.encode(json), new CompressionStream('deflate-raw')));
}

export async function unpackDesign(s: string): Promise<Design | null> {
  try {
    if (s.startsWith('j1:')) return parseDesign(JSON.parse(s.slice(3)));
    if (s.startsWith('z1:') && typeof DecompressionStream !== 'undefined') return parseDesign(JSON.parse(new TextDecoder().decode(await pipe(fromBase64(s.slice(3)), new DecompressionStream('deflate-raw')))));
  } catch {
    // Damaged: treated as missing.
  }
  return null;
}

export function cleanTitle(s: string): string {
  // eslint-disable-next-line no-control-regex
  return s.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 32);
}

export class Designs {
  /** Storage is there: designs can be kept. */
  readonly canSave: boolean;

  constructor(
    private readonly online: Online,
    canStore: boolean,
  ) {
    this.canSave = canStore;
  }

  private get indexKey(): string {
    return this.online.key('designs');
  }

  private designKey(id: string): string {
    return `design:${this.online.account.id}:${id}`;
  }

  /** This account's designs, newest first. */
  async list(): Promise<DesignInfo[]> {
    if (!this.canSave) return [];
    try {
      const v = JSON.parse((await storage.getItem(this.indexKey)) ?? '[]') as DesignInfo[];
      return Array.isArray(v) ? v.filter((d) => d && typeof d.id === 'string').map((d) => ({ id: d.id, name: cleanTitle(String(d.name ?? '')) || 'Design', base: colour(d.base), bytes: num(d.bytes, 0, STORAGE_BUDGET * 4, 0) })) : [];
    } catch {
      return [];
    }
  }

  async load(id: string): Promise<Design | null> {
    if (!this.canSave) return null;
    const s = await storage.getItem(this.designKey(id)).catch(() => null);
    return s ? unpackDesign(s) : null;
  }

  /**
   * Keep a design (a new one, or over its old self). Fails, saving nothing, if it would
   * take the game's storage past its budget. Returns its stored size.
   */
  async save(d: Design): Promise<number> {
    if (!this.canSave) throw new Error('Saving needs a host with storage.');
    const packed = await packDesign(d);
    const key = this.designKey(d.id);
    const old = await storage.getItem(key).catch(() => null);
    const bytes = byteSize(key) + byteSize(packed);
    const used = await this.used();
    if (used - (old ? byteSize(key) + byteSize(old) : 0) + bytes + 200 > STORAGE_BUDGET) throw new Error('Not enough room: delete a design, or rub out some detail.');
    await storage.setItem(key, packed);
    const list = (await this.list()).filter((x) => x.id !== d.id);
    list.unshift({ id: d.id, name: d.name, base: d.base, bytes });
    await storage.setItem(this.indexKey, JSON.stringify(list));
    return bytes;
  }

  async remove(id: string): Promise<void> {
    if (!this.canSave) return;
    await storage.removeItem(this.designKey(id)).catch(() => undefined);
    const list = (await this.list()).filter((x) => x.id !== id);
    await storage.setItem(this.indexKey, JSON.stringify(list)).catch(() => undefined);
    if ((await this.appliedId()) === id) await this.apply(null);
  }

  /** The design on this account's car (its id), or null for plain paint. */
  async appliedId(): Promise<string | null> {
    if (!this.canSave) return null;
    return (await storage.getItem(this.online.key('livery')).catch(() => null)) || null;
  }

  async apply(id: string | null): Promise<void> {
    if (!this.canSave) return;
    if (id) await storage.setItem(this.online.key('livery'), id).catch(() => undefined);
    else await storage.removeItem(this.online.key('livery')).catch(() => undefined);
  }

  /** Everything the game keeps in storage, bytes (every account's, settings and all). */
  async used(): Promise<number> {
    if (!this.canSave) return 0;
    try {
      const keys = await storage.keys();
      const values = await Promise.all(keys.map((k) => storage.getItem(k)));
      return keys.reduce((sum, k, i) => sum + byteSize(k) + byteSize(values[i] ?? ''), 0);
    } catch {
      return 0;
    }
  }
}

export function newDesignId(): string {
  return Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
}