diff --git a/mathprimitives/mathprimitives.c b/mathprimitives/mathprimitives.c deleted file mode 100644 index 0c5820e..0000000 --- a/mathprimitives/mathprimitives.c +++ /dev/null @@ -1,28 +0,0 @@ -#include "mathprimitives.h" - -struct Mat3 mat3_inv(struct Mat3 a) { - double inv_det = 1.0 / mat3_det(a); - struct Vec3 r1 = vec3_scale( - (struct Vec3){ - a.r2.y * a.r3.z - a.r2.z * a.r3.y, - a.r1.z * a.r3.y - a.r1.y * a.r3.z, - a.r1.y * a.r2.z - a.r1.z * a.r2.y, - }, - inv_det); - struct Vec3 r2 = vec3_scale( - (struct Vec3){ - a.r2.z * a.r3.x - a.r2.x * a.r3.z, - a.r1.x * a.r3.z - a.r1.z * a.r3.x, - a.r1.z * a.r2.x - a.r1.x * a.r2.z, - }, - inv_det); - struct Vec3 r3 = vec3_scale( - (struct Vec3){ - a.r2.x * a.r3.y - a.r2.y * a.r3.x, - a.r1.y * a.r3.x - a.r1.x * a.r3.y, - a.r1.x * a.r2.y - a.r1.y * a.r2.x, - }, - inv_det); - - return (struct Mat3){r1, r2, r3}; -} diff --git a/mathprimitives/mathprimitives.h b/mathprimitives/mathprimitives.h index 86c0d88..633e52f 100644 --- a/mathprimitives/mathprimitives.h +++ b/mathprimitives/mathprimitives.h @@ -98,6 +98,39 @@ static inline double mat3_det(struct Mat3 a) { a.r1.z * (a.r2.x * a.r3.y - a.r2.y * a.r3.x); } -struct Mat3 mat3_inv(struct Mat3 a); +static struct Mat3 mat3_inv(struct Mat3 a) { + double inv_det = 1.0 / mat3_det(a); + struct Vec3 r1 = vec3_scale( + (struct Vec3){ + a.r2.y * a.r3.z - a.r2.z * a.r3.y, + a.r1.z * a.r3.y - a.r1.y * a.r3.z, + a.r1.y * a.r2.z - a.r1.z * a.r2.y, + }, + inv_det); + struct Vec3 r2 = vec3_scale( + (struct Vec3){ + a.r2.z * a.r3.x - a.r2.x * a.r3.z, + a.r1.x * a.r3.z - a.r1.z * a.r3.x, + a.r1.z * a.r2.x - a.r1.x * a.r2.z, + }, + inv_det); + struct Vec3 r3 = vec3_scale( + (struct Vec3){ + a.r2.x * a.r3.y - a.r2.y * a.r3.x, + a.r1.y * a.r3.x - a.r1.x * a.r3.y, + a.r1.x * a.r2.y - a.r1.y * a.r2.x, + }, + inv_det); + + return (struct Mat3){r1, r2, r3}; +} + +static inline struct Vec3 mat3_mul_vec(struct Mat3 a, struct Vec3 b) { + return (struct Vec3){ + vec3_dot(a.r1, b), + vec3_dot(a.r2, b), + vec3_dot(a.r3, b), + }; +} #endif diff --git a/mathprimitives/test.c b/mathprimitives/test.c index a7a42cf..a906ad7 100644 --- a/mathprimitives/test.c +++ b/mathprimitives/test.c @@ -135,6 +135,19 @@ int test_mat3_inv() { return mat3_eql_tol(inv_a, expected_inv, 1e-11); } +int test_mat3_mul_vec3() { + struct Mat3 a = { + {0.0, 1.0, 0.0}, + {0.0, 1.0, 1.0}, + {0.0, 0.0, 1.0}, + }; + + struct Vec3 b = {1.0, 2.0, 3.0}; + struct Vec3 expected_c = {2.0, 5.0, 3.0}; + + return vec3_eql_tol(expected_c, mat3_mul_vec(a, b), 1e-12); +} + int main() { int tests_total = 0; int tests_passed = 0; @@ -152,6 +165,7 @@ int main() { run_test(test_mat3_mul); run_test(test_mat3_det); run_test(test_mat3_inv); + run_test(test_mat3_mul_vec3); if (tests_total == tests_passed) { printf("\033[92mAll tests passed!\033[0m");