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
use bevy_app::prelude::*;
use bevy_ecs::prelude::*;
use valence_protocol::packets::play::{ResourcePackSendS2c, ResourcePackStatusC2s};
use valence_protocol::text::Text;
use valence_protocol::WritePacket;

use crate::client::Client;
use crate::event_loop::{EventLoopPreUpdate, PacketEvent};

pub struct ResourcePackPlugin;

impl Plugin for ResourcePackPlugin {
    fn build(&self, app: &mut App) {
        app.add_event::<ResourcePackStatusEvent>()
            .add_systems(EventLoopPreUpdate, handle_resource_pack_status);
    }
}

#[derive(Event, Copy, Clone, PartialEq, Eq, Debug)]
pub struct ResourcePackStatusEvent {
    pub client: Entity,
    pub status: ResourcePackStatusC2s,
}

impl Client {
    /// Requests that the client download and enable a resource pack.
    ///
    /// # Arguments
    /// * `url` - The URL of the resource pack file.
    /// * `hash` - The SHA-1 hash of the resource pack file. The value must be a
    ///   40-character hexadecimal string.
    /// * `forced` - Whether a client should be kicked from the server upon
    ///   declining the pack (this is enforced client-side)
    /// * `prompt_message` - A message to be displayed with the resource pack
    ///   dialog.
    pub fn set_resource_pack(
        &mut self,
        url: &str,
        hash: &str,
        forced: bool,
        prompt_message: Option<Text>,
    ) {
        self.write_packet(&ResourcePackSendS2c {
            url,
            hash: hash.into(),
            forced,
            prompt_message: prompt_message.map(|t| t.into()),
        });
    }
}

fn handle_resource_pack_status(
    mut packets: EventReader<PacketEvent>,
    mut events: EventWriter<ResourcePackStatusEvent>,
) {
    for packet in packets.read() {
        if let Some(pkt) = packet.decode::<ResourcePackStatusC2s>() {
            events.send(ResourcePackStatusEvent {
                client: packet.client,
                status: pkt,
            });
        }
    }
}