import { STRIDE, type Mesh } from "./Mesh"

type Corner = [number, number, number]

export namespace MeshBuilder {
  export function quad(
    mesh: Mesh,
    a: Corner,
    b: Corner,
    c: Corner,
    d: Corner,
    uScale: number,
    vScale: number,
  ): void {
    const base = mesh.verts.length / STRIDE
    mesh.verts.push(
      a[0],
      a[1],
      a[2],
      0,
      0,
      b[0],
      b[1],
      b[2],
      uScale,
      0,
      c[0],
      c[1],
      c[2],
      uScale,
      vScale,
      d[0],
      d[1],
      d[2],
      0,
      vScale,
    )
    mesh.indices.push(base, base + 1, base + 2, base, base + 2, base + 3)
  }

  export function slab(
    mesh: Mesh,
    x0: number,
    x1: number,
    z0: number,
    z1: number,
    y0: number,
    y1: number,
    tilesPerUnit: number,
  ): void {
    const dx = (x1 - x0) * tilesPerUnit
    const dz = (z1 - z0) * tilesPerUnit
    const dy = (y1 - y0) * tilesPerUnit
    quad(mesh, [x0, y1, z0], [x1, y1, z0], [x1, y1, z1], [x0, y1, z1], dx, dz)
    quad(mesh, [x0, y0, z0], [x1, y0, z0], [x1, y1, z0], [x0, y1, z0], dx, dy)
    quad(mesh, [x1, y0, z1], [x0, y0, z1], [x0, y1, z1], [x1, y1, z1], dx, dy)
    quad(mesh, [x0, y0, z1], [x0, y0, z0], [x0, y1, z0], [x0, y1, z1], dz, dy)
    quad(mesh, [x1, y0, z0], [x1, y0, z1], [x1, y1, z1], [x1, y1, z0], dz, dy)
  }

  export function box(
    mesh: Mesh,
    centerX: number,
    centerZ: number,
    half: number,
    base: number,
    height: number,
  ): void {
    const x0 = centerX - half
    const x1 = centerX + half
    const z0 = centerZ - half
    const z1 = centerZ + half
    const y1 = base + height
    quad(mesh, [x0, y1, z0], [x1, y1, z0], [x1, y1, z1], [x0, y1, z1], 1, 1)
    quad(mesh, [x0, base, z0], [x1, base, z0], [x1, y1, z0], [x0, y1, z0], 1, 1)
    quad(mesh, [x1, base, z1], [x0, base, z1], [x0, y1, z1], [x1, y1, z1], 1, 1)
    quad(mesh, [x1, base, z0], [x1, base, z1], [x1, y1, z1], [x1, y1, z0], 1, 1)
    quad(mesh, [x0, base, z1], [x0, base, z0], [x0, y1, z0], [x0, y1, z1], 1, 1)
  }
}
