package ocelot.desktop.geometry

object Box3D {
  def fromMinMax(min: Vector3D, max: Vector3D): Box3D = {
    val center = (min + max) * 0.5f
    val halfExtents = (max - min) * 0.5f
    Box3D(center, halfExtents)
  }

  def fromVertices(vertices: Iterator[Vector3D]): Box3D = {
    val first = vertices.next()
    val (min, max) = vertices.foldLeft((first, first)) { case ((min, max), vertex) =>
      (min.min(vertex), max.max(vertex))
    }
    Box3D.fromMinMax(min, max)
  }
}

case class Box3D(center: Vector3D, halfExtents: Vector3D) {
  def vertices: Seq[Vector3D] = Seq(
    center + halfExtents * Vector3D(-1, -1, -1),
    center + halfExtents * Vector3D(-1, -1, 1),
    center + halfExtents * Vector3D(-1, 1, -1),
    center + halfExtents * Vector3D(-1, 1, 1),
    center + halfExtents * Vector3D(1, -1, -1),
    center + halfExtents * Vector3D(1, -1, 1),
    center + halfExtents * Vector3D(1, 1, -1),
    center + halfExtents * Vector3D(1, 1, 1),
  )

  def transform(transform: Transform3D): Box3D = {
    Box3D.fromVertices(vertices.iterator.map(transform * _))
  }
}
