From 83ee6de1dadf5a0321610e80d5374f0e4fa6dc91 Mon Sep 17 00:00:00 2001 From: irate Date: Tue, 5 Dec 2023 03:44:27 +0100 Subject: [PATCH] Remove `From` implementations from the direction types (#10857) This removes the `From` implementations for the direction types. It doesn't seem right to have when it only works if the vector is nonzero and finite and produces NaN otherwise. Added `Direction2d/3d::new` which uses `Vec2/3::try_normalize` to guarantee it returns either a valid direction or `None`. This should make it impossible to create an invalid direction, which I think was the intention with these types. --- crates/bevy_math/src/primitives/dim2.rs | 13 +++++++------ crates/bevy_math/src/primitives/dim3.rs | 13 +++++++------ 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/crates/bevy_math/src/primitives/dim2.rs b/crates/bevy_math/src/primitives/dim2.rs index 35e5363dc6..a60cd3d619 100644 --- a/crates/bevy_math/src/primitives/dim2.rs +++ b/crates/bevy_math/src/primitives/dim2.rs @@ -5,13 +5,14 @@ use crate::Vec2; #[derive(Clone, Copy, Debug)] pub struct Direction2d(Vec2); -impl From for Direction2d { - fn from(value: Vec2) -> Self { - Self(value.normalize()) - } -} - impl Direction2d { + /// Create a direction from a finite, nonzero [`Vec2`]. + /// + /// Returns `None` if the input is zero (or very close to zero), or non-finite. + pub fn new(value: Vec2) -> Option { + value.try_normalize().map(Self) + } + /// Create a direction from a [`Vec2`] that is already normalized pub fn from_normalized(value: Vec2) -> Self { debug_assert!(value.is_normalized()); diff --git a/crates/bevy_math/src/primitives/dim3.rs b/crates/bevy_math/src/primitives/dim3.rs index 891f51558f..60594c8824 100644 --- a/crates/bevy_math/src/primitives/dim3.rs +++ b/crates/bevy_math/src/primitives/dim3.rs @@ -5,13 +5,14 @@ use crate::Vec3; #[derive(Clone, Copy, Debug)] pub struct Direction3d(Vec3); -impl From for Direction3d { - fn from(value: Vec3) -> Self { - Self(value.normalize()) - } -} - impl Direction3d { + /// Create a direction from a finite, nonzero [`Vec3`]. + /// + /// Returns `None` if the input is zero (or very close to zero), or non-finite. + pub fn new(value: Vec3) -> Option { + value.try_normalize().map(Self) + } + /// Create a direction from a [`Vec3`] that is already normalized pub fn from_normalized(value: Vec3) -> Self { debug_assert!(value.is_normalized());