Skip to content

Commit

Permalink
Added new_packet.py and some fixed/removed other things.
Browse files Browse the repository at this point in the history
  • Loading branch information
Sweattypalms committed Dec 30, 2024
1 parent 02cb156 commit c5eb15c
Show file tree
Hide file tree
Showing 6 changed files with 79 additions and 64 deletions.
64 changes: 64 additions & 0 deletions scripts/new_packet.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import os.path

incoming_template = """
use crate::packets::IncomingPacket;
use crate::NetResult;
use ferrumc_macros::{packet, NetDecode};
use ferrumc_state::ServerState;
use std::sync::Arc;
#[derive(NetDecode)]
#[packet(packet_id = ++id++, state = "play")]
pub struct ++name++ {
}
impl IncomingPacket for ++name++ {
async fn handle(self, conn_id: usize, state: Arc<ServerState>) -> NetResult<()> {
todo!()
}
}
"""

outgoing_template = """
use ferrumc_macros::{packet, NetEncode};\
use std::io::Write;
#[derive(NetEncode)]
#[packet(packet_id = ++id++)]
pub struct ++name++ {}
"""


def to_snake_case(string) -> str:
return string.lower().replace(" ", "_")


def to_camel_case(string) -> str:
return string.title().replace(" ", "")


packet_type_input = input("Incoming or outgoing packet? (i/o): ")
packet_type = ""
if packet_type_input == "i":
packet_type = "incoming"
elif packet_type_input == "o":
packet_type = "outgoing"
else:
print("Invalid input")
exit()

packet_name = input("Packet name: ")
packets_dir = os.path.join(os.path.join(os.path.dirname(__file__), ".."), "src/lib/net/src/packets")

packet_id = input("Packet ID (formatted like 0x01): ")
packet_id = packet_id[:-2] + packet_id[-2:].upper()

with open(f"{packets_dir}/{packet_type}/{to_snake_case(packet_name)}.rs", "x") as f:
if packet_type == "incoming":
f.write(incoming_template.replace("++name++", to_camel_case(packet_name)).replace("++id++", packet_id))
with open(f"{packets_dir}/incoming/mod.rs", "a") as modfile:
modfile.write(f"\npub mod {to_snake_case(packet_name)};")
else:
f.write(outgoing_template.replace("++name++", to_camel_case(packet_name)).replace("++id++", packet_id))
with open(f"{packets_dir}/outgoing/mod.rs", "a") as modfile:
modfile.write(f"\npub mod {to_snake_case(packet_name)};")
6 changes: 3 additions & 3 deletions src/bin/src/systems/chunk_fetcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::collections::HashMap;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use tokio::task::JoinSet;
use tracing::{error, info, trace};
use tracing::{debug, info, trace};

pub struct ChunkFetcher {
stop: AtomicBool,
Expand Down Expand Up @@ -70,11 +70,11 @@ impl System for ChunkFetcher {
match result {
Ok(task_res) => {
if let Err(e) = task_res {
error!("Error fetching chunk: {:?}", e);
debug!("Error fetching chunk: {:?}", e);
}
}
Err(e) => {
error!("Error fetching chunk: {:?}", e);
debug!("Error fetching chunk: {:?}", e);
}
}
}
Expand Down
12 changes: 9 additions & 3 deletions src/bin/src/systems/ticking_system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
use tokio::time::Instant;
use tracing::{debug, info};
use tracing::{debug, info, trace};
pub struct TickingSystem;

static KILLED: AtomicBool = AtomicBool::new(false);
Expand All @@ -19,12 +19,18 @@ impl System for TickingSystem {
let mut tick = 0;
while !KILLED.load(Ordering::Relaxed) {
let required_end = Instant::now() + Duration::from_millis(50);
// TODO handle error
let res = TickEvent::trigger(TickEvent::new(tick), state.clone()).await;
let res = {
let start = Instant::now();
let res = TickEvent::trigger(TickEvent::new(tick), state.clone()).await;
trace!("Tick took {:?}", Instant::now() - start);

res
};
if res.is_err() {
debug!("error handling tick event: {:?}", res);
}
let now = Instant::now();

if required_end > now {
tokio::time::sleep(required_end - now).await;
} else {
Expand Down
56 changes: 0 additions & 56 deletions src/lib/events/src/infrastructure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,62 +99,6 @@ pub trait Event: Sized + Send + Sync + 'static {
Ok(())
}

/*/// Trigger the execution of an event with concurrency support
///
/// If the event structure supports cloning. This method can be used to execute
/// listeners of the same priority concurrently (using tokio::task). This imply a
/// cloning cost at each listener execution. See `Event::trigger` for a more
/// efficient but more linear approach.
///
/// # Mutability policy
///
/// The listeners having the same priority being runned concurrently, there are no
/// guarantees in the order of mutation of the event data.
///
/// It is recommended to ensure listeners of the same priority exclusively update fields
/// in the event data that are untouched by other listeners of the same group.
async fn trigger_concurrently(event: Self::Data) -> Result<(), Self::Error>
where
Self::Data: Clone,
{
let read_guard = &EVENTS_LISTENERS;
let listeners = read_guard.get(Self::name()).unwrap();
// Convert listeners iterator into Stream
let mut stream = stream::iter(listeners.iter());
let mut priority_join_set = Vec::new();
let mut current_priority = 0;
while let Some(Some(listener)) = stream
.next()
.await
.map(|l| l.downcast_ref::<EventListener<Self>>())
{
if listener.priority == current_priority {
priority_join_set.push(tokio::spawn((listener.listener)(event.clone())));
} else {
// Await over all listeners launched
let joined = future::join_all(priority_join_set.iter_mut()).await;
// If one listener fail we return the first error
if let Some(err) = joined
.into_iter()
.filter_map(|res| res.expect("No task should ever panic. Impossible;").err())
.next()
{
return Err(err);
}
// Update priority to the new listener(s)
current_priority = listener.priority;
priority_join_set.push(tokio::spawn((listener.listener)(event.clone())));
}
}
Ok(())
}
*/
/// Register a new event listener for this event
fn register(listener: AsyncEventListener<Self>, priority: u8) {
// Create the event listener structure
Expand Down
1 change: 1 addition & 0 deletions src/lib/net/crates/codec/src/net_types/network_position.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ impl NetEncode for NetworkPosition {
_: &NetEncodeOpts,
) -> NetEncodeResult<()> {
use tokio::io::AsyncWriteExt;

writer
.write_all(self.as_u64().to_be_bytes().as_ref())
.await?;
Expand Down
4 changes: 2 additions & 2 deletions src/lib/net/src/packets/outgoing/chunk_and_light_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use ferrumc_net_codec::net_types::var_int::VarInt;
use ferrumc_world::chunk_format::{Chunk, Heightmaps};
use std::io::{Cursor, Write};
use std::ops::Not;
use tracing::warn;
use tracing::{trace, warn};

const SECTIONS: usize = 24; // Number of sections, adjust for your Y range (-64 to 319)

Expand Down Expand Up @@ -117,7 +117,7 @@ impl ChunkAndLightData {
// If there is no palette entry, write a 0 (air) and log a warning
None => {
VarInt::new(0).write(&mut data)?;
warn!(
trace!(
"No palette entry found for section at {}, {}, {}",
chunk.x, section.y, chunk.z
);
Expand Down

0 comments on commit c5eb15c

Please sign in to comment.