10. Determinants and Inverse Matrices

By now we can build a matrix for almost anything: scale, rotation, shear, reflection, and (since chapter 9) translation.
In this chapter we ask two questions about any matrix we've built.
First: how much does it stretch space, and does it turn space inside out? The answer is a single number called the determinant.
Second: how do I undo it? The answer is another matrix called the inverse.

These two ideas show up everywhere in graphics.
The camera's view matrix is an inverse.
Lighting on a stretched model only looks right thanks to an inverse.
And a mirrored model renders inside out unless you check the sign of a determinant.
Let's see how all of that works.

10.1 How much does a matrix stretch space?

In chapter 6 we learned that the columns of a matrix are where the basis vectors land.
So in 2D, the unit square with sides 𝐢 and 𝐣 (area 1) turns into a parallelogram whose sides are the two columns of the matrix.

Take this matrix:

𝐌=[3112]

Its first column 𝐮=(3,1) is where 𝐢 lands, and its second column 𝐯=(1,2) is where 𝐣 lands.
The unit square becomes this parallelogram:

The unit square turned into the parallelogram spanned by u = 3, 1 and v = 1, 2

Its area turns out to be 5.
And here's the important part: because a matrix is linear, it stretches every shape by the same factor.
A circle of area 2 becomes an ellipse of area 10.
A sprite covering 100 pixels becomes a shape covering 500 pixels.
This "area scale factor" of the matrix is its determinant.

10.2 What the formula is

For a 2×2 matrix the determinant is:

det(𝐌)=det[abcd]=ad−bc

You'll also see it written with straight bars instead of brackets:

|abcd|=ad−bc

Careful: these bars do not mean "absolute value" here, and the determinant can be negative.

For a 3×3 matrix we use cofactor expansion along the first row: each entry of the first row times the 2×2 determinant left over when you cross out that entry's row and column, with alternating signs:

det[abcdefghi]=a|efhi|−b|dfgi|+c|degh|
=a(ei−fh)−b(di−fg)+c(dh−eg)

(Here the letters a to i are just the nine entries, nothing to do with the basis vectors.)
In 2D the determinant is the signed area scale factor, and in 3D it's the signed volume scale factor.

10.3 How it works: the 2×2 determinant

Where ad − bc comes from

Let's check that the parallelogram in 10.1 really has area ad−bc=3⋅2−1⋅1=5.
Draw a rectangle around it, from (0,0) to (4,3).
Its area is (a+b)(c+d)=4⋅3=12.
The parallelogram is that rectangle minus six pieces in the corners:

  • two triangles with legs a=3 and c=1, each with area 3⋅12=1.5, together 3;
  • two triangles with legs b=1 and d=2, each with area 1⋅22=1, together 2;
  • two small rectangles of size b×c=1×1, together 2.

So the area is 12−3−2−2=5.
The same subtraction with letters gives the formula:

(a+b)(c+d)−ac−bd−2bc=ac+ad+bc+bd−ac−bd−2bc=ad−bc

A gallery of determinants

Let's try the transformations from chapter 8.

Matrix Determinant What happens to area
[2003] (scale) 2⋅3−0⋅0=6 6 times bigger
[cosθ−sinθsinθcosθ] (rotation) cos2θ+sin2θ=1 unchanged
[11.501] (shear) 1⋅1−1.5⋅0=1 unchanged
[−1001] (mirror) −1⋅1−0⋅0=−1 same size, flipped
[1224] (flatten) 1⋅4−2⋅2=0 squashed to a line

The rotation row uses sin2θ+cos2θ=1, the Pythagorean theorem on the unit circle (chapter 1).
Rotations never change area, which matches common sense: turning a sheet of paper doesn't make it bigger.
The shear is like pushing a deck of cards sideways: the deck leans, but it's still the same amount of cards.

For a diagonal (or triangular) matrix, the determinant is simply the product of the diagonal entries.
That's why a 3D scale matrix with factors (2,3,0.5) has determinant 2⋅3⋅0.5=3.

The sign: inside out

What does a negative area mean?
It means the matrix flips the orientation of space, like a mirror.
In the original square, you turn counter-clockwise to get from 𝐢 to 𝐣.
After a matrix with a positive determinant, you still turn counter-clockwise from the first column to the second.
After a matrix with a negative determinant, you turn clockwise: the shape is a mirror image.

With det greater than 0 the turn from i to j stays counter-clockwise, a mirror makes it clockwise

Remember your left and right hands: they have the same size and shape, but no rotation will ever turn one into the other.
Only a mirror can, and mirrors are exactly the matrices with negative determinants.
We'll see in 10.11 why this matters a lot for rendering.

10.4 How it works: the 3×3 determinant

Worked example

Let's compute the determinant of:

𝐌=[210031104]

We go along the first row: 2, 1, 0.
For each entry we cross out its row and column, and take the 2×2 determinant of what's left (that's called the entry's minor):

  • Entry 2 (row 1, column 1): what's left is [3104], minor 3⋅4−1⋅0=12.
  • Entry 1 (row 1, column 2): what's left is [0114], minor 0⋅4−1⋅1=−1.
  • Entry 0 (row 1, column 3): what's left is [0310], minor 0⋅0−3⋅1=−3.

Now combine them with the signs +,−,+:

det(𝐌)=2⋅12−1⋅(−1)+0⋅(−3)=24+1+0=25

So this matrix makes every 3D object 25 times bigger in volume, without mirroring it.

The signs follow a checkerboard pattern, and you can expand along any row or column as long as you use the matching signs:

[+−+−+−+−+]

A good trick is to expand along the row or column with the most zeros, because every 0 entry saves you a whole 2×2 determinant.
(A minor multiplied by its sign is called a cofactor. We'll need that word for the inverse.)

Signed volume and the triple product

In 3D the unit cube becomes a slanted box (a parallelepiped) whose three edges are the three columns of the matrix.
We already know how to get that volume from chapters 4 and 5: the cross product of two edges is perpendicular to them with a length equal to their parallelogram's area, and the dot product with the third edge multiplies by the height.
So the determinant is also the scalar triple product of the columns:

det[𝐚𝐛𝐜]=𝐚⋅(𝐛×𝐜)

Let's check with our example.
The columns are 𝐚=(2,0,1), 𝐛=(1,3,0) and 𝐜=(0,1,4).

𝐛×𝐜=(3⋅4−0⋅1,0⋅0−1⋅4,1⋅1−3⋅0)=(12,−4,1)
𝐚⋅(𝐛×𝐜)=2⋅12+0⋅(−4)+1⋅1=25

Same answer, from a completely different direction.
The sign again tells us about handedness: a positive determinant means the three columns form a right-handed set like 𝐢,𝐣,𝐤; a negative one means they're left-handed (mirrored).

10.5 Rules of determinants

A few rules make determinants much easier to work with:

  • det(𝐈)=1. The identity doesn't change anything.
  • det(𝐀𝐁)=det(𝐀)det(𝐁). Doing two transformations multiplies their stretch factors.
  • det(𝐌⊤)=det(𝐌). Rows and columns are equally good.
  • For an n×n matrix, det(s𝐌)=sndet(𝐌). Scaling a 3D object by 2 in every direction multiplies its volume by 23=8.
  • Swapping two columns (or two rows) flips the sign. Swapping two axes is a mirror.

Let's check the product rule with numbers.
Take 𝐀=[3112] (determinant 5) and 𝐁=[2011] (determinant 2⋅1−0⋅1=2).

𝐀𝐁=[3⋅2+1⋅13⋅0+1⋅11⋅2+2⋅11⋅0+2⋅1]=[7142]
det(𝐀𝐁)=7⋅2−1⋅4=10=5⋅2

The product rule also gives us a nice fact for mirrors: one mirror has a negative determinant, two mirrors in a row give a positive one.
Mirroring twice is just a rotation.

Determinant zero: squashing space flat

When the determinant is 0, the matrix squashes the whole plane onto a line (or a point), or the whole 3D space onto a plane, a line or a point.
Look at the "flatten" matrix from the gallery:

[1224][xy]=[x+2y2x+4y]=(x+2y)[12]

Every result is a multiple of (1,2), so every point of the plane lands on one line.
The second column (2,4) is just twice the first column (1,2), so the "parallelogram" has no width at all.

And now the crucial consequence: information is lost.
The point (2,−1) goes to (2−2,4−4)=(0,0), and so does (0,0).
If someone gives you the result (0,0), you can't tell which one it came from.
So a matrix with determinant 0 cannot be undone: it has no inverse.
Such a matrix is called singular.

4×4 determinants

The same cofactor idea works for 4×4 matrices (each of the four cofactors is a 3×3 determinant), but by hand that's a lot of arithmetic, so we let the code do it.
For our affine matrices from chapter 9 there's a shortcut: the determinant of [𝐀𝐭𝟎⊤1] is just det(𝐀).
That makes sense: moving an object doesn't change its volume.
For example, translate({1, 2, 3}) * rotateY(0.4f) * scale({2, 3, 0.5f}) has determinant 1⋅1⋅3=3 (1 for the translation, 1 for the rotation, 3 for the scale).

10.6 Inverse matrices: the undo button

The inverse of a matrix 𝐌 is the matrix 𝐌−1 that undoes it:

𝐌−1𝐌=𝐌𝐌−1=𝐈

If 𝐌 turns 𝐩 into 𝐩′, then 𝐌−1 turns 𝐩′ back into 𝐩.
If 𝐌 rotates 30° to the left, 𝐌−1 rotates 30° to the right.
If 𝐌 doubles the size, 𝐌−1 halves it.

It's the same idea as dividing numbers.
The inverse of 5 is 15, because 5⋅15=1.
And just like 0 has no inverse (you can't divide by zero), a matrix with determinant 0 has no inverse.
For matrices, "determinant is not zero" is the exact condition for "the inverse exists".

10.7 What the formula is: the 2×2 inverse

For a 2×2 matrix there's a short formula: swap the two diagonal entries, negate the other two, and divide by the determinant.

[abcd]−1=1ad−bc[d−b−ca]

How it works

Let's multiply the matrix by the swapped-and-negated matrix and see what happens:

[abcd][d−b−ca]=[ad−bc−ab+bacd−dc−cb+da]=[ad−bc00ad−bc]

That's the identity matrix times ad−bc.
So dividing by ad−bc gives exactly the identity.
And you can see why the determinant must not be 0: we have to divide by it.

Worked example

Let's invert our friend from 10.1:

𝐌=[3112],det(𝐌)=3⋅2−1⋅1=5

Swap 3 and 2, negate the two 1s, and divide by 5:

𝐌−1=15[2−1−13]=[0.4−0.2−0.20.6]

Check: multiply them together.

𝐌𝐌−1=15[3⋅2+1⋅(−1)3⋅(−1)+1⋅31⋅2+2⋅(−1)1⋅(−1)+2⋅3]=15[5005]=[1001]

Now let's actually undo something.
𝐌 sends (1,1) to (3+1,1+2)=(4,3).
Does 𝐌−1 bring it back?

𝐌−1[43]=[0.4⋅4−0.2⋅3−0.2⋅4+0.6⋅3]=[1.6−0.6−0.8+1.8]=[11]

It does.
Also notice that det(𝐌−1)=0.4⋅0.6−(−0.2)⋅(−0.2)=0.24−0.04=0.2=15: if M makes areas 5 times bigger, the inverse makes them 5 times smaller.

10.8 Cheap inverses

A general inverse takes quite a lot of arithmetic.
But for the matrices we build in games, we usually know what they're made of, and then the inverse is almost free.

Socks and shoes

In the morning you put on your socks, then your shoes.
To undo that, you take off your shoes first, then your socks.
Matrices work the same way:

(𝐀𝐁)−1=𝐁−1𝐀−1

Proof: (𝐀𝐁)(𝐁−1𝐀−1)=𝐀(𝐁𝐁−1)𝐀−1=𝐀𝐈𝐀−1=𝐀𝐀−1=𝐈.
(It's the same order reversal as (𝐀𝐁)⊤=𝐁⊤𝐀⊤ from chapter 7.)

So to invert a combination, we only need the inverses of the pieces.

The pieces

  • Scale: undo scaling by s by scaling by 1s. So 𝐒(sx,sy,sz)−1=𝐒(1sx,1sy,1sz). A scale of 0 can't be undone, as expected.
  • Translation: undo moving by 𝐭 by moving by −𝐭. So 𝐓(𝐭)−1=𝐓(−𝐭).
  • Rotation: undo rotating by θ by rotating by −θ. And there's an even nicer way to say it: 𝐑−1=𝐑⊤.

Why the inverse of a rotation is its transpose

The columns of a rotation matrix are the rotated basis vectors.
A rotation doesn't change lengths or angles, so the columns are still unit length (chapter 3) and still perpendicular to each other (dot product 0, chapter 4).
Now look at the product 𝐑⊤𝐑: entry (i,j) is row i of 𝐑⊤ dotted with column j of 𝐑, and row i of 𝐑⊤ is just column i of 𝐑.
So every entry is a dot product of two columns: 1 when a column meets itself, 0 when it meets a different one.
That's exactly the identity matrix.

Let's verify with the 2D rotation (write c=cosθ, s=sinθ):

𝐑⊤𝐑=[cs−sc][c−ssc]=[c2+s2−cs+sc−sc+css2+c2]=[1001]

Matrices whose columns are unit length and mutually perpendicular are called orthogonal matrices, and for all of them the inverse is simply the transpose.
Rotations are orthogonal matrices with determinant 1; mirrors are orthogonal matrices with determinant −1.
The transpose costs no arithmetic at all, just reading the numbers in a different order, which is why game engines love rotations.

Undoing a whole model matrix

Putting it all together with socks and shoes:

(𝐓𝐑𝐒)−1=𝐒−1𝐑−1𝐓−1=𝐒−1𝐑⊤𝐓(−𝐭)

Read from the right: move back, rotate back, un-scale.
Let's test it on the plank from chapter 9: 𝐓(5,0,0), 𝐑 = 90° around Z, 𝐒(2,1,1).
That model matrix sent the local tip (1,0,0) to the world point (5,2,0).
Let's send it back:

  1. 𝐓(−5,0,0): (5,2,0)→(0,2,0).
  2. 𝐑⊤ (a rotation by −90°, which sends (x,y) to (y,−x)): (0,2,0)→(2,0,0).
  3. 𝐒(12,1,1): (2,0,0)→(1,0,0).

We're back at the tip, (1,0,0).

10.9 The general inverse: cofactors and the adjugate

When we don't know what a matrix is made of, we need a general method.
The 2×2 formula is actually a small case of a general recipe:

  1. For every entry, compute its cofactor (its minor with the checkerboard sign from 10.4).
  2. Put the cofactors into a matrix, and transpose it. This is called the adjugate, adj(𝐌).
  3. Divide by the determinant.

𝐌−1=1det(𝐌)adj(𝐌)

Check it on the 2×2 case: the cofactor of a is d, of b is −c, of c is −b and of d is a.
Transposed, that's [d−b−ca], exactly the matrix from 10.7.

For 4×4 matrices, linalg.hh uses this recipe with a clever shortcut.
Every cofactor of a 4×4 matrix is a 3×3 determinant, and every 3×3 determinant is made of 2×2 determinants.
Many of those 2×2 determinants are the same, so the code computes them only once:

  • s0 to s5 are the six 2×2 determinants you can make from the top two rows (one for each pair of columns: 0-1, 0-2, 0-3, 1-2, 1-3, 2-3).
  • c0 to c5 are the six 2×2 determinants from the bottom two rows.

The determinant is then a sum of six products, pairing each top-rows pair of columns with the bottom-rows pair that uses the other two columns: s0 * c5 - s1 * c4 + s2 * c3 + s3 * c2 - s4 * c1 + s5 * c0.
After that, each of the 16 entries of the inverse is one cofactor built from those twelve numbers, divided by the determinant.
You don't need to memorize any of those lines; just know that it's "cofactors, transposed, divided by the determinant", done efficiently.

Two practical notes:

  • With floating-point numbers, a determinant is rarely exactly 0. The header treats anything smaller than 10−8 as zero, reports it through the optional ok flag, and returns the identity instead of a matrix full of infinities.
  • A general 4×4 inverse costs close to a hundred multiplications (94 in the header's version). That's nothing once per object per frame on the CPU, but don't do it once per vertex in a shader if you can avoid it.

10.10 The normal matrix

Here's a problem that confuses almost every beginner.
In chapter 9 we transformed normals with the model matrix and w=0.
That's correct for rotations and uniform scaling, but with non-uniform scale the normals come out wrong: they are no longer perpendicular to the surface.

A worked 2D example

Take a surface going diagonally up, in the direction 𝐭=(1,1) (a direction along the surface is called a tangent).
Its normal is 𝐧=(1,−1), and indeed 𝐧⋅𝐭=1−1=0.
Now we stretch the model by 2 along x: 𝐒=[2001].

Stretching x by 2: S n is no longer perpendicular to the tangent, the inverse transpose normal is

The tangent is part of the surface, so it simply gets stretched: 𝐭′=𝐒𝐭=(2,1).
If we transform the normal the same way we get 𝐒𝐧=(2,−1), and:

𝐭′⋅(𝐒𝐧)=2⋅2+1⋅(−1)=3≠0

Not perpendicular!
The surface got flatter, but the naive normal leaned the wrong way.
Lighting with this normal would look wrong, and it gets worse the more you stretch.

Now try the inverse transpose instead.
𝐒−1=[0.5001], and a diagonal matrix is its own transpose, so:

(𝐒−1)⊤𝐧=[0.5001][1−1]=[0.5−1],𝐭′⋅(0.5,−1)=2⋅0.5+1⋅(−1)=0

Perpendicular again.
Stretching along x made the surface flatter, so its normal must lean less along x, and dividing by 2 does exactly that.

Why the inverse transpose works

We need one small tool first: a dot product can be written as a matrix product, a row times a column:

𝐚⋅𝐛=𝐚⊤𝐛

(a 1×n matrix times an n×1 matrix gives a 1×1 matrix, which is just a number.)
Say the tangent is transformed by 𝐌 and we transform the normal by some unknown matrix 𝐍.
Using (𝐀𝐁)⊤=𝐁⊤𝐀⊤ from chapter 7:

(𝐍𝐧)⋅(𝐌𝐭)=(𝐍𝐧)⊤(𝐌𝐭)=𝐧⊤𝐍⊤𝐌𝐭

If we choose 𝐍 so that 𝐍⊤𝐌=𝐈, the middle disappears and we're left with 𝐧⊤𝐭=𝐧⋅𝐭=0.
So we need 𝐍⊤=𝐌−1, which means:

𝐍=(𝐌−1)⊤

This is called the normal matrix.
Since normals are directions, only the upper-left 3×3 part (the linear part 𝐀) matters.
For an affine 4×4 matrix, the upper-left 3×3 of transpose(inverse(model)) is exactly (𝐀−1)⊤, so you can compute the full 4×4 version and multiply normals with w=0.
The normal matrix doesn't keep lengths, so always normalize the result.

When you can skip it

  • Rotation only: (𝐑−1)⊤=(𝐑⊤)⊤=𝐑. The normal matrix is the model matrix itself.
  • Rotation and uniform scale s: the normal matrix is 1s𝐑, which points the same way as s𝐑. After normalizing, the plain model matrix gives the same answer.
  • Non-uniform scale (or shear): you need the real normal matrix.

Many engines check whether an object's scale is uniform and skip the inverse when it is.

10.11 Use in graphics programming

The normal matrix in the vertex shader

Compute the normal matrix on the CPU once per object (transpose(inverse(model))) and send it as a uniform next to the model matrix.
GLSL does have a built-in inverse function, so you'll often see transpose(inverse(mat3(model))) written directly in the shader, but that recomputes the same inverse for every single vertex.
Passing it in as a uniform is faster and works the same in Slang, GLSL and HLSL.

struct Matrices {
  float4x4 model;
  float4x4 view;
  float4x4 proj;
  float4x4 normalMatrix; // transpose(inverse(model)), computed on the CPU
};
ConstantBuffer<Matrices> matrices;

struct VSInput {
  float3 position : POSITION;
  float3 normal   : NORMAL;
};

struct VSOutput {
  float4 position    : SV_Position;
  float3 worldNormal : NORMAL;
};

[shader("vertex")]
VSOutput vertexMain(VSInput input) {
  VSOutput output;
  float4 worldPos = mul(matrices.model, float4(input.position, 1.0));
  output.position = mul(matrices.proj, mul(matrices.view, worldPos));
  // w = 0: a direction. Normalize, because the normal matrix changes lengths.
  output.worldNormal = normalize(mul(matrices.normalMatrix, float4(input.normal, 0.0)).xyz);
  return output;
}
#version 450

layout(set = 0, binding = 0) uniform Matrices {
  mat4 model;
  mat4 view;
  mat4 proj;
  mat4 normalMatrix; // transpose(inverse(model)), computed on the CPU
};

layout(location = 0) in vec3 inPosition;
layout(location = 1) in vec3 inNormal;

layout(location = 0) out vec3 worldNormal;

void main() {
  vec4 worldPos = model * vec4(inPosition, 1.0);
  gl_Position = proj * (view * worldPos);
  // w = 0: a direction. Normalize, because the normal matrix changes lengths.
  worldNormal = normalize((normalMatrix * vec4(inNormal, 0.0)).xyz);
}
struct Matrices {
  float4x4 model;
  float4x4 view;
  float4x4 proj;
  float4x4 normalMatrix; // transpose(inverse(model)), computed on the CPU
};
ConstantBuffer<Matrices> matrices;

struct VSInput {
  float3 position : POSITION;
  float3 normal   : NORMAL;
};

struct VSOutput {
  float4 position    : SV_Position;
  float3 worldNormal : NORMAL;
};

VSOutput vertexMain(VSInput input) {
  VSOutput output;
  float4 worldPos = mul(matrices.model, float4(input.position, 1.0));
  output.position = mul(matrices.proj, mul(matrices.view, worldPos));
  // w = 0: a direction. Normalize, because the normal matrix changes lengths.
  output.worldNormal = normalize(mul(matrices.normalMatrix, float4(input.normal, 0.0)).xyz);
  return output;
}

Also normalize again in the fragment shader: interpolating between unit vectors across a triangle gives vectors that are slightly shorter than 1.

The view matrix is an inverse

A camera is just another object in the world, with its own position and rotation, so it has a world matrix like any model.
But when rendering, we need the opposite direction: we want to know where everything is relative to the camera.
That's the inverse:

𝐕=(𝐓camera𝐑camera)−1=𝐑camera⊤𝐓(−𝐩camera)

For example, a camera at (0,0,5) that isn't rotated has the world matrix 𝐓(0,0,5), so its view matrix is 𝐓(0,0,−5).
The world origin ends up at (0,0,−5) in view space: 5 units in front of the camera, which looks down −Z.
Chapter 11 builds this properly with lookAt, which uses exactly the cheap "transpose the rotation, negate the translation" inverse.

Mirrored models flip the winding order

In chapter 5 we saw that the GPU decides which side of a triangle faces the camera from the winding order of its vertices, counter-clockwise or clockwise on screen.
A matrix with a negative determinant mirrors the model, and a mirror turns every counter-clockwise triangle into a clockwise one.
For example, the triangle (0,0),(1,0),(0,1) is counter-clockwise: the z of the cross product of its two edges is 1⋅1−0⋅0=1>0.
Mirror x and it becomes (0,0),(−1,0),(0,1), and the z of the cross product becomes (−1)⋅1−0⋅0=−1<0: clockwise.

So if you use scale({-1.0f, 1.0f, 1.0f}) to make a left hand from a right hand, backface culling suddenly removes the front of the model and you see it inside out.
The fix is to check the determinant on the CPU and swap the front-face setting for that object:

// 鏡映された物体か / is this object mirrored?
inline bool isMirrored(const Mat4 &model) {
  return determinant(model) < 0.0f;
}

In OpenGL that means calling glFrontFace(GL_CW) instead of glFrontFace(GL_CCW) while drawing a mirrored object (or swapping whatever front face you normally use).
In Vulkan the front face is part of the pipeline's rasterization state, so you either keep a second pipeline with VK_FRONT_FACE_CLOCKWISE and VK_FRONT_FACE_COUNTER_CLOCKWISE swapped, or enable it as dynamic state and call vkCmdSetFrontFace (core since Vulkan 1.3).

From the world into an object's own space

The inverse of a model matrix takes world positions into the object's local space.
That makes many questions much easier.
For example: is the player inside this rotated trigger box?
In world space the box is rotated, which is awkward to test.
In its own local space the box is a simple axis-aligned box from −𝐡 to 𝐡 (its half size), so we just compare coordinates:

// 回転した箱の中に点があるか / is a point inside a rotated (and moved) box?
bool insideBox(const Mat4 &boxModel, Vec3 halfSize, Vec3 worldPoint) {
  Vec4 p = inverse(boxModel) * Vec4{worldPoint.x, worldPoint.y, worldPoint.z, 1.0f};
  return std::fabs(p.x) <= halfSize.x &&
         std::fabs(p.y) <= halfSize.y &&
         std::fabs(p.z) <= halfSize.z;
}

Let's use a box with half size (2,1,1), rotated 90° around Y and placed at (10,0,0), so its long side now runs along world Z.
The player at (10.5,0,1.5) is moved back by −(10,0,0) to (0.5,0,1.5), then rotated back by −90° around Y to (−1.5,0,0.5).
All three coordinates are inside the half size, so the player is inside.
If we had forgotten the rotation and compared (0.5,0,1.5) directly, we'd wrongly say "outside" because 1.5>1.
The point (12,0,0) becomes (0,0,2) in local space and is correctly outside, since the box only reaches 1 unit from its center in that direction.

More places you'll meet inverses

  • Mouse picking: to find what's under the mouse cursor, you go backwards through the projection and view matrices, using the inverse of 𝐏𝐕 (chapter 12).
  • Shadow maps and decals: a world position is moved into the light's or the decal projector's space with the inverse of its world matrix.
  • Degenerate scale: an animation that scales an object to exactly 0 makes its determinant 0. Its inverse (and normal matrix) no longer exists, which is a common source of NaN lighting. Clamp the scale to a tiny positive value or skip the object.

10.12 Other uses

  • Solving systems of equations: the equations 3x+y=9 and x+2y=8 are the matrix equation 𝐌𝐱=𝐛 with our matrix 𝐌=[3112] and 𝐛=(9,8). Then 𝐱=𝐌−1𝐛=(0.4⋅9−0.2⋅8,−0.2⋅9+0.6⋅8)=(2,3). (Real solvers use elimination methods instead of the full inverse, but the idea is the same.)
  • Unique solutions: a system 𝐌𝐱=𝐛 with a square matrix has exactly one solution if and only if det(𝐌)≠0. With determinant 0 there are either no solutions or infinitely many.
  • Cramer's rule: each unknown is a ratio of determinants: replace that unknown's column with 𝐛. For the system above, x=9⋅2−1⋅85=2 and y=3⋅8−9⋅15=3. It's handy for 2×2 and 3×3 systems by hand.
  • Cryptography: the Hill cipher encrypts groups of letters by multiplying them with a key matrix (modulo 26). Decryption needs the inverse, so the key's determinant must have no common factor with 26.
  • Electronics: circuit analysis turns Kirchhoff's laws into a matrix equation between voltages and currents, solved with the inverse (or elimination).
  • Economics: the Leontief input–output model computes how much each industry must produce with 𝐱=(𝐈−𝐀)−1𝐝.
  • Statistics and machine learning: linear regression's classic formula contains (𝐗⊤𝐗)−1, and the determinant of a covariance matrix measures how "spread out" data is.

10.13 Code

Here are this chapter's additions to linalg.hh, exactly as they are in the header.
Both functions share the same twelve 2×2 determinants described in 10.9.

// 行列式(余因子展開) / determinant (cofactor expansion) (chapter 10)
inline float determinant(const Mat4 &m) {
  auto a = [&](int r, int c) { return m.at(r, c); };
  float s0 = a(0,0) * a(1,1) - a(1,0) * a(0,1);
  float s1 = a(0,0) * a(1,2) - a(1,0) * a(0,2);
  float s2 = a(0,0) * a(1,3) - a(1,0) * a(0,3);
  float s3 = a(0,1) * a(1,2) - a(1,1) * a(0,2);
  float s4 = a(0,1) * a(1,3) - a(1,1) * a(0,3);
  float s5 = a(0,2) * a(1,3) - a(1,2) * a(0,3);
  float c5 = a(2,2) * a(3,3) - a(3,2) * a(2,3);
  float c4 = a(2,1) * a(3,3) - a(3,1) * a(2,3);
  float c3 = a(2,1) * a(3,2) - a(3,1) * a(2,2);
  float c2 = a(2,0) * a(3,3) - a(3,0) * a(2,3);
  float c1 = a(2,0) * a(3,2) - a(3,0) * a(2,2);
  float c0 = a(2,0) * a(3,1) - a(3,0) * a(2,1);
  return s0 * c5 - s1 * c4 + s2 * c3 + s3 * c2 - s4 * c1 + s5 * c0;
}

// 逆行列 / inverse matrix (chapter 10)
// 行列式が0なら逆行列は存在しない。okにfalseを入れて単位行列を返す。
// If the determinant is 0 there is no inverse: sets ok to false and returns identity.
inline Mat4 inverse(const Mat4 &m, bool *ok = nullptr) {
  auto a = [&](int r, int c) { return m.at(r, c); };
  float s0 = a(0,0) * a(1,1) - a(1,0) * a(0,1);
  float s1 = a(0,0) * a(1,2) - a(1,0) * a(0,2);
  float s2 = a(0,0) * a(1,3) - a(1,0) * a(0,3);
  float s3 = a(0,1) * a(1,2) - a(1,1) * a(0,2);
  float s4 = a(0,1) * a(1,3) - a(1,1) * a(0,3);
  float s5 = a(0,2) * a(1,3) - a(1,2) * a(0,3);
  float c5 = a(2,2) * a(3,3) - a(3,2) * a(2,3);
  float c4 = a(2,1) * a(3,3) - a(3,1) * a(2,3);
  float c3 = a(2,1) * a(3,2) - a(3,1) * a(2,2);
  float c2 = a(2,0) * a(3,3) - a(3,0) * a(2,3);
  float c1 = a(2,0) * a(3,2) - a(3,0) * a(2,2);
  float c0 = a(2,0) * a(3,1) - a(3,0) * a(2,1);
  float det = s0 * c5 - s1 * c4 + s2 * c3 + s3 * c2 - s4 * c1 + s5 * c0;

  if (std::fabs(det) < 1e-8f) {
    if (ok) *ok = false;
    return Mat4::identity();
  }
  if (ok) *ok = true;

  float inv = 1.0f / det;
  Mat4 r;
  r.at(0,0) = ( a(1,1) * c5 - a(1,2) * c4 + a(1,3) * c3) * inv;
  r.at(0,1) = (-a(0,1) * c5 + a(0,2) * c4 - a(0,3) * c3) * inv;
  r.at(0,2) = ( a(3,1) * s5 - a(3,2) * s4 + a(3,3) * s3) * inv;
  r.at(0,3) = (-a(2,1) * s5 + a(2,2) * s4 - a(2,3) * s3) * inv;
  r.at(1,0) = (-a(1,0) * c5 + a(1,2) * c2 - a(1,3) * c1) * inv;
  r.at(1,1) = ( a(0,0) * c5 - a(0,2) * c2 + a(0,3) * c1) * inv;
  r.at(1,2) = (-a(3,0) * s5 + a(3,2) * s2 - a(3,3) * s1) * inv;
  r.at(1,3) = ( a(2,0) * s5 - a(2,2) * s2 + a(2,3) * s1) * inv;
  r.at(2,0) = ( a(1,0) * c4 - a(1,1) * c2 + a(1,3) * c0) * inv;
  r.at(2,1) = (-a(0,0) * c4 + a(0,1) * c2 - a(0,3) * c0) * inv;
  r.at(2,2) = ( a(3,0) * s4 - a(3,1) * s2 + a(3,3) * s0) * inv;
  r.at(2,3) = (-a(2,0) * s4 + a(2,1) * s2 - a(2,3) * s0) * inv;
  r.at(3,0) = (-a(1,0) * c3 + a(1,1) * c1 - a(1,2) * c0) * inv;
  r.at(3,1) = ( a(0,0) * c3 - a(0,1) * c1 + a(0,2) * c0) * inv;
  r.at(3,2) = (-a(3,0) * s3 + a(3,1) * s1 - a(3,2) * s0) * inv;
  r.at(3,3) = ( a(2,0) * s3 - a(2,1) * s1 + a(2,2) * s0) * inv;
  return r;
}

The ok pointer is optional: pass &ok when you want to know whether the inverse exists, or leave it out when you're sure it does.

Here's a test program.
It checks the determinants from this chapter, verifies that model * inverse(model) is the identity (allowing for tiny floating-point errors, so we compare with a tolerance instead of ==), undoes the plank from chapter 9, and computes the normal from 10.10 in 3D.
radians() comes from chapter 1, and tidy hides the -0.00 that floating-point math likes to produce.

#include "linalg.hh"
#include <cstdio>

static float tidy(float v) { return std::fabs(v) < 1e-5f ? 0.0f : v; }

static void printMat(const char *name, const Mat4 &m) {
  printf("%s\n", name);
  for (int row = 0; row < 4; ++row) {
    printf("  %7.3f %7.3f %7.3f %7.3f\n",
           tidy(m.at(row, 0)), tidy(m.at(row, 1)), tidy(m.at(row, 2)), tidy(m.at(row, 3)));
  }
}

// 単位行列との最大誤差 / largest difference from the identity matrix
static float errorFromIdentity(const Mat4 &m) {
  Mat4 id = Mat4::identity();
  float worst = 0.0f;
  for (int row = 0; row < 4; ++row)
    for (int col = 0; col < 4; ++col)
      worst = std::fmax(worst, std::fabs(m.at(row, col) - id.at(row, col)));
  return worst;
}

int main() {
  // 1. Determinants
  Mat4 model = translate({1.0f, 2.0f, 3.0f}) * rotateY(0.4f) * scale({2.0f, 3.0f, 0.5f});
  printf("det(model)  = %.3f\n", determinant(model));
  printf("det(mirror) = %.3f\n", determinant(scale({-1.0f, 1.0f, 1.0f})));
  printf("det(flat)   = %.3f\n", determinant(scale({1.0f, 0.0f, 1.0f})));

  // 2. Inverse and the M * M^-1 = I check
  bool ok = false;
  Mat4 inv = inverse(model, &ok);
  printf("ok = %s, error = %s\n", ok ? "true" : "false",
         errorFromIdentity(model * inv) < 1e-5f ? "tiny" : "LARGE");

  inverse(scale({1.0f, 0.0f, 1.0f}), &ok);
  printf("flat matrix: ok = %s\n", ok ? "true" : "false");

  // 3. Undoing a TRS matrix
  Mat4 m = translate({5.0f, 0.0f, 0.0f}) * rotateZ(radians(90.0f)) * scale({2.0f, 1.0f, 1.0f});
  printMat("inverse(TRS)", inverse(m));
  Vec4 back = inverse(m) * Vec4{5.0f, 2.0f, 0.0f, 1.0f};
  printf("back = (%.2f, %.2f, %.2f, %.2f)\n", tidy(back.x), tidy(back.y), tidy(back.z), tidy(back.w));

  // 4. Normal matrix
  Mat4 stretch = scale({2.0f, 1.0f, 1.0f});
  Mat4 normalMatrix = transpose(inverse(stretch));
  Vec4 n = normalMatrix * Vec4{1.0f, -1.0f, 0.0f, 0.0f};
  printf("normal = (%.2f, %.2f, %.2f)\n", tidy(n.x), tidy(n.y), tidy(n.z));
  return 0;
}

Expected output:

det(model)  = 3.000
det(mirror) = -1.000
det(flat)   = 0.000
ok = true, error = tiny
flat matrix: ok = false
inverse(TRS)
    0.000   0.500   0.000   0.000
   -1.000   0.000   0.000   5.000
    0.000   0.000   1.000   0.000
    0.000   0.000   0.000   1.000
back = (1.00, 0.00, 0.00, 1.00)
normal = (0.50, -1.00, 0.00)

Look at the printed inverse: its upper-left part is 𝐒−1𝐑⊤ (the transposed rotation with one row halved), and its last column (0,5,0) is −𝐒−1𝐑⊤𝐭.
That's exactly the cheap formula from 10.8, computed the expensive way.
The normal (0.5,−1,0) isn't unit length yet; in a shader we'd normalize it.

10.14 Summary

  • The determinant is the signed area (2D) or volume (3D) scale factor of a matrix. For 2×2 it's ad−bc; for 3×3 use cofactor expansion, or the triple product 𝐚⋅(𝐛×𝐜) of the columns.
  • Negative determinant = mirrored (orientation flipped). Zero determinant = space squashed flat, information lost, no inverse.
  • det(𝐀𝐁)=det(𝐀)det(𝐁), rotations have determinant 1, translation doesn't change the determinant.
  • The inverse undoes a matrix: 𝐌𝐌−1=𝐈. For 2×2: swap the diagonal, negate the rest, divide by the determinant.
  • Socks and shoes: (𝐀𝐁)−1=𝐁−1𝐀−1. Cheap pieces: scale by 1s, rotation by 𝐑⊤, translation by −𝐭, so (𝐓𝐑𝐒)−1=𝐒−1𝐑⊤𝐓−1.
  • The general inverse is the adjugate (transposed cofactors) divided by the determinant; inverse() reports failure through ok.
  • Normals must be transformed with the normal matrix (𝐌−1)⊤ (upper 3×3) and renormalized; with only rotation and uniform scale the model matrix is enough.
  • In graphics: the view matrix is an inverse, a negative determinant means you must swap the front face, and the inverse model matrix takes world positions into an object's local space.

10.15 Challenges

  1. ★ Compute the determinants of [4213] and [2613]. What does each one do to the area of the unit square? You should get 10 and 0; explain what the 0 means for the second matrix's columns.
  2. ★ Compute the determinant of [123045106] with cofactor expansion along the first row, then again along the first column. Both should give 22.
  3. ★ Invert [4726] with the 2×2 formula and check that the product with the original is the identity. You should get [0.6−0.7−0.20.4].
  4. ★ Invert [120013001] (its determinant is 1, so the inverse has only whole numbers). Check your answer by multiplying.
  5. ★ A 2D surface has the tangent (1,2) and the normal (2,−1). Scale it by [3001]. Show that the naive normal (6,−1) is not perpendicular to the new tangent (the dot product is 16), and that the normal matrix gives a normal that is.
  6. ★★ Write Mat4 inverseTRS(Vec3 t, float angleY, Vec3 s) that returns 𝐒−1𝐑⊤𝐓(−𝐭) using only scale, transpose, rotateY and translate. Compare all 16 entries with inverse(translate(t) * rotateY(angleY) * scale(s)) for t = {1, 2, 3}, angleY = 0.4f, s = {2, 3, 0.5f}; the largest difference should be below 0.00001.
  7. ★★★ Show that the inverse of an affine matrix [𝐀𝐭𝟎⊤1] is [𝐀−1−𝐀−1𝐭𝟎⊤1] (multiply them with the block formula from chapter 9). Then simplify it for a camera whose 𝐀 is a rotation. Each entry of the new translation column turns out to be a dot product; which vectors are being dotted? (You'll meet this again in chapter 11's lookAt.)


コメント(0)

まだコメントはありません。