ghast_data/modern.rs
1//! Types shared by the modern versions (26.1, 26.2): block kinds and flags, collision voxel
2//! shapes and the packed per-state movement record. `v26_1` and `v26_2` re-export them, so
3//! code written for one works with the other.
4
5use crate::common::{Aabb, EntityDimensions, VanillaEntitySize};
6
7/// Blocks the movement code treats specially.
8#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
9#[non_exhaustive]
10pub enum BlockKind {
11 /// Nothing special.
12 Other = 0,
13 /// `cobweb` (stuck multiplier 0.25 / 0.05).
14 Cobweb,
15 /// `sweet_berry_bush` (stuck multiplier 0.8 / 0.75).
16 SweetBerryBush,
17 /// `powder_snow` (entity-dependent collision, stuck multiplier, climbing with leather boots).
18 PowderSnow,
19 /// `honey_block` (wall slide).
20 HoneyBlock,
21 /// `bubble_column` (`aux` bit 0 = drag down).
22 BubbleColumn,
23 /// `slime_block` (bounce, step slowdown).
24 SlimeBlock,
25 /// `scaffolding` (`aux` bit 0 = has the bottom shape).
26 Scaffolding,
27 /// `ladder` (`aux` = facing: 0 N, 1 E, 2 S, 3 W).
28 Ladder,
29 /// `water`.
30 Water,
31 /// `lava`.
32 Lava,
33 /// `moving_piston`.
34 MovingPiston,
35}
36
37/// Bits of `BlockData::flags` (vanilla tags and `instanceof` tests of the movement code).
38pub mod block_flags {
39 /// `#minecraft:climbable`.
40 pub const CLIMBABLE: u32 = 1;
41 /// `#minecraft:fences`.
42 pub const FENCES: u32 = 2;
43 /// `#minecraft:walls`.
44 pub const WALLS: u32 = 4;
45 /// `instanceof FenceGateBlock`.
46 pub const FENCE_GATE: u32 = 8;
47 /// `instanceof TrapDoorBlock` (the state's `aux`: bit 0 open, bits 1-2 facing N/E/S/W).
48 pub const TRAPDOOR: u32 = 16;
49 /// `instanceof IceBlock` (ice, frosted ice).
50 pub const ICE: u32 = 32;
51 /// `instanceof BedBlock`.
52 pub const BED: u32 = 64;
53 /// `#minecraft:fall_damage_resetting`.
54 pub const FALL_DAMAGE_RESETTING: u32 = 128;
55 /// `#minecraft:soul_speed_blocks`.
56 pub const SOUL_SPEED_BLOCKS: u32 = 256;
57 /// `#minecraft:fire`.
58 pub const FIRE: u32 = 512;
59 /// `#minecraft:can_glide_through` (vines: not climbable for a gliding player).
60 pub const CAN_GLIDE_THROUGH: u32 = 1024;
61}
62
63/// VoxelShape implementation class (decides how a coordinate maps to a cell index in vanilla).
64#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
65pub enum VoxelClass {
66 /// `CubeVoxelShape`: points are `i / n`; vanilla indexes with `floor(c * n)`, clamped.
67 Simple,
68 /// `ArrayVoxelShape`: explicit point lists; vanilla binary-searches them.
69 Array,
70}
71
72/// A vanilla collision `VoxelShape` (block-local), exactly as the jar has it.
73#[derive(Clone, Copy, Debug, PartialEq)]
74pub struct VoxelShapeRef {
75 /// Implementation class.
76 pub class: VoxelClass,
77 /// Cell counts `[nx, ny, nz]` (`0, 0, 0` for the empty shape).
78 pub sizes: [u8; 3],
79 /// `getCoords(X)` (`nx + 1` values; the empty shape has `[0.0]`).
80 pub xs: &'static [f64],
81 /// `getCoords(Y)`.
82 pub ys: &'static [f64],
83 /// `getCoords(Z)`.
84 pub zs: &'static [f64],
85 /// Filled-cell bitset, bit index `(x * ny + y) * nz + z`, 64 bits per word.
86 pub cells: &'static [u64],
87 /// `VoxelShape.isEmpty()`.
88 pub empty: bool,
89 /// `toAabbs()` in vanilla's order.
90 pub boxes: &'static [Aabb],
91}
92
93impl VoxelShapeRef {
94 /// `true` when cell (`x`, `y`, `z`) is filled; `false` outside the grid.
95 #[must_use]
96 pub fn filled(&self, x: usize, y: usize, z: usize) -> bool {
97 let [nx, ny, nz] = self.sizes.map(usize::from);
98 if x >= nx || y >= ny || z >= nz {
99 return false;
100 }
101 let i = (x * ny + y) * nz + z;
102 self.cells[i / 64] & (1 << (i % 64)) != 0
103 }
104}
105
106/// The packed per-state record of the movement code (one `u64` per state).
107#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
108pub struct StatePhys(pub u64);
109
110/// Bits of [`StatePhys::flags`].
111pub mod state_flags {
112 /// The collision shape is `Shapes.block()` (identity; vanilla's fast path).
113 pub const FULL_CUBE: u16 = 1;
114 /// The context-free collision shape is empty.
115 pub const EMPTY: u16 = 2;
116 /// `hasLargeCollisionShape()` (shape exceeds the unit cube, or dynamic bounds).
117 pub const LARGE: u16 = 4;
118 /// `isSuffocating()`.
119 pub const SUFFOCATING: u16 = 8;
120 /// `isAir()`.
121 pub const AIR: u16 = 16;
122 /// `blocksMotion()`.
123 pub const BLOCKS_MOTION: u16 = 32;
124 /// `isFaceSturdy(NORTH)`; the next three bits are EAST, SOUTH, WEST.
125 pub const STURDY_NORTH: u16 = 64;
126 /// The collision shape depends on the colliding entity (scaffolding, powder snow).
127 pub const CONTEXT: u16 = 1 << 10;
128 /// The collision shape is shifted by the block's model offset (bamboo, pointed dripstone);
129 /// [`super::StatePhys::shape`] is the unshifted shape.
130 pub const OFFSET: u16 = 1 << 11;
131 /// `moving_piston`.
132 pub const MOVING_PISTON: u16 = 1 << 12;
133}
134
135impl StatePhys {
136 /// Collision shape index into `voxel_shapes()` of the version (context-free; unshifted for offset blocks).
137 #[inline]
138 #[must_use]
139 pub const fn shape(self) -> u16 {
140 self.0 as u16
141 }
142
143 /// [`state_flags`] bits.
144 #[inline]
145 #[must_use]
146 pub const fn flags(self) -> u16 {
147 (self.0 >> 16) as u16
148 }
149
150 /// `true` when all of `bits` are set.
151 #[inline]
152 #[must_use]
153 pub const fn has(self, bits: u16) -> bool {
154 self.flags() & bits == bits
155 }
156
157 /// Fluid byte: bits 6-7 kind (0 none, 1 water, 2 lava), bit 4 falling, bits 0-3 amount 1..=8.
158 #[inline]
159 #[must_use]
160 pub const fn fluid(self) -> u8 {
161 (self.0 >> 32) as u8
162 }
163
164 /// Per-kind extra bits (see [`BlockKind`] and [`block_flags::TRAPDOOR`]).
165 #[inline]
166 #[must_use]
167 pub const fn aux(self) -> u8 {
168 (self.0 >> 40) as u8
169 }
170
171 /// The block's [`BlockKind`] discriminant.
172 #[inline]
173 #[must_use]
174 pub const fn kind(self) -> u8 {
175 (self.0 >> 48) as u8
176 }
177}
178
179/// Bits of [`EntityTypeData::flags`].
180pub mod type_flags {
181 /// `instanceof LivingEntity` (has attributes, a head rotation, the sleeping pose).
182 pub const LIVING: u8 = 1;
183 /// `isPickable()` of a fresh client instance (players also need to be non-spectators,
184 /// armor stands non-markers).
185 pub const PICKABLE: u8 = 2;
186 /// The client box is not the centred dimensions box (hanging entities: from facing; shulker:
187 /// attach face and peek; interaction: width / height metadata; wind charges: lowered box).
188 /// Not modelled.
189 pub const NO_BOX: u8 = 4;
190 /// The type's registered dimensions are fixed (not scaled for babies / the scale attribute).
191 pub const FIXED: u8 = 8;
192 /// `instanceof Mob`: the client turns its body and head with a `BodyRotationControl`.
193 pub const MOB: u8 = 16;
194 /// The mob uses the default `BodyRotationControl` (not the camel / creaking / happy ghast /
195 /// phantom / shulker / armadillo ones).
196 pub const DEFAULT_BODY: u8 = 32;
197}
198
199/// Per-type client facts.
200#[derive(Clone, Copy, Debug, PartialEq)]
201#[non_exhaustive]
202pub struct EntityTypeData {
203 /// Network (registry) id.
204 pub id: u16,
205 /// Registry path (`"zombie"`).
206 pub name: &'static str,
207 /// [`type_flags`].
208 pub flags: u8,
209 /// Steps of the client instance's interpolation handler: position packets set a target the
210 /// entity moves to over that many ticks (`Some(3)`: living entities, boats, minecarts,
211 /// experience orbs, fishing bobbers; `Some(0)`: displays, which snap unless metadata sets a
212 /// duration). `None`: position packets move the entity at once.
213 pub interpolation: Option<u8>,
214 /// Mobs: `getMaxHeadYRot()` (how far the head may turn from the body; 0 for non-mobs).
215 pub max_head_y_rot: u8,
216 /// Bit `1 << pose id` set when that pose's dimensions are fixed (`EntityDimensions.fixed`:
217 /// not scaled by the scale attribute; a player dying, a digging warden, sleeping).
218 pub fixed_poses: u32,
219 /// Synched data index of the boolean baby flag.
220 pub baby_meta: Option<u8>,
221 /// Synched data index of the slime / magma cube size (int).
222 pub size_meta: Option<u8>,
223 /// Synched data index of the armor stand client flags (byte: 0x01 small, 0x10 marker).
224 pub flags_meta: Option<u8>,
225 /// Measured client sizes (`None`: no client instance, e.g. lightning).
226 pub size: Option<&'static VanillaEntitySize>,
227}
228
229impl EntityTypeData {
230 /// `instanceof LivingEntity`.
231 #[must_use]
232 pub fn is_living(&self) -> bool {
233 self.flags & type_flags::LIVING != 0
234 }
235
236 /// `isPickable()` of a fresh client instance.
237 #[must_use]
238 pub fn is_pickable(&self) -> bool {
239 self.flags & type_flags::PICKABLE != 0
240 }
241
242 /// The vanilla client dimensions for a variant (`"default"`, `"baby"`, `"small"`, `"marker"`,
243 /// `"small_marker"`; slime sizes via `slime_size`) and pose id, before the scale attribute
244 /// (see [`EntityTypeData::scaled`]). `None` for [`type_flags::NO_BOX`] types and types
245 /// without a client instance.
246 #[must_use]
247 pub fn dimensions(
248 &self,
249 variant: &str,
250 slime_size: Option<i32>,
251 pose: i32,
252 ) -> Option<EntityDimensions> {
253 if self.flags & type_flags::NO_BOX != 0 {
254 return None;
255 }
256 let s = self.size?;
257 if pose == 2 && self.is_living() {
258 return Some(LIVING_SLEEPING);
259 }
260 let pose_name = POSES.get(pose as usize).copied().unwrap_or("standing");
261 if let Some(n) = slime_size {
262 // Slime.getDefaultDimensions: the type's size (= the size-1 default) scaled by the size,
263 // whatever the pose.
264 return Some(scale(s.default_dimensions()?, n as f32, false));
265 }
266 if variant == "default" {
267 if let Some(d) = s.pose(pose_name) {
268 return Some(d);
269 }
270 return s.default_dimensions();
271 }
272 let mut key = [0u8; 40];
273 let k = join(&mut key, variant, pose_name);
274 if let Some(d) = k.and_then(|k| s.pose(k)) {
275 return Some(d);
276 }
277 s.variant(variant)
278 .map(|v| v.dimensions)
279 .or_else(|| s.default_dimensions())
280 }
281
282 /// `EntityDimensions.scale(f)` of a living entity's dimensions by its scale attribute
283 /// (`fixed` dimensions and `f == 1` stay as they are).
284 #[must_use]
285 pub fn scaled(d: EntityDimensions, f: f32, fixed: bool) -> EntityDimensions {
286 scale(d, f, fixed)
287 }
288}
289
290/// `LivingEntity.SLEEPING_DIMENSIONS`: every living entity in the sleeping pose (never scaled).
291pub const LIVING_SLEEPING: EntityDimensions = EntityDimensions {
292 width: 0.2,
293 height: 0.2,
294 eye_height: 0.2,
295};
296
297fn scale(d: EntityDimensions, f: f32, fixed: bool) -> EntityDimensions {
298 if fixed || f == 1.0 {
299 d
300 } else {
301 EntityDimensions {
302 width: d.width * f,
303 height: d.height * f,
304 eye_height: d.eye_height * f,
305 }
306 }
307}
308
309fn join<'a>(buf: &'a mut [u8; 40], a: &str, b: &str) -> Option<&'a str> {
310 let n = a.len() + 1 + b.len();
311 if n > buf.len() {
312 return None;
313 }
314 buf[..a.len()].copy_from_slice(a.as_bytes());
315 buf[a.len()] = b'/';
316 buf[a.len() + 1..n].copy_from_slice(b.as_bytes());
317 core::str::from_utf8(&buf[..n]).ok()
318}
319
320/// `Pose` names by id (out-of-range ids read as standing, as vanilla's `BY_ID` does).
321pub const POSES: [&str; 18] = [
322 "standing",
323 "fall_flying",
324 "sleeping",
325 "swimming",
326 "spin_attack",
327 "crouching",
328 "long_jumping",
329 "dying",
330 "croaking",
331 "using_tongue",
332 "sitting",
333 "roaring",
334 "sniffing",
335 "emerging",
336 "digging",
337 "sliding",
338 "shooting",
339 "inhaling",
340];