use crate::common::{Aabb, SelectionShape, lookup_name};
use crate::generated::v26_1 as g;
use core::fmt;
pub use g::blocks::Property;
pub mod dig;
pub mod entities;
pub mod items;
pub use entities::{
EntityTypeData, entities, entity, entity_by_name, entity_type, entity_types,
vanilla_entity_size, vanilla_entity_sizes,
};
pub use items::{BlockSet, Food, Item, ItemData, Tool, ToolRule, food};
pub const BLOCK_COUNT: usize = g::blocks::BLOCKS.len();
pub const STATE_COUNT: usize = g::blocks::STATE_BLOCK.len();
impl Property {
#[must_use]
pub fn from_name(name: &str) -> Option<Property> {
g::blocks::PROPERTY_NAMES
.binary_search_by(|e| e.0.cmp(name))
.ok()
.map(|i| g::blocks::PROPERTY_NAMES[i].1)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PropertyDef {
pub property: Property,
pub values: &'static [&'static str],
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct StateLayout {
pub min_state: u16,
pub state_count: u16,
pub default_state: u16,
pub(crate) properties: &'static [u8],
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BlockKind {
Other = 0,
Cobweb,
SweetBerryBush,
PowderSnow,
HoneyBlock,
BubbleColumn,
SlimeBlock,
Scaffolding,
Ladder,
Water,
Lava,
MovingPiston,
}
pub mod block_flags {
pub const CLIMBABLE: u32 = 1;
pub const FENCES: u32 = 2;
pub const WALLS: u32 = 4;
pub const FENCE_GATE: u32 = 8;
pub const TRAPDOOR: u32 = 16;
pub const ICE: u32 = 32;
pub const BED: u32 = 64;
pub const FALL_DAMAGE_RESETTING: u32 = 128;
pub const SOUL_SPEED_BLOCKS: u32 = 256;
pub const FIRE: u32 = 512;
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BlockData {
pub name: &'static str,
#[cfg(feature = "display-names")]
pub display_name: &'static str,
pub hardness: Option<f32>,
pub resistance: f32,
pub diggable: bool,
pub transparent: bool,
pub emit_light: u8,
pub filter_light: u8,
pub friction: f32,
pub speed_factor: f32,
pub jump_factor: f32,
pub flags: u32,
pub kind: BlockKind,
pub offset: Option<(f32, f32, bool)>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum VoxelClass {
Simple,
Array,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct VoxelShapeRef {
pub class: VoxelClass,
pub sizes: [u8; 3],
pub xs: &'static [f64],
pub ys: &'static [f64],
pub zs: &'static [f64],
pub cells: &'static [u64],
pub empty: bool,
pub boxes: &'static [Aabb],
}
impl VoxelShapeRef {
#[must_use]
pub fn filled(&self, x: usize, y: usize, z: usize) -> bool {
let [nx, ny, nz] = self.sizes.map(usize::from);
if x >= nx || y >= ny || z >= nz {
return false;
}
let i = (x * ny + y) * nz + z;
self.cells[i / 64] & (1 << (i % 64)) != 0
}
}
#[must_use]
pub fn voxel_shapes() -> &'static [VoxelShapeRef] {
&g::blocks::VOXEL_SHAPES
}
pub const FULL_CUBE_VOXEL: u16 = g::blocks::FULL_CUBE_VOXEL;
pub const SCAFFOLDING_BOTTOM_VOXEL: u16 = g::blocks::SCAFFOLDING_BOTTOM_VOXEL;
pub const POWDER_SNOW_FALLING_VOXEL: u16 = g::blocks::POWDER_SNOW_FALLING_VOXEL;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct StatePhys(pub u64);
pub mod state_flags {
pub const FULL_CUBE: u16 = 1;
pub const EMPTY: u16 = 2;
pub const LARGE: u16 = 4;
pub const SUFFOCATING: u16 = 8;
pub const AIR: u16 = 16;
pub const BLOCKS_MOTION: u16 = 32;
pub const STURDY_NORTH: u16 = 64;
pub const CONTEXT: u16 = 1 << 10;
pub const OFFSET: u16 = 1 << 11;
pub const MOVING_PISTON: u16 = 1 << 12;
}
impl StatePhys {
#[inline]
#[must_use]
pub const fn shape(self) -> u16 {
self.0 as u16
}
#[inline]
#[must_use]
pub const fn flags(self) -> u16 {
(self.0 >> 16) as u16
}
#[inline]
#[must_use]
pub const fn has(self, bits: u16) -> bool {
self.flags() & bits == bits
}
#[inline]
#[must_use]
pub const fn fluid(self) -> u8 {
(self.0 >> 32) as u8
}
#[inline]
#[must_use]
pub const fn aux(self) -> u8 {
(self.0 >> 40) as u8
}
#[inline]
#[must_use]
pub const fn kind(self) -> u8 {
(self.0 >> 48) as u8
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Block(pub(crate) u16);
impl Block {
#[must_use]
pub const fn from_id(id: u16) -> Option<Block> {
if (id as usize) < BLOCK_COUNT {
Some(Block(id))
} else {
None
}
}
#[must_use]
pub fn from_name(name: &str) -> Option<Block> {
lookup_name(&g::blocks::BLOCK_NAMES, name).map(Block)
}
#[must_use]
pub const fn id(self) -> u16 {
self.0
}
#[inline]
#[must_use]
pub fn data(self) -> &'static BlockData {
&g::blocks::BLOCKS[self.0 as usize]
}
#[must_use]
pub fn name(self) -> &'static str {
self.data().name
}
#[must_use]
pub const fn is_air(self) -> bool {
matches!(self, Block::AIR | Block::CAVE_AIR | Block::VOID_AIR)
}
#[must_use]
pub fn layout(self) -> &'static StateLayout {
&g::blocks::LAYOUTS[self.0 as usize]
}
#[must_use]
pub fn default_state(self) -> BlockState {
BlockState(self.layout().default_state)
}
pub fn states(self) -> impl ExactSizeIterator<Item = BlockState> {
let l = self.layout();
(l.min_state..l.min_state + l.state_count).map(BlockState)
}
pub fn properties(self) -> impl ExactSizeIterator<Item = &'static PropertyDef> {
self.layout()
.properties
.iter()
.map(|&i| &g::blocks::PROPERTY_DEFS[i as usize])
}
#[must_use]
pub fn state_with(self, props: &[(Property, &str)]) -> Option<BlockState> {
props
.iter()
.try_fold(self.default_state(), |s, &(p, v)| s.with(p, v))
}
pub fn all() -> impl ExactSizeIterator<Item = Block> {
(0..BLOCK_COUNT as u16).map(Block)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct BlockState(u16);
impl BlockState {
pub const AIR: BlockState = BlockState(0);
#[must_use]
pub const fn from_id(id: u16) -> Option<BlockState> {
if (id as usize) < STATE_COUNT {
Some(BlockState(id))
} else {
None
}
}
#[inline]
#[must_use]
pub const fn id(self) -> u16 {
self.0
}
#[inline]
#[must_use]
pub fn block(self) -> Block {
Block(g::blocks::STATE_BLOCK[self.0 as usize])
}
#[must_use]
pub fn is_air(self) -> bool {
self.phys().has(state_flags::AIR)
}
#[inline]
#[must_use]
pub fn phys(self) -> StatePhys {
StatePhys(g::blocks::STATE_PHYS[self.0 as usize])
}
#[must_use]
pub fn voxel_shape(self) -> &'static VoxelShapeRef {
&g::blocks::VOXEL_SHAPES[self.phys().shape() as usize]
}
#[must_use]
pub fn outline_shape(self) -> &'static SelectionShape {
&g::selection::SELECTION_SHAPES[g::selection::STATE_OUTLINE[self.0 as usize] as usize]
}
#[must_use]
pub fn outline_shape_holding_own_item(self) -> &'static SelectionShape {
let t = &g::selection::OUTLINE_HOLDING_OWN_ITEM;
match t.binary_search_by_key(&self.0, |e| e.0) {
Ok(i) => &g::selection::SELECTION_SHAPES[t[i].1 as usize],
Err(_) => self.outline_shape(),
}
}
#[must_use]
pub fn outline_offset(self) -> bool {
g::selection::STATE_OUTLINE_OFFSET[self.0 as usize / 64] & (1 << (self.0 % 64)) != 0
}
#[must_use]
pub fn interaction_shape(self) -> &'static SelectionShape {
&g::selection::SELECTION_SHAPES[g::selection::STATE_INTERACTION[self.0 as usize] as usize]
}
#[must_use]
pub fn get_index(self, prop: Property) -> Option<usize> {
let layout = self.block().layout();
let mut rem = usize::from(self.0 - layout.min_state);
for &d in layout.properties.iter().rev() {
let def = &g::blocks::PROPERTY_DEFS[d as usize];
let n = def.values.len();
if def.property == prop {
return Some(rem % n);
}
rem /= n;
}
None
}
#[must_use]
pub fn get(self, prop: Property) -> Option<&'static str> {
let def = self.block().properties().find(|d| d.property == prop)?;
self.get_index(prop).map(|i| def.values[i])
}
#[must_use]
pub fn with(self, prop: Property, value: &str) -> Option<BlockState> {
let layout = self.block().layout();
let mut stride = 1usize;
for &d in layout.properties.iter().rev() {
let def = &g::blocks::PROPERTY_DEFS[d as usize];
let n = def.values.len();
if def.property == prop {
let new = def.values.iter().position(|v| *v == value)?;
let base = usize::from(self.0 - layout.min_state);
let old = base / stride % n;
let id = base - old * stride + new * stride + usize::from(layout.min_state);
return Some(BlockState(id as u16));
}
stride *= n;
}
None
}
pub fn properties(self) -> impl Iterator<Item = (Property, &'static str)> {
let block = self.block();
block
.properties()
.filter_map(move |d| self.get(d.property).map(|v| (d.property, v)))
}
#[must_use]
pub fn parse(s: &str) -> Option<BlockState> {
let s = s.strip_prefix("minecraft:").unwrap_or(s);
let (name, props) = match s.split_once('[') {
Some((n, rest)) => (n, rest.strip_suffix(']')?),
None => (s, ""),
};
let mut st = Block::from_name(name)?.default_state();
for kv in props.split(',').filter(|p| !p.is_empty()) {
let (k, v) = kv.split_once('=')?;
st = st.with(Property::from_name(k)?, v)?;
}
Some(st)
}
}
impl fmt::Display for BlockState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "minecraft:{}", self.block().name())?;
let mut first = true;
for (p, v) in self.properties() {
f.write_str(if first { "[" } else { "," })?;
write!(f, "{}={v}", p.name())?;
first = false;
}
if !first {
f.write_str("]")?;
}
Ok(())
}
}
#[cfg(test)]
mod tests;