azalea_client/
local_player.rs

1use std::{
2    collections::HashMap,
3    error, io,
4    sync::{Arc, PoisonError},
5};
6
7use azalea_core::game_type::GameMode;
8use azalea_world::{Instance, PartialInstance};
9use bevy_ecs::{component::Component, prelude::*};
10use derive_more::{Deref, DerefMut};
11use parking_lot::RwLock;
12use thiserror::Error;
13use tokio::sync::mpsc;
14use tracing::error;
15use uuid::Uuid;
16
17use crate::{ClientInformation, events::Event as AzaleaEvent, player::PlayerInfo};
18
19/// A component that keeps strong references to our [`PartialInstance`] and
20/// [`Instance`] for local players.
21///
22/// This can also act as a convenience for accessing the player's Instance since
23/// the alternative is to look up the player's [`InstanceName`] in the
24/// [`InstanceContainer`].
25///
26/// [`InstanceContainer`]: azalea_world::InstanceContainer
27/// [`InstanceName`]: azalea_world::InstanceName
28#[derive(Component, Clone)]
29pub struct InstanceHolder {
30    /// The partial instance is the world this client currently has loaded. It
31    /// has a limited render distance.
32    pub partial_instance: Arc<RwLock<PartialInstance>>,
33    /// The world is the combined [`PartialInstance`]s of all clients in the
34    /// same world.
35    ///
36    /// This is only relevant if you're using a shared world (i.e. a
37    /// swarm).
38    pub instance: Arc<RwLock<Instance>>,
39}
40
41/// The gamemode of a local player. For a non-local player, you can look up the
42/// player in the [`TabList`].
43#[derive(Component, Clone, Debug, Copy)]
44pub struct LocalGameMode {
45    pub current: GameMode,
46    pub previous: Option<GameMode>,
47}
48impl From<GameMode> for LocalGameMode {
49    fn from(current: GameMode) -> Self {
50        LocalGameMode {
51            current,
52            previous: None,
53        }
54    }
55}
56
57/// Level must be 0..=4
58#[derive(Component, Clone, Default, Deref, DerefMut)]
59pub struct PermissionLevel(pub u8);
60
61/// A component that contains a map of player UUIDs to their information in the
62/// tab list.
63///
64/// ```
65/// # use azalea_client::local_player::TabList;
66/// # fn example(client: &azalea_client::Client) {
67/// let tab_list = client.component::<TabList>();
68/// println!("Online players:");
69/// for (uuid, player_info) in tab_list.iter() {
70///     println!("- {} ({}ms)", player_info.profile.name, player_info.latency);
71/// }
72/// # }
73/// ```
74///
75/// For convenience, `TabList` is also a resource in the ECS.
76/// It's set to be the same as the tab list for the last client whose tab list
77/// was updated.
78/// This means you should avoid using `TabList` as a resource unless you know
79/// all of your clients will have the same tab list.
80#[derive(Component, Resource, Clone, Debug, Deref, DerefMut, Default)]
81pub struct TabList(HashMap<Uuid, PlayerInfo>);
82
83#[derive(Component, Clone)]
84pub struct Hunger {
85    /// The main hunger bar. Goes from 0 to 20.
86    pub food: u32,
87    /// The amount of saturation the player has. This isn't shown in normal
88    /// vanilla clients but it's a separate counter that makes it so your hunger
89    /// only starts decreasing when this is 0.
90    pub saturation: f32,
91}
92
93impl Default for Hunger {
94    fn default() -> Self {
95        Hunger {
96            food: 20,
97            saturation: 5.,
98        }
99    }
100}
101impl Hunger {
102    /// Returns true if we have enough food level to sprint.
103    ///
104    /// Note that this doesn't consider our gamemode or passenger status.
105    pub fn is_enough_to_sprint(&self) -> bool {
106        // hasEnoughFoodToSprint
107        self.food >= 6
108    }
109}
110
111impl InstanceHolder {
112    /// Create a new `InstanceHolder` for the given entity.
113    ///
114    /// The partial instance will be created for you. The render distance will
115    /// be set to a default value, which you can change by creating a new
116    /// partial_instance.
117    pub fn new(entity: Entity, instance: Arc<RwLock<Instance>>) -> Self {
118        let client_information = ClientInformation::default();
119
120        InstanceHolder {
121            instance,
122            partial_instance: Arc::new(RwLock::new(PartialInstance::new(
123                azalea_world::chunk_storage::calculate_chunk_storage_range(
124                    client_information.view_distance.into(),
125                ),
126                Some(entity),
127            ))),
128        }
129    }
130
131    /// Reset the `Instance` to a new reference to an empty instance, but with
132    /// the same registries as the current one.
133    ///
134    /// This is used by Azalea when entering the config state.
135    pub fn reset(&mut self) {
136        let registries = self.instance.read().registries.clone();
137
138        let new_instance = Instance {
139            registries,
140            ..Default::default()
141        };
142        self.instance = Arc::new(RwLock::new(new_instance));
143
144        self.partial_instance.write().reset();
145    }
146}
147
148#[derive(Error, Debug)]
149pub enum HandlePacketError {
150    #[error("{0}")]
151    Poison(String),
152    #[error(transparent)]
153    Io(#[from] io::Error),
154    #[error(transparent)]
155    Other(#[from] Box<dyn error::Error + Send + Sync>),
156    #[error("{0}")]
157    Send(#[from] mpsc::error::SendError<AzaleaEvent>),
158}
159
160impl<T> From<PoisonError<T>> for HandlePacketError {
161    fn from(e: PoisonError<T>) -> Self {
162        HandlePacketError::Poison(e.to_string())
163    }
164}