use std::{sync::Arc, collections::VecDeque}; use async_std::{task::block_on, sync::Mutex}; //use hecs::World; use instant::Instant; use tracing::{metadata::LevelFilter, info, debug, warn, error, Level}; use tracing_appender::non_blocking; use tracing_subscriber::{ layer::{Layer, SubscriberExt}, filter::{FilterFn, self}, util::SubscriberInitExt, fmt, }; use winit::{window::{WindowBuilder, Window}, event::{Event, WindowEvent, KeyboardInput, ElementState, VirtualKeyCode, DeviceEvent}, event_loop::{EventLoop, ControlFlow}}; use crate::{render::renderer::{Renderer, BasicRenderer}, input_event::InputEvent, ecs::{SimpleSystem, SystemDispatcher, EventQueue, Events}, input::InputSystem, plugin::Plugin}; pub struct Controls<'a> { pub world: &'a mut edict::World, } #[derive(Clone, Default)] pub struct WindowState { pub is_focused: bool, pub is_cursor_inside_window: bool, } impl WindowState { pub fn new() -> Self { Self::default() } } struct GameLoop { window: Arc, renderer: Box, world: edict::World, /// higher priority systems engine_sys_dispatcher: SystemDispatcher, user_sys_dispatcher: SystemDispatcher, } impl GameLoop { pub async fn new(window: Arc, world: edict::World, user_systems: SystemDispatcher) -> GameLoop { Self { window: Arc::clone(&window), renderer: Box::new(BasicRenderer::create_with_window(window).await), world, engine_sys_dispatcher: SystemDispatcher::new(), user_sys_dispatcher: user_systems, } } pub async fn on_resize(&mut self, new_size: winit::dpi::PhysicalSize) { self.renderer.on_resize(new_size); } pub async fn on_init(&mut self) { // Create the EventQueue resource in the world self.world.insert_resource(self.window.clone()); } 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) { if let Err(e) = self.engine_sys_dispatcher.execute_mut(&mut self.world) { error!("Error when executing engine ecs systems: '{}'", e); } if let Err(e) = self.user_sys_dispatcher.execute_mut(&mut self.world) { error!("Error when executing user ecs systems: '{}'", e); } } async fn input_update(&mut self, event: &InputEvent) -> Option { match event { InputEvent::KeyboardInput { input: KeyboardInput { state: ElementState::Pressed, virtual_keycode: Some(VirtualKeyCode::Escape), .. }, .. } => { self.on_exit(); Some(ControlFlow::Exit) }, // TODO: Create system for this? or maybe merge into input system, idk InputEvent::CursorEntered { .. } => { let mut state = self.world.with_resource(|| WindowState::new()); state.is_cursor_inside_window = true; None }, InputEvent::CursorLeft { .. } => { let mut state = self.world.with_resource(|| WindowState::new()); state.is_cursor_inside_window = false; None } _ => { //debug!("Got unhandled input event: \"{:?}\"", event); 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 { Event::DeviceEvent { device_id, event } => match event { // convert a MouseMotion event to an InputEvent DeviceEvent::MouseMotion { delta } => { // make sure that the mouse is inside the window and the mouse has focus before reporting mouse motion let trigger = match self.world.get_resource::() { Some(window_state) if window_state.is_focused && window_state.is_cursor_inside_window => true, _ => false, }; if trigger { let event_queue = self.world.with_resource(|| Events::::new()); let input_event = InputEvent::MouseMotion { device_id, delta, }; event_queue.push_back(input_event); } }, _ => {} }, Event::WindowEvent { ref event, window_id, } if window_id == self.window.id() => { // 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. { if let Some(mut event_queue) = self.world.get_resource_mut::() { event_queue.trigger_event(input_event.clone()); }; } 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) => { let mut state = self.world.with_resource(|| WindowState::new()); state.is_focused = *is_focused; }, _ => {} } } }, 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()); } */ self.renderer.as_mut().prepare(&mut self.world); if let Some(mut event_queue) = self.world.get_resource_mut::() { event_queue.update_events(); } match self.renderer.as_mut().render() { Ok(_) => {} // Reconfigure the surface if lost Err(wgpu::SurfaceError::Lost) => self.on_resize(self.renderer.as_ref().surface_size()).await, // 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 { world: Option, plugins: VecDeque>, system_dispatcher: Option, startup_systems: VecDeque>, } impl Default for Game { fn default() -> Self { Self { world: Some(edict::World::new()), plugins: VecDeque::new(), system_dispatcher: Some(SystemDispatcher::new()), startup_systems: VecDeque::new(), } } } impl Game { pub async fn initialize() -> Game { Self::default() } /// Get the world of this game pub fn world(&mut self) -> &mut edict::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(&mut self, name: &str, system: S, depends: &[&str]) -> &mut Self where S: SimpleSystem + 'static { let system_dispatcher = self.system_dispatcher.as_mut().unwrap(); system_dispatcher.add_system(name, 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(&mut self, system: S) -> &mut Self where S: SimpleSystem + '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 pub fn with_plugin

(&mut self, plugin: P) -> &mut Self where P: Plugin + 'static { self.plugins.push_back(Box::new(plugin)); self } /// Override the default (empty) world /// /// This isn't recommended, you should create a startup system and add it to `with_startup_system` pub fn with_world(&mut self, world: edict::World) -> &mut Self { self.world = Some(world); self } /// Start the game 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::INFO) .with_default(Level::DEBUG)) .init(); // setup all the plugins while let Some(plugin) = self.plugins.pop_front() { plugin.as_ref().setup(self); } let mut world = self.world.take().unwrap_or_else(|| edict::World::new()); // run startup systems while let Some(mut startup) = self.startup_systems.pop_front() { let startup = startup.as_mut(); startup.setup(&mut world).expect("World returned an error!"); startup.execute_mut(&mut world).expect("World returned an error!"); } // start winit event loops let event_loop = EventLoop::new(); let window = Arc::new(WindowBuilder::new().build(&event_loop).unwrap()); let system_dispatcher = self.system_dispatcher.take().unwrap(); let mut g_loop = GameLoop::new(Arc::clone(&window), world, system_dispatcher).await; g_loop.on_init().await; event_loop.run(move |event, _, control_flow| { g_loop.run_sync(event, control_flow); }); } }