Remove unnecessarily qualified paths

This commit is contained in:
tygyh 2022-07-15 14:08:04 +02:00
parent 61573a7800
commit 5e5698249b
184 changed files with 671 additions and 757 deletions

View File

@ -55,7 +55,7 @@ pub(crate) async fn try_connect<F>(
f: F,
) -> Result<network::Participant, crate::error::Error>
where
F: Fn(std::net::SocketAddr) -> network::ConnectAddr,
F: Fn(SocketAddr) -> network::ConnectAddr,
{
use crate::error::Error;
let mut participant = None;
@ -77,7 +77,7 @@ where
fn sort_ipv6(s: impl Iterator<Item = SocketAddr>, prefer_ipv6: bool) -> Vec<SocketAddr> {
let (mut first_addrs, mut second_addrs) =
s.partition::<Vec<_>, _>(|a| a.is_ipv6() == prefer_ipv6);
std::iter::Iterator::chain(first_addrs.drain(..), second_addrs.drain(..)).collect::<Vec<_>>()
Iterator::chain(first_addrs.drain(..), second_addrs.drain(..)).collect::<Vec<_>>()
}
#[cfg(test)]

View File

@ -183,7 +183,7 @@ impl BotClient {
}
fn create_default_body() -> Body {
comp::body::humanoid::Body {
Body {
species: comp::body::humanoid::Species::Human,
body_type: comp::body::humanoid::BodyType::Male,
hair_style: 0,
@ -208,14 +208,14 @@ impl BotClient {
let client = match self.bot_clients.get_mut(&cred.username) {
Some(c) => c,
None => {
tracing::trace!(?cred.username, "skip not logged in client");
trace!(?cred.username, "skip not logged in client");
continue;
},
};
let list = client.character_list();
if list.loading || list.characters.is_empty() {
tracing::trace!(?cred.username, "skip client as it has no character");
trace!(?cred.username, "skip client as it has no character");
continue;
}

View File

@ -36,7 +36,7 @@ impl Settings {
let mut new_path = path.to_owned();
new_path.pop();
new_path.push("settings.invalid.ron");
if let Err(e) = std::fs::rename(&path, &new_path) {
if let Err(e) = fs::rename(&path, &new_path) {
warn!(?e, ?path, ?new_path, "Failed to rename settings file.");
}
},

View File

@ -217,8 +217,8 @@ fn run_client(
let entity = client.entity();
// Move or stay still depending on specified options
// TODO: make sure server cheat protections aren't triggering
let pos = common::comp::Pos(position(index, opt) + world_center);
let vel = common::comp::Vel(Default::default());
let pos = comp::Pos(position(index, opt) + world_center);
let vel = comp::Vel(Default::default());
client
.state_mut()
.write_component_ignore_entity_dead(entity, pos);

View File

@ -321,7 +321,7 @@ impl Client {
ping_stream.send(PingMsg::Ping)?;
// Wait for initial sync
let mut ping_interval = tokio::time::interval(core::time::Duration::from_secs(1));
let mut ping_interval = tokio::time::interval(Duration::from_secs(1));
let (
state,
lod_base,
@ -601,7 +601,7 @@ impl Client {
let mut raw = vec![0u8; 4 * world_map_rgba.len()];
LittleEndian::write_u32_into(rgb, &mut raw);
Ok(Arc::new(
image::DynamicImage::ImageRgba8({
DynamicImage::ImageRgba8({
// Should not fail if the dimensions are correct.
let map =
image::ImageBuffer::from_raw(u32::from(map_size.x), u32::from(map_size.y), raw);
@ -991,7 +991,7 @@ impl Client {
.map_or(false, |cs| matches!(cs, CharacterState::Glide(_)))
}
pub fn split_swap_slots(&mut self, a: comp::slot::Slot, b: comp::slot::Slot) {
pub fn split_swap_slots(&mut self, a: Slot, b: Slot) {
match (a, b) {
(Slot::Equip(equip), slot) | (slot, Slot::Equip(equip)) => self.control_action(
ControlAction::InventoryAction(InventoryAction::Swap(equip, slot)),
@ -1004,7 +1004,7 @@ impl Client {
}
}
pub fn split_drop_slot(&mut self, slot: comp::slot::Slot) {
pub fn split_drop_slot(&mut self, slot: Slot) {
match slot {
Slot::Equip(equip) => {
self.control_action(ControlAction::InventoryAction(InventoryAction::Drop(equip)))
@ -1238,9 +1238,7 @@ impl Client {
pub fn max_group_size(&self) -> u32 { self.max_group_size }
pub fn invite(&self) -> Option<(Uid, std::time::Instant, std::time::Duration, InviteKind)> {
self.invite
}
pub fn invite(&self) -> Option<(Uid, Instant, Duration, InviteKind)> { self.invite }
pub fn group_info(&self) -> Option<(String, Uid)> {
self.group_leader.map(|l| ("Group".into(), l)) // TODO
@ -1529,7 +1527,7 @@ impl Client {
pub fn send_chat(&mut self, message: String) {
match validate_chat_msg(&message) {
Ok(()) => self.send_msg(ClientGeneral::ChatMsg(message)),
Err(ChatMsgValidationError::TooLong) => tracing::warn!(
Err(ChatMsgValidationError::TooLong) => warn!(
"Attempted to send a message that's too long (Over {} bytes)",
MAX_BYTES_CHAT_MSG
),
@ -1568,7 +1566,7 @@ impl Client {
.map_or((None, None), |inv| {
let tool_kind = |slot| {
inv.equipped(slot).and_then(|item| match &*item.kind() {
comp::item::ItemKind::Tool(tool) => Some(tool.kind),
ItemKind::Tool(tool) => Some(tool.kind),
_ => None,
})
};
@ -2013,7 +2011,7 @@ impl Client {
},
ServerGeneral::SetPlayerEntity(uid) => {
if let Some(entity) = self.state.ecs().entity_from_uid(uid.0) {
let old_player_entity = core::mem::replace(
let old_player_entity = mem::replace(
&mut *self.state.ecs_mut().write_resource(),
PlayerEntity(Some(entity)),
);
@ -2161,7 +2159,7 @@ impl Client {
timeout,
kind,
} => {
self.invite = Some((inviter, std::time::Instant::now(), timeout, kind));
self.invite = Some((inviter, Instant::now(), timeout, kind));
},
ServerGeneral::InvitePending(uid) => {
if !self.pending_invites.insert(uid) {
@ -2236,7 +2234,7 @@ impl Client {
});
},
ServerGeneral::UpdatePendingTrade(id, trade, pricing) => {
tracing::trace!("UpdatePendingTrade {:?} {:?}", id, trade);
trace!("UpdatePendingTrade {:?} {:?}", id, trade);
self.pending_trade = Some((id, trade, pricing));
},
ServerGeneral::FinishedTrade(result) => {
@ -2871,7 +2869,7 @@ mod tests {
//tick
let events_result: Result<Vec<Event>, Error> =
client.tick(comp::ControllerInputs::default(), clock.dt(), |_| {});
client.tick(ControllerInputs::default(), clock.dt(), |_| {});
//chat functionality
client.send_chat("foobar".to_string());
@ -2886,11 +2884,11 @@ mod tests {
},
Event::Disconnect => {},
Event::DisconnectionNotification(_) => {
tracing::debug!("Will be disconnected soon! :/")
debug!("Will be disconnected soon! :/")
},
Event::Notification(notification) => {
let notification: Notification = notification;
tracing::debug!("Notification: {:?}", notification);
debug!("Notification: {:?}", notification);
},
_ => {},
}

View File

@ -179,7 +179,7 @@ pub struct DotVoxAsset(pub DotVoxData);
pub struct DotVoxLoader;
impl Loader<DotVoxAsset> for DotVoxLoader {
fn load(content: std::borrow::Cow<[u8]>, _: &str) -> Result<DotVoxAsset, BoxedError> {
fn load(content: Cow<[u8]>, _: &str) -> Result<DotVoxAsset, BoxedError> {
let data = dot_vox::load_bytes(&content).map_err(|err| err.to_owned())?;
Ok(DotVoxAsset(data))
}
@ -201,7 +201,7 @@ impl Asset for ObjAsset {
pub struct ObjAssetLoader;
impl Loader<ObjAsset> for ObjAssetLoader {
fn load(content: std::borrow::Cow<[u8]>, _: &str) -> Result<ObjAsset, BoxedError> {
fn load(content: Cow<[u8]>, _: &str) -> Result<ObjAsset, BoxedError> {
let data = wavefront::Obj::from_reader(&*content)?;
Ok(ObjAsset(data))
}
@ -407,7 +407,7 @@ pub mod asset_tweak {
/// assert_eq!(y1, 10);
///
/// // you may want to remove this file later
/// std::fs::remove_file(tweak_path);
/// fs::remove_file(tweak_path);
/// ```
pub fn tweak_expect<T>(specifier: Specifier) -> T
where

View File

@ -54,7 +54,7 @@ fn main() {
}
// Check if git-lfs is working
if std::env::var("DISABLE_GIT_LFS_CHECK").is_err() && cfg!(not(feature = "no-assets")) {
if env::var("DISABLE_GIT_LFS_CHECK").is_err() && cfg!(not(feature = "no-assets")) {
let asset_path: PathBuf = ["..", "assets", "voxygen", "background", "bg_main.jpg"]
.iter()
.collect();

View File

@ -141,23 +141,23 @@ pub enum ServerGeneral {
CharacterEdited(character::CharacterId),
CharacterSuccess,
//Ingame related
GroupUpdate(comp::group::ChangeNotification<sync::Uid>),
GroupUpdate(comp::group::ChangeNotification<Uid>),
/// Indicate to the client that they are invited to join a group
Invite {
inviter: sync::Uid,
timeout: std::time::Duration,
inviter: Uid,
timeout: Duration,
kind: InviteKind,
},
/// Indicate to the client that their sent invite was not invalid and is
/// currently pending
InvitePending(sync::Uid),
InvitePending(Uid),
/// Note: this could potentially include all the failure cases such as
/// inviting yourself in which case the `InvitePending` message could be
/// removed and the client could consider their invite pending until
/// they receive this message Indicate to the client the result of their
/// invite
InviteComplete {
target: sync::Uid,
target: Uid,
answer: InviteAnswer,
kind: InviteKind,
},

View File

@ -56,7 +56,7 @@ impl WorldSyncExt for specs::World {
}
fn create_entity_synced(&mut self) -> specs::EntityBuilder {
self.create_entity().marked::<super::Uid>()
self.create_entity().marked::<Uid>()
}
fn delete_entity_and_clear_from_uid_allocator(&mut self, uid: u64) {

View File

@ -33,7 +33,7 @@ where
pub fn removed(&self) -> &BitSet { &self.removed }
pub fn record_changes<'a>(&mut self, storage: &specs::ReadStorage<'a, C>) {
pub fn record_changes<'a>(&mut self, storage: &ReadStorage<'a, C>) {
self.inserted.clear();
self.modified.clear();
self.removed.clear();
@ -86,8 +86,8 @@ impl<C: Component + Clone + Send + Sync> UpdateTracker<C> {
pub fn get_updates_for<'a, P>(
&self,
uids: &specs::ReadStorage<'a, Uid>,
storage: &specs::ReadStorage<'a, C>,
uids: &ReadStorage<'a, Uid>,
storage: &ReadStorage<'a, C>,
entity_filter: impl Join + Copy,
buf: &mut Vec<(u64, CompUpdateKind<P>)>,
) where
@ -127,7 +127,7 @@ impl<C: Component + Clone + Send + Sync> UpdateTracker<C> {
/// entity.
pub fn get_update<'a, P>(
&self,
storage: &specs::ReadStorage<'a, C>,
storage: &ReadStorage<'a, C>,
entity: Entity,
) -> Option<CompUpdateKind<P>>
where

View File

@ -50,7 +50,7 @@ fn walk_tree(dir: &Path, root: &Path) -> io::Result<Vec<Walk>> {
Ok(buff)
}
fn walk_with_migrate<OldV, NewV>(tree: Walk, from: &Path, to: &Path) -> std::io::Result<()>
fn walk_with_migrate<OldV, NewV>(tree: Walk, from: &Path, to: &Path) -> io::Result<()>
where
NewV: From<OldV>,
OldV: DeserializeOwned,

View File

@ -46,7 +46,7 @@ fn armor_stats() -> Result<(), Box<dyn Error>> {
"Description",
])?;
for item in comp::item::Item::new_from_asset_glob("common.items.armor.*")
for item in Item::new_from_asset_glob("common.items.armor.*")
.expect("Failed to iterate over item folders!")
{
match &*item.kind() {
@ -118,8 +118,8 @@ fn weapon_stats() -> Result<(), Box<dyn Error>> {
// Does all items even outside weapon folder since we check if itemkind was a
// tool anyways
let items: Vec<comp::Item> = comp::Item::new_from_asset_glob("common.items.*")
.expect("Failed to iterate over item folders!");
let items: Vec<Item> =
Item::new_from_asset_glob("common.items.*").expect("Failed to iterate over item folders!");
for item in items.iter() {
if let comp::item::ItemKind::Tool(tool) = &*item.kind() {
@ -207,8 +207,8 @@ fn all_items() -> Result<(), Box<dyn Error>> {
let mut wtr = csv::Writer::from_path("items.csv")?;
wtr.write_record(&["Path", "Name"])?;
for item in comp::item::Item::new_from_asset_glob("common.items.*")
.expect("Failed to iterate over item folders!")
for item in
Item::new_from_asset_glob("common.items.*").expect("Failed to iterate over item folders!")
{
wtr.write_record(&[
item.item_definition_id()
@ -305,7 +305,7 @@ fn entity_drops(entity_config: &str) -> Result<(), Box<dyn Error>> {
"Quantity",
])?;
fn write_entity_loot<W: std::io::Write>(
fn write_entity_loot<W: Write>(
wtr: &mut csv::Writer<W>,
asset_path: &str,
) -> Result<(), Box<dyn Error>> {

View File

@ -72,7 +72,7 @@ fn armor_stats() -> Result<(), Box<dyn Error>> {
.expect("Failed to iterate over item folders!")
{
match &*item.kind() {
comp::item::ItemKind::Armor(armor) => {
ItemKind::Armor(armor) => {
if let ArmorKind::Bag = armor.kind {
continue;
}
@ -190,20 +190,20 @@ fn armor_stats() -> Result<(), Box<dyn Error>> {
let quality = if let Some(quality_raw) = record.get(headers["Quality"])
{
match quality_raw {
"Low" => comp::item::Quality::Low,
"Common" => comp::item::Quality::Common,
"Moderate" => comp::item::Quality::Moderate,
"High" => comp::item::Quality::High,
"Epic" => comp::item::Quality::Epic,
"Legendary" => comp::item::Quality::Legendary,
"Artifact" => comp::item::Quality::Artifact,
"Debug" => comp::item::Quality::Debug,
"Low" => Quality::Low,
"Common" => Quality::Common,
"Moderate" => Quality::Moderate,
"High" => Quality::High,
"Epic" => Quality::Epic,
"Legendary" => Quality::Legendary,
"Artifact" => Quality::Artifact,
"Debug" => Quality::Debug,
_ => {
eprintln!(
"Unknown quality variant for {:?}",
item.item_definition_id()
);
comp::item::Quality::Debug
Quality::Debug
},
}
} else {
@ -211,7 +211,7 @@ fn armor_stats() -> Result<(), Box<dyn Error>> {
"Could not unwrap quality for {:?}",
item.item_definition_id()
);
comp::item::Quality::Debug
Quality::Debug
};
let description = record
@ -284,7 +284,7 @@ fn weapon_stats() -> Result<(), Box<dyn Error>> {
.expect("Failed to iterate over item folders!");
for item in items.iter() {
if let comp::item::ItemKind::Tool(tool) = &*item.kind() {
if let ItemKind::Tool(tool) = &*item.kind() {
if let Ok(ref record) = record {
if item.item_definition_id()
== ItemDefinitionId::Simple(
@ -328,19 +328,19 @@ fn weapon_stats() -> Result<(), Box<dyn Error>> {
let hands = if let Some(hands_raw) = record.get(headers["Hands"]) {
match hands_raw {
"One" | "1" | "1h" => comp::item::tool::Hands::One,
"Two" | "2" | "2h" => comp::item::tool::Hands::Two,
"One" | "1" | "1h" => Hands::One,
"Two" | "2" | "2h" => Hands::Two,
_ => {
eprintln!(
"Unknown hand variant for {:?}",
item.item_definition_id()
);
comp::item::tool::Hands::Two
Hands::Two
},
}
} else {
eprintln!("Could not unwrap hand for {:?}", item.item_definition_id());
comp::item::tool::Hands::Two
Hands::Two
};
let crit_chance: f32 = record
@ -392,20 +392,20 @@ fn weapon_stats() -> Result<(), Box<dyn Error>> {
let quality = if let Some(quality_raw) = record.get(headers["Quality"]) {
match quality_raw {
"Low" => comp::item::Quality::Low,
"Common" => comp::item::Quality::Common,
"Moderate" => comp::item::Quality::Moderate,
"High" => comp::item::Quality::High,
"Epic" => comp::item::Quality::Epic,
"Legendary" => comp::item::Quality::Legendary,
"Artifact" => comp::item::Quality::Artifact,
"Debug" => comp::item::Quality::Debug,
"Low" => Quality::Low,
"Common" => Quality::Common,
"Moderate" => Quality::Moderate,
"High" => Quality::High,
"Epic" => Quality::Epic,
"Legendary" => Quality::Legendary,
"Artifact" => Quality::Artifact,
"Debug" => Quality::Debug,
_ => {
eprintln!(
"Unknown quality variant for {:?}",
item.item_definition_id()
);
comp::item::Quality::Debug
Quality::Debug
},
}
} else {
@ -413,7 +413,7 @@ fn weapon_stats() -> Result<(), Box<dyn Error>> {
"Could not unwrap quality for {:?}",
item.item_definition_id()
);
comp::item::Quality::Debug
Quality::Debug
};
let description = record.get(headers["Description"]).expect(&format!(

View File

@ -804,7 +804,7 @@ impl ServerChatCommand {
}
/// Produce an iterator over all the available commands
pub fn iter() -> impl Iterator<Item = Self> { <Self as strum::IntoEnumIterator>::iter() }
pub fn iter() -> impl Iterator<Item = Self> { <Self as IntoEnumIterator>::iter() }
/// A message that explains what the command does
pub fn help_string(&self) -> String {

View File

@ -300,18 +300,14 @@ impl CharacterState {
pub fn behavior(&self, j: &JoinData, output_events: &mut OutputEvents) -> StateUpdate {
match &self {
CharacterState::Idle(data) => data.behavior(j, output_events),
CharacterState::Talk => states::talk::Data.behavior(j, output_events),
CharacterState::Talk => talk::Data.behavior(j, output_events),
CharacterState::Climb(data) => data.behavior(j, output_events),
CharacterState::Wallrun(data) => data.behavior(j, output_events),
CharacterState::Glide(data) => data.behavior(j, output_events),
CharacterState::GlideWield(data) => data.behavior(j, output_events),
CharacterState::Stunned(data) => data.behavior(j, output_events),
CharacterState::Sit => {
states::sit::Data::behavior(&states::sit::Data, j, output_events)
},
CharacterState::Dance => {
states::dance::Data::behavior(&states::dance::Data, j, output_events)
},
CharacterState::Sit => sit::Data::behavior(&sit::Data, j, output_events),
CharacterState::Dance => dance::Data::behavior(&dance::Data, j, output_events),
CharacterState::BasicBlock(data) => data.behavior(j, output_events),
CharacterState::Roll(data) => data.behavior(j, output_events),
CharacterState::Wielding(data) => data.behavior(j, output_events),
@ -347,17 +343,17 @@ impl CharacterState {
) -> StateUpdate {
match &self {
CharacterState::Idle(data) => data.handle_event(j, output_events, action),
CharacterState::Talk => states::talk::Data.handle_event(j, output_events, action),
CharacterState::Talk => talk::Data.handle_event(j, output_events, action),
CharacterState::Climb(data) => data.handle_event(j, output_events, action),
CharacterState::Wallrun(data) => data.handle_event(j, output_events, action),
CharacterState::Glide(data) => data.handle_event(j, output_events, action),
CharacterState::GlideWield(data) => data.handle_event(j, output_events, action),
CharacterState::Stunned(data) => data.handle_event(j, output_events, action),
CharacterState::Sit => {
states::sit::Data::handle_event(&states::sit::Data, j, output_events, action)
states::sit::Data::handle_event(&sit::Data, j, output_events, action)
},
CharacterState::Dance => {
states::dance::Data::handle_event(&states::dance::Data, j, output_events, action)
states::dance::Data::handle_event(&dance::Data, j, output_events, action)
},
CharacterState::BasicBlock(data) => data.handle_event(j, output_events, action),
CharacterState::Roll(data) => data.handle_event(j, output_events, action),

View File

@ -263,8 +263,8 @@ impl TagExampleInfo for ItemTag {
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ItemKind {
/// Something wieldable
Tool(tool::Tool),
ModularComponent(modular::ModularComponent),
Tool(Tool),
ModularComponent(ModularComponent),
Lantern(Lantern),
Armor(armor::Armor),
Glider,
@ -373,7 +373,7 @@ pub enum ItemName {
#[derive(Clone, Debug)]
pub enum ItemBase {
Simple(Arc<ItemDef>),
Modular(modular::ModularBase),
Modular(ModularBase),
}
impl Serialize for ItemBase {
@ -1262,7 +1262,7 @@ mod tests {
fn test_assets_items() {
let ids = all_item_defs_expect();
for item in ids.iter().map(|id| Item::new_from_asset_expect(id)) {
std::mem::drop(item)
drop(item)
}
}
}

View File

@ -41,8 +41,8 @@ impl MaterialStatManifest {
/// needed for tests to load it without actual assets
pub fn with_empty() -> Self {
Self {
tool_stats: hashbrown::HashMap::default(),
armor_stats: hashbrown::HashMap::default(),
tool_stats: HashMap::default(),
armor_stats: HashMap::default(),
}
}
}

View File

@ -84,7 +84,7 @@ impl ItemSpec {
let mut rng = rand::thread_rng();
match self {
ItemSpec::Item(item_asset) => Item::new_from_asset(item_asset)
.map(std::mem::drop)
.map(drop)
.map_err(ValidationError::ItemAssetError),
ItemSpec::Choice(choices) => {
// TODO: check for sanity of weigts?
@ -100,7 +100,7 @@ impl ItemSpec {
material,
hands,
} => item::modular::random_weapon(*tool, *material, *hands, &mut rng)
.map(std::mem::drop)
.map(drop)
.map_err(ValidationError::ModularWeaponCreationError),
}
}
@ -1219,7 +1219,7 @@ mod tests {
#[test]
fn test_loadout_presets() {
for preset in Preset::iter() {
std::mem::drop(LoadoutBuilder::empty().with_preset(preset));
drop(LoadoutBuilder::empty().with_preset(preset));
}
}

View File

@ -269,7 +269,7 @@ impl Inventory {
/// item or the same item again if that slot was not found.
pub fn insert_at(&mut self, inv_slot_id: InvSlotId, item: Item) -> Result<Option<Item>, Item> {
match self.slot_mut(inv_slot_id) {
Some(slot) => Ok(core::mem::replace(slot, Some(item))),
Some(slot) => Ok(mem::replace(slot, Some(item))),
None => Err(item),
}
}
@ -319,7 +319,7 @@ impl Inventory {
.err()
.and(Some(item))
} else {
let old_item = core::mem::replace(slot_item, item);
let old_item = mem::replace(slot_item, item);
// No need to recount--we know the count is the same.
Some(old_item)
})
@ -808,8 +808,8 @@ impl Inventory {
/// Used only when loading in persistence code.
pub fn persistence_update_all_item_states(
&mut self,
ability_map: &item::tool::AbilityMap,
msm: &item::MaterialStatManifest,
ability_map: &AbilityMap,
msm: &MaterialStatManifest,
) {
self.slots_mut().for_each(|slot| {
if let Some(item) = slot {

View File

@ -110,7 +110,7 @@ pub enum ArmorSlot {
}
impl Slot {
pub fn can_hold(self, item_kind: &item::ItemKind) -> bool {
pub fn can_hold(self, item_kind: &ItemKind) -> bool {
match (self, item_kind) {
(Self::Inventory(_), _) => true,
(Self::Equip(slot), item_kind) => slot.can_hold(item_kind),
@ -119,7 +119,7 @@ impl Slot {
}
impl EquipSlot {
pub fn can_hold(self, item_kind: &item::ItemKind) -> bool {
pub fn can_hold(self, item_kind: &ItemKind) -> bool {
match (self, item_kind) {
(Self::Armor(slot), ItemKind::Armor(armor::Armor { kind, .. })) => slot.can_hold(kind),
(Self::ActiveMainhand, ItemKind::Tool(_)) => true,
@ -134,7 +134,7 @@ impl EquipSlot {
}
impl ArmorSlot {
fn can_hold(self, armor: &item::armor::ArmorKind) -> bool {
fn can_hold(self, armor: &ArmorKind) -> bool {
matches!(
(self, armor),
(Self::Head, ArmorKind::Head)

View File

@ -519,12 +519,12 @@ fn get_scaling(contents: &AssetGuard<TradingPriceFile>, good: Good) -> f32 {
}
#[cfg(test)]
impl std::cmp::PartialOrd for ItemDefinitionIdOwned {
impl PartialOrd for ItemDefinitionIdOwned {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) }
}
#[cfg(test)]
impl std::cmp::Ord for ItemDefinitionIdOwned {
impl Ord for ItemDefinitionIdOwned {
fn cmp(&self, other: &Self) -> Ordering {
match self {
ItemDefinitionIdOwned::Simple(na) => match other {
@ -781,7 +781,7 @@ impl TradePricing {
for (_, recipe) in book.iter() {
let (ref asset_path, amount) = recipe.output;
if let ItemKind::ModularComponent(
crate::comp::inventory::item::modular::ModularComponent::ToolSecondaryComponent {
inventory::item::modular::ModularComponent::ToolSecondaryComponent {
toolkind,
stats: _,
hand_restriction: _,

View File

@ -405,9 +405,7 @@ impl MeleeConstructor {
if let Some(ref mut scaled) = &mut self.scaled {
*scaled = scaled.adjusted_by_stats(stats, regen);
}
if let Some(CombatEffect::Buff(combat::CombatBuff { strength, .. })) =
&mut self.damage_effect
{
if let Some(CombatEffect::Buff(CombatBuff { strength, .. })) = &mut self.damage_effect {
*strength *= stats.buff_strength;
}
self

View File

@ -126,7 +126,7 @@ pub enum ServerEvent {
},
// TODO: to avoid breakage when adding new fields, perhaps have an `NpcBuilder` type?
CreateNpc {
pos: comp::Pos,
pos: Pos,
stats: comp::Stats,
skill_set: comp::SkillSet,
health: Option<comp::Health>,
@ -142,7 +142,7 @@ pub enum ServerEvent {
projectile: Option<comp::Projectile>,
},
CreateShip {
pos: comp::Pos,
pos: Pos,
ship: comp::ship::Body,
mountable: bool,
agent: Option<comp::Agent>,

View File

@ -167,7 +167,7 @@ pub struct EntityInfo {
// Loadout
pub inventory: Vec<(u32, Item)>,
pub loadout: LoadoutBuilder,
pub make_loadout: Option<fn(LoadoutBuilder, Option<&trade::SiteInformation>) -> LoadoutBuilder>,
pub make_loadout: Option<fn(LoadoutBuilder, Option<&SiteInformation>) -> LoadoutBuilder>,
// Skills
pub skillset_asset: Option<String>,
@ -176,7 +176,7 @@ pub struct EntityInfo {
// Economy
// we can't use DHashMap, do we want to move that into common?
pub trading_information: Option<trade::SiteInformation>,
pub trading_information: Option<SiteInformation>,
//Option<hashbrown::HashMap<crate::trade::Good, (f32, f32)>>, /* price and available amount */
}
@ -394,7 +394,7 @@ impl EntityInfo {
#[must_use]
pub fn with_lazy_loadout(
mut self,
creator: fn(LoadoutBuilder, Option<&trade::SiteInformation>) -> LoadoutBuilder,
creator: fn(LoadoutBuilder, Option<&SiteInformation>) -> LoadoutBuilder,
) -> Self {
self.make_loadout = Some(creator);
self
@ -576,7 +576,7 @@ mod tests {
match field {
Meta::SkillSetAsset(asset) => {
std::mem::drop(SkillSetBuilder::from_asset_expect(&asset));
drop(SkillSetBuilder::from_asset_expect(&asset));
},
}
}

View File

@ -28,9 +28,7 @@ pub struct Is<R: Role> {
}
impl<R: Role> Is<R> {
pub fn delete(&self, data: <R::Link as Link>::DeleteData<'_>) {
R::Link::delete(&self.link, data)
}
pub fn delete(&self, data: <R::Link as Link>::DeleteData<'_>) { Link::delete(&self.link, data) }
}
impl<R: Role> Clone for Is<R> {

View File

@ -108,7 +108,7 @@ impl<T: AsRef<str>> LootSpec<T> {
warn!(?e, "error while loading item: {}", item.as_ref());
None
},
Option::Some,
Some,
),
Self::ItemQuantity(item, lower, upper) => {
let range = *lower..=*upper;
@ -148,7 +148,7 @@ impl<T: AsRef<str>> LootSpec<T> {
);
None
},
Option::Some,
Some,
),
Self::ModularWeaponPrimaryComponent {
tool,

View File

@ -54,7 +54,7 @@ pub enum Outcome {
},
SkillPointGain {
uid: Uid,
skill_tree: comp::skillset::SkillGroupKind,
skill_tree: SkillGroupKind,
total_points: u16,
},
ComboChange {

View File

@ -167,7 +167,7 @@ mod tests {
fn test_all_skillset_assets() {
let skillsets = assets::read_expect_dir::<SkillSetTree>("common.skillset", true);
for skillset in skillsets {
std::mem::drop({
drop({
let mut skillset_builder = SkillSetBuilder::default();
let nodes = &*skillset.0;
let tree = skills_from_nodes(nodes);

View File

@ -303,7 +303,7 @@ impl Body {
/// set footwear in idle data and potential state change to Skate
pub fn handle_skating(data: &JoinData, update: &mut StateUpdate) {
if let Idle(crate::states::idle::Data {
if let Idle(idle::Data {
is_sneaking,
mut footwear,
}) = data.character
@ -313,19 +313,17 @@ pub fn handle_skating(data: &JoinData, update: &mut StateUpdate) {
inv.equipped(EquipSlot::Armor(ArmorSlot::Feet))
.map(|armor| match armor.kind().as_ref() {
ItemKind::Armor(a) => a.stats(data.msm).ground_contact,
_ => crate::comp::inventory::item::armor::Friction::Normal,
_ => Friction::Normal,
})
});
update.character = Idle(crate::states::idle::Data {
update.character = Idle(idle::Data {
is_sneaking: *is_sneaking,
footwear,
});
}
if data.physics.skating_active {
update.character = CharacterState::Skate(crate::states::skate::Data::new(
data,
footwear.unwrap_or(Friction::Normal),
));
update.character =
CharacterState::Skate(skate::Data::new(data, footwear.unwrap_or(Friction::Normal)));
}
}
}
@ -687,7 +685,7 @@ pub fn attempt_talk(data: &JoinData<'_>, update: &mut StateUpdate) {
pub fn attempt_sneak(data: &JoinData<'_>, update: &mut StateUpdate) {
if data.physics.on_ground.is_some() && data.body.is_humanoid() {
update.character = CharacterState::Idle(idle::Data {
update.character = Idle(idle::Data {
is_sneaking: true,
footwear: data.character.footwear(),
});

View File

@ -341,7 +341,7 @@ pub enum Good {
impl Default for Good {
fn default() -> Self {
Good::Terrain(crate::terrain::BiomeKind::Void) // Arbitrary
Good::Terrain(BiomeKind::Void) // Arbitrary
}
}

View File

@ -165,7 +165,7 @@ impl std::ops::Neg for Dir {
/// Additionally, it avoids unnecessary calculations if they are near identical
/// Assumes `from` and `to` are normalized and returns a normalized vector
#[inline(always)]
fn slerp_normalized(from: vek::Vec3<f32>, to: vek::Vec3<f32>, factor: f32) -> vek::Vec3<f32> {
fn slerp_normalized(from: Vec3<f32>, to: Vec3<f32>, factor: f32) -> Vec3<f32> {
debug_assert!(!to.map(f32::is_nan).reduce_or());
debug_assert!(!from.map(f32::is_nan).reduce_or());
// Ensure from is normalized

View File

@ -277,9 +277,9 @@ impl<V, S: VolSize, M> Chunk<V, S, M> {
{
if vox != self.default {
let idx = self.force_idx_unchecked(pos);
core::mem::replace(&mut self.vox[idx], vox)
mem::replace(&mut self.vox[idx], vox)
} else if let Some(idx) = self.idx_unchecked(pos) {
core::mem::replace(&mut self.vox[idx], vox)
mem::replace(&mut self.vox[idx], vox)
} else {
self.default.clone()
}

View File

@ -22,7 +22,7 @@ pub enum BuildAreaError {
const RESERVED_BUILD_AREA_NAMES: &[&str] = &["world"];
impl BuildAreas {
pub fn areas(&self) -> &Depot<geom::Aabb<i32>> { &self.areas }
pub fn areas(&self) -> &Depot<Aabb<i32>> { &self.areas }
pub fn area_names(&self) -> &HashMap<String, Id<Aabb<i32>>> { &self.area_names }

View File

@ -27,7 +27,7 @@ mod tests {
state
}
fn create_entity(state: &mut State, ori: Ori) -> specs::Entity {
fn create_entity(state: &mut State, ori: Ori) -> Entity {
let body = common::comp::Body::Humanoid(common::comp::humanoid::Body::random_with(
&mut thread_rng(),
&common::comp::humanoid::Species::Human,

View File

@ -36,14 +36,14 @@ fn dont_fall_outside_world() -> Result<(), Box<dyn Error>> {
assert_relative_eq!(pos.0.x, 1000.0);
assert_relative_eq!(pos.0.y, 1000.0);
assert_relative_eq!(pos.0.z, 265.0);
assert_eq!(vel.0, vek::Vec3::zero());
assert_eq!(vel.0, Vec3::zero());
utils::tick(&mut state, DT);
let (pos, vel, _) = utils::get_transform(&state, p1)?;
assert_relative_eq!(pos.0.x, 1000.0);
assert_relative_eq!(pos.0.y, 1000.0);
assert_relative_eq!(pos.0.z, 265.0);
assert_eq!(vel.0, vek::Vec3::zero());
assert_eq!(vel.0, Vec3::zero());
Ok(())
}
@ -56,7 +56,7 @@ fn fall_simple() -> Result<(), Box<dyn Error>> {
assert_relative_eq!(pos.0.x, 16.0);
assert_relative_eq!(pos.0.y, 16.0);
assert_relative_eq!(pos.0.z, 265.0);
assert_eq!(vel.0, vek::Vec3::zero());
assert_eq!(vel.0, Vec3::zero());
utils::tick(&mut state, DT);
let (pos, vel, _) = utils::get_transform(&state, p1)?;
@ -145,7 +145,7 @@ fn walk_simple() -> Result<(), Box<dyn Error>> {
}
let (pos, vel, _) = utils::get_transform(&state, p1)?;
assert_relative_eq!(pos.0.z, 257.0); // make sure it landed on ground
assert_eq!(vel.0, vek::Vec3::zero());
assert_eq!(vel.0, Vec3::zero());
let mut actions = Controller::default();
actions.inputs.move_dir = Vec2::new(1.0, 0.0);

View File

@ -62,7 +62,7 @@ fn main() {
}
fn file_exists(file: &str) -> Result<(), String> {
let file: std::path::PathBuf = shellexpand::tilde(file).parse().unwrap();
let file: PathBuf = shellexpand::tilde(file).parse().unwrap();
if file.exists() {
Ok(())
} else {

View File

@ -192,16 +192,16 @@ fn client(address: ConnectAddr, runtime: Arc<Runtime>) {
}
if id > 2000000 {
println!("Stop");
std::thread::sleep(std::time::Duration::from_millis(2000));
thread::sleep(Duration::from_millis(2000));
break;
}
}
drop(s1);
std::thread::sleep(std::time::Duration::from_millis(2000));
thread::sleep(Duration::from_millis(2000));
info!("Closing participant");
runtime.block_on(p1.disconnect()).unwrap();
std::thread::sleep(std::time::Duration::from_millis(2000));
thread::sleep(Duration::from_millis(2000));
info!("DROPPING! client");
drop(client);
std::thread::sleep(std::time::Duration::from_millis(2000));
thread::sleep(Duration::from_millis(2000));
}

View File

@ -192,8 +192,8 @@ mod utils {
cap: usize,
metrics: Option<ProtocolMetricCache>,
) -> [(MpscSendProtocol<ACDrain>, MpscRecvProtocol<ACSink>); 2] {
let (s1, r1) = async_channel::bounded(cap);
let (s2, r2) = async_channel::bounded(cap);
let (s1, r1) = bounded(cap);
let (s2, r2) = bounded(cap);
let m = metrics.unwrap_or_else(|| {
ProtocolMetricCache::new("mpsc", Arc::new(ProtocolMetrics::new().unwrap()))
});
@ -222,8 +222,8 @@ mod utils {
cap: usize,
metrics: Option<ProtocolMetricCache>,
) -> [(TcpSendProtocol<TcpDrain>, TcpRecvProtocol<TcpSink>); 2] {
let (s1, r1) = async_channel::bounded(cap);
let (s2, r2) = async_channel::bounded(cap);
let (s1, r1) = bounded(cap);
let (s2, r2) = bounded(cap);
let m = metrics.unwrap_or_else(|| {
ProtocolMetricCache::new("tcp", Arc::new(ProtocolMetrics::new().unwrap()))
});
@ -252,8 +252,8 @@ mod utils {
cap: usize,
metrics: Option<ProtocolMetricCache>,
) -> [(QuicSendProtocol<QuicDrain>, QuicRecvProtocol<QuicSink>); 2] {
let (s1, r1) = async_channel::bounded(cap);
let (s2, r2) = async_channel::bounded(cap);
let (s1, r1) = bounded(cap);
let (s2, r2) = bounded(cap);
let m = metrics.unwrap_or_else(|| {
ProtocolMetricCache::new("quic", Arc::new(ProtocolMetrics::new().unwrap()))
});

View File

@ -202,8 +202,8 @@ pub mod test_utils {
cap: usize,
metrics: Option<ProtocolMetricCache>,
) -> [(MpscSendProtocol<ACDrain>, MpscRecvProtocol<ACSink>); 2] {
let (s1, r1) = async_channel::bounded(cap);
let (s2, r2) = async_channel::bounded(cap);
let (s1, r1) = bounded(cap);
let (s2, r2) = bounded(cap);
let m = metrics.unwrap_or_else(|| {
ProtocolMetricCache::new("mpsc", Arc::new(ProtocolMetrics::new().unwrap()))
});

View File

@ -543,8 +543,8 @@ mod test_utils {
drop_ratio: f32,
metrics: Option<ProtocolMetricCache>,
) -> [(QuicSendProtocol<QuicDrain>, QuicRecvProtocol<QuicSink>); 2] {
let (s1, r1) = async_channel::bounded(cap);
let (s2, r2) = async_channel::bounded(cap);
let (s1, r1) = bounded(cap);
let (s2, r2) = bounded(cap);
let m = metrics.unwrap_or_else(|| {
ProtocolMetricCache::new("quic", Arc::new(ProtocolMetrics::new().unwrap()))
});
@ -804,8 +804,7 @@ mod tests {
let sid = Sid::new(1);
let (s, r) = async_channel::bounded(10);
let m = ProtocolMetricCache::new("quic", Arc::new(ProtocolMetrics::new().unwrap()));
let mut r =
super::QuicRecvProtocol::new(super::test_utils::QuicSink { receiver: r }, m.clone());
let mut r = super::QuicRecvProtocol::new(QuicSink { receiver: r }, m.clone());
const DATA1: &[u8; 69] =
b"We need to make sure that its okay to send OPEN_STREAM and DATA_HEAD ";
@ -861,8 +860,7 @@ mod tests {
let sid = Sid::new(1);
let (s, r) = async_channel::bounded(10);
let m = ProtocolMetricCache::new("quic", Arc::new(ProtocolMetrics::new().unwrap()));
let mut r =
super::QuicRecvProtocol::new(super::test_utils::QuicSink { receiver: r }, m.clone());
let mut r = super::QuicRecvProtocol::new(QuicSink { receiver: r }, m.clone());
let mut bytes = BytesMut::with_capacity(1500);
OTFrame::OpenStream {

View File

@ -360,8 +360,8 @@ mod test_utils {
cap: usize,
metrics: Option<ProtocolMetricCache>,
) -> [(TcpSendProtocol<TcpDrain>, TcpRecvProtocol<TcpSink>); 2] {
let (s1, r1) = async_channel::bounded(cap);
let (s2, r2) = async_channel::bounded(cap);
let (s1, r1) = bounded(cap);
let (s2, r2) = bounded(cap);
let m = metrics.unwrap_or_else(|| {
ProtocolMetricCache::new("tcp", Arc::new(ProtocolMetrics::new().unwrap()))
});
@ -603,8 +603,7 @@ mod tests {
let sid = Sid::new(1);
let (s, r) = async_channel::bounded(10);
let m = ProtocolMetricCache::new("tcp", Arc::new(ProtocolMetrics::new().unwrap()));
let mut r =
super::TcpRecvProtocol::new(super::test_utils::TcpSink { receiver: r }, m.clone());
let mut r = super::TcpRecvProtocol::new(TcpSink { receiver: r }, m.clone());
const DATA1: &[u8; 69] =
b"We need to make sure that its okay to send OPEN_STREAM and DATA_HEAD ";
@ -653,8 +652,7 @@ mod tests {
let sid = Sid::new(1);
let (s, r) = async_channel::bounded(10);
let m = ProtocolMetricCache::new("tcp", Arc::new(ProtocolMetrics::new().unwrap()));
let mut r =
super::TcpRecvProtocol::new(super::test_utils::TcpSink { receiver: r }, m.clone());
let mut r = super::TcpRecvProtocol::new(TcpSink { receiver: r }, m.clone());
let mut bytes = BytesMut::with_capacity(1500);
OTFrame::OpenStream {

View File

@ -107,7 +107,7 @@ pub struct Stream {
#[derive(Debug)]
pub enum NetworkError {
NetworkClosed,
ListenFailed(std::io::Error),
ListenFailed(io::Error),
ConnectFailed(NetworkConnectError),
}
@ -117,7 +117,7 @@ pub enum NetworkConnectError {
/// Either a Pid UUID clash or you are trying to hijack a connection
InvalidSecret,
Handshake(InitProtocolError<ProtocolsError>),
Io(std::io::Error),
Io(io::Error),
}
/// Error type thrown by [`Participants`](Participant) methods
@ -168,7 +168,7 @@ pub struct StreamParams {
/// use tokio::runtime::Runtime;
/// use veloren_network::{Network, ConnectAddr, ListenAddr, Pid};
///
/// # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // Create a Network, listen on port `2999` to accept connections and connect to port `8080` to connect to a (pseudo) database Application
/// let runtime = Runtime::new().unwrap();
/// let network = Network::new(Pid::new(), &runtime);
@ -272,7 +272,7 @@ impl Network {
#[cfg(feature = "metrics")] registry: Option<&Registry>,
) -> Self {
let p = participant_id;
let span = tracing::info_span!("network", ?p);
let span = info_span!("network", ?p);
span.in_scope(|| trace!("Starting Network"));
let (scheduler, listen_sender, connect_sender, connected_receiver, shutdown_sender) =
Scheduler::new(
@ -295,7 +295,7 @@ impl Network {
scheduler.run().await;
trace!("Stopping scheduler and his own thread");
}
.instrument(tracing::info_span!("network", ?p)),
.instrument(info_span!("network", ?p)),
);
Self {
local_pid: participant_id,
@ -340,7 +340,7 @@ impl Network {
/// [`ListenAddr`]: crate::api::ListenAddr
#[instrument(name="network", skip(self, address), fields(p = %self.local_pid))]
pub async fn listen(&self, address: ListenAddr) -> Result<(), NetworkError> {
let (s2a_result_s, s2a_result_r) = oneshot::channel::<tokio::io::Result<()>>();
let (s2a_result_s, s2a_result_r) = oneshot::channel::<io::Result<()>>();
debug!(?address, "listening on address");
self.listen_sender
.lock()
@ -428,7 +428,7 @@ impl Network {
/// use tokio::runtime::Runtime;
/// use veloren_network::{ConnectAddr, ListenAddr, Network, Pid};
///
/// # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // Create a Network, listen on port `2020` TCP and opens returns their Pid
/// let runtime = Runtime::new().unwrap();
/// let network = Network::new(Pid::new(), &runtime);
@ -567,7 +567,7 @@ impl Participant {
/// use tokio::runtime::Runtime;
/// use veloren_network::{ConnectAddr, ListenAddr, Network, Pid, Promises};
///
/// # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // Create a Network, connect on port 2100 and open a stream
/// let runtime = Runtime::new().unwrap();
/// let network = Network::new(Pid::new(), &runtime);
@ -634,7 +634,7 @@ impl Participant {
/// use tokio::runtime::Runtime;
/// use veloren_network::{Network, Pid, ListenAddr, ConnectAddr, Promises};
///
/// # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // Create a Network, connect on port 2110 and wait for the other side to open a stream
/// // Note: It's quite unusual to actively connect, but then wait on a stream to be connected, usually the Application taking initiative want's to also create the first Stream.
/// let runtime = Runtime::new().unwrap();
@ -691,7 +691,7 @@ impl Participant {
/// use tokio::runtime::Runtime;
/// use veloren_network::{Network, Pid, ListenAddr, ConnectAddr};
///
/// # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // Create a Network, listen on port `2030` TCP and opens returns their Pid and close connection.
/// let runtime = Runtime::new().unwrap();
/// let network = Network::new(Pid::new(), &runtime);
@ -775,7 +775,7 @@ impl Participant {
/// use tokio::runtime::Runtime;
/// use veloren_network::{Network, Pid, ListenAddr, ConnectAddr, Promises, ParticipantEvent};
///
/// # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // Create a Network, connect on port 2040 and wait for the other side to open a stream
/// // Note: It's quite unusual to actively connect, but then wait on a stream to be connected, usually the Application taking initiative want's to also create the first Stream.
/// let runtime = Runtime::new().unwrap();
@ -889,7 +889,7 @@ impl Stream {
/// use tokio::runtime::Runtime;
/// use veloren_network::{Network, ListenAddr, ConnectAddr, Pid};
///
/// # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // Create a Network, listen on Port `2200` and wait for a Stream to be opened, then answer `Hello World`
/// let runtime = Runtime::new().unwrap();
/// let network = Network::new(Pid::new(), &runtime);
@ -931,7 +931,7 @@ impl Stream {
/// use bincode;
/// use veloren_network::{Network, ListenAddr, ConnectAddr, Pid, Message};
///
/// # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let runtime = Runtime::new().unwrap();
/// let network = Network::new(Pid::new(), &runtime);
/// # let remote1 = Network::new(Pid::new(), &runtime);
@ -999,7 +999,7 @@ impl Stream {
/// use tokio::runtime::Runtime;
/// use veloren_network::{Network, ListenAddr, ConnectAddr, Pid};
///
/// # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // Create a Network, listen on Port `2220` and wait for a Stream to be opened, then listen on it
/// let runtime = Runtime::new().unwrap();
/// let network = Network::new(Pid::new(), &runtime);
@ -1033,7 +1033,7 @@ impl Stream {
/// use tokio::runtime::Runtime;
/// use veloren_network::{Network, ListenAddr, ConnectAddr, Pid};
///
/// # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // Create a Network, listen on Port `2230` and wait for a Stream to be opened, then listen on it
/// let runtime = Runtime::new().unwrap();
/// let network = Network::new(Pid::new(), &runtime);
@ -1089,7 +1089,7 @@ impl Stream {
/// use tokio::runtime::Runtime;
/// use veloren_network::{Network, ListenAddr, ConnectAddr, Pid};
///
/// # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // Create a Network, listen on Port `2240` and wait for a Stream to be opened, then listen on it
/// let runtime = Runtime::new().unwrap();
/// let network = Network::new(Pid::new(), &runtime);
@ -1141,7 +1141,7 @@ impl Stream {
}
}
impl core::cmp::PartialEq for Participant {
impl PartialEq for Participant {
fn eq(&self, other: &Self) -> bool {
//don't check local_pid, 2 Participant from different network should match if
// they are the "same"
@ -1293,8 +1293,8 @@ impl From<oneshot::error::RecvError> for NetworkError {
fn from(_err: oneshot::error::RecvError) -> Self { NetworkError::NetworkClosed }
}
impl From<std::io::Error> for NetworkError {
fn from(_err: std::io::Error) -> Self { NetworkError::NetworkClosed }
impl From<io::Error> for NetworkError {
fn from(_err: io::Error) -> Self { NetworkError::NetworkClosed }
}
impl From<Box<bincode::ErrorKind>> for StreamError {
@ -1346,7 +1346,7 @@ impl core::fmt::Display for NetworkConnectError {
}
/// implementing PartialEq as it's super convenient in tests
impl core::cmp::PartialEq for StreamError {
impl PartialEq for StreamError {
fn eq(&self, other: &Self) -> bool {
match self {
StreamError::StreamClosed => match other {

View File

@ -94,7 +94,7 @@ impl Protocols {
metrics: Arc<ProtocolMetrics>,
s2s_stop_listening_r: oneshot::Receiver<()>,
c2s_protocol_s: mpsc::UnboundedSender<C2sProtocol>,
) -> std::io::Result<()> {
) -> io::Result<()> {
use socket2::{Domain, Socket, Type};
let domain = Domain::for_address(addr);
let socket2_socket = Socket::new(domain, Type::STREAM, None)?;
@ -109,7 +109,7 @@ impl Protocols {
socket2_socket.bind(&socket2_addr)?;
socket2_socket.listen(1024)?;
let std_listener: std::net::TcpListener = socket2_socket.into();
let listener = tokio::net::TcpListener::from_std(std_listener)?;
let listener = net::TcpListener::from_std(std_listener)?;
trace!(?addr, "Tcp Listener bound");
let mut end_receiver = s2s_stop_listening_r.fuse();
tokio::spawn(async move {
@ -143,7 +143,7 @@ impl Protocols {
Ok(())
}
pub(crate) fn new_tcp(stream: tokio::net::TcpStream, metrics: ProtocolMetricCache) -> Self {
pub(crate) fn new_tcp(stream: net::TcpStream, metrics: ProtocolMetricCache) -> Self {
let (r, w) = stream.into_split();
let sp = TcpSendProtocol::new(TcpDrain { half: w }, metrics.clone());
let rp = TcpRecvProtocol::new(
@ -453,14 +453,14 @@ impl network_protocol::RecvProtocol for RecvProtocols {
#[derive(Debug)]
pub enum MpscError {
Send(tokio::sync::mpsc::error::SendError<network_protocol::MpscMsg>),
Send(mpsc::error::SendError<MpscMsg>),
Recv,
}
#[cfg(feature = "quic")]
#[derive(Debug)]
pub enum QuicError {
Send(std::io::Error),
Send(io::Error),
Connection(quinn::ConnectionError),
Write(quinn::WriteError),
Read(quinn::ReadError),
@ -470,8 +470,8 @@ pub enum QuicError {
/// Error types for Protocols
#[derive(Debug)]
pub enum ProtocolsError {
Tcp(std::io::Error),
Udp(std::io::Error),
Tcp(io::Error),
Udp(io::Error),
#[cfg(feature = "quic")]
Quic(QuicError),
Mpsc(MpscError),
@ -527,12 +527,12 @@ impl UnreliableSink for TcpSink {
//// MPSC
#[derive(Debug)]
pub struct MpscDrain {
sender: tokio::sync::mpsc::Sender<MpscMsg>,
sender: mpsc::Sender<MpscMsg>,
}
#[derive(Debug)]
pub struct MpscSink {
receiver: tokio::sync::mpsc::Receiver<MpscMsg>,
receiver: mpsc::Receiver<MpscMsg>,
}
#[async_trait]
@ -666,7 +666,7 @@ impl UnreliableSink for QuicSink {
let (mut buffer, result, mut recvstream, id) = loop {
use futures_util::FutureExt;
// first handle all bi streams!
let (a, b) = tokio::select! {
let (a, b) = select! {
biased;
Some(n) = self.bi.next().fuse() => (Some(n), None),
Some(n) = self.recvstreams_r.recv().fuse() => (None, Some(n)),

View File

@ -44,7 +44,7 @@
//! use veloren_network::{ConnectAddr, ListenAddr, Network, Pid, Promises};
//!
//! // Client
//! async fn client(runtime: &Runtime) -> std::result::Result<(), Box<dyn std::error::Error>> {
//! async fn client(runtime: &Runtime) -> Result<(), Box<dyn std::error::Error>> {
//! sleep(std::time::Duration::from_secs(1)).await; // `connect` MUST be after `listen`
//! let client_network = Network::new(Pid::new(), runtime);
//! let server = client_network
@ -58,7 +58,7 @@
//! }
//!
//! // Server
//! async fn server(runtime: &Runtime) -> std::result::Result<(), Box<dyn std::error::Error>> {
//! async fn server(runtime: &Runtime) -> Result<(), Box<dyn std::error::Error>> {
//! let server_network = Network::new(Pid::new(), runtime);
//! server_network
//! .listen(ListenAddr::Tcp("127.0.0.1:12345".parse().unwrap()))
@ -71,7 +71,7 @@
//! Ok(())
//! }
//!
//! fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let runtime = Runtime::new().unwrap();
//! runtime.block_on(async {
//! let (result_c, result_s) = join!(client(&runtime), server(&runtime),);

View File

@ -75,7 +75,7 @@ impl Message {
/// # use tokio::runtime::Runtime;
/// # use std::sync::Arc;
///
/// # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // Create a Network, listen on Port `2300` and wait for a Stream to be opened, then listen on it
/// # let runtime = Runtime::new().unwrap();
/// # let network = Network::new(Pid::new(), &runtime);

View File

@ -175,7 +175,7 @@ impl NetworkMetrics {
Ok(())
}
pub(crate) fn connect_requests_cache(&self, protocol: &ListenAddr) -> prometheus::IntCounter {
pub(crate) fn connect_requests_cache(&self, protocol: &ListenAddr) -> IntCounter {
self.incoming_connections_total
.with_label_values(&[protocollisten_name(protocol)])
}

View File

@ -474,7 +474,7 @@ impl BParticipant {
recv_protocols.is_empty()
};
let mut defered_orphan = DeferredTracer::new(tracing::Level::WARN);
let mut defered_orphan = DeferredTracer::new(Level::WARN);
loop {
let (event, addp, remp) = select!(
@ -705,7 +705,7 @@ impl BParticipant {
.map(|(timeout_time, _)| *timeout_time)
.unwrap_or_default(),
);
let timeout = tokio::select! {
let timeout = select! {
_ = wait_for_manager() => false,
_ = timeout => true,
};
@ -825,7 +825,7 @@ mod tests {
watch::Receiver<f32>,
JoinHandle<()>,
) {
let runtime = Arc::new(tokio::runtime::Runtime::new().unwrap());
let runtime = Arc::new(Runtime::new().unwrap());
let runtime_clone = Arc::clone(&runtime);
let (b2s_prio_statistic_s, b2s_prio_statistic_r) =

View File

@ -402,7 +402,7 @@ impl Scheduler {
use network_protocol::InitProtocol;
let init_result = protocol
.initialize(send_handshake, local_pid, local_secret)
.instrument(tracing::info_span!("handshake", ?cid))
.instrument(info_span!("handshake", ?cid))
.await;
match init_result {
Ok((pid, sid, secret)) => {
@ -447,7 +447,7 @@ impl Scheduler {
tokio::spawn(
bparticipant
.run(participant_channels.b2s_prio_statistic_s)
.instrument(tracing::info_span!("remote", ?p)),
.instrument(info_span!("remote", ?p)),
);
//create a new channel within BParticipant and wait for it to run
let (b2s_create_channel_done_s, b2s_create_channel_done_r) =
@ -516,7 +516,7 @@ impl Scheduler {
},
}
}
.instrument(tracing::info_span!("")),
.instrument(info_span!("")),
); /*WORKAROUND FOR SPAN NOT TO GET LOST*/
}
}

View File

@ -15,11 +15,11 @@ use veloren_network::{ConnectAddr, ListenAddr, Network, Participant, Pid, Promis
// sleep time when only internal rust calculations are done
#[allow(dead_code)]
pub const SLEEP_INTERNAL: std::time::Duration = std::time::Duration::from_millis(3000);
pub const SLEEP_INTERNAL: Duration = Duration::from_millis(3000);
// sleep time when we interact with the system, e.g. actually send TCP/UDP
// package
#[allow(dead_code)]
pub const SLEEP_EXTERNAL: std::time::Duration = std::time::Duration::from_millis(5000);
pub const SLEEP_EXTERNAL: Duration = Duration::from_millis(5000);
#[allow(dead_code)]
pub fn setup(tracing: bool, sleep: u64) -> (u64, u64) {

View File

@ -118,7 +118,7 @@ fn stream_simple_udp_3msg() {
#[test]
#[ignore]
fn tcp_and_udp_2_connections() -> std::result::Result<(), Box<dyn std::error::Error>> {
fn tcp_and_udp_2_connections() -> Result<(), Box<dyn std::error::Error>> {
let (_, _) = helper::setup(false, 0);
let r = Arc::new(Runtime::new().unwrap());
let network = Network::new(Pid::new(), &r);
@ -145,7 +145,7 @@ fn tcp_and_udp_2_connections() -> std::result::Result<(), Box<dyn std::error::Er
#[test]
#[ignore]
fn failed_listen_on_used_ports() -> std::result::Result<(), Box<dyn std::error::Error>> {
fn failed_listen_on_used_ports() -> Result<(), Box<dyn std::error::Error>> {
let (_, _) = helper::setup(false, 0);
let r = Arc::new(Runtime::new().unwrap());
let network = Network::new(Pid::new(), &r);
@ -176,7 +176,7 @@ fn failed_listen_on_used_ports() -> std::result::Result<(), Box<dyn std::error::
/// So i rather put the same test into a unit test, these are now duplicate to
/// the api, but are left here, just to be save!
#[test]
fn api_stream_send_main() -> std::result::Result<(), Box<dyn std::error::Error>> {
fn api_stream_send_main() -> Result<(), Box<dyn std::error::Error>> {
let (_, _) = helper::setup(false, 0);
// Create a Network, listen on Port `1200` and wait for a Stream to be opened,
// then answer `Hello World`
@ -205,7 +205,7 @@ fn api_stream_send_main() -> std::result::Result<(), Box<dyn std::error::Error>>
}
#[test]
fn api_stream_recv_main() -> std::result::Result<(), Box<dyn std::error::Error>> {
fn api_stream_recv_main() -> Result<(), Box<dyn std::error::Error>> {
let (_, _) = helper::setup(false, 0);
// Create a Network, listen on Port `1220` and wait for a Stream to be opened,
// then listen on it

View File

@ -55,7 +55,7 @@ pub fn read_input<T>(ptr: i64, len: i64) -> Result<T, &'static str>
where
T: DeserializeOwned,
{
let slice = unsafe { ::std::slice::from_raw_parts(from_i64(ptr) as _, from_i64(len) as _) };
let slice = unsafe { std::slice::from_raw_parts(from_i64(ptr) as _, from_i64(len) as _) };
bincode::deserialize(slice).map_err(|_| "Failed to deserialize function input")
}

View File

@ -31,7 +31,7 @@ impl Settings {
let mut new_path = path.to_owned();
new_path.pop();
new_path.push("settings.invalid.ron");
if let Err(e) = std::fs::rename(&path, &new_path) {
if let Err(e) = fs::rename(&path, &new_path) {
warn!(?e, ?path, ?new_path, "Failed to rename settings file.");
}
},

View File

@ -100,7 +100,7 @@ impl Tui {
},
Ok(_) => {
debug!(?line, "basic mode: command entered");
crate::cli::parse_command(line.trim(), &mut msg_s);
cli::parse_command(line.trim(), &mut msg_s);
},
}
}

View File

@ -273,7 +273,7 @@ fn uuid(server: &Server, entity: EcsEntity, descriptor: &str) -> CmdResult<Uuid>
.ok_or_else(|| format!("Cannot get player information for {:?}", descriptor))
}
fn real_role(server: &Server, uuid: Uuid, descriptor: &str) -> CmdResult<comp::AdminRole> {
fn real_role(server: &Server, uuid: Uuid, descriptor: &str) -> CmdResult<AdminRole> {
server
.editable_settings()
.admins
@ -294,7 +294,7 @@ fn uid(server: &Server, target: EcsEntity, descriptor: &str) -> CmdResult<Uid> {
.ok_or_else(|| format!("Cannot get uid for {:?}", descriptor))
}
fn area(server: &mut Server, area_name: &str) -> CmdResult<depot::Id<vek::Aabb<i32>>> {
fn area(server: &mut Server, area_name: &str) -> CmdResult<depot::Id<Aabb<i32>>> {
server
.state
.mut_resource::<BuildAreas>()
@ -458,13 +458,13 @@ fn handle_drop_all(
if let Some(mut inventory) = server
.state
.ecs()
.write_storage::<comp::Inventory>()
.write_storage::<Inventory>()
.get_mut(target)
{
items = inventory.drain().collect();
}
let mut rng = rand::thread_rng();
let mut rng = thread_rng();
let item_to_place = items
.into_iter()
@ -512,7 +512,7 @@ fn handle_give_item(
server
.state
.ecs()
.write_storage::<comp::Inventory>()
.write_storage::<Inventory>()
.get_mut(target)
.map(|mut inv| {
// NOTE: Deliberately ignores items that couldn't be pushed.
@ -530,7 +530,7 @@ fn handle_give_item(
server
.state
.ecs()
.write_storage::<comp::Inventory>()
.write_storage::<Inventory>()
.get_mut(target)
.map(|mut inv| {
for i in 0..give_amount {
@ -618,7 +618,7 @@ fn handle_make_npc(
Err(_err) => return Err(format!("Failed to load entity config: {}", entity_config)),
};
let mut loadout_rng = rand::thread_rng();
let mut loadout_rng = thread_rng();
for _ in 0..number {
let comp::Pos(pos) = position(server, target, "target")?;
let entity_info = EntityInfo::at(pos).with_entity_config(
@ -861,7 +861,7 @@ fn handle_home(
_action: &ServerChatCommand,
) -> CmdResult<()> {
let home_pos = server.state.mut_resource::<SpawnPoint>().0;
let time = *server.state.mut_resource::<common::resources::Time>();
let time = *server.state.mut_resource::<Time>();
position_mut(server, target, "target", |current_pos| {
current_pos.0 = home_pos
@ -1170,8 +1170,8 @@ fn handle_spawn(
for _ in 0..amount {
let vel = Vec3::new(
rand::thread_rng().gen_range(-2.0..3.0),
rand::thread_rng().gen_range(-2.0..3.0),
thread_rng().gen_range(-2.0..3.0),
thread_rng().gen_range(-2.0..3.0),
10.0,
);
@ -1208,10 +1208,10 @@ fn handle_spawn(
pet_entity: new_entity,
});
} else if let Some(group) = match alignment {
comp::Alignment::Wild => None,
comp::Alignment::Passive => None,
comp::Alignment::Enemy => Some(comp::group::ENEMY),
comp::Alignment::Npc | comp::Alignment::Tame => Some(comp::group::NPC),
Alignment::Wild => None,
Alignment::Passive => None,
Alignment::Enemy => Some(comp::group::ENEMY),
Alignment::Npc | Alignment::Tame => Some(comp::group::NPC),
comp::Alignment::Owned(_) => unreachable!(),
} {
insert_or_replace_component(server, new_entity, group, "new entity")?;
@ -1249,8 +1249,8 @@ fn handle_spawn_training_dummy(
) -> CmdResult<()> {
let pos = position(server, target, "target")?;
let vel = Vec3::new(
rand::thread_rng().gen_range(-2.0..3.0),
rand::thread_rng().gen_range(-2.0..3.0),
thread_rng().gen_range(-2.0..3.0),
thread_rng().gen_range(-2.0..3.0),
10.0,
);
@ -1302,7 +1302,7 @@ fn handle_spawn_airship(
200.0,
)
});
let mut rng = rand::thread_rng();
let mut rng = thread_rng();
let ship = comp::ship::Body::random_airship_with(&mut rng);
let mut builder = server
.state
@ -1350,7 +1350,7 @@ fn handle_spawn_ship(
200.0,
)
});
let mut rng = rand::thread_rng();
let mut rng = thread_rng();
let ship = comp::ship::Body::random_ship_with(&mut rng);
let mut builder = server
.state
@ -1782,11 +1782,11 @@ fn handle_help(
Ok(())
}
fn parse_alignment(owner: Uid, alignment: &str) -> CmdResult<comp::Alignment> {
fn parse_alignment(owner: Uid, alignment: &str) -> CmdResult<Alignment> {
match alignment {
"wild" => Ok(comp::Alignment::Wild),
"enemy" => Ok(comp::Alignment::Enemy),
"npc" => Ok(comp::Alignment::Npc),
"wild" => Ok(Alignment::Wild),
"enemy" => Ok(Alignment::Enemy),
"npc" => Ok(Alignment::Npc),
"pet" => Ok(comp::Alignment::Owned(owner)),
_ => Err(format!("Invalid alignment: {:?}", alignment)),
}
@ -1808,7 +1808,7 @@ fn handle_kill_npcs(
let ecs = server.state.ecs();
let mut healths = ecs.write_storage::<comp::Health>();
let players = ecs.read_storage::<comp::Player>();
let alignments = ecs.read_storage::<comp::Alignment>();
let alignments = ecs.read_storage::<Alignment>();
let mut count = 0;
for (mut health, (), alignment) in (&mut healths, !&players, alignments.maybe()).join() {
@ -1907,7 +1907,7 @@ where
server
.state()
.ecs()
.write_storage::<comp::Inventory>()
.write_storage::<Inventory>()
.get_mut(target),
server.state.ecs().write_storage::<comp::InventoryUpdate>(),
) {
@ -1918,7 +1918,7 @@ where
let mut rng = thread_rng();
for (item_id, quantity) in kit {
let mut item = match &item_id {
KitSpec::Item(item_id) => comp::Item::new_from_asset(item_id)
KitSpec::Item(item_id) => Item::new_from_asset(item_id)
.map_err(|_| format!("Unknown item: {:#?}", item_id))?,
KitSpec::ModularWeapon { tool, material } => {
comp::item::modular::random_weapon(*tool, *material, None, &mut rng)
@ -2029,7 +2029,7 @@ fn handle_light(
let (opt_r, opt_g, opt_b, opt_x, opt_y, opt_z, opt_s) =
parse_cmd_args!(args, f32, f32, f32, f32, f32, f32, f32);
let mut light_emitter = comp::LightEmitter::default();
let mut light_emitter = LightEmitter::default();
let mut light_offset_opt = None;
if let (Some(r), Some(g), Some(b)) = (opt_r, opt_g, opt_b) {
@ -2083,7 +2083,7 @@ fn handle_lantern(
if let Some(mut light) = server
.state
.ecs()
.write_storage::<comp::LightEmitter>()
.write_storage::<LightEmitter>()
.get_mut(target)
{
light.strength = s.max(0.1).min(10.0);
@ -2181,7 +2181,7 @@ fn handle_waypoint(
_action: &ServerChatCommand,
) -> CmdResult<()> {
let pos = position(server, target, "target")?;
let time = *server.state.mut_resource::<common::resources::Time>();
let time = *server.state.mut_resource::<Time>();
insert_or_replace_component(
server,
target,
@ -2897,8 +2897,8 @@ fn handle_remove_lights(
for (entity, pos, _, _, _) in (
&ecs.entities(),
&ecs.read_storage::<comp::Pos>(),
&ecs.read_storage::<comp::LightEmitter>(),
!&ecs.read_storage::<comp::WaypointArea>(),
&ecs.read_storage::<LightEmitter>(),
!&ecs.read_storage::<WaypointArea>(),
!&ecs.read_storage::<comp::Player>(),
)
.join()
@ -3072,7 +3072,7 @@ fn kick_player(
.mut_resource::<EventBus<ServerEvent>>()
.emit_now(ServerEvent::ClientDisconnect(
target_player,
common::comp::DisconnectReason::Kicked,
comp::DisconnectReason::Kicked,
));
Ok(())
}

View File

@ -140,10 +140,10 @@ pub fn handle_create_npc(
);
}
} else if let Some(group) = match alignment {
comp::Alignment::Wild => None,
comp::Alignment::Passive => None,
comp::Alignment::Enemy => Some(comp::group::ENEMY),
comp::Alignment::Npc | comp::Alignment::Tame => Some(comp::group::NPC),
Alignment::Wild => None,
Alignment::Passive => None,
Alignment::Enemy => Some(comp::group::ENEMY),
Alignment::Npc | Alignment::Tame => Some(comp::group::NPC),
comp::Alignment::Owned(_) => unreachable!(),
} {
let _ = server.state.ecs().write_storage().insert(new_entity, group);
@ -152,7 +152,7 @@ pub fn handle_create_npc(
pub fn handle_create_ship(
server: &mut Server,
pos: comp::Pos,
pos: Pos,
ship: comp::ship::Body,
mountable: bool,
agent: Option<Agent>,

View File

@ -172,7 +172,7 @@ pub fn handle_destroy(server: &mut Server, entity: EcsEntity, last_change: Healt
// one, we probably don't care about emitting death outcome)
if state
.ecs()
.read_storage::<comp::CharacterState>()
.read_storage::<CharacterState>()
.get(entity)
.is_some()
{
@ -225,7 +225,7 @@ pub fn handle_destroy(server: &mut Server, entity: EcsEntity, last_change: Healt
let inventories = state.ecs().read_storage::<Inventory>();
let players = state.ecs().read_storage::<Player>();
let bodies = state.ecs().read_storage::<Body>();
let poises = state.ecs().read_storage::<comp::Poise>();
let poises = state.ecs().read_storage::<Poise>();
let positions = state.ecs().read_storage::<Pos>();
let groups = state.ecs().read_storage::<Group>();
@ -307,7 +307,7 @@ pub fn handle_destroy(server: &mut Server, entity: EcsEntity, last_change: Healt
let alignments = state.ecs().read_storage::<Alignment>();
let uids = state.ecs().read_storage::<Uid>();
let mut outcomes = state.ecs().write_resource::<EventBus<Outcome>>();
let inventories = state.ecs().read_storage::<comp::Inventory>();
let inventories = state.ecs().read_storage::<Inventory>();
let destroyed_group = groups.get(entity);
@ -416,7 +416,7 @@ pub fn handle_destroy(server: &mut Server, entity: EcsEntity, last_change: Healt
.map(|e| error!(?e, ?entity, "Failed to insert ForceUpdate on dead client"));
state
.ecs()
.write_storage::<comp::Energy>()
.write_storage::<Energy>()
.get_mut(entity)
.map(|mut energy| {
let energy = &mut *energy;
@ -424,11 +424,11 @@ pub fn handle_destroy(server: &mut Server, entity: EcsEntity, last_change: Healt
});
let _ = state
.ecs()
.write_storage::<comp::CharacterState>()
.insert(entity, comp::CharacterState::default());
.write_storage::<CharacterState>()
.insert(entity, CharacterState::default());
false
} else if state.ecs().read_storage::<comp::Agent>().contains(entity)
} else if state.ecs().read_storage::<Agent>().contains(entity)
&& !matches!(
state.ecs().read_storage::<comp::Alignment>().get(entity),
Some(comp::Alignment::Owned(_))
@ -445,7 +445,7 @@ pub fn handle_destroy(server: &mut Server, entity: EcsEntity, last_change: Healt
};
if let Some(item) = item {
let pos = state.ecs().read_storage::<comp::Pos>().get(entity).cloned();
let pos = state.ecs().read_storage::<Pos>().get(entity).cloned();
let vel = state.ecs().read_storage::<comp::Vel>().get(entity).cloned();
if let Some(pos) = pos {
// Remove entries where zero exp was awarded - this happens because some
@ -471,7 +471,7 @@ pub fn handle_destroy(server: &mut Server, entity: EcsEntity, last_change: Healt
} else {
let uid = state
.ecs()
.read_storage::<comp::Body>()
.read_storage::<Body>()
.get(winner)
.and_then(|body| {
// Only humanoids are awarded loot ownership - if the winner
@ -490,7 +490,7 @@ pub fn handle_destroy(server: &mut Server, entity: EcsEntity, last_change: Healt
};
let item_drop_entity = state
.create_item_drop(comp::Pos(pos.0 + Vec3::unit_z() * 0.25), item)
.create_item_drop(Pos(pos.0 + Vec3::unit_z() * 0.25), item)
.maybe_with(vel)
.build();
@ -502,7 +502,7 @@ pub fn handle_destroy(server: &mut Server, entity: EcsEntity, last_change: Healt
state
.ecs()
.write_storage::<comp::LootOwner>()
.write_storage::<LootOwner>()
.insert(item_drop_entity, LootOwner::new(uid))
.unwrap();
}
@ -633,7 +633,7 @@ pub fn handle_respawn(server: &Server, entity: EcsEntity) {
state
.ecs()
.write_storage::<comp::Health>()
.write_storage::<Health>()
.get_mut(entity)
.map(|mut health| health.revive());
state
@ -643,7 +643,7 @@ pub fn handle_respawn(server: &Server, entity: EcsEntity) {
.map(|mut combo| combo.reset());
state
.ecs()
.write_storage::<comp::Pos>()
.write_storage::<Pos>()
.get_mut(entity)
.map(|pos| pos.0 = respawn_point);
state
@ -692,7 +692,7 @@ pub fn handle_explosion(server: &Server, pos: Vec3<f32>, explosion: Explosion, o
.any(|e| matches!(e, RadiusEffect::Attack(_))),
reagent: explosion.reagent,
});
let groups = ecs.read_storage::<comp::Group>();
let groups = ecs.read_storage::<Group>();
// Used to get strength of explosion effects as they falloff over distance
fn cylinder_sphere_strength(
@ -859,12 +859,12 @@ pub fn handle_explosion(server: &Server, pos: Vec3<f32>, explosion: Explosion, o
}
},
RadiusEffect::Attack(attack) => {
let energies = &ecs.read_storage::<comp::Energy>();
let energies = &ecs.read_storage::<Energy>();
let combos = &ecs.read_storage::<comp::Combo>();
let inventories = &ecs.read_storage::<comp::Inventory>();
let inventories = &ecs.read_storage::<Inventory>();
let alignments = &ecs.read_storage::<Alignment>();
let uid_allocator = &ecs.read_resource::<UidAllocator>();
let players = &ecs.read_storage::<comp::Player>();
let players = &ecs.read_storage::<Player>();
for (
entity_b,
pos_b,
@ -872,13 +872,13 @@ pub fn handle_explosion(server: &Server, pos: Vec3<f32>, explosion: Explosion, o
(body_b_maybe, stats_b_maybe, ori_b_maybe, char_state_b_maybe, uid_b),
) in (
&ecs.entities(),
&ecs.read_storage::<comp::Pos>(),
&ecs.read_storage::<comp::Health>(),
&ecs.read_storage::<Pos>(),
&ecs.read_storage::<Health>(),
(
ecs.read_storage::<comp::Body>().maybe(),
ecs.read_storage::<comp::Stats>().maybe(),
ecs.read_storage::<Body>().maybe(),
ecs.read_storage::<Stats>().maybe(),
ecs.read_storage::<comp::Ori>().maybe(),
ecs.read_storage::<comp::CharacterState>().maybe(),
ecs.read_storage::<CharacterState>().maybe(),
&ecs.read_storage::<Uid>(),
),
)
@ -975,11 +975,11 @@ pub fn handle_explosion(server: &Server, pos: Vec3<f32>, explosion: Explosion, o
RadiusEffect::Entity(mut effect) => {
let alignments = &ecs.read_storage::<Alignment>();
let uid_allocator = &ecs.read_resource::<UidAllocator>();
let players = &ecs.read_storage::<comp::Player>();
let players = &ecs.read_storage::<Player>();
for (entity_b, pos_b, body_b_maybe) in (
&ecs.entities(),
&ecs.read_storage::<comp::Pos>(),
ecs.read_storage::<comp::Body>().maybe(),
&ecs.read_storage::<Pos>(),
ecs.read_storage::<Body>().maybe(),
)
.join()
{
@ -1011,7 +1011,7 @@ pub fn handle_explosion(server: &Server, pos: Vec3<f32>, explosion: Explosion, o
};
if strength > 0.0 {
let is_alive = ecs
.read_storage::<comp::Health>()
.read_storage::<Health>()
.get(entity_b)
.map_or(true, |h| !h.is_dead);
@ -1056,7 +1056,7 @@ pub fn handle_bonk(server: &mut Server, pos: Vec3<f32>, owner: Option<Uid>, targ
Some(SpriteKind::Bomb) => comp::object::Body::Bomb,
_ => comp::object::Body::Pouch,
})
.with(comp::Pos(pos.map(|e| e as f32) + Vec3::new(0.5, 0.5, 0.0)))
.with(Pos(pos.map(|e| e as f32) + Vec3::new(0.5, 0.5, 0.0)))
.with(item)
.maybe_with(match block.get_sprite() {
Some(SpriteKind::Bomb) => Some(comp::Object::Bomb { owner }),
@ -1071,7 +1071,7 @@ pub fn handle_bonk(server: &mut Server, pos: Vec3<f32>, owner: Option<Uid>, targ
pub fn handle_aura(server: &mut Server, entity: EcsEntity, aura_change: aura::AuraChange) {
let ecs = &server.state.ecs();
let mut auras_all = ecs.write_storage::<comp::Auras>();
let mut auras_all = ecs.write_storage::<Auras>();
if let Some(mut auras) = auras_all.get_mut(entity) {
use aura::AuraChange;
match aura_change {
@ -1090,7 +1090,7 @@ pub fn handle_aura(server: &mut Server, entity: EcsEntity, aura_change: aura::Au
pub fn handle_buff(server: &mut Server, entity: EcsEntity, buff_change: buff::BuffChange) {
let ecs = &server.state.ecs();
let mut buffs_all = ecs.write_storage::<comp::Buffs>();
let bodies = ecs.read_storage::<comp::Body>();
let bodies = ecs.read_storage::<Body>();
if let Some(mut buffs) = buffs_all.get_mut(entity) {
use buff::BuffChange;
match buff_change {
@ -1238,7 +1238,7 @@ pub fn handle_combo_change(server: &Server, entity: EcsEntity, change: i32) {
pub fn handle_parry(server: &Server, entity: EcsEntity, energy_cost: f32) {
let ecs = &server.state.ecs();
if let Some(mut character) = ecs.write_storage::<comp::CharacterState>().get_mut(entity) {
if let Some(mut character) = ecs.write_storage::<CharacterState>().get_mut(entity) {
*character =
CharacterState::Wielding(common::states::wielding::Data { is_sneaking: false });
};
@ -1316,11 +1316,11 @@ pub fn handle_entity_attacked_hook(server: &Server, entity: EcsEntity) {
// Remove potion/saturation buff if attacked
server_eventbus.emit_now(ServerEvent::Buff {
entity,
buff_change: buff::BuffChange::RemoveByKind(buff::BuffKind::Potion),
buff_change: buff::BuffChange::RemoveByKind(BuffKind::Potion),
});
server_eventbus.emit_now(ServerEvent::Buff {
entity,
buff_change: buff::BuffChange::RemoveByKind(buff::BuffKind::Saturation),
buff_change: buff::BuffChange::RemoveByKind(BuffKind::Saturation),
});
}
@ -1332,8 +1332,8 @@ pub fn handle_change_ability(
new_ability: ability::AuxiliaryAbility,
) {
let ecs = &server.state.ecs();
let inventories = ecs.read_storage::<comp::Inventory>();
let skill_sets = ecs.read_storage::<comp::SkillSet>();
let inventories = ecs.read_storage::<Inventory>();
let skill_sets = ecs.read_storage::<SkillSet>();
if let Some(mut active_abilities) = ecs.write_storage::<comp::ActiveAbilities>().get_mut(entity)
{

View File

@ -113,7 +113,7 @@ pub fn update_map_markers<'a>(
}
// TODO: turn chat messages into enums
pub fn handle_group(server: &mut Server, entity: specs::Entity, manip: GroupManip) {
pub fn handle_group(server: &mut Server, entity: Entity, manip: GroupManip) {
match manip {
GroupManip::Leave => {
let state = server.state_mut();
@ -184,7 +184,7 @@ pub fn handle_group(server: &mut Server, entity: specs::Entity, manip: GroupMani
return;
}
let mut groups = state.ecs().write_storage::<group::Group>();
let mut groups = state.ecs().write_storage::<Group>();
let mut group_manager = state.ecs().write_resource::<GroupManager>();
let map_markers = state.ecs().read_storage::<comp::MapMarker>();
// Make sure kicker is the group leader
@ -267,7 +267,7 @@ pub fn handle_group(server: &mut Server, entity: specs::Entity, manip: GroupMani
return;
},
};
let groups = state.ecs().read_storage::<group::Group>();
let groups = state.ecs().read_storage::<Group>();
let mut group_manager = state.ecs().write_resource::<GroupManager>();
let map_markers = state.ecs().read_storage::<comp::MapMarker>();
// Make sure assigner is the group leader

View File

@ -100,7 +100,7 @@ pub fn handle_mount(server: &mut Server, rider: EcsEntity, mount: EcsEntity) {
let not_mounting_yet = state.ecs().read_storage::<Is<Mount>>().get(mount).is_none();
let within_range = || {
let positions = state.ecs().read_storage::<comp::Pos>();
let positions = state.ecs().read_storage::<Pos>();
within_mounting_range(positions.get(rider), positions.get(mount))
};
let healths = state.ecs().read_storage::<comp::Health>();
@ -234,7 +234,7 @@ pub fn handle_mine_block(
}
let item_drop = state
.create_item_drop(Default::default(), item)
.with(comp::Pos(pos.map(|e| e as f32) + Vec3::new(0.5, 0.5, 0.0)));
.with(Pos(pos.map(|e| e as f32) + Vec3::new(0.5, 0.5, 0.0)));
if let Some(uid) = maybe_uid {
item_drop.with(LootOwner::new(LootOwnerKind::Player(uid)))
} else {
@ -257,7 +257,7 @@ pub fn handle_mine_block(
pub fn handle_sound(server: &mut Server, sound: &Sound) {
let ecs = &server.state.ecs();
let positions = &ecs.read_storage::<comp::Pos>();
let positions = &ecs.read_storage::<Pos>();
let agents = &mut ecs.write_storage::<comp::Agent>();
// TODO: Reduce the complexity of this problem by using spatial partitioning

View File

@ -33,7 +33,7 @@ use common::{
use common_net::msg::ServerGeneral;
pub fn swap_lantern(
storage: &mut WriteStorage<comp::LightEmitter>,
storage: &mut WriteStorage<LightEmitter>,
entity: EcsEntity,
(lantern_color, lantern_strength): (Rgb<f32>, f32),
) {
@ -43,7 +43,7 @@ pub fn swap_lantern(
}
}
pub fn snuff_lantern(storage: &mut WriteStorage<comp::LightEmitter>, entity: EcsEntity) {
pub fn snuff_lantern(storage: &mut WriteStorage<LightEmitter>, entity: EcsEntity) {
storage.remove(entity);
}
@ -212,9 +212,9 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
);
drop(item_storage);
drop(inventories);
comp::InventoryUpdate::new(comp::InventoryUpdateEvent::EntityCollectFailed {
comp::InventoryUpdate::new(InventoryUpdateEvent::EntityCollectFailed {
entity: pickup_uid,
reason: comp::CollectFailedReason::InventoryFull,
reason: CollectFailedReason::InventoryFull,
})
},
Ok(_) => {
@ -227,10 +227,10 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
component.",
);
let ecs = state.ecs();
if let Some(group_id) = ecs.read_storage::<comp::Group>().get(entity) {
if let Some(group_id) = ecs.read_storage::<Group>().get(entity) {
announce_loot_to_group(group_id, ecs, entity, &item_msg.name());
}
comp::InventoryUpdate::new(comp::InventoryUpdateEvent::Collected(item_msg))
comp::InventoryUpdate::new(InventoryUpdateEvent::Collected(item_msg))
},
};
@ -255,12 +255,10 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
let event = match inventory.push(item) {
Ok(_) => {
let ecs = state.ecs();
if let Some(group_id) =
ecs.read_storage::<comp::Group>().get(entity)
{
if let Some(group_id) = ecs.read_storage::<Group>().get(entity) {
announce_loot_to_group(group_id, ecs, entity, &item_msg.name());
}
comp::InventoryUpdate::new(comp::InventoryUpdateEvent::Collected(
comp::InventoryUpdate::new(InventoryUpdateEvent::Collected(
item_msg,
))
},
@ -269,9 +267,9 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
Err(_) => {
drop_item = Some(item_msg);
comp::InventoryUpdate::new(
comp::InventoryUpdateEvent::BlockCollectFailed {
InventoryUpdateEvent::BlockCollectFailed {
pos,
reason: comp::CollectFailedReason::InventoryFull,
reason: CollectFailedReason::InventoryFull,
},
)
},
@ -343,18 +341,16 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
)
}));
}
Some(comp::InventoryUpdateEvent::Used)
Some(InventoryUpdateEvent::Used)
} else if let Some(item) = inventory.take(
slot,
&state.ecs().read_resource::<AbilityMap>(),
&state.ecs().read_resource::<item::MaterialStatManifest>(),
&state.ecs().read_resource::<MaterialStatManifest>(),
) {
match &*item.kind() {
ItemKind::Consumable { effects, .. } => {
maybe_effect = Some(effects.clone());
Some(comp::InventoryUpdateEvent::Consumed(
item.name().into_owned(),
))
Some(InventoryUpdateEvent::Consumed(item.name().into_owned()))
},
ItemKind::Throwable { kind, .. } => {
if let Some(pos) =
@ -374,10 +370,10 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
*kind,
));
}
Some(comp::InventoryUpdateEvent::Used)
Some(InventoryUpdateEvent::Used)
},
ItemKind::Utility {
kind: comp::item::Utility::Collar,
kind: item::Utility::Collar,
..
} => {
const MAX_PETS: usize = 3;
@ -385,7 +381,7 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
state.read_storage::<comp::Pos>().get(entity)
{
if (
&state.read_storage::<comp::Alignment>(),
&state.read_storage::<Alignment>(),
&state.read_storage::<comp::Agent>(),
)
.join()
@ -399,17 +395,16 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
} else if let Some(tameable_entity) = {
let nearest_tameable = (
&state.ecs().entities(),
&state.ecs().read_storage::<comp::Body>(),
&state.ecs().read_storage::<Body>(),
&state.ecs().read_storage::<comp::Pos>(),
&state.ecs().read_storage::<comp::Alignment>(),
&state.ecs().read_storage::<Alignment>(),
)
.join()
.filter(|(_, _, wild_pos, _)| {
wild_pos.0.distance_squared(pos.0) < 5.0f32.powi(2)
})
.filter(|(_, body, _, alignment)| {
alignment == &&comp::Alignment::Wild
&& is_tameable(body)
alignment == &&Alignment::Wild && is_tameable(body)
})
.min_by_key(|(_, _, wild_pos, _)| {
(wild_pos.0.distance_squared(pos.0) * 100.0) as i32
@ -435,7 +430,7 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
let _ = inventory.insert_or_stack_at(slot, item);
}
Some(comp::InventoryUpdateEvent::Used)
Some(InventoryUpdateEvent::Used)
},
_ => {
inventory.insert_or_stack_at(slot, item).expect(
@ -468,7 +463,7 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
}));
}
}
Some(comp::InventoryUpdateEvent::Used)
Some(InventoryUpdateEvent::Used)
},
};
@ -535,7 +530,7 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
.write_storage()
.insert(
entity,
comp::InventoryUpdate::new(comp::InventoryUpdateEvent::Swapped),
comp::InventoryUpdate::new(InventoryUpdateEvent::Swapped),
)
.expect("We know entity exists since we got its inventory.");
},
@ -576,7 +571,7 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
.write_storage()
.insert(
entity,
comp::InventoryUpdate::new(comp::InventoryUpdateEvent::Swapped),
comp::InventoryUpdate::new(InventoryUpdateEvent::Swapped),
)
.expect("We know entity exists since we got its inventory.");
drop(inventories);
@ -605,7 +600,7 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
.write_storage()
.insert(
entity,
comp::InventoryUpdate::new(comp::InventoryUpdateEvent::Dropped),
comp::InventoryUpdate::new(InventoryUpdateEvent::Dropped),
)
.expect("We know entity exists since we got its inventory.");
drop(inventories);
@ -637,7 +632,7 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
.write_storage()
.insert(
entity,
comp::InventoryUpdate::new(comp::InventoryUpdateEvent::Dropped),
comp::InventoryUpdate::new(InventoryUpdateEvent::Dropped),
)
.expect("We know entity exists since we got its inventory.");
drop(inventories);
@ -692,7 +687,7 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
&mut inventory,
slots,
&state.ecs().read_resource::<AbilityMap>(),
&state.ecs().read_resource::<item::MaterialStatManifest>(),
&state.ecs().read_resource::<MaterialStatManifest>(),
)
.ok()
}),
@ -757,7 +752,7 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
modifier,
slots,
&state.ecs().read_resource::<AbilityMap>(),
&state.ecs().read_resource::<item::MaterialStatManifest>(),
&state.ecs().read_resource::<MaterialStatManifest>(),
)
.ok()
})
@ -794,7 +789,7 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
if items_were_crafted {
let _ = state.ecs().write_storage().insert(
entity,
comp::InventoryUpdate::new(comp::InventoryUpdateEvent::Craft),
comp::InventoryUpdate::new(InventoryUpdateEvent::Craft),
);
}
},
@ -934,7 +929,7 @@ mod tests {
use super::*;
// Helper function
fn test_cylinder(pos: comp::Pos) -> Option<Cylinder> {
fn test_cylinder(pos: Pos) -> Option<Cylinder> {
Some(Cylinder::from_components(pos.0, None, None, None))
}

View File

@ -26,12 +26,7 @@ const INVITE_TIMEOUT_DUR: Duration = Duration::from_secs(31);
/// Reduced duration shown to the client to help alleviate latency issues
const PRESENTED_INVITE_TIMEOUT_DUR: Duration = Duration::from_secs(30);
pub fn handle_invite(
server: &mut Server,
inviter: specs::Entity,
invitee_uid: Uid,
kind: InviteKind,
) {
pub fn handle_invite(server: &mut Server, inviter: Entity, invitee_uid: Uid, kind: InviteKind) {
let max_group_size = server.settings().max_player_group_size;
let state = server.state_mut();
let clients = state.ecs().read_storage::<Client>();
@ -61,12 +56,12 @@ pub fn handle_invite(
}
let mut pending_invites = state.ecs().write_storage::<PendingInvites>();
let mut agents = state.ecs().write_storage::<comp::Agent>();
let mut agents = state.ecs().write_storage::<Agent>();
let mut invites = state.ecs().write_storage::<Invite>();
if let InviteKind::Trade = kind {
// Check whether the inviter is in range of the invitee
let positions = state.ecs().read_storage::<comp::Pos>();
let positions = state.ecs().read_storage::<Pos>();
if !within_trading_range(positions.get(inviter), positions.get(invitee)) {
return;
}
@ -180,18 +175,14 @@ pub fn handle_invite(
}
}
}
pub fn handle_invite_response(
server: &mut Server,
entity: specs::Entity,
response: InviteResponse,
) {
pub fn handle_invite_response(server: &mut Server, entity: Entity, response: InviteResponse) {
match response {
InviteResponse::Accept => handle_invite_accept(server, entity),
InviteResponse::Decline => handle_invite_decline(server, entity),
}
}
pub fn handle_invite_accept(server: &mut Server, entity: specs::Entity) {
pub fn handle_invite_accept(server: &mut Server, entity: Entity) {
let index = server.index.clone();
let state = server.state_mut();
if let Some((inviter, kind)) = get_inviter_and_kind(entity, state) {
@ -324,7 +315,7 @@ fn handle_invite_answer(
client
.send_fallible(ServerGeneral::FinishedTrade(TradeResult::Declined));
}
if let Some(agent) = state.ecs().write_storage::<comp::Agent>().get_mut(e) {
if let Some(agent) = state.ecs().write_storage::<Agent>().get_mut(e) {
agent
.inbox
.push_back(AgentEvent::FinishedTrade(TradeResult::Declined));
@ -342,7 +333,7 @@ fn handle_invite_answer(
}
}
pub fn handle_invite_decline(server: &mut Server, entity: specs::Entity) {
pub fn handle_invite_decline(server: &mut Server, entity: Entity) {
let state = server.state_mut();
if let Some((inviter, kind)) = get_inviter_and_kind(entity, state) {
// Inform inviter of rejection

View File

@ -223,12 +223,12 @@ fn persist_entity(state: &mut State, entity: EcsEntity) -> EcsEntity {
PresenceKind::Character(char_id) => {
let waypoint = state
.ecs()
.read_storage::<common::comp::Waypoint>()
.read_storage::<comp::Waypoint>()
.get(entity)
.cloned();
let map_marker = state
.ecs()
.read_storage::<common::comp::MapMarker>()
.read_storage::<comp::MapMarker>()
.get(entity)
.cloned();
// Store last battle mode change
@ -421,8 +421,9 @@ pub fn handle_possess(server: &mut Server, possessor_uid: Uid, possessee_uid: Ui
if let Some(player) = players.get(possessee) {
use common_net::msg;
let add_player_msg = ServerGeneral::PlayerListUpdate(
msg::server::PlayerListUpdate::Add(possessee_uid, msg::server::PlayerInfo {
let add_player_msg = ServerGeneral::PlayerListUpdate(PlayerListUpdate::Add(
possessee_uid,
msg::server::PlayerInfo {
player_alias: player.alias.clone(),
is_online: true,
is_moderator: admins.contains(possessee),
@ -432,11 +433,10 @@ pub fn handle_possess(server: &mut Server, possessor_uid: Uid, possessee_uid: Ui
}
}),
uuid: player.uuid(),
}),
);
let remove_player_msg = ServerGeneral::PlayerListUpdate(
msg::server::PlayerListUpdate::Remove(possessor_uid),
);
},
));
let remove_player_msg =
ServerGeneral::PlayerListUpdate(PlayerListUpdate::Remove(possessor_uid));
drop((clients, players)); // need to drop so we can use `notify_players` below
state.notify_players(remove_player_msg);

View File

@ -333,7 +333,7 @@ impl Server {
state.ecs_mut().register::<Presence>();
state.ecs_mut().register::<wiring::WiringElement>();
state.ecs_mut().register::<wiring::Circuit>();
state.ecs_mut().register::<comp::Anchor>();
state.ecs_mut().register::<Anchor>();
state.ecs_mut().register::<comp::Pet>();
state.ecs_mut().register::<login_provider::PendingLogin>();
state.ecs_mut().register::<RepositionOnChunkLoad>();
@ -346,7 +346,7 @@ impl Server {
Ok(file) => match ron::de::from_reader(&file) {
Ok(vec) => vec,
Err(error) => {
tracing::warn!(?error, ?file, "Couldn't deserialize banned words file");
warn!(?error, ?file, "Couldn't deserialize banned words file");
return Err(Error::Other(format!(
"Couldn't read banned words file \"{}\"",
path.to_string_lossy()
@ -354,7 +354,7 @@ impl Server {
},
},
Err(error) => {
tracing::warn!(?error, ?path, "Couldn't open banned words file");
warn!(?error, ?path, "Couldn't open banned words file");
return Err(Error::Other(format!(
"Couldn't open banned words file \"{}\". Error: {}",
path.to_string_lossy(),
@ -365,8 +365,8 @@ impl Server {
banned_words.append(&mut list);
}
let banned_words_count = banned_words.len();
tracing::debug!(?banned_words_count);
tracing::trace!(?banned_words);
debug!(?banned_words_count);
trace!(?banned_words);
state.ecs_mut().insert(AliasValidator::new(banned_words));
#[cfg(feature = "worldgen")]
@ -759,10 +759,10 @@ impl Server {
}
// Prevent anchor entity chains which are not currently supported
let anchors = self.state.ecs().read_storage::<comp::Anchor>();
let anchors = self.state.ecs().read_storage::<Anchor>();
let anchored_anchor_entities: Vec<Entity> = (
&self.state.ecs().entities(),
&self.state.ecs().read_storage::<comp::Anchor>(),
&self.state.ecs().read_storage::<Anchor>(),
)
.join()
.filter_map(|(_, anchor)| match anchor {
@ -792,7 +792,7 @@ impl Server {
&self.state.ecs().entities(),
&self.state.ecs().read_storage::<comp::Pos>(),
!&self.state.ecs().read_storage::<Presence>(),
self.state.ecs().read_storage::<comp::Anchor>().maybe(),
self.state.ecs().read_storage::<Anchor>().maybe(),
)
.join()
.filter(|(_, pos, _, anchor)| {
@ -847,15 +847,9 @@ impl Server {
// 7 Persistence updates
let before_persistence_updates = Instant::now();
let character_loader = self
.state
.ecs()
.read_resource::<persistence::character_loader::CharacterLoader>();
let character_loader = self.state.ecs().read_resource::<CharacterLoader>();
let character_updater = self
.state
.ecs()
.read_resource::<persistence::character_updater::CharacterUpdater>();
let character_updater = self.state.ecs().read_resource::<CharacterUpdater>();
// Get character-related database responses and notify the requesting client
character_loader
@ -1005,7 +999,7 @@ impl Server {
{
// Report timing info
let tick_metrics = self.state.ecs().read_resource::<metrics::TickMetrics>();
let tick_metrics = self.state.ecs().read_resource::<TickMetrics>();
let tt = &tick_metrics.tick_time;
tt.with_label_values(&["new connections"])
@ -1049,8 +1043,8 @@ impl Server {
fn initialize_client(
&mut self,
client: crate::connection_handler::IncomingClient,
) -> Result<Option<specs::Entity>, Error> {
client: connection_handler::IncomingClient,
) -> Result<Option<Entity>, Error> {
if self.settings().max_players <= self.state.ecs().read_storage::<Client>().join().count() {
trace!(
?client.participant,
@ -1166,7 +1160,7 @@ impl Server {
while let Ok(sender) = self.connection_handler.info_requester_receiver.try_recv() {
// can fail, e.g. due to timeout or network prob.
trace!("sending info to connection_handler");
let _ = sender.send(crate::connection_handler::ServerInfoPacket {
let _ = sender.send(connection_handler::ServerInfoPacket {
info: self.get_server_info(),
time: self.state.get_time(),
});

View File

@ -164,13 +164,13 @@ impl LoginProvider {
info!(?username, "New User");
Some(Ok((username, uuid)))
},
Err(tokio::sync::oneshot::error::TryRecvError::Closed) => {
Err(oneshot::error::TryRecvError::Closed) => {
error!("channel got closed to early, this shouldn't happen");
Some(Err(RegisterError::AuthError(
"Internal Error verifying".to_string(),
)))
},
Err(tokio::sync::oneshot::error::TryRecvError::Empty) => None,
Err(oneshot::error::TryRecvError::Empty) => None,
}
}
@ -186,7 +186,7 @@ impl LoginProvider {
match async {
let uuid = srv.validate(token).await?;
let username = srv.uuid_to_username(uuid).await?;
let r: Result<_, authc::AuthClientError> = Ok((username, uuid));
let r: Result<_, AuthClientError> = Ok((username, uuid));
r
}
.await

View File

@ -543,9 +543,7 @@ pub fn edit_character(
.iter_mut()
.find(|c| c.character.id == Some(character_id))
{
if let (crate::comp::Body::Humanoid(new), crate::comp::Body::Humanoid(old)) =
(body, char.body)
{
if let (comp::Body::Humanoid(new), comp::Body::Humanoid(old)) = (body, char.body) {
if new.species != old.species || new.body_type != old.body_type {
warn!(
"Character edit rejected due to failed validation - Character ID: {} \
@ -948,7 +946,7 @@ fn delete_pets(
pub fn update(
char_id: CharacterId,
char_skill_set: comp::SkillSet,
inventory: comp::Inventory,
inventory: Inventory,
pets: Vec<PetPersistenceData>,
char_waypoint: Option<comp::Waypoint>,
active_abilities: comp::ability::ActiveAbilities,

View File

@ -28,7 +28,7 @@ use tracing::{trace, warn};
#[derive(Debug)]
pub struct ItemModelPair {
pub comp: Arc<common::comp::item::ItemId>,
pub comp: Arc<item::ItemId>,
pub model: Item,
}
@ -193,23 +193,23 @@ pub fn convert_body_to_database_json(
comp_body: &CompBody,
) -> Result<(&str, String), PersistenceError> {
Ok(match comp_body {
common::comp::Body::Humanoid(body) => (
Body::Humanoid(body) => (
"humanoid",
serde_json::to_string(&HumanoidBody::from(body))?,
),
common::comp::Body::QuadrupedLow(body) => (
Body::QuadrupedLow(body) => (
"quadruped_low",
serde_json::to_string(&GenericBody::from(body))?,
),
common::comp::Body::QuadrupedMedium(body) => (
Body::QuadrupedMedium(body) => (
"quadruped_medium",
serde_json::to_string(&GenericBody::from(body))?,
),
common::comp::Body::QuadrupedSmall(body) => (
Body::QuadrupedSmall(body) => (
"quadruped_small",
serde_json::to_string(&GenericBody::from(body))?,
),
common::comp::Body::BirdMedium(body) => (
Body::BirdMedium(body) => (
"bird_medium",
serde_json::to_string(&GenericBody::from(body))?,
),
@ -544,8 +544,8 @@ pub fn convert_body_from_database(
// extra fields on its body struct
"humanoid" => {
let json_model = serde_json::de::from_str::<HumanoidBody>(body_data)?;
CompBody::Humanoid(common::comp::humanoid::Body {
species: common::comp::humanoid::ALL_SPECIES
CompBody::Humanoid(humanoid::Body {
species: humanoid::ALL_SPECIES
.get(json_model.species as usize)
.ok_or_else(|| {
PersistenceError::ConversionError(format!(
@ -554,7 +554,7 @@ pub fn convert_body_from_database(
))
})?
.to_owned(),
body_type: common::comp::humanoid::ALL_BODY_TYPES
body_type: humanoid::ALL_BODY_TYPES
.get(json_model.body_type as usize)
.ok_or_else(|| {
PersistenceError::ConversionError(format!(
@ -600,16 +600,16 @@ pub fn convert_character_from_database(character: &Character) -> common::charact
}
}
pub fn convert_stats_from_database(alias: String) -> common::comp::Stats {
let mut new_stats = common::comp::Stats::empty();
pub fn convert_stats_from_database(alias: String) -> Stats {
let mut new_stats = Stats::empty();
new_stats.name = alias;
new_stats
}
pub fn convert_skill_set_from_database(skill_groups: &[SkillGroup]) -> common::comp::SkillSet {
pub fn convert_skill_set_from_database(skill_groups: &[SkillGroup]) -> SkillSet {
let (skillless_skill_groups, deserialized_skills) =
convert_skill_groups_from_database(skill_groups);
common::comp::SkillSet::load_from_database(skillless_skill_groups, deserialized_skills)
SkillSet::load_from_database(skillless_skill_groups, deserialized_skills)
}
#[allow(clippy::type_complexity)]
@ -618,9 +618,9 @@ fn convert_skill_groups_from_database(
) -> (
// Skill groups in the vec do not contain skills, those are added later. The skill group only
// contains fields related to experience and skill points
HashMap<skillset::SkillGroupKind, skillset::SkillGroup>,
HashMap<SkillGroupKind, skillset::SkillGroup>,
//
HashMap<skillset::SkillGroupKind, Result<Vec<skills::Skill>, skillset::SkillsPersistenceError>>,
HashMap<SkillGroupKind, Result<Vec<Skill>, skillset::SkillsPersistenceError>>,
) {
let mut new_skill_groups = HashMap::new();
let mut deserialized_skills = HashMap::new();
@ -657,7 +657,7 @@ fn convert_skill_groups_from_database(
Err(SkillsPersistenceError::HashMismatch)
} else {
// Else attempt to deserialize skills from a json string
match serde_json::from_str::<Vec<skills::Skill>>(&skill_group.skills) {
match serde_json::from_str::<Vec<Skill>>(&skill_group.skills) {
// If it correctly deserializes, return the persisted skills
Ok(skills) => Ok(skills),
// Else if doesn't deserialize correctly, force a respec
@ -702,7 +702,7 @@ pub fn convert_skill_groups_to_database<'a, I: Iterator<Item = &'a skillset::Ski
pub fn convert_active_abilities_to_database(
entity_id: CharacterId,
active_abilities: &ability::ActiveAbilities,
active_abilities: &ActiveAbilities,
) -> AbilitySets {
let ability_sets = json_models::active_abilities_to_db_model(active_abilities);
AbilitySets {
@ -711,9 +711,7 @@ pub fn convert_active_abilities_to_database(
}
}
pub fn convert_active_abilities_from_database(
ability_sets: &AbilitySets,
) -> ability::ActiveAbilities {
pub fn convert_active_abilities_from_database(ability_sets: &AbilitySets) -> ActiveAbilities {
let ability_sets = serde_json::from_str::<Vec<DatabaseAbilitySet>>(&ability_sets.ability_sets)
.unwrap_or_else(|err| {
common_base::dev_panic!(format!(

View File

@ -118,7 +118,7 @@ pub struct DatabaseAbilitySet {
abilities: Vec<String>,
}
fn aux_ability_to_string(ability: common::comp::ability::AuxiliaryAbility) -> String {
fn aux_ability_to_string(ability: comp::ability::AuxiliaryAbility) -> String {
use common::comp::ability::AuxiliaryAbility;
match ability {
AuxiliaryAbility::MainWeapon(index) => format!("Main Weapon:index:{}", index),
@ -127,7 +127,7 @@ fn aux_ability_to_string(ability: common::comp::ability::AuxiliaryAbility) -> St
}
}
fn aux_ability_from_string(ability: &str) -> common::comp::ability::AuxiliaryAbility {
fn aux_ability_from_string(ability: &str) -> comp::ability::AuxiliaryAbility {
use common::comp::ability::AuxiliaryAbility;
let mut parts = ability.split(":index:");
match parts.next() {
@ -184,7 +184,7 @@ fn aux_ability_from_string(ability: &str) -> common::comp::ability::AuxiliaryAbi
}
}
fn tool_kind_to_string(tool: Option<common::comp::item::tool::ToolKind>) -> String {
fn tool_kind_to_string(tool: Option<comp::item::tool::ToolKind>) -> String {
use common::comp::item::tool::ToolKind::*;
String::from(match tool {
Some(Sword) => "Sword",
@ -208,7 +208,7 @@ fn tool_kind_to_string(tool: Option<common::comp::item::tool::ToolKind>) -> Stri
})
}
fn tool_kind_from_string(tool: String) -> Option<common::comp::item::tool::ToolKind> {
fn tool_kind_from_string(tool: String) -> Option<comp::item::tool::ToolKind> {
use common::comp::item::tool::ToolKind::*;
match tool.as_str() {
"Sword" => Some(Sword),

View File

@ -1022,7 +1022,7 @@ mod tests {
#[test]
fn test_entity_configs() {
let dummy_pos = Vec3::new(0.0, 0.0, 0.0);
let mut dummy_rng = rand::thread_rng();
let mut dummy_rng = thread_rng();
// Bird Large test
for bird_large_species in BIRD_LARGE_ROSTER {
let female_body = comp::bird_large::Body {
@ -1035,13 +1035,9 @@ mod tests {
};
let female_config = bird_large_config(female_body);
std::mem::drop(
EntityInfo::at(dummy_pos).with_asset_expect(female_config, &mut dummy_rng),
);
drop(EntityInfo::at(dummy_pos).with_asset_expect(female_config, &mut dummy_rng));
let male_config = bird_large_config(male_body);
std::mem::drop(
EntityInfo::at(dummy_pos).with_asset_expect(male_config, &mut dummy_rng),
);
drop(EntityInfo::at(dummy_pos).with_asset_expect(male_config, &mut dummy_rng));
}
// Bird Medium test
for bird_med_species in BIRD_MEDIUM_ROSTER {
@ -1055,19 +1051,15 @@ mod tests {
};
let female_config = bird_medium_config(female_body);
std::mem::drop(
EntityInfo::at(dummy_pos).with_asset_expect(female_config, &mut dummy_rng),
);
drop(EntityInfo::at(dummy_pos).with_asset_expect(female_config, &mut dummy_rng));
let male_config = bird_medium_config(male_body);
std::mem::drop(
EntityInfo::at(dummy_pos).with_asset_expect(male_config, &mut dummy_rng),
);
drop(EntityInfo::at(dummy_pos).with_asset_expect(male_config, &mut dummy_rng));
}
// Humanoid test
for kind in RtSimEntityKind::iter() {
for rank in TravelerRank::iter() {
let config = humanoid_config(kind, rank);
std::mem::drop(EntityInfo::at(dummy_pos).with_asset_expect(config, &mut dummy_rng));
drop(EntityInfo::at(dummy_pos).with_asset_expect(config, &mut dummy_rng));
}
}
}

View File

@ -18,7 +18,7 @@ pub use self::v1::*;
#[derive(Deserialize, Serialize)]
pub enum AdminsRaw {
V0(v0::Admins),
V1(v1::Admins),
V1(Admins),
}
impl From<Admins> for AdminsRaw {

View File

@ -19,7 +19,7 @@ pub use self::v1::*;
#[derive(Deserialize, Serialize)]
pub enum BanlistRaw {
V0(v0::Banlist),
V1(v1::Banlist),
V1(Banlist),
}
impl From<Banlist> for BanlistRaw {

View File

@ -19,7 +19,7 @@ pub use self::v1::*;
#[derive(Deserialize, Serialize)]
pub enum ServerDescriptionRaw {
V0(v0::ServerDescription),
V1(v1::ServerDescription),
V1(ServerDescription),
}
impl From<ServerDescription> for ServerDescriptionRaw {

View File

@ -18,7 +18,7 @@ pub use self::v1::*;
#[derive(Deserialize, Serialize)]
pub enum WhitelistRaw {
V0(v0::Whitelist),
V1(v1::Whitelist),
V1(Whitelist),
}
impl From<Whitelist> for WhitelistRaw {

View File

@ -50,8 +50,8 @@ pub trait StateExt {
stats: comp::Stats,
skill_set: comp::SkillSet,
health: Option<comp::Health>,
poise: comp::Poise,
inventory: comp::Inventory,
poise: Poise,
inventory: Inventory,
body: comp::Body,
) -> EcsEntityBuilder;
/// Build a static object entity
@ -139,7 +139,7 @@ impl StateExt for State {
Effect::Damage(damage) => {
let inventories = self.ecs().read_storage::<Inventory>();
let stats = self.ecs().read_storage::<comp::Stats>();
let groups = self.ecs().read_storage::<comp::Group>();
let groups = self.ecs().read_storage::<Group>();
let damage_contributor = source.and_then(|uid| {
self.ecs().entity_from_uid(uid.0).map(|attacker_entity| {
@ -159,7 +159,7 @@ impl StateExt for State {
0.0,
1.0,
*time,
rand::random(),
random(),
);
self.ecs()
.write_storage::<comp::Health>()
@ -176,7 +176,7 @@ impl StateExt for State {
.get(entity)
{
if !character_state.is_stunned() {
let groups = self.ecs().read_storage::<comp::Group>();
let groups = self.ecs().read_storage::<Group>();
let damage_contributor = source.and_then(|uid| {
self.ecs().entity_from_uid(uid.0).map(|attacker_entity| {
DamageContributor::new(uid, groups.get(attacker_entity).cloned())
@ -191,7 +191,7 @@ impl StateExt for State {
time: *time,
};
self.ecs()
.write_storage::<comp::Poise>()
.write_storage::<Poise>()
.get_mut(entity)
.map(|mut poise| poise.change(poise_change));
}
@ -219,8 +219,8 @@ impl StateExt for State {
stats: comp::Stats,
skill_set: comp::SkillSet,
health: Option<comp::Health>,
poise: comp::Poise,
inventory: comp::Inventory,
poise: Poise,
inventory: Inventory,
body: comp::Body,
) -> EcsEntityBuilder {
self.ecs_mut()
@ -310,7 +310,7 @@ impl StateExt for State {
.with(body)
.with(comp::Scale(comp::ship::AIRSHIP_SCALE))
.with(comp::Controller::default())
.with(comp::inventory::Inventory::with_empty())
.with(Inventory::with_empty())
.with(comp::CharacterState::default())
// TODO: some of these are required in order for the character_behavior system to
// recognize a possesed airship; that system should be refactored to use `.maybe()`
@ -561,7 +561,7 @@ impl StateExt for State {
);
self.write_component_ignore_entity_dead(entity, comp::Health::new(body, health_level));
self.write_component_ignore_entity_dead(entity, comp::Energy::new(body, energy_level));
self.write_component_ignore_entity_dead(entity, comp::Poise::new(body));
self.write_component_ignore_entity_dead(entity, Poise::new(body));
self.write_component_ignore_entity_dead(entity, stats);
self.write_component_ignore_entity_dead(entity, active_abilities);
self.write_component_ignore_entity_dead(entity, skill_set);
@ -952,13 +952,8 @@ impl StateExt for State {
}
}
fn send_to_group(g: &comp::Group, ecs: &specs::World, msg: &comp::ChatMsg) {
for (client, group) in (
&ecs.read_storage::<Client>(),
&ecs.read_storage::<comp::Group>(),
)
.join()
{
fn send_to_group(g: &Group, ecs: &specs::World, msg: &comp::ChatMsg) {
for (client, group) in (&ecs.read_storage::<Client>(), &ecs.read_storage::<Group>()).join() {
if g == group {
client.send_fallible(ServerGeneral::ChatMsg(msg.clone()));
}

View File

@ -1104,7 +1104,7 @@ impl<'a> AgentData<'a> {
self.chat_npc(msg, event_emitter);
}
} else {
let mut rng = rand::thread_rng();
let mut rng = thread_rng();
if let Some(extreme_trait) =
self.rtsim_entity.and_then(|e| {
e.brain.personality.random_chat_trait(&mut rng)

View File

@ -924,7 +924,7 @@ impl<'a> AgentData<'a> {
_ =>
// if some illegal value slipped in, get zero vector
{
vek::Vec2::zero()
Vec2::zero()
},
};
let obstacle = read_data

View File

@ -30,7 +30,7 @@ pub fn add_server_systems(dispatch_builder: &mut DispatcherBuilder) {
dispatch::<melee::Sys>(dispatch_builder, &[&projectile::Sys::sys_name()]);
//Note: server should not depend on interpolation system
dispatch::<agent::Sys>(dispatch_builder, &[]);
dispatch::<terrain::Sys>(dispatch_builder, &[&msg::terrain::Sys::sys_name()]);
dispatch::<terrain::Sys>(dispatch_builder, &[&terrain::Sys::sys_name()]);
dispatch::<waypoint::Sys>(dispatch_builder, &[]);
dispatch::<invite_timeout::Sys>(dispatch_builder, &[]);
dispatch::<persistence::Sys>(dispatch_builder, &[]);

View File

@ -110,7 +110,7 @@ impl<'a> System<'a> for Sys {
for (entity, client, pending) in
(&read_data.entities, &read_data.clients, &mut pending_logins).join()
{
if let Err(e) = || -> std::result::Result<(), crate::error::Error> {
if let Err(e) = || -> Result<(), crate::error::Error> {
#[cfg(feature = "plugins")]
let ecs_world = EcsWorld {
entities: &read_data.entities,
@ -140,7 +140,7 @@ impl<'a> System<'a> for Sys {
entity,
common::comp::DisconnectReason::Kicked,
));
client.send(ServerRegisterAnswer::Err(e))?;
client.send(Err(e))?;
return Ok(());
},
Ok((username, uuid)) => (username, uuid),
@ -183,7 +183,7 @@ impl<'a> System<'a> for Sys {
if !player.is_valid() {
// Invalid player
client.send(ServerRegisterAnswer::Err(RegisterError::InvalidCharacter))?;
client.send(Err(RegisterError::InvalidCharacter))?;
return Ok(());
}
@ -201,7 +201,7 @@ impl<'a> System<'a> for Sys {
}
// Tell the client its request was successful.
client.send(ServerRegisterAnswer::Ok(()))?;
client.send(Ok(()))?;
// Send initial player list
client.send(ServerGeneral::PlayerListUpdate(PlayerListUpdate::Init(
@ -213,7 +213,7 @@ impl<'a> System<'a> for Sys {
}
Ok(())
}() {
tracing::trace!(?e, "failed to process register")
trace!(?e, "failed to process register")
};
}
for e in finished_pending {

View File

@ -214,7 +214,7 @@ pub fn initialize_region_subscription(world: &World, entity: specs::Entity) {
let fuzzy_chunk = (Vec2::<f32>::from(client_pos.0))
.map2(TerrainChunkSize::RECT_SIZE, |e, sz| e as i32 / sz as i32);
let chunk_size = TerrainChunkSize::RECT_SIZE.reduce_max() as f32;
let regions = common::region::regions_in_vd(
let regions = regions_in_vd(
client_pos.0,
(presence.view_distance as f32 * chunk_size) as f32
+ (presence::CHUNK_FUZZ as f32 + chunk_size) * 2.0f32.sqrt(),

View File

@ -88,10 +88,7 @@ impl TerrainPersistence {
File::open(&path)
.ok()
.map(|f| {
let bytes = match std::io::BufReader::new(f)
.bytes()
.collect::<Result<Vec<_>, _>>()
{
let bytes = match io::BufReader::new(f).bytes().collect::<Result<Vec<_>, _>>() {
Ok(bytes) => bytes,
Err(err) => {
error!(
@ -101,7 +98,7 @@ impl TerrainPersistence {
return Chunk::default();
},
};
match Chunk::deserialize_from(std::io::Cursor::new(bytes)) {
match Chunk::deserialize_from(io::Cursor::new(bytes)) {
Some(chunk) => chunk,
None => {
// Find an untaken name for a backup

View File

@ -134,7 +134,7 @@ pub struct SkeletonAttr {
snapper: bool,
}
impl<'a> std::convert::TryFrom<&'a comp::Body> for SkeletonAttr {
impl<'a> TryFrom<&'a comp::Body> for SkeletonAttr {
type Error = ();
fn try_from(body: &'a comp::Body) -> Result<Self, Self::Error> {

View File

@ -47,7 +47,7 @@ impl Animation for ChargeAnimation {
let ori: Vec2<f32> = Vec2::from(orientation);
let last_ori = Vec2::from(last_ori);
let tilt = if ::vek::Vec2::new(ori, last_ori)
let tilt = if vek::Vec2::new(ori, last_ori)
.map(|o| o.magnitude_squared())
.map(|m| m > 0.001 && m.is_finite())
.reduce_and()

View File

@ -131,7 +131,7 @@ impl Skeleton for BipedLargeSkeleton {
lantern: None,
// TODO: see quadruped_medium for how to animate this
mount_bone: Transform {
position: common::comp::Body::BipedLarge(body)
position: comp::Body::BipedLarge(body)
.mount_offset()
.into_tuple()
.into(),
@ -173,7 +173,7 @@ pub struct SkeletonAttr {
height: f32,
}
impl<'a> std::convert::TryFrom<&'a comp::Body> for SkeletonAttr {
impl<'a> TryFrom<&'a comp::Body> for SkeletonAttr {
type Error = ();
fn try_from(body: &'a comp::Body) -> Result<Self, Self::Error> {

View File

@ -105,7 +105,7 @@ impl Animation for RunAnimation {
let ori: Vec2<f32> = Vec2::from(orientation);
let last_ori = Vec2::from(last_ori);
let tilt = if ::vek::Vec2::new(ori, last_ori)
let tilt = if vek::Vec2::new(ori, last_ori)
.map(|o| o.magnitude_squared())
.map(|m| m > 0.001 && m.is_finite())
.reduce_and()

View File

@ -77,7 +77,7 @@ impl Skeleton for BipedSmallSkeleton {
lantern: None,
// TODO: see quadruped_medium for how to animate this
mount_bone: Transform {
position: common::comp::Body::BipedSmall(body)
position: comp::Body::BipedSmall(body)
.mount_offset()
.into_tuple()
.into(),
@ -100,7 +100,7 @@ pub struct SkeletonAttr {
scaler: f32,
}
impl<'a> std::convert::TryFrom<&'a comp::Body> for SkeletonAttr {
impl<'a> TryFrom<&'a comp::Body> for SkeletonAttr {
type Error = ();
fn try_from(body: &'a comp::Body) -> Result<Self, Self::Error> {

View File

@ -62,7 +62,7 @@ impl Animation for RunAnimation {
let sideabs = side.abs();
let ori: Vec2<f32> = Vec2::from(orientation);
let last_ori = Vec2::from(last_ori);
let tilt = if ::vek::Vec2::new(ori, last_ori)
let tilt = if vek::Vec2::new(ori, last_ori)
.map(|o| o.magnitude_squared())
.map(|m| m > 0.001 && m.is_finite())
.reduce_and()

View File

@ -43,7 +43,7 @@ impl Animation for AlphaAnimation {
let move1mirror = move1base * pullback * mirror;
let ori: Vec2<f32> = Vec2::from(orientation);
let last_ori = Vec2::from(last_ori);
let tilt = if ::vek::Vec2::new(ori, last_ori)
let tilt = if vek::Vec2::new(ori, last_ori)
.map(|o| o.magnitude_squared())
.map(|m| m > 0.001 && m.is_finite())
.reduce_and()

View File

@ -75,7 +75,7 @@ impl Animation for DashAnimation {
let ori: Vec2<f32> = Vec2::from(orientation);
let last_ori = Vec2::from(last_ori);
let tilt = if ::vek::Vec2::new(ori, last_ori)
let tilt = if vek::Vec2::new(ori, last_ori)
.map(|o| o.magnitude_squared())
.map(|m| m > 0.001 && m.is_finite())
.reduce_and()

View File

@ -46,7 +46,7 @@ impl Animation for FlyAnimation {
let ori: Vec2<f32> = Vec2::from(orientation);
let last_ori = Vec2::from(last_ori);
let tilt = if ::vek::Vec2::new(ori, last_ori)
let tilt = if vek::Vec2::new(ori, last_ori)
.map(|o| o.magnitude_squared())
.map(|m| m > 0.001 && m.is_finite())
.reduce_and()

View File

@ -100,7 +100,7 @@ impl Skeleton for BirdLargeSkeleton {
lantern: None,
// TODO: see quadruped_medium for how to animate this
mount_bone: Transform {
position: common::comp::Body::BirdLarge(body)
position: comp::Body::BirdLarge(body)
.mount_offset()
.into_tuple()
.into(),
@ -129,7 +129,7 @@ pub struct SkeletonAttr {
wyvern: bool,
}
impl<'a> std::convert::TryFrom<&'a comp::Body> for SkeletonAttr {
impl<'a> TryFrom<&'a comp::Body> for SkeletonAttr {
type Error = ();
fn try_from(body: &'a comp::Body) -> Result<Self, Self::Error> {

View File

@ -53,7 +53,7 @@ impl Animation for RunAnimation {
let foot2b = (mixed_vel * 1.0 * lab * speedmult + PI / 2.0).sin() * speednorm; //1.6
let ori: Vec2<f32> = Vec2::from(orientation);
let last_ori = Vec2::from(last_ori);
let tilt = if ::vek::Vec2::new(ori, last_ori)
let tilt = if vek::Vec2::new(ori, last_ori)
.map(|o| o.magnitude_squared())
.map(|m| m > 0.001 && m.is_finite())
.reduce_and()

View File

@ -54,7 +54,7 @@ impl Skeleton for BirdMediumSkeleton {
lantern: None,
// TODO: see quadruped_medium for how to animate this
mount_bone: Transform {
position: common::comp::Body::BirdMedium(body)
position: comp::Body::BirdMedium(body)
.mount_offset()
.into_tuple()
.into(),
@ -75,7 +75,7 @@ pub struct SkeletonAttr {
feed: f32,
}
impl<'a> std::convert::TryFrom<&'a comp::Body> for SkeletonAttr {
impl<'a> TryFrom<&'a comp::Body> for SkeletonAttr {
type Error = ();
fn try_from(body: &'a comp::Body) -> Result<Self, Self::Error> {

View File

@ -42,7 +42,7 @@ impl Animation for JumpAnimation {
let ori: Vec2<f32> = Vec2::from(orientation);
let last_ori = Vec2::from(last_ori);
let tilt = if ::vek::Vec2::new(ori, last_ori)
let tilt = if vek::Vec2::new(ori, last_ori)
.map(|o| o.magnitude_squared())
.map(|m| m > 0.001 && m.is_finite())
.reduce_and()

View File

@ -157,7 +157,7 @@ impl Skeleton for CharacterSkeleton {
lantern: Some((lantern_mat * Vec4::new(0.0, 0.5, -6.0, 1.0)).xyz()),
// TODO: see quadruped_medium for how to animate this
mount_bone: Transform {
position: common::comp::Body::Humanoid(body)
position: comp::Body::Humanoid(body)
.mount_offset()
.into_tuple()
.into(),
@ -243,7 +243,7 @@ impl Default for SkeletonAttr {
}
}
impl<'a> std::convert::TryFrom<&'a comp::Body> for SkeletonAttr {
impl<'a> TryFrom<&'a comp::Body> for SkeletonAttr {
type Error = ();
fn try_from(body: &'a comp::Body) -> Result<Self, Self::Error> {

View File

@ -60,7 +60,7 @@ impl Animation for MountAnimation {
let speed = (Vec2::<f32>::from(velocity).magnitude()).min(24.0);
let canceler = (speed / 24.0).powf(0.6);
let _x_tilt = avg_vel.z.atan2(avg_vel.xy().magnitude()) * canceler;
let tilt = if ::vek::Vec2::new(ori, last_ori)
let tilt = if vek::Vec2::new(ori, last_ori)
.map(|o| o.magnitude_squared())
.map(|m| m > 0.001 && m.is_finite())
.reduce_and()

View File

@ -51,7 +51,7 @@ impl Animation for RollAnimation {
let ori: Vec2<f32> = Vec2::from(orientation);
let last_ori = Vec2::from(last_ori);
let tilt = if ::vek::Vec2::new(ori, last_ori)
let tilt = if vek::Vec2::new(ori, last_ori)
.map(|o| o.magnitude_squared())
.map(|m| m > 0.0001 && m.is_finite())
.reduce_and()

View File

@ -92,7 +92,7 @@ impl Animation for RunAnimation {
let sideabs = side.abs();
let ori: Vec2<f32> = Vec2::from(orientation);
let last_ori = Vec2::from(last_ori);
let tilt = if ::vek::Vec2::new(ori, last_ori)
let tilt = if vek::Vec2::new(ori, last_ori)
.map(|o| o.magnitude_squared())
.map(|m| m > 0.001 && m.is_finite())
.reduce_and()

View File

@ -53,7 +53,7 @@ impl Animation for ShootAnimation {
let lab: f32 = 1.0;
let ori: Vec2<f32> = Vec2::from(orientation);
let last_ori = Vec2::from(last_ori);
let tilt = if ::vek::Vec2::new(ori, last_ori)
let tilt = if vek::Vec2::new(ori, last_ori)
.map(|o| o.magnitude_squared())
.map(|m| m > 0.001 && m.is_finite())
.reduce_and()

View File

@ -62,7 +62,7 @@ impl Animation for SneakAnimation {
let orientation: Vec2<f32> = Vec2::from(orientation);
let last_ori = Vec2::from(last_ori);
let tilt = if ::vek::Vec2::new(orientation, last_ori)
let tilt = if vek::Vec2::new(orientation, last_ori)
.map(|o| o.magnitude_squared())
.map(|m| m > 0.001 && m.is_finite())
.reduce_and()

View File

@ -61,7 +61,7 @@ impl Animation for SneakEquipAnimation {
let orientation: Vec2<f32> = Vec2::from(orientation);
let last_ori = Vec2::from(last_ori);
let tilt = if ::vek::Vec2::new(orientation, last_ori)
let tilt = if vek::Vec2::new(orientation, last_ori)
.map(|o| o.magnitude_squared())
.map(|m| m > 0.001 && m.is_finite())
.reduce_and()

View File

@ -72,7 +72,7 @@ impl Animation for SneakWieldAnimation {
let orientation: Vec2<f32> = Vec2::from(orientation);
let last_ori = Vec2::from(last_ori);
let tilt = if ::vek::Vec2::new(orientation, last_ori)
let tilt = if vek::Vec2::new(orientation, last_ori)
.map(|o| o.magnitude_squared())
.map(|m| m > 0.001 && m.is_finite())
.reduce_and()

View File

@ -37,7 +37,7 @@ impl Animation for StandAnimation {
let impact = (avg_vel.z).max(-15.0);
let ori: Vec2<f32> = Vec2::from(orientation);
let last_ori = Vec2::from(last_ori);
let tilt = if ::vek::Vec2::new(ori, last_ori)
let tilt = if vek::Vec2::new(ori, last_ori)
.map(|o| o.magnitude_squared())
.map(|m| m > 0.001 && m.is_finite())
.reduce_and()

Some files were not shown because too many files have changed in this diff Show More