Skip to content

Commit

Permalink
Merge branch 'master' of https://github.com/Snowiiii/Pumpkin
Browse files Browse the repository at this point in the history
Resolve merge conflicts
Update Use Item (SUseItem) to return Ok
  • Loading branch information
neeleshpoli committed Aug 25, 2024
2 parents 4012b9a + 268fc19 commit 1849dac
Show file tree
Hide file tree
Showing 23 changed files with 296 additions and 164 deletions.
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ There are several ways you can contribute to Pumpkin:
If you'd like to contribute code changes, fork the Pumpkin repository on GitHub.
Install Rust at [rust-lang.org](https://www.rust-lang.org/).
Make your changes on your local fork and create a pull request to the main repository.
Ensure your code adheres to the project's coding style guidelines (if any).
Ensure your code adheres to our project structure and style guidelines.
Write clear and concise commit messages that describe your changes.

### Project Structure
Expand Down
2 changes: 1 addition & 1 deletion pumpkin-protocol/src/bytebuf/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ impl ByteBuffer {
}
}

pub fn put_uuid(&mut self, v: uuid::Uuid) {
pub fn put_uuid(&mut self, v: &uuid::Uuid) {
// thats the vanilla way
let pair = v.as_u64_pair();
self.put_u64(pair.0);
Expand Down
4 changes: 2 additions & 2 deletions pumpkin-protocol/src/client/login/c_login_success.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ use crate::{bytebuf::ByteBuffer, ClientPacket, Property};

#[packet(0x02)]
pub struct CLoginSuccess<'a> {
pub uuid: uuid::Uuid,
pub uuid: &'a uuid::Uuid,
pub username: &'a str, // 16
pub properties: &'a [Property],
pub strict_error_handling: bool,
}

impl<'a> CLoginSuccess<'a> {
pub fn new(
uuid: uuid::Uuid,
uuid: &'a uuid::Uuid,
username: &'a str,
properties: &'a [Property],
strict_error_handling: bool,
Expand Down
6 changes: 3 additions & 3 deletions pumpkin-protocol/src/client/play/c_player_info_update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ impl<'a> ClientPacket for CPlayerInfoUpdate<'a> {
fn write(&self, bytebuf: &mut ByteBuffer) {
bytebuf.put_i8(self.actions);
bytebuf.put_list::<Player>(self.players, |p, v| {
p.put_uuid(v.uuid);
p.put_uuid(&v.uuid);
for action in &v.actions {
match action {
PlayerAction::AddPlayer { name, properties } => {
Expand All @@ -37,8 +37,8 @@ impl<'a> ClientPacket for CPlayerInfoUpdate<'a> {
});
}
PlayerAction::InitializeChat(_) => todo!(),
PlayerAction::UpdateGameMode(_) => todo!(),
PlayerAction::UpdateListed { listed } => p.put_bool(*listed),
PlayerAction::UpdateGameMode(gamemode) => p.put_var_int(gamemode),
PlayerAction::UpdateListed(listed) => p.put_bool(*listed),
PlayerAction::UpdateLatency(_) => todo!(),
PlayerAction::UpdateDisplayName(_) => todo!(),
}
Expand Down
10 changes: 5 additions & 5 deletions pumpkin-protocol/src/client/play/player_action.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
use crate::Property;
use crate::{Property, VarInt};

pub enum PlayerAction {
AddPlayer {
name: String,
properties: Vec<Property>,
},
InitializeChat(u8),
UpdateGameMode(u8),
UpdateListed {
listed: bool,
},
/// Gamemode ?
UpdateGameMode(VarInt),
/// Listed ?
UpdateListed(bool),
UpdateLatency(u8),
UpdateDisplayName(u8),
}
2 changes: 2 additions & 0 deletions pumpkin-protocol/src/server/play/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ mod s_interact;
mod s_ping_request;
mod s_player_action;
mod s_player_command;
mod s_player_ground;
mod s_player_position;
mod s_player_position_rotation;
mod s_player_rotation;
Expand All @@ -25,6 +26,7 @@ pub use s_interact::*;
pub use s_ping_request::*;
pub use s_player_action::*;
pub use s_player_command::*;
pub use s_player_ground::*;
pub use s_player_position::*;
pub use s_player_position_rotation::*;
pub use s_player_rotation::*;
Expand Down
8 changes: 8 additions & 0 deletions pumpkin-protocol/src/server/play/s_player_ground.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
use pumpkin_macros::packet;
use serde::Deserialize;

#[derive(Deserialize)]
#[packet(0x1D)]
pub struct SSetPlayerGround {
pub on_ground: bool,
}
1 change: 0 additions & 1 deletion pumpkin-protocol/src/server/play/s_set_creative_slot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use pumpkin_macros::packet;
use crate::slot::Slot;

#[derive(serde::Deserialize, Debug)]
#[allow(dead_code)]
#[packet(0x32)]
pub struct SSetCreativeSlot {
pub slot: i16,
Expand Down
6 changes: 3 additions & 3 deletions pumpkin/src/client/client_packet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ impl Client {
dbg!("handshake");
self.protocol_version = handshake.protocol_version.0;
self.connection_state = handshake.next_state;
if self.connection_state == ConnectionState::Login {
if self.connection_state != ConnectionState::Status {
let protocol = self.protocol_version;
match protocol.cmp(&(CURRENT_MC_PROTOCOL as i32)) {
std::cmp::Ordering::Less => {
Expand Down Expand Up @@ -65,7 +65,7 @@ impl Client {
}

pub fn handle_login_start(&mut self, server: &mut Server, login_start: SLoginStart) {
dbg!("login start");
log::debug!("login start, State {:?}", self.connection_state);

if !Self::is_valid_player_name(&login_start.name) {
self.kick("Invalid characters in username");
Expand Down Expand Up @@ -175,7 +175,7 @@ impl Client {
}

if let Some(profile) = self.gameprofile.as_ref().cloned() {
let packet = CLoginSuccess::new(profile.id, &profile.name, &profile.properties, false);
let packet = CLoginSuccess::new(&profile.id, &profile.name, &profile.properties, false);
self.send_packet(&packet);
} else {
self.kick("game profile is none");
Expand Down
144 changes: 90 additions & 54 deletions pumpkin/src/client/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use std::{
collections::VecDeque,
io::{self, Write},
net::SocketAddr,
rc::Rc,
sync::Arc,
};

use crate::{
Expand All @@ -14,7 +13,7 @@ use authentication::GameProfile;
use mio::{event::Event, net::TcpStream, Token};
use pumpkin_core::text::TextComponent;
use pumpkin_protocol::{
bytebuf::packet_id::Packet,
bytebuf::{packet_id::Packet, DeserializerError},
client::{config::CConfigDisconnect, login::CLoginDisconnect, play::CPlayDisconnect},
packet_decoder::PacketDecoder,
packet_encoder::PacketEncoder,
Expand Down Expand Up @@ -71,18 +70,18 @@ pub struct Client {
pub connection_state: ConnectionState,
pub encryption: bool,
pub closed: bool,
pub token: Rc<Token>,
pub token: Arc<Token>,
pub connection: TcpStream,
pub address: SocketAddr,
enc: PacketEncoder,
dec: PacketDecoder,
pub client_packets_queue: VecDeque<RawPacket>,
pub client_packets_queue: Vec<RawPacket>,

pub make_player: bool,
}

impl Client {
pub fn new(token: Rc<Token>, connection: TcpStream, address: SocketAddr) -> Self {
pub fn new(token: Arc<Token>, connection: TcpStream, address: SocketAddr) -> Self {
Self {
protocol_version: 0,
gameprofile: None,
Expand All @@ -96,14 +95,14 @@ impl Client {
dec: PacketDecoder::default(),
encryption: true,
closed: false,
client_packets_queue: VecDeque::new(),
client_packets_queue: Vec::new(),
make_player: false,
}
}

/// adds a Incoming packet to the queue
pub fn add_packet(&mut self, packet: RawPacket) {
self.client_packets_queue.push_back(packet);
self.client_packets_queue.push(packet);
}

/// enables encryption
Expand Down Expand Up @@ -146,84 +145,121 @@ impl Client {
}

pub async fn process_packets(&mut self, server: &mut Server) {
let mut i = 0;
while i < self.client_packets_queue.len() {
let mut packet = self.client_packets_queue.remove(i).unwrap();
self.handle_packet(server, &mut packet).await;
i += 1;
while let Some(mut packet) = self.client_packets_queue.pop() {
match self.handle_packet(server, &mut packet).await {
Ok(_) => {}
Err(e) => {
let text = format!("Error while reading incoming packet {}", e);
log::error!("{}", text);
self.kick(&text)
}
};
}
}

/// Handles an incoming decoded not Play state Packet
pub async fn handle_packet(&mut self, server: &mut Server, packet: &mut RawPacket) {
pub async fn handle_packet(
&mut self,
server: &mut Server,
packet: &mut RawPacket,
) -> Result<(), DeserializerError> {
// TODO: handle each packet's Error instead of calling .unwrap()
let bytebuf = &mut packet.bytebuf;
match self.connection_state {
pumpkin_protocol::ConnectionState::HandShake => match packet.id.0 {
SHandShake::PACKET_ID => {
self.handle_handshake(server, SHandShake::read(bytebuf).unwrap())
self.handle_handshake(server, SHandShake::read(bytebuf)?);
Ok(())
}
_ => {
log::error!(
"Failed to handle packet id {} while in Handshake state",
packet.id.0
);
Ok(())
}
_ => log::error!(
"Failed to handle packet id {} while in Handshake state",
packet.id.0
),
},
pumpkin_protocol::ConnectionState::Status => match packet.id.0 {
SStatusRequest::PACKET_ID => {
self.handle_status_request(server, SStatusRequest::read(bytebuf).unwrap())
self.handle_status_request(server, SStatusRequest::read(bytebuf)?);
Ok(())
}
SStatusPingRequest::PACKET_ID => {
self.handle_ping_request(server, SStatusPingRequest::read(bytebuf).unwrap())
self.handle_ping_request(server, SStatusPingRequest::read(bytebuf)?);
Ok(())
}
_ => {
log::error!(
"Failed to handle packet id {} while in Status state",
packet.id.0
);
Ok(())
}
_ => log::error!(
"Failed to handle packet id {} while in Status state",
packet.id.0
),
},
pumpkin_protocol::ConnectionState::Login => match packet.id.0 {
// TODO: Check config if transfer is enabled
pumpkin_protocol::ConnectionState::Login
| pumpkin_protocol::ConnectionState::Transfer => match packet.id.0 {
SLoginStart::PACKET_ID => {
self.handle_login_start(server, SLoginStart::read(bytebuf).unwrap())
self.handle_login_start(server, SLoginStart::read(bytebuf)?);
Ok(())
}
SEncryptionResponse::PACKET_ID => {
self.handle_encryption_response(
server,
SEncryptionResponse::read(bytebuf).unwrap(),
)
.await
self.handle_encryption_response(server, SEncryptionResponse::read(bytebuf)?)
.await;
Ok(())
}
SLoginPluginResponse::PACKET_ID => {
self.handle_plugin_response(server, SLoginPluginResponse::read(bytebuf)?);
Ok(())
}
SLoginAcknowledged::PACKET_ID => {
self.handle_login_acknowledged(server, SLoginAcknowledged::read(bytebuf)?);
Ok(())
}
_ => {
log::error!(
"Failed to handle packet id {} while in Login state",
packet.id.0
);
Ok(())
}
SLoginPluginResponse::PACKET_ID => self
.handle_plugin_response(server, SLoginPluginResponse::read(bytebuf).unwrap()),
SLoginAcknowledged::PACKET_ID => self
.handle_login_acknowledged(server, SLoginAcknowledged::read(bytebuf).unwrap()),
_ => log::error!(
"Failed to handle packet id {} while in Login state",
packet.id.0
),
},
pumpkin_protocol::ConnectionState::Config => match packet.id.0 {
SClientInformationConfig::PACKET_ID => self.handle_client_information_config(
server,
SClientInformationConfig::read(bytebuf).unwrap(),
),
SClientInformationConfig::PACKET_ID => {
self.handle_client_information_config(
server,
SClientInformationConfig::read(bytebuf)?,
);
Ok(())
}
SPluginMessage::PACKET_ID => {
self.handle_plugin_message(server, SPluginMessage::read(bytebuf).unwrap())
self.handle_plugin_message(server, SPluginMessage::read(bytebuf)?);
Ok(())
}
SAcknowledgeFinishConfig::PACKET_ID => {
self.handle_config_acknowledged(
server,
SAcknowledgeFinishConfig::read(bytebuf).unwrap(),
SAcknowledgeFinishConfig::read(bytebuf)?,
)
.await
.await;
Ok(())
}
SKnownPacks::PACKET_ID => {
self.handle_known_packs(server, SKnownPacks::read(bytebuf).unwrap())
self.handle_known_packs(server, SKnownPacks::read(bytebuf)?);
Ok(())
}
_ => {
log::error!(
"Failed to handle packet id {} while in Config state",
packet.id.0
);
Ok(())
}
_ => log::error!(
"Failed to handle packet id {} while in Config state",
packet.id.0
),
},
_ => log::error!("Invalid Connection state {:?}", self.connection_state),
_ => {
log::error!("Invalid Connection state {:?}", self.connection_state);
Ok(())
}
}
}

Expand Down Expand Up @@ -277,7 +313,7 @@ impl Client {
match self.connection_state {
ConnectionState::Login => {
self.try_send_packet(&CLoginDisconnect::new(
&serde_json::to_string_pretty(&reason).unwrap(),
&serde_json::to_string_pretty(&reason).unwrap_or("".into()),
))
.unwrap_or_else(|_| self.close());
}
Expand Down
10 changes: 7 additions & 3 deletions pumpkin/src/client/player_packet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use num_traits::FromPrimitive;
use pumpkin_core::text::TextComponent;
use pumpkin_entity::EntityId;
use pumpkin_inventory::WindowType;
use pumpkin_protocol::server::play::SCloseContainer;
use pumpkin_protocol::server::play::{SCloseContainer, SSetPlayerGround};
use pumpkin_protocol::{
client::play::{
Animation, CAcknowledgeBlockChange, CBlockUpdate, CEntityAnimation, CEntityVelocity,
Expand Down Expand Up @@ -174,8 +174,12 @@ impl Player {
server.broadcast_packet(self, &CHeadRot::new(entity_id.into(), yaw as u8));
}

pub fn handle_chat_command(&mut self, _server: &mut Server, command: SChatCommand) {
handle_command(&mut CommandSender::Player(self), &command.command);
pub fn handle_chat_command(&mut self, server: &mut Server, command: SChatCommand) {
handle_command(&mut CommandSender::Player(self), server, &command.command);
}

pub fn handle_player_ground(&mut self, _server: &mut Server, ground: SSetPlayerGround) {
self.on_ground = ground.on_ground;
}

pub fn handle_player_command(&mut self, _server: &mut Server, command: SPlayerCommand) {
Expand Down
Loading

0 comments on commit 1849dac

Please sign in to comment.