From 98e3a3599ffe363eb03bf04e0aff2e37a06d813c Mon Sep 17 00:00:00 2001 From: 3gg <3gg@shellblade.net> Date: Fri, 24 Oct 2025 19:17:18 -0700 Subject: Less error-prone normalize --- include/math/vec2.h | 3 +-- include/math/vec3.h | 14 ++++++-------- include/math/vec4.h | 4 ++-- 3 files changed, 9 insertions(+), 12 deletions(-) (limited to 'include') diff --git a/include/math/vec2.h b/include/math/vec2.h index 5a56a94..7898edf 100644 --- a/include/math/vec2.h +++ b/include/math/vec2.h @@ -91,8 +91,7 @@ static inline R vec2_dist(vec2 a, vec2 b) { return sqrt(vec2_dist2(a, b)); } /// Return the given vector divided by its magnitude. static inline vec2 vec2_normalize(vec2 v) { const R n = vec2_norm(v); - assert(n > 0); - return (vec2){v.x / n, v.y / n}; + return (n > 0) ? (vec2){v.x / n, v.y / n} : (vec2){0, 0}; } /// Return the dot product of two vectors. diff --git a/include/math/vec3.h b/include/math/vec3.h index ee6d460..bb53cfb 100644 --- a/include/math/vec3.h +++ b/include/math/vec3.h @@ -99,8 +99,7 @@ static inline R vec3_dist(vec3 a, vec3 b) { return sqrt(vec3_dist2(a, b)); } /// Return the given vector divided by its magnitude. static inline vec3 vec3_normalize(vec3 v) { const R n = vec3_norm(v); - assert(n > 0); - return (vec3){v.x / n, v.y / n, v.z / n}; + return (n > 0) ? (vec3){v.x / n, v.y / n, v.z / n} : (vec3){0, 0, 0}; } /// Return the dot product of two vectors. @@ -110,8 +109,8 @@ static inline R vec3_dot(vec3 a, vec3 b) { /// Return the cross product of two vectors. static inline vec3 vec3_cross(vec3 a, vec3 b) { - return (vec3){ - a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; + return (vec3){a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, + a.x * b.y - a.y * b.x}; } /// Reflect the vector about the normal. @@ -137,10 +136,9 @@ static inline vec3 vec3_pow(vec3 v, R p) { /// Linearly interpolate two vectors. static inline vec3 vec3_lerp(vec3 a, vec3 b, R t) { - return (vec3){ - .x = a.x + t * (b.x - a.x), - .y = a.y + t * (b.y - a.y), - .z = a.z + t * (b.z - a.z)}; + return (vec3){.x = a.x + t * (b.x - a.x), + .y = a.y + t * (b.y - a.y), + .z = a.z + t * (b.z - a.z)}; } /// Interpolate two unit vectors using spherical linear interpolation. diff --git a/include/math/vec4.h b/include/math/vec4.h index 5a797f6..0e29807 100644 --- a/include/math/vec4.h +++ b/include/math/vec4.h @@ -91,8 +91,8 @@ static inline R vec4_dist(vec4 a, vec4 b) { return sqrt(vec4_dist2(a, b)); } /// Return the given vector divided by its magnitude. static inline vec4 vec4_normalize(vec4 v) { const R n = vec4_norm(v); - assert(n > 0); - return (vec4){v.x / n, v.y / n, v.z / n, v.w / n}; + return (n > 0) ? (vec4){v.x / n, v.y / n, v.z / n, v.w / n} + : (vec4){0, 0, 0, 0}; } /// Return the dot product of two vectors. -- cgit v1.2.3