valence_server/
interact_block.rs

1use bevy_app::prelude::*;
2use bevy_ecs::prelude::*;
3use valence_math::Vec3;
4use valence_protocol::packets::play::PlayerInteractBlockC2s;
5use valence_protocol::{BlockPos, Direction, Hand};
6
7use crate::action::ActionSequence;
8use crate::event_loop::{EventLoopPreUpdate, PacketEvent};
9
10pub struct InteractBlockPlugin;
11
12impl Plugin for InteractBlockPlugin {
13    fn build(&self, app: &mut App) {
14        app.add_event::<InteractBlockEvent>()
15            .add_systems(EventLoopPreUpdate, handle_interact_block);
16    }
17}
18
19#[derive(Event, Copy, Clone, Debug)]
20pub struct InteractBlockEvent {
21    pub client: Entity,
22    /// The hand that was used
23    pub hand: Hand,
24    /// The location of the block that was interacted with
25    pub position: BlockPos,
26    /// The face of the block that was clicked
27    pub face: Direction,
28    /// The position inside of the block that was clicked on
29    pub cursor_pos: Vec3,
30    /// Whether or not the player's head is inside a block
31    pub head_inside_block: bool,
32    /// Sequence number for synchronization
33    pub sequence: i32,
34}
35
36fn handle_interact_block(
37    mut packets: EventReader<PacketEvent>,
38    mut clients: Query<&mut ActionSequence>,
39    mut events: EventWriter<InteractBlockEvent>,
40) {
41    for packet in packets.read() {
42        if let Some(pkt) = packet.decode::<PlayerInteractBlockC2s>() {
43            if let Ok(mut action_seq) = clients.get_mut(packet.client) {
44                action_seq.update(pkt.sequence.0);
45            }
46
47            // TODO: check that the block interaction is valid.
48
49            events.send(InteractBlockEvent {
50                client: packet.client,
51                hand: pkt.hand,
52                position: pkt.position,
53                face: pkt.face,
54                cursor_pos: pkt.cursor_pos,
55                head_inside_block: pkt.head_inside_block,
56                sequence: pkt.sequence.0,
57            });
58        }
59    }
60}