// Shared geometry: every mesh in the scene is a shape or a quad built once and
// handed out, because only the materials carry state.
import * as THREE from 'three';
import type { Kind } from '../sim';
import { lum } from './ink';

export const PIECE_R = 11; // world radius of a hull piece

// Polygon of n points on a circle of radius r. Every piece kind has the same
// footprint so slots pack the hull evenly.
export function poly(n: number, r: number, inner = 0, tilt = 0): THREE.Shape {
  const s = new THREE.Shape();
  for (let i = 0; i < n; i++) {
    const a = tilt + (i * Math.PI * 2) / n;
    const rr = inner && i % 2 ? inner : r;
    const x = Math.cos(a) * rr;
    const y = Math.sin(a) * rr;
    if (i) s.lineTo(x, y);
    else s.moveTo(x, y);
  }
  s.closePath();
  return s;
}

// The four piece kinds are named after their shape. Geometry is identical for every
// piece of a kind at a scale, so it is built once and shared; only the materials are
// per piece, because a piece's colours are its state.
const shapes = new Map<string, THREE.BufferGeometry>();
export function pieceGeometry(kind: Kind, scale: number): THREE.BufferGeometry {
  const key = `${kind}:${scale}`;
  let g = shapes.get(key);
  if (!g) shapes.set(key, (g = buildPiece(kind, PIECE_R * scale)));
  return g;
}

function buildPiece(kind: Kind, r: number): THREE.BufferGeometry {
  if (kind === 'square') return new THREE.ShapeGeometry(poly(4, r * 0.8, 0, Math.PI / 4));
  if (kind === 'circle') return new THREE.CircleGeometry(r * 0.75, 18);
  if (kind === 'star') return new THREE.ShapeGeometry(poly(10, r, r * 0.45, -Math.PI / 2));
  return new THREE.ShapeGeometry(poly(3, r));
}

// A removed mesh hands its materials back: the geometry is shared and cached, but
// every piece owns the colours that say what it is.
export function free(o: THREE.Object3D): void {
  o.traverse((m) => ((m as THREE.Mesh).material as THREE.Material | undefined)?.dispose());
}

// A plate of a given size is always the same quad, so it is shared: a piece, a shot
// or a ray only ever needs its own colour, and a removed mesh only gives that back.
const quads = new Map<string, THREE.PlaneGeometry>();
export function plate(w: number, h: number, v: number): THREE.Mesh<THREE.PlaneGeometry, THREE.MeshBasicMaterial> {
  const key = `${w}:${h}`;
  let g = quads.get(key);
  if (!g) quads.set(key, (g = new THREE.PlaneGeometry(w, h)));
  return new THREE.Mesh(g, new THREE.MeshBasicMaterial({ color: lum(v) }));
}
