Skip to content

Commit

Permalink
feat(network): - impl GameEvent and SetCenterChunk packets
Browse files Browse the repository at this point in the history
feat(entity): add UUID

- Add UUID field to EntityData and Player structs
  • Loading branch information
Liyze09 committed Oct 20, 2024
1 parent 7cacd44 commit afce34b
Show file tree
Hide file tree
Showing 14 changed files with 238 additions and 33 deletions.
95 changes: 88 additions & 7 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ serde_json = "1.0.131"
serde_derive = "1.0.210"
static-files = "0.2.4"
fastrand = "2.1.1"
nohash-hasher = "0.2.0"
mimalloc = "0.1.43"
rayon = "1.10.0"
parking_lot = "0.12.3"
Expand All @@ -37,6 +36,7 @@ tracing-subscriber = { version = "0.3.18" }
anyhow = "1.0.90"
thiserror = "1.0.64"
arc-swap = "1.7.1"
uuid = { version = "1.11.0", default-features = false, features = ["fast-rng", "v4"] }

[build-dependencies]
static-files = "0.2.4"
22 changes: 22 additions & 0 deletions crates/kernel/src/entity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::world::dimension::Dimension;
use crate::WORLD;
use downcast_rs::{impl_downcast, DowncastSync};
use std::sync::Arc;
use uuid::Uuid;

pub mod entity_manager;
pub mod player;
Expand Down Expand Up @@ -68,6 +69,7 @@ pub trait LivingEntity: Entity {

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct EntityData {
pub uuid: Uuid,
pub dimension: usize,
pub entity_id: i32,
pub portal_cooldown: i32,
Expand All @@ -80,6 +82,26 @@ pub struct EntityData {
impl EntityData {
pub fn new(entity_id: i32, dimension: usize, pos: (f64, f64, f64)) -> EntityData {
EntityData {
uuid: Uuid::new_v4(),
dimension,
entity_id,
portal_cooldown: 0,
pos,
velocity: (0.0, 0.0, 0.0),
on_ground: false,
yaw: 0.0,
pitch: 0.0,
}
}

pub fn with_uuid(
entity_id: i32,
uuid: Uuid,
dimension: usize,
pos: (f64, f64, f64),
) -> EntityData {
EntityData {
uuid,
dimension,
entity_id,
portal_cooldown: 0,
Expand Down
9 changes: 8 additions & 1 deletion crates/kernel/src/entity/entity_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use crate::world::dimension::Dimension;
use dashmap::DashMap;
use parking_lot::Mutex;
use std::sync::Arc;

pub struct EntityManager {
entities: DashMap<i32, Arc<Mutex<dyn Entity>>>,
}
Expand Down Expand Up @@ -37,6 +36,14 @@ impl EntityManager {
entities: self.entities.clone(),
}
}

pub fn generate_eid(&self) -> i32 {
let mut eid = fastrand::i32(i32::MIN..i32::MAX);
while self.entities.contains_key(&eid) {
eid = fastrand::i32(i32::MIN..i32::MAX);
}
eid
}
}

impl Default for EntityManager {
Expand Down
6 changes: 3 additions & 3 deletions crates/kernel/src/entity/player.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::entity::{Entity, EntityData, LivingEntity};
use crate::registry::protocol_id::get_protocol_id;
use crate::{impl_entity, impl_living_entity};
use tokio::sync::mpsc::UnboundedSender;
use uuid::Uuid;

pub struct Player {
pub health: f32,
Expand All @@ -20,11 +21,12 @@ impl Player {
dimension: usize,
tx: UnboundedSender<PlayerUpdate>,
pos: (f64, f64, f64),
uuid: Uuid,
) -> Player {
Player {
health: 20.0,
max_health: 20,
entity: EntityData::new(entity_id, dimension, pos),
entity: EntityData::with_uuid(entity_id, uuid, dimension, pos),
game_mode: 0,
previous_game_mode: -1,
death_location: None,
Expand All @@ -46,5 +48,3 @@ impl PartialEq<Self> for Player {
impl Eq for Player {}

pub struct PlayerUpdate {}
unsafe impl Send for PlayerUpdate {}
unsafe impl Sync for PlayerUpdate {}
36 changes: 26 additions & 10 deletions crates/kernel/src/gameplay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,34 @@ use crate::entity::player::Player;
use crate::entity::Entity;
use crate::network::connection::Connection;
use crate::network::connection::State::Play;
use crate::network::packet::s2c::play_login_s2c::PlayLoginS2C;
use crate::network::packet::s2c::synchronize_player_position::SynchronizePlayerPosition;
use crate::network::packet::s2c::game_event::{GameEvent, GameEventS2C};
use crate::network::packet::s2c::play_login::PlayLoginS2C;
use crate::network::packet::s2c::set_center_chunk::SetCenterChunkS2C;
use crate::network::packet::s2c::synchronize_player_position::SynchronizePlayerPositionS2C;
use crate::WORLD;
use fastrand::i32;
use parking_lot::Mutex;
use std::sync::Arc;
use tokio::sync::mpsc::unbounded_channel;
use uuid::Uuid;

pub(crate) async fn player_join(connection: &mut Connection<'_>) -> anyhow::Result<()> {
let mut eid;
let eid;
let arc: Arc<Mutex<Player>>;
let (chunk_x, chunk_z);
{
let wsp = WORLD.get_world_spawn_point();
eid = i32(i32::MIN..i32::MAX);
while WORLD.entities.get_mut(eid).is_some() {
eid = i32(i32::MIN..i32::MAX);
}
eid = WORLD.entities.generate_eid();
let (tx, recv) = unbounded_channel();
let player = Player::new(eid, wsp.0, tx, (wsp.1 as f64, wsp.2 as f64, wsp.3 as f64));
let player = Player::new(
eid,
wsp.0,
tx,
(wsp.1 as f64, wsp.2 as f64, wsp.3 as f64),
Uuid::from_u128(connection.uuid.unwrap()),
);
connection.recv = Some(recv);
chunk_x = player.entity.pos.0 as i32 >> 4;
chunk_z = player.entity.pos.2 as i32 >> 4;
arc = Arc::new(Mutex::new(player));
connection.player = Some(arc.clone());
WORLD
Expand All @@ -30,7 +38,15 @@ pub(crate) async fn player_join(connection: &mut Connection<'_>) -> anyhow::Resu
}
connection.player_eid = Some(eid);
connection.send_packet(&PlayLoginS2C).await?;
connection.send_packet(&SynchronizePlayerPosition).await?;
connection
.send_packet(&GameEventS2C::empty(GameEvent::StartWaitingForLevelChunks))
.await?;
connection
.send_packet(&SynchronizePlayerPositionS2C)
.await?;
connection
.send_packet(&SetCenterChunkS2C { chunk_x, chunk_z })
.await?;
connection.state = Play;
Ok(())
}
4 changes: 2 additions & 2 deletions crates/kernel/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ pub mod config;
pub mod entity;
pub mod gameplay;
pub mod item;
pub(crate) mod network;
pub mod network;
pub mod registry;
mod test;
pub mod util;
Expand Down Expand Up @@ -40,7 +40,7 @@ pub const PROTOCOL_VERSION: i32 = 767;
pub const MINECRAFT_VERSION: &str = "1.21"; // 1.21 - 1.21.1 ( Protocol 767 )
include!(concat!(env!("OUT_DIR"), "/generated.rs"));
pub static GENERATED: LazyLock<HashMap<&'static str, Resource>> = LazyLock::new(generate);
pub static WORLD: LazyLock<world::World> = LazyLock::new(|| world::World::new());
pub static WORLD: LazyLock<world::World> = LazyLock::new(world::World::new);
#[tokio::main]
#[instrument]
async fn main() {
Expand Down
8 changes: 4 additions & 4 deletions crates/kernel/src/network/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ pub(crate) async fn read_socket(socket: &mut TcpStream) -> Result<()> {
}
}
}
pub(crate) struct Connection<'a> {
pub struct Connection<'a> {
pub stream: &'a mut TcpStream,
pub state: State,
pub username: Option<String>,
Expand All @@ -76,12 +76,12 @@ pub(crate) struct Connection<'a> {
pub recv: Option<UnboundedReceiver<PlayerUpdate>>,
}

pub(crate) enum ChatMode {
pub enum ChatMode {
Enabled,
CommandsOnly,
Hidden,
}
pub(crate) enum MainHand {
pub enum MainHand {
Left,
Right,
}
Expand All @@ -105,7 +105,7 @@ impl Connection<'_> {
recv: None,
}
}
pub(crate) async fn send_packet<D: Encode>(&mut self, data: &D) -> Result<()> {
pub async fn send_packet<D: Encode>(&mut self, data: &D) -> Result<()> {
let mut buf = Vec::new();
buf.write_var_int(data.get_id()).await?;
data.encode(self, &mut buf).await?;
Expand Down
5 changes: 3 additions & 2 deletions crates/kernel/src/network/packet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,19 @@ use anyhow::Result;
use arc_swap::ArcSwap;
use async_trait::async_trait;
use hashbrown::HashMap;
use std::future::Future;
use std::sync::{Arc, LazyLock};
use tokio::io::AsyncWrite;

pub mod c2s;
pub mod s2c;

pub trait Encode {
async fn encode<W: AsyncWrite + Unpin>(
fn encode<W: AsyncWrite + Unpin>(
&self,
connection: &mut Connection<'_>,
buf: &mut W,
) -> Result<()>;
) -> impl Future<Output = Result<()>>;
fn get_id(&self) -> i32;
}

Expand Down
Loading

0 comments on commit afce34b

Please sign in to comment.