ghast-ext 0.5.4

Sequential, mineflayer-style async helpers (look, dig, place, equip, containers, chat, events, find) on top of the ghast bot library's deterministic tick model
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
//! Riding: boarding a mount or vehicle, getting off, the jump bar and the stick boost.
//!
//! Every helper here works the way a player does it, on every version, through the
//! client's own simulation (which moves the mount exactly as vanilla does):
//!
//! - **boarding** ([`Bot::mount`]) is a right click with the crosshair on the entity; the
//!   server seats the player (`set_passengers`, 1.8: `attach_entity`) or refuses silently
//!   (no saddle, not tamed, the seats taken: [`Error::NotSeated`]);
//! - **steering** is the normal movement keys and the look ([`Bot::set_controls`],
//!   [`Bot::look`]): a horse, camel, happy ghast or nautilus follows the rider's yaw and the
//!   keys, a pig or strider walks where the rider looks while a carrot / warped fungus on a
//!   stick is in a hand, a boat paddles with the keys, a minecart is moved by the server;
//! - **getting off** ([`Bot::dismount`]) is the sneak key: on 1.8.9, 1.12.2 and 26.x the
//!   sneak reaches the server in the steer / input packet and the server takes the player
//!   off; on 1.16.5 the client also gets off by itself one tick after the sneak;
//! - **the jump bar** ([`Bot::ride_jump`], [`Bot::dash`]) is the jump key held and released
//!   (horse family jump, camel and nautilus dash): the strength follows from the ticks held;
//! - **the stick boost** ([`Bot::boost`]) is a right click with the stick (an item use).
//!
//! Every helper needs [`ghast_client::Interests::ENTITIES`] for the entity's box and type.

use ghast_client::hands::PressOutcome;
use ghast_client::{Buttons, Controls, TickContext, Vec3};

use crate::look::step_toward;
use crate::{Bot, Error};

/// The entity interaction reach outside creative mode (blocks from the eyes to the box).
const REACH: f64 = 3.0;

/// Right clicks [`Bot::mount`] tries before it gives up.
const MOUNT_TRIES: u32 = 3;

/// Ticks [`Bot::mount`] waits for the server to seat the player after a click.
const SEAT_TICKS: u32 = 20;

/// Ticks [`Bot::dismount`] holds sneak before it gives up.
const DISMOUNT_TICKS: u32 = 60;

/// What the bot rides ([`Bot::vehicle`]).
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Ride {
    /// The vehicle's entity id.
    pub entity_id: i32,
    /// Its type's registry / minecraft-data name, as [`crate::EntityInfo::name`] has it
    /// (`"horse"`, `"pig"`, `"camel"`, `"oak_boat"`; 1.8.9 `"EntityHorse"`, `"Pig"`,
    /// `"Boat"`, `"MinecartRideable"`), `""` when the entity is not tracked.
    pub name: &'static str,
    /// Position (the client's own for a vehicle it moves, else where the client has it).
    pub pos: Vec3,
    /// Yaw.
    pub yaw: f32,
    /// Pitch.
    pub pitch: f32,
    /// On the ground.
    pub on_ground: bool,
    /// The client moves it from the bot's keys (a saddled horse, a camel, a pig or strider
    /// with its stick in a hand on 1.12.2+, a harnessed happy ghast, a saddled tame
    /// nautilus, a boat) rather than the server (1.8.9 living mounts, a minecart, a llama, a
    /// pig without the stick).
    pub controlled: bool,
    /// The bot's seat: its index in the vehicle's passenger list (0 steers), `None` when the
    /// list is not known.
    pub seat: Option<usize>,
}

/// Whether entities of this type can carry a player (any version's name; plugins can seat
/// players on anything, which [`Bot::mount`] does not try).
#[must_use]
pub(crate) fn rideable(name: &str) -> bool {
    let n = name.to_ascii_lowercase();
    matches!(
        n.as_str(),
        "horse"
            | "entityhorse"
            | "donkey"
            | "mule"
            | "skeleton_horse"
            | "zombie_horse"
            | "llama"
            | "trader_llama"
            | "pig"
            | "strider"
            | "camel"
            | "camel_husk"
            | "happy_ghast"
            | "nautilus"
            | "zombie_nautilus"
            | "boat"
            | "chest_boat"
            | "minecart"
            | "minecartrideable"
    ) || n.ends_with("_boat")
        || n.ends_with("_raft")
}

/// The bot's ride in this tick.
fn ride(ctx: &TickContext<'_>) -> Option<Ride> {
    let v = ctx.vehicle()?;
    let (name, seat) = match ctx.entities() {
        Some(es) => {
            let name = crate::find::entity_info(ctx, v.entity_id).map_or("", |e| e.name);
            let me = es.self_id().unwrap_or_else(|| ctx.entity_id());
            let seat = es
                .get(v.entity_id)
                .and_then(|e| e.passengers().iter().position(|&p| p == me));
            (name, seat)
        }
        None => ("", None),
    };
    Some(Ride {
        entity_id: v.entity_id,
        name,
        pos: v.pos,
        yaw: v.yaw,
        pitch: v.pitch,
        on_ground: v.on_ground,
        controlled: v.controlled,
        seat,
    })
}

/// The point of `b` nearest the eyes, pulled up to 0.4 inside per axis (a look at it lands
/// inside the box even after rounding to whole mouse counts; a box thinner than 0.8: its
/// middle), and the distance from the eyes to the box.
fn aim_point(b: [f64; 6], eyes: Vec3) -> (Vec3, f64) {
    let near = |lo: f64, hi: f64, v: f64| {
        let m = ((hi - lo) / 2.0).min(0.4);
        v.clamp(lo + m, hi - m)
    };
    let p = Vec3::new(
        near(b[0], b[3], eyes.x),
        near(b[1], b[4], eyes.y),
        near(b[2], b[5], eyes.z),
    );
    let d = Vec3::new(
        eyes.x.clamp(b[0], b[3]) - eyes.x,
        eyes.y.clamp(b[1], b[4]) - eyes.y,
        eyes.z.clamp(b[2], b[5]) - eyes.z,
    );
    (p, (d.x * d.x + d.y * d.y + d.z * d.z).sqrt())
}

/// One aiming tick of [`Bot::mount`]: `Ok(true)` once this tick's right press acts on the
/// entity (the press is made), `Ok(false)` while turning.
fn mount_step(ctx: &mut TickContext<'_>, id: i32) -> Result<bool, Error> {
    let es = ctx.entities().ok_or(Error::NoSuchEntity(id))?;
    let e = es
        .get(id)
        .filter(|e| e.is_alive())
        .ok_or(Error::NoSuchEntity(id))?;
    let b = e.bounding_box().ok_or(Error::NoSuchEntity(id))?;
    let eyes = ctx.eyes(ctx.pose());
    let (p, dist) = aim_point(b, eyes);
    if dist > REACH {
        return Err(Error::EntityOutOfReach(id));
    }
    let (yaw, pitch) = crate::yaw_pitch(eyes, p);
    let cur = ctx.pose().yaw;
    // A mount that moves (a nautilus bobbing, a horse wandering) keeps the look turning:
    // press as soon as both this tick's pick and the server's view are on it.
    step_toward(
        ctx,
        cur + ghast_client::rotation::wrap_degrees(yaw - cur),
        pitch,
    );
    let on = matches!(ctx.press_preview(ghast_client::hands::Button::Right),
        PressOutcome::Entity(h) if h.id == id);
    if on && ctx.target_entity().is_some_and(|t| t.id == id) {
        ctx.set_buttons(Buttons {
            left: false,
            right: true,
        });
        return Ok(true);
    }
    Ok(false)
}

/// Releases the movement keys when a helper ends early.
struct ReleaseKeys(Option<Bot>);

impl ReleaseKeys {
    fn disarm(mut self) {
        self.0 = None;
    }
}

impl Drop for ReleaseKeys {
    fn drop(&mut self) {
        if let Some(bot) = self.0.take() {
            bot.act(|ctx| {
                ctx.set_controls(Controls::NONE);
                ctx.set_buttons(Buttons::default());
            });
        }
    }
}

/// The jump key ticks (press included) that charge the bar to `strength`, and the bar they
/// give: vanilla's bar is 0.1 per held tick after the press, full (1.0) on the 10th, then
/// falls again (`0.8 + 0.2 / (ticks - 9)`).
fn jump_ticks(strength: f32) -> (u32, f32) {
    let c = (strength.clamp(0.0, 1.0) * 10.0).round().clamp(1.0, 10.0) as u32;
    let bar = if c < 10 { c as f32 * 0.1 } else { 1.0 };
    (c + 1, bar)
}

impl Bot {
    /// What the bot rides now (`None` on foot): the vehicle's id, type name, position,
    /// whether the client moves it and the bot's seat.
    ///
    /// ```no_run
    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
    /// if let Some(r) = bot.vehicle().await? {
    ///     println!("on a {} (seat {:?}), steering: {}", r.name, r.seat, r.controlled);
    /// }
    /// # Ok(()) }
    /// ```
    pub async fn vehicle(&self) -> Result<Option<Ride>, Error> {
        self.with(|ctx| ride(ctx)).await
    }

    /// Boards entity `id` the way a player does: releases the movement keys (a sneaking
    /// right click opens a horse's inventory instead), turns until the crosshair is on the
    /// entity (the server's view too), right-clicks it and waits until the server seats the
    /// player. Right-clicking with an item in the hand can use it on the mount instead
    /// (food feeds a horse, a saddle saddles it): board with an empty hand. On 26.x the client
    /// does not model yet which entity clicks a mob handles, so it also sends the held item's
    /// use after the click (and the off hand's click): with a carrot / fungus on a stick that
    /// use reaches the server after the seat and boosts the mount at once; take the stick
    /// after boarding.
    ///
    /// Fails with [`Error::NoSuchEntity`] (not tracked: needs
    /// [`ghast_client::Interests::ENTITIES`]), [`Error::NotRideable`] (a type that carries
    /// no player), [`Error::EntityOutOfReach`] (more than 3 blocks from the eyes) or
    /// [`Error::NotSeated`] (the server did not seat the player after three clicks: no
    /// saddle on a pig / strider / nautilus, no harness on a happy ghast, an untamed
    /// donkey on 26.x, the seats taken, or a protected region). An untamed horse seats the
    /// player and throws them off again a little later (taming), which this does not wait
    /// for.
    ///
    /// ```no_run
    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
    /// if let Some(h) = bot.nearest_entity(|e| e.name == "horse", 3.0).await? {
    ///     let ride = bot.mount(h.id).await?;
    ///     assert_eq!(ride.entity_id, h.id);
    /// }
    /// # Ok(()) }
    /// ```
    pub async fn mount(&self, id: i32) -> Result<Ride, Error> {
        let mark = self.mark();
        let first = self
            .with(move |ctx| -> Result<Option<Ride>, Error> {
                if let Some(r) = ride(ctx).filter(|r| r.entity_id == id) {
                    return Ok(Some(r));
                }
                let info = crate::find::entity_info(ctx, id).ok_or(Error::NoSuchEntity(id))?;
                if !info.alive {
                    return Err(Error::NoSuchEntity(id));
                }
                if !info.name.is_empty() && !rideable(info.name) {
                    return Err(Error::NotRideable(id));
                }
                ctx.set_controls(Controls::NONE);
                Ok(None)
            })
            .await??;
        if let Some(r) = first {
            return Ok(r);
        }
        let keys = ReleaseKeys(Some(self.clone()));
        for _ in 0..MOUNT_TRIES {
            let mut pressed = false;
            for _ in 0..60 {
                pressed = self.with(move |ctx| mount_step(ctx, id)).await??;
                self.next_tick().await;
                self.check(mark)?;
                if pressed {
                    break;
                }
            }
            if !pressed {
                return Err(Error::EntityOutOfReach(id));
            }
            self.act(|ctx| ctx.set_buttons(Buttons::default()));
            for _ in 0..SEAT_TICKS {
                if let Some(r) = self
                    .with(move |ctx| ride(ctx).filter(|r| r.entity_id == id))
                    .await?
                {
                    keys.disarm();
                    return Ok(r);
                }
                self.next_tick().await;
                self.check(mark)?;
            }
        }
        Err(Error::NotSeated(id))
    }

    /// Gets off: holds sneak until the client no longer rides, then releases every key (on
    /// 1.8.9, 1.12.2 and 26.x the server takes the player off when the sneak reaches it, on
    /// 1.16.5 the client also gets off one tick after the sneak). The server's placement of
    /// the player next to the vehicle (a teleport on most versions) does not interrupt it.
    /// Returns at once when not riding. Fails with [`Error::Timeout`] when the server keeps
    /// the player seated for 3 s (a plugin).
    ///
    /// ```no_run
    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
    /// bot.dismount().await?;
    /// # Ok(()) }
    /// ```
    pub async fn dismount(&self) -> Result<(), Error> {
        let mark = self.mark();
        let riding = self
            .with(|ctx| {
                let on = ctx.is_riding();
                if on {
                    ctx.set_buttons(Buttons::default());
                    ctx.set_controls(Controls {
                        sneak: true,
                        ..Controls::NONE
                    });
                }
                on
            })
            .await?;
        if !riding {
            return Ok(());
        }
        let _keys = ReleaseKeys(Some(self.clone()));
        for _ in 0..DISMOUNT_TICKS {
            self.next_tick().await;
            self.check_alive(mark)?;
            if !self.with(|ctx| ctx.is_riding()).await? {
                return Ok(());
            }
        }
        Err(Error::Timeout)
    }

    /// Charges the jump bar to `strength` (0 to 1, in steps of 0.1) and releases it: a horse
    /// family mount jumps (higher with more strength), a camel or nautilus dashes. The bar
    /// is the jump key: pressed, held one tick per 0.1 (full after 10 ticks, it falls again
    /// when held longer), released; the client sends the riding jump with the bar on the
    /// release. The other movement keys are kept (hold forward for a jump forward). Returns
    /// the bar released (vanilla's float, e.g. `0.3` for `0.25`).
    ///
    /// The jump only happens where vanilla's does: on a saddled horse family mount or a
    /// camel / nautilus the player controls, on the ground (a nautilus in water too), and
    /// not while its cooldown runs (horse 10 ticks, camel 55, nautilus 40 after the last
    /// jump: the bar does not charge then). Fails with [`Error::NotRiding`] on foot.
    ///
    /// ```no_run
    /// use ghast_client::Controls;
    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
    /// bot.set_controls(Controls { forward: true, ..Controls::NONE });
    /// bot.ride_jump(0.7).await?;
    /// # Ok(()) }
    /// ```
    pub async fn ride_jump(&self, strength: f32) -> Result<f32, Error> {
        let mark = self.mark();
        let (ticks, bar) = jump_ticks(strength);
        let set_jump = |jump: bool| {
            move |ctx: &mut TickContext<'_>| -> Result<(), Error> {
                if !ctx.is_riding() {
                    return Err(Error::NotRiding);
                }
                let mut c = ctx.controls();
                c.jump = jump;
                ctx.set_controls(c);
                Ok(())
            }
        };
        // A fresh press: the key up for one tick first.
        self.with(set_jump(false)).await??;
        self.next_tick().await;
        self.check(mark)?;
        for _ in 0..ticks {
            self.with(set_jump(true)).await??;
            self.next_tick().await;
            self.check(mark)?;
        }
        self.with(set_jump(false)).await??;
        self.next_tick().await;
        Ok(bar)
    }

    /// A full jump bar ([`Bot::ride_jump`] with 1.0): a camel's or nautilus's dash, a
    /// horse's highest jump.
    ///
    /// ```no_run
    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
    /// bot.dash().await?;
    /// bot.wait_ticks(55).await; // a camel's dash cooldown
    /// # Ok(()) }
    /// ```
    pub async fn dash(&self) -> Result<f32, Error> {
        self.ride_jump(1.0).await
    }

    /// Uses the carrot on a stick (pig) or warped fungus on a stick (strider, 1.16.5+) in a
    /// hand while riding: one right click, the item use that boosts the mount (the server
    /// starts the boost; 1.12.2+ clients then speed the pig up themselves, on 1.8.9 the
    /// server moves the pig). Keep the crosshair off the mount and other entities / blocks
    /// in reach (look ahead or up): a click on them would not use the item. Fails with
    /// [`Error::NotRiding`], [`Error::NoSuchItem`] (no stick in a hand) or
    /// [`Error::CannotUse`] (the click would act on an entity or a block).
    ///
    /// ```no_run
    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
    /// bot.equip("carrot_on_a_stick").await?;
    /// bot.boost().await?;
    /// # Ok(()) }
    /// ```
    pub async fn boost(&self) -> Result<(), Error> {
        let mark = self.mark();
        self.with(|ctx| -> Result<(), Error> {
            if !ctx.is_riding() {
                return Err(Error::NotRiding);
            }
            let v = ctx.version();
            let stick = |s: Option<&ghast_client::inventory::Stack>| {
                s.is_some_and(|s| {
                    matches!(
                        crate::item_name(v, s.id()),
                        "carrot_on_a_stick" | "warped_fungus_on_a_stick"
                    )
                })
            };
            if !stick(ctx.inventory().held()) && !stick(ctx.inventory().offhand()) {
                return Err(Error::NoSuchItem("carrot_on_a_stick".into()));
            }
            let press = ctx.press_preview(ghast_client::hands::Button::Right);
            if press != PressOutcome::Item {
                log::debug!("boost: a right press would act on {press:?}");
                return Err(Error::CannotUse);
            }
            ctx.set_buttons(Buttons {
                left: false,
                right: true,
            });
            Ok(())
        })
        .await??;
        self.next_tick().await;
        self.act(|ctx| ctx.set_buttons(Buttons::default()));
        self.check(mark)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn jump_bar_ticks() {
        assert_eq!(jump_ticks(0.0), (2, 0.1));
        assert_eq!(jump_ticks(0.25), (4, 0.3));
        assert_eq!(jump_ticks(0.7), (8, 7.0 * 0.1));
        assert_eq!(jump_ticks(1.0), (11, 1.0));
        assert_eq!(jump_ticks(5.0), (11, 1.0));
        // The value the riding jump action carries.
        assert_eq!((jump_ticks(0.7).1 * 100.0) as i32, 70);
    }

    #[test]
    fn rideable_names() {
        for n in [
            "horse",
            "EntityHorse",
            "Pig",
            "Boat",
            "oak_boat",
            "bamboo_raft",
            "oak_chest_boat",
            "MinecartRideable",
            "minecart",
            "camel",
            "happy_ghast",
            "nautilus",
            "strider",
        ] {
            assert!(rideable(n), "{n}");
        }
        for n in ["zombie", "chest_minecart", "player", "cow"] {
            assert!(!rideable(n), "{n}");
        }
    }

    #[test]
    fn aim_point_inside() {
        let b = [0.0, 0.0, 0.0, 1.0, 1.0, 1.0];
        let (p, d) = aim_point(b, Vec3::new(3.0, 0.5, 0.5));
        assert_eq!((p.x, p.y, p.z), (0.6, 0.5, 0.5));
        assert!((d - 2.0).abs() < 1e-12);
    }
}