aboutsummaryrefslogtreecommitdiff
path: root/src/core/vector2.rs
diff options
context:
space:
mode:
authorJulian T <julian@jtle.dk>2021-01-30 15:37:07 +0100
committerJulian T <julian@jtle.dk>2021-01-30 15:37:07 +0100
commit86303936ab3180828b984ebb256bab8e69dab5cf (patch)
treee4bfb08d9c73edd12aef944e0d698c03753032da /src/core/vector2.rs
parentfdb3e8cb8d53449c107388e143345beae162f95e (diff)
Finished initial film, reorganization and started work on shapes
Diffstat (limited to 'src/core/vector2.rs')
-rw-r--r--src/core/vector2.rs110
1 files changed, 110 insertions, 0 deletions
diff --git a/src/core/vector2.rs b/src/core/vector2.rs
new file mode 100644
index 0000000..ac70947
--- /dev/null
+++ b/src/core/vector2.rs
@@ -0,0 +1,110 @@
+use crate::{Float, Number};
+use std::ops::{Sub, Add};
+
+#[derive(Clone, Copy)]
+pub struct Vector2<T: Number> {
+ pub x: T,
+ pub y: T,
+}
+
+pub type Vector2f = Vector2<Float>;
+pub type Vector2i = Vector2<i32>;
+
+impl<T: Number> Vector2<T> {
+ pub fn new(initial: T) -> Vector2<T> {
+ Vector2 { x: initial, y: initial }
+ }
+
+ pub fn new_xy(x: T, y: T) -> Vector2<T> {
+ Vector2 { x, y }
+ }
+}
+
+impl<T: Number> Sub for Vector2<T> {
+ type Output = Self;
+ fn sub(self, op: Self) -> Self::Output {
+ Self::new_xy(
+ self.x - op.x,
+ self.y - op.y,
+ )
+ }
+}
+
+impl<T: Number> Add for Vector2<T> {
+ type Output = Self;
+ fn add(self, op: Self) -> Self::Output {
+ Self::new_xy(
+ self.x + op.x,
+ self.y + op.y,
+ )
+ }
+}
+
+impl Vector2f {
+ pub fn ceil(&self) -> Self {
+ Self::new_xy(
+ self.x.ceil(),
+ self.y.ceil()
+ )
+ }
+
+ pub fn floor(&self) -> Self {
+ Self::new_xy(
+ self.x.ceil(),
+ self.y.ceil()
+ )
+ }
+}
+
+impl From<Vector2i> for Vector2f {
+ fn from(v: Vector2i) -> Self {
+ Self {
+ x: v.x as Float,
+ y: v.y as Float,
+ }
+ }
+}
+
+impl From<Vector2f> for Vector2i {
+ fn from(v: Vector2f) -> Self {
+ Self {
+ x: v.x as i32,
+ y: v.y as i32,
+ }
+ }
+}
+
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn new_vec2() {
+ let v = Vector2::new_xy(2.0, 10.0);
+
+ assert!(v.x == 2.0 && v.y == 10.0);
+
+ let v = Vector2::new(3);
+
+ assert!(v.x == 3 && v.y == 3);
+ }
+
+ #[test]
+ fn sub_vec2() {
+ let v1 = Vector2::new_xy(10, 11);
+ let v2 = Vector2::new_xy(2, 3);
+
+ let v3 = v1-v2;
+ assert!(v3.x == 8 && v3.y == 8);
+ }
+
+ #[test]
+ fn add_vec2() {
+ let v1 = Vector2::new_xy(10, 11);
+ let v2 = Vector2::new_xy(2, 3);
+
+ let v3 = v1+v2;
+ assert!(v3.x == 12 && v3.y == 14);
+ }
+}