We closed the previous module with some unfinished business: orientations. We know how to rotate the ship about a coordinate axis and how to build an orientation matrix from a direction, but we still cannot describe an arbitrary rotation with just a few numbers, combine it with others without surprises, or move smoothly from one orientation to another. This module solves all three, and it starts with the most intuitive description of all: three angles. "Turn 53° to the left, raise the nose 30° and bank the wings 20°" is a sentence anyone understands, and that is why Euler angles sit in the inspector of every 3D editor. But that simplicity comes with fine print—the order of the rotations matters, and the same three numbers mean different things in each program—and it hides a famous flaw, gimbal lock, which is worth understanding properly before it shows up in your game.

The code assumes that rotation_matrix_x, rotation_matrix_y and rotation_matrix_z (4×4, from "Rotations, Translations and Scalings"), orthonormal_basis, angle_between and displacement (from Module 3) and the matrix ship_orientation are already defined.

Orientation and rotation: three degrees of freedom

Two words that we tend to use as synonyms and that are worth telling apart:

  • A rotation is an action: a transformation that turns vectors (an "angular displacement").
  • An orientation is a state: where an object's own axes are pointing.

The relationship between the two is the same as the one between a displacement and a position. A position is described as the displacement that takes you from the origin to it; an orientation is described as the rotation that takes you from a reference orientation to it. The reference is the "factory" orientation: the object's axes aligned with the world's (the identity matrix). So when we say that the ship's orientation is \(N = R_y(53.13°)\), we are saying that the ship sits the way a freshly loaded model would after that rotation is applied to it. That is why the same mathematical object—a rotation matrix—serves both purposes.

How many numbers does it take to pin down an orientation? A 3×3 matrix has nine, but they are not free. To be a rotation, its columns must be unit vectors (three conditions) and mutually perpendicular (another three). That leaves

\[ 9 - 6 = 3 \ \text{degrees of freedom} \]

You can also see it geometrically: to place the ship you have to choose where the nose points (a direction is two numbers, like the azimuth and elevation of spherical coordinates) and how far it is rotated about that direction (a third number). An orientation in 3D is three numbers; the matrix uses nine and therefore stores redundant information. Euler angles are the most direct attempt to keep only the three essential ones.

Euler angles: yaw, pitch and roll

The idea, due to Leonhard Euler, is that any orientation can be reached by chaining three basic rotations about coordinate axes. The three angles of those rotations are the Euler angles. In aviation and in video games they have names of their own, and we already introduced them when we built \(R_x\), \(R_y\) and \(R_z\):

Name Axis (with Y up and the nose along +Z) What the ship does Positive rotation
Yaw Y (vertical) Swings the nose to one side or the other Takes the nose from +Z toward +X
Pitch X (transverse, from wing to wing) Raises or lowers the nose Takes the nose from +Z toward −Y: lowers it
Roll Z (longitudinal, from tail to nose) Banks the wings Takes the wing from +X toward +Y: raises it

The positive directions are not a matter of choice: they follow from the right-hand rule and the cyclic pattern \(X \to Y \to Z \to X\). The most surprising one is pitch: \(R_x\) takes Y toward Z and, therefore, Z toward \(-Y\). Since the nose of our ship is its local \(+Z\) axis, a positive pitch lowers the nose; to raise it 30° you have to use a pitch of \(-30°\). (In an engine whose camera or objects look toward \(-Z\), the opposite happens. It is the first warning that with Euler angles everything depends on conventions.)

Order matters: conventions

Three angles are not enough to define an orientation: you also have to say in what order the rotations are applied, because rotations do not commute. Let's check it with two quarter turns applied to the ship in its factory orientation (nose \((0, 0, 1)\), roof \((0, 1, 0)\)):

  • First a 90° pitch, then a 90° yaw (\(R_y R_x\); remember that the matrix on the right is applied first). The pitch lowers the nose to \((0, -1, 0)\) and leaves the roof at \((0, 0, 1)\). The yaw does not move the nose (it lies on the Y axis) and takes the roof to \((1, 0, 0)\). Result: the ship points straight down.
  • First a 90° yaw, then a 90° pitch (\(R_x R_y\)). The yaw takes the nose to \((1, 0, 0)\). The pitch does not move it (it lies on the X axis) and tips the roof over to \((0, 0, 1)\). Result: the ship points toward +X, flying on its side.
import numpy as np

quarter = np.radians(90.0)
pitch_then_yaw = (rotation_matrix_y(quarter) @ rotation_matrix_x(quarter))[:3, :3]
yaw_then_pitch = (rotation_matrix_x(quarter) @ rotation_matrix_y(quarter))[:3, :3]

nose, roof = np.array([0.0, 0.0, 1.0]), np.array([0.0, 1.0, 0.0])
print(np.round(pitch_then_yaw @ nose, 6) + 0.0, np.round(pitch_then_yaw @ roof, 6) + 0.0)
print(np.round(yaw_then_pitch @ nose, 6) + 0.0, np.round(yaw_then_pitch @ roof, 6) + 0.0)
[ 0. -1.  0.] [1. 0. 0.]
[1. 0. 0.] [0. 0. 1.]

The same two angles, two completely different orientations. That is why there are many conventions. With three different axes there are six possible orders (XYZ, XZY, YXZ, YZX, ZXY, ZYX), sometimes called Tait–Bryan angles; if the first axis is allowed to repeat in the third rotation (ZXZ, ZYZ...), another six appear, the "classical" Euler angles of mechanics. Twelve sequences in total, and each of them can also be read in two ways, as we are about to see.

Where Usual convention
Aeronautics (Z down, X toward the nose) Yaw about Z, pitch about Y, roll about X
Engines with Y up (like mini3d) Yaw about Y, pitch about X, roll about Z
Modeling tools Configurable per object (XYZ by default in many)
Classical mechanics, robotics ZXZ or ZYZ

The practical consequence: three angles without their convention mean nothing. When passing data between a modeling program and an engine you need to know each one's axis sequence, the positive direction and whether the angles are in degrees or in radians.

Fixed axes and body axes

There is one more ambiguity left, and a subtler one. When we say "first yaw, then pitch", is the pitch performed about the world's X axis or about the ship's X axis, which has already turned with the yaw?

  • Extrinsic rotations: every rotation is performed about the fixed axes of the world.
  • Intrinsic rotations: each rotation is performed about one of the object's own axes, as it stands after the previous rotations.

A pilot thinks in intrinsic rotations: pull the stick and the ship pitches about its wings, wherever they happen to be. The matrices \(R_x\), \(R_y\), \(R_z\), on the other hand, rotate about the world axes. Fortunately, there is a result that reconciles them:

A sequence of intrinsic rotations is equivalent to the extrinsic sequence with the same angles applied in reverse order.

Let's see why. Suppose the object already has orientation \(R\) and we want to rotate it about one of its own axes, say its local X axis, with the basic matrix \(R_x(\theta)\). That matrix is written "in the object's coordinates". In "Inverse Transformations and Change of Coordinate System" we saw how a transformation defined in another system is expressed in the world: you go to the local system, apply it and come back, that is, \(R,R_x(\theta),R^{-1}\). Applying it after the current orientation:

\[ \underbrace{\left(R,R_x(\theta),R^{-1}\right)}_{\text{rotation about the local axis}}\ R ;=; R,R_x(\theta) \]

Rotating about one of the object's own axes means multiplying on the right; rotating about a world axis means multiplying on the left. So a product such as \(R_y,R_x,R_z\) admits two readings, both correct:

Reading Order Axes
From right to left (extrinsic) Roll, then pitch, then yaw The world's, fixed
From left to right (intrinsic) Yaw, then pitch, then roll The ship's, which turn along with it

The mini3d convention

Polaris Studio fixes for mini3d the most common convention in engines with the Y axis pointing up:

\[ R(\psi, \theta, \varphi) = R_y(\psi);R_x(\theta);R_z(\varphi) \]

with \(\psi\) the yaw, \(\theta\) the pitch and \(\varphi\) the roll. In the code, the parameters always come in that order: (yaw, pitch, roll), in radians.

The intrinsic reading is the one that matches intuition: starting from the factory orientation, the ship swings its nose (yaw, about the vertical), then raises or lowers it (pitch, about its own wing-to-wing axis) and finally banks its wings (roll, about its own longitudinal axis). This is the "YXZ" convention.

It also has a very convenient property. The nose is the image of \((0, 0, 1)\), and the roll does not move it because it rotates about that very axis. So the direction of the nose depends only on the yaw and the pitch:

\[ \text{nose} = \begin{pmatrix} \sin\psi,\cos\theta \ -\sin\theta \ \cos\psi,\cos\theta \end{pmatrix} \]

Compare it with the spherical coordinates of "Coordinates and Planes": it is exactly the direction with azimuth \(\psi\) (measured from \(+Z\) toward \(+X\)) and elevation \(-\theta\). Yaw and pitch are the spherical coordinates of the nose, and roll is the third degree of freedom, the rotation about it.

From Euler angles to a matrix

Multiplying the three basic matrices (3×3 blocks) gives the full matrix. With the shorthand \(c_\psi = \cos\psi\), \(s_\psi = \sin\psi\), and so on, first the product on the right:

\[ R_x(\theta),R_z(\varphi) = \begin{pmatrix} 1 & 0 & 0 \ 0 & c_\theta & -s_\theta \ 0 & s_\theta & c_\theta \end{pmatrix} \begin{pmatrix} c_\varphi & -s_\varphi & 0 \ s_\varphi & c_\varphi & 0 \ 0 & 0 & 1 \end{pmatrix}

\begin{pmatrix} c_\varphi & -s_\varphi & 0 \ c_\theta s_\varphi & c_\theta c_\varphi & -s_\theta \ s_\theta s_\varphi & s_\theta c_\varphi & c_\theta \end{pmatrix} \]

and then, multiplying by \(R_y(\psi)\) on the left:

\[ R = \begin{pmatrix} c_\psi c_\varphi + s_\psi s_\theta s_\varphi & -c_\psi s_\varphi + s_\psi s_\theta c_\varphi & s_\psi c_\theta \\ c_\theta s_\varphi & c_\theta c_\varphi & -s_\theta \\ -s_\psi c_\varphi + c_\psi s_\theta s_\varphi & s_\psi s_\varphi + c_\psi s_\theta c_\varphi & c_\psi c_\theta \end{pmatrix} \]

There is no need to memorize it; it is worth noticing, though, two especially simple regions that we will use for the way back: the third column (the nose, with no trace of the roll) and the second row (with no trace of the yaw).

Example: orienting the ship. The ship's current orientation is \(N = R_y(53.13°)\): a yaw of 53.13°, pitch 0° and roll 0°. Now the pilot raises the nose 30° (a pitch of \(-30°\)), with no roll. With \(c_\psi = 0.6\), \(s_\psi = 0.8\), \(c_\theta = \cos(-30°) \approx 0.866\), \(s_\theta = -0.5\), \(c_\varphi = 1\) and \(s_\varphi = 0\):

\[ R = \begin{pmatrix} 0.6 & 0.8 \cdot (-0.5) & 0.8 \cdot 0.866 \\ 0 & 0.866 & 0.5 \\ -0.8 & 0.6 \cdot (-0.5) & 0.6 \cdot 0.866 \end{pmatrix} = \begin{pmatrix} 0.6 & -0.4 & 0.693 \\ 0 & 0.866 & 0.5 \\ -0.8 & -0.3 & 0.520 \end{pmatrix} \]

The third column, \((0.693, 0.5, 0.520)\), is the new nose: its Y component is \(0.5 = \sin 30°\), so it points 30° above the horizon, as we wanted. The first column (the wing-to-wing axis, \(n_1\)) has not changed: it is the axis about which the ship has pitched.

def euler_to_matrix(yaw, pitch, roll):
    """3x3 orientation matrix: R = R_y(yaw) @ R_x(pitch) @ R_z(roll).

    Angles in radians. Read from left to right, about the object's own axes:
    first yaw, then pitch and finally roll.
    """
    r = rotation_matrix_y(yaw) @ rotation_matrix_x(pitch) @ rotation_matrix_z(roll)
    return r[:3, :3]

ship_yaw = np.arctan2(0.8, 0.6)                         # 53.13 degrees
print(np.allclose(euler_to_matrix(ship_yaw, 0.0, 0.0), ship_orientation))

maneuver = euler_to_matrix(ship_yaw, np.radians(-30.0), np.radians(20.0))
print(np.round(maneuver, 4))
print(np.round(maneuver[:, 2], 4))                      # the nose
True
[[ 0.427  -0.5811  0.6928]
 [ 0.2962  0.8138  0.5   ]
 [-0.8544 -0.0083  0.5196]]
[0.6928 0.5    0.5196]

The function returns a 3×3 matrix, like ship_orientation; model_matrix accepts it as is to assemble the full model matrix. In the second call we have added a roll of 20°: the first two columns have changed (the wings and the roof tilt), but the nose is the same one we computed by hand.

From a matrix to Euler angles

The way back—given a rotation matrix, recover the three angles—is done by reading the simple regions of the matrix. Numbering rows and columns from 0, as NumPy does:

  1. Pitch. The entry \(r_{12}\) (second row, third column) equals \(-\sin\theta\). Therefore \(\theta = \arcsin(-r_{12})\).
  2. Yaw. In the third column, \(r_{02} = s_\psi c_\theta\) and \(r_{22} = c_\psi c_\theta\). Their quotient is \(\tan\psi\), and since \(c_\theta > 0\) it does not alter the signs: \(\psi = \text{arctan2}(r_{02},\ r_{22})\).
  3. Roll. In the second row, \(r_{10} = c_\theta s_\varphi\) and \(r_{11} = c_\theta c_\varphi\): \(\varphi = \text{arctan2}(r_{10},\ r_{11})\).

We use arctan2(sine, cosine) whenever we can because it tells the four quadrants apart; arcsin only returns angles between \(-90°\) and \(90°\), and that determines the ranges of the extraction:

Angle Function Range returned
Yaw \(\psi\) arctan2 \((-180°, 180°]\)
Pitch \(\theta\) arcsin \([-90°, 90°]\)
Roll \(\varphi\) arctan2 \((-180°, 180°]\)

Steps 2 and 3 implicitly divide by \(c_\theta\). If the pitch is \(\pm 90°\), then \(c_\theta = 0\), all four entries are zero and arctan2(0, 0) tells us nothing. That special case is the gimbal lock of the next section; the function handles it separately (we will see in a moment where the alternative formula comes from).

def matrix_to_euler(r, tolerance=1e-6):
    """Return (yaw, pitch, roll) in radians for a rotation matrix.

    Convention R = R_y @ R_x @ R_z. Pitch in [-pi/2, pi/2]. At gimbal lock
    (a pitch of +-90 degrees) roll = 0 is returned.
    """
    r = np.asarray(r, dtype=float)[:3, :3]
    sin_pitch = float(np.clip(-r[1, 2], -1.0, 1.0))
    pitch = np.arcsin(sin_pitch)
    if abs(sin_pitch) < 1.0 - tolerance:
        yaw = np.arctan2(r[0, 2], r[2, 2])
        roll = np.arctan2(r[1, 0], r[1, 1])
    else:                                        # gimbal lock
        yaw = np.arctan2(-r[2, 0], r[0, 0])
        roll = 0.0
    return float(yaw), float(pitch), float(roll)

print(np.round(np.degrees(matrix_to_euler(ship_orientation)), 2) + 0.0)
print(np.round(np.degrees(matrix_to_euler(maneuver)), 2) + 0.0)

# "Pointing at the lighthouse" orientation built with orthonormal_basis in Module 3
toward_lighthouse = orthonormal_basis(displacement(vec3(8.0, 3.0, 6.0), vec3(0.0, 0.0, 0.0)))
print(np.round(np.degrees(matrix_to_euler(toward_lighthouse)), 2) + 0.0)
[53.13  0.    0.  ]
[ 53.13 -30.    20.  ]
[-126.87   16.7     0.  ]

The first line confirms what we knew: \(N\) is a pure yaw of 53.13°. The third is more interesting. To look at the lighthouse from \((8, 3, 6)\), the ship needs a yaw of \(-126.87°\)—exactly half a turn from the current one, because the lighthouse is dead astern—and a pitch of \(+16.7°\) (nose down: the lighthouse is lower). And the roll comes out as 0: orthonormal_basis always produces orientations with no roll, because it builds the "right" axis perpendicular to the vertical, that is, with the wings level.

Gimbal lock

What it is

A gimbal is a ring that can turn about an axis. Mounting three rings, one inside another, with perpendicular axes gives the classic support of a gyroscope: the object at the center can take any orientation. Euler angles describe exactly that mechanism: the outer ring is the yaw, the middle one the pitch and the inner one the roll. Each ring carries along the ones inside it.

The problem appears when the middle ring turns 90°: the axis of the inner ring ends up aligned with that of the outer one. From that moment on, turning the outer ring and turning the inner ring produce the same motion. Of the three degrees of freedom only two remain: there is a direction of rotation that the mechanism can no longer perform. That is gimbal lock.

On the ship: with a pitch of 90°, the nose points straight down. The roll axis (the longitudinal one) then coincides with the vertical, which is the yaw axis. "Yawing" and "rolling" are now the same thing: both spin the ship about the vertical.

Algebraic proof

Let's substitute \(\theta = 90°\) (\(s_\theta = 1\), \(c_\theta = 0\)) into the general matrix:

\[ R = \begin{pmatrix} c_\psi c_\varphi + s_\psi s_\varphi & -c_\psi s_\varphi + s_\psi c_\varphi & 0 \\ 0 & 0 & -1 \\ -s_\psi c_\varphi + c_\psi s_\varphi & s_\psi s_\varphi + c_\psi c_\varphi & 0 \end{pmatrix} \]

The four expressions that remain are the formulas for the cosine and the sine of a difference of angles:

\[ R = \begin{pmatrix} \cos(\psi - \varphi) & \sin(\psi - \varphi) & 0 \\ 0 & 0 & -1 \\ -\sin(\psi - \varphi) & \cos(\psi - \varphi) & 0 \end{pmatrix} \]

The matrix no longer depends on \(\psi\) and \(\varphi\) separately, but only on their difference \(\psi - \varphi\). We had three parameters and the orientation only "sees" two: the pitch (fixed at 90°) and \(\psi - \varphi\). A degree of freedom has been lost. With \(\theta = -90°\) (nose straight up) the same thing happens, but the matrix depends on the sum \(\psi + \varphi\).

Numerical proof

Let's take two different triples of angles with a pitch of 90° and the same difference \(\psi - \varphi = 20°\):

g = np.radians
a = euler_to_matrix(g(30.0), g(90.0), g(10.0))
b = euler_to_matrix(g(50.0), g(90.0), g(30.0))
print(np.round(a, 4) + 0.0)
print(np.allclose(a, b))
print(np.round(np.degrees(matrix_to_euler(a)), 2) + 0.0)
[[ 0.9397  0.342   0.    ]
 [ 0.      0.     -1.    ]
 [-0.342   0.9397  0.    ]]
True
[20. 90.  0.]

The triples \((30°, 90°, 10°)\) and \((50°, 90°, 30°)\) give the same matrix, with \(\cos 20° \approx 0.9397\) and \(\sin 20° \approx 0.342\). The third column is \((0, -1, 0)\): the nose straight down.

Why the extraction becomes ambiguous

Seen from matrix_to_euler, the situation is this: the matrix contains the value of \(\psi - \varphi\), but there is no way of knowing how much belongs to each angle. Infinitely many triples \((\psi, 90°, \varphi)\) produce that matrix, and any of them is a correct answer. One has to be chosen, and the usual convention is to assign the whole rotation to the yaw and return roll 0. With \(\varphi = 0\), the first column of the matrix is \((\cos\psi, 0, -\sin\psi)\), which is where the formula of the special branch comes from: \(\psi = \text{arctan2}(-r_{20},\ r_{00})\). It works just as well for \(\theta = -90°\), where it returns \(\psi + \varphi\). That is why the code answered \((20°, 90°, 0°)\): it did not recover either of the two original triples, but a third, equivalent one.

The lock is not just an isolated point. Near 90° of pitch the denominators are almost zero and small variations in the orientation produce huge jumps in yaw and roll. The function above treats as locked any pitch within roughly a tenth of a degree of the vertical (the tolerance parameter), so as not to divide noise by noise.

It is worth making clear what gimbal lock is not: it is not a flaw of rotations (the ship can point straight down without any trouble, and its orientation matrix is perfectly valid), but of describing them with three chained angles. Every Euler convention suffers from it; the only thing that changes is the orientation at which it appears (always when the middle rotation aligns the first axis with the third). Choosing Y as the outer axis places it at "looking straight up or down", which is infrequent in many games. For a spaceship that can point anywhere, there is no escape: another representation is needed.

Other problems: non-uniqueness and interpolation

Non-uniqueness. Even far from the lock, a single orientation has several triples:

  • Adding 360° to any angle changes nothing: a yaw of 350° and one of \(-10°\) are the same.
  • The triple \((\psi + 180°,\ 180° - \theta,\ \varphi + 180°)\) produces the same matrix as \((\psi, \theta, \varphi)\): making a half turn, pitching "over the other side" and rolling half a turn leaves the ship just as it was.
print(np.allclose(euler_to_matrix(g(40.0), g(25.0), g(10.0)),
                  euler_to_matrix(g(220.0), g(155.0), g(190.0))))
True

Restricting the pitch to \([-90°, 90°]\), as matrix_to_euler does, removes this second duplication. But the consequence remains: orientations cannot be compared by comparing angles, and the triple extracted from a matrix may not be the one that was used to create it.

Component-by-component interpolation. To turn smoothly from one orientation to another, the first thing that occurs to anyone is to interpolate each angle separately. The result is usually a strange trajectory. Example: the ship points almost straight up, with a pitch of \(-80°\), and we want to go from yaw 0° to yaw 180°. The two noses are only 20° apart (10° on either side of the vertical): the natural thing would be to tilt 20°, passing through the vertical. Let's see what interpolating the angles does:

start_nose = euler_to_matrix(g(0.0), g(-80.0), 0.0)[:, 2]
end_nose = euler_to_matrix(g(180.0), g(-80.0), 0.0)[:, 2]
print(round(np.degrees(angle_between(start_nose, end_nose)), 2))

traveled, previous = 0.0, start_nose
for t in np.linspace(0.0, 1.0, 1001)[1:]:
    current = euler_to_matrix(g(180.0 * t), g(-80.0), 0.0)[:, 2]    # interpolated yaw
    traveled += angle_between(previous, current)
    previous = current
print(round(np.degrees(traveled), 2))
print(np.round(euler_to_matrix(g(90.0), g(-80.0), 0.0)[:, 2], 4))  # halfway there
20.0
31.26
[0.1736 0.9848 0.    ]

The nose travels 31.26° instead of 20°: rather than passing through the vertical, it goes around it, tracing half a circle, while the ship makes a half turn on its own axis. The closer to the lock, the worse it gets. And there is another classic trap: interpolating the yaw from 170° to \(-170°\) sweeps 340° through 0°, when the two orientations are 20° apart. The correct interpolation of orientations is the subject of the last lesson of the module.

When Euler angles are the right choice

None of the above means they should be banished. They have virtues that no other representation matches:

Use Why they work well
Interface and editing Three readable numbers that a person can type and understand: "yaw 90°"
First-person camera, turrets The mouse controls yaw and pitch; the roll is always 0 and the pitch is limited, for example, to \(\pm 89°\), so the lock is never reached
Constraints Limiting one particular angle is trivial: "the lighthouse lamp only rotates in yaw", "this hinge opens between 0° and 90°"
Rotations of more than one turn A yaw of 720° represents two full turns; a matrix cannot tell 720° from 0°
Storage Three numbers, with no constraints to maintain

The usual practice in engines is a division of roles: Euler at the boundary with people (the editor, configuration files, player input) and another representation on the inside for composing and interpolating. In mini3d we will do the same: euler_to_matrix and matrix_to_euler will be the way in and the way out.

Common Mistakes and Tips

  • Giving three angles without stating the convention. Always state the order of the axes, whether the rotations are about the object's own axes or fixed axes, the positive direction and the unit. In mini3d: \(R_y R_x R_z\), radians, parameters (yaw, pitch, roll).
  • Confusing the order of application with the order of writing. In \(R_y R_x R_z\), about world axes the roll is applied first; about the object's own axes, the yaw comes first. They are the same matrix.
  • Forgetting the sign of the pitch. With the nose along \(+Z\), positive pitch is nose down. If your ship climbs when it should dive, this is why.
  • Adding Euler triples to compose rotations. \((\psi_1 + \psi_2,\ \theta_1 + \theta_2,\ \varphi_1 + \varphi_2)\) is not the composition of the two rotations (unless both are rotations about the same axis). To compose, convert to matrices and multiply.
  • Using arccos or arctan instead of arctan2. Quadrants are lost. And protect arcsin with np.clip: because of rounding the argument may be 1.0000000001.
  • Expecting matrix_to_euler(euler_to_matrix(...)) to return the original angles. It returns an equivalent triple, with the pitch in \([-90°, 90°]\), which may be different.
  • Accumulating rotations in Euler angles frame after frame on objects that can be oriented freely. Sooner or later they will pass near the lock. Accumulate in a matrix (or, better, in a quaternion, as we will see).
  • Tip. To check a convention, try angles of 90° one at a time and watch where the nose and the roof go, as we did in this lesson.

Exercises

Exercise 1. The ship starts from its factory orientation and receives the command (yaw, pitch, roll) = (90°, 0°, 90°). a) Compute the orientation matrix by hand. b) Where do the nose and the roof point? c) The antenna is at the local point \((1, 2, 0)\): what vector is it relative to the center of the ship, in world axes? d) Describe the maneuver with rotations about the world axes.

Exercise 2. In "Dot Product and Cross Product" we used orthonormal_basis to build the orientation with which the ship points at beacon Alpha, whose third column (the nose) is \((2/3,\ 2/3,\ -1/3)\). Without using the computer, obtain its yaw and its pitch. What is the roll, and why? Check the result with matrix_to_euler.

Exercise 3. The ship points straight up (a pitch of \(-90°\)). a) Substitute \(\theta = -90°\) into the general matrix and show that it depends only on \(\psi + \varphi\). b) Check with code that \((30°, -90°, 10°)\) and \((10°, -90°, 30°)\) give the same matrix. c) Which triple does matrix_to_euler return?

Solutions

Solution 1.

a) With no pitch, \(R = R_y(90°),R_z(90°)\):

\[ R = \begin{pmatrix} 0 & 0 & 1 \ 0 & 1 & 0 \ -1 & 0 & 0 \end{pmatrix} \begin{pmatrix} 0 & -1 & 0 \ 1 & 0 & 0 \ 0 & 0 & 1 \end{pmatrix} = \begin{pmatrix} 0 & 0 & 1 \ 1 & 0 & 0 \ 0 & 1 & 0 \end{pmatrix} \]

b) The nose is the third column, \((1, 0, 0)\): it points toward \(+X\). The roof is the second, \((0, 0, 1)\): it points toward \(+Z\). The ship flies "on edge", with the local \(+X\) wing (first column, \((0, 1, 0)\)) pointing up.

c) \(R,(1, 2, 0)^T = (0, 1, 2)\): one unit of the first column plus two of the second.

d) About the world axes it is read from right to left: first a 90° roll about the world's Z axis (which in the factory orientation coincides with the longitudinal axis) and then a 90° yaw about the world's Y axis. About the ship's own axes, the other way around: first the yaw and then the roll about the longitudinal axis, which by then points toward \(+X\). Both descriptions lead to the same matrix.

print(np.round(euler_to_matrix(g(90.0), 0.0, g(90.0)), 6) + 0.0)
print(np.round(euler_to_matrix(g(90.0), 0.0, g(90.0)) @ np.array([1.0, 2.0, 0.0]), 6) + 0.0)
[[0. 0. 1.]
 [1. 0. 0.]
 [0. 1. 0.]]
[0. 1. 2.]

Solution 2.

The nose is \((\sin\psi\cos\theta,\ -\sin\theta,\ \cos\psi\cos\theta) = (2/3,\ 2/3,\ -1/3)\).

  • Pitch: \(-\sin\theta = 2/3\), so \(\theta = \arcsin(-2/3) \approx -41.81°\). Negative: nose up, as befits a beacon that is 4 m higher than the ship.
  • Yaw: \(\psi = \text{arctan2}(2/3,\ -1/3)\). The sine is positive and the cosine negative: second quadrant. \(\psi = 180° - \arctan 2 \approx 116.57°\).
  • Roll: 0°. orthonormal_basis chooses the "right" axis perpendicular to the vertical, so the wings stay level; in the matrix, \(r_{10} = 0\) and arctan2(0, positive) is 0.
alpha_orientation = orthonormal_basis([4.0, 4.0, -2.0])
print(np.round(np.degrees(matrix_to_euler(alpha_orientation)), 2) + 0.0)
[116.57 -41.81   0.  ]

Solution 3.

a) With \(s_\theta = -1\) and \(c_\theta = 0\):

\[ R = \begin{pmatrix} c_\psi c_\varphi - s_\psi s_\varphi & -c_\psi s_\varphi - s_\psi c_\varphi & 0 \\ 0 & 0 & 1 \\ -s_\psi c_\varphi - c_\psi s_\varphi & s_\psi s_\varphi - c_\psi c_\varphi & 0 \end{pmatrix} = \begin{pmatrix} \cos(\psi + \varphi) & -\sin(\psi + \varphi) & 0 \\ 0 & 0 & 1 \\ -\sin(\psi + \varphi) & -\cos(\psi + \varphi) & 0 \end{pmatrix} \]

Only the sum appears. The third column is \((0, 1, 0)\): the nose pointing up.

b) and c) Both triples add up to 40°; the function assigns the whole sum to the yaw:

c = euler_to_matrix(g(30.0), g(-90.0), g(10.0))
d = euler_to_matrix(g(10.0), g(-90.0), g(30.0))
print(np.allclose(c, d))
print(np.round(np.degrees(matrix_to_euler(c)), 2) + 0.0)
True
[ 40. -90.   0.]

Check of the special branch: \(\text{arctan2}(-r_{20},\ r_{00}) = \text{arctan2}(\sin 40°,\ \cos 40°) = 40°\).

Conclusion

An orientation has three degrees of freedom, and Euler angles capture them with three chained basic rotations: yaw, pitch and roll. They are three numbers that anyone understands, but they only mean something together with their convention; that of mini3d is \(R = R_y(\text{yaw}),R_x(\text{pitch}),R_z(\text{roll})\), which about the ship's own axes reads "yaw, pitch, roll" and about the world's, the other way around. We know how to convert in both directions (euler_to_matrix, matrix_to_euler) and we know the price: with the pitch at \(\pm 90°\) two of the axes line up and a degree of freedom is lost—gimbal lock—the triples are not unique and angle-by-angle interpolation traces strange paths. That is why we will reserve them for the interface with people. The root of all these ills is breaking a rotation into three pieces; in the next lesson, "Axis-Angle Representation and Rodrigues' Formula", we will do the opposite: describe any rotation as a single turn about a well-chosen axis.

© Copyright 2026. All rights reserved