Math Libraries
You wrote Vec3, Mat4 and Quat by hand in this course to see how they work. In a real project, use a library: they are tested, SIMD-optimized, and they match the conventions of the graphics APIs and engines around them. Inside an engine, use the engine's own types (Vector3, FVector, Godot's Vector3). Outside one, in your own engine, tools, servers or web games, pick from the libraries below.
| Library | Language | Best for | Conventions |
|---|---|---|---|
| GLM | C++ (header-only) | OpenGL/Vulkan engines, learning | GLSL-like names, column vectors, column-major storage, right-handed, depth -1..1 by default |
| DirectXMath | C++ (header-only, ships with the Windows SDK, also on GitHub) | Direct3D engines, max SIMD performance | row vectors, row-major storage, LH and RH variants of every camera function |
| Eigen | C++ (header-only) | tools, physics, robotics, general linear algebra | column vectors, column-major storage, any matrix size |
| System.Numerics | C# (.NET built-in) | .NET game servers, tools, MonoGame-style code, Godot C# interop | row vectors, right-handed camera helpers, SIMD-accelerated |
| Unity.Mathematics | C# (Unity package) | Burst-compiled DOTS/Jobs code in Unity | HLSL-like (float3, math.dot), column vectors, radians |
| gl-matrix | JavaScript | WebGL/WebGPU without a framework | Float32Arrays, out-parameter style, column-major |
GLM
GLM copies GLSL's names (vec3, mat4, dot, mix, normalize), so code moves between C++ and shaders easily. Extensions live in gtc/ (stable) and gtx/ (experimental, needs GLM_ENABLE_EXPERIMENTAL).
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp> // translate, rotate, scale, perspective, lookAt
#include <glm/gtc/quaternion.hpp> // quat, angleAxis, slerp, quatLookAt, mat4_cast
glm::mat4 model = glm::translate(glm::mat4(1.0f), position)
* glm::mat4_cast(glm::angleAxis(glm::radians(30.0f), glm::vec3(0, 1, 0)))
* glm::scale(glm::mat4(1.0f), glm::vec3(2.0f));
glm::mat4 view = glm::lookAt(eye, target, glm::vec3(0, 1, 0));
glm::mat4 proj = glm::perspective(glm::radians(60.0f), 16.0f / 9.0f, 0.1f, 500.0f);
glm::vec4 clip = proj * view * model * glm::vec4(localPoint, 1.0f);Define GLM_FORCE_DEPTH_ZERO_TO_ONE for Vulkan, Direct3D and Metal (clip depth 0..1 instead of OpenGL's -1..1), and GLM_FORCE_LEFT_HANDED if your engine is left-handed. Set them once, before every GLM include (in a wrapper header or as compiler flags), or different files will disagree.
DirectXMath
DirectXMath separates storage types (XMFLOAT3, XMFLOAT4X4) from SIMD register types (XMVECTOR, XMMATRIX). Load, compute, store. It uses row vectors, so transforms read left to right: scale, then rotate, then translate.
#include <DirectXMath.h>
using namespace DirectX;
XMFLOAT3 posStored{4.0f, 0.0f, 2.0f};
XMVECTOR pos = XMLoadFloat3(&posStored);
XMMATRIX world = XMMatrixScaling(2, 2, 2)
* XMMatrixRotationRollPitchYaw(0.0f, XMConvertToRadians(30.0f), 0.0f)
* XMMatrixTranslationFromVector(pos); // S * R * T with row vectors
XMMATRIX proj = XMMatrixPerspectiveFovLH(XMConvertToRadians(60.0f), 16.0f / 9.0f, 0.1f, 500.0f);
XMVECTOR q = XMQuaternionSlerp(qA, qB, 0.5f);
float d = XMVectorGetX(XMVector3Dot(a, b)); // dot is replicated in all 4 lanes
XMFLOAT4X4 stored; XMStoreFloat4x4(&stored, world);Eigen
Eigen is a general linear-algebra library, so it handles any size of matrix plus solvers and decompositions. Its Geometry module has what games need. Note that Quaternionf(w, x, y, z) takes w first in the constructor, while coeffs() stores x, y, z, w.
#include <Eigen/Geometry>
Eigen::Vector3f a(1, 2, 3), b(0, 1, 0);
float d = a.dot(b);
Eigen::Vector3f n = a.cross(b).normalized();
Eigen::Quaternionf q(Eigen::AngleAxisf(0.5f, Eigen::Vector3f::UnitY()));
Eigen::Affine3f T = Eigen::Translation3f(4, 0, 2) * q * Eigen::Scaling(2.0f);
Eigen::Vector3f world = T * Eigen::Vector3f(1, 0, 0);
Eigen::Quaternionf halfway = q.slerp(0.5f, Eigen::Quaternionf::Identity());Before C++17, classes holding fixed-size vectorizable members (Vector4f, Matrix4f, Quaternionf) needed EIGEN_MAKE_ALIGNED_OPERATOR_NEW, or new could return misaligned memory and crash. With C++17 aligned new this is handled automatically.
System.Numerics (C#)
Built into .NET, SIMD-accelerated, no package needed. It uses row vectors like DirectX (Vector3.Transform(v, m) computes v * m), so a world matrix is scale * rotation * translation.
using System.Numerics;
Vector3 dir = Vector3.Normalize(target - position);
float facing = Vector3.Dot(forward, dir);
Quaternion q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, MathF.PI / 6);
Matrix4x4 world = Matrix4x4.CreateScale(2f) * Matrix4x4.CreateFromQuaternion(q) * Matrix4x4.CreateTranslation(position);
Vector3 p = Vector3.Transform(localPoint, world);
Matrix4x4 view = Matrix4x4.CreateLookAt(eye, target, Vector3.UnitY); // right-handed
Matrix4x4 proj = Matrix4x4.CreatePerspectiveFieldOfView(MathF.PI / 3, 16f / 9f, 0.1f, 500f);
Matrix4x4.Invert(world, out Matrix4x4 worldToLocal);Unity.Mathematics
The math package for Unity's DOTS: types and functions mirror HLSL (float3, quaternion, math.mul), and Burst compiles them to SIMD code. Two differences from classic UnityEngine math catch everyone: angles are in radians (not degrees like Mathf and Quaternion.Euler), and you multiply with math.mul, not * (* on two float4x4 is component-wise).
using Unity.Mathematics;
float3 dir = math.normalizesafe(target - position);
quaternion look = quaternion.LookRotationSafe(dir, math.up());
quaternion turned = math.slerp(current, look, 1f - math.exp(-8f * dt));
float3 rotated = math.mul(turned, new float3(0, 0, 1));
float4x4 m = float4x4.TRS(position, turned, new float3(1));
float3 world = math.transform(m, localPoint);
var rng = new Unity.Mathematics.Random(12345u); // seed must be non-zero
float roll = rng.NextFloat(0f, 1f);gl-matrix (JavaScript)
For WebGL or WebGPU without Three.js. Everything is a Float32Array, and functions write into an out argument instead of allocating, which avoids garbage-collection hitches in a render loop.
import { vec3, mat4, quat } from 'gl-matrix';
const q = quat.setAxisAngle(quat.create(), [0, 1, 0], Math.PI / 6);
const model = mat4.fromRotationTranslationScale(mat4.create(), q, [4, 0, 2], [2, 2, 2]);
const view = mat4.lookAt(mat4.create(), [0, 2, 6], [0, 0, 0], [0, 1, 0]);
const proj = mat4.perspective(mat4.create(), Math.PI / 3, 16 / 9, 0.1, 500); // -1..1 depth; perspectiveZO for 0..1
const world = vec3.transformMat4(vec3.create(), [1, 0, 0], model);
const tmp = vec3.create(); // reuse scratch vectors across frames
vec3.subtract(tmp, target, position);
vec3.normalize(tmp, tmp);Storage order: the transpose bug
"Column-major" and "row-major" describe how the 16 numbers sit in memory. When you upload a matrix to a shader, or pass it between two libraries, a mismatch silently transposes it: rotations turn backwards and the translation ends up in the bottom row, where it does nothing useful. This program prints the same translation matrix in both layouts:
#include <iostream>
int main() {
// Translation by (5, 6, 7), written the column-vector way (offset in the last column).
double m[4][4] = {{1, 0, 0, 5}, {0, 1, 0, 6}, {0, 0, 1, 7}, {0, 0, 0, 1}};
std::cout << "row-major (a C array m[4][4]):";
for (int r = 0; r < 4; r++) for (int c = 0; c < 4; c++) std::cout << " " << m[r][c];
std::cout << "\ncolumn-major (GLM, gl-matrix, Eigen):";
for (int c = 0; c < 4; c++) for (int r = 0; r < 4; r++) std::cout << " " << m[r][c];
std::cout << "\n";
}row-major (a C array m[4][4]): 1 0 0 5 0 1 0 6 0 0 1 7 0 0 0 1
column-major (GLM, gl-matrix, Eigen): 1 0 0 0 0 1 0 0 0 0 1 0 5 6 7 1
In GLM's memory the translation is elements 12, 13 and 14, which is also where DirectXMath keeps it (it stores the transposed, row-vector matrix row by row). That coincidence is why both "just work" with their own shaders. Trouble starts when one side's convention leaks into the other: a GLM matrix uploaded to an HLSL mul(v, M) shader, or a C array written row by row into gl-matrix.
Tip: When a scene renders black or everything rotates the wrong way after switching libraries, print one known matrix (a pure translation like the one above) from both sides and compare where the
5 6 7ends up.
Test yourself
Which library writes results into an out parameter to avoid allocations in JavaScript render loops?
- GLM
- gl-matrix
- Eigen
- System.Numerics
Unity.Mathematics' quaternion.AxisAngle(axis, angle) expects the angle in what unit?
- Degrees
- Radians
- Turns
- Gradians
What does GLM_FORCE_DEPTH_ZERO_TO_ONE change?
- Handedness
- The clip-space depth range of projection matrices to 0..1, as Vulkan and Direct3D expect
- Matrix storage order
- Angle units