3dexperiments/src/engine/mesh/aabb.js
2020-03-31 11:15:29 +03:00

38 lines
1.0 KiB
JavaScript

class BoundingBox {
constructor (min, max) {
this.min = min
this.max = max
this.calculateSphere()
}
static fromMesh (mesh) {
const min = [0, 0, 0]
const max = [0, 0, 0]
for (let v = 0; v < mesh.vertices.length; v += 3) {
const 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 }