### ResourceMapEntitiesPlugin Usage Example Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.ResourceMapEntitiesPlugin.html This example demonstrates how to define a resource that maps entities and how to integrate ResourceMapEntitiesPlugin into a Bevy application. ```APIDOC ## ResourceMapEntitiesPlugin A `Plugin` which updates the state of a post-rollback `Resource` `R` using `MapEntities`. ### Examples ```rust #[derive(Resource, Clone)] struct Player(Entity); impl MapEntities for Player { fn map_entities(&mut self, entity_mapper: &mut M) { self.0 = entity_mapper.get_mapped(self.0); } } // Mapped resources must be snapshot using any supported method app.rollback_resource_with_clone::(); // This will apply MapEntities on each rollback app.add_plugins(ResourceMapEntitiesPlugin::::default()); ``` ### `update` System ```rust /// Exclusive system which will apply a `RollbackEntityMap` to the `Resource` `R`, provided it implements `MapEntities`. pub fn update(world: &mut World) ``` ### `Default` Implementation ```rust /// Returns the "default value" for a type. fn default() -> Self ``` ### `Plugin` Implementation ```rust /// Registers the entity-mapping system for this resource type in `LoadWorldSystems::Mapping`. fn build(&self, app: &mut App) /// Has the plugin finished its setup? This can be useful for plugins that need something asynchronous to happen before they can finish their setup, like the initialization of a renderer. Once the plugin is ready, `finish` should be called. fn ready(&self, _app: &App) -> bool /// Finish adding this plugin to the `App`, once all plugins registered are ready. This can be useful for plugins that depends on another plugin asynchronous setup, like the renderer. fn finish(&self, _app: &mut App) /// Runs after all plugins are built and finished, but before the app schedule is executed. This can be useful if you have some resource that other plugins need during their build step, but after build you want to remove it and send it to another thread. fn cleanup(&self, _app: &mut App) /// Configures a name for the `Plugin` which is primarily used for checking plugin uniqueness and debugging. fn name(&self) -> &str /// If the plugin can be meaningfully instantiated several times in an `App`, override this method to return `false`. fn is_unique(&self) -> bool ``` ``` -------------------------------- ### GgrsPlugin::ready Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.GgrsPlugin.html Checks if the plugin has finished its setup. This is useful for plugins that require asynchronous operations before completing their setup. ```APIDOC ## GgrsPlugin::ready ### Description Has the plugin finished its setup? This can be useful for plugins that need something asynchronous to happen before they can finish their setup, like the initialization of a renderer. Once the plugin is ready, `finish` should be called. ### Signature ```rust fn ready(&self, _app: &App) -> bool ``` ``` -------------------------------- ### ResourceSnapshotPlugin::ready Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.ResourceSnapshotPlugin.html Checks if the plugin has finished its setup. ```APIDOC ## ResourceSnapshotPlugin::ready ### Description Has the plugin finished its setup? This can be useful for plugins that need something asynchronous to happen before they can finish their setup, like the initialization of a renderer. Once the plugin is ready, `finish` should be called. ### Parameters - `_app`: &App - The Bevy application. ### Returns - `bool`: `true` if the plugin is ready, `false` otherwise. ``` -------------------------------- ### GgrsPlugin::finish Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.GgrsPlugin.html Completes the plugin's setup after all other plugins have finished their setup. Useful for plugins that depend on the asynchronous setup of other plugins. ```APIDOC ## GgrsPlugin::finish ### Description Finish adding this plugin to the `App`, once all plugins registered are ready. This can be useful for plugins that depends on another plugin asynchronous setup, like the renderer. ### Signature ```rust fn finish(&self, _app: &mut App) ``` ``` -------------------------------- ### ResourceMapEntitiesPlugin Usage Example Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.ResourceMapEntitiesPlugin.html This example demonstrates how to define a resource that implements MapEntities and then use ResourceMapEntitiesPlugin to automatically apply this mapping on rollbacks. Ensure the resource is snapshot using a supported method before adding the plugin. ```rust #[derive(Resource, Clone)] struct Player(Entity); impl MapEntities for Player { fn map_entities(&mut self, entity_mapper: &mut M) { self.0 = entity_mapper.get_mapped(self.0); } } // Mapped resources must be snapshot using any supported method app.rollback_resource_with_clone::(); // This will apply MapEntities on each rollback app.add_plugins(ResourceMapEntitiesPlugin::::default()); ``` -------------------------------- ### GgrsPlugin Setup and Usage Source: https://docs.rs/bevy_ggrs/0.21.0/src/bevy_ggrs/lib.rs.html Demonstrates how to add the GgrsPlugin to a Bevy application, configure rollback, and integrate input systems. ```APIDOC ## GgrsPlugin ### Description Bevy plugin for GGRS, providing rollback management for Bevy ECS elements like Entities, Components, and Time. ### Methods - `new(schedule: impl ScheduleLabel) -> Self` Creates a new [`GgrsPlugin`] that runs the GGRS update loop in the given `schedule`. - `default() -> Self` Creates a [`GgrsPlugin`] that runs the GGRS update loop in [`PreUpdate`] (the recommended default). ### Plugin Implementation ```rust impl Plugin for GgrsPlugin { /// Registers all GGRS resources, schedules, and the session update system. fn build(&self, app: &mut App) { app.add_plugins(SnapshotPlugin) .init_resource::() .init_resource::() .init_resource::() .init_schedule(ReadInputs) .edit_schedule(AdvanceWorld, |schedule| { // AdvanceWorld is mostly a facilitator for GgrsSchedule, so SingleThreaded avoids overhead // This can be overridden if desired. schedule.set_executor_kind(ExecutorKind::SingleThreaded); }) .edit_schedule(GgrsSchedule, |schedule| { schedule.set_build_settings(ScheduleBuildSettings { ambiguity_detection: LogLevel::Error, ..default() }); }) .add_systems( AdvanceWorld, (|world: &mut World| world.run_schedule(GgrsSchedule)) .in_set(AdvanceWorldSystems::Main), ) .add_systems( self.schedule, schedule_systems::run_ggrs_schedules:: .in_set(RunGgrsSystems) ); } } ``` ### Example Usage ```rust # use bevy::prelude::* # use bevy_ggrs::prelude::* # # const FPS: usize = 60; # # type MyInputType = u8; # # fn read_local_inputs() {} # # fn start(session: Session>) { # let mut app = App::new(); // Add the GgrsPlugin with your input type app.add_plugins(GgrsPlugin::>::default()); // (optional) Override the default frequency (60) of rollback game logic updates app.insert_resource(RollbackFrameRate(FPS)); // Provide a system to get player input app.add_systems(ReadInputs, read_local_inputs); // Add custom resources/components to be rolled back app.rollback_component_with_clone::(); // Once started, add your Session app.insert_resource(session); # } ``` ``` -------------------------------- ### start_p2p_session Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/prelude/struct.SessionBuilder.html Consumes the builder to construct and start a P2P session, synchronizing endpoints. ```APIDOC ## pub fn start_p2p_session( self, socket: impl NonBlockingSocket<::Address> + 'static, ) -> Result, GgrsError> ### Description Consumes the builder to construct a `P2PSession` and starts synchronization of endpoints. ### Errors * Returns `InvalidRequest` if insufficient players have been registered. ``` -------------------------------- ### ChildOfSnapshotPlugin Plugin finish Method Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.ChildOfSnapshotPlugin.html Completes the plugin's setup after all other registered plugins are ready. This is useful for plugins that depend on the asynchronous setup of other plugins. ```rust fn finish(&self, _app: &mut App) ``` -------------------------------- ### ComponentSnapshotPlugin Usage Example Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.ComponentSnapshotPlugin.html Demonstrates how to add the ComponentSnapshotPlugin to a Bevy application, specifying the strategy and component type for snapshotting. ```APIDOC ## Example Usage ```rust // The Transform component is a good candidate for Clone-based rollback app.add_plugins(ComponentSnapshotPlugin::>::default()); ``` ``` -------------------------------- ### start_synctest_session Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/prelude/struct.SessionBuilder.html Consumes the builder to construct and start a SyncTestSession for detecting non-determinism bugs by simulating rollbacks and comparing checksums. ```APIDOC ## pub fn start_synctest_session(self) -> Result, GgrsError> ### Description Consumes the builder to construct a new `SyncTestSession`. During a `SyncTestSession`, GGRS simulates a rollback every frame and re-simulates the last `check_distance` frames, then compares checksums against the originals. A mismatch indicates a non-determinism bug in your save/load/advance logic. No network is involved. Checksum comparisons require a `check_distance` of 2 or higher (the default). ### Errors * Returns `InvalidRequest` if `check_distance` is greater than or equal to `max_prediction_window`. * Returns `InvalidRequest` if sparse saving is enabled — synctest must save every frame to compare checksums across the full check window, so sparse saving is incompatible. ``` -------------------------------- ### Example Usage of ResourceChecksumPlugin Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.ResourceChecksumPlugin.html Demonstrates how to use ResourceChecksumPlugin to include a resource in checksum calculations. Ensure the resource is also rolled back. ```rust #[derive(Resource, Clone, Hash)] struct BossHealth(u32); // To include something in the checksum, it should also be rolled back app.rollback_resource_with_clone::(); // This will update the checksum every frame to include BossHealth app.add_plugins(ResourceChecksumPlugin::::default()); ``` -------------------------------- ### GgrsComponentSnapshot Methods Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.GgrsComponentSnapshot.html Provides methods for creating, inserting, getting, and iterating over component snapshots. ```APIDOC ## `GgrsComponentSnapshot` A storage type suitable for per-`Entity` snapshots, such as `Component` types. ### Methods #### `new(components: impl IntoIterator) -> Self` Create a new snapshot from a list of `Rollback` flags and stored `Component` types. #### `insert(&mut self, entity: RollbackId, snapshot: As) -> &mut Self` Insert a single snapshot for the provided `Rollback`. #### `get(&self, entity: &RollbackId) -> Option<&As>` Get a single snapshot for the provided `Rollback`. #### `iter(&self) -> impl Iterator + '_` Iterate over all stored snapshots. ``` -------------------------------- ### SnapshotPlugin Setup Source: https://docs.rs/bevy_ggrs/0.21.0/src/bevy_ggrs/snapshot/mod.rs.html Configures Bevy's schedules and resources for rollback functionality. This plugin is independent of the GGRS plugin and can be used standalone. ```rust /// This plugin sets up the [`LoadWorld`], [`SaveWorld`], and [`AdvanceWorld`] /// schedules and adds the required systems and resources for basic rollback /// functionality. /// /// This is independent of the GGRS plugin and can be used with any Bevy app, /// including tests and benchmarks. pub struct SnapshotPlugin; impl Plugin for SnapshotPlugin { /// Registers the rollback schedules, frame-count resources, and core snapshot plugins. fn build(&self, app: &mut App) { app.add_plugins(SnapshotSetPlugin) .init_resource::() .init_resource::() .init_resource::() .init_schedule(LoadWorld) .init_schedule(SaveWorld) .init_schedule(AdvanceWorld) .add_plugins(( EntitySnapshotPlugin, ResourceSnapshotPlugin::>::default(), ChildOfSnapshotPlugin, RollbackDespawnPlugin, )); } } ``` -------------------------------- ### Test Component with Entity References Source: https://docs.rs/bevy_ggrs/0.21.0/src/bevy_ggrs/snapshot/component_map.rs.html Example test setup demonstrating a component `Likes` that holds an `Entity` reference and implements `MapEntities`. This is used to test the rollback and remapping functionality. ```rust #[derive(Component, MapEntities, Clone, Copy)] struct Likes(#[entities] Entity); ``` -------------------------------- ### Resource Checksum Plugin Example Source: https://docs.rs/bevy_ggrs/0.21.0/src/bevy_ggrs/snapshot/resource_checksum.rs.html Demonstrates how to include a resource in the checksum calculation and add the `ResourceChecksumPlugin` to the Bevy app. Ensure the resource is also rolled back using `rollback_resource_with_clone`. ```rust use bevy::prelude::* use bevy_ggrs::{prelude::*, ResourceChecksumPlugin}; const FPS: usize = 60; type MyInputType = u8; fn read_local_inputs() {} fn start(session: Session>) { let mut app = App::new(); #[derive(Resource, Clone, Hash)] struct BossHealth(u32); // To include something in the checksum, it should also be rolled back app.rollback_resource_with_clone::(); // This will update the checksum every frame to include BossHealth app.add_plugins(ResourceChecksumPlugin::::default()); } ``` -------------------------------- ### Example Usage of ComponentChecksumPlugin Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.ComponentChecksumPlugin.html Demonstrates how to include a component in the checksum by first registering it for rollback and then adding the ComponentChecksumPlugin to the Bevy app. ```rust #[derive(Component, Clone, Copy, Hash)] struct Health(u32); // To include something in the checksum, it should also be rolled back app.rollback_component_with_clone::(); // This will update the checksum every frame to include Health on rollback entities app.add_plugins(ComponentChecksumPlugin::::default()); ``` -------------------------------- ### ChildOfSnapshotPlugin Plugin ready Method Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.ChildOfSnapshotPlugin.html Checks if the plugin has finished its setup. This is useful for plugins that have asynchronous initialization steps. It returns a boolean indicating readiness. ```rust fn ready(&self, _app: &App) -> bool ``` -------------------------------- ### ChecksumPlugin Example Source: https://docs.rs/bevy_ggrs/0.21.0/src/bevy_ggrs/snapshot/checksum.rs.html Demonstrates how to integrate `ChecksumPlugin` into a Bevy application to include component data in the frame checksum. Components included in the checksum should also be rollback-able. ```rust # use bevy::prelude::* # use bevy_ggrs::{prelude::*, ChecksumPlugin}; # # const FPS: usize = 60; # # type MyInputType = u8; # # fn read_local_inputs() {} # # fn start(session: Session>) { # let mut app = App::new(); #[derive(Component, Clone, Copy, Hash)] struct Health(u32); // To include something in the checksum, it should also be rolled back app.rollback_component_with_clone::(); // This will update the checksum every frame to include Health on rollback entities app.checksum_component_with_hash::(); // This will take the Health checksum (and any others) and create a total checksum for the frame app.add_plugins(ChecksumPlugin); # } ``` -------------------------------- ### ComponentMapEntitiesPlugin Usage Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.ComponentMapEntitiesPlugin.html This example demonstrates how to use ComponentMapEntitiesPlugin with a custom component. It shows the necessary trait implementations and how to add the plugin to a Bevy application. ```APIDOC ## Struct ComponentMapEntitiesPlugin A `Plugin` which updates the state of a post-rollback `Component` `C` using `MapEntities`. ### Examples ```rust #[derive(Component, Clone)] struct BestFriend(Entity); impl MapEntities for BestFriend { fn map_entities(&mut self, entity_mapper: &mut M) { self.0 = entity_mapper.get_mapped(self.0); } } // Mapped components must be snapshot using any supported method app.rollback_component_with_clone::(); // This will apply MapEntities on each rollback app.add_plugins(ComponentMapEntitiesPlugin::::default()); ``` ### impl ComponentMapEntitiesPlugin #### pub fn update(world: &mut World) Exclusive system which will apply a `RollbackEntityMap` to the `Component` `C`, provided it implements `MapEntities`. ### impl Default for ComponentMapEntitiesPlugin #### fn default() -> Self Returns the “default value” for a type. ``` -------------------------------- ### Example Usage of GgrsTime Source: https://docs.rs/bevy_ggrs/0.21.0/src/bevy_ggrs/time.rs.html Demonstrates how to access and use both real-time and GGRS-synchronized game time within Bevy systems. This is useful for debugging or displaying different time values. ```rust use bevy::prelude::* use bevy_ggrs::prelude::* const FPS: usize = 60; fn read_local_inputs() {} fn start(session: Session>) { let mut app = App::new(); app.add_plugins(GgrsPlugin::>::default()); app.add_systems(ReadInputs, read_local_inputs); app.insert_resource(session); fn get_in_game_time(real_time: Res>, game_time: Res>) { info!("Real Time: {}", real_time.elapsed_secs()); info!("Game Time: {}", game_time.elapsed_secs()); } app.add_systems(Update, get_in_game_time); } ``` -------------------------------- ### Spawn Player System Source: https://docs.rs/bevy_ggrs/0.21.0/src/bevy_ggrs/snapshot/childof_snapshot.rs.html A simple Bevy system to spawn a player entity. This serves as a basic setup for systems that manage player-related entities. ```rust fn spawn_player(mut commands: Commands) { commands.spawn(Player); } ``` -------------------------------- ### Create a new SessionBuilder Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/prelude/struct.SessionBuilder.html Constructs a new SessionBuilder with default values. This is the starting point for configuring a GGRS session. ```rust pub fn new() -> SessionBuilder ``` -------------------------------- ### Remove a prefix from a slice Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Use `strip_prefix` to get a subslice with a specified prefix removed. Returns `None` if the slice does not start with the prefix. An empty prefix returns the original slice. ```rust let v = &[10, 40, 30]; assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..])); assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..])); assert_eq!(v.strip_prefix(&[10, 40, 30]), Some(&[][..])); assert_eq!(v.strip_prefix(&[50]), None); assert_eq!(v.strip_prefix(&[10, 50]), None); ``` ```rust let prefix : &str = "he"; assert_eq!(b"hello".strip_prefix(prefix.as_bytes()), Some(b"llo".as_ref())); ``` -------------------------------- ### Get Element Offset Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Illustrates using `element_offset` to find the index of a reference within a slice. This method uses pointer arithmetic and does not compare elements. It returns `None` if the element reference is not aligned with the start of an element. ```rust let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` ```rust let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0 assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1 ``` -------------------------------- ### IntoScheduleConfigs, ()> Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.RunGgrsSystems.html Provides methods to configure how systems are scheduled within a Bevy application. ```APIDOC ## fn into_configs(self) -> ScheduleConfigs> Convert into a `ScheduleConfigs`. ``` ```APIDOC ## fn in_set(self, set: impl SystemSet) -> ScheduleConfigs Add these systems to the provided `set`. ``` ```APIDOC ## fn before(self, set: impl IntoSystemSet) -> ScheduleConfigs Runs before all systems in `set`. If `self` has any systems that produce `Commands` or other `Deferred` operations, all systems in `set` will see their effect. ``` ```APIDOC ## fn after(self, set: impl IntoSystemSet) -> ScheduleConfigs Runs after all systems in `set`. If `set` has any systems that produce `Commands` or other `Deferred` operations, all systems in `self` will see their effect. ``` ```APIDOC ## fn before_ignore_deferred(self, set: impl IntoSystemSet) -> ScheduleConfigs Runs before all systems in `set`. ``` ```APIDOC ## fn after_ignore_deferred(self, set: impl IntoSystemSet) -> ScheduleConfigs Runs after all systems in `set`. ``` ```APIDOC ## fn distributive_run_if(self, condition: impl SystemCondition + Clone) -> ScheduleConfigs Adds a run condition to each contained system. ``` ```APIDOC ## fn run_if(self, condition: impl SystemCondition) -> ScheduleConfigs Runs the systems only if the `SystemCondition` is `true`. ``` ```APIDOC ## fn ambiguous_with(self, set: impl IntoSystemSet) -> ScheduleConfigs Suppresses warnings and errors that would result from these systems having ambiguities (conflicting access but indeterminate order) with systems in `set`. ``` ```APIDOC ## fn ambiguous_with_all(self) -> ScheduleConfigs Suppresses warnings and errors that would result from these systems having ambiguities (conflicting access but indeterminate order) with any other system. ``` ```APIDOC ## fn chain(self) -> ScheduleConfigs Treats this collection as a sequence of systems. ``` ```APIDOC ## fn chain_ignore_deferred(self) -> ScheduleConfigs Treats this collection as a sequence of systems. ``` -------------------------------- ### EntityMapper Get Mapped Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.RollbackEntityMap.html Implements the EntityMapper trait to get the target entity for a given source entity. ```rust fn get_mapped(&mut self, source: Entity) -> Entity ``` -------------------------------- ### Add EntitySnapshotPlugin to Bevy App Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.EntitySnapshotPlugin.html This example shows how to add the EntitySnapshotPlugin to a Bevy application. This ensures that entities are updated on rollback to match the state of the target snapshot. ```rust // This will ensure entities are updated on rollback to match the state of the target snapshot app.add_plugins(EntitySnapshotPlugin); ``` -------------------------------- ### Unsafe Get Unchecked Mutable Element Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Get a mutable reference to an element without bounds checking. Out-of-bounds access is undefined behavior. ```rust let x = &mut [1, 2, 4]; unsafe { let elem = x.get_unchecked_mut(1); *elem = 13; } assert_eq!(x, &[1, 13, 4]); ``` -------------------------------- ### Example Usage of ResourceMapEntitiesPlugin Source: https://docs.rs/bevy_ggrs/0.21.0/src/bevy_ggrs/snapshot/resource_map.rs.html Demonstrates how to register a resource for entity mapping and add `ResourceMapEntitiesPlugin` to an Bevy application. This ensures that cross-entity references within the `Player` resource are correctly updated after a rollback. ```rust use bevy::{prelude::*, ecs::entity::{MapEntities, EntityMapper}}; use bevy_ggrs::{prelude::*, ResourceMapEntitiesPlugin}; const FPS: usize = 60; type MyInputType = u8; fn read_local_inputs() {} fn start(session: Session>) { let mut app = App::new(); #[derive(Resource, Clone)] struct Player(Entity); impl MapEntities for Player { fn map_entities(&mut self, entity_mapper: &mut M) { self.0 = entity_mapper.get_mapped(self.0); } } // Mapped resources must be snapshot using any supported method app.rollback_resource_with_clone::(); // This will apply MapEntities on each rollback app.add_plugins(ResourceMapEntitiesPlugin::::default()); } ``` -------------------------------- ### Test: Get Absent Key Returns None Source: https://docs.rs/bevy_ggrs/0.21.0/src/bevy_ggrs/snapshot/rollback_entity_map.rs.html Verifies that calling `get` on a RollbackEntityMap with an entity ID not present in the map correctly returns `None`. ```rust /// get returns None for an entity not in the map. #[test] fn get_absent_key_returns_none() { let m = map_from(&[(1, 2)]); assert_eq!(m.get(entity(99)), None); } ``` -------------------------------- ### Get Reference to Underlying Array Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Attempts to get a reference to the underlying array if the specified size `N` matches the slice length. Returns `None` otherwise. ```rust let slice = &[1, 2, 3]; let array_ref: Option<&[i32; 3]> = slice.as_array(); assert!(array_ref.is_some()); let array_ref_wrong_size: Option<&[i32; 2]> = slice.as_array(); assert!(array_ref_wrong_size.is_none()); ``` -------------------------------- ### Get Mutable Reference to Underlying Array Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Attempts to get a mutable reference to the slice's underlying array if the specified size `N` matches the slice length. Returns `None` otherwise. ```rust let slice = &mut [1, 2, 3]; let array_mut_ref: Option<&mut [i32; 3]> = slice.as_mut_array(); assert!(array_mut_ref.is_some()); let array_mut_ref_wrong_size: Option<&mut [i32; 2]> = slice.as_mut_array(); assert!(array_mut_ref_wrong_size.is_none()); ``` -------------------------------- ### Binary Search Example Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Demonstrates the usage of binary_search on a sorted slice. It shows how to find an element, handle cases where the element is not found, and check for a range of possible positions for duplicate elements. ```rust let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; assert_eq!(s.binary_search(&13), Ok(9)); assert_eq!(s.binary_search(&4), Err(7)); assert_eq!(s.binary_search(&100), Err(13)); let r = s.binary_search(&1); assert!(match r { Ok(1..=4) => true, _ => false, }); ``` -------------------------------- ### strip_prefix Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Returns a subslice with the prefix removed. If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. If `prefix` is empty, simply returns the original slice. If `prefix` is equal to the original slice, returns an empty slice. If the slice does not start with `prefix`, returns `None`. ```APIDOC ## pub fn strip_prefix

(&self, prefix: &P) -> Option<&[T]> where P: SlicePattern + ?Sized, T: PartialEq ### Description Returns a subslice with the prefix removed. If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. If `prefix` is empty, simply returns the original slice. If `prefix` is equal to the original slice, returns an empty slice. If the slice does not start with `prefix`, returns `None`. ### Parameters #### Path Parameters - `prefix` (&P) - The prefix to remove from the slice. ### Response #### Success Response (Option<&[T]>) - `Some(subslice)` if the slice starts with the prefix. - `None` if the slice does not start with the prefix. ### Examples ```rust let v = &[10, 40, 30]; assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..])); assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..])); assert_eq!(v.strip_prefix(&[10, 40, 30]), Some(&[][..])); assert_eq!(v.strip_prefix(&[50]), None); assert_eq!(v.strip_prefix(&[10, 50]), None); let prefix : &str = "he"; assert_eq!(b"hello".strip_prefix(prefix.as_bytes()), Some(b"llo".as_ref())); ``` ``` -------------------------------- ### Get Vector Length Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Returns the number of elements currently stored in the vector. ```rust let v = vec![1, 2, 3]; assert_eq!(v.len(), 3); ``` -------------------------------- ### iter Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Returns an iterator over the slice. The iterator yields all items from start to end. ```APIDOC ## pub fn iter(&self) -> Iter<'_, T> ### Description Returns an iterator over the slice. The iterator yields all items from start to end. ### Examples ```rust let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` ``` -------------------------------- ### Get RollbackEntityMap Length Source: https://docs.rs/bevy_ggrs/0.21.0/src/bevy_ggrs/snapshot/rollback_entity_map.rs.html Returns the number of entity mappings currently stored in the RollbackEntityMap. ```rust /// The quantity of mappings contained. pub fn len(&self) -> usize { let Self(map) = self; map.len() } ``` -------------------------------- ### Default Implementation Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.RollbackFrameCount.html Provides a default value for RollbackFrameCount, which is typically the starting frame (0). ```APIDOC ### impl Default for RollbackFrameCount #### fn default() -> RollbackFrameCount Returns the default value for `RollbackFrameCount`, which is `RollbackFrameCount(0)`. ``` -------------------------------- ### start_spectator_session Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/prelude/struct.SessionBuilder.html Consumes the builder to create a new SpectatorSession, allowing connection to a remote host to spectate without contributing input. ```APIDOC ## pub fn start_spectator_session( self, host_addr: ::Address, socket: impl NonBlockingSocket<::Address> + 'static, ) -> SpectatorSession ### Description Consumes the builder to create a new `SpectatorSession`. A `SpectatorSession` provides all functionality to connect to a remote host in a peer-to-peer fashion. The host will broadcast all confirmed inputs to this session. This session can be used to spectate a session without contributing to the game input. ``` -------------------------------- ### SessionBuilder::add_player Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/prelude/struct.SessionBuilder.html Adds a player to the session. This must be called for each player before starting the session. ```APIDOC ## add_player ### Description Must be called for each player in the session (e.g. in a 3 player session, must be called 3 times) before starting the session. Player handles for players should be between 0 and `num_players`, spectator handles should be higher than `num_players`. Later, you will need the player handle to add input, change parameters or disconnect the player or spectator. ### Parameters - **player_type**: `PlayerType<::Address>` - The type of player being added. - **player_handle**: `usize` - The unique handle for the player. ### Returns - `Result, GgrsError>`: The updated SessionBuilder or an error if the handle is invalid or already exists. ``` -------------------------------- ### IntoScheduleConfigs Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/enum.AdvanceWorldSystems.html Provides methods for configuring how systems are run within a schedule, including ordering, conditions, and ambiguity handling. ```APIDOC ## impl IntoScheduleConfigs, ()> for S where S: SystemSet, ### into_configs Convert into a `ScheduleConfigs`. ### in_set Add these systems to the provided `set`. ### before Runs before all systems in `set`. If `self` has any systems that produce `Commands` or other `Deferred` operations, all systems in `set` will see their effect. ### after Run after all systems in `set`. If `set` has any systems that produce `Commands` or other `Deferred` operations, all systems in `self` will see their effect. ### before_ignore_deferred Run before all systems in `set`. ### after_ignore_deferred Run after all systems in `set`. ### distributive_run_if Add a run condition to each contained system. ### run_if Run the systems only if the `SystemCondition` is `true`. ### ambiguous_with Suppress warnings and errors that would result from these systems having ambiguities (conflicting access but indeterminate order) with systems in `set`. ### ambiguous_with_all Suppress warnings and errors that would result from these systems having ambiguities (conflicting access but indeterminate order) with any other system. ### chain Treat this collection as a sequence of systems. ### chain_ignore_deferred Treat this collection as a sequence of systems. ``` -------------------------------- ### Implement Plugin for EntitySnapshotPlugin Source: https://docs.rs/bevy_ggrs/0.21.0/src/bevy_ggrs/snapshot/entity.rs.html The `build` method registers the necessary resources (`GgrsComponentSnapshots`, `RollbackEntityMap`) and systems (`save`, `load`) for entity snapshot management within the Bevy application. ```rust impl Plugin for EntitySnapshotPlugin { /// Registers entity snapshot storage, [`RollbackEntityMap`], and the save/load systems. fn build(&self, app: &mut App) { app.init_resource::>() .init_resource::() .add_systems( SaveWorld, ( GgrsComponentSnapshots::::sync_depth, GgrsComponentSnapshots::::discard_old_snapshots, Self::save, ) .chain() .in_set(SaveWorldSystems::Snapshot), ) .add_systems(LoadWorld, Self::load.in_set(LoadWorldSystems::Entity)); } } ``` -------------------------------- ### Get Number of Mappings Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.RollbackEntityMap.html Returns the total count of Entity ID mappings stored in the map. ```rust pub fn len(&self) -> usize ``` -------------------------------- ### Add ComponentSnapshotPlugin with CloneStrategy Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.ComponentSnapshotPlugin.html This example shows how to add the ComponentSnapshotPlugin to a Bevy application, configuring it to use CloneStrategy for the Transform component. This is suitable for components that implement Clone and can be efficiently copied. ```rust // The Transform component is a good candidate for Clone-based rollback app.add_plugins(ComponentSnapshotPlugin::>::default()); ``` -------------------------------- ### Get Entity Mapping Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.RollbackEntityMap.html Retrieves the mapped Entity ID for a given Entity, if a mapping exists. ```rust pub fn get(&self, entity: Entity) -> Option ``` -------------------------------- ### Get Snapshot Storage Capacity Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.GgrsSnapshots.html Retrieves the current capacity of the snapshot storage. This is a constant function. ```rust pub const fn depth(&self) -> usize ``` -------------------------------- ### Example: Adding ResourceSnapshotPlugin for BossHealth Source: https://docs.rs/bevy_ggrs/0.21.0/src/bevy_ggrs/snapshot/resource_snapshot.rs.html Demonstrates how to add `ResourceSnapshotPlugin` to a Bevy application to manage the snapshotting of a custom `BossHealth` resource. This ensures the resource's state is saved and restored correctly during rollbacks. ```rust use bevy::prelude::* use bevy_ggrs::{prelude::*, ResourceSnapshotPlugin, CloneStrategy}; const FPS: usize = 60; type MyInputType = u8; fn read_local_inputs() {} fn start(session: Session>) { let mut app = App::new(); #[derive(Resource, Clone)] struct BossHealth(u32); // This will ensure the BossHealth resource is rolled back app.add_plugins(ResourceSnapshotPlugin::>::default()); } ``` -------------------------------- ### DynamicBundle Operations Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.ChecksumPart.html Methods for handling components within a `DynamicBundle`, including getting and applying effects. ```APIDOC #### type Effect = () An operation on the entity that happens _after_ inserting this bundle. Source§ #### unsafe fn get_components( ptr: MovingPtr<'_, C>, func: &mut impl FnMut(StorageType, OwningPtr<'_>), ) -> ::Effect Moves the components out of the bundle. Read more Source§ #### unsafe fn apply_effect( _ptr: MovingPtr<'_, MaybeUninit>, _entity: &mut EntityWorldMut<'_>, ) Applies the after-effects of spawning this bundle. Read more Source§ ``` -------------------------------- ### ComponentSnapshotPlugin Build Method Source: https://docs.rs/bevy_ggrs/0.21.0/src/bevy_ggrs/snapshot/component_snapshot.rs.html The build method for ComponentSnapshotPlugin. It initializes the GgrsComponentSnapshots resource and adds the necessary save and load systems to the Bevy application's update schedule. ```rust fn build(&self, app: &mut App) { app.init_resource::>() .add_systems( SaveWorld, ( GgrsComponentSnapshots::::sync_depth, GgrsComponentSnapshots::::discard_old_snapshots, Self::save, ) .chain() .in_set(SaveWorldSystems::Snapshot), ); ``` -------------------------------- ### Initializing Vec with Raw Pointers Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Demonstrates initializing a Vec's elements using raw pointer writes and then setting its length. This method requires `unsafe` and careful management of pointer validity. ```rust #![feature(box_vec_non_null)] // Allocate vector big enough for 4 elements. let size = 4; let mut x: Vec = Vec::with_capacity(size); let x_ptr = x.as_non_null(); // Initialize elements via raw pointer writes, then set length. unsafe { for i in 0..size { x_ptr.add(i).write(i as i32); } x.set_len(size); } assert_eq!(&*x, &[0, 1, 2, 3]); ``` -------------------------------- ### iter_mut Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Returns an iterator that allows modifying each value. The iterator yields all items from start to end. ```APIDOC ## pub fn iter_mut(&mut self) -> IterMut<'_, T> ### Description Returns an iterator that allows modifying each value. The iterator yields all items from start to end. ### Examples ```rust let x = &mut [1, 2, 4]; for elem in x.iter_mut() { *elem += 2; } assert_eq!(x, &[3, 4, 6]); ``` ``` -------------------------------- ### as_array Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Attempts to get a reference to the underlying array if the requested size `N` matches the slice length. ```APIDOC ## as_array(&self) -> Option<&[T; N]> ### Description Gets a reference to the underlying array. ### Returns `Some(&[T; N])` if `N` is equal to the length of `self`, otherwise `None`. ``` -------------------------------- ### load System Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.ComponentSnapshotPlugin.html This system restores a component to its snapshotted state for a target frame, handling insertions and removals as necessary. ```APIDOC ## `load` System ### Description System that restores the component to its snapshotted state for the target frame, inserting or removing it as required. ### Signature ```rust pub fn load< S: Strategy, >(commands: Commands<'_, '_>, snapshots: ResMut<'_, GgrsComponentSnapshots>, frame: Res<'_, RollbackFrameCount>, query: Query<'_, '_, (Entity, &RollbackId, Option<&mut S::Target>)>,) ``` ``` -------------------------------- ### get Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Returns a reference to an element or subslice based on the provided index. Returns `None` if the index is out of bounds. ```APIDOC ## get ### Description Returns a reference to an element or subslice depending on the type of index. If given a position, returns a reference to the element at that position or `None` if out of bounds. If given a range, returns the subslice corresponding to that range, or `None` if out of bounds. ### Method `slice.get(index)` ### Parameters * `index` (I): A type that implements `SliceIndex<[T]>`, such as a `usize` for an element or a range (e.g., `0..2`) for a subslice. ### Returns * `Option<&>::Output>`: An optional reference to the element or subslice, or `None` if the index is out of bounds. ``` -------------------------------- ### Get the length of a slice Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html The `len` method returns the number of elements in a slice. This is a standard method for collections. ```rust let a = [1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### SnapshotPlugin Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.SnapshotPlugin.html This plugin sets up the `LoadWorld`, `SaveWorld`, and `AdvanceWorld` schedules and adds the required systems and resources for basic rollback functionality. This is independent of the GGRS plugin and can be used with any Bevy app, including tests and benchmarks. ```APIDOC ## Struct SnapshotPlugin ```rust pub struct SnapshotPlugin; ``` This plugin sets up the `LoadWorld`, `SaveWorld`, and `AdvanceWorld` schedules and adds the required systems and resources for basic rollback functionality. This is independent of the GGRS plugin and can be used with any Bevy app, including tests and benchmarks. ``` -------------------------------- ### SessionBuilder::new Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/prelude/struct.SessionBuilder.html Constructs a new SessionBuilder with all default values. ```APIDOC ## new() ### Description Construct a new builder with all values set to their defaults. ### Returns - `SessionBuilder`: A new instance of SessionBuilder. ``` -------------------------------- ### Iterate Over Slice Elements Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Provides an iterator that yields immutable references to each element in the slice from start to end. ```rust let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` -------------------------------- ### as_mut_array Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.PlayerInputs.html Attempts to get a mutable reference to the underlying array if the requested size `N` matches the slice length. ```APIDOC ## as_mut_array(&mut self) -> Option<&mut [T; N]> ### Description Gets a mutable reference to the slice’s underlying array. ### Returns `Some(&mut [T; N])` if `N` is equal to the length of `self`, otherwise `None`. ``` -------------------------------- ### ResourceSnapshotPlugin::default Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.ResourceSnapshotPlugin.html Creates a default instance of ResourceSnapshotPlugin. ```APIDOC ## ResourceSnapshotPlugin::default ### Description Returns the default value for a `ResourceSnapshotPlugin`. ### Returns - `Self`: A default instance of `ResourceSnapshotPlugin`. ``` -------------------------------- ### Bundle Get Component IDs Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.RollbackId.html Retrieves an iterator over the Option for each component within a Bundle, indicating if they are registered. ```rust fn get_component_ids( components: &Components, ) -> impl Iterator> ``` -------------------------------- ### Configure AdvanceWorld System Dependencies Source: https://docs.rs/bevy_ggrs/0.21.0/src/bevy_ggrs/snapshot/set.rs.html Adds the ApplyDeferred system to the AdvanceWorld set, establishing specific ordering constraints using `.after()` and `.before()`. This ensures ApplyDeferred runs after AdvanceWorldSystems::First and before AdvanceWorldSystems::Main, and again after AdvanceWorldSystems::Main and before AdvanceWorldSystems::Last. ```rust .add_systems( AdvanceWorld, ApplyDeferred .after(AdvanceWorldSystems::First) .before(AdvanceWorldSystems::Main), ) .add_systems( AdvanceWorld, ApplyDeferred .after(AdvanceWorldSystems::Main) .before(AdvanceWorldSystems::Last), ); ``` -------------------------------- ### Get a SeaHasher for Checksums Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/fn.checksum_hasher.html Use this function to obtain a SeaHasher instance. It's designed for creating portable checksums. ```rust pub fn checksum_hasher() -> SeaHasher ``` -------------------------------- ### Resource Implementation for MaxPredictionWindow Source: https://docs.rs/bevy_ggrs/0.21.0/bevy_ggrs/struct.MaxPredictionWindow.html Indicates that `MaxPredictionWindow` can be used as a Bevy resource. ```APIDOC ### impl Resource for MaxPredictionWindow where Self: Send + Sync + 'static, ```