Skip to content

Commit

Permalink
Merge pull request #84 from Snowiiii/server-cleanup
Browse files Browse the repository at this point in the history
Cleanup Server struct
  • Loading branch information
Snowiiii authored Sep 8, 2024
2 parents 6a75617 + 08743d1 commit 2ef1a13
Show file tree
Hide file tree
Showing 15 changed files with 131 additions and 126 deletions.
8 changes: 4 additions & 4 deletions pumpkin-inventory/src/open_container.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
use crate::{Container, WindowType};
use pumpkin_world::item::ItemStack;
use std::sync::Mutex;
use std::sync::{Arc, Mutex};

pub struct OpenContainer {
players: Vec<i32>,
container: Mutex<Box<dyn Container>>,
container: Arc<Mutex<Box<dyn Container>>>,
}

impl OpenContainer {
pub fn try_open(&self, player_id: i32) -> Option<&Mutex<Box<dyn Container>>> {
pub fn try_open(&self, player_id: i32) -> Option<&Arc<Mutex<Box<dyn Container>>>> {
if !self.players.contains(&player_id) {
dbg!("couldn't open container");
return None;
Expand Down Expand Up @@ -38,7 +38,7 @@ impl OpenContainer {
pub fn empty(player_id: i32) -> Self {
Self {
players: vec![player_id],
container: Mutex::new(Box::new(Chest::new())),
container: Arc::new(Mutex::new(Box::new(Chest::new()))),
}
}

Expand Down
12 changes: 6 additions & 6 deletions pumpkin/src/client/authentication.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{collections::HashMap, net::IpAddr};
use std::{collections::HashMap, net::IpAddr, sync::Arc};

use base64::{engine::general_purpose, Engine};
use num_bigint::BigInt;
Expand All @@ -13,13 +13,13 @@ use uuid::Uuid;
use crate::server::Server;

#[derive(Deserialize, Clone, Debug)]
#[expect(non_snake_case)]
#[expect(dead_code)]
#[serde(rename_all = "camelCase")]
pub struct ProfileTextures {
timestamp: i64,
profileId: Uuid,
profileName: String,
signatureRequired: bool,
profile_id: Uuid,
profile_name: String,
signature_required: bool,
textures: HashMap<String, Texture>,
}

Expand All @@ -43,7 +43,7 @@ pub async fn authenticate(
username: &str,
server_hash: &str,
ip: &IpAddr,
server: &mut Server,
server: &Arc<Server>,
) -> Result<GameProfile, AuthError> {
assert!(ADVANCED_CONFIG.authentication.enabled);
assert!(server.auth_client.is_some());
Expand Down
24 changes: 13 additions & 11 deletions pumpkin/src/client/client_packet.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::sync::Arc;

use num_traits::FromPrimitive;
use pumpkin_config::{ADVANCED_CONFIG, BASIC_CONFIG};
use pumpkin_core::text::TextComponent;
Expand Down Expand Up @@ -35,7 +37,7 @@ use super::{
/// NEVER TRUST THE CLIENT. HANDLE EVERY ERROR, UNWRAP/EXPECT
/// TODO: REMOVE ALL UNWRAPS
impl Client {
pub fn handle_handshake(&mut self, _server: &mut Server, handshake: SHandShake) {
pub fn handle_handshake(&mut self, _server: &Arc<Server>, handshake: SHandShake) {
dbg!("handshake");
self.protocol_version = handshake.protocol_version.0;
self.connection_state = handshake.next_state;
Expand All @@ -53,11 +55,11 @@ impl Client {
}
}

pub fn handle_status_request(&mut self, server: &mut Server, _status_request: SStatusRequest) {
pub fn handle_status_request(&mut self, server: &Arc<Server>, _status_request: SStatusRequest) {
self.send_packet(&CStatusResponse::new(&server.status_response_json));
}

pub fn handle_ping_request(&mut self, _server: &mut Server, ping_request: SStatusPingRequest) {
pub fn handle_ping_request(&mut self, _server: &Arc<Server>, ping_request: SStatusPingRequest) {
dbg!("ping");
self.send_packet(&CPingResponse::new(ping_request.payload));
self.close();
Expand All @@ -70,7 +72,7 @@ impl Client {
.all(|c| c > 32_u8 as char && c < 127_u8 as char)
}

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

if !Self::is_valid_player_name(&login_start.name) {
Expand Down Expand Up @@ -107,7 +109,7 @@ impl Client {

pub async fn handle_encryption_response(
&mut self,
server: &mut Server,
server: &Arc<Server>,
encryption_response: SEncryptionResponse,
) {
let shared_secret = server
Expand Down Expand Up @@ -185,14 +187,14 @@ impl Client {

pub fn handle_plugin_response(
&mut self,
_server: &mut Server,
_server: &Arc<Server>,
_plugin_response: SLoginPluginResponse,
) {
}

pub fn handle_login_acknowledged(
&mut self,
server: &mut Server,
server: &Arc<Server>,
_login_acknowledged: SLoginAcknowledged,
) {
self.connection_state = ConnectionState::Config;
Expand Down Expand Up @@ -227,7 +229,7 @@ impl Client {
}
pub fn handle_client_information_config(
&mut self,
_server: &mut Server,
_server: &Arc<Server>,
client_information: SClientInformationConfig,
) {
dbg!("got client settings");
Expand All @@ -243,7 +245,7 @@ impl Client {
});
}

pub fn handle_plugin_message(&mut self, _server: &mut Server, plugin_message: SPluginMessage) {
pub fn handle_plugin_message(&mut self, _server: &Arc<Server>, plugin_message: SPluginMessage) {
if plugin_message.channel.starts_with("minecraft:brand")
|| plugin_message.channel.starts_with("MC|Brand")
{
Expand All @@ -255,7 +257,7 @@ impl Client {
}
}

pub fn handle_known_packs(&mut self, server: &mut Server, _config_acknowledged: SKnownPacks) {
pub fn handle_known_packs(&mut self, server: &Arc<Server>, _config_acknowledged: SKnownPacks) {
for registry in &server.cached_registry {
self.send_packet(&CRegistryData::new(
&registry.registry_id,
Expand All @@ -270,7 +272,7 @@ impl Client {

pub async fn handle_config_acknowledged(
&mut self,
_server: &mut Server,
_server: &Arc<Server>,
_config_acknowledged: SAcknowledgeFinishConfig,
) {
dbg!("config acknowledged");
Expand Down
46 changes: 24 additions & 22 deletions pumpkin/src/client/container.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,12 @@ use pumpkin_world::item::ItemStack;
use std::sync::{Arc, Mutex};

impl Player {
pub fn open_container(&mut self, server: &mut Server, minecraft_menu_id: &str) {
pub fn open_container(&mut self, server: &Arc<Server>, minecraft_menu_id: &str) {
self.inventory.state_id = 0;
let total_opened_containers = self.inventory.total_opened_containers;
let mut container = self
.get_open_container(server)
let container = self.get_open_container(server);
let mut container = container
.as_ref()
.map(|container| container.lock().unwrap());
let menu_protocol_id = (*pumpkin_world::global_registry::REGISTRY
.get("minecraft:menu")
Expand Down Expand Up @@ -97,11 +98,12 @@ impl Player {

pub async fn handle_click_container(
&mut self,
server: &mut Server,
server: &Arc<Server>,
packet: SClickContainer,
) -> Result<(), InventoryError> {
let mut opened_container = self
.get_open_container(server)
let opened_container = self.get_open_container(server);
let mut opened_container = opened_container
.as_ref()
.map(|container| container.lock().unwrap());
let drag_handler = &server.drag_handler;

Expand Down Expand Up @@ -358,14 +360,19 @@ impl Player {
&mut self,
server: &Server,
) -> Vec<Arc<Mutex<Player>>> {
let player_ids = server
.open_containers
.get(&self.open_container.unwrap())
.unwrap()
.all_player_ids()
.into_iter()
.filter(|player_id| *player_id != self.entity_id())
.collect_vec();
let player_ids = {
let open_containers = server
.open_containers
.read()
.expect("open_containers is poisoned");
open_containers
.get(&self.open_container.unwrap())
.unwrap()
.all_player_ids()
.into_iter()
.filter(|player_id| *player_id != self.entity_id())
.collect_vec()
};
let player_token = self.client.token;

// TODO: Figure out better way to get only the players from player_ids
Expand Down Expand Up @@ -418,19 +425,14 @@ impl Player {

for player in players {
let mut player = player.lock().unwrap();
let mut container = player
.get_open_container(server)
.map(|container| container.lock().unwrap());
let container = player.get_open_container(server);
let mut container = container.as_ref().map(|v| v.lock().unwrap());
player.set_container_content(container.as_deref_mut());
drop(container)
}
Ok(())
}

pub fn get_open_container<'a>(
&self,
server: &'a Server,
) -> Option<&'a Mutex<Box<dyn Container>>> {
pub fn get_open_container(&self, server: &Server) -> Option<Arc<Mutex<Box<dyn Container>>>> {
if let Some(id) = self.open_container {
server.try_get_container(self.entity_id(), id)
} else {
Expand Down
5 changes: 3 additions & 2 deletions pumpkin/src/client/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::{
io::{self, Write},
net::SocketAddr,
sync::Arc,
};

use crate::{
Expand Down Expand Up @@ -148,7 +149,7 @@ impl Client {
Ok(())
}

pub async fn process_packets(&mut self, server: &mut Server) {
pub async fn process_packets(&mut self, server: &Arc<Server>) {
while let Some(mut packet) = self.client_packets_queue.pop() {
match self.handle_packet(server, &mut packet).await {
Ok(_) => {}
Expand All @@ -164,7 +165,7 @@ impl Client {
/// Handles an incoming decoded not Play state Packet
pub async fn handle_packet(
&mut self,
server: &mut Server,
server: &Arc<Server>,
packet: &mut RawPacket,
) -> Result<(), DeserializerError> {
// TODO: handle each packet's Error instead of calling .unwrap()
Expand Down
Loading

0 comments on commit 2ef1a13

Please sign in to comment.