Skip to main content

ghast_data/v26_1/
mod.rs

1//! Minecraft 26.1 (protocol 775) data: the global block-state palette with properties, collision
2//! voxel shapes and the per-state facts the movement code reads.
3//!
4//! Every movement-relevant value comes from the real 26.1 jar (oracle dump
5//! `tests/golden/26.1/voxel_shapes.jsonl.gz`): collision voxel grids, per-state flags, fluids,
6//! friction / speed / jump factors, the block tags and `instanceof` tests vanilla's movement code
7//! makes. PrismarineJS minecraft-data (`pc/26.1`) supplies the property layout and display data
8//! and is cross-checked against the jar at generation time.
9//!
10//! The hot path is one table read per state: [`BlockState::phys`] returns a packed
11//! [`StatePhys`] (shape index, flags, fluid, per-kind extra bits, [`BlockKind`]).
12
13use crate::common::{Aabb, SelectionShape, lookup_name};
14use crate::generated::v26_1 as g;
15use core::fmt;
16
17pub use g::blocks::Property;
18
19pub mod dig;
20pub mod entities;
21pub mod items;
22
23pub use entities::{
24    EntityTypeData, entities, entity, entity_by_name, entity_type, entity_types,
25    vanilla_entity_size, vanilla_entity_sizes,
26};
27pub use items::{BlockSet, Food, Item, ItemData, Tool, ToolRule, food};
28
29/// Number of blocks (ids `0..BLOCK_COUNT`).
30pub const BLOCK_COUNT: usize = g::blocks::BLOCKS.len();
31/// Number of block states (ids `0..STATE_COUNT`).
32pub const STATE_COUNT: usize = g::blocks::STATE_BLOCK.len();
33
34impl Property {
35    /// Looks a property up by name (`"facing"`).
36    #[must_use]
37    pub fn from_name(name: &str) -> Option<Property> {
38        g::blocks::PROPERTY_NAMES
39            .binary_search_by(|e| e.0.cmp(name))
40            .ok()
41            .map(|i| g::blocks::PROPERTY_NAMES[i].1)
42    }
43}
44
45/// One property of a block with its possible values, in palette order.
46#[derive(Clone, Copy, Debug, PartialEq, Eq)]
47pub struct PropertyDef {
48    /// Which property.
49    pub property: Property,
50    /// Values in palette order (booleans are `["true", "false"]`, integers `"0"`, `"1"`, ...).
51    pub values: &'static [&'static str],
52}
53
54/// The state-id layout of one block.
55#[derive(Clone, Copy, Debug, PartialEq, Eq)]
56pub struct StateLayout {
57    /// First state id.
58    pub min_state: u16,
59    /// Number of states.
60    pub state_count: u16,
61    /// Default state id.
62    pub default_state: u16,
63    /// Indices into the property definition table, most significant first.
64    pub(crate) properties: &'static [u8],
65}
66
67/// Blocks the movement code treats specially.
68#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
69#[non_exhaustive]
70pub enum BlockKind {
71    /// Nothing special.
72    Other = 0,
73    /// `cobweb` (stuck multiplier 0.25 / 0.05).
74    Cobweb,
75    /// `sweet_berry_bush` (stuck multiplier 0.8 / 0.75).
76    SweetBerryBush,
77    /// `powder_snow` (entity-dependent collision, stuck multiplier, climbing with leather boots).
78    PowderSnow,
79    /// `honey_block` (wall slide).
80    HoneyBlock,
81    /// `bubble_column` (`aux` bit 0 = drag down).
82    BubbleColumn,
83    /// `slime_block` (bounce, step slowdown).
84    SlimeBlock,
85    /// `scaffolding` (`aux` bit 0 = has the bottom shape).
86    Scaffolding,
87    /// `ladder` (`aux` = facing: 0 N, 1 E, 2 S, 3 W).
88    Ladder,
89    /// `water`.
90    Water,
91    /// `lava`.
92    Lava,
93    /// `moving_piston`.
94    MovingPiston,
95}
96
97/// Bits of [`BlockData::flags`] (vanilla tags and `instanceof` tests of the movement code).
98pub mod block_flags {
99    /// `#minecraft:climbable`.
100    pub const CLIMBABLE: u32 = 1;
101    /// `#minecraft:fences`.
102    pub const FENCES: u32 = 2;
103    /// `#minecraft:walls`.
104    pub const WALLS: u32 = 4;
105    /// `instanceof FenceGateBlock`.
106    pub const FENCE_GATE: u32 = 8;
107    /// `instanceof TrapDoorBlock` (the state's `aux`: bit 0 open, bits 1-2 facing N/E/S/W).
108    pub const TRAPDOOR: u32 = 16;
109    /// `instanceof IceBlock` (ice, frosted ice).
110    pub const ICE: u32 = 32;
111    /// `instanceof BedBlock`.
112    pub const BED: u32 = 64;
113    /// `#minecraft:fall_damage_resetting`.
114    pub const FALL_DAMAGE_RESETTING: u32 = 128;
115    /// `#minecraft:soul_speed_blocks`.
116    pub const SOUL_SPEED_BLOCKS: u32 = 256;
117    /// `#minecraft:fire`.
118    pub const FIRE: u32 = 512;
119}
120
121/// Static per-block data (jar values for everything movement reads).
122#[derive(Clone, Copy, Debug, PartialEq)]
123pub struct BlockData {
124    /// Registry name without namespace.
125    pub name: &'static str,
126    /// English display name (minecraft-data).
127    #[cfg(feature = "display-names")]
128    pub display_name: &'static str,
129    /// Destroy time (minecraft-data; `None` = unbreakable).
130    pub hardness: Option<f32>,
131    /// Explosion resistance (minecraft-data).
132    pub resistance: f32,
133    /// Can be mined (minecraft-data).
134    pub diggable: bool,
135    /// Lets light through (minecraft-data).
136    pub transparent: bool,
137    /// Light emitted (minecraft-data).
138    pub emit_light: u8,
139    /// Light filtered (minecraft-data).
140    pub filter_light: u8,
141    /// `Block.getFriction()` (jar).
142    pub friction: f32,
143    /// `Block.getSpeedFactor()` (jar).
144    pub speed_factor: f32,
145    /// `Block.getJumpFactor()` (jar).
146    pub jump_factor: f32,
147    /// [`block_flags`] bits.
148    pub flags: u32,
149    /// Special movement behaviour.
150    pub kind: BlockKind,
151    /// Model offset function: `(max horizontal, max vertical, xyz)`; bamboo and pointed dripstone
152    /// shift their collision shape by it.
153    pub offset: Option<(f32, f32, bool)>,
154}
155
156/// VoxelShape implementation class (decides how a coordinate maps to a cell index in vanilla).
157#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
158pub enum VoxelClass {
159    /// `CubeVoxelShape`: points are `i / n`; vanilla indexes with `floor(c * n)`, clamped.
160    Simple,
161    /// `ArrayVoxelShape`: explicit point lists; vanilla binary-searches them.
162    Array,
163}
164
165/// A vanilla 26.1 collision `VoxelShape` (block-local), exactly as the jar has it.
166#[derive(Clone, Copy, Debug, PartialEq)]
167pub struct VoxelShapeRef {
168    /// Implementation class.
169    pub class: VoxelClass,
170    /// Cell counts `[nx, ny, nz]` (`0, 0, 0` for the empty shape).
171    pub sizes: [u8; 3],
172    /// `getCoords(X)` (`nx + 1` values; the empty shape has `[0.0]`).
173    pub xs: &'static [f64],
174    /// `getCoords(Y)`.
175    pub ys: &'static [f64],
176    /// `getCoords(Z)`.
177    pub zs: &'static [f64],
178    /// Filled-cell bitset, bit index `(x * ny + y) * nz + z`, 64 bits per word.
179    pub cells: &'static [u64],
180    /// `VoxelShape.isEmpty()`.
181    pub empty: bool,
182    /// `toAabbs()` in vanilla's order.
183    pub boxes: &'static [Aabb],
184}
185
186impl VoxelShapeRef {
187    /// `true` when cell (`x`, `y`, `z`) is filled; `false` outside the grid.
188    #[must_use]
189    pub fn filled(&self, x: usize, y: usize, z: usize) -> bool {
190        let [nx, ny, nz] = self.sizes.map(usize::from);
191        if x >= nx || y >= ny || z >= nz {
192            return false;
193        }
194        let i = (x * ny + y) * nz + z;
195        self.cells[i / 64] & (1 << (i % 64)) != 0
196    }
197}
198
199/// The collision voxel shape table (index 0 = empty).
200#[must_use]
201pub fn voxel_shapes() -> &'static [VoxelShapeRef] {
202    &g::blocks::VOXEL_SHAPES
203}
204
205/// Index of `Shapes.block()` in [`voxel_shapes`].
206pub const FULL_CUBE_VOXEL: u16 = g::blocks::FULL_CUBE_VOXEL;
207/// Index of scaffolding's bottom shape in [`voxel_shapes`].
208pub const SCAFFOLDING_BOTTOM_VOXEL: u16 = g::blocks::SCAFFOLDING_BOTTOM_VOXEL;
209/// Index of powder snow's falling shape (`box(0, 0, 0, 1, 0.9F, 1)`) in [`voxel_shapes`].
210pub const POWDER_SNOW_FALLING_VOXEL: u16 = g::blocks::POWDER_SNOW_FALLING_VOXEL;
211
212/// The packed per-state record of the movement code (one `u64` per state).
213#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
214pub struct StatePhys(pub u64);
215
216/// Bits of [`StatePhys::flags`].
217pub mod state_flags {
218    /// The collision shape is `Shapes.block()` (identity; vanilla's fast path).
219    pub const FULL_CUBE: u16 = 1;
220    /// The context-free collision shape is empty.
221    pub const EMPTY: u16 = 2;
222    /// `hasLargeCollisionShape()` (shape exceeds the unit cube, or dynamic bounds).
223    pub const LARGE: u16 = 4;
224    /// `isSuffocating()`.
225    pub const SUFFOCATING: u16 = 8;
226    /// `isAir()`.
227    pub const AIR: u16 = 16;
228    /// `blocksMotion()`.
229    pub const BLOCKS_MOTION: u16 = 32;
230    /// `isFaceSturdy(NORTH)`; the next three bits are EAST, SOUTH, WEST.
231    pub const STURDY_NORTH: u16 = 64;
232    /// The collision shape depends on the colliding entity (scaffolding, powder snow).
233    pub const CONTEXT: u16 = 1 << 10;
234    /// The collision shape is shifted by the block's model offset (bamboo, pointed dripstone);
235    /// [`super::StatePhys::shape`] is the unshifted shape.
236    pub const OFFSET: u16 = 1 << 11;
237    /// `moving_piston`.
238    pub const MOVING_PISTON: u16 = 1 << 12;
239}
240
241impl StatePhys {
242    /// Collision shape index into [`voxel_shapes`] (context-free; unshifted for offset blocks).
243    #[inline]
244    #[must_use]
245    pub const fn shape(self) -> u16 {
246        self.0 as u16
247    }
248
249    /// [`state_flags`] bits.
250    #[inline]
251    #[must_use]
252    pub const fn flags(self) -> u16 {
253        (self.0 >> 16) as u16
254    }
255
256    /// `true` when all of `bits` are set.
257    #[inline]
258    #[must_use]
259    pub const fn has(self, bits: u16) -> bool {
260        self.flags() & bits == bits
261    }
262
263    /// Fluid byte: bits 6-7 kind (0 none, 1 water, 2 lava), bit 4 falling, bits 0-3 amount 1..=8.
264    #[inline]
265    #[must_use]
266    pub const fn fluid(self) -> u8 {
267        (self.0 >> 32) as u8
268    }
269
270    /// Per-kind extra bits (see [`BlockKind`] and [`block_flags::TRAPDOOR`]).
271    #[inline]
272    #[must_use]
273    pub const fn aux(self) -> u8 {
274        (self.0 >> 40) as u8
275    }
276
277    /// The block's [`BlockKind`] discriminant.
278    #[inline]
279    #[must_use]
280    pub const fn kind(self) -> u8 {
281        (self.0 >> 48) as u8
282    }
283}
284
285/// A 26.1 block type (registry id).
286#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
287pub struct Block(pub(crate) u16);
288
289impl Block {
290    /// The block with this registry id.
291    #[must_use]
292    pub const fn from_id(id: u16) -> Option<Block> {
293        if (id as usize) < BLOCK_COUNT {
294            Some(Block(id))
295        } else {
296            None
297        }
298    }
299
300    /// Looks a block up by registry name (`"oak_stairs"`, no namespace).
301    #[must_use]
302    pub fn from_name(name: &str) -> Option<Block> {
303        lookup_name(&g::blocks::BLOCK_NAMES, name).map(Block)
304    }
305
306    /// Registry id.
307    #[must_use]
308    pub const fn id(self) -> u16 {
309        self.0
310    }
311
312    /// Static data.
313    #[inline]
314    #[must_use]
315    pub fn data(self) -> &'static BlockData {
316        &g::blocks::BLOCKS[self.0 as usize]
317    }
318
319    /// Registry name.
320    #[must_use]
321    pub fn name(self) -> &'static str {
322        self.data().name
323    }
324
325    /// `true` for `air`, `cave_air` and `void_air` (vanilla `BlockState.isAir`).
326    #[must_use]
327    pub const fn is_air(self) -> bool {
328        matches!(self, Block::AIR | Block::CAVE_AIR | Block::VOID_AIR)
329    }
330
331    /// State-id layout.
332    #[must_use]
333    pub fn layout(self) -> &'static StateLayout {
334        &g::blocks::LAYOUTS[self.0 as usize]
335    }
336
337    /// The default state.
338    #[must_use]
339    pub fn default_state(self) -> BlockState {
340        BlockState(self.layout().default_state)
341    }
342
343    /// All states of this block in id order.
344    pub fn states(self) -> impl ExactSizeIterator<Item = BlockState> {
345        let l = self.layout();
346        (l.min_state..l.min_state + l.state_count).map(BlockState)
347    }
348
349    /// The block's properties, most significant first.
350    pub fn properties(self) -> impl ExactSizeIterator<Item = &'static PropertyDef> {
351        self.layout()
352            .properties
353            .iter()
354            .map(|&i| &g::blocks::PROPERTY_DEFS[i as usize])
355    }
356
357    /// The default state with the given properties changed; `None` if a property or value does not
358    /// exist for this block.
359    #[must_use]
360    pub fn state_with(self, props: &[(Property, &str)]) -> Option<BlockState> {
361        props
362            .iter()
363            .try_fold(self.default_state(), |s, &(p, v)| s.with(p, v))
364    }
365
366    /// All blocks in id order.
367    pub fn all() -> impl ExactSizeIterator<Item = Block> {
368        (0..BLOCK_COUNT as u16).map(Block)
369    }
370}
371
372/// A 26.1 block state (global palette id).
373#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
374pub struct BlockState(u16);
375
376impl BlockState {
377    /// `minecraft:air` (id 0).
378    pub const AIR: BlockState = BlockState(0);
379
380    /// Wraps a palette id; `None` if out of range.
381    #[must_use]
382    pub const fn from_id(id: u16) -> Option<BlockState> {
383        if (id as usize) < STATE_COUNT {
384            Some(BlockState(id))
385        } else {
386            None
387        }
388    }
389
390    /// Palette id.
391    #[inline]
392    #[must_use]
393    pub const fn id(self) -> u16 {
394        self.0
395    }
396
397    /// The block type.
398    #[inline]
399    #[must_use]
400    pub fn block(self) -> Block {
401        Block(g::blocks::STATE_BLOCK[self.0 as usize])
402    }
403
404    /// `true` for `air`, `cave_air` and `void_air`.
405    #[must_use]
406    pub fn is_air(self) -> bool {
407        self.phys().has(state_flags::AIR)
408    }
409
410    /// The packed movement record (one table read).
411    #[inline]
412    #[must_use]
413    pub fn phys(self) -> StatePhys {
414        StatePhys(g::blocks::STATE_PHYS[self.0 as usize])
415    }
416
417    /// The context-free collision voxel shape (unshifted for offset blocks).
418    #[must_use]
419    pub fn voxel_shape(self) -> &'static VoxelShapeRef {
420        &g::blocks::VOXEL_SHAPES[self.phys().shape() as usize]
421    }
422
423    /// The crosshair outline shape (`getShape` / `getOutlineShape` with the player's context,
424    /// empty hand). For states with [`BlockState::outline_offset`] this is the unshifted shape: the
425    /// block moves it by its per-position model offset.
426    #[must_use]
427    pub fn outline_shape(self) -> &'static SelectionShape {
428        &g::selection::SELECTION_SHAPES[g::selection::STATE_OUTLINE[self.0 as usize] as usize]
429    }
430
431    /// The outline while the player holds this block's own item (scaffolding and, where it
432    /// exists, the light block show a full cube then); otherwise [`BlockState::outline_shape`].
433    #[must_use]
434    pub fn outline_shape_holding_own_item(self) -> &'static SelectionShape {
435        let t = &g::selection::OUTLINE_HOLDING_OWN_ITEM;
436        match t.binary_search_by_key(&self.0, |e| e.0) {
437            Ok(i) => &g::selection::SELECTION_SHAPES[t[i].1 as usize],
438            Err(_) => self.outline_shape(),
439        }
440    }
441
442    /// `true` when the outline is moved by the block's model offset (flowers, bamboo, ...).
443    #[must_use]
444    pub fn outline_offset(self) -> bool {
445        g::selection::STATE_OUTLINE_OFFSET[self.0 as usize / 64] & (1 << (self.0 % 64)) != 0
446    }
447
448    /// The interaction shape (`getInteractionShape`): when the ray hits it nearer than the outline,
449    /// the hit keeps the outline's position but takes this shape's face (cauldrons, composters,
450    /// hoppers, scaffolding).
451    #[must_use]
452    pub fn interaction_shape(self) -> &'static SelectionShape {
453        &g::selection::SELECTION_SHAPES[g::selection::STATE_INTERACTION[self.0 as usize] as usize]
454    }
455
456    /// Index of `prop`'s value in [`PropertyDef::values`], if the block has that property.
457    #[must_use]
458    pub fn get_index(self, prop: Property) -> Option<usize> {
459        let layout = self.block().layout();
460        let mut rem = usize::from(self.0 - layout.min_state);
461        for &d in layout.properties.iter().rev() {
462            let def = &g::blocks::PROPERTY_DEFS[d as usize];
463            let n = def.values.len();
464            if def.property == prop {
465                return Some(rem % n);
466            }
467            rem /= n;
468        }
469        None
470    }
471
472    /// The value of `prop` (`"north"`, `"true"`, `"3"`), if the block has that property.
473    #[must_use]
474    pub fn get(self, prop: Property) -> Option<&'static str> {
475        let def = self.block().properties().find(|d| d.property == prop)?;
476        self.get_index(prop).map(|i| def.values[i])
477    }
478
479    /// This state with `prop` set to `value`; `None` if the block lacks the property or value.
480    #[must_use]
481    pub fn with(self, prop: Property, value: &str) -> Option<BlockState> {
482        let layout = self.block().layout();
483        let mut stride = 1usize;
484        for &d in layout.properties.iter().rev() {
485            let def = &g::blocks::PROPERTY_DEFS[d as usize];
486            let n = def.values.len();
487            if def.property == prop {
488                let new = def.values.iter().position(|v| *v == value)?;
489                let base = usize::from(self.0 - layout.min_state);
490                let old = base / stride % n;
491                let id = base - old * stride + new * stride + usize::from(layout.min_state);
492                return Some(BlockState(id as u16));
493            }
494            stride *= n;
495        }
496        None
497    }
498
499    /// `(property, value)` pairs of this state, most significant property first.
500    pub fn properties(self) -> impl Iterator<Item = (Property, &'static str)> {
501        let block = self.block();
502        block
503            .properties()
504            .filter_map(move |d| self.get(d.property).map(|v| (d.property, v)))
505    }
506
507    /// Parses `minecraft:name[prop=value,...]` (the namespace is optional).
508    #[must_use]
509    pub fn parse(s: &str) -> Option<BlockState> {
510        let s = s.strip_prefix("minecraft:").unwrap_or(s);
511        let (name, props) = match s.split_once('[') {
512            Some((n, rest)) => (n, rest.strip_suffix(']')?),
513            None => (s, ""),
514        };
515        let mut st = Block::from_name(name)?.default_state();
516        for kv in props.split(',').filter(|p| !p.is_empty()) {
517            let (k, v) = kv.split_once('=')?;
518            st = st.with(Property::from_name(k)?, v)?;
519        }
520        Some(st)
521    }
522}
523
524/// `minecraft:oak_stairs[facing=north,half=bottom,...]`, the vanilla block-state string form.
525impl fmt::Display for BlockState {
526    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
527        write!(f, "minecraft:{}", self.block().name())?;
528        let mut first = true;
529        for (p, v) in self.properties() {
530            f.write_str(if first { "[" } else { "," })?;
531            write!(f, "{}={v}", p.name())?;
532            first = false;
533        }
534        if !first {
535            f.write_str("]")?;
536        }
537        Ok(())
538    }
539}
540
541#[cfg(test)]
542mod tests;