Math Types

Microsoft::Xna::Framework math library — vectors, matrices, quaternions, colors, bounding volumes, curves

Implementation status: All math types listed on this page are fully implemented with 100% test coverage. Unless noted otherwise, every member lives in the Microsoft::Xna::Framework namespace.

Overview

CNA provides the complete XNA 4.0 math library as a header-only C++23 implementation. Types are value types (structs) and support the same member functions, static helpers, and operator overloads as their XNA counterparts. All floating-point arithmetic matches XNA semantics: row-major matrices, right-handed coordinate system for CreateLookAt and view-space conventions, and clockwise winding by default.

The library is organized into three groups: core types (vectors, matrix, quaternion, color, and helpers), bounding types (collision and visibility volumes), and curve types (animation splines). A separate PackedVector sub-namespace in Microsoft::Xna::Framework::Graphics::PackedVector provides GPU-format value types documented separately.

Core types

Vector2

A 2D vector with float components X and Y. Supports arithmetic with other vectors and scalars, and provides the most common geometric operations.

MemberDescription
X, YFloat components
operator + - * /Component-wise vector arithmetic and scalar multiply/divide
Dot(a, b)Dot product of two vectors
Cross(a, b)Scalar cross product (the Z component of the 3D cross product)
Length()Euclidean length
LengthSquared()Squared length (avoids square root)
Normalize(v)Returns a unit-length copy; instance Normalize() normalizes in place
Distance(a, b)Distance between two points
DistanceSquared(a, b)Squared distance
Lerp(a, b, t)Linear interpolation
Reflect(v, normal)Reflects a vector about a surface normal
Transform(v, matrix)Transforms by a Matrix (position transform)
TransformNormal(v, matrix)Transforms by a matrix, ignoring translation
Min(a, b) / Max(a, b)Component-wise minimum / maximum
Clamp(v, min, max)Component-wise clamp
Negate(v)Returns the additive inverse
ZeroStatic: (0, 0)
OneStatic: (1, 1)
UnitXStatic: (1, 0)
UnitYStatic: (0, 1)

Vector3

A 3D vector with float components X, Y, Z. Used for positions, directions, normals, and colors throughout the 3D API.

MemberDescription
X, Y, ZFloat components
operator + - * /Component-wise arithmetic and scalar operations
Dot(a, b)Dot product
Cross(a, b)3D cross product, returning a perpendicular Vector3
Length() / LengthSquared()Euclidean length and squared length
Normalize(v)Unit-length copy or in-place normalization
Distance(a, b) / DistanceSquared(a, b)Point-to-point distance
Lerp(a, b, t)Linear interpolation
SmoothStep(a, b, t)Smooth Hermite interpolation (cubic)
Reflect(v, normal)Reflects about a surface normal
Transform(v, matrix)Transforms by a Matrix (applies translation)
Transform(v, quaternion)Rotates by a Quaternion
TransformNormal(v, matrix)Transforms ignoring translation (for normals)
Min / Max / ClampComponent-wise operations
Hermite(v1, t1, v2, t2, a)Hermite spline interpolation
Barycentric(v1, v2, v3, b2, b3)Point in barycentric coordinates
CatmullRom(v1, v2, v3, v4, a)Catmull-Rom spline interpolation
Zero / OneStatic: (0,0,0) and (1,1,1)
UnitX / UnitY / UnitZAxis unit vectors
ForwardStatic: (0, 0, −1)
BackwardStatic: (0, 0, +1)
UpStatic: (0, +1, 0)
DownStatic: (0, −1, 0)
LeftStatic: (−1, 0, 0)
RightStatic: (+1, 0, 0)

Vector4

A 4D vector with float components X, Y, Z, W. Used for homogeneous coordinates, RGBA colors, and as shader parameter types.

MemberDescription
X, Y, Z, WFloat components
operator + - * /Component-wise arithmetic and scalar operations
Dot(a, b)4D dot product
Length() / LengthSquared()4D Euclidean length
Normalize(v)Unit-length copy or in-place normalization
Distance(a, b) / DistanceSquared(a, b)4D distance
Lerp(a, b, t)Linear interpolation
SmoothStep(a, b, t)Smooth Hermite interpolation
Transform(v, matrix)Transforms by a 4×4 Matrix
Min / Max / ClampComponent-wise operations
Hermite / Barycentric / CatmullRomSpline and interpolation helpers
Zero / OneStatic: (0,0,0,0) and (1,1,1,1)
UnitX / UnitY / UnitZ / UnitWAxis unit vectors

Matrix

A 4×4 row-major floating-point matrix. Elements are named M11–M44 (row, column). Used for world/view/projection transforms and general linear algebra. Multiplication is left-to-right (row-vector convention), matching XNA 4.0 exactly.

MemberDescription
M11M44Individual float elements (row-major)
operator *Matrix multiplication
operator + -Component-wise addition / subtraction
operator * (float)Scalar multiply
Transpose(m)Returns the transpose
Invert(m)Returns the inverse; sets the determinant output parameter
Determinant()Returns the scalar determinant
Decompose(scale, rotation, translation)Decomposes into TRS components; returns false if not decomposable
CreateTranslation(x, y, z)Translation matrix
CreateScale(x, y, z)Non-uniform scale matrix
CreateRotationX/Y/Z(radians)Axis-aligned rotation matrices
CreateFromAxisAngle(axis, angle)Arbitrary axis rotation
CreateFromQuaternion(q)Rotation matrix from a Quaternion
CreateFromYawPitchRoll(yaw, pitch, roll)Euler-angle rotation matrix
CreateLookAt(eye, target, up)View matrix (right-handed)
CreatePerspectiveFOV(fov, aspect, near, far)Perspective projection matrix
CreatePerspective(w, h, near, far)Perspective from width and height
CreatePerspectiveOffCenter(...)Off-center perspective frustum
CreateOrthographic(w, h, near, far)Orthographic projection matrix
CreateOrthographicOffCenter(...)Off-center orthographic projection
CreateBillboard(...)Camera-facing billboard matrix
CreateConstrainedBillboard(...)Axis-constrained billboard
CreateShadow(light, plane)Planar shadow projection
CreateReflection(plane)Reflection matrix about a plane
CreateWorld(pos, forward, up)Full world matrix from TBN vectors
Lerp(a, b, t)Component-wise linear interpolation
IdentityStatic: the 4×4 identity matrix

Quaternion

A unit quaternion representing a 3D rotation, stored as X, Y, Z (imaginary) and W (real) float components. Quaternions avoid gimbal lock and are the preferred rotation representation for animation and interpolation.

MemberDescription
X, Y, Z, WFloat components
operator * (Quaternion)Quaternion concatenation (rotation composition)
operator + - *Component-wise arithmetic
Length() / LengthSquared()Quaternion magnitude
Normalize(q)Returns or applies unit normalization
Conjugate(q)Conjugate (negates X, Y, Z; equivalent to inverse for unit quaternions)
Inverse(q)Multiplicative inverse
Dot(a, b)4D dot product
Concatenate(a, b)Applies rotation a then b
Slerp(a, b, t)Spherical linear interpolation
Lerp(a, b, t)Normalized linear interpolation (faster, less accurate than Slerp)
CreateFromAxisAngle(axis, angle)Constructs from axis and angle in radians
CreateFromYawPitchRoll(yaw, pitch, roll)Constructs from Euler angles
CreateFromRotationMatrix(m)Extracts rotation from a Matrix
IdentityStatic: (0, 0, 0, 1) — no rotation

Color

An RGBA color stored as four byte (uint8) components, packed into a 32-bit integer. Over 140 named static colors are provided as static fields, matching the XNA Color class exactly (including CornflowerBlue, the classic XNA clear color).

MemberDescription
R, G, B, AByte (0–255) RGBA components
PackedValueThe packed 32-bit RGBA value (ABGR in memory on little-endian)
ToVector4()Converts to a Vector4 in [0, 1] range
ToVector3()Converts RGB to a Vector3 in [0, 1] range
Lerp(a, b, t)Component-wise linear interpolation between two colors
Multiply(c, scale)Scales all channels by a float in [0, 1]
operator == !=Equality comparison by packed value
CornflowerBlueStatic: #6495ED — the iconic XNA clear color
Red, Green, BlueStatic primary colors
White, Black, TransparentStatic utility colors
140+ named staticsFull set matching XNA: AliceBlue through YellowGreen

Rectangle

An axis-aligned integer rectangle defined by its top-left corner (X, Y) and its dimensions (Width, Height). Used for screen regions, texture source rectangles, and 2D collision detection.

MemberDescription
X, YInteger coordinates of the top-left corner
Width, HeightInteger dimensions
Left, RightComputed X and X+Width
Top, BottomComputed Y and Y+Height
CenterPoint at the geometric center
LocationTop-left corner as a Point
SizeDimensions as a Point
IsEmptyTrue if width or height is zero
Contains(x, y)Point-in-rectangle test (integer and float overloads)
Contains(Point)Point containment
Contains(Rectangle)Rectangle fully contained
Intersects(Rectangle)Overlap test
Intersect(a, b)Returns the overlapping rectangle
Union(a, b)Returns the bounding rectangle of both inputs
Inflate(h, v)Expands (or contracts) by horizontal and vertical amounts
Offset(x, y)Translates the rectangle by (x, y)
EmptyStatic: Rectangle(0, 0, 0, 0)

Point

A pair of integer values X and Y. Used for screen coordinates, texture offsets, and as the return type of several Rectangle properties.

MemberDescription
X, YInteger components
operator + - * /Component-wise arithmetic
operator == !=Equality comparison
ToVector2()Converts to a Vector2
ZeroStatic: (0, 0)

MathHelper

A static utility class with common scalar math functions and constants. Mirrors Microsoft.Xna.Framework.MathHelper exactly.

MemberDescription
PiStatic constant π (3.14159…)
TwoPiStatic constant 2π
PiOver2Static constant π/2
PiOver4Static constant π/4
EStatic constant e (2.71828…)
Clamp(v, min, max)Clamps a float to [min, max]
Lerp(a, b, t)Linear interpolation: a + (b−a) * t
SmoothStep(a, b, t)Smooth cubic interpolation using 3t²−2t³
ToDegrees(radians)Converts radians to degrees
ToRadians(degrees)Converts degrees to radians
WrapAngle(angle)Wraps an angle to (−π, π]
Distance(a, b)Absolute difference between two floats
Min(a, b) / Max(a, b)Scalar min and max
IsPowerOfTwo(n)Returns true if n is a power of two
Log2(n)Integer base-2 logarithm

Bounding types

Bounding volume types live in Microsoft::Xna::Framework alongside the core math types. They are used for frustum culling, collision detection, and ray casting. Contains returns a ContainmentType enum value (Disjoint, Contains, or Intersects). Intersects returns bool except for ray tests which return std::optional<float> (the hit distance along the ray).

BoundingBox

An axis-aligned bounding box (AABB) defined by its minimum and maximum corner points as Vector3 values.

MemberDescription
Min, MaxVector3 corners of the AABB
Contains(Vector3)Point containment test
Contains(BoundingSphere)Sphere containment test
Contains(BoundingBox)AABB containment test
Intersects(BoundingBox)AABB overlap test
Intersects(BoundingSphere)Sphere overlap test
Intersects(BoundingFrustum)Frustum overlap test
Intersects(Ray)Ray cast; returns optional hit distance
GetCorners()Returns the 8 corner points as Vector3[8]
CreateFromPoints(points)Static: AABB enclosing a span of points
CreateFromSphere(sphere)Static: Smallest AABB enclosing a sphere
CreateMerged(a, b)Static: AABB enclosing both input AABBs

BoundingSphere

A bounding sphere defined by a center Vector3 and a float radius.

MemberDescription
CenterVector3 center of the sphere
RadiusFloat radius
Contains(Vector3)Point containment test
Contains(BoundingBox)AABB containment test
Contains(BoundingSphere)Sphere containment test
Contains(BoundingFrustum)Frustum containment test
Intersects(BoundingBox)AABB overlap test
Intersects(BoundingSphere)Sphere overlap test
Intersects(BoundingFrustum)Frustum overlap test
Intersects(Ray)Ray cast; returns optional hit distance
Intersects(Plane)Plane classification (front, back, or intersecting)
Transform(matrix)Transforms center and scales radius
CreateFromBoundingBox(box)Static: Sphere enclosing an AABB
CreateFromPoints(points)Static: Minimum enclosing sphere for a span of points
CreateMerged(a, b)Static: Sphere enclosing both input spheres

BoundingFrustum

A view frustum defined by a combined view-projection matrix. Computes the six clip planes automatically from the matrix and exposes them as Plane objects. Typically used for frustum culling.

MemberDescription
MatrixThe combined view-projection Matrix; setting this recomputes all planes
Near, FarNear and far clip planes as Plane
Left, RightLeft and right clip planes
Top, BottomTop and bottom clip planes
GetCorners()Returns the 8 frustum corner vertices as Vector3[8]
Contains(Vector3)Point containment test
Contains(BoundingBox)AABB containment test
Contains(BoundingSphere)Sphere containment test
Contains(BoundingFrustum)Frustum-in-frustum test
Intersects(BoundingBox)AABB overlap test
Intersects(BoundingSphere)Sphere overlap test
Intersects(BoundingFrustum)Frustum overlap test
Intersects(Ray)Ray cast; returns optional hit distance

Plane

A half-space plane defined by a Normal (Vector3) and a scalar distance D, satisfying the equation Normal·X + D = 0.

MemberDescription
NormalVector3 unit normal of the plane
DFloat distance from the origin along the normal
Dot(plane, v4)Dot product with a Vector4
DotCoordinate(plane, v3)Signed distance from a point to the plane
DotNormal(plane, v3)Dot product of the plane normal with a Vector3
Normalize(plane)Returns a unit-normal copy of the plane
Transform(plane, matrix)Transforms the plane by a matrix
Transform(plane, quaternion)Rotates the plane by a quaternion
CreateFromVertices(a, b, c)Static: Constructs a plane from three points
Intersects(BoundingBox)Box classification
Intersects(BoundingSphere)Sphere classification

Ray

A ray defined by an origin (Position) and a unit direction (Direction), both Vector3. The primary use is ray casting against bounding volumes and planes.

MemberDescription
PositionVector3 ray origin
DirectionVector3 unit direction
Intersects(BoundingBox)Returns std::optional<float> hit distance, or empty if no intersection
Intersects(BoundingSphere)Returns optional hit distance
Intersects(BoundingFrustum)Returns optional hit distance
Intersects(Plane)Returns optional hit distance along the ray to the plane
operator == !=Equality comparison

Curve types

The curve types provide 1D floating-point animation splines. They are used by the content pipeline and by AnimationPlayer implementations to drive scalar properties over time.

Curve

A piecewise Hermite spline that maps a float position (typically time) to a float value. The spline is defined by a sorted collection of CurveKey control points and loop types that govern behaviour outside the key range.

MemberDescription
KeysCurveKeyCollection — the sorted set of control points
PreLoopCurveLoopType controlling extrapolation before the first key
PostLoopCurveLoopType controlling extrapolation after the last key
IsConstantTrue if the curve has fewer than two keys
Evaluate(position)Evaluates the spline at the given position and returns the interpolated float value
ComputeTangents(type)Recomputes all tangents using the specified CurveTangent type (Flat / Linear / Smooth)
Clone()Returns a deep copy

The CurveLoopType enum controls what happens outside the key range:

ValueBehaviour
ConstantClamps to the value of the nearest key (default)
CycleRepeats the curve from the start
CycleOffsetRepeats and offsets by the value difference between endpoints
OscillatePing-pongs back and forth (reverse on alternate cycles)
LinearExtrapolates linearly from the endpoint tangent

CurveKey

A single control point on a Curve. Stores the position, value, and in/out tangents that define the Hermite segment connecting adjacent keys.

MemberDescription
PositionThe x-axis value (typically time) of this key
ValueThe y-axis value (the output) at this key
TangentInThe incoming tangent (controls the slope arriving at this key)
TangentOutThe outgoing tangent (controls the slope leaving this key)
ContinuityCurveContinuity enum: Smooth (connected) or Step (discrete jump)
Clone()Returns a copy of this key

PackedVector types

The Microsoft::Xna::Framework::Graphics::PackedVector namespace provides 17 GPU-oriented packed value types such as HalfVector2, HalfVector4, NormalizedByte4, Rgba1010102, and others. These types implement the IPackedVector interface and are used as vertex element formats and texture pixel formats. They are fully implemented with the same 100% test coverage as the core math types.

A dedicated PackedVector reference page is planned. In the meantime, the namespace and all member names mirror XNA 4.0 exactly.

Code examples

Vector3 math — normalize and dot product

// Compute the angle between two directions using dot product
Vector3 toEnemy = enemy.Position - player.Position;
float distance  = toEnemy.Length();
Vector3 dir     = Vector3::Normalize(toEnemy);          // unit direction

Vector3 facing  = Vector3::Normalize(player.Forward);
float   cosAngle = Vector3::Dot(facing, dir);            // in [-1, 1]
float   angleDeg = MathHelper::ToDegrees(std::acos(cosAngle));

if (angleDeg < 45.0f)
    DrawAimingReticle();

Matrix camera setup — LookAt and PerspectiveFOV

// Build a standard view-projection matrix pair
Matrix view = Matrix::CreateLookAt(
    Vector3(0.0f, 5.0f, 10.0f),   // eye position
    Vector3::Zero,                  // look-at target
    Vector3::Up                     // world up
);

Matrix projection = Matrix::CreatePerspectiveFieldOfView(
    MathHelper::ToRadians(60.0f),   // vertical FOV
    graphicsDevice->Viewport().AspectRatio(),
    0.1f,   // near plane
    1000.0f // far plane
);

// Pass to a BasicEffect
effect->SetView(view);
effect->SetProjection(projection);

Quaternion rotation interpolation — Slerp

// Smoothly rotate an object from startRotation to endRotation over 2 seconds
Quaternion startRotation = Quaternion::CreateFromYawPitchRoll(0.0f, 0.0f, 0.0f);
Quaternion endRotation   = Quaternion::CreateFromAxisAngle(Vector3::Up,
                               MathHelper::ToRadians(180.0f));

float elapsed = 0.0f;
const float duration = 2.0f;

// Inside Update():
elapsed += gameTime.ElapsedSeconds();
float t = MathHelper::Clamp(elapsed / duration, 0.0f, 1.0f);
Quaternion current = Quaternion::Slerp(startRotation, endRotation, t);

Matrix world = Matrix::CreateFromQuaternion(current);
effect->SetWorld(world);

BoundingSphere intersection test

// Simple frustum-culling check before submitting a draw call
BoundingSphere sphere(mesh.Center, mesh.Radius);
BoundingFrustum frustum(camera.View * camera.Projection);

if (frustum.Contains(sphere) != ContainmentType::Disjoint)
{
    // Sphere is at least partially visible — draw it
    mesh.Draw(graphicsDevice, effect);
}

// Ray-cast from the cursor to pick an object
Ray pickRay = viewport.Unproject(cursorPos, projection, view, Matrix::Identity);
auto hitDistance = sphere.Intersects(pickRay);
if (hitDistance.has_value())
    SelectObject(object, hitDistance.value());

MathHelper.Lerp for smooth transitions

// Smoothly fade a value (e.g. music volume) toward a target each frame
float currentVolume = 0.0f;
float targetVolume  = 1.0f;
const float speed   = 2.0f;   // units per second

// Inside Update():
float dt = (float)gameTime.ElapsedSeconds();
currentVolume = MathHelper::Lerp(currentVolume, targetVolume,
                                  MathHelper::Clamp(speed * dt, 0.0f, 1.0f));
MediaPlayer::SetVolume(currentVolume);