use core::f32::consts::{PI, TAU};
use crate::{ops, Dir2, Dir3, Dir3A, Quat, Rot2, Vec2, Vec3};
use rand::{
distr::{Distribution, StandardUniform},
RngExt,
};
pub trait FromRng
where
Self: Sized,
StandardUniform: Distribution<Self>,
{
fn from_rng<R: RngExt + ?Sized>(rng: &mut R) -> Self {
rng.random()
}
}
impl Distribution<Dir2> for StandardUniform {
#[inline]
fn sample<R: RngExt + ?Sized>(&self, rng: &mut R) -> Dir2 {
let theta = rng.random_range(0.0..TAU);
let (sin, cos) = ops::sin_cos(theta);
let vector = Vec2::new(cos, sin);
Dir2::new_unchecked(vector)
}
}
#[inline]
fn sample_unit_sphere_boundary<R: RngExt + ?Sized>(rng: &mut R) -> Vec3 {
let z = rng.random_range(-1f32..=1f32);
let (a_sin, a_cos) = ops::sin_cos(rng.random_range(-PI..=PI));
let c = ops::sqrt(1f32 - z * z);
let x = a_sin * c;
let y = a_cos * c;
Vec3::new(x, y, z)
}
impl FromRng for Dir2 {}
impl Distribution<Dir3> for StandardUniform {
#[inline]
fn sample<R: RngExt + ?Sized>(&self, rng: &mut R) -> Dir3 {
let vector = sample_unit_sphere_boundary(rng);
Dir3::new_unchecked(vector)
}
}
impl FromRng for Dir3 {}
impl Distribution<Dir3A> for StandardUniform {
#[inline]
fn sample<R: RngExt + ?Sized>(&self, rng: &mut R) -> Dir3A {
let vector = sample_unit_sphere_boundary(rng);
Dir3A::new_unchecked(vector.to_vec3a())
}
}
impl FromRng for Dir3A {}
impl Distribution<Rot2> for StandardUniform {
#[inline]
fn sample<R: RngExt + ?Sized>(&self, rng: &mut R) -> Rot2 {
let angle = rng.random_range(0.0..TAU);
Rot2::radians(angle)
}
}
impl FromRng for Rot2 {}
impl FromRng for Quat {}