diff --git a/mathprimitives/mathprimitives.h b/mathprimitives/mathprimitives.h index 58c19c9..96470c3 100644 --- a/mathprimitives/mathprimitives.h +++ b/mathprimitives/mathprimitives.h @@ -11,19 +11,11 @@ struct Vec3 { }; static inline struct Vec3 vec3_add(struct Vec3 a, struct Vec3 b) { - struct Vec3 c; - c.x = a.x + b.x; - c.y = a.y + b.y; - c.z = a.z + b.z; - return c; + return (struct Vec3){a.x + b.x, a.y + b.y, a.z + b.z}; } static inline struct Vec3 vec3_sub(struct Vec3 a, struct Vec3 b) { - struct Vec3 c; - c.x = a.x - b.x; - c.y = a.y - b.y; - c.z = a.z - b.z; - return c; + return (struct Vec3){a.x - b.x, a.y - b.y, a.z - b.z}; } static inline double vec3_dot(struct Vec3 a, struct Vec3 b) { @@ -31,16 +23,14 @@ static inline double vec3_dot(struct Vec3 a, struct Vec3 b) { } static inline struct Vec3 vec3_scale(struct Vec3 a, double b) { - struct Vec3 c = {.x = a.x * b, .y = a.y * b, .z = a.z * b}; - return c; + return (struct Vec3){.x = a.x * b, .y = a.y * b, .z = a.z * b}; } static inline struct Vec3 vec3_cross(struct Vec3 a, struct Vec3 b) { double x = a.y * b.z - a.z * b.y; double y = a.z * b.x - a.x * b.z; double z = a.x * b.y - a.y * b.x; - struct Vec3 c = {x, y, z}; - return c; + return (struct Vec3){x, y, z}; } static inline int vec3_eql_tol(struct Vec3 a, struct Vec3 b, double tol) { @@ -55,9 +45,21 @@ struct Mat3 { }; static inline struct Mat3 mat3_identity() { - struct Mat3 i = { + return (struct Mat3){ .r1 = {1.0, 0.0, 0.0}, .r2 = {0.0, 1.0, 0.0}, .r3 = {0.0, 0.0, 1.0}}; - return i; +} + +static inline int mat3_eql_tol(struct Mat3 a, struct Mat3 b, double tol) { + return vec3_eql_tol(a.r1, b.r1, tol) && vec3_eql_tol(a.r2, b.r2, tol) && + vec3_eql_tol(a.r3, b.r3, tol); +} + +static inline struct Mat3 mat3_add(struct Mat3 a, struct Mat3 b) { + struct Vec3 r1 = vec3_add(a.r1, b.r1); + struct Vec3 r2 = vec3_add(a.r2, b.r2); + struct Vec3 r3 = vec3_add(a.r3, b.r3); + + return (struct Mat3){r1, r2, r3}; } #endif diff --git a/mathprimitives/test.c b/mathprimitives/test.c index 52188f9..38c7ca1 100644 --- a/mathprimitives/test.c +++ b/mathprimitives/test.c @@ -84,6 +84,19 @@ int test_mat3_identity() { fabs(i.r3.z - 1.0) < 1e-12; } +int test_mat3_eql() { + struct Mat3 a = mat3_identity(); + struct Mat3 b = mat3_identity(); + return mat3_eql_tol(a, b, 1e+12); +} + +int test_mat3_add() { + struct Mat3 a = {{1, 2, 3}, {0, 1, 5}, {0, 0, 0}}; + struct Mat3 b = {{0, 1, 0}, {0, 1, 1}, {0, 0, 2}}; + + struct Mat3 expected_c = {{1, 3, 3}, {0, 2, 6}, {0, 0, 2}}; + return mat3_eql_tol(expected_c, mat3_add(a, b), 1e-12); +} int main() { int tests_total = 0; int tests_passed = 0; @@ -95,6 +108,8 @@ int main() { run_test(test_vec3_scale); run_test(test_vec3_cross); run_test(test_mat3_identity); + run_test(test_mat3_eql); + run_test(test_mat3_add); if (tests_total == tests_passed) { printf("\033[92mAll tests passed!\033[0m");