From 3671c8867acf24fd58c058f7f1d8c557b655dac4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcel=20M=C3=A4rtens?= Date: Tue, 19 Nov 2019 15:11:13 +0100 Subject: [PATCH 1/3] change veloren code style --- .rustfmt.toml | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 .rustfmt.toml diff --git a/.rustfmt.toml b/.rustfmt.toml new file mode 100644 index 0000000000..f9caff8da5 --- /dev/null +++ b/.rustfmt.toml @@ -0,0 +1,17 @@ +hard_tabs = false +version = "Two" + +format_code_in_doc_comments = true +format_strings = true +wrap_comments = true +normalize_doc_attributes = true + +use_try_shorthand = true +reorder_impl_items = true + +fn_single_line = true +inline_attribute_width = 50 +match_block_trailing_comma = true +merge_imports = true +overflow_delimited_expr = true +use_field_init_shorthand = true From dd21235ff8a6c8bb18295c6644c53ba33f15578a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcel=20M=C3=A4rtens?= Date: Mon, 27 Jan 2020 17:48:42 +0100 Subject: [PATCH 2/3] Apply prefixes to veloren source, espacially comments, so that reformating wont make it unreadable, especially enumerations and other source code in errosions file --- client/src/lib.rs | 24 ++++++---- common/src/comp/inventory/mod.rs | 3 +- server/src/lib.rs | 19 +++++--- server/src/sys/terrain.rs | 3 +- server/src/sys/terrain_sync.rs | 3 +- voxygen/src/hud/settings_window.rs | 1 + voxygen/src/ui/graphic/pixel_art.rs | 7 +-- world/src/sim/erosion.rs | 69 ++++++++++++++++++----------- 8 files changed, 80 insertions(+), 49 deletions(-) diff --git a/client/src/lib.rs b/client/src/lib.rs index d8021759a9..056f28b0e6 100644 --- a/client/src/lib.rs +++ b/client/src/lib.rs @@ -36,8 +36,9 @@ use std::{ use uvth::{ThreadPool, ThreadPoolBuilder}; use vek::*; -// The duration of network inactivity until the player is kicked to the main menu -// @TODO in the future, this should be configurable on the server, and be provided to the client +// The duration of network inactivity until the player is kicked +// @TODO: in the future, this should be configurable on the server +// and be provided to the client const SERVER_TIMEOUT: Duration = Duration::from_secs(20); // After this duration has elapsed, the user will begin getting kick warnings in their chat window @@ -330,14 +331,18 @@ impl Client { // the core developers before making significant changes to this code. Here is the // approximate order of things. Please update it as this code changes. // - // 1) Collect input from the frontend, apply input effects to the state of the game + // 1) Collect input from the frontend, apply input effects to the state + // of the game // 2) Handle messages from the server - // 3) Go through any events (timer-driven or otherwise) that need handling and apply them - // to the state of the game - // 4) Perform a single LocalState tick (i.e: update the world and entities in the world) - // 5) Go through the terrain update queue and apply all changes to the terrain + // 3) Go through any events (timer-driven or otherwise) that need handling + // and apply them to the state of the game + // 4) Perform a single LocalState tick (i.e: update the world and entities + // in the world) + // 5) Go through the terrain update queue and apply all changes + // to the terrain // 6) Sync information to the server - // 7) Finish the tick, passing actions of the main thread back to the frontend + // 7) Finish the tick, passing actions of the main thread back + // to the frontend // 1) Handle input from frontend. // Pass character actions from frontend input to the player's entity. @@ -422,7 +427,8 @@ impl Client { // -0.5 for being able to move to the corner of the current chunk // -1 because chunks are not meshed if they don't have all their neighbors // (notice also that view_distance is decreased by 1) - // (this subtraction on vd is ommitted elsewhere in order to provide a buffer layer of loaded chunks) + // (this subtraction on vd is ommitted elsewhere in order to provide + // a buffer layer of loaded chunks) let top = if 2 * (dist - 2).max(0).pow(2) > (view_distance - 1).pow(2) as i32 { ((view_distance - 1).pow(2) as f32 - (dist - 2).pow(2) as f32) .sqrt() diff --git a/common/src/comp/inventory/mod.rs b/common/src/comp/inventory/mod.rs index ce5eef18e1..c4c3c4c875 100644 --- a/common/src/comp/inventory/mod.rs +++ b/common/src/comp/inventory/mod.rs @@ -59,7 +59,8 @@ impl Inventory { } } - /// Add a series of items to an inventory without giving duplicates. (n * m complexity) + /// Add a series of items to an inventory without giving duplicates. + /// (n * m complexity) /// /// Error if inventory cannot contain the items (is full), returning the un-added items. /// This is a lazy inefficient implementation, as it iterates over the inventory more times diff --git a/server/src/lib.rs b/server/src/lib.rs index ddd934cb10..b127b671df 100644 --- a/server/src/lib.rs +++ b/server/src/lib.rs @@ -985,15 +985,20 @@ impl Server { // the core developers before making significant changes to this code. Here is the // approximate order of things. Please update it as this code changes. // - // 1) Collect input from the frontend, apply input effects to the state of the game - // 2) Go through any events (timer-driven or otherwise) that need handling and apply them - // to the state of the game - // 3) Go through all incoming client network communications, apply them to the game state - // 4) Perform a single LocalState tick (i.e: update the world and entities in the world) - // 5) Go through the terrain update queue and apply all changes to the terrain + // 1) Collect input from the frontend, apply input effects to the + // state of the game + // 2) Go through any events (timer-driven or otherwise) that need handling + // and apply them to the state of the game + // 3) Go through all incoming client network communications, apply them to + // the game state + // 4) Perform a single LocalState tick (i.e: update the world and entities + // in the world) + // 5) Go through the terrain update queue and apply all changes to + // the terrain // 6) Send relevant state updates to all clients // 7) Update Metrics with current data - // 8) Finish the tick, passing control of the main thread back to the frontend + // 8) Finish the tick, passing control of the main thread back + // to the frontend let before_tick_1 = Instant::now(); // 1) Build up a list of events for this frame, to be passed to the frontend. diff --git a/server/src/sys/terrain.rs b/server/src/sys/terrain.rs index c0c5e1b559..d127cbd9f4 100644 --- a/server/src/sys/terrain.rs +++ b/server/src/sys/terrain.rs @@ -15,7 +15,8 @@ use specs::{Join, Read, ReadStorage, System, Write, WriteExpect, WriteStorage}; use std::sync::Arc; use vek::*; -/// This system will handle loading generated chunks and unloading uneeded chunks. +/// This system will handle loading generated chunks and unloading +/// uneeded chunks. /// 1. Inserts newly generated chunks into the TerrainGrid /// 2. Sends new chunks to neaby clients /// 3. Handles the chunk's supplement (e.g. npcs) diff --git a/server/src/sys/terrain_sync.rs b/server/src/sys/terrain_sync.rs index 536c62bd1e..426a062788 100644 --- a/server/src/sys/terrain_sync.rs +++ b/server/src/sys/terrain_sync.rs @@ -8,7 +8,8 @@ use common::{ }; use specs::{Join, Read, ReadExpect, ReadStorage, System, Write, WriteStorage}; -/// This system will handle loading generated chunks and unloading uneeded chunks. +/// This system will handle loading generated chunks and unloading +/// uneeded chunks. /// 1. Inserts newly generated chunks into the TerrainGrid /// 2. Sends new chunks to neaby clients /// 3. Handles the chunk's supplement (e.g. npcs) diff --git a/voxygen/src/hud/settings_window.rs b/voxygen/src/hud/settings_window.rs index ac77d83da9..b0b0cf940c 100644 --- a/voxygen/src/hud/settings_window.rs +++ b/voxygen/src/hud/settings_window.rs @@ -1288,6 +1288,7 @@ impl<'a> Widget for SettingsWindow<'a> { .font_size(18) .set(state.ids.controls_text, ui); // TODO: Replace with buttons that show actual keybinds and allow the user to change them. + #[rustfmt::skip] Text::new(&format!( "{}\n\ {}\n\ diff --git a/voxygen/src/ui/graphic/pixel_art.rs b/voxygen/src/ui/graphic/pixel_art.rs index d48018fbfd..6523f78e2c 100644 --- a/voxygen/src/ui/graphic/pixel_art.rs +++ b/voxygen/src/ui/graphic/pixel_art.rs @@ -13,11 +13,12 @@ const EPSILON: f32 = 0.0001; // averaged // Say we have two areas that we are combining to form a single pixel // A1 and A2 where these are the fraction of the area of the pixel each color contributes to -// Then if the colors were opaque we would say that the final color ouput color o3 is +// Then if the colors were opaque we would say that the final color +// ouput color o3 is // E1: o3 = A1 * o1 + A2 * o2 // where o1 and o2 are the opaque colors of the two areas -// now say the areas are actually translucent and these opaque colors are derived by blending with a -// common backgound color b +// now say the areas are actually translucent and these opaque colors are +// derived by blending with a common backgound color b // E2: o1 = c1 * a1 + b * (1 - a1) // E3: o2 = c2 * a2 + b * (1 - a2) // we want to find the combined color (c3) and combined alpha (a3) such that diff --git a/world/src/sim/erosion.rs b/world/src/sim/erosion.rs index 56187657b8..5e9c4acf65 100644 --- a/world/src/sim/erosion.rs +++ b/world/src/sim/erosion.rs @@ -368,12 +368,12 @@ pub fn get_rivers, G: Float + Into>( // Now, we know we are a river *candidate*. We still don't know whether we are actually a // river, though. There are two ways for that to happen: // (i) We are already a river. - // (ii) Using the Gauckler–Manning–Strickler formula for cross-sectional average velocity - // of water, we establish that the river can be "big enough" to appear on the Veloren - // map. + // (ii) Using the Gauckler–Manning–Strickler formula for cross-sectional + // average velocity of water, we establish that the river can be + // "big enough" to appear on the Veloren map. // - // This is very imprecise, of course, and (ii) may (and almost certainly will) change over - // time. + // This is very imprecise, of course, and (ii) may (and almost certainly will) + // change over time. // // In both cases, we preemptively set our child to be a river, to make sure we have an // unbroken stream. Also in both cases, we go to the effort of computing an effective @@ -573,24 +573,30 @@ fn get_max_slope( /// /// This algorithm does this in four steps: /// -/// 1. Sort the nodes in h by height (so the lowest node by altitude is first in the -/// list, and the highest node by altitude is last). -/// 2. Iterate through the list in *reverse.* For each node, we compute its drainage area as -/// the sum of the drainage areas of its "children" nodes (i.e. the nodes with directed edges to -/// this node). To do this efficiently, we start with the "leaves" (the highest nodes), which -/// have no neighbors higher than them, hence no directed edges to them. We add their area to -/// themselves, and then to all neighbors that they flow into (their "ancestors" in the flow -/// graph); currently, this just means the node immediately downhill of this node. -/// As we go lower, we know that all our "children" already had their areas computed, which -/// means that we can repeat the process in order to derive all the final areas. -/// 3. Now, iterate through the list in *order.* Whether we used the filling method to compute a -/// "filled" version of each depression, or used the lake connection algoirthm described in [1], -/// each node is guaranteed to have zero or one drainage edges out, representing the direction -/// of water flow for that node. For nodes i with zero drainage edges out (boundary nodes and -/// lake bottoms) we set the slope to 0 (so the change in altitude is uplift(i)) -/// For nodes with at least one drainage edge out, we take advantage of the fact that we are -/// computing new heights in order and rewrite our equation as (letting j = downhill[i], A[i] -/// be the computed area of point i, p(i) be the x-y position of point i, +/// 1. Sort the nodes in h by height (so the lowest node by altitude is first +/// in the list, and the highest node by altitude is last). +/// 2. Iterate through the list in *reverse.* For each node, we compute its +/// drainage area as the sum of the drainage areas of its "children" nodes +/// (i.e. the nodes with directed edges to this node). To do this +/// efficiently, we start with the "leaves" (the highest nodes), which +/// have no neighbors higher than them, hence no directed edges to them. +/// We add their area to themselves, and then to all neighbors that they +/// flow into (their "ancestors" in the flow graph); currently, this just +/// means the node immediately downhill of this node. As we go lower, we +/// know that all our "children" already had their areas computed, which +/// means that we can repeat the process in order to derive all the final +/// areas. +/// 3. Now, iterate through the list in *order.* Whether we used the filling +/// method to compute a "filled" version of each depression, or used the lake +/// connection algoirthm described in [1], each node is guaranteed to have +/// zero or one drainage edges out, representing the direction of water flow +/// for that node. For nodes i with zero drainage edges out (boundary nodes +/// and lake bottoms) we set the slope to 0 (so the change in altitude is +/// uplift(i)) +/// For nodes with at least one drainage edge out, we take advantage of the +/// fact that we are computing new heights in order and rewrite our equation +/// as (letting j = downhill[i], A[i] be the computed area of point i, +/// p(i) be the x-y position of point i, /// flux(i) = k * A[i]^m / ((p(i) - p(j)).magnitude()), and δt = 1): /// /// h[i](t + dt) = h[i](t) + δt * (uplift[i] + flux(i) * h[j](t + δt)) / (1 + flux(i) * δt). @@ -614,12 +620,14 @@ fn get_max_slope( /// prediction that hillslope diffusion should be nonlinear, which we sort of attempt to /// approximate. /// -/// [1] Guillaume Cordonnier, Jean Braun, Marie-Paule Cani, Bedrich Benes, Eric Galin, et al.. +/// [1] Guillaume Cordonnier, Jean Braun, Marie-Paule Cani, +/// Bedrich Benes, Eric Galin, et al.. /// Large Scale Terrain Generation from Tectonic Uplift and Fluvial Erosion. /// Computer Graphics Forum, Wiley, 2016, Proc. EUROGRAPHICS 2016, 35 (2), pp.165-175. /// ⟨10.1111/cgf.12820⟩. ⟨hal-01262376⟩ /// -/// [2] William E. Dietrich, Dino G. Bellugi, Leonard S. Sklar, Jonathan D. Stock +/// [2] William E. Dietrich, Dino G. Bellugi, Leonard S. Sklar, +/// Jonathan D. Stock /// Geomorphic Transport Laws for Predicting Landscape Form and Dynamics. /// Prediction in Geomorphology, Geophysical Monograph 135. /// Copyright 2003 by the American Geophysical Union @@ -678,6 +686,7 @@ fn erode( let dx = TerrainChunkSize::RECT_SIZE.x as f64; let dy = TerrainChunkSize::RECT_SIZE.y as f64; + #[rustfmt::skip] // ε₀ and α are part of the soil production approximate // equation: // @@ -860,6 +869,7 @@ fn erode( mrec_downhill(&mrec, posi).for_each(|(kk, posj)| { let mwrec_kk = mwrec_i[kk] as f64; + #[rustfmt::skip] // Working equation: // U = uplift per time // D = sediment deposition per time @@ -1031,6 +1041,7 @@ fn erode( "(Done precomputation, time={:?}ms).", start_time.elapsed().as_millis() ); + #[rustfmt::skip] // sum the erosion in stack order // // After: @@ -1065,6 +1076,7 @@ fn erode( "(Done sediment transport computation, time={:?}ms).", start_time.elapsed().as_millis() ); + #[rustfmt::skip] // do ij=nn,1,-1 // ijk=stack(ij) // ijr=rec(ijk) @@ -1122,11 +1134,14 @@ fn erode( let g_i_ratio = g_i / (p * area_i); // One side of nonlinear equation (23): // - // h_i(t) + U_i * Δt + G / (p̃ * Ã_i) * Σ{j ∈ upstream_i(t)}(h_j(t, FINAL) + U_j * Δt - h_j(t + Δt, k)) + // h_i(t) + U_i * Δt + G / (p̃ * Ã_i) * Σ + // {j ∈ upstream_i(t)}(h_j(t, FINAL) + // + U_j * Δt - h_j(t + Δt, k)) // // where // - // Ã_i = A_i / (∆x∆y) = N_i, number of cells upstream of cell i. + // Ã_i = A_i / (∆x∆y) = N_i, + // number of cells upstream of cell i. *elev = old_h_after_uplift_i + uphill_silt_i * g_i_ratio; } }, From dae31ae5b64b6bc6e1f1390f77ea75bac65bbb70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcel=20M=C3=A4rtens?= Date: Sat, 1 Feb 2020 21:39:39 +0100 Subject: [PATCH 3/3] apply new rustfmt - touching alot of files --- chat-cli/src/main.rs | 14 +- client/src/error.rs | 4 +- client/src/lib.rs | 161 ++-- common/benches/chonk_benchmark.rs | 5 +- common/benches/color_benchmark.rs | 5 +- common/build.rs | 16 +- common/src/assets/mod.rs | 62 +- common/src/assets/watch.rs | 28 +- common/src/astar.rs | 13 +- common/src/clock.rs | 8 +- common/src/comp/agent.rs | 4 +- common/src/comp/body.rs | 12 +- common/src/comp/body/humanoid.rs | 31 +- common/src/comp/character_state.rs | 2 + common/src/comp/controller.rs | 32 +- common/src/comp/energy.rs | 8 +- common/src/comp/inventory/item.rs | 29 +- common/src/comp/inventory/mod.rs | 47 +- common/src/comp/inventory/test.rs | 13 +- common/src/comp/location.rs | 16 +- common/src/comp/stats.rs | 85 +-- common/src/event.rs | 20 +- common/src/figure/cell.rs | 8 +- common/src/figure/mat_cell.rs | 10 +- common/src/figure/mod.rs | 15 +- common/src/lib.rs | 13 +- common/src/msg/ecs_packet.rs | 5 +- common/src/msg/mod.rs | 8 +- common/src/msg/server.rs | 9 +- common/src/net/data.rs | 3 +- common/src/net/post2.rs | 58 +- common/src/npc.rs | 13 +- common/src/path.rs | 37 +- common/src/ray.rs | 6 +- common/src/region.rs | 74 +- common/src/state.rs | 80 +- common/src/sync/mod.rs | 3 +- common/src/sync/packet.rs | 13 +- common/src/sync/sync_ext.rs | 10 +- common/src/sync/track.rs | 25 +- common/src/sync/uid.rs | 34 +- common/src/sys/agent.rs | 15 +- common/src/sys/combat.rs | 3 +- common/src/sys/controller.rs | 87 ++- common/src/sys/mod.rs | 18 +- common/src/sys/mount.rs | 4 +- common/src/sys/movement.rs | 10 +- common/src/sys/phys.rs | 33 +- common/src/sys/projectile.rs | 10 +- common/src/sys/stats.rs | 7 +- common/src/terrain/block.rs | 12 +- common/src/terrain/chonk.rs | 22 +- common/src/terrain/mod.rs | 8 +- common/src/terrain/structure.rs | 16 +- common/src/util/mod.rs | 3 +- common/src/vol.rs | 51 +- common/src/volumes/chunk.rs | 44 +- common/src/volumes/dyna.rs | 26 +- common/src/volumes/vol_grid_2d.rs | 52 +- common/src/volumes/vol_grid_3d.rs | 36 +- server/src/chunk_generator.rs | 7 +- server/src/client.rs | 8 +- server/src/cmd.rs | 76 +- server/src/error.rs | 4 +- server/src/input.rs | 4 +- server/src/lib.rs | 157 ++-- server/src/metrics.rs | 2 +- server/src/settings.rs | 20 +- server/src/sys/entity_sync.rs | 30 +- server/src/sys/message.rs | 60 +- server/src/sys/mod.rs | 16 +- server/src/sys/sentinel.rs | 6 +- server/src/sys/subscription.rs | 35 +- server/src/sys/terrain.rs | 5 +- server/src/test_world.rs | 4 +- voxygen/benches/meshing_benchmark.rs | 38 +- voxygen/src/anim/biped_large/idle.rs | 2 +- voxygen/src/anim/biped_large/jump.rs | 2 +- voxygen/src/anim/biped_large/mod.rs | 5 +- voxygen/src/anim/biped_large/run.rs | 2 +- voxygen/src/anim/bird_medium/idle.rs | 2 +- voxygen/src/anim/bird_medium/jump.rs | 2 +- voxygen/src/anim/bird_medium/mod.rs | 9 +- voxygen/src/anim/bird_medium/run.rs | 2 +- voxygen/src/anim/bird_small/idle.rs | 2 +- voxygen/src/anim/bird_small/jump.rs | 2 +- voxygen/src/anim/bird_small/mod.rs | 13 +- voxygen/src/anim/bird_small/run.rs | 2 +- voxygen/src/anim/character/attack.rs | 20 +- voxygen/src/anim/character/block.rs | 20 +- voxygen/src/anim/character/blockidle.rs | 20 +- voxygen/src/anim/character/charge.rs | 2 +- voxygen/src/anim/character/cidle.rs | 20 +- voxygen/src/anim/character/climb.rs | 2 +- voxygen/src/anim/character/gliding.rs | 2 +- voxygen/src/anim/character/idle.rs | 2 +- voxygen/src/anim/character/jump.rs | 2 +- voxygen/src/anim/character/mod.rs | 27 +- voxygen/src/anim/character/roll.rs | 2 +- voxygen/src/anim/character/run.rs | 5 +- voxygen/src/anim/character/sit.rs | 2 +- voxygen/src/anim/character/stand.rs | 3 +- voxygen/src/anim/character/swim.rs | 5 +- voxygen/src/anim/character/wield.rs | 20 +- voxygen/src/anim/critter/idle.rs | 2 +- voxygen/src/anim/critter/jump.rs | 2 +- voxygen/src/anim/critter/mod.rs | 8 +- voxygen/src/anim/critter/run.rs | 2 +- voxygen/src/anim/dragon/idle.rs | 2 +- voxygen/src/anim/dragon/jump.rs | 2 +- voxygen/src/anim/dragon/mod.rs | 12 +- voxygen/src/anim/dragon/run.rs | 2 +- voxygen/src/anim/fish_medium/idle.rs | 2 +- voxygen/src/anim/fish_medium/jump.rs | 2 +- voxygen/src/anim/fish_medium/mod.rs | 13 +- voxygen/src/anim/fish_medium/run.rs | 2 +- voxygen/src/anim/fish_small/idle.rs | 2 +- voxygen/src/anim/fish_small/jump.rs | 2 +- voxygen/src/anim/fish_small/mod.rs | 13 +- voxygen/src/anim/fish_small/run.rs | 2 +- voxygen/src/anim/fixture/mod.rs | 5 +- voxygen/src/anim/object/mod.rs | 5 +- voxygen/src/anim/quadruped_medium/idle.rs | 2 +- voxygen/src/anim/quadruped_medium/jump.rs | 2 +- voxygen/src/anim/quadruped_medium/mod.rs | 9 +- voxygen/src/anim/quadruped_medium/run.rs | 2 +- voxygen/src/anim/quadruped_small/idle.rs | 2 +- voxygen/src/anim/quadruped_small/jump.rs | 2 +- voxygen/src/anim/quadruped_small/mod.rs | 9 +- voxygen/src/anim/quadruped_small/run.rs | 2 +- voxygen/src/audio/channel.rs | 41 +- voxygen/src/audio/fader.rs | 8 +- voxygen/src/audio/mod.rs | 10 +- .../src/audio/sfx/event_mapper/movement.rs | 50 +- .../src/audio/sfx/event_mapper/progression.rs | 4 +- voxygen/src/audio/sfx/mod.rs | 15 +- voxygen/src/audio/soundcache.rs | 13 +- voxygen/src/ecs/comp.rs | 6 +- voxygen/src/ecs/sys.rs | 8 +- voxygen/src/ecs/sys/floater.rs | 30 +- voxygen/src/error.rs | 8 +- voxygen/src/hud/bag.rs | 15 +- voxygen/src/hud/buttons.rs | 6 +- voxygen/src/hud/character_window.rs | 16 +- voxygen/src/hud/chat.rs | 25 +- voxygen/src/hud/esc_menu.rs | 6 +- voxygen/src/hud/item_imgs.rs | 11 +- voxygen/src/hud/map.rs | 8 +- voxygen/src/hud/minimap.rs | 10 +- voxygen/src/hud/mod.rs | 187 +++-- voxygen/src/hud/quest.rs | 15 +- voxygen/src/hud/settings_window.rs | 13 +- voxygen/src/hud/skillbar.rs | 67 +- voxygen/src/hud/social.rs | 18 +- voxygen/src/hud/spell.rs | 13 +- voxygen/src/i18n.rs | 18 +- voxygen/src/main.rs | 47 +- voxygen/src/menu/char_selection/mod.rs | 19 +- voxygen/src/menu/char_selection/scene.rs | 44 +- voxygen/src/menu/char_selection/ui.rs | 21 +- voxygen/src/menu/main/client_init.rs | 55 +- voxygen/src/menu/main/mod.rs | 33 +- voxygen/src/menu/main/ui.rs | 25 +- voxygen/src/mesh/segment.rs | 4 +- voxygen/src/mesh/terrain.rs | 20 +- voxygen/src/mesh/vol.rs | 12 +- voxygen/src/meta.rs | 6 +- voxygen/src/render/consts.rs | 5 +- voxygen/src/render/error.rs | 49 +- voxygen/src/render/instances.rs | 4 +- voxygen/src/render/mesh.rs | 31 +- voxygen/src/render/mod.rs | 5 +- voxygen/src/render/model.rs | 7 +- voxygen/src/render/pipelines/figure.rs | 18 +- voxygen/src/render/pipelines/fluid.rs | 10 +- voxygen/src/render/pipelines/mod.rs | 20 +- voxygen/src/render/pipelines/postprocess.rs | 14 +- voxygen/src/render/pipelines/skybox.rs | 14 +- voxygen/src/render/pipelines/sprite.rs | 14 +- voxygen/src/render/pipelines/terrain.rs | 10 +- voxygen/src/render/pipelines/ui.rs | 14 +- voxygen/src/render/renderer.rs | 98 +-- voxygen/src/render/texture.rs | 4 +- voxygen/src/scene/camera.rs | 61 +- voxygen/src/scene/figure/cache.rs | 28 +- voxygen/src/scene/figure/load.rs | 158 ++-- voxygen/src/scene/figure/mod.rs | 108 ++- voxygen/src/scene/mod.rs | 79 +- voxygen/src/scene/terrain.rs | 180 +++-- voxygen/src/session.rs | 124 ++-- voxygen/src/settings.rs | 24 +- voxygen/src/ui/cache.rs | 20 +- voxygen/src/ui/event.rs | 20 +- voxygen/src/ui/font_ids.rs | 4 +- voxygen/src/ui/graphic/mod.rs | 60 +- voxygen/src/ui/graphic/pixel_art.rs | 22 +- voxygen/src/ui/graphic/renderer.rs | 5 +- voxygen/src/ui/img_ids.rs | 18 +- voxygen/src/ui/mod.rs | 92 +-- voxygen/src/ui/scale.rs | 38 +- voxygen/src/ui/widgets/image_frame.rs | 64 +- voxygen/src/ui/widgets/image_slider.rs | 40 +- voxygen/src/ui/widgets/ingame.rs | 26 +- voxygen/src/ui/widgets/radio_list.rs | 31 +- voxygen/src/ui/widgets/toggle_button.rs | 12 +- voxygen/src/ui/widgets/tooltip.rs | 58 +- voxygen/src/window.rs | 391 +++++----- world/examples/view.rs | 11 +- world/examples/water.rs | 50 +- world/src/block/mod.rs | 10 +- world/src/block/natural.rs | 9 +- world/src/column/mod.rs | 105 +-- world/src/config.rs | 50 +- world/src/generator/town/mod.rs | 74 +- world/src/generator/town/util.rs | 16 +- world/src/generator/town/vol.rs | 14 +- world/src/lib.rs | 12 +- world/src/sim/diffusion.rs | 18 +- world/src/sim/erosion.rs | 697 ++++++++++-------- world/src/sim/location.rs | 23 +- world/src/sim/map.rs | 75 +- world/src/sim/mod.rs | 415 ++++++----- world/src/sim/settlement.rs | 8 +- world/src/sim/util.rs | 222 +++--- world/src/util/grid.rs | 8 +- world/src/util/hash_cache.rs | 4 +- world/src/util/random.rs | 11 +- world/src/util/structure.rs | 21 +- 228 files changed, 3351 insertions(+), 3666 deletions(-) diff --git a/chat-cli/src/main.rs b/chat-cli/src/main.rs index f21da11295..b74c1ea87f 100644 --- a/chat-cli/src/main.rs +++ b/chat-cli/src/main.rs @@ -55,9 +55,11 @@ fn main() { .unwrap(); let (tx, rx) = mpsc::channel(); - thread::spawn(move || loop { - let msg = read_input(); - tx.send(msg).unwrap(); + thread::spawn(move || { + loop { + let msg = read_input(); + tx.send(msg).unwrap(); + } }); loop { @@ -74,13 +76,13 @@ fn main() { Err(err) => { error!("Error: {:?}", err); break; - } + }, }; for event in events { match event { Event::Chat { message, .. } => println!("{}", message), - Event::Disconnect => {} // TODO + Event::Disconnect => {}, // TODO Event::DisconnectionNotification(time) => { let message = match time { 0 => String::from("Goodbye!"), @@ -88,7 +90,7 @@ fn main() { }; println!("{}", message) - } + }, } } diff --git a/client/src/error.rs b/client/src/error.rs index 27ff6b9142..154387e16c 100644 --- a/client/src/error.rs +++ b/client/src/error.rs @@ -13,7 +13,5 @@ pub enum Error { } impl From for Error { - fn from(err: PostError) -> Self { - Error::Network(err) - } + fn from(err: PostError) -> Self { Error::Network(err) } } diff --git a/client/src/lib.rs b/client/src/lib.rs index 056f28b0e6..90ecb651c6 100644 --- a/client/src/lib.rs +++ b/client/src/lib.rs @@ -41,7 +41,8 @@ use vek::*; // and be provided to the client const SERVER_TIMEOUT: Duration = Duration::from_secs(20); -// After this duration has elapsed, the user will begin getting kick warnings in their chat window +// After this duration has elapsed, the user will begin getting kick warnings in +// their chat window const SERVER_TIMEOUT_GRACE_PERIOD: Duration = Duration::from_secs(14); pub enum Event { @@ -94,7 +95,8 @@ impl Client { // TODO: Display that versions don't match in Voxygen if server_info.git_hash != common::util::GIT_HASH.to_string() { log::warn!( - "Server is running {}[{}], you are running {}[{}], versions might be incompatible!", + "Server is running {}[{}], you are running {}[{}], versions might be \ + incompatible!", server_info.git_hash, server_info.git_date, common::util::GIT_HASH.to_string(), @@ -125,10 +127,10 @@ impl Client { log::debug!("Done preparing image..."); (state, entity, server_info, (world_map, map_size)) - } + }, Some(ServerMsg::Error(ServerError::TooManyPlayers)) => { - return Err(Error::TooManyPlayers) - } + return Err(Error::TooManyPlayers); + }, _ => return Err(Error::ServerWentMad), }; @@ -176,10 +178,10 @@ impl Client { loop { match self.postbox.next_message() { Some(ServerMsg::StateAnswer(Err((RequestStateError::Denied, _)))) => { - break Err(Error::InvalidAuth) - } + break Err(Error::InvalidAuth); + }, Some(ServerMsg::StateAnswer(Ok(ClientState::Registered))) => break Ok(()), - _ => {} + _ => {}, } } } @@ -197,7 +199,8 @@ impl Client { self.client_state = ClientState::Pending; } - /// Request a state transition to `ClientState::Registered` from an ingame state. + /// Request a state transition to `ClientState::Registered` from an ingame + /// state. pub fn request_remove_character(&mut self) { self.postbox.send_message(ClientMsg::ExitIngame); self.client_state = ClientState::Pending; @@ -260,13 +263,9 @@ impl Client { .send_message(ClientMsg::ControlEvent(ControlEvent::Unmount)); } - pub fn view_distance(&self) -> Option { - self.view_distance - } + pub fn view_distance(&self) -> Option { self.view_distance } - pub fn loaded_distance(&self) -> f32 { - self.loaded_distance - } + pub fn loaded_distance(&self) -> f32 { self.loaded_distance } pub fn current_chunk(&self) -> Option> { let chunk_pos = Vec2::from( @@ -283,9 +282,7 @@ impl Client { self.state.terrain().get_key_arc(chunk_pos).cloned() } - pub fn inventories(&self) -> ReadStorage { - self.state.read_storage() - } + pub fn inventories(&self) -> ReadStorage { self.state.read_storage() } /// Send a chat message to the server. pub fn send_chat(&mut self, message: String) { @@ -319,17 +316,19 @@ impl Client { ))); } - /// Execute a single client tick, handle input and update the game state by the given duration. + /// Execute a single client tick, handle input and update the game state by + /// the given duration. pub fn tick( &mut self, inputs: ControllerInputs, dt: Duration, add_foreign_systems: impl Fn(&mut DispatcherBuilder), ) -> Result, Error> { - // This tick function is the centre of the Veloren universe. Most client-side things are - // managed from here, and as such it's important that it stays organised. Please consult - // the core developers before making significant changes to this code. Here is the - // approximate order of things. Please update it as this code changes. + // This tick function is the centre of the Veloren universe. Most client-side + // things are managed from here, and as such it's important that it + // stays organised. Please consult the core developers before making + // significant changes to this code. Here is the approximate order of + // things. Please update it as this code changes. // // 1) Collect input from the frontend, apply input effects to the state // of the game @@ -347,13 +346,10 @@ impl Client { // 1) Handle input from frontend. // Pass character actions from frontend input to the player's entity. if let ClientState::Character = self.client_state { - self.state.write_component( - self.entity, - Controller { - inputs: inputs.clone(), - events: Vec::new(), - }, - ); + self.state.write_component(self.entity, Controller { + inputs: inputs.clone(), + events: Vec::new(), + }); self.postbox .send_message(ClientMsg::ControllerInputs(inputs)); } @@ -528,7 +524,8 @@ impl Client { let mut frontend_events = Vec::new(); // Check that we have an valid connection. - // Use the last ping time as a 1s rate limiter, we only notify the user once per second + // Use the last ping time as a 1s rate limiter, we only notify the user once per + // second if Instant::now().duration_since(self.last_server_ping) > Duration::from_secs(1) { let duration_since_last_pong = Instant::now().duration_since(self.last_server_pong); @@ -558,24 +555,37 @@ impl Client { ServerMsg::InitialSync { .. } => return Err(Error::ServerWentMad), ServerMsg::PlayerListUpdate(PlayerListUpdate::Init(list)) => { self.player_list = list - } + }, ServerMsg::PlayerListUpdate(PlayerListUpdate::Add(uid, name)) => { if let Some(old_name) = self.player_list.insert(uid, name.clone()) { - warn!("Received msg to insert {} with uid {} into the player list but there was already an entry for {} with the same uid that was overwritten!", name, uid, old_name); + warn!( + "Received msg to insert {} with uid {} into the player list but \ + there was already an entry for {} with the same uid that was \ + overwritten!", + name, uid, old_name + ); } - } + }, ServerMsg::PlayerListUpdate(PlayerListUpdate::Remove(uid)) => { if self.player_list.remove(&uid).is_none() { - warn!("Received msg to remove uid {} from the player list by they weren't in the list!", uid); + warn!( + "Received msg to remove uid {} from the player list by they \ + weren't in the list!", + uid + ); } - } + }, ServerMsg::PlayerListUpdate(PlayerListUpdate::Alias(uid, new_name)) => { if let Some(name) = self.player_list.get_mut(&uid) { *name = new_name; } else { - warn!("Received msg to alias player with uid {} to {} but this uid is not in the player list", uid, new_name); + warn!( + "Received msg to alias player with uid {} to {} but this uid is \ + not in the player list", + uid, new_name + ); } - } + }, ServerMsg::Ping => self.postbox.send_message(ClientMsg::Pong), ServerMsg::Pong => { @@ -584,26 +594,26 @@ impl Client { self.last_ping_delta = Instant::now() .duration_since(self.last_server_ping) .as_secs_f64(); - } + }, ServerMsg::ChatMsg { message, chat_type } => { frontend_events.push(Event::Chat { message, chat_type }) - } + }, ServerMsg::SetPlayerEntity(uid) => { if let Some(entity) = self.state.ecs().entity_from_uid(uid) { self.entity = entity; } else { return Err(Error::Other("Failed to find entity from uid.".to_owned())); } - } + }, ServerMsg::TimeOfDay(time_of_day) => { *self.state.ecs_mut().write_resource() = time_of_day; - } + }, ServerMsg::EcsSync(sync_package) => { self.state.ecs_mut().apply_sync_package(sync_package); - } + }, ServerMsg::CreateEntity(entity_package) => { self.state.ecs_mut().apply_entity_package(entity_package); - } + }, ServerMsg::DeleteEntity(entity) => { if self .state @@ -615,7 +625,7 @@ impl Client { .ecs_mut() .delete_entity_and_clear_from_uid_allocator(entity); } - } + }, // Cleanup for when the client goes back to the `Registered` state ServerMsg::ExitIngameCleanup => { // Get client entity Uid @@ -635,22 +645,22 @@ impl Client { .write_resource::() .allocate(entity_builder.entity, Some(client_uid)); self.entity = entity_builder.with(uid).build(); - } + }, ServerMsg::EntityPos { entity, pos } => { if let Some(entity) = self.state.ecs().entity_from_uid(entity) { self.state.write_component(entity, pos); } - } + }, ServerMsg::EntityVel { entity, vel } => { if let Some(entity) = self.state.ecs().entity_from_uid(entity) { self.state.write_component(entity, vel); } - } + }, ServerMsg::EntityOri { entity, ori } => { if let Some(entity) = self.state.ecs().entity_from_uid(entity) { self.state.write_component(entity, ori); } - } + }, ServerMsg::EntityCharacterState { entity, character_state, @@ -658,24 +668,24 @@ impl Client { if let Some(entity) = self.state.ecs().entity_from_uid(entity) { self.state.write_component(entity, character_state); } - } + }, ServerMsg::InventoryUpdate(inventory) => { self.state.write_component(self.entity, inventory) - } + }, ServerMsg::TerrainChunkUpdate { key, chunk } => { if let Ok(chunk) = chunk { self.state.insert_chunk(key, *chunk); } self.pending_chunks.remove(&key); - } + }, ServerMsg::TerrainBlockUpdates(mut blocks) => { blocks.drain().for_each(|(pos, block)| { self.state.set_block(pos, block); }); - } + }, ServerMsg::StateAnswer(Ok(state)) => { self.client_state = state; - } + }, ServerMsg::StateAnswer(Err((error, state))) => { if error == RequestStateError::Denied { warn!("Connection denied!"); @@ -685,10 +695,10 @@ impl Client { "StateAnswer: {:?}. Server thinks client is in state {:?}.", error, state ); - } + }, ServerMsg::Disconnect => { frontend_events.push(Event::Disconnect); - } + }, } } } else if let Some(err) = self.postbox.error() { @@ -701,40 +711,27 @@ impl Client { } /// Get the player's entity. - pub fn entity(&self) -> EcsEntity { - self.entity - } + pub fn entity(&self) -> EcsEntity { self.entity } /// Get the client state - pub fn get_client_state(&self) -> ClientState { - self.client_state - } + pub fn get_client_state(&self) -> ClientState { self.client_state } /// Get the current tick number. - pub fn get_tick(&self) -> u64 { - self.tick - } + pub fn get_tick(&self) -> u64 { self.tick } - pub fn get_ping_ms(&self) -> f64 { - self.last_ping_delta * 1000.0 - } + pub fn get_ping_ms(&self) -> f64 { self.last_ping_delta * 1000.0 } - /// Get a reference to the client's worker thread pool. This pool should be used for any - /// computationally expensive operations that run outside of the main thread (i.e., threads that - /// block on I/O operations are exempt). - pub fn thread_pool(&self) -> &ThreadPool { - &self.thread_pool - } + /// Get a reference to the client's worker thread pool. This pool should be + /// used for any computationally expensive operations that run outside + /// of the main thread (i.e., threads that block on I/O operations are + /// exempt). + pub fn thread_pool(&self) -> &ThreadPool { &self.thread_pool } /// Get a reference to the client's game state. - pub fn state(&self) -> &State { - &self.state - } + pub fn state(&self) -> &State { &self.state } /// Get a mutable reference to the client's game state. - pub fn state_mut(&mut self) -> &mut State { - &mut self.state - } + pub fn state_mut(&mut self) -> &mut State { &mut self.state } /// Get a vector of all the players on the server pub fn get_players(&mut self) -> Vec { @@ -749,7 +746,5 @@ impl Client { } impl Drop for Client { - fn drop(&mut self) { - self.postbox.send_message(ClientMsg::Disconnect); - } + fn drop(&mut self) { self.postbox.send_message(ClientMsg::Disconnect); } } diff --git a/common/benches/chonk_benchmark.rs b/common/benches/chonk_benchmark.rs index d325f02888..d6fd95e695 100644 --- a/common/benches/chonk_benchmark.rs +++ b/common/benches/chonk_benchmark.rs @@ -1,7 +1,4 @@ -use criterion::black_box; -use criterion::criterion_group; -use criterion::criterion_main; -use criterion::Criterion; +use criterion::{black_box, criterion_group, criterion_main, Criterion}; use vek::*; use veloren_common::{ diff --git a/common/benches/color_benchmark.rs b/common/benches/color_benchmark.rs index 5031cb4c06..ad6f930774 100644 --- a/common/benches/color_benchmark.rs +++ b/common/benches/color_benchmark.rs @@ -1,7 +1,4 @@ -use criterion::black_box; -use criterion::criterion_group; -use criterion::criterion_main; -use criterion::Criterion; +use criterion::{black_box, criterion_group, criterion_main, Criterion}; use vek::*; use veloren_common::util::{linear_to_srgb, srgb_to_linear}; diff --git a/common/build.rs b/common/build.rs index 44d7aed036..a56637b973 100644 --- a/common/build.rs +++ b/common/build.rs @@ -1,10 +1,10 @@ -use std::env; -use std::fs::File; -use std::io::Read; -use std::io::Write; -use std::path::Path; -use std::path::PathBuf; -use std::process::Command; +use std::{ + env, + fs::File, + io::{Read, Write}, + path::{Path, PathBuf}, + process::Command, +}; fn main() { // Get the current githash @@ -30,7 +30,7 @@ fn main() { target .write_all(hash.trim().as_bytes()) .expect("failed to write to file!"); - } + }, Err(e) => panic!("failed to convert git output to UTF-8: {}", e), }, Err(e) => panic!("failed to retrieve current git commit hash: {}", e), diff --git a/common/src/assets/mod.rs b/common/src/assets/mod.rs index 8198aa657f..cadff415de 100644 --- a/common/src/assets/mod.rs +++ b/common/src/assets/mod.rs @@ -21,7 +21,8 @@ use std::{ pub enum Error { /// An internal error occurred. Internal(Arc), - /// An asset of a different type has already been loaded with this specifier. + /// An asset of a different type has already been loaded with this + /// specifier. InvalidType, /// Asset does not exist. NotFound(String), @@ -41,15 +42,11 @@ impl fmt::Display for Error { } impl From> for Error { - fn from(_: Arc) -> Self { - Error::InvalidType - } + fn from(_: Arc) -> Self { Error::InvalidType } } impl From for Error { - fn from(err: std::io::Error) -> Self { - Error::NotFound(format!("{}", err)) - } + fn from(err: std::io::Error) -> Self { Error::NotFound(format!("{}", err)) } } lazy_static! { @@ -58,19 +55,20 @@ lazy_static! { RwLock::new(HashMap::new()); } -// TODO: Remove this function. It's only used in world/ in a really ugly way.To do this properly -// assets should have all their necessary data in one file. A ron file could be used to combine -// voxel data with positioning data for example. -/// Function used to load assets from the filesystem or the cache. Permits manipulating the loaded asset with a mapping function. -/// Example usage: +// TODO: Remove this function. It's only used in world/ in a really ugly way.To +// do this properly assets should have all their necessary data in one file. A +// ron file could be used to combine voxel data with positioning data for +// example. +/// Function used to load assets from the filesystem or the cache. Permits +/// manipulating the loaded asset with a mapping function. Example usage: /// ```no_run -/// use veloren_common::{assets, terrain::Structure}; /// use vek::*; +/// use veloren_common::{assets, terrain::Structure}; /// -/// let my_tree_structure = assets::load_map( -/// "world.tree.oak_green.1", -/// |s: Structure| s.with_center(Vec3::new(15, 18, 14)), -/// ).unwrap(); +/// let my_tree_structure = assets::load_map("world.tree.oak_green.1", |s: Structure| { +/// s.with_center(Vec3::new(15, 18, 14)) +/// }) +/// .unwrap(); /// ``` pub fn load_map A>( specifier: &str, @@ -84,7 +82,7 @@ pub fn load_map A>( let clone = Arc::clone(&asset); assets_write.insert(specifier.to_owned(), clone); Ok(asset) - } + }, } } @@ -120,7 +118,7 @@ pub fn load_glob(specifier: &str) -> Result>> let mut assets_write = ASSETS.write().unwrap(); assets_write.insert(specifier.to_owned(), clone); Ok(assets) - } + }, Err(error) => Err(error), } } @@ -137,13 +135,14 @@ pub fn load(specifier: &str) -> Result, Error> { load_map(specifier, |x| x) } -/// Function used to load assets from the filesystem or the cache and return a clone. +/// Function used to load assets from the filesystem or the cache and return a +/// clone. pub fn load_cloned(specifier: &str) -> Result { load::(specifier).map(|asset| (*asset).clone()) } -/// Function used to load essential assets from the filesystem or the cache. It will panic if the asset is not found. -/// Example usage: +/// Function used to load essential assets from the filesystem or the cache. It +/// will panic if the asset is not found. Example usage: /// ```no_run /// use image::DynamicImage; /// use veloren_common::assets; @@ -159,12 +158,14 @@ pub fn load_expect(specifier: &str) -> Arc { }) } -/// Function used to load essential assets from the filesystem or the cache and return a clone. It will panic if the asset is not found. +/// Function used to load essential assets from the filesystem or the cache and +/// return a clone. It will panic if the asset is not found. pub fn load_expect_cloned(specifier: &str) -> A { load_expect::(specifier).as_ref().clone() } -/// Load an asset while registering it to be watched and reloaded when it changes +/// Load an asset while registering it to be watched and reloaded when it +/// changes pub fn load_watched( specifier: &str, indicator: &mut watch::ReloadIndicator, @@ -205,14 +206,14 @@ fn reload(specifier: &str) -> Result<(), Error> { Some(a) => *a = clone, None => { assets_write.insert(specifier.to_owned(), clone); - } + }, } Ok(()) } -/// The Asset trait, which is implemented by all structures that have their data stored in the -/// filesystem. +/// The Asset trait, which is implemented by all structures that have their data +/// stored in the filesystem. pub trait Asset: Send + Sync + Sized { const ENDINGS: &'static [&'static str]; /// Parse the input file and return the correct Asset. @@ -221,6 +222,7 @@ pub trait Asset: Send + Sync + Sized { impl Asset for DynamicImage { const ENDINGS: &'static [&'static str] = &["png", "jpg"]; + fn parse(mut buf_reader: BufReader) -> Result { let mut buf = Vec::new(); buf_reader.read_to_end(&mut buf)?; @@ -230,6 +232,7 @@ impl Asset for DynamicImage { impl Asset for DotVoxData { const ENDINGS: &'static [&'static str] = &["vox"]; + fn parse(mut buf_reader: BufReader) -> Result { let mut buf = Vec::new(); buf_reader.read_to_end(&mut buf)?; @@ -240,6 +243,7 @@ impl Asset for DotVoxData { // Read a JSON file impl Asset for Value { const ENDINGS: &'static [&'static str] = &["json"]; + fn parse(buf_reader: BufReader) -> Result { Ok(serde_json::from_reader(buf_reader).unwrap()) } @@ -247,6 +251,7 @@ impl Asset for Value { impl Asset for String { const ENDINGS: &'static [&'static str] = &["glsl"]; + fn parse(mut buf_reader: BufReader) -> Result { let mut string = String::new(); buf_reader.read_to_string(&mut string)?; @@ -300,7 +305,8 @@ lazy_static! { }; } -/// Converts a specifier like "core.backgrounds.city" to ".../veloren/assets/core/backgrounds/city". +/// Converts a specifier like "core.backgrounds.city" to +/// ".../veloren/assets/core/backgrounds/city". fn unpack_specifier(specifier: &str) -> PathBuf { let mut path = ASSETS_PATH.clone(); path.push(specifier.replace(".", "/")); diff --git a/common/src/assets/watch.rs b/common/src/assets/watch.rs index 91f3b3ddad..6d79340412 100644 --- a/common/src/assets/watch.rs +++ b/common/src/assets/watch.rs @@ -19,7 +19,8 @@ lazy_static! { Mutex::new(Watcher::new().run()); } -// This will need to be adjusted when specifier mapping to asset location becomes more dynamic +// This will need to be adjusted when specifier mapping to asset location +// becomes more dynamic struct Watcher { watching: HashMap>)>, watcher: RecommendedWatcher, @@ -37,6 +38,7 @@ impl Watcher { event_rx, } } + fn watch(&mut self, path: PathBuf, handler: Handler, signal: Weak) { match self.watching.get_mut(&path) { Some((_, ref mut v)) => { @@ -46,16 +48,17 @@ impl Watcher { }) { v.push(signal); } - } + }, None => { if let Err(err) = self.watcher.watch(path.clone(), RecursiveMode::Recursive) { warn!("Could not start watching {:#?} due to: {}", &path, err); return; } self.watching.insert(path, (handler, vec![signal])); - } + }, } } + fn handle_event(&mut self, event: Event) { if let Event { kind: EventKind::Modify(_), @@ -74,7 +77,7 @@ impl Watcher { Some(signal) => { signal.store(true, Ordering::Release); true - } + }, None => false, }); } @@ -85,17 +88,22 @@ impl Watcher { } self.watching.remove(&path); } - } + }, None => { - warn!("Watching {:#?} but there are no signals for this path. The path will be unwatched.", path); + warn!( + "Watching {:#?} but there are no signals for this path. The path will \ + be unwatched.", + path + ); if let Err(err) = self.watcher.unwatch(&path) { warn!("Error unwatching: {}", err); } - } + }, } } } } + fn run(mut self) -> Sender<(PathBuf, Handler, Weak)> { let (watch_tx, watch_rx) = unbounded(); @@ -134,6 +142,7 @@ impl ReloadIndicator { paths: Vec::new(), } } + pub fn add(&mut self, path: PathBuf, reloader: F) where F: 'static + Fn() + Send, @@ -155,8 +164,7 @@ impl ReloadIndicator { error!("Could not add. Asset watcher channel disconnected."); } } + // Returns true if the watched file was changed - pub fn reloaded(&self) -> bool { - self.reloaded.swap(false, Ordering::Acquire) - } + pub fn reloaded(&self) -> bool { self.reloaded.swap(false, Ordering::Acquire) } } diff --git a/common/src/astar.rs b/common/src/astar.rs index a74ac64e67..4c153c9de9 100644 --- a/common/src/astar.rs +++ b/common/src/astar.rs @@ -1,10 +1,7 @@ use crate::path::Path; use core::cmp::Ordering::Equal; use hashbrown::{HashMap, HashSet}; -use std::cmp::Ordering; -use std::collections::BinaryHeap; -use std::f32; -use std::hash::Hash; +use std::{cmp::Ordering, collections::BinaryHeap, f32, hash::Hash}; #[derive(Copy, Clone, Debug)] pub struct PathEntry { @@ -13,9 +10,7 @@ pub struct PathEntry { } impl PartialEq for PathEntry { - fn eq(&self, other: &PathEntry) -> bool { - self.node.eq(&other.node) - } + fn eq(&self, other: &PathEntry) -> bool { self.node.eq(&other.node) } } impl Eq for PathEntry {} @@ -29,9 +24,7 @@ impl Ord for PathEntry { } impl PartialOrd for PathEntry { - fn partial_cmp(&self, other: &PathEntry) -> Option { - Some(self.cmp(other)) - } + fn partial_cmp(&self, other: &PathEntry) -> Option { Some(self.cmp(other)) } } pub enum PathResult { diff --git a/common/src/clock.rs b/common/src/clock.rs index d03a95e815..10f9d7601c 100644 --- a/common/src/clock.rs +++ b/common/src/clock.rs @@ -22,17 +22,13 @@ impl Clock { } } - pub fn get_tps(&self) -> f64 { - 1.0 / self.running_tps_average - } + pub fn get_tps(&self) -> f64 { 1.0 / self.running_tps_average } pub fn get_last_delta(&self) -> Duration { self.last_delta.unwrap_or_else(|| Duration::new(0, 0)) } - pub fn get_avg_delta(&self) -> Duration { - Duration::from_secs_f64(self.running_tps_average) - } + pub fn get_avg_delta(&self) -> Duration { Duration::from_secs_f64(self.running_tps_average) } pub fn tick(&mut self, tgt: Duration) { let delta = Instant::now().duration_since(self.last_sys_time); diff --git a/common/src/comp/agent.rs b/common/src/comp/agent.rs index 5652a0ca87..80965cf2cc 100644 --- a/common/src/comp/agent.rs +++ b/common/src/comp/agent.rs @@ -81,7 +81,5 @@ impl Activity { } impl Default for Activity { - fn default() -> Self { - Activity::Idle(Vec2::zero()) - } + fn default() -> Self { Activity::Idle(Vec2::zero()) } } diff --git a/common/src/comp/body.rs b/common/src/comp/body.rs index b1cc8dd44b..ac3569cb1d 100644 --- a/common/src/comp/body.rs +++ b/common/src/comp/body.rs @@ -45,8 +45,8 @@ pub struct BodyData { pub species: SpeciesData, } -/// Metadata intended to be stored per-body, together with data intended to be stored for each -/// species for each body. +/// Metadata intended to be stored per-body, together with data intended to be +/// stored for each species for each body. /// /// NOTE: Deliberately don't (yet?) implement serialize. #[derive(Clone, Debug, Deserialize)] @@ -76,11 +76,12 @@ impl core::ops::Index for AllBodies serde::Deserialize<'de>, - SpeciesMeta: Send + Sync + for<'de> serde::Deserialize<'de>, - > Asset for AllBodies + BodyMeta: Send + Sync + for<'de> serde::Deserialize<'de>, + SpeciesMeta: Send + Sync + for<'de> serde::Deserialize<'de>, +> Asset for AllBodies { const ENDINGS: &'static [&'static str] = &["json"]; + fn parse(buf_reader: BufReader) -> Result { serde_json::de::from_reader(buf_reader).map_err(|e| assets::Error::Internal(Arc::new(e))) } @@ -93,6 +94,7 @@ impl Body { _ => false, } } + // Note: this might need to be refined to something more complex for realistic // behavior with less cylindrical bodies (e.g. wolfs) pub fn radius(&self) -> f32 { diff --git a/common/src/comp/body/humanoid.rs b/common/src/comp/body/humanoid.rs index c75d899de2..9e77190436 100644 --- a/common/src/comp/body/humanoid.rs +++ b/common/src/comp/body/humanoid.rs @@ -310,6 +310,7 @@ impl Race { Race::Undead => &UNDEAD_HAIR_COLORS, } } + fn skin_colors(self) -> &'static [Skin] { match self { Race::Danari => &DANARI_SKIN_COLORS, @@ -320,6 +321,7 @@ impl Race { Race::Undead => &UNDEAD_SKIN_COLORS, } } + fn eye_colors(self) -> &'static [EyeColor] { match self { Race::Danari => &DANARI_EYE_COLORS, @@ -330,6 +332,7 @@ impl Race { Race::Undead => &UNDEAD_EYE_COLORS, } } + pub fn hair_color(self, val: u8) -> Rgb { self.hair_colors() .get(val as usize) @@ -337,27 +340,27 @@ impl Race { .unwrap_or((0, 0, 0)) .into() } - pub fn num_hair_colors(self) -> u8 { - self.hair_colors().len() as u8 - } + + pub fn num_hair_colors(self) -> u8 { self.hair_colors().len() as u8 } + pub fn skin_color(self, val: u8) -> Skin { self.skin_colors() .get(val as usize) .copied() .unwrap_or(Skin::Tanned) } - pub fn num_skin_colors(self) -> u8 { - self.skin_colors().len() as u8 - } + + pub fn num_skin_colors(self) -> u8 { self.skin_colors().len() as u8 } + pub fn eye_color(self, val: u8) -> EyeColor { self.eye_colors() .get(val as usize) .copied() .unwrap_or(EyeColor::NobleBlue) } - pub fn num_eye_colors(self) -> u8 { - self.eye_colors().len() as u8 - } + + pub fn num_eye_colors(self) -> u8 { self.eye_colors().len() as u8 } + pub fn num_hair_styles(self, body_type: BodyType) -> u8 { match (self, body_type) { (Race::Danari, BodyType::Female) => 2, @@ -374,6 +377,7 @@ impl Race { (Race::Undead, BodyType::Male) => 3, } } + pub fn num_accessories(self, body_type: BodyType) -> u8 { match (self, body_type) { (Race::Danari, BodyType::Female) => 1, @@ -390,6 +394,7 @@ impl Race { (Race::Undead, BodyType::Male) => 1, } } + pub fn num_beards(self, body_type: BodyType) -> u8 { match (self, body_type) { (Race::Danari, BodyType::Female) => 1, @@ -527,6 +532,7 @@ impl EyeColor { EyeColor::ExoticPurple => Rgb::new(95, 32, 111), } } + pub fn dark_rgb(self) -> Rgb { match self { EyeColor::VigorousBlack => Rgb::new(32, 32, 32), @@ -541,9 +547,8 @@ impl EyeColor { EyeColor::ExoticPurple => Rgb::new(69, 23, 80), } } - pub fn white_rgb(self) -> Rgb { - Rgb::new(255, 255, 255) - } + + pub fn white_rgb(self) -> Rgb { Rgb::new(255, 255, 255) } } #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] @@ -606,6 +611,7 @@ impl Skin { }; Rgb::from(color) } + pub fn light_rgb(self) -> Rgb { let color = match self { Self::Pale => (255, 227, 193), @@ -632,6 +638,7 @@ impl Skin { }; Rgb::from(color) } + pub fn dark_rgb(self) -> Rgb { let color = match self { Self::Pale => (229, 192, 163), diff --git a/common/src/comp/character_state.rs b/common/src/comp/character_state.rs index 1ac19ae950..ec19fa7e30 100644 --- a/common/src/comp/character_state.rs +++ b/common/src/comp/character_state.rs @@ -101,10 +101,12 @@ impl CharacterState { // Check if enum item is the same without looking at the inner data std::mem::discriminant(&self.movement) == std::mem::discriminant(&other.movement) } + pub fn is_same_action(&self, other: &Self) -> bool { // Check if enum item is the same without looking at the inner data std::mem::discriminant(&self.action) == std::mem::discriminant(&other.action) } + pub fn is_same_state(&self, other: &Self) -> bool { self.is_same_movement(other) && self.is_same_action(other) } diff --git a/common/src/comp/controller.rs b/common/src/comp/controller.rs index 6712d2a85f..2f74fffbb8 100644 --- a/common/src/comp/controller.rs +++ b/common/src/comp/controller.rs @@ -53,15 +53,11 @@ impl Input { } /// Whether input is in `InputState::Pressed` state - pub fn is_pressed(&self) -> bool { - self.state == InputState::Pressed - } + pub fn is_pressed(&self) -> bool { self.state == InputState::Pressed } /// Whether it's the first frame this input has been in /// its current state - pub fn is_just_pressed(&self) -> bool { - (self.just_changed && self.is_pressed()) - } + pub fn is_just_pressed(&self) -> bool { (self.just_changed && self.is_pressed()) } /// Whether input has been in current state longer than /// `DEFAULT_HOLD_DURATION` @@ -78,14 +74,14 @@ impl Input { self.dirty = true; self.state = InputState::Pressed; self.duration = Duration::default(); - } + }, (true, false) => { self.just_changed = true; self.dirty = true; self.state = InputState::Unpressed; self.duration = Duration::default(); - } - (_, _) => {} + }, + (_, _) => {}, }; } @@ -95,9 +91,7 @@ impl Input { } /// Returns `input::duration` - pub fn get_dur(&self) -> Duration { - self.duration - } + pub fn get_dur(&self) -> Duration { self.duration } } impl Default for Input { @@ -154,6 +148,7 @@ impl ControllerInputs { self.toggle_wield.tick(dt); self.charge.tick(dt); } + /// Updates `inputs.move_dir`. pub fn update_move_dir(&mut self) { self.move_dir = if self.move_dir.magnitude_squared() > 1.0 { @@ -163,6 +158,7 @@ impl ControllerInputs { self.move_dir }; } + /// Updates `inputs.look_dir` pub fn update_look_dir(&mut self) { self.look_dir @@ -173,17 +169,11 @@ impl ControllerInputs { impl Controller { /// Sets all inputs to default - pub fn reset(&mut self) { - *self = Self::default(); - } + pub fn reset(&mut self) { *self = Self::default(); } - pub fn clear_events(&mut self) { - self.events.clear(); - } + pub fn clear_events(&mut self) { self.events.clear(); } - pub fn push_event(&mut self, event: ControlEvent) { - self.events.push(event); - } + pub fn push_event(&mut self, event: ControlEvent) { self.events.push(event); } } impl Component for Controller { diff --git a/common/src/comp/energy.rs b/common/src/comp/energy.rs index 32169ddbff..8cf2d9224e 100644 --- a/common/src/comp/energy.rs +++ b/common/src/comp/energy.rs @@ -34,13 +34,9 @@ impl Energy { } } - pub fn current(&self) -> u32 { - self.current - } + pub fn current(&self) -> u32 { self.current } - pub fn maximum(&self) -> u32 { - self.maximum - } + pub fn maximum(&self) -> u32 { self.maximum } pub fn set_to(&mut self, amount: u32, cause: EnergySource) { let amount = amount.min(self.maximum); diff --git a/common/src/comp/inventory/item.rs b/common/src/comp/inventory/item.rs index 23365ceb76..da958ee9b9 100644 --- a/common/src/comp/inventory/item.rs +++ b/common/src/comp/inventory/item.rs @@ -7,9 +7,7 @@ use crate::{ use rand::seq::SliceRandom; use specs::{Component, FlaggedStorage}; use specs_idvs::IDVStorage; -use std::fs::File; -use std::io::BufReader; -use std::time::Duration; +use std::{fs::File, io::BufReader, time::Duration}; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum Tool { @@ -37,6 +35,7 @@ impl Tool { Tool::Debug(_) => Duration::from_millis(0), } } + pub fn attack_buildup_duration(&self) -> Duration { match self { Tool::Sword => Duration::from_millis(100), @@ -49,6 +48,7 @@ impl Tool { Tool::Debug(_) => Duration::from_millis(0), } } + pub fn attack_recover_duration(&self) -> Duration { match self { Tool::Sword => Duration::from_millis(500), @@ -61,6 +61,7 @@ impl Tool { Tool::Debug(_) => Duration::from_millis(0), } } + pub fn attack_duration(&self) -> Duration { self.attack_buildup_duration() + self.attack_recover_duration() } @@ -74,7 +75,8 @@ pub enum Debug { #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum Armor { - // TODO: Don't make armor be a body part. Wearing enemy's head is funny but also a creepy thing to do. + // TODO: Don't make armor be a body part. Wearing enemy's head is funny but also a creepy + // thing to do. Helmet, Shoulders, Chestplate, @@ -128,18 +130,17 @@ pub struct Item { impl Asset for Item { const ENDINGS: &'static [&'static str] = &["ron"]; + fn parse(buf_reader: BufReader) -> Result { Ok(ron::de::from_reader(buf_reader).unwrap()) } } impl Item { - pub fn name(&self) -> &str { - &self.name - } - pub fn description(&self) -> &str { - &self.description - } + pub fn name(&self) -> &str { &self.name } + + pub fn description(&self) -> &str { &self.description } + pub fn try_reclaim_from_block(block: Block) -> Option { match block.kind() { BlockKind::Apple => Some(assets::load_expect_cloned("common.items.apple")), @@ -149,19 +150,19 @@ impl Item { BlockKind::PinkFlower => Some(assets::load_expect_cloned("common.items.flowers.pink")), BlockKind::PurpleFlower => { Some(assets::load_expect_cloned("common.items.flowers.purple")) - } + }, BlockKind::RedFlower => Some(assets::load_expect_cloned("common.items.flowers.red")), BlockKind::WhiteFlower => { Some(assets::load_expect_cloned("common.items.flowers.white")) - } + }, BlockKind::YellowFlower => { Some(assets::load_expect_cloned("common.items.flowers.yellow")) - } + }, BlockKind::Sunflower => Some(assets::load_expect_cloned("common.items.flowers.sun")), BlockKind::LongGrass => Some(assets::load_expect_cloned("common.items.grasses.long")), BlockKind::MediumGrass => { Some(assets::load_expect_cloned("common.items.grasses.medium")) - } + }, BlockKind::ShortGrass => Some(assets::load_expect_cloned("common.items.grasses.short")), BlockKind::Chest => Some(assets::load_expect_cloned( [ diff --git a/common/src/comp/inventory/mod.rs b/common/src/comp/inventory/mod.rs index c4c3c4c875..f6833ff923 100644 --- a/common/src/comp/inventory/mod.rs +++ b/common/src/comp/inventory/mod.rs @@ -15,32 +15,30 @@ pub struct Inventory { /// Errors which the methods on `Inventory` produce #[derive(Debug)] pub enum Error { - /// The inventory is full and items could not be added. The extra items have been returned. + /// The inventory is full and items could not be added. The extra items have + /// been returned. Full(Vec), } impl Inventory { - pub fn slots(&self) -> &[Option] { - &self.slots - } + pub fn slots(&self) -> &[Option] { &self.slots } - pub fn len(&self) -> usize { - self.slots.len() - } + pub fn len(&self) -> usize { self.slots.len() } - /// Adds a new item to the first empty slot of the inventory. Returns the item again if no free - /// slot was found. + /// Adds a new item to the first empty slot of the inventory. Returns the + /// item again if no free slot was found. pub fn push(&mut self, item: Item) -> Option { match self.slots.iter_mut().find(|slot| slot.is_none()) { Some(slot) => { *slot = Some(item); None - } + }, None => Some(item), } } - /// Add a series of items to inventory, returning any which do not fit as an error. + /// Add a series of items to inventory, returning any which do not fit as an + /// error. pub fn push_all>(&mut self, mut items: I) -> Result<(), Error> { // Vec doesn't allocate for zero elements so this should be cheap let mut leftovers = Vec::new(); @@ -62,10 +60,12 @@ impl Inventory { /// Add a series of items to an inventory without giving duplicates. /// (n * m complexity) /// - /// Error if inventory cannot contain the items (is full), returning the un-added items. - /// This is a lazy inefficient implementation, as it iterates over the inventory more times - /// than necessary (n^2) and with the proper structure wouldn't need to iterate at all, but because - /// this should be fairly cold code, clarity has been favored over efficiency. + /// Error if inventory cannot contain the items (is full), returning the + /// un-added items. This is a lazy inefficient implementation, as it + /// iterates over the inventory more times than necessary (n^2) and with + /// the proper structure wouldn't need to iterate at all, but because + /// this should be fairly cold code, clarity has been favored over + /// efficiency. pub fn push_all_unique>(&mut self, mut items: I) -> Result<(), Error> { let mut leftovers = Vec::new(); for item in &mut items { @@ -80,27 +80,23 @@ impl Inventory { } } - /// Replaces an item in a specific slot of the inventory. Returns the old item or the same item again if that slot - /// was not found. + /// Replaces an item in a specific slot of the inventory. Returns the old + /// item or the same item again if that slot was not found. pub fn insert(&mut self, cell: usize, item: Item) -> Result, Item> { match self.slots.get_mut(cell) { Some(slot) => { let old = slot.take(); *slot = Some(item); Ok(old) - } + }, None => Err(item), } } - pub fn is_full(&self) -> bool { - self.slots.iter().all(|slot| slot.is_some()) - } + pub fn is_full(&self) -> bool { self.slots.iter().all(|slot| slot.is_some()) } /// O(n) count the number of items in this inventory. - pub fn count(&self) -> usize { - self.slots.iter().filter_map(|slot| slot.as_ref()).count() - } + pub fn count(&self) -> usize { self.slots.iter().filter_map(|slot| slot.as_ref()).count() } /// O(n) check if an item is in this inventory. pub fn contains(&self, item: &Item) -> bool { @@ -148,5 +144,4 @@ impl Component for InventoryUpdate { type Storage = NullStorage; } -#[cfg(test)] -mod test; +#[cfg(test)] mod test; diff --git a/common/src/comp/inventory/test.rs b/common/src/comp/inventory/test.rs index 51abc2db73..f2665d7cb5 100644 --- a/common/src/comp/inventory/test.rs +++ b/common/src/comp/inventory/test.rs @@ -8,9 +8,7 @@ lazy_static! { } /// The `Default` inventory should contain two items #[test] -fn create_default_count() { - assert_eq!(Inventory::default().count(), 2) -} +fn create_default_count() { assert_eq!(Inventory::default().count(), 2) } /// Attempting to push into a full inventory should return the same item. #[test] @@ -36,7 +34,8 @@ fn push_all_full() { assert_eq!(leftovers, TEST_ITEMS.clone()) } -/// Attempting to push uniquely into an inventory containing all the items should work fine. +/// Attempting to push uniquely into an inventory containing all the items +/// should work fine. #[test] fn push_unique_all_full() { let mut inv = Inventory { @@ -46,7 +45,8 @@ fn push_unique_all_full() { .expect("Pushing unique items into an inventory that already contains them didn't work!"); } -/// Attempting to push uniquely into an inventory containing all the items should work fine. +/// Attempting to push uniquely into an inventory containing all the items +/// should work fine. #[test] fn push_all_empty() { let mut inv = Inventory { @@ -56,7 +56,8 @@ fn push_all_empty() { .expect("Pushing items into an empty inventory didn't work!"); } -/// Attempting to push uniquely into an inventory containing all the items should work fine. +/// Attempting to push uniquely into an inventory containing all the items +/// should work fine. #[test] fn push_all_unique_empty() { let mut inv = Inventory { diff --git a/common/src/comp/location.rs b/common/src/comp/location.rs index 879c91ce5e..492ca13114 100644 --- a/common/src/comp/location.rs +++ b/common/src/comp/location.rs @@ -8,13 +8,9 @@ pub struct Waypoint { } impl Waypoint { - pub fn new(pos: Vec3) -> Self { - Self { pos } - } + pub fn new(pos: Vec3) -> Self { Self { pos } } - pub fn get_pos(&self) -> Vec3 { - self.pos - } + pub fn get_pos(&self) -> Vec3 { self.pos } } impl Component for Waypoint { @@ -25,9 +21,7 @@ impl Component for Waypoint { pub struct WaypointArea(f32); impl WaypointArea { - pub fn radius(&self) -> f32 { - self.0 - } + pub fn radius(&self) -> f32 { self.0 } } impl Component for WaypointArea { @@ -35,7 +29,5 @@ impl Component for WaypointArea { } impl Default for WaypointArea { - fn default() -> Self { - Self(5.0) - } + fn default() -> Self { Self(5.0) } } diff --git a/common/src/comp/stats.rs b/common/src/comp/stats.rs index 67d8f335d9..aaa768fee3 100644 --- a/common/src/comp/stats.rs +++ b/common/src/comp/stats.rs @@ -1,5 +1,8 @@ -use crate::comp::{body::humanoid::Race, Body}; -use crate::{comp, sync::Uid}; +use crate::{ + comp, + comp::{body::humanoid::Race, Body}, + sync::Uid, +}; use specs::{Component, FlaggedStorage}; use specs_idvs::IDVStorage; @@ -47,23 +50,16 @@ pub struct Equipment { } impl Health { - pub fn current(&self) -> u32 { - self.current - } + pub fn current(&self) -> u32 { self.current } - pub fn maximum(&self) -> u32 { - self.maximum - } + pub fn maximum(&self) -> u32 { self.maximum } pub fn set_to(&mut self, amount: u32, cause: HealthSource) { let amount = amount.min(self.maximum); - self.last_change = ( - 0.0, - HealthChange { - amount: amount as i32 - self.current as i32, - cause, - }, - ); + self.last_change = (0.0, HealthChange { + amount: amount as i32 - self.current as i32, + cause, + }); self.current = amount; } @@ -83,34 +79,23 @@ pub enum StatChangeError { Underflow, Overflow, } -use std::error::Error; -use std::fmt; +use std::{error::Error, fmt}; impl fmt::Display for StatChangeError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "{}", - match self { - Self::Underflow => "insufficient stat quantity", - Self::Overflow => "stat quantity would overflow", - } - ) + write!(f, "{}", match self { + Self::Underflow => "insufficient stat quantity", + Self::Overflow => "stat quantity would overflow", + }) } } impl Error for StatChangeError {} impl Exp { - pub fn current(&self) -> u32 { - self.current - } + pub fn current(&self) -> u32 { self.current } - pub fn maximum(&self) -> u32 { - self.maximum - } + pub fn maximum(&self) -> u32 { self.maximum } - pub fn set_current(&mut self, current: u32) { - self.current = current; - } + pub fn set_current(&mut self, current: u32) { self.current = current; } // TODO: Uncomment when needed // pub fn set_maximum(&mut self, maximum: u32) { @@ -127,17 +112,11 @@ impl Exp { } impl Level { - pub fn set_level(&mut self, level: u32) { - self.amount = level; - } + pub fn set_level(&mut self, level: u32) { self.amount = level; } - pub fn level(&self) -> u32 { - self.amount - } + pub fn level(&self) -> u32 { self.amount } - pub fn change_by(&mut self, level: u32) { - self.amount += level; - } + pub fn change_by(&mut self, level: u32) { self.amount += level; } } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -154,9 +133,8 @@ pub struct Stats { } impl Stats { - pub fn should_die(&self) -> bool { - self.health.current == 0 - } + pub fn should_die(&self) -> bool { self.health.current == 0 } + pub fn revive(&mut self) { self.health .set_to(self.health.maximum(), HealthSource::Revive); @@ -164,9 +142,7 @@ impl Stats { } // TODO: Delete this once stat points will be a thing - pub fn update_max_hp(&mut self) { - self.health.set_maximum(27 + 15 * self.level.amount); - } + pub fn update_max_hp(&mut self) { self.health.set_maximum(27 + 15 * self.level.amount); } } impl Stats { @@ -192,13 +168,10 @@ impl Stats { health: Health { current: 0, maximum: 0, - last_change: ( - 0.0, - HealthChange { - amount: 0, - cause: HealthSource::Revive, - }, - ), + last_change: (0.0, HealthChange { + amount: 0, + cause: HealthSource::Revive, + }), }, level: Level { amount: 1 }, exp: Exp { diff --git a/common/src/event.rs b/common/src/event.rs index ccf1786736..919ca04c45 100644 --- a/common/src/event.rs +++ b/common/src/event.rs @@ -12,13 +12,9 @@ pub struct SfxEventItem { } impl SfxEventItem { - pub fn new(sfx: SfxEvent, pos: Option>) -> Self { - Self { sfx, pos } - } + pub fn new(sfx: SfxEvent, pos: Option>) -> Self { Self { sfx, pos } } - pub fn at_player_position(sfx: SfxEvent) -> Self { - Self { sfx, pos: None } - } + pub fn at_player_position(sfx: SfxEvent) -> Self { Self { sfx, pos: None } } } #[derive(Copy, Clone, Debug, PartialEq, Deserialize, Hash, Eq)] @@ -131,9 +127,7 @@ impl EventBus { } } - pub fn emit(&self, event: E) { - self.queue.lock().push_front(event); - } + pub fn emit(&self, event: E) { self.queue.lock().push_front(event); } pub fn recv_all(&self) -> impl ExactSizeIterator { std::mem::replace(self.queue.lock().deref_mut(), VecDeque::new()).into_iter() @@ -146,13 +140,9 @@ pub struct Emitter<'a, E> { } impl<'a, E> Emitter<'a, E> { - pub fn emit(&mut self, event: E) { - self.events.push_front(event); - } + pub fn emit(&mut self, event: E) { self.events.push_front(event); } } impl<'a, E> Drop for Emitter<'a, E> { - fn drop(&mut self) { - self.bus.queue.lock().append(&mut self.events); - } + fn drop(&mut self) { self.bus.queue.lock().append(&mut self.events); } } diff --git a/common/src/figure/cell.rs b/common/src/figure/cell.rs index 130c92bf27..a6ada431a6 100644 --- a/common/src/figure/cell.rs +++ b/common/src/figure/cell.rs @@ -9,9 +9,7 @@ pub enum Cell { } impl Cell { - pub fn new(rgb: Rgb) -> Self { - Cell::Filled(rgb.into_array()) - } + pub fn new(rgb: Rgb) -> Self { Cell::Filled(rgb.into_array()) } pub fn get_color(&self) -> Option> { match self { @@ -22,9 +20,7 @@ impl Cell { } impl Vox for Cell { - fn empty() -> Self { - Cell::Empty - } + fn empty() -> Self { Cell::Empty } fn is_empty(&self) -> bool { match self { diff --git a/common/src/figure/mat_cell.rs b/common/src/figure/mat_cell.rs index 0154054f8c..1a51b1da74 100644 --- a/common/src/figure/mat_cell.rs +++ b/common/src/figure/mat_cell.rs @@ -10,9 +10,9 @@ pub enum Material { EyeDark, EyeLight, EyeWhite, - //HairLight, - //HairDark, - //Clothing, + /*HairLight, + *HairDark, + *Clothing, */ } #[derive(Copy, Clone, Debug, PartialEq, Eq)] @@ -23,9 +23,7 @@ pub enum MatCell { } impl Vox for MatCell { - fn empty() -> Self { - MatCell::None - } + fn empty() -> Self { MatCell::None } fn is_empty(&self) -> bool { match self { diff --git a/common/src/figure/mod.rs b/common/src/figure/mod.rs index 099311fbd7..4a3e6aa787 100644 --- a/common/src/figure/mod.rs +++ b/common/src/figure/mod.rs @@ -2,8 +2,7 @@ pub mod cell; pub mod mat_cell; pub use mat_cell::Material; -use self::cell::Cell; -use self::mat_cell::MatCell; +use self::{cell::Cell, mat_cell::MatCell}; use crate::{ vol::{IntoFullPosIterator, IntoFullVolIterator, ReadVol, SizedVol, Vox, WriteVol}, volumes::dyna::Dyna, @@ -60,6 +59,7 @@ impl Segment { self } + /// Transform cell colors pub fn map_rgb(self, transform: impl Fn(Rgb) -> Rgb) -> Self { self.map(|cell| cell.get_color().map(|rgb| Cell::new(transform(rgb)))) @@ -71,19 +71,20 @@ impl Segment { pub struct DynaUnionizer(Vec<(Dyna, Vec3)>); impl DynaUnionizer { - pub fn new() -> Self { - DynaUnionizer(Vec::new()) - } + pub fn new() -> Self { DynaUnionizer(Vec::new()) } + pub fn add(mut self, dyna: Dyna, offset: Vec3) -> Self { self.0.push((dyna, offset)); self } + pub fn maybe_add(self, maybe: Option<(Dyna, Vec3)>) -> Self { match maybe { Some((dyna, offset)) => self.add(dyna, offset), None => self, } } + pub fn unify(self) -> (Dyna, Vec3) { if self.0.is_empty() { return (Dyna::filled(Vec3::zero(), V::empty(), ()), Vec3::zero()); @@ -129,6 +130,7 @@ impl MatSegment { } vol } + /// Transform cells pub fn map(mut self, transform: impl Fn(MatCell) -> Option) -> Self { for pos in self.full_pos_iter() { @@ -139,6 +141,7 @@ impl MatSegment { self } + /// Transform cell colors pub fn map_rgb(self, transform: impl Fn(Rgb) -> Rgb) -> Self { self.map(|cell| match cell { @@ -179,7 +182,7 @@ impl From<&DotVoxData> for MatSegment { .copied() .unwrap_or_else(|| Rgb::broadcast(0)); MatCell::Normal(color) - } + }, }; vol.set( diff --git a/common/src/lib.rs b/common/src/lib.rs index e9960f6567..0595cc384d 100644 --- a/common/src/lib.rs +++ b/common/src/lib.rs @@ -2,10 +2,8 @@ #![type_length_limit = "1664759"] #![feature(trait_alias, arbitrary_enum_discriminant, label_break_value)] -#[macro_use] -extern crate serde_derive; -#[macro_use] -extern crate log; +#[macro_use] extern crate serde_derive; +#[macro_use] extern crate log; pub mod assets; pub mod astar; @@ -28,11 +26,12 @@ pub mod util; pub mod vol; pub mod volumes; -/// The networking module containing high-level wrappers of `TcpListener` and `TcpStream` (`PostOffice` and `PostBox` respectively) and data types used by both the server and client. -/// # Examples +/// The networking module containing high-level wrappers of `TcpListener` and +/// `TcpStream` (`PostOffice` and `PostBox` respectively) and data types used by +/// both the server and client. # Examples /// ``` /// use std::net::SocketAddr; -/// use veloren_common::net::{PostOffice, PostBox}; +/// use veloren_common::net::{PostBox, PostOffice}; /// /// let listen_addr = SocketAddr::from(([0, 0, 0, 0], 12345u16)); /// let conn_addr = SocketAddr::from(([127, 0, 0, 1], 12345u16)); diff --git a/common/src/msg/ecs_packet.rs b/common/src/msg/ecs_packet.rs index 6e1a2a65a7..1a8b10df2a 100644 --- a/common/src/msg/ecs_packet.rs +++ b/common/src/msg/ecs_packet.rs @@ -45,6 +45,7 @@ sum_type! { } impl sync::CompPacket for EcsCompPacket { type Phantom = EcsCompPhantom; + fn apply_insert(self, entity: specs::Entity, world: &specs::World) { match self { EcsCompPacket::Body(comp) => sync::handle_insert(comp, entity, world), @@ -62,6 +63,7 @@ impl sync::CompPacket for EcsCompPacket { EcsCompPacket::Sticky(comp) => sync::handle_insert(comp, entity, world), } } + fn apply_modify(self, entity: specs::Entity, world: &specs::World) { match self { EcsCompPacket::Body(comp) => sync::handle_modify(comp, entity, world), @@ -79,6 +81,7 @@ impl sync::CompPacket for EcsCompPacket { EcsCompPacket::Sticky(comp) => sync::handle_modify(comp, entity, world), } } + fn apply_remove(phantom: Self::Phantom, entity: specs::Entity, world: &specs::World) { match phantom { EcsCompPhantom::Body(_) => sync::handle_remove::(entity, world), @@ -88,7 +91,7 @@ impl sync::CompPacket for EcsCompPacket { EcsCompPhantom::Energy(_) => sync::handle_remove::(entity, world), EcsCompPhantom::LightEmitter(_) => { sync::handle_remove::(entity, world) - } + }, EcsCompPhantom::Item(_) => sync::handle_remove::(entity, world), EcsCompPhantom::Scale(_) => sync::handle_remove::(entity, world), EcsCompPhantom::MountState(_) => sync::handle_remove::(entity, world), diff --git a/common/src/msg/mod.rs b/common/src/msg/mod.rs index f0c19f719d..1baee67e15 100644 --- a/common/src/msg/mod.rs +++ b/common/src/msg/mod.rs @@ -3,9 +3,11 @@ pub mod ecs_packet; pub mod server; // Reexports -pub use self::client::ClientMsg; -pub use self::ecs_packet::EcsCompPacket; -pub use self::server::{PlayerListUpdate, RequestStateError, ServerError, ServerInfo, ServerMsg}; +pub use self::{ + client::ClientMsg, + ecs_packet::EcsCompPacket, + server::{PlayerListUpdate, RequestStateError, ServerError, ServerInfo, ServerMsg}, +}; #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] pub enum ClientState { diff --git a/common/src/msg/server.rs b/common/src/msg/server.rs index 6e3f9ad661..a9244b15f6 100644 --- a/common/src/msg/server.rs +++ b/common/src/msg/server.rs @@ -41,8 +41,8 @@ pub enum ServerMsg { }, PlayerListUpdate(PlayerListUpdate), StateAnswer(Result), - /// Trigger cleanup for when the client goes back to the `Registered` state from an ingame - /// state + /// Trigger cleanup for when the client goes back to the `Registered` state + /// from an ingame state ExitIngameCleanup, Ping, Pong, @@ -96,30 +96,35 @@ impl ServerMsg { message, } } + pub fn tell(message: String) -> ServerMsg { ServerMsg::ChatMsg { chat_type: ChatType::Tell, message, } } + pub fn game(message: String) -> ServerMsg { ServerMsg::ChatMsg { chat_type: ChatType::GameUpdate, message, } } + pub fn broadcast(message: String) -> ServerMsg { ServerMsg::ChatMsg { chat_type: ChatType::Broadcast, message, } } + pub fn private(message: String) -> ServerMsg { ServerMsg::ChatMsg { chat_type: ChatType::Private, message, } } + pub fn kill(message: String) -> ServerMsg { ServerMsg::ChatMsg { chat_type: ChatType::Kill, diff --git a/common/src/net/data.rs b/common/src/net/data.rs index 3239321f56..ff16b1fe94 100644 --- a/common/src/net/data.rs +++ b/common/src/net/data.rs @@ -12,7 +12,8 @@ pub enum ClientMsg { VersionInfo {}, } -/// Control message type, used in [PostBox](super::PostBox) and [PostOffice](super::PostOffice) to control threads. +/// Control message type, used in [PostBox](super::PostBox) and +/// [PostOffice](super::PostOffice) to control threads. pub enum ControlMsg { Shutdown, } diff --git a/common/src/net/post2.rs b/common/src/net/post2.rs index e06c8802ff..f117122c19 100644 --- a/common/src/net/post2.rs +++ b/common/src/net/post2.rs @@ -24,21 +24,15 @@ pub enum Error { } impl From for Error { - fn from(err: io::Error) -> Self { - Error::Io(Arc::new(err)) - } + fn from(err: io::Error) -> Self { Error::Io(Arc::new(err)) } } impl From for Error { - fn from(err: bincode::Error) -> Self { - Error::Bincode(Arc::new(err)) - } + fn from(err: bincode::Error) -> Self { Error::Bincode(Arc::new(err)) } } impl From for Error { - fn from(_error: channel::TryRecvError) -> Self { - Error::ChannelFailure - } + fn from(_error: channel::TryRecvError) -> Self { Error::ChannelFailure } } pub trait PostMsg = Serialize + DeserializeOwned + 'static + Send; @@ -63,9 +57,7 @@ impl PostOffice { }) } - pub fn error(&self) -> Option { - self.error.clone() - } + pub fn error(&self) -> Option { self.error.clone() } pub fn new_postboxes(&mut self) -> impl ExactSizeIterator> { let mut new = Vec::new(); @@ -78,11 +70,11 @@ impl PostOffice { match self.listener.accept() { Ok((stream, _sock)) => new.push(PostBox::from_stream(stream).unwrap()), Err(e) if e.kind() == io::ErrorKind::WouldBlock => break, - Err(e) if e.kind() == io::ErrorKind::Interrupted => {} + Err(e) if e.kind() == io::ErrorKind::Interrupted => {}, Err(e) => { self.error = Some(e.into()); break; - } + }, } } @@ -123,13 +115,9 @@ impl PostBox { }) } - pub fn error(&self) -> Option { - self.error.clone() - } + pub fn error(&self) -> Option { self.error.clone() } - pub fn send_message(&mut self, msg: S) { - let _ = self.send_tx.send(msg); - } + pub fn send_message(&mut self, msg: S) { let _ = self.send_tx.send(msg); } pub fn next_message(&mut self) -> Option { if self.error.is_some() { @@ -141,7 +129,7 @@ impl PostBox { Err(e) => { self.error = Some(e); None - } + }, } } @@ -159,11 +147,11 @@ impl PostBox { Err(e) => { self.error = Some(e.into()); break; - } + }, Ok(Err(e)) => { self.error = Some(e); break; - } + }, } } @@ -186,8 +174,8 @@ impl PostBox { Ok(Some(e)) | Err(e) => { recv_tx.send(Err(e.into())).unwrap(); break 'work; - } - Ok(None) => {} + }, + Ok(None) => {}, } // Try getting messages from the send channel. @@ -215,13 +203,13 @@ impl PostBox { .chunks(4096) .map(|chunk| chunk.to_vec()) .for_each(|chunk| outgoing_chunks.push_back(chunk)) - } + }, Err(channel::TryRecvError::Empty) => break, // Worker error Err(e) => { let _ = recv_tx.send(Err(e.into())); break 'work; - } + }, } } @@ -229,21 +217,21 @@ impl PostBox { for _ in 0..1000 { match outgoing_chunks.pop_front() { Some(mut chunk) => match stream.write(&chunk) { - Ok(n) if n == chunk.len() => {} + Ok(n) if n == chunk.len() => {}, Ok(n) => { outgoing_chunks.push_front(chunk.split_off(n)); break; - } + }, Err(e) if e.kind() == io::ErrorKind::WouldBlock => { // Return chunk to the queue to try again later. outgoing_chunks.push_front(chunk); break; - } + }, // Worker error Err(e) => { recv_tx.send(Err(e.into())).unwrap(); break 'work; - } + }, }, None => break, } @@ -256,12 +244,12 @@ impl PostBox { match stream.read(&mut buf) { Ok(n) => incoming_buf.extend_from_slice(&buf[0..n]), Err(e) if e.kind() == io::ErrorKind::WouldBlock => break, - Err(e) if e.kind() == io::ErrorKind::Interrupted => {} + Err(e) if e.kind() == io::ErrorKind::Interrupted => {}, // Worker error Err(e) => { recv_tx.send(Err(e.into())).unwrap(); break 'work; - } + }, } } @@ -294,14 +282,14 @@ impl PostBox { Err(err) => { println!("BINCODE ERROR: {:?}", err); recv_tx.send(Err(err.into())).unwrap() - } + }, } incoming_buf = incoming_buf.split_off(len + 9); } else { break; } - } + }, None => break, } } diff --git a/common/src/npc.rs b/common/src/npc.rs index eb578fe649..be378c9bc5 100644 --- a/common/src/npc.rs +++ b/common/src/npc.rs @@ -1,8 +1,7 @@ use crate::{assets, comp::AllBodies}; use lazy_static::lazy_static; use rand::seq::SliceRandom; -use std::str::FromStr; -use std::sync::Arc; +use std::{str::FromStr, sync::Arc}; #[derive(Clone, Copy, PartialEq)] pub enum NpcKind { @@ -28,12 +27,12 @@ pub const ALL_NPCS: [NpcKind; 6] = [ /// NOTE: Deliberately don't (yet?) implement serialize. #[derive(Clone, Debug, Deserialize)] pub struct BodyNames { - /// The keyword used to refer to this body type (e.g. via the command console). Should be - /// unique per body type. + /// The keyword used to refer to this body type (e.g. via the command + /// console). Should be unique per body type. pub keyword: String, - /// A list of canonical names for NPCs with this body types (currently used when spawning this - /// kind of NPC from the console). Going forward, these names will likely be split up by - /// species. + /// A list of canonical names for NPCs with this body types (currently used + /// when spawning this kind of NPC from the console). Going forward, + /// these names will likely be split up by species. pub names: Vec, } diff --git a/common/src/path.rs b/common/src/path.rs index e4ea0b52c7..1d21b51819 100644 --- a/common/src/path.rs +++ b/common/src/path.rs @@ -31,17 +31,11 @@ impl FromIterator for Path { } impl Path { - pub fn len(&self) -> usize { - self.nodes.len() - } + pub fn len(&self) -> usize { self.nodes.len() } - pub fn start(&self) -> Option<&T> { - self.nodes.first() - } + pub fn start(&self) -> Option<&T> { self.nodes.first() } - pub fn end(&self) -> Option<&T> { - self.nodes.last() - } + pub fn end(&self) -> Option<&T> { self.nodes.last() } } // Route: A path that can be progressed along @@ -53,23 +47,15 @@ pub struct Route { } impl From>> for Route { - fn from(path: Path>) -> Self { - Self { path, next_idx: 0 } - } + fn from(path: Path>) -> Self { Self { path, next_idx: 0 } } } impl Route { - pub fn path(&self) -> &Path> { - &self.path - } + pub fn path(&self) -> &Path> { &self.path } - pub fn next(&self) -> Option> { - self.path.nodes.get(self.next_idx).copied() - } + pub fn next(&self) -> Option> { self.path.nodes.get(self.next_idx).copied() } - pub fn is_finished(&self) -> bool { - self.next().is_none() - } + pub fn is_finished(&self) -> bool { self.next().is_none() } pub fn traverse(&mut self, vol: &V, pos: Vec3) -> Option> where @@ -89,7 +75,8 @@ impl Route { } } -/// A self-contained system that attempts to chase a moving target, only performing pathfinding if necessary +/// A self-contained system that attempts to chase a moving target, only +/// performing pathfinding if necessary #[derive(Default, Clone, Debug)] pub struct Chaser { last_search_tgt: Option>, @@ -258,15 +245,15 @@ where PathResult::Path(path) => { *astar = None; path - } + }, PathResult::None(path) => { *astar = None; path - } + }, PathResult::Exhausted(path) => { *astar = None; path - } + }, PathResult::Pending => Path::default(), } } diff --git a/common/src/ray.rs b/common/src/ray.rs index a236a07f9d..86b0e51a18 100644 --- a/common/src/ray.rs +++ b/common/src/ray.rs @@ -27,9 +27,7 @@ impl<'a, V: ReadVol, F: RayUntil, G: RayForEach> Ray<'a, V, F, G> { } } - pub fn until(self, f: F) -> Ray<'a, V, F, G> { - Ray { until: f, ..self } - } + pub fn until(self, f: F) -> Ray<'a, V, F, G> { Ray { until: f, ..self } } pub fn for_each(self, f: H) -> Ray<'a, V, F, H> { Ray { @@ -79,7 +77,7 @@ impl<'a, V: ReadVol, F: RayUntil, G: RayForEach> Ray<'a, V, F, G> { match self.vol.get(ipos).map(|vox| (vox, (self.until)(vox))) { Ok((vox, true)) => return (dist, Ok(Some(vox))), Err(err) if !self.ignore_error => return (dist, Err(err)), - _ => {} + _ => {}, } let deltas = diff --git a/common/src/region.rs b/common/src/region.rs index 295c86dc44..4b814b54ea 100644 --- a/common/src/region.rs +++ b/common/src/region.rs @@ -29,28 +29,27 @@ impl Region { events: Vec::new(), } } + /// Checks if the region contains no entities and no events - fn removable(&self) -> bool { - self.bitset.is_empty() && self.events.is_empty() - } + fn removable(&self) -> bool { self.bitset.is_empty() && self.events.is_empty() } + fn add(&mut self, id: u32, from: Option>) { self.bitset.add(id); self.events.push(Event::Entered(id, from)); } + fn remove(&mut self, id: u32, to: Option>) { self.bitset.remove(id); self.events.push(Event::Left(id, to)); } - pub fn events(&self) -> &[Event] { - &self.events - } - pub fn entities(&self) -> &BitSet { - &self.bitset - } + + pub fn events(&self) -> &[Event] { &self.events } + + pub fn entities(&self) -> &BitSet { &self.bitset } } -/// How far can an entity roam outside its region before it is switched over to the neighboring one -/// In units of blocks (i.e. world pos) +/// How far can an entity roam outside its region before it is switched over to +/// the neighboring one In units of blocks (i.e. world pos) /// Used to prevent rapid switching of entities between regions pub const TETHER_LENGTH: u32 = 16; /// Bitshift between region and world pos, i.e. log2(REGION_SIZE) @@ -76,7 +75,8 @@ const NEIGHBOR_OFFSETS: [Vec2; 8] = [ pub struct RegionMap { // Tree? // Sorted Vec? (binary search lookup) - // Sort into multiple vecs (say 32) using lower bits of morton code, then binary search via upper bits? <-- sounds very promising to me (might not be super good though?) + // Sort into multiple vecs (say 32) using lower bits of morton code, then binary search via + // upper bits? <-- sounds very promising to me (might not be super good though?) regions: IndexMap, Region, DefaultHashBuilder>, // If an entity isn't here it needs to be added to a region tracked_entities: BitSet, @@ -99,6 +99,7 @@ impl RegionMap { tick: 0, } } + // TODO maintain within a system? // TODO special case large entities pub fn tick(&mut self, pos: ReadStorage, vel: ReadStorage, entities: Entities) { @@ -154,13 +155,14 @@ impl RegionMap { // Switch self.entities_to_move.push((i, id, pos)); } - } - // Remove any non-existant entities (or just ones that lost their position component) - // TODO: distribute this between ticks + }, + // Remove any non-existant entities (or just ones that lost their position + // component) TODO: distribute this between ticks None => { - // TODO: shouldn't there be a way to extract the bitset of entities with positions directly from specs? + // TODO: shouldn't there be a way to extract the bitset of entities with + // positions directly from specs? self.entities_to_remove.push((i, id)); - } + }, } } @@ -173,7 +175,8 @@ impl RegionMap { } // Mutate - // Note entity moving is outside the whole loop so that the same entity is not checked twice (this may be fine though...) + // Note entity moving is outside the whole loop so that the same entity is not + // checked twice (this may be fine though...) while let Some((i, id, pos)) = self.entities_to_move.pop() { let (prev_key, region) = self.regions.get_index_mut(i).map(|(k, v)| (*k, v)).unwrap(); region.remove(id, Some(Self::pos_key(pos))); @@ -191,11 +194,13 @@ impl RegionMap { for key in regions_to_remove.into_iter() { // Check that the region is still removable if self.regions.get(&key).unwrap().removable() { - // Note we have to use key's here since the index can change when others are removed + // Note we have to use key's here since the index can change when others are + // removed self.remove(key); } } } + fn add_entity(&mut self, id: u32, pos: Vec3, from: Option>) { let key = Self::pos_key(pos); if let Some(region) = self.regions.get_mut(&key) { @@ -210,13 +215,13 @@ impl RegionMap { .unwrap() .add(id, None); } - fn pos_key>>(pos: P) -> Vec2 { - pos.into().map(|e| e >> REGION_LOG2) - } - pub fn key_pos(key: Vec2) -> Vec2 { - key.map(|e| e << REGION_LOG2) - } - /// Finds the region where a given entity is located using a given position to speed up the search + + fn pos_key>>(pos: P) -> Vec2 { pos.into().map(|e| e >> REGION_LOG2) } + + pub fn key_pos(key: Vec2) -> Vec2 { key.map(|e| e << REGION_LOG2) } + + /// Finds the region where a given entity is located using a given position + /// to speed up the search pub fn find_region(&self, entity: specs::Entity, pos: Vec3) -> Option> { let id = entity.id(); // Compute key for most likely region @@ -257,12 +262,15 @@ impl RegionMap { None } + fn key_index(&self, key: Vec2) -> Option { self.regions.get_full(&key).map(|(i, _, _)| i) } + fn index_key(&self, index: usize) -> Option> { self.regions.get_index(index).map(|(k, _)| k).copied() } + /// Adds a new region /// Returns the index of the region in the index map fn insert(&mut self, key: Vec2) -> usize { @@ -289,15 +297,18 @@ impl RegionMap { index } + /// Remove a region using its key fn remove(&mut self, key: Vec2) { if let Some(index) = self.key_index(key) { self.remove_index(index); } } + /// Add a region using its key fn remove_index(&mut self, index: usize) { - // Remap neighbor indices for neighbors of the region that will be moved from the end of the index map + // Remap neighbor indices for neighbors of the region that will be moved from + // the end of the index map if index != self.regions.len() - 1 { let moved_neighbors = self .regions @@ -335,10 +346,10 @@ impl RegionMap { } } } + // Returns a region given a key - pub fn get(&self, key: Vec2) -> Option<&Region> { - self.regions.get(&key) - } + pub fn get(&self, key: Vec2) -> Option<&Region> { self.regions.get(&key) } + // Returns an iterator of (Position, Region) pub fn iter(&self) -> impl Iterator, &Region)> { self.regions.iter().map(|(key, r)| (*key, r)) @@ -350,7 +361,8 @@ pub fn region_in_vd(key: Vec2, pos: Vec3, vd: f32) -> bool { let vd_extended = vd + TETHER_LENGTH as f32 * 2.0f32.sqrt(); let min_region_pos = RegionMap::key_pos(key).map(|e| e as f32); - // Should be diff to closest point on the square (which can be in the middle of an edge) + // Should be diff to closest point on the square (which can be in the middle of + // an edge) let diff = (min_region_pos - Vec2::from(pos)).map(|e| { if e < 0.0 { (e + REGION_SIZE as f32).min(0.0) diff --git a/common/src/state.rs b/common/src/state.rs index ba190df7ed..c657785b25 100644 --- a/common/src/state.rs +++ b/common/src/state.rs @@ -34,10 +34,11 @@ pub struct Time(pub f64); #[derive(Default)] pub struct DeltaTime(pub f32); -/// At what point should we stop speeding up physics to compensate for lag? If we speed physics up -/// too fast, we'd skip important physics events like collisions. This constant determines the -/// upper limit. If delta time exceeds this value, the game's physics will begin to produce time -/// lag. Ideally, we'd avoid such a situation. +/// At what point should we stop speeding up physics to compensate for lag? If +/// we speed physics up too fast, we'd skip important physics events like +/// collisions. This constant determines the upper limit. If delta time exceeds +/// this value, the game's physics will begin to produce time lag. Ideally, we'd +/// avoid such a situation. const MAX_DELTA_TIME: f32 = 1.0; const HUMANOID_JUMP_ACCEL: f32 = 26.0; @@ -47,9 +48,7 @@ pub struct BlockChange { } impl BlockChange { - pub fn set(&mut self, pos: Vec3, block: Block) { - self.blocks.insert(pos, block); - } + pub fn set(&mut self, pos: Vec3, block: Block) { self.blocks.insert(pos, block); } pub fn try_set(&mut self, pos: Vec3, block: Block) -> Option<()> { if !self.blocks.contains_key(&pos) { @@ -60,9 +59,7 @@ impl BlockChange { } } - pub fn clear(&mut self) { - self.blocks.clear(); - } + pub fn clear(&mut self) { self.blocks.clear(); } } #[derive(Default)] @@ -81,8 +78,9 @@ impl TerrainChanges { } } -/// A type used to represent game state stored on both the client and the server. This includes -/// things like entity components, terrain data, and global states like weather, time of day, etc. +/// A type used to represent game state stored on both the client and the +/// server. This includes things like entity components, terrain data, and +/// global states like weather, time of day, etc. pub struct State { ecs: specs::World, // Avoid lifetime annotation by storing a thread pool instead of the whole dispatcher @@ -101,7 +99,8 @@ impl Default for State { impl State { /// Creates ecs world and registers all the common components and resources - // TODO: Split up registering into server and client (e.g. move EventBus to the server) + // TODO: Split up registering into server and client (e.g. move + // EventBus to the server) fn setup_ecs_world() -> specs::World { let mut ecs = specs::World::new(); // Uids for sync @@ -197,56 +196,43 @@ impl State { } /// Get a reference to the internal ECS world. - pub fn ecs(&self) -> &specs::World { - &self.ecs - } + pub fn ecs(&self) -> &specs::World { &self.ecs } /// Get a mutable reference to the internal ECS world. - pub fn ecs_mut(&mut self) -> &mut specs::World { - &mut self.ecs - } + pub fn ecs_mut(&mut self) -> &mut specs::World { &mut self.ecs } - /// Get a reference to the `TerrainChanges` structure of the state. This contains - /// information about terrain state that has changed since the last game tick. - pub fn terrain_changes(&self) -> Fetch { - self.ecs.read_resource() - } + /// Get a reference to the `TerrainChanges` structure of the state. This + /// contains information about terrain state that has changed since the + /// last game tick. + pub fn terrain_changes(&self) -> Fetch { self.ecs.read_resource() } /// Get the current in-game time of day. /// - /// Note that this should not be used for physics, animations or other such localised timings. - pub fn get_time_of_day(&self) -> f64 { - self.ecs.read_resource::().0 - } + /// Note that this should not be used for physics, animations or other such + /// localised timings. + pub fn get_time_of_day(&self) -> f64 { self.ecs.read_resource::().0 } /// Get the current in-game time. /// /// Note that this does not correspond to the time of day. - pub fn get_time(&self) -> f64 { - self.ecs.read_resource::