From 21c92685a53bffcf53436cd02427f2f01ec097a5 Mon Sep 17 00:00:00 2001 From: Jonathan Flueren Date: Tue, 12 Apr 2022 19:14:11 +0200 Subject: [PATCH] 2nd --- src/main.rs | 6 ++++++ src/vec3.rs | 49 +++++++++++++++++++++++++++++++++++++++++++------ 2 files changed, 49 insertions(+), 6 deletions(-) diff --git a/src/main.rs b/src/main.rs index 913f0ca..645ccc4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,6 @@ +mod vec3; +use vec3::Vec3; + fn main() { let image_width = 256; let image_height = 256; @@ -19,4 +22,7 @@ fn main() { } } eprintln!("\nDone!"); + + let v = Vec3::new(1.0,2.0,3.0); + println!("{:?}",v) } diff --git a/src/vec3.rs b/src/vec3.rs index 469f019..342de9b 100644 --- a/src/vec3.rs +++ b/src/vec3.rs @@ -1,5 +1,9 @@ -struct Vec3 { - pub e: [f64: 3], +use std::ops::*; +use std::io::Write; + +#[derive(Clone, Copy, Debug)] +pub struct Vec3 { + pub e: [f64; 3], } type Color = Vec3; @@ -11,7 +15,7 @@ impl Vec3 { Vec3 { e: [x, y, z] } } - pub fn length() -> f64 { + pub fn length(&self) -> f64 { self.length_squared().sqrt() } @@ -21,6 +25,20 @@ impl Vec3 { + self.e[2]*self.e[2] } + pub fn cross(a: Vec3, b: Vec3) -> Vec3 { + Vec3::new(a.y()*b.z() - a.z()*b.y(), + a.z()*b.x() - a.x()*b.z(), + a.x()*b.y() - a.y()*b.x()) + } + + pub fn dot(a: Vec3, b: Vec3) -> f64 { + a.x()*b.x() + a.y()*b.y() + a.z()*b.z() + } + + pub fn unit_vector(a: Vec3) -> Vec3 { + a / a.length() + } + pub fn x(&self) -> f64 { self.e[0] } pub fn y(&self) -> f64 { self.e[1] } pub fn z(&self) -> f64 { self.e[2] } @@ -30,7 +48,7 @@ impl Add for Vec3 { type Output = Vec3; fn add(self, rhs: Self) -> Vec3 { - Vec3::new(self.x()+rhs.x(), self.y()+rhs.y(), self.z()+rhs.z()); + Vec3::new(self.x()+rhs.x(), self.y()+rhs.y(), self.z()+rhs.z()) } } @@ -50,11 +68,19 @@ impl Sub for Vec3 { } } +impl SubAssign for Vec3 { + fn sub_assign(&mut self, rhs: Self) { + self.e[0] -= rhs.x(); + self.e[1] -= rhs.y(); + self.e[2] -= rhs.z(); + } +} + impl Mul for f64 { type Output = Vec3; fn mul(self, rhs: Vec3) -> Vec3 { - Vec3::new(self*rhs.x(), self*rhs.y(), self*rhs.z()); + Vec3::new(self*rhs.x(), self*rhs.y(), self*rhs.z()) } } @@ -67,10 +93,21 @@ impl MulAssign for Vec3 { } impl DivAssign for Vec3 { - fn div_assign(&mul self, rhs: f64) { + fn div_assign(&mut self, rhs: f64) { self.e[0] /= rhs; self.e[1] /= rhs; self.e[2] /= rhs; } } +impl Div for Vec3 { + type Output = Vec3; + + fn div(self, rhs: f64) -> Vec3 { + Vec3::new(self.x()/rhs, self.y()/rhs, self.z()/rhs) + } +} + +fn write_color(out: &mut impl Write, pixel_color: Color) { + write!(out, "{} {} {}\n", 255.999*pixel_color.x(), 255.999*pixel_color.y(), 255.999*pixel_color.z()); +} \ No newline at end of file