Skip to content

Commit

Permalink
cargo fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
TheHellBox committed Mar 30, 2021
1 parent 2dd1309 commit 1820e9f
Show file tree
Hide file tree
Showing 11 changed files with 99 additions and 74 deletions.
10 changes: 4 additions & 6 deletions kissmp-bridge/src/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub async fn decode(data: &[u8], writer: tokio::sync::mpsc::Sender<Vec<u8>>) {
result.append(&mut data_left.to_le_bytes().to_vec());
result.append(&mut data.clone());
writer.send(result).await.unwrap();
},
}
_ => {
let json = serde_json::to_string(&decoded);
if let Ok(json) = json {
Expand All @@ -22,14 +22,12 @@ pub async fn decode(data: &[u8], writer: tokio::sync::mpsc::Sender<Vec<u8>>) {
result.append(&mut (data.len() as u32).to_le_bytes().to_vec());
result.append(&mut data);
writer.send(result).await.unwrap();
}
else{
} else {
println!("Error: {:?}", json);
}
},
}
}
}
else{
} else {
println!("Error bin: {:?}", decoded);
}
}
4 changes: 2 additions & 2 deletions kissmp-bridge/src/discord.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
pub async fn spawn_discord_rpc(mut discord_rx: std::sync::mpsc::Receiver<crate::DiscordState>) {
//let discord_rx = tokio_stream::wrappers::ReceiverStream::new(discord_rx);
std::thread::spawn(move || {
async move{
async move {
let mut drpc_client = discord_rpc_client::Client::new(771278096627662928);
drpc_client.start();
drpc_client
Expand All @@ -21,7 +21,7 @@ pub async fn spawn_discord_rpc(mut discord_rx: std::sync::mpsc::Receiver<crate::
let _ = drpc_client.set_activity(|activity| {
activity
.details(state.clone().server_name.unwrap())
//.state("[1/8]")
//.state("[1/8]")
.assets(|assets| assets.large_image("kissmp_logo"))
//.secrets(|secrets| secrets.game("Test").join("127.0.0.1:3698"))
});
Expand Down
8 changes: 3 additions & 5 deletions kissmp-bridge/src/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,11 @@ pub fn encode(data: &[u8]) -> Vec<u8> {
if let Ok(decoded) = decoded {
let binary = bincode::serialize::<shared::ClientCommand>(&decoded);
if let Ok(binary) = binary {
return binary
}
else{
return binary;
} else {
println!("e {:?}", binary);
}
}
else{
} else {
println!("e j {:?}", decoded);
}
vec![]
Expand Down
2 changes: 1 addition & 1 deletion kissmp-bridge/src/http_proxy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ pub async fn spawn_http_proxy(mut discord_tx: std::sync::mpsc::Sender<crate::Dis
// Master server proxy
//println!("start");
let server = tiny_http::Server::http("0.0.0.0:3693").unwrap();
loop{
loop {
for request in server.incoming_requests() {
let addr = request.remote_addr();
if addr.ip() != Ipv4Addr::new(127, 0, 0, 1) {
Expand Down
7 changes: 3 additions & 4 deletions kissmp-bridge/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
pub mod http_proxy;
pub mod discord;
pub mod decoder;
pub mod discord;
pub mod encoder;
pub mod http_proxy;

use futures::{StreamExt, TryStreamExt};
use std::net::{IpAddr, Ipv4Addr, SocketAddr, ToSocketAddrs};
Expand Down Expand Up @@ -130,8 +130,7 @@ pub async fn drive_receive(
let next = writer_rx.recv().await;
if let Some(next) = next {
let _ = writer.write_all(&next).await;
}
else{
} else {
break;
}
}
Expand Down
36 changes: 22 additions & 14 deletions kissmp-server/src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ use crate::*;

impl Server {
pub async fn on_client_event(&mut self, client_id: u32, event: IncomingEvent) {
use IncomingEvent::*;
use shared::ClientCommand::*;
use IncomingEvent::*;
match event {
ClientConnected(connection) => {
let player_name = connection.client_info_public.name.clone();
Expand Down Expand Up @@ -109,7 +109,9 @@ impl Server {
}
}
VehicleUpdate(data) => {
if let Some(server_id) = self.get_server_id_from_game_id(client_id, data.vehicle_id) {
if let Some(server_id) =
self.get_server_id_from_game_id(client_id, data.vehicle_id)
{
if let Some(vehicle) = self.vehicles.get_mut(&server_id) {
vehicle.data.position = data.transform.position;
vehicle.data.rotation = data.transform.rotation;
Expand All @@ -121,12 +123,15 @@ impl Server {
}
VehicleData(data) => {
// Remove old vehicle with the same ID
if let Some(server_id) = self.get_server_id_from_game_id(client_id, data.in_game_id)
if let Some(server_id) =
self.get_server_id_from_game_id(client_id, data.in_game_id)
{
self.remove_vehicle(server_id, Some(client_id)).await;
}
if let Some(client_vehicles) = self.vehicle_ids.get(&client_id) {
if (data.name == "unicicle") && (client_vehicles.len() as u8 >= self.max_vehicles_per_client) {
if (data.name == "unicicle")
&& (client_vehicles.len() as u8 >= self.max_vehicles_per_client)
{
return;
}
}
Expand Down Expand Up @@ -164,7 +169,8 @@ impl Server {
}
}
VehicleMetaUpdate(meta) => {
if let Some(server_id) = self.get_server_id_from_game_id(client_id, meta.vehicle_id)
if let Some(server_id) =
self.get_server_id_from_game_id(client_id, meta.vehicle_id)
{
if let Some(vehicle) = self.vehicles.get_mut(&server_id) {
vehicle.data.color = meta.colors_table[0];
Expand All @@ -186,7 +192,7 @@ impl Server {
if let Some(server_id) =
self.get_server_id_from_game_id(client_id, vehicle_id)
{
/* if let Some(vehicle) = self.vehicles.get_mut(&server_id) {
/* if let Some(vehicle) = self.vehicles.get_mut(&server_id) {
for (key, value) in &undefined_update.diff {
if let Some(electrics) = &mut vehicle.electrics {
electrics.undefined.insert(key.clone(), *value);
Expand All @@ -196,21 +202,23 @@ impl Server {
for (_, client) in &mut self.connections {
let _ = client
.ordered
.send(ServerCommand::ElectricsUndefinedUpdate(server_id, undefined_update.clone()))
.send(ServerCommand::ElectricsUndefinedUpdate(
server_id,
undefined_update.clone(),
))
.await;
}
}
}
Ping(ping) => {
let connection = self.connections
.get_mut(&client_id)
.unwrap();
connection
.client_info_public
.ping = ping as u32;
let connection = self.connections.get_mut(&client_id).unwrap();
connection.client_info_public.ping = ping as u32;
let start = std::time::SystemTime::now();
let since_the_epoch = start.duration_since(std::time::UNIX_EPOCH).unwrap();
let data = bincode::serialize(&shared::ServerCommand::Pong(since_the_epoch.as_secs_f64())).unwrap();
let data = bincode::serialize(&shared::ServerCommand::Pong(
since_the_epoch.as_secs_f64(),
))
.unwrap();
let _ = connection.conn.send_datagram(data.into());
}
VehicleChanged(id) => {
Expand Down
19 changes: 12 additions & 7 deletions kissmp-server/src/file_transfer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,18 @@ pub async fn transfer_file(
break;
}
let mut stream = connection.open_uni().await?;
send(&mut stream, &bincode::serialize(&shared::ServerCommand::FilePart(
file_name.to_string(),
buf[0..n].to_vec(),
chunk_n,
file_length,
n as u32
)).unwrap()).await?;
send(
&mut stream,
&bincode::serialize(&shared::ServerCommand::FilePart(
file_name.to_string(),
buf[0..n].to_vec(),
chunk_n,
file_length,
n as u32,
))
.unwrap(),
)
.await?;
stream.finish();
chunk_n += 1;
}
Expand Down
6 changes: 4 additions & 2 deletions kissmp-server/src/incoming.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use crate::*;
pub enum IncomingEvent {
ClientConnected(Connection),
ConnectionLost,
ClientCommand(shared::ClientCommand)
ClientCommand(shared::ClientCommand),
}

impl Server {
Expand All @@ -14,7 +14,9 @@ impl Server {
client_events_tx: &mut mpsc::Sender<(u32, IncomingEvent)>,
) -> anyhow::Result<()> {
let client_command = bincode::deserialize::<shared::ClientCommand>(&data)?;
client_events_tx.send((id, IncomingEvent::ClientCommand(client_command))).await?;
client_events_tx
.send((id, IncomingEvent::ClientCommand(client_command)))
.await?;
Ok(())
}
}
21 changes: 15 additions & 6 deletions kissmp-server/src/lua.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,11 @@ struct LuaVehicleData(VehicleData);
impl rlua::UserData for LuaTransform {
fn add_methods<'lua, M: rlua::UserDataMethods<'lua, Self>>(methods: &mut M) {
methods.add_method("getPosition", |_, this, _: ()| {
Ok(vec![this.0.position[0], this.0.position[1], this.0.position[2]])
Ok(vec![
this.0.position[0],
this.0.position[1],
this.0.position[2],
])
});
methods.add_method("getRotation", |_, this, _: ()| {
Ok(vec![
Expand All @@ -36,7 +40,11 @@ impl rlua::UserData for LuaTransform {
])
});
methods.add_method("getVelocity", |_, this, _: ()| {
Ok(vec![this.0.velocity[0], this.0.velocity[1], this.0.velocity[2]])
Ok(vec![
this.0.velocity[0],
this.0.velocity[1],
this.0.velocity[2],
])
});
methods.add_method("getAngularVelocity", |_, this, _: ()| {
Ok(vec![
Expand Down Expand Up @@ -68,12 +76,13 @@ impl rlua::UserData for Vehicle {
methods.add_method("getTransform", |_, this, _: ()| {
if let Some(transform) = &this.transform {
Ok(Some(LuaTransform(transform.clone())))
}
else{
} else {
Ok(None)
}
});
methods.add_method("getData", |_, this, _: ()| Ok(LuaVehicleData(this.data.clone())));
methods.add_method("getData", |_, this, _: ()| {
Ok(LuaVehicleData(this.data.clone()))
});
methods.add_method("remove", |lua_ctx, this, _: ()| {
let globals = lua_ctx.globals();
let sender: MpscChannelSender = globals.get("MPSC_CHANNEL_SENDER")?;
Expand Down Expand Up @@ -397,7 +406,7 @@ pub fn setup_lua() -> (rlua::Lua, mpsc::Receiver<LuaCommand>) {
Vec<f32>,
Vec<f32>,
)| {
Ok(LuaVehicleData(VehicleData{
Ok(LuaVehicleData(VehicleData {
parts_config,
in_game_id: 0,
color: [color[0], color[1], color[2], color[3]],
Expand Down
55 changes: 32 additions & 23 deletions kissmp-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ pub mod outgoing;
pub mod server_vehicle;

use incoming::IncomingEvent;
use shared::{ClientInfoPublic, ClientInfoPrivate, ServerCommand};
use server_vehicle::*;
use shared::{ClientInfoPrivate, ClientInfoPublic, ServerCommand};
use vehicle::*;

use anyhow::Error;
Expand Down Expand Up @@ -41,7 +41,10 @@ impl std::fmt::Debug for Connection {
}
impl Connection {
pub async fn send_chat_message(&mut self, message: String) {
let _ = self.ordered.send(ServerCommand::Chat(message.clone())).await;
let _ = self
.ordered
.send(ServerCommand::Chat(message.clone()))
.await;
}
pub async fn send_lua(&mut self, lua: String) {
let _ = self.ordered.send(ServerCommand::SendLua(lua.clone())).await;
Expand Down Expand Up @@ -72,9 +75,12 @@ struct Server {

impl Server {
async fn run(mut self) {
let mut ticks =
IntervalStream::new(tokio::time::interval(std::time::Duration::from_secs(1) / self.tickrate as u32)).fuse();
let mut send_info_ticks = IntervalStream::new(tokio::time::interval(std::time::Duration::from_secs(1))).fuse();
let mut ticks = IntervalStream::new(tokio::time::interval(
std::time::Duration::from_secs(1) / self.tickrate as u32,
))
.fuse();
let mut send_info_ticks =
IntervalStream::new(tokio::time::interval(std::time::Duration::from_secs(1))).fuse();

let (certificate_chain, key) = generate_certificate();
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), self.port);
Expand Down Expand Up @@ -201,11 +207,11 @@ impl Server {
let len = u32::from_le_bytes(buf) as usize;
let mut buf: Vec<u8> = vec![0; len];
stream.read_exact(&mut buf).await?;
let info: shared::ClientCommand = bincode::deserialize::<shared::ClientCommand>(&buf)?;
let info: shared::ClientCommand =
bincode::deserialize::<shared::ClientCommand>(&buf)?;
if let shared::ClientCommand::ClientInfo(info) = info {
Ok(info)
}
else{
} else {
Err(anyhow::Error::msg("Failed to fetch client info"))
}
} else {
Expand All @@ -232,24 +238,25 @@ impl Server {
0u32.into(),
format!(
"Client version mismatch.\nClient version: {:?}\nServer version: {:?}",
client_info.client_version, shared::VERSION
client_info.client_version,
shared::VERSION
)
.as_bytes(),
);
return;
}
let client_info_public = ClientInfoPublic{
let client_info_public = ClientInfoPublic {
name: client_info.name.clone(),
id: id,
current_vehicle: 0,
ping: 0
ping: 0,
};
let client_connection = Connection {
conn: connection_clone.clone(),
ordered: ordered_tx,
unreliable: unreliable_tx,
client_info_private: client_info,
client_info_public: client_info_public
client_info_public: client_info_public,
};
client_events_tx
.send((id, IncomingEvent::ClientConnected(client_connection)))
Expand All @@ -270,16 +277,18 @@ impl Server {
}
});

let server_info = bincode::serialize(&shared::ServerCommand::ServerInfo(shared::ServerInfo{
name: self.name.clone(),
player_count: self.connections.len() as u8,
client_id: id,
map: self.map.clone(),
tickrate: self.tickrate,
max_vehicles_per_client: self.max_vehicles_per_client,
mods: list_mods().unwrap_or(vec![]),
server_identifier: self.server_identifier.clone()
})).unwrap();
let server_info =
bincode::serialize(&shared::ServerCommand::ServerInfo(shared::ServerInfo {
name: self.name.clone(),
player_count: self.connections.len() as u8,
client_id: id,
map: self.map.clone(),
tickrate: self.tickrate,
max_vehicles_per_client: self.max_vehicles_per_client,
mods: list_mods().unwrap_or(vec![]),
server_identifier: self.server_identifier.clone(),
}))
.unwrap();
// Sender
tokio::spawn(async move {
let mut stream = connection.open_uni().await;
Expand Down Expand Up @@ -458,7 +467,7 @@ async fn main() {
lua_watcher_rx: watcher_rx,
lua_commands: receiver,
server_identifier: config.server_identifier,
tick: 0
tick: 0,
};
server.run().await;
}
Expand Down
Loading

0 comments on commit 1820e9f

Please sign in to comment.