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 af3af6c169
commit 589254e4ab
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"
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",
]

View File

@ -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"] }

View File

@ -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...");

View File

@ -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"] }

View File

@ -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()

View File

@ -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"

View File

@ -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)]

View File

@ -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<dyn Fn() + Send>;

View File

@ -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 {

View File

@ -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 {

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()
}
pub fn worldpath_get_neighbors<V: RectRasterableVol + ReadVol + Debug>(
&mut self,
vol: &VolGrid2d<V>,
@ -95,6 +97,7 @@ impl ChunkPath {
.collect();
neighbors.into_iter()
}
pub fn is_valid_space<V: RectRasterableVol + ReadVol + Debug>(
&mut self,
vol: &VolGrid2d<V>,
@ -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<V: RectRasterableVol + ReadVol + Debug>(
&mut self,
vol: &VolGrid2d<V>,
@ -132,6 +136,4 @@ pub fn chunk_euclidean_distance(start: &Vec2<i32>, end: &Vec2<i32>) -> f32 {
istart.distance(iend)
}
pub fn chunk_transition_cost(_start: &Vec2<i32>, _end: &Vec2<i32>) -> f32 {
1.0f32
}
pub fn chunk_transition_cost(_start: &Vec2<i32>, _end: &Vec2<i32>) -> f32 { 1.0f32 }

View File

@ -11,7 +11,6 @@
)]
#[macro_use] extern crate serde_derive;
#[macro_use] extern crate log;
pub mod assets;
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 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<io::Error> for Error {
fn from(err: io::Error) -> Self {
Error::Network
}
fn from(err: io::Error) -> Self { Error::Network }
}
impl From<TryRecvError> for Error {
fn from(err: TryRecvError) -> Self {
Error::Internal
}
fn from(err: TryRecvError) -> Self { Error::Internal }
}
impl From<bincode::ErrorKind> for Error {
fn from(err: bincode::ErrorKind) -> Self {
Error::InvalidMsg
}
fn from(err: bincode::ErrorKind) -> Self { Error::InvalidMsg }
}
impl<T> From<mio_extras::channel::SendError<T>> for Error {
fn from(err: mio_extras::channel::SendError<T>) -> Self {
Error::Internal
}
fn from(err: mio_extras::channel::SendError<T>) -> 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<S: PostSend, R: PostRecv> PostOffice<S, R> {
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<S: PostSend, R: PostRecv> PostOffice<S, R> {
})
}
pub fn error(&self) -> Option<Error> {
self.err.clone()
}
pub fn error(&self) -> Option<Error> { 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();
if self.err.is_some() {
@ -123,10 +101,7 @@ impl<S: PostSend, R: PostRecv> PostOffice<S, R> {
}
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<S: PostSend, R: PostRecv>(
},
}
},
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<S: PostSend, R: PostRecv> {
impl<S: PostSend, R: PostRecv> PostBox<S, R> {
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> {
@ -220,20 +195,21 @@ impl<S: PostSend, R: PostRecv> PostBox<S, R> {
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<S: PostSend, R: PostRecv> PostBox<S, R> {
})
}
pub fn error(&self) -> Option<Error> {
self.err.clone()
}
pub fn error(&self) -> Option<Error> { 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<R> {
@ -261,10 +233,7 @@ impl<S: PostSend, R: PostRecv> PostBox<S, R> {
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<S: PostSend, R: PostRecv> PostBox<S, R> {
}
}
pub fn new_messages(&mut self) -> impl ExactSizeIterator<Item=R> {
pub fn new_messages(&mut self) -> impl ExactSizeIterator<Item = R> {
let mut msgs = VecDeque::new();
if self.err.is_some() {
@ -300,10 +269,7 @@ impl<S: PostSend, R: PostRecv> PostBox<S, R> {
}
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<S: PostSend, R: PostRecv>(
send_rx: Receiver<S>,
recv_tx: Sender<Result<R, 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 {
let chunk = match chunks.pop_front() {
Some(chunk) => chunk,
@ -389,16 +358,15 @@ fn postbox_worker<S: PostSend, R: PostRecv>(
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<S: PostSend, R: PostRecv>(
},
};
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<S: PostSend, R: PostRecv>(
},
}
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;
},
}
}
},
}

View File

@ -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 {

View File

@ -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

View File

@ -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);

View File

@ -1,3 +1,4 @@
use tracing::warn;
use vek::*;
/// 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 }
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"] }

View File

@ -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...");

View File

@ -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"

View File

@ -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 {

View File

@ -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);

View File

@ -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) {

View File

@ -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();

View File

@ -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(

View File

@ -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();

View File

@ -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::<Client>()
@ -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 });
}

View File

@ -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,

View File

@ -16,6 +16,7 @@ use common::{
};
use crossbeam::channel;
use diesel::prelude::*;
use tracing::{error, warn};
type CharacterListResult = Result<Vec<CharacterItem>, 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<Item = (i32, CharacterUpdateData)>, 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);
}
}
}

View File

@ -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()
}

View File

@ -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()

View File

@ -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

View File

@ -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 {}: {}",

View File

@ -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()

View File

@ -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

View File

@ -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"

View File

@ -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"

View File

@ -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);
}
}
}

View File

@ -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();

View File

@ -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! \

View File

@ -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<F: fmt::Debug + Float + Into<f64>, G: Float + Into<f64>>(
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 -<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,
// 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<F: Float>(
});
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<F: Float>(
)));
}
}
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::<f64>();
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,

View File

@ -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
);
}
},