// The celestial bodies: one mesh per kind, built from disks, a lit limb and plates.
// A body is the only thing in the scene drawn behind the ships.
import * as THREE from 'three';
import { lum } from './ink';
import { plate } from './shapes';

const disk = (r: number, v: number, idx: number, x = 0, y = 0): THREE.Mesh => {
  const m = new THREE.Mesh(
    new THREE.CircleGeometry(r, 48),
    new THREE.MeshBasicMaterial({ color: lum(v, idx) }),
  );
  m.position.set(x, y, 0);
  return m;
};

// A lit limb: the bright edge that makes a disk pop off the black.
const limb = (r: number, v: number, idx: number): THREE.Mesh =>
  new THREE.Mesh(
    new THREE.RingGeometry(r * 0.88, r, 64),
    new THREE.MeshBasicMaterial({ color: lum(v, idx), side: THREE.DoubleSide }),
  );

// A star reads as a hot core with long rays, so it can never be mistaken for a
// planet at any zoom: it is the only thing in the scene that shines.
export function starMesh(r: number): THREE.Group {
  const g = new THREE.Group();
  g.add(disk(r, 0.8, 6));
  g.add(disk(r * 0.62, 1, 7));
  g.add(disk(r * 0.3, 1, 12));
  const rays = new THREE.Group();
  for (let i = 0; i < 8; i++) {
    const a = (i / 8) * Math.PI * 2;
    const len = (i % 2 ? 0.5 : 0.9) * r;
    const m = plate(r * 0.24, len, 0.7);
    (m.material as THREE.MeshBasicMaterial).color.copy(lum(0.6, 6));
    m.position.set(Math.cos(a) * (r * 0.8 + len / 2), Math.sin(a) * (r * 0.8 + len / 2), 0);
    m.rotation.z = a - Math.PI / 2;
    rays.add(m);
  }
  g.add(rays);
  return g;
}

// A barren planet: a rust disk lit from one side, with craters punched out of it.
// These are the ore bodies of the galaxy.
export function barrenMesh(r: number): THREE.Group {
  const g = new THREE.Group();
  g.add(disk(r, 0.7, 9));
  g.add(limb(r, 1, 9));
  for (const [dx, dy, cr] of [[0.3, 0.28, 0.34], [-0.12, 0.5, 0.2], [0.36, -0.34, 0.16]]) {
    g.add(disk(r * cr, 0.3, 8, dx * r, dy * r)); // craters
  }
  return g;
}

// A shipyard planet: cool steel, a lit cap, and a cream ring studded with gold
// docks. It is the only body in the system with anything bolted around it.
export function shipyardMesh(r: number): THREE.Group {
  const g = new THREE.Group();
  g.add(disk(r, 0.55, 10));
  g.add(disk(r * 0.82, 0.9, 11, -r * 0.07, r * 0.09));
  // The berth ring floats clear of the hull: a station, not a moon.
  const ring = new THREE.Mesh(
    new THREE.RingGeometry(r * 1.18, r * 1.38, 64),
    new THREE.MeshBasicMaterial({ color: lum(1, 12), side: THREE.DoubleSide }),
  );
  g.add(ring);
  for (let i = 0; i < 4; i++) {
    const a = (i / 4) * Math.PI * 2 + Math.PI / 4;
    const d = plate(r * 0.34, r * 0.34, 1);
    (d.material as THREE.MeshBasicMaterial).color.copy(lum(1, 7));
    d.position.set(Math.cos(a) * r * 1.5, Math.sin(a) * r * 1.5, 0.06);
    d.rotation.z = a;
    g.add(d);
  }
  return g;
}
