Przeglądaj źródła

Merge remote-tracking branch 'bhouston/dev' into dev

Mr.doob 12 lat temu
rodzic
commit
2c948037b9
56 zmienionych plików z 4718 dodań i 356 usunięć
  1. 6 5
      examples/canvas_geometry_hierarchy.html
  2. 2 2
      examples/canvas_geometry_panorama.html
  3. 2 2
      examples/canvas_geometry_panorama_fisheye.html
  4. 7 7
      examples/canvas_interactive_cubes.html
  5. 10 10
      examples/canvas_interactive_cubes_tween.html
  6. 4 4
      examples/canvas_interactive_particles.html
  7. 2 2
      examples/css3d_panorama.html
  8. 4 4
      examples/js/controls/FirstPersonControls.js
  9. 3 4
      examples/js/controls/PathControls.js
  10. 1 1
      examples/js/effects/AnaglyphEffect.js
  11. 1 1
      examples/js/effects/ParallaxBarrierEffect.js
  12. 3 5
      examples/js/loaders/ColladaLoader.js
  13. 1 1
      examples/js/renderers/CSS3DRenderer.js
  14. 1 2
      examples/webgl_geometry_extrude_uvs2.html
  15. 2 2
      examples/webgl_geometry_hierarchy.html
  16. 7 7
      examples/webgl_interactive_cubes.html
  17. 3 3
      examples/webgl_interactive_cubes_gpu.html
  18. 3 3
      examples/webgl_interactive_draggablecubes.html
  19. 4 4
      examples/webgl_interactive_voxelpainter.html
  20. 1 1
      examples/webgl_lensflares.html
  21. 2 2
      examples/webgl_materials_cubemap_dynamic2.html
  22. 3 3
      examples/webgl_morphnormals.html
  23. 3 3
      examples/webgl_morphtargets_horse.html
  24. 2 2
      examples/webgl_panorama_equirectangular.html
  25. 2 2
      examples/webgl_performance.html
  26. 2 2
      examples/webgl_performance_doublesided.html
  27. 2 2
      examples/webgl_performance_static.html
  28. 1 1
      examples/webgl_sandbox.html
  29. 2 2
      src/cameras/PerspectiveCamera.js
  30. 1 1
      src/extras/cameras/CombinedCamera.js
  31. 11 0
      src/math/Box3.js
  32. 2 2
      src/math/Math.js
  33. 138 139
      src/math/Matrix4.js
  34. 63 65
      src/math/Quaternion.js
  35. 1 1
      src/math/Sphere.js
  36. 3919 0
      test/benchmark/benchmark-1.0.0.js
  37. 36 0
      test/benchmark/benchmarking_float32array_accesspatterns.html
  38. 155 0
      test/benchmark/core/Float32ArrayAccessPatterns.js
  39. 0 41
      test/sources.html
  40. 0 0
      test/unit/math/Box2.js
  41. 10 0
      test/unit/math/Box3.js
  42. 0 0
      test/unit/math/Constants.js
  43. 0 0
      test/unit/math/Plane.js
  44. 231 0
      test/unit/math/Quaternion.js
  45. 0 0
      test/unit/math/Ray.js
  46. 4 4
      test/unit/math/Sphere.js
  47. 0 0
      test/unit/math/Triangle.js
  48. 0 0
      test/unit/math/Vector2.js
  49. 0 0
      test/unit/math/Vector3.js
  50. 0 0
      test/unit/math/Vector4.js
  51. 0 0
      test/unit/qunit-1.10.0.css
  52. 0 0
      test/unit/qunit-1.10.0.js
  53. 44 0
      test/unit/unittests_sources.html
  54. 6 5
      test/unit/unittests_three-math.html
  55. 5 4
      test/unit/unittests_three.html
  56. 6 5
      test/unit/unittests_three.min.html

+ 6 - 5
examples/canvas_geometry_hierarchy.html

@@ -59,8 +59,8 @@
 					mesh.position.x = Math.random() * 2000 - 1000;
 					mesh.position.y = Math.random() * 2000 - 1000;
 					mesh.position.z = Math.random() * 2000 - 1000;
-					mesh.rotation.x = Math.random() * 360 * ( Math.PI / 180 );
-					mesh.rotation.y = Math.random() * 360 * ( Math.PI / 180 );
+					mesh.rotation.x = Math.random() * 2 * Math.PI;
+					mesh.rotation.y = Math.random() * 2 * Math.PI;
 					mesh.matrixAutoUpdate = false;
 					mesh.updateMatrix();
 					group.add( mesh );
@@ -122,9 +122,10 @@
 				camera.position.y += ( - mouseY - camera.position.y ) * .05;
 				camera.lookAt( scene.position );
 
-				group.rotation.x = Math.sin( Date.now() * 0.0007 ) * 0.5;
-				group.rotation.y = Math.sin( Date.now() * 0.0003 ) * 0.5;
-				group.rotation.z = Math.sin( Date.now() * 0.0002 ) * 0.5;
+				var currentSeconds = Date.now();
+				group.rotation.x = Math.sin( currentSeconds * 0.0007 ) * 0.5;
+				group.rotation.y = Math.sin( currentSeconds * 0.0003 ) * 0.5;
+				group.rotation.z = Math.sin( currentSeconds * 0.0002 ) * 0.5;
 
 				renderer.render( scene, camera );
 

+ 2 - 2
examples/canvas_geometry_panorama.html

@@ -208,8 +208,8 @@
 			function render() {
 
 				lat = Math.max( - 85, Math.min( 85, lat ) );
-				phi = ( 90 - lat ) * Math.PI / 180;
-				theta = lon * Math.PI / 180;
+				phi = THREE.Math.degToRad( 90 - lat );
+				theta = THREE.Math.degToRad( lon );
 
 				target.x = 500 * Math.sin( phi ) * Math.cos( theta );
 				target.y = 500 * Math.cos( phi );

+ 2 - 2
examples/canvas_geometry_panorama_fisheye.html

@@ -236,8 +236,8 @@
 			function render() {
 
 				lat = Math.max( - 85, Math.min( 85, lat ) );
-				phi = ( 90 - lat ) * Math.PI / 180;
-				theta = lon * Math.PI / 180;
+				phi = THREE.Math.degToRad( 90 - lat );
+				theta = THREE.Math.degToRad( lon );
 
 				target.x = 500 * Math.sin( phi ) * Math.cos( theta );
 				target.y = 500 * Math.cos( phi );

+ 7 - 7
examples/canvas_interactive_cubes.html

@@ -61,9 +61,9 @@
 					object.scale.y = Math.random() * 2 + 1;
 					object.scale.z = Math.random() * 2 + 1;
 
-					object.rotation.x = ( Math.random() * 360 ) * Math.PI / 180;
-					object.rotation.y = ( Math.random() * 360 ) * Math.PI / 180;
-					object.rotation.z = ( Math.random() * 360 ) * Math.PI / 180;
+					object.rotation.x = Math.random() * 2 * Math.PI;
+					object.rotation.y = Math.random() * 2 * Math.PI;
+					object.rotation.z = Math.random() * 2 * Math.PI;
 
 					scene.add( object );
 
@@ -163,11 +163,11 @@
 
 			function render() {
 
-				theta += 0.2;
+				theta += 0.1;
 
-				camera.position.x = radius * Math.sin( theta * Math.PI / 360 );
-				camera.position.y = radius * Math.sin( theta * Math.PI / 360 );
-				camera.position.z = radius * Math.cos( theta * Math.PI / 360 );
+				camera.position.x = radius * Math.sin( THREE.Math.degToRad( theta ) );
+				camera.position.y = radius * Math.sin( THREE.Math.degToRad( theta ) );
+				camera.position.z = radius * Math.cos( THREE.Math.degToRad( theta ) );
 				camera.lookAt( scene.position );
 
 				renderer.render( scene, camera );

+ 10 - 10
examples/canvas_interactive_cubes_tween.html

@@ -58,9 +58,9 @@
 					object.scale.x = Math.random() * 2 + 1;
 					object.scale.y = Math.random() * 2 + 1;
 					object.scale.z = Math.random() * 2 + 1;
-					object.rotation.x = ( Math.random() * 360 ) * Math.PI / 180;
-					object.rotation.y = ( Math.random() * 360 ) * Math.PI / 180;
-					object.rotation.z = ( Math.random() * 360 ) * Math.PI / 180;
+					object.rotation.x = Math.random() * 2 * Math.PI;
+					object.rotation.y = Math.random() * 2 * Math.PI;
+					object.rotation.z = Math.random() * 2 * Math.PI;
 					scene.add( object );
 
 				}
@@ -114,9 +114,9 @@
 					.easing( TWEEN.Easing.Elastic.Out).start();
 
 					new TWEEN.Tween( intersects[ 0 ].object.rotation ).to( {
-						x: ( Math.random() * 360 ) * Math.PI / 180,
-						y: ( Math.random() * 360 ) * Math.PI / 180,
-						z: ( Math.random() * 360 ) * Math.PI / 180 }, 2000 )
+						x: Math.random() * 2 * Math.PI,
+						y: Math.random() * 2 * Math.PI,
+						z: Math.random() * 2 * Math.PI }, 2000 )
 					.easing( TWEEN.Easing.Elastic.Out).start();
 
 				}
@@ -149,11 +149,11 @@
 
 				TWEEN.update();
 
-				theta += 0.2;
+				theta += 0.1;
 
-				camera.position.x = radius * Math.sin( theta * Math.PI / 360 );
-				camera.position.y = radius * Math.sin( theta * Math.PI / 360 );
-				camera.position.z = radius * Math.cos( theta * Math.PI / 360 );
+				camera.position.x = radius * Math.sin( THREE.Math.degToRad( theta ) );
+				camera.position.y = radius * Math.sin( THREE.Math.degToRad( theta ) );
+				camera.position.z = radius * Math.cos( THREE.Math.degToRad( theta ) );
 				camera.lookAt( scene.position );
 
 				renderer.render( scene, camera );

+ 4 - 4
examples/canvas_interactive_particles.html

@@ -135,11 +135,11 @@
 
 				// rotate camera
 
-				theta += 0.2;
+				theta += 0.1;
 
-				camera.position.x = radius * Math.sin( theta * Math.PI / 360 );
-				camera.position.y = radius * Math.sin( theta * Math.PI / 360 );
-				camera.position.z = radius * Math.cos( theta * Math.PI / 360 );
+				camera.position.x = radius * Math.sin( THREE.Math.degToRad( theta ) );
+				camera.position.y = radius * Math.sin( THREE.Math.degToRad( theta ) );
+				camera.position.z = radius * Math.cos( THREE.Math.degToRad( theta ) );
 				camera.lookAt( scene.position );
 
 				// find intersections

+ 2 - 2
examples/css3d_panorama.html

@@ -192,8 +192,8 @@
 
 				lon +=  0.1;
 				lat = Math.max( - 85, Math.min( 85, lat ) );
-				phi = ( 90 - lat ) * Math.PI / 180;
-				theta = lon * Math.PI / 180;
+				phi = THREE.Math.degToRad( 90 - lat );
+				theta = THREE.Math.degToRad( lon );
 
 				target.x = Math.sin( phi ) * Math.cos( theta );
 				target.y = Math.cos( phi );

+ 4 - 4
examples/js/controls/FirstPersonControls.js

@@ -231,8 +231,8 @@ THREE.FirstPersonControls = function ( object, domElement ) {
 			if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed; // * this.invertVertical?-1:1;
 
 			this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
-			this.phi = ( 90 - this.lat ) * Math.PI / 180;
-			this.theta = this.lon * Math.PI / 180;
+			this.phi = THREE.Math.degToRad( 90 - this.lat );
+			this.theta = THREE.Math.degToRad( this.lon );
 
 			var targetPosition = this.target,
 				position = this.object.position;
@@ -255,9 +255,9 @@ THREE.FirstPersonControls = function ( object, domElement ) {
 		if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed * verticalLookRatio;
 
 		this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
-		this.phi = ( 90 - this.lat ) * Math.PI / 180;
+		this.phi = THREE.Math.degToRad( 90 - this.lat );
 
-		this.theta = this.lon * Math.PI / 180;
+		this.theta = THREE.Math.degToRad( this.lon );
 
 		if ( this.constrainVertical ) {
 

+ 3 - 4
examples/js/controls/PathControls.js

@@ -41,8 +41,7 @@ THREE.PathControls = function ( object, domElement ) {
 	this.phi = 0;
 	this.theta = 0;
 
-	var PI2 = Math.PI * 2,
-		PI180 = Math.PI / 180;
+	var PI2 = Math.PI * 2;
 
 	this.viewHalfX = 0;
 	this.viewHalfY = 0;
@@ -81,8 +80,8 @@ THREE.PathControls = function ( object, domElement ) {
 		this.lon = Math.max( 0, Math.min( 360, this.lon ) );
 		this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
 
-		this.phi = ( 90 - this.lat ) * PI180;
-		this.theta = this.lon * PI180;
+		this.phi = THREE.Math.degToRad( 90 - this.lat );
+		this.theta = THREE.Math.degToRad( this.lon );
 
 		this.phi = normalize_angle_rad( this.phi );
 

+ 1 - 1
examples/js/effects/AnaglyphEffect.js

@@ -117,7 +117,7 @@ THREE.AnaglyphEffect = function ( renderer, width, height ) {
 			var projectionMatrix = camera.projectionMatrix.clone();
 			var eyeSep = focalLength / 30 * 0.5;
 			var eyeSepOnProjection = eyeSep * _near / focalLength;
-			var ymax = _near * Math.tan( _fov * Math.PI / 360 );
+			var ymax = _near * Math.tan( THREE.Math.degToRad( _fov * 0.5 ) );
 			var xmin, xmax;
 
 			// translate xOffset

+ 1 - 1
examples/js/effects/ParallaxBarrierEffect.js

@@ -118,7 +118,7 @@ THREE.ParallaxBarrierEffect = function ( renderer ) {
 			var projectionMatrix = camera.projectionMatrix.clone();
 			var eyeSep = focalLength / 30 * 0.5;
 			var eyeSepOnProjection = eyeSep * _near / focalLength;
-			var ymax = _near * Math.tan( _fov * Math.PI / 360 );
+			var ymax = _near * Math.tan( THREE.Math.degToRad( _fov * 0.5 ) );
 			var xmin, xmax;
 
 			// translate xOffset

+ 3 - 5
examples/js/loaders/ColladaLoader.js

@@ -52,8 +52,6 @@ THREE.ColladaLoader = function () {
 	var colladaUp = 'Y';
 	var upConversion = null;
 
-	var TO_RADIANS = Math.PI / 180;
-
 	function load ( url, readyCallback, progressCallback ) {
 
 		var length = 0;
@@ -1920,7 +1918,7 @@ THREE.ColladaLoader = function () {
 
 			case 'rotate':
 
-				this.angle = this.data[3] * TO_RADIANS;
+				this.angle = THREE.Math.degToRad( this.data[3] );
 
 			case 'translate':
 
@@ -2101,7 +2099,7 @@ THREE.ColladaLoader = function () {
 
 					case 'ANGLE':
 
-						this.angle = data * TO_RADIANS;
+						this.angle = THREE.Math.degToRad( data );
 						break;
 
 					default:
@@ -2109,7 +2107,7 @@ THREE.ColladaLoader = function () {
 						this.obj.x = data[ 0 ];
 						this.obj.y = data[ 1 ];
 						this.obj.z = data[ 2 ];
-						this.angle = data[ 3 ] * TO_RADIANS;
+						this.angle = THREE.Math.degToRad( data[ 3 ] );
 						break;
 
 				}

+ 1 - 1
examples/js/renderers/CSS3DRenderer.js

@@ -139,7 +139,7 @@ THREE.CSS3DRenderer = function () {
 
 	this.render = function ( scene, camera ) {
 
-		var fov = 0.5 / Math.tan( camera.fov * Math.PI / 360 ) * _height;
+		var fov = 0.5 / Math.tan( THREE.Math.degToRad( camera.fov * 0.5 ) ) * _height;
 
 		this.domElement.style.WebkitPerspective = fov + "px";
 		this.domElement.style.MozPerspective = fov + "px";

+ 1 - 2
examples/webgl_geometry_extrude_uvs2.html

@@ -66,8 +66,7 @@
 	function updateRotation() {
 		rX = (rX + 3600) % 360;
 		rY = (rY + 3600) % 360;
-		var torad = Math.PI / 180.0;
-		testMesh.rotation.set(rY *torad, 0, rX *torad);
+		testMesh.rotation.set( THREE.Math.degToRad( rY ), 0, THREE.Math.degToRad( rX ) );
 	}
 
 	function render() {

+ 2 - 2
examples/webgl_geometry_hierarchy.html

@@ -60,8 +60,8 @@
 					mesh.position.y = Math.random() * 2000 - 1000;
 					mesh.position.z = Math.random() * 2000 - 1000;
 
-					mesh.rotation.x = Math.random() * 360 * ( Math.PI / 180 );
-					mesh.rotation.y = Math.random() * 360 * ( Math.PI / 180 );
+					mesh.rotation.x = Math.random() * 2 * Math.PI;
+					mesh.rotation.y = Math.random() * 2 * Math.PI;
 
 					mesh.matrixAutoUpdate = false;
 					mesh.updateMatrix();

+ 7 - 7
examples/webgl_interactive_cubes.html

@@ -65,9 +65,9 @@
 					object.position.y = Math.random() * 800 - 400;
 					object.position.z = Math.random() * 800 - 400;
 
-					object.rotation.x = ( Math.random() * 360 ) * Math.PI / 180;
-					object.rotation.y = ( Math.random() * 360 ) * Math.PI / 180;
-					object.rotation.z = ( Math.random() * 360 ) * Math.PI / 180;
+					object.rotation.x = Math.random() * 2 * Math.PI;
+					object.rotation.y = Math.random() * 2 * Math.PI;
+					object.rotation.z = Math.random() * 2 * Math.PI;
 
 					object.scale.x = Math.random() + 0.5;
 					object.scale.y = Math.random() + 0.5;
@@ -132,11 +132,11 @@
 
 			function render() {
 
-				theta += 0.2;
+				theta += 0.1;
 
-				camera.position.x = radius * Math.sin( theta * Math.PI / 360 );
-				camera.position.y = radius * Math.sin( theta * Math.PI / 360 );
-				camera.position.z = radius * Math.cos( theta * Math.PI / 360 );
+				camera.position.x = radius * Math.sin( THREE.Math.degToRad( theta ) );
+				camera.position.y = radius * Math.sin( THREE.Math.degToRad( theta ) );
+				camera.position.z = radius * Math.cos( THREE.Math.degToRad( theta ) );
 
 				camera.lookAt( scene.position );
 

+ 3 - 3
examples/webgl_interactive_cubes_gpu.html

@@ -114,9 +114,9 @@
 
 					var rotation = new THREE.Vector3();
 
-					rotation.x = ( Math.random() * 2 * Math.PI );
-					rotation.y = ( Math.random() * 2 * Math.PI );
-					rotation.z = ( Math.random() * 2 * Math.PI );
+					rotation.x = Math.random() * 2 * Math.PI;
+					rotation.y = Math.random() * 2 * Math.PI;
+					rotation.z = Math.random() * 2 * Math.PI;
 
 					var scale = new THREE.Vector3();
 

+ 3 - 3
examples/webgl_interactive_draggablecubes.html

@@ -83,9 +83,9 @@
 					object.position.y = Math.random() * 600 - 300;
 					object.position.z = Math.random() * 800 - 400;
 
-					object.rotation.x = ( Math.random() * 360 ) * Math.PI / 180;
-					object.rotation.y = ( Math.random() * 360 ) * Math.PI / 180;
-					object.rotation.z = ( Math.random() * 360 ) * Math.PI / 180;
+					object.rotation.x = Math.random() * 2 * Math.PI;
+					object.rotation.y = Math.random() * 2 * Math.PI;
+					object.rotation.z = Math.random() * 2 * Math.PI;
 
 					object.scale.x = Math.random() * 2 + 1;
 					object.scale.y = Math.random() * 2 + 1;

+ 4 - 4
examples/webgl_interactive_voxelpainter.html

@@ -33,7 +33,7 @@
 			var projector, plane, cube;
 			var mouse2D, mouse3D, raycaster,
 			rollOveredFace, isShiftDown = false,
-			theta = 45, isCtrlDown = false;
+			theta = 45 * 0.5, isCtrlDown = false;
 
 			var rollOverMesh, rollOverMaterial, voxelPosition = new THREE.Vector3(), tmpVec = new THREE.Vector3();
 			var cubeGeo, cubeMaterial;
@@ -272,7 +272,7 @@
 
 				if ( isShiftDown ) {
 
-					theta += mouse2D.x * 3;
+					theta += mouse2D.x * 1.5;
 
 				}
 
@@ -292,8 +292,8 @@
 
 				}
 
-				camera.position.x = 1400 * Math.sin( theta * Math.PI / 360 );
-				camera.position.z = 1400 * Math.cos( theta * Math.PI / 360 );
+				camera.position.x = 1400 * Math.sin( THREE.Math.degToRad( theta ) );
+				camera.position.z = 1400 * Math.cos( THREE.Math.degToRad( theta ) );
 
 				camera.lookAt( scene.position );
 

+ 1 - 1
examples/webgl_lensflares.html

@@ -216,7 +216,7 @@
 				}
 
 				object.lensFlares[ 2 ].y += 0.025;
-				object.lensFlares[ 3 ].rotation = object.positionScreen.x * 0.5 + 45 * Math.PI / 180;
+				object.lensFlares[ 3 ].rotation = object.positionScreen.x * 0.5 + THREE.Math.degToRad( 45 );
 
 			}
 

+ 2 - 2
examples/webgl_materials_cubemap_dynamic2.html

@@ -170,8 +170,8 @@
 				lon += .15;
 
 				lat = Math.max( - 85, Math.min( 85, lat ) );
-				phi = ( 90 - lat ) * Math.PI / 180;
-				theta = lon * Math.PI / 180;
+				phi = THREE.Math.degToRad( 90 - lat );
+				theta = THREE.Math.degToRad( lon );
 
 				sphere.position.x = Math.sin( time * 0.001 ) * 30;
 				sphere.position.y = Math.sin( time * 0.0011 ) * 30;

+ 3 - 3
examples/webgl_morphnormals.html

@@ -195,10 +195,10 @@
 
 			function render() {
 
-				theta += 0.2;
+				theta += 0.1;
 
-				camera.position.x = radius * Math.sin( theta * Math.PI / 360 );
-				camera.position.z = radius * Math.cos( theta * Math.PI / 360 );
+				camera.position.x = radius * Math.sin( THREE.Math.degToRad( theta ) );
+				camera.position.z = radius * Math.cos( THREE.Math.degToRad( theta ) );
 
 				camera.lookAt( camera.target );
 

+ 3 - 3
examples/webgl_morphtargets_horse.html

@@ -118,10 +118,10 @@
 
 			function render() {
 
-				theta += 0.2;
+				theta += 0.1;
 
-				camera.position.x = radius * Math.sin( theta * Math.PI / 360 );
-				camera.position.z = radius * Math.cos( theta * Math.PI / 360 );
+				camera.position.x = radius * Math.sin( THREE.Math.degToRad( theta ) );
+				camera.position.z = radius * Math.cos( THREE.Math.degToRad( theta ) );
 
 				camera.lookAt( camera.target );
 

+ 2 - 2
examples/webgl_panorama_equirectangular.html

@@ -157,8 +157,8 @@
 			function render() {
 
 				lat = Math.max( - 85, Math.min( 85, lat ) );
-				phi = ( 90 - lat ) * Math.PI / 180;
-				theta = lon * Math.PI / 180;
+				phi = THREE.Math.degToRad( 90 - lat );
+				theta = THREE.Math.degToRad( lon );
 
 				camera.target.x = 500 * Math.sin( phi ) * Math.cos( theta );
 				camera.target.y = 500 * Math.cos( phi );

+ 2 - 2
examples/webgl_performance.html

@@ -66,8 +66,8 @@
 						mesh.position.x = Math.random() * 8000 - 4000;
 						mesh.position.y = Math.random() * 8000 - 4000;
 						mesh.position.z = Math.random() * 8000 - 4000;
-						mesh.rotation.x = Math.random() * 360 * ( Math.PI / 180 );
-						mesh.rotation.y = Math.random() * 360 * ( Math.PI / 180 );
+						mesh.rotation.x = Math.random() * 2 * Math.PI;
+						mesh.rotation.y = Math.random() * 2 * Math.PI;
 						mesh.scale.x = mesh.scale.y = mesh.scale.z = Math.random() * 50 + 100;
 
 						objects.push( mesh );

+ 2 - 2
examples/webgl_performance_doublesided.html

@@ -105,8 +105,8 @@
 					mesh.position.y = Math.random() * 10000 - 5000;
 					mesh.position.z = Math.random() * 10000 - 5000;
 
-					mesh.rotation.x = Math.random() * 360 * ( Math.PI / 180 );
-					mesh.rotation.y = Math.random() * 360 * ( Math.PI / 180 );
+					mesh.rotation.x = Math.random() * 2 * Math.PI;
+					mesh.rotation.y = Math.random() * 2 * Math.PI;
 					mesh.scale.x = mesh.scale.y = mesh.scale.z = Math.random() * 50 + 100;
 
 					mesh.matrixAutoUpdate = false;

+ 2 - 2
examples/webgl_performance_static.html

@@ -62,8 +62,8 @@
 						mesh.position.x = Math.random() * 10000 - 5000;
 						mesh.position.y = Math.random() * 10000 - 5000;
 						mesh.position.z = Math.random() * 10000 - 5000;
-						mesh.rotation.x = Math.random() * 360 * ( Math.PI / 180 );
-						mesh.rotation.y = Math.random() * 360 * ( Math.PI / 180 );
+						mesh.rotation.x = Math.random() * 2 * Math.PI;
+						mesh.rotation.y = Math.random() * 2 * Math.PI;
 						mesh.scale.x = mesh.scale.y = mesh.scale.z = Math.random() * 50 + 100;
 						mesh.matrixAutoUpdate = false;
 						mesh.updateMatrix();

+ 1 - 1
examples/webgl_sandbox.html

@@ -128,7 +128,7 @@
 					mesh.position.z = Math.random() * 10000 - 5000;
 
 					//mesh.rotation.x = Math.random() * 360 * ( Math.PI / 180 );
-					mesh.rotation.y = Math.random() * 360 * ( Math.PI / 180 );
+					mesh.rotation.y = Math.random() * 2 * Math.PI;
 
 					mesh.scale.x = mesh.scale.y = mesh.scale.z = Math.random() * 4 + 1;
 

+ 2 - 2
src/cameras/PerspectiveCamera.js

@@ -30,7 +30,7 @@ THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight
 
 	if ( frameHeight === undefined ) frameHeight = 24;
 
-	this.fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
+	this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
 	this.updateProjectionMatrix();
 
 }
@@ -91,7 +91,7 @@ THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
 	if ( this.fullWidth ) {
 
 		var aspect = this.fullWidth / this.fullHeight;
-		var top = Math.tan( this.fov * Math.PI / 360 ) * this.near;
+		var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
 		var bottom = -top;
 		var left = aspect * bottom;
 		var right = aspect * top;

+ 1 - 1
src/extras/cameras/CombinedCamera.js

@@ -154,7 +154,7 @@ THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
 
 	if ( frameHeight === undefined ) frameHeight = 24;
 
-	var fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
+	var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
 
 	this.setFov( fov );
 

+ 11 - 0
src/math/Box3.js

@@ -226,6 +226,17 @@ THREE.Box3.prototype = {
 
 	},
 
+	getBoundingSphere: function ( optionalTarget ) {
+
+		var result = optionalTarget || new THREE.Sphere();
+		
+		result.center = this.center();
+		result.radius = this.size( THREE.Box3.__v0 ).length() * 0.5;;
+
+		return result;
+
+	},
+
 	intersect: function ( box ) {
 
 		this.min.maxSelf( box.min );

+ 2 - 2
src/math/Math.js

@@ -67,13 +67,13 @@ THREE.Math = {
 
 	},
 
-	degreesToRadians: function ( degrees ) {
+	degToRad: function ( degrees ) {
 
 		return degrees * THREE.Math.__d2r;
 
 	},
 
-	radiansToDegrees: function ( radians ) {
+	radToDeg: function ( radians ) {
 
 		return radians * THREE.Math.__r2d;
 

+ 138 - 139
src/math/Matrix4.js

@@ -74,6 +74,143 @@ THREE.Matrix4.prototype = {
 
 	},
 
+	setRotationFromEuler: function ( v, order ) {
+
+		var te = this.elements;
+
+		var x = v.x, y = v.y, z = v.z;
+		var a = Math.cos( x ), b = Math.sin( x );
+		var c = Math.cos( y ), d = Math.sin( y );
+		var e = Math.cos( z ), f = Math.sin( z );
+
+		if ( order === undefined || order === 'XYZ' ) {
+
+			var ae = a * e, af = a * f, be = b * e, bf = b * f;
+
+			te[0] = c * e;
+			te[4] = - c * f;
+			te[8] = d;
+
+			te[1] = af + be * d;
+			te[5] = ae - bf * d;
+			te[9] = - b * c;
+
+			te[2] = bf - ae * d;
+			te[6] = be + af * d;
+			te[10] = a * c;
+
+		} else if ( order === 'YXZ' ) {
+
+			var ce = c * e, cf = c * f, de = d * e, df = d * f;
+
+			te[0] = ce + df * b;
+			te[4] = de * b - cf;
+			te[8] = a * d;
+
+			te[1] = a * f;
+			te[5] = a * e;
+			te[9] = - b;
+
+			te[2] = cf * b - de;
+			te[6] = df + ce * b;
+			te[10] = a * c;
+
+		} else if ( order === 'ZXY' ) {
+
+			var ce = c * e, cf = c * f, de = d * e, df = d * f;
+
+			te[0] = ce - df * b;
+			te[4] = - a * f;
+			te[8] = de + cf * b;
+
+			te[1] = cf + de * b;
+			te[5] = a * e;
+			te[9] = df - ce * b;
+
+			te[2] = - a * d;
+			te[6] = b;
+			te[10] = a * c;
+
+		} else if ( order === 'ZYX' ) {
+
+			var ae = a * e, af = a * f, be = b * e, bf = b * f;
+
+			te[0] = c * e;
+			te[4] = be * d - af;
+			te[8] = ae * d + bf;
+
+			te[1] = c * f;
+			te[5] = bf * d + ae;
+			te[9] = af * d - be;
+
+			te[2] = - d;
+			te[6] = b * c;
+			te[10] = a * c;
+
+		} else if ( order === 'YZX' ) {
+
+			var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
+
+			te[0] = c * e;
+			te[4] = bd - ac * f;
+			te[8] = bc * f + ad;
+
+			te[1] = f;
+			te[5] = a * e;
+			te[9] = - b * e;
+
+			te[2] = - d * e;
+			te[6] = ad * f + bc;
+			te[10] = ac - bd * f;
+
+		} else if ( order === 'XZY' ) {
+
+			var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
+
+			te[0] = c * e;
+			te[4] = - f;
+			te[8] = d * e;
+
+			te[1] = ac * f + bd;
+			te[5] = a * e;
+			te[9] = ad * f - bc;
+
+			te[2] = bc * f - ad;
+			te[6] = b * e;
+			te[10] = bd * f + ac;
+
+		}
+
+		return this;
+
+	},
+
+	setRotationFromQuaternion: function ( q ) {
+
+		var te = this.elements;
+
+		var x = q.x, y = q.y, z = q.z, w = q.w;
+		var x2 = x + x, y2 = y + y, z2 = z + z;
+		var xx = x * x2, xy = x * y2, xz = x * z2;
+		var yy = y * y2, yz = y * z2, zz = z * z2;
+		var wx = w * x2, wy = w * y2, wz = w * z2;
+
+		te[0] = 1 - ( yy + zz );
+		te[4] = xy - wz;
+		te[8] = xz + wy;
+
+		te[1] = xy + wz;
+		te[5] = 1 - ( xx + zz );
+		te[9] = yz - wx;
+
+		te[2] = xz - wy;
+		te[6] = yz + wx;
+		te[10] = 1 - ( xx + yy );
+
+		return this;
+
+	},
+
 	lookAt: function ( eye, target, up ) {
 
 		var te = this.elements;
@@ -440,144 +577,6 @@ THREE.Matrix4.prototype = {
 
 	},
 
-	setRotationFromEuler: function ( v, order ) {
-
-		var te = this.elements;
-
-		var x = v.x, y = v.y, z = v.z;
-		var a = Math.cos( x ), b = Math.sin( x );
-		var c = Math.cos( y ), d = Math.sin( y );
-		var e = Math.cos( z ), f = Math.sin( z );
-
-		if ( order === undefined || order === 'XYZ' ) {
-
-			var ae = a * e, af = a * f, be = b * e, bf = b * f;
-
-			te[0] = c * e;
-			te[4] = - c * f;
-			te[8] = d;
-
-			te[1] = af + be * d;
-			te[5] = ae - bf * d;
-			te[9] = - b * c;
-
-			te[2] = bf - ae * d;
-			te[6] = be + af * d;
-			te[10] = a * c;
-
-		} else if ( order === 'YXZ' ) {
-
-			var ce = c * e, cf = c * f, de = d * e, df = d * f;
-
-			te[0] = ce + df * b;
-			te[4] = de * b - cf;
-			te[8] = a * d;
-
-			te[1] = a * f;
-			te[5] = a * e;
-			te[9] = - b;
-
-			te[2] = cf * b - de;
-			te[6] = df + ce * b;
-			te[10] = a * c;
-
-		} else if ( order === 'ZXY' ) {
-
-			var ce = c * e, cf = c * f, de = d * e, df = d * f;
-
-			te[0] = ce - df * b;
-			te[4] = - a * f;
-			te[8] = de + cf * b;
-
-			te[1] = cf + de * b;
-			te[5] = a * e;
-			te[9] = df - ce * b;
-
-			te[2] = - a * d;
-			te[6] = b;
-			te[10] = a * c;
-
-		} else if ( order === 'ZYX' ) {
-
-			var ae = a * e, af = a * f, be = b * e, bf = b * f;
-
-			te[0] = c * e;
-			te[4] = be * d - af;
-			te[8] = ae * d + bf;
-
-			te[1] = c * f;
-			te[5] = bf * d + ae;
-			te[9] = af * d - be;
-
-			te[2] = - d;
-			te[6] = b * c;
-			te[10] = a * c;
-
-		} else if ( order === 'YZX' ) {
-
-			var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
-
-			te[0] = c * e;
-			te[4] = bd - ac * f;
-			te[8] = bc * f + ad;
-
-			te[1] = f;
-			te[5] = a * e;
-			te[9] = - b * e;
-
-			te[2] = - d * e;
-			te[6] = ad * f + bc;
-			te[10] = ac - bd * f;
-
-		} else if ( order === 'XZY' ) {
-
-			var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
-
-			te[0] = c * e;
-			te[4] = - f;
-			te[8] = d * e;
-
-			te[1] = ac * f + bd;
-			te[5] = a * e;
-			te[9] = ad * f - bc;
-
-			te[2] = bc * f - ad;
-			te[6] = b * e;
-			te[10] = bd * f + ac;
-
-		}
-
-		return this;
-
-	},
-
-
-	setRotationFromQuaternion: function ( q ) {
-
-		var te = this.elements;
-
-		var x = q.x, y = q.y, z = q.z, w = q.w;
-		var x2 = x + x, y2 = y + y, z2 = z + z;
-		var xx = x * x2, xy = x * y2, xz = x * z2;
-		var yy = y * y2, yz = y * z2, zz = z * z2;
-		var wx = w * x2, wy = w * y2, wz = w * z2;
-
-		te[0] = 1 - ( yy + zz );
-		te[4] = xy - wz;
-		te[8] = xz + wy;
-
-		te[1] = xy + wz;
-		te[5] = 1 - ( xx + zz );
-		te[9] = yz - wx;
-
-		te[2] = xz - wy;
-		te[6] = yz + wx;
-		te[10] = 1 - ( xx + yy );
-
-		return this;
-
-	},
-
 	compose: function ( translation, rotation, scale ) {
 
 		var te = this.elements;
@@ -1014,7 +1013,7 @@ THREE.Matrix4.prototype = {
 
 	makePerspective: function ( fov, aspect, near, far ) {
 
-		var ymax = near * Math.tan( fov * Math.PI / 360 );
+		var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
 		var ymin = - ymax;
 		var xmin = ymin * aspect;
 		var xmax = ymax * aspect;

+ 63 - 65
src/math/Quaternion.js

@@ -2,6 +2,7 @@
  * @author mikael emtinger / http://gomo.se/
  * @author alteredq / http://alteredqualia.com/
  * @author WestLangley / http://github.com/WestLangley
+ * @author bhouston / http://exocortex.com
  */
 
 THREE.Quaternion = function( x, y, z, w ) {
@@ -174,6 +175,50 @@ THREE.Quaternion.prototype = {
 
 	},
 
+	add: function ( a, b ) {
+
+		this.x = a.x + b.x;
+		this.y = a.y + b.y;
+		this.z = a.z + b.z;
+		this.w = a.w + b.w;
+
+		return this;
+
+	},
+
+	addSelf: function ( v ) {
+
+		this.x += v.x;
+		this.y += v.y;
+		this.z += v.z;
+		this.w += v.w;
+
+		return this;
+
+	},
+
+	sub: function ( a, b ) {
+
+		this.x = a.x - b.x;
+		this.y = a.y - b.y;
+		this.z = a.z - b.z;
+		this.w = a.w - b.w;
+
+		return this;
+
+	},
+
+	subSelf: function ( v ) {
+
+		this.x -= v.x;
+		this.y -= v.y;
+		this.z -= v.z;
+		this.w -= v.w;
+
+		return this;
+
+	},
+
 	inverse: function () {
 
 		this.conjugate().normalize();
@@ -192,15 +237,21 @@ THREE.Quaternion.prototype = {
 
 	},
 
+	lengthSq: function () {
+
+		return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
+
+	},
+
 	length: function () {
 
-		return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
+		return Math.sqrt( this.lengthSq() );
 
 	},
 
 	normalize: function () {
 
-		var l = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
+		var l = this.length();
 
 		if ( l === 0 ) {
 
@@ -226,21 +277,14 @@ THREE.Quaternion.prototype = {
 
 	multiply: function ( a, b ) {
 
-		// from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
-		var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w,
-		qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
-
-		this.x =  qax * qbw + qay * qbz - qaz * qby + qaw * qbx;
-		this.y = -qax * qbz + qay * qbw + qaz * qbx + qaw * qby;
-		this.z =  qax * qby - qay * qbx + qaz * qbw + qaw * qbz;
-		this.w = -qax * qbx - qay * qby - qaz * qbz + qaw * qbw;
-
-		return this;
+		this.copy( a );
+		return this.multiplySelf( b );
 
 	},
 
 	multiplySelf: function ( b ) {
 
+		// from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
 		var qax = this.x, qay = this.y, qaz = this.z, qaw = this.w,
 		qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
 
@@ -337,6 +381,12 @@ THREE.Quaternion.prototype = {
 
 	},
 
+	equals: function ( v ) {
+
+		return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
+
+	},
+
 	clone: function () {
 
 		return new THREE.Quaternion( this.x, this.y, this.z, this.w );
@@ -347,58 +397,6 @@ THREE.Quaternion.prototype = {
 
 THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
 
-	// http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
-
-	var cosHalfTheta = qa.w * qb.w + qa.x * qb.x + qa.y * qb.y + qa.z * qb.z;
-
-	if ( cosHalfTheta < 0 ) {
-
-		qm.w = -qb.w;
-		qm.x = -qb.x;
-		qm.y = -qb.y;
-		qm.z = -qb.z;
-
-		cosHalfTheta = -cosHalfTheta;
-
-	} else {
-
-		qm.copy( qb );
-
-	}
-
-	if ( Math.abs( cosHalfTheta ) >= 1.0 ) {
-
-		qm.w = qa.w;
-		qm.x = qa.x;
-		qm.y = qa.y;
-		qm.z = qa.z;
-
-		return qm;
-
-	}
-
-	var halfTheta = Math.acos( cosHalfTheta );
-	var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
-
-	if ( Math.abs( sinHalfTheta ) < 0.001 ) {
-
-		qm.w = 0.5 * ( qa.w + qm.w );
-		qm.x = 0.5 * ( qa.x + qm.x );
-		qm.y = 0.5 * ( qa.y + qm.y );
-		qm.z = 0.5 * ( qa.z + qm.z );
-
-		return qm;
-
-	}
-
-	var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta;
-	var ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
-
-	qm.w = ( qa.w * ratioA + qm.w * ratioB );
-	qm.x = ( qa.x * ratioA + qm.x * ratioB );
-	qm.y = ( qa.y * ratioA + qm.y * ratioB );
-	qm.z = ( qa.z * ratioA + qm.z * ratioB );
-
-	return qm;
+	return qm.copy( qa ).slerpSelf( qb, t );
 
 }

+ 1 - 1
src/math/Sphere.js

@@ -85,7 +85,7 @@ THREE.Sphere.prototype = {
 
 	},
 
-	bounds: function ( optionalTarget ) {
+	getBoundingBox: function ( optionalTarget ) {
 
 		var box = optionalTarget || new THREE.Box3();
 

+ 3919 - 0
test/benchmark/benchmark-1.0.0.js

@@ -0,0 +1,3919 @@
+/*!
+ * Benchmark.js v1.0.0 <http://benchmarkjs.com/>
+ * Copyright 2010-2012 Mathias Bynens <http://mths.be/>
+ * Based on JSLitmus.js, copyright Robert Kieffer <http://broofa.com/>
+ * Modified by John-David Dalton <http://allyoucanleet.com/>
+ * Available under MIT license <http://mths.be/mit>
+ */
+;(function(window, undefined) {
+  'use strict';
+
+  /** Used to assign each benchmark an incrimented id */
+  var counter = 0;
+
+  /** Detect DOM document object */
+  var doc = isHostType(window, 'document') && document;
+
+  /** Detect free variable `define` */
+  var freeDefine = typeof define == 'function' &&
+    typeof define.amd == 'object' && define.amd && define;
+
+  /** Detect free variable `exports` */
+  var freeExports = typeof exports == 'object' && exports &&
+    (typeof global == 'object' && global && global == global.global && (window = global), exports);
+
+  /** Detect free variable `require` */
+  var freeRequire = typeof require == 'function' && require;
+
+  /** Used to crawl all properties regardless of enumerability */
+  var getAllKeys = Object.getOwnPropertyNames;
+
+  /** Used to get property descriptors */
+  var getDescriptor = Object.getOwnPropertyDescriptor;
+
+  /** Used in case an object doesn't have its own method */
+  var hasOwnProperty = {}.hasOwnProperty;
+
+  /** Used to check if an object is extensible */
+  var isExtensible = Object.isExtensible || function() { return true; };
+
+  /** Used to access Wade Simmons' Node microtime module */
+  var microtimeObject = req('microtime');
+
+  /** Used to access the browser's high resolution timer */
+  var perfObject = isHostType(window, 'performance') && performance;
+
+  /** Used to call the browser's high resolution timer */
+  var perfName = perfObject && (
+    perfObject.now && 'now' ||
+    perfObject.webkitNow && 'webkitNow'
+  );
+
+  /** Used to access Node's high resolution timer */
+  var processObject = isHostType(window, 'process') && process;
+
+  /** Used to check if an own property is enumerable */
+  var propertyIsEnumerable = {}.propertyIsEnumerable;
+
+  /** Used to set property descriptors */
+  var setDescriptor = Object.defineProperty;
+
+  /** Used to resolve a value's internal [[Class]] */
+  var toString = {}.toString;
+
+  /** Used to prevent a `removeChild` memory leak in IE < 9 */
+  var trash = doc && doc.createElement('div');
+
+  /** Used to integrity check compiled tests */
+  var uid = 'uid' + (+new Date);
+
+  /** Used to avoid infinite recursion when methods call each other */
+  var calledBy = {};
+
+  /** Used to avoid hz of Infinity */
+  var divisors = {
+    '1': 4096,
+    '2': 512,
+    '3': 64,
+    '4': 8,
+    '5': 0
+  };
+
+  /**
+   * T-Distribution two-tailed critical values for 95% confidence
+   * http://www.itl.nist.gov/div898/handbook/eda/section3/eda3672.htm
+   */
+  var tTable = {
+    '1':  12.706,'2':  4.303, '3':  3.182, '4':  2.776, '5':  2.571, '6':  2.447,
+    '7':  2.365, '8':  2.306, '9':  2.262, '10': 2.228, '11': 2.201, '12': 2.179,
+    '13': 2.16,  '14': 2.145, '15': 2.131, '16': 2.12,  '17': 2.11,  '18': 2.101,
+    '19': 2.093, '20': 2.086, '21': 2.08,  '22': 2.074, '23': 2.069, '24': 2.064,
+    '25': 2.06,  '26': 2.056, '27': 2.052, '28': 2.048, '29': 2.045, '30': 2.042,
+    'infinity': 1.96
+  };
+
+  /**
+   * Critical Mann-Whitney U-values for 95% confidence
+   * http://www.saburchill.com/IBbiology/stats/003.html
+   */
+  var uTable = {
+    '5':  [0, 1, 2],
+    '6':  [1, 2, 3, 5],
+    '7':  [1, 3, 5, 6, 8],
+    '8':  [2, 4, 6, 8, 10, 13],
+    '9':  [2, 4, 7, 10, 12, 15, 17],
+    '10': [3, 5, 8, 11, 14, 17, 20, 23],
+    '11': [3, 6, 9, 13, 16, 19, 23, 26, 30],
+    '12': [4, 7, 11, 14, 18, 22, 26, 29, 33, 37],
+    '13': [4, 8, 12, 16, 20, 24, 28, 33, 37, 41, 45],
+    '14': [5, 9, 13, 17, 22, 26, 31, 36, 40, 45, 50, 55],
+    '15': [5, 10, 14, 19, 24, 29, 34, 39, 44, 49, 54, 59, 64],
+    '16': [6, 11, 15, 21, 26, 31, 37, 42, 47, 53, 59, 64, 70, 75],
+    '17': [6, 11, 17, 22, 28, 34, 39, 45, 51, 57, 63, 67, 75, 81, 87],
+    '18': [7, 12, 18, 24, 30, 36, 42, 48, 55, 61, 67, 74, 80, 86, 93, 99],
+    '19': [7, 13, 19, 25, 32, 38, 45, 52, 58, 65, 72, 78, 85, 92, 99, 106, 113],
+    '20': [8, 14, 20, 27, 34, 41, 48, 55, 62, 69, 76, 83, 90, 98, 105, 112, 119, 127],
+    '21': [8, 15, 22, 29, 36, 43, 50, 58, 65, 73, 80, 88, 96, 103, 111, 119, 126, 134, 142],
+    '22': [9, 16, 23, 30, 38, 45, 53, 61, 69, 77, 85, 93, 101, 109, 117, 125, 133, 141, 150, 158],
+    '23': [9, 17, 24, 32, 40, 48, 56, 64, 73, 81, 89, 98, 106, 115, 123, 132, 140, 149, 157, 166, 175],
+    '24': [10, 17, 25, 33, 42, 50, 59, 67, 76, 85, 94, 102, 111, 120, 129, 138, 147, 156, 165, 174, 183, 192],
+    '25': [10, 18, 27, 35, 44, 53, 62, 71, 80, 89, 98, 107, 117, 126, 135, 145, 154, 163, 173, 182, 192, 201, 211],
+    '26': [11, 19, 28, 37, 46, 55, 64, 74, 83, 93, 102, 112, 122, 132, 141, 151, 161, 171, 181, 191, 200, 210, 220, 230],
+    '27': [11, 20, 29, 38, 48, 57, 67, 77, 87, 97, 107, 118, 125, 138, 147, 158, 168, 178, 188, 199, 209, 219, 230, 240, 250],
+    '28': [12, 21, 30, 40, 50, 60, 70, 80, 90, 101, 111, 122, 132, 143, 154, 164, 175, 186, 196, 207, 218, 228, 239, 250, 261, 272],
+    '29': [13, 22, 32, 42, 52, 62, 73, 83, 94, 105, 116, 127, 138, 149, 160, 171, 182, 193, 204, 215, 226, 238, 249, 260, 271, 282, 294],
+    '30': [13, 23, 33, 43, 54, 65, 76, 87, 98, 109, 120, 131, 143, 154, 166, 177, 189, 200, 212, 223, 235, 247, 258, 270, 282, 293, 305, 317]
+  };
+
+  /**
+   * An object used to flag environments/features.
+   *
+   * @static
+   * @memberOf Benchmark
+   * @type Object
+   */
+  var support = {};
+
+  (function() {
+
+    /**
+     * Detect Adobe AIR.
+     *
+     * @memberOf Benchmark.support
+     * @type Boolean
+     */
+    support.air = isClassOf(window.runtime, 'ScriptBridgingProxyObject');
+
+    /**
+     * Detect if `arguments` objects have the correct internal [[Class]] value.
+     *
+     * @memberOf Benchmark.support
+     * @type Boolean
+     */
+    support.argumentsClass = isClassOf(arguments, 'Arguments');
+
+    /**
+     * Detect if in a browser environment.
+     *
+     * @memberOf Benchmark.support
+     * @type Boolean
+     */
+    support.browser = doc && isHostType(window, 'navigator');
+
+    /**
+     * Detect if strings support accessing characters by index.
+     *
+     * @memberOf Benchmark.support
+     * @type Boolean
+     */
+    support.charByIndex =
+      // IE 8 supports indexes on string literals but not string objects
+      ('x'[0] + Object('x')[0]) == 'xx';
+
+    /**
+     * Detect if strings have indexes as own properties.
+     *
+     * @memberOf Benchmark.support
+     * @type Boolean
+     */
+    support.charByOwnIndex =
+      // Narwhal, Rhino, RingoJS, IE 8, and Opera < 10.52 support indexes on
+      // strings but don't detect them as own properties
+      support.charByIndex && hasKey('x', '0');
+
+    /**
+     * Detect if Java is enabled/exposed.
+     *
+     * @memberOf Benchmark.support
+     * @type Boolean
+     */
+    support.java = isClassOf(window.java, 'JavaPackage');
+
+    /**
+     * Detect if the Timers API exists.
+     *
+     * @memberOf Benchmark.support
+     * @type Boolean
+     */
+    support.timeout = isHostType(window, 'setTimeout') && isHostType(window, 'clearTimeout');
+
+    /**
+     * Detect if functions support decompilation.
+     *
+     * @name decompilation
+     * @memberOf Benchmark.support
+     * @type Boolean
+     */
+    try {
+      // Safari 2.x removes commas in object literals
+      // from Function#toString results
+      // http://webk.it/11609
+      // Firefox 3.6 and Opera 9.25 strip grouping
+      // parentheses from Function#toString results
+      // http://bugzil.la/559438
+      support.decompilation = Function(
+        'return (' + (function(x) { return { 'x': '' + (1 + x) + '', 'y': 0 }; }) + ')'
+      )()(0).x === '1';
+    } catch(e) {
+      support.decompilation = false;
+    }
+
+    /**
+     * Detect ES5+ property descriptor API.
+     *
+     * @name descriptors
+     * @memberOf Benchmark.support
+     * @type Boolean
+     */
+    try {
+      var o = {};
+      support.descriptors = (setDescriptor(o, o, o), 'value' in getDescriptor(o, o));
+    } catch(e) {
+      support.descriptors = false;
+    }
+
+    /**
+     * Detect ES5+ Object.getOwnPropertyNames().
+     *
+     * @name getAllKeys
+     * @memberOf Benchmark.support
+     * @type Boolean
+     */
+    try {
+      support.getAllKeys = /\bvalueOf\b/.test(getAllKeys(Object.prototype));
+    } catch(e) {
+      support.getAllKeys = false;
+    }
+
+    /**
+     * Detect if own properties are iterated before inherited properties (all but IE < 9).
+     *
+     * @name iteratesOwnLast
+     * @memberOf Benchmark.support
+     * @type Boolean
+     */
+    support.iteratesOwnFirst = (function() {
+      var props = [];
+      function ctor() { this.x = 1; }
+      ctor.prototype = { 'y': 1 };
+      for (var prop in new ctor) { props.push(prop); }
+      return props[0] == 'x';
+    }());
+
+    /**
+     * Detect if a node's [[Class]] is resolvable (all but IE < 9)
+     * and that the JS engine errors when attempting to coerce an object to a
+     * string without a `toString` property value of `typeof` "function".
+     *
+     * @name nodeClass
+     * @memberOf Benchmark.support
+     * @type Boolean
+     */
+    try {
+      support.nodeClass = ({ 'toString': 0 } + '', toString.call(doc || 0) != '[object Object]');
+    } catch(e) {
+      support.nodeClass = true;
+    }
+  }());
+
+  /**
+   * Timer object used by `clock()` and `Deferred#resolve`.
+   *
+   * @private
+   * @type Object
+   */
+  var timer = {
+
+   /**
+    * The timer namespace object or constructor.
+    *
+    * @private
+    * @memberOf timer
+    * @type Function|Object
+    */
+    'ns': Date,
+
+   /**
+    * Starts the deferred timer.
+    *
+    * @private
+    * @memberOf timer
+    * @param {Object} deferred The deferred instance.
+    */
+    'start': null, // lazy defined in `clock()`
+
+   /**
+    * Stops the deferred timer.
+    *
+    * @private
+    * @memberOf timer
+    * @param {Object} deferred The deferred instance.
+    */
+    'stop': null // lazy defined in `clock()`
+  };
+
+  /** Shortcut for inverse results */
+  var noArgumentsClass = !support.argumentsClass,
+      noCharByIndex = !support.charByIndex,
+      noCharByOwnIndex = !support.charByOwnIndex;
+
+  /** Math shortcuts */
+  var abs   = Math.abs,
+      floor = Math.floor,
+      max   = Math.max,
+      min   = Math.min,
+      pow   = Math.pow,
+      sqrt  = Math.sqrt;
+
+  /*--------------------------------------------------------------------------*/
+
+  /**
+   * The Benchmark constructor.
+   *
+   * @constructor
+   * @param {String} name A name to identify the benchmark.
+   * @param {Function|String} fn The test to benchmark.
+   * @param {Object} [options={}] Options object.
+   * @example
+   *
+   * // basic usage (the `new` operator is optional)
+   * var bench = new Benchmark(fn);
+   *
+   * // or using a name first
+   * var bench = new Benchmark('foo', fn);
+   *
+   * // or with options
+   * var bench = new Benchmark('foo', fn, {
+   *
+   *   // displayed by Benchmark#toString if `name` is not available
+   *   'id': 'xyz',
+   *
+   *   // called when the benchmark starts running
+   *   'onStart': onStart,
+   *
+   *   // called after each run cycle
+   *   'onCycle': onCycle,
+   *
+   *   // called when aborted
+   *   'onAbort': onAbort,
+   *
+   *   // called when a test errors
+   *   'onError': onError,
+   *
+   *   // called when reset
+   *   'onReset': onReset,
+   *
+   *   // called when the benchmark completes running
+   *   'onComplete': onComplete,
+   *
+   *   // compiled/called before the test loop
+   *   'setup': setup,
+   *
+   *   // compiled/called after the test loop
+   *   'teardown': teardown
+   * });
+   *
+   * // or name and options
+   * var bench = new Benchmark('foo', {
+   *
+   *   // a flag to indicate the benchmark is deferred
+   *   'defer': true,
+   *
+   *   // benchmark test function
+   *   'fn': function(deferred) {
+   *     // call resolve() when the deferred test is finished
+   *     deferred.resolve();
+   *   }
+   * });
+   *
+   * // or options only
+   * var bench = new Benchmark({
+   *
+   *   // benchmark name
+   *   'name': 'foo',
+   *
+   *   // benchmark test as a string
+   *   'fn': '[1,2,3,4].sort()'
+   * });
+   *
+   * // a test's `this` binding is set to the benchmark instance
+   * var bench = new Benchmark('foo', function() {
+   *   'My name is '.concat(this.name); // My name is foo
+   * });
+   */
+  function Benchmark(name, fn, options) {
+    var me = this;
+
+    // allow instance creation without the `new` operator
+    if (me == null || me.constructor != Benchmark) {
+      return new Benchmark(name, fn, options);
+    }
+    // juggle arguments
+    if (isClassOf(name, 'Object')) {
+      // 1 argument (options)
+      options = name;
+    }
+    else if (isClassOf(name, 'Function')) {
+      // 2 arguments (fn, options)
+      options = fn;
+      fn = name;
+    }
+    else if (isClassOf(fn, 'Object')) {
+      // 2 arguments (name, options)
+      options = fn;
+      fn = null;
+      me.name = name;
+    }
+    else {
+      // 3 arguments (name, fn [, options])
+      me.name = name;
+    }
+    setOptions(me, options);
+    me.id || (me.id = ++counter);
+    me.fn == null && (me.fn = fn);
+    me.stats = deepClone(me.stats);
+    me.times = deepClone(me.times);
+  }
+
+  /**
+   * The Deferred constructor.
+   *
+   * @constructor
+   * @memberOf Benchmark
+   * @param {Object} clone The cloned benchmark instance.
+   */
+  function Deferred(clone) {
+    var me = this;
+    if (me == null || me.constructor != Deferred) {
+      return new Deferred(clone);
+    }
+    me.benchmark = clone;
+    clock(me);
+  }
+
+  /**
+   * The Event constructor.
+   *
+   * @constructor
+   * @memberOf Benchmark
+   * @param {String|Object} type The event type.
+   */
+  function Event(type) {
+    var me = this;
+    return (me == null || me.constructor != Event)
+      ? new Event(type)
+      : (type instanceof Event)
+          ? type
+          : extend(me, { 'timeStamp': +new Date }, typeof type == 'string' ? { 'type': type } : type);
+  }
+
+  /**
+   * The Suite constructor.
+   *
+   * @constructor
+   * @memberOf Benchmark
+   * @param {String} name A name to identify the suite.
+   * @param {Object} [options={}] Options object.
+   * @example
+   *
+   * // basic usage (the `new` operator is optional)
+   * var suite = new Benchmark.Suite;
+   *
+   * // or using a name first
+   * var suite = new Benchmark.Suite('foo');
+   *
+   * // or with options
+   * var suite = new Benchmark.Suite('foo', {
+   *
+   *   // called when the suite starts running
+   *   'onStart': onStart,
+   *
+   *   // called between running benchmarks
+   *   'onCycle': onCycle,
+   *
+   *   // called when aborted
+   *   'onAbort': onAbort,
+   *
+   *   // called when a test errors
+   *   'onError': onError,
+   *
+   *   // called when reset
+   *   'onReset': onReset,
+   *
+   *   // called when the suite completes running
+   *   'onComplete': onComplete
+   * });
+   */
+  function Suite(name, options) {
+    var me = this;
+
+    // allow instance creation without the `new` operator
+    if (me == null || me.constructor != Suite) {
+      return new Suite(name, options);
+    }
+    // juggle arguments
+    if (isClassOf(name, 'Object')) {
+      // 1 argument (options)
+      options = name;
+    } else {
+      // 2 arguments (name [, options])
+      me.name = name;
+    }
+    setOptions(me, options);
+  }
+
+  /*--------------------------------------------------------------------------*/
+
+  /**
+   * Note: Some array methods have been implemented in plain JavaScript to avoid
+   * bugs in IE, Opera, Rhino, and Mobile Safari.
+   *
+   * IE compatibility mode and IE < 9 have buggy Array `shift()` and `splice()`
+   * functions that fail to remove the last element, `object[0]`, of
+   * array-like-objects even though the `length` property is set to `0`.
+   * The `shift()` method is buggy in IE 8 compatibility mode, while `splice()`
+   * is buggy regardless of mode in IE < 9 and buggy in compatibility mode in IE 9.
+   *
+   * In Opera < 9.50 and some older/beta Mobile Safari versions using `unshift()`
+   * generically to augment the `arguments` object will pave the value at index 0
+   * without incrimenting the other values's indexes.
+   * https://github.com/documentcloud/underscore/issues/9
+   *
+   * Rhino and environments it powers, like Narwhal and RingoJS, may have
+   * buggy Array `concat()`, `reverse()`, `shift()`, `slice()`, `splice()` and
+   * `unshift()` functions that make sparse arrays non-sparse by assigning the
+   * undefined indexes a value of undefined.
+   * https://github.com/mozilla/rhino/commit/702abfed3f8ca043b2636efd31c14ba7552603dd
+   */
+
+  /**
+   * Creates an array containing the elements of the host array followed by the
+   * elements of each argument in order.
+   *
+   * @memberOf Benchmark.Suite
+   * @returns {Array} The new array.
+   */
+  function concat() {
+    var value,
+        j = -1,
+        length = arguments.length,
+        result = slice.call(this),
+        index = result.length;
+
+    while (++j < length) {
+      value = arguments[j];
+      if (isClassOf(value, 'Array')) {
+        for (var k = 0, l = value.length; k < l; k++, index++) {
+          if (k in value) {
+            result[index] = value[k];
+          }
+        }
+      } else {
+        result[index++] = value;
+      }
+    }
+    return result;
+  }
+
+  /**
+   * Utility function used by `shift()`, `splice()`, and `unshift()`.
+   *
+   * @private
+   * @param {Number} start The index to start inserting elements.
+   * @param {Number} deleteCount The number of elements to delete from the insert point.
+   * @param {Array} elements The elements to insert.
+   * @returns {Array} An array of deleted elements.
+   */
+  function insert(start, deleteCount, elements) {
+    // `result` should have its length set to the `deleteCount`
+    // see https://bugs.ecmascript.org/show_bug.cgi?id=332
+    var deleteEnd = start + deleteCount,
+        elementCount = elements ? elements.length : 0,
+        index = start - 1,
+        length = start + elementCount,
+        object = this,
+        result = Array(deleteCount),
+        tail = slice.call(object, deleteEnd);
+
+    // delete elements from the array
+    while (++index < deleteEnd) {
+      if (index in object) {
+        result[index - start] = object[index];
+        delete object[index];
+      }
+    }
+    // insert elements
+    index = start - 1;
+    while (++index < length) {
+      object[index] = elements[index - start];
+    }
+    // append tail elements
+    start = index--;
+    length = max(0, (object.length >>> 0) - deleteCount + elementCount);
+    while (++index < length) {
+      if ((index - start) in tail) {
+        object[index] = tail[index - start];
+      } else if (index in object) {
+        delete object[index];
+      }
+    }
+    // delete excess elements
+    deleteCount = deleteCount > elementCount ? deleteCount - elementCount : 0;
+    while (deleteCount--) {
+      index = length + deleteCount;
+      if (index in object) {
+        delete object[index];
+      }
+    }
+    object.length = length;
+    return result;
+  }
+
+  /**
+   * Rearrange the host array's elements in reverse order.
+   *
+   * @memberOf Benchmark.Suite
+   * @returns {Array} The reversed array.
+   */
+  function reverse() {
+    var upperIndex,
+        value,
+        index = -1,
+        object = Object(this),
+        length = object.length >>> 0,
+        middle = floor(length / 2);
+
+    if (length > 1) {
+      while (++index < middle) {
+        upperIndex = length - index - 1;
+        value = upperIndex in object ? object[upperIndex] : uid;
+        if (index in object) {
+          object[upperIndex] = object[index];
+        } else {
+          delete object[upperIndex];
+        }
+        if (value != uid) {
+          object[index] = value;
+        } else {
+          delete object[index];
+        }
+      }
+    }
+    return object;
+  }
+
+  /**
+   * Removes the first element of the host array and returns it.
+   *
+   * @memberOf Benchmark.Suite
+   * @returns {Mixed} The first element of the array.
+   */
+  function shift() {
+    return insert.call(this, 0, 1)[0];
+  }
+
+  /**
+   * Creates an array of the host array's elements from the start index up to,
+   * but not including, the end index.
+   *
+   * @memberOf Benchmark.Suite
+   * @param {Number} start The starting index.
+   * @param {Number} end The end index.
+   * @returns {Array} The new array.
+   */
+  function slice(start, end) {
+    var index = -1,
+        object = Object(this),
+        length = object.length >>> 0,
+        result = [];
+
+    start = toInteger(start);
+    start = start < 0 ? max(length + start, 0) : min(start, length);
+    start--;
+    end = end == null ? length : toInteger(end);
+    end = end < 0 ? max(length + end, 0) : min(end, length);
+
+    while ((++index, ++start) < end) {
+      if (start in object) {
+        result[index] = object[start];
+      }
+    }
+    return result;
+  }
+
+  /**
+   * Allows removing a range of elements and/or inserting elements into the
+   * host array.
+   *
+   * @memberOf Benchmark.Suite
+   * @param {Number} start The start index.
+   * @param {Number} deleteCount The number of elements to delete.
+   * @param {Mixed} [val1, val2, ...] values to insert at the `start` index.
+   * @returns {Array} An array of removed elements.
+   */
+  function splice(start, deleteCount) {
+    var object = Object(this),
+        length = object.length >>> 0;
+
+    start = toInteger(start);
+    start = start < 0 ? max(length + start, 0) : min(start, length);
+
+    // support the de-facto SpiderMonkey extension
+    // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice#Parameters
+    // https://bugs.ecmascript.org/show_bug.cgi?id=429
+    deleteCount = arguments.length == 1
+      ? length - start
+      : min(max(toInteger(deleteCount), 0), length - start);
+
+    return insert.call(object, start, deleteCount, slice.call(arguments, 2));
+  }
+
+  /**
+   * Converts the specified `value` to an integer.
+   *
+   * @private
+   * @param {Mixed} value The value to convert.
+   * @returns {Number} The resulting integer.
+   */
+  function toInteger(value) {
+    value = +value;
+    return value === 0 || !isFinite(value) ? value || 0 : value - (value % 1);
+  }
+
+  /**
+   * Appends arguments to the host array.
+   *
+   * @memberOf Benchmark.Suite
+   * @returns {Number} The new length.
+   */
+  function unshift() {
+    var object = Object(this);
+    insert.call(object, 0, 0, arguments);
+    return object.length;
+  }
+
+  /*--------------------------------------------------------------------------*/
+
+  /**
+   * A generic `Function#bind` like method.
+   *
+   * @private
+   * @param {Function} fn The function to be bound to `thisArg`.
+   * @param {Mixed} thisArg The `this` binding for the given function.
+   * @returns {Function} The bound function.
+   */
+  function bind(fn, thisArg) {
+    return function() { fn.apply(thisArg, arguments); };
+  }
+
+  /**
+   * Creates a function from the given arguments string and body.
+   *
+   * @private
+   * @param {String} args The comma separated function arguments.
+   * @param {String} body The function body.
+   * @returns {Function} The new function.
+   */
+  function createFunction() {
+    // lazy define
+    createFunction = function(args, body) {
+      var result,
+          anchor = freeDefine ? define.amd : Benchmark,
+          prop = uid + 'createFunction';
+
+      runScript((freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '=function(' + args + '){' + body + '}');
+      result = anchor[prop];
+      delete anchor[prop];
+      return result;
+    };
+    // fix JaegerMonkey bug
+    // http://bugzil.la/639720
+    createFunction = support.browser && (createFunction('', 'return"' + uid + '"') || noop)() == uid ? createFunction : Function;
+    return createFunction.apply(null, arguments);
+  }
+
+  /**
+   * Delay the execution of a function based on the benchmark's `delay` property.
+   *
+   * @private
+   * @param {Object} bench The benchmark instance.
+   * @param {Object} fn The function to execute.
+   */
+  function delay(bench, fn) {
+    bench._timerId = setTimeout(fn, bench.delay * 1e3);
+  }
+
+  /**
+   * Destroys the given element.
+   *
+   * @private
+   * @param {Element} element The element to destroy.
+   */
+  function destroyElement(element) {
+    trash.appendChild(element);
+    trash.innerHTML = '';
+  }
+
+  /**
+   * Iterates over an object's properties, executing the `callback` for each.
+   * Callbacks may terminate the loop by explicitly returning `false`.
+   *
+   * @private
+   * @param {Object} object The object to iterate over.
+   * @param {Function} callback The function executed per own property.
+   * @param {Object} options The options object.
+   * @returns {Object} Returns the object iterated over.
+   */
+  function forProps() {
+    var forShadowed,
+        skipSeen,
+        forArgs = true,
+        shadowed = ['constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf'];
+
+    (function(enumFlag, key) {
+      // must use a non-native constructor to catch the Safari 2 issue
+      function Klass() { this.valueOf = 0; };
+      Klass.prototype.valueOf = 0;
+      // check various for-in bugs
+      for (key in new Klass) {
+        enumFlag += key == 'valueOf' ? 1 : 0;
+      }
+      // check if `arguments` objects have non-enumerable indexes
+      for (key in arguments) {
+        key == '0' && (forArgs = false);
+      }
+      // Safari 2 iterates over shadowed properties twice
+      // http://replay.waybackmachine.org/20090428222941/http://tobielangel.com/2007/1/29/for-in-loop-broken-in-safari/
+      skipSeen = enumFlag == 2;
+      // IE < 9 incorrectly makes an object's properties non-enumerable if they have
+      // the same name as other non-enumerable properties in its prototype chain.
+      forShadowed = !enumFlag;
+    }(0));
+
+    // lazy define
+    forProps = function(object, callback, options) {
+      options || (options = {});
+
+      var result = object;
+      object = Object(object);
+
+      var ctor,
+          key,
+          keys,
+          skipCtor,
+          done = !result,
+          which = options.which,
+          allFlag = which == 'all',
+          index = -1,
+          iteratee = object,
+          length = object.length,
+          ownFlag = allFlag || which == 'own',
+          seen = {},
+          skipProto = isClassOf(object, 'Function'),
+          thisArg = options.bind;
+
+      if (thisArg !== undefined) {
+        callback = bind(callback, thisArg);
+      }
+      // iterate all properties
+      if (allFlag && support.getAllKeys) {
+        for (index = 0, keys = getAllKeys(object), length = keys.length; index < length; index++) {
+          key = keys[index];
+          if (callback(object[key], key, object) === false) {
+            break;
+          }
+        }
+      }
+      // else iterate only enumerable properties
+      else {
+        for (key in object) {
+          // Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1
+          // (if the prototype or a property on the prototype has been set)
+          // incorrectly set a function's `prototype` property [[Enumerable]] value
+          // to `true`. Because of this we standardize on skipping the `prototype`
+          // property of functions regardless of their [[Enumerable]] value.
+          if ((done =
+              !(skipProto && key == 'prototype') &&
+              !(skipSeen && (hasKey(seen, key) || !(seen[key] = true))) &&
+              (!ownFlag || ownFlag && hasKey(object, key)) &&
+              callback(object[key], key, object) === false)) {
+            break;
+          }
+        }
+        // in IE < 9 strings don't support accessing characters by index
+        if (!done && (forArgs && isArguments(object) ||
+            ((noCharByIndex || noCharByOwnIndex) && isClassOf(object, 'String') &&
+              (iteratee = noCharByIndex ? object.split('') : object)))) {
+          while (++index < length) {
+            if ((done =
+                callback(iteratee[index], String(index), object) === false)) {
+              break;
+            }
+          }
+        }
+        if (!done && forShadowed) {
+          // Because IE < 9 can't set the `[[Enumerable]]` attribute of an existing
+          // property and the `constructor` property of a prototype defaults to
+          // non-enumerable, we manually skip the `constructor` property when we
+          // think we are iterating over a `prototype` object.
+          ctor = object.constructor;
+          skipCtor = ctor && ctor.prototype && ctor.prototype.constructor === ctor;
+          for (index = 0; index < 7; index++) {
+            key = shadowed[index];
+            if (!(skipCtor && key == 'constructor') &&
+                hasKey(object, key) &&
+                callback(object[key], key, object) === false) {
+              break;
+            }
+          }
+        }
+      }
+      return result;
+    };
+    return forProps.apply(null, arguments);
+  }
+
+  /**
+   * Gets the name of the first argument from a function's source.
+   *
+   * @private
+   * @param {Function} fn The function.
+   * @returns {String} The argument name.
+   */
+  function getFirstArgument(fn) {
+    return (!hasKey(fn, 'toString') &&
+      (/^[\s(]*function[^(]*\(([^\s,)]+)/.exec(fn) || 0)[1]) || '';
+  }
+
+  /**
+   * Computes the arithmetic mean of a sample.
+   *
+   * @private
+   * @param {Array} sample The sample.
+   * @returns {Number} The mean.
+   */
+  function getMean(sample) {
+    return reduce(sample, function(sum, x) {
+      return sum + x;
+    }) / sample.length || 0;
+  }
+
+  /**
+   * Gets the source code of a function.
+   *
+   * @private
+   * @param {Function} fn The function.
+   * @param {String} altSource A string used when a function's source code is unretrievable.
+   * @returns {String} The function's source code.
+   */
+  function getSource(fn, altSource) {
+    var result = altSource;
+    if (isStringable(fn)) {
+      result = String(fn);
+    } else if (support.decompilation) {
+      // escape the `{` for Firefox 1
+      result = (/^[^{]+\{([\s\S]*)}\s*$/.exec(fn) || 0)[1];
+    }
+    // trim string
+    result = (result || '').replace(/^\s+|\s+$/g, '');
+
+    // detect strings containing only the "use strict" directive
+    return /^(?:\/\*+[\w|\W]*?\*\/|\/\/.*?[\n\r\u2028\u2029]|\s)*(["'])use strict\1;?$/.test(result)
+      ? ''
+      : result;
+  }
+
+  /**
+   * Checks if a value is an `arguments` object.
+   *
+   * @private
+   * @param {Mixed} value The value to check.
+   * @returns {Boolean} Returns `true` if the value is an `arguments` object, else `false`.
+   */
+  function isArguments() {
+    // lazy define
+    isArguments = function(value) {
+      return toString.call(value) == '[object Arguments]';
+    };
+    if (noArgumentsClass) {
+      isArguments = function(value) {
+        return hasKey(value, 'callee') &&
+          !(propertyIsEnumerable && propertyIsEnumerable.call(value, 'callee'));
+      };
+    }
+    return isArguments(arguments[0]);
+  }
+
+  /**
+   * Checks if an object is of the specified class.
+   *
+   * @private
+   * @param {Mixed} value The value to check.
+   * @param {String} name The name of the class.
+   * @returns {Boolean} Returns `true` if the value is of the specified class, else `false`.
+   */
+  function isClassOf(value, name) {
+    return value != null && toString.call(value) == '[object ' + name + ']';
+  }
+
+  /**
+   * Host objects can return type values that are different from their actual
+   * data type. The objects we are concerned with usually return non-primitive
+   * types of object, function, or unknown.
+   *
+   * @private
+   * @param {Mixed} object The owner of the property.
+   * @param {String} property The property to check.
+   * @returns {Boolean} Returns `true` if the property value is a non-primitive, else `false`.
+   */
+  function isHostType(object, property) {
+    var type = object != null ? typeof object[property] : 'number';
+    return !/^(?:boolean|number|string|undefined)$/.test(type) &&
+      (type == 'object' ? !!object[property] : true);
+  }
+
+  /**
+   * Checks if a given `value` is an object created by the `Object` constructor
+   * assuming objects created by the `Object` constructor have no inherited
+   * enumerable properties and that there are no `Object.prototype` extensions.
+   *
+   * @private
+   * @param {Mixed} value The value to check.
+   * @returns {Boolean} Returns `true` if the `value` is a plain `Object` object, else `false`.
+   */
+  function isPlainObject(value) {
+    // avoid non-objects and false positives for `arguments` objects in IE < 9
+    var result = false;
+    if (!(value && typeof value == 'object') || isArguments(value)) {
+      return result;
+    }
+    // IE < 9 presents DOM nodes as `Object` objects except they have `toString`
+    // methods that are `typeof` "string" and still can coerce nodes to strings.
+    // Also check that the constructor is `Object` (i.e. `Object instanceof Object`)
+    var ctor = value.constructor;
+    if ((support.nodeClass || !(typeof value.toString != 'function' && typeof (value + '') == 'string')) &&
+        (!isClassOf(ctor, 'Function') || ctor instanceof ctor)) {
+      // In most environments an object's own properties are iterated before
+      // its inherited properties. If the last iterated property is an object's
+      // own property then there are no inherited enumerable properties.
+      if (support.iteratesOwnFirst) {
+        forProps(value, function(subValue, subKey) {
+          result = subKey;
+        });
+        return result === false || hasKey(value, result);
+      }
+      // IE < 9 iterates inherited properties before own properties. If the first
+      // iterated property is an object's own property then there are no inherited
+      // enumerable properties.
+      forProps(value, function(subValue, subKey) {
+        result = !hasKey(value, subKey);
+        return false;
+      });
+      return result === false;
+    }
+    return result;
+  }
+
+  /**
+   * Checks if a value can be safely coerced to a string.
+   *
+   * @private
+   * @param {Mixed} value The value to check.
+   * @returns {Boolean} Returns `true` if the value can be coerced, else `false`.
+   */
+  function isStringable(value) {
+    return hasKey(value, 'toString') || isClassOf(value, 'String');
+  }
+
+  /**
+   * Wraps a function and passes `this` to the original function as the
+   * first argument.
+   *
+   * @private
+   * @param {Function} fn The function to be wrapped.
+   * @returns {Function} The new function.
+   */
+  function methodize(fn) {
+    return function() {
+      var args = [this];
+      args.push.apply(args, arguments);
+      return fn.apply(null, args);
+    };
+  }
+
+  /**
+   * A no-operation function.
+   *
+   * @private
+   */
+  function noop() {
+    // no operation performed
+  }
+
+  /**
+   * A wrapper around require() to suppress `module missing` errors.
+   *
+   * @private
+   * @param {String} id The module id.
+   * @returns {Mixed} The exported module or `null`.
+   */
+  function req(id) {
+    try {
+      var result = freeExports && freeRequire(id);
+    } catch(e) { }
+    return result || null;
+  }
+
+  /**
+   * Runs a snippet of JavaScript via script injection.
+   *
+   * @private
+   * @param {String} code The code to run.
+   */
+  function runScript(code) {
+    var anchor = freeDefine ? define.amd : Benchmark,
+        script = doc.createElement('script'),
+        sibling = doc.getElementsByTagName('script')[0],
+        parent = sibling.parentNode,
+        prop = uid + 'runScript',
+        prefix = '(' + (freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '||function(){})();';
+
+    // Firefox 2.0.0.2 cannot use script injection as intended because it executes
+    // asynchronously, but that's OK because script injection is only used to avoid
+    // the previously commented JaegerMonkey bug.
+    try {
+      // remove the inserted script *before* running the code to avoid differences
+      // in the expected script element count/order of the document.
+      script.appendChild(doc.createTextNode(prefix + code));
+      anchor[prop] = function() { destroyElement(script); };
+    } catch(e) {
+      parent = parent.cloneNode(false);
+      sibling = null;
+      script.text = code;
+    }
+    parent.insertBefore(script, sibling);
+    delete anchor[prop];
+  }
+
+  /**
+   * A helper function for setting options/event handlers.
+   *
+   * @private
+   * @param {Object} bench The benchmark instance.
+   * @param {Object} [options={}] Options object.
+   */
+  function setOptions(bench, options) {
+    options = extend({}, bench.constructor.options, options);
+    bench.options = forOwn(options, function(value, key) {
+      if (value != null) {
+        // add event listeners
+        if (/^on[A-Z]/.test(key)) {
+          forEach(key.split(' '), function(key) {
+            bench.on(key.slice(2).toLowerCase(), value);
+          });
+        } else if (!hasKey(bench, key)) {
+          bench[key] = deepClone(value);
+        }
+      }
+    });
+  }
+
+  /*--------------------------------------------------------------------------*/
+
+  /**
+   * Handles cycling/completing the deferred benchmark.
+   *
+   * @memberOf Benchmark.Deferred
+   */
+  function resolve() {
+    var me = this,
+        clone = me.benchmark,
+        bench = clone._original;
+
+    if (bench.aborted) {
+      // cycle() -> clone cycle/complete event -> compute()'s invoked bench.run() cycle/complete
+      me.teardown();
+      clone.running = false;
+      cycle(me);
+    }
+    else if (++me.cycles < clone.count) {
+      // continue the test loop
+      if (support.timeout) {
+        // use setTimeout to avoid a call stack overflow if called recursively
+        setTimeout(function() { clone.compiled.call(me, timer); }, 0);
+      } else {
+        clone.compiled.call(me, timer);
+      }
+    }
+    else {
+      timer.stop(me);
+      me.teardown();
+      delay(clone, function() { cycle(me); });
+    }
+  }
+
+  /*--------------------------------------------------------------------------*/
+
+  /**
+   * A deep clone utility.
+   *
+   * @static
+   * @memberOf Benchmark
+   * @param {Mixed} value The value to clone.
+   * @returns {Mixed} The cloned value.
+   */
+  function deepClone(value) {
+    var accessor,
+        circular,
+        clone,
+        ctor,
+        descriptor,
+        extensible,
+        key,
+        length,
+        markerKey,
+        parent,
+        result,
+        source,
+        subIndex,
+        data = { 'value': value },
+        index = 0,
+        marked = [],
+        queue = { 'length': 0 },
+        unmarked = [];
+
+    /**
+     * An easily detectable decorator for cloned values.
+     */
+    function Marker(object) {
+      this.raw = object;
+    }
+
+    /**
+     * The callback used by `forProps()`.
+     */
+    function forPropsCallback(subValue, subKey) {
+      // exit early to avoid cloning the marker
+      if (subValue && subValue.constructor == Marker) {
+        return;
+      }
+      // add objects to the queue
+      if (subValue === Object(subValue)) {
+        queue[queue.length++] = { 'key': subKey, 'parent': clone, 'source': value };
+      }
+      // assign non-objects
+      else {
+        try {
+          // will throw an error in strict mode if the property is read-only
+          clone[subKey] = subValue;
+        } catch(e) { }
+      }
+    }
+
+    /**
+     * Gets an available marker key for the given object.
+     */
+    function getMarkerKey(object) {
+      // avoid collisions with existing keys
+      var result = uid;
+      while (object[result] && object[result].constructor != Marker) {
+        result += 1;
+      }
+      return result;
+    }
+
+    do {
+      key = data.key;
+      parent = data.parent;
+      source = data.source;
+      clone = value = source ? source[key] : data.value;
+      accessor = circular = descriptor = false;
+
+      // create a basic clone to filter out functions, DOM elements, and
+      // other non `Object` objects
+      if (value === Object(value)) {
+        // use custom deep clone function if available
+        if (isClassOf(value.deepClone, 'Function')) {
+          clone = value.deepClone();
+        } else {
+          ctor = value.constructor;
+          switch (toString.call(value)) {
+            case '[object Array]':
+              clone = new ctor(value.length);
+              break;
+
+            case '[object Boolean]':
+              clone = new ctor(value == true);
+              break;
+
+            case '[object Date]':
+              clone = new ctor(+value);
+              break;
+
+            case '[object Object]':
+              isPlainObject(value) && (clone = {});
+              break;
+
+            case '[object Number]':
+            case '[object String]':
+              clone = new ctor(value);
+              break;
+
+            case '[object RegExp]':
+              clone = ctor(value.source,
+                (value.global     ? 'g' : '') +
+                (value.ignoreCase ? 'i' : '') +
+                (value.multiline  ? 'm' : ''));
+          }
+        }
+        // continue clone if `value` doesn't have an accessor descriptor
+        // http://es5.github.com/#x8.10.1
+        if (clone && clone != value &&
+            !(descriptor = source && support.descriptors && getDescriptor(source, key),
+              accessor = descriptor && (descriptor.get || descriptor.set))) {
+          // use an existing clone (circular reference)
+          if ((extensible = isExtensible(value))) {
+            markerKey = getMarkerKey(value);
+            if (value[markerKey]) {
+              circular = clone = value[markerKey].raw;
+            }
+          } else {
+            // for frozen/sealed objects
+            for (subIndex = 0, length = unmarked.length; subIndex < length; subIndex++) {
+              data = unmarked[subIndex];
+              if (data.object === value) {
+                circular = clone = data.clone;
+                break;
+              }
+            }
+          }
+          if (!circular) {
+            // mark object to allow quickly detecting circular references and tie it to its clone
+            if (extensible) {
+              value[markerKey] = new Marker(clone);
+              marked.push({ 'key': markerKey, 'object': value });
+            } else {
+              // for frozen/sealed objects
+              unmarked.push({ 'clone': clone, 'object': value });
+            }
+            // iterate over object properties
+            forProps(value, forPropsCallback, { 'which': 'all' });
+          }
+        }
+      }
+      if (parent) {
+        // for custom property descriptors
+        if (accessor || (descriptor && !(descriptor.configurable && descriptor.enumerable && descriptor.writable))) {
+          if ('value' in descriptor) {
+            descriptor.value = clone;
+          }
+          setDescriptor(parent, key, descriptor);
+        }
+        // for default property descriptors
+        else {
+          parent[key] = clone;
+        }
+      } else {
+        result = clone;
+      }
+    } while ((data = queue[index++]));
+
+    // remove markers
+    for (index = 0, length = marked.length; index < length; index++) {
+      data = marked[index];
+      delete data.object[data.key];
+    }
+    return result;
+  }
+
+  /**
+   * An iteration utility for arrays and objects.
+   * Callbacks may terminate the loop by explicitly returning `false`.
+   *
+   * @static
+   * @memberOf Benchmark
+   * @param {Array|Object} object The object to iterate over.
+   * @param {Function} callback The function called per iteration.
+   * @param {Mixed} thisArg The `this` binding for the callback.
+   * @returns {Array|Object} Returns the object iterated over.
+   */
+  function each(object, callback, thisArg) {
+    var result = object;
+    object = Object(object);
+
+    var fn = callback,
+        index = -1,
+        length = object.length,
+        isSnapshot = !!(object.snapshotItem && (length = object.snapshotLength)),
+        isSplittable = (noCharByIndex || noCharByOwnIndex) && isClassOf(object, 'String'),
+        isConvertable = isSnapshot || isSplittable || 'item' in object,
+        origObject = object;
+
+    // in Opera < 10.5 `hasKey(object, 'length')` returns `false` for NodeLists
+    if (length === length >>> 0) {
+      if (isConvertable) {
+        // the third argument of the callback is the original non-array object
+        callback = function(value, index) {
+          return fn.call(this, value, index, origObject);
+        };
+        // in IE < 9 strings don't support accessing characters by index
+        if (isSplittable) {
+          object = object.split('');
+        } else {
+          object = [];
+          while (++index < length) {
+            // in Safari 2 `index in object` is always `false` for NodeLists
+            object[index] = isSnapshot ? result.snapshotItem(index) : result[index];
+          }
+        }
+      }
+      forEach(object, callback, thisArg);
+    } else {
+      forOwn(object, callback, thisArg);
+    }
+    return result;
+  }
+
+  /**
+   * Copies enumerable properties from the source(s) object to the destination object.
+   *
+   * @static
+   * @memberOf Benchmark
+   * @param {Object} destination The destination object.
+   * @param {Object} [source={}] The source object.
+   * @returns {Object} The destination object.
+   */
+  function extend(destination, source) {
+    // Chrome < 14 incorrectly sets `destination` to `undefined` when we `delete arguments[0]`
+    // http://code.google.com/p/v8/issues/detail?id=839
+    var result = destination;
+    delete arguments[0];
+
+    forEach(arguments, function(source) {
+      forProps(source, function(value, key) {
+        result[key] = value;
+      });
+    });
+    return result;
+  }
+
+  /**
+   * A generic `Array#filter` like method.
+   *
+   * @static
+   * @memberOf Benchmark
+   * @param {Array} array The array to iterate over.
+   * @param {Function|String} callback The function/alias called per iteration.
+   * @param {Mixed} thisArg The `this` binding for the callback.
+   * @returns {Array} A new array of values that passed callback filter.
+   * @example
+   *
+   * // get odd numbers
+   * Benchmark.filter([1, 2, 3, 4, 5], function(n) {
+   *   return n % 2;
+   * }); // -> [1, 3, 5];
+   *
+   * // get fastest benchmarks
+   * Benchmark.filter(benches, 'fastest');
+   *
+   * // get slowest benchmarks
+   * Benchmark.filter(benches, 'slowest');
+   *
+   * // get benchmarks that completed without erroring
+   * Benchmark.filter(benches, 'successful');
+   */
+  function filter(array, callback, thisArg) {
+    var result;
+
+    if (callback == 'successful') {
+      // callback to exclude those that are errored, unrun, or have hz of Infinity
+      callback = function(bench) { return bench.cycles && isFinite(bench.hz); };
+    }
+    else if (callback == 'fastest' || callback == 'slowest') {
+      // get successful, sort by period + margin of error, and filter fastest/slowest
+      result = filter(array, 'successful').sort(function(a, b) {
+        a = a.stats; b = b.stats;
+        return (a.mean + a.moe > b.mean + b.moe ? 1 : -1) * (callback == 'fastest' ? 1 : -1);
+      });
+      result = filter(result, function(bench) {
+        return result[0].compare(bench) == 0;
+      });
+    }
+    return result || reduce(array, function(result, value, index) {
+      return callback.call(thisArg, value, index, array) ? (result.push(value), result) : result;
+    }, []);
+  }
+
+  /**
+   * A generic `Array#forEach` like method.
+   * Callbacks may terminate the loop by explicitly returning `false`.
+   *
+   * @static
+   * @memberOf Benchmark
+   * @param {Array} array The array to iterate over.
+   * @param {Function} callback The function called per iteration.
+   * @param {Mixed} thisArg The `this` binding for the callback.
+   * @returns {Array} Returns the array iterated over.
+   */
+  function forEach(array, callback, thisArg) {
+    var index = -1,
+        length = (array = Object(array)).length >>> 0;
+
+    if (thisArg !== undefined) {
+      callback = bind(callback, thisArg);
+    }
+    while (++index < length) {
+      if (index in array &&
+          callback(array[index], index, array) === false) {
+        break;
+      }
+    }
+    return array;
+  }
+
+  /**
+   * Iterates over an object's own properties, executing the `callback` for each.
+   * Callbacks may terminate the loop by explicitly returning `false`.
+   *
+   * @static
+   * @memberOf Benchmark
+   * @param {Object} object The object to iterate over.
+   * @param {Function} callback The function executed per own property.
+   * @param {Mixed} thisArg The `this` binding for the callback.
+   * @returns {Object} Returns the object iterated over.
+   */
+  function forOwn(object, callback, thisArg) {
+    return forProps(object, callback, { 'bind': thisArg, 'which': 'own' });
+  }
+
+  /**
+   * Converts a number to a more readable comma-separated string representation.
+   *
+   * @static
+   * @memberOf Benchmark
+   * @param {Number} number The number to convert.
+   * @returns {String} The more readable string representation.
+   */
+  function formatNumber(number) {
+    number = String(number).split('.');
+    return number[0].replace(/(?=(?:\d{3})+$)(?!\b)/g, ',') +
+      (number[1] ? '.' + number[1] : '');
+  }
+
+  /**
+   * Checks if an object has the specified key as a direct property.
+   *
+   * @static
+   * @memberOf Benchmark
+   * @param {Object} object The object to check.
+   * @param {String} key The key to check for.
+   * @returns {Boolean} Returns `true` if key is a direct property, else `false`.
+   */
+  function hasKey() {
+    // lazy define for worst case fallback (not as accurate)
+    hasKey = function(object, key) {
+      var parent = object != null && (object.constructor || Object).prototype;
+      return !!parent && key in Object(object) && !(key in parent && object[key] === parent[key]);
+    };
+    // for modern browsers
+    if (isClassOf(hasOwnProperty, 'Function')) {
+      hasKey = function(object, key) {
+        return object != null && hasOwnProperty.call(object, key);
+      };
+    }
+    // for Safari 2
+    else if ({}.__proto__ == Object.prototype) {
+      hasKey = function(object, key) {
+        var result = false;
+        if (object != null) {
+          object = Object(object);
+          object.__proto__ = [object.__proto__, object.__proto__ = null, result = key in object][0];
+        }
+        return result;
+      };
+    }
+    return hasKey.apply(this, arguments);
+  }
+
+  /**
+   * A generic `Array#indexOf` like method.
+   *
+   * @static
+   * @memberOf Benchmark
+   * @param {Array} array The array to iterate over.
+   * @param {Mixed} value The value to search for.
+   * @param {Number} [fromIndex=0] The index to start searching from.
+   * @returns {Number} The index of the matched value or `-1`.
+   */
+  function indexOf(array, value, fromIndex) {
+    var index = toInteger(fromIndex),
+        length = (array = Object(array)).length >>> 0;
+
+    index = (index < 0 ? max(0, length + index) : index) - 1;
+    while (++index < length) {
+      if (index in array && value === array[index]) {
+        return index;
+      }
+    }
+    return -1;
+  }
+
+  /**
+   * Modify a string by replacing named tokens with matching object property values.
+   *
+   * @static
+   * @memberOf Benchmark
+   * @param {String} string The string to modify.
+   * @param {Object} object The template object.
+   * @returns {String} The modified string.
+   */
+  function interpolate(string, object) {
+    forOwn(object, function(value, key) {
+      // escape regexp special characters in `key`
+      string = string.replace(RegExp('#\\{' + key.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1') + '\\}', 'g'), value);
+    });
+    return string;
+  }
+
+  /**
+   * Invokes a method on all items in an array.
+   *
+   * @static
+   * @memberOf Benchmark
+   * @param {Array} benches Array of benchmarks to iterate over.
+   * @param {String|Object} name The name of the method to invoke OR options object.
+   * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the method with.
+   * @returns {Array} A new array of values returned from each method invoked.
+   * @example
+   *
+   * // invoke `reset` on all benchmarks
+   * Benchmark.invoke(benches, 'reset');
+   *
+   * // invoke `emit` with arguments
+   * Benchmark.invoke(benches, 'emit', 'complete', listener);
+   *
+   * // invoke `run(true)`, treat benchmarks as a queue, and register invoke callbacks
+   * Benchmark.invoke(benches, {
+   *
+   *   // invoke the `run` method
+   *   'name': 'run',
+   *
+   *   // pass a single argument
+   *   'args': true,
+   *
+   *   // treat as queue, removing benchmarks from front of `benches` until empty
+   *   'queued': true,
+   *
+   *   // called before any benchmarks have been invoked.
+   *   'onStart': onStart,
+   *
+   *   // called between invoking benchmarks
+   *   'onCycle': onCycle,
+   *
+   *   // called after all benchmarks have been invoked.
+   *   'onComplete': onComplete
+   * });
+   */
+  function invoke(benches, name) {
+    var args,
+        bench,
+        queued,
+        index = -1,
+        eventProps = { 'currentTarget': benches },
+        options = { 'onStart': noop, 'onCycle': noop, 'onComplete': noop },
+        result = map(benches, function(bench) { return bench; });
+
+    /**
+     * Invokes the method of the current object and if synchronous, fetches the next.
+     */
+    function execute() {
+      var listeners,
+          async = isAsync(bench);
+
+      if (async) {
+        // use `getNext` as the first listener
+        bench.on('complete', getNext);
+        listeners = bench.events.complete;
+        listeners.splice(0, 0, listeners.pop());
+      }
+      // execute method
+      result[index] = isClassOf(bench && bench[name], 'Function') ? bench[name].apply(bench, args) : undefined;
+      // if synchronous return true until finished
+      return !async && getNext();
+    }
+
+    /**
+     * Fetches the next bench or executes `onComplete` callback.
+     */
+    function getNext(event) {
+      var cycleEvent,
+          last = bench,
+          async = isAsync(last);
+
+      if (async) {
+        last.off('complete', getNext);
+        last.emit('complete');
+      }
+      // emit "cycle" event
+      eventProps.type = 'cycle';
+      eventProps.target = last;
+      cycleEvent = Event(eventProps);
+      options.onCycle.call(benches, cycleEvent);
+
+      // choose next benchmark if not exiting early
+      if (!cycleEvent.aborted && raiseIndex() !== false) {
+        bench = queued ? benches[0] : result[index];
+        if (isAsync(bench)) {
+          delay(bench, execute);
+        }
+        else if (async) {
+          // resume execution if previously asynchronous but now synchronous
+          while (execute()) { }
+        }
+        else {
+          // continue synchronous execution
+          return true;
+        }
+      } else {
+        // emit "complete" event
+        eventProps.type = 'complete';
+        options.onComplete.call(benches, Event(eventProps));
+      }
+      // When used as a listener `event.aborted = true` will cancel the rest of
+      // the "complete" listeners because they were already called above and when
+      // used as part of `getNext` the `return false` will exit the execution while-loop.
+      if (event) {
+        event.aborted = true;
+      } else {
+        return false;
+      }
+    }
+
+    /**
+     * Checks if invoking `Benchmark#run` with asynchronous cycles.
+     */
+    function isAsync(object) {
+      // avoid using `instanceof` here because of IE memory leak issues with host objects
+      var async = args[0] && args[0].async;
+      return Object(object).constructor == Benchmark && name == 'run' &&
+        ((async == null ? object.options.async : async) && support.timeout || object.defer);
+    }
+
+    /**
+     * Raises `index` to the next defined index or returns `false`.
+     */
+    function raiseIndex() {
+      var length = result.length;
+      if (queued) {
+        // if queued remove the previous bench and subsequent skipped non-entries
+        do {
+          ++index > 0 && shift.call(benches);
+        } while ((length = benches.length) && !('0' in benches));
+      }
+      else {
+        while (++index < length && !(index in result)) { }
+      }
+      // if we reached the last index then return `false`
+      return (queued ? length : index < length) ? index : (index = false);
+    }
+
+    // juggle arguments
+    if (isClassOf(name, 'String')) {
+      // 2 arguments (array, name)
+      args = slice.call(arguments, 2);
+    } else {
+      // 2 arguments (array, options)
+      options = extend(options, name);
+      name = options.name;
+      args = isClassOf(args = 'args' in options ? options.args : [], 'Array') ? args : [args];
+      queued = options.queued;
+    }
+
+    // start iterating over the array
+    if (raiseIndex() !== false) {
+      // emit "start" event
+      bench = result[index];
+      eventProps.type = 'start';
+      eventProps.target = bench;
+      options.onStart.call(benches, Event(eventProps));
+
+      // end early if the suite was aborted in an "onStart" listener
+      if (benches.aborted && benches.constructor == Suite && name == 'run') {
+        // emit "cycle" event
+        eventProps.type = 'cycle';
+        options.onCycle.call(benches, Event(eventProps));
+        // emit "complete" event
+        eventProps.type = 'complete';
+        options.onComplete.call(benches, Event(eventProps));
+      }
+      // else start
+      else {
+        if (isAsync(bench)) {
+          delay(bench, execute);
+        } else {
+          while (execute()) { }
+        }
+      }
+    }
+    return result;
+  }
+
+  /**
+   * Creates a string of joined array values or object key-value pairs.
+   *
+   * @static
+   * @memberOf Benchmark
+   * @param {Array|Object} object The object to operate on.
+   * @param {String} [separator1=','] The separator used between key-value pairs.
+   * @param {String} [separator2=': '] The separator used between keys and values.
+   * @returns {String} The joined result.
+   */
+  function join(object, separator1, separator2) {
+    var result = [],
+        length = (object = Object(object)).length,
+        arrayLike = length === length >>> 0;
+
+    separator2 || (separator2 = ': ');
+    each(object, function(value, key) {
+      result.push(arrayLike ? value : key + separator2 + value);
+    });
+    return result.join(separator1 || ',');
+  }
+
+  /**
+   * A generic `Array#map` like method.
+   *
+   * @static
+   * @memberOf Benchmark
+   * @param {Array} array The array to iterate over.
+   * @param {Function} callback The function called per iteration.
+   * @param {Mixed} thisArg The `this` binding for the callback.
+   * @returns {Array} A new array of values returned by the callback.
+   */
+  function map(array, callback, thisArg) {
+    return reduce(array, function(result, value, index) {
+      result[index] = callback.call(thisArg, value, index, array);
+      return result;
+    }, Array(Object(array).length >>> 0));
+  }
+
+  /**
+   * Retrieves the value of a specified property from all items in an array.
+   *
+   * @static
+   * @memberOf Benchmark
+   * @param {Array} array The array to iterate over.
+   * @param {String} property The property to pluck.
+   * @returns {Array} A new array of property values.
+   */
+  function pluck(array, property) {
+    return map(array, function(object) {
+      return object == null ? undefined : object[property];
+    });
+  }
+
+  /**
+   * A generic `Array#reduce` like method.
+   *
+   * @static
+   * @memberOf Benchmark
+   * @param {Array} array The array to iterate over.
+   * @param {Function} callback The function called per iteration.
+   * @param {Mixed} accumulator Initial value of the accumulator.
+   * @returns {Mixed} The accumulator.
+   */
+  function reduce(array, callback, accumulator) {
+    var noaccum = arguments.length < 3;
+    forEach(array, function(value, index) {
+      accumulator = noaccum ? (noaccum = false, value) : callback(accumulator, value, index, array);
+    });
+    return accumulator;
+  }
+
+  /*--------------------------------------------------------------------------*/
+
+  /**
+   * Aborts all benchmarks in the suite.
+   *
+   * @name abort
+   * @memberOf Benchmark.Suite
+   * @returns {Object} The suite instance.
+   */
+  function abortSuite() {
+    var event,
+        me = this,
+        resetting = calledBy.resetSuite;
+
+    if (me.running) {
+      event = Event('abort');
+      me.emit(event);
+      if (!event.cancelled || resetting) {
+        // avoid infinite recursion
+        calledBy.abortSuite = true;
+        me.reset();
+        delete calledBy.abortSuite;
+
+        if (!resetting) {
+          me.aborted = true;
+          invoke(me, 'abort');
+        }
+      }
+    }
+    return me;
+  }
+
+  /**
+   * Adds a test to the benchmark suite.
+   *
+   * @memberOf Benchmark.Suite
+   * @param {String} name A name to identify the benchmark.
+   * @param {Function|String} fn The test to benchmark.
+   * @param {Object} [options={}] Options object.
+   * @returns {Object} The benchmark instance.
+   * @example
+   *
+   * // basic usage
+   * suite.add(fn);
+   *
+   * // or using a name first
+   * suite.add('foo', fn);
+   *
+   * // or with options
+   * suite.add('foo', fn, {
+   *   'onCycle': onCycle,
+   *   'onComplete': onComplete
+   * });
+   *
+   * // or name and options
+   * suite.add('foo', {
+   *   'fn': fn,
+   *   'onCycle': onCycle,
+   *   'onComplete': onComplete
+   * });
+   *
+   * // or options only
+   * suite.add({
+   *   'name': 'foo',
+   *   'fn': fn,
+   *   'onCycle': onCycle,
+   *   'onComplete': onComplete
+   * });
+   */
+  function add(name, fn, options) {
+    var me = this,
+        bench = Benchmark(name, fn, options),
+        event = Event({ 'type': 'add', 'target': bench });
+
+    if (me.emit(event), !event.cancelled) {
+      me.push(bench);
+    }
+    return me;
+  }
+
+  /**
+   * Creates a new suite with cloned benchmarks.
+   *
+   * @name clone
+   * @memberOf Benchmark.Suite
+   * @param {Object} options Options object to overwrite cloned options.
+   * @returns {Object} The new suite instance.
+   */
+  function cloneSuite(options) {
+    var me = this,
+        result = new me.constructor(extend({}, me.options, options));
+
+    // copy own properties
+    forOwn(me, function(value, key) {
+      if (!hasKey(result, key)) {
+        result[key] = value && isClassOf(value.clone, 'Function')
+          ? value.clone()
+          : deepClone(value);
+      }
+    });
+    return result;
+  }
+
+  /**
+   * An `Array#filter` like method.
+   *
+   * @name filter
+   * @memberOf Benchmark.Suite
+   * @param {Function|String} callback The function/alias called per iteration.
+   * @returns {Object} A new suite of benchmarks that passed callback filter.
+   */
+  function filterSuite(callback) {
+    var me = this,
+        result = new me.constructor;
+
+    result.push.apply(result, filter(me, callback));
+    return result;
+  }
+
+  /**
+   * Resets all benchmarks in the suite.
+   *
+   * @name reset
+   * @memberOf Benchmark.Suite
+   * @returns {Object} The suite instance.
+   */
+  function resetSuite() {
+    var event,
+        me = this,
+        aborting = calledBy.abortSuite;
+
+    if (me.running && !aborting) {
+      // no worries, `resetSuite()` is called within `abortSuite()`
+      calledBy.resetSuite = true;
+      me.abort();
+      delete calledBy.resetSuite;
+    }
+    // reset if the state has changed
+    else if ((me.aborted || me.running) &&
+        (me.emit(event = Event('reset')), !event.cancelled)) {
+      me.running = false;
+      if (!aborting) {
+        invoke(me, 'reset');
+      }
+    }
+    return me;
+  }
+
+  /**
+   * Runs the suite.
+   *
+   * @name run
+   * @memberOf Benchmark.Suite
+   * @param {Object} [options={}] Options object.
+   * @returns {Object} The suite instance.
+   * @example
+   *
+   * // basic usage
+   * suite.run();
+   *
+   * // or with options
+   * suite.run({ 'async': true, 'queued': true });
+   */
+  function runSuite(options) {
+    var me = this;
+
+    me.reset();
+    me.running = true;
+    options || (options = {});
+
+    invoke(me, {
+      'name': 'run',
+      'args': options,
+      'queued': options.queued,
+      'onStart': function(event) {
+        me.emit(event);
+      },
+      'onCycle': function(event) {
+        var bench = event.target;
+        if (bench.error) {
+          me.emit({ 'type': 'error', 'target': bench });
+        }
+        me.emit(event);
+        event.aborted = me.aborted;
+      },
+      'onComplete': function(event) {
+        me.running = false;
+        me.emit(event);
+      }
+    });
+    return me;
+  }
+
+  /*--------------------------------------------------------------------------*/
+
+  /**
+   * Executes all registered listeners of the specified event type.
+   *
+   * @memberOf Benchmark, Benchmark.Suite
+   * @param {String|Object} type The event type or object.
+   * @returns {Mixed} Returns the return value of the last listener executed.
+   */
+  function emit(type) {
+    var listeners,
+        me = this,
+        event = Event(type),
+        events = me.events,
+        args = (arguments[0] = event, arguments);
+
+    event.currentTarget || (event.currentTarget = me);
+    event.target || (event.target = me);
+    delete event.result;
+
+    if (events && (listeners = hasKey(events, event.type) && events[event.type])) {
+      forEach(listeners.slice(), function(listener) {
+        if ((event.result = listener.apply(me, args)) === false) {
+          event.cancelled = true;
+        }
+        return !event.aborted;
+      });
+    }
+    return event.result;
+  }
+
+  /**
+   * Returns an array of event listeners for a given type that can be manipulated
+   * to add or remove listeners.
+   *
+   * @memberOf Benchmark, Benchmark.Suite
+   * @param {String} type The event type.
+   * @returns {Array} The listeners array.
+   */
+  function listeners(type) {
+    var me = this,
+        events = me.events || (me.events = {});
+
+    return hasKey(events, type) ? events[type] : (events[type] = []);
+  }
+
+  /**
+   * Unregisters a listener for the specified event type(s),
+   * or unregisters all listeners for the specified event type(s),
+   * or unregisters all listeners for all event types.
+   *
+   * @memberOf Benchmark, Benchmark.Suite
+   * @param {String} [type] The event type.
+   * @param {Function} [listener] The function to unregister.
+   * @returns {Object} The benchmark instance.
+   * @example
+   *
+   * // unregister a listener for an event type
+   * bench.off('cycle', listener);
+   *
+   * // unregister a listener for multiple event types
+   * bench.off('start cycle', listener);
+   *
+   * // unregister all listeners for an event type
+   * bench.off('cycle');
+   *
+   * // unregister all listeners for multiple event types
+   * bench.off('start cycle complete');
+   *
+   * // unregister all listeners for all event types
+   * bench.off();
+   */
+  function off(type, listener) {
+    var me = this,
+        events = me.events;
+
+    events && each(type ? type.split(' ') : events, function(listeners, type) {
+      var index;
+      if (typeof listeners == 'string') {
+        type = listeners;
+        listeners = hasKey(events, type) && events[type];
+      }
+      if (listeners) {
+        if (listener) {
+          index = indexOf(listeners, listener);
+          if (index > -1) {
+            listeners.splice(index, 1);
+          }
+        } else {
+          listeners.length = 0;
+        }
+      }
+    });
+    return me;
+  }
+
+  /**
+   * Registers a listener for the specified event type(s).
+   *
+   * @memberOf Benchmark, Benchmark.Suite
+   * @param {String} type The event type.
+   * @param {Function} listener The function to register.
+   * @returns {Object} The benchmark instance.
+   * @example
+   *
+   * // register a listener for an event type
+   * bench.on('cycle', listener);
+   *
+   * // register a listener for multiple event types
+   * bench.on('start cycle', listener);
+   */
+  function on(type, listener) {
+    var me = this,
+        events = me.events || (me.events = {});
+
+    forEach(type.split(' '), function(type) {
+      (hasKey(events, type)
+        ? events[type]
+        : (events[type] = [])
+      ).push(listener);
+    });
+    return me;
+  }
+
+  /*--------------------------------------------------------------------------*/
+
+  /**
+   * Aborts the benchmark without recording times.
+   *
+   * @memberOf Benchmark
+   * @returns {Object} The benchmark instance.
+   */
+  function abort() {
+    var event,
+        me = this,
+        resetting = calledBy.reset;
+
+    if (me.running) {
+      event = Event('abort');
+      me.emit(event);
+      if (!event.cancelled || resetting) {
+        // avoid infinite recursion
+        calledBy.abort = true;
+        me.reset();
+        delete calledBy.abort;
+
+        if (support.timeout) {
+          clearTimeout(me._timerId);
+          delete me._timerId;
+        }
+        if (!resetting) {
+          me.aborted = true;
+          me.running = false;
+        }
+      }
+    }
+    return me;
+  }
+
+  /**
+   * Creates a new benchmark using the same test and options.
+   *
+   * @memberOf Benchmark
+   * @param {Object} options Options object to overwrite cloned options.
+   * @returns {Object} The new benchmark instance.
+   * @example
+   *
+   * var bizarro = bench.clone({
+   *   'name': 'doppelganger'
+   * });
+   */
+  function clone(options) {
+    var me = this,
+        result = new me.constructor(extend({}, me, options));
+
+    // correct the `options` object
+    result.options = extend({}, me.options, options);
+
+    // copy own custom properties
+    forOwn(me, function(value, key) {
+      if (!hasKey(result, key)) {
+        result[key] = deepClone(value);
+      }
+    });
+    return result;
+  }
+
+  /**
+   * Determines if a benchmark is faster than another.
+   *
+   * @memberOf Benchmark
+   * @param {Object} other The benchmark to compare.
+   * @returns {Number} Returns `-1` if slower, `1` if faster, and `0` if indeterminate.
+   */
+  function compare(other) {
+    var critical,
+        zStat,
+        me = this,
+        sample1 = me.stats.sample,
+        sample2 = other.stats.sample,
+        size1 = sample1.length,
+        size2 = sample2.length,
+        maxSize = max(size1, size2),
+        minSize = min(size1, size2),
+        u1 = getU(sample1, sample2),
+        u2 = getU(sample2, sample1),
+        u = min(u1, u2);
+
+    function getScore(xA, sampleB) {
+      return reduce(sampleB, function(total, xB) {
+        return total + (xB > xA ? 0 : xB < xA ? 1 : 0.5);
+      }, 0);
+    }
+
+    function getU(sampleA, sampleB) {
+      return reduce(sampleA, function(total, xA) {
+        return total + getScore(xA, sampleB);
+      }, 0);
+    }
+
+    function getZ(u) {
+      return (u - ((size1 * size2) / 2)) / sqrt((size1 * size2 * (size1 + size2 + 1)) / 12);
+    }
+
+    // exit early if comparing the same benchmark
+    if (me == other) {
+      return 0;
+    }
+    // reject the null hyphothesis the two samples come from the
+    // same population (i.e. have the same median) if...
+    if (size1 + size2 > 30) {
+      // ...the z-stat is greater than 1.96 or less than -1.96
+      // http://www.statisticslectures.com/topics/mannwhitneyu/
+      zStat = getZ(u);
+      return abs(zStat) > 1.96 ? (zStat > 0 ? -1 : 1) : 0;
+    }
+    // ...the U value is less than or equal the critical U value
+    // http://www.geoib.com/mann-whitney-u-test.html
+    critical = maxSize < 5 || minSize < 3 ? 0 : uTable[maxSize][minSize - 3];
+    return u <= critical ? (u == u1 ? 1 : -1) : 0;
+  }
+
+  /**
+   * Reset properties and abort if running.
+   *
+   * @memberOf Benchmark
+   * @returns {Object} The benchmark instance.
+   */
+  function reset() {
+    var data,
+        event,
+        me = this,
+        index = 0,
+        changes = { 'length': 0 },
+        queue = { 'length': 0 };
+
+    if (me.running && !calledBy.abort) {
+      // no worries, `reset()` is called within `abort()`
+      calledBy.reset = true;
+      me.abort();
+      delete calledBy.reset;
+    }
+    else {
+      // a non-recursive solution to check if properties have changed
+      // http://www.jslab.dk/articles/non.recursive.preorder.traversal.part4
+      data = { 'destination': me, 'source': extend({}, me.constructor.prototype, me.options) };
+      do {
+        forOwn(data.source, function(value, key) {
+          var changed,
+              destination = data.destination,
+              currValue = destination[key];
+
+          if (value && typeof value == 'object') {
+            if (isClassOf(value, 'Array')) {
+              // check if an array value has changed to a non-array value
+              if (!isClassOf(currValue, 'Array')) {
+                changed = currValue = [];
+              }
+              // or has changed its length
+              if (currValue.length != value.length) {
+                changed = currValue = currValue.slice(0, value.length);
+                currValue.length = value.length;
+              }
+            }
+            // check if an object has changed to a non-object value
+            else if (!currValue || typeof currValue != 'object') {
+              changed = currValue = {};
+            }
+            // register a changed object
+            if (changed) {
+              changes[changes.length++] = { 'destination': destination, 'key': key, 'value': currValue };
+            }
+            queue[queue.length++] = { 'destination': currValue, 'source': value };
+          }
+          // register a changed primitive
+          else if (value !== currValue && !(value == null || isClassOf(value, 'Function'))) {
+            changes[changes.length++] = { 'destination': destination, 'key': key, 'value': value };
+          }
+        });
+      }
+      while ((data = queue[index++]));
+
+      // if changed emit the `reset` event and if it isn't cancelled reset the benchmark
+      if (changes.length && (me.emit(event = Event('reset')), !event.cancelled)) {
+        forEach(changes, function(data) {
+          data.destination[data.key] = data.value;
+        });
+      }
+    }
+    return me;
+  }
+
+  /**
+   * Displays relevant benchmark information when coerced to a string.
+   *
+   * @name toString
+   * @memberOf Benchmark
+   * @returns {String} A string representation of the benchmark instance.
+   */
+  function toStringBench() {
+    var me = this,
+        error = me.error,
+        hz = me.hz,
+        id = me.id,
+        stats = me.stats,
+        size = stats.sample.length,
+        pm = support.java ? '+/-' : '\xb1',
+        result = me.name || (isNaN(id) ? id : '<Test #' + id + '>');
+
+    if (error) {
+      result += ': ' + join(error);
+    } else {
+      result += ' x ' + formatNumber(hz.toFixed(hz < 100 ? 2 : 0)) + ' ops/sec ' + pm +
+        stats.rme.toFixed(2) + '% (' + size + ' run' + (size == 1 ? '' : 's') + ' sampled)';
+    }
+    return result;
+  }
+
+  /*--------------------------------------------------------------------------*/
+
+  /**
+   * Clocks the time taken to execute a test per cycle (secs).
+   *
+   * @private
+   * @param {Object} bench The benchmark instance.
+   * @returns {Number} The time taken.
+   */
+  function clock() {
+    var applet,
+        options = Benchmark.options,
+        template = { 'begin': 's$=new n$', 'end': 'r$=(new n$-s$)/1e3', 'uid': uid },
+        timers = [{ 'ns': timer.ns, 'res': max(0.0015, getRes('ms')), 'unit': 'ms' }];
+
+    // lazy define for hi-res timers
+    clock = function(clone) {
+      var deferred;
+      if (clone instanceof Deferred) {
+        deferred = clone;
+        clone = deferred.benchmark;
+      }
+
+      var bench = clone._original,
+          fn = bench.fn,
+          fnArg = deferred ? getFirstArgument(fn) || 'deferred' : '',
+          stringable = isStringable(fn);
+
+      var source = {
+        'setup': getSource(bench.setup, preprocess('m$.setup()')),
+        'fn': getSource(fn, preprocess('m$.fn(' + fnArg + ')')),
+        'fnArg': fnArg,
+        'teardown': getSource(bench.teardown, preprocess('m$.teardown()'))
+      };
+
+      var count = bench.count = clone.count,
+          decompilable = support.decompilation || stringable,
+          id = bench.id,
+          isEmpty = !(source.fn || stringable),
+          name = bench.name || (typeof id == 'number' ? '<Test #' + id + '>' : id),
+          ns = timer.ns,
+          result = 0;
+
+      // init `minTime` if needed
+      clone.minTime = bench.minTime || (bench.minTime = bench.options.minTime = options.minTime);
+
+      // repair nanosecond timer
+      // (some Chrome builds erase the `ns` variable after millions of executions)
+      if (applet) {
+        try {
+          ns.nanoTime();
+        } catch(e) {
+          // use non-element to avoid issues with libs that augment them
+          ns = timer.ns = new applet.Packages.nano;
+        }
+      }
+
+      // Compile in setup/teardown functions and the test loop.
+      // Create a new compiled test, instead of using the cached `bench.compiled`,
+      // to avoid potential engine optimizations enabled over the life of the test.
+      var compiled = bench.compiled = createFunction(preprocess('t$'), interpolate(
+        preprocess(deferred
+          ? 'var d$=this,#{fnArg}=d$,m$=d$.benchmark._original,f$=m$.fn,su$=m$.setup,td$=m$.teardown;' +
+            // when `deferred.cycles` is `0` then...
+            'if(!d$.cycles){' +
+            // set `deferred.fn`
+            'd$.fn=function(){var #{fnArg}=d$;if(typeof f$=="function"){try{#{fn}\n}catch(e$){f$(d$)}}else{#{fn}\n}};' +
+            // set `deferred.teardown`
+            'd$.teardown=function(){d$.cycles=0;if(typeof td$=="function"){try{#{teardown}\n}catch(e$){td$()}}else{#{teardown}\n}};' +
+            // execute the benchmark's `setup`
+            'if(typeof su$=="function"){try{#{setup}\n}catch(e$){su$()}}else{#{setup}\n};' +
+            // start timer
+            't$.start(d$);' +
+            // execute `deferred.fn` and return a dummy object
+            '}d$.fn();return{}'
+
+          : 'var r$,s$,m$=this,f$=m$.fn,i$=m$.count,n$=t$.ns;#{setup}\n#{begin};' +
+            'while(i$--){#{fn}\n}#{end};#{teardown}\nreturn{elapsed:r$,uid:"#{uid}"}'),
+        source
+      ));
+
+      try {
+        if (isEmpty) {
+          // Firefox may remove dead code from Function#toString results
+          // http://bugzil.la/536085
+          throw new Error('The test "' + name + '" is empty. This may be the result of dead code removal.');
+        }
+        else if (!deferred) {
+          // pretest to determine if compiled code is exits early, usually by a
+          // rogue `return` statement, by checking for a return object with the uid
+          bench.count = 1;
+          compiled = (compiled.call(bench, timer) || {}).uid == uid && compiled;
+          bench.count = count;
+        }
+      } catch(e) {
+        compiled = null;
+        clone.error = e || new Error(String(e));
+        bench.count = count;
+      }
+      // fallback when a test exits early or errors during pretest
+      if (decompilable && !compiled && !deferred && !isEmpty) {
+        compiled = createFunction(preprocess('t$'), interpolate(
+          preprocess(
+            (clone.error && !stringable
+              ? 'var r$,s$,m$=this,f$=m$.fn,i$=m$.count'
+              : 'function f$(){#{fn}\n}var r$,s$,m$=this,i$=m$.count'
+            ) +
+            ',n$=t$.ns;#{setup}\n#{begin};m$.f$=f$;while(i$--){m$.f$()}#{end};' +
+            'delete m$.f$;#{teardown}\nreturn{elapsed:r$}'
+          ),
+          source
+        ));
+
+        try {
+          // pretest one more time to check for errors
+          bench.count = 1;
+          compiled.call(bench, timer);
+          bench.compiled = compiled;
+          bench.count = count;
+          delete clone.error;
+        }
+        catch(e) {
+          bench.count = count;
+          if (clone.error) {
+            compiled = null;
+          } else {
+            bench.compiled = compiled;
+            clone.error = e || new Error(String(e));
+          }
+        }
+      }
+      // assign `compiled` to `clone` before calling in case a deferred benchmark
+      // immediately calls `deferred.resolve()`
+      clone.compiled = compiled;
+      // if no errors run the full test loop
+      if (!clone.error) {
+        result = compiled.call(deferred || bench, timer).elapsed;
+      }
+      return result;
+    };
+
+    /*------------------------------------------------------------------------*/
+
+    /**
+     * Gets the current timer's minimum resolution (secs).
+     */
+    function getRes(unit) {
+      var measured,
+          begin,
+          count = 30,
+          divisor = 1e3,
+          ns = timer.ns,
+          sample = [];
+
+      // get average smallest measurable time
+      while (count--) {
+        if (unit == 'us') {
+          divisor = 1e6;
+          if (ns.stop) {
+            ns.start();
+            while (!(measured = ns.microseconds())) { }
+          } else if (ns[perfName]) {
+            divisor = 1e3;
+            measured = Function('n', 'var r,s=n.' + perfName + '();while(!(r=n.' + perfName + '()-s)){};return r')(ns);
+          } else {
+            begin = ns();
+            while (!(measured = ns() - begin)) { }
+          }
+        }
+        else if (unit == 'ns') {
+          divisor = 1e9;
+          if (ns.nanoTime) {
+            begin = ns.nanoTime();
+            while (!(measured = ns.nanoTime() - begin)) { }
+          } else {
+            begin = (begin = ns())[0] + (begin[1] / divisor);
+            while (!(measured = ((measured = ns())[0] + (measured[1] / divisor)) - begin)) { }
+            divisor = 1;
+          }
+        }
+        else {
+          begin = new ns;
+          while (!(measured = new ns - begin)) { }
+        }
+        // check for broken timers (nanoTime may have issues)
+        // http://alivebutsleepy.srnet.cz/unreliable-system-nanotime/
+        if (measured > 0) {
+          sample.push(measured);
+        } else {
+          sample.push(Infinity);
+          break;
+        }
+      }
+      // convert to seconds
+      return getMean(sample) / divisor;
+    }
+
+    /**
+     * Replaces all occurrences of `$` with a unique number and
+     * template tokens with content.
+     */
+    function preprocess(code) {
+      return interpolate(code, template).replace(/\$/g, /\d+/.exec(uid));
+    }
+
+    /*------------------------------------------------------------------------*/
+
+    // detect nanosecond support from a Java applet
+    each(doc && doc.applets || [], function(element) {
+      return !(timer.ns = applet = 'nanoTime' in element && element);
+    });
+
+    // check type in case Safari returns an object instead of a number
+    try {
+      if (typeof timer.ns.nanoTime() == 'number') {
+        timers.push({ 'ns': timer.ns, 'res': getRes('ns'), 'unit': 'ns' });
+      }
+    } catch(e) { }
+
+    // detect Chrome's microsecond timer:
+    // enable benchmarking via the --enable-benchmarking command
+    // line switch in at least Chrome 7 to use chrome.Interval
+    try {
+      if ((timer.ns = new (window.chrome || window.chromium).Interval)) {
+        timers.push({ 'ns': timer.ns, 'res': getRes('us'), 'unit': 'us' });
+      }
+    } catch(e) { }
+
+    // detect `performance.now` microsecond resolution timer
+    if ((timer.ns = perfName && perfObject)) {
+      timers.push({ 'ns': timer.ns, 'res': getRes('us'), 'unit': 'us' });
+    }
+
+    // detect Node's nanosecond resolution timer available in Node >= 0.8
+    if (processObject && typeof (timer.ns = processObject.hrtime) == 'function') {
+      timers.push({ 'ns': timer.ns, 'res': getRes('ns'), 'unit': 'ns' });
+    }
+
+    // detect Wade Simmons' Node microtime module
+    if (microtimeObject && typeof (timer.ns = microtimeObject.now) == 'function') {
+      timers.push({ 'ns': timer.ns,  'res': getRes('us'), 'unit': 'us' });
+    }
+
+    // pick timer with highest resolution
+    timer = reduce(timers, function(timer, other) {
+      return other.res < timer.res ? other : timer;
+    });
+
+    // remove unused applet
+    if (timer.unit != 'ns' && applet) {
+      applet = destroyElement(applet);
+    }
+    // error if there are no working timers
+    if (timer.res == Infinity) {
+      throw new Error('Benchmark.js was unable to find a working timer.');
+    }
+    // use API of chosen timer
+    if (timer.unit == 'ns') {
+      if (timer.ns.nanoTime) {
+        extend(template, {
+          'begin': 's$=n$.nanoTime()',
+          'end': 'r$=(n$.nanoTime()-s$)/1e9'
+        });
+      } else {
+        extend(template, {
+          'begin': 's$=n$()',
+          'end': 'r$=n$(s$);r$=r$[0]+(r$[1]/1e9)'
+        });
+      }
+    }
+    else if (timer.unit == 'us') {
+      if (timer.ns.stop) {
+        extend(template, {
+          'begin': 's$=n$.start()',
+          'end': 'r$=n$.microseconds()/1e6'
+        });
+      } else if (perfName) {
+        extend(template, {
+          'begin': 's$=n$.' + perfName + '()',
+          'end': 'r$=(n$.' + perfName + '()-s$)/1e3'
+        });
+      } else {
+        extend(template, {
+          'begin': 's$=n$()',
+          'end': 'r$=(n$()-s$)/1e6'
+        });
+      }
+    }
+
+    // define `timer` methods
+    timer.start = createFunction(preprocess('o$'),
+      preprocess('var n$=this.ns,#{begin};o$.elapsed=0;o$.timeStamp=s$'));
+
+    timer.stop = createFunction(preprocess('o$'),
+      preprocess('var n$=this.ns,s$=o$.timeStamp,#{end};o$.elapsed=r$'));
+
+    // resolve time span required to achieve a percent uncertainty of at most 1%
+    // http://spiff.rit.edu/classes/phys273/uncert/uncert.html
+    options.minTime || (options.minTime = max(timer.res / 2 / 0.01, 0.05));
+    return clock.apply(null, arguments);
+  }
+
+  /*--------------------------------------------------------------------------*/
+
+  /**
+   * Computes stats on benchmark results.
+   *
+   * @private
+   * @param {Object} bench The benchmark instance.
+   * @param {Object} options The options object.
+   */
+  function compute(bench, options) {
+    options || (options = {});
+
+    var async = options.async,
+        elapsed = 0,
+        initCount = bench.initCount,
+        minSamples = bench.minSamples,
+        queue = [],
+        sample = bench.stats.sample;
+
+    /**
+     * Adds a clone to the queue.
+     */
+    function enqueue() {
+      queue.push(bench.clone({
+        '_original': bench,
+        'events': {
+          'abort': [update],
+          'cycle': [update],
+          'error': [update],
+          'start': [update]
+        }
+      }));
+    }
+
+    /**
+     * Updates the clone/original benchmarks to keep their data in sync.
+     */
+    function update(event) {
+      var clone = this,
+          type = event.type;
+
+      if (bench.running) {
+        if (type == 'start') {
+          // Note: `clone.minTime` prop is inited in `clock()`
+          clone.count = bench.initCount;
+        }
+        else {
+          if (type == 'error') {
+            bench.error = clone.error;
+          }
+          if (type == 'abort') {
+            bench.abort();
+            bench.emit('cycle');
+          } else {
+            event.currentTarget = event.target = bench;
+            bench.emit(event);
+          }
+        }
+      } else if (bench.aborted) {
+        // clear abort listeners to avoid triggering bench's abort/cycle again
+        clone.events.abort.length = 0;
+        clone.abort();
+      }
+    }
+
+    /**
+     * Determines if more clones should be queued or if cycling should stop.
+     */
+    function evaluate(event) {
+      var critical,
+          df,
+          mean,
+          moe,
+          rme,
+          sd,
+          sem,
+          variance,
+          clone = event.target,
+          done = bench.aborted,
+          now = +new Date,
+          size = sample.push(clone.times.period),
+          maxedOut = size >= minSamples && (elapsed += now - clone.times.timeStamp) / 1e3 > bench.maxTime,
+          times = bench.times,
+          varOf = function(sum, x) { return sum + pow(x - mean, 2); };
+
+      // exit early for aborted or unclockable tests
+      if (done || clone.hz == Infinity) {
+        maxedOut = !(size = sample.length = queue.length = 0);
+      }
+
+      if (!done) {
+        // sample mean (estimate of the population mean)
+        mean = getMean(sample);
+        // sample variance (estimate of the population variance)
+        variance = reduce(sample, varOf, 0) / (size - 1) || 0;
+        // sample standard deviation (estimate of the population standard deviation)
+        sd = sqrt(variance);
+        // standard error of the mean (a.k.a. the standard deviation of the sampling distribution of the sample mean)
+        sem = sd / sqrt(size);
+        // degrees of freedom
+        df = size - 1;
+        // critical value
+        critical = tTable[Math.round(df) || 1] || tTable.infinity;
+        // margin of error
+        moe = sem * critical;
+        // relative margin of error
+        rme = (moe / mean) * 100 || 0;
+
+        extend(bench.stats, {
+          'deviation': sd,
+          'mean': mean,
+          'moe': moe,
+          'rme': rme,
+          'sem': sem,
+          'variance': variance
+        });
+
+        // Abort the cycle loop when the minimum sample size has been collected
+        // and the elapsed time exceeds the maximum time allowed per benchmark.
+        // We don't count cycle delays toward the max time because delays may be
+        // increased by browsers that clamp timeouts for inactive tabs.
+        // https://developer.mozilla.org/en/window.setTimeout#Inactive_tabs
+        if (maxedOut) {
+          // reset the `initCount` in case the benchmark is rerun
+          bench.initCount = initCount;
+          bench.running = false;
+          done = true;
+          times.elapsed = (now - times.timeStamp) / 1e3;
+        }
+        if (bench.hz != Infinity) {
+          bench.hz = 1 / mean;
+          times.cycle = mean * bench.count;
+          times.period = mean;
+        }
+      }
+      // if time permits, increase sample size to reduce the margin of error
+      if (queue.length < 2 && !maxedOut) {
+        enqueue();
+      }
+      // abort the invoke cycle when done
+      event.aborted = done;
+    }
+
+    // init queue and begin
+    enqueue();
+    invoke(queue, {
+      'name': 'run',
+      'args': { 'async': async },
+      'queued': true,
+      'onCycle': evaluate,
+      'onComplete': function() { bench.emit('complete'); }
+    });
+  }
+
+  /*--------------------------------------------------------------------------*/
+
+  /**
+   * Cycles a benchmark until a run `count` can be established.
+   *
+   * @private
+   * @param {Object} clone The cloned benchmark instance.
+   * @param {Object} options The options object.
+   */
+  function cycle(clone, options) {
+    options || (options = {});
+
+    var deferred;
+    if (clone instanceof Deferred) {
+      deferred = clone;
+      clone = clone.benchmark;
+    }
+
+    var clocked,
+        cycles,
+        divisor,
+        event,
+        minTime,
+        period,
+        async = options.async,
+        bench = clone._original,
+        count = clone.count,
+        times = clone.times;
+
+    // continue, if not aborted between cycles
+    if (clone.running) {
+      // `minTime` is set to `Benchmark.options.minTime` in `clock()`
+      cycles = ++clone.cycles;
+      clocked = deferred ? deferred.elapsed : clock(clone);
+      minTime = clone.minTime;
+
+      if (cycles > bench.cycles) {
+        bench.cycles = cycles;
+      }
+      if (clone.error) {
+        event = Event('error');
+        event.message = clone.error;
+        clone.emit(event);
+        if (!event.cancelled) {
+          clone.abort();
+        }
+      }
+    }
+
+    // continue, if not errored
+    if (clone.running) {
+      // time taken to complete last test cycle
+      bench.times.cycle = times.cycle = clocked;
+      // seconds per operation
+      period = bench.times.period = times.period = clocked / count;
+      // ops per second
+      bench.hz = clone.hz = 1 / period;
+      // avoid working our way up to this next time
+      bench.initCount = clone.initCount = count;
+      // do we need to do another cycle?
+      clone.running = clocked < minTime;
+
+      if (clone.running) {
+        // tests may clock at `0` when `initCount` is a small number,
+        // to avoid that we set its count to something a bit higher
+        if (!clocked && (divisor = divisors[clone.cycles]) != null) {
+          count = floor(4e6 / divisor);
+        }
+        // calculate how many more iterations it will take to achive the `minTime`
+        if (count <= clone.count) {
+          count += Math.ceil((minTime - clocked) / period);
+        }
+        clone.running = count != Infinity;
+      }
+    }
+    // should we exit early?
+    event = Event('cycle');
+    clone.emit(event);
+    if (event.aborted) {
+      clone.abort();
+    }
+    // figure out what to do next
+    if (clone.running) {
+      // start a new cycle
+      clone.count = count;
+      if (deferred) {
+        clone.compiled.call(deferred, timer);
+      } else if (async) {
+        delay(clone, function() { cycle(clone, options); });
+      } else {
+        cycle(clone);
+      }
+    }
+    else {
+      // fix TraceMonkey bug associated with clock fallbacks
+      // http://bugzil.la/509069
+      if (support.browser) {
+        runScript(uid + '=1;delete ' + uid);
+      }
+      // done
+      clone.emit('complete');
+    }
+  }
+
+  /*--------------------------------------------------------------------------*/
+
+  /**
+   * Runs the benchmark.
+   *
+   * @memberOf Benchmark
+   * @param {Object} [options={}] Options object.
+   * @returns {Object} The benchmark instance.
+   * @example
+   *
+   * // basic usage
+   * bench.run();
+   *
+   * // or with options
+   * bench.run({ 'async': true });
+   */
+  function run(options) {
+    var me = this,
+        event = Event('start');
+
+    // set `running` to `false` so `reset()` won't call `abort()`
+    me.running = false;
+    me.reset();
+    me.running = true;
+
+    me.count = me.initCount;
+    me.times.timeStamp = +new Date;
+    me.emit(event);
+
+    if (!event.cancelled) {
+      options = { 'async': ((options = options && options.async) == null ? me.async : options) && support.timeout };
+
+      // for clones created within `compute()`
+      if (me._original) {
+        if (me.defer) {
+          Deferred(me);
+        } else {
+          cycle(me, options);
+        }
+      }
+      // for original benchmarks
+      else {
+        compute(me, options);
+      }
+    }
+    return me;
+  }
+
+  /*--------------------------------------------------------------------------*/
+
+  // Firefox 1 erroneously defines variable and argument names of functions on
+  // the function itself as non-configurable properties with `undefined` values.
+  // The bugginess continues as the `Benchmark` constructor has an argument
+  // named `options` and Firefox 1 will not assign a value to `Benchmark.options`,
+  // making it non-writable in the process, unless it is the first property
+  // assigned by for-in loop of `extend()`.
+  extend(Benchmark, {
+
+    /**
+     * The default options copied by benchmark instances.
+     *
+     * @static
+     * @memberOf Benchmark
+     * @type Object
+     */
+    'options': {
+
+      /**
+       * A flag to indicate that benchmark cycles will execute asynchronously
+       * by default.
+       *
+       * @memberOf Benchmark.options
+       * @type Boolean
+       */
+      'async': false,
+
+      /**
+       * A flag to indicate that the benchmark clock is deferred.
+       *
+       * @memberOf Benchmark.options
+       * @type Boolean
+       */
+      'defer': false,
+
+      /**
+       * The delay between test cycles (secs).
+       * @memberOf Benchmark.options
+       * @type Number
+       */
+      'delay': 0.005,
+
+      /**
+       * Displayed by Benchmark#toString when a `name` is not available
+       * (auto-generated if absent).
+       *
+       * @memberOf Benchmark.options
+       * @type String
+       */
+      'id': undefined,
+
+      /**
+       * The default number of times to execute a test on a benchmark's first cycle.
+       *
+       * @memberOf Benchmark.options
+       * @type Number
+       */
+      'initCount': 1,
+
+      /**
+       * The maximum time a benchmark is allowed to run before finishing (secs).
+       *
+       * Note: Cycle delays aren't counted toward the maximum time.
+       *
+       * @memberOf Benchmark.options
+       * @type Number
+       */
+      'maxTime': 5,
+
+      /**
+       * The minimum sample size required to perform statistical analysis.
+       *
+       * @memberOf Benchmark.options
+       * @type Number
+       */
+      'minSamples': 5,
+
+      /**
+       * The time needed to reduce the percent uncertainty of measurement to 1% (secs).
+       *
+       * @memberOf Benchmark.options
+       * @type Number
+       */
+      'minTime': 0,
+
+      /**
+       * The name of the benchmark.
+       *
+       * @memberOf Benchmark.options
+       * @type String
+       */
+      'name': undefined,
+
+      /**
+       * An event listener called when the benchmark is aborted.
+       *
+       * @memberOf Benchmark.options
+       * @type Function
+       */
+      'onAbort': undefined,
+
+      /**
+       * An event listener called when the benchmark completes running.
+       *
+       * @memberOf Benchmark.options
+       * @type Function
+       */
+      'onComplete': undefined,
+
+      /**
+       * An event listener called after each run cycle.
+       *
+       * @memberOf Benchmark.options
+       * @type Function
+       */
+      'onCycle': undefined,
+
+      /**
+       * An event listener called when a test errors.
+       *
+       * @memberOf Benchmark.options
+       * @type Function
+       */
+      'onError': undefined,
+
+      /**
+       * An event listener called when the benchmark is reset.
+       *
+       * @memberOf Benchmark.options
+       * @type Function
+       */
+      'onReset': undefined,
+
+      /**
+       * An event listener called when the benchmark starts running.
+       *
+       * @memberOf Benchmark.options
+       * @type Function
+       */
+      'onStart': undefined
+    },
+
+    /**
+     * Platform object with properties describing things like browser name,
+     * version, and operating system.
+     *
+     * @static
+     * @memberOf Benchmark
+     * @type Object
+     */
+    'platform': req('platform') || window.platform || {
+
+      /**
+       * The platform description.
+       *
+       * @memberOf Benchmark.platform
+       * @type String
+       */
+      'description': window.navigator && navigator.userAgent || null,
+
+      /**
+       * The name of the browser layout engine.
+       *
+       * @memberOf Benchmark.platform
+       * @type String|Null
+       */
+      'layout': null,
+
+      /**
+       * The name of the product hosting the browser.
+       *
+       * @memberOf Benchmark.platform
+       * @type String|Null
+       */
+      'product': null,
+
+      /**
+       * The name of the browser/environment.
+       *
+       * @memberOf Benchmark.platform
+       * @type String|Null
+       */
+      'name': null,
+
+      /**
+       * The name of the product's manufacturer.
+       *
+       * @memberOf Benchmark.platform
+       * @type String|Null
+       */
+      'manufacturer': null,
+
+      /**
+       * The name of the operating system.
+       *
+       * @memberOf Benchmark.platform
+       * @type String|Null
+       */
+      'os': null,
+
+      /**
+       * The alpha/beta release indicator.
+       *
+       * @memberOf Benchmark.platform
+       * @type String|Null
+       */
+      'prerelease': null,
+
+      /**
+       * The browser/environment version.
+       *
+       * @memberOf Benchmark.platform
+       * @type String|Null
+       */
+      'version': null,
+
+      /**
+       * Return platform description when the platform object is coerced to a string.
+       *
+       * @memberOf Benchmark.platform
+       * @type Function
+       * @returns {String} The platform description.
+       */
+      'toString': function() {
+        return this.description || '';
+      }
+    },
+
+    /**
+     * The semantic version number.
+     *
+     * @static
+     * @memberOf Benchmark
+     * @type String
+     */
+    'version': '1.0.0',
+
+    // an object of environment/feature detection flags
+    'support': support,
+
+    // clone objects
+    'deepClone': deepClone,
+
+    // iteration utility
+    'each': each,
+
+    // augment objects
+    'extend': extend,
+
+    // generic Array#filter
+    'filter': filter,
+
+    // generic Array#forEach
+    'forEach': forEach,
+
+    // generic own property iteration utility
+    'forOwn': forOwn,
+
+    // converts a number to a comma-separated string
+    'formatNumber': formatNumber,
+
+    // generic Object#hasOwnProperty
+    // (trigger hasKey's lazy define before assigning it to Benchmark)
+    'hasKey': (hasKey(Benchmark, ''), hasKey),
+
+    // generic Array#indexOf
+    'indexOf': indexOf,
+
+    // template utility
+    'interpolate': interpolate,
+
+    // invokes a method on each item in an array
+    'invoke': invoke,
+
+    // generic Array#join for arrays and objects
+    'join': join,
+
+    // generic Array#map
+    'map': map,
+
+    // retrieves a property value from each item in an array
+    'pluck': pluck,
+
+    // generic Array#reduce
+    'reduce': reduce
+  });
+
+  /*--------------------------------------------------------------------------*/
+
+  extend(Benchmark.prototype, {
+
+    /**
+     * The number of times a test was executed.
+     *
+     * @memberOf Benchmark
+     * @type Number
+     */
+    'count': 0,
+
+    /**
+     * The number of cycles performed while benchmarking.
+     *
+     * @memberOf Benchmark
+     * @type Number
+     */
+    'cycles': 0,
+
+    /**
+     * The number of executions per second.
+     *
+     * @memberOf Benchmark
+     * @type Number
+     */
+    'hz': 0,
+
+    /**
+     * The compiled test function.
+     *
+     * @memberOf Benchmark
+     * @type Function|String
+     */
+    'compiled': undefined,
+
+    /**
+     * The error object if the test failed.
+     *
+     * @memberOf Benchmark
+     * @type Object
+     */
+    'error': undefined,
+
+    /**
+     * The test to benchmark.
+     *
+     * @memberOf Benchmark
+     * @type Function|String
+     */
+    'fn': undefined,
+
+    /**
+     * A flag to indicate if the benchmark is aborted.
+     *
+     * @memberOf Benchmark
+     * @type Boolean
+     */
+    'aborted': false,
+
+    /**
+     * A flag to indicate if the benchmark is running.
+     *
+     * @memberOf Benchmark
+     * @type Boolean
+     */
+    'running': false,
+
+    /**
+     * Compiled into the test and executed immediately **before** the test loop.
+     *
+     * @memberOf Benchmark
+     * @type Function|String
+     * @example
+     *
+     * // basic usage
+     * var bench = Benchmark({
+     *   'setup': function() {
+     *     var c = this.count,
+     *         element = document.getElementById('container');
+     *     while (c--) {
+     *       element.appendChild(document.createElement('div'));
+     *     }
+     *   },
+     *   'fn': function() {
+     *     element.removeChild(element.lastChild);
+     *   }
+     * });
+     *
+     * // compiles to something like:
+     * var c = this.count,
+     *     element = document.getElementById('container');
+     * while (c--) {
+     *   element.appendChild(document.createElement('div'));
+     * }
+     * var start = new Date;
+     * while (count--) {
+     *   element.removeChild(element.lastChild);
+     * }
+     * var end = new Date - start;
+     *
+     * // or using strings
+     * var bench = Benchmark({
+     *   'setup': '\
+     *     var a = 0;\n\
+     *     (function() {\n\
+     *       (function() {\n\
+     *         (function() {',
+     *   'fn': 'a += 1;',
+     *   'teardown': '\
+     *          }())\n\
+     *        }())\n\
+     *      }())'
+     * });
+     *
+     * // compiles to something like:
+     * var a = 0;
+     * (function() {
+     *   (function() {
+     *     (function() {
+     *       var start = new Date;
+     *       while (count--) {
+     *         a += 1;
+     *       }
+     *       var end = new Date - start;
+     *     }())
+     *   }())
+     * }())
+     */
+    'setup': noop,
+
+    /**
+     * Compiled into the test and executed immediately **after** the test loop.
+     *
+     * @memberOf Benchmark
+     * @type Function|String
+     */
+    'teardown': noop,
+
+    /**
+     * An object of stats including mean, margin or error, and standard deviation.
+     *
+     * @memberOf Benchmark
+     * @type Object
+     */
+    'stats': {
+
+      /**
+       * The margin of error.
+       *
+       * @memberOf Benchmark#stats
+       * @type Number
+       */
+      'moe': 0,
+
+      /**
+       * The relative margin of error (expressed as a percentage of the mean).
+       *
+       * @memberOf Benchmark#stats
+       * @type Number
+       */
+      'rme': 0,
+
+      /**
+       * The standard error of the mean.
+       *
+       * @memberOf Benchmark#stats
+       * @type Number
+       */
+      'sem': 0,
+
+      /**
+       * The sample standard deviation.
+       *
+       * @memberOf Benchmark#stats
+       * @type Number
+       */
+      'deviation': 0,
+
+      /**
+       * The sample arithmetic mean.
+       *
+       * @memberOf Benchmark#stats
+       * @type Number
+       */
+      'mean': 0,
+
+      /**
+       * The array of sampled periods.
+       *
+       * @memberOf Benchmark#stats
+       * @type Array
+       */
+      'sample': [],
+
+      /**
+       * The sample variance.
+       *
+       * @memberOf Benchmark#stats
+       * @type Number
+       */
+      'variance': 0
+    },
+
+    /**
+     * An object of timing data including cycle, elapsed, period, start, and stop.
+     *
+     * @memberOf Benchmark
+     * @type Object
+     */
+    'times': {
+
+      /**
+       * The time taken to complete the last cycle (secs).
+       *
+       * @memberOf Benchmark#times
+       * @type Number
+       */
+      'cycle': 0,
+
+      /**
+       * The time taken to complete the benchmark (secs).
+       *
+       * @memberOf Benchmark#times
+       * @type Number
+       */
+      'elapsed': 0,
+
+      /**
+       * The time taken to execute the test once (secs).
+       *
+       * @memberOf Benchmark#times
+       * @type Number
+       */
+      'period': 0,
+
+      /**
+       * A timestamp of when the benchmark started (ms).
+       *
+       * @memberOf Benchmark#times
+       * @type Number
+       */
+      'timeStamp': 0
+    },
+
+    // aborts benchmark (does not record times)
+    'abort': abort,
+
+    // creates a new benchmark using the same test and options
+    'clone': clone,
+
+    // compares benchmark's hertz with another
+    'compare': compare,
+
+    // executes listeners
+    'emit': emit,
+
+    // get listeners
+    'listeners': listeners,
+
+    // unregister listeners
+    'off': off,
+
+    // register listeners
+    'on': on,
+
+    // reset benchmark properties
+    'reset': reset,
+
+    // runs the benchmark
+    'run': run,
+
+    // pretty print benchmark info
+    'toString': toStringBench
+  });
+
+  /*--------------------------------------------------------------------------*/
+
+  extend(Deferred.prototype, {
+
+    /**
+     * The deferred benchmark instance.
+     *
+     * @memberOf Benchmark.Deferred
+     * @type Object
+     */
+    'benchmark': null,
+
+    /**
+     * The number of deferred cycles performed while benchmarking.
+     *
+     * @memberOf Benchmark.Deferred
+     * @type Number
+     */
+    'cycles': 0,
+
+    /**
+     * The time taken to complete the deferred benchmark (secs).
+     *
+     * @memberOf Benchmark.Deferred
+     * @type Number
+     */
+    'elapsed': 0,
+
+    /**
+     * A timestamp of when the deferred benchmark started (ms).
+     *
+     * @memberOf Benchmark.Deferred
+     * @type Number
+     */
+    'timeStamp': 0,
+
+    // cycles/completes the deferred benchmark
+    'resolve': resolve
+  });
+
+  /*--------------------------------------------------------------------------*/
+
+  extend(Event.prototype, {
+
+    /**
+     * A flag to indicate if the emitters listener iteration is aborted.
+     *
+     * @memberOf Benchmark.Event
+     * @type Boolean
+     */
+    'aborted': false,
+
+    /**
+     * A flag to indicate if the default action is cancelled.
+     *
+     * @memberOf Benchmark.Event
+     * @type Boolean
+     */
+    'cancelled': false,
+
+    /**
+     * The object whose listeners are currently being processed.
+     *
+     * @memberOf Benchmark.Event
+     * @type Object
+     */
+    'currentTarget': undefined,
+
+    /**
+     * The return value of the last executed listener.
+     *
+     * @memberOf Benchmark.Event
+     * @type Mixed
+     */
+    'result': undefined,
+
+    /**
+     * The object to which the event was originally emitted.
+     *
+     * @memberOf Benchmark.Event
+     * @type Object
+     */
+    'target': undefined,
+
+    /**
+     * A timestamp of when the event was created (ms).
+     *
+     * @memberOf Benchmark.Event
+     * @type Number
+     */
+    'timeStamp': 0,
+
+    /**
+     * The event type.
+     *
+     * @memberOf Benchmark.Event
+     * @type String
+     */
+    'type': ''
+  });
+
+  /*--------------------------------------------------------------------------*/
+
+  /**
+   * The default options copied by suite instances.
+   *
+   * @static
+   * @memberOf Benchmark.Suite
+   * @type Object
+   */
+  Suite.options = {
+
+    /**
+     * The name of the suite.
+     *
+     * @memberOf Benchmark.Suite.options
+     * @type String
+     */
+    'name': undefined
+  };
+
+  /*--------------------------------------------------------------------------*/
+
+  extend(Suite.prototype, {
+
+    /**
+     * The number of benchmarks in the suite.
+     *
+     * @memberOf Benchmark.Suite
+     * @type Number
+     */
+    'length': 0,
+
+    /**
+     * A flag to indicate if the suite is aborted.
+     *
+     * @memberOf Benchmark.Suite
+     * @type Boolean
+     */
+    'aborted': false,
+
+    /**
+     * A flag to indicate if the suite is running.
+     *
+     * @memberOf Benchmark.Suite
+     * @type Boolean
+     */
+    'running': false,
+
+    /**
+     * An `Array#forEach` like method.
+     * Callbacks may terminate the loop by explicitly returning `false`.
+     *
+     * @memberOf Benchmark.Suite
+     * @param {Function} callback The function called per iteration.
+     * @returns {Object} The suite iterated over.
+     */
+    'forEach': methodize(forEach),
+
+    /**
+     * An `Array#indexOf` like method.
+     *
+     * @memberOf Benchmark.Suite
+     * @param {Mixed} value The value to search for.
+     * @returns {Number} The index of the matched value or `-1`.
+     */
+    'indexOf': methodize(indexOf),
+
+    /**
+     * Invokes a method on all benchmarks in the suite.
+     *
+     * @memberOf Benchmark.Suite
+     * @param {String|Object} name The name of the method to invoke OR options object.
+     * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the method with.
+     * @returns {Array} A new array of values returned from each method invoked.
+     */
+    'invoke': methodize(invoke),
+
+    /**
+     * Converts the suite of benchmarks to a string.
+     *
+     * @memberOf Benchmark.Suite
+     * @param {String} [separator=','] A string to separate each element of the array.
+     * @returns {String} The string.
+     */
+    'join': [].join,
+
+    /**
+     * An `Array#map` like method.
+     *
+     * @memberOf Benchmark.Suite
+     * @param {Function} callback The function called per iteration.
+     * @returns {Array} A new array of values returned by the callback.
+     */
+    'map': methodize(map),
+
+    /**
+     * Retrieves the value of a specified property from all benchmarks in the suite.
+     *
+     * @memberOf Benchmark.Suite
+     * @param {String} property The property to pluck.
+     * @returns {Array} A new array of property values.
+     */
+    'pluck': methodize(pluck),
+
+    /**
+     * Removes the last benchmark from the suite and returns it.
+     *
+     * @memberOf Benchmark.Suite
+     * @returns {Mixed} The removed benchmark.
+     */
+    'pop': [].pop,
+
+    /**
+     * Appends benchmarks to the suite.
+     *
+     * @memberOf Benchmark.Suite
+     * @returns {Number} The suite's new length.
+     */
+    'push': [].push,
+
+    /**
+     * Sorts the benchmarks of the suite.
+     *
+     * @memberOf Benchmark.Suite
+     * @param {Function} [compareFn=null] A function that defines the sort order.
+     * @returns {Object} The sorted suite.
+     */
+    'sort': [].sort,
+
+    /**
+     * An `Array#reduce` like method.
+     *
+     * @memberOf Benchmark.Suite
+     * @param {Function} callback The function called per iteration.
+     * @param {Mixed} accumulator Initial value of the accumulator.
+     * @returns {Mixed} The accumulator.
+     */
+    'reduce': methodize(reduce),
+
+    // aborts all benchmarks in the suite
+    'abort': abortSuite,
+
+    // adds a benchmark to the suite
+    'add': add,
+
+    // creates a new suite with cloned benchmarks
+    'clone': cloneSuite,
+
+    // executes listeners of a specified type
+    'emit': emit,
+
+    // creates a new suite of filtered benchmarks
+    'filter': filterSuite,
+
+    // get listeners
+    'listeners': listeners,
+
+    // unregister listeners
+    'off': off,
+
+   // register listeners
+    'on': on,
+
+    // resets all benchmarks in the suite
+    'reset': resetSuite,
+
+    // runs all benchmarks in the suite
+    'run': runSuite,
+
+    // array methods
+    'concat': concat,
+
+    'reverse': reverse,
+
+    'shift': shift,
+
+    'slice': slice,
+
+    'splice': splice,
+
+    'unshift': unshift
+  });
+
+  /*--------------------------------------------------------------------------*/
+
+  // expose Deferred, Event and Suite
+  extend(Benchmark, {
+    'Deferred': Deferred,
+    'Event': Event,
+    'Suite': Suite
+  });
+
+  // expose Benchmark
+  // some AMD build optimizers, like r.js, check for specific condition patterns like the following:
+  if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
+    // define as an anonymous module so, through path mapping, it can be aliased
+    define(function() {
+      return Benchmark;
+    });
+  }
+  // check for `exports` after `define` in case a build optimizer adds an `exports` object
+  else if (freeExports) {
+    // in Node.js or RingoJS v0.8.0+
+    if (typeof module == 'object' && module && module.exports == freeExports) {
+      (module.exports = Benchmark).Benchmark = Benchmark;
+    }
+    // in Narwhal or RingoJS v0.7.0-
+    else {
+      freeExports.Benchmark = Benchmark;
+    }
+  }
+  // in a browser or Rhino
+  else {
+    // use square bracket notation so Closure Compiler won't munge `Benchmark`
+    // http://code.google.com/closure/compiler/docs/api-tutorial3.html#export
+    window['Benchmark'] = Benchmark;
+  }
+
+  // trigger clock's lazy define early to avoid a security error
+  if (support.air) {
+    clock({ '_original': { 'fn': noop, 'count': 1, 'options': {} } });
+  }
+}(this));

+ 36 - 0
test/benchmark/benchmarking_float32array_accesspatterns.html

@@ -0,0 +1,36 @@
+<!DOCTYPE html>
+<html>
+<head>
+  <meta charset="utf-8">
+  <title>ThreeJS Benchmark Tests - Using Files in /src</title>
+</head>
+<body>
+
+  During this Benchmarking test the browser will be unresponsive.<br/><br/>
+
+  Benchmark output is written to the JavaScript console.  To access the JavaScript console presss Ctrl-Shift-J.
+
+  <script src="benchmark-1.0.0.js"></script>
+
+  <!-- add ThreeJS sources to test below -->
+
+  <script src="../../src/Three.js"></script>
+  <script src="../../src/math/Vector2.js"></script>
+  <script src="../../src/math/Vector3.js"></script>
+  <script src="../../src/math/Vector4.js"></script>
+  <script src="../../src/math/Box2.js"></script>
+  <script src="../../src/math/Box3.js"></script>
+  <script src="../../src/math/Plane.js"></script>
+  <script src="../../src/math/Ray.js"></script>
+  <script src="../../src/math/Sphere.js"></script>
+  <script src="../../src/math/Triangle.js"></script>
+  <script src="../../src/math/Matrix3.js"></script>
+  <script src="../../src/math/Matrix4.js"></script>
+  <script src="../../src/math/Color.js"></script>
+
+  <!-- add class-based unit tests below -->
+
+  <script src="core/Float32ArrayAccessPatterns.js"></script>
+  
+</body>
+</html>

+ 155 - 0
test/benchmark/core/Float32ArrayAccessPatterns.js

@@ -0,0 +1,155 @@
+
+var array = new Float32Array( 10000 * 3 );
+
+for( var j = 0, jl = array.length; j < jl; j ++ ) {
+	array[j] = j;
+}
+
+var vectorArray = [];
+
+for( var j = 0, jl = array.length/3; j < jl; j ++ ) {
+	vectorArray.push( new THREE.Vector3( j*3, j*3+1, j*3+2 ) );
+}
+
+var Float32ArrayCopyTest = function( array ) {
+	var x, y, z;
+	for (var i = 0, il = array.length / 3; i < il; i += 3) {
+	  x = array[i + 0];
+	  y = array[i + 1];
+	  z = array[i + 2];
+	  x *= 1.01;
+	  y *= 1.03;
+	  z *= 0.98;
+	  array[i + 0] = x;
+	  array[i + 1] = y;
+	  array[i + 2] = z;
+	}
+};
+
+var Float32ArrayDirectTest = function( array ) {
+	for (var i = 0, il = array.length / 3; i < il; i += 3) {
+	  array[i + 0] *= 1.01;
+	  array[i + 1] *= 1.03;
+	  array[i + 2] *= 0.98;
+	}
+};
+
+
+var Float32ArrayVector3CopyTest = function( array ) {
+	var value = new THREE.Vector3();
+	for (var i = 0, il = array.length / 3; i < il; i += 3) {
+	  value.x = array[i + 0];
+	  value.y = array[i + 1];
+	  value.z = array[i + 2];
+	  value.x *= 1.01;
+	  value.y *= 1.03;
+	  value.z *= 0.98;
+	  array[i + 0] = value.x;
+	  array[i + 1] = value.y;
+	  array[i + 2] = value.z;
+	}
+};
+
+var Float32ArrayArrayCopyTest = function( array ) {
+	var value2 = [0,0,0];
+	for (var i = 0, il = array.length / 3; i < il; i += 3) {
+	  value2[0] = array[i + 0];
+	  value2[1] = array[i + 1];
+	  value2[2] = array[i + 2];
+	  value2[0] *= 1.01;
+	  value2[1] *= 1.03;
+	  value2[2] *= 0.98;
+	  array[i + 0] = value2[0];
+	  array[i + 1] = value2[1];
+	  array[i + 2] = value2[2];
+	}
+};
+
+var Float32ArrayFloat32ArrayCopyTest = function( array ) {
+	var value3 = new Float32Array( 3 );
+	for (var i = 0, il = array.length / 3; i < il; i += 3) {
+	  value3[0] = array[i + 0];
+	  value3[1] = array[i + 1];
+	  value3[2] = array[i + 2];
+	  value3[0] *= 1.01;
+	  value3[1] *= 1.03;
+	  value3[2] *= 0.98;
+	  array[i + 0] = value3[0];
+	  array[i + 1] = value3[1];
+	  array[i + 2] = value3[2];
+	}
+};
+
+
+var Vector3ArrayVector3CopyTest = function( array ) {
+	var value = new THREE.Vector3();
+	for (var i = 0, il = vectorArray.length; i < il; i ++ ) {
+	  value.copy( vectorArray[i] );
+	  value.x *= 1.01;
+	  value.y *= 1.03;
+	  value.z *= 0.98;
+	  vectorArray[i].copy( value );
+	}
+};
+
+var Vector3ArrayVector3RefTest = function( array ) {
+	for (var i = 0, il = vectorArray.length; i < il; i ++ ) {
+	  var value = vectorArray[i];
+	  value.x *= 1.01;
+	  value.y *= 1.03;
+	  value.z *= 0.98;
+	}
+};
+
+var Vector3ArrayVector3DirectTest = function( array ) {
+	for (var i = 0, il = vectorArray.length; i < il; i ++ ) {
+	  vectorArray[i].x *= 1.01;
+	  vectorArray[i].y *= 1.03;
+	  vectorArray[i].z *= 0.98;
+	}
+};
+
+var suite = new Benchmark.Suite;
+
+suite.add('Float32ArrayFloat32ArrayCopyTest', function() {
+  Float32ArrayFloat32ArrayCopyTest( array );
+});
+
+suite.add('Float32DirectArray', function() {
+  Float32ArrayDirectTest( array );
+});
+
+suite.add('Float32ArrayArrayCopyTest', function() {
+  Float32ArrayArrayCopyTest( array );
+});
+
+suite.add('Float32CopyArray', function() {
+  Float32ArrayCopyTest( array );
+});
+
+suite.add('Float32ArrayVector3CopyTest', function() {
+  Float32ArrayVector3CopyTest( array );
+});
+
+suite.add('Vector3ArrayVector3Ref', function() {
+  Vector3ArrayVector3RefTest( array );
+});
+
+suite.add('Vector3ArrayVector3Direct', function() {
+  Vector3ArrayVector3DirectTest( array );
+});
+
+suite.add('Vector3ArrayVector3Copy', function() {
+  Vector3ArrayVector3CopyTest( array );
+});
+
+suite.on('cycle', function(event, bench) {
+  console.log(String(event.target));
+});
+
+suite.on('complete', function() {
+  console.log('Fastest is ' + this.filter('fastest').pluck('name'));
+  console.log( "Done" );
+});
+
+suite.run(true);

+ 0 - 41
test/sources.html

@@ -1,41 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-  <meta charset="utf-8">
-  <title>ThreeJS Test Suite - Using Files in /src</title>
-  <link rel="stylesheet" href="qunit/qunit-1.10.0.css">
-</head>
-<body>
-  <div id="qunit"></div>
-  <script src="qunit/qunit-1.10.0.js"></script>
-
-  <!-- add ThreeJS sources to test below -->
-
-  <script src="../src/Three.js"></script>
-  <script src="../src/math/Vector2.js"></script>
-  <script src="../src/math/Vector3.js"></script>
-  <script src="../src/math/Vector4.js"></script>
-  <script src="../src/math/Box2.js"></script>
-  <script src="../src/math/Box3.js"></script>
-  <script src="../src/math/Plane.js"></script>
-  <script src="../src/math/Ray.js"></script>
-  <script src="../src/math/Sphere.js"></script>
-  <script src="../src/math/Triangle.js"></script>
-  <script src="../src/math/Matrix3.js"></script>
-  <script src="../src/math/Matrix4.js"></script>
-
-  <!-- add class-based unit tests below -->
-
-  <script src="math/Constants.js"></script>
-  <script src="math/Box2.js"></script>
-  <script src="math/Box3.js"></script>
-  <script src="math/Plane.js"></script>
-  <script src="math/Ray.js"></script>
-  <script src="math/Sphere.js"></script>
-  <script src="math/Triangle.js"></script>
-  <script src="math/Vector2.js"></script>
-  <script src="math/Vector3.js"></script>
-  <script src="math/Vector4.js"></script>
-  
-</body>
-</html>

+ 0 - 0
test/math/Box2.js → test/unit/math/Box2.js


+ 10 - 0
test/math/Box3.js → test/unit/math/Box3.js

@@ -208,6 +208,16 @@ test( "isIntersectionBox", function() {
 	ok( ! b.isIntersectionBox( c ), "Passed!" );
 });
 
+test( "getBoundingSphere", function() {
+	var a = new THREE.Box3( zero3, zero3 );
+	var b = new THREE.Box3( zero3, one3 );
+	var c = new THREE.Box3( one3.clone().negate(), one3 );
+
+	ok( a.getBoundingSphere().equals( new THREE.Sphere( zero3, 0 ) ), "Passed!" );
+	ok( b.getBoundingSphere().equals( new THREE.Sphere( one3.clone().multiplyScalar( 0.5 ), Math.sqrt( 3 ) * 0.5 ) ), "Passed!" );
+	ok( c.getBoundingSphere().equals( new THREE.Sphere( zero3, Math.sqrt( 12 ) * 0.5 ) ), "Passed!" );
+});
+
 test( "intersect", function() {
 	var a = new THREE.Box3( zero3, zero3 );
 	var b = new THREE.Box3( zero3, one3 );

+ 0 - 0
test/math/Constants.js → test/unit/math/Constants.js


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


+ 231 - 0
test/unit/math/Quaternion.js

@@ -0,0 +1,231 @@
+/**
+ * @author bhouston / http://exocortex.com
+ */
+
+module( "Quaternion" );
+
+var orders = [ 'XYZ', 'YXZ', 'ZXY', 'ZYX', 'YZX', 'XZY' ];
+var eulerAngles = new THREE.Vector3( 0.1, -0.3, 0.25 );
+
+
+test( "constructor", function() {
+	var a = new THREE.Quaternion();
+	ok( a.x == 0, "Passed!" );
+	ok( a.y == 0, "Passed!" );
+	ok( a.z == 0, "Passed!" );
+	ok( a.w == 1, "Passed!" );
+
+	a = new THREE.Quaternion( x, y, z, w );
+	ok( a.x === x, "Passed!" );
+	ok( a.y === y, "Passed!" );
+	ok( a.z === z, "Passed!" );
+	ok( a.w === w, "Passed!" );
+});
+
+test( "copy", function() {
+	var a = new THREE.Quaternion( x, y, z, w );
+	var b = new THREE.Quaternion().copy( a );
+	ok( b.x == x, "Passed!" );
+	ok( b.y == y, "Passed!" );
+	ok( b.z == z, "Passed!" );
+	ok( b.w == w, "Passed!" );
+
+	// ensure that it is a true copy
+	a.x = 0;
+	a.y = -1;
+	a.z = 0;
+	a.w = -1;
+	ok( b.x == x, "Passed!" );
+	ok( b.y == y, "Passed!" );
+});
+
+test( "set", function() {
+	var a = new THREE.Quaternion();
+	ok( a.x == 0, "Passed!" );
+	ok( a.y == 0, "Passed!" );
+	ok( a.z == 0, "Passed!" );
+	ok( a.w == 1, "Passed!" );
+
+	a.set( x, y, z, w );
+	ok( a.x == x, "Passed!" );
+	ok( a.y == y, "Passed!" );
+	ok( a.z === z, "Passed!" );
+	ok( a.w === w, "Passed!" );
+});
+
+test( "setFromAxisAngle", function() {
+
+	// TODO: find cases to validate.
+	ok( true, "Passed!" );
+
+	var zero = new THREE.Quaternion();
+
+	var a = new THREE.Quaternion().setFromAxisAngle( new THREE.Vector3( 1, 0, 0 ), 0 );
+	ok( a.equals( zero ), "Passed!" );
+	a = new THREE.Quaternion().setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), 0 );
+	ok( a.equals( zero ), "Passed!" );
+	a = new THREE.Quaternion().setFromAxisAngle( new THREE.Vector3( 0, 0, 1 ), 0 );
+	ok( a.equals( zero ), "Passed!" );
+
+	var b1 = new THREE.Quaternion().setFromAxisAngle( new THREE.Vector3( 1, 0, 0 ), Math.PI );
+	ok( ! a.equals( b1 ), "Passed!" );
+	var b2 = new THREE.Quaternion().setFromAxisAngle( new THREE.Vector3( 1, 0, 0 ), -Math.PI );
+	ok( ! a.equals( b2 ), "Passed!" );
+
+	b1.multiplySelf( b2 );
+	ok( a.equals( b1 ), "Passed!" );
+});
+
+
+test( "setFromEuler/setEulerFromQuaternion", function() {
+
+	var angles = [ new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ) ];
+
+	// ensure euler conversion to/from Quaternion matches.
+	for( var i = 0; i < orders.length; i ++ ) {
+		for( var j = 0; j < angles.length; j ++ ) {
+			var eulers2 = new THREE.Vector3().setEulerFromQuaternion( new THREE.Quaternion().setFromEuler( angles[j], orders[i] ), orders[i] );
+		
+			ok( eulers2.distanceTo( angles[j] ) < 0.001, "Passed!" );
+		}
+	}
+
+});
+
+test( "setFromEuler/setFromRotationMatrix", function() {
+
+	// ensure euler conversion for Quaternion matches that of Matrix4
+	for( var i = 0; i < orders.length; i ++ ) {
+		var q = new THREE.Quaternion().setFromEuler( eulerAngles, orders[i] );
+		var m = new THREE.Matrix4().setRotationFromEuler( eulerAngles, orders[i] );
+		var q2 = new THREE.Quaternion().setFromRotationMatrix( m );
+
+		ok( q.subSelf( q2 ).length() < 0.001, "Passed!" );
+	}
+
+});
+
+test( "add/addSelf", function() {
+	var a = new THREE.Quaternion( x, y, z, w );
+	var b = new THREE.Quaternion( -x, -y, -z, -w );
+
+	a.addSelf( b );
+	ok( a.x == 0, "Passed!" );
+	ok( a.y == 0, "Passed!" );
+	ok( a.z == 0, "Passed!" );
+	ok( a.w == 0, "Passed!" );
+
+	var c = new THREE.Quaternion().add( b, b );
+	ok( c.x == -2*x, "Passed!" );
+	ok( c.y == -2*y, "Passed!" );	
+	ok( c.z == -2*z, "Passed!" );
+	ok( c.w == -2*w, "Passed!" );	
+});
+
+test( "sub/subSelf", function() {
+	var a = new THREE.Quaternion( x, y, z, w );
+	var b = new THREE.Quaternion( -x, -y, -z, -w );
+
+	a.subSelf( b );
+	ok( a.x == 2*x, "Passed!" );
+	ok( a.y == 2*y, "Passed!" );
+	ok( a.z == 2*z, "Passed!" );
+	ok( a.w == 2*w, "Passed!" );
+
+	var c = new THREE.Quaternion().sub( b, b );
+	ok( c.x == 0, "Passed!" );
+	ok( c.y == 0, "Passed!" );	
+	ok( c.z == 0, "Passed!" );
+	ok( c.w == 0, "Passed!" );	
+});
+
+test( "normalize/length/lengthSq", function() {
+	var a = new THREE.Quaternion( x, y, z, w );
+	var b = new THREE.Quaternion( -x, -y, -z, -w );
+
+	ok( a.length() != 1, "Passed!");
+	ok( a.lengthSq() != 1, "Passed!");
+	a.normalize();
+	ok( a.length() == 1, "Passed!");
+	ok( a.lengthSq() == 1, "Passed!");
+
+	a.set( 0, 0, 0, 0 );
+	ok( a.lengthSq() == 0, "Passed!");
+	ok( a.length() == 0, "Passed!");
+	a.normalize();
+	ok( a.lengthSq() == 1, "Passed!");
+	ok( a.length() == 1, "Passed!");
+});
+
+test( "inverse/conjugate", function() {
+	var a = new THREE.Quaternion( x, y, z, w );
+
+	// TODO: add better validation here.
+
+	var b = a.clone().conjugate();
+
+	ok( a.x == -b.x, "Passed!" );
+	ok( a.y == -b.y, "Passed!" );
+	ok( a.z == -b.z, "Passed!" );
+	ok( a.w == b.w, "Passed!" );
+});
+
+
+test( "multiply/multiplySelf", function() {
+	
+	var angles = [ new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ) ];
+
+	var q1 = new THREE.Quaternion().setFromEuler( angles[0], "XYZ" );
+	var q2 = new THREE.Quaternion().setFromEuler( angles[1], "XYZ" );
+	var q3 = new THREE.Quaternion().setFromEuler( angles[2], "XYZ" );
+
+	var q = new THREE.Quaternion().multiply( q1, q2 ).multiplySelf( q3 );
+
+	var m1 = new THREE.Matrix4().setRotationFromEuler( angles[0], "XYZ" );
+	var m2 = new THREE.Matrix4().setRotationFromEuler( angles[1], "XYZ" );
+	var m3 = new THREE.Matrix4().setRotationFromEuler( angles[2], "XYZ" );
+
+	var m = new THREE.Matrix4().multiply( m1, m2 ).multiplySelf( m3 );
+
+	var qFromM = new THREE.Quaternion().setFromRotationMatrix( m );
+
+	ok( q.subSelf( qFromM ).length() < 0.001, "Passed!" );
+});
+
+test( "multiplyVector3", function() {
+	
+	var angles = [ new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ) ];
+
+	// ensure euler conversion for Quaternion matches that of Matrix4
+	for( var i = 0; i < orders.length; i ++ ) {
+		for( var j = 0; j < angles.length; j ++ ) {
+			var q = new THREE.Quaternion().setFromEuler( angles[j], orders[i] );
+			var m = new THREE.Matrix4().setRotationFromEuler( angles[j], orders[i] );
+
+			var v0 = new THREE.Vector3(1, 0, 0);
+			var qv = q.multiplyVector3( v0.clone() );
+			var mv = m.multiplyVector3( v0.clone() );
+		
+			ok( qv.distanceTo( mv ) < 0.001, "Passed!" );
+		}
+	}
+
+});
+
+test( "equals", function() {
+	var a = new THREE.Quaternion( x, y, z, w );
+	var b = new THREE.Quaternion( -x, -y, -z, -w );
+	
+	ok( a.x != b.x, "Passed!" );
+	ok( a.y != b.y, "Passed!" );
+
+	ok( ! a.equals( b ), "Passed!" );
+	ok( ! b.equals( a ), "Passed!" );
+
+	a.copy( b );
+	ok( a.x == b.x, "Passed!" );
+	ok( a.y == b.y, "Passed!" );
+
+	ok( a.equals( b ), "Passed!" );
+	ok( b.equals( a ), "Passed!" );
+});

+ 0 - 0
test/math/Ray.js → test/unit/math/Ray.js


+ 4 - 4
test/math/Sphere.js → test/unit/math/Sphere.js

@@ -67,13 +67,13 @@ test( "clampPoint", function() {
 	ok( a.clampPoint( new THREE.Vector3( 1, 1, -3 ) ).equals( new THREE.Vector3( 1, 1, 0 ) ), "Passed!" );
 });
 
-test( "bounds", function() {
+test( "getBoundingBox", function() {
 	var a = new THREE.Sphere( one3, 1 );
 
-	ok( a.bounds().equals( new THREE.Box3( zero3, two3 ) ), "Passed!" );
+	ok( a.getBoundingBox().equals( new THREE.Box3( zero3, two3 ) ), "Passed!" );
 
 	a.set( zero3, 0 )
-	ok( a.bounds().equals( new THREE.Box3( zero3, zero3 ) ), "Passed!" );
+	ok( a.getBoundingBox().equals( new THREE.Box3( zero3, zero3 ) ), "Passed!" );
 });
 
 test( "transform", function() {
@@ -83,7 +83,7 @@ test( "transform", function() {
 	var t1 = new THREE.Vector3( 1, -2, 1 );
 	m.makeTranslation( t1 );
 
-	ok( a.clone().transform( m ).bounds().equals( a.bounds().transform( m ) ), "Passed!" );
+	ok( a.clone().transform( m ).getBoundingBox().equals( a.getBoundingBox().transform( m ) ), "Passed!" );
 });
 
 test( "translate", function() {

+ 0 - 0
test/math/Triangle.js → test/unit/math/Triangle.js


+ 0 - 0
test/math/Vector2.js → test/unit/math/Vector2.js


+ 0 - 0
test/math/Vector3.js → test/unit/math/Vector3.js


+ 0 - 0
test/math/Vector4.js → test/unit/math/Vector4.js


+ 0 - 0
test/qunit/qunit-1.10.0.css → test/unit/qunit-1.10.0.css


+ 0 - 0
test/qunit/qunit-1.10.0.js → test/unit/qunit-1.10.0.js


+ 44 - 0
test/unit/unittests_sources.html

@@ -0,0 +1,44 @@
+<!DOCTYPE html>
+<html>
+<head>
+  <meta charset="utf-8">
+  <title>ThreeJS Unit Tests - Using Files in /src</title>
+  <link rel="stylesheet" href="qunit-1.10.0.css">
+</head>
+<body>
+  <div id="qunit"></div>
+  <script src="qunit-1.10.0.js"></script>
+
+  <!-- add ThreeJS sources to test below -->
+
+  <script src="../../src/Three.js"></script>
+  <script src="../../src/math/Vector2.js"></script>
+  <script src="../../src/math/Vector3.js"></script>
+  <script src="../../src/math/Vector4.js"></script>
+  <script src="../../src/math/Box2.js"></script>
+  <script src="../../src/math/Box3.js"></script>
+  <script src="../../src/math/Plane.js"></script>
+  <script src="../../src/math/Ray.js"></script>
+  <script src="../../src/math/Sphere.js"></script>
+  <script src="../../src/math/Triangle.js"></script>
+  <script src="../../src/math/Matrix3.js"></script>
+  <script src="../../src/math/Matrix4.js"></script>
+  <script src="../../src/math/Color.js"></script>
+  <script src="../../src/math/Quaternion.js"></script>
+
+  <!-- add class-based unit tests below -->
+
+  <script src="math/Constants.js"></script>
+  <script src="math/Box2.js"></script>
+  <script src="math/Box3.js"></script>
+  <script src="math/Plane.js"></script>
+  <script src="math/Ray.js"></script>
+  <script src="math/Sphere.js"></script>
+  <script src="math/Triangle.js"></script>
+  <script src="math/Vector2.js"></script>
+  <script src="math/Vector3.js"></script>
+  <script src="math/Vector4.js"></script>
+  <script src="math/Quaternion.js"></script>
+  
+</body>
+</html>

+ 6 - 5
test/three.min.html → test/unit/unittests_three-math.html

@@ -2,16 +2,16 @@
 <html>
 <head>
   <meta charset="utf-8">
-  <title>ThreeJS Test Suite - Using build/Three.min.js</title>
-  <link rel="stylesheet" href="qunit/qunit-1.10.0.css">
+  <title>ThreeJS Unit Tests - Using build/Three-math.js</title>
+  <link rel="stylesheet" href="qunit-1.10.0.css">
 </head>
 <body>
   <div id="qunit"></div>
-  <script src="qunit/qunit-1.10.0.js"></script>
+  <script src="qunit-1.10.0.js"></script>
 
   <!-- add ThreeJS sources to test below -->
 
-  <script src="../build/three.min.js"></script>
+  <script src="../../build/three-math.js"></script>
 
   <!-- add class-based unit tests below -->
 
@@ -25,6 +25,7 @@
   <script src="math/Vector2.js"></script>
   <script src="math/Vector3.js"></script>
   <script src="math/Vector4.js"></script>
-  
+  <script src="math/Quaternion.js"></script>
+
 </body>
 </html>

+ 5 - 4
test/three-math.html → test/unit/unittests_three.html

@@ -2,16 +2,16 @@
 <html>
 <head>
   <meta charset="utf-8">
-  <title>ThreeJS Test Suite - Using build/Three-math.js</title>
-  <link rel="stylesheet" href="qunit/qunit-1.10.0.css">
+  <title>ThreeJS Unit Tests - Using build/Three.js</title>
+  <link rel="stylesheet" href="qunit-1.10.0.css">
 </head>
 <body>
   <div id="qunit"></div>
-  <script src="qunit/qunit-1.10.0.js"></script>
+  <script src="qunit-1.10.0.js"></script>
 
   <!-- add ThreeJS sources to test below -->
 
-  <script src="../build/three-math.js"></script>
+  <script src="../../build/three.js"></script>
 
   <!-- add class-based unit tests below -->
 
@@ -25,6 +25,7 @@
   <script src="math/Vector2.js"></script>
   <script src="math/Vector3.js"></script>
   <script src="math/Vector4.js"></script>
+  <script src="math/Quaternion.js"></script>
   
 </body>
 </html>

+ 6 - 5
test/three.html → test/unit/unittests_three.min.html

@@ -2,16 +2,16 @@
 <html>
 <head>
   <meta charset="utf-8">
-  <title>ThreeJS Test Suite - Using build/Three.js</title>
-  <link rel="stylesheet" href="qunit/qunit-1.10.0.css">
+  <title>ThreeJS Unit Tests - Using build/Three.min.js</title>
+  <link rel="stylesheet" href="qunit-1.10.0.css">
 </head>
 <body>
   <div id="qunit"></div>
-  <script src="qunit/qunit-1.10.0.js"></script>
+  <script src="qunit-1.10.0.js"></script>
 
   <!-- add ThreeJS sources to test below -->
 
-  <script src="../build/three.js"></script>
+  <script src="../../build/three.min.js"></script>
 
   <!-- add class-based unit tests below -->
 
@@ -25,6 +25,7 @@
   <script src="math/Vector2.js"></script>
   <script src="math/Vector3.js"></script>
   <script src="math/Vector4.js"></script>
-  
+  <script src="math/Quaternion.js"></script>
+
 </body>
 </html>