code cleanup

This commit is contained in:
Sardelka
2022-07-20 17:50:01 +08:00
parent bbe0b21aa4
commit 71ecdbd5b9
37 changed files with 1568 additions and 1650 deletions

View File

@ -1,8 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RageCoop.Client
{
@ -21,7 +18,7 @@ namespace RageCoop.Client
CheckProjectiles,
GetAllEntities,
Receive,
ProjectilesTotal,
}
internal static class Debug
{
@ -29,7 +26,7 @@ namespace RageCoop.Client
private static int _lastNfHandle;
static Debug()
{
foreach(TimeStamp t in Enum.GetValues(typeof(TimeStamp)))
foreach (TimeStamp t in Enum.GetValues(typeof(TimeStamp)))
{
TimeStamps.Add(t, 0);
}
@ -37,7 +34,7 @@ namespace RageCoop.Client
public static string Dump(this Dictionary<TimeStamp, long> d)
{
string s = "";
foreach(KeyValuePair<TimeStamp, long> kvp in d)
foreach (KeyValuePair<TimeStamp, long> kvp in d)
{
s+=kvp.Key+":"+kvp.Value+"\n";
}

View File

@ -1,20 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GTA;
using GTA;
using GTA.Math;
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
using System.Windows.Forms;
namespace RageCoop.Client
{
internal class DevTool:Script
internal class DevTool : Script
{
public static Vehicle ToMark;
public static bool UseSecondary=false;
public static bool UseSecondary = false;
public static int Current = 0;
public static int Secondary = 0;
public static MuzzleDir Direction = MuzzleDir.Forward;
@ -27,7 +23,8 @@ namespace RageCoop.Client
private void OnKeyDown(object sender, KeyEventArgs e)
{
if (ToMark==null||(!ToMark.Exists())) { return; }
if (DevToolMenu.Menu.SelectedItem==DevToolMenu.boneIndexItem) {
if (DevToolMenu.Menu.SelectedItem==DevToolMenu.boneIndexItem)
{
switch (e.KeyCode)
{
@ -78,7 +75,7 @@ namespace RageCoop.Client
}
private static void OnTick(object sender, EventArgs e)
{
if(ToMark == null || !ToMark.Exists()){ return;}
if (ToMark == null || !ToMark.Exists()) { return; }
Update();
Draw(Current);
if (UseSecondary)
@ -172,13 +169,13 @@ namespace RageCoop.Client
}
}
internal enum MuzzleDir:byte
internal enum MuzzleDir : byte
{
Forward=0,
Forward = 0,
Right = 1,
Up=2,
Backward=3,
Up = 2,
Backward = 3,
Left = 4,
Down=5,
Down = 5,
}
}

View File

@ -1,16 +1,14 @@
using System;
using GTA;
using GTA.Math;
using GTA.Native;
using RageCoop.Client.Menus;
using RageCoop.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Drawing;
using System.Threading;
using System.Diagnostics;
using RageCoop.Client.Menus;
using RageCoop.Core;
using GTA;
using GTA.Native;
using GTA.Math;
namespace RageCoop.Client
{
@ -23,12 +21,12 @@ namespace RageCoop.Client
private bool _gameLoaded = false;
internal static readonly string CurrentVersion = "V0_5_0";
internal static int LocalPlayerID=0;
internal static int LocalPlayerID = 0;
internal static RelationshipGroup SyncedPedsGroup;
internal static new Settings Settings = null;
internal static Scripting.BaseScript BaseScript=new Scripting.BaseScript();
internal static Scripting.BaseScript BaseScript = new Scripting.BaseScript();
#if !NON_INTERACTIVE
#endif
@ -38,7 +36,7 @@ namespace RageCoop.Client
internal static ulong Ticked = 0;
internal static Vector3 PlayerPosition;
internal static Scripting.Resources Resources=null;
internal static Scripting.Resources Resources = null;
private static List<Func<bool>> QueuedActions = new List<Func<bool>>();
/// <summary>
/// Don't use it!
@ -90,7 +88,7 @@ namespace RageCoop.Client
#endif
MainChat = new Chat();
Tick += OnTick;
Tick += (s,e) => { Scripting.API.Events.InvokeTick(); };
Tick += (s, e) => { Scripting.API.Events.InvokeTick(); };
KeyDown += OnKeyDown;
KeyDown+=(s, e) => { Scripting.API.Events.InvokeKeyDown(s, e); };
KeyUp+=(s, e) => { Scripting.API.Events.InvokeKeyUp(s, e); };
@ -102,10 +100,12 @@ namespace RageCoop.Client
#if DEBUG
#endif
public static Ped P;
public static float FPS;
private void OnTick(object sender, EventArgs e)
{
var P = Game.Player.Character;
P= Game.Player.Character;
FPS=Game.FPS;
PlayerPosition=P.Position;
if (Game.IsLoading)
{
@ -114,7 +114,7 @@ namespace RageCoop.Client
else if (!_gameLoaded && (_gameLoaded = true))
{
#if !NON_INTERACTIVE
GTA.UI.Notification.Show(GTA.UI.NotificationIcon.AllPlayersConf, "RAGECOOP","Welcome!", $"Press ~g~{Main.Settings.MenuKey}~s~ to open the menu.");
GTA.UI.Notification.Show(GTA.UI.NotificationIcon.AllPlayersConf, "RAGECOOP", "Welcome!", $"Press ~g~{Main.Settings.MenuKey}~s~ to open the menu.");
#endif
}
@ -350,7 +350,7 @@ namespace RageCoop.Client
QueuedActions.Remove(action);
}
}
catch(Exception ex)
catch (Exception ex)
{
Logger.Error(ex);
QueuedActions.Remove(action);
@ -374,7 +374,7 @@ namespace RageCoop.Client
{
lock (QueuedActions)
{
QueuedActions.Add(() => { a(); return true; }) ;
QueuedActions.Add(() => { a(); return true; });
}
}
/// <summary>

View File

@ -1,10 +1,8 @@
using GTA;
using System.Drawing;
using LemonUI;
using LemonUI.Menus;
using LemonUI.Scaleform;
using System.Drawing;
namespace RageCoop.Client.Menus
{
@ -19,7 +17,7 @@ namespace RageCoop.Client.Menus
UseMouse = false,
Alignment = Main.Settings.FlipMenu ? GTA.UI.Alignment.Right : GTA.UI.Alignment.Left
};
public static PopUp PopUp=new PopUp()
public static PopUp PopUp = new PopUp()
{
Title="",
Prompt="",
@ -31,14 +29,15 @@ namespace RageCoop.Client.Menus
public static NativeMenu LastMenu { get; set; } = Menu;
#region ITEMS
private static readonly NativeItem _usernameItem = new NativeItem("Username") { AltTitle = Main.Settings.Username };
private static readonly NativeItem _passwordItem = new NativeItem("Password") { AltTitle = new string('*',Main.Settings.Password.Length) };
private static readonly NativeItem _passwordItem = new NativeItem("Password") { AltTitle = new string('*', Main.Settings.Password.Length) };
public static readonly NativeItem ServerIpItem = new NativeItem("Server IP") { AltTitle = Main.Settings.LastServerAddress };
internal static readonly NativeItem _serverConnectItem = new NativeItem("Connect");
private static readonly NativeItem _aboutItem = new NativeItem("About", "~y~SOURCE~s~~n~" +
"https://github.com/RAGECOOP~n~" +
"~y~VERSION~s~~n~" +
Main.CurrentVersion.Replace("_", ".")) { LeftBadge = new LemonUI.Elements.ScaledTexture("commonmenu", "shop_new_star") };
Main.CurrentVersion.Replace("_", "."))
{ LeftBadge = new LemonUI.Elements.ScaledTexture("commonmenu", "shop_new_star") };
#endregion
@ -84,7 +83,7 @@ namespace RageCoop.Client.Menus
}
public static bool ShowPopUp(string prompt, string title,string subtitle,string error,bool showbackground)
public static bool ShowPopUp(string prompt, string title, string subtitle, string error, bool showbackground)
{
PopUp.Prompt=prompt;
PopUp.Title=title;

View File

@ -1,18 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LemonUI;
using GTA;
using LemonUI.Menus;
using GTA;
using System.Drawing;
namespace RageCoop.Client
{
internal static class DebugMenu
{
public static NativeMenu Menu = new NativeMenu("RAGECOOP", "Debug", "Debug settings") {
public static NativeMenu Menu = new NativeMenu("RAGECOOP", "Debug", "Debug settings")
{
UseMouse = false,
Alignment = Main.Settings.FlipMenu ? GTA.UI.Alignment.Right : GTA.UI.Alignment.Left
};
@ -21,15 +16,15 @@ namespace RageCoop.Client
UseMouse = false,
Alignment = Main.Settings.FlipMenu ? GTA.UI.Alignment.Right : GTA.UI.Alignment.Left
};
private static NativeItem d1=new NativeItem("PositionPrediction");
private static NativeItem d1 = new NativeItem("PositionPrediction");
static DebugMenu()
{
Menu.Banner.Color = Color.FromArgb(225, 0, 0, 0);
Menu.Title.Color = Color.FromArgb(255, 165, 0);
d1.Activated+=(sender,e) =>
d1.Activated+=(sender, e) =>
{
try{ SyncParameters.PositioinPredictionDefault =float.Parse(Game.GetUserInput(WindowTitle.EnterMessage20, SyncParameters.PositioinPredictionDefault.ToString(), 20));}
try { SyncParameters.PositioinPredictionDefault =float.Parse(Game.GetUserInput(WindowTitle.EnterMessage20, SyncParameters.PositioinPredictionDefault.ToString(), 20)); }
catch { }
Update();
};
@ -37,7 +32,7 @@ namespace RageCoop.Client
Menu.Add(d1);
Menu.AddSubMenu(DiagnosticMenu);
Menu.Opening+=(sender, e) =>Update();
Menu.Opening+=(sender, e) => Update();
DiagnosticMenu.Opening+=(sender, e) =>
{
DiagnosticMenu.Clear();

View File

@ -1,10 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GTA;
using LemonUI.Menus;
using GTA;
using System;
using System.Drawing;
namespace RageCoop.Client
@ -18,7 +14,7 @@ namespace RageCoop.Client
};
private static NativeCheckboxItem enableItem = new NativeCheckboxItem("Enable");
private static NativeCheckboxItem enableSecondaryItem = new NativeCheckboxItem("Secondary","Enable if this vehicle have two muzzles");
private static NativeCheckboxItem enableSecondaryItem = new NativeCheckboxItem("Secondary", "Enable if this vehicle have two muzzles");
public static NativeItem boneIndexItem = new NativeItem("Current bone index");
public static NativeItem secondaryBoneIndexItem = new NativeItem("Secondary bone index");
public static NativeItem clipboardItem = new NativeItem("Copy to clipboard");

View File

@ -1,9 +1,9 @@
using System;
using System.Net;
using System.Drawing;
using System.Collections.Generic;
using LemonUI.Menus;
using Newtonsoft.Json;
using LemonUI.Menus;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Net;
using System.Threading;
namespace RageCoop.Client.Menus
@ -59,7 +59,7 @@ namespace RageCoop.Client.Menus
Menu.Add(ResultItem = new NativeItem("Loading..."));
// Prevent freezing
GetServersThread=new Thread(()=> GetAllServers());
GetServersThread=new Thread(() => GetAllServers());
GetServersThread.Start();
};
Menu.Closing += (object sender, System.ComponentModel.CancelEventArgs e) =>

View File

@ -1,8 +1,8 @@
using System.Drawing;
using System;
using System.Windows.Forms;
using GTA;
using GTA;
using LemonUI.Menus;
using System;
using System.Drawing;
using System.Windows.Forms;
namespace RageCoop.Client.Menus
{
@ -23,9 +23,9 @@ namespace RageCoop.Client.Menus
private static readonly NativeCheckboxItem _showNetworkInfoItem = new NativeCheckboxItem("Show Network Info", Networking.ShowNetworkInfo);
private static NativeItem _menuKey = new NativeItem("Menu Key","The key to open menu", Main.Settings.MenuKey.ToString());
private static NativeItem _menuKey = new NativeItem("Menu Key", "The key to open menu", Main.Settings.MenuKey.ToString());
private static NativeItem _passengerKey = new NativeItem("Passenger Key", "The key to enter a vehicle as passenger", Main.Settings.PassengerKey.ToString());
private static NativeItem _vehicleSoftLimit = new NativeItem("Vehicle limit (soft)", "The game won't spawn more NPC traffic if the limit is exceeded. \n-1 for unlimited (not recommended).",Main.Settings.WorldVehicleSoftLimit.ToString());
private static NativeItem _vehicleSoftLimit = new NativeItem("Vehicle limit (soft)", "The game won't spawn more NPC traffic if the limit is exceeded. \n-1 for unlimited (not recommended).", Main.Settings.WorldVehicleSoftLimit.ToString());
/// <summary>
/// Don't use it!
@ -102,7 +102,7 @@ namespace RageCoop.Client.Menus
public static void DisableTrafficCheckboxChanged(object a, System.EventArgs b)
{
Main.Settings.DisableTraffic = _disableTrafficItem.Checked;
Util.SaveSettings() ;
Util.SaveSettings();
}
public static void FlipMenuCheckboxChanged(object a, System.EventArgs b)

View File

@ -1,14 +1,10 @@
using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ICSharpCode.SharpZipLib.Zip;
using LemonUI.Menus;
using System.Web;
using System.Net;
using System;
using System.Drawing;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using System.Net;
using System.Threading.Tasks;
namespace RageCoop.Client.Menus
{
@ -16,7 +12,7 @@ namespace RageCoop.Client.Menus
{
public static bool IsUpdating { get; private set; } = false;
private static NativeItem _updatingItem = new NativeItem("Updating...");
private static NativeItem _downloadItem = new NativeItem("Download","Download and update to latest nightly");
private static NativeItem _downloadItem = new NativeItem("Download", "Download and update to latest nightly");
private static string _downloadPath = Path.Combine(Main.Settings.DataDirectory, "RageCoop.Client.zip");
public static NativeMenu Menu = new NativeMenu("Update", "Update", "Download and install latest nightly build from GitHub")
@ -68,7 +64,7 @@ namespace RageCoop.Client.Menus
{
_updatingItem.AltTitle="Installing...";
});
new FastZip().ExtractZip(_downloadPath, "Scripts",FastZip.Overwrite.Always, null,null,null,true);
new FastZip().ExtractZip(_downloadPath, "Scripts", FastZip.Overwrite.Always, null, null, null, true);
Main.QueueAction(() =>
{
Util.Reload();

View File

@ -1,10 +1,9 @@
using System;
using GTA;
using GTA.Native;
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using RageCoop.Core;
using GTA;
using GTA.Native;
namespace RageCoop.Client
{

View File

@ -1,8 +1,8 @@
using System.IO;
using System.Linq;
using System.Collections.Generic;
using RageCoop.Core;
using RageCoop.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RageCoop.Client
{
@ -22,7 +22,7 @@ namespace RageCoop.Client
return new Packets.FileTransferResponse()
{
ID= fr.ID,
Response=AddFile(fr.ID,fr.Name,fr.FileLength) ? FileResponse.NeedToDownload : FileResponse.AlreadyExists
Response=AddFile(fr.ID, fr.Name, fr.FileLength) ? FileResponse.NeedToDownload : FileResponse.AlreadyExists
};
});
Networking.RequestHandlers.Add(PacketType.FileTransferComplete, (data) =>
@ -44,10 +44,10 @@ namespace RageCoop.Client
{
try
{
Main.Resources.Load(ResourceFolder,_resources.ToArray());
Main.Resources.Load(ResourceFolder, _resources.ToArray());
return new Packets.FileTransferResponse() { ID=0, Response=FileResponse.Loaded };
}
catch(Exception ex)
catch (Exception ex)
{
Main.Logger.Error("Error occurred when loading server resource:");
@ -56,9 +56,11 @@ namespace RageCoop.Client
}
});
}
public static string ResourceFolder {
get {
return Path.Combine(Main.Settings.DataDirectory,"Resources", Main.Settings.LastServerAddress.Replace(":", "."));
public static string ResourceFolder
{
get
{
return Path.Combine(Main.Settings.DataDirectory, "Resources", Main.Settings.LastServerAddress.Replace(":", "."));
}
}
private static readonly Dictionary<int, DownloadFile> InProgressDownloads = new Dictionary<int, DownloadFile>();
@ -173,7 +175,7 @@ namespace RageCoop.Client
}
}
internal class DownloadFile: IDisposable
internal class DownloadFile : IDisposable
{
public int FileID { get; set; } = 0;
public string FileName { get; set; } = string.Empty;
@ -182,7 +184,7 @@ namespace RageCoop.Client
public FileStream Stream { get; set; }
public void Dispose()
{
if(Stream!= null)
if (Stream!= null)
{
Stream.Flush();
Stream.Close();

View File

@ -1,10 +1,9 @@
using System;
using Lidgren.Network;
using Lidgren.Network;
using RageCoop.Core;
using System.Threading.Tasks;
using System.Threading;
using System.IO;
using System;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
namespace RageCoop.Client
{
@ -34,7 +33,7 @@ namespace RageCoop.Client
});
}
public static void ToggleConnection(string address,string username=null,string password=null)
public static void ToggleConnection(string address, string username = null, string password = null)
{
if (IsOnServer)
{
@ -79,7 +78,7 @@ namespace RageCoop.Client
Main.QueueAction(() => { GTA.UI.Notification.Show($"~y~Trying to connect..."); });
Menus.CoopMenu._serverConnectItem.Enabled=false;
Security.Regen();
if(!GetServerPublicKey(address))
if (!GetServerPublicKey(address))
{
Menus.CoopMenu._serverConnectItem.Enabled=true;
throw new TimeoutException("Failed to retrive server's public key");
@ -100,7 +99,7 @@ namespace RageCoop.Client
Client.Connect(ip[0], short.Parse(ip[1]), outgoingMessage);
}
catch(Exception ex)
catch (Exception ex)
{
Main.Logger.Error("Cannot connect to server: ", ex);
Main.QueueAction(() => GTA.UI.Notification.Show("Cannot connect to server: "+ex.Message));
@ -130,7 +129,7 @@ namespace RageCoop.Client
}
private static void PlayerDisconnect(Packets.PlayerDisconnect packet)
{
var name=PlayerList.GetPlayer(packet.PedID).Username;
var name = PlayerList.GetPlayer(packet.PedID).Username;
GTA.UI.Notification.Show($"{name} left.");
PlayerList.RemovePlayer(packet.PedID);
EntityPool.RemoveAllFromPlayer(packet.PedID);
@ -140,12 +139,12 @@ namespace RageCoop.Client
#endregion // -- PLAYER --
private static bool GetServerPublicKey(string address,int timeout=10000)
private static bool GetServerPublicKey(string address, int timeout = 10000)
{
var msg=Client.CreateMessage();
var msg = Client.CreateMessage();
new Packets.PublicKeyRequest().Pack(msg);
var adds =address.Split(':');
Client.SendUnconnectedMessage(msg,adds[0],int.Parse(adds[1]));
var adds = address.Split(':');
Client.SendUnconnectedMessage(msg, adds[0], int.Parse(adds[1]));
return _publicKeyReceived.WaitOne(timeout);
}
#endregion

View File

@ -1,9 +1,9 @@
using System;
using System.Collections.Generic;
using GTA;
using Lidgren.Network;
using RageCoop.Core;
using GTA;
using RageCoop.Client.Menus;
using RageCoop.Core;
using System;
using System.Collections.Generic;
using System.Threading;
namespace RageCoop.Client
@ -27,12 +27,12 @@ namespace RageCoop.Client
}
};
private static readonly AutoResetEvent _publicKeyReceived=new AutoResetEvent(false);
private static readonly AutoResetEvent _publicKeyReceived = new AutoResetEvent(false);
private static readonly Dictionary<int, Action<PacketType, byte[]>> PendingResponses = new Dictionary<int, Action<PacketType, byte[]>>();
internal static readonly Dictionary<PacketType, Func< byte[], Packet>> RequestHandlers = new Dictionary<PacketType, Func< byte[], Packet>>();
internal static readonly Dictionary<PacketType, Func<byte[], Packet>> RequestHandlers = new Dictionary<PacketType, Func<byte[], Packet>>();
public static void ProcessMessage(NetIncomingMessage message)
{
if(message == null) { return; }
if (message == null) { return; }
switch (message.MessageType)
{
@ -49,7 +49,8 @@ namespace RageCoop.Client
#endif
break;
case NetConnectionStatus.Connected:
Main.QueueAction(() => {
Main.QueueAction(() =>
{
CoopMenu.ConnectedMenuSetting();
Main.MainChat.Init();
PlayerList.Cleanup();
@ -119,7 +120,7 @@ namespace RageCoop.Client
response.Write((byte)PacketType.Response);
response.Write(id);
handler(message.ReadBytes(len)).Pack(response);
Client.SendMessage(response, NetDeliveryMethod.ReliableOrdered,message.SequenceChannel);
Client.SendMessage(response, NetDeliveryMethod.ReliableOrdered, message.SequenceChannel);
}
break;
}
@ -134,7 +135,8 @@ namespace RageCoop.Client
}
catch (Exception ex)
{
Main.QueueAction(() => {
Main.QueueAction(() =>
{
GTA.UI.Notification.Show("~r~~h~Packet Error");
return true;
});
@ -154,9 +156,9 @@ namespace RageCoop.Client
byte[] data = message.ReadBytes(len);
if (packetType==PacketType.PublicKeyResponse)
{
var packet=new Packets.PublicKeyResponse();
var packet = new Packets.PublicKeyResponse();
packet.Unpack(data);
Security.SetServerPublicKey(packet.Modulus,packet.Exponent);
Security.SetServerPublicKey(packet.Modulus, packet.Exponent);
_publicKeyReceived.Set();
}

View File

@ -1,8 +1,8 @@
using Lidgren.Network;
using RageCoop.Core;
using GTA;
using GTA.Native;
using GTA;
using GTA.Math;
using GTA.Native;
using Lidgren.Network;
using RageCoop.Core;
namespace RageCoop.Client
{
@ -24,10 +24,10 @@ namespace RageCoop.Client
Client.SendMessage(outgoingMessage, method, (int)channel);
}
public static void SendPed(SyncedPed c,bool full)
public static void SendPed(SyncedPed c, bool full)
{
Ped p = c.MainPed;
var packet=new Packets.PedSync()
var packet = new Packets.PedSync()
{
ID =c.ID,
OwnerID=c.OwnerID,
@ -81,7 +81,7 @@ namespace RageCoop.Client
}
Send(packet, ConnectionChannel.PedSync);
}
public static void SendVehicle(SyncedVehicle v,bool full)
public static void SendVehicle(SyncedVehicle v, bool full)
{
Vehicle veh = v.MainVehicle;
var packet = new Packets.VehicleSync()
@ -123,7 +123,7 @@ namespace RageCoop.Client
packet.RadioStation=Util.GetPlayerRadioIndex();
}
}
Send(packet,ConnectionChannel.VehicleSync);
Send(packet, ConnectionChannel.VehicleSync);
}
public static void SendProjectile(SyncedProjectile sp)
{
@ -138,13 +138,13 @@ namespace RageCoop.Client
WeaponHash=(uint)p.WeaponHash,
Exploded=p.IsDead
};
if (p.IsDead) { EntityPool.RemoveProjectile(sp.ID,"Dead"); }
if (p.IsDead) { EntityPool.RemoveProjectile(sp.ID, "Dead"); }
Send(packet, ConnectionChannel.ProjectileSync);
}
#region SYNC EVENTS
public static void SendBulletShot(Vector3 start,Vector3 end,uint weapon,int ownerID)
public static void SendBulletShot(Vector3 start, Vector3 end, uint weapon, int ownerID)
{
Send(new Packets.BulletShot()
{

View File

@ -1,15 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading;
using System.Threading.Tasks;
namespace RageCoop.Client
{
internal static class Statistics
{
public static int BytesDownPerSecond{ get; private set; }
public static int BytesDownPerSecond { get; private set; }
public static int BytesUpPerSecond { get; private set; }
static Statistics()
{
@ -17,7 +13,7 @@ namespace RageCoop.Client
{
while (true)
{
var bu=Networking.Client.Statistics.SentBytes;
var bu = Networking.Client.Statistics.SentBytes;
var bd = Networking.Client.Statistics.ReceivedBytes;
Thread.Sleep(1000);
BytesUpPerSecond=Networking.Client.Statistics.SentBytes-bu;

View File

@ -1,9 +1,7 @@
using System.Collections.Generic;
using System.Linq;
using GTA;
using GTA.Math;
using RageCoop.Core;
using GTA;
using GTA.Native;
using RageCoop.Core;
using System.Collections.Generic;
namespace RageCoop.Client
{
@ -16,7 +14,7 @@ namespace RageCoop.Client
public static ulong Pressed { get; set; }
public static bool LeftAlign = true;
public static Dictionary<int,PlayerData> Players=new Dictionary<int, PlayerData> { };
public static Dictionary<int, PlayerData> Players = new Dictionary<int, PlayerData> { };
public static void Tick()
{
if (!Networking.IsOnServer)
@ -26,7 +24,7 @@ namespace RageCoop.Client
if ((Util.GetTickCount64() - _lastUpdate) >= 1000)
{
Update( Main.Settings.Username);
Update(Main.Settings.Username);
}
if ((Util.GetTickCount64() - Pressed) < 5000 && !Main.MainChat.Focused
@ -42,7 +40,7 @@ namespace RageCoop.Client
}
}
private static void Update( string localUsername)
private static void Update(string localUsername)
{
_lastUpdate = Util.GetTickCount64();
@ -59,11 +57,11 @@ namespace RageCoop.Client
_mainScaleform.CallFunction("SET_TITLE", "Player list", $"{Players.Count+1} players");
_mainScaleform.CallFunction("DISPLAY_VIEW");
}
public static void SetPlayer(int id, string username,float latency=0)
public static void SetPlayer(int id, string username, float latency = 0)
{
PlayerData p;
if (Players.TryGetValue(id,out p))
if (Players.TryGetValue(id, out p))
{
p.Username=username;
p.PedID=id;
@ -71,14 +69,14 @@ namespace RageCoop.Client
}
else
{
p = new PlayerData { PedID=id, Username=username,Latency=latency };
Players.Add(id,p);
p = new PlayerData { PedID=id, Username=username, Latency=latency };
Players.Add(id, p);
}
}
public static void UpdatePlayer(Packets.PlayerInfoUpdate packet)
{
var p = GetPlayer(packet.PedID);
if(p?.Character != null)
if (p?.Character != null)
{
p.Latency= packet.Latency;
}
@ -107,7 +105,7 @@ namespace RageCoop.Client
}
public static void Cleanup()
{
Players=new Dictionary<int, PlayerData>{ };
Players=new Dictionary<int, PlayerData> { };
}
}

View File

@ -1,5 +1,4 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following

View File

@ -1,10 +1,9 @@
#undef DEBUG
using System.Collections.Generic;
using System;
using System.Linq;
using RageCoop.Core;
using System.Windows.Forms;
using GTA;
using RageCoop.Core;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace RageCoop.Client.Scripting
{
@ -136,13 +135,13 @@ namespace RageCoop.Client.Scripting
internal static void InvokePlayerDied() { OnPlayerDied?.Invoke(); }
internal static void InvokeTick() { OnTick?.Invoke(); }
internal static void InvokeKeyDown(object s,KeyEventArgs e) { OnKeyDown?.Invoke(s,e); }
internal static void InvokeKeyDown(object s, KeyEventArgs e) { OnKeyDown?.Invoke(s, e); }
internal static void InvokeKeyUp(object s, KeyEventArgs e) { OnKeyUp?.Invoke(s, e); }
internal static void InvokeCustomEventReceived(Packets.CustomEvent p)
{
var args = new CustomEventReceivedArgs() { Hash=p.Hash, Args=p.Args};
var args = new CustomEventReceivedArgs() { Hash=p.Hash, Args=p.Args };
// Main.Logger.Debug($"CustomEvent:\n"+args.Args.DumpWithType());
@ -284,7 +283,7 @@ namespace RageCoop.Client.Scripting
///
/// </summary>
/// <returns></returns>
public static void RequestSharedFile(string name,Action<string> callback)
public static void RequestSharedFile(string name, Action<string> callback)
{
EventHandler<string> handler = (s, e) =>
{
@ -300,7 +299,7 @@ namespace RageCoop.Client.Scripting
},
(p) =>
{
if(p.Response != FileResponse.Loaded)
if (p.Response != FileResponse.Loaded)
{
DownloadManager.DownloadCompleted-=handler;
throw new ArgumentException("Requested file was not found on the server: "+name);

View File

@ -1,27 +1,25 @@
using System;
using System.Collections.Generic;
using GTA.Native;
using GTA;
using GTA.Math;
using GTA;
using RageCoop.Core;
using GTA.Native;
using RageCoop.Core.Scripting;
using System.Linq;
using System.Threading.Tasks;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace RageCoop.Client.Scripting
{
internal class BaseScript : ClientScript
{
private bool _isHost=false;
private bool _isHost = false;
public override void OnStart()
{
API.Events.OnPedDeleted+=(s, p) => { API.SendCustomEvent(CustomEvents.OnPedDeleted, p.ID); };
API.Events.OnVehicleDeleted+=(s, p) => { API.SendCustomEvent(CustomEvents.OnVehicleDeleted, p.ID); };
API.RegisterCustomEventHandler(CustomEvents.SetAutoRespawn,SetAutoRespawn);
API.RegisterCustomEventHandler(CustomEvents.SetDisplayNameTag,SetDisplayNameTag);
API.RegisterCustomEventHandler(CustomEvents.NativeCall,NativeCall);
API.RegisterCustomEventHandler(CustomEvents.SetAutoRespawn, SetAutoRespawn);
API.RegisterCustomEventHandler(CustomEvents.SetDisplayNameTag, SetDisplayNameTag);
API.RegisterCustomEventHandler(CustomEvents.NativeCall, NativeCall);
API.RegisterCustomEventHandler(CustomEvents.ServerPropSync, ServerObjectSync);
API.RegisterCustomEventHandler(CustomEvents.DeleteServerProp, DeleteServerProp);
API.RegisterCustomEventHandler(CustomEvents.DeleteEntity, DeleteEntity);
@ -66,7 +64,7 @@ namespace RageCoop.Client.Scripting
private void SetDisplayNameTag(CustomEventReceivedArgs e)
{
var p = PlayerList.GetPlayer((int)e.Args[0]);
if(p != null) { p.DisplayNameTag=(bool)e.Args[1]; }
if (p != null) { p.DisplayNameTag=(bool)e.Args[1]; }
}
private void UpdatePedBlip(CustomEventReceivedArgs e)
@ -93,7 +91,7 @@ namespace RageCoop.Client.Scripting
{
var vehicleModel = (Model)e.Args[1];
vehicleModel.Request(1000);
Vehicle veh= World.CreateVehicle(vehicleModel, (Vector3)e.Args[2], (float)e.Args[3]);
Vehicle veh = World.CreateVehicle(vehicleModel, (Vector3)e.Args[2], (float)e.Args[3]);
while (veh==null)
{
veh = World.CreateVehicle(vehicleModel, (Vector3)e.Args[2], (float)e.Args[3]);
@ -120,13 +118,13 @@ namespace RageCoop.Client.Scripting
private void ServerBlipSync(CustomEventReceivedArgs obj)
{
int id= (int)obj.Args[0];
var sprite=(BlipSprite)(ushort)obj.Args[1];
int id = (int)obj.Args[0];
var sprite = (BlipSprite)(ushort)obj.Args[1];
var color = (BlipColor)(byte)obj.Args[2];
var scale=(float)obj.Args[3];
var pos=(Vector3)obj.Args[4];
int rot= (int)obj.Args[5];
var name=(string)obj.Args[6];
var scale = (float)obj.Args[3];
var pos = (Vector3)obj.Args[4];
int rot = (int)obj.Args[5];
var name = (string)obj.Args[6];
Blip blip;
if (!EntityPool.ServerBlips.TryGetValue(id, out blip))
{
@ -151,8 +149,8 @@ namespace RageCoop.Client.Scripting
}
private void SetNameTag(CustomEventReceivedArgs e)
{
var p =PlayerList.GetPlayer((int)e.Args[0]);
if(p!= null)
var p = PlayerList.GetPlayer((int)e.Args[0]);
if (p!= null)
{
p.DisplayNameTag=(bool)e.Args[1];
}
@ -193,10 +191,10 @@ namespace RageCoop.Client.Scripting
List<InputArgument> arguments = new List<InputArgument>();
int i;
var ty = (byte)e.Args[0];
TypeCode returnType=(TypeCode)ty;
TypeCode returnType = (TypeCode)ty;
i = returnType==TypeCode.Empty ? 1 : 2;
var hash = (Hash)e.Args[i++];
for(; i<e.Args.Length;i++)
for (; i<e.Args.Length; i++)
{
arguments.Add(GetInputArgument(e.Args[i]));
}

View File

@ -1,11 +1,11 @@
using System.IO;
using RageCoop.Core.Scripting;
using ICSharpCode.SharpZipLib.Zip;
using RageCoop.Core;
using ICSharpCode.SharpZipLib.Zip;
using RageCoop.Core.Scripting;
using System;
using System.Reflection;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
namespace RageCoop.Client.Scripting
{
@ -38,7 +38,8 @@ namespace RageCoop.Client.Scripting
}
internal class Resources
{
public Resources(){
public Resources()
{
BaseScriptType = "RageCoop.Client.Scripting.ClientScript";
Logger = Main.Logger;
}
@ -55,7 +56,7 @@ namespace RageCoop.Client.Scripting
s.CurrentResource=d;
s.OnStart();
}
catch(Exception ex)
catch (Exception ex)
{
Logger.Error("Error occurred when starting script:"+s.GetType().FullName);
Logger?.Error(ex);
@ -85,14 +86,14 @@ namespace RageCoop.Client.Scripting
}
}
}
public void Load(string path,string[] zips)
public void Load(string path, string[] zips)
{
LoadedResources.Clear();
foreach (var zip in zips)
{
var zipPath=Path.Combine(path, zip);
var zipPath = Path.Combine(path, zip);
Logger?.Info($"Loading resource: {Path.GetFileNameWithoutExtension(zip)}");
LoadResource(new ZipFile(zipPath),Path.Combine(path,"data"));
LoadResource(new ZipFile(zipPath), Path.Combine(path, "data"));
}
StartAll();
}
@ -101,7 +102,7 @@ namespace RageCoop.Client.Scripting
StopAll();
if (LoadedResources.Count > 0)
{
API.QueueAction(()=>Util.Reload());
API.QueueAction(() => Util.Reload());
}
LoadedResources.Clear();
}

View File

@ -1,17 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using RageCoop.Core;
using System.IO;
using RageCoop.Core;
using System.Security.Cryptography;
namespace RageCoop.Client
{
internal class Security
{
public RSA ServerRSA { get; set; }
public Aes ClientAes { get; set; }=Aes.Create();
public Aes ClientAes { get; set; } = Aes.Create();
private Logger Logger;
public Security(Logger logger)
{
@ -19,17 +14,17 @@ namespace RageCoop.Client
ClientAes.GenerateKey();
ClientAes.GenerateIV();
}
public void GetSymmetricKeysCrypted(out byte[] cryptedKey,out byte[] cryptedIV)
public void GetSymmetricKeysCrypted(out byte[] cryptedKey, out byte[] cryptedIV)
{
// Logger?.Debug($"Aes.Key:{ClientAes.Key.Dump()}, Aes.IV:{ClientAes.IV.Dump()}");
cryptedKey =ServerRSA.Encrypt(ClientAes.Key, RSAEncryptionPadding.Pkcs1);
cryptedIV =ServerRSA.Encrypt(ClientAes.IV,RSAEncryptionPadding.Pkcs1);
cryptedIV =ServerRSA.Encrypt(ClientAes.IV, RSAEncryptionPadding.Pkcs1);
}
public byte[] Encrypt(byte[] data)
{
return new CryptoStream(new MemoryStream(data), ClientAes.CreateEncryptor(), CryptoStreamMode.Read).ReadToEnd();
}
public void SetServerPublicKey(byte[] modulus,byte[] exponent)
public void SetServerPublicKey(byte[] modulus, byte[] exponent)
{
var para = new RSAParameters();
para.Modulus = modulus;

View File

@ -42,7 +42,7 @@ namespace RageCoop.Client
/// <summary>
/// The key to enter a vehicle as passenger.
/// </summary>
public Keys PassengerKey { get; set; }=Keys.G;
public Keys PassengerKey { get; set; } = Keys.G;
/// <summary>
/// Disable world NPC traffic, mission entities won't be affected

View File

@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GTA;
using GTA;
using GTA.Math;
namespace RageCoop.Client
@ -28,7 +23,7 @@ namespace RageCoop.Client
/// <summary>
/// Network ID for this entity
/// </summary>
public int ID { get;internal set; }
public int ID { get; internal set; }
/// <summary>
///
/// </summary>
@ -45,7 +40,7 @@ namespace RageCoop.Client
}
internal bool IsReady
{
get {return (LastSynced>0||LastFullSynced==0);}
get { return (LastSynced>0||LastFullSynced==0); }
}
internal bool IsInvincible { get; set; } = false;
internal bool NeedUpdate
@ -67,10 +62,13 @@ namespace RageCoop.Client
public ulong LastUpdated { get; set; } = 0;
#endregion
public bool SendNextFrame { get; set; } = false;
public bool SendFullNextFrame { get; set; } = false;
/// <summary>
///
/// </summary>
internal protected bool _lastFrozen=false;
internal protected bool _lastFrozen = false;
internal Model Model { get; set; }
internal Vector3 Position { get; set; }
internal Vector3 Rotation { get; set; }

View File

@ -1,20 +1,19 @@
using System;
using System.Linq;
using System.Drawing;
using System.Collections.Generic;
using RageCoop.Core;
using GTA;
using GTA.Native;
using GTA;
using GTA.Math;
using GTA.Native;
using LemonUI.Elements;
using System.Security.Cryptography;
using RageCoop.Core;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
namespace RageCoop.Client
{
/// <summary>
/// ?
/// </summary>
public class SyncedPed:SyncedEntity
public class SyncedPed : SyncedEntity
{
#region CONSTRUCTORS
@ -49,7 +48,7 @@ namespace RageCoop.Client
internal Blip PedBlip = null;
internal BlipColor BlipColor = (BlipColor)255;
internal BlipSprite BlipSprite = (BlipSprite)0;
internal float BlipScale=1;
internal float BlipScale = 1;
internal PlayerData Player;
#endregion
@ -69,10 +68,10 @@ namespace RageCoop.Client
internal Vector3 LeftFootPosition { get; set; }
internal byte WeaponTint { get; set; }
internal bool _lastEnteringVehicle=false;
internal bool _lastSittingInVehicle=false;
private bool _lastRagdoll=false;
private ulong _lastRagdollTime=0;
internal bool _lastEnteringVehicle = false;
internal bool _lastSittingInVehicle = false;
private bool _lastRagdoll = false;
private ulong _lastRagdollTime = 0;
private bool _lastInCover = false;
private byte[] _lastClothes = null;
internal byte[] Clothes { get; set; }
@ -218,7 +217,7 @@ namespace RageCoop.Client
}
Vector3 targetPos = MainPed.Bones[Bone.IKHead].Position;
Point toDraw=default;
Point toDraw = default;
if (Util.WorldToScreen(targetPos, ref toDraw))
{
toDraw.Y-=100;
@ -282,7 +281,7 @@ namespace RageCoop.Client
Function.Call(Hash.SET_PED_CAN_EVASIVE_DIVE, MainPed.Handle, false);
MainPed.SetConfigFlag((int)PedConfigFlags.CPED_CONFIG_FLAG_DrownsInWater,false);
MainPed.SetConfigFlag((int)PedConfigFlags.CPED_CONFIG_FLAG_DrownsInWater, false);
MainPed.SetConfigFlag((int)PedConfigFlags.CPED_CONFIG_FLAG_DisableHurt, true);
MainPed.SetConfigFlag((int)PedConfigFlags.CPED_CONFIG_FLAG_DisableExplosionReactions, true);
MainPed.SetConfigFlag((int)PedConfigFlags.CPED_CONFIG_FLAG_AvoidTearGas, false);
@ -617,7 +616,7 @@ namespace RageCoop.Client
}
_lastWeaponComponents = WeaponComponents;
}
if (Function.Call<int>(Hash.GET_PED_WEAPON_TINT_INDEX,MainPed,CurrentWeaponHash)!=WeaponTint)
if (Function.Call<int>(Hash.GET_PED_WEAPON_TINT_INDEX, MainPed, CurrentWeaponHash)!=WeaponTint)
{
Function.Call<int>(Hash.SET_PED_WEAPON_TINT_INDEX, MainPed, CurrentWeaponHash, WeaponTint);
}
@ -627,7 +626,7 @@ namespace RageCoop.Client
{
if (Velocity==default)
{
MainPed.Task.AimAt(AimCoords,1000);
MainPed.Task.AimAt(AimCoords, 1000);
}
else
{

View File

@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GTA;
using GTA;
using GTA.Math;
using RageCoop.Core;
@ -30,7 +25,7 @@ namespace RageCoop.Client
Main.Logger.Warning($"Could not find owner for projectile:{Hash}");
}
}
if(shooter != null)
if (shooter != null)
{
if (shooter.MainPed!=null && (p.AttachedEntity==shooter.MainPed.Weapons.CurrentWeaponObject || p.AttachedEntity== shooter.MainPed))
{
@ -52,20 +47,20 @@ namespace RageCoop.Client
public bool Exploded { get; set; } = false;
public Projectile MainProjectile { get; set; }
public int ShooterID { get; set; }
private SyncedPed Shooter { get;set; }
private SyncedPed Shooter { get; set; }
public Vector3 Origin { get; set; }
/// <summary>
/// Invalid property for projectile.
/// </summary>
private new int OwnerID{ set { } }
private new int OwnerID { set { } }
public WeaponHash Hash { get; set; }
private WeaponAsset Asset { get; set; }
internal override void Update()
{
// Skip update if no new sync message has arrived.
if (!NeedUpdate){ return; }
if (!NeedUpdate) { return; }
if (MainProjectile == null || !MainProjectile.Exists())
{
@ -81,7 +76,7 @@ namespace RageCoop.Client
{
Asset=new WeaponAsset(Hash);
if (!Asset.IsLoaded) { Asset.Request(); }
World.ShootBullet(Position,Position+Velocity,(Shooter=EntityPool.GetPedByID(ShooterID))?.MainPed,Asset,0);
World.ShootBullet(Position, Position+Velocity, (Shooter=EntityPool.GetPedByID(ShooterID))?.MainPed, Asset, 0);
var ps = World.GetAllProjectiles();
MainProjectile=ps[ps.Length-1];
if (Hash==(WeaponHash)VehicleWeaponHash.Tank)

View File

@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GTA.Native;
using GTA;
using GTA;
namespace RageCoop.Client
{
@ -21,18 +15,21 @@ namespace RageCoop.Client
/// The real entity
/// </summary>
public Prop MainProp { get; set; }
internal new int OwnerID { get
internal new int OwnerID
{
get
{
// alwayse owned by server
return 0;
} }
}
}
internal override void Update()
{
if (!NeedUpdate) { return; }
if (MainProp== null || !MainProp.Exists())
{
MainProp=World.CreateProp(Model,Position,Rotation,false,false);
MainProp=World.CreateProp(Model, Position, Rotation, false, false);
MainProp.IsInvincible=true;
}
MainProp.Position=Position;

View File

@ -1,14 +1,11 @@
using System;
using System.Security.Cryptography;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GTA;
using GTA.Native;
using GTA;
using GTA.Math;
using GTA.Native;
using RageCoop.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace RageCoop.Client
{
@ -50,8 +47,8 @@ namespace RageCoop.Client
/// <summary>
/// VehicleSeat,ID
/// </summary>
public Vehicle MainVehicle { get;internal set; }
public Stopwatch LastSyncedStopWatch=new Stopwatch();
public Vehicle MainVehicle { get; internal set; }
public Stopwatch LastSyncedStopWatch = new Stopwatch();
#region LAST STATE
@ -99,7 +96,7 @@ namespace RageCoop.Client
internal byte[] Colors { get; set; }
internal Dictionary<int, int> Mods { get; set; }
internal float EngineHealth { get; set; }
internal VehicleLockStatus LockStatus{get;set;}
internal VehicleLockStatus LockStatus { get; set; }
/// <summary>
/// VehicleSeat,PedID
/// </summary>
@ -117,7 +114,7 @@ namespace RageCoop.Client
#region -- INITIAL CHECK --
// Check if all data avalible
if(!IsReady) { return; }
if (!IsReady) { return; }
#endregion
#region -- CHECK EXISTENCE --
if ((MainVehicle == null) || (!MainVehicle.Exists()) || (MainVehicle.Model.Hash != Model))
@ -322,7 +319,7 @@ namespace RageCoop.Client
if (Function.Call<string>(Hash.GET_VEHICLE_NUMBER_PLATE_TEXT, MainVehicle)!=LicensePlate)
{
Function.Call(Hash.SET_VEHICLE_NUMBER_PLATE_TEXT,MainVehicle,LicensePlate);
Function.Call(Hash.SET_VEHICLE_NUMBER_PLATE_TEXT, MainVehicle, LicensePlate);
}
if (_lastLivery!=Livery)
@ -346,7 +343,7 @@ namespace RageCoop.Client
}
else if (current.DistanceTo(Position)<5)
{
MainVehicle.Velocity = Velocity+5*( predicted - current);
MainVehicle.Velocity = Velocity+5*(predicted - current);
if (IsFlipped)
{
MainVehicle.Quaternion=Quaternion.Slerp(MainVehicle.Quaternion, Quaternion, 0.5f);
@ -375,12 +372,12 @@ namespace RageCoop.Client
}
private Vector3 GetCalibrationRotation()
{
var rot=Quaternion.LookRotation(Quaternion*Vector3.RelativeFront, Quaternion*Vector3.RelativeTop).ToEulerAngles();
var curRot=Quaternion.LookRotation(MainVehicle.Quaternion*Vector3.RelativeFront, MainVehicle.Quaternion*Vector3.RelativeTop).ToEulerAngles();
var rot = Quaternion.LookRotation(Quaternion*Vector3.RelativeFront, Quaternion*Vector3.RelativeTop).ToEulerAngles();
var curRot = Quaternion.LookRotation(MainVehicle.Quaternion*Vector3.RelativeFront, MainVehicle.Quaternion*Vector3.RelativeTop).ToEulerAngles();
var r = (rot-curRot).ToDegree();
if (r.X>180) { r.X=r.X-360; }
else if(r.X<-180) { r.X=360+r.X; }
else if (r.X<-180) { r.X=360+r.X; }
if (r.Y>180) { r.Y=r.Y-360; }
else if (r.Y<-180) { r.Y=360+r.Y; }

View File

@ -1,14 +1,10 @@

using System;
using GTA;
using GTA.Native;
using RageCoop.Core;
using RageCoop.Client.Scripting;
using System;
using System.Collections.Generic;
using System.Linq;
using RageCoop.Client.Scripting;
using System.Text;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Security.Cryptography;
namespace RageCoop.Client
@ -36,16 +32,16 @@ namespace RageCoop.Client
private static Dictionary<int, SyncedProjectile> ID_Projectiles = new Dictionary<int, SyncedProjectile>();
private static Dictionary<int, SyncedProjectile> Handle_Projectiles = new Dictionary<int, SyncedProjectile>();
public static object PropsLock=new object();
public static Dictionary<int,SyncedProp> ServerProps=new Dictionary<int,SyncedProp>();
public static object PropsLock = new object();
public static Dictionary<int, SyncedProp> ServerProps = new Dictionary<int, SyncedProp>();
public static object BlipsLock = new object();
public static Dictionary<int, Blip> ServerBlips = new Dictionary<int, Blip>();
public static void Cleanup(bool keepPlayer=true,bool keepMine=true)
public static void Cleanup(bool keepPlayer = true, bool keepMine = true)
{
foreach(int id in new List<int>(ID_Peds.Keys))
foreach (int id in new List<int>(ID_Peds.Keys))
{
if (keepPlayer&&(id==Main.LocalPlayerID)) { continue; }
if (keepMine&&(ID_Peds[id].OwnerID==Main.LocalPlayerID)) { continue; }
@ -62,7 +58,7 @@ namespace RageCoop.Client
ID_Vehicles.Clear();
Handle_Vehicles.Clear();
foreach(var p in ID_Projectiles.Values)
foreach (var p in ID_Projectiles.Values)
{
if (p.ShooterID!=Main.LocalPlayerID && p.MainProjectile!=null && p.MainProjectile.Exists())
{
@ -72,13 +68,13 @@ namespace RageCoop.Client
ID_Projectiles.Clear();
Handle_Projectiles.Clear();
foreach(var p in ServerProps.Values)
foreach (var p in ServerProps.Values)
{
p?.MainProp?.Delete();
}
ServerProps.Clear();
foreach(var b in ServerBlips.Values)
foreach (var b in ServerBlips.Values)
{
if (b.Exists())
{
@ -113,10 +109,10 @@ namespace RageCoop.Client
player.MainPed = p;
// Remove it from Handle_Characters
var pairs=Handle_Peds.Where(x=>x.Value==player);
var pairs = Handle_Peds.Where(x => x.Value==player);
if (pairs.Any())
{
var pair=pairs.First();
var pair = pairs.First();
// Re-add
Handle_Peds.Remove(pair.Key);
@ -135,7 +131,7 @@ namespace RageCoop.Client
Main.LocalPlayerID=c.OwnerID=c.ID;
Add(c);
Main.Logger.Debug($"Local player ID is:{c.ID}");
PlayerList.SetPlayer(c.ID, Main.Settings.Username );
PlayerList.SetPlayer(c.ID, Main.Settings.Username);
return true;
}
return false;
@ -164,7 +160,7 @@ namespace RageCoop.Client
API.Events.InvokePedSpawned(c);
}
}
public static void RemovePed(int id,string reason="Cleanup")
public static void RemovePed(int id, string reason = "Cleanup")
{
if (ID_Peds.ContainsKey(id))
{
@ -231,7 +227,7 @@ namespace RageCoop.Client
API.Events.InvokeVehicleSpawned(v);
}
}
public static void RemoveVehicle(int id,string reason = "Cleanup")
public static void RemoveVehicle(int id, string reason = "Cleanup")
{
if (ID_Vehicles.ContainsKey(id))
{
@ -319,9 +315,9 @@ namespace RageCoop.Client
static int vehStatesPerFrame;
static int pedStatesPerFrame;
static int i;
public static Ped[] allPeds=new Ped[0];
public static Vehicle[] allVehicles=new Vehicle[0];
public static Projectile[] allProjectiles=new Projectile[0];
public static Ped[] allPeds = new Ped[0];
public static Vehicle[] allVehicles = new Vehicle[0];
public static Projectile[] allProjectiles = new Projectile[0];
public static void DoSync()
{
@ -497,13 +493,13 @@ namespace RageCoop.Client
var type = veh.PopulationType;
if (type==EntityPopulationType.RandomAmbient || type==EntityPopulationType.RandomParked)
{
foreach(var p in veh.Occupants)
foreach (var p in veh.Occupants)
{
p.Delete();
var c = EntityPool.GetPedByHandle(p.Handle);
if (c!=null)
{
EntityPool.RemovePed(c.ID,"ThrottleTraffic");
EntityPool.RemovePed(c.ID, "ThrottleTraffic");
}
}
veh.Delete();
@ -532,7 +528,7 @@ namespace RageCoop.Client
i++;
if ((v.MainVehicle!=null)&&(!v.MainVehicle.Exists()))
{
EntityPool.RemoveVehicle(v.ID,"non-existent");
EntityPool.RemoveVehicle(v.ID, "non-existent");
continue;
}
@ -570,7 +566,7 @@ namespace RageCoop.Client
public static void RemoveAllFromPlayer(int playerPedId)
{
foreach(SyncedPed p in ID_Peds.Values.ToArray())
foreach (SyncedPed p in ID_Peds.Values.ToArray())
{
if (p.OwnerID==playerPedId)
{
@ -588,7 +584,7 @@ namespace RageCoop.Client
public static int RequestNewID()
{
int ID=0;
int ID = 0;
while ((ID==0)
|| ID_Peds.ContainsKey(ID)
|| ID_Vehicles.ContainsKey(ID)
@ -610,7 +606,7 @@ namespace RageCoop.Client
}
public static string DumpDebug()
{
string s= "";
string s = "";
s+="\nID_Peds: "+ID_Peds.Count;
s+="\nHandle_Peds: "+Handle_Peds.Count;
s+="\nID_Vehicles: "+ID_Vehicles.Count;

View File

@ -1,24 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GTA;
using GTA;
using GTA.Math;
using RageCoop.Core;
using GTA.Native;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace RageCoop.Client {
namespace RageCoop.Client
{
internal static class SyncEvents
{
#region TRIGGER
public static void TriggerPedKilled(SyncedPed victim)
{
Networking.Send(new Packets.PedKilled() { VictimID=victim.ID},ConnectionChannel.SyncEvents);
Networking.Send(new Packets.PedKilled() { VictimID=victim.ID }, ConnectionChannel.SyncEvents);
}
public static void TriggerEnteringVehicle(SyncedPed c,SyncedVehicle veh, VehicleSeat seat)
public static void TriggerEnteringVehicle(SyncedPed c, SyncedVehicle veh, VehicleSeat seat)
{
Networking.
Send(new Packets.EnteringVehicle()
@ -42,7 +39,7 @@ namespace RageCoop.Client {
VehicleSeat=(short)seat,
PedID=c.ID,
VehicleID=veh.ID
},ConnectionChannel.SyncEvents);
}, ConnectionChannel.SyncEvents);
}
public static void TriggerChangeOwner(SyncedVehicle c, int newOwnerID)
@ -56,7 +53,7 @@ namespace RageCoop.Client {
}
public static void TriggerBulletShot(uint hash,SyncedPed owner,Vector3 impactPosition)
public static void TriggerBulletShot(uint hash, SyncedPed owner, Vector3 impactPosition)
{
// Main.Logger.Trace($"bullet shot:{(WeaponHash)hash}");
@ -84,18 +81,18 @@ namespace RageCoop.Client {
// ANNIHL
if (veh.Model.Hash==837858166)
{
Networking.SendBulletShot(veh.Bones[35].Position, veh.Bones[35].Position+veh.Bones[35].ForwardVector,hash,owner.ID);
Networking.SendBulletShot(veh.Bones[36].Position, veh.Bones[36].Position+veh.Bones[36].ForwardVector,hash, owner.ID);
Networking.SendBulletShot(veh.Bones[37].Position, veh.Bones[37].Position+veh.Bones[37].ForwardVector,hash, owner.ID);
Networking.SendBulletShot(veh.Bones[38].Position, veh.Bones[38].Position+veh.Bones[38].ForwardVector,hash, owner.ID);
Networking.SendBulletShot(veh.Bones[35].Position, veh.Bones[35].Position+veh.Bones[35].ForwardVector, hash, owner.ID);
Networking.SendBulletShot(veh.Bones[36].Position, veh.Bones[36].Position+veh.Bones[36].ForwardVector, hash, owner.ID);
Networking.SendBulletShot(veh.Bones[37].Position, veh.Bones[37].Position+veh.Bones[37].ForwardVector, hash, owner.ID);
Networking.SendBulletShot(veh.Bones[38].Position, veh.Bones[38].Position+veh.Bones[38].ForwardVector, hash, owner.ID);
return;
}
var info = veh.GetMuzzleInfo();
if (info==null) { Main.Logger.Warning($"Failed to get muzzle info for vehicle:{veh.DisplayName}");return; }
Networking.SendBulletShot(info.Position,info.Position+info.ForawardVector,hash,owner.ID);
if (info==null) { Main.Logger.Warning($"Failed to get muzzle info for vehicle:{veh.DisplayName}"); return; }
Networking.SendBulletShot(info.Position, info.Position+info.ForawardVector, hash, owner.ID);
}
public static void TriggerNozzleTransform(int vehID,bool hover)
public static void TriggerNozzleTransform(int vehID, bool hover)
{
Networking.Send(new Packets.NozzleTransform() { VehicleID=vehID, Hover=hover }, ConnectionChannel.SyncEvents);
}
@ -117,9 +114,9 @@ namespace RageCoop.Client {
var flag = LeaveVehicleFlags.None;
if (ped.MainPed?.CurrentVehicle==null) { return; }
// Bail out
if (ped.MainPed.CurrentVehicle.Speed>5) { flag|=LeaveVehicleFlags.BailOut;}
if (ped.MainPed.CurrentVehicle.Speed>5) { flag|=LeaveVehicleFlags.BailOut; }
// ped.PauseUpdate((ulong)Game.FPS*2);
ped.MainPed.Task.LeaveVehicle(flag) ;
ped.MainPed.Task.LeaveVehicle(flag);
Task.Run(() =>
{
Thread.Sleep(1000);
@ -132,7 +129,7 @@ namespace RageCoop.Client {
}
private static void HandleEnteringVehicle(SyncedPed c, SyncedVehicle veh, VehicleSeat seat)
{
c.MainPed?.Task.EnterVehicle(veh.MainVehicle, seat,-1,2,EnterVehicleFlags.WarpToDoor|EnterVehicleFlags.AllowJacking);
c.MainPed?.Task.EnterVehicle(veh.MainVehicle, seat, -1, 2, EnterVehicleFlags.WarpToDoor|EnterVehicleFlags.AllowJacking);
}
private static void HandleEnteredVehicle(int pedId, int vehId, VehicleSeat seat)
{
@ -193,7 +190,7 @@ namespace RageCoop.Client {
case (uint)VehicleWeaponHash.PlayerBuzzard:
weaponHash=1176362416;
break ;
break;
}
var p = EntityPool.GetPedByID(ownerID)?.MainPed;
@ -208,7 +205,7 @@ namespace RageCoop.Client {
if (!_weaponAsset.IsLoaded) { _weaponAsset.Request(); }
World.ShootBullet(start, end, p, _weaponAsset, (int)p.GetWeaponDamage(weaponHash));
Prop w;
if(((w = p.Weapons.CurrentWeaponObject) != null)&&(p.VehicleWeapon==VehicleWeaponHash.Invalid))
if (((w = p.Weapons.CurrentWeaponObject) != null)&&(p.VehicleWeapon==VehicleWeaponHash.Invalid))
{
if (p.Weapons.Current.Components.GetSuppressorComponent().Active)
{
@ -228,7 +225,7 @@ namespace RageCoop.Client {
}
}
}
public static void HandleEvent(PacketType type,byte[] data)
public static void HandleEvent(PacketType type, byte[] data)
{
switch (type)
{
@ -273,7 +270,7 @@ namespace RageCoop.Client {
{
var packet = new Packets.EnteredVehicle();
packet.Unpack(data);
HandleEnteredVehicle(packet.PedID,packet.VehicleID,(VehicleSeat)packet.VehicleSeat);
HandleEnteredVehicle(packet.PedID, packet.VehicleID, (VehicleSeat)packet.VehicleSeat);
break;
}
case PacketType.NozzleTransform:
@ -313,16 +310,16 @@ namespace RageCoop.Client {
{
if (subject.IsOnTurretSeat())
{
TriggerBulletShot((uint)subject.VehicleWeapon, subject.GetSyncEntity(), endPos);
TriggerBulletShot((uint)subject.VehicleWeapon, c, endPos);
}
else
{
TriggerVehBulletShot((uint)subject.VehicleWeapon, subject.CurrentVehicle,c);
TriggerVehBulletShot((uint)subject.VehicleWeapon, subject.CurrentVehicle, c);
}
}
else
{
TriggerBulletShot((uint)subject.Weapons.Current.Hash, subject.GetSyncEntity(), endPos);
TriggerBulletShot((uint)subject.Weapons.Current.Hash, c, endPos);
}
return true;
}
@ -335,16 +332,16 @@ namespace RageCoop.Client {
{
if (subject.IsOnTurretSeat())
{
TriggerBulletShot((uint)subject.VehicleWeapon, subject.GetSyncEntity(), endPos);
TriggerBulletShot((uint)subject.VehicleWeapon, c, endPos);
}
else
{
TriggerVehBulletShot((uint)subject.VehicleWeapon, subject.CurrentVehicle,c);
TriggerVehBulletShot((uint)subject.VehicleWeapon, subject.CurrentVehicle, c);
}
}
else
{
TriggerBulletShot((uint)subject.Weapons.Current.Hash, subject.GetSyncEntity(), endPos);
TriggerBulletShot((uint)subject.Weapons.Current.Hash, c, endPos);
}
return true;
}
@ -358,7 +355,7 @@ namespace RageCoop.Client {
}
else if (subject.VehicleWeapon==VehicleWeaponHash.Tank && subject.LastWeaponImpactPosition!=default)
{
TriggerBulletShot((uint)VehicleWeaponHash.Tank, subject.GetSyncEntity(),subject.LastWeaponImpactPosition);
TriggerBulletShot((uint)VehicleWeaponHash.Tank, c, subject.LastWeaponImpactPosition);
}
}
@ -366,12 +363,12 @@ namespace RageCoop.Client {
// Vehicles
var g = subject.IsGettingIntoVehicle;
if ( g && (!c._lastEnteringVehicle))
if (g && (!c._lastEnteringVehicle))
{
var v = subject.VehicleTryingToEnter.GetSyncEntity();
TriggerEnteringVehicle(c, v, subject.GetSeatTryingToEnter());
}
var currentSitting= subject.IsSittingInVehicle();
var currentSitting = subject.IsSittingInVehicle();
if (c._lastSittingInVehicle)
{
if (!currentSitting)
@ -396,13 +393,13 @@ namespace RageCoop.Client {
{
if (v.MainVehicle!=null&&v.MainVehicle.HasNozzle())
{
if((v.LastNozzleAngle==1) && (v.MainVehicle.GetNozzleAngel()!=1))
if ((v.LastNozzleAngle==1) && (v.MainVehicle.GetNozzleAngel()!=1))
{
TriggerNozzleTransform(v.ID,false);
TriggerNozzleTransform(v.ID, false);
}
else if((v.LastNozzleAngle==0) && (v.MainVehicle.GetNozzleAngel()!=0))
else if ((v.LastNozzleAngle==0) && (v.MainVehicle.GetNozzleAngel()!=0))
{
TriggerNozzleTransform(v.ID,true);
TriggerNozzleTransform(v.ID, true);
}
v.LastNozzleAngle=v.MainVehicle.GetNozzleAngel();
}

View File

@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RageCoop.Client
namespace RageCoop.Client
{
internal class SyncParameters
{

View File

@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RageCoop.Client
namespace RageCoop.Client
{
// Potential names and hash collisions included as comments
internal enum PedConfigFlags

View File

@ -1,14 +1,8 @@
using System;
using System.IO;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using RageCoop.Core;
using GTA;
using GTA.Native;
using GTA;
using GTA.Math;
using System.Linq;
using System.Diagnostics;
using GTA.Native;
using RageCoop.Core;
using System.Collections.Generic;
namespace RageCoop.Client
{
@ -135,7 +129,7 @@ namespace RageCoop.Client
flags |=PedDataFlags.IsInCover;
}
if(Function.Call<bool>(Hash.GET_PED_STEALTH_MOVEMENT, ped))
if (Function.Call<bool>(Hash.GET_PED_STEALTH_MOVEMENT, ped))
{
flags |= PedDataFlags.IsInStealthMode;
}
@ -294,7 +288,7 @@ namespace RageCoop.Client
}
return result;
}
public static bool IsTaskActive(this Ped p,TaskType task)
public static bool IsTaskActive(this Ped p, TaskType task)
{
return Function.Call<bool>(Hash.GET_IS_TASK_ACTIVE, p.Handle, task);
}

View File

@ -1,17 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GTA;
using GTA.Math;
using System.Drawing;
using GTA;
using RageCoop.Core;
using GTA.Native;
using RageCoop.Core;
using System;
using System.Drawing;
using System.IO;
using System.Xml.Serialization;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using System.Xml.Serialization;
namespace RageCoop.Client
{
@ -122,7 +121,7 @@ namespace RageCoop.Client
#endregion
public static string SettingsPath= "Scripts\\RageCoop\\Data\\RageCoop.Client.Settings.xml";
public static string SettingsPath = "Scripts\\RageCoop\\Data\\RageCoop.Client.Settings.xml";
public static Settings ReadSettings()
{
XmlSerializer ser = new XmlSerializer(typeof(Settings));
@ -157,7 +156,7 @@ namespace RageCoop.Client
{
try
{
string path = SettingsPath ;
string path = SettingsPath;
Directory.CreateDirectory(Directory.GetParent(path).FullName);
using (FileStream stream = new FileStream(path, File.Exists(path) ? FileMode.Truncate : FileMode.Create, FileAccess.ReadWrite))
@ -198,7 +197,7 @@ namespace RageCoop.Client
Function.Call(Hash.STOP_ENTITY_FIRE, e.Handle);
}
}
public static void SetFrozen(this Entity e,bool toggle)
public static void SetFrozen(this Entity e, bool toggle)
{
Function.Call(Hash.FREEZE_ENTITY_POSITION, e, toggle);
}
@ -219,7 +218,7 @@ namespace RageCoop.Client
return v;
}
public static void ApplyForce(this Entity e,int boneIndex, Vector3 direction, Vector3 rotation = default(Vector3), ForceType forceType = ForceType.MaxForceRot2)
public static void ApplyForce(this Entity e, int boneIndex, Vector3 direction, Vector3 rotation = default(Vector3), ForceType forceType = ForceType.MaxForceRot2)
{
Function.Call(Hash.APPLY_FORCE_TO_ENTITY, e.Handle, forceType, direction.X, direction.Y, direction.Z, rotation.X, rotation.Y, rotation.Z, boneIndex, false, true, true, false, true);
}
@ -242,12 +241,12 @@ namespace RageCoop.Client
const UInt32 WM_KEYDOWN = 0x0100;
public static void Reload()
{
string reloadKey="None";
string reloadKey = "None";
var lines = File.ReadAllLines("ScriptHookVDotNet.ini");
foreach (var l in lines)
{
var ss = l.Split('=');
if(ss.Length > 0 && ss[0]=="ReloadKey")
if (ss.Length > 0 && ss[0]=="ReloadKey")
{
reloadKey = ss[1];
}
@ -265,7 +264,7 @@ namespace RageCoop.Client
}
}
lineList.Add("ReloadKey=Insert");
File.WriteAllLines("ScriptHookVDotNet.ini",lineList.ToArray());
File.WriteAllLines("ScriptHookVDotNet.ini", lineList.ToArray());
}
Keys key = (Keys)Enum.Parse(typeof(Keys), reloadKey, true);
@ -278,7 +277,7 @@ namespace RageCoop.Client
if (File.Exists(path)) { File.Delete(path); }
if (File.Exists(Main.Logger.LogPath)) { File.Move(Main.Logger.LogPath, path); }
}
catch(Exception ex)
catch (Exception ex)
{
GTA.UI.Notification.Show(ex.Message);
}

View File

@ -1,12 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GTA;
using GTA;
using GTA.Native;
using RageCoop.Core;
using GTA.Math;
using System;
using System.Collections.Generic;
namespace RageCoop.Client
{

View File

@ -1,17 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GTA;
using GTA.Native;
using GTA;
using GTA.Math;
using GTA.Native;
using System.Collections.Generic;
namespace RageCoop.Client
{
internal class MuzzleInfo
{
public MuzzleInfo(Vector3 pos,Vector3 forward)
public MuzzleInfo(Vector3 pos, Vector3 forward)
{
Position = pos;
ForawardVector=forward;
@ -49,7 +45,7 @@ namespace RageCoop.Client
}
return p.Bones[Bone.SkelRightHand].Position;
}
static long BulletsShot=0;
static long BulletsShot = 0;
public static float GetWeaponDamage(this Ped P, uint hash)
{
@ -199,7 +195,7 @@ namespace RageCoop.Client
// RHINO
case 782665360:
return new MuzzleInfo(v.Bones[35].Position,v.Bones[35].ForwardVector);
return new MuzzleInfo(v.Bones[35].Position, v.Bones[35].ForwardVector);
default:
return null;
@ -212,7 +208,7 @@ namespace RageCoop.Client
var type = Function.Call<int>(Hash.GET_WEAPON_DAMAGE_TYPE, vp);
if (vp!=VehicleWeaponHash.Invalid)
{
if(type==3)
if (type==3)
{
return false;
}

View File

@ -1,8 +1,6 @@
using System;
using System.Linq;
using RageCoop.Core;
using GTA;
using GTA;
using GTA.Native;
using System;
namespace RageCoop.Client
{
@ -37,7 +35,7 @@ namespace RageCoop.Client
if (!Networking.IsOnServer)
{
return ;
return;
}
Game.DisableControlThisFrame(Control.FrontendPause);
if (Main.Settings.DisableAlternatePause)
@ -131,7 +129,7 @@ namespace RageCoop.Client
// Don't delete player's vehicle
continue;
}
if((v== null) || (v.IsLocal&&veh.PopulationType!=EntityPopulationType.Mission))
if ((v== null) || (v.IsLocal&&veh.PopulationType!=EntityPopulationType.Mission))
{
Main.Logger.Debug($"Removing Vehicle {veh.Handle}. Reason:ClearTraffic");