Overview / Math, game & observability

math

Scalars, vectors, matrices and geometric primitives, with SIMD concentrated in batch functions that transform, normalize and multiply thousands of elements at once.

Always compiled: part of the core build.Include #include <ethereal/cpp/math/math_inc.hpp>C layer

math_inc.hpp

#include <ethereal/cpp/math/math_inc.hpp>

batch.hpp

#include <ethereal/cpp/math/batch.hpp>

Batch math of the Math module: where the SIMD lives.

The single element types stay plain floats. 'CVector3D' and 'CMatrix4x4' are 'constexpr' and trivially copyable. A float4 wrapped in a '__m128' looks fast and is usually slower, since each component access pays a load, a shuffle and an extract. The gain is in transforming ten thousand points at once, and that is what these functions are for.

The fast path is the structure of arrays: x, y and z in three separate arrays ('SSoaVector3', the '...Soa' functions), with no shuffle at all. The versions over interleaved 'CVector3D' also gain, but pay the deinterleave in every block. For the dot and cross products, with few operations per point, that keeps the gain at 2x to 2.7x, and the '...Soa' variants give 4x to 5x (the numbers are in the README).

The dispatch is resolved once. The first call picks the path (scalar, SSE2, SSE4.1 or AVX2) from 'Cpu::ActiveSimdLevel' and stores a table of pointers. Later calls are one load and one indirect jump, with no question to the processor. 'BatchPath' tells which path was taken. The AVX-512 path exists and gives the same bits, but it is never picked on its own: its gain was never measured on a real machine (see the README). AVX without AVX2, FMA and NEON have no path of their own (ARM runs the scalar path).

Determinism: every path gives the same bits. Each batch operation is written once over a "lane" type with the same IEEE operations (add, subtract, multiply, divide and square root, correctly rounded), without FMA, in the exact order of the existing scalar code. The scalar, SSE2, SSE4.1, AVX2 and AVX-512 paths give the same bits, which are also the bits of 'CVector3D::Normalized', 'CMatrix4x4::TransformPoint' and 'CMatrix4x4::operator*'. The suite checks this bit by bit over millions of inputs. Limits of the promise: a NaN may come out with another payload (the suite only requires NaN on both sides), and the rounding mode and FTZ/DAZ are those of the process (on x86-64 the scalar code also runs on SSE, so the paths change together).

No function allocates. Every result goes to an array given by the caller. Each function processes the smallest of the sizes it receives. Output equal to input (in place) is allowed, partial overlap is not.

Conventions of 'CMatrix4x4' (the ones the type always had):

  • Stored by columns: 'm[ col * 4 + row ]'. The translation is in m[12..14].
  • Column vectors on the right: 'M v'. 'A B' applies B first, then A.
  • 'Perspective' and 'LookAt' are right handed, with the camera looking down -Z and the depth in [-1, 1] after the division (the OpenGL convention). A test asserts each of these ('MathConventions').
struct

SSoaVector3

Ethereal::Math#
C++
struct   SSoaVector3
{
    /// @brief    Array of the x components.
    ETL_FLOAT *        x = nullptr;

    /// @brief    Array of the y components.
    ETL_FLOAT *        y = nullptr;

    /// @brief    Array of the z components.
    ETL_FLOAT *        z = nullptr;
};

Points as a structure of arrays: x, y and z in three separate arrays.

Owns nothing. It points to memory of the caller, and the size is given apart, in each call. This is the layout that really vectorizes.

struct

SSoaConstVector3

Ethereal::Math#
C++
struct   SSoaConstVector3
{
    /// @brief    Array of the x components.
    const ETL_FLOAT *    x = nullptr;

    /// @brief    Array of the y components.
    const ETL_FLOAT *    y = nullptr;

    /// @brief    Array of the z components.
    const ETL_FLOAT *    z = nullptr;

    /// @brief    Empty view.
    ETL_CEXPR SSoaConstVector3() ETL_NOEXCEPT = default;

    /// @brief    View over three arrays.
    ETL_CEXPR SSoaConstVector3( const ETL_FLOAT * pX, const ETL_FLOAT * pY, const ETL_FLOAT * pZ ) ETL_NOEXCEPT : x( pX ), y( pY ), z( pZ ) {}

    /// @brief    Implicit conversion from the mutable structure.
    ETL_CEXPR SSoaConstVector3( const SSoaVector3 & S ) ETL_NOEXCEPT : x( S.x ), y( S.y ), z( S.z ) {}        /// NOLINT: implicit on purpose.
};

Read only view of a SSoaVector3.

function

TransformPoints

Ethereal::Math#
void TransformPoints( const Matrix::CMatrix4x4 & M, std::span< const Vector::CVector3D > In, std::span< Vector::CVector3D > Out ) noexcept;

'Out[i] = M.TransformPoint( In[i] )': w = 1, then division by the resulting w.

Same bits as 'CMatrix4x4::TransformPoint' wherever that one is defined. The difference is a w close to zero. 'TransformPoint' asserts |w| > EPSILON and stops the program. The batch does not stop in the middle of ten thousand points, and gives what the IEEE division gives (infinity or NaN for that point).

M
Transform matrix.
In
Input points.
Out
Output points. May be the same array as In.
function

TransformDirections

Ethereal::Math#
void TransformDirections( const Matrix::CMatrix4x4 & M, std::span< const Vector::CVector3D > In, std::span< Vector::CVector3D > Out ) noexcept;

'Out[i] = M.TransformDirection( In[i] )': w = 0, no translation.

M
Transform matrix.
In
Input directions.
Out
Output directions. May be the same array as In.
function

TransformPointsSoa

Ethereal::Math#
void TransformPointsSoa( const Matrix::CMatrix4x4 & M, SSoaConstVector3 In, SSoaVector3 Out, std::size_t uCount ) noexcept;

TransformPoints over a structure of arrays. The fastest path.

M
Transform matrix.
In
Input points.
Out
Output points.
uCount
Number of points. Each of the six arrays has at least this many.
function

TransformPointsSoaAligned32

Ethereal::Math#
void TransformPointsSoaAligned32( const Matrix::CMatrix4x4 & M, SSoaConstVector3 In, SSoaVector3 Out, std::size_t uCount ) noexcept;

TransformPointsSoa with aligned loads.

Precondition: the six pointers are aligned to 32 bytes. A fatal assertion ('ETL_SDK_ASSERT') checks it once on entry. With 'ETL_DISABLE_ASSERTS', breaking it is undefined behavior (the processor refuses the load). The requirement is in the name so it is never a hidden branch inside the loop.

M
Transform matrix.
In
Input points, 32-byte aligned.
Out
Output points, 32-byte aligned.
uCount
Number of points.
function

MultiplyBatch

Ethereal::Math#
void MultiplyBatch( std::span< const Matrix::CMatrix4x4 > A, std::span< const Matrix::CMatrix4x4 > B, std::span< Matrix::CMatrix4x4 > Out ) noexcept;

'Out[i] = A[i] B[i]', with the same bits as 'CMatrix4x4::operator'.

A
Left matrices.
B
Right matrices.
Out
Products. May be the same array as A or B.
function

NormalizeBatch

Ethereal::Math#
void NormalizeBatch( std::span< const Vector::CVector3D > In, std::span< Vector::CVector3D > Out ) noexcept;

'Out[i] = In[i].Normalized()'.

Gives zero when the squared length is not above EPSILON² (and for NaN).

In
Input vectors.
Out
Unit vectors. May be the same array as In.
function

DotBatch

Ethereal::Math#
void DotBatch( std::span< const Vector::CVector3D > A, std::span< const Vector::CVector3D > B, std::span< ETL_FLOAT > Out ) noexcept;

'Out[i] = A[i].Dot( B[i] )'.

A
First vectors.
B
Second vectors.
Out
Dot products.
function

CrossBatch

Ethereal::Math#
void CrossBatch( std::span< const Vector::CVector3D > A, std::span< const Vector::CVector3D > B, std::span< Vector::CVector3D > Out ) noexcept;

'Out[i] = A[i].Cross( B[i] )'.

A
First vectors.
B
Second vectors.
Out
Cross products. May be the same array as A or B.
function

LengthBatch

Ethereal::Math#
void LengthBatch( std::span< const Vector::CVector3D > In, std::span< ETL_FLOAT > Out ) noexcept;

'Out[i] = In[i].Length()'.

In
Input vectors.
Out
Lengths.
function

DistanceBatch

Ethereal::Math#
void DistanceBatch( std::span< const Vector::CVector3D > A, std::span< const Vector::CVector3D > B, std::span< ETL_FLOAT > Out ) noexcept;

'Out[i] = Geometry::Distance3D( A[i], B[i] )'.

A
First points.
B
Second points.
Out
Distances.
function

LerpBatch

Ethereal::Math#
void LerpBatch( std::span< const Vector::CVector3D > A, std::span< const Vector::CVector3D > B, ETL_FLOAT t, std::span< Vector::CVector3D > Out ) noexcept;

'Out[i] = A[i] + ( B[i] - A[i] ) * t', per component (as 'Interpolation::Lerp').

A
Start vectors.
B
End vectors.
t
Interpolation factor, the same for every vector.
Out
Interpolated vectors. May be the same array as A or B.
function

NormalizeBatchSoa

Ethereal::Math#
void NormalizeBatchSoa( SSoaConstVector3 In, SSoaVector3 Out, std::size_t uCount ) noexcept;

NormalizeBatch over a structure of arrays.

In
Input vectors.
Out
Unit vectors.
uCount
Number of vectors.
function

DotBatchSoa

Ethereal::Math#
void DotBatchSoa( SSoaConstVector3 A, SSoaConstVector3 B, std::size_t uCount, std::span< ETL_FLOAT > Out ) noexcept;

DotBatch over a structure of arrays.

A
First vectors.
B
Second vectors.
uCount
Number of vectors.
Out
Dot products.
function

CrossBatchSoa

Ethereal::Math#
void CrossBatchSoa( SSoaConstVector3 A, SSoaConstVector3 B, SSoaVector3 Out, std::size_t uCount ) noexcept;

CrossBatch over a structure of arrays.

A
First vectors.
B
Second vectors.
Out
Cross products.
uCount
Number of vectors.
function

LengthBatchSoa

Ethereal::Math#
void LengthBatchSoa( SSoaConstVector3 In, std::size_t uCount, std::span< ETL_FLOAT > Out ) noexcept;

LengthBatch over a structure of arrays.

In
Input vectors.
uCount
Number of vectors.
Out
Lengths.
function

DistanceBatchSoa

Ethereal::Math#
void DistanceBatchSoa( SSoaConstVector3 A, SSoaConstVector3 B, std::size_t uCount, std::span< ETL_FLOAT > Out ) noexcept;

DistanceBatch over a structure of arrays.

A
First points.
B
Second points.
uCount
Number of points.
Out
Distances.
function

LerpBatchSoa

Ethereal::Math#
void LerpBatchSoa( SSoaConstVector3 A, SSoaConstVector3 B, ETL_FLOAT t, SSoaVector3 Out, std::size_t uCount ) noexcept;

LerpBatch over a structure of arrays.

A
Start vectors.
B
End vectors.
t
Interpolation factor.
Out
Interpolated vectors.
uCount
Number of vectors.
function

AosToSoa

Ethereal::Math#
void AosToSoa( std::span< const Vector::CVector3D > In, SSoaVector3 Out ) noexcept;

Converts interleaved points to a structure of arrays.

In
Interleaved points.
Out
Arrays with room for 'In.size()' points.
function

SoaToAos

Ethereal::Math#
void SoaToAos( SSoaConstVector3 In, std::size_t uCount, std::span< Vector::CVector3D > Out ) noexcept;

Converts a structure of arrays to interleaved points: min( uCount, Out.size() ) points.

In
Input arrays.
uCount
Number of points in In.
Out
Interleaved points.
function

FastInvSqrt

Ethereal::Math#
ETL_FLOAT FastInvSqrt( ETL_FLOAT x ) noexcept;

Approximate 1 / sqrt( x ).

Domain: normal positive x. 0 gives a large finite number, not +inf.

x
Input value.
The approximation.
function

FastSin

Ethereal::Math#
ETL_FLOAT FastSin( ETL_FLOAT x ) noexcept;

Approximate sine.

Domain: |x| <= 8192 for the published error. Above 6.5e6 the result has no meaning. NaN and ±inf give NaN. sin( -0 ) = -0.

x
Angle in radians.
The approximation.
function

FastCos

Ethereal::Math#
ETL_FLOAT FastCos( ETL_FLOAT x ) noexcept;

Approximate cosine.

Same domain as FastSin.

x
Angle in radians.
The approximation.
function

FastExp

Ethereal::Math#
ETL_FLOAT FastExp( ETL_FLOAT x ) noexcept;

Approximate e^x.

Domain: [-87.68, 88.37]. Outside it the result saturates at the ends (it never gives 0 or +inf).

x
Exponent.
The approximation.
function

FastLog

Ethereal::Math#
ETL_FLOAT FastLog( ETL_FLOAT x ) noexcept;

Approximate natural logarithm.

Domain: normal positive x. ±0 gives -inf, +inf gives +inf, negative and NaN give NaN. A subnormal gives a wrong value.

x
Input value.
The approximation.
function

FastAtan2

Ethereal::Math#
ETL_FLOAT FastAtan2( ETL_FLOAT y, ETL_FLOAT x ) noexcept;

Approximate atan2( y, x ).

Domain: finite values. atan2( ±0, -0 ) = ±pi. The two infinities together give NaN.

y
Y coordinate.
x
X coordinate.
The angle in radians.
function

FastNormalize

Ethereal::Math#
Vector::CVector3D FastNormalize( const Vector::CVector3D & v ) noexcept;

Like 'Normalized', with the error of FastInvSqrt.

v
Input vector.
The unit vector, or zero under the same rule as 'Normalized'.
function

FastDistance

Ethereal::Math#
ETL_FLOAT FastDistance( const Vector::CVector3D & a, const Vector::CVector3D & b ) noexcept;

Approximate distance between two points.

Domain: a normal squared distance. Below about 1.08e-19 it gives 0.

a
First point.
b
Second point.
The approximation.
function

FastInvSqrtBatch

Ethereal::Math#
void FastInvSqrtBatch( std::span< const ETL_FLOAT > In, std::span< ETL_FLOAT > Out ) noexcept;

FastInvSqrt over an array.

In
Input values.
Out
Results. May be the same array as In.
function

FastSinBatch

Ethereal::Math#
void FastSinBatch( std::span< const ETL_FLOAT > In, std::span< ETL_FLOAT > Out ) noexcept;

FastSin over an array.

In
Angles in radians.
Out
Results. May be the same array as In.
function

FastCosBatch

Ethereal::Math#
void FastCosBatch( std::span< const ETL_FLOAT > In, std::span< ETL_FLOAT > Out ) noexcept;

FastCos over an array.

In
Angles in radians.
Out
Results. May be the same array as In.
function

FastExpBatch

Ethereal::Math#
void FastExpBatch( std::span< const ETL_FLOAT > In, std::span< ETL_FLOAT > Out ) noexcept;

FastExp over an array.

In
Exponents.
Out
Results. May be the same array as In.
function

FastLogBatch

Ethereal::Math#
void FastLogBatch( std::span< const ETL_FLOAT > In, std::span< ETL_FLOAT > Out ) noexcept;

FastLog over an array.

In
Input values.
Out
Results. May be the same array as In.
function

FastAtan2Batch

Ethereal::Math#
void FastAtan2Batch( std::span< const ETL_FLOAT > Y, std::span< const ETL_FLOAT > X, std::span< ETL_FLOAT > Out ) noexcept;

FastAtan2 over two arrays.

Y
Y coordinates.
X
X coordinates.
Out
Angles in radians.
function

FastNormalizeBatch

Ethereal::Math#
void FastNormalizeBatch( std::span< const Vector::CVector3D > In, std::span< Vector::CVector3D > Out ) noexcept;

FastNormalize over an array.

In
Input vectors.
Out
Unit vectors. May be the same array as In.
function

FastDistanceBatch

Ethereal::Math#
void FastDistanceBatch( std::span< const Vector::CVector3D > A, std::span< const Vector::CVector3D > B, std::span< ETL_FLOAT > Out ) noexcept;

FastDistance over two arrays.

A
First points.
B
Second points.
Out
Distances.
function

BatchPath

Ethereal::Math#
Cpu::ESimdLevel BatchPath() noexcept;

Path used by the batch: Scalar, Sse2, Sse41, Avx2 or (only when forced) Avx512.

Resolves the dispatch if it was not resolved yet. It exists so the path is declared: a differential test that compares "the scalar path" with the vector path must know the scalar path is really scalar, or it compares AVX2 with AVX2.

Thread safety: full.

constants.hpp

#include <ethereal/cpp/math/constants.hpp>
const

PI

Ethereal::Math#
inline constexpr long double PI = 3.141592653589793238462643383279502884L;

Ratio between a circle's circumference and its diameter.

const

TWO_PI

Ethereal::Math#
inline constexpr long double TWO_PI = 6.283185307179586476925286766559005768L;

Full circle constant (2 * PI).

const

HALF_PI

Ethereal::Math#
inline constexpr long double HALF_PI = 1.570796326794896619231321691639751442L;

Half circle constant (PI / 2).

const

QUARTER_PI

Ethereal::Math#
inline constexpr long double QUARTER_PI = 0.785398163397448309615660845819875721L;

Quarter circle constant (PI / 4).

const

INV_PI

Ethereal::Math#
inline constexpr long double INV_PI = 0.318309886183790671537767526745028724L;

Reciprocal of PI (1 / PI).

const

INV_TWO_PI

Ethereal::Math#
inline constexpr long double INV_TWO_PI = 0.159154943091895335768883763372514362L;

Reciprocal of TWO_PI (1 / 2PI).

const

SQRT2

Ethereal::Math#
inline constexpr long double SQRT2 = 1.414213562373095048801688724209698079L;

Square root of 2.

const

INV_SQRT2

Ethereal::Math#
inline constexpr long double INV_SQRT2 = 0.707106781186547524400844362104849039L;

Reciprocal of SQRT2 (1 / √2).

const

SQRT3

Ethereal::Math#
inline constexpr long double SQRT3 = 1.732050807568877293527446341505872367L;

Square root of 3.

const

INV_SQRT3

Ethereal::Math#
inline constexpr long double INV_SQRT3 = 0.577350269189625764509148780501957456L;

Reciprocal of SQRT3 (1 / √3).

const

SQRT5

Ethereal::Math#
inline constexpr long double SQRT5 = 2.236067977499789696409173668731276235L;

Square root of 5.

const

SQRT_PI

Ethereal::Math#
inline constexpr long double SQRT_PI = 1.772453850905516027298167483341145182L;

Square root of PI.

const

INV_SQRT_PI

Ethereal::Math#
inline constexpr long double INV_SQRT_PI = 0.564189583547756286948079451560772586L;

Reciprocal of SQRT_PI (1 / √PI).

const

SQRT_TWO_PI

Ethereal::Math#
inline constexpr long double SQRT_TWO_PI = 2.506628274631000502415765284811045253L;

Square root of TWO_PI (√(2PI)).

const

SQRT_HALF_PI

Ethereal::Math#
inline constexpr long double SQRT_HALF_PI = 1.253314137315500251207882642405522626L;

Square root of HALF_PI (√(PI / 2)).

const

TWO_INV_SQRT_PI

Ethereal::Math#
inline constexpr long double TWO_INV_SQRT_PI = 1.128379167095512573896158903121545172L;

Two divided by the square root of PI (2 / √PI).

const

EULER_NUMBER

Ethereal::Math#
inline constexpr long double EULER_NUMBER = 2.718281828459045235360287471352662498L;

Euler's number (base of natural logarithms).

const

LOG2E

Ethereal::Math#
inline constexpr long double LOG2E = 1.442695040888963407359924681001892137L;

Base-2 logarithm of E.

const

LOG10E

Ethereal::Math#
inline constexpr long double LOG10E = 0.434294481903251827651128918916605082L;

Base-10 logarithm of E.

const

LN2

Ethereal::Math#
inline constexpr long double LN2 = 0.693147180559945309417232121458176568L;

Natural logarithm of 2.

const

LN10

Ethereal::Math#
inline constexpr long double LN10 = 2.302585092994045684017991454684364208L;

Natural logarithm of 10.

const

DEG_TO_RAD

Ethereal::Math#
inline constexpr long double DEG_TO_RAD = 0.017453292519943295769236907684886127L;

Conversion factor from degrees to radians.

const

RAD_TO_DEG

Ethereal::Math#
inline constexpr long double RAD_TO_DEG = 57.29577951308232087679815481410517033L;

Conversion factor from radians to degrees.

const

EPSILON

Ethereal::Math#
inline constexpr long double EPSILON = 1e-6L;

Small epsilon value for floating-point comparisons.

const

SMALL_NUMBER

Ethereal::Math#
inline constexpr long double SMALL_NUMBER = 1e-8L;

Very small floating-point value.

const

KINDA_SMALL_NUMBER

Ethereal::Math#
inline constexpr long double KINDA_SMALL_NUMBER = 1e-4L;

Slightly larger tolerance used in approximate comparisons.

const

CATALAN

Ethereal::Math#
inline constexpr long double CATALAN = 0.915965594177219015054603514932384110L;

Catalan's constant G.

const

APERY

Ethereal::Math#
inline constexpr long double APERY = 1.202056903159594285399738161511449990L;

Apéry's constant ζ(3).

const

GOLDEN_RATIO

Ethereal::Math#
inline constexpr long double GOLDEN_RATIO = 1.618033988749894848204586834365638117L;

Golden ratio constant (φ).

const

INV_GOLDEN_RATIO

Ethereal::Math#
inline constexpr long double INV_GOLDEN_RATIO = 0.618033988749894848204586834365638117L;

Reciprocal of the golden ratio (1 / φ).

core.hpp

#include <ethereal/cpp/math/core.hpp>
function

Min

Ethereal::Math#
template< typename T > inline constexpr T Min( const T a, const T b ) noexcept
function

Max

Ethereal::Math#
template< typename T > inline constexpr T Max( const T a, const T b ) noexcept
function

Sqrt

Ethereal::Math#
template< typename T > T Sqrt( const T value ) noexcept
function

InvSqrt

Ethereal::Math#
template< typename T > T InvSqrt( const T value ) noexcept
function

NormalizeAngle

Ethereal::Math#
template< typename T > T NormalizeAngle( T radians ) noexcept
function

Sin

Ethereal::Math#
template< typename T > T Sin( /*const*/ T radians ) noexcept
function

Cos

Ethereal::Math#
template< typename T > T Cos( T radians ) noexcept
function

SinCos

Ethereal::Math#
template< typename T > void SinCos( const T radians, T & outSin, T & outCos ) noexcept
function

Tan

Ethereal::Math#
template< typename T > T Tan( const T radians ) noexcept
function

Atan2

Ethereal::Math#
template< typename T > T Atan2( const T y, const T x ) noexcept
function

Floor

Ethereal::Math#
template< typename T > T Floor( const T value ) noexcept
function

Ceil

Ethereal::Math#
template< typename T > T Ceil( const T value ) noexcept
function

Clamp

Ethereal::Math#
template< typename T > inline constexpr T Clamp( const T v, const T minimum, const T maximum ) noexcept
function

Normalize

Ethereal::Math#
template< typename T > inline constexpr T Normalize( const T v, const T minimum, const T maximum ) noexcept
function

Remap

Ethereal::Math#
template< typename T > inline constexpr T Remap( const T value, const T inMinimum, const T inMaximum, const T outMinimum, const T outMaximum ) noexcept
function

Saturate

Ethereal::Math#
template< typename T > inline constexpr T Saturate( const T v ) noexcept
function

Map01ToSigned

Ethereal::Math#
template< typename T > inline constexpr T Map01ToSigned( const T v ) noexcept
function

MapSignedTo01

Ethereal::Math#
template< typename T > inline constexpr T MapSignedTo01( const T v ) noexcept
function

Abs

Ethereal::Math#
template< typename T > inline constexpr T Abs( const T v ) noexcept
function

Sign

Ethereal::Math#
template< typename T > inline constexpr int Sign( const T v ) noexcept
function

Square

Ethereal::Math#
template< typename T > inline constexpr T Square( const T v ) noexcept
function

Cube

Ethereal::Math#
template< typename T > inline constexpr T Cube( const T v ) noexcept
function

Average_impl

Ethereal::Math#
template< typename T > inline constexpr T Average_impl( const T a, const T b, std::true_type ) noexcept /* integral */
function

Average_impl

Ethereal::Math#
template< typename T > inline constexpr T Average_impl( const T a, const T b, std::false_type ) noexcept /* floating-point */
function

Average

Ethereal::Math#
template< typename T > inline constexpr T Average( const T a, const T b ) noexcept
function

Distance_impl

Ethereal::Math#
template< typename T > inline constexpr T Distance_impl( const T a, const T b, std::true_type ) noexcept /* unsigned integral */
function

Distance_impl

Ethereal::Math#
template< typename T > inline constexpr T Distance_impl( const T a, const T b, std::false_type ) noexcept /* signed / floating-point */
function

Distance

Ethereal::Math#
template< typename T > inline constexpr T Distance( const T a, const T b ) noexcept
function

Midpoint_impl

Ethereal::Math#
template< typename T > inline constexpr T Midpoint_impl( const T a, const T b, std::true_type ) noexcept /* integral */
function

Midpoint_impl

Ethereal::Math#
template< typename T > inline constexpr T Midpoint_impl( const T a, const T b, std::false_type ) noexcept /* floating-point */
function

Midpoint

Ethereal::Math#
template< typename T > inline constexpr T Midpoint( const T a, const T b ) noexcept
function

GetRatio_impl

Ethereal::Math#
template< typename T > inline constexpr T GetRatio_impl( const T a, const T b, std::true_type ) noexcept /* floating-point */
function

GetRatio_impl

Ethereal::Math#
template< typename T > inline constexpr T GetRatio_impl( const T a, const T b, std::false_type ) noexcept /* integral */
function

GetRatio

Ethereal::Math#
template< typename T > inline constexpr T GetRatio( const T a, const T b ) noexcept
function

GetRawRatio

Ethereal::Math#
template< typename T > inline constexpr T GetRawRatio( const T a, const T b ) noexcept
function

SafeDivide

Ethereal::Math#
template< typename T > inline constexpr T SafeDivide( const T a, const T b, const T fallback = T(0) ) noexcept
function

Percent

Ethereal::Math#
template< typename T > inline constexpr T Percent( const T value, const T total ) noexcept
function

NearEqual

Ethereal::Math#
template< typename T > inline constexpr bool NearEqual( const T a, const T b, const T epsilon ) noexcept
function

IsNearlyZero

Ethereal::Math#
template< typename T > inline constexpr bool IsNearlyZero( const T v, const T epsilon = T(1e-6) ) noexcept
function

Fract

Ethereal::Math#
template< typename T > T Fract( const T v ) noexcept
function

Hypot

Ethereal::Math#
template< typename T > T Hypot( const T a, const T b ) noexcept
function

Log2Floor

Ethereal::Math#
inline constexpr ETL_UINT32 Log2Floor( ETL_UINT32 v ) noexcept

Computes the floor of the base-2 logarithm of an unsigned integer. Returns the position of the most significant set bit in the value. Equivalent to 'floor(log2(v))'. If the input value is zero, the function returns '0'. When available, this function uses standard C++20 bit utilities (std::bit_width) or compiler intrinsics for maximum performance.

v
Input value.
Floor of log₂(v). Returns '0' when 'v == 0'.
function

Log2Ceil

Ethereal::Math#
inline constexpr ETL_UINT32 Log2Ceil( ETL_UINT32 v ) noexcept

Computes the ceiling of the base-2 logarithm of an unsigned integer. Returns the smallest integer 'n' such that '2^n >= v'. Equivalent to 'ceil(log2(v))'. For values '0' and '1', the result is defined as '0'. This function uses C++20 bit utilities when available, otherwise it derives the result using @Log2Floor.

v
Input value.
Ceiling of log₂(v).
function

IsPowerOfTwo

Ethereal::Math#
inline constexpr bool IsPowerOfTwo( const ETL_UINT64 v ) noexcept

Checks whether the given value is a power of two. A number is a power of two if it contains exactly one set bit in its binary representation. This function performs a fast bitwise test using the identity '(v & (v - 1)) == 0'.

v
Input value.
True if the value is a power of two, otherwise false.
function

NextPowerOfTwo

Ethereal::Math#
inline constexpr ETL_UINT64 NextPowerOfTwo( ETL_UINT64 v ) noexcept

Computes the next power of two greater than or equal to the input value. Expands the highest set bit across lower bits and then increments the result to obtain the next power-of-two boundary. If the input value is already a power of two, it is returned unchanged. If the input is '0', the function returns '1'.

v
Input value.
Smallest power of two greater than or equal to 'v'.
function

PrevPowerOfTwo

Ethereal::Math#
inline constexpr ETL_UINT64 PrevPowerOfTwo( ETL_UINT64 v ) noexcept

Computes the largest power of two less than or equal to the input value. Determines the position of the most significant set bit and reconstructs the corresponding power-of-two value. If the input value is '0', the function returns '0'.

v
Input value.
Largest power of two less than or equal to 'v'.
function

AlignUp

Ethereal::Math#
inline constexpr ETL_UINT64 AlignUp( ETL_UINT64 value, ETL_UINT64 alignment ) noexcept

Aligns a value upward to the specified power-of-two boundary. Rounds the input value up to the nearest multiple of alignment. The alignment must be a power of two. Internally, the function uses efficient bit masking to compute the aligned value.

value
Value to align.
alignment
Alignment boundary (must be a power of two).
Aligned value greater than or equal to value.
function

AlignDown

Ethereal::Math#
inline constexpr ETL_UINT64 AlignDown( ETL_UINT64 value, ETL_UINT64 alignment ) noexcept

Aligns a value downward to the specified power-of-two boundary. Rounds the input value down to the nearest multiple of alignment. The alignment must be a power of two. The operation is implemented using fast bit masking.

value
Value to align.
alignment
Alignment boundary (must be a power of two).
Aligned value less than or equal to 'value'.
function

IsAligned

Ethereal::Math#
inline constexpr bool IsAligned( ETL_UINT64 value, ETL_UINT64 alignment ) noexcept

Checks whether a value is aligned to a power-of-two boundary. Tests if the input value satisfies the specified alignment. The alignment must be a power of two. Internally this performs a fast bitmask check to determine if the lower bits are zero.

value
Value to test.
alignment
Alignment boundary (must be a power of two).
True if the value is properly aligned, otherwise false.

geometry.hpp

#include <ethereal/cpp/math/geometry.hpp>
function

AreaSquare

Ethereal::Math::Geometry#
template< typename T > inline constexpr T AreaSquare( const T side ) noexcept
function

AreaRectangle

Ethereal::Math::Geometry#
template< typename T > inline constexpr T AreaRectangle( const T width, const T height ) noexcept
function

AreaTriangle

Ethereal::Math::Geometry#
template< typename T > inline constexpr T AreaTriangle( const T base, const T height ) noexcept
function

AreaCircle

Ethereal::Math::Geometry#
template< typename T > inline constexpr T AreaCircle( const T radius ) noexcept
function

VolumeCube

Ethereal::Math::Geometry#
template< typename T > inline constexpr T VolumeCube( const T side ) noexcept
function

VolumeBox

Ethereal::Math::Geometry#
template< typename T > inline constexpr T VolumeBox( const T width, const T height, const T depth ) noexcept
function

VolumeCylinder

Ethereal::Math::Geometry#
template< typename T > inline constexpr T VolumeCylinder( const T radius, const T height ) noexcept
function

VolumeSphere

Ethereal::Math::Geometry#
template< typename T > inline constexpr T VolumeSphere( const T radius ) noexcept
function

DistanceSq2D

Ethereal::Math::Geometry#
template< typename T > inline constexpr T DistanceSq2D( const T x1, const T y1, const T x2, const T y2 ) noexcept
function

Distance2D

Ethereal::Math::Geometry#
template< typename T > inline constexpr T Distance2D( const T x1, const T y1, const T x2, const T y2 ) noexcept
function

DistanceSq3D

Ethereal::Math::Geometry#
template< typename T > inline constexpr T DistanceSq3D( const T x1, const T y1, const T z1, const T x2, const T y2, const T z2 ) noexcept
function

Distance3D

Ethereal::Math::Geometry#
template< typename T > inline constexpr T Distance3D( const T x1, const T y1, const T z1, const T x2, const T y2, const T z2 ) noexcept
function

IsPointInRectangle

Ethereal::Math::Geometry#
template< typename T > inline constexpr bool IsPointInRectangle( const T px, const T py, const T rx, const T ry, const T width, const T height ) noexcept
function

IsPointInCircle

Ethereal::Math::Geometry#
template< typename T > inline constexpr bool IsPointInCircle( const T px, const T py, const T cx, const T cy, const T radius ) noexcept
function

IsPointInTriangle

Ethereal::Math::Geometry#
template< typename T > inline constexpr bool IsPointInTriangle( const T px, const T py, const T ax, const T ay, const T bx, const T by, const T cx, const T cy ) noexcept
function

DistancePointToSegment

Ethereal::Math::Geometry#
template< typename T > inline constexpr T DistancePointToSegment( const T px, const T py, const T ax, const T ay, const T bx, const T by )
function

IntersectsRect

Ethereal::Math::Geometry#
template< typename T > inline constexpr bool IntersectsRect( const T ax, const T ay, const T aw, const T ah, const T bx, const T by, const T bw, const T bh ) noexcept
function

IsPointOnSegment

Ethereal::Math::Geometry#
template< typename T > inline constexpr bool IsPointOnSegment( const T px, const T py, const T ax, const T ay, const T bx, const T by)
function

ClosestPointOnSegment

Ethereal::Math::Geometry#
template< typename T > inline constexpr void ClosestPointOnSegment( const T px, const T py, const T ax, const T ay, const T bx, const T by, T & ox, T & oy )
function

DistancePointToLine

Ethereal::Math::Geometry#
template< typename T > inline constexpr T DistancePointToLine( const T px, const T py, const T ax, const T ay, const T bx, const T by ) noexcept
function

IntersectsLineLine

Ethereal::Math::Geometry#
template< typename T > inline constexpr bool IntersectsLineLine( const T x1, const T y1, const T x2, const T y2, const T x3, const T y3, const T x4, const T y4 ) noexcept
function

ProjectPointOnLine

Ethereal::Math::Geometry#
template< typename T > inline constexpr void ProjectPointOnLine( const T px, const T py, const T ax, const T ay, const T bx, const T by, T & ox, T & oy ) noexcept
function

DistancePointToAABB

Ethereal::Math::Geometry#
template< typename T > inline constexpr T DistancePointToAABB( const T px, const T py, const T minx, const T miny, const T maxx, const T maxy )
function

IsPointInAABB

Ethereal::Math::Geometry#
template< typename T > inline constexpr bool IsPointInAABB( const T px, const T py, const T minx, const T miny, const T maxx, const T maxy ) noexcept
function

IntersectsAABB

Ethereal::Math::Geometry#
template< typename T > inline constexpr bool IntersectsAABB( const T aminx, const T aminy, const T amaxx, const T amaxy, const T bminx, const T bminy, const T bmaxx, const T bmaxy ) noexcept
function

AABBContainsAABB

Ethereal::Math::Geometry#
template< typename T > inline constexpr bool AABBContainsAABB( const T aminx, const T aminy, const T amaxx, const T amaxy, const T bminx, const T bminy, const T bmaxx, const T bmaxy ) noexcept
function

RayIntersectsAABB

Ethereal::Math::Geometry#
template< typename T > inline constexpr bool RayIntersectsAABB( const T ox, const T oy, const T dx, const T dy, const T minx, const T miny, const T maxx, const T maxy )
function

RayIntersectsCircle

Ethereal::Math::Geometry#
template< typename T > inline constexpr bool RayIntersectsCircle( const T ox, const T oy, const T dx, const T dy, const T cx, const T cy, const T radius ) noexcept
function

TriangleCentroid

Ethereal::Math::Geometry#
template< typename T > inline constexpr void TriangleCentroid( const T ax, const T ay, const T bx, const T by, const T cx, const T cy, T & ox, T & oy ) noexcept
function

TriangleAreaCoords

Ethereal::Math::Geometry#
template< typename T > inline constexpr T TriangleAreaCoords( const T ax, const T ay, const T bx, const T by, const T cx, const T cy ) noexcept
function

Orientation

Ethereal::Math::Geometry#
template< typename T > inline constexpr T Orientation( const T ax, const T ay, const T bx, const T by, const T cx, const T cy ) noexcept

interpolation.hpp

#include <ethereal/cpp/math/interpolation.hpp>
function

Lerp

Ethereal::Math::Interpolation#
template< typename T > inline constexpr T Lerp( const T a, const T b, const T t ) noexcept
function

Step

Ethereal::Math::Interpolation#
template< typename T > inline constexpr T Step( const T edge, const T x ) noexcept
function

SmoothStep

Ethereal::Math::Interpolation#
template< typename T > inline constexpr T SmoothStep( const T edge0, const T edge1, const T x ) noexcept
function

Barycentric

Ethereal::Math::Interpolation#
template< typename T > inline constexpr T Barycentric( const T a, const T b, const T c, const T u, const T v ) noexcept

primitives.hpp

#include <ethereal/cpp/math/primitives.hpp>

Primitives of the Math module: quaternion, transform, plane, ray, box, sphere and frustum.

Simple single element types, trivially copyable and usable in 'constexpr'. They are not SIMD types ('batch.hpp' explains why). The conventions are those of 'CMatrix4x4': right handed, column vectors, 'A * B' applies B first.

  • SQuaternion: (x, y, z) is the vector part, w the scalar part. Hamilton product. 'q * p' applies p first (like the matrices). Rotation by the right hand rule, the same as 'CMatrix4x4::Rotate( axis, angle )'.
  • STransform: scale, then rotation, then translation. 'ToMatrix() = T R S'.
  • SPlane: 'Normal . p + D = 0'. The signed distance is positive on the side the normal points to.
  • SRay: 'Origin + Direction * t'. The direction need not be unit length. The returned t is in its units.
  • SAabb: axis aligned box, closed [Min, Max].
  • SSphere: center and radius.
  • SFrustum: six planes with the normal pointing inward, taken from a view-projection matrix (Gribb-Hartmann, depth in [-1, 1]).

Double precision does not exist in these types nor in the vectors. 'CVector3D' is float only, and making it a template would change the public API. The README says so.

struct

SQuaternion

Ethereal::Math#
C++
struct   SQuaternion
{
    /// @brief  Vector part (x, y, z) and scalar part (w). The default is the identity.
    ETL_FLOAT x = 0.0f, y = 0.0f, z = 0.0f, w = 1.0f;

    /// @brief  Identity quaternion.
    ETL_CEXPR SQuaternion() ETL_NOEXCEPT = default;

    /// @brief  Quaternion from its four components.
    ETL_CEXPR SQuaternion( const ETL_FLOAT fX, const ETL_FLOAT fY, const ETL_FLOAT fZ, const ETL_FLOAT fW ) ETL_NOEXCEPT
        : x( fX ), y( fY ), z( fZ ), w( fW ) {}

    /// @brief  Identity quaternion.
    static ETL_CEXPR SQuaternion Identity() ETL_NOEXCEPT { return SQuaternion(); }


    ///
    /// FromAxisAngle
    ///
    /// @brief  Rotation of @p fRad radians around @p Axis, by the right hand rule.
    ///
    /// @param Axis        Rotation axis. Must be unit length.
    /// @param fRad        Angle in radians.
    ///
    /// @return  The rotation quaternion.
    ///
    static SQuaternion FromAxisAngle( const Vector::CVector3D & Axis, const ETL_FLOAT fRad ) ETL_NOEXCEPT
    {
        const ETL_FLOAT s = std::sin( fRad * 0.5f );
        return SQuaternion( Axis.x * s, Axis.y * s, Axis.z * s, std::cos( fRad * 0.5f ) );
    }


    /// @brief  Hamilton product: applies @p r first, then this one.
    ///
    ETL_CEXPR SQuaternion operator*( const SQuaternion & r ) const ETL_NOEXCEPT
    {
        return SQuaternion( w * r.x + x * r.w + y * r.z - z * r.y,
                            w * r.y - x * r.z + y * r.w + z * r.x,
                            w * r.z + x * r.y - y * r.x + z * r.w,
                            w * r.w - x * r.x - y * r.y - z * r.z );
    }

    /// @brief  Four dimensional dot product.
    ETL_CEXPR ETL_FLOAT Dot( const SQuaternion & r ) const ETL_NOEXCEPT        { return x * r.x + y * r.y + z * r.z + w * r.w; }

    /// @brief  Squared length.
    ETL_CEXPR ETL_FLOAT LengthSquared() const ETL_NOEXCEPT                    { return Dot( *this ); }

    /// @brief  Conjugate: the inverse rotation of a unit quaternion.
    ETL_CEXPR SQuaternion Conjugate() const ETL_NOEXCEPT                    { return SQuaternion( -x, -y, -z, w ); }


    /// @brief  Unit length copy. The null quaternion gives the identity.
    ///
    SQuaternion Normalized() const ETL_NOEXCEPT
    {
        /// A null length (or NaN) gives the identity.
        const ETL_FLOAT l2 = LengthSquared();
        if( !( l2 > 0.0f ) )
            return SQuaternion();
        const ETL_FLOAT inv = 1.0f / std::sqrt( l2 );
        return SQuaternion( x * inv, y * inv, z * inv, w * inv );
    }


    ///
    /// Rotate
    ///
    /// @brief  Rotates @p v: v + 2w(u x v) + 2u x (u x v).
    ///
    /// @param v        Vector to rotate. The quaternion must be unit length.
    ///
    /// @return  The rotated vector.
    ///
    ETL_CEXPR Vector::CVector3D Rotate( const Vector::CVector3D & v ) const ETL_NOEXCEPT
    {
        const Vector::CVector3D u( x, y, z );
        const Vector::CVector3D t = u.Cross( v ) * 2.0f;
        return v + t * w + u.Cross( t );
    }


    /// @brief  Rotation matrix (column-major), equal to 'CMatrix4x4::Rotate' with the same axis and angle.
    ///
    ETL_CEXPR Matrix::CMatrix4x4 ToMatrix() const ETL_NOEXCEPT
    {
        const ETL_FLOAT xx = x * x, yy = y * y, zz = z * z;
        const ETL_FLOAT xy = x * y, xz = x * z, yz = y * z;
        const ETL_FLOAT wx = w * x, wy = w * y, wz = w * z;
        return Matrix::CMatrix4x4( 1.0f - 2.0f * ( yy + zz ), 2.0f * ( xy + wz ), 2.0f * ( xz - wy ), 0.0f,
                                   2.0f * ( xy - wz ), 1.0f - 2.0f * ( xx + zz ), 2.0f * ( yz + wx ), 0.0f,
                                   2.0f * ( xz + wy ), 2.0f * ( yz - wx ), 1.0f - 2.0f * ( xx + yy ), 0.0f,
                                   0.0f, 0.0f, 0.0f, 1.0f );
    }


    ///
    /// Slerp
    ///
    /// @brief  Spherical interpolation along the short path.
    ///
    /// @details  Close to 0 degrees it uses the normalized linear interpolation.
    ///
    /// @param a        Start rotation.
    /// @param b        End rotation.
    /// @param t        Interpolation factor in [0, 1].
    ///
    /// @return  The interpolated rotation.
    ///
    static SQuaternion Slerp( const SQuaternion & a, SQuaternion b, const ETL_FLOAT t ) ETL_NOEXCEPT
    {
        /// Takes the short path: with a negative dot product, flips b.
        ETL_FLOAT c = a.Dot( b );
        if( c < 0.0f )
        {
            b = SQuaternion( -b.x, -b.y, -b.z, -b.w );
            c = -c;
        }

        /// Almost the same rotation: the sine would be close to zero, so it uses the linear form.
        if( c > 0.9995f )
        {
            return SQuaternion( a.x + ( b.x - a.x ) * t, a.y + ( b.y - a.y ) * t,
                                a.z + ( b.z - a.z ) * t, a.w + ( b.w - a.w ) * t ).Normalized();
        }

        /// Weights of the spherical interpolation.
        const ETL_FLOAT th = std::acos( c );
        const ETL_FLOAT s = std::sin( th );
        const ETL_FLOAT ka = std::sin( ( 1.0f - t ) * th ) / s;
        const ETL_FLOAT kb = std::sin( t * th ) / s;
        return SQuaternion( a.x * ka + b.x * kb, a.y * ka + b.y * kb, a.z * ka + b.z * kb, a.w * ka + b.w * kb );
    }
};

Rotation quaternion. (x, y, z) is the vector part, w the scalar part.

struct

STransform

Ethereal::Math#
C++
struct   STransform
{
    /// @brief  Translation.
    Vector::CVector3D    Position{ 0.0f, 0.0f, 0.0f };

    /// @brief  Rotation. Must be unit length.
    SQuaternion            Rotation{};

    /// @brief  Scale per axis.
    Vector::CVector3D    Scale{ 1.0f, 1.0f, 1.0f };


    /// @brief  'T * R * S': scale, then rotation, then translation.
    ///
    ETL_CEXPR Matrix::CMatrix4x4 ToMatrix() const ETL_NOEXCEPT
    {
        /// Scales the three columns of the rotation.
        Matrix::CMatrix4x4 M = Rotation.ToMatrix();
        for( int r = 0; r < 3; ++r )
        {
            M.m[ 0 + r ] *= Scale.x;
            M.m[ 4 + r ] *= Scale.y;
            M.m[ 8 + r ] *= Scale.z;
        }

        /// The translation goes in the last column.
        M.m[ 12 ] = Position.x;
        M.m[ 13 ] = Position.y;
        M.m[ 14 ] = Position.z;
        return M;
    }


    ///
    /// TransformPoint
    ///
    /// @brief  Applies the transform to a point.
    ///
    /// @param p        Point to transform.
    ///
    /// @return  The transformed point.
    ///
    ETL_CEXPR Vector::CVector3D TransformPoint( const Vector::CVector3D & p ) const ETL_NOEXCEPT
    {
        return Position + Rotation.Rotate( Vector::CVector3D( p.x * Scale.x, p.y * Scale.y, p.z * Scale.z ) );
    }
};

Scale, then rotation, then translation.

struct

SPlane

Ethereal::Math#
C++
struct   SPlane
{
    /// @brief  Plane normal.
    Vector::CVector3D    Normal{ 0.0f, 1.0f, 0.0f };

    /// @brief  Plane offset.
    ETL_FLOAT            D = 0.0f;


    ///
    /// FromPointNormal
    ///
    /// @brief  The plane through @p Point with normal @p N.
    ///
    /// @param Point        A point on the plane.
    /// @param N            Unit normal.
    ///
    /// @return  The plane.
    ///
    static ETL_CEXPR SPlane FromPointNormal( const Vector::CVector3D & Point, const Vector::CVector3D & N ) ETL_NOEXCEPT
    {
        return SPlane{ N, -N.Dot( Point ) };
    }


    ///
    /// FromPoints
    ///
    /// @brief  The plane of a triangle. The normal follows the right hand rule (a, b, c counterclockwise).
    ///
    /// @param a        First vertex.
    /// @param b        Second vertex.
    /// @param c        Third vertex.
    ///
    /// @return  The plane, with a unit normal.
    ///
    static SPlane FromPoints( const Vector::CVector3D & a, const Vector::CVector3D & b, const Vector::CVector3D & c ) ETL_NOEXCEPT
    {
        return FromPointNormal( a, ( b - a ).Cross( c - a ).Normalized() );
    }


    /// @brief  Signed distance, positive on the side of the normal. In units of the normal (meters if it is unit length).
    ETL_CEXPR ETL_FLOAT SignedDistance( const Vector::CVector3D & p ) const ETL_NOEXCEPT    { return Normal.Dot( p ) + D; }


    /// @brief  Copy with a unit normal (and D scaled with it).
    ///
    SPlane Normalized() const ETL_NOEXCEPT
    {
        /// A null normal (or NaN) keeps the plane as it is.
        const ETL_FLOAT l = Normal.Length();
        if( !( l > 0.0f ) )
            return *this;
        const ETL_FLOAT inv = 1.0f / l;
        return SPlane{ Normal * inv, D * inv };
    }
};

Plane 'Normal . p + D = 0'.

struct

SRay

Ethereal::Math#
C++
struct   SRay
{
    /// @brief  Ray origin.
    Vector::CVector3D    Origin{ 0.0f, 0.0f, 0.0f };

    /// @brief  Ray direction. Need not be unit length.
    Vector::CVector3D    Direction{ 0.0f, 0.0f, -1.0f };

    /// @brief  Point at parameter @p t.
    ETL_CEXPR Vector::CVector3D At( const ETL_FLOAT t ) const ETL_NOEXCEPT    { return Origin + Direction * t; }


    ///
    /// Intersect
    ///
    /// @brief  Where the ray hits the plane (t >= 0).
    ///
    /// @param P        The plane.
    /// @param pT        Receives the parameter of the hit. May be null.
    ///
    /// @return  false when the ray is parallel to the plane or points away from it.
    ///
    bool Intersect( const SPlane & P, ETL_FLOAT * pT ) const ETL_NOEXCEPT
    {
        /// Parallel to the plane.
        const ETL_FLOAT den = P.Normal.Dot( Direction );
        if( den == 0.0f )
            return false;

        /// The plane is behind the origin.
        const ETL_FLOAT t = -P.SignedDistance( Origin ) / den;
        if( !( t >= 0.0f ) )
            return false;
        if( pT != nullptr )
            *pT = t;
        return true;
    }
};

Ray 'Origin + Direction * t'.

struct

SAabb

Ethereal::Math#
C++
struct   SAabb
{
    /// @brief  Lower corner.
    Vector::CVector3D    Min{ 0.0f, 0.0f, 0.0f };

    /// @brief  Upper corner.
    Vector::CVector3D    Max{ 0.0f, 0.0f, 0.0f };

    /// @brief  Center of the box.
    ETL_CEXPR Vector::CVector3D Center() const ETL_NOEXCEPT        { return ( Min + Max ) * 0.5f; }

    /// @brief  Half size of the box on each axis.
    ETL_CEXPR Vector::CVector3D Extents() const ETL_NOEXCEPT    { return ( Max - Min ) * 0.5f; }


    /// @brief  true when @p p is inside the box or on its surface.
    ///
    ETL_CEXPR bool Contains( const Vector::CVector3D & p ) const ETL_NOEXCEPT
    {
        return p.x >= Min.x && p.x <= Max.x && p.y >= Min.y && p.y <= Max.y && p.z >= Min.z && p.z <= Max.z;
    }


    /// @brief  true when the two boxes overlap (touching counts).
    ///
    ETL_CEXPR bool Intersects( const SAabb & o ) const ETL_NOEXCEPT
    {
        return Min.x <= o.Max.x && Max.x >= o.Min.x && Min.y <= o.Max.y && Max.y >= o.Min.y && Min.z <= o.Max.z && Max.z >= o.Min.z;
    }


    ///
    /// Intersect
    ///
    /// @brief  Ray against box, by the slab method.
    ///
    /// @details  A direction with a null component works (1/0 = infinity).
    ///
    /// @param R        The ray.
    /// @param pT        Receives the entry parameter (0 when the origin is already inside). May be null.
    ///
    /// @return  true when the ray hits the box.
    ///
    bool Intersect( const SRay & R, ETL_FLOAT * pT ) const ETL_NOEXCEPT
    {
        /// The interval of the ray inside every slab seen so far.
        ETL_FLOAT t0 = 0.0f;
        ETL_FLOAT t1 = std::numeric_limits< ETL_FLOAT >::infinity();
        const ETL_FLOAT o[ 3 ] = { R.Origin.x, R.Origin.y, R.Origin.z };
        const ETL_FLOAT d[ 3 ] = { R.Direction.x, R.Direction.y, R.Direction.z };
        const ETL_FLOAT lo[ 3 ] = { Min.x, Min.y, Min.z };
        const ETL_FLOAT hi[ 3 ] = { Max.x, Max.y, Max.z };

        /// Loop : One slab per axis.
        for( int k = 0; k < 3; ++k )
        {
            /// Parallel to the slab: the origin must be between its planes.
            if( d[ k ] == 0.0f )
            {
                if( o[ k ] < lo[ k ] || o[ k ] > hi[ k ] )
                    return false;
                continue;
            }

            /// Entry and exit of this slab, in order.
            const ETL_FLOAT inv = 1.0f / d[ k ];
            ETL_FLOAT a = ( lo[ k ] - o[ k ] ) * inv;
            ETL_FLOAT b = ( hi[ k ] - o[ k ] ) * inv;
            if( a > b )
            {
                const ETL_FLOAT tmp = a;
                a = b;
                b = tmp;
            }

            /// Narrows the interval. An empty interval means a miss.
            t0 = ( a > t0 ) ? a : t0;
            t1 = ( b < t1 ) ? b : t1;
            if( t0 > t1 )
                return false;
        }
        if( pT != nullptr )
            *pT = t0;
        return true;
    }
};

Axis aligned box, closed [Min, Max].

struct

SSphere

Ethereal::Math#
C++
struct   SSphere
{
    /// @brief  Center.
    Vector::CVector3D    Center{ 0.0f, 0.0f, 0.0f };

    /// @brief  Radius.
    ETL_FLOAT            Radius = 0.0f;


    /// @brief  true when @p p is inside the sphere or on its surface.
    ///
    ETL_CEXPR bool Contains( const Vector::CVector3D & p ) const ETL_NOEXCEPT
    {
        const Vector::CVector3D d = p - Center;
        return d.Dot( d ) <= Radius * Radius;
    }


    /// @brief  true when the two spheres overlap (touching counts).
    ///
    ETL_CEXPR bool Intersects( const SSphere & o ) const ETL_NOEXCEPT
    {
        const Vector::CVector3D d = o.Center - Center;
        const ETL_FLOAT r = Radius + o.Radius;
        return d.Dot( d ) <= r * r;
    }


    /// @brief  Sphere against box, through the point of the box closest to the center.
    ///
    ETL_CEXPR bool Intersects( const SAabb & B ) const ETL_NOEXCEPT
    {
        const ETL_FLOAT cx = Center.x < B.Min.x ? B.Min.x : ( Center.x > B.Max.x ? B.Max.x : Center.x );
        const ETL_FLOAT cy = Center.y < B.Min.y ? B.Min.y : ( Center.y > B.Max.y ? B.Max.y : Center.y );
        const ETL_FLOAT cz = Center.z < B.Min.z ? B.Min.z : ( Center.z > B.Max.z ? B.Max.z : Center.z );
        return Contains( Vector::CVector3D( cx, cy, cz ) );
    }


    ///
    /// Intersect
    ///
    /// @brief  Ray against sphere: the first t >= 0.
    ///
    /// @param R        The ray.
    /// @param pT        Receives the parameter of the hit (0 when the origin is already inside). May be null.
    ///
    /// @return  true when the ray hits the sphere.
    ///
    bool Intersect( const SRay & R, ETL_FLOAT * pT ) const ETL_NOEXCEPT
    {
        /// Coefficients of a t² + 2 b t + c = 0.
        const Vector::CVector3D m = R.Origin - Center;
        const ETL_FLOAT a = R.Direction.Dot( R.Direction );
        const ETL_FLOAT b = m.Dot( R.Direction );
        const ETL_FLOAT c = m.Dot( m ) - Radius * Radius;
        if( !( a > 0.0f ) )
            return false;

        /// The origin is inside: the hit is at the origin.
        if( c <= 0.0f )
        {
            if( pT != nullptr )
                *pT = 0.0f;
            return true;
        }
        if( b > 0.0f )
            return false;                    /// Outside and moving away.

        /// A negative discriminant means a miss.
        const ETL_FLOAT disc = b * b - a * c;
        if( disc < 0.0f )
            return false;
        if( pT != nullptr )
            *pT = ( -b - std::sqrt( disc ) ) / a;
        return true;
    }
};

Sphere given by center and radius.

struct

SFrustum

Ethereal::Math#
C++
struct   SFrustum
{
    /// @brief  Left, right, bottom, top, near, far. Unit normals pointing inward.
    SPlane    Planes[ 6 ];


    ///
    /// FromMatrix
    ///
    /// @brief  The planes of a view-projection matrix ('Projection * View').
    ///
    /// @details  The clip depth is in [-1, 1] (that of 'CMatrix4x4::Perspective').
    ///
    /// @param M        View-projection matrix.
    ///
    /// @return  The frustum.
    ///
    static SFrustum FromMatrix( const Matrix::CMatrix4x4 & M ) ETL_NOEXCEPT
    {
        /// The rows of the matrix (stored by columns): r_i = ( m[i], m[4+i], m[8+i], m[12+i] ).
        ///     The plane 'r3 + s * rj' is the clip test -w <= x, y, z <= w read row by row.
        auto Row = [ & ]( const ETL_FLOAT s, const int j ) -> SPlane
        {
            return SPlane{ Vector::CVector3D( M.m[ 3 ] + s * M.m[ j ], M.m[ 7 ] + s * M.m[ 4 + j ], M.m[ 11 ] + s * M.m[ 8 + j ] ),
                           M.m[ 15 ] + s * M.m[ 12 + j ] }.Normalized();
        };
        SFrustum F;
        F.Planes[ 0 ] = Row( 1.0f, 0 );        /// w + x >= 0
        F.Planes[ 1 ] = Row( -1.0f, 0 );        /// w - x >= 0
        F.Planes[ 2 ] = Row( 1.0f, 1 );        /// w + y >= 0
        F.Planes[ 3 ] = Row( -1.0f, 1 );        /// w - y >= 0
        F.Planes[ 4 ] = Row( 1.0f, 2 );        /// w + z >= 0
        F.Planes[ 5 ] = Row( -1.0f, 2 );        /// w - z >= 0
        return F;
    }


    /// @brief  true when @p p is on the inner side of every plane.
    ///
    ETL_CEXPR bool Contains( const Vector::CVector3D & p ) const ETL_NOEXCEPT
    {
        for( const SPlane & P : Planes )
            if( P.SignedDistance( p ) < 0.0f )
                return false;
        return true;
    }


    /// @brief  Conservative test. It may say "yes" to a sphere outside near a corner, never "no" to one inside.
    ///
    ETL_CEXPR bool Intersects( const SSphere & S ) const ETL_NOEXCEPT
    {
        for( const SPlane & P : Planes )
            if( P.SignedDistance( S.Center ) < -S.Radius )
                return false;
        return true;
    }


    /// @brief  Conservative test, through the vertex of the box furthest inside each plane.
    ///
    ETL_CEXPR bool Intersects( const SAabb & B ) const ETL_NOEXCEPT
    {
        for( const SPlane & P : Planes )
        {
            const Vector::CVector3D v( P.Normal.x >= 0.0f ? B.Max.x : B.Min.x,
                                       P.Normal.y >= 0.0f ? B.Max.y : B.Min.y,
                                       P.Normal.z >= 0.0f ? B.Max.z : B.Min.z );
            if( P.SignedDistance( v ) < 0.0f )
                return false;
        }
        return true;
    }
};

View frustum: six planes with unit normals pointing inward.

trigonometry.hpp

#include <ethereal/cpp/math/trigonometry.hpp>
function

DegToRad

Ethereal::Math::Trigonometry#
template< typename T > inline constexpr T DegToRad( const T deg ) noexcept
function

RadToDeg

Ethereal::Math::Trigonometry#
template< typename T > inline constexpr T RadToDeg( const T rad ) noexcept
function

WrapAngle

Ethereal::Math::Trigonometry#
template< typename T > inline constexpr T WrapAngle( const T rad ) noexcept
function

AngleDifference

Ethereal::Math::Trigonometry#
template< typename T > inline constexpr T AngleDifference( const T from, const T to ) noexcept
function

AngleLerp

Ethereal::Math::Trigonometry#
template< typename T > inline constexpr T AngleLerp( const T from, const T to, const T t ) noexcept
function

IsAngleInRange

Ethereal::Math::Trigonometry#
template< typename T > inline constexpr bool IsAngleInRange( const T angle, const T from, const T to ) noexcept
function

AngleToDirection

Ethereal::Math::Trigonometry#
template< typename T > inline constexpr void AngleToDirection( const T rad, T & ox, T & oy ) noexcept
function

DirectionToAngle

Ethereal::Math::Trigonometry#
template< typename T > inline constexpr T DirectionToAngle( const T dx, const T dy ) noexcept
function

Sinh

Ethereal::Math::Trigonometry#
template< typename T > inline constexpr T Sinh( const T v ) noexcept
function

Cosh

Ethereal::Math::Trigonometry#
template< typename T > inline constexpr T Cosh( const T v ) noexcept
function

Tanh

Ethereal::Math::Trigonometry#
template< typename T > inline constexpr T Tanh( const T v ) noexcept

wrap.hpp

#include <ethereal/cpp/math/wrap.hpp>
function

PositiveMod_impl

Ethereal::Math#
template< typename T > inline constexpr T PositiveMod_impl( const T a, const T b, std::true_type ) noexcept /* integral */
function

PositiveMod_impl

Ethereal::Math#
template< typename T > inline constexpr T PositiveMod_impl( const T a, const T b, std::false_type ) noexcept /* floating-point */
function

PositiveMod

Ethereal::Math#
template< typename T > inline constexpr T PositiveMod( const T a, const T b ) noexcept
function

Wrap

Ethereal::Math#
template< typename T > inline constexpr T Wrap( const T value, const T minimum, const T maximum ) noexcept
function

WrapExclusive

Ethereal::Math#
template< typename T > inline constexpr T WrapExclusive( const T value, const T minimum, const T maximum ) noexcept
function

WrapIndex

Ethereal::Math#
inline constexpr ETL_INT64 WrapIndex( const ETL_INT64 index, const ETL_INT64 size ) noexcept

Wraps an index into the range [0, size).

Safe circular indexing for arrays and ring buffers. Handles negative indices correctly.

index
Index to wrap.
size
Size of the circular buffer (exclusive upper bound).
Wrapped index in [0, size).
function

Repeat

Ethereal::Math#
template< typename T > inline constexpr T Repeat( const T value, const T length ) noexcept
function

PingPong

Ethereal::Math#
template< typename T > inline constexpr T PingPong( const T t, const T length ) noexcept
function

PingPongSmooth

Ethereal::Math#
template< typename T > inline constexpr T PingPongSmooth( const T t, const T length ) noexcept
function

Triangle

Ethereal::Math#
template< typename T > inline constexpr T Triangle( const T t ) noexcept
function

Sawtooth

Ethereal::Math#
template< typename T > inline constexpr T Sawtooth( const T t ) noexcept
function

CyclicDistance

Ethereal::Math#
template< typename T > inline constexpr T CyclicDistance( const T from, const T to, const T minimum, const T maximum ) noexcept
function

CyclicLerp

Ethereal::Math#
template< typename T > inline constexpr T CyclicLerp( const T from, const T to, const T t, const T minimum, const T maximum ) noexcept

matrix2.hpp

#include <ethereal/cpp/math/geometry/matrix2.hpp>
class

CMatrix2x2

Ethereal::Matrix#

2x2 matrix class, column-major storage, for column vectors ('M v'). 'A B' applies B first. Represents linear transformations in 2D space, commonly used for rotations, scaling, shearing, and basis changes.

class ETL_ALIGN CMatrix2x2

Storage layout: m[col * 2 + row]. Identity by default. | m[0] m[2] | | m[1] m[3] |

May be force-aligned depending on build configuration to enable SIMD-friendly memory layout.
const

m

#
ETL_FLOAT m[ 4 ];

Column-major flat storage. Access via m[col * 2 + row] or operator().

constructor

CMatrix2x2

#
constexpr CMatrix2x2() noexcept

Default constructor. Initializes to identity matrix.

constructor

CMatrix2x2

#
constexpr CMatrix2x2( ETL_FLOAT m00, ETL_FLOAT m10, ETL_FLOAT m01, ETL_FLOAT m11 ) noexcept

Direct initialization constructor. Arguments are in column-major order: (col0row0, col0row1, col1row0, col1row1).

m00
Column 0, row 0.
m10
Column 0, row 1.
m01
Column 1, row 0.
m11
Column 1, row 1.
constructor

CMatrix2x2

#
CMatrix2x2( const CMatrix2x2 & ) = default;

Copy constructor.

constructor

CMatrix2x2

#
CMatrix2x2( CMatrix2x2 && ) = default;

Move constructor.

operator

operator()

#
constexpr ETL_FLOAT & operator()( ETL_INT32 row, ETL_INT32 col ) noexcept

Reference to the element at (row, col).

operator

operator()

#
constexpr ETL_FLOAT operator()( ETL_INT32 row, ETL_INT32 col ) const noexcept

Element at (row, col) by value.

operator

operator=

#
CMatrix2x2 & operator=( const CMatrix2x2 & ) = default;

Copy assignment operator.

operator

operator=

#
CMatrix2x2 & operator=( CMatrix2x2 && ) = default;

Move assignment operator.

operator

operator+

#
constexpr CMatrix2x2 operator+( const CMatrix2x2 & rhs ) const noexcept

Matrix addition operator.

operator

operator-

#
constexpr CMatrix2x2 operator-( const CMatrix2x2 & rhs ) const noexcept

Matrix subtraction operator.

operator

operator*

#
constexpr CMatrix2x2 operator*( const CMatrix2x2 & rhs ) const noexcept

Matrix multiplication operator. Computes the standard matrix product. Result represents the combined transformation of rhs followed by this matrix.

operator

operator*

#
constexpr CMatrix2x2 operator*( const ETL_FLOAT scalar ) const noexcept

Scalar multiplication operator.

operator

operator*

#
constexpr Vector::CVector2D operator*( const Vector::CVector2D & v ) const noexcept

Transforms a 2D vector by this matrix (matrix-vector product). Equivalent to multiplying a column vector on the right: result = M * v.

operator

operator==

#
bool operator==( const CMatrix2x2 & rhs ) const noexcept

Equality comparison operator.

operator

operator!=

#
bool operator!=( const CMatrix2x2 & rhs ) const noexcept

Inequality comparison operator.

function

Transposed

#
constexpr CMatrix2x2 Transposed( void ) const noexcept

Transpose of this matrix. Swaps rows and columns. For orthogonal matrices, the transpose is equivalent to the inverse and is much cheaper to compute.

function

Determinant

#
constexpr ETL_FLOAT Determinant( void ) const noexcept

Determinant of this matrix. A zero determinant means the matrix is singular and has no inverse.

function

Inverse

#
CMatrix2x2 Inverse( void ) const noexcept

Inverse of this matrix. Computed via the adjugate divided by the determinant. If the matrix is singular (determinant == 0), returns the identity matrix.

Inverse matrix, or identity if not invertible.
function

Identity

#
static constexpr CMatrix2x2 Identity( void ) noexcept

2x2 identity matrix.

Identity matrix.
function

Scale

#
static constexpr CMatrix2x2 Scale( ETL_FLOAT sx, ETL_FLOAT sy ) noexcept

Returns a 2D scale matrix.

sx
Scale factor along X.
sy
Scale factor along Y.
Scale matrix.
function

Rotate

#
static CMatrix2x2 Rotate( ETL_FLOAT rad ) noexcept

Returns a 2D rotation matrix. Rotates counter-clockwise by the given angle in radians.

rad
Angle in radians.
Rotation matrix.

matrix3.hpp

#include <ethereal/cpp/math/geometry/matrix3.hpp>
class

CMatrix3x3

Ethereal::Matrix#

3x3 matrix class, column-major storage, for column vectors ('M v'). 'A B' applies B first. Represents linear transformations in 3D space or affine transformations in 2D (including translation), commonly used for rotations, scaling, and normal transforms.

class CMatrix3x3

Storage layout: m[col * 3 + row]. Identity by default. | m[0] m[3] m[6] | | m[1] m[4] m[7] | | m[2] m[5] m[8] |

const

m

#
ETL_FLOAT m[ 9 ];

Column-major flat storage. Access via m[col * 3 + row] or operator().

constructor

CMatrix3x3

#
constexpr CMatrix3x3() noexcept

Default constructor. Initializes to identity matrix.

constructor

CMatrix3x3

#
constexpr CMatrix3x3( ETL_FLOAT m00, ETL_FLOAT m10, ETL_FLOAT m20, ETL_FLOAT m01, ETL_FLOAT m11, ETL_FLOAT m21, ETL_FLOAT m02, ETL_FLOAT m12, ETL_FLOAT m22 ) noexcept

Direct initialization constructor. Arguments are in column-major order.

m00
Column 0, row 0.
m10
Column 0, row 1.
m20
Column 0, row 2.
m01
Column 1, row 0.
m11
Column 1, row 1.
m21
Column 1, row 2.
m02
Column 2, row 0.
m12
Column 2, row 1.
m22
Column 2, row 2.
constructor

CMatrix3x3

#
CMatrix3x3( const CMatrix3x3 & ) = default;

Copy constructor.

constructor

CMatrix3x3

#
CMatrix3x3( CMatrix3x3 && ) = default;

Move constructor.

operator

operator()

#
constexpr ETL_FLOAT & operator()( ETL_INT32 row, ETL_INT32 col ) noexcept

Reference to the element at (row, col).

operator

operator()

#
constexpr ETL_FLOAT operator()( ETL_INT32 row, ETL_INT32 col ) const noexcept

Element at (row, col) by value.

operator

operator=

#
CMatrix3x3 & operator=( const CMatrix3x3 & ) = default;

Copy assignment operator.

operator

operator=

#
CMatrix3x3 & operator=( CMatrix3x3 && ) = default;

Move assignment operator.

operator

operator+

#
constexpr CMatrix3x3 operator+( const CMatrix3x3 & rhs ) const noexcept

Matrix addition operator.

operator

operator-

#
constexpr CMatrix3x3 operator-( const CMatrix3x3 & rhs ) const noexcept

Matrix subtraction operator.

operator

operator*

#
constexpr CMatrix3x3 operator*( const CMatrix3x3 & rhs ) const noexcept

Matrix multiplication operator. Computes the standard matrix product. Result represents the combined transformation of rhs followed by this matrix.

operator

operator*

#
constexpr CMatrix3x3 operator*( const ETL_FLOAT scalar ) const noexcept

Scalar multiplication operator.

operator

operator*

#
constexpr Vector::CVector3D operator*( const Vector::CVector3D & v ) const noexcept

Transforms a 3D vector by this matrix (matrix-vector product). Equivalent to multiplying a column vector on the right: result = M * v.

operator

operator==

#
bool operator==( const CMatrix3x3 & rhs ) const noexcept

Equality comparison operator.

operator

operator!=

#
bool operator!=( const CMatrix3x3 & rhs ) const noexcept

Inequality comparison operator.

function

Transposed

#
constexpr CMatrix3x3 Transposed( void ) const noexcept

Transpose of this matrix. Swaps rows and columns. For orthogonal matrices the transpose equals the inverse and is much cheaper to compute.

Transposed matrix.
function

Determinant

#
constexpr ETL_FLOAT Determinant( void ) const noexcept

Returns the determinant of this matrix. A zero determinant means the matrix is singular and has no inverse.

Scalar determinant value.
function

Inverse

#
CMatrix3x3 Inverse( void ) const noexcept

Returns the inverse of this matrix. Computed via the classical adjugate/cofactor method. If the matrix is singular (determinant == 0), returns the identity matrix.

Inverse matrix, or identity if not invertible.
function

Identity

#
static constexpr CMatrix3x3 Identity( void ) noexcept

3x3 identity matrix.

Identity matrix.
function

Scale

#
static constexpr CMatrix3x3 Scale( ETL_FLOAT sx, ETL_FLOAT sy, ETL_FLOAT sz ) noexcept

3D scale matrix.

sx
Scale factor along X.
sy
Scale factor along Y.
sz
Scale factor along Z.
Scale matrix.
function

RotateX

#
static CMatrix3x3 RotateX( ETL_FLOAT rad ) noexcept

Rotation matrix around the X axis. Rotates counter-clockwise when viewed from the positive X axis.

rad
Angle in radians.
Rotation matrix.
function

RotateY

#
static CMatrix3x3 RotateY( ETL_FLOAT rad ) noexcept

Rotation matrix around the Y axis. Rotates counter-clockwise when viewed from the positive Y axis.

rad
Angle in radians.
Rotation matrix.
function

RotateZ

#
static CMatrix3x3 RotateZ( ETL_FLOAT rad ) noexcept

Rotation matrix around the Z axis. Rotates counter-clockwise when viewed from the positive Z axis.

rad
Angle in radians.
Rotation matrix.
function

Rotate

#
static CMatrix3x3 Rotate( const Vector::CVector3D & axis, ETL_FLOAT rad ) noexcept

Rotation matrix around an arbitrary axis. The axis vector must be normalized before calling. Uses the Rodrigues rotation formula.

axis
Normalized rotation axis.
rad
Angle in radians.
Rotation matrix.

matrix4.hpp

#include <ethereal/cpp/math/geometry/matrix4.hpp>
class

CMatrix4x4

Ethereal::Matrix#

4x4 matrix class, column-major storage, for column vectors ('M v'). 'A B' applies B first, then A. Perspective/LookAt are right-handed (camera looks down -Z, clip depth [-1, 1]). A test asserts each of these ('MathConvencoes'). Represents affine and projective transformations in 3D homogeneous coordinates, commonly used for model, view, and projection matrices in rendering pipelines.

class ETL_ALIGN CMatrix4x4

Storage layout: m[col * 4 + row]. Identity by default. | m[0] m[4] m[8] m[12] | | m[1] m[5] m[9] m[13] | | m[2] m[6] m[10] m[14] | | m[3] m[7] m[11] m[15] |

May be force-aligned depending on build configuration to enable SIMD-friendly memory layout.
const

m

#
ETL_FLOAT m[ 16 ];

Column-major flat storage. Access via m[col * 4 + row] or operator().

constructor

CMatrix4x4

#
constexpr CMatrix4x4() noexcept

Default constructor. Initializes to identity matrix.

constructor

CMatrix4x4

#
constexpr CMatrix4x4( ETL_FLOAT m00, ETL_FLOAT m10, ETL_FLOAT m20, ETL_FLOAT m30, ETL_FLOAT m01, ETL_FLOAT m11, ETL_FLOAT m21, ETL_FLOAT m31, ETL_FLOAT m02, ETL_FLOAT m12, ETL_FLOAT m22, ETL_FLOAT m32, ETL_FLOAT m03, ETL_FLOAT m13, ETL_FLOAT m23, ETL_FLOAT m33 ) noexcept

Direct initialization constructor. Arguments are in column-major order.

m00
Column 0, row 0. @param m10 Column 0, row 1.
m20
Column 0, row 2. @param m30 Column 0, row 3.
m01
Column 1, row 0. @param m11 Column 1, row 1.
m21
Column 1, row 2. @param m31 Column 1, row 3.
m02
Column 2, row 0. @param m12 Column 2, row 1.
m22
Column 2, row 2. @param m32 Column 2, row 3.
m03
Column 3, row 0. @param m13 Column 3, row 1.
m23
Column 3, row 2. @param m33 Column 3, row 3.
constructor

CMatrix4x4

#
constexpr CMatrix4x4( const CMatrix3x3 & rot, const Vector::CVector3D & trans ) noexcept

Construct from a 3x3 rotation/scale matrix and a translation vector. The W column is set to (0, 0, 0, 1).

rot
Upper-left 3x3 block (rotation and scale).
trans
Translation vector placed in column 3.
constructor

CMatrix4x4

#
CMatrix4x4( const CMatrix4x4 & ) = default;

Copy constructor.

constructor

CMatrix4x4

#
CMatrix4x4( CMatrix4x4 && ) = default;

Move constructor.

operator

operator()

#
constexpr ETL_FLOAT & operator()( ETL_INT32 row, ETL_INT32 col ) noexcept

Reference to the element at (row, col).

operator

operator()

#
constexpr ETL_FLOAT operator()( ETL_INT32 row, ETL_INT32 col ) const noexcept

Element at (row, col) by value.

operator

operator=

#
CMatrix4x4 & operator=( const CMatrix4x4 & ) = default;

Copy assignment operator.

operator

operator=

#
CMatrix4x4 & operator=( CMatrix4x4 && ) = default;

Move assignment operator.

operator

operator+

#
constexpr CMatrix4x4 operator+( const CMatrix4x4 & rhs ) const noexcept

Matrix addition operator.

operator

operator-

#
constexpr CMatrix4x4 operator-( const CMatrix4x4 & rhs ) const noexcept

Matrix subtraction operator.

operator

operator*

#
constexpr CMatrix4x4 operator*( const CMatrix4x4 & rhs ) const noexcept

Matrix multiplication operator. Computes the standard 4x4 matrix product. Result represents the combined transformation of rhs followed by this matrix. All 64 multiplications and 48 additions are written out explicitly to allow the compiler to fully inline and optimize the operation.

operator

operator*

#
constexpr CMatrix4x4 operator*( const ETL_FLOAT scalar ) const noexcept

Scalar multiplication operator.

operator

operator*

#
constexpr Vector::CVector4D operator*( const Vector::CVector4D & v ) const noexcept

Transforms a 4D vector by this matrix (matrix-vector product). Equivalent to multiplying a column vector on the right: result = M * v.

function

TransformPoint

#
Vector::CVector3D TransformPoint( const Vector::CVector3D & v ) const noexcept

Transforms a 3D point by this matrix. Treats the vector as a homogeneous point (w=1), applies the full 4x4 transform including translation, then performs perspective divide.

function

TransformDirection

#
Vector::CVector3D TransformDirection( const Vector::CVector3D & v ) const noexcept

Transforms a 3D direction vector by this matrix. Treats the vector as a direction (w=0), ignoring translation. Suitable for normals only when the matrix is orthogonal. For non-uniform scale, use the inverse-transpose for normals instead.

v
Direction vector to transform.
Transformed direction vector.
operator

operator==

#
bool operator==( const CMatrix4x4 & rhs ) const noexcept

Equality comparison operator.

operator

operator!=

#
bool operator!=( const CMatrix4x4 & rhs ) const noexcept

Inequality comparison operator.

function

Transposed

#
constexpr CMatrix4x4 Transposed( void ) const noexcept

Transpose of this matrix. Swaps rows and columns. For orthogonal matrices the transpose equals the inverse and is much cheaper to compute.

Transposed matrix.
function

Determinant

#
constexpr ETL_FLOAT Determinant( void ) const noexcept

Determinant of this matrix. Computed via 2x2 minor expansion (Laplace's theorem on pairs of rows). More numerically balanced than single-row/column expansion.

Scalar determinant value.
function

Inverse

#
CMatrix4x4 Inverse( void ) const noexcept

Inverse of this matrix. Computed via the adjugate matrix method, explicit cofactor expansion, optimal for fixed 4x4 matrices where loop overhead would dominate.

Inverse matrix, or identity if not invertible.
function

Identity

#
static constexpr CMatrix4x4 Identity( void ) noexcept

4x4 identity matrix.

Identity matrix.
function

Translate

#
static constexpr CMatrix4x4 Translate( ETL_FLOAT tx, ETL_FLOAT ty, ETL_FLOAT tz ) noexcept

Translation matrix.

tx
Translation along X.
ty
Translation along Y.
tz
Translation along Z.
Translation matrix.
function

Scale

#
static constexpr CMatrix4x4 Scale( ETL_FLOAT sx, ETL_FLOAT sy, ETL_FLOAT sz ) noexcept

3D scale matrix.

sx
Scale factor along X.
sy
Scale factor along Y.
sz
Scale factor along Z.
Scale matrix.
function

RotateX

#
static CMatrix4x4 RotateX( ETL_FLOAT rad ) noexcept

Rotation matrix around the X axis.

rad
Angle in radians.
Rotation matrix.
function

RotateY

#
static CMatrix4x4 RotateY( ETL_FLOAT rad ) noexcept

Rotation matrix around the Y axis.

rad
Angle in radians.
Rotation matrix.
function

RotateZ

#
static CMatrix4x4 RotateZ( ETL_FLOAT rad ) noexcept

Rotation matrix around the Z axis.

rad
Angle in radians.
Rotation matrix.
function

Rotate

#
static CMatrix4x4 Rotate( const Vector::CVector3D & axis, ETL_FLOAT rad ) noexcept

Rotation matrix around an arbitrary axis. The axis vector must be normalized before calling. Uses the Rodrigues rotation formula extended to 4x4.

axis
Normalized rotation axis.
rad
Angle in radians.
Rotation matrix.
function

Perspective

#
static CMatrix4x4 Perspective( ETL_FLOAT fovY, ETL_FLOAT aspect, ETL_FLOAT zNear, ETL_FLOAT zFar ) noexcept

Perspective projection matrix (right-handed, depth [-1, 1]). Standard OpenGL perspective projection.

fovY
Vertical field of view in radians.
aspect
Aspect ratio (width / height).
zNear
Near clip plane distance. Must be greater than zero.
zFar
Far clip plane distance. Must be greater than zNear.
Perspective projection matrix.
function

Orthographic

#
static CMatrix4x4 Orthographic( ETL_FLOAT left, ETL_FLOAT right, ETL_FLOAT bottom, ETL_FLOAT top, ETL_FLOAT zNear, ETL_FLOAT zFar ) noexcept

Orthographic projection matrix (right-handed, depth [-1, 1]).

left
Left clip plane.
right
Right clip plane.
bottom
Bottom clip plane.
top
Top clip plane.
zNear
Near clip plane.
zFar
Far clip plane.
Orthographic projection matrix.
function

LookAt

#
static CMatrix4x4 LookAt( const Vector::CVector3D & eye, const Vector::CVector3D & center, const Vector::CVector3D & up ) noexcept

Returns a look-at view matrix (right-handed). Constructs a view matrix that positions the camera at eye, looking toward center, with the given up vector.

eye
Camera position in world space.
center
Target point the camera is looking at.
up
World up vector (typically 0, 1, 0).
View matrix.

vector2.hpp

#include <ethereal/cpp/math/geometry/vector2.hpp>
class

CVector2D

Ethereal::Vector#

2D vector class with x and y components. Represents a point or direction in 2D space, commonly used for positions, velocities, texture coordinates, and screen-space math.

class CVector2D
const

y

#
ETL_FLOAT x, y;

Axis component.

constructor

CVector2D

#
constexpr CVector2D() noexcept : x( 0.0f ), y( 0.0f )

Default constructor.

constructor

CVector2D

#
constexpr CVector2D( const ETL_FLOAT fX, const ETL_FLOAT fY ) noexcept : x( fX ), y( fY )

Direct initialization constructor.

fX
X component value.
fY
Y component value.
constructor

CVector2D

#
CVector2D( const CVector2D & ) = default;

Copy constructor.

constructor

CVector2D

#
CVector2D( CVector2D && ) = default;

Move constructor.

operator

operatorbool

#
explicit operator bool() const noexcept

Null check operator. Returns true if the vector is non-zero.

operator

operator==

#
/*constexpr*/ bool operator==( const CVector2D & rhs ) const noexcept

Equality comparison operator.

operator

operator!=

#
/*constexpr*/ bool operator!=( const CVector2D & rhs ) const noexcept

Inequality comparison operator.

operator

operator=

#
CVector2D & operator=( const CVector2D & ) = default;

Copy assignment operator.

operator

operator=

#
CVector2D & operator=( CVector2D && ) = default;

Move assignment operator.

operator

operator+

#
constexpr CVector2D operator+( const CVector2D & rhs ) const noexcept

Vector addition operator.

operator

operator-

#
constexpr CVector2D operator-( const CVector2D & rhs ) const noexcept

Vector subtraction operator.

operator

operator*

#
constexpr CVector2D operator*( const ETL_FLOAT scalar ) const noexcept

Scalar multiplication operator.

operator

operator/

#
CVector2D operator/( const ETL_FLOAT scalar ) const noexcept

Scalar division operator.

operator

operator+=

#
constexpr CVector2D & operator+=( const CVector2D & rhs ) noexcept

Compound vector addition operator.

operator

operator-=

#
constexpr CVector2D & operator-=( const CVector2D & rhs ) noexcept

Compound vector subtraction operator.

operator

operator*=

#
constexpr CVector2D & operator*=( const ETL_FLOAT scalar ) noexcept

Compound scalar multiplication operator.

operator

operator/=

#
CVector2D & operator/=( const ETL_FLOAT scalar ) noexcept

Compound scalar division operator.

operator

operator-

#
constexpr CVector2D operator-() const noexcept

Unary negation operator.

function

LengthSquared

#
constexpr ETL_FLOAT LengthSquared( void ) const noexcept

Squared length (magnitude) of the vector. More efficient than @Length since it avoids the square root. Prefer this for distance comparisons where the exact length is not needed.

x² + y².
function

Length

#
ETL_FLOAT Length( void ) const noexcept

Length (magnitude) of the vector. Computed as sqrt(x² + y²). Represents the distance from the origin. Use @LengthSquared instead when only comparing distances.

Floating-point magnitude of the vector.
function

Normalized

#
CVector2D Normalized( void ) const noexcept

Normalized copy of the vector (unit length). Divides each component by the vector's length to produce a unit vector pointing in the same direction.

Unit vector in the same direction, or zero vector if length is near zero.
function

Dot

#
constexpr ETL_FLOAT Dot( const CVector2D & rhs ) const noexcept

Dot product between this vector and another. Measures directional similarity, returns the cosine of the angle between the two vectors when both are unit length.

rhs
Vector to compute dot product with.
Scalar dot product: x₁·x₂ + y₁·y₂.
function

Cross

#
constexpr ETL_FLOAT Cross( const CVector2D & rhs ) const noexcept

2D cross product (scalar). Returns the z-component of the 3D cross product treating both vectors as (x, y, 0). Geometrically, equals |a| |b| sin(θ), the signed area of the parallelogram formed by the two vectors. Sign indicates orientation: positive if rhs is counter-clockwise from this vector, negative if clockwise, zero if parallel.

rhs
Right-hand side vector.
Scalar cross product (signed area).
function

AngleBetween

Ethereal::Math#
inline ETL_FLOAT AngleBetween( const Vector::CVector2D & a, const Vector::CVector2D & b ) noexcept

Unsigned angle between two 2D vectors, in radians, in [0, pi]. Computed as atan2( |a x b|, a . b ). For the signed angle, use atan2( a x b, a . b ) directly.

a
First vector (need not be normalized).
b
Second vector (need not be normalized).
The unsigned angle. A zero vector on either side gives 0.

vector3.hpp

#include <ethereal/cpp/math/geometry/vector3.hpp>
class

CVector3D

Ethereal::Vector#

3D vector class with x, y, and z components. Represents a point or direction in 3D space, commonly used for positions, velocities, normals, and world-space math.

class CVector3D
const

z

#
ETL_FLOAT x, y, z;

Axis component.

constructor

CVector3D

#
constexpr CVector3D() noexcept : x( 0.0f ), y( 0.0f ), z( 0.0f )

Default constructor.

constructor

CVector3D

#
constexpr CVector3D( const ETL_FLOAT fX, const ETL_FLOAT fY, const ETL_FLOAT fZ ) noexcept : x( fX ), y( fY ), z( fZ )

Direct initialization constructor.

fX
X component value.
fY
Y component value.
fZ
Z component value.
constructor

CVector3D

#
CVector3D( const CVector3D & ) = default;

Copy constructor.

constructor

CVector3D

#
CVector3D( CVector3D && ) = default;

Move constructor.

operator

operatorbool

#
explicit operator bool() const noexcept

Null check operator. Returns true if the vector is non-zero.

operator

operator==

#
/*constexpr*/ bool operator==( const CVector3D & rhs ) const noexcept

Equality comparison operator.

operator

operator!=

#
/*constexpr*/ bool operator!=( const CVector3D & rhs ) const noexcept

Inequality comparison operator.

operator

operator=

#
CVector3D & operator=( const CVector3D & ) = default;

Copy assignment operator.

operator

operator=

#
CVector3D & operator=( CVector3D && ) = default;

Move assignment operator.

operator

operator+

#
constexpr CVector3D operator+( const CVector3D & rhs ) const noexcept

Vector addition operator.

operator

operator-

#
constexpr CVector3D operator-( const CVector3D & rhs ) const noexcept

Vector subtraction operator.

operator

operator*

#
constexpr CVector3D operator*( const ETL_FLOAT scalar ) const noexcept

Vector scalar multiplication operator.

operator

operator/

#
CVector3D operator/( const ETL_FLOAT scalar ) const noexcept

Scalar division operator.

operator

operator+=

#
constexpr CVector3D & operator+=( const CVector3D & rhs ) noexcept

Compound vector addition operator.

operator

operator-=

#
constexpr CVector3D & operator-=( const CVector3D & rhs ) noexcept

Compound vector subtraction operator.

operator

operator*=

#
constexpr CVector3D & operator*=( const ETL_FLOAT scalar ) noexcept

Compound scalar multiplication operator.

operator

operator/=

#
CVector3D & operator/=( const ETL_FLOAT scalar ) noexcept

Compound scalar division operator.

operator

operator-

#
constexpr CVector3D operator-() const noexcept

Unary negation operator.

function

LengthSquared

#
constexpr ETL_FLOAT LengthSquared( void ) const noexcept

Squared length (magnitude) of the vector. More efficient than @Length since it avoids the square root. Prefer this for distance comparisons where the exact length is not needed.

x² + y² + z².
function

Length

#
ETL_FLOAT Length( void ) const noexcept

Length (magnitude) of the vector. Computed as sqrt(x² + y² + z²). Represents the distance from the origin. Use @LengthSquared instead when only comparing distances.

Floating-point magnitude of the vector.
function

Normalized

#
CVector3D Normalized( void ) const noexcept

Normalized copy of the vector (unit length). Divides each component by the vector's length to produce a unit vector pointing in the same direction.

Unit vector in the same direction, or zero vector if length is near zero.
function

Dot

#
constexpr ETL_FLOAT Dot( const CVector3D & rhs ) const noexcept

Dot product between this vector and another. Measures directional similarity, returns the cosine of the angle between the two vectors when both are unit length. Positive if vectors point in the same general direction, zero if perpendicular, negative if opposing.

rhs
Vector to compute dot product with.
Scalar dot product: x₁·x₂ + y₁·y₂ + z₁·z₂.
function

Cross

#
constexpr CVector3D Cross( const CVector3D & rhs ) const noexcept

Cross product between this vector and another. Produces a vector perpendicular to both inputs, following the right-hand rule. The magnitude equals the area of the parallelogram spanned by the two vectors. If the result points toward you, the rotation from this to rhs is counter-clockwise.

rhs
Vector to compute cross product with.
Vector perpendicular to both inputs: (y₁z₂ - z₁y₂, z₁x₂ - x₁z₂, x₁y₂ - y₁x₂).
function

AngleBetween

Ethereal::Math#
inline ETL_FLOAT AngleBetween( const Vector::CVector3D & a, const Vector::CVector3D & b ) noexcept

Angle between two 3D vectors, in radians, in [0, pi]. Computed as atan2( |a x b|, a . b ), which stays accurate for small and near-pi angles, where the acos( a.b / (|a||b|) ) form loses most of its digits.

a
First vector (need not be normalized).
b
Second vector (need not be normalized).
The unsigned angle. A zero vector on either side gives 0.

vector4.hpp

#include <ethereal/cpp/math/geometry/vector4.hpp>
class

CVector4D

Ethereal::Vector#

4D vector class with x, y, z, and w components. Represents a point or direction in homogeneous coordinates, commonly used for matrix transformations, RGBA colors, and quaternion-like math.

class ETL_ALIGN CVector4D
May be force-aligned (e.g. 16 bytes) depending on build configuration to enable SIMD-friendly memory layout.
const

w

#
ETL_FLOAT x, y, z, w;

Axis components.

constructor

CVector4D

#
constexpr CVector4D() noexcept : x( 0.0f ), y( 0.0f ), z( 0.0f ), w( 0.0f )

Default constructor. Initializes all components to zero.

constructor

CVector4D

#
constexpr CVector4D( const ETL_FLOAT fX, const ETL_FLOAT fY, const ETL_FLOAT fZ, const ETL_FLOAT fW ) noexcept : x( fX ), y( fY ), z( fZ ), w( fW )

Direct initialization constructor.

fX
X component value.
fY
Y component value.
fZ
Z component value.
fW
W component value.
constructor

CVector4D

#
constexpr explicit CVector4D( const CVector3D & v, const ETL_FLOAT fW ) noexcept : x( v.x ), y( v.y ), z( v.z ), w( fW )

Construct from a 3D vector and a W component. Useful for homogeneous coordinates, pass w=1 for points, w=0 for directions.

v
3D vector to initialize X, Y, Z from.
fW
W component value.
constructor

CVector4D

#
CVector4D( const CVector4D & ) = default;

Copy constructor.

constructor

CVector4D

#
CVector4D( CVector4D && ) = default;

Move constructor.

operator

operatorbool

#
explicit operator bool() const noexcept

Null check operator. Returns true if any component exceeds ETL_EPSILON.

operator

operator==

#
/*constexpr*/ bool operator==( const CVector4D & rhs ) const noexcept

Equality comparison operator.

operator

operator!=

#
/*constexpr*/ bool operator!=( const CVector4D & rhs ) const noexcept

Inequality comparison operator.

operator

operator=

#
CVector4D & operator=( const CVector4D & ) = default;

Copy assignment operator.

operator

operator=

#
CVector4D & operator=( CVector4D && ) = default;

Move assignment operator.

operator

operator+

#
constexpr CVector4D operator+( const CVector4D & rhs ) const noexcept

Vector addition operator.

operator

operator-

#
constexpr CVector4D operator-( const CVector4D & rhs ) const noexcept

Vector subtraction operator.

operator

operator*

#
constexpr CVector4D operator*( const ETL_FLOAT scalar ) const noexcept

Vector scalar multiplication operator.

operator

operator/

#
CVector4D operator/( const ETL_FLOAT scalar ) const noexcept

Scalar division operator.

operator

operator+=

#
constexpr CVector4D & operator+=( const CVector4D & rhs ) noexcept

Compound vector addition operator.

operator

operator-=

#
constexpr CVector4D & operator-=( const CVector4D & rhs ) noexcept

Compound vector subtraction operator.

operator

operator*=

#
constexpr CVector4D & operator*=( const ETL_FLOAT scalar ) noexcept

Compound scalar multiplication operator.

operator

operator/=

#
CVector4D & operator/=( const ETL_FLOAT scalar ) noexcept

Compound scalar division operator.

operator

operator-

#
constexpr CVector4D operator-() const noexcept

Unary negation operator.

function

LengthSquared

#
constexpr ETL_FLOAT LengthSquared( void ) const noexcept

Squared length (magnitude) of the vector. More efficient than @Length since it avoids the square root. Prefer this for distance comparisons where the exact length is not needed.

x² + y² + z² + w².
function

Length

#
ETL_FLOAT Length( void ) const noexcept

Length (magnitude) of the vector. Computed as sqrt(x² + y² + z² + w²). Represents the distance from the origin. Use @LengthSquared instead when only comparing distances.

Floating-point magnitude of the vector.
function

Normalized

#
CVector4D Normalized( void ) const noexcept

Normalized copy of the vector (unit length). Divides each component by the vector's length to produce a unit vector pointing in the same direction.

Unit vector in the same direction, or zero vector if length is near zero.
function

Dot

#
constexpr ETL_FLOAT Dot( const CVector4D & rhs ) const noexcept

Dot product between this vector and another. Measures directional similarity, returns the cosine of the angle between the two vectors when both are unit length. Includes the W component in the calculation.

rhs
Vector to compute dot product with.
Scalar dot product: x₁·x₂ + y₁·y₂ + z₁·z₂ + w₁·w₂.
function

XYZ

#
constexpr CVector3D XYZ( void ) const noexcept

XYZ components as a CVector3D, discarding W. Useful for extracting the spatial component from a homogeneous coordinate.

CVector3D containing the X, Y and Z components.