cp_library_rs/geometry/
vec2.rs

1//! 幾何ライブラリ
2
3use std::{
4    hash::Hash,
5    ops::{Add, Div, Mul, Neg, Sub},
6};
7
8#[allow(unused_imports)]
9use crate::geometry::basic;
10
11use num_traits::Num;
12
13/// 2次元ベクトル
14#[derive(Debug, Clone, Copy)]
15pub struct Vec2<T>(pub T, pub T);
16
17impl<T: PartialEq> PartialEq for Vec2<T> {
18    fn eq(&self, other: &Self) -> bool {
19        self.0.eq(&other.0) && self.1.eq(&other.1)
20    }
21}
22
23impl<T: Hash> Hash for Vec2<T> {
24    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
25        self.0.hash(state);
26        self.1.hash(state);
27    }
28}
29
30impl<T> Add for Vec2<T>
31where
32    T: Add<Output = T>,
33{
34    type Output = Self;
35    fn add(self, rhs: Self) -> Self::Output {
36        Self(self.0 + rhs.0, self.1 + rhs.1)
37    }
38}
39
40impl<T> Sub for Vec2<T>
41where
42    T: Sub<Output = T>,
43{
44    type Output = Self;
45    fn sub(self, rhs: Self) -> Self::Output {
46        Self(self.0 - rhs.0, self.1 - rhs.1)
47    }
48}
49
50impl<T> Neg for Vec2<T>
51where
52    T: Neg<Output = T>,
53{
54    type Output = Self;
55    fn neg(self) -> Self::Output {
56        Self(-self.0, -self.1)
57    }
58}
59
60impl<T> Mul<T> for Vec2<T>
61where
62    T: Mul<Output = T> + Clone,
63{
64    type Output = Self;
65    fn mul(self, rhs: T) -> Self::Output {
66        Self(self.0 * rhs.clone(), self.1 * rhs)
67    }
68}
69
70impl<T> Div<T> for Vec2<T>
71where
72    T: Div<Output = T> + Clone,
73{
74    type Output = Self;
75    fn div(self, rhs: T) -> Self::Output {
76        Self(self.0 / rhs.clone(), self.1 / rhs)
77    }
78}
79
80impl<T: Num + Copy> Vec2<T> {
81    /// 2つのベクトルのドット積を求める
82    ///
83    /// ```math
84    /// \boldsymbol{a}\cdot\boldsymbol{b} = a_x b_x + a_y b_y
85    /// ```
86    pub fn dot(&self, other: Self) -> T {
87        let Self(ax, ay) = *self;
88        let Self(bx, by) = other;
89        ax * bx + ay * by
90    }
91
92    /// ノルムの2乗を求める
93    ///
94    /// ```math
95    /// \|\boldsymbol{a}\|^2 = a_x^2 + a_y^2
96    /// ```
97    pub fn norm2(&self) -> T {
98        self.dot(*self)
99    }
100
101    /// ベクトル同士の距離の2乗を求める
102    ///
103    /// ```math
104    /// \|\boldsymbol{a} - \boldsymbol{b}\|^2 = (a_x - b_x)^2 + (a_y - b_y)^2
105    /// ```
106    pub fn dist2(&self, other: Self) -> T {
107        let diff = *self - other;
108        diff.norm2()
109    }
110
111    /// クロス積を求める
112    ///
113    /// ```math
114    /// \boldsymbol{a} \times \boldsymbol{b} = a_x b_y - a_y b_x
115    /// ```
116    pub fn cross(&self, other: Self) -> T {
117        let Self(ax, ay) = *self;
118        let Self(bx, by) = other;
119        ax * by - ay * bx
120    }
121}