use super::*;
#[allow(non_camel_case_types)]
#[repr(C)]
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub struct vec3<T>(pub T, pub T, pub T);
impl<T: std::fmt::Display> std::fmt::Display for vec3<T> {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(fmt, "({}, {}, {})", self.x, self.y, self.z)
}
}
impl<T> From<[T; 3]> for vec3<T> {
fn from(v: [T; 3]) -> vec3<T> {
let [x, y, z] = v;
vec3(x, y, z)
}
}
pub struct XYZ<T> {
#[allow(missing_docs)]
pub x: T,
#[allow(missing_docs)]
pub y: T,
#[allow(missing_docs)]
pub z: T,
}
impl<T> Deref for XYZ<T> {
type Target = [T; 3];
fn deref(&self) -> &[T; 3] {
unsafe { std::mem::transmute(self) }
}
}
impl<T> DerefMut for XYZ<T> {
fn deref_mut(&mut self) -> &mut [T; 3] {
unsafe { std::mem::transmute(self) }
}
}
impl<T> Deref for vec3<T> {
type Target = XYZ<T>;
fn deref(&self) -> &XYZ<T> {
unsafe { std::mem::transmute(self) }
}
}
impl<T> DerefMut for vec3<T> {
fn deref_mut(&mut self) -> &mut XYZ<T> {
unsafe { std::mem::transmute(self) }
}
}
impl<T> vec3<T> {
pub fn xy(self) -> vec2<T> {
vec2(self.0, self.1)
}
pub fn extend(self, w: T) -> vec4<T> {
vec4(self.0, self.1, self.2, w)
}
pub fn map<U, F: Fn(T) -> U>(self, f: F) -> vec3<U> {
vec3(f(self.0), f(self.1), f(self.2))
}
pub fn zip<U>(self, v: vec3<U>) -> vec3<(T, U)> {
vec3((self.0, v.0), (self.1, v.1), (self.2, v.2))
}
}
impl<T: Clone> vec3<T> {
pub fn splat(value: T) -> Self {
Self(value.clone(), value.clone(), value)
}
}
impl<T: UNum> vec3<T> {
pub const ZERO: Self = vec3(T::ZERO, T::ZERO, T::ZERO);
pub const UNIT_X: Self = Self(T::ONE, T::ZERO, T::ZERO);
pub const UNIT_Y: Self = Self(T::ZERO, T::ONE, T::ZERO);
pub const UNIT_Z: Self = Self(T::ZERO, T::ZERO, T::ONE);
}
impl<T: Copy + Num> vec3<T> {
pub fn dot(a: Self, b: Self) -> T {
a.x * b.x + a.y * b.y + a.z * b.z
}
pub fn cross(a: Self, b: Self) -> Self {
vec3(
a.y * b.z - a.z * b.y,
a.z * b.x - a.x * b.z,
a.x * b.y - a.y * b.x,
)
}
}
impl<T: Float> vec3<T> {
pub fn normalize(self) -> Self {
self / self.len()
}
pub fn normalize_or_zero(self) -> Self {
let len = self.len();
if len.approx_eq(&T::ZERO) {
vec3::ZERO
} else {
self / len
}
}
pub fn len(self) -> T {
T::sqrt(self.len_sqr())
}
pub fn len_sqr(self) -> T {
vec3::dot(self, self)
}
pub fn into_2d(self) -> vec2<T> {
self.xy() / self.z
}
pub fn clamp_len(self, len_range: impl FixedRangeBounds<T>) -> Self {
let len = self.len();
let target_len = len.clamp_range(len_range);
if len == target_len {
self
} else {
self * target_len / len
}
}
pub fn clamp_coordinates(
self,
x_range: impl FixedRangeBounds<T>,
y_range: impl FixedRangeBounds<T>,
z_range: impl FixedRangeBounds<T>,
) -> Self {
vec3(
self.x.clamp_range(x_range),
self.y.clamp_range(y_range),
self.z.clamp_range(z_range),
)
}
pub fn transform(self, transform: mat4<T>) -> Self {
(transform * self.extend(T::ONE)).into_3d()
}
}