Skip to content

Commit

Permalink
Merge pull request #115 from ferrumc-rs/fix/state_in_seperate_crate
Browse files Browse the repository at this point in the history
  • Loading branch information
ReCore-sys authored Dec 1, 2024
2 parents b1a9394 + d2a8e18 commit abe285d
Show file tree
Hide file tree
Showing 39 changed files with 125 additions and 86 deletions.
13 changes: 11 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,23 @@ resolver = "2"
#================= Members =================#
members = [
"src/bin",
"src/lib/adapters/anvil",
"src/lib/adapters/mca",
"src/lib/adapters/nbt",
"src/lib/core",
"src/lib/core/state",
"src/lib/derive_macros",
"src/lib/ecs",
"src/lib/events",
"src/lib/net",
"src/lib/net/crates/encryption",
"src/lib/net/crates/codec",
"src/lib/net/crates/encryption",
"src/lib/plugins",
"src/lib/storage",
"src/lib/utils", "src/lib/utils/logging", "src/lib/utils/profiling", "src/lib/utils/general_purpose",
"src/lib/utils",
"src/lib/utils/general_purpose",
"src/lib/utils/logging",
"src/lib/utils/profiling",
"src/lib/world",
"src/lib/derive_macros",
"src/lib/adapters/nbt", "src/lib/adapters/mca",
Expand Down Expand Up @@ -85,6 +93,7 @@ ferrumc-world = { path = "src/lib/world" }
ferrumc-nbt = { path = "src/lib/adapters/nbt" }
ferrumc-anvil = { path = "src/lib/adapters/anvil" }
ferrumc-tests = { path = "src/tests" }
ferrumc-state = { path = "src/lib/core/state"}


# Asynchronous
Expand Down
1 change: 1 addition & 0 deletions src/bin/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ ferrumc-world = { workspace = true }
ferrumc-macros = { workspace = true }
ferrumc-nbt = { workspace = true }
ferrumc-general-purpose = { workspace = true }
ferrumc-state = { workspace = true }

ctor = { workspace = true }
parking_lot = { workspace = true }
Expand Down
2 changes: 1 addition & 1 deletion src/bin/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use ferrumc_config::statics::get_global_config;
use ferrumc_ecs::Universe;
use ferrumc_general_purpose::paths::get_root_path;
use ferrumc_net::server::create_server_listener;
use ferrumc_net::ServerState;
use ferrumc_state::ServerState;
use ferrumc_world::World;
use std::sync::Arc;
use systems::definition;
Expand Down
2 changes: 1 addition & 1 deletion src/bin/src/packet_handlers/handshake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use ferrumc_net::connection::ConnectionState;
use ferrumc_net::errors::NetError::{Packet};
use ferrumc_net::errors::{NetError, PacketError};
use ferrumc_net::packets::incoming::handshake::HandshakeEvent;
use ferrumc_net::GlobalState;
use ferrumc_state::GlobalState;
use tracing::{error, trace};
use ferrumc_ecs::errors::ECSError;
use ferrumc_net::utils::ecs_helpers::EntityExt;
Expand Down
2 changes: 1 addition & 1 deletion src/bin/src/packet_handlers/login_process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use ferrumc_net::packets::outgoing::set_render_distance::SetRenderDistance;
use ferrumc_net::packets::outgoing::registry_data::get_registry_packets;
use ferrumc_net::packets::outgoing::set_default_spawn_position::SetDefaultSpawnPositionPacket;
use ferrumc_net::packets::outgoing::synchronize_player_position::SynchronizePlayerPositionPacket;
use ferrumc_net::GlobalState;
use ferrumc_state::GlobalState;
use ferrumc_net_codec::encode::NetEncodeOpts;
use tracing::{debug, trace};
use ferrumc_core::transform::grounded::OnGround;
Expand Down
13 changes: 6 additions & 7 deletions src/bin/src/packet_handlers/tick_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,11 @@ use ferrumc_net::errors::NetError;
use ferrumc_net::packets::outgoing::update_time::TickEvent;
use ferrumc_net::packets::outgoing::update_time::UpdateTimePacket;
use ferrumc_net::utils::broadcast::{BroadcastOptions, BroadcastToAll};
use ferrumc_net::GlobalState;
use ferrumc_state::GlobalState;
use tracing::warn;

#[event_handler]
async fn handle_tick(
event: TickEvent,
state: GlobalState,
) -> Result<TickEvent, NetError> {
async fn handle_tick(event: TickEvent, state: GlobalState) -> Result<TickEvent, NetError> {
// info!("Tick {} ", event.tick);
// TODO: Handle tick in terms of game logic here
// this should call a function in world which handles the world state and calls the appropriate events which send their respective packets
Expand All @@ -36,9 +33,11 @@ async fn handle_tick(
})
.collect::<Vec<_>>();


tokio::spawn(async move {
if let Err(e) = state.broadcast(&packet, BroadcastOptions::default().only(entities)).await {
if let Err(e) = state
.broadcast(&packet, BroadcastOptions::default().only(entities))
.await
{
warn!("Failed to broadcast tick packet: {:?}", e);
}
});
Expand Down
18 changes: 5 additions & 13 deletions src/bin/src/packet_handlers/transform/update_player_position.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ use ferrumc_core::transform::position::Position;
use ferrumc_core::transform::rotation::Rotation;
use ferrumc_macros::event_handler;
use ferrumc_net::errors::NetError;
use ferrumc_net::utils::ecs_helpers::EntityExt;
use ferrumc_net::GlobalState;
use ferrumc_net::packets::packet_events::TransformEvent;
use ferrumc_net::utils::ecs_helpers::EntityExt;
use ferrumc_state::GlobalState;

#[event_handler]
async fn handle_player_move(
Expand All @@ -16,21 +16,13 @@ async fn handle_player_move(
if let Some(ref new_position) = event.position {
let mut position = conn_id.get_mut::<Position>(&state)?;

*position = Position::new(
new_position.x,
new_position.y,
new_position.z,
);
*position = Position::new(new_position.x, new_position.y, new_position.z);
}

if let Some(ref new_rotation) = event.rotation {
let mut rotation = conn_id.get_mut::<Rotation>(&state)?;

*rotation = Rotation::new(
new_rotation.yaw,
new_rotation.pitch,
);

*rotation = Rotation::new(new_rotation.yaw, new_rotation.pitch);
}

if let Some(new_grounded) = event.on_ground {
Expand All @@ -40,4 +32,4 @@ async fn handle_player_move(
}

Ok(event)
}
}
2 changes: 1 addition & 1 deletion src/bin/src/systems/chunk_sender.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ use ferrumc_core::transform::position::Position;
use ferrumc_net::connection::StreamWriter;
use ferrumc_net::packets::outgoing::chunk_and_light_data::ChunkAndLightData;
use ferrumc_net::packets::outgoing::set_center_chunk::SetCenterChunk;
use ferrumc_net::GlobalState;
use ferrumc_net_codec::encode::NetEncodeOpts;
use ferrumc_state::GlobalState;
use std::ops::Div;
use std::simd::num::SimdFloat;
use std::simd::{f64x2, StdFloat};
Expand Down
3 changes: 2 additions & 1 deletion src/bin/src/systems/definition.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ use crate::systems::keep_alive_system::KeepAliveSystem;
use crate::systems::tcp_listener_system::TcpListenerSystem;
use crate::systems::ticking_system::TickingSystem;
use async_trait::async_trait;
use ferrumc_net::{GlobalState, NetResult};
use ferrumc_net::{NetResult};
use ferrumc_state::GlobalState;
use futures::stream::FuturesUnordered;
use std::sync::{Arc, LazyLock};
use tracing::{debug, debug_span, info, Instrument};
Expand Down
18 changes: 14 additions & 4 deletions src/bin/src/systems/keep_alive_system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use ferrumc_net::packets::incoming::keep_alive::IncomingKeepAlivePacket;
use ferrumc_net::packets::outgoing::keep_alive::OutgoingKeepAlivePacket;
use ferrumc_net::utils::broadcast::{BroadcastOptions, BroadcastToAll};
use ferrumc_net::utils::state::terminate_connection;
use ferrumc_net::GlobalState;
use ferrumc_state::GlobalState;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use tracing::{error, info, trace, warn};
Expand Down Expand Up @@ -49,7 +49,10 @@ impl System for KeepAliveSystem {
.into_iter()
.filter_map(|entity| {
let conn_state = state.universe.get::<ConnectionState>(entity).ok()?;
let keep_alive = state.universe.get_mut::<IncomingKeepAlivePacket>(entity).ok()?;
let keep_alive = state
.universe
.get_mut::<IncomingKeepAlivePacket>(entity)
.ok()?;

if matches!(*conn_state, ConnectionState::Play)
&& (current_time - keep_alive.timestamp) >= 15000
Expand Down Expand Up @@ -87,7 +90,9 @@ impl System for KeepAliveSystem {
}
}
}
let packet = OutgoingKeepAlivePacket { timestamp: current_time };
let packet = OutgoingKeepAlivePacket {
timestamp: current_time,
};

let broadcast_opts = BroadcastOptions::default()
.only(entities)
Expand All @@ -106,7 +111,12 @@ impl System for KeepAliveSystem {
});

if let Err(e) = state
.broadcast(&OutgoingKeepAlivePacket { timestamp: current_time }, broadcast_opts)
.broadcast(
&OutgoingKeepAlivePacket {
timestamp: current_time,
},
broadcast_opts,
)
.await
{
error!("Error sending keep alive packet: {}", e);
Expand Down
2 changes: 1 addition & 1 deletion src/bin/src/systems/tcp_listener_system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::sync::Arc;
use async_trait::async_trait;
use tracing::{debug, error, info, info_span, Instrument};
use ferrumc_net::connection::handle_connection;
use ferrumc_net::GlobalState;
use ferrumc_state::GlobalState;
use crate::systems::definition::System;
use crate::Result;

Expand Down
2 changes: 1 addition & 1 deletion src/bin/src/systems/ticking_system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::systems::definition::System;
use async_trait::async_trait;
use ferrumc_events::infrastructure::Event;
use ferrumc_net::packets::outgoing::update_time::TickEvent;
use ferrumc_net::GlobalState;
use ferrumc_state::GlobalState;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
Expand Down
2 changes: 2 additions & 0 deletions src/lib/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,5 @@ edition = "2021"

[dependencies]
thiserror = { workspace = true }
tokio = { workspace = true}
ferrumc-ecs = {workspace = true}
3 changes: 2 additions & 1 deletion src/lib/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ pub mod errors;

// Core structs/types. Usually used in ECS Components.
pub mod transform;
pub mod identity;
pub mod identity;
pub mod state;
Empty file added src/lib/core/src/state.rs
Empty file.
9 changes: 9 additions & 0 deletions src/lib/core/state/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[package]
name = "ferrumc-state"
version = "0.1.0"
edition = "2021"

[dependencies]
tokio = { workspace = true }
ferrumc-ecs = { workspace = true }
ferrumc-world = { workspace = true }
11 changes: 11 additions & 0 deletions src/lib/core/state/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
use ferrumc_ecs::Universe;
use ferrumc_world::World;
use std::sync::Arc;
use tokio::net::TcpListener;
pub struct ServerState {
pub universe: Universe,
pub tcp_listener: TcpListener,
pub world: World,
}

pub type GlobalState = Arc<ServerState>;
2 changes: 1 addition & 1 deletion src/lib/derive_macros/src/events/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ pub(crate) fn derive(input: TokenStream) -> TokenStream {
let output = quote! {
impl ::ferrumc_events::infrastructure::Event for #name {
type Data = Self;
type State = #net_crate::GlobalState;
type State = ferrumc_state::GlobalState;
type Error = #net_crate::errors::NetError;

fn name() -> &'static str {
Expand Down
2 changes: 1 addition & 1 deletion src/lib/derive_macros/src/net/packets/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ pub fn bake_registry(input: TokenStream) -> TokenStream {
let match_arms = match_arms.into_iter();

let output = quote! {
pub async fn handle_packet<R: std::io::Read>(packet_id: u8, conn_id: usize, conn_state: &crate::connection::ConnectionState, cursor: &mut R, state: std::sync::Arc<crate::ServerState>) -> crate::NetResult<()> {
pub async fn handle_packet<R: std::io::Read>(packet_id: u8, conn_id: usize, conn_state: &crate::connection::ConnectionState, cursor: &mut R, state: std::sync::Arc<ferrumc_state::ServerState>) -> crate::NetResult<()> {
match (packet_id, conn_state.as_str()) {
#(#match_arms)*
_ => tracing::debug!("No packet found for ID: 0x{:02X} in state: {}", packet_id, conn_state.as_str()),
Expand Down
1 change: 1 addition & 0 deletions src/lib/net/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,4 @@ rand = { workspace = true }
uuid = { workspace = true, features = ["v4"] }
async-trait = { workspace = true }
byteorder = { workspace = true }
ferrumc-state = { workspace = true }
3 changes: 2 additions & 1 deletion src/lib/net/src/connection.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use crate::packets::incoming::packet_skeleton::PacketSkeleton;
use crate::utils::state::terminate_connection;
use crate::{handle_packet, NetResult, ServerState};
use crate::{handle_packet, NetResult};
use ferrumc_net_codec::encode::NetEncode;
use ferrumc_net_codec::encode::NetEncodeOpts;
use ferrumc_state::ServerState;
use std::sync::Arc;
use std::time::Duration;
use tokio::net::tcp::{OwnedReadHalf, OwnedWriteHalf};
Expand Down
10 changes: 0 additions & 10 deletions src/lib/net/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
#![feature(portable_simd)]
extern crate core;

use tokio::net::TcpListener;
use ferrumc_ecs::Universe;
use ferrumc_macros::bake_packet_registry;
use std::sync::{Arc};
use ferrumc_world::World;

pub mod connection;
pub mod errors;
Expand All @@ -14,13 +10,7 @@ pub mod server;
pub mod utils;
pub type NetResult<T> = Result<T, errors::NetError>;

pub struct ServerState {
pub universe: Universe,
pub tcp_listener: TcpListener,
pub world: World
}

pub type GlobalState = Arc<ServerState>;


bake_packet_registry!("\\src\\packets\\incoming");
9 changes: 5 additions & 4 deletions src/lib/net/src/packets/incoming/ack_finish_configuration.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use crate::packets::IncomingPacket;
use crate::{NetResult, ServerState};
use crate::NetResult;
use ferrumc_state::ServerState;
use ferrumc_events::infrastructure::Event;
use ferrumc_macros::{packet, Event, NetDecode};
use std::sync::Arc;
use ferrumc_events::infrastructure::Event;

#[derive(NetDecode)]
#[packet(packet_id = 0x03, state = "configuration")]
Expand All @@ -11,9 +12,9 @@ pub struct AckFinishConfigurationPacket {}
impl IncomingPacket for AckFinishConfigurationPacket {
async fn handle(self, conn_id: usize, state: Arc<ServerState>) -> NetResult<()> {
let event = AckFinishConfigurationEvent::new(self, conn_id);

tokio::spawn(AckFinishConfigurationEvent::trigger(event, state));

Ok(())
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/lib/net/src/packets/incoming/client_information.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use std::sync::Arc;
use tracing::debug;
use ferrumc_state::ServerState;
use ferrumc_macros::{packet, NetDecode};
use ferrumc_net_codec::net_types::var_int::VarInt;
use crate::packets::IncomingPacket;
use crate::{NetResult, ServerState};
use crate::NetResult;

#[derive(Debug, NetDecode)]
#[packet(packet_id = 0x00, state = "configuration")]
Expand Down
2 changes: 1 addition & 1 deletion src/lib/net/src/packets/incoming/handshake.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::packets::IncomingPacket;
use crate::{NetResult, ServerState};
use crate::NetResult; use ferrumc_state::ServerState;
use ferrumc_events::infrastructure::Event;
use ferrumc_macros::{packet, Event, NetDecode};
use ferrumc_net_codec::net_types::var_int::VarInt;
Expand Down
6 changes: 4 additions & 2 deletions src/lib/net/src/packets/incoming/keep_alive.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use crate::packets::outgoing::keep_alive::OutgoingKeepAlivePacket;
use crate::packets::IncomingPacket;
use crate::utils::state::terminate_connection;
use crate::{NetResult, ServerState};
use crate::NetResult;
use ferrumc_macros::{packet, NetDecode};
use ferrumc_state::ServerState;
use std::sync::Arc;
use tracing::debug;

Expand All @@ -26,7 +27,8 @@ impl IncomingPacket for IncomingKeepAlivePacket {
debug!("Error terminating connection: {:?}", e);
}
} else {
let mut last_rec_keep_alive = state.universe.get_mut::<IncomingKeepAlivePacket>(conn_id)?;
let mut last_rec_keep_alive =
state.universe.get_mut::<IncomingKeepAlivePacket>(conn_id)?;
*last_rec_keep_alive = self;
}

Expand Down
2 changes: 1 addition & 1 deletion src/lib/net/src/packets/incoming/login_acknowledged.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::sync::Arc;
use ferrumc_macros::{Event, NetDecode, packet};
use ferrumc_events::infrastructure::Event;
use crate::packets::IncomingPacket;
use crate::{NetResult, ServerState};
use crate::NetResult; use ferrumc_state::ServerState;

#[derive(Debug, NetDecode)]
#[packet(packet_id = 0x03, state = "login")]
Expand Down
Loading

0 comments on commit abe285d

Please sign in to comment.