Skip to content

Commit

Permalink
add CmpToZero and MagnitudeSquared traits
Browse files Browse the repository at this point in the history
  • Loading branch information
jcornaz committed Aug 2, 2023
1 parent fe3297a commit c28e28f
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 21 deletions.
7 changes: 2 additions & 5 deletions src/gjk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vec2, Vec2>,
Expand Down Expand Up @@ -110,7 +107,7 @@ impl Simplex<Vec2> {
fn perp<V>(axis: V, direction: V) -> V
where
V: Copy + Perp + Neg<Output = V> + Dot,
<V as Dot>::Scalar: IsNegative,
<V as Dot>::Scalar: CmpToZero,
{
let perp = axis.perp();
if perp.dot(direction).is_negative() {
Expand Down
10 changes: 0 additions & 10 deletions src/math/glam_0_24.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
52 changes: 46 additions & 6 deletions src/math/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<V: Dot + Copy> MagnitudeSquared for V {
type Scalar = <V as Dot>::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);
}
}

0 comments on commit c28e28f

Please sign in to comment.