haxe-gl-matrix

Haxe port of gl-matrix Javascript library, with couple of twists.
https://gitlab.com/ravendyne-haxe/haxe-gl-matrix

To install, run:

haxelib install haxe-gl-matrix 1.1.1 

See using Haxelib in Haxelib documentation for more information.

README.md

haxe-gl-matrix

Latest version: 1.0

Dependencies: - none

A Haxe vector/matrix/quaternion library

Write code like this:

// v2 is Array<Float>
var v2_ : Vec3 = v2;
// v0_, v1_, v2_, side_A, side_B is Vec3
var side_A = v1_.subtract( v0_ );
var side_B = v2_.subtract( v1_ );
// normal is Vec3
var normal = side_A.cross( side_B ).normalize();
// mesh.normals accepts Array<Float> as parameter
mesh.normals.push( normal );

or like this:

var viewMatrix = nodeRotationM.transpose().mul( Mat4.fromTranslation( nodePositionV.negate() ) );

or, maybe, like this:

var m = Mat4.fromRotation( GLMatrix.toRadians( 75 ), Vec3.Z_AXIS );
var a : Vec3 = [ 100, 100, 0 ];
var b = m.multiplyVec3( a );
var d = b.normalize().cross( dir );
return Vec3Tools.lerp( 0.4, a, d );

Basic overview of library structure and content

The library introduces nine types, all of which are essential for your everyday graphics programming:

  • Vec2 : 2-component vector
  • Vec3 : 3-component vector
  • Vec4 : 4-component vector
  • Mat2 : 2x2 matrix
  • Mat3 : 3x3 matrix
  • Mat4 : 4x4 matrix
  • Quat : quaternion
  • Quat2 : double-quaternion
  • Mat2d : 3x2 matrix, 3 columns and 2 rows where last column holds 2D translation vector and first two columns are a 2D rotation matrix

For each of the types there is a static extension class named by the type, with Tools suffix added to it:

  • Vec2Tools
  • Vec3Tools
  • Vec4Tools
  • Mat2Tools
  • Mat3Tools
  • Mat4Tools
  • QuatTools
  • Quat2Tools
  • Mat2dTools

You can either import any of these Tools classes and use them directly, or you can use them as static extension via using directive, for which they are intended in the first place.

Type classes only have basic methods:

  • constructor
  • @arrayAcces methods
  • support for implicit casting from/to an array
  • one or more fromABC static constructor functions
  • maybe few properties (i.e. x, y, z, w etc.)
  • maybe few public static vars (i.e. X_AXIS, Y_AXIS etc.)

Bulk of methods for an xyz type are in its xyzTools extension class.

Almost all of the methods in an xyzTools class can be used as extension methods, except for select few, mostly because it doesan't make sense for them to be extension methods. For example, Vec3Tools.create() is not an extension method because it takes no parameters.

Some of the methods in xyzTools classes can't be used as extensions for xyz type because it doesn't make sense for them to be used as such. For example, Vec4Tools.lerp() has a Float as a first parameter and therefore it can't be used as Vec4 extension. It could be used as an extension for Float type, but whether you are going to do that or not, is up to you.

What's implemented

You can find a list of implemented methods right after the opening declaration of each of the xyzTools classes.

The list is wrapped into a comment and organized into few groups:

  • generators in xyz class
  • generators (in this xyzTools class)
  • editors
  • operators - unary - unary, non-xyz result - binary - binary, non-xyz arg - binary, non-xyz result - ternary
  • misc

The list gives full signature of a method with optional parameters marked with?, as is usual in Haxe.

How to read the method list

Each function is prefixed with one variant of (example is for list in Vec2Tools):

  • Vec2.
  • vec2.
  • ?vec2.

Vec2 (uppercase first letter) means "literally use this", i.e. Vec2.fromValues... means you should write code like:

var v = Vec2.fromValues(....)

vec2 (lowercase first letter) means "name of your variable which is of this type", i.e. vec2.floor... means use this method on a variable of type Vec2, so your code might look like this:

var a : Vec2 = [ 5.76, 2.35 ];
var z = a.floor();

?vec2. means you can use this method on your variable as static extension or you could call it directly. In each case it does the same thing: changes the variable it is called on/with. You will find this on methods that have a result variable out as a first parameter. For example, ?vec2.random... means you can use this method in one of the two ways:

a.random();
// or
Vec2Tools.random( a );

with same result: your variable will be changed after the method call.

The output parameter

Almost every function has the output parameter named out, and almost every function has this out parameter as a last parameter in the list. This parameter is always optional, except in handful of cases (i.e. in set() method).

If you omit this parameter, the called function will create a new variable to place the result in, and will return that new variable.

If you provide this parameter, the called function will use that provided variable to place the result in, and will return that provided variable.

This is a port of javascript gl-matrix

This is almost direct port of javascript gl-matrix library to Haxe.

The reason for "almost" is because, while almost all of the code comes from gl-matrix, the library is reorganized a bit to better conform to Haxe way of doing things: it has been Haxe-fied (or maybe Haxe-d) :)

Almost all of the functions you can find in version 2.0 of gl-matrix are here, except forEach functions for vec2, vec3 and vec4.

Some functions are renamed, i.e. vec2.transformMat2() (and all similarly named ones) is renamed to vec2.postmultiplyMat2() and reason for this is to keep the operation performing functions named after the operations they do. In this particular case transformMat2() is not doing anything exotic, it simply multiplies a mat2 with a vec2. In context of computer graphics, or CAD applications etc. it may make sense to call it transformMat2, but in a more general context of vector/matrix/quaternion algebra it is just a multiplication of 2x2 matrix with 2-element vector.

These are mostly cosmetic differences, and not that important ones. More important differences are in the way Haxe gl-matrix is structured to conform to Haxe idioms (i.e. static extensions).

Most important differences from javascript gl-matrix

  • all "types" in gl-matrix are just javascript arrays, haxe-gl-matrix has dedicated class for each type (which is still an abstract over array, so you don't loose "array-ness" but you gain type safety and host of other Haxe goodies)
  • order of parameters in almost all functions differs in a way that the result variable comes as a first parameter in gl-matrix and in haxe-gl-matrix it comes as, optional, last parameter
  • you have to pre-allocate (create an array) result variable when using gl-matrix, haxe-gl-matrix can do this for you with no extra effort
  • haxe-gl-matrix allows you to automatically work with all types as if they were immutable while, with gl-matrix you have to be extra careful

Usage and differences

Usage: creating new variables

Constructors for all haxe-gl-matrix types have no parameters. They all create default values, suitable for use in graphics programming, i.e.:

var v = new Vec4();

will create 4-component vector with values set to:

  • x = 0.0
  • y = 0.0
  • z = 0.0
  • w = 1.0

and similarly for other types.

You will most probably very rarely create variables with new and instead use one of these methods:

  • create a variable using implicit cast from array
  • create a variable using one of static fromxyz() methods
  • create a variable as a result of some operation (a call to a method from xyzTools class)

Using implicit cast from array

The easiest way to create vectors is:

var v3 : Vec3 = [ 1, 2, 3 ];

This will create var v3 of type Vec3 with it's components initialized to:

  • x = 1.0
  • y = 2.0
  • z = 3.0

This, of course, also works for method parameters. For example, let's say you have this method:

public function translace( delta : Vec3 ) ...

You can call it with literal Vec3 value like this:

an_object.translate([ 10, 10, 0 ]);

which will create an instance of Vec3 with components set to x=10, y=10 and z=0 and pass that as delta parameter to translate.

Using fromxyz() methods

All types have one or more static fromxyz() methods, you can use as a convenient way of creating instances of haxe-gl-matrix types.

For example, all types have the fromValues() method, and for Vec3 you could use one of these:

var v3 : Vec3 = [ 2, 3, 4 ];
var v3 = Vec3.fromValues( 2, 3, 4 );

Since there's that implicit cast from an array, you probably won't use fromValues() very often. Other fromxyz() static constructors however, may be more useful, i.e.:

var translationMatrix = Mat4.fromTranslation([ 100, 100, -50 ]);
var rotationMatrix = Mat4.fromRotation( GLMatrix.toRadian( 45 ), Vec3.X_AXIS );
var quat = Quat.fromEuler( 0, 45, 75 );
// etc...

As a result of operation

This is self-explanatory, but requires section of its own.

You can create new instance of a haxe-gl-matrix type (i.e. Vec3) by performing operations on existing values, i.e.:

// somewhere out there you've created instances of: var a:Vec3, b:Vec3;
var result = a.mul( b );

The "trick" is not to provide out parameter for an operation method (mul() in this case), which will trigger the method to create a new variable and return it as a result.

Differences: where is the out (result) parameter placed

The first major difference between the javascript gl-matrix and haxe-gl-matrix is related to placement of the result parameter, a.k.a out parameter. If you look at the gl-matrix sources, you will see that almost all of the functions follow this pattern:

function_name( result, list-of-operands )

For example, multiplying two 3-component vectors A and B and placing the result into R would be written (in vector algebra) like this:

R = A * B

and coded by using gl-matrix functions like this:

vec3.mul( R, A, B );

haxe-gl-matrix follows a different convention:

function_name( first-operand, other-operands, [optional] result )

and for this particular 3-component vector example we would write:

Vec3Tools.mul( A, B, R );

or

R = Vec3Tools.mul( A, B );

or, and this is the preferred variant:

using mme.math.glmatrix.Vec3Tools;

var R = A.mul( B );

The convention with result as last parameter may seem odd at the first glance, but there are two important reasons for this:

  • all of the xyzTools classes are Haxe static extensions for their xyz type, so the first parameter has to be of xyz type
  • by simply omitting the optional result parameter, you can use library functions as if all of the operands were immutable

Read more on the immutability thing in it's own section.

Differences: using, or not, the optional result parameter

As for the optional result parameter, you have a choice to: - omit it, in which case a new result variable is created and returned by the function - specify it, in which case the result is placed in the given var, and also returned by the function

This way you can optimize. or "optimize", your code by avoiding unneeded allocation of variables (arrays).

For example, you can use Vec3Tools.normalize( a : Vec3, ?out : Vec3 ) : Vec3 function like this:

using mme.math.glmatrix.Vec3Tools;

var myvecNorm = myvec.normalize();

This will create a new Vec3 value (normalized myvec) and place it into myvecNorm. Variable myvec will stay unchanged.

Or, you can use it like this:

using mme.math.glmatrix.Vec3Tools;

myvec.normalize( myvec );

This will not create any new variables, but will instead place the result of operation (normalized vector myvec) into variable myvec. It is the same as if you wrote:

myvec = myvec.normalize();

which also works and is perfectly fine, except in this case normalize() will allocate an extra variable for the result of normalization operation and that new variable will then be assigned to myvec.

These two variants:

myvec.normalize( myvec );
myvec = myvec.normalize();

enable you to do two different things when it comes to properties and such stuff. For example, if some other code have got a reference to the myvec variable, i.e. through implicit call to it's property getter get_myvar(), this is what happens:

  • in the first case, you will normalize() (or whatever) myvec and that change will be immediately visible to whichever code got a reference of myvec
  • in the second case, you create new local value for myvec, and whichever code got a reference to previous value of myvec will have to come back and get the new one (i.e. implicitly calling get_ymvec() function ) if they want to see the change

Choose wisely. With great power comes chaos and spaghetti code. And sometimes a brilliant code. The choice is yours.

Differences: order of parameters for parametric generators and some other methods

Another difference from javascript gl-matrix is that some methods, mostly parameteric generators, have for the first variable a type that is not one of haxe-gl-matrix classes. This means that these methods can't be used as static extensions on the xyz type that xyzTools class supports.

For example, Vec3Tools.lerp(), Vec3Tools.hermite(), Vec3Tools.bezier() all have a Float for the first parameter.

This means that you can write this:

var vt = Vec3Tools.lerp( t, start, end );

or this:

var vt : Vec3;
// ... create and/or assign vt somewhere here...
// ...and then call...
Vec3Tools.lerp( t, start, end, vt );

In the first case, as usual, lerp() will create a new variable to place the result in it and return that one to be assigned to vt. In the second case, lerp() will place the result in vt so you avoid creating additional variable each time you call lerp().

And, of course, you could do this too:

using mme.math.glmatrix.Vec3Tools;

var t : Float = 0.7;

var vt = t.lerp( start, end );

and if you should or should not do it, is totally up to you.

The Float32Array stuff

In the spirit of its origins (the javascript gl-matrix library), and in the spirit of its main intended purpose as a means to work with vectors and matrices that will eventually end as parameters to OpenGL API calls, all of the haxe-gl-matrix types (Vec2, Vec3 etc) are Haxe abstracts over arrays.

All of the haxe-gl-matrix types are abstractions of haxe.io.Float32Array. If your build target is html5, this will ultimately end up being mapped to javascript ArrayBuffer. If not, haxe.io.ArrayBufferView over haxe.io.Bytes will be the underlying implementation.

This allows for having a byte buffer that contains i.e. a lot of 2D or 3D vectors where you can then use i.e. Vec2 or Vec3 over that byte array to work with values directly.

For example, to create a Vec4 over some elements of a Bytes buffer, you can use something like this:

var buffer = Bytes.alloc( .... );
var startOffsetInBytes = ...// wherever your vec4 starts in the buffer
var vec_4 : Vec4 = Float32Array.fromBytes( buffer, startOffsetInBytes, Vec4.ELEMENT_COUNT );

You can also create a Vec2 (or 3, or 4, or a matrix, or a quaternion) at an index of a Float32Array using createFromIndexAt and createFromElementAt, like so:

var f32arr = Float32Array.fromArray( [ 1.0, 2.0, 3.0, 4.0 ] );
// this will create 2d vector with elements [ 2.0, 3.0 ]
var vec_2_a = Vec2.createFromIndexAt( 1 );
// this will create 2d vector with elements [ 3.0, 4.0 ]
var vec_2_b = Vec2.createFromElementAt( 1 );

Vec2.createFromIndexAt treates the Float32Array as an array of float elements, and Vec2.createFromElementAt treats it as an array of elements each containing 2 float elements. Similar goes for other types: Vec3 is 3 float elements, Vec4 is 4 float elements, etc.

When you do any kind of operations with instances created over arrays and you want to change values of those instances, make sure to use the optional result parameter when performing the operations. For example, this operation:

vec_4.normalize( vec_4 );

will normalize vec_4 and store the result of normalization in the same space in the buffer over which vec_4 is created, whereas this operation:

var vec_4_n = vec_4.normalize();

wouldn't change the underlying vec_4 buffer, but would create a new Vec4 instance vec_4_n.

The immutability thing

Long time ago, on a strange continent, in a university far, far away, there was a professor of programming who had, as one of her hobbies, a habit to repeat how we should think about, and code, our Java classes as immutable objects. She did this time and again, among other things, for reasons I was blissfully oblivious at the time.

Long years later, whenver possible and almost always, I would be thinking of and coding my (not-just-Java-anymore) classes as immutable objects, for reasons I painfuly get reminded of every time I dare to think (with a smug look on my face): "What? I'm smarter now...".

This immutability, in my experience, turns out to be particularly important when it comes to performing any kind of, even slightly, complex calculations. And haxe-gl-matrix is all about calculations.

If your vectors/matrices/quaternions are mutable, with their bottoms exposed, they will get changed at some point without your express intention, even when there are tons of unit tests lying around and 6 pairs of developer eyes looking at the same code.

The rule is very simple:

"Code for correctness now, optimize for speed later"
                                          Batman

With immutable vectors, for example, you know for sure that your scene node will keep its position, until explicitly changed by assignment. Which is very easy to spot. Even easier to find. And can be super easy to optimize. Later. If ever.

With mutable node position, someone somewhere will inevitably get a hold on a reference to that array you call vector that keeps the node's position, and they will make a change to it's content, for some very pragmatic reasons. Let's say to avoid creating a new, temporary, array. To speed things up a bit.

In the process of porting from its javascript origins, haxe-gl-matrix is re-designed to provide means where you can write code that preserves vector/matrix/quaternion immutability, automatically. This is achieved by making the out result parameter optional. When you don't provide this parameter, a function you use will create a new value and place the result in there.

You can always come back later and optimize, after the code does what it is intended to do in the first place, and you, hopefully, have a ton of unit tests on stand by to check for any deviations from the desired behaviour when you perform your refactoring.

As most of us (my grandmother excluded) do not beleive in rigid, strict rules, haxe-gl-matrix also keeps a way to use mutable vectors/quaternions/matrices, and you achieve this by simply providing a variable for the out parameter.

Syntax may be a bit odd:

var res = new Vec4();
a.mul( b, res );

instead of

var res = a.mul( b );

but it does help when you have to, for example, multiply, scale, rotate, transpose and then negate, or whatnot, a half a dozen 4x4 matrices for 104379 nodes.

Are these matrices column-major or row-major?

"Never discuss column-major vs row-major with graphics programmer"
                                                    Tony Stark

"Who is this Column Major and what is Army doing in my computer?!!"
                                                    Grandpa
Contributors
rdynhaxe
Version
1.1.1
Published
1 year ago
License
MIT

All libraries are free

Every month, more than a thousand developers use Haxelib to find, share, and reuse code — and assemble it in powerful new ways. Enjoy Haxe; It is great!

Explore Haxe

Haxe Manual

Haxe Code Cookbook

Haxe API documentation

You can try Haxe in the browser! try.haxe.org

Join us on GitHub!

Haxe is being developed on GitHub. Feel free to contribute or report issues to our projects.

Haxe on GitHub

⌂