Skip to main content

ghast_data/v1_16_5/
mod.rs

1//! Minecraft 1.16.5 (protocol 754) data: global block-state palette with properties.
2//!
3//! A [`BlockState`] is the global palette id used on the wire and in chunk sections
4//! (`0..STATE_COUNT`). Each [`Block`] owns a contiguous id range; the state's properties are a
5//! mixed-radix number over that range with the first property most significant (vanilla order).
6//! In 1.16 neighbour connections (fences, panes, walls, stairs, doors, chests) are part of the
7//! state, so their collision shapes are static per state; the few that are not are flagged with a
8//! [`ShapeDependency`].
9
10use crate::common::{
11    Aabb, BiomeInfo, BlockInfo, BlockPhysics, Collision, DigMaterial, EffectInfo, EnchantmentInfo,
12    EntityInfo, EntityKind, Fluid, FluidKind, FoodInfo, ItemInfo, SelectionShape, ShapeDependency,
13    lookup_id, lookup_name,
14};
15use crate::generated::v1_16_5 as g;
16
17pub mod dig;
18use core::fmt;
19
20pub use g::blocks::{Material, Property};
21
22/// Number of blocks (ids `0..BLOCK_COUNT`).
23pub const BLOCK_COUNT: usize = g::blocks::BLOCKS.len();
24/// Number of block states (ids `0..STATE_COUNT`).
25pub const STATE_COUNT: usize = g::blocks::STATE_BLOCK.len();
26
27impl Property {
28    /// Looks a property up by name (`"facing"`).
29    #[must_use]
30    pub fn from_name(name: &str) -> Option<Property> {
31        lookup_name(&g::blocks::PROPERTY_NAMES, name)
32    }
33}
34
35/// One property of a block with its possible values, in palette order.
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub struct PropertyDef {
38    /// Which property.
39    pub property: Property,
40    /// Values in palette order (booleans are `["true", "false"]`, integers `"0"`, `"1"`, ...).
41    pub values: &'static [&'static str],
42}
43
44/// The state-id layout of one block.
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub struct StateLayout {
47    /// First state id.
48    pub min_state: u16,
49    /// Number of states.
50    pub state_count: u16,
51    /// Default state id.
52    pub default_state: u16,
53    /// Indices into the property definition table, most significant first.
54    pub(crate) properties: &'static [u8],
55}
56
57/// Vanilla model offset type (`AbstractBlock.OffsetType`): bamboo and plants are shifted by a
58/// per-position pseudo-random offset.
59#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
60pub enum OffsetType {
61    /// No offset.
62    None,
63    /// Horizontal offset (bamboo's collision shape follows it).
64    Xz,
65    /// Horizontal and vertical offset.
66    Xyz,
67}
68
69/// Vanilla 1.16.5 per-block facts dumped by the oracle.
70#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
71pub struct VanillaBlock {
72    /// `AbstractBlock.collidable` (false for plants, cobweb, fluids, ...).
73    pub collidable: bool,
74    /// Model / shape offset type.
75    pub offset: OffsetType,
76}
77
78/// Scaffolding's context-dependent collision shapes; pick one with [`ScaffoldingShapes::select`].
79///
80/// Vanilla (`ScaffoldingBlock.getCollisionShape`), confirmed by the oracle's feet-height sweep:
81/// `stable` when the entity's feet `minY > y + 1 - 1.0E-5F` and it is not descending (sneaking);
82/// otherwise `bottom` when the state has `bottom=true`, `distance != 0` and `minY > y + 0 - 1.0E-5F`
83/// (`OUTLINE_SHAPE` is the full cube offset down by one, max Y 0); otherwise empty.
84#[derive(Clone, Copy, Debug, PartialEq)]
85pub struct ScaffoldingShapes {
86    /// The full (stable) shape, also [`BlockState::shape`].
87    pub stable: &'static [Aabb],
88    /// The bottom "collision" shape.
89    pub bottom: &'static [Aabb],
90    /// `stable` as a VoxelShape.
91    pub stable_voxel: &'static VoxelShapeRef,
92    /// `bottom` as a VoxelShape (the empty shape when there is none).
93    pub bottom_voxel: &'static VoxelShapeRef,
94    /// The state has a bottom shape (`bottom=true`, `distance != 0`).
95    pub has_bottom: bool,
96}
97
98impl ScaffoldingShapes {
99    /// The collision shape vanilla uses for an entity whose box bottom is `feet_min_y`, against
100    /// the scaffolding block at height `block_y`. Returns the boxes and the VoxelShape.
101    #[must_use]
102    pub fn select(
103        &self,
104        feet_min_y: f64,
105        block_y: i32,
106        descending: bool,
107    ) -> (&'static [Aabb], &'static VoxelShapeRef) {
108        let eps = f64::from(1.0e-5_f32);
109        if feet_min_y > f64::from(block_y) + 1.0 - eps && !descending {
110            (self.stable, self.stable_voxel)
111        } else if self.has_bottom && feet_min_y > f64::from(block_y) + 0.0 - eps {
112            (self.bottom, self.bottom_voxel)
113        } else {
114            (&[], &g::blocks::VOXEL_SHAPES[0])
115        }
116    }
117}
118
119/// VoxelShape implementation class (decides how a coordinate maps to a cell index in vanilla).
120#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
121pub enum VoxelClass {
122    /// `SimpleVoxelShape`: points are `i / n`; vanilla indexes with `floor(c * n)`, clamped.
123    Simple,
124    /// `ArrayVoxelShape`: explicit point lists; vanilla binary-searches them.
125    Array,
126}
127
128/// A vanilla 1.16.5 collision `VoxelShape` (block-local), exactly as the oracle dumped it.
129#[derive(Clone, Copy, Debug, PartialEq)]
130pub struct VoxelShapeRef {
131    /// Implementation class.
132    pub class: VoxelClass,
133    /// Cell counts `[nx, ny, nz]` (`0, 0, 0` for the empty shape).
134    pub sizes: [u8; 3],
135    /// `getPointPositions(X)` (`nx + 1` values; the empty shape has `[0.0]`).
136    pub xs: &'static [f64],
137    /// `getPointPositions(Y)`.
138    pub ys: &'static [f64],
139    /// `getPointPositions(Z)`.
140    pub zs: &'static [f64],
141    /// Filled-cell bitset, bit index `(x * ny + y) * nz + z`, 64 bits per word.
142    pub cells: &'static [u64],
143    /// `VoxelShape.isEmpty()`.
144    pub empty: bool,
145}
146
147impl VoxelShapeRef {
148    /// `true` when cell (`x`, `y`, `z`) is filled; `false` outside the grid.
149    #[must_use]
150    pub fn filled(&self, x: usize, y: usize, z: usize) -> bool {
151        let [nx, ny, nz] = self.sizes.map(usize::from);
152        if x >= nx || y >= ny || z >= nz {
153            return false;
154        }
155        let i = (x * ny + y) * nz + z;
156        self.cells[i / 64] & (1 << (i % 64)) != 0
157    }
158}
159
160/// Block side for [`BlockState::side_solid_full_square`].
161#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
162pub enum Side {
163    /// -Z.
164    North = 0,
165    /// +X.
166    East = 1,
167    /// +Z.
168    South = 2,
169    /// -X.
170    West = 3,
171    /// +Y.
172    Up = 4,
173    /// -Y.
174    Down = 5,
175}
176
177/// A 1.16.5 block type (registry id).
178#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
179pub struct Block(pub(crate) u16);
180
181impl Block {
182    /// The block with this registry id.
183    #[must_use]
184    pub const fn from_id(id: u16) -> Option<Block> {
185        if (id as usize) < BLOCK_COUNT {
186            Some(Block(id))
187        } else {
188            None
189        }
190    }
191
192    /// Looks a block up by registry name (`"oak_stairs"`, no namespace).
193    #[must_use]
194    pub fn from_name(name: &str) -> Option<Block> {
195        lookup_name(&g::blocks::BLOCK_NAMES, name).map(Block)
196    }
197
198    /// Registry id.
199    #[must_use]
200    pub const fn id(self) -> u16 {
201        self.0
202    }
203
204    /// Static information (names, hardness, drops, physics).
205    #[must_use]
206    pub fn info(self) -> &'static BlockInfo {
207        &g::blocks::BLOCKS[self.0 as usize]
208    }
209
210    /// Registry name.
211    #[must_use]
212    pub fn name(self) -> &'static str {
213        self.info().name
214    }
215
216    /// Physics properties.
217    #[must_use]
218    pub fn physics(self) -> &'static BlockPhysics {
219        &g::blocks::BLOCKS[self.0 as usize].physics
220    }
221
222    /// What the collision shape depends on besides the state.
223    #[must_use]
224    pub fn shape_dependency(self) -> ShapeDependency {
225        g::blocks::BLOCK_SHAPE_DEPENDENCY[self.0 as usize]
226    }
227
228    /// `true` for `air`, `cave_air` and `void_air` (vanilla `BlockState.isAir`).
229    #[must_use]
230    pub const fn is_air(self) -> bool {
231        matches!(self, Block::AIR | Block::CAVE_AIR | Block::VOID_AIR)
232    }
233
234    /// `true` for the 16 coloured beds (contiguous ids `WHITE_BED..=BLACK_BED`).
235    #[must_use]
236    pub const fn is_bed(self) -> bool {
237        self.0 >= Block::WHITE_BED.0 && self.0 <= Block::BLACK_BED.0
238    }
239
240    /// Vanilla material (Yarn `Material` field), per block as in vanilla.
241    #[must_use]
242    pub fn material(self) -> Material {
243        g::blocks::BLOCK_MATERIAL[self.0 as usize]
244    }
245
246    /// Vanilla per-block facts (oracle).
247    #[must_use]
248    pub fn vanilla(self) -> &'static VanillaBlock {
249        &g::blocks::VANILLA_BLOCKS[self.0 as usize]
250    }
251
252    /// State-id layout.
253    #[must_use]
254    pub fn layout(self) -> &'static StateLayout {
255        &g::blocks::LAYOUTS[self.0 as usize]
256    }
257
258    /// The default state.
259    #[must_use]
260    pub fn default_state(self) -> BlockState {
261        BlockState(self.layout().default_state)
262    }
263
264    /// All states of this block in id order.
265    pub fn states(self) -> impl ExactSizeIterator<Item = BlockState> {
266        let l = self.layout();
267        (l.min_state..l.min_state + l.state_count).map(BlockState)
268    }
269
270    /// The block's properties, most significant first.
271    pub fn properties(self) -> impl ExactSizeIterator<Item = &'static PropertyDef> {
272        self.layout()
273            .properties
274            .iter()
275            .map(|&i| &g::blocks::PROPERTY_DEFS[i as usize])
276    }
277
278    /// The default state with the given properties changed; `None` if a property or value does not
279    /// exist for this block.
280    #[must_use]
281    pub fn state_with(self, props: &[(Property, &str)]) -> Option<BlockState> {
282        props
283            .iter()
284            .try_fold(self.default_state(), |s, &(p, v)| s.with(p, v))
285    }
286
287    /// All blocks in id order.
288    pub fn all() -> impl ExactSizeIterator<Item = Block> {
289        (0..BLOCK_COUNT as u16).map(Block)
290    }
291}
292
293/// A 1.16.5 block state (global palette id).
294#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
295pub struct BlockState(u16);
296
297impl BlockState {
298    /// `minecraft:air` (id 0).
299    pub const AIR: BlockState = BlockState(0);
300
301    /// Wraps a palette id; `None` if out of range.
302    #[must_use]
303    pub const fn from_id(id: u16) -> Option<BlockState> {
304        if (id as usize) < STATE_COUNT {
305            Some(BlockState(id))
306        } else {
307            None
308        }
309    }
310
311    /// Palette id.
312    #[must_use]
313    pub const fn id(self) -> u16 {
314        self.0
315    }
316
317    /// The block type.
318    #[must_use]
319    pub fn block(self) -> Block {
320        Block(g::blocks::STATE_BLOCK[self.0 as usize])
321    }
322
323    /// `true` for `air`, `cave_air` and `void_air`.
324    #[must_use]
325    pub fn is_air(self) -> bool {
326        self.block().is_air()
327    }
328
329    /// Collision boxes and what else they depend on. Hot path: three table lookups.
330    #[must_use]
331    pub fn collision(self) -> Collision {
332        Collision {
333            boxes: self.shape(),
334            dependency: g::blocks::BLOCK_SHAPE_DEPENDENCY
335                [g::blocks::STATE_BLOCK[self.0 as usize] as usize],
336            // 1.16 places shapes with double arithmetic (VoxelShape offset).
337            world_coords: None,
338        }
339    }
340
341    /// `true` when the collision shape is exactly a full cube (oracle `full_cube`).
342    #[must_use]
343    pub fn full_cube(self) -> bool {
344        g::blocks::STATE_VANILLA_FLAGS[self.0 as usize] & 1 != 0
345    }
346
347    /// `AbstractBlockState.isSolidBlock` (oracle `solid_block`).
348    #[must_use]
349    pub fn solid_block(self) -> bool {
350        g::blocks::STATE_VANILLA_FLAGS[self.0 as usize] & 2 != 0
351    }
352
353    /// `AbstractBlockState.shouldSuffocate` (oracle `suffocates`).
354    #[must_use]
355    pub fn should_suffocate(self) -> bool {
356        g::blocks::STATE_VANILLA_FLAGS[self.0 as usize] & 4 != 0
357    }
358
359    /// The collision `VoxelShape` (context-free; see [`BlockState::scaffolding_shapes`]).
360    #[must_use]
361    pub fn voxel_shape(self) -> &'static VoxelShapeRef {
362        &g::blocks::VOXEL_SHAPES[g::blocks::STATE_VOXEL[self.0 as usize] as usize]
363    }
364
365    /// The crosshair outline shape (`getShape` / `getOutlineShape` with the player's context,
366    /// empty hand). For states with [`BlockState::outline_offset`] this is the unshifted shape: the
367    /// block moves it by its per-position model offset.
368    #[must_use]
369    pub fn outline_shape(self) -> &'static SelectionShape {
370        &g::selection::SELECTION_SHAPES[g::selection::STATE_OUTLINE[self.0 as usize] as usize]
371    }
372
373    /// The outline while the player holds this block's own item (scaffolding and, where it
374    /// exists, the light block show a full cube then); otherwise [`BlockState::outline_shape`].
375    #[must_use]
376    pub fn outline_shape_holding_own_item(self) -> &'static SelectionShape {
377        let t = &g::selection::OUTLINE_HOLDING_OWN_ITEM;
378        match t.binary_search_by_key(&self.0, |e| e.0) {
379            Ok(i) => &g::selection::SELECTION_SHAPES[t[i].1 as usize],
380            Err(_) => self.outline_shape(),
381        }
382    }
383
384    /// `true` when the outline is moved by the block's model offset (flowers, bamboo, ...).
385    #[must_use]
386    pub fn outline_offset(self) -> bool {
387        g::selection::STATE_OUTLINE_OFFSET[self.0 as usize / 64] & (1 << (self.0 % 64)) != 0
388    }
389
390    /// The raycast shape (`getRaycastShape`): when the ray hits it nearer than the outline, the
391    /// hit keeps the outline's position but takes this shape's side (cauldrons, composters,
392    /// hoppers, scaffolding).
393    #[must_use]
394    pub fn raycast_shape(self) -> &'static SelectionShape {
395        &g::selection::SELECTION_SHAPES[g::selection::STATE_INTERACTION[self.0 as usize] as usize]
396    }
397
398    fn voxel_flag(self, bit: u16) -> bool {
399        g::blocks::STATE_VOXEL_FLAGS[self.0 as usize] & bit != 0
400    }
401
402    /// The collision shape *is* `VoxelShapes.fullCube()` (identity, as vanilla's fast paths test).
403    #[must_use]
404    pub fn full_cube_identity(self) -> bool {
405        self.voxel_flag(1)
406    }
407
408    /// The collision shape *is* `VoxelShapes.empty()` (identity).
409    #[must_use]
410    pub fn empty_identity(self) -> bool {
411        self.voxel_flag(1 << 12)
412    }
413
414    /// `Material.isLiquid()` of the state's material.
415    #[must_use]
416    pub fn material_liquid(self) -> bool {
417        self.voxel_flag(1 << 13)
418    }
419
420    /// `Material.isSolid()` of the state's material.
421    #[must_use]
422    pub fn material_solid(self) -> bool {
423        self.voxel_flag(1 << 14)
424    }
425
426    /// `Material.isReplaceable()` of the state's material.
427    #[must_use]
428    pub fn material_replaceable(self) -> bool {
429        self.voxel_flag(1 << 15)
430    }
431
432    /// `AbstractBlockState.exceedsCube()`.
433    #[must_use]
434    pub fn exceeds_cube(self) -> bool {
435        self.voxel_flag(2)
436    }
437
438    /// `AbstractBlock.dynamicBounds` (no shape cache; shapes recomputed per query).
439    #[must_use]
440    pub fn has_dynamic_bounds(self) -> bool {
441        self.voxel_flag(16)
442    }
443
444    /// `Material.blocksMovement()` of the state's material.
445    #[must_use]
446    pub fn material_blocks_movement(self) -> bool {
447        self.voxel_flag(32)
448    }
449
450    /// `isSideSolidFullSquare(world, pos, side)` in an otherwise empty world.
451    #[must_use]
452    pub fn side_solid_full_square(self, side: Side) -> bool {
453        self.voxel_flag(64 << side as u16)
454    }
455
456    /// Scaffolding context shapes; `None` for other blocks.
457    #[must_use]
458    pub fn scaffolding_shapes(self) -> Option<ScaffoldingShapes> {
459        if self.block() != Block::SCAFFOLDING {
460            return None;
461        }
462        let has_bottom =
463            self.get(Property::Bottom) == Some("true") && self.get(Property::Distance) != Some("0");
464        Some(ScaffoldingShapes {
465            stable: self.shape(),
466            bottom: if has_bottom {
467                g::blocks::SCAFFOLDING_BOTTOM
468            } else {
469                &[]
470            },
471            stable_voxel: self.voxel_shape(),
472            has_bottom,
473            bottom_voxel: &g::blocks::VOXEL_SHAPES[if has_bottom {
474                g::blocks::SCAFFOLDING_BOTTOM_VOXEL as usize
475            } else {
476                0
477            }],
478        })
479    }
480
481    /// Collision boxes from the table.
482    #[must_use]
483    pub fn shape(self) -> &'static [Aabb] {
484        g::blocks::SHAPES[g::blocks::STATE_SHAPE[self.0 as usize] as usize]
485    }
486
487    /// Fluid in this state: water / lava blocks with their `level`, waterlogged states and
488    /// always-wet blocks (kelp, seagrass, bubble column) as water level 0.
489    #[must_use]
490    pub fn fluid(self) -> Option<Fluid> {
491        let f = g::blocks::STATE_FLUID[self.0 as usize];
492        let kind = match f >> 4 {
493            1 => FluidKind::Water,
494            2 => FluidKind::Lava,
495            _ => return None,
496        };
497        Some(Fluid {
498            kind,
499            level: f & 15,
500        })
501    }
502
503    /// Index of `prop`'s value in [`PropertyDef::values`], if the block has that property.
504    #[must_use]
505    pub fn get_index(self, prop: Property) -> Option<usize> {
506        let layout = self.block().layout();
507        let mut rem = usize::from(self.0 - layout.min_state);
508        for &d in layout.properties.iter().rev() {
509            let def = &g::blocks::PROPERTY_DEFS[d as usize];
510            let n = def.values.len();
511            if def.property == prop {
512                return Some(rem % n);
513            }
514            rem /= n;
515        }
516        None
517    }
518
519    /// The value of `prop` (`"north"`, `"true"`, `"3"`), if the block has that property.
520    #[must_use]
521    pub fn get(self, prop: Property) -> Option<&'static str> {
522        let def = self.property_def(prop)?;
523        self.get_index(prop).map(|i| def.values[i])
524    }
525
526    /// This state with `prop` set to `value`; `None` if the block lacks the property or value.
527    #[must_use]
528    pub fn with(self, prop: Property, value: &str) -> Option<BlockState> {
529        let layout = self.block().layout();
530        let mut stride = 1usize;
531        for &d in layout.properties.iter().rev() {
532            let def = &g::blocks::PROPERTY_DEFS[d as usize];
533            let n = def.values.len();
534            if def.property == prop {
535                let new = def.values.iter().position(|v| *v == value)?;
536                let base = usize::from(self.0 - layout.min_state);
537                let old = base / stride % n;
538                let id = base - old * stride + new * stride + usize::from(layout.min_state);
539                return Some(BlockState(id as u16));
540            }
541            stride *= n;
542        }
543        None
544    }
545
546    /// `(property, value)` pairs of this state, most significant property first.
547    pub fn properties(self) -> impl Iterator<Item = (Property, &'static str)> {
548        let block = self.block();
549        block
550            .properties()
551            .filter_map(move |d| self.get(d.property).map(|v| (d.property, v)))
552    }
553
554    fn property_def(self, prop: Property) -> Option<&'static PropertyDef> {
555        self.block().properties().find(|d| d.property == prop)
556    }
557}
558
559/// `minecraft:oak_stairs[facing=north,half=bottom,...]`, the vanilla block-state string form.
560impl fmt::Display for BlockState {
561    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
562        write!(f, "minecraft:{}", self.block().name())?;
563        let mut first = true;
564        for (p, v) in self.properties() {
565            f.write_str(if first { "[" } else { "," })?;
566            write!(f, "{}={v}", p.name())?;
567            first = false;
568        }
569        if !first {
570            f.write_str("]")?;
571        }
572        Ok(())
573    }
574}
575
576/// 1.16.5 slime / magma cube dimensions for metadata size `n` (vanilla: the type's 2.04 x 2.04
577/// `scaled(0.255F * n)`, eye height `0.625F * height`).
578#[must_use]
579#[allow(clippy::cast_precision_loss)]
580pub fn slime_dimensions(n: i32) -> crate::common::EntityDimensions {
581    let ratio = 0.255_f32 * n as f32;
582    let s = 2.04_f32 * ratio;
583    crate::common::EntityDimensions {
584        width: s,
585        height: s,
586        eye_height: 0.625 * s,
587    }
588}
589
590crate::macros::common_api!();