Browse Source

Merge pull request #14001 from takahirox/MMDLoaderUpdate

MMDLoader clean up part2
Mr.doob 7 years ago
parent
commit
22f53d6599

+ 100 - 0
docs/examples/animations/CCDIKSolver.html

@@ -0,0 +1,100 @@
+<!DOCTYPE html>
+<html lang="en">
+	<head>
+		<meta charset="utf-8" />
+		<base href="../../" />
+		<script src="list.js"></script>
+		<script src="page.js"></script>
+		<link type="text/css" rel="stylesheet" href="page.css" />
+	</head>
+	<body>
+		<h1>[name]</h1>
+
+		<p class="desc"> A solver for IK with <a href="https://sites.google.com/site/auraliusproject/ccd-algorithm"><em>CCD Algorithm</em></a>. <br /><br />
+		[name] solves Inverse Kinematics Problem with CCD Algorithm.
+		[name] is designed to work with [page:SkinnedMesh] loaded by [page:MMDLoader] but also can be used for generic [page:SkinnedMesh].
+		</p>
+
+		<h2>Example</h2>
+
+		<code>
+		var ikSolver;
+
+		// Load MMD resources and instantiate CCDIKSolver
+		new THREE.MMDLoader().load(
+			'models/mmd/miku.pmd',
+			function ( mesh ) {
+
+				ikSolver = new CCDIKSolver( mesh, mesh.geometry.iks );
+				scene.add( mesh );
+
+			}
+		);
+
+		function render() {
+
+			animate(); // update bones
+			if ( ikSolver !== undefined ) ikSolver.update();
+			renderer.render( scene, camera );
+
+		}
+		</code>
+
+		[example:webgl_loader_mmd]<br />
+		[example:webgl_loader_mmd_pose]<br />
+		[example:webgl_loader_mmd_audio]<br />
+
+		<br />
+		<hr>
+
+		<h2>Constructor</h2>
+
+		<h3>[name]( [param:SkinnedMesh mesh], [param:Array iks] )</h3>
+		<p>
+		[page:SkinnedMesh mesh] — [page:SkinnedMesh] for which [name] solves IK problem.<br />
+		[page:Array iks] — An array of [page:Object] specifying IK parameter. target, effector, and link-index are index integers in .skeleton.bones.
+		The bones relation should be "links[ n ], links[ n - 1 ], ..., links[ 0 ], effector" in order from parent to child.<br />
+		<ul>
+			<li>[page:Integer target] — Target bone.</li>
+			<li>[page:Integer effector] — Effector bone.</li>
+			<li>[page:Array links] — An array of [page: Object] specifying link bones.
+			<ul>
+				<li>[page:Integer index] — Link bone.</li>
+				<li>[page:Vector3 limitation] — (optional) Rotation axis. Default is undefined.</li>
+				<li>[page:Boolean enabled] — (optional) Default is true.</li>
+			</ul>
+			</li>
+			<li>[page:Integer iteration] — (optional) Iteration number of calculation. Smaller is faster but less precise. Default is 1.</li>
+			<li>[page:Number minAngle] — (optional) Minimum rotation angle in a step. Default is undefined.</li>
+			<li>[page:Number maxAngle] — (optional) Maximum rotation angle in a step. Default is undefined.</li>
+		</ul>
+		</p>
+		<p>
+		Creates a new [name].
+		</p>
+
+		<h2>Properties</h2>
+
+		<h3>[property:Array iks]</h3>
+		<p>An array of IK parameter passed to the constructor.</p>
+
+		<h3>[property:SkinnedMesh mesh]</h3>
+		<p>[page:SkinnedMesh] passed to the constructor.</p>
+
+		<h2>Methods</h2>
+
+		<h3>[method:CCDIKHelper createHelper]()</h3>
+		<p>
+		Return [page:CCDIKHelper]. You can visualize IK bones by adding the helper to scene.
+		</p>
+
+		<h3>[method:CCDIKSolver update]()</h3>
+		<p>
+		Update bones quaternion by solving CCD algorithm.
+		</p>
+
+		<h2>Source</h2>
+
+		[link:https://github.com/mrdoob/three.js/blob/master/examples/js/animation/CCDIKSolver.js examples/js/animation/CCDIKSolver.js]
+	</body>
+</html>

+ 8 - 1
docs/examples/animations/MMDAnimationHelper.html

@@ -12,6 +12,7 @@
 
 		<p class="desc"> A animation helper for <a href="http://www.geocities.jp/higuchuu4/index_e.htm"><em>MMD</em></a> resources. <br /><br />
 		[name] handles animation of MMD assets loaded by [page:MMDLoader] with MMD special features as IK, Grant, and Physics.
+		It uses [page:CCDIKSolver] and [page:MMDPhysics] inside.
 		</p>
 
 		<h2>Example</h2>
@@ -31,7 +32,7 @@
 					physics: true
 				} );
 
-				scene.add( mesh );
+				scene.add( mmd.mesh );
 
 				new THREE.AudioLoader().load(
 					'audios/mmd/song.mp3',
@@ -97,6 +98,8 @@
 		<h3>[property:WeakMap objects]</h3>
 		<p>A [page:WeakMap] which holds animation stuffs used in helper for objects added to helper. For example, you can access [page:AnimationMixer] for an added [page:SkinnedMesh] with "helper.objects.get( mesh ).mixer"</p>
 
+		<h3>[property:function onBeforePhysics]</h3>
+		<p>An optional callback that is executed immediately before the physicis calculation for an [page:SkinnedMesh]. This function is called with the [page:SkinnedMesh].</p>
 
 		<h2>Methods</h2>
 
@@ -107,6 +110,10 @@
 		<ul>
 			<li>[page:AnimationClip animation] - an [page:AnimationClip] or an array of [page:AnimationClip] set to object. Only for [page:SkinnedMesh] and [page:Camera]. Default is undefined.</li>
 			<li>[page:Boolean physics] - Only for [page:SkinnedMesh]. A flag whether turn on physics. Default is true.</li>
+			<li>[page:Integer warmup] - Only for [page:SkinnedMesh] and physics is true. Physics parameter. Default is 60.</li>
+			<li>[page:Number unitStep] - Only for [page:SkinnedMesh] and physics is true. Physics parameter. Default is 1 / 65.</li>
+			<li>[page:Integer maxStepNum] - Only for [page:SkinnedMesh] and physics is true. Physics parameter. Default is 3.</li>
+			<li>[page:Vector3 gravity] - Only for [page:SkinnedMesh] and physics is true. Physics parameter. Default is ( 0, - 9.8 * 10, 0 ).</li>
 			<li>[page:Number delayTime] - Only for [page:Audio]. Default is 0.0.</li>
 		</ul>
 		</p>

+ 112 - 0
docs/examples/animations/MMDPhysics.html

@@ -0,0 +1,112 @@
+<!DOCTYPE html>
+<html lang="en">
+	<head>
+		<meta charset="utf-8" />
+		<base href="../../" />
+		<script src="list.js"></script>
+		<script src="page.js"></script>
+		<link type="text/css" rel="stylesheet" href="page.css" />
+	</head>
+	<body>
+		<h1>[name]</h1>
+
+		<p class="desc"> A Physics handler for <a href="http://www.geocities.jp/higuchuu4/index_e.htm"><em>MMD</em></a> resources. <br /><br />
+		[name] calculates Physics for model loaded by [page:MMDLoader] with <a href="https://github.com/kripken/ammo.js/">ammo.js</a> (Bullet-based JavaScript Physics engine).
+		</p>
+
+		<h2>Example</h2>
+
+		<code>
+		var physics;
+
+		// Load MMD resources and instantiate MMDPhysics
+		new THREE.MMDLoader().load(
+			'models/mmd/miku.pmd',
+			function ( mesh ) {
+
+				physics = new THREE.MMDPhysics( mesh )
+				scene.add( mesh );
+
+			}
+		);
+
+		function render() {
+
+			var delta = clock.getDelta();
+			animate( delta );  // update bones
+			if ( physics !== undefined ) physics.update( delta );
+			renderer.render( scene, camera );
+
+		}
+		</code>
+
+		[example:webgl_loader_mmd]<br />
+		[example:webgl_loader_mmd_audio]<br />
+
+		<br />
+		<hr>
+
+		<h2>Constructor</h2>
+
+		<h3>[name]( [param:SkinnedMesh mesh], [param:Array rigidBodyParams], [param:Array constraintParams], [param:Object params] )</h3>
+		<p>
+		[page:SkinnedMesh mesh] — [page:SkinnedMesh] for which [name] calculates Physics.<br />
+		[page:Array rigidBodyParams] — An array of [page:Object] specifying Rigid Body parameters.<br />
+		[page:Array constraintParams] — (optional) An array of [page:Object] specifying Constraint parameters.<br />
+		[page:Object params] — (optional)<br />
+		<ul>
+			<li>[page:Number unitStep] - Default is 1 / 65.</li>
+			<li>[page:Integer maxStepNum] - Default is 3.</li>
+			<li>[page:Vector3 gravity] - Default is ( 0, - 9.8 * 10, 0 )</li>
+		</ul>
+		</p>
+		<p>
+		Creates a new [name].
+		</p>
+
+		<h2>Properties</h2>
+
+		<h3>[property:Array mesh]</h3>
+		<p>[page:SkinnedMesh] passed to the constructor.</p>
+
+		<h2>Methods</h2>
+
+		<h3>[method:MMDPhysicsHelper createHelper]()</h3>
+		<p>
+		Return [page:MMDPhysicsHelper]. You can visualize Rigid bodies by adding the helper to scene.
+		</p>
+
+		<h3>[method:CCDIKSolver reset]()</h3>
+		<p>
+		Resets Rigid bodies transorm to current bone's.
+		</p>
+
+		<h3>[method:CCDIKSolver setGravity]( [param:Vector3 gravity] )</h3>
+		<p>
+		[page:Vector3 gravity] — Direction and volume of gravity.
+		</p>
+		<p>
+		Set gravity.
+		</p>
+
+		<h3>[method:CCDIKSolver update]( [param:Number delta] )</h3>
+		<p>
+		[page:Number delta] — Time in second.
+		</p>
+		<p>
+		Advance Physics calculation and updates bones.
+		</p>
+
+		<h3>[method:CCDIKSolver warmup]( [param:Integer cycles] )</h3>
+		<p>
+		[page:Number delta] — Time in second.
+		</p>
+		<p>
+		Warm up Rigid bodies. Calculates cycles steps.
+		</p>
+
+		<h2>Source</h2>
+
+		[link:https://github.com/mrdoob/three.js/blob/master/examples/js/animation/MMDPhysics.js examples/js/animation/MMDPhysics.js]
+	</body>
+</html>

+ 3 - 1
docs/list.js

@@ -338,7 +338,9 @@ var list = {
 	"Examples": {
 
 		"Animations": {
-			"MMDAnimationHelper": "examples/animations/MMDAnimationHelper"
+			"CCDIKSolver": "examples/animations/CCDIKSolver",
+			"MMDAnimationHelper": "examples/animations/MMDAnimationHelper",
+			"MMDPhysics": "examples/animations/MMDPhysics"
 		},
 
 		"Controls": {

+ 262 - 244
examples/js/animation/CCDIKSolver.js

@@ -2,416 +2,434 @@
  * @author takahiro / https://github.com/takahirox
  *
  * CCD Algorithm
- *  https://sites.google.com/site/auraliusproject/ccd-algorithm
- *
- * mesh.geometry needs to have iks array.
+ *  - https://sites.google.com/site/auraliusproject/ccd-algorithm
  *
  * // ik parameter example
  * //
- * // target, effector, index in links are bone index in skeleton.
+ * // target, effector, index in links are bone index in skeleton.bones.
  * // the bones relation should be
  * // <-- parent                                  child -->
  * // links[ n ], links[ n - 1 ], ..., links[ 0 ], effector
- * ik = {
+ * iks = [ {
  *	target: 1,
  *	effector: 2,
  *	links: [ { index: 5, limitation: new THREE.Vector3( 1, 0, 0 ) }, { index: 4, enabled: false }, { index : 3 } ],
  *	iteration: 10,
  *	minAngle: 0.0,
  *	maxAngle: 1.0,
- * };
+ * } ];
  */
 
-THREE.CCDIKSolver = function ( mesh ) {
+THREE.CCDIKSolver = ( function () {
 
-	this.mesh = mesh;
+	/**
+	 * @param {THREE.SkinnedMesh} mesh
+	 * @param {Array<Object>} iks
+	 */
+	function CCDIKSolver( mesh, iks ) {
 
-	this._valid();
+		this.mesh = mesh;
+		this.iks = iks || [];
 
-};
+		this._valid();
 
-THREE.CCDIKSolver.prototype = {
+	}
 
-	constructor: THREE.CCDIKSolver,
+	CCDIKSolver.prototype = {
 
-	_valid: function () {
+		constructor: CCDIKSolver,
 
-		var iks = this.mesh.geometry.iks;
-		var bones = this.mesh.skeleton.bones;
+		/**
+		 * Update IK bones.
+		 *
+		 * @return {THREE.CCDIKSolver}
+		 */
+		update: function () {
 
-		for ( var i = 0, il = iks.length; i < il; i ++ ) {
+			var q = new THREE.Quaternion();
+			var targetPos = new THREE.Vector3();
+			var targetVec = new THREE.Vector3();
+			var effectorPos = new THREE.Vector3();
+			var effectorVec = new THREE.Vector3();
+			var linkPos = new THREE.Vector3();
+			var invLinkQ = new THREE.Quaternion();
+			var linkScale = new THREE.Vector3();
+			var axis = new THREE.Vector3();
 
-			var ik = iks[ i ];
+			return function update() {
 
-			var effector = bones[ ik.effector ];
+				var bones = this.mesh.skeleton.bones;
+				var iks = this.iks;
 
-			var links = ik.links;
+				// for reference overhead reduction in loop
+				var math = Math;
 
-			var link0, link1;
+				for ( var i = 0, il = iks.length; i < il; i++ ) {
 
-			link0 = effector;
+					var ik = iks[ i ];
+					var effector = bones[ ik.effector ];
+					var target = bones[ ik.target ];
 
-			for ( var j = 0, jl = links.length; j < jl; j ++ ) {
+					// don't use getWorldPosition() here for the performance
+					// because it calls updateMatrixWorld( true ) inside.
+					targetPos.setFromMatrixPosition( target.matrixWorld );
 
-				link1 = bones[ links[ j ].index ];
+					var links = ik.links;
+					var iteration = ik.iteration !== undefined ? ik.iteration : 1;
 
-				if ( link0.parent !== link1 ) {
+					for ( var j = 0; j < iteration; j++ ) {
 
-					console.warn( 'THREE.CCDIKSolver: bone ' + link0.name + ' is not the child of bone ' + link1.name );
+						var rotated = false;
 
-				}
+						for ( var k = 0, kl = links.length; k < kl; k++ ) {
 
-				link0 = link1;
+							var link = bones[ links[ k ].index ];
 
-			}
+							// skip this link and following links.
+							// this skip is used for MMD performance optimization.
+							if ( links[ k ].enabled === false ) break;
 
-		}
+							var limitation = links[ k ].limitation;
 
-	},
+							// don't use getWorldPosition/Quaternion() here for the performance
+							// because they call updateMatrixWorld( true ) inside.
+							link.matrixWorld.decompose( linkPos, invLinkQ, linkScale );
+							invLinkQ.inverse();
+							effectorPos.setFromMatrixPosition( effector.matrixWorld );
 
-	/*
-	 * save the bone matrices before solving IK.
-	 * they're used for generating VMD and VPD.
-	 */
-	_saveOriginalBonesInfo: function () {
+							// work in link world
+							effectorVec.subVectors( effectorPos, linkPos );
+							effectorVec.applyQuaternion( invLinkQ );
+							effectorVec.normalize();
 
-		var bones = this.mesh.skeleton.bones;
+							targetVec.subVectors( targetPos, linkPos );
+							targetVec.applyQuaternion( invLinkQ );
+							targetVec.normalize();
 
-		for ( var i = 0, il = bones.length; i < il; i ++ ) {
+							var angle = targetVec.dot( effectorVec );
 
-			var bone = bones[ i ];
+							if ( angle > 1.0 ) {
 
-			if ( bone.userData.ik === undefined ) bone.userData.ik = {};
+								angle = 1.0;
 
-			bone.userData.ik.originalMatrix = bone.matrix.toArray();
+							} else if ( angle < -1.0 ) {
 
-		}
+								angle = -1.0;
 
-	},
+							}
 
-	update: function ( saveOriginalBones ) {
+							angle = math.acos( angle );
 
-		var q = new THREE.Quaternion();
+							// skip if changing angle is too small to prevent vibration of bone
+							// Refer to http://www20.atpages.jp/katwat/three.js_r58/examples/mytest37/mmd.three.js
+							if ( angle < 1e-5 ) continue;
 
-		var targetPos = new THREE.Vector3();
-		var targetVec = new THREE.Vector3();
-		var effectorPos = new THREE.Vector3();
-		var effectorVec = new THREE.Vector3();
-		var linkPos = new THREE.Vector3();
-		var invLinkQ = new THREE.Quaternion();
-		var linkScale = new THREE.Vector3();
-		var axis = new THREE.Vector3();
+							if ( ik.minAngle !== undefined && angle < ik.minAngle ) {
 
-		var bones = this.mesh.skeleton.bones;
-		var iks = this.mesh.geometry.iks;
+								angle = ik.minAngle;
 
-		var boneParams = this.mesh.geometry.bones;
+							}
 
-		// for reference overhead reduction in loop
-		var math = Math;
+							if ( ik.maxAngle !== undefined && angle > ik.maxAngle ) {
 
-		this.mesh.updateMatrixWorld( true );
+								angle = ik.maxAngle;
 
-		if ( saveOriginalBones === true ) this._saveOriginalBonesInfo();
+							}
 
-		for ( var i = 0, il = iks.length; i < il; i++ ) {
+							axis.crossVectors( effectorVec, targetVec );
+							axis.normalize();
 
-			var ik = iks[ i ];
-			var effector = bones[ ik.effector ];
-			var target = bones[ ik.target ];
+							q.setFromAxisAngle( axis, angle );
+							link.quaternion.multiply( q );
 
-			// don't use getWorldPosition() here for the performance
-			// because it calls updateMatrixWorld( true ) inside.
-			targetPos.setFromMatrixPosition( target.matrixWorld );
+							// TODO: re-consider the limitation specification
+							if ( limitation !== undefined ) {
 
-			var links = ik.links;
-			var iteration = ik.iteration !== undefined ? ik.iteration : 1;
+								var c = link.quaternion.w;
 
-			for ( var j = 0; j < iteration; j++ ) {
+								if ( c > 1.0 ) c = 1.0;
 
-				var rotated = false;
+								var c2 = math.sqrt( 1 - c * c );
+								link.quaternion.set( limitation.x * c2,
+								                     limitation.y * c2,
+								                     limitation.z * c2,
+								                     c );
 
-				for ( var k = 0, kl = links.length; k < kl; k++ ) {
+							}
 
-					var link = bones[ links[ k ].index ];
+							link.updateMatrixWorld( true );
 
-					// skip this link and following links.
-					// this skip is used for MMD performance optimization.
-					if ( links[ k ].enabled === false ) break;
+							rotated = true;
 
-					var limitation = links[ k ].limitation;
+						}
 
-					// don't use getWorldPosition/Quaternion() here for the performance
-					// because they call updateMatrixWorld( true ) inside.
-					link.matrixWorld.decompose( linkPos, invLinkQ, linkScale );
-					invLinkQ.inverse();
-					effectorPos.setFromMatrixPosition( effector.matrixWorld );
+						if ( ! rotated ) break;
 
-					// work in link world
-					effectorVec.subVectors( effectorPos, linkPos );
-					effectorVec.applyQuaternion( invLinkQ );
-					effectorVec.normalize();
+					}
 
-					targetVec.subVectors( targetPos, linkPos );
-					targetVec.applyQuaternion( invLinkQ );
-					targetVec.normalize();
+				}
 
-					var angle = targetVec.dot( effectorVec );
+				return this;
 
-					if ( angle > 1.0 ) {
+			};
 
-						angle = 1.0;
+		}(),
 
-					} else if ( angle < -1.0 ) {
+		/**
+		 * Creates Helper
+		 *
+		 * @return {CCDIKHelper}
+		 */
+		createHelper: function () {
 
-						angle = -1.0;
+			return new CCDIKHelper( this.mesh, this.mesh.geometry.iks );
 
-					}
+		},
 
-					angle = math.acos( angle );
+		// private methods
 
-					// skip if changing angle is too small to prevent vibration of bone
-					// Refer to http://www20.atpages.jp/katwat/three.js_r58/examples/mytest37/mmd.three.js
-					if ( angle < 1e-5 ) continue;
+		_valid: function () {
 
-					if ( ik.minAngle !== undefined && angle < ik.minAngle ) {
+			var iks = this.iks;
+			var bones = this.mesh.skeleton.bones;
 
-						angle = ik.minAngle;
+			for ( var i = 0, il = iks.length; i < il; i ++ ) {
 
-					}
-
-					if ( ik.maxAngle !== undefined && angle > ik.maxAngle ) {
+				var ik = iks[ i ];
+				var effector = bones[ ik.effector ];
+				var links = ik.links;
+				var link0, link1;
 
-						angle = ik.maxAngle;
+				link0 = effector;
 
-					}
+				for ( var j = 0, jl = links.length; j < jl; j ++ ) {
 
-					axis.crossVectors( effectorVec, targetVec );
-					axis.normalize();
+					link1 = bones[ links[ j ].index ];
 
-					q.setFromAxisAngle( axis, angle );
-					link.quaternion.multiply( q );
+					if ( link0.parent !== link1 ) {
 
-					// TODO: re-consider the limitation specification
-					if ( limitation !== undefined ) {
+						console.warn( 'THREE.CCDIKSolver: bone ' + link0.name + ' is not the child of bone ' + link1.name );
 
-						var c = link.quaternion.w;
+					}
 
-						if ( c > 1.0 ) {
+					link0 = link1;
 
-							c = 1.0;
+				}
 
-						}
+			}
 
-						var c2 = math.sqrt( 1 - c * c );
-						link.quaternion.set( limitation.x * c2,
-						                     limitation.y * c2,
-						                     limitation.z * c2,
-						                     c );
+		}
 
-					}
+	};
 
-					link.updateMatrixWorld( true );
-					rotated = true;
+	/**
+	 * Visualize IK bones
+	 *
+	 * @param {SkinnedMesh} mesh
+	 * @param {Array<Object>} iks
+	 */
+	function CCDIKHelper( mesh, iks ) {
 
-				}
+		THREE.Object3D.call( this );
 
-				if ( ! rotated ) break;
+		this.root = mesh;
+		this.iks = iks || [];
 
-			}
+		this.matrix.copy( mesh.matrixWorld );
+		this.matrixAutoUpdate = false;
 
-		}
+		this.sphereGeometry = new THREE.SphereBufferGeometry( 0.25, 16, 8 );
 
-		// just in case
-		this.mesh.updateMatrixWorld( true );
+		this.targetSphereMaterial = new THREE.MeshBasicMaterial( {
+			color: new THREE.Color( 0xff8888 ),
+			depthTest: false,
+			depthWrite: false,
+			transparent: true
+		} );
 
-	}
+		this.effectorSphereMaterial = new THREE.MeshBasicMaterial( {
+			color: new THREE.Color( 0x88ff88 ),
+			depthTest: false,
+			depthWrite: false,
+			transparent: true
+		} );
 
-};
+		this.linkSphereMaterial = new THREE.MeshBasicMaterial( {
+			color: new THREE.Color( 0x8888ff ),
+			depthTest: false,
+			depthWrite: false,
+			transparent: true
+		} );
 
+		this.lineMaterial = new THREE.LineBasicMaterial( {
+			color: new THREE.Color( 0xff0000 ),
+			depthTest: false,
+			depthWrite: false,
+			transparent: true
+		} );
 
-THREE.CCDIKHelper = function ( mesh ) {
+		this._init();
 
-	if ( mesh.geometry.iks === undefined || mesh.skeleton === undefined ) {
+	}
 
-		throw 'THREE.CCDIKHelper requires iks in mesh.geometry and skeleton in mesh.';
+	CCDIKHelper.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), {
 
-	}
+		constructor: CCDIKHelper,
 
-	THREE.Object3D.call( this );
+		/**
+		 * Updates IK bones visualization.
+		 */
+		updateMatrixWorld: function () {
 
-	this.root = mesh;
+			var matrix = new THREE.Matrix4();
+			var vector = new THREE.Vector3();
 
-	this.matrix = mesh.matrixWorld;
-	this.matrixAutoUpdate = false;
+			function getPosition( bone, matrixWorldInv ) {
 
-	this.sphereGeometry = new THREE.SphereBufferGeometry( 0.25, 16, 8 );
+				return vector
+					.setFromMatrixPosition( bone.matrixWorld )
+					.applyMatrix4( matrixWorldInv );
 
-	this.targetSphereMaterial = new THREE.MeshBasicMaterial( {
-		color: new THREE.Color( 0xff8888 ),
-		depthTest: false,
-		depthWrite: false,
-		transparent: true
-	} );
+			}
 
-	this.effectorSphereMaterial = new THREE.MeshBasicMaterial( {
-		color: new THREE.Color( 0x88ff88 ),
-		depthTest: false,
-		depthWrite: false,
-		transparent: true
-	} );
+			function setPositionOfBoneToAttributeArray( array, index, bone, matrixWorldInv ) {
 
-	this.linkSphereMaterial = new THREE.MeshBasicMaterial( {
-		color: new THREE.Color( 0x8888ff ),
-		depthTest: false,
-		depthWrite: false,
-		transparent: true
-	} );
+				var v = getPosition( bone, matrixWorldInv );
 
-	this.lineMaterial = new THREE.LineBasicMaterial( {
-		color: new THREE.Color( 0xff0000 ),
-		depthTest: false,
-		depthWrite: false,
-		transparent: true
-	} );
+				array[ index * 3 + 0 ] = v.x;
+				array[ index * 3 + 1 ] = v.y;
+				array[ index * 3 + 2 ] = v.z;
 
-	this._init();
-	this.update();
+			}
 
-};
+			return function updateMatrixWorld( force ) {
 
-THREE.CCDIKHelper.prototype = Object.create( THREE.Object3D.prototype );
-THREE.CCDIKHelper.prototype.constructor = THREE.CCDIKHelper;
+				var mesh = this.root;
 
-THREE.CCDIKHelper.prototype._init = function () {
+				if ( this.visible ) {
 
-	var self = this;
-	var mesh = this.root;
-	var iks = mesh.geometry.iks;
+					var offset = 0;
 
-	function createLineGeometry( ik ) {
+					var iks = this.iks;
+					var bones = mesh.skeleton.bones;
 
-		var geometry = new THREE.BufferGeometry();
-		var vertices = new Float32Array( ( 2 + ik.links.length ) * 3 );
-		geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
+					matrix.getInverse( mesh.matrixWorld );
 
-		return geometry;
+					for ( var i = 0, il = iks.length; i < il; i ++ ) {
 
-	}
+						var ik = iks[ i ];
 
-	function createTargetMesh() {
+						var targetBone = bones[ ik.target ];
+						var effectorBone = bones[ ik.effector ];
 
-		return new THREE.Mesh( self.sphereGeometry, self.targetSphereMaterial );
+						var targetMesh = this.children[ offset ++ ];
+						var effectorMesh = this.children[ offset ++ ];
 
-	}
+						targetMesh.position.copy( getPosition( targetBone, matrix ) );
+						effectorMesh.position.copy( getPosition( effectorBone, matrix ) );
 
-	function createEffectorMesh() {
+						for ( var j = 0, jl = ik.links.length; j < jl; j ++ ) {
 
-		return new THREE.Mesh( self.sphereGeometry, self.effectorSphereMaterial );
+							var link = ik.links[ j ];
+							var linkBone = bones[ link.index ];
 
-	}
+							var linkMesh = this.children[ offset ++ ];
 
-	function createLinkMesh() {
+							linkMesh.position.copy( getPosition( linkBone, matrix ) );
 
-		return new THREE.Mesh( self.sphereGeometry, self.linkSphereMaterial );
+						}
 
-	}
+						var line = this.children[ offset ++ ];
+						var array = line.geometry.attributes.position.array;
 
-	function createLine( ik ) {
+						setPositionOfBoneToAttributeArray( array, 0, targetBone, matrix );
+						setPositionOfBoneToAttributeArray( array, 1, effectorBone, matrix );
 
-		return new THREE.Line( createLineGeometry( ik ), self.lineMaterial );
+						for ( var j = 0, jl = ik.links.length; j < jl; j ++ ) {
 
-	}
+							var link = ik.links[ j ];
+							var linkBone = bones[ link.index ];
+							setPositionOfBoneToAttributeArray( array, j + 2, linkBone, matrix );
 
-	for ( var i = 0, il = iks.length; i < il; i ++ ) {
+						}
 
-		var ik = iks[ i ];
+						line.geometry.attributes.position.needsUpdate = true;
 
-		this.add( createTargetMesh() );
-		this.add( createEffectorMesh() );
+					}
 
-		for ( var j = 0, jl = ik.links.length; j < jl; j ++ ) {
+				}
 
-			this.add( createLinkMesh() );
+				this.matrix.copy( mesh.matrixWorld );
 
-		}
+				THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
 
-		this.add( createLine( ik ) );
+			};
 
-	}
+		}(),
 
-};
+		// private method
 
-THREE.CCDIKHelper.prototype.update = function () {
+		_init: function () {
 
-	var offset = 0;
+			var self = this;
+			var mesh = this.root;
+			var iks = this.iks;
 
-	var mesh = this.root;
-	var iks = mesh.geometry.iks;
-	var bones = mesh.skeleton.bones;
+			function createLineGeometry( ik ) {
 
-	var matrixWorldInv = new THREE.Matrix4().getInverse( mesh.matrixWorld );
-	var vector = new THREE.Vector3();
+				var geometry = new THREE.BufferGeometry();
+				var vertices = new Float32Array( ( 2 + ik.links.length ) * 3 );
+				geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
 
-	function getPosition( bone ) {
+				return geometry;
 
-		vector.setFromMatrixPosition( bone.matrixWorld );
-		vector.applyMatrix4( matrixWorldInv );
+			}
 
-		return vector;
+			function createTargetMesh() {
 
-	}
+				return new THREE.Mesh( self.sphereGeometry, self.targetSphereMaterial );
 
-	function setPositionOfBoneToAttributeArray( array, index, bone ) {
+			}
 
-		var v = getPosition( bone );
+			function createEffectorMesh() {
 
-		array[ index * 3 + 0 ] = v.x;
-		array[ index * 3 + 1 ] = v.y;
-		array[ index * 3 + 2 ] = v.z;
+				return new THREE.Mesh( self.sphereGeometry, self.effectorSphereMaterial );
 
-	}
+			}
 
-	for ( var i = 0, il = iks.length; i < il; i ++ ) {
+			function createLinkMesh() {
 
-		var ik = iks[ i ];
+				return new THREE.Mesh( self.sphereGeometry, self.linkSphereMaterial );
 
-		var targetBone = bones[ ik.target ];
-		var effectorBone = bones[ ik.effector ];
+			}
 
-		var targetMesh = this.children[ offset ++ ];
-		var effectorMesh = this.children[ offset ++ ];
+			function createLine( ik ) {
 
-		targetMesh.position.copy( getPosition( targetBone ) );
-		effectorMesh.position.copy( getPosition( effectorBone ) );
+				return new THREE.Line( createLineGeometry( ik ), self.lineMaterial );
 
-		for ( var j = 0, jl = ik.links.length; j < jl; j ++ ) {
+			}
 
-			var link = ik.links[ j ];
-			var linkBone = bones[ link.index ];
+			for ( var i = 0, il = iks.length; i < il; i ++ ) {
 
-			var linkMesh = this.children[ offset ++ ];
+				var ik = iks[ i ];
 
-			linkMesh.position.copy( getPosition( linkBone ) );
+				this.add( createTargetMesh() );
+				this.add( createEffectorMesh() );
 
-		}
+				for ( var j = 0, jl = ik.links.length; j < jl; j ++ ) {
 
-		var line = this.children[ offset ++ ];
-		var array = line.geometry.attributes.position.array;
+					this.add( createLinkMesh() );
 
-		setPositionOfBoneToAttributeArray( array, 0, targetBone );
-		setPositionOfBoneToAttributeArray( array, 1, effectorBone );
+				}
 
-		for ( var j = 0, jl = ik.links.length; j < jl; j ++ ) {
+				this.add( createLine( ik ) );
 
-			var link = ik.links[ j ];
-			var linkBone = bones[ link.index ];
-			setPositionOfBoneToAttributeArray( array, j + 2, linkBone );
+			}
 
 		}
 
-		line.geometry.attributes.position.needsUpdate = true;
+	} );
 
-	}
+	return CCDIKSolver;
 
-};
+} )();

+ 79 - 62
examples/js/animation/MMDAnimationHelper.js

@@ -53,6 +53,8 @@ THREE.MMDAnimationHelper = ( function () {
 			cameraAnimation: true
 		};
 
+		this.onBeforePhysics = function ( mesh ) {};
+
 		// experimental
 		this.sharedPhysics = false;
 		this.masterPhysics = null;
@@ -72,6 +74,10 @@ THREE.MMDAnimationHelper = ( function () {
 		 * @param {Object} params - (optional)
 		 * @param {THREE.AnimationClip|Array<THREE.AnimationClip>} params.animation - Only for THREE.SkinnedMesh and THREE.Camera. Default is undefined.
 		 * @param {boolean} params.physics - Only for THREE.SkinnedMesh. Default is true.
+		 * @param {Integer} params.warmup - Only for THREE.SkinnedMesh and physics is true. Default is 60.
+		 * @param {Number} params.unitStep - Only for THREE.SkinnedMesh and physics is true. Default is 1 / 65.
+		 * @param {Integer} params.maxStepNum - Only for THREE.SkinnedMesh and physics is true. Default is 3.
+		 * @param {THREE.Vector3} params.gravity - Only for THREE.SkinnedMesh and physics is true. Default ( 0, - 9.8 * 10, 0 ).
 		 * @param {Number} params.delayTime - Only for THREE.Audio. Default is 0.0.
 		 * @return {THREE.MMDAnimationHelper}
 		 */
@@ -215,15 +221,13 @@ THREE.MMDAnimationHelper = ( function () {
 
 			if ( params.ik !== false ) {
 
-				var solver = this._createCCDIKSolver( mesh );
-				solver.update( params.saveOriginalBonesBeforeIK );  // this param is experimental
+				this._createCCDIKSolver( mesh ).update( params.saveOriginalBonesBeforeIK );  // this param is experimental
 
 			}
 
 			if ( params.grant !== false ) {
 
-				var solver = this.createGrantSolver( mesh );
-				solver.update();
+				this.createGrantSolver( mesh ).update();
 
 			}
 
@@ -271,7 +275,7 @@ THREE.MMDAnimationHelper = ( function () {
 		 */
 		createGrantSolver: function ( mesh ) {
 
-			return new GrantSolver( mesh );
+			return new GrantSolver( mesh, mesh.geometry.grants );
 
 		},
 
@@ -289,9 +293,6 @@ THREE.MMDAnimationHelper = ( function () {
 			this.meshes.push( mesh );
 			this.objects.set( mesh, { looped: false } );
 
-			// workaround until I make IK and Physics Animation plugin
-			this._initBackupBones( mesh );
-
 			if ( params.animation !== undefined ) {
 
 				this._setupMeshAnimation( mesh, params.animation );
@@ -401,7 +402,7 @@ THREE.MMDAnimationHelper = ( function () {
 
 			this.camera.remove( this.cameraTarget );
 
-			this.params.delete( this.camera );
+			this.objects.delete( this.camera );
 			this.camera = null;
 
 			return this;
@@ -479,8 +480,6 @@ THREE.MMDAnimationHelper = ( function () {
 
 		_setupMeshPhysics: function ( mesh, params ) {
 
-			params = Object.assign( {}, params );
-
 			var objects = this.objects.get( mesh );
 
 			// shared physics is experimental
@@ -493,8 +492,6 @@ THREE.MMDAnimationHelper = ( function () {
 
 			}
 
-			var warmup = params.warmup !== undefined ? params.warmup : 60;
-
 			objects.physics = this._createMMDPhysics( mesh, params );
 
 			if ( objects.mixer && params.animationWarmup !== false ) {
@@ -504,7 +501,7 @@ THREE.MMDAnimationHelper = ( function () {
 
 			}
 
-			objects.physics.warmup( warmup );
+			objects.physics.warmup( params.warmup !== undefined ? params.warmup : 60 );
 
 			this._optimizeIK( mesh, true );
 
@@ -522,25 +519,28 @@ THREE.MMDAnimationHelper = ( function () {
 
 			if ( mixer && this.enabled.animation ) {
 
-				// restore/backupBones are workaround
-				// until I make IK, Grant, and Physics Animation plugin
 				this._restoreBones( mesh );
 
+				// another solution but less performant?
+				//mesh.pose();
+				//this._updatePropertyMixersBuffer( mesh );
+
 				mixer.update( delta );
 
-				this._backupBones( mesh );
+				this._saveBones( mesh );
 
-			}
+				if ( ikSolver && this.enabled.ik ) {
 
-			if ( ikSolver && this.enabled.ik ) {
+					mesh.updateMatrixWorld( true );
+					ikSolver.update();
 
-				ikSolver.update();
+				}
 
-			}
+				if ( grantSolver && this.enabled.grant ) {
 
-			if ( grantSolver && this.enabled.grant ) {
+					grantSolver.update();
 
-				grantSolver.update();
+				}
 
 			}
 
@@ -554,6 +554,7 @@ THREE.MMDAnimationHelper = ( function () {
 
 			if ( physics && this.enabled.physics && ! this.sharedPhysics ) {
 
+				this.onBeforePhysics( mesh );
 				physics.update( delta );
 
 			}
@@ -618,7 +619,7 @@ THREE.MMDAnimationHelper = ( function () {
 
 			}
 
-			return new THREE.CCDIKSolver( mesh );
+			return new THREE.CCDIKSolver( mesh, mesh.geometry.iks );
 
 		},
 
@@ -630,7 +631,8 @@ THREE.MMDAnimationHelper = ( function () {
 
 			}
 
-			return new THREE.MMDPhysics( mesh, params );
+			return new THREE.MMDPhysics(
+				mesh, mesh.geometry.rigidBodies, mesh.geometry.constraints, params );
 
 		},
 
@@ -749,44 +751,55 @@ THREE.MMDAnimationHelper = ( function () {
 
 		// workaround
 
-		/*
-		 * Note: These following three functions are workaround for r74dev.
-		 *       THREE.PropertyMixer.apply() seems to save values into buffer cache
-		 *       when mixer.update() is called.
-		 *       ikSolver.update() and physics.update() change bone position/quaternion
-		 *       without mixer.update() then buffer cache will be inconsistent.
-		 *       So trying to avoid buffer cache inconsistency by doing
-		 *       backup bones position/quaternion right after mixer.update() call
-		 *       and then restore them after rendering.
-		 */
-		_initBackupBones: function ( mesh ) {
+		_updatePropertyMixersBuffer: function ( mesh ) {
 
-			var backupBones = [];
+			var mixer = this.objects.get( mesh ).mixer;
 
-			for ( var i = 0, il = mesh.skeleton.bones.length; i < il; i ++ ) {
+			var propertyMixers = mixer._bindings;
+			var accuIndex = mixer._accuIndex;
 
-				backupBones.push( mesh.skeleton.bones[ i ].clone() );
+			for ( var i = 0, il = propertyMixers.length; i < il; i ++ ) {
 
-			}
+				var propertyMixer = propertyMixers[ i ];
+				var buffer = propertyMixer.buffer;
+				var stride = propertyMixer.valueSize;
+				var offset = ( accuIndex + 1 ) * stride;
 
-			this.objects.get( mesh ).backupBones = backupBones;
+				propertyMixer.binding.getValue( buffer, offset );
+
+			}
 
 		},
 
-		_backupBones: function ( mesh ) {
+		/*
+		 * Avoiding these two issues by restore/save bones before/after mixer animation.
+		 *
+		 * 1. PropertyMixer used by AnimationMixer holds cache value in .buffer.
+		 *    Calculating IK, Grant, and Physics after mixer animation can break
+		 *    the cache coherency.
+		 *
+		 * 2. Applying Grant two or more times without reset the posing breaks model.
+		 */
+		_saveBones: function ( mesh ) {
 
 			var objects = this.objects.get( mesh );
 
-			objects.backupBoneIsSaved = true;
+			var bones = mesh.skeleton.bones;
 
 			var backupBones = objects.backupBones;
 
-			for ( var i = 0, il = mesh.skeleton.bones.length; i < il; i ++ ) {
+			if ( backupBones === undefined ) {
+
+				backupBones = new Float32Array( bones.length * 7 );
+				objects.backupBones = backupBones;
+
+			}
+
+			for ( var i = 0, il = bones.length; i < il; i ++ ) {
 
-				var backupBone = backupBones[ i ];
-				var bone = mesh.skeleton.bones[ i ];
-				backupBone.position.copy( bone.position );
-				backupBone.quaternion.copy( bone.quaternion );
+				var bone = bones[ i ];
+				bone.position.toArray( backupBones, i * 7 );
+				bone.quaternion.toArray( backupBones, i * 7 + 3 );
 
 			}
 
@@ -796,18 +809,17 @@ THREE.MMDAnimationHelper = ( function () {
 
 			var objects = this.objects.get( mesh );
 
-			if ( objects.backupBoneIsSaved !== true ) return;
+			var backupBones = objects.backupBones;
 
-			objects.backupBoneIsSaved = false;
+			if ( backupBones === undefined ) return;
 
-			var backupBones = objects.backupBones;
+			var bones = mesh.skeleton.bones;
 
-			for ( var i = 0, il = mesh.skeleton.bones.length; i < il; i ++ ) {
+			for ( var i = 0, il = bones.length; i < il; i ++ ) {
 
-				var bone = mesh.skeleton.bones[ i ];
-				var backupBone = backupBones[ i ];
-				bone.position.copy( backupBone.position );
-				bone.quaternion.copy( backupBone.quaternion );
+				var bone = bones[ i ];
+				bone.position.fromArray( backupBones, i * 7 );
+				bone.quaternion.fromArray( backupBones, i * 7 + 3 );
 
 			}
 
@@ -948,10 +960,12 @@ THREE.MMDAnimationHelper = ( function () {
 
 	/**
 	 * @param {THREE.SkinnedMesh} mesh
+	 * @param {Array<Object>} grants
 	 */
-	function GrantSolver( mesh ) {
+	function GrantSolver( mesh, grants ) {
 
 		this.mesh = mesh;
+		this.grants = grants || [];
 
 	}
 
@@ -968,11 +982,14 @@ THREE.MMDAnimationHelper = ( function () {
 
 			return function () {
 
-				for ( var i = 0, il = this.mesh.geometry.grants.length; i < il; i ++ ) {
+				var bones = this.mesh.skeleton.bones;
+				var grants = this.grants;
+
+				for ( var i = 0, il = grants.length; i < il; i ++ ) {
 
-					var grant = this.mesh.geometry.grants[ i ];
-					var bone = this.mesh.skeleton.bones[ grant.index ];
-					var parentBone = this.mesh.skeleton.bones[ grant.parentIndex ];
+					var grant = grants[ i ];
+					var bone = bones[ grant.index ];
+					var parentBone = bones[ grant.parentIndex ];
 
 					if ( grant.isLocal ) {
 
@@ -1005,7 +1022,7 @@ THREE.MMDAnimationHelper = ( function () {
 
 				}
 
-				this;
+				return this;
 
 			};
 

+ 962 - 778
examples/js/animation/MMDPhysics.js

@@ -4,1220 +4,1404 @@
  * Dependencies
  *  - Ammo.js https://github.com/kripken/ammo.js
  *
- * MMD specific Physics class.
- *
- * See THREE.MMDLoader for the passed parameter list of RigidBody/Constraint.
- *
- * Requirement:
- *  - don't change object's scale from (1,1,1) after setting physics to object
+ * MMDPhysics calculates physics with Ammo(Bullet based JavaScript Physics engine)
+ * for MMD model loaded by THREE.MMDLoader.
  *
  * TODO
- *  - optimize for the performance
- *  - use Physijs http://chandlerprall.github.io/Physijs/
- *    and improve the performance by making use of Web worker.
- *  - if possible, make this class being non-MMD specific.
- *  - object scale change support
+ *  - Physics in Worker
  */
 
-THREE.MMDPhysics = function ( mesh, params ) {
+THREE.MMDPhysics = ( function () {
 
-	if ( typeof Ammo === 'undefined' ) {
+	/**
+	 * @param {THREE.SkinnedMesh} mesh
+	 * @param {Array<Object>} rigidBodyParams
+	 * @param {Array<Object>} (optional) constraintParams
+	 * @param {Object} params - (optional)
+	 * @param {Number} params.unitStep - Default is 1 / 65.
+	 * @param {Integer} params.maxStepNum - Default is 3.
+	 * @param {THREE.Vector3} params.gravity - Default is ( 0, - 9.8 * 10, 0 )
+	 */
+	function MMDPhysics( mesh, rigidBodyParams, constraintParams, params ) {
 
-		throw new Error( 'THREE.MMDPhysics: Import ammo.js https://github.com/kripken/ammo.js' );
+		if ( typeof Ammo === 'undefined' ) {
 
-	}
+			throw new Error( 'THREE.MMDPhysics: Import ammo.js https://github.com/kripken/ammo.js' );
 
-	if ( params === undefined ) params = {};
+		}
 
-	this.mesh = mesh;
-	this.helper = new THREE.MMDPhysics.ResourceHelper();
+		constraintParams = constraintParams || [];
+		params = params || {};
 
-	/*
-	 * I don't know why but 1/60 unitStep easily breaks models
-	 * so I set it 1/65 so far.
-	 * Don't set too small unitStep because
-	 * the smaller unitStep can make the performance worse.
-	 */
-	this.unitStep = ( params.unitStep !== undefined ) ? params.unitStep : 1 / 65;
-	this.maxStepNum = ( params.maxStepNum !== undefined ) ? params.maxStepNum : 3;
+		this.manager = new ResourceManager();
 
-	this.world = params.world !== undefined ? params.world : null;
-	this.bodies = [];
-	this.constraints = [];
+		this.mesh = mesh;
 
-	this.init( mesh );
+		/*
+		 * I don't know why but 1/60 unitStep easily breaks models
+		 * so I set it 1/65 so far.
+		 * Don't set too small unitStep because
+		 * the smaller unitStep can make the performance worse.
+		 */
+		this.unitStep = ( params.unitStep !== undefined ) ? params.unitStep : 1 / 65;
+		this.maxStepNum = ( params.maxStepNum !== undefined ) ? params.maxStepNum : 3;
+		this.gravity = new THREE.Vector3( 0, - 9.8 * 10, 0 );
 
-};
+		if ( params.gravity !== undefined ) this.gravity.copy( gravity );
 
-THREE.MMDPhysics.prototype = {
+		this.world = params.world !== undefined ? params.world : null; // experimental
 
-	constructor: THREE.MMDPhysics,
+		this.bodies = [];
+		this.constraints = [];
 
-	init: function ( mesh ) {
+		this._init( mesh, rigidBodyParams, constraintParams );
 
-		var parent = mesh.parent;
+	}
 
-		if ( parent !== null ) {
+	MMDPhysics.prototype = {
 
-			parent.remove( mesh );
+		constructor: MMDPhysics,
 
-		}
+		/**
+		 * Advances Physics calculation and updates bones.
+		 *
+		 * @param {Number} delta - time in second
+		 * @return {THREE.MMDPhysics}
+		 */
+		update: function ( delta ) {
 
-		var helper = this.helper;
-		var currentPosition = helper.allocThreeVector3();
-		var currentRotation = helper.allocThreeEuler();
-		var currentScale = helper.allocThreeVector3();
+			var manager = this.manager;
+			var mesh = this.mesh;
 
-		currentPosition.copy( mesh.position );
-		currentRotation.copy( mesh.rotation );
-		currentScale.copy( mesh.scale );
+			// rigid bodies and constrains are for
+			// mesh's world scale (1, 1, 1).
+			// Convert to (1, 1, 1) if it isn't.
 
-		mesh.position.set( 0, 0, 0 );
-		mesh.rotation.set( 0, 0, 0 );
-		mesh.scale.set( 1, 1, 1 );
+			var isNonDefaultScale = false;
 
-		mesh.updateMatrixWorld( true );
+			var position = manager.allocThreeVector3();
+			var quaternion = manager.allocThreeQuaternion();
+			var scale = manager.allocThreeVector3();
 
-		if ( this.world === null ) this.initWorld();
-		this.initRigidBodies();
-		this.initConstraints();
+			mesh.matrixWorld.decompose( position, quaternion, scale );
 
-		if ( parent !== null ) {
+			if ( scale.x !== 1 || scale.y !== 1 || scale.z !== 1 ) {
 
-			parent.add( mesh );
+				isNonDefaultScale = true;
 
-		}
+			}
 
-		mesh.position.copy( currentPosition );
-		mesh.rotation.copy( currentRotation );
-		mesh.scale.copy( currentScale );
+			var parent;
 
-		mesh.updateMatrixWorld( true );
+			if ( isNonDefaultScale ) {
 
-		this.reset();
+				parent = mesh.parent;
 
-		helper.freeThreeVector3( currentPosition );
-		helper.freeThreeEuler( currentRotation );
-		helper.freeThreeVector3( currentScale );
+				if ( parent !== null ) mesh.parent = null;
 
-	},
+				scale.copy( this.mesh.scale );
 
-	initWorld: function () {
+				mesh.scale.set( 1, 1, 1 );
+				mesh.updateMatrixWorld( true );
 
-		var config = new Ammo.btDefaultCollisionConfiguration();
-		var dispatcher = new Ammo.btCollisionDispatcher( config );
-		var cache = new Ammo.btDbvtBroadphase();
-		var solver = new Ammo.btSequentialImpulseConstraintSolver();
-		var world = new Ammo.btDiscreteDynamicsWorld( dispatcher, cache, solver, config );
-		world.setGravity( new Ammo.btVector3( 0, -9.8 * 10, 0 ) );
-		this.world = world;
+			}
 
-	},
+			// calculate physics and update bones
 
-	initRigidBodies: function () {
+			this._updateRigidBodies();
+			this._stepSimulation( delta );
+			this._updateBones();
 
-		var bodies = this.mesh.geometry.rigidBodies;
+			// restore mesh if converted above
 
-		for ( var i = 0; i < bodies.length; i++ ) {
+			if ( isNonDefaultScale ) {
 
-			var b = new THREE.MMDPhysics.RigidBody( this.mesh, this.world, bodies[ i ], this.helper );
-			this.bodies.push( b );
+				if ( parent !== null ) parent.parent = parent;
 
-		}
+				mesh.scale.copy( scale );
 
-	},
+			}
 
-	initConstraints: function () {
+			manager.freeThreeVector3( scale );
+			manager.freeThreeQuaternion( quaternion );
+			manager.freeThreeVector3( position );
 
-		var constraints = this.mesh.geometry.constraints;
+			return this;
 
-		for ( var i = 0; i < constraints.length; i++ ) {
+		},
 
-			var params = constraints[ i ];
-			var bodyA = this.bodies[ params.rigidBodyIndex1 ];
-			var bodyB = this.bodies[ params.rigidBodyIndex2 ];
-			var c = new THREE.MMDPhysics.Constraint( this.mesh, this.world, bodyA, bodyB, params, this.helper );
-			this.constraints.push( c );
+		/**
+		 * Resets rigid bodies transorm to current bone's.
+		 *
+		 * @return {THREE.MMDPhysics}
+		 */
+		reset: function () {
 
-		}
+			for ( var i = 0, il = this.bodies.length; i < il; i++ ) {
 
+				this.bodies[ i ].reset();
 
-	},
+			}
 
-	update: function ( delta ) {
+			return this;
 
-		this.updateRigidBodies();
-		this.stepSimulation( delta );
-		this.updateBones();
+		},
 
-	},
+		/**
+		 * Warm ups Rigid bodies. Calculates cycles steps.
+		 *
+		 * @param {Integer} cycles
+		 * @return {THREE.MMDPhysics}
+		 */
+		warmup: function ( cycles ) {
 
-	stepSimulation: function ( delta ) {
+			for ( var i = 0; i < cycles; i++ ) {
 
-		var unitStep = this.unitStep;
-		var stepTime = delta;
-		var maxStepNum = ( ( delta / unitStep ) | 0 ) + 1;
+				this.update( 1 / 60 );
 
-		if ( stepTime < unitStep ) {
+			}
 
-			stepTime = unitStep;
-			maxStepNum = 1;
+			return this;
 
-		}
+		},
 
-		if ( maxStepNum > this.maxStepNum ) {
+		/**
+		 * Sets gravity.
+		 *
+		 * @param {THREE.Vector3} gravity
+		 * @return {MMDPhysicsHelper}
+		 */
+		setGravity: function ( gravity ) {
 
-			maxStepNum = this.maxStepNum;
+			this.world.setGravity( new Ammo.btVector3( gravity.x, gravity.y, gravity.z ) );
+			this.gravity.copy( gravity );
 
-		}
+			return this;
 
-		this.world.stepSimulation( stepTime, maxStepNum, unitStep );
+		},
 
-	},
+		/**
+		 * Creates MMDPhysicsHelper
+		 *
+		 * @return {MMDPhysicsHelper}
+		 */
+		createHelper: function () {
 
-	updateRigidBodies: function () {
+			return new MMDPhysicsHelper( this.mesh, this );
 
-		for ( var i = 0; i < this.bodies.length; i++ ) {
+		},
 
-			this.bodies[ i ].updateFromBone();
+		// private methods
 
-		}
+		_init: function ( mesh, rigidBodyParams, constraintParams ) {
 
-	},
+			var manager = this.manager;
 
-	updateBones: function () {
+			// rigid body/constraint parameters are for
+			// mesh's default world transform as position(0, 0, 0),
+			// quaternion(0, 0, 0, 1) and scale(0, 0, 0)
 
-		for ( var i = 0; i < this.bodies.length; i++ ) {
+			var parent = mesh.parent;
 
-			this.bodies[ i ].updateBone();
+			if ( parent !== null ) parent = null;
 
-		}
+			var currentPosition = manager.allocThreeVector3();
+			var currentQuaternion = manager.allocThreeQuaternion();
+			var currentScale = manager.allocThreeVector3();
 
-	},
+			currentPosition.copy( mesh.position );
+			currentQuaternion.copy( mesh.quaternion );
+			currentScale.copy( mesh.scale );
 
-	reset: function () {
+			mesh.position.set( 0, 0, 0 );
+			mesh.quaternion.set( 0, 0, 0, 1 );
+			mesh.scale.set( 1, 1, 1 );
 
-		for ( var i = 0; i < this.bodies.length; i++ ) {
+			mesh.updateMatrixWorld( true );
 
-			this.bodies[ i ].reset();
+			if ( this.world === null ) {
 
-		}
+				this.world = this._createWorld();
+				this.setGravity( this.gravity );
 
-	},
+			}
 
-	warmup: function ( cycles ) {
+			this._initRigidBodies( rigidBodyParams );
+			this._initConstraints( constraintParams );
 
-		for ( var i = 0; i < cycles; i++ ) {
+			if ( parent !== null ) mesh.parent = parent;
 
-			this.update( 1 / 60 );
+			mesh.position.copy( currentPosition );
+			mesh.quaternion.copy( currentQuaternion );
+			mesh.scale.copy( currentScale );
 
-		}
+			mesh.updateMatrixWorld( true );
 
-	}
+			this.reset();
 
-};
+			manager.freeThreeVector3( currentPosition );
+			manager.freeThreeQuaternion( currentQuaternion );
+			manager.freeThreeVector3( currentScale );
 
-/**
- * This helper class responsibilies are
- *
- * 1. manage Ammo.js and Three.js object resources and
- *    improve the performance and the memory consumption by
- *    reusing objects.
- *
- * 2. provide simple Ammo object operations.
- */
-THREE.MMDPhysics.ResourceHelper = function () {
+		},
 
-	// for Three.js
-	this.threeVector3s = [];
-	this.threeMatrix4s = [];
-	this.threeQuaternions = [];
-	this.threeEulers = [];
+		_createWorld: function () {
 
-	// for Ammo.js
-	this.transforms = [];
-	this.quaternions = [];
-	this.vector3s = [];
+			var config = new Ammo.btDefaultCollisionConfiguration();
+			var dispatcher = new Ammo.btCollisionDispatcher( config );
+			var cache = new Ammo.btDbvtBroadphase();
+			var solver = new Ammo.btSequentialImpulseConstraintSolver();
+			var world = new Ammo.btDiscreteDynamicsWorld( dispatcher, cache, solver, config );
+			return world;
 
-};
+		},
 
-THREE.MMDPhysics.ResourceHelper.prototype = {
+		_initRigidBodies: function ( rigidBodies ) {
 
-	allocThreeVector3: function () {
+			for ( var i = 0, il = rigidBodies.length; i < il; i++ ) {
 
-		return ( this.threeVector3s.length > 0 ) ? this.threeVector3s.pop() : new THREE.Vector3();
+				this.bodies.push( new RigidBody(
+					this.mesh, this.world, rigidBodies[ i ], this.manager ) );
 
-	},
+			}
 
-	freeThreeVector3: function ( v ) {
+		},
 
-		this.threeVector3s.push( v );
+		_initConstraints: function ( constraints ) {
 
-	},
+			for ( var i = 0, il = constraints.length; i < il; i++ ) {
 
-	allocThreeMatrix4: function () {
+				var params = constraints[ i ];
+				var bodyA = this.bodies[ params.rigidBodyIndex1 ];
+				var bodyB = this.bodies[ params.rigidBodyIndex2 ];
+				this.constraints.push( new Constraint(
+					this.mesh, this.world, bodyA, bodyB, params, this.manager ) );
 
-		return ( this.threeMatrix4s.length > 0 ) ? this.threeMatrix4s.pop() : new THREE.Matrix4();
+			}
 
-	},
 
-	freeThreeMatrix4: function ( m ) {
+		},
 
-		this.threeMatrix4s.push( m );
+		_stepSimulation: function ( delta ) {
 
-	},
+			var unitStep = this.unitStep;
+			var stepTime = delta;
+			var maxStepNum = ( ( delta / unitStep ) | 0 ) + 1;
 
-	allocThreeQuaternion: function () {
+			if ( stepTime < unitStep ) {
 
-		return ( this.threeQuaternions.length > 0 ) ? this.threeQuaternions.pop() : new THREE.Quaternion();
+				stepTime = unitStep;
+				maxStepNum = 1;
 
-	},
+			}
 
-	freeThreeQuaternion: function ( q ) {
+			if ( maxStepNum > this.maxStepNum ) {
 
-		this.threeQuaternions.push( q );
+				maxStepNum = this.maxStepNum;
 
-	},
+			}
 
-	allocThreeEuler: function () {
+			this.world.stepSimulation( stepTime, maxStepNum, unitStep );
 
-		return ( this.threeEulers.length > 0 ) ? this.threeEulers.pop() : new THREE.Euler();
+		},
 
-	},
+		_updateRigidBodies: function () {
 
-	freeThreeEuler: function ( e ) {
+			for ( var i = 0, il = this.bodies.length; i < il; i++ ) {
 
-		this.threeEulers.push( e );
+				this.bodies[ i ].updateFromBone();
 
-	},
+			}
 
-	allocTransform: function () {
+		},
 
-		return ( this.transforms.length > 0 ) ? this.transforms.pop() : new Ammo.btTransform();
+		_updateBones: function () {
 
-	},
+			for ( var i = 0, il = this.bodies.length; i < il; i++ ) {
 
-	freeTransform: function ( t ) {
+				this.bodies[ i ].updateBone();
 
-		this.transforms.push( t );
+			}
 
-	},
+		}
 
-	allocQuaternion: function () {
+	};
 
-		return ( this.quaternions.length > 0 ) ? this.quaternions.pop() : new Ammo.btQuaternion();
+	/**
+	 * This manager's responsibilies are
+	 *
+	 * 1. manage Ammo.js and Three.js object resources and
+	 *    improve the performance and the memory consumption by
+	 *    reusing objects.
+	 *
+	 * 2. provide simple Ammo object operations.
+	 */
+	function ResourceManager() {
 
-	},
+		// for Three.js
+		this.threeVector3s = [];
+		this.threeMatrix4s = [];
+		this.threeQuaternions = [];
+		this.threeEulers = [];
 
-	freeQuaternion: function ( q ) {
+		// for Ammo.js
+		this.transforms = [];
+		this.quaternions = [];
+		this.vector3s = [];
 
-		this.quaternions.push( q );
+	}
 
-	},
+	ResourceManager.prototype = {
 
-	allocVector3: function () {
+		constructor: ResourceManager,
 
-		return ( this.vector3s.length > 0 ) ? this.vector3s.pop() : new Ammo.btVector3();
+		allocThreeVector3: function () {
 
-	},
+			return ( this.threeVector3s.length > 0 )
+				? this.threeVector3s.pop()
+				: new THREE.Vector3();
 
-	freeVector3: function ( v ) {
+		},
 
-		this.vector3s.push( v );
+		freeThreeVector3: function ( v ) {
 
-	},
+			this.threeVector3s.push( v );
 
-	setIdentity: function ( t ) {
+		},
 
-		t.setIdentity();
+		allocThreeMatrix4: function () {
 
-	},
+			return ( this.threeMatrix4s.length > 0 )
+				? this.threeMatrix4s.pop()
+				: new THREE.Matrix4();
 
-	getBasis: function ( t ) {
+		},
 
-		var q = this.allocQuaternion();
-		t.getBasis().getRotation( q );
-		return q;
+		freeThreeMatrix4: function ( m ) {
 
-	},
+			this.threeMatrix4s.push( m );
 
-	getBasisAsMatrix3: function ( t ) {
+		},
 
-		var q = this.getBasis( t );
-		var m = this.quaternionToMatrix3( q );
-		this.freeQuaternion( q );
-		return m;
+		allocThreeQuaternion: function () {
 
-	},
+			return ( this.threeQuaternions.length > 0 )
+				? this.threeQuaternions.pop()
+				: new THREE.Quaternion();
 
-	getOrigin: function( t ) {
+		},
 
-		return t.getOrigin();
+		freeThreeQuaternion: function ( q ) {
 
-	},
+			this.threeQuaternions.push( q );
 
-	setOrigin: function( t, v ) {
+		},
 
-		t.getOrigin().setValue( v.x(), v.y(), v.z() );
+		allocThreeEuler: function () {
 
-	},
+			return ( this.threeEulers.length > 0 )
+				? this.threeEulers.pop()
+				: new THREE.Euler();
 
-	copyOrigin: function( t1, t2 ) {
+		},
 
-		var o = t2.getOrigin();
-		this.setOrigin( t1, o );
+		freeThreeEuler: function ( e ) {
 
-	},
+			this.threeEulers.push( e );
 
-	setBasis: function( t, q ) {
+		},
 
-		t.setRotation( q );
+		allocTransform: function () {
 
-	},
+			return ( this.transforms.length > 0 )
+				? this.transforms.pop()
+				: new Ammo.btTransform();
 
-	setBasisFromMatrix3: function( t, m ) {
+		},
 
-		var q = this.matrix3ToQuaternion( m );
-		this.setBasis( t, q );
-		this.freeQuaternion( q );
+		freeTransform: function ( t ) {
 
-	},
+			this.transforms.push( t );
 
-	setOriginFromArray3: function ( t, a ) {
+		},
 
-		t.getOrigin().setValue( a[ 0 ], a[ 1 ], a[ 2 ] );
+		allocQuaternion: function () {
 
-	},
+			return ( this.quaternions.length > 0 )
+				? this.quaternions.pop()
+				: new Ammo.btQuaternion();
 
-	setOriginFromThreeVector3: function ( t, v ) {
+		},
 
-		t.getOrigin().setValue( v.x, v.y, v.z );
+		freeQuaternion: function ( q ) {
 
-	},
+			this.quaternions.push( q );
 
-	setBasisFromArray3: function ( t, a ) {
+		},
 
-		var thQ = this.allocThreeQuaternion();
-		var thE = this.allocThreeEuler();
-		thE.set( a[ 0 ], a[ 1 ], a[ 2 ] );
-		this.setBasisFromThreeQuaternion( t, thQ.setFromEuler( thE ) );
+		allocVector3: function () {
 
-		this.freeThreeEuler( thE );
-		this.freeThreeQuaternion( thQ );
+			return ( this.vector3s.length > 0 )
+				? this.vector3s.pop()
+				: new Ammo.btVector3();
 
-	},
+		},
 
-	setBasisFromThreeQuaternion: function ( t, a ) {
+		freeVector3: function ( v ) {
 
-		var q = this.allocQuaternion();
+			this.vector3s.push( v );
 
-		q.setX( a.x );
-		q.setY( a.y );
-		q.setZ( a.z );
-		q.setW( a.w );
-		this.setBasis( t, q );
+		},
 
-		this.freeQuaternion( q );
+		setIdentity: function ( t ) {
 
-	},
+			t.setIdentity();
 
-	multiplyTransforms: function ( t1, t2 ) {
+		},
 
-		var t = this.allocTransform();
-		this.setIdentity( t );
+		getBasis: function ( t ) {
 
-		var m1 = this.getBasisAsMatrix3( t1 );
-		var m2 = this.getBasisAsMatrix3( t2 );
+			var q = this.allocQuaternion();
+			t.getBasis().getRotation( q );
+			return q;
 
-		var o1 = this.getOrigin( t1 );
-		var o2 = this.getOrigin( t2 );
+		},
 
-		var v1 = this.multiplyMatrix3ByVector3( m1, o2 );
-		var v2 = this.addVector3( v1, o1 );
-		this.setOrigin( t, v2 );
+		getBasisAsMatrix3: function ( t ) {
 
-		var m3 = this.multiplyMatrices3( m1, m2 );
-		this.setBasisFromMatrix3( t, m3 );
+			var q = this.getBasis( t );
+			var m = this.quaternionToMatrix3( q );
+			this.freeQuaternion( q );
+			return m;
 
-		this.freeVector3( v1 );
-		this.freeVector3( v2 );
+		},
 
-		return t;
+		getOrigin: function( t ) {
 
-	},
+			return t.getOrigin();
 
-	inverseTransform: function ( t ) {
+		},
 
-		var t2 = this.allocTransform();
+		setOrigin: function( t, v ) {
 
-		var m1 = this.getBasisAsMatrix3( t );
-		var o = this.getOrigin( t );
+			t.getOrigin().setValue( v.x(), v.y(), v.z() );
 
-		var m2 = this.transposeMatrix3( m1 );
-		var v1 = this.negativeVector3( o );
-		var v2 = this.multiplyMatrix3ByVector3( m2, v1 );
+		},
 
-		this.setOrigin( t2, v2 );
-		this.setBasisFromMatrix3( t2, m2 );
+		copyOrigin: function( t1, t2 ) {
 
-		this.freeVector3( v1 );
-		this.freeVector3( v2 );
+			var o = t2.getOrigin();
+			this.setOrigin( t1, o );
 
-		return t2;
+		},
 
-	},
+		setBasis: function( t, q ) {
 
-	multiplyMatrices3: function ( m1, m2 ) {
+			t.setRotation( q );
 
-		var m3 = [];
+		},
 
-		var v10 = this.rowOfMatrix3( m1, 0 );
-		var v11 = this.rowOfMatrix3( m1, 1 );
-		var v12 = this.rowOfMatrix3( m1, 2 );
+		setBasisFromMatrix3: function( t, m ) {
 
-		var v20 = this.columnOfMatrix3( m2, 0 );
-		var v21 = this.columnOfMatrix3( m2, 1 );
-		var v22 = this.columnOfMatrix3( m2, 2 );
+			var q = this.matrix3ToQuaternion( m );
+			this.setBasis( t, q );
+			this.freeQuaternion( q );
 
-		m3[ 0 ] = this.dotVectors3( v10, v20 );
-		m3[ 1 ] = this.dotVectors3( v10, v21 );
-		m3[ 2 ] = this.dotVectors3( v10, v22 );
-		m3[ 3 ] = this.dotVectors3( v11, v20 );
-		m3[ 4 ] = this.dotVectors3( v11, v21 );
-		m3[ 5 ] = this.dotVectors3( v11, v22 );
-		m3[ 6 ] = this.dotVectors3( v12, v20 );
-		m3[ 7 ] = this.dotVectors3( v12, v21 );
-		m3[ 8 ] = this.dotVectors3( v12, v22 );
+		},
 
-		this.freeVector3( v10 );
-		this.freeVector3( v11 );
-		this.freeVector3( v12 );
-		this.freeVector3( v20 );
-		this.freeVector3( v21 );
-		this.freeVector3( v22 );
+		setOriginFromArray3: function ( t, a ) {
 
-		return m3;
+			t.getOrigin().setValue( a[ 0 ], a[ 1 ], a[ 2 ] );
 
-	},
+		},
 
-	addVector3: function( v1, v2 ) {
+		setOriginFromThreeVector3: function ( t, v ) {
 
-		var v = this.allocVector3();
-		v.setValue( v1.x() + v2.x(), v1.y() + v2.y(), v1.z() + v2.z() );
-		return v;
+			t.getOrigin().setValue( v.x, v.y, v.z );
 
-	},
+		},
 
-	dotVectors3: function( v1, v2 ) {
+		setBasisFromArray3: function ( t, a ) {
 
-		return v1.x() * v2.x() + v1.y() * v2.y() + v1.z() * v2.z();
+			var thQ = this.allocThreeQuaternion();
+			var thE = this.allocThreeEuler();
+			thE.set( a[ 0 ], a[ 1 ], a[ 2 ] );
+			this.setBasisFromThreeQuaternion( t, thQ.setFromEuler( thE ) );
 
-	},
+			this.freeThreeEuler( thE );
+			this.freeThreeQuaternion( thQ );
 
-	rowOfMatrix3: function( m, i ) {
+		},
 
-		var v = this.allocVector3();
-		v.setValue( m[ i * 3 + 0 ], m[ i * 3 + 1 ], m[ i * 3 + 2 ] );
-		return v;
+		setBasisFromThreeQuaternion: function ( t, a ) {
 
-	},
+			var q = this.allocQuaternion();
 
-	columnOfMatrix3: function( m, i ) {
+			q.setX( a.x );
+			q.setY( a.y );
+			q.setZ( a.z );
+			q.setW( a.w );
+			this.setBasis( t, q );
 
-		var v = this.allocVector3();
-		v.setValue( m[ i + 0 ], m[ i + 3 ], m[ i + 6 ] );
-		return v;
+			this.freeQuaternion( q );
 
-	},
+		},
 
-	negativeVector3: function( v ) {
+		multiplyTransforms: function ( t1, t2 ) {
 
-		var v2 = this.allocVector3();
-		v2.setValue( -v.x(), -v.y(), -v.z() );
-		return v2;
+			var t = this.allocTransform();
+			this.setIdentity( t );
 
-	},
+			var m1 = this.getBasisAsMatrix3( t1 );
+			var m2 = this.getBasisAsMatrix3( t2 );
 
-	multiplyMatrix3ByVector3: function ( m, v ) {
+			var o1 = this.getOrigin( t1 );
+			var o2 = this.getOrigin( t2 );
 
-		var v4 = this.allocVector3();
+			var v1 = this.multiplyMatrix3ByVector3( m1, o2 );
+			var v2 = this.addVector3( v1, o1 );
+			this.setOrigin( t, v2 );
 
-		var v0 = this.rowOfMatrix3( m, 0 );
-		var v1 = this.rowOfMatrix3( m, 1 );
-		var v2 = this.rowOfMatrix3( m, 2 );
-		var x = this.dotVectors3( v0, v );
-		var y = this.dotVectors3( v1, v );
-		var z = this.dotVectors3( v2, v );
+			var m3 = this.multiplyMatrices3( m1, m2 );
+			this.setBasisFromMatrix3( t, m3 );
 
-		v4.setValue( x, y, z );
+			this.freeVector3( v1 );
+			this.freeVector3( v2 );
 
-		this.freeVector3( v0 );
-		this.freeVector3( v1 );
-		this.freeVector3( v2 );
+			return t;
 
-		return v4;
+		},
 
-	},
+		inverseTransform: function ( t ) {
 
-	transposeMatrix3: function( m ) {
+			var t2 = this.allocTransform();
 
-		var m2 = [];
-		m2[ 0 ] = m[ 0 ];
-		m2[ 1 ] = m[ 3 ];
-		m2[ 2 ] = m[ 6 ];
-		m2[ 3 ] = m[ 1 ];
-		m2[ 4 ] = m[ 4 ];
-		m2[ 5 ] = m[ 7 ];
-		m2[ 6 ] = m[ 2 ];
-		m2[ 7 ] = m[ 5 ];
-		m2[ 8 ] = m[ 8 ];
-		return m2;
+			var m1 = this.getBasisAsMatrix3( t );
+			var o = this.getOrigin( t );
 
-	},
+			var m2 = this.transposeMatrix3( m1 );
+			var v1 = this.negativeVector3( o );
+			var v2 = this.multiplyMatrix3ByVector3( m2, v1 );
 
-	quaternionToMatrix3: function ( q ) {
+			this.setOrigin( t2, v2 );
+			this.setBasisFromMatrix3( t2, m2 );
 
-		var m = [];
+			this.freeVector3( v1 );
+			this.freeVector3( v2 );
 
-		var x = q.x();
-		var y = q.y();
-		var z = q.z();
-		var w = q.w();
+			return t2;
 
-		var xx = x * x;
-		var yy = y * y;
-		var zz = z * z;
+		},
 
-		var xy = x * y;
-		var yz = y * z;
-		var zx = z * x;
+		multiplyMatrices3: function ( m1, m2 ) {
 
-		var xw = x * w;
-		var yw = y * w;
-		var zw = z * w;
+			var m3 = [];
 
-		m[ 0 ] = 1 - 2 * ( yy + zz );
-		m[ 1 ] = 2 * ( xy - zw );
-		m[ 2 ] = 2 * ( zx + yw );
-		m[ 3 ] = 2 * ( xy + zw );
-		m[ 4 ] = 1 - 2 * ( zz + xx );
-		m[ 5 ] = 2 * ( yz - xw );
-		m[ 6 ] = 2 * ( zx - yw );
-		m[ 7 ] = 2 * ( yz + xw );
-		m[ 8 ] = 1 - 2 * ( xx + yy );
+			var v10 = this.rowOfMatrix3( m1, 0 );
+			var v11 = this.rowOfMatrix3( m1, 1 );
+			var v12 = this.rowOfMatrix3( m1, 2 );
 
-		return m;
+			var v20 = this.columnOfMatrix3( m2, 0 );
+			var v21 = this.columnOfMatrix3( m2, 1 );
+			var v22 = this.columnOfMatrix3( m2, 2 );
 
-	},
+			m3[ 0 ] = this.dotVectors3( v10, v20 );
+			m3[ 1 ] = this.dotVectors3( v10, v21 );
+			m3[ 2 ] = this.dotVectors3( v10, v22 );
+			m3[ 3 ] = this.dotVectors3( v11, v20 );
+			m3[ 4 ] = this.dotVectors3( v11, v21 );
+			m3[ 5 ] = this.dotVectors3( v11, v22 );
+			m3[ 6 ] = this.dotVectors3( v12, v20 );
+			m3[ 7 ] = this.dotVectors3( v12, v21 );
+			m3[ 8 ] = this.dotVectors3( v12, v22 );
 
-	matrix3ToQuaternion: function( m ) {
+			this.freeVector3( v10 );
+			this.freeVector3( v11 );
+			this.freeVector3( v12 );
+			this.freeVector3( v20 );
+			this.freeVector3( v21 );
+			this.freeVector3( v22 );
 
-		var t = m[ 0 ] + m[ 4 ] + m[ 8 ];
-		var s, x, y, z, w;
+			return m3;
 
-		if( t > 0 ) {
+		},
 
-			s = Math.sqrt( t + 1.0 ) * 2;
-			w = 0.25 * s;
-			x = ( m[ 7 ] - m[ 5 ] ) / s;
-			y = ( m[ 2 ] - m[ 6 ] ) / s; 
-			z = ( m[ 3 ] - m[ 1 ] ) / s; 
+		addVector3: function( v1, v2 ) {
 
-		} else if( ( m[ 0 ] > m[ 4 ] ) && ( m[ 0 ] > m[ 8 ] ) ) {
+			var v = this.allocVector3();
+			v.setValue( v1.x() + v2.x(), v1.y() + v2.y(), v1.z() + v2.z() );
+			return v;
 
-			s = Math.sqrt( 1.0 + m[ 0 ] - m[ 4 ] - m[ 8 ] ) * 2;
-			w = ( m[ 7 ] - m[ 5 ] ) / s;
-			x = 0.25 * s;
-			y = ( m[ 1 ] + m[ 3 ] ) / s;
-			z = ( m[ 2 ] + m[ 6 ] ) / s;
+		},
 
-		} else if( m[ 4 ] > m[ 8 ] ) {
+		dotVectors3: function( v1, v2 ) {
 
-			s = Math.sqrt( 1.0 + m[ 4 ] - m[ 0 ] - m[ 8 ] ) * 2;
-			w = ( m[ 2 ] - m[ 6 ] ) / s;
-			x = ( m[ 1 ] + m[ 3 ] ) / s;
-			y = 0.25 * s;
-			z = ( m[ 5 ] + m[ 7 ] ) / s;
+			return v1.x() * v2.x() + v1.y() * v2.y() + v1.z() * v2.z();
 
-		} else {
+		},
 
-			s = Math.sqrt( 1.0 + m[ 8 ] - m[ 0 ] - m[ 4 ] ) * 2;
-			w = ( m[ 3 ] - m[ 1 ] ) / s;
-			x = ( m[ 2 ] + m[ 6 ] ) / s;
-			y = ( m[ 5 ] + m[ 7 ] ) / s;
-			z = 0.25 * s;
+		rowOfMatrix3: function( m, i ) {
 
-		}
+			var v = this.allocVector3();
+			v.setValue( m[ i * 3 + 0 ], m[ i * 3 + 1 ], m[ i * 3 + 2 ] );
+			return v;
 
-		var q = this.allocQuaternion();
-		q.setX( x );
-		q.setY( y );
-		q.setZ( z );
-		q.setW( w );
-		return q;
+		},
 
-	}
+		columnOfMatrix3: function( m, i ) {
 
-};
+			var v = this.allocVector3();
+			v.setValue( m[ i + 0 ], m[ i + 3 ], m[ i + 6 ] );
+			return v;
 
-THREE.MMDPhysics.RigidBody = function ( mesh, world, params, helper ) {
+		},
 
-	this.mesh  = mesh;
-	this.world = world;
-	this.params = params;
-	this.helper = helper;
+		negativeVector3: function( v ) {
 
-	this.body = null;
-	this.bone = null;
-	this.boneOffsetForm = null;
-	this.boneOffsetFormInverse = null;
+			var v2 = this.allocVector3();
+			v2.setValue( -v.x(), -v.y(), -v.z() );
+			return v2;
 
-	this.init();
+		},
 
-};
+		multiplyMatrix3ByVector3: function ( m, v ) {
 
-THREE.MMDPhysics.RigidBody.prototype = {
+			var v4 = this.allocVector3();
 
-	constructor: THREE.MMDPhysics.RigidBody,
+			var v0 = this.rowOfMatrix3( m, 0 );
+			var v1 = this.rowOfMatrix3( m, 1 );
+			var v2 = this.rowOfMatrix3( m, 2 );
+			var x = this.dotVectors3( v0, v );
+			var y = this.dotVectors3( v1, v );
+			var z = this.dotVectors3( v2, v );
 
-	init: function () {
+			v4.setValue( x, y, z );
 
-		function generateShape( p ) {
+			this.freeVector3( v0 );
+			this.freeVector3( v1 );
+			this.freeVector3( v2 );
 
-			switch( p.shapeType ) {
+			return v4;
 
-				case 0:
-					return new Ammo.btSphereShape( p.width );
+		},
 
-				case 1:
-					return new Ammo.btBoxShape( new Ammo.btVector3( p.width, p.height, p.depth ) );
+		transposeMatrix3: function( m ) {
 
-				case 2:
-					return new Ammo.btCapsuleShape( p.width, p.height );
+			var m2 = [];
+			m2[ 0 ] = m[ 0 ];
+			m2[ 1 ] = m[ 3 ];
+			m2[ 2 ] = m[ 6 ];
+			m2[ 3 ] = m[ 1 ];
+			m2[ 4 ] = m[ 4 ];
+			m2[ 5 ] = m[ 7 ];
+			m2[ 6 ] = m[ 2 ];
+			m2[ 7 ] = m[ 5 ];
+			m2[ 8 ] = m[ 8 ];
+			return m2;
 
-				default:
-					throw 'unknown shape type ' + p.shapeType;
+		},
 
-			}
+		quaternionToMatrix3: function ( q ) {
 
-		}
+			var m = [];
 
-		var helper = this.helper;
-		var params = this.params;
-		var bones = this.mesh.skeleton.bones;
-		var bone = ( params.boneIndex === -1 ) ? new THREE.Bone() : bones[ params.boneIndex ];
+			var x = q.x();
+			var y = q.y();
+			var z = q.z();
+			var w = q.w();
 
-		var shape = generateShape( params );
-		var weight = ( params.type === 0 ) ? 0 : params.weight;
-		var localInertia = helper.allocVector3();
-		localInertia.setValue( 0, 0, 0 );
+			var xx = x * x;
+			var yy = y * y;
+			var zz = z * z;
 
-		if( weight !== 0 ) {
+			var xy = x * y;
+			var yz = y * z;
+			var zx = z * x;
 
-			shape.calculateLocalInertia( weight, localInertia );
+			var xw = x * w;
+			var yw = y * w;
+			var zw = z * w;
 
-		}
+			m[ 0 ] = 1 - 2 * ( yy + zz );
+			m[ 1 ] = 2 * ( xy - zw );
+			m[ 2 ] = 2 * ( zx + yw );
+			m[ 3 ] = 2 * ( xy + zw );
+			m[ 4 ] = 1 - 2 * ( zz + xx );
+			m[ 5 ] = 2 * ( yz - xw );
+			m[ 6 ] = 2 * ( zx - yw );
+			m[ 7 ] = 2 * ( yz + xw );
+			m[ 8 ] = 1 - 2 * ( xx + yy );
 
-		var boneOffsetForm = helper.allocTransform();
-		helper.setIdentity( boneOffsetForm );
-		helper.setOriginFromArray3( boneOffsetForm, params.position );
-		helper.setBasisFromArray3( boneOffsetForm, params.rotation );
+			return m;
 
-		var vector = helper.allocThreeVector3();
-		var boneForm = helper.allocTransform();
-		helper.setIdentity( boneForm );
-		helper.setOriginFromThreeVector3( boneForm, bone.getWorldPosition( vector ) );
+		},
 
-		var form = helper.multiplyTransforms( boneForm, boneOffsetForm );
-		var state = new Ammo.btDefaultMotionState( form );
+		matrix3ToQuaternion: function( m ) {
 
-		var info = new Ammo.btRigidBodyConstructionInfo( weight, state, shape, localInertia );
-		info.set_m_friction( params.friction );
-		info.set_m_restitution( params.restitution );
+			var t = m[ 0 ] + m[ 4 ] + m[ 8 ];
+			var s, x, y, z, w;
 
-		var body = new Ammo.btRigidBody( info );
+			if( t > 0 ) {
 
-		if ( params.type === 0 ) {
+				s = Math.sqrt( t + 1.0 ) * 2;
+				w = 0.25 * s;
+				x = ( m[ 7 ] - m[ 5 ] ) / s;
+				y = ( m[ 2 ] - m[ 6 ] ) / s; 
+				z = ( m[ 3 ] - m[ 1 ] ) / s; 
 
-			body.setCollisionFlags( body.getCollisionFlags() | 2 );
+			} else if( ( m[ 0 ] > m[ 4 ] ) && ( m[ 0 ] > m[ 8 ] ) ) {
 
-			/*
-			 * It'd be better to comment out this line though in general I should call this method
-			 * because I'm not sure why but physics will be more like MMD's
-			 * if I comment out.
-			 */
-			body.setActivationState( 4 );
+				s = Math.sqrt( 1.0 + m[ 0 ] - m[ 4 ] - m[ 8 ] ) * 2;
+				w = ( m[ 7 ] - m[ 5 ] ) / s;
+				x = 0.25 * s;
+				y = ( m[ 1 ] + m[ 3 ] ) / s;
+				z = ( m[ 2 ] + m[ 6 ] ) / s;
 
-		}
+			} else if( m[ 4 ] > m[ 8 ] ) {
 
-		body.setDamping( params.positionDamping, params.rotationDamping );
-		body.setSleepingThresholds( 0, 0 );
+				s = Math.sqrt( 1.0 + m[ 4 ] - m[ 0 ] - m[ 8 ] ) * 2;
+				w = ( m[ 2 ] - m[ 6 ] ) / s;
+				x = ( m[ 1 ] + m[ 3 ] ) / s;
+				y = 0.25 * s;
+				z = ( m[ 5 ] + m[ 7 ] ) / s;
 
-		this.world.addRigidBody( body, 1 << params.groupIndex, params.groupTarget );
+			} else {
 
-		this.body = body;
-		this.bone = bone;
-		this.boneOffsetForm = boneOffsetForm;
-		this.boneOffsetFormInverse = helper.inverseTransform( boneOffsetForm );
+				s = Math.sqrt( 1.0 + m[ 8 ] - m[ 0 ] - m[ 4 ] ) * 2;
+				w = ( m[ 3 ] - m[ 1 ] ) / s;
+				x = ( m[ 2 ] + m[ 6 ] ) / s;
+				y = ( m[ 5 ] + m[ 7 ] ) / s;
+				z = 0.25 * s;
 
-		helper.freeVector3( localInertia );
-		helper.freeTransform( form );
-		helper.freeTransform( boneForm );
-		helper.freeThreeVector3( vector );
+			}
 
-	},
+			var q = this.allocQuaternion();
+			q.setX( x );
+			q.setY( y );
+			q.setZ( z );
+			q.setW( w );
+			return q;
 
-	reset: function () {
+		}
 
-		this.setTransformFromBone();
+	};
 
-	},
+	/**
+	 * @param {THREE.SkinnedMesh} mesh
+	 * @param {Ammo.btDiscreteDynamicsWorld} world
+	 * @param {Object} params
+	 * @param {ResourceManager} manager
+	 */
+	function RigidBody( mesh, world, params, manager ) {
 
-	updateFromBone: function () {
+		this.mesh  = mesh;
+		this.world = world;
+		this.params = params;
+		this.manager = manager;
 
-		if ( this.params.boneIndex === -1 ) {
+		this.body = null;
+		this.bone = null;
+		this.boneOffsetForm = null;
+		this.boneOffsetFormInverse = null;
 
-			return;
+		this._init();
 
-		}
+	}
 
-		if ( this.params.type === 0 ) {
+	RigidBody.prototype = {
 
-			this.setTransformFromBone();
+		constructor: MMDPhysics.RigidBody,
 
-		}
+		/**
+		 * Resets rigid body transform to the current bone's.
+		 *
+		 * @return {RigidBody}
+		 */
+		reset: function () {
 
-	},
+			this._setTransformFromBone();
+			return this;
 
-	updateBone: function () {
+		},
 
-		if ( this.params.type === 0 || this.params.boneIndex === -1 ) {
+		/**
+		 * Updates rigid body's transform from the current bone.
+		 *
+		 * @return {RidigBody}
+		 */
+		updateFromBone: function () {
 
-			return;
+			if ( this.params.boneIndex !== - 1 &&
+				this.params.type === 0 ) {
 
-		}
+				this._setTransformFromBone();
 
-		this.updateBoneRotation();
+			}
 
-		if ( this.params.type === 1 ) {
+			return this;
 
-			this.updateBonePosition();
+		},
 
-		}
+		/**
+		 * Updates bone from the current ridid body's transform.
+		 *
+		 * @return {RidigBody}
+		 */
+		updateBone: function () {
 
-		this.bone.updateMatrixWorld( true );
+			if ( this.params.type === 0 ||
+				this.params.boneIndex === - 1 ) {
 
-		if ( this.params.type === 2 ) {
+				return this;
 
-			this.setPositionFromBone();
+			}
 
-		}
+			this._updateBoneRotation();
 
-	},
+			if ( this.params.type === 1 ) {
 
-	getBoneTransform: function () {
+				this._updateBonePosition();
 
-		var helper = this.helper;
-		var p = helper.allocThreeVector3();
-		var q = helper.allocThreeQuaternion();
-		var s = helper.allocThreeVector3();
+			}
 
-		this.bone.matrixWorld.decompose( p, q, s );
+			this.bone.updateMatrixWorld( true );
 
-		var tr = helper.allocTransform();
-		helper.setOriginFromThreeVector3( tr, p );
-		helper.setBasisFromThreeQuaternion( tr, q );
+			if ( this.params.type === 2 ) {
 
-		var form = helper.multiplyTransforms( tr, this.boneOffsetForm );
+				this._setPositionFromBone();
 
-		helper.freeTransform( tr );
-		helper.freeThreeVector3( s );
-		helper.freeThreeQuaternion( q );
-		helper.freeThreeVector3( p );
+			}
 
-		return form;
+			return this;
 
-	},
+		},
 
-	getWorldTransformForBone: function () {
+		// private methods
 
-		var helper = this.helper;
+		_init: function () {
 
-		var tr = helper.allocTransform();
-		this.body.getMotionState().getWorldTransform( tr );
-		var tr2 = helper.multiplyTransforms( tr, this.boneOffsetFormInverse );
+			function generateShape( p ) {
 
-		helper.freeTransform( tr );
+				switch( p.shapeType ) {
 
-		return tr2;
+					case 0:
+						return new Ammo.btSphereShape( p.width );
 
-	},
+					case 1:
+						return new Ammo.btBoxShape( new Ammo.btVector3( p.width, p.height, p.depth ) );
 
-	setTransformFromBone: function () {
+					case 2:
+						return new Ammo.btCapsuleShape( p.width, p.height );
 
-		var helper = this.helper;
-		var form = this.getBoneTransform();
+					default:
+						throw 'unknown shape type ' + p.shapeType;
 
-		// TODO: check the most appropriate way to set
-		//this.body.setWorldTransform( form );
-		this.body.setCenterOfMassTransform( form );
-		this.body.getMotionState().setWorldTransform( form );
+				}
 
-		helper.freeTransform( form );
+			}
 
-	},
+			var manager = this.manager;
+			var params = this.params;
+			var bones = this.mesh.skeleton.bones;
+			var bone = ( params.boneIndex === - 1 )
+				? new THREE.Bone()
+				: bones[ params.boneIndex ];
 
-	setPositionFromBone: function () {
+			var shape = generateShape( params );
+			var weight = ( params.type === 0 ) ? 0 : params.weight;
+			var localInertia = manager.allocVector3();
+			localInertia.setValue( 0, 0, 0 );
 
-		var helper = this.helper;
-		var form = this.getBoneTransform();
+			if( weight !== 0 ) {
 
-		var tr = helper.allocTransform();
-		this.body.getMotionState().getWorldTransform( tr );
-		helper.copyOrigin( tr, form );
+				shape.calculateLocalInertia( weight, localInertia );
 
-		// TODO: check the most appropriate way to set
-		//this.body.setWorldTransform( tr );
-		this.body.setCenterOfMassTransform( tr );
-		this.body.getMotionState().setWorldTransform( tr );
+			}
 
-		helper.freeTransform( tr );
-		helper.freeTransform( form );
+			var boneOffsetForm = manager.allocTransform();
+			manager.setIdentity( boneOffsetForm );
+			manager.setOriginFromArray3( boneOffsetForm, params.position );
+			manager.setBasisFromArray3( boneOffsetForm, params.rotation );
 
-	},
+			var vector = manager.allocThreeVector3();
+			var boneForm = manager.allocTransform();
+			manager.setIdentity( boneForm );
+			manager.setOriginFromThreeVector3( boneForm, bone.getWorldPosition( vector ) );
 
-	updateBoneRotation: function () {
+			var form = manager.multiplyTransforms( boneForm, boneOffsetForm );
+			var state = new Ammo.btDefaultMotionState( form );
 
-		var helper = this.helper;
+			var info = new Ammo.btRigidBodyConstructionInfo( weight, state, shape, localInertia );
+			info.set_m_friction( params.friction );
+			info.set_m_restitution( params.restitution );
 
-		var tr = this.getWorldTransformForBone();
-		var q = helper.getBasis( tr );
+			var body = new Ammo.btRigidBody( info );
 
-		var thQ = helper.allocThreeQuaternion();
-		var thQ2 = helper.allocThreeQuaternion();
-		var thQ3 = helper.allocThreeQuaternion();
+			if ( params.type === 0 ) {
 
-		thQ.set( q.x(), q.y(), q.z(), q.w() );
-		thQ2.setFromRotationMatrix( this.bone.matrixWorld );
-		thQ2.conjugate();
-		thQ2.multiply( thQ );
+				body.setCollisionFlags( body.getCollisionFlags() | 2 );
 
-		//this.bone.quaternion.multiply( thQ2 );
+				/*
+				 * It'd be better to comment out this line though in general I should call this method
+				 * because I'm not sure why but physics will be more like MMD's
+				 * if I comment out.
+				 */
+				body.setActivationState( 4 );
 
-		thQ3.setFromRotationMatrix( this.bone.matrix );
-		this.bone.quaternion.copy( thQ2.multiply( thQ3 ) );
+			}
 
-		helper.freeThreeQuaternion( thQ );
-		helper.freeThreeQuaternion( thQ2 );
-		helper.freeThreeQuaternion( thQ3 );
+			body.setDamping( params.positionDamping, params.rotationDamping );
+			body.setSleepingThresholds( 0, 0 );
 
-		helper.freeQuaternion( q );
-		helper.freeTransform( tr );
+			this.world.addRigidBody( body, 1 << params.groupIndex, params.groupTarget );
 
-	},
+			this.body = body;
+			this.bone = bone;
+			this.boneOffsetForm = boneOffsetForm;
+			this.boneOffsetFormInverse = manager.inverseTransform( boneOffsetForm );
 
-	updateBonePosition: function () {
+			manager.freeVector3( localInertia );
+			manager.freeTransform( form );
+			manager.freeTransform( boneForm );
+			manager.freeThreeVector3( vector );
 
-		var helper = this.helper;
+		},
 
-		var tr = this.getWorldTransformForBone();
+		_getBoneTransform: function () {
 
-		var thV = helper.allocThreeVector3();
+			var manager = this.manager;
+			var p = manager.allocThreeVector3();
+			var q = manager.allocThreeQuaternion();
+			var s = manager.allocThreeVector3();
 
-		var o = helper.getOrigin( tr );
-		thV.set( o.x(), o.y(), o.z() );
+			this.bone.matrixWorld.decompose( p, q, s );
 
-		var v = this.bone.worldToLocal( thV );
-		this.bone.position.add( v );
+			var tr = manager.allocTransform();
+			manager.setOriginFromThreeVector3( tr, p );
+			manager.setBasisFromThreeQuaternion( tr, q );
 
-		helper.freeThreeVector3( thV );
+			var form = manager.multiplyTransforms( tr, this.boneOffsetForm );
 
-		helper.freeTransform( tr );
+			manager.freeTransform( tr );
+			manager.freeThreeVector3( s );
+			manager.freeThreeQuaternion( q );
+			manager.freeThreeVector3( p );
 
-	}
+			return form;
 
-};
+		},
 
-THREE.MMDPhysics.Constraint = function ( mesh, world, bodyA, bodyB, params, helper ) {
+		_getWorldTransformForBone: function () {
 
-	this.mesh  = mesh;
-	this.world = world;
-	this.bodyA = bodyA;
-	this.bodyB = bodyB;
-	this.params = params;
-	this.helper = helper;
+			var manager = this.manager;
 
-	this.constraint = null;
+			var tr = manager.allocTransform();
+			this.body.getMotionState().getWorldTransform( tr );
+			var tr2 = manager.multiplyTransforms( tr, this.boneOffsetFormInverse );
 
-	this.init();
+			manager.freeTransform( tr );
 
-};
+			return tr2;
 
-THREE.MMDPhysics.Constraint.prototype = {
+		},
 
-	constructor: THREE.MMDPhysics.Constraint,
+		_setTransformFromBone: function () {
 
-	init: function () {
+			var manager = this.manager;
+			var form = this._getBoneTransform();
 
-		var helper = this.helper;
-		var params = this.params;
-		var bodyA = this.bodyA;
-		var bodyB = this.bodyB;
+			// TODO: check the most appropriate way to set
+			//this.body.setWorldTransform( form );
+			this.body.setCenterOfMassTransform( form );
+			this.body.getMotionState().setWorldTransform( form );
 
-		var form = helper.allocTransform();
-		helper.setIdentity( form );
-		helper.setOriginFromArray3( form, params.position );
-		helper.setBasisFromArray3( form, params.rotation );
+			manager.freeTransform( form );
 
-		var formA = helper.allocTransform();
-		var formB = helper.allocTransform();
+		},
 
-		bodyA.body.getMotionState().getWorldTransform( formA );
-		bodyB.body.getMotionState().getWorldTransform( formB );
+		_setPositionFromBone: function () {
 
-		var formInverseA = helper.inverseTransform( formA );
-		var formInverseB = helper.inverseTransform( formB );
+			var manager = this.manager;
+			var form = this._getBoneTransform();
 
-		var formA2 = helper.multiplyTransforms( formInverseA, form );
-		var formB2 = helper.multiplyTransforms( formInverseB, form );
+			var tr = manager.allocTransform();
+			this.body.getMotionState().getWorldTransform( tr );
+			manager.copyOrigin( tr, form );
 
-		var constraint = new Ammo.btGeneric6DofSpringConstraint( bodyA.body, bodyB.body, formA2, formB2, true );
+			// TODO: check the most appropriate way to set
+			//this.body.setWorldTransform( tr );
+			this.body.setCenterOfMassTransform( tr );
+			this.body.getMotionState().setWorldTransform( tr );
 
-		var lll = helper.allocVector3();
-		var lul = helper.allocVector3();
-		var all = helper.allocVector3();
-		var aul = helper.allocVector3();
+			manager.freeTransform( tr );
+			manager.freeTransform( form );
 
-		lll.setValue( params.translationLimitation1[ 0 ],
-		              params.translationLimitation1[ 1 ],
-		              params.translationLimitation1[ 2 ] );
-		lul.setValue( params.translationLimitation2[ 0 ],
-		              params.translationLimitation2[ 1 ],
-		              params.translationLimitation2[ 2 ] );
-		all.setValue( params.rotationLimitation1[ 0 ],
-		              params.rotationLimitation1[ 1 ],
-		              params.rotationLimitation1[ 2 ] );
-		aul.setValue( params.rotationLimitation2[ 0 ],
-		              params.rotationLimitation2[ 1 ],
-		              params.rotationLimitation2[ 2 ] );
+		},
 
-		constraint.setLinearLowerLimit( lll );
-		constraint.setLinearUpperLimit( lul );
-		constraint.setAngularLowerLimit( all );
-		constraint.setAngularUpperLimit( aul );
+		_updateBoneRotation: function () {
 
-		for ( var i = 0; i < 3; i++ ) {
+			var manager = this.manager;
 
-			if( params.springPosition[ i ] !== 0 ) {
+			var tr = this._getWorldTransformForBone();
+			var q = manager.getBasis( tr );
 
-				constraint.enableSpring( i, true );
-				constraint.setStiffness( i, params.springPosition[ i ] );
+			var thQ = manager.allocThreeQuaternion();
+			var thQ2 = manager.allocThreeQuaternion();
+			var thQ3 = manager.allocThreeQuaternion();
 
-			}
+			thQ.set( q.x(), q.y(), q.z(), q.w() );
+			thQ2.setFromRotationMatrix( this.bone.matrixWorld );
+			thQ2.conjugate();
+			thQ2.multiply( thQ );
 
-		}
+			//this.bone.quaternion.multiply( thQ2 );
 
-		for ( var i = 0; i < 3; i++ ) {
+			thQ3.setFromRotationMatrix( this.bone.matrix );
+			this.bone.quaternion.copy( thQ2.multiply( thQ3 ) );
 
-			if( params.springRotation[ i ] !== 0 ) {
+			manager.freeThreeQuaternion( thQ );
+			manager.freeThreeQuaternion( thQ2 );
+			manager.freeThreeQuaternion( thQ3 );
 
-				constraint.enableSpring( i + 3, true );
-				constraint.setStiffness( i + 3, params.springRotation[ i ] );
+			manager.freeQuaternion( q );
+			manager.freeTransform( tr );
 
-			}
+		},
 
-		}
+		_updateBonePosition: function () {
 
-		/*
-		 * Currently(10/31/2016) official ammo.js doesn't support
-		 * btGeneric6DofSpringConstraint.setParam method.
-		 * You need custom ammo.js (add the method into idl) if you wanna use.
-		 * By setting this parameter, physics will be more like MMD's
-		 */
-		if ( constraint.setParam !== undefined ) {
+			var manager = this.manager;
 
-			for ( var i = 0; i < 6; i ++ ) {
+			var tr = this._getWorldTransformForBone();
 
-				// this parameter is from http://www20.atpages.jp/katwat/three.js_r58/examples/mytest37/mmd.three.js
-				constraint.setParam( 2, 0.475, i );
+			var thV = manager.allocThreeVector3();
 
-			}
+			var o = manager.getOrigin( tr );
+			thV.set( o.x(), o.y(), o.z() );
+
+			var v = this.bone.worldToLocal( thV );
+			this.bone.position.add( v );
+
+			manager.freeThreeVector3( thV );
+
+			manager.freeTransform( tr );
 
 		}
 
-		this.world.addConstraint( constraint, true );
-		this.constraint = constraint;
-
-		helper.freeTransform( form );
-		helper.freeTransform( formA );
-		helper.freeTransform( formB );
-		helper.freeTransform( formInverseA );
-		helper.freeTransform( formInverseB );
-		helper.freeTransform( formA2 );
-		helper.freeTransform( formB2 );
-		helper.freeVector3( lll );
-		helper.freeVector3( lul );
-		helper.freeVector3( all );
-		helper.freeVector3( aul );
+	};
+
+	/**
+	 * @param {THREE.SkinnedMesh} mesh
+	 * @param {Ammo.btDiscreteDynamicsWorld} world
+	 * @param {RigidBody} bodyA
+	 * @param {RigidBody} bodyB
+	 * @param {Object} params
+	 * @param {ResourceManager} manager
+	 */
+	function Constraint( mesh, world, bodyA, bodyB, params, manager ) {
+
+		this.mesh  = mesh;
+		this.world = world;
+		this.bodyA = bodyA;
+		this.bodyB = bodyB;
+		this.params = params;
+		this.manager = manager;
+
+		this.constraint = null;
+
+		this._init();
 
 	}
 
-};
+	Constraint.prototype = {
 
+		constructor: Constraint,
 
-THREE.MMDPhysicsHelper = function ( mesh, physics ) {
+		// private method
 
-	if ( mesh.geometry.rigidBodies === undefined ) {
+		_init: function () {
 
-		throw new Error( 'THREE.MMDPhysicsHelper requires rigidBodies in mesh.geometry.' );
+			var manager = this.manager;
+			var params = this.params;
+			var bodyA = this.bodyA;
+			var bodyB = this.bodyB;
 
-	}
+			var form = manager.allocTransform();
+			manager.setIdentity( form );
+			manager.setOriginFromArray3( form, params.position );
+			manager.setBasisFromArray3( form, params.rotation );
 
-	THREE.Object3D.call( this );
+			var formA = manager.allocTransform();
+			var formB = manager.allocTransform();
 
-	this.root = mesh;
-	this.physics = physics;
+			bodyA.body.getMotionState().getWorldTransform( formA );
+			bodyB.body.getMotionState().getWorldTransform( formB );
 
-	this.matrix = mesh.matrixWorld;
-	this.matrixAutoUpdate = false;
+			var formInverseA = manager.inverseTransform( formA );
+			var formInverseB = manager.inverseTransform( formB );
 
-	this.materials = [];
+			var formA2 = manager.multiplyTransforms( formInverseA, form );
+			var formB2 = manager.multiplyTransforms( formInverseB, form );
 
-	this.materials.push(
-		new THREE.MeshBasicMaterial( {
-			color: new THREE.Color( 0xff8888 ),
-			wireframe: true,
-			depthTest: false,
-			depthWrite: false,
-			opacity: 0.25,
-			transparent: true
-		} )
-	);
+			var constraint = new Ammo.btGeneric6DofSpringConstraint( bodyA.body, bodyB.body, formA2, formB2, true );
 
-	this.materials.push(
-		new THREE.MeshBasicMaterial( {
-			color: new THREE.Color( 0x88ff88 ),
-			wireframe: true,
-			depthTest: false,
-			depthWrite: false,
-			opacity: 0.25,
-			transparent: true
-		} )
-	);
+			var lll = manager.allocVector3();
+			var lul = manager.allocVector3();
+			var all = manager.allocVector3();
+			var aul = manager.allocVector3();
 
-	this.materials.push(
-		new THREE.MeshBasicMaterial( {
-			color: new THREE.Color( 0x8888ff ),
-			wireframe: true,
-			depthTest: false,
-			depthWrite: false,
-			opacity: 0.25,
-			transparent: true
-		} )
-	);
+			lll.setValue( params.translationLimitation1[ 0 ],
+			              params.translationLimitation1[ 1 ],
+			              params.translationLimitation1[ 2 ] );
+			lul.setValue( params.translationLimitation2[ 0 ],
+			              params.translationLimitation2[ 1 ],
+			              params.translationLimitation2[ 2 ] );
+			all.setValue( params.rotationLimitation1[ 0 ],
+			              params.rotationLimitation1[ 1 ],
+			              params.rotationLimitation1[ 2 ] );
+			aul.setValue( params.rotationLimitation2[ 0 ],
+			              params.rotationLimitation2[ 1 ],
+			              params.rotationLimitation2[ 2 ] );
 
-	this._init();
-	this.update();
+			constraint.setLinearLowerLimit( lll );
+			constraint.setLinearUpperLimit( lul );
+			constraint.setAngularLowerLimit( all );
+			constraint.setAngularUpperLimit( aul );
 
-};
+			for ( var i = 0; i < 3; i++ ) {
 
-THREE.MMDPhysicsHelper.prototype = Object.create( THREE.Object3D.prototype );
-THREE.MMDPhysicsHelper.prototype.constructor = THREE.MMDPhysicsHelper;
+				if( params.springPosition[ i ] !== 0 ) {
 
-THREE.MMDPhysicsHelper.prototype._init = function () {
+					constraint.enableSpring( i, true );
+					constraint.setStiffness( i, params.springPosition[ i ] );
 
-	var mesh = this.root;
-	var rigidBodies = mesh.geometry.rigidBodies;
+				}
+
+			}
+
+			for ( var i = 0; i < 3; i++ ) {
+
+				if( params.springRotation[ i ] !== 0 ) {
+
+					constraint.enableSpring( i + 3, true );
+					constraint.setStiffness( i + 3, params.springRotation[ i ] );
+
+				}
+
+			}
 
-	function createGeometry( param ) {
+			/*
+			 * Currently(10/31/2016) official ammo.js doesn't support
+			 * btGeneric6DofSpringConstraint.setParam method.
+			 * You need custom ammo.js (add the method into idl) if you wanna use.
+			 * By setting this parameter, physics will be more like MMD's
+			 */
+			if ( constraint.setParam !== undefined ) {
 
-		switch ( param.shapeType ) {
+				for ( var i = 0; i < 6; i ++ ) {
 
-			case 0:
-				return new THREE.SphereBufferGeometry( param.width, 16, 8 );
+					// this parameter is from http://www20.atpages.jp/katwat/three.js_r58/examples/mytest37/mmd.three.js
+					constraint.setParam( 2, 0.475, i );
 
-			case 1:
-				return new THREE.BoxBufferGeometry( param.width * 2, param.height * 2, param.depth * 2, 8, 8, 8 );
+				}
 
-			case 2:
-				return new createCapsuleGeometry( param.width, param.height, 16, 8 );
+			}
 
-			default:
-				return null;
+			this.world.addConstraint( constraint, true );
+			this.constraint = constraint;
+
+			manager.freeTransform( form );
+			manager.freeTransform( formA );
+			manager.freeTransform( formB );
+			manager.freeTransform( formInverseA );
+			manager.freeTransform( formInverseB );
+			manager.freeTransform( formA2 );
+			manager.freeTransform( formB2 );
+			manager.freeVector3( lll );
+			manager.freeVector3( lul );
+			manager.freeVector3( all );
+			manager.freeVector3( aul );
 
 		}
 
+	};
+
+	/**
+	 * Visualize Rigid bodies
+	 *
+	 * @param {THREE.SkinnedMesh} mesh
+	 * @param {THREE.Physics} physics
+	 */
+	function MMDPhysicsHelper( mesh, physics ) {
+
+		THREE.Object3D.call( this );
+
+		this.root = mesh;
+		this.physics = physics;
+
+		this.matrix.copy( mesh.matrixWorld );
+		this.matrixAutoUpdate = false;
+
+		this.materials = [];
+
+		this.materials.push(
+			new THREE.MeshBasicMaterial( {
+				color: new THREE.Color( 0xff8888 ),
+				wireframe: true,
+				depthTest: false,
+				depthWrite: false,
+				opacity: 0.25,
+				transparent: true
+			} )
+		);
+
+		this.materials.push(
+			new THREE.MeshBasicMaterial( {
+				color: new THREE.Color( 0x88ff88 ),
+				wireframe: true,
+				depthTest: false,
+				depthWrite: false,
+				opacity: 0.25,
+				transparent: true
+			} )
+		);
+
+		this.materials.push(
+			new THREE.MeshBasicMaterial( {
+				color: new THREE.Color( 0x8888ff ),
+				wireframe: true,
+				depthTest: false,
+				depthWrite: false,
+				opacity: 0.25,
+				transparent: true
+			} )
+		);
+
+		this._init();
+
 	}
 
-	// copy from http://www20.atpages.jp/katwat/three.js_r58/examples/mytest37/mytest37.js?ver=20160815
-	function createCapsuleGeometry( radius, cylinderHeight, segmentsRadius, segmentsHeight ) {
+	MMDPhysicsHelper.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), {
 
-		var geometry = new THREE.CylinderBufferGeometry( radius, radius, cylinderHeight, segmentsRadius, segmentsHeight, true );
-		var upperSphere = new THREE.Mesh( new THREE.SphereBufferGeometry( radius, segmentsRadius, segmentsHeight, 0, Math.PI * 2, 0, Math.PI / 2 ) );
-		var lowerSphere = new THREE.Mesh( new THREE.SphereBufferGeometry( radius, segmentsRadius, segmentsHeight, 0, Math.PI * 2, Math.PI / 2, Math.PI / 2 ) );
+		constructor: MMDPhysicsHelper,
 
-		upperSphere.position.set( 0, cylinderHeight / 2, 0 );
-		lowerSphere.position.set( 0, -cylinderHeight / 2, 0 );
+		/**
+		 * Updates Rigid Bodies visualization.
+		 */
+		updateMatrixWorld: function () {
 
-		upperSphere.updateMatrix();
-		lowerSphere.updateMatrix();
+			var position = new THREE.Vector3();
+			var quaternion = new THREE.Quaternion();
+			var scale = new THREE.Vector3();
+			var matrixWorldInv = new THREE.Matrix4();
 
-		geometry.merge( upperSphere.geometry, upperSphere.matrix );
-		geometry.merge( lowerSphere.geometry, lowerSphere.matrix );
+			return function updateMatrixWorld( force ) {
 
-		return geometry;
+				var mesh = this.root;
 
-	}
+				if ( this.visible ) {
 
-	for ( var i = 0, il = rigidBodies.length; i < il; i ++ ) {
+					var bodies = this.physics.bodies;
 
-		var param = rigidBodies[ i ];
-		this.add( new THREE.Mesh( createGeometry( param ), this.materials[ param.type ] ) );
+					matrixWorldInv
+						.copy( mesh.matrixWorld )
+						.decompose( position, quaternion, scale )
+						.compose( position, quaternion, scale.set( 1, 1, 1 ) )
+						.getInverse( matrixWorldInv );
 
-	}
+					for ( var i = 0, il = bodies.length; i < il; i ++ ) {
 
-};
+						var body = bodies[ i ].body;
+						var child = this.children[ i ];
 
-THREE.MMDPhysicsHelper.prototype.update = function () {
+						var tr = body.getCenterOfMassTransform();
+						var origin = tr.getOrigin();
+						var rotation = tr.getRotation();
 
-	var mesh = this.root;
-	var rigidBodies = mesh.geometry.rigidBodies;
-	var bodies = this.physics.bodies;
+						child.position
+							.set( origin.x(), origin.y(), origin.z() )
+							.applyMatrix4( matrixWorldInv );
 
-	var matrixWorldInv = new THREE.Matrix4().getInverse( mesh.matrixWorld );
-	var vector = new THREE.Vector3();
-	var quaternion = new THREE.Quaternion();
-	var quaternion2 = new THREE.Quaternion();
+						child.quaternion
+							.setFromRotationMatrix( matrixWorldInv )
+							.multiply(
+								quaternion.set(
+									rotation.x(), rotation.y(), rotation.z(), rotation.w() )
+							);
 
-	function getPosition( origin ) {
+					}
 
-		vector.set( origin.x(), origin.y(), origin.z() );
-		vector.applyMatrix4( matrixWorldInv );
+				}
 
-		return vector;
+				this.matrix
+					.copy( mesh.matrixWorld )
+					.decompose( position, quaternion, scale )
+					.compose( position, quaternion, scale.set( 1, 1, 1 ) );
 
-	}
+				THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
 
-	function getQuaternion( rotation ) {
+			};
 
-		quaternion.set( rotation.x(), rotation.y(), rotation.z(), rotation.w() );
-		quaternion2.setFromRotationMatrix( matrixWorldInv );
-		quaternion2.multiply( quaternion );
+		}(),
 
-		return quaternion2;
+		// private method
 
-	}
+		_init: function () {
 
-	for ( var i = 0, il = rigidBodies.length; i < il; i ++ ) {
+			var mesh = this.root;
+			var bodies = this.physics.bodies;
 
-		var body = bodies[ i ].body;
-		var mesh = this.children[ i ];
+			function createGeometry( param ) {
 
-		var tr = body.getCenterOfMassTransform();
+				switch ( param.shapeType ) {
 
-		mesh.position.copy( getPosition( tr.getOrigin() ) );
-		mesh.quaternion.copy( getQuaternion( tr.getRotation() ) );
+					case 0:
+						return new THREE.SphereBufferGeometry( param.width, 16, 8 );
 
-	}
+					case 1:
+						return new THREE.BoxBufferGeometry( param.width * 2, param.height * 2, param.depth * 2, 8, 8, 8 );
+
+					case 2:
+						return new createCapsuleGeometry( param.width, param.height, 16, 8 );
+
+					default:
+						return null;
+
+				}
+
+			}
+
+			// copy from http://www20.atpages.jp/katwat/three.js_r58/examples/mytest37/mytest37.js?ver=20160815
+			function createCapsuleGeometry( radius, cylinderHeight, segmentsRadius, segmentsHeight ) {
+
+				var geometry = new THREE.CylinderBufferGeometry( radius, radius, cylinderHeight, segmentsRadius, segmentsHeight, true );
+				var upperSphere = new THREE.Mesh( new THREE.SphereBufferGeometry( radius, segmentsRadius, segmentsHeight, 0, Math.PI * 2, 0, Math.PI / 2 ) );
+				var lowerSphere = new THREE.Mesh( new THREE.SphereBufferGeometry( radius, segmentsRadius, segmentsHeight, 0, Math.PI * 2, Math.PI / 2, Math.PI / 2 ) );
+
+				upperSphere.position.set( 0, cylinderHeight / 2, 0 );
+				lowerSphere.position.set( 0, - cylinderHeight / 2, 0 );
+
+				upperSphere.updateMatrix();
+				lowerSphere.updateMatrix();
+
+				geometry.merge( upperSphere.geometry, upperSphere.matrix );
+				geometry.merge( lowerSphere.geometry, lowerSphere.matrix );
+
+				return geometry;
+
+			}
+
+			for ( var i = 0, il = bodies.length; i < il; i ++ ) {
+
+				var param = bodies[ i ].params;
+				this.add( new THREE.Mesh( createGeometry( param ), this.materials[ param.type ] ) );
+
+			}
+
+		}
+
+	} );
+
+	return MMDPhysics;
 
-};
+} )();

+ 2 - 9
examples/webgl_loader_mmd.html

@@ -138,14 +138,11 @@
 						physics: true
 					} );
 
-					/*
-					 * Note: create CCDIKHelper and MMDPhysicsHelper after calling helper.add( mesh )
-					 */
-					ikHelper = new THREE.CCDIKHelper( mesh );
+					ikHelper = helper.objects.get( mesh ).ikSolver.createHelper();
 					ikHelper.visible = false;
 					scene.add( ikHelper );
 
-					physicsHelper = new THREE.MMDPhysicsHelper( mesh, helper.objects.get( mesh ).physics );
+					physicsHelper = helper.objects.get( mesh ).physics.createHelper();
 					physicsHelper.visible = false;
 					scene.add( physicsHelper );
 
@@ -264,10 +261,6 @@
 			function render() {
 
 				helper.update( clock.getDelta() );
-
-				if ( physicsHelper !== undefined && physicsHelper.visible ) physicsHelper.update();
-				if ( ikHelper !== undefined && ikHelper.visible ) ikHelper.update();
-
 				effect.render( scene, camera );
 
 			}