2015-05-15 19:16:58 +00:00
|
|
|
//! 2D points.
|
|
|
|
|
2015-05-15 23:06:48 +00:00
|
|
|
use std::ops::{Add, Sub, Mul, Div};
|
2015-05-15 18:58:47 +00:00
|
|
|
use std::cmp::min;
|
|
|
|
|
|
|
|
/// Simple 2D size, in characters.
|
|
|
|
#[derive(Clone,Copy)]
|
|
|
|
pub struct Vec2 {
|
|
|
|
/// X coordinate (column), from left to right.
|
|
|
|
pub x: u32,
|
|
|
|
/// Y coordinate (row), from top to bottom.
|
|
|
|
pub y: u32,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Vec2 {
|
|
|
|
/// Creates a new Vec2 from coordinates.
|
|
|
|
pub fn new(x: u32, y: u32) -> Self {
|
|
|
|
Vec2 {
|
|
|
|
x: x,
|
|
|
|
y: y,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns a new Vec2 that is no larger than any input in both dimensions.
|
|
|
|
pub fn min(a: Vec2, b: Vec2) -> Vec2 {
|
|
|
|
Vec2 {
|
|
|
|
x: min(a.x, b.x),
|
|
|
|
y: min(a.y, b.y),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// A generic trait for converting a value into a 2D vector.
|
|
|
|
pub trait ToVec2 {
|
|
|
|
fn to_vec2(self) -> Vec2;
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ToVec2 for Vec2 {
|
|
|
|
fn to_vec2(self) -> Vec2 {
|
|
|
|
self
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ToVec2 for (u32,u32) {
|
|
|
|
fn to_vec2(self) -> Vec2 {
|
|
|
|
Vec2::new(self.0, self.1)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-05-15 22:00:20 +00:00
|
|
|
impl ToVec2 for (usize,usize) {
|
|
|
|
fn to_vec2(self) -> Vec2 {
|
|
|
|
Vec2::new(self.0 as u32, self.1 as u32)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-05-16 21:02:15 +00:00
|
|
|
impl <T: ToVec2> Add<T> for Vec2 {
|
2015-05-15 18:58:47 +00:00
|
|
|
type Output = Vec2;
|
|
|
|
|
2015-05-16 21:02:15 +00:00
|
|
|
fn add(self, other: T) -> Vec2 {
|
|
|
|
let ov = other.to_vec2();
|
2015-05-15 18:58:47 +00:00
|
|
|
Vec2 {
|
2015-05-16 21:02:15 +00:00
|
|
|
x: self.x + ov.x,
|
|
|
|
y: self.y + ov.y,
|
2015-05-15 18:58:47 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-05-16 21:02:15 +00:00
|
|
|
impl <T: ToVec2> Sub<T> for Vec2 {
|
2015-05-15 18:58:47 +00:00
|
|
|
type Output = Vec2;
|
|
|
|
|
2015-05-16 21:02:15 +00:00
|
|
|
fn sub(self, other: T) -> Vec2 {
|
|
|
|
let ov = other.to_vec2();
|
2015-05-15 18:58:47 +00:00
|
|
|
Vec2 {
|
2015-05-16 21:02:15 +00:00
|
|
|
x: self.x - ov.x,
|
|
|
|
y: self.y - ov.y,
|
2015-05-15 18:58:47 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-05-15 23:06:48 +00:00
|
|
|
|
|
|
|
impl Div<u32> for Vec2 {
|
|
|
|
type Output = Vec2;
|
|
|
|
|
|
|
|
fn div(self, other: u32) -> Vec2 {
|
|
|
|
Vec2 {
|
|
|
|
x: self.x / other,
|
|
|
|
y: self.y / other,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Mul<u32> for Vec2 {
|
|
|
|
type Output = Vec2;
|
|
|
|
|
|
|
|
fn mul(self, other: u32) -> Vec2 {
|
|
|
|
Vec2 {
|
|
|
|
x: self.x * other,
|
|
|
|
y: self.y * other,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|