Skip to content
This repository has been archived by the owner on Jul 5, 2024. It is now read-only.

Commit

Permalink
v0.2.0 - split server/client types (#12)
Browse files Browse the repository at this point in the history
* refactor: refactor types for server/client, clear()
  • Loading branch information
simbleau authored Apr 8, 2024
1 parent d554f3b commit a070750
Show file tree
Hide file tree
Showing 18 changed files with 123 additions and 115 deletions.
17 changes: 17 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,25 @@ Subheadings to categorize changes are `added, changed, deprecated, removed, fixe

## Unreleased

## 0.2.0

### added

- The `RtcClient` and `RtcServer` system parameters (prev. `NetworkReader`/`NetworkWriter`) have new methods:
- `clear()` to clear all incoming messages in the buffer.

### changed

- To fix name conflicts with the `server` and `client` feature, the respective types have changed names.
- `RtcState` has changed to `RtcClientState` or `RtcServerState`, depending on the feature.
- `RtcStatus` has changed to `RtcClientStatus` or `RtcServerStatus`, depending on the feature.
- `NetworkReader`/`NetworkWriter` have been both merged and changed to `RtcClient` or `RtcServer` respectively.
- `RtcClient.read()` (previously `NetworkReader`) now returns a `Vec<_>` rather than a `Drain<'_, _>`.

## 0.1.1

### fixes

- Fixed blank README on crates.io

## 0.1.0
Expand Down
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ resolver = "2"

[workspace.package]
edition = "2021"
version = "0.1.1"
version = "0.2.0"
license = "MIT OR Apache-2.0"
description = "A client-server library designed over WebRTC for Bevy"
repository = "https://github.com/loopystudios/bevy_rtc"
Expand Down
16 changes: 8 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ Run the [demos](#demos) and [instructions](#instructions).

| bevy | bevy_rtc |
|-------|-------------|
| 0.13 | 0.1, main |
| 0.13 | 0.1-0.2, main |
| < 0.13| unsupported |

## Cargo features
Expand Down Expand Up @@ -124,10 +124,10 @@ pub enum MyPacket {
```rust
.add_systems(
Update,
|mut reader: NetworkReader<MyPacket>, mut writer: NetworkWriter<MyPacket>| {
for (peer_id, packet) in reader.read() {
|mut server: RtcServer<MyPacket>| {
for (peer_id, packet) in server.read() {
if let MyPacket::Ping = packet {
writer.reliable_to_peer(peer_id, MyPacket::Pong);
server.reliable_to_peer(peer_id, MyPacket::Pong);
}
}
})
Expand Down Expand Up @@ -168,8 +168,8 @@ pub enum MyPacket {
.add_systems(
Update,
{
|mut writer: NetworkWriter<PingPayload>| {
writer.reliable_to_host(PingPayload::Ping);
|mut client: RtcClient<PingPayload>| {
client.reliable_to_host(PingPayload::Ping);
}
}
.run_if(
Expand All @@ -179,8 +179,8 @@ pub enum MyPacket {
),
),
)
.add_systems(Update, |mut reader: NetworkReader<PingPayload>| {
for payload in reader.read() {
.add_systems(Update, |mut client: RtcClient<PingPayload>| {
for payload in client.read() {
if let PingPayload::Pong = payload {
info!("..Received pong!");
}
Expand Down
4 changes: 2 additions & 2 deletions bevy_rtc/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@ mod systems;
pub use events::{ConnectionRequest, RtcClientEvent};
pub use plugin::RtcClientPlugin;
pub use router::AddProtocolExt;
pub use state::{RtcClientStatus, RtcState};
pub use system_params::{NetworkReader, NetworkWriter};
pub use state::{RtcClientState, RtcClientStatus};
pub use system_params::RtcClient;
4 changes: 2 additions & 2 deletions bevy_rtc/src/client/plugin.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::{
systems, AddProtocolExt, ConnectionRequest, RtcClientEvent, RtcClientStatus, RtcState,
systems, AddProtocolExt, ConnectionRequest, RtcClientEvent, RtcClientState, RtcClientStatus,
};
use crate::{
events::SocketRecvEvent,
Expand All @@ -15,7 +15,7 @@ pub struct RtcClientPlugin;
impl Plugin for RtcClientPlugin {
fn build(&self, app: &mut App) {
app.add_event::<SocketRecvEvent>()
.insert_resource(RtcState::default())
.insert_resource(RtcClientState::default())
.add_bounded_protocol::<LatencyTracerPayload>(2)
.init_state::<RtcClientStatus>()
.add_event::<ConnectionRequest>()
Expand Down
4 changes: 2 additions & 2 deletions bevy_rtc/src/client/router/send.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::{
client::state::RtcState,
client::state::RtcClientState,
protocol::Payload,
socket::{RtcSocket, RELIABLE_CHANNEL_INDEX, UNRELIABLE_CHANNEL_INDEX},
};
Expand All @@ -22,7 +22,7 @@ impl<M: Payload> OutgoingMessages<M> {
pub(crate) fn send_payloads(
mut queue: ResMut<Self>,
mut socket: ResMut<RtcSocket>,
state: Res<RtcState>,
state: Res<RtcClientState>,
) {
if let Some(host) = state.host_id {
// Client is sending
Expand Down
2 changes: 1 addition & 1 deletion bevy_rtc/src/client/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub enum RtcClientStatus {
}

#[derive(Resource, Default)]
pub struct RtcState {
pub struct RtcClientState {
/// The socket address, used for connecting/reconnecting
pub addr: Option<String>,
/// The ID of the host
Expand Down
25 changes: 12 additions & 13 deletions bevy_rtc/src/client/system_params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ use crate::protocol::Payload;
use bevy::{ecs::system::SystemParam, prelude::*};

#[derive(SystemParam, Debug)]
pub struct NetworkReader<'w, M: Payload> {
incoming: ResMut<'w, IncomingMessages<M>>,
pub struct RtcClient<'w, M: Payload> {
pub(crate) incoming: ResMut<'w, IncomingMessages<M>>,
pub(crate) outgoing: ResMut<'w, OutgoingMessages<M>>,
}

impl<'w, M: Payload> NetworkReader<'w, M> {
/// Returns the capacity of this network reader.
impl<'w, M: Payload> RtcClient<'w, M> {
/// Returns the capacity of incoming messages.
pub fn capacity(&self) -> usize {
self.incoming.bound
}
Expand All @@ -23,18 +24,16 @@ impl<'w, M: Payload> NetworkReader<'w, M> {
self.incoming.messages.is_empty()
}

/// Consumes all messages in the buffer and iterate on them.
pub fn read(&mut self) -> std::collections::vec_deque::Drain<'_, M> {
self.incoming.messages.drain(..)
/// Clear all messages waiting in the buffer.
pub fn clear(&mut self) {
self.incoming.messages.clear()
}
}

#[derive(SystemParam, Debug)]
pub struct NetworkWriter<'w, M: Payload> {
pub(crate) outgoing: ResMut<'w, OutgoingMessages<M>>,
}
/// Consumes all messages in the buffer and iterate on them.
pub fn read(&mut self) -> Vec<M> {
self.incoming.messages.drain(..).collect()
}

impl<'w, M: Payload> NetworkWriter<'w, M> {
/// Send a payload to the host with reliability. The payload is created with
/// lazy behavior, only when the send rate allows.
pub fn reliable_to_host_with(&mut self, message_fn: impl Fn() -> M) {
Expand Down
32 changes: 17 additions & 15 deletions bevy_rtc/src/client/systems.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use super::{
events::{ConnectionRequest, RtcClientEvent},
state::{RtcClientStatus, RtcState},
NetworkReader, NetworkWriter,
state::{RtcClientState, RtcClientStatus},
RtcClient,
};
use crate::{
latency::{LatencyTracer, LatencyTracerPayload},
Expand All @@ -15,7 +15,7 @@ use bevy_matchbox::{
use instant::Duration;

/// Initialize the socket
pub(crate) fn init_socket(mut commands: Commands, socket_res: Res<RtcState>) {
pub(crate) fn init_socket(mut commands: Commands, socket_res: Res<RtcClientState>) {
if let Some(addr) = socket_res.addr.as_ref() {
debug!("connecting to: {addr:?}");

Expand All @@ -40,13 +40,13 @@ pub(crate) fn init_socket(mut commands: Commands, socket_res: Res<RtcState>) {
pub(crate) fn reset_socket(
mut commands: Commands,
tracer_query: Query<Entity, With<LatencyTracer>>,
mut state: ResMut<RtcState>,
mut state: ResMut<RtcClientState>,
) {
commands.close_socket::<RtcSocketPlurality>();
if let Ok(entity) = tracer_query.get_single() {
commands.entity(entity).despawn();
}
*state = RtcState {
*state = RtcClientState {
// Keep for reconnecting
addr: state.addr.clone(),
host_id: None,
Expand All @@ -59,7 +59,7 @@ pub(crate) fn reset_socket(
/// Reads and handles connection request events
pub(crate) fn connection_request_handler(
mut cxn_event_reader: EventReader<ConnectionRequest>,
mut state: ResMut<RtcState>,
mut state: ResMut<RtcClientState>,
mut next_connection_state: ResMut<NextState<RtcClientStatus>>,
current_connection_state: Res<State<RtcClientStatus>>,
mut event_wtr: EventWriter<RtcClientEvent>,
Expand Down Expand Up @@ -92,7 +92,7 @@ pub(crate) fn connection_request_handler(
/// Translates socket updates into bevy events
pub(crate) fn client_event_writer(
mut commands: Commands,
mut state: ResMut<RtcState>,
mut state: ResMut<RtcClientState>,
mut socket: ResMut<RtcSocket>,
mut event_wtr: EventWriter<RtcClientEvent>,
mut next_connection_state: ResMut<NextState<RtcClientStatus>>,
Expand Down Expand Up @@ -140,27 +140,29 @@ pub(crate) fn client_event_writer(
}
}

pub fn send_latency_tracers(state: Res<RtcState>, mut writer: NetworkWriter<LatencyTracerPayload>) {
pub fn send_latency_tracers(
state: Res<RtcClientState>,
mut client: RtcClient<LatencyTracerPayload>,
) {
let peer_id = state.id.expect("expected peer id");
writer.unreliable_to_host(LatencyTracerPayload::new(peer_id));
client.unreliable_to_host(LatencyTracerPayload::new(peer_id));
}

pub fn read_latency_tracers(
state: Res<RtcState>,
state: Res<RtcClientState>,
mut trace_query: Query<&mut LatencyTracer>,
mut reader: NetworkReader<LatencyTracerPayload>,
mut writer: NetworkWriter<LatencyTracerPayload>,
mut client: RtcClient<LatencyTracerPayload>,
) {
let host_id = state.host_id.expect("expected host id");
let peer_id = state.id.expect("expected peer id");
let mut tracer = trace_query.single_mut();

for payload in reader.read() {
for payload in client.read() {
if payload.from == peer_id {
tracer.process(payload);
} else if payload.from == host_id {
// Server time payloads get sent right back to the server
writer.unreliable_to_host(payload);
client.unreliable_to_host(payload);
}
// Process payloads we sent out
else {
Expand All @@ -174,7 +176,7 @@ pub fn read_latency_tracers(

pub fn calculate_latency(
time: Res<Time>,
mut state: ResMut<RtcState>,
mut state: ResMut<RtcClientState>,
mut tracer: Query<&mut LatencyTracer>,
) {
let mut tracer = tracer.single_mut();
Expand Down
4 changes: 2 additions & 2 deletions bevy_rtc/src/server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@ mod systems;
pub use events::RtcServerEvent;
pub use plugin::RtcServerPlugin;
pub use router::AddProtocolExt;
pub use state::{RtcServerStatus, RtcState};
pub use system_params::{NetworkReader, NetworkWriter};
pub use state::{RtcServerState, RtcServerStatus};
pub use system_params::RtcServer;
6 changes: 4 additions & 2 deletions bevy_rtc/src/server/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use bevy::{prelude::*, time::common_conditions::on_timer};
use instant::Duration;
use std::net::Ipv4Addr;

use super::{systems, AddProtocolExt, RtcServerEvent, RtcServerStatus, RtcState};
use super::{systems, AddProtocolExt, RtcServerEvent, RtcServerState, RtcServerStatus};

/// A plugin to serve a WebRTC server.
pub struct RtcServerPlugin {
Expand All @@ -21,7 +21,9 @@ impl Plugin for RtcServerPlugin {
.add_event::<RtcServerEvent>()
.add_bounded_protocol::<LatencyTracerPayload>(2)
.init_state::<RtcServerStatus>()
.insert_resource(RtcState::new((Ipv4Addr::UNSPECIFIED, self.port).into()))
.insert_resource(RtcServerState::new(
(Ipv4Addr::UNSPECIFIED, self.port).into(),
))
.add_systems(
Startup,
// We start a signaling server on localhost and the first peer
Expand Down
4 changes: 2 additions & 2 deletions bevy_rtc/src/server/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pub enum RtcServerStatus {
}

#[derive(Resource)]
pub struct RtcState {
pub struct RtcServerState {
/// The socket address bound
pub addr: SocketAddr,

Expand All @@ -35,7 +35,7 @@ pub struct RtcState {
pub(crate) smoothed_latencies: HashMap<PeerId, Option<Duration>>,
}

impl RtcState {
impl RtcServerState {
pub fn new(addr: SocketAddr) -> Self {
Self {
addr,
Expand Down
19 changes: 9 additions & 10 deletions bevy_rtc/src/server/system_params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@ use bevy_matchbox::prelude::PeerId;

/// A [`SystemParam`] for reading payloads of a particular type.
#[derive(SystemParam, Debug)]
pub struct NetworkReader<'w, M: Payload> {
incoming: ResMut<'w, IncomingMessages<M>>,
pub struct RtcServer<'w, M: Payload> {
pub(crate) incoming: ResMut<'w, IncomingMessages<M>>,
pub(crate) outgoing: ResMut<'w, OutgoingMessages<M>>,
}

impl<'w, M: Payload> NetworkReader<'w, M> {
/// Returns the capacity of this network reader.
impl<'w, M: Payload> RtcServer<'w, M> {
/// Returns the capacity of incoming messages.
pub fn capacity(&self) -> usize {
self.incoming.bound
}
Expand All @@ -35,14 +36,12 @@ impl<'w, M: Payload> NetworkReader<'w, M> {
v
})
}
}

#[derive(SystemParam, Debug)]
pub struct NetworkWriter<'w, M: Payload> {
pub(crate) outgoing: ResMut<'w, OutgoingMessages<M>>,
}
/// Clear all messages waiting in the buffer.
pub fn clear(&mut self) {
self.incoming.messages.clear()
}

impl<'w, M: Payload> NetworkWriter<'w, M> {
/// Send a payload to all connected peers with reliability.
pub fn reliable_to_all(&mut self, message: M) {
self.outgoing.reliable_to_all.push(message);
Expand Down
Loading

0 comments on commit a070750

Please sign in to comment.