Skip to main content

ghast_pathfinder/
follower.rs

1//! Following a path from a `ghast_client::Behavior`: plan, follow, replan.
2
3use std::collections::HashSet;
4use std::time::{Duration, Instant};
5
6use ghast_client::{BlockPos, Buttons, Controls, Face, TickContext};
7use ghast_physics::Keys;
8
9use crate::Version;
10use crate::control::{Controller, ControllerConfig, Progress};
11use crate::goal::Goal;
12use crate::physics::Observation;
13use crate::plan::{Budget, Path, Pathfinder, PlanError, Search};
14use crate::sim::{SimOutcome, Simulation};
15use crate::world::BlockSource;
16
17/// What the follower reads and does in one tick. Implemented for ghast-client's
18/// [`TickContext`]; the tests drive the same follower with a simulated player.
19pub(crate) trait Io {
20    /// The world type.
21    type World<'w>: BlockSource + ?Sized
22    where
23        Self: 'w;
24    /// The world as the client knows it.
25    fn world(&self) -> &Self::World<'_>;
26    /// The planner's version (`None`: not supported by the planner, e.g. 26.1).
27    fn version(&self) -> Option<Version>;
28    /// The player.
29    fn observation(&self) -> Observation;
30    /// The server moved the player this tick (teleport, respawn).
31    fn moved_by_server(&self) -> bool;
32    /// Dead.
33    fn is_dead(&self) -> bool;
34    /// Aim target.
35    fn set_aim(&mut self, yaw: f32, pitch: f32);
36    /// The look this tick's movement uses (after turning toward the aim).
37    fn planned_look(&self) -> (f32, f32);
38    /// Movement keys from now on.
39    fn set_keys(&mut self, keys: Keys);
40    /// The left button is held.
41    fn left_button(&self) -> bool;
42    /// Holds or releases the left button (and the right one).
43    fn set_left_button(&mut self, on: bool);
44    /// The crosshair is on this block (as the server judges it).
45    fn targets(&self, block: [i32; 3]) -> bool;
46    /// Right-clicks the face of `against` toward `dir` (a unit offset) with the held item if
47    /// the crosshair is on it; `true` when the place was sent.
48    fn place_against(&mut self, against: [i32; 3], dir: [i32; 3]) -> bool;
49    /// Right-clicks `block` (opens a door or gate) if the crosshair is on it; `true` when the
50    /// click was sent.
51    fn activate(&mut self, block: [i32; 3]) -> bool;
52    /// 26.1: the live client player (attributes, effects, abilities, level).
53    #[cfg(ghast_modern)]
54    fn modern_player(&self) -> Option<&ghast_physics::modern::PlayerState> {
55        None
56    }
57    /// The build height `(min_y, height)` of the player's dimension, when known.
58    fn build_height(&self) -> Option<(i32, i32)> {
59        #[cfg(ghast_modern)]
60        if let Some(p) = self.modern_player() {
61            return Some((p.level.min_y, p.level.height));
62        }
63        None
64    }
65}
66
67/// The client's world with the dimension's build height (unknown below it).
68struct Height<'a, W: ?Sized> {
69    world: &'a W,
70    height: Option<(i32, i32)>,
71}
72
73impl<W: BlockSource + ?Sized> BlockSource for Height<'_, W> {
74    #[inline]
75    fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32> {
76        if let Some((lo, h)) = self.height
77            && (y < lo || y >= lo + h)
78        {
79            return None;
80        }
81        self.world.raw_block(x, y, z)
82    }
83
84    #[inline]
85    fn is_column_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool {
86        self.world.is_column_loaded(chunk_x, chunk_z)
87    }
88
89    fn build_height(&self) -> Option<(i32, i32)> {
90        self.height.or_else(|| self.world.build_height())
91    }
92}
93
94/// [`Height`] over an [`Io`]'s world.
95fn world_of<I: Io + ?Sized>(ctx: &I) -> Height<'_, I::World<'_>> {
96    Height {
97        world: ctx.world(),
98        height: ctx.build_height(),
99    }
100}
101
102impl Io for TickContext<'_> {
103    type World<'w>
104        = dyn ghast_client::WorldView + 'w
105    where
106        Self: 'w;
107
108    fn world(&self) -> &Self::World<'_> {
109        TickContext::world(self)
110    }
111
112    fn version(&self) -> Option<Version> {
113        Version::from_game(TickContext::version(self))
114    }
115
116    fn observation(&self) -> Observation {
117        let pose = *self.pose();
118        Observation {
119            pos: [pose.pos.x, pose.pos.y, pose.pos.z],
120            vel: [pose.motion.x, pose.motion.y, pose.motion.z],
121            on_ground: pose.on_ground,
122            yaw: pose.yaw,
123            pitch: pose.pitch,
124            sprinting: pose.sprinting,
125            food: self.health().food,
126        }
127    }
128
129    fn moved_by_server(&self) -> bool {
130        !self.events().teleports.is_empty() || self.events().respawned
131    }
132
133    fn is_dead(&self) -> bool {
134        TickContext::is_dead(self)
135    }
136
137    fn set_aim(&mut self, yaw: f32, pitch: f32) {
138        TickContext::set_aim(self, yaw, pitch);
139    }
140
141    fn planned_look(&self) -> (f32, f32) {
142        TickContext::planned_look(self)
143    }
144
145    fn set_keys(&mut self, k: Keys) {
146        self.set_controls(Controls {
147            forward: k.forward,
148            back: k.back,
149            left: k.left,
150            right: k.right,
151            jump: k.jump,
152            sneak: k.sneak,
153            sprint: k.sprint,
154        });
155    }
156
157    fn left_button(&self) -> bool {
158        self.buttons().left
159    }
160
161    fn set_left_button(&mut self, on: bool) {
162        self.set_buttons(Buttons {
163            left: on,
164            right: false,
165        });
166    }
167
168    fn targets(&self, block: [i32; 3]) -> bool {
169        let pos = BlockPos::new(block[0], block[1], block[2]);
170        self.target().is_some_and(|t| t.pos == pos)
171    }
172
173    fn place_against(&mut self, against: [i32; 3], dir: [i32; 3]) -> bool {
174        let face = match dir {
175            [0, -1, 0] => Face::Down,
176            [0, 0, -1] => Face::North,
177            [0, 0, 1] => Face::South,
178            [-1, 0, 0] => Face::West,
179            [1, 0, 0] => Face::East,
180            _ => Face::Up,
181        };
182        let against = BlockPos::new(against[0], against[1], against[2]);
183        match self.target().filter(|t| t.pos == against && t.face == face) {
184            Some(hit) => self.place(against, face, hit.hit),
185            None => false,
186        }
187    }
188
189    fn activate(&mut self, block: [i32; 3]) -> bool {
190        let pos = BlockPos::new(block[0], block[1], block[2]);
191        match self.target().filter(|t| t.pos == pos) {
192            Some(hit) => self.place(pos, hit.face, hit.hit),
193            None => false,
194        }
195    }
196    #[cfg(ghast_modern)]
197    fn modern_player(&self) -> Option<&ghast_physics::modern::PlayerState> {
198        TickContext::modern_player(self)
199    }
200}
201
202/// Options of the [`Follower`]. Build with [`FollowConfig::default`] and the `with_*`
203/// methods.
204#[derive(Clone, Debug, PartialEq)]
205#[non_exhaustive]
206pub struct FollowConfig {
207    /// The controller's options.
208    pub controller: ControllerConfig,
209    /// Replans after a stuck / off-path move or a blocked partial path before giving up.
210    /// Default 8. Teleports replan without counting.
211    pub max_replans: u32,
212    /// Simulate each plan in `ghast-physics` before moving and plan around moves the
213    /// simulation fails (see [`Pathfinder::plan_verified`]). Default on.
214    pub verify: bool,
215    /// Planning work per game tick: the search expands at most `budget.nodes` nodes and
216    /// planning plus verification stop after `budget.time`. Default 2000 nodes and 5 ms
217    /// (about 4 ms of A* on a desktop core), so a long plan spreads over several ticks
218    /// while the player stands still.
219    pub budget: Budget,
220    /// Most simulated ticks of the verification per game tick (also bounded by
221    /// `budget.time`). Default 400.
222    pub verify_ticks: u32,
223    /// Movement only: the follower leaves the aim to the behaviour (a fight keeps looking at
224    /// its target) and steers with the keys relative to the look the behaviour's aim gives
225    /// this tick. Default off. See [`FollowConfig::with_movement_only`].
226    pub movement_only: bool,
227}
228
229impl Default for FollowConfig {
230    fn default() -> Self {
231        FollowConfig {
232            controller: ControllerConfig::default(),
233            max_replans: 8,
234            verify: true,
235            budget: Budget::nodes(2000).with_time(Duration::from_millis(5)),
236            verify_ticks: 400,
237            movement_only: false,
238        }
239    }
240}
241
242impl FollowConfig {
243    /// The controller's options.
244    #[must_use]
245    pub fn with_controller(mut self, c: ControllerConfig) -> Self {
246        self.controller = c;
247        self
248    }
249
250    /// Replan budget.
251    #[must_use]
252    pub fn with_max_replans(mut self, n: u32) -> Self {
253        self.max_replans = n;
254        self
255    }
256
257    /// Movement only (strafe-relative steering): the follower never sets the aim on plain moves
258    /// (walks, diagonals, step-ups, drops, swims); it plans the keys for the look it wants and
259    /// presses the one of the eight key directions (forward / back × left / right) closest to
260    /// that move for the look the behaviour's aim gives this tick
261    /// ([`TickContext::planned_look`], so tick the follower after `set_aim`): the direction
262    /// whose next ticks, simulated, end closest to where the planned keys would go and keep
263    /// to the floor. The sprint key stays down only with forward. Moves that need the look — digging, placing, doors, gap
264    /// jumps, ladders, pillars — still aim while they last ([`Follower::aiming`] tells). Eight
265    /// directions are coarser than a turned look (up to 22.5° off), so corners and ledges are
266    /// walked less exactly than with the aim; [`Follower::waypoint`] gives the point to steer
267    /// to for a behaviour that drives the keys itself.
268    #[must_use]
269    pub fn with_movement_only(mut self, on: bool) -> Self {
270        self.movement_only = on;
271        self
272    }
273
274    /// Simulated verification of plans on or off.
275    #[must_use]
276    pub fn with_verify(mut self, on: bool) -> Self {
277        self.verify = on;
278        self
279    }
280
281    /// Planning work per game tick ([`Budget::UNLIMITED`]: plan in one tick).
282    #[must_use]
283    pub fn with_budget(mut self, budget: Budget) -> Self {
284        self.budget = budget;
285        self
286    }
287
288    /// Simulated verification ticks per game tick.
289    #[must_use]
290    pub fn with_verify_ticks(mut self, ticks: u32) -> Self {
291        self.verify_ticks = ticks.max(1);
292        self
293    }
294}
295
296/// Why following failed.
297#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
298#[non_exhaustive]
299pub enum FollowError {
300    /// Planning failed.
301    Plan(PlanError),
302    /// The replan budget ([`FollowConfig::max_replans`]) is used up.
303    GaveUp,
304    /// The planner does not support this game version (26.1) or its feature is off.
305    UnsupportedVersion,
306}
307
308impl std::fmt::Display for FollowError {
309    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
310        match self {
311            FollowError::Plan(e) => write!(f, "planning failed: {e}"),
312            FollowError::GaveUp => f.write_str("gave up after too many replans"),
313            FollowError::UnsupportedVersion => {
314                f.write_str("the path finder does not support this game version")
315            }
316        }
317    }
318}
319
320impl std::error::Error for FollowError {}
321
322/// What the [`Follower`] is doing.
323#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
324#[non_exhaustive]
325pub enum FollowStatus {
326    /// No goal.
327    Idle,
328    /// Walking (or digging / placing) toward the goal.
329    Moving,
330    /// The goal is reached; keys released.
331    Arrived,
332    /// Following failed; keys released.
333    Failed(FollowError),
334}
335
336/// Plans and follows a path from a behaviour's tick: call [`Follower::tick`] once per tick from
337/// `Behavior::tick`. It sets the aim, the movement keys and (for digs) the left button
338/// through the [`TickContext`], so the client's rules hold: rotation in whole mouse counts,
339/// actions before the tick's single movement packet, digs / places only with the sent
340/// crosshair on the block.
341///
342/// It replans after a teleport, when the controller gets stuck or leaves the path (that move
343/// is avoided from then on), and at the end of a partial path (goal beyond loaded terrain).
344/// Digging and placing follow [`crate::Config::dig`] / [`crate::Config::place`]; for places
345/// the behaviour keeps a block in the hand.
346///
347/// ```no_run
348/// use ghast_client::{Behavior, TickContext};
349/// use ghast_pathfinder::{Config, FollowConfig, FollowStatus, Follower, Goal, Pathfinder};
350///
351/// struct GoThere(Follower);
352///
353/// impl Behavior for GoThere {
354///     fn tick(&mut self, ctx: &mut TickContext<'_>) {
355///         match self.0.tick(ctx) {
356///             FollowStatus::Arrived => ctx.disconnect("arrived"),
357///             FollowStatus::Failed(e) => ctx.disconnect(format!("failed: {e}")),
358///             _ => {}
359///         }
360///     }
361/// }
362///
363/// let mut f = Follower::new(Pathfinder::new(Config::default()), FollowConfig::default());
364/// f.goto(Goal::Block([20, 64, 5]));
365/// let mut behaviour = GoThere(f);
366/// ```
367#[derive(Clone, Debug)]
368pub struct Follower {
369    pf: Pathfinder,
370    cfg: FollowConfig,
371    goal: Option<Goal>,
372    ctrl: Option<Controller>,
373    status: FollowStatus,
374    replans: u32,
375    banned: HashSet<([i32; 3], [i32; 3])>,
376    /// Closest a partial path has come to the goal so far (no progress beyond it = blocked).
377    partial_best: f64,
378    /// The path being followed is partial and final: no path to the goal exists through the
379    /// loaded terrain (the search was exhausted), it ends as close to the goal as possible.
380    unreachable: bool,
381    /// Ticks to wait after a place was sent.
382    place_wait: u32,
383    digging: bool,
384    plans: u64,
385    /// A plan in progress (spread over ticks).
386    planning: Option<Planning>,
387    /// Ticks the current (or last) plan took.
388    plan_ticks: u32,
389    /// Whether the goal lay in loaded terrain when the current plan started.
390    goal_loaded: Option<bool>,
391    /// The last tick set the aim.
392    aimed: bool,
393}
394
395/// A plan in progress: the search, then the simulated check.
396#[derive(Clone, Debug)]
397enum Planning {
398    Search {
399        search: Box<Search>,
400        /// Moves the verification failed (on top of [`Follower::banned`]).
401        bans: HashSet<([i32; 3], [i32; 3])>,
402        attempt: u32,
403        /// The previous attempt's path (followed if a later search fails) and whether its
404        /// search was exhausted.
405        last: Option<(Path, bool)>,
406    },
407    Verify {
408        sim: Box<Simulation>,
409        bans: HashSet<([i32; 3], [i32; 3])>,
410        attempt: u32,
411        /// The search of the path was exhausted.
412        exhausted: bool,
413    },
414}
415
416/// A search with the live player's movement limits when the client has one (26.1).
417fn with_player<I: Io + ?Sized>(ctx: &I, search: Search) -> Search {
418    #[cfg(ghast_modern)]
419    if let Some(p) = ctx.modern_player() {
420        return search.with_modern_player(p);
421    }
422    let _ = ctx;
423    search
424}
425
426/// The verification of `path` with the live player when the client has one (26.1).
427fn new_sim<I: Io + ?Sized>(ctx: &I, path: &Path, cfg: &ControllerConfig) -> Simulation {
428    #[cfg(ghast_modern)]
429    if let Some(p) = ctx.modern_player() {
430        return Simulation::with_modern_player(path, cfg, p);
431    }
432    let _ = ctx;
433    Simulation::new(path, cfg)
434}
435
436/// Plans per goal and replan: the first one and two repairs after failed simulations.
437const VERIFY_ATTEMPTS: u32 = 3;
438
439/// Whether the goal's place lies in loaded terrain (goals without one: no).
440fn goal_loaded<W: BlockSource + ?Sized>(goal: &Goal, world: &W) -> bool {
441    match goal {
442        Goal::Block(p) | Goal::Near { pos: p, .. } => world.is_column_loaded(p[0] >> 4, p[2] >> 4),
443        Goal::Xz { x, z } => world.is_column_loaded(x >> 4, z >> 4),
444        Goal::Y(_) => false,
445        Goal::AnyOf(gs) => !gs.is_empty() && gs.iter().all(|g| goal_loaded(g, world)),
446    }
447}
448
449impl Follower {
450    /// A follower without a goal.
451    #[must_use]
452    pub fn new(pathfinder: Pathfinder, cfg: FollowConfig) -> Self {
453        Follower {
454            pf: pathfinder,
455            cfg,
456            goal: None,
457            ctrl: None,
458            status: FollowStatus::Idle,
459            replans: 0,
460            banned: HashSet::new(),
461            partial_best: f64::INFINITY,
462            unreachable: false,
463            place_wait: 0,
464            digging: false,
465            plans: 0,
466            planning: None,
467            plan_ticks: 0,
468            goal_loaded: None,
469            aimed: false,
470        }
471    }
472
473    /// Sets a new goal (planned on the next [`Follower::tick`]).
474    pub fn goto(&mut self, goal: Goal) {
475        self.goal = Some(goal);
476        self.ctrl = None;
477        self.planning = None;
478        self.status = FollowStatus::Moving;
479        self.replans = 0;
480        self.banned.clear();
481        self.partial_best = f64::INFINITY;
482        self.unreachable = false;
483    }
484
485    /// Drops the goal and releases the keys and buttons (in this tick).
486    pub fn stop(&mut self, ctx: &mut TickContext<'_>) {
487        self.goal = None;
488        self.ctrl = None;
489        self.planning = None;
490        self.status = FollowStatus::Idle;
491        self.release(ctx);
492    }
493
494    /// The goal.
495    #[must_use]
496    pub fn goal(&self) -> Option<&Goal> {
497        self.goal.as_ref()
498    }
499
500    /// The current state.
501    #[must_use]
502    pub fn status(&self) -> FollowStatus {
503        self.status
504    }
505
506    /// The path being followed.
507    #[must_use]
508    pub fn path(&self) -> Option<&crate::Path> {
509        self.ctrl.as_ref().map(Controller::path)
510    }
511
512    /// The point the follower walks to now (the next step's block centre at its feet height),
513    /// `None` without a path being followed.
514    #[must_use]
515    pub fn waypoint(&self) -> Option<[f64; 3]> {
516        self.ctrl.as_ref().and_then(Controller::waypoint)
517    }
518
519    /// The move (`from`, `to` feet blocks) being followed.
520    #[must_use]
521    pub fn current_move(&self) -> Option<([i32; 3], [i32; 3])> {
522        self.ctrl.as_ref().and_then(Controller::current_move)
523    }
524
525    /// Whether the last [`Follower::tick`] set the aim (always, unless
526    /// [`FollowConfig::with_movement_only`] is on and the move did not need the look).
527    #[must_use]
528    pub fn aiming(&self) -> bool {
529        self.aimed
530    }
531
532    /// Plans made since the follower was created (for logs and tests).
533    #[must_use]
534    pub fn plans(&self) -> u64 {
535        self.plans
536    }
537
538    /// A plan is in progress: the player stands still (keys released, no turning) and the
539    /// client keeps sending its normal movement packet every tick.
540    #[must_use]
541    pub fn is_planning(&self) -> bool {
542        self.planning.is_some()
543    }
544
545    /// Ticks the current (or the last) plan took, verification included (1 = planned within
546    /// the tick it started).
547    #[must_use]
548    pub fn plan_ticks(&self) -> u32 {
549        self.plan_ticks
550    }
551
552    /// The planner.
553    #[must_use]
554    pub fn pathfinder(&self) -> &Pathfinder {
555        &self.pf
556    }
557
558    fn release<I: Io + ?Sized>(&mut self, ctx: &mut I) {
559        ctx.set_keys(Keys::NONE);
560        if self.digging || ctx.left_button() {
561            ctx.set_left_button(false);
562        }
563        self.digging = false;
564    }
565
566    fn fail<I: Io + ?Sized>(&mut self, ctx: &mut I, e: FollowError) -> FollowStatus {
567        self.ctrl = None;
568        self.planning = None;
569        self.status = FollowStatus::Failed(e);
570        self.release(ctx);
571        self.status
572    }
573
574    /// Starts a plan from the player's feet block.
575    fn start_plan<I: Io + ?Sized>(&mut self, ctx: &I, version: Version) {
576        let goal = self.goal.clone().expect("planning without a goal");
577        let start = Pathfinder::start_block(ctx.observation().pos);
578        self.plans += 1;
579        self.plan_ticks = 0;
580        self.planning = Some(Planning::Search {
581            search: Box::new(with_player(
582                ctx,
583                self.pf.search(version, start, goal, self.banned.clone()),
584            )),
585            bans: HashSet::new(),
586            attempt: 0,
587            last: None,
588        });
589    }
590
591    /// This tick's share of the plan in progress: the controller once the path is ready.
592    fn work<I: Io + ?Sized>(&mut self, ctx: &I) -> Result<Option<Controller>, PlanError> {
593        self.plan_ticks += 1;
594        let t0 = Instant::now();
595        let left = |budget: Option<Duration>| budget.map(|b| b.saturating_sub(t0.elapsed()));
596        loop {
597            if let Some(max) = self.cfg.budget.time
598                && t0.elapsed() >= max
599            {
600                return Ok(None);
601            }
602            let Some(phase) = self.planning.take() else {
603                return Ok(None);
604            };
605            match phase {
606                Planning::Search {
607                    mut search,
608                    bans,
609                    attempt,
610                    last,
611                } => {
612                    let budget = Budget {
613                        nodes: self.cfg.budget.nodes,
614                        time: left(self.cfg.budget.time),
615                    };
616                    match search.step(&world_of(ctx), budget) {
617                        None => {
618                            self.planning = Some(Planning::Search {
619                                search,
620                                bans,
621                                attempt,
622                                last,
623                            });
624                            return Ok(None);
625                        }
626                        Some(Err(e)) => match last {
627                            // A repair failed: follow the previous path after all.
628                            Some((p, ex)) => return Ok(Some(self.ready(p, ex))),
629                            None => return Err(e),
630                        },
631                        Some(Ok(path)) => {
632                            let exhausted = search.exhausted();
633                            if !self.cfg.verify {
634                                return Ok(Some(self.ready(path, exhausted)));
635                            }
636                            let sim = new_sim(ctx, &path, &self.cfg.controller);
637                            self.planning = Some(Planning::Verify {
638                                sim: Box::new(sim),
639                                bans,
640                                attempt,
641                                exhausted,
642                            });
643                        }
644                    }
645                }
646                Planning::Verify {
647                    mut sim,
648                    mut bans,
649                    attempt,
650                    exhausted,
651                } => {
652                    let Some((outcome, reached)) = sim
653                        .step(
654                            &world_of(ctx),
655                            self.cfg.verify_ticks,
656                            left(self.cfg.budget.time),
657                        )
658                        .map(|r| (r.outcome, r.reached))
659                    else {
660                        self.planning = Some(Planning::Verify {
661                            sim,
662                            bans,
663                            attempt,
664                            exhausted,
665                        });
666                        return Ok(None);
667                    };
668                    let path = sim.path();
669                    if outcome == SimOutcome::Arrived {
670                        let path = path.clone();
671                        return Ok(Some(self.ready(path, exhausted)));
672                    }
673                    // Plan around the move the simulation failed.
674                    let k = (reached + 1).min(path.steps.len() - 1);
675                    let m = (path.steps[k.saturating_sub(1)].pos, path.steps[k].pos);
676                    log::debug!("pathfinder: simulation {outcome:?} on move {m:?}");
677                    if k == 0 || attempt + 1 >= VERIFY_ATTEMPTS || !bans.insert(m) {
678                        let path = path.clone();
679                        return Ok(Some(self.ready(path, exhausted)));
680                    }
681                    let goal = self.goal.clone().expect("planning without a goal");
682                    let mut all = self.banned.clone();
683                    all.extend(bans.iter().copied());
684                    let search = with_player(
685                        ctx,
686                        self.pf.search(path.version, path.steps[0].pos, goal, all),
687                    );
688                    self.planning = Some(Planning::Search {
689                        search: Box::new(search),
690                        bans,
691                        attempt: attempt + 1,
692                        last: Some((path.clone(), exhausted)),
693                    });
694                }
695            }
696        }
697    }
698
699    fn ready(&mut self, path: Path, exhausted: bool) -> Controller {
700        // An exhausted search knows every block reachable through the loaded terrain: if the
701        // goal lies in loaded terrain too, its partial path is as close as one gets.
702        self.unreachable = path.partial && exhausted && self.goal_loaded.unwrap_or(false);
703        log::debug!(
704            "pathfinder: {} steps, cost {:.0} ticks, {} nodes{}, planned in {} ticks",
705            path.steps.len(),
706            path.cost,
707            path.expanded,
708            if self.unreachable {
709                ", partial (goal unreachable)"
710            } else if path.partial {
711                ", partial"
712            } else {
713                ""
714            },
715            self.plan_ticks
716        );
717        self.planning = None;
718        Controller::new(path, self.cfg.controller.clone())
719    }
720
721    /// One tick: plans when needed, then aims and sets the keys (and digs / places). Returns
722    /// the status after this tick.
723    pub fn tick(&mut self, ctx: &mut TickContext<'_>) -> FollowStatus {
724        self.step(ctx)
725    }
726
727    /// [`Follower::tick`] over any [`Io`].
728    pub(crate) fn step<I: Io + ?Sized>(&mut self, ctx: &mut I) -> FollowStatus {
729        if self.goal.is_none() || !matches!(self.status, FollowStatus::Moving) {
730            return self.status;
731        }
732        if ctx.moved_by_server() {
733            self.ctrl = None;
734            self.planning = None;
735        }
736        if ctx.is_dead() {
737            self.release(ctx);
738            return self.status;
739        }
740        if self.ctrl.is_none() {
741            if self.planning.is_none() {
742                let Some(version) = ctx.version() else {
743                    return self.fail(ctx, FollowError::UnsupportedVersion);
744                };
745                self.goal_loaded = self.goal.as_ref().map(|g| goal_loaded(g, ctx.world()));
746                self.start_plan(ctx, version);
747            }
748            match self.work(ctx) {
749                Ok(Some(c)) => self.ctrl = Some(c),
750                Ok(None) => {
751                    // Still planning: stand still; the movement packet goes out as usual.
752                    self.release(ctx);
753                    return self.status;
754                }
755                Err(e) => return self.fail(ctx, FollowError::Plan(e)),
756            }
757        }
758        let obs = ctx.observation();
759        let ctrl = self.ctrl.as_mut().expect("planned above");
760        #[cfg(ghast_modern)]
761        if let Some(p) = ctx.modern_player() {
762            ctrl.set_modern_player(p);
763        }
764        let (yaw, pitch) = ctrl.aim(&obs, &world_of(ctx));
765        let done = matches!(
766            ctrl.progress(),
767            Progress::Arrived | Progress::Stuck | Progress::OffPath
768        );
769        let steer = self.cfg.movement_only && !ctrl.needs_look();
770        self.aimed = !done && !steer;
771        if self.aimed {
772            ctx.set_aim(yaw, pitch);
773        }
774        let look = ctx.planned_look();
775        let cmd = if steer {
776            // The keys for the wanted look, pressed relative to the behaviour's look.
777            let mut cmd = ctrl.keys(&obs, (yaw, look.1), &world_of(ctx));
778            cmd.keys = ctrl.steer_keys(&obs, cmd.keys, look, &world_of(ctx));
779            cmd
780        } else {
781            ctrl.keys(&obs, look, &world_of(ctx))
782        };
783        match ctrl.progress() {
784            Progress::Arrived => {
785                let path = ctrl.path();
786                if !path.partial {
787                    self.release(ctx);
788                    self.status = FollowStatus::Arrived;
789                    return self.status;
790                }
791                if self.unreachable {
792                    // As close as it gets: no path exists through the loaded terrain.
793                    return self.fail(ctx, FollowError::Plan(PlanError::NoPath));
794                }
795                // The end of a partial path: plan the rest from here. Count it against the
796                // replan budget unless it got closer to the goal than any partial path before.
797                let goal = self.goal.as_ref().expect("following without a goal");
798                let d = path
799                    .steps
800                    .last()
801                    .map_or(f64::INFINITY, |s| goal.distance(s.pos));
802                if d < self.partial_best - 0.5 {
803                    self.partial_best = d;
804                } else {
805                    self.replans += 1;
806                }
807                self.ctrl = None;
808                self.release(ctx);
809                if self.replans > self.cfg.max_replans {
810                    return self.fail(ctx, FollowError::GaveUp);
811                }
812                return self.status;
813            }
814            Progress::Stuck | Progress::OffPath => {
815                if let Some(m) = ctrl.current_move() {
816                    log::debug!(
817                        "pathfinder: {:?} on move {m:?}, replanning",
818                        ctrl.progress()
819                    );
820                    self.banned.insert(m);
821                }
822                self.ctrl = None;
823                self.replans += 1;
824                self.release(ctx);
825                if self.replans > self.cfg.max_replans {
826                    return self.fail(ctx, FollowError::GaveUp);
827                }
828                return self.status;
829            }
830            Progress::Moving | Progress::Working => {}
831        }
832        ctx.set_keys(cmd.keys);
833        if let Some(d) = cmd.dig {
834            let on = ctx.targets(d);
835            ctx.set_left_button(on);
836            self.digging = true;
837        } else if self.digging {
838            ctx.set_left_button(false);
839            self.digging = false;
840        }
841        if let Some(p) = cmd.place {
842            if self.place_wait > 0 {
843                self.place_wait -= 1;
844            } else if ctx.place_against(p.against, p.face()) {
845                self.place_wait = 10;
846            }
847        } else if let Some(b) = cmd.interact {
848            // A second click would close the door again: wait for the server's answer.
849            if self.place_wait > 0 {
850                self.place_wait -= 1;
851            } else if ctx.activate(b) {
852                self.place_wait = 20;
853            }
854        } else {
855            self.place_wait = 0;
856        }
857        self.status
858    }
859}
860
861#[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
862pub(crate) mod tests {
863    //! The follower driven tick by tick in the physics (a simulated client): mazes, unreachable
864    //! goals, gap jumps.
865
866    use std::time::{Duration, Instant};
867
868    use ghast_physics::Keys;
869
870    use super::{FollowConfig, FollowError, FollowStatus, Follower, Io};
871    use crate::physics::{Observation, P12, P16, P18, P26, P262, Physics, SourceView};
872    use crate::plan::{Config, Pathfinder, PlanError};
873    use crate::sim::Turner;
874    use crate::world::BlockSource;
875    use crate::{Goal, Version};
876
877    /// The world as the simulated client sees it: the test's world plus the blocks the player
878    /// dug, placed or clicked (doors).
879    pub(crate) struct Overlay<'w, W> {
880        base: &'w W,
881        set: std::collections::HashMap<[i32; 3], u32>,
882    }
883
884    impl<W: BlockSource> BlockSource for Overlay<'_, W> {
885        fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32> {
886            match self.set.get(&[x, y, z]) {
887                Some(&r) => Some(r),
888                None => self.base.raw_block(x, y, z),
889            }
890        }
891
892        fn is_column_loaded(&self, cx: i32, cz: i32) -> bool {
893            self.base.is_column_loaded(cx, cz)
894        }
895
896        fn build_height(&self) -> Option<(i32, i32)> {
897            self.base.build_height()
898        }
899    }
900
901    /// A simulated client: the player in `ghast-physics`, turning in whole mouse counts. Digs,
902    /// places and clicks go through a crosshair ray from the pose of the previous tick (the
903    /// one the server has), within 4.5 blocks, like the real client: a dig breaks the block
904    /// after `5 + 30 × hardness` ticks, a place or a door click takes effect two ticks after it
905    /// was sent (the server's answer).
906    pub(crate) struct SimIo<'w, P: Physics, W: BlockSource> {
907        pub(crate) world: Overlay<'w, W>,
908        pub(crate) state: P::State,
909        turner: Turner,
910        aim: (f32, f32),
911        keys: Keys,
912        left: bool,
913        digging: Option<([i32; 3], u32)>,
914        /// Block changes on their way from the server: (ticks left, position, raw).
915        pending: Vec<(u32, [i32; 3], u32)>,
916        /// Places and clicks sent.
917        pub(crate) places: u32,
918        /// Places asked for while the new block's cell overlapped the player's box (a
919        /// client's placed-block prediction would not apply; vanilla refuses them).
920        pub(crate) overlapping: u32,
921        pub(crate) clicks: u32,
922    }
923
924    impl<'w, P: Physics, W: BlockSource> SimIo<'w, P, W> {
925        pub(crate) fn new(world: &'w W, feet: [f64; 3]) -> Self {
926            let mut state = P::new_state(feet, 0.0, 0.0);
927            let view = SourceView::<P, W>::new(world);
928            for _ in 0..3 {
929                P::tick(&mut state, Keys::NONE, 0.0, 0.0, &view);
930            }
931            SimIo {
932                world: Overlay {
933                    base: world,
934                    set: std::collections::HashMap::new(),
935                },
936                state,
937                turner: Turner::default(),
938                aim: (0.0, 0.0),
939                keys: Keys::NONE,
940                left: false,
941                digging: None,
942                pending: Vec::new(),
943                places: 0,
944                overlapping: 0,
945                clicks: 0,
946            }
947        }
948
949        /// Runs this tick's movement with what the follower asked for.
950        pub(crate) fn advance(&mut self) {
951            // The digging hand first (the server judges it with the pose sent last tick).
952            let target = self.ray().map(|(b, _)| b);
953            match (self.left, target) {
954                (true, Some(b)) => {
955                    let n = match self.digging {
956                        Some((d, n)) if d == b => n + 1,
957                        _ => 1,
958                    };
959                    let hard = self.class(b).hardness.max(0.0);
960                    if n >= 5 + (f64::from(hard) * 30.0) as u32 {
961                        self.world.set.insert(b, 0);
962                        self.digging = None;
963                    } else {
964                        self.digging = Some((b, n));
965                    }
966                }
967                _ => self.digging = None,
968            }
969            for p in &mut self.pending {
970                p.0 -= 1;
971            }
972            let (due, rest): (Vec<_>, Vec<_>) = self.pending.drain(..).partition(|p| p.0 == 0);
973            self.pending = rest;
974            for (_, pos, raw) in due {
975                self.world.set.insert(pos, raw);
976            }
977            let o = P::observe(&self.state);
978            let look = self.turner.step(o.yaw, o.pitch, self.aim);
979            let view = SourceView::<P, Overlay<'w, W>>::new(&self.world);
980            P::tick(&mut self.state, self.keys, look.0, look.1, &view);
981        }
982
983        pub(crate) fn feet(&self) -> [f64; 3] {
984            P::observe(&self.state).pos
985        }
986
987        pub(crate) fn class(&self, p: [i32; 3]) -> crate::class::Class {
988            let t = crate::class::table(P::VERSION);
989            self.world
990                .raw_block(p[0], p[1], p[2])
991                .map_or(crate::class::Class::UNKNOWN, |r| {
992                    t.classes[t.index(r) as usize]
993                })
994        }
995
996        /// The block the crosshair is on and the face it enters (as a unit offset), from the
997        /// pose the server has; cells with any collision box count as whole cubes.
998        pub(crate) fn ray(&self) -> Option<([i32; 3], [i32; 3])> {
999            let o = P::observe(&self.state);
1000            let (yaw, pitch) = (
1001                f64::from(o.yaw).to_radians(),
1002                f64::from(o.pitch).to_radians(),
1003            );
1004            let d = [
1005                -yaw.sin() * pitch.cos(),
1006                -pitch.sin(),
1007                yaw.cos() * pitch.cos(),
1008            ];
1009            let e = [o.pos[0], o.pos[1] + 1.62, o.pos[2]];
1010            let mut c = [
1011                e[0].floor() as i32,
1012                e[1].floor() as i32,
1013                e[2].floor() as i32,
1014            ];
1015            let step = d.map(|v| if v > 0.0 { 1 } else { -1 });
1016            let mut tmax = [0.0f64; 3];
1017            let mut tdelta = [0.0f64; 3];
1018            for i in 0..3 {
1019                if d[i].abs() < 1e-12 {
1020                    tmax[i] = f64::INFINITY;
1021                    tdelta[i] = f64::INFINITY;
1022                } else {
1023                    let next = if d[i] > 0.0 {
1024                        f64::from(c[i]) + 1.0
1025                    } else {
1026                        f64::from(c[i])
1027                    };
1028                    tmax[i] = (next - e[i]) / d[i];
1029                    tdelta[i] = 1.0 / d[i].abs();
1030                }
1031            }
1032            loop {
1033                let i = (0..3).min_by(|&a, &b| tmax[a].total_cmp(&tmax[b])).unwrap();
1034                if tmax[i] > 4.5 {
1035                    return None;
1036                }
1037                c[i] += step[i];
1038                tmax[i] += tdelta[i];
1039                let k = self.class(c);
1040                if k.has(crate::class::flag::SOLID) {
1041                    let mut face = [0; 3];
1042                    face[i] = -step[i];
1043                    return Some((c, face));
1044                }
1045            }
1046        }
1047
1048        /// Whether a block at `p` would overlap the player's box.
1049        fn overlaps_player(&self, p: [i32; 3]) -> bool {
1050            let o = P::observe(&self.state).pos;
1051            let (x, y, z) = (f64::from(p[0]), f64::from(p[1]), f64::from(p[2]));
1052            o[0] + 0.3 > x
1053                && o[0] - 0.3 < x + 1.0
1054                && o[1] + 1.8 > y
1055                && o[1] < y + 1.0
1056                && o[2] + 0.3 > z
1057                && o[2] - 0.3 < z + 1.0
1058        }
1059    }
1060
1061    impl<'w, P: Physics, W: BlockSource> Io for SimIo<'w, P, W> {
1062        type World<'a>
1063            = Overlay<'w, W>
1064        where
1065            Self: 'a;
1066
1067        fn world(&self) -> &Overlay<'w, W> {
1068            &self.world
1069        }
1070
1071        fn version(&self) -> Option<Version> {
1072            Some(P::VERSION)
1073        }
1074
1075        fn observation(&self) -> Observation {
1076            let mut o = P::observe(&self.state);
1077            o.food = 20;
1078            o
1079        }
1080
1081        fn moved_by_server(&self) -> bool {
1082            false
1083        }
1084
1085        fn is_dead(&self) -> bool {
1086            false
1087        }
1088
1089        fn set_aim(&mut self, yaw: f32, pitch: f32) {
1090            self.aim = (yaw, pitch);
1091        }
1092
1093        fn planned_look(&self) -> (f32, f32) {
1094            let o = P::observe(&self.state);
1095            let mut t = self.turner;
1096            t.step(o.yaw, o.pitch, self.aim)
1097        }
1098
1099        fn set_keys(&mut self, keys: Keys) {
1100            self.keys = keys;
1101        }
1102
1103        fn left_button(&self) -> bool {
1104            self.left
1105        }
1106
1107        fn set_left_button(&mut self, on: bool) {
1108            self.left = on;
1109        }
1110
1111        fn targets(&self, block: [i32; 3]) -> bool {
1112            self.ray().is_some_and(|(b, _)| b == block)
1113        }
1114
1115        fn place_against(&mut self, against: [i32; 3], dir: [i32; 3]) -> bool {
1116            if self.ray() != Some((against, dir)) {
1117                return false;
1118            }
1119            let pos = [
1120                against[0] + dir[0],
1121                against[1] + dir[1],
1122                against[2] + dir[2],
1123            ];
1124            if self.overlaps_player(pos) {
1125                self.overlapping += 1;
1126                return false;
1127            }
1128            if !self.class(pos).has(crate::class::flag::REPLACEABLE) {
1129                return false;
1130            }
1131            self.places += 1;
1132            self.pending
1133                .push((2, pos, crate::sim::stone_raw(P::VERSION)));
1134            true
1135        }
1136
1137        fn activate(&mut self, block: [i32; 3]) -> bool {
1138            if self.ray().map(|(b, _)| b) != Some(block) {
1139                return false;
1140            }
1141            self.clicks += 1;
1142            if let Some(changes) = crate::door::toggle(P::VERSION, &self.world, block) {
1143                for (p, raw) in changes {
1144                    self.pending.push((2, p, raw));
1145                }
1146            }
1147            true
1148        }
1149
1150        fn modern_player(&self) -> Option<&ghast_physics::modern::PlayerState> {
1151            P::as_modern(&self.state)
1152        }
1153    }
1154
1155    /// How a drive went.
1156    #[derive(Debug)]
1157    pub(crate) struct Drive {
1158        pub(crate) status: FollowStatus,
1159        pub(crate) ticks: u32,
1160        /// Ticks the follower stood still planning.
1161        pub(crate) planning_ticks: u32,
1162        /// The longest follower tick (wall clock).
1163        pub(crate) worst_tick: Duration,
1164        pub(crate) plans: u64,
1165        pub(crate) end: [f64; 3],
1166    }
1167
1168    /// Drives `follower` to `goal` from standing at `feet`, at most `max` ticks.
1169    pub(crate) fn drive<P: Physics, W: BlockSource>(
1170        world: &W,
1171        feet: [f64; 3],
1172        mut follower: Follower,
1173        goal: Goal,
1174        max: u32,
1175    ) -> Drive {
1176        let mut io = SimIo::<P, W>::new(world, feet);
1177        follower.goto(goal);
1178        let mut d = Drive {
1179            status: FollowStatus::Moving,
1180            ticks: 0,
1181            planning_ticks: 0,
1182            worst_tick: Duration::ZERO,
1183            plans: 0,
1184            end: feet,
1185        };
1186        while d.ticks < max {
1187            let t0 = Instant::now();
1188            d.status = follower.step(&mut io);
1189            // The first tick of a process also measures the move costs once.
1190            if d.ticks > 0 {
1191                d.worst_tick = d.worst_tick.max(t0.elapsed());
1192            }
1193            if follower.is_planning() {
1194                d.planning_ticks += 1;
1195            }
1196            d.ticks += 1;
1197            if d.status != FollowStatus::Moving {
1198                break;
1199            }
1200            io.advance();
1201        }
1202        d.plans = follower.plans();
1203        d.end = io.feet();
1204        d
1205    }
1206
1207    const STONE18: u16 = 1 << 4;
1208
1209    fn rng(s: &mut u64) -> u64 {
1210        *s ^= *s << 13;
1211        *s ^= *s >> 7;
1212        *s ^= *s << 17;
1213        *s
1214    }
1215
1216    /// A perfect maze (recursive backtracker) of `n` × `n` cells with `h`-high stone walls on
1217    /// a stone floor at y = 63; grid (2n + 1)², corner (ox, oz). Cell (i, j) has its feet
1218    /// block at (ox + 2i + 1, 64, oz + 2j + 1). Entrances: west of cell (0, 0), east of
1219    /// cell (n - 1, n - 1).
1220    pub(crate) fn maze<B: Copy>(
1221        w: &mut ghast_physics::MemoryWorld<B>,
1222        (ox, oz): (i32, i32),
1223        n: i32,
1224        h: i32,
1225        seed: u64,
1226    ) {
1227        let size = 2 * n + 1;
1228        w.fill_raw(
1229            [ox, 64, oz],
1230            [ox + size - 1, 63 + h, oz + size - 1],
1231            STONE18,
1232        );
1233        let carve = |w: &mut ghast_physics::MemoryWorld<B>, gx: i32, gz: i32| {
1234            w.fill_raw([ox + gx, 64, oz + gz], [ox + gx, 63 + h, oz + gz], 0);
1235        };
1236        let mut s = seed | 1;
1237        let mut seen = vec![false; (n * n) as usize];
1238        let mut stack = vec![(0, 0)];
1239        seen[0] = true;
1240        carve(w, 1, 1);
1241        while let Some(&(cx, cz)) = stack.last() {
1242            let nb: Vec<(i32, i32)> = [(1, 0), (-1, 0), (0, 1), (0, -1)]
1243                .iter()
1244                .map(|(dx, dz)| (cx + dx, cz + dz))
1245                .filter(|&(x, z)| x >= 0 && z >= 0 && x < n && z < n && !seen[(z * n + x) as usize])
1246                .collect();
1247            if nb.is_empty() {
1248                stack.pop();
1249                continue;
1250            }
1251            let (nx, nz) = nb[(rng(&mut s) % nb.len() as u64) as usize];
1252            seen[(nz * n + nx) as usize] = true;
1253            carve(w, 2 * nx + 1, 2 * nz + 1);
1254            carve(w, cx + nx + 1, cz + nz + 1);
1255            stack.push((nx, nz));
1256        }
1257        carve(w, 0, 1);
1258        carve(w, size - 1, size - 2);
1259    }
1260
1261    /// A flat stone world over chunks -r..=r.
1262    pub(crate) fn flat(r: i32) -> ghast_physics::v1_8::MemoryWorld {
1263        flat_in(ghast_physics::v1_8::memory_world(), r)
1264    }
1265
1266    /// [`flat`] in a world of any version with 1.8 raw ids (1.8 and 1.12).
1267    pub(crate) fn flat_in<B: Copy>(
1268        mut w: ghast_physics::MemoryWorld<B>,
1269        r: i32,
1270    ) -> ghast_physics::MemoryWorld<B> {
1271        w.load_chunks(-r, -r, r, r);
1272        w.fill_raw(
1273            [-16 * r, 63, -16 * r],
1274            [16 * r + 15, 63, 16 * r + 15],
1275            STONE18,
1276        );
1277        w
1278    }
1279
1280    fn follower() -> Follower {
1281        Follower::new(Pathfinder::new(Config::default()), FollowConfig::default())
1282    }
1283
1284    /// Movement only: the behaviour looks a fixed way (a fight's target) the whole time, the
1285    /// follower never touches the aim and still walks the maze with strafe-relative keys.
1286    #[test]
1287    fn movement_only_walks_a_maze_with_the_behaviours_look() {
1288        for (n, seed) in [(7, 3u64), (15, 5)] {
1289            let mut w = flat(6);
1290            maze(&mut w, (-n, -n), n, 2, seed);
1291            let c = if n % 2 == 1 { 0 } else { 1 };
1292            let goal = Goal::Near {
1293                pos: [c, 64, c],
1294                radius: 1.0,
1295            };
1296            let from = [f64::from(-n - 4) + 0.5, 64.0, f64::from(n + 4) + 0.5];
1297            for look in [37.0f32, -120.0, 180.0] {
1298                let mut f = Follower::new(
1299                    Pathfinder::new(Config::default()),
1300                    FollowConfig::default().with_movement_only(true),
1301                );
1302                f.goto(goal.clone());
1303                let mut io = SimIo::<P18, _>::new(&w, from);
1304                let mut status = FollowStatus::Moving;
1305                let mut ticks = 0;
1306                while ticks < 20_000 {
1307                    io.set_aim(look, 0.0);
1308                    status = f.step(&mut io);
1309                    if status != FollowStatus::Moving {
1310                        break;
1311                    }
1312                    assert!(!f.aiming(), "a plain walk aimed");
1313                    io.advance();
1314                    ticks += 1;
1315                }
1316                eprintln!(
1317                    "maze {n} look {look}: {status:?} in {ticks} ticks, {} plans",
1318                    f.plans()
1319                );
1320                assert_eq!(status, FollowStatus::Arrived, "maze {n} look {look}");
1321                assert!(goal.is_reached(Pathfinder::start_block(io.feet())));
1322            }
1323        }
1324    }
1325
1326    /// Mazes of 15, 31 and 63 blocks: the bot starts outside, the goal is the centre cell,
1327    /// whose way through the maze is many times the straight distance.
1328    #[test]
1329    fn mazes_are_solved() {
1330        for (n, seed) in [(7, 3u64), (15, 5), (31, 7)] {
1331            let mut w = flat(6);
1332            maze(&mut w, (-n, -n), n, 2, seed);
1333            let centre = [
1334                if n % 2 == 1 { 0 } else { 1 },
1335                64,
1336                if n % 2 == 1 { 0 } else { 1 },
1337            ];
1338            let from = [f64::from(-n - 4) + 0.5, 64.0, f64::from(n + 4) + 0.5];
1339            let d = drive::<P18, _>(
1340                &w,
1341                from,
1342                follower(),
1343                Goal::Near {
1344                    pos: centre,
1345                    radius: 1.0,
1346                },
1347                20_000,
1348            );
1349            eprintln!("maze {}: {d:?}", 2 * n + 1);
1350            assert_eq!(d.status, FollowStatus::Arrived, "maze {}", 2 * n + 1);
1351            let end = Pathfinder::start_block(d.end);
1352            assert!(
1353                Goal::Near {
1354                    pos: centre,
1355                    radius: 1.0
1356                }
1357                .is_reached(end)
1358            );
1359        }
1360    }
1361
1362    /// Unreachable goals end cleanly: the bot walks to the reachable block closest to the
1363    /// goal, then fails with `NoPath`, after a single search (no second full search from the
1364    /// closest block).
1365    #[test]
1366    fn unreachable_goals_end_after_one_search() {
1367        // A goal in the air (a flying player) and a goal sealed inside a maze.
1368        let w = flat(4);
1369        let d = drive::<P18, _>(
1370            &w,
1371            [-20.5, 64.0, 3.5],
1372            follower(),
1373            Goal::Near {
1374                pos: [10, 70, -4],
1375                radius: 2.0,
1376            },
1377            3000,
1378        );
1379        assert_eq!(
1380            d.status,
1381            FollowStatus::Failed(FollowError::Plan(PlanError::NoPath)),
1382            "{d:?}"
1383        );
1384        assert_eq!(d.plans, 1, "{d:?}");
1385        let end = Pathfinder::start_block(d.end);
1386        assert!((end[0] - 10).abs() <= 1 && (end[2] + 4).abs() <= 1, "{d:?}");
1387        let mut w = flat(4);
1388        maze(&mut w, (-15, -15), 15, 2, 11);
1389        w.fill_raw([-2, 64, -2], [2, 65, 2], STONE18);
1390        w.fill_raw([0, 64, 0], [0, 65, 0], 0);
1391        let d = drive::<P18, _>(
1392            &w,
1393            [-18.5, 64.0, 18.5],
1394            follower(),
1395            Goal::Block([0, 64, 0]),
1396            20_000,
1397        );
1398        assert_eq!(
1399            d.status,
1400            FollowStatus::Failed(FollowError::Plan(PlanError::NoPath)),
1401            "{d:?}"
1402        );
1403        assert_eq!(d.plans, 1, "{d:?}");
1404    }
1405
1406    /// A node budget far below what the maze needs: partial paths into dead ends must not make
1407    /// the bot wander (and search) forever.
1408    #[test]
1409    fn capped_searches_give_up() {
1410        let mut w = flat(4);
1411        maze(&mut w, (-31, -31), 31, 2, 13);
1412        let f = Follower::new(
1413            Pathfinder::new(Config::default().with_max_nodes(1500)),
1414            FollowConfig::default(),
1415        );
1416        let d = drive::<P18, _>(&w, [-34.5, 64.0, -29.5], f, Goal::Block([0, 64, 0]), 40_000);
1417        eprintln!("{d:?}");
1418        assert_ne!(d.status, FollowStatus::Moving, "still wandering: {d:?}");
1419        assert!(d.plans <= 20, "{d:?}");
1420    }
1421
1422    /// The per-tick work stays in the budget on the biggest maze. The wall-clock check runs
1423    /// only with `GHAST_TIMING` set, in release builds (debug builds are ~10 times slower,
1424    /// and a loaded machine stretches any tick).
1425    #[test]
1426    fn per_tick_budget_on_a_big_maze() {
1427        let mut w = flat(10);
1428        maze(&mut w, (-63, -63), 63, 2, 17);
1429        let budget = FollowConfig::default().budget;
1430        let d = drive::<P18, _>(
1431            &w,
1432            [-67.5, 64.0, 67.5],
1433            follower(),
1434            Goal::Near {
1435                pos: [1, 64, 1],
1436                radius: 1.0,
1437            },
1438            40_000,
1439        );
1440        eprintln!("maze 127, view distance 10: {d:?}");
1441        assert_eq!(d.status, FollowStatus::Arrived, "{d:?}");
1442        if !cfg!(debug_assertions) && std::env::var_os("GHAST_TIMING").is_some() {
1443            let max = budget.time.unwrap() + Duration::from_millis(3);
1444            assert!(d.worst_tick <= max, "{d:?}");
1445        }
1446        let _ = P16::VERSION;
1447    }
1448
1449    /// The parkour corridor of `lab/pathfinder-course.sh` (superflat: grass y 3, feet y 4),
1450    /// east and back west, driven by the follower.
1451    #[test]
1452    fn the_lab_parkour_corridor() {
1453        let w = corridor(ghast_physics::v1_8::memory_world());
1454        run_corridor::<P18, _>(&w);
1455        let w = corridor(ghast_physics::v1_12::memory_world());
1456        run_corridor::<P12, _>(&w);
1457    }
1458
1459    /// The 1.12 rules through mazes and an unreachable goal as well.
1460    #[test]
1461    fn mazes_on_1_12() {
1462        let n = 15;
1463        let mut w = flat_in(ghast_physics::v1_12::memory_world(), 6);
1464        maze(&mut w, (-n, -n), n, 2, 5);
1465        let from = [f64::from(-n - 4) + 0.5, 64.0, f64::from(n + 4) + 0.5];
1466        let goal = Goal::Near {
1467            pos: [1, 64, 1],
1468            radius: 1.0,
1469        };
1470        let d = drive::<P12, _>(&w, from, follower(), goal, 20_000);
1471        assert_eq!(d.status, FollowStatus::Arrived, "{d:?}");
1472        let air = Goal::Near {
1473            pos: [1, 70, 1],
1474            radius: 2.0,
1475        };
1476        let d = drive::<P12, _>(&w, from, follower(), air, 20_000);
1477        assert_eq!(
1478            d.status,
1479            FollowStatus::Failed(FollowError::Plan(PlanError::NoPath)),
1480            "{d:?}"
1481        );
1482        assert_eq!(d.plans, 1, "{d:?}");
1483    }
1484
1485    fn corridor<B: Copy>(mut w: ghast_physics::MemoryWorld<B>) -> ghast_physics::MemoryWorld<B> {
1486        w.load_chunks(0, -2, 9, 2);
1487        w.fill_raw([0, 0, -32], [159, 0, 47], 7 << 4);
1488        w.fill_raw([0, 1, -32], [159, 2, 47], 3 << 4);
1489        w.fill_raw([0, 3, -32], [159, 3, 47], 2 << 4);
1490        for z in [-2, 2] {
1491            w.fill_raw([60, 1, z], [123, 7, z], STONE18);
1492        }
1493        w.fill_raw([123, 4, -2], [123, 7, 2], STONE18);
1494        let trench = |w: &mut ghast_physics::MemoryWorld<B>, a: i32, b: i32| {
1495            w.fill_raw([a, 1, -1], [b, 3, 1], 0);
1496        };
1497        trench(&mut w, 66, 66);
1498        trench(&mut w, 71, 72);
1499        trench(&mut w, 77, 79);
1500        trench(&mut w, 84, 84);
1501        w.fill_raw([85, 4, -1], [89, 4, 1], STONE18);
1502        trench(&mut w, 90, 91);
1503        trench(&mut w, 96, 111);
1504        for (x, top) in [(98, 3), (100, 3), (104, 3), (107, 4), (109, 3)] {
1505            w.fill_raw([x, 1, 0], [x, top, 0], STONE18);
1506        }
1507        w
1508    }
1509
1510    /// A 26.1 block's state id.
1511    fn id26(spec: &str) -> u16 {
1512        ghast_data::v26_1::BlockState::parse(spec)
1513            .unwrap_or_else(|| panic!("{spec}"))
1514            .id()
1515    }
1516
1517    /// The lab corridor in a 26.1 world (same layout, 26.1 ids).
1518    fn corridor_26() -> ghast_physics::modern::MemoryWorld26 {
1519        let mut w = ghast_physics::modern::memory_world_26_1();
1520        let stone = id26("stone");
1521        w.load_chunks(0, -2, 9, 2);
1522        w.fill_raw([0, 0, -32], [159, 0, 47], id26("bedrock"));
1523        w.fill_raw([0, 1, -32], [159, 2, 47], id26("dirt"));
1524        w.fill_raw([0, 3, -32], [159, 3, 47], id26("grass_block"));
1525        for z in [-2, 2] {
1526            w.fill_raw([60, 1, z], [123, 7, z], stone);
1527        }
1528        w.fill_raw([123, 4, -2], [123, 7, 2], stone);
1529        let trench = |w: &mut ghast_physics::modern::MemoryWorld26, a: i32, b: i32| {
1530            w.fill_raw([a, 1, -1], [b, 3, 1], 0);
1531        };
1532        trench(&mut w, 66, 66);
1533        trench(&mut w, 71, 72);
1534        trench(&mut w, 77, 79);
1535        trench(&mut w, 84, 84);
1536        w.fill_raw([85, 4, -1], [89, 4, 1], stone);
1537        trench(&mut w, 90, 91);
1538        trench(&mut w, 96, 111);
1539        for (x, top) in [(98, 3), (100, 3), (104, 3), (107, 4), (109, 3)] {
1540            w.fill_raw([x, 1, 0], [x, top, 0], stone);
1541        }
1542        w
1543    }
1544
1545    /// The parkour corridor driven by the follower on 26.1.
1546    #[test]
1547    fn the_lab_parkour_corridor_26_1() {
1548        run_corridor::<P26, _>(&corridor_26());
1549    }
1550
1551    /// 26.1: a maze (in negative Y, under the overworld's old floor) and an unreachable goal.
1552    #[test]
1553    fn mazes_on_26_1() {
1554        let n = 15;
1555        let (y, stone) = (-40, id26("stone"));
1556        let mut w = ghast_physics::modern::memory_world_26_1();
1557        w.load_chunks(-6, -6, 6, 6);
1558        w.fill_raw([-96, y - 1, -96], [111, y - 1, 111], stone);
1559        let size = 2 * n + 1;
1560        let (ox, oz) = (-n, -n);
1561        w.fill_raw([ox, y, oz], [ox + size - 1, y + 1, oz + size - 1], stone);
1562        let mut s = 5u64 | 1;
1563        let mut seen = vec![false; (n * n) as usize];
1564        let mut stack = vec![(0, 0)];
1565        seen[0] = true;
1566        let carve = |w: &mut ghast_physics::modern::MemoryWorld26, gx: i32, gz: i32| {
1567            w.fill_raw([ox + gx, y, oz + gz], [ox + gx, y + 1, oz + gz], 0);
1568        };
1569        carve(&mut w, 1, 1);
1570        while let Some(&(cx, cz)) = stack.last() {
1571            let nb: Vec<(i32, i32)> = [(1, 0), (-1, 0), (0, 1), (0, -1)]
1572                .iter()
1573                .map(|(dx, dz)| (cx + dx, cz + dz))
1574                .filter(|&(x, z)| x >= 0 && z >= 0 && x < n && z < n && !seen[(z * n + x) as usize])
1575                .collect();
1576            if nb.is_empty() {
1577                stack.pop();
1578                continue;
1579            }
1580            let (nx, nz) = nb[(rng(&mut s) % nb.len() as u64) as usize];
1581            seen[(nz * n + nx) as usize] = true;
1582            carve(&mut w, 2 * nx + 1, 2 * nz + 1);
1583            carve(&mut w, cx + nx + 1, cz + nz + 1);
1584            stack.push((nx, nz));
1585        }
1586        carve(&mut w, 0, 1);
1587        carve(&mut w, size - 1, size - 2);
1588        let from = [
1589            f64::from(-n - 4) + 0.5,
1590            f64::from(y),
1591            f64::from(n + 4) + 0.5,
1592        ];
1593        let goal = Goal::Near {
1594            pos: [1, y, 1],
1595            radius: 1.0,
1596        };
1597        let d = drive::<P26, _>(&w, from, follower(), goal, 20_000);
1598        eprintln!("26.1 maze 31: {d:?}");
1599        assert_eq!(d.status, FollowStatus::Arrived, "{d:?}");
1600        let air = Goal::Near {
1601            pos: [1, y + 6, 1],
1602            radius: 2.0,
1603        };
1604        let d = drive::<P26, _>(&w, from, follower(), air, 20_000);
1605        assert_eq!(
1606            d.status,
1607            FollowStatus::Failed(FollowError::Plan(PlanError::NoPath)),
1608            "{d:?}"
1609        );
1610        assert_eq!(d.plans, 1, "{d:?}");
1611    }
1612
1613    /// The live attributes drive the look-ahead and the verification: with jump strength 0
1614    /// (a server attribute) a one-block step cannot be climbed, and the follower plans around
1615    /// it instead of jumping in place forever.
1616    #[test]
1617    fn live_attributes_26_1() {
1618        use ghast_physics::modern::AttributeKind;
1619        let stone = id26("stone");
1620        let mut w = ghast_physics::modern::memory_world_26_1();
1621        w.load_chunks(-2, -2, 2, 2);
1622        w.fill_raw([-32, 63, -32], [31, 63, 31], stone);
1623        // A wall one block high across the way, with a gap at z = 6.
1624        w.fill_raw([4, 64, -32], [4, 64, 31], stone);
1625        w.set_raw(4, 64, 6, 0);
1626        let goal = Goal::Block([8, 64, 0]);
1627        // Default attributes: straight over the step.
1628        let d = drive::<P26, _>(&w, [0.5, 64.0, 0.5], follower(), goal.clone(), 2000);
1629        assert_eq!(d.status, FollowStatus::Arrived, "{d:?}");
1630        // No jumping: around through the gap.
1631        let mut io = SimIo::<P26, _>::new(&w, [0.5, 64.0, 0.5]);
1632        io.state
1633            .apply_attribute(AttributeKind::JumpStrength, 0.0, &[]);
1634        let mut f = follower();
1635        f.goto(goal);
1636        let mut through_gap = false;
1637        let mut status = FollowStatus::Moving;
1638        for _ in 0..3000 {
1639            status = f.step(&mut io);
1640            if status != FollowStatus::Moving {
1641                break;
1642            }
1643            io.advance();
1644            let p = io.feet();
1645            through_gap |= p[0].floor() as i32 == 4 && p[2].floor() as i32 == 6;
1646        }
1647        assert_eq!(status, FollowStatus::Arrived, "{:?}", io.feet());
1648        assert!(through_gap, "the step was not avoided");
1649        // Planned around at plan time (the move set follows the attributes), not by repairs.
1650        assert_eq!(f.plans(), 1, "replanned");
1651    }
1652
1653    /// Digging straight down through dirt (the probe's `dig_down_6`), driven by the follower
1654    /// in a client that digs through its crosshair: six digs, each aimed a tick before it
1655    /// starts, and a goal level six blocks down.
1656    #[test]
1657    fn dig_down_6_follower() {
1658        let cfg = Config::default().with_dig(Some(crate::DigCost {
1659            base: 8.0,
1660            ticks_per_hardness: 30.0,
1661            max_hardness: 1.0,
1662        }));
1663        let mut w = flat(2);
1664        w.fill_raw([-3, 64, -3], [3, 69, 3], 3 << 4);
1665        let f = Follower::new(Pathfinder::new(cfg.clone()), FollowConfig::default());
1666        let mut io = SimIo::<P18, _>::new(&w, [0.5, 70.0, 0.5]);
1667        let status = run(&mut io, f, Goal::Block([0, 64, 0]), 2000);
1668        assert_eq!(status, FollowStatus::Arrived, "{:?}", io.feet());
1669        assert_eq!(Pathfinder::start_block(io.feet()), [0, 64, 0]);
1670        // 26.2 (the version the probe runs).
1671        let mut w = ghast_physics::modern::memory_world_26_2();
1672        w.load_chunks(-1, -1, 1, 1);
1673        w.fill_raw([-8, 63, -8], [8, 63, 8], id262("stone"));
1674        w.fill_raw([-3, 64, -3], [3, 69, 3], id262("dirt"));
1675        let f = Follower::new(Pathfinder::new(cfg), FollowConfig::default());
1676        let mut io = SimIo::<P262, _>::new(&w, [0.5, 70.0, 0.5]);
1677        let status = run(&mut io, f, Goal::Y(64), 2000);
1678        assert_eq!(status, FollowStatus::Arrived, "{:?}", io.feet());
1679        assert_eq!(Pathfinder::start_block(io.feet())[1], 64);
1680    }
1681
1682    /// Through a closed oak door (the probe's `door_closed`) and an open one, driven by the
1683    /// follower in a client that clicks through its crosshair; the approach comes in at an
1684    /// angle, so the walk lines up with the door's free side on its own.
1685    #[test]
1686    fn doors_follower() {
1687        for open in [false, true] {
1688            for hinge in ["left", "right"] {
1689                let mut w = ghast_physics::modern::memory_world_26_2();
1690                w.load_chunks(-2, -2, 2, 2);
1691                w.fill_raw([-32, 63, -32], [31, 63, 31], id262("stone"));
1692                w.fill_raw([3, 64, -32], [3, 66, 31], id262("stone"));
1693                for (y, half) in [(64, "lower"), (65, "upper")] {
1694                    w.set_raw(
1695                        3,
1696                        y,
1697                        0,
1698                        id262(&format!(
1699                            "oak_door[facing=east,half={half},hinge={hinge},open={open}]"
1700                        )),
1701                    );
1702                }
1703                let mut io = SimIo::<P262, _>::new(&w, [0.5, 64.0, -3.5]);
1704                let status = run(&mut io, follower(), Goal::Block([7, 64, 2]), 1500);
1705                assert_eq!(
1706                    status,
1707                    FollowStatus::Arrived,
1708                    "open {open} {hinge}: {:?}",
1709                    io.feet()
1710                );
1711                assert_eq!(io.clicks, u32::from(!open), "open {open} {hinge}");
1712            }
1713        }
1714        // 1.8.9: the door's state is split over both halves.
1715        let mut w = flat(2);
1716        w.fill_raw([3, 64, -32], [3, 66, 31], STONE18);
1717        w.set_raw(3, 64, 0, 64 << 4); // lower half: facing east, closed
1718        w.set_raw(3, 65, 0, 64 << 4 | 8); // upper half: left hinge
1719        let mut io = SimIo::<P18, _>::new(&w, [0.5, 64.0, -3.5]);
1720        let status = run(&mut io, follower(), Goal::Block([7, 64, 2]), 1500);
1721        assert_eq!(status, FollowStatus::Arrived, "{:?}", io.feet());
1722        assert_eq!(io.clicks, 1);
1723    }
1724
1725    /// Bridging over a three-wide gap and towering up three blocks (the probe's
1726    /// `bridge_gap_3` and `tower_up_3`), driven by the follower in a client that places only
1727    /// where its crosshair, from the pose the server has, is on the clicked face and the new
1728    /// block clears the player.
1729    #[test]
1730    fn bridge_and_tower_follower() {
1731        let cfg = Config::default().with_place(Some(20.0)).with_parkour(false);
1732        let follower = || Follower::new(Pathfinder::new(cfg.clone()), FollowConfig::default());
1733        // 26.2
1734        let stone = id262("stone");
1735        let mut w = ghast_physics::modern::memory_world_26_2();
1736        w.load_chunks(-2, -2, 2, 2);
1737        w.fill_raw([-8, 63, -8], [1, 63, 8], stone);
1738        w.fill_raw([5, 63, -8], [12, 63, 8], stone);
1739        let mut io = SimIo::<P262, _>::new(&w, [0.5, 64.0, 0.5]);
1740        let status = run(&mut io, follower(), Goal::Block([7, 64, 0]), 2000);
1741        assert_eq!(
1742            status,
1743            FollowStatus::Arrived,
1744            "bridge 26.2: {:?}",
1745            io.feet()
1746        );
1747        assert_eq!(io.places, 3, "bridge 26.2");
1748        assert_eq!(
1749            io.overlapping, 0,
1750            "bridge 26.2: a place overlapped the player"
1751        );
1752        let mut w = ghast_physics::modern::memory_world_26_2();
1753        w.load_chunks(-2, -2, 2, 2);
1754        w.fill_raw([-8, 63, -8], [8, 63, 8], stone);
1755        let mut io = SimIo::<P262, _>::new(&w, [0.5, 64.0, 0.5]);
1756        let status = run(&mut io, follower(), Goal::Block([0, 67, 0]), 2000);
1757        assert_eq!(status, FollowStatus::Arrived, "tower 26.2: {:?}", io.feet());
1758        assert_eq!(io.places, 3, "tower 26.2");
1759        assert_eq!(
1760            io.overlapping, 0,
1761            "tower 26.2: a place overlapped the player"
1762        );
1763        // 1.8.9
1764        let mut w = ghast_physics::v1_8::memory_world();
1765        w.load_chunks(-2, -2, 2, 2);
1766        w.fill_raw([-8, 63, -8], [1, 63, 8], STONE18);
1767        w.fill_raw([5, 63, -8], [12, 63, 8], STONE18);
1768        let mut io = SimIo::<P18, _>::new(&w, [0.5, 64.0, 0.5]);
1769        let status = run(&mut io, follower(), Goal::Block([7, 64, 0]), 2000);
1770        assert_eq!(status, FollowStatus::Arrived, "bridge 1.8: {:?}", io.feet());
1771        let w = flat(2);
1772        let mut io = SimIo::<P18, _>::new(&w, [0.5, 64.0, 0.5]);
1773        let status = run(&mut io, follower(), Goal::Block([0, 67, 0]), 2000);
1774        assert_eq!(status, FollowStatus::Arrived, "tower 1.8: {:?}", io.feet());
1775        assert_eq!(
1776            io.overlapping, 0,
1777            "tower 1.8: a place overlapped the player"
1778        );
1779    }
1780
1781    /// A staircase down through dirt to a goal ten lower and ten away, on 26.2, driven by the
1782    /// follower in a client that digs through its crosshair.
1783    #[test]
1784    fn staircase_follower() {
1785        let cfg = Config::default().with_dig(Some(crate::DigCost {
1786            base: 8.0,
1787            ticks_per_hardness: 30.0,
1788            max_hardness: 1.0,
1789        }));
1790        let mut w = ghast_physics::modern::memory_world_26_2();
1791        w.load_chunks(-2, -2, 2, 2);
1792        w.fill_raw([-32, 63, -32], [31, 63, 31], id262("stone"));
1793        w.fill_raw([-32, 64, -32], [31, 80, 31], id262("dirt"));
1794        w.fill_raw([0, 74, 0], [0, 75, 0], 0);
1795        let f = Follower::new(Pathfinder::new(cfg), FollowConfig::default());
1796        let mut io = SimIo::<P262, _>::new(&w, [0.5, 74.0, 0.5]);
1797        let status = run(&mut io, f, Goal::Block([10, 64, 0]), 6000);
1798        assert_eq!(status, FollowStatus::Arrived, "{:?}", io.feet());
1799    }
1800
1801    /// A closed oak trapdoor at head height in a two-high opening, clicked open through the
1802    /// crosshair (26.2 and 1.8.9).
1803    #[test]
1804    fn trapdoor_follower() {
1805        let mut w = ghast_physics::modern::memory_world_26_2();
1806        w.load_chunks(-2, -2, 2, 2);
1807        w.fill_raw([-32, 63, -32], [31, 63, 31], id262("stone"));
1808        w.fill_raw([3, 64, -32], [3, 66, 31], id262("stone"));
1809        w.set_raw(3, 64, 0, 0);
1810        w.set_raw(
1811            3,
1812            65,
1813            0,
1814            id262("oak_trapdoor[facing=north,half=bottom,open=false]"),
1815        );
1816        let mut io = SimIo::<P262, _>::new(&w, [0.5, 64.0, -2.5]);
1817        let status = run(&mut io, follower(), Goal::Block([6, 64, 0]), 1500);
1818        assert_eq!(status, FollowStatus::Arrived, "{:?}", io.feet());
1819        assert_eq!(io.clicks, 1);
1820        let mut w = flat(2);
1821        w.fill_raw([3, 64, -32], [3, 66, 31], STONE18);
1822        w.set_raw(3, 64, 0, 0);
1823        w.set_raw(3, 65, 0, 96 << 4); // trapdoor, facing north, bottom half, closed
1824        let mut io = SimIo::<P18, _>::new(&w, [0.5, 64.0, -2.5]);
1825        let status = run(&mut io, follower(), Goal::Block([6, 64, 0]), 1500);
1826        assert_eq!(status, FollowStatus::Arrived, "{:?}", io.feet());
1827        assert_eq!(io.clicks, 1);
1828    }
1829
1830    /// A 26.2 block's state id.
1831    pub(crate) fn id262(spec: &str) -> u16 {
1832        ghast_data::v26_2::BlockState::parse(spec)
1833            .unwrap_or_else(|| panic!("{spec}"))
1834            .id()
1835    }
1836
1837    /// Drives a follower in `io` to `goal` for at most `max` ticks.
1838    pub(crate) fn run<P: Physics, W: BlockSource>(
1839        io: &mut SimIo<'_, P, W>,
1840        mut f: Follower,
1841        goal: Goal,
1842        max: u32,
1843    ) -> FollowStatus {
1844        f.goto(goal);
1845        let mut status = FollowStatus::Moving;
1846        for _ in 0..max {
1847            status = f.step(io);
1848            if status != FollowStatus::Moving {
1849                break;
1850            }
1851            io.advance();
1852        }
1853        status
1854    }
1855
1856    fn run_corridor<P: Physics, W: BlockSource>(w: &W) {
1857        let d = drive::<P, _>(
1858            w,
1859            [62.5, 4.0, 0.5],
1860            follower(),
1861            Goal::Xz { x: 119, z: 0 },
1862            4000,
1863        );
1864        eprintln!("{:?} east: {d:?}", P::VERSION);
1865        assert_eq!(d.status, FollowStatus::Arrived, "{d:?}");
1866        let d = drive::<P, _>(w, d.end, follower(), Goal::Xz { x: 62, z: 0 }, 4000);
1867        eprintln!("{:?} west: {d:?}", P::VERSION);
1868        assert_eq!(d.status, FollowStatus::Arrived, "{d:?}");
1869    }
1870}
1871
1872/// 26.3: the follower through the blocks new in 26.3, in the simulated client of
1873/// [`tests`] (clicks, digs and places through the crosshair of the pose the server has).
1874#[cfg(all(
1875    test,
1876    feature = "v1_8",
1877    feature = "v1_12_2",
1878    feature = "v1_16_5",
1879    feature = "v26_3"
1880))]
1881mod tests_26_3 {
1882    use super::tests::{SimIo, run};
1883    use super::{FollowConfig, FollowStatus, Follower};
1884    use crate::Goal;
1885    use crate::physics::P263;
1886    use crate::plan::{Config, Pathfinder};
1887
1888    fn id(spec: &str) -> u16 {
1889        ghast_data::v26_3::BlockState::parse(spec)
1890            .unwrap_or_else(|| panic!("{spec}"))
1891            .id()
1892    }
1893
1894    fn follower() -> Follower {
1895        Follower::new(Pathfinder::new(Config::default()), FollowConfig::default())
1896    }
1897
1898    /// Stone floor at y = 63 and a stone wall at x = 3 (y 64..=66) with an opening at z = 0.
1899    fn walled() -> ghast_physics::modern::MemoryWorld263 {
1900        let mut w = ghast_physics::modern::memory_world_26_3();
1901        w.load_chunks(-2, -2, 2, 2);
1902        w.fill_raw([-32, 63, -32], [31, 63, 31], id("stone"));
1903        w.fill_raw([3, 64, -32], [3, 66, 31], id("stone"));
1904        w.fill_raw([3, 64, 0], [3, 65, 0], 0);
1905        w
1906    }
1907
1908    /// A closed and an open poplar door, both hinges.
1909    #[test]
1910    fn poplar_door() {
1911        for open in [false, true] {
1912            for hinge in ["left", "right"] {
1913                let mut w = walled();
1914                for (y, half) in [(64, "lower"), (65, "upper")] {
1915                    w.set_raw(
1916                        3,
1917                        y,
1918                        0,
1919                        id(&format!(
1920                            "poplar_door[facing=east,half={half},hinge={hinge},open={open}]"
1921                        )),
1922                    );
1923                }
1924                let mut io = SimIo::<P263, _>::new(&w, [0.5, 64.0, -3.5]);
1925                let status = run(&mut io, follower(), Goal::Block([7, 64, 2]), 1500);
1926                assert_eq!(
1927                    status,
1928                    FollowStatus::Arrived,
1929                    "open {open} {hinge}: {:?}",
1930                    io.feet()
1931                );
1932                assert_eq!(io.clicks, u32::from(!open), "open {open} {hinge}");
1933            }
1934        }
1935    }
1936
1937    /// A closed poplar fence gate in a poplar fence (1.5 high: no jumping over it).
1938    #[test]
1939    fn poplar_fence_gate() {
1940        let mut w = ghast_physics::modern::memory_world_26_3();
1941        w.load_chunks(-2, -2, 2, 2);
1942        w.fill_raw([-32, 63, -32], [31, 63, 31], id("stone"));
1943        w.fill_raw(
1944            [3, 64, -32],
1945            [3, 64, 31],
1946            id("poplar_fence[east=false,north=true,south=true,waterlogged=false,west=false]"),
1947        );
1948        w.set_raw(
1949            3,
1950            64,
1951            0,
1952            id("poplar_fence_gate[facing=east,in_wall=false,open=false,powered=false]"),
1953        );
1954        let mut io = SimIo::<P263, _>::new(&w, [0.5, 64.0, -2.5]);
1955        let status = run(&mut io, follower(), Goal::Block([7, 64, 1]), 1500);
1956        assert_eq!(status, FollowStatus::Arrived, "{:?}", io.feet());
1957        assert_eq!(io.clicks, 1);
1958    }
1959
1960    /// A closed poplar trapdoor at head height in a two-high opening.
1961    #[test]
1962    fn poplar_trapdoor() {
1963        let mut w = walled();
1964        w.set_raw(
1965            3,
1966            65,
1967            0,
1968            id("poplar_trapdoor[facing=north,half=bottom,open=false,powered=false,waterlogged=false]"),
1969        );
1970        let mut io = SimIo::<P263, _>::new(&w, [0.5, 64.0, -2.5]);
1971        let status = run(&mut io, follower(), Goal::Block([6, 64, 0]), 1500);
1972        assert_eq!(status, FollowStatus::Arrived, "{:?}", io.feet());
1973        assert_eq!(io.clicks, 1);
1974    }
1975
1976    /// Up a staircase of half steps (concrete slabs, bottom and double) and the matching
1977    /// concrete stairs, to a goal three blocks higher.
1978    #[test]
1979    fn concrete_slab_staircase() {
1980        let bottom = id("white_concrete_slab[type=bottom,waterlogged=false]");
1981        let double = id("white_concrete_slab[type=double,waterlogged=false]");
1982        let stairs =
1983            id("red_concrete_stairs[facing=east,half=bottom,shape=straight,waterlogged=false]");
1984        for (name, step) in [("slabs", None), ("stairs", Some(stairs))] {
1985            let mut w = ghast_physics::modern::memory_world_26_3();
1986            w.load_chunks(-2, -2, 2, 2);
1987            w.fill_raw([-32, 63, -32], [31, 63, 31], id("stone"));
1988            // x = 2k + 2: a half step at height k, x = 2k + 3: a full block (k = 0, 1, 2).
1989            for k in 0..3 {
1990                let x = 2 * k + 2;
1991                w.fill_raw([x, 64, -1], [x + 1, 63 + k, 1], double);
1992                w.fill_raw([x, 64 + k, -1], [x, 64 + k, 1], step.unwrap_or(bottom));
1993                w.fill_raw([x + 1, 64 + k, -1], [x + 1, 64 + k, 1], double);
1994            }
1995            w.fill_raw([8, 64, -1], [10, 66, 1], double);
1996            let mut io = SimIo::<P263, _>::new(&w, [0.5, 64.0, 0.5]);
1997            let status = run(&mut io, follower(), Goal::Block([9, 67, 0]), 2000);
1998            assert_eq!(status, FollowStatus::Arrived, "{name}: {:?}", io.feet());
1999        }
2000    }
2001
2002    /// Shelf mushrooms (ledges at y 0.375..0.6875 that bounce 0.75): the planner does not
2003    /// stand on a partial block that floats above its cell's bottom (`moves::spot`), so a
2004    /// mushroom is an obstacle: walked around in the open, and no plan when it is the only
2005    /// step onto a platform 1.5 high (a bottom slab in its place is climbed, see the check).
2006    #[test]
2007    fn shelf_mushroom_is_an_obstacle() {
2008        let mut w = ghast_physics::modern::memory_world_26_3();
2009        w.load_chunks(-2, -2, 2, 2);
2010        w.fill_raw([-32, 63, -32], [31, 63, 31], id("stone"));
2011        w.fill_raw(
2012            [3, 64, -1],
2013            [3, 64, 1],
2014            id("shelf_mushroom[age=1,facing=west]"),
2015        );
2016        let mut io = SimIo::<P263, _>::new(&w, [0.5, 64.0, 0.5]);
2017        let status = run(&mut io, follower(), Goal::Block([7, 64, 0]), 1500);
2018        assert_eq!(status, FollowStatus::Arrived, "around: {:?}", io.feet());
2019
2020        for (step, arrives) in [
2021            ("shelf_mushroom[age=1,facing=west]", false),
2022            ("smooth_stone_slab[type=bottom,waterlogged=false]", true),
2023        ] {
2024            let mut w = ghast_physics::modern::memory_world_26_3();
2025            w.load_chunks(-2, -2, 2, 2);
2026            w.fill_raw([-32, 63, -32], [31, 63, 31], id("stone"));
2027            w.fill_raw([4, 64, -32], [10, 64, 31], id("stone"));
2028            w.fill_raw(
2029                [4, 65, -32],
2030                [10, 65, 31],
2031                id("smooth_stone_slab[type=bottom,waterlogged=false]"),
2032            );
2033            w.set_raw(3, 64, 0, id(step));
2034            let mut io = SimIo::<P263, _>::new(&w, [0.5, 64.0, 0.5]);
2035            let status = run(&mut io, follower(), Goal::Block([6, 65, 0]), 2000);
2036            assert_eq!(
2037                status == FollowStatus::Arrived,
2038                arrives,
2039                "{step}: {status:?} {:?}",
2040                io.feet()
2041            );
2042        }
2043    }
2044}