var Vec3 = require('./Vec3');
A bounding box is a box with the smallest possible measure (area for 2D or volume for 3D) for a given geometry or a set of points
var someGeometryMin = new Vec3(0, 0, 0)
var someGeometryMax = new Vec3(2, 2, 2);
var bbox = new BoundingBox(someGeometryMin, someGeometryMax);
console.log(bbox.getSize());
console.log(bbox.getCenter());
var Vec3 = require('./Vec3');
function BoundingBox(min, max) {
this.min = min;
this.max = max;
}
pos
- The position of the enclosed geometry { Vec3 }size
- Size of the enclosed geometry { Vec3 }
returns { BoundingBox }
BoundingBox.fromPositionSize = function(pos, size) {
return new BoundingBox(Vec3.create(pos.x - size.x / 2,
pos.y - size.y / 2,
pos.z - size.z / 2),
Vec3.create(pos.x + size.x / 2,
pos.y + size.y / 2,
pos.z + size.z / 2));
};
points
- Points in space that the bounding box will enclose { Array of { Vec3 } }
returns { BoundingBox }
BoundingBox.fromPoints = function(points) {
var bbox = new BoundingBox(points[0].clone(), points[0].clone());
points.forEach(bbox.addPoint.bind(bbox));
return bbox;
};
BoundingBox.prototype.isEmpty = function() {
if (!this.min || !this.max) return true;
else return false;
};
BoundingBox.prototype.addPoint = function(p) {
if (this.isEmpty()) {
this.min = p.clone();
this.max = p.clone();
}
if (p.x < this.min.x) this.min.x = p.x;
if (p.y < this.min.y) this.min.y = p.y;
if (p.z < this.min.z) this.min.z = p.z;
if (p.x > this.max.x) this.max.x = p.x;
if (p.y > this.max.y) this.max.y = p.y;
if (p.z > this.max.z) this.max.z = p.z;
};
BoundingBox.prototype.getSize = function() {
return Vec3.create(this.max.x - this.min.x,
this.max.y - this.min.y,
this.max.z - this.min.z);
};
BoundingBox.prototype.getCenter = function() {
return Vec3.create(this.min.x + (this.max.x - this.min.x) / 2,
this.min.y + (this.max.y - this.min.y) / 2,
this.min.z + (this.max.z - this.min.z) / 2);
};
BoundingBox.prototype.contains = function(p) {
return p.x >= this.min.x
&& p.x <= this.max.x
&& p.y >= this.min.y
&& p.y <= this.max.y
&& p.z >= this.min.z
&& p.z <= this.max.z;
}
module.exports = BoundingBox;