ghast-pathfinder 0.4.2

Physics-exact path planning and path following for the ghast Minecraft Java Edition bot library (1.8.9, 1.12.2, 1.16.5 and 26.1): every move type is validated against the vanilla-exact ghast-physics
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! The planner's world access: raw block states from any source, cached per block as classes.

use std::collections::HashMap;

use crate::Version;
use crate::class::{Class, Table, table};

/// Read access to raw block states, as the version encodes them on the wire: 1.8
/// `id << 4 | meta`, 1.16.5 and 26.1 the global palette id.
///
/// `None` means **unknown** (column not loaded, or below the world): the planner never walks
/// through unknown blocks. Implemented for ghast-client's `WorldView`, the ghast-world worlds
/// (feature `client`) and the physics crate's `MemoryWorld`s.
pub trait BlockSource {
    /// The raw state at a position; `None` when unknown.
    fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32>;

    /// Whether the chunk column is loaded (default: probes one block of it).
    fn is_column_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool {
        self.raw_block(chunk_x << 4, 0, chunk_z << 4).is_some()
    }

    /// The build height `(min_y, height)` when the source knows it (26.1 dimensions differ:
    /// the overworld is `(-64, 384)`, the nether `(0, 256)`, data packs choose freely). `None`
    /// (the default): the version's usual one. Below `min_y` the planner sees unknown blocks,
    /// at `min_y + height` and above air. 1.8.9 – 1.16.5 always use `(0, 256)`.
    fn build_height(&self) -> Option<(i32, i32)> {
        None
    }
}

impl<T: BlockSource + ?Sized> BlockSource for &T {
    #[inline]
    fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32> {
        (**self).raw_block(x, y, z)
    }

    #[inline]
    fn is_column_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool {
        (**self).is_column_loaded(chunk_x, chunk_z)
    }

    #[inline]
    fn build_height(&self) -> Option<(i32, i32)> {
        (**self).build_height()
    }
}

/// A modern dimension's `[lo, hi)` (a source without one: the vanilla overworld).
#[cfg(ghast_modern)]
#[inline]
fn modern_range<S: BlockSource + ?Sized>(src: &S) -> (i32, i32) {
    let (min_y, height) = src.build_height().unwrap_or((-64, 384));
    (min_y, min_y.saturating_add(height.max(0)))
}

/// The build height the planner uses for a version and a source: `[lo, hi)`.
#[inline]
pub(crate) fn y_range<S: BlockSource + ?Sized>(version: Version, src: &S) -> (i32, i32) {
    match version {
        #[cfg(feature = "v26_1")]
        Version::V26_1 => modern_range(src),
        #[cfg(feature = "v26_2")]
        Version::V26_2 => modern_range(src),
        #[allow(unreachable_patterns)]
        _ => {
            let _ = src;
            (0, 256)
        }
    }
}

#[cfg(feature = "v26_1")]
impl BlockSource for ghast_physics::modern::MemoryWorld26 {
    #[inline]
    fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32> {
        use ghast_physics::BlockView;
        let lo = self.min_y();
        if y < lo || y >= lo + self.height() || !self.is_chunk_loaded(x >> 4, z >> 4) {
            return None;
        }
        Some(u32::from(self.block(x, y, z).id()))
    }

    fn is_column_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool {
        ghast_physics::BlockView::is_chunk_loaded(self, chunk_x, chunk_z)
    }

    fn build_height(&self) -> Option<(i32, i32)> {
        Some((self.min_y(), self.height()))
    }
}

#[cfg(feature = "v26_2")]
impl BlockSource for ghast_physics::modern::MemoryWorld262 {
    #[inline]
    fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32> {
        use ghast_physics::BlockView;
        let lo = self.min_y();
        if y < lo || y >= lo + self.height() || !self.is_chunk_loaded(x >> 4, z >> 4) {
            return None;
        }
        Some(u32::from(self.block(x, y, z).id()))
    }

    fn is_column_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool {
        ghast_physics::BlockView::is_chunk_loaded(self, chunk_x, chunk_z)
    }

    fn build_height(&self) -> Option<(i32, i32)> {
        Some((self.min_y(), self.height()))
    }
}

#[cfg(feature = "v1_8")]
impl BlockSource for ghast_physics::MemoryWorld<ghast_data::v1_8::BlockState> {
    #[inline]
    fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32> {
        use ghast_physics::BlockView;
        if !(0..256).contains(&y) || !self.is_chunk_loaded(x >> 4, z >> 4) {
            return None;
        }
        Some(u32::from(self.block(x, y, z).raw()))
    }

    fn is_column_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool {
        ghast_physics::BlockView::is_chunk_loaded(self, chunk_x, chunk_z)
    }
}

#[cfg(feature = "v1_12_2")]
impl BlockSource for ghast_physics::MemoryWorld<ghast_data::v1_12::BlockState> {
    #[inline]
    fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32> {
        use ghast_physics::BlockView;
        if !(0..256).contains(&y) || !self.is_chunk_loaded(x >> 4, z >> 4) {
            return None;
        }
        Some(u32::from(self.block(x, y, z).raw()))
    }

    fn is_column_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool {
        ghast_physics::BlockView::is_chunk_loaded(self, chunk_x, chunk_z)
    }
}

#[cfg(feature = "v1_16_5")]
impl BlockSource for ghast_physics::MemoryWorld<ghast_data::v1_16_5::BlockState> {
    #[inline]
    fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32> {
        use ghast_physics::BlockView;
        if !(0..256).contains(&y) || !self.is_chunk_loaded(x >> 4, z >> 4) {
            return None;
        }
        Some(u32::from(self.block(x, y, z).id()))
    }

    fn is_column_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool {
        ghast_physics::BlockView::is_chunk_loaded(self, chunk_x, chunk_z)
    }
}

#[cfg(feature = "client")]
mod client_impls {
    use super::BlockSource;

    /// The planner clamps the height per version and dimension itself; this accepts any
    /// height a 26.1 dimension can have.
    impl BlockSource for dyn ghast_client::WorldView + '_ {
        #[inline]
        fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32> {
            if !(-2048..2048).contains(&y) {
                return None;
            }
            ghast_client::WorldView::raw_block(self, x, y, z)
        }

        fn is_column_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool {
            ghast_client::WorldView::is_column_loaded(self, chunk_x, chunk_z)
        }
    }

    #[cfg(feature = "v1_8")]
    impl BlockSource for ghast_client::world::v1_8::World {
        #[inline]
        fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32> {
            if !(0..256).contains(&y) {
                return None;
            }
            self.block_state(x, y, z).map(|s| u32::from(s.raw()))
        }

        fn is_column_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool {
            ghast_client::world::v1_8::World::is_column_loaded(self, chunk_x, chunk_z)
        }
    }

    #[cfg(feature = "v1_12_2")]
    impl BlockSource for ghast_client::world::v1_12::World {
        #[inline]
        fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32> {
            if !(0..256).contains(&y) {
                return None;
            }
            self.block_state(x, y, z).map(|s| u32::from(s.raw()))
        }

        fn is_column_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool {
            ghast_client::world::v1_12::World::is_column_loaded(self, chunk_x, chunk_z)
        }
    }

    #[cfg(feature = "v26_1")]
    impl BlockSource for ghast_client::world::v26_1::World {
        #[inline]
        fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32> {
            if let Some((lo, h)) = self.build_height()
                && (y < lo || y >= lo + h)
            {
                return None;
            }
            self.block_state(x, y, z).map(|s| u32::from(s.id()))
        }

        fn is_column_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool {
            ghast_client::world::v26_1::World::is_column_loaded(self, chunk_x, chunk_z)
        }

        fn build_height(&self) -> Option<(i32, i32)> {
            self.dimension().map(|d| (d.kind.min_y, d.kind.height))
        }
    }

    #[cfg(feature = "v26_2")]
    impl BlockSource for ghast_client::world::v26_2::World {
        #[inline]
        fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32> {
            if let Some((lo, h)) = self.build_height()
                && (y < lo || y >= lo + h)
            {
                return None;
            }
            self.block_state(x, y, z).map(|s| u32::from(s.id()))
        }

        fn is_column_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool {
            ghast_client::world::v26_2::World::is_column_loaded(self, chunk_x, chunk_z)
        }

        fn build_height(&self) -> Option<(i32, i32)> {
            self.dimension().map(|d| (d.kind.min_y, d.kind.height))
        }
    }

    #[cfg(feature = "v1_16_5")]
    impl BlockSource for ghast_client::world::v1_16_5::World {
        #[inline]
        fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32> {
            if !(0..256).contains(&y) {
                return None;
            }
            self.block_state(x, y, z).map(|s| u32::from(s.id()))
        }

        fn is_column_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool {
            ghast_client::world::v1_16_5::World::is_column_loaded(self, chunk_x, chunk_z)
        }
    }
}

/// Cache sentinel: not looked up yet.
const NOT_CACHED: u16 = u16::MAX;
/// Cache sentinel: unknown (not loaded / outside the world).
const UNKNOWN: u16 = u16::MAX - 1;

/// One 16×16×16 section of cached class indices.
type Section = Box<[u16; 4096]>;

/// The class cache of a planning run, kept between the slices of an incremental search.
#[derive(Clone)]
pub(crate) struct Sections {
    index: HashMap<u64, u32, BuildKeyHasher>,
    secs: Vec<Section>,
    /// The last section looked up (most lookups hit the same section in a row).
    last: (u64, u32),
}

impl Default for Sections {
    fn default() -> Self {
        Sections {
            index: HashMap::with_capacity_and_hasher(64, BuildKeyHasher),
            secs: Vec::with_capacity(64),
            last: (u64::MAX, u32::MAX),
        }
    }
}

/// Per-planning-run cache of block classes (1 lookup in the source per block at most).
pub(crate) struct Grid<'w, S: ?Sized> {
    src: &'w S,
    table: &'static Table,
    sections: Sections,
    /// Build height `[lo, hi)`: unknown below, air above.
    y_lo: i32,
    y_hi: i32,
}

impl<'w, S: BlockSource + ?Sized> Grid<'w, S> {
    pub(crate) fn new(src: &'w S, version: Version) -> Self {
        Self::with_cache(src, version, Sections::default())
    }

    /// A grid over `src` that continues an earlier run's cache.
    pub(crate) fn with_cache(src: &'w S, version: Version, sections: Sections) -> Self {
        let (y_lo, y_hi) = y_range(version, src);
        Grid {
            src,
            table: table(version),
            sections,
            y_lo,
            y_hi,
        }
    }

    /// The cache, for the next slice.
    pub(crate) fn into_cache(self) -> Sections {
        self.sections
    }

    /// The build height `[lo, hi)`.
    #[inline]
    pub(crate) fn y_range(&self) -> (i32, i32) {
        (self.y_lo, self.y_hi)
    }

    /// Air's class index (always 0).
    pub(crate) const AIR: u16 = 0;

    #[inline]
    fn key(x: i32, y: i32, z: i32) -> u64 {
        let sx = (x >> 4) as u32 as u64 & 0x3f_ffff;
        let sz = (z >> 4) as u32 as u64 & 0x3f_ffff;
        let sy = (y >> 4) as u32 as u64 & 0xfffff;
        sx << 42 | sz << 20 | sy
    }

    /// Class index at a position (`UNKNOWN` sentinel resolved by [`Grid::class`]).
    #[inline]
    pub(crate) fn index(&mut self, x: i32, y: i32, z: i32) -> u16 {
        if y < self.y_lo || y >= self.y_hi {
            return if y >= self.y_hi { Self::AIR } else { UNKNOWN };
        }
        let key = Self::key(x, y, z);
        let i = (((y & 15) as usize) << 8) | (((z & 15) as usize) << 4) | ((x & 15) as usize);
        let c = &mut self.sections;
        let si = if c.last.0 == key {
            c.last.1
        } else {
            let n = c.secs.len() as u32;
            let si = *c.index.entry(key).or_insert(n);
            if si == n {
                c.secs.push(Box::new([NOT_CACHED; 4096]));
            }
            c.last = (key, si);
            si
        };
        let v = c.secs[si as usize][i];
        if v != NOT_CACHED {
            return v;
        }
        let v = match self.src.raw_block(x, y, z) {
            Some(raw) => self.table.index(raw),
            None => UNKNOWN,
        };
        self.sections.secs[si as usize][i] = v;
        v
    }

    /// The class at a position ([`Class::UNKNOWN`] when unknown).
    #[inline]
    pub(crate) fn class(&mut self, x: i32, y: i32, z: i32) -> Class {
        let i = self.index(x, y, z);
        if i == UNKNOWN {
            Class::UNKNOWN
        } else {
            self.table.classes[i as usize]
        }
    }

    /// `true` when the position is unknown.
    #[inline]
    pub(crate) fn unknown(&mut self, x: i32, y: i32, z: i32) -> bool {
        self.index(x, y, z) == UNKNOWN
    }
}

/// A fast hasher for packed section keys (one multiply; keys are well spread already).
#[derive(Clone, Copy, Default)]
pub(crate) struct BuildKeyHasher;

impl std::hash::BuildHasher for BuildKeyHasher {
    type Hasher = KeyHasher;
    fn build_hasher(&self) -> KeyHasher {
        KeyHasher(0)
    }
}

/// See [`BuildKeyHasher`].
#[derive(Clone, Copy, Default)]
pub(crate) struct KeyHasher(u64);

impl std::hash::Hasher for KeyHasher {
    #[inline]
    fn finish(&self) -> u64 {
        self.0
    }

    #[inline]
    fn write(&mut self, bytes: &[u8]) {
        for &b in bytes {
            self.0 = (self.0.rotate_left(8) ^ u64::from(b)).wrapping_mul(0x9e37_79b9_7f4a_7c15);
        }
    }

    #[inline]
    fn write_u64(&mut self, v: u64) {
        self.0 = (self.0 ^ v)
            .wrapping_mul(0x9e37_79b9_7f4a_7c15)
            .rotate_left(29);
    }

    #[inline]
    fn write_u32(&mut self, v: u32) {
        self.write_u64(u64::from(v));
    }

    #[inline]
    fn write_i32(&mut self, v: i32) {
        self.write_u64(u64::from(v as u32));
    }
}