ghast_ext/goto.rs
1//! Walking along planned paths (feature `pathfinder`).
2
3use ghast_client::{Buttons, Controls, Vec3};
4use ghast_pathfinder::{
5 Config, FollowConfig, FollowError, FollowStatus, Follower, Goal, Pathfinder,
6};
7
8use crate::{Bot, Error};
9
10/// State of [`Bot::follow_path`] between ticks.
11struct Chase {
12 follower: Follower,
13 /// The entity's feet block the current plan goes to.
14 target: Option<[i32; 3]>,
15 /// The entity's feet block when following last failed (out of reach): wait until it moves.
16 failed_at: Option<[i32; 3]>,
17}
18
19/// Feet block of a position.
20fn feet_block(p: Vec3) -> [i32; 3] {
21 Pathfinder::start_block([p.x, p.y, p.z])
22}
23
24/// Largest horizontal or vertical block distance.
25fn blocks_apart(a: [i32; 3], b: [i32; 3]) -> i32 {
26 (a[0] - b[0])
27 .abs()
28 .max((a[1] - b[1]).abs())
29 .max((a[2] - b[2]).abs())
30}
31
32/// Releases the keys and buttons when a walk ends early.
33struct Release(Option<Bot>);
34
35impl Drop for Release {
36 fn drop(&mut self) {
37 if let Some(bot) = self.0.take() {
38 bot.act(|ctx| {
39 ctx.set_controls(Controls::NONE);
40 if ctx.buttons().left {
41 ctx.set_buttons(Buttons::default());
42 }
43 });
44 }
45 }
46}
47
48impl Bot {
49 /// Walks to `goal` along a path planned by [`ghast_pathfinder`] with the default
50 /// [`Config`] (sprinting, gap jumps, swimming, ladders; no digging or placing) and
51 /// followed by its [`Follower`]: every plan is first run through the vanilla-exact
52 /// physics, moves the simulation fails are planned around, and the follower replans when
53 /// it gets stuck or leaves the path.
54 ///
55 /// Fails with [`Error::NoPath`] when no path exists (or the start is not loaded),
56 /// [`Error::Stuck`] after too many replans, and the usual interrupts (teleport / death,
57 /// see [`crate::Ext::interrupt_on_teleport`]). Unloaded terrain is never treated as air:
58 /// a goal beyond it is approached through partial paths. Dropping the future releases
59 /// the keys.
60 ///
61 /// A long plan is spread over several ticks (by default at most 2000 nodes and 5 ms of
62 /// planning per tick, see [`FollowConfig::budget`]); the bot stands still meanwhile and
63 /// the client keeps sending its movement packet every tick.
64 ///
65 /// ```no_run
66 /// use ghast_ext::pathfinder::Goal;
67 /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
68 /// bot.goto(Goal::Block([20, 64, -5])).await?;
69 /// bot.goto(Goal::Near { pos: [0, 64, 0], radius: 3.0 }).await?;
70 /// # Ok(()) }
71 /// ```
72 pub async fn goto(&self, goal: Goal) -> Result<(), Error> {
73 let follower = Follower::new(Pathfinder::new(Config::default()), FollowConfig::default());
74 self.goto_with(follower, goal).await
75 }
76
77 /// [`Bot::goto`] with a configured [`Follower`] (planner options such as digging or
78 /// placing, controller options, replan budget).
79 ///
80 /// ```no_run
81 /// use ghast_ext::pathfinder::{Config, DigCost, FollowConfig, Follower, Goal, Pathfinder};
82 /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
83 /// let pf = Pathfinder::new(Config::default().with_dig(Some(DigCost::default())));
84 /// let follower = Follower::new(pf, FollowConfig::default());
85 /// bot.goto_with(follower, Goal::Xz { x: 100, z: 40 }).await?;
86 /// # Ok(()) }
87 /// ```
88 pub async fn goto_with(&self, mut follower: Follower, goal: Goal) -> Result<(), Error> {
89 let mark = self.mark();
90 let mut release = Release(Some(self.clone()));
91 follower.goto(goal);
92 loop {
93 let (f, status) = self
94 .with(move |ctx| {
95 let mut f = follower;
96 let s = f.tick(ctx);
97 (f, s)
98 })
99 .await?;
100 follower = f;
101 match status {
102 FollowStatus::Arrived => {
103 release.0 = None;
104 return Ok(());
105 }
106 FollowStatus::Failed(FollowError::Plan(e)) => {
107 log::debug!("goto: {e}");
108 return Err(Error::NoPath);
109 }
110 FollowStatus::Failed(_) => return Err(Error::Stuck),
111 _ => {}
112 }
113 self.next_tick().await;
114 self.check(mark)?;
115 }
116 }
117
118 /// Follows entity `id` along planned paths (the planner and follower of [`Bot::goto`]),
119 /// staying within `range` blocks of it: through mazes, over gaps, around walls (unlike
120 /// [`Bot::follow`], which walks in a straight line). The bot plans again when the entity
121 /// has moved more than `range` (at least 2) blocks from where the current path goes, at
122 /// most one plan at a time; within range it stands and looks at the entity. When the
123 /// entity is out of reach (flying, across a gap too wide), the bot walks to the reachable
124 /// block closest to it and waits there until the entity moves.
125 ///
126 /// Runs until the entity is gone ([`Error::NoSuchEntity`]) or the task is cancelled (e.g.
127 /// with [`Bot::timeout`] or [`crate::JoinHandle::abort`]). Needs
128 /// [`ghast_client::Interests::ENTITIES`]. Dropping the future releases the keys.
129 ///
130 /// ```no_run
131 /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
132 /// if let Some(p) = bot.player("Steve").await? {
133 /// let _ = bot.timeout(20 * 60, bot.follow_path(p.id, 2.0)).await; // one minute
134 /// }
135 /// # Ok(()) }
136 /// ```
137 pub async fn follow_path(&self, id: i32, range: f64) -> Result<(), Error> {
138 let follower = Follower::new(Pathfinder::new(Config::default()), FollowConfig::default());
139 self.follow_path_with(follower, id, range).await
140 }
141
142 /// [`Bot::follow_path`] with a configured [`Follower`].
143 pub async fn follow_path_with(
144 &self,
145 follower: Follower,
146 id: i32,
147 range: f64,
148 ) -> Result<(), Error> {
149 let mark = self.mark();
150 let _release = Release(Some(self.clone()));
151 let mut chase = Chase {
152 follower,
153 target: None,
154 failed_at: None,
155 };
156 let retarget = (range.ceil() as i32).max(2);
157 loop {
158 chase = self
159 .with(move |ctx| -> Result<Chase, Error> {
160 let mut c = chase;
161 let e = crate::find::entity_info(ctx, id).ok_or(Error::NoSuchEntity(id))?;
162 let goal_block = feet_block(e.pos);
163 let me = ctx.pose().pos;
164 let (dx, dy, dz) = (me.x - e.pos.x, me.y - e.pos.y, me.z - e.pos.z);
165 // Within range, or on a block the goal accepts (block centres).
166 let goal = Goal::Near {
167 pos: goal_block,
168 radius: range,
169 };
170 let near = (dx * dx + dy * dy + dz * dz).sqrt() <= range
171 || goal.is_reached(feet_block(me));
172 let moving = c.follower.status() == FollowStatus::Moving;
173 if near && !moving {
174 // Within range: watch it.
175 let (yaw, pitch) = crate::yaw_pitch(
176 ctx.eyes(ctx.pose()),
177 Vec3::new(e.pos.x, e.pos.y + 1.6, e.pos.z),
178 );
179 ctx.set_aim(yaw, pitch);
180 c.target = None;
181 return Ok(c);
182 }
183 let stale = c
184 .target
185 .is_none_or(|t| blocks_apart(t, goal_block) > retarget);
186 let waiting = c
187 .failed_at
188 .is_some_and(|f| blocks_apart(f, goal_block) <= 1);
189 if stale
190 && !waiting
191 && (!c.follower.is_planning() || c.target.is_none())
192 && (!near || c.target.is_none())
193 {
194 c.follower.goto(goal);
195 c.target = Some(goal_block);
196 c.failed_at = None;
197 }
198 if c.follower.status() == FollowStatus::Moving {
199 match c.follower.tick(ctx) {
200 FollowStatus::Failed(err) => {
201 log::debug!("follow_path: {err}");
202 c.failed_at = Some(goal_block);
203 c.target = None;
204 }
205 FollowStatus::Arrived => c.target = None,
206 _ => {}
207 }
208 }
209 Ok(c)
210 })
211 .await??;
212 self.next_tick().await;
213 self.check(mark)?;
214 }
215 }
216}