Refactor Slot (#87)

* create ItemStack type

* move slot back into protocol

* change DropItemStack to use ItemStack, because it's imposible to drop nothing
This commit is contained in:
Carson McManus 2022-09-26 23:44:06 -04:00 committed by GitHub
parent 2044add969
commit 47538ea05c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 53 additions and 45 deletions

View file

@ -12,8 +12,8 @@ use valence::entity::{Entity, EntityId, EntityKind};
use valence::player_list::PlayerListId; use valence::player_list::PlayerListId;
use valence::protocol::packets::c2s::play::ClickContainerMode; use valence::protocol::packets::c2s::play::ClickContainerMode;
use valence::protocol::packets::s2c::play::SoundCategory; use valence::protocol::packets::s2c::play::SoundCategory;
use valence::protocol::SlotId;
use valence::server::{Server, SharedServer, ShutdownResult}; use valence::server::{Server, SharedServer, ShutdownResult};
use valence::slot::SlotId;
use valence::text::{Color, TextFormat}; use valence::text::{Color, TextFormat};
use valence::{async_trait, ident}; use valence::{async_trait, ident};

View file

@ -35,10 +35,9 @@ use crate::protocol::packets::s2c::play::{
TeleportEntity, UnloadChunk, UpdateAttributes, UpdateEntityPosition, TeleportEntity, UnloadChunk, UpdateAttributes, UpdateEntityPosition,
UpdateEntityPositionAndRotation, UpdateEntityRotation, UpdateTime, UpdateEntityPositionAndRotation, UpdateEntityRotation, UpdateTime,
}; };
use crate::protocol::{BoundedInt, BoundedString, ByteAngle, RawBytes, VarInt}; use crate::protocol::{BoundedInt, BoundedString, ByteAngle, RawBytes, Slot, VarInt};
use crate::server::{C2sPacketChannels, NewClientData, S2cPlayMessage, SharedServer}; use crate::server::{C2sPacketChannels, NewClientData, S2cPlayMessage, SharedServer};
use crate::slab_versioned::{Key, VersionedSlab}; use crate::slab_versioned::{Key, VersionedSlab};
use crate::slot::Slot;
use crate::text::Text; use crate::text::Text;
use crate::util::{chunks_in_view_distance, is_chunk_in_view_distance}; use crate::util::{chunks_in_view_distance, is_chunk_in_view_distance};
use crate::world::{WorldId, Worlds}; use crate::world::{WorldId, Worlds};
@ -789,15 +788,9 @@ impl<C: Config> Client<C> {
let held = std::mem::replace(&mut self.cursor_held_item, Slot::Empty); let held = std::mem::replace(&mut self.cursor_held_item, Slot::Empty);
match held { match held {
Slot::Empty => {} Slot::Empty => {}
Slot::Present { Slot::Present(stack) => {
item_id, self.events.push_back(ClientEvent::DropItemStack { stack })
item_count, }
nbt,
} => self.events.push_back(ClientEvent::DropItemStack {
item_id,
item_count,
nbt,
}),
} }
} else { } else {
self.cursor_held_item = p.carried_item.clone(); self.cursor_held_item = p.carried_item.clone();
@ -981,15 +974,9 @@ impl<C: Config> Client<C> {
Slot::Empty => log::warn!( Slot::Empty => log::warn!(
"Invalid packet, creative client tried to drop a stack of nothing." "Invalid packet, creative client tried to drop a stack of nothing."
), ),
Slot::Present { Slot::Present(stack) => {
item_id, self.events.push_back(ClientEvent::DropItemStack { stack })
item_count, }
nbt,
} => self.events.push_back(ClientEvent::DropItemStack {
item_id,
item_count,
nbt,
}),
} }
} else { } else {
self.events.push_back(ClientEvent::SetSlotCreative { self.events.push_back(ClientEvent::SetSlotCreative {

View file

@ -1,6 +1,5 @@
use std::time::Duration; use std::time::Duration;
use valence_nbt::Compound;
use vek::Vec3; use vek::Vec3;
use super::Client; use super::Client;
@ -8,13 +7,13 @@ use crate::block_pos::BlockPos;
use crate::config::Config; use crate::config::Config;
use crate::entity::types::Pose; use crate::entity::types::Pose;
use crate::entity::{Entity, EntityEvent, EntityId, TrackedData}; use crate::entity::{Entity, EntityEvent, EntityId, TrackedData};
use crate::itemstack::ItemStack;
use crate::protocol::packets::c2s::play::ClickContainerMode; use crate::protocol::packets::c2s::play::ClickContainerMode;
pub use crate::protocol::packets::c2s::play::{ pub use crate::protocol::packets::c2s::play::{
BlockFace, ChatMode, DisplayedSkinParts, Hand, MainHand, ResourcePackC2s as ResourcePackStatus, BlockFace, ChatMode, DisplayedSkinParts, Hand, MainHand, ResourcePackC2s as ResourcePackStatus,
}; };
pub use crate::protocol::packets::s2c::play::GameMode; pub use crate::protocol::packets::s2c::play::GameMode;
use crate::protocol::VarInt; use crate::protocol::{Slot, SlotId, VarInt};
use crate::slot::{Slot, SlotId};
/// Represents an action performed by a client. /// Represents an action performed by a client.
/// ///
@ -147,9 +146,7 @@ pub enum ClientEvent {
/// user's inventory. /// user's inventory.
DropItemStack { DropItemStack {
// TODO: maybe we could add `from_slot_id` to make validation easier // TODO: maybe we could add `from_slot_id` to make validation easier
item_id: VarInt, stack: ItemStack,
item_count: u8,
nbt: Option<Compound>,
}, },
/// The client is in creative mode, and is trying to set it's inventory slot /// The client is in creative mode, and is trying to set it's inventory slot
/// to a value. /// to a value.

9
src/itemstack.rs Normal file
View file

@ -0,0 +1,9 @@
use crate::nbt::Compound;
use crate::protocol::VarInt;
#[derive(Debug, Clone, PartialEq)]
pub struct ItemStack {
pub item_id: VarInt,
pub item_count: u8,
pub nbt: Option<Compound>,
}

View file

@ -100,6 +100,7 @@ pub mod config;
pub mod dimension; pub mod dimension;
pub mod entity; pub mod entity;
pub mod ident; pub mod ident;
pub mod itemstack;
pub mod player_list; pub mod player_list;
pub mod player_textures; pub mod player_textures;
#[allow(dead_code)] #[allow(dead_code)]
@ -109,7 +110,6 @@ pub mod server;
mod slab; mod slab;
mod slab_rc; mod slab_rc;
mod slab_versioned; mod slab_versioned;
pub mod slot;
pub mod spatial_index; pub mod spatial_index;
pub mod text; pub mod text;
pub mod util; pub mod util;

View file

@ -10,6 +10,7 @@ use arrayvec::ArrayVec;
use bitvec::prelude::*; use bitvec::prelude::*;
pub use byte_angle::ByteAngle; pub use byte_angle::ByteAngle;
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
pub use slot::{Slot, SlotId};
use uuid::Uuid; use uuid::Uuid;
use valence_nbt::Compound; use valence_nbt::Compound;
pub use var_int::VarInt; pub use var_int::VarInt;
@ -22,6 +23,7 @@ use crate::nbt;
mod byte_angle; mod byte_angle;
pub mod codec; pub mod codec;
pub mod packets; pub mod packets;
mod slot;
mod var_int; mod var_int;
mod var_long; mod var_long;

View file

@ -20,9 +20,9 @@ use crate::block_pos::BlockPos;
use crate::ident::Ident; use crate::ident::Ident;
use crate::nbt::Compound; use crate::nbt::Compound;
use crate::protocol::{ use crate::protocol::{
BoundedArray, BoundedInt, BoundedString, ByteAngle, Decode, Encode, RawBytes, VarInt, VarLong, BoundedArray, BoundedInt, BoundedString, ByteAngle, Decode, Encode, RawBytes, Slot, VarInt,
VarLong,
}; };
use crate::slot::Slot;
use crate::text::Text; use crate::text::Text;
/// Provides the name of a packet for debugging purposes. /// Provides the name of a packet for debugging purposes.

View file

@ -2,6 +2,7 @@ use std::io::Write;
use byteorder::ReadBytesExt; use byteorder::ReadBytesExt;
use crate::itemstack::ItemStack;
use crate::nbt::Compound; use crate::nbt::Compound;
use crate::protocol::{Decode, Encode, VarInt}; use crate::protocol::{Decode, Encode, VarInt};
@ -12,26 +13,18 @@ pub type SlotId = i16;
pub enum Slot { pub enum Slot {
#[default] #[default]
Empty, Empty,
Present { Present(ItemStack),
item_id: VarInt,
item_count: u8,
nbt: Option<Compound>,
},
} }
impl Encode for Slot { impl Encode for Slot {
fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> { fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
match self { match self {
Slot::Empty => false.encode(w), Slot::Empty => false.encode(w),
Slot::Present { Slot::Present(s) => {
item_id,
item_count,
nbt,
} => {
true.encode(w)?; true.encode(w)?;
item_id.encode(w)?; s.item_id.encode(w)?;
item_count.encode(w)?; s.item_count.encode(w)?;
match &nbt { match &s.nbt {
Some(n) => n.encode(w), Some(n) => n.encode(w),
None => 0u8.encode(w), None => 0u8.encode(w),
} }
@ -46,7 +39,7 @@ impl Decode for Slot {
if !present { if !present {
return Ok(Slot::Empty); return Ok(Slot::Empty);
} }
Ok(Slot::Present { Ok(Slot::Present(ItemStack {
item_id: VarInt::decode(r)?, item_id: VarInt::decode(r)?,
item_count: u8::decode(r)?, item_count: u8::decode(r)?,
nbt: if r.first() == Some(&0) { nbt: if r.first() == Some(&0) {
@ -55,6 +48,26 @@ impl Decode for Slot {
} else { } else {
Some(Compound::decode(r)?) Some(Compound::decode(r)?)
}, },
}) }))
}
}
impl From<Option<ItemStack>> for Slot {
fn from(s: Option<ItemStack>) -> Self {
if let Some(s) = s {
Slot::Present(s)
} else {
Slot::Empty
}
}
}
impl From<Slot> for Option<ItemStack> {
fn from(s: Slot) -> Self {
if let Slot::Present(s) = s {
Some(s)
} else {
None
}
} }
} }