mcproto-types 0.5.0

Minecraft protocol types.
Documentation
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Type-safe client recipe displays.

use std::{fmt, io::Read};

use mcproto_codec::error::{CodecError, CodecKind, InvalidEncodingReason};

use crate::{Float, PrefixedArray, SlotDisplay, TypeCodec, TypeStructCodec, VarInt};

/// A shapeless crafting recipe display.
#[derive(Debug, Clone, PartialEq, TypeStructCodec)]
#[type_struct_codec(kind = RecipeDisplay)]
pub struct CraftingShapelessRecipeDisplay {
    /// Ingredient displays. The array prefix is the official ingredient count.
    pub ingredients: PrefixedArray<SlotDisplay>,
    /// Display for the crafted result.
    pub result: SlotDisplay,
    /// Crafting-station icon shown by the client.
    pub crafting_station: SlotDisplay,
}

/// A width, height, and exactly `width * height` ingredient displays.
///
/// Fields are private so the length invariant cannot be broken after
/// construction. Width, height, and ingredient count are encoded as VarInts.
#[derive(Debug, Clone, PartialEq)]
pub struct ShapedRecipeGrid {
    width: u32,
    height: u32,
    ingredients: Vec<SlotDisplay>,
}

impl ShapedRecipeGrid {
    /// Creates a grid when its dimensions and ingredient count are valid.
    pub fn new(
        width: u32,
        height: u32,
        ingredients: Vec<SlotDisplay>,
    ) -> Result<Self, InvalidShapedRecipeGrid> {
        validate_grid(width, height, ingredients.len())?;
        Ok(Self {
            width,
            height,
            ingredients,
        })
    }

    /// Returns the grid width.
    #[must_use]
    pub const fn width(&self) -> u32 {
        self.width
    }

    /// Returns the grid height.
    #[must_use]
    pub const fn height(&self) -> u32 {
        self.height
    }

    /// Returns the grid dimensions as `(width, height)`.
    #[must_use]
    pub const fn dimensions(&self) -> (u32, u32) {
        (self.width, self.height)
    }

    /// Returns the ingredient displays in row-major order.
    #[must_use]
    pub fn ingredients(&self) -> &[SlotDisplay] {
        &self.ingredients
    }

    /// Extracts the ingredient displays in row-major order.
    #[must_use]
    pub fn into_ingredients(self) -> Vec<SlotDisplay> {
        self.ingredients
    }
}

impl TypeCodec for ShapedRecipeGrid {
    fn encode(&self, writer: &mut impl std::io::Write) -> Result<(), CodecError> {
        VarInt(self.width as i32)
            .encode(writer)
            .map_err(|error| error.with_context(CodecKind::ShapedRecipeGrid))?;
        VarInt(self.height as i32)
            .encode(writer)
            .map_err(|error| error.with_context(CodecKind::ShapedRecipeGrid))?;
        VarInt(self.ingredients.len() as i32)
            .encode(writer)
            .map_err(|error| error.with_context(CodecKind::ShapedRecipeGrid))?;
        for ingredient in &self.ingredients {
            ingredient
                .encode(writer)
                .map_err(|error| error.with_context(CodecKind::ShapedRecipeGrid))?;
        }
        Ok(())
    }

    fn decode(reader: &mut impl Read) -> Result<Self, CodecError> {
        let width = decode_grid_dimension(reader)?;
        let height = decode_grid_dimension(reader)?;
        let ingredient_count = decode_ingredient_count(reader)?;
        validate_decoded_grid(width, height, ingredient_count)?;

        let mut ingredients = Vec::new();
        for _ in 0..ingredient_count {
            ingredients.push(
                SlotDisplay::decode(reader)
                    .map_err(|error| error.with_context(CodecKind::ShapedRecipeGrid))?,
            );
        }
        Ok(Self {
            width,
            height,
            ingredients,
        })
    }
}

/// A shaped crafting recipe display.
#[derive(Debug, Clone, PartialEq, TypeStructCodec)]
#[type_struct_codec(kind = RecipeDisplay)]
pub struct CraftingShapedRecipeDisplay {
    /// Validated rectangular ingredient grid.
    pub grid: ShapedRecipeGrid,
    /// Display for the crafted result.
    pub result: SlotDisplay,
    /// Crafting-station icon shown by the client.
    pub crafting_station: SlotDisplay,
}

impl CraftingShapedRecipeDisplay {
    /// Creates a shaped display while enforcing the ingredient-grid invariant.
    pub fn new(
        width: u32,
        height: u32,
        ingredients: Vec<SlotDisplay>,
        result: SlotDisplay,
        crafting_station: SlotDisplay,
    ) -> Result<Self, InvalidShapedRecipeGrid> {
        Ok(Self {
            grid: ShapedRecipeGrid::new(width, height, ingredients)?,
            result,
            crafting_station,
        })
    }
}

/// A furnace-style recipe display.
#[derive(Debug, Clone, PartialEq, TypeStructCodec)]
#[type_struct_codec(kind = RecipeDisplay)]
pub struct FurnaceRecipeDisplay {
    /// Ingredient accepted by the furnace recipe.
    pub ingredient: SlotDisplay,
    /// Fuel display.
    pub fuel: SlotDisplay,
    /// Smelting result display.
    pub result: SlotDisplay,
    /// Furnace icon shown by the client.
    pub crafting_station: SlotDisplay,
    /// Cooking duration in ticks.
    pub cooking_time: VarInt,
    /// Experience awarded by the recipe.
    pub experience: Float,
}

/// A stonecutter recipe display.
#[derive(Debug, Clone, PartialEq, TypeStructCodec)]
#[type_struct_codec(kind = RecipeDisplay)]
pub struct StonecutterRecipeDisplay {
    /// Input ingredient display.
    pub ingredient: SlotDisplay,
    /// Result display.
    pub result: SlotDisplay,
    /// Stonecutter icon shown by the client.
    pub crafting_station: SlotDisplay,
}

/// A smithing recipe display.
#[derive(Debug, Clone, PartialEq, TypeStructCodec)]
#[type_struct_codec(kind = RecipeDisplay)]
pub struct SmithingRecipeDisplay {
    /// Smithing template display.
    pub template: SlotDisplay,
    /// Base item display.
    pub base: SlotDisplay,
    /// Addition material display.
    pub addition: SlotDisplay,
    /// Smithing result display.
    pub result: SlotDisplay,
    /// Smithing-table icon shown by the client.
    pub crafting_station: SlotDisplay,
}

/// A recipe description sent for display by the client.
///
/// Each enum variant fixes both the ID in the `minecraft:recipe_display`
/// registry and its payload structure, so mismatched IDs and payloads cannot
/// be represented. The current protocol IDs are:
///
/// - `0`: `minecraft:crafting_shapeless`
/// - `1`: `minecraft:crafting_shaped`
/// - `2`: `minecraft:furnace`
/// - `3`: `minecraft:stonecutter`
/// - `4`: `minecraft:smithing`
///
/// # Examples
///
/// ```
/// use mcproto_types::{
///     CraftingShapedRecipeDisplay, RecipeDisplay, SlotDisplay, TypeCodec,
/// };
///
/// let display = RecipeDisplay::CraftingShaped(
///     CraftingShapedRecipeDisplay::new(
///         2,
///         1,
///         vec![SlotDisplay::Empty, SlotDisplay::AnyFuel],
///         SlotDisplay::Empty,
///         SlotDisplay::AnyFuel,
///     )?,
/// );
/// let mut encoded = Vec::new();
/// display.encode(&mut encoded)?;
/// let mut input = encoded.as_slice();
/// assert_eq!(RecipeDisplay::decode(&mut input)?, display);
/// assert!(input.is_empty());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// See the official [Recipe Display structure] documentation.
///
/// [Recipe Display structure]: https://minecraft.wiki/w/Java_Edition_protocol/Recipes#Recipe_Display_structure
#[derive(Debug, Clone, PartialEq)]
pub enum RecipeDisplay {
    CraftingShapeless(CraftingShapelessRecipeDisplay),
    CraftingShaped(CraftingShapedRecipeDisplay),
    Furnace(FurnaceRecipeDisplay),
    Stonecutter(StonecutterRecipeDisplay),
    Smithing(SmithingRecipeDisplay),
}

impl TypeCodec for RecipeDisplay {
    fn encode(&self, writer: &mut impl std::io::Write) -> Result<(), CodecError> {
        match self {
            Self::CraftingShapeless(value) => {
                encode_display_type(0, writer)?;
                value.encode(writer)
            }
            Self::CraftingShaped(value) => {
                encode_display_type(1, writer)?;
                value.encode(writer)
            }
            Self::Furnace(value) => {
                encode_display_type(2, writer)?;
                value.encode(writer)
            }
            Self::Stonecutter(value) => {
                encode_display_type(3, writer)?;
                value.encode(writer)
            }
            Self::Smithing(value) => {
                encode_display_type(4, writer)?;
                value.encode(writer)
            }
        }
    }

    fn decode(reader: &mut impl Read) -> Result<Self, CodecError> {
        let display_type = VarInt::decode(reader)
            .map_err(|error| error.with_context(CodecKind::RecipeDisplay))?
            .0;
        match display_type {
            0 => CraftingShapelessRecipeDisplay::decode(reader).map(Self::CraftingShapeless),
            1 => CraftingShapedRecipeDisplay::decode(reader).map(Self::CraftingShaped),
            2 => FurnaceRecipeDisplay::decode(reader).map(Self::Furnace),
            3 => StonecutterRecipeDisplay::decode(reader).map(Self::Stonecutter),
            4 => SmithingRecipeDisplay::decode(reader).map(Self::Smithing),
            value => Err(CodecError::invalid_encoding(
                CodecKind::RecipeDisplay,
                0,
                InvalidEncodingReason::InvalidEnumValue {
                    value: i128::from(value),
                },
            )),
        }
    }
}

fn encode_display_type(
    display_type: i32,
    writer: &mut impl std::io::Write,
) -> Result<(), CodecError> {
    VarInt(display_type)
        .encode(writer)
        .map_err(|error| error.with_context(CodecKind::RecipeDisplay))
}

fn decode_grid_dimension(reader: &mut impl Read) -> Result<u32, CodecError> {
    let value = VarInt::decode(reader)
        .map_err(|error| error.with_context(CodecKind::ShapedRecipeGrid))?
        .0;
    u32::try_from(value).map_err(|_| {
        CodecError::invalid_encoding(
            CodecKind::ShapedRecipeGrid,
            0,
            InvalidEncodingReason::NegativeLength { value },
        )
    })
}

fn decode_ingredient_count(reader: &mut impl Read) -> Result<usize, CodecError> {
    let value = VarInt::decode(reader)
        .map_err(|error| error.with_context(CodecKind::ShapedRecipeGrid))?
        .0;
    usize::try_from(value).map_err(|_| {
        CodecError::invalid_encoding(
            CodecKind::ShapedRecipeGrid,
            0,
            InvalidEncodingReason::NegativeLength { value },
        )
    })
}

fn validate_decoded_grid(
    width: u32,
    height: u32,
    ingredient_count: usize,
) -> Result<(), CodecError> {
    let expected = encoded_grid_area(width, height).ok_or_else(|| {
        CodecError::invalid_encoding(
            CodecKind::ShapedRecipeGrid,
            0,
            InvalidEncodingReason::LengthOutOfRange {
                max: i32::MAX as usize,
                actual: usize::MAX,
            },
        )
    })?;
    if ingredient_count != expected {
        return Err(CodecError::invalid_encoding(
            CodecKind::ShapedRecipeGrid,
            0,
            InvalidEncodingReason::ArrayLengthMismatch {
                expected,
                actual: ingredient_count,
            },
        ));
    }
    Ok(())
}

fn validate_grid(
    width: u32,
    height: u32,
    ingredient_count: usize,
) -> Result<(), InvalidShapedRecipeGrid> {
    if width > i32::MAX as u32 {
        return Err(InvalidShapedRecipeGrid::WidthOutOfRange { width });
    }
    if height > i32::MAX as u32 {
        return Err(InvalidShapedRecipeGrid::HeightOutOfRange { height });
    }
    let expected = encoded_grid_area(width, height)
        .ok_or(InvalidShapedRecipeGrid::AreaOutOfRange { width, height })?;
    if ingredient_count != expected {
        return Err(InvalidShapedRecipeGrid::IngredientCountMismatch {
            expected,
            actual: ingredient_count,
        });
    }
    Ok(())
}

fn encoded_grid_area(width: u32, height: u32) -> Option<usize> {
    let area = u64::from(width).checked_mul(u64::from(height))?;
    if area > i32::MAX as u64 {
        return None;
    }
    Some(area as usize)
}

/// Error returned when constructing an invalid shaped recipe grid.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum InvalidShapedRecipeGrid {
    /// Width cannot be represented by the protocol VarInt.
    WidthOutOfRange { width: u32 },
    /// Height cannot be represented by the protocol VarInt.
    HeightOutOfRange { height: u32 },
    /// The rectangular area cannot be represented by the ingredient-count VarInt.
    AreaOutOfRange { width: u32, height: u32 },
    /// The supplied ingredient count is not exactly `width * height`.
    IngredientCountMismatch { expected: usize, actual: usize },
}

impl fmt::Display for InvalidShapedRecipeGrid {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::WidthOutOfRange { width } => {
                write!(
                    formatter,
                    "recipe grid width exceeds a positive VarInt: {width}"
                )
            }
            Self::HeightOutOfRange { height } => {
                write!(
                    formatter,
                    "recipe grid height exceeds a positive VarInt: {height}"
                )
            }
            Self::AreaOutOfRange { width, height } => write!(
                formatter,
                "recipe grid area {width} * {height} exceeds a positive VarInt"
            ),
            Self::IngredientCountMismatch { expected, actual } => write!(
                formatter,
                "recipe grid requires {expected} ingredients, got {actual}"
            ),
        }
    }
}

impl std::error::Error for InvalidShapedRecipeGrid {}