Skip to main content

azalea_client/plugins/packet/game/
events.rs

1use std::sync::{Arc, Weak};
2
3use azalea_chat::FormattedText;
4use azalea_protocol::packets::{
5    Packet,
6    game::{ClientboundGamePacket, ClientboundPlayerCombatKill, ServerboundGamePacket},
7};
8use azalea_world::{World, WorldName};
9use bevy_ecs::prelude::*;
10use parking_lot::RwLock;
11use tracing::{error, trace};
12use uuid::Uuid;
13
14use crate::{
15    client::InGameState, connection::RawConnection, local_player::WorldHolder, player::PlayerInfo,
16};
17
18/// An event that's sent when we receive a packet.
19/// ```
20/// # use azalea_client::packet::game::ReceiveGamePacketEvent;
21/// # use azalea_protocol::packets::game::ClientboundGamePacket;
22/// # use bevy_ecs::message::MessageReader;
23///
24/// fn handle_packets(mut events: MessageReader<ReceiveGamePacketEvent>) {
25///     for ReceiveGamePacketEvent { entity, packet } in events.read() {
26///         match packet.as_ref() {
27///             ClientboundGamePacket::LevelParticles(p) => {
28///                 // ...
29///             }
30///             _ => {}
31///         }
32///     }
33/// }
34/// ```
35#[derive(Clone, Debug, Message)]
36pub struct ReceiveGamePacketEvent {
37    /// The client entity that received the packet.
38    pub entity: Entity,
39    /// The packet that was actually received.
40    pub packet: Arc<ClientboundGamePacket>,
41}
42
43/// An event for sending a packet to the server while we're in the `game` state.
44#[derive(Clone, Debug, EntityEvent)]
45pub struct SendGamePacketEvent {
46    #[event_target]
47    pub sent_by: Entity,
48    pub packet: ServerboundGamePacket,
49}
50impl SendGamePacketEvent {
51    pub fn new(sent_by: Entity, packet: impl Packet<ServerboundGamePacket>) -> Self {
52        let packet = packet.into_variant();
53        Self { sent_by, packet }
54    }
55}
56
57pub fn handle_outgoing_packets_observer(
58    trigger: On<SendGamePacketEvent>,
59    mut query: Query<(
60        &mut RawConnection,
61        Option<&WorldHolder>,
62        Option<&InGameState>,
63    )>,
64) {
65    let event = trigger.event();
66
67    if let Ok((mut raw_connection, world, in_game_state)) = query.get_mut(event.sent_by) {
68        if in_game_state.is_none() {
69            error!(
70                "Tried to send a game packet {:?} while not in game state",
71                event.packet
72            );
73            return;
74        }
75
76        trace!("Sending game packet: {:?}", event.packet);
77
78        let mut write_fn = |ctx: azalea_buf::Ctx| {
79            if let Err(e) = raw_connection.write(ctx, event.packet.clone()) {
80                error!("Failed to send packet: {e}");
81            }
82        };
83        if let Some(world) = world {
84            write_fn(azalea_buf::Ctx::new(&world.shared.read().registries))
85        } else {
86            write_fn(azalea_buf::Ctx::default())
87        };
88    } else {
89        trace!("Not sending game packet: {:?}", event.packet);
90    }
91}
92
93/// A player joined the game (or more specifically, was added to the tab
94/// list of a local player).
95#[derive(Clone, Debug, Message)]
96pub struct AddPlayerEvent {
97    /// The local player entity that received this event.
98    pub entity: Entity,
99    pub info: PlayerInfo,
100}
101/// A player left the game (or maybe is still in the game and was just
102/// removed from the tab list of a local player).
103#[derive(Clone, Debug, Message)]
104pub struct RemovePlayerEvent {
105    /// The local player entity that received this event.
106    pub entity: Entity,
107    pub info: PlayerInfo,
108}
109/// A player was updated in the tab list of a local player (gamemode, display
110/// name, or latency changed).
111#[derive(Clone, Debug, Message)]
112pub struct UpdatePlayerEvent {
113    /// The local player entity that received this event.
114    pub entity: Entity,
115    pub info: PlayerInfo,
116}
117
118/// Event for when an entity dies.
119///
120/// If it's a local player and there's a reason in the death screen, the
121/// [`ClientboundPlayerCombatKill`] will be included.
122#[derive(Clone, Debug, Message)]
123pub struct DeathEvent {
124    pub entity: Entity,
125    pub packet: Option<ClientboundPlayerCombatKill>,
126}
127
128/// A KeepAlive packet is sent from the server to verify that the client is
129/// still connected.
130#[derive(Clone, Debug, EntityEvent)]
131pub struct KeepAliveEvent {
132    pub entity: Entity,
133    /// The ID of the keepalive.
134    ///
135    /// This is an arbitrary number, but vanilla servers use the current time to
136    /// generate this.
137    pub id: u64,
138}
139
140#[derive(Clone, Debug, Message)]
141pub struct ResourcePackEvent {
142    pub entity: Entity,
143    /// The random ID for this request to download the resource pack.
144    ///
145    /// The packet for replying to a resource pack push must contain the same
146    /// ID.
147    pub id: Uuid,
148    pub url: String,
149    pub hash: String,
150    pub required: bool,
151    pub prompt: Option<FormattedText>,
152}
153
154/// A world instance (aka dimension) was loaded by a client.
155///
156/// Since the world is given to you as a weak reference, it won't be able to be
157/// `upgrade`d if all local players unload it.
158#[derive(Clone, Debug, Message)]
159pub struct WorldLoadedEvent {
160    pub entity: Entity,
161    pub name: WorldName,
162    pub world: Weak<RwLock<World>>,
163}
164#[deprecated = "renamed to `WorldLoadedEvent`."]
165pub type InstanceLoadedEvent = WorldLoadedEvent;
166
167/// A Bevy trigger that's sent when our client receives a [`ClientboundPing`]
168/// packet in the game state.
169///
170/// Also see [`ConfigPingEvent`] which is used for the config state.
171///
172/// [`ClientboundPing`]: azalea_protocol::packets::game::ClientboundPing
173/// [`ConfigPingEvent`]: crate::packet::config::ConfigPingEvent
174#[derive(Clone, Debug, EntityEvent)]
175pub struct GamePingEvent {
176    pub entity: Entity,
177    pub packet: azalea_protocol::packets::game::ClientboundPing,
178}