Skip to content

Commit

Permalink
Updated incomplete/incorrect documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
bushrat011899 committed Nov 7, 2023
1 parent 2e8b463 commit d38e7da
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 18 deletions.
13 changes: 3 additions & 10 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
//! bevy_ggrs is a bevy plugin for the P2P rollback networking library GGRS.
//!
//! See [`GgrsPlugin`] for getting started.
#![forbid(unsafe_code)] // let us try

use bevy::{
Expand Down Expand Up @@ -26,7 +28,7 @@ pub(crate) mod time;
pub mod prelude {
pub use crate::{
snapshot::prelude::*, AddRollbackCommandExtension, GgrsApp, GgrsConfig, GgrsPlugin,
GgrsSchedule, PlayerInputs, ReadInputs, Rollback, Session,
GgrsSchedule, GgrsTime, PlayerInputs, ReadInputs, Rollback, Session,
};
pub use ggrs::{GGRSEvent as GgrsEvent, PlayerType, SessionBuilder};
}
Expand Down Expand Up @@ -146,15 +148,6 @@ pub struct AdvanceWorld;
///
/// To add more data to the rollback management, see the methods provided by [GgrsApp].
///
/// # Rollback
///
/// This will provide rollback management for the following items in the Bevy ECS:
/// - [Entities](`Entity`)
/// - [Parent] and [Children] components
/// - [Time]
///
/// To add more data to the rollback management, see the methods provided by [GgrsApp].
///
/// # Examples
/// ```rust
/// # use bevy::prelude::*;
Expand Down
12 changes: 6 additions & 6 deletions src/rollback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,19 @@ use bevy::{

/// This component flags an entity as being included in the rollback save/load schedule with GGRS.
///
/// You must use the `AddRollbackCommand` when spawning an entity to add this component. Alternatively,
/// you can use the `add_rollback()` extension method provided by `AddRollbackCommandExtension`.
/// You must use the [`AddRollbackCommand`] when spawning an entity to add this component. Alternatively,
/// you can use the `add_rollback()` extension method provided by [`AddRollbackCommandExtension`].
#[derive(Component, Hash, PartialEq, Eq, Clone, Copy, Debug)]
pub struct Rollback(Entity);

impl Rollback {
/// Creates a new `Rollback` component from an `Entity`.
/// Creates a new [`Rollback`] component from an [`Entity`].
pub(crate) fn new(entity: Entity) -> Self {
Self(entity)
}
}

/// An `EntityCommand` which adds a `Rollback` component to an entity.
/// An [`EntityCommand`] which adds a [`Rollback`] component to an entity.
pub struct AddRollbackCommand;

impl EntityCommand for AddRollbackCommand {
Expand All @@ -34,11 +34,11 @@ impl EntityCommand for AddRollbackCommand {
}

mod private {
/// Private seal to ensure `AddRollbackCommandExtension` cannot be implemented by crate consumers.
/// Private seal to ensure [`AddRollbackCommandExtension`](`super::AddRollbackCommandExtension`) cannot be implemented by crate consumers.
pub trait AddRollbackCommandExtensionSeal {}
}

/// Extension trait for `EntityCommands` which adds the `add_rollback()` method.
/// Extension trait for [`EntityCommands`] which adds the `add_rollback()` method.
pub trait AddRollbackCommandExtension: private::AddRollbackCommandExtensionSeal {
/// Adds an automatically generated `Rollback` component to this `Entity`.
fn add_rollback(&mut self) -> &mut Self;
Expand Down
20 changes: 18 additions & 2 deletions src/snapshot/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,10 @@ pub type GgrsComponentSnapshots<C, As = C> = GgrsSnapshots<C, GgrsComponentSnaps
#[derive(Resource)]
pub struct GgrsSnapshots<For, As = For> {
/// Queue of snapshots, newest at the front, oldest at the back.
/// Separate from `frames`` to avoid padding.
snapshots: VecDeque<As>,
/// Queue of snapshots, newest at the front, oldest at the back.\
/// Separate from snapshots to avoid padding.
/// Queue of frames, newest at the front, oldest at the back.
/// Separate from `snapshots`` to avoid padding.
frames: VecDeque<i32>,
/// Maximum amount of snapshots to store at any one time
depth: usize,
Expand All @@ -65,6 +66,7 @@ impl<For, As> Default for GgrsSnapshots<For, As> {
}

impl<For, As> GgrsSnapshots<For, As> {
/// Updates the capacity of this storage to the provided depth.
pub fn set_depth(&mut self, depth: usize) -> &mut Self {
self.depth = depth;

Expand All @@ -82,10 +84,13 @@ impl<For, As> GgrsSnapshots<For, As> {
self
}

/// Get the current capacity of this snapshot storage.
pub const fn depth(&self) -> usize {
self.depth
}

/// Push a new snapshot for the provided frame. If the frame is earlier than any
/// currently stored snapshots, those snapshots will be discarded.
pub fn push(&mut self, frame: i32, snapshot: As) -> &mut Self {
debug_assert_eq!(
self.snapshots.len(),
Expand Down Expand Up @@ -122,6 +127,8 @@ impl<For, As> GgrsSnapshots<For, As> {
self
}

/// Confirms a snapshot as being stable across clients. Snapshots from before this
/// point are discarded as no longer required.
pub fn confirm(&mut self, confirmed_frame: i32) -> &mut Self {
debug_assert_eq!(
self.snapshots.len(),
Expand All @@ -141,6 +148,7 @@ impl<For, As> GgrsSnapshots<For, As> {
self
}

/// Rolls back to the provided frame, discarding snapshots taken after the rollback point.
pub fn rollback(&mut self, frame: i32) -> &mut Self {
loop {
let Some(&current) = self.frames.front() else {
Expand All @@ -159,10 +167,12 @@ impl<For, As> GgrsSnapshots<For, As> {
self
}

/// Get the current snapshot. Use `rollback(frame)` to first select a frame to rollback to.
pub fn get(&self) -> &As {
self.snapshots.front().unwrap()
}

/// Get a particular snapshot if it exists.
pub fn peek(&self, frame: i32) -> Option<&As> {
let (index, _) = self
.frames
Expand All @@ -172,6 +182,7 @@ impl<For, As> GgrsSnapshots<For, As> {
self.snapshots.get(index)
}

/// A system which automatically confirms the [`ConfirmedFrameCount`], discarding older snapshots.
pub fn discard_old_snapshots(
mut snapshots: ResMut<Self>,
confirmed_frame: Option<Res<ConfirmedFrameCount>>,
Expand All @@ -187,6 +198,7 @@ impl<For, As> GgrsSnapshots<For, As> {
}
}

/// A storage type suitable for per-[`Entity`] snapshots, such as [`Component`] types.
pub struct GgrsComponentSnapshot<For, As = For> {
snapshot: HashMap<Rollback, As>,
_phantom: PhantomData<For>,
Expand All @@ -202,22 +214,26 @@ impl<For, As> Default for GgrsComponentSnapshot<For, As> {
}

impl<For, As> GgrsComponentSnapshot<For, As> {
/// Create a new snapshot from a list of [`Rollback`] flags and stored [`Component`] types.
pub fn new(components: impl IntoIterator<Item = (Rollback, As)>) -> Self {
Self {
snapshot: components.into_iter().collect(),
..default()
}
}

/// Insert a single snapshot for the provided [`Rollback`].
pub fn insert(&mut self, entity: Rollback, snapshot: As) -> &mut Self {
self.snapshot.insert(entity, snapshot);
self
}

/// Get a single snapshot for the provided [`Rollback`].
pub fn get(&self, entity: &Rollback) -> Option<&As> {
self.snapshot.get(entity)
}

/// Iterate over all stored snapshots.
pub fn iter(&self) -> impl Iterator<Item = (&Rollback, &As)> + '_ {
self.snapshot.iter()
}
Expand Down
29 changes: 29 additions & 0 deletions src/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,32 @@ impl Default for RollbackFrameRate {
}
}

/// A [`Time`] type for use with GGRS. This time is guaranteed to be in-sync with
/// all peers, and reflect that exactly [`RollbackFrameCount`] frames have passed at
/// the [`RollbackFrameRate`] rate. Note that in the [`GgrsSchedule`](`crate::GgrsSchedule`),
/// this is the [default time](`Time<()>`).
///
/// # Examples
/// ```rust
/// # use bevy::prelude::*;
/// # use bevy_ggrs::prelude::*;
/// #
/// # const FPS: usize = 60;
/// #
/// # fn read_local_inputs() {}
/// #
/// # fn start(session: Session<GgrsConfig<u8>>) {
/// # let mut app = App::new();
/// # app.add_plugins(GgrsPlugin::<GgrsConfig<u8>>::default());
/// # app.add_systems(ReadInputs, read_local_inputs);
/// # app.insert_resource(session);
/// fn get_in_game_time(real_time: Res<Time<Real>>, game_time: Res<Time<GgrsTime>>) {
/// info!("Real Time: {}", real_time.elapsed_seconds());
/// info!("Game Time: {}", game_time.elapsed_seconds());
/// }
/// # app.add_systems(Update, get_in_game_time);
/// # }
/// ```
#[derive(Default, Clone, Copy, Debug)]
pub struct GgrsTime;

Expand All @@ -25,6 +51,7 @@ pub struct GgrsTime;
pub struct GgrsTimePlugin;

impl GgrsTimePlugin {
/// Updates the [`Time<GgrsTime>`] resource to match [`RollbackFrameCount`] and [`RollbackFrameRate`].
pub fn update(
mut time: ResMut<Time<GgrsTime>>,
framerate: Res<RollbackFrameRate>,
Expand All @@ -40,13 +67,15 @@ impl GgrsTimePlugin {
time.advance_to(runtime);
}

/// Overrides the [default time](`Time<()>`) with [`Time<GgrsTime>`].
pub fn replace_default_with_ggrs(
mut default_time: ResMut<Time<()>>,
ggrs_time: Res<Time<GgrsTime>>,
) {
*default_time = ggrs_time.as_generic();
}

/// Overrides the [default time](`Time<()>`) with [`Time<Virtual>`].
pub fn replace_default_with_virtual(
mut default_time: ResMut<Time<()>>,
virtual_time: Res<Time<Virtual>>,
Expand Down

0 comments on commit d38e7da

Please sign in to comment.