Skip to content

Commit

Permalink
Add logs and cleanup for debugging
Browse files Browse the repository at this point in the history
  • Loading branch information
snendev committed Aug 15, 2024
1 parent 76ac9d6 commit 4ec28dd
Show file tree
Hide file tree
Showing 10 changed files with 77 additions and 26 deletions.
15 changes: 9 additions & 6 deletions apps/server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use bevy::{
};

use server::ServerPlugin;
use wordfight::WordFightPlugins;
use wordfight::{ActiveGamePlugin, WordFightPlugins};

fn main() {
App::default()
Expand All @@ -14,11 +14,14 @@ fn main() {
// need some wait duration so that async tasks are not entirely outcompeted by the main loop
std::time::Duration::from_millis(10),
),
WordFightPlugins.build().set(LogPlugin {
filter: "wgpu=error,naga=warn,h3=error".to_string(),
level: Level::INFO,
..Default::default()
}),
WordFightPlugins
.build()
.set(LogPlugin {
filter: "wgpu=error,naga=warn,h3=error".to_string(),
level: Level::INFO,
..Default::default()
})
.disable::<ActiveGamePlugin>(),
))
.add_plugins(ServerPlugin {
port: option_env!("SERVER_PORT").unwrap_or("7636").to_string(),
Expand Down
12 changes: 8 additions & 4 deletions apps/web/src/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,6 @@ impl Worker for BevyWorker {
}

fn update(&mut self, scope: &WorkerScope<Self>, message: Self::Message) {
#[cfg(feature = "log")]
log("Update".to_string());
if let Some(app) = self.game.as_mut() {
let WorkerUpdateMessage::Update = message else {
return;
Expand Down Expand Up @@ -85,9 +83,9 @@ impl Worker for BevyWorker {
}

fn received(&mut self, _: &WorkerScope<Self>, message: Self::Input, id: HandlerId) {
#[cfg(feature = "log")]
log(format!("Message received! {:?}", message));
if let Some(app) = self.game.as_mut() {
#[cfg(feature = "log")]
log(format!("Message received! {:?}", message));
self.subscriptions.insert(id);
let action: wordfight::Action = match message {
AppMessage::AddLetter(letter) => wordfight::Action::Append(letter),
Expand All @@ -104,6 +102,12 @@ impl Worker for BevyWorker {
.send_event(action.made_by(my_player, wordfight::PlayerSide::Left));

app.update();
} else {
#[cfg(feature = "log")]
log(format!(
"Discarding message received before app is ready: {:?}",
message
));
}
}
}
Expand Down
9 changes: 7 additions & 2 deletions plugins/active_game/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,9 @@ impl Plugin for ActiveGamePlugin {
}

impl ActiveGamePlugin {
fn set_active_game(mut commands: Commands, spawned_games: Query<Entity, Added<Game>>) {
for game in spawned_games.iter() {
fn set_active_game(mut commands: Commands, spawned_games: Query<Entity, With<Game>>) {
if let Some(game) = spawned_games.iter().next() {
info!("Setting active game: {game}");
commands.insert_resource(ActiveGame(game));
}
}
Expand All @@ -32,6 +33,7 @@ impl ActiveGamePlugin {
games: Query<(&GamePlayers, &Arena)>,
words: Query<(&Word, &Score)>,
updated_words: Query<(), Changed<Word>>,
updated_scores: Query<(), Changed<Score>>,
) {
let Some((game, players, arena)) = games
.get(active_game.0)
Expand All @@ -41,6 +43,8 @@ impl ActiveGamePlugin {
game.is_changed()
|| updated_words.contains(players.left)
|| updated_words.contains(players.right)
|| updated_scores.contains(players.left)
|| updated_scores.contains(players.right)
})
else {
return;
Expand All @@ -64,6 +68,7 @@ impl ActiveGamePlugin {
right_word,
right_score,
};
info!("Game update triggered: {event:?}");
commands.trigger(event.clone());
events.send(event);
}
Expand Down
16 changes: 14 additions & 2 deletions plugins/client/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
use bevy::{
ecs::world::Command,
prelude::{App, Commands, Plugin, Startup, World},
log::info,
prelude::{App, Commands, IntoSystem, Plugin, Startup, Update, World},
};

use bevy_replicon::core::common_conditions as network_conditions;
use bevy_replicon::prelude::RepliconChannels;
use bevy_replicon_renet2::{
renet2::{ConnectionConfig, RenetClient},
RenetChannelsExt,
RenetChannelsExt, RepliconRenetClientPlugin,
};

mod transport;
Expand All @@ -19,6 +21,8 @@ pub struct ClientPlugin {

impl Plugin for ClientPlugin {
fn build(&self, app: &mut App) {
app.add_plugins(RepliconRenetClientPlugin);

#[cfg(target_family = "wasm")]
app.add_plugins(transport::ClientTransportPlugin::new(
&self.server_origin,
Expand All @@ -28,6 +32,14 @@ impl Plugin for ClientPlugin {
app.add_systems(Startup, |mut commands: Commands| {
commands.add(ClientCommand::Connect);
});
app.add_systems(
Update,
network_conditions::client_just_connected.map(|just_connected| {
if just_connected {
info!("Connected!");
}
}),
);
}
}

Expand Down
2 changes: 1 addition & 1 deletion plugins/client/src/transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ impl ClientTransportPlugin {
.unwrap()
}

fn url(host: &str, port: &str, server_token: &str) -> Option<Self> {
fn _url(host: &str, port: &str, server_token: &str) -> Option<Self> {
format!("{host}:{port}")
.parse::<Url>()
.map(|url| Self {
Expand Down
9 changes: 8 additions & 1 deletion plugins/game/src/action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,17 @@ impl Action {
let test_string = format!("{}{}", word.to_string(), letter.to_string());
if dictionary.is_word_substring(test_string.as_str()) {
word.push(*letter);
info!("Added {letter}, making {word}");
} else {
info!(
"{word}{} is not in the dictionary",
letter.to_string().to_lowercase()
);
}
}
Delete => {
word.pop();
let removed_letter = word.pop();
info!("Removed {removed_letter:?} from {word}");
}
}
}
Expand Down
1 change: 1 addition & 0 deletions plugins/game/src/arena.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ impl Arena {
}
}

#[derive(Debug)]
pub enum Strike {
Score(PlayerSide),
Parry,
Expand Down
10 changes: 10 additions & 0 deletions plugins/game/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ impl WordFightGamePlugin {
event: action,
} in action_events.read()
{
info!("Client {client_id:?} took action: {action:?}");
let ActionEvent {
action,
side,
Expand All @@ -71,6 +72,7 @@ impl WordFightGamePlugin {
};

if **client == *client_id && *player_side == *side {
info!("Action {action:?} applied to {}", word.clone());
action.apply(&mut word, &dictionary);
}
}
Expand All @@ -84,11 +86,13 @@ impl WordFightGamePlugin {
let Ok([(left_word, _), (right_word, _)]) =
players.get_many([game_players.left, game_players.right])
else {
error!("Failed to find players {game_players:?}");
continue;
};
let Ok(strike) = arena.strike(left_word, right_word) else {
continue;
};
info!("Strike occurred: {strike:?}");
// contact has occurred!
// first determine whether anyone gets a point
match strike {
Expand All @@ -98,9 +102,14 @@ impl WordFightGamePlugin {
PlayerSide::Right => game_players.right,
};
let Ok((_, mut score)) = players.get_mut(winner) else {
error!("Failed to find winner! {winner}");
continue;
};
**score += 1;
info!(
"Player {winner} (side {winning_side:?} gains score! Total: {}",
**score
);
}
// both parry conditions result in no score change
Strike::OverRange | Strike::Parry => {}
Expand Down Expand Up @@ -200,6 +209,7 @@ impl SpawnGame {
.id();
commands.entity(player_one).insert(InGame(game));
commands.entity(player_two).insert(InGame(game));
info!("Spawned game {game} with players {player_one}, {player_two}");
}
}

Expand Down
27 changes: 18 additions & 9 deletions plugins/server/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
use bevy::prelude::{
App, Commands, Entity, EventReader, IntoSystemConfigs, Name, Plugin, Query, Res, ResMut,
Startup, Update, With, Without,
use bevy::{
log::info,
prelude::{
App, Commands, Entity, EventReader, IntoSystemConfigs, Name, Plugin, Query, Res, ResMut,
Startup, Update, With, Without,
},
};

use bevy_replicon::prelude::{ConnectedClients, Replicated, RepliconChannels, ServerEvent};
use bevy_replicon_renet2::{
renet2::{ConnectionConfig, RenetServer},
RenetChannelsExt,
RenetChannelsExt, RepliconRenetServerPlugin,
};

use game::{Client, InGame, SpawnGame};
Expand All @@ -21,6 +24,8 @@ pub struct ServerPlugin {

impl Plugin for ServerPlugin {
fn build(&self, app: &mut App) {
app.add_plugins(RepliconRenetServerPlugin);

app.add_plugins(ServerTransportPlugin {
port: self.port.clone(),
wt_tokens_port: self.wt_tokens_port.clone(),
Expand All @@ -42,6 +47,11 @@ impl ServerPlugin {
let server_channels_config = replicon_channels.get_server_configs();
let client_channels_config = replicon_channels.get_client_configs();

info!(
"Starting server! Server channels: {} | Client channels: {}",
server_channels_config.len(),
client_channels_config.len()
);
let server = RenetServer::new(ConnectionConfig {
server_channels_config,
client_channels_config,
Expand All @@ -54,9 +64,10 @@ impl ServerPlugin {
for [client1, client2] in clients
.iter()
.collect::<Vec<_>>()
.chunks(2)
.chunks_exact(2)
.map(|chunk| [chunk[0], chunk[1]])
{
info!("Found match: {client1} + {client2}");
commands.trigger(SpawnGame::new(7, client1, client2));
}
}
Expand All @@ -69,8 +80,7 @@ impl ServerPlugin {
for event in server_events.read() {
match event {
ServerEvent::ClientConnected { client_id } => {
#[cfg(feature = "log")]
bevy_log::info!("Player {} connected.", client_id.get());
info!("Player {} connected.", client_id.get());
// Spawn new player entity
commands.spawn((
Replicated,
Expand All @@ -82,8 +92,7 @@ impl ServerPlugin {
if let Some((player_entity, _)) =
clients.iter().find(|(_, id)| ***id == *client_id)
{
#[cfg(feature = "log")]
bevy_log::debug!("Player disconnected: {}", reason);
info!("Player disconnected: {}", reason);
commands.entity(player_entity).despawn();
}
}
Expand Down
2 changes: 1 addition & 1 deletion plugins/server/src/transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ struct NativeServerTransportPlugin {
}

impl NativeServerTransportPlugin {
fn url(host: &str, port: &str, tokens_port: &str) -> Self {
fn _url(host: &str, port: &str, tokens_port: &str) -> Self {
Self {
server_address: WebServerDestination::Url(format!("{host}:{port}").parse().unwrap()),
tokens_address: WebServerDestination::Url(
Expand Down

0 comments on commit 4ec28dd

Please sign in to comment.