Browse Source

add Plane.intersectLine with unit tests.

Ben Houston 12 years ago
parent
commit
3595365f6b
2 changed files with 59 additions and 0 deletions
  1. 34 0
      src/math/Plane.js
  2. 25 0
      test/unit/math/Plane.js

+ 34 - 0
src/math/Plane.js

@@ -112,6 +112,40 @@ THREE.Plane.prototype = {
 
 
 	},
 	},
 
 
+	intersectLine: function ( startPoint, endPoint, optionalTarget ) {
+
+		var result = optionalTarget || new THREE.Vector3();
+
+		var direction = THREE.Plane.__v1.sub( endPoint, startPoint );
+
+		var denominator = this.normal.dot( direction );
+
+		if ( denominator == 0 ) {
+
+			// line is coplanar, return origin
+			if( this.distanceToPoint( startPoint ) == 0 ) {
+
+				return result.copy( startPoint );
+
+			}
+
+			// Unsure if this is the correct method to handle this case.
+			return undefined;
+
+		}
+
+		var t = - ( startPoint.dot( this.normal ) + this.constant ) / denominator;
+
+		if( t < 0 || t > 1 ) {
+
+			return undefined;
+
+		}
+
+		return result.copy( direction ).multiplyScalar( t ).addSelf( startPoint );
+
+	},
+
 	coplanarPoint: function ( optionalTarget ) {
 	coplanarPoint: function ( optionalTarget ) {
 
 
 		var result = optionalTarget || new THREE.Vector3();
 		var result = optionalTarget || new THREE.Vector3();

+ 25 - 0
test/unit/math/Plane.js

@@ -115,6 +115,31 @@ test( "distanceToSphere", function() {
 	ok( a.distanceToSphere( b ) === -1, "Passed!" );
 	ok( a.distanceToSphere( b ) === -1, "Passed!" );
 });
 });
 
 
+test( "isInterestionLine/intersectLine", function() {
+	var a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), 0 );
+
+	ok( a.isIntersectionLine( new THREE.Vector3( -10, 0, 0 ), new THREE.Vector3( 10, 0, 0 ) ), "Passed!" );
+	ok( a.intersectLine( new THREE.Vector3( -10, 0, 0 ), new THREE.Vector3( 10, 0, 0 ) ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" );
+
+	a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), -3 );
+
+	ok( a.isIntersectionLine( new THREE.Vector3( -10, 0, 0 ), new THREE.Vector3( 10, 0, 0 ) ), "Passed!" );
+	ok( a.intersectLine( new THREE.Vector3( -10, 0, 0 ), new THREE.Vector3( 10, 0, 0 ) ).equals( new THREE.Vector3( 3, 0, 0 ) ), "Passed!" );
+
+
+	a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), -11 );
+
+	ok( ! a.isIntersectionLine( new THREE.Vector3( -10, 0, 0 ), new THREE.Vector3( 10, 0, 0 ) ), "Passed!" );
+	ok( a.intersectLine( new THREE.Vector3( -10, 0, 0 ), new THREE.Vector3( 10, 0, 0 ) ) === undefined, "Passed!" );
+	
+	a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), 11 );
+
+	ok( ! a.isIntersectionLine( new THREE.Vector3( -10, 0, 0 ), new THREE.Vector3( 10, 0, 0 ) ), "Passed!" );
+	ok( a.intersectLine( new THREE.Vector3( -10, 0, 0 ), new THREE.Vector3( 10, 0, 0 ) ) === undefined, "Passed!" );
+
+});
+
+
 test( "projectPoint", function() {
 test( "projectPoint", function() {
 	var a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), 0 );
 	var a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), 0 );