Skip to content

Use Bevy state API for client and server states #487

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 10 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Changed

- Rename `RepliconClientStatus` to `ClientState` and `RepliconServerStatus` to `ServerState`. They are now regular Bevy states. As result, we now require `StatesPlugin` to be added. It's present by default in `DefaultPlugins`, but with `MinimalPlugins` you have to add it manually.
- `AppRuleExt::replicate_with` now accepts `IntoReplicationRule` trait that allows to define rules with multiple components.
- Rename `GroupReplication` into `BundleReplication`.
- Rename `AppRuleExt::replicate_group` into `AppRuleExt::replicate_bundle`.
Expand All @@ -30,6 +31,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- `WriteCtx::commands`. You can now insert and remove components directly through `DeferredEntity`.
- Deprecated methods.
- Methods in `RepliconServer` and `RepliconClient` that updated the connection state. Use Bevy's state API with `ServerState` and `ClientState` instead.
- All provided run conditions. Just use `in_state` or `OnEnter`/`OnExit` with `ServerState` and `ClientState` instead.

## [0.33.0] - 2025-04-27

Expand Down
4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ all-features = true
members = ["bevy_replicon_example_backend"]

[dependencies]
bevy = { version = "0.16.0", default-features = false }
bevy = { version = "0.16.0", default-features = false, features = [
"bevy_state",
] }
log = "0.4" # Directly depend on `log` like other `no_std` Bevy crates, since `bevy_log` currently requires `std`.
petgraph = { version = "0.8", default-features = false, features = [
"stable_graph",
Expand Down
24 changes: 13 additions & 11 deletions benches/related_entities.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use bevy::prelude::*;
use bevy::{prelude::*, state::app::StatesPlugin};
use bevy_replicon::prelude::*;
use criterion::{Criterion, criterion_group, criterion_main};

Expand All @@ -11,24 +11,25 @@ fn hierarchy_spawning(c: &mut Criterion) {

group.bench_function("regular", |b| {
let mut app = App::new();
app.add_plugins((MinimalPlugins, RepliconPlugins));
app.add_plugins((MinimalPlugins, StatesPlugin, RepliconPlugins));

b.iter(|| spawn_then_despawn(&mut app));
});
group.bench_function("related_without_server", |b| {
let mut app = App::new();
app.add_plugins((MinimalPlugins, RepliconPlugins))
app.add_plugins((MinimalPlugins, StatesPlugin, RepliconPlugins))
.sync_related_entities::<ChildOf>();

b.iter(|| spawn_then_despawn(&mut app));
});
group.bench_function("related", |b| {
let mut app = App::new();
app.add_plugins((MinimalPlugins, RepliconPlugins))
app.add_plugins((MinimalPlugins, StatesPlugin, RepliconPlugins))
.sync_related_entities::<ChildOf>();

let mut server = app.world_mut().resource_mut::<RepliconServer>();
server.set_running(true);
app.world_mut()
.resource_mut::<NextState<ServerState>>()
.set(ServerState::Running);

b.iter(|| spawn_then_despawn(&mut app));
});
Expand All @@ -45,15 +46,15 @@ fn hierarchy_changes(c: &mut Criterion) {

group.bench_function("regular", |b| {
let mut app = App::new();
app.add_plugins((MinimalPlugins, RepliconPlugins));
app.add_plugins((MinimalPlugins, StatesPlugin, RepliconPlugins));

spawn_hierarchy(app.world_mut());

b.iter(|| trigger_hierarchy_change(&mut app));
});
group.bench_function("related_without_server", |b| {
let mut app = App::new();
app.add_plugins((MinimalPlugins, RepliconPlugins))
app.add_plugins((MinimalPlugins, StatesPlugin, RepliconPlugins))
.sync_related_entities::<ChildOf>();

spawn_hierarchy(app.world_mut());
Expand All @@ -62,13 +63,14 @@ fn hierarchy_changes(c: &mut Criterion) {
});
group.bench_function("related", |b| {
let mut app = App::new();
app.add_plugins((MinimalPlugins, RepliconPlugins))
app.add_plugins((MinimalPlugins, StatesPlugin, RepliconPlugins))
.sync_related_entities::<ChildOf>();

spawn_hierarchy(app.world_mut());

let mut server = app.world_mut().resource_mut::<RepliconServer>();
server.set_running(true);
app.world_mut()
.resource_mut::<NextState<ServerState>>()
.set(ServerState::Running);

b.iter(|| trigger_hierarchy_change(&mut app));
});
Expand Down
5 changes: 4 additions & 1 deletion benches/replication.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use core::time::Duration;

use bevy::{ecs::component::Mutable, platform::time::Instant, prelude::*};
use bevy::{
ecs::component::Mutable, platform::time::Instant, prelude::*, state::app::StatesPlugin,
};
use bevy_replicon::{prelude::*, test_app::ServerTestAppExt};
use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
Expand Down Expand Up @@ -184,6 +186,7 @@ fn create_app<C: BenchmarkComponent>() -> App {
let mut app = App::new();
app.add_plugins((
MinimalPlugins,
StatesPlugin,
RepliconPlugins.set(ServerPlugin {
tick_policy: TickPolicy::EveryFrame,
..Default::default()
Expand Down
1 change: 0 additions & 1 deletion bevy_replicon_example_backend/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ fastrand = "2.3"
[dev-dependencies]
bevy = { version = "0.16.0", default-features = false, features = [
"bevy_gizmos",
"bevy_state",
"bevy_text",
"bevy_ui_picking_backend",
"bevy_ui",
Expand Down
18 changes: 8 additions & 10 deletions bevy_replicon_example_backend/examples/tic_tac_toe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,19 +55,17 @@ fn main() {
.add_systems(OnEnter(GameState::Winner), show_winner_text)
.add_systems(OnEnter(GameState::Tie), show_tie_text)
.add_systems(OnEnter(GameState::Disconnected), stop_networking)
.add_systems(OnEnter(ClientState::Connected), client_start)
.add_systems(OnEnter(ClientState::Connecting), show_connecting_text)
.add_systems(OnExit(ClientState::Connected), disconnect_by_server)
.add_systems(OnEnter(ServerState::Running), show_waiting_client_text)
.add_systems(
Update,
(
show_connecting_text.run_if(resource_added::<ExampleClient>),
show_waiting_client_text.run_if(resource_added::<ExampleServer>),
client_start.run_if(client_just_connected),
(
disconnect_by_server.run_if(client_just_disconnected),
update_buttons_background.run_if(local_player_turn),
show_turn_symbol.run_if(resource_changed::<TurnSymbol>),
)
.run_if(in_state(GameState::InGame)),
),
update_buttons_background.run_if(local_player_turn),
show_turn_symbol.run_if(resource_changed::<TurnSymbol>),
)
.run_if(in_state(GameState::InGame)),
)
.run();
}
Expand Down
14 changes: 8 additions & 6 deletions bevy_replicon_example_backend/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@ impl Plugin for RepliconExampleClientPlugin {
app.add_systems(
PreUpdate,
(
set_disconnected.run_if(resource_removed::<ExampleClient>),
set_connected.run_if(resource_added::<ExampleClient>),
receive_packets.run_if(resource_exists::<ExampleClient>),
(
set_disconnected.run_if(resource_removed::<ExampleClient>),
set_connected.run_if(resource_added::<ExampleClient>),
),
)
.chain()
.in_set(ClientSet::ReceivePackets),
Expand All @@ -36,12 +38,12 @@ impl Plugin for RepliconExampleClientPlugin {
}
}

fn set_disconnected(mut replicon_client: ResMut<RepliconClient>) {
replicon_client.set_status(RepliconClientStatus::Disconnected);
fn set_disconnected(mut state: ResMut<NextState<ClientState>>) {
state.set(ClientState::Disconnected);
}

fn set_connected(mut replicon_client: ResMut<RepliconClient>) {
replicon_client.set_status(RepliconClientStatus::Connected);
fn set_connected(mut state: ResMut<NextState<ClientState>>) {
state.set(ClientState::Connected);
}

fn receive_packets(
Expand Down
14 changes: 8 additions & 6 deletions bevy_replicon_example_backend/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@ impl Plugin for RepliconExampleServerPlugin {
app.add_systems(
PreUpdate,
(
set_stopped.run_if(resource_removed::<ExampleServer>),
set_running.run_if(resource_added::<ExampleServer>),
receive_packets.run_if(resource_exists::<ExampleServer>),
(
set_stopped.run_if(resource_removed::<ExampleServer>),
set_running.run_if(resource_added::<ExampleServer>),
),
)
.chain()
.in_set(ServerSet::ReceivePackets),
Expand All @@ -36,12 +38,12 @@ impl Plugin for RepliconExampleServerPlugin {
}
}

fn set_stopped(mut server: ResMut<RepliconServer>) {
server.set_running(false);
fn set_stopped(mut state: ResMut<NextState<ServerState>>) {
state.set(ServerState::Stopped);
}

fn set_running(mut server: ResMut<RepliconServer>) {
server.set_running(true);
fn set_running(mut state: ResMut<NextState<ServerState>>) {
state.set(ServerState::Running);
}

fn receive_packets(
Expand Down
20 changes: 13 additions & 7 deletions bevy_replicon_example_backend/tests/backend.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::io;

use bevy::prelude::*;
use bevy::{prelude::*, state::app::StatesPlugin};
use bevy_replicon::prelude::*;
use bevy_replicon_example_backend::{ExampleClient, ExampleServer, RepliconExampleBackendPlugins};
use serde::{Deserialize, Serialize};
Expand All @@ -12,6 +12,7 @@ fn connect_disconnect() {
for app in [&mut server_app, &mut client_app] {
app.add_plugins((
MinimalPlugins,
StatesPlugin,
RepliconPlugins.set(ServerPlugin {
tick_policy: TickPolicy::EveryFrame,
..Default::default()
Expand All @@ -22,13 +23,14 @@ fn connect_disconnect() {

setup(&mut server_app, &mut client_app).unwrap();

assert!(server_app.world().resource::<RepliconServer>().is_running());
let server_state = server_app.world().resource::<State<ServerState>>();
assert_eq!(*server_state, ServerState::Running);

let mut clients = server_app.world_mut().query::<&ConnectedClient>();
assert_eq!(clients.iter(server_app.world()).len(), 1);

let replicon_client = client_app.world().resource::<RepliconClient>();
assert!(replicon_client.is_connected());
let client_state = client_app.world().resource::<State<ClientState>>();
assert_eq!(*client_state, ClientState::Connected);

let renet_client = client_app.world().resource::<ExampleClient>();
assert!(renet_client.is_connected());
Expand All @@ -40,14 +42,15 @@ fn connect_disconnect() {

assert_eq!(clients.iter(server_app.world()).len(), 0);

let replicon_client = client_app.world().resource::<RepliconClient>();
assert!(replicon_client.is_disconnected());
let client_state = client_app.world().resource::<State<ClientState>>();
assert_eq!(*client_state, ClientState::Disconnected);

server_app.world_mut().remove_resource::<ExampleServer>();

server_app.update();

assert!(!server_app.world().resource::<RepliconServer>().is_running());
let server_state = server_app.world().resource::<State<ServerState>>();
assert_eq!(*server_state, ServerState::Stopped);
}

#[test]
Expand All @@ -57,6 +60,7 @@ fn replication() {
for app in [&mut server_app, &mut client_app] {
app.add_plugins((
MinimalPlugins,
StatesPlugin,
RepliconPlugins.set(ServerPlugin {
tick_policy: TickPolicy::EveryFrame,
..Default::default()
Expand All @@ -83,6 +87,7 @@ fn server_event() {
for app in [&mut server_app, &mut client_app] {
app.add_plugins((
MinimalPlugins,
StatesPlugin,
RepliconPlugins.set(ServerPlugin {
tick_policy: TickPolicy::EveryFrame,
..Default::default()
Expand Down Expand Up @@ -114,6 +119,7 @@ fn client_event() {
for app in [&mut server_app, &mut client_app] {
app.add_plugins((
MinimalPlugins,
StatesPlugin,
RepliconPlugins.set(ServerPlugin {
tick_policy: TickPolicy::EveryFrame,
..Default::default()
Expand Down
21 changes: 11 additions & 10 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ use postcard::experimental::max_size::MaxSize;

use crate::shared::{
backend::{
ClientState,
replicon_channels::{ReplicationChannel, RepliconChannels},
replicon_client::RepliconClient,
},
common_conditions::{client_connected, client_just_connected, client_just_disconnected},
entity_serde, postcard_utils,
replication::{
Replicated,
Expand Down Expand Up @@ -51,10 +51,6 @@ impl Plugin for ClientPlugin {
PreUpdate,
(
ClientSet::ReceivePackets,
(
ClientSet::ResetEvents.run_if(client_just_connected),
ClientSet::Reset.run_if(client_just_disconnected),
),
ClientSet::Receive,
ClientSet::Diagnostics,
)
Expand All @@ -65,13 +61,16 @@ impl Plugin for ClientPlugin {
(ClientSet::Send, ClientSet::SendPackets).chain(),
)
.add_systems(Startup, setup_channels)
.add_systems(
OnExit(ClientState::Connected),
reset.in_set(ClientSet::Reset),
)
Comment on lines +64 to +67
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not equivalent. client_just_disconnected also encompasses the connecting -> disconnected sequence.

.add_systems(
PreUpdate,
receive_replication
.in_set(ClientSet::Receive)
.run_if(client_connected),
)
.add_systems(PreUpdate, reset.in_set(ClientSet::Reset));
.run_if(in_state(ClientState::Connected)),
);
}

fn finish(&self, app: &mut App) {
Expand Down Expand Up @@ -156,11 +155,13 @@ pub(super) fn receive_replication(
}

fn reset(
mut client: ResMut<RepliconClient>,
mut update_tick: ResMut<ServerUpdateTick>,
mut entity_map: ResMut<ServerEntityMap>,
mut buffered_mutations: ResMut<BufferedMutations>,
stats: Option<ResMut<ClientReplicationStats>>,
) {
client.clear();
*update_tick = Default::default();
entity_map.clear();
buffered_mutations.clear();
Expand Down Expand Up @@ -727,7 +728,7 @@ pub enum ClientSet {
SendPackets,
/// Systems that reset queued server events.
///
/// Runs in [`PreUpdate`] immediately after the client connects to ensure client sessions have a fresh start.
/// Runs in [`OnEnter`] with [`ClientState::Connected`] to ensure client sessions have a fresh start.
///
/// This is a separate set from [`ClientSet::Reset`] because the reset requirements for events are different
/// from the replicon client internals.
Expand All @@ -736,7 +737,7 @@ pub enum ClientSet {
ResetEvents,
/// Systems that reset the client.
///
/// Runs in [`PreUpdate`] when the client just disconnected.
/// Runs in [`OnExit`] with [`ClientState::Disconnected`] (when the client just disconnected).
///
/// You may want to disable this set if you want to preserve client replication state across reconnects.
/// In that case, you need to manually repair the client state (or use something like
Expand Down
6 changes: 2 additions & 4 deletions src/client/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ use bevy::{
};

use super::{ClientReplicationStats, ClientSet};
use crate::shared::{
backend::replicon_client::RepliconClient, common_conditions::client_connected,
};
use crate::shared::backend::{ClientState, replicon_client::RepliconClient};

/// Plugin to write [`Diagnostics`] based on [`ClientReplicationStats`] every second.
///
Expand All @@ -21,7 +19,7 @@ impl Plugin for ClientDiagnosticsPlugin {
PreUpdate,
add_measurements
.in_set(ClientSet::Diagnostics)
.run_if(client_connected),
.run_if(in_state(ClientState::Connected)),
)
.register_diagnostic(
Diagnostic::new(RTT)
Expand Down
Loading