mod backend;
pub(crate) mod fake;
mod parse;
#[cfg(feature = "steam")]
pub(crate) mod real;
#[cfg(test)]
mod tests;
pub use backend::{JoinSource, LobbyBackend, LobbyKind};
pub use parse::{connect_string, parse_connect_lobby};
use bevy_app::{App, AppExit, First, Last, Update};
use bevy_ecs::prelude::*;
use bevy_ecs::system::SystemParam;
use tracing::{info, warn};
use crate::{is_individual_steam_id64, BackendEvent, PumpedEvents, SteamBackendRes, SteamKitSystems, SteamLost};
pub const MAX_LOBBY_MEMBERS: u32 = 250;
#[derive(Resource, Clone, Debug)]
pub struct LobbySettings {
pub connect_prefix: String,
pub set_connect_presence: bool,
pub check_launch_args: bool,
}
impl Default for LobbySettings {
fn default() -> Self {
Self { connect_prefix: "+connect_lobby".to_string(), set_connect_presence: true, check_launch_args: true }
}
}
pub(crate) fn build(app: &mut App, settings: &LobbySettings) {
app.insert_resource(settings.clone())
.init_resource::<SteamLobby>()
.init_resource::<LobbyInternals>()
.add_message::<CreateLobby>()
.add_message::<JoinLobby>()
.add_message::<LeaveLobby>()
.add_message::<InviteFriend>()
.add_message::<SetRichPresence>()
.add_message::<ClearRichPresence>()
.add_message::<LobbyCreated>()
.add_message::<LobbyEntered>()
.add_message::<JoinRequested>()
.add_message::<LobbyLeft>()
.add_message::<InviteSent>()
.add_message::<LobbyError>()
.add_systems(First, apply_lobby_events.in_set(SteamKitSystems::Callbacks))
.add_systems(Update, (clear_on_steam_lost, handle_requests).chain().in_set(SteamKitSystems::Requests))
.add_systems(Last, leave_on_exit.in_set(SteamKitSystems::Requests));
}
#[derive(Resource, Clone, Debug, Default, PartialEq, Eq)]
pub struct SteamLobby {
pub current: Option<u64>,
pub pending_create: bool,
pub pending_join: Option<u64>,
pub generation: u32,
}
#[derive(Resource, Default, Debug)]
struct LobbyInternals {
pending_data: Vec<(String, String)>,
orphaned_creates: u32,
presence_set: bool,
launch_checked: bool,
}
#[derive(Message, Clone, Debug)]
pub struct CreateLobby {
pub kind: LobbyKind,
pub max_members: u32,
pub data: Vec<(String, String)>,
}
#[derive(Message, Clone, Debug)]
pub struct JoinLobby {
pub lobby: u64,
}
#[derive(Message, Clone, Debug, Default)]
pub struct LeaveLobby;
#[derive(Message, Clone, Debug)]
pub struct InviteFriend {
pub steam_id: u64,
}
#[derive(Message, Clone, Debug)]
pub struct SetRichPresence {
pub key: String,
pub value: Option<String>,
}
#[derive(Message, Clone, Debug, Default)]
pub struct ClearRichPresence;
#[derive(Message, Clone, Debug, PartialEq, Eq)]
pub struct LobbyCreated {
pub lobby: u64,
}
#[derive(Message, Clone, Debug, PartialEq, Eq)]
pub struct LobbyEntered {
pub lobby: u64,
}
#[derive(Message, Clone, Debug, PartialEq, Eq)]
pub struct JoinRequested {
pub lobby: u64,
pub from: u64,
pub source: JoinSource,
}
#[derive(Message, Clone, Debug, PartialEq, Eq)]
pub struct LobbyLeft {
pub lobby: u64,
}
#[derive(Message, Clone, Debug, PartialEq, Eq)]
pub struct InviteSent {
pub steam_id: u64,
pub lobby: u64,
pub ok: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LobbyErrorKind {
CreateFailed,
AlreadyInLobby,
JoinFailed,
NoLobby,
NoBackend,
InvalidSteamId,
InvalidRequest,
PresenceFailed,
}
#[derive(Message, Clone, Debug, PartialEq, Eq)]
pub struct LobbyError {
pub kind: LobbyErrorKind,
pub message: String,
}
impl LobbyError {
fn new(kind: LobbyErrorKind, message: impl Into<String>) -> Self {
Self { kind, message: message.into() }
}
}
#[derive(SystemParam)]
struct LobbyOut<'w> {
created: MessageWriter<'w, LobbyCreated>,
entered: MessageWriter<'w, LobbyEntered>,
join_requested: MessageWriter<'w, JoinRequested>,
left: MessageWriter<'w, LobbyLeft>,
invite_sent: MessageWriter<'w, InviteSent>,
error: MessageWriter<'w, LobbyError>,
}
#[derive(SystemParam)]
struct LobbyIn<'w, 's> {
create: MessageReader<'w, 's, CreateLobby>,
join: MessageReader<'w, 's, JoinLobby>,
leave: MessageReader<'w, 's, LeaveLobby>,
invite: MessageReader<'w, 's, InviteFriend>,
set_presence: MessageReader<'w, 's, SetRichPresence>,
clear_presence: MessageReader<'w, 's, ClearRichPresence>,
}
fn bump(state: &mut SteamLobby) {
state.generation = state.generation.wrapping_add(1);
}
fn lobby_api<'a>(backend: &'a Option<Res<'_, SteamBackendRes>>) -> Option<&'a dyn LobbyBackend> {
backend.as_ref().and_then(|b| b.0.lobby())
}
fn leave_all(backend: &dyn LobbyBackend, state: &mut SteamLobby, internals: &mut LobbyInternals, left: &mut MessageWriter<LobbyLeft>) {
let mut changed = false;
if let Some(lobby) = state.current.take() {
backend.leave_lobby(lobby);
left.write(LobbyLeft { lobby });
info!(">>> STEAM: left lobby {lobby}");
changed = true;
}
if state.pending_create {
state.pending_create = false;
internals.orphaned_creates = internals.orphaned_creates.saturating_add(1);
internals.pending_data.clear();
info!(">>> STEAM: abandoned a lobby create in flight (it will be left when it completes)");
changed = true;
}
if let Some(lobby) = state.pending_join.take() {
info!(">>> STEAM: abandoned joining lobby {lobby} (it will be left if the join completes)");
changed = true;
}
if internals.presence_set {
backend.clear_rich_presence();
internals.presence_set = false;
}
if changed {
bump(state);
}
}
fn apply_lobby_events(
backend: Option<Res<SteamBackendRes>>,
pumped: Res<PumpedEvents>,
settings: Res<LobbySettings>,
mut state: ResMut<SteamLobby>,
mut internals: ResMut<LobbyInternals>,
mut out: LobbyOut,
) {
let Some(backend) = backend.as_ref() else {
if !pumped.0.is_empty() {
warn!(">>> STEAM: backend removed before {} pumped event(s) were applied - dropped", pumped.0.len());
}
return;
};
let Some(lobby_api) = backend.0.lobby() else { return };
if settings.check_launch_args && !internals.launch_checked {
internals.launch_checked = true;
let text = launch_text(std::env::args_os().skip(1), &backend.0.launch_command_line());
if let Some(lobby) = parse_connect_lobby(&text, &settings.connect_prefix) {
info!(">>> STEAM: launched to join lobby {lobby}");
out.join_requested.write(JoinRequested { lobby, from: 0, source: JoinSource::LaunchArgs });
}
}
for ev in &pumped.0 {
apply_event(ev, lobby_api, &settings, &mut state, &mut internals, &mut out);
}
}
fn clear_on_steam_lost(
mut lost: MessageReader<SteamLost>,
mut state: ResMut<SteamLobby>,
mut internals: ResMut<LobbyInternals>,
mut left: MessageWriter<LobbyLeft>,
mut error: MessageWriter<LobbyError>,
) {
if lost.read().count() == 0 {
return;
}
let changed = state.current.is_some() || state.pending_create || state.pending_join.is_some();
if let Some(lobby) = state.current.take() {
info!(">>> STEAM: Steam is gone - lobby {lobby} dropped");
left.write(LobbyLeft { lobby });
}
if std::mem::take(&mut state.pending_create) {
warn!(">>> STEAM: Steam is gone - the lobby create in flight is answered NoBackend");
error.write(LobbyError::new(LobbyErrorKind::NoBackend, "create lobby: Steam is gone (SteamLost)"));
}
if let Some(lobby) = state.pending_join.take() {
warn!(">>> STEAM: Steam is gone - joining lobby {lobby} is answered NoBackend");
error.write(LobbyError::new(LobbyErrorKind::NoBackend, format!("join lobby {lobby}: Steam is gone (SteamLost)")));
}
let launch_checked = internals.launch_checked;
*internals = LobbyInternals { launch_checked, ..Default::default() };
if changed {
bump(&mut state);
}
}
pub(crate) fn launch_text(args: impl Iterator<Item = std::ffi::OsString>, launch_command_line: &str) -> String {
let mut text: String = args.filter_map(|a| a.into_string().ok()).collect::<Vec<_>>().join(" ");
text.push(' ');
text.push_str(launch_command_line);
text
}
fn apply_event(
ev: &BackendEvent,
backend: &dyn LobbyBackend,
settings: &LobbySettings,
state: &mut SteamLobby,
internals: &mut LobbyInternals,
out: &mut LobbyOut,
) {
match ev {
&BackendEvent::LobbyCreated { lobby } => {
if internals.orphaned_creates > 0 {
internals.orphaned_creates -= 1;
backend.leave_lobby(lobby);
info!(">>> STEAM: lobby {lobby} created after it was abandoned - left it");
} else if !state.pending_create {
backend.leave_lobby(lobby);
warn!(">>> STEAM: unexpected lobby {lobby} created - left it");
} else {
state.pending_create = false;
for (key, value) in std::mem::take(&mut internals.pending_data) {
if !backend.set_lobby_data(lobby, &key, &value) {
warn!(">>> STEAM: lobby {lobby}: could not set data {key:?}");
}
}
if !backend.set_lobby_joinable(lobby, true) {
warn!(">>> STEAM: lobby {lobby}: could not make it joinable");
}
if settings.set_connect_presence {
let connect = connect_string(&settings.connect_prefix, lobby);
if backend.set_rich_presence("connect", Some(&connect)) {
internals.presence_set = true;
} else {
warn!(">>> STEAM: lobby {lobby}: could not set rich presence connect");
}
}
state.current = Some(lobby);
bump(state);
info!(">>> STEAM: lobby {lobby} open");
out.created.write(LobbyCreated { lobby });
}
}
BackendEvent::LobbyCreateFailed { message } => {
if internals.orphaned_creates > 0 {
internals.orphaned_creates -= 1;
info!(">>> STEAM: abandoned lobby create failed: {message}");
} else if state.pending_create {
state.pending_create = false;
internals.pending_data.clear();
bump(state);
warn!(">>> STEAM: lobby create FAILED: {message}");
out.error.write(LobbyError::new(LobbyErrorKind::CreateFailed, format!("lobby create failed: {message}")));
}
}
&BackendEvent::LobbyEntered { lobby } => {
if state.pending_join == Some(lobby) {
state.pending_join = None;
state.current = Some(lobby);
bump(state);
info!(">>> STEAM: joined lobby {lobby}");
out.entered.write(LobbyEntered { lobby });
} else if state.current != Some(lobby) {
backend.leave_lobby(lobby);
info!(">>> STEAM: lobby {lobby} joined after it was abandoned - left it");
}
}
&BackendEvent::LobbyJoinFailed { lobby } => {
if state.pending_join == Some(lobby) {
state.pending_join = None;
bump(state);
warn!(">>> STEAM: joining lobby {lobby} FAILED");
out.error.write(LobbyError::new(LobbyErrorKind::JoinFailed, format!("could not join lobby {lobby}")));
}
}
&BackendEvent::LobbyJoinRequested { lobby, from } => {
if lobby == 0 {
warn!(">>> STEAM: ignored a lobby join request with lobby id 0");
return;
}
let from = if is_individual_steam_id64(from) { from } else { 0 };
info!(">>> STEAM: join requested (lobby invite) lobby {lobby} from {from}");
out.join_requested.write(JoinRequested { lobby, from, source: JoinSource::LobbyInvite });
}
BackendEvent::RichPresenceJoinRequested { from, connect } => match parse_connect_lobby(connect, &settings.connect_prefix) {
Some(lobby) => {
let from = if is_individual_steam_id64(*from) { *from } else { 0 };
info!(">>> STEAM: join requested (rich presence) lobby {lobby} from {from}");
out.join_requested.write(JoinRequested { lobby, from, source: JoinSource::RichPresence });
}
None => warn!(">>> STEAM: ignored rich-presence join with connect {connect:?}"),
},
#[allow(unreachable_patterns)]
_ => {}
}
}
fn handle_requests(
backend: Option<Res<SteamBackendRes>>,
settings: Res<LobbySettings>,
mut state: ResMut<SteamLobby>,
mut internals: ResMut<LobbyInternals>,
mut input: LobbyIn,
mut out: LobbyOut,
) {
let Some(backend) = lobby_api(&backend) else {
let no_backend = |what: &str| LobbyError::new(LobbyErrorKind::NoBackend, format!("{what}: Steam is not available"));
for _ in input.create.read() {
out.error.write(no_backend("create lobby"));
}
for _ in input.join.read() {
out.error.write(no_backend("join lobby"));
}
for _ in input.invite.read() {
out.error.write(no_backend("invite"));
}
for _ in input.set_presence.read() {
out.error.write(no_backend("rich presence"));
}
input.leave.clear();
input.clear_presence.clear();
return;
};
if input.leave.read().count() > 0 {
leave_all(backend, &mut state, &mut internals, &mut out.left);
}
for req in input.join.read() {
if req.lobby == 0 {
out.error.write(LobbyError::new(LobbyErrorKind::InvalidRequest, "lobby id 0"));
continue;
}
if state.current == Some(req.lobby) {
out.entered.write(LobbyEntered { lobby: req.lobby });
continue;
}
if state.pending_join == Some(req.lobby) {
continue;
}
leave_all(backend, &mut state, &mut internals, &mut out.left);
info!(">>> STEAM: joining lobby {}", req.lobby);
state.pending_join = Some(req.lobby);
bump(&mut state);
backend.join_lobby(req.lobby);
}
for req in input.create.read() {
if state.current.is_some() || state.pending_create || state.pending_join.is_some() {
warn!(">>> STEAM: create lobby refused - already in or joining a lobby");
out.error.write(LobbyError::new(LobbyErrorKind::AlreadyInLobby, "already in a lobby (or a lobby request is in flight)"));
continue;
}
let max = req.max_members.clamp(1, MAX_LOBBY_MEMBERS);
if max != req.max_members {
warn!(">>> STEAM: lobby max_members {} clamped to {max}", req.max_members);
}
info!(">>> STEAM: creating {:?} lobby (max {max})", req.kind);
state.pending_create = true;
internals.pending_data = req.data.clone();
bump(&mut state);
backend.create_lobby(req.kind, max);
}
for req in input.invite.read() {
if !is_individual_steam_id64(req.steam_id) {
out.error.write(LobbyError::new(LobbyErrorKind::InvalidSteamId, format!("not a SteamID64: {}", req.steam_id)));
continue;
}
let Some(lobby) = state.current else {
out.error.write(LobbyError::new(LobbyErrorKind::NoLobby, "not in a lobby - nothing to invite to"));
continue;
};
let connect = connect_string(&settings.connect_prefix, lobby);
let ok = backend.invite_to_game(req.steam_id, &connect);
info!(">>> STEAM: invite sent to {} (lobby {lobby}) ok={ok}", req.steam_id);
out.invite_sent.write(InviteSent { steam_id: req.steam_id, lobby, ok });
}
for req in input.set_presence.read() {
if backend.set_rich_presence(&req.key, req.value.as_deref()) {
if req.value.is_some() {
internals.presence_set = true;
}
} else {
out.error.write(LobbyError::new(LobbyErrorKind::PresenceFailed, format!("could not set rich presence {:?}", req.key)));
}
}
if input.clear_presence.read().count() > 0 {
backend.clear_rich_presence();
internals.presence_set = false;
}
}
fn leave_on_exit(
mut exit: MessageReader<AppExit>,
backend: Option<Res<SteamBackendRes>>,
mut state: ResMut<SteamLobby>,
mut internals: ResMut<LobbyInternals>,
mut left: MessageWriter<LobbyLeft>,
) {
if exit.read().count() == 0 {
return;
}
let Some(backend) = lobby_api(&backend) else { return };
leave_all(backend, &mut state, &mut internals, &mut left);
}