Implement divide-by-scalar for Vec3

This commit is contained in:
Matthew Gordon 2025-03-21 20:51:50 -03:00
parent c1a79e7893
commit 07651817dc
1 changed files with 33 additions and 1 deletions

View File

@ -2,7 +2,7 @@ use super::Mat3;
use itertools::izip; 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)] #[derive(Copy, Clone, PartialEq, Debug, Default)]
pub struct Vec3 { pub struct Vec3 {
@ -316,6 +316,30 @@ impl Mul<&Vec3> for f64 {
} }
} }
impl Div<f64> 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<f64> 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)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@ -459,6 +483,14 @@ mod tests {
assert!(a * b == c); 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] #[test]
fn mul_assign_by_scalar_returns_correct_result() { fn mul_assign_by_scalar_returns_correct_result() {
let mut a = Vec3::new(1.0, 2.0, 3.0); let mut a = Vec3::new(1.0, 2.0, 3.0);