From c28e28f6be11f2c77e6a184ef88df4674f6ccf6b Mon Sep 17 00:00:00 2001 From: Jonathan Cornaz Date: Wed, 2 Aug 2023 14:14:09 +0200 Subject: [PATCH] add `CmpToZero` and `MagnitudeSquared` traits --- src/gjk.rs | 7 ++---- src/math/glam_0_24.rs | 10 --------- src/math/mod.rs | 52 ++++++++++++++++++++++++++++++++++++++----- 3 files changed, 48 insertions(+), 21 deletions(-) diff --git a/src/gjk.rs b/src/gjk.rs index f545e99..78b87b8 100644 --- a/src/gjk.rs +++ b/src/gjk.rs @@ -2,10 +2,7 @@ use core::{cmp::Ordering, ops::Neg}; use glam::Vec2; -use crate::{ - math::{Dot, IsNegative, Perp}, - Support, -}; +use crate::{math::*, Support}; pub(crate) fn find_simplex_enclosing_origin( shape: &impl Support, @@ -110,7 +107,7 @@ impl Simplex { fn perp(axis: V, direction: V) -> V where V: Copy + Perp + Neg + Dot, - ::Scalar: IsNegative, + ::Scalar: CmpToZero, { let perp = axis.perp(); if perp.dot(direction).is_negative() { diff --git a/src/math/glam_0_24.rs b/src/math/glam_0_24.rs index b47ddbc..86cba30 100644 --- a/src/math/glam_0_24.rs +++ b/src/math/glam_0_24.rs @@ -9,16 +9,6 @@ impl Dot for Vec2 { } } -impl Zero for Vec2 { - const ZERO: Self = Vec2::ZERO; -} - -impl IsNegative for f32 { - fn is_negative(&self) -> bool { - *self < 0.0 - } -} - impl Perp for Vec2 { fn perp(self) -> Self { Vec2::perp(self) diff --git a/src/math/mod.rs b/src/math/mod.rs index 83c271d..a01a34c 100644 --- a/src/math/mod.rs +++ b/src/math/mod.rs @@ -6,14 +6,54 @@ pub(crate) trait Dot { fn dot(self, other: Self) -> Self::Scalar; } -pub(crate) trait Zero { - const ZERO: Self; -} - -pub(crate) trait IsNegative { - fn is_negative(&self) -> bool; +pub(crate) trait CmpToZero: Copy { + fn is_negative(self) -> bool; + fn is_zero(self) -> bool; + fn is_positive(self) -> bool; } pub(crate) trait Perp { fn perp(self) -> Self; } + +pub(crate) trait MagnitudeSquared { + type Scalar; + fn magnitude_squared(self) -> Self::Scalar; +} + +impl MagnitudeSquared for V { + type Scalar = ::Scalar; + fn magnitude_squared(self) -> Self::Scalar { + self.dot(self) + } +} + +impl CmpToZero for f32 { + fn is_negative(self) -> bool { + self < 0.0 + } + + fn is_zero(self) -> bool { + self == 0.0 + } + + fn is_positive(self) -> bool { + self > 0.0 + } +} + +#[cfg(test)] +mod tests { + use super::*; + use approx::assert_ulps_eq; + use rstest::rstest; + + #[rstest] + #[case([0.0, 0.0], 0.0)] + #[case([2.0, 3.0], 13.0)] + #[case([3.0, 4.0], 25.0)] + #[case([4.0, 3.0], 25.0)] + fn test_magnitude_squared(#[case] vector: [f32; 2], #[case] expected: f32) { + assert_ulps_eq!(vector.magnitude_squared(), expected); + } +}