@awayjs/core
Version:
AwayJS core classes
92 lines (91 loc) • 3.58 kB
JavaScript
var Sphere = /** @class */ (function () {
/**
* Create a Sphere with ABCD coefficients
*/
function Sphere(x, y, z, radius) {
if (x === void 0) { x = 0; }
if (y === void 0) { y = 0; }
if (z === void 0) { z = 0; }
if (radius === void 0) { radius = 0; }
this.x = x;
this.y = y;
this.z = z;
this.radius = radius;
}
Sphere.prototype.rayIntersection = function (position, direction, targetNormal) {
if (this.containsPoint(position))
return 0;
var px = position.x - this.x, py = position.y - this.y, pz = position.z - this.z;
var vx = direction.x, vy = direction.y, vz = direction.z;
var rayEntryDistance;
var a = vx * vx + vy * vy + vz * vz;
var b = 2 * (px * vx + py * vy + pz * vz);
var c = px * px + py * py + pz * pz - this.radius * this.radius;
var det = b * b - 4 * a * c;
if (det >= 0) { // ray goes through sphere
var sqrtDet = Math.sqrt(det);
rayEntryDistance = (-b - sqrtDet) / (2 * a);
if (rayEntryDistance >= 0) {
targetNormal.x = px + rayEntryDistance * vx;
targetNormal.y = py + rayEntryDistance * vy;
targetNormal.z = pz + rayEntryDistance * vz;
targetNormal.normalize();
return rayEntryDistance;
}
}
// ray misses sphere
return -1;
};
Sphere.prototype.containsPoint = function (position) {
var px = position.x - this.x;
var py = position.y - this.y;
var pz = position.z - this.z;
var distance = Math.sqrt(px * px + py * py + pz * pz);
return distance <= this.radius;
};
/**
* Copies all of sphere data from the source Sphere object into the calling
* Sphere object.
*
* @param sourceSphere The Sphere object from which to copy the data.
*/
Sphere.prototype.copyFrom = function (sourceSphere) {
this.x = sourceSphere.x;
this.y = sourceSphere.y;
this.z = sourceSphere.z;
this.radius = sourceSphere.radius;
};
/**
* Adds two spheres together to create a new Sphere object, by filling
* in the horizontal, vertical and longitudinal space between the two spheres.
*
* <p><b>Note:</b> The <code>union()</code> method ignores spheres with
* <code>0</code> as the height, width or depth value, such as: <code>var
* box2:Sphere = new Sphere(300,300,300,50,50,0);</code></p>
*
* @param toUnion A Sphere object to add to this Sphere object.
* @return A new Sphere object that is the union of the two spheres.
*/
Sphere.prototype.union = function (toUnion, target) {
if (target === void 0) { target = null; }
if (target == null)
target = new Sphere();
if (toUnion == null) {
target.copyFrom(this);
return target;
}
var xDiff = toUnion.x - this.x;
var yDiff = toUnion.y - this.y;
var zDiff = toUnion.z - this.z;
target.radius = (Math.sqrt(xDiff * xDiff + yDiff * yDiff + zDiff * zDiff) + toUnion.radius + this.radius) / 2;
target.x = this.x + xDiff / 2;
target.y = this.y + yDiff / 2;
target.z = this.z + zDiff / 2;
return target;
};
Sphere.prototype.toString = function () {
return 'Sphere [x:' + this.x + ', y:' + this.y + ', z:' + this.z + ', radius:' + this.radius + ']';
};
return Sphere;
}());
export { Sphere };