From 07651817dc2ec3fc6c4c92aa7f27659573e48473 Mon Sep 17 00:00:00 2001 From: Matthew Gordon Date: Fri, 21 Mar 2025 20:51:50 -0300 Subject: [PATCH] Implement divide-by-scalar for Vec3 --- src/math/vec3.rs | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/src/math/vec3.rs b/src/math/vec3.rs index 3914f49..d5c8fb0 100644 --- a/src/math/vec3.rs +++ b/src/math/vec3.rs @@ -2,7 +2,7 @@ use super::Mat3; use itertools::izip; -use std::ops::{Add, AddAssign, Index, IndexMut, Mul, MulAssign, Neg, Sub, SubAssign}; +use std::ops::{Add, AddAssign, Div, Index, IndexMut, Mul, MulAssign, Neg, Sub, SubAssign}; #[derive(Copy, Clone, PartialEq, Debug, Default)] pub struct Vec3 { @@ -316,6 +316,30 @@ impl Mul<&Vec3> for f64 { } } +impl Div for &Vec3 { + type Output = Vec3; + + fn div(self, rhs: f64) -> Vec3 { + let mut coords = [0.0; 3]; + for (r, a) in coords.iter_mut().zip(self.coords.iter()) { + *r = a / rhs; + } + Vec3 { coords } + } +} + +impl Div for Vec3 { + type Output = Vec3; + + fn div(self, rhs: f64) -> Vec3 { + let mut coords = [0.0; 3]; + for (r, a) in coords.iter_mut().zip(self.coords.iter()) { + *r = a / rhs; + } + Vec3 { coords } + } +} + #[cfg(test)] mod tests { use super::*; @@ -459,6 +483,14 @@ mod tests { assert!(a * b == c); } + #[test] + fn div_by_scalar_returns_correct_result() { + let a = Vec3::new(1.0, 2.0, 3.0); + let b = 2.0; + let c = Vec3::new(0.5, 1.0, 1.5); + assert!(dbg!(a / b) == dbg!(c)); + } + #[test] fn mul_assign_by_scalar_returns_correct_result() { let mut a = Vec3::new(1.0, 2.0, 3.0);