lyra-engine/lyra-game/src/game.rs

358 lines
12 KiB
Rust
Raw Normal View History

use std::{sync::Arc, collections::VecDeque, ptr::NonNull};
2023-03-16 21:47:36 +00:00
2023-10-23 01:49:31 +00:00
use async_std::task::block_on;
use lyra_ecs::{world::World, system::{System, IntoSystem}};
use tracing::{info, error, Level};
use tracing_appender::non_blocking;
2023-03-16 21:47:36 +00:00
use tracing_subscriber::{
2023-10-23 01:49:31 +00:00
layer::SubscriberExt,
filter,
util::SubscriberInitExt, fmt,
2023-03-16 21:47:36 +00:00
};
use winit::{window::{WindowBuilder, Window}, event::{Event, WindowEvent, KeyboardInput, ElementState, VirtualKeyCode, DeviceEvent}, event_loop::{EventLoop, ControlFlow}};
2023-03-16 21:47:36 +00:00
use crate::{render::{renderer::{Renderer, BasicRenderer}, window::WindowOptions}, input::InputEvent, plugin::Plugin, change_tracker::Ct, EventQueue, StagedExecutor, Stage};
#[derive(Clone, Copy, Hash, Debug)]
pub enum GameStages {
Core,
User,
}
impl Stage for GameStages {}
pub struct Controls<'a> {
2023-12-26 19:12:53 +00:00
pub world: &'a mut World,
}
2023-03-16 21:47:36 +00:00
2023-09-08 04:13:46 +00:00
#[derive(Clone, Default)]
pub struct WindowState {
pub is_focused: bool,
pub is_cursor_inside_window: bool,
}
2023-09-08 04:13:46 +00:00
impl WindowState {
pub fn new() -> Self {
Self::default()
}
}
struct GameLoop {
2023-03-16 21:47:36 +00:00
window: Arc<Window>,
renderer: Box<dyn Renderer>,
2023-12-26 19:12:53 +00:00
world: World,
staged_exec: StagedExecutor,
2023-03-16 21:47:36 +00:00
}
impl GameLoop {
pub async fn new(window: Arc<Window>, world: World, staged_exec: StagedExecutor) -> GameLoop {
2023-03-16 21:47:36 +00:00
Self {
window: Arc::clone(&window),
renderer: Box::new(BasicRenderer::create_with_window(window).await),
world,
staged_exec,
2023-03-16 21:47:36 +00:00
}
}
pub async fn on_resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) {
2023-09-01 01:34:58 +00:00
self.renderer.on_resize(new_size);
2023-03-16 21:47:36 +00:00
}
2023-09-01 15:41:54 +00:00
pub async fn on_init(&mut self) {
// Create the EventQueue resource in the world
2023-12-26 19:12:53 +00:00
self.world.add_resource(self.window.clone());
2023-09-01 15:41:54 +00:00
}
2023-03-16 21:47:36 +00:00
pub fn run_sync(&mut self, event: Event<()>, control_flow: &mut ControlFlow) {
block_on(self.run_event_loop(event, control_flow))
}
async fn update(&mut self) {
let world_ptr = NonNull::from(&self.world);
if let Err(e) = self.staged_exec.execute(world_ptr, true) {
error!("Error when executing staged systems: '{}'", e);
}
2023-03-16 21:47:36 +00:00
}
async fn input_update(&mut self, event: &InputEvent) -> Option<ControlFlow> {
match event {
InputEvent::KeyboardInput {
input:
KeyboardInput {
state: ElementState::Pressed,
virtual_keycode: Some(VirtualKeyCode::Escape),
..
},
..
} => {
self.on_exit();
Some(ControlFlow::Exit)
},
_ => {
//debug!("Got unhandled input event: \"{:?}\"", event);
2023-03-16 21:47:36 +00:00
None
}
}
}
fn on_exit(&mut self) {
info!("On exit!");
}
pub async fn run_event_loop(&mut self, event: Event<'_, ()>, control_flow: &mut ControlFlow) {
*control_flow = ControlFlow::Poll;
match event {
2023-10-23 01:49:31 +00:00
Event::DeviceEvent { device_id, event: DeviceEvent::MouseMotion { delta } } => {
2023-10-26 01:49:38 +00:00
//debug!("motion: {delta:?}");
// convert a MouseMotion event to an InputEvent
2023-10-23 01:49:31 +00:00
// make sure that the mouse is inside the window and the mouse has focus before reporting mouse motion
2023-10-26 01:49:38 +00:00
/* let trigger = matches!(self.world.get_resource::<WindowState>(), Some(window_state)
if window_state.is_focused && window_state.is_cursor_inside_window); */
2023-12-26 19:12:53 +00:00
let trigger = matches!(self.world.try_get_resource::<Ct<WindowOptions>>(), Some(window)
2023-10-26 01:49:38 +00:00
if window.focused && window.cursor_inside_window);
2023-10-23 01:49:31 +00:00
if trigger {
2023-12-26 19:12:53 +00:00
let mut event_queue = self.world.try_get_resource_mut::<EventQueue>().unwrap();
2023-10-23 01:49:31 +00:00
let input_event = InputEvent::MouseMotion { device_id, delta, };
2023-10-26 01:49:38 +00:00
event_queue.trigger_event(input_event);
2023-10-23 01:49:31 +00:00
}
},
2023-03-16 21:47:36 +00:00
Event::WindowEvent {
ref event,
window_id,
} if window_id == self.window.id() => {
2023-03-16 21:47:36 +00:00
// If try_from failed, that means that the WindowEvent is not an
// input related event.
if let Ok(input_event) = InputEvent::try_from(event) {
// Its possible to receive multiple input events before the update event for
// the InputSystem is called, so we must use a queue for the events.
{
2023-12-26 19:12:53 +00:00
if let Some(mut event_queue) = self.world.try_get_resource_mut::<EventQueue>() {
2023-09-01 01:34:58 +00:00
event_queue.trigger_event(input_event.clone());
};
}
2023-03-16 21:47:36 +00:00
if let Some(new_control) = self.input_update(&input_event).await {
*control_flow = new_control;
}
} else {
match event {
WindowEvent::CloseRequested => {
self.on_exit();
*control_flow = ControlFlow::Exit
},
WindowEvent::Resized(physical_size) => {
self.on_resize(*physical_size).await;
},
WindowEvent::ScaleFactorChanged { new_inner_size, .. } => {
self.on_resize(**new_inner_size).await;
},
WindowEvent::Focused(is_focused) => {
2023-12-26 19:12:53 +00:00
let mut state = self.world.get_resource_or_else(WindowState::new);
state.is_focused = *is_focused;
},
2023-03-16 21:47:36 +00:00
_ => {}
}
}
},
Event::RedrawRequested(window_id) if window_id == self.window.id() => {
// Update the world
self.update().await;
/* self.fps_counter.tick();
if let Some(fps) = self.fps_counter.get_change() {
debug!("FPS: {}fps, {:.2}ms/frame", fps, self.fps_counter.get_tick_time());
} */
2023-09-09 14:51:58 +00:00
self.renderer.as_mut().prepare(&mut self.world);
2023-12-26 19:12:53 +00:00
if let Some(mut event_queue) = self.world.try_get_resource_mut::<EventQueue>() {
2023-09-01 01:34:58 +00:00
event_queue.update_events();
}
2023-09-01 01:34:58 +00:00
match self.renderer.as_mut().render() {
2023-03-16 21:47:36 +00:00
Ok(_) => {}
// Reconfigure the surface if lost
2023-04-19 04:53:06 +00:00
Err(wgpu::SurfaceError::Lost) => self.on_resize(self.renderer.as_ref().surface_size()).await,
2023-03-16 21:47:36 +00:00
// The system is out of memory, we should probably quit
Err(wgpu::SurfaceError::OutOfMemory) => *control_flow = ControlFlow::Exit,
// All other errors (Outdated, Timeout) should be resolved by the next frame
Err(e) => eprintln!("{:?}", e),
}
},
Event::MainEventsCleared => {
self.window.request_redraw();
},
_ => {}
}
}
}
pub struct Game {
2023-12-26 19:12:53 +00:00
world: Option<World>,
2023-09-09 14:51:58 +00:00
plugins: VecDeque<Box<dyn Plugin>>,
system_exec: Option<StagedExecutor>,
startup_systems: VecDeque<Box<dyn System>>,
2023-03-16 21:47:36 +00:00
}
impl Default for Game {
fn default() -> Self {
let mut staged = StagedExecutor::new();
staged.add_stage(GameStages::Core);
staged.add_stage_after(GameStages::Core, GameStages::User);
Self {
2023-12-26 19:12:53 +00:00
world: Some(World::new()),
2023-09-09 14:51:58 +00:00
plugins: VecDeque::new(),
system_exec: Some(staged),
startup_systems: VecDeque::new(),
}
}
}
2023-03-16 21:47:36 +00:00
impl Game {
pub async fn initialize() -> Game {
Self::default()
2023-03-16 21:47:36 +00:00
}
/// Get the world of this game
2023-12-26 19:12:53 +00:00
pub fn world(&mut self) -> &mut World {
// world is always `Some`, so unwrapping is safe
self.world.as_mut().unwrap()
}
/// Add a system to the ecs world
pub fn with_system<S, A>(&mut self, name: &str, system: S, depends: &[&str]) -> &mut Self
2023-09-09 14:51:58 +00:00
where
S: IntoSystem<A>,
<S as IntoSystem<A>>::System: 'static
2023-09-09 14:51:58 +00:00
{
let system_dispatcher = self.system_exec.as_mut().unwrap();
system_dispatcher.add_system_to_stage(GameStages::User, name, system.into_system(), depends);
2023-03-16 21:47:36 +00:00
self
2023-03-16 21:47:36 +00:00
}
/// Add a stage.
///
/// This stage could run at any moment if nothing is dependent on it.
pub fn add_stage<T: Stage>(&mut self, stage: T) -> &mut Self {
let system_dispatcher = self.system_exec.as_mut().unwrap();
system_dispatcher.add_stage(stage);
self
}
/// Add a stage that executes after another one.
///
/// Parameters:
/// * `before` - The stage that will run before `after`.
/// * `after` - The stage that will run after `before`.
pub fn add_stage_after<T: Stage, U: Stage>(&mut self, before: T, after: U) -> &mut Self {
let system_dispatcher = self.system_exec.as_mut().unwrap();
system_dispatcher.add_stage_after(before, after);
self
}
/// Add a system to an already existing stage.
///
/// # Panics
/// Panics if the stage was not already added to the executor
pub fn add_system_to_stage<ST: Stage, I: IntoSystem<()> + 'static>(&mut self, stage: ST,
name: &str, system: I, depends: &[&str]) -> &mut Self {
let system_dispatcher = self.system_exec.as_mut().unwrap();
system_dispatcher.add_system_to_stage(stage, name, system.into_system(), depends);
self
}
/// Add a startup system that will be ran right after plugins are setup.
/// They will only be ran once
pub fn with_startup_system<S>(&mut self, system: S) -> &mut Self
where
S: System + 'static
{
self.startup_systems.push_back(Box::new(system));
self
}
/// Add a plugin to the game. These will be executed before the window is initiated and opened
2023-09-09 14:51:58 +00:00
pub fn with_plugin<P>(&mut self, plugin: P) -> &mut Self
where
P: Plugin + 'static
{
self.plugins.push_back(Box::new(plugin));
self
2023-03-16 21:47:36 +00:00
}
/// Override the default (empty) world
///
/// This isn't recommended, you should create a startup system and add it to `with_startup_system`
2023-12-26 19:12:53 +00:00
pub fn with_world(&mut self, world: World) -> &mut Self {
2023-09-09 14:51:58 +00:00
self.world = Some(world);
2023-06-29 03:18:44 +00:00
self
}
/// Start the game
2023-03-16 21:47:36 +00:00
pub async fn run(&mut self) {
// init logging
let (stdout_layer, _stdout_nb) = non_blocking(std::io::stdout());
tracing_subscriber::registry()
.with(fmt::layer().with_writer(stdout_layer))
.with(filter::Targets::new()
.with_target("lyra_engine", Level::TRACE)
.with_target("wgpu_core", Level::WARN)
.with_default(Level::DEBUG))
.init();
2023-09-09 14:51:58 +00:00
// setup all the plugins
while let Some(plugin) = self.plugins.pop_front() {
plugin.as_ref().setup(self);
}
let world = self.world.take().unwrap_or_default();
// run startup systems
while let Some(mut startup) = self.startup_systems.pop_front() {
let startup = startup.as_mut();
let world_ptr = NonNull::from(&world);
startup.setup(world_ptr).expect("World returned an error!");
startup.execute(world_ptr).expect("World returned an error!");
}
2023-09-09 14:51:58 +00:00
// start winit event loops
2023-03-16 21:47:36 +00:00
let event_loop = EventLoop::new();
let window = Arc::new(WindowBuilder::new().build(&event_loop).unwrap());
let system_dispatcher = self.system_exec.take().unwrap();
2023-09-09 14:51:58 +00:00
let mut g_loop = GameLoop::new(Arc::clone(&window), world, system_dispatcher).await;
2023-09-01 15:41:54 +00:00
g_loop.on_init().await;
2023-03-16 21:47:36 +00:00
event_loop.run(move |event, _, control_flow| {
g_loop.run_sync(event, control_flow);
});
}
}