Microsoft

Quaternions (DirectX)

Overview

Quaternions are a mathematical construct used to represent rotations in three‑dimensional space. In DirectX, they provide a compact and numerically stable way to interpolate orientations, avoid gimbal lock, and compose rotations efficiently.

Syntax

struct XMFLOAT4
{
    float x; // i component
    float y; // j component
    float z; // k component
    float w; // real component
};

typedef XMFLOAT4 XQuaternion;

The XQuaternion type is defined as an XMFLOAT4 where (x, y, z) represent the vector part and w is the scalar part.

Common Functions

FunctionPurpose
XMQuaternionRotationRollPitchYawCreates a quaternion from Euler angles (pitch, yaw, roll).
XMQuaternionMultiplyCombines two rotations.
XMQuaternionConjugateReturns the inverse rotation for unit quaternions.
XMQuaternionSlerpSpherical linear interpolation between two quaternions.
XMQuaternionToRollPitchYawExtracts Euler angles from a quaternion.

Example: Rotating a Cube

#include <DirectXMath.h>
using namespace DirectX;

XQuaternion q = XMQuaternionRotationRollPitchYaw(pitch, yaw, roll);
XMMATRIX rotMatrix = XMMatrixRotationQuaternion(q);
XMMATRIX world = rotMatrix * XMMatrixTranslation(pos.x, pos.y, pos.z);

This snippet demonstrates creating a quaternion from Euler angles, converting it to a rotation matrix, and applying a translation to form a world matrix for rendering a 3‑D cube.

Quaternion Calculator

Remarks

See Also