Add Multiplayer support

This commit is contained in:
Snowiiii committed 2024-08-06 16:19:03 +02:00
1 parent d1c3b2f10c
commit 32569bafe5
34 files changed
+445 -243

No files matched your search

+154 -78
View File
@@ -1,5 +1,6 @@
use std::{
cell::RefCell,
collections::HashMap,
io::Cursor,
rc::Rc,
sync::atomic::{AtomicI32, Ordering},
@@ -8,13 +9,17 @@ use std::{
use base64::{engine::general_purpose, Engine};
use mio::{event::Event, Poll, Token};
use num_traits::ToPrimitive;
use pumpkin_entity::{entity_type::EntityType, EntityId};
use pumpkin_protocol::{
client::{
config::CPluginMessage,
play::{CChunkDataUpdateLight, CGameEvent, CLogin, CPlayerInfoUpdate, PlayerAction},
play::{
CChunkDataUpdateLight, CGameEvent, CLogin, CPlayerAbilities, CPlayerInfoUpdate,
CSpawnEntity, PlayerAction,
},
},
BitSet, ClientPacket, PacketError, Players, Sample, StatusResponse, VarInt, VarInt32, Version,
CURRENT_MC_PROTOCOL,
BitSet, ClientPacket, Players, Sample, StatusResponse, VarInt,
Version, CURRENT_MC_PROTOCOL,
};
use pumpkin_world::chunk::TestChunk;
use rsa::{rand_core::OsRng, traits::PublicKeyParts, RsaPrivateKey, RsaPublicKey};
@@ -23,10 +28,7 @@ use serde::{Deserialize, Serialize};
use crate::{
client::Client,
configuration::{AdvancedConfiguration, BasicConfiguration},
entity::{
player::{GameMode, Player},
Entity, EntityId,
},
entity::player::{GameMode, Player},
};
pub const CURRENT_MC_VERSION: &str = "1.21";
@@ -47,7 +49,7 @@ pub struct Server {
/// Cache the Server brand buffer so we don't have to rebuild them every time a player joins
pub cached_server_brand: Vec<u8>,
// pub current_clients: HashMap<Rc<Token>, Rc<RefCell<Client>>>,
pub current_clients: HashMap<Rc<Token>, Rc<RefCell<Client>>>,
// todo replace with HashMap <World, Player>
entity_id: AtomicI32, // todo: place this into every world
@@ -90,7 +92,7 @@ impl Server {
status_response,
status_response_json,
public_key_der,
// current_clients: HashMap::new(),
current_clients: HashMap::new(),
base_config: config.0,
auth_client,
advanced_config: config.1,
@@ -103,114 +105,188 @@ impl Server {
client.poll(self, event)
}
pub fn add_client(&mut self, _token: Rc<Token>, _client: Rc<RefCell<Client>>) {
// self.current_clients.insert(token, client);
pub fn add_client(&mut self, token: Rc<Token>, client: Rc<RefCell<Client>>) {
self.current_clients.insert(token, client);
}
pub fn remove_client(&mut self, _token: &Token) {
// self.current_clients.remove(token);
pub fn remove_client(&mut self, token: &Token) {
self.current_clients.remove(token);
}
// here is where the magic happens
// todo: do this in a world
pub fn spawn_player(&mut self, client: &mut Client) {
// This code follows the vanilla packet order
dbg!("spawning player");
let entity_id = self.new_entity_id();
let player = Player::new(Entity { entity_id });
let player = Player::new(entity_id);
client.player = Some(player);
client
.send_packet(CLogin::new(
entity_id,
self.base_config.hardcore,
vec!["minecraft:overworld".into()],
self.base_config.max_players as VarInt,
self.base_config.view_distance as VarInt, // view distance todo
self.base_config.simulation_distance as VarInt, // sim view dinstance todo
false,
false,
false,
0,
"minecraft:overworld".into(),
0, // seed
match self.base_config.default_gamemode {
GameMode::Undefined => GameMode::Survival,
game_mode => game_mode,
}
.to_u8()
.unwrap(),
self.base_config.default_gamemode.to_i8().unwrap(),
false,
false,
false, // deth loc
None,
None,
0,
false,
))
.unwrap_or_else(|e| client.kick(&e.to_string()));
// login packet for our new player
client.send_packet(CLogin::new(
entity_id,
self.base_config.hardcore,
vec!["minecraft:overworld".into()],
self.base_config.max_players.into(),
self.base_config.view_distance.into(), // view distance todo
self.base_config.simulation_distance.into(), // sim view dinstance todo
false,
false,
false,
0.into(),
"minecraft:overworld".into(),
0, // seed
match self.base_config.default_gamemode {
GameMode::Undefined => GameMode::Survival,
game_mode => game_mode,
}
.to_u8()
.unwrap(),
self.base_config.default_gamemode.to_i8().unwrap(),
false,
false,
false, // deth loc
None,
None,
0.into(),
false,
));
// player abilities
client.send_packet(CPlayerAbilities::new(0x02, 00.2, 0.1));
// teleport
client.teleport(10.0, 500.0, 10.0, 10.0, 10.0);
let x = 10.0;
let y = 500.0;
let z = 10.0;
client.teleport(x, y, z, 10.0, 10.0);
let gameprofile = client.gameprofile.as_ref().unwrap();
// first send info update to our new player, So he can see his Skin
// TODO: send more actions, (chat. list, ping)
client
.send_packet(CPlayerInfoUpdate::new(
client.send_packet(CPlayerInfoUpdate::new(
0x01,
&[pumpkin_protocol::client::play::Player {
uuid: gameprofile.id,
actions: vec![PlayerAction::AddPlayer {
name: gameprofile.name.clone(),
properties: gameprofile.properties.clone(),
}],
}],
));
let gameprofile = client.gameprofile.as_ref().unwrap();
// send his info to everyone else
self.broadcast_packet(
client,
CPlayerInfoUpdate::new(
0x01,
&[pumpkin_protocol::client::play::Player {
uuid: gameprofile.id,
actions: &[PlayerAction::AddPlayer {
actions: vec![PlayerAction::AddPlayer {
name: gameprofile.name.clone(),
properties: gameprofile.properties.clone(),
}],
}],
))
.unwrap_or_else(|e| client.kick(&e.to_string()));
// TODO: Now we send this to all other client
),
);
// here we send all the infos of already joined players
let mut entries = Vec::new();
for (_, client) in self.current_clients.iter().filter(|c| c.0 != &client.token) {
let client = client.borrow();
if client.is_player() {
let gameprofile = client.gameprofile.as_ref().unwrap();
entries.push(pumpkin_protocol::client::play::Player {
uuid: gameprofile.id,
actions: vec![PlayerAction::AddPlayer {
name: gameprofile.name.clone(),
properties: gameprofile.properties.clone(),
}],
})
}
}
client.send_packet(CPlayerInfoUpdate::new(0x01, &entries));
// Start waiting for level chunks
client
.send_packet(CGameEvent::new(13, 0.0))
.unwrap_or_else(|e| client.kick(&e.to_string()));
client.send_packet(CGameEvent::new(13, 0.0));
let gameprofile = client.gameprofile.as_ref().unwrap();
// spawn player for every client
self.broadcast_packet(
client,
CSpawnEntity::new(
entity_id.into(),
gameprofile.id,
EntityType::Player.to_i32().unwrap().into(),
x,
y,
z,
0,
0,
0,
0.into(),
0,
0,
0,
),
);
// spawn players for our client
let token = client.token.clone();
for (_, existing_client) in self.current_clients.iter().filter(|c| c.0 != &token) {
let existing_client = existing_client.borrow();
if let Some(player) = &existing_client.player {
let gameprofile = existing_client.gameprofile.as_ref().unwrap();
client.send_packet(CSpawnEntity::new(
player.entity_id().into(),
gameprofile.id,
EntityType::Player.to_i32().unwrap().into(),
x,
y,
z,
0,
0,
0,
0.into(),
0,
0,
0,
))
}
}
// Server::spawn_test_chunk(client);
}
/// Sends a Packet to all Players
fn _broadcast_packet<P>(&mut self, _packet: P) -> Result<(), PacketError>
fn broadcast_packet<P>(&mut self, from: &Client, packet: P)
where
P: ClientPacket,
P: Clone,
{
/* for client in self.current_clients.values() {
for (_, client) in self.current_clients.iter().filter(|c| c.0 != &from.token) {
// Check if client is a player
if client.borrow().is_player() {
let mut client = client.borrow_mut();
if client.is_player() {
// we need to clone, Because we send a new packet to every client
client.borrow_mut().send_packet(packet.clone())?;
client.send_packet(packet.clone());
}
}
*/
Ok(())
}
// todo: do this in a world
fn _spawn_test_chunk(client: &mut Client) {
let test_chunk = TestChunk::new();
client
.send_packet(CChunkDataUpdateLight::new(
10,
10,
test_chunk.heightmap,
Vec::new(),
Vec::new(),
BitSet(0, Vec::new()),
BitSet(0, Vec::new()),
BitSet(0, Vec::new()),
Vec::new(),
Vec::new(),
))
.unwrap_or_else(|e| client.kick(&e.to_string()))
client.send_packet(CChunkDataUpdateLight::new(
10,
10,
test_chunk.heightmap,
Vec::new(),
Vec::new(),
BitSet(0.into(), Vec::new()),
BitSet(0.into(), Vec::new()),
BitSet(0.into(), Vec::new()),
Vec::new(),
Vec::new(),
));
}
// move to world
@@ -221,17 +297,17 @@ impl Server {
pub fn build_brand() -> Vec<u8> {
let brand = "Pumpkin";
let mut buf = vec![];
let _ = VarInt32(brand.len() as i32).encode(&mut buf);
let _ = VarInt(brand.len() as i32).encode(&mut buf);
buf.extend_from_slice(brand.as_bytes());
buf
}
pub fn send_brand(&self, client: &mut Client) -> Result<(), PacketError> {
pub fn send_brand(&self, client: &mut Client) {
// send server brand
client.send_packet(CPluginMessage::new(
"minecraft:brand",
&self.cached_server_brand,
))
));
}
pub fn build_response(config: &BasicConfiguration) -> StatusResponse {