Skip to content

Commit

Permalink
limit player size to u32 and avoid usize in network messages
Browse files Browse the repository at this point in the history
  • Loading branch information
dignifiedquire committed Jun 18, 2024
1 parent 29357d6 commit c343d98
Show file tree
Hide file tree
Showing 6 changed files with 68 additions and 62 deletions.
38 changes: 21 additions & 17 deletions framework_crates/bones_framework/src/networking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,13 +154,13 @@ pub trait NetworkSocket: Sync + Send {
fn send_reliable(&self, target: SocketTarget, message: &[u8]);
/// Receive reliable messages from other players. The `usize` is the index of the player that
/// sent the message.
fn recv_reliable(&self) -> Vec<(usize, Vec<u8>)>;
fn recv_reliable(&self) -> Vec<(u32, Vec<u8>)>;
/// Close the connection.
fn close(&self);
/// Get the player index of the local player.
fn player_idx(&self) -> usize;
fn player_idx(&self) -> u32;
/// Get the player count for this network match.
fn player_count(&self) -> usize;
fn player_count(&self) -> u32;

/// Increment match id so messages from previous match that are still in flight
/// will be filtered out. Used when starting new session with existing socket.
Expand All @@ -170,7 +170,7 @@ pub trait NetworkSocket: Sync + Send {
/// The destination for a reliable network message.
pub enum SocketTarget {
/// Send to a specific player.
Player(usize),
Player(u32),
/// Broadcast to all players.
All,
}
Expand Down Expand Up @@ -211,10 +211,10 @@ pub struct GgrsSessionRunner<'a, InputTypes: NetworkInputConfig<'a>> {
pub session: P2PSession<GgrsConfig<InputTypes::Dense>>,

/// Local player idx.
pub player_idx: usize,
pub player_idx: u32,

/// Index of local player, computed from player_is_local
pub local_player_idx: usize,
pub local_player_idx: u32,

/// The frame time accumulator, used to produce a fixed refresh rate.
pub accumulator: f64,
Expand Down Expand Up @@ -250,9 +250,9 @@ pub struct GgrsSessionRunnerInfo {
/// The socket that will be converted into GGRS socket implementation.
pub socket: Socket,
/// The local player idx
pub player_idx: usize,
pub player_idx: u32,
/// the player count.
pub player_count: usize,
pub player_count: u32,

/// Max prediction window (max number of frames client may predict ahead of last confirmed frame)
/// `None` will use Bone's default.
Expand Down Expand Up @@ -318,7 +318,7 @@ where
.unwrap();

let mut builder = ggrs::SessionBuilder::new()
.with_num_players(info.player_count)
.with_num_players(info.player_count as usize)
.with_input_delay(local_input_delay)
.with_fps(network_fps)
.unwrap()
Expand All @@ -328,9 +328,13 @@ where
let local_player_idx = info.player_idx;
for i in 0..info.player_count {
if i == info.player_idx {
builder = builder.add_player(ggrs::PlayerType::Local, i).unwrap();
builder = builder
.add_player(ggrs::PlayerType::Local, i as usize)
.unwrap();
} else {
builder = builder.add_player(ggrs::PlayerType::Remote(i), i).unwrap();
builder = builder
.add_player(ggrs::PlayerType::Remote(i as usize), i as usize)
.unwrap();
}
}

Expand Down Expand Up @@ -387,11 +391,11 @@ where
self.input_collector.update_just_pressed();

// save local players dense input for use with ggrs
match player_inputs.get_control_source(self.local_player_idx) {
match player_inputs.get_control_source(self.local_player_idx as usize) {
Some(control_source) => {
let control = self
.input_collector
.get_control(self.local_player_idx, control_source);
.get_control(self.local_player_idx as usize, control_source);

self.last_player_input = control.get_dense_input();
},
Expand Down Expand Up @@ -474,13 +478,13 @@ where

if !self.local_input_disabled {
self.session
.add_local_input(self.local_player_idx, self.last_player_input)
.add_local_input(self.local_player_idx as usize, self.last_player_input)
.unwrap();
} else {
// If local input is disabled, we still submit a default value representing no-inputs.
// This way if input is disabled current inputs will not be held down indefinitely.
self.session
.add_local_input(self.local_player_idx, InputTypes::Dense::default())
.add_local_input(self.local_player_idx as usize, InputTypes::Dense::default())
.unwrap();
}

Expand Down Expand Up @@ -558,7 +562,7 @@ where
{
trace!(
"Net player({player_idx}) local: {}, status: {status:?}, input: {:?}",
self.local_player_idx == player_idx,
self.local_player_idx as usize == player_idx,
input
);
player_inputs.network_update(
Expand Down Expand Up @@ -623,7 +627,7 @@ where
let runner_info = GgrsSessionRunnerInfo {
socket: self.socket.clone(),
player_idx: self.player_idx,
player_count: self.session.num_players(),
player_count: self.session.num_players().try_into().unwrap(),
max_prediction_window: Some(self.session.max_prediction()),
local_input_delay: Some(self.local_input_delay),
};
Expand Down
26 changes: 14 additions & 12 deletions framework_crates/bones_framework/src/networking/lan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,9 @@ static PINGER: Lazy<Pinger> = Lazy::new(|| {
});

/// Host a server.
pub fn start_server(server: ServerInfo, player_count: usize) {
///
/// The number of players is limited to `u32::MAX`.
pub fn start_server(server: ServerInfo, player_count: u32) {
MDNS.register(server.service)
.expect("Could not register MDNS service.");
LAN_MATCHMAKER
Expand Down Expand Up @@ -295,7 +297,7 @@ async fn lan_matchmaker(

async fn lan_start_server(
matchmaker_channel: &BiChannelServer<LanMatchmakerRequest, LanMatchmakerResponse>,
mut player_count: usize,
mut player_count: u32,
) -> anyhow::Result<()> {
info!("Starting LAN server");
matchmaker_channel
Expand Down Expand Up @@ -366,7 +368,7 @@ async fn lan_start_server(
info!(%current_players, %target_players);

// If we're ready to start a match
if connections.len() == player_count - 1 {
if connections.len() == (player_count - 1) as usize {
info!("All players joined.");

let endpoint = get_network_endpoint().await;
Expand All @@ -390,12 +392,12 @@ async fn lan_start_server(
);
}

peers.push((i + 1, addr));
peers.push((u32::try_from(i + 1).unwrap(), addr));
});

let mut uni = conn.open_uni().await?;
uni.write_all(&postcard::to_vec::<_, 20>(&MatchmakerNetMsg::MatchReady {
player_idx: i + 1,
player_idx: (i + 1).try_into()?,
peers,
player_count,
})?)
Expand All @@ -406,7 +408,7 @@ async fn lan_start_server(
let connections = connections
.into_iter()
.enumerate()
.map(|(i, c)| (i + 1, c))
.map(|(i, c)| (u32::try_from(i + 1).unwrap(), c))
.collect();

// Send the connections to the game so that it can start the network match.
Expand Down Expand Up @@ -476,10 +478,10 @@ async fn lan_join_server(
enum MatchmakerNetMsg {
MatchReady {
/// The peers they have for the match, with the index in the array being the player index of the peer.
peers: Vec<(usize, NodeAddr)>,
peers: Vec<(u32, NodeAddr)>,
/// The player index of the player getting the message.
player_idx: usize,
player_count: usize,
player_idx: u32,
player_count: u32,
},
}

Expand All @@ -493,7 +495,7 @@ pub enum LanMatchmakerRequest {
/// Start matchmaker server
StartServer {
/// match player count
player_count: usize,
player_count: u32,
},
/// Join server
JoinServer {
Expand All @@ -517,9 +519,9 @@ pub enum LanMatchmakerResponse {
/// Lan socket to game
socket: Socket,
/// Local player index
player_idx: usize,
player_idx: u32,
/// Game player count
player_count: usize,
player_count: u32,
},
}

Expand Down
6 changes: 3 additions & 3 deletions framework_crates/bones_framework/src/networking/online.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,14 +150,14 @@ async fn search_for_game(
info!(%random_seed, %player_idx, player_count=%client_count, "Online match complete");

let peer_connections = establish_peer_connections(
player_idx as usize,
client_count as usize,
player_idx,
client_count,
player_ids,
None,
)
.await?;

let socket = Socket::new(player_idx as usize, peer_connections);
let socket = Socket::new(player_idx, peer_connections);

matchmaker_channel.try_send(OnlineMatchmakerResponse::GameStarting {
socket,
Expand Down
40 changes: 20 additions & 20 deletions framework_crates/bones_framework/src/networking/socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,17 @@ use super::{GameMessage, NetworkSocket, SocketTarget, RUNTIME};
#[derive(Debug, Clone)]
pub struct Socket {
///
pub connections: Vec<(usize, iroh_quinn::Connection)>,
pub ggrs_receiver: async_channel::Receiver<(usize, GameMessage)>,
pub reliable_receiver: async_channel::Receiver<(usize, Vec<u8>)>,
pub player_idx: usize,
pub player_count: usize,
pub connections: Vec<(u32, iroh_quinn::Connection)>,
pub ggrs_receiver: async_channel::Receiver<(u32, GameMessage)>,
pub reliable_receiver: async_channel::Receiver<(u32, Vec<u8>)>,
pub player_idx: u32,
pub player_count: u32,
/// ID for current match, messages received that do not match ID are dropped.
pub match_id: u8,
}

impl Socket {
pub fn new(player_idx: usize, connections: Vec<(usize, iroh_quinn::Connection)>) -> Self {
pub fn new(player_idx: u32, connections: Vec<(u32, iroh_quinn::Connection)>) -> Self {
let (ggrs_sender, ggrs_receiver) = async_channel::unbounded();
let (reliable_sender, reliable_receiver) = async_channel::unbounded();

Expand Down Expand Up @@ -122,15 +122,15 @@ impl Socket {

Self {
player_idx,
player_count: connections.iter().count() + 1,
player_count: (connections.len() + 1).try_into().unwrap(),
connections,
ggrs_receiver,
reliable_receiver,
match_id: 0,
}
}

fn get_connection(&self, idx: usize) -> &iroh_quinn::Connection {
fn get_connection(&self, idx: u32) -> &iroh_quinn::Connection {
debug_assert!(idx < self.player_count);
// TODO: if this is too slow, optimize storage
self.connections
Expand Down Expand Up @@ -181,7 +181,7 @@ impl NetworkSocket for Socket {
}
}

fn recv_reliable(&self) -> Vec<(usize, Vec<u8>)> {
fn recv_reliable(&self) -> Vec<(u32, Vec<u8>)> {
let mut messages = Vec::new();
while let Ok(message) = self.reliable_receiver.try_recv() {
messages.push(message);
Expand All @@ -199,11 +199,11 @@ impl NetworkSocket for Socket {
}
}

fn player_idx(&self) -> usize {
fn player_idx(&self) -> u32 {
self.player_idx
}

fn player_count(&self) -> usize {
fn player_count(&self) -> u32 {
self.player_count
}

Expand All @@ -213,11 +213,11 @@ impl NetworkSocket for Socket {
}

pub(super) async fn establish_peer_connections(
player_idx: usize,
player_count: usize,
peer_addrs: Vec<(usize, NodeAddr)>,
player_idx: u32,
player_count: u32,
peer_addrs: Vec<(u32, NodeAddr)>,
conn: Option<iroh_quinn::Connection>,
) -> anyhow::Result<Vec<(usize, iroh_quinn::Connection)>> {
) -> anyhow::Result<Vec<(u32, iroh_quinn::Connection)>> {
let mut peer_connections = Vec::new();
let had_og_conn = conn.is_some();
if let Some(conn) = conn {
Expand Down Expand Up @@ -245,11 +245,11 @@ pub(super) async fn establish_peer_connections(

// Receive the player index
let idx = {
let mut buf = [0; 1];
let mut buf = [0; 4];
let mut channel = conn.accept_uni().await?;
channel.read_exact(&mut buf).await?;

buf[0] as usize
u32::from_le_bytes(buf)
};

in_connections.push((idx, conn));
Expand All @@ -267,7 +267,7 @@ pub(super) async fn establish_peer_connections(

// Send player index
let mut channel = conn.open_uni().await?;
channel.write(&[player_idx as u8]).await?;
channel.write(&player_idx.to_le_bytes()).await?;
channel.finish().await?;

out_connections.push((i, conn));
Expand All @@ -286,7 +286,7 @@ impl ggrs::NonBlockingSocket<usize> for Socket {
message: msg.clone(),
match_id: self.match_id,
};
let conn = self.get_connection(*addr);
let conn = self.get_connection((*addr).try_into().unwrap());

let msg_bytes = postcard::to_allocvec(&msg).unwrap();
conn.send_datagram(Bytes::copy_from_slice(&msg_bytes[..]))
Expand All @@ -297,7 +297,7 @@ impl ggrs::NonBlockingSocket<usize> for Socket {
let mut messages = Vec::new();
while let Ok(message) = self.ggrs_receiver.try_recv() {
if message.1.match_id == self.match_id {
messages.push((message.0, message.1.message));
messages.push((message.0 as usize, message.1.message));
}
}
messages
Expand Down
8 changes: 4 additions & 4 deletions other_crates/bones_matchmaker/src/matchmaker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ async fn impl_matchmaker(ep: iroh_net::MagicEndpoint, conn: Connection) -> anyho
let result = async {
let message = postcard::to_allocvec(
&MatchmakerResponse::ClientCount(
members.len()
members.len().try_into()?
),
)?;
for conn in members {
Expand Down Expand Up @@ -145,7 +145,7 @@ async fn impl_matchmaker(ep: iroh_net::MagicEndpoint, conn: Connection) -> anyho

if !members_to_notify.is_empty() {
let message = postcard::to_allocvec(&MatchmakerResponse::ClientCount(
members_to_notify.len()
members_to_notify.len().try_into()?
))?;
for conn in members_to_notify {
let mut send = conn.open_uni().await?;
Expand All @@ -171,7 +171,7 @@ async fn impl_matchmaker(ep: iroh_net::MagicEndpoint, conn: Connection) -> anyho
);
}

player_ids.push((idx, addr));
player_ids.push((u32::try_from(idx)?, addr));
}

for (player_idx, conn) in members_to_join.into_iter().enumerate() {
Expand All @@ -180,7 +180,7 @@ async fn impl_matchmaker(ep: iroh_net::MagicEndpoint, conn: Connection) -> anyho
postcard::to_allocvec(&MatchmakerResponse::Success {
random_seed,
client_count: player_count,
player_idx: player_idx,
player_idx: player_idx.try_into()?,
player_ids: player_ids.clone(),
})?;
let mut send = conn.open_uni().await?;
Expand Down
Loading

0 comments on commit c343d98

Please sign in to comment.