
class BoundingBox {
  constructor (min, max) {
    this.min = min
    this.max = max
    this.calculateSphere()
  }

  static fromMesh (mesh) {
    let min = [0, 0, 0]
    let max = [0, 0, 0]
    for (let v = 0; v < mesh.vertices.length; v += 3) {
      let vertex = [mesh.vertices[v], mesh.vertices[v + 1], mesh.vertices[v + 2]]
      // X
      if (vertex[0] > max[0]) max[0] = vertex[0]
      if (vertex[0] < min[0]) min[0] = vertex[0]
      // Y
      if (vertex[1] > max[1]) max[1] = vertex[1]
      if (vertex[1] < min[1]) min[1] = vertex[1]
      // Z
      if (vertex[2] > max[2]) max[2] = vertex[2]
      if (vertex[2] < min[2]) min[2] = vertex[2]
    }
    return new BoundingBox(min, max)
  }

  calculateSphere () {
    this.center = [
      this.min[0] + (this.max[0] - this.min[0]) / 2,
      this.min[1] + (this.max[1] - this.min[1]) / 2,
      this.min[2] + (this.max[2] - this.min[2]) / 2
    ]
    this.radius = Math.max((this.max[0] - this.min[0]) / 2, (this.max[1] - this.min[1]) / 2, (this.max[2] - this.min[2]) / 2)
  }
}

export { BoundingBox }
