Matrix3/Matrix4 constructor or setter taking JS array

Description of the problem

It’s often the case that for purposes of clarity or convenience or data ingestion, values for Vectors and Matrices originate in JS array of numbers form, e.g. [0, 1, 2].

We currently have to do some bending over backwards to do something like initialize e.g. a Matrix3 using the API… The constructor sets it to identity and then we have to call a setter with 9 arguments to set it!

Since the constructor allocates a [1, 0, 0, 0, 1, 0, 0, 0, 1] JS array just to pass it to the Float32Array anyway why can’t we have the constructor take an optional array here? Is it written this way for maximum efficiency so we want to avoid checking the length of the array or something?

I would say at least provide a SetFromArray method that we can use. For the time being perhaps I might write this:

var mat = new THREE.Matrix3();
mat.elements = new Float32Array(myVectorOf9Numbers);

This is quite wasteful, allocating and cleaning up JS array of numbers (identity matrix in the ctor)!

(caveat: I’m not actually terribly familiar with Typed Arrays so I suppose I can do something smarter by calling set with mat.elements and then it’s mostly performant.)

Three.js version
  • Dev
  • r78
Browser
  • All of them
  • Chrome
  • Firefox
  • Internet Explorer
OS
  • All of them
  • Linux
  • Windows
  • Android
  • IOS
Hardware Requirements (graphics card, VR Device, …)

Author: Fantashit

1 thought on “Matrix3/Matrix4 constructor or setter taking JS array

  1. We have to be careful, here. Matrix4.set() takes elements in row-major order. It is done that way so the code is human-readable.

    matrix.set( 1.0, 0.0, 0.0, 0.5,
                0.0, 1.0, 0.0, 0.6,
                0.0, 0.0, 1.0, 0.7,
                0.0, 0.0, 0.0, 1.0 );

    What you are proposing here involves specifying array elements in column-major order.

    var matrix = new THREE.Matrix4( array );

    It may be OK, as long as the docs and code are very clear… but personally, I am not liking it due to the potential for user confusion.

Comments are closed.