kubi/kubi-server/src/client.rs

82 lines
2.4 KiB
Rust
Raw Normal View History

2023-05-19 06:22:32 -05:00
use glam::Mat4;
use shipyard::{Component, EntityId, Unique, AllStoragesView, UniqueView, NonSendSync, View, ViewMut, Get, IntoIter};
use hashbrown::HashMap;
use uflow::SendMode;
2023-03-08 20:30:37 -06:00
use std::net::SocketAddr;
2023-05-19 06:22:32 -05:00
use kubi_shared::{
networking::{
2024-02-01 09:00:32 -06:00
client::{ClientIdMap, Client},
messages::{ClientToServerMessage, ServerToClientMessage, ClientToServerMessageType},
channels::Channel
2023-05-19 06:22:32 -05:00
},
transform::Transform
};
use crate::{
2024-02-01 09:00:32 -06:00
server::{ServerEvents, UdpServer},
2023-05-19 06:22:32 -05:00
util::check_message_auth
};
2023-02-11 17:37:24 -06:00
2023-03-08 20:30:37 -06:00
#[derive(Component, Clone, Copy)]
pub struct ClientAddress(pub SocketAddr);
2023-03-08 20:30:37 -06:00
#[derive(Unique, Default)]
pub struct ClientAddressMap(pub HashMap<SocketAddr, EntityId>);
impl ClientAddressMap {
pub fn new() -> Self { Self::default() }
}
pub fn init_client_maps(
storages: AllStoragesView
) {
storages.add_unique(ClientIdMap::new());
storages.add_unique(ClientAddressMap::new());
}
pub fn sync_client_positions(
server: NonSendSync<UniqueView<UdpServer>>,
events: UniqueView<ServerEvents>,
addr_map: UniqueView<ClientAddressMap>,
clients: View<Client>,
mut transforms: ViewMut<Transform>,
addrs: View<ClientAddress>,
) {
for event in &events.0 {
2024-02-01 09:00:32 -06:00
let Some(message) = check_message_auth
::<{ClientToServerMessageType::PositionChanged as u8}>
(&server, event, &clients, &addr_map) else { continue };
2023-05-19 06:22:32 -05:00
let ClientToServerMessage::PositionChanged { position, velocity: _, direction } = message.message else {
unreachable!()
};
//log movement (annoying duh)
log::debug!("dbg: player moved id: {} coords: {} quat: {}", message.client_id, position, direction);
//Apply position to server-side client
2023-05-19 06:22:32 -05:00
let mut trans = (&mut transforms).get(message.entity_id).unwrap();
trans.0 = Mat4::from_rotation_translation(direction, position);
//Transmit the change to other players
for (other_client, other_client_address) in (&clients, &addrs).iter() {
if other_client.0 == message.client_id {
continue
}
let Some(client) = server.0.client(&other_client_address.0) else {
log::error!("Client with address not found");
continue
};
client.borrow_mut().send(
postcard::to_allocvec(
&ServerToClientMessage::PlayerPositionChanged {
client_id: message.client_id,
position,
direction
}
2024-02-01 09:00:32 -06:00
).unwrap().into_boxed_slice(),
Channel::Move as usize,
SendMode::Reliable
);
}
}
}