#[cfg(feature = "plugins")] use crate::plugin::PluginMgr; use common::{ comp, event::{EventBus, LocalEvent, ServerEvent}, metrics::{PhysicsMetrics, SysMetrics}, region::RegionMap, resources, resources::{DeltaTime, Time, TimeOfDay}, span, terrain::{Block, TerrainChunk, TerrainGrid}, time::DayPeriod, vol::{ReadVol, WriteVol}, }; use common_net::sync::WorldSyncExt; use hashbrown::{HashMap, HashSet}; use rayon::{ThreadPool, ThreadPoolBuilder}; use specs::{ shred::{Fetch, FetchMut}, storage::{MaskedStorage as EcsMaskedStorage, Storage as EcsStorage}, Component, DispatcherBuilder, Entity as EcsEntity, WorldExt, }; use std::{sync::Arc, time::Duration}; use vek::*; /// How much faster should an in-game day be compared to a real day? // TODO: Don't hard-code this. const DAY_CYCLE_FACTOR: f64 = 24.0 * 2.0; /// At what point should we stop speeding up physics to compensate for lag? If /// we speed physics up too fast, we'd skip important physics events like /// collisions. This constant determines the upper limit. If delta time exceeds /// this value, the game's physics will begin to produce time lag. Ideally, we'd /// avoid such a situation. const MAX_DELTA_TIME: f32 = 1.0; const HUMANOID_JUMP_ACCEL: f32 = 16.0; #[derive(Default)] pub struct BlockChange { blocks: HashMap, Block>, } impl BlockChange { pub fn set(&mut self, pos: Vec3, block: Block) { self.blocks.insert(pos, block); } pub fn try_set(&mut self, pos: Vec3, block: Block) -> Option<()> { if !self.blocks.contains_key(&pos) { self.blocks.insert(pos, block); Some(()) } else { None } } pub fn clear(&mut self) { self.blocks.clear(); } } #[derive(Default)] pub struct TerrainChanges { pub new_chunks: HashSet>, pub modified_chunks: HashSet>, pub removed_chunks: HashSet>, pub modified_blocks: HashMap, Block>, } impl TerrainChanges { pub fn clear(&mut self) { self.new_chunks.clear(); self.modified_chunks.clear(); self.removed_chunks.clear(); } } #[derive(Copy, Clone)] pub enum ExecMode { Server, Client, Singleplayer, } /// A type used to represent game state stored on both the client and the /// server. This includes things like entity components, terrain data, and /// global states like weather, time of day, etc. pub struct State { ecs: specs::World, // Avoid lifetime annotation by storing a thread pool instead of the whole dispatcher thread_pool: Arc, } impl State { /// Create a new `State` in client mode. pub fn client() -> Self { Self::new(resources::GameMode::Client) } /// Create a new `State` in server mode. pub fn server() -> Self { Self::new(resources::GameMode::Server) } pub fn new(game_mode: resources::GameMode) -> Self { Self { ecs: Self::setup_ecs_world(game_mode), thread_pool: Arc::new(ThreadPoolBuilder::new().build().unwrap()), } } /// Creates ecs world and registers all the common components and resources // TODO: Split up registering into server and client (e.g. move // EventBus to the server) fn setup_ecs_world(game_mode: resources::GameMode) -> specs::World { let mut ecs = specs::World::new(); // Uids for sync ecs.register_sync_marker(); // Register server -> all clients synced components. ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); // Register components send from clients -> server ecs.register::(); // Register components send directly from server -> all but one client ecs.register::(); // Register components synced from client -> server -> all other clients ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); // Register client-local components // TODO: only register on the client ecs.register::(); // Register server-local components // TODO: only register on the server ecs.register::>(); ecs.register::>(); ecs.register::>(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); ecs.register::(); // Register synced resources used by the ECS. ecs.insert(TimeOfDay(0.0)); // Register unsynced resources used by the ECS. ecs.insert(Time(0.0)); ecs.insert(DeltaTime(0.0)); ecs.insert(TerrainGrid::new().unwrap()); ecs.insert(BlockChange::default()); ecs.insert(TerrainChanges::default()); ecs.insert(EventBus::::default()); ecs.insert(game_mode); ecs.insert(Vec::::new()); // TODO: only register on the server ecs.insert(EventBus::::default()); ecs.insert(comp::group::GroupManager::default()); ecs.insert(RegionMap::new()); ecs.insert(SysMetrics::default()); ecs.insert(PhysicsMetrics::default()); // Load plugins from asset directory #[cfg(feature = "plugins")] ecs.insert(match PluginMgr::from_assets() { Ok(plugin_mgr) => { if let Err(e) = plugin_mgr .execute_event("on_load", &plugin_api::event::PluginLoadEvent { game_mode }) { tracing::error!(?e, "Failed to run plugin init"); tracing::info!( "Error occurred when loading plugins. Running without plugins instead." ); PluginMgr::default() } else { plugin_mgr } }, Err(_) => { tracing::info!( "Error occurred when loading plugins. Running without plugins instead." ); PluginMgr::default() }, }); ecs } /// Register a component with the state's ECS. pub fn with_component(mut self) -> Self where ::Storage: Default, { self.ecs.register::(); self } /// Write a component attributed to a particular entity. pub fn write_component(&mut self, entity: EcsEntity, comp: C) { let _ = self.ecs.write_storage().insert(entity, comp); } /// Delete a component attributed to a particular entity. pub fn delete_component(&mut self, entity: EcsEntity) -> Option { self.ecs.write_storage().remove(entity) } /// Read a component attributed to a particular entity. pub fn read_component_cloned(&self, entity: EcsEntity) -> Option { self.ecs.read_storage().get(entity).cloned() } /// Read a component attributed to a particular entity. pub fn read_component_copied(&self, entity: EcsEntity) -> Option { self.ecs.read_storage().get(entity).copied() } /// Get a read-only reference to the storage of a particular component type. pub fn read_storage(&self) -> EcsStorage>> { self.ecs.read_storage::() } /// Get a reference to the internal ECS world. pub fn ecs(&self) -> &specs::World { &self.ecs } /// Get a mutable reference to the internal ECS world. pub fn ecs_mut(&mut self) -> &mut specs::World { &mut self.ecs } /// Get a reference to the `TerrainChanges` structure of the state. This /// contains information about terrain state that has changed since the /// last game tick. pub fn terrain_changes(&self) -> Fetch { self.ecs.read_resource() } /// Get the current in-game time of day. /// /// Note that this should not be used for physics, animations or other such /// localised timings. pub fn get_time_of_day(&self) -> f64 { self.ecs.read_resource::().0 } /// Get the current in-game day period (period of the day/night cycle) /// Get the current in-game day period (period of the day/night cycle) pub fn get_day_period(&self) -> DayPeriod { self.get_time_of_day().into() } /// Get the current in-game time. /// /// Note that this does not correspond to the time of day. pub fn get_time(&self) -> f64 { self.ecs.read_resource::