summaryrefslogtreecommitdiffstats
path: root/src/main.rs
blob: 4aeaa5ea61cfbcbbc6e9f641408de63c875579bf (plain) (blame)
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
mod window;
mod ui;
mod tacmap;
mod wgpuctx;
mod eguictx;
mod vertex;
mod texture;
mod solar_system;
mod known_stars;
mod timeman;

use std::cell::RefCell;
use std::thread;
use std::time::{Duration, Instant};

use winit::event::{KeyEvent, WindowEvent};
use winit::event_loop::{EventLoop, ActiveEventLoop, ControlFlow};
use winit::error::{EventLoopError};
use winit::application::{ApplicationHandler};
use winit::keyboard::PhysicalKey;
use winit::window::{Window, WindowId, WindowAttributes};

use solar_system::*;

use crate::timeman::TimeMan;
use crate::window::GameWindow;

const TARGET_FPS: f32 = 100.0;
const TARGET_DT: Duration = Duration::from_millis((1000.0 / TARGET_FPS) as u64);

struct SystemicApp
{
    window: Option<GameWindow>,
    wgpu_instance: wgpu::Instance,

    last_render_time: Instant,
    game_state: Option<RefCell<GameState>>
}

struct GameState
{
    timeman: TimeMan,
    solar_systems: Vec<SolarSystem>
}

impl SystemicApp
{
    fn create_window(
        &mut self,
        event_loop: &ActiveEventLoop)
    {
        self.window = Some(GameWindow::new(
                &self.wgpu_instance,
                event_loop).unwrap());

        self.game_state = Some(RefCell::new(GameState::new()));
    }
}

impl GameState
{
    pub fn new()
    -> Self {
        let timeman = TimeMan::new(0);
        let mut sol_system = match SolarSystem::new_from_known_star(0, "sol")
        {
            Ok(system) => system,
            Err(e) => panic!("Unable to create sol system : {}", e)
        };

        sol_system.update(timeman.seconds());

        Self {
            timeman: timeman,
            solar_systems: vec![ sol_system ]
        }
    }

    pub fn solar_systems(&self) -> &[SolarSystem]
    { self.solar_systems.as_slice() }

    pub fn timeman(&self) -> &TimeMan
    { &self.timeman }

    pub fn timeman_mut(&mut self) -> &mut TimeMan
    { &mut self.timeman }

    fn update(
        &mut self,
        dt: Duration)
    {
        let ticks = self.timeman.update();
        ticks.iter().for_each(|time| {
            solar_system::update_systems(self.solar_systems.iter_mut(), *time);
        });
    }
}

impl ApplicationHandler for SystemicApp
{
    fn resumed(
        &mut self, 
        event_loop: &ActiveEventLoop
    ) {
        match self.window {
            Some(_) => {}
            None => self.create_window(event_loop)
        }
    }

    fn window_event(
            &mut self,
            event_loop: &ActiveEventLoop,
            window_id: WindowId,
            event: winit::event::WindowEvent,
    ) {
        let window = match &mut self.window {
            Some(w) => w,
            None => return
        };

        let game_state = match &self.game_state {
            Some(state) => state,
            None => return
        };

        window.on_event(&event);

        match event {
            WindowEvent::CloseRequested => {
                event_loop.exit();  
            }
            WindowEvent::Resized(size) => {
                window.resize(size.width, size.height);
            }
            WindowEvent::RedrawRequested => {
                let now = Instant::now();
                let delta_time = now - self.last_render_time;
                self.last_render_time = now;

                game_state.borrow_mut().update(delta_time);
                window.update(game_state, delta_time);
                
                match window.render(game_state) {
                    Ok(_) => {}
                    Err(wgpu::SurfaceError::Outdated | wgpu::SurfaceError::Lost) => {
                        let size = window.size();
                        window.resize(size.width, size.height);
                    },
                    Err(e) => {
                        log::error!("Unable to render: {}", e);
                    }
                }
                if delta_time < TARGET_DT {
                    thread::sleep(TARGET_DT - delta_time);
                }
            }
            WindowEvent::KeyboardInput {
                event: KeyEvent {
                    physical_key: PhysicalKey::Code(key_code),
                    state: key_state,
                    ..
                },
                ..
            } => {
                window.keyboard_input(key_code, key_state);
            }
            _ => {}
        }
    }
} // impl ApplicationHandler for SystemicApp

fn main()
    -> Result<(), EventLoopError>
{
    env_logger::init();
    let event_loop = EventLoop::new().unwrap();

    event_loop.set_control_flow(ControlFlow::Poll);

    let mut app = SystemicApp {
        window: None,
        wgpu_instance: wgpu::Instance::default(),
        last_render_time: Instant::now(),
        game_state: None
    };

    event_loop.run_app(&mut app)
}