diff --git a/Cargo.lock b/Cargo.lock index 9b0b4535bf..c5e2dd44b2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1125,19 +1125,6 @@ version = "1.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bb1f6b1ce1c140482ea30ddd3335fc0024ac7ee112895426e0a629a6c20adfe3" -[[package]] -name = "env_logger" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aafcde04e90a5226a6443b7aabdb016ba2f8307c847d524724bd9b346dd1a2d3" -dependencies = [ - "atty", - "humantime", - "log", - "regex", - "termcolor", -] - [[package]] name = "error-chain" version = "0.12.2" @@ -1954,15 +1941,6 @@ version = "1.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cd179ae861f0c2e53da70d892f5f3029f9594be0c41dc5269cd371691b1dc2f9" -[[package]] -name = "humantime" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df004cfca50ef23c36850aaaa59ad52cc70d0e90243c3c7737a4dd32dc7a3c4f" -dependencies = [ - "quick-error", -] - [[package]] name = "hyper" version = "0.12.35" @@ -3034,17 +3012,6 @@ version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "237a5ed80e274dbc66f86bd59c1e25edc039660be53194b5fe0a482e0f2612ea" -[[package]] -name = "pretty_env_logger" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "717ee476b1690853d222af4634056d830b5197ffd747726a9a1eee6da9f49074" -dependencies = [ - "chrono", - "env_logger", - "log", -] - [[package]] name = "proc-macro-hack" version = "0.5.16" @@ -4000,15 +3967,6 @@ dependencies = [ "unicode-xid 0.2.0", ] -[[package]] -name = "termcolor" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb6bfa289a4d7c5766392812c0a1f4c1ba45afa1ad47803c11e1f407d846d75f" -dependencies = [ - "winapi-util", -] - [[package]] name = "textwrap" version = "0.11.0" @@ -4478,8 +4436,8 @@ dependencies = [ name = "veloren-chat-cli" version = "0.6.0" dependencies = [ - "log", - "pretty_env_logger", + "tracing", + "tracing-subscriber", "veloren-client", "veloren-common", ] @@ -4492,9 +4450,9 @@ dependencies = [ "byteorder 1.3.4", "hashbrown", "image", - "log", "num_cpus", "specs", + "tracing", "uvth 3.1.1", "vek", "veloren-common", @@ -4514,7 +4472,6 @@ dependencies = [ "image", "indexmap", "lazy_static", - "log", "lz4-compress", "mio", "notify", @@ -4528,6 +4485,7 @@ dependencies = [ "specs", "specs-idvs", "sum_type", + "tracing", "vek", ] @@ -4544,7 +4502,6 @@ dependencies = [ "hashbrown", "lazy_static", "libsqlite3-sys", - "log", "portpicker", "prometheus", "prometheus-static-metric", @@ -4557,6 +4514,7 @@ dependencies = [ "specs", "specs-idvs", "tiny_http", + "tracing", "uvth 3.1.1", "vek", "veloren-common", @@ -4567,8 +4525,8 @@ dependencies = [ name = "veloren-server-cli" version = "0.6.0" dependencies = [ - "log", - "pretty_env_logger", + "tracing", + "tracing-subscriber", "veloren-common", "veloren-server", ] @@ -4652,13 +4610,11 @@ dependencies = [ "image", "itertools 0.8.2", "lazy_static", - "log", "minifb", "noise", "num 0.2.1", "ordered-float", "packed_simd", - "pretty_env_logger", "rand 0.7.3", "rand_chacha 0.2.2", "rayon", @@ -4666,6 +4622,8 @@ dependencies = [ "roots", "serde", "serde_derive", + "tracing", + "tracing-subscriber", "vek", "veloren-common", ] diff --git a/chat-cli/Cargo.toml b/chat-cli/Cargo.toml index 26496086dd..253fee4334 100644 --- a/chat-cli/Cargo.toml +++ b/chat-cli/Cargo.toml @@ -8,5 +8,5 @@ edition = "2018" client = { package = "veloren-client", path = "../client" } common = { package = "veloren-common", path = "../common" } -log = "0.4.8" -pretty_env_logger = "0.3.1" +tracing = { version = "0.1", default-features = false , features = ["attributes"] } +tracing-subscriber = { version = "0.2.3", default-features = false, features = ["fmt", "chrono", "ansi", "smallvec"] } diff --git a/chat-cli/src/main.rs b/chat-cli/src/main.rs index e982be403e..c7e1aabacf 100644 --- a/chat-cli/src/main.rs +++ b/chat-cli/src/main.rs @@ -3,8 +3,8 @@ use client::{Client, Event}; use common::{clock::Clock, comp}; -use log::{error, info}; use std::{io, net::ToSocketAddrs, sync::mpsc, thread, time::Duration}; +use tracing::{error, info}; const TPS: u64 = 10; // Low value is okay, just reading messages. @@ -20,7 +20,7 @@ fn read_input() -> String { fn main() { // Initialize logging. - pretty_env_logger::init(); + tracing_subscriber::fmt::init(); info!("Starting chat-cli..."); diff --git a/client/Cargo.toml b/client/Cargo.toml index e32e0a3771..8960b700ea 100644 --- a/client/Cargo.toml +++ b/client/Cargo.toml @@ -11,7 +11,7 @@ byteorder = "1.3.2" uvth = "3.1.1" image = { version = "0.22.3", default-features = false, features = ["png"] } num_cpus = "1.10.1" -log = "0.4.8" +tracing = { version = "0.1", default-features = false , features = ["attributes"] } specs = "0.15.1" vek = { version = "0.11.0", features = ["serde"] } hashbrown = { version = "0.6", features = ["rayon", "serde", "nightly"] } diff --git a/client/src/lib.rs b/client/src/lib.rs index 5e0a84fc0d..6f21487b4e 100644 --- a/client/src/lib.rs +++ b/client/src/lib.rs @@ -36,12 +36,12 @@ use common::{ }; use hashbrown::HashMap; use image::DynamicImage; -use log::{error, warn}; use std::{ net::SocketAddr, sync::Arc, time::{Duration, Instant}, }; +use tracing::{debug, error, warn}; use uvth::{ThreadPool, ThreadPoolBuilder}; use vek::*; @@ -117,7 +117,7 @@ impl Client { } => { // TODO: Display that versions don't match in Voxygen if server_info.git_hash != common::util::GIT_HASH.to_string() { - log::warn!( + warn!( "Server is running {}[{}], you are running {}[{}], versions might be \ incompatible!", server_info.git_hash, @@ -127,7 +127,7 @@ impl Client { ); } - log::debug!("Auth Server: {:?}", server_info.auth_provider); + debug!("Auth Server: {:?}", server_info.auth_provider); // Initialize `State` let mut state = State::default(); @@ -142,7 +142,7 @@ impl Client { assert_eq!(world_map.len(), (map_size.x * map_size.y) as usize); let mut world_map_raw = vec![0u8; 4 * world_map.len()/*map_size.x * map_size.y*/]; LittleEndian::write_u32_into(&world_map, &mut world_map_raw); - log::debug!("Preparing image..."); + debug!("Preparing image..."); let world_map = Arc::new( image::DynamicImage::ImageRgba8({ // Should not fail if the dimensions are correct. @@ -154,7 +154,7 @@ impl Client { // positive x axis to positive y axis is counterclockwise around the z axis. .flipv(), ); - log::debug!("Done preparing image..."); + debug!("Done preparing image..."); (state, entity, server_info, (world_map, map_size)) }, @@ -463,7 +463,7 @@ impl Client { pub fn send_chat(&mut self, message: String) { match validate_chat_msg(&message) { Ok(()) => self.postbox.send_message(ClientMsg::ChatMsg { message }), - Err(ChatMsgValidationError::TooLong) => log::warn!( + Err(ChatMsgValidationError::TooLong) => warn!( "Attempted to send a message that's too long (Over {} bytes)", MAX_BYTES_CHAT_MSG ), @@ -691,7 +691,7 @@ impl Client { /* // Output debug metrics - if log_enabled!(log::Level::Info) && self.tick % 600 == 0 { + if log_enabled!(Level::Info) && self.tick % 600 == 0 { let metrics = self .state .terrain() diff --git a/common/Cargo.toml b/common/Cargo.toml index 3b733d4354..0962224906 100644 --- a/common/Cargo.toml +++ b/common/Cargo.toml @@ -20,7 +20,7 @@ serde_derive = "1.0" serde_json = "1.0.41" ron = { version = "0.6", default-features = false } bincode = "1.2.0" -log = "0.4.8" +tracing = { version = "0.1", default-features = false , features = ["attributes"] } rand = "0.7" rayon = "^1.3.0" lazy_static = "1.4.0" diff --git a/common/src/assets/mod.rs b/common/src/assets/mod.rs index 05ff190eb7..86c427970f 100644 --- a/common/src/assets/mod.rs +++ b/common/src/assets/mod.rs @@ -5,7 +5,6 @@ use dot_vox::DotVoxData; use hashbrown::HashMap; use image::DynamicImage; use lazy_static::lazy_static; -use log::error; use serde_json::Value; use std::{ any::Any, @@ -15,6 +14,7 @@ use std::{ path::PathBuf, sync::{Arc, RwLock}, }; +use tracing::{debug, error, trace}; /// The error returned by asset loading functions #[derive(Debug, Clone)] diff --git a/common/src/assets/watch.rs b/common/src/assets/watch.rs index 3fd652385e..1745b097d5 100644 --- a/common/src/assets/watch.rs +++ b/common/src/assets/watch.rs @@ -1,6 +1,5 @@ use crossbeam::channel::{select, unbounded, Receiver, Sender}; use lazy_static::lazy_static; -use log::warn; use notify::{Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher as _}; use std::{ collections::HashMap, @@ -11,6 +10,7 @@ use std::{ }, thread, }; +use tracing::{error, warn}; type Handler = Box; diff --git a/common/src/cmd.rs b/common/src/cmd.rs index f54a27997c..4a803c7c5d 100644 --- a/common/src/cmd.rs +++ b/common/src/cmd.rs @@ -1,6 +1,7 @@ use crate::{assets, comp, npc}; use lazy_static::lazy_static; use std::{ops::Deref, path::Path, str::FromStr}; +use tracing::warn; /// Struct representing a command that a user can run from server chat. pub struct ChatCommandData { diff --git a/common/src/comp/inventory/slot.rs b/common/src/comp/inventory/slot.rs index aefdd5c503..8bcf69edff 100644 --- a/common/src/comp/inventory/slot.rs +++ b/common/src/comp/inventory/slot.rs @@ -1,6 +1,6 @@ use crate::{comp, comp::item}; use comp::{Inventory, Loadout}; -use log::warn; +use tracing::warn; #[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)] pub enum Slot { diff --git a/common/src/hierarchical.rs b/common/src/hierarchical.rs index 32dcb3e747..91feaad848 100644 --- a/common/src/hierarchical.rs +++ b/common/src/hierarchical.rs @@ -60,10 +60,12 @@ impl ChunkPath { } } - //let neighbors: Vec> = directions.into_iter().map(|dir| dir + pos).collect(); + //let neighbors: Vec> = directions.into_iter().map(|dir| dir + + // pos).collect(); neighbors.into_iter() } + pub fn worldpath_get_neighbors( &mut self, vol: &VolGrid2d, @@ -95,6 +97,7 @@ impl ChunkPath { .collect(); neighbors.into_iter() } + pub fn is_valid_space( &mut self, vol: &VolGrid2d, @@ -107,13 +110,14 @@ impl ChunkPath { is_within_chunk = chunk_path .iter() .any(|new_pos| new_pos.cmpeq(&vol.pos_key(pos)).iter().all(|e| *e)); - } + }, _ => { //println!("No chunk path"); - } + }, } return is_walkable_position && is_within_chunk; } + pub fn get_worldpath( &mut self, vol: &VolGrid2d, @@ -132,6 +136,4 @@ pub fn chunk_euclidean_distance(start: &Vec2, end: &Vec2) -> f32 { istart.distance(iend) } -pub fn chunk_transition_cost(_start: &Vec2, _end: &Vec2) -> f32 { - 1.0f32 -} +pub fn chunk_transition_cost(_start: &Vec2, _end: &Vec2) -> f32 { 1.0f32 } diff --git a/common/src/lib.rs b/common/src/lib.rs index 99f9020b76..213587d337 100644 --- a/common/src/lib.rs +++ b/common/src/lib.rs @@ -11,7 +11,6 @@ )] #[macro_use] extern crate serde_derive; -#[macro_use] extern crate log; pub mod assets; pub mod astar; diff --git a/common/src/net/post.rs b/common/src/net/post.rs index 2dd7620c05..5912e323e9 100644 --- a/common/src/net/post.rs +++ b/common/src/net/post.rs @@ -1,29 +1,21 @@ -use std::{ - fmt, - thread, - net::{SocketAddr, Shutdown}, - sync::mpsc::TryRecvError, - io::{self, Read, Write}, - collections::VecDeque, - time::Duration, - convert::TryFrom, -}; -use serde; -use mio::{ - net::{TcpListener, TcpStream}, - Events, - Poll, - PollOpt, - Ready, - Token, -}; -use mio_extras::channel::{ - channel, - Receiver, - Sender, -}; use bincode; use middleman::Middleman; +use mio::{ + net::{TcpListener, TcpStream}, + Events, Poll, PollOpt, Ready, Token, +}; +use mio_extras::channel::{channel, Receiver, Sender}; +use serde; +use std::{ + collections::VecDeque, + convert::TryFrom, + fmt, + io::{self, Read, Write}, + net::{Shutdown, SocketAddr}, + sync::mpsc::TryRecvError, + thread, + time::Duration, +}; #[derive(Clone, Debug, PartialEq)] pub enum Error { @@ -34,37 +26,29 @@ pub enum Error { } impl From for Error { - fn from(err: io::Error) -> Self { - Error::Network - } + fn from(err: io::Error) -> Self { Error::Network } } impl From for Error { - fn from(err: TryRecvError) -> Self { - Error::Internal - } + fn from(err: TryRecvError) -> Self { Error::Internal } } impl From for Error { - fn from(err: bincode::ErrorKind) -> Self { - Error::InvalidMsg - } + fn from(err: bincode::ErrorKind) -> Self { Error::InvalidMsg } } impl From> for Error { - fn from(err: mio_extras::channel::SendError) -> Self { - Error::Internal - } + fn from(err: mio_extras::channel::SendError) -> Self { Error::Internal } } pub trait PostSend = 'static + serde::Serialize + Send + middleman::Message; pub trait PostRecv = 'static + serde::de::DeserializeOwned + Send + middleman::Message; -const TCP_TOK: Token = Token(0); -const CTRL_TOK: Token = Token(1); -const POSTBOX_TOK: Token = Token(2); -const SEND_TOK: Token = Token(3); -const RECV_TOK: Token = Token(4); +const TCP_TOK: Token = Token(0); +const CTRL_TOK: Token = Token(1); +const POSTBOX_TOK: Token = Token(2); +const SEND_TOK: Token = Token(3); +const RECV_TOK: Token = Token(4); const MIDDLEMAN_TOK: Token = Token(5); const MAX_MSG_BYTES: usize = 1 << 28; @@ -95,12 +79,8 @@ impl PostOffice { let office_poll = Poll::new()?; office_poll.register(&postbox_rx, POSTBOX_TOK, Ready::readable(), PollOpt::edge())?; - let worker = thread::spawn(move || office_worker( - worker_poll, - tcp_listener, - ctrl_rx, - postbox_tx, - )); + let worker = + thread::spawn(move || office_worker(worker_poll, tcp_listener, ctrl_rx, postbox_tx)); Ok(Self { worker: Some(worker), @@ -111,11 +91,9 @@ impl PostOffice { }) } - pub fn error(&self) -> Option { - self.err.clone() - } + pub fn error(&self) -> Option { self.err.clone() } - pub fn new_connections(&mut self) -> impl ExactSizeIterator> { + pub fn new_connections(&mut self) -> impl ExactSizeIterator> { let mut conns = VecDeque::new(); if self.err.is_some() { @@ -123,10 +101,7 @@ impl PostOffice { } let mut events = Events::with_capacity(64); - if let Err(err) = self.poll.poll( - &mut events, - Some(Duration::new(0, 0)), - ) { + if let Err(err) = self.poll.poll(&mut events, Some(Duration::new(0, 0))) { self.err = Some(err.into()); return conns.into_iter(); } @@ -188,12 +163,10 @@ fn office_worker( }, } }, - TCP_TOK => postbox_tx.send( - match tcp_listener.accept() { - Ok((stream, _)) => PostBox::from_tcpstream(stream), - Err(err) => Err(err.into()), - } - )?, + TCP_TOK => postbox_tx.send(match tcp_listener.accept() { + Ok((stream, _)) => PostBox::from_tcpstream(stream), + Err(err) => Err(err.into()), + })?, tok => panic!("Unexpected event token '{:?}'", tok), } } @@ -211,7 +184,9 @@ pub struct PostBox { impl PostBox { pub fn to_server>(addr: A) -> Result { - Self::from_tcpstream(TcpStream::from_stream(std::net::TcpStream::connect(&addr.into())?)?) + Self::from_tcpstream(TcpStream::from_stream(std::net::TcpStream::connect( + &addr.into(), + )?)?) } fn from_tcpstream(tcp_stream: TcpStream) -> Result { @@ -220,20 +195,21 @@ impl PostBox { let (recv_tx, recv_rx) = channel(); let worker_poll = Poll::new()?; - worker_poll.register(&tcp_stream, TCP_TOK, Ready::readable() | Ready::writable(), PollOpt::edge())?; + worker_poll.register( + &tcp_stream, + TCP_TOK, + Ready::readable() | Ready::writable(), + PollOpt::edge(), + )?; worker_poll.register(&ctrl_rx, CTRL_TOK, Ready::readable(), PollOpt::edge())?; worker_poll.register(&send_rx, SEND_TOK, Ready::readable(), PollOpt::edge())?; let postbox_poll = Poll::new()?; postbox_poll.register(&recv_rx, RECV_TOK, Ready::readable(), PollOpt::edge())?; - let worker = thread::spawn(move || postbox_worker( - worker_poll, - tcp_stream, - ctrl_rx, - send_rx, - recv_tx, - )); + let worker = thread::spawn(move || { + postbox_worker(worker_poll, tcp_stream, ctrl_rx, send_rx, recv_tx) + }); Ok(Self { worker: Some(worker), @@ -245,13 +221,9 @@ impl PostBox { }) } - pub fn error(&self) -> Option { - self.err.clone() - } + pub fn error(&self) -> Option { self.err.clone() } - pub fn send(&mut self, data: S) { - let _ = self.send_tx.send(data); - } + pub fn send(&mut self, data: S) { let _ = self.send_tx.send(data); } // TODO: This method is super messy. pub fn next_message(&mut self) -> Option { @@ -261,10 +233,7 @@ impl PostBox { loop { let mut events = Events::with_capacity(10); - if let Err(err) = self.poll.poll( - &mut events, - Some(Duration::new(0, 0)), - ) { + if let Err(err) = self.poll.poll(&mut events, Some(Duration::new(0, 0))) { self.err = Some(err.into()); return None; } @@ -292,7 +261,7 @@ impl PostBox { } } - pub fn new_messages(&mut self) -> impl ExactSizeIterator { + pub fn new_messages(&mut self) -> impl ExactSizeIterator { let mut msgs = VecDeque::new(); if self.err.is_some() { @@ -300,10 +269,7 @@ impl PostBox { } let mut events = Events::with_capacity(64); - if let Err(err) = self.poll.poll( - &mut events, - Some(Duration::new(0, 0)), - ) { + if let Err(err) = self.poll.poll(&mut events, Some(Duration::new(0, 0))) { self.err = Some(err.into()); return msgs.into_iter(); } @@ -347,7 +313,10 @@ fn postbox_worker( send_rx: Receiver, recv_tx: Sender>, ) -> Result<(), Error> { - fn try_tcp_send(tcp_stream: &mut TcpStream, chunks: &mut VecDeque>) -> Result<(), Error> { + fn try_tcp_send( + tcp_stream: &mut TcpStream, + chunks: &mut VecDeque>, + ) -> Result<(), Error> { loop { let chunk = match chunks.pop_front() { Some(chunk) => chunk, @@ -389,16 +358,15 @@ fn postbox_worker( for event in &events { match event.token() { - CTRL_TOK => - match ctrl_rx.try_recv() { - Ok(CtrlMsg::Shutdown) => { - break 'work; - }, - Err(TryRecvError::Empty) => (), - Err(err) => { - recv_tx.send(Err(err.into()))?; - break 'work; - }, + CTRL_TOK => match ctrl_rx.try_recv() { + Ok(CtrlMsg::Shutdown) => { + break 'work; + }, + Err(TryRecvError::Empty) => (), + Err(err) => { + recv_tx.send(Err(err.into()))?; + break 'work; + }, }, SEND_TOK => loop { match send_rx.try_recv() { @@ -411,11 +379,7 @@ fn postbox_worker( }, }; - let mut bytes = msg_bytes - .len() - .to_le_bytes() - .as_ref() - .to_vec(); + let mut bytes = msg_bytes.len().to_le_bytes().as_ref().to_vec(); bytes.append(&mut msg_bytes); bytes @@ -450,49 +414,52 @@ fn postbox_worker( }, } match &mut recv_state { - RecvState::ReadHead(head) => if head.len() == 8 { - let len = usize::from_le_bytes(<[u8; 8]>::try_from(head.as_slice()).unwrap()); - if len > MAX_MSG_BYTES { - println!("TOO BIG! {:x}", len); - recv_tx.send(Err(Error::InvalidMsg))?; - break 'work; - } else if len == 0 { - recv_state = RecvState::ReadHead(Vec::with_capacity(8)); - break; - } else { - recv_state = RecvState::ReadBody( - len, - Vec::new(), + RecvState::ReadHead(head) => { + if head.len() == 8 { + let len = usize::from_le_bytes( + <[u8; 8]>::try_from(head.as_slice()).unwrap(), ); - } - } else { - let mut b = [0; 1]; - match tcp_stream.read(&mut b) { - Ok(0) => {}, - Ok(_) => head.push(b[0]), - Err(_) => break, + if len > MAX_MSG_BYTES { + println!("TOO BIG! {:x}", len); + recv_tx.send(Err(Error::InvalidMsg))?; + break 'work; + } else if len == 0 { + recv_state = RecvState::ReadHead(Vec::with_capacity(8)); + break; + } else { + recv_state = RecvState::ReadBody(len, Vec::new()); + } + } else { + let mut b = [0; 1]; + match tcp_stream.read(&mut b) { + Ok(0) => {}, + Ok(_) => head.push(b[0]), + Err(_) => break, + } } }, - RecvState::ReadBody(len, body) => if body.len() == *len { - match bincode::deserialize(&body) { - Ok(msg) => { - recv_tx.send(Ok(msg))?; - recv_state = RecvState::ReadHead(Vec::with_capacity(8)); - }, - Err(err) => { - recv_tx.send(Err((*err).into()))?; - break 'work; - }, - } - } else { - let left = *len - body.len(); - let mut buf = vec![0; left]; - match tcp_stream.read(&mut buf) { - Ok(_) => body.append(&mut buf), - Err(err) => { - recv_tx.send(Err(err.into()))?; - break 'work; - }, + RecvState::ReadBody(len, body) => { + if body.len() == *len { + match bincode::deserialize(&body) { + Ok(msg) => { + recv_tx.send(Ok(msg))?; + recv_state = RecvState::ReadHead(Vec::with_capacity(8)); + }, + Err(err) => { + recv_tx.send(Err((*err).into()))?; + break 'work; + }, + } + } else { + let left = *len - body.len(); + let mut buf = vec![0; left]; + match tcp_stream.read(&mut buf) { + Ok(_) => body.append(&mut buf), + Err(err) => { + recv_tx.send(Err(err.into()))?; + break 'work; + }, + } } }, } diff --git a/common/src/net/post2.rs b/common/src/net/post2.rs index 6429eedb24..e4ba5b31cb 100644 --- a/common/src/net/post2.rs +++ b/common/src/net/post2.rs @@ -1,5 +1,4 @@ use crossbeam::channel; -use log::warn; use serde::{de::DeserializeOwned, Serialize}; use std::{ collections::VecDeque, @@ -14,6 +13,7 @@ use std::{ thread, time::Duration, }; +use tracing::warn; #[derive(Clone, Debug)] pub enum Error { diff --git a/common/src/sync/packet.rs b/common/src/sync/packet.rs index 37e47ae30b..b0e764792d 100644 --- a/common/src/sync/packet.rs +++ b/common/src/sync/packet.rs @@ -1,5 +1,4 @@ use super::{track::UpdateTracker, uid::Uid}; -use log::error; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use specs::{Component, Entity, Join, ReadStorage, World, WorldExt}; use std::{ @@ -7,6 +6,7 @@ use std::{ fmt::Debug, marker::PhantomData, }; +use tracing::error; /// Implemented by type that carries component data for insertion and /// modification The assocatied `Phantom` type only carries information about diff --git a/common/src/sync/sync_ext.rs b/common/src/sync/sync_ext.rs index a8224b62a5..2dd6eb5686 100644 --- a/common/src/sync/sync_ext.rs +++ b/common/src/sync/sync_ext.rs @@ -5,12 +5,12 @@ use super::{ track::UpdateTracker, uid::{Uid, UidAllocator}, }; -use log::error; use specs::{ saveload::{MarkedBuilder, MarkerAllocator}, world::Builder, WorldExt, }; +use tracing::error; pub trait WorldSyncExt { fn register_sync_marker(&mut self); diff --git a/common/src/util/dir.rs b/common/src/util/dir.rs index 763c527fdd..5ce7636b12 100644 --- a/common/src/util/dir.rs +++ b/common/src/util/dir.rs @@ -1,3 +1,4 @@ +use tracing::warn; use vek::*; /// Type representing a direction using Vec3 that is normalized and NaN free diff --git a/server-cli/Cargo.toml b/server-cli/Cargo.toml index a7e64705d5..708bc2558d 100644 --- a/server-cli/Cargo.toml +++ b/server-cli/Cargo.toml @@ -12,5 +12,5 @@ default = ["worldgen"] server = { package = "veloren-server", path = "../server", default-features = false } common = { package = "veloren-common", path = "../common" } -log = "0.4.8" -pretty_env_logger = "0.3.1" +tracing = { version = "0.1", default-features = false , features = ["attributes"] } +tracing-subscriber = { version = "0.2.3", default-features = false, features = ["fmt", "chrono", "ansi", "smallvec"] } diff --git a/server-cli/src/main.rs b/server-cli/src/main.rs index 5b5c9af5f9..d10437f5fa 100644 --- a/server-cli/src/main.rs +++ b/server-cli/src/main.rs @@ -2,9 +2,9 @@ #![allow(clippy::option_map_unit_fn)] use common::clock::Clock; -use log::info; use server::{Event, Input, Server, ServerSettings}; use std::time::Duration; +use tracing::info; const TPS: u64 = 30; @@ -14,7 +14,8 @@ fn main() { if let Err(_) = std::env::var("RUST_LOG") { std::env::set_var("RUST_LOG", "info"); } - pretty_env_logger::init(); + + tracing_subscriber::fmt::init(); info!("Starting server..."); diff --git a/server/Cargo.toml b/server/Cargo.toml index 12df9946b4..94053ed6d0 100644 --- a/server/Cargo.toml +++ b/server/Cargo.toml @@ -14,7 +14,7 @@ world = { package = "veloren-world", path = "../world" } specs-idvs = { git = "https://gitlab.com/veloren/specs-idvs.git" } -log = "0.4.8" +tracing = { version = "0.1", default-features = false , features = ["attributes"] } specs = { version = "0.15.1", features = ["shred-derive"] } vek = "0.11.0" uvth = "3.1.1" diff --git a/server/src/auth_provider.rs b/server/src/auth_provider.rs index 61623b6076..14156bd398 100644 --- a/server/src/auth_provider.rs +++ b/server/src/auth_provider.rs @@ -1,8 +1,8 @@ use authc::{AuthClient, AuthToken, Uuid}; use common::msg::RegisterError; use hashbrown::HashMap; -use log::error; use std::str::FromStr; +use tracing::{error, info}; fn derive_uuid(username: &str) -> Uuid { let mut state = 144066263297769815596495629667062367629; @@ -45,7 +45,7 @@ impl AuthProvider { match &self.auth_server { // Token from auth server expected Some(srv) => { - log::info!("Validating '{}' token.", &username_or_token); + info!("Validating '{}' token.", &username_or_token); // Parse token let token = AuthToken::from_str(&username_or_token) .map_err(|e| RegisterError::AuthError(e.to_string()))?; @@ -66,7 +66,7 @@ impl AuthProvider { let username = username_or_token; let uuid = derive_uuid(&username); if !self.accounts.contains_key(&uuid) { - log::info!("New User '{}'", username); + info!("New User '{}'", username); self.accounts.insert(uuid, username.clone()); Ok((username, uuid)) } else { diff --git a/server/src/cmd.rs b/server/src/cmd.rs index 3fdf6cd6aa..7ce557f6a3 100644 --- a/server/src/cmd.rs +++ b/server/src/cmd.rs @@ -22,8 +22,8 @@ use specs::{Builder, Entity as EcsEntity, Join, WorldExt}; use vek::*; use world::util::Sampler; -use log::error; use scan_fmt::{scan_fmt, scan_fmt_some}; +use tracing::error; pub trait ChatCommandExt { fn execute(&self, server: &mut Server, entity: EcsEntity, args: String); diff --git a/server/src/events/entity_manipulation.rs b/server/src/events/entity_manipulation.rs index cdc8527f93..c049a65b07 100644 --- a/server/src/events/entity_manipulation.rs +++ b/server/src/events/entity_manipulation.rs @@ -9,9 +9,9 @@ use common::{ terrain::{Block, TerrainGrid}, vol::{ReadVol, Vox}, }; -use log::error; use rand::seq::SliceRandom; use specs::{join::Join, Entity as EcsEntity, WorldExt}; +use tracing::error; use vek::Vec3; pub fn handle_damage(server: &Server, uid: Uid, change: HealthChange) { diff --git a/server/src/events/interaction.rs b/server/src/events/interaction.rs index b07c68bed4..28d13870b8 100644 --- a/server/src/events/interaction.rs +++ b/server/src/events/interaction.rs @@ -8,8 +8,8 @@ use common::{ msg::ServerMsg, sync::{Uid, WorldSyncExt}, }; -use log::error; use specs::{world::WorldExt, Entity as EcsEntity}; +use tracing::error; pub fn handle_lantern(server: &mut Server, entity: EcsEntity) { let ecs = server.state_mut().ecs(); diff --git a/server/src/events/inventory_manip.rs b/server/src/events/inventory_manip.rs index 3c87baac02..4c4c7b109f 100644 --- a/server/src/events/inventory_manip.rs +++ b/server/src/events/inventory_manip.rs @@ -9,9 +9,9 @@ use common::{ terrain::block::Block, vol::{ReadVol, Vox}, }; -use log::error; use rand::Rng; use specs::{join::Join, world::WorldExt, Builder, Entity as EcsEntity, WriteStorage}; +use tracing::error; use vek::Vec3; pub fn swap_lantern( diff --git a/server/src/events/player.rs b/server/src/events/player.rs index f857e4a1a5..9039d990cc 100644 --- a/server/src/events/player.rs +++ b/server/src/events/player.rs @@ -8,8 +8,8 @@ use common::{ msg::{ClientState, PlayerListUpdate, ServerMsg}, sync::{Uid, UidAllocator}, }; -use log::error; use specs::{saveload::MarkerAllocator, Builder, Entity as EcsEntity, Join, WorldExt}; +use tracing::error; pub fn handle_exit_ingame(server: &mut Server, entity: EcsEntity) { let state = server.state_mut(); diff --git a/server/src/lib.rs b/server/src/lib.rs index eb74ac30b4..26d961a802 100644 --- a/server/src/lib.rs +++ b/server/src/lib.rs @@ -38,7 +38,6 @@ use common::{ terrain::TerrainChunkSize, vol::{ReadVol, RectVolSize}, }; -use log::{debug, error}; use metrics::{ServerMetrics, TickMetrics}; use specs::{join::Join, Builder, Entity as EcsEntity, RunNow, SystemData, WorldExt}; use std::{ @@ -48,6 +47,7 @@ use std::{ }; #[cfg(not(feature = "worldgen"))] use test_world::{World, WORLD_SIZE}; +use tracing::{debug, error, info}; use uvth::{ThreadPool, ThreadPoolBuilder}; use vek::*; #[cfg(feature = "worldgen")] @@ -256,12 +256,12 @@ impl Server { if let Some(error) = persistence::run_migrations(&this.server_settings.persistence_db_dir).err() { - log::info!("Migration error: {}", format!("{:#?}", error)); + info!("Migration error: {}", format!("{:#?}", error)); } debug!("created veloren server with: {:?}", &settings); - log::info!( + info!( "Server version: {}[{}]", *common::util::GIT_HASH, *common::util::GIT_DATE @@ -536,7 +536,7 @@ impl Server { .build(); // Send client all the tracked components currently attached to its entity as // well as synced resources (currently only `TimeOfDay`) - log::debug!("Starting initial sync with client."); + debug!("Starting initial sync with client."); self.state .ecs() .write_storage::() @@ -550,7 +550,7 @@ impl Server { time_of_day: *self.state.ecs().read_resource(), world_map: (WORLD_SIZE.map(|e| e as u32), self.map.clone()), }); - log::debug!("Done initial sync with client."); + debug!("Done initial sync with client."); frontend_events.push(Event::ClientConnected { entity }); } diff --git a/server/src/metrics.rs b/server/src/metrics.rs index 89faf74114..5169bbc5ac 100644 --- a/server/src/metrics.rs +++ b/server/src/metrics.rs @@ -1,4 +1,3 @@ -use log::{debug, error}; use prometheus::{Encoder, Gauge, IntGauge, IntGaugeVec, Opts, Registry, TextEncoder}; use std::{ convert::TryInto, @@ -11,6 +10,7 @@ use std::{ thread, time::{Duration, SystemTime, UNIX_EPOCH}, }; +use tracing::{debug, error}; pub struct TickMetrics { pub chonks_count: IntGauge, diff --git a/server/src/persistence/character.rs b/server/src/persistence/character.rs index c0b6650b63..248f38f08d 100644 --- a/server/src/persistence/character.rs +++ b/server/src/persistence/character.rs @@ -16,6 +16,7 @@ use common::{ }; use crossbeam::channel; use diesel::prelude::*; +use tracing::{error, warn}; type CharacterListResult = Result, Error>; @@ -54,10 +55,9 @@ pub fn load_character_data( .values(&row) .execute(&connection) { - log::warn!( + warn!( "Failed to create an inventory record for character {}: {}", - &character_data.id, - error + &character_data.id, error ) } @@ -81,10 +81,9 @@ pub fn load_character_data( .values(&row) .execute(&connection) { - log::warn!( + warn!( "Failed to create an loadout record for character {}: {}", - &character_data.id, - error + &character_data.id, error ) } @@ -232,7 +231,7 @@ pub fn create_character( .values(&new_loadout) .execute(&connection)?; }, - _ => log::warn!("Creating non-humanoid characters is not supported."), + _ => warn!("Creating non-humanoid characters is not supported."), }; Ok(()) @@ -316,7 +315,7 @@ impl CharacterUpdater { .collect(); if let Err(err) = self.update_tx.as_ref().unwrap().send(updates) { - log::error!("Could not send stats updates: {:?}", err); + error!("Could not send stats updates: {:?}", err); } } @@ -349,7 +348,7 @@ fn batch_update(updates: impl Iterator, db_di Ok(()) }) { - log::error!("Error during stats batch update transaction: {:?}", err); + error!("Error during stats batch update transaction: {:?}", err); } } @@ -365,10 +364,9 @@ fn update( .set(stats) .execute(connection) { - log::warn!( + warn!( "Failed to update stats for character: {:?}: {:?}", - character_id, - error + character_id, error ) } @@ -378,10 +376,9 @@ fn update( .set(inventory) .execute(connection) { - log::warn!( + warn!( "Failed to update inventory for character: {:?}: {:?}", - character_id, - error + character_id, error ) } @@ -391,10 +388,9 @@ fn update( .set(loadout) .execute(connection) { - log::warn!( + warn!( "Failed to update loadout for character: {:?}: {:?}", - character_id, - error + character_id, error ) } } @@ -403,7 +399,7 @@ impl Drop for CharacterUpdater { fn drop(&mut self) { drop(self.update_tx.take()); if let Err(err) = self.handle.take().unwrap().join() { - log::error!("Error from joining character update thread: {:?}", err); + error!("Error from joining character update thread: {:?}", err); } } } diff --git a/server/src/persistence/mod.rs b/server/src/persistence/mod.rs index e3e788b72e..fc3389053f 100644 --- a/server/src/persistence/mod.rs +++ b/server/src/persistence/mod.rs @@ -9,6 +9,7 @@ extern crate diesel; use diesel::{connection::SimpleConnection, prelude::*}; use diesel_migrations::embed_migrations; use std::{env, fs, path::PathBuf}; +use tracing::warn; // See: https://docs.rs/diesel_migrations/1.4.0/diesel_migrations/macro.embed_migrations.html // This macro is called at build-time, and produces the necessary migration info @@ -36,7 +37,7 @@ fn establish_connection(db_dir: &str) -> SqliteConnection { PRAGMA busy_timeout = 250; ", ) { - log::warn!( + warn!( "Failed adding PRAGMA statements while establishing sqlite connection, this will \ result in a higher likelihood of locking errors: {}", error @@ -57,7 +58,7 @@ fn apply_saves_dir_override(db_dir: &str) -> String { None => {}, } } - log::warn!("VELOREN_SAVES_DIR points to an invalid path."); + warn!("VELOREN_SAVES_DIR points to an invalid path."); } db_dir.to_string() } diff --git a/server/src/persistence/models.rs b/server/src/persistence/models.rs index 563d11d12c..a717376e97 100644 --- a/server/src/persistence/models.rs +++ b/server/src/persistence/models.rs @@ -5,6 +5,7 @@ use crate::comp; use common::{character::Character as CharacterData, LoadoutBuilder}; use diesel::sql_types::Text; use serde::{Deserialize, Serialize}; +use tracing::warn; /// The required elements to build comp::Stats from database data pub struct StatsJoinData<'a> { @@ -173,7 +174,7 @@ where match serde_json::from_str(&t) { Ok(data) => Ok(Self(data)), Err(error) => { - log::warn!("Failed to deserialise inventory data: {}", error); + warn!("Failed to deserialise inventory data: {}", error); Ok(Self(comp::Inventory::default())) }, } @@ -259,7 +260,7 @@ where match serde_json::from_str(&t) { Ok(data) => Ok(Self(data)), Err(error) => { - log::warn!("Failed to deserialise loadout data: {}", error); + warn!("Failed to deserialise loadout data: {}", error); // We don't have a weapon reference here, so we default to sword let loadout = LoadoutBuilder::new() diff --git a/server/src/settings.rs b/server/src/settings.rs index 3432482777..d8d17b0117 100644 --- a/server/src/settings.rs +++ b/server/src/settings.rs @@ -1,6 +1,7 @@ use portpicker::pick_unused_port; use serde_derive::{Deserialize, Serialize}; use std::{fs, io::prelude::*, net::SocketAddr, path::PathBuf}; +use tracing::{error, warn}; use world::sim::FileOpts; const DEFAULT_WORLD_SEED: u32 = 59686; @@ -71,7 +72,7 @@ impl ServerSettings { match ron::de::from_reader(file) { Ok(x) => x, Err(e) => { - log::warn!("Failed to parse setting file! Fallback to default. {}", e); + warn!("Failed to parse setting file! Fallback to default. {}", e); Self::default() }, } @@ -79,7 +80,7 @@ impl ServerSettings { let default_settings = Self::default(); match default_settings.save_to_file() { - Err(e) => log::error!("Failed to create default setting file! {}", e), + Err(e) => error!("Failed to create default setting file! {}", e), _ => {}, } default_settings diff --git a/server/src/state_ext.rs b/server/src/state_ext.rs index 06c3645cf0..551be9886b 100644 --- a/server/src/state_ext.rs +++ b/server/src/state_ext.rs @@ -12,8 +12,8 @@ use common::{ sync::{Uid, WorldSyncExt}, util::Dir, }; -use log::warn; use specs::{Builder, Entity as EcsEntity, EntityBuilder as EcsEntityBuilder, Join, WorldExt}; +use tracing::warn; use vek::*; pub trait StateExt { @@ -173,7 +173,7 @@ impl StateExt for State { self.write_component(entity, loadout); }, Err(error) => { - log::warn!( + warn!( "{}", format!( "Failed to load character data for character_id {}: {}", diff --git a/server/src/sys/message.rs b/server/src/sys/message.rs index 676b768fbd..91ee00541d 100644 --- a/server/src/sys/message.rs +++ b/server/src/sys/message.rs @@ -22,6 +22,7 @@ use hashbrown::HashMap; use specs::{ Entities, Join, Read, ReadExpect, ReadStorage, System, Write, WriteExpect, WriteStorage, }; +use tracing::warn; /// This system will handle new messages from clients pub struct Sys; @@ -274,7 +275,7 @@ impl<'a> System<'a> for Sys { | ClientState::Spectator | ClientState::Character => match validate_chat_msg(&message) { Ok(()) => new_chat_msgs.push((Some(entity), ServerMsg::chat(message))), - Err(ChatMsgValidationError::TooLong) => log::warn!( + Err(ChatMsgValidationError::TooLong) => warn!( "Recieved a chat message that's too long (max:{} len:{})", MAX_BYTES_CHAT_MSG, message.len() diff --git a/server/src/sys/subscription.rs b/server/src/sys/subscription.rs index 8195cde1eb..39413a8450 100644 --- a/server/src/sys/subscription.rs +++ b/server/src/sys/subscription.rs @@ -11,11 +11,11 @@ use common::{ terrain::TerrainChunkSize, vol::RectVolSize, }; -use log::{debug, error}; use specs::{ Entities, Join, ReadExpect, ReadStorage, System, SystemData, World, WorldExt, Write, WriteStorage, }; +use tracing::{debug, error}; use vek::*; /// This system will update region subscriptions based on client positions diff --git a/voxygen/Cargo.toml b/voxygen/Cargo.toml index cdf93d4074..2366ff3043 100644 --- a/voxygen/Cargo.toml +++ b/voxygen/Cargo.toml @@ -71,10 +71,7 @@ uvth = "3.1.1" authc = { git = "https://gitlab.com/veloren/auth.git", rev = "223a4097f7ebc8d451936dccb5e6517194bbf086" } const-tweaker = { version = "0.2.5", optional = true } -# # Logging -# log = "0.4.8" -# fern = { version = "0.5.8", features = ["colored"] } -# Logging (new) +# Logging tracing = { version = "0.1", default-features = false , features = ["attributes"] } tracing-subscriber = { version = "0.2.3", default-features = false, features = ["env-filter", "fmt", "chrono", "ansi", "smallvec", "registry", "tracing-log"] } tracing-log = "0.1.1" diff --git a/world/Cargo.toml b/world/Cargo.toml index d8b2def456..9601d5b5f8 100644 --- a/world/Cargo.toml +++ b/world/Cargo.toml @@ -17,7 +17,7 @@ num = "0.2.0" ordered-float = "1.0" hashbrown = { version = "0.6", features = ["rayon", "serde", "nightly"] } lazy_static = "1.4.0" -log = "0.4.8" +tracing = { version = "0.1", default-features = false , features = ["attributes"] } rand = "0.7" rand_chacha = "0.2.1" arr_macro = "0.1.2" @@ -29,5 +29,5 @@ serde_derive = "1.0" ron = { version = "0.6", default-features = false } [dev-dependencies] -pretty_env_logger = "0.3.0" +tracing-subscriber = { version = "0.2.3", default-features = false, features = ["fmt", "chrono", "ansi", "smallvec"] } minifb = "0.14.0" diff --git a/world/examples/water.rs b/world/examples/water.rs index d1bb627eb5..1ac35361e5 100644 --- a/world/examples/water.rs +++ b/world/examples/water.rs @@ -1,5 +1,7 @@ use common::{terrain::TerrainChunkSize, vol::RectVolSize}; use std::{f64, io::Write, path::PathBuf, time::SystemTime}; +use tracing::warn; +use tracing_subscriber; use vek::*; use veloren_world::{ sim::{self, MapConfig, MapDebug, WorldOpts, WORLD_SIZE}, @@ -12,7 +14,7 @@ const H: usize = 1024; #[allow(clippy::needless_update)] // TODO: Pending review in #587 #[allow(clippy::unused_io_amount)] // TODO: Pending review in #587 fn main() { - pretty_env_logger::init(); + tracing_subscriber::fmt::init(); // To load a map file of your choice, replace map_file with the name of your map // (stored locally in the map directory of your Veloren root), and swap the @@ -113,7 +115,7 @@ fn main() { let mut path = PathBuf::from("./screenshots"); if !path.exists() { if let Err(err) = std::fs::create_dir(&path) { - log::warn!("Couldn't create folder for screenshot: {:?}", err); + warn!("Couldn't create folder for screenshot: {:?}", err); } } path.push(format!( @@ -124,7 +126,7 @@ fn main() { .unwrap_or(0) )); if let Err(err) = world_map.save(&path) { - log::warn!("Couldn't save screenshot: {:?}", err); + warn!("Couldn't save screenshot: {:?}", err); } } } diff --git a/world/src/civ/mod.rs b/world/src/civ/mod.rs index 921607931a..efeaffa9d9 100644 --- a/world/src/civ/mod.rs +++ b/world/src/civ/mod.rs @@ -25,6 +25,7 @@ use fxhash::{FxHasher32, FxHasher64}; use hashbrown::{HashMap, HashSet}; use rand::prelude::*; use rand_chacha::ChaChaRng; +use tracing::{info, warn}; use vek::*; const INITIAL_CIV_COUNT: usize = (crate::sim::WORLD_SIZE.x * crate::sim::WORLD_SIZE.y * 3) / 65536; //48 at default scale @@ -76,9 +77,9 @@ impl Civs { let mut ctx = GenCtx { sim, rng }; for _ in 0..INITIAL_CIV_COUNT { - log::info!("Creating civilisation..."); + info!("Creating civilisation..."); if this.birth_civ(&mut ctx.reseed()).is_none() { - log::warn!("Failed to find starting site for civilisation."); + warn!("Failed to find starting site for civilisation."); } } @@ -186,7 +187,7 @@ impl Civs { .get_mut(pos) .map(|chunk| chunk.sites.push(world_site.clone())); } - log::info!("Placed site at {:?}", site.center); + info!("Placed site at {:?}", site.center); } //this.display_info(); diff --git a/world/src/column/mod.rs b/world/src/column/mod.rs index 8d3bc2a419..f7fb19161f 100644 --- a/world/src/column/mod.rs +++ b/world/src/column/mod.rs @@ -13,6 +13,7 @@ use std::{ f32, f64, ops::{Add, Div, Mul, Neg, Sub}, }; +use tracing::error; use vek::*; pub struct ColumnGen<'a> { @@ -213,7 +214,7 @@ impl<'a> Sampler<'a> for ColumnGen<'a> { } else { match kind { RiverKind::River { .. } => { - log::error!("What? River: {:?}, Pos: {:?}", river, posj); + error!("What? River: {:?}, Pos: {:?}", river, posj); panic!("How can a river have no downhill?"); }, RiverKind::Lake { .. } => { @@ -617,11 +618,9 @@ impl<'a> Sampler<'a> for ColumnGen<'a> { ) = if let Some(dist) = max_border_river_dist { dist } else { - log::error!( + error!( "Ocean: {:?} Here: {:?}, Ocean: {:?}", - max_border_river, - chunk_pos, - max_border_river_pos + max_border_river, chunk_pos, max_border_river_pos ); panic!( "Oceans should definitely have a downhill! \ diff --git a/world/src/sim/erosion.rs b/world/src/sim/erosion.rs index 1412de21af..787c75a45b 100644 --- a/world/src/sim/erosion.rs +++ b/world/src/sim/erosion.rs @@ -4,6 +4,7 @@ use super::{ }; use crate::{config::CONFIG, util::RandomField}; use common::{terrain::TerrainChunkSize, vol::RectVolSize}; +use tracing::{debug, error, warn}; // use faster::*; use itertools::izip; use noise::{NoiseFn, Point3}; @@ -427,7 +428,7 @@ pub fn get_rivers, G: Float + Into>( if slope == 0.0 { // This is not a river--how did this even happen? let pass_idx = (-indirection_idx) as usize; - log::error!( + error!( "Our chunk (and downhill, lake, pass, neighbor_pass): {:?} (to {:?}, in {:?} via \ {:?} to {:?}), chunk water alt: {:?}, lake water alt: {:?}", uniform_idx_as_vec2(chunk_idx), @@ -715,7 +716,7 @@ fn erode( k_da_scale: impl Fn(f64) -> f64, ) { let compute_stats = true; - log::debug!("Done draining..."); + debug!("Done draining..."); // NOTE: To experimentally allow erosion to proceed below sea level, replace 0.0 // with -::infinity(). let min_erosion_height = 0.0; // -::infinity(); @@ -723,7 +724,7 @@ fn erode( // NOTE: The value being divided by here sets the effective maximum uplift rate, // as everything is scaled to it! let dt = max_uplift as f64 / 1e-3; - log::debug!("dt={:?}", dt); + debug!("dt={:?}", dt); // Minimum sediment thickness before we treat erosion as sediment based. let sediment_thickness = |_n| /*6.25e-5*/1.0e-4 * dt; let neighbor_coef = TerrainChunkSize::RECT_SIZE.map(|e| e as f64); @@ -801,9 +802,9 @@ fn erode( let ((dh, newh, maxh, mrec, mstack, mwrec, area), (mut max_slopes, h_t)) = rayon::join( || { let mut dh = downhill(|posi| h[posi], |posi| is_ocean(posi) && h[posi] <= 0.0); - log::debug!("Computed downhill..."); + debug!("Computed downhill..."); let (boundary_len, _indirection, newh, maxh) = get_lakes(|posi| h[posi], &mut dh); - log::debug!("Got lakes..."); + debug!("Got lakes..."); let (mrec, mstack, mwrec) = get_multi_rec( |posi| h[posi], &dh, @@ -815,12 +816,12 @@ fn erode( dy as Compute, maxh, ); - log::debug!("Got multiple receivers..."); + debug!("Got multiple receivers..."); // TODO: Figure out how to switch between single-receiver and multi-receiver // drainage, as the former is much less computationally costly. // let area = get_drainage(&newh, &dh, boundary_len); let area = get_multi_drainage(&mstack, &mrec, &*mwrec, boundary_len); - log::debug!("Got flux..."); + debug!("Got flux..."); (dh, newh, maxh, mrec, mstack, mwrec, area) }, || { @@ -828,7 +829,7 @@ fn erode( || { let max_slope = get_max_slope(h, rock_strength_nz, |posi| height_scale(n_f(posi))); - log::debug!("Got max slopes..."); + debug!("Got max slopes..."); max_slope }, || h.to_vec().into_boxed_slice(), @@ -987,7 +988,7 @@ fn erode( }, ); - log::debug!("Computed stream power factors..."); + debug!("Computed stream power factors..."); let mut lake_water_volume = vec![0.0 as Compute; WORLD_SIZE.x * WORLD_SIZE.y].into_boxed_slice(); @@ -1056,7 +1057,7 @@ fn erode( }); while err > tol && n_gs_stream_power_law < max_n_gs_stream_power_law { - log::debug!("Stream power iteration #{:?}", n_gs_stream_power_law); + debug!("Stream power iteration #{:?}", n_gs_stream_power_law); // Reset statistics in each loop. maxh = 0.0; @@ -1096,7 +1097,7 @@ fn erode( }); }, ); - log::debug!( + debug!( "(Done precomputation, time={:?}ms).", start_time.elapsed().as_millis() ); @@ -1131,7 +1132,7 @@ fn erode( }); } }); - log::debug!( + debug!( "(Done sediment transport computation, time={:?}ms).", start_time.elapsed().as_millis() ); @@ -1206,7 +1207,7 @@ fn erode( } }, ); - log::debug!( + debug!( "(Done elevation estimation, time={:?}ms).", start_time.elapsed().as_millis() ); @@ -1232,7 +1233,7 @@ fn erode( panic!("Disconnected lake!"); } if h_t_i > 0.0 { - log::warn!("Ocean above zero?"); + warn!("Ocean above zero?"); } // Egress with no outgoing flows. // wh for oceans is always at least min_erosion_height. @@ -1427,21 +1428,20 @@ fn erode( sum_err += (iteration_error + h_stack[stacki] as Compute - h_p_i as Compute).powi(2); }); - log::debug!( + debug!( "(Done erosion computation, time={:?}ms)", start_time.elapsed().as_millis() ); err = (sum_err / mstack.len() as Compute).sqrt(); - log::debug!("(RMSE: {:?})", err); + debug!("(RMSE: {:?})", err); if max_g == 0.0 { err = 0.0; } if n_gs_stream_power_law == max_n_gs_stream_power_law { - log::warn!( + warn!( "Beware: Gauss-Siedel scheme not convergent: err={:?}, expected={:?}", - err, - tol + err, tol ); } } @@ -1507,7 +1507,7 @@ fn erode( new_b_i = new_b_i.min(h_i); *b = new_b_i; }); - log::debug!("Done updating basement and applying soil production..."); + debug!("Done updating basement and applying soil production..."); // update the height to reflect sediment flux. if max_g > 0.0 { @@ -1541,7 +1541,7 @@ fn erode( // endif // enddo - log::debug!( + debug!( "Done applying stream power (max height: {:?}) (avg height: {:?}) (min height: {:?}) (avg \ slope: {:?})\n (above talus angle, geom. mean slope [actual/critical/ratio]: {:?} \ / {:?} / {:?})\n (old avg sediment thickness [all/land]: {:?} / {:?})\n \ @@ -1670,7 +1670,7 @@ fn erode( maxh = h_i.max(maxh); } }); - log::debug!( + debug!( "Done applying thermal erosion (max height: {:?}) (avg height: {:?}) (min height: {:?}) \ (avg slope: {:?})\n (above talus angle, geom. mean slope [actual/critical/ratio]: \ {:?} / {:?} / {:?})\n (avg sediment thickness [all/land]: {:?} / {:?})\n \ @@ -1702,8 +1702,8 @@ fn erode( |posi| max_slopes[posi], -1.0, ); - log::debug!("Done applying diffusion."); - log::debug!("Done eroding."); + debug!("Done applying diffusion."); + debug!("Done eroding."); } /// The Planchon-Darboux algorithm for extracting drainage networks. @@ -1878,7 +1878,7 @@ pub fn get_lakes( }); assert_eq!(newh.len(), downhill.len()); - log::debug!("Old lake roots: {:?}", lake_roots.len()); + debug!("Old lake roots: {:?}", lake_roots.len()); let newh = newh.into_boxed_slice(); let mut maxh = -F::infinity(); @@ -2112,7 +2112,7 @@ pub fn get_lakes( ))); } } - log::debug!("Total lakes: {:?}", pass_flows_sorted.len()); + debug!("Total lakes: {:?}", pass_flows_sorted.len()); // Perform the bfs once again. #[derive(Clone, Copy, PartialEq)] @@ -2520,7 +2520,7 @@ pub fn do_erosion( k_d_scale: f64, k_da_scale: impl Fn(f64) -> f64, ) -> (Box<[Alt]>, Box<[Alt]> /* , Box<[Alt]> */) { - log::debug!("Initializing erosion arrays..."); + debug!("Initializing erosion arrays..."); let oldh_ = (0..WORLD_SIZE.x * WORLD_SIZE.y) .into_par_iter() .map(|posi| oldh(posi) as Alt) @@ -2587,7 +2587,7 @@ pub fn do_erosion( .cloned() .map(|e| e as f64) .sum::(); - log::debug!("Sum uplifts: {:?}", sum_uplift); + debug!("Sum uplifts: {:?}", sum_uplift); let max_uplift = uplift .into_par_iter() @@ -2599,8 +2599,8 @@ pub fn do_erosion( .cloned() .max_by(|a, b| a.partial_cmp(&b).unwrap()) .unwrap(); - log::debug!("Max uplift: {:?}", max_uplift); - log::debug!("Max g: {:?}", max_g); + debug!("Max uplift: {:?}", max_uplift); + debug!("Max g: {:?}", max_g); // Height of terrain, including sediment. let mut h = oldh_; // Bedrock transport coefficients (diffusivity) in m^2 / year, for sediment. @@ -2619,7 +2619,7 @@ pub fn do_erosion( let height_scale = |n| height_scale(n); let k_da_scale = |q| k_da_scale(q); (0..n_steps).for_each(|i| { - log::debug!("Erosion iteration #{:?}", i); + debug!("Erosion iteration #{:?}", i); erode( &mut h, &mut b, diff --git a/world/src/sim/mod.rs b/world/src/sim/mod.rs index 08d26d4965..81126c2171 100644 --- a/world/src/sim/mod.rs +++ b/world/src/sim/mod.rs @@ -52,6 +52,7 @@ use std::{ ops::{Add, Div, Mul, Neg, Sub}, path::PathBuf, }; +use tracing::{debug, warn}; use vek::*; // NOTE: I suspect this is too small (1024 * 16 * 1024 * 16 * 8 doesn't fit in @@ -877,7 +878,7 @@ impl WorldSim { let file = match File::open(path) { Ok(file) => file, Err(err) => { - log::warn!("Couldn't read path for maps: {:?}", err); + warn!("Couldn't read path for maps: {:?}", err); return None; }, }; @@ -886,7 +887,7 @@ impl WorldSim { let map: WorldFileLegacy = match bincode::deserialize_from(reader) { Ok(map) => map, Err(err) => { - log::warn!( + warn!( "Couldn't parse legacy map: {:?}). Maybe you meant to try a \ regular load?", err @@ -901,7 +902,7 @@ impl WorldSim { let file = match File::open(path) { Ok(file) => file, Err(err) => { - log::warn!("Couldn't read path for maps: {:?}", err); + warn!("Couldn't read path for maps: {:?}", err); return None; }, }; @@ -910,7 +911,7 @@ impl WorldSim { let map: WorldFile = match bincode::deserialize_from(reader) { Ok(map) => map, Err(err) => { - log::warn!( + warn!( "Couldn't parse modern map: {:?}). Maybe you meant to try a \ legacy load?", err @@ -925,10 +926,9 @@ impl WorldSim { let reader = match assets::load_file(specifier, &["bin"]) { Ok(reader) => reader, Err(err) => { - log::warn!( + warn!( "Couldn't read asset specifier {:?} for maps: {:?}", - specifier, - err + specifier, err ); return None; }, @@ -937,7 +937,7 @@ impl WorldSim { let map: WorldFile = match bincode::deserialize_from(reader) { Ok(map) => map, Err(err) => { - log::warn!( + warn!( "Couldn't parse modern map: {:?}). Maybe you meant to try a \ legacy load?", err @@ -956,7 +956,7 @@ impl WorldSim { Err(e) => { match e { WorldFileError::WorldSizeInvalid => { - log::warn!("World size of map is invalid."); + warn!("World size of map is invalid."); }, } None @@ -1027,7 +1027,7 @@ impl WorldSim { let mut path = PathBuf::from("./maps"); if !path.exists() { if let Err(err) = std::fs::create_dir(&path) { - log::warn!("Couldn't create folder for map: {:?}", err); + warn!("Couldn't create folder for map: {:?}", err); return; } } @@ -1042,14 +1042,14 @@ impl WorldSim { let file = match File::create(path) { Ok(file) => file, Err(err) => { - log::warn!("Couldn't create file for maps: {:?}", err); + warn!("Couldn't create file for maps: {:?}", err); return; }, }; let writer = BufWriter::new(file); if let Err(err) = bincode::serialize_into(writer, &map) { - log::warn!("Couldn't write map: {:?}", err); + warn!("Couldn't write map: {:?}", err); } } })(); @@ -1088,7 +1088,7 @@ impl WorldSim { let is_ocean_fn = |posi: usize| is_ocean[posi]; let mut dh = downhill(|posi| alt[posi], is_ocean_fn); let (boundary_len, indirection, water_alt_pos, maxh) = get_lakes(|posi| alt[posi], &mut dh); - log::debug!("Max height: {:?}", maxh); + debug!("Max height: {:?}", maxh); let (mrec, mstack, mwrec) = { let mut wh = vec![0.0; WORLD_SIZE.x * WORLD_SIZE.y]; get_multi_rec( @@ -1911,11 +1911,9 @@ impl SimChunk { ); */ } if river_slope.abs() >= 0.25 && cross_section.x >= 1.0 { - log::debug!( + debug!( "Big waterfall! Pos area: {:?}, River data: {:?}, slope: {:?}", - wposf, - river, - river_slope + wposf, river, river_slope ); } },