Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow creation of random Rotation2d #13684

Merged
merged 2 commits into from
Jun 5, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions crates/bevy_math/src/sampling/standard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
//! ```
//! # use rand::{random, Rng, SeedableRng, rngs::StdRng, distributions::Standard};
//! # use bevy_math::{Dir3, sampling::FromRng};
//! let mut rng = StdRng::from_entropy();
//! let mut rng = StdRng::seed_from_u64(7313429298);
//! // Random direction using thread-local rng
//! let random_direction1: Dir3 = random();
//!
Expand All @@ -21,9 +21,11 @@
//! let many_random_directions: Vec<Dir3> = rng.sample_iter(Standard).take(5).collect();
//! ```

use std::f32::consts::TAU;

use crate::{
primitives::{Circle, Sphere},
Dir2, Dir3, Dir3A, Quat, ShapeSample, Vec3A,
Dir2, Dir3, Dir3A, Quat, Rotation2d, ShapeSample, Vec3A,
};
use rand::{
distributions::{Distribution, Standard},
Expand All @@ -37,7 +39,7 @@ use rand::{
/// ```
/// # use rand::{Rng, SeedableRng, rngs::StdRng};
/// # use bevy_math::{Dir3, sampling::FromRng};
/// let mut rng = StdRng::from_entropy();
/// let mut rng = StdRng::seed_from_u64(451);
/// let random_dir = Dir3::from_rng(&mut rng);
/// ```
pub trait FromRng
Expand All @@ -52,6 +54,7 @@ where
}

impl Distribution<Dir2> for Standard {
#[inline]
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Dir2 {
let circle = Circle::new(1.0);
let vector = circle.sample_boundary(rng);
Expand All @@ -62,6 +65,7 @@ impl Distribution<Dir2> for Standard {
impl FromRng for Dir2 {}

impl Distribution<Dir3> for Standard {
#[inline]
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Dir3 {
let sphere = Sphere::new(1.0);
let vector = sphere.sample_boundary(rng);
Expand All @@ -72,6 +76,7 @@ impl Distribution<Dir3> for Standard {
impl FromRng for Dir3 {}

impl Distribution<Dir3A> for Standard {
#[inline]
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Dir3A {
let sphere = Sphere::new(1.0);
let vector: Vec3A = sphere.sample_boundary(rng).into();
Expand All @@ -81,4 +86,14 @@ impl Distribution<Dir3A> for Standard {

impl FromRng for Dir3A {}

impl Distribution<Rotation2d> for Standard {
#[inline]
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Rotation2d {
let angle = rng.gen_range(0.0..TAU);
Rotation2d::radians(angle)
}
}

impl FromRng for Rotation2d {}

impl FromRng for Quat {}