diff --git a/src/point.rs b/src/point.rs index a7274f1..ea19b9a 100644 --- a/src/point.rs +++ b/src/point.rs @@ -46,6 +46,21 @@ impl Point2D { } } +impl + + Add + + Sub + + Copy> Point2D { + #[inline] + pub fn dot(self, other: Point2D) -> T { + self.x * other.x + + self.y * other.y + } + + #[inline] + pub fn cross(self, other: Point2D) -> T { + self.x * other.y - self.y * other.x + } +} impl> Add for Point2D { type Output = Point2D; @@ -173,6 +188,27 @@ impl Point3D { } } +impl + + Add + + Sub + + Copy> Point3D { + #[inline] + pub fn dot(self, other: Point3D) -> T { + self.x * other.x + + self.y * other.y + + self.z * other.z + } + + #[inline] + pub fn cross(self, other: Point3D) -> Point3D { + Point3D { + x: self.y * other.z - self.z * other.y, + y: self.z * other.x - self.x * other.z, + z: self.x * other.y - self.y * other.x, + } + } +} + impl> Add for Point3D { type Output = Point3D; fn add(self, other: Point3D) -> Point3D { @@ -266,3 +302,35 @@ impl > Neg for Point4D { Point4D::new(-self.x, -self.y, -self.z, -self.w) } } + +#[test] +pub fn test_dot_2d() { + let p1 = Point2D::new(2.0, 7.0); + let p2 = Point2D::new(13.0, 11.0); + assert!(p1.dot(p2) == 103.0); +} + +#[test] +pub fn test_dot_3d() { + let p1 = Point3D::new(7.0, 21.0, 32.0); + let p2 = Point3D::new(43.0, 5.0, 16.0); + assert!(p1.dot(p2) == 918.0); +} + +#[test] +pub fn test_cross_2d() { + let p1 = Point2D::new(4.0, 7.0); + let p2 = Point2D::new(13.0, 8.0); + let r = p1.cross(p2); + assert!(r == -59.0); +} + +#[test] +pub fn test_cross_3d() { + let p1 = Point3D::new(4.0, 7.0, 9.0); + let p2 = Point3D::new(13.0, 8.0, 3.0); + let p3 = p1.cross(p2); + assert!(p3.x == -51.0); + assert!(p3.y == 105.0); + assert!(p3.z == -59.0); +}