Merge branch 'master' of https://github.com/Snowiiii/Pumpkin
Resolve merge conflicts Update Use Item (SUseItem) to return Ok
This commit is contained in:
23 files changed
+296
-164
No files matched your search
+1
-1
@@ -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.
|
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/).
|
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.
|
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.
|
Write clear and concise commit messages that describe your changes.
|
||||||
|
|
||||||
### Project Structure
|
### Project Structure
|
||||||
|
|||||||
@@ -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
|
// thats the vanilla way
|
||||||
let pair = v.as_u64_pair();
|
let pair = v.as_u64_pair();
|
||||||
self.put_u64(pair.0);
|
self.put_u64(pair.0);
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use crate::{bytebuf::ByteBuffer, ClientPacket, Property};
|
|||||||
|
|
||||||
#[packet(0x02)]
|
#[packet(0x02)]
|
||||||
pub struct CLoginSuccess<'a> {
|
pub struct CLoginSuccess<'a> {
|
||||||
pub uuid: uuid::Uuid,
|
pub uuid: &'a uuid::Uuid,
|
||||||
pub username: &'a str, // 16
|
pub username: &'a str, // 16
|
||||||
pub properties: &'a [Property],
|
pub properties: &'a [Property],
|
||||||
pub strict_error_handling: bool,
|
pub strict_error_handling: bool,
|
||||||
@@ -12,7 +12,7 @@ pub struct CLoginSuccess<'a> {
|
|||||||
|
|
||||||
impl<'a> CLoginSuccess<'a> {
|
impl<'a> CLoginSuccess<'a> {
|
||||||
pub fn new(
|
pub fn new(
|
||||||
uuid: uuid::Uuid,
|
uuid: &'a uuid::Uuid,
|
||||||
username: &'a str,
|
username: &'a str,
|
||||||
properties: &'a [Property],
|
properties: &'a [Property],
|
||||||
strict_error_handling: bool,
|
strict_error_handling: bool,
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ impl<'a> ClientPacket for CPlayerInfoUpdate<'a> {
|
|||||||
fn write(&self, bytebuf: &mut ByteBuffer) {
|
fn write(&self, bytebuf: &mut ByteBuffer) {
|
||||||
bytebuf.put_i8(self.actions);
|
bytebuf.put_i8(self.actions);
|
||||||
bytebuf.put_list::<Player>(self.players, |p, v| {
|
bytebuf.put_list::<Player>(self.players, |p, v| {
|
||||||
p.put_uuid(v.uuid);
|
p.put_uuid(&v.uuid);
|
||||||
for action in &v.actions {
|
for action in &v.actions {
|
||||||
match action {
|
match action {
|
||||||
PlayerAction::AddPlayer { name, properties } => {
|
PlayerAction::AddPlayer { name, properties } => {
|
||||||
@@ -37,8 +37,8 @@ impl<'a> ClientPacket for CPlayerInfoUpdate<'a> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
PlayerAction::InitializeChat(_) => todo!(),
|
PlayerAction::InitializeChat(_) => todo!(),
|
||||||
PlayerAction::UpdateGameMode(_) => todo!(),
|
PlayerAction::UpdateGameMode(gamemode) => p.put_var_int(gamemode),
|
||||||
PlayerAction::UpdateListed { listed } => p.put_bool(*listed),
|
PlayerAction::UpdateListed(listed) => p.put_bool(*listed),
|
||||||
PlayerAction::UpdateLatency(_) => todo!(),
|
PlayerAction::UpdateLatency(_) => todo!(),
|
||||||
PlayerAction::UpdateDisplayName(_) => todo!(),
|
PlayerAction::UpdateDisplayName(_) => todo!(),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::Property;
|
use crate::{Property, VarInt};
|
||||||
|
|
||||||
pub enum PlayerAction {
|
pub enum PlayerAction {
|
||||||
AddPlayer {
|
AddPlayer {
|
||||||
@@ -6,10 +6,10 @@ pub enum PlayerAction {
|
|||||||
properties: Vec<Property>,
|
properties: Vec<Property>,
|
||||||
},
|
},
|
||||||
InitializeChat(u8),
|
InitializeChat(u8),
|
||||||
UpdateGameMode(u8),
|
/// Gamemode ?
|
||||||
UpdateListed {
|
UpdateGameMode(VarInt),
|
||||||
listed: bool,
|
/// Listed ?
|
||||||
},
|
UpdateListed(bool),
|
||||||
UpdateLatency(u8),
|
UpdateLatency(u8),
|
||||||
UpdateDisplayName(u8),
|
UpdateDisplayName(u8),
|
||||||
}
|
}
|
||||||
@@ -7,6 +7,7 @@ mod s_interact;
|
|||||||
mod s_ping_request;
|
mod s_ping_request;
|
||||||
mod s_player_action;
|
mod s_player_action;
|
||||||
mod s_player_command;
|
mod s_player_command;
|
||||||
|
mod s_player_ground;
|
||||||
mod s_player_position;
|
mod s_player_position;
|
||||||
mod s_player_position_rotation;
|
mod s_player_position_rotation;
|
||||||
mod s_player_rotation;
|
mod s_player_rotation;
|
||||||
@@ -25,6 +26,7 @@ pub use s_interact::*;
|
|||||||
pub use s_ping_request::*;
|
pub use s_ping_request::*;
|
||||||
pub use s_player_action::*;
|
pub use s_player_action::*;
|
||||||
pub use s_player_command::*;
|
pub use s_player_command::*;
|
||||||
|
pub use s_player_ground::*;
|
||||||
pub use s_player_position::*;
|
pub use s_player_position::*;
|
||||||
pub use s_player_position_rotation::*;
|
pub use s_player_position_rotation::*;
|
||||||
pub use s_player_rotation::*;
|
pub use s_player_rotation::*;
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
use pumpkin_macros::packet;
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[packet(0x1D)]
|
||||||
|
pub struct SSetPlayerGround {
|
||||||
|
pub on_ground: bool,
|
||||||
|
}
|
||||||
@@ -3,7 +3,6 @@ use pumpkin_macros::packet;
|
|||||||
use crate::slot::Slot;
|
use crate::slot::Slot;
|
||||||
|
|
||||||
#[derive(serde::Deserialize, Debug)]
|
#[derive(serde::Deserialize, Debug)]
|
||||||
#[allow(dead_code)]
|
|
||||||
#[packet(0x32)]
|
#[packet(0x32)]
|
||||||
pub struct SSetCreativeSlot {
|
pub struct SSetCreativeSlot {
|
||||||
pub slot: i16,
|
pub slot: i16,
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ impl Client {
|
|||||||
dbg!("handshake");
|
dbg!("handshake");
|
||||||
self.protocol_version = handshake.protocol_version.0;
|
self.protocol_version = handshake.protocol_version.0;
|
||||||
self.connection_state = handshake.next_state;
|
self.connection_state = handshake.next_state;
|
||||||
if self.connection_state == ConnectionState::Login {
|
if self.connection_state != ConnectionState::Status {
|
||||||
let protocol = self.protocol_version;
|
let protocol = self.protocol_version;
|
||||||
match protocol.cmp(&(CURRENT_MC_PROTOCOL as i32)) {
|
match protocol.cmp(&(CURRENT_MC_PROTOCOL as i32)) {
|
||||||
std::cmp::Ordering::Less => {
|
std::cmp::Ordering::Less => {
|
||||||
@@ -65,7 +65,7 @@ impl Client {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn handle_login_start(&mut self, server: &mut Server, login_start: SLoginStart) {
|
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) {
|
if !Self::is_valid_player_name(&login_start.name) {
|
||||||
self.kick("Invalid characters in username");
|
self.kick("Invalid characters in username");
|
||||||
@@ -175,7 +175,7 @@ impl Client {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if let Some(profile) = self.gameprofile.as_ref().cloned() {
|
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);
|
self.send_packet(&packet);
|
||||||
} else {
|
} else {
|
||||||
self.kick("game profile is none");
|
self.kick("game profile is none");
|
||||||
|
|||||||
+90
-54
@@ -1,8 +1,7 @@
|
|||||||
use std::{
|
use std::{
|
||||||
collections::VecDeque,
|
|
||||||
io::{self, Write},
|
io::{self, Write},
|
||||||
net::SocketAddr,
|
net::SocketAddr,
|
||||||
rc::Rc,
|
sync::Arc,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -14,7 +13,7 @@ use authentication::GameProfile;
|
|||||||
use mio::{event::Event, net::TcpStream, Token};
|
use mio::{event::Event, net::TcpStream, Token};
|
||||||
use pumpkin_core::text::TextComponent;
|
use pumpkin_core::text::TextComponent;
|
||||||
use pumpkin_protocol::{
|
use pumpkin_protocol::{
|
||||||
bytebuf::packet_id::Packet,
|
bytebuf::{packet_id::Packet, DeserializerError},
|
||||||
client::{config::CConfigDisconnect, login::CLoginDisconnect, play::CPlayDisconnect},
|
client::{config::CConfigDisconnect, login::CLoginDisconnect, play::CPlayDisconnect},
|
||||||
packet_decoder::PacketDecoder,
|
packet_decoder::PacketDecoder,
|
||||||
packet_encoder::PacketEncoder,
|
packet_encoder::PacketEncoder,
|
||||||
@@ -71,18 +70,18 @@ pub struct Client {
|
|||||||
pub connection_state: ConnectionState,
|
pub connection_state: ConnectionState,
|
||||||
pub encryption: bool,
|
pub encryption: bool,
|
||||||
pub closed: bool,
|
pub closed: bool,
|
||||||
pub token: Rc<Token>,
|
pub token: Arc<Token>,
|
||||||
pub connection: TcpStream,
|
pub connection: TcpStream,
|
||||||
pub address: SocketAddr,
|
pub address: SocketAddr,
|
||||||
enc: PacketEncoder,
|
enc: PacketEncoder,
|
||||||
dec: PacketDecoder,
|
dec: PacketDecoder,
|
||||||
pub client_packets_queue: VecDeque<RawPacket>,
|
pub client_packets_queue: Vec<RawPacket>,
|
||||||
|
|
||||||
pub make_player: bool,
|
pub make_player: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Client {
|
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 {
|
Self {
|
||||||
protocol_version: 0,
|
protocol_version: 0,
|
||||||
gameprofile: None,
|
gameprofile: None,
|
||||||
@@ -96,14 +95,14 @@ impl Client {
|
|||||||
dec: PacketDecoder::default(),
|
dec: PacketDecoder::default(),
|
||||||
encryption: true,
|
encryption: true,
|
||||||
closed: false,
|
closed: false,
|
||||||
client_packets_queue: VecDeque::new(),
|
client_packets_queue: Vec::new(),
|
||||||
make_player: false,
|
make_player: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// adds a Incoming packet to the queue
|
/// adds a Incoming packet to the queue
|
||||||
pub fn add_packet(&mut self, packet: RawPacket) {
|
pub fn add_packet(&mut self, packet: RawPacket) {
|
||||||
self.client_packets_queue.push_back(packet);
|
self.client_packets_queue.push(packet);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// enables encryption
|
/// enables encryption
|
||||||
@@ -146,84 +145,121 @@ impl Client {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn process_packets(&mut self, server: &mut Server) {
|
pub async fn process_packets(&mut self, server: &mut Server) {
|
||||||
let mut i = 0;
|
while let Some(mut packet) = self.client_packets_queue.pop() {
|
||||||
while i < self.client_packets_queue.len() {
|
match self.handle_packet(server, &mut packet).await {
|
||||||
let mut packet = self.client_packets_queue.remove(i).unwrap();
|
Ok(_) => {}
|
||||||
self.handle_packet(server, &mut packet).await;
|
Err(e) => {
|
||||||
i += 1;
|
let text = format!("Error while reading incoming packet {}", e);
|
||||||
|
log::error!("{}", text);
|
||||||
|
self.kick(&text)
|
||||||
|
}
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handles an incoming decoded not Play state Packet
|
/// 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()
|
// TODO: handle each packet's Error instead of calling .unwrap()
|
||||||
let bytebuf = &mut packet.bytebuf;
|
let bytebuf = &mut packet.bytebuf;
|
||||||
match self.connection_state {
|
match self.connection_state {
|
||||||
pumpkin_protocol::ConnectionState::HandShake => match packet.id.0 {
|
pumpkin_protocol::ConnectionState::HandShake => match packet.id.0 {
|
||||||
SHandShake::PACKET_ID => {
|
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 {
|
pumpkin_protocol::ConnectionState::Status => match packet.id.0 {
|
||||||
SStatusRequest::PACKET_ID => {
|
SStatusRequest::PACKET_ID => {
|
||||||
self.handle_status_request(server, SStatusRequest::read(bytebuf).unwrap())
|
self.handle_status_request(server, SStatusRequest::read(bytebuf)?);
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
SStatusPingRequest::PACKET_ID => {
|
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 => {
|
SLoginStart::PACKET_ID => {
|
||||||
self.handle_login_start(server, SLoginStart::read(bytebuf).unwrap())
|
self.handle_login_start(server, SLoginStart::read(bytebuf)?);
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
SEncryptionResponse::PACKET_ID => {
|
SEncryptionResponse::PACKET_ID => {
|
||||||
self.handle_encryption_response(
|
self.handle_encryption_response(server, SEncryptionResponse::read(bytebuf)?)
|
||||||
server,
|
.await;
|
||||||
SEncryptionResponse::read(bytebuf).unwrap(),
|
Ok(())
|
||||||
)
|
}
|
||||||
.await
|
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 {
|
pumpkin_protocol::ConnectionState::Config => match packet.id.0 {
|
||||||
SClientInformationConfig::PACKET_ID => self.handle_client_information_config(
|
SClientInformationConfig::PACKET_ID => {
|
||||||
server,
|
self.handle_client_information_config(
|
||||||
SClientInformationConfig::read(bytebuf).unwrap(),
|
server,
|
||||||
),
|
SClientInformationConfig::read(bytebuf)?,
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
SPluginMessage::PACKET_ID => {
|
SPluginMessage::PACKET_ID => {
|
||||||
self.handle_plugin_message(server, SPluginMessage::read(bytebuf).unwrap())
|
self.handle_plugin_message(server, SPluginMessage::read(bytebuf)?);
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
SAcknowledgeFinishConfig::PACKET_ID => {
|
SAcknowledgeFinishConfig::PACKET_ID => {
|
||||||
self.handle_config_acknowledged(
|
self.handle_config_acknowledged(
|
||||||
server,
|
server,
|
||||||
SAcknowledgeFinishConfig::read(bytebuf).unwrap(),
|
SAcknowledgeFinishConfig::read(bytebuf)?,
|
||||||
)
|
)
|
||||||
.await
|
.await;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
SKnownPacks::PACKET_ID => {
|
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(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -277,7 +313,7 @@ impl Client {
|
|||||||
match self.connection_state {
|
match self.connection_state {
|
||||||
ConnectionState::Login => {
|
ConnectionState::Login => {
|
||||||
self.try_send_packet(&CLoginDisconnect::new(
|
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());
|
.unwrap_or_else(|_| self.close());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ use num_traits::FromPrimitive;
|
|||||||
use pumpkin_core::text::TextComponent;
|
use pumpkin_core::text::TextComponent;
|
||||||
use pumpkin_entity::EntityId;
|
use pumpkin_entity::EntityId;
|
||||||
use pumpkin_inventory::WindowType;
|
use pumpkin_inventory::WindowType;
|
||||||
use pumpkin_protocol::server::play::SCloseContainer;
|
use pumpkin_protocol::server::play::{SCloseContainer, SSetPlayerGround};
|
||||||
use pumpkin_protocol::{
|
use pumpkin_protocol::{
|
||||||
client::play::{
|
client::play::{
|
||||||
Animation, CAcknowledgeBlockChange, CBlockUpdate, CEntityAnimation, CEntityVelocity,
|
Animation, CAcknowledgeBlockChange, CBlockUpdate, CEntityAnimation, CEntityVelocity,
|
||||||
@@ -174,8 +174,12 @@ impl Player {
|
|||||||
server.broadcast_packet(self, &CHeadRot::new(entity_id.into(), yaw as u8));
|
server.broadcast_packet(self, &CHeadRot::new(entity_id.into(), yaw as u8));
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn handle_chat_command(&mut self, _server: &mut Server, command: SChatCommand) {
|
pub fn handle_chat_command(&mut self, server: &mut Server, command: SChatCommand) {
|
||||||
handle_command(&mut CommandSender::Player(self), &command.command);
|
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) {
|
pub fn handle_player_command(&mut self, _server: &mut Server, command: SPlayerCommand) {
|
||||||
|
|||||||
@@ -60,12 +60,12 @@ pub(crate) fn init_command_tree<'a>() -> CommandTree<'a> {
|
|||||||
CommandTree::new(NAMES, DESCRIPTION).with_child(
|
CommandTree::new(NAMES, DESCRIPTION).with_child(
|
||||||
require(&|sender| sender.permission_lvl() >= 2).with_child(
|
require(&|sender| sender.permission_lvl() >= 2).with_child(
|
||||||
argument(ARG_GAMEMODE, consume_arg_gamemode)
|
argument(ARG_GAMEMODE, consume_arg_gamemode)
|
||||||
.with_child(
|
.with_child(require(&|sender| sender.is_player()).execute(
|
||||||
require(&|sender| sender.is_player()).execute(&|sender, args| {
|
&|sender, server, args| {
|
||||||
let gamemode = parse_arg_gamemode(args)?;
|
let gamemode = parse_arg_gamemode(args)?;
|
||||||
|
|
||||||
return if let Player(target) = sender {
|
return if let Player(target) = sender {
|
||||||
target.set_gamemode(gamemode);
|
target.set_gamemode(server, gamemode);
|
||||||
target.send_system_message(TextComponent::text(&format!(
|
target.send_system_message(TextComponent::text(&format!(
|
||||||
"Game mode was set to {:?}",
|
"Game mode was set to {:?}",
|
||||||
gamemode
|
gamemode
|
||||||
@@ -75,22 +75,22 @@ pub(crate) fn init_command_tree<'a>() -> CommandTree<'a> {
|
|||||||
} else {
|
} else {
|
||||||
Err(InvalidRequirementError)
|
Err(InvalidRequirementError)
|
||||||
};
|
};
|
||||||
}),
|
},
|
||||||
)
|
))
|
||||||
.with_child(
|
.with_child(argument(ARG_TARGET, consume_arg_player).execute(
|
||||||
argument(ARG_TARGET, consume_arg_player).execute(&|sender, args| {
|
&|sender, server, args| {
|
||||||
let gamemode = parse_arg_gamemode(args)?;
|
let gamemode = parse_arg_gamemode(args)?;
|
||||||
let target = parse_arg_player(sender, ARG_TARGET, args)?;
|
let target = parse_arg_player(sender, ARG_TARGET, args)?;
|
||||||
|
|
||||||
target.set_gamemode(gamemode);
|
target.set_gamemode(server, gamemode);
|
||||||
target.send_system_message(TextComponent::text(&format!(
|
target.send_system_message(TextComponent::text(&format!(
|
||||||
"Set own game mode to {:?}",
|
"Set own game mode to {:?}",
|
||||||
gamemode
|
gamemode
|
||||||
)));
|
)));
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}),
|
},
|
||||||
),
|
)),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -35,7 +35,7 @@ fn parse_arg_command<'a>(
|
|||||||
pub(crate) fn init_command_tree<'a>() -> CommandTree<'a> {
|
pub(crate) fn init_command_tree<'a>() -> CommandTree<'a> {
|
||||||
CommandTree::new(NAMES, DESCRIPTION)
|
CommandTree::new(NAMES, DESCRIPTION)
|
||||||
.with_child(
|
.with_child(
|
||||||
argument(ARG_COMMAND, consume_arg_command).execute(&|sender, args| {
|
argument(ARG_COMMAND, consume_arg_command).execute(&|sender, _, args| {
|
||||||
let dispatcher = DISPATCHER.get_or_init(dispatcher_init);
|
let dispatcher = DISPATCHER.get_or_init(dispatcher_init);
|
||||||
|
|
||||||
let tree = parse_arg_command(args, dispatcher)?;
|
let tree = parse_arg_command(args, dispatcher)?;
|
||||||
@@ -50,7 +50,7 @@ pub(crate) fn init_command_tree<'a>() -> CommandTree<'a> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.execute(&|sender, _args| {
|
.execute(&|sender, _, _args| {
|
||||||
let dispatcher = DISPATCHER.get_or_init(dispatcher_init);
|
let dispatcher = DISPATCHER.get_or_init(dispatcher_init);
|
||||||
|
|
||||||
let mut keys: Vec<&str> = dispatcher.commands.keys().copied().collect();
|
let mut keys: Vec<&str> = dispatcher.commands.keys().copied().collect();
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ const NAMES: [&str; 1] = ["pumpkin"];
|
|||||||
const DESCRIPTION: &str = "Display information about Pumpkin.";
|
const DESCRIPTION: &str = "Display information about Pumpkin.";
|
||||||
|
|
||||||
pub(crate) fn init_command_tree<'a>() -> CommandTree<'a> {
|
pub(crate) fn init_command_tree<'a>() -> CommandTree<'a> {
|
||||||
CommandTree::new(NAMES, DESCRIPTION).execute(&|sender, _| {
|
CommandTree::new(NAMES, DESCRIPTION).execute(&|sender, _, _| {
|
||||||
let version = env!("CARGO_PKG_VERSION");
|
let version = env!("CARGO_PKG_VERSION");
|
||||||
let description = env!("CARGO_PKG_DESCRIPTION");
|
let description = env!("CARGO_PKG_DESCRIPTION");
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ const DESCRIPTION: &str = "Stop the server.";
|
|||||||
|
|
||||||
pub(crate) fn init_command_tree<'a>() -> CommandTree<'a> {
|
pub(crate) fn init_command_tree<'a>() -> CommandTree<'a> {
|
||||||
CommandTree::new(NAMES, DESCRIPTION).with_child(
|
CommandTree::new(NAMES, DESCRIPTION).with_child(
|
||||||
require(&|sender| sender.permission_lvl() >= 4).execute(&|sender, _args| {
|
require(&|sender| sender.permission_lvl() >= 4).execute(&|sender, _, _args| {
|
||||||
sender
|
sender
|
||||||
.send_message(TextComponent::text("Stopping Server").color_named(NamedColor::Red));
|
.send_message(TextComponent::text("Stopping Server").color_named(NamedColor::Red));
|
||||||
std::process::exit(0)
|
std::process::exit(0)
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ use crate::commands::dispatcher::InvalidTreeError::{
|
|||||||
};
|
};
|
||||||
use crate::commands::tree::{Command, CommandTree, ConsumedArgs, NodeType, RawArgs};
|
use crate::commands::tree::{Command, CommandTree, ConsumedArgs, NodeType, RawArgs};
|
||||||
use crate::commands::CommandSender;
|
use crate::commands::CommandSender;
|
||||||
|
use crate::server::Server;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@@ -23,7 +24,12 @@ pub(crate) struct CommandDispatcher<'a> {
|
|||||||
/// Stores registered [CommandTree]s and dispatches commands to them.
|
/// Stores registered [CommandTree]s and dispatches commands to them.
|
||||||
impl<'a> CommandDispatcher<'a> {
|
impl<'a> CommandDispatcher<'a> {
|
||||||
/// Execute a command using its corresponding [CommandTree].
|
/// Execute a command using its corresponding [CommandTree].
|
||||||
pub(crate) fn dispatch(&'a self, src: &mut CommandSender, cmd: &str) -> Result<(), String> {
|
pub(crate) fn dispatch(
|
||||||
|
&'a self,
|
||||||
|
src: &mut CommandSender,
|
||||||
|
server: &mut Server,
|
||||||
|
cmd: &str,
|
||||||
|
) -> Result<(), String> {
|
||||||
let mut parts = cmd.split_ascii_whitespace();
|
let mut parts = cmd.split_ascii_whitespace();
|
||||||
let key = parts.next().ok_or("Empty Command")?;
|
let key = parts.next().ok_or("Empty Command")?;
|
||||||
let raw_args: Vec<&str> = parts.rev().collect();
|
let raw_args: Vec<&str> = parts.rev().collect();
|
||||||
@@ -32,7 +38,7 @@ impl<'a> CommandDispatcher<'a> {
|
|||||||
|
|
||||||
// try paths until fitting path is found
|
// try paths until fitting path is found
|
||||||
for path in tree.iter_paths() {
|
for path in tree.iter_paths() {
|
||||||
match Self::try_is_fitting_path(src, path, tree, raw_args.clone()) {
|
match Self::try_is_fitting_path(src, server, path, tree, raw_args.clone()) {
|
||||||
Err(InvalidConsumptionError(s)) => {
|
Err(InvalidConsumptionError(s)) => {
|
||||||
println!("Error while parsing command \"{cmd}\": {s:?} was consumed, but couldn't be parsed");
|
println!("Error while parsing command \"{cmd}\": {s:?} was consumed, but couldn't be parsed");
|
||||||
return Err("Internal Error (See logs for details)".into());
|
return Err("Internal Error (See logs for details)".into());
|
||||||
@@ -69,6 +75,7 @@ impl<'a> CommandDispatcher<'a> {
|
|||||||
|
|
||||||
fn try_is_fitting_path(
|
fn try_is_fitting_path(
|
||||||
src: &mut CommandSender,
|
src: &mut CommandSender,
|
||||||
|
server: &mut Server,
|
||||||
path: Vec<usize>,
|
path: Vec<usize>,
|
||||||
tree: &CommandTree,
|
tree: &CommandTree,
|
||||||
mut raw_args: RawArgs,
|
mut raw_args: RawArgs,
|
||||||
@@ -79,7 +86,7 @@ impl<'a> CommandDispatcher<'a> {
|
|||||||
match node.node_type {
|
match node.node_type {
|
||||||
NodeType::ExecuteLeaf { run } => {
|
NodeType::ExecuteLeaf { run } => {
|
||||||
return if raw_args.is_empty() {
|
return if raw_args.is_empty() {
|
||||||
run(src, &parsed_args)?;
|
run(src, server, &parsed_args)?;
|
||||||
Ok(true)
|
Ok(true)
|
||||||
} else {
|
} else {
|
||||||
Ok(false)
|
Ok(false)
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ use std::sync::OnceLock;
|
|||||||
|
|
||||||
use crate::commands::dispatcher::CommandDispatcher;
|
use crate::commands::dispatcher::CommandDispatcher;
|
||||||
use crate::entity::player::Player;
|
use crate::entity::player::Player;
|
||||||
|
use crate::server::Server;
|
||||||
mod arg_player;
|
mod arg_player;
|
||||||
mod cmd_gamemode;
|
mod cmd_gamemode;
|
||||||
mod cmd_help;
|
mod cmd_help;
|
||||||
@@ -83,10 +84,10 @@ fn dispatcher_init<'a>() -> CommandDispatcher<'a> {
|
|||||||
dispatcher
|
dispatcher
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn handle_command(sender: &mut CommandSender, cmd: &str) {
|
pub fn handle_command(sender: &mut CommandSender, server: &mut Server, cmd: &str) {
|
||||||
let dispatcher = DISPATCHER.get_or_init(dispatcher_init);
|
let dispatcher = DISPATCHER.get_or_init(dispatcher_init);
|
||||||
|
|
||||||
if let Err(err) = dispatcher.dispatch(sender, cmd) {
|
if let Err(err) = dispatcher.dispatch(sender, server, cmd) {
|
||||||
sender.send_message(
|
sender.send_message(
|
||||||
TextComponent::text(&err).color_named(pumpkin_core::text::color::NamedColor::Red),
|
TextComponent::text(&err).color_named(pumpkin_core::text::color::NamedColor::Red),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ use std::collections::{HashMap, VecDeque};
|
|||||||
|
|
||||||
use crate::commands::dispatcher::InvalidTreeError;
|
use crate::commands::dispatcher::InvalidTreeError;
|
||||||
use crate::commands::CommandSender;
|
use crate::commands::CommandSender;
|
||||||
|
use crate::server::Server;
|
||||||
|
|
||||||
/// see [crate::commands::tree_builder::argument]
|
/// see [crate::commands::tree_builder::argument]
|
||||||
pub(crate) type RawArgs<'a> = Vec<&'a str>;
|
pub(crate) type RawArgs<'a> = Vec<&'a str>;
|
||||||
@@ -19,7 +20,8 @@ pub(crate) struct Node<'a> {
|
|||||||
|
|
||||||
pub(crate) enum NodeType<'a> {
|
pub(crate) enum NodeType<'a> {
|
||||||
ExecuteLeaf {
|
ExecuteLeaf {
|
||||||
run: &'a (dyn Fn(&mut CommandSender, &ConsumedArgs) -> Result<(), InvalidTreeError> + Sync),
|
run: &'a (dyn Fn(&mut CommandSender, &mut Server, &ConsumedArgs) -> Result<(), InvalidTreeError>
|
||||||
|
+ Sync),
|
||||||
},
|
},
|
||||||
#[allow(dead_code)] // todo: remove (so far no commands requiring this are implemented)
|
#[allow(dead_code)] // todo: remove (so far no commands requiring this are implemented)
|
||||||
Literal { string: &'a str },
|
Literal { string: &'a str },
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
use crate::commands::dispatcher::InvalidTreeError;
|
use crate::commands::dispatcher::InvalidTreeError;
|
||||||
use crate::commands::tree::{ArgumentConsumer, CommandTree, ConsumedArgs, Node, NodeType};
|
use crate::commands::tree::{ArgumentConsumer, CommandTree, ConsumedArgs, Node, NodeType};
|
||||||
use crate::commands::CommandSender;
|
use crate::commands::CommandSender;
|
||||||
|
use crate::server::Server;
|
||||||
|
|
||||||
impl<'a> CommandTree<'a> {
|
impl<'a> CommandTree<'a> {
|
||||||
/// Add a child [Node] to the root of this [CommandTree].
|
/// Add a child [Node] to the root of this [CommandTree].
|
||||||
@@ -41,7 +42,8 @@ impl<'a> CommandTree<'a> {
|
|||||||
/// Also see [NonLeafNodeBuilder::execute].
|
/// Also see [NonLeafNodeBuilder::execute].
|
||||||
pub fn execute(
|
pub fn execute(
|
||||||
mut self,
|
mut self,
|
||||||
run: &'a (dyn Fn(&mut CommandSender, &ConsumedArgs) -> Result<(), InvalidTreeError> + Sync),
|
run: &'a (dyn Fn(&mut CommandSender, &mut Server, &ConsumedArgs) -> Result<(), InvalidTreeError>
|
||||||
|
+ Sync),
|
||||||
) -> Self {
|
) -> Self {
|
||||||
let node = Node {
|
let node = Node {
|
||||||
node_type: NodeType::ExecuteLeaf { run },
|
node_type: NodeType::ExecuteLeaf { run },
|
||||||
@@ -117,7 +119,8 @@ impl<'a> NonLeafNodeBuilder<'a> {
|
|||||||
/// Also see [CommandTree::execute].
|
/// Also see [CommandTree::execute].
|
||||||
pub fn execute(
|
pub fn execute(
|
||||||
mut self,
|
mut self,
|
||||||
run: &'a (dyn Fn(&mut CommandSender, &ConsumedArgs) -> Result<(), InvalidTreeError> + Sync),
|
run: &'a (dyn Fn(&mut CommandSender, &mut Server, &ConsumedArgs) -> Result<(), InvalidTreeError>
|
||||||
|
+ Sync),
|
||||||
) -> Self {
|
) -> Self {
|
||||||
self.leaf_nodes.push(LeafNodeBuilder {
|
self.leaf_nodes.push(LeafNodeBuilder {
|
||||||
node_type: NodeType::ExecuteLeaf { run },
|
node_type: NodeType::ExecuteLeaf { run },
|
||||||
|
|||||||
@@ -6,10 +6,13 @@ use pumpkin_core::text::TextComponent;
|
|||||||
use pumpkin_entity::{entity_type::EntityType, Entity, EntityId};
|
use pumpkin_entity::{entity_type::EntityType, Entity, EntityId};
|
||||||
use pumpkin_inventory::player::PlayerInventory;
|
use pumpkin_inventory::player::PlayerInventory;
|
||||||
use pumpkin_protocol::{
|
use pumpkin_protocol::{
|
||||||
bytebuf::packet_id::Packet,
|
bytebuf::{packet_id::Packet, DeserializerError},
|
||||||
client::play::{CGameEvent, CPlayDisconnect, CSyncPlayerPosition, CSystemChatMessage},
|
client::play::{
|
||||||
|
CGameEvent, CPlayDisconnect, CPlayerInfoUpdate, CSyncPlayerPosition, CSystemChatMessage,
|
||||||
|
PlayerAction,
|
||||||
|
},
|
||||||
server::play::{
|
server::play::{
|
||||||
SChatCommand, SChatMessage, SClientInformationPlay, SConfirmTeleport, SInteract, SPlayPingRequest, SPlayerAction, SPlayerCommand, SPlayerPosition, SPlayerPositionRotation, SPlayerRotation, SSetCreativeSlot, SSetHeldItem, SSwingArm, SUseItem, SUseItemOn
|
SChatCommand, SChatMessage, SClientInformationPlay, SConfirmTeleport, SInteract, SPlayPingRequest, SPlayerAction, SPlayerCommand, SPlayerPosition, SPlayerPositionRotation, SPlayerRotation, SSetCreativeSlot, SSetHeldItem, SSetPlayerGround, SSwingArm, SUseItem, SUseItemOn
|
||||||
},
|
},
|
||||||
ConnectionState, RawPacket, ServerPacket, VarInt,
|
ConnectionState, RawPacket, ServerPacket, VarInt,
|
||||||
};
|
};
|
||||||
@@ -137,8 +140,18 @@ impl Player {
|
|||||||
self.food_saturation = food_saturation;
|
self.food_saturation = food_saturation;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_gamemode(&mut self, gamemode: GameMode) {
|
pub fn set_gamemode(&mut self, server: &mut Server, gamemode: GameMode) {
|
||||||
self.gamemode = gamemode;
|
self.gamemode = gamemode;
|
||||||
|
server.broadcast_packet(
|
||||||
|
self,
|
||||||
|
&CPlayerInfoUpdate::new(
|
||||||
|
0x04,
|
||||||
|
&[pumpkin_protocol::client::play::Player {
|
||||||
|
uuid: self.client.gameprofile.as_ref().unwrap().id,
|
||||||
|
actions: vec![PlayerAction::UpdateGameMode((self.gamemode as i32).into())],
|
||||||
|
}],
|
||||||
|
),
|
||||||
|
);
|
||||||
self.client
|
self.client
|
||||||
.send_packet(&CGameEvent::new(3, gamemode.to_f32().unwrap()));
|
.send_packet(&CGameEvent::new(3, gamemode.to_f32().unwrap()));
|
||||||
}
|
}
|
||||||
@@ -151,64 +164,97 @@ impl Player {
|
|||||||
|
|
||||||
impl Player {
|
impl Player {
|
||||||
pub fn process_packets(&mut self, server: &mut Server) {
|
pub fn process_packets(&mut self, server: &mut Server) {
|
||||||
let mut i = 0;
|
while let Some(mut packet) = self.client.client_packets_queue.pop() {
|
||||||
while i < self.client.client_packets_queue.len() {
|
match self.handle_play_packet(server, &mut packet) {
|
||||||
let mut packet = self.client.client_packets_queue.remove(i).unwrap();
|
Ok(_) => {}
|
||||||
self.handle_play_packet(server, &mut packet);
|
Err(e) => {
|
||||||
i += 1;
|
let text = format!("Error while reading incoming packet {}", e);
|
||||||
|
log::error!("{}", text);
|
||||||
|
self.kick(TextComponent::text(&text))
|
||||||
|
}
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn handle_play_packet(&mut self, server: &mut Server, packet: &mut RawPacket) {
|
pub fn handle_play_packet(
|
||||||
|
&mut self,
|
||||||
|
server: &mut Server,
|
||||||
|
packet: &mut RawPacket,
|
||||||
|
) -> Result<(), DeserializerError> {
|
||||||
let bytebuf = &mut packet.bytebuf;
|
let bytebuf = &mut packet.bytebuf;
|
||||||
match packet.id.0 {
|
match packet.id.0 {
|
||||||
SConfirmTeleport::PACKET_ID => {
|
SConfirmTeleport::PACKET_ID => {
|
||||||
self.handle_confirm_teleport(server, SConfirmTeleport::read(bytebuf).unwrap())
|
self.handle_confirm_teleport(server, SConfirmTeleport::read(bytebuf)?);
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
SChatCommand::PACKET_ID => {
|
SChatCommand::PACKET_ID => {
|
||||||
self.handle_chat_command(server, SChatCommand::read(bytebuf).unwrap())
|
self.handle_chat_command(server, SChatCommand::read(bytebuf)?);
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
SPlayerPosition::PACKET_ID => {
|
SPlayerPosition::PACKET_ID => {
|
||||||
self.handle_position(server, SPlayerPosition::read(bytebuf).unwrap())
|
self.handle_position(server, SPlayerPosition::read(bytebuf)?);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
SPlayerPositionRotation::PACKET_ID => {
|
||||||
|
self.handle_position_rotation(server, SPlayerPositionRotation::read(bytebuf)?);
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
SPlayerPositionRotation::PACKET_ID => self
|
|
||||||
.handle_position_rotation(server, SPlayerPositionRotation::read(bytebuf).unwrap()),
|
|
||||||
SPlayerRotation::PACKET_ID => {
|
SPlayerRotation::PACKET_ID => {
|
||||||
self.handle_rotation(server, SPlayerRotation::read(bytebuf).unwrap())
|
self.handle_rotation(server, SPlayerRotation::read(bytebuf)?);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
SSetPlayerGround::PACKET_ID => {
|
||||||
|
self.handle_player_ground(server, SSetPlayerGround::read(bytebuf)?);
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
SPlayerCommand::PACKET_ID => {
|
SPlayerCommand::PACKET_ID => {
|
||||||
self.handle_player_command(server, SPlayerCommand::read(bytebuf).unwrap())
|
self.handle_player_command(server, SPlayerCommand::read(bytebuf)?);
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
SSwingArm::PACKET_ID => {
|
SSwingArm::PACKET_ID => {
|
||||||
self.handle_swing_arm(server, SSwingArm::read(bytebuf).unwrap())
|
self.handle_swing_arm(server, SSwingArm::read(bytebuf)?);
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
SChatMessage::PACKET_ID => {
|
SChatMessage::PACKET_ID => {
|
||||||
self.handle_chat_message(server, SChatMessage::read(bytebuf).unwrap())
|
self.handle_chat_message(server, SChatMessage::read(bytebuf)?);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
SClientInformationPlay::PACKET_ID => {
|
||||||
|
self.handle_client_information_play(server, SClientInformationPlay::read(bytebuf)?);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
SInteract::PACKET_ID => {
|
||||||
|
self.handle_interact(server, SInteract::read(bytebuf)?);
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
SClientInformationPlay::PACKET_ID => self.handle_client_information_play(
|
|
||||||
server,
|
|
||||||
SClientInformationPlay::read(bytebuf).unwrap(),
|
|
||||||
),
|
|
||||||
SInteract::PACKET_ID => self.handle_interact(server, SInteract::read(bytebuf).unwrap()),
|
|
||||||
SPlayerAction::PACKET_ID => {
|
SPlayerAction::PACKET_ID => {
|
||||||
self.handle_player_action(server, SPlayerAction::read(bytebuf).unwrap())
|
self.handle_player_action(server, SPlayerAction::read(bytebuf)?);
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
SUseItemOn::PACKET_ID => {
|
SUseItemOn::PACKET_ID => {
|
||||||
self.handle_use_item_on(server, SUseItemOn::read(bytebuf).unwrap())
|
self.handle_use_item_on(server, SUseItemOn::read(bytebuf)?);
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
SUseItem::PACKET_ID => {
|
SUseItem::PACKET_ID => {
|
||||||
log::error!("An item was used(SUseItem), but the packet is not implemented yet");
|
log::error!("An item was used(SUseItem), but the packet is not implemented yet");
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
SSetHeldItem::PACKET_ID => {
|
SSetHeldItem::PACKET_ID => {
|
||||||
self.handle_set_held_item(server, SSetHeldItem::read(bytebuf).unwrap())
|
self.handle_set_held_item(server, SSetHeldItem::read(bytebuf)?);
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
SSetCreativeSlot::PACKET_ID => {
|
SSetCreativeSlot::PACKET_ID => {
|
||||||
self.handle_set_creative_slot(server, SSetCreativeSlot::read(bytebuf).unwrap())
|
self.handle_set_creative_slot(server, SSetCreativeSlot::read(bytebuf)?);
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
SPlayPingRequest::PACKET_ID => {
|
SPlayPingRequest::PACKET_ID => {
|
||||||
self.handle_play_ping_request(server, SPlayPingRequest::read(bytebuf).unwrap())
|
self.handle_play_ping_request(server, SPlayPingRequest::read(bytebuf)?);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
log::error!("Failed to handle player packet id {:#04x}", packet.id.0);
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
_ => log::error!("Failed to handle player packet id {:#04x}", packet.id.0),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+26
-14
@@ -1,4 +1,5 @@
|
|||||||
#![allow(clippy::await_holding_refcell_ref)]
|
#![allow(clippy::await_holding_refcell_ref)]
|
||||||
|
#![allow(clippy::await_holding_lock)]
|
||||||
|
|
||||||
use mio::net::TcpListener;
|
use mio::net::TcpListener;
|
||||||
use mio::{Events, Interest, Poll, Token};
|
use mio::{Events, Interest, Poll, Token};
|
||||||
@@ -8,7 +9,7 @@ use client::Client;
|
|||||||
use commands::handle_command;
|
use commands::handle_command;
|
||||||
use config::AdvancedConfiguration;
|
use config::AdvancedConfiguration;
|
||||||
|
|
||||||
use std::{collections::HashMap, rc::Rc, thread};
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use client::interrupted;
|
use client::interrupted;
|
||||||
use config::BasicConfiguration;
|
use config::BasicConfiguration;
|
||||||
@@ -31,8 +32,11 @@ static ALLOC: dhat::Alloc = dhat::Alloc;
|
|||||||
|
|
||||||
#[cfg(not(target_os = "wasi"))]
|
#[cfg(not(target_os = "wasi"))]
|
||||||
fn main() -> io::Result<()> {
|
fn main() -> io::Result<()> {
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
use entity::player::Player;
|
use entity::player::Player;
|
||||||
use pumpkin_core::text::{color::NamedColor, TextComponent};
|
use pumpkin_core::text::{color::NamedColor, TextComponent};
|
||||||
|
use rcon::RCONServer;
|
||||||
|
|
||||||
#[cfg(feature = "dhat-heap")]
|
#[cfg(feature = "dhat-heap")]
|
||||||
let _profiler = dhat::Profiler::new_heap();
|
let _profiler = dhat::Profiler::new_heap();
|
||||||
@@ -57,9 +61,7 @@ fn main() -> io::Result<()> {
|
|||||||
rayon::ThreadPoolBuilder::new().build_global().unwrap();
|
rayon::ThreadPoolBuilder::new().build_global().unwrap();
|
||||||
rt.block_on(async {
|
rt.block_on(async {
|
||||||
const SERVER: Token = Token(0);
|
const SERVER: Token = Token(0);
|
||||||
use std::{cell::RefCell, time::Instant};
|
use std::time::Instant;
|
||||||
|
|
||||||
use rcon::RCONServer;
|
|
||||||
|
|
||||||
let time = Instant::now();
|
let time = Instant::now();
|
||||||
let basic_config = BasicConfiguration::load("configuration.toml");
|
let basic_config = BasicConfiguration::load("configuration.toml");
|
||||||
@@ -95,14 +97,18 @@ fn main() -> io::Result<()> {
|
|||||||
let rcon = advanced_configuration.rcon.clone();
|
let rcon = advanced_configuration.rcon.clone();
|
||||||
|
|
||||||
let mut clients: HashMap<Token, Client> = HashMap::new();
|
let mut clients: HashMap<Token, Client> = HashMap::new();
|
||||||
let mut players: HashMap<Rc<Token>, Rc<RefCell<Player>>> = HashMap::new();
|
let mut players: HashMap<Arc<Token>, Arc<Mutex<Player>>> = HashMap::new();
|
||||||
|
|
||||||
let mut server = Server::new((basic_config, advanced_configuration));
|
let server = Arc::new(tokio::sync::Mutex::new(Server::new((
|
||||||
|
basic_config,
|
||||||
|
advanced_configuration,
|
||||||
|
))));
|
||||||
log::info!("Started Server took {}ms", time.elapsed().as_millis());
|
log::info!("Started Server took {}ms", time.elapsed().as_millis());
|
||||||
log::info!("You now can connect to the server, Listening on {}", addr);
|
log::info!("You now can connect to the server, Listening on {}", addr);
|
||||||
|
|
||||||
|
let server1 = server.clone();
|
||||||
if use_console {
|
if use_console {
|
||||||
thread::spawn(move || {
|
tokio::spawn(async move {
|
||||||
let stdin = std::io::stdin();
|
let stdin = std::io::stdin();
|
||||||
loop {
|
loop {
|
||||||
let mut out = String::new();
|
let mut out = String::new();
|
||||||
@@ -111,14 +117,16 @@ fn main() -> io::Result<()> {
|
|||||||
.expect("Failed to read console line");
|
.expect("Failed to read console line");
|
||||||
|
|
||||||
if !out.is_empty() {
|
if !out.is_empty() {
|
||||||
handle_command(&mut commands::CommandSender::Console, &out);
|
let mut server = server1.lock().await;
|
||||||
|
handle_command(&mut commands::CommandSender::Console, &mut server, &out);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if rcon.enabled {
|
if rcon.enabled {
|
||||||
|
let server = server.clone();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
RCONServer::new(&rcon).await.unwrap();
|
RCONServer::new(&rcon, server).await.unwrap();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
loop {
|
loop {
|
||||||
@@ -161,16 +169,17 @@ fn main() -> io::Result<()> {
|
|||||||
token,
|
token,
|
||||||
Interest::READABLE.add(Interest::WRITABLE),
|
Interest::READABLE.add(Interest::WRITABLE),
|
||||||
)?;
|
)?;
|
||||||
let rc_token = Rc::new(token);
|
let rc_token = Arc::new(token);
|
||||||
let client = Client::new(Rc::clone(&rc_token), connection, addr);
|
let client = Client::new(Arc::clone(&rc_token), connection, addr);
|
||||||
clients.insert(token, client);
|
clients.insert(token, client);
|
||||||
},
|
},
|
||||||
|
|
||||||
token => {
|
token => {
|
||||||
// Poll Players
|
// Poll Players
|
||||||
let done = if let Some(player) = players.get_mut(&token) {
|
let done = if let Some(player) = players.get_mut(&token) {
|
||||||
let mut player = player.borrow_mut();
|
let mut player = player.lock().unwrap();
|
||||||
player.client.poll(event).await;
|
player.client.poll(event).await;
|
||||||
|
let mut server = server.lock().await;
|
||||||
player.process_packets(&mut server);
|
player.process_packets(&mut server);
|
||||||
player.client.closed
|
player.client.closed
|
||||||
} else {
|
} else {
|
||||||
@@ -179,8 +188,9 @@ fn main() -> io::Result<()> {
|
|||||||
|
|
||||||
if done {
|
if done {
|
||||||
if let Some(player) = players.remove(&token) {
|
if let Some(player) = players.remove(&token) {
|
||||||
|
let mut server = server.lock().await;
|
||||||
server.remove_player(&token);
|
server.remove_player(&token);
|
||||||
let mut player = player.borrow_mut();
|
let mut player = player.lock().unwrap();
|
||||||
poll.registry().deregister(&mut player.client.connection)?;
|
poll.registry().deregister(&mut player.client.connection)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -189,6 +199,7 @@ fn main() -> io::Result<()> {
|
|||||||
// Maybe received an event for a TCP connection.
|
// Maybe received an event for a TCP connection.
|
||||||
let (done, make_player) = if let Some(client) = clients.get_mut(&token) {
|
let (done, make_player) = if let Some(client) = clients.get_mut(&token) {
|
||||||
client.poll(event).await;
|
client.poll(event).await;
|
||||||
|
let mut server = server.lock().await;
|
||||||
client.process_packets(&mut server).await;
|
client.process_packets(&mut server).await;
|
||||||
(client.closed, client.make_player)
|
(client.closed, client.make_player)
|
||||||
} else {
|
} else {
|
||||||
@@ -201,9 +212,10 @@ fn main() -> io::Result<()> {
|
|||||||
poll.registry().deregister(&mut client.connection)?;
|
poll.registry().deregister(&mut client.connection)?;
|
||||||
} else if make_player {
|
} else if make_player {
|
||||||
let token = client.token.clone();
|
let token = client.token.clone();
|
||||||
|
let mut server = server.lock().await;
|
||||||
let player = server.add_player(token.clone(), client);
|
let player = server.add_player(token.clone(), client);
|
||||||
players.insert(token, player.clone());
|
players.insert(token, player.clone());
|
||||||
let mut player = player.borrow_mut();
|
let mut player = player.lock().unwrap();
|
||||||
server.spawn_player(&mut player).await;
|
server.spawn_player(&mut player).await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+21
-7
@@ -1,6 +1,7 @@
|
|||||||
use std::{
|
use std::{
|
||||||
collections::HashMap,
|
collections::HashMap,
|
||||||
io::{self, Read},
|
io::{self, Read},
|
||||||
|
sync::Arc,
|
||||||
};
|
};
|
||||||
|
|
||||||
use mio::{
|
use mio::{
|
||||||
@@ -10,7 +11,7 @@ use mio::{
|
|||||||
use packet::{Packet, PacketError, PacketType};
|
use packet::{Packet, PacketError, PacketType};
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
use crate::{commands::handle_command, config::RCONConfig};
|
use crate::{commands::handle_command, config::RCONConfig, server::Server};
|
||||||
|
|
||||||
mod packet;
|
mod packet;
|
||||||
|
|
||||||
@@ -29,7 +30,10 @@ const SERVER: Token = Token(0);
|
|||||||
pub struct RCONServer {}
|
pub struct RCONServer {}
|
||||||
|
|
||||||
impl RCONServer {
|
impl RCONServer {
|
||||||
pub async fn new(config: &RCONConfig) -> Result<Self, io::Error> {
|
pub async fn new(
|
||||||
|
config: &RCONConfig,
|
||||||
|
server: Arc<tokio::sync::Mutex<Server>>,
|
||||||
|
) -> Result<Self, io::Error> {
|
||||||
assert!(config.enabled, "RCON is not enabled");
|
assert!(config.enabled, "RCON is not enabled");
|
||||||
let addr = format!("{}:{}", config.ip, config.port)
|
let addr = format!("{}:{}", config.ip, config.port)
|
||||||
.parse()
|
.parse()
|
||||||
@@ -43,7 +47,7 @@ impl RCONServer {
|
|||||||
|
|
||||||
let mut unique_token = Token(SERVER.0 + 1);
|
let mut unique_token = Token(SERVER.0 + 1);
|
||||||
|
|
||||||
let mut events = Events::with_capacity(128);
|
let mut events = Events::with_capacity(20);
|
||||||
|
|
||||||
let mut connections: HashMap<Token, RCONClient> = HashMap::new();
|
let mut connections: HashMap<Token, RCONClient> = HashMap::new();
|
||||||
|
|
||||||
@@ -87,7 +91,7 @@ impl RCONServer {
|
|||||||
|
|
||||||
token => {
|
token => {
|
||||||
let done = if let Some(client) = connections.get_mut(&token) {
|
let done = if let Some(client) = connections.get_mut(&token) {
|
||||||
client.handle(&password).await
|
client.handle(&server, &password).await
|
||||||
} else {
|
} else {
|
||||||
false
|
false
|
||||||
};
|
};
|
||||||
@@ -126,7 +130,11 @@ impl RCONClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn handle(&mut self, password: &str) -> bool {
|
pub async fn handle(
|
||||||
|
&mut self,
|
||||||
|
server: &Arc<tokio::sync::Mutex<Server>>,
|
||||||
|
password: &str,
|
||||||
|
) -> bool {
|
||||||
if !self.closed {
|
if !self.closed {
|
||||||
loop {
|
loop {
|
||||||
match self.read_bytes() {
|
match self.read_bytes() {
|
||||||
@@ -141,7 +149,7 @@ impl RCONClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// If we get a close here, we might have a reply, which we still want to write.
|
// If we get a close here, we might have a reply, which we still want to write.
|
||||||
match self.poll(password).await {
|
match self.poll(server, password).await {
|
||||||
Ok(()) => {}
|
Ok(()) => {}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
log::error!("rcon error: {e}");
|
log::error!("rcon error: {e}");
|
||||||
@@ -152,7 +160,11 @@ impl RCONClient {
|
|||||||
self.closed
|
self.closed
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn poll(&mut self, password: &str) -> Result<(), PacketError> {
|
async fn poll(
|
||||||
|
&mut self,
|
||||||
|
server: &Arc<tokio::sync::Mutex<Server>>,
|
||||||
|
password: &str,
|
||||||
|
) -> Result<(), PacketError> {
|
||||||
loop {
|
loop {
|
||||||
let packet = match self.receive_packet().await? {
|
let packet = match self.receive_packet().await? {
|
||||||
Some(p) => p,
|
Some(p) => p,
|
||||||
@@ -183,8 +195,10 @@ impl RCONClient {
|
|||||||
PacketType::ExecCommand => {
|
PacketType::ExecCommand => {
|
||||||
if self.logged_in {
|
if self.logged_in {
|
||||||
let mut output = Vec::new();
|
let mut output = Vec::new();
|
||||||
|
let mut server = server.lock().await;
|
||||||
handle_command(
|
handle_command(
|
||||||
&mut crate::commands::CommandSender::Rcon(&mut output),
|
&mut crate::commands::CommandSender::Rcon(&mut output),
|
||||||
|
&mut server,
|
||||||
packet.get_body(),
|
packet.get_body(),
|
||||||
);
|
);
|
||||||
for line in output {
|
for line in output {
|
||||||
|
|||||||
+16
-18
@@ -1,12 +1,10 @@
|
|||||||
use std::{
|
use std::{
|
||||||
cell::{RefCell, RefMut},
|
|
||||||
collections::HashMap,
|
collections::HashMap,
|
||||||
io::Cursor,
|
io::Cursor,
|
||||||
path::Path,
|
path::Path,
|
||||||
rc::Rc,
|
|
||||||
sync::{
|
sync::{
|
||||||
atomic::{AtomicI32, Ordering},
|
atomic::{AtomicI32, Ordering},
|
||||||
Arc,
|
Arc, Mutex, MutexGuard,
|
||||||
},
|
},
|
||||||
time::Duration,
|
time::Duration,
|
||||||
};
|
};
|
||||||
@@ -33,7 +31,7 @@ use pumpkin_world::{dimension::Dimension, radial_chunk_iterator::RadialIterator,
|
|||||||
use pumpkin_registry::Registry;
|
use pumpkin_registry::Registry;
|
||||||
use rsa::{traits::PublicKeyParts, RsaPrivateKey, RsaPublicKey};
|
use rsa::{traits::PublicKeyParts, RsaPrivateKey, RsaPublicKey};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use tokio::sync::{mpsc, Mutex};
|
use tokio::sync::mpsc;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
client::Client,
|
client::Client,
|
||||||
@@ -48,7 +46,7 @@ pub struct Server {
|
|||||||
pub private_key: RsaPrivateKey,
|
pub private_key: RsaPrivateKey,
|
||||||
pub public_key_der: Box<[u8]>,
|
pub public_key_der: Box<[u8]>,
|
||||||
|
|
||||||
pub world: Arc<Mutex<World>>,
|
pub world: Arc<tokio::sync::Mutex<World>>,
|
||||||
pub status_response: StatusResponse,
|
pub status_response: StatusResponse,
|
||||||
// We cache the json response here so we don't parse it every time someone makes a Status request.
|
// We cache the json response here so we don't parse it every time someone makes a Status request.
|
||||||
// Keep in mind that we must parse this again, when the StatusResponse changes which usally happen when a player joins or leaves
|
// Keep in mind that we must parse this again, when the StatusResponse changes which usally happen when a player joins or leaves
|
||||||
@@ -60,7 +58,7 @@ pub struct Server {
|
|||||||
/// Cache the registry so we don't have to parse it every time a player joins
|
/// Cache the registry so we don't have to parse it every time a player joins
|
||||||
pub cached_registry: Vec<Registry>,
|
pub cached_registry: Vec<Registry>,
|
||||||
|
|
||||||
pub current_players: HashMap<Rc<Token>, Rc<RefCell<Player>>>,
|
pub current_players: HashMap<Arc<Token>, Arc<Mutex<Player>>>,
|
||||||
|
|
||||||
// TODO: replace with HashMap <World, Player>
|
// TODO: replace with HashMap <World, Player>
|
||||||
entity_id: AtomicI32, // TODO: place this into every world
|
entity_id: AtomicI32, // TODO: place this into every world
|
||||||
@@ -108,7 +106,7 @@ impl Server {
|
|||||||
cached_registry: Registry::get_static(),
|
cached_registry: Registry::get_static(),
|
||||||
// 0 is invalid
|
// 0 is invalid
|
||||||
entity_id: 2.into(),
|
entity_id: 2.into(),
|
||||||
world: Arc::new(Mutex::new(world)),
|
world: Arc::new(tokio::sync::Mutex::new(world)),
|
||||||
public_key,
|
public_key,
|
||||||
cached_server_brand,
|
cached_server_brand,
|
||||||
private_key,
|
private_key,
|
||||||
@@ -122,20 +120,20 @@ impl Server {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn add_player(&mut self, token: Rc<Token>, client: Client) -> Rc<RefCell<Player>> {
|
pub fn add_player(&mut self, token: Arc<Token>, client: Client) -> Arc<Mutex<Player>> {
|
||||||
let entity_id = self.new_entity_id();
|
let entity_id = self.new_entity_id();
|
||||||
let gamemode = match self.base_config.default_gamemode {
|
let gamemode = match self.base_config.default_gamemode {
|
||||||
GameMode::Undefined => GameMode::Survival,
|
GameMode::Undefined => GameMode::Survival,
|
||||||
game_mode => game_mode,
|
game_mode => game_mode,
|
||||||
};
|
};
|
||||||
let player = Rc::new(RefCell::new(Player::new(client, entity_id, gamemode)));
|
let player = Arc::new(Mutex::new(Player::new(client, entity_id, gamemode)));
|
||||||
self.current_players.insert(token, player.clone());
|
self.current_players.insert(token, player.clone());
|
||||||
player
|
player
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn remove_player(&mut self, token: &Token) {
|
pub fn remove_player(&mut self, token: &Token) {
|
||||||
let player = self.current_players.remove(token).unwrap();
|
let player = self.current_players.remove(token).unwrap();
|
||||||
let player = player.as_ref().borrow();
|
let player = player.as_ref().lock().unwrap();
|
||||||
// despawn the player
|
// despawn the player
|
||||||
// todo: put this into the entitiy struct
|
// todo: put this into the entitiy struct
|
||||||
let id = player.entity_id();
|
let id = player.entity_id();
|
||||||
@@ -204,7 +202,7 @@ impl Server {
|
|||||||
name: gameprofile.name.clone(),
|
name: gameprofile.name.clone(),
|
||||||
properties: gameprofile.properties.clone(),
|
properties: gameprofile.properties.clone(),
|
||||||
},
|
},
|
||||||
PlayerAction::UpdateListed { listed: true },
|
PlayerAction::UpdateListed(true),
|
||||||
],
|
],
|
||||||
}],
|
}],
|
||||||
),
|
),
|
||||||
@@ -217,7 +215,7 @@ impl Server {
|
|||||||
.iter()
|
.iter()
|
||||||
.filter(|c| c.0 != &player.client.token)
|
.filter(|c| c.0 != &player.client.token)
|
||||||
{
|
{
|
||||||
let playerr = playerr.as_ref().borrow();
|
let playerr = playerr.as_ref().lock().unwrap();
|
||||||
let gameprofile = &playerr.client.gameprofile.as_ref().unwrap();
|
let gameprofile = &playerr.client.gameprofile.as_ref().unwrap();
|
||||||
entries.push(pumpkin_protocol::client::play::Player {
|
entries.push(pumpkin_protocol::client::play::Player {
|
||||||
uuid: gameprofile.id,
|
uuid: gameprofile.id,
|
||||||
@@ -226,7 +224,7 @@ impl Server {
|
|||||||
name: gameprofile.name.clone(),
|
name: gameprofile.name.clone(),
|
||||||
properties: gameprofile.properties.clone(),
|
properties: gameprofile.properties.clone(),
|
||||||
},
|
},
|
||||||
PlayerAction::UpdateListed { listed: true },
|
PlayerAction::UpdateListed(true),
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -262,7 +260,7 @@ impl Server {
|
|||||||
// spawn players for our client
|
// spawn players for our client
|
||||||
let token = player.client.token.clone();
|
let token = player.client.token.clone();
|
||||||
for (_, existing_player) in self.current_players.iter().filter(|c| c.0 != &token) {
|
for (_, existing_player) in self.current_players.iter().filter(|c| c.0 != &token) {
|
||||||
let existing_player = existing_player.as_ref().borrow();
|
let existing_player = existing_player.as_ref().lock().unwrap();
|
||||||
let entity = &existing_player.entity;
|
let entity = &existing_player.entity;
|
||||||
let gameprofile = existing_player.client.gameprofile.as_ref().unwrap();
|
let gameprofile = existing_player.client.gameprofile.as_ref().unwrap();
|
||||||
player.client.send_packet(&CSpawnEntity::new(
|
player.client.send_packet(&CSpawnEntity::new(
|
||||||
@@ -297,13 +295,13 @@ impl Server {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// TODO: This definitly should be in world
|
/// TODO: This definitly should be in world
|
||||||
pub fn get_by_entityid(&self, from: &Player, id: EntityId) -> Option<RefMut<Player>> {
|
pub fn get_by_entityid(&self, from: &Player, id: EntityId) -> Option<MutexGuard<Player>> {
|
||||||
for (_, player) in self
|
for (_, player) in self
|
||||||
.current_players
|
.current_players
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|c| c.0 != &from.client.token)
|
.filter(|c| c.0 != &from.client.token)
|
||||||
{
|
{
|
||||||
let player = player.borrow_mut();
|
let player = player.lock().unwrap();
|
||||||
if player.entity_id() == id {
|
if player.entity_id() == id {
|
||||||
return Some(player);
|
return Some(player);
|
||||||
}
|
}
|
||||||
@@ -323,7 +321,7 @@ impl Server {
|
|||||||
.iter()
|
.iter()
|
||||||
.filter(|c| c.0 != &from.client.token)
|
.filter(|c| c.0 != &from.client.token)
|
||||||
{
|
{
|
||||||
let mut player = player.borrow_mut();
|
let mut player = player.lock().unwrap();
|
||||||
player.client.send_packet(packet);
|
player.client.send_packet(packet);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -338,7 +336,7 @@ impl Server {
|
|||||||
.iter()
|
.iter()
|
||||||
.filter(|c| !from.contains(&c.0.as_ref()))
|
.filter(|c| !from.contains(&c.0.as_ref()))
|
||||||
{
|
{
|
||||||
let mut player = player.borrow_mut();
|
let mut player = player.lock().unwrap();
|
||||||
player.client.send_packet(packet);
|
player.client.send_packet(packet);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user