Something went wrong. Try again.
cozy factory game
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125use 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<Add, LinkOf>, 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<Add, Connected>, query: Query<&RemoteId, With<ClientOf>>, 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<LocalTimeline>, host_server: Query<(), With<HostServer>>, mut position_query: Query<( &mut PlayerPosition, &ActionState<PlayerActions>, Has<Predicted>, )>,) { 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 wowfn startup(mut commands: Commands, config: Res<ServerStartupConfig>) -> 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(())}