use crate::automation::ServerStartupConfig; use crate::protocol::*; use crate::shared; use bevy::ecs::system::command; use bevy::prelude::*; use leafwing_input_manager::prelude::*; use lightyear::connection::client::Connected; use lightyear::connection::host::HostServer; use lightyear::prelude::server::*; use lightyear::prelude::*; use shared::SERVER_REPLICATION_INTERVAL; pub struct ServerPlugin; impl Plugin for ServerPlugin { fn build(&self, app: &mut App) { app.insert_resource(ReplicationMetadata::new(SERVER_REPLICATION_INTERVAL)); app.add_systems(Startup, startup); app.add_systems(FixedUpdate, movement); app.add_observer(handle_new_client); app.add_observer(handle_connected); } } /// When a new client tries to connect to a server, an entity is created for it with the `LinkOf` component. /// This entity represents the link between the server and that client. /// /// You can add additional components to update the link. In this case we will add a `ReplicationSender` that /// will enable us to replicate local entities to that client. pub(crate) fn handle_new_client(trigger: On, mut commands: Commands) { commands .entity(trigger.entity) .insert((ReplicationSender, Name::from("Client"))); } /// If the new client connects to the server, we want to spawn a new player entity for it. /// /// We have to react specifically on `Connected` because there is no guarantee that the connection request we /// received was valid. The server could reject the connection attempt for many reasons (server is full, packet is invalid, /// DDoS attempt, etc.). We want to start the replication only when the client is confirmed as connected. pub(crate) fn handle_connected( trigger: On, query: Query<&RemoteId, With>, mut commands: Commands, ) { let Ok(client_id) = query.get(trigger.entity) else { return; }; let client_id = client_id.0; let h = (((client_id.to_bits().wrapping_mul(30)) % 360) as f32) / 360.0; let s = 0.8; let l = 0.5; let color = Color::hsl(h, s, l); let entity = commands .spawn(( Player, PlayerPosition(Vec2::ZERO), PlayerColor(color), PlayerId(client_id), // we replicate the Player entity to all clients that are connected to this server Replicate::to_clients(NetworkTarget::All), PredictionTarget::to_clients(NetworkTarget::Single(client_id)), InterpolationTarget::to_clients(NetworkTarget::AllExceptSingle(client_id)), ControlledBy { owner: trigger.entity, lifetime: Default::default(), }, )) .id(); info!( "Create player entity {:?} for client {:?}", entity, client_id ); } /// Applies the received client inputs on the server so other clients can see too!! fn movement( timeline: Res, host_server: Query<(), With>, mut position_query: Query<( &mut PlayerPosition, &ActionState, Has, )>, ) { let is_host_server = !host_server.is_empty(); let _tick = timeline.tick(); for (position, inputs, predicted) in position_query.iter_mut() { if is_host_server && predicted { continue; } shared::shared_movement_behaviour(position, inputs); } } /// Starts the server wow fn startup(mut commands: Commands, config: Res) -> Result { info!("Starting up server"); if !config.auto_spawn { return Ok(()); } let server = commands .spawn(( NetcodeServer::new(NetcodeConfig::default()), LocalAddr(shared::SERVER_ADDR), #[cfg(all(feature = "webtransport", not(target_family = "wasm")))] WebTransportServerIo { certificate: webtransport_self_signed_certificate(), }, #[cfg(all(not(feature = "webtransport"), feature = "udp"))] ServerUdpIo::default(), )) .id(); commands.trigger(Start { entity: server }); Ok(()) }