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
use crate::input;
use crate::math::{Mat4, Vec2, Vec3};
use crate::window;
use crate::Context;
#[derive(Debug, Clone)]
pub struct Camera {
pub position: Vec2<f32>,
pub rotation: f32,
pub zoom: f32,
pub viewport_width: f32,
pub viewport_height: f32,
matrix: Mat4<f32>,
}
impl Camera {
pub fn new(viewport_width: f32, viewport_height: f32) -> Camera {
Camera {
position: Vec2::zero(),
rotation: 0.0,
zoom: 1.0,
viewport_width,
viewport_height,
matrix: Mat4::identity(),
}
}
pub fn with_window_size(ctx: &Context) -> Camera {
let (width, height) = window::get_size(ctx);
Camera::new(width as f32, height as f32)
}
pub fn set_viewport_size(&mut self, width: f32, height: f32) {
self.viewport_width = width;
self.viewport_height = height;
}
pub fn update(&mut self) {
self.matrix = Mat4::translation_2d(-self.position);
self.matrix.rotate_z(self.rotation);
self.matrix.scale_3d(Vec3::new(self.zoom, self.zoom, 1.0));
self.matrix.translate_2d(Vec2::new(
self.viewport_width / 2.0,
self.viewport_height / 2.0,
));
}
pub fn as_matrix(&self) -> Mat4<f32> {
self.matrix
}
pub fn project(&self, point: Vec2<f32>) -> Vec2<f32> {
self.as_matrix()
.inverted()
.mul_point(Vec3::from_point_2d(point))
.xy()
}
pub fn unproject(&self, point: Vec2<f32>) -> Vec2<f32> {
self.as_matrix().mul_point(Vec3::from_point_2d(point)).xy()
}
pub fn mouse_position(&self, ctx: &Context) -> Vec2<f32> {
self.project(input::get_mouse_position(ctx))
}
pub fn mouse_x(&self, ctx: &Context) -> f32 {
self.mouse_position(ctx).x
}
pub fn mouse_y(&self, ctx: &Context) -> f32 {
self.mouse_position(ctx).y
}
}