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