azalea/
bot.rs

1use std::f64::consts::PI;
2
3use azalea_client::{
4    mining::Mining,
5    tick_broadcast::{TickBroadcast, UpdateBroadcast},
6};
7use azalea_core::{
8    position::{BlockPos, Vec3},
9    tick::GameTick,
10};
11use azalea_entity::{
12    Jumping, LocalEntity, LookDirection, Position, clamp_look_direction,
13    dimensions::EntityDimensions, metadata::Player, update_dimensions,
14};
15use azalea_physics::PhysicsSystems;
16use bevy_app::Update;
17use bevy_ecs::prelude::*;
18use futures_lite::Future;
19use tracing::trace;
20
21use crate::{
22    accept_resource_packs::AcceptResourcePacksPlugin,
23    app::{App, Plugin, PluginGroup, PluginGroupBuilder},
24    auto_respawn::AutoRespawnPlugin,
25    container::ContainerPlugin,
26    ecs::{
27        component::Component,
28        entity::Entity,
29        query::{With, Without},
30        system::{Commands, Query},
31    },
32    pathfinder::PathfinderPlugin,
33};
34
35#[derive(Clone, Default)]
36pub struct BotPlugin;
37impl Plugin for BotPlugin {
38    fn build(&self, app: &mut App) {
39        app.add_message::<LookAtEvent>()
40            .add_message::<JumpEvent>()
41            .add_systems(
42                Update,
43                (
44                    insert_bot,
45                    look_at_listener
46                        .before(clamp_look_direction)
47                        .after(update_dimensions),
48                    jump_listener,
49                ),
50            )
51            .add_systems(
52                GameTick,
53                stop_jumping
54                    .after(PhysicsSystems)
55                    .after(azalea_client::movement::send_player_input_packet),
56            );
57    }
58}
59
60/// A component that clients with [`BotPlugin`] will have. If you just want to
61/// check if an entity is one of our bots, you should use [`LocalEntity`].
62#[derive(Default, Component)]
63pub struct Bot {
64    jumping_once: bool,
65}
66
67/// Insert the [`Bot`] component for any local players that don't have it.
68#[allow(clippy::type_complexity)]
69fn insert_bot(
70    mut commands: Commands,
71    mut query: Query<Entity, (Without<Bot>, With<LocalEntity>, With<Player>)>,
72) {
73    for entity in &mut query {
74        commands.entity(entity).insert(Bot::default());
75    }
76}
77
78fn stop_jumping(mut query: Query<(&mut Jumping, &mut Bot)>) {
79    for (mut jumping, mut bot) in &mut query {
80        if bot.jumping_once && **jumping {
81            bot.jumping_once = false;
82            **jumping = false;
83        }
84    }
85}
86
87pub trait BotClientExt {
88    /// Queue a jump for the next tick.
89    fn jump(&self);
90    /// Turn the bot's head to look at the coordinate in the world.
91    fn look_at(&self, pos: Vec3);
92    /// Get a receiver that will receive a message every tick.
93    fn get_tick_broadcaster(&self) -> tokio::sync::broadcast::Receiver<()>;
94    /// Get a receiver that will receive a message every ECS Update.
95    fn get_update_broadcaster(&self) -> tokio::sync::broadcast::Receiver<()>;
96    /// Wait for the specified number of game ticks.
97    fn wait_ticks(&self, n: usize) -> impl Future<Output = ()> + Send;
98    /// Wait for the specified number of ECS `Update`s.
99    fn wait_updates(&self, n: usize) -> impl Future<Output = ()> + Send;
100    /// Mine a block. This won't turn the bot's head towards the block, so if
101    /// that's necessary you'll have to do that yourself with [`look_at`].
102    ///
103    /// [`look_at`]: crate::prelude::BotClientExt::look_at
104    fn mine(&self, position: BlockPos) -> impl Future<Output = ()> + Send;
105}
106
107impl BotClientExt for azalea_client::Client {
108    fn jump(&self) {
109        let mut ecs = self.ecs.lock();
110        ecs.write_message(JumpEvent {
111            entity: self.entity,
112        });
113    }
114
115    fn look_at(&self, position: Vec3) {
116        let mut ecs = self.ecs.lock();
117        ecs.write_message(LookAtEvent {
118            entity: self.entity,
119            position,
120        });
121    }
122
123    /// Returns a Receiver that receives a message every game tick.
124    ///
125    /// This is useful if you want to efficiently loop until a certain condition
126    /// is met.
127    ///
128    /// ```
129    /// # use azalea::prelude::*;
130    /// # use azalea::container::WaitingForInventoryOpen;
131    /// # async fn example(bot: &mut azalea::Client) {
132    /// let mut ticks = bot.get_tick_broadcaster();
133    /// while ticks.recv().await.is_ok() {
134    ///     let ecs = bot.ecs.lock();
135    ///     if ecs.get::<WaitingForInventoryOpen>(bot.entity).is_none() {
136    ///         break;
137    ///     }
138    /// }
139    /// # }
140    /// ```
141    fn get_tick_broadcaster(&self) -> tokio::sync::broadcast::Receiver<()> {
142        let ecs = self.ecs.lock();
143        let tick_broadcast = ecs.resource::<TickBroadcast>();
144        tick_broadcast.subscribe()
145    }
146
147    /// Returns a Receiver that receives a message every ECS Update.
148    ///
149    /// ECS Updates happen at least at the frequency of game ticks, usually
150    /// faster.
151    ///
152    /// This is useful if you're sending an ECS event and want to make sure it's
153    /// been handled before continuing.
154    fn get_update_broadcaster(&self) -> tokio::sync::broadcast::Receiver<()> {
155        let ecs = self.ecs.lock();
156        let update_broadcast = ecs.resource::<UpdateBroadcast>();
157        update_broadcast.subscribe()
158    }
159
160    /// Wait for the specified number of ticks using
161    /// [`Self::get_tick_broadcaster`].
162    ///
163    /// If you're going to run this in a loop, you may want to use that function
164    /// instead and use the `Receiver` from it to avoid accidentally skipping
165    /// ticks and having to wait longer.
166    async fn wait_ticks(&self, n: usize) {
167        let mut receiver = self.get_tick_broadcaster();
168        for _ in 0..n {
169            let _ = receiver.recv().await;
170        }
171    }
172    /// Waits for the specified number of ECS `Update`s using
173    /// [`Self::get_update_broadcaster`].
174    ///
175    /// These are basically equivalent to frames because even though we have no
176    /// rendering, some game mechanics depend on frames.
177    ///
178    /// If you're going to run this in a loop, you may want to use that function
179    /// instead and use the `Receiver` from it to avoid accidentally skipping
180    /// ticks and having to wait longer.
181    async fn wait_updates(&self, n: usize) {
182        let mut receiver = self.get_update_broadcaster();
183        for _ in 0..n {
184            let _ = receiver.recv().await;
185        }
186    }
187
188    async fn mine(&self, position: BlockPos) {
189        self.start_mining(position);
190
191        let mut receiver = self.get_tick_broadcaster();
192        while receiver.recv().await.is_ok() {
193            let ecs = self.ecs.lock();
194            if ecs.get::<Mining>(self.entity).is_none() {
195                break;
196            }
197        }
198    }
199}
200
201/// Event to jump once.
202#[derive(Message)]
203pub struct JumpEvent {
204    pub entity: Entity,
205}
206
207pub fn jump_listener(
208    mut query: Query<(&mut Jumping, &mut Bot)>,
209    mut events: MessageReader<JumpEvent>,
210) {
211    for event in events.read() {
212        if let Ok((mut jumping, mut bot)) = query.get_mut(event.entity) {
213            **jumping = true;
214            bot.jumping_once = true;
215        }
216    }
217}
218
219/// Make an entity look towards a certain position in the world.
220#[derive(Message)]
221pub struct LookAtEvent {
222    pub entity: Entity,
223    /// The position we want the entity to be looking at.
224    pub position: Vec3,
225}
226fn look_at_listener(
227    mut events: MessageReader<LookAtEvent>,
228    mut query: Query<(&Position, &EntityDimensions, &mut LookDirection)>,
229) {
230    for event in events.read() {
231        if let Ok((position, dimensions, mut look_direction)) = query.get_mut(event.entity) {
232            let new_look_direction =
233                direction_looking_at(position.up(dimensions.eye_height.into()), event.position);
234
235            trace!("look at {} (currently at {})", event.position, **position);
236            look_direction.update(new_look_direction);
237        }
238    }
239}
240
241/// Return the look direction that would make a client at `current` be
242/// looking at `target`.
243pub fn direction_looking_at(current: Vec3, target: Vec3) -> LookDirection {
244    // borrowed from mineflayer's Bot.lookAt because i didn't want to do math
245    let delta = target - current;
246    let y_rot = (PI - f64::atan2(-delta.x, -delta.z)) * (180.0 / PI);
247    let ground_distance = f64::sqrt(delta.x * delta.x + delta.z * delta.z);
248    let x_rot = f64::atan2(delta.y, ground_distance) * -(180.0 / PI);
249
250    LookDirection::new(y_rot as f32, x_rot as f32)
251}
252
253/// A [`PluginGroup`] for the plugins that add extra bot functionality to the
254/// client.
255pub struct DefaultBotPlugins;
256
257impl PluginGroup for DefaultBotPlugins {
258    fn build(self) -> PluginGroupBuilder {
259        PluginGroupBuilder::start::<Self>()
260            .add(BotPlugin)
261            .add(PathfinderPlugin)
262            .add(ContainerPlugin)
263            .add(AutoRespawnPlugin)
264            .add(AcceptResourcePacksPlugin)
265    }
266}