ghast-client 0.4.6

Headless Minecraft Java Edition client for the ghast library: connection, login, fixed 50 ms tick loop and a version-agnostic bot API (1.8.9, 1.12.2, 1.16.5, 26.1 and 26.2)
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
//! Protocol 47 (1.8 – 1.8.9).

use bytes::BytesMut;
use ghast_protocol::types::ByteString;
use ghast_protocol::v1_8::{handshaking, login, play};
use ghast_protocol::{DecodeError, EncodeError, FrameEncoder, McWrite, PacketFilter, RawPacket};

use super::{ClientVersion, GameVersion, V1_8, teleport_target, truncate_utf16};
use crate::common::{
    Abilities, ChatMessage, ChatPosition, EntityAction, GameMode, Health, Inbound, JoinGame,
    LoginInbound, MovePacket, Outbound, Pose, Teleport, Vec3,
};
use crate::interest::Interests;

use play::clientbound as cb;
use play::serverbound as sb;

impl ClientVersion for V1_8 {
    const GAME: GameVersion = GameVersion::V1_8_9;
    const CHAT_LIMIT: usize = 100;

    fn write_handshake(enc: &mut FrameEncoder, host: &str, port: u16) -> Result<(), EncodeError> {
        enc.write_packet(&handshaking::serverbound::SetProtocol {
            protocol_version: 47,
            server_host: ByteString::from(host),
            server_port: port,
            next_state: 2,
        })
    }

    type Wire = ();

    fn write_login_start(
        enc: &mut FrameEncoder,
        username: &str,
        _uuid: uuid::Uuid,
    ) -> Result<(), EncodeError> {
        enc.write_packet(&login::serverbound::LoginStart {
            username: ByteString::from(username),
        })
    }

    fn write_encryption_response(
        enc: &mut FrameEncoder,
        shared_secret: &[u8],
        verify_token: &[u8],
    ) -> Result<(), EncodeError> {
        enc.write_packet(&login::serverbound::EncryptionBegin {
            shared_secret: bytes::Bytes::copy_from_slice(shared_secret),
            verify_token: bytes::Bytes::copy_from_slice(verify_token),
        })
    }

    fn write_plugin_response(_enc: &mut FrameEncoder, _message_id: i32) -> Result<(), EncodeError> {
        // 1.8 has no login plugin messages; decode_login never asks for an answer.
        Ok(())
    }

    fn decode_login(raw: &RawPacket) -> Result<Option<LoginInbound>, DecodeError> {
        use login::clientbound as lc;
        Ok(Some(match raw.id {
            lc::id::DISCONNECT => {
                LoginInbound::Disconnect(raw.decode_as::<lc::Disconnect>()?.reason)
            }
            lc::id::ENCRYPTION_BEGIN => {
                let p: lc::EncryptionBegin = raw.decode_as()?;
                LoginInbound::EncryptionRequest {
                    server_id: p.server_id,
                    public_key: p.public_key,
                    verify_token: p.verify_token,
                }
            }
            lc::id::SUCCESS => {
                let p: lc::Success = raw.decode_as()?;
                LoginInbound::Success {
                    uuid: uuid::Uuid::parse_str(&p.uuid).ok(),
                    username: p.username,
                }
            }
            lc::id::COMPRESS => LoginInbound::Compress(raw.decode_as::<lc::Compress>()?.threshold),
            _ => return Ok(None),
        }))
    }

    fn play_filter(interests: Interests) -> PacketFilter {
        let mut f = PacketFilter::none()
            .with(cb::id::KEEP_ALIVE)
            .with(cb::id::LOGIN)
            .with(cb::id::UPDATE_HEALTH)
            .with(cb::id::RESPAWN)
            .with(cb::id::POSITION)
            .with(cb::id::HELD_ITEM_SLOT)
            .with(cb::id::GAME_STATE_CHANGE)
            .with(cb::id::OPEN_WINDOW)
            .with(cb::id::CLOSE_WINDOW)
            .with(cb::id::TRANSACTION)
            .with(cb::id::WINDOW_ITEMS)
            .with(cb::id::SET_SLOT)
            .with(cb::id::CRAFT_PROGRESS_BAR)
            .with(cb::id::ABILITIES)
            .with(cb::id::EXPERIENCE)
            .with(cb::id::KICK_DISCONNECT)
            .with(cb::id::SET_COMPRESSION)
            // Knockback. Every entity's velocity passes the filter (it is per packet id) but
            // the body is 7 bytes; only our entity's is applied.
            .with(cb::id::ENTITY_VELOCITY)
            // Our item use finished (status 9).
            .with(cb::id::ENTITY_STATUS)
            // Our speed attribute and status effects (physics, dig speed).
            .with(cb::id::UPDATE_ATTRIBUTES)
            .with(cb::id::ENTITY_EFFECT)
            .with(cb::id::REMOVE_ENTITY_EFFECT)
            .with(cb::id::EXPLOSION);
        // The world: chunks, block changes, border (physics and the loaded-column check).
        for &id in ghast_world::v1_8::PACKET_IDS {
            f.insert(id);
        }
        // Server resource packs are answered (servers that need one kick a silent client).
        f.insert(cb::id::RESOURCE_PACK_SEND);
        if interests.contains(Interests::CHAT) {
            f.insert(cb::id::CHAT);
        }
        f
    }

    fn decode_play(raw: &RawPacket, (): &mut ()) -> Result<Option<Inbound>, DecodeError> {
        Ok(Some(match raw.id {
            cb::id::KEEP_ALIVE => {
                Inbound::KeepAlive(i64::from(raw.decode_as::<cb::KeepAlive>()?.keep_alive_id))
            }
            cb::id::LOGIN => {
                let p: cb::Login = raw.decode_as()?;
                Inbound::JoinGame(JoinGame {
                    entity_id: p.entity_id,
                    game_mode: GameMode::from_wire(p.game_mode),
                    dimension: p.dimension.to_string(),
                    hardcore: p.game_mode & 0x08 != 0,
                    dimension_nbt: None,
                    respawn_screen: true,
                })
            }
            cb::id::CHAT => {
                let p: cb::Chat = raw.decode_as()?;
                Inbound::Chat(ChatMessage {
                    rendered: None,
                    json: p.message,
                    position: ChatPosition::from_wire(p.position),
                    sender: None,
                })
            }
            cb::id::UPDATE_HEALTH => {
                let p: cb::UpdateHealth = raw.decode_as()?;
                Inbound::Health(Health {
                    health: p.health,
                    food: p.food,
                    saturation: p.food_saturation,
                })
            }
            cb::id::RESPAWN => {
                let p: cb::Respawn = raw.decode_as()?;
                Inbound::Respawn {
                    dimension: p.dimension.to_string(),
                    game_mode: GameMode::from_wire(p.gamemode),

                    keep: 0,
                }
            }
            cb::id::POSITION => {
                let p: cb::Position = raw.decode_as()?;
                Inbound::Teleport(Teleport {
                    x: p.x,
                    y: p.y,
                    z: p.z,
                    yaw: p.yaw,
                    pitch: p.pitch,
                    flags: p.flags,
                    teleport_id: None,
                    relative: u32::from(p.flags as u8),
                    delta: Vec3::default(),
                })
            }
            cb::id::HELD_ITEM_SLOT => Inbound::HeldSlot(raw.decode_as::<cb::HeldItemSlot>()?.slot),
            cb::id::GAME_STATE_CHANGE => {
                let p: cb::GameStateChange = raw.decode_as()?;
                Inbound::GameState {
                    reason: p.reason.0,
                    value: p.game_mode,
                }
            }
            cb::id::OPEN_WINDOW => {
                Inbound::OpenWindow(i32::from(raw.decode_as::<cb::OpenWindow>()?.window_id))
            }
            cb::id::CLOSE_WINDOW => {
                Inbound::CloseWindow(i32::from(raw.decode_as::<cb::CloseWindow>()?.window_id))
            }
            cb::id::TRANSACTION => {
                let p: cb::Transaction = raw.decode_as()?;
                Inbound::Transaction {
                    window_id: p.window_id,
                    action: p.action,
                    accepted: p.accepted,
                }
            }
            cb::id::ABILITIES => {
                let p: cb::Abilities = raw.decode_as()?;
                Inbound::Abilities(Abilities {
                    flags: p.flags,
                    flying_speed: p.flying_speed,
                    walking_speed: p.walking_speed,
                })
            }
            cb::id::KICK_DISCONNECT => {
                Inbound::Disconnect(raw.decode_as::<cb::KickDisconnect>()?.reason)
            }
            cb::id::SET_COMPRESSION => {
                Inbound::SetCompression(raw.decode_as::<cb::SetCompression>()?.threshold)
            }
            cb::id::UPDATE_ATTRIBUTES => {
                let p: cb::UpdateAttributes = raw.decode_as()?;
                let Some(speed) = p.properties.iter().find(|a| {
                    a.key.ends_with("generic.movementSpeed")
                        || a.key.ends_with("generic.movement_speed")
                }) else {
                    return Ok(None);
                };
                Inbound::MovementSpeed {
                    entity_id: p.entity_id,
                    base: speed.value,
                    modifiers: speed
                        .modifiers
                        .iter()
                        .map(|m| (m.uuid, m.amount, m.operation))
                        .collect(),
                }
            }
            cb::id::ENTITY_EFFECT => {
                let p: cb::EntityEffect = raw.decode_as()?;
                Inbound::Effect {
                    entity_id: p.entity_id,
                    id: p.effect_id,
                    amplifier: p.amplifier,
                }
            }
            cb::id::REMOVE_ENTITY_EFFECT => {
                let p: cb::RemoveEntityEffect = raw.decode_as()?;
                Inbound::EffectRemoved {
                    entity_id: p.entity_id,
                    id: p.effect_id,
                }
            }
            cb::id::ENTITY_STATUS => {
                let p: cb::EntityStatus = raw.decode_as()?;
                Inbound::EntityStatus {
                    entity_id: p.entity_id,
                    status: p.entity_status,
                }
            }
            cb::id::ENTITY_VELOCITY => {
                let p: cb::EntityVelocity = raw.decode_as()?;
                Inbound::Velocity {
                    entity_id: p.entity_id,
                    motion: velocity(p.velocity.x, p.velocity.y, p.velocity.z),
                }
            }
            cb::id::EXPLOSION => {
                let p: cb::Explosion = raw.decode_as()?;
                Inbound::ExplosionPush(Vec3::new(
                    f64::from(p.player_motion_x),
                    f64::from(p.player_motion_y),
                    f64::from(p.player_motion_z),
                ))
            }
            _ => return Ok(None),
        }))
    }

    fn resource_pack(
        raw: &RawPacket,
        accept: bool,
        out: &mut Vec<Outbound>,
    ) -> Result<(), DecodeError> {
        if raw.id == cb::id::RESOURCE_PACK_SEND {
            pack_answer(raw, accept, out)?;
        }
        Ok(())
    }

    const INVENTORY: ghast_inventory::Version = ghast_inventory::Version::V1_8;

    /// A mount's `open_window` (`EntityHorse`): the entity whose rules the screen reads.
    fn mount_screen_entity(raw: &RawPacket) -> Option<i32> {
        use ghast_protocol::v1_8::play::clientbound as cb;
        if raw.id != cb::id::OPEN_WINDOW {
            return None;
        }
        let p: cb::OpenWindow = raw.decode_as().ok()?;
        (&*p.inventory_type == "EntityHorse")
            .then_some(p.entity_id)
            .flatten()
    }

    fn inventory_packet_ids(inv: &ghast_inventory::Inventory) -> &'static [i32] {
        // the villager offers (`MC|TrList`), sent right after the merchant's `open_window`
        if inv.window().map(ghast_inventory::Window::kind)
            == Some(ghast_inventory::WindowKind::Merchant)
        {
            &[cb::id::CUSTOM_PAYLOAD]
        } else {
            &[]
        }
    }

    fn inventory_packet(
        inv: &mut ghast_inventory::Inventory,
        raw: &RawPacket,
    ) -> Result<Option<ghast_inventory::Outgoing>, DecodeError> {
        // Only the window packets are decoded (decode_raw would link every packet's decoder).
        use cb::ClientboundPlayPacket as P;
        let p = match raw.id {
            cb::id::LOGIN => P::Login(raw.decode_as()?),
            cb::id::RESPAWN => P::Respawn(raw.decode_as()?),
            cb::id::OPEN_WINDOW => P::OpenWindow(raw.decode_as()?),
            cb::id::CLOSE_WINDOW => P::CloseWindow(raw.decode_as()?),
            cb::id::WINDOW_ITEMS => P::WindowItems(raw.decode_as()?),
            cb::id::SET_SLOT => P::SetSlot(raw.decode_as()?),
            cb::id::TRANSACTION => P::Transaction(raw.decode_as()?),
            cb::id::HELD_ITEM_SLOT => P::HeldItemSlot(raw.decode_as()?),
            cb::id::CRAFT_PROGRESS_BAR => P::CraftProgressBar(raw.decode_as()?),
            // the villager offers (`MC|TrList`; the filter passes them only while a merchant
            // window is open): every other channel is skipped undecoded
            cb::id::CUSTOM_PAYLOAD if super::payload_channel_is(&raw.body, b"MC|TrList") => {
                P::CustomPayload(raw.decode_as()?)
            }
            cb::id::CUSTOM_PAYLOAD => return Ok(None),
            // the anvil's level check: the level and creative mode
            cb::id::EXPERIENCE => P::Experience(raw.decode_as()?),
            cb::id::ABILITIES => P::Abilities(raw.decode_as()?),
            _ => return Ok(None),
        };
        Ok(inv.apply_v1_8(&p))
    }

    fn write_play(enc: &mut FrameEncoder, out: &Outbound, (): &mut ()) -> Result<(), EncodeError> {
        match out {
            Outbound::Raw(p) => enc.write_raw(p),
            Outbound::KeepAlive(id) => enc.write_packet(&sb::KeepAlive {
                // 1.8 keep-alive ids are VarInts; the value came from one.
                keep_alive_id: *id as i32,
            }),
            Outbound::TeleportConfirm(_) => Ok(()),
            Outbound::Move(m) => match *m {
                MovePacket::Flying { on_ground, .. } => enc.write_packet(&sb::Flying { on_ground }),
                MovePacket::Position { pos, on_ground, .. } => enc.write_packet(&sb::Position {
                    x: pos.x,
                    y: pos.y,
                    z: pos.z,
                    on_ground,
                }),
                MovePacket::Look {
                    yaw,
                    pitch,
                    on_ground,
                    ..
                } => enc.write_packet(&sb::Look {
                    yaw,
                    pitch,
                    on_ground,
                }),
                MovePacket::PositionLook {
                    pos,
                    yaw,
                    pitch,
                    on_ground,
                    ..
                } => enc.write_packet(&sb::PositionLook {
                    x: pos.x,
                    y: pos.y,
                    z: pos.z,
                    yaw,
                    pitch,
                    on_ground,
                }),
            },
            Outbound::EntityAction { entity_id, action } => {
                let action_id = match action {
                    EntityAction::StartSneaking => sb::EntityActionActionId::START_SNEAKING,
                    EntityAction::StopSneaking => sb::EntityActionActionId::STOP_SNEAKING,
                    EntityAction::StartSprinting => sb::EntityActionActionId::START_SPRINTING,
                    EntityAction::StopSprinting => sb::EntityActionActionId::STOP_SPRINTING,
                    // Only the 26.1 elytra start sends it.
                    EntityAction::StartFallFlying => return Ok(()),
                };
                enc.write_packet(&sb::EntityAction {
                    entity_id: *entity_id,
                    action_id,
                    jump_boost: 0,
                })
            }
            Outbound::Chat(text) => enc.write_packet(&sb::Chat {
                message: ByteString::from(truncate_utf16(text, Self::CHAT_LIMIT)),
            }),
            Outbound::Respawn => enc.write_packet(&sb::ClientCommand {
                payload: sb::ClientCommandPayload::PERFORM_RESPAWN,
            }),
            Outbound::Transaction {
                window_id,
                action,
                accepted,
            } => enc.write_packet(&sb::Transaction {
                window_id: *window_id,
                action: *action,
                accepted: *accepted,
            }),
            Outbound::Abilities {
                flags,
                flying_speed,
                walking_speed,
            } => enc.write_packet(&sb::Abilities {
                flags: *flags,
                flying_speed: *flying_speed,
                walking_speed: *walking_speed,
            }),
            // Only the window packets' encoders (write_set would link every packet's).
            Outbound::Inventory(o) => match o.to_v1_8() {
                Some(sb::ServerboundPlayPacket::WindowClick(p)) => enc.write_packet(&p),
                Some(sb::ServerboundPlayPacket::Transaction(p)) => enc.write_packet(&p),
                Some(sb::ServerboundPlayPacket::CloseWindow(p)) => enc.write_packet(&p),
                Some(sb::ServerboundPlayPacket::ClientCommand(p)) => enc.write_packet(&p),
                // the trading screen's `MC|TrSel`
                Some(sb::ServerboundPlayPacket::CustomPayload(p)) => enc.write_packet(&p),
                _ => Ok(()),
            },
            Outbound::UseEntity {
                target,
                action,
                off_hand,
                sneaking,
            } => {
                let _ = (off_hand, sneaking);
                let (mouse, at) = match action {
                    crate::common::EntityUse::Interact => (0, None),
                    crate::common::EntityUse::Attack => (1, None),
                    crate::common::EntityUse::InteractAt(v) => (2, Some(*v)),
                };
                enc.write_packet(&sb::UseEntity {
                    target: *target,
                    mouse,
                    x: at.map(|v| v.x as f32),
                    y: at.map(|v| v.y as f32),
                    z: at.map(|v| v.z as f32),
                })
            }
            Outbound::HeldSlot(slot) => enc.write_packet(&sb::HeldItemSlot { slot_id: *slot }),
            Outbound::Swing | Outbound::SwingOffHand => enc.write_packet(&sb::ArmAnimation {}),
            Outbound::Dig { status, pos, face } => enc.write_packet(&sb::BlockDig {
                status: status.id(),
                location: *pos,
                face: face.id(),
            }),
            Outbound::Place {
                pos,
                face,
                cursor,
                held,
                ..
            } => enc.write_packet(&sb::BlockPlace {
                location: *pos,
                direction: face.id(),
                held_item: legacy_slot(held.as_ref()),
                cursor_x: ((cursor.x as f32) * 16.0) as i32 as i8,
                cursor_y: ((cursor.y as f32) * 16.0) as i32 as i8,
                cursor_z: ((cursor.z as f32) * 16.0) as i32 as i8,
            }),
            Outbound::UseItem { held, .. } => enc.write_packet(&sb::BlockPlace {
                location: ghast_protocol::BlockPos::new(-1, -1, -1),
                direction: -1,
                held_item: legacy_slot(held.as_ref()),
                cursor_x: 0,
                cursor_y: 0,
                cursor_z: 0,
            }),
            Outbound::Settings(s) => enc.write_packet(&sb::Settings {
                locale: ByteString::from(s.locale.as_str()),
                view_distance: s.view_distance,
                chat_flags: s.chat_mode,
                chat_colors: s.chat_colors,
                skin_parts: s.skin_parts,
            }),
            Outbound::Brand(brand) => {
                let mut data = BytesMut::with_capacity(brand.len() + 1);
                data.put_string(brand)?;
                enc.write_packet(&sb::CustomPayload {
                    channel: ByteString::from_static("MC|Brand"),
                    data: data.freeze(),
                })
            }
            // Riding a boat (the 1.8 client simulates it and sends its input).
            Outbound::SteerVehicle {
                sideways,
                forward,
                jump,
                sneak,
            } => enc.write_packet(&sb::SteerVehicle {
                sideways: *sideways,
                forward: *forward,
                jump: u8::from(*jump) | (u8::from(*sneak) << 1),
            }),
            // Packets of newer versions: never produced for this one.
            Outbound::PlayerInput(_)
            | Outbound::TickEnd
            | Outbound::PlayerLoaded
            | Outbound::ChatSessionUpdate
            | Outbound::ChunkBatchReceived(_)
            | Outbound::Pong(_)
            | Outbound::ResourcePackStatus { .. }
            | Outbound::CookieResponse { .. }
            | Outbound::LookAnswer { .. }
            | Outbound::VehicleMove { .. }
            | Outbound::SteerBoat { .. }
            | Outbound::CustomClickAction { .. }
            | Outbound::DialogCommand(_) => Ok(()),
        }
    }

    fn apply_teleport(pose: &mut Pose, t: &Teleport) {
        let (yaw, pitch) = teleport_target(pose, t);
        // Entity.updatePositionAndAngles -> setRotation: both angles `% 360`, no clamp.
        pose.yaw = yaw % 360.0;
        pose.pitch = pitch % 360.0;
    }
}

/// Entity velocity packet units (1/8000 block per tick).
fn velocity(x: i16, y: i16, z: i16) -> Vec3 {
    Vec3::new(
        f64::from(x) / 8000.0,
        f64::from(y) / 8000.0,
        f64::from(z) / 8000.0,
    )
}

/// `onResourcePackSend` (1.8.9: no URL check; a `level://` pack is a world save's, which a bot
/// does not have). The answer echoes the hash, at most 40 characters like the packet's
/// constructor.
#[cold]
fn pack_answer(raw: &RawPacket, accept: bool, out: &mut Vec<Outbound>) -> Result<(), DecodeError> {
    let p: cb::ResourcePackSend = raw.decode_as()?;
    let hash = ByteString::from(truncate_utf16(&p.hash, 40));
    for &result in super::legacy_pack_statuses(!p.url.starts_with("level://"), accept) {
        let answer = sb::ResourcePackReceive {
            hash: hash.clone(),
            result,
        };
        // A short string and a VarInt always encode.
        if let Ok(raw) = RawPacket::from_packet(&answer) {
            out.push(Outbound::Raw(raw));
        }
    }
    Ok(())
}

impl super::HasSim for V1_8 {
    type Sim = crate::sim::Sim18;
    fn new_sim(opts: &crate::sim::SimOptions) -> Self::Sim {
        crate::sim::Sim18::with(opts)
    }
}

/// The held stack as the 1.8 wire slot (C08 carries it; Grim compares it with the hand).
fn legacy_slot(s: Option<&ghast_inventory::Stack>) -> ghast_protocol::types::slot::legacy::Slot {
    use ghast_protocol::types::slot::legacy::{ItemStack, Slot};
    Slot(s.and_then(|s| {
        Some(ItemStack {
            id: i16::try_from(s.id()).ok()?,
            count: i8::try_from(s.count()).unwrap_or(i8::MAX),
            damage: s.damage(),
            nbt: s.nbt().cloned(),
        })
    }))
}