Convert all other veloren crates to use tracing

- Completely removed both `log` and `pretty_env_logger` and replaced
with `tracing` and `tracing_subscriber` where necessary.

- Converted all `log::info!(...)` et al. statements to just use the
shorthand macro i.e. `info!`. This was mostly to make renaming easier.
This commit is contained in:
Kevin Glasson
2020-06-21 22:26:06 +08:00
parent 16cf7689a8
commit cfe09c2f55
42 changed files with 257 additions and 331 deletions

60
Cargo.lock generated
View File

@ -1125,19 +1125,6 @@ version = "1.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb1f6b1ce1c140482ea30ddd3335fc0024ac7ee112895426e0a629a6c20adfe3" 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]] [[package]]
name = "error-chain" name = "error-chain"
version = "0.12.2" version = "0.12.2"
@ -1954,15 +1941,6 @@ version = "1.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd179ae861f0c2e53da70d892f5f3029f9594be0c41dc5269cd371691b1dc2f9" 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]] [[package]]
name = "hyper" name = "hyper"
version = "0.12.35" version = "0.12.35"
@ -3034,17 +3012,6 @@ version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "237a5ed80e274dbc66f86bd59c1e25edc039660be53194b5fe0a482e0f2612ea" 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]] [[package]]
name = "proc-macro-hack" name = "proc-macro-hack"
version = "0.5.16" version = "0.5.16"
@ -4000,15 +3967,6 @@ dependencies = [
"unicode-xid 0.2.0", "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]] [[package]]
name = "textwrap" name = "textwrap"
version = "0.11.0" version = "0.11.0"
@ -4478,8 +4436,8 @@ dependencies = [
name = "veloren-chat-cli" name = "veloren-chat-cli"
version = "0.6.0" version = "0.6.0"
dependencies = [ dependencies = [
"log", "tracing",
"pretty_env_logger", "tracing-subscriber",
"veloren-client", "veloren-client",
"veloren-common", "veloren-common",
] ]
@ -4492,9 +4450,9 @@ dependencies = [
"byteorder 1.3.4", "byteorder 1.3.4",
"hashbrown", "hashbrown",
"image", "image",
"log",
"num_cpus", "num_cpus",
"specs", "specs",
"tracing",
"uvth 3.1.1", "uvth 3.1.1",
"vek", "vek",
"veloren-common", "veloren-common",
@ -4514,7 +4472,6 @@ dependencies = [
"image", "image",
"indexmap", "indexmap",
"lazy_static", "lazy_static",
"log",
"lz4-compress", "lz4-compress",
"mio", "mio",
"notify", "notify",
@ -4528,6 +4485,7 @@ dependencies = [
"specs", "specs",
"specs-idvs", "specs-idvs",
"sum_type", "sum_type",
"tracing",
"vek", "vek",
] ]
@ -4544,7 +4502,6 @@ dependencies = [
"hashbrown", "hashbrown",
"lazy_static", "lazy_static",
"libsqlite3-sys", "libsqlite3-sys",
"log",
"portpicker", "portpicker",
"prometheus", "prometheus",
"prometheus-static-metric", "prometheus-static-metric",
@ -4557,6 +4514,7 @@ dependencies = [
"specs", "specs",
"specs-idvs", "specs-idvs",
"tiny_http", "tiny_http",
"tracing",
"uvth 3.1.1", "uvth 3.1.1",
"vek", "vek",
"veloren-common", "veloren-common",
@ -4567,8 +4525,8 @@ dependencies = [
name = "veloren-server-cli" name = "veloren-server-cli"
version = "0.6.0" version = "0.6.0"
dependencies = [ dependencies = [
"log", "tracing",
"pretty_env_logger", "tracing-subscriber",
"veloren-common", "veloren-common",
"veloren-server", "veloren-server",
] ]
@ -4652,13 +4610,11 @@ dependencies = [
"image", "image",
"itertools 0.8.2", "itertools 0.8.2",
"lazy_static", "lazy_static",
"log",
"minifb", "minifb",
"noise", "noise",
"num 0.2.1", "num 0.2.1",
"ordered-float", "ordered-float",
"packed_simd", "packed_simd",
"pretty_env_logger",
"rand 0.7.3", "rand 0.7.3",
"rand_chacha 0.2.2", "rand_chacha 0.2.2",
"rayon", "rayon",
@ -4666,6 +4622,8 @@ dependencies = [
"roots", "roots",
"serde", "serde",
"serde_derive", "serde_derive",
"tracing",
"tracing-subscriber",
"vek", "vek",
"veloren-common", "veloren-common",
] ]

View File

@ -8,5 +8,5 @@ edition = "2018"
client = { package = "veloren-client", path = "../client" } client = { package = "veloren-client", path = "../client" }
common = { package = "veloren-common", path = "../common" } common = { package = "veloren-common", path = "../common" }
log = "0.4.8" tracing = { version = "0.1", default-features = false , features = ["attributes"] }
pretty_env_logger = "0.3.1" tracing-subscriber = { version = "0.2.3", default-features = false, features = ["fmt", "chrono", "ansi", "smallvec"] }

View File

@ -3,8 +3,8 @@
use client::{Client, Event}; use client::{Client, Event};
use common::{clock::Clock, comp}; use common::{clock::Clock, comp};
use log::{error, info};
use std::{io, net::ToSocketAddrs, sync::mpsc, thread, time::Duration}; 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. const TPS: u64 = 10; // Low value is okay, just reading messages.
@ -20,7 +20,7 @@ fn read_input() -> String {
fn main() { fn main() {
// Initialize logging. // Initialize logging.
pretty_env_logger::init(); tracing_subscriber::fmt::init();
info!("Starting chat-cli..."); info!("Starting chat-cli...");

View File

@ -11,7 +11,7 @@ byteorder = "1.3.2"
uvth = "3.1.1" uvth = "3.1.1"
image = { version = "0.22.3", default-features = false, features = ["png"] } image = { version = "0.22.3", default-features = false, features = ["png"] }
num_cpus = "1.10.1" num_cpus = "1.10.1"
log = "0.4.8" tracing = { version = "0.1", default-features = false , features = ["attributes"] }
specs = "0.15.1" specs = "0.15.1"
vek = { version = "0.11.0", features = ["serde"] } vek = { version = "0.11.0", features = ["serde"] }
hashbrown = { version = "0.6", features = ["rayon", "serde", "nightly"] } hashbrown = { version = "0.6", features = ["rayon", "serde", "nightly"] }

View File

@ -36,12 +36,12 @@ use common::{
}; };
use hashbrown::HashMap; use hashbrown::HashMap;
use image::DynamicImage; use image::DynamicImage;
use log::{error, warn};
use std::{ use std::{
net::SocketAddr, net::SocketAddr,
sync::Arc, sync::Arc,
time::{Duration, Instant}, time::{Duration, Instant},
}; };
use tracing::{debug, error, warn};
use uvth::{ThreadPool, ThreadPoolBuilder}; use uvth::{ThreadPool, ThreadPoolBuilder};
use vek::*; use vek::*;
@ -117,7 +117,7 @@ impl Client {
} => { } => {
// TODO: Display that versions don't match in Voxygen // TODO: Display that versions don't match in Voxygen
if server_info.git_hash != common::util::GIT_HASH.to_string() { if server_info.git_hash != common::util::GIT_HASH.to_string() {
log::warn!( warn!(
"Server is running {}[{}], you are running {}[{}], versions might be \ "Server is running {}[{}], you are running {}[{}], versions might be \
incompatible!", incompatible!",
server_info.git_hash, 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` // Initialize `State`
let mut state = State::default(); let mut state = State::default();
@ -142,7 +142,7 @@ impl Client {
assert_eq!(world_map.len(), (map_size.x * map_size.y) as usize); 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*/]; 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); LittleEndian::write_u32_into(&world_map, &mut world_map_raw);
log::debug!("Preparing image..."); debug!("Preparing image...");
let world_map = Arc::new( let world_map = Arc::new(
image::DynamicImage::ImageRgba8({ image::DynamicImage::ImageRgba8({
// Should not fail if the dimensions are correct. // 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. // positive x axis to positive y axis is counterclockwise around the z axis.
.flipv(), .flipv(),
); );
log::debug!("Done preparing image..."); debug!("Done preparing image...");
(state, entity, server_info, (world_map, map_size)) (state, entity, server_info, (world_map, map_size))
}, },
@ -463,7 +463,7 @@ impl Client {
pub fn send_chat(&mut self, message: String) { pub fn send_chat(&mut self, message: String) {
match validate_chat_msg(&message) { match validate_chat_msg(&message) {
Ok(()) => self.postbox.send_message(ClientMsg::ChatMsg { 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)", "Attempted to send a message that's too long (Over {} bytes)",
MAX_BYTES_CHAT_MSG MAX_BYTES_CHAT_MSG
), ),
@ -691,7 +691,7 @@ impl Client {
/* /*
// Output debug metrics // 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 let metrics = self
.state .state
.terrain() .terrain()

View File

@ -20,7 +20,7 @@ serde_derive = "1.0"
serde_json = "1.0.41" serde_json = "1.0.41"
ron = { version = "0.6", default-features = false } ron = { version = "0.6", default-features = false }
bincode = "1.2.0" bincode = "1.2.0"
log = "0.4.8" tracing = { version = "0.1", default-features = false , features = ["attributes"] }
rand = "0.7" rand = "0.7"
rayon = "^1.3.0" rayon = "^1.3.0"
lazy_static = "1.4.0" lazy_static = "1.4.0"

View File

@ -5,7 +5,6 @@ use dot_vox::DotVoxData;
use hashbrown::HashMap; use hashbrown::HashMap;
use image::DynamicImage; use image::DynamicImage;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use log::error;
use serde_json::Value; use serde_json::Value;
use std::{ use std::{
any::Any, any::Any,
@ -15,6 +14,7 @@ use std::{
path::PathBuf, path::PathBuf,
sync::{Arc, RwLock}, sync::{Arc, RwLock},
}; };
use tracing::{debug, error, trace};
/// The error returned by asset loading functions /// The error returned by asset loading functions
#[derive(Debug, Clone)] #[derive(Debug, Clone)]

View File

@ -1,6 +1,5 @@
use crossbeam::channel::{select, unbounded, Receiver, Sender}; use crossbeam::channel::{select, unbounded, Receiver, Sender};
use lazy_static::lazy_static; use lazy_static::lazy_static;
use log::warn;
use notify::{Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher as _}; use notify::{Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher as _};
use std::{ use std::{
collections::HashMap, collections::HashMap,
@ -11,6 +10,7 @@ use std::{
}, },
thread, thread,
}; };
use tracing::{error, warn};
type Handler = Box<dyn Fn() + Send>; type Handler = Box<dyn Fn() + Send>;

View File

@ -1,6 +1,7 @@
use crate::{assets, comp, npc}; use crate::{assets, comp, npc};
use lazy_static::lazy_static; use lazy_static::lazy_static;
use std::{ops::Deref, path::Path, str::FromStr}; use std::{ops::Deref, path::Path, str::FromStr};
use tracing::warn;
/// Struct representing a command that a user can run from server chat. /// Struct representing a command that a user can run from server chat.
pub struct ChatCommandData { pub struct ChatCommandData {

View File

@ -1,6 +1,6 @@
use crate::{comp, comp::item}; use crate::{comp, comp::item};
use comp::{Inventory, Loadout}; use comp::{Inventory, Loadout};
use log::warn; use tracing::warn;
#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)] #[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
pub enum Slot { pub enum Slot {

View File

@ -60,10 +60,12 @@ impl ChunkPath {
} }
} }
//let neighbors: Vec<Vec2<i32>> = directions.into_iter().map(|dir| dir + pos).collect(); //let neighbors: Vec<Vec2<i32>> = directions.into_iter().map(|dir| dir +
// pos).collect();
neighbors.into_iter() neighbors.into_iter()
} }
pub fn worldpath_get_neighbors<V: RectRasterableVol + ReadVol + Debug>( pub fn worldpath_get_neighbors<V: RectRasterableVol + ReadVol + Debug>(
&mut self, &mut self,
vol: &VolGrid2d<V>, vol: &VolGrid2d<V>,
@ -95,6 +97,7 @@ impl ChunkPath {
.collect(); .collect();
neighbors.into_iter() neighbors.into_iter()
} }
pub fn is_valid_space<V: RectRasterableVol + ReadVol + Debug>( pub fn is_valid_space<V: RectRasterableVol + ReadVol + Debug>(
&mut self, &mut self,
vol: &VolGrid2d<V>, vol: &VolGrid2d<V>,
@ -107,13 +110,14 @@ impl ChunkPath {
is_within_chunk = chunk_path is_within_chunk = chunk_path
.iter() .iter()
.any(|new_pos| new_pos.cmpeq(&vol.pos_key(pos)).iter().all(|e| *e)); .any(|new_pos| new_pos.cmpeq(&vol.pos_key(pos)).iter().all(|e| *e));
} },
_ => { _ => {
//println!("No chunk path"); //println!("No chunk path");
} },
} }
return is_walkable_position && is_within_chunk; return is_walkable_position && is_within_chunk;
} }
pub fn get_worldpath<V: RectRasterableVol + ReadVol + Debug>( pub fn get_worldpath<V: RectRasterableVol + ReadVol + Debug>(
&mut self, &mut self,
vol: &VolGrid2d<V>, vol: &VolGrid2d<V>,
@ -132,6 +136,4 @@ pub fn chunk_euclidean_distance(start: &Vec2<i32>, end: &Vec2<i32>) -> f32 {
istart.distance(iend) istart.distance(iend)
} }
pub fn chunk_transition_cost(_start: &Vec2<i32>, _end: &Vec2<i32>) -> f32 { pub fn chunk_transition_cost(_start: &Vec2<i32>, _end: &Vec2<i32>) -> f32 { 1.0f32 }
1.0f32
}

View File

@ -11,7 +11,6 @@
)] )]
#[macro_use] extern crate serde_derive; #[macro_use] extern crate serde_derive;
#[macro_use] extern crate log;
pub mod assets; pub mod assets;
pub mod astar; pub mod astar;

View File

@ -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 bincode;
use middleman::Middleman; 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)] #[derive(Clone, Debug, PartialEq)]
pub enum Error { pub enum Error {
@ -34,27 +26,19 @@ pub enum Error {
} }
impl From<io::Error> for Error { impl From<io::Error> for Error {
fn from(err: io::Error) -> Self { fn from(err: io::Error) -> Self { Error::Network }
Error::Network
}
} }
impl From<TryRecvError> for Error { impl From<TryRecvError> for Error {
fn from(err: TryRecvError) -> Self { fn from(err: TryRecvError) -> Self { Error::Internal }
Error::Internal
}
} }
impl From<bincode::ErrorKind> for Error { impl From<bincode::ErrorKind> for Error {
fn from(err: bincode::ErrorKind) -> Self { fn from(err: bincode::ErrorKind) -> Self { Error::InvalidMsg }
Error::InvalidMsg
}
} }
impl<T> From<mio_extras::channel::SendError<T>> for Error { impl<T> From<mio_extras::channel::SendError<T>> for Error {
fn from(err: mio_extras::channel::SendError<T>) -> Self { fn from(err: mio_extras::channel::SendError<T>) -> Self { Error::Internal }
Error::Internal
}
} }
pub trait PostSend = 'static + serde::Serialize + Send + middleman::Message; pub trait PostSend = 'static + serde::Serialize + Send + middleman::Message;
@ -95,12 +79,8 @@ impl<S: PostSend, R: PostRecv> PostOffice<S, R> {
let office_poll = Poll::new()?; let office_poll = Poll::new()?;
office_poll.register(&postbox_rx, POSTBOX_TOK, Ready::readable(), PollOpt::edge())?; office_poll.register(&postbox_rx, POSTBOX_TOK, Ready::readable(), PollOpt::edge())?;
let worker = thread::spawn(move || office_worker( let worker =
worker_poll, thread::spawn(move || office_worker(worker_poll, tcp_listener, ctrl_rx, postbox_tx));
tcp_listener,
ctrl_rx,
postbox_tx,
));
Ok(Self { Ok(Self {
worker: Some(worker), worker: Some(worker),
@ -111,9 +91,7 @@ impl<S: PostSend, R: PostRecv> PostOffice<S, R> {
}) })
} }
pub fn error(&self) -> Option<Error> { pub fn error(&self) -> Option<Error> { self.err.clone() }
self.err.clone()
}
pub fn new_connections(&mut self) -> impl ExactSizeIterator<Item = PostBox<S, R>> { pub fn new_connections(&mut self) -> impl ExactSizeIterator<Item = PostBox<S, R>> {
let mut conns = VecDeque::new(); let mut conns = VecDeque::new();
@ -123,10 +101,7 @@ impl<S: PostSend, R: PostRecv> PostOffice<S, R> {
} }
let mut events = Events::with_capacity(64); let mut events = Events::with_capacity(64);
if let Err(err) = self.poll.poll( if let Err(err) = self.poll.poll(&mut events, Some(Duration::new(0, 0))) {
&mut events,
Some(Duration::new(0, 0)),
) {
self.err = Some(err.into()); self.err = Some(err.into());
return conns.into_iter(); return conns.into_iter();
} }
@ -188,12 +163,10 @@ fn office_worker<S: PostSend, R: PostRecv>(
}, },
} }
}, },
TCP_TOK => postbox_tx.send( TCP_TOK => postbox_tx.send(match tcp_listener.accept() {
match tcp_listener.accept() {
Ok((stream, _)) => PostBox::from_tcpstream(stream), Ok((stream, _)) => PostBox::from_tcpstream(stream),
Err(err) => Err(err.into()), Err(err) => Err(err.into()),
} })?,
)?,
tok => panic!("Unexpected event token '{:?}'", tok), tok => panic!("Unexpected event token '{:?}'", tok),
} }
} }
@ -211,7 +184,9 @@ pub struct PostBox<S: PostSend, R: PostRecv> {
impl<S: PostSend, R: PostRecv> PostBox<S, R> { impl<S: PostSend, R: PostRecv> PostBox<S, R> {
pub fn to_server<A: Into<SocketAddr>>(addr: A) -> Result<Self, Error> { pub fn to_server<A: Into<SocketAddr>>(addr: A) -> Result<Self, Error> {
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<Self, Error> { fn from_tcpstream(tcp_stream: TcpStream) -> Result<Self, Error> {
@ -220,20 +195,21 @@ impl<S: PostSend, R: PostRecv> PostBox<S, R> {
let (recv_tx, recv_rx) = channel(); let (recv_tx, recv_rx) = channel();
let worker_poll = Poll::new()?; 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(&ctrl_rx, CTRL_TOK, Ready::readable(), PollOpt::edge())?;
worker_poll.register(&send_rx, SEND_TOK, Ready::readable(), PollOpt::edge())?; worker_poll.register(&send_rx, SEND_TOK, Ready::readable(), PollOpt::edge())?;
let postbox_poll = Poll::new()?; let postbox_poll = Poll::new()?;
postbox_poll.register(&recv_rx, RECV_TOK, Ready::readable(), PollOpt::edge())?; postbox_poll.register(&recv_rx, RECV_TOK, Ready::readable(), PollOpt::edge())?;
let worker = thread::spawn(move || postbox_worker( let worker = thread::spawn(move || {
worker_poll, postbox_worker(worker_poll, tcp_stream, ctrl_rx, send_rx, recv_tx)
tcp_stream, });
ctrl_rx,
send_rx,
recv_tx,
));
Ok(Self { Ok(Self {
worker: Some(worker), worker: Some(worker),
@ -245,13 +221,9 @@ impl<S: PostSend, R: PostRecv> PostBox<S, R> {
}) })
} }
pub fn error(&self) -> Option<Error> { pub fn error(&self) -> Option<Error> { self.err.clone() }
self.err.clone()
}
pub fn send(&mut self, data: S) { pub fn send(&mut self, data: S) { let _ = self.send_tx.send(data); }
let _ = self.send_tx.send(data);
}
// TODO: This method is super messy. // TODO: This method is super messy.
pub fn next_message(&mut self) -> Option<R> { pub fn next_message(&mut self) -> Option<R> {
@ -261,10 +233,7 @@ impl<S: PostSend, R: PostRecv> PostBox<S, R> {
loop { loop {
let mut events = Events::with_capacity(10); let mut events = Events::with_capacity(10);
if let Err(err) = self.poll.poll( if let Err(err) = self.poll.poll(&mut events, Some(Duration::new(0, 0))) {
&mut events,
Some(Duration::new(0, 0)),
) {
self.err = Some(err.into()); self.err = Some(err.into());
return None; return None;
} }
@ -300,10 +269,7 @@ impl<S: PostSend, R: PostRecv> PostBox<S, R> {
} }
let mut events = Events::with_capacity(64); let mut events = Events::with_capacity(64);
if let Err(err) = self.poll.poll( if let Err(err) = self.poll.poll(&mut events, Some(Duration::new(0, 0))) {
&mut events,
Some(Duration::new(0, 0)),
) {
self.err = Some(err.into()); self.err = Some(err.into());
return msgs.into_iter(); return msgs.into_iter();
} }
@ -347,7 +313,10 @@ fn postbox_worker<S: PostSend, R: PostRecv>(
send_rx: Receiver<S>, send_rx: Receiver<S>,
recv_tx: Sender<Result<R, Error>>, recv_tx: Sender<Result<R, Error>>,
) -> Result<(), Error> { ) -> Result<(), Error> {
fn try_tcp_send(tcp_stream: &mut TcpStream, chunks: &mut VecDeque<Vec<u8>>) -> Result<(), Error> { fn try_tcp_send(
tcp_stream: &mut TcpStream,
chunks: &mut VecDeque<Vec<u8>>,
) -> Result<(), Error> {
loop { loop {
let chunk = match chunks.pop_front() { let chunk = match chunks.pop_front() {
Some(chunk) => chunk, Some(chunk) => chunk,
@ -389,8 +358,7 @@ fn postbox_worker<S: PostSend, R: PostRecv>(
for event in &events { for event in &events {
match event.token() { match event.token() {
CTRL_TOK => CTRL_TOK => match ctrl_rx.try_recv() {
match ctrl_rx.try_recv() {
Ok(CtrlMsg::Shutdown) => { Ok(CtrlMsg::Shutdown) => {
break 'work; break 'work;
}, },
@ -411,11 +379,7 @@ fn postbox_worker<S: PostSend, R: PostRecv>(
}, },
}; };
let mut bytes = msg_bytes let mut bytes = msg_bytes.len().to_le_bytes().as_ref().to_vec();
.len()
.to_le_bytes()
.as_ref()
.to_vec();
bytes.append(&mut msg_bytes); bytes.append(&mut msg_bytes);
bytes bytes
@ -450,8 +414,11 @@ fn postbox_worker<S: PostSend, R: PostRecv>(
}, },
} }
match &mut recv_state { match &mut recv_state {
RecvState::ReadHead(head) => if head.len() == 8 { RecvState::ReadHead(head) => {
let len = usize::from_le_bytes(<[u8; 8]>::try_from(head.as_slice()).unwrap()); if head.len() == 8 {
let len = usize::from_le_bytes(
<[u8; 8]>::try_from(head.as_slice()).unwrap(),
);
if len > MAX_MSG_BYTES { if len > MAX_MSG_BYTES {
println!("TOO BIG! {:x}", len); println!("TOO BIG! {:x}", len);
recv_tx.send(Err(Error::InvalidMsg))?; recv_tx.send(Err(Error::InvalidMsg))?;
@ -460,10 +427,7 @@ fn postbox_worker<S: PostSend, R: PostRecv>(
recv_state = RecvState::ReadHead(Vec::with_capacity(8)); recv_state = RecvState::ReadHead(Vec::with_capacity(8));
break; break;
} else { } else {
recv_state = RecvState::ReadBody( recv_state = RecvState::ReadBody(len, Vec::new());
len,
Vec::new(),
);
} }
} else { } else {
let mut b = [0; 1]; let mut b = [0; 1];
@ -472,8 +436,10 @@ fn postbox_worker<S: PostSend, R: PostRecv>(
Ok(_) => head.push(b[0]), Ok(_) => head.push(b[0]),
Err(_) => break, Err(_) => break,
} }
}
}, },
RecvState::ReadBody(len, body) => if body.len() == *len { RecvState::ReadBody(len, body) => {
if body.len() == *len {
match bincode::deserialize(&body) { match bincode::deserialize(&body) {
Ok(msg) => { Ok(msg) => {
recv_tx.send(Ok(msg))?; recv_tx.send(Ok(msg))?;
@ -494,6 +460,7 @@ fn postbox_worker<S: PostSend, R: PostRecv>(
break 'work; break 'work;
}, },
} }
}
}, },
} }
} }

View File

@ -1,5 +1,4 @@
use crossbeam::channel; use crossbeam::channel;
use log::warn;
use serde::{de::DeserializeOwned, Serialize}; use serde::{de::DeserializeOwned, Serialize};
use std::{ use std::{
collections::VecDeque, collections::VecDeque,
@ -14,6 +13,7 @@ use std::{
thread, thread,
time::Duration, time::Duration,
}; };
use tracing::warn;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub enum Error { pub enum Error {

View File

@ -1,5 +1,4 @@
use super::{track::UpdateTracker, uid::Uid}; use super::{track::UpdateTracker, uid::Uid};
use log::error;
use serde::{de::DeserializeOwned, Deserialize, Serialize}; use serde::{de::DeserializeOwned, Deserialize, Serialize};
use specs::{Component, Entity, Join, ReadStorage, World, WorldExt}; use specs::{Component, Entity, Join, ReadStorage, World, WorldExt};
use std::{ use std::{
@ -7,6 +6,7 @@ use std::{
fmt::Debug, fmt::Debug,
marker::PhantomData, marker::PhantomData,
}; };
use tracing::error;
/// Implemented by type that carries component data for insertion and /// Implemented by type that carries component data for insertion and
/// modification The assocatied `Phantom` type only carries information about /// modification The assocatied `Phantom` type only carries information about

View File

@ -5,12 +5,12 @@ use super::{
track::UpdateTracker, track::UpdateTracker,
uid::{Uid, UidAllocator}, uid::{Uid, UidAllocator},
}; };
use log::error;
use specs::{ use specs::{
saveload::{MarkedBuilder, MarkerAllocator}, saveload::{MarkedBuilder, MarkerAllocator},
world::Builder, world::Builder,
WorldExt, WorldExt,
}; };
use tracing::error;
pub trait WorldSyncExt { pub trait WorldSyncExt {
fn register_sync_marker(&mut self); fn register_sync_marker(&mut self);

View File

@ -1,3 +1,4 @@
use tracing::warn;
use vek::*; use vek::*;
/// Type representing a direction using Vec3 that is normalized and NaN free /// Type representing a direction using Vec3 that is normalized and NaN free

View File

@ -12,5 +12,5 @@ default = ["worldgen"]
server = { package = "veloren-server", path = "../server", default-features = false } server = { package = "veloren-server", path = "../server", default-features = false }
common = { package = "veloren-common", path = "../common" } common = { package = "veloren-common", path = "../common" }
log = "0.4.8" tracing = { version = "0.1", default-features = false , features = ["attributes"] }
pretty_env_logger = "0.3.1" tracing-subscriber = { version = "0.2.3", default-features = false, features = ["fmt", "chrono", "ansi", "smallvec"] }

View File

@ -2,9 +2,9 @@
#![allow(clippy::option_map_unit_fn)] #![allow(clippy::option_map_unit_fn)]
use common::clock::Clock; use common::clock::Clock;
use log::info;
use server::{Event, Input, Server, ServerSettings}; use server::{Event, Input, Server, ServerSettings};
use std::time::Duration; use std::time::Duration;
use tracing::info;
const TPS: u64 = 30; const TPS: u64 = 30;
@ -14,7 +14,8 @@ fn main() {
if let Err(_) = std::env::var("RUST_LOG") { if let Err(_) = std::env::var("RUST_LOG") {
std::env::set_var("RUST_LOG", "info"); std::env::set_var("RUST_LOG", "info");
} }
pretty_env_logger::init();
tracing_subscriber::fmt::init();
info!("Starting server..."); info!("Starting server...");

View File

@ -14,7 +14,7 @@ world = { package = "veloren-world", path = "../world" }
specs-idvs = { git = "https://gitlab.com/veloren/specs-idvs.git" } 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"] } specs = { version = "0.15.1", features = ["shred-derive"] }
vek = "0.11.0" vek = "0.11.0"
uvth = "3.1.1" uvth = "3.1.1"

View File

@ -1,8 +1,8 @@
use authc::{AuthClient, AuthToken, Uuid}; use authc::{AuthClient, AuthToken, Uuid};
use common::msg::RegisterError; use common::msg::RegisterError;
use hashbrown::HashMap; use hashbrown::HashMap;
use log::error;
use std::str::FromStr; use std::str::FromStr;
use tracing::{error, info};
fn derive_uuid(username: &str) -> Uuid { fn derive_uuid(username: &str) -> Uuid {
let mut state = 144066263297769815596495629667062367629; let mut state = 144066263297769815596495629667062367629;
@ -45,7 +45,7 @@ impl AuthProvider {
match &self.auth_server { match &self.auth_server {
// Token from auth server expected // Token from auth server expected
Some(srv) => { Some(srv) => {
log::info!("Validating '{}' token.", &username_or_token); info!("Validating '{}' token.", &username_or_token);
// Parse token // Parse token
let token = AuthToken::from_str(&username_or_token) let token = AuthToken::from_str(&username_or_token)
.map_err(|e| RegisterError::AuthError(e.to_string()))?; .map_err(|e| RegisterError::AuthError(e.to_string()))?;
@ -66,7 +66,7 @@ impl AuthProvider {
let username = username_or_token; let username = username_or_token;
let uuid = derive_uuid(&username); let uuid = derive_uuid(&username);
if !self.accounts.contains_key(&uuid) { if !self.accounts.contains_key(&uuid) {
log::info!("New User '{}'", username); info!("New User '{}'", username);
self.accounts.insert(uuid, username.clone()); self.accounts.insert(uuid, username.clone());
Ok((username, uuid)) Ok((username, uuid))
} else { } else {

View File

@ -22,8 +22,8 @@ use specs::{Builder, Entity as EcsEntity, Join, WorldExt};
use vek::*; use vek::*;
use world::util::Sampler; use world::util::Sampler;
use log::error;
use scan_fmt::{scan_fmt, scan_fmt_some}; use scan_fmt::{scan_fmt, scan_fmt_some};
use tracing::error;
pub trait ChatCommandExt { pub trait ChatCommandExt {
fn execute(&self, server: &mut Server, entity: EcsEntity, args: String); fn execute(&self, server: &mut Server, entity: EcsEntity, args: String);

View File

@ -9,9 +9,9 @@ use common::{
terrain::{Block, TerrainGrid}, terrain::{Block, TerrainGrid},
vol::{ReadVol, Vox}, vol::{ReadVol, Vox},
}; };
use log::error;
use rand::seq::SliceRandom; use rand::seq::SliceRandom;
use specs::{join::Join, Entity as EcsEntity, WorldExt}; use specs::{join::Join, Entity as EcsEntity, WorldExt};
use tracing::error;
use vek::Vec3; use vek::Vec3;
pub fn handle_damage(server: &Server, uid: Uid, change: HealthChange) { pub fn handle_damage(server: &Server, uid: Uid, change: HealthChange) {

View File

@ -8,8 +8,8 @@ use common::{
msg::ServerMsg, msg::ServerMsg,
sync::{Uid, WorldSyncExt}, sync::{Uid, WorldSyncExt},
}; };
use log::error;
use specs::{world::WorldExt, Entity as EcsEntity}; use specs::{world::WorldExt, Entity as EcsEntity};
use tracing::error;
pub fn handle_lantern(server: &mut Server, entity: EcsEntity) { pub fn handle_lantern(server: &mut Server, entity: EcsEntity) {
let ecs = server.state_mut().ecs(); let ecs = server.state_mut().ecs();

View File

@ -9,9 +9,9 @@ use common::{
terrain::block::Block, terrain::block::Block,
vol::{ReadVol, Vox}, vol::{ReadVol, Vox},
}; };
use log::error;
use rand::Rng; use rand::Rng;
use specs::{join::Join, world::WorldExt, Builder, Entity as EcsEntity, WriteStorage}; use specs::{join::Join, world::WorldExt, Builder, Entity as EcsEntity, WriteStorage};
use tracing::error;
use vek::Vec3; use vek::Vec3;
pub fn swap_lantern( pub fn swap_lantern(

View File

@ -8,8 +8,8 @@ use common::{
msg::{ClientState, PlayerListUpdate, ServerMsg}, msg::{ClientState, PlayerListUpdate, ServerMsg},
sync::{Uid, UidAllocator}, sync::{Uid, UidAllocator},
}; };
use log::error;
use specs::{saveload::MarkerAllocator, Builder, Entity as EcsEntity, Join, WorldExt}; use specs::{saveload::MarkerAllocator, Builder, Entity as EcsEntity, Join, WorldExt};
use tracing::error;
pub fn handle_exit_ingame(server: &mut Server, entity: EcsEntity) { pub fn handle_exit_ingame(server: &mut Server, entity: EcsEntity) {
let state = server.state_mut(); let state = server.state_mut();

View File

@ -38,7 +38,6 @@ use common::{
terrain::TerrainChunkSize, terrain::TerrainChunkSize,
vol::{ReadVol, RectVolSize}, vol::{ReadVol, RectVolSize},
}; };
use log::{debug, error};
use metrics::{ServerMetrics, TickMetrics}; use metrics::{ServerMetrics, TickMetrics};
use specs::{join::Join, Builder, Entity as EcsEntity, RunNow, SystemData, WorldExt}; use specs::{join::Join, Builder, Entity as EcsEntity, RunNow, SystemData, WorldExt};
use std::{ use std::{
@ -48,6 +47,7 @@ use std::{
}; };
#[cfg(not(feature = "worldgen"))] #[cfg(not(feature = "worldgen"))]
use test_world::{World, WORLD_SIZE}; use test_world::{World, WORLD_SIZE};
use tracing::{debug, error, info};
use uvth::{ThreadPool, ThreadPoolBuilder}; use uvth::{ThreadPool, ThreadPoolBuilder};
use vek::*; use vek::*;
#[cfg(feature = "worldgen")] #[cfg(feature = "worldgen")]
@ -256,12 +256,12 @@ impl Server {
if let Some(error) = if let Some(error) =
persistence::run_migrations(&this.server_settings.persistence_db_dir).err() 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); debug!("created veloren server with: {:?}", &settings);
log::info!( info!(
"Server version: {}[{}]", "Server version: {}[{}]",
*common::util::GIT_HASH, *common::util::GIT_HASH,
*common::util::GIT_DATE *common::util::GIT_DATE
@ -536,7 +536,7 @@ impl Server {
.build(); .build();
// Send client all the tracked components currently attached to its entity as // Send client all the tracked components currently attached to its entity as
// well as synced resources (currently only `TimeOfDay`) // well as synced resources (currently only `TimeOfDay`)
log::debug!("Starting initial sync with client."); debug!("Starting initial sync with client.");
self.state self.state
.ecs() .ecs()
.write_storage::<Client>() .write_storage::<Client>()
@ -550,7 +550,7 @@ impl Server {
time_of_day: *self.state.ecs().read_resource(), time_of_day: *self.state.ecs().read_resource(),
world_map: (WORLD_SIZE.map(|e| e as u32), self.map.clone()), 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 }); frontend_events.push(Event::ClientConnected { entity });
} }

View File

@ -1,4 +1,3 @@
use log::{debug, error};
use prometheus::{Encoder, Gauge, IntGauge, IntGaugeVec, Opts, Registry, TextEncoder}; use prometheus::{Encoder, Gauge, IntGauge, IntGaugeVec, Opts, Registry, TextEncoder};
use std::{ use std::{
convert::TryInto, convert::TryInto,
@ -11,6 +10,7 @@ use std::{
thread, thread,
time::{Duration, SystemTime, UNIX_EPOCH}, time::{Duration, SystemTime, UNIX_EPOCH},
}; };
use tracing::{debug, error};
pub struct TickMetrics { pub struct TickMetrics {
pub chonks_count: IntGauge, pub chonks_count: IntGauge,

View File

@ -16,6 +16,7 @@ use common::{
}; };
use crossbeam::channel; use crossbeam::channel;
use diesel::prelude::*; use diesel::prelude::*;
use tracing::{error, warn};
type CharacterListResult = Result<Vec<CharacterItem>, Error>; type CharacterListResult = Result<Vec<CharacterItem>, Error>;
@ -54,10 +55,9 @@ pub fn load_character_data(
.values(&row) .values(&row)
.execute(&connection) .execute(&connection)
{ {
log::warn!( warn!(
"Failed to create an inventory record for character {}: {}", "Failed to create an inventory record for character {}: {}",
&character_data.id, &character_data.id, error
error
) )
} }
@ -81,10 +81,9 @@ pub fn load_character_data(
.values(&row) .values(&row)
.execute(&connection) .execute(&connection)
{ {
log::warn!( warn!(
"Failed to create an loadout record for character {}: {}", "Failed to create an loadout record for character {}: {}",
&character_data.id, &character_data.id, error
error
) )
} }
@ -232,7 +231,7 @@ pub fn create_character(
.values(&new_loadout) .values(&new_loadout)
.execute(&connection)?; .execute(&connection)?;
}, },
_ => log::warn!("Creating non-humanoid characters is not supported."), _ => warn!("Creating non-humanoid characters is not supported."),
}; };
Ok(()) Ok(())
@ -316,7 +315,7 @@ impl CharacterUpdater {
.collect(); .collect();
if let Err(err) = self.update_tx.as_ref().unwrap().send(updates) { 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<Item = (i32, CharacterUpdateData)>, db_di
Ok(()) 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) .set(stats)
.execute(connection) .execute(connection)
{ {
log::warn!( warn!(
"Failed to update stats for character: {:?}: {:?}", "Failed to update stats for character: {:?}: {:?}",
character_id, character_id, error
error
) )
} }
@ -378,10 +376,9 @@ fn update(
.set(inventory) .set(inventory)
.execute(connection) .execute(connection)
{ {
log::warn!( warn!(
"Failed to update inventory for character: {:?}: {:?}", "Failed to update inventory for character: {:?}: {:?}",
character_id, character_id, error
error
) )
} }
@ -391,10 +388,9 @@ fn update(
.set(loadout) .set(loadout)
.execute(connection) .execute(connection)
{ {
log::warn!( warn!(
"Failed to update loadout for character: {:?}: {:?}", "Failed to update loadout for character: {:?}: {:?}",
character_id, character_id, error
error
) )
} }
} }
@ -403,7 +399,7 @@ impl Drop for CharacterUpdater {
fn drop(&mut self) { fn drop(&mut self) {
drop(self.update_tx.take()); drop(self.update_tx.take());
if let Err(err) = self.handle.take().unwrap().join() { 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);
} }
} }
} }

View File

@ -9,6 +9,7 @@ extern crate diesel;
use diesel::{connection::SimpleConnection, prelude::*}; use diesel::{connection::SimpleConnection, prelude::*};
use diesel_migrations::embed_migrations; use diesel_migrations::embed_migrations;
use std::{env, fs, path::PathBuf}; use std::{env, fs, path::PathBuf};
use tracing::warn;
// See: https://docs.rs/diesel_migrations/1.4.0/diesel_migrations/macro.embed_migrations.html // 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 // 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; PRAGMA busy_timeout = 250;
", ",
) { ) {
log::warn!( warn!(
"Failed adding PRAGMA statements while establishing sqlite connection, this will \ "Failed adding PRAGMA statements while establishing sqlite connection, this will \
result in a higher likelihood of locking errors: {}", result in a higher likelihood of locking errors: {}",
error error
@ -57,7 +58,7 @@ fn apply_saves_dir_override(db_dir: &str) -> String {
None => {}, None => {},
} }
} }
log::warn!("VELOREN_SAVES_DIR points to an invalid path."); warn!("VELOREN_SAVES_DIR points to an invalid path.");
} }
db_dir.to_string() db_dir.to_string()
} }

View File

@ -5,6 +5,7 @@ use crate::comp;
use common::{character::Character as CharacterData, LoadoutBuilder}; use common::{character::Character as CharacterData, LoadoutBuilder};
use diesel::sql_types::Text; use diesel::sql_types::Text;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tracing::warn;
/// The required elements to build comp::Stats from database data /// The required elements to build comp::Stats from database data
pub struct StatsJoinData<'a> { pub struct StatsJoinData<'a> {
@ -173,7 +174,7 @@ where
match serde_json::from_str(&t) { match serde_json::from_str(&t) {
Ok(data) => Ok(Self(data)), Ok(data) => Ok(Self(data)),
Err(error) => { Err(error) => {
log::warn!("Failed to deserialise inventory data: {}", error); warn!("Failed to deserialise inventory data: {}", error);
Ok(Self(comp::Inventory::default())) Ok(Self(comp::Inventory::default()))
}, },
} }
@ -259,7 +260,7 @@ where
match serde_json::from_str(&t) { match serde_json::from_str(&t) {
Ok(data) => Ok(Self(data)), Ok(data) => Ok(Self(data)),
Err(error) => { 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 // We don't have a weapon reference here, so we default to sword
let loadout = LoadoutBuilder::new() let loadout = LoadoutBuilder::new()

View File

@ -1,6 +1,7 @@
use portpicker::pick_unused_port; use portpicker::pick_unused_port;
use serde_derive::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize};
use std::{fs, io::prelude::*, net::SocketAddr, path::PathBuf}; use std::{fs, io::prelude::*, net::SocketAddr, path::PathBuf};
use tracing::{error, warn};
use world::sim::FileOpts; use world::sim::FileOpts;
const DEFAULT_WORLD_SEED: u32 = 59686; const DEFAULT_WORLD_SEED: u32 = 59686;
@ -71,7 +72,7 @@ impl ServerSettings {
match ron::de::from_reader(file) { match ron::de::from_reader(file) {
Ok(x) => x, Ok(x) => x,
Err(e) => { 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() Self::default()
}, },
} }
@ -79,7 +80,7 @@ impl ServerSettings {
let default_settings = Self::default(); let default_settings = Self::default();
match default_settings.save_to_file() { 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 default_settings

View File

@ -12,8 +12,8 @@ use common::{
sync::{Uid, WorldSyncExt}, sync::{Uid, WorldSyncExt},
util::Dir, util::Dir,
}; };
use log::warn;
use specs::{Builder, Entity as EcsEntity, EntityBuilder as EcsEntityBuilder, Join, WorldExt}; use specs::{Builder, Entity as EcsEntity, EntityBuilder as EcsEntityBuilder, Join, WorldExt};
use tracing::warn;
use vek::*; use vek::*;
pub trait StateExt { pub trait StateExt {
@ -173,7 +173,7 @@ impl StateExt for State {
self.write_component(entity, loadout); self.write_component(entity, loadout);
}, },
Err(error) => { Err(error) => {
log::warn!( warn!(
"{}", "{}",
format!( format!(
"Failed to load character data for character_id {}: {}", "Failed to load character data for character_id {}: {}",

View File

@ -22,6 +22,7 @@ use hashbrown::HashMap;
use specs::{ use specs::{
Entities, Join, Read, ReadExpect, ReadStorage, System, Write, WriteExpect, WriteStorage, Entities, Join, Read, ReadExpect, ReadStorage, System, Write, WriteExpect, WriteStorage,
}; };
use tracing::warn;
/// This system will handle new messages from clients /// This system will handle new messages from clients
pub struct Sys; pub struct Sys;
@ -274,7 +275,7 @@ impl<'a> System<'a> for Sys {
| ClientState::Spectator | ClientState::Spectator
| ClientState::Character => match validate_chat_msg(&message) { | ClientState::Character => match validate_chat_msg(&message) {
Ok(()) => new_chat_msgs.push((Some(entity), ServerMsg::chat(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:{})", "Recieved a chat message that's too long (max:{} len:{})",
MAX_BYTES_CHAT_MSG, MAX_BYTES_CHAT_MSG,
message.len() message.len()

View File

@ -11,11 +11,11 @@ use common::{
terrain::TerrainChunkSize, terrain::TerrainChunkSize,
vol::RectVolSize, vol::RectVolSize,
}; };
use log::{debug, error};
use specs::{ use specs::{
Entities, Join, ReadExpect, ReadStorage, System, SystemData, World, WorldExt, Write, Entities, Join, ReadExpect, ReadStorage, System, SystemData, World, WorldExt, Write,
WriteStorage, WriteStorage,
}; };
use tracing::{debug, error};
use vek::*; use vek::*;
/// This system will update region subscriptions based on client positions /// This system will update region subscriptions based on client positions

View File

@ -71,10 +71,7 @@ uvth = "3.1.1"
authc = { git = "https://gitlab.com/veloren/auth.git", rev = "223a4097f7ebc8d451936dccb5e6517194bbf086" } authc = { git = "https://gitlab.com/veloren/auth.git", rev = "223a4097f7ebc8d451936dccb5e6517194bbf086" }
const-tweaker = { version = "0.2.5", optional = true } const-tweaker = { version = "0.2.5", optional = true }
# # Logging # Logging
# log = "0.4.8"
# fern = { version = "0.5.8", features = ["colored"] }
# Logging (new)
tracing = { version = "0.1", default-features = false , features = ["attributes"] } 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-subscriber = { version = "0.2.3", default-features = false, features = ["env-filter", "fmt", "chrono", "ansi", "smallvec", "registry", "tracing-log"] }
tracing-log = "0.1.1" tracing-log = "0.1.1"

View File

@ -17,7 +17,7 @@ num = "0.2.0"
ordered-float = "1.0" ordered-float = "1.0"
hashbrown = { version = "0.6", features = ["rayon", "serde", "nightly"] } hashbrown = { version = "0.6", features = ["rayon", "serde", "nightly"] }
lazy_static = "1.4.0" lazy_static = "1.4.0"
log = "0.4.8" tracing = { version = "0.1", default-features = false , features = ["attributes"] }
rand = "0.7" rand = "0.7"
rand_chacha = "0.2.1" rand_chacha = "0.2.1"
arr_macro = "0.1.2" arr_macro = "0.1.2"
@ -29,5 +29,5 @@ serde_derive = "1.0"
ron = { version = "0.6", default-features = false } ron = { version = "0.6", default-features = false }
[dev-dependencies] [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" minifb = "0.14.0"

View File

@ -1,5 +1,7 @@
use common::{terrain::TerrainChunkSize, vol::RectVolSize}; use common::{terrain::TerrainChunkSize, vol::RectVolSize};
use std::{f64, io::Write, path::PathBuf, time::SystemTime}; use std::{f64, io::Write, path::PathBuf, time::SystemTime};
use tracing::warn;
use tracing_subscriber;
use vek::*; use vek::*;
use veloren_world::{ use veloren_world::{
sim::{self, MapConfig, MapDebug, WorldOpts, WORLD_SIZE}, 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::needless_update)] // TODO: Pending review in #587
#[allow(clippy::unused_io_amount)] // TODO: Pending review in #587 #[allow(clippy::unused_io_amount)] // TODO: Pending review in #587
fn main() { 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 // 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 // (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"); let mut path = PathBuf::from("./screenshots");
if !path.exists() { if !path.exists() {
if let Err(err) = std::fs::create_dir(&path) { 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!( path.push(format!(
@ -124,7 +126,7 @@ fn main() {
.unwrap_or(0) .unwrap_or(0)
)); ));
if let Err(err) = world_map.save(&path) { if let Err(err) = world_map.save(&path) {
log::warn!("Couldn't save screenshot: {:?}", err); warn!("Couldn't save screenshot: {:?}", err);
} }
} }
} }

View File

@ -25,6 +25,7 @@ use fxhash::{FxHasher32, FxHasher64};
use hashbrown::{HashMap, HashSet}; use hashbrown::{HashMap, HashSet};
use rand::prelude::*; use rand::prelude::*;
use rand_chacha::ChaChaRng; use rand_chacha::ChaChaRng;
use tracing::{info, warn};
use vek::*; use vek::*;
const INITIAL_CIV_COUNT: usize = (crate::sim::WORLD_SIZE.x * crate::sim::WORLD_SIZE.y * 3) / 65536; //48 at default scale 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 }; let mut ctx = GenCtx { sim, rng };
for _ in 0..INITIAL_CIV_COUNT { for _ in 0..INITIAL_CIV_COUNT {
log::info!("Creating civilisation..."); info!("Creating civilisation...");
if this.birth_civ(&mut ctx.reseed()).is_none() { 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) .get_mut(pos)
.map(|chunk| chunk.sites.push(world_site.clone())); .map(|chunk| chunk.sites.push(world_site.clone()));
} }
log::info!("Placed site at {:?}", site.center); info!("Placed site at {:?}", site.center);
} }
//this.display_info(); //this.display_info();

View File

@ -13,6 +13,7 @@ use std::{
f32, f64, f32, f64,
ops::{Add, Div, Mul, Neg, Sub}, ops::{Add, Div, Mul, Neg, Sub},
}; };
use tracing::error;
use vek::*; use vek::*;
pub struct ColumnGen<'a> { pub struct ColumnGen<'a> {
@ -213,7 +214,7 @@ impl<'a> Sampler<'a> for ColumnGen<'a> {
} else { } else {
match kind { match kind {
RiverKind::River { .. } => { RiverKind::River { .. } => {
log::error!("What? River: {:?}, Pos: {:?}", river, posj); error!("What? River: {:?}, Pos: {:?}", river, posj);
panic!("How can a river have no downhill?"); panic!("How can a river have no downhill?");
}, },
RiverKind::Lake { .. } => { RiverKind::Lake { .. } => {
@ -617,11 +618,9 @@ impl<'a> Sampler<'a> for ColumnGen<'a> {
) = if let Some(dist) = max_border_river_dist { ) = if let Some(dist) = max_border_river_dist {
dist dist
} else { } else {
log::error!( error!(
"Ocean: {:?} Here: {:?}, Ocean: {:?}", "Ocean: {:?} Here: {:?}, Ocean: {:?}",
max_border_river, max_border_river, chunk_pos, max_border_river_pos
chunk_pos,
max_border_river_pos
); );
panic!( panic!(
"Oceans should definitely have a downhill! \ "Oceans should definitely have a downhill! \

View File

@ -4,6 +4,7 @@ use super::{
}; };
use crate::{config::CONFIG, util::RandomField}; use crate::{config::CONFIG, util::RandomField};
use common::{terrain::TerrainChunkSize, vol::RectVolSize}; use common::{terrain::TerrainChunkSize, vol::RectVolSize};
use tracing::{debug, error, warn};
// use faster::*; // use faster::*;
use itertools::izip; use itertools::izip;
use noise::{NoiseFn, Point3}; use noise::{NoiseFn, Point3};
@ -427,7 +428,7 @@ pub fn get_rivers<F: fmt::Debug + Float + Into<f64>, G: Float + Into<f64>>(
if slope == 0.0 { if slope == 0.0 {
// This is not a river--how did this even happen? // This is not a river--how did this even happen?
let pass_idx = (-indirection_idx) as usize; let pass_idx = (-indirection_idx) as usize;
log::error!( error!(
"Our chunk (and downhill, lake, pass, neighbor_pass): {:?} (to {:?}, in {:?} via \ "Our chunk (and downhill, lake, pass, neighbor_pass): {:?} (to {:?}, in {:?} via \
{:?} to {:?}), chunk water alt: {:?}, lake water alt: {:?}", {:?} to {:?}), chunk water alt: {:?}, lake water alt: {:?}",
uniform_idx_as_vec2(chunk_idx), uniform_idx_as_vec2(chunk_idx),
@ -715,7 +716,7 @@ fn erode(
k_da_scale: impl Fn(f64) -> f64, k_da_scale: impl Fn(f64) -> f64,
) { ) {
let compute_stats = true; let compute_stats = true;
log::debug!("Done draining..."); debug!("Done draining...");
// NOTE: To experimentally allow erosion to proceed below sea level, replace 0.0 // NOTE: To experimentally allow erosion to proceed below sea level, replace 0.0
// with -<Alt as Float>::infinity(). // with -<Alt as Float>::infinity().
let min_erosion_height = 0.0; // -<Alt as Float>::infinity(); let min_erosion_height = 0.0; // -<Alt as Float>::infinity();
@ -723,7 +724,7 @@ fn erode(
// NOTE: The value being divided by here sets the effective maximum uplift rate, // NOTE: The value being divided by here sets the effective maximum uplift rate,
// as everything is scaled to it! // as everything is scaled to it!
let dt = max_uplift as f64 / 1e-3; 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. // Minimum sediment thickness before we treat erosion as sediment based.
let sediment_thickness = |_n| /*6.25e-5*/1.0e-4 * dt; let sediment_thickness = |_n| /*6.25e-5*/1.0e-4 * dt;
let neighbor_coef = TerrainChunkSize::RECT_SIZE.map(|e| e as f64); 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 ((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); 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); 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( let (mrec, mstack, mwrec) = get_multi_rec(
|posi| h[posi], |posi| h[posi],
&dh, &dh,
@ -815,12 +816,12 @@ fn erode(
dy as Compute, dy as Compute,
maxh, maxh,
); );
log::debug!("Got multiple receivers..."); debug!("Got multiple receivers...");
// TODO: Figure out how to switch between single-receiver and multi-receiver // TODO: Figure out how to switch between single-receiver and multi-receiver
// drainage, as the former is much less computationally costly. // drainage, as the former is much less computationally costly.
// let area = get_drainage(&newh, &dh, boundary_len); // let area = get_drainage(&newh, &dh, boundary_len);
let area = get_multi_drainage(&mstack, &mrec, &*mwrec, 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) (dh, newh, maxh, mrec, mstack, mwrec, area)
}, },
|| { || {
@ -828,7 +829,7 @@ fn erode(
|| { || {
let max_slope = let max_slope =
get_max_slope(h, rock_strength_nz, |posi| height_scale(n_f(posi))); get_max_slope(h, rock_strength_nz, |posi| height_scale(n_f(posi)));
log::debug!("Got max slopes..."); debug!("Got max slopes...");
max_slope max_slope
}, },
|| h.to_vec().into_boxed_slice(), || 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 = let mut lake_water_volume =
vec![0.0 as Compute; WORLD_SIZE.x * WORLD_SIZE.y].into_boxed_slice(); 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 { 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. // Reset statistics in each loop.
maxh = 0.0; maxh = 0.0;
@ -1096,7 +1097,7 @@ fn erode(
}); });
}, },
); );
log::debug!( debug!(
"(Done precomputation, time={:?}ms).", "(Done precomputation, time={:?}ms).",
start_time.elapsed().as_millis() start_time.elapsed().as_millis()
); );
@ -1131,7 +1132,7 @@ fn erode(
}); });
} }
}); });
log::debug!( debug!(
"(Done sediment transport computation, time={:?}ms).", "(Done sediment transport computation, time={:?}ms).",
start_time.elapsed().as_millis() start_time.elapsed().as_millis()
); );
@ -1206,7 +1207,7 @@ fn erode(
} }
}, },
); );
log::debug!( debug!(
"(Done elevation estimation, time={:?}ms).", "(Done elevation estimation, time={:?}ms).",
start_time.elapsed().as_millis() start_time.elapsed().as_millis()
); );
@ -1232,7 +1233,7 @@ fn erode(
panic!("Disconnected lake!"); panic!("Disconnected lake!");
} }
if h_t_i > 0.0 { if h_t_i > 0.0 {
log::warn!("Ocean above zero?"); warn!("Ocean above zero?");
} }
// Egress with no outgoing flows. // Egress with no outgoing flows.
// wh for oceans is always at least min_erosion_height. // wh for oceans is always at least min_erosion_height.
@ -1427,21 +1428,20 @@ fn erode(
sum_err += sum_err +=
(iteration_error + h_stack[stacki] as Compute - h_p_i as Compute).powi(2); (iteration_error + h_stack[stacki] as Compute - h_p_i as Compute).powi(2);
}); });
log::debug!( debug!(
"(Done erosion computation, time={:?}ms)", "(Done erosion computation, time={:?}ms)",
start_time.elapsed().as_millis() start_time.elapsed().as_millis()
); );
err = (sum_err / mstack.len() as Compute).sqrt(); err = (sum_err / mstack.len() as Compute).sqrt();
log::debug!("(RMSE: {:?})", err); debug!("(RMSE: {:?})", err);
if max_g == 0.0 { if max_g == 0.0 {
err = 0.0; err = 0.0;
} }
if n_gs_stream_power_law == max_n_gs_stream_power_law { if n_gs_stream_power_law == max_n_gs_stream_power_law {
log::warn!( warn!(
"Beware: Gauss-Siedel scheme not convergent: err={:?}, expected={:?}", "Beware: Gauss-Siedel scheme not convergent: err={:?}, expected={:?}",
err, err, tol
tol
); );
} }
} }
@ -1507,7 +1507,7 @@ fn erode(
new_b_i = new_b_i.min(h_i); new_b_i = new_b_i.min(h_i);
*b = new_b_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. // update the height to reflect sediment flux.
if max_g > 0.0 { if max_g > 0.0 {
@ -1541,7 +1541,7 @@ fn erode(
// endif // endif
// enddo // enddo
log::debug!( debug!(
"Done applying stream power (max height: {:?}) (avg height: {:?}) (min height: {:?}) (avg \ "Done applying stream power (max height: {:?}) (avg height: {:?}) (min height: {:?}) (avg \
slope: {:?})\n (above talus angle, geom. mean slope [actual/critical/ratio]: {:?} \ slope: {:?})\n (above talus angle, geom. mean slope [actual/critical/ratio]: {:?} \
/ {:?} / {:?})\n (old avg sediment thickness [all/land]: {:?} / {:?})\n \ / {:?} / {:?})\n (old avg sediment thickness [all/land]: {:?} / {:?})\n \
@ -1670,7 +1670,7 @@ fn erode(
maxh = h_i.max(maxh); maxh = h_i.max(maxh);
} }
}); });
log::debug!( debug!(
"Done applying thermal erosion (max height: {:?}) (avg height: {:?}) (min height: {:?}) \ "Done applying thermal erosion (max height: {:?}) (avg height: {:?}) (min height: {:?}) \
(avg slope: {:?})\n (above talus angle, geom. mean slope [actual/critical/ratio]: \ (avg slope: {:?})\n (above talus angle, geom. mean slope [actual/critical/ratio]: \
{:?} / {:?} / {:?})\n (avg sediment thickness [all/land]: {:?} / {:?})\n \ {:?} / {:?} / {:?})\n (avg sediment thickness [all/land]: {:?} / {:?})\n \
@ -1702,8 +1702,8 @@ fn erode(
|posi| max_slopes[posi], |posi| max_slopes[posi],
-1.0, -1.0,
); );
log::debug!("Done applying diffusion."); debug!("Done applying diffusion.");
log::debug!("Done eroding."); debug!("Done eroding.");
} }
/// The Planchon-Darboux algorithm for extracting drainage networks. /// The Planchon-Darboux algorithm for extracting drainage networks.
@ -1878,7 +1878,7 @@ pub fn get_lakes<F: Float>(
}); });
assert_eq!(newh.len(), downhill.len()); 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 newh = newh.into_boxed_slice();
let mut maxh = -F::infinity(); let mut maxh = -F::infinity();
@ -2112,7 +2112,7 @@ pub fn get_lakes<F: Float>(
))); )));
} }
} }
log::debug!("Total lakes: {:?}", pass_flows_sorted.len()); debug!("Total lakes: {:?}", pass_flows_sorted.len());
// Perform the bfs once again. // Perform the bfs once again.
#[derive(Clone, Copy, PartialEq)] #[derive(Clone, Copy, PartialEq)]
@ -2520,7 +2520,7 @@ pub fn do_erosion(
k_d_scale: f64, k_d_scale: f64,
k_da_scale: impl Fn(f64) -> f64, k_da_scale: impl Fn(f64) -> f64,
) -> (Box<[Alt]>, Box<[Alt]> /* , Box<[Alt]> */) { ) -> (Box<[Alt]>, Box<[Alt]> /* , Box<[Alt]> */) {
log::debug!("Initializing erosion arrays..."); debug!("Initializing erosion arrays...");
let oldh_ = (0..WORLD_SIZE.x * WORLD_SIZE.y) let oldh_ = (0..WORLD_SIZE.x * WORLD_SIZE.y)
.into_par_iter() .into_par_iter()
.map(|posi| oldh(posi) as Alt) .map(|posi| oldh(posi) as Alt)
@ -2587,7 +2587,7 @@ pub fn do_erosion(
.cloned() .cloned()
.map(|e| e as f64) .map(|e| e as f64)
.sum::<f64>(); .sum::<f64>();
log::debug!("Sum uplifts: {:?}", sum_uplift); debug!("Sum uplifts: {:?}", sum_uplift);
let max_uplift = uplift let max_uplift = uplift
.into_par_iter() .into_par_iter()
@ -2599,8 +2599,8 @@ pub fn do_erosion(
.cloned() .cloned()
.max_by(|a, b| a.partial_cmp(&b).unwrap()) .max_by(|a, b| a.partial_cmp(&b).unwrap())
.unwrap(); .unwrap();
log::debug!("Max uplift: {:?}", max_uplift); debug!("Max uplift: {:?}", max_uplift);
log::debug!("Max g: {:?}", max_g); debug!("Max g: {:?}", max_g);
// Height of terrain, including sediment. // Height of terrain, including sediment.
let mut h = oldh_; let mut h = oldh_;
// Bedrock transport coefficients (diffusivity) in m^2 / year, for sediment. // 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 height_scale = |n| height_scale(n);
let k_da_scale = |q| k_da_scale(q); let k_da_scale = |q| k_da_scale(q);
(0..n_steps).for_each(|i| { (0..n_steps).for_each(|i| {
log::debug!("Erosion iteration #{:?}", i); debug!("Erosion iteration #{:?}", i);
erode( erode(
&mut h, &mut h,
&mut b, &mut b,

View File

@ -52,6 +52,7 @@ use std::{
ops::{Add, Div, Mul, Neg, Sub}, ops::{Add, Div, Mul, Neg, Sub},
path::PathBuf, path::PathBuf,
}; };
use tracing::{debug, warn};
use vek::*; use vek::*;
// NOTE: I suspect this is too small (1024 * 16 * 1024 * 16 * 8 doesn't fit in // 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) { let file = match File::open(path) {
Ok(file) => file, Ok(file) => file,
Err(err) => { Err(err) => {
log::warn!("Couldn't read path for maps: {:?}", err); warn!("Couldn't read path for maps: {:?}", err);
return None; return None;
}, },
}; };
@ -886,7 +887,7 @@ impl WorldSim {
let map: WorldFileLegacy = match bincode::deserialize_from(reader) { let map: WorldFileLegacy = match bincode::deserialize_from(reader) {
Ok(map) => map, Ok(map) => map,
Err(err) => { Err(err) => {
log::warn!( warn!(
"Couldn't parse legacy map: {:?}). Maybe you meant to try a \ "Couldn't parse legacy map: {:?}). Maybe you meant to try a \
regular load?", regular load?",
err err
@ -901,7 +902,7 @@ impl WorldSim {
let file = match File::open(path) { let file = match File::open(path) {
Ok(file) => file, Ok(file) => file,
Err(err) => { Err(err) => {
log::warn!("Couldn't read path for maps: {:?}", err); warn!("Couldn't read path for maps: {:?}", err);
return None; return None;
}, },
}; };
@ -910,7 +911,7 @@ impl WorldSim {
let map: WorldFile = match bincode::deserialize_from(reader) { let map: WorldFile = match bincode::deserialize_from(reader) {
Ok(map) => map, Ok(map) => map,
Err(err) => { Err(err) => {
log::warn!( warn!(
"Couldn't parse modern map: {:?}). Maybe you meant to try a \ "Couldn't parse modern map: {:?}). Maybe you meant to try a \
legacy load?", legacy load?",
err err
@ -925,10 +926,9 @@ impl WorldSim {
let reader = match assets::load_file(specifier, &["bin"]) { let reader = match assets::load_file(specifier, &["bin"]) {
Ok(reader) => reader, Ok(reader) => reader,
Err(err) => { Err(err) => {
log::warn!( warn!(
"Couldn't read asset specifier {:?} for maps: {:?}", "Couldn't read asset specifier {:?} for maps: {:?}",
specifier, specifier, err
err
); );
return None; return None;
}, },
@ -937,7 +937,7 @@ impl WorldSim {
let map: WorldFile = match bincode::deserialize_from(reader) { let map: WorldFile = match bincode::deserialize_from(reader) {
Ok(map) => map, Ok(map) => map,
Err(err) => { Err(err) => {
log::warn!( warn!(
"Couldn't parse modern map: {:?}). Maybe you meant to try a \ "Couldn't parse modern map: {:?}). Maybe you meant to try a \
legacy load?", legacy load?",
err err
@ -956,7 +956,7 @@ impl WorldSim {
Err(e) => { Err(e) => {
match e { match e {
WorldFileError::WorldSizeInvalid => { WorldFileError::WorldSizeInvalid => {
log::warn!("World size of map is invalid."); warn!("World size of map is invalid.");
}, },
} }
None None
@ -1027,7 +1027,7 @@ impl WorldSim {
let mut path = PathBuf::from("./maps"); let mut path = PathBuf::from("./maps");
if !path.exists() { if !path.exists() {
if let Err(err) = std::fs::create_dir(&path) { 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; return;
} }
} }
@ -1042,14 +1042,14 @@ impl WorldSim {
let file = match File::create(path) { let file = match File::create(path) {
Ok(file) => file, Ok(file) => file,
Err(err) => { Err(err) => {
log::warn!("Couldn't create file for maps: {:?}", err); warn!("Couldn't create file for maps: {:?}", err);
return; return;
}, },
}; };
let writer = BufWriter::new(file); let writer = BufWriter::new(file);
if let Err(err) = bincode::serialize_into(writer, &map) { 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 is_ocean_fn = |posi: usize| is_ocean[posi];
let mut dh = downhill(|posi| alt[posi], is_ocean_fn); 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); 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 (mrec, mstack, mwrec) = {
let mut wh = vec![0.0; WORLD_SIZE.x * WORLD_SIZE.y]; let mut wh = vec![0.0; WORLD_SIZE.x * WORLD_SIZE.y];
get_multi_rec( get_multi_rec(
@ -1911,11 +1911,9 @@ impl SimChunk {
); */ ); */
} }
if river_slope.abs() >= 0.25 && cross_section.x >= 1.0 { if river_slope.abs() >= 0.25 && cross_section.x >= 1.0 {
log::debug!( debug!(
"Big waterfall! Pos area: {:?}, River data: {:?}, slope: {:?}", "Big waterfall! Pos area: {:?}, River data: {:?}, slope: {:?}",
wposf, wposf, river, river_slope
river,
river_slope
); );
} }
}, },