1use 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
17pub(crate) trait Io {
20 type World<'w>: BlockSource + ?Sized
22 where
23 Self: 'w;
24 fn world(&self) -> &Self::World<'_>;
26 fn version(&self) -> Option<Version>;
28 fn observation(&self) -> Observation;
30 fn moved_by_server(&self) -> bool;
32 fn is_dead(&self) -> bool;
34 fn set_aim(&mut self, yaw: f32, pitch: f32);
36 fn planned_look(&self) -> (f32, f32);
38 fn set_keys(&mut self, keys: Keys);
40 fn left_button(&self) -> bool;
42 fn set_left_button(&mut self, on: bool);
44 fn targets(&self, block: [i32; 3]) -> bool;
46 fn place_against(&mut self, against: [i32; 3], dir: [i32; 3]) -> bool;
49 fn activate(&mut self, block: [i32; 3]) -> bool;
52 #[cfg(ghast_modern)]
54 fn modern_player(&self) -> Option<&ghast_physics::modern::PlayerState> {
55 None
56 }
57 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
67struct 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
94fn 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#[derive(Clone, Debug, PartialEq)]
205#[non_exhaustive]
206pub struct FollowConfig {
207 pub controller: ControllerConfig,
209 pub max_replans: u32,
212 pub verify: bool,
215 pub budget: Budget,
220 pub verify_ticks: u32,
223 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 #[must_use]
245 pub fn with_controller(mut self, c: ControllerConfig) -> Self {
246 self.controller = c;
247 self
248 }
249
250 #[must_use]
252 pub fn with_max_replans(mut self, n: u32) -> Self {
253 self.max_replans = n;
254 self
255 }
256
257 #[must_use]
269 pub fn with_movement_only(mut self, on: bool) -> Self {
270 self.movement_only = on;
271 self
272 }
273
274 #[must_use]
276 pub fn with_verify(mut self, on: bool) -> Self {
277 self.verify = on;
278 self
279 }
280
281 #[must_use]
283 pub fn with_budget(mut self, budget: Budget) -> Self {
284 self.budget = budget;
285 self
286 }
287
288 #[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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
298#[non_exhaustive]
299pub enum FollowError {
300 Plan(PlanError),
302 GaveUp,
304 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
324#[non_exhaustive]
325pub enum FollowStatus {
326 Idle,
328 Moving,
330 Arrived,
332 Failed(FollowError),
334}
335
336#[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 partial_best: f64,
378 unreachable: bool,
381 place_wait: u32,
383 digging: bool,
384 plans: u64,
385 planning: Option<Planning>,
387 plan_ticks: u32,
389 goal_loaded: Option<bool>,
391 aimed: bool,
393}
394
395#[derive(Clone, Debug)]
397enum Planning {
398 Search {
399 search: Box<Search>,
400 bans: HashSet<([i32; 3], [i32; 3])>,
402 attempt: u32,
403 last: Option<(Path, bool)>,
406 },
407 Verify {
408 sim: Box<Simulation>,
409 bans: HashSet<([i32; 3], [i32; 3])>,
410 attempt: u32,
411 exhausted: bool,
413 },
414}
415
416fn 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
426fn 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
436const VERIFY_ATTEMPTS: u32 = 3;
438
439fn 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 #[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 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 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 #[must_use]
496 pub fn goal(&self) -> Option<&Goal> {
497 self.goal.as_ref()
498 }
499
500 #[must_use]
502 pub fn status(&self) -> FollowStatus {
503 self.status
504 }
505
506 #[must_use]
508 pub fn path(&self) -> Option<&crate::Path> {
509 self.ctrl.as_ref().map(Controller::path)
510 }
511
512 #[must_use]
515 pub fn waypoint(&self) -> Option<[f64; 3]> {
516 self.ctrl.as_ref().and_then(Controller::waypoint)
517 }
518
519 #[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 #[must_use]
528 pub fn aiming(&self) -> bool {
529 self.aimed
530 }
531
532 #[must_use]
534 pub fn plans(&self) -> u64 {
535 self.plans
536 }
537
538 #[must_use]
541 pub fn is_planning(&self) -> bool {
542 self.planning.is_some()
543 }
544
545 #[must_use]
548 pub fn plan_ticks(&self) -> u32 {
549 self.plan_ticks
550 }
551
552 #[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 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 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 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 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 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 pub fn tick(&mut self, ctx: &mut TickContext<'_>) -> FollowStatus {
724 self.step(ctx)
725 }
726
727 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 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 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 return self.fail(ctx, FollowError::Plan(PlanError::NoPath));
794 }
795 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 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 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 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 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 pending: Vec<(u32, [i32; 3], u32)>,
916 pub(crate) places: u32,
918 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 pub(crate) fn advance(&mut self) {
951 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 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 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 #[derive(Debug)]
1157 pub(crate) struct Drive {
1158 pub(crate) status: FollowStatus,
1159 pub(crate) ticks: u32,
1160 pub(crate) planning_ticks: u32,
1162 pub(crate) worst_tick: Duration,
1164 pub(crate) plans: u64,
1165 pub(crate) end: [f64; 3],
1166 }
1167
1168 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 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 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 pub(crate) fn flat(r: i32) -> ghast_physics::v1_8::MemoryWorld {
1263 flat_in(ghast_physics::v1_8::memory_world(), r)
1264 }
1265
1266 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 #[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 #[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 #[test]
1366 fn unreachable_goals_end_after_one_search() {
1367 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 #[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 #[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 #[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 #[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 fn id26(spec: &str) -> u16 {
1512 ghast_data::v26_1::BlockState::parse(spec)
1513 .unwrap_or_else(|| panic!("{spec}"))
1514 .id()
1515 }
1516
1517 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 #[test]
1547 fn the_lab_parkour_corridor_26_1() {
1548 run_corridor::<P26, _>(&corridor_26());
1549 }
1550
1551 #[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 #[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 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 let d = drive::<P26, _>(&w, [0.5, 64.0, 0.5], follower(), goal.clone(), 2000);
1629 assert_eq!(d.status, FollowStatus::Arrived, "{d:?}");
1630 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 assert_eq!(f.plans(), 1, "replanned");
1651 }
1652
1653 #[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 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 #[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 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); w.set_raw(3, 65, 0, 64 << 4 | 8); 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 #[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 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 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 #[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 #[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); 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 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 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#[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 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 #[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 #[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 #[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 #[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 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 #[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}