diff --git a/Cargo.toml b/Cargo.toml index dc84bf06..dd3c6bcf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,7 +23,7 @@ resolver = "2" [workspace.package] version = "0.11.0+mc1.21.4" -edition = "2021" +edition = "2024" license = "MIT" repository = "https://github.com/azalea-rs/azalea" # homepage = "https://github.com/azalea-rs/azalea" diff --git a/azalea-auth/src/auth.rs b/azalea-auth/src/auth.rs index 55d7d36a..99dfc115 100755 --- a/azalea-auth/src/auth.rs +++ b/azalea-auth/src/auth.rs @@ -360,7 +360,7 @@ pub async fn get_ms_auth_token( tokio::time::sleep(std::time::Duration::from_secs(res.interval)).await; trace!("Polling to check if user has logged in..."); - if let Ok(access_token_response) = client + let res = client .post(format!( "https://login.live.com/oauth20_token.srf?client_id={client_id}" )) @@ -372,8 +372,8 @@ pub async fn get_ms_auth_token( .send() .await? .json::() - .await - { + .await; + if let Ok(access_token_response) = res { trace!("access_token_response: {:?}", access_token_response); let expires_at = SystemTime::now() + std::time::Duration::from_secs(access_token_response.expires_in); diff --git a/azalea-auth/src/certs.rs b/azalea-auth/src/certs.rs index 9f9147a8..7a6e12f9 100644 --- a/azalea-auth/src/certs.rs +++ b/azalea-auth/src/certs.rs @@ -1,6 +1,6 @@ use base64::Engine; use chrono::{DateTime, Utc}; -use rsa::{pkcs8::DecodePrivateKey, RsaPrivateKey}; +use rsa::{RsaPrivateKey, pkcs8::DecodePrivateKey}; use serde::Deserialize; use thiserror::Error; use tracing::trace; diff --git a/azalea-auth/src/sessionserver.rs b/azalea-auth/src/sessionserver.rs index e7052e11..87d0e32c 100755 --- a/azalea-auth/src/sessionserver.rs +++ b/azalea-auth/src/sessionserver.rs @@ -159,7 +159,7 @@ pub async fn serverside_auth( StatusCode::FORBIDDEN => { return Err(ServerSessionServerError::Unknown( res.json::().await?.error, - )) + )); } status_code => { // log the headers diff --git a/azalea-block/azalea-block-macros/src/lib.rs b/azalea-block/azalea-block-macros/src/lib.rs index f0f27343..7952a8d1 100755 --- a/azalea-block/azalea-block-macros/src/lib.rs +++ b/azalea-block/azalea-block-macros/src/lib.rs @@ -9,13 +9,13 @@ use proc_macro::TokenStream; use proc_macro2::TokenTree; use quote::quote; use syn::{ - braced, + Expr, Ident, LitStr, Token, braced, ext::IdentExt, parenthesized, parse::{Parse, ParseStream, Result}, parse_macro_input, punctuated::Punctuated, - token, Expr, Ident, LitStr, Token, + token, }; use utils::{combinations_of, to_pascal_case}; @@ -511,13 +511,13 @@ pub fn make_block_states(input: TokenStream) -> TokenStream { Ident::new(&combination[i].to_string(), proc_macro2::Span::call_site()); // this terrible code just gets the property default as a string - let property_default_as_string = if let TokenTree::Ident(ident) = - property.default.clone().into_iter().last().unwrap() - { - ident.to_string() - } else { - panic!() - }; + let property_default_as_string = + match property.default.clone().into_iter().last().unwrap() { + TokenTree::Ident(ident) => ident.to_string(), + _ => { + panic!() + } + }; if property_default_as_string != combination[i] { is_default = false; } @@ -565,15 +565,16 @@ pub fn make_block_states(input: TokenStream) -> TokenStream { let Some(default_state_id) = default_state_id else { let defaults = properties_with_name .iter() - .map(|p| { - if let TokenTree::Ident(i) = p.default.clone().into_iter().last().unwrap() { - i.to_string() - } else { + .map(|p| match p.default.clone().into_iter().last().unwrap() { + TokenTree::Ident(i) => i.to_string(), + _ => { panic!() } }) .collect::>(); - panic!("Couldn't get default state id for {block_name_pascal_case}, combinations={block_properties_vec:?}, defaults={defaults:?}") + panic!( + "Couldn't get default state id for {block_name_pascal_case}, combinations={block_properties_vec:?}, defaults={defaults:?}" + ) }; // 7035..=7058 => { diff --git a/azalea-block/src/range.rs b/azalea-block/src/range.rs index 7182bb65..18e74c88 100644 --- a/azalea-block/src/range.rs +++ b/azalea-block/src/range.rs @@ -1,9 +1,9 @@ use std::{ - collections::{hash_set, HashSet}, + collections::{HashSet, hash_set}, ops::{Add, RangeInclusive}, }; -use crate::{block_state::BlockStateIntegerRepr, BlockState}; +use crate::{BlockState, block_state::BlockStateIntegerRepr}; #[derive(Debug, Clone)] pub struct BlockStates { diff --git a/azalea-brigadier/src/command_dispatcher.rs b/azalea-brigadier/src/command_dispatcher.rs index 619131e2..15648b42 100755 --- a/azalea-brigadier/src/command_dispatcher.rs +++ b/azalea-brigadier/src/command_dispatcher.rs @@ -108,23 +108,30 @@ impl CommandDispatcher { 1 }) { reader.skip(); - if let Some(redirect) = &child.read().redirect { - let child_context = - CommandContextBuilder::new(self, source, redirect.clone(), reader.cursor); - let parse = self - .parse_nodes(redirect, &reader, child_context) - .expect("Parsing nodes failed"); - context.with_child(Rc::new(parse.context)); - return Ok(ParseResults { - context, - reader: parse.reader, - exceptions: parse.exceptions, - }); - } else { - let parse = self - .parse_nodes(&child, &reader, context) - .expect("Parsing nodes failed"); - potentials.push(parse); + match &child.read().redirect { + Some(redirect) => { + let child_context = CommandContextBuilder::new( + self, + source, + redirect.clone(), + reader.cursor, + ); + let parse = self + .parse_nodes(redirect, &reader, child_context) + .expect("Parsing nodes failed"); + context.with_child(Rc::new(parse.context)); + return Ok(ParseResults { + context, + reader: parse.reader, + exceptions: parse.exceptions, + }); + } + _ => { + let parse = self + .parse_nodes(&child, &reader, context) + .expect("Parsing nodes failed"); + potentials.push(parse); + } } } else { potentials.push(ParseResults { @@ -215,11 +222,14 @@ impl CommandDispatcher { pub fn find_node(&self, path: &[&str]) -> Option>>> { let mut node = self.root.clone(); for name in path { - if let Some(child) = node.clone().read().child(name) { - node = child; - } else { - return None; - } + match node.clone().read().child(name) { + Some(child) => { + node = child; + } + _ => { + return None; + } + }; } Some(node) } @@ -258,31 +268,41 @@ impl CommandDispatcher { let modifier = &context.modifier; if let Some(modifier) = modifier { let results = modifier(context); - if let Ok(results) = results { - if !results.is_empty() { - next.extend(results.iter().map(|s| child.copy_for(s.clone()))); + match results { + Ok(results) => { + if !results.is_empty() { + next.extend( + results.iter().map(|s| child.copy_for(s.clone())), + ); + } } - } else { - // TODO - // self.consumer.on_command_complete(context, false, 0); - if !forked { - return Err(results.err().unwrap()); + _ => { + // TODO + // self.consumer.on_command_complete(context, false, 0); + if !forked { + return Err(results.err().unwrap()); + } } } } else { next.push(child.copy_for(context.source.clone())); } } - } else if let Some(context_command) = &context.command { - found_command = true; + } else { + match &context.command { + Some(context_command) => { + found_command = true; - let value = context_command(context); - result += value; - // consumer.on_command_complete(context, true, value); - successful_forks += 1; + let value = context_command(context); + result += value; + // consumer.on_command_complete(context, true, value); + successful_forks += 1; - // TODO: allow context_command to error and handle those - // errors + // TODO: allow context_command to error and handle + // those errors + } + _ => {} + } } } @@ -332,32 +352,35 @@ impl CommandDispatcher { if node.command.is_some() { result.push(prefix.to_owned()); } - if let Some(redirect) = &node.redirect { - let redirect = if redirect.data_ptr() == self.root.data_ptr() { - "...".to_string() - } else { - format!("-> {}", redirect.read().usage_text()) - }; - if prefix.is_empty() { - result.push(format!("{} {redirect}", node.usage_text())); - } else { - result.push(format!("{prefix} {redirect}")); + match &node.redirect { + Some(redirect) => { + let redirect = if redirect.data_ptr() == self.root.data_ptr() { + "...".to_string() + } else { + format!("-> {}", redirect.read().usage_text()) + }; + if prefix.is_empty() { + result.push(format!("{} {redirect}", node.usage_text())); + } else { + result.push(format!("{prefix} {redirect}")); + } } - } else { - for child in node.children.values() { - let child = child.read(); - self.get_all_usage_recursive( - &child, - source, - result, - if prefix.is_empty() { - child.usage_text() - } else { - format!("{prefix} {}", child.usage_text()) - } - .as_str(), - restricted, - ); + _ => { + for child in node.children.values() { + let child = child.read(); + self.get_all_usage_recursive( + &child, + source, + result, + if prefix.is_empty() { + child.usage_text() + } else { + format!("{prefix} {}", child.usage_text()) + } + .as_str(), + restricted, + ); + } } } } diff --git a/azalea-brigadier/src/context/command_context.rs b/azalea-brigadier/src/context/command_context.rs index 3d401f96..202d6f21 100755 --- a/azalea-brigadier/src/context/command_context.rs +++ b/azalea-brigadier/src/context/command_context.rs @@ -2,7 +2,7 @@ use std::{any::Any, collections::HashMap, fmt::Debug, rc::Rc, sync::Arc}; use parking_lot::RwLock; -use super::{parsed_command_node::ParsedCommandNode, string_range::StringRange, ParsedArgument}; +use super::{ParsedArgument, parsed_command_node::ParsedCommandNode, string_range::StringRange}; use crate::{ modifier::RedirectModifier, tree::{Command, CommandNode}, diff --git a/azalea-brigadier/src/context/command_context_builder.rs b/azalea-brigadier/src/context/command_context_builder.rs index 3fb8ec70..87427bc1 100755 --- a/azalea-brigadier/src/context/command_context_builder.rs +++ b/azalea-brigadier/src/context/command_context_builder.rs @@ -3,8 +3,8 @@ use std::{collections::HashMap, fmt::Debug, rc::Rc, sync::Arc}; use parking_lot::RwLock; use super::{ - command_context::CommandContext, parsed_command_node::ParsedCommandNode, - string_range::StringRange, suggestion_context::SuggestionContext, ParsedArgument, + ParsedArgument, command_context::CommandContext, parsed_command_node::ParsedCommandNode, + string_range::StringRange, suggestion_context::SuggestionContext, }; use crate::{ command_dispatcher::CommandDispatcher, @@ -107,18 +107,18 @@ impl<'a, S> CommandContextBuilder<'a, S> { } if self.range.end() < cursor { - if let Some(child) = &self.child { - child.find_suggestion_context(cursor) - } else if let Some(last) = self.nodes.last() { - SuggestionContext { - parent: Arc::clone(&last.node), - start_pos: last.range.end() + 1, - } - } else { - SuggestionContext { - parent: Arc::clone(&self.root), - start_pos: self.range.start(), - } + match &self.child { + Some(child) => child.find_suggestion_context(cursor), + _ => match self.nodes.last() { + Some(last) => SuggestionContext { + parent: Arc::clone(&last.node), + start_pos: last.range.end() + 1, + }, + _ => SuggestionContext { + parent: Arc::clone(&self.root), + start_pos: self.range.start(), + }, + }, } } else { let mut prev = &self.root; diff --git a/azalea-brigadier/src/tree/mod.rs b/azalea-brigadier/src/tree/mod.rs index dfa3b375..690e5df3 100755 --- a/azalea-brigadier/src/tree/mod.rs +++ b/azalea-brigadier/src/tree/mod.rs @@ -292,18 +292,27 @@ impl PartialEq for CommandNode { } } - if let Some(selfexecutes) = &self.command { - // idk how to do this better since we can't compare `dyn Fn`s - if let Some(otherexecutes) = &other.command { - #[allow(ambiguous_wide_pointer_comparisons)] - if !Arc::ptr_eq(selfexecutes, otherexecutes) { + match &self.command { + Some(selfexecutes) => { + // idk how to do this better since we can't compare `dyn Fn`s + match &other.command { + Some(otherexecutes) => + { + #[allow(ambiguous_wide_pointer_comparisons)] + if !Arc::ptr_eq(selfexecutes, otherexecutes) { + return false; + } + } + _ => { + return false; + } + } + } + _ => { + if other.command.is_some() { return false; } - } else { - return false; } - } else if other.command.is_some() { - return false; } true } diff --git a/azalea-brigadier/tests/builder/argument_builder_test.rs b/azalea-brigadier/tests/builder/argument_builder_test.rs index d5f940dd..178a383b 100755 --- a/azalea-brigadier/tests/builder/argument_builder_test.rs +++ b/azalea-brigadier/tests/builder/argument_builder_test.rs @@ -10,11 +10,13 @@ fn test_arguments() { let builder = builder.then(argument.clone()); assert_eq!(builder.arguments().children.len(), 1); let built_argument = Rc::new(argument.build()); - assert!(builder - .arguments() - .children - .values() - .any(|e| *e.read() == *built_argument)); + assert!( + builder + .arguments() + .children + .values() + .any(|e| *e.read() == *built_argument) + ); } // @Test diff --git a/azalea-buf/azalea-buf-macros/src/lib.rs b/azalea-buf/azalea-buf-macros/src/lib.rs index dec624e3..c4938f89 100755 --- a/azalea-buf/azalea-buf-macros/src/lib.rs +++ b/azalea-buf/azalea-buf-macros/src/lib.rs @@ -3,7 +3,7 @@ mod write; use proc_macro::TokenStream; use quote::quote; -use syn::{parse_macro_input, DeriveInput}; +use syn::{DeriveInput, parse_macro_input}; #[proc_macro_derive(AzaleaRead, attributes(var))] pub fn derive_azalearead(input: TokenStream) -> TokenStream { diff --git a/azalea-buf/azalea-buf-macros/src/read.rs b/azalea-buf/azalea-buf-macros/src/read.rs index c093d4a1..0500ec7c 100644 --- a/azalea-buf/azalea-buf-macros/src/read.rs +++ b/azalea-buf/azalea-buf-macros/src/read.rs @@ -1,5 +1,5 @@ -use quote::{quote, ToTokens}; -use syn::{punctuated::Punctuated, token::Comma, Data, Field, FieldsNamed, Ident}; +use quote::{ToTokens, quote}; +use syn::{Data, Field, FieldsNamed, Ident, punctuated::Punctuated, token::Comma}; fn read_named_fields( named: &Punctuated, diff --git a/azalea-buf/azalea-buf-macros/src/write.rs b/azalea-buf/azalea-buf-macros/src/write.rs index df461d59..de436e70 100644 --- a/azalea-buf/azalea-buf-macros/src/write.rs +++ b/azalea-buf/azalea-buf-macros/src/write.rs @@ -1,6 +1,6 @@ use proc_macro2::Span; -use quote::{quote, ToTokens}; -use syn::{punctuated::Punctuated, token::Comma, Data, Field, FieldsNamed, Ident}; +use quote::{ToTokens, quote}; +use syn::{Data, Field, FieldsNamed, Ident, punctuated::Punctuated, token::Comma}; fn write_named_fields( named: &Punctuated, diff --git a/azalea-buf/src/read.rs b/azalea-buf/src/read.rs index 71c96c34..e6f7aa51 100755 --- a/azalea-buf/src/read.rs +++ b/azalea-buf/src/read.rs @@ -5,11 +5,11 @@ use std::{ io::{Cursor, Read}, }; -use byteorder::{ReadBytesExt, BE}; +use byteorder::{BE, ReadBytesExt}; use thiserror::Error; use tracing::warn; -use super::{UnsizedByteArray, MAX_STRING_LENGTH}; +use super::{MAX_STRING_LENGTH, UnsizedByteArray}; #[derive(Error, Debug)] pub enum BufReadError { @@ -19,7 +19,9 @@ pub enum BufReadError { InvalidVarLong, #[error("Error reading bytes")] CouldNotReadBytes, - #[error("The received encoded string buffer length is longer than maximum allowed ({length} > {max_length})")] + #[error( + "The received encoded string buffer length is longer than maximum allowed ({length} > {max_length})" + )] StringLengthTooLong { length: u32, max_length: u32 }, #[error("The received Vec length is longer than maximum allowed ({length} > {max_length})")] VecLengthTooLong { length: u32, max_length: u32 }, diff --git a/azalea-buf/src/serializable_uuid.rs b/azalea-buf/src/serializable_uuid.rs index 53eccbbb..10e57eeb 100755 --- a/azalea-buf/src/serializable_uuid.rs +++ b/azalea-buf/src/serializable_uuid.rs @@ -2,7 +2,7 @@ use std::io::{Cursor, Write}; use uuid::Uuid; -use crate::{read::BufReadError, AzaleaRead, AzaleaWrite}; +use crate::{AzaleaRead, AzaleaWrite, read::BufReadError}; pub trait SerializableUuid { fn to_int_array(&self) -> [u32; 4]; diff --git a/azalea-buf/src/write.rs b/azalea-buf/src/write.rs index 73bcbdce..c4b9f413 100755 --- a/azalea-buf/src/write.rs +++ b/azalea-buf/src/write.rs @@ -5,7 +5,7 @@ use std::{ use byteorder::{BigEndian, WriteBytesExt}; -use super::{UnsizedByteArray, MAX_STRING_LENGTH}; +use super::{MAX_STRING_LENGTH, UnsizedByteArray}; fn write_utf_with_len(buf: &mut impl Write, string: &str, len: usize) -> Result<(), io::Error> { if string.len() > len { diff --git a/azalea-chat/src/base_component.rs b/azalea-chat/src/base_component.rs index b01f2eb3..cbc5ae8b 100755 --- a/azalea-chat/src/base_component.rs +++ b/azalea-chat/src/base_component.rs @@ -1,6 +1,6 @@ use serde::Serialize; -use crate::{style::Style, FormattedText}; +use crate::{FormattedText, style::Style}; #[derive(Clone, Debug, PartialEq, Serialize, Eq, Hash)] pub struct BaseComponent { diff --git a/azalea-chat/src/component.rs b/azalea-chat/src/component.rs index 4f772e36..e96ead43 100755 --- a/azalea-chat/src/component.rs +++ b/azalea-chat/src/component.rs @@ -2,7 +2,7 @@ use std::{fmt::Display, sync::LazyLock}; #[cfg(feature = "azalea-buf")] use azalea_buf::{AzaleaRead, AzaleaWrite, BufReadError}; -use serde::{de, Deserialize, Deserializer, Serialize}; +use serde::{Deserialize, Deserializer, Serialize, de}; #[cfg(feature = "simdnbt")] use simdnbt::{Deserialize as _, FromNbtTag as _, Serialize as _}; use tracing::{debug, trace, warn}; @@ -371,7 +371,9 @@ impl FormattedText { } else if let Some(s) = primitive.string() { with_array.push(StringOrComponent::String(s.to_string())); } else { - warn!("couldn't parse {item:?} as FormattedText because it has a disallowed primitive"); + warn!( + "couldn't parse {item:?} as FormattedText because it has a disallowed primitive" + ); with_array.push(StringOrComponent::String("?".to_string())); } } else if let Some(c) = FormattedText::from_nbt_compound(item) { @@ -392,7 +394,9 @@ impl FormattedText { } } } else { - warn!("couldn't parse {with:?} as FormattedText because it's not a list of compounds"); + warn!( + "couldn't parse {with:?} as FormattedText because it's not a list of compounds" + ); return None; } component = @@ -456,12 +460,11 @@ impl From<&simdnbt::Mutf8Str> for FormattedText { impl AzaleaRead for FormattedText { fn azalea_read(buf: &mut std::io::Cursor<&[u8]>) -> Result { let nbt = simdnbt::borrow::read_optional_tag(buf)?; - if let Some(nbt) = nbt { - FormattedText::from_nbt_tag(nbt.as_tag()).ok_or(BufReadError::Custom( + match nbt { + Some(nbt) => FormattedText::from_nbt_tag(nbt.as_tag()).ok_or(BufReadError::Custom( "couldn't convert nbt to chat message".to_owned(), - )) - } else { - Ok(FormattedText::default()) + )), + _ => Ok(FormattedText::default()), } } } diff --git a/azalea-chat/src/style.rs b/azalea-chat/src/style.rs index 57fe76a0..26fa2633 100755 --- a/azalea-chat/src/style.rs +++ b/azalea-chat/src/style.rs @@ -2,7 +2,7 @@ use std::{collections::HashMap, fmt, sync::LazyLock}; #[cfg(feature = "azalea-buf")] use azalea_buf::AzBuf; -use serde::{ser::SerializeStruct, Serialize, Serializer}; +use serde::{Serialize, Serializer, ser::SerializeStruct}; use serde_json::Value; #[cfg(feature = "simdnbt")] use simdnbt::owned::{NbtCompound, NbtTag}; @@ -334,10 +334,15 @@ fn simdnbt_serialize_field( default: impl simdnbt::ToNbtTag, reset: bool, ) { - if let Some(value) = value { - compound.insert(name, value); - } else if reset { - compound.insert(name, default); + match value { + Some(value) => { + compound.insert(name, value); + } + _ => { + if reset { + compound.insert(name, default); + } + } } } diff --git a/azalea-chat/src/text_component.rs b/azalea-chat/src/text_component.rs index d3418ad8..db1b4edf 100755 --- a/azalea-chat/src/text_component.rs +++ b/azalea-chat/src/text_component.rs @@ -1,8 +1,8 @@ use std::fmt::Display; -use serde::{ser::SerializeMap, Serialize, Serializer, __private::ser::FlatMapSerializer}; +use serde::{__private::ser::FlatMapSerializer, Serialize, Serializer, ser::SerializeMap}; -use crate::{base_component::BaseComponent, style::ChatFormatting, FormattedText}; +use crate::{FormattedText, base_component::BaseComponent, style::ChatFormatting}; /// A component that contains text that's the same in all locales. #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] diff --git a/azalea-chat/src/translatable_component.rs b/azalea-chat/src/translatable_component.rs index ecd238a5..452de738 100755 --- a/azalea-chat/src/translatable_component.rs +++ b/azalea-chat/src/translatable_component.rs @@ -1,11 +1,11 @@ use std::fmt::{self, Display, Formatter}; -use serde::{ser::SerializeMap, Serialize, Serializer, __private::ser::FlatMapSerializer}; +use serde::{__private::ser::FlatMapSerializer, Serialize, Serializer, ser::SerializeMap}; #[cfg(feature = "simdnbt")] use simdnbt::Serialize as _; use crate::{ - base_component::BaseComponent, style::Style, text_component::TextComponent, FormattedText, + FormattedText, base_component::BaseComponent, style::Style, text_component::TextComponent, }; #[derive(Clone, Debug, PartialEq, Serialize, Eq, Hash)] diff --git a/azalea-chat/tests/integration_test.rs b/azalea-chat/tests/integration_test.rs index 122df538..ec305d49 100755 --- a/azalea-chat/tests/integration_test.rs +++ b/azalea-chat/tests/integration_test.rs @@ -1,6 +1,6 @@ use azalea_chat::{ - style::{Ansi, ChatFormatting, TextColor}, FormattedText, + style::{Ansi, ChatFormatting, TextColor}, }; use serde::Deserialize; use serde_json::Value; diff --git a/azalea-client/src/account.rs b/azalea-client/src/account.rs index 87573de0..5e2fafa7 100755 --- a/azalea-client/src/account.rs +++ b/azalea-client/src/account.rs @@ -2,8 +2,8 @@ use std::sync::Arc; -use azalea_auth::certs::{Certificates, FetchCertificatesError}; use azalea_auth::AccessTokenResponse; +use azalea_auth::certs::{Certificates, FetchCertificatesError}; use bevy_ecs::component::Component; use parking_lot::Mutex; use thiserror::Error; diff --git a/azalea-client/src/attack.rs b/azalea-client/src/attack.rs index f626483f..0f5a8305 100644 --- a/azalea-client/src/attack.rs +++ b/azalea-client/src/attack.rs @@ -1,7 +1,8 @@ use azalea_core::{game_type::GameMode, tick::GameTick}; use azalea_entity::{ + Attributes, Physics, metadata::{ShiftKeyDown, Sprinting}, - update_bounding_box, Attributes, Physics, + update_bounding_box, }; use azalea_physics::PhysicsSet; use azalea_protocol::packets::game::s_interact::{self, ServerboundInteract}; @@ -11,8 +12,8 @@ use bevy_ecs::prelude::*; use derive_more::{Deref, DerefMut}; use crate::{ - interact::SwingArmEvent, local_player::LocalGameMode, movement::MoveEventsSet, - packet_handling::game::SendPacketEvent, respawn::perform_respawn, Client, + Client, interact::SwingArmEvent, local_player::LocalGameMode, movement::MoveEventsSet, + packet_handling::game::SendPacketEvent, respawn::perform_respawn, }; pub struct AttackPlugin; diff --git a/azalea-client/src/chat.rs b/azalea-client/src/chat.rs index 97fdde72..2bef9570 100755 --- a/azalea-client/src/chat.rs +++ b/azalea-client/src/chat.rs @@ -7,6 +7,7 @@ use std::{ use azalea_chat::FormattedText; use azalea_protocol::packets::{ + Packet, game::{ c_disguised_chat::ClientboundDisguisedChat, c_player_chat::ClientboundPlayerChat, @@ -14,7 +15,6 @@ use azalea_protocol::packets::{ s_chat::{LastSeenMessagesUpdate, ServerboundChat}, s_chat_command::ServerboundChatCommand, }, - Packet, }; use bevy_app::{App, Plugin, Update}; use bevy_ecs::{ @@ -27,7 +27,7 @@ use uuid::Uuid; use crate::{ client::Client, - packet_handling::game::{handle_send_packet_event, SendPacketEvent}, + packet_handling::game::{SendPacketEvent, handle_send_packet_event}, }; /// A chat packet, either a system message or a chat message. diff --git a/azalea-client/src/chunks.rs b/azalea-client/src/chunks.rs index 0267c164..67313757 100644 --- a/azalea-client/src/chunks.rs +++ b/azalea-client/src/chunks.rs @@ -19,11 +19,11 @@ use simdnbt::owned::BaseNbt; use tracing::{error, trace}; use crate::{ + InstanceHolder, interact::handle_block_interact_event, inventory::InventorySet, - packet_handling::game::{handle_send_packet_event, SendPacketEvent}, + packet_handling::game::{SendPacketEvent, handle_send_packet_event}, respawn::perform_respawn, - InstanceHolder, }; pub struct ChunkPlugin; diff --git a/azalea-client/src/client.rs b/azalea-client/src/client.rs index 9de97cc1..2f7460f5 100644 --- a/azalea-client/src/client.rs +++ b/azalea-client/src/client.rs @@ -14,29 +14,29 @@ use azalea_core::{ tick::GameTick, }; use azalea_entity::{ + EntityPlugin, EntityUpdateSet, EyeHeight, LocalEntity, Position, indexing::{EntityIdIndex, EntityUuidIndex}, metadata::Health, - EntityPlugin, EntityUpdateSet, EyeHeight, LocalEntity, Position, }; use azalea_physics::PhysicsPlugin; use azalea_protocol::{ + ServerAddress, common::client_information::ClientInformation, connect::{Connection, ConnectionError, Proxy}, packets::{ - self, + self, ClientIntention, ConnectionProtocol, PROTOCOL_VERSION, Packet, config::{ClientboundConfigPacket, ServerboundConfigPacket}, game::ServerboundGamePacket, handshake::{ - s_intention::ServerboundIntention, ClientboundHandshakePacket, - ServerboundHandshakePacket, + ClientboundHandshakePacket, ServerboundHandshakePacket, + s_intention::ServerboundIntention, }, login::{ - s_hello::ServerboundHello, s_key::ServerboundKey, - s_login_acknowledged::ServerboundLoginAcknowledged, ClientboundLoginPacket, + ClientboundLoginPacket, s_hello::ServerboundHello, s_key::ServerboundKey, + s_login_acknowledged::ServerboundLoginAcknowledged, }, - ClientIntention, ConnectionProtocol, Packet, PROTOCOL_VERSION, }, - resolver, ServerAddress, + resolver, }; use azalea_world::{Instance, InstanceContainer, InstanceName, PartialInstance}; use bevy_app::{App, Plugin, PluginGroup, PluginGroupBuilder, Update}; @@ -61,6 +61,7 @@ use tracing::{debug, error}; use uuid::Uuid; use crate::{ + Account, PlayerInfo, attack::{self, AttackPlugin}, chat::ChatPlugin, chunks::{ChunkBatchInfo, ChunkPlugin}, @@ -70,21 +71,20 @@ use crate::{ interact::{CurrentSequenceNumber, InteractPlugin}, inventory::{Inventory, InventoryPlugin}, local_player::{ - death_event, GameProfileComponent, Hunger, InstanceHolder, PermissionLevel, - PlayerAbilities, TabList, + GameProfileComponent, Hunger, InstanceHolder, PermissionLevel, PlayerAbilities, TabList, + death_event, }, mining::{self, MinePlugin}, movement::{LastSentLookDirection, PhysicsState, PlayerMovePlugin}, packet_handling::{ - login::{self, InLoginState, LoginSendPacketQueue}, PacketHandlerPlugin, + login::{self, InLoginState, LoginSendPacketQueue}, }, player::retroactively_add_game_profile_component, raw_connection::RawConnection, respawn::RespawnPlugin, send_client_end::TickEndPlugin, task_pool::TaskPoolPlugin, - Account, PlayerInfo, }; /// `Client` has the things that a user interacting with the library will want. diff --git a/azalea-client/src/configuration.rs b/azalea-client/src/configuration.rs index 6f752bbd..d578be7a 100644 --- a/azalea-client/src/configuration.rs +++ b/azalea-client/src/configuration.rs @@ -44,7 +44,9 @@ fn handle_end_login_state( let client_information = match query.get(entity).ok() { Some(i) => i, None => { - warn!("ClientInformation component was not set before leaving login state, using a default"); + warn!( + "ClientInformation component was not set before leaving login state, using a default" + ); &ClientInformation::default() } }; diff --git a/azalea-client/src/disconnect.rs b/azalea-client/src/disconnect.rs index c653e195..a1eac971 100644 --- a/azalea-client/src/disconnect.rs +++ b/azalea-client/src/disconnect.rs @@ -1,7 +1,7 @@ //! Disconnect a client from the server. use azalea_chat::FormattedText; -use azalea_entity::{metadata::PlayerMetadataBundle, EntityBundle, LocalEntity}; +use azalea_entity::{EntityBundle, LocalEntity, metadata::PlayerMetadataBundle}; use bevy_app::{App, Plugin, PostUpdate}; use bevy_ecs::{ component::Component, @@ -16,8 +16,8 @@ use derive_more::Deref; use tracing::trace; use crate::{ - client::JoinedClientBundle, events::LocalPlayerEvents, raw_connection::RawConnection, - InstanceHolder, + InstanceHolder, client::JoinedClientBundle, events::LocalPlayerEvents, + raw_connection::RawConnection, }; pub struct DisconnectPlugin; diff --git a/azalea-client/src/events.rs b/azalea-client/src/events.rs index 372350bb..aed16bcb 100644 --- a/azalea-client/src/events.rs +++ b/azalea-client/src/events.rs @@ -6,7 +6,7 @@ use std::sync::Arc; use azalea_chat::FormattedText; use azalea_core::tick::GameTick; use azalea_protocol::packets::game::{ - c_player_combat_kill::ClientboundPlayerCombatKill, ClientboundGamePacket, + ClientboundGamePacket, c_player_combat_kill::ClientboundPlayerCombatKill, }; use azalea_world::{InstanceName, MinecraftEntityId}; use bevy_app::{App, Plugin, PreUpdate, Update}; @@ -21,13 +21,13 @@ use derive_more::{Deref, DerefMut}; use tokio::sync::mpsc; use crate::{ + PlayerInfo, chat::{ChatPacket, ChatReceivedEvent}, disconnect::DisconnectEvent, packet_handling::game::{ AddPlayerEvent, DeathEvent, KeepAliveEvent, PacketEvent, RemovePlayerEvent, UpdatePlayerEvent, }, - PlayerInfo, }; // (for contributors): diff --git a/azalea-client/src/interact.rs b/azalea-client/src/interact.rs index e11873ae..fdeff197 100644 --- a/azalea-client/src/interact.rs +++ b/azalea-client/src/interact.rs @@ -8,9 +8,9 @@ use azalea_core::{ position::{BlockPos, Vec3}, }; use azalea_entity::{ - clamp_look_direction, view_vector, Attributes, EyeHeight, LocalEntity, LookDirection, Position, + Attributes, EyeHeight, LocalEntity, LookDirection, Position, clamp_look_direction, view_vector, }; -use azalea_inventory::{components, ItemStack, ItemStackData}; +use azalea_inventory::{ItemStack, ItemStackData, components}; use azalea_physics::clip::{BlockShapeType, ClipContext, FluidPickType}; use azalea_protocol::packets::game::{ s_interact::InteractionHand, @@ -31,13 +31,13 @@ use derive_more::{Deref, DerefMut}; use tracing::warn; use crate::{ + Client, attack::handle_attack_event, inventory::{Inventory, InventorySet}, local_player::{LocalGameMode, PermissionLevel, PlayerAbilities}, movement::MoveEventsSet, - packet_handling::game::{handle_send_packet_event, SendPacketEvent}, + packet_handling::game::{SendPacketEvent, handle_send_packet_event}, respawn::perform_respawn, - Client, }; /// A plugin that allows clients to interact with blocks in the world. @@ -245,15 +245,16 @@ pub fn check_is_interaction_restricted( // way of modifying that let held_item = inventory.held_item(); - if let ItemStack::Present(item) = &held_item { - let block = instance.chunks.get_block_state(block_pos); - let Some(block) = block else { - // block isn't loaded so just say that it is restricted - return true; - }; - check_block_can_be_broken_by_item_in_adventure_mode(item, &block) - } else { - true + match &held_item { + ItemStack::Present(item) => { + let block = instance.chunks.get_block_state(block_pos); + let Some(block) = block else { + // block isn't loaded so just say that it is restricted + return true; + }; + check_block_can_be_broken_by_item_in_adventure_mode(item, &block) + } + _ => true, } } GameMode::Spectator => true, diff --git a/azalea-client/src/inventory.rs b/azalea-client/src/inventory.rs index 2dd17853..4d796c9c 100644 --- a/azalea-client/src/inventory.rs +++ b/azalea-client/src/inventory.rs @@ -26,10 +26,10 @@ use bevy_ecs::{ use tracing::warn; use crate::{ - local_player::PlayerAbilities, - packet_handling::game::{handle_send_packet_event, SendPacketEvent}, - respawn::perform_respawn, Client, + local_player::PlayerAbilities, + packet_handling::game::{SendPacketEvent, handle_send_packet_event}, + respawn::perform_respawn, }; pub struct InventoryPlugin; @@ -124,10 +124,9 @@ impl Inventory { /// /// Use [`Self::menu_mut`] if you need a mutable reference. pub fn menu(&self) -> &azalea_inventory::Menu { - if let Some(menu) = &self.container_menu { - menu - } else { - &self.inventory_menu + match &self.container_menu { + Some(menu) => menu, + _ => &self.inventory_menu, } } @@ -137,10 +136,9 @@ impl Inventory { /// /// Use [`Self::menu`] if you don't need a mutable reference. pub fn menu_mut(&mut self) -> &mut azalea_inventory::Menu { - if let Some(menu) = &mut self.container_menu { - menu - } else { - &mut self.inventory_menu + match &mut self.container_menu { + Some(menu) => menu, + _ => &mut self.inventory_menu, } } @@ -286,10 +284,9 @@ impl Inventory { carried_count -= new_carried.count - slot_item_count; // we have to inline self.menu_mut() here to avoid the borrow checker // complaining - let menu = if let Some(menu) = &mut self.container_menu { - menu - } else { - &mut self.inventory_menu + let menu = match &mut self.container_menu { + Some(menu) => menu, + _ => &mut self.inventory_menu, }; *menu.slot_mut(slot_index as usize).unwrap() = ItemStack::Present(new_carried); diff --git a/azalea-client/src/lib.rs b/azalea-client/src/lib.rs index d07e323d..abe7c692 100644 --- a/azalea-client/src/lib.rs +++ b/azalea-client/src/lib.rs @@ -35,8 +35,8 @@ pub mod test_simulation; pub use account::{Account, AccountOpts}; pub use azalea_protocol::common::client_information::ClientInformation; pub use client::{ - start_ecs_runner, Client, DefaultPlugins, InConfigState, JoinError, JoinedClientBundle, - LocalPlayerBundle, StartClientOpts, TickBroadcast, + Client, DefaultPlugins, InConfigState, JoinError, JoinedClientBundle, LocalPlayerBundle, + StartClientOpts, TickBroadcast, start_ecs_runner, }; pub use events::Event; pub use local_player::{GameProfileComponent, Hunger, InstanceHolder, TabList}; diff --git a/azalea-client/src/local_player.rs b/azalea-client/src/local_player.rs index 9939c47a..7e323f4c 100644 --- a/azalea-client/src/local_player.rs +++ b/azalea-client/src/local_player.rs @@ -14,8 +14,8 @@ use tracing::error; use uuid::Uuid; use crate::{ - events::{Event as AzaleaEvent, LocalPlayerEvents}, ClientInformation, PlayerInfo, + events::{Event as AzaleaEvent, LocalPlayerEvents}, }; /// A component that keeps strong references to our [`PartialInstance`] and diff --git a/azalea-client/src/mining.rs b/azalea-client/src/mining.rs index ac4c9c0d..03063b3e 100644 --- a/azalea-client/src/mining.rs +++ b/azalea-client/src/mining.rs @@ -1,6 +1,6 @@ -use azalea_block::{fluid_state::FluidState, Block, BlockState}; +use azalea_block::{Block, BlockState, fluid_state::FluidState}; use azalea_core::{direction::Direction, game_type::GameMode, position::BlockPos, tick::GameTick}; -use azalea_entity::{mining::get_mine_progress, FluidOnEyes, Physics}; +use azalea_entity::{FluidOnEyes, Physics, mining::get_mine_progress}; use azalea_inventory::ItemStack; use azalea_physics::PhysicsSet; use azalea_protocol::packets::game::s_player_action::{self, ServerboundPlayerAction}; @@ -10,15 +10,15 @@ use bevy_ecs::prelude::*; use derive_more::{Deref, DerefMut}; use crate::{ + Client, interact::{ - can_use_game_master_blocks, check_is_interaction_restricted, CurrentSequenceNumber, - HitResultComponent, SwingArmEvent, + CurrentSequenceNumber, HitResultComponent, SwingArmEvent, can_use_game_master_blocks, + check_is_interaction_restricted, }, inventory::{Inventory, InventorySet}, local_player::{LocalGameMode, PermissionLevel, PlayerAbilities}, movement::MoveEventsSet, packet_handling::game::SendPacketEvent, - Client, }; /// A plugin that allows clients to break blocks in the world. diff --git a/azalea-client/src/movement.rs b/azalea-client/src/movement.rs index 3bea9de2..b0ff70f4 100644 --- a/azalea-client/src/movement.rs +++ b/azalea-client/src/movement.rs @@ -2,18 +2,18 @@ use std::backtrace::Backtrace; use azalea_core::position::Vec3; use azalea_core::tick::GameTick; -use azalea_entity::{metadata::Sprinting, Attributes, Jumping}; +use azalea_entity::{Attributes, Jumping, metadata::Sprinting}; use azalea_entity::{InLoadedChunk, LastSentPosition, LookDirection, Physics, Position}; -use azalea_physics::{ai_step, PhysicsSet}; +use azalea_physics::{PhysicsSet, ai_step}; use azalea_protocol::packets::game::{ServerboundPlayerCommand, ServerboundPlayerInput}; use azalea_protocol::packets::{ + Packet, game::{ s_move_player_pos::ServerboundMovePlayerPos, s_move_player_pos_rot::ServerboundMovePlayerPosRot, s_move_player_rot::ServerboundMovePlayerRot, s_move_player_status_only::ServerboundMovePlayerStatusOnly, }, - Packet, }; use azalea_world::{MinecraftEntityId, MoveEntityError}; use bevy_app::{App, Plugin, Update}; diff --git a/azalea-client/src/packet_handling/configuration.rs b/azalea-client/src/packet_handling/configuration.rs index 9124f6aa..bfa6914b 100644 --- a/azalea-client/src/packet_handling/configuration.rs +++ b/azalea-client/src/packet_handling/configuration.rs @@ -14,12 +14,12 @@ use bevy_ecs::prelude::*; use bevy_ecs::system::SystemState; use tracing::{debug, error, warn}; +use crate::InstanceHolder; use crate::client::InConfigState; use crate::disconnect::DisconnectEvent; use crate::local_player::Hunger; use crate::packet_handling::game::KeepAliveEvent; use crate::raw_connection::RawConnection; -use crate::InstanceHolder; #[derive(Event, Debug, Clone)] pub struct ConfigurationEvent { diff --git a/azalea-client/src/packet_handling/game.rs b/azalea-client/src/packet_handling/game.rs index 73442804..6f2868e9 100644 --- a/azalea-client/src/packet_handling/game.rs +++ b/azalea-client/src/packet_handling/game.rs @@ -13,21 +13,22 @@ use azalea_core::{ resource_location::ResourceLocation, }; use azalea_entity::{ - indexing::{EntityIdIndex, EntityUuidIndex}, - metadata::{apply_metadata, Health}, Dead, EntityBundle, EntityKind, LastSentPosition, LoadedBy, LocalEntity, LookDirection, Physics, Position, RelativeEntityUpdate, + indexing::{EntityIdIndex, EntityUuidIndex}, + metadata::{Health, apply_metadata}, }; use azalea_protocol::{ packets::{ + Packet, game::{ + ClientboundGamePacket, ServerboundGamePacket, c_player_combat_kill::ClientboundPlayerCombatKill, s_accept_teleportation::ServerboundAcceptTeleportation, s_configuration_acknowledged::ServerboundConfigurationAcknowledged, s_keep_alive::ServerboundKeepAlive, s_move_player_pos_rot::ServerboundMovePlayerPosRot, - s_pong::ServerboundPong, ClientboundGamePacket, ServerboundGamePacket, + s_pong::ServerboundPong, }, - Packet, }, read::deserialize_packet, }; @@ -38,6 +39,7 @@ use tracing::{debug, error, trace, warn}; use uuid::Uuid; use crate::{ + ClientInformation, PlayerInfo, chat::{ChatPacket, ChatReceivedEvent}, chunks, disconnect::DisconnectEvent, @@ -49,7 +51,6 @@ use crate::{ }, movement::{KnockbackEvent, KnockbackType}, raw_connection::RawConnection, - ClientInformation, PlayerInfo, }; /// An event that's sent when we receive a packet. @@ -427,11 +428,7 @@ pub fn process_packet_events(ecs: &mut World) { **last_sent_position = **position; fn apply_change>(base: T, condition: bool, change: T) -> T { - if condition { - base + change - } else { - change - } + if condition { base + change } else { change } } let new_x = apply_change(position.x, p.relative.x, p.change.pos.x); @@ -655,9 +652,13 @@ pub fn process_packet_events(ecs: &mut World) { let entity_in_ecs = entity_query.get(ecs_entity).is_ok(); if entity_in_ecs { - error!("LoadedBy for entity {entity_id:?} ({ecs_entity:?}) isn't in the ecs, but the entity is in entity_by_id"); + error!( + "LoadedBy for entity {entity_id:?} ({ecs_entity:?}) isn't in the ecs, but the entity is in entity_by_id" + ); } else { - error!("Entity {entity_id:?} ({ecs_entity:?}) isn't in the ecs, but the entity is in entity_by_id"); + error!( + "Entity {entity_id:?} ({ecs_entity:?}) isn't in the ecs, but the entity is in entity_by_id" + ); } continue; }; @@ -719,7 +720,10 @@ pub fn process_packet_events(ecs: &mut World) { let Some(entity) = entity else { // some servers like hypixel trigger this a lot :( - debug!("Server sent an entity data packet for an entity id ({}) that we don't know about", p.id); + debug!( + "Server sent an entity data packet for an entity id ({}) that we don't know about", + p.id + ); continue; }; let entity_kind = *entity_kind_query.get(entity).unwrap(); @@ -1035,7 +1039,9 @@ pub fn process_packet_events(ecs: &mut World) { for &id in &p.entity_ids { let Some(entity) = entity_id_index.remove(id) else { - debug!("Tried to remove entity with id {id} but it wasn't in the EntityIdIndex"); + debug!( + "Tried to remove entity with id {id} but it wasn't in the EntityIdIndex" + ); continue; }; let Ok(mut loaded_by) = entity_query.get_mut(entity) else { diff --git a/azalea-client/src/packet_handling/login.rs b/azalea-client/src/packet_handling/login.rs index dec4aa06..8cf45afc 100644 --- a/azalea-client/src/packet_handling/login.rs +++ b/azalea-client/src/packet_handling/login.rs @@ -4,11 +4,11 @@ use std::{collections::HashSet, sync::Arc}; use azalea_protocol::packets::{ - login::{ - s_custom_query_answer::ServerboundCustomQueryAnswer, ClientboundLoginPacket, - ServerboundLoginPacket, - }, Packet, + login::{ + ClientboundLoginPacket, ServerboundLoginPacket, + s_custom_query_answer::ServerboundCustomQueryAnswer, + }, }; use bevy_ecs::{prelude::*, system::SystemState}; use derive_more::{Deref, DerefMut}; diff --git a/azalea-client/src/packet_handling/mod.rs b/azalea-client/src/packet_handling/mod.rs index 6bb9c319..908f368e 100644 --- a/azalea-client/src/packet_handling/mod.rs +++ b/azalea-client/src/packet_handling/mod.rs @@ -1,4 +1,4 @@ -use azalea_entity::{metadata::Health, EntityUpdateSet}; +use azalea_entity::{EntityUpdateSet, metadata::Health}; use bevy_app::{App, First, Plugin, PreUpdate, Update}; use bevy_ecs::prelude::*; diff --git a/azalea-client/src/ping.rs b/azalea-client/src/ping.rs index f5d714cd..38d5c26f 100755 --- a/azalea-client/src/ping.rs +++ b/azalea-client/src/ping.rs @@ -3,19 +3,20 @@ use std::io; use azalea_protocol::{ + ServerAddress, connect::{Connection, ConnectionError, Proxy}, packets::{ + ClientIntention, PROTOCOL_VERSION, handshake::{ - s_intention::ServerboundIntention, ClientboundHandshakePacket, - ServerboundHandshakePacket, + ClientboundHandshakePacket, ServerboundHandshakePacket, + s_intention::ServerboundIntention, }, status::{ - c_status_response::ClientboundStatusResponse, - s_status_request::ServerboundStatusRequest, ClientboundStatusPacket, + ClientboundStatusPacket, c_status_response::ClientboundStatusResponse, + s_status_request::ServerboundStatusRequest, }, - ClientIntention, PROTOCOL_VERSION, }, - resolver, ServerAddress, + resolver, }; use thiserror::Error; diff --git a/azalea-client/src/player.rs b/azalea-client/src/player.rs index 9289d260..f0641cf1 100755 --- a/azalea-client/src/player.rs +++ b/azalea-client/src/player.rs @@ -8,7 +8,7 @@ use bevy_ecs::{ }; use uuid::Uuid; -use crate::{packet_handling::game::AddPlayerEvent, GameProfileComponent}; +use crate::{GameProfileComponent, packet_handling::game::AddPlayerEvent}; /// A player in the tab list. #[derive(Debug, Clone)] diff --git a/azalea-client/src/respawn.rs b/azalea-client/src/respawn.rs index edd2a43a..41d1c470 100644 --- a/azalea-client/src/respawn.rs +++ b/azalea-client/src/respawn.rs @@ -2,7 +2,7 @@ use azalea_protocol::packets::game::s_client_command::{self, ServerboundClientCo use bevy_app::{App, Plugin, Update}; use bevy_ecs::prelude::*; -use crate::packet_handling::game::{handle_send_packet_event, SendPacketEvent}; +use crate::packet_handling::game::{SendPacketEvent, handle_send_packet_event}; /// Tell the server that we're respawning. #[derive(Event, Debug, Clone)] diff --git a/azalea-client/src/task_pool.rs b/azalea-client/src/task_pool.rs index d4963cd5..ab56bf69 100644 --- a/azalea-client/src/task_pool.rs +++ b/azalea-client/src/task_pool.rs @@ -5,8 +5,8 @@ use std::marker::PhantomData; use bevy_app::{App, Last, Plugin}; use bevy_ecs::system::{NonSend, Resource}; use bevy_tasks::{ - tick_global_task_pools_on_main_thread, AsyncComputeTaskPool, ComputeTaskPool, IoTaskPool, - TaskPoolBuilder, + AsyncComputeTaskPool, ComputeTaskPool, IoTaskPool, TaskPoolBuilder, + tick_global_task_pools_on_main_thread, }; /// Setup of default task pools: `AsyncComputeTaskPool`, `ComputeTaskPool`, diff --git a/azalea-client/src/test_simulation.rs b/azalea-client/src/test_simulation.rs index 5afd8b00..38cfbc15 100644 --- a/azalea-client/src/test_simulation.rs +++ b/azalea-client/src/test_simulation.rs @@ -25,9 +25,9 @@ use tokio::{sync::mpsc, time::sleep}; use uuid::Uuid; use crate::{ + ClientInformation, GameProfileComponent, InConfigState, InstanceHolder, LocalPlayerBundle, events::LocalPlayerEvents, raw_connection::{RawConnection, RawConnectionReader, RawConnectionWriter}, - ClientInformation, GameProfileComponent, InConfigState, InstanceHolder, LocalPlayerBundle, }; /// A way to simulate a client in a server, used for some internal tests. diff --git a/azalea-client/tests/change_dimension_to_nether_and_back.rs b/azalea-client/tests/change_dimension_to_nether_and_back.rs index 3ed623ef..16febca0 100644 --- a/azalea-client/tests/change_dimension_to_nether_and_back.rs +++ b/azalea-client/tests/change_dimension_to_nether_and_back.rs @@ -1,10 +1,10 @@ -use azalea_client::{test_simulation::*, InConfigState}; +use azalea_client::{InConfigState, test_simulation::*}; use azalea_core::{position::ChunkPos, resource_location::ResourceLocation}; -use azalea_entity::{metadata::Health, LocalEntity}; +use azalea_entity::{LocalEntity, metadata::Health}; use azalea_protocol::packets::{ + ConnectionProtocol, config::{ClientboundFinishConfiguration, ClientboundRegistryData}, game::ClientboundSetHealth, - ConnectionProtocol, }; use azalea_registry::DimensionType; use azalea_world::InstanceName; diff --git a/azalea-client/tests/set_health_before_login.rs b/azalea-client/tests/set_health_before_login.rs index d6b6c426..c078cae4 100644 --- a/azalea-client/tests/set_health_before_login.rs +++ b/azalea-client/tests/set_health_before_login.rs @@ -1,10 +1,10 @@ -use azalea_client::{test_simulation::*, InConfigState}; +use azalea_client::{InConfigState, test_simulation::*}; use azalea_core::resource_location::ResourceLocation; -use azalea_entity::{metadata::Health, LocalEntity}; +use azalea_entity::{LocalEntity, metadata::Health}; use azalea_protocol::packets::{ + ConnectionProtocol, config::{ClientboundFinishConfiguration, ClientboundRegistryData}, game::ClientboundSetHealth, - ConnectionProtocol, }; use azalea_registry::DimensionType; use bevy_log::tracing_subscriber; diff --git a/azalea-core/src/math.rs b/azalea-core/src/math.rs index a763fc49..c09bddda 100644 --- a/azalea-core/src/math.rs +++ b/azalea-core/src/math.rs @@ -91,18 +91,10 @@ pub fn to_degrees(radians: f64) -> f64 { /// /// This function exists because f64::signum doesn't check for 0. pub fn sign(num: f64) -> f64 { - if num == 0. { - 0. - } else { - num.signum() - } + if num == 0. { 0. } else { num.signum() } } pub fn sign_as_int(num: f64) -> i32 { - if num == 0. { - 0 - } else { - num.signum() as i32 - } + if num == 0. { 0 } else { num.signum() as i32 } } #[cfg(test)] diff --git a/azalea-core/src/registry_holder.rs b/azalea-core/src/registry_holder.rs index b2f1f5b9..f5657dc6 100644 --- a/azalea-core/src/registry_holder.rs +++ b/azalea-core/src/registry_holder.rs @@ -9,8 +9,8 @@ use std::{collections::HashMap, io::Cursor}; use indexmap::IndexMap; use simdnbt::{ - owned::{NbtCompound, NbtTag}, Deserialize, FromNbtTag, Serialize, ToNbtTag, + owned::{NbtCompound, NbtTag}, }; use tracing::error; diff --git a/azalea-core/src/resource_location.rs b/azalea-core/src/resource_location.rs index c95e3109..0b21a43b 100755 --- a/azalea-core/src/resource_location.rs +++ b/azalea-core/src/resource_location.rs @@ -8,8 +8,8 @@ use std::{ use azalea_buf::{AzaleaRead, AzaleaWrite, BufReadError}; #[cfg(feature = "serde")] -use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; -use simdnbt::{owned::NbtTag, FromNbtTag, ToNbtTag}; +use serde::{Deserialize, Deserializer, Serialize, Serializer, de}; +use simdnbt::{FromNbtTag, ToNbtTag, owned::NbtTag}; #[derive(Hash, Clone, PartialEq, Eq)] pub struct ResourceLocation { diff --git a/azalea-crypto/benches/my_benchmark.rs b/azalea-crypto/benches/my_benchmark.rs index 1781f471..4a115b37 100755 --- a/azalea-crypto/benches/my_benchmark.rs +++ b/azalea-crypto/benches/my_benchmark.rs @@ -1,5 +1,5 @@ use azalea_crypto::{create_cipher, decrypt_packet, encrypt_packet}; -use criterion::{criterion_group, criterion_main, Criterion}; +use criterion::{Criterion, criterion_group, criterion_main}; fn bench(c: &mut Criterion) { let (mut enc, dec) = create_cipher(b"0123456789abcdef"); diff --git a/azalea-crypto/src/lib.rs b/azalea-crypto/src/lib.rs index 90e248a2..b087c426 100755 --- a/azalea-crypto/src/lib.rs +++ b/azalea-crypto/src/lib.rs @@ -4,10 +4,10 @@ mod signing; use aes::cipher::inout::InOutBuf; use aes::{ - cipher::{BlockDecryptMut, BlockEncryptMut, KeyIvInit}, Aes128, + cipher::{BlockDecryptMut, BlockEncryptMut, KeyIvInit}, }; -use rand::{rngs::OsRng, RngCore}; +use rand::{RngCore, rngs::OsRng}; use sha1::{Digest, Sha1}; pub use signing::*; diff --git a/azalea-crypto/src/signing.rs b/azalea-crypto/src/signing.rs index ba9cc305..05fa1810 100755 --- a/azalea-crypto/src/signing.rs +++ b/azalea-crypto/src/signing.rs @@ -2,8 +2,8 @@ use std::time::{SystemTime, UNIX_EPOCH}; use azalea_buf::{AzBuf, AzaleaWrite}; use rsa::{ - signature::{RandomizedSigner, SignatureEncoding}, RsaPrivateKey, + signature::{RandomizedSigner, SignatureEncoding}, }; use sha2::Sha256; use uuid::Uuid; diff --git a/azalea-entity/src/attributes.rs b/azalea-entity/src/attributes.rs index 9af3bcaa..d3881147 100644 --- a/azalea-entity/src/attributes.rs +++ b/azalea-entity/src/attributes.rs @@ -1,6 +1,6 @@ //! See . -use std::collections::{hash_map, HashMap}; +use std::collections::{HashMap, hash_map}; use azalea_buf::AzBuf; use azalea_core::resource_location::ResourceLocation; diff --git a/azalea-entity/src/lib.rs b/azalea-entity/src/lib.rs index 472ba29a..1024ffe6 100644 --- a/azalea-entity/src/lib.rs +++ b/azalea-entity/src/lib.rs @@ -17,7 +17,7 @@ use std::{ }; pub use attributes::Attributes; -use azalea_block::{fluid_state::FluidKind, BlockState}; +use azalea_block::{BlockState, fluid_state::FluidKind}; use azalea_buf::AzBuf; use azalea_core::{ aabb::AABB, diff --git a/azalea-entity/src/mining.rs b/azalea-entity/src/mining.rs index b17cddf0..370478ee 100644 --- a/azalea-entity/src/mining.rs +++ b/azalea-entity/src/mining.rs @@ -2,7 +2,7 @@ use azalea_block::{Block, BlockBehavior}; use azalea_core::tier::get_item_tier; use azalea_registry as registry; -use crate::{effects, FluidOnEyes, Physics}; +use crate::{FluidOnEyes, Physics, effects}; /// How much progress is made towards mining the block per tick, as a /// percentage. If this is 1 then the block gets broken instantly. diff --git a/azalea-entity/src/plugin/indexing.rs b/azalea-entity/src/plugin/indexing.rs index 78d5fb7e..21dd273a 100644 --- a/azalea-entity/src/plugin/indexing.rs +++ b/azalea-entity/src/plugin/indexing.rs @@ -181,19 +181,24 @@ pub fn remove_despawned_entities_from_indexes( // remove the entity from the chunk index let chunk = ChunkPos::from(*position); - if let Some(entities_in_chunk) = instance.entities_by_chunk.get_mut(&chunk) { - if entities_in_chunk.remove(&entity) { - // remove the chunk if there's no entities in it anymore - if entities_in_chunk.is_empty() { - instance.entities_by_chunk.remove(&chunk); + match instance.entities_by_chunk.get_mut(&chunk) { + Some(entities_in_chunk) => { + if entities_in_chunk.remove(&entity) { + // remove the chunk if there's no entities in it anymore + if entities_in_chunk.is_empty() { + instance.entities_by_chunk.remove(&chunk); + } + } else { + warn!( + "Tried to remove entity {entity:?} from chunk {chunk:?} but the entity was not there." + ); } - } else { - warn!( - "Tried to remove entity {entity:?} from chunk {chunk:?} but the entity was not there." + } + _ => { + debug!( + "Tried to remove entity {entity:?} from chunk {chunk:?} but the chunk was not found." ); } - } else { - debug!("Tried to remove entity {entity:?} from chunk {chunk:?} but the chunk was not found."); } // remove it from the uuid index if entity_uuid_index.entity_by_uuid.remove(uuid).is_none() { diff --git a/azalea-entity/src/plugin/mod.rs b/azalea-entity/src/plugin/mod.rs index 560d0ec6..bddb4b66 100644 --- a/azalea-entity/src/plugin/mod.rs +++ b/azalea-entity/src/plugin/mod.rs @@ -3,7 +3,7 @@ mod relative_updates; use std::collections::HashSet; -use azalea_block::{fluid_state::FluidKind, BlockState}; +use azalea_block::{BlockState, fluid_state::FluidKind}; use azalea_core::{ position::{BlockPos, ChunkPos, Vec3}, tick::GameTick, @@ -17,8 +17,8 @@ pub use relative_updates::RelativeEntityUpdate; use tracing::debug; use crate::{ - metadata::Health, Dead, EyeHeight, FluidOnEyes, LocalEntity, LookDirection, OnClimbable, - Physics, Position, + Dead, EyeHeight, FluidOnEyes, LocalEntity, LookDirection, OnClimbable, Physics, Position, + metadata::Health, }; /// A Bevy [`SystemSet`] for various types of entity updates. diff --git a/azalea-inventory/azalea-inventory-macros/src/lib.rs b/azalea-inventory/azalea-inventory-macros/src/lib.rs index e39f1bc6..3905a63e 100644 --- a/azalea-inventory/azalea-inventory-macros/src/lib.rs +++ b/azalea-inventory/azalea-inventory-macros/src/lib.rs @@ -8,7 +8,7 @@ use parse_macro::{DeclareMenus, Field}; use proc_macro::TokenStream; use proc_macro2::Span; use quote::quote; -use syn::{parse_macro_input, Ident}; +use syn::{Ident, parse_macro_input}; #[proc_macro] pub fn declare_menus(input: TokenStream) -> TokenStream { diff --git a/azalea-inventory/azalea-inventory-macros/src/parse_macro.rs b/azalea-inventory/azalea-inventory-macros/src/parse_macro.rs index de1ec972..c415959d 100644 --- a/azalea-inventory/azalea-inventory-macros/src/parse_macro.rs +++ b/azalea-inventory/azalea-inventory-macros/src/parse_macro.rs @@ -1,7 +1,6 @@ use syn::{ - braced, + Ident, LitInt, Token, braced, parse::{Parse, ParseStream, Result}, - Ident, LitInt, Token, }; /// An identifier, colon, and number diff --git a/azalea-inventory/src/components.rs b/azalea-inventory/src/components.rs index 6dd60819..b299664f 100644 --- a/azalea-inventory/src/components.rs +++ b/azalea-inventory/src/components.rs @@ -42,10 +42,9 @@ where } fn eq(&self, other: Box) -> bool { let other_any: Box = other; - if let Some(other) = other_any.downcast_ref::() { - self == other - } else { - false + match other_any.downcast_ref::() { + Some(other) => self == other, + _ => false, } } } diff --git a/azalea-inventory/src/operations.rs b/azalea-inventory/src/operations.rs index 0df7c794..90ad2403 100644 --- a/azalea-inventory/src/operations.rs +++ b/azalea-inventory/src/operations.rs @@ -3,14 +3,14 @@ use std::ops::RangeInclusive; use azalea_buf::AzBuf; use crate::{ - item::MaxStackSizeExt, AnvilMenuLocation, BeaconMenuLocation, BlastFurnaceMenuLocation, - BrewingStandMenuLocation, CartographyTableMenuLocation, Crafter3x3MenuLocation, - CraftingMenuLocation, EnchantmentMenuLocation, FurnaceMenuLocation, Generic3x3MenuLocation, - Generic9x1MenuLocation, Generic9x2MenuLocation, Generic9x3MenuLocation, Generic9x4MenuLocation, - Generic9x5MenuLocation, Generic9x6MenuLocation, GrindstoneMenuLocation, HopperMenuLocation, - ItemStack, ItemStackData, LecternMenuLocation, LoomMenuLocation, Menu, MenuLocation, - MerchantMenuLocation, Player, PlayerMenuLocation, ShulkerBoxMenuLocation, SmithingMenuLocation, - SmokerMenuLocation, StonecutterMenuLocation, + AnvilMenuLocation, BeaconMenuLocation, BlastFurnaceMenuLocation, BrewingStandMenuLocation, + CartographyTableMenuLocation, Crafter3x3MenuLocation, CraftingMenuLocation, + EnchantmentMenuLocation, FurnaceMenuLocation, Generic3x3MenuLocation, Generic9x1MenuLocation, + Generic9x2MenuLocation, Generic9x3MenuLocation, Generic9x4MenuLocation, Generic9x5MenuLocation, + Generic9x6MenuLocation, GrindstoneMenuLocation, HopperMenuLocation, ItemStack, ItemStackData, + LecternMenuLocation, LoomMenuLocation, Menu, MenuLocation, MerchantMenuLocation, Player, + PlayerMenuLocation, ShulkerBoxMenuLocation, SmithingMenuLocation, SmokerMenuLocation, + StonecutterMenuLocation, item::MaxStackSizeExt, }; #[derive(Debug, Clone)] diff --git a/azalea-inventory/src/slot.rs b/azalea-inventory/src/slot.rs index 3ca38f56..2b886955 100644 --- a/azalea-inventory/src/slot.rs +++ b/azalea-inventory/src/slot.rs @@ -310,21 +310,24 @@ impl PartialEq for DataComponentPatch { return false; } for (kind, component) in &self.components { - if let Some(other_component) = other.components.get(kind) { - // we can't use PartialEq, but we can use our own eq method - if let Some(component) = component { - if let Some(other_component) = other_component { - if !component.eq((*other_component).clone()) { + match other.components.get(kind) { + Some(other_component) => { + // we can't use PartialEq, but we can use our own eq method + if let Some(component) = component { + if let Some(other_component) = other_component { + if !component.eq((*other_component).clone()) { + return false; + } + } else { return false; } - } else { + } else if other_component.is_some() { return false; } - } else if other_component.is_some() { + } + _ => { return false; } - } else { - return false; } } true diff --git a/azalea-physics/src/clip.rs b/azalea-physics/src/clip.rs index b6e6a9f9..ea5940a5 100644 --- a/azalea-physics/src/clip.rs +++ b/azalea-physics/src/clip.rs @@ -1,21 +1,21 @@ use std::collections::HashSet; use azalea_block::{ - fluid_state::{FluidKind, FluidState}, BlockState, + fluid_state::{FluidKind, FluidState}, }; use azalea_core::{ aabb::AABB, block_hit_result::BlockHitResult, direction::{Axis, Direction}, - math::{self, lerp, EPSILON}, + math::{self, EPSILON, lerp}, position::{BlockPos, Vec3}, }; use azalea_inventory::ItemStack; use azalea_world::ChunkStorage; use bevy_ecs::entity::Entity; -use crate::collision::{BlockWithShape, VoxelShape, EMPTY_SHAPE}; +use crate::collision::{BlockWithShape, EMPTY_SHAPE, VoxelShape}; #[derive(Debug, Clone)] pub struct ClipContext { diff --git a/azalea-physics/src/collision/mergers.rs b/azalea-physics/src/collision/mergers.rs index 85fd2826..dbe9c1e8 100755 --- a/azalea-physics/src/collision/mergers.rs +++ b/azalea-physics/src/collision/mergers.rs @@ -1,6 +1,6 @@ use std::cmp::{self, Ordering}; -use azalea_core::math::{gcd, lcm, EPSILON}; +use azalea_core::math::{EPSILON, gcd, lcm}; use super::CubePointRange; diff --git a/azalea-physics/src/collision/mod.rs b/azalea-physics/src/collision/mod.rs index 530aa47f..540cf7d4 100644 --- a/azalea-physics/src/collision/mod.rs +++ b/azalea-physics/src/collision/mod.rs @@ -6,7 +6,7 @@ mod world_collisions; use std::{ops::Add, sync::LazyLock}; -use azalea_block::{fluid_state::FluidState, BlockState}; +use azalea_block::{BlockState, fluid_state::FluidState}; use azalea_core::{ aabb::AABB, direction::Axis, diff --git a/azalea-physics/src/collision/shape.rs b/azalea-physics/src/collision/shape.rs index b0dceabb..726e62ad 100755 --- a/azalea-physics/src/collision/shape.rs +++ b/azalea-physics/src/collision/shape.rs @@ -3,12 +3,12 @@ use std::{cmp, num::NonZeroU32, sync::LazyLock}; use azalea_core::{ block_hit_result::BlockHitResult, direction::{Axis, AxisCycle, Direction}, - math::{binary_search, EPSILON}, + math::{EPSILON, binary_search}, position::{BlockPos, Vec3}, }; use super::mergers::IndexMerger; -use crate::collision::{BitSetDiscreteVoxelShape, DiscreteVoxelShape, AABB}; +use crate::collision::{AABB, BitSetDiscreteVoxelShape, DiscreteVoxelShape}; pub struct Shapes; diff --git a/azalea-physics/src/collision/world_collisions.rs b/azalea-physics/src/collision/world_collisions.rs index f0b41986..3aede743 100644 --- a/azalea-physics/src/collision/world_collisions.rs +++ b/azalea-physics/src/collision/world_collisions.rs @@ -9,8 +9,8 @@ use azalea_core::{ use azalea_world::{Chunk, Instance}; use parking_lot::RwLock; -use super::{Shapes, BLOCK_SHAPE}; -use crate::collision::{BlockWithShape, VoxelShape, AABB}; +use super::{BLOCK_SHAPE, Shapes}; +use crate::collision::{AABB, BlockWithShape, VoxelShape}; pub fn get_block_collisions(world: &Instance, aabb: AABB) -> Vec { let mut state = BlockCollisionsState::new(world, aabb); @@ -27,12 +27,11 @@ pub fn get_block_collisions(world: &Instance, aabb: AABB) -> Vec { let item_chunk_pos = ChunkPos::from(item.pos); let block_state: BlockState = if item_chunk_pos == initial_chunk_pos { - if let Some(initial_chunk) = &initial_chunk { - initial_chunk + match &initial_chunk { + Some(initial_chunk) => initial_chunk .get(&ChunkBlockPos::from(item.pos), state.world.chunks.min_y) - .unwrap_or(BlockState::AIR) - } else { - BlockState::AIR + .unwrap_or(BlockState::AIR), + _ => BlockState::AIR, } } else { state.get_block_state(item.pos) diff --git a/azalea-physics/src/fluids.rs b/azalea-physics/src/fluids.rs index 78a9d467..7a0c86a9 100644 --- a/azalea-physics/src/fluids.rs +++ b/azalea-physics/src/fluids.rs @@ -1,6 +1,6 @@ use azalea_block::{ - fluid_state::{FluidKind, FluidState}, BlockState, + fluid_state::{FluidKind, FluidState}, }; use azalea_core::{ direction::Direction, diff --git a/azalea-physics/src/lib.rs b/azalea-physics/src/lib.rs index c626dcdf..0541042c 100644 --- a/azalea-physics/src/lib.rs +++ b/azalea-physics/src/lib.rs @@ -8,15 +8,15 @@ pub mod travel; use std::collections::HashSet; -use azalea_block::{fluid_state::FluidState, properties, Block, BlockState}; +use azalea_block::{Block, BlockState, fluid_state::FluidState, properties}; use azalea_core::{ math, position::{BlockPos, Vec3}, tick::GameTick, }; use azalea_entity::{ - metadata::Sprinting, move_relative, Attributes, InLoadedChunk, Jumping, LocalEntity, - LookDirection, OnClimbable, Physics, Pose, Position, + Attributes, InLoadedChunk, Jumping, LocalEntity, LookDirection, OnClimbable, Physics, Pose, + Position, metadata::Sprinting, move_relative, }; use azalea_world::{Instance, InstanceContainer, InstanceName}; use bevy_app::{App, Plugin}; @@ -27,7 +27,7 @@ use bevy_ecs::{ world::Mut, }; use clip::box_traverse_blocks; -use collision::{move_colliding, BlockWithShape, MoverType, VoxelShape, BLOCK_SHAPE}; +use collision::{BLOCK_SHAPE, BlockWithShape, MoverType, VoxelShape, move_colliding}; /// A Bevy [`SystemSet`] for running physics that makes entities do things. #[derive(SystemSet, Debug, Hash, PartialEq, Eq, Clone)] @@ -476,11 +476,7 @@ fn get_friction_influenced_speed( speed * (0.216f32 / (friction * friction * friction)) } else { // entity.flying_speed - if is_sprinting { - 0.025999999f32 - } else { - 0.02 - } + if is_sprinting { 0.025999999f32 } else { 0.02 } } } diff --git a/azalea-physics/src/travel.rs b/azalea-physics/src/travel.rs index 08b59867..e6145c18 100644 --- a/azalea-physics/src/travel.rs +++ b/azalea-physics/src/travel.rs @@ -1,16 +1,16 @@ use azalea_block::{Block, BlockState}; use azalea_core::{aabb::AABB, position::Vec3}; use azalea_entity::{ - metadata::Sprinting, move_relative, Attributes, InLoadedChunk, Jumping, LocalEntity, - LookDirection, OnClimbable, Physics, Pose, Position, + Attributes, InLoadedChunk, Jumping, LocalEntity, LookDirection, OnClimbable, Physics, Pose, + Position, metadata::Sprinting, move_relative, }; use azalea_world::{Instance, InstanceContainer, InstanceName}; use bevy_ecs::prelude::*; use crate::{ - collision::{move_colliding, MoverType}, - get_block_pos_below_that_affects_movement, handle_relative_friction_and_calculate_movement, HandleRelativeFrictionAndCalculateMovementOpts, + collision::{MoverType, move_colliding}, + get_block_pos_below_that_affects_movement, handle_relative_friction_and_calculate_movement, }; /// Move the entity with the given acceleration while handling friction, diff --git a/azalea-protocol/azalea-protocol-macros/src/lib.rs b/azalea-protocol/azalea-protocol-macros/src/lib.rs index 5cbf2925..a33d21e0 100755 --- a/azalea-protocol/azalea-protocol-macros/src/lib.rs +++ b/azalea-protocol/azalea-protocol-macros/src/lib.rs @@ -1,9 +1,9 @@ use proc_macro::TokenStream; use quote::quote; use syn::{ - bracketed, + DeriveInput, Ident, Token, bracketed, parse::{Parse, ParseStream, Result}, - parse_macro_input, DeriveInput, Ident, Token, + parse_macro_input, }; fn as_packet_derive(input: TokenStream, state: proc_macro2::TokenStream) -> TokenStream { diff --git a/azalea-protocol/examples/handshake_proxy.rs b/azalea-protocol/examples/handshake_proxy.rs index f50300d0..0161258a 100644 --- a/azalea-protocol/examples/handshake_proxy.rs +++ b/azalea-protocol/examples/handshake_proxy.rs @@ -6,17 +6,17 @@ use std::{error::Error, sync::LazyLock}; use azalea_protocol::{ connect::Connection, packets::{ + ClientIntention, PROTOCOL_VERSION, VERSION_NAME, handshake::{ - s_intention::ServerboundIntention, ClientboundHandshakePacket, - ServerboundHandshakePacket, + ClientboundHandshakePacket, ServerboundHandshakePacket, + s_intention::ServerboundIntention, }, - login::{s_hello::ServerboundHello, ServerboundLoginPacket}, + login::{ServerboundLoginPacket, s_hello::ServerboundHello}, status::{ + ServerboundStatusPacket, c_pong_response::ClientboundPongResponse, c_status_response::{ClientboundStatusResponse, Players, Version}, - ServerboundStatusPacket, }, - ClientIntention, PROTOCOL_VERSION, VERSION_NAME, }, read::ReadPacketError, }; diff --git a/azalea-protocol/src/connect.rs b/azalea-protocol/src/connect.rs index 0f8bc912..6ac14e0b 100755 --- a/azalea-protocol/src/connect.rs +++ b/azalea-protocol/src/connect.rs @@ -10,19 +10,19 @@ use azalea_auth::sessionserver::{ClientSessionServerError, ServerSessionServerEr use azalea_crypto::{Aes128CfbDec, Aes128CfbEnc}; use thiserror::Error; use tokio::io::{AsyncWriteExt, BufStream}; -use tokio::net::tcp::{OwnedReadHalf, OwnedWriteHalf, ReuniteError}; use tokio::net::TcpStream; +use tokio::net::tcp::{OwnedReadHalf, OwnedWriteHalf, ReuniteError}; use tracing::{error, info}; use uuid::Uuid; +use crate::packets::ProtocolPacket; use crate::packets::config::{ClientboundConfigPacket, ServerboundConfigPacket}; use crate::packets::game::{ClientboundGamePacket, ServerboundGamePacket}; use crate::packets::handshake::{ClientboundHandshakePacket, ServerboundHandshakePacket}; use crate::packets::login::c_hello::ClientboundHello; use crate::packets::login::{ClientboundLoginPacket, ServerboundLoginPacket}; use crate::packets::status::{ClientboundStatusPacket, ServerboundStatusPacket}; -use crate::packets::ProtocolPacket; -use crate::read::{deserialize_packet, read_raw_packet, try_read_raw_packet, ReadPacketError}; +use crate::read::{ReadPacketError, deserialize_packet, read_raw_packet, try_read_raw_packet}; use crate::write::{serialize_packet, write_raw_packet}; pub struct RawReadConnection { diff --git a/azalea-protocol/src/lib.rs b/azalea-protocol/src/lib.rs index 12243de6..f9d29785 100644 --- a/azalea-protocol/src/lib.rs +++ b/azalea-protocol/src/lib.rs @@ -115,9 +115,9 @@ mod tests { use crate::{ packets::{ - game::s_chat::{LastSeenMessagesUpdate, ServerboundChat}, - login::{s_hello::ServerboundHello, ServerboundLoginPacket}, Packet, + game::s_chat::{LastSeenMessagesUpdate, ServerboundChat}, + login::{ServerboundLoginPacket, s_hello::ServerboundHello}, }, read::{compression_decoder, read_packet}, write::{compression_encoder, serialize_packet, write_packet}, @@ -136,7 +136,9 @@ mod tests { assert_eq!( stream, - [22, 0, 4, 116, 101, 115, 116, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + [ + 22, 0, 4, 116, 101, 115, 116, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + ] ); let mut stream = Cursor::new(stream); diff --git a/azalea-protocol/src/resolver.rs b/azalea-protocol/src/resolver.rs index a21d5d9b..63b66be3 100755 --- a/azalea-protocol/src/resolver.rs +++ b/azalea-protocol/src/resolver.rs @@ -4,8 +4,8 @@ use std::net::{IpAddr, SocketAddr}; use async_recursion::async_recursion; use hickory_resolver::{ - config::{ResolverConfig, ResolverOpts}, Name, TokioAsyncResolver, + config::{ResolverConfig, ResolverOpts}, }; use thiserror::Error; diff --git a/azalea-protocol/src/write.rs b/azalea-protocol/src/write.rs index f1ffd82e..adefc340 100755 --- a/azalea-protocol/src/write.rs +++ b/azalea-protocol/src/write.rs @@ -7,7 +7,7 @@ use std::{ use azalea_buf::AzaleaWriteVar; use azalea_crypto::Aes128CfbEnc; -use flate2::{bufread::ZlibEncoder, Compression}; +use flate2::{Compression, bufread::ZlibEncoder}; use thiserror::Error; use tokio::io::{AsyncWrite, AsyncWriteExt}; use tracing::trace; diff --git a/azalea-registry/azalea-registry-macros/src/lib.rs b/azalea-registry/azalea-registry-macros/src/lib.rs index 2b148fd2..ee0f2490 100755 --- a/azalea-registry/azalea-registry-macros/src/lib.rs +++ b/azalea-registry/azalea-registry-macros/src/lib.rs @@ -1,11 +1,10 @@ use proc_macro::TokenStream; use quote::quote; use syn::{ - braced, + Attribute, Ident, LitStr, Token, braced, parse::{Parse, ParseStream, Result}, parse_macro_input, punctuated::Punctuated, - Attribute, Ident, LitStr, Token, }; struct RegistryItem { diff --git a/azalea-world/benches/chunks.rs b/azalea-world/benches/chunks.rs index 2fb65821..0e7f4554 100644 --- a/azalea-world/benches/chunks.rs +++ b/azalea-world/benches/chunks.rs @@ -2,7 +2,7 @@ use std::hint::black_box; use azalea_core::position::ChunkBlockPos; use azalea_world::{BitStorage, Chunk}; -use criterion::{criterion_group, criterion_main, Criterion}; +use criterion::{Criterion, criterion_group, criterion_main}; fn bench_chunks(c: &mut Criterion) { c.bench_function("Chunk::set", |b| { diff --git a/azalea-world/src/chunk_storage.rs b/azalea-world/src/chunk_storage.rs index 8362385a..9852dd1a 100755 --- a/azalea-world/src/chunk_storage.rs +++ b/azalea-world/src/chunk_storage.rs @@ -556,21 +556,31 @@ mod tests { Some(Chunk::default()), &mut chunk_storage, ); - assert!(chunk_storage - .get_block_state(&BlockPos { x: 0, y: 319, z: 0 }) - .is_some()); - assert!(chunk_storage - .get_block_state(&BlockPos { x: 0, y: 320, z: 0 }) - .is_none()); - assert!(chunk_storage - .get_block_state(&BlockPos { x: 0, y: 338, z: 0 }) - .is_none()); - assert!(chunk_storage - .get_block_state(&BlockPos { x: 0, y: -64, z: 0 }) - .is_some()); - assert!(chunk_storage - .get_block_state(&BlockPos { x: 0, y: -65, z: 0 }) - .is_none()); + assert!( + chunk_storage + .get_block_state(&BlockPos { x: 0, y: 319, z: 0 }) + .is_some() + ); + assert!( + chunk_storage + .get_block_state(&BlockPos { x: 0, y: 320, z: 0 }) + .is_none() + ); + assert!( + chunk_storage + .get_block_state(&BlockPos { x: 0, y: 338, z: 0 }) + .is_none() + ); + assert!( + chunk_storage + .get_block_state(&BlockPos { x: 0, y: -64, z: 0 }) + .is_some() + ); + assert!( + chunk_storage + .get_block_state(&BlockPos { x: 0, y: -65, z: 0 }) + .is_none() + ); } #[test] diff --git a/azalea-world/src/container.rs b/azalea-world/src/container.rs index f7f05a89..8648d19e 100644 --- a/azalea-world/src/container.rs +++ b/azalea-world/src/container.rs @@ -53,31 +53,34 @@ impl InstanceContainer { min_y: i32, default_registries: &RegistryHolder, ) -> Arc> { - if let Some(existing_lock) = self.instances.get(&name).and_then(|world| world.upgrade()) { - let existing = existing_lock.read(); - if existing.chunks.height != height { - error!( - "Shared dimension height mismatch: {} != {height}", - existing.chunks.height - ); + match self.instances.get(&name).and_then(|world| world.upgrade()) { + Some(existing_lock) => { + let existing = existing_lock.read(); + if existing.chunks.height != height { + error!( + "Shared dimension height mismatch: {} != {height}", + existing.chunks.height + ); + } + if existing.chunks.min_y != min_y { + error!( + "Shared world min_y mismatch: {} != {min_y}", + existing.chunks.min_y + ); + } + existing_lock.clone() } - if existing.chunks.min_y != min_y { - error!( - "Shared world min_y mismatch: {} != {min_y}", - existing.chunks.min_y - ); + _ => { + let world = Arc::new(RwLock::new(Instance { + chunks: ChunkStorage::new(height, min_y), + entities_by_chunk: HashMap::new(), + entity_by_id: IntMap::default(), + registries: default_registries.clone(), + })); + debug!("Added new instance {name}"); + self.instances.insert(name, Arc::downgrade(&world)); + world } - existing_lock.clone() - } else { - let world = Arc::new(RwLock::new(Instance { - chunks: ChunkStorage::new(height, min_y), - entities_by_chunk: HashMap::new(), - entity_by_id: IntMap::default(), - registries: default_registries.clone(), - })); - debug!("Added new instance {name}"); - self.instances.insert(name, Arc::downgrade(&world)); - world } } } diff --git a/azalea-world/src/find_blocks.rs b/azalea-world/src/find_blocks.rs index 6228687f..068a5029 100644 --- a/azalea-world/src/find_blocks.rs +++ b/azalea-world/src/find_blocks.rs @@ -1,7 +1,7 @@ -use azalea_block::{block_state::BlockState, BlockStates}; +use azalea_block::{BlockStates, block_state::BlockState}; use azalea_core::position::{BlockPos, ChunkPos}; -use crate::{iterators::ChunkIterator, palette::Palette, ChunkStorage, Instance}; +use crate::{ChunkStorage, Instance, iterators::ChunkIterator, palette::Palette}; fn palette_maybe_has_block(palette: &Palette, block_states: &BlockStates) -> bool { match &palette { diff --git a/azalea-world/src/heightmap.rs b/azalea-world/src/heightmap.rs index c38f3edc..35142cf2 100644 --- a/azalea-world/src/heightmap.rs +++ b/azalea-world/src/heightmap.rs @@ -4,7 +4,7 @@ use azalea_block::BlockState; use azalea_core::{math, position::ChunkBlockPos}; use azalea_registry::tags::blocks::LEAVES; -use crate::{chunk_storage::get_block_state_from_sections, BitStorage, Section}; +use crate::{BitStorage, Section, chunk_storage::get_block_state_from_sections}; // (wg stands for worldgen) diff --git a/azalea-world/src/world.rs b/azalea-world/src/world.rs index ae257696..3428ab5e 100644 --- a/azalea-world/src/world.rs +++ b/azalea-world/src/world.rs @@ -6,8 +6,8 @@ use std::{ fmt::Debug, }; -use azalea_block::fluid_state::FluidState; use azalea_block::BlockState; +use azalea_block::fluid_state::FluidState; use azalea_buf::{AzaleaRead, AzaleaReadVar, AzaleaWrite, AzaleaWriteVar, BufReadError}; use azalea_core::position::{BlockPos, ChunkPos}; use azalea_core::registry_holder::RegistryHolder; diff --git a/azalea/benches/checks.rs b/azalea/benches/checks.rs index b246f1f6..ee737359 100644 --- a/azalea/benches/checks.rs +++ b/azalea/benches/checks.rs @@ -2,7 +2,7 @@ use std::hint::black_box; use azalea::pathfinder::mining::MiningCache; pub use azalea_registry as registry; -use criterion::{criterion_group, criterion_main, Criterion}; +use criterion::{Criterion, criterion_group, criterion_main}; fn benchmark(c: &mut Criterion) { let mining_cache = MiningCache::new(None); diff --git a/azalea/benches/pathfinder.rs b/azalea/benches/pathfinder.rs index bc6a2fea..79c8efc9 100644 --- a/azalea/benches/pathfinder.rs +++ b/azalea/benches/pathfinder.rs @@ -1,21 +1,21 @@ use std::{hint::black_box, sync::Arc, time::Duration}; use azalea::{ + BlockPos, pathfinder::{ - astar::{self, a_star, PathfinderTimeout}, + astar::{self, PathfinderTimeout, a_star}, goals::{BlockPosGoal, Goal}, mining::MiningCache, rel_block_pos::RelBlockPos, world::CachedWorld, }, - BlockPos, }; use azalea_core::position::{ChunkBlockPos, ChunkPos}; use azalea_inventory::Menu; use azalea_world::{Chunk, ChunkStorage, PartialChunkStorage}; -use criterion::{criterion_group, criterion_main, Bencher, Criterion}; +use criterion::{Bencher, Criterion, criterion_group, criterion_main}; use parking_lot::RwLock; -use rand::{rngs::StdRng, Rng, SeedableRng}; +use rand::{Rng, SeedableRng, rngs::StdRng}; #[allow(dead_code)] fn generate_bedrock_world( diff --git a/azalea/benches/physics.rs b/azalea/benches/physics.rs index 146b3018..5eb164d7 100644 --- a/azalea/benches/physics.rs +++ b/azalea/benches/physics.rs @@ -1,10 +1,10 @@ use azalea::{ - pathfinder::simulation::{SimulatedPlayerBundle, SimulationSet}, Vec3, + pathfinder::simulation::{SimulatedPlayerBundle, SimulationSet}, }; use azalea_core::position::{ChunkBlockPos, ChunkPos}; use azalea_world::{Chunk, ChunkStorage, PartialChunkStorage}; -use criterion::{criterion_group, criterion_main, Bencher, Criterion}; +use criterion::{Bencher, Criterion, criterion_group, criterion_main}; #[allow(dead_code)] fn generate_world(partial_chunks: &mut PartialChunkStorage, size: u32) -> ChunkStorage { diff --git a/azalea/build.rs b/azalea/build.rs index 18300151..cd0a16b2 100644 --- a/azalea/build.rs +++ b/azalea/build.rs @@ -7,7 +7,9 @@ fn main() { if toolchain.contains("nightly") { return; } else { - panic!("Azalea currently requires nightly Rust. You can run `rustup override set nightly` to set the toolchain for this directory."); + panic!( + "Azalea currently requires nightly Rust. You can run `rustup override set nightly` to set the toolchain for this directory." + ); } } @@ -22,7 +24,9 @@ fn main() { if rustc_command.status.success() { let rustc_output = String::from_utf8(rustc_command.stdout).unwrap(); if !rustc_output.contains("nightly") { - panic!("Azalea currently requires nightly Rust. Please check the documentation for your installation method and ensure you are using the nightly toolchain."); + panic!( + "Azalea currently requires nightly Rust. Please check the documentation for your installation method and ensure you are using the nightly toolchain." + ); } } else { let rustc_output = String::from_utf8(rustc_command.stderr).unwrap(); diff --git a/azalea/examples/nearest_entity.rs b/azalea/examples/nearest_entity.rs index d50e6c46..911f9f58 100644 --- a/azalea/examples/nearest_entity.rs +++ b/azalea/examples/nearest_entity.rs @@ -1,5 +1,5 @@ -use azalea::nearest_entity::EntityFinder; use azalea::ClientBuilder; +use azalea::nearest_entity::EntityFinder; use azalea::{Bot, LookAtEvent}; use azalea_client::Account; use azalea_core::tick::GameTick; diff --git a/azalea/examples/steal.rs b/azalea/examples/steal.rs index f64fb8f3..74501ada 100644 --- a/azalea/examples/steal.rs +++ b/azalea/examples/steal.rs @@ -2,9 +2,9 @@ use std::sync::Arc; -use azalea::{prelude::*, BlockPos}; -use azalea_inventory::operations::QuickMoveClick; +use azalea::{BlockPos, prelude::*}; use azalea_inventory::ItemStack; +use azalea_inventory::operations::QuickMoveClick; use parking_lot::Mutex; #[tokio::main] diff --git a/azalea/examples/testbot/commands.rs b/azalea/examples/testbot/commands.rs index 9cdb3cb7..c3cf1b47 100644 --- a/azalea/examples/testbot/commands.rs +++ b/azalea/examples/testbot/commands.rs @@ -2,12 +2,12 @@ pub mod combat; pub mod debug; pub mod movement; +use azalea::Client; +use azalea::GameProfileComponent; use azalea::brigadier::prelude::*; use azalea::chat::ChatPacket; use azalea::ecs::prelude::*; use azalea::entity::metadata::Player; -use azalea::Client; -use azalea::GameProfileComponent; use parking_lot::Mutex; use crate::State; diff --git a/azalea/examples/testbot/commands/debug.rs b/azalea/examples/testbot/commands/debug.rs index 10b9711d..fe552668 100644 --- a/azalea/examples/testbot/commands/debug.rs +++ b/azalea/examples/testbot/commands/debug.rs @@ -3,12 +3,12 @@ use std::{env, fs::File, io::Write, thread, time::Duration}; use azalea::{ + BlockPos, brigadier::prelude::*, entity::{LookDirection, Position}, interact::HitResultComponent, pathfinder::{ExecutingPath, Pathfinder}, world::MinecraftEntityId, - BlockPos, }; use parking_lot::Mutex; diff --git a/azalea/examples/testbot/commands/movement.rs b/azalea/examples/testbot/commands/movement.rs index b0adec8b..a8511cc5 100644 --- a/azalea/examples/testbot/commands/movement.rs +++ b/azalea/examples/testbot/commands/movement.rs @@ -1,11 +1,11 @@ use std::time::Duration; use azalea::{ + BlockPos, SprintDirection, WalkDirection, brigadier::prelude::*, entity::{EyeHeight, Position}, pathfinder::goals::{BlockPosGoal, RadiusGoal, XZGoal}, prelude::*, - BlockPos, SprintDirection, WalkDirection, }; use parking_lot::Mutex; diff --git a/azalea/examples/testbot/killaura.rs b/azalea/examples/testbot/killaura.rs index d86356fe..e98fe6ec 100644 --- a/azalea/examples/testbot/killaura.rs +++ b/azalea/examples/testbot/killaura.rs @@ -1,6 +1,6 @@ use azalea::{ ecs::prelude::*, - entity::{metadata::AbstractMonster, Dead, LocalEntity, Position}, + entity::{Dead, LocalEntity, Position, metadata::AbstractMonster}, prelude::*, world::{InstanceName, MinecraftEntityId}, }; diff --git a/azalea/examples/testbot/main.rs b/azalea/examples/testbot/main.rs index 958c17d0..410d1b6d 100644 --- a/azalea/examples/testbot/main.rs +++ b/azalea/examples/testbot/main.rs @@ -29,13 +29,13 @@ use std::time::Duration; use std::{env, process}; use std::{sync::Arc, thread}; +use azalea::ClientInformation; use azalea::brigadier::command_dispatcher::CommandDispatcher; use azalea::ecs::prelude::*; use azalea::pathfinder::PathfinderDebugParticles; use azalea::prelude::*; use azalea::swarm::prelude::*; -use azalea::ClientInformation; -use commands::{register_commands, CommandSource}; +use commands::{CommandSource, register_commands}; use parking_lot::Mutex; #[tokio::main] diff --git a/azalea/src/auto_respawn.rs b/azalea/src/auto_respawn.rs index 43ec4821..191e6df7 100644 --- a/azalea/src/auto_respawn.rs +++ b/azalea/src/auto_respawn.rs @@ -1,6 +1,6 @@ use azalea_client::{ packet_handling::{death_event_on_0_health, game::DeathEvent}, - respawn::{perform_respawn, PerformRespawnEvent}, + respawn::{PerformRespawnEvent, perform_respawn}, }; use bevy_app::Update; use bevy_ecs::prelude::*; diff --git a/azalea/src/auto_tool.rs b/azalea/src/auto_tool.rs index 9aea23d7..81fe3131 100644 --- a/azalea/src/auto_tool.rs +++ b/azalea/src/auto_tool.rs @@ -1,7 +1,7 @@ -use azalea_block::{fluid_state::FluidKind, Block, BlockState}; -use azalea_client::{inventory::Inventory, Client}; +use azalea_block::{Block, BlockState, fluid_state::FluidKind}; +use azalea_client::{Client, inventory::Inventory}; use azalea_entity::{FluidOnEyes, Physics}; -use azalea_inventory::{components, ItemStack, Menu}; +use azalea_inventory::{ItemStack, Menu, components}; #[derive(Debug)] pub struct BestToolResult { diff --git a/azalea/src/bot.rs b/azalea/src/bot.rs index 539a5281..aae8af05 100644 --- a/azalea/src/bot.rs +++ b/azalea/src/bot.rs @@ -1,13 +1,13 @@ use std::f64::consts::PI; +use azalea_client::TickBroadcast; use azalea_client::interact::SwingArmEvent; use azalea_client::mining::Mining; -use azalea_client::TickBroadcast; use azalea_core::position::{BlockPos, Vec3}; use azalea_core::tick::GameTick; use azalea_entity::{ - clamp_look_direction, metadata::Player, EyeHeight, Jumping, LocalEntity, LookDirection, - Position, + EyeHeight, Jumping, LocalEntity, LookDirection, Position, clamp_look_direction, + metadata::Player, }; use azalea_physics::PhysicsSet; use bevy_app::Update; @@ -185,8 +185,7 @@ fn look_at_listener( direction_looking_at(&position.up(eye_height.into()), &event.position); trace!( "look at {:?} (currently at {:?})", - event.position, - **position + event.position, **position ); *look_direction = new_look_direction; } diff --git a/azalea/src/container.rs b/azalea/src/container.rs index 38877616..e1a018b0 100644 --- a/azalea/src/container.rs +++ b/azalea/src/container.rs @@ -2,12 +2,12 @@ use std::fmt::Debug; use std::fmt::Formatter; use azalea_client::{ + Client, inventory::{CloseContainerEvent, ContainerClickEvent, Inventory}, packet_handling::game::PacketEvent, - Client, }; use azalea_core::position::BlockPos; -use azalea_inventory::{operations::ClickOperation, ItemStack, Menu}; +use azalea_inventory::{ItemStack, Menu, operations::ClickOperation}; use azalea_protocol::packets::game::ClientboundGamePacket; use bevy_app::{App, Plugin, Update}; use bevy_ecs::{component::Component, prelude::EventReader, system::Commands}; diff --git a/azalea/src/lib.rs b/azalea/src/lib.rs index e50fde0a..0a8300b1 100644 --- a/azalea/src/lib.rs +++ b/azalea/src/lib.rs @@ -37,9 +37,9 @@ pub use bevy_app as app; pub use bevy_ecs as ecs; pub use bot::*; use ecs::component::Component; -use futures::{future::BoxFuture, Future}; +use futures::{Future, future::BoxFuture}; use protocol::connect::Proxy; -use protocol::{resolver::ResolverError, ServerAddress}; +use protocol::{ServerAddress, resolver::ResolverError}; use swarm::SwarmBuilder; use thiserror::Error; diff --git a/azalea/src/pathfinder/debug.rs b/azalea/src/pathfinder/debug.rs index ca08cbc5..98778cad 100644 --- a/azalea/src/pathfinder/debug.rs +++ b/azalea/src/pathfinder/debug.rs @@ -1,4 +1,4 @@ -use azalea_client::{chat::SendChatEvent, InstanceHolder}; +use azalea_client::{InstanceHolder, chat::SendChatEvent}; use azalea_core::position::Vec3; use bevy_ecs::prelude::*; @@ -89,16 +89,16 @@ pub fn debug_render_path_with_particles( z: start_vec3.z + (end_vec3.z - start_vec3.z) * percent, }; let particle_command = format!( - "/particle dust{{color:[{r},{g},{b}],scale:{size}}} {start_x} {start_y} {start_z} {delta_x} {delta_y} {delta_z} 0 {count}", - size = 1, - start_x = pos.x, - start_y = pos.y, - start_z = pos.z, - delta_x = 0, - delta_y = 0, - delta_z = 0, - count = 1 - ); + "/particle dust{{color:[{r},{g},{b}],scale:{size}}} {start_x} {start_y} {start_z} {delta_x} {delta_y} {delta_z} 0 {count}", + size = 1, + start_x = pos.x, + start_y = pos.y, + start_z = pos.z, + delta_x = 0, + delta_y = 0, + delta_z = 0, + count = 1 + ); chat_events.send(SendChatEvent { entity, content: particle_command, diff --git a/azalea/src/pathfinder/mining.rs b/azalea/src/pathfinder/mining.rs index 8c1b2e1d..40cdf8a2 100644 --- a/azalea/src/pathfinder/mining.rs +++ b/azalea/src/pathfinder/mining.rs @@ -1,7 +1,7 @@ use std::{cell::UnsafeCell, ops::RangeInclusive}; use azalea_block::{ - block_state::BlockStateIntegerRepr, properties::Waterlogged, BlockState, BlockStates, + BlockState, BlockStates, block_state::BlockStateIntegerRepr, properties::Waterlogged, }; use azalea_inventory::Menu; use nohash_hasher::IntMap; diff --git a/azalea/src/pathfinder/mod.rs b/azalea/src/pathfinder/mod.rs index ae23788b..0db627ac 100644 --- a/azalea/src/pathfinder/mod.rs +++ b/azalea/src/pathfinder/mod.rs @@ -14,8 +14,8 @@ pub mod world; use std::collections::VecDeque; use std::ops::RangeInclusive; -use std::sync::atomic::{self, AtomicUsize}; use std::sync::Arc; +use std::sync::atomic::{self, AtomicUsize}; use std::time::{Duration, Instant}; use std::{cmp, thread}; @@ -26,8 +26,8 @@ use azalea_client::movement::MoveEventsSet; use azalea_client::{InstanceHolder, StartSprintEvent, StartWalkEvent}; use azalea_core::position::BlockPos; use azalea_core::tick::GameTick; -use azalea_entity::metadata::Player; use azalea_entity::LocalEntity; +use azalea_entity::metadata::Player; use azalea_entity::{Physics, Position}; use azalea_physics::PhysicsSet; use azalea_world::{InstanceContainer, InstanceName}; @@ -42,11 +42,12 @@ use parking_lot::RwLock; use rel_block_pos::RelBlockPos; use tracing::{debug, error, info, trace, warn}; -use self::debug::debug_render_path_with_particles; pub use self::debug::PathfinderDebugParticles; +use self::debug::debug_render_path_with_particles; use self::goals::Goal; use self::mining::MiningCache; use self::moves::{ExecuteCtx, IsReachedCtx, SuccessorsFn}; +use crate::WalkDirection; use crate::app::{App, Plugin}; use crate::bot::{JumpEvent, LookAtEvent}; use crate::ecs::{ @@ -57,7 +58,6 @@ use crate::ecs::{ system::{Commands, Query, Res}, }; use crate::pathfinder::{astar::a_star, moves::PathfinderCtx, world::CachedWorld}; -use crate::WalkDirection; #[derive(Clone, Default)] pub struct PathfinderPlugin; @@ -874,54 +874,62 @@ pub fn recalculate_near_end_of_path( && !pathfinder.is_calculating && executing_path.is_path_partial { - if let Some(goal) = pathfinder.goal.as_ref().cloned() { - debug!("Recalculating path because it's empty or ends soon"); - debug!( - "recalculate_near_end_of_path executing_path.is_path_partial: {}", - executing_path.is_path_partial - ); - goto_events.send(GotoEvent { - entity, - goal, - successors_fn, - allow_mining: pathfinder.allow_mining, - min_timeout: if executing_path.path.len() == 50 { - // we have quite some time until the node is reached, soooo we might as well - // burn some cpu cycles to get a good path - PathfinderTimeout::Time(Duration::from_secs(5)) - } else { - PathfinderTimeout::Time(Duration::from_secs(1)) - }, - max_timeout: pathfinder.max_timeout.expect("max_timeout should be set"), - }); - pathfinder.is_calculating = true; + match pathfinder.goal.as_ref().cloned() { + Some(goal) => { + debug!("Recalculating path because it's empty or ends soon"); + debug!( + "recalculate_near_end_of_path executing_path.is_path_partial: {}", + executing_path.is_path_partial + ); + goto_events.send(GotoEvent { + entity, + goal, + successors_fn, + allow_mining: pathfinder.allow_mining, + min_timeout: if executing_path.path.len() == 50 { + // we have quite some time until the node is reached, soooo we might as + // well burn some cpu cycles to get a good + // path + PathfinderTimeout::Time(Duration::from_secs(5)) + } else { + PathfinderTimeout::Time(Duration::from_secs(1)) + }, + max_timeout: pathfinder.max_timeout.expect("max_timeout should be set"), + }); + pathfinder.is_calculating = true; - if executing_path.path.is_empty() { - if let Some(new_path) = executing_path.queued_path.take() { - executing_path.path = new_path; - if executing_path.path.is_empty() { - info!("the path we just swapped to was empty, so reached end of path"); + if executing_path.path.is_empty() { + if let Some(new_path) = executing_path.queued_path.take() { + executing_path.path = new_path; + if executing_path.path.is_empty() { + info!( + "the path we just swapped to was empty, so reached end of path" + ); + walk_events.send(StartWalkEvent { + entity, + direction: WalkDirection::None, + }); + commands.entity(entity).remove::(); + break; + } + } else { walk_events.send(StartWalkEvent { entity, direction: WalkDirection::None, }); commands.entity(entity).remove::(); - break; } - } else { + } + } + _ => { + if executing_path.path.is_empty() { + // idk when this can happen but stop moving just in case walk_events.send(StartWalkEvent { entity, direction: WalkDirection::None, }); - commands.entity(entity).remove::(); } } - } else if executing_path.path.is_empty() { - // idk when this can happen but stop moving just in case - walk_events.send(StartWalkEvent { - entity, - direction: WalkDirection::None, - }); } } } @@ -968,8 +976,7 @@ pub fn tick_execute_path( }; trace!( "executing move, position: {}, last_reached_node: {}", - **position, - executing_path.last_reached_node + **position, executing_path.last_reached_node ); (movement.data.execute)(ctx); } @@ -1117,11 +1124,11 @@ mod tests { use azalea_world::{Chunk, ChunkStorage, PartialChunkStorage}; use super::{ + GotoEvent, astar::PathfinderTimeout, goals::BlockPosGoal, moves, simulation::{SimulatedPlayerBundle, Simulation}, - GotoEvent, }; fn setup_blockposgoal_simulation( diff --git a/azalea/src/pathfinder/moves/basic.rs b/azalea/src/pathfinder/moves/basic.rs index 8a679376..4955ed08 100644 --- a/azalea/src/pathfinder/moves/basic.rs +++ b/azalea/src/pathfinder/moves/basic.rs @@ -6,7 +6,7 @@ use azalea_core::{ position::{BlockPos, Vec3}, }; -use super::{default_is_reached, Edge, ExecuteCtx, IsReachedCtx, MoveData, PathfinderCtx}; +use super::{Edge, ExecuteCtx, IsReachedCtx, MoveData, PathfinderCtx, default_is_reached}; use crate::pathfinder::{astar, costs::*, rel_block_pos::RelBlockPos}; pub fn basic_move(ctx: &mut PathfinderCtx, node: RelBlockPos) { diff --git a/azalea/src/pathfinder/moves/mod.rs b/azalea/src/pathfinder/moves/mod.rs index 68c65d5d..83e6369f 100644 --- a/azalea/src/pathfinder/moves/mod.rs +++ b/azalea/src/pathfinder/moves/mod.rs @@ -4,8 +4,8 @@ pub mod parkour; use std::{fmt::Debug, sync::Arc}; use azalea_client::{ - inventory::SetSelectedHotbarSlotEvent, mining::StartMiningBlockEvent, SprintDirection, - StartSprintEvent, StartWalkEvent, WalkDirection, + SprintDirection, StartSprintEvent, StartWalkEvent, WalkDirection, + inventory::SetSelectedHotbarSlotEvent, mining::StartMiningBlockEvent, }; use azalea_core::position::{BlockPos, Vec3}; use azalea_inventory::Menu; @@ -17,9 +17,9 @@ use super::{ astar, mining::MiningCache, rel_block_pos::RelBlockPos, - world::{is_block_state_passable, CachedWorld}, + world::{CachedWorld, is_block_state_passable}, }; -use crate::{auto_tool::best_tool_in_hotbar_for_block, JumpEvent, LookAtEvent}; +use crate::{JumpEvent, LookAtEvent, auto_tool::best_tool_in_hotbar_for_block}; type Edge = astar::Edge; diff --git a/azalea/src/pathfinder/simulation.rs b/azalea/src/pathfinder/simulation.rs index 0067c19f..ab0e540a 100644 --- a/azalea/src/pathfinder/simulation.rs +++ b/azalea/src/pathfinder/simulation.rs @@ -2,10 +2,10 @@ use std::sync::Arc; -use azalea_client::{inventory::Inventory, packet_handling::game::SendPacketEvent, PhysicsState}; +use azalea_client::{PhysicsState, inventory::Inventory, packet_handling::game::SendPacketEvent}; use azalea_core::{position::Vec3, resource_location::ResourceLocation, tick::GameTick}; use azalea_entity::{ - attributes::AttributeInstance, Attributes, EntityDimensions, LookDirection, Physics, Position, + Attributes, EntityDimensions, LookDirection, Physics, Position, attributes::AttributeInstance, }; use azalea_registry::EntityKind; use azalea_world::{ChunkStorage, Instance, InstanceContainer, MinecraftEntityId, PartialInstance}; @@ -87,7 +87,7 @@ fn create_simulation_instance(chunks: ChunkStorage) -> (App, Arc>, player: &SimulatedPlayerBundle, -) -> impl Bundle { +) -> impl Bundle + use<> { let instance_name = simulation_instance_name(); ( diff --git a/azalea/src/prelude.rs b/azalea/src/prelude.rs index d1442b10..4f68f1ea 100644 --- a/azalea/src/prelude.rs +++ b/azalea/src/prelude.rs @@ -8,6 +8,6 @@ pub use azalea_core::tick::GameTick; pub use crate::ecs as bevy_ecs; pub use crate::ecs::{component::Component, system::Resource}; pub use crate::{ - bot::BotClientExt, container::ContainerClientExt, pathfinder::PathfinderClientExt, - ClientBuilder, + ClientBuilder, bot::BotClientExt, container::ContainerClientExt, + pathfinder::PathfinderClientExt, }; diff --git a/azalea/src/swarm/mod.rs b/azalea/src/swarm/mod.rs index 696f751b..cc0d7eb1 100644 --- a/azalea/src/swarm/mod.rs +++ b/azalea/src/swarm/mod.rs @@ -9,14 +9,14 @@ pub mod prelude; use std::{collections::HashMap, future::Future, net::SocketAddr, sync::Arc, time::Duration}; use azalea_client::{ - chat::ChatPacket, start_ecs_runner, Account, Client, DefaultPlugins, Event, JoinError, - StartClientOpts, + Account, Client, DefaultPlugins, Event, JoinError, StartClientOpts, chat::ChatPacket, + start_ecs_runner, }; -use azalea_protocol::{resolver, ServerAddress}; +use azalea_protocol::{ServerAddress, resolver}; use azalea_world::InstanceContainer; use bevy_app::{App, PluginGroup, PluginGroupBuilder, Plugins}; use bevy_ecs::{component::Component, entity::Entity, system::Resource, world::World}; -use futures::future::{join_all, BoxFuture}; +use futures::future::{BoxFuture, join_all}; use parking_lot::{Mutex, RwLock}; use tokio::sync::mpsc; use tracing::{debug, error}; @@ -692,14 +692,17 @@ impl Swarm { .min(Duration::from_secs(15)); let username = account.username.clone(); - if let JoinError::Disconnect { reason } = &e { - error!( - "Error joining as {username}, server says: \"{reason}\". Waiting {delay:?} and trying again." - ); - } else { - error!( - "Error joining as {username}: {e}. Waiting {delay:?} and trying again." - ); + match &e { + JoinError::Disconnect { reason } => { + error!( + "Error joining as {username}, server says: \"{reason}\". Waiting {delay:?} and trying again." + ); + } + _ => { + error!( + "Error joining as {username}: {e}. Waiting {delay:?} and trying again." + ); + } } tokio::time::sleep(delay).await;