SolarEngine/solar_engine/src/application.rs

77 lines
2.5 KiB
Rust
Raw Normal View History

use winit::application::ApplicationHandler;
use winit::event::WindowEvent;
use winit::event_loop::ActiveEventLoop;
use winit::window::{Window, WindowId};
pub struct StateApplication<'a> {
state: Option<crate::state::State<'a>>,
update_fn: Option<Box<dyn FnMut(&mut crate::state::State<'a>) + 'a>>,
input_fn: Option<Box<dyn FnMut(&mut crate::state::State<'a>, &WindowEvent) + 'a>>,
}
impl<'a> StateApplication<'a> {
pub fn new() -> Self {
Self { state: None, update_fn: None, input_fn: None }
}
pub fn on_update<F: FnMut(&mut crate::state::State<'a>) + 'a>(mut self, func: F) -> Self {
self.update_fn = Some(Box::new(func));
self
}
pub fn on_input<F: FnMut(&mut crate::state::State<'a>, &WindowEvent) + 'a>(mut self, func: F) -> Self {
self.input_fn = Some(Box::new(func));
self
}
}
impl<'a> ApplicationHandler for StateApplication<'a> {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
let window = event_loop
.create_window(Window::default_attributes().with_title("Solar Engine"))
.unwrap();
self.state = Some(crate::state::State::new(window));
}
fn window_event(
&mut self,
event_loop: &ActiveEventLoop,
window_id: WindowId,
event: WindowEvent,
) {
let window = self.state.as_ref().unwrap().window();
if window.id() == window_id {
match event {
WindowEvent::CloseRequested => {
event_loop.exit();
}
WindowEvent::Resized(physical_size) => {
self.state.as_mut().unwrap().resize(physical_size);
}
WindowEvent::RedrawRequested => {
if let (Some(state), Some(update_fn)) = (self.state.as_mut(), self.update_fn.as_mut()) {
update_fn(state);
}
self.state.as_mut().unwrap().render().unwrap();
}
WindowEvent::KeyboardInput { .. } => {
if let Some(state) = self.state.as_mut() {
if let Some(input_fn) = self.input_fn.as_mut() {
input_fn(state, &event);
}
}
}
_ => {}
}
}
}
fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
if let Some(state) = self.state.as_ref() {
state.window().request_redraw();
}
}
}