Created
August 22, 2011 00:31
-
-
Save timknip/1161394 to your computer and use it in GitHub Desktop.
Matrix decomposition
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Decompose a THREE.Matrix4 into translation, rotation and scale. | |
*/ | |
var translation = new THREE.Vector3(); | |
var rotation = new THREE.Quaternion(); | |
var scale = new THREE.Vector3(); | |
// decompose! | |
matrix.decompose(translation, rotation, scale); | |
var mt = new THREE.Matrix4(); | |
var mr = new THREE.Matrix4(); | |
var ms = new THREE.Matrix4(); | |
// and recompose... | |
mt.setTranslation(translation.x, translation.y, translation.z); | |
mr.setRotationFromQuaternion(rotation); | |
ms.setScale(scale.x, scale.y, scale.z); | |
matrix.identity(); | |
matrix.multiply(mr, ms); | |
matrix.multiply(mt, matrix); | |
// check whether the matrix is still sound! | |
// here the relevant THREE.Matrix4 code: | |
decompose: function ( translation, rotation, scale ) { | |
// grab the axis vecs | |
var x = new THREE.Vector3(this.n11, this.n21, this.n31); | |
var y = new THREE.Vector3(this.n12, this.n22, this.n32); | |
var z = new THREE.Vector3(this.n13, this.n23, this.n33); | |
translation = (translation instanceof THREE.Vector3) ? translation : new THREE.Vector3(); | |
rotation = (rotation instanceof THREE.Quaternion) ? rotation : new THREE.Quaternion(); | |
scale = (scale instanceof THREE.Vector3) ? scale : new THREE.Vector3(); | |
scale.x = x.length(); | |
scale.y = y.length(); | |
scale.z = z.length(); | |
translation.x = this.n14; | |
translation.y = this.n24; | |
translation.z = this.n34; | |
// scale the rotation part | |
var matrix = this.clone(); | |
matrix.n11 /= scale.x; | |
matrix.n21 /= scale.x; | |
matrix.n31 /= scale.x; | |
matrix.n12 /= scale.y; | |
matrix.n22 /= scale.y; | |
matrix.n32 /= scale.y; | |
matrix.n13 /= scale.z; | |
matrix.n23 /= scale.z; | |
matrix.n33 /= scale.z; | |
rotation.setFromRotationMatrix(matrix); | |
return [translation, rotation, scale]; | |
}, |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment