Finish basic vec3 and start on mat3

This commit is contained in:
Alex Selimov 2026-10-23 23:01:53 -04:00
parent 2ff1e0791b
commit 519fbd131a
2 changed files with 57 additions and 1 deletions

View file

@ -30,9 +30,34 @@ static inline double vec3_dot(struct Vec3 a, struct Vec3 b) {
return a.x * b.x + a.y * b.y + a.z * b.z; return a.x * b.x + a.y * b.y + a.z * b.z;
} }
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;
}
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;
}
static inline int vec3_eql_tol(struct Vec3 a, struct Vec3 b, double tol) { static inline int vec3_eql_tol(struct Vec3 a, struct Vec3 b, double tol) {
return fabs(a.x - b.x) < tol && fabs(a.y - b.y) < tol && return fabs(a.x - b.x) < tol && fabs(a.y - b.y) < tol &&
fabs(a.z - b.z) < tol; fabs(a.z - b.z) < tol;
} }
struct Mat3 {
struct Vec3 r1;
struct Vec3 r2;
struct Vec3 r3;
};
static inline struct Mat3 mat3_identity() {
struct Mat3 i = {
.r1 = {1.0, 0.0, 0.0}, .r2 = {0.0, 1.0, 0.0}, .r3 = {0.0, 0.0, 1.0}};
return i;
}
#endif #endif

View file

@ -55,6 +55,35 @@ int test_vec3_dot() {
return fabs(real_dot - expected_dot) < 1e-12; return fabs(real_dot - expected_dot) < 1e-12;
} }
int test_vec3_scale() {
struct Vec3 a = {.x = 1.0, .y = 2.0, .z = 3.0};
double b = 3.0;
struct Vec3 expected_c = {.x = 3.0, .y = 6.0, .z = 9.0};
struct Vec3 real_c = vec3_scale(a, b);
return vec3_eql_tol(expected_c, real_c, 1e-12);
}
int test_vec3_cross() {
struct Vec3 a = {.x = 1.0, .y = 2.0, .z = 3.0};
struct Vec3 b = {.x = 3.0, .y = 1.0, .z = 0.0};
struct Vec3 expected_c = {.x = -3.0, .y = 9.0, .z = -5.0};
struct Vec3 real_c = vec3_cross(a, b);
return vec3_eql_tol(expected_c, real_c, 1e-12);
}
int test_mat3_identity() {
struct Mat3 i = mat3_identity();
return fabs(i.r1.x - 1.0) < 1e-12 && fabs(i.r1.y - 0.0) < 1e-12 &&
fabs(i.r1.z - 0.0) < 1e-12 && fabs(i.r2.x - 0.0) < 1e-12 &&
fabs(i.r2.y - 1.0) < 1e-12 && fabs(i.r2.z - 0.0) < 1e-12 &&
fabs(i.r3.x - 0.0) < 1e-12 && fabs(i.r3.y - 0.0) < 1e-12 &&
fabs(i.r3.z - 1.0) < 1e-12;
}
int main() { int main() {
int tests_total = 0; int tests_total = 0;
int tests_passed = 0; int tests_passed = 0;
@ -63,11 +92,13 @@ int main() {
run_test(test_vec3_add); run_test(test_vec3_add);
run_test(test_vec3_sub); run_test(test_vec3_sub);
run_test(test_vec3_dot); run_test(test_vec3_dot);
run_test(test_vec3_scale);
run_test(test_vec3_cross);
run_test(test_mat3_identity);
if (tests_total == tests_passed) { if (tests_total == tests_passed) {
printf("\033[92mAll tests passed!\033[0m"); printf("\033[92mAll tests passed!\033[0m");
} else { } else {
printf("\033[91m%d of %d tests failed\033[0m", tests_total - tests_passed, printf("\033[91m%d of %d tests failed\033[0m", tests_total - tests_passed,
tests_total); tests_total);
} }