ghast 0.5.4

Headless Minecraft Java Edition client / bot library (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3) with vanilla-exact behaviour: facade crate re-exporting the ghast-* crates
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
//! Live entity checks for the lab (26.1; boat and cart modes also 1.8.9, 1.12.2 and 1.16.5),
//! chosen with `GHAST_PROBE`:
//!
//! * `walk` (default): walks straight along +z for `--minutes` (through whatever stands there,
//!   e.g. a crowd of NoAI mobs and a boat; `--entities` turns on entity tracking, which the 26.1
//!   client needs to collide with and be pushed by them). Prints the end position.
//! * `horse`: finds the nearest horse, looks at it, sneak-right-clicks it (the tamed horse's
//!   inventory), moves its saddle into the player inventory and back. `PASS` when the screen
//!   opened and every click was confirmed as predicted.
//! * `villager`: finds the nearest villager, right-clicks it (the trade screen), selects trade 0
//!   and shift-takes the result. `PASS` when the screen opened, the trade was selected and the
//!   take was confirmed as predicted.
//! * `boat`: boards the nearest boat (a right click with `--entities`, or the server seats
//!   us), paddles straight / left / right, sneaks off (`lab/boats.sh`).
//! * `cart`: boards the nearest rideable minecart by a right click (`--entities`), pushes it
//!   forward, looks around for 60 s with jump and sprint presses while the server moves it,
//!   then sneaks off and stands a second (`lab/carts.sh`).
//!
//! ```text
//! GHAST_PROBE=villager cargo run -p ghast --release --example entity_probe -- \
//!     --host 127.0.0.1 --port 25626 --username GhastBot11 --version 26.1 --minutes 1
//! ```
//! `lab/entities.sh` sets the scene and runs every mode.

mod support;

use std::time::{Duration, Instant};

use ghast::inventory::{Click, ClickError, ClickOutcome};
use ghast::{Behavior, Buttons, ClickRefused, Controls, Interests, TickContext, Vec3};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Mode {
    Walk,
    Horse,
    Villager,
    Boat,
    Cart,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Step {
    Settle,
    Aim,
    Use,
    WaitWindow,
    Trade,
    Clicks,
    Close,
    Done,
}

struct Probe {
    mode: Mode,
    entities: bool,
    step: Step,
    wait: u32,
    target: Option<i32>,
    opened: bool,
    awaiting: bool,
    clicks: Vec<Click>,
    sent: u32,
    accepted: u32,
    failures: Vec<String>,
    started: Instant,
    limit: Duration,
    reported: bool,
    /// Boat mode: ticks since boarding (`None`: not on yet), whether it was ever on.
    ride_ticks: Option<u32>,
    rode: bool,
    /// Ticks on foot after a dismount.
    off_ticks: u32,
    /// Cart mode: the yaw the look-around swings about.
    cart_yaw: Option<f32>,
    /// Walk direction (`GHAST_YAW`, default 0 = +z).
    yaw: f32,
}

impl Probe {
    fn finish(&mut self, ctx: &mut TickContext<'_>) {
        if self.reported {
            return;
        }
        self.reported = true;
        let p = ctx.pose().pos;
        println!("end position {:.4} {:.4} {:.4}", p.x, p.y, p.z);
        if self.mode != Mode::Walk {
            println!(
                "screen opened {}, clicks sent {}, accepted {}, failures {}",
                self.opened,
                self.sent,
                self.accepted,
                self.failures.len()
            );
            for f in &self.failures {
                println!("  FAIL {f}");
            }
            if self.ok() {
                println!("PASS");
            }
        }
        ctx.disconnect("probe done");
    }

    fn ok(&self) -> bool {
        if matches!(self.mode, Mode::Boat | Mode::Cart) {
            return self.rode && self.failures.is_empty();
        }
        self.mode == Mode::Walk
            || (self.opened
                && self.failures.is_empty()
                && self.sent > 0
                && self.sent == self.accepted)
    }

    /// The nearest tracked entity of a type, with its box.
    fn find(ctx: &TickContext<'_>, name: &str) -> Option<(i32, [f64; 6])> {
        let ents = ctx.entities()?;
        let eyes = ctx.eyes(ctx.pose());
        ents.iter()
            .filter(|e| type_name(ctx, e) == Some(name))
            .filter_map(|e| Some((e.id(), e.bounding_box()?)))
            .min_by(|a, b| {
                let d = |b: &[f64; 6]| {
                    let c = [
                        (b[0] + b[3]) / 2.0,
                        (b[1] + b[4]) / 2.0,
                        (b[2] + b[5]) / 2.0,
                    ];
                    (c[0] - eyes.x).powi(2) + (c[1] - eyes.y).powi(2) + (c[2] - eyes.z).powi(2)
                };
                d(&a.1).total_cmp(&d(&b.1))
            })
    }
}

impl Probe {
    /// Boat mode: board (a right click on the nearest boat with entity tracking; else wait for
    /// the server to seat us, e.g. `ride <bot> mount <boat>`), paddle a course (straight, a
    /// left turn, a right turn, straight on), then hold sneak until the server dismounts us.
    fn boat(&mut self, ctx: &mut TickContext<'_>) {
        let riding = ctx.is_riding();
        if riding && self.ride_ticks.is_none() {
            self.ride_ticks = Some(0);
            self.rode = true;
            println!("boarded: {:?}", ctx.vehicle());
        }
        let Some(t) = self.ride_ticks else {
            // Not on yet: with tracking, look at the nearest boat and right-click it.
            if self.wait < 40 {
                self.wait += 1;
                return;
            }
            if let Some((id, b)) = Self::find_boat(ctx, self.mode == Mode::Cart) {
                let eyes = ctx.eyes(ctx.pose());
                // The box point nearest the eyes, pulled 0.1 inside (the pick range is 3).
                let near = |lo: f64, hi: f64, v: f64| v.clamp(lo + 0.1, hi - 0.1);
                let c = Vec3::new(
                    near(b[0], b[3], eyes.x),
                    near(b[1], b[4], eyes.y),
                    near(b[2], b[5], eyes.z),
                );
                let (dx, dy, dz) = (c.x - eyes.x, c.y - eyes.y, c.z - eyes.z);
                let yaw = (-dx).atan2(dz).to_degrees() as f32;
                let mut pitch = -(dy.atan2((dx * dx + dz * dz).sqrt())).to_degrees() as f32;
                // A teleport answered after our aim tick (e.g. the scene's /tp racing Paper's
                // "moved too quickly" re-teleports) leaves the server with the teleport's
                // rotation while ours is back on the aim: vanilla sends no look packet then
                // (its last reported rotation is untouched), and the server's crosshair stays
                // off the boat for good. Aim half a degree lower until the server has ours.
                let (sent, pose) = (*ctx.sent(), ctx.pose());
                if sent.yaw != pose.yaw || sent.pitch != pose.pitch {
                    pitch += 0.5;
                }
                let cur = pose.yaw;
                ctx.set_aim(cur + ghast::rotation::wrap_degrees(yaw - cur), pitch);
                let on = ctx.target_entity().is_some_and(|e| e.id == id);
                ctx.set_buttons(Buttons {
                    left: false,
                    right: on && ctx.tick().is_multiple_of(10),
                });
            }
            return;
        };
        ctx.set_buttons(Buttons::default());
        if !riding {
            if self.off_ticks == 0 {
                println!("dismounted after {t} ticks at {:?}", ctx.pose().pos);
            }
            // A second on foot (the first position packets from the seat), then done.
            self.off_ticks += 1;
            ctx.set_controls(Controls::NONE);
            if self.off_ticks > 20 {
                self.finish(ctx);
            }
            return;
        }
        self.ride_ticks = Some(t + 1);
        if self.mode == Mode::Cart {
            self.cart(ctx, t);
            return;
        }
        let (forward, left, right, sneak) = match t {
            0..20 => (false, false, false, false),
            20..80 => (true, false, false, false),
            80..110 => (true, true, false, false),
            110..150 => (true, false, true, false),
            150..230 => (true, false, false, false),
            230..260 => (false, false, false, false),
            _ => (false, false, false, true),
        };
        ctx.set_controls(Controls {
            forward,
            left,
            right,
            sneak,
            ..Controls::NONE
        });
        if t % 20 == 0
            && let Some(v) = ctx.vehicle()
        {
            // The tracker's position of it: what the server last sent (1.8 drift check).
            let tracked = ctx
                .entities()
                .and_then(|es| es.get(v.entity_id))
                .map(ghast::entity::Entity::position);
            log::info!(
                "vehicle at {:.3} {:.3} {:.3} yaw {:.1} ground {} tracked {:?}",
                v.pos.x,
                v.pos.y,
                v.pos.z,
                v.yaw,
                v.on_ground,
                tracked
            );
        }
        if t > 400 {
            self.failures
                .push("not dismounted after 140 sneaking ticks".into());
            self.finish(ctx);
        }
    }

    /// The first tracked boat (`cart`: rideable minecart).
    /// Cart mode, riding: a push forward, then 60 s of looking around (whole mouse steps) with
    /// jump presses and a sprint press while the server moves the cart, then sneak until the
    /// server takes us off.
    fn cart(&mut self, ctx: &mut TickContext<'_>, t: u32) {
        // Face east (+x) for the push: the scene's cart stands on an east-west rail.
        let base = *self.cart_yaw.get_or_insert(-90.0);
        let look = (60..1200).contains(&t);
        if t < 60 {
            ctx.set_aim(base, 10.0);
        } else if look {
            let f = t as f32;
            ctx.set_aim(
                base + 70.0 * (f / 40.0).sin(),
                15.0 + 25.0 * (f / 27.0).sin(),
            );
        }
        ctx.set_controls(Controls {
            forward: (20..60).contains(&t),
            jump: look && t % 100 < 4,
            sprint: (300..340).contains(&t),
            sneak: t >= 1200,
            ..Controls::NONE
        });
        if t.is_multiple_of(20)
            && let Some(v) = ctx.vehicle()
        {
            let tracked = ctx
                .entities()
                .and_then(|es| es.get(v.entity_id))
                .map(ghast::entity::Entity::position);
            log::info!(
                "cart at {:.3} {:.3} {:.3} yaw {:.1}; seat sent {:.3} {:.3} {:.3}; tracked {:?}",
                v.pos.x,
                v.pos.y,
                v.pos.z,
                v.yaw,
                ctx.sent().pos.x,
                ctx.sent().pos.y,
                ctx.sent().pos.z,
                tracked
            );
        }
        if t > 1400 {
            self.failures
                .push("not dismounted after 200 sneaking ticks".into());
            self.finish(ctx);
        }
    }

    fn find_boat(ctx: &TickContext<'_>, cart: bool) -> Option<(i32, [f64; 6])> {
        let ents = ctx.entities()?;
        ents.iter()
            .filter(|e| {
                type_name(ctx, e).is_some_and(|t| {
                    if cart {
                        t == "minecart"
                    } else {
                        t == "boat" || t.ends_with("_boat") || t.ends_with("_raft")
                    }
                })
            })
            .filter_map(|e| Some((e.id(), e.bounding_box()?)))
            .next()
    }
}

impl Behavior for Probe {
    fn name(&self) -> &str {
        "entity-probe"
    }

    fn interests(&self) -> Interests {
        if self.entities || matches!(self.mode, Mode::Horse | Mode::Villager) {
            // The tab list gives other players' scoreboard names (their teams).
            Interests::ENTITIES | Interests::PLAYER_LIST | Interests::CHAT
        } else {
            Interests::CHAT
        }
    }

    fn tick(&mut self, ctx: &mut TickContext<'_>) {
        for m in &ctx.events().chat {
            let line = m.plain();
            if line.contains("Grim") || line.contains("failed") {
                log::warn!("ALERT {line}");
            }
        }
        if ctx.is_dead() {
            // A bot left dead by an earlier run (the respawn screen): back to the spawn.
            ctx.respawn();
            return;
        }
        if self.started.elapsed() >= self.limit {
            if self.mode != Mode::Walk {
                self.failures.push(format!("timed out at {:?}", self.step));
            }
            self.finish(ctx);
            return;
        }
        let ev = ctx.events().inventory.clone();
        for c in &ev.clicks {
            self.awaiting = false;
            match c.outcome {
                ClickOutcome::Accepted => self.accepted += 1,
                o => self.failures.push(format!(
                    "action {} in window {}: {o:?}",
                    c.action, c.window_id
                )),
            }
        }
        if ev.opened.is_some() {
            self.opened = true;
        }
        if matches!(self.mode, Mode::Boat | Mode::Cart) {
            self.boat(ctx);
            return;
        }
        if self.mode == Mode::Walk {
            if self.wait < 40 {
                self.wait += 1;
                return;
            }
            ctx.set_aim(self.yaw, 0.0);
            ctx.set_controls(Controls {
                forward: true,
                ..Controls::NONE
            });
            if ctx.tick().is_multiple_of(20) {
                let p = ctx.pose().pos;
                log::info!("at {:.3} {:.3} {:.3}", p.x, p.y, p.z);
            }
            return;
        }
        if self.wait > 0 {
            self.wait -= 1;
            return;
        }
        match self.step {
            Step::Settle => {
                self.wait = 40;
                self.step = Step::Aim;
            }
            Step::Aim => {
                let name = if self.mode == Mode::Horse {
                    "horse"
                } else {
                    "villager"
                };
                let Some((id, b)) = Self::find(ctx, name) else {
                    return;
                };
                self.target = Some(id);
                let eyes = ctx.eyes(ctx.pose());
                let c = Vec3::new(
                    (b[0] + b[3]) / 2.0,
                    (b[1] + b[4]) / 2.0,
                    (b[2] + b[5]) / 2.0,
                );
                let (dx, dy, dz) = (c.x - eyes.x, c.y - eyes.y, c.z - eyes.z);
                let yaw = (-dx).atan2(dz).to_degrees() as f32;
                let mut pitch = -(dy.atan2((dx * dx + dz * dz).sqrt())).to_degrees() as f32;
                // As in boat mode: a teleport answered after the aim tick leaves the server
                // with its rotation and no look packet follows; aim a little off until the
                // server has ours.
                let (sent, pose) = (*ctx.sent(), ctx.pose());
                if sent.yaw != pose.yaw || sent.pitch != pose.pitch {
                    pitch += 0.5;
                }
                let cur = pose.yaw;
                ctx.set_aim(cur + ghast::rotation::wrap_degrees(yaw - cur), pitch);
                // A tamed horse opens its inventory on a sneaking right click.
                ctx.set_controls(Controls {
                    sneak: self.mode == Mode::Horse,
                    ..Controls::NONE
                });
                if ctx.target_entity().is_some_and(|e| e.id == id) {
                    self.wait = 3;
                    self.step = Step::Use;
                }
            }
            Step::Use => {
                if ctx
                    .target_entity()
                    .is_none_or(|e| Some(e.id) != self.target)
                {
                    self.step = Step::Aim;
                    return;
                }
                ctx.set_buttons(Buttons {
                    left: false,
                    right: true,
                });
                self.step = Step::WaitWindow;
            }
            Step::WaitWindow => {
                ctx.set_buttons(Buttons::default());
                ctx.set_controls(Controls::NONE);
                if self.opened && !ctx.inventory().resyncing() {
                    let n = ctx.inventory().container_len();
                    println!(
                        "screen open: window {:?}, {n} container slots",
                        ctx.open_window()
                    );
                    self.wait = 10;
                    self.step = if self.mode == Mode::Villager {
                        Step::Trade
                    } else {
                        // Saddle (slot 0) into the inventory, then back (first free slot of the
                        // main inventory after the container: shift-click moves it there).
                        self.clicks = vec![Click::QuickMove {
                            slot: 0,
                            right: false,
                        }];
                        Step::Clicks
                    };
                }
            }
            Step::Trade => match ctx.select_trade(0) {
                Ok(()) => {
                    println!("trade 0 selected");
                    self.wait = 10;
                    self.clicks = vec![Click::QuickMove {
                        slot: 2,
                        right: false,
                    }];
                    self.step = Step::Clicks;
                }
                Err(ClickRefused::Turning) => {}
                Err(e) => {
                    self.failures.push(format!("select_trade refused: {e}"));
                    self.step = Step::Close;
                }
            },
            Step::Clicks => {
                if self.awaiting {
                    return;
                }
                if self.clicks.is_empty() {
                    if self.mode == Mode::Horse && self.sent == 1 {
                        // Back: find the saddle in the player part and shift-click it.
                        let inv = ctx.inventory();
                        let n = inv.container_len();
                        let id = ghast::inventory::modern::item_id(inv.version(), "saddle");
                        let saddle = (n..inv.slot_count())
                            .find(|&i| inv.slot(i).is_some_and(|s| Some(s.id()) == id));
                        match saddle {
                            Some(i) => self.clicks.push(Click::QuickMove {
                                slot: i as i16,
                                right: false,
                            }),
                            None => self.failures.push("saddle not in the inventory".into()),
                        }
                        if !self.clicks.is_empty() {
                            return;
                        }
                    }
                    self.wait = 10;
                    self.step = Step::Close;
                    return;
                }
                let c = self.clicks[0];
                match ctx.click(c) {
                    Ok(_) => {
                        println!("  click {c:?}");
                        self.clicks.remove(0);
                        self.sent += 1;
                        self.awaiting = true;
                    }
                    Err(
                        ClickRefused::Turning
                        | ClickRefused::Inventory(
                            ClickError::Pending | ClickError::SameTick | ClickError::Resyncing,
                        ),
                    ) => {}
                    Err(e) => {
                        self.failures.push(format!("{c:?} refused: {e}"));
                        self.clicks.clear();
                    }
                }
            }
            Step::Close => {
                if ctx.close_window().is_ok() {
                    self.wait = 20;
                    self.step = Step::Done;
                }
            }
            Step::Done => self.finish(ctx),
        }
    }
}

fn main() {
    let opts = support::Options::parse();
    support::init_logger(opts.verbose);
    let mode = match std::env::var("GHAST_PROBE").as_deref() {
        Ok("horse") => Mode::Horse,
        Ok("villager") => Mode::Villager,
        Ok("boat") => Mode::Boat,
        Ok("cart") => Mode::Cart,
        Ok("walk") | Err(_) => Mode::Walk,
        Ok(other) => {
            eprintln!("GHAST_PROBE: walk | horse | villager | boat | cart, not {other}");
            std::process::exit(2);
        }
    };
    let limit = Duration::from_secs_f64(opts.minutes.unwrap_or(1.0) * 60.0);
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .expect("tokio runtime");
    rt.block_on(async {
        let client = match opts.client() {
            Ok(c) => c,
            Err(e) => {
                log::error!("{e}");
                std::process::exit(2);
            }
        };
        let mut probe = Probe {
            mode,
            entities: opts.entities,
            step: Step::Settle,
            wait: 0,
            target: None,
            opened: false,
            awaiting: false,
            clicks: Vec::new(),
            sent: 0,
            accepted: 0,
            failures: Vec::new(),
            started: Instant::now(),
            limit,
            reported: false,
            ride_ticks: None,
            rode: false,
            off_ticks: 0,
            cart_yaw: None,
            yaw: std::env::var("GHAST_YAW")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(0.0),
        };
        let end = client.run(&mut probe).await;
        log::info!("session ended: {end:?}");
        std::process::exit(if probe.ok() { 0 } else { 1 });
    });
}

/// The registry name of a tracked entity's type in the session's version.
fn type_name(ctx: &TickContext<'_>, e: &ghast::entity::Entity) -> Option<&'static str> {
    match ctx.version() {
        #[cfg(feature = "v26_2")]
        ghast::GameVersion::V26_2 => ghast::entity::v26_2::entity_type(e).map(|t| t.name),
        #[cfg(feature = "v26_3")]
        ghast::GameVersion::V26_3 => ghast::entity::v26_3::entity_type(e).map(|t| t.name),
        // 1.8.9 / 1.12.2 (boat mode): object type 1 is the boat.
        #[cfg(any(feature = "v1_8", feature = "v1_12_2"))]
        ghast::GameVersion::V1_8_9 | ghast::GameVersion::V1_12_2 => match e.entity_type() {
            ghast::entity::EntityType::LegacyObject(1) => Some("boat"),
            // Object type 10 with data 0: the rideable minecart (the probe only rides that one).
            ghast::entity::EntityType::LegacyObject(10) => Some("minecart"),
            _ => None,
        },
        // 1.16.5 (boat mode): the registry id names the type.
        #[cfg(feature = "v1_16_5")]
        ghast::GameVersion::V1_16_5 => match e.entity_type() {
            ghast::entity::EntityType::Registry(id) => {
                ghast::data::v1_16_5::entity(ghast::data::EntityKind::Mob, id).map(|t| t.name)
            }
            _ => None,
        },
        _ => ghast::entity::v26_1::entity_type(e).map(|t| t.name),
    }
}