use std::collections::HashSet;
use std::time::{Duration, Instant};
use ghast_client::{BlockPos, Buttons, Controls, Face, TickContext};
use ghast_physics::Keys;
use crate::Version;
use crate::control::{Controller, ControllerConfig, Progress};
use crate::goal::Goal;
use crate::physics::Observation;
use crate::plan::{Budget, Path, Pathfinder, PlanError, Search};
use crate::sim::{SimOutcome, Simulation};
use crate::world::BlockSource;
pub(crate) trait Io {
type World<'w>: BlockSource + ?Sized
where
Self: 'w;
fn world(&self) -> &Self::World<'_>;
fn version(&self) -> Option<Version>;
fn observation(&self) -> Observation;
fn moved_by_server(&self) -> bool;
fn is_dead(&self) -> bool;
fn set_aim(&mut self, yaw: f32, pitch: f32);
fn planned_look(&self) -> (f32, f32);
fn set_keys(&mut self, keys: Keys);
fn left_button(&self) -> bool;
fn set_left_button(&mut self, on: bool);
fn targets(&self, block: [i32; 3]) -> bool;
fn place_against(&mut self, against: [i32; 3], dir: [i32; 3]) -> bool;
fn activate(&mut self, block: [i32; 3]) -> bool;
#[cfg(ghast_modern)]
fn modern_player(&self) -> Option<&ghast_physics::modern::PlayerState> {
None
}
fn build_height(&self) -> Option<(i32, i32)> {
#[cfg(ghast_modern)]
if let Some(p) = self.modern_player() {
return Some((p.level.min_y, p.level.height));
}
None
}
}
struct Height<'a, W: ?Sized> {
world: &'a W,
height: Option<(i32, i32)>,
}
impl<W: BlockSource + ?Sized> BlockSource for Height<'_, W> {
#[inline]
fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32> {
if let Some((lo, h)) = self.height
&& (y < lo || y >= lo + h)
{
return None;
}
self.world.raw_block(x, y, z)
}
#[inline]
fn is_column_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool {
self.world.is_column_loaded(chunk_x, chunk_z)
}
fn build_height(&self) -> Option<(i32, i32)> {
self.height.or_else(|| self.world.build_height())
}
}
fn world_of<I: Io + ?Sized>(ctx: &I) -> Height<'_, I::World<'_>> {
Height {
world: ctx.world(),
height: ctx.build_height(),
}
}
impl Io for TickContext<'_> {
type World<'w>
= dyn ghast_client::WorldView + 'w
where
Self: 'w;
fn world(&self) -> &Self::World<'_> {
TickContext::world(self)
}
fn version(&self) -> Option<Version> {
Version::from_game(TickContext::version(self))
}
fn observation(&self) -> Observation {
let pose = *self.pose();
Observation {
pos: [pose.pos.x, pose.pos.y, pose.pos.z],
vel: [pose.motion.x, pose.motion.y, pose.motion.z],
on_ground: pose.on_ground,
yaw: pose.yaw,
pitch: pose.pitch,
sprinting: pose.sprinting,
food: self.health().food,
}
}
fn moved_by_server(&self) -> bool {
!self.events().teleports.is_empty() || self.events().respawned
}
fn is_dead(&self) -> bool {
TickContext::is_dead(self)
}
fn set_aim(&mut self, yaw: f32, pitch: f32) {
TickContext::set_aim(self, yaw, pitch);
}
fn planned_look(&self) -> (f32, f32) {
TickContext::planned_look(self)
}
fn set_keys(&mut self, k: Keys) {
self.set_controls(Controls {
forward: k.forward,
back: k.back,
left: k.left,
right: k.right,
jump: k.jump,
sneak: k.sneak,
sprint: k.sprint,
});
}
fn left_button(&self) -> bool {
self.buttons().left
}
fn set_left_button(&mut self, on: bool) {
self.set_buttons(Buttons {
left: on,
right: false,
});
}
fn targets(&self, block: [i32; 3]) -> bool {
let pos = BlockPos::new(block[0], block[1], block[2]);
self.target().is_some_and(|t| t.pos == pos)
}
fn place_against(&mut self, against: [i32; 3], dir: [i32; 3]) -> bool {
let face = match dir {
[0, -1, 0] => Face::Down,
[0, 0, -1] => Face::North,
[0, 0, 1] => Face::South,
[-1, 0, 0] => Face::West,
[1, 0, 0] => Face::East,
_ => Face::Up,
};
let against = BlockPos::new(against[0], against[1], against[2]);
match self.target().filter(|t| t.pos == against && t.face == face) {
Some(hit) => self.place(against, face, hit.hit),
None => false,
}
}
fn activate(&mut self, block: [i32; 3]) -> bool {
let pos = BlockPos::new(block[0], block[1], block[2]);
match self.target().filter(|t| t.pos == pos) {
Some(hit) => self.place(pos, hit.face, hit.hit),
None => false,
}
}
#[cfg(ghast_modern)]
fn modern_player(&self) -> Option<&ghast_physics::modern::PlayerState> {
TickContext::modern_player(self)
}
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct FollowConfig {
pub controller: ControllerConfig,
pub max_replans: u32,
pub verify: bool,
pub budget: Budget,
pub verify_ticks: u32,
pub movement_only: bool,
}
impl Default for FollowConfig {
fn default() -> Self {
FollowConfig {
controller: ControllerConfig::default(),
max_replans: 8,
verify: true,
budget: Budget::nodes(2000).with_time(Duration::from_millis(5)),
verify_ticks: 400,
movement_only: false,
}
}
}
impl FollowConfig {
#[must_use]
pub fn with_controller(mut self, c: ControllerConfig) -> Self {
self.controller = c;
self
}
#[must_use]
pub fn with_max_replans(mut self, n: u32) -> Self {
self.max_replans = n;
self
}
#[must_use]
pub fn with_movement_only(mut self, on: bool) -> Self {
self.movement_only = on;
self
}
#[must_use]
pub fn with_verify(mut self, on: bool) -> Self {
self.verify = on;
self
}
#[must_use]
pub fn with_budget(mut self, budget: Budget) -> Self {
self.budget = budget;
self
}
#[must_use]
pub fn with_verify_ticks(mut self, ticks: u32) -> Self {
self.verify_ticks = ticks.max(1);
self
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum FollowError {
Plan(PlanError),
GaveUp,
UnsupportedVersion,
}
impl std::fmt::Display for FollowError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
FollowError::Plan(e) => write!(f, "planning failed: {e}"),
FollowError::GaveUp => f.write_str("gave up after too many replans"),
FollowError::UnsupportedVersion => {
f.write_str("the path finder does not support this game version")
}
}
}
}
impl std::error::Error for FollowError {}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum FollowStatus {
Idle,
Moving,
Arrived,
Failed(FollowError),
}
#[derive(Clone, Debug)]
pub struct Follower {
pf: Pathfinder,
cfg: FollowConfig,
goal: Option<Goal>,
ctrl: Option<Controller>,
status: FollowStatus,
replans: u32,
banned: HashSet<([i32; 3], [i32; 3])>,
partial_best: f64,
unreachable: bool,
place_wait: u32,
digging: bool,
plans: u64,
planning: Option<Planning>,
plan_ticks: u32,
goal_loaded: Option<bool>,
aimed: bool,
}
#[derive(Clone, Debug)]
enum Planning {
Search {
search: Box<Search>,
bans: HashSet<([i32; 3], [i32; 3])>,
attempt: u32,
last: Option<(Path, bool)>,
},
Verify {
sim: Box<Simulation>,
bans: HashSet<([i32; 3], [i32; 3])>,
attempt: u32,
exhausted: bool,
},
}
fn with_player<I: Io + ?Sized>(ctx: &I, search: Search) -> Search {
#[cfg(ghast_modern)]
if let Some(p) = ctx.modern_player() {
return search.with_modern_player(p);
}
let _ = ctx;
search
}
fn new_sim<I: Io + ?Sized>(ctx: &I, path: &Path, cfg: &ControllerConfig) -> Simulation {
#[cfg(ghast_modern)]
if let Some(p) = ctx.modern_player() {
return Simulation::with_modern_player(path, cfg, p);
}
let _ = ctx;
Simulation::new(path, cfg)
}
const VERIFY_ATTEMPTS: u32 = 3;
fn goal_loaded<W: BlockSource + ?Sized>(goal: &Goal, world: &W) -> bool {
match goal {
Goal::Block(p) | Goal::Near { pos: p, .. } => world.is_column_loaded(p[0] >> 4, p[2] >> 4),
Goal::Xz { x, z } => world.is_column_loaded(x >> 4, z >> 4),
Goal::Y(_) => false,
Goal::AnyOf(gs) => !gs.is_empty() && gs.iter().all(|g| goal_loaded(g, world)),
}
}
impl Follower {
#[must_use]
pub fn new(pathfinder: Pathfinder, cfg: FollowConfig) -> Self {
Follower {
pf: pathfinder,
cfg,
goal: None,
ctrl: None,
status: FollowStatus::Idle,
replans: 0,
banned: HashSet::new(),
partial_best: f64::INFINITY,
unreachable: false,
place_wait: 0,
digging: false,
plans: 0,
planning: None,
plan_ticks: 0,
goal_loaded: None,
aimed: false,
}
}
pub fn goto(&mut self, goal: Goal) {
self.goal = Some(goal);
self.ctrl = None;
self.planning = None;
self.status = FollowStatus::Moving;
self.replans = 0;
self.banned.clear();
self.partial_best = f64::INFINITY;
self.unreachable = false;
}
pub fn stop(&mut self, ctx: &mut TickContext<'_>) {
self.goal = None;
self.ctrl = None;
self.planning = None;
self.status = FollowStatus::Idle;
self.release(ctx);
}
#[must_use]
pub fn goal(&self) -> Option<&Goal> {
self.goal.as_ref()
}
#[must_use]
pub fn status(&self) -> FollowStatus {
self.status
}
#[must_use]
pub fn path(&self) -> Option<&crate::Path> {
self.ctrl.as_ref().map(Controller::path)
}
#[must_use]
pub fn waypoint(&self) -> Option<[f64; 3]> {
self.ctrl.as_ref().and_then(Controller::waypoint)
}
#[must_use]
pub fn current_move(&self) -> Option<([i32; 3], [i32; 3])> {
self.ctrl.as_ref().and_then(Controller::current_move)
}
#[must_use]
pub fn aiming(&self) -> bool {
self.aimed
}
#[must_use]
pub fn plans(&self) -> u64 {
self.plans
}
#[must_use]
pub fn is_planning(&self) -> bool {
self.planning.is_some()
}
#[must_use]
pub fn plan_ticks(&self) -> u32 {
self.plan_ticks
}
#[must_use]
pub fn pathfinder(&self) -> &Pathfinder {
&self.pf
}
fn release<I: Io + ?Sized>(&mut self, ctx: &mut I) {
ctx.set_keys(Keys::NONE);
if self.digging || ctx.left_button() {
ctx.set_left_button(false);
}
self.digging = false;
}
fn fail<I: Io + ?Sized>(&mut self, ctx: &mut I, e: FollowError) -> FollowStatus {
self.ctrl = None;
self.planning = None;
self.status = FollowStatus::Failed(e);
self.release(ctx);
self.status
}
fn start_plan<I: Io + ?Sized>(&mut self, ctx: &I, version: Version) {
let goal = self.goal.clone().expect("planning without a goal");
let start = Pathfinder::start_block(ctx.observation().pos);
self.plans += 1;
self.plan_ticks = 0;
self.planning = Some(Planning::Search {
search: Box::new(with_player(
ctx,
self.pf.search(version, start, goal, self.banned.clone()),
)),
bans: HashSet::new(),
attempt: 0,
last: None,
});
}
fn work<I: Io + ?Sized>(&mut self, ctx: &I) -> Result<Option<Controller>, PlanError> {
self.plan_ticks += 1;
let t0 = Instant::now();
let left = |budget: Option<Duration>| budget.map(|b| b.saturating_sub(t0.elapsed()));
loop {
if let Some(max) = self.cfg.budget.time
&& t0.elapsed() >= max
{
return Ok(None);
}
let Some(phase) = self.planning.take() else {
return Ok(None);
};
match phase {
Planning::Search {
mut search,
bans,
attempt,
last,
} => {
let budget = Budget {
nodes: self.cfg.budget.nodes,
time: left(self.cfg.budget.time),
};
match search.step(&world_of(ctx), budget) {
None => {
self.planning = Some(Planning::Search {
search,
bans,
attempt,
last,
});
return Ok(None);
}
Some(Err(e)) => match last {
Some((p, ex)) => return Ok(Some(self.ready(p, ex))),
None => return Err(e),
},
Some(Ok(path)) => {
let exhausted = search.exhausted();
if !self.cfg.verify {
return Ok(Some(self.ready(path, exhausted)));
}
let sim = new_sim(ctx, &path, &self.cfg.controller);
self.planning = Some(Planning::Verify {
sim: Box::new(sim),
bans,
attempt,
exhausted,
});
}
}
}
Planning::Verify {
mut sim,
mut bans,
attempt,
exhausted,
} => {
let Some((outcome, reached)) = sim
.step(
&world_of(ctx),
self.cfg.verify_ticks,
left(self.cfg.budget.time),
)
.map(|r| (r.outcome, r.reached))
else {
self.planning = Some(Planning::Verify {
sim,
bans,
attempt,
exhausted,
});
return Ok(None);
};
let path = sim.path();
if outcome == SimOutcome::Arrived {
let path = path.clone();
return Ok(Some(self.ready(path, exhausted)));
}
let k = (reached + 1).min(path.steps.len() - 1);
let m = (path.steps[k.saturating_sub(1)].pos, path.steps[k].pos);
log::debug!("pathfinder: simulation {outcome:?} on move {m:?}");
if k == 0 || attempt + 1 >= VERIFY_ATTEMPTS || !bans.insert(m) {
let path = path.clone();
return Ok(Some(self.ready(path, exhausted)));
}
let goal = self.goal.clone().expect("planning without a goal");
let mut all = self.banned.clone();
all.extend(bans.iter().copied());
let search = with_player(
ctx,
self.pf.search(path.version, path.steps[0].pos, goal, all),
);
self.planning = Some(Planning::Search {
search: Box::new(search),
bans,
attempt: attempt + 1,
last: Some((path.clone(), exhausted)),
});
}
}
}
}
fn ready(&mut self, path: Path, exhausted: bool) -> Controller {
self.unreachable = path.partial && exhausted && self.goal_loaded.unwrap_or(false);
log::debug!(
"pathfinder: {} steps, cost {:.0} ticks, {} nodes{}, planned in {} ticks",
path.steps.len(),
path.cost,
path.expanded,
if self.unreachable {
", partial (goal unreachable)"
} else if path.partial {
", partial"
} else {
""
},
self.plan_ticks
);
self.planning = None;
Controller::new(path, self.cfg.controller.clone())
}
pub fn tick(&mut self, ctx: &mut TickContext<'_>) -> FollowStatus {
self.step(ctx)
}
pub(crate) fn step<I: Io + ?Sized>(&mut self, ctx: &mut I) -> FollowStatus {
if self.goal.is_none() || !matches!(self.status, FollowStatus::Moving) {
return self.status;
}
if ctx.moved_by_server() {
self.ctrl = None;
self.planning = None;
}
if ctx.is_dead() {
self.release(ctx);
return self.status;
}
if self.ctrl.is_none() {
if self.planning.is_none() {
let Some(version) = ctx.version() else {
return self.fail(ctx, FollowError::UnsupportedVersion);
};
self.goal_loaded = self.goal.as_ref().map(|g| goal_loaded(g, ctx.world()));
self.start_plan(ctx, version);
}
match self.work(ctx) {
Ok(Some(c)) => self.ctrl = Some(c),
Ok(None) => {
self.release(ctx);
return self.status;
}
Err(e) => return self.fail(ctx, FollowError::Plan(e)),
}
}
let obs = ctx.observation();
let ctrl = self.ctrl.as_mut().expect("planned above");
#[cfg(ghast_modern)]
if let Some(p) = ctx.modern_player() {
ctrl.set_modern_player(p);
}
let (yaw, pitch) = ctrl.aim(&obs, &world_of(ctx));
let done = matches!(
ctrl.progress(),
Progress::Arrived | Progress::Stuck | Progress::OffPath
);
let steer = self.cfg.movement_only && !ctrl.needs_look();
self.aimed = !done && !steer;
if self.aimed {
ctx.set_aim(yaw, pitch);
}
let look = ctx.planned_look();
let cmd = if steer {
let mut cmd = ctrl.keys(&obs, (yaw, look.1), &world_of(ctx));
cmd.keys = ctrl.steer_keys(&obs, cmd.keys, look, &world_of(ctx));
cmd
} else {
ctrl.keys(&obs, look, &world_of(ctx))
};
match ctrl.progress() {
Progress::Arrived => {
let path = ctrl.path();
if !path.partial {
self.release(ctx);
self.status = FollowStatus::Arrived;
return self.status;
}
if self.unreachable {
return self.fail(ctx, FollowError::Plan(PlanError::NoPath));
}
let goal = self.goal.as_ref().expect("following without a goal");
let d = path
.steps
.last()
.map_or(f64::INFINITY, |s| goal.distance(s.pos));
if d < self.partial_best - 0.5 {
self.partial_best = d;
} else {
self.replans += 1;
}
self.ctrl = None;
self.release(ctx);
if self.replans > self.cfg.max_replans {
return self.fail(ctx, FollowError::GaveUp);
}
return self.status;
}
Progress::Stuck | Progress::OffPath => {
if let Some(m) = ctrl.current_move() {
log::debug!(
"pathfinder: {:?} on move {m:?}, replanning",
ctrl.progress()
);
self.banned.insert(m);
}
self.ctrl = None;
self.replans += 1;
self.release(ctx);
if self.replans > self.cfg.max_replans {
return self.fail(ctx, FollowError::GaveUp);
}
return self.status;
}
Progress::Moving | Progress::Working => {}
}
ctx.set_keys(cmd.keys);
if let Some(d) = cmd.dig {
let on = ctx.targets(d);
ctx.set_left_button(on);
self.digging = true;
} else if self.digging {
ctx.set_left_button(false);
self.digging = false;
}
if let Some(p) = cmd.place {
if self.place_wait > 0 {
self.place_wait -= 1;
} else if ctx.place_against(p.against, p.face()) {
self.place_wait = 10;
}
} else if let Some(b) = cmd.interact {
if self.place_wait > 0 {
self.place_wait -= 1;
} else if ctx.activate(b) {
self.place_wait = 20;
}
} else {
self.place_wait = 0;
}
self.status
}
}
#[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
pub(crate) mod tests {
use std::time::{Duration, Instant};
use ghast_physics::Keys;
use super::{FollowConfig, FollowError, FollowStatus, Follower, Io};
use crate::physics::{Observation, P12, P16, P18, P26, P262, Physics, SourceView};
use crate::plan::{Config, Pathfinder, PlanError};
use crate::sim::Turner;
use crate::world::BlockSource;
use crate::{Goal, Version};
pub(crate) struct Overlay<'w, W> {
base: &'w W,
set: std::collections::HashMap<[i32; 3], u32>,
}
impl<W: BlockSource> BlockSource for Overlay<'_, W> {
fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32> {
match self.set.get(&[x, y, z]) {
Some(&r) => Some(r),
None => self.base.raw_block(x, y, z),
}
}
fn is_column_loaded(&self, cx: i32, cz: i32) -> bool {
self.base.is_column_loaded(cx, cz)
}
fn build_height(&self) -> Option<(i32, i32)> {
self.base.build_height()
}
}
pub(crate) struct SimIo<'w, P: Physics, W: BlockSource> {
pub(crate) world: Overlay<'w, W>,
pub(crate) state: P::State,
turner: Turner,
aim: (f32, f32),
keys: Keys,
left: bool,
digging: Option<([i32; 3], u32)>,
pending: Vec<(u32, [i32; 3], u32)>,
pub(crate) places: u32,
pub(crate) overlapping: u32,
pub(crate) clicks: u32,
}
impl<'w, P: Physics, W: BlockSource> SimIo<'w, P, W> {
pub(crate) fn new(world: &'w W, feet: [f64; 3]) -> Self {
let mut state = P::new_state(feet, 0.0, 0.0);
let view = SourceView::<P, W>::new(world);
for _ in 0..3 {
P::tick(&mut state, Keys::NONE, 0.0, 0.0, &view);
}
SimIo {
world: Overlay {
base: world,
set: std::collections::HashMap::new(),
},
state,
turner: Turner::default(),
aim: (0.0, 0.0),
keys: Keys::NONE,
left: false,
digging: None,
pending: Vec::new(),
places: 0,
overlapping: 0,
clicks: 0,
}
}
pub(crate) fn advance(&mut self) {
let target = self.ray().map(|(b, _)| b);
match (self.left, target) {
(true, Some(b)) => {
let n = match self.digging {
Some((d, n)) if d == b => n + 1,
_ => 1,
};
let hard = self.class(b).hardness.max(0.0);
if n >= 5 + (f64::from(hard) * 30.0) as u32 {
self.world.set.insert(b, 0);
self.digging = None;
} else {
self.digging = Some((b, n));
}
}
_ => self.digging = None,
}
for p in &mut self.pending {
p.0 -= 1;
}
let (due, rest): (Vec<_>, Vec<_>) = self.pending.drain(..).partition(|p| p.0 == 0);
self.pending = rest;
for (_, pos, raw) in due {
self.world.set.insert(pos, raw);
}
let o = P::observe(&self.state);
let look = self.turner.step(o.yaw, o.pitch, self.aim);
let view = SourceView::<P, Overlay<'w, W>>::new(&self.world);
P::tick(&mut self.state, self.keys, look.0, look.1, &view);
}
pub(crate) fn feet(&self) -> [f64; 3] {
P::observe(&self.state).pos
}
pub(crate) fn class(&self, p: [i32; 3]) -> crate::class::Class {
let t = crate::class::table(P::VERSION);
self.world
.raw_block(p[0], p[1], p[2])
.map_or(crate::class::Class::UNKNOWN, |r| {
t.classes[t.index(r) as usize]
})
}
pub(crate) fn ray(&self) -> Option<([i32; 3], [i32; 3])> {
let o = P::observe(&self.state);
let (yaw, pitch) = (
f64::from(o.yaw).to_radians(),
f64::from(o.pitch).to_radians(),
);
let d = [
-yaw.sin() * pitch.cos(),
-pitch.sin(),
yaw.cos() * pitch.cos(),
];
let e = [o.pos[0], o.pos[1] + 1.62, o.pos[2]];
let mut c = [
e[0].floor() as i32,
e[1].floor() as i32,
e[2].floor() as i32,
];
let step = d.map(|v| if v > 0.0 { 1 } else { -1 });
let mut tmax = [0.0f64; 3];
let mut tdelta = [0.0f64; 3];
for i in 0..3 {
if d[i].abs() < 1e-12 {
tmax[i] = f64::INFINITY;
tdelta[i] = f64::INFINITY;
} else {
let next = if d[i] > 0.0 {
f64::from(c[i]) + 1.0
} else {
f64::from(c[i])
};
tmax[i] = (next - e[i]) / d[i];
tdelta[i] = 1.0 / d[i].abs();
}
}
loop {
let i = (0..3).min_by(|&a, &b| tmax[a].total_cmp(&tmax[b])).unwrap();
if tmax[i] > 4.5 {
return None;
}
c[i] += step[i];
tmax[i] += tdelta[i];
let k = self.class(c);
if k.has(crate::class::flag::SOLID) {
let mut face = [0; 3];
face[i] = -step[i];
return Some((c, face));
}
}
}
fn overlaps_player(&self, p: [i32; 3]) -> bool {
let o = P::observe(&self.state).pos;
let (x, y, z) = (f64::from(p[0]), f64::from(p[1]), f64::from(p[2]));
o[0] + 0.3 > x
&& o[0] - 0.3 < x + 1.0
&& o[1] + 1.8 > y
&& o[1] < y + 1.0
&& o[2] + 0.3 > z
&& o[2] - 0.3 < z + 1.0
}
}
impl<'w, P: Physics, W: BlockSource> Io for SimIo<'w, P, W> {
type World<'a>
= Overlay<'w, W>
where
Self: 'a;
fn world(&self) -> &Overlay<'w, W> {
&self.world
}
fn version(&self) -> Option<Version> {
Some(P::VERSION)
}
fn observation(&self) -> Observation {
let mut o = P::observe(&self.state);
o.food = 20;
o
}
fn moved_by_server(&self) -> bool {
false
}
fn is_dead(&self) -> bool {
false
}
fn set_aim(&mut self, yaw: f32, pitch: f32) {
self.aim = (yaw, pitch);
}
fn planned_look(&self) -> (f32, f32) {
let o = P::observe(&self.state);
let mut t = self.turner;
t.step(o.yaw, o.pitch, self.aim)
}
fn set_keys(&mut self, keys: Keys) {
self.keys = keys;
}
fn left_button(&self) -> bool {
self.left
}
fn set_left_button(&mut self, on: bool) {
self.left = on;
}
fn targets(&self, block: [i32; 3]) -> bool {
self.ray().is_some_and(|(b, _)| b == block)
}
fn place_against(&mut self, against: [i32; 3], dir: [i32; 3]) -> bool {
if self.ray() != Some((against, dir)) {
return false;
}
let pos = [
against[0] + dir[0],
against[1] + dir[1],
against[2] + dir[2],
];
if self.overlaps_player(pos) {
self.overlapping += 1;
return false;
}
if !self.class(pos).has(crate::class::flag::REPLACEABLE) {
return false;
}
self.places += 1;
self.pending
.push((2, pos, crate::sim::stone_raw(P::VERSION)));
true
}
fn activate(&mut self, block: [i32; 3]) -> bool {
if self.ray().map(|(b, _)| b) != Some(block) {
return false;
}
self.clicks += 1;
if let Some(changes) = crate::door::toggle(P::VERSION, &self.world, block) {
for (p, raw) in changes {
self.pending.push((2, p, raw));
}
}
true
}
fn modern_player(&self) -> Option<&ghast_physics::modern::PlayerState> {
P::as_modern(&self.state)
}
}
#[derive(Debug)]
pub(crate) struct Drive {
pub(crate) status: FollowStatus,
pub(crate) ticks: u32,
pub(crate) planning_ticks: u32,
pub(crate) worst_tick: Duration,
pub(crate) plans: u64,
pub(crate) end: [f64; 3],
}
pub(crate) fn drive<P: Physics, W: BlockSource>(
world: &W,
feet: [f64; 3],
mut follower: Follower,
goal: Goal,
max: u32,
) -> Drive {
let mut io = SimIo::<P, W>::new(world, feet);
follower.goto(goal);
let mut d = Drive {
status: FollowStatus::Moving,
ticks: 0,
planning_ticks: 0,
worst_tick: Duration::ZERO,
plans: 0,
end: feet,
};
while d.ticks < max {
let t0 = Instant::now();
d.status = follower.step(&mut io);
if d.ticks > 0 {
d.worst_tick = d.worst_tick.max(t0.elapsed());
}
if follower.is_planning() {
d.planning_ticks += 1;
}
d.ticks += 1;
if d.status != FollowStatus::Moving {
break;
}
io.advance();
}
d.plans = follower.plans();
d.end = io.feet();
d
}
const STONE18: u16 = 1 << 4;
fn rng(s: &mut u64) -> u64 {
*s ^= *s << 13;
*s ^= *s >> 7;
*s ^= *s << 17;
*s
}
pub(crate) fn maze<B: Copy>(
w: &mut ghast_physics::MemoryWorld<B>,
(ox, oz): (i32, i32),
n: i32,
h: i32,
seed: u64,
) {
let size = 2 * n + 1;
w.fill_raw(
[ox, 64, oz],
[ox + size - 1, 63 + h, oz + size - 1],
STONE18,
);
let carve = |w: &mut ghast_physics::MemoryWorld<B>, gx: i32, gz: i32| {
w.fill_raw([ox + gx, 64, oz + gz], [ox + gx, 63 + h, oz + gz], 0);
};
let mut s = seed | 1;
let mut seen = vec![false; (n * n) as usize];
let mut stack = vec![(0, 0)];
seen[0] = true;
carve(w, 1, 1);
while let Some(&(cx, cz)) = stack.last() {
let nb: Vec<(i32, i32)> = [(1, 0), (-1, 0), (0, 1), (0, -1)]
.iter()
.map(|(dx, dz)| (cx + dx, cz + dz))
.filter(|&(x, z)| x >= 0 && z >= 0 && x < n && z < n && !seen[(z * n + x) as usize])
.collect();
if nb.is_empty() {
stack.pop();
continue;
}
let (nx, nz) = nb[(rng(&mut s) % nb.len() as u64) as usize];
seen[(nz * n + nx) as usize] = true;
carve(w, 2 * nx + 1, 2 * nz + 1);
carve(w, cx + nx + 1, cz + nz + 1);
stack.push((nx, nz));
}
carve(w, 0, 1);
carve(w, size - 1, size - 2);
}
pub(crate) fn flat(r: i32) -> ghast_physics::v1_8::MemoryWorld {
flat_in(ghast_physics::v1_8::memory_world(), r)
}
pub(crate) fn flat_in<B: Copy>(
mut w: ghast_physics::MemoryWorld<B>,
r: i32,
) -> ghast_physics::MemoryWorld<B> {
w.load_chunks(-r, -r, r, r);
w.fill_raw(
[-16 * r, 63, -16 * r],
[16 * r + 15, 63, 16 * r + 15],
STONE18,
);
w
}
fn follower() -> Follower {
Follower::new(Pathfinder::new(Config::default()), FollowConfig::default())
}
#[test]
fn movement_only_walks_a_maze_with_the_behaviours_look() {
for (n, seed) in [(7, 3u64), (15, 5)] {
let mut w = flat(6);
maze(&mut w, (-n, -n), n, 2, seed);
let c = if n % 2 == 1 { 0 } else { 1 };
let goal = Goal::Near {
pos: [c, 64, c],
radius: 1.0,
};
let from = [f64::from(-n - 4) + 0.5, 64.0, f64::from(n + 4) + 0.5];
for look in [37.0f32, -120.0, 180.0] {
let mut f = Follower::new(
Pathfinder::new(Config::default()),
FollowConfig::default().with_movement_only(true),
);
f.goto(goal.clone());
let mut io = SimIo::<P18, _>::new(&w, from);
let mut status = FollowStatus::Moving;
let mut ticks = 0;
while ticks < 20_000 {
io.set_aim(look, 0.0);
status = f.step(&mut io);
if status != FollowStatus::Moving {
break;
}
assert!(!f.aiming(), "a plain walk aimed");
io.advance();
ticks += 1;
}
eprintln!(
"maze {n} look {look}: {status:?} in {ticks} ticks, {} plans",
f.plans()
);
assert_eq!(status, FollowStatus::Arrived, "maze {n} look {look}");
assert!(goal.is_reached(Pathfinder::start_block(io.feet())));
}
}
}
#[test]
fn mazes_are_solved() {
for (n, seed) in [(7, 3u64), (15, 5), (31, 7)] {
let mut w = flat(6);
maze(&mut w, (-n, -n), n, 2, seed);
let centre = [
if n % 2 == 1 { 0 } else { 1 },
64,
if n % 2 == 1 { 0 } else { 1 },
];
let from = [f64::from(-n - 4) + 0.5, 64.0, f64::from(n + 4) + 0.5];
let d = drive::<P18, _>(
&w,
from,
follower(),
Goal::Near {
pos: centre,
radius: 1.0,
},
20_000,
);
eprintln!("maze {}: {d:?}", 2 * n + 1);
assert_eq!(d.status, FollowStatus::Arrived, "maze {}", 2 * n + 1);
let end = Pathfinder::start_block(d.end);
assert!(
Goal::Near {
pos: centre,
radius: 1.0
}
.is_reached(end)
);
}
}
#[test]
fn unreachable_goals_end_after_one_search() {
let w = flat(4);
let d = drive::<P18, _>(
&w,
[-20.5, 64.0, 3.5],
follower(),
Goal::Near {
pos: [10, 70, -4],
radius: 2.0,
},
3000,
);
assert_eq!(
d.status,
FollowStatus::Failed(FollowError::Plan(PlanError::NoPath)),
"{d:?}"
);
assert_eq!(d.plans, 1, "{d:?}");
let end = Pathfinder::start_block(d.end);
assert!((end[0] - 10).abs() <= 1 && (end[2] + 4).abs() <= 1, "{d:?}");
let mut w = flat(4);
maze(&mut w, (-15, -15), 15, 2, 11);
w.fill_raw([-2, 64, -2], [2, 65, 2], STONE18);
w.fill_raw([0, 64, 0], [0, 65, 0], 0);
let d = drive::<P18, _>(
&w,
[-18.5, 64.0, 18.5],
follower(),
Goal::Block([0, 64, 0]),
20_000,
);
assert_eq!(
d.status,
FollowStatus::Failed(FollowError::Plan(PlanError::NoPath)),
"{d:?}"
);
assert_eq!(d.plans, 1, "{d:?}");
}
#[test]
fn capped_searches_give_up() {
let mut w = flat(4);
maze(&mut w, (-31, -31), 31, 2, 13);
let f = Follower::new(
Pathfinder::new(Config::default().with_max_nodes(1500)),
FollowConfig::default(),
);
let d = drive::<P18, _>(&w, [-34.5, 64.0, -29.5], f, Goal::Block([0, 64, 0]), 40_000);
eprintln!("{d:?}");
assert_ne!(d.status, FollowStatus::Moving, "still wandering: {d:?}");
assert!(d.plans <= 20, "{d:?}");
}
#[test]
fn per_tick_budget_on_a_big_maze() {
let mut w = flat(10);
maze(&mut w, (-63, -63), 63, 2, 17);
let budget = FollowConfig::default().budget;
let d = drive::<P18, _>(
&w,
[-67.5, 64.0, 67.5],
follower(),
Goal::Near {
pos: [1, 64, 1],
radius: 1.0,
},
40_000,
);
eprintln!("maze 127, view distance 10: {d:?}");
assert_eq!(d.status, FollowStatus::Arrived, "{d:?}");
if !cfg!(debug_assertions) && std::env::var_os("GHAST_TIMING").is_some() {
let max = budget.time.unwrap() + Duration::from_millis(3);
assert!(d.worst_tick <= max, "{d:?}");
}
let _ = P16::VERSION;
}
#[test]
fn the_lab_parkour_corridor() {
let w = corridor(ghast_physics::v1_8::memory_world());
run_corridor::<P18, _>(&w);
let w = corridor(ghast_physics::v1_12::memory_world());
run_corridor::<P12, _>(&w);
}
#[test]
fn mazes_on_1_12() {
let n = 15;
let mut w = flat_in(ghast_physics::v1_12::memory_world(), 6);
maze(&mut w, (-n, -n), n, 2, 5);
let from = [f64::from(-n - 4) + 0.5, 64.0, f64::from(n + 4) + 0.5];
let goal = Goal::Near {
pos: [1, 64, 1],
radius: 1.0,
};
let d = drive::<P12, _>(&w, from, follower(), goal, 20_000);
assert_eq!(d.status, FollowStatus::Arrived, "{d:?}");
let air = Goal::Near {
pos: [1, 70, 1],
radius: 2.0,
};
let d = drive::<P12, _>(&w, from, follower(), air, 20_000);
assert_eq!(
d.status,
FollowStatus::Failed(FollowError::Plan(PlanError::NoPath)),
"{d:?}"
);
assert_eq!(d.plans, 1, "{d:?}");
}
fn corridor<B: Copy>(mut w: ghast_physics::MemoryWorld<B>) -> ghast_physics::MemoryWorld<B> {
w.load_chunks(0, -2, 9, 2);
w.fill_raw([0, 0, -32], [159, 0, 47], 7 << 4);
w.fill_raw([0, 1, -32], [159, 2, 47], 3 << 4);
w.fill_raw([0, 3, -32], [159, 3, 47], 2 << 4);
for z in [-2, 2] {
w.fill_raw([60, 1, z], [123, 7, z], STONE18);
}
w.fill_raw([123, 4, -2], [123, 7, 2], STONE18);
let trench = |w: &mut ghast_physics::MemoryWorld<B>, a: i32, b: i32| {
w.fill_raw([a, 1, -1], [b, 3, 1], 0);
};
trench(&mut w, 66, 66);
trench(&mut w, 71, 72);
trench(&mut w, 77, 79);
trench(&mut w, 84, 84);
w.fill_raw([85, 4, -1], [89, 4, 1], STONE18);
trench(&mut w, 90, 91);
trench(&mut w, 96, 111);
for (x, top) in [(98, 3), (100, 3), (104, 3), (107, 4), (109, 3)] {
w.fill_raw([x, 1, 0], [x, top, 0], STONE18);
}
w
}
fn id26(spec: &str) -> u16 {
ghast_data::v26_1::BlockState::parse(spec)
.unwrap_or_else(|| panic!("{spec}"))
.id()
}
fn corridor_26() -> ghast_physics::modern::MemoryWorld26 {
let mut w = ghast_physics::modern::memory_world_26_1();
let stone = id26("stone");
w.load_chunks(0, -2, 9, 2);
w.fill_raw([0, 0, -32], [159, 0, 47], id26("bedrock"));
w.fill_raw([0, 1, -32], [159, 2, 47], id26("dirt"));
w.fill_raw([0, 3, -32], [159, 3, 47], id26("grass_block"));
for z in [-2, 2] {
w.fill_raw([60, 1, z], [123, 7, z], stone);
}
w.fill_raw([123, 4, -2], [123, 7, 2], stone);
let trench = |w: &mut ghast_physics::modern::MemoryWorld26, a: i32, b: i32| {
w.fill_raw([a, 1, -1], [b, 3, 1], 0);
};
trench(&mut w, 66, 66);
trench(&mut w, 71, 72);
trench(&mut w, 77, 79);
trench(&mut w, 84, 84);
w.fill_raw([85, 4, -1], [89, 4, 1], stone);
trench(&mut w, 90, 91);
trench(&mut w, 96, 111);
for (x, top) in [(98, 3), (100, 3), (104, 3), (107, 4), (109, 3)] {
w.fill_raw([x, 1, 0], [x, top, 0], stone);
}
w
}
#[test]
fn the_lab_parkour_corridor_26_1() {
run_corridor::<P26, _>(&corridor_26());
}
#[test]
fn mazes_on_26_1() {
let n = 15;
let (y, stone) = (-40, id26("stone"));
let mut w = ghast_physics::modern::memory_world_26_1();
w.load_chunks(-6, -6, 6, 6);
w.fill_raw([-96, y - 1, -96], [111, y - 1, 111], stone);
let size = 2 * n + 1;
let (ox, oz) = (-n, -n);
w.fill_raw([ox, y, oz], [ox + size - 1, y + 1, oz + size - 1], stone);
let mut s = 5u64 | 1;
let mut seen = vec![false; (n * n) as usize];
let mut stack = vec![(0, 0)];
seen[0] = true;
let carve = |w: &mut ghast_physics::modern::MemoryWorld26, gx: i32, gz: i32| {
w.fill_raw([ox + gx, y, oz + gz], [ox + gx, y + 1, oz + gz], 0);
};
carve(&mut w, 1, 1);
while let Some(&(cx, cz)) = stack.last() {
let nb: Vec<(i32, i32)> = [(1, 0), (-1, 0), (0, 1), (0, -1)]
.iter()
.map(|(dx, dz)| (cx + dx, cz + dz))
.filter(|&(x, z)| x >= 0 && z >= 0 && x < n && z < n && !seen[(z * n + x) as usize])
.collect();
if nb.is_empty() {
stack.pop();
continue;
}
let (nx, nz) = nb[(rng(&mut s) % nb.len() as u64) as usize];
seen[(nz * n + nx) as usize] = true;
carve(&mut w, 2 * nx + 1, 2 * nz + 1);
carve(&mut w, cx + nx + 1, cz + nz + 1);
stack.push((nx, nz));
}
carve(&mut w, 0, 1);
carve(&mut w, size - 1, size - 2);
let from = [
f64::from(-n - 4) + 0.5,
f64::from(y),
f64::from(n + 4) + 0.5,
];
let goal = Goal::Near {
pos: [1, y, 1],
radius: 1.0,
};
let d = drive::<P26, _>(&w, from, follower(), goal, 20_000);
eprintln!("26.1 maze 31: {d:?}");
assert_eq!(d.status, FollowStatus::Arrived, "{d:?}");
let air = Goal::Near {
pos: [1, y + 6, 1],
radius: 2.0,
};
let d = drive::<P26, _>(&w, from, follower(), air, 20_000);
assert_eq!(
d.status,
FollowStatus::Failed(FollowError::Plan(PlanError::NoPath)),
"{d:?}"
);
assert_eq!(d.plans, 1, "{d:?}");
}
#[test]
fn live_attributes_26_1() {
use ghast_physics::modern::AttributeKind;
let stone = id26("stone");
let mut w = ghast_physics::modern::memory_world_26_1();
w.load_chunks(-2, -2, 2, 2);
w.fill_raw([-32, 63, -32], [31, 63, 31], stone);
w.fill_raw([4, 64, -32], [4, 64, 31], stone);
w.set_raw(4, 64, 6, 0);
let goal = Goal::Block([8, 64, 0]);
let d = drive::<P26, _>(&w, [0.5, 64.0, 0.5], follower(), goal.clone(), 2000);
assert_eq!(d.status, FollowStatus::Arrived, "{d:?}");
let mut io = SimIo::<P26, _>::new(&w, [0.5, 64.0, 0.5]);
io.state
.apply_attribute(AttributeKind::JumpStrength, 0.0, &[]);
let mut f = follower();
f.goto(goal);
let mut through_gap = false;
let mut status = FollowStatus::Moving;
for _ in 0..3000 {
status = f.step(&mut io);
if status != FollowStatus::Moving {
break;
}
io.advance();
let p = io.feet();
through_gap |= p[0].floor() as i32 == 4 && p[2].floor() as i32 == 6;
}
assert_eq!(status, FollowStatus::Arrived, "{:?}", io.feet());
assert!(through_gap, "the step was not avoided");
assert_eq!(f.plans(), 1, "replanned");
}
#[test]
fn dig_down_6_follower() {
let cfg = Config::default().with_dig(Some(crate::DigCost {
base: 8.0,
ticks_per_hardness: 30.0,
max_hardness: 1.0,
}));
let mut w = flat(2);
w.fill_raw([-3, 64, -3], [3, 69, 3], 3 << 4);
let f = Follower::new(Pathfinder::new(cfg.clone()), FollowConfig::default());
let mut io = SimIo::<P18, _>::new(&w, [0.5, 70.0, 0.5]);
let status = run(&mut io, f, Goal::Block([0, 64, 0]), 2000);
assert_eq!(status, FollowStatus::Arrived, "{:?}", io.feet());
assert_eq!(Pathfinder::start_block(io.feet()), [0, 64, 0]);
let mut w = ghast_physics::modern::memory_world_26_2();
w.load_chunks(-1, -1, 1, 1);
w.fill_raw([-8, 63, -8], [8, 63, 8], id262("stone"));
w.fill_raw([-3, 64, -3], [3, 69, 3], id262("dirt"));
let f = Follower::new(Pathfinder::new(cfg), FollowConfig::default());
let mut io = SimIo::<P262, _>::new(&w, [0.5, 70.0, 0.5]);
let status = run(&mut io, f, Goal::Y(64), 2000);
assert_eq!(status, FollowStatus::Arrived, "{:?}", io.feet());
assert_eq!(Pathfinder::start_block(io.feet())[1], 64);
}
#[test]
fn doors_follower() {
for open in [false, true] {
for hinge in ["left", "right"] {
let mut w = ghast_physics::modern::memory_world_26_2();
w.load_chunks(-2, -2, 2, 2);
w.fill_raw([-32, 63, -32], [31, 63, 31], id262("stone"));
w.fill_raw([3, 64, -32], [3, 66, 31], id262("stone"));
for (y, half) in [(64, "lower"), (65, "upper")] {
w.set_raw(
3,
y,
0,
id262(&format!(
"oak_door[facing=east,half={half},hinge={hinge},open={open}]"
)),
);
}
let mut io = SimIo::<P262, _>::new(&w, [0.5, 64.0, -3.5]);
let status = run(&mut io, follower(), Goal::Block([7, 64, 2]), 1500);
assert_eq!(
status,
FollowStatus::Arrived,
"open {open} {hinge}: {:?}",
io.feet()
);
assert_eq!(io.clicks, u32::from(!open), "open {open} {hinge}");
}
}
let mut w = flat(2);
w.fill_raw([3, 64, -32], [3, 66, 31], STONE18);
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]);
let status = run(&mut io, follower(), Goal::Block([7, 64, 2]), 1500);
assert_eq!(status, FollowStatus::Arrived, "{:?}", io.feet());
assert_eq!(io.clicks, 1);
}
#[test]
fn bridge_and_tower_follower() {
let cfg = Config::default().with_place(Some(20.0)).with_parkour(false);
let follower = || Follower::new(Pathfinder::new(cfg.clone()), FollowConfig::default());
let stone = id262("stone");
let mut w = ghast_physics::modern::memory_world_26_2();
w.load_chunks(-2, -2, 2, 2);
w.fill_raw([-8, 63, -8], [1, 63, 8], stone);
w.fill_raw([5, 63, -8], [12, 63, 8], stone);
let mut io = SimIo::<P262, _>::new(&w, [0.5, 64.0, 0.5]);
let status = run(&mut io, follower(), Goal::Block([7, 64, 0]), 2000);
assert_eq!(
status,
FollowStatus::Arrived,
"bridge 26.2: {:?}",
io.feet()
);
assert_eq!(io.places, 3, "bridge 26.2");
assert_eq!(
io.overlapping, 0,
"bridge 26.2: a place overlapped the player"
);
let mut w = ghast_physics::modern::memory_world_26_2();
w.load_chunks(-2, -2, 2, 2);
w.fill_raw([-8, 63, -8], [8, 63, 8], stone);
let mut io = SimIo::<P262, _>::new(&w, [0.5, 64.0, 0.5]);
let status = run(&mut io, follower(), Goal::Block([0, 67, 0]), 2000);
assert_eq!(status, FollowStatus::Arrived, "tower 26.2: {:?}", io.feet());
assert_eq!(io.places, 3, "tower 26.2");
assert_eq!(
io.overlapping, 0,
"tower 26.2: a place overlapped the player"
);
let mut w = ghast_physics::v1_8::memory_world();
w.load_chunks(-2, -2, 2, 2);
w.fill_raw([-8, 63, -8], [1, 63, 8], STONE18);
w.fill_raw([5, 63, -8], [12, 63, 8], STONE18);
let mut io = SimIo::<P18, _>::new(&w, [0.5, 64.0, 0.5]);
let status = run(&mut io, follower(), Goal::Block([7, 64, 0]), 2000);
assert_eq!(status, FollowStatus::Arrived, "bridge 1.8: {:?}", io.feet());
let w = flat(2);
let mut io = SimIo::<P18, _>::new(&w, [0.5, 64.0, 0.5]);
let status = run(&mut io, follower(), Goal::Block([0, 67, 0]), 2000);
assert_eq!(status, FollowStatus::Arrived, "tower 1.8: {:?}", io.feet());
assert_eq!(
io.overlapping, 0,
"tower 1.8: a place overlapped the player"
);
}
#[test]
fn staircase_follower() {
let cfg = Config::default().with_dig(Some(crate::DigCost {
base: 8.0,
ticks_per_hardness: 30.0,
max_hardness: 1.0,
}));
let mut w = ghast_physics::modern::memory_world_26_2();
w.load_chunks(-2, -2, 2, 2);
w.fill_raw([-32, 63, -32], [31, 63, 31], id262("stone"));
w.fill_raw([-32, 64, -32], [31, 80, 31], id262("dirt"));
w.fill_raw([0, 74, 0], [0, 75, 0], 0);
let f = Follower::new(Pathfinder::new(cfg), FollowConfig::default());
let mut io = SimIo::<P262, _>::new(&w, [0.5, 74.0, 0.5]);
let status = run(&mut io, f, Goal::Block([10, 64, 0]), 6000);
assert_eq!(status, FollowStatus::Arrived, "{:?}", io.feet());
}
#[test]
fn trapdoor_follower() {
let mut w = ghast_physics::modern::memory_world_26_2();
w.load_chunks(-2, -2, 2, 2);
w.fill_raw([-32, 63, -32], [31, 63, 31], id262("stone"));
w.fill_raw([3, 64, -32], [3, 66, 31], id262("stone"));
w.set_raw(3, 64, 0, 0);
w.set_raw(
3,
65,
0,
id262("oak_trapdoor[facing=north,half=bottom,open=false]"),
);
let mut io = SimIo::<P262, _>::new(&w, [0.5, 64.0, -2.5]);
let status = run(&mut io, follower(), Goal::Block([6, 64, 0]), 1500);
assert_eq!(status, FollowStatus::Arrived, "{:?}", io.feet());
assert_eq!(io.clicks, 1);
let mut w = flat(2);
w.fill_raw([3, 64, -32], [3, 66, 31], STONE18);
w.set_raw(3, 64, 0, 0);
w.set_raw(3, 65, 0, 96 << 4); let mut io = SimIo::<P18, _>::new(&w, [0.5, 64.0, -2.5]);
let status = run(&mut io, follower(), Goal::Block([6, 64, 0]), 1500);
assert_eq!(status, FollowStatus::Arrived, "{:?}", io.feet());
assert_eq!(io.clicks, 1);
}
pub(crate) fn id262(spec: &str) -> u16 {
ghast_data::v26_2::BlockState::parse(spec)
.unwrap_or_else(|| panic!("{spec}"))
.id()
}
pub(crate) fn run<P: Physics, W: BlockSource>(
io: &mut SimIo<'_, P, W>,
mut f: Follower,
goal: Goal,
max: u32,
) -> FollowStatus {
f.goto(goal);
let mut status = FollowStatus::Moving;
for _ in 0..max {
status = f.step(io);
if status != FollowStatus::Moving {
break;
}
io.advance();
}
status
}
fn run_corridor<P: Physics, W: BlockSource>(w: &W) {
let d = drive::<P, _>(
w,
[62.5, 4.0, 0.5],
follower(),
Goal::Xz { x: 119, z: 0 },
4000,
);
eprintln!("{:?} east: {d:?}", P::VERSION);
assert_eq!(d.status, FollowStatus::Arrived, "{d:?}");
let d = drive::<P, _>(w, d.end, follower(), Goal::Xz { x: 62, z: 0 }, 4000);
eprintln!("{:?} west: {d:?}", P::VERSION);
assert_eq!(d.status, FollowStatus::Arrived, "{d:?}");
}
}
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_3"
))]
mod tests_26_3 {
use super::tests::{SimIo, run};
use super::{FollowConfig, FollowStatus, Follower};
use crate::Goal;
use crate::physics::P263;
use crate::plan::{Config, Pathfinder};
fn id(spec: &str) -> u16 {
ghast_data::v26_3::BlockState::parse(spec)
.unwrap_or_else(|| panic!("{spec}"))
.id()
}
fn follower() -> Follower {
Follower::new(Pathfinder::new(Config::default()), FollowConfig::default())
}
fn walled() -> ghast_physics::modern::MemoryWorld263 {
let mut w = ghast_physics::modern::memory_world_26_3();
w.load_chunks(-2, -2, 2, 2);
w.fill_raw([-32, 63, -32], [31, 63, 31], id("stone"));
w.fill_raw([3, 64, -32], [3, 66, 31], id("stone"));
w.fill_raw([3, 64, 0], [3, 65, 0], 0);
w
}
#[test]
fn poplar_door() {
for open in [false, true] {
for hinge in ["left", "right"] {
let mut w = walled();
for (y, half) in [(64, "lower"), (65, "upper")] {
w.set_raw(
3,
y,
0,
id(&format!(
"poplar_door[facing=east,half={half},hinge={hinge},open={open}]"
)),
);
}
let mut io = SimIo::<P263, _>::new(&w, [0.5, 64.0, -3.5]);
let status = run(&mut io, follower(), Goal::Block([7, 64, 2]), 1500);
assert_eq!(
status,
FollowStatus::Arrived,
"open {open} {hinge}: {:?}",
io.feet()
);
assert_eq!(io.clicks, u32::from(!open), "open {open} {hinge}");
}
}
}
#[test]
fn poplar_fence_gate() {
let mut w = ghast_physics::modern::memory_world_26_3();
w.load_chunks(-2, -2, 2, 2);
w.fill_raw([-32, 63, -32], [31, 63, 31], id("stone"));
w.fill_raw(
[3, 64, -32],
[3, 64, 31],
id("poplar_fence[east=false,north=true,south=true,waterlogged=false,west=false]"),
);
w.set_raw(
3,
64,
0,
id("poplar_fence_gate[facing=east,in_wall=false,open=false,powered=false]"),
);
let mut io = SimIo::<P263, _>::new(&w, [0.5, 64.0, -2.5]);
let status = run(&mut io, follower(), Goal::Block([7, 64, 1]), 1500);
assert_eq!(status, FollowStatus::Arrived, "{:?}", io.feet());
assert_eq!(io.clicks, 1);
}
#[test]
fn poplar_trapdoor() {
let mut w = walled();
w.set_raw(
3,
65,
0,
id("poplar_trapdoor[facing=north,half=bottom,open=false,powered=false,waterlogged=false]"),
);
let mut io = SimIo::<P263, _>::new(&w, [0.5, 64.0, -2.5]);
let status = run(&mut io, follower(), Goal::Block([6, 64, 0]), 1500);
assert_eq!(status, FollowStatus::Arrived, "{:?}", io.feet());
assert_eq!(io.clicks, 1);
}
#[test]
fn concrete_slab_staircase() {
let bottom = id("white_concrete_slab[type=bottom,waterlogged=false]");
let double = id("white_concrete_slab[type=double,waterlogged=false]");
let stairs =
id("red_concrete_stairs[facing=east,half=bottom,shape=straight,waterlogged=false]");
for (name, step) in [("slabs", None), ("stairs", Some(stairs))] {
let mut w = ghast_physics::modern::memory_world_26_3();
w.load_chunks(-2, -2, 2, 2);
w.fill_raw([-32, 63, -32], [31, 63, 31], id("stone"));
for k in 0..3 {
let x = 2 * k + 2;
w.fill_raw([x, 64, -1], [x + 1, 63 + k, 1], double);
w.fill_raw([x, 64 + k, -1], [x, 64 + k, 1], step.unwrap_or(bottom));
w.fill_raw([x + 1, 64 + k, -1], [x + 1, 64 + k, 1], double);
}
w.fill_raw([8, 64, -1], [10, 66, 1], double);
let mut io = SimIo::<P263, _>::new(&w, [0.5, 64.0, 0.5]);
let status = run(&mut io, follower(), Goal::Block([9, 67, 0]), 2000);
assert_eq!(status, FollowStatus::Arrived, "{name}: {:?}", io.feet());
}
}
#[test]
fn shelf_mushroom_is_an_obstacle() {
let mut w = ghast_physics::modern::memory_world_26_3();
w.load_chunks(-2, -2, 2, 2);
w.fill_raw([-32, 63, -32], [31, 63, 31], id("stone"));
w.fill_raw(
[3, 64, -1],
[3, 64, 1],
id("shelf_mushroom[age=1,facing=west]"),
);
let mut io = SimIo::<P263, _>::new(&w, [0.5, 64.0, 0.5]);
let status = run(&mut io, follower(), Goal::Block([7, 64, 0]), 1500);
assert_eq!(status, FollowStatus::Arrived, "around: {:?}", io.feet());
for (step, arrives) in [
("shelf_mushroom[age=1,facing=west]", false),
("smooth_stone_slab[type=bottom,waterlogged=false]", true),
] {
let mut w = ghast_physics::modern::memory_world_26_3();
w.load_chunks(-2, -2, 2, 2);
w.fill_raw([-32, 63, -32], [31, 63, 31], id("stone"));
w.fill_raw([4, 64, -32], [10, 64, 31], id("stone"));
w.fill_raw(
[4, 65, -32],
[10, 65, 31],
id("smooth_stone_slab[type=bottom,waterlogged=false]"),
);
w.set_raw(3, 64, 0, id(step));
let mut io = SimIo::<P263, _>::new(&w, [0.5, 64.0, 0.5]);
let status = run(&mut io, follower(), Goal::Block([6, 65, 0]), 2000);
assert_eq!(
status == FollowStatus::Arrived,
arrives,
"{step}: {status:?} {:?}",
io.feet()
);
}
}
}