1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
use std::ops::{Mul, Sub};
use glam::{IVec2, Vec2};
use crate::GridPoint;
#[derive(Eq, PartialEq, Clone, Copy, Debug)]
pub enum Pivot {
TopLeft,
TopRight,
Center,
BottomLeft,
BottomRight,
}
impl Pivot {
pub fn axis(&self) -> IVec2 {
match self {
Pivot::TopLeft => IVec2::new(1, -1),
Pivot::TopRight => IVec2::new(-1, -1),
Pivot::Center => IVec2::new(1, 1),
Pivot::BottomLeft => IVec2::new(1, 1),
Pivot::BottomRight => IVec2::new(-1, 1),
}
}
#[inline]
pub fn transform_point(&self, point: impl GridPoint, size: impl GridPoint) -> IVec2 {
let origin = size.as_vec2().sub(1.0).mul(Vec2::from(*self));
let point = point.as_ivec2() * self.axis();
origin.round().as_ivec2() + point
}
}
impl From<Pivot> for Vec2 {
fn from(p: Pivot) -> Self {
match p {
Pivot::TopLeft => Vec2::new(0.0, 1.0),
Pivot::TopRight => Vec2::new(1.0, 1.0),
Pivot::Center => Vec2::new(0.5, 0.5),
Pivot::BottomLeft => Vec2::new(0.0, 0.0),
Pivot::BottomRight => Vec2::new(1.0, 0.0),
}
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct PivotedPoint {
pub point: IVec2,
pub pivot: Pivot,
}
impl GridPoint for PivotedPoint {
#[inline]
fn x(&self) -> i32 {
self.point.x
}
#[inline]
fn y(&self) -> i32 {
self.point.y
}
fn get_pivot(self) -> Option<Pivot> {
Some(self.pivot)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn transform_point() {
let pivot = Pivot::TopRight;
assert_eq!([8, 8], pivot.transform_point([1, 1], [10, 10]).to_array());
assert_eq!([9, 9], pivot.transform_point([0, 0], [10, 10]).to_array());
let pivot = Pivot::TopLeft;
assert_eq!([1, 8], pivot.transform_point([1, 1], [10, 10]).to_array());
let pivot = Pivot::BottomLeft;
assert_eq!([1, 1], pivot.transform_point([1, 1], [10, 10]).to_array());
let pivot = Pivot::BottomRight;
assert_eq!([8, 1], pivot.transform_point([1, 1], [10, 10]).to_array());
}
}