Skip to main content

ghast_data/
modern_api.rs

1// Shared block API of the modern versions: included by `v26_1/mod.rs` and `v26_2/mod.rs`,
2// whose `g` (generated tables), `BlockData`, `block_name` and `block_display_name` it uses.
3/// Number of blocks (ids `0..BLOCK_COUNT`).
4pub const BLOCK_COUNT: usize = g::blocks::BLOCKS.len();
5/// Number of block states (ids `0..STATE_COUNT`).
6pub const STATE_COUNT: usize = g::blocks::STATE_BLOCK.len();
7
8impl Property {
9    /// Looks a property up by name (`"facing"`).
10    #[must_use]
11    pub fn from_name(name: &str) -> Option<Property> {
12        crate::common::lookup_name(
13            g::blocks::PROPERTY_NAMES_TEXT,
14            &g::blocks::PROPERTY_NAMES,
15            name,
16        )
17    }
18}
19
20/// One property of a block with its possible values, in palette order.
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub struct PropertyDef {
23    /// Which property.
24    pub property: Property,
25    /// Values in palette order (booleans are `["true", "false"]`, integers `"0"`, `"1"`, ...).
26    pub values: &'static [&'static str],
27}
28
29/// The state-id layout of one block.
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub struct StateLayout {
32    /// First state id.
33    pub min_state: u16,
34    /// Number of states.
35    pub state_count: u16,
36    /// Default state id.
37    pub default_state: u16,
38    /// Indices into the property definition table, most significant first: `(start, len)` in
39    /// the generated `LAYOUT_PROPERTIES` (plain data, no pointer).
40    pub(crate) properties: (u16, u8),
41}
42
43impl StateLayout {
44    /// Indices into the property definition table, most significant first.
45    #[inline]
46    pub(crate) fn property_ids(&self) -> &'static [u8] {
47        let (start, len) = (
48            usize::from(self.properties.0),
49            usize::from(self.properties.1),
50        );
51        g::blocks::LAYOUT_PROPERTIES
52            .get(start..start + len)
53            .unwrap_or(&[])
54    }
55}
56
57
58/// The collision voxel shape table (index 0 = empty; shared by the modern versions, so it
59/// also holds the shapes of later versions).
60#[must_use]
61pub fn voxel_shapes() -> &'static [VoxelShapeRef] {
62    &crate::generated::modern::VOXEL_SHAPES
63}
64
65/// Index of `Shapes.block()` in [`voxel_shapes`].
66pub const FULL_CUBE_VOXEL: u16 = g::blocks::FULL_CUBE_VOXEL;
67/// Index of scaffolding's bottom shape in [`voxel_shapes`].
68pub const SCAFFOLDING_BOTTOM_VOXEL: u16 = g::blocks::SCAFFOLDING_BOTTOM_VOXEL;
69/// Index of powder snow's falling shape (`box(0, 0, 0, 1, 0.9F, 1)`) in [`voxel_shapes`].
70pub const POWDER_SNOW_FALLING_VOXEL: u16 = g::blocks::POWDER_SNOW_FALLING_VOXEL;
71
72
73/// A 26.1 block type (registry id).
74#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
75pub struct Block(pub(crate) u16);
76
77impl Block {
78    /// The block with this registry id.
79    #[must_use]
80    pub const fn from_id(id: u16) -> Option<Block> {
81        if (id as usize) < BLOCK_COUNT {
82            Some(Block(id))
83        } else {
84            None
85        }
86    }
87
88    /// Looks a block up by registry name (`"oak_stairs"`, no namespace).
89    #[must_use]
90    pub fn from_name(name: &str) -> Option<Block> {
91        lookup_name(g::blocks::BLOCK_NAMES_TEXT, &g::blocks::BLOCK_NAMES, name).map(Block)
92    }
93
94    /// Registry id.
95    #[must_use]
96    pub const fn id(self) -> u16 {
97        self.0
98    }
99
100    /// Static data.
101    #[inline]
102    #[must_use]
103    pub fn data(self) -> &'static BlockData {
104        &g::blocks::BLOCKS[self.0 as usize]
105    }
106
107    /// Registry name.
108    #[must_use]
109    pub fn name(self) -> &'static str {
110        block_name(self.0)
111    }
112
113    /// English display name.
114    #[cfg(feature = "display-names")]
115    #[must_use]
116    pub fn display_name(self) -> &'static str {
117        block_display_name(self.0)
118    }
119
120    /// `true` for `air`, `cave_air` and `void_air` (vanilla `BlockState.isAir`).
121    #[must_use]
122    pub const fn is_air(self) -> bool {
123        matches!(self, Block::AIR | Block::CAVE_AIR | Block::VOID_AIR)
124    }
125
126    /// State-id layout.
127    #[must_use]
128    pub fn layout(self) -> &'static StateLayout {
129        &g::blocks::LAYOUTS[self.0 as usize]
130    }
131
132    /// The default state.
133    #[must_use]
134    pub fn default_state(self) -> BlockState {
135        BlockState(self.layout().default_state)
136    }
137
138    /// All states of this block in id order.
139    pub fn states(self) -> impl ExactSizeIterator<Item = BlockState> {
140        let l = self.layout();
141        (l.min_state..l.min_state + l.state_count).map(BlockState)
142    }
143
144    /// The block's properties, most significant first.
145    pub fn properties(self) -> impl ExactSizeIterator<Item = &'static PropertyDef> {
146        self.layout()
147            .property_ids()
148            .iter()
149            .map(|&i| &g::blocks::PROPERTY_DEFS[i as usize])
150    }
151
152    /// The default state with the given properties changed; `None` if a property or value does not
153    /// exist for this block.
154    #[must_use]
155    pub fn state_with(self, props: &[(Property, &str)]) -> Option<BlockState> {
156        props
157            .iter()
158            .try_fold(self.default_state(), |s, &(p, v)| s.with(p, v))
159    }
160
161    /// All blocks in id order.
162    pub fn all() -> impl ExactSizeIterator<Item = Block> {
163        (0..BLOCK_COUNT as u16).map(Block)
164    }
165}
166
167/// A 26.1 block state (global palette id).
168#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
169pub struct BlockState(u16);
170
171impl BlockState {
172    /// `minecraft:air` (id 0).
173    pub const AIR: BlockState = BlockState(0);
174
175    /// Wraps a palette id; `None` if out of range.
176    #[must_use]
177    pub const fn from_id(id: u16) -> Option<BlockState> {
178        if (id as usize) < STATE_COUNT {
179            Some(BlockState(id))
180        } else {
181            None
182        }
183    }
184
185    /// Palette id.
186    #[inline]
187    #[must_use]
188    pub const fn id(self) -> u16 {
189        self.0
190    }
191
192    /// The block type.
193    #[inline]
194    #[must_use]
195    pub fn block(self) -> Block {
196        Block(g::blocks::STATE_BLOCK[self.0 as usize])
197    }
198
199    /// `true` for `air`, `cave_air` and `void_air`.
200    #[must_use]
201    pub fn is_air(self) -> bool {
202        self.phys().has(state_flags::AIR)
203    }
204
205    /// The packed movement record (one table read).
206    #[inline]
207    #[must_use]
208    pub fn phys(self) -> StatePhys {
209        StatePhys(g::blocks::STATE_PHYS[self.0 as usize])
210    }
211
212    /// The context-free collision voxel shape (unshifted for offset blocks).
213    #[must_use]
214    pub fn voxel_shape(self) -> &'static VoxelShapeRef {
215        &crate::generated::modern::VOXEL_SHAPES[self.phys().shape() as usize]
216    }
217
218    /// The crosshair outline shape (`getShape` / `getOutlineShape` with the player's context,
219    /// empty hand). For states with [`BlockState::outline_offset`] this is the unshifted shape: the
220    /// block moves it by its per-position model offset.
221    #[must_use]
222    pub fn outline_shape(self) -> &'static SelectionShape {
223        &crate::generated::modern::SELECTION_SHAPES[g::selection::STATE_OUTLINE[self.0 as usize] as usize]
224    }
225
226    /// The outline while the player holds this block's own item (scaffolding and, where it
227    /// exists, the light block show a full cube then); otherwise [`BlockState::outline_shape`].
228    #[must_use]
229    pub fn outline_shape_holding_own_item(self) -> &'static SelectionShape {
230        let t = &g::selection::OUTLINE_HOLDING_OWN_ITEM;
231        match t.binary_search_by_key(&self.0, |e| e.0) {
232            Ok(i) => &crate::generated::modern::SELECTION_SHAPES[t[i].1 as usize],
233            Err(_) => self.outline_shape(),
234        }
235    }
236
237    /// `true` when the outline is moved by the block's model offset (flowers, bamboo, ...).
238    #[must_use]
239    pub fn outline_offset(self) -> bool {
240        g::selection::STATE_OUTLINE_OFFSET[self.0 as usize / 64] & (1 << (self.0 % 64)) != 0
241    }
242
243    /// The interaction shape (`getInteractionShape`): when the ray hits it nearer than the outline,
244    /// the hit keeps the outline's position but takes this shape's face (cauldrons, composters,
245    /// hoppers, scaffolding).
246    #[must_use]
247    pub fn interaction_shape(self) -> &'static SelectionShape {
248        &crate::generated::modern::SELECTION_SHAPES[g::selection::STATE_INTERACTION[self.0 as usize] as usize]
249    }
250
251    /// Index of `prop`'s value in [`PropertyDef::values`], if the block has that property.
252    #[must_use]
253    pub fn get_index(self, prop: Property) -> Option<usize> {
254        let layout = self.block().layout();
255        let mut rem = usize::from(self.0 - layout.min_state);
256        for &d in layout.property_ids().iter().rev() {
257            let def = &g::blocks::PROPERTY_DEFS[d as usize];
258            let n = def.values.len();
259            if def.property == prop {
260                return Some(rem % n);
261            }
262            rem /= n;
263        }
264        None
265    }
266
267    /// The value of `prop` (`"north"`, `"true"`, `"3"`), if the block has that property.
268    #[must_use]
269    pub fn get(self, prop: Property) -> Option<&'static str> {
270        let def = self.block().properties().find(|d| d.property == prop)?;
271        self.get_index(prop).map(|i| def.values[i])
272    }
273
274    /// This state with `prop` set to `value`; `None` if the block lacks the property or value.
275    #[must_use]
276    pub fn with(self, prop: Property, value: &str) -> Option<BlockState> {
277        let layout = self.block().layout();
278        let mut stride = 1usize;
279        for &d in layout.property_ids().iter().rev() {
280            let def = &g::blocks::PROPERTY_DEFS[d as usize];
281            let n = def.values.len();
282            if def.property == prop {
283                let new = def.values.iter().position(|v| *v == value)?;
284                let base = usize::from(self.0 - layout.min_state);
285                let old = base / stride % n;
286                let id = base - old * stride + new * stride + usize::from(layout.min_state);
287                return Some(BlockState(id as u16));
288            }
289            stride *= n;
290        }
291        None
292    }
293
294    /// `(property, value)` pairs of this state, most significant property first.
295    pub fn properties(self) -> impl Iterator<Item = (Property, &'static str)> {
296        let block = self.block();
297        block
298            .properties()
299            .filter_map(move |d| self.get(d.property).map(|v| (d.property, v)))
300    }
301
302    /// Parses `minecraft:name[prop=value,...]` (the namespace is optional).
303    #[must_use]
304    pub fn parse(s: &str) -> Option<BlockState> {
305        let s = s.strip_prefix("minecraft:").unwrap_or(s);
306        let (name, props) = match s.split_once('[') {
307            Some((n, rest)) => (n, rest.strip_suffix(']')?),
308            None => (s, ""),
309        };
310        let mut st = Block::from_name(name)?.default_state();
311        for kv in props.split(',').filter(|p| !p.is_empty()) {
312            let (k, v) = kv.split_once('=')?;
313            st = st.with(Property::from_name(k)?, v)?;
314        }
315        Some(st)
316    }
317}
318
319/// `minecraft:oak_stairs[facing=north,half=bottom,...]`, the vanilla block-state string form.
320impl fmt::Display for BlockState {
321    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
322        write!(f, "minecraft:{}", self.block().name())?;
323        let mut first = true;
324        for (p, v) in self.properties() {
325            f.write_str(if first { "[" } else { "," })?;
326            write!(f, "{}={v}", p.name())?;
327            first = false;
328        }
329        if !first {
330            f.write_str("]")?;
331        }
332        Ok(())
333    }
334}