What is a Vector?
In DirectXMath, a vector represents a 2‑D, 3‑D, or 4‑D floating‑point value that can be used for geometry, physics, and shading calculations. The primary types are XMVECTOR
(SIMD‑optimized) and XMFLOAT2/3/4
(plain storage).
XMVECTOR
XMVECTOR
is a 128‑bit type that holds four float
components (x, y, z, w). It is compatible with SSE/NEON instructions for high‑performance calculations.
Creating an XMVECTOR
// Using XMVectorSet
XMVECTOR v = XMVectorSet(1.0f, 2.0f, 3.0f, 1.0f);
// From an XMFLOAT3
XMFLOAT3 pos = {4.0f,5.0f,6.0f};
XMVECTOR v2 = XMLoadFloat3(&pos);
// Zero vector
XMVECTOR zero = XMVectorZero();
Common Operations
Operation | Function | Example |
---|---|---|
Add | XMVectorAdd | XMVectorAdd(v1, v2) |
Subtract | XMVectorSubtract | XMVectorSubtract(v1, v2) |
Multiply (component‑wise) | XMVectorMultiply | XMVectorMultiply(v1, v2) |
Dot Product | XMVector3Dot | XMVector3Dot(v1, v2) |
Cross Product | XMVector3Cross | XMVector3Cross(v1, v2) |
Length | XMVector3Length | XMVector3Length(v) |
Normalize | XMVector3Normalize | XMVector3Normalize(v) |
XMFLOAT2, XMFLOAT3, XMFLOAT4
These structs provide simple storage for vector components and are useful when you need to serialize or interface with APIs that expect plain data.
Definition
struct XMFLOAT2 { float x; float y; };
struct XMFLOAT3 { float x; float y; float z; };
struct XMFLOAT4 { float x; float y; float z; float w; };
Loading and Storing
// Load into XMVECTOR
XMFLOAT3 point = {1.0f,2.0f,3.0f};
XMVECTOR v = XMLoadFloat3(&point);
// Store from XMVECTOR
XMFLOAT3 result;
XMStoreFloat3(&result, v);
Practical Example – Transforming a Position
// Assume we have a world matrix (XMMATRIX) and a position (XMFLOAT3)
XMFLOAT3 pos = {10.0f, 5.0f, -3.0f};
XMMATRIX world = XMMatrixRotationY(XMConvertToRadians(45.0f)) *
XMMatrixTranslation(0.0f, 2.0f, 0.0f);
// Load, transform, store
XMVECTOR vPos = XMLoadFloat3(&pos);
XMVECTOR vWorldPos = XMVector3TransformCoord(vPos, world);
XMFLOAT3 transformed;
XMStoreFloat3(&transformed, vWorldPos);
// transformed now holds the new coordinates