122 lines
2.6 KiB
Rust
122 lines
2.6 KiB
Rust
use std::ops::{Add, Div, Mul, Sub};
|
|
|
|
#[derive(Copy, Clone)]
|
|
struct Vector3 {
|
|
x: f64,
|
|
y: f64,
|
|
z: f64,
|
|
}
|
|
|
|
impl Vector3 {
|
|
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)]
|
|
struct Point3 {
|
|
x: f64,
|
|
y: f64,
|
|
z: f64,
|
|
}
|
|
|
|
impl Point3 {
|
|
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)
|
|
}
|
|
}
|
|
|
|
fn main() {
|
|
let vec1 = Vector3::new(1.0, 0.0, 0.0);
|
|
let vec2 = Vector3::new(1.0, 1.0, 0.0);
|
|
|
|
let vec3 = vec1 + vec2;
|
|
let vec4 = vec1 - vec2;
|
|
let vec5 = vec4 * 3.14159;
|
|
let vec6 = 3.14159 * vec3;
|
|
let dot_product = vec1 * vec2;
|
|
let vec7 = vec6 / 3.14159;
|
|
|
|
println!("x = {}, y = {}, z = {}", vec3.x, vec3.y, vec3.z);
|
|
println!("x = {}, y = {}, z = {}", vec4.x, vec4.y, vec4.z);
|
|
println!("x = {}, y = {}, z = {}", vec5.x, vec5.y, vec5.z);
|
|
println!("x = {}, y = {}, z = {}", vec6.x, vec6.y, vec6.z);
|
|
println!("dot_product = {}", dot_product);
|
|
println!("x = {}, y = {}, z = {}", vec7.x, vec7.y, vec7.z);
|
|
|
|
let p1 = Point3::new(0.0, 0.0, 0.0);
|
|
let p2 = Point3::new(1.0, 2.0, 3.0);
|
|
|
|
let vec8 = p1 - p2;
|
|
|
|
println!("x = {}, y = {}, z = {}", vec8.x, vec8.y, vec8.z);
|
|
|
|
let p3 = p2 + vec6;
|
|
|
|
println!("x = {}, y = {}, z = {}", p3.x, p3.y, p3.z);
|
|
}
|