The DirectXMath library is a set of common math types and functions used in DirectX development. It is designed to be fast, flexible, and easy to use, leveraging SIMD instructions for performance critical operations.
This API provides essential mathematical types like vectors (XMVECTOR), matrices (XMMATRIX), and quaternions (XMVECTOR with specific packing), along with functions for common operations such as:
XMVECTOR and XMMATRIX is crucial for performance.A 4-component vector. Can represent points, directions, colors, or packed matrix rows.
Typically uses 128-bit SIMD registers.
A 4x4 matrix, typically represented as an array of four XMVECTOR objects, each representing a row.
Used for transformations.
Structs for 2D, 3D, and 4D floating-point vectors with standard C++ alignment.
Useful for data structures not requiring SIMD optimization.
A 4x4 matrix struct using standard C++ alignment.
The library is organized into functional categories. Here are a few examples:
XMVectorAdd(): Adds two vectors.XMVectorSubtract(): Subtracts one vector from another.XMVectorDot(): Computes the dot product of two vectors.XMVector3Cross(): Computes the 3D cross product.XMVector3Normalize(): Normalizes a 3D vector.XMVectorSet(): Creates an XMVECTOR from individual components.XMVectorGetX(), XMVectorGetY(), etc.: Extracts components from an XMVECTOR.XMMatrixIdentity(): Creates an identity matrix.XMMatrixTranslation(): Creates a translation matrix.XMMatrixRotationX(), XMMatrixRotationY(), XMMatrixRotationZ(): Creates rotation matrices around the axes.XMMatrixScaling(): Creates a scaling matrix.XMMatrixPerspectiveFovLH(): Creates a left-handed perspective projection matrix.XMMatrixLookAtLH(): Creates a left-handed view matrix.XMMatrixMultiply(): Multiplies two matrices.XMQuaternionRotationMatrix(): Creates a quaternion from a rotation matrix.XMQuaternionMultiply(): Multiplies two quaternions.XMQuaternionSlerp(): Performs spherical linear interpolation between two quaternions.Here's a simple example demonstrating how to create a translation matrix and apply it to a vector:
#include <DirectXMath.h>
#include <iostream>
using namespace DirectX;
int main() {
// Define a translation vector
XMVECTOR translation = XMVectorSet(10.0f, 5.0f, -2.0f, 0.0f);
// Create a translation matrix
XMMATRIX translationMatrix = XMMatrixTranslationFromVector(translation);
// Define a point (as a vector)
XMVECTOR point = XMVectorSet(1.0f, 2.0f, 3.0f, 1.0f); // W=1 for a point
// Apply the translation matrix to the point
XMVECTOR transformedPoint = XMVector4Transform(point, translationMatrix);
// Output the results (requires helper functions to print XMVECTOR)
std::cout << "Original Point: (" << XMVectorGetX(point) << ", " << XMVectorGetY(point) << ", " << XMVectorGetZ(point) << ")" << std::endl;
std::cout << "Translated Point: (" << XMVectorGetX(transformedPoint) << ", " << XMVectorGetY(transformedPoint) << ", " << XMVectorGetZ(transformedPoint) << ")" << std::endl;
return 0;
}