javascriptmatrixthree.jsmatrix-inverse

How to get the inverse of a Matrix3 in three.js?


The three.js documentation states that Matrix3 has a .getInverse function.

But it takes a Matrix4 as the its first parameter.

So I tried it the naive way in r71:

var m = new THREE.Matrix3();
console.log('Initial:', m.elements);
m.set(10,8,3,15,7,2,10,6,1);
console.log('Set    :', m.elements);
console.log('Inverse:', m.getInverse(m).elements);

http://jsfiddle.net/as8g61nb/5/ (tested only in Chrome)

But this gives me:

Initial: [1, 0, 0, 0, 1, 0, 0, 0, 1]                   // OK
Set    : [10, 15, 10, 8, 7, 6, 3, 2, 1]                // Arbitrary numbers
Inverse: [NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN] // Not what I expected

Wolfram Alpha returns a valid 3x3 Matrix.

Input: Inverse[{{10, 15, 10}, {8, 7, 6}, {3, 2, 1}}]

Output: {{-1/10, 1/10, 2/5}, {1/5, -2/5, 2/5}, {-1/10, 1/2, -1}}

I've looked into the three.js source code to check what it does in .getInverse but this confuses me even more.

As said before it wants a Matrix4 as its first parameter and thus accesses elements[10] and elements[11] which wont work on a Matrix3 and therefore may result in the NaN Elements array.

So am I supposed to create a Matrix4 out of my Matrix3 then Invert it and convert it back to get my Inverse Matrix3 ? Or am I missing out on something obvious here ?


Solution

  • three.js is Matrix4-based, and hence does not have a method to invert a Matrix3 directly.

    One solution is to use Matrix4 in your code everywhere.

    The other solution is to populate a Matrix4 from your Matrix3, and then call getInverse().

    var m3 = new THREE.Matrix3();
    
    m3.set( 10,8,3, 15,7,2, 10,6,1 ); // column1, column2, column3
    
    console.log( 'Set    :', m3.elements );
    
    var m4 = new THREE.Matrix4();
    
    m4.set( 10,8,3,0, 15,7,2,0, 10,6,1,0, 0,0,0,1 );
    
    console.log( 'Inverse:', m3.getInverse(m4).elements );
    

    three.js r.71