1// Shared geometry: every mesh in the scene is a shape or a quad built once and 2// handed out, because only the materials carry state. 3import * as THREE from 'three'; 4import type { Kind } from '../sim'; 5import { lum } from './ink'; 6 7export const PIECE_R = 11; // world radius of a hull piece 8 9// Polygon of n points on a circle of radius r. Every piece kind has the same 10// footprint so slots pack the hull evenly. 11export function poly(n: number, r: number, inner = 0, tilt = 0): THREE.Shape { 12 const s = new THREE.Shape(); 13 for (let i = 0; i < n; i++) { 14 const a = tilt + (i * Math.PI * 2) / n; 15 const rr = inner && i % 2 ? inner : r; 16 const x = Math.cos(a) * rr; 17 const y = Math.sin(a) * rr; 18 if (i) s.lineTo(x, y); 19 else s.moveTo(x, y); 20 } 21 s.closePath(); 22 return s; 23} 24 25// The four piece kinds are named after their shape. Geometry is identical for every 26// piece of a kind at a scale, so it is built once and shared; only the materials are 27// per piece, because a piece's colours are its state. 28const shapes = new Map<string, THREE.BufferGeometry>(); 29export function pieceGeometry(kind: Kind, scale: number): THREE.BufferGeometry { 30 const key = `${kind}:${scale}`; 31 let g = shapes.get(key); 32 if (!g) shapes.set(key, (g = buildPiece(kind, PIECE_R * scale))); 33 return g; 34} 35 36function buildPiece(kind: Kind, r: number): THREE.BufferGeometry { 37 if (kind === 'square') return new THREE.ShapeGeometry(poly(4, r * 0.8, 0, Math.PI / 4)); 38 if (kind === 'circle') return new THREE.CircleGeometry(r * 0.75, 18); 39 if (kind === 'star') return new THREE.ShapeGeometry(poly(10, r, r * 0.45, -Math.PI / 2)); 40 return new THREE.ShapeGeometry(poly(3, r)); 41} 42 43// A removed mesh hands its materials back: the geometry is shared and cached, but 44// every piece owns the colours that say what it is. 45export function free(o: THREE.Object3D): void { 46 o.traverse((m) => ((m as THREE.Mesh).material as THREE.Material | undefined)?.dispose()); 47} 48 49// A plate of a given size is always the same quad, so it is shared: a piece, a shot 50// or a ray only ever needs its own colour, and a removed mesh only gives that back. 51const quads = new Map<string, THREE.PlaneGeometry>(); 52export function plate(w: number, h: number, v: number): THREE.Mesh<THREE.PlaneGeometry, THREE.MeshBasicMaterial> { 53 const key = `${w}:${h}`; 54 let g = quads.get(key); 55 if (!g) quads.set(key, (g = new THREE.PlaneGeometry(w, h))); 56 return new THREE.Mesh(g, new THREE.MeshBasicMaterial({ color: lum(v) })); 57}