Skip to content

Commit

Permalink
Merge pull request #68 from gschup/refactor/naming_conventions
Browse files Browse the repository at this point in the history
Refactor: naming conventions
  • Loading branch information
gschup committed Nov 10, 2023
2 parents d062ead + d3f9417 commit 27c16b1
Show file tree
Hide file tree
Showing 18 changed files with 178 additions and 191 deletions.
10 changes: 6 additions & 4 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ In this document, all remarkable changes are listed. Not mentioned are smaller c

## Unreleased

- Rename types with GGRS prefix to match rust naming conventions
- Removed deprecated `GgrsError` variants
- `GameStateCell` now implements debug.
- fixed a bug where checksums of unconfirmed frames were compared during desync detection.
- You can now trigger a desync manually in the example game by pressing SPACE.
Expand Down Expand Up @@ -92,7 +94,7 @@ In this document, all remarkable changes are listed. Not mentioned are smaller c

## 0.4.2

- users are now allowed to save `None` buffers for a `GGRSRequest::SaveRequest`. This allows users to keep their own state history and load/save more efficiently
- users are now allowed to save `None` buffers for a `GgrsRequest::SaveRequest`. This allows users to keep their own state history and load/save more efficiently
- added `num_players()`, `input_size()` getters to all sessions

## 0.4.1
Expand All @@ -115,8 +117,8 @@ In this document, all remarkable changes are listed. Not mentioned are smaller c

## 0.3.0

- `GGRSError::InvalidRequest` now has an added `info` field to explain the problem in more detail
- removed unused `GGRSError::GeneralFailure`
- `GgrsError::InvalidRequest` now has an added `info` field to explain the problem in more detail
- removed unused `GgrsError::GeneralFailure`
- removed multiple methods in `SyncTestSession`, as they didn't fulfill any meaningful purpose
- removed unused sequence number from message header, fixing related issues
- fixed an issue where out-of-order packets would cause a crash
Expand Down Expand Up @@ -150,4 +152,4 @@ In this document, all remarkable changes are listed. Not mentioned are smaller c

## 0.2.0

- Reworked API: Instead of the user passing a GGRSInterface trait object, GGRS now returns a list of GGRSRequests for the user to fulfill
- Reworked API: Instead of the user passing a GGRSInterface trait object, GGRS now returns a list of GgrsRequests for the user to fulfill
12 changes: 6 additions & 6 deletions examples/ex_game/ex_game.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::net::SocketAddr;

use bytemuck::{Pod, Zeroable};
use ggrs::{Config, Frame, GGRSRequest, GameStateCell, InputStatus, PlayerHandle, NULL_FRAME};
use ggrs::{Config, Frame, GameStateCell, GgrsRequest, InputStatus, PlayerHandle, NULL_FRAME};
use macroquad::prelude::*;
use serde::{Deserialize, Serialize};

Expand Down Expand Up @@ -51,7 +51,7 @@ fn fletcher16(data: &[u8]) -> u16 {
(sum2 << 8) | sum1
}

// BoxGame will handle rendering, gamestate, inputs and GGRSRequests
// BoxGame will handle rendering, gamestate, inputs and GgrsRequests
pub struct Game {
num_players: usize,
game_state: State,
Expand All @@ -73,12 +73,12 @@ impl Game {
}

// for each request, call the appropriate function
pub fn handle_requests(&mut self, requests: Vec<GGRSRequest<GGRSConfig>>) {
pub fn handle_requests(&mut self, requests: Vec<GgrsRequest<GGRSConfig>>) {
for request in requests {
match request {
GGRSRequest::LoadGameState { cell, .. } => self.load_game_state(cell),
GGRSRequest::SaveGameState { cell, frame } => self.save_game_state(cell, frame),
GGRSRequest::AdvanceFrame { inputs } => self.advance_frame(inputs),
GgrsRequest::LoadGameState { cell, .. } => self.load_game_state(cell),
GgrsRequest::SaveGameState { cell, frame } => self.save_game_state(cell, frame),
GgrsRequest::AdvanceFrame { inputs } => self.advance_frame(inputs),
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions examples/ex_game/ex_game_p2p.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
mod ex_game;

use ex_game::{GGRSConfig, Game};
use ggrs::{GGRSError, PlayerType, SessionBuilder, SessionState, UdpNonBlockingSocket};
use ggrs::{GgrsError, PlayerType, SessionBuilder, SessionState, UdpNonBlockingSocket};
use instant::{Duration, Instant};
use macroquad::prelude::*;
use std::net::SocketAddr;
Expand Down Expand Up @@ -112,7 +112,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {

match sess.advance_frame() {
Ok(requests) => game.handle_requests(requests),
Err(GGRSError::PredictionThreshold) => {
Err(GgrsError::PredictionThreshold) => {
println!("Frame {} skipped", sess.current_frame())
}

Expand Down
6 changes: 3 additions & 3 deletions examples/ex_game/ex_game_spectator.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
mod ex_game;

use ex_game::{GGRSConfig, Game};
use ggrs::{GGRSError, GGRSEvent, SessionBuilder, SessionState, UdpNonBlockingSocket};
use ggrs::{GgrsError, GgrsEvent, SessionBuilder, SessionState, UdpNonBlockingSocket};
use instant::{Duration, Instant};
use macroquad::prelude::*;
use std::net::SocketAddr;
Expand Down Expand Up @@ -59,7 +59,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// handle GGRS events
for event in sess.events() {
println!("Event: {:?}", event);
if let GGRSEvent::Disconnected { .. } = event {
if let GgrsEvent::Disconnected { .. } = event {
println!("Disconnected from host.");
return Ok(());
}
Expand All @@ -79,7 +79,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
if sess.current_state() == SessionState::Running {
match sess.advance_frame() {
Ok(requests) => game.handle_requests(requests),
Err(GGRSError::PredictionThreshold) => {
Err(GgrsError::PredictionThreshold) => {
println!(
"Frame {} skipped: Waiting for input from host.",
game.current_frame()
Expand Down
35 changes: 10 additions & 25 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ use std::fmt::Display;

use crate::Frame;

/// This enum contains all error messages this library can return. Most API functions will generally return a [`Result<(),GGRSError>`].
/// This enum contains all error messages this library can return. Most API functions will generally return a [`Result<(), GgrsError>`].
///
/// [`Result<(),GGRSError>`]: std::result::Result
/// [`Result<(), GgrsError>`]: std::result::Result
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum GGRSError {
pub enum GgrsError {
/// When the prediction threshold has been reached, we cannot accept more inputs from the local player.
PredictionThreshold,
/// You made an invalid request, usually by using wrong parameters for function calls.
Expand All @@ -27,56 +27,41 @@ pub enum GGRSError {
NotSynchronized,
/// The spectator got so far behind the host that catching up is impossible.
SpectatorTooFarBehind,
/// Deprecated, will be removed in next major release
SocketCreationFailed,
/// Deprecated, will be removed in next major release
PlayerDisconnected,
/// Deprecated, will be removed in next major release
DecodingError,
}

impl Display for GGRSError {
impl Display for GgrsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
GGRSError::PredictionThreshold => {
GgrsError::PredictionThreshold => {
write!(
f,
"Prediction threshold is reached, cannot proceed without catching up."
)
}
GGRSError::InvalidRequest { info } => {
GgrsError::InvalidRequest { info } => {
write!(f, "Invalid Request: {}", info)
}
GGRSError::NotSynchronized => {
GgrsError::NotSynchronized => {
write!(
f,
"The session is not yet synchronized with all remote sessions."
)
}
GGRSError::MismatchedChecksum { frame } => {
GgrsError::MismatchedChecksum { frame } => {
write!(
f,
"Detected checksum mismatch during rollback on frame {}.",
frame
)
}
GGRSError::SpectatorTooFarBehind => {
GgrsError::SpectatorTooFarBehind => {
write!(
f,
"The spectator got so far behind the host that catching up is impossible."
)
}
GGRSError::SocketCreationFailed => {
write!(f, "Deprecated, will be removed in next major release.")
}
GGRSError::PlayerDisconnected => {
write!(f, "Deprecated, will be removed in next major release.")
}
GGRSError::DecodingError => {
write!(f, "Deprecated, will be removed in next major release.")
}
}
}
}

impl Error for GGRSError {}
impl Error for GgrsError {}
8 changes: 4 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
//#![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)]
use std::{fmt::Debug, hash::Hash};

pub use error::GGRSError;
pub use error::GgrsError;
pub use network::messages::Message;
pub use network::network_stats::NetworkStats;
pub use network::udp_socket::UdpNonBlockingSocket;
Expand Down Expand Up @@ -113,7 +113,7 @@ pub enum InputStatus {

/// Notifications that you can receive from the session. Handling them is up to the user.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum GGRSEvent<T>
pub enum GgrsEvent<T>
where
T: Config,
{
Expand Down Expand Up @@ -143,7 +143,7 @@ where
/// The client will be disconnected in this amount of ms.
disconnect_timeout: u128,
},
/// Sent only after a [`GGRSEvent::NetworkInterrupted`] event, if communication with that player has resumed.
/// Sent only after a [`GgrsEvent::NetworkInterrupted`] event, if communication with that player has resumed.
NetworkResumed {
/// The address of the endpoint.
addr: T::Address,
Expand All @@ -167,7 +167,7 @@ where
}

/// Requests that you can receive from the session. Handling them is mandatory.
pub enum GGRSRequest<T>
pub enum GgrsRequest<T>
where
T: Config,
{
Expand Down
8 changes: 4 additions & 4 deletions src/network/protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::network::messages::{
};
use crate::time_sync::TimeSync;
use crate::{
Config, DesyncDetection, Frame, GGRSError, NonBlockingSocket, PlayerHandle, NULL_FRAME,
Config, DesyncDetection, Frame, GgrsError, NonBlockingSocket, PlayerHandle, NULL_FRAME,
};

use instant::{Duration, Instant};
Expand Down Expand Up @@ -280,15 +280,15 @@ impl<T: Config> UdpProtocol<T> {
self.local_frame_advantage = remote_frame - local_frame;
}

pub(crate) fn network_stats(&self) -> Result<NetworkStats, GGRSError> {
pub(crate) fn network_stats(&self) -> Result<NetworkStats, GgrsError> {
if self.state != ProtocolState::Synchronizing && self.state != ProtocolState::Running {
return Err(GGRSError::NotSynchronized);
return Err(GgrsError::NotSynchronized);
}

let now = millis_since_epoch();
let seconds = (now - self.stats_start_time) / 1000;
if seconds == 0 {
return Err(GGRSError::NotSynchronized);
return Err(GgrsError::NotSynchronized);
}

let total_bytes_sent = self.bytes_sent + (self.packets_sent * UDP_HEADER_SIZE);
Expand Down

0 comments on commit 27c16b1

Please sign in to comment.