use std::{ fmt::Display, ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}, }; use numtoa::NumToA; pub type Point3 = Vec3; pub type Colour = Vec3; #[derive(Debug, Clone, Copy)] pub struct Vec3 { pub x: f64, pub y: f64, pub z: f64, } impl Vec3 { pub fn new(x: f64, y: f64, z: f64) -> Self { Self { x, y, z } } #[inline] pub fn length(&self) -> f64 { f64::sqrt(self.length_squared()) } #[inline] pub fn length_squared(&self) -> f64 { self.x * self.x + self.y * self.y + self.z * self.z } #[inline] pub fn unit_vector(self) -> Vec3 { self / self.length() } #[inline] pub fn dot(&self, rhs: &Self) -> f64 { self.x * rhs.x + self.y * rhs.y + self.z * rhs.z } #[inline] pub fn cross(&self, rhs: &Self) -> Self { Vec3::new( self.y * rhs.z - self.z * rhs.y, self.z * rhs.x - self.x * rhs.z, self.x * rhs.y - self.y * rhs.x, ) } /// Pushes it self onto buffer (appending to the end) /// numtoa_buffer is required to be at least [3] in size #[inline] pub fn write_as_u8(&self, buffer: &mut String, numtoa_buffer: &mut [u8]) { let red = (255.999 * self.x) as u8; let green = (255.999 * self.y) as u8; let blue = (255.999 * self.z) as u8; // We are using numtoa to skip the allocating a string when using fmt // Using push_str is faster then using fmt::write as well buffer.push_str(red.numtoa_str(10, numtoa_buffer)); buffer.push(' '); buffer.push_str(green.numtoa_str(10, numtoa_buffer)); buffer.push(' '); buffer.push_str(blue.numtoa_str(10, numtoa_buffer)); buffer.push_str(" "); } } // -Vec3 impl Neg for Vec3 { type Output = Vec3; fn neg(self) -> Vec3 { Vec3::new(-self.x, -self.y, -self.z) } } // Vec3 += Vec3 impl AddAssign for Vec3 { fn add_assign(&mut self, v: Vec3) { *self = *self + v; } } // Vec3 *= f64 impl MulAssign for Vec3 { fn mul_assign(&mut self, t: f64) { *self = *self * t; } } // Vec3 /= f64 impl DivAssign for Vec3 { fn div_assign(&mut self, t: f64) { *self = *self / t; } } // Vec3 + Vec3 impl Add for Vec3 { type Output = Vec3; fn add(self, v: Vec3) -> Vec3 { Vec3::new(self.x + v.x, self.y + v.y, self.z + v.z) } } // Vec3 - Vec3 impl Sub for Vec3 { type Output = Vec3; fn sub(self, v: Vec3) -> Vec3 { Vec3::new(self.x - v.x, self.y - v.y, self.z - v.z) } } // Vec3 * Vec3 impl Mul for Vec3 { type Output = Vec3; fn mul(self, v: Vec3) -> Vec3 { Vec3::new(self.x * v.x, self.y * v.y, self.z * v.z) } } // f64 * Vec3 impl Mul for f64 { type Output = Vec3; fn mul(self, v: Vec3) -> Vec3 { Vec3::new(self * v.x, self * v.y, self * v.z) } } // Vec3 * f64 impl Mul for Vec3 { type Output = Vec3; fn mul(self, t: f64) -> Vec3 { Vec3::new(self.x * t, self.y * t, self.z * t) } } // Vec3 / f64 impl Div for Vec3 { type Output = Vec3; fn div(self, t: f64) -> Vec3 { Vec3::new(self.x / t, self.y / t, self.z / t) } } impl Display for Vec3 { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{{ x: {}, y: {}, z: {} }}", self.x, self.y, self.z) } }