LibGame v0.4.0
The LG Game Engine - Copyright (C) 2024-2026 ETMSoftware
Loading...
Searching...
No Matches
math_3d.c File Reference

Data Structures

struct  vec3_t
 
union  mat4_t
 

Macros

#define MATH_3D_IMPLEMENTATION
 
#define MATH_3D_HEADER
 

Functions

static vec3_t vec3 (float x, float y, float z)
 
static vec3_t v3_add (vec3_t a, vec3_t b)
 
static vec3_t v3_adds (vec3_t a, float s)
 
static vec3_t v3_sub (vec3_t a, vec3_t b)
 
static vec3_t v3_subs (vec3_t a, float s)
 
static vec3_t v3_mul (vec3_t a, vec3_t b)
 
static vec3_t v3_muls (vec3_t a, float s)
 
static vec3_t v3_div (vec3_t a, vec3_t b)
 
static vec3_t v3_divs (vec3_t a, float s)
 
static float v3_length (vec3_t v)
 
static vec3_t v3_norm (vec3_t v)
 
static float v3_dot (vec3_t a, vec3_t b)
 
static vec3_t v3_proj (vec3_t v, vec3_t onto)
 
static vec3_t v3_cross (vec3_t a, vec3_t b)
 
static float v3_angle_between (vec3_t a, vec3_t b)
 
static mat4_t mat4 (float m00, float m10, float m20, float m30, float m01, float m11, float m21, float m31, float m02, float m12, float m22, float m32, float m03, float m13, float m23, float m33)
 
static mat4_t m4_identity ()
 
static mat4_t m4_translation (vec3_t offset)
 
static mat4_t m4_scaling (vec3_t scale)
 
static mat4_t m4_rotation_x (float angle_in_rad)
 
static mat4_t m4_rotation_y (float angle_in_rad)
 
static mat4_t m4_rotation_z (float angle_in_rad)
 
mat4_t m4_rotation (float angle_in_rad, vec3_t axis)
 
mat4_t m4_ortho_RH (float left, float right, float bottom, float top, float back, float front)
 
mat4_t m4_perspective_RH (float vertical_field_of_view_in_deg, float aspect_ratio, float near_view_distance, float far_view_distance)
 
mat4_t m4_look_at_RH (vec3_t from, vec3_t to, vec3_t up)
 
mat4_t m4_frustum (float left, float right, float bottom, float top, float near, float far)
 
static mat4_t m4_transpose (mat4_t matrix)
 
static mat4_t m4_mul (mat4_t a, mat4_t b)
 
mat4_t m4_invert_affine (mat4_t matrix)
 
vec3_t m4_mul_pos (mat4_t matrix, vec3_t position)
 
vec3_t m4_mul_dir (mat4_t matrix, vec3_t direction)
 
void m4_print (mat4_t matrix)
 
void m4_printp (mat4_t matrix, int width, int precision)
 
void m4_fprint (FILE *stream, mat4_t matrix)
 
void m4_fprintp (FILE *stream, mat4_t matrix, int width, int precision)
 
void m4_print2 (mat4_t matrix, const char *line_start)
 
void m4_printp2 (mat4_t matrix, int width, int precision, const char *line_start)
 
void m4_fprint2 (FILE *stream, mat4_t matrix, const char *line_start)
 
void m4_fprintp2 (FILE *stream, mat4_t matrix, int width, int precision, const char *line_start)
 

Macro Definition Documentation

◆ MATH_3D_HEADER

#define MATH_3D_HEADER

Math 3D v1.0 - by Stephan Soller steph.nosp@m.an.s.nosp@m.oller.nosp@m.@hel.nosp@m.ionwe.nosp@m.b.de and Tobias Malmsheimer

Licensed under the MIT license

See: https://github.com/arkanis/single-header-file-c-libs/blob/master/math_3d.h


A few (mainly cosmetic) changes by Emmanuel Thomas-Maurin manu@.nosp@m.etms.nosp@m.oftwa.nosp@m.re.n.nosp@m.et

  • m4_frustum() added
  • Some new matrix info functions
  • New matrix funcs specifying RH/LH - everything here was originally RH (All matrices are column-major-order)
  • Now:
  • Not implemented:
    • m4_ortho_LH (float left, float right, float bottom, float top, float back, float front)
    • m4_perspective_LH (float vertical_field_of_view_in_deg, float aspect_ratio, float near_view_distance, float far_view_distance)
    • m4_look_at_LH (vec3_t from, vec3_t to, vec3_t up)
  • Indentation and coding style

Last change on 2025-02-22


Math 3D v1.0 By Stephan Soller steph.nosp@m.an.s.nosp@m.oller.nosp@m.@hel.nosp@m.ionwe.nosp@m.b.de and Tobias Malmsheimer Licensed under the MIT license

Math 3D is a compact C99 library meant to be used with OpenGL. It provides basic 3D vector and 4x4 matrix operations as well as functions to create transformation and projection matrices. The OpenGL binary layout is used so you can just upload vectors and matrices into shaders and work with them without any conversions.

It's an stb style single header file library. Define MATH_3D_IMPLEMENTATION before you include this file in one C file to create the implementation.

QUICK NOTES

  • If not explicitly stated by a parameter name all angles are in radians.
  • The matrices use column-major indices. This is the same as in OpenGL and GLSL. See the matrix documentation below for details.
  • Matrices are passed by value. This is probably a bit inefficient but simplifies code quite a bit. Most operations will be inlined by the compiler anyway so the difference shouldn't matter that much. A matrix fits into 4 of the 16 SSE2 registers anyway. If profiling shows significant slowdowns the matrix type might change but ease of use is more important than every last percent of performance.
  • When combining matrices with multiplication the effects apply right to left. This is the convention used in mathematics and OpenGL. Source: https://en.wikipedia.org/wiki/Transformation_matrix#Composing_and_inverting_transformations Direct3D does it differently.
  • The m4_mul_pos() and m4_mul_dir() functions do a correct perspective divide (division by w) when necessary. This is a bit slower but ensures that the functions will properly work with projection matrices. If profiling shows this is a bottleneck special functions without perspective division can be added. But the normal multiplications should avoid any surprises.
  • The library consistently uses a right-handed coordinate system. The old glOrtho() broke that rule and m4_ortho() has be slightly modified so you can always think of right-handed cubes that are projected into OpenGLs normalized device coordinates.
  • Special care has been taken to document all complex operations and important sources. Most code is covered by test cases that have been manually calculated and checked on the whiteboard. Since indices and math code is prone to be confusing we used pair programming to avoid mistakes.

FURTHER IDEAS

These are ideas for future work on the library. They're implemented as soon as there is a proper use case and we can find good names for them.

  • bool v3_is_null(vec3_t v, float epsilon) To check if the length of a vector is smaller than epsilon.
  • vec3_t v3_length_default(vec3_t v, float default_length, float epsilon) Returns default_length if the length of v is smaller than epsilon. Otherwise same as v3_length().
  • vec3_t v3_norm_default(vec3_t v, vec3_t default_vector, float epsilon) Returns default_vector if the length of v is smaller than epsilon. Otherwise the same as v3_norm().
  • mat4_t m4_invert(mat4_t matrix) Matrix inversion that works with arbitrary matrices. m4_invert_affine() can already invert translation, rotation, scaling, mirroring, reflection and shearing matrices. So a general inversion might only be useful to invert projection matrices for picking. But with orthographic and perspective projection it's probably simpler to calculate the ray into the scene directly based on the screen coordinates.

VERSION HISTORY

v1.0 2016-02-15 Initial release

Function Documentation

◆ vec3()

static vec3_t vec3 ( float  x,
float  y,
float  z 
)
inlinestatic

bla bla

◆ v3_add()

static vec3_t v3_add ( vec3_t  a,
vec3_t  b 
)
inlinestatic

bla bla

◆ v3_adds()

static vec3_t v3_adds ( vec3_t  a,
float  s 
)
inlinestatic

bla bla

◆ v3_sub()

static vec3_t v3_sub ( vec3_t  a,
vec3_t  b 
)
inlinestatic

bla bla

◆ v3_subs()

static vec3_t v3_subs ( vec3_t  a,
float  s 
)
inlinestatic

bla bla

◆ v3_mul()

static vec3_t v3_mul ( vec3_t  a,
vec3_t  b 
)
inlinestatic

bla bla

◆ v3_muls()

static vec3_t v3_muls ( vec3_t  a,
float  s 
)
inlinestatic

bla bla

◆ v3_div()

static vec3_t v3_div ( vec3_t  a,
vec3_t  b 
)
inlinestatic

bla bla

◆ v3_divs()

static vec3_t v3_divs ( vec3_t  a,
float  s 
)
inlinestatic

bla bla

◆ v3_length()

static float v3_length ( vec3_t  v)
inlinestatic

bla bla

◆ v3_norm()

static vec3_t v3_norm ( vec3_t  v)
inlinestatic

bla bla

◆ v3_dot()

static float v3_dot ( vec3_t  a,
vec3_t  b 
)
inlinestatic

bla bla

◆ v3_proj()

static vec3_t v3_proj ( vec3_t  v,
vec3_t  onto 
)
inlinestatic

bla bla

◆ v3_cross()

static vec3_t v3_cross ( vec3_t  a,
vec3_t  b 
)
inlinestatic

bla bla

◆ v3_angle_between()

static float v3_angle_between ( vec3_t  a,
vec3_t  b 
)
inlinestatic

bla bla

◆ mat4()

static mat4_t mat4 ( float  m00,
float  m10,
float  m20,
float  m30,
float  m01,
float  m11,
float  m21,
float  m31,
float  m02,
float  m12,
float  m22,
float  m32,
float  m03,
float  m13,
float  m23,
float  m33 
)
inlinestatic

bla bla

◆ m4_identity()

static mat4_t m4_identity ( )
inlinestatic

bla bla

◆ m4_translation()

static mat4_t m4_translation ( vec3_t  offset)
inlinestatic

bla bla

◆ m4_scaling()

static mat4_t m4_scaling ( vec3_t  scale)
inlinestatic

bla bla

◆ m4_rotation_x()

static mat4_t m4_rotation_x ( float  angle_in_rad)
inlinestatic

bla bla

◆ m4_rotation_y()

static mat4_t m4_rotation_y ( float  angle_in_rad)
inlinestatic

bla bla

◆ m4_rotation_z()

static mat4_t m4_rotation_z ( float  angle_in_rad)
inlinestatic

bla bla

◆ m4_rotation()

mat4_t m4_rotation ( float  angle_in_rad,
vec3_t  axis 
)

Creates a matrix to rotate around an axis by a given angle. The axis doesn't need to be normalized.

Sources:

https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle

Parameters
angle_in_rad
axis
Returns
The rotation matrix

◆ m4_ortho_RH()

mat4_t m4_ortho_RH ( float  left,
float  right,
float  bottom,
float  top,
float  back,
float  front 
)

Creates an orthographic projection matrix. It maps the right handed cube defined by left, right, bottom, top, back and front onto the screen and z-buffer. You can think of it as a cube you move through world or camera space and everything inside is visible.

This is slightly different from the traditional glOrtho() and from the linked sources. These functions require the user to negate the last two arguments (creating a left-handed coordinate system). We avoid that here so you can think of this function as moving a right-handed cube through world space.

The arguments are ordered in a way that for each axis you specify the minimum followed by the maximum. Thats why it's bottom to top and back to front.

Implementation details:

To be more exact the right-handed cube is mapped into normalized device coordinates, a left-handed cube where (-1 -1) is the lower left corner, (1, 1) the upper right corner and a z-value of -1 is the nearest point and 1 the furthest point. OpenGL takes it from there and puts it on the screen and into the z-buffer.

Sources:

https://msdn.microsoft.com/en-us/library/windows/desktop/dd373965(v=vs.85).aspx https://unspecified.wordpress.com/2012/06/21/calculating-the-gluperspective-matrix-and-other-opengl-matrix-maths/

◆ m4_perspective_RH()

mat4_t m4_perspective_RH ( float  vertical_field_of_view_in_deg,
float  aspect_ratio,
float  near_view_distance,
float  far_view_distance 
)

Creates a perspective projection matrix for a camera.

The camera is at the origin and looks in the direction of the negative Z axis. near_view_distance and far_view_distance have to be positive and > 0. They are distances from the camera eye, not values on an axis.

near_view_distance can be small but not 0. 0 breaks the projection and everything ends up at the max value (far end) of the z-buffer. Making the z-buffer useless.

The matrix is the same as gluPerspective() builds. The view distance is mapped to the z-buffer with a reciprocal function (1/x). Therefore the z-buffer resolution for near objects is very good while resolution for far objects is limited.

Sources:

https://unspecified.wordpress.com/2012/06/21/calculating-the-gluperspective-matrix-and-other-opengl-matrix-maths/

◆ m4_look_at_RH()

mat4_t m4_look_at_RH ( vec3_t  from,
vec3_t  to,
vec3_t  up 
)

Builds a transformation matrix for a camera that looks from from towards to. up defines the direction that's upwards for the camera. All three vectors are given in world space and up doesn't need to be normalized.

Sources: Derived on whiteboard.

Implementation details:

  • * x, y and z are the right-handed base vectors of the cameras subspace. x has to be normalized because the cross product only produces a normalized output vector if both input vectors are orthogonal to each other. And up probably isn't orthogonal to z.

    These vectors are then used to build a 3x3 rotation matrix. This matrix rotates a vector by the same amount the camera is rotated. But instead we need to rotate all incoming vertices backwards by that amount. That's what a camera matrix is for: To move the world so that the camera is in the origin. So we take the inverse of that rotation matrix and in case of a rotation matrix this is just the transposed matrix. That's why the 3x3 part of the matrix are the x, y and z vectors but written horizontally instead of vertically.

    The translation is derived by creating a translation matrix to move the world into the origin (thats translate by minus from). The complete lookat matrix is then this translation followed by the rotation. Written as matrix multiplication:

    lookat = rotation * translation

    Since we're right-handed this equals to first doing the translation and after that doing the rotation. During that multiplication the rotation 3x3 part doesn't change but the translation vector is multiplied with each rotation axis. The dot product is just a more compact way to write the actual multiplications.

◆ m4_frustum()

mat4_t m4_frustum ( float  left,
float  right,
float  bottom,
float  top,
float  near,
float  far 
)

Some extra stuff by Emmanuel Thomas-Maurin

Frustum matrix Similar to Android OpenGL ES 2.0 frustum matrix: https://developer.android.com/reference/android/opengl/Matrix#frustumM(float[],%20int,%20float,%20float,%20float,%20float,%20float,%20float)

NOT USED SO FAR

◆ m4_transpose()

static mat4_t m4_transpose ( mat4_t  matrix)
inlinestatic

bla bla

◆ m4_mul()

static mat4_t m4_mul ( mat4_t  a,
mat4_t  b 
)
inlinestatic

Multiplication of two 4x4 matrices.

Implemented by following the row times column rule and illustrating it on a whiteboard with the proper indices in mind.

Further reading: https://en.wikipedia.org/wiki/Matrix_multiplication But note that the article use the first index for rows and the second for columns.

◆ m4_invert_affine()

mat4_t m4_invert_affine ( mat4_t  matrix)

Inverts an affine transformation matrix. That are translation, scaling, mirroring, reflection, rotation and shearing matrices or any combination of them.

Implementation details:

  • Invert the 3x3 part of the 4x4 matrix to handle rotation, scaling, etc. correctly (see source).
  • Invert the translation part of the 4x4 matrix by multiplying it with the inverted rotation matrix and negating it.

When a 3D point is multiplied with a transformation matrix it is first rotated and then translated. The inverted transformation matrix is the inverse translation followed by the inverse rotation. Written as a matrix multiplication (remember, the effect applies right to left):

inv(matrix) = inv(rotation) * inv(translation)

The inverse translation is a translation into the opposite direction, just the negative translation. The rotation part isn't changed by that multiplication but the translation part is multiplied by the inverse rotation matrix. It's the same situation as with m4_look_at(). But since we don't store the rotation matrix as 3D vectors we can't use the dot product and have to write the matrix multiplication operations by hand.

Sources for 3x3 matrix inversion:

https://www.khanacademy.org/math/precalculus/precalc-matrices/determinants-and-inverses-of-large-matrices/v/inverting-3x3-part-2-determinant-and-adjugate-of-a-matrix

◆ m4_mul_pos()

vec3_t m4_mul_pos ( mat4_t  matrix,
vec3_t  position 
)

Multiplies a 4x4 matrix with a 3D vector representing a point in 3D space.

Before the matrix multiplication the vector is first expanded to a 4D vector (x, y, z, 1). After the multiplication the vector is reduced to 3D again by dividing through the 4th component (if it's not 0 or 1).

◆ m4_mul_dir()

vec3_t m4_mul_dir ( mat4_t  matrix,
vec3_t  direction 
)

Multiplies a 4x4 matrix with a 3D vector representing a direction in 3D space.

Before the matrix multiplication the vector is first expanded to a 4D vector (x, y, z, 0). For directions the 4th component is set to 0 because directions are only rotated, not translated. After the multiplication the vector is reduced to 3D again by dividing through the 4th component (if it's not 0 or 1). This is necessary because the matrix might contains something other than (0, 0, 0, 1) in the bottom row which might set w to something other than 0 or 1.

◆ m4_print()

void m4_print ( mat4_t  matrix)

bla bla

◆ m4_printp()

void m4_printp ( mat4_t  matrix,
int  width,
int  precision 
)

bla bla

◆ m4_fprint()

void m4_fprint ( FILE *  stream,
mat4_t  matrix 
)

bla bla

◆ m4_fprintp()

void m4_fprintp ( FILE *  stream,
mat4_t  matrix,
int  width,
int  precision 
)

bla bla

◆ m4_print2()

void m4_print2 ( mat4_t  matrix,
const char *  line_start 
)

bla bla

◆ m4_printp2()

void m4_printp2 ( mat4_t  matrix,
int  width,
int  precision,
const char *  line_start 
)

bla bla

◆ m4_fprint2()

void m4_fprint2 ( FILE *  stream,
mat4_t  matrix,
const char *  line_start 
)

bla bla

◆ m4_fprintp2()

void m4_fprintp2 ( FILE *  stream,
mat4_t  matrix,
int  width,
int  precision,
const char *  line_start 
)

bla bla