Skip to main content

ghast_ext/
actions.rs

1//! Hands: dig, place, activate blocks, use items.
2
3use ghast_client::hands::BlockHit;
4use ghast_client::{BlockPos, Buttons, Face, GameMode, TickContext};
5
6use crate::{Bot, Error};
7
8/// Releases the mouse buttons when a helper ends early (dropped, failed, cancelled).
9struct ReleaseButtons(Option<Bot>);
10
11impl ReleaseButtons {
12    fn new(bot: &Bot) -> Self {
13        ReleaseButtons(Some(bot.clone()))
14    }
15
16    fn disarm(mut self) {
17        self.0 = None;
18    }
19}
20
21impl Drop for ReleaseButtons {
22    fn drop(&mut self) {
23        if let Some(bot) = self.0.take() {
24            bot.act(|ctx| ctx.set_buttons(Buttons::default()));
25        }
26    }
27}
28
29/// Options of [`Bot::dig_with`].
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31#[non_exhaustive]
32pub struct DigOptions {
33    /// Select the hotbar slot that digs fastest first (default on; only `select_slot`, no
34    /// clicks). See [`Bot::equip_for_block`] to bring a tool from the main inventory.
35    pub best_tool: bool,
36    /// The face to dig from (default: the most visible one).
37    pub face: Option<Face>,
38    /// Give up after this many ticks (default: twice the vanilla dig time + 2 s).
39    pub timeout: Option<u64>,
40}
41
42impl Default for DigOptions {
43    fn default() -> Self {
44        DigOptions {
45            best_tool: true,
46            face: None,
47            timeout: None,
48        }
49    }
50}
51
52impl DigOptions {
53    /// Whether to select the fastest hotbar tool first.
54    ///
55    /// ```
56    /// let o = ghast_ext::DigOptions::default().best_tool(false);
57    /// ```
58    #[must_use]
59    pub const fn best_tool(mut self, on: bool) -> Self {
60        self.best_tool = on;
61        self
62    }
63
64    /// The face to dig from.
65    ///
66    /// ```
67    /// let o = ghast_ext::DigOptions::default().face(ghast_client::Face::Up);
68    /// ```
69    #[must_use]
70    pub const fn face(mut self, face: Face) -> Self {
71        self.face = Some(face);
72        self
73    }
74
75    /// Time limit in ticks.
76    ///
77    /// ```
78    /// let o = ghast_ext::DigOptions::default().timeout(400);
79    /// ```
80    #[must_use]
81    pub const fn timeout(mut self, ticks: u64) -> Self {
82        self.timeout = Some(ticks);
83        self
84    }
85}
86
87/// The hotbar slot that digs `pos` fastest (the held slot on a tie) and its speed.
88pub(crate) fn best_hotbar_tool(ctx: &TickContext<'_>, pos: BlockPos) -> (u8, f32) {
89    let held = ctx.held_slot();
90    let speed = |k: u8| {
91        ctx.dig_speed(pos, ctx.inventory().hotbar(usize::from(k)))
92            .unwrap_or(0.0)
93    };
94    let mut best = (held, speed(held));
95    for k in 0..9u8 {
96        let s = speed(k);
97        if s > best.1 {
98            best = (k, s);
99        }
100    }
101    best
102}
103
104/// Ticks to break at `speed` progress per tick (vanilla sums f32 progress up to 1).
105fn dig_ticks(speed: f32) -> u64 {
106    if speed <= 0.0 {
107        return u64::MAX;
108    }
109    let mut p = 0.0f32;
110    let mut n = 0u64;
111    while p < 1.0 && n < 100_000 {
112        p += speed;
113        n += 1;
114    }
115    n
116}
117
118impl Bot {
119    /// Digs the block at `pos`: selects the fastest hotbar tool, turns until the server
120    /// has the crosshair on the block (aim first), then holds the left button for the
121    /// vanilla dig time (tool, efficiency, haste / fatigue, water, not on ground) and
122    /// releases it once the block is gone. The player should stand still meanwhile.
123    ///
124    /// Fails with [`Error::NothingToDig`] (air), [`Error::Unbreakable`],
125    /// [`Error::OutOfReach`], [`Error::LostTarget`], [`Error::Teleported`] /
126    /// [`Error::Died`] or [`Error::Timeout`]. The client predicts the broken block as air;
127    /// if the server disagrees it sends the block back (see [`Bot::block_at`]).
128    ///
129    /// ```no_run
130    /// use ghast_client::BlockPos;
131    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
132    /// bot.dig(BlockPos::new(2, 64, 0)).await?;
133    /// # Ok(()) }
134    /// ```
135    pub async fn dig(&self, pos: BlockPos) -> Result<(), Error> {
136        self.dig_with(pos, DigOptions::default()).await
137    }
138
139    /// [`Bot::dig`] with options.
140    ///
141    /// ```no_run
142    /// use ghast_client::{BlockPos, Face};
143    /// use ghast_ext::DigOptions;
144    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
145    /// bot.dig_with(BlockPos::new(2, 64, 0), DigOptions::default().best_tool(false).face(Face::Up)).await?;
146    /// # Ok(()) }
147    /// ```
148    pub async fn dig_with(&self, pos: BlockPos, opts: DigOptions) -> Result<(), Error> {
149        let mark = self.mark();
150        // Check and pick the tool.
151        let (original, ticks) = self
152            .with(move |ctx| -> Result<(u32, u64), Error> {
153                let raw = ctx
154                    .world()
155                    .raw_block(pos.x, pos.y, pos.z)
156                    .ok_or(Error::NotLoaded(pos))?;
157                let q = ctx
158                    .world()
159                    .block_query(pos.x, pos.y, pos.z)
160                    .ok_or(Error::NotLoaded(pos))?;
161                if q.air {
162                    return Err(Error::NothingToDig(pos));
163                }
164                if ctx.game_mode() == GameMode::Creative {
165                    return Ok((raw, 1));
166                }
167                if q.hardness < 0.0 {
168                    return Err(Error::Unbreakable(pos));
169                }
170                let speed = if opts.best_tool {
171                    let (slot, speed) = best_hotbar_tool(ctx, pos);
172                    ctx.select_slot(slot);
173                    speed
174                } else {
175                    ctx.dig_speed(pos, ctx.inventory().held()).unwrap_or(0.0)
176                };
177                if speed <= 0.0 {
178                    return Err(Error::Unbreakable(pos));
179                }
180                Ok((raw, dig_ticks(speed)))
181            })
182            .await??;
183        let limit = opts
184            .timeout
185            .unwrap_or_else(|| ticks.saturating_mul(2).saturating_add(40));
186        // Aim first: the server judges the dig with the sent look.
187        self.look_at_block(pos, opts.face).await?;
188        // Hold left until the block changes.
189        let release = ReleaseButtons::new(self);
190        let start = self.tick();
191        let mut off_ticks = 0u32;
192        loop {
193            let state = self
194                .with(move |ctx| {
195                    let now = ctx.world().raw_block(pos.x, pos.y, pos.z);
196                    if now != Some(original) {
197                        ctx.set_buttons(Buttons::default());
198                        return Some(true);
199                    }
200                    let on = ctx.target().is_some_and(|t| t.pos == pos);
201                    ctx.set_buttons(Buttons {
202                        left: on,
203                        right: false,
204                    });
205                    on.then_some(false)
206                })
207                .await?;
208            match state {
209                Some(true) => break,
210                Some(false) => off_ticks = 0,
211                None => {
212                    off_ticks += 1;
213                    if off_ticks > 10 {
214                        return Err(Error::LostTarget(pos));
215                    }
216                }
217            }
218            if self.tick().saturating_sub(start) > limit {
219                return Err(Error::Timeout);
220            }
221            self.next_tick().await;
222            self.check(mark)?;
223        }
224        release.disarm();
225        Ok(())
226    }
227
228    /// Places the held block against `against`'s `face` (the new block goes to
229    /// `face.offset(against)`): turns until the server has the crosshair on that face, sends
230    /// the right click at the crosshair's hit point, and waits until the block appears.
231    ///
232    /// Fails with [`Error::NoSupport`] (air), [`Error::Occupied`] (the target is not air /
233    /// liquid, or the player stands in it), [`Error::WouldActivate`] (a chest, door, ... :
234    /// the click would use it), [`Error::NothingHeld`], [`Error::OutOfReach`],
235    /// [`Error::NotPlaced`] (the server refused) and the usual interrupts.
236    ///
237    /// ```no_run
238    /// use ghast_client::{BlockPos, Face};
239    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
240    /// bot.equip("cobblestone").await?;
241    /// bot.place(BlockPos::new(2, 63, 0), Face::Up).await?; // on top of the block at y 63
242    /// # Ok(()) }
243    /// ```
244    pub async fn place(&self, against: BlockPos, face: Face) -> Result<(), Error> {
245        let mark = self.mark();
246        let target = face.offset(against);
247        let before = self
248            .with(move |ctx| -> Result<Option<u32>, Error> {
249                let w = ctx.world();
250                let s = w
251                    .block_query(against.x, against.y, against.z)
252                    .ok_or(Error::NotLoaded(against))?;
253                if s.air {
254                    return Err(Error::NoSupport(against));
255                }
256                if s.activates && !ctx.pose().sneaking {
257                    return Err(Error::WouldActivate(against));
258                }
259                let t = w
260                    .block_query(target.x, target.y, target.z)
261                    .ok_or(Error::NotLoaded(target))?;
262                let raw = w.raw_block(target.x, target.y, target.z);
263                let liquid = raw.is_some_and(|r| crate::Block::new(ctx.version(), r).is_liquid());
264                if !t.air && !liquid {
265                    return Err(Error::Occupied(target));
266                }
267                if ctx.inventory().held().is_none() {
268                    return Err(Error::NothingHeld);
269                }
270                // The player's box (0.6 x 1.8) must not overlap the new block.
271                let p = ctx.pose().pos;
272                let (tx, ty, tz) = (
273                    f64::from(target.x),
274                    f64::from(target.y),
275                    f64::from(target.z),
276                );
277                if p.x + 0.3 > tx
278                    && p.x - 0.3 < tx + 1.0
279                    && p.y + 1.8 > ty
280                    && p.y < ty + 1.0
281                    && p.z + 0.3 > tz
282                    && p.z - 0.3 < tz + 1.0
283                {
284                    return Err(Error::Occupied(target));
285                }
286                Ok(raw)
287            })
288            .await??;
289        let hit = self.look_at_block(against, Some(face)).await?;
290        self.right_click(against, face, hit, mark).await?;
291        // Wait for the server's block change.
292        for _ in 0..20 {
293            self.next_tick().await;
294            self.check(mark)?;
295            let now = self
296                .with(move |ctx| ctx.world().raw_block(target.x, target.y, target.z))
297                .await?;
298            if now != before {
299                return Ok(());
300            }
301        }
302        Err(Error::NotPlaced(target))
303    }
304
305    /// Right-clicks `pos` (opens a chest, flips a lever, uses a door, ...): turns until the
306    /// server has the crosshair on the block, then sends the click. Returns once it was sent;
307    /// see [`Bot::open_container`] to wait for a window.
308    ///
309    /// ```no_run
310    /// use ghast_client::BlockPos;
311    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
312    /// bot.activate_block(BlockPos::new(5, 64, 5)).await?; // a lever
313    /// # Ok(()) }
314    /// ```
315    pub async fn activate_block(&self, pos: BlockPos) -> Result<(), Error> {
316        let mark = self.mark();
317        let hit = self.look_at_block(pos, None).await?;
318        self.right_click(pos, hit.face, hit, mark).await
319    }
320
321    /// Sends `place` once the sent crosshair is on (`pos`, `face`), retrying a few ticks.
322    async fn right_click(
323        &self,
324        pos: BlockPos,
325        face: Face,
326        hit: BlockHit,
327        mark: crate::executor::Mark,
328    ) -> Result<(), Error> {
329        for _ in 0..10 {
330            let sent = self
331                .with(move |ctx| {
332                    // The hit point of the crosshair as the server will compute it.
333                    let h = ctx
334                        .target()
335                        .filter(|t| t.pos == pos && t.face == face)
336                        .map_or(hit.hit, |t| t.hit);
337                    ctx.place(pos, face, h)
338                })
339                .await?;
340            if sent {
341                return Ok(());
342            }
343            self.next_tick().await;
344            self.check(mark)?;
345        }
346        Err(Error::OutOfReach(pos))
347    }
348
349    /// Uses the held item until it is done: eats / drinks (food needs a non-full food bar;
350    /// golden apples always), with the right button held until the server ends the use.
351    /// Fails with [`Error::CannotUse`] when the use does not start. Look away from
352    /// containers / doors first (the right click would use them; checked:
353    /// [`Error::WouldActivate`]).
354    ///
355    /// ```no_run
356    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
357    /// if bot.health().food < 18 {
358    ///     bot.equip("bread").await?;
359    ///     bot.consume().await?;
360    /// }
361    /// # Ok(()) }
362    /// ```
363    pub async fn consume(&self) -> Result<(), Error> {
364        let mark = self.mark();
365        self.with(|ctx| -> Result<(), Error> {
366            let held = ctx.inventory().held().ok_or(Error::NothingHeld)?;
367            if !ctx.item_facts(held).is_some_and(|f| f.usable) {
368                return Err(Error::CannotUse);
369            }
370            if let Some(t) = ctx.target()
371                && ctx
372                    .world()
373                    .block_query(t.pos.x, t.pos.y, t.pos.z)
374                    .is_some_and(|b| b.activates)
375            {
376                return Err(Error::WouldActivate(t.pos));
377            }
378            ctx.set_buttons(Buttons {
379                left: false,
380                right: true,
381            });
382            Ok(())
383        })
384        .await??;
385        let release = ReleaseButtons::new(self);
386        let mut started = false;
387        for n in 0..100u32 {
388            self.next_tick().await;
389            self.check(mark)?;
390            let using = self.with(|ctx| ctx.using_item()).await?;
391            if using {
392                started = true;
393            } else if started {
394                drop(release);
395                return Ok(());
396            } else if n >= 5 {
397                return Err(Error::CannotUse);
398            }
399        }
400        Err(Error::Timeout)
401    }
402
403    /// Starts using the held item (right button held: draw a bow, block with a sword /
404    /// shield, start eating). Release it with [`Bot::deactivate_item`]. While the held item
405    /// cools down ([`Bot::held_cooldown`]) the held button only sends its packets, every 4
406    /// ticks, like vanilla ([`Bot::wait_cooldown`] waits for the end).
407    ///
408    /// ```no_run
409    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
410    /// bot.equip("bow").await?;
411    /// bot.activate_item();
412    /// bot.wait_ticks(20).await; // full draw
413    /// bot.deactivate_item();      // shoot
414    /// # Ok(()) }
415    /// ```
416    pub fn activate_item(&self) {
417        self.act(|ctx| {
418            ctx.set_buttons(Buttons {
419                left: false,
420                right: true,
421            });
422        });
423    }
424
425    /// Releases the mouse buttons (ends an item use, stops digging).
426    ///
427    /// ```no_run
428    /// # fn f(bot: ghast_ext::Bot) {
429    /// bot.deactivate_item();
430    /// # }
431    /// ```
432    pub fn deactivate_item(&self) {
433        self.act(|ctx| ctx.set_buttons(Buttons::default()));
434    }
435
436    /// Swings the arm.
437    ///
438    /// ```no_run
439    /// # fn f(bot: ghast_ext::Bot) {
440    /// bot.swing();
441    /// # }
442    /// ```
443    pub fn swing(&self) {
444        self.act(|ctx| ctx.swing());
445    }
446
447    /// Clicks the left button once in this tick's (or the next tick's) key handling, like a
448    /// vanilla mouse click: attacks the entity the crosshair is on, starts a dig, or misses
449    /// (then the 10-tick miss delay holds back the clicks after it in the same tick). Several
450    /// calls before a tick are several clicks in it. See
451    /// [`TickContext::press`](ghast_client::TickContext::press).
452    ///
453    /// ```no_run
454    /// # fn f(bot: ghast_ext::Bot) {
455    /// bot.left_click();
456    /// bot.left_click(); // two clicks in one tick
457    /// # }
458    /// ```
459    pub fn left_click(&self) {
460        self.act(|ctx| {
461            ctx.press(ghast_client::hands::Button::Left);
462        });
463    }
464
465    /// Attacks entity `id`: turns until the server's crosshair is on it, then attacks
466    /// (refused by the client unless it is). Needs [`ghast_client::Interests::ENTITIES`].
467    /// A living entity that already died ([`EntityInfo::alive`] `false`: its body stays for
468    /// the death animation) is not attacked: [`Error::NoSuchEntity`], like one that is gone
469    /// (vanilla would let the hit through, but it does nothing and costs the swing).
470    ///
471    /// [`EntityInfo::alive`]: crate::EntityInfo::alive
472    ///
473    /// ```no_run
474    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
475    /// if let Some(z) = bot.nearest_entity(|e| e.name == "zombie", 4.0).await? {
476    ///     bot.attack(z.id).await?;
477    /// }
478    /// # Ok(()) }
479    /// ```
480    pub async fn attack(&self, id: i32) -> Result<(), Error> {
481        let mark = self.mark();
482        for _ in 0..60 {
483            let r = self
484                .with(move |ctx| -> Result<bool, Error> {
485                    let es = ctx.entities().ok_or(Error::NoSuchEntity(id))?;
486                    let e = es
487                        .get(id)
488                        .filter(|e| e.is_alive())
489                        .ok_or(Error::NoSuchEntity(id))?;
490                    // Aim at the middle of its box (types without dimensions: item frames,
491                    // paintings, shulkers, ... have their own box).
492                    let [x, y, z] = e.position();
493                    let at = match (e.size(), e.bounding_box()) {
494                        (Some((_, h)), _) => ghast_client::Vec3::new(x, y + f64::from(h) / 2.0, z),
495                        (None, Some(b)) => ghast_client::Vec3::new(
496                            (b[0] + b[3]) / 2.0,
497                            (b[1] + b[4]) / 2.0,
498                            (b[2] + b[5]) / 2.0,
499                        ),
500                        (None, None) => ghast_client::Vec3::new(x, y + 0.9, z),
501                    };
502                    let (yaw, pitch) = crate::yaw_pitch(ctx.eyes(ctx.pose()), at);
503                    if ctx.target_entity().is_some_and(|t| t.id == id) {
504                        return Ok(ctx.attack(id));
505                    }
506                    ctx.set_aim(yaw, pitch);
507                    Ok(false)
508                })
509                .await??;
510            if r {
511                return Ok(());
512            }
513            self.next_tick().await;
514            self.check(mark)?;
515        }
516        Err(Error::Timeout)
517    }
518
519    /// Right clicks entity `id` once: turns until this tick's crosshair and the server's view
520    /// are on it, presses the right button for that tick and releases it. The client sends
521    /// what vanilla sends for the click (the interact packet per hand, the held item's use
522    /// where the entity passes the click). Needs [`ghast_client::Interests::ENTITIES`].
523    ///
524    /// An item frame takes the held item when it is empty and turns its item otherwise
525    /// ([`Bot::attack`] knocks the item out); a villager opens its trades, a sheep is sheared,
526    /// a mob takes a name tag. The server's answer is not waited for.
527    ///
528    /// Errors: [`Error::NoSuchEntity`] (gone or dead), [`Error::EntityOutOfReach`] (more than
529    /// 3 blocks from the eyes to its box), [`Error::Timeout`] (3 s without the crosshair on it).
530    ///
531    /// ```no_run
532    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
533    /// if let Some(frame) = bot.nearest_entity(|e| e.name == "item_frame", 3.0).await? {
534    ///     bot.interact(frame.id).await?; // put the held item in, or turn it
535    ///     bot.attack(frame.id).await?; // take it out again
536    /// }
537    /// # Ok(()) }
538    /// ```
539    pub async fn interact(&self, id: i32) -> Result<(), Error> {
540        let mark = self.mark();
541        let release = ReleaseButtons::new(self);
542        for _ in 0..60 {
543            let pressed = self
544                .with(move |ctx| crate::ride::mount_step(ctx, id))
545                .await??;
546            self.next_tick().await;
547            if pressed {
548                self.act(|ctx| ctx.set_buttons(Buttons::default()));
549                release.disarm();
550                return Ok(());
551            }
552            self.check(mark)?;
553        }
554        Err(Error::Timeout)
555    }
556}