diff --git a/chat-cli/src/main.rs b/chat-cli/src/main.rs index f21da11295..b74c1ea87f 100644 --- a/chat-cli/src/main.rs +++ b/chat-cli/src/main.rs @@ -55,9 +55,11 @@ fn main() { .unwrap(); let (tx, rx) = mpsc::channel(); - thread::spawn(move || loop { - let msg = read_input(); - tx.send(msg).unwrap(); + thread::spawn(move || { + loop { + let msg = read_input(); + tx.send(msg).unwrap(); + } }); loop { @@ -74,13 +76,13 @@ fn main() { Err(err) => { error!("Error: {:?}", err); break; - } + }, }; for event in events { match event { Event::Chat { message, .. } => println!("{}", message), - Event::Disconnect => {} // TODO + Event::Disconnect => {}, // TODO Event::DisconnectionNotification(time) => { let message = match time { 0 => String::from("Goodbye!"), @@ -88,7 +90,7 @@ fn main() { }; println!("{}", message) - } + }, } } diff --git a/client/src/error.rs b/client/src/error.rs index 27ff6b9142..154387e16c 100644 --- a/client/src/error.rs +++ b/client/src/error.rs @@ -13,7 +13,5 @@ pub enum Error { } impl From for Error { - fn from(err: PostError) -> Self { - Error::Network(err) - } + fn from(err: PostError) -> Self { Error::Network(err) } } diff --git a/client/src/lib.rs b/client/src/lib.rs index 056f28b0e6..90ecb651c6 100644 --- a/client/src/lib.rs +++ b/client/src/lib.rs @@ -41,7 +41,8 @@ use vek::*; // and be provided to the client const SERVER_TIMEOUT: Duration = Duration::from_secs(20); -// After this duration has elapsed, the user will begin getting kick warnings in their chat window +// After this duration has elapsed, the user will begin getting kick warnings in +// their chat window const SERVER_TIMEOUT_GRACE_PERIOD: Duration = Duration::from_secs(14); pub enum Event { @@ -94,7 +95,8 @@ impl Client { // TODO: Display that versions don't match in Voxygen if server_info.git_hash != common::util::GIT_HASH.to_string() { log::warn!( - "Server is running {}[{}], you are running {}[{}], versions might be incompatible!", + "Server is running {}[{}], you are running {}[{}], versions might be \ + incompatible!", server_info.git_hash, server_info.git_date, common::util::GIT_HASH.to_string(), @@ -125,10 +127,10 @@ impl Client { log::debug!("Done preparing image..."); (state, entity, server_info, (world_map, map_size)) - } + }, Some(ServerMsg::Error(ServerError::TooManyPlayers)) => { - return Err(Error::TooManyPlayers) - } + return Err(Error::TooManyPlayers); + }, _ => return Err(Error::ServerWentMad), }; @@ -176,10 +178,10 @@ impl Client { loop { match self.postbox.next_message() { Some(ServerMsg::StateAnswer(Err((RequestStateError::Denied, _)))) => { - break Err(Error::InvalidAuth) - } + break Err(Error::InvalidAuth); + }, Some(ServerMsg::StateAnswer(Ok(ClientState::Registered))) => break Ok(()), - _ => {} + _ => {}, } } } @@ -197,7 +199,8 @@ impl Client { self.client_state = ClientState::Pending; } - /// Request a state transition to `ClientState::Registered` from an ingame state. + /// Request a state transition to `ClientState::Registered` from an ingame + /// state. pub fn request_remove_character(&mut self) { self.postbox.send_message(ClientMsg::ExitIngame); self.client_state = ClientState::Pending; @@ -260,13 +263,9 @@ impl Client { .send_message(ClientMsg::ControlEvent(ControlEvent::Unmount)); } - pub fn view_distance(&self) -> Option { - self.view_distance - } + pub fn view_distance(&self) -> Option { self.view_distance } - pub fn loaded_distance(&self) -> f32 { - self.loaded_distance - } + pub fn loaded_distance(&self) -> f32 { self.loaded_distance } pub fn current_chunk(&self) -> Option> { let chunk_pos = Vec2::from( @@ -283,9 +282,7 @@ impl Client { self.state.terrain().get_key_arc(chunk_pos).cloned() } - pub fn inventories(&self) -> ReadStorage { - self.state.read_storage() - } + pub fn inventories(&self) -> ReadStorage { self.state.read_storage() } /// Send a chat message to the server. pub fn send_chat(&mut self, message: String) { @@ -319,17 +316,19 @@ impl Client { ))); } - /// Execute a single client tick, handle input and update the game state by the given duration. + /// Execute a single client tick, handle input and update the game state by + /// the given duration. pub fn tick( &mut self, inputs: ControllerInputs, dt: Duration, add_foreign_systems: impl Fn(&mut DispatcherBuilder), ) -> Result, Error> { - // This tick function is the centre of the Veloren universe. Most client-side things are - // managed from here, and as such it's important that it stays organised. Please consult - // the core developers before making significant changes to this code. Here is the - // approximate order of things. Please update it as this code changes. + // This tick function is the centre of the Veloren universe. Most client-side + // things are managed from here, and as such it's important that it + // stays organised. Please consult the core developers before making + // significant changes to this code. Here is the approximate order of + // things. Please update it as this code changes. // // 1) Collect input from the frontend, apply input effects to the state // of the game @@ -347,13 +346,10 @@ impl Client { // 1) Handle input from frontend. // Pass character actions from frontend input to the player's entity. if let ClientState::Character = self.client_state { - self.state.write_component( - self.entity, - Controller { - inputs: inputs.clone(), - events: Vec::new(), - }, - ); + self.state.write_component(self.entity, Controller { + inputs: inputs.clone(), + events: Vec::new(), + }); self.postbox .send_message(ClientMsg::ControllerInputs(inputs)); } @@ -528,7 +524,8 @@ impl Client { let mut frontend_events = Vec::new(); // Check that we have an valid connection. - // Use the last ping time as a 1s rate limiter, we only notify the user once per second + // Use the last ping time as a 1s rate limiter, we only notify the user once per + // second if Instant::now().duration_since(self.last_server_ping) > Duration::from_secs(1) { let duration_since_last_pong = Instant::now().duration_since(self.last_server_pong); @@ -558,24 +555,37 @@ impl Client { ServerMsg::InitialSync { .. } => return Err(Error::ServerWentMad), ServerMsg::PlayerListUpdate(PlayerListUpdate::Init(list)) => { self.player_list = list - } + }, ServerMsg::PlayerListUpdate(PlayerListUpdate::Add(uid, name)) => { if let Some(old_name) = self.player_list.insert(uid, name.clone()) { - warn!("Received msg to insert {} with uid {} into the player list but there was already an entry for {} with the same uid that was overwritten!", name, uid, old_name); + warn!( + "Received msg to insert {} with uid {} into the player list but \ + there was already an entry for {} with the same uid that was \ + overwritten!", + name, uid, old_name + ); } - } + }, ServerMsg::PlayerListUpdate(PlayerListUpdate::Remove(uid)) => { if self.player_list.remove(&uid).is_none() { - warn!("Received msg to remove uid {} from the player list by they weren't in the list!", uid); + warn!( + "Received msg to remove uid {} from the player list by they \ + weren't in the list!", + uid + ); } - } + }, ServerMsg::PlayerListUpdate(PlayerListUpdate::Alias(uid, new_name)) => { if let Some(name) = self.player_list.get_mut(&uid) { *name = new_name; } else { - warn!("Received msg to alias player with uid {} to {} but this uid is not in the player list", uid, new_name); + warn!( + "Received msg to alias player with uid {} to {} but this uid is \ + not in the player list", + uid, new_name + ); } - } + }, ServerMsg::Ping => self.postbox.send_message(ClientMsg::Pong), ServerMsg::Pong => { @@ -584,26 +594,26 @@ impl Client { self.last_ping_delta = Instant::now() .duration_since(self.last_server_ping) .as_secs_f64(); - } + }, ServerMsg::ChatMsg { message, chat_type } => { frontend_events.push(Event::Chat { message, chat_type }) - } + }, ServerMsg::SetPlayerEntity(uid) => { if let Some(entity) = self.state.ecs().entity_from_uid(uid) { self.entity = entity; } else { return Err(Error::Other("Failed to find entity from uid.".to_owned())); } - } + }, ServerMsg::TimeOfDay(time_of_day) => { *self.state.ecs_mut().write_resource() = time_of_day; - } + }, ServerMsg::EcsSync(sync_package) => { self.state.ecs_mut().apply_sync_package(sync_package); - } + }, ServerMsg::CreateEntity(entity_package) => { self.state.ecs_mut().apply_entity_package(entity_package); - } + }, ServerMsg::DeleteEntity(entity) => { if self .state @@ -615,7 +625,7 @@ impl Client { .ecs_mut() .delete_entity_and_clear_from_uid_allocator(entity); } - } + }, // Cleanup for when the client goes back to the `Registered` state ServerMsg::ExitIngameCleanup => { // Get client entity Uid @@ -635,22 +645,22 @@ impl Client { .write_resource::() .allocate(entity_builder.entity, Some(client_uid)); self.entity = entity_builder.with(uid).build(); - } + }, ServerMsg::EntityPos { entity, pos } => { if let Some(entity) = self.state.ecs().entity_from_uid(entity) { self.state.write_component(entity, pos); } - } + }, ServerMsg::EntityVel { entity, vel } => { if let Some(entity) = self.state.ecs().entity_from_uid(entity) { self.state.write_component(entity, vel); } - } + }, ServerMsg::EntityOri { entity, ori } => { if let Some(entity) = self.state.ecs().entity_from_uid(entity) { self.state.write_component(entity, ori); } - } + }, ServerMsg::EntityCharacterState { entity, character_state, @@ -658,24 +668,24 @@ impl Client { if let Some(entity) = self.state.ecs().entity_from_uid(entity) { self.state.write_component(entity, character_state); } - } + }, ServerMsg::InventoryUpdate(inventory) => { self.state.write_component(self.entity, inventory) - } + }, ServerMsg::TerrainChunkUpdate { key, chunk } => { if let Ok(chunk) = chunk { self.state.insert_chunk(key, *chunk); } self.pending_chunks.remove(&key); - } + }, ServerMsg::TerrainBlockUpdates(mut blocks) => { blocks.drain().for_each(|(pos, block)| { self.state.set_block(pos, block); }); - } + }, ServerMsg::StateAnswer(Ok(state)) => { self.client_state = state; - } + }, ServerMsg::StateAnswer(Err((error, state))) => { if error == RequestStateError::Denied { warn!("Connection denied!"); @@ -685,10 +695,10 @@ impl Client { "StateAnswer: {:?}. Server thinks client is in state {:?}.", error, state ); - } + }, ServerMsg::Disconnect => { frontend_events.push(Event::Disconnect); - } + }, } } } else if let Some(err) = self.postbox.error() { @@ -701,40 +711,27 @@ impl Client { } /// Get the player's entity. - pub fn entity(&self) -> EcsEntity { - self.entity - } + pub fn entity(&self) -> EcsEntity { self.entity } /// Get the client state - pub fn get_client_state(&self) -> ClientState { - self.client_state - } + pub fn get_client_state(&self) -> ClientState { self.client_state } /// Get the current tick number. - pub fn get_tick(&self) -> u64 { - self.tick - } + pub fn get_tick(&self) -> u64 { self.tick } - pub fn get_ping_ms(&self) -> f64 { - self.last_ping_delta * 1000.0 - } + pub fn get_ping_ms(&self) -> f64 { self.last_ping_delta * 1000.0 } - /// Get a reference to the client's worker thread pool. This pool should be used for any - /// computationally expensive operations that run outside of the main thread (i.e., threads that - /// block on I/O operations are exempt). - pub fn thread_pool(&self) -> &ThreadPool { - &self.thread_pool - } + /// Get a reference to the client's worker thread pool. This pool should be + /// used for any computationally expensive operations that run outside + /// of the main thread (i.e., threads that block on I/O operations are + /// exempt). + pub fn thread_pool(&self) -> &ThreadPool { &self.thread_pool } /// Get a reference to the client's game state. - pub fn state(&self) -> &State { - &self.state - } + pub fn state(&self) -> &State { &self.state } /// Get a mutable reference to the client's game state. - pub fn state_mut(&mut self) -> &mut State { - &mut self.state - } + pub fn state_mut(&mut self) -> &mut State { &mut self.state } /// Get a vector of all the players on the server pub fn get_players(&mut self) -> Vec { @@ -749,7 +746,5 @@ impl Client { } impl Drop for Client { - fn drop(&mut self) { - self.postbox.send_message(ClientMsg::Disconnect); - } + fn drop(&mut self) { self.postbox.send_message(ClientMsg::Disconnect); } } diff --git a/common/benches/chonk_benchmark.rs b/common/benches/chonk_benchmark.rs index d325f02888..d6fd95e695 100644 --- a/common/benches/chonk_benchmark.rs +++ b/common/benches/chonk_benchmark.rs @@ -1,7 +1,4 @@ -use criterion::black_box; -use criterion::criterion_group; -use criterion::criterion_main; -use criterion::Criterion; +use criterion::{black_box, criterion_group, criterion_main, Criterion}; use vek::*; use veloren_common::{ diff --git a/common/benches/color_benchmark.rs b/common/benches/color_benchmark.rs index 5031cb4c06..ad6f930774 100644 --- a/common/benches/color_benchmark.rs +++ b/common/benches/color_benchmark.rs @@ -1,7 +1,4 @@ -use criterion::black_box; -use criterion::criterion_group; -use criterion::criterion_main; -use criterion::Criterion; +use criterion::{black_box, criterion_group, criterion_main, Criterion}; use vek::*; use veloren_common::util::{linear_to_srgb, srgb_to_linear}; diff --git a/common/build.rs b/common/build.rs index 44d7aed036..a56637b973 100644 --- a/common/build.rs +++ b/common/build.rs @@ -1,10 +1,10 @@ -use std::env; -use std::fs::File; -use std::io::Read; -use std::io::Write; -use std::path::Path; -use std::path::PathBuf; -use std::process::Command; +use std::{ + env, + fs::File, + io::{Read, Write}, + path::{Path, PathBuf}, + process::Command, +}; fn main() { // Get the current githash @@ -30,7 +30,7 @@ fn main() { target .write_all(hash.trim().as_bytes()) .expect("failed to write to file!"); - } + }, Err(e) => panic!("failed to convert git output to UTF-8: {}", e), }, Err(e) => panic!("failed to retrieve current git commit hash: {}", e), diff --git a/common/src/assets/mod.rs b/common/src/assets/mod.rs index 8198aa657f..cadff415de 100644 --- a/common/src/assets/mod.rs +++ b/common/src/assets/mod.rs @@ -21,7 +21,8 @@ use std::{ pub enum Error { /// An internal error occurred. Internal(Arc), - /// An asset of a different type has already been loaded with this specifier. + /// An asset of a different type has already been loaded with this + /// specifier. InvalidType, /// Asset does not exist. NotFound(String), @@ -41,15 +42,11 @@ impl fmt::Display for Error { } impl From> for Error { - fn from(_: Arc) -> Self { - Error::InvalidType - } + fn from(_: Arc) -> Self { Error::InvalidType } } impl From for Error { - fn from(err: std::io::Error) -> Self { - Error::NotFound(format!("{}", err)) - } + fn from(err: std::io::Error) -> Self { Error::NotFound(format!("{}", err)) } } lazy_static! { @@ -58,19 +55,20 @@ lazy_static! { RwLock::new(HashMap::new()); } -// TODO: Remove this function. It's only used in world/ in a really ugly way.To do this properly -// assets should have all their necessary data in one file. A ron file could be used to combine -// voxel data with positioning data for example. -/// Function used to load assets from the filesystem or the cache. Permits manipulating the loaded asset with a mapping function. -/// Example usage: +// TODO: Remove this function. It's only used in world/ in a really ugly way.To +// do this properly assets should have all their necessary data in one file. A +// ron file could be used to combine voxel data with positioning data for +// example. +/// Function used to load assets from the filesystem or the cache. Permits +/// manipulating the loaded asset with a mapping function. Example usage: /// ```no_run -/// use veloren_common::{assets, terrain::Structure}; /// use vek::*; +/// use veloren_common::{assets, terrain::Structure}; /// -/// let my_tree_structure = assets::load_map( -/// "world.tree.oak_green.1", -/// |s: Structure| s.with_center(Vec3::new(15, 18, 14)), -/// ).unwrap(); +/// let my_tree_structure = assets::load_map("world.tree.oak_green.1", |s: Structure| { +/// s.with_center(Vec3::new(15, 18, 14)) +/// }) +/// .unwrap(); /// ``` pub fn load_map A>( specifier: &str, @@ -84,7 +82,7 @@ pub fn load_map A>( let clone = Arc::clone(&asset); assets_write.insert(specifier.to_owned(), clone); Ok(asset) - } + }, } } @@ -120,7 +118,7 @@ pub fn load_glob(specifier: &str) -> Result>> let mut assets_write = ASSETS.write().unwrap(); assets_write.insert(specifier.to_owned(), clone); Ok(assets) - } + }, Err(error) => Err(error), } } @@ -137,13 +135,14 @@ pub fn load(specifier: &str) -> Result, Error> { load_map(specifier, |x| x) } -/// Function used to load assets from the filesystem or the cache and return a clone. +/// Function used to load assets from the filesystem or the cache and return a +/// clone. pub fn load_cloned(specifier: &str) -> Result { load::(specifier).map(|asset| (*asset).clone()) } -/// Function used to load essential assets from the filesystem or the cache. It will panic if the asset is not found. -/// Example usage: +/// Function used to load essential assets from the filesystem or the cache. It +/// will panic if the asset is not found. Example usage: /// ```no_run /// use image::DynamicImage; /// use veloren_common::assets; @@ -159,12 +158,14 @@ pub fn load_expect(specifier: &str) -> Arc { }) } -/// Function used to load essential assets from the filesystem or the cache and return a clone. It will panic if the asset is not found. +/// Function used to load essential assets from the filesystem or the cache and +/// return a clone. It will panic if the asset is not found. pub fn load_expect_cloned(specifier: &str) -> A { load_expect::(specifier).as_ref().clone() } -/// Load an asset while registering it to be watched and reloaded when it changes +/// Load an asset while registering it to be watched and reloaded when it +/// changes pub fn load_watched( specifier: &str, indicator: &mut watch::ReloadIndicator, @@ -205,14 +206,14 @@ fn reload(specifier: &str) -> Result<(), Error> { Some(a) => *a = clone, None => { assets_write.insert(specifier.to_owned(), clone); - } + }, } Ok(()) } -/// The Asset trait, which is implemented by all structures that have their data stored in the -/// filesystem. +/// The Asset trait, which is implemented by all structures that have their data +/// stored in the filesystem. pub trait Asset: Send + Sync + Sized { const ENDINGS: &'static [&'static str]; /// Parse the input file and return the correct Asset. @@ -221,6 +222,7 @@ pub trait Asset: Send + Sync + Sized { impl Asset for DynamicImage { const ENDINGS: &'static [&'static str] = &["png", "jpg"]; + fn parse(mut buf_reader: BufReader) -> Result { let mut buf = Vec::new(); buf_reader.read_to_end(&mut buf)?; @@ -230,6 +232,7 @@ impl Asset for DynamicImage { impl Asset for DotVoxData { const ENDINGS: &'static [&'static str] = &["vox"]; + fn parse(mut buf_reader: BufReader) -> Result { let mut buf = Vec::new(); buf_reader.read_to_end(&mut buf)?; @@ -240,6 +243,7 @@ impl Asset for DotVoxData { // Read a JSON file impl Asset for Value { const ENDINGS: &'static [&'static str] = &["json"]; + fn parse(buf_reader: BufReader) -> Result { Ok(serde_json::from_reader(buf_reader).unwrap()) } @@ -247,6 +251,7 @@ impl Asset for Value { impl Asset for String { const ENDINGS: &'static [&'static str] = &["glsl"]; + fn parse(mut buf_reader: BufReader) -> Result { let mut string = String::new(); buf_reader.read_to_string(&mut string)?; @@ -300,7 +305,8 @@ lazy_static! { }; } -/// Converts a specifier like "core.backgrounds.city" to ".../veloren/assets/core/backgrounds/city". +/// Converts a specifier like "core.backgrounds.city" to +/// ".../veloren/assets/core/backgrounds/city". fn unpack_specifier(specifier: &str) -> PathBuf { let mut path = ASSETS_PATH.clone(); path.push(specifier.replace(".", "/")); diff --git a/common/src/assets/watch.rs b/common/src/assets/watch.rs index 91f3b3ddad..6d79340412 100644 --- a/common/src/assets/watch.rs +++ b/common/src/assets/watch.rs @@ -19,7 +19,8 @@ lazy_static! { Mutex::new(Watcher::new().run()); } -// This will need to be adjusted when specifier mapping to asset location becomes more dynamic +// This will need to be adjusted when specifier mapping to asset location +// becomes more dynamic struct Watcher { watching: HashMap>)>, watcher: RecommendedWatcher, @@ -37,6 +38,7 @@ impl Watcher { event_rx, } } + fn watch(&mut self, path: PathBuf, handler: Handler, signal: Weak) { match self.watching.get_mut(&path) { Some((_, ref mut v)) => { @@ -46,16 +48,17 @@ impl Watcher { }) { v.push(signal); } - } + }, None => { if let Err(err) = self.watcher.watch(path.clone(), RecursiveMode::Recursive) { warn!("Could not start watching {:#?} due to: {}", &path, err); return; } self.watching.insert(path, (handler, vec![signal])); - } + }, } } + fn handle_event(&mut self, event: Event) { if let Event { kind: EventKind::Modify(_), @@ -74,7 +77,7 @@ impl Watcher { Some(signal) => { signal.store(true, Ordering::Release); true - } + }, None => false, }); } @@ -85,17 +88,22 @@ impl Watcher { } self.watching.remove(&path); } - } + }, None => { - warn!("Watching {:#?} but there are no signals for this path. The path will be unwatched.", path); + warn!( + "Watching {:#?} but there are no signals for this path. The path will \ + be unwatched.", + path + ); if let Err(err) = self.watcher.unwatch(&path) { warn!("Error unwatching: {}", err); } - } + }, } } } } + fn run(mut self) -> Sender<(PathBuf, Handler, Weak)> { let (watch_tx, watch_rx) = unbounded(); @@ -134,6 +142,7 @@ impl ReloadIndicator { paths: Vec::new(), } } + pub fn add(&mut self, path: PathBuf, reloader: F) where F: 'static + Fn() + Send, @@ -155,8 +164,7 @@ impl ReloadIndicator { error!("Could not add. Asset watcher channel disconnected."); } } + // Returns true if the watched file was changed - pub fn reloaded(&self) -> bool { - self.reloaded.swap(false, Ordering::Acquire) - } + pub fn reloaded(&self) -> bool { self.reloaded.swap(false, Ordering::Acquire) } } diff --git a/common/src/astar.rs b/common/src/astar.rs index a74ac64e67..4c153c9de9 100644 --- a/common/src/astar.rs +++ b/common/src/astar.rs @@ -1,10 +1,7 @@ use crate::path::Path; use core::cmp::Ordering::Equal; use hashbrown::{HashMap, HashSet}; -use std::cmp::Ordering; -use std::collections::BinaryHeap; -use std::f32; -use std::hash::Hash; +use std::{cmp::Ordering, collections::BinaryHeap, f32, hash::Hash}; #[derive(Copy, Clone, Debug)] pub struct PathEntry { @@ -13,9 +10,7 @@ pub struct PathEntry { } impl PartialEq for PathEntry { - fn eq(&self, other: &PathEntry) -> bool { - self.node.eq(&other.node) - } + fn eq(&self, other: &PathEntry) -> bool { self.node.eq(&other.node) } } impl Eq for PathEntry {} @@ -29,9 +24,7 @@ impl Ord for PathEntry { } impl PartialOrd for PathEntry { - fn partial_cmp(&self, other: &PathEntry) -> Option { - Some(self.cmp(other)) - } + fn partial_cmp(&self, other: &PathEntry) -> Option { Some(self.cmp(other)) } } pub enum PathResult { diff --git a/common/src/clock.rs b/common/src/clock.rs index d03a95e815..10f9d7601c 100644 --- a/common/src/clock.rs +++ b/common/src/clock.rs @@ -22,17 +22,13 @@ impl Clock { } } - pub fn get_tps(&self) -> f64 { - 1.0 / self.running_tps_average - } + pub fn get_tps(&self) -> f64 { 1.0 / self.running_tps_average } pub fn get_last_delta(&self) -> Duration { self.last_delta.unwrap_or_else(|| Duration::new(0, 0)) } - pub fn get_avg_delta(&self) -> Duration { - Duration::from_secs_f64(self.running_tps_average) - } + pub fn get_avg_delta(&self) -> Duration { Duration::from_secs_f64(self.running_tps_average) } pub fn tick(&mut self, tgt: Duration) { let delta = Instant::now().duration_since(self.last_sys_time); diff --git a/common/src/comp/agent.rs b/common/src/comp/agent.rs index 5652a0ca87..80965cf2cc 100644 --- a/common/src/comp/agent.rs +++ b/common/src/comp/agent.rs @@ -81,7 +81,5 @@ impl Activity { } impl Default for Activity { - fn default() -> Self { - Activity::Idle(Vec2::zero()) - } + fn default() -> Self { Activity::Idle(Vec2::zero()) } } diff --git a/common/src/comp/body.rs b/common/src/comp/body.rs index b1cc8dd44b..ac3569cb1d 100644 --- a/common/src/comp/body.rs +++ b/common/src/comp/body.rs @@ -45,8 +45,8 @@ pub struct BodyData { pub species: SpeciesData, } -/// Metadata intended to be stored per-body, together with data intended to be stored for each -/// species for each body. +/// Metadata intended to be stored per-body, together with data intended to be +/// stored for each species for each body. /// /// NOTE: Deliberately don't (yet?) implement serialize. #[derive(Clone, Debug, Deserialize)] @@ -76,11 +76,12 @@ impl core::ops::Index for AllBodies serde::Deserialize<'de>, - SpeciesMeta: Send + Sync + for<'de> serde::Deserialize<'de>, - > Asset for AllBodies + BodyMeta: Send + Sync + for<'de> serde::Deserialize<'de>, + SpeciesMeta: Send + Sync + for<'de> serde::Deserialize<'de>, +> Asset for AllBodies { const ENDINGS: &'static [&'static str] = &["json"]; + fn parse(buf_reader: BufReader) -> Result { serde_json::de::from_reader(buf_reader).map_err(|e| assets::Error::Internal(Arc::new(e))) } @@ -93,6 +94,7 @@ impl Body { _ => false, } } + // Note: this might need to be refined to something more complex for realistic // behavior with less cylindrical bodies (e.g. wolfs) pub fn radius(&self) -> f32 { diff --git a/common/src/comp/body/humanoid.rs b/common/src/comp/body/humanoid.rs index c75d899de2..9e77190436 100644 --- a/common/src/comp/body/humanoid.rs +++ b/common/src/comp/body/humanoid.rs @@ -310,6 +310,7 @@ impl Race { Race::Undead => &UNDEAD_HAIR_COLORS, } } + fn skin_colors(self) -> &'static [Skin] { match self { Race::Danari => &DANARI_SKIN_COLORS, @@ -320,6 +321,7 @@ impl Race { Race::Undead => &UNDEAD_SKIN_COLORS, } } + fn eye_colors(self) -> &'static [EyeColor] { match self { Race::Danari => &DANARI_EYE_COLORS, @@ -330,6 +332,7 @@ impl Race { Race::Undead => &UNDEAD_EYE_COLORS, } } + pub fn hair_color(self, val: u8) -> Rgb { self.hair_colors() .get(val as usize) @@ -337,27 +340,27 @@ impl Race { .unwrap_or((0, 0, 0)) .into() } - pub fn num_hair_colors(self) -> u8 { - self.hair_colors().len() as u8 - } + + pub fn num_hair_colors(self) -> u8 { self.hair_colors().len() as u8 } + pub fn skin_color(self, val: u8) -> Skin { self.skin_colors() .get(val as usize) .copied() .unwrap_or(Skin::Tanned) } - pub fn num_skin_colors(self) -> u8 { - self.skin_colors().len() as u8 - } + + pub fn num_skin_colors(self) -> u8 { self.skin_colors().len() as u8 } + pub fn eye_color(self, val: u8) -> EyeColor { self.eye_colors() .get(val as usize) .copied() .unwrap_or(EyeColor::NobleBlue) } - pub fn num_eye_colors(self) -> u8 { - self.eye_colors().len() as u8 - } + + pub fn num_eye_colors(self) -> u8 { self.eye_colors().len() as u8 } + pub fn num_hair_styles(self, body_type: BodyType) -> u8 { match (self, body_type) { (Race::Danari, BodyType::Female) => 2, @@ -374,6 +377,7 @@ impl Race { (Race::Undead, BodyType::Male) => 3, } } + pub fn num_accessories(self, body_type: BodyType) -> u8 { match (self, body_type) { (Race::Danari, BodyType::Female) => 1, @@ -390,6 +394,7 @@ impl Race { (Race::Undead, BodyType::Male) => 1, } } + pub fn num_beards(self, body_type: BodyType) -> u8 { match (self, body_type) { (Race::Danari, BodyType::Female) => 1, @@ -527,6 +532,7 @@ impl EyeColor { EyeColor::ExoticPurple => Rgb::new(95, 32, 111), } } + pub fn dark_rgb(self) -> Rgb { match self { EyeColor::VigorousBlack => Rgb::new(32, 32, 32), @@ -541,9 +547,8 @@ impl EyeColor { EyeColor::ExoticPurple => Rgb::new(69, 23, 80), } } - pub fn white_rgb(self) -> Rgb { - Rgb::new(255, 255, 255) - } + + pub fn white_rgb(self) -> Rgb { Rgb::new(255, 255, 255) } } #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] @@ -606,6 +611,7 @@ impl Skin { }; Rgb::from(color) } + pub fn light_rgb(self) -> Rgb { let color = match self { Self::Pale => (255, 227, 193), @@ -632,6 +638,7 @@ impl Skin { }; Rgb::from(color) } + pub fn dark_rgb(self) -> Rgb { let color = match self { Self::Pale => (229, 192, 163), diff --git a/common/src/comp/character_state.rs b/common/src/comp/character_state.rs index 1ac19ae950..ec19fa7e30 100644 --- a/common/src/comp/character_state.rs +++ b/common/src/comp/character_state.rs @@ -101,10 +101,12 @@ impl CharacterState { // Check if enum item is the same without looking at the inner data std::mem::discriminant(&self.movement) == std::mem::discriminant(&other.movement) } + pub fn is_same_action(&self, other: &Self) -> bool { // Check if enum item is the same without looking at the inner data std::mem::discriminant(&self.action) == std::mem::discriminant(&other.action) } + pub fn is_same_state(&self, other: &Self) -> bool { self.is_same_movement(other) && self.is_same_action(other) } diff --git a/common/src/comp/controller.rs b/common/src/comp/controller.rs index 6712d2a85f..2f74fffbb8 100644 --- a/common/src/comp/controller.rs +++ b/common/src/comp/controller.rs @@ -53,15 +53,11 @@ impl Input { } /// Whether input is in `InputState::Pressed` state - pub fn is_pressed(&self) -> bool { - self.state == InputState::Pressed - } + pub fn is_pressed(&self) -> bool { self.state == InputState::Pressed } /// Whether it's the first frame this input has been in /// its current state - pub fn is_just_pressed(&self) -> bool { - (self.just_changed && self.is_pressed()) - } + pub fn is_just_pressed(&self) -> bool { (self.just_changed && self.is_pressed()) } /// Whether input has been in current state longer than /// `DEFAULT_HOLD_DURATION` @@ -78,14 +74,14 @@ impl Input { self.dirty = true; self.state = InputState::Pressed; self.duration = Duration::default(); - } + }, (true, false) => { self.just_changed = true; self.dirty = true; self.state = InputState::Unpressed; self.duration = Duration::default(); - } - (_, _) => {} + }, + (_, _) => {}, }; } @@ -95,9 +91,7 @@ impl Input { } /// Returns `input::duration` - pub fn get_dur(&self) -> Duration { - self.duration - } + pub fn get_dur(&self) -> Duration { self.duration } } impl Default for Input { @@ -154,6 +148,7 @@ impl ControllerInputs { self.toggle_wield.tick(dt); self.charge.tick(dt); } + /// Updates `inputs.move_dir`. pub fn update_move_dir(&mut self) { self.move_dir = if self.move_dir.magnitude_squared() > 1.0 { @@ -163,6 +158,7 @@ impl ControllerInputs { self.move_dir }; } + /// Updates `inputs.look_dir` pub fn update_look_dir(&mut self) { self.look_dir @@ -173,17 +169,11 @@ impl ControllerInputs { impl Controller { /// Sets all inputs to default - pub fn reset(&mut self) { - *self = Self::default(); - } + pub fn reset(&mut self) { *self = Self::default(); } - pub fn clear_events(&mut self) { - self.events.clear(); - } + pub fn clear_events(&mut self) { self.events.clear(); } - pub fn push_event(&mut self, event: ControlEvent) { - self.events.push(event); - } + pub fn push_event(&mut self, event: ControlEvent) { self.events.push(event); } } impl Component for Controller { diff --git a/common/src/comp/energy.rs b/common/src/comp/energy.rs index 32169ddbff..8cf2d9224e 100644 --- a/common/src/comp/energy.rs +++ b/common/src/comp/energy.rs @@ -34,13 +34,9 @@ impl Energy { } } - pub fn current(&self) -> u32 { - self.current - } + pub fn current(&self) -> u32 { self.current } - pub fn maximum(&self) -> u32 { - self.maximum - } + pub fn maximum(&self) -> u32 { self.maximum } pub fn set_to(&mut self, amount: u32, cause: EnergySource) { let amount = amount.min(self.maximum); diff --git a/common/src/comp/inventory/item.rs b/common/src/comp/inventory/item.rs index 23365ceb76..da958ee9b9 100644 --- a/common/src/comp/inventory/item.rs +++ b/common/src/comp/inventory/item.rs @@ -7,9 +7,7 @@ use crate::{ use rand::seq::SliceRandom; use specs::{Component, FlaggedStorage}; use specs_idvs::IDVStorage; -use std::fs::File; -use std::io::BufReader; -use std::time::Duration; +use std::{fs::File, io::BufReader, time::Duration}; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum Tool { @@ -37,6 +35,7 @@ impl Tool { Tool::Debug(_) => Duration::from_millis(0), } } + pub fn attack_buildup_duration(&self) -> Duration { match self { Tool::Sword => Duration::from_millis(100), @@ -49,6 +48,7 @@ impl Tool { Tool::Debug(_) => Duration::from_millis(0), } } + pub fn attack_recover_duration(&self) -> Duration { match self { Tool::Sword => Duration::from_millis(500), @@ -61,6 +61,7 @@ impl Tool { Tool::Debug(_) => Duration::from_millis(0), } } + pub fn attack_duration(&self) -> Duration { self.attack_buildup_duration() + self.attack_recover_duration() } @@ -74,7 +75,8 @@ pub enum Debug { #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum Armor { - // TODO: Don't make armor be a body part. Wearing enemy's head is funny but also a creepy thing to do. + // TODO: Don't make armor be a body part. Wearing enemy's head is funny but also a creepy + // thing to do. Helmet, Shoulders, Chestplate, @@ -128,18 +130,17 @@ pub struct Item { impl Asset for Item { const ENDINGS: &'static [&'static str] = &["ron"]; + fn parse(buf_reader: BufReader) -> Result { Ok(ron::de::from_reader(buf_reader).unwrap()) } } impl Item { - pub fn name(&self) -> &str { - &self.name - } - pub fn description(&self) -> &str { - &self.description - } + pub fn name(&self) -> &str { &self.name } + + pub fn description(&self) -> &str { &self.description } + pub fn try_reclaim_from_block(block: Block) -> Option { match block.kind() { BlockKind::Apple => Some(assets::load_expect_cloned("common.items.apple")), @@ -149,19 +150,19 @@ impl Item { BlockKind::PinkFlower => Some(assets::load_expect_cloned("common.items.flowers.pink")), BlockKind::PurpleFlower => { Some(assets::load_expect_cloned("common.items.flowers.purple")) - } + }, BlockKind::RedFlower => Some(assets::load_expect_cloned("common.items.flowers.red")), BlockKind::WhiteFlower => { Some(assets::load_expect_cloned("common.items.flowers.white")) - } + }, BlockKind::YellowFlower => { Some(assets::load_expect_cloned("common.items.flowers.yellow")) - } + }, BlockKind::Sunflower => Some(assets::load_expect_cloned("common.items.flowers.sun")), BlockKind::LongGrass => Some(assets::load_expect_cloned("common.items.grasses.long")), BlockKind::MediumGrass => { Some(assets::load_expect_cloned("common.items.grasses.medium")) - } + }, BlockKind::ShortGrass => Some(assets::load_expect_cloned("common.items.grasses.short")), BlockKind::Chest => Some(assets::load_expect_cloned( [ diff --git a/common/src/comp/inventory/mod.rs b/common/src/comp/inventory/mod.rs index c4c3c4c875..f6833ff923 100644 --- a/common/src/comp/inventory/mod.rs +++ b/common/src/comp/inventory/mod.rs @@ -15,32 +15,30 @@ pub struct Inventory { /// Errors which the methods on `Inventory` produce #[derive(Debug)] pub enum Error { - /// The inventory is full and items could not be added. The extra items have been returned. + /// The inventory is full and items could not be added. The extra items have + /// been returned. Full(Vec), } impl Inventory { - pub fn slots(&self) -> &[Option] { - &self.slots - } + pub fn slots(&self) -> &[Option] { &self.slots } - pub fn len(&self) -> usize { - self.slots.len() - } + pub fn len(&self) -> usize { self.slots.len() } - /// Adds a new item to the first empty slot of the inventory. Returns the item again if no free - /// slot was found. + /// Adds a new item to the first empty slot of the inventory. Returns the + /// item again if no free slot was found. pub fn push(&mut self, item: Item) -> Option { match self.slots.iter_mut().find(|slot| slot.is_none()) { Some(slot) => { *slot = Some(item); None - } + }, None => Some(item), } } - /// Add a series of items to inventory, returning any which do not fit as an error. + /// Add a series of items to inventory, returning any which do not fit as an + /// error. pub fn push_all>(&mut self, mut items: I) -> Result<(), Error> { // Vec doesn't allocate for zero elements so this should be cheap let mut leftovers = Vec::new(); @@ -62,10 +60,12 @@ impl Inventory { /// Add a series of items to an inventory without giving duplicates. /// (n * m complexity) /// - /// Error if inventory cannot contain the items (is full), returning the un-added items. - /// This is a lazy inefficient implementation, as it iterates over the inventory more times - /// than necessary (n^2) and with the proper structure wouldn't need to iterate at all, but because - /// this should be fairly cold code, clarity has been favored over efficiency. + /// Error if inventory cannot contain the items (is full), returning the + /// un-added items. This is a lazy inefficient implementation, as it + /// iterates over the inventory more times than necessary (n^2) and with + /// the proper structure wouldn't need to iterate at all, but because + /// this should be fairly cold code, clarity has been favored over + /// efficiency. pub fn push_all_unique>(&mut self, mut items: I) -> Result<(), Error> { let mut leftovers = Vec::new(); for item in &mut items { @@ -80,27 +80,23 @@ impl Inventory { } } - /// Replaces an item in a specific slot of the inventory. Returns the old item or the same item again if that slot - /// was not found. + /// Replaces an item in a specific slot of the inventory. Returns the old + /// item or the same item again if that slot was not found. pub fn insert(&mut self, cell: usize, item: Item) -> Result, Item> { match self.slots.get_mut(cell) { Some(slot) => { let old = slot.take(); *slot = Some(item); Ok(old) - } + }, None => Err(item), } } - pub fn is_full(&self) -> bool { - self.slots.iter().all(|slot| slot.is_some()) - } + pub fn is_full(&self) -> bool { self.slots.iter().all(|slot| slot.is_some()) } /// O(n) count the number of items in this inventory. - pub fn count(&self) -> usize { - self.slots.iter().filter_map(|slot| slot.as_ref()).count() - } + pub fn count(&self) -> usize { self.slots.iter().filter_map(|slot| slot.as_ref()).count() } /// O(n) check if an item is in this inventory. pub fn contains(&self, item: &Item) -> bool { @@ -148,5 +144,4 @@ impl Component for InventoryUpdate { type Storage = NullStorage; } -#[cfg(test)] -mod test; +#[cfg(test)] mod test; diff --git a/common/src/comp/inventory/test.rs b/common/src/comp/inventory/test.rs index 51abc2db73..f2665d7cb5 100644 --- a/common/src/comp/inventory/test.rs +++ b/common/src/comp/inventory/test.rs @@ -8,9 +8,7 @@ lazy_static! { } /// The `Default` inventory should contain two items #[test] -fn create_default_count() { - assert_eq!(Inventory::default().count(), 2) -} +fn create_default_count() { assert_eq!(Inventory::default().count(), 2) } /// Attempting to push into a full inventory should return the same item. #[test] @@ -36,7 +34,8 @@ fn push_all_full() { assert_eq!(leftovers, TEST_ITEMS.clone()) } -/// Attempting to push uniquely into an inventory containing all the items should work fine. +/// Attempting to push uniquely into an inventory containing all the items +/// should work fine. #[test] fn push_unique_all_full() { let mut inv = Inventory { @@ -46,7 +45,8 @@ fn push_unique_all_full() { .expect("Pushing unique items into an inventory that already contains them didn't work!"); } -/// Attempting to push uniquely into an inventory containing all the items should work fine. +/// Attempting to push uniquely into an inventory containing all the items +/// should work fine. #[test] fn push_all_empty() { let mut inv = Inventory { @@ -56,7 +56,8 @@ fn push_all_empty() { .expect("Pushing items into an empty inventory didn't work!"); } -/// Attempting to push uniquely into an inventory containing all the items should work fine. +/// Attempting to push uniquely into an inventory containing all the items +/// should work fine. #[test] fn push_all_unique_empty() { let mut inv = Inventory { diff --git a/common/src/comp/location.rs b/common/src/comp/location.rs index 879c91ce5e..492ca13114 100644 --- a/common/src/comp/location.rs +++ b/common/src/comp/location.rs @@ -8,13 +8,9 @@ pub struct Waypoint { } impl Waypoint { - pub fn new(pos: Vec3) -> Self { - Self { pos } - } + pub fn new(pos: Vec3) -> Self { Self { pos } } - pub fn get_pos(&self) -> Vec3 { - self.pos - } + pub fn get_pos(&self) -> Vec3 { self.pos } } impl Component for Waypoint { @@ -25,9 +21,7 @@ impl Component for Waypoint { pub struct WaypointArea(f32); impl WaypointArea { - pub fn radius(&self) -> f32 { - self.0 - } + pub fn radius(&self) -> f32 { self.0 } } impl Component for WaypointArea { @@ -35,7 +29,5 @@ impl Component for WaypointArea { } impl Default for WaypointArea { - fn default() -> Self { - Self(5.0) - } + fn default() -> Self { Self(5.0) } } diff --git a/common/src/comp/stats.rs b/common/src/comp/stats.rs index 67d8f335d9..aaa768fee3 100644 --- a/common/src/comp/stats.rs +++ b/common/src/comp/stats.rs @@ -1,5 +1,8 @@ -use crate::comp::{body::humanoid::Race, Body}; -use crate::{comp, sync::Uid}; +use crate::{ + comp, + comp::{body::humanoid::Race, Body}, + sync::Uid, +}; use specs::{Component, FlaggedStorage}; use specs_idvs::IDVStorage; @@ -47,23 +50,16 @@ pub struct Equipment { } impl Health { - pub fn current(&self) -> u32 { - self.current - } + pub fn current(&self) -> u32 { self.current } - pub fn maximum(&self) -> u32 { - self.maximum - } + pub fn maximum(&self) -> u32 { self.maximum } pub fn set_to(&mut self, amount: u32, cause: HealthSource) { let amount = amount.min(self.maximum); - self.last_change = ( - 0.0, - HealthChange { - amount: amount as i32 - self.current as i32, - cause, - }, - ); + self.last_change = (0.0, HealthChange { + amount: amount as i32 - self.current as i32, + cause, + }); self.current = amount; } @@ -83,34 +79,23 @@ pub enum StatChangeError { Underflow, Overflow, } -use std::error::Error; -use std::fmt; +use std::{error::Error, fmt}; impl fmt::Display for StatChangeError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "{}", - match self { - Self::Underflow => "insufficient stat quantity", - Self::Overflow => "stat quantity would overflow", - } - ) + write!(f, "{}", match self { + Self::Underflow => "insufficient stat quantity", + Self::Overflow => "stat quantity would overflow", + }) } } impl Error for StatChangeError {} impl Exp { - pub fn current(&self) -> u32 { - self.current - } + pub fn current(&self) -> u32 { self.current } - pub fn maximum(&self) -> u32 { - self.maximum - } + pub fn maximum(&self) -> u32 { self.maximum } - pub fn set_current(&mut self, current: u32) { - self.current = current; - } + pub fn set_current(&mut self, current: u32) { self.current = current; } // TODO: Uncomment when needed // pub fn set_maximum(&mut self, maximum: u32) { @@ -127,17 +112,11 @@ impl Exp { } impl Level { - pub fn set_level(&mut self, level: u32) { - self.amount = level; - } + pub fn set_level(&mut self, level: u32) { self.amount = level; } - pub fn level(&self) -> u32 { - self.amount - } + pub fn level(&self) -> u32 { self.amount } - pub fn change_by(&mut self, level: u32) { - self.amount += level; - } + pub fn change_by(&mut self, level: u32) { self.amount += level; } } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -154,9 +133,8 @@ pub struct Stats { } impl Stats { - pub fn should_die(&self) -> bool { - self.health.current == 0 - } + pub fn should_die(&self) -> bool { self.health.current == 0 } + pub fn revive(&mut self) { self.health .set_to(self.health.maximum(), HealthSource::Revive); @@ -164,9 +142,7 @@ impl Stats { } // TODO: Delete this once stat points will be a thing - pub fn update_max_hp(&mut self) { - self.health.set_maximum(27 + 15 * self.level.amount); - } + pub fn update_max_hp(&mut self) { self.health.set_maximum(27 + 15 * self.level.amount); } } impl Stats { @@ -192,13 +168,10 @@ impl Stats { health: Health { current: 0, maximum: 0, - last_change: ( - 0.0, - HealthChange { - amount: 0, - cause: HealthSource::Revive, - }, - ), + last_change: (0.0, HealthChange { + amount: 0, + cause: HealthSource::Revive, + }), }, level: Level { amount: 1 }, exp: Exp { diff --git a/common/src/event.rs b/common/src/event.rs index ccf1786736..919ca04c45 100644 --- a/common/src/event.rs +++ b/common/src/event.rs @@ -12,13 +12,9 @@ pub struct SfxEventItem { } impl SfxEventItem { - pub fn new(sfx: SfxEvent, pos: Option>) -> Self { - Self { sfx, pos } - } + pub fn new(sfx: SfxEvent, pos: Option>) -> Self { Self { sfx, pos } } - pub fn at_player_position(sfx: SfxEvent) -> Self { - Self { sfx, pos: None } - } + pub fn at_player_position(sfx: SfxEvent) -> Self { Self { sfx, pos: None } } } #[derive(Copy, Clone, Debug, PartialEq, Deserialize, Hash, Eq)] @@ -131,9 +127,7 @@ impl EventBus { } } - pub fn emit(&self, event: E) { - self.queue.lock().push_front(event); - } + pub fn emit(&self, event: E) { self.queue.lock().push_front(event); } pub fn recv_all(&self) -> impl ExactSizeIterator { std::mem::replace(self.queue.lock().deref_mut(), VecDeque::new()).into_iter() @@ -146,13 +140,9 @@ pub struct Emitter<'a, E> { } impl<'a, E> Emitter<'a, E> { - pub fn emit(&mut self, event: E) { - self.events.push_front(event); - } + pub fn emit(&mut self, event: E) { self.events.push_front(event); } } impl<'a, E> Drop for Emitter<'a, E> { - fn drop(&mut self) { - self.bus.queue.lock().append(&mut self.events); - } + fn drop(&mut self) { self.bus.queue.lock().append(&mut self.events); } } diff --git a/common/src/figure/cell.rs b/common/src/figure/cell.rs index 130c92bf27..a6ada431a6 100644 --- a/common/src/figure/cell.rs +++ b/common/src/figure/cell.rs @@ -9,9 +9,7 @@ pub enum Cell { } impl Cell { - pub fn new(rgb: Rgb) -> Self { - Cell::Filled(rgb.into_array()) - } + pub fn new(rgb: Rgb) -> Self { Cell::Filled(rgb.into_array()) } pub fn get_color(&self) -> Option> { match self { @@ -22,9 +20,7 @@ impl Cell { } impl Vox for Cell { - fn empty() -> Self { - Cell::Empty - } + fn empty() -> Self { Cell::Empty } fn is_empty(&self) -> bool { match self { diff --git a/common/src/figure/mat_cell.rs b/common/src/figure/mat_cell.rs index 0154054f8c..1a51b1da74 100644 --- a/common/src/figure/mat_cell.rs +++ b/common/src/figure/mat_cell.rs @@ -10,9 +10,9 @@ pub enum Material { EyeDark, EyeLight, EyeWhite, - //HairLight, - //HairDark, - //Clothing, + /*HairLight, + *HairDark, + *Clothing, */ } #[derive(Copy, Clone, Debug, PartialEq, Eq)] @@ -23,9 +23,7 @@ pub enum MatCell { } impl Vox for MatCell { - fn empty() -> Self { - MatCell::None - } + fn empty() -> Self { MatCell::None } fn is_empty(&self) -> bool { match self { diff --git a/common/src/figure/mod.rs b/common/src/figure/mod.rs index 099311fbd7..4a3e6aa787 100644 --- a/common/src/figure/mod.rs +++ b/common/src/figure/mod.rs @@ -2,8 +2,7 @@ pub mod cell; pub mod mat_cell; pub use mat_cell::Material; -use self::cell::Cell; -use self::mat_cell::MatCell; +use self::{cell::Cell, mat_cell::MatCell}; use crate::{ vol::{IntoFullPosIterator, IntoFullVolIterator, ReadVol, SizedVol, Vox, WriteVol}, volumes::dyna::Dyna, @@ -60,6 +59,7 @@ impl Segment { self } + /// Transform cell colors pub fn map_rgb(self, transform: impl Fn(Rgb) -> Rgb) -> Self { self.map(|cell| cell.get_color().map(|rgb| Cell::new(transform(rgb)))) @@ -71,19 +71,20 @@ impl Segment { pub struct DynaUnionizer(Vec<(Dyna, Vec3)>); impl DynaUnionizer { - pub fn new() -> Self { - DynaUnionizer(Vec::new()) - } + pub fn new() -> Self { DynaUnionizer(Vec::new()) } + pub fn add(mut self, dyna: Dyna, offset: Vec3) -> Self { self.0.push((dyna, offset)); self } + pub fn maybe_add(self, maybe: Option<(Dyna, Vec3)>) -> Self { match maybe { Some((dyna, offset)) => self.add(dyna, offset), None => self, } } + pub fn unify(self) -> (Dyna, Vec3) { if self.0.is_empty() { return (Dyna::filled(Vec3::zero(), V::empty(), ()), Vec3::zero()); @@ -129,6 +130,7 @@ impl MatSegment { } vol } + /// Transform cells pub fn map(mut self, transform: impl Fn(MatCell) -> Option) -> Self { for pos in self.full_pos_iter() { @@ -139,6 +141,7 @@ impl MatSegment { self } + /// Transform cell colors pub fn map_rgb(self, transform: impl Fn(Rgb) -> Rgb) -> Self { self.map(|cell| match cell { @@ -179,7 +182,7 @@ impl From<&DotVoxData> for MatSegment { .copied() .unwrap_or_else(|| Rgb::broadcast(0)); MatCell::Normal(color) - } + }, }; vol.set( diff --git a/common/src/lib.rs b/common/src/lib.rs index e9960f6567..0595cc384d 100644 --- a/common/src/lib.rs +++ b/common/src/lib.rs @@ -2,10 +2,8 @@ #![type_length_limit = "1664759"] #![feature(trait_alias, arbitrary_enum_discriminant, label_break_value)] -#[macro_use] -extern crate serde_derive; -#[macro_use] -extern crate log; +#[macro_use] extern crate serde_derive; +#[macro_use] extern crate log; pub mod assets; pub mod astar; @@ -28,11 +26,12 @@ pub mod util; pub mod vol; pub mod volumes; -/// The networking module containing high-level wrappers of `TcpListener` and `TcpStream` (`PostOffice` and `PostBox` respectively) and data types used by both the server and client. -/// # Examples +/// The networking module containing high-level wrappers of `TcpListener` and +/// `TcpStream` (`PostOffice` and `PostBox` respectively) and data types used by +/// both the server and client. # Examples /// ``` /// use std::net::SocketAddr; -/// use veloren_common::net::{PostOffice, PostBox}; +/// use veloren_common::net::{PostBox, PostOffice}; /// /// let listen_addr = SocketAddr::from(([0, 0, 0, 0], 12345u16)); /// let conn_addr = SocketAddr::from(([127, 0, 0, 1], 12345u16)); diff --git a/common/src/msg/ecs_packet.rs b/common/src/msg/ecs_packet.rs index 6e1a2a65a7..1a8b10df2a 100644 --- a/common/src/msg/ecs_packet.rs +++ b/common/src/msg/ecs_packet.rs @@ -45,6 +45,7 @@ sum_type! { } impl sync::CompPacket for EcsCompPacket { type Phantom = EcsCompPhantom; + fn apply_insert(self, entity: specs::Entity, world: &specs::World) { match self { EcsCompPacket::Body(comp) => sync::handle_insert(comp, entity, world), @@ -62,6 +63,7 @@ impl sync::CompPacket for EcsCompPacket { EcsCompPacket::Sticky(comp) => sync::handle_insert(comp, entity, world), } } + fn apply_modify(self, entity: specs::Entity, world: &specs::World) { match self { EcsCompPacket::Body(comp) => sync::handle_modify(comp, entity, world), @@ -79,6 +81,7 @@ impl sync::CompPacket for EcsCompPacket { EcsCompPacket::Sticky(comp) => sync::handle_modify(comp, entity, world), } } + fn apply_remove(phantom: Self::Phantom, entity: specs::Entity, world: &specs::World) { match phantom { EcsCompPhantom::Body(_) => sync::handle_remove::(entity, world), @@ -88,7 +91,7 @@ impl sync::CompPacket for EcsCompPacket { EcsCompPhantom::Energy(_) => sync::handle_remove::(entity, world), EcsCompPhantom::LightEmitter(_) => { sync::handle_remove::(entity, world) - } + }, EcsCompPhantom::Item(_) => sync::handle_remove::(entity, world), EcsCompPhantom::Scale(_) => sync::handle_remove::(entity, world), EcsCompPhantom::MountState(_) => sync::handle_remove::(entity, world), diff --git a/common/src/msg/mod.rs b/common/src/msg/mod.rs index f0c19f719d..1baee67e15 100644 --- a/common/src/msg/mod.rs +++ b/common/src/msg/mod.rs @@ -3,9 +3,11 @@ pub mod ecs_packet; pub mod server; // Reexports -pub use self::client::ClientMsg; -pub use self::ecs_packet::EcsCompPacket; -pub use self::server::{PlayerListUpdate, RequestStateError, ServerError, ServerInfo, ServerMsg}; +pub use self::{ + client::ClientMsg, + ecs_packet::EcsCompPacket, + server::{PlayerListUpdate, RequestStateError, ServerError, ServerInfo, ServerMsg}, +}; #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] pub enum ClientState { diff --git a/common/src/msg/server.rs b/common/src/msg/server.rs index 6e3f9ad661..a9244b15f6 100644 --- a/common/src/msg/server.rs +++ b/common/src/msg/server.rs @@ -41,8 +41,8 @@ pub enum ServerMsg { }, PlayerListUpdate(PlayerListUpdate), StateAnswer(Result), - /// Trigger cleanup for when the client goes back to the `Registered` state from an ingame - /// state + /// Trigger cleanup for when the client goes back to the `Registered` state + /// from an ingame state ExitIngameCleanup, Ping, Pong, @@ -96,30 +96,35 @@ impl ServerMsg { message, } } + pub fn tell(message: String) -> ServerMsg { ServerMsg::ChatMsg { chat_type: ChatType::Tell, message, } } + pub fn game(message: String) -> ServerMsg { ServerMsg::ChatMsg { chat_type: ChatType::GameUpdate, message, } } + pub fn broadcast(message: String) -> ServerMsg { ServerMsg::ChatMsg { chat_type: ChatType::Broadcast, message, } } + pub fn private(message: String) -> ServerMsg { ServerMsg::ChatMsg { chat_type: ChatType::Private, message, } } + pub fn kill(message: String) -> ServerMsg { ServerMsg::ChatMsg { chat_type: ChatType::Kill, diff --git a/common/src/net/data.rs b/common/src/net/data.rs index 3239321f56..ff16b1fe94 100644 --- a/common/src/net/data.rs +++ b/common/src/net/data.rs @@ -12,7 +12,8 @@ pub enum ClientMsg { VersionInfo {}, } -/// Control message type, used in [PostBox](super::PostBox) and [PostOffice](super::PostOffice) to control threads. +/// Control message type, used in [PostBox](super::PostBox) and +/// [PostOffice](super::PostOffice) to control threads. pub enum ControlMsg { Shutdown, } diff --git a/common/src/net/post2.rs b/common/src/net/post2.rs index e06c8802ff..f117122c19 100644 --- a/common/src/net/post2.rs +++ b/common/src/net/post2.rs @@ -24,21 +24,15 @@ pub enum Error { } impl From for Error { - fn from(err: io::Error) -> Self { - Error::Io(Arc::new(err)) - } + fn from(err: io::Error) -> Self { Error::Io(Arc::new(err)) } } impl From for Error { - fn from(err: bincode::Error) -> Self { - Error::Bincode(Arc::new(err)) - } + fn from(err: bincode::Error) -> Self { Error::Bincode(Arc::new(err)) } } impl From for Error { - fn from(_error: channel::TryRecvError) -> Self { - Error::ChannelFailure - } + fn from(_error: channel::TryRecvError) -> Self { Error::ChannelFailure } } pub trait PostMsg = Serialize + DeserializeOwned + 'static + Send; @@ -63,9 +57,7 @@ impl PostOffice { }) } - pub fn error(&self) -> Option { - self.error.clone() - } + pub fn error(&self) -> Option { self.error.clone() } pub fn new_postboxes(&mut self) -> impl ExactSizeIterator> { let mut new = Vec::new(); @@ -78,11 +70,11 @@ impl PostOffice { match self.listener.accept() { Ok((stream, _sock)) => new.push(PostBox::from_stream(stream).unwrap()), Err(e) if e.kind() == io::ErrorKind::WouldBlock => break, - Err(e) if e.kind() == io::ErrorKind::Interrupted => {} + Err(e) if e.kind() == io::ErrorKind::Interrupted => {}, Err(e) => { self.error = Some(e.into()); break; - } + }, } } @@ -123,13 +115,9 @@ impl PostBox { }) } - pub fn error(&self) -> Option { - self.error.clone() - } + pub fn error(&self) -> Option { self.error.clone() } - pub fn send_message(&mut self, msg: S) { - let _ = self.send_tx.send(msg); - } + pub fn send_message(&mut self, msg: S) { let _ = self.send_tx.send(msg); } pub fn next_message(&mut self) -> Option { if self.error.is_some() { @@ -141,7 +129,7 @@ impl PostBox { Err(e) => { self.error = Some(e); None - } + }, } } @@ -159,11 +147,11 @@ impl PostBox { Err(e) => { self.error = Some(e.into()); break; - } + }, Ok(Err(e)) => { self.error = Some(e); break; - } + }, } } @@ -186,8 +174,8 @@ impl PostBox { Ok(Some(e)) | Err(e) => { recv_tx.send(Err(e.into())).unwrap(); break 'work; - } - Ok(None) => {} + }, + Ok(None) => {}, } // Try getting messages from the send channel. @@ -215,13 +203,13 @@ impl PostBox { .chunks(4096) .map(|chunk| chunk.to_vec()) .for_each(|chunk| outgoing_chunks.push_back(chunk)) - } + }, Err(channel::TryRecvError::Empty) => break, // Worker error Err(e) => { let _ = recv_tx.send(Err(e.into())); break 'work; - } + }, } } @@ -229,21 +217,21 @@ impl PostBox { for _ in 0..1000 { match outgoing_chunks.pop_front() { Some(mut chunk) => match stream.write(&chunk) { - Ok(n) if n == chunk.len() => {} + Ok(n) if n == chunk.len() => {}, Ok(n) => { outgoing_chunks.push_front(chunk.split_off(n)); break; - } + }, Err(e) if e.kind() == io::ErrorKind::WouldBlock => { // Return chunk to the queue to try again later. outgoing_chunks.push_front(chunk); break; - } + }, // Worker error Err(e) => { recv_tx.send(Err(e.into())).unwrap(); break 'work; - } + }, }, None => break, } @@ -256,12 +244,12 @@ impl PostBox { match stream.read(&mut buf) { Ok(n) => incoming_buf.extend_from_slice(&buf[0..n]), Err(e) if e.kind() == io::ErrorKind::WouldBlock => break, - Err(e) if e.kind() == io::ErrorKind::Interrupted => {} + Err(e) if e.kind() == io::ErrorKind::Interrupted => {}, // Worker error Err(e) => { recv_tx.send(Err(e.into())).unwrap(); break 'work; - } + }, } } @@ -294,14 +282,14 @@ impl PostBox { Err(err) => { println!("BINCODE ERROR: {:?}", err); recv_tx.send(Err(err.into())).unwrap() - } + }, } incoming_buf = incoming_buf.split_off(len + 9); } else { break; } - } + }, None => break, } } diff --git a/common/src/npc.rs b/common/src/npc.rs index eb578fe649..be378c9bc5 100644 --- a/common/src/npc.rs +++ b/common/src/npc.rs @@ -1,8 +1,7 @@ use crate::{assets, comp::AllBodies}; use lazy_static::lazy_static; use rand::seq::SliceRandom; -use std::str::FromStr; -use std::sync::Arc; +use std::{str::FromStr, sync::Arc}; #[derive(Clone, Copy, PartialEq)] pub enum NpcKind { @@ -28,12 +27,12 @@ pub const ALL_NPCS: [NpcKind; 6] = [ /// NOTE: Deliberately don't (yet?) implement serialize. #[derive(Clone, Debug, Deserialize)] pub struct BodyNames { - /// The keyword used to refer to this body type (e.g. via the command console). Should be - /// unique per body type. + /// The keyword used to refer to this body type (e.g. via the command + /// console). Should be unique per body type. pub keyword: String, - /// A list of canonical names for NPCs with this body types (currently used when spawning this - /// kind of NPC from the console). Going forward, these names will likely be split up by - /// species. + /// A list of canonical names for NPCs with this body types (currently used + /// when spawning this kind of NPC from the console). Going forward, + /// these names will likely be split up by species. pub names: Vec, } diff --git a/common/src/path.rs b/common/src/path.rs index e4ea0b52c7..1d21b51819 100644 --- a/common/src/path.rs +++ b/common/src/path.rs @@ -31,17 +31,11 @@ impl FromIterator for Path { } impl Path { - pub fn len(&self) -> usize { - self.nodes.len() - } + pub fn len(&self) -> usize { self.nodes.len() } - pub fn start(&self) -> Option<&T> { - self.nodes.first() - } + pub fn start(&self) -> Option<&T> { self.nodes.first() } - pub fn end(&self) -> Option<&T> { - self.nodes.last() - } + pub fn end(&self) -> Option<&T> { self.nodes.last() } } // Route: A path that can be progressed along @@ -53,23 +47,15 @@ pub struct Route { } impl From>> for Route { - fn from(path: Path>) -> Self { - Self { path, next_idx: 0 } - } + fn from(path: Path>) -> Self { Self { path, next_idx: 0 } } } impl Route { - pub fn path(&self) -> &Path> { - &self.path - } + pub fn path(&self) -> &Path> { &self.path } - pub fn next(&self) -> Option> { - self.path.nodes.get(self.next_idx).copied() - } + pub fn next(&self) -> Option> { self.path.nodes.get(self.next_idx).copied() } - pub fn is_finished(&self) -> bool { - self.next().is_none() - } + pub fn is_finished(&self) -> bool { self.next().is_none() } pub fn traverse(&mut self, vol: &V, pos: Vec3) -> Option> where @@ -89,7 +75,8 @@ impl Route { } } -/// A self-contained system that attempts to chase a moving target, only performing pathfinding if necessary +/// A self-contained system that attempts to chase a moving target, only +/// performing pathfinding if necessary #[derive(Default, Clone, Debug)] pub struct Chaser { last_search_tgt: Option>, @@ -258,15 +245,15 @@ where PathResult::Path(path) => { *astar = None; path - } + }, PathResult::None(path) => { *astar = None; path - } + }, PathResult::Exhausted(path) => { *astar = None; path - } + }, PathResult::Pending => Path::default(), } } diff --git a/common/src/ray.rs b/common/src/ray.rs index a236a07f9d..86b0e51a18 100644 --- a/common/src/ray.rs +++ b/common/src/ray.rs @@ -27,9 +27,7 @@ impl<'a, V: ReadVol, F: RayUntil, G: RayForEach> Ray<'a, V, F, G> { } } - pub fn until(self, f: F) -> Ray<'a, V, F, G> { - Ray { until: f, ..self } - } + pub fn until(self, f: F) -> Ray<'a, V, F, G> { Ray { until: f, ..self } } pub fn for_each(self, f: H) -> Ray<'a, V, F, H> { Ray { @@ -79,7 +77,7 @@ impl<'a, V: ReadVol, F: RayUntil, G: RayForEach> Ray<'a, V, F, G> { match self.vol.get(ipos).map(|vox| (vox, (self.until)(vox))) { Ok((vox, true)) => return (dist, Ok(Some(vox))), Err(err) if !self.ignore_error => return (dist, Err(err)), - _ => {} + _ => {}, } let deltas = diff --git a/common/src/region.rs b/common/src/region.rs index 295c86dc44..4b814b54ea 100644 --- a/common/src/region.rs +++ b/common/src/region.rs @@ -29,28 +29,27 @@ impl Region { events: Vec::new(), } } + /// Checks if the region contains no entities and no events - fn removable(&self) -> bool { - self.bitset.is_empty() && self.events.is_empty() - } + fn removable(&self) -> bool { self.bitset.is_empty() && self.events.is_empty() } + fn add(&mut self, id: u32, from: Option>) { self.bitset.add(id); self.events.push(Event::Entered(id, from)); } + fn remove(&mut self, id: u32, to: Option>) { self.bitset.remove(id); self.events.push(Event::Left(id, to)); } - pub fn events(&self) -> &[Event] { - &self.events - } - pub fn entities(&self) -> &BitSet { - &self.bitset - } + + pub fn events(&self) -> &[Event] { &self.events } + + pub fn entities(&self) -> &BitSet { &self.bitset } } -/// How far can an entity roam outside its region before it is switched over to the neighboring one -/// In units of blocks (i.e. world pos) +/// How far can an entity roam outside its region before it is switched over to +/// the neighboring one In units of blocks (i.e. world pos) /// Used to prevent rapid switching of entities between regions pub const TETHER_LENGTH: u32 = 16; /// Bitshift between region and world pos, i.e. log2(REGION_SIZE) @@ -76,7 +75,8 @@ const NEIGHBOR_OFFSETS: [Vec2; 8] = [ pub struct RegionMap { // Tree? // Sorted Vec? (binary search lookup) - // Sort into multiple vecs (say 32) using lower bits of morton code, then binary search via upper bits? <-- sounds very promising to me (might not be super good though?) + // Sort into multiple vecs (say 32) using lower bits of morton code, then binary search via + // upper bits? <-- sounds very promising to me (might not be super good though?) regions: IndexMap, Region, DefaultHashBuilder>, // If an entity isn't here it needs to be added to a region tracked_entities: BitSet, @@ -99,6 +99,7 @@ impl RegionMap { tick: 0, } } + // TODO maintain within a system? // TODO special case large entities pub fn tick(&mut self, pos: ReadStorage, vel: ReadStorage, entities: Entities) { @@ -154,13 +155,14 @@ impl RegionMap { // Switch self.entities_to_move.push((i, id, pos)); } - } - // Remove any non-existant entities (or just ones that lost their position component) - // TODO: distribute this between ticks + }, + // Remove any non-existant entities (or just ones that lost their position + // component) TODO: distribute this between ticks None => { - // TODO: shouldn't there be a way to extract the bitset of entities with positions directly from specs? + // TODO: shouldn't there be a way to extract the bitset of entities with + // positions directly from specs? self.entities_to_remove.push((i, id)); - } + }, } } @@ -173,7 +175,8 @@ impl RegionMap { } // Mutate - // Note entity moving is outside the whole loop so that the same entity is not checked twice (this may be fine though...) + // Note entity moving is outside the whole loop so that the same entity is not + // checked twice (this may be fine though...) while let Some((i, id, pos)) = self.entities_to_move.pop() { let (prev_key, region) = self.regions.get_index_mut(i).map(|(k, v)| (*k, v)).unwrap(); region.remove(id, Some(Self::pos_key(pos))); @@ -191,11 +194,13 @@ impl RegionMap { for key in regions_to_remove.into_iter() { // Check that the region is still removable if self.regions.get(&key).unwrap().removable() { - // Note we have to use key's here since the index can change when others are removed + // Note we have to use key's here since the index can change when others are + // removed self.remove(key); } } } + fn add_entity(&mut self, id: u32, pos: Vec3, from: Option>) { let key = Self::pos_key(pos); if let Some(region) = self.regions.get_mut(&key) { @@ -210,13 +215,13 @@ impl RegionMap { .unwrap() .add(id, None); } - fn pos_key>>(pos: P) -> Vec2 { - pos.into().map(|e| e >> REGION_LOG2) - } - pub fn key_pos(key: Vec2) -> Vec2 { - key.map(|e| e << REGION_LOG2) - } - /// Finds the region where a given entity is located using a given position to speed up the search + + fn pos_key>>(pos: P) -> Vec2 { pos.into().map(|e| e >> REGION_LOG2) } + + pub fn key_pos(key: Vec2) -> Vec2 { key.map(|e| e << REGION_LOG2) } + + /// Finds the region where a given entity is located using a given position + /// to speed up the search pub fn find_region(&self, entity: specs::Entity, pos: Vec3) -> Option> { let id = entity.id(); // Compute key for most likely region @@ -257,12 +262,15 @@ impl RegionMap { None } + fn key_index(&self, key: Vec2) -> Option { self.regions.get_full(&key).map(|(i, _, _)| i) } + fn index_key(&self, index: usize) -> Option> { self.regions.get_index(index).map(|(k, _)| k).copied() } + /// Adds a new region /// Returns the index of the region in the index map fn insert(&mut self, key: Vec2) -> usize { @@ -289,15 +297,18 @@ impl RegionMap { index } + /// Remove a region using its key fn remove(&mut self, key: Vec2) { if let Some(index) = self.key_index(key) { self.remove_index(index); } } + /// Add a region using its key fn remove_index(&mut self, index: usize) { - // Remap neighbor indices for neighbors of the region that will be moved from the end of the index map + // Remap neighbor indices for neighbors of the region that will be moved from + // the end of the index map if index != self.regions.len() - 1 { let moved_neighbors = self .regions @@ -335,10 +346,10 @@ impl RegionMap { } } } + // Returns a region given a key - pub fn get(&self, key: Vec2) -> Option<&Region> { - self.regions.get(&key) - } + pub fn get(&self, key: Vec2) -> Option<&Region> { self.regions.get(&key) } + // Returns an iterator of (Position, Region) pub fn iter(&self) -> impl Iterator, &Region)> { self.regions.iter().map(|(key, r)| (*key, r)) @@ -350,7 +361,8 @@ pub fn region_in_vd(key: Vec2, pos: Vec3, vd: f32) -> bool { let vd_extended = vd + TETHER_LENGTH as f32 * 2.0f32.sqrt(); let min_region_pos = RegionMap::key_pos(key).map(|e| e as f32); - // Should be diff to closest point on the square (which can be in the middle of an edge) + // Should be diff to closest point on the square (which can be in the middle of + // an edge) let diff = (min_region_pos - Vec2::from(pos)).map(|e| { if e < 0.0 { (e + REGION_SIZE as f32).min(0.0) diff --git a/common/src/state.rs b/common/src/state.rs index ba190df7ed..c657785b25 100644 --- a/common/src/state.rs +++ b/common/src/state.rs @@ -34,10 +34,11 @@ pub struct Time(pub f64); #[derive(Default)] pub struct DeltaTime(pub f32); -/// 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. +/// 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 = 26.0; @@ -47,9 +48,7 @@ pub struct BlockChange { } impl BlockChange { - pub fn set(&mut self, pos: Vec3, block: Block) { - self.blocks.insert(pos, block); - } + 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) { @@ -60,9 +59,7 @@ impl BlockChange { } } - pub fn clear(&mut self) { - self.blocks.clear(); - } + pub fn clear(&mut self) { self.blocks.clear(); } } #[derive(Default)] @@ -81,8 +78,9 @@ impl TerrainChanges { } } -/// 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. +/// 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 @@ -101,7 +99,8 @@ impl Default for State { impl State { /// 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) + // TODO: Split up registering into server and client (e.g. move + // EventBus to the server) fn setup_ecs_world() -> specs::World { let mut ecs = specs::World::new(); // Uids for sync @@ -197,56 +196,43 @@ impl State { } /// Get a reference to the internal ECS world. - pub fn ecs(&self) -> &specs::World { - &self.ecs - } + 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 - } + 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 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 - } + /// 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 time. /// /// Note that this does not correspond to the time of day. - pub fn get_time(&self) -> f64 { - self.ecs.read_resource::