Skip to main content

ghast_data/v1_8/
mod.rs

1//! Minecraft 1.8.x (protocol 47) data: numeric block ids with 4-bit metadata.
2//!
3//! In 1.8 a block state travels on the wire and in chunk sections as one `u16`:
4//! `block_id << 4 | meta` ([`BlockState::raw`]). Block ids are `0..=197`; every meta `0..=15`
5//! is representable. Collision shapes are per (id, meta); blocks whose shape vanilla computes from
6//! neighbours report a [`ShapeDependency::Neighbours`] instead of pretending to be static.
7//!
8//! Unregistered combinations: vanilla 1.8 reads a raw value that no registered block state
9//! produces (unknown id, or a meta the block never uses, e.g. `stone:7`) as air.
10//! [`BlockState::is_registered`] tells them apart (registered set from the 1.8.9 oracle),
11//! [`BlockState::from_raw_vanilla`] applies vanilla's mapping, and the collision table already
12//! gives unregistered states no boxes.
13
14use crate::common::{
15    Aabb, BiomeInfo, BlockInfo, BlockPhysics, Collision, DigMaterial, EffectInfo, EnchantmentInfo,
16    EntityInfo, EntityKind, Fluid, FluidKind, FoodInfo, ItemInfo, NeighbourShape, PhysicsFlags,
17    ShapeDependency, lookup_id, lookup_name,
18};
19use crate::generated::v1_8 as g;
20
21pub mod dig;
22
23/// Number of blocks (ids `0..BLOCK_COUNT`).
24pub const BLOCK_COUNT: usize = g::blocks::BLOCKS.len();
25
26/// Identity of the vanilla 1.8 materials that vanilla code compares with `==`.
27#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
28pub enum MaterialKind {
29    /// `Material.AIR` (only `air`).
30    Air,
31    /// `Material.WATER` (`water`, `flowing_water`).
32    Water,
33    /// `Material.LAVA` (`lava`, `flowing_lava`).
34    Lava,
35    /// `Material.ICE` (only `ice`; `packed_ice` has its own material).
36    Ice,
37    /// Any other material.
38    Other,
39}
40
41/// A block's vanilla 1.8.9 material (flags from the oracle).
42#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
43pub struct Material {
44    /// Identity, for `== Material.X` checks.
45    pub kind: MaterialKind,
46    /// `Material.blocksMovement()`.
47    pub blocks_movement: bool,
48    /// `Material.isSolid()`.
49    pub solid: bool,
50    /// `Material.isFluid()`.
51    pub fluid: bool,
52    /// `Material.isOpaque()`.
53    pub opaque: bool,
54    /// `Material.isReplaceable()`.
55    pub replaceable: bool,
56}
57
58/// Vanilla 1.8.9 per-block flags, dumped by the oracle (`tests/golden/1.8.9/collision_boxes.jsonl.gz`
59/// `"type":"block"` lines). In 1.8 these are block-level, not per state.
60#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
61pub struct VanillaProps {
62    /// `Block.isFullCube()` (Yarn): used e.g. by `ClientPlayerEntity.pushOutOfBlocks`.
63    pub full_cube: bool,
64    /// `Block.isNormalBlock()`: material blocks movement and renders as a normal block.
65    pub normal_block: bool,
66    /// The `Block.fullBlock` field.
67    pub full_block: bool,
68    /// `Block.renderAsNormalBlock()`.
69    pub render_as_normal_block: bool,
70    /// `Block.hasCollision()` (the raytrace "collidable" check, not the collision box).
71    pub has_collision: bool,
72    /// The block's material.
73    pub material: Material,
74}
75
76/// What the 1.8.9 crosshair ray test (`Block.rayTrace` via `World.rayTrace`) sees of a block state.
77#[derive(Clone, Copy, Debug, PartialEq)]
78pub struct Selection {
79    /// Bounds after `setBoundingBox(world, pos)` with all neighbours air (block-local). For
80    /// neighbour-dependent blocks this is the isolated shape, see `dependency`.
81    pub bounds: Aabb,
82    /// Same classes as the collision dependency (fences, panes, walls, doors, chests, stairs).
83    pub dependency: ShapeDependency,
84    /// Stairs: vanilla's ray test runs 8 passes over half-cube sub-boxes instead of using `bounds`.
85    pub multi_pass_ray: bool,
86    /// `Block.canCollide(state, false)`: rays skip the block when false (air, fire, fluids, ...).
87    pub can_collide: bool,
88    /// `Block.canCollide(state, true)` (ray tests that stop at fluids).
89    pub can_collide_liquid: bool,
90    /// The block has a collision box (for `ignoreBlockWithoutBoundingBox` ray tests).
91    pub has_collision_box: bool,
92}
93
94/// A 1.8 block type (registry id `0..=197`).
95#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
96pub struct Block(pub(crate) u8);
97
98impl Block {
99    /// The block with this registry id, if it exists in 1.8.
100    #[must_use]
101    pub const fn from_id(id: u8) -> Option<Block> {
102        if (id as usize) < BLOCK_COUNT {
103            Some(Block(id))
104        } else {
105            None
106        }
107    }
108
109    /// Looks a block up by registry name (`"stone"`, no namespace).
110    #[must_use]
111    pub fn from_name(name: &str) -> Option<Block> {
112        lookup_name(g::blocks::BLOCK_NAMES_TEXT, &g::blocks::BLOCK_NAMES, name).map(Block)
113    }
114
115    /// Registry id.
116    #[must_use]
117    pub const fn id(self) -> u8 {
118        self.0
119    }
120
121    /// Static information (names, hardness, drops, physics).
122    #[must_use]
123    pub fn info(self) -> &'static BlockInfo {
124        &g::blocks::BLOCKS[self.0 as usize]
125    }
126
127    /// Registry name.
128    #[must_use]
129    pub fn name(self) -> &'static str {
130        self.info().name
131    }
132
133    /// Physics properties (slipperiness, climbable, ...).
134    #[must_use]
135    pub fn physics(self) -> &'static BlockPhysics {
136        &g::blocks::BLOCKS[self.0 as usize].physics
137    }
138
139    /// Vanilla 1.8.9 shape and material flags.
140    #[must_use]
141    pub fn vanilla(self) -> &'static VanillaProps {
142        &g::blocks::VANILLA_PROPS[self.0 as usize]
143    }
144
145    /// Vanilla material (shorthand for `self.vanilla().material`).
146    #[must_use]
147    pub fn material(self) -> Material {
148        g::blocks::VANILLA_PROPS[self.0 as usize].material
149    }
150
151    /// `Block.isFullCube()` (shorthand for `self.vanilla().full_cube`).
152    #[must_use]
153    pub fn full_cube(self) -> bool {
154        g::blocks::VANILLA_PROPS[self.0 as usize].full_cube
155    }
156
157    /// What the collision shape depends on besides (id, meta).
158    #[must_use]
159    pub fn shape_dependency(self) -> ShapeDependency {
160        g::blocks::BLOCK_SHAPE_DEPENDENCY[self.0 as usize]
161    }
162
163    /// The state with this metadata (`meta & 15`).
164    #[must_use]
165    pub const fn with_meta(self, meta: u8) -> BlockState {
166        BlockState(((self.0 as u16) << 4) | (meta & 15) as u16)
167    }
168
169    /// The state with metadata 0.
170    #[must_use]
171    pub const fn default_state(self) -> BlockState {
172        self.with_meta(0)
173    }
174
175    /// All blocks in id order.
176    pub fn all() -> impl ExactSizeIterator<Item = Block> {
177        (0..BLOCK_COUNT as u8).map(Block)
178    }
179}
180
181/// A 1.8 block state: `block_id << 4 | meta`, exactly the wire / chunk-section value.
182#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
183pub struct BlockState(u16);
184
185impl BlockState {
186    /// Air (raw 0).
187    pub const AIR: BlockState = BlockState(0);
188
189    /// Wraps a raw `id << 4 | meta` value; `None` if the block id is not a 1.8 block.
190    #[must_use]
191    pub const fn from_raw(raw: u16) -> Option<BlockState> {
192        if ((raw >> 4) as usize) < BLOCK_COUNT {
193            Some(BlockState(raw))
194        } else {
195            None
196        }
197    }
198
199    /// Vanilla's chunk-read mapping: unknown block ids and unregistered metas become air.
200    #[must_use]
201    pub fn from_raw_vanilla(raw: u16) -> BlockState {
202        match BlockState::from_raw(raw) {
203            Some(s) if s.is_registered() => s,
204            _ => BlockState::AIR,
205        }
206    }
207
208    /// `true` when vanilla 1.8.9 has a block state for this (id, meta); otherwise it reads as air.
209    #[must_use]
210    pub fn is_registered(self) -> bool {
211        g::blocks::REGISTERED_METAS[(self.0 >> 4) as usize] & (1 << (self.0 & 15)) != 0
212    }
213
214    /// Builds a state from a block and metadata (`meta & 15`).
215    #[must_use]
216    pub const fn new(block: Block, meta: u8) -> BlockState {
217        block.with_meta(meta)
218    }
219
220    /// The raw `id << 4 | meta` value.
221    #[must_use]
222    pub const fn raw(self) -> u16 {
223        self.0
224    }
225
226    /// The block type.
227    #[must_use]
228    pub const fn block(self) -> Block {
229        Block((self.0 >> 4) as u8)
230    }
231
232    /// Metadata `0..=15`.
233    #[must_use]
234    pub const fn meta(self) -> u8 {
235        (self.0 & 15) as u8
236    }
237
238    /// `true` for air.
239    #[must_use]
240    pub const fn is_air(self) -> bool {
241        self.0 >> 4 == 0
242    }
243
244    /// Collision boxes, what else they depend on, and how vanilla places them in the world
245    /// ([`Collision::world_box`]). Hot path: three table lookups.
246    #[must_use]
247    pub fn collision(self) -> Collision {
248        Collision {
249            boxes: g::blocks::SHAPES[g::blocks::STATE_SHAPE[self.0 as usize] as usize],
250            dependency: g::blocks::BLOCK_SHAPE_DEPENDENCY[(self.0 >> 4) as usize],
251            world_coords: g::blocks::WORLD_COORDS
252                [g::blocks::STATE_WORLD_COORDS[self.0 as usize] as usize],
253        }
254    }
255
256    /// Crosshair ray-test data (oracle `selection_boxes.jsonl.gz`).
257    #[must_use]
258    pub fn selection(self) -> Selection {
259        let f = g::blocks::STATE_SELECTION_FLAGS[self.0 as usize];
260        let dependency = g::blocks::BLOCK_SHAPE_DEPENDENCY[(self.0 >> 4) as usize];
261        Selection {
262            bounds: g::blocks::SELECTION_BOUNDS
263                [g::blocks::STATE_SELECTION[self.0 as usize] as usize],
264            dependency,
265            multi_pass_ray: dependency == ShapeDependency::Neighbours(NeighbourShape::Stairs),
266            can_collide: f & 1 != 0,
267            can_collide_liquid: f & 2 != 0,
268            has_collision_box: f & 4 != 0,
269        }
270    }
271
272    /// The collision boxes from the table (for dependent shapes: the isolated / default shape).
273    #[must_use]
274    pub fn shape(self) -> &'static [Aabb] {
275        g::blocks::SHAPES[g::blocks::STATE_SHAPE[self.0 as usize] as usize]
276    }
277
278    /// Fluid in this state (water / lava blocks; `level` = meta).
279    #[must_use]
280    pub fn fluid(self) -> Option<Fluid> {
281        let flags = self.block().physics().flags;
282        let kind = if flags.contains(PhysicsFlags::WATER) {
283            FluidKind::Water
284        } else if flags.contains(PhysicsFlags::LAVA) {
285            FluidKind::Lava
286        } else {
287            return None;
288        };
289        Some(Fluid {
290            kind,
291            level: self.meta(),
292        })
293    }
294}
295
296/// A 1.8.9 crafting recipe (from the oracle's dump of `RecipeDispatcher.getAllRecipes()`).
297///
298/// Ingredients are `(item id, data)`; data `32767` matches any damage value (vanilla's wildcard,
299/// used for block ingredients). Outputs are `(item id, count, damage)`; no output carries NBT.
300#[derive(Clone, Copy, Debug, PartialEq, Eq)]
301pub enum Recipe {
302    /// Shaped recipe: `inputs` is row-major, `width * height` slots, `None` = must be empty.
303    Shaped {
304        /// Pattern width.
305        width: u8,
306        /// Pattern height.
307        height: u8,
308        /// Row-major ingredients.
309        inputs: &'static [Option<(u16, u16)>],
310        /// Result `(id, count, damage)`.
311        output: (u16, u8, u16),
312    },
313    /// Shapeless recipe: every input must be matched by exactly one grid item.
314    Shapeless {
315        /// Ingredients in vanilla's list order.
316        inputs: &'static [(u16, u16)],
317        /// Result `(id, count, damage)`.
318        output: (u16, u8, u16),
319    },
320    /// A recipe implemented in code.
321    Special(SpecialRecipe),
322}
323
324/// Vanilla 1.8.9 code-defined recipes.
325#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
326pub enum SpecialRecipe {
327    /// `ArmorDyeRecipeType`: dye leather armour.
328    ArmorDye,
329    /// `FireworkRecipeType`: rockets, stars, star fades.
330    Firework,
331    /// `PatternRecipeType`: copy a patterned banner onto a blank banner of the same colour.
332    BannerDuplicate,
333    /// `BookCloningRecipeType`: copy a written book.
334    BookCloning,
335    /// `MapCloningRecipeType`: copy a map.
336    MapCloning,
337    /// `MapUpscaleRecipeType`: zoom a map out.
338    MapUpscale,
339    /// `RepairingRecipeType`: combine two damaged tools.
340    Repairing,
341    /// `CopyingRecipeType`: add a pattern to a banner with dye (appends to `BlockEntityTag.Patterns`).
342    BannerPattern,
343}
344
345/// Wildcard ingredient data value (matches any damage).
346pub const RECIPE_ANY_DATA: u16 = 32767;
347
348/// All 1.8.9 crafting recipes in vanilla's match order: the first that matches the grid wins.
349#[must_use]
350pub fn recipes() -> &'static [Recipe] {
351    &g::recipes::RECIPES
352}
353
354/// 1.8.9 slime / magma cube dimensions for metadata size `n` (vanilla `SlimeEntity.setSize`:
355/// `0.51000005F * n` square, eye height `0.625F * height`).
356#[must_use]
357#[allow(clippy::cast_precision_loss)]
358pub fn slime_dimensions(n: i32) -> crate::common::EntityDimensions {
359    let s = 0.510_000_05_f32 * n as f32;
360    crate::common::EntityDimensions {
361        width: s,
362        height: s,
363        eye_height: 0.625 * s,
364    }
365}
366
367crate::macros::common_api!();