rust-kurs/src/math.rs
2026-05-13 18:23:12 +02:00

125 lines
2.4 KiB
Rust

use std::ops::{Add, Div, Mul, Sub};
#[derive(Copy, Clone, PartialEq, Debug)]
pub struct Vector3 {
x: f64,
y: f64,
z: f64,
}
impl Vector3 {
pub fn new(x: f64, y: f64, z: f64) -> Vector3 {
Vector3 { x, y, z }
}
}
impl Add for Vector3 {
type Output = Vector3;
fn add(self, rhs: Vector3) -> Self::Output {
Vector3::new(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z)
}
}
impl Sub for Vector3 {
type Output = Vector3;
fn sub(self, rhs: Vector3) -> Self::Output {
Vector3::new(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z)
}
}
impl Mul<f64> for Vector3 {
type Output = Vector3;
fn mul(self, rhs: f64) -> Self::Output {
Vector3::new(self.x * rhs, self.y * rhs, self.z * rhs)
}
}
impl Mul<Vector3> for f64 {
type Output = Vector3;
fn mul(self, rhs: Vector3) -> Self::Output {
Vector3::new(self * rhs.x, self * rhs.y, self * rhs.z)
}
}
impl Mul for Vector3 {
type Output = f64;
fn mul(self, rhs: Vector3) -> Self::Output {
self.x * rhs.x + self.y * rhs.y + self.z * rhs.z
}
}
impl Div<f64> for Vector3 {
type Output = Vector3;
fn div(self, rhs: f64) -> Self::Output {
Vector3::new(self.x / rhs, self.y / rhs, self.z / rhs)
}
}
#[derive(Copy, Clone, PartialEq, Debug)]
pub struct Point3 {
x: f64,
y: f64,
z: f64,
}
impl Point3 {
pub fn new(x: f64, y: f64, z: f64) -> Point3 {
Point3 { x, y, z }
}
}
impl Add<Vector3> for Point3 {
type Output = Point3;
fn add(self, rhs: Vector3) -> Self::Output {
Point3::new(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z)
}
}
impl Sub for Point3 {
type Output = Vector3;
fn sub(self, rhs: Point3) -> Self::Output {
Vector3::new(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn new_vector3() {
let v = Vector3::new(1.0, 2.0, 3.0);
assert_eq!(v.x, 1.0);
assert_eq!(v.y, 2.0);
assert_eq!(v.z, 3.0);
}
#[test]
fn add_vector3_to_vector3() {
let v1 = Vector3::new(1.0, 2.0, 3.0);
let v2 = Vector3::new(4.0, 5.0, 6.0);
let r = v1 + v2;
assert_eq!(r.x, 5.0);
assert_eq!(r.y, 7.0);
assert_eq!(r.z, 9.0);
}
#[test]
fn new_point3() {
let p = Point3::new(1.0, 2.0, 3.0);
assert_eq!(p.x, 1.0);
assert_eq!(p.y, 2.0);
assert_eq!(p.z, 3.0);
}
}