aboutsummaryrefslogtreecommitdiff
path: root/azalea-block/src/lib.rs
blob: 4719ef4263f79f7673eed9a55031c39dc68d4e9f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
#![doc = include_str!("../README.md")]
#![feature(trait_upcasting)]

mod behavior;
mod generated;
mod range;

use core::fmt::Debug;
use std::{
    any::Any,
    fmt,
    io::{self, Cursor, Write},
};

use azalea_buf::{AzaleaRead, AzaleaReadVar, AzaleaWrite, AzaleaWriteVar, BufReadError};
pub use behavior::BlockBehavior;
pub use generated::{blocks, properties};
pub use range::BlockStates;

pub trait Block: Debug + Any {
    fn behavior(&self) -> BlockBehavior;
    /// Get the Minecraft ID for this block. For example `stone` or
    /// `grass_block`.
    fn id(&self) -> &'static str;
    /// Convert the block to a block state. This is lossless, as the block
    /// contains all the state data.
    fn as_block_state(&self) -> BlockState;
    /// Convert the block to an [`azalea_registry::Block`]. This is lossy, as
    /// `azalea_registry::Block` doesn't contain any state data.
    fn as_registry_block(&self) -> azalea_registry::Block;
}
impl dyn Block {
    pub fn downcast_ref<T: Block>(&self) -> Option<&T> {
        (self as &dyn Any).downcast_ref::<T>()
    }
}

pub trait Property {
    type Value;

    fn try_from_block_state(state: BlockState) -> Option<Self::Value>;
}

/// The type that's used internally to represent a block state ID.
///
/// This should be either `u16` or `u32`. If you choose to modify it, you must
/// also change it in `azalea-block-macros/src/lib.rs`.
///
/// This does not affect protocol serialization, it just allows you to make the
/// internal type smaller if you want.
pub type BlockStateIntegerRepr = u16;

/// A representation of a state a block can be in.
///
/// For example, a stone block only has one state but each possible stair
/// rotation is a different state.
///
/// Note that this type is internally either a `u16` or `u32`, depending on
/// [`BlockStateIntegerRepr`].
#[derive(Copy, Clone, PartialEq, Eq, Default, Hash)]
pub struct BlockState {
    /// The protocol ID for the block state. IDs may change every
    /// version, so you shouldn't hard-code them or store them in databases.
    pub id: BlockStateIntegerRepr,
}

impl BlockState {
    pub const AIR: BlockState = BlockState { id: 0 };

    #[inline]
    pub fn is_valid_state(state_id: BlockStateIntegerRepr) -> bool {
        state_id <= Self::MAX_STATE
    }

    /// Returns true if the block is air. This only checks for normal air, not
    /// other types like cave air.
    #[inline]
    pub fn is_air(&self) -> bool {
        self == &Self::AIR
    }
}

impl TryFrom<u32> for BlockState {
    type Error = ();

    /// Safely converts a u32 state id to a block state.
    fn try_from(state_id: u32) -> Result<Self, Self::Error> {
        let state_id = state_id as BlockStateIntegerRepr;
        if Self::is_valid_state(state_id) {
            Ok(BlockState { id: state_id })
        } else {
            Err(())
        }
    }
}
impl TryFrom<u16> for BlockState {
    type Error = ();

    /// Safely converts a u16 state id to a block state.
    fn try_from(state_id: u16) -> Result<Self, Self::Error> {
        let state_id = state_id as BlockStateIntegerRepr;
        if Self::is_valid_state(state_id) {
            Ok(BlockState { id: state_id })
        } else {
            Err(())
        }
    }
}

impl AzaleaRead for BlockState {
    fn azalea_read(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        let state_id = u32::azalea_read_var(buf)?;
        Self::try_from(state_id).map_err(|_| BufReadError::UnexpectedEnumVariant {
            id: state_id as i32,
        })
    }
}
impl AzaleaWrite for BlockState {
    fn azalea_write(&self, buf: &mut impl Write) -> Result<(), io::Error> {
        u32::azalea_write_var(&(self.id as u32), buf)
    }
}

impl Debug for BlockState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "BlockState(id: {}, {:?})",
            self.id,
            Box::<dyn Block>::from(*self)
        )
    }
}

#[derive(Clone, Debug)]
pub struct FluidState {
    pub fluid: azalea_registry::Fluid,
    /// 0 = empty, 8 = full, 9 = max.
    ///
    /// 9 is meant to be used when there's another fluid block of the same type
    /// above it, but it's usually unused by this struct.
    pub amount: u8,
}
impl FluidState {
    /// A floating point number in between 0 and 1 representing the height (as a
    /// percentage of a full block) of the fluid.
    pub fn height(&self) -> f32 {
        self.amount as f32 / 9.
    }
}

impl Default for FluidState {
    fn default() -> Self {
        Self {
            fluid: azalea_registry::Fluid::Empty,
            amount: 0,
        }
    }
}

impl From<BlockState> for FluidState {
    fn from(state: BlockState) -> Self {
        // note that 8 here might be treated as 9 in some cases if there's another fluid
        // block of the same type above it

        if state
            .property::<crate::properties::Waterlogged>()
            .unwrap_or_default()
        {
            Self {
                fluid: azalea_registry::Fluid::Water,
                amount: 8,
            }
        } else {
            let block = Box::<dyn Block>::from(state);
            if let Some(water) = block.downcast_ref::<crate::blocks::Water>() {
                Self {
                    fluid: azalea_registry::Fluid::Water,
                    amount: to_or_from_legacy_fluid_level(water.level as u8),
                }
            } else if let Some(lava) = block.downcast_ref::<crate::blocks::Lava>() {
                Self {
                    fluid: azalea_registry::Fluid::Lava,
                    amount: to_or_from_legacy_fluid_level(lava.level as u8),
                }
            } else {
                Self {
                    fluid: azalea_registry::Fluid::Empty,
                    amount: 0,
                }
            }
        }
    }
}

// see FlowingFluid.getLegacyLevel
fn to_or_from_legacy_fluid_level(level: u8) -> u8 {
    8_u8.saturating_sub(level)
}

impl From<FluidState> for BlockState {
    fn from(state: FluidState) -> Self {
        match state.fluid {
            azalea_registry::Fluid::Empty => BlockState::AIR,
            azalea_registry::Fluid::Water | azalea_registry::Fluid::FlowingWater => {
                BlockState::from(crate::blocks::Water {
                    level: crate::properties::WaterLevel::from(
                        state.amount as BlockStateIntegerRepr,
                    ),
                })
            }
            azalea_registry::Fluid::Lava | azalea_registry::Fluid::FlowingLava => {
                BlockState::from(crate::blocks::Lava {
                    level: crate::properties::LavaLevel::from(
                        state.amount as BlockStateIntegerRepr,
                    ),
                })
            }
        }
    }
}

impl From<BlockState> for azalea_registry::Block {
    fn from(value: BlockState) -> Self {
        Box::<dyn Block>::from(value).as_registry_block()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_from_u32() {
        assert_eq!(
            BlockState::try_from(0 as BlockStateIntegerRepr).unwrap(),
            BlockState::AIR
        );

        assert!(BlockState::try_from(BlockState::MAX_STATE).is_ok());
        assert!(BlockState::try_from(BlockState::MAX_STATE + 1).is_err());
    }

    #[test]
    fn test_from_blockstate() {
        let block: Box<dyn Block> = Box::<dyn Block>::from(BlockState::AIR);
        assert_eq!(block.id(), "air");

        let block: Box<dyn Block> =
            Box::<dyn Block>::from(BlockState::from(azalea_registry::Block::FloweringAzalea));
        assert_eq!(block.id(), "flowering_azalea");
    }

    #[test]
    fn test_debug_blockstate() {
        let formatted = format!(
            "{:?}",
            BlockState::from(azalea_registry::Block::FloweringAzalea)
        );
        assert!(formatted.ends_with(", FloweringAzalea)"), "{}", formatted);

        let formatted = format!(
            "{:?}",
            BlockState::from(azalea_registry::Block::BigDripleafStem)
        );
        assert!(
            formatted.ends_with(", BigDripleafStem { facing: North, waterlogged: false })"),
            "{}",
            formatted
        );
    }
}