Skip to main content

sge_camera/
lib.rs

1use d2::{Camera2D, projection};
2use d3::Camera3D;
3use sge_global::global;
4use sge_vectors::{Mat4, Vec2, Vec3};
5
6pub mod d2;
7pub mod d3;
8
9#[derive(Clone, Debug, Copy)]
10pub struct Cameras {
11    pub flat: Mat4,
12    pub d2: Camera2D,
13    pub d3: Camera3D,
14    pub flip_y: bool,
15}
16
17impl Cameras {
18    pub fn set_flip_y(&mut self, value: bool) {
19        self.flip_y = value;
20        self.d2.set_flip_y(value);
21    }
22}
23
24global!(Cameras, cameras);
25
26pub fn init(width: u32, height: u32, flip_y: bool) {
27    let flat = projection(width, height, flip_y);
28    let d2 = Camera2D::new(width, height, flip_y);
29    let d3 = Camera3D::new(width, height);
30
31    set_cameras(Cameras {
32        flat,
33        d2,
34        d3,
35        flip_y,
36    });
37    log::info!("Initialized cameras");
38}
39
40pub fn update_cameras_on_resize(width: u32, height: u32) {
41    let cameras = get_cameras();
42
43    cameras.d2.update_sizes(width, height);
44    cameras.d3.update_sizes(width, height);
45    cameras.flat = projection(width, height, cameras.flip_y);
46}
47
48pub fn get_camera_2d() -> &'static Camera2D {
49    &get_cameras().d2
50}
51
52pub fn get_flat_projection() -> Mat4 {
53    get_cameras().flat
54}
55
56pub fn get_camera_3d() -> &'static Camera3D {
57    &get_cameras().d3
58}
59
60pub fn get_camera_3d_mut() -> &'static mut Camera3D {
61    &mut get_cameras().d3
62}
63
64pub fn get_camera_2d_mut() -> &'static mut Camera2D {
65    &mut get_cameras().d2
66}
67
68pub fn camera2d_zoom_at(screen_pos: Vec2, zoom_factor: f32) {
69    get_camera_2d_mut().zoom_at(screen_pos, zoom_factor);
70}
71
72pub fn cameras_for_resolution(width: u32, height: u32) -> Cameras {
73    let current = get_cameras();
74    let mut d2 = current.d2;
75    d2.update_sizes(width, height);
76    let flat = projection(width, height, current.flip_y);
77    let mut d3 = current.d3;
78    d3.update_sizes(width, height);
79    Cameras {
80        flat,
81        d2,
82        d3,
83        flip_y: current.flip_y,
84    }
85}
86
87pub fn screen_to_world(screen_pos: Vec2) -> Vec2 {
88    get_camera_2d_mut().screen_to_world(screen_pos)
89}
90
91pub fn world_to_screen(world_pos: Vec2) -> Vec2 {
92    get_camera_2d_mut().world_to_screen(world_pos)
93}
94
95pub fn screen_distance_to_world(screen_length: f32) -> f32 {
96    get_camera_2d_mut().screen_distance_to_world(screen_length)
97}
98
99pub fn world_distance_to_screen(world_length: f32) -> f32 {
100    get_camera_2d_mut().world_distance_to_screen(world_length)
101}
102
103pub fn world_to_screen_3d(world_pos: Vec3) -> Option<Vec2> {
104    get_camera_3d_mut().world_to_screen(world_pos)
105}