Browse Source

implement Sphere.js class, add to common.js - issue #2708

Ben Houston 12 years ago
parent
commit
38563ecb13
2 changed files with 87 additions and 0 deletions
  1. 86 0
      src/core/Sphere.js
  2. 1 0
      utils/includes/common.json

+ 86 - 0
src/core/Sphere.js

@@ -0,0 +1,86 @@
+/**
+ * @author Ben Houston / [email protected] / http://github.com/bhouston
+ */
+
+( function ( THREE ) {
+
+	THREE.Sphere = function ( center, radius ) {
+
+		this.center = center || new THREE.Vector3();
+		this.radius = radius || 0;
+
+	};
+
+	THREE.Sphere.prototype.set = function ( center, radius ) {
+
+		this.center = center;
+		this.radius = radius;
+
+		return this;
+	};
+
+	THREE.Sphere.prototype.empty = function () {
+
+		return ( this.radius <= 0 );
+
+	};
+
+
+	THREE.Sphere.prototype.volume = function () {
+
+		// NOTE: would love to replace r*r*r with a helper cube(r), but may be much slower
+		return Math.PI * 4 / 3 * this.radius * this.radius * this.radius;
+
+	};
+
+	THREE.Sphere.prototype.containsPoint = function ( point ) {
+
+		var delta = new THREE.VEctor3();
+		var distanceSq = delta.sub( point, this.center ).lengthSq();
+
+		return ( distanceSq <= this.radius * this.radius );
+	};
+
+	THREE.Sphere.prototype.distanceToPoint = function ( point ) {
+
+		var delta = new THREE.VEctor3();
+		var distanceSq = delta.sub( point, this.center ).length();
+
+		return ( distanceSq - this.radius  );
+	};
+
+	THREE.Sphere.prototype.clampPoint = function ( point ) {
+
+		// NOTE: There is likely a more optimal way of doing this.
+
+		var delta = new THREE.VEctor3();
+		delta.sub( point, this.center );
+
+		var deltaLengthSq = delta.lengthSq();
+
+		if( deltaLengthSq > ( this.radius*this.radius ) ) {
+
+			delta.normalize().multiplyByScalar( this.radius ).addSelf( this.center );
+			return delta;
+
+		}
+
+		return point;
+	};
+
+	THREE.Sphere.prototype.bounds = function () {
+
+		var box =  new THREE.Box3( this.center );
+		box.expandByScalar( this.radius );
+
+		return box;
+	};
+
+	THREE.Sphere.prototype.translate = function ( offset ) {
+
+		this.center.add( this.center, this.offset );
+		
+		return this;
+	};
+
+}( THREE ) );

+ 1 - 0
utils/includes/common.json

@@ -13,6 +13,7 @@
 	"../src/core/Plane.js",
 	"../src/core/Ray.js",
 	"../src/core/Rectangle.js",
+	"../src/core/Sphere.js",
 	"../src/core/Math.js",
 	"../src/core/Object3D.js",
 	"../src/core/Projector.js",