diff --git a/Directory.Build.props b/Directory.Build.props index 4ec01a6dd..534d72ae5 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,61 +1,61 @@ - - $(MSBuildThisFileDirectory)DevEnv.targets - - - - - - - C:\Program Files (x86)\Steam\steamapps\common\Dyson Sphere Program\ - $([MSBuild]::EnsureTrailingSlash('$(DSPGameDir)')) - $(DSPGameDir)BepInEx\plugins\nebula-NebulaMultiplayerMod\ - $([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)')) - $(PropSheetPath)dist\release\nebula-NebulaMultiplayerMod\ - - - - false - false - true - - $(PluginOutputDirectory) - net472 - latest - true - true - $(DefaultItemExcludes);*.binlog - - portable - true - $(MSBuildThisFileDirectory) - - - - $(OutputPath)..\nebula-NebulaMultiplayerModApi - - - - - - - - - - - - - - - - - - - - - - - + + $(MSBuildThisFileDirectory)DevEnv.targets + + + + + + + C:\Program Files (x86)\Steam\steamapps\common\Dyson Sphere Program\ + $([MSBuild]::EnsureTrailingSlash('$(DSPGameDir)')) + $(DSPGameDir)BepInEx\plugins\nebula-NebulaMultiplayerMod\ + $([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)')) + $(PropSheetPath)dist\release\nebula-NebulaMultiplayerMod\ + + + + false + false + true + + $(PluginOutputDirectory) + net472 + latest + true + true + $(DefaultItemExcludes);*.binlog + + portable + true + $(MSBuildThisFileDirectory) + + + + $(OutputPath)..\nebula-NebulaMultiplayerModApi + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Directory.Build.targets b/Directory.Build.targets index 1c8bb4c28..048dc696a 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/NebulaAPI/CHANGELOG.md b/NebulaAPI/CHANGELOG.md index c6fb49364..3da32250e 100644 --- a/NebulaAPI/CHANGELOG.md +++ b/NebulaAPI/CHANGELOG.md @@ -35,7 +35,8 @@ 1.1.0: -- Float3 IPlayerData.MechaColor has been changed to Float4[] IPlayerData.MechaColors in line with changes introduced in DSP version 0.8.21.8562. +- Float3 IPlayerData.MechaColor has been changed to Float4[] IPlayerData.MechaColors in line with changes introduced in + DSP version 0.8.21.8562. - Edited description. 1.0.0: diff --git a/NebulaAPI/DataStructures/CollectionExtensions.cs b/NebulaAPI/DataStructures/CollectionExtensions.cs index 43fefafdd..31573ed59 100644 --- a/NebulaAPI/DataStructures/CollectionExtensions.cs +++ b/NebulaAPI/DataStructures/CollectionExtensions.cs @@ -1,37 +1,40 @@ -using System; +#region + +using System; using System.Collections; using System.Threading; -namespace NebulaAPI +#endregion + +namespace NebulaAPI; + +public static class CollectionExtensions { - public static class CollectionExtensions + public static Locker Lock(this ICollection collection) { - public static Locker Lock(this ICollection collection) - { - return new Locker(collection.SyncRoot); - } - - public static Locker GetLocked(this T collection, out T result) where T : ICollection - { - result = collection; - return new Locker(collection.SyncRoot); - } + return new Locker(collection.SyncRoot); } - public readonly struct Locker : IDisposable + public static Locker GetLocked(this T collection, out T result) where T : ICollection { - private readonly object lockObject; + result = collection; + return new Locker(collection.SyncRoot); + } +} - public Locker(object lockObject) - { - this.lockObject = lockObject; +public readonly struct Locker : IDisposable +{ + private readonly object lockObject; - Monitor.Enter(lockObject); - } + public Locker(object lockObject) + { + this.lockObject = lockObject; - public void Dispose() - { - Monitor.Exit(lockObject); - } + Monitor.Enter(lockObject); + } + + public void Dispose() + { + Monitor.Exit(lockObject); } } diff --git a/NebulaAPI/DataStructures/DataStructureExtenstions.cs b/NebulaAPI/DataStructures/DataStructureExtenstions.cs index 9d8d5c7e1..6595b58e5 100644 --- a/NebulaAPI/DataStructures/DataStructureExtenstions.cs +++ b/NebulaAPI/DataStructures/DataStructureExtenstions.cs @@ -1,32 +1,35 @@ -using UnityEngine; +#region -namespace NebulaAPI +using UnityEngine; + +#endregion + +namespace NebulaAPI; + +public static class DataStructureExtenstions { - public static class DataStructureExtenstions + public static Vector3 ToVector3(this Float3 value) + { + return new Vector3(value.x, value.y, value.z); + } + + public static VectorLF3 ToVectorLF3(this Double3 value) + { + return new VectorLF3(value.x, value.y, value.z); + } + + public static Float3 ToFloat3(this Vector3 value) + { + return new Float3(value.x, value.y, value.z); + } + + public static Quaternion ToQuaternion(this Float4 value) + { + return new Quaternion(value.x, value.y, value.z, value.w); + } + + public static Float4 ToFloat4(this Quaternion value) { - public static Vector3 ToVector3(this Float3 value) - { - return new Vector3(value.x, value.y, value.z); - } - - public static VectorLF3 ToVectorLF3(this Double3 value) - { - return new VectorLF3(value.x, value.y, value.z); - } - - public static Float3 ToFloat3(this Vector3 value) - { - return new Float3(value.x, value.y, value.z); - } - - public static Quaternion ToQuaternion(this Float4 value) - { - return new Quaternion(value.x, value.y, value.z, value.w); - } - - public static Float4 ToFloat4(this Quaternion value) - { - return new Float4(value.x, value.y, value.z, value.w); - } + return new Float4(value.x, value.y, value.z, value.w); } -} \ No newline at end of file +} diff --git a/NebulaAPI/DataStructures/Double3.cs b/NebulaAPI/DataStructures/Double3.cs index 7706ece86..f7d3ad31c 100644 --- a/NebulaAPI/DataStructures/Double3.cs +++ b/NebulaAPI/DataStructures/Double3.cs @@ -1,38 +1,36 @@ - -namespace NebulaAPI +namespace NebulaAPI; + +[RegisterNestedType] +public struct Double3 : INetSerializable { - [RegisterNestedType] - public struct Double3 : INetSerializable - { - public double x; - public double y; - public double z; + public double x; + public double y; + public double z; - public Double3(double x, double y, double z) - { - this.x = x; - this.y = y; - this.z = z; - } + public Double3(double x, double y, double z) + { + this.x = x; + this.y = y; + this.z = z; + } - public void Serialize(INetDataWriter writer) - { - writer.Put(x); - writer.Put(y); - writer.Put(z); - } + public void Serialize(INetDataWriter writer) + { + writer.Put(x); + writer.Put(y); + writer.Put(z); + } - public void Deserialize(INetDataReader reader) - { - x = reader.GetDouble(); - y = reader.GetDouble(); - z = reader.GetDouble(); - } + public void Deserialize(INetDataReader reader) + { + x = reader.GetDouble(); + y = reader.GetDouble(); + z = reader.GetDouble(); + } - public override string ToString() - { - return $"x: {x}, y: {y}, z: {z}"; - } + public override string ToString() + { + return $"x: {x}, y: {y}, z: {z}"; } } diff --git a/NebulaAPI/DataStructures/Float3.cs b/NebulaAPI/DataStructures/Float3.cs index 6a3abb723..ec4bd2641 100644 --- a/NebulaAPI/DataStructures/Float3.cs +++ b/NebulaAPI/DataStructures/Float3.cs @@ -1,49 +1,53 @@ -using UnityEngine; +#region -namespace NebulaAPI +using UnityEngine; + +#endregion + +namespace NebulaAPI; + +[RegisterNestedType] +public struct Float3 : INetSerializable { - [RegisterNestedType] - public struct Float3 : INetSerializable + public float x; + public float y; + public float z; + + public Float3(float x, float y, float z) + { + this.x = x; + this.y = y; + this.z = z; + } + + public Float3(Vector3 value) + { + x = value.x; + y = value.y; + z = value.z; + } + + public Color ToColor() + { + return new Color(x, y, z); + } + + public void Serialize(INetDataWriter writer) + { + writer.Put(x); + writer.Put(y); + writer.Put(z); + } + + public void Deserialize(INetDataReader reader) + { + x = reader.GetFloat(); + y = reader.GetFloat(); + z = reader.GetFloat(); + } + + public override string ToString() { - public float x; - public float y; - public float z; - - public Float3(float x, float y, float z) - { - this.x = x; - this.y = y; - this.z = z; - } - - public Float3(Vector3 value) - { - x = value.x; - y = value.y; - z = value.z; - } - public Color ToColor() - { - return new Color(x, y, z); - } - - public void Serialize(INetDataWriter writer) - { - writer.Put(x); - writer.Put(y); - writer.Put(z); - } - - public void Deserialize(INetDataReader reader) - { - x = reader.GetFloat(); - y = reader.GetFloat(); - z = reader.GetFloat(); - } - - public override string ToString() - { - return $"(x: {x}, y: {y}, z: {z})"; - } + return $"(x: {x}, y: {y}, z: {z})"; } } diff --git a/NebulaAPI/DataStructures/Float4.cs b/NebulaAPI/DataStructures/Float4.cs index 8f9d865b2..cff43bc2b 100644 --- a/NebulaAPI/DataStructures/Float4.cs +++ b/NebulaAPI/DataStructures/Float4.cs @@ -1,85 +1,89 @@ -using UnityEngine; +#region -namespace NebulaAPI +using UnityEngine; + +#endregion + +namespace NebulaAPI; + +[RegisterNestedType] +public struct Float4 : INetSerializable { - [RegisterNestedType] - public struct Float4 : INetSerializable + public float x; + public float y; + public float z; + public float w; + + public Float4(float x, float y, float z, float w) { - public float x; - public float y; - public float z; - public float w; + this.x = x; + this.y = y; + this.z = z; + this.w = w; + } - public Float4(float x, float y, float z, float w) - { - this.x = x; - this.y = y; - this.z = z; - this.w = w; - } + public Float4(Quaternion value) + { + x = value.x; + y = value.y; + z = value.z; + w = value.w; + } - public Float4(Quaternion value) - { - x = value.x; - y = value.y; - z = value.z; - w = value.w; - } + public Color ToColor() + { + return new Color(x, y, z, w); + } - public Color ToColor() - { - return new Color(x, y, z, w); - } + public Color32 ToColor32() + { + return new Color32((byte)x, (byte)y, (byte)z, (byte)w); + } - public Color32 ToColor32() + public static Color32[] ToColor32(Float4[] float4s) + { + var color32s = new Color32[float4s.Length]; + for (var i = 0; i < float4s.Length; i++) { - return new Color32((byte)x, (byte)y, (byte)z, (byte)w); + color32s[i] = float4s[i].ToColor32(); } + return color32s; + } - public static Color32[] ToColor32(Float4[] float4s) - { - Color32[] color32s = new Color32[float4s.Length]; - for (int i = 0; i < float4s.Length; i++) - { - color32s[i] = float4s[i].ToColor32(); - } - return color32s; - } - public static Float4 ToFloat4(Color32 color32) - { - return new Float4(color32.r, color32.g, color32.b, color32.a); - } + public static Float4 ToFloat4(Color32 color32) + { + return new Float4(color32.r, color32.g, color32.b, color32.a); + } - public static Float4[] ToFloat4(Color32[] color32s) + public static Float4[] ToFloat4(Color32[] color32s) + { + var float4s = new Float4[color32s.Length]; + for (var i = 0; i < color32s.Length; i++) { - Float4[] float4s = new Float4[color32s.Length]; - for (int i = 0; i < color32s.Length; i++) - { - float4s[i] = new Float4(color32s[i].r, color32s[i].g, color32s[i].b, color32s[i].a); - } - return float4s; + float4s[i] = new Float4(color32s[i].r, color32s[i].g, color32s[i].b, color32s[i].a); } + return float4s; + } - public void Serialize(INetDataWriter writer) - { - writer.Put(x); - writer.Put(y); - writer.Put(z); - writer.Put(w); - } + public void Serialize(INetDataWriter writer) + { + writer.Put(x); + writer.Put(y); + writer.Put(z); + writer.Put(w); + } - public void Deserialize(INetDataReader reader) - { - x = reader.GetFloat(); - y = reader.GetFloat(); - z = reader.GetFloat(); - w = reader.GetFloat(); - } + public void Deserialize(INetDataReader reader) + { + x = reader.GetFloat(); + y = reader.GetFloat(); + z = reader.GetFloat(); + w = reader.GetFloat(); + } - public override string ToString() - { - return $"x: {x}, y: {y}, z: {z}, w: {w}"; - } + public override string ToString() + { + return $"x: {x}, y: {y}, z: {z}, w: {w}"; } } diff --git a/NebulaAPI/DataStructures/IMechaData.cs b/NebulaAPI/DataStructures/IMechaData.cs index aedf07cf1..09bfff0e2 100644 --- a/NebulaAPI/DataStructures/IMechaData.cs +++ b/NebulaAPI/DataStructures/IMechaData.cs @@ -1,16 +1,13 @@ -// unset +namespace NebulaAPI; -namespace NebulaAPI +public interface IMechaData : INetSerializable { - public interface IMechaData : INetSerializable - { - int SandCount { get; set; } - double CoreEnergy { get; set; } - double ReactorEnergy { get; set; } - StorageComponent Inventory { get; set; } - DeliveryPackage DeliveryPackage { get; set; } - StorageComponent ReactorStorage { get; set; } - StorageComponent WarpStorage { get; set; } - MechaForge Forge { get; set; } - } -} \ No newline at end of file + int SandCount { get; set; } + double CoreEnergy { get; set; } + double ReactorEnergy { get; set; } + StorageComponent Inventory { get; set; } + DeliveryPackage DeliveryPackage { get; set; } + StorageComponent ReactorStorage { get; set; } + StorageComponent WarpStorage { get; set; } + MechaForge Forge { get; set; } +} diff --git a/NebulaAPI/DataStructures/IPlayerTechBonuses.cs b/NebulaAPI/DataStructures/IPlayerTechBonuses.cs index 1fdae9053..591b66c20 100644 --- a/NebulaAPI/DataStructures/IPlayerTechBonuses.cs +++ b/NebulaAPI/DataStructures/IPlayerTechBonuses.cs @@ -1,37 +1,34 @@ -// unset +namespace NebulaAPI; -namespace NebulaAPI +public interface IPlayerTechBonuses : INetSerializable { - public interface IPlayerTechBonuses : INetSerializable - { - double coreEnergyCap { get; } - double corePowerGen { get; } - double reactorPowerGen { get; } - double walkPower { get; } - double jumpEnergy { get; } - double thrustPowerPerAcc { get; } - double warpKeepingPowerPerSpeed { get; } - double warpStartPowerPerSpeed { get; } - double miningPower { get; } - double replicatePower { get; } - double researchPower { get; } - double droneEjectEnergy { get; } - double droneEnergyPerMeter { get; } - int coreLevel { get; } - int thrusterLevel { get; } - float miningSpeed { get; } - float replicateSpeed { get; } - float walkSpeed { get; } - float jumpSpeed { get; } - float maxSailSpeed { get; } - float maxWarpSpeed { get; } - float buildArea { get; } - int droneCount { get; } - float droneSpeed { get; } - int droneMovement { get; } - int inventorySize { get; } - bool deliveryPackageUnlocked { get; } - int deliveryPackageColCount { get; set; } - int deliveryPackageStackSizeMultiplier { get; } - } -} \ No newline at end of file + double coreEnergyCap { get; } + double corePowerGen { get; } + double reactorPowerGen { get; } + double walkPower { get; } + double jumpEnergy { get; } + double thrustPowerPerAcc { get; } + double warpKeepingPowerPerSpeed { get; } + double warpStartPowerPerSpeed { get; } + double miningPower { get; } + double replicatePower { get; } + double researchPower { get; } + double droneEjectEnergy { get; } + double droneEnergyPerMeter { get; } + int coreLevel { get; } + int thrusterLevel { get; } + float miningSpeed { get; } + float replicateSpeed { get; } + float walkSpeed { get; } + float jumpSpeed { get; } + float maxSailSpeed { get; } + float maxWarpSpeed { get; } + float buildArea { get; } + int droneCount { get; } + float droneSpeed { get; } + int droneMovement { get; } + int inventorySize { get; } + bool deliveryPackageUnlocked { get; } + int deliveryPackageColCount { get; set; } + int deliveryPackageStackSizeMultiplier { get; } +} diff --git a/NebulaAPI/GameState/IFactoryManager.cs b/NebulaAPI/GameState/IFactoryManager.cs index a977cf22b..dd529cd0f 100644 --- a/NebulaAPI/GameState/IFactoryManager.cs +++ b/NebulaAPI/GameState/IFactoryManager.cs @@ -1,47 +1,50 @@ -using System; +#region + +using System; using UnityEngine; -namespace NebulaAPI +#endregion + +namespace NebulaAPI; + +/// +/// Represents data about factory +/// +public interface IFactoryManager : IDisposable { /// - /// Represents data about factory + /// Did we receive a packet? /// - public interface IFactoryManager : IDisposable - { - /// - /// Did we receive a packet? - /// - IToggle IsIncomingRequest { get; } + IToggle IsIncomingRequest { get; } - int PacketAuthor { get; set; } + int PacketAuthor { get; set; } - int TargetPlanet { get; set; } + int TargetPlanet { get; set; } - PlanetFactory EventFactory { get; set; } + PlanetFactory EventFactory { get; set; } - /// - /// Request to load planet - /// - void AddPlanetTimer(int planetId); + /// + /// Request to load planet + /// + void AddPlanetTimer(int planetId); - void LoadPlanetData(int planetId); + void LoadPlanetData(int planetId); - void UnloadPlanetData(int planetId); + void UnloadPlanetData(int planetId); - void InitializePrebuildRequests(); + void InitializePrebuildRequests(); - void SetPrebuildRequest(int planetId, int prebuildId, ushort playerId); + void SetPrebuildRequest(int planetId, int prebuildId, ushort playerId); - bool RemovePrebuildRequest(int planetId, int prebuildId); + bool RemovePrebuildRequest(int planetId, int prebuildId); - bool ContainsPrebuildRequest(int planetId, int prebuildId); + bool ContainsPrebuildRequest(int planetId, int prebuildId); - int GetNextPrebuildId(int planetId); + int GetNextPrebuildId(int planetId); - int GetNextPrebuildId(PlanetFactory factory); + int GetNextPrebuildId(PlanetFactory factory); - void OnNewSetInserterPickTarget(int objId, int otherObjId, int inserterId, int offset, Vector3 pointPos); + void OnNewSetInserterPickTarget(int objId, int otherObjId, int inserterId, int offset, Vector3 pointPos); - void OnNewSetInserterInsertTarget(int objId, int otherObjId, int inserterId, int offset, Vector3 pointPos); - } -} \ No newline at end of file + void OnNewSetInserterInsertTarget(int objId, int otherObjId, int inserterId, int offset, Vector3 pointPos); +} diff --git a/NebulaAPI/GameState/ILocalPlayer.cs b/NebulaAPI/GameState/ILocalPlayer.cs index 008d98459..9d283740d 100644 --- a/NebulaAPI/GameState/ILocalPlayer.cs +++ b/NebulaAPI/GameState/ILocalPlayer.cs @@ -1,17 +1,20 @@ -using System; +#region -namespace NebulaAPI +using System; + +#endregion + +namespace NebulaAPI; + +/// +/// Represents local player. Allows to send packets. +/// +public interface ILocalPlayer : IDisposable { - /// - /// Represents local player. Allows to send packets. - /// - public interface ILocalPlayer : IDisposable - { - bool IsInitialDataReceived { get; } - bool IsHost { get; } - bool IsClient { get; } - bool IsNewPlayer { get; } - ushort Id { get; } - IPlayerData Data { get; } - } -} \ No newline at end of file + bool IsInitialDataReceived { get; } + bool IsHost { get; } + bool IsClient { get; } + bool IsNewPlayer { get; } + ushort Id { get; } + IPlayerData Data { get; } +} diff --git a/NebulaAPI/GameState/IMultiplayerSession.cs b/NebulaAPI/GameState/IMultiplayerSession.cs index b66a55784..99c7703be 100644 --- a/NebulaAPI/GameState/IMultiplayerSession.cs +++ b/NebulaAPI/GameState/IMultiplayerSession.cs @@ -1,11 +1,10 @@ -namespace NebulaAPI +namespace NebulaAPI; + +public interface IMultiplayerSession { - public interface IMultiplayerSession - { - INetworkProvider Network { get; } - ILocalPlayer LocalPlayer { get; } - IFactoryManager Factories { get; } + INetworkProvider Network { get; } + ILocalPlayer LocalPlayer { get; } + IFactoryManager Factories { get; } - bool IsGameLoaded { get; } - } -} \ No newline at end of file + bool IsGameLoaded { get; } +} diff --git a/NebulaAPI/GameState/INebulaPlayer.cs b/NebulaAPI/GameState/INebulaPlayer.cs index d7d89a25d..ac182c526 100644 --- a/NebulaAPI/GameState/INebulaPlayer.cs +++ b/NebulaAPI/GameState/INebulaPlayer.cs @@ -1,12 +1,12 @@ -namespace NebulaAPI +namespace NebulaAPI; + +public interface INebulaPlayer { - public interface INebulaPlayer - { - INebulaConnection Connection { get; } - IPlayerData Data { get; } - ushort Id { get; } + INebulaConnection Connection { get; } + IPlayerData Data { get; } + ushort Id { get; } + + void SendPacket(T packet) where T : class, new(); - void SendPacket(T packet) where T : class, new(); - void LoadUserData(IPlayerData data); - } -} \ No newline at end of file + void LoadUserData(IPlayerData data); +} diff --git a/NebulaAPI/GameState/INetworkProvider.cs b/NebulaAPI/GameState/INetworkProvider.cs index 8ef1071dc..f3ffff5f2 100644 --- a/NebulaAPI/GameState/INetworkProvider.cs +++ b/NebulaAPI/GameState/INetworkProvider.cs @@ -1,42 +1,49 @@ -using System; +#region -namespace NebulaAPI +using System; + +#endregion + +namespace NebulaAPI; + +public interface INetworkProvider : IDisposable { - public interface INetworkProvider : IDisposable - { - /// - /// Send packet to Host (If ran on Client) or all Clients (If ran on Host) - /// - void SendPacket(T packet) where T : class, new(); - /// - /// Broadcast packet to all Players within current star system - /// - void SendPacketToLocalStar(T packet) where T : class, new(); - /// - /// Broadcast packet to all Players within current planet - /// - void SendPacketToLocalPlanet(T packet) where T : class, new(); - - /// - /// Send packet to all Clients on a planet - /// - void SendPacketToPlanet(T packet, int planetId) where T : class, new(); - /// - /// Send packet to all Clients within star system - /// - void SendPacketToStar(T packet, int starId) where T : class, new(); - - /// - /// Send packet to all Clients except the excluded client - /// - void SendPacketExclude(T packet, INebulaConnection exclude) where T : class, new(); - /// - /// Send packet to all Clients within star system except the excluded client - /// - void SendPacketToStarExclude(T packet, int starId, INebulaConnection exclude) where T : class, new(); - - IPlayerManager PlayerManager { get; } - - void Update(); - } -} \ No newline at end of file + IPlayerManager PlayerManager { get; } + + /// + /// Send packet to Host (If ran on Client) or all Clients (If ran on Host) + /// + void SendPacket(T packet) where T : class, new(); + + /// + /// Broadcast packet to all Players within current star system + /// + void SendPacketToLocalStar(T packet) where T : class, new(); + + /// + /// Broadcast packet to all Players within current planet + /// + void SendPacketToLocalPlanet(T packet) where T : class, new(); + + /// + /// Send packet to all Clients on a planet + /// + void SendPacketToPlanet(T packet, int planetId) where T : class, new(); + + /// + /// Send packet to all Clients within star system + /// + void SendPacketToStar(T packet, int starId) where T : class, new(); + + /// + /// Send packet to all Clients except the excluded client + /// + void SendPacketExclude(T packet, INebulaConnection exclude) where T : class, new(); + + /// + /// Send packet to all Clients within star system except the excluded client + /// + void SendPacketToStarExclude(T packet, int starId, INebulaConnection exclude) where T : class, new(); + + void Update(); +} diff --git a/NebulaAPI/GameState/IPlayerData.cs b/NebulaAPI/GameState/IPlayerData.cs index 8b81b5186..61390e330 100644 --- a/NebulaAPI/GameState/IPlayerData.cs +++ b/NebulaAPI/GameState/IPlayerData.cs @@ -1,22 +1,21 @@ -namespace NebulaAPI +namespace NebulaAPI; + +public interface IPlayerData : INetSerializable { - public interface IPlayerData : INetSerializable - { - string Username { get; set; } - ushort PlayerId { get; set; } - int LocalPlanetId { get; set; } - Float3 LocalPlanetPosition { get; set; } - Double3 UPosition { get; set; } - Float3 Rotation { get; set; } - Float3 BodyRotation { get; set; } - int LocalStarId { get; set; } + string Username { get; set; } + ushort PlayerId { get; set; } + int LocalPlanetId { get; set; } + Float3 LocalPlanetPosition { get; set; } + Double3 UPosition { get; set; } + Float3 Rotation { get; set; } + Float3 BodyRotation { get; set; } + int LocalStarId { get; set; } - IMechaData Mecha { get; set; } - MechaAppearance Appearance { get; set; } - MechaAppearance DIYAppearance { get; set; } - int[] DIYItemId { get; set; } - int[] DIYItemValue { get; set; } + IMechaData Mecha { get; set; } + MechaAppearance Appearance { get; set; } + MechaAppearance DIYAppearance { get; set; } + int[] DIYItemId { get; set; } + int[] DIYItemValue { get; set; } - IPlayerData CreateCopyWithoutMechaData(); - } -} \ No newline at end of file + IPlayerData CreateCopyWithoutMechaData(); +} diff --git a/NebulaAPI/GameState/IPlayerManager.cs b/NebulaAPI/GameState/IPlayerManager.cs index 4f51f1f03..14ba089ed 100644 --- a/NebulaAPI/GameState/IPlayerManager.cs +++ b/NebulaAPI/GameState/IPlayerManager.cs @@ -1,55 +1,58 @@ -using System.Collections.Generic; +#region -namespace NebulaAPI +using System.Collections.Generic; + +#endregion + +namespace NebulaAPI; + +public interface IPlayerManager { - public interface IPlayerManager - { - Locker GetPendingPlayers(out Dictionary pendingPlayers); + Locker GetPendingPlayers(out Dictionary pendingPlayers); - Locker GetSyncingPlayers(out Dictionary syncingPlayers); + Locker GetSyncingPlayers(out Dictionary syncingPlayers); - Locker GetConnectedPlayers(out Dictionary connectedPlayers); + Locker GetConnectedPlayers(out Dictionary connectedPlayers); - Locker GetSavedPlayerData(out Dictionary savedPlayerData); + Locker GetSavedPlayerData(out Dictionary savedPlayerData); - IPlayerData[] GetAllPlayerDataIncludingHost(); + IPlayerData[] GetAllPlayerDataIncludingHost(); - INebulaPlayer GetPlayer(INebulaConnection conn); + INebulaPlayer GetPlayer(INebulaConnection conn); - INebulaPlayer GetSyncingPlayer(INebulaConnection conn); + INebulaPlayer GetSyncingPlayer(INebulaConnection conn); - INebulaPlayer GetPlayerById(ushort playerId); + INebulaPlayer GetPlayerById(ushort playerId); - INebulaPlayer GetConnectedPlayerByUsername(string username); + INebulaPlayer GetConnectedPlayerByUsername(string username); - void SendPacketToAllPlayers(T packet) where T : class, new(); + void SendPacketToAllPlayers(T packet) where T : class, new(); - void SendPacketToLocalStar(T packet) where T : class, new(); + void SendPacketToLocalStar(T packet) where T : class, new(); - void SendPacketToLocalPlanet(T packet) where T : class, new(); + void SendPacketToLocalPlanet(T packet) where T : class, new(); - void SendPacketToPlanet(T packet, int planetId) where T : class, new(); + void SendPacketToPlanet(T packet, int planetId) where T : class, new(); - void SendPacketToStar(T packet, int starId) where T : class, new(); + void SendPacketToStar(T packet, int starId) where T : class, new(); - void SendPacketToStarExcept(T packet, int starId, INebulaConnection exclude) where T : class, new(); + void SendPacketToStarExcept(T packet, int starId, INebulaConnection exclude) where T : class, new(); - void SendRawPacketToStar(byte[] rawPacket, int starId, INebulaConnection sender); + void SendRawPacketToStar(byte[] rawPacket, int starId, INebulaConnection sender); - void SendRawPacketToPlanet(byte[] rawPacket, int planetId, INebulaConnection sender); + void SendRawPacketToPlanet(byte[] rawPacket, int planetId, INebulaConnection sender); - void SendPacketToOtherPlayers(T packet, INebulaConnection exclude) where T : class, new(); + void SendPacketToOtherPlayers(T packet, INebulaConnection exclude) where T : class, new(); - void SendPacketToOtherPlayers(T packet, INebulaPlayer sender) where T : class, new(); + void SendPacketToOtherPlayers(T packet, INebulaPlayer sender) where T : class, new(); - INebulaPlayer PlayerConnected(INebulaConnection conn); + INebulaPlayer PlayerConnected(INebulaConnection conn); - void PlayerDisconnected(INebulaConnection conn); + void PlayerDisconnected(INebulaConnection conn); - ushort GetNextAvailablePlayerId(); + ushort GetNextAvailablePlayerId(); - void UpdateMechaData(IMechaData mechaData, INebulaConnection conn); + void UpdateMechaData(IMechaData mechaData, INebulaConnection conn); - void UpdateSyncedSandCount(int deltaSandCount); - } + void UpdateSyncedSandCount(int deltaSandCount); } diff --git a/NebulaAPI/GlobalSuppressions.cs b/NebulaAPI/GlobalSuppressions.cs index ef5300a0b..b754e58db 100644 --- a/NebulaAPI/GlobalSuppressions.cs +++ b/NebulaAPI/GlobalSuppressions.cs @@ -1,8 +1,9 @@ -// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. +#region using System.Diagnostics.CodeAnalysis; -[assembly: SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Original Field Name", Scope = "namespaceanddescendants", Target = "NebulaAPI")] +#endregion + +[assembly: + SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Original Field Name", Scope = "namespaceanddescendants", + Target = "NebulaAPI")] diff --git a/NebulaAPI/Interfaces/BinaryInterfaces.cs b/NebulaAPI/Interfaces/BinaryInterfaces.cs index 06c710ecb..d28a485a4 100644 --- a/NebulaAPI/Interfaces/BinaryInterfaces.cs +++ b/NebulaAPI/Interfaces/BinaryInterfaces.cs @@ -1,22 +1,26 @@ -using System; +#region + +using System; using System.IO; -namespace NebulaAPI +#endregion + +namespace NebulaAPI; + +/// +/// Provides access to BinaryWriter with LZ4 compression +/// +public interface IWriterProvider : IDisposable { - /// - /// Provides access to BinaryWriter with LZ4 compression - /// - public interface IWriterProvider : IDisposable - { - BinaryWriter BinaryWriter { get; } - byte[] CloseAndGetBytes(); - } + BinaryWriter BinaryWriter { get; } - /// - /// Provides access to BinaryReader with LZ4 compression - /// - public interface IReaderProvider : IDisposable - { - BinaryReader BinaryReader { get; } - } -} \ No newline at end of file + byte[] CloseAndGetBytes(); +} + +/// +/// Provides access to BinaryReader with LZ4 compression +/// +public interface IReaderProvider : IDisposable +{ + BinaryReader BinaryReader { get; } +} diff --git a/NebulaAPI/Interfaces/IMultiplayerMod.cs b/NebulaAPI/Interfaces/IMultiplayerMod.cs index bcaee5fc2..9f50715a9 100644 --- a/NebulaAPI/Interfaces/IMultiplayerMod.cs +++ b/NebulaAPI/Interfaces/IMultiplayerMod.cs @@ -1,22 +1,27 @@ -using System.IO; +#region -namespace NebulaAPI +using System.IO; + +#endregion + +namespace NebulaAPI; + +/// +/// Implement this interface to make sure your mod will be the same version on the host +/// +public interface IMultiplayerMod +{ + string Version { get; } + + bool CheckVersion(string hostVersion, string clientVersion); +} + +/// +/// Implement this interface if you have important settings that clients need to know +/// +public interface IMultiplayerModWithSettings : IMultiplayerMod { - /// - /// Implement this interface to make sure your mod will be the same version on the host - /// - public interface IMultiplayerMod - { - string Version { get; } - bool CheckVersion(string hostVersion, string clientVersion); - } + void Export(BinaryWriter w); - /// - /// Implement this interface if you have important settings that clients need to know - /// - public interface IMultiplayerModWithSettings : IMultiplayerMod - { - void Export(BinaryWriter w); - void Import(BinaryReader r); - } + void Import(BinaryReader r); } diff --git a/NebulaAPI/Interfaces/INetSerializable.cs b/NebulaAPI/Interfaces/INetSerializable.cs index 7df6ca20c..99d9a7bf8 100644 --- a/NebulaAPI/Interfaces/INetSerializable.cs +++ b/NebulaAPI/Interfaces/INetSerializable.cs @@ -1,149 +1,153 @@ -using System; +#region + +using System; using System.Net; -namespace NebulaAPI +#endregion + +namespace NebulaAPI; + +public interface INetSerializable { - public interface INetSerializable - { - void Serialize(INetDataWriter writer); - void Deserialize(INetDataReader reader); - } + void Serialize(INetDataWriter writer); + + void Deserialize(INetDataReader reader); +} - public interface INetDataWriter - { - void Put(float value); +public interface INetDataWriter +{ + void Put(float value); - void Put(double value); + void Put(double value); - void Put(long value); + void Put(long value); - void Put(ulong value); + void Put(ulong value); - void Put(int value); + void Put(int value); - void Put(uint value); + void Put(uint value); - void Put(char value); + void Put(char value); - void Put(ushort value); + void Put(ushort value); - void Put(short value); + void Put(short value); - void Put(sbyte value); + void Put(sbyte value); - void Put(byte value); + void Put(byte value); - void Put(byte[] data, int offset, int length); + void Put(byte[] data, int offset, int length); - void Put(byte[] data); + void Put(byte[] data); - void PutSBytesWithLength(sbyte[] data, int offset, int length); + void PutSBytesWithLength(sbyte[] data, int offset, int length); - void PutSBytesWithLength(sbyte[] data); + void PutSBytesWithLength(sbyte[] data); - void PutBytesWithLength(byte[] data, int offset, int length); + void PutBytesWithLength(byte[] data, int offset, int length); - void PutBytesWithLength(byte[] data); + void PutBytesWithLength(byte[] data); - void Put(bool value); + void Put(bool value); - void PutArray(float[] value); + void PutArray(float[] value); - void PutArray(double[] value); + void PutArray(double[] value); - void PutArray(long[] value); + void PutArray(long[] value); - void PutArray(ulong[] value); + void PutArray(ulong[] value); - void PutArray(int[] value); + void PutArray(int[] value); - void PutArray(uint[] value); + void PutArray(uint[] value); - void PutArray(ushort[] value); + void PutArray(ushort[] value); - void PutArray(short[] value); + void PutArray(short[] value); - void PutArray(bool[] value); + void PutArray(bool[] value); - void PutArray(string[] value); + void PutArray(string[] value); - void PutArray(string[] value, int maxLength); + void PutArray(string[] value, int maxLength); - void Put(IPEndPoint endPoint); + void Put(IPEndPoint endPoint); - void Put(string value); + void Put(string value); - void Put(string value, int maxLength); + void Put(string value, int maxLength); - void Put(T obj) where T : INetSerializable; - } + void Put(T obj) where T : INetSerializable; +} - public interface INetDataReader - { - IPEndPoint GetNetEndPoint(); +public interface INetDataReader +{ + IPEndPoint GetNetEndPoint(); - byte GetByte(); + byte GetByte(); - sbyte GetSByte(); + sbyte GetSByte(); - bool[] GetBoolArray(); + bool[] GetBoolArray(); - ushort[] GetUShortArray(); + ushort[] GetUShortArray(); - short[] GetShortArray(); + short[] GetShortArray(); - long[] GetLongArray(); + long[] GetLongArray(); - ulong[] GetULongArray(); + ulong[] GetULongArray(); - int[] GetIntArray(); + int[] GetIntArray(); - uint[] GetUIntArray(); + uint[] GetUIntArray(); - float[] GetFloatArray(); + float[] GetFloatArray(); - double[] GetDoubleArray(); + double[] GetDoubleArray(); - string[] GetStringArray(); + string[] GetStringArray(); - string[] GetStringArray(int maxStringLength); + string[] GetStringArray(int maxStringLength); - bool GetBool(); + bool GetBool(); - char GetChar(); + char GetChar(); - ushort GetUShort(); + ushort GetUShort(); - short GetShort(); + short GetShort(); - long GetLong(); + long GetLong(); - ulong GetULong(); + ulong GetULong(); - int GetInt(); + int GetInt(); - uint GetUInt(); + uint GetUInt(); - float GetFloat(); + float GetFloat(); - double GetDouble(); + double GetDouble(); - string GetString(int maxLength); + string GetString(int maxLength); - string GetString(); + string GetString(); - ArraySegment GetRemainingBytesSegment(); + ArraySegment GetRemainingBytesSegment(); - T Get() where T : INetSerializable, new(); + T Get() where T : INetSerializable, new(); - byte[] GetRemainingBytes(); + byte[] GetRemainingBytes(); - void GetBytes(byte[] destination, int start, int count); + void GetBytes(byte[] destination, int start, int count); - void GetBytes(byte[] destination, int count); + void GetBytes(byte[] destination, int count); - sbyte[] GetSBytesWithLength(); + sbyte[] GetSBytesWithLength(); - byte[] GetBytesWithLength(); - } + byte[] GetBytesWithLength(); } diff --git a/NebulaAPI/Interfaces/IToggle.cs b/NebulaAPI/Interfaces/IToggle.cs index 35f757294..158c1c2a8 100644 --- a/NebulaAPI/Interfaces/IToggle.cs +++ b/NebulaAPI/Interfaces/IToggle.cs @@ -1,10 +1,14 @@ -using System; +#region -namespace NebulaAPI +using System; + +#endregion + +namespace NebulaAPI; + +public interface IToggle { - public interface IToggle - { - bool Value { get; } - IDisposable On(); - } -} \ No newline at end of file + bool Value { get; } + + IDisposable On(); +} diff --git a/NebulaAPI/NebulaAPI.csproj b/NebulaAPI/NebulaAPI.csproj index e34922699..03d81a464 100644 --- a/NebulaAPI/NebulaAPI.csproj +++ b/NebulaAPI/NebulaAPI.csproj @@ -1,12 +1,12 @@  - - DysonSphereProgram.Modding.NebulaMultiplayerModApi - Nebula Mod Team - API for other mods to work with the Nebula Multiplayer Mod for Dyson Sphere Program. - https://github.com/hubastard/nebula - $(MSBuildThisFileDirectory) - + + DysonSphereProgram.Modding.NebulaMultiplayerModApi + Nebula Mod Team + API for other mods to work with the Nebula Multiplayer Mod for Dyson Sphere Program. + https://github.com/hubastard/nebula + $(MSBuildThisFileDirectory) + \ No newline at end of file diff --git a/NebulaAPI/NebulaModAPI.cs b/NebulaAPI/NebulaModAPI.cs index aab774ac1..b97d11e55 100644 --- a/NebulaAPI/NebulaModAPI.cs +++ b/NebulaAPI/NebulaModAPI.cs @@ -1,178 +1,180 @@ -using BepInEx; -using HarmonyLib; +#region + using System; using System.Collections.Generic; using System.Reflection; +using BepInEx; +using BepInEx.Bootstrap; +using HarmonyLib; -namespace NebulaAPI -{ - [BepInPlugin(API_GUID, API_NAME, ThisAssembly.AssemblyFileVersion)] - [BepInDependency(NEBULA_MODID, BepInDependency.DependencyFlags.SoftDependency)] - public class NebulaModAPI : BaseUnityPlugin - { - private static bool nebulaIsInstalled; - - private static Type multiplayer; - - private static Type binaryWriter; - private static Type binaryReader; - - public static readonly List TargetAssemblies = new List(); - - public const string NEBULA_MODID = "dsp.nebula-multiplayer"; - - public const string API_GUID = "dsp.nebula-multiplayer-api"; - public const string API_NAME = "NebulaMultiplayerModApi"; +#endregion - public static bool NebulaIsInstalled => nebulaIsInstalled; +namespace NebulaAPI; - /// - /// Is this session in multiplayer - /// - public static bool IsMultiplayerActive +[BepInPlugin(API_GUID, API_NAME, ThisAssembly.AssemblyFileVersion)] +[BepInDependency(NEBULA_MODID, BepInDependency.DependencyFlags.SoftDependency)] +public class NebulaModAPI : BaseUnityPlugin +{ + public const string NEBULA_MODID = "dsp.nebula-multiplayer"; + + public const string API_GUID = "dsp.nebula-multiplayer-api"; + public const string API_NAME = "NebulaMultiplayerModApi"; + + public const int PLANET_NONE = -2; + public const int AUTHOR_NONE = -1; + public const int STAR_NONE = -1; + + private static Type multiplayer; + + private static Type binaryWriter; + private static Type binaryReader; + + public static readonly List TargetAssemblies = new(); + + /// + /// Subscribe to receive event when new multiplayer game is started
+ /// (Host sets up a game, or Client establishes connection) + ///
+ public static Action OnMultiplayerGameStarted; + + /// + /// Subscribe to receive event when multiplayer game end
+ /// (Host ends the game, or Client disconnects) + ///
+ public static Action OnMultiplayerGameEnded; + + /// + /// Subscribe to receive event when a new star starts loading (client)
+ /// int starIndex - index of star to load
+ ///
+ public static Action OnStarLoadRequest; + + /// + /// Subscribe to receive event when a DysonSphere finishs loading (client)
+ /// int starIndex - index of star of dyson sphere to load
+ ///
+ public static Action OnDysonSphereLoadFinished; + + /// + /// Subscribe to receive event when a PlanetFactory starts loading (client)
+ /// int planetId - id of planet to load
+ ///
+ public static Action OnPlanetLoadRequest; + + /// + /// Subscribe to receive event when a PlanetFactory is finished loading (client)
+ /// int planetId - id of planet to load + ///
+ public static Action OnPlanetLoadFinished; + + /// + /// Subscribe to receive even when a player joins the game (Host)
+ /// The event fires after the player sync all the data
+ /// - joined player data + ///
+ public static Action OnPlayerJoinedGame; + + /// + /// Subscribe to receive even when a player leaves the game (Host)
+ /// The event fires after the player disconnect
+ /// - left player data + ///
+ public static Action OnPlayerLeftGame; + + public static bool NebulaIsInstalled { get; private set; } + + /// + /// Is this session in multiplayer + /// + public static bool IsMultiplayerActive + { + get { - get + if (!NebulaIsInstalled) { - if (!NebulaIsInstalled) - { - return false; - } - - return (bool)multiplayer.GetProperty("IsActive").GetValue(null); + return false; } + + return (bool)multiplayer.GetProperty("IsActive").GetValue(null); } + } - /// - /// Provides access to MultiplayerSession class - /// - public static IMultiplayerSession MultiplayerSession + /// + /// Provides access to MultiplayerSession class + /// + public static IMultiplayerSession MultiplayerSession + { + get { - get + if (!NebulaIsInstalled) { - if (!NebulaIsInstalled) - { - return null; - } - - return (IMultiplayerSession)multiplayer.GetProperty("Session").GetValue(null); + return null; } + + return (IMultiplayerSession)multiplayer.GetProperty("Session").GetValue(null); } + } - /// - /// Subscribe to receive event when new multiplayer game is started
- /// (Host sets up a game, or Client establishes connection) - ///
- public static Action OnMultiplayerGameStarted; - - /// - /// Subscribe to receive event when multiplayer game end
- /// (Host ends the game, or Client disconnects) - ///
- public static Action OnMultiplayerGameEnded; - - /// - /// Subscribe to receive event when a new star starts loading (client)
- /// int starIndex - index of star to load
- ///
- public static Action OnStarLoadRequest; - - /// - /// Subscribe to receive event when a DysonSphere finishs loading (client)
- /// int starIndex - index of star of dyson sphere to load
- ///
- public static Action OnDysonSphereLoadFinished; - - /// - /// Subscribe to receive event when a PlanetFactory starts loading (client)
- /// int planetId - id of planet to load
- ///
- public static Action OnPlanetLoadRequest; - - /// - /// Subscribe to receive event when a PlanetFactory is finished loading (client)
- /// int planetId - id of planet to load - ///
- public static Action OnPlanetLoadFinished; - - /// - /// Subscribe to receive even when a player joins the game (Host)
- /// The event fires after the player sync all the data
- /// - joined player data - ///
- public static Action OnPlayerJoinedGame; - - /// - /// Subscribe to receive even when a player leaves the game (Host)
- /// The event fires after the player disconnect
- /// - left player data - ///
- public static Action OnPlayerLeftGame; - - private void Awake() - { - nebulaIsInstalled = false; + private void Awake() + { + NebulaIsInstalled = false; - foreach (KeyValuePair pluginInfo in BepInEx.Bootstrap.Chainloader.PluginInfos) + foreach (var pluginInfo in Chainloader.PluginInfos) + { + if (pluginInfo.Value.Metadata.GUID == NEBULA_MODID) { - if (pluginInfo.Value.Metadata.GUID == NEBULA_MODID) - { - nebulaIsInstalled = true; - break; - } + NebulaIsInstalled = true; + break; } + } - if (!nebulaIsInstalled) - { - return; - } + if (!NebulaIsInstalled) + { + return; + } - multiplayer = AccessTools.TypeByName("NebulaWorld.Multiplayer"); + multiplayer = AccessTools.TypeByName("NebulaWorld.Multiplayer"); - Type binaryUtils = AccessTools.TypeByName("NebulaModel.Networking.BinaryUtils"); + var binaryUtils = AccessTools.TypeByName("NebulaModel.Networking.BinaryUtils"); - binaryWriter = binaryUtils.GetNestedType("Writer"); - binaryReader = binaryUtils.GetNestedType("Reader"); + binaryWriter = binaryUtils.GetNestedType("Writer"); + binaryReader = binaryUtils.GetNestedType("Reader"); - Logger.LogInfo("Nebula API is ready!"); - } + Logger.LogInfo("Nebula API is ready!"); + } - public const int PLANET_NONE = -2; - public const int AUTHOR_NONE = -1; - public const int STAR_NONE = -1; + /// + /// Register all packets within assembly + /// + /// Target assembly + public static void RegisterPackets(Assembly assembly) + { + TargetAssemblies.Add(assembly); + } - /// - /// Register all packets within assembly - /// - /// Target assembly - public static void RegisterPackets(Assembly assembly) + /// + /// Provides access to BinaryWriter with LZ4 compression + /// + public static IWriterProvider GetBinaryWriter() + { + if (!NebulaIsInstalled) { - TargetAssemblies.Add(assembly); + return null; } - /// - /// Provides access to BinaryWriter with LZ4 compression - /// - public static IWriterProvider GetBinaryWriter() - { - if (!NebulaIsInstalled) - { - return null; - } - - return (IWriterProvider)binaryWriter.GetConstructor(new Type[0]).Invoke(new object[0]); - } + return (IWriterProvider)binaryWriter.GetConstructor(new Type[0]).Invoke(new object[0]); + } - /// - /// Provides access to BinaryReader with LZ4 compression - /// - public static IReaderProvider GetBinaryReader(byte[] bytes) + /// + /// Provides access to BinaryReader with LZ4 compression + /// + public static IReaderProvider GetBinaryReader(byte[] bytes) + { + if (!NebulaIsInstalled) { - if (!NebulaIsInstalled) - { - return null; - } - - return (IReaderProvider)binaryReader.GetConstructor(new[] { typeof(byte[]) }).Invoke(new object[] { bytes }); + return null; } + + return (IReaderProvider)binaryReader.GetConstructor(new[] { typeof(byte[]) }).Invoke(new object[] { bytes }); } -} \ No newline at end of file +} diff --git a/NebulaAPI/Packets/BasePacketProcessor.cs b/NebulaAPI/Packets/BasePacketProcessor.cs index 066232bcb..a5d64b13f 100644 --- a/NebulaAPI/Packets/BasePacketProcessor.cs +++ b/NebulaAPI/Packets/BasePacketProcessor.cs @@ -1,30 +1,30 @@ -namespace NebulaAPI +namespace NebulaAPI; + +/// +/// Describes how to process received packets of type T +/// +/// Packet class +public abstract class BasePacketProcessor { /// - /// Describes how to process received packets of type T + /// Is code running on Host /// - /// Packet class - public abstract class BasePacketProcessor - { - /// - /// Is code running on Host - /// - protected bool IsHost; - /// - /// Is code running on Client - /// - protected bool IsClient => !IsHost; + protected bool IsHost; - internal void Initialize(bool isHost) - { - IsHost = isHost; - } + /// + /// Is code running on Client + /// + protected bool IsClient => !IsHost; - /// - /// Process packets here - /// - /// Received packet - /// Connection that sent the packet - public abstract void ProcessPacket(T packet, INebulaConnection conn); + internal void Initialize(bool isHost) + { + IsHost = isHost; } -} \ No newline at end of file + + /// + /// Process packets here + /// + /// Received packet + /// Connection that sent the packet + public abstract void ProcessPacket(T packet, INebulaConnection conn); +} diff --git a/NebulaAPI/Packets/HidePacketInDebugLogsAttribute.cs b/NebulaAPI/Packets/HidePacketInDebugLogsAttribute.cs index b3a3a3415..59ad8d381 100644 --- a/NebulaAPI/Packets/HidePacketInDebugLogsAttribute.cs +++ b/NebulaAPI/Packets/HidePacketInDebugLogsAttribute.cs @@ -1,7 +1,12 @@ -using System; +#region -namespace NebulaAPI +using System; + +#endregion + +namespace NebulaAPI; + +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)] +public class HidePacketInDebugLogsAttribute : Attribute { - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false)] - public class HidePacketInDebugLogsAttribute : Attribute { } } diff --git a/NebulaAPI/Packets/INebulaConnection.cs b/NebulaAPI/Packets/INebulaConnection.cs index b97187962..d85d89494 100644 --- a/NebulaAPI/Packets/INebulaConnection.cs +++ b/NebulaAPI/Packets/INebulaConnection.cs @@ -1,11 +1,15 @@ -using System; +#region -namespace NebulaAPI +using System; + +#endregion + +namespace NebulaAPI; + +// Use Equals() to check value equality +public interface INebulaConnection : IEquatable { - // Use Equals() to check value equality - public interface INebulaConnection : IEquatable - { - void SendPacket(T packet) where T : class, new(); - void SendRawPacket(byte[] rawData); - } + void SendPacket(T packet) where T : class, new(); + + void SendRawPacket(byte[] rawData); } diff --git a/NebulaAPI/Packets/RegisterNestedTypeAttribute.cs b/NebulaAPI/Packets/RegisterNestedTypeAttribute.cs index ed1cf53f8..30a1d3aad 100644 --- a/NebulaAPI/Packets/RegisterNestedTypeAttribute.cs +++ b/NebulaAPI/Packets/RegisterNestedTypeAttribute.cs @@ -1,10 +1,15 @@ -using System; +#region -namespace NebulaAPI +using System; + +#endregion + +namespace NebulaAPI; + +/// +/// Registers custom data structure serializer. Make sure to register your assembly using NebulaModAPI.RegisterPackets +/// +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)] +public class RegisterNestedTypeAttribute : Attribute { - /// - /// Registers custom data structure serializer. Make sure to register your assembly using NebulaModAPI.RegisterPackets - /// - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false)] - public class RegisterNestedTypeAttribute : Attribute { } } diff --git a/NebulaAPI/Packets/RegisterPacketProcessorAttribute.cs b/NebulaAPI/Packets/RegisterPacketProcessorAttribute.cs index c229a7f12..c408e066d 100644 --- a/NebulaAPI/Packets/RegisterPacketProcessorAttribute.cs +++ b/NebulaAPI/Packets/RegisterPacketProcessorAttribute.cs @@ -1,10 +1,15 @@ -using System; +#region -namespace NebulaAPI +using System; + +#endregion + +namespace NebulaAPI; + +/// +/// Registers packet processors. Make sure to register your assembly using NebulaModAPI.RegisterPackets +/// +[AttributeUsage(AttributeTargets.Class)] +public class RegisterPacketProcessorAttribute : Attribute { - /// - /// Registers packet processors. Make sure to register your assembly using NebulaModAPI.RegisterPackets - /// - [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] - public class RegisterPacketProcessorAttribute : Attribute { } } diff --git a/NebulaAPI/README.md b/NebulaAPI/README.md index 928e4c700..e92ea9517 100644 --- a/NebulaAPI/README.md +++ b/NebulaAPI/README.md @@ -1,17 +1,23 @@ # Nebula Multiplayer API -API for [Nebula multiplayer mod](https://dsp.thunderstore.io/package/nebula/NebulaMultiplayerMod/). This API allows mod developers to support Nebula. You can find setting up guide, examples and documentation [here](https://github.com/hubastard/nebula/wiki) +API for [Nebula multiplayer mod](https://dsp.thunderstore.io/package/nebula/NebulaMultiplayerMod/). This API allows mod +developers to support Nebula. You can find setting up guide, examples and +documentation [here](https://github.com/hubastard/nebula/wiki) # FAQ ## Where can I get help using the API? -Please join our [Discord Server](https://discord.gg/UHeB2QvgDa) and ask your question in the `General` channel. We have a really nice community that will be able to answer your questions. +Please join our [Discord Server](https://discord.gg/UHeB2QvgDa) and ask your question in the `General` channel. We have +a really nice community that will be able to answer your questions. ## How can I contribute? -Please join our [Discord Server](https://discord.gg/UHeB2QvgDa) to ask if someone is already working on the task that you want to do. Once, you are done with your modification, simply submit a pull request. Contribution documentation can be found here: [Wiki](https://github.com/hubastard/nebula/wiki/Setting-up-a-development-environment). +Please join our [Discord Server](https://discord.gg/UHeB2QvgDa) to ask if someone is already working on the task that +you want to do. Once, you are done with your modification, simply submit a pull request. Contribution documentation can +be found here: [Wiki](https://github.com/hubastard/nebula/wiki/Setting-up-a-development-environment). ## How can I support the team? -If you like what we do and would like to support us, you can donate through our [Patreon](https://www.patreon.com/nebula_mod_team). Thanks for the support <3 \ No newline at end of file +If you like what we do and would like to support us, you can donate through +our [Patreon](https://www.patreon.com/nebula_mod_team). Thanks for the support <3 \ No newline at end of file diff --git a/NebulaModel/Attributes/UICharacterLimitAttribute.cs b/NebulaModel/Attributes/UICharacterLimitAttribute.cs index d325541d4..4dc13e928 100644 --- a/NebulaModel/Attributes/UICharacterLimitAttribute.cs +++ b/NebulaModel/Attributes/UICharacterLimitAttribute.cs @@ -1,15 +1,18 @@ -using System; +#region -namespace NebulaModel.Attributes +using System; + +#endregion + +namespace NebulaModel.Attributes; + +[AttributeUsage(AttributeTargets.Property)] +public class UICharacterLimitAttribute : Attribute { - [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] - public class UICharacterLimitAttribute : Attribute - { - public readonly int Max; + public readonly int Max; - public UICharacterLimitAttribute(int max) - { - Max = max; - } + public UICharacterLimitAttribute(int max) + { + Max = max; } } diff --git a/NebulaModel/Attributes/UIContentTypeAttribute.cs b/NebulaModel/Attributes/UIContentTypeAttribute.cs index 5ecfbc193..67d72e607 100644 --- a/NebulaModel/Attributes/UIContentTypeAttribute.cs +++ b/NebulaModel/Attributes/UIContentTypeAttribute.cs @@ -1,16 +1,19 @@ -using System; +#region + +using System; using UnityEngine.UI; -namespace NebulaModel.Attributes +#endregion + +namespace NebulaModel.Attributes; + +[AttributeUsage(AttributeTargets.Property)] +public class UIContentTypeAttribute : Attribute { - [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] - public class UIContentTypeAttribute : Attribute - { - public readonly InputField.ContentType ContentType; + public readonly InputField.ContentType ContentType; - public UIContentTypeAttribute(InputField.ContentType contentType) - { - ContentType = contentType; - } + public UIContentTypeAttribute(InputField.ContentType contentType) + { + ContentType = contentType; } } diff --git a/NebulaModel/Attributes/UIRangeAttribute.cs b/NebulaModel/Attributes/UIRangeAttribute.cs index 995245bd5..a32e5f7c0 100644 --- a/NebulaModel/Attributes/UIRangeAttribute.cs +++ b/NebulaModel/Attributes/UIRangeAttribute.cs @@ -1,19 +1,22 @@ -using System; +#region -namespace NebulaModel.Attributes +using System; + +#endregion + +namespace NebulaModel.Attributes; + +[AttributeUsage(AttributeTargets.Property)] +public class UIRangeAttribute : Attribute { - [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] - public class UIRangeAttribute : Attribute - { - public readonly float Min; - public readonly float Max; - public readonly bool Slider; + public readonly float Max; + public readonly float Min; + public readonly bool Slider; - public UIRangeAttribute(float min, float max, bool slider = false) - { - Min = min; - Max = max; - Slider = slider; - } + public UIRangeAttribute(float min, float max, bool slider = false) + { + Min = min; + Max = max; + Slider = slider; } -} \ No newline at end of file +} diff --git a/NebulaModel/Config.cs b/NebulaModel/Config.cs index de5963644..4a6646575 100644 --- a/NebulaModel/Config.cs +++ b/NebulaModel/Config.cs @@ -1,80 +1,81 @@ -using BepInEx; -using BepInEx.Configuration; -using HarmonyLib; -using NebulaModel.Logger; +#region + using System; -using System.Collections.Generic; using System.IO; using System.Linq; -using System.Reflection; +using BepInEx; +using BepInEx.Configuration; +using HarmonyLib; +using NebulaModel.Logger; + +#endregion -namespace NebulaModel +namespace NebulaModel; + +public static class Config { - public static class Config - { - private const string OPTION_SAVE_FILE = "nebula.cfg"; - private const string SECTION_NAME = "Nebula - Settings"; + private const string OPTION_SAVE_FILE = "nebula.cfg"; + private const string SECTION_NAME = "Nebula - Settings"; + + public static Action OnConfigApplied; + + private static ConfigFile configFile; - public static PluginInfo ModInfo { get; set; } - public static string ModVersion => ThisAssembly.AssemblyInformationalVersion; - public static MultiplayerOptions Options { get; set; } + public static PluginInfo ModInfo { get; set; } + public static string ModVersion => ThisAssembly.AssemblyInformationalVersion; + public static MultiplayerOptions Options { get; set; } - public static Action OnConfigApplied; - - private static ConfigFile configFile; - - public static bool LoadOptions() + public static bool LoadOptions() + { + Options = new MultiplayerOptions(); + + try { - Options = new MultiplayerOptions(); + configFile = new ConfigFile(Path.Combine(Paths.ConfigPath, OPTION_SAVE_FILE), true); - try - { - configFile = new ConfigFile(Path.Combine(Paths.ConfigPath, OPTION_SAVE_FILE), true); - - List properties = AccessTools.GetDeclaredProperties(typeof(MultiplayerOptions)); - MethodInfo configBindMethod = typeof(ConfigFile) - .GetMethods() - .Where(m => m.Name == nameof(ConfigFile.Bind)) - .First(m => m.IsGenericMethod && m.GetParameters().Length == 4); - - foreach (PropertyInfo prop in properties) - { - object entry = configBindMethod.MakeGenericMethod(prop.PropertyType).Invoke(configFile, - new object[] { SECTION_NAME, prop.Name, prop.GetValue(Options), null }); - - Type entryType = typeof(ConfigEntry<>).MakeGenericType(prop.PropertyType); - prop.SetValue(Options, AccessTools.Property(entryType, "Value").GetValue(entry)); - } - } - catch (Exception e) + var properties = AccessTools.GetDeclaredProperties(typeof(MultiplayerOptions)); + var configBindMethod = typeof(ConfigFile) + .GetMethods() + .Where(m => m.Name == nameof(ConfigFile.Bind)) + .First(m => m.IsGenericMethod && m.GetParameters().Length == 4); + + foreach (var prop in properties) { - Log.Error($"Could not load {OPTION_SAVE_FILE}", e); - return false; - } + var entry = configBindMethod.MakeGenericMethod(prop.PropertyType).Invoke(configFile, + new[] { SECTION_NAME, prop.Name, prop.GetValue(Options), null }); - return true; + var entryType = typeof(ConfigEntry<>).MakeGenericType(prop.PropertyType); + prop.SetValue(Options, AccessTools.Property(entryType, "Value").GetValue(entry)); + } } + catch (Exception e) + { + Log.Error($"Could not load {OPTION_SAVE_FILE}", e); + return false; + } + + return true; + } - public static bool SaveOptions() + public static bool SaveOptions() + { + try { - try - { - List properties = AccessTools.GetDeclaredProperties(typeof(MultiplayerOptions)); - foreach (PropertyInfo prop in properties) - { - ConfigDefinition key = new ConfigDefinition(SECTION_NAME, prop.Name); - configFile[key].BoxedValue = prop.GetValue(Options); - } - configFile.Save(); - } - catch (Exception e) + var properties = AccessTools.GetDeclaredProperties(typeof(MultiplayerOptions)); + foreach (var prop in properties) { - Log.Error($"Could not load {OPTION_SAVE_FILE}", e); - return false; + var key = new ConfigDefinition(SECTION_NAME, prop.Name); + configFile[key].BoxedValue = prop.GetValue(Options); } - - return true; + configFile.Save(); } + catch (Exception e) + { + Log.Error($"Could not load {OPTION_SAVE_FILE}", e); + return false; + } + + return true; } } diff --git a/NebulaModel/DataStructures/Chat/ChatMessage.cs b/NebulaModel/DataStructures/Chat/ChatMessage.cs index edfb6f932..dadc629dd 100644 --- a/NebulaModel/DataStructures/Chat/ChatMessage.cs +++ b/NebulaModel/DataStructures/Chat/ChatMessage.cs @@ -1,69 +1,71 @@ -using NebulaModel.Utils; +#region + using System; +using NebulaModel.Utils; using TMPro; using UnityEngine; using Object = UnityEngine.Object; +#endregion + #pragma warning disable IDE1006 -namespace NebulaModel.DataStructures +namespace NebulaModel.DataStructures; + +/// +/// This is what is rendered in the chat area (already sent chat messages) +/// +[Serializable] +public class ChatMessage { - /// - /// This is what is rendered in the chat area (already sent chat messages) - /// - [Serializable] - public class ChatMessage - { - private string text; - private ChatMessageType messageType; + public TMP_Text textObject; + public TMP_Text notificationText; + private ChatMessageType messageType; + private string text; - public TMP_Text textObject; - public TMP_Text notificationText; + public ChatMessage(GameObject textObj, string message, ChatMessageType messageType) + { + textObject = textObj.GetComponent(); + Text = message; + MessageType = messageType; + } - public string Text + public string Text + { + get => text; + set { - get => text; - set + textObject.text = value; + if (notificationText != null) { - textObject.text = value; - if (notificationText != null) - { - notificationText.text = value; - } - - text = value; + notificationText.text = value; } + + text = value; } + } - public ChatMessageType MessageType + public ChatMessageType MessageType + { + get => messageType; + set { - get => messageType; - set + textObject.color = ChatUtils.GetMessageColor(value); + if (notificationText != null) { - textObject.color = ChatUtils.GetMessageColor(value); - if (notificationText != null) - { - notificationText.color = textObject.color; - } - - messageType = value; + notificationText.color = textObject.color; } - } - public ChatMessage(GameObject textObj, string message, ChatMessageType messageType) - { - textObject = textObj.GetComponent(); - Text = message; - MessageType = messageType; + messageType = value; } + } - public void DestroyMessage() + public void DestroyMessage() + { + Object.Destroy(textObject.gameObject); + if (notificationText != null) { - Object.Destroy(textObject.gameObject); - if (notificationText != null) - { - Object.Destroy(notificationText.gameObject); - } + Object.Destroy(notificationText.gameObject); } } } diff --git a/NebulaModel/DataStructures/Chat/ChatMessageType.cs b/NebulaModel/DataStructures/Chat/ChatMessageType.cs index 3e2af68ed..827acc50d 100644 --- a/NebulaModel/DataStructures/Chat/ChatMessageType.cs +++ b/NebulaModel/DataStructures/Chat/ChatMessageType.cs @@ -1,13 +1,12 @@ -namespace NebulaModel.DataStructures +namespace NebulaModel.DataStructures; + +public enum ChatMessageType { - public enum ChatMessageType - { - PlayerMessage = 0, - SystemInfoMessage = 1, - SystemWarnMessage = 2, - CommandUsageMessage = 3, - CommandOutputMessage = 4, - CommandErrorMessage = 5, - PlayerMessagePrivate = 6 - } -} \ No newline at end of file + PlayerMessage = 0, + SystemInfoMessage = 1, + SystemWarnMessage = 2, + CommandUsageMessage = 3, + CommandOutputMessage = 4, + CommandErrorMessage = 5, + PlayerMessagePrivate = 6 +} diff --git a/NebulaModel/DataStructures/Chat/ChatPosition.cs b/NebulaModel/DataStructures/Chat/ChatPosition.cs index d24195538..547345d99 100644 --- a/NebulaModel/DataStructures/Chat/ChatPosition.cs +++ b/NebulaModel/DataStructures/Chat/ChatPosition.cs @@ -1,17 +1,16 @@ -namespace NebulaModel.DataStructures +namespace NebulaModel.DataStructures; + +public enum ChatPosition { - public enum ChatPosition - { - LeftMiddle = 0, - RightMiddle = 1, - LeftTop = 2, - RightTop = 3 - } + LeftMiddle = 0, + RightMiddle = 1, + LeftTop = 2, + RightTop = 3 +} - public enum ChatSize - { - Small = 0, - Medium = 1, - Big = 2 - } -} \ No newline at end of file +public enum ChatSize +{ + Small = 0, + Medium = 1, + Big = 2 +} diff --git a/NebulaModel/DataStructures/DysonLaunchData.cs b/NebulaModel/DataStructures/DysonLaunchData.cs index 38edbd5a4..90c57a7ed 100644 --- a/NebulaModel/DataStructures/DysonLaunchData.cs +++ b/NebulaModel/DataStructures/DysonLaunchData.cs @@ -1,90 +1,93 @@ -using NebulaAPI; +#region + using System.Collections.Generic; +using NebulaAPI; using UnityEngine; -namespace NebulaModel.DataStructures +#endregion + +namespace NebulaModel.DataStructures; + +[RegisterNestedType] +public class DysonLaunchData : INetSerializable { - [RegisterNestedType] - public class DysonLaunchData : INetSerializable + public DysonLaunchData(int starIndex) { - public struct Projectile - { - public int PlanetId; - public byte Interval; - public ushort TargetId; - public Vector3 LocalPos; - } + StarIndex = starIndex; + BulletList = new List(); + RocketList = new List(); + } - public int StarIndex { get; set; } - public List BulletList { get; set; } - public List RocketList { get; set; } - public int BulletCursor { get; set; } - public int RocketCursor { get; set; } - public byte BulletTick { get; set; } - public byte RocketTick { get; set; } + public DysonLaunchData() : this(0) { } - public DysonLaunchData(int starIndex) + public int StarIndex { get; set; } + public List BulletList { get; set; } + public List RocketList { get; set; } + public int BulletCursor { get; set; } + public int RocketCursor { get; set; } + public byte BulletTick { get; set; } + public byte RocketTick { get; set; } + + public void Serialize(INetDataWriter writer) + { + writer.Put(StarIndex); + writer.Put((ushort)BulletList.Count); + for (ushort i = 0; i < (ushort)BulletList.Count; i++) { - StarIndex = starIndex; - BulletList = new List(); - RocketList = new List(); + var data = BulletList[i]; + writer.Put((byte)(data.PlanetId % 100)); + writer.Put(data.Interval); + writer.Put(data.TargetId); + writer.Put(data.LocalPos.ToFloat3()); } - - public DysonLaunchData() : this(0) { } - - public void Serialize(INetDataWriter writer) + writer.Put((ushort)RocketList.Count); + for (ushort i = 0; i < (ushort)RocketList.Count; i++) { - writer.Put(StarIndex); - writer.Put((ushort)BulletList.Count); - for (ushort i = 0; i < (ushort)BulletList.Count; i++) - { - Projectile data = BulletList[i]; - writer.Put((byte)(data.PlanetId % 100)); - writer.Put(data.Interval); - writer.Put(data.TargetId); - writer.Put(data.LocalPos.ToFloat3()); - } - writer.Put((ushort)RocketList.Count); - for (ushort i = 0; i < (ushort)RocketList.Count; i++) - { - Projectile data = RocketList[i]; - writer.Put((byte)(data.PlanetId % 100)); - writer.Put(data.Interval); - writer.Put(data.TargetId); - writer.Put(data.LocalPos.ToFloat3()); - } + var data = RocketList[i]; + writer.Put((byte)(data.PlanetId % 100)); + writer.Put(data.Interval); + writer.Put(data.TargetId); + writer.Put(data.LocalPos.ToFloat3()); } + } - public void Deserialize(INetDataReader reader) + public void Deserialize(INetDataReader reader) + { + StarIndex = reader.GetInt(); + var starId = (StarIndex + 1) * 100; + int count = reader.GetUShort(); + BulletList = new List(count); + for (var i = 0; i < count; i++) { - StarIndex = reader.GetInt(); - int starId = (StarIndex + 1) * 100; - int count = reader.GetUShort(); - BulletList = new List(count); - for (int i = 0; i < count; i++) + var data = new Projectile { - Projectile data = new Projectile - { - PlanetId = reader.GetByte() + starId, - Interval = reader.GetByte(), - TargetId = reader.GetUShort(), - LocalPos = reader.GetFloat3().ToVector3() - }; - BulletList.Add(data); - } - count = reader.GetUShort(); - RocketList = new List(count); - for (ushort i = 0; i < count; i++) + PlanetId = reader.GetByte() + starId, + Interval = reader.GetByte(), + TargetId = reader.GetUShort(), + LocalPos = reader.GetFloat3().ToVector3() + }; + BulletList.Add(data); + } + count = reader.GetUShort(); + RocketList = new List(count); + for (ushort i = 0; i < count; i++) + { + var data = new Projectile { - Projectile data = new Projectile - { - PlanetId = reader.GetByte() + starId, - Interval = reader.GetByte(), - TargetId = reader.GetUShort(), - LocalPos = reader.GetFloat3().ToVector3() - }; - RocketList.Add(data); - } + PlanetId = reader.GetByte() + starId, + Interval = reader.GetByte(), + TargetId = reader.GetUShort(), + LocalPos = reader.GetFloat3().ToVector3() + }; + RocketList.Add(data); } } + + public struct Projectile + { + public int PlanetId; + public byte Interval; + public ushort TargetId; + public Vector3 LocalPos; + } } diff --git a/NebulaModel/DataStructures/GameState.cs b/NebulaModel/DataStructures/GameState.cs index b6c5df8e6..f8c5d767a 100644 --- a/NebulaModel/DataStructures/GameState.cs +++ b/NebulaModel/DataStructures/GameState.cs @@ -1,29 +1,32 @@ -using NebulaAPI; +#region -namespace NebulaModel.DataStructures +using NebulaAPI; + +#endregion + +namespace NebulaModel.DataStructures; + +[RegisterNestedType] +public struct GameState : INetSerializable { - [RegisterNestedType] - public struct GameState : INetSerializable - { - public long timestamp; - public long gameTick; + public long timestamp; + public long gameTick; - public GameState(long timestamp, long gameTick) - { - this.timestamp = timestamp; - this.gameTick = gameTick; - } + public GameState(long timestamp, long gameTick) + { + this.timestamp = timestamp; + this.gameTick = gameTick; + } - public void Serialize(INetDataWriter writer) - { - writer.Put(timestamp); - writer.Put(gameTick); - } + public void Serialize(INetDataWriter writer) + { + writer.Put(timestamp); + writer.Put(gameTick); + } - public void Deserialize(INetDataReader reader) - { - timestamp = reader.GetLong(); - gameTick = reader.GetLong(); - } + public void Deserialize(INetDataReader reader) + { + timestamp = reader.GetLong(); + gameTick = reader.GetLong(); } } diff --git a/NebulaModel/DataStructures/MechaData.cs b/NebulaModel/DataStructures/MechaData.cs index 8582545a4..eac912571 100644 --- a/NebulaModel/DataStructures/MechaData.cs +++ b/NebulaModel/DataStructures/MechaData.cs @@ -1,140 +1,133 @@ -using NebulaAPI; -using NebulaModel.Packets.Players; +#region + using System.Collections.Generic; using System.IO; +using NebulaAPI; +using NebulaModel.Packets.Players; + +#endregion -namespace NebulaModel.DataStructures +namespace NebulaModel.DataStructures; + +[RegisterNestedType] +public class MechaData : IMechaData { - [RegisterNestedType] - public class MechaData : IMechaData + public MechaData() { - public int SandCount { get; set; } - public double CoreEnergy { get; set; } - public double ReactorEnergy { get; set; } - public StorageComponent Inventory { get; set; } - public DeliveryPackage DeliveryPackage { get; set; } - public StorageComponent ReactorStorage { get; set; } - public StorageComponent WarpStorage { get; set; } - public MechaForge Forge { get; set; } - public PlayerTechBonuses TechBonuses { get; set; } + //This is needed for the serialization and deserialization + Forge = new MechaForge { tasks = new List() }; + TechBonuses = new PlayerTechBonuses(); + } - public MechaData() - { - //This is needed for the serialization and deserialization - Forge = new MechaForge - { - tasks = new List() - }; - TechBonuses = new PlayerTechBonuses(); - } + public MechaData(int sandCount, double coreEnergy, double reactorEnergy, StorageComponent inventory, + DeliveryPackage deliveryPackage, StorageComponent reactorStorage, StorageComponent warpStorage, MechaForge forge) + { + SandCount = sandCount; + CoreEnergy = coreEnergy; + ReactorEnergy = reactorEnergy; + ReactorStorage = reactorStorage; + WarpStorage = warpStorage; + Forge = forge; + Inventory = inventory; + DeliveryPackage = deliveryPackage; + TechBonuses = new PlayerTechBonuses(); + } - public MechaData(int sandCount, double coreEnergy, double reactorEnergy, StorageComponent inventory, DeliveryPackage deliveryPackage, StorageComponent reactorStorage, StorageComponent warpStorage, MechaForge forge) - { - SandCount = sandCount; - CoreEnergy = coreEnergy; - ReactorEnergy = reactorEnergy; - ReactorStorage = reactorStorage; - WarpStorage = warpStorage; - Forge = forge; - Inventory = inventory; - DeliveryPackage = deliveryPackage; - TechBonuses = new PlayerTechBonuses(); - } + public PlayerTechBonuses TechBonuses { get; set; } + public int SandCount { get; set; } + public double CoreEnergy { get; set; } + public double ReactorEnergy { get; set; } + public StorageComponent Inventory { get; set; } + public DeliveryPackage DeliveryPackage { get; set; } + public StorageComponent ReactorStorage { get; set; } + public StorageComponent WarpStorage { get; set; } + public MechaForge Forge { get; set; } - public void Serialize(INetDataWriter writer) + public void Serialize(INetDataWriter writer) + { + TechBonuses.Serialize(writer); + writer.Put(SandCount); + writer.Put(CoreEnergy); + writer.Put(ReactorEnergy); + writer.Put(ReactorStorage != null); + if (ReactorStorage != null) { - TechBonuses.Serialize(writer); - writer.Put(SandCount); - writer.Put(CoreEnergy); - writer.Put(ReactorEnergy); - writer.Put(ReactorStorage != null); - if (ReactorStorage != null) + using var ms = new MemoryStream(); + using (var wr = new BinaryWriter(ms)) { - using MemoryStream ms = new MemoryStream(); - using (BinaryWriter wr = new BinaryWriter(ms)) - { - Inventory.Export(wr); - DeliveryPackage.Export(wr); - ReactorStorage.Export(wr); - WarpStorage.Export(wr); - Forge.Export(wr); - } - byte[] export = ms.ToArray(); - writer.Put(export.Length); - writer.Put(export); + Inventory.Export(wr); + DeliveryPackage.Export(wr); + ReactorStorage.Export(wr); + WarpStorage.Export(wr); + Forge.Export(wr); } + var export = ms.ToArray(); + writer.Put(export.Length); + writer.Put(export); } + } - public void Deserialize(INetDataReader reader) + public void Deserialize(INetDataReader reader) + { + TechBonuses = new PlayerTechBonuses(); + Inventory = new StorageComponent(4); + DeliveryPackage = new DeliveryPackage(); + DeliveryPackage.Init(); + ReactorStorage = new StorageComponent(4); + WarpStorage = new StorageComponent(1); + Forge = new MechaForge { tasks = new List(), extraItems = new ItemBundle() }; + TechBonuses.Deserialize(reader); + SandCount = reader.GetInt(); + CoreEnergy = reader.GetDouble(); + ReactorEnergy = reader.GetDouble(); + var isPayloadPresent = reader.GetBool(); + if (isPayloadPresent) { - TechBonuses = new PlayerTechBonuses(); - Inventory = new StorageComponent(4); - DeliveryPackage = new DeliveryPackage(); - DeliveryPackage.Init(); - ReactorStorage = new StorageComponent(4); - WarpStorage = new StorageComponent(1); - Forge = new MechaForge - { - tasks = new List(), - extraItems = new ItemBundle() - }; - TechBonuses.Deserialize(reader); - SandCount = reader.GetInt(); - CoreEnergy = reader.GetDouble(); - ReactorEnergy = reader.GetDouble(); - bool isPayloadPresent = reader.GetBool(); - if (isPayloadPresent) + var mechaLength = reader.GetInt(); + var mechaBytes = new byte[mechaLength]; + reader.GetBytes(mechaBytes, mechaLength); + using (var ms = new MemoryStream(mechaBytes)) + using (var br = new BinaryReader(ms)) { - int mechaLength = reader.GetInt(); - byte[] mechaBytes = new byte[mechaLength]; - reader.GetBytes(mechaBytes, mechaLength); - using (MemoryStream ms = new MemoryStream(mechaBytes)) - using (BinaryReader br = new BinaryReader(ms)) - { - Inventory.Import(br); - DeliveryPackage.Import(br); - ReactorStorage.Import(br); - WarpStorage.Import(br); - Forge.Import(br); - } + Inventory.Import(br); + DeliveryPackage.Import(br); + ReactorStorage.Import(br); + WarpStorage.Import(br); + Forge.Import(br); } } + } - public void Import(INetDataReader reader, int revision) + public void Import(INetDataReader reader, int revision) + { + TechBonuses = new PlayerTechBonuses(); + Inventory = new StorageComponent(4); + DeliveryPackage = new DeliveryPackage(); + DeliveryPackage.Init(); + ReactorStorage = new StorageComponent(4); + WarpStorage = new StorageComponent(1); + Forge = new MechaForge { tasks = new List(), extraItems = new ItemBundle() }; + TechBonuses.Import(reader, revision); + SandCount = reader.GetInt(); + CoreEnergy = reader.GetDouble(); + ReactorEnergy = reader.GetDouble(); + var isPayloadPresent = reader.GetBool(); + if (isPayloadPresent) { - TechBonuses = new PlayerTechBonuses(); - Inventory = new StorageComponent(4); - DeliveryPackage = new DeliveryPackage(); - DeliveryPackage.Init(); - ReactorStorage = new StorageComponent(4); - WarpStorage = new StorageComponent(1); - Forge = new MechaForge - { - tasks = new List(), - extraItems = new ItemBundle() - }; - TechBonuses.Import(reader, revision); - SandCount = reader.GetInt(); - CoreEnergy = reader.GetDouble(); - ReactorEnergy = reader.GetDouble(); - bool isPayloadPresent = reader.GetBool(); - if (isPayloadPresent) + var mechaLength = reader.GetInt(); + var mechaBytes = new byte[mechaLength]; + reader.GetBytes(mechaBytes, mechaLength); + using (var ms = new MemoryStream(mechaBytes)) + using (var br = new BinaryReader(ms)) { - int mechaLength = reader.GetInt(); - byte[] mechaBytes = new byte[mechaLength]; - reader.GetBytes(mechaBytes, mechaLength); - using (MemoryStream ms = new MemoryStream(mechaBytes)) - using (BinaryReader br = new BinaryReader(ms)) + Inventory.Import(br); + if (revision >= 7) { - Inventory.Import(br); - if (revision >= 7) - { - DeliveryPackage.Import(br); - } - ReactorStorage.Import(br); - WarpStorage.Import(br); - Forge.Import(br); + DeliveryPackage.Import(br); } + ReactorStorage.Import(br); + WarpStorage.Import(br); + Forge.Import(br); } } } diff --git a/NebulaModel/DataStructures/NetDataReaderExtensions.cs b/NebulaModel/DataStructures/NetDataReaderExtensions.cs index d800add81..50b4d3e3a 100644 --- a/NebulaModel/DataStructures/NetDataReaderExtensions.cs +++ b/NebulaModel/DataStructures/NetDataReaderExtensions.cs @@ -1,28 +1,31 @@ -using NebulaAPI; +#region -namespace NebulaModel.DataStructures +using NebulaAPI; + +#endregion + +namespace NebulaModel.DataStructures; + +public static class NetDataReaderExtensions { - public static class NetDataReaderExtensions + public static Float3 GetFloat3(this INetDataReader reader) { - public static Float3 GetFloat3(this INetDataReader reader) - { - Float3 value = new Float3(); - value.Deserialize(reader); - return value; - } + var value = new Float3(); + value.Deserialize(reader); + return value; + } - public static Float4 GetFloat4(this INetDataReader reader) - { - Float4 value = new Float4(); - value.Deserialize(reader); - return value; - } + public static Float4 GetFloat4(this INetDataReader reader) + { + var value = new Float4(); + value.Deserialize(reader); + return value; + } - public static Double3 GetDouble3(this INetDataReader reader) - { - Double3 value = new Double3(); - value.Deserialize(reader); - return value; - } + public static Double3 GetDouble3(this INetDataReader reader) + { + var value = new Double3(); + value.Deserialize(reader); + return value; } } diff --git a/NebulaModel/DataStructures/PlayerData.cs b/NebulaModel/DataStructures/PlayerData.cs index db5b4bfa8..2688a765a 100644 --- a/NebulaModel/DataStructures/PlayerData.cs +++ b/NebulaModel/DataStructures/PlayerData.cs @@ -1,212 +1,218 @@ -using NebulaAPI; +#region + +using System; using System.IO; +using NebulaAPI; + +#endregion -namespace NebulaModel.DataStructures +namespace NebulaModel.DataStructures; + +[RegisterNestedType] +public class PlayerData : IPlayerData { - [RegisterNestedType] - public class PlayerData : IPlayerData + public PlayerData() { - public string Username { get; set; } - public ushort PlayerId { get; set; } - public int LocalPlanetId { get; set; } - public Float3 LocalPlanetPosition { get; set; } - public Double3 UPosition { get; set; } - public Float3 Rotation { get; set; } - public Float3 BodyRotation { get; set; } - public IMechaData Mecha { get; set; } - public int LocalStarId { get; set; } - public MechaAppearance Appearance { get; set; } - public MechaAppearance DIYAppearance { get; set; } - public int[] DIYItemId { get; set; } - public int[] DIYItemValue { get; set; } + Appearance = null; + DIYAppearance = null; + DIYItemId = Array.Empty(); + DIYItemValue = Array.Empty(); + } - public PlayerData() - { - Appearance = null; - DIYAppearance = null; - DIYItemId = System.Array.Empty(); - DIYItemValue = System.Array.Empty(); - } - public PlayerData(ushort playerId, int localPlanetId, string username = null, Float3 localPlanetPosition = new Float3(), Double3 position = new Double3(), Float3 rotation = new Float3(), Float3 bodyRotation = new Float3()) - { - PlayerId = playerId; - LocalPlanetId = localPlanetId; - Username = !string.IsNullOrWhiteSpace(username) ? username : $"Player {playerId}"; - LocalPlanetPosition = localPlanetPosition; - UPosition = position; - Rotation = rotation; - BodyRotation = bodyRotation; - Mecha = new MechaData(); - Appearance = null; - DIYAppearance = null; - DIYItemId = System.Array.Empty(); - DIYItemValue = System.Array.Empty(); - } + public PlayerData(ushort playerId, int localPlanetId, string username = null, Float3 localPlanetPosition = new(), + Double3 position = new(), Float3 rotation = new(), Float3 bodyRotation = new()) + { + PlayerId = playerId; + LocalPlanetId = localPlanetId; + Username = !string.IsNullOrWhiteSpace(username) ? username : $"Player {playerId}"; + LocalPlanetPosition = localPlanetPosition; + UPosition = position; + Rotation = rotation; + BodyRotation = bodyRotation; + Mecha = new MechaData(); + Appearance = null; + DIYAppearance = null; + DIYItemId = Array.Empty(); + DIYItemValue = Array.Empty(); + } - public void Serialize(INetDataWriter writer) + public string Username { get; set; } + public ushort PlayerId { get; set; } + public int LocalPlanetId { get; set; } + public Float3 LocalPlanetPosition { get; set; } + public Double3 UPosition { get; set; } + public Float3 Rotation { get; set; } + public Float3 BodyRotation { get; set; } + public IMechaData Mecha { get; set; } + public int LocalStarId { get; set; } + public MechaAppearance Appearance { get; set; } + public MechaAppearance DIYAppearance { get; set; } + public int[] DIYItemId { get; set; } + public int[] DIYItemValue { get; set; } + + public void Serialize(INetDataWriter writer) + { + writer.Put(Username); + writer.Put(PlayerId); + writer.Put(LocalPlanetId); + LocalPlanetPosition.Serialize(writer); + UPosition.Serialize(writer); + Rotation.Serialize(writer); + BodyRotation.Serialize(writer); + Mecha.Serialize(writer); + writer.Put(Appearance != null); + if (Appearance != null) { - writer.Put(Username); - writer.Put(PlayerId); - writer.Put(LocalPlanetId); - LocalPlanetPosition.Serialize(writer); - UPosition.Serialize(writer); - Rotation.Serialize(writer); - BodyRotation.Serialize(writer); - Mecha.Serialize(writer); - writer.Put(Appearance != null); - if(Appearance != null) + using (var ms = new MemoryStream()) { - using (MemoryStream ms = new MemoryStream()) + using (var wr = new BinaryWriter(ms)) { - using (BinaryWriter wr = new BinaryWriter(ms)) - { - Appearance.Export(wr); - } - byte[] export = ms.ToArray(); - writer.Put(export.Length); - writer.Put(export); + Appearance.Export(wr); } + var export = ms.ToArray(); + writer.Put(export.Length); + writer.Put(export); } - writer.Put(DIYAppearance != null); - if (DIYAppearance != null) + } + writer.Put(DIYAppearance != null); + if (DIYAppearance != null) + { + using (var ms = new MemoryStream()) { - using (MemoryStream ms = new MemoryStream()) + using (var wr = new BinaryWriter(ms)) { - using (BinaryWriter wr = new BinaryWriter(ms)) - { - DIYAppearance.Export(wr); - } - byte[] export = ms.ToArray(); - writer.Put(export.Length); - writer.Put(export); + DIYAppearance.Export(wr); } + var export = ms.ToArray(); + writer.Put(export.Length); + writer.Put(export); } - writer.Put(DIYItemId.Length); - for(int i = 0; i < DIYItemId.Length; i++) + } + writer.Put(DIYItemId.Length); + for (var i = 0; i < DIYItemId.Length; i++) + { + writer.Put(DIYItemId[i]); + writer.Put(DIYItemValue[i]); + } + } + + public void Deserialize(INetDataReader reader) + { + Username = reader.GetString(); + PlayerId = reader.GetUShort(); + LocalPlanetId = reader.GetInt(); + LocalPlanetPosition = reader.GetFloat3(); + UPosition = reader.GetDouble3(); + Rotation = reader.GetFloat3(); + BodyRotation = reader.GetFloat3(); + Mecha = new MechaData(); + Mecha.Deserialize(reader); + var isAppearancePresent = reader.GetBool(); + if (isAppearancePresent) + { + var len = reader.GetInt(); + var data = new byte[len]; + reader.GetBytes(data, len); + using (var ms = new MemoryStream(data)) + using (var br = new BinaryReader(ms)) + { + Appearance = new MechaAppearance(); + Appearance.Init(); + Appearance.Import(br); + } + } + var isDIYAppearancePresent = reader.GetBool(); + if (isDIYAppearancePresent) + { + var len = reader.GetInt(); + var data = new byte[len]; + reader.GetBytes(data, len); + using (var ms = new MemoryStream(data)) + using (var br = new BinaryReader(ms)) { - writer.Put(DIYItemId[i]); - writer.Put(DIYItemValue[i]); + DIYAppearance = new MechaAppearance(); + DIYAppearance.Init(); + DIYAppearance.Import(br); } } + var DIYItemLen = reader.GetInt(); + DIYItemId = new int[DIYItemLen]; + DIYItemValue = new int[DIYItemLen]; + for (var i = 0; i < DIYItemLen; i++) + { + DIYItemId[i] = reader.GetInt(); + DIYItemValue[i] = reader.GetInt(); + } + } + + public IPlayerData CreateCopyWithoutMechaData() + { + return new PlayerData(PlayerId, LocalPlanetId, Username, LocalPlanetPosition, UPosition, Rotation, BodyRotation); + } - public void Deserialize(INetDataReader reader) + // Backward compatiblity for older versions + public void Import(INetDataReader reader, int revision) + { + Username = reader.GetString(); + PlayerId = reader.GetUShort(); + LocalPlanetId = reader.GetInt(); + if (revision < 7) + { + // MechaColors is obsoleted by MechaAppearance + var mechaColors = new Float4[reader.GetInt()]; + for (var i = 0; i < mechaColors.Length; i++) + { + mechaColors[i] = reader.GetFloat4(); + } + } + LocalPlanetPosition = reader.GetFloat3(); + UPosition = reader.GetDouble3(); + Rotation = reader.GetFloat3(); + BodyRotation = reader.GetFloat3(); + MechaData mechaData = new(); + mechaData.Import(reader, revision); + Mecha = mechaData; + if (revision >= 5) { - Username = reader.GetString(); - PlayerId = reader.GetUShort(); - LocalPlanetId = reader.GetInt(); - LocalPlanetPosition = reader.GetFloat3(); - UPosition = reader.GetDouble3(); - Rotation = reader.GetFloat3(); - BodyRotation = reader.GetFloat3(); - Mecha = new MechaData(); - Mecha.Deserialize(reader); - bool isAppearancePresent = reader.GetBool(); + var isAppearancePresent = reader.GetBool(); if (isAppearancePresent) { - int len = reader.GetInt(); - byte[] data = new byte[len]; + var len = reader.GetInt(); + var data = new byte[len]; reader.GetBytes(data, len); - using (MemoryStream ms = new MemoryStream(data)) - using (BinaryReader br = new BinaryReader(ms)) + using (var ms = new MemoryStream(data)) + using (var br = new BinaryReader(ms)) { Appearance = new MechaAppearance(); Appearance.Init(); Appearance.Import(br); } } - bool isDIYAppearancePresent = reader.GetBool(); + } + if (revision >= 6) + { + var isDIYAppearancePresent = reader.GetBool(); if (isDIYAppearancePresent) { - int len = reader.GetInt(); - byte[] data = new byte[len]; + var len = reader.GetInt(); + var data = new byte[len]; reader.GetBytes(data, len); - using (MemoryStream ms = new MemoryStream(data)) - using (BinaryReader br = new BinaryReader(ms)) + using (var ms = new MemoryStream(data)) + using (var br = new BinaryReader(ms)) { DIYAppearance = new MechaAppearance(); DIYAppearance.Init(); DIYAppearance.Import(br); } } - int DIYItemLen = reader.GetInt(); + var DIYItemLen = reader.GetInt(); DIYItemId = new int[DIYItemLen]; DIYItemValue = new int[DIYItemLen]; - for(int i = 0; i < DIYItemLen; i++) + for (var i = 0; i < DIYItemLen; i++) { DIYItemId[i] = reader.GetInt(); DIYItemValue[i] = reader.GetInt(); } } - - // Backward compatiblity for older versions - public void Import(INetDataReader reader, int revision) - { - Username = reader.GetString(); - PlayerId = reader.GetUShort(); - LocalPlanetId = reader.GetInt(); - if (revision < 7) - { - // MechaColors is obsoleted by MechaAppearance - Float4[] mechaColors = new Float4[reader.GetInt()]; - for (int i = 0; i < mechaColors.Length; i++) - { - mechaColors[i] = reader.GetFloat4(); - } - } - LocalPlanetPosition = reader.GetFloat3(); - UPosition = reader.GetDouble3(); - Rotation = reader.GetFloat3(); - BodyRotation = reader.GetFloat3(); - MechaData mechaData = new(); - mechaData.Import(reader, revision); - Mecha = mechaData; - if (revision >= 5) - { - bool isAppearancePresent = reader.GetBool(); - if (isAppearancePresent) - { - int len = reader.GetInt(); - byte[] data = new byte[len]; - reader.GetBytes(data, len); - using (MemoryStream ms = new MemoryStream(data)) - using (BinaryReader br = new BinaryReader(ms)) - { - Appearance = new MechaAppearance(); - Appearance.Init(); - Appearance.Import(br); - } - } - } - if (revision >= 6) - { - bool isDIYAppearancePresent = reader.GetBool(); - if (isDIYAppearancePresent) - { - int len = reader.GetInt(); - byte[] data = new byte[len]; - reader.GetBytes(data, len); - using (MemoryStream ms = new MemoryStream(data)) - using (BinaryReader br = new BinaryReader(ms)) - { - DIYAppearance = new MechaAppearance(); - DIYAppearance.Init(); - DIYAppearance.Import(br); - } - } - int DIYItemLen = reader.GetInt(); - DIYItemId = new int[DIYItemLen]; - DIYItemValue = new int[DIYItemLen]; - for (int i = 0; i < DIYItemLen; i++) - { - DIYItemId[i] = reader.GetInt(); - DIYItemValue[i] = reader.GetInt(); - } - } - } - - public IPlayerData CreateCopyWithoutMechaData() - { - return new PlayerData(PlayerId, LocalPlanetId, Username, LocalPlanetPosition, UPosition, Rotation, BodyRotation); - } } } diff --git a/NebulaModel/DataStructures/StatisticalSnapshot.cs b/NebulaModel/DataStructures/StatisticalSnapshot.cs index 9e748af5c..72204cb90 100644 --- a/NebulaModel/DataStructures/StatisticalSnapshot.cs +++ b/NebulaModel/DataStructures/StatisticalSnapshot.cs @@ -1,116 +1,121 @@ -using System.Collections.Generic; +#region + +using System.Collections.Generic; using System.IO; -namespace NebulaModel.DataStructures +#endregion + +namespace NebulaModel.DataStructures; + +public class StatisticalSnapShot { - public class StatisticalSnapShot + public long CapturedGameTick; + public long[] EnergyStored; + public long[] HashRegister; + public long[] PowerChargingRegister; + public long[] PowerConsumptionRegister; + public long[] PowerDischargingRegister; + + public long[] PowerGenerationRegister; + + //List of statistical changes for each planet that happend in one gameTick + public List[] ProductionChangesPerFactory; + + public StatisticalSnapShot(long gameTick, int numOfActiveFactories) { - //List of statistical changes for each planet that happend in one gameTick - public List[] ProductionChangesPerFactory; - public long[] PowerGenerationRegister; - public long[] PowerConsumptionRegister; - public long[] PowerChargingRegister; - public long[] PowerDischargingRegister; - public long[] HashRegister; - public long CapturedGameTick; - public long[] EnergyStored; - - public StatisticalSnapShot(long gameTick, int numOfActiveFactories) + ProductionChangesPerFactory = new List[numOfActiveFactories]; + for (var i = 0; i < numOfActiveFactories; i++) { - ProductionChangesPerFactory = new List[numOfActiveFactories]; - for (int i = 0; i < numOfActiveFactories; i++) - { - ProductionChangesPerFactory[i] = new List(); - } - PowerGenerationRegister = new long[numOfActiveFactories]; - PowerConsumptionRegister = new long[numOfActiveFactories]; - PowerChargingRegister = new long[numOfActiveFactories]; - PowerDischargingRegister = new long[numOfActiveFactories]; - HashRegister = new long[numOfActiveFactories]; - EnergyStored = new long[numOfActiveFactories]; - CapturedGameTick = gameTick; + ProductionChangesPerFactory[i] = new List(); } + PowerGenerationRegister = new long[numOfActiveFactories]; + PowerConsumptionRegister = new long[numOfActiveFactories]; + PowerChargingRegister = new long[numOfActiveFactories]; + PowerDischargingRegister = new long[numOfActiveFactories]; + HashRegister = new long[numOfActiveFactories]; + EnergyStored = new long[numOfActiveFactories]; + CapturedGameTick = gameTick; + } + + public StatisticalSnapShot(BinaryReader br) + { + CapturedGameTick = br.ReadInt64(); + var factoryCount = br.ReadInt32(); + + ProductionChangesPerFactory = new List[factoryCount]; + PowerGenerationRegister = new long[factoryCount]; + PowerConsumptionRegister = new long[factoryCount]; + PowerChargingRegister = new long[factoryCount]; + PowerDischargingRegister = new long[factoryCount]; + EnergyStored = new long[factoryCount]; + HashRegister = new long[factoryCount]; - public StatisticalSnapShot(BinaryReader br) + for (var factoryId = 0; factoryId < factoryCount; factoryId++) { - CapturedGameTick = br.ReadInt64(); - int factoryCount = br.ReadInt32(); - - ProductionChangesPerFactory = new List[factoryCount]; - PowerGenerationRegister = new long[factoryCount]; - PowerConsumptionRegister = new long[factoryCount]; - PowerChargingRegister = new long[factoryCount]; - PowerDischargingRegister = new long[factoryCount]; - EnergyStored = new long[factoryCount]; - HashRegister = new long[factoryCount]; - - for (int factoryId = 0; factoryId < factoryCount; factoryId++) + ProductionChangesPerFactory[factoryId] = new List(); + var changesCount = br.ReadInt32(); + for (var changeId = 0; changeId < changesCount; changeId++) { - ProductionChangesPerFactory[factoryId] = new List(); - int changesCount = br.ReadInt32(); - for (int changeId = 0; changeId < changesCount; changeId++) - { - ProductionChangesPerFactory[factoryId].Add(new ProductionChangeStruct(br)); - } - PowerGenerationRegister[factoryId] = br.ReadInt64(); - PowerConsumptionRegister[factoryId] = br.ReadInt64(); - PowerChargingRegister[factoryId] = br.ReadInt64(); - PowerDischargingRegister[factoryId] = br.ReadInt64(); - EnergyStored[factoryId] = br.ReadInt64(); - HashRegister[factoryId] = br.ReadInt64(); + ProductionChangesPerFactory[factoryId].Add(new ProductionChangeStruct(br)); } + PowerGenerationRegister[factoryId] = br.ReadInt64(); + PowerConsumptionRegister[factoryId] = br.ReadInt64(); + PowerChargingRegister[factoryId] = br.ReadInt64(); + PowerDischargingRegister[factoryId] = br.ReadInt64(); + EnergyStored[factoryId] = br.ReadInt64(); + HashRegister[factoryId] = br.ReadInt64(); } + } - public void Export(BinaryWriter bw) - { - bw.Write(CapturedGameTick); + public void Export(BinaryWriter bw) + { + bw.Write(CapturedGameTick); - //Collect production/consumption statistics from factories - bw.Write(ProductionChangesPerFactory.Length); - for (int factoryId = 0; factoryId < ProductionChangesPerFactory.Length; factoryId++) + //Collect production/consumption statistics from factories + bw.Write(ProductionChangesPerFactory.Length); + for (var factoryId = 0; factoryId < ProductionChangesPerFactory.Length; factoryId++) + { + bw.Write(ProductionChangesPerFactory[factoryId].Count); + for (var changeId = 0; changeId < ProductionChangesPerFactory[factoryId].Count; changeId++) { - bw.Write(ProductionChangesPerFactory[factoryId].Count); - for (int changeId = 0; changeId < ProductionChangesPerFactory[factoryId].Count; changeId++) - { - ProductionChangesPerFactory[factoryId][changeId].Export(bw); - } - - //Collect info about power system of the factory - bw.Write(PowerGenerationRegister[factoryId]); - bw.Write(PowerConsumptionRegister[factoryId]); - bw.Write(PowerChargingRegister[factoryId]); - bw.Write(PowerDischargingRegister[factoryId]); - bw.Write(EnergyStored[factoryId]); - bw.Write(HashRegister[factoryId]); + ProductionChangesPerFactory[factoryId][changeId].Export(bw); } + + //Collect info about power system of the factory + bw.Write(PowerGenerationRegister[factoryId]); + bw.Write(PowerConsumptionRegister[factoryId]); + bw.Write(PowerChargingRegister[factoryId]); + bw.Write(PowerDischargingRegister[factoryId]); + bw.Write(EnergyStored[factoryId]); + bw.Write(HashRegister[factoryId]); } + } - public struct ProductionChangeStruct //12 bytes total - { - public bool IsProduction; //1-byte - public ushort ProductId; //2-byte - public int Amount; //4-byte + public struct ProductionChangeStruct //12 bytes total + { + public bool IsProduction; //1-byte + public ushort ProductId; //2-byte + public int Amount; //4-byte - public ProductionChangeStruct(bool isProduction, ushort productId, int amount) - { - IsProduction = isProduction; - ProductId = productId; - Amount = amount; - } + public ProductionChangeStruct(bool isProduction, ushort productId, int amount) + { + IsProduction = isProduction; + ProductId = productId; + Amount = amount; + } - public ProductionChangeStruct(BinaryReader r) - { - IsProduction = r.ReadBoolean(); - ProductId = r.ReadUInt16(); - Amount = r.ReadInt32(); - } + public ProductionChangeStruct(BinaryReader r) + { + IsProduction = r.ReadBoolean(); + ProductId = r.ReadUInt16(); + Amount = r.ReadInt32(); + } - public void Export(BinaryWriter w) - { - w.Write(IsProduction); - w.Write(ProductId); - w.Write(Amount); - } + public void Export(BinaryWriter w) + { + w.Write(IsProduction); + w.Write(ProductId); + w.Write(Amount); } } } diff --git a/NebulaModel/DataStructures/ToggleSwitch.cs b/NebulaModel/DataStructures/ToggleSwitch.cs index eb2b78f92..cedc875fd 100644 --- a/NebulaModel/DataStructures/ToggleSwitch.cs +++ b/NebulaModel/DataStructures/ToggleSwitch.cs @@ -1,47 +1,50 @@ -using NebulaAPI; +#region + using System; using System.Threading; +using NebulaAPI; + +#endregion + +namespace NebulaModel.DataStructures; -namespace NebulaModel.DataStructures +public sealed class ToggleSwitch : IToggle { - public sealed class ToggleSwitch : IToggle + private int onCount; + + public bool Value => onCount > 0; + + public IDisposable On() { - private int onCount; + return new Toggle(this, 1); + } - public bool Value => onCount > 0; + public static implicit operator bool(ToggleSwitch toggle) + { + return toggle.Value; + } - public static implicit operator bool(ToggleSwitch toggle) - { - return toggle.Value; - } + public Toggle On(bool conditional) + { + return new Toggle(this, conditional ? 1 : 0); + } - public Toggle On(bool conditional) - { - return new Toggle(this, conditional ? 1 : 0); - } + public readonly struct Toggle : IDisposable + { + private readonly ToggleSwitch value; + private readonly int count; - public IDisposable On() + public Toggle(ToggleSwitch value, int count) { - return new Toggle(this, 1); + this.value = value; + this.count = count; + + Interlocked.Add(ref value.onCount, count); } - public readonly struct Toggle : IDisposable + public void Dispose() { - private readonly ToggleSwitch value; - private readonly int count; - - public Toggle(ToggleSwitch value, int count) - { - this.value = value; - this.count = count; - - Interlocked.Add(ref value.onCount, count); - } - - public void Dispose() - { - Interlocked.Add(ref value.onCount, -count); - } + Interlocked.Add(ref value.onCount, -count); } } } diff --git a/NebulaModel/Logger/ILogger.cs b/NebulaModel/Logger/ILogger.cs index 2caea6b15..d013e9f94 100644 --- a/NebulaModel/Logger/ILogger.cs +++ b/NebulaModel/Logger/ILogger.cs @@ -1,13 +1,12 @@ -namespace NebulaModel.Logger +namespace NebulaModel.Logger; + +public interface ILogger { - public interface ILogger - { - void LogDebug(object data); + void LogDebug(object data); - void LogInfo(object data); + void LogInfo(object data); - void LogWarning(object data); + void LogWarning(object data); - void LogError(object data); - } + void LogError(object data); } diff --git a/NebulaModel/Logger/Log.cs b/NebulaModel/Logger/Log.cs index 116e0d95f..db6fb9075 100644 --- a/NebulaModel/Logger/Log.cs +++ b/NebulaModel/Logger/Log.cs @@ -1,99 +1,101 @@ -using System; +#region + +using System; using System.Diagnostics; using System.Text.RegularExpressions; using WebSocketSharp; -namespace NebulaModel.Logger +#endregion + +namespace NebulaModel.Logger; + +public static class Log { - public static class Log + private static ILogger logger; + public static string LastInfoMsg { get; set; } + public static string LastWarnMsg { get; set; } + public static string LastErrorMsg { get; set; } + + public static void Init(ILogger logger) { - public static string LastInfoMsg { get; set; } - public static string LastWarnMsg { get; set; } - public static string LastErrorMsg { get; set; } + Log.logger = logger; + } - private static ILogger logger; + [Conditional("DEBUG")] + public static void Debug(string message) + { + logger.LogDebug(message); + } - public static void Init(ILogger logger) - { - Log.logger = logger; - } + [Conditional("DEBUG")] + public static void Debug(object message) + { + Debug(message?.ToString()); + } - [Conditional("DEBUG")] - public static void Debug(string message) - { - logger.LogDebug(message); - } + public static void Info(string message) + { + logger.LogInfo(message); + LastInfoMsg = message; + } - [Conditional("DEBUG")] - public static void Debug(object message) - { - Debug(message?.ToString()); - } + public static void Info(object message) + { + Info(message?.ToString()); + } - public static void Info(string message) - { - logger.LogInfo(message); - LastInfoMsg = message; - } + public static void Warn(string message) + { + logger.LogWarning(message); + } - public static void Info(object message) - { - Info(message?.ToString()); - } + public static void Warn(object message) + { + Warn(message?.ToString()); + } - public static void Warn(string message) - { - logger.LogWarning(message); - } + public static void WarnInform(string message) + { + Warn(message); + LastWarnMsg = message; + } - public static void Warn(object message) + public static void Error(string message) + { + logger.LogError(message); + LastErrorMsg = message; + if (UIFatalErrorTip.instance != null) { - Warn(message?.ToString()); + UIFatalErrorTip.instance.ShowError("[Nebula Error] " + message, ""); } + } - public static void WarnInform(string message) - { - Warn(message); - LastWarnMsg = message; - } + public static void Error(Exception ex) + { + Error(ex?.ToString()); + } - public static void Error(string message) - { - logger.LogError(message); - LastErrorMsg = message; - if (UIFatalErrorTip.instance != null) - { - UIFatalErrorTip.instance.ShowError("[Nebula Error] " + message, ""); - } - } + public static void Error(string message, Exception ex) + { + Error(message); + Error(ex); + } - public static void Error(Exception ex) - { - Error(ex?.ToString()); - } + public static void SocketOutput(LogData data, string _) + { + var log = data.ToString(); + var ipv4Regex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"; + var ipv6Regex = "([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}"; + log = Regex.Replace(log, ipv4Regex, "(IPv4 Address)"); + log = Regex.Replace(log, ipv6Regex, "(IPv6 Address)"); - public static void Error(string message, Exception ex) + if (data.Level >= LogLevel.Warn) { - Error(message); - Error(ex); + Warn(log); } - - public static void SocketOutput(LogData data, string _) + else { - string log = data.ToString(); - string ipv4Regex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"; - string ipv6Regex = "([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}"; - log = Regex.Replace(log, ipv4Regex, "(IPv4 Address)"); - log = Regex.Replace(log, ipv6Regex, "(IPv6 Address)"); - - if (data.Level >= LogLevel.Warn) - { - Warn(log); - } - else - { - Info(log); - } + Info(log); } } } diff --git a/NebulaModel/MultiplayerOptions.cs b/NebulaModel/MultiplayerOptions.cs index 5a26ecb8b..da8d7398b 100644 --- a/NebulaModel/MultiplayerOptions.cs +++ b/NebulaModel/MultiplayerOptions.cs @@ -1,173 +1,186 @@ -using BepInEx.Configuration; -using NebulaAPI; +#region + +using System; +using System.ComponentModel; +using BepInEx.Configuration; using NebulaModel.Attributes; using NebulaModel.DataStructures; using NebulaModel.Utils; -using System; -using System.ComponentModel; using UnityEngine; using UnityEngine.UI; -namespace NebulaModel +#endregion + +namespace NebulaModel; + +[Serializable] +public class MultiplayerOptions : ICloneable { - [System.Serializable] - public class MultiplayerOptions : ICloneable - { - [DisplayName("Nickname")] - public string Nickname { get; set; } = string.Empty; + private const string _ngrokAuthtokenDisplayname = "Ngrok Authtoken"; - [DisplayName("Server Password"), Category("Network")] - [Description("If provided, this will set a password for your hosted server.")] - [UIContentType(InputField.ContentType.Password)] - public string ServerPassword { get; set; } = string.Empty; + private bool _streamerMode; - public string LastClientPassword { get; set; } = string.Empty; + [DisplayName("Nickname")] public string Nickname { get; set; } = string.Empty; - [DisplayName("Host Port"), Category("Network")] - [UIRange(1, ushort.MaxValue)] - public ushort HostPort { get; set; } = 8469; + [DisplayName("Server Password")] + [Category("Network")] + [Description("If provided, this will set a password for your hosted server.")] + [UIContentType(InputField.ContentType.Password)] + public string ServerPassword { get; set; } = string.Empty; - [DisplayName("Enable UPnp/Pmp Support"), Category("Network")] - [Description("If enabled, attempt to automatically create a port mapping using UPnp/Pmp (only works if your router has this feature and it is enabled)")] - public bool EnableUPnpOrPmpSupport { get; set; } = false; + public string LastClientPassword { get; set; } = string.Empty; - [DisplayName("Enable Experimental Ngrok support"), Category("Network")] - [Description("If enabled, when hosting a server this will automatically download and install the Ngrok client and set up an Ngrok tunnel that provides an address at which the server can be joined")] - public bool EnableNgrok { get; set; } = false; + [DisplayName("Host Port")] [Category("Network")] [UIRange(1, ushort.MaxValue)] + public ushort HostPort { get; set; } = 8469; - private const string _ngrokAuthtokenDisplayname = "Ngrok Authtoken"; - [DisplayName(_ngrokAuthtokenDisplayname), Category("Network")] - [Description("This is required for Ngrok support and can be obtained by creating a free account at https://ngrok.com/")] - [UICharacterLimit(49)] - public string NgrokAuthtoken { get; set; } = string.Empty; + [DisplayName("Enable UPnp/Pmp Support")] + [Category("Network")] + [Description( + "If enabled, attempt to automatically create a port mapping using UPnp/Pmp (only works if your router has this feature and it is enabled)")] + public bool EnableUPnpOrPmpSupport { get; set; } = false; - [DisplayName("Ngrok Region"), Category("Network")] - [Description("Available Regions: us, eu, au, ap, sa, jp, in")] - public string NgrokRegion { get; set; } = string.Empty; + [DisplayName("Enable Experimental Ngrok support")] + [Category("Network")] + [Description( + "If enabled, when hosting a server this will automatically download and install the Ngrok client and set up an Ngrok tunnel that provides an address at which the server can be joined")] + public bool EnableNgrok { get; set; } = false; - [DisplayName("Remember Last IP"), Category("Network")] - public bool RememberLastIP { get; set; } = true; + [DisplayName(_ngrokAuthtokenDisplayname)] + [Category("Network")] + [Description("This is required for Ngrok support and can be obtained by creating a free account at https://ngrok.com/")] + [UICharacterLimit(49)] + public string NgrokAuthtoken { get; set; } = string.Empty; - [DisplayName("Remember Last Client Password"), Category("Network")] - public bool RememberLastClientPassword { get; set; } = true; + [DisplayName("Ngrok Region")] [Category("Network")] [Description("Available Regions: us, eu, au, ap, sa, jp, in")] + public string NgrokRegion { get; set; } = string.Empty; - [DisplayName("Enable Discord RPC (requires restart)"), Category("Network")] - public bool EnableDiscordRPC { get; set; } = true; + [DisplayName("Remember Last IP")] [Category("Network")] + public bool RememberLastIP { get; set; } = true; - [DisplayName("Auto accept Discord join requests"), Category("Network")] - public bool AutoAcceptDiscordJoinRequests { get; set; } = false; + [DisplayName("Remember Last Client Password")] [Category("Network")] + public bool RememberLastClientPassword { get; set; } = true; - [DisplayName("IP Configuration"), Category("Network")] - [Description("Configure which type of IP should be used by Discord RPC")] - public IPUtils.IPConfiguration IPConfiguration { get; set; } + [DisplayName("Enable Discord RPC (requires restart)")] [Category("Network")] + public bool EnableDiscordRPC { get; set; } = true; - [DisplayName("Cleanup inactive sessions"), Category("Network")] - [Description("If disabled the underlying networking library will not cleanup inactive connections. This might solve issues with clients randomly disconnecting and hosts having a 'System.ObjectDisposedException'.")] - public bool CleanupInactiveSessions { get; set; } = false; + [DisplayName("Auto accept Discord join requests")] [Category("Network")] + public bool AutoAcceptDiscordJoinRequests { get; set; } = false; - [DisplayName("Show Lobby Hints")] - public bool ShowLobbyHints { get; set; } = true; + [DisplayName("IP Configuration")] + [Category("Network")] + [Description("Configure which type of IP should be used by Discord RPC")] + public IPUtils.IPConfiguration IPConfiguration { get; set; } - public string LastIP { get; set; } = string.Empty; + [DisplayName("Cleanup inactive sessions")] + [Category("Network")] + [Description( + "If disabled the underlying networking library will not cleanup inactive connections. This might solve issues with clients randomly disconnecting and hosts having a 'System.ObjectDisposedException'.")] + public bool CleanupInactiveSessions { get; set; } = false; - [DisplayName("Sync Ups")] - [Description("If enabled the UPS of each player is synced. This ensures a similar amount of GameTick() calls.")] - public bool SyncUps { get; set; } = true; + [DisplayName("Show Lobby Hints")] public bool ShowLobbyHints { get; set; } = true; - [DisplayName("Sync Soil")] - [Description("If enabled the soil count of each players is added together and used as one big pool for everyone. Note that this is a server side setting applied to all clients.")] - public bool SyncSoil { get; set; } = false; + public string LastIP { get; set; } = string.Empty; - private bool _streamerMode = false; - [DisplayName("Streamer mode")] - [Description("If enabled specific personal information like your IP address is hidden from the ingame chat and input fields.")] - public bool StreamerMode { - get => _streamerMode; - set { - _streamerMode = value; + [DisplayName("Sync Ups")] + [Description("If enabled the UPS of each player is synced. This ensures a similar amount of GameTick() calls.")] + public bool SyncUps { get; set; } = true; - InputField ngrokAuthTokenInput = GameObject.Find("list/scroll-view/viewport/content/Network/NgrokAuthtoken")?.GetComponentInChildren(); - UpdateInputFieldContentType(ref ngrokAuthTokenInput); + [DisplayName("Sync Soil")] + [Description( + "If enabled the soil count of each players is added together and used as one big pool for everyone. Note that this is a server side setting applied to all clients.")] + public bool SyncSoil { get; set; } = false; - InputField hostIpInput = GameObject.Find("UI Root/Overlay Canvas/Nebula - Multiplayer Menu/Host IP Address/InputField")?.GetComponentInChildren(); - UpdateInputFieldContentType(ref hostIpInput); - } + [DisplayName("Streamer mode")] + [Description( + "If enabled specific personal information like your IP address is hidden from the ingame chat and input fields.")] + public bool StreamerMode + { + get => _streamerMode; + set + { + _streamerMode = value; + + var ngrokAuthTokenInput = GameObject.Find("list/scroll-view/viewport/content/Network/NgrokAuthtoken") + ?.GetComponentInChildren(); + UpdateInputFieldContentType(ref ngrokAuthTokenInput); + + var hostIpInput = GameObject.Find("UI Root/Overlay Canvas/Nebula - Multiplayer Menu/Host IP Address/InputField") + ?.GetComponentInChildren(); + UpdateInputFieldContentType(ref hostIpInput); } + } - [DisplayName("Chat Hotkey"), Category("Chat")] - [Description("Keyboard shortcut to toggle the chat window")] - public KeyboardShortcut ChatHotkey { get; set; } = new KeyboardShortcut(KeyCode.BackQuote, KeyCode.LeftAlt); + [DisplayName("Chat Hotkey")] [Category("Chat")] [Description("Keyboard shortcut to toggle the chat window")] + public KeyboardShortcut ChatHotkey { get; set; } = new(KeyCode.BackQuote, KeyCode.LeftAlt); - [DisplayName("Auto Open Chat"), Category("Chat")] - [Description("Auto open chat window when receiving message from other players")] - public bool AutoOpenChat { get; set; } = true; + [DisplayName("Auto Open Chat")] + [Category("Chat")] + [Description("Auto open chat window when receiving message from other players")] + public bool AutoOpenChat { get; set; } = true; - [DisplayName("Show system warn message"), Category("Chat")] - public bool EnableWarnMessage { get; set; } = true; + [DisplayName("Show system warn message")] [Category("Chat")] + public bool EnableWarnMessage { get; set; } = true; - [DisplayName("Show system info message"), Category("Chat")] - public bool EnableInfoMessage { get; set; } = true; + [DisplayName("Show system info message")] [Category("Chat")] + public bool EnableInfoMessage { get; set; } = true; - [DisplayName("Default chat position"), Category("Chat")] - public ChatPosition DefaultChatPosition { get; set; } = ChatPosition.LeftMiddle; - - [DisplayName("Default chat size"), Category("Chat")] - public ChatSize DefaultChatSize { get; set; } = ChatSize.Medium; + [DisplayName("Default chat position")] [Category("Chat")] + public ChatPosition DefaultChatPosition { get; set; } = ChatPosition.LeftMiddle; - [DisplayName("Notification duration"), Category("Chat")] - [Description("How long should the active message stay on the screen in seconds")] - public int NotificationDuration { get; set; } = 15; + [DisplayName("Default chat size")] [Category("Chat")] + public ChatSize DefaultChatSize { get; set; } = ChatSize.Medium; - [DisplayName("Chat Window Opacity"), Category("Chat")] - [UIRange(0f, 1.0f, true)] - public float ChatWindowOpacity { get; set; } = 0.8f; + [DisplayName("Notification duration")] + [Category("Chat")] + [Description("How long should the active message stay on the screen in seconds")] + public int NotificationDuration { get; set; } = 15; - // Detail function group buttons - public bool PowerGridEnabled { get; set; } = false; - public bool VeinDistributionEnabled { get; set; } = false; - public bool SpaceNavigationEnabled { get; set; } = true; - public bool BuildingWarningEnabled { get; set; } = true; - public bool BuildingIconEnabled { get; set; } = true; - public bool GuidingLightEnabled { get; set; } = true; + [DisplayName("Chat Window Opacity")] [Category("Chat")] [UIRange(0f, 1.0f, true)] + public float ChatWindowOpacity { get; set; } = 0.8f; - public bool RemoteAccessEnabled { get; set; } = false; - public string RemoteAccessPassword { get; set; } = ""; - public bool AutoPauseEnabled { get; set; } = true; + // Detail function group buttons + public bool PowerGridEnabled { get; set; } = false; + public bool VeinDistributionEnabled { get; set; } = false; + public bool SpaceNavigationEnabled { get; set; } = true; + public bool BuildingWarningEnabled { get; set; } = true; + public bool BuildingIconEnabled { get; set; } = true; + public bool GuidingLightEnabled { get; set; } = true; + public bool RemoteAccessEnabled { get; set; } = false; + public string RemoteAccessPassword { get; set; } = ""; + public bool AutoPauseEnabled { get; set; } = true; - public object Clone() - { - return MemberwiseClone(); - } - private void UpdateInputFieldContentType(ref InputField inputField) + public object Clone() + { + return MemberwiseClone(); + } + + private void UpdateInputFieldContentType(ref InputField inputField) + { + if (inputField != null) { - if (inputField != null) + if (StreamerMode) { - if (StreamerMode) - { - inputField.contentType = InputField.ContentType.Password; - } - else - { - inputField.contentType = InputField.ContentType.Standard; - } - inputField.UpdateLabel(); + inputField.contentType = InputField.ContentType.Password; } - } - - public void ModifyInputFieldAtCreation(string displayName, ref InputField inputField) - { - switch (displayName) + else { - case _ngrokAuthtokenDisplayname: - { - UpdateInputFieldContentType(ref inputField); - break; - } + inputField.contentType = InputField.ContentType.Standard; } - + inputField.UpdateLabel(); } + } + public void ModifyInputFieldAtCreation(string displayName, ref InputField inputField) + { + switch (displayName) + { + case _ngrokAuthtokenDisplayname: + { + UpdateInputFieldContentType(ref inputField); + break; + } + } } } diff --git a/NebulaModel/NebulaModel.csproj b/NebulaModel/NebulaModel.csproj index 336c618cd..9a118cda4 100644 --- a/NebulaModel/NebulaModel.csproj +++ b/NebulaModel/NebulaModel.csproj @@ -1,20 +1,20 @@  - - - - + + + + - - - PreserveNewest - - - PreserveNewest - - + + + PreserveNewest + + + PreserveNewest + + - - - + + + \ No newline at end of file diff --git a/NebulaModel/NetworkProvider.cs b/NebulaModel/NetworkProvider.cs index c517461a7..e14e1da8d 100644 --- a/NebulaModel/NetworkProvider.cs +++ b/NebulaModel/NetworkProvider.cs @@ -1,43 +1,46 @@ -using NebulaAPI; -using NebulaModel.Networking.Serialization; +#region + using System; +using NebulaAPI; +using NebulaModel.Networking.Serialization; + +#endregion -namespace NebulaModel +namespace NebulaModel; + +public abstract class NetworkProvider : IDisposable, INetworkProvider { - public abstract class NetworkProvider : IDisposable, INetworkProvider + protected NetworkProvider(IPlayerManager playerManager) { - public NetPacketProcessor PacketProcessor { get; protected set; } + PacketProcessor = new NetPacketProcessor(); + PlayerManager = playerManager; + } - public IPlayerManager PlayerManager { get; } + public NetPacketProcessor PacketProcessor { get; protected set; } - protected NetworkProvider(IPlayerManager playerManager) - { - PacketProcessor = new NetPacketProcessor(); - PlayerManager = playerManager; - } + public abstract void Dispose(); - public abstract void Start(); + public IPlayerManager PlayerManager { get; } - public abstract void Stop(); + public abstract void SendPacket(T packet) where T : class, new(); - public abstract void Dispose(); + public abstract void SendPacketToLocalStar(T packet) where T : class, new(); - public abstract void SendPacket(T packet) where T : class, new(); + public abstract void SendPacketToLocalPlanet(T packet) where T : class, new(); - public abstract void SendPacketToLocalStar(T packet) where T : class, new(); + public abstract void SendPacketToPlanet(T packet, int planetId) where T : class, new(); - public abstract void SendPacketToLocalPlanet(T packet) where T : class, new(); + public abstract void SendPacketToStar(T packet, int starId) where T : class, new(); - public abstract void SendPacketToPlanet(T packet, int planetId) where T : class, new(); + public abstract void SendPacketExclude(T packet, INebulaConnection exclude) + where T : class, new(); - public abstract void SendPacketToStar(T packet, int starId) where T : class, new(); + public abstract void SendPacketToStarExclude(T packet, int starId, INebulaConnection exclude) + where T : class, new(); - public abstract void SendPacketExclude(T packet, INebulaConnection exclude) - where T : class, new(); + public abstract void Update(); - public abstract void SendPacketToStarExclude(T packet, int starId, INebulaConnection exclude) - where T : class, new(); + public abstract void Start(); - public abstract void Update(); - } + public abstract void Stop(); } diff --git a/NebulaModel/Networking/BinaryUtils.cs b/NebulaModel/Networking/BinaryUtils.cs index d765cac0a..d72ac3036 100644 --- a/NebulaModel/Networking/BinaryUtils.cs +++ b/NebulaModel/Networking/BinaryUtils.cs @@ -1,73 +1,74 @@ -using K4os.Compression.LZ4.Streams; -using NebulaAPI; +#region + using System; using System.IO; +using K4os.Compression.LZ4.Streams; +using NebulaAPI; + +#endregion -namespace NebulaModel.Networking +namespace NebulaModel.Networking; + +public static class BinaryUtils { - public static class BinaryUtils + private const int BUFFER_SIZE = 8192; + + public class Writer : IWriterProvider { - private const int BUFFER_SIZE = 8192; + private readonly BufferedStream bs; + private readonly LZ4EncoderStream ls; + private readonly MemoryStream ms; - public class Writer : IWriterProvider + public Writer() { - private readonly MemoryStream ms; - private readonly LZ4EncoderStream ls; - private readonly BufferedStream bs; - private readonly BinaryWriter bw; - - public BinaryWriter BinaryWriter => bw; + ms = new MemoryStream(); + ls = LZ4Stream.Encode(ms); + bs = new BufferedStream(ls, BUFFER_SIZE); + BinaryWriter = new BinaryWriter(bs); + } - public Writer() - { - ms = new MemoryStream(); - ls = LZ4Stream.Encode(ms); - bs = new BufferedStream(ls, BUFFER_SIZE); - bw = new BinaryWriter(bs); - } + public BinaryWriter BinaryWriter { get; } - public void Dispose() - { - bw?.Close(); - bs?.Dispose(); - ls?.Dispose(); - ms?.Dispose(); - GC.SuppressFinalize(this); - } + public void Dispose() + { + BinaryWriter?.Close(); + bs?.Dispose(); + ls?.Dispose(); + ms?.Dispose(); + GC.SuppressFinalize(this); + } - public byte[] CloseAndGetBytes() - { - bw?.Close(); - return ms?.ToArray() ?? Array.Empty(); - } + public byte[] CloseAndGetBytes() + { + BinaryWriter?.Close(); + return ms?.ToArray() ?? Array.Empty(); } + } - public class Reader : IReaderProvider + public class Reader : IReaderProvider + { + private readonly BufferedStream bs; + private readonly LZ4DecoderStream ls; + + public Reader(byte[] bytes) { - private readonly MemoryStream ms; - private readonly LZ4DecoderStream ls; - private readonly BufferedStream bs; - private readonly BinaryReader br; + MemoryStream = new MemoryStream(bytes); + ls = LZ4Stream.Decode(MemoryStream); + bs = new BufferedStream(ls, BUFFER_SIZE); + BinaryReader = new BinaryReader(bs); + } - public MemoryStream MemoryStream => ms; - public BinaryReader BinaryReader => br; + public MemoryStream MemoryStream { get; } - public Reader(byte[] bytes) - { - ms = new MemoryStream(bytes); - ls = LZ4Stream.Decode(ms); - bs = new BufferedStream(ls, BUFFER_SIZE); - br = new BinaryReader(bs); - } + public BinaryReader BinaryReader { get; } - public void Dispose() - { - br?.Close(); - bs?.Dispose(); - ls?.Dispose(); - ms?.Dispose(); - GC.SuppressFinalize(this); - } + public void Dispose() + { + BinaryReader?.Close(); + bs?.Dispose(); + ls?.Dispose(); + MemoryStream?.Dispose(); + GC.SuppressFinalize(this); } } } diff --git a/NebulaModel/Networking/DelayedPacket.cs b/NebulaModel/Networking/DelayedPacket.cs index 16e91d812..ea3e214c7 100644 --- a/NebulaModel/Networking/DelayedPacket.cs +++ b/NebulaModel/Networking/DelayedPacket.cs @@ -1,16 +1,19 @@ -using System; +#region -namespace NebulaModel.Networking +using System; + +#endregion + +namespace NebulaModel.Networking; + +public struct DelayedPacket { - public struct DelayedPacket - { - public PendingPacket Packet { get; } - public DateTime DueTime { get; } + public PendingPacket Packet { get; } + public DateTime DueTime { get; } - public DelayedPacket(PendingPacket packet, DateTime dueTime) - { - Packet = packet; - DueTime = dueTime; - } + public DelayedPacket(PendingPacket packet, DateTime dueTime) + { + Packet = packet; + DueTime = dueTime; } } diff --git a/NebulaModel/Networking/DisconnectionReason.cs b/NebulaModel/Networking/DisconnectionReason.cs index c75e7046d..2b1626de4 100644 --- a/NebulaModel/Networking/DisconnectionReason.cs +++ b/NebulaModel/Networking/DisconnectionReason.cs @@ -1,21 +1,20 @@ -namespace NebulaModel.Networking +namespace NebulaModel.Networking; + +public enum DisconnectionReason { - public enum DisconnectionReason - { - // Websocket Error Codes - Normal = 1000, - ProtocolError = 1002, - InvalidData = 1007, + // Websocket Error Codes + Normal = 1000, + ProtocolError = 1002, + InvalidData = 1007, - // Nebula Specific Error Codes - HostStillLoading = 2000, - ClientRequestedDisconnect = 2001, - ModVersionMismatch = 2002, - GameVersionMismatch = 2003, + // Nebula Specific Error Codes + HostStillLoading = 2000, + ClientRequestedDisconnect = 2001, + ModVersionMismatch = 2002, + GameVersionMismatch = 2003, - // Mod Specific Error Codes - ModIsMissing = 2500, - ModIsMissingOnServer = 2501 - } + // Mod Specific Error Codes + ModIsMissing = 2500, + ModIsMissingOnServer = 2501 } diff --git a/NebulaModel/Networking/IClient.cs b/NebulaModel/Networking/IClient.cs index fd0cdad1c..0ee488939 100644 --- a/NebulaModel/Networking/IClient.cs +++ b/NebulaModel/Networking/IClient.cs @@ -1,9 +1,12 @@ -using System.Net; +#region -namespace NebulaModel.Networking +using System.Net; + +#endregion + +namespace NebulaModel.Networking; + +public interface IClient { - public interface IClient - { - IPEndPoint ServerEndpoint { get; } - } -} \ No newline at end of file + IPEndPoint ServerEndpoint { get; } +} diff --git a/NebulaModel/Networking/IServer.cs b/NebulaModel/Networking/IServer.cs index ed9e68945..d49f21557 100644 --- a/NebulaModel/Networking/IServer.cs +++ b/NebulaModel/Networking/IServer.cs @@ -1,11 +1,10 @@ -namespace NebulaModel.Networking +namespace NebulaModel.Networking; + +public interface IServer { - public interface IServer - { - ushort Port { get; } - string NgrokAddress { get; } - bool NgrokActive { get; } - bool NgrokEnabled { get; } - string NgrokLastErrorCode { get; } - } -} \ No newline at end of file + ushort Port { get; } + string NgrokAddress { get; } + bool NgrokActive { get; } + bool NgrokEnabled { get; } + string NgrokLastErrorCode { get; } +} diff --git a/NebulaModel/Networking/NebulaConnection.cs b/NebulaModel/Networking/NebulaConnection.cs index 021e04524..78a89f7f4 100644 --- a/NebulaModel/Networking/NebulaConnection.cs +++ b/NebulaModel/Networking/NebulaConnection.cs @@ -1,129 +1,133 @@ -using NebulaAPI; -using NebulaModel.Logger; -using NebulaModel.Networking.Serialization; +#region + using System; using System.Collections.Generic; using System.Net; +using System.Text; +using NebulaAPI; +using NebulaModel.Logger; +using NebulaModel.Networking.Serialization; using WebSocketSharp; -namespace NebulaModel.Networking +#endregion + +namespace NebulaModel.Networking; + +public class NebulaConnection : INebulaConnection { - public class NebulaConnection : INebulaConnection + private readonly NetPacketProcessor packetProcessor; + private readonly EndPoint peerEndpoint; + private readonly WebSocket peerSocket; + private readonly Queue pendingPackets = new(); + private bool enable = true; + + public NebulaConnection(WebSocket peerSocket, EndPoint peerEndpoint, NetPacketProcessor packetProcessor) { - private readonly EndPoint peerEndpoint; - private readonly WebSocket peerSocket; - private readonly NetPacketProcessor packetProcessor; - private readonly Queue pendingPackets = new Queue(); - private bool enable = true; + this.peerEndpoint = peerEndpoint; + this.peerSocket = peerSocket; + this.packetProcessor = packetProcessor; + } - public bool IsAlive => peerSocket?.IsAlive ?? false; + public bool IsAlive => peerSocket?.IsAlive ?? false; - public NebulaConnection(WebSocket peerSocket, EndPoint peerEndpoint, NetPacketProcessor packetProcessor) + public void SendPacket(T packet) where T : class, new() + { + lock (pendingPackets) { - this.peerEndpoint = peerEndpoint; - this.peerSocket = peerSocket; - this.packetProcessor = packetProcessor; + var rawData = packetProcessor.Write(packet); + pendingPackets.Enqueue(rawData); + ProcessPacketQueue(); } + } - public void SendPacket(T packet) where T : class, new() + public void SendRawPacket(byte[] rawData) + { + lock (pendingPackets) { - lock (pendingPackets) - { - byte[] rawData = packetProcessor.Write(packet); - pendingPackets.Enqueue(rawData); - ProcessPacketQueue(); - } + pendingPackets.Enqueue(rawData); + ProcessPacketQueue(); } + } - public void SendRawPacket(byte[] rawData) - { - lock (pendingPackets) - { - pendingPackets.Enqueue(rawData); - ProcessPacketQueue(); - } - } + public bool Equals(INebulaConnection connection) + { + return connection != null && (connection as NebulaConnection).peerEndpoint.Equals(peerEndpoint); + } - private void ProcessPacketQueue() + private void ProcessPacketQueue() + { + if (enable && pendingPackets.Count > 0) { - if (enable && pendingPackets.Count > 0) + var packet = pendingPackets.Dequeue(); + if (peerSocket.ReadyState == WebSocketState.Open) { - byte[] packet = pendingPackets.Dequeue(); - if (peerSocket.ReadyState == WebSocketState.Open) - { - peerSocket.SendAsync(packet, OnSendCompleted); - enable = false; - } - else - { - Log.Warn($"Cannot send packet to a {peerSocket.ReadyState} connection {peerEndpoint.GetHashCode()}"); - } + peerSocket.SendAsync(packet, OnSendCompleted); + enable = false; + } + else + { + Log.Warn($"Cannot send packet to a {peerSocket.ReadyState} connection {peerEndpoint.GetHashCode()}"); } } + } - private void OnSendCompleted(bool result) + private void OnSendCompleted(bool result) + { + lock (pendingPackets) { - lock (pendingPackets) - { - enable = true; - ProcessPacketQueue(); - } + enable = true; + ProcessPacketQueue(); } + } - public void Disconnect(DisconnectionReason reason = DisconnectionReason.Normal, string reasonString = null) + public void Disconnect(DisconnectionReason reason = DisconnectionReason.Normal, string reasonString = null) + { + if (string.IsNullOrEmpty(reasonString)) { - if (string.IsNullOrEmpty(reasonString)) + peerSocket.Close((ushort)reason); + } + else + { + if (Encoding.UTF8.GetBytes(reasonString).Length <= 123) { - peerSocket.Close((ushort)reason); + peerSocket.Close((ushort)reason, reasonString); } else { - if (System.Text.Encoding.UTF8.GetBytes(reasonString).Length <= 123) - { - peerSocket.Close((ushort)reason, reasonString); - } - else - { - throw new ArgumentException("Reason string cannot take up more than 123 bytes"); - } + throw new ArgumentException("Reason string cannot take up more than 123 bytes"); } } + } - public static bool operator ==(NebulaConnection left, NebulaConnection right) - { - return Equals(left, right); - } + public static bool operator ==(NebulaConnection left, NebulaConnection right) + { + return Equals(left, right); + } - public static bool operator !=(NebulaConnection left, NebulaConnection right) - { - return !Equals(left, right); - } + public static bool operator !=(NebulaConnection left, NebulaConnection right) + { + return !Equals(left, right); + } - public bool Equals(INebulaConnection connection) + public override bool Equals(object obj) + { + if (obj is null) { - return connection != null && (connection as NebulaConnection).peerEndpoint.Equals(peerEndpoint); + return false; } - - public override bool Equals(object obj) + if (ReferenceEquals(this, obj)) { - if (obj is null) - { - return false; - } - if (ReferenceEquals(this, obj)) - { - return true; - } - if (obj.GetType() != GetType()) - { - return false; - } - return (obj as NebulaConnection).peerEndpoint.Equals(peerEndpoint); + return true; } - - public override int GetHashCode() + if (obj.GetType() != GetType()) { - return peerEndpoint?.GetHashCode() ?? 0; + return false; } + return (obj as NebulaConnection).peerEndpoint.Equals(peerEndpoint); + } + + public override int GetHashCode() + { + return peerEndpoint?.GetHashCode() ?? 0; } } diff --git a/NebulaModel/Networking/PacketUtils.cs b/NebulaModel/Networking/PacketUtils.cs index 8e1b0d1be..526d6a82b 100644 --- a/NebulaModel/Networking/PacketUtils.cs +++ b/NebulaModel/Networking/PacketUtils.cs @@ -1,117 +1,126 @@ +#region + +using System; +using System.Linq; +using System.Reflection; using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking.Serialization; using NebulaModel.Utils; -using System; -using System.Linq; -using System.Reflection; -namespace NebulaModel.Networking +#endregion + +namespace NebulaModel.Networking; + +public static class PacketUtils { - public static class PacketUtils + public static void RegisterAllPacketNestedTypesInAssembly(Assembly assembly, NetPacketProcessor packetProcessor) { - - public static void RegisterAllPacketNestedTypesInAssembly(Assembly assembly, NetPacketProcessor packetProcessor) + var nestedTypes = AssembliesUtils.GetTypesWithAttributeInAssembly(assembly); + var isAPIAssemblies = NebulaModAPI.TargetAssemblies.Contains(assembly); + foreach (var type in nestedTypes) { - System.Collections.Generic.IEnumerable nestedTypes = AssembliesUtils.GetTypesWithAttributeInAssembly(assembly); - bool isAPIAssemblies = NebulaModAPI.TargetAssemblies.Contains(assembly); - foreach (Type type in nestedTypes) + if (isAPIAssemblies) { - if (isAPIAssemblies) - { - Log.Info($"Registering Nested Type: {type.Name}"); - } - else - { - Log.Debug($"Registering Nested Type: {type.Name}"); - } - if (type.IsClass) - { - MethodInfo registerMethod = packetProcessor.GetType().GetMethods() - .Where(m => m.Name == nameof(NetPacketProcessor.RegisterNestedType)) - .FirstOrDefault(m => m.GetParameters().Length == 1 && m.GetParameters()[0].ParameterType.Name.Equals(typeof(Func<>).Name)) - .MakeGenericMethod(type); + Log.Info($"Registering Nested Type: {type.Name}"); + } + else + { + Log.Debug($"Registering Nested Type: {type.Name}"); + } + if (type.IsClass) + { + var registerMethod = packetProcessor.GetType().GetMethods() + .Where(m => m.Name == nameof(NetPacketProcessor.RegisterNestedType)) + .FirstOrDefault(m => + m.GetParameters().Length == 1 && m.GetParameters()[0].ParameterType.Name.Equals(typeof(Func<>).Name)) + .MakeGenericMethod(type); - MethodInfo delegateMethod = packetProcessor.GetType().GetMethod(nameof(NetPacketProcessor.CreateNestedClassInstance)).MakeGenericMethod(type); - Type funcType = typeof(Func<>).MakeGenericType(type); - Delegate callback = Delegate.CreateDelegate(funcType, packetProcessor, delegateMethod); - registerMethod.Invoke(packetProcessor, new object[] { callback }); - } - else if (type.IsValueType) - { - MethodInfo method = typeof(NetPacketProcessor).GetMethod(nameof(NetPacketProcessor.RegisterNestedType), Type.EmptyTypes); - MethodInfo generic = method.MakeGenericMethod(type); - generic.Invoke(packetProcessor, null); - } - else - { - Log.Error($"Could not register nested type: {type.Name}. Must be a class or struct."); - } + var delegateMethod = packetProcessor.GetType().GetMethod(nameof(NetPacketProcessor.CreateNestedClassInstance)) + .MakeGenericMethod(type); + var funcType = typeof(Func<>).MakeGenericType(type); + var callback = Delegate.CreateDelegate(funcType, packetProcessor, delegateMethod); + registerMethod.Invoke(packetProcessor, new object[] { callback }); + } + else if (type.IsValueType) + { + var method = typeof(NetPacketProcessor).GetMethod(nameof(NetPacketProcessor.RegisterNestedType), + Type.EmptyTypes); + var generic = method.MakeGenericMethod(type); + generic.Invoke(packetProcessor, null); + } + else + { + Log.Error($"Could not register nested type: {type.Name}. Must be a class or struct."); } } + } - private static bool IsSubclassOfRawGeneric(Type generic, Type toCheck) + private static bool IsSubclassOfRawGeneric(Type generic, Type toCheck) + { + while (toCheck != null && toCheck != typeof(object)) { - while (toCheck != null && toCheck != typeof(object)) + var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck; + if (generic == cur) { - Type cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck; - if (generic == cur) - { - return true; - } - toCheck = toCheck.BaseType; + return true; } - return false; + toCheck = toCheck.BaseType; } + return false; + } - public static void RegisterAllPacketProcessorsInAssembly(Assembly assembly, NetPacketProcessor packetProcessor, bool isMasterClient) - { - System.Collections.Generic.IEnumerable processors = assembly.GetTypes() - .Where(t => t.GetCustomAttributes(typeof(RegisterPacketProcessorAttribute), true).Length > 0); + public static void RegisterAllPacketProcessorsInAssembly(Assembly assembly, NetPacketProcessor packetProcessor, + bool isMasterClient) + { + var processors = assembly.GetTypes() + .Where(t => t.GetCustomAttributes(typeof(RegisterPacketProcessorAttribute), true).Length > 0); - MethodInfo method = packetProcessor.GetType().GetMethods() - .Where(m => m.Name == nameof(NetPacketProcessor.SubscribeReusable)) - .Where(m => m.IsGenericMethod && m.GetGenericArguments().Length == 2) - .FirstOrDefault(); + var method = packetProcessor.GetType().GetMethods() + .Where(m => m.Name == nameof(NetPacketProcessor.SubscribeReusable)) + .Where(m => m.IsGenericMethod && m.GetGenericArguments().Length == 2) + .FirstOrDefault(); - bool isAPIAssemblies = NebulaModAPI.TargetAssemblies.Contains(assembly); - foreach (Type type in processors) + var isAPIAssemblies = NebulaModAPI.TargetAssemblies.Contains(assembly); + foreach (var type in processors) + { + if (IsSubclassOfRawGeneric(typeof(BasePacketProcessor<>), type)) { - if (IsSubclassOfRawGeneric(typeof(BasePacketProcessor<>), type)) + var packetType = type.BaseType.GetGenericArguments().FirstOrDefault(); + if (isAPIAssemblies) { - Type packetType = type.BaseType.GetGenericArguments().FirstOrDefault(); - if (isAPIAssemblies) - { - Log.Info($"Registering {type.Name} to process packet of type: {packetType.Name}"); - } - else - { - Log.Debug($"Registering {type.Name} to process packet of type: {packetType.Name}"); - } - - // Create instance of the processor - Type delegateType = typeof(Action<,>).MakeGenericType(packetType, typeof(INebulaConnection)); - object processor = Activator.CreateInstance(type); - Delegate callback = Delegate.CreateDelegate(delegateType, processor, type.GetMethod(nameof(BasePacketProcessor.ProcessPacket), new Type[] { packetType, typeof(INebulaConnection) })); - - // Initialize processor - type.BaseType.GetMethod("Initialize", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(processor, new object[] { isMasterClient }); - - // Register our processor callback to the PacketProcessor - Type subscribeGenericType = typeof(Action<,>).MakeGenericType(packetType, typeof(INebulaConnection)); - MethodInfo generic = method.MakeGenericMethod(packetType, typeof(INebulaConnection)); - generic.Invoke(packetProcessor, new object[] { callback }); + Log.Info($"Registering {type.Name} to process packet of type: {packetType.Name}"); } else { - Log.Warn($"{type.FullName} registered, but doesn't implement {typeof(BasePacketProcessor<>).FullName}"); + Log.Debug($"Registering {type.Name} to process packet of type: {packetType.Name}"); } + + // Create instance of the processor + var delegateType = typeof(Action<,>).MakeGenericType(packetType, typeof(INebulaConnection)); + var processor = Activator.CreateInstance(type); + var callback = Delegate.CreateDelegate(delegateType, processor, + type.GetMethod(nameof(BasePacketProcessor.ProcessPacket), + new[] { packetType, typeof(INebulaConnection) })); + + // Initialize processor + type.BaseType.GetMethod("Initialize", BindingFlags.NonPublic | BindingFlags.Instance) + .Invoke(processor, new object[] { isMasterClient }); + + // Register our processor callback to the PacketProcessor + var subscribeGenericType = typeof(Action<,>).MakeGenericType(packetType, typeof(INebulaConnection)); + var generic = method.MakeGenericMethod(packetType, typeof(INebulaConnection)); + generic.Invoke(packetProcessor, new object[] { callback }); + } + else + { + Log.Warn($"{type.FullName} registered, but doesn't implement {typeof(BasePacketProcessor<>).FullName}"); } } + } - public static void RegisterAllPacketProcessorsInCallingAssembly(NetPacketProcessor packetProcessor, bool isMasterClient) - { - RegisterAllPacketProcessorsInAssembly(Assembly.GetCallingAssembly(), packetProcessor, isMasterClient); - } + public static void RegisterAllPacketProcessorsInCallingAssembly(NetPacketProcessor packetProcessor, bool isMasterClient) + { + RegisterAllPacketProcessorsInAssembly(Assembly.GetCallingAssembly(), packetProcessor, isMasterClient); } } diff --git a/NebulaModel/Networking/PendingPacket.cs b/NebulaModel/Networking/PendingPacket.cs index b52a69604..67404d3ee 100644 --- a/NebulaModel/Networking/PendingPacket.cs +++ b/NebulaModel/Networking/PendingPacket.cs @@ -1,14 +1,13 @@ -namespace NebulaModel.Networking +namespace NebulaModel.Networking; + +public struct PendingPacket { - public struct PendingPacket - { - public byte[] Data { get; } - public object UserData { get; } + public byte[] Data { get; } + public object UserData { get; } - public PendingPacket(byte[] data, object userData) - { - Data = data; - UserData = userData; - } + public PendingPacket(byte[] data, object userData) + { + Data = data; + UserData = userData; } } diff --git a/NebulaModel/Networking/Serialization/FastBitConverter.cs b/NebulaModel/Networking/Serialization/FastBitConverter.cs index d081090c5..732d122b0 100644 --- a/NebulaModel/Networking/Serialization/FastBitConverter.cs +++ b/NebulaModel/Networking/Serialization/FastBitConverter.cs @@ -1,31 +1,15 @@ -using System.Runtime.InteropServices; +#region -namespace NebulaModel.Networking.Serialization +using System.Runtime.InteropServices; + +#endregion + +namespace NebulaModel.Networking.Serialization; + +public static class FastBitConverter { - public static class FastBitConverter + private static void WriteLittleEndian(byte[] buffer, int offset, ulong data) { - [StructLayout(LayoutKind.Explicit)] - private struct ConverterHelperDouble - { - [FieldOffset(0)] - public ulong Along; - - [FieldOffset(0)] - public double Adouble; - } - - [StructLayout(LayoutKind.Explicit)] - private struct ConverterHelperFloat - { - [FieldOffset(0)] - public int Aint; - - [FieldOffset(0)] - public float Afloat; - } - - private static void WriteLittleEndian(byte[] buffer, int offset, ulong data) - { #if BIGENDIAN buffer[offset + 7] = (byte)(data); buffer[offset + 6] = (byte)(data >> 8); @@ -36,83 +20,98 @@ private static void WriteLittleEndian(byte[] buffer, int offset, ulong data) buffer[offset + 1] = (byte)(data >> 48); buffer[offset ] = (byte)(data >> 56); #else - buffer[offset] = (byte)(data); - buffer[offset + 1] = (byte)(data >> 8); - buffer[offset + 2] = (byte)(data >> 16); - buffer[offset + 3] = (byte)(data >> 24); - buffer[offset + 4] = (byte)(data >> 32); - buffer[offset + 5] = (byte)(data >> 40); - buffer[offset + 6] = (byte)(data >> 48); - buffer[offset + 7] = (byte)(data >> 56); + buffer[offset] = (byte)data; + buffer[offset + 1] = (byte)(data >> 8); + buffer[offset + 2] = (byte)(data >> 16); + buffer[offset + 3] = (byte)(data >> 24); + buffer[offset + 4] = (byte)(data >> 32); + buffer[offset + 5] = (byte)(data >> 40); + buffer[offset + 6] = (byte)(data >> 48); + buffer[offset + 7] = (byte)(data >> 56); #endif - } + } - private static void WriteLittleEndian(byte[] buffer, int offset, int data) - { + private static void WriteLittleEndian(byte[] buffer, int offset, int data) + { #if BIGENDIAN buffer[offset + 3] = (byte)(data); buffer[offset + 2] = (byte)(data >> 8); buffer[offset + 1] = (byte)(data >> 16); buffer[offset ] = (byte)(data >> 24); #else - buffer[offset] = (byte)(data); - buffer[offset + 1] = (byte)(data >> 8); - buffer[offset + 2] = (byte)(data >> 16); - buffer[offset + 3] = (byte)(data >> 24); + buffer[offset] = (byte)data; + buffer[offset + 1] = (byte)(data >> 8); + buffer[offset + 2] = (byte)(data >> 16); + buffer[offset + 3] = (byte)(data >> 24); #endif - } + } - public static void WriteLittleEndian(byte[] buffer, int offset, short data) - { + public static void WriteLittleEndian(byte[] buffer, int offset, short data) + { #if BIGENDIAN buffer[offset + 1] = (byte)(data); buffer[offset ] = (byte)(data >> 8); #else - buffer[offset] = (byte)(data); - buffer[offset + 1] = (byte)(data >> 8); + buffer[offset] = (byte)data; + buffer[offset + 1] = (byte)(data >> 8); #endif - } - - public static void GetBytes(byte[] bytes, int startIndex, double value) - { - ConverterHelperDouble ch = new ConverterHelperDouble { Adouble = value }; - WriteLittleEndian(bytes, startIndex, ch.Along); - } - - public static void GetBytes(byte[] bytes, int startIndex, float value) - { - ConverterHelperFloat ch = new ConverterHelperFloat { Afloat = value }; - WriteLittleEndian(bytes, startIndex, ch.Aint); - } - - public static void GetBytes(byte[] bytes, int startIndex, short value) - { - WriteLittleEndian(bytes, startIndex, value); - } - - public static void GetBytes(byte[] bytes, int startIndex, ushort value) - { - WriteLittleEndian(bytes, startIndex, (short)value); - } - - public static void GetBytes(byte[] bytes, int startIndex, int value) - { - WriteLittleEndian(bytes, startIndex, value); - } - - public static void GetBytes(byte[] bytes, int startIndex, uint value) - { - WriteLittleEndian(bytes, startIndex, (int)value); - } - - public static void GetBytes(byte[] bytes, int startIndex, long value) - { - WriteLittleEndian(bytes, startIndex, (ulong)value); - } - - public static void GetBytes(byte[] bytes, int startIndex, ulong value) - { - WriteLittleEndian(bytes, startIndex, value); - } + } + + public static void GetBytes(byte[] bytes, int startIndex, double value) + { + var ch = new ConverterHelperDouble { Adouble = value }; + WriteLittleEndian(bytes, startIndex, ch.Along); + } + + public static void GetBytes(byte[] bytes, int startIndex, float value) + { + var ch = new ConverterHelperFloat { Afloat = value }; + WriteLittleEndian(bytes, startIndex, ch.Aint); + } + + public static void GetBytes(byte[] bytes, int startIndex, short value) + { + WriteLittleEndian(bytes, startIndex, value); + } + + public static void GetBytes(byte[] bytes, int startIndex, ushort value) + { + WriteLittleEndian(bytes, startIndex, (short)value); + } + + public static void GetBytes(byte[] bytes, int startIndex, int value) + { + WriteLittleEndian(bytes, startIndex, value); + } + + public static void GetBytes(byte[] bytes, int startIndex, uint value) + { + WriteLittleEndian(bytes, startIndex, (int)value); + } + + public static void GetBytes(byte[] bytes, int startIndex, long value) + { + WriteLittleEndian(bytes, startIndex, (ulong)value); + } + + public static void GetBytes(byte[] bytes, int startIndex, ulong value) + { + WriteLittleEndian(bytes, startIndex, value); + } + + [StructLayout(LayoutKind.Explicit)] + private struct ConverterHelperDouble + { + [FieldOffset(0)] public ulong Along; + + [FieldOffset(0)] public double Adouble; + } + + [StructLayout(LayoutKind.Explicit)] + private struct ConverterHelperFloat + { + [FieldOffset(0)] public int Aint; + + [FieldOffset(0)] public float Afloat; } } diff --git a/NebulaModel/Networking/Serialization/NetDataReader.cs b/NebulaModel/Networking/Serialization/NetDataReader.cs index 35ee6bbd2..a306da005 100644 --- a/NebulaModel/Networking/Serialization/NetDataReader.cs +++ b/NebulaModel/Networking/Serialization/NetDataReader.cs @@ -1,670 +1,675 @@ -using NebulaAPI; +#region + using System; using System.Net; using System.Text; +using NebulaAPI; + +#endregion + +namespace NebulaModel.Networking.Serialization; -namespace NebulaModel.Networking.Serialization +public class NetDataReader : INetDataReader { - public class NetDataReader : INetDataReader + protected byte[] _data; + protected int _dataSize; + protected int _position; + + public NetDataReader() { - protected byte[] _data; - protected int _position; - protected int _dataSize; - private int _offset; + } - public byte[] RawData => _data; + public NetDataReader(NetDataWriter writer) + { + SetSource(writer); + } - public int RawDataSize => _dataSize; + public NetDataReader(byte[] source) + { + SetSource(source); + } - public int UserDataOffset => _offset; + public NetDataReader(byte[] source, int offset) + { + SetSource(source, offset); + } - public int UserDataSize => _dataSize - _offset; + public NetDataReader(byte[] source, int offset, int maxSize) + { + SetSource(source, offset, maxSize); + } - public bool IsNull => _data == null; + public byte[] RawData => _data; - public int Position => _position; + public int RawDataSize => _dataSize; - public bool EndOfData => _position == _dataSize; + public int UserDataOffset { get; private set; } - public int AvailableBytes => _dataSize - _position; + public int UserDataSize => _dataSize - UserDataOffset; - public void SkipBytes(int count) - { - _position += count; - } + public bool IsNull => _data == null; - public void SetSource(NetDataWriter dataWriter) - { - _data = dataWriter.Data; - _position = 0; - _offset = 0; - _dataSize = dataWriter.Length; - } + public int Position => _position; - public void SetSource(byte[] source) - { - _data = source; - _position = 0; - _offset = 0; - _dataSize = source.Length; - } + public bool EndOfData => _position == _dataSize; - public void SetSource(byte[] source, int offset) - { - _data = source; - _position = offset; - _offset = offset; - _dataSize = source.Length; - } + public int AvailableBytes => _dataSize - _position; - public void SetSource(byte[] source, int offset, int maxSize) - { - _data = source; - _position = offset; - _offset = offset; - _dataSize = maxSize; - } + public void SkipBytes(int count) + { + _position += count; + } - public NetDataReader() - { + public void SetSource(NetDataWriter dataWriter) + { + _data = dataWriter.Data; + _position = 0; + UserDataOffset = 0; + _dataSize = dataWriter.Length; + } - } + public void SetSource(byte[] source) + { + _data = source; + _position = 0; + UserDataOffset = 0; + _dataSize = source.Length; + } - public NetDataReader(NetDataWriter writer) - { - SetSource(writer); - } + public void SetSource(byte[] source, int offset) + { + _data = source; + _position = offset; + UserDataOffset = offset; + _dataSize = source.Length; + } - public NetDataReader(byte[] source) - { - SetSource(source); - } + public void SetSource(byte[] source, int offset, int maxSize) + { + _data = source; + _position = offset; + UserDataOffset = offset; + _dataSize = maxSize; + } - public NetDataReader(byte[] source, int offset) - { - SetSource(source, offset); - } + public void Clear() + { + _position = 0; + _dataSize = 0; + _data = null; + } - public NetDataReader(byte[] source, int offset, int maxSize) - { - SetSource(source, offset, maxSize); - } + #region GetMethods - #region GetMethods - public IPEndPoint GetNetEndPoint() - { - string host = GetString(1000); - int port = GetInt(); - return NetUtils.MakeEndPoint(host, port); - } + public IPEndPoint GetNetEndPoint() + { + var host = GetString(1000); + var port = GetInt(); + return NetUtils.MakeEndPoint(host, port); + } - public byte GetByte() - { - byte res = _data[_position]; - _position += 1; - return res; - } + public byte GetByte() + { + var res = _data[_position]; + _position += 1; + return res; + } - public sbyte GetSByte() - { - sbyte b = (sbyte)_data[_position]; - _position++; - return b; - } + public sbyte GetSByte() + { + var b = (sbyte)_data[_position]; + _position++; + return b; + } - public bool[] GetBoolArray() - { - ushort size = BitConverter.ToUInt16(_data, _position); - _position += 2; - bool[] arr = new bool[size]; - Buffer.BlockCopy(_data, _position, arr, 0, size); - _position += size; - return arr; - } + public bool[] GetBoolArray() + { + var size = BitConverter.ToUInt16(_data, _position); + _position += 2; + var arr = new bool[size]; + Buffer.BlockCopy(_data, _position, arr, 0, size); + _position += size; + return arr; + } - public ushort[] GetUShortArray() - { - ushort size = BitConverter.ToUInt16(_data, _position); - _position += 2; - ushort[] arr = new ushort[size]; - Buffer.BlockCopy(_data, _position, arr, 0, size * 2); - _position += size * 2; - return arr; - } + public ushort[] GetUShortArray() + { + var size = BitConverter.ToUInt16(_data, _position); + _position += 2; + var arr = new ushort[size]; + Buffer.BlockCopy(_data, _position, arr, 0, size * 2); + _position += size * 2; + return arr; + } - public short[] GetShortArray() - { - ushort size = BitConverter.ToUInt16(_data, _position); - _position += 2; - short[] arr = new short[size]; - Buffer.BlockCopy(_data, _position, arr, 0, size * 2); - _position += size * 2; - return arr; - } + public short[] GetShortArray() + { + var size = BitConverter.ToUInt16(_data, _position); + _position += 2; + var arr = new short[size]; + Buffer.BlockCopy(_data, _position, arr, 0, size * 2); + _position += size * 2; + return arr; + } - public long[] GetLongArray() - { - ushort size = BitConverter.ToUInt16(_data, _position); - _position += 2; - long[] arr = new long[size]; - Buffer.BlockCopy(_data, _position, arr, 0, size * 8); - _position += size * 8; - return arr; - } + public long[] GetLongArray() + { + var size = BitConverter.ToUInt16(_data, _position); + _position += 2; + var arr = new long[size]; + Buffer.BlockCopy(_data, _position, arr, 0, size * 8); + _position += size * 8; + return arr; + } - public ulong[] GetULongArray() - { - ushort size = BitConverter.ToUInt16(_data, _position); - _position += 2; - ulong[] arr = new ulong[size]; - Buffer.BlockCopy(_data, _position, arr, 0, size * 8); - _position += size * 8; - return arr; - } + public ulong[] GetULongArray() + { + var size = BitConverter.ToUInt16(_data, _position); + _position += 2; + var arr = new ulong[size]; + Buffer.BlockCopy(_data, _position, arr, 0, size * 8); + _position += size * 8; + return arr; + } - public int[] GetIntArray() - { - ushort size = BitConverter.ToUInt16(_data, _position); - _position += 2; - int[] arr = new int[size]; - Buffer.BlockCopy(_data, _position, arr, 0, size * 4); - _position += size * 4; - return arr; - } + public int[] GetIntArray() + { + var size = BitConverter.ToUInt16(_data, _position); + _position += 2; + var arr = new int[size]; + Buffer.BlockCopy(_data, _position, arr, 0, size * 4); + _position += size * 4; + return arr; + } - public uint[] GetUIntArray() - { - ushort size = BitConverter.ToUInt16(_data, _position); - _position += 2; - uint[] arr = new uint[size]; - Buffer.BlockCopy(_data, _position, arr, 0, size * 4); - _position += size * 4; - return arr; - } + public uint[] GetUIntArray() + { + var size = BitConverter.ToUInt16(_data, _position); + _position += 2; + var arr = new uint[size]; + Buffer.BlockCopy(_data, _position, arr, 0, size * 4); + _position += size * 4; + return arr; + } - public float[] GetFloatArray() - { - ushort size = BitConverter.ToUInt16(_data, _position); - _position += 2; - float[] arr = new float[size]; - Buffer.BlockCopy(_data, _position, arr, 0, size * 4); - _position += size * 4; - return arr; - } + public float[] GetFloatArray() + { + var size = BitConverter.ToUInt16(_data, _position); + _position += 2; + var arr = new float[size]; + Buffer.BlockCopy(_data, _position, arr, 0, size * 4); + _position += size * 4; + return arr; + } - public double[] GetDoubleArray() - { - ushort size = BitConverter.ToUInt16(_data, _position); - _position += 2; - double[] arr = new double[size]; - Buffer.BlockCopy(_data, _position, arr, 0, size * 8); - _position += size * 8; - return arr; - } + public double[] GetDoubleArray() + { + var size = BitConverter.ToUInt16(_data, _position); + _position += 2; + var arr = new double[size]; + Buffer.BlockCopy(_data, _position, arr, 0, size * 8); + _position += size * 8; + return arr; + } - public string[] GetStringArray() + public string[] GetStringArray() + { + var size = BitConverter.ToUInt16(_data, _position); + _position += 2; + var arr = new string[size]; + for (var i = 0; i < size; i++) { - ushort size = BitConverter.ToUInt16(_data, _position); - _position += 2; - string[] arr = new string[size]; - for (int i = 0; i < size; i++) - { - arr[i] = GetString(); - } - return arr; + arr[i] = GetString(); } + return arr; + } - public string[] GetStringArray(int maxStringLength) + public string[] GetStringArray(int maxStringLength) + { + var size = BitConverter.ToUInt16(_data, _position); + _position += 2; + var arr = new string[size]; + for (var i = 0; i < size; i++) { - ushort size = BitConverter.ToUInt16(_data, _position); - _position += 2; - string[] arr = new string[size]; - for (int i = 0; i < size; i++) - { - arr[i] = GetString(maxStringLength); - } - return arr; + arr[i] = GetString(maxStringLength); } + return arr; + } - public bool GetBool() - { - bool res = _data[_position] > 0; - _position += 1; - return res; - } + public bool GetBool() + { + var res = _data[_position] > 0; + _position += 1; + return res; + } - public char GetChar() - { - char result = BitConverter.ToChar(_data, _position); - _position += 2; - return result; - } + public char GetChar() + { + var result = BitConverter.ToChar(_data, _position); + _position += 2; + return result; + } - public ushort GetUShort() - { - ushort result = BitConverter.ToUInt16(_data, _position); - _position += 2; - return result; - } + public ushort GetUShort() + { + var result = BitConverter.ToUInt16(_data, _position); + _position += 2; + return result; + } - public short GetShort() - { - short result = BitConverter.ToInt16(_data, _position); - _position += 2; - return result; - } + public short GetShort() + { + var result = BitConverter.ToInt16(_data, _position); + _position += 2; + return result; + } - public long GetLong() - { - long result = BitConverter.ToInt64(_data, _position); - _position += 8; - return result; - } + public long GetLong() + { + var result = BitConverter.ToInt64(_data, _position); + _position += 8; + return result; + } - public ulong GetULong() - { - ulong result = BitConverter.ToUInt64(_data, _position); - _position += 8; - return result; - } + public ulong GetULong() + { + var result = BitConverter.ToUInt64(_data, _position); + _position += 8; + return result; + } - public int GetInt() - { - int result = BitConverter.ToInt32(_data, _position); - _position += 4; - return result; - } + public int GetInt() + { + var result = BitConverter.ToInt32(_data, _position); + _position += 4; + return result; + } + + public uint GetUInt() + { + var result = BitConverter.ToUInt32(_data, _position); + _position += 4; + return result; + } - public uint GetUInt() + public float GetFloat() + { + var result = BitConverter.ToSingle(_data, _position); + _position += 4; + return result; + } + + public double GetDouble() + { + var result = BitConverter.ToDouble(_data, _position); + _position += 8; + return result; + } + + public string GetString(int maxLength) + { + var bytesCount = GetInt(); + if (bytesCount <= 0 || bytesCount > maxLength * 2) { - uint result = BitConverter.ToUInt32(_data, _position); - _position += 4; - return result; + return string.Empty; } - public float GetFloat() + var charCount = Encoding.UTF8.GetCharCount(_data, _position, bytesCount); + if (charCount > maxLength) { - float result = BitConverter.ToSingle(_data, _position); - _position += 4; - return result; + return string.Empty; } - public double GetDouble() + var result = Encoding.UTF8.GetString(_data, _position, bytesCount); + _position += bytesCount; + return result; + } + + public string GetString() + { + var bytesCount = GetInt(); + if (bytesCount <= 0) { - double result = BitConverter.ToDouble(_data, _position); - _position += 8; - return result; + return string.Empty; } - public string GetString(int maxLength) - { - int bytesCount = GetInt(); - if (bytesCount <= 0 || bytesCount > maxLength * 2) - { - return string.Empty; - } + var result = Encoding.UTF8.GetString(_data, _position, bytesCount); + _position += bytesCount; + return result; + } - int charCount = Encoding.UTF8.GetCharCount(_data, _position, bytesCount); - if (charCount > maxLength) - { - return string.Empty; - } + public ArraySegment GetRemainingBytesSegment() + { + var segment = new ArraySegment(_data, _position, AvailableBytes); + _position = _data.Length; + return segment; + } - string result = Encoding.UTF8.GetString(_data, _position, bytesCount); - _position += bytesCount; - return result; - } + public T Get() where T : INetSerializable, new() + { + var obj = new T(); + obj.Deserialize(this); + return obj; + } - public string GetString() - { - int bytesCount = GetInt(); - if (bytesCount <= 0) - { - return string.Empty; - } + public byte[] GetRemainingBytes() + { + var outgoingData = new byte[AvailableBytes]; + Buffer.BlockCopy(_data, _position, outgoingData, 0, AvailableBytes); + _position = _data.Length; + return outgoingData; + } - string result = Encoding.UTF8.GetString(_data, _position, bytesCount); - _position += bytesCount; - return result; - } + public void GetBytes(byte[] destination, int start, int count) + { + Buffer.BlockCopy(_data, _position, destination, start, count); + _position += count; + } - public ArraySegment GetRemainingBytesSegment() - { - ArraySegment segment = new ArraySegment(_data, _position, AvailableBytes); - _position = _data.Length; - return segment; - } + public void GetBytes(byte[] destination, int count) + { + Buffer.BlockCopy(_data, _position, destination, 0, count); + _position += count; + } - public T Get() where T : INetSerializable, new() - { - T obj = new T(); - obj.Deserialize(this); - return obj; - } + public sbyte[] GetSBytesWithLength() + { + var length = GetInt(); + var outgoingData = new sbyte[length]; + Buffer.BlockCopy(_data, _position, outgoingData, 0, length); + _position += length; + return outgoingData; + } - public byte[] GetRemainingBytes() - { - byte[] outgoingData = new byte[AvailableBytes]; - Buffer.BlockCopy(_data, _position, outgoingData, 0, AvailableBytes); - _position = _data.Length; - return outgoingData; - } + public byte[] GetBytesWithLength() + { + var length = GetInt(); + var outgoingData = new byte[length]; + Buffer.BlockCopy(_data, _position, outgoingData, 0, length); + _position += length; + return outgoingData; + } - public void GetBytes(byte[] destination, int start, int count) - { - Buffer.BlockCopy(_data, _position, destination, start, count); - _position += count; - } + #endregion - public void GetBytes(byte[] destination, int count) - { - Buffer.BlockCopy(_data, _position, destination, 0, count); - _position += count; - } + #region PeekMethods - public sbyte[] GetSBytesWithLength() - { - int length = GetInt(); - sbyte[] outgoingData = new sbyte[length]; - Buffer.BlockCopy(_data, _position, outgoingData, 0, length); - _position += length; - return outgoingData; - } + public byte PeekByte() + { + return _data[_position]; + } - public byte[] GetBytesWithLength() - { - int length = GetInt(); - byte[] outgoingData = new byte[length]; - Buffer.BlockCopy(_data, _position, outgoingData, 0, length); - _position += length; - return outgoingData; - } - #endregion + public sbyte PeekSByte() + { + return (sbyte)_data[_position]; + } - #region PeekMethods + public bool PeekBool() + { + return _data[_position] > 0; + } - public byte PeekByte() - { - return _data[_position]; - } + public char PeekChar() + { + return BitConverter.ToChar(_data, _position); + } - public sbyte PeekSByte() - { - return (sbyte)_data[_position]; - } + public ushort PeekUShort() + { + return BitConverter.ToUInt16(_data, _position); + } - public bool PeekBool() - { - return _data[_position] > 0; - } + public short PeekShort() + { + return BitConverter.ToInt16(_data, _position); + } - public char PeekChar() - { - return BitConverter.ToChar(_data, _position); - } + public long PeekLong() + { + return BitConverter.ToInt64(_data, _position); + } - public ushort PeekUShort() - { - return BitConverter.ToUInt16(_data, _position); - } + public ulong PeekULong() + { + return BitConverter.ToUInt64(_data, _position); + } - public short PeekShort() - { - return BitConverter.ToInt16(_data, _position); - } + public int PeekInt() + { + return BitConverter.ToInt32(_data, _position); + } - public long PeekLong() - { - return BitConverter.ToInt64(_data, _position); - } + public uint PeekUInt() + { + return BitConverter.ToUInt32(_data, _position); + } - public ulong PeekULong() - { - return BitConverter.ToUInt64(_data, _position); - } + public float PeekFloat() + { + return BitConverter.ToSingle(_data, _position); + } - public int PeekInt() - { - return BitConverter.ToInt32(_data, _position); - } + public double PeekDouble() + { + return BitConverter.ToDouble(_data, _position); + } - public uint PeekUInt() + public string PeekString(int maxLength) + { + var bytesCount = BitConverter.ToInt32(_data, _position); + if (bytesCount <= 0 || bytesCount > maxLength * 2) { - return BitConverter.ToUInt32(_data, _position); + return string.Empty; } - public float PeekFloat() + var charCount = Encoding.UTF8.GetCharCount(_data, _position + 4, bytesCount); + if (charCount > maxLength) { - return BitConverter.ToSingle(_data, _position); + return string.Empty; } - public double PeekDouble() + var result = Encoding.UTF8.GetString(_data, _position + 4, bytesCount); + return result; + } + + public string PeekString() + { + var bytesCount = BitConverter.ToInt32(_data, _position); + if (bytesCount <= 0) { - return BitConverter.ToDouble(_data, _position); + return string.Empty; } - public string PeekString(int maxLength) - { - int bytesCount = BitConverter.ToInt32(_data, _position); - if (bytesCount <= 0 || bytesCount > maxLength * 2) - { - return string.Empty; - } + var result = Encoding.UTF8.GetString(_data, _position + 4, bytesCount); + return result; + } - int charCount = Encoding.UTF8.GetCharCount(_data, _position + 4, bytesCount); - if (charCount > maxLength) - { - return string.Empty; - } + #endregion - string result = Encoding.UTF8.GetString(_data, _position + 4, bytesCount); - return result; - } + #region TryGetMethods - public string PeekString() + public bool TryGetByte(out byte result) + { + if (AvailableBytes >= 1) { - int bytesCount = BitConverter.ToInt32(_data, _position); - if (bytesCount <= 0) - { - return string.Empty; - } - - string result = Encoding.UTF8.GetString(_data, _position + 4, bytesCount); - return result; + result = GetByte(); + return true; } - #endregion + result = 0; + return false; + } - #region TryGetMethods - public bool TryGetByte(out byte result) + public bool TryGetSByte(out sbyte result) + { + if (AvailableBytes >= 1) { - if (AvailableBytes >= 1) - { - result = GetByte(); - return true; - } - result = 0; - return false; + result = GetSByte(); + return true; } + result = 0; + return false; + } - public bool TryGetSByte(out sbyte result) + public bool TryGetBool(out bool result) + { + if (AvailableBytes >= 1) { - if (AvailableBytes >= 1) - { - result = GetSByte(); - return true; - } - result = 0; - return false; + result = GetBool(); + return true; } + result = false; + return false; + } - public bool TryGetBool(out bool result) + public bool TryGetChar(out char result) + { + if (AvailableBytes >= 2) { - if (AvailableBytes >= 1) - { - result = GetBool(); - return true; - } - result = false; - return false; + result = GetChar(); + return true; } + result = '\0'; + return false; + } - public bool TryGetChar(out char result) + public bool TryGetShort(out short result) + { + if (AvailableBytes >= 2) { - if (AvailableBytes >= 2) - { - result = GetChar(); - return true; - } - result = '\0'; - return false; + result = GetShort(); + return true; } + result = 0; + return false; + } - public bool TryGetShort(out short result) + public bool TryGetUShort(out ushort result) + { + if (AvailableBytes >= 2) { - if (AvailableBytes >= 2) - { - result = GetShort(); - return true; - } - result = 0; - return false; + result = GetUShort(); + return true; } + result = 0; + return false; + } - public bool TryGetUShort(out ushort result) + public bool TryGetInt(out int result) + { + if (AvailableBytes >= 4) { - if (AvailableBytes >= 2) - { - result = GetUShort(); - return true; - } - result = 0; - return false; + result = GetInt(); + return true; } + result = 0; + return false; + } - public bool TryGetInt(out int result) + public bool TryGetUInt(out uint result) + { + if (AvailableBytes >= 4) { - if (AvailableBytes >= 4) - { - result = GetInt(); - return true; - } - result = 0; - return false; + result = GetUInt(); + return true; } + result = 0; + return false; + } - public bool TryGetUInt(out uint result) + public bool TryGetLong(out long result) + { + if (AvailableBytes >= 8) { - if (AvailableBytes >= 4) - { - result = GetUInt(); - return true; - } - result = 0; - return false; + result = GetLong(); + return true; } + result = 0; + return false; + } - public bool TryGetLong(out long result) + public bool TryGetULong(out ulong result) + { + if (AvailableBytes >= 8) { - if (AvailableBytes >= 8) - { - result = GetLong(); - return true; - } - result = 0; - return false; + result = GetULong(); + return true; } + result = 0; + return false; + } - public bool TryGetULong(out ulong result) + public bool TryGetFloat(out float result) + { + if (AvailableBytes >= 4) { - if (AvailableBytes >= 8) - { - result = GetULong(); - return true; - } - result = 0; - return false; + result = GetFloat(); + return true; } + result = 0; + return false; + } - public bool TryGetFloat(out float result) + public bool TryGetDouble(out double result) + { + if (AvailableBytes >= 8) { - if (AvailableBytes >= 4) - { - result = GetFloat(); - return true; - } - result = 0; - return false; + result = GetDouble(); + return true; } + result = 0; + return false; + } - public bool TryGetDouble(out double result) + public bool TryGetString(out string result) + { + if (AvailableBytes >= 4) { - if (AvailableBytes >= 8) + var bytesCount = PeekInt(); + if (AvailableBytes >= bytesCount + 4) { - result = GetDouble(); + result = GetString(); return true; } - result = 0; - return false; } + result = null; + return false; + } - public bool TryGetString(out string result) + public bool TryGetStringArray(out string[] result) + { + if (!TryGetUShort(out var size)) { - if (AvailableBytes >= 4) - { - int bytesCount = PeekInt(); - if (AvailableBytes >= bytesCount + 4) - { - result = GetString(); - return true; - } - } result = null; return false; } - public bool TryGetStringArray(out string[] result) + result = new string[size]; + for (var i = 0; i < size; i++) { - if (!TryGetUShort(out ushort size)) + if (!TryGetString(out result[i])) { result = null; return false; } - - result = new string[size]; - for (int i = 0; i < size; i++) - { - if (!TryGetString(out result[i])) - { - result = null; - return false; - } - } - - return true; } - public bool TryGetBytesWithLength(out byte[] result) + return true; + } + + public bool TryGetBytesWithLength(out byte[] result) + { + if (AvailableBytes >= 4) { - if (AvailableBytes >= 4) + var length = PeekInt(); + if (length >= 0 && AvailableBytes >= length + 4) { - int length = PeekInt(); - if (length >= 0 && AvailableBytes >= length + 4) - { - result = GetBytesWithLength(); - return true; - } + result = GetBytesWithLength(); + return true; } - result = null; - return false; - } - #endregion - - public void Clear() - { - _position = 0; - _dataSize = 0; - _data = null; } + result = null; + return false; } -} + #endregion +} diff --git a/NebulaModel/Networking/Serialization/NetDataWriter.cs b/NebulaModel/Networking/Serialization/NetDataWriter.cs index cb5c86e0b..3b67b8588 100644 --- a/NebulaModel/Networking/Serialization/NetDataWriter.cs +++ b/NebulaModel/Networking/Serialization/NetDataWriter.cs @@ -1,458 +1,461 @@ -using NebulaAPI; +#region + using System; using System.Net; using System.Text; +using NebulaAPI; + +#endregion -namespace NebulaModel.Networking.Serialization +namespace NebulaModel.Networking.Serialization; + +public class NetDataWriter : INetDataWriter { - public class NetDataWriter : INetDataWriter + private const int InitialSize = 64; + private readonly bool _autoResize; + protected byte[] _data; + protected int _position; + + public NetDataWriter() : this(true, InitialSize) { - protected byte[] _data; - protected int _position; - private const int InitialSize = 64; - private readonly bool _autoResize; + } - public int Capacity => _data.Length; + public NetDataWriter(bool autoResize) : this(autoResize, InitialSize) + { + } - public NetDataWriter() : this(true, InitialSize) - { - } + public NetDataWriter(bool autoResize, int initialSize) + { + _data = new byte[initialSize]; + _autoResize = autoResize; + } - public NetDataWriter(bool autoResize) : this(autoResize, InitialSize) - { - } + public int Capacity => _data.Length; - public NetDataWriter(bool autoResize, int initialSize) - { - _data = new byte[initialSize]; - _autoResize = autoResize; - } + public byte[] Data => _data; - /// - /// Creates NetDataWriter from existing ByteArray - /// - /// Source byte array - /// Copy array to new location or use existing - public static NetDataWriter FromBytes(byte[] bytes, bool copy) - { - if (copy) - { - NetDataWriter netDataWriter = new NetDataWriter(true, bytes.Length); - netDataWriter.Put(bytes); - return netDataWriter; - } - return new NetDataWriter(true, 0) { _data = bytes, _position = bytes.Length }; - } + public int Length => _position; - /// - /// Creates NetDataWriter from existing ByteArray (always copied data) - /// - /// Source byte array - /// Offset of array - /// Length of array - public static NetDataWriter FromBytes(byte[] bytes, int offset, int length) + public void Put(float value) + { + if (_autoResize) { - NetDataWriter netDataWriter = new NetDataWriter(true, bytes.Length); - netDataWriter.Put(bytes, offset, length); - return netDataWriter; + ResizeIfNeed(_position + 4); } - public static NetDataWriter FromString(string value) - { - NetDataWriter netDataWriter = new NetDataWriter(); - netDataWriter.Put(value); - return netDataWriter; - } + FastBitConverter.GetBytes(_data, _position, value); + _position += 4; + } - public void ResizeIfNeed(int newSize) + public void Put(double value) + { + if (_autoResize) { - int len = _data.Length; - if (len < newSize) - { - while (len < newSize) - { - len *= 2; - } - - Array.Resize(ref _data, len); - } + ResizeIfNeed(_position + 8); } - public void Reset(int size) - { - ResizeIfNeed(size); - _position = 0; - } + FastBitConverter.GetBytes(_data, _position, value); + _position += 8; + } - public void Reset() + public void Put(long value) + { + if (_autoResize) { - _position = 0; + ResizeIfNeed(_position + 8); } - public byte[] CopyData() + FastBitConverter.GetBytes(_data, _position, value); + _position += 8; + } + + public void Put(ulong value) + { + if (_autoResize) { - byte[] resultData = new byte[_position]; - Buffer.BlockCopy(_data, 0, resultData, 0, _position); - return resultData; + ResizeIfNeed(_position + 8); } - public byte[] Data => _data; - - public int Length => _position; + FastBitConverter.GetBytes(_data, _position, value); + _position += 8; + } - /// - /// Sets position of NetDataWriter to rewrite previous values - /// - /// new byte position - /// previous position of data writer - public int SetPosition(int position) + public void Put(int value) + { + if (_autoResize) { - int prevPosition = _position; - _position = position; - return prevPosition; + ResizeIfNeed(_position + 4); } - public void Put(float value) - { - if (_autoResize) - { - ResizeIfNeed(_position + 4); - } - - FastBitConverter.GetBytes(_data, _position, value); - _position += 4; - } + FastBitConverter.GetBytes(_data, _position, value); + _position += 4; + } - public void Put(double value) + public void Put(uint value) + { + if (_autoResize) { - if (_autoResize) - { - ResizeIfNeed(_position + 8); - } - - FastBitConverter.GetBytes(_data, _position, value); - _position += 8; + ResizeIfNeed(_position + 4); } - public void Put(long value) - { - if (_autoResize) - { - ResizeIfNeed(_position + 8); - } - - FastBitConverter.GetBytes(_data, _position, value); - _position += 8; - } + FastBitConverter.GetBytes(_data, _position, value); + _position += 4; + } - public void Put(ulong value) + public void Put(char value) + { + if (_autoResize) { - if (_autoResize) - { - ResizeIfNeed(_position + 8); - } - - FastBitConverter.GetBytes(_data, _position, value); - _position += 8; + ResizeIfNeed(_position + 2); } - public void Put(int value) - { - if (_autoResize) - { - ResizeIfNeed(_position + 4); - } + FastBitConverter.GetBytes(_data, _position, value); + _position += 2; + } - FastBitConverter.GetBytes(_data, _position, value); - _position += 4; + public void Put(ushort value) + { + if (_autoResize) + { + ResizeIfNeed(_position + 2); } - public void Put(uint value) - { - if (_autoResize) - { - ResizeIfNeed(_position + 4); - } + FastBitConverter.GetBytes(_data, _position, value); + _position += 2; + } - FastBitConverter.GetBytes(_data, _position, value); - _position += 4; + public void Put(short value) + { + if (_autoResize) + { + ResizeIfNeed(_position + 2); } - public void Put(char value) - { - if (_autoResize) - { - ResizeIfNeed(_position + 2); - } + FastBitConverter.GetBytes(_data, _position, value); + _position += 2; + } - FastBitConverter.GetBytes(_data, _position, value); - _position += 2; + public void Put(sbyte value) + { + if (_autoResize) + { + ResizeIfNeed(_position + 1); } - public void Put(ushort value) - { - if (_autoResize) - { - ResizeIfNeed(_position + 2); - } + _data[_position] = (byte)value; + _position++; + } - FastBitConverter.GetBytes(_data, _position, value); - _position += 2; + public void Put(byte value) + { + if (_autoResize) + { + ResizeIfNeed(_position + 1); } - public void Put(short value) - { - if (_autoResize) - { - ResizeIfNeed(_position + 2); - } + _data[_position] = value; + _position++; + } - FastBitConverter.GetBytes(_data, _position, value); - _position += 2; + public void Put(byte[] data, int offset, int length) + { + if (_autoResize) + { + ResizeIfNeed(_position + length); } - public void Put(sbyte value) - { - if (_autoResize) - { - ResizeIfNeed(_position + 1); - } + Buffer.BlockCopy(data, offset, _data, _position, length); + _position += length; + } - _data[_position] = (byte)value; - _position++; + public void Put(byte[] data) + { + if (_autoResize) + { + ResizeIfNeed(_position + data.Length); } - public void Put(byte value) - { - if (_autoResize) - { - ResizeIfNeed(_position + 1); - } + Buffer.BlockCopy(data, 0, _data, _position, data.Length); + _position += data.Length; + } - _data[_position] = value; - _position++; + public void PutSBytesWithLength(sbyte[] data, int offset, int length) + { + if (_autoResize) + { + ResizeIfNeed(_position + length + 4); } - public void Put(byte[] data, int offset, int length) - { - if (_autoResize) - { - ResizeIfNeed(_position + length); - } + FastBitConverter.GetBytes(_data, _position, length); + Buffer.BlockCopy(data, offset, _data, _position + 4, length); + _position += length + 4; + } - Buffer.BlockCopy(data, offset, _data, _position, length); - _position += length; + public void PutSBytesWithLength(sbyte[] data) + { + if (_autoResize) + { + ResizeIfNeed(_position + data.Length + 4); } - public void Put(byte[] data) - { - if (_autoResize) - { - ResizeIfNeed(_position + data.Length); - } + FastBitConverter.GetBytes(_data, _position, data.Length); + Buffer.BlockCopy(data, 0, _data, _position + 4, data.Length); + _position += data.Length + 4; + } - Buffer.BlockCopy(data, 0, _data, _position, data.Length); - _position += data.Length; + public void PutBytesWithLength(byte[] data, int offset, int length) + { + if (_autoResize) + { + ResizeIfNeed(_position + length + 4); } - public void PutSBytesWithLength(sbyte[] data, int offset, int length) - { - if (_autoResize) - { - ResizeIfNeed(_position + length + 4); - } + FastBitConverter.GetBytes(_data, _position, length); + Buffer.BlockCopy(data, offset, _data, _position + 4, length); + _position += length + 4; + } - FastBitConverter.GetBytes(_data, _position, length); - Buffer.BlockCopy(data, offset, _data, _position + 4, length); - _position += length + 4; + public void PutBytesWithLength(byte[] data) + { + if (_autoResize) + { + ResizeIfNeed(_position + data.Length + 4); } - public void PutSBytesWithLength(sbyte[] data) - { - if (_autoResize) - { - ResizeIfNeed(_position + data.Length + 4); - } + FastBitConverter.GetBytes(_data, _position, data.Length); + Buffer.BlockCopy(data, 0, _data, _position + 4, data.Length); + _position += data.Length + 4; + } - FastBitConverter.GetBytes(_data, _position, data.Length); - Buffer.BlockCopy(data, 0, _data, _position + 4, data.Length); - _position += data.Length + 4; + public void Put(bool value) + { + if (_autoResize) + { + ResizeIfNeed(_position + 1); } - public void PutBytesWithLength(byte[] data, int offset, int length) - { - if (_autoResize) - { - ResizeIfNeed(_position + length + 4); - } + _data[_position] = (byte)(value ? 1 : 0); + _position++; + } - FastBitConverter.GetBytes(_data, _position, length); - Buffer.BlockCopy(data, offset, _data, _position + 4, length); - _position += length + 4; - } + public void PutArray(float[] value) + { + PutArray(value, 4); + } - public void PutBytesWithLength(byte[] data) - { - if (_autoResize) - { - ResizeIfNeed(_position + data.Length + 4); - } + public void PutArray(double[] value) + { + PutArray(value, 8); + } - FastBitConverter.GetBytes(_data, _position, data.Length); - Buffer.BlockCopy(data, 0, _data, _position + 4, data.Length); - _position += data.Length + 4; - } + public void PutArray(long[] value) + { + PutArray(value, 8); + } - public void Put(bool value) - { - if (_autoResize) - { - ResizeIfNeed(_position + 1); - } + public void PutArray(ulong[] value) + { + PutArray(value, 8); + } - _data[_position] = (byte)(value ? 1 : 0); - _position++; - } + public void PutArray(int[] value) + { + PutArray(value, 4); + } - private void PutArray(Array arr, int sz) - { - ushort length = arr == null ? (ushort)0 : (ushort)arr.Length; - sz *= length; - if (_autoResize) - { - ResizeIfNeed(_position + sz + 2); - } + public void PutArray(uint[] value) + { + PutArray(value, 4); + } - FastBitConverter.GetBytes(_data, _position, length); - if (arr != null) - { - Buffer.BlockCopy(arr, 0, _data, _position + 2, sz); - } + public void PutArray(ushort[] value) + { + PutArray(value, 2); + } - _position += sz + 2; - } + public void PutArray(short[] value) + { + PutArray(value, 2); + } - public void PutArray(float[] value) - { - PutArray(value, 4); - } + public void PutArray(bool[] value) + { + PutArray(value, 1); + } - public void PutArray(double[] value) + public void PutArray(string[] value) + { + var len = value == null ? (ushort)0 : (ushort)value.Length; + Put(len); + for (var i = 0; i < len; i++) { - PutArray(value, 8); + Put(value[i]); } + } - public void PutArray(long[] value) + public void PutArray(string[] value, int maxLength) + { + var len = value == null ? (ushort)0 : (ushort)value.Length; + Put(len); + for (var i = 0; i < len; i++) { - PutArray(value, 8); + Put(value[i], maxLength); } + } - public void PutArray(ulong[] value) - { - PutArray(value, 8); - } + public void Put(IPEndPoint endPoint) + { + Put(endPoint.Address.ToString()); + Put(endPoint.Port); + } - public void PutArray(int[] value) + public void Put(string value) + { + if (string.IsNullOrEmpty(value)) { - PutArray(value, 4); + Put(0); + return; } - public void PutArray(uint[] value) + //put bytes count + var bytesCount = Encoding.UTF8.GetByteCount(value); + if (_autoResize) { - PutArray(value, 4); + ResizeIfNeed(_position + bytesCount + 4); } - public void PutArray(ushort[] value) - { - PutArray(value, 2); - } + Put(bytesCount); - public void PutArray(short[] value) - { - PutArray(value, 2); - } + //put string + Encoding.UTF8.GetBytes(value, 0, value.Length, _data, _position); + _position += bytesCount; + } - public void PutArray(bool[] value) + public void Put(string value, int maxLength) + { + if (string.IsNullOrEmpty(value)) { - PutArray(value, 1); + Put(0); + return; } - public void PutArray(string[] value) + var length = value.Length > maxLength ? maxLength : value.Length; + //calculate max count + var bytesCount = Encoding.UTF8.GetByteCount(value); + if (_autoResize) { - ushort len = value == null ? (ushort)0 : (ushort)value.Length; - Put(len); - for (int i = 0; i < len; i++) - { - Put(value[i]); - } + ResizeIfNeed(_position + bytesCount + 4); } - public void PutArray(string[] value, int maxLength) - { - ushort len = value == null ? (ushort)0 : (ushort)value.Length; - Put(len); - for (int i = 0; i < len; i++) - { - Put(value[i], maxLength); - } - } + //put bytes count + Put(bytesCount); + + //put string + Encoding.UTF8.GetBytes(value, 0, length, _data, _position); + + _position += bytesCount; + } - public void Put(IPEndPoint endPoint) + public void Put(T obj) where T : INetSerializable + { + obj.Serialize(this); + } + + /// + /// Creates NetDataWriter from existing ByteArray + /// + /// Source byte array + /// Copy array to new location or use existing + public static NetDataWriter FromBytes(byte[] bytes, bool copy) + { + if (copy) { - Put(endPoint.Address.ToString()); - Put(endPoint.Port); + var netDataWriter = new NetDataWriter(true, bytes.Length); + netDataWriter.Put(bytes); + return netDataWriter; } + return new NetDataWriter(true, 0) { _data = bytes, _position = bytes.Length }; + } - public void Put(string value) - { - if (string.IsNullOrEmpty(value)) - { - Put(0); - return; - } + /// + /// Creates NetDataWriter from existing ByteArray (always copied data) + /// + /// Source byte array + /// Offset of array + /// Length of array + public static NetDataWriter FromBytes(byte[] bytes, int offset, int length) + { + var netDataWriter = new NetDataWriter(true, bytes.Length); + netDataWriter.Put(bytes, offset, length); + return netDataWriter; + } + + public static NetDataWriter FromString(string value) + { + var netDataWriter = new NetDataWriter(); + netDataWriter.Put(value); + return netDataWriter; + } - //put bytes count - int bytesCount = Encoding.UTF8.GetByteCount(value); - if (_autoResize) + public void ResizeIfNeed(int newSize) + { + var len = _data.Length; + if (len < newSize) + { + while (len < newSize) { - ResizeIfNeed(_position + bytesCount + 4); + len *= 2; } - Put(bytesCount); - - //put string - Encoding.UTF8.GetBytes(value, 0, value.Length, _data, _position); - _position += bytesCount; + Array.Resize(ref _data, len); } + } - public void Put(string value, int maxLength) - { - if (string.IsNullOrEmpty(value)) - { - Put(0); - return; - } + public void Reset(int size) + { + ResizeIfNeed(size); + _position = 0; + } - int length = value.Length > maxLength ? maxLength : value.Length; - //calculate max count - int bytesCount = Encoding.UTF8.GetByteCount(value); - if (_autoResize) - { - ResizeIfNeed(_position + bytesCount + 4); - } + public void Reset() + { + _position = 0; + } - //put bytes count - Put(bytesCount); + public byte[] CopyData() + { + var resultData = new byte[_position]; + Buffer.BlockCopy(_data, 0, resultData, 0, _position); + return resultData; + } - //put string - Encoding.UTF8.GetBytes(value, 0, length, _data, _position); + /// + /// Sets position of NetDataWriter to rewrite previous values + /// + /// new byte position + /// previous position of data writer + public int SetPosition(int position) + { + var prevPosition = _position; + _position = position; + return prevPosition; + } - _position += bytesCount; + private void PutArray(Array arr, int sz) + { + var length = arr == null ? (ushort)0 : (ushort)arr.Length; + sz *= length; + if (_autoResize) + { + ResizeIfNeed(_position + sz + 2); } - public void Put(T obj) where T : INetSerializable + FastBitConverter.GetBytes(_data, _position, length); + if (arr != null) { - obj.Serialize(this); + Buffer.BlockCopy(arr, 0, _data, _position + 2, sz); } + + _position += sz + 2; } } diff --git a/NebulaModel/Networking/Serialization/NetPacketProcessor.cs b/NebulaModel/Networking/Serialization/NetPacketProcessor.cs index 0c1c0aebb..483a7f100 100644 --- a/NebulaModel/Networking/Serialization/NetPacketProcessor.cs +++ b/NebulaModel/Networking/Serialization/NetPacketProcessor.cs @@ -1,433 +1,440 @@ -using NebulaAPI; +#region + using System; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using NebulaAPI; +using NebulaModel.Logger; + +#endregion + +namespace NebulaModel.Networking.Serialization; -namespace NebulaModel.Networking.Serialization +public class NetPacketProcessor { - public class NetPacketProcessor - { - private static class HashCache - { - public static bool Initialized; - public static ulong Id; - } + private readonly Dictionary _callbacks = new(); + private readonly Dictionary _callbacksDebugInfo = new(); + private readonly NetDataWriter _netDataWriter = new(); + private readonly NetSerializer _netSerializer; + private readonly List delayedPackets = new(); + private readonly Queue pendingPackets = new(); - protected delegate void SubscribeDelegate(NetDataReader reader, object userData); - private readonly NetSerializer _netSerializer; - private readonly Dictionary _callbacks = new Dictionary(); - private readonly Dictionary _callbacksDebugInfo = new Dictionary(); - private readonly NetDataWriter _netDataWriter = new NetDataWriter(); + private readonly Random simulationRandom = new(); + public int SimulatedMaxLatency = 50; + public int SimulatedMinLatency = 20; - private readonly Random simulationRandom = new Random(); - private readonly List delayedPackets = new List(); - private readonly Queue pendingPackets = new Queue(); + public bool SimulateLatency = false; - public bool SimulateLatency = false; - public int SimulatedMinLatency = 20; - public int SimulatedMaxLatency = 50; - public bool Enable { get; set; } = true; + public NetPacketProcessor() + { + _netSerializer = new NetSerializer(); + } - public NetPacketProcessor() - { - _netSerializer = new NetSerializer(); - } + public NetPacketProcessor(int maxStringLength) + { + _netSerializer = new NetSerializer(maxStringLength); + } - public NetPacketProcessor(int maxStringLength) - { - _netSerializer = new NetSerializer(maxStringLength); - } + public bool Enable { get; set; } = true; - public void EnqueuePacketForProcessing(byte[] rawData, object userData) - { + public void EnqueuePacketForProcessing(byte[] rawData, object userData) + { #if DEBUG - if (SimulateLatency) + if (SimulateLatency) + { + lock (delayedPackets) { - lock (delayedPackets) - { - PendingPacket packet = new PendingPacket(rawData, userData); - DateTime dueTime = DateTime.UtcNow.AddMilliseconds(simulationRandom.Next(SimulatedMinLatency, SimulatedMaxLatency)); - delayedPackets.Add(new DelayedPacket(packet, dueTime)); - } + var packet = new PendingPacket(rawData, userData); + var dueTime = DateTime.UtcNow.AddMilliseconds(simulationRandom.Next(SimulatedMinLatency, SimulatedMaxLatency)); + delayedPackets.Add(new DelayedPacket(packet, dueTime)); } - else + } + else + { + lock (pendingPackets) { - lock (pendingPackets) - { - pendingPackets.Enqueue(new PendingPacket(rawData, userData)); - } + pendingPackets.Enqueue(new PendingPacket(rawData, userData)); } + } #else lock (pendingPackets) { pendingPackets.Enqueue(new PendingPacket(rawData, userData)); } #endif - } + } - public void ProcessPacketQueue() + public void ProcessPacketQueue() + { + lock (pendingPackets) { - lock (pendingPackets) - { - ProcessDelayedPackets(); + ProcessDelayedPackets(); - while (pendingPackets.Count > 0 && Enable) - { - PendingPacket packet = pendingPackets.Dequeue(); - ReadPacket(new NetDataReader(packet.Data), packet.UserData); - } + while (pendingPackets.Count > 0 && Enable) + { + var packet = pendingPackets.Dequeue(); + ReadPacket(new NetDataReader(packet.Data), packet.UserData); } } + } - [Conditional("DEBUG")] - private void ProcessDelayedPackets() + [Conditional("DEBUG")] + private void ProcessDelayedPackets() + { + lock (delayedPackets) { - lock (delayedPackets) - { - DateTime now = DateTime.UtcNow; - int deleteCount = 0; + var now = DateTime.UtcNow; + var deleteCount = 0; - for (int i = 0; i < delayedPackets.Count; ++i) + for (var i = 0; i < delayedPackets.Count; ++i) + { + if (now >= delayedPackets[i].DueTime) { - if (now >= delayedPackets[i].DueTime) - { - pendingPackets.Enqueue(delayedPackets[i].Packet); - deleteCount = i + 1; - } - else - { - // We need to break to avoid messing up the order of the packets. - break; - } + pendingPackets.Enqueue(delayedPackets[i].Packet); + deleteCount = i + 1; } - - if (deleteCount > 0) + else { - delayedPackets.RemoveRange(0, deleteCount); + // We need to break to avoid messing up the order of the packets. + break; } } - } - - //FNV-1 64 bit hash - protected virtual ulong GetHash() - { - if (HashCache.Initialized) - { - return HashCache.Id; - } - - ulong hash = 14695981039346656037UL; //offset - string typeName = typeof(T).FullName; - for (int i = 0; i < typeName.Length; i++) - { - hash ^= typeName[i]; - hash *= 1099511628211UL; //prime - } - HashCache.Initialized = true; - HashCache.Id = hash; - return hash; - } - - protected virtual SubscribeDelegate GetCallbackFromData(NetDataReader reader) - { - ulong hash = reader.GetULong(); - if (!_callbacks.TryGetValue(hash, out SubscribeDelegate action)) - { - Logger.Log.Warn($"Unknown packet hash: {hash}"); - throw new Exception("Undefined packet in NetDataReader"); - } -#if DEBUG - if (_callbacksDebugInfo.TryGetValue(hash, out Type packetType)) - { - if (!packetType.IsDefined(typeof(HidePacketInDebugLogsAttribute), false)) - { - Logger.Log.Debug($"Packet Received: {packetType.Name}"); - } - } - else + if (deleteCount > 0) { - Logger.Log.Warn($"Packet not registered: {hash}"); + delayedPackets.RemoveRange(0, deleteCount); } -#endif - - return action; - } - - protected virtual void WriteHash(NetDataWriter writer) - { - writer.Put(GetHash()); - } - - [System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Produces error when static")] - public T CreateNestedClassInstance() where T : class, INetSerializable, new() - { - return new T(); } + } - /// - /// Register nested property type - /// - /// INetSerializable structure - public void RegisterNestedType() where T : struct, INetSerializable + //FNV-1 64 bit hash + protected virtual ulong GetHash() + { + if (HashCache.Initialized) { - _netSerializer.RegisterNestedType(); + return HashCache.Id; } - /// - /// Register nested property type - /// - /// - /// - public void RegisterNestedType(Action writeDelegate, Func readDelegate) + var hash = 14695981039346656037UL; //offset + var typeName = typeof(T).FullName; + for (var i = 0; i < typeName.Length; i++) { - _netSerializer.RegisterNestedType(writeDelegate, readDelegate); + hash ^= typeName[i]; + hash *= 1099511628211UL; //prime } + HashCache.Initialized = true; + HashCache.Id = hash; + return hash; + } - /// - /// Register nested property type - /// - /// INetSerializable class - public void RegisterNestedType(Func constructor) where T : class, INetSerializable + protected virtual SubscribeDelegate GetCallbackFromData(NetDataReader reader) + { + var hash = reader.GetULong(); + if (!_callbacks.TryGetValue(hash, out var action)) { - _netSerializer.RegisterNestedType(constructor); + Log.Warn($"Unknown packet hash: {hash}"); + throw new Exception("Undefined packet in NetDataReader"); } - /// - /// Reads all available data from NetDataReader and calls OnReceive delegates - /// - /// NetDataReader with packets data - public void ReadAllPackets(NetDataReader reader) +#if DEBUG + if (_callbacksDebugInfo.TryGetValue(hash, out var packetType)) { - while (reader.AvailableBytes > 0) + if (!packetType.IsDefined(typeof(HidePacketInDebugLogsAttribute), false)) { - ReadPacket(reader); + Log.Debug($"Packet Received: {packetType.Name}"); } } - - /// - /// Reads all available data from NetDataReader and calls OnReceive delegates - /// - /// NetDataReader with packets data - /// Argument that passed to OnReceivedEvent - /// Malformed packet - public void ReadAllPackets(NetDataReader reader, object userData) + else { - while (reader.AvailableBytes > 0) - { - ReadPacket(reader, userData); - } + Log.Warn($"Packet not registered: {hash}"); } +#endif - /// - /// Reads one packet from NetDataReader and calls OnReceive delegate - /// - /// NetDataReader with packet - /// Malformed packet - public void ReadPacket(NetDataReader reader) - { - ReadPacket(reader, null); - } + return action; + } - /* public void Send(NetPeer peer, T packet, DeliveryMethod options) where T : class, new() - { - _netDataWriter.Reset(); - Write(_netDataWriter, packet); - peer.Send(_netDataWriter, options); - } + protected virtual void WriteHash(NetDataWriter writer) + { + writer.Put(GetHash()); + } - public void SendNetSerializable(NetPeer peer, T packet, DeliveryMethod options) where T : INetSerializable - { - _netDataWriter.Reset(); - WriteNetSerializable(_netDataWriter, packet); - peer.Send(_netDataWriter, options); - } + [SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Produces error when static")] + public T CreateNestedClassInstance() where T : class, INetSerializable, new() + { + return new T(); + } - public void Send(NetManager manager, T packet, DeliveryMethod options) where T : class, new() - { - _netDataWriter.Reset(); - Write(_netDataWriter, packet); - manager.SendToAll(_netDataWriter, options); - } + /// + /// Register nested property type + /// + /// INetSerializable structure + public void RegisterNestedType() where T : struct, INetSerializable + { + _netSerializer.RegisterNestedType(); + } - public void SendNetSerializable(NetManager manager, T packet, DeliveryMethod options) where T : INetSerializable - { - _netDataWriter.Reset(); - WriteNetSerializable(_netDataWriter, packet); - manager.SendToAll(_netDataWriter, options); - }*/ + /// + /// Register nested property type + /// + /// + /// + public void RegisterNestedType(Action writeDelegate, Func readDelegate) + { + _netSerializer.RegisterNestedType(writeDelegate, readDelegate); + } + + /// + /// Register nested property type + /// + /// INetSerializable class + public void RegisterNestedType(Func constructor) where T : class, INetSerializable + { + _netSerializer.RegisterNestedType(constructor); + } - public void Write(NetDataWriter writer, T packet) where T : class, new() + /// + /// Reads all available data from NetDataReader and calls OnReceive delegates + /// + /// NetDataReader with packets data + public void ReadAllPackets(NetDataReader reader) + { + while (reader.AvailableBytes > 0) { - WriteHash(writer); - _netSerializer.Serialize(writer, packet); + ReadPacket(reader); } + } - public void WriteNetSerializable(NetDataWriter writer, T packet) where T : INetSerializable + /// + /// Reads all available data from NetDataReader and calls OnReceive delegates + /// + /// NetDataReader with packets data + /// Argument that passed to OnReceivedEvent + /// Malformed packet + public void ReadAllPackets(NetDataReader reader, object userData) + { + while (reader.AvailableBytes > 0) { - WriteHash(writer); - packet.Serialize(writer); + ReadPacket(reader, userData); } + } - public byte[] Write(T packet) where T : class, new() - { -#if DEBUG - if (!typeof(T).IsDefined(typeof(HidePacketInDebugLogsAttribute), false)) + /// + /// Reads one packet from NetDataReader and calls OnReceive delegate + /// + /// NetDataReader with packet + /// Malformed packet + public void ReadPacket(NetDataReader reader) + { + ReadPacket(reader, null); + } + + /* public void Send(NetPeer peer, T packet, DeliveryMethod options) where T : class, new() { - Logger.Log.Debug($"Packet Sent: {packet.GetType().Name}"); + _netDataWriter.Reset(); + Write(_netDataWriter, packet); + peer.Send(_netDataWriter, options); } -#endif - _netDataWriter.Reset(); - WriteHash(_netDataWriter); - _netSerializer.Serialize(_netDataWriter, packet); - return _netDataWriter.CopyData(); - } - public byte[] WriteNetSerializable(T packet) where T : INetSerializable - { - _netDataWriter.Reset(); - WriteHash(_netDataWriter); - packet.Serialize(_netDataWriter); - return _netDataWriter.CopyData(); - } + public void SendNetSerializable(NetPeer peer, T packet, DeliveryMethod options) where T : INetSerializable + { + _netDataWriter.Reset(); + WriteNetSerializable(_netDataWriter, packet); + peer.Send(_netDataWriter, options); + } - /// - /// Reads one packet from NetDataReader and calls OnReceive delegate - /// - /// NetDataReader with packet - /// Argument that passed to OnReceivedEvent - /// Malformed packet - public void ReadPacket(NetDataReader reader, object userData) + public void Send(NetManager manager, T packet, DeliveryMethod options) where T : class, new() + { + _netDataWriter.Reset(); + Write(_netDataWriter, packet); + manager.SendToAll(_netDataWriter, options); + } + + public void SendNetSerializable(NetManager manager, T packet, DeliveryMethod options) where T : INetSerializable + { + _netDataWriter.Reset(); + WriteNetSerializable(_netDataWriter, packet); + manager.SendToAll(_netDataWriter, options); + }*/ + + public void Write(NetDataWriter writer, T packet) where T : class, new() + { + WriteHash(writer); + _netSerializer.Serialize(writer, packet); + } + + public void WriteNetSerializable(NetDataWriter writer, T packet) where T : INetSerializable + { + WriteHash(writer); + packet.Serialize(writer); + } + + public byte[] Write(T packet) where T : class, new() + { +#if DEBUG + if (!typeof(T).IsDefined(typeof(HidePacketInDebugLogsAttribute), false)) { - GetCallbackFromData(reader)(reader, userData); + Log.Debug($"Packet Sent: {packet.GetType().Name}"); } +#endif + _netDataWriter.Reset(); + WriteHash(_netDataWriter); + _netSerializer.Serialize(_netDataWriter, packet); + return _netDataWriter.CopyData(); + } + + public byte[] WriteNetSerializable(T packet) where T : INetSerializable + { + _netDataWriter.Reset(); + WriteHash(_netDataWriter); + packet.Serialize(_netDataWriter); + return _netDataWriter.CopyData(); + } + + /// + /// Reads one packet from NetDataReader and calls OnReceive delegate + /// + /// NetDataReader with packet + /// Argument that passed to OnReceivedEvent + /// Malformed packet + public void ReadPacket(NetDataReader reader, object userData) + { + GetCallbackFromData(reader)(reader, userData); + } - /// - /// Register and subscribe to packet receive event - /// - /// event that will be called when packet deserialized with ReadPacket method - /// Method that constructs packet instead of slow Activator.CreateInstance - /// 's fields are not supported, or it has no fields - public void Subscribe(Action onReceive, Func packetConstructor) where T : class, new() + /// + /// Register and subscribe to packet receive event + /// + /// event that will be called when packet deserialized with ReadPacket method + /// Method that constructs packet instead of slow Activator.CreateInstance + /// 's fields are not supported, or it has no fields + public void Subscribe(Action onReceive, Func packetConstructor) where T : class, new() + { + _netSerializer.Register(); + _callbacks[GetHash()] = (reader, userData) => { - _netSerializer.Register(); - _callbacks[GetHash()] = (reader, userData) => - { - T reference = packetConstructor(); - _netSerializer.Deserialize(reader, reference); - onReceive(reference); - }; - } + var reference = packetConstructor(); + _netSerializer.Deserialize(reader, reference); + onReceive(reference); + }; + } - /// - /// Register and subscribe to packet receive event (with userData) - /// - /// event that will be called when packet deserialized with ReadPacket method - /// Method that constructs packet instead of slow Activator.CreateInstance - /// 's fields are not supported, or it has no fields - public void Subscribe(Action onReceive, Func packetConstructor) where T : class, new() + /// + /// Register and subscribe to packet receive event (with userData) + /// + /// event that will be called when packet deserialized with ReadPacket method + /// Method that constructs packet instead of slow Activator.CreateInstance + /// 's fields are not supported, or it has no fields + public void Subscribe(Action onReceive, Func packetConstructor) where T : class, new() + { + _netSerializer.Register(); + _callbacks[GetHash()] = (reader, userData) => { - _netSerializer.Register(); - _callbacks[GetHash()] = (reader, userData) => - { - T reference = packetConstructor(); - _netSerializer.Deserialize(reader, reference); - onReceive(reference, (TUserData)userData); - }; - } + var reference = packetConstructor(); + _netSerializer.Deserialize(reader, reference); + onReceive(reference, (TUserData)userData); + }; + } - /// - /// Register and subscribe to packet receive event - /// This method will overwrite last received packet class on receive (less garbage) - /// - /// event that will be called when packet deserialized with ReadPacket method - /// 's fields are not supported, or it has no fields - public void SubscribeReusable(Action onReceive) where T : class, new() + /// + /// Register and subscribe to packet receive event + /// This method will overwrite last received packet class on receive (less garbage) + /// + /// event that will be called when packet deserialized with ReadPacket method + /// 's fields are not supported, or it has no fields + public void SubscribeReusable(Action onReceive) where T : class, new() + { + _netSerializer.Register(); + var reference = new T(); + _callbacks[GetHash()] = (reader, userData) => { - _netSerializer.Register(); - T reference = new T(); - _callbacks[GetHash()] = (reader, userData) => - { - _netSerializer.Deserialize(reader, reference); - onReceive(reference); - }; - } + _netSerializer.Deserialize(reader, reference); + onReceive(reference); + }; + } - /// - /// Register and subscribe to packet receive event - /// This method will overwrite last received packet class on receive (less garbage) - /// - /// event that will be called when packet deserialized with ReadPacket method - /// 's fields are not supported, or it has no fields - public void SubscribeReusable(Action onReceive) where T : class, new() + /// + /// Register and subscribe to packet receive event + /// This method will overwrite last received packet class on receive (less garbage) + /// + /// event that will be called when packet deserialized with ReadPacket method + /// 's fields are not supported, or it has no fields + public void SubscribeReusable(Action onReceive) where T : class, new() + { + _netSerializer.Register(); + var reference = new T(); + _callbacks[GetHash()] = (reader, userData) => { - _netSerializer.Register(); - T reference = new T(); - _callbacks[GetHash()] = (reader, userData) => - { - _netSerializer.Deserialize(reader, reference); - onReceive(reference, (TUserData)userData); - }; + _netSerializer.Deserialize(reader, reference); + onReceive(reference, (TUserData)userData); + }; #if DEBUG - _callbacksDebugInfo[GetHash()] = typeof(T); + _callbacksDebugInfo[GetHash()] = typeof(T); #endif - } + } - public void SubscribeNetSerializable( - Action onReceive, - Func packetConstructor) where T : INetSerializable + public void SubscribeNetSerializable( + Action onReceive, + Func packetConstructor) where T : INetSerializable + { + _callbacks[GetHash()] = (reader, userData) => { - _callbacks[GetHash()] = (reader, userData) => - { - T pkt = packetConstructor(); - pkt.Deserialize(reader); - onReceive(pkt, (TUserData)userData); - }; - } + var pkt = packetConstructor(); + pkt.Deserialize(reader); + onReceive(pkt, (TUserData)userData); + }; + } - public void SubscribeNetSerializable( - Action onReceive, - Func packetConstructor) where T : INetSerializable + public void SubscribeNetSerializable( + Action onReceive, + Func packetConstructor) where T : INetSerializable + { + _callbacks[GetHash()] = (reader, userData) => { - _callbacks[GetHash()] = (reader, userData) => - { - T pkt = packetConstructor(); - pkt.Deserialize(reader); - onReceive(pkt); - }; - } + var pkt = packetConstructor(); + pkt.Deserialize(reader); + onReceive(pkt); + }; + } - public void SubscribeNetSerializable( - Action onReceive) where T : INetSerializable, new() + public void SubscribeNetSerializable( + Action onReceive) where T : INetSerializable, new() + { + var reference = new T(); + _callbacks[GetHash()] = (reader, userData) => { - T reference = new T(); - _callbacks[GetHash()] = (reader, userData) => - { - reference.Deserialize(reader); - onReceive(reference, (TUserData)userData); - }; - } + reference.Deserialize(reader); + onReceive(reference, (TUserData)userData); + }; + } - public void SubscribeNetSerializable( - Action onReceive) where T : INetSerializable, new() + public void SubscribeNetSerializable( + Action onReceive) where T : INetSerializable, new() + { + var reference = new T(); + _callbacks[GetHash()] = (reader, userData) => { - T reference = new T(); - _callbacks[GetHash()] = (reader, userData) => - { - reference.Deserialize(reader); - onReceive(reference); - }; - } + reference.Deserialize(reader); + onReceive(reference); + }; + } - /// - /// Remove any subscriptions by type - /// - /// Packet type - /// true if remove is success - public bool RemoveSubscription() - { - return _callbacks.Remove(GetHash()); - } + /// + /// Remove any subscriptions by type + /// + /// Packet type + /// true if remove is success + public bool RemoveSubscription() + { + return _callbacks.Remove(GetHash()); } + + private static class HashCache + { + public static bool Initialized; + public static ulong Id; + } + + protected delegate void SubscribeDelegate(NetDataReader reader, object userData); } diff --git a/NebulaModel/Networking/Serialization/NetSerializer.cs b/NebulaModel/Networking/Serialization/NetSerializer.cs index 661fda66d..dbcb6d987 100644 --- a/NebulaModel/Networking/Serialization/NetSerializer.cs +++ b/NebulaModel/Networking/Serialization/NetSerializer.cs @@ -1,832 +1,932 @@ -using NebulaAPI; +#region + using System; using System.Collections.Generic; using System.Net; using System.Reflection; +using NebulaAPI; + +#endregion -namespace NebulaModel.Networking.Serialization +namespace NebulaModel.Networking.Serialization; + +public class InvalidTypeException : ArgumentException { - public class InvalidTypeException : ArgumentException + public InvalidTypeException(string message) : base(message) { } +} + +public class ParseException : Exception +{ + public ParseException(string message) : base(message) { } +} + +public class NetSerializer +{ + private readonly int _maxStringLength; + private readonly Dictionary _registeredTypes = new(); + + private NetDataWriter _writer; + + public NetSerializer() : this(0) { - public InvalidTypeException(string message) : base(message) { } } - public class ParseException : Exception + public NetSerializer(int maxStringLength) { - public ParseException(string message) : base(message) { } + _maxStringLength = maxStringLength; } - public class NetSerializer + /// + /// Register custom property type + /// + /// INetSerializable structure + public void RegisterNestedType() where T : struct, INetSerializable { - private enum CallType - { - Basic, - Array, - List - } + _registeredTypes.Add(typeof(T), new CustomTypeStruct()); + } + + /// + /// Register custom property type + /// + /// INetSerializable class + public void RegisterNestedType(Func constructor) where T : class, INetSerializable + { + _registeredTypes.Add(typeof(T), new CustomTypeClass(constructor)); + } + + /// + /// Register custom property type + /// + /// Any packet + /// custom type writer + /// custom type reader + public void RegisterNestedType(Action writer, Func reader) + { + _registeredTypes.Add(typeof(T), new CustomTypeStatic(writer, reader)); + } - private abstract class FastCall + private ClassInfo RegisterInternal() + { + if (ClassInfo.Instance != null) { - public CallType Type; - public virtual void Init(MethodInfo getMethod, MethodInfo setMethod, CallType type) { Type = type; } - public abstract void Read(T inf, NetDataReader r); - public abstract void Write(T inf, NetDataWriter w); - public abstract void ReadArray(T inf, NetDataReader r); - public abstract void WriteArray(T inf, NetDataWriter w); - public abstract void ReadList(T inf, NetDataReader r); - public abstract void WriteList(T inf, NetDataWriter w); + return ClassInfo.Instance; } - private abstract class FastCallSpecific : FastCall + var t = typeof(T); + var props = t.GetProperties( + BindingFlags.Instance | + BindingFlags.Public | + BindingFlags.GetProperty | + BindingFlags.SetProperty); + var serializers = new List>(); + for (var i = 0; i < props.Length; i++) { - protected Func Getter; - protected Action Setter; - protected Func GetterArr; - protected Action SetterArr; - protected Func> GetterList; - protected Action> SetterList; + var property = props[i]; + var propertyType = property.PropertyType; - public override void ReadArray(TClass inf, NetDataReader r) { throw new InvalidTypeException("Unsupported type: " + typeof(TProperty) + "[]"); } - public override void WriteArray(TClass inf, NetDataWriter w) { throw new InvalidTypeException("Unsupported type: " + typeof(TProperty) + "[]"); } - public override void ReadList(TClass inf, NetDataReader r) { throw new InvalidTypeException("Unsupported type: List<" + typeof(TProperty) + ">"); } - public override void WriteList(TClass inf, NetDataWriter w) { throw new InvalidTypeException("Unsupported type: List<" + typeof(TProperty) + ">"); } + var elementType = propertyType.IsArray ? propertyType.GetElementType() : propertyType; + var callType = propertyType.IsArray ? CallType.Array : CallType.Basic; - protected TProperty[] ReadArrayHelper(TClass inf, NetDataReader r) + if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(List<>)) { - ushort count = r.GetUShort(); - TProperty[] arr = GetterArr(inf); - arr = arr == null || arr.Length != count ? new TProperty[count] : arr; - SetterArr(inf, arr); - return arr; + elementType = propertyType.GetGenericArguments()[0]; + callType = CallType.List; } - protected TProperty[] WriteArrayHelper(TClass inf, NetDataWriter w) + // Note from Cod: Required to get it to build + // TODO: Fix this + /*if (Attribute.IsDefined(property, typeof(IgnoreDataMemberAttribute))) + continue;*/ + + var getMethod = property.GetGetMethod(); + var setMethod = property.GetSetMethod(); + if (getMethod == null || setMethod == null) { - TProperty[] arr = GetterArr(inf); - w.Put((ushort)arr.Length); - return arr; + continue; } - protected List ReadListHelper(TClass inf, NetDataReader r, out int len) + FastCall serialzer = null; + if (propertyType.IsEnum) { - len = r.GetUShort(); - List list = GetterList(inf); - if (list == null) + var underlyingType = Enum.GetUnderlyingType(propertyType); + if (underlyingType == typeof(byte)) { - list = new List(len); - SetterList(inf, list); + serialzer = new EnumByteSerializer(property, propertyType); } - return list; - } - - protected List WriteListHelper(TClass inf, NetDataWriter w, out int len) - { - List list = GetterList(inf); - if (list == null) + else if (underlyingType == typeof(int)) { - len = 0; - w.Put(0); - return null; + serialzer = new EnumIntSerializer(property, propertyType); } - len = list.Count; - w.Put((ushort)len); - return list; - } - - public override void Init(MethodInfo getMethod, MethodInfo setMethod, CallType type) - { - base.Init(getMethod, setMethod, type); - switch (type) + else { - case CallType.Array: - GetterArr = (Func)Delegate.CreateDelegate(typeof(Func), getMethod); - SetterArr = (Action)Delegate.CreateDelegate(typeof(Action), setMethod); - break; - case CallType.List: - GetterList = (Func>)Delegate.CreateDelegate(typeof(Func>), getMethod); - SetterList = (Action>)Delegate.CreateDelegate(typeof(Action>), setMethod); - break; - default: - Getter = (Func)Delegate.CreateDelegate(typeof(Func), getMethod); - Setter = (Action)Delegate.CreateDelegate(typeof(Action), setMethod); - break; + throw new InvalidTypeException("Not supported enum underlying type: " + underlyingType.Name); } } - } - - private abstract class FastCallSpecificAuto : FastCallSpecific - { - protected abstract void ElementRead(NetDataReader r, out TProperty prop); - protected abstract void ElementWrite(NetDataWriter w, ref TProperty prop); - - public override void Read(TClass inf, NetDataReader r) + else if (elementType == typeof(string)) { - ElementRead(r, out TProperty elem); - Setter(inf, elem); + serialzer = new StringSerializer(_maxStringLength); } - - public override void Write(TClass inf, NetDataWriter w) + else if (elementType == typeof(bool)) { - TProperty elem = Getter(inf); - ElementWrite(w, ref elem); + serialzer = new BoolSerializer(); } - - public override void ReadArray(TClass inf, NetDataReader r) + else if (elementType == typeof(byte)) { - TProperty[] arr = ReadArrayHelper(inf, r); - for (int i = 0; i < arr.Length; i++) - { - ElementRead(r, out arr[i]); - } + serialzer = new ByteSerializer(); } - - public override void WriteArray(TClass inf, NetDataWriter w) + else if (elementType == typeof(sbyte)) { - TProperty[] arr = WriteArrayHelper(inf, w); - for (int i = 0; i < arr.Length; i++) - { - ElementWrite(w, ref arr[i]); - } + serialzer = new SByteSerializer(); } - } - - private sealed class FastCallStatic : FastCallSpecific - { - private readonly Action _writer; - private readonly Func _reader; - - public FastCallStatic(Action write, Func read) + else if (elementType == typeof(short)) { - _writer = write; - _reader = read; + serialzer = new ShortSerializer(); } - - public override void Read(TClass inf, NetDataReader r) { Setter(inf, _reader(r)); } - public override void Write(TClass inf, NetDataWriter w) { _writer(w, Getter(inf)); } - - public override void ReadList(TClass inf, NetDataReader r) + else if (elementType == typeof(ushort)) { - List list = ReadListHelper(inf, r, out int len); - int listCount = list.Count; - for (int i = 0; i < len; i++) - { - if (i < listCount) - { - list[i] = _reader(r); - } - else - { - list.Add(_reader(r)); - } - } - if (len < listCount) - { - list.RemoveRange(len, listCount - len); - } + serialzer = new UShortSerializer(); } - - public override void WriteList(TClass inf, NetDataWriter w) + else if (elementType == typeof(int)) { - List list = WriteListHelper(inf, w, out int len); - for (int i = 0; i < len; i++) - { - _writer(w, list[i]); - } + serialzer = new IntSerializer(); } - - public override void ReadArray(TClass inf, NetDataReader r) + else if (elementType == typeof(uint)) { - TProperty[] arr = ReadArrayHelper(inf, r); - int len = arr.Length; - for (int i = 0; i < len; i++) - { - arr[i] = _reader(r); - } + serialzer = new UIntSerializer(); } - - public override void WriteArray(TClass inf, NetDataWriter w) + else if (elementType == typeof(long)) { - TProperty[] arr = WriteArrayHelper(inf, w); - int len = arr.Length; - for (int i = 0; i < len; i++) - { - _writer(w, arr[i]); - } + serialzer = new LongSerializer(); } - } - - private sealed class FastCallStruct : FastCallSpecific where TProperty : struct, INetSerializable - { - private TProperty _p; - - public override void Read(TClass inf, NetDataReader r) + else if (elementType == typeof(ulong)) { - _p.Deserialize(r); - Setter(inf, _p); + serialzer = new ULongSerializer(); } - - public override void Write(TClass inf, NetDataWriter w) + else if (elementType == typeof(float)) { - _p = Getter(inf); - _p.Serialize(w); + serialzer = new FloatSerializer(); } - - public override void ReadList(TClass inf, NetDataReader r) + else if (elementType == typeof(double)) { - List list = ReadListHelper(inf, r, out int len); - int listCount = list.Count; - for (int i = 0; i < len; i++) - { - TProperty itm = default(TProperty); - itm.Deserialize(r); - if (i < listCount) - { - list[i] = itm; - } - else - { - list.Add(itm); - } - } - if (len < listCount) - { - list.RemoveRange(len, listCount - len); - } + serialzer = new DoubleSerializer(); } - - public override void WriteList(TClass inf, NetDataWriter w) + else if (elementType == typeof(char)) { - List list = WriteListHelper(inf, w, out int len); - for (int i = 0; i < len; i++) - { - list[i].Serialize(w); - } + serialzer = new CharSerializer(); } - - public override void ReadArray(TClass inf, NetDataReader r) + else if (elementType == typeof(IPEndPoint)) { - TProperty[] arr = ReadArrayHelper(inf, r); - int len = arr.Length; - for (int i = 0; i < len; i++) - { - arr[i].Deserialize(r); - } + serialzer = new IPEndPointSerializer(); } - - public override void WriteArray(TClass inf, NetDataWriter w) + else { - TProperty[] arr = WriteArrayHelper(inf, w); - int len = arr.Length; - for (int i = 0; i < len; i++) + _registeredTypes.TryGetValue(elementType, out var customType); + if (customType != null) { - arr[i].Serialize(w); + serialzer = customType.Get(); } } - } - - private sealed class FastCallClass : FastCallSpecific where TProperty : class, INetSerializable - { - private readonly Func _constructor; - public FastCallClass(Func constructor) { _constructor = constructor; } - public override void Read(TClass inf, NetDataReader r) + if (serialzer != null) { - TProperty p = _constructor(); - p.Deserialize(r); - Setter(inf, p); + serialzer.Init(getMethod, setMethod, callType); + serializers.Add(serialzer); } - - public override void Write(TClass inf, NetDataWriter w) + else { - TProperty p = Getter(inf); - if (p != null) - { - p.Serialize(w); - } + throw new InvalidTypeException("Unknown property type: " + propertyType.FullName); } + } + ClassInfo.Instance = new ClassInfo(serializers); + return ClassInfo.Instance; + } - public override void ReadList(TClass inf, NetDataReader r) - { - List list = ReadListHelper(inf, r, out int len); - int listCount = list.Count; - for (int i = 0; i < len; i++) - { - if (i < listCount) - { - list[i].Deserialize(r); - } - else - { - TProperty itm = _constructor(); - itm.Deserialize(r); - list.Add(itm); - } - } - if (len < listCount) - { - list.RemoveRange(len, listCount - len); - } - } + /// 's fields are not supported, or it has no fields + public void Register() + { + RegisterInternal(); + } - public override void WriteList(TClass inf, NetDataWriter w) - { - List list = WriteListHelper(inf, w, out int len); - for (int i = 0; i < len; i++) - { - list[i].Serialize(w); - } - } + /// + /// Reads packet with known type + /// + /// NetDataReader with packet + /// Returns packet if packet in reader is matched type + /// 's fields are not supported, or it has no fields + public T Deserialize(NetDataReader reader) where T : class, new() + { + var info = RegisterInternal(); + var result = new T(); + try + { + info.Read(result, reader); + } + catch + { + return null; + } + return result; + } - public override void ReadArray(TClass inf, NetDataReader r) - { - TProperty[] arr = ReadArrayHelper(inf, r); - int len = arr.Length; - for (int i = 0; i < len; i++) - { - arr[i] = _constructor(); - arr[i].Deserialize(r); - } - } + /// + /// Reads packet with known type (non alloc variant) + /// + /// NetDataReader with packet + /// Deserialization target + /// Returns true if packet in reader is matched type + /// 's fields are not supported, or it has no fields + public bool Deserialize(NetDataReader reader, T target) where T : class, new() + { + var info = RegisterInternal(); + try + { + info.Read(target, reader); + } + catch + { + return false; + } + return true; + } - public override void WriteArray(TClass inf, NetDataWriter w) - { - TProperty[] arr = WriteArrayHelper(inf, w); - int len = arr.Length; - for (int i = 0; i < len; i++) - { - arr[i].Serialize(w); - } - } + /// + /// Serialize object to NetDataWriter (fast) + /// + /// Serialization target NetDataWriter + /// Object to serialize + /// 's fields are not supported, or it has no fields + public void Serialize(NetDataWriter writer, T obj) where T : class, new() + { + RegisterInternal().Write(obj, writer); + } + + /// + /// Serialize object to byte array + /// + /// Object to serialize + /// byte array with serialized data + public byte[] Serialize(T obj) where T : class, new() + { + if (_writer == null) + { + _writer = new NetDataWriter(); } - private class IntSerializer : FastCallSpecific + _writer.Reset(); + Serialize(_writer, obj); + return _writer.CopyData(); + } + + private enum CallType + { + Basic, + Array, + List + } + + private abstract class FastCall + { + public CallType Type; + + public virtual void Init(MethodInfo getMethod, MethodInfo setMethod, CallType type) { Type = type; } + + public abstract void Read(T inf, NetDataReader r); + + public abstract void Write(T inf, NetDataWriter w); + + public abstract void ReadArray(T inf, NetDataReader r); + + public abstract void WriteArray(T inf, NetDataWriter w); + + public abstract void ReadList(T inf, NetDataReader r); + + public abstract void WriteList(T inf, NetDataWriter w); + } + + private abstract class FastCallSpecific : FastCall + { + protected Func Getter; + protected Func GetterArr; + protected Func> GetterList; + protected Action Setter; + protected Action SetterArr; + protected Action> SetterList; + + public override void ReadArray(TClass inf, NetDataReader r) { - public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetInt()); } - public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } - public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetIntArray()); } - public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf)); } + throw new InvalidTypeException("Unsupported type: " + typeof(TProperty) + "[]"); } - private class UIntSerializer : FastCallSpecific + public override void WriteArray(TClass inf, NetDataWriter w) { - public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetUInt()); } - public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } - public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetUIntArray()); } - public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf)); } + throw new InvalidTypeException("Unsupported type: " + typeof(TProperty) + "[]"); } - private class ShortSerializer : FastCallSpecific + public override void ReadList(TClass inf, NetDataReader r) { - public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetShort()); } - public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } - public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetShortArray()); } - public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf)); } + throw new InvalidTypeException("Unsupported type: List<" + typeof(TProperty) + ">"); } - private class UShortSerializer : FastCallSpecific + public override void WriteList(TClass inf, NetDataWriter w) { - public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetUShort()); } - public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } - public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetUShortArray()); } - public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf)); } + throw new InvalidTypeException("Unsupported type: List<" + typeof(TProperty) + ">"); } - private class LongSerializer : FastCallSpecific + protected TProperty[] ReadArrayHelper(TClass inf, NetDataReader r) { - public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetLong()); } - public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } - public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetLongArray()); } - public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf)); } + var count = r.GetUShort(); + var arr = GetterArr(inf); + arr = arr == null || arr.Length != count ? new TProperty[count] : arr; + SetterArr(inf, arr); + return arr; } - private class ULongSerializer : FastCallSpecific + protected TProperty[] WriteArrayHelper(TClass inf, NetDataWriter w) { - public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetULong()); } - public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } - public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetULongArray()); } - public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf)); } + var arr = GetterArr(inf); + w.Put((ushort)arr.Length); + return arr; } - private class ByteSerializer : FastCallSpecific + protected List ReadListHelper(TClass inf, NetDataReader r, out int len) { - public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetByte()); } - public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } - public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetBytesWithLength()); } - public override void WriteArray(T inf, NetDataWriter w) { w.PutBytesWithLength(GetterArr(inf)); } + len = r.GetUShort(); + var list = GetterList(inf); + if (list == null) + { + list = new List(len); + SetterList(inf, list); + } + return list; } - private class SByteSerializer : FastCallSpecific + protected List WriteListHelper(TClass inf, NetDataWriter w, out int len) { - public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetSByte()); } - public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } - public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetSBytesWithLength()); } - public override void WriteArray(T inf, NetDataWriter w) { w.PutSBytesWithLength(GetterArr(inf)); } + var list = GetterList(inf); + if (list == null) + { + len = 0; + w.Put(0); + return null; + } + len = list.Count; + w.Put((ushort)len); + return list; } - private class FloatSerializer : FastCallSpecific + public override void Init(MethodInfo getMethod, MethodInfo setMethod, CallType type) { - public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetFloat()); } - public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } - public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetFloatArray()); } - public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf)); } + base.Init(getMethod, setMethod, type); + switch (type) + { + case CallType.Array: + GetterArr = (Func)Delegate.CreateDelegate(typeof(Func), + getMethod); + SetterArr = (Action)Delegate.CreateDelegate(typeof(Action), + setMethod); + break; + case CallType.List: + GetterList = (Func>)Delegate.CreateDelegate(typeof(Func>), + getMethod); + SetterList = (Action>)Delegate.CreateDelegate( + typeof(Action>), setMethod); + break; + default: + Getter = (Func)Delegate.CreateDelegate(typeof(Func), getMethod); + Setter = (Action)Delegate.CreateDelegate(typeof(Action), setMethod); + break; + } } + } + + private abstract class FastCallSpecificAuto : FastCallSpecific + { + protected abstract void ElementRead(NetDataReader r, out TProperty prop); + + protected abstract void ElementWrite(NetDataWriter w, ref TProperty prop); - private class DoubleSerializer : FastCallSpecific + public override void Read(TClass inf, NetDataReader r) { - public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetDouble()); } - public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } - public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetDoubleArray()); } - public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf)); } + ElementRead(r, out var elem); + Setter(inf, elem); } - private class BoolSerializer : FastCallSpecific + public override void Write(TClass inf, NetDataWriter w) { - public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetBool()); } - public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } - public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetBoolArray()); } - public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf)); } + var elem = Getter(inf); + ElementWrite(w, ref elem); } - private class CharSerializer : FastCallSpecificAuto + public override void ReadArray(TClass inf, NetDataReader r) { - protected override void ElementWrite(NetDataWriter w, ref char prop) { w.Put(prop); } - protected override void ElementRead(NetDataReader r, out char prop) { prop = r.GetChar(); } + var arr = ReadArrayHelper(inf, r); + for (var i = 0; i < arr.Length; i++) + { + ElementRead(r, out arr[i]); + } } - private class IPEndPointSerializer : FastCallSpecificAuto + public override void WriteArray(TClass inf, NetDataWriter w) { - protected override void ElementWrite(NetDataWriter w, ref IPEndPoint prop) { w.Put(prop); } - protected override void ElementRead(NetDataReader r, out IPEndPoint prop) { prop = r.GetNetEndPoint(); } + var arr = WriteArrayHelper(inf, w); + for (var i = 0; i < arr.Length; i++) + { + ElementWrite(w, ref arr[i]); + } } + } + + private sealed class FastCallStatic : FastCallSpecific + { + private readonly Func _reader; + private readonly Action _writer; - private class StringSerializer : FastCallSpecific + public FastCallStatic(Action write, Func read) { - private readonly int _maxLength; - public StringSerializer(int maxLength) { _maxLength = maxLength > 0 ? maxLength : short.MaxValue; } - public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetString(_maxLength)); } - public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf), _maxLength); } - public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetStringArray(_maxLength)); } - public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf), _maxLength); } + _writer = write; + _reader = read; } - private class EnumByteSerializer : FastCall + public override void Read(TClass inf, NetDataReader r) { Setter(inf, _reader(r)); } + + public override void Write(TClass inf, NetDataWriter w) { _writer(w, Getter(inf)); } + + public override void ReadList(TClass inf, NetDataReader r) { - protected readonly PropertyInfo Property; - protected readonly Type PropertyType; - public EnumByteSerializer(PropertyInfo property, Type propertyType) + var list = ReadListHelper(inf, r, out var len); + var listCount = list.Count; + for (var i = 0; i < len; i++) { - Property = property; - PropertyType = propertyType; + if (i < listCount) + { + list[i] = _reader(r); + } + else + { + list.Add(_reader(r)); + } + } + if (len < listCount) + { + list.RemoveRange(len, listCount - len); } - public override void Read(T inf, NetDataReader r) { Property.SetValue(inf, Enum.ToObject(PropertyType, r.GetByte()), null); } - public override void Write(T inf, NetDataWriter w) { w.Put((byte)Property.GetValue(inf, null)); } - public override void ReadArray(T inf, NetDataReader r) { throw new InvalidTypeException("Unsupported type: Enum[]"); } - public override void WriteArray(T inf, NetDataWriter w) { throw new InvalidTypeException("Unsupported type: Enum[]"); } - public override void ReadList(T inf, NetDataReader r) { throw new InvalidTypeException("Unsupported type: List"); } - public override void WriteList(T inf, NetDataWriter w) { throw new InvalidTypeException("Unsupported type: List"); } } - private class EnumIntSerializer : EnumByteSerializer + public override void WriteList(TClass inf, NetDataWriter w) { - public EnumIntSerializer(PropertyInfo property, Type propertyType) : base(property, propertyType) { } - public override void Read(T inf, NetDataReader r) { Property.SetValue(inf, Enum.ToObject(PropertyType, r.GetInt()), null); } - public override void Write(T inf, NetDataWriter w) { w.Put((int)Property.GetValue(inf, null)); } + var list = WriteListHelper(inf, w, out var len); + for (var i = 0; i < len; i++) + { + _writer(w, list[i]); + } } - private sealed class ClassInfo + public override void ReadArray(TClass inf, NetDataReader r) { - public static ClassInfo Instance; - private readonly FastCall[] _serializers; - private readonly int _membersCount; + var arr = ReadArrayHelper(inf, r); + var len = arr.Length; + for (var i = 0; i < len; i++) + { + arr[i] = _reader(r); + } + } - public ClassInfo(List> serializers) + public override void WriteArray(TClass inf, NetDataWriter w) + { + var arr = WriteArrayHelper(inf, w); + var len = arr.Length; + for (var i = 0; i < len; i++) { - _membersCount = serializers.Count; - _serializers = serializers.ToArray(); + _writer(w, arr[i]); } + } + } + + private sealed class FastCallStruct : FastCallSpecific + where TProperty : struct, INetSerializable + { + private TProperty _p; + + public override void Read(TClass inf, NetDataReader r) + { + _p.Deserialize(r); + Setter(inf, _p); + } + + public override void Write(TClass inf, NetDataWriter w) + { + _p = Getter(inf); + _p.Serialize(w); + } - public void Write(T obj, NetDataWriter writer) + public override void ReadList(TClass inf, NetDataReader r) + { + var list = ReadListHelper(inf, r, out var len); + var listCount = list.Count; + for (var i = 0; i < len; i++) { - for (int i = 0; i < _membersCount; i++) + var itm = default(TProperty); + itm.Deserialize(r); + if (i < listCount) { - FastCall s = _serializers[i]; - if (s.Type == CallType.Basic) - { - s.Write(obj, writer); - } - else if (s.Type == CallType.Array) - { - s.WriteArray(obj, writer); - } - else - { - s.WriteList(obj, writer); - } + list[i] = itm; + } + else + { + list.Add(itm); } } + if (len < listCount) + { + list.RemoveRange(len, listCount - len); + } + } - public void Read(T obj, NetDataReader reader) + public override void WriteList(TClass inf, NetDataWriter w) + { + var list = WriteListHelper(inf, w, out var len); + for (var i = 0; i < len; i++) { - for (int i = 0; i < _membersCount; i++) - { - FastCall s = _serializers[i]; - if (s.Type == CallType.Basic) - { - s.Read(obj, reader); - } - else if (s.Type == CallType.Array) - { - s.ReadArray(obj, reader); - } - else - { - s.ReadList(obj, reader); - } - } + list[i].Serialize(w); + } + } + + public override void ReadArray(TClass inf, NetDataReader r) + { + var arr = ReadArrayHelper(inf, r); + var len = arr.Length; + for (var i = 0; i < len; i++) + { + arr[i].Deserialize(r); } } - private abstract class CustomType + public override void WriteArray(TClass inf, NetDataWriter w) { - public abstract FastCall Get(); + var arr = WriteArrayHelper(inf, w); + var len = arr.Length; + for (var i = 0; i < len; i++) + { + arr[i].Serialize(w); + } } + } + + private sealed class FastCallClass : FastCallSpecific + where TProperty : class, INetSerializable + { + private readonly Func _constructor; - private sealed class CustomTypeStruct : CustomType where TProperty : struct, INetSerializable + public FastCallClass(Func constructor) { _constructor = constructor; } + + public override void Read(TClass inf, NetDataReader r) { - public override FastCall Get() { return new FastCallStruct(); } + var p = _constructor(); + p.Deserialize(r); + Setter(inf, p); } - private sealed class CustomTypeClass : CustomType where TProperty : class, INetSerializable + public override void Write(TClass inf, NetDataWriter w) { - private readonly Func _constructor; - public CustomTypeClass(Func constructor) { _constructor = constructor; } - public override FastCall Get() { return new FastCallClass(_constructor); } + var p = Getter(inf); + if (p != null) + { + p.Serialize(w); + } } - private sealed class CustomTypeStatic : CustomType + public override void ReadList(TClass inf, NetDataReader r) { - private readonly Action _writer; - private readonly Func _reader; - public CustomTypeStatic(Action writer, Func reader) + var list = ReadListHelper(inf, r, out var len); + var listCount = list.Count; + for (var i = 0; i < len; i++) { - _writer = writer; - _reader = reader; + if (i < listCount) + { + list[i].Deserialize(r); + } + else + { + var itm = _constructor(); + itm.Deserialize(r); + list.Add(itm); + } + } + if (len < listCount) + { + list.RemoveRange(len, listCount - len); } - public override FastCall Get() { return new FastCallStatic(_writer, _reader); } } - /// - /// Register custom property type - /// - /// INetSerializable structure - public void RegisterNestedType() where T : struct, INetSerializable + public override void WriteList(TClass inf, NetDataWriter w) { - _registeredTypes.Add(typeof(T), new CustomTypeStruct()); + var list = WriteListHelper(inf, w, out var len); + for (var i = 0; i < len; i++) + { + list[i].Serialize(w); + } } - /// - /// Register custom property type - /// - /// INetSerializable class - public void RegisterNestedType(Func constructor) where T : class, INetSerializable + public override void ReadArray(TClass inf, NetDataReader r) { - _registeredTypes.Add(typeof(T), new CustomTypeClass(constructor)); + var arr = ReadArrayHelper(inf, r); + var len = arr.Length; + for (var i = 0; i < len; i++) + { + arr[i] = _constructor(); + arr[i].Deserialize(r); + } } - /// - /// Register custom property type - /// - /// Any packet - /// custom type writer - /// custom type reader - public void RegisterNestedType(Action writer, Func reader) + public override void WriteArray(TClass inf, NetDataWriter w) { - _registeredTypes.Add(typeof(T), new CustomTypeStatic(writer, reader)); + var arr = WriteArrayHelper(inf, w); + var len = arr.Length; + for (var i = 0; i < len; i++) + { + arr[i].Serialize(w); + } } + } + + private class IntSerializer : FastCallSpecific + { + public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetInt()); } + + public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } + + public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetIntArray()); } + + public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf)); } + } + + private class UIntSerializer : FastCallSpecific + { + public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetUInt()); } + + public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } + + public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetUIntArray()); } + + public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf)); } + } + + private class ShortSerializer : FastCallSpecific + { + public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetShort()); } + + public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } + + public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetShortArray()); } + + public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf)); } + } + + private class UShortSerializer : FastCallSpecific + { + public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetUShort()); } + + public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } + + public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetUShortArray()); } + + public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf)); } + } + + private class LongSerializer : FastCallSpecific + { + public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetLong()); } + + public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } + + public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetLongArray()); } + + public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf)); } + } + + private class ULongSerializer : FastCallSpecific + { + public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetULong()); } + + public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } + + public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetULongArray()); } + + public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf)); } + } + + private class ByteSerializer : FastCallSpecific + { + public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetByte()); } + + public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } + + public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetBytesWithLength()); } + + public override void WriteArray(T inf, NetDataWriter w) { w.PutBytesWithLength(GetterArr(inf)); } + } + + private class SByteSerializer : FastCallSpecific + { + public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetSByte()); } + + public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } + + public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetSBytesWithLength()); } + + public override void WriteArray(T inf, NetDataWriter w) { w.PutSBytesWithLength(GetterArr(inf)); } + } + + private class FloatSerializer : FastCallSpecific + { + public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetFloat()); } + + public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } + + public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetFloatArray()); } + + public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf)); } + } + + private class DoubleSerializer : FastCallSpecific + { + public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetDouble()); } + + public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } + + public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetDoubleArray()); } + + public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf)); } + } + + private class BoolSerializer : FastCallSpecific + { + public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetBool()); } + + public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf)); } + + public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetBoolArray()); } + + public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf)); } + } + + private class CharSerializer : FastCallSpecificAuto + { + protected override void ElementWrite(NetDataWriter w, ref char prop) { w.Put(prop); } + + protected override void ElementRead(NetDataReader r, out char prop) { prop = r.GetChar(); } + } + + private class IPEndPointSerializer : FastCallSpecificAuto + { + protected override void ElementWrite(NetDataWriter w, ref IPEndPoint prop) { w.Put(prop); } + + protected override void ElementRead(NetDataReader r, out IPEndPoint prop) { prop = r.GetNetEndPoint(); } + } + + private class StringSerializer : FastCallSpecific + { + private readonly int _maxLength; + + public StringSerializer(int maxLength) { _maxLength = maxLength > 0 ? maxLength : short.MaxValue; } - private NetDataWriter _writer; - private readonly int _maxStringLength; - private readonly Dictionary _registeredTypes = new Dictionary(); + public override void Read(T inf, NetDataReader r) { Setter(inf, r.GetString(_maxLength)); } - public NetSerializer() : this(0) + public override void Write(T inf, NetDataWriter w) { w.Put(Getter(inf), _maxLength); } + + public override void ReadArray(T inf, NetDataReader r) { SetterArr(inf, r.GetStringArray(_maxLength)); } + + public override void WriteArray(T inf, NetDataWriter w) { w.PutArray(GetterArr(inf), _maxLength); } + } + + private class EnumByteSerializer : FastCall + { + protected readonly PropertyInfo Property; + protected readonly Type PropertyType; + + public EnumByteSerializer(PropertyInfo property, Type propertyType) { + Property = property; + PropertyType = propertyType; } - public NetSerializer(int maxStringLength) + public override void Read(T inf, NetDataReader r) { - _maxStringLength = maxStringLength; + Property.SetValue(inf, Enum.ToObject(PropertyType, r.GetByte()), null); } - private ClassInfo RegisterInternal() + public override void Write(T inf, NetDataWriter w) { w.Put((byte)Property.GetValue(inf, null)); } + + public override void ReadArray(T inf, NetDataReader r) { throw new InvalidTypeException("Unsupported type: Enum[]"); } + + public override void WriteArray(T inf, NetDataWriter w) { throw new InvalidTypeException("Unsupported type: Enum[]"); } + + public override void ReadList(T inf, NetDataReader r) { - if (ClassInfo.Instance != null) - { - return ClassInfo.Instance; - } + throw new InvalidTypeException("Unsupported type: List"); + } - Type t = typeof(T); - PropertyInfo[] props = t.GetProperties( - BindingFlags.Instance | - BindingFlags.Public | - BindingFlags.GetProperty | - BindingFlags.SetProperty); - List> serializers = new List>(); - for (int i = 0; i < props.Length; i++) - { - PropertyInfo property = props[i]; - Type propertyType = property.PropertyType; + public override void WriteList(T inf, NetDataWriter w) + { + throw new InvalidTypeException("Unsupported type: List"); + } + } - Type elementType = propertyType.IsArray ? propertyType.GetElementType() : propertyType; - CallType callType = propertyType.IsArray ? CallType.Array : CallType.Basic; + private class EnumIntSerializer : EnumByteSerializer + { + public EnumIntSerializer(PropertyInfo property, Type propertyType) : base(property, propertyType) { } - if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(List<>)) - { - elementType = propertyType.GetGenericArguments()[0]; - callType = CallType.List; - } + public override void Read(T inf, NetDataReader r) + { + Property.SetValue(inf, Enum.ToObject(PropertyType, r.GetInt()), null); + } - // Note from Cod: Required to get it to build - // TODO: Fix this - /*if (Attribute.IsDefined(property, typeof(IgnoreDataMemberAttribute))) - continue;*/ + public override void Write(T inf, NetDataWriter w) { w.Put((int)Property.GetValue(inf, null)); } + } - MethodInfo getMethod = property.GetGetMethod(); - MethodInfo setMethod = property.GetSetMethod(); - if (getMethod == null || setMethod == null) - { - continue; - } + private sealed class ClassInfo + { + public static ClassInfo Instance; + private readonly int _membersCount; + private readonly FastCall[] _serializers; - FastCall serialzer = null; - if (propertyType.IsEnum) - { - Type underlyingType = Enum.GetUnderlyingType(propertyType); - if (underlyingType == typeof(byte)) - { - serialzer = new EnumByteSerializer(property, propertyType); - } - else if (underlyingType == typeof(int)) - { - serialzer = new EnumIntSerializer(property, propertyType); - } - else - { - throw new InvalidTypeException("Not supported enum underlying type: " + underlyingType.Name); - } - } - else if (elementType == typeof(string)) - { - serialzer = new StringSerializer(_maxStringLength); - } - else if (elementType == typeof(bool)) - { - serialzer = new BoolSerializer(); - } - else if (elementType == typeof(byte)) - { - serialzer = new ByteSerializer(); - } - else if (elementType == typeof(sbyte)) - { - serialzer = new SByteSerializer(); - } - else if (elementType == typeof(short)) - { - serialzer = new ShortSerializer(); - } - else if (elementType == typeof(ushort)) - { - serialzer = new UShortSerializer(); - } - else if (elementType == typeof(int)) - { - serialzer = new IntSerializer(); - } - else if (elementType == typeof(uint)) - { - serialzer = new UIntSerializer(); - } - else if (elementType == typeof(long)) - { - serialzer = new LongSerializer(); - } - else if (elementType == typeof(ulong)) - { - serialzer = new ULongSerializer(); - } - else if (elementType == typeof(float)) - { - serialzer = new FloatSerializer(); - } - else if (elementType == typeof(double)) - { - serialzer = new DoubleSerializer(); - } - else if (elementType == typeof(char)) + public ClassInfo(List> serializers) + { + _membersCount = serializers.Count; + _serializers = serializers.ToArray(); + } + + public void Write(T obj, NetDataWriter writer) + { + for (var i = 0; i < _membersCount; i++) + { + var s = _serializers[i]; + if (s.Type == CallType.Basic) { - serialzer = new CharSerializer(); + s.Write(obj, writer); } - else if (elementType == typeof(IPEndPoint)) + else if (s.Type == CallType.Array) { - serialzer = new IPEndPointSerializer(); + s.WriteArray(obj, writer); } else { - _registeredTypes.TryGetValue(elementType, out CustomType customType); - if (customType != null) - { - serialzer = customType.Get(); - } + s.WriteList(obj, writer); } + } + } - if (serialzer != null) + public void Read(T obj, NetDataReader reader) + { + for (var i = 0; i < _membersCount; i++) + { + var s = _serializers[i]; + if (s.Type == CallType.Basic) + { + s.Read(obj, reader); + } + else if (s.Type == CallType.Array) { - serialzer.Init(getMethod, setMethod, callType); - serializers.Add(serialzer); + s.ReadArray(obj, reader); } else { - throw new InvalidTypeException("Unknown property type: " + propertyType.FullName); + s.ReadList(obj, reader); } } - ClassInfo.Instance = new ClassInfo(serializers); - return ClassInfo.Instance; } + } - /// 's fields are not supported, or it has no fields - public void Register() - { - RegisterInternal(); - } + private abstract class CustomType + { + public abstract FastCall Get(); + } - /// - /// Reads packet with known type - /// - /// NetDataReader with packet - /// Returns packet if packet in reader is matched type - /// 's fields are not supported, or it has no fields - public T Deserialize(NetDataReader reader) where T : class, new() - { - ClassInfo info = RegisterInternal(); - T result = new T(); - try - { - info.Read(result, reader); - } - catch - { - return null; - } - return result; - } + private sealed class CustomTypeStruct : CustomType where TProperty : struct, INetSerializable + { + public override FastCall Get() { return new FastCallStruct(); } + } - /// - /// Reads packet with known type (non alloc variant) - /// - /// NetDataReader with packet - /// Deserialization target - /// Returns true if packet in reader is matched type - /// 's fields are not supported, or it has no fields - public bool Deserialize(NetDataReader reader, T target) where T : class, new() - { - ClassInfo info = RegisterInternal(); - try - { - info.Read(target, reader); - } - catch - { - return false; - } - return true; - } + private sealed class CustomTypeClass : CustomType where TProperty : class, INetSerializable + { + private readonly Func _constructor; - /// - /// Serialize object to NetDataWriter (fast) - /// - /// Serialization target NetDataWriter - /// Object to serialize - /// 's fields are not supported, or it has no fields - public void Serialize(NetDataWriter writer, T obj) where T : class, new() - { - RegisterInternal().Write(obj, writer); - } + public CustomTypeClass(Func constructor) { _constructor = constructor; } - /// - /// Serialize object to byte array - /// - /// Object to serialize - /// byte array with serialized data - public byte[] Serialize(T obj) where T : class, new() - { - if (_writer == null) - { - _writer = new NetDataWriter(); - } + public override FastCall Get() { return new FastCallClass(_constructor); } + } + + private sealed class CustomTypeStatic : CustomType + { + private readonly Func _reader; + private readonly Action _writer; - _writer.Reset(); - Serialize(_writer, obj); - return _writer.CopyData(); + public CustomTypeStatic(Action writer, Func reader) + { + _writer = writer; + _reader = reader; } + + public override FastCall Get() { return new FastCallStatic(_writer, _reader); } } } diff --git a/NebulaModel/Networking/Serialization/NetUtils.cs b/NebulaModel/Networking/Serialization/NetUtils.cs index 41c28d598..bf8e44d59 100644 --- a/NebulaModel/Networking/Serialization/NetUtils.cs +++ b/NebulaModel/Networking/Serialization/NetUtils.cs @@ -1,179 +1,183 @@ -using System; +#region + +using System; using System.Collections.Generic; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; -namespace NebulaModel.Networking.Serialization +#endregion + +namespace NebulaModel.Networking.Serialization; + +/// +/// Address type that you want to receive from NetUtils.GetLocalIp method +/// +[Flags] +public enum LocalAddrType { - /// - /// Address type that you want to receive from NetUtils.GetLocalIp method - /// - [Flags] - public enum LocalAddrType + IPv4 = 1, + IPv6 = 2, + All = IPv4 | IPv6 +} + +/// +/// Some specific network utilities +/// +public static class NetUtils +{ + private static readonly List IpList = new(); + + public static IPEndPoint MakeEndPoint(string hostStr, int port) { - IPv4 = 1, - IPv6 = 2, - All = IPv4 | IPv6 + return new IPEndPoint(ResolveAddress(hostStr), port); } - /// - /// Some specific network utilities - /// - public static class NetUtils + public static IPAddress ResolveAddress(string hostStr) { - public static IPEndPoint MakeEndPoint(string hostStr, int port) + if (hostStr == "localhost") { - return new IPEndPoint(ResolveAddress(hostStr), port); + return IPAddress.Loopback; } - public static IPAddress ResolveAddress(string hostStr) + if (!IPAddress.TryParse(hostStr, out var ipAddress)) { - if (hostStr == "localhost") - { - return IPAddress.Loopback; - } - - if (!IPAddress.TryParse(hostStr, out IPAddress ipAddress)) - { - // We can assume true because the version of unity is new enough (2018.4) - //if (NetSocket.IPv6Support) - ipAddress = ResolveAddress(hostStr, AddressFamily.InterNetworkV6); - if (ipAddress == null) - { - ipAddress = ResolveAddress(hostStr, AddressFamily.InterNetwork); - } - } + // We can assume true because the version of unity is new enough (2018.4) + //if (NetSocket.IPv6Support) + ipAddress = ResolveAddress(hostStr, AddressFamily.InterNetworkV6); if (ipAddress == null) { - throw new ArgumentException("Invalid address: " + hostStr); + ipAddress = ResolveAddress(hostStr, AddressFamily.InterNetwork); } - - return ipAddress; } + if (ipAddress == null) + { + throw new ArgumentException("Invalid address: " + hostStr); + } + + return ipAddress; + } - private static IPAddress ResolveAddress(string hostStr, AddressFamily addressFamily) + private static IPAddress ResolveAddress(string hostStr, AddressFamily addressFamily) + { + var addresses = ResolveAddresses(hostStr); + foreach (var ip in addresses) { - IPAddress[] addresses = ResolveAddresses(hostStr); - foreach (IPAddress ip in addresses) + if (ip.AddressFamily == addressFamily) { - if (ip.AddressFamily == addressFamily) - { - return ip; - } + return ip; } - return null; } + return null; + } - private static IPAddress[] ResolveAddresses(string hostStr) - { + private static IPAddress[] ResolveAddresses(string hostStr) + { #if NETSTANDARD || NETCOREAPP var hostTask = Dns.GetHostEntryAsync(hostStr); hostTask.GetAwaiter().GetResult(); var host = hostTask.Result; #else - IPHostEntry host = Dns.GetHostEntry(hostStr); + var host = Dns.GetHostEntry(hostStr); #endif - return host.AddressList; - } + return host.AddressList; + } - /// - /// Get all local ip addresses - /// - /// type of address (IPv4, IPv6 or both) - /// List with all local ip addresses - public static List GetLocalIpList(LocalAddrType addrType) - { - List targetList = new List(); - GetLocalIpList(targetList, addrType); - return targetList; - } + /// + /// Get all local ip addresses + /// + /// type of address (IPv4, IPv6 or both) + /// List with all local ip addresses + public static List GetLocalIpList(LocalAddrType addrType) + { + var targetList = new List(); + GetLocalIpList(targetList, addrType); + return targetList; + } - /// - /// Get all local ip addresses (non alloc version) - /// - /// result list - /// type of address (IPv4, IPv6 or both) - public static void GetLocalIpList(IList targetList, LocalAddrType addrType) + /// + /// Get all local ip addresses (non alloc version) + /// + /// result list + /// type of address (IPv4, IPv6 or both) + public static void GetLocalIpList(IList targetList, LocalAddrType addrType) + { + var ipv4 = (addrType & LocalAddrType.IPv4) == LocalAddrType.IPv4; + var ipv6 = (addrType & LocalAddrType.IPv6) == LocalAddrType.IPv6; + try { - bool ipv4 = (addrType & LocalAddrType.IPv4) == LocalAddrType.IPv4; - bool ipv6 = (addrType & LocalAddrType.IPv6) == LocalAddrType.IPv6; - try + foreach (var ni in NetworkInterface.GetAllNetworkInterfaces()) { - foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) + //Skip loopback and disabled network interfaces + if (ni.NetworkInterfaceType == NetworkInterfaceType.Loopback || + ni.OperationalStatus != OperationalStatus.Up) { - //Skip loopback and disabled network interfaces - if (ni.NetworkInterfaceType == NetworkInterfaceType.Loopback || - ni.OperationalStatus != OperationalStatus.Up) - { - continue; - } + continue; + } - IPInterfaceProperties ipProps = ni.GetIPProperties(); + var ipProps = ni.GetIPProperties(); - //Skip address without gateway - if (ipProps.GatewayAddresses.Count == 0) - { - continue; - } + //Skip address without gateway + if (ipProps.GatewayAddresses.Count == 0) + { + continue; + } - foreach (UnicastIPAddressInformation ip in ipProps.UnicastAddresses) + foreach (var ip in ipProps.UnicastAddresses) + { + var address = ip.Address; + if (ipv4 && address.AddressFamily == AddressFamily.InterNetwork || + ipv6 && address.AddressFamily == AddressFamily.InterNetworkV6) { - IPAddress address = ip.Address; - if ((ipv4 && address.AddressFamily == AddressFamily.InterNetwork) || - (ipv6 && address.AddressFamily == AddressFamily.InterNetworkV6)) - { - targetList.Add(address.ToString()); - } + targetList.Add(address.ToString()); } } } - catch - { - //ignored - } + } + catch + { + //ignored + } - //Fallback mode (unity android) - if (targetList.Count == 0) + //Fallback mode (unity android) + if (targetList.Count == 0) + { + var addresses = ResolveAddresses(Dns.GetHostName()); + foreach (var ip in addresses) { - IPAddress[] addresses = ResolveAddresses(Dns.GetHostName()); - foreach (IPAddress ip in addresses) + if (ipv4 && ip.AddressFamily == AddressFamily.InterNetwork || + ipv6 && ip.AddressFamily == AddressFamily.InterNetworkV6) { - if ((ipv4 && ip.AddressFamily == AddressFamily.InterNetwork) || - (ipv6 && ip.AddressFamily == AddressFamily.InterNetworkV6)) - { - targetList.Add(ip.ToString()); - } + targetList.Add(ip.ToString()); } } - if (targetList.Count == 0) + } + if (targetList.Count == 0) + { + if (ipv4) { - if (ipv4) - { - targetList.Add("127.0.0.1"); - } + targetList.Add("127.0.0.1"); + } - if (ipv6) - { - targetList.Add("::1"); - } + if (ipv6) + { + targetList.Add("::1"); } } + } - private static readonly List IpList = new List(); - /// - /// Get first detected local ip address - /// - /// type of address (IPv4, IPv6 or both) - /// IP address if available. Else - string.Empty - public static string GetLocalIp(LocalAddrType addrType) + /// + /// Get first detected local ip address + /// + /// type of address (IPv4, IPv6 or both) + /// IP address if available. Else - string.Empty + public static string GetLocalIp(LocalAddrType addrType) + { + lock (IpList) { - lock (IpList) - { - IpList.Clear(); - GetLocalIpList(IpList, addrType); - return IpList.Count == 0 ? string.Empty : IpList[0]; - } + IpList.Clear(); + GetLocalIpList(IpList, addrType); + return IpList.Count == 0 ? string.Empty : IpList[0]; } } } diff --git a/NebulaModel/Packets/Chat/ChatCommandWhisperPacket.cs b/NebulaModel/Packets/Chat/ChatCommandWhisperPacket.cs index 9c08d7377..760ef085b 100644 --- a/NebulaModel/Packets/Chat/ChatCommandWhisperPacket.cs +++ b/NebulaModel/Packets/Chat/ChatCommandWhisperPacket.cs @@ -1,18 +1,17 @@ -namespace NebulaModel.Packets.Players -{ - public class ChatCommandWhisperPacket - { - public string SenderUsername { get; set; } - public string RecipientUsername { get; set; } - public string Message { get; set; } +namespace NebulaModel.Packets.Players; - public ChatCommandWhisperPacket() { } +public class ChatCommandWhisperPacket +{ + public ChatCommandWhisperPacket() { } - public ChatCommandWhisperPacket(string sender, string recipient, string message) - { - SenderUsername = sender; - RecipientUsername = recipient; - Message = message; - } + public ChatCommandWhisperPacket(string sender, string recipient, string message) + { + SenderUsername = sender; + RecipientUsername = recipient; + Message = message; } -} \ No newline at end of file + + public string SenderUsername { get; set; } + public string RecipientUsername { get; set; } + public string Message { get; set; } +} diff --git a/NebulaModel/Packets/Chat/ChatCommandWhoPacket.cs b/NebulaModel/Packets/Chat/ChatCommandWhoPacket.cs index 72bcf07bb..6dabe78de 100644 --- a/NebulaModel/Packets/Chat/ChatCommandWhoPacket.cs +++ b/NebulaModel/Packets/Chat/ChatCommandWhoPacket.cs @@ -1,22 +1,21 @@ -namespace NebulaModel.Packets.Players -{ - public class ChatCommandWhoPacket - { - public bool IsRequest { get; set; } - public string ResponsePayload { get; set; } +namespace NebulaModel.Packets.Players; - public ChatCommandWhoPacket() { } +public class ChatCommandWhoPacket +{ + public ChatCommandWhoPacket() { } - public ChatCommandWhoPacket(bool isRequest, string responsePayload) - { - IsRequest = isRequest; + public ChatCommandWhoPacket(bool isRequest, string responsePayload) + { + IsRequest = isRequest; #if DEBUG - if (!isRequest) - { - Assert.False(string.IsNullOrEmpty(responsePayload)); - } -#endif - ResponsePayload = responsePayload; + if (!isRequest) + { + Assert.False(string.IsNullOrEmpty(responsePayload)); } +#endif + ResponsePayload = responsePayload; } -} \ No newline at end of file + + public bool IsRequest { get; set; } + public string ResponsePayload { get; set; } +} diff --git a/NebulaModel/Packets/Chat/NewChatMessagePacket.cs b/NebulaModel/Packets/Chat/NewChatMessagePacket.cs index 1283dc3bb..dfa44c3f5 100644 --- a/NebulaModel/Packets/Chat/NewChatMessagePacket.cs +++ b/NebulaModel/Packets/Chat/NewChatMessagePacket.cs @@ -1,23 +1,26 @@ -using NebulaModel.DataStructures; +#region + using System; +using NebulaModel.DataStructures; -namespace NebulaModel.Packets.Players -{ - public class NewChatMessagePacket - { - public ChatMessageType MessageType { get; set; } - public string MessageText { get; set; } - public long SentAt { get; set; } - public string UserName { get; set; } +#endregion - public NewChatMessagePacket() { } +namespace NebulaModel.Packets.Players; - public NewChatMessagePacket(ChatMessageType messageType, string messageText, DateTime sentAt, string userName) - { - MessageType = messageType; - MessageText = messageText; - SentAt = sentAt.ToBinary(); - UserName = userName; - } +public class NewChatMessagePacket +{ + public NewChatMessagePacket() { } + + public NewChatMessagePacket(ChatMessageType messageType, string messageText, DateTime sentAt, string userName) + { + MessageType = messageType; + MessageText = messageText; + SentAt = sentAt.ToBinary(); + UserName = userName; } -} \ No newline at end of file + + public ChatMessageType MessageType { get; set; } + public string MessageText { get; set; } + public long SentAt { get; set; } + public string UserName { get; set; } +} diff --git a/NebulaModel/Packets/Chat/RemoteServerCommandPacket.cs b/NebulaModel/Packets/Chat/RemoteServerCommandPacket.cs index 7f096837a..07bac6d29 100644 --- a/NebulaModel/Packets/Chat/RemoteServerCommandPacket.cs +++ b/NebulaModel/Packets/Chat/RemoteServerCommandPacket.cs @@ -1,25 +1,24 @@ -namespace NebulaModel.Packets.Players -{ - public class RemoteServerCommandPacket - { - public RemoteServerCommand Command { get; set; } - public string Content { get; set; } - - public RemoteServerCommandPacket () {} +namespace NebulaModel.Packets.Players; - public RemoteServerCommandPacket(RemoteServerCommand comand, string content) - { - Command = comand; - Content = content; - } - } +public class RemoteServerCommandPacket +{ + public RemoteServerCommandPacket() { } - public enum RemoteServerCommand + public RemoteServerCommandPacket(RemoteServerCommand comand, string content) { - Login, - ServerList, - ServerSave, - ServerLoad, - ServerInfo + Command = comand; + Content = content; } + + public RemoteServerCommand Command { get; set; } + public string Content { get; set; } +} + +public enum RemoteServerCommand +{ + Login, + ServerList, + ServerSave, + ServerLoad, + ServerInfo } diff --git a/NebulaModel/Packets/Factory/Assembler/AssemblerRecipeEventPacket.cs b/NebulaModel/Packets/Factory/Assembler/AssemblerRecipeEventPacket.cs index c7290e93f..baa63448e 100644 --- a/NebulaModel/Packets/Factory/Assembler/AssemblerRecipeEventPacket.cs +++ b/NebulaModel/Packets/Factory/Assembler/AssemblerRecipeEventPacket.cs @@ -1,18 +1,17 @@ -namespace NebulaModel.Packets.Factory.Assembler -{ - public class AssemblerRecipeEventPacket - { - public int PlanetId { get; set; } - public int AssemblerIndex { get; set; } - public int RecipeId { get; set; } +namespace NebulaModel.Packets.Factory.Assembler; - public AssemblerRecipeEventPacket() { } +public class AssemblerRecipeEventPacket +{ + public AssemblerRecipeEventPacket() { } - public AssemblerRecipeEventPacket(int planetId, int assemblerIndex, int recipeId) - { - PlanetId = planetId; - AssemblerIndex = assemblerIndex; - RecipeId = recipeId; - } + public AssemblerRecipeEventPacket(int planetId, int assemblerIndex, int recipeId) + { + PlanetId = planetId; + AssemblerIndex = assemblerIndex; + RecipeId = recipeId; } + + public int PlanetId { get; set; } + public int AssemblerIndex { get; set; } + public int RecipeId { get; set; } } diff --git a/NebulaModel/Packets/Factory/Assembler/AssemblerUpdateProducesPacket.cs b/NebulaModel/Packets/Factory/Assembler/AssemblerUpdateProducesPacket.cs index ab4f663fa..655c832e5 100644 --- a/NebulaModel/Packets/Factory/Assembler/AssemblerUpdateProducesPacket.cs +++ b/NebulaModel/Packets/Factory/Assembler/AssemblerUpdateProducesPacket.cs @@ -1,19 +1,19 @@ -namespace NebulaModel.Packets.Factory.Assembler +namespace NebulaModel.Packets.Factory.Assembler; + +public class AssemblerUpdateProducesPacket { - public class AssemblerUpdateProducesPacket - { - public int PlanetId { get; set; } - public int AssemblerIndex { get; set; } - public int ProducesIndex { get; set; } - public int ProducesValue { get; set; } + public AssemblerUpdateProducesPacket() { } - public AssemblerUpdateProducesPacket() { } - public AssemblerUpdateProducesPacket(int producesIndex, int producesValue, int planetId, int assemblerIndex) - { - PlanetId = planetId; - AssemblerIndex = assemblerIndex; - ProducesIndex = producesIndex; - ProducesValue = producesValue; - } + public AssemblerUpdateProducesPacket(int producesIndex, int producesValue, int planetId, int assemblerIndex) + { + PlanetId = planetId; + AssemblerIndex = assemblerIndex; + ProducesIndex = producesIndex; + ProducesValue = producesValue; } + + public int PlanetId { get; set; } + public int AssemblerIndex { get; set; } + public int ProducesIndex { get; set; } + public int ProducesValue { get; set; } } diff --git a/NebulaModel/Packets/Factory/Assembler/AssemblerUpdateStoragePacket.cs b/NebulaModel/Packets/Factory/Assembler/AssemblerUpdateStoragePacket.cs index 5d5e41f0e..2133be98c 100644 --- a/NebulaModel/Packets/Factory/Assembler/AssemblerUpdateStoragePacket.cs +++ b/NebulaModel/Packets/Factory/Assembler/AssemblerUpdateStoragePacket.cs @@ -1,18 +1,19 @@ -namespace NebulaModel.Packets.Factory.Assembler +namespace NebulaModel.Packets.Factory.Assembler; + +public class AssemblerUpdateStoragePacket { - public class AssemblerUpdateStoragePacket + public AssemblerUpdateStoragePacket() { } + + public AssemblerUpdateStoragePacket(int planetId, int assemblerIndex, int[] served, int[] incServed) { - public int PlanetId { get; set; } - public int AssemblerIndex { get; set; } - public int[] Served { get; set; } - public int[] IncServed { get; set; } - public AssemblerUpdateStoragePacket() { } - public AssemblerUpdateStoragePacket(int planetId, int assemblerIndex, int[] served, int[] incServed) - { - PlanetId = planetId; - AssemblerIndex = assemblerIndex; - Served = served; - IncServed = incServed; - } + PlanetId = planetId; + AssemblerIndex = assemblerIndex; + Served = served; + IncServed = incServed; } + + public int PlanetId { get; set; } + public int AssemblerIndex { get; set; } + public int[] Served { get; set; } + public int[] IncServed { get; set; } } diff --git a/NebulaModel/Packets/Factory/Belt/BeltReversePacket.cs b/NebulaModel/Packets/Factory/Belt/BeltReversePacket.cs index a83c8459c..65b03329c 100644 --- a/NebulaModel/Packets/Factory/Belt/BeltReversePacket.cs +++ b/NebulaModel/Packets/Factory/Belt/BeltReversePacket.cs @@ -1,15 +1,15 @@ -namespace NebulaModel.Packets.Factory.Belt +namespace NebulaModel.Packets.Factory.Belt; + +public class BeltReversePacket { - public class BeltReversePacket - { - public int BeltId { get; set; } - public int PlanetId { get; set; } + public BeltReversePacket() { } - public BeltReversePacket() { } - public BeltReversePacket(int beltId, int planetId) - { - BeltId = beltId; - PlanetId = planetId; - } + public BeltReversePacket(int beltId, int planetId) + { + BeltId = beltId; + PlanetId = planetId; } + + public int BeltId { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Factory/Belt/BeltSignalIconPacket.cs b/NebulaModel/Packets/Factory/Belt/BeltSignalIconPacket.cs index 634b601c0..3d1e996c2 100644 --- a/NebulaModel/Packets/Factory/Belt/BeltSignalIconPacket.cs +++ b/NebulaModel/Packets/Factory/Belt/BeltSignalIconPacket.cs @@ -1,17 +1,17 @@ -namespace NebulaModel.Packets.Factory.Belt +namespace NebulaModel.Packets.Factory.Belt; + +public class BeltSignalIconPacket { - public class BeltSignalIconPacket - { - public int EntityId { get; set; } - public int SignalId { get; set; } - public int PlanetId { get; set; } + public BeltSignalIconPacket() { } - public BeltSignalIconPacket() { } - public BeltSignalIconPacket(int entityId, int signalId, int planetId) - { - EntityId = entityId; - SignalId = signalId; - PlanetId = planetId; - } + public BeltSignalIconPacket(int entityId, int signalId, int planetId) + { + EntityId = entityId; + SignalId = signalId; + PlanetId = planetId; } + + public int EntityId { get; set; } + public int SignalId { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Factory/Belt/BeltSignalNumberPacket.cs b/NebulaModel/Packets/Factory/Belt/BeltSignalNumberPacket.cs index 492fc0707..43120306b 100644 --- a/NebulaModel/Packets/Factory/Belt/BeltSignalNumberPacket.cs +++ b/NebulaModel/Packets/Factory/Belt/BeltSignalNumberPacket.cs @@ -1,17 +1,17 @@ -namespace NebulaModel.Packets.Factory.Belt +namespace NebulaModel.Packets.Factory.Belt; + +public class BeltSignalNumberPacket { - public class BeltSignalNumberPacket - { - public int EntityId { get; set; } - public float Number { get; set; } - public int PlanetId { get; set; } + public BeltSignalNumberPacket() { } - public BeltSignalNumberPacket() { } - public BeltSignalNumberPacket(int entityId, float number, int planetId) - { - EntityId = entityId; - Number = number; - PlanetId = planetId; - } + public BeltSignalNumberPacket(int entityId, float number, int planetId) + { + EntityId = entityId; + Number = number; + PlanetId = planetId; } + + public int EntityId { get; set; } + public float Number { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Factory/Belt/BeltUpdatePickupItemsPacket.cs b/NebulaModel/Packets/Factory/Belt/BeltUpdatePickupItemsPacket.cs index af0e8c993..df0ec229b 100644 --- a/NebulaModel/Packets/Factory/Belt/BeltUpdatePickupItemsPacket.cs +++ b/NebulaModel/Packets/Factory/Belt/BeltUpdatePickupItemsPacket.cs @@ -1,47 +1,50 @@ -using NebulaAPI; +#region -namespace NebulaModel.Packets.Factory.Belt +using NebulaAPI; + +#endregion + +namespace NebulaModel.Packets.Factory.Belt; + +public class BeltUpdatePickupItemsPacket { - public class BeltUpdatePickupItemsPacket + public BeltUpdatePickupItemsPacket() { } + + public BeltUpdatePickupItemsPacket(BeltUpdate[] beltUpdates, int planetId) { - public int PlanetId { get; set; } - public BeltUpdate[] BeltUpdates { get; set; } + BeltUpdates = beltUpdates; + PlanetId = planetId; + } + + public int PlanetId { get; set; } + public BeltUpdate[] BeltUpdates { get; set; } +} + +[RegisterNestedType] +public struct BeltUpdate : INetSerializable +{ + public int ItemId { get; set; } + public int Count { get; set; } + public int BeltId { get; set; } - public BeltUpdatePickupItemsPacket() { } + public BeltUpdate(int itemId, int count, int beltId) + { + ItemId = itemId; + Count = count; + BeltId = beltId; + } - public BeltUpdatePickupItemsPacket(BeltUpdate[] beltUpdates, int planetId) - { - BeltUpdates = beltUpdates; - PlanetId = planetId; - } + public void Serialize(INetDataWriter writer) + { + writer.Put(ItemId); + writer.Put(Count); + writer.Put(BeltId); } - [RegisterNestedType] - public struct BeltUpdate : INetSerializable + public void Deserialize(INetDataReader reader) { - public int ItemId { get; set; } - public int Count { get; set; } - public int BeltId { get; set; } - - public BeltUpdate(int itemId, int count, int beltId) - { - ItemId = itemId; - Count = count; - BeltId = beltId; - } - - public void Serialize(INetDataWriter writer) - { - writer.Put(ItemId); - writer.Put(Count); - writer.Put(BeltId); - } - - public void Deserialize(INetDataReader reader) - { - ItemId = reader.GetInt(); - Count = reader.GetInt(); - BeltId = reader.GetInt(); - } + ItemId = reader.GetInt(); + Count = reader.GetInt(); + BeltId = reader.GetInt(); } } diff --git a/NebulaModel/Packets/Factory/Belt/BeltUpdatePutItemOnPacket.cs b/NebulaModel/Packets/Factory/Belt/BeltUpdatePutItemOnPacket.cs index 6f631d8f4..bc896d771 100644 --- a/NebulaModel/Packets/Factory/Belt/BeltUpdatePutItemOnPacket.cs +++ b/NebulaModel/Packets/Factory/Belt/BeltUpdatePutItemOnPacket.cs @@ -1,20 +1,21 @@ -namespace NebulaModel.Packets.Factory.Belt +namespace NebulaModel.Packets.Factory.Belt; + +public class BeltUpdatePutItemOnPacket { - public class BeltUpdatePutItemOnPacket + public BeltUpdatePutItemOnPacket() { } + + public BeltUpdatePutItemOnPacket(int beltId, int itemId, byte itemCount, byte itemInc, int planetId) { - public int BeltId { get; set; } - public int ItemId { get; set; } - public byte ItemCount { get; set; } - public byte ItemInc { get; set; } - public int PlanetId { get; set; } - public BeltUpdatePutItemOnPacket() { } - public BeltUpdatePutItemOnPacket(int beltId, int itemId, byte itemCount, byte itemInc, int planetId) - { - BeltId = beltId; - ItemId = itemId; - ItemCount = itemCount; - ItemInc = itemInc; - PlanetId = planetId; - } + BeltId = beltId; + ItemId = itemId; + ItemCount = itemCount; + ItemInc = itemInc; + PlanetId = planetId; } + + public int BeltId { get; set; } + public int ItemId { get; set; } + public byte ItemCount { get; set; } + public byte ItemInc { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Factory/Belt/ConnectToMonitorPacket.cs b/NebulaModel/Packets/Factory/Belt/ConnectToMonitorPacket.cs index ac3e45cef..cbdf546d0 100644 --- a/NebulaModel/Packets/Factory/Belt/ConnectToMonitorPacket.cs +++ b/NebulaModel/Packets/Factory/Belt/ConnectToMonitorPacket.cs @@ -1,19 +1,19 @@ -namespace NebulaModel.Packets.Factory.Belt +namespace NebulaModel.Packets.Factory.Belt; + +public class ConnectToMonitorPacket { - public class ConnectToMonitorPacket - { - public int MonitorId { get; set; } - public int BeltId { get; set; } - public int Offset { get; set; } - public int PlanetId { get; set; } + public ConnectToMonitorPacket() { } - public ConnectToMonitorPacket() { } - public ConnectToMonitorPacket(int monitorId, int beltId, int offset, int planetId) - { - MonitorId = monitorId; - BeltId = beltId; - Offset = offset; - PlanetId = planetId; - } + public ConnectToMonitorPacket(int monitorId, int beltId, int offset, int planetId) + { + MonitorId = monitorId; + BeltId = beltId; + Offset = offset; + PlanetId = planetId; } + + public int MonitorId { get; set; } + public int BeltId { get; set; } + public int Offset { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Factory/Belt/ConnectToSpraycoaterPacket.cs b/NebulaModel/Packets/Factory/Belt/ConnectToSpraycoaterPacket.cs index fe82f1d21..44c2bf509 100644 --- a/NebulaModel/Packets/Factory/Belt/ConnectToSpraycoaterPacket.cs +++ b/NebulaModel/Packets/Factory/Belt/ConnectToSpraycoaterPacket.cs @@ -1,19 +1,19 @@ -namespace NebulaModel.Packets.Factory.Belt +namespace NebulaModel.Packets.Factory.Belt; + +public class ConnectToSpraycoaterPacket { - public class ConnectToSpraycoaterPacket - { - public int SpraycoaterId { get; set; } - public int CargoBeltId { get; set; } - public int IncBeltId { get; set; } - public int PlanetId { get; set; } + public ConnectToSpraycoaterPacket() { } - public ConnectToSpraycoaterPacket() { } - public ConnectToSpraycoaterPacket(int spraycoaterId, int cargoBeltId, int incBeltId, int planetId) - { - SpraycoaterId = spraycoaterId; - CargoBeltId = cargoBeltId; - IncBeltId = incBeltId; - PlanetId = planetId; - } + public ConnectToSpraycoaterPacket(int spraycoaterId, int cargoBeltId, int incBeltId, int planetId) + { + SpraycoaterId = spraycoaterId; + CargoBeltId = cargoBeltId; + IncBeltId = incBeltId; + PlanetId = planetId; } + + public int SpraycoaterId { get; set; } + public int CargoBeltId { get; set; } + public int IncBeltId { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Factory/BuildEntityRequest.cs b/NebulaModel/Packets/Factory/BuildEntityRequest.cs index 4b3d43310..478e8f2e1 100644 --- a/NebulaModel/Packets/Factory/BuildEntityRequest.cs +++ b/NebulaModel/Packets/Factory/BuildEntityRequest.cs @@ -1,19 +1,19 @@ -namespace NebulaModel.Packets.Factory +namespace NebulaModel.Packets.Factory; + +public class BuildEntityRequest { - public class BuildEntityRequest - { - public int PlanetId { get; set; } - public int PrebuildId { get; set; } - public int AuthorId { get; set; } - public int EntityId { get; set; } + public BuildEntityRequest() { } - public BuildEntityRequest() { } - public BuildEntityRequest(int planetId, int prebuildId, int authorId, int entityId) - { - PlanetId = planetId; - PrebuildId = prebuildId; - AuthorId = authorId; - EntityId = entityId; - } + public BuildEntityRequest(int planetId, int prebuildId, int authorId, int entityId) + { + PlanetId = planetId; + PrebuildId = prebuildId; + AuthorId = authorId; + EntityId = entityId; } + + public int PlanetId { get; set; } + public int PrebuildId { get; set; } + public int AuthorId { get; set; } + public int EntityId { get; set; } } diff --git a/NebulaModel/Packets/Factory/CreatePrebuildsRequest.cs b/NebulaModel/Packets/Factory/CreatePrebuildsRequest.cs index c8e186507..fc699f62b 100644 --- a/NebulaModel/Packets/Factory/CreatePrebuildsRequest.cs +++ b/NebulaModel/Packets/Factory/CreatePrebuildsRequest.cs @@ -1,289 +1,289 @@ -using NebulaModel.Networking; +#region + using System.Collections.Generic; using System.IO; +using NebulaModel.Networking; using UnityEngine; -namespace NebulaModel.Packets.Factory -{ - public class CreatePrebuildsRequest - { - public int PlanetId { get; set; } - public byte[] BuildPreviewData { get; set; } - public int AuthorId { get; set; } - public string BuildToolType { get; set; } - public int PrebuildId { get; set; } +#endregion - public CreatePrebuildsRequest() { } +namespace NebulaModel.Packets.Factory; - public CreatePrebuildsRequest(int planetId, List buildPreviews, int playerId, string buildToolType, int prebuildId) +public class CreatePrebuildsRequest +{ + public CreatePrebuildsRequest() { } + + public CreatePrebuildsRequest(int planetId, List buildPreviews, int playerId, string buildToolType, + int prebuildId) + { + AuthorId = playerId; + PlanetId = planetId; + BuildToolType = buildToolType; + using (var writer = new BinaryUtils.Writer()) { - AuthorId = playerId; - PlanetId = planetId; - BuildToolType = buildToolType; - using (BinaryUtils.Writer writer = new BinaryUtils.Writer()) + writer.BinaryWriter.Write(buildPreviews.Count); + for (var i = 0; i < buildPreviews.Count; i++) { - writer.BinaryWriter.Write(buildPreviews.Count); - for (int i = 0; i < buildPreviews.Count; i++) - { - SerializeBuildPreview(buildPreviews[i], buildPreviews, writer.BinaryWriter); - } - BuildPreviewData = writer.CloseAndGetBytes(); + SerializeBuildPreview(buildPreviews[i], buildPreviews, writer.BinaryWriter); } - PrebuildId = prebuildId; + BuildPreviewData = writer.CloseAndGetBytes(); } + PrebuildId = prebuildId; + } - public List GetBuildPreviews() - { - List result = new List(); + public int PlanetId { get; set; } + public byte[] BuildPreviewData { get; set; } + public int AuthorId { get; set; } + public string BuildToolType { get; set; } + public int PrebuildId { get; set; } - using (BinaryUtils.Reader reader = new BinaryUtils.Reader(BuildPreviewData)) - { - int previewCount = reader.BinaryReader.ReadInt32(); - for (int i = 0; i < previewCount; i++) - { - result.Add(new BuildPreview()); - } - for (int i = 0; i < previewCount; i++) - { - DeserializeBuildPreview(result[i], result, reader.BinaryReader); - } - } - return result; - } + public List GetBuildPreviews() + { + var result = new List(); - private static void DeserializeBuildPreview(BuildPreview buildPreview, List list, BinaryReader br) + using (var reader = new BinaryUtils.Reader(BuildPreviewData)) { - int outputRef = br.ReadInt32(); - buildPreview.output = outputRef == -1 ? null : list[outputRef]; - int inputRef = br.ReadInt32(); - buildPreview.input = inputRef == -1 ? null : list[inputRef]; - buildPreview.objId = br.ReadInt32(); - int num = br.ReadInt32(); - buildPreview.nearestPowerObjId = num == 0 ? null : new int[num]; - for (int i = 0; i < num; i++) - { - buildPreview.nearestPowerObjId[i] = br.ReadInt32(); - } - buildPreview.coverObjId = br.ReadInt32(); - buildPreview.willRemoveCover = br.ReadBoolean(); - buildPreview.genNearColliderArea2 = br.ReadSingle(); - buildPreview.outputObjId = br.ReadInt32(); - buildPreview.inputObjId = br.ReadInt32(); - buildPreview.outputToSlot = br.ReadInt32(); - buildPreview.inputFromSlot = br.ReadInt32(); - buildPreview.outputFromSlot = br.ReadInt32(); - buildPreview.inputToSlot = br.ReadInt32(); - buildPreview.outputOffset = br.ReadInt32(); - buildPreview.inputOffset = br.ReadInt32(); - buildPreview.needModel = br.ReadBoolean(); - buildPreview.previewIndex = br.ReadInt32(); - buildPreview.bpgpuiModelId = br.ReadInt32(); - buildPreview.bpgpuiModelInstIndex = br.ReadInt32(); - buildPreview.recipeId = br.ReadInt32(); - buildPreview.filterId = br.ReadInt32(); - buildPreview.isConnNode = br.ReadBoolean(); - buildPreview.desc = new PrefabDesc + var previewCount = reader.BinaryReader.ReadInt32(); + for (var i = 0; i < previewCount; i++) { - //Import more data about the Prefab to properly validate the build condition on server-side - assemblerRecipeType = (ERecipeType)br.ReadInt32(), - cullingHeight = br.ReadSingle(), - gammaRayReceiver = br.ReadBoolean(), - inserterSTT = br.ReadInt32(), - isAccumulator = br.ReadBoolean(), - isAssembler = br.ReadBoolean(), - isBelt = br.ReadBoolean(), - isCollectStation = br.ReadBoolean(), - isDispenser = br.ReadBoolean(), - isEjector = br.ReadBoolean(), - isFractionator = br.ReadBoolean(), - isInserter = br.ReadBoolean(), - isLab = br.ReadBoolean(), - isPowerExchanger = br.ReadBoolean(), - isSplitter = br.ReadBoolean(), - isStation = br.ReadBoolean(), - isStellarStation = br.ReadBoolean(), - isStorage = br.ReadBoolean(), - isTank = br.ReadBoolean(), - isVeinCollector = br.ReadBoolean(), - minerType = (EMinerType)br.ReadInt32(), - modelIndex = br.ReadInt32(), - multiLevel = br.ReadBoolean(), - oilMiner = br.ReadBoolean(), - stationCollectSpeed = br.ReadInt32(), - veinMiner = br.ReadBoolean(), - windForcedPower = br.ReadBoolean(), - workEnergyPerTick = br.ReadInt64() - }; - - //Import information about the position of build (land / sea) - num = br.ReadInt32(); - buildPreview.desc.landPoints = new Vector3[num]; - for (int i = 0; i < num; i++) - { - buildPreview.desc.landPoints[i] = new Vector3(br.ReadSingle(), br.ReadSingle(), br.ReadSingle()); + result.Add(new BuildPreview()); } - num = br.ReadInt32(); - buildPreview.desc.waterPoints = new Vector3[num]; - for (int i = 0; i < num; i++) + for (var i = 0; i < previewCount; i++) { - buildPreview.desc.waterPoints[i] = new Vector3(br.ReadSingle(), br.ReadSingle(), br.ReadSingle()); + DeserializeBuildPreview(result[i], result, reader.BinaryReader); } + } + return result; + } - //Import information about the collider to check the collisions - buildPreview.desc.hasBuildCollider = br.ReadBoolean(); - num = br.ReadInt32(); - buildPreview.desc.buildColliders = new ColliderData[num]; - for (int i = 0; i < num; i++) - { - buildPreview.desc.buildColliders[i].pos = new Vector3(br.ReadSingle(), br.ReadSingle(), br.ReadSingle()); - buildPreview.desc.buildColliders[i].ext = new Vector3(br.ReadSingle(), br.ReadSingle(), br.ReadSingle()); - buildPreview.desc.buildColliders[i].q = new Quaternion(br.ReadSingle(), br.ReadSingle(), br.ReadSingle(), br.ReadSingle()); - buildPreview.desc.buildColliders[i].radius = br.ReadSingle(); - buildPreview.desc.buildColliders[i].idType = br.ReadInt32(); - buildPreview.desc.buildColliders[i].link = br.ReadInt32(); - } + private static void DeserializeBuildPreview(BuildPreview buildPreview, List list, BinaryReader br) + { + var outputRef = br.ReadInt32(); + buildPreview.output = outputRef == -1 ? null : list[outputRef]; + var inputRef = br.ReadInt32(); + buildPreview.input = inputRef == -1 ? null : list[inputRef]; + buildPreview.objId = br.ReadInt32(); + var num = br.ReadInt32(); + buildPreview.nearestPowerObjId = num == 0 ? null : new int[num]; + for (var i = 0; i < num; i++) + { + buildPreview.nearestPowerObjId[i] = br.ReadInt32(); + } + buildPreview.coverObjId = br.ReadInt32(); + buildPreview.willRemoveCover = br.ReadBoolean(); + buildPreview.genNearColliderArea2 = br.ReadSingle(); + buildPreview.outputObjId = br.ReadInt32(); + buildPreview.inputObjId = br.ReadInt32(); + buildPreview.outputToSlot = br.ReadInt32(); + buildPreview.inputFromSlot = br.ReadInt32(); + buildPreview.outputFromSlot = br.ReadInt32(); + buildPreview.inputToSlot = br.ReadInt32(); + buildPreview.outputOffset = br.ReadInt32(); + buildPreview.inputOffset = br.ReadInt32(); + buildPreview.needModel = br.ReadBoolean(); + buildPreview.previewIndex = br.ReadInt32(); + buildPreview.bpgpuiModelId = br.ReadInt32(); + buildPreview.bpgpuiModelInstIndex = br.ReadInt32(); + buildPreview.recipeId = br.ReadInt32(); + buildPreview.filterId = br.ReadInt32(); + buildPreview.isConnNode = br.ReadBoolean(); + buildPreview.desc = new PrefabDesc + { + //Import more data about the Prefab to properly validate the build condition on server-side + assemblerRecipeType = (ERecipeType)br.ReadInt32(), + cullingHeight = br.ReadSingle(), + gammaRayReceiver = br.ReadBoolean(), + inserterSTT = br.ReadInt32(), + isAccumulator = br.ReadBoolean(), + isAssembler = br.ReadBoolean(), + isBelt = br.ReadBoolean(), + isCollectStation = br.ReadBoolean(), + isDispenser = br.ReadBoolean(), + isEjector = br.ReadBoolean(), + isFractionator = br.ReadBoolean(), + isInserter = br.ReadBoolean(), + isLab = br.ReadBoolean(), + isPowerExchanger = br.ReadBoolean(), + isSplitter = br.ReadBoolean(), + isStation = br.ReadBoolean(), + isStellarStation = br.ReadBoolean(), + isStorage = br.ReadBoolean(), + isTank = br.ReadBoolean(), + isVeinCollector = br.ReadBoolean(), + minerType = (EMinerType)br.ReadInt32(), + modelIndex = br.ReadInt32(), + multiLevel = br.ReadBoolean(), + oilMiner = br.ReadBoolean(), + stationCollectSpeed = br.ReadInt32(), + veinMiner = br.ReadBoolean(), + windForcedPower = br.ReadBoolean(), + workEnergyPerTick = br.ReadInt64() + }; - buildPreview.item = new ItemProto - { - ID = br.ReadInt32(), - BuildMode = br.ReadInt32(), - Grade = br.ReadInt32() - }; + //Import information about the position of build (land / sea) + num = br.ReadInt32(); + buildPreview.desc.landPoints = new Vector3[num]; + for (var i = 0; i < num; i++) + { + buildPreview.desc.landPoints[i] = new Vector3(br.ReadSingle(), br.ReadSingle(), br.ReadSingle()); + } + num = br.ReadInt32(); + buildPreview.desc.waterPoints = new Vector3[num]; + for (var i = 0; i < num; i++) + { + buildPreview.desc.waterPoints[i] = new Vector3(br.ReadSingle(), br.ReadSingle(), br.ReadSingle()); + } - buildPreview.paramCount = br.ReadInt32(); - buildPreview.parameters = new int[buildPreview.paramCount]; - for (int i = 0; i < buildPreview.paramCount; i++) - { - buildPreview.parameters[i] = br.ReadInt32(); - } - buildPreview.lpos = new Vector3(br.ReadSingle(), br.ReadSingle(), br.ReadSingle()); - buildPreview.lpos2 = new Vector3(br.ReadSingle(), br.ReadSingle(), br.ReadSingle()); - buildPreview.lrot = new Quaternion(br.ReadSingle(), br.ReadSingle(), br.ReadSingle(), br.ReadSingle()); - buildPreview.lrot2 = new Quaternion(br.ReadSingle(), br.ReadSingle(), br.ReadSingle(), br.ReadSingle()); - buildPreview.condition = (EBuildCondition)br.ReadInt32(); + //Import information about the collider to check the collisions + buildPreview.desc.hasBuildCollider = br.ReadBoolean(); + num = br.ReadInt32(); + buildPreview.desc.buildColliders = new ColliderData[num]; + for (var i = 0; i < num; i++) + { + buildPreview.desc.buildColliders[i].pos = new Vector3(br.ReadSingle(), br.ReadSingle(), br.ReadSingle()); + buildPreview.desc.buildColliders[i].ext = new Vector3(br.ReadSingle(), br.ReadSingle(), br.ReadSingle()); + buildPreview.desc.buildColliders[i].q = + new Quaternion(br.ReadSingle(), br.ReadSingle(), br.ReadSingle(), br.ReadSingle()); + buildPreview.desc.buildColliders[i].radius = br.ReadSingle(); + buildPreview.desc.buildColliders[i].idType = br.ReadInt32(); + buildPreview.desc.buildColliders[i].link = br.ReadInt32(); } - private static void SerializeBuildPreview(BuildPreview buildPreview, List list, BinaryWriter bw) + buildPreview.item = new ItemProto { ID = br.ReadInt32(), BuildMode = br.ReadInt32(), Grade = br.ReadInt32() }; + + buildPreview.paramCount = br.ReadInt32(); + buildPreview.parameters = new int[buildPreview.paramCount]; + for (var i = 0; i < buildPreview.paramCount; i++) { - bw.Write(list.IndexOf(buildPreview.output)); - bw.Write(list.IndexOf(buildPreview.input)); - bw.Write(buildPreview.objId); - int num = buildPreview.nearestPowerObjId == null ? 0 : buildPreview.nearestPowerObjId.Length; - bw.Write(num); - for (int i = 0; i < num; i++) - { - bw.Write(buildPreview.nearestPowerObjId[i]); - } - bw.Write(buildPreview.coverObjId); - bw.Write(buildPreview.willRemoveCover); - bw.Write(buildPreview.genNearColliderArea2); - bw.Write(buildPreview.outputObjId); - bw.Write(buildPreview.inputObjId); - bw.Write(buildPreview.outputToSlot); - bw.Write(buildPreview.inputFromSlot); - bw.Write(buildPreview.outputFromSlot); - bw.Write(buildPreview.inputToSlot); - bw.Write(buildPreview.outputOffset); - bw.Write(buildPreview.inputOffset); - bw.Write(buildPreview.needModel); - bw.Write(buildPreview.previewIndex); - bw.Write(buildPreview.bpgpuiModelId); - bw.Write(buildPreview.bpgpuiModelInstIndex); - bw.Write(buildPreview.recipeId); - bw.Write(buildPreview.filterId); - bw.Write(buildPreview.isConnNode); + buildPreview.parameters[i] = br.ReadInt32(); + } + buildPreview.lpos = new Vector3(br.ReadSingle(), br.ReadSingle(), br.ReadSingle()); + buildPreview.lpos2 = new Vector3(br.ReadSingle(), br.ReadSingle(), br.ReadSingle()); + buildPreview.lrot = new Quaternion(br.ReadSingle(), br.ReadSingle(), br.ReadSingle(), br.ReadSingle()); + buildPreview.lrot2 = new Quaternion(br.ReadSingle(), br.ReadSingle(), br.ReadSingle(), br.ReadSingle()); + buildPreview.condition = (EBuildCondition)br.ReadInt32(); + } - //Export more data about the Prefab to properly validate the build condition on server-side - bw.Write((int)buildPreview.desc.assemblerRecipeType); - bw.Write(buildPreview.desc.cullingHeight); - bw.Write(buildPreview.desc.gammaRayReceiver); - bw.Write(buildPreview.desc.inserterSTT); - bw.Write(buildPreview.desc.isAccumulator); - bw.Write(buildPreview.desc.isAssembler); - bw.Write(buildPreview.desc.isBelt); - bw.Write(buildPreview.desc.isCollectStation); - bw.Write(buildPreview.desc.isDispenser); - bw.Write(buildPreview.desc.isEjector); - bw.Write(buildPreview.desc.isFractionator); - bw.Write(buildPreview.desc.isInserter); - bw.Write(buildPreview.desc.isLab); - bw.Write(buildPreview.desc.isPowerExchanger); - bw.Write(buildPreview.desc.isSplitter); - bw.Write(buildPreview.desc.isStation); - bw.Write(buildPreview.desc.isStellarStation); - bw.Write(buildPreview.desc.isStorage); - bw.Write(buildPreview.desc.isTank); - bw.Write(buildPreview.desc.isVeinCollector); - bw.Write((int)buildPreview.desc.minerType); - bw.Write(buildPreview.desc.modelIndex); - bw.Write(buildPreview.desc.multiLevel); - bw.Write(buildPreview.desc.oilMiner); - bw.Write(buildPreview.desc.stationCollectSpeed); - bw.Write(buildPreview.desc.veinMiner); - bw.Write(buildPreview.desc.windForcedPower); - bw.Write(buildPreview.desc.workEnergyPerTick); + private static void SerializeBuildPreview(BuildPreview buildPreview, List list, BinaryWriter bw) + { + bw.Write(list.IndexOf(buildPreview.output)); + bw.Write(list.IndexOf(buildPreview.input)); + bw.Write(buildPreview.objId); + var num = buildPreview.nearestPowerObjId == null ? 0 : buildPreview.nearestPowerObjId.Length; + bw.Write(num); + for (var i = 0; i < num; i++) + { + bw.Write(buildPreview.nearestPowerObjId[i]); + } + bw.Write(buildPreview.coverObjId); + bw.Write(buildPreview.willRemoveCover); + bw.Write(buildPreview.genNearColliderArea2); + bw.Write(buildPreview.outputObjId); + bw.Write(buildPreview.inputObjId); + bw.Write(buildPreview.outputToSlot); + bw.Write(buildPreview.inputFromSlot); + bw.Write(buildPreview.outputFromSlot); + bw.Write(buildPreview.inputToSlot); + bw.Write(buildPreview.outputOffset); + bw.Write(buildPreview.inputOffset); + bw.Write(buildPreview.needModel); + bw.Write(buildPreview.previewIndex); + bw.Write(buildPreview.bpgpuiModelId); + bw.Write(buildPreview.bpgpuiModelInstIndex); + bw.Write(buildPreview.recipeId); + bw.Write(buildPreview.filterId); + bw.Write(buildPreview.isConnNode); - //Export information about the position of build (land / sea) - num = buildPreview.desc.landPoints.Length; - bw.Write(num); - for (int i = 0; i < num; i++) - { - bw.Write(buildPreview.desc.landPoints[i].x); - bw.Write(buildPreview.desc.landPoints[i].y); - bw.Write(buildPreview.desc.landPoints[i].z); - } - num = buildPreview.desc.waterPoints.Length; - bw.Write(num); - for (int i = 0; i < num; i++) - { - bw.Write(buildPreview.desc.waterPoints[i].x); - bw.Write(buildPreview.desc.waterPoints[i].y); - bw.Write(buildPreview.desc.waterPoints[i].z); - } - //Export information about the collider to check the collisions - bw.Write(buildPreview.desc.hasBuildCollider); - num = buildPreview.desc.buildColliders.Length; - bw.Write(num); - for (int i = 0; i < num; i++) - { - bw.Write(buildPreview.desc.buildColliders[i].pos.x); - bw.Write(buildPreview.desc.buildColliders[i].pos.y); - bw.Write(buildPreview.desc.buildColliders[i].pos.z); - bw.Write(buildPreview.desc.buildColliders[i].ext.x); - bw.Write(buildPreview.desc.buildColliders[i].ext.y); - bw.Write(buildPreview.desc.buildColliders[i].ext.z); - bw.Write(buildPreview.desc.buildColliders[i].q.x); - bw.Write(buildPreview.desc.buildColliders[i].q.y); - bw.Write(buildPreview.desc.buildColliders[i].q.z); - bw.Write(buildPreview.desc.buildColliders[i].q.w); - bw.Write(buildPreview.desc.buildColliders[i].radius); - bw.Write(buildPreview.desc.buildColliders[i].idType); - bw.Write(buildPreview.desc.buildColliders[i].link); - } + //Export more data about the Prefab to properly validate the build condition on server-side + bw.Write((int)buildPreview.desc.assemblerRecipeType); + bw.Write(buildPreview.desc.cullingHeight); + bw.Write(buildPreview.desc.gammaRayReceiver); + bw.Write(buildPreview.desc.inserterSTT); + bw.Write(buildPreview.desc.isAccumulator); + bw.Write(buildPreview.desc.isAssembler); + bw.Write(buildPreview.desc.isBelt); + bw.Write(buildPreview.desc.isCollectStation); + bw.Write(buildPreview.desc.isDispenser); + bw.Write(buildPreview.desc.isEjector); + bw.Write(buildPreview.desc.isFractionator); + bw.Write(buildPreview.desc.isInserter); + bw.Write(buildPreview.desc.isLab); + bw.Write(buildPreview.desc.isPowerExchanger); + bw.Write(buildPreview.desc.isSplitter); + bw.Write(buildPreview.desc.isStation); + bw.Write(buildPreview.desc.isStellarStation); + bw.Write(buildPreview.desc.isStorage); + bw.Write(buildPreview.desc.isTank); + bw.Write(buildPreview.desc.isVeinCollector); + bw.Write((int)buildPreview.desc.minerType); + bw.Write(buildPreview.desc.modelIndex); + bw.Write(buildPreview.desc.multiLevel); + bw.Write(buildPreview.desc.oilMiner); + bw.Write(buildPreview.desc.stationCollectSpeed); + bw.Write(buildPreview.desc.veinMiner); + bw.Write(buildPreview.desc.windForcedPower); + bw.Write(buildPreview.desc.workEnergyPerTick); - bw.Write(buildPreview.item.ID); - bw.Write(buildPreview.item.BuildMode); - bw.Write(buildPreview.item.Grade); - bw.Write(buildPreview.paramCount); - for (int i = 0; i < buildPreview.paramCount; i++) - { - bw.Write(buildPreview.parameters[i]); - } - bw.Write(buildPreview.lpos.x); - bw.Write(buildPreview.lpos.y); - bw.Write(buildPreview.lpos.z); - bw.Write(buildPreview.lpos2.x); - bw.Write(buildPreview.lpos2.y); - bw.Write(buildPreview.lpos2.z); - bw.Write(buildPreview.lrot.x); - bw.Write(buildPreview.lrot.y); - bw.Write(buildPreview.lrot.z); - bw.Write(buildPreview.lrot.w); - bw.Write(buildPreview.lrot2.x); - bw.Write(buildPreview.lrot2.y); - bw.Write(buildPreview.lrot2.z); - bw.Write(buildPreview.lrot2.w); - bw.Write(((int)buildPreview.condition)); + //Export information about the position of build (land / sea) + num = buildPreview.desc.landPoints.Length; + bw.Write(num); + for (var i = 0; i < num; i++) + { + bw.Write(buildPreview.desc.landPoints[i].x); + bw.Write(buildPreview.desc.landPoints[i].y); + bw.Write(buildPreview.desc.landPoints[i].z); + } + num = buildPreview.desc.waterPoints.Length; + bw.Write(num); + for (var i = 0; i < num; i++) + { + bw.Write(buildPreview.desc.waterPoints[i].x); + bw.Write(buildPreview.desc.waterPoints[i].y); + bw.Write(buildPreview.desc.waterPoints[i].z); + } + //Export information about the collider to check the collisions + bw.Write(buildPreview.desc.hasBuildCollider); + num = buildPreview.desc.buildColliders.Length; + bw.Write(num); + for (var i = 0; i < num; i++) + { + bw.Write(buildPreview.desc.buildColliders[i].pos.x); + bw.Write(buildPreview.desc.buildColliders[i].pos.y); + bw.Write(buildPreview.desc.buildColliders[i].pos.z); + bw.Write(buildPreview.desc.buildColliders[i].ext.x); + bw.Write(buildPreview.desc.buildColliders[i].ext.y); + bw.Write(buildPreview.desc.buildColliders[i].ext.z); + bw.Write(buildPreview.desc.buildColliders[i].q.x); + bw.Write(buildPreview.desc.buildColliders[i].q.y); + bw.Write(buildPreview.desc.buildColliders[i].q.z); + bw.Write(buildPreview.desc.buildColliders[i].q.w); + bw.Write(buildPreview.desc.buildColliders[i].radius); + bw.Write(buildPreview.desc.buildColliders[i].idType); + bw.Write(buildPreview.desc.buildColliders[i].link); + } + + bw.Write(buildPreview.item.ID); + bw.Write(buildPreview.item.BuildMode); + bw.Write(buildPreview.item.Grade); + bw.Write(buildPreview.paramCount); + for (var i = 0; i < buildPreview.paramCount; i++) + { + bw.Write(buildPreview.parameters[i]); } + bw.Write(buildPreview.lpos.x); + bw.Write(buildPreview.lpos.y); + bw.Write(buildPreview.lpos.z); + bw.Write(buildPreview.lpos2.x); + bw.Write(buildPreview.lpos2.y); + bw.Write(buildPreview.lpos2.z); + bw.Write(buildPreview.lrot.x); + bw.Write(buildPreview.lrot.y); + bw.Write(buildPreview.lrot.z); + bw.Write(buildPreview.lrot.w); + bw.Write(buildPreview.lrot2.x); + bw.Write(buildPreview.lrot2.y); + bw.Write(buildPreview.lrot2.z); + bw.Write(buildPreview.lrot2.w); + bw.Write((int)buildPreview.condition); } } diff --git a/NebulaModel/Packets/Factory/DestructEntityRequest.cs b/NebulaModel/Packets/Factory/DestructEntityRequest.cs index af8075a2c..032d4d3d8 100644 --- a/NebulaModel/Packets/Factory/DestructEntityRequest.cs +++ b/NebulaModel/Packets/Factory/DestructEntityRequest.cs @@ -1,17 +1,17 @@ -namespace NebulaModel.Packets.Factory +namespace NebulaModel.Packets.Factory; + +public class DestructEntityRequest { - public class DestructEntityRequest - { - public int PlanetId { get; set; } - public int ObjId { get; set; } - public int AuthorId { get; set; } + public DestructEntityRequest() { } - public DestructEntityRequest() { } - public DestructEntityRequest(int planetId, int objId, int authorId) - { - AuthorId = authorId; - PlanetId = planetId; - ObjId = objId; - } + public DestructEntityRequest(int planetId, int objId, int authorId) + { + AuthorId = authorId; + PlanetId = planetId; + ObjId = objId; } + + public int PlanetId { get; set; } + public int ObjId { get; set; } + public int AuthorId { get; set; } } diff --git a/NebulaModel/Packets/Factory/Ejector/EjectorOrbitUpdatePacket.cs b/NebulaModel/Packets/Factory/Ejector/EjectorOrbitUpdatePacket.cs index d2f8c1f0b..15f137c9d 100644 --- a/NebulaModel/Packets/Factory/Ejector/EjectorOrbitUpdatePacket.cs +++ b/NebulaModel/Packets/Factory/Ejector/EjectorOrbitUpdatePacket.cs @@ -1,16 +1,17 @@ -namespace NebulaModel.Packets.Factory.Ejector +namespace NebulaModel.Packets.Factory.Ejector; + +public class EjectorOrbitUpdatePacket { - public class EjectorOrbitUpdatePacket + public EjectorOrbitUpdatePacket() { } + + public EjectorOrbitUpdatePacket(int ejectorIndex, int newOrbitIndex, int planetId) { - public int EjectorIndex { get; set; } - public int NewOrbitIndex { get; set; } - public int PlanetId { get; set; } - public EjectorOrbitUpdatePacket() { } - public EjectorOrbitUpdatePacket(int ejectorIndex, int newOrbitIndex, int planetId) - { - EjectorIndex = ejectorIndex; - NewOrbitIndex = newOrbitIndex; - PlanetId = planetId; - } + EjectorIndex = ejectorIndex; + NewOrbitIndex = newOrbitIndex; + PlanetId = planetId; } + + public int EjectorIndex { get; set; } + public int NewOrbitIndex { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Factory/Ejector/EjectorStorageUpdatePacket.cs b/NebulaModel/Packets/Factory/Ejector/EjectorStorageUpdatePacket.cs index 5aa0cf045..62f0b087c 100644 --- a/NebulaModel/Packets/Factory/Ejector/EjectorStorageUpdatePacket.cs +++ b/NebulaModel/Packets/Factory/Ejector/EjectorStorageUpdatePacket.cs @@ -1,19 +1,19 @@ -namespace NebulaModel.Packets.Factory.Ejector +namespace NebulaModel.Packets.Factory.Ejector; + +public class EjectorStorageUpdatePacket { - public class EjectorStorageUpdatePacket - { - public int EjectorIndex { get; set; } - public int ItemCount { get; set; } - public int ItemInc { get; set; } - public int PlanetId { get; set; } + public EjectorStorageUpdatePacket() { } - public EjectorStorageUpdatePacket() { } - public EjectorStorageUpdatePacket(int ejectorIndex, int itemCount, int itemInc, int planetId) - { - EjectorIndex = ejectorIndex; - ItemCount = itemCount; - ItemInc = itemInc; - PlanetId = planetId; - } + public EjectorStorageUpdatePacket(int ejectorIndex, int itemCount, int itemInc, int planetId) + { + EjectorIndex = ejectorIndex; + ItemCount = itemCount; + ItemInc = itemInc; + PlanetId = planetId; } + + public int EjectorIndex { get; set; } + public int ItemCount { get; set; } + public int ItemInc { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Factory/EntityBoostSwitchPacket.cs b/NebulaModel/Packets/Factory/EntityBoostSwitchPacket.cs index 126d98135..d08f99e07 100644 --- a/NebulaModel/Packets/Factory/EntityBoostSwitchPacket.cs +++ b/NebulaModel/Packets/Factory/EntityBoostSwitchPacket.cs @@ -1,27 +1,26 @@ -namespace NebulaModel.Packets.Factory -{ - public class EntityBoostSwitchPacket - { - public int PlanetId { get; set; } - public EBoostEntityType EntityType { get; set; } - public int Id { get; set; } - public bool Enable { get; set; } - - public EntityBoostSwitchPacket() { } +namespace NebulaModel.Packets.Factory; - public EntityBoostSwitchPacket(int planetId, EBoostEntityType entityType, int id, bool enable) - { - PlanetId = planetId; - EntityType = entityType; - Id = id; - Enable = enable; - } - } +public class EntityBoostSwitchPacket +{ + public EntityBoostSwitchPacket() { } - public enum EBoostEntityType + public EntityBoostSwitchPacket(int planetId, EBoostEntityType entityType, int id, bool enable) { - ArtificialStar, - Ejector, - Silo + PlanetId = planetId; + EntityType = entityType; + Id = id; + Enable = enable; } + + public int PlanetId { get; set; } + public EBoostEntityType EntityType { get; set; } + public int Id { get; set; } + public bool Enable { get; set; } +} + +public enum EBoostEntityType +{ + ArtificialStar, + Ejector, + Silo } diff --git a/NebulaModel/Packets/Factory/EntityWarningSwitchPacket.cs b/NebulaModel/Packets/Factory/EntityWarningSwitchPacket.cs index 4aba590bc..dfe1a8700 100644 --- a/NebulaModel/Packets/Factory/EntityWarningSwitchPacket.cs +++ b/NebulaModel/Packets/Factory/EntityWarningSwitchPacket.cs @@ -1,18 +1,17 @@ -namespace NebulaModel.Packets.Factory -{ - public class EntityWarningSwitchPacket - { - public int PlanetId { get; set; } - public int EntityId { get; set; } - public bool Enable { get; set; } +namespace NebulaModel.Packets.Factory; - public EntityWarningSwitchPacket() { } +public class EntityWarningSwitchPacket +{ + public EntityWarningSwitchPacket() { } - public EntityWarningSwitchPacket(int planetId, int entityId, bool enable) - { - PlanetId = planetId; - EntityId = entityId; - Enable = enable; - } + public EntityWarningSwitchPacket(int planetId, int entityId, bool enable) + { + PlanetId = planetId; + EntityId = entityId; + Enable = enable; } + + public int PlanetId { get; set; } + public int EntityId { get; set; } + public bool Enable { get; set; } } diff --git a/NebulaModel/Packets/Factory/Foundation/FoundationBuildUpdatePacket.cs b/NebulaModel/Packets/Factory/Foundation/FoundationBuildUpdatePacket.cs index 951670e02..38b677e97 100644 --- a/NebulaModel/Packets/Factory/Foundation/FoundationBuildUpdatePacket.cs +++ b/NebulaModel/Packets/Factory/Foundation/FoundationBuildUpdatePacket.cs @@ -1,33 +1,37 @@ -using NebulaAPI; +#region + +using NebulaAPI; using UnityEngine; -namespace NebulaModel.Packets.Factory.Foundation +#endregion + +namespace NebulaModel.Packets.Factory.Foundation; + +public class FoundationBuildUpdatePacket { - public class FoundationBuildUpdatePacket - { - public float Radius { get; set; } - public int ReformSize { get; set; } - public bool VeinBuried { get; set; } - public float Fade0 { get; set; } - public int ReformType { get; set; } - public int ReformColor { get; set; } - public int PlanetId { get; set; } - public int[] ReformIndices { get; set; } - public Float3 GroundTestPos { get; set; } + public FoundationBuildUpdatePacket() { } - public FoundationBuildUpdatePacket() { } - public FoundationBuildUpdatePacket(float radius, int reformSize, bool veinBuried, float fade0) - { - Radius = radius; - ReformSize = reformSize; - VeinBuried = veinBuried; - Fade0 = fade0; - BuildTool_Reform btr = GameMain.mainPlayer.controller?.actionBuild.reformTool; - ReformType = btr?.brushType ?? -1; - ReformColor = btr?.brushColor ?? -1; - PlanetId = GameMain.mainPlayer.planetId; - ReformIndices = btr?.cursorIndices; - GroundTestPos = new Float3(btr?.castGroundPos ?? Vector3.zero); - } + public FoundationBuildUpdatePacket(float radius, int reformSize, bool veinBuried, float fade0) + { + Radius = radius; + ReformSize = reformSize; + VeinBuried = veinBuried; + Fade0 = fade0; + var btr = GameMain.mainPlayer.controller?.actionBuild.reformTool; + ReformType = btr?.brushType ?? -1; + ReformColor = btr?.brushColor ?? -1; + PlanetId = GameMain.mainPlayer.planetId; + ReformIndices = btr?.cursorIndices; + GroundTestPos = new Float3(btr?.castGroundPos ?? Vector3.zero); } + + public float Radius { get; set; } + public int ReformSize { get; set; } + public bool VeinBuried { get; set; } + public float Fade0 { get; set; } + public int ReformType { get; set; } + public int ReformColor { get; set; } + public int PlanetId { get; set; } + public int[] ReformIndices { get; set; } + public Float3 GroundTestPos { get; set; } } diff --git a/NebulaModel/Packets/Factory/Foundation/PlanetReformPacket.cs b/NebulaModel/Packets/Factory/Foundation/PlanetReformPacket.cs index 032c10985..e1176d6db 100644 --- a/NebulaModel/Packets/Factory/Foundation/PlanetReformPacket.cs +++ b/NebulaModel/Packets/Factory/Foundation/PlanetReformPacket.cs @@ -1,21 +1,21 @@ -namespace NebulaModel.Packets.Factory.Foundation +namespace NebulaModel.Packets.Factory.Foundation; + +public class PlanetReformPacket { - public class PlanetReformPacket - { - public int PlanetId { get; set; } - public bool IsReform { get; set; } // true = reform all, false = revert - public int Type { get; set; } - public int Color { get; set; } - public bool Bury { get; set; } + public PlanetReformPacket() { } - public PlanetReformPacket() { } - public PlanetReformPacket(int planetId, bool isReform, int type = 0, int color = 0, bool bury = false) - { - PlanetId = planetId; - IsReform = isReform; - Type = type; - Color = color; - Bury = bury; - } + public PlanetReformPacket(int planetId, bool isReform, int type = 0, int color = 0, bool bury = false) + { + PlanetId = planetId; + IsReform = isReform; + Type = type; + Color = color; + Bury = bury; } + + public int PlanetId { get; set; } + public bool IsReform { get; set; } // true = reform all, false = revert + public int Type { get; set; } + public int Color { get; set; } + public bool Bury { get; set; } } diff --git a/NebulaModel/Packets/Factory/Fractionator/TankStorageUpdatePacket.cs b/NebulaModel/Packets/Factory/Fractionator/TankStorageUpdatePacket.cs index 8d381a8fb..b578d33b0 100644 --- a/NebulaModel/Packets/Factory/Fractionator/TankStorageUpdatePacket.cs +++ b/NebulaModel/Packets/Factory/Fractionator/TankStorageUpdatePacket.cs @@ -1,21 +1,21 @@ -namespace NebulaModel.Packets.Factory.Fractionator +namespace NebulaModel.Packets.Factory.Fractionator; + +public class FractionatorStorageUpdatePacket { - public class FractionatorStorageUpdatePacket - { - public int FractionatorId { get; set; } - public int ProductOutputCount { get; set; } - public int FluidOutputCount { get; set; } - public int FluidOutputInc { get; set; } - public int PlanetId { get; set; } + public FractionatorStorageUpdatePacket() { } - public FractionatorStorageUpdatePacket() { } - public FractionatorStorageUpdatePacket(in FractionatorComponent fractionatorComponent, int planetId) - { - FractionatorId = fractionatorComponent.id; - ProductOutputCount = fractionatorComponent.productOutputCount; - FluidOutputCount = fractionatorComponent.fluidOutputCount; - FluidOutputInc = fractionatorComponent.fluidOutputInc; - PlanetId = planetId; - } + public FractionatorStorageUpdatePacket(in FractionatorComponent fractionatorComponent, int planetId) + { + FractionatorId = fractionatorComponent.id; + ProductOutputCount = fractionatorComponent.productOutputCount; + FluidOutputCount = fractionatorComponent.fluidOutputCount; + FluidOutputInc = fractionatorComponent.fluidOutputInc; + PlanetId = planetId; } + + public int FractionatorId { get; set; } + public int ProductOutputCount { get; set; } + public int FluidOutputCount { get; set; } + public int FluidOutputInc { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Factory/Inserter/InserterFilterUpdatePacket.cs b/NebulaModel/Packets/Factory/Inserter/InserterFilterUpdatePacket.cs index ed19618e2..9afb8a585 100644 --- a/NebulaModel/Packets/Factory/Inserter/InserterFilterUpdatePacket.cs +++ b/NebulaModel/Packets/Factory/Inserter/InserterFilterUpdatePacket.cs @@ -1,18 +1,17 @@ -namespace NebulaModel.Packets.Factory.Inserter -{ - public class InserterFilterUpdatePacket - { - public int InserterIndex { get; set; } - public int ItemId { get; set; } - public int PlanetId { get; set; } +namespace NebulaModel.Packets.Factory.Inserter; - public InserterFilterUpdatePacket() { } +public class InserterFilterUpdatePacket +{ + public InserterFilterUpdatePacket() { } - public InserterFilterUpdatePacket(int inserterIndex, int itemId, int planetId) - { - InserterIndex = inserterIndex; - ItemId = itemId; - PlanetId = planetId; - } + public InserterFilterUpdatePacket(int inserterIndex, int itemId, int planetId) + { + InserterIndex = inserterIndex; + ItemId = itemId; + PlanetId = planetId; } + + public int InserterIndex { get; set; } + public int ItemId { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Factory/Inserter/InserterItemUpdatePacket.cs b/NebulaModel/Packets/Factory/Inserter/InserterItemUpdatePacket.cs index b8b054d67..21b48e903 100644 --- a/NebulaModel/Packets/Factory/Inserter/InserterItemUpdatePacket.cs +++ b/NebulaModel/Packets/Factory/Inserter/InserterItemUpdatePacket.cs @@ -1,23 +1,23 @@ -namespace NebulaModel.Packets.Factory.Inserter +namespace NebulaModel.Packets.Factory.Inserter; + +public class InserterItemUpdatePacket { - public class InserterItemUpdatePacket - { - public int InserterIndex { get; set; } - public int ItemId { get; set; } - public short ItemCount { get; set; } - public short ItemInc { get; set; } - public int StackCount { get; set; } - public int PlanetId { get; set; } + public InserterItemUpdatePacket() { } - public InserterItemUpdatePacket() { } - public InserterItemUpdatePacket(in InserterComponent inserter, int planetId) - { - InserterIndex = inserter.id; - ItemId = inserter.itemId; - ItemCount = inserter.itemCount; - ItemInc = inserter.itemInc; - StackCount = inserter.stackCount; - PlanetId = planetId; - } + public InserterItemUpdatePacket(in InserterComponent inserter, int planetId) + { + InserterIndex = inserter.id; + ItemId = inserter.itemId; + ItemCount = inserter.itemCount; + ItemInc = inserter.itemInc; + StackCount = inserter.stackCount; + PlanetId = planetId; } + + public int InserterIndex { get; set; } + public int ItemId { get; set; } + public short ItemCount { get; set; } + public short ItemInc { get; set; } + public int StackCount { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Factory/Inserter/InserterOffsetCorrectionPacket.cs b/NebulaModel/Packets/Factory/Inserter/InserterOffsetCorrectionPacket.cs index 4e28605b1..cda68d656 100644 --- a/NebulaModel/Packets/Factory/Inserter/InserterOffsetCorrectionPacket.cs +++ b/NebulaModel/Packets/Factory/Inserter/InserterOffsetCorrectionPacket.cs @@ -1,19 +1,19 @@ -namespace NebulaModel.Packets.Factory.Inserter +namespace NebulaModel.Packets.Factory.Inserter; + +public class InserterOffsetCorrectionPacket { - public class InserterOffsetCorrectionPacket - { - public int InserterId { get; set; } - public short PickOffset { get; set; } - public short InsertOffset { get; set; } - public int PlanetId { get; set; } + public InserterOffsetCorrectionPacket() { } - public InserterOffsetCorrectionPacket() { } - public InserterOffsetCorrectionPacket(int inserterId, short pickOffset, short insertOffset, int planetId) - { - InserterId = inserterId; - PickOffset = pickOffset; - InsertOffset = insertOffset; - PlanetId = planetId; - } + public InserterOffsetCorrectionPacket(int inserterId, short pickOffset, short insertOffset, int planetId) + { + InserterId = inserterId; + PickOffset = pickOffset; + InsertOffset = insertOffset; + PlanetId = planetId; } + + public int InserterId { get; set; } + public short PickOffset { get; set; } + public short InsertOffset { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Factory/Inserter/NewSetInserterInsertTargetPacket.cs b/NebulaModel/Packets/Factory/Inserter/NewSetInserterInsertTargetPacket.cs index d4d5ca40f..9a58b1616 100644 --- a/NebulaModel/Packets/Factory/Inserter/NewSetInserterInsertTargetPacket.cs +++ b/NebulaModel/Packets/Factory/Inserter/NewSetInserterInsertTargetPacket.cs @@ -1,26 +1,31 @@ -using NebulaAPI; +#region + +using NebulaAPI; using UnityEngine; -namespace NebulaModel.Packets.Factory.Inserter +#endregion + +namespace NebulaModel.Packets.Factory.Inserter; + +public class NewSetInserterInsertTargetPacket { - public class NewSetInserterInsertTargetPacket - { - public int ObjId { get; set; } - public int OtherObjId { get; set; } - public int InserterId { get; set; } - public int Offset { get; set; } - public Float3 PointPos { get; set; } - public int PlanetId { get; set; } + public NewSetInserterInsertTargetPacket() { } - public NewSetInserterInsertTargetPacket() { } - public NewSetInserterInsertTargetPacket(int objId, int otherObjId, int inserterId, int offset, Vector3 pointPos, int planetId) - { - ObjId = objId; - OtherObjId = otherObjId; - InserterId = inserterId; - Offset = offset; - PointPos = new Float3(pointPos - pointPos.normalized * 0.15f); - PlanetId = planetId; - } + public NewSetInserterInsertTargetPacket(int objId, int otherObjId, int inserterId, int offset, Vector3 pointPos, + int planetId) + { + ObjId = objId; + OtherObjId = otherObjId; + InserterId = inserterId; + Offset = offset; + PointPos = new Float3(pointPos - pointPos.normalized * 0.15f); + PlanetId = planetId; } -} \ No newline at end of file + + public int ObjId { get; set; } + public int OtherObjId { get; set; } + public int InserterId { get; set; } + public int Offset { get; set; } + public Float3 PointPos { get; set; } + public int PlanetId { get; set; } +} diff --git a/NebulaModel/Packets/Factory/Inserter/NewSetInserterPickTargetPacket.cs b/NebulaModel/Packets/Factory/Inserter/NewSetInserterPickTargetPacket.cs index 5138775a4..26ba39b58 100644 --- a/NebulaModel/Packets/Factory/Inserter/NewSetInserterPickTargetPacket.cs +++ b/NebulaModel/Packets/Factory/Inserter/NewSetInserterPickTargetPacket.cs @@ -1,26 +1,30 @@ -using NebulaAPI; +#region + +using NebulaAPI; using UnityEngine; -namespace NebulaModel.Packets.Factory.Inserter +#endregion + +namespace NebulaModel.Packets.Factory.Inserter; + +public class NewSetInserterPickTargetPacket { - public class NewSetInserterPickTargetPacket - { - public int ObjId { get; set; } - public int OtherObjId { get; set; } - public int InserterId { get; set; } - public int Offset { get; set; } - public Float3 PointPos { get; set; } - public int PlanetId { get; set; } + public NewSetInserterPickTargetPacket() { } - public NewSetInserterPickTargetPacket() { } - public NewSetInserterPickTargetPacket(int objId, int otherObjId, int inserterId, int offset, Vector3 pointPos, int planetId) - { - ObjId = objId; - OtherObjId = otherObjId; - InserterId = inserterId; - Offset = offset; - PointPos = new Float3(pointPos - pointPos.normalized * 0.15f); - PlanetId = planetId; - } + public NewSetInserterPickTargetPacket(int objId, int otherObjId, int inserterId, int offset, Vector3 pointPos, int planetId) + { + ObjId = objId; + OtherObjId = otherObjId; + InserterId = inserterId; + Offset = offset; + PointPos = new Float3(pointPos - pointPos.normalized * 0.15f); + PlanetId = planetId; } -} \ No newline at end of file + + public int ObjId { get; set; } + public int OtherObjId { get; set; } + public int InserterId { get; set; } + public int Offset { get; set; } + public Float3 PointPos { get; set; } + public int PlanetId { get; set; } +} diff --git a/NebulaModel/Packets/Factory/Laboratory/LaboratoryUpdateCubesPacket.cs b/NebulaModel/Packets/Factory/Laboratory/LaboratoryUpdateCubesPacket.cs index 8fe464e0b..7b1013a65 100644 --- a/NebulaModel/Packets/Factory/Laboratory/LaboratoryUpdateCubesPacket.cs +++ b/NebulaModel/Packets/Factory/Laboratory/LaboratoryUpdateCubesPacket.cs @@ -1,21 +1,21 @@ -namespace NebulaModel.Packets.Factory.Laboratory +namespace NebulaModel.Packets.Factory.Laboratory; + +public class LaboratoryUpdateCubesPacket { - public class LaboratoryUpdateCubesPacket - { - public int ItemCount { get; set; } - public int ItemInc { get; set; } - public int Index { get; set; } - public int LabIndex { get; set; } - public int PlanetId { get; set; } + public LaboratoryUpdateCubesPacket() { } - public LaboratoryUpdateCubesPacket() { } - public LaboratoryUpdateCubesPacket(int itemCount, int itemInc, int index, int labIndex, int planetId) - { - ItemCount = itemCount; - ItemInc = itemInc; - Index = index; - LabIndex = labIndex; - PlanetId = planetId; - } + public LaboratoryUpdateCubesPacket(int itemCount, int itemInc, int index, int labIndex, int planetId) + { + ItemCount = itemCount; + ItemInc = itemInc; + Index = index; + LabIndex = labIndex; + PlanetId = planetId; } + + public int ItemCount { get; set; } + public int ItemInc { get; set; } + public int Index { get; set; } + public int LabIndex { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Factory/Laboratory/LaboratoryUpdateEventPacket.cs b/NebulaModel/Packets/Factory/Laboratory/LaboratoryUpdateEventPacket.cs index 33fcf7aa1..cc673a48a 100644 --- a/NebulaModel/Packets/Factory/Laboratory/LaboratoryUpdateEventPacket.cs +++ b/NebulaModel/Packets/Factory/Laboratory/LaboratoryUpdateEventPacket.cs @@ -1,18 +1,17 @@ -namespace NebulaModel.Packets.Factory.Laboratory -{ - public class LaboratoryUpdateEventPacket - { - public int LabIndex { get; set; } - public int ProductId { get; set; } - public int PlanetId { get; set; } +namespace NebulaModel.Packets.Factory.Laboratory; - public LaboratoryUpdateEventPacket() { } +public class LaboratoryUpdateEventPacket +{ + public LaboratoryUpdateEventPacket() { } - public LaboratoryUpdateEventPacket(int productId, int labId, int planetId) - { - LabIndex = labId; - ProductId = productId; - PlanetId = planetId; - } + public LaboratoryUpdateEventPacket(int productId, int labId, int planetId) + { + LabIndex = labId; + ProductId = productId; + PlanetId = planetId; } + + public int LabIndex { get; set; } + public int ProductId { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Factory/Laboratory/LaboratoryUpdateStoragePacket.cs b/NebulaModel/Packets/Factory/Laboratory/LaboratoryUpdateStoragePacket.cs index 470f838d6..37569a3a4 100644 --- a/NebulaModel/Packets/Factory/Laboratory/LaboratoryUpdateStoragePacket.cs +++ b/NebulaModel/Packets/Factory/Laboratory/LaboratoryUpdateStoragePacket.cs @@ -1,21 +1,21 @@ -namespace NebulaModel.Packets.Factory.Laboratory +namespace NebulaModel.Packets.Factory.Laboratory; + +public class LaboratoryUpdateStoragePacket { - public class LaboratoryUpdateStoragePacket - { - public int ItemCount { get; set; } - public int ItemInc { get; set; } - public int Index { get; set; } - public int LabIndex { get; set; } - public int PlanetId { get; set; } + public LaboratoryUpdateStoragePacket() { } - public LaboratoryUpdateStoragePacket() { } - public LaboratoryUpdateStoragePacket(int itemCount, int itemInc, int index, int labIndex, int planetId) - { - ItemCount = itemCount; - ItemInc = itemInc; - Index = index; - LabIndex = labIndex; - PlanetId = planetId; - } + public LaboratoryUpdateStoragePacket(int itemCount, int itemInc, int index, int labIndex, int planetId) + { + ItemCount = itemCount; + ItemInc = itemInc; + Index = index; + LabIndex = labIndex; + PlanetId = planetId; } + + public int ItemCount { get; set; } + public int ItemInc { get; set; } + public int Index { get; set; } + public int LabIndex { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Factory/Miner/MinerStoragePickupPacket.cs b/NebulaModel/Packets/Factory/Miner/MinerStoragePickupPacket.cs index 2eedd98cb..68631c6bd 100644 --- a/NebulaModel/Packets/Factory/Miner/MinerStoragePickupPacket.cs +++ b/NebulaModel/Packets/Factory/Miner/MinerStoragePickupPacket.cs @@ -1,16 +1,15 @@ -namespace NebulaModel.Packets.Factory.Miner -{ - public class MinerStoragePickupPacket - { - public int MinerIndex { get; set; } - public int PlanetId { get; set; } +namespace NebulaModel.Packets.Factory.Miner; - public MinerStoragePickupPacket() { } +public class MinerStoragePickupPacket +{ + public MinerStoragePickupPacket() { } - public MinerStoragePickupPacket(int minerIndex, int planetId) - { - MinerIndex = minerIndex; - PlanetId = planetId; - } + public MinerStoragePickupPacket(int minerIndex, int planetId) + { + MinerIndex = minerIndex; + PlanetId = planetId; } + + public int MinerIndex { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Factory/Monitor/MonitorSettingUpdatePacket.cs b/NebulaModel/Packets/Factory/Monitor/MonitorSettingUpdatePacket.cs index 0f29de26d..a8e6dda05 100644 --- a/NebulaModel/Packets/Factory/Monitor/MonitorSettingUpdatePacket.cs +++ b/NebulaModel/Packets/Factory/Monitor/MonitorSettingUpdatePacket.cs @@ -1,38 +1,42 @@ -namespace NebulaModel.Packets.Factory.Monitor +namespace NebulaModel.Packets.Factory.Monitor; + +public class MonitorSettingUpdatePacket { - public class MonitorSettingUpdatePacket - { - public int PlanetId { get; set; } - public int MonitorId { get; set; } - public MonitorSettingEvent Event { get; set; } - public int Parameter1 { get; set; } - public int Parameter2 { get; set; } + public MonitorSettingUpdatePacket() { } - public MonitorSettingUpdatePacket() { } - public MonitorSettingUpdatePacket(int planetId, int monitorId, MonitorSettingEvent settingEvent, int parameter1, int parameter2) - { - PlanetId = planetId; - MonitorId = monitorId; - Event = settingEvent; - Parameter1 = parameter1; - Parameter2 = parameter2; - } - public MonitorSettingUpdatePacket(int planetId, int monitorId, MonitorSettingEvent settingEvent, int parameter) - : this(planetId, monitorId, settingEvent, parameter, 0) { } + public MonitorSettingUpdatePacket(int planetId, int monitorId, MonitorSettingEvent settingEvent, int parameter1, + int parameter2) + { + PlanetId = planetId; + MonitorId = monitorId; + Event = settingEvent; + Parameter1 = parameter1; + Parameter2 = parameter2; } - public enum MonitorSettingEvent + public MonitorSettingUpdatePacket(int planetId, int monitorId, MonitorSettingEvent settingEvent, int parameter) + : this(planetId, monitorId, settingEvent, parameter, 0) { - SetPassColorId = 0, - SetFailColorId = 1, - SetPassOperator = 2, - SetMonitorMode = 3, - SetSystemWarningMode = 4, - SetSystemWarningSignalId = 5, - SetCargoFilter = 6, - SetTargetCargoBytes = 7, - SetPeriodTickCount = 8, - SetTargetBelt = 9, - SetSpawnOperator = 10 } + + public int PlanetId { get; set; } + public int MonitorId { get; set; } + public MonitorSettingEvent Event { get; set; } + public int Parameter1 { get; set; } + public int Parameter2 { get; set; } +} + +public enum MonitorSettingEvent +{ + SetPassColorId = 0, + SetFailColorId = 1, + SetPassOperator = 2, + SetMonitorMode = 3, + SetSystemWarningMode = 4, + SetSystemWarningSignalId = 5, + SetCargoFilter = 6, + SetTargetCargoBytes = 7, + SetPeriodTickCount = 8, + SetTargetBelt = 9, + SetSpawnOperator = 10 } diff --git a/NebulaModel/Packets/Factory/Monitor/SpeakerSettingUpdatePacket.cs b/NebulaModel/Packets/Factory/Monitor/SpeakerSettingUpdatePacket.cs index 1e5eec58e..8586a1bbb 100644 --- a/NebulaModel/Packets/Factory/Monitor/SpeakerSettingUpdatePacket.cs +++ b/NebulaModel/Packets/Factory/Monitor/SpeakerSettingUpdatePacket.cs @@ -1,33 +1,37 @@ -namespace NebulaModel.Packets.Factory.Monitor +namespace NebulaModel.Packets.Factory.Monitor; + +public class SpeakerSettingUpdatePacket { - public class SpeakerSettingUpdatePacket - { - public int PlanetId { get; set; } - public int SpeakerId { get; set; } - public SpeakerSettingEvent Event { get; set; } - public int Parameter1 { get; set; } - public int Parameter2 { get; set; } + public SpeakerSettingUpdatePacket() { } - public SpeakerSettingUpdatePacket() { } - public SpeakerSettingUpdatePacket(int planetId, int speakerId, SpeakerSettingEvent settingEvent, int parameter1, int parameter2) - { - PlanetId = planetId; - SpeakerId = speakerId; - Event = settingEvent; - Parameter1 = parameter1; - Parameter2 = parameter2; - } - public SpeakerSettingUpdatePacket(int planetId, int speakerId, SpeakerSettingEvent settingEvent, int parameter) - : this(planetId, speakerId, settingEvent, parameter, 0) { } + public SpeakerSettingUpdatePacket(int planetId, int speakerId, SpeakerSettingEvent settingEvent, int parameter1, + int parameter2) + { + PlanetId = planetId; + SpeakerId = speakerId; + Event = settingEvent; + Parameter1 = parameter1; + Parameter2 = parameter2; } - public enum SpeakerSettingEvent + public SpeakerSettingUpdatePacket(int planetId, int speakerId, SpeakerSettingEvent settingEvent, int parameter) + : this(planetId, speakerId, settingEvent, parameter, 0) { - SetTone = 0, - SetVolume = 1, - SetPitch = 2, - SetLength = 3, - SetRepeat = 4, - SetFalloffRadius = 5 } -} \ No newline at end of file + + public int PlanetId { get; set; } + public int SpeakerId { get; set; } + public SpeakerSettingEvent Event { get; set; } + public int Parameter1 { get; set; } + public int Parameter2 { get; set; } +} + +public enum SpeakerSettingEvent +{ + SetTone = 0, + SetVolume = 1, + SetPitch = 2, + SetLength = 3, + SetRepeat = 4, + SetFalloffRadius = 5 +} diff --git a/NebulaModel/Packets/Factory/PasteBuildingSettingUpdate.cs b/NebulaModel/Packets/Factory/PasteBuildingSettingUpdate.cs index dff2fe0c1..3cb24739d 100644 --- a/NebulaModel/Packets/Factory/PasteBuildingSettingUpdate.cs +++ b/NebulaModel/Packets/Factory/PasteBuildingSettingUpdate.cs @@ -1,69 +1,68 @@ -namespace NebulaModel.Packets.Factory +namespace NebulaModel.Packets.Factory; + +public class PasteBuildingSettingUpdate { - public class PasteBuildingSettingUpdate - { - public int ObjectId { get; set; } - public BuildingType Type { get; set; } - public int ItemId { get; set; } - public int ModelIndex { get; set; } - public float Yaw { get; set; } - public ERecipeType RecipeType { get; set; } - public int RecipeId { get; set; } - public int FilterId { get; set; } - public int Mode0 { get; set; } - public int Mode1 { get; set; } - public int Mode2 { get; set; } - public int Mode3 { get; set; } - public int[] Parameters { get; set; } - public int[] InserterItemIds { get; set; } - public int[] InserterLengths { get; set; } - public int[] InserterFilters { get; set; } - public int PlanetId { get; set; } + public PasteBuildingSettingUpdate() { } - public PasteBuildingSettingUpdate() { } + public PasteBuildingSettingUpdate(int objectId, BuildingParameters clipboard, int planetId) + { + ObjectId = objectId; + Type = clipboard.type; + ItemId = clipboard.itemId; + ModelIndex = clipboard.modelIndex; + Yaw = clipboard.yaw; + RecipeType = clipboard.recipeType; + RecipeId = clipboard.recipeId; + FilterId = clipboard.filterId; + Mode0 = clipboard.mode0; + Mode1 = clipboard.mode1; + Mode2 = clipboard.mode2; + Mode3 = clipboard.mode3; + Parameters = clipboard.parameters; + InserterItemIds = clipboard.inserterItemIds; + InserterLengths = clipboard.inserterLengths; + InserterFilters = clipboard.inserterFilters; + PlanetId = planetId; + } - public PasteBuildingSettingUpdate(int objectId, BuildingParameters clipboard, int planetId) - { - ObjectId = objectId; - Type = clipboard.type; - ItemId = clipboard.itemId; - ModelIndex = clipboard.modelIndex; - Yaw = clipboard.yaw; - RecipeType = clipboard.recipeType; - RecipeId = clipboard.recipeId; - FilterId = clipboard.filterId; - Mode0 = clipboard.mode0; - Mode1 = clipboard.mode1; - Mode2 = clipboard.mode2; - Mode3 = clipboard.mode3; - Parameters = clipboard.parameters; - InserterItemIds = clipboard.inserterItemIds; - InserterLengths = clipboard.inserterLengths; - InserterFilters = clipboard.inserterFilters; - PlanetId = planetId; - } + public int ObjectId { get; set; } + public BuildingType Type { get; set; } + public int ItemId { get; set; } + public int ModelIndex { get; set; } + public float Yaw { get; set; } + public ERecipeType RecipeType { get; set; } + public int RecipeId { get; set; } + public int FilterId { get; set; } + public int Mode0 { get; set; } + public int Mode1 { get; set; } + public int Mode2 { get; set; } + public int Mode3 { get; set; } + public int[] Parameters { get; set; } + public int[] InserterItemIds { get; set; } + public int[] InserterLengths { get; set; } + public int[] InserterFilters { get; set; } + public int PlanetId { get; set; } - public BuildingParameters GetBuildingSettings() + public BuildingParameters GetBuildingSettings() + { + var result = new BuildingParameters { - BuildingParameters result = new BuildingParameters - { - type = Type, - itemId = ItemId, - modelIndex = ModelIndex, - yaw = Yaw, - recipeType = RecipeType, - recipeId = RecipeId, - filterId = FilterId, - mode0 = Mode0, - mode1 = Mode1, - mode2 = Mode2, - mode3 = Mode3, - parameters = Parameters, - inserterItemIds = InserterItemIds, - inserterLengths = InserterLengths, - inserterFilters = InserterFilters - }; - return result; - } + type = Type, + itemId = ItemId, + modelIndex = ModelIndex, + yaw = Yaw, + recipeType = RecipeType, + recipeId = RecipeId, + filterId = FilterId, + mode0 = Mode0, + mode1 = Mode1, + mode2 = Mode2, + mode3 = Mode3, + parameters = Parameters, + inserterItemIds = InserterItemIds, + inserterLengths = InserterLengths, + inserterFilters = InserterFilters + }; + return result; } } diff --git a/NebulaModel/Packets/Factory/PowerExchanger/PowerExchangerChangeModePacket.cs b/NebulaModel/Packets/Factory/PowerExchanger/PowerExchangerChangeModePacket.cs index adc247222..188f0a39d 100644 --- a/NebulaModel/Packets/Factory/PowerExchanger/PowerExchangerChangeModePacket.cs +++ b/NebulaModel/Packets/Factory/PowerExchanger/PowerExchangerChangeModePacket.cs @@ -1,18 +1,17 @@ -namespace NebulaModel.Packets.Factory.PowerExchanger -{ - public class PowerExchangerChangeModePacket - { - public int PowerExchangerIndex { get; set; } - public int Mode { get; set; } - public int PlanetId { get; set; } +namespace NebulaModel.Packets.Factory.PowerExchanger; - public PowerExchangerChangeModePacket() { } +public class PowerExchangerChangeModePacket +{ + public PowerExchangerChangeModePacket() { } - public PowerExchangerChangeModePacket(int powerExchangerIndex, int mode, int planetId) - { - PowerExchangerIndex = powerExchangerIndex; - Mode = mode; - PlanetId = planetId; - } + public PowerExchangerChangeModePacket(int powerExchangerIndex, int mode, int planetId) + { + PowerExchangerIndex = powerExchangerIndex; + Mode = mode; + PlanetId = planetId; } + + public int PowerExchangerIndex { get; set; } + public int Mode { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Factory/PowerExchanger/PowerExchangerStorageUpdatePacket.cs b/NebulaModel/Packets/Factory/PowerExchanger/PowerExchangerStorageUpdatePacket.cs index 47e450097..3f4c296ba 100644 --- a/NebulaModel/Packets/Factory/PowerExchanger/PowerExchangerStorageUpdatePacket.cs +++ b/NebulaModel/Packets/Factory/PowerExchanger/PowerExchangerStorageUpdatePacket.cs @@ -1,20 +1,20 @@ -namespace NebulaModel.Packets.Factory.PowerExchanger -{ - public class PowerExchangerStorageUpdatePacket - { - public int PowerExchangerIndex { get; set; } - public int EmptyAccumulatorCount { get; set; } - public int FullAccumulatorCount { get; set; } - public int PlanetId { get; set; } +namespace NebulaModel.Packets.Factory.PowerExchanger; - public PowerExchangerStorageUpdatePacket() { } +public class PowerExchangerStorageUpdatePacket +{ + public PowerExchangerStorageUpdatePacket() { } - public PowerExchangerStorageUpdatePacket(int powerExchangerIndex, int emptyAccumulatorCount, int fullAccumulatorCount, int planetId) - { - PowerExchangerIndex = powerExchangerIndex; - EmptyAccumulatorCount = emptyAccumulatorCount; - FullAccumulatorCount = fullAccumulatorCount; - PlanetId = planetId; - } + public PowerExchangerStorageUpdatePacket(int powerExchangerIndex, int emptyAccumulatorCount, int fullAccumulatorCount, + int planetId) + { + PowerExchangerIndex = powerExchangerIndex; + EmptyAccumulatorCount = emptyAccumulatorCount; + FullAccumulatorCount = fullAccumulatorCount; + PlanetId = planetId; } + + public int PowerExchangerIndex { get; set; } + public int EmptyAccumulatorCount { get; set; } + public int FullAccumulatorCount { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Factory/PowerGenerator/PowerGeneratorFuelUpdatePacket.cs b/NebulaModel/Packets/Factory/PowerGenerator/PowerGeneratorFuelUpdatePacket.cs index 9072dfe3d..de905b530 100644 --- a/NebulaModel/Packets/Factory/PowerGenerator/PowerGeneratorFuelUpdatePacket.cs +++ b/NebulaModel/Packets/Factory/PowerGenerator/PowerGeneratorFuelUpdatePacket.cs @@ -1,22 +1,21 @@ -namespace NebulaModel.Packets.Factory.PowerGenerator -{ - public class PowerGeneratorFuelUpdatePacket - { - public int PowerGeneratorIndex { get; set; } - public int FuelId { get; set; } - public short FuelAmount { get; set; } - public short FuelInc { get; set; } - public int PlanetId { get; set; } +namespace NebulaModel.Packets.Factory.PowerGenerator; - public PowerGeneratorFuelUpdatePacket() { } +public class PowerGeneratorFuelUpdatePacket +{ + public PowerGeneratorFuelUpdatePacket() { } - public PowerGeneratorFuelUpdatePacket(int powerGeneratorIndex, int fuelId, short fuelAmount, short fuelInc, int planetId) - { - PowerGeneratorIndex = powerGeneratorIndex; - FuelId = fuelId; - FuelAmount = fuelAmount; - FuelInc = fuelInc; - PlanetId = planetId; - } + public PowerGeneratorFuelUpdatePacket(int powerGeneratorIndex, int fuelId, short fuelAmount, short fuelInc, int planetId) + { + PowerGeneratorIndex = powerGeneratorIndex; + FuelId = fuelId; + FuelAmount = fuelAmount; + FuelInc = fuelInc; + PlanetId = planetId; } + + public int PowerGeneratorIndex { get; set; } + public int FuelId { get; set; } + public short FuelAmount { get; set; } + public short FuelInc { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Factory/PowerGenerator/PowerGeneratorProductUpdatePacket.cs b/NebulaModel/Packets/Factory/PowerGenerator/PowerGeneratorProductUpdatePacket.cs index 090e7dc7b..3c4d2ba1c 100644 --- a/NebulaModel/Packets/Factory/PowerGenerator/PowerGeneratorProductUpdatePacket.cs +++ b/NebulaModel/Packets/Factory/PowerGenerator/PowerGeneratorProductUpdatePacket.cs @@ -1,17 +1,17 @@ -namespace NebulaModel.Packets.Factory.PowerGenerator +namespace NebulaModel.Packets.Factory.PowerGenerator; + +public class PowerGeneratorProductUpdatePacket { - public class PowerGeneratorProductUpdatePacket - { - public int PowerGeneratorIndex { get; set; } - public float ProductCount { get; set; } - public int PlanetId { get; set; } + public PowerGeneratorProductUpdatePacket() { } - public PowerGeneratorProductUpdatePacket() { } - public PowerGeneratorProductUpdatePacket(in PowerGeneratorComponent powerGenerator, int planetId) - { - PowerGeneratorIndex = powerGenerator.id; - ProductCount = powerGenerator.productCount; - PlanetId = planetId; - } + public PowerGeneratorProductUpdatePacket(in PowerGeneratorComponent powerGenerator, int planetId) + { + PowerGeneratorIndex = powerGenerator.id; + ProductCount = powerGenerator.productCount; + PlanetId = planetId; } + + public int PowerGeneratorIndex { get; set; } + public float ProductCount { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Factory/PowerTower/PowerTowerUserLoadingRequest.cs b/NebulaModel/Packets/Factory/PowerTower/PowerTowerUserLoadingRequest.cs index 4e8da2cb5..14e0a60e5 100644 --- a/NebulaModel/Packets/Factory/PowerTower/PowerTowerUserLoadingRequest.cs +++ b/NebulaModel/Packets/Factory/PowerTower/PowerTowerUserLoadingRequest.cs @@ -1,22 +1,21 @@ -namespace NebulaModel.Packets.Factory.PowerTower -{ - public class PowerTowerUserLoadingRequest - { - public int PlanetId { get; set; } - public int NetId { get; set; } - public int NodeId { get; set; } - public int PowerAmount { get; set; } - public bool Charging { get; set; } +namespace NebulaModel.Packets.Factory.PowerTower; - public PowerTowerUserLoadingRequest() { } +public class PowerTowerUserLoadingRequest +{ + public PowerTowerUserLoadingRequest() { } - public PowerTowerUserLoadingRequest(int PlanetId, int NetId, int NodeId, int PowerAmount, bool Charging) - { - this.PlanetId = PlanetId; - this.NetId = NetId; - this.NodeId = NodeId; - this.PowerAmount = PowerAmount; - this.Charging = Charging; - } + public PowerTowerUserLoadingRequest(int PlanetId, int NetId, int NodeId, int PowerAmount, bool Charging) + { + this.PlanetId = PlanetId; + this.NetId = NetId; + this.NodeId = NodeId; + this.PowerAmount = PowerAmount; + this.Charging = Charging; } + + public int PlanetId { get; set; } + public int NetId { get; set; } + public int NodeId { get; set; } + public int PowerAmount { get; set; } + public bool Charging { get; set; } } diff --git a/NebulaModel/Packets/Factory/PowerTower/PowerTowerUserLoadingResponse.cs b/NebulaModel/Packets/Factory/PowerTower/PowerTowerUserLoadingResponse.cs index cd6c888ef..7ae1c8b43 100644 --- a/NebulaModel/Packets/Factory/PowerTower/PowerTowerUserLoadingResponse.cs +++ b/NebulaModel/Packets/Factory/PowerTower/PowerTowerUserLoadingResponse.cs @@ -1,30 +1,32 @@ -namespace NebulaModel.Packets.Factory.PowerTower +namespace NebulaModel.Packets.Factory.PowerTower; + +public class PowerTowerUserLoadingResponse { - public class PowerTowerUserLoadingResponse + public PowerTowerUserLoadingResponse() { } + + public PowerTowerUserLoadingResponse(int PlanetId, int NetId, int NodeId, int PowerAmount, long EnergyCapacity, + long EnergyRequired, long EnergyServed, long EnergyAccumulated, long EnergyExchanged, bool Charging) { - public int PlanetId { get; set; } - public int NetId { get; set; } - public int NodeId { get; set; } - public int PowerAmount { get; set; } - public long EnergyCapacity { get; set; } - public long EnergyRequired { get; set; } - public long EnergyServed { get; set; } - public long EnergyAccumulated { get; set; } - public long EnergyExchanged { get; set; } - public bool Charging { get; set; } - public PowerTowerUserLoadingResponse() { } - public PowerTowerUserLoadingResponse(int PlanetId, int NetId, int NodeId, int PowerAmount, long EnergyCapacity, long EnergyRequired, long EnergyServed, long EnergyAccumulated, long EnergyExchanged, bool Charging) - { - this.PlanetId = PlanetId; - this.NetId = NetId; - this.NodeId = NodeId; - this.PowerAmount = PowerAmount; - this.EnergyCapacity = EnergyCapacity; - this.EnergyRequired = EnergyRequired; - this.EnergyServed = EnergyServed; - this.EnergyAccumulated = EnergyAccumulated; - this.EnergyExchanged = EnergyExchanged; - this.Charging = Charging; - } + this.PlanetId = PlanetId; + this.NetId = NetId; + this.NodeId = NodeId; + this.PowerAmount = PowerAmount; + this.EnergyCapacity = EnergyCapacity; + this.EnergyRequired = EnergyRequired; + this.EnergyServed = EnergyServed; + this.EnergyAccumulated = EnergyAccumulated; + this.EnergyExchanged = EnergyExchanged; + this.Charging = Charging; } + + public int PlanetId { get; set; } + public int NetId { get; set; } + public int NodeId { get; set; } + public int PowerAmount { get; set; } + public long EnergyCapacity { get; set; } + public long EnergyRequired { get; set; } + public long EnergyServed { get; set; } + public long EnergyAccumulated { get; set; } + public long EnergyExchanged { get; set; } + public bool Charging { get; set; } } diff --git a/NebulaModel/Packets/Factory/RayReceiver/RayReceiverChangeLensPacket.cs b/NebulaModel/Packets/Factory/RayReceiver/RayReceiverChangeLensPacket.cs index f968415cc..69c1d00c2 100644 --- a/NebulaModel/Packets/Factory/RayReceiver/RayReceiverChangeLensPacket.cs +++ b/NebulaModel/Packets/Factory/RayReceiver/RayReceiverChangeLensPacket.cs @@ -1,20 +1,19 @@ -namespace NebulaModel.Packets.Factory.RayReceiver -{ - public class RayReceiverChangeLensPacket - { - public int GeneratorId { get; set; } - public int LensCount { get; set; } - public int LensInc { get; set; } - public int PlanetId { get; set; } +namespace NebulaModel.Packets.Factory.RayReceiver; - public RayReceiverChangeLensPacket() { } +public class RayReceiverChangeLensPacket +{ + public RayReceiverChangeLensPacket() { } - public RayReceiverChangeLensPacket(int generatorId, int lensCount, int lensInc, int planetId) - { - GeneratorId = generatorId; - LensCount = lensCount; - LensInc = lensInc; - PlanetId = planetId; - } + public RayReceiverChangeLensPacket(int generatorId, int lensCount, int lensInc, int planetId) + { + GeneratorId = generatorId; + LensCount = lensCount; + LensInc = lensInc; + PlanetId = planetId; } + + public int GeneratorId { get; set; } + public int LensCount { get; set; } + public int LensInc { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Factory/RayReceiver/RayReceiverChangeModePacket.cs b/NebulaModel/Packets/Factory/RayReceiver/RayReceiverChangeModePacket.cs index a8810d36a..02077fb9c 100644 --- a/NebulaModel/Packets/Factory/RayReceiver/RayReceiverChangeModePacket.cs +++ b/NebulaModel/Packets/Factory/RayReceiver/RayReceiverChangeModePacket.cs @@ -1,24 +1,23 @@ -namespace NebulaModel.Packets.Factory.RayReceiver -{ - public class RayReceiverChangeModePacket - { - public int GeneratorId { get; set; } - public RayReceiverMode Mode { get; set; } - public int PlanetId { get; set; } - - public RayReceiverChangeModePacket() { } +namespace NebulaModel.Packets.Factory.RayReceiver; - public RayReceiverChangeModePacket(int generatorId, RayReceiverMode mode, int planetId) - { - GeneratorId = generatorId; - Mode = mode; - PlanetId = planetId; - } - } +public class RayReceiverChangeModePacket +{ + public RayReceiverChangeModePacket() { } - public enum RayReceiverMode + public RayReceiverChangeModePacket(int generatorId, RayReceiverMode mode, int planetId) { - Electricity = 0, - Photon = 1 + GeneratorId = generatorId; + Mode = mode; + PlanetId = planetId; } + + public int GeneratorId { get; set; } + public RayReceiverMode Mode { get; set; } + public int PlanetId { get; set; } +} + +public enum RayReceiverMode +{ + Electricity = 0, + Photon = 1 } diff --git a/NebulaModel/Packets/Factory/Silo/SiloStorageUpdatePacket.cs b/NebulaModel/Packets/Factory/Silo/SiloStorageUpdatePacket.cs index 406356a55..50e8bd80a 100644 --- a/NebulaModel/Packets/Factory/Silo/SiloStorageUpdatePacket.cs +++ b/NebulaModel/Packets/Factory/Silo/SiloStorageUpdatePacket.cs @@ -1,19 +1,19 @@ -namespace NebulaModel.Packets.Factory.Silo +namespace NebulaModel.Packets.Factory.Silo; + +public class SiloStorageUpdatePacket { - public class SiloStorageUpdatePacket - { - public int SiloIndex { get; set; } - public int ItemCount { get; set; } - public int ItemInc { get; set; } - public int PlanetId { get; set; } + public SiloStorageUpdatePacket() { } - public SiloStorageUpdatePacket() { } - public SiloStorageUpdatePacket(int siloIndex, int itemCount, int itemInc, int planetId) - { - SiloIndex = siloIndex; - ItemCount = itemCount; - ItemInc = itemInc; - PlanetId = planetId; - } + public SiloStorageUpdatePacket(int siloIndex, int itemCount, int itemInc, int planetId) + { + SiloIndex = siloIndex; + ItemCount = itemCount; + ItemInc = itemInc; + PlanetId = planetId; } + + public int SiloIndex { get; set; } + public int ItemCount { get; set; } + public int ItemInc { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Factory/Splitter/SplitterFilterChangePacket.cs b/NebulaModel/Packets/Factory/Splitter/SplitterFilterChangePacket.cs index 3db523148..c5e4f1755 100644 --- a/NebulaModel/Packets/Factory/Splitter/SplitterFilterChangePacket.cs +++ b/NebulaModel/Packets/Factory/Splitter/SplitterFilterChangePacket.cs @@ -1,18 +1,17 @@ -namespace NebulaModel.Packets.Factory.Splitter -{ - public class SplitterFilterChangePacket - { - public int SplitterIndex { get; set; } - public int ItemId { get; set; } - public int PlanetId { get; set; } +namespace NebulaModel.Packets.Factory.Splitter; - public SplitterFilterChangePacket() { } +public class SplitterFilterChangePacket +{ + public SplitterFilterChangePacket() { } - public SplitterFilterChangePacket(int splitterIndex, int itemId, int planetId) - { - SplitterIndex = splitterIndex; - ItemId = itemId; - PlanetId = planetId; - } + public SplitterFilterChangePacket(int splitterIndex, int itemId, int planetId) + { + SplitterIndex = splitterIndex; + ItemId = itemId; + PlanetId = planetId; } + + public int SplitterIndex { get; set; } + public int ItemId { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Factory/Splitter/SplitterPriorityChangePacket.cs b/NebulaModel/Packets/Factory/Splitter/SplitterPriorityChangePacket.cs index 19f17f64f..b5f037bc0 100644 --- a/NebulaModel/Packets/Factory/Splitter/SplitterPriorityChangePacket.cs +++ b/NebulaModel/Packets/Factory/Splitter/SplitterPriorityChangePacket.cs @@ -1,22 +1,21 @@ -namespace NebulaModel.Packets.Factory.Splitter -{ - public class SplitterPriorityChangePacket - { - public int SplitterIndex { get; set; } - public int Slot { get; set; } - public bool IsPriority { get; set; } - public int Filter { get; set; } - public int PlanetId { get; set; } +namespace NebulaModel.Packets.Factory.Splitter; - public SplitterPriorityChangePacket() { } +public class SplitterPriorityChangePacket +{ + public SplitterPriorityChangePacket() { } - public SplitterPriorityChangePacket(int splitterIndex, int slot, bool isPriority, int filter, int planetId) - { - SplitterIndex = splitterIndex; - Slot = slot; - IsPriority = isPriority; - Filter = filter; - PlanetId = planetId; - } + public SplitterPriorityChangePacket(int splitterIndex, int slot, bool isPriority, int filter, int planetId) + { + SplitterIndex = splitterIndex; + Slot = slot; + IsPriority = isPriority; + Filter = filter; + PlanetId = planetId; } + + public int SplitterIndex { get; set; } + public int Slot { get; set; } + public bool IsPriority { get; set; } + public int Filter { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Factory/Storage/StorageSyncRealtimeChangePacket.cs b/NebulaModel/Packets/Factory/Storage/StorageSyncRealtimeChangePacket.cs index e9681e3ac..41cdb7739 100644 --- a/NebulaModel/Packets/Factory/Storage/StorageSyncRealtimeChangePacket.cs +++ b/NebulaModel/Packets/Factory/Storage/StorageSyncRealtimeChangePacket.cs @@ -1,83 +1,87 @@ -namespace NebulaModel.Packets.Factory.Storage -{ - public class StorageSyncRealtimeChangePacket - { - public StorageSyncRealtimeChangeEvent StorageEvent { get; set; } - public int ItemId { get; set; } - public int Count { get; set; } - public bool UseBan { get; set; } - public int StartIndex { get; set; } - public int Length { get; set; } - public int[] Needs { get; set; } - public int StorageIndex { get; set; } - public int Inc { get; set; } - public int PlanetId { get; set; } +namespace NebulaModel.Packets.Factory.Storage; - public StorageSyncRealtimeChangePacket() { } - - public StorageSyncRealtimeChangePacket(int storageIndex, StorageSyncRealtimeChangeEvent storageEvent, int itemId, int count, int inc) - { - StorageEvent = storageEvent; - ItemId = itemId; - Count = count; - StorageIndex = storageIndex; - Inc = inc; - PlanetId = GameMain.localPlanet?.id ?? -1; - } +public class StorageSyncRealtimeChangePacket +{ + public StorageSyncRealtimeChangePacket() { } - public StorageSyncRealtimeChangePacket(int storageIndex, StorageSyncRealtimeChangeEvent storageEvent, int itemId, int count, bool useBan) - { - StorageEvent = storageEvent; - ItemId = itemId; - Count = count; - UseBan = useBan; - StorageIndex = storageIndex; - PlanetId = GameMain.localPlanet?.id ?? -1; - } + public StorageSyncRealtimeChangePacket(int storageIndex, StorageSyncRealtimeChangeEvent storageEvent, int itemId, int count, + int inc) + { + StorageEvent = storageEvent; + ItemId = itemId; + Count = count; + StorageIndex = storageIndex; + Inc = inc; + PlanetId = GameMain.localPlanet?.id ?? -1; + } - public StorageSyncRealtimeChangePacket(int storageIndex, StorageSyncRealtimeChangeEvent storageEvent, int itemId, int count, int[] needs, bool useBan) - { - StorageEvent = storageEvent; - ItemId = itemId; - Count = count; - Needs = needs; - UseBan = useBan; - StorageIndex = storageIndex; - PlanetId = GameMain.localPlanet?.id ?? -1; - } + public StorageSyncRealtimeChangePacket(int storageIndex, StorageSyncRealtimeChangeEvent storageEvent, int itemId, int count, + bool useBan) + { + StorageEvent = storageEvent; + ItemId = itemId; + Count = count; + UseBan = useBan; + StorageIndex = storageIndex; + PlanetId = GameMain.localPlanet?.id ?? -1; + } - public StorageSyncRealtimeChangePacket(int storageIndex, StorageSyncRealtimeChangeEvent storageEvent, int gridIndex, int itemId, int count, int inc) - { - StorageEvent = storageEvent; - ItemId = itemId; - Count = count; - Length = gridIndex; - StorageIndex = storageIndex; - PlanetId = GameMain.localPlanet?.id ?? -1; - } + public StorageSyncRealtimeChangePacket(int storageIndex, StorageSyncRealtimeChangeEvent storageEvent, int itemId, int count, + int[] needs, bool useBan) + { + StorageEvent = storageEvent; + ItemId = itemId; + Count = count; + Needs = needs; + UseBan = useBan; + StorageIndex = storageIndex; + PlanetId = GameMain.localPlanet?.id ?? -1; + } - public StorageSyncRealtimeChangePacket(int storageIndex, StorageSyncRealtimeChangeEvent storageEvent, int itemId, int count, int startIndex, int length, int inc) - { - StorageEvent = storageEvent; - ItemId = itemId; - Count = count; - StartIndex = startIndex; - Length = length; - StorageIndex = storageIndex; - Inc = inc; - PlanetId = GameMain.localPlanet?.id ?? -1; - } + public StorageSyncRealtimeChangePacket(int storageIndex, StorageSyncRealtimeChangeEvent storageEvent, int gridIndex, + int itemId, int count, int inc) + { + StorageEvent = storageEvent; + ItemId = itemId; + Count = count; + Length = gridIndex; + StorageIndex = storageIndex; + PlanetId = GameMain.localPlanet?.id ?? -1; } - public enum StorageSyncRealtimeChangeEvent + public StorageSyncRealtimeChangePacket(int storageIndex, StorageSyncRealtimeChangeEvent storageEvent, int itemId, int count, + int startIndex, int length, int inc) { - AddItem1 = 1, - AddItem2 = 2, - AddItemStacked = 3, - TakeItem = 4, - TakeItemFromGrid = 5, - TakeHeadItems = 6, - TakeTailItems1 = 7, - TakeTailItems2 = 8 + StorageEvent = storageEvent; + ItemId = itemId; + Count = count; + StartIndex = startIndex; + Length = length; + StorageIndex = storageIndex; + Inc = inc; + PlanetId = GameMain.localPlanet?.id ?? -1; } + + public StorageSyncRealtimeChangeEvent StorageEvent { get; set; } + public int ItemId { get; set; } + public int Count { get; set; } + public bool UseBan { get; set; } + public int StartIndex { get; set; } + public int Length { get; set; } + public int[] Needs { get; set; } + public int StorageIndex { get; set; } + public int Inc { get; set; } + public int PlanetId { get; set; } +} + +public enum StorageSyncRealtimeChangeEvent +{ + AddItem1 = 1, + AddItem2 = 2, + AddItemStacked = 3, + TakeItem = 4, + TakeItemFromGrid = 5, + TakeHeadItems = 6, + TakeTailItems1 = 7, + TakeTailItems2 = 8 } diff --git a/NebulaModel/Packets/Factory/Storage/StorageSyncRequestPacket.cs b/NebulaModel/Packets/Factory/Storage/StorageSyncRequestPacket.cs index 5704dbac2..e02371b78 100644 --- a/NebulaModel/Packets/Factory/Storage/StorageSyncRequestPacket.cs +++ b/NebulaModel/Packets/Factory/Storage/StorageSyncRequestPacket.cs @@ -1,16 +1,15 @@ -namespace NebulaModel.Packets.Factory.Storage -{ - public class StorageSyncRequestPacket - { - public int PlanetId { get; set; } - public int StorageId { get; set; } +namespace NebulaModel.Packets.Factory.Storage; - public StorageSyncRequestPacket() { } +public class StorageSyncRequestPacket +{ + public StorageSyncRequestPacket() { } - public StorageSyncRequestPacket(int planetId, int storageId) - { - PlanetId = planetId; - StorageId = storageId; - } + public StorageSyncRequestPacket(int planetId, int storageId) + { + PlanetId = planetId; + StorageId = storageId; } + + public int PlanetId { get; set; } + public int StorageId { get; set; } } diff --git a/NebulaModel/Packets/Factory/Storage/StorageSyncResponsePacket.cs b/NebulaModel/Packets/Factory/Storage/StorageSyncResponsePacket.cs index 0c0894a58..dcf4fb481 100644 --- a/NebulaModel/Packets/Factory/Storage/StorageSyncResponsePacket.cs +++ b/NebulaModel/Packets/Factory/Storage/StorageSyncResponsePacket.cs @@ -1,18 +1,17 @@ -namespace NebulaModel.Packets.Factory.Storage -{ - public class StorageSyncResponsePacket - { - public byte[] StorageComponent { get; set; } - public int PlanetId { get; set; } - public int StorageIndex { get; set; } +namespace NebulaModel.Packets.Factory.Storage; - public StorageSyncResponsePacket() { } +public class StorageSyncResponsePacket +{ + public StorageSyncResponsePacket() { } - public StorageSyncResponsePacket(int planetId, int storageIndex, byte[] storageComponent) - { - StorageIndex = storageIndex; - StorageComponent = storageComponent; - PlanetId = planetId; - } + public StorageSyncResponsePacket(int planetId, int storageIndex, byte[] storageComponent) + { + StorageIndex = storageIndex; + StorageComponent = storageComponent; + PlanetId = planetId; } + + public byte[] StorageComponent { get; set; } + public int PlanetId { get; set; } + public int StorageIndex { get; set; } } diff --git a/NebulaModel/Packets/Factory/Storage/StorageSyncSetBansPacket.cs b/NebulaModel/Packets/Factory/Storage/StorageSyncSetBansPacket.cs index 2c1debb7a..51f26456e 100644 --- a/NebulaModel/Packets/Factory/Storage/StorageSyncSetBansPacket.cs +++ b/NebulaModel/Packets/Factory/Storage/StorageSyncSetBansPacket.cs @@ -1,18 +1,17 @@ -namespace NebulaModel.Packets.Factory.Storage -{ - public class StorageSyncSetBansPacket - { - public int StorageIndex { get; set; } - public int PlanetId { get; set; } - public int Bans { get; set; } +namespace NebulaModel.Packets.Factory.Storage; - public StorageSyncSetBansPacket() { } +public class StorageSyncSetBansPacket +{ + public StorageSyncSetBansPacket() { } - public StorageSyncSetBansPacket(int storageIndex, int planetId, int bans) - { - StorageIndex = storageIndex; - PlanetId = planetId; - Bans = bans; - } + public StorageSyncSetBansPacket(int storageIndex, int planetId, int bans) + { + StorageIndex = storageIndex; + PlanetId = planetId; + Bans = bans; } + + public int StorageIndex { get; set; } + public int PlanetId { get; set; } + public int Bans { get; set; } } diff --git a/NebulaModel/Packets/Factory/Storage/StorageSyncSortPacket.cs b/NebulaModel/Packets/Factory/Storage/StorageSyncSortPacket.cs index f4786b7f9..02a293d94 100644 --- a/NebulaModel/Packets/Factory/Storage/StorageSyncSortPacket.cs +++ b/NebulaModel/Packets/Factory/Storage/StorageSyncSortPacket.cs @@ -1,16 +1,15 @@ -namespace NebulaModel.Packets.Factory.Storage -{ - public class StorageSyncSortPacket - { - public int StorageIndex { get; set; } - public int PlanetId { get; set; } +namespace NebulaModel.Packets.Factory.Storage; - public StorageSyncSortPacket() { } +public class StorageSyncSortPacket +{ + public StorageSyncSortPacket() { } - public StorageSyncSortPacket(int storageIndex, int planetId) - { - StorageIndex = storageIndex; - PlanetId = planetId; - } + public StorageSyncSortPacket(int storageIndex, int planetId) + { + StorageIndex = storageIndex; + PlanetId = planetId; } + + public int StorageIndex { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Factory/Tank/SprayerStorageUpdatePacket.cs b/NebulaModel/Packets/Factory/Tank/SprayerStorageUpdatePacket.cs index 65ef16910..f0163c311 100644 --- a/NebulaModel/Packets/Factory/Tank/SprayerStorageUpdatePacket.cs +++ b/NebulaModel/Packets/Factory/Tank/SprayerStorageUpdatePacket.cs @@ -1,25 +1,25 @@ -namespace NebulaModel.Packets.Factory.Tank +namespace NebulaModel.Packets.Factory.Tank; + +public class SprayerStorageUpdatePacket { - public class SprayerStorageUpdatePacket - { - public int SprayerIndex { get; set; } - public int IncItemId { get; set; } - public int IncAbility { get; set; } - public int IncSprayTimes { get; set; } - public int IncCount { get; set; } - public int ExtraIncCount { get; set; } - public int PlanetId { get; set; } + public SprayerStorageUpdatePacket() { } - public SprayerStorageUpdatePacket() { } - public SprayerStorageUpdatePacket(in SpraycoaterComponent spraycoater, int planetId) - { - SprayerIndex = spraycoater.id; - IncItemId = spraycoater.incItemId; - IncAbility = spraycoater.incAbility; - IncSprayTimes = spraycoater.incSprayTimes; - IncCount = spraycoater.incCount; - ExtraIncCount = spraycoater.extraIncCount; - PlanetId = planetId; - } + public SprayerStorageUpdatePacket(in SpraycoaterComponent spraycoater, int planetId) + { + SprayerIndex = spraycoater.id; + IncItemId = spraycoater.incItemId; + IncAbility = spraycoater.incAbility; + IncSprayTimes = spraycoater.incSprayTimes; + IncCount = spraycoater.incCount; + ExtraIncCount = spraycoater.extraIncCount; + PlanetId = planetId; } + + public int SprayerIndex { get; set; } + public int IncItemId { get; set; } + public int IncAbility { get; set; } + public int IncSprayTimes { get; set; } + public int IncCount { get; set; } + public int ExtraIncCount { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Factory/Tank/TankInputOutputSwitchPacket.cs b/NebulaModel/Packets/Factory/Tank/TankInputOutputSwitchPacket.cs index 3761c94f5..278a13468 100644 --- a/NebulaModel/Packets/Factory/Tank/TankInputOutputSwitchPacket.cs +++ b/NebulaModel/Packets/Factory/Tank/TankInputOutputSwitchPacket.cs @@ -1,20 +1,19 @@ -namespace NebulaModel.Packets.Factory.Tank -{ - public class TankInputOutputSwitchPacket - { - public int TankIndex { get; set; } - public bool IsInput { get; set; } - public bool IsClosed { get; set; } - public int PlanetId { get; set; } +namespace NebulaModel.Packets.Factory.Tank; - public TankInputOutputSwitchPacket() { } +public class TankInputOutputSwitchPacket +{ + public TankInputOutputSwitchPacket() { } - public TankInputOutputSwitchPacket(int tankIndex, bool isInput, bool inClosed, int planetId) - { - TankIndex = tankIndex; - IsInput = isInput; - IsClosed = inClosed; - PlanetId = planetId; - } + public TankInputOutputSwitchPacket(int tankIndex, bool isInput, bool inClosed, int planetId) + { + TankIndex = tankIndex; + IsInput = isInput; + IsClosed = inClosed; + PlanetId = planetId; } + + public int TankIndex { get; set; } + public bool IsInput { get; set; } + public bool IsClosed { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Factory/Tank/TankStorageUpdatePacket.cs b/NebulaModel/Packets/Factory/Tank/TankStorageUpdatePacket.cs index 40c4e6fff..7c9aa07ec 100644 --- a/NebulaModel/Packets/Factory/Tank/TankStorageUpdatePacket.cs +++ b/NebulaModel/Packets/Factory/Tank/TankStorageUpdatePacket.cs @@ -1,22 +1,21 @@ -namespace NebulaModel.Packets.Factory.Tank -{ - public class TankStorageUpdatePacket - { - public int TankIndex { get; set; } - public int FluidId { get; set; } - public int FluidCount { get; set; } - public int FluidInc { get; set; } - public int PlanetId { get; set; } +namespace NebulaModel.Packets.Factory.Tank; - public TankStorageUpdatePacket() { } +public class TankStorageUpdatePacket +{ + public TankStorageUpdatePacket() { } - public TankStorageUpdatePacket(in TankComponent tankComponent, int planetId) - { - TankIndex = tankComponent.id; - FluidId = tankComponent.fluidId; - FluidCount = tankComponent.fluidCount; - FluidInc = tankComponent.fluidInc; - PlanetId = planetId; - } + public TankStorageUpdatePacket(in TankComponent tankComponent, int planetId) + { + TankIndex = tankComponent.id; + FluidId = tankComponent.fluidId; + FluidCount = tankComponent.fluidCount; + FluidInc = tankComponent.fluidInc; + PlanetId = planetId; } + + public int TankIndex { get; set; } + public int FluidId { get; set; } + public int FluidCount { get; set; } + public int FluidInc { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Factory/UpgradeEntityRequest.cs b/NebulaModel/Packets/Factory/UpgradeEntityRequest.cs index a95370cad..973b90af2 100644 --- a/NebulaModel/Packets/Factory/UpgradeEntityRequest.cs +++ b/NebulaModel/Packets/Factory/UpgradeEntityRequest.cs @@ -1,21 +1,19 @@ -using NebulaAPI; +namespace NebulaModel.Packets.Factory; -namespace NebulaModel.Packets.Factory +public class UpgradeEntityRequest { - public class UpgradeEntityRequest - { - public int PlanetId { get; set; } - public int ObjId { get; set; } - public int UpgradeProtoId { get; set; } - public int AuthorId { get; set; } + public UpgradeEntityRequest() { } - public UpgradeEntityRequest() { } - public UpgradeEntityRequest(int planetId, int objId, int upgradeProtoId, int authorId) - { - PlanetId = planetId; - ObjId = objId; - UpgradeProtoId = upgradeProtoId; - AuthorId = authorId; - } + public UpgradeEntityRequest(int planetId, int objId, int upgradeProtoId, int authorId) + { + PlanetId = planetId; + ObjId = objId; + UpgradeProtoId = upgradeProtoId; + AuthorId = authorId; } + + public int PlanetId { get; set; } + public int ObjId { get; set; } + public int UpgradeProtoId { get; set; } + public int AuthorId { get; set; } } diff --git a/NebulaModel/Packets/GameHistory/GameHistoryDataResponse.cs b/NebulaModel/Packets/GameHistory/GameHistoryDataResponse.cs index 41f9ca535..84063e03d 100644 --- a/NebulaModel/Packets/GameHistory/GameHistoryDataResponse.cs +++ b/NebulaModel/Packets/GameHistory/GameHistoryDataResponse.cs @@ -1,15 +1,15 @@ -namespace NebulaModel.Packets.GameHistory +namespace NebulaModel.Packets.GameHistory; + +public class GameHistoryDataResponse { - public class GameHistoryDataResponse - { - public byte[] HistoryBinaryData { get; set; } - public bool SandboxToolsEnabled { get; set; } + public GameHistoryDataResponse() { } - public GameHistoryDataResponse() { } - public GameHistoryDataResponse(byte[] historyBinaryData, bool sandboxToolsEnabled) - { - HistoryBinaryData = historyBinaryData; - SandboxToolsEnabled = sandboxToolsEnabled; - } + public GameHistoryDataResponse(byte[] historyBinaryData, bool sandboxToolsEnabled) + { + HistoryBinaryData = historyBinaryData; + SandboxToolsEnabled = sandboxToolsEnabled; } + + public byte[] HistoryBinaryData { get; set; } + public bool SandboxToolsEnabled { get; set; } } diff --git a/NebulaModel/Packets/GameHistory/GameHistoryEnqueueTechPacket.cs b/NebulaModel/Packets/GameHistory/GameHistoryEnqueueTechPacket.cs index 4285bd86a..dd9dd1222 100644 --- a/NebulaModel/Packets/GameHistory/GameHistoryEnqueueTechPacket.cs +++ b/NebulaModel/Packets/GameHistory/GameHistoryEnqueueTechPacket.cs @@ -1,13 +1,13 @@ -namespace NebulaModel.Packets.GameHistory +namespace NebulaModel.Packets.GameHistory; + +public class GameHistoryEnqueueTechPacket { - public class GameHistoryEnqueueTechPacket - { - public int TechId { get; set; } + public GameHistoryEnqueueTechPacket() { } - public GameHistoryEnqueueTechPacket() { } - public GameHistoryEnqueueTechPacket(int techId) - { - TechId = techId; - } + public GameHistoryEnqueueTechPacket(int techId) + { + TechId = techId; } + + public int TechId { get; set; } } diff --git a/NebulaModel/Packets/GameHistory/GameHistoryFeatureKeyPacket.cs b/NebulaModel/Packets/GameHistory/GameHistoryFeatureKeyPacket.cs index 2945eb8f9..14789b632 100644 --- a/NebulaModel/Packets/GameHistory/GameHistoryFeatureKeyPacket.cs +++ b/NebulaModel/Packets/GameHistory/GameHistoryFeatureKeyPacket.cs @@ -1,15 +1,15 @@ -namespace NebulaModel.Packets.GameHistory +namespace NebulaModel.Packets.GameHistory; + +public class GameHistoryFeatureKeyPacket { - public class GameHistoryFeatureKeyPacket - { - public int FeatureId { get; set; } - public bool Add { get; set; } + public GameHistoryFeatureKeyPacket() { } - public GameHistoryFeatureKeyPacket() { } - public GameHistoryFeatureKeyPacket(int featureId, bool add) - { - FeatureId = featureId; - Add = add; - } + public GameHistoryFeatureKeyPacket(int featureId, bool add) + { + FeatureId = featureId; + Add = add; } + + public int FeatureId { get; set; } + public bool Add { get; set; } } diff --git a/NebulaModel/Packets/GameHistory/GameHistoryNotificationPacket.cs b/NebulaModel/Packets/GameHistory/GameHistoryNotificationPacket.cs index 4e990cc4b..02523fa5e 100644 --- a/NebulaModel/Packets/GameHistory/GameHistoryNotificationPacket.cs +++ b/NebulaModel/Packets/GameHistory/GameHistoryNotificationPacket.cs @@ -1,20 +1,20 @@ -namespace NebulaModel.Packets.GameHistory -{ - public class GameHistoryNotificationPacket - { - public GameHistoryEvent Event { get; set; } +namespace NebulaModel.Packets.GameHistory; - public GameHistoryNotificationPacket() { } - public GameHistoryNotificationPacket(GameHistoryEvent Event) - { - this.Event = Event; - } - } +public class GameHistoryNotificationPacket +{ + public GameHistoryNotificationPacket() { } - public enum GameHistoryEvent + public GameHistoryNotificationPacket(GameHistoryEvent Event) { - PauseQueue = 1, - ResumeQueue = 2, - OneKeyUnlock = 3 + this.Event = Event; } + + public GameHistoryEvent Event { get; set; } +} + +public enum GameHistoryEvent +{ + PauseQueue = 1, + ResumeQueue = 2, + OneKeyUnlock = 3 } diff --git a/NebulaModel/Packets/GameHistory/GameHistoryRemoveTechPacket.cs b/NebulaModel/Packets/GameHistory/GameHistoryRemoveTechPacket.cs index e32ffc86c..f65335938 100644 --- a/NebulaModel/Packets/GameHistory/GameHistoryRemoveTechPacket.cs +++ b/NebulaModel/Packets/GameHistory/GameHistoryRemoveTechPacket.cs @@ -1,14 +1,13 @@ -namespace NebulaModel.Packets.GameHistory -{ - public class GameHistoryRemoveTechPacket - { - public int TechId { get; set; } +namespace NebulaModel.Packets.GameHistory; - public GameHistoryRemoveTechPacket() { } +public class GameHistoryRemoveTechPacket +{ + public GameHistoryRemoveTechPacket() { } - public GameHistoryRemoveTechPacket(int techId) - { - TechId = techId; - } + public GameHistoryRemoveTechPacket(int techId) + { + TechId = techId; } -} \ No newline at end of file + + public int TechId { get; set; } +} diff --git a/NebulaModel/Packets/GameHistory/GameHistoryResearchContributionPacket.cs b/NebulaModel/Packets/GameHistory/GameHistoryResearchContributionPacket.cs index a2431ebb5..07a39d7c6 100644 --- a/NebulaModel/Packets/GameHistory/GameHistoryResearchContributionPacket.cs +++ b/NebulaModel/Packets/GameHistory/GameHistoryResearchContributionPacket.cs @@ -1,16 +1,15 @@ -namespace NebulaModel.Packets.GameHistory -{ - public class GameHistoryResearchContributionPacket - { - public long Hashes { get; set; } - public int TechId { get; set; } +namespace NebulaModel.Packets.GameHistory; - public GameHistoryResearchContributionPacket() { } +public class GameHistoryResearchContributionPacket +{ + public GameHistoryResearchContributionPacket() { } - public GameHistoryResearchContributionPacket(long hashes, int techId) - { - Hashes = hashes; - TechId = techId; - } + public GameHistoryResearchContributionPacket(long hashes, int techId) + { + Hashes = hashes; + TechId = techId; } + + public long Hashes { get; set; } + public int TechId { get; set; } } diff --git a/NebulaModel/Packets/GameHistory/GameHistoryResearchUpdatePacket.cs b/NebulaModel/Packets/GameHistory/GameHistoryResearchUpdatePacket.cs index 32ab0c278..be517afde 100644 --- a/NebulaModel/Packets/GameHistory/GameHistoryResearchUpdatePacket.cs +++ b/NebulaModel/Packets/GameHistory/GameHistoryResearchUpdatePacket.cs @@ -1,20 +1,19 @@ -namespace NebulaModel.Packets.GameHistory -{ - public class GameHistoryResearchUpdatePacket - { - public int TechId { get; set; } - public long HashUploaded { get; set; } - public long HashNeeded { get; set; } - public int TechHashedFor10Frames { get; set; } +namespace NebulaModel.Packets.GameHistory; - public GameHistoryResearchUpdatePacket() { } +public class GameHistoryResearchUpdatePacket +{ + public GameHistoryResearchUpdatePacket() { } - public GameHistoryResearchUpdatePacket(int techId, long hashUploaded, long hashNeeded, int techHashedFor10Frames) - { - TechId = techId; - HashUploaded = hashUploaded; - HashNeeded = hashNeeded; - TechHashedFor10Frames = techHashedFor10Frames; - } + public GameHistoryResearchUpdatePacket(int techId, long hashUploaded, long hashNeeded, int techHashedFor10Frames) + { + TechId = techId; + HashUploaded = hashUploaded; + HashNeeded = hashNeeded; + TechHashedFor10Frames = techHashedFor10Frames; } + + public int TechId { get; set; } + public long HashUploaded { get; set; } + public long HashNeeded { get; set; } + public int TechHashedFor10Frames { get; set; } } diff --git a/NebulaModel/Packets/GameHistory/GameHistoryTechRefundPacket.cs b/NebulaModel/Packets/GameHistory/GameHistoryTechRefundPacket.cs index d675c53ba..7fdbcf9aa 100644 --- a/NebulaModel/Packets/GameHistory/GameHistoryTechRefundPacket.cs +++ b/NebulaModel/Packets/GameHistory/GameHistoryTechRefundPacket.cs @@ -1,16 +1,15 @@ -namespace NebulaModel.Packets.GameHistory -{ - public class GameHistoryTechRefundPacket - { - public int TechIdContributed { get; set; } - public long TechHashedContributed { get; set; } +namespace NebulaModel.Packets.GameHistory; - public GameHistoryTechRefundPacket() { } +public class GameHistoryTechRefundPacket +{ + public GameHistoryTechRefundPacket() { } - public GameHistoryTechRefundPacket(int techId, long contributed) - { - TechIdContributed = techId; - TechHashedContributed = contributed; - } + public GameHistoryTechRefundPacket(int techId, long contributed) + { + TechIdContributed = techId; + TechHashedContributed = contributed; } + + public int TechIdContributed { get; set; } + public long TechHashedContributed { get; set; } } diff --git a/NebulaModel/Packets/GameHistory/GameHistoryUnlockTechPacket.cs b/NebulaModel/Packets/GameHistory/GameHistoryUnlockTechPacket.cs index 0bb1a41b5..300662bd2 100644 --- a/NebulaModel/Packets/GameHistory/GameHistoryUnlockTechPacket.cs +++ b/NebulaModel/Packets/GameHistory/GameHistoryUnlockTechPacket.cs @@ -1,15 +1,15 @@ -namespace NebulaModel.Packets.GameHistory +namespace NebulaModel.Packets.GameHistory; + +public class GameHistoryUnlockTechPacket { - public class GameHistoryUnlockTechPacket - { - public int TechId { get; set; } - public int Level { get; set; } + public GameHistoryUnlockTechPacket() { } - public GameHistoryUnlockTechPacket() { } - public GameHistoryUnlockTechPacket(int techId, int level) - { - TechId = techId; - Level = level; - } + public GameHistoryUnlockTechPacket(int techId, int level) + { + TechId = techId; + Level = level; } + + public int TechId { get; set; } + public int Level { get; set; } } diff --git a/NebulaModel/Packets/GameStates/FragmentInfo.cs b/NebulaModel/Packets/GameStates/FragmentInfo.cs index 971e10cdf..2966d8a36 100644 --- a/NebulaModel/Packets/GameStates/FragmentInfo.cs +++ b/NebulaModel/Packets/GameStates/FragmentInfo.cs @@ -1,13 +1,13 @@ -namespace NebulaModel.Packets.GameStates +namespace NebulaModel.Packets.GameStates; + +public class FragmentInfo { - public class FragmentInfo - { - public int Size { get; set; } + public FragmentInfo() { } - public FragmentInfo() { } - public FragmentInfo(int size) - { - Size = size; - } + public FragmentInfo(int size) + { + Size = size; } + + public int Size { get; set; } } diff --git a/NebulaModel/Packets/GameStates/GameStateRequest.cs b/NebulaModel/Packets/GameStates/GameStateRequest.cs index 3793ff8fd..2ef0e1543 100644 --- a/NebulaModel/Packets/GameStates/GameStateRequest.cs +++ b/NebulaModel/Packets/GameStates/GameStateRequest.cs @@ -1,16 +1,19 @@ -using NebulaAPI; +#region + using System; +using NebulaAPI; + +#endregion + +namespace NebulaModel.Packets.GameStates; -namespace NebulaModel.Packets.GameStates +[HidePacketInDebugLogs] +public class GameStateRequest { - [HidePacketInDebugLogs] - public class GameStateRequest + public GameStateRequest() { - public long SentTimestamp { get; set; } - - public GameStateRequest() - { - SentTimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); - } + SentTimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); } + + public long SentTimestamp { get; set; } } diff --git a/NebulaModel/Packets/GameStates/GameStateUpdate.cs b/NebulaModel/Packets/GameStates/GameStateUpdate.cs index 8bc6e0729..0c4d25768 100644 --- a/NebulaModel/Packets/GameStates/GameStateUpdate.cs +++ b/NebulaModel/Packets/GameStates/GameStateUpdate.cs @@ -1,21 +1,24 @@ -using NebulaAPI; -using NebulaModel.DataStructures; +#region -namespace NebulaModel.Packets.GameStates +using NebulaAPI; + +#endregion + +namespace NebulaModel.Packets.GameStates; + +[HidePacketInDebugLogs] +public class GameStateUpdate { - [HidePacketInDebugLogs] - public class GameStateUpdate - { - public long SentTime { get; set; } - public long GameTick { get; set; } - public float UnitsPerSecond { get; set; } + public GameStateUpdate() { } - public GameStateUpdate() { } - public GameStateUpdate(long sentTime, long gameTick, float unitsPerSecond) - { - SentTime = sentTime; - GameTick = gameTick; - UnitsPerSecond = unitsPerSecond; - } + public GameStateUpdate(long sentTime, long gameTick, float unitsPerSecond) + { + SentTime = sentTime; + GameTick = gameTick; + UnitsPerSecond = unitsPerSecond; } + + public long SentTime { get; set; } + public long GameTick { get; set; } + public float UnitsPerSecond { get; set; } } diff --git a/NebulaModel/Packets/Logistics/DispenserAddTakePacket.cs b/NebulaModel/Packets/Logistics/DispenserAddTakePacket.cs index 35612ec3a..7350113ab 100644 --- a/NebulaModel/Packets/Logistics/DispenserAddTakePacket.cs +++ b/NebulaModel/Packets/Logistics/DispenserAddTakePacket.cs @@ -1,32 +1,33 @@ -namespace NebulaModel.Packets.Logistics -{ - public class DispenserAddTakePacket - { - public int PlanetId { get; set; } - public int EntityId { get; set; } - public EDispenserAddTakeEvent AddTakeEvent { get; set; } - public int ItemId { get; set; } - public int ItemCount { get; set; } - public int ItemInc { get; set; } +namespace NebulaModel.Packets.Logistics; - public DispenserAddTakePacket() { } - public DispenserAddTakePacket(int planetId, int entityId, EDispenserAddTakeEvent addTakeEvent, int itemId, int itemCount, int itemInc) - { - PlanetId = planetId; - EntityId = entityId; - AddTakeEvent = addTakeEvent; - ItemId = itemId; - ItemCount = itemCount; - ItemInc = itemInc; - } - } +public class DispenserAddTakePacket +{ + public DispenserAddTakePacket() { } - public enum EDispenserAddTakeEvent + public DispenserAddTakePacket(int planetId, int entityId, EDispenserAddTakeEvent addTakeEvent, int itemId, int itemCount, + int itemInc) { - None, - ManualAdd, - ManualTake, - CourierAdd, - CourierTake + PlanetId = planetId; + EntityId = entityId; + AddTakeEvent = addTakeEvent; + ItemId = itemId; + ItemCount = itemCount; + ItemInc = itemInc; } + + public int PlanetId { get; set; } + public int EntityId { get; set; } + public EDispenserAddTakeEvent AddTakeEvent { get; set; } + public int ItemId { get; set; } + public int ItemCount { get; set; } + public int ItemInc { get; set; } +} + +public enum EDispenserAddTakeEvent +{ + None, + ManualAdd, + ManualTake, + CourierAdd, + CourierTake } diff --git a/NebulaModel/Packets/Logistics/DispenserCourierPacket.cs b/NebulaModel/Packets/Logistics/DispenserCourierPacket.cs index e7780b629..b93007a7a 100644 --- a/NebulaModel/Packets/Logistics/DispenserCourierPacket.cs +++ b/NebulaModel/Packets/Logistics/DispenserCourierPacket.cs @@ -1,21 +1,21 @@ -namespace NebulaModel.Packets.Logistics +namespace NebulaModel.Packets.Logistics; + +public class DispenserCourierPacket { - public class DispenserCourierPacket - { - public int PlanetId { get; set; } - public int PlayerId { get; set; } - public int DispenserId { get; set; } - public int ItemId { get; set; } - public int ItemCount { get; set; } + public DispenserCourierPacket() { } - public DispenserCourierPacket() { } - public DispenserCourierPacket(int planetId, int playerId, int dispenserId, int itemId, int itemCount) - { - PlanetId = planetId; - PlayerId = playerId; - DispenserId = dispenserId; - ItemId = itemId; - ItemCount = itemCount; - } + public DispenserCourierPacket(int planetId, int playerId, int dispenserId, int itemId, int itemCount) + { + PlanetId = planetId; + PlayerId = playerId; + DispenserId = dispenserId; + ItemId = itemId; + ItemCount = itemCount; } + + public int PlanetId { get; set; } + public int PlayerId { get; set; } + public int DispenserId { get; set; } + public int ItemId { get; set; } + public int ItemCount { get; set; } } diff --git a/NebulaModel/Packets/Logistics/DispenserSettingPacket.cs b/NebulaModel/Packets/Logistics/DispenserSettingPacket.cs index 5a2fcecd8..0a6dcfb23 100644 --- a/NebulaModel/Packets/Logistics/DispenserSettingPacket.cs +++ b/NebulaModel/Packets/Logistics/DispenserSettingPacket.cs @@ -1,30 +1,30 @@ -namespace NebulaModel.Packets.Logistics -{ - public class DispenserSettingPacket - { - public int PlanetId { get; set; } - public int DispenserId { get; set; } - public EDispenserSettingEvent Event { get; set; } - public int Parameter1 { get; set; } +namespace NebulaModel.Packets.Logistics; - public DispenserSettingPacket() { } - public DispenserSettingPacket(int planetId, int dispenserId, EDispenserSettingEvent settingEvent, int parameter1) - { - PlanetId = planetId; - DispenserId = dispenserId; - Event = settingEvent; - Parameter1 = parameter1; - } - } +public class DispenserSettingPacket +{ + public DispenserSettingPacket() { } - public enum EDispenserSettingEvent + public DispenserSettingPacket(int planetId, int dispenserId, EDispenserSettingEvent settingEvent, int parameter1) { - None, - SetCourierCount, // CourierIconClick - ToggleAutoReplenish, // CourierAutoReplenishButtonClick - SetMaxChargePower, // MaxChargePowerSliderValueChange - SetFilter, // GuessFilterButtonClick, OnItemPickerReturn, OnTakeBackButtonClick - SetPlayerDeliveryMode, // ModeSwitchClicked - SetStorageDeliveryMode // ModeToggleClicked + PlanetId = planetId; + DispenserId = dispenserId; + Event = settingEvent; + Parameter1 = parameter1; } + + public int PlanetId { get; set; } + public int DispenserId { get; set; } + public EDispenserSettingEvent Event { get; set; } + public int Parameter1 { get; set; } +} + +public enum EDispenserSettingEvent +{ + None, + SetCourierCount, // CourierIconClick + ToggleAutoReplenish, // CourierAutoReplenishButtonClick + SetMaxChargePower, // MaxChargePowerSliderValueChange + SetFilter, // GuessFilterButtonClick, OnItemPickerReturn, OnTakeBackButtonClick + SetPlayerDeliveryMode, // ModeSwitchClicked + SetStorageDeliveryMode // ModeToggleClicked } diff --git a/NebulaModel/Packets/Logistics/DispenserStorePacket.cs b/NebulaModel/Packets/Logistics/DispenserStorePacket.cs index f084a46b4..aa6cfccce 100644 --- a/NebulaModel/Packets/Logistics/DispenserStorePacket.cs +++ b/NebulaModel/Packets/Logistics/DispenserStorePacket.cs @@ -1,29 +1,29 @@ -namespace NebulaModel.Packets.Logistics +namespace NebulaModel.Packets.Logistics; + +public class DispenserStorePacket { - public class DispenserStorePacket - { - public int PlanetId { get; set; } - public int DispenserId { get; set; } - public int HoldupItemCount { get; set; } - public int[] ItemIds { get; set; } - public int[] Counts { get; set; } - public int[] Incs { get; set; } + public DispenserStorePacket() { } - public DispenserStorePacket() { } - public DispenserStorePacket(int planetId, in DispenserComponent dispenser) + public DispenserStorePacket(int planetId, in DispenserComponent dispenser) + { + PlanetId = planetId; + DispenserId = dispenser.id; + HoldupItemCount = dispenser.holdupItemCount; + ItemIds = new int[HoldupItemCount]; + Counts = new int[HoldupItemCount]; + Incs = new int[HoldupItemCount]; + for (var i = 0; i < HoldupItemCount; i++) { - PlanetId = planetId; - DispenserId = dispenser.id; - HoldupItemCount = dispenser.holdupItemCount; - ItemIds = new int[HoldupItemCount]; - Counts = new int[HoldupItemCount]; - Incs = new int[HoldupItemCount]; - for (int i = 0; i < HoldupItemCount; i++) - { - ItemIds[i] = dispenser.holdupPackage[i].itemId; - Counts[i] = dispenser.holdupPackage[i].count; - Incs[i] = dispenser.holdupPackage[i].inc; - } + ItemIds[i] = dispenser.holdupPackage[i].itemId; + Counts[i] = dispenser.holdupPackage[i].count; + Incs[i] = dispenser.holdupPackage[i].inc; } } + + public int PlanetId { get; set; } + public int DispenserId { get; set; } + public int HoldupItemCount { get; set; } + public int[] ItemIds { get; set; } + public int[] Counts { get; set; } + public int[] Incs { get; set; } } diff --git a/NebulaModel/Packets/Logistics/ILSAddStationComponent.cs b/NebulaModel/Packets/Logistics/ILSAddStationComponent.cs index aa4d7bd94..3e35fb258 100644 --- a/NebulaModel/Packets/Logistics/ILSAddStationComponent.cs +++ b/NebulaModel/Packets/Logistics/ILSAddStationComponent.cs @@ -1,20 +1,20 @@ -namespace NebulaModel.Packets.Logistics +namespace NebulaModel.Packets.Logistics; + +public class ILSAddStationComponent { - public class ILSAddStationComponent + public ILSAddStationComponent() { } + + public ILSAddStationComponent(int planetId, int stationId, int stationGId, int maxShipCount) { - public int PlanetId { get; set; } - public int StationId { get; set; } - public int StationGId { get; set; } - - public int MaxShipCount { get; set; } - - public ILSAddStationComponent() { } - public ILSAddStationComponent(int planetId, int stationId, int stationGId, int maxShipCount) - { - StationGId = stationGId; - PlanetId = planetId; - StationId = stationId; - MaxShipCount = maxShipCount; - } + StationGId = stationGId; + PlanetId = planetId; + StationId = stationId; + MaxShipCount = maxShipCount; } + + public int PlanetId { get; set; } + public int StationId { get; set; } + public int StationGId { get; set; } + + public int MaxShipCount { get; set; } } diff --git a/NebulaModel/Packets/Logistics/ILSArriveStarPlanetRequest.cs b/NebulaModel/Packets/Logistics/ILSArriveStarPlanetRequest.cs index e790d65ce..1ab25a593 100644 --- a/NebulaModel/Packets/Logistics/ILSArriveStarPlanetRequest.cs +++ b/NebulaModel/Packets/Logistics/ILSArriveStarPlanetRequest.cs @@ -1,16 +1,13 @@ -/* - * when a client arrives at a star he requests the current storages from all ILS in that system - * this will also sync the belt filters - */ -namespace NebulaModel.Packets.Logistics +namespace NebulaModel.Packets.Logistics; + +public class ILSArriveStarPlanetRequest { - public class ILSArriveStarPlanetRequest + public ILSArriveStarPlanetRequest() { } + + public ILSArriveStarPlanetRequest(int starId) { - public int StarId { get; set; } - public ILSArriveStarPlanetRequest() { } - public ILSArriveStarPlanetRequest(int starId) - { - StarId = starId; - } + StarId = starId; } + + public int StarId { get; set; } } diff --git a/NebulaModel/Packets/Logistics/ILSArriveStarPlanetResponse.cs b/NebulaModel/Packets/Logistics/ILSArriveStarPlanetResponse.cs index 311e222ec..ba31ce56b 100644 --- a/NebulaModel/Packets/Logistics/ILSArriveStarPlanetResponse.cs +++ b/NebulaModel/Packets/Logistics/ILSArriveStarPlanetResponse.cs @@ -1,40 +1,38 @@ -/* - * see request for info - */ -namespace NebulaModel.Packets.Logistics +namespace NebulaModel.Packets.Logistics; + +public class ILSArriveStarPlanetResponse { - public class ILSArriveStarPlanetResponse + public ILSArriveStarPlanetResponse() { } + + public ILSArriveStarPlanetResponse(int[] stationGId, + int[] planetId, + int[] stationMaxShips, + int[] storageLength, + int[] storageIdx, + int[] slotLength, + int[] itemId, + int[] count, + int[] inc) { - public int[] StationGId { get; set; } - public int[] StationPId { get; set; } - - public int[] StationMaxShips { get; set; } - public int[] StorageLength { get; set; } - public int[] SlotLength { get; set; } - public int[] StorageIdx { get; set; } - public int[] ItemId { get; set; } - public int[] Count { get; set; } - public int[] Inc { get; set; } - public ILSArriveStarPlanetResponse() { } - public ILSArriveStarPlanetResponse(int[] stationGId, - int[] planetId, - int[] stationMaxShips, - int[] storageLength, - int[] storageIdx, - int[] slotLength, - int[] itemId, - int[] count, - int[] inc) - { - StationGId = stationGId; - StationPId = planetId; - StationMaxShips = stationMaxShips; - StorageLength = storageLength; - StorageIdx = storageIdx; - SlotLength = slotLength; - ItemId = itemId; - Count = count; - Inc = inc; - } + StationGId = stationGId; + StationPId = planetId; + StationMaxShips = stationMaxShips; + StorageLength = storageLength; + StorageIdx = storageIdx; + SlotLength = slotLength; + ItemId = itemId; + Count = count; + Inc = inc; } + + public int[] StationGId { get; set; } + public int[] StationPId { get; set; } + + public int[] StationMaxShips { get; set; } + public int[] StorageLength { get; set; } + public int[] SlotLength { get; set; } + public int[] StorageIdx { get; set; } + public int[] ItemId { get; set; } + public int[] Count { get; set; } + public int[] Inc { get; set; } } diff --git a/NebulaModel/Packets/Logistics/ILSIdleShipBackToWork.cs b/NebulaModel/Packets/Logistics/ILSIdleShipBackToWork.cs index 6f3659afa..55467a598 100644 --- a/NebulaModel/Packets/Logistics/ILSIdleShipBackToWork.cs +++ b/NebulaModel/Packets/Logistics/ILSIdleShipBackToWork.cs @@ -1,35 +1,35 @@ -namespace NebulaModel.Packets.Logistics +namespace NebulaModel.Packets.Logistics; + +public class ILSIdleShipBackToWork { - public class ILSIdleShipBackToWork - { - public int ThisGId { get; set; } - public int PlanetA { get; set; } - public int PlanetB { get; set; } - public int OtherGId { get; set; } - public int ItemId { get; set; } - public int ItemCount { get; set; } - public int Inc { get; set; } - public int Gene { get; set; } - public int ShipIndex { get; set; } - public int ShipWarperCount { get; set; } - public int StationMaxShipCount { get; set; } - public int StationWarperCount { get; set; } + public ILSIdleShipBackToWork() { } - public ILSIdleShipBackToWork() { } - public ILSIdleShipBackToWork(ShipData ShipData, int thisGId, int stationMaxShipCount, int stationWarperCount) - { - ThisGId = thisGId; - PlanetA = ShipData.planetA; - PlanetB = ShipData.planetB; - OtherGId = ShipData.otherGId; - ItemId = ShipData.itemId; - ItemCount = ShipData.itemCount; - Inc = ShipData.inc; - Gene = ShipData.gene; - ShipIndex = ShipData.shipIndex; - ShipWarperCount = ShipData.warperCnt; - StationMaxShipCount = stationMaxShipCount; - StationWarperCount = stationWarperCount; - } + public ILSIdleShipBackToWork(ShipData ShipData, int thisGId, int stationMaxShipCount, int stationWarperCount) + { + ThisGId = thisGId; + PlanetA = ShipData.planetA; + PlanetB = ShipData.planetB; + OtherGId = ShipData.otherGId; + ItemId = ShipData.itemId; + ItemCount = ShipData.itemCount; + Inc = ShipData.inc; + Gene = ShipData.gene; + ShipIndex = ShipData.shipIndex; + ShipWarperCount = ShipData.warperCnt; + StationMaxShipCount = stationMaxShipCount; + StationWarperCount = stationWarperCount; } + + public int ThisGId { get; set; } + public int PlanetA { get; set; } + public int PlanetB { get; set; } + public int OtherGId { get; set; } + public int ItemId { get; set; } + public int ItemCount { get; set; } + public int Inc { get; set; } + public int Gene { get; set; } + public int ShipIndex { get; set; } + public int ShipWarperCount { get; set; } + public int StationMaxShipCount { get; set; } + public int StationWarperCount { get; set; } } diff --git a/NebulaModel/Packets/Logistics/ILSRematchRemotePairs.cs b/NebulaModel/Packets/Logistics/ILSRematchRemotePairs.cs index aa53c5cae..7e9589358 100644 --- a/NebulaModel/Packets/Logistics/ILSRematchRemotePairs.cs +++ b/NebulaModel/Packets/Logistics/ILSRematchRemotePairs.cs @@ -1,24 +1,27 @@ -using System; +#region + using System.Collections.Generic; -namespace NebulaModel.Packets.Logistics +#endregion + +namespace NebulaModel.Packets.Logistics; + +public class ILSRematchRemotePairs { - public class ILSRematchRemotePairs - { - public int GId { get; set; } - public int[] ShipIndex { get; set; } - public int[] OtherGId { get; set; } - public int[] Direction { get; set; } - public int[] ItemId { get; set; } + public ILSRematchRemotePairs() { } - public ILSRematchRemotePairs() { } - public ILSRematchRemotePairs(int gid, List shipIndex, List otherGId, List direction, List itemId) - { - this.GId = gid; - ShipIndex = shipIndex.ToArray(); - OtherGId = otherGId.ToArray(); - Direction = direction.ToArray(); - ItemId = itemId.ToArray(); - } + public ILSRematchRemotePairs(int gid, List shipIndex, List otherGId, List direction, List itemId) + { + GId = gid; + ShipIndex = shipIndex.ToArray(); + OtherGId = otherGId.ToArray(); + Direction = direction.ToArray(); + ItemId = itemId.ToArray(); } + + public int GId { get; set; } + public int[] ShipIndex { get; set; } + public int[] OtherGId { get; set; } + public int[] Direction { get; set; } + public int[] ItemId { get; set; } } diff --git a/NebulaModel/Packets/Logistics/ILSRemoveStationComponent.cs b/NebulaModel/Packets/Logistics/ILSRemoveStationComponent.cs index c262d080d..6d4b435bb 100644 --- a/NebulaModel/Packets/Logistics/ILSRemoveStationComponent.cs +++ b/NebulaModel/Packets/Logistics/ILSRemoveStationComponent.cs @@ -1,16 +1,17 @@ -namespace NebulaModel.Packets.Logistics +namespace NebulaModel.Packets.Logistics; + +public class ILSRemoveStationComponent { - public class ILSRemoveStationComponent + public ILSRemoveStationComponent() { } + + public ILSRemoveStationComponent(int stationId, int planetId, int stationGId) { - public int StationId { get; set; } - public int PlanetId { get; set; } - public int StationGId { get; set; } - public ILSRemoveStationComponent() { } - public ILSRemoveStationComponent(int stationId, int planetId, int stationGId) - { - StationId = stationId; - PlanetId = planetId; - StationGId = stationGId; - } + StationId = stationId; + PlanetId = planetId; + StationGId = stationGId; } + + public int StationId { get; set; } + public int PlanetId { get; set; } + public int StationGId { get; set; } } diff --git a/NebulaModel/Packets/Logistics/ILSRequestShipDock.cs b/NebulaModel/Packets/Logistics/ILSRequestShipDock.cs index cf75a376f..fbd6460e9 100644 --- a/NebulaModel/Packets/Logistics/ILSRequestShipDock.cs +++ b/NebulaModel/Packets/Logistics/ILSRequestShipDock.cs @@ -1,12 +1,13 @@ -namespace NebulaModel.Packets.Logistics +namespace NebulaModel.Packets.Logistics; + +public class ILSRequestShipDock { - public class ILSRequestShipDock + public ILSRequestShipDock() { } + + public ILSRequestShipDock(int stationGId) { - public int StationGId { get; set; } - public ILSRequestShipDock() { } - public ILSRequestShipDock(int stationGId) - { - StationGId = stationGId; - } + StationGId = stationGId; } + + public int StationGId { get; set; } } diff --git a/NebulaModel/Packets/Logistics/ILSRequestgStationPoolSync.cs b/NebulaModel/Packets/Logistics/ILSRequestgStationPoolSync.cs index b49aab6d6..f0bc9aa5a 100644 --- a/NebulaModel/Packets/Logistics/ILSRequestgStationPoolSync.cs +++ b/NebulaModel/Packets/Logistics/ILSRequestgStationPoolSync.cs @@ -1,7 +1,5 @@ -namespace NebulaModel.Packets.Logistics +namespace NebulaModel.Packets.Logistics; + +public class ILSRequestgStationPoolSync { - public class ILSRequestgStationPoolSync - { - public ILSRequestgStationPoolSync() { } - } } diff --git a/NebulaModel/Packets/Logistics/ILSShipAddTake.cs b/NebulaModel/Packets/Logistics/ILSShipAddTake.cs index 104157ddf..ebf723cf3 100644 --- a/NebulaModel/Packets/Logistics/ILSShipAddTake.cs +++ b/NebulaModel/Packets/Logistics/ILSShipAddTake.cs @@ -1,24 +1,24 @@ -namespace NebulaModel.Packets.Logistics +namespace NebulaModel.Packets.Logistics; + +// This packet is only used to tell clients about AddItem() and TakeItem() calls in InternalTickRemote() of host +// there are other places where items are added/taken from storage in that method but they have their own packet +// there is alos a different packet for updates regarding remoteOrder as it only needs to be sent to the planets where the corresponding two ILS are. +public class ILSShipAddTake { - // This packet is only used to tell clients about AddItem() and TakeItem() calls in InternalTickRemote() of host - // there are other places where items are added/taken from storage in that method but they have their own packet - // there is alos a different packet for updates regarding remoteOrder as it only needs to be sent to the planets where the corresponding two ILS are. - public class ILSShipAddTake - { - public bool AddItem { get; set; } - public int ItemId { get; set; } - public int ItemCount { get; set; } - public int StationGID { get; set; } - public int Inc { get; set; } // if TakeItem() is called this holds the workShipDatas index needed to update the ShipData + public ILSShipAddTake() { } - public ILSShipAddTake() { } - public ILSShipAddTake(bool addItem, int itemId, int itemCount, int stationGID, int inc) - { - AddItem = addItem; - ItemId = itemId; - ItemCount = itemCount; - StationGID = stationGID; - Inc = inc; - } + public ILSShipAddTake(bool addItem, int itemId, int itemCount, int stationGID, int inc) + { + AddItem = addItem; + ItemId = itemId; + ItemCount = itemCount; + StationGID = stationGID; + Inc = inc; } + + public bool AddItem { get; set; } + public int ItemId { get; set; } + public int ItemCount { get; set; } + public int StationGID { get; set; } + public int Inc { get; set; } // if TakeItem() is called this holds the workShipDatas index needed to update the ShipData } diff --git a/NebulaModel/Packets/Logistics/ILSShipDock.cs b/NebulaModel/Packets/Logistics/ILSShipDock.cs index c74da23b8..6997f29e8 100644 --- a/NebulaModel/Packets/Logistics/ILSShipDock.cs +++ b/NebulaModel/Packets/Logistics/ILSShipDock.cs @@ -1,36 +1,49 @@ -using NebulaAPI; +#region + +using NebulaAPI; using UnityEngine; -namespace NebulaModel.Packets.Logistics +#endregion + +namespace NebulaModel.Packets.Logistics; + +public class ILSShipDock { - public class ILSShipDock + public ILSShipDock() { } + + // Update ship position and rotation with the host values + // as they are computed based on dock pos and rot + // and may be computed wrong before client received that information + // so we correct that here + public ILSShipDock(int stationGId, Vector3 shipDockPos, Quaternion shipDockRot, int[] shipOtherGId, int[] shipIndex, + Double3[] shipPos, Float4[] shipRot, Double3[] shipPPosTemp, Float4[] shipPRotTemp) { - public int stationGId { get; set; } - public Float3 shipDockPos { get; set; } - public Float4 shipDockRot { get; set; } - public int[] shipOtherGId { get; set; } // this is the GId of the station the ship belongs to (as stationGId points to the station that the ship has as otherGId) - public int[] shipIndex { get; set; } - public Double3[] shipPos { get; set; } - public Float4[] shipRot { get; set; } - public Double3[] shipPPosTemp { get; set; } - public Float4[] shipPRotTemp { get; set; } - public ILSShipDock() { } - // Update ship position and rotation with the host values - // as they are computed based on dock pos and rot - // and may be computed wrong before client received that information - // so we correct that here - public ILSShipDock(int stationGId, Vector3 shipDockPos, Quaternion shipDockRot, int[] shipOtherGId, int[] shipIndex, Double3[] shipPos, Float4[] shipRot, Double3[] shipPPosTemp, Float4[] shipPRotTemp) - { - this.stationGId = stationGId; - this.shipDockPos = new Float3(shipDockPos); - this.shipDockRot = new Float4(shipDockRot); - - this.shipOtherGId = shipOtherGId; - this.shipIndex = shipIndex; - this.shipPos = shipPos; - this.shipRot = shipRot; - this.shipPPosTemp = shipPPosTemp; - this.shipPRotTemp = shipPRotTemp; - } + this.stationGId = stationGId; + this.shipDockPos = new Float3(shipDockPos); + this.shipDockRot = new Float4(shipDockRot); + + this.shipOtherGId = shipOtherGId; + this.shipIndex = shipIndex; + this.shipPos = shipPos; + this.shipRot = shipRot; + this.shipPPosTemp = shipPPosTemp; + this.shipPRotTemp = shipPRotTemp; } + + public int stationGId { get; set; } + public Float3 shipDockPos { get; set; } + public Float4 shipDockRot { get; set; } + + public int[] + shipOtherGId + { + get; + set; + } // this is the GId of the station the ship belongs to (as stationGId points to the station that the ship has as otherGId) + + public int[] shipIndex { get; set; } + public Double3[] shipPos { get; set; } + public Float4[] shipRot { get; set; } + public Double3[] shipPPosTemp { get; set; } + public Float4[] shipPRotTemp { get; set; } } diff --git a/NebulaModel/Packets/Logistics/ILSShipEnterWarp.cs b/NebulaModel/Packets/Logistics/ILSShipEnterWarp.cs index 59dd24d03..f86abd216 100644 --- a/NebulaModel/Packets/Logistics/ILSShipEnterWarp.cs +++ b/NebulaModel/Packets/Logistics/ILSShipEnterWarp.cs @@ -1,14 +1,15 @@ -namespace NebulaModel.Packets.Logistics +namespace NebulaModel.Packets.Logistics; + +public class ILSShipEnterWarp { - public class ILSShipEnterWarp + public ILSShipEnterWarp() { } + + public ILSShipEnterWarp(int thisGId, int workShipIndex) { - public int ThisGId { get; set; } - public int WorkShipIndex { get; set; } - public ILSShipEnterWarp() { } - public ILSShipEnterWarp(int thisGId, int workShipIndex) - { - ThisGId = thisGId; - WorkShipIndex = workShipIndex; - } + ThisGId = thisGId; + WorkShipIndex = workShipIndex; } + + public int ThisGId { get; set; } + public int WorkShipIndex { get; set; } } diff --git a/NebulaModel/Packets/Logistics/ILSUpdateSlotData.cs b/NebulaModel/Packets/Logistics/ILSUpdateSlotData.cs index 5fcf07c95..e5f00969b 100644 --- a/NebulaModel/Packets/Logistics/ILSUpdateSlotData.cs +++ b/NebulaModel/Packets/Logistics/ILSUpdateSlotData.cs @@ -1,20 +1,21 @@ -namespace NebulaModel.Packets.Logistics +namespace NebulaModel.Packets.Logistics; + +public class ILSUpdateSlotData { - public class ILSUpdateSlotData + public ILSUpdateSlotData() { } + + public ILSUpdateSlotData(int planetId, int stationId, int stationGId, int index, int storageIdx) { - public int PlanetId { get; set; } - public int StationId { get; set; } - public int StationGId { get; set; } - public int Index { get; set; } - public int StorageIdx { get; set; } - public ILSUpdateSlotData() { } - public ILSUpdateSlotData(int planetId, int stationId, int stationGId, int index, int storageIdx) - { - PlanetId = planetId; - StationId = stationId; - StationGId = stationGId; - Index = index; - StorageIdx = storageIdx; - } + PlanetId = planetId; + StationId = stationId; + StationGId = stationGId; + Index = index; + StorageIdx = storageIdx; } + + public int PlanetId { get; set; } + public int StationId { get; set; } + public int StationGId { get; set; } + public int Index { get; set; } + public int StorageIdx { get; set; } } diff --git a/NebulaModel/Packets/Logistics/ILSUpdateStorage.cs b/NebulaModel/Packets/Logistics/ILSUpdateStorage.cs index 02f290064..6eb6de7e4 100644 --- a/NebulaModel/Packets/Logistics/ILSUpdateStorage.cs +++ b/NebulaModel/Packets/Logistics/ILSUpdateStorage.cs @@ -1,19 +1,20 @@ -namespace NebulaModel.Packets.Logistics +namespace NebulaModel.Packets.Logistics; + +// sent when InternalTickRemote() updates the storage count and inc values +public class ILSUpdateStorage { - // sent when InternalTickRemote() updates the storage count and inc values - public class ILSUpdateStorage + public ILSUpdateStorage() { } + + public ILSUpdateStorage(int gid, int index, int count, int inc) { - public int GId { get; set; } - public int Index { get; set; } - public int Count { get; set; } - public int Inc { get; set; } - public ILSUpdateStorage() { } - public ILSUpdateStorage(int gid, int index, int count, int inc) - { - GId = gid; - Index = index; - Count = count; - Inc = inc; - } + GId = gid; + Index = index; + Count = count; + Inc = inc; } + + public int GId { get; set; } + public int Index { get; set; } + public int Count { get; set; } + public int Inc { get; set; } } diff --git a/NebulaModel/Packets/Logistics/ILSWorkShipBackToIdle.cs b/NebulaModel/Packets/Logistics/ILSWorkShipBackToIdle.cs index c063169e3..c63af820f 100644 --- a/NebulaModel/Packets/Logistics/ILSWorkShipBackToIdle.cs +++ b/NebulaModel/Packets/Logistics/ILSWorkShipBackToIdle.cs @@ -1,20 +1,21 @@ -namespace NebulaModel.Packets.Logistics +namespace NebulaModel.Packets.Logistics; + +public class ILSWorkShipBackToIdle { - public class ILSWorkShipBackToIdle + public ILSWorkShipBackToIdle() { } + + public ILSWorkShipBackToIdle(StationComponent stationComponent, ShipData shipData, int workShipIndex) { - public int GId { get; set; } - public int PlanetA { get; set; } - public int StationMaxShipCount { get; set; } - public int ShipIndex { get; set; } - public int WorkShipIndex { get; set; } - public ILSWorkShipBackToIdle() { } - public ILSWorkShipBackToIdle(StationComponent stationComponent, ShipData shipData, int workShipIndex) - { - GId = stationComponent.gid; - PlanetA = shipData.planetA; - StationMaxShipCount = stationComponent.workShipDatas.Length; - ShipIndex = shipData.shipIndex; - WorkShipIndex = workShipIndex; - } + GId = stationComponent.gid; + PlanetA = shipData.planetA; + StationMaxShipCount = stationComponent.workShipDatas.Length; + ShipIndex = shipData.shipIndex; + WorkShipIndex = workShipIndex; } + + public int GId { get; set; } + public int PlanetA { get; set; } + public int StationMaxShipCount { get; set; } + public int ShipIndex { get; set; } + public int WorkShipIndex { get; set; } } diff --git a/NebulaModel/Packets/Logistics/ILSgStationPoolSync.cs b/NebulaModel/Packets/Logistics/ILSgStationPoolSync.cs index e05af16ed..d50d14363 100644 --- a/NebulaModel/Packets/Logistics/ILSgStationPoolSync.cs +++ b/NebulaModel/Packets/Logistics/ILSgStationPoolSync.cs @@ -1,103 +1,108 @@ -using NebulaAPI; +#region -namespace NebulaModel.Packets.Logistics +using System.Diagnostics.CodeAnalysis; +using NebulaAPI; + +#endregion + +namespace NebulaModel.Packets.Logistics; + +// this one is only used when a client connects to sync all existing gStations. +// needed because we also need to tell clients about ships that are already flying +[SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Original Field Name")] +public class ILSgStationPoolSync { - // this one is only used when a client connects to sync all existing gStations. - // needed because we also need to tell clients about ships that are already flying - [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Original Field Name")] - public class ILSgStationPoolSync - { - public int[] stationGId { get; set; } - - public int[] stationMaxShipCount { get; set; } - public int[] stationId { get; set; } - public string[] stationName { get; set; } - public Float3[] DockPos { get; set; } - public Float4[] DockRot { get; set; } - public int[] planetId { get; set; } - public int[] workShipCount { get; set; } - public int[] idleShipCount { get; set; } - public ulong[] workShipIndices { get; set; } - public ulong[] idleShipIndices { get; set; } - public int[] shipStage { get; set; } - public int[] shipDirection { get; set; } - public float[] shipWarpState { get; set; } - public int[] shipWarperCnt { get; set; } - public int[] shipItemID { get; set; } - public int[] shipItemCount { get; set; } - public int[] shipPlanetA { get; set; } - public int[] shipPlanetB { get; set; } - public int[] shipOtherGId { get; set; } - public float[] shipT { get; set; } - public int[] shipIndex { get; set; } - public Double3[] shipPos { get; set; } - public Float4[] shipRot { get; set; } - public Float3[] shipVel { get; set; } - public float[] shipSpeed { get; set; } - public Float3[] shipAngularVel { get; set; } - public Double3[] shipPPosTemp { get; set; } - public Float4[] shipPRotTemp { get; set; } + public ILSgStationPoolSync() { } - public ILSgStationPoolSync() { } - public ILSgStationPoolSync(int[] stationGId, - int[] stationMaxShipCount, - int[] stationId, - string[] stationName, - Float3[] DockPos, - Float4[] DockRot, - int[] planetId, - int[] workShipCount, - int[] idleShipCount, - ulong[] workShipIndices, - ulong[] idleShipIndices, - int[] shipStage, - int[] shipDirection, - float[] shipWarpState, - int[] shipWarperCnt, - int[] shipItemID, - int[] shipItemCount, - int[] shipPlanetA, - int[] shipPlanetB, - int[] shipOtherGId, - float[] shipT, - int[] shipIndex, - Double3[] shipPos, - Float4[] shipRot, - Float3[] shipVel, - float[] shipSpeed, - Float3[] shipAngularVel, - Double3[] shipPPosTemp, - Float4[] shipPRotTemp) - { - this.stationGId = stationGId; - this.stationMaxShipCount = stationMaxShipCount; - this.stationId = stationId; - this.stationName = stationName; - this.DockPos = DockPos; - this.DockRot = DockRot; - this.planetId = planetId; - this.workShipCount = workShipCount; - this.idleShipCount = idleShipCount; - this.workShipIndices = workShipIndices; - this.idleShipIndices = idleShipIndices; - this.shipStage = shipStage; - this.shipDirection = shipDirection; - this.shipWarpState = shipWarpState; - this.shipWarperCnt = shipWarperCnt; - this.shipItemID = shipItemID; - this.shipItemCount = shipItemCount; - this.shipPlanetA = shipPlanetA; - this.shipPlanetB = shipPlanetB; - this.shipOtherGId = shipOtherGId; - this.shipT = shipT; - this.shipIndex = shipIndex; - this.shipPos = shipPos; - this.shipRot = shipRot; - this.shipVel = shipVel; - this.shipSpeed = shipSpeed; - this.shipAngularVel = shipAngularVel; - this.shipPPosTemp = shipPPosTemp; - this.shipPRotTemp = shipPRotTemp; - } + public ILSgStationPoolSync(int[] stationGId, + int[] stationMaxShipCount, + int[] stationId, + string[] stationName, + Float3[] DockPos, + Float4[] DockRot, + int[] planetId, + int[] workShipCount, + int[] idleShipCount, + ulong[] workShipIndices, + ulong[] idleShipIndices, + int[] shipStage, + int[] shipDirection, + float[] shipWarpState, + int[] shipWarperCnt, + int[] shipItemID, + int[] shipItemCount, + int[] shipPlanetA, + int[] shipPlanetB, + int[] shipOtherGId, + float[] shipT, + int[] shipIndex, + Double3[] shipPos, + Float4[] shipRot, + Float3[] shipVel, + float[] shipSpeed, + Float3[] shipAngularVel, + Double3[] shipPPosTemp, + Float4[] shipPRotTemp) + { + this.stationGId = stationGId; + this.stationMaxShipCount = stationMaxShipCount; + this.stationId = stationId; + this.stationName = stationName; + this.DockPos = DockPos; + this.DockRot = DockRot; + this.planetId = planetId; + this.workShipCount = workShipCount; + this.idleShipCount = idleShipCount; + this.workShipIndices = workShipIndices; + this.idleShipIndices = idleShipIndices; + this.shipStage = shipStage; + this.shipDirection = shipDirection; + this.shipWarpState = shipWarpState; + this.shipWarperCnt = shipWarperCnt; + this.shipItemID = shipItemID; + this.shipItemCount = shipItemCount; + this.shipPlanetA = shipPlanetA; + this.shipPlanetB = shipPlanetB; + this.shipOtherGId = shipOtherGId; + this.shipT = shipT; + this.shipIndex = shipIndex; + this.shipPos = shipPos; + this.shipRot = shipRot; + this.shipVel = shipVel; + this.shipSpeed = shipSpeed; + this.shipAngularVel = shipAngularVel; + this.shipPPosTemp = shipPPosTemp; + this.shipPRotTemp = shipPRotTemp; } + + public int[] stationGId { get; set; } + + public int[] stationMaxShipCount { get; set; } + public int[] stationId { get; set; } + public string[] stationName { get; set; } + public Float3[] DockPos { get; set; } + public Float4[] DockRot { get; set; } + public int[] planetId { get; set; } + public int[] workShipCount { get; set; } + public int[] idleShipCount { get; set; } + public ulong[] workShipIndices { get; set; } + public ulong[] idleShipIndices { get; set; } + public int[] shipStage { get; set; } + public int[] shipDirection { get; set; } + public float[] shipWarpState { get; set; } + public int[] shipWarperCnt { get; set; } + public int[] shipItemID { get; set; } + public int[] shipItemCount { get; set; } + public int[] shipPlanetA { get; set; } + public int[] shipPlanetB { get; set; } + public int[] shipOtherGId { get; set; } + public float[] shipT { get; set; } + public int[] shipIndex { get; set; } + public Double3[] shipPos { get; set; } + public Float4[] shipRot { get; set; } + public Float3[] shipVel { get; set; } + public float[] shipSpeed { get; set; } + public Float3[] shipAngularVel { get; set; } + public Double3[] shipPPosTemp { get; set; } + public Float4[] shipPRotTemp { get; set; } } diff --git a/NebulaModel/Packets/Logistics/RemoteOrderUpdate.cs b/NebulaModel/Packets/Logistics/RemoteOrderUpdate.cs index a9c726f14..d850b6795 100644 --- a/NebulaModel/Packets/Logistics/RemoteOrderUpdate.cs +++ b/NebulaModel/Packets/Logistics/RemoteOrderUpdate.cs @@ -1,15 +1,15 @@ -namespace NebulaModel.Packets.Logistics +namespace NebulaModel.Packets.Logistics; + +public class RemoteOrderUpdate { - public class RemoteOrderUpdate - { - public int StationGId { get; set; } - public int[] RemoteOrder { get; set; } + public RemoteOrderUpdate() { } - public RemoteOrderUpdate() { } - public RemoteOrderUpdate(int stationGid, int[] remoteOrder) - { - StationGId = stationGid; - RemoteOrder = remoteOrder; - } + public RemoteOrderUpdate(int stationGid, int[] remoteOrder) + { + StationGId = stationGid; + RemoteOrder = remoteOrder; } + + public int StationGId { get; set; } + public int[] RemoteOrder { get; set; } } diff --git a/NebulaModel/Packets/Logistics/StationUI.cs b/NebulaModel/Packets/Logistics/StationUI.cs index d9dcbce8f..adc1808cc 100644 --- a/NebulaModel/Packets/Logistics/StationUI.cs +++ b/NebulaModel/Packets/Logistics/StationUI.cs @@ -1,54 +1,56 @@ -namespace NebulaModel.Packets.Logistics +namespace NebulaModel.Packets.Logistics; + +public class StationUI { - public class StationUI + public enum EUISettings { - public enum EUISettings - { - None, - MaxChargePower, - MaxTripDrones, - MaxTripVessel, - MinDeliverDrone, - MinDeliverVessel, - WarpDistance, - WarperNeeded, - IncludeCollectors, - SetDroneCount, - SetShipCount, - SetWarperCount, - PilerCount, - MaxMiningSpeed, - NameInput, - DroneAutoReplenish, - ShipAutoReplenish - } + None, + MaxChargePower, + MaxTripDrones, + MaxTripVessel, + MinDeliverDrone, + MinDeliverVessel, + WarpDistance, + WarperNeeded, + IncludeCollectors, + SetDroneCount, + SetShipCount, + SetWarperCount, + PilerCount, + MaxMiningSpeed, + NameInput, + DroneAutoReplenish, + ShipAutoReplenish + } - public int PlanetId { get; set; } - public int StationId { get; set; } - public int StationGId { get; set; } - public StationUI.EUISettings SettingIndex { get; set; } - public float SettingValue { get; set; } - public string SettingString { get; set; } - public bool WarperShouldTakeFromStorage { get; set; } - public bool ShouldRefund { get; set; } + public StationUI() { } - public StationUI() { } - public StationUI(int planetId, int stationId, int stationGId, StationUI.EUISettings settingIndex, float value, bool warperShouldTakeFromStorage = false) - { - PlanetId = planetId; - StationId = stationId; - StationGId = stationGId; - SettingIndex = settingIndex; - SettingValue = value; - WarperShouldTakeFromStorage = warperShouldTakeFromStorage; - } - public StationUI(int planetId, int stationId, int stationGId, StationUI.EUISettings settingIndex, string settingString) - { - PlanetId = planetId; - StationId = stationId; - StationGId = stationGId; - SettingIndex = settingIndex; - SettingString = settingString; - } + public StationUI(int planetId, int stationId, int stationGId, EUISettings settingIndex, float value, + bool warperShouldTakeFromStorage = false) + { + PlanetId = planetId; + StationId = stationId; + StationGId = stationGId; + SettingIndex = settingIndex; + SettingValue = value; + WarperShouldTakeFromStorage = warperShouldTakeFromStorage; } + + public StationUI(int planetId, int stationId, int stationGId, EUISettings settingIndex, string settingString) + { + PlanetId = planetId; + StationId = stationId; + StationGId = stationGId; + SettingIndex = settingIndex; + SettingString = settingString; + } + + public int PlanetId { get; set; } + public int StationId { get; set; } + public int StationGId { get; set; } + public EUISettings SettingIndex { get; set; } + public float SettingValue { get; set; } + public string SettingString { get; set; } + public bool WarperShouldTakeFromStorage { get; set; } + public bool ShouldRefund { get; set; } } diff --git a/NebulaModel/Packets/Logistics/StationUIInitialSync.cs b/NebulaModel/Packets/Logistics/StationUIInitialSync.cs index 03ad8da54..b6418804a 100644 --- a/NebulaModel/Packets/Logistics/StationUIInitialSync.cs +++ b/NebulaModel/Packets/Logistics/StationUIInitialSync.cs @@ -1,73 +1,73 @@ -namespace NebulaModel.Packets.Logistics +namespace NebulaModel.Packets.Logistics; + +public class StationUIInitialSync { - public class StationUIInitialSync - { - public int PlanetId { get; set; } - public int StationGId { get; set; } - public int StationId { get; set; } - public double TripRangeDrones { get; set; } - public double TripRangeShips { get; set; } - public int DeliveryDrones { get; set; } - public int DeliveryShips { get; set; } - public double WarperEnableDistance { get; set; } - public bool WarperNecessary { get; set; } - public bool IncludeOrbitCollector { get; set; } - public long Energy { get; set; } - public long EnergyPerTick { get; set; } - public int PilerCount { get; set; } - public int[] ItemId { get; set; } - public int[] ItemCountMax { get; set; } - public int[] ItemCount { get; set; } - public int[] ItemInc { get; set; } - public int[] LocalLogic { get; set; } - public int[] RemoteLogic { get; set; } - public int[] RemoteOrder { get; set; } - public StationUIInitialSync() { } + public StationUIInitialSync() { } - public StationUIInitialSync( - int planetId, - int stationId, - int stationGId, - double tripRangeDrones, - double tripRangeShips, - int deliveryDrones, - int deliveryShips, - double warperEnableDistance, - bool warperNecessary, - bool includeOrbitCollector, - long energy, - long energyPerTick, - int pilerCount, - int[] itemId, - int[] itemCountMax, - int[] itemCount, - int[] itemInc, - int[] localLogic, - int[] remoteLogic, - int[] remoteOrder - ) - { - PlanetId = planetId; - StationId = stationId; - StationGId = stationGId; - TripRangeDrones = tripRangeDrones; - TripRangeShips = tripRangeShips; - DeliveryDrones = deliveryDrones; - DeliveryShips = deliveryShips; - WarperEnableDistance = warperEnableDistance; - WarperNecessary = warperNecessary; - IncludeOrbitCollector = includeOrbitCollector; - Energy = energy; - EnergyPerTick = energyPerTick; - PilerCount = pilerCount; + public StationUIInitialSync( + int planetId, + int stationId, + int stationGId, + double tripRangeDrones, + double tripRangeShips, + int deliveryDrones, + int deliveryShips, + double warperEnableDistance, + bool warperNecessary, + bool includeOrbitCollector, + long energy, + long energyPerTick, + int pilerCount, + int[] itemId, + int[] itemCountMax, + int[] itemCount, + int[] itemInc, + int[] localLogic, + int[] remoteLogic, + int[] remoteOrder + ) + { + PlanetId = planetId; + StationId = stationId; + StationGId = stationGId; + TripRangeDrones = tripRangeDrones; + TripRangeShips = tripRangeShips; + DeliveryDrones = deliveryDrones; + DeliveryShips = deliveryShips; + WarperEnableDistance = warperEnableDistance; + WarperNecessary = warperNecessary; + IncludeOrbitCollector = includeOrbitCollector; + Energy = energy; + EnergyPerTick = energyPerTick; + PilerCount = pilerCount; - ItemId = itemId; - ItemCountMax = itemCountMax; - ItemCount = itemCount; - ItemInc = itemInc; - LocalLogic = localLogic; - RemoteLogic = remoteLogic; - RemoteOrder = remoteOrder; - } + ItemId = itemId; + ItemCountMax = itemCountMax; + ItemCount = itemCount; + ItemInc = itemInc; + LocalLogic = localLogic; + RemoteLogic = remoteLogic; + RemoteOrder = remoteOrder; } + + public int PlanetId { get; set; } + public int StationGId { get; set; } + public int StationId { get; set; } + public double TripRangeDrones { get; set; } + public double TripRangeShips { get; set; } + public int DeliveryDrones { get; set; } + public int DeliveryShips { get; set; } + public double WarperEnableDistance { get; set; } + public bool WarperNecessary { get; set; } + public bool IncludeOrbitCollector { get; set; } + public long Energy { get; set; } + public long EnergyPerTick { get; set; } + public int PilerCount { get; set; } + public int[] ItemId { get; set; } + public int[] ItemCountMax { get; set; } + public int[] ItemCount { get; set; } + public int[] ItemInc { get; set; } + public int[] LocalLogic { get; set; } + public int[] RemoteLogic { get; set; } + public int[] RemoteOrder { get; set; } } diff --git a/NebulaModel/Packets/Logistics/StationUIInitialSyncRequest.cs b/NebulaModel/Packets/Logistics/StationUIInitialSyncRequest.cs index 25f54904e..25b8b15a5 100644 --- a/NebulaModel/Packets/Logistics/StationUIInitialSyncRequest.cs +++ b/NebulaModel/Packets/Logistics/StationUIInitialSyncRequest.cs @@ -1,16 +1,17 @@ -namespace NebulaModel.Packets.Logistics +namespace NebulaModel.Packets.Logistics; + +public class StationUIInitialSyncRequest { - public class StationUIInitialSyncRequest + public StationUIInitialSyncRequest() { } + + public StationUIInitialSyncRequest(int planetId, int stationId, int stationGId) { - public int PlanetId { get; set; } - public int StationId { get; set; } - public int StationGId { get; set; } - public StationUIInitialSyncRequest() { } - public StationUIInitialSyncRequest(int planetId, int stationId, int stationGId) - { - PlanetId = planetId; - StationId = stationId; - StationGId = stationGId; - } + PlanetId = planetId; + StationId = stationId; + StationGId = stationGId; } + + public int PlanetId { get; set; } + public int StationId { get; set; } + public int StationGId { get; set; } } diff --git a/NebulaModel/Packets/Logistics/StorageUI.cs b/NebulaModel/Packets/Logistics/StorageUI.cs index 361067c47..1500cad74 100644 --- a/NebulaModel/Packets/Logistics/StorageUI.cs +++ b/NebulaModel/Packets/Logistics/StorageUI.cs @@ -1,54 +1,57 @@ -namespace NebulaModel.Packets.Logistics +namespace NebulaModel.Packets.Logistics; + +public class StorageUI { - public class StorageUI + public StorageUI() { } + + public StorageUI(int planetId, int stationId, int stationGId, int storageIdx, int itemId, int itemCountMax, + ELogisticStorage localLogic, ELogisticStorage remoteLogic) + { + ItemCount = -1; //Indicate it is SetStationStorage() + + PlanetId = planetId; + StationId = stationId; + StationGId = stationGId; + StorageIdx = storageIdx; + ItemId = itemId; + ItemCountMax = itemCountMax; + LocalLogic = localLogic; + RemoteLogic = remoteLogic; + } + + public StorageUI(int planetId, int stationId, int stationGId, int storageIdx, int itemCount, int itemInc) { - public int PlanetId { get; set; } - public int StationId { get; set; } - public int StationGId { get; set; } - public int StorageIdx { get; set; } - public int ItemId { get; set; } - public int ItemCountMax { get; set; } - public ELogisticStorage LocalLogic { get; set; } - public ELogisticStorage RemoteLogic { get; set; } - public int ItemCount { get; set; } - public int ItemInc { get; set; } - public bool ShouldRefund { get; set; } - public byte KeepMode { get; set; } - - public StorageUI() { } - public StorageUI(int planetId, int stationId, int stationGId, int storageIdx, int itemId, int itemCountMax, ELogisticStorage localLogic, ELogisticStorage remoteLogic) - { - ItemCount = -1; //Indicate it is SetStationStorage() - - PlanetId = planetId; - StationId = stationId; - StationGId = stationGId; - StorageIdx = storageIdx; - ItemId = itemId; - ItemCountMax = itemCountMax; - LocalLogic = localLogic; - RemoteLogic = remoteLogic; - } - public StorageUI(int planetId, int stationId, int stationGId, int storageIdx, int itemCount, int itemInc) - { - ShouldRefund = false; - - PlanetId = planetId; - StationId = stationId; - StationGId = stationGId; - StorageIdx = storageIdx; - ItemCount = itemCount; - ItemInc = itemInc; - } - public StorageUI(int planetId, int stationId, int stationGId, int storageIdx, byte keepMode) - { - ItemCount = -2; //Indicate it is other settings update - - PlanetId = planetId; - StationId = stationId; - StationGId = stationGId; - StorageIdx = storageIdx; - KeepMode = keepMode; - } + ShouldRefund = false; + + PlanetId = planetId; + StationId = stationId; + StationGId = stationGId; + StorageIdx = storageIdx; + ItemCount = itemCount; + ItemInc = itemInc; + } + + public StorageUI(int planetId, int stationId, int stationGId, int storageIdx, byte keepMode) + { + ItemCount = -2; //Indicate it is other settings update + + PlanetId = planetId; + StationId = stationId; + StationGId = stationGId; + StorageIdx = storageIdx; + KeepMode = keepMode; } + + public int PlanetId { get; set; } + public int StationId { get; set; } + public int StationGId { get; set; } + public int StorageIdx { get; set; } + public int ItemId { get; set; } + public int ItemCountMax { get; set; } + public ELogisticStorage LocalLogic { get; set; } + public ELogisticStorage RemoteLogic { get; set; } + public int ItemCount { get; set; } + public int ItemInc { get; set; } + public bool ShouldRefund { get; set; } + public byte KeepMode { get; set; } } diff --git a/NebulaModel/Packets/PacketProcessor.cs b/NebulaModel/Packets/PacketProcessor.cs index a8174d4a9..be9876c33 100644 --- a/NebulaModel/Packets/PacketProcessor.cs +++ b/NebulaModel/Packets/PacketProcessor.cs @@ -1,15 +1,18 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; -namespace NebulaModel.Packets +#endregion + +namespace NebulaModel.Packets; + +public abstract class PacketProcessor : BasePacketProcessor { - public abstract class PacketProcessor : BasePacketProcessor + public override void ProcessPacket(T packet, INebulaConnection conn) { - public override void ProcessPacket(T packet, INebulaConnection conn) - { - ProcessPacket(packet, (NebulaConnection)conn); - } - - public abstract void ProcessPacket(T packet, NebulaConnection conn); + ProcessPacket(packet, (NebulaConnection)conn); } + + public abstract void ProcessPacket(T packet, NebulaConnection conn); } diff --git a/NebulaModel/Packets/Planet/FactoryData.cs b/NebulaModel/Packets/Planet/FactoryData.cs index 14c1a042b..dd76b281c 100644 --- a/NebulaModel/Packets/Planet/FactoryData.cs +++ b/NebulaModel/Packets/Planet/FactoryData.cs @@ -1,17 +1,17 @@ -namespace NebulaModel.Packets.Planet +namespace NebulaModel.Packets.Planet; + +public class FactoryData { - public class FactoryData - { - public int PlanetId { get; set; } - public byte[] BinaryData { get; set; } - public byte[] TerrainModData { get; set; } + public FactoryData() { } - public FactoryData() { } - public FactoryData(int id, byte[] data, byte[] terrainModData) - { - PlanetId = id; - BinaryData = data; - TerrainModData = terrainModData; - } + public FactoryData(int id, byte[] data, byte[] terrainModData) + { + PlanetId = id; + BinaryData = data; + TerrainModData = terrainModData; } + + public int PlanetId { get; set; } + public byte[] BinaryData { get; set; } + public byte[] TerrainModData { get; set; } } diff --git a/NebulaModel/Packets/Planet/FactoryLoadRequest.cs b/NebulaModel/Packets/Planet/FactoryLoadRequest.cs index 21b4c3c94..c0d11f4c7 100644 --- a/NebulaModel/Packets/Planet/FactoryLoadRequest.cs +++ b/NebulaModel/Packets/Planet/FactoryLoadRequest.cs @@ -1,13 +1,13 @@ -namespace NebulaModel.Packets.Planet +namespace NebulaModel.Packets.Planet; + +public class FactoryLoadRequest { - public class FactoryLoadRequest - { - public int PlanetID { get; set; } + public FactoryLoadRequest() { } - public FactoryLoadRequest() { } - public FactoryLoadRequest(int planetID) - { - PlanetID = planetID; - } + public FactoryLoadRequest(int planetID) + { + PlanetID = planetID; } + + public int PlanetID { get; set; } } diff --git a/NebulaModel/Packets/Planet/PlanetDataRequest.cs b/NebulaModel/Packets/Planet/PlanetDataRequest.cs index 909fc7121..73849b000 100644 --- a/NebulaModel/Packets/Planet/PlanetDataRequest.cs +++ b/NebulaModel/Packets/Planet/PlanetDataRequest.cs @@ -1,14 +1,13 @@ -namespace NebulaModel.Packets.Planet -{ - public class PlanetDataRequest - { - public int[] PlanetIDs { get; set; } +namespace NebulaModel.Packets.Planet; - public PlanetDataRequest() { } +public class PlanetDataRequest +{ + public PlanetDataRequest() { } - public PlanetDataRequest(int[] planetIDs) - { - PlanetIDs = planetIDs; - } + public PlanetDataRequest(int[] planetIDs) + { + PlanetIDs = planetIDs; } + + public int[] PlanetIDs { get; set; } } diff --git a/NebulaModel/Packets/Planet/PlanetDataResponse.cs b/NebulaModel/Packets/Planet/PlanetDataResponse.cs index 9a43a633f..e131b739c 100644 --- a/NebulaModel/Packets/Planet/PlanetDataResponse.cs +++ b/NebulaModel/Packets/Planet/PlanetDataResponse.cs @@ -1,16 +1,15 @@ -namespace NebulaModel.Packets.Planet -{ - public class PlanetDataResponse - { - public int PlanetDataID { get; set; } - public byte[] PlanetDataByte { get; set; } +namespace NebulaModel.Packets.Planet; - public PlanetDataResponse() { } +public class PlanetDataResponse +{ + public PlanetDataResponse() { } - public PlanetDataResponse(int planetId, byte[] planetData) - { - PlanetDataID = planetId; - PlanetDataByte = planetData; - } + public PlanetDataResponse(int planetId, byte[] planetData) + { + PlanetDataID = planetId; + PlanetDataByte = planetData; } + + public int PlanetDataID { get; set; } + public byte[] PlanetDataByte { get; set; } } diff --git a/NebulaModel/Packets/Planet/PlanetDetailRequest.cs b/NebulaModel/Packets/Planet/PlanetDetailRequest.cs index 0ca584b88..3d5b19be7 100644 --- a/NebulaModel/Packets/Planet/PlanetDetailRequest.cs +++ b/NebulaModel/Packets/Planet/PlanetDetailRequest.cs @@ -1,14 +1,13 @@ -namespace NebulaModel.Packets.Planet -{ - public class PlanetDetailRequest - { - public int PlanetID { get; set; } +namespace NebulaModel.Packets.Planet; - public PlanetDetailRequest() { } +public class PlanetDetailRequest +{ + public PlanetDetailRequest() { } - public PlanetDetailRequest(int planetID) - { - PlanetID = planetID; - } + public PlanetDetailRequest(int planetID) + { + PlanetID = planetID; } + + public int PlanetID { get; set; } } diff --git a/NebulaModel/Packets/Planet/PlanetDetailResponse.cs b/NebulaModel/Packets/Planet/PlanetDetailResponse.cs index 9b300adb5..40514aee7 100644 --- a/NebulaModel/Packets/Planet/PlanetDetailResponse.cs +++ b/NebulaModel/Packets/Planet/PlanetDetailResponse.cs @@ -1,27 +1,27 @@ -namespace NebulaModel.Packets.Planet +namespace NebulaModel.Packets.Planet; + +public class PlanetDetailResponse { - public class PlanetDetailResponse - { - public int PlanetDataID { get; set; } - public byte[] VeinTypes { get; set; } - public int[] VeinCounts { get; set; } - public long[] VeinAmounts { get; set; } - public float LandPercent { get; set; } + public PlanetDetailResponse() { } - public PlanetDetailResponse() { } - public PlanetDetailResponse(int planetId, in VeinGroup[] veinGroups, float landPercent) + public PlanetDetailResponse(int planetId, in VeinGroup[] veinGroups, float landPercent) + { + PlanetDataID = planetId; + VeinTypes = new byte[veinGroups.Length]; + VeinCounts = new int[veinGroups.Length]; + VeinAmounts = new long[veinGroups.Length]; + for (var i = 1; i < veinGroups.Length; i++) { - PlanetDataID = planetId; - VeinTypes = new byte[veinGroups.Length]; - VeinCounts = new int[veinGroups.Length]; - VeinAmounts = new long[veinGroups.Length]; - for (int i = 1; i < veinGroups.Length; i++) - { - VeinTypes[i] = (byte)veinGroups[i].type; - VeinCounts[i] = veinGroups[i].count; - VeinAmounts[i] = veinGroups[i].amount; - } - LandPercent = landPercent; + VeinTypes[i] = (byte)veinGroups[i].type; + VeinCounts[i] = veinGroups[i].count; + VeinAmounts[i] = veinGroups[i].amount; } + LandPercent = landPercent; } + + public int PlanetDataID { get; set; } + public byte[] VeinTypes { get; set; } + public int[] VeinCounts { get; set; } + public long[] VeinAmounts { get; set; } + public float LandPercent { get; set; } } diff --git a/NebulaModel/Packets/Planet/VegeAddPacket.cs b/NebulaModel/Packets/Planet/VegeAddPacket.cs index 373cff935..1eff5e39a 100644 --- a/NebulaModel/Packets/Planet/VegeAddPacket.cs +++ b/NebulaModel/Packets/Planet/VegeAddPacket.cs @@ -1,17 +1,17 @@ -namespace NebulaModel.Packets.Planet +namespace NebulaModel.Packets.Planet; + +public class VegeAddPacket { - public class VegeAddPacket - { - public int PlanetId { get; set; } - public bool IsVein { get; set; } - public byte[] Data { get; set; } + public VegeAddPacket() { } - public VegeAddPacket() { } - public VegeAddPacket(int planetId, bool isVein, byte[] data) - { - PlanetId = planetId; - IsVein = isVein; - Data = data; - } + public VegeAddPacket(int planetId, bool isVein, byte[] data) + { + PlanetId = planetId; + IsVein = isVein; + Data = data; } + + public int PlanetId { get; set; } + public bool IsVein { get; set; } + public byte[] Data { get; set; } } diff --git a/NebulaModel/Packets/Planet/VegeMinedPacket.cs b/NebulaModel/Packets/Planet/VegeMinedPacket.cs index 01e6a16e3..1dfd1d05d 100644 --- a/NebulaModel/Packets/Planet/VegeMinedPacket.cs +++ b/NebulaModel/Packets/Planet/VegeMinedPacket.cs @@ -1,20 +1,19 @@ -namespace NebulaModel.Packets.Planet -{ - public class VegeMinedPacket - { - public int PlanetId { get; set; } - public int VegeId { get; set; } - public int Amount { get; set; } // the current amount, if 0 remove vege - public bool IsVein { get; set; } +namespace NebulaModel.Packets.Planet; - public VegeMinedPacket() { } +public class VegeMinedPacket +{ + public VegeMinedPacket() { } - public VegeMinedPacket(int planetId, int vegeId, int amount, bool isVein) - { - PlanetId = planetId; - VegeId = vegeId; - Amount = amount; - IsVein = isVein; - } + public VegeMinedPacket(int planetId, int vegeId, int amount, bool isVein) + { + PlanetId = planetId; + VegeId = vegeId; + Amount = amount; + IsVein = isVein; } + + public int PlanetId { get; set; } + public int VegeId { get; set; } + public int Amount { get; set; } // the current amount, if 0 remove vege + public bool IsVein { get; set; } } diff --git a/NebulaModel/Packets/Players/NewDroneOrderPacket.cs b/NebulaModel/Packets/Players/NewDroneOrderPacket.cs index f6c792368..c98ad2154 100644 --- a/NebulaModel/Packets/Players/NewDroneOrderPacket.cs +++ b/NebulaModel/Packets/Players/NewDroneOrderPacket.cs @@ -1,28 +1,33 @@ -using NebulaAPI; +#region + +using NebulaAPI; using UnityEngine; -namespace NebulaModel.Packets.Players +#endregion + +namespace NebulaModel.Packets.Players; + +public class NewDroneOrderPacket { - public class NewDroneOrderPacket - { - public int PlanetId { get; set; } - public int DroneId { get; set; } - public int EntityId { get; set; } - public ushort PlayerId { get; set; } - public int Stage { get; set; } - public int Priority { get; set; } - public Float3 EntityPos { get; set; } + public NewDroneOrderPacket() { } - public NewDroneOrderPacket() { } - public NewDroneOrderPacket(int planetId, int droneId, int entityId, ushort playerId, int stage, int priority, Vector3 entityPos) - { - PlanetId = planetId; - DroneId = droneId; - EntityId = entityId; - PlayerId = playerId; - Stage = stage; - Priority = priority; - EntityPos = entityPos.ToFloat3(); - } + public NewDroneOrderPacket(int planetId, int droneId, int entityId, ushort playerId, int stage, int priority, + Vector3 entityPos) + { + PlanetId = planetId; + DroneId = droneId; + EntityId = entityId; + PlayerId = playerId; + Stage = stage; + Priority = priority; + EntityPos = entityPos.ToFloat3(); } + + public int PlanetId { get; set; } + public int DroneId { get; set; } + public int EntityId { get; set; } + public ushort PlayerId { get; set; } + public int Stage { get; set; } + public int Priority { get; set; } + public Float3 EntityPos { get; set; } } diff --git a/NebulaModel/Packets/Players/PlayerMechaArmor.cs b/NebulaModel/Packets/Players/PlayerMechaArmor.cs index a116b772c..4d644345b 100644 --- a/NebulaModel/Packets/Players/PlayerMechaArmor.cs +++ b/NebulaModel/Packets/Players/PlayerMechaArmor.cs @@ -1,14 +1,15 @@ -namespace NebulaModel.Packets.Players +namespace NebulaModel.Packets.Players; + +public class PlayerMechaArmor { - public class PlayerMechaArmor + public PlayerMechaArmor() { } + + public PlayerMechaArmor(ushort playerId, byte[] appearanceData) { - public ushort PlayerId { get; set; } - public byte[] AppearanceData { get; set; } - public PlayerMechaArmor() { } - public PlayerMechaArmor(ushort playerId, byte[] appearanceData) - { - PlayerId = playerId; - AppearanceData = appearanceData; - } + PlayerId = playerId; + AppearanceData = appearanceData; } + + public ushort PlayerId { get; set; } + public byte[] AppearanceData { get; set; } } diff --git a/NebulaModel/Packets/Players/PlayerMechaDIYArmor.cs b/NebulaModel/Packets/Players/PlayerMechaDIYArmor.cs index 5edc26405..fb308bc43 100644 --- a/NebulaModel/Packets/Players/PlayerMechaDIYArmor.cs +++ b/NebulaModel/Packets/Players/PlayerMechaDIYArmor.cs @@ -1,16 +1,17 @@ -namespace NebulaModel.Packets.Players +namespace NebulaModel.Packets.Players; + +public class PlayerMechaDIYArmor { - public class PlayerMechaDIYArmor + public PlayerMechaDIYArmor() { } + + public PlayerMechaDIYArmor(byte[] diyArmorData, int[] diyItemId, int[] diyItemValue) { - public byte[] DIYAppearanceData { get; set; } - public int[] DIYItemId { get; set; } - public int[] DIYItemValue { get; set; } - public PlayerMechaDIYArmor() { } - public PlayerMechaDIYArmor(byte[] diyArmorData, int[] diyItemId, int[] diyItemValue) - { - DIYAppearanceData = diyArmorData; - DIYItemId = diyItemId; - DIYItemValue = diyItemValue; - } + DIYAppearanceData = diyArmorData; + DIYItemId = diyItemId; + DIYItemValue = diyItemValue; } + + public byte[] DIYAppearanceData { get; set; } + public int[] DIYItemId { get; set; } + public int[] DIYItemValue { get; set; } } diff --git a/NebulaModel/Packets/Players/PlayerMechaData.cs b/NebulaModel/Packets/Players/PlayerMechaData.cs index 302e3417b..f19663c84 100644 --- a/NebulaModel/Packets/Players/PlayerMechaData.cs +++ b/NebulaModel/Packets/Players/PlayerMechaData.cs @@ -1,17 +1,22 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.DataStructures; -namespace NebulaModel.Packets.Players +#endregion + +namespace NebulaModel.Packets.Players; + +[HidePacketInDebugLogs] +public class PlayerMechaData { - [HidePacketInDebugLogs] - public class PlayerMechaData - { - public MechaData Data { get; set; } + public PlayerMechaData() { } - public PlayerMechaData() { } - public PlayerMechaData(Player player) - { - Data = new MechaData(player.sandCount, player.mecha.coreEnergy, player.mecha.reactorEnergy, player.package, player.deliveryPackage, player.mecha.reactorStorage, player.mecha.warpStorage, player.mecha.forge); - } + public PlayerMechaData(Player player) + { + Data = new MechaData(player.sandCount, player.mecha.coreEnergy, player.mecha.reactorEnergy, player.package, + player.deliveryPackage, player.mecha.reactorStorage, player.mecha.warpStorage, player.mecha.forge); } + + public MechaData Data { get; set; } } diff --git a/NebulaModel/Packets/Players/PlayerMechaStat.cs b/NebulaModel/Packets/Players/PlayerMechaStat.cs index 8553cd06a..97a2be41b 100644 --- a/NebulaModel/Packets/Players/PlayerMechaStat.cs +++ b/NebulaModel/Packets/Players/PlayerMechaStat.cs @@ -1,15 +1,15 @@ -namespace NebulaModel.Packets.Players +namespace NebulaModel.Packets.Players; + +public class PlayerMechaStat { - public class PlayerMechaStat - { - public int ItemId { get; set; } - public int ItemCount { get; set; } + public PlayerMechaStat() { } - public PlayerMechaStat() { } - public PlayerMechaStat(int itemId, int itemCount) - { - ItemId = itemId; - ItemCount = itemCount; - } + public PlayerMechaStat(int itemId, int itemCount) + { + ItemId = itemId; + ItemCount = itemCount; } + + public int ItemId { get; set; } + public int ItemCount { get; set; } } diff --git a/NebulaModel/Packets/Players/PlayerMovement.cs b/NebulaModel/Packets/Players/PlayerMovement.cs index 675f3d473..1444a4f92 100644 --- a/NebulaModel/Packets/Players/PlayerMovement.cs +++ b/NebulaModel/Packets/Players/PlayerMovement.cs @@ -1,74 +1,79 @@ -using NebulaAPI; +#region -namespace NebulaModel.Packets.Players +using NebulaAPI; + +#endregion + +namespace NebulaModel.Packets.Players; + +[HidePacketInDebugLogs] +public class PlayerMovement { - [HidePacketInDebugLogs] - public class PlayerMovement + public enum EFlags : byte + { + isGrounded = 1, + inWater = 2, + warping = 4 + } + + public PlayerMovement() { } + + public PlayerMovement(ushort playerId, int localPlanetId, Float3 localPlanetPosition, Double3 uPosition, Float3 rotation, + Float3 bodyRotation, PlayerAnimator animator) { // Movement - public ushort PlayerId { get; set; } - public int LocalPlanetId { get; set; } - public Float3 LocalPlanetPosition { get; set; } - public Double3 UPosition { get; set; } - public Float3 Rotation { get; set; } - public Float3 BodyRotation { get; set; } + PlayerId = playerId; + LocalPlanetId = localPlanetId; + LocalPlanetPosition = localPlanetPosition; + UPosition = uPosition; + Rotation = rotation; + BodyRotation = bodyRotation; // Animation - public EMovementState MovementState { get; set; } - public float HorzSpeed { get; set; } - public float VertSpeed { get; set; } - public float Turning { get; set; } - public float JumpWeight { get; set; } - public float JumpNormalizedTime { get; set; } - public byte IdleAnimIndex { get; set; } - public byte MiningAnimIndex { get; set; } - public float MiningWeight { get; set; } - public EFlags Flags { get; set; } - public enum EFlags : byte - { - isGrounded = 1, - inWater = 2, - warping = 4 - } + MovementState = animator.movementState; + HorzSpeed = animator.controller.horzSpeed; + VertSpeed = animator.controller.vertSpeed; + Turning = animator.turning; + JumpWeight = animator.jumpWeight; + JumpNormalizedTime = animator.jumpNormalizedTime; - public PlayerMovement() { } + //Compress AnimIndex, assume their values are less than 256 + IdleAnimIndex = (byte)animator.idleAnimIndex; + MiningAnimIndex = (byte)animator.miningAnimIndex; + MiningWeight = animator.miningWeight; - public PlayerMovement(ushort playerId, int localPlanetId, Float3 localPlanetPosition, Double3 uPosition, Float3 rotation, Float3 bodyRotation, PlayerAnimator animator) + Flags = 0; + if (animator.controller.actionWalk.isGrounded) { - // Movement - PlayerId = playerId; - LocalPlanetId = localPlanetId; - LocalPlanetPosition = localPlanetPosition; - UPosition = uPosition; - Rotation = rotation; - BodyRotation = bodyRotation; - - // Animation - MovementState = animator.movementState; - HorzSpeed = animator.controller.horzSpeed; - VertSpeed = animator.controller.vertSpeed; - Turning = animator.turning; - JumpWeight = animator.jumpWeight; - JumpNormalizedTime = animator.jumpNormalizedTime; - - //Compress AnimIndex, assume their values are less than 256 - IdleAnimIndex = (byte)animator.idleAnimIndex; - MiningAnimIndex = (byte)animator.miningAnimIndex; - MiningWeight = animator.miningWeight; - - Flags = 0; - if (animator.controller.actionWalk.isGrounded) - { - Flags |= EFlags.isGrounded; - } - if (animator.controller.actionDrift.inWater) - { - Flags |= EFlags.inWater; - } - if (animator.player.warping) - { - Flags |= EFlags.warping; - } + Flags |= EFlags.isGrounded; + } + if (animator.controller.actionDrift.inWater) + { + Flags |= EFlags.inWater; + } + if (animator.player.warping) + { + Flags |= EFlags.warping; } } + + // Movement + public ushort PlayerId { get; set; } + public int LocalPlanetId { get; set; } + public Float3 LocalPlanetPosition { get; set; } + public Double3 UPosition { get; set; } + public Float3 Rotation { get; set; } + public Float3 BodyRotation { get; set; } + + // Animation + public EMovementState MovementState { get; set; } + public float HorzSpeed { get; set; } + public float VertSpeed { get; set; } + public float Turning { get; set; } + public float JumpWeight { get; set; } + public float JumpNormalizedTime { get; set; } + public byte IdleAnimIndex { get; set; } + public byte MiningAnimIndex { get; set; } + public float MiningWeight { get; set; } + public EFlags Flags { get; set; } } diff --git a/NebulaModel/Packets/Players/PlayerSandCount.cs b/NebulaModel/Packets/Players/PlayerSandCount.cs index 5b190e8f0..b15e5e9f1 100644 --- a/NebulaModel/Packets/Players/PlayerSandCount.cs +++ b/NebulaModel/Packets/Players/PlayerSandCount.cs @@ -1,12 +1,13 @@ -namespace NebulaModel.Packets.Players +namespace NebulaModel.Packets.Players; + +public class PlayerSandCount { - public class PlayerSandCount + public PlayerSandCount() { } + + public PlayerSandCount(int sandCount) { - public int SandCount { get; set; } - public PlayerSandCount() { } - public PlayerSandCount(int sandCount) - { - SandCount = sandCount; - } + SandCount = sandCount; } + + public int SandCount { get; set; } } diff --git a/NebulaModel/Packets/Players/PlayerTechBonuses.cs b/NebulaModel/Packets/Players/PlayerTechBonuses.cs index 8dea75f17..bc2c821b6 100644 --- a/NebulaModel/Packets/Players/PlayerTechBonuses.cs +++ b/NebulaModel/Packets/Players/PlayerTechBonuses.cs @@ -1,216 +1,220 @@ -using NebulaAPI; +#region -namespace NebulaModel.Packets.Players +using NebulaAPI; + +#endregion + +namespace NebulaModel.Packets.Players; + +public class PlayerTechBonuses : IPlayerTechBonuses { - public class PlayerTechBonuses : IPlayerTechBonuses + public PlayerTechBonuses() { } + + public PlayerTechBonuses(Mecha source) { - public double coreEnergyCap { get; set; } - public double corePowerGen { get; set; } - public double reactorPowerGen { get; set; } - public double walkPower { get; set; } - public double jumpEnergy { get; set; } - public double thrustPowerPerAcc { get; set; } - public double warpKeepingPowerPerSpeed { get; set; } - public double warpStartPowerPerSpeed { get; set; } - public double miningPower { get; set; } - public double replicatePower { get; set; } - public double researchPower { get; set; } - public double droneEjectEnergy { get; set; } - public double droneEnergyPerMeter { get; set; } - public int coreLevel { get; set; } - public int thrusterLevel { get; set; } - public float miningSpeed { get; set; } - public float replicateSpeed { get; set; } - public float walkSpeed { get; set; } - public float jumpSpeed { get; set; } - public float maxSailSpeed { get; set; } - public float maxWarpSpeed { get; set; } - public float buildArea { get; set; } - public int droneCount { get; set; } - public float droneSpeed { get; set; } - public int droneMovement { get; set; } - public int inventorySize { get; set; } - public bool deliveryPackageUnlocked { get; set; } - public int deliveryPackageColCount { get; set; } - public int deliveryPackageStackSizeMultiplier { get; set; } + coreEnergyCap = source.coreEnergyCap; + corePowerGen = source.corePowerGen; + reactorPowerGen = source.reactorPowerGen; + walkPower = source.walkPower; + jumpEnergy = source.jumpEnergy; + thrustPowerPerAcc = source.thrustPowerPerAcc; + warpKeepingPowerPerSpeed = source.warpKeepingPowerPerSpeed; + warpStartPowerPerSpeed = source.warpStartPowerPerSpeed; + miningPower = source.miningPower; + replicatePower = source.replicatePower; + researchPower = source.researchPower; + droneEjectEnergy = source.droneEjectEnergy; + droneEnergyPerMeter = source.droneEnergyPerMeter; + coreLevel = source.coreLevel; + thrusterLevel = source.thrusterLevel; + miningSpeed = source.miningSpeed; + replicateSpeed = source.replicateSpeed; + walkSpeed = source.walkSpeed; + jumpSpeed = source.jumpSpeed; + maxSailSpeed = source.maxSailSpeed; + maxWarpSpeed = source.maxWarpSpeed; + buildArea = source.buildArea; + droneCount = source.droneCount; + droneSpeed = source.droneSpeed; + droneMovement = source.droneMovement; + inventorySize = source.player.package.size; + deliveryPackageUnlocked = source.player.deliveryPackage.unlocked; + deliveryPackageColCount = source.player.deliveryPackage.colCount; + deliveryPackageStackSizeMultiplier = source.player.deliveryPackage.stackSizeMultiplier; + } - public PlayerTechBonuses() { } + public double coreEnergyCap { get; set; } + public double corePowerGen { get; set; } + public double reactorPowerGen { get; set; } + public double walkPower { get; set; } + public double jumpEnergy { get; set; } + public double thrustPowerPerAcc { get; set; } + public double warpKeepingPowerPerSpeed { get; set; } + public double warpStartPowerPerSpeed { get; set; } + public double miningPower { get; set; } + public double replicatePower { get; set; } + public double researchPower { get; set; } + public double droneEjectEnergy { get; set; } + public double droneEnergyPerMeter { get; set; } + public int coreLevel { get; set; } + public int thrusterLevel { get; set; } + public float miningSpeed { get; set; } + public float replicateSpeed { get; set; } + public float walkSpeed { get; set; } + public float jumpSpeed { get; set; } + public float maxSailSpeed { get; set; } + public float maxWarpSpeed { get; set; } + public float buildArea { get; set; } + public int droneCount { get; set; } + public float droneSpeed { get; set; } + public int droneMovement { get; set; } + public int inventorySize { get; set; } + public bool deliveryPackageUnlocked { get; set; } + public int deliveryPackageColCount { get; set; } + public int deliveryPackageStackSizeMultiplier { get; set; } - public PlayerTechBonuses(Mecha source) - { - coreEnergyCap = source.coreEnergyCap; - corePowerGen = source.corePowerGen; - reactorPowerGen = source.reactorPowerGen; - walkPower = source.walkPower; - jumpEnergy = source.jumpEnergy; - thrustPowerPerAcc = source.thrustPowerPerAcc; - warpKeepingPowerPerSpeed = source.warpKeepingPowerPerSpeed; - warpStartPowerPerSpeed = source.warpStartPowerPerSpeed; - miningPower = source.miningPower; - replicatePower = source.replicatePower; - researchPower = source.researchPower; - droneEjectEnergy = source.droneEjectEnergy; - droneEnergyPerMeter = source.droneEnergyPerMeter; - coreLevel = source.coreLevel; - thrusterLevel = source.thrusterLevel; - miningSpeed = source.miningSpeed; - replicateSpeed = source.replicateSpeed; - walkSpeed = source.walkSpeed; - jumpSpeed = source.jumpSpeed; - maxSailSpeed = source.maxSailSpeed; - maxWarpSpeed = source.maxWarpSpeed; - buildArea = source.buildArea; - droneCount = source.droneCount; - droneSpeed = source.droneSpeed; - droneMovement = source.droneMovement; - inventorySize = source.player.package.size; - deliveryPackageUnlocked = source.player.deliveryPackage.unlocked; - deliveryPackageColCount = source.player.deliveryPackage.colCount; - deliveryPackageStackSizeMultiplier = source.player.deliveryPackage.stackSizeMultiplier; - } + public void Serialize(INetDataWriter writer) + { + writer.Put(coreEnergyCap); + writer.Put(corePowerGen); + writer.Put(reactorPowerGen); + writer.Put(walkPower); + writer.Put(jumpEnergy); + writer.Put(thrustPowerPerAcc); + writer.Put(warpKeepingPowerPerSpeed); + writer.Put(warpStartPowerPerSpeed); + writer.Put(miningPower); + writer.Put(replicatePower); + writer.Put(researchPower); + writer.Put(droneEjectEnergy); + writer.Put(droneEnergyPerMeter); + writer.Put(coreLevel); + writer.Put(thrusterLevel); + writer.Put(miningSpeed); + writer.Put(replicateSpeed); + writer.Put(walkSpeed); + writer.Put(jumpSpeed); + writer.Put(maxSailSpeed); + writer.Put(maxWarpSpeed); + writer.Put(buildArea); + writer.Put(droneCount); + writer.Put(droneSpeed); + writer.Put(droneMovement); + writer.Put(inventorySize); + writer.Put(deliveryPackageUnlocked); + writer.Put(deliveryPackageColCount); + writer.Put(deliveryPackageStackSizeMultiplier); + } - public void UpdateMech(Mecha destination) + public void Deserialize(INetDataReader reader) + { + coreEnergyCap = reader.GetDouble(); + corePowerGen = reader.GetDouble(); + reactorPowerGen = reader.GetDouble(); + walkPower = reader.GetDouble(); + jumpEnergy = reader.GetDouble(); + thrustPowerPerAcc = reader.GetDouble(); + warpKeepingPowerPerSpeed = reader.GetDouble(); + warpStartPowerPerSpeed = reader.GetDouble(); + miningPower = reader.GetDouble(); + replicatePower = reader.GetDouble(); + researchPower = reader.GetDouble(); + droneEjectEnergy = reader.GetDouble(); + droneEnergyPerMeter = reader.GetDouble(); + coreLevel = reader.GetInt(); + thrusterLevel = reader.GetInt(); + miningSpeed = reader.GetFloat(); + replicateSpeed = reader.GetFloat(); + walkSpeed = reader.GetFloat(); + jumpSpeed = reader.GetFloat(); + maxSailSpeed = reader.GetFloat(); + maxWarpSpeed = reader.GetFloat(); + buildArea = reader.GetFloat(); + droneCount = reader.GetInt(); + droneSpeed = reader.GetFloat(); + droneMovement = reader.GetInt(); + inventorySize = reader.GetInt(); + deliveryPackageUnlocked = reader.GetBool(); + deliveryPackageColCount = reader.GetInt(); + deliveryPackageStackSizeMultiplier = reader.GetInt(); + } + + public void UpdateMech(Mecha destination) + { + destination.coreEnergyCap = coreEnergyCap; + destination.corePowerGen = corePowerGen; + destination.reactorPowerGen = reactorPowerGen; + destination.walkPower = walkPower; + destination.jumpEnergy = jumpEnergy; + destination.thrustPowerPerAcc = thrustPowerPerAcc; + destination.warpKeepingPowerPerSpeed = warpKeepingPowerPerSpeed; + destination.warpStartPowerPerSpeed = warpStartPowerPerSpeed; + destination.miningPower = miningPower; + destination.replicatePower = replicatePower; + destination.researchPower = researchPower; + destination.droneEjectEnergy = droneEjectEnergy; + destination.droneEnergyPerMeter = droneEnergyPerMeter; + destination.coreLevel = coreLevel; + destination.thrusterLevel = thrusterLevel; + destination.miningSpeed = miningSpeed; + destination.replicateSpeed = replicateSpeed; + destination.walkSpeed = walkSpeed; + destination.jumpSpeed = jumpSpeed; + destination.maxSailSpeed = maxSailSpeed; + destination.maxWarpSpeed = maxWarpSpeed; + destination.buildArea = buildArea; + destination.droneCount = droneCount; + destination.droneSpeed = droneSpeed; + destination.droneMovement = droneMovement; + if (inventorySize > destination.player.package.size) { - destination.coreEnergyCap = coreEnergyCap; - destination.corePowerGen = corePowerGen; - destination.reactorPowerGen = reactorPowerGen; - destination.walkPower = walkPower; - destination.jumpEnergy = jumpEnergy; - destination.thrustPowerPerAcc = thrustPowerPerAcc; - destination.warpKeepingPowerPerSpeed = warpKeepingPowerPerSpeed; - destination.warpStartPowerPerSpeed = warpStartPowerPerSpeed; - destination.miningPower = miningPower; - destination.replicatePower = replicatePower; - destination.researchPower = researchPower; - destination.droneEjectEnergy = droneEjectEnergy; - destination.droneEnergyPerMeter = droneEnergyPerMeter; - destination.coreLevel = coreLevel; - destination.thrusterLevel = thrusterLevel; - destination.miningSpeed = miningSpeed; - destination.replicateSpeed = replicateSpeed; - destination.walkSpeed = walkSpeed; - destination.jumpSpeed = jumpSpeed; - destination.maxSailSpeed = maxSailSpeed; - destination.maxWarpSpeed = maxWarpSpeed; - destination.buildArea = buildArea; - destination.droneCount = droneCount; - destination.droneSpeed = droneSpeed; - destination.droneMovement = droneMovement; - if (inventorySize > destination.player.package.size) - { - destination.player.package.SetSize(inventorySize); - } - destination.player.deliveryPackage.unlocked = deliveryPackageUnlocked; - int deliveryPackageRowCount = (destination.player.package.size - 1) / 10 + 1; - if (destination.player.deliveryPackage.rowCount != deliveryPackageRowCount || deliveryPackageColCount != destination.player.deliveryPackage.colCount) - { - destination.player.deliveryPackage.rowCount = deliveryPackageRowCount; - destination.player.deliveryPackage.colCount = deliveryPackageColCount; - destination.player.deliveryPackage.NotifySizeChange(); - } - destination.player.deliveryPackage.stackSizeMultiplier = deliveryPackageStackSizeMultiplier; + destination.player.package.SetSize(inventorySize); } - - public void Serialize(INetDataWriter writer) + destination.player.deliveryPackage.unlocked = deliveryPackageUnlocked; + var deliveryPackageRowCount = (destination.player.package.size - 1) / 10 + 1; + if (destination.player.deliveryPackage.rowCount != deliveryPackageRowCount || + deliveryPackageColCount != destination.player.deliveryPackage.colCount) { - writer.Put(coreEnergyCap); - writer.Put(corePowerGen); - writer.Put(reactorPowerGen); - writer.Put(walkPower); - writer.Put(jumpEnergy); - writer.Put(thrustPowerPerAcc); - writer.Put(warpKeepingPowerPerSpeed); - writer.Put(warpStartPowerPerSpeed); - writer.Put(miningPower); - writer.Put(replicatePower); - writer.Put(researchPower); - writer.Put(droneEjectEnergy); - writer.Put(droneEnergyPerMeter); - writer.Put(coreLevel); - writer.Put(thrusterLevel); - writer.Put(miningSpeed); - writer.Put(replicateSpeed); - writer.Put(walkSpeed); - writer.Put(jumpSpeed); - writer.Put(maxSailSpeed); - writer.Put(maxWarpSpeed); - writer.Put(buildArea); - writer.Put(droneCount); - writer.Put(droneSpeed); - writer.Put(droneMovement); - writer.Put(inventorySize); - writer.Put(deliveryPackageUnlocked); - writer.Put(deliveryPackageColCount); - writer.Put(deliveryPackageStackSizeMultiplier); + destination.player.deliveryPackage.rowCount = deliveryPackageRowCount; + destination.player.deliveryPackage.colCount = deliveryPackageColCount; + destination.player.deliveryPackage.NotifySizeChange(); } + destination.player.deliveryPackage.stackSizeMultiplier = deliveryPackageStackSizeMultiplier; + } - public void Deserialize(INetDataReader reader) + public void Import(INetDataReader reader, int revision) + { + coreEnergyCap = reader.GetDouble(); + corePowerGen = reader.GetDouble(); + reactorPowerGen = reader.GetDouble(); + walkPower = reader.GetDouble(); + jumpEnergy = reader.GetDouble(); + thrustPowerPerAcc = reader.GetDouble(); + warpKeepingPowerPerSpeed = reader.GetDouble(); + warpStartPowerPerSpeed = reader.GetDouble(); + miningPower = reader.GetDouble(); + replicatePower = reader.GetDouble(); + researchPower = reader.GetDouble(); + droneEjectEnergy = reader.GetDouble(); + droneEnergyPerMeter = reader.GetDouble(); + coreLevel = reader.GetInt(); + thrusterLevel = reader.GetInt(); + miningSpeed = reader.GetFloat(); + replicateSpeed = reader.GetFloat(); + walkSpeed = reader.GetFloat(); + jumpSpeed = reader.GetFloat(); + maxSailSpeed = reader.GetFloat(); + maxWarpSpeed = reader.GetFloat(); + buildArea = reader.GetFloat(); + droneCount = reader.GetInt(); + droneSpeed = reader.GetFloat(); + droneMovement = reader.GetInt(); + inventorySize = reader.GetInt(); + if (revision >= 7) { - coreEnergyCap = reader.GetDouble(); - corePowerGen = reader.GetDouble(); - reactorPowerGen = reader.GetDouble(); - walkPower = reader.GetDouble(); - jumpEnergy = reader.GetDouble(); - thrustPowerPerAcc = reader.GetDouble(); - warpKeepingPowerPerSpeed = reader.GetDouble(); - warpStartPowerPerSpeed = reader.GetDouble(); - miningPower = reader.GetDouble(); - replicatePower = reader.GetDouble(); - researchPower = reader.GetDouble(); - droneEjectEnergy = reader.GetDouble(); - droneEnergyPerMeter = reader.GetDouble(); - coreLevel = reader.GetInt(); - thrusterLevel = reader.GetInt(); - miningSpeed = reader.GetFloat(); - replicateSpeed = reader.GetFloat(); - walkSpeed = reader.GetFloat(); - jumpSpeed = reader.GetFloat(); - maxSailSpeed = reader.GetFloat(); - maxWarpSpeed = reader.GetFloat(); - buildArea = reader.GetFloat(); - droneCount = reader.GetInt(); - droneSpeed = reader.GetFloat(); - droneMovement = reader.GetInt(); - inventorySize = reader.GetInt(); deliveryPackageUnlocked = reader.GetBool(); deliveryPackageColCount = reader.GetInt(); deliveryPackageStackSizeMultiplier = reader.GetInt(); } - - public void Import(INetDataReader reader, int revision) - { - coreEnergyCap = reader.GetDouble(); - corePowerGen = reader.GetDouble(); - reactorPowerGen = reader.GetDouble(); - walkPower = reader.GetDouble(); - jumpEnergy = reader.GetDouble(); - thrustPowerPerAcc = reader.GetDouble(); - warpKeepingPowerPerSpeed = reader.GetDouble(); - warpStartPowerPerSpeed = reader.GetDouble(); - miningPower = reader.GetDouble(); - replicatePower = reader.GetDouble(); - researchPower = reader.GetDouble(); - droneEjectEnergy = reader.GetDouble(); - droneEnergyPerMeter = reader.GetDouble(); - coreLevel = reader.GetInt(); - thrusterLevel = reader.GetInt(); - miningSpeed = reader.GetFloat(); - replicateSpeed = reader.GetFloat(); - walkSpeed = reader.GetFloat(); - jumpSpeed = reader.GetFloat(); - maxSailSpeed = reader.GetFloat(); - maxWarpSpeed = reader.GetFloat(); - buildArea = reader.GetFloat(); - droneCount = reader.GetInt(); - droneSpeed = reader.GetFloat(); - droneMovement = reader.GetInt(); - inventorySize = reader.GetInt(); - if (revision >= 7) - { - deliveryPackageUnlocked = reader.GetBool(); - deliveryPackageColCount = reader.GetInt(); - deliveryPackageStackSizeMultiplier = reader.GetInt(); - } - } } } diff --git a/NebulaModel/Packets/Players/PlayerUpdateLocalStarId.cs b/NebulaModel/Packets/Players/PlayerUpdateLocalStarId.cs index 38a7fc912..6329534bc 100644 --- a/NebulaModel/Packets/Players/PlayerUpdateLocalStarId.cs +++ b/NebulaModel/Packets/Players/PlayerUpdateLocalStarId.cs @@ -1,14 +1,13 @@ -namespace NebulaModel.Packets.Players -{ - public class PlayerUpdateLocalStarId - { - public int StarId { get; set; } +namespace NebulaModel.Packets.Players; - public PlayerUpdateLocalStarId() { } +public class PlayerUpdateLocalStarId +{ + public PlayerUpdateLocalStarId() { } - public PlayerUpdateLocalStarId(int starId) - { - StarId = starId; - } + public PlayerUpdateLocalStarId(int starId) + { + StarId = starId; } + + public int StarId { get; set; } } diff --git a/NebulaModel/Packets/Players/RemoveDroneOrdersPacket.cs b/NebulaModel/Packets/Players/RemoveDroneOrdersPacket.cs index 09ed2fff1..7edb656b6 100644 --- a/NebulaModel/Packets/Players/RemoveDroneOrdersPacket.cs +++ b/NebulaModel/Packets/Players/RemoveDroneOrdersPacket.cs @@ -1,14 +1,13 @@ -namespace NebulaNetwork.PacketProcessors.Players -{ - public class RemoveDroneOrdersPacket - { - public int[] QueuedEntityIds { get; set; } +namespace NebulaNetwork.PacketProcessors.Players; - public RemoveDroneOrdersPacket() { } +public class RemoveDroneOrdersPacket +{ + public RemoveDroneOrdersPacket() { } - public RemoveDroneOrdersPacket(int[] queuedEntityIds) - { - QueuedEntityIds = queuedEntityIds; - } + public RemoveDroneOrdersPacket(int[] queuedEntityIds) + { + QueuedEntityIds = queuedEntityIds; } + + public int[] QueuedEntityIds { get; set; } } diff --git a/NebulaModel/Packets/Routers/PlanetBroadcastPacket.cs b/NebulaModel/Packets/Routers/PlanetBroadcastPacket.cs index 0f1e67cb0..ce15aa14d 100644 --- a/NebulaModel/Packets/Routers/PlanetBroadcastPacket.cs +++ b/NebulaModel/Packets/Routers/PlanetBroadcastPacket.cs @@ -1,15 +1,15 @@ -namespace NebulaModel.Packets.Routers +namespace NebulaModel.Packets.Routers; + +public class PlanetBroadcastPacket { - public class PlanetBroadcastPacket - { - public byte[] PacketObject { get; set; } - public int PlanetId { get; set; } + public PlanetBroadcastPacket() { } - public PlanetBroadcastPacket() { } - public PlanetBroadcastPacket(byte[] packetObject, int planetId) - { - PacketObject = packetObject; - PlanetId = planetId; - } + public PlanetBroadcastPacket(byte[] packetObject, int planetId) + { + PacketObject = packetObject; + PlanetId = planetId; } + + public byte[] PacketObject { get; set; } + public int PlanetId { get; set; } } diff --git a/NebulaModel/Packets/Routers/StarBroadcastPacket.cs b/NebulaModel/Packets/Routers/StarBroadcastPacket.cs index 6efc67cac..ed8348db1 100644 --- a/NebulaModel/Packets/Routers/StarBroadcastPacket.cs +++ b/NebulaModel/Packets/Routers/StarBroadcastPacket.cs @@ -1,15 +1,15 @@ -namespace NebulaModel.Packets.Routers +namespace NebulaModel.Packets.Routers; + +public class StarBroadcastPacket { - public class StarBroadcastPacket - { - public byte[] PacketObject { get; set; } - public int StarId { get; set; } + public StarBroadcastPacket() { } - public StarBroadcastPacket() { } - public StarBroadcastPacket(byte[] packetObject, int starId) - { - PacketObject = packetObject; - StarId = starId; - } + public StarBroadcastPacket(byte[] packetObject, int starId) + { + PacketObject = packetObject; + StarId = starId; } + + public byte[] PacketObject { get; set; } + public int StarId { get; set; } } diff --git a/NebulaModel/Packets/Session/GlobalGameDataRequest.cs b/NebulaModel/Packets/Session/GlobalGameDataRequest.cs index 0b7f90b85..586b5f029 100644 --- a/NebulaModel/Packets/Session/GlobalGameDataRequest.cs +++ b/NebulaModel/Packets/Session/GlobalGameDataRequest.cs @@ -1,7 +1,5 @@ -namespace NebulaModel.Packets.Session +namespace NebulaModel.Packets.Session; + +public class GlobalGameDataRequest { - public class GlobalGameDataRequest - { - public GlobalGameDataRequest() { } - } } diff --git a/NebulaModel/Packets/Session/HandshakeRequest.cs b/NebulaModel/Packets/Session/HandshakeRequest.cs index dbe8d95a0..0b23fc4e9 100644 --- a/NebulaModel/Packets/Session/HandshakeRequest.cs +++ b/NebulaModel/Packets/Session/HandshakeRequest.cs @@ -1,57 +1,61 @@ -using NebulaAPI; +#region + +using BepInEx.Bootstrap; +using NebulaAPI; using NebulaModel.Networking; +#endregion + /* * This packet is only here to handle older clients and tell them to upgrade to a newer nebula version. (this packet was replaced by the lobby packets) */ -namespace NebulaModel.Packets.Session +namespace NebulaModel.Packets.Session; + +public class HandshakeRequest { - public class HandshakeRequest - { - public string Username { get; set; } - public Float4[] MechaColors { get; set; } - public byte[] ModsVersion { get; set; } - public int ModsCount { get; set; } - public int GameVersionSig { get; set; } - public byte[] ClientCert { get; set; } + public HandshakeRequest() { } - public HandshakeRequest() { } + public HandshakeRequest(byte[] clientCert, string username, Float4[] mechaColors) + { + Username = username; + MechaColors = mechaColors; - public HandshakeRequest(byte[] clientCert, string username, Float4[] mechaColors) + using (var writer = new BinaryUtils.Writer()) { - Username = username; - MechaColors = mechaColors; - - using (BinaryUtils.Writer writer = new BinaryUtils.Writer()) + var count = 0; + foreach (var pluginInfo in Chainloader.PluginInfos) { - int count = 0; - foreach (System.Collections.Generic.KeyValuePair pluginInfo in BepInEx.Bootstrap.Chainloader.PluginInfos) + if (pluginInfo.Value.Instance is IMultiplayerMod mod) { - if (pluginInfo.Value.Instance is IMultiplayerMod mod) - { - writer.BinaryWriter.Write(pluginInfo.Key); - writer.BinaryWriter.Write(mod.Version); - count++; - } - else + writer.BinaryWriter.Write(pluginInfo.Key); + writer.BinaryWriter.Write(mod.Version); + count++; + } + else + { + foreach (var dependency in pluginInfo.Value.Dependencies) { - foreach (BepInEx.BepInDependency dependency in pluginInfo.Value.Dependencies) + if (dependency.DependencyGUID == NebulaModAPI.API_GUID) { - if (dependency.DependencyGUID == NebulaModAPI.API_GUID) - { - writer.BinaryWriter.Write(pluginInfo.Key); - writer.BinaryWriter.Write(pluginInfo.Value.Metadata.Version.ToString()); - } + writer.BinaryWriter.Write(pluginInfo.Key); + writer.BinaryWriter.Write(pluginInfo.Value.Metadata.Version.ToString()); } } } - - ModsVersion = writer.CloseAndGetBytes(); - ModsCount = count; } - GameVersionSig = GameConfig.gameVersion.sig; - ClientCert = clientCert; + ModsVersion = writer.CloseAndGetBytes(); + ModsCount = count; } + + GameVersionSig = GameConfig.gameVersion.sig; + ClientCert = clientCert; } -} \ No newline at end of file + + public string Username { get; set; } + public Float4[] MechaColors { get; set; } + public byte[] ModsVersion { get; set; } + public int ModsCount { get; set; } + public int GameVersionSig { get; set; } + public byte[] ClientCert { get; set; } +} diff --git a/NebulaModel/Packets/Session/HandshakeResponse.cs b/NebulaModel/Packets/Session/HandshakeResponse.cs index 6ae9c39de..198d6bb96 100644 --- a/NebulaModel/Packets/Session/HandshakeResponse.cs +++ b/NebulaModel/Packets/Session/HandshakeResponse.cs @@ -1,40 +1,44 @@ -using NebulaModel.DataStructures; +#region -namespace NebulaModel.Packets.Session -{ - public class HandshakeResponse - { - public int GalaxyAlgo { get; set; } - public int GalaxySeed { get; set; } - public int StarCount { get; set; } - public float ResourceMultiplier { get; set; } - public bool IsSandboxMode { get; set; } - public int[] SavedThemeIds { get; set; } - public bool IsNewPlayer { get; set; } - public PlayerData LocalPlayerData { get; set; } - public byte[] ModsSettings { get; set; } - public int ModsSettingsCount { get; set; } - public bool SyncSoil { get; set; } - public ushort NumPlayers { get; set; } - public string DiscordPartyId { get; set; } +using NebulaModel.DataStructures; - public HandshakeResponse() { } +#endregion - public HandshakeResponse(in GameDesc gameDesc, bool isNewPlayer, PlayerData localPlayerData, byte[] modsSettings, int settingsCount, bool syncSoil, ushort numPlayers, string discordPartyId) - { - GalaxyAlgo = gameDesc.galaxyAlgo; - GalaxySeed = gameDesc.galaxySeed; - StarCount = gameDesc.starCount; - ResourceMultiplier = gameDesc.resourceMultiplier; - IsSandboxMode = gameDesc.isSandboxMode; - SavedThemeIds = gameDesc.savedThemeIds; - IsNewPlayer = isNewPlayer; - LocalPlayerData = localPlayerData; - ModsSettings = modsSettings; - ModsSettingsCount = settingsCount; - SyncSoil = syncSoil; - NumPlayers = numPlayers; - DiscordPartyId = discordPartyId; - } +namespace NebulaModel.Packets.Session; + +public class HandshakeResponse +{ + public HandshakeResponse() { } + + public HandshakeResponse(in GameDesc gameDesc, bool isNewPlayer, PlayerData localPlayerData, byte[] modsSettings, + int settingsCount, bool syncSoil, ushort numPlayers, string discordPartyId) + { + GalaxyAlgo = gameDesc.galaxyAlgo; + GalaxySeed = gameDesc.galaxySeed; + StarCount = gameDesc.starCount; + ResourceMultiplier = gameDesc.resourceMultiplier; + IsSandboxMode = gameDesc.isSandboxMode; + SavedThemeIds = gameDesc.savedThemeIds; + IsNewPlayer = isNewPlayer; + LocalPlayerData = localPlayerData; + ModsSettings = modsSettings; + ModsSettingsCount = settingsCount; + SyncSoil = syncSoil; + NumPlayers = numPlayers; + DiscordPartyId = discordPartyId; } + + public int GalaxyAlgo { get; set; } + public int GalaxySeed { get; set; } + public int StarCount { get; set; } + public float ResourceMultiplier { get; set; } + public bool IsSandboxMode { get; set; } + public int[] SavedThemeIds { get; set; } + public bool IsNewPlayer { get; set; } + public PlayerData LocalPlayerData { get; set; } + public byte[] ModsSettings { get; set; } + public int ModsSettingsCount { get; set; } + public bool SyncSoil { get; set; } + public ushort NumPlayers { get; set; } + public string DiscordPartyId { get; set; } } diff --git a/NebulaModel/Packets/Session/LobbyRequest.cs b/NebulaModel/Packets/Session/LobbyRequest.cs index 810bcca63..d5b5d215f 100644 --- a/NebulaModel/Packets/Session/LobbyRequest.cs +++ b/NebulaModel/Packets/Session/LobbyRequest.cs @@ -1,51 +1,57 @@ -using NebulaAPI; +#region + +using BepInEx.Bootstrap; +using NebulaAPI; using NebulaModel.Networking; -namespace NebulaModel.Packets.Session +#endregion + +namespace NebulaModel.Packets.Session; + +public class LobbyRequest { - public class LobbyRequest + public LobbyRequest() { } + + public LobbyRequest(byte[] clientCert, string username) { - public string Username { get; set; } - public byte[] ModsVersion { get; set; } - public int ModsCount { get; set; } - public int GameVersionSig { get; set; } - public byte[] ClientCert { get; set; } - public LobbyRequest() { } - public LobbyRequest(byte[] clientCert, string username) - { - Username = username; + Username = username; - using (BinaryUtils.Writer writer = new BinaryUtils.Writer()) + using (var writer = new BinaryUtils.Writer()) + { + var count = 0; + foreach (var pluginInfo in Chainloader.PluginInfos) { - int count = 0; - foreach (System.Collections.Generic.KeyValuePair pluginInfo in BepInEx.Bootstrap.Chainloader.PluginInfos) + if (pluginInfo.Value.Instance is IMultiplayerMod mod) { - if (pluginInfo.Value.Instance is IMultiplayerMod mod) - { - writer.BinaryWriter.Write(pluginInfo.Key); - writer.BinaryWriter.Write(mod.Version); - count++; - } - else + writer.BinaryWriter.Write(pluginInfo.Key); + writer.BinaryWriter.Write(mod.Version); + count++; + } + else + { + foreach (var dependency in pluginInfo.Value.Dependencies) { - foreach (BepInEx.BepInDependency dependency in pluginInfo.Value.Dependencies) + if (dependency.DependencyGUID == NebulaModAPI.API_GUID) { - if (dependency.DependencyGUID == NebulaModAPI.API_GUID) - { - writer.BinaryWriter.Write(pluginInfo.Key); - writer.BinaryWriter.Write(pluginInfo.Value.Metadata.Version.ToString()); - count++; - } + writer.BinaryWriter.Write(pluginInfo.Key); + writer.BinaryWriter.Write(pluginInfo.Value.Metadata.Version.ToString()); + count++; } } } - - ModsVersion = writer.CloseAndGetBytes(); - ModsCount = count; } - GameVersionSig = GameConfig.gameVersion.sig; - ClientCert = clientCert; + ModsVersion = writer.CloseAndGetBytes(); + ModsCount = count; } + + GameVersionSig = GameConfig.gameVersion.sig; + ClientCert = clientCert; } + + public string Username { get; set; } + public byte[] ModsVersion { get; set; } + public int ModsCount { get; set; } + public int GameVersionSig { get; set; } + public byte[] ClientCert { get; set; } } diff --git a/NebulaModel/Packets/Session/LobbyResponse.cs b/NebulaModel/Packets/Session/LobbyResponse.cs index 7f817f814..3c462447c 100644 --- a/NebulaModel/Packets/Session/LobbyResponse.cs +++ b/NebulaModel/Packets/Session/LobbyResponse.cs @@ -1,31 +1,31 @@ -namespace NebulaModel.Packets.Session +namespace NebulaModel.Packets.Session; + +public class LobbyResponse { - public class LobbyResponse - { - public int GalaxyAlgo { get; set; } - public int GalaxySeed { get; set; } - public int StarCount { get; set; } - public float ResourceMultiplier { get; set; } - public bool IsSandboxMode { get; set; } - public int[] SavedThemeIds { get; set; } - public byte[] ModsSettings { get; set; } - public int ModsSettingsCount { get; set; } - public ushort NumPlayers { get; set; } - public string DiscordPartyId { get; set; } + public LobbyResponse() { } - public LobbyResponse() { } - public LobbyResponse(in GameDesc gameDesc, byte[] modsSettings, int settingsCount, ushort numPlayers, string discordPartyId) - { - GalaxyAlgo = gameDesc.galaxyAlgo; - GalaxySeed = gameDesc.galaxySeed; - StarCount = gameDesc.starCount; - ResourceMultiplier = gameDesc.resourceMultiplier; - IsSandboxMode = gameDesc.isSandboxMode; - SavedThemeIds = gameDesc.savedThemeIds; - ModsSettings = modsSettings; - ModsSettingsCount = settingsCount; - NumPlayers = numPlayers; - DiscordPartyId = discordPartyId; - } + public LobbyResponse(in GameDesc gameDesc, byte[] modsSettings, int settingsCount, ushort numPlayers, string discordPartyId) + { + GalaxyAlgo = gameDesc.galaxyAlgo; + GalaxySeed = gameDesc.galaxySeed; + StarCount = gameDesc.starCount; + ResourceMultiplier = gameDesc.resourceMultiplier; + IsSandboxMode = gameDesc.isSandboxMode; + SavedThemeIds = gameDesc.savedThemeIds; + ModsSettings = modsSettings; + ModsSettingsCount = settingsCount; + NumPlayers = numPlayers; + DiscordPartyId = discordPartyId; } + + public int GalaxyAlgo { get; set; } + public int GalaxySeed { get; set; } + public int StarCount { get; set; } + public float ResourceMultiplier { get; set; } + public bool IsSandboxMode { get; set; } + public int[] SavedThemeIds { get; set; } + public byte[] ModsSettings { get; set; } + public int ModsSettingsCount { get; set; } + public ushort NumPlayers { get; set; } + public string DiscordPartyId { get; set; } } diff --git a/NebulaModel/Packets/Session/LobbyUpdateValues.cs b/NebulaModel/Packets/Session/LobbyUpdateValues.cs index 96ea7a53d..3a70129a6 100644 --- a/NebulaModel/Packets/Session/LobbyUpdateValues.cs +++ b/NebulaModel/Packets/Session/LobbyUpdateValues.cs @@ -1,21 +1,21 @@ -namespace NebulaModel.Packets.Session +namespace NebulaModel.Packets.Session; + +public class LobbyUpdateValues { - public class LobbyUpdateValues - { - public int GalaxyAlgo { get; set; } - public int GalaxySeed { get; set; } - public int StarCount { get; set; } - public float ResourceMultiplier { get; set; } - public bool IsSandboxMode { get; set; } + public LobbyUpdateValues() { } - public LobbyUpdateValues() { } - public LobbyUpdateValues(int galaxyAlgo, int galaxySeed, int starCount, float resourceMultiplier, bool isSandboxMode) - { - GalaxyAlgo = galaxyAlgo; - GalaxySeed = galaxySeed; - StarCount = starCount; - ResourceMultiplier = resourceMultiplier; - IsSandboxMode = isSandboxMode; - } + public LobbyUpdateValues(int galaxyAlgo, int galaxySeed, int starCount, float resourceMultiplier, bool isSandboxMode) + { + GalaxyAlgo = galaxyAlgo; + GalaxySeed = galaxySeed; + StarCount = starCount; + ResourceMultiplier = resourceMultiplier; + IsSandboxMode = isSandboxMode; } + + public int GalaxyAlgo { get; set; } + public int GalaxySeed { get; set; } + public int StarCount { get; set; } + public float ResourceMultiplier { get; set; } + public bool IsSandboxMode { get; set; } } diff --git a/NebulaModel/Packets/Session/PlayerDisconnected.cs b/NebulaModel/Packets/Session/PlayerDisconnected.cs index 5d9c9f080..d6712fe48 100644 --- a/NebulaModel/Packets/Session/PlayerDisconnected.cs +++ b/NebulaModel/Packets/Session/PlayerDisconnected.cs @@ -1,15 +1,15 @@ -namespace NebulaModel.Packets.Session +namespace NebulaModel.Packets.Session; + +public class PlayerDisconnected { - public class PlayerDisconnected - { - public ushort PlayerId { get; set; } - public ushort NumPlayers { get; set; } + public PlayerDisconnected() { } - public PlayerDisconnected() { } - public PlayerDisconnected(ushort playerId, ushort numPlayers) - { - PlayerId = playerId; - NumPlayers = numPlayers; - } + public PlayerDisconnected(ushort playerId, ushort numPlayers) + { + PlayerId = playerId; + NumPlayers = numPlayers; } + + public ushort PlayerId { get; set; } + public ushort NumPlayers { get; set; } } diff --git a/NebulaModel/Packets/Session/PlayerJoining.cs b/NebulaModel/Packets/Session/PlayerJoining.cs index 2402b0bb3..8d6458cbf 100644 --- a/NebulaModel/Packets/Session/PlayerJoining.cs +++ b/NebulaModel/Packets/Session/PlayerJoining.cs @@ -1,17 +1,21 @@ -using NebulaModel.DataStructures; +#region -namespace NebulaModel.Packets.Session +using NebulaModel.DataStructures; + +#endregion + +namespace NebulaModel.Packets.Session; + +public class PlayerJoining { - public class PlayerJoining - { - public PlayerData PlayerData { get; set; } - public ushort NumPlayers { get; set; } + public PlayerJoining() { } - public PlayerJoining() { } - public PlayerJoining(PlayerData playerData, ushort numPlayers) - { - PlayerData = playerData; - NumPlayers = numPlayers; - } + public PlayerJoining(PlayerData playerData, ushort numPlayers) + { + PlayerData = playerData; + NumPlayers = numPlayers; } + + public PlayerData PlayerData { get; set; } + public ushort NumPlayers { get; set; } } diff --git a/NebulaModel/Packets/Session/StartGameMessage.cs b/NebulaModel/Packets/Session/StartGameMessage.cs index 6ab87f8a1..06ede8c81 100644 --- a/NebulaModel/Packets/Session/StartGameMessage.cs +++ b/NebulaModel/Packets/Session/StartGameMessage.cs @@ -1,18 +1,23 @@ -using NebulaModel.DataStructures; +#region -namespace NebulaModel.Packets.Session +using NebulaModel.DataStructures; + +#endregion + +namespace NebulaModel.Packets.Session; + +public class StartGameMessage { - public class StartGameMessage + public StartGameMessage() { } + + public StartGameMessage(bool isAllowedToStart, PlayerData localPlayerData, bool syncSoil) { - public bool IsAllowedToStart { get; set; } - public PlayerData LocalPlayerData { get; set; } - public bool SyncSoil { get; set; } - public StartGameMessage() { } - public StartGameMessage(bool isAllowedToStart, PlayerData localPlayerData, bool syncSoil) - { - IsAllowedToStart = isAllowedToStart; - LocalPlayerData = localPlayerData; - SyncSoil = syncSoil; - } + IsAllowedToStart = isAllowedToStart; + LocalPlayerData = localPlayerData; + SyncSoil = syncSoil; } + + public bool IsAllowedToStart { get; set; } + public PlayerData LocalPlayerData { get; set; } + public bool SyncSoil { get; set; } } diff --git a/NebulaModel/Packets/Session/SyncComplete.cs b/NebulaModel/Packets/Session/SyncComplete.cs index 25301602e..02643d3ea 100644 --- a/NebulaModel/Packets/Session/SyncComplete.cs +++ b/NebulaModel/Packets/Session/SyncComplete.cs @@ -1,28 +1,33 @@ -using NebulaAPI; -using NebulaModel.DataStructures; +#region + using System.Linq; +using NebulaAPI; +using NebulaModel.DataStructures; -namespace NebulaModel.Packets.Session +#endregion + +namespace NebulaModel.Packets.Session; + +public class SyncComplete { - public class SyncComplete + public SyncComplete() { - public PlayerData[] AllPlayers { get; set; } - public byte[] ClientCert { get; set; } + AllPlayers = new PlayerData[] { }; + ClientCert = new byte[] { }; + } - public SyncComplete() - { - AllPlayers = new PlayerData[] { }; - ClientCert = new byte[] { }; - } - public SyncComplete(IPlayerData[] otherPlayers) - { - AllPlayers = otherPlayers.Select(data => (PlayerData)data).ToArray(); - ClientCert = new byte[] { }; - } - public SyncComplete(byte[] clientCert) - { - AllPlayers = new PlayerData[] { }; - ClientCert = clientCert; - } + public SyncComplete(IPlayerData[] otherPlayers) + { + AllPlayers = otherPlayers.Select(data => (PlayerData)data).ToArray(); + ClientCert = new byte[] { }; } + + public SyncComplete(byte[] clientCert) + { + AllPlayers = new PlayerData[] { }; + ClientCert = clientCert; + } + + public PlayerData[] AllPlayers { get; set; } + public byte[] ClientCert { get; set; } } diff --git a/NebulaModel/Packets/Statistics/MilestoneDataResponse.cs b/NebulaModel/Packets/Statistics/MilestoneDataResponse.cs index b94ad231f..a38458b18 100644 --- a/NebulaModel/Packets/Statistics/MilestoneDataResponse.cs +++ b/NebulaModel/Packets/Statistics/MilestoneDataResponse.cs @@ -1,13 +1,13 @@ -namespace NebulaModel.Packets.Statistics +namespace NebulaModel.Packets.Statistics; + +public class MilestoneDataResponse { - public class MilestoneDataResponse - { - public byte[] BinaryData { get; set; } + public MilestoneDataResponse() { } - public MilestoneDataResponse() { } - public MilestoneDataResponse(byte[] binaryData) - { - BinaryData = binaryData; - } + public MilestoneDataResponse(byte[] binaryData) + { + BinaryData = binaryData; } + + public byte[] BinaryData { get; set; } } diff --git a/NebulaModel/Packets/Statistics/MilestoneUnlockPacket.cs b/NebulaModel/Packets/Statistics/MilestoneUnlockPacket.cs index 2cd52b141..3da2b4a24 100644 --- a/NebulaModel/Packets/Statistics/MilestoneUnlockPacket.cs +++ b/NebulaModel/Packets/Statistics/MilestoneUnlockPacket.cs @@ -1,19 +1,19 @@ -namespace NebulaModel.Packets.Statistics +namespace NebulaModel.Packets.Statistics; + +public class MilestoneUnlockPacket { - public class MilestoneUnlockPacket - { - public int Id { get; set; } - public long UnlockTick { get; set; } - public int PatternId { get; set; } - public long[] Parameters { get; set; } + public MilestoneUnlockPacket() { } - public MilestoneUnlockPacket() { } - public MilestoneUnlockPacket(int id, long unlockTick, int patternId, long[] parameters) - { - Id = id; - UnlockTick = unlockTick; - PatternId = patternId; - Parameters = parameters; - } + public MilestoneUnlockPacket(int id, long unlockTick, int patternId, long[] parameters) + { + Id = id; + UnlockTick = unlockTick; + PatternId = patternId; + Parameters = parameters; } + + public int Id { get; set; } + public long UnlockTick { get; set; } + public int PatternId { get; set; } + public long[] Parameters { get; set; } } diff --git a/NebulaModel/Packets/Statistics/StatisticUpdateDataPacket.cs b/NebulaModel/Packets/Statistics/StatisticUpdateDataPacket.cs index cf4af6554..568f7a428 100644 --- a/NebulaModel/Packets/Statistics/StatisticUpdateDataPacket.cs +++ b/NebulaModel/Packets/Statistics/StatisticUpdateDataPacket.cs @@ -1,13 +1,13 @@ -namespace NebulaModel.Packets.Statistics +namespace NebulaModel.Packets.Statistics; + +public class StatisticUpdateDataPacket { - public class StatisticUpdateDataPacket - { - public byte[] StatisticsBinaryData { get; set; } + public StatisticUpdateDataPacket() { } - public StatisticUpdateDataPacket() { } - public StatisticUpdateDataPacket(byte[] statisticsBinaryData) - { - StatisticsBinaryData = statisticsBinaryData; - } + public StatisticUpdateDataPacket(byte[] statisticsBinaryData) + { + StatisticsBinaryData = statisticsBinaryData; } + + public byte[] StatisticsBinaryData { get; set; } } diff --git a/NebulaModel/Packets/Statistics/StatisticsDataPacket.cs b/NebulaModel/Packets/Statistics/StatisticsDataPacket.cs index 6f21382ec..91093e067 100644 --- a/NebulaModel/Packets/Statistics/StatisticsDataPacket.cs +++ b/NebulaModel/Packets/Statistics/StatisticsDataPacket.cs @@ -1,13 +1,13 @@ -namespace NebulaModel.Packets.Statistics +namespace NebulaModel.Packets.Statistics; + +public class StatisticsDataPacket { - public class StatisticsDataPacket - { - public byte[] StatisticsBinaryData { get; set; } + public StatisticsDataPacket() { } - public StatisticsDataPacket() { } - public StatisticsDataPacket(byte[] statisticsBinaryData) - { - StatisticsBinaryData = statisticsBinaryData; - } + public StatisticsDataPacket(byte[] statisticsBinaryData) + { + StatisticsBinaryData = statisticsBinaryData; } + + public byte[] StatisticsBinaryData { get; set; } } diff --git a/NebulaModel/Packets/Statistics/StatisticsRequestEvent.cs b/NebulaModel/Packets/Statistics/StatisticsRequestEvent.cs index 643c3d6cd..8be140e8a 100644 --- a/NebulaModel/Packets/Statistics/StatisticsRequestEvent.cs +++ b/NebulaModel/Packets/Statistics/StatisticsRequestEvent.cs @@ -1,19 +1,19 @@ -namespace NebulaModel.Packets.Statistics -{ - public class StatisticsRequestEvent - { - public StatisticEvent Event { get; set; } +namespace NebulaModel.Packets.Statistics; - public StatisticsRequestEvent() { } - public StatisticsRequestEvent(StatisticEvent Event) - { - this.Event = Event; - } - } +public class StatisticsRequestEvent +{ + public StatisticsRequestEvent() { } - public enum StatisticEvent + public StatisticsRequestEvent(StatisticEvent Event) { - WindowOpened = 1, - WindowClosed = 2 + this.Event = Event; } + + public StatisticEvent Event { get; set; } +} + +public enum StatisticEvent +{ + WindowOpened = 1, + WindowClosed = 2 } diff --git a/NebulaModel/Packets/Trash/TrashSystemClearAllTrashPacket.cs b/NebulaModel/Packets/Trash/TrashSystemClearAllTrashPacket.cs index 7bf027275..308f79a1b 100644 --- a/NebulaModel/Packets/Trash/TrashSystemClearAllTrashPacket.cs +++ b/NebulaModel/Packets/Trash/TrashSystemClearAllTrashPacket.cs @@ -1,7 +1,5 @@ -namespace NebulaModel.Packets.Trash +namespace NebulaModel.Packets.Trash; + +public class TrashSystemClearAllTrashPacket { - public class TrashSystemClearAllTrashPacket - { - public TrashSystemClearAllTrashPacket() { } - } } diff --git a/NebulaModel/Packets/Trash/TrashSystemNewTrashCreatedPacket.cs b/NebulaModel/Packets/Trash/TrashSystemNewTrashCreatedPacket.cs index 7067460e8..89fa12e17 100644 --- a/NebulaModel/Packets/Trash/TrashSystemNewTrashCreatedPacket.cs +++ b/NebulaModel/Packets/Trash/TrashSystemNewTrashCreatedPacket.cs @@ -1,55 +1,60 @@ -using NebulaModel.Networking; +#region -namespace NebulaModel.Packets.Trash +using NebulaModel.Networking; + +#endregion + +namespace NebulaModel.Packets.Trash; + +public class TrashSystemNewTrashCreatedPacket { - public class TrashSystemNewTrashCreatedPacket + public TrashSystemNewTrashCreatedPacket() { } + + public TrashSystemNewTrashCreatedPacket(int trashId, TrashObject trashObj, TrashData trashData, ushort playerId, + int localPlanetId) { - public int TrashId { get; set; } - public byte[] TrashObjectByte { get; set; } - public byte[] TrashDataByte { get; set; } - public int Count { get; set; } - public ushort PlayerId { get; set; } - public int LocalPlanetId { get; set; } - - public TrashSystemNewTrashCreatedPacket() { } - public TrashSystemNewTrashCreatedPacket(int trashId, TrashObject trashObj, TrashData trashData, ushort playerId, int localPlanetId) + TrashId = trashId; + using (var writer = new BinaryUtils.Writer()) + { + trashObj.Export(writer.BinaryWriter); + TrashObjectByte = writer.CloseAndGetBytes(); + } + using (var writer = new BinaryUtils.Writer()) { - TrashId = trashId; - using (BinaryUtils.Writer writer = new BinaryUtils.Writer()) - { - trashObj.Export(writer.BinaryWriter); - TrashObjectByte = writer.CloseAndGetBytes(); - } - using (BinaryUtils.Writer writer = new BinaryUtils.Writer()) - { - trashData.Export(writer.BinaryWriter); - TrashDataByte = writer.CloseAndGetBytes(); - } - // Fix overflow in TrashObj.Export() for item.count - Count = trashObj.count; - LocalPlanetId = localPlanetId; - PlayerId = playerId; + trashData.Export(writer.BinaryWriter); + TrashDataByte = writer.CloseAndGetBytes(); } + // Fix overflow in TrashObj.Export() for item.count + Count = trashObj.count; + LocalPlanetId = localPlanetId; + PlayerId = playerId; + } + + public int TrashId { get; set; } + public byte[] TrashObjectByte { get; set; } + public byte[] TrashDataByte { get; set; } + public int Count { get; set; } + public ushort PlayerId { get; set; } + public int LocalPlanetId { get; set; } - public TrashObject GetTrashObject() - { - using (BinaryUtils.Reader reader = new BinaryUtils.Reader(TrashObjectByte)) - { - TrashObject result = new TrashObject(); - result.Import(reader.BinaryReader); - result.count = Count; - return result; - } + public TrashObject GetTrashObject() + { + using (var reader = new BinaryUtils.Reader(TrashObjectByte)) + { + var result = new TrashObject(); + result.Import(reader.BinaryReader); + result.count = Count; + return result; } + } - public TrashData GetTrashData() + public TrashData GetTrashData() + { + using (var reader = new BinaryUtils.Reader(TrashDataByte)) { - using (BinaryUtils.Reader reader = new BinaryUtils.Reader(TrashDataByte)) - { - TrashData result = new TrashData(); - result.Import(reader.BinaryReader); - return result; - } + var result = new TrashData(); + result.Import(reader.BinaryReader); + return result; } } } diff --git a/NebulaModel/Packets/Trash/TrashSystemResponseDataPacket.cs b/NebulaModel/Packets/Trash/TrashSystemResponseDataPacket.cs index ec74b1b39..9b6f76edc 100644 --- a/NebulaModel/Packets/Trash/TrashSystemResponseDataPacket.cs +++ b/NebulaModel/Packets/Trash/TrashSystemResponseDataPacket.cs @@ -1,14 +1,13 @@ -namespace NebulaModel.Packets.Trash -{ - public class TrashSystemResponseDataPacket - { - public byte[] TrashSystemData { get; set; } +namespace NebulaModel.Packets.Trash; - public TrashSystemResponseDataPacket() { } +public class TrashSystemResponseDataPacket +{ + public TrashSystemResponseDataPacket() { } - public TrashSystemResponseDataPacket(byte[] trashSystemData) - { - TrashSystemData = trashSystemData; - } + public TrashSystemResponseDataPacket(byte[] trashSystemData) + { + TrashSystemData = trashSystemData; } + + public byte[] TrashSystemData { get; set; } } diff --git a/NebulaModel/Packets/Trash/TrashSystemTrashRemovedPacket.cs b/NebulaModel/Packets/Trash/TrashSystemTrashRemovedPacket.cs index 760158dee..f566b35af 100644 --- a/NebulaModel/Packets/Trash/TrashSystemTrashRemovedPacket.cs +++ b/NebulaModel/Packets/Trash/TrashSystemTrashRemovedPacket.cs @@ -1,14 +1,13 @@ -namespace NebulaModel.Packets.Trash -{ - public class TrashSystemTrashRemovedPacket - { - public int TrashId { get; set; } +namespace NebulaModel.Packets.Trash; - public TrashSystemTrashRemovedPacket() { } +public class TrashSystemTrashRemovedPacket +{ + public TrashSystemTrashRemovedPacket() { } - public TrashSystemTrashRemovedPacket(int trashId) - { - TrashId = trashId; - } + public TrashSystemTrashRemovedPacket(int trashId) + { + TrashId = trashId; } + + public int TrashId { get; set; } } diff --git a/NebulaModel/Packets/Universe/DysonLaunchDataPacket.cs b/NebulaModel/Packets/Universe/DysonLaunchDataPacket.cs index 66b9e2696..9cefcaf97 100644 --- a/NebulaModel/Packets/Universe/DysonLaunchDataPacket.cs +++ b/NebulaModel/Packets/Universe/DysonLaunchDataPacket.cs @@ -1,17 +1,21 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.DataStructures; -namespace NebulaModel.Packets.Universe +#endregion + +namespace NebulaModel.Packets.Universe; + +[HidePacketInDebugLogs] +public class DysonLaunchDataPacket { - [HidePacketInDebugLogs] - public class DysonLaunchDataPacket - { - public DysonLaunchData Data { get; set; } + public DysonLaunchDataPacket() { } - public DysonLaunchDataPacket() { } - public DysonLaunchDataPacket(DysonLaunchData data) - { - Data = data; - } + public DysonLaunchDataPacket(DysonLaunchData data) + { + Data = data; } + + public DysonLaunchData Data { get; set; } } diff --git a/NebulaModel/Packets/Universe/DysonSailDataPacket.cs b/NebulaModel/Packets/Universe/DysonSailDataPacket.cs index 09a25e7c8..f36768037 100644 --- a/NebulaModel/Packets/Universe/DysonSailDataPacket.cs +++ b/NebulaModel/Packets/Universe/DysonSailDataPacket.cs @@ -1,35 +1,35 @@ #pragma warning disable IDE1006 -namespace NebulaModel.Packets.Universe +namespace NebulaModel.Packets.Universe; + +public class DysonSailDataPacket { - public class DysonSailDataPacket - { - public int StarIndex { get; set; } - public int OrbitId { get; set; } - public long ExpiryTime { get; set; } - public float st { get; set; } - public float px { get; set; } - public float py { get; set; } - public float pz { get; set; } - public float vx { get; set; } - public float vy { get; set; } - public float vz { get; set; } - public float gs { get; set; } + public DysonSailDataPacket() { } - public DysonSailDataPacket() { } - public DysonSailDataPacket(int starIndex, ref DysonSail sail, int orbitId, long expiryTime) - { - StarIndex = starIndex; - OrbitId = orbitId; - ExpiryTime = expiryTime; - st = sail.st; - px = sail.px; - py = sail.py; - pz = sail.pz; - vx = sail.vx; - vy = sail.vy; - vz = sail.vz; - gs = sail.gs; - } + public DysonSailDataPacket(int starIndex, ref DysonSail sail, int orbitId, long expiryTime) + { + StarIndex = starIndex; + OrbitId = orbitId; + ExpiryTime = expiryTime; + st = sail.st; + px = sail.px; + py = sail.py; + pz = sail.pz; + vx = sail.vx; + vy = sail.vy; + vz = sail.vz; + gs = sail.gs; } + + public int StarIndex { get; set; } + public int OrbitId { get; set; } + public long ExpiryTime { get; set; } + public float st { get; set; } + public float px { get; set; } + public float py { get; set; } + public float pz { get; set; } + public float vx { get; set; } + public float vy { get; set; } + public float vz { get; set; } + public float gs { get; set; } } #pragma warning restore IDE1006 diff --git a/NebulaModel/Packets/Universe/DysonSphereData.cs b/NebulaModel/Packets/Universe/DysonSphereData.cs index 8ed7af598..a774f59c6 100644 --- a/NebulaModel/Packets/Universe/DysonSphereData.cs +++ b/NebulaModel/Packets/Universe/DysonSphereData.cs @@ -1,24 +1,24 @@ -namespace NebulaModel.Packets.Universe -{ - public class DysonSphereData - { - public int StarIndex { get; set; } - public byte[] BinaryData { get; set; } - public DysonSphereRespondEvent Event { get; set; } +namespace NebulaModel.Packets.Universe; - public DysonSphereData() { } - public DysonSphereData(int starIndex, byte[] data, DysonSphereRespondEvent respondEvent) - { - StarIndex = starIndex; - BinaryData = data; - Event = respondEvent; - } - } +public class DysonSphereData +{ + public DysonSphereData() { } - public enum DysonSphereRespondEvent + public DysonSphereData(int starIndex, byte[] data, DysonSphereRespondEvent respondEvent) { - List = 1, - Load = 2, - Desync = 3 + StarIndex = starIndex; + BinaryData = data; + Event = respondEvent; } + + public int StarIndex { get; set; } + public byte[] BinaryData { get; set; } + public DysonSphereRespondEvent Event { get; set; } +} + +public enum DysonSphereRespondEvent +{ + List = 1, + Load = 2, + Desync = 3 } diff --git a/NebulaModel/Packets/Universe/DysonSphereLoadRequest.cs b/NebulaModel/Packets/Universe/DysonSphereLoadRequest.cs index 35bcde251..9a11b2ae2 100644 --- a/NebulaModel/Packets/Universe/DysonSphereLoadRequest.cs +++ b/NebulaModel/Packets/Universe/DysonSphereLoadRequest.cs @@ -1,22 +1,22 @@ -namespace NebulaModel.Packets.Universe -{ - public class DysonSphereLoadRequest - { - public int StarIndex { get; set; } - public DysonSphereRequestEvent Event { get; set; } +namespace NebulaModel.Packets.Universe; - public DysonSphereLoadRequest() { } - public DysonSphereLoadRequest(int starIndex, DysonSphereRequestEvent requestEvent) - { - StarIndex = starIndex; - Event = requestEvent; - } - } +public class DysonSphereLoadRequest +{ + public DysonSphereLoadRequest() { } - public enum DysonSphereRequestEvent + public DysonSphereLoadRequest(int starIndex, DysonSphereRequestEvent requestEvent) { - List = 1, - Load = 2, - Unload = 3 + StarIndex = starIndex; + Event = requestEvent; } + + public int StarIndex { get; set; } + public DysonSphereRequestEvent Event { get; set; } +} + +public enum DysonSphereRequestEvent +{ + List = 1, + Load = 2, + Unload = 3 } diff --git a/NebulaModel/Packets/Universe/DysonSphereStatusPacket.cs b/NebulaModel/Packets/Universe/DysonSphereStatusPacket.cs index 21b53865b..e89e5bfde 100644 --- a/NebulaModel/Packets/Universe/DysonSphereStatusPacket.cs +++ b/NebulaModel/Packets/Universe/DysonSphereStatusPacket.cs @@ -1,22 +1,26 @@ -using NebulaAPI; +#region -namespace NebulaModel.Packets.Universe +using NebulaAPI; + +#endregion + +namespace NebulaModel.Packets.Universe; + +[HidePacketInDebugLogs] +public class DysonSphereStatusPacket { - [HidePacketInDebugLogs] - public class DysonSphereStatusPacket - { - public int StarIndex { get; set; } - public float GrossRadius { get; set; } - public long EnergyReqCurrentTick { get; set; } - public long EnergyGenCurrentTick { get; set; } + public DysonSphereStatusPacket() { } - public DysonSphereStatusPacket() {} - public DysonSphereStatusPacket(DysonSphere dysonSphere) - { - StarIndex = dysonSphere.starData.index; - GrossRadius = dysonSphere.grossRadius; - EnergyReqCurrentTick = dysonSphere.energyReqCurrentTick; - EnergyGenCurrentTick = dysonSphere.energyGenCurrentTick; - } + public DysonSphereStatusPacket(DysonSphere dysonSphere) + { + StarIndex = dysonSphere.starData.index; + GrossRadius = dysonSphere.grossRadius; + EnergyReqCurrentTick = dysonSphere.energyReqCurrentTick; + EnergyGenCurrentTick = dysonSphere.energyGenCurrentTick; } + + public int StarIndex { get; set; } + public float GrossRadius { get; set; } + public long EnergyReqCurrentTick { get; set; } + public long EnergyGenCurrentTick { get; set; } } diff --git a/NebulaModel/Packets/Universe/Editor/DysonBlueprintPacket.cs b/NebulaModel/Packets/Universe/Editor/DysonBlueprintPacket.cs index b370bd057..d4270cad4 100644 --- a/NebulaModel/Packets/Universe/Editor/DysonBlueprintPacket.cs +++ b/NebulaModel/Packets/Universe/Editor/DysonBlueprintPacket.cs @@ -1,22 +1,26 @@ -using System.Text; +#region -namespace NebulaModel.Packets.Universe +using System.Text; + +#endregion + +namespace NebulaModel.Packets.Universe; + +public class DysonBlueprintPacket { - public class DysonBlueprintPacket - { - public int StarIndex { get; set; } - public int LayerId { get; set; } - public EDysonBlueprintType BlueprintType {get; set; } - public byte[] BinaryData { get; set; } + public DysonBlueprintPacket() { } - public DysonBlueprintPacket() { } - public DysonBlueprintPacket(int starIndex, int layerId, EDysonBlueprintType blueprintType, string stringData) - { - StarIndex = starIndex; - LayerId = layerId; - BlueprintType = blueprintType; - // because string length may exceed maxStringLength in NetSerializer, convert to char array here - BinaryData = Encoding.ASCII.GetBytes(stringData); - } + public DysonBlueprintPacket(int starIndex, int layerId, EDysonBlueprintType blueprintType, string stringData) + { + StarIndex = starIndex; + LayerId = layerId; + BlueprintType = blueprintType; + // because string length may exceed maxStringLength in NetSerializer, convert to char array here + BinaryData = Encoding.ASCII.GetBytes(stringData); } + + public int StarIndex { get; set; } + public int LayerId { get; set; } + public EDysonBlueprintType BlueprintType { get; set; } + public byte[] BinaryData { get; set; } } diff --git a/NebulaModel/Packets/Universe/Editor/DysonSphereAddFramePacket.cs b/NebulaModel/Packets/Universe/Editor/DysonSphereAddFramePacket.cs index 32ef38a4c..146baa78e 100644 --- a/NebulaModel/Packets/Universe/Editor/DysonSphereAddFramePacket.cs +++ b/NebulaModel/Packets/Universe/Editor/DysonSphereAddFramePacket.cs @@ -1,25 +1,25 @@ -namespace NebulaModel.Packets.Universe +namespace NebulaModel.Packets.Universe; + +public class DysonSphereAddFramePacket { - public class DysonSphereAddFramePacket - { - public int StarIndex { get; set; } - public int LayerId { get; set; } - public int FrameId { get; set; } - public int ProtoId { get; set; } - public int NodeAId { get; set; } - public int NodeBId { get; set; } - public bool Euler { get; set; } + public DysonSphereAddFramePacket() { } - public DysonSphereAddFramePacket() { } - public DysonSphereAddFramePacket(int starIndex, int layerId, int frameId, int protoId, int nodeAId, int nodeBId, bool euler) - { - StarIndex = starIndex; - LayerId = layerId; - FrameId = frameId; - ProtoId = protoId; - NodeAId = nodeAId; - NodeBId = nodeBId; - Euler = euler; - } + public DysonSphereAddFramePacket(int starIndex, int layerId, int frameId, int protoId, int nodeAId, int nodeBId, bool euler) + { + StarIndex = starIndex; + LayerId = layerId; + FrameId = frameId; + ProtoId = protoId; + NodeAId = nodeAId; + NodeBId = nodeBId; + Euler = euler; } + + public int StarIndex { get; set; } + public int LayerId { get; set; } + public int FrameId { get; set; } + public int ProtoId { get; set; } + public int NodeAId { get; set; } + public int NodeBId { get; set; } + public bool Euler { get; set; } } diff --git a/NebulaModel/Packets/Universe/Editor/DysonSphereAddLayerPacket.cs b/NebulaModel/Packets/Universe/Editor/DysonSphereAddLayerPacket.cs index 92e12ae47..2f2ec5898 100644 --- a/NebulaModel/Packets/Universe/Editor/DysonSphereAddLayerPacket.cs +++ b/NebulaModel/Packets/Universe/Editor/DysonSphereAddLayerPacket.cs @@ -1,24 +1,29 @@ -using NebulaAPI; +#region + +using NebulaAPI; using UnityEngine; -namespace NebulaModel.Packets.Universe +#endregion + +namespace NebulaModel.Packets.Universe; + +public class DysonSphereAddLayerPacket { - public class DysonSphereAddLayerPacket - { - public int StarIndex { get; set; } - public int LayerId { get; set; } - public float OrbitRadius { get; set; } - public Float4 OrbitRotation { get; set; } - public float OrbitAngularSpeed { get; set; } + public DysonSphereAddLayerPacket() { } - public DysonSphereAddLayerPacket() { } - public DysonSphereAddLayerPacket(int starIndex, int layerId, float orbitRadius, Quaternion orbitRotation, float orbitAngularSpeed) - { - StarIndex = starIndex; - LayerId = layerId; - OrbitRadius = orbitRadius; - OrbitRotation = new Float4(orbitRotation); - OrbitAngularSpeed = orbitAngularSpeed; - } + public DysonSphereAddLayerPacket(int starIndex, int layerId, float orbitRadius, Quaternion orbitRotation, + float orbitAngularSpeed) + { + StarIndex = starIndex; + LayerId = layerId; + OrbitRadius = orbitRadius; + OrbitRotation = new Float4(orbitRotation); + OrbitAngularSpeed = orbitAngularSpeed; } -} \ No newline at end of file + + public int StarIndex { get; set; } + public int LayerId { get; set; } + public float OrbitRadius { get; set; } + public Float4 OrbitRotation { get; set; } + public float OrbitAngularSpeed { get; set; } +} diff --git a/NebulaModel/Packets/Universe/Editor/DysonSphereAddNodePacket.cs b/NebulaModel/Packets/Universe/Editor/DysonSphereAddNodePacket.cs index e87fbd462..8ea37fba2 100644 --- a/NebulaModel/Packets/Universe/Editor/DysonSphereAddNodePacket.cs +++ b/NebulaModel/Packets/Universe/Editor/DysonSphereAddNodePacket.cs @@ -1,23 +1,27 @@ -using NebulaAPI; +#region -namespace NebulaModel.Packets.Universe +using NebulaAPI; + +#endregion + +namespace NebulaModel.Packets.Universe; + +public class DysonSphereAddNodePacket { - public class DysonSphereAddNodePacket - { - public int StarIndex { get; set; } - public int LayerId { get; set; } - public int NodeId { get; set; } - public int NodeProtoId { get; set; } - public Float3 Position { get; set; } + public DysonSphereAddNodePacket() { } - public DysonSphereAddNodePacket() { } - public DysonSphereAddNodePacket(int starIndex, int layerId, int nodeId, int nodeProtoId, Float3 position) - { - StarIndex = starIndex; - LayerId = layerId; - NodeId = nodeId; - NodeProtoId = nodeProtoId; - Position = position; - } + public DysonSphereAddNodePacket(int starIndex, int layerId, int nodeId, int nodeProtoId, Float3 position) + { + StarIndex = starIndex; + LayerId = layerId; + NodeId = nodeId; + NodeProtoId = nodeProtoId; + Position = position; } + + public int StarIndex { get; set; } + public int LayerId { get; set; } + public int NodeId { get; set; } + public int NodeProtoId { get; set; } + public Float3 Position { get; set; } } diff --git a/NebulaModel/Packets/Universe/Editor/DysonSphereAddShellPacket.cs b/NebulaModel/Packets/Universe/Editor/DysonSphereAddShellPacket.cs index d9ff72c4d..b3cfc8bbe 100644 --- a/NebulaModel/Packets/Universe/Editor/DysonSphereAddShellPacket.cs +++ b/NebulaModel/Packets/Universe/Editor/DysonSphereAddShellPacket.cs @@ -1,23 +1,27 @@ -using System.Collections.Generic; +#region -namespace NebulaModel.Packets.Universe +using System.Collections.Generic; + +#endregion + +namespace NebulaModel.Packets.Universe; + +public class DysonSphereAddShellPacket { - public class DysonSphereAddShellPacket - { - public int StarIndex { get; set; } - public int LayerId { get; set; } - public int ShellId { get; set; } - public int ProtoId { get; set; } - public int[] NodeIds { get; set; } + public DysonSphereAddShellPacket() { } - public DysonSphereAddShellPacket() { } - public DysonSphereAddShellPacket(int starIndex, int layerId, int shellId, int protoId, List nodeIds) - { - StarIndex = starIndex; - LayerId = layerId; - ShellId = shellId; - ProtoId = protoId; - NodeIds = nodeIds.ToArray(); - } + public DysonSphereAddShellPacket(int starIndex, int layerId, int shellId, int protoId, List nodeIds) + { + StarIndex = starIndex; + LayerId = layerId; + ShellId = shellId; + ProtoId = protoId; + NodeIds = nodeIds.ToArray(); } + + public int StarIndex { get; set; } + public int LayerId { get; set; } + public int ShellId { get; set; } + public int ProtoId { get; set; } + public int[] NodeIds { get; set; } } diff --git a/NebulaModel/Packets/Universe/Editor/DysonSphereColorChangePacket.cs b/NebulaModel/Packets/Universe/Editor/DysonSphereColorChangePacket.cs index fad2fbb4e..5d095e9ef 100644 --- a/NebulaModel/Packets/Universe/Editor/DysonSphereColorChangePacket.cs +++ b/NebulaModel/Packets/Universe/Editor/DysonSphereColorChangePacket.cs @@ -1,31 +1,35 @@ -using NebulaAPI; +#region + +using NebulaAPI; using UnityEngine; -namespace NebulaModel.Packets.Universe +#endregion + +namespace NebulaModel.Packets.Universe; + +public class DysonSphereColorChangePacket { - public class DysonSphereColorChangePacket + public enum ComponentType : byte { - public int StarIndex { get; set; } - public int LayerId { get; set; } - public Float4 Color { get; set; } - public ComponentType Type { get; set; } - public int Index { get; set; } + Node, + Frame, + Shell + } - public DysonSphereColorChangePacket() { } - public DysonSphereColorChangePacket(int starIndex, int layerId, Color32 color, ComponentType component, int index) - { - StarIndex = starIndex; - LayerId = layerId; - Color = Float4.ToFloat4(color); - Type = component; - Index = index; - } + public DysonSphereColorChangePacket() { } - public enum ComponentType : byte - { - Node, - Frame, - Shell - } + public DysonSphereColorChangePacket(int starIndex, int layerId, Color32 color, ComponentType component, int index) + { + StarIndex = starIndex; + LayerId = layerId; + Color = Float4.ToFloat4(color); + Type = component; + Index = index; } + + public int StarIndex { get; set; } + public int LayerId { get; set; } + public Float4 Color { get; set; } + public ComponentType Type { get; set; } + public int Index { get; set; } } diff --git a/NebulaModel/Packets/Universe/Editor/DysonSphereEditLayerPacket.cs b/NebulaModel/Packets/Universe/Editor/DysonSphereEditLayerPacket.cs index 99598a2a8..7ed278da8 100644 --- a/NebulaModel/Packets/Universe/Editor/DysonSphereEditLayerPacket.cs +++ b/NebulaModel/Packets/Universe/Editor/DysonSphereEditLayerPacket.cs @@ -1,20 +1,24 @@ -using NebulaAPI; +#region + +using NebulaAPI; using UnityEngine; -namespace NebulaModel.Packets.Universe +#endregion + +namespace NebulaModel.Packets.Universe; + +public class DysonSphereEditLayerPacket { - public class DysonSphereEditLayerPacket - { - public int StarIndex { get; set; } - public int LayerId { get; set; } - public Float4 OrbitRotation { get; set; } + public DysonSphereEditLayerPacket() { } - public DysonSphereEditLayerPacket() { } - public DysonSphereEditLayerPacket(int starIndex, int layerId, Quaternion orbitRotation) - { - StarIndex = starIndex; - LayerId = layerId; - OrbitRotation = new Float4(orbitRotation); - } + public DysonSphereEditLayerPacket(int starIndex, int layerId, Quaternion orbitRotation) + { + StarIndex = starIndex; + LayerId = layerId; + OrbitRotation = new Float4(orbitRotation); } + + public int StarIndex { get; set; } + public int LayerId { get; set; } + public Float4 OrbitRotation { get; set; } } diff --git a/NebulaModel/Packets/Universe/Editor/DysonSpherePaintCellsPacket.cs b/NebulaModel/Packets/Universe/Editor/DysonSpherePaintCellsPacket.cs index 1c1df2f7a..2f146bed9 100644 --- a/NebulaModel/Packets/Universe/Editor/DysonSpherePaintCellsPacket.cs +++ b/NebulaModel/Packets/Universe/Editor/DysonSpherePaintCellsPacket.cs @@ -1,28 +1,33 @@ -using NebulaAPI; +#region + +using NebulaAPI; using UnityEngine; -namespace NebulaModel.Packets.Universe +#endregion + +namespace NebulaModel.Packets.Universe; + +public class DysonSpherePaintCellsPacket { - public class DysonSpherePaintCellsPacket - { - public int StarIndex { get; set; } - public int LayerId { get; set; } - public Float4 Paint { get; set; } - public float Strength { get; set; } - public bool SuperBrightMode { get; set; } - public int[] CursorCells { get; set; } - public int CellCount { get; set; } + public DysonSpherePaintCellsPacket() { } - public DysonSpherePaintCellsPacket() { } - public DysonSpherePaintCellsPacket(int starIndex, int layerId, Color32 paint, float strength, bool superBrightMode, int[] cursorCells, int cellCount) - { - StarIndex = starIndex; - LayerId = layerId; - Paint = Float4.ToFloat4(paint); - Strength = strength; - SuperBrightMode = superBrightMode; - CursorCells = cursorCells; - CellCount = cellCount; - } + public DysonSpherePaintCellsPacket(int starIndex, int layerId, Color32 paint, float strength, bool superBrightMode, + int[] cursorCells, int cellCount) + { + StarIndex = starIndex; + LayerId = layerId; + Paint = Float4.ToFloat4(paint); + Strength = strength; + SuperBrightMode = superBrightMode; + CursorCells = cursorCells; + CellCount = cellCount; } + + public int StarIndex { get; set; } + public int LayerId { get; set; } + public Float4 Paint { get; set; } + public float Strength { get; set; } + public bool SuperBrightMode { get; set; } + public int[] CursorCells { get; set; } + public int CellCount { get; set; } } diff --git a/NebulaModel/Packets/Universe/Editor/DysonSphereRemoveFramePacket.cs b/NebulaModel/Packets/Universe/Editor/DysonSphereRemoveFramePacket.cs index b29a50e3f..e85c02fc9 100644 --- a/NebulaModel/Packets/Universe/Editor/DysonSphereRemoveFramePacket.cs +++ b/NebulaModel/Packets/Universe/Editor/DysonSphereRemoveFramePacket.cs @@ -1,17 +1,17 @@ -namespace NebulaModel.Packets.Universe +namespace NebulaModel.Packets.Universe; + +public class DysonSphereRemoveFramePacket { - public class DysonSphereRemoveFramePacket - { - public int StarIndex { get; set; } - public int LayerId { get; set; } - public int FrameId { get; set; } + public DysonSphereRemoveFramePacket() { } - public DysonSphereRemoveFramePacket() { } - public DysonSphereRemoveFramePacket(int starIndex, int layerId, int frameId) - { - StarIndex = starIndex; - LayerId = layerId; - FrameId = frameId; - } + public DysonSphereRemoveFramePacket(int starIndex, int layerId, int frameId) + { + StarIndex = starIndex; + LayerId = layerId; + FrameId = frameId; } + + public int StarIndex { get; set; } + public int LayerId { get; set; } + public int FrameId { get; set; } } diff --git a/NebulaModel/Packets/Universe/Editor/DysonSphereRemoveLayerPacket.cs b/NebulaModel/Packets/Universe/Editor/DysonSphereRemoveLayerPacket.cs index e0dfb940b..54b2722ab 100644 --- a/NebulaModel/Packets/Universe/Editor/DysonSphereRemoveLayerPacket.cs +++ b/NebulaModel/Packets/Universe/Editor/DysonSphereRemoveLayerPacket.cs @@ -1,15 +1,15 @@ -namespace NebulaModel.Packets.Universe +namespace NebulaModel.Packets.Universe; + +public class DysonSphereRemoveLayerPacket { - public class DysonSphereRemoveLayerPacket - { - public int StarIndex { get; set; } - public int LayerId { get; set; } + public DysonSphereRemoveLayerPacket() { } - public DysonSphereRemoveLayerPacket() { } - public DysonSphereRemoveLayerPacket(int starIndex, int layerId) - { - StarIndex = starIndex; - LayerId = layerId; - } + public DysonSphereRemoveLayerPacket(int starIndex, int layerId) + { + StarIndex = starIndex; + LayerId = layerId; } + + public int StarIndex { get; set; } + public int LayerId { get; set; } } diff --git a/NebulaModel/Packets/Universe/Editor/DysonSphereRemoveNodePacket.cs b/NebulaModel/Packets/Universe/Editor/DysonSphereRemoveNodePacket.cs index 1c6593203..00217a7a0 100644 --- a/NebulaModel/Packets/Universe/Editor/DysonSphereRemoveNodePacket.cs +++ b/NebulaModel/Packets/Universe/Editor/DysonSphereRemoveNodePacket.cs @@ -1,17 +1,17 @@ -namespace NebulaModel.Packets.Universe +namespace NebulaModel.Packets.Universe; + +public class DysonSphereRemoveNodePacket { - public class DysonSphereRemoveNodePacket - { - public int StarIndex { get; set; } - public int LayerId { get; set; } - public int NodeId { get; set; } + public DysonSphereRemoveNodePacket() { } - public DysonSphereRemoveNodePacket() { } - public DysonSphereRemoveNodePacket(int starIndex, int layerId, int nodeId) - { - StarIndex = starIndex; - LayerId = layerId; - NodeId = nodeId; - } + public DysonSphereRemoveNodePacket(int starIndex, int layerId, int nodeId) + { + StarIndex = starIndex; + LayerId = layerId; + NodeId = nodeId; } + + public int StarIndex { get; set; } + public int LayerId { get; set; } + public int NodeId { get; set; } } diff --git a/NebulaModel/Packets/Universe/Editor/DysonSphereRemoveShellPacket.cs b/NebulaModel/Packets/Universe/Editor/DysonSphereRemoveShellPacket.cs index 976b6ab3d..e12758c1d 100644 --- a/NebulaModel/Packets/Universe/Editor/DysonSphereRemoveShellPacket.cs +++ b/NebulaModel/Packets/Universe/Editor/DysonSphereRemoveShellPacket.cs @@ -1,17 +1,17 @@ -namespace NebulaModel.Packets.Universe +namespace NebulaModel.Packets.Universe; + +public class DysonSphereRemoveShellPacket { - public class DysonSphereRemoveShellPacket - { - public int StarIndex { get; set; } - public int LayerId { get; set; } - public int ShellId { get; set; } + public DysonSphereRemoveShellPacket() { } - public DysonSphereRemoveShellPacket() { } - public DysonSphereRemoveShellPacket(int starIndex, int layerId, int shellId) - { - StarIndex = starIndex; - LayerId = layerId; - ShellId = shellId; - } + public DysonSphereRemoveShellPacket(int starIndex, int layerId, int shellId) + { + StarIndex = starIndex; + LayerId = layerId; + ShellId = shellId; } + + public int StarIndex { get; set; } + public int LayerId { get; set; } + public int ShellId { get; set; } } diff --git a/NebulaModel/Packets/Universe/Editor/DysonSwarmAddOrbitPacket.cs b/NebulaModel/Packets/Universe/Editor/DysonSwarmAddOrbitPacket.cs index 5389c955f..2124f074c 100644 --- a/NebulaModel/Packets/Universe/Editor/DysonSwarmAddOrbitPacket.cs +++ b/NebulaModel/Packets/Universe/Editor/DysonSwarmAddOrbitPacket.cs @@ -1,22 +1,26 @@ -using NebulaAPI; +#region + +using NebulaAPI; using UnityEngine; -namespace NebulaModel.Packets.Universe +#endregion + +namespace NebulaModel.Packets.Universe; + +public class DysonSwarmAddOrbitPacket { - public class DysonSwarmAddOrbitPacket - { - public int StarIndex { get; set; } - public int OrbitId { get; set; } - public float Radius { get; set; } - public Float4 Rotation { get; set; } + public DysonSwarmAddOrbitPacket() { } - public DysonSwarmAddOrbitPacket() { } - public DysonSwarmAddOrbitPacket(int starIndex, int orbitId, float radius, Quaternion rotation) - { - StarIndex = starIndex; - OrbitId = orbitId; - Radius = radius; - Rotation = new Float4(rotation); - } + public DysonSwarmAddOrbitPacket(int starIndex, int orbitId, float radius, Quaternion rotation) + { + StarIndex = starIndex; + OrbitId = orbitId; + Radius = radius; + Rotation = new Float4(rotation); } + + public int StarIndex { get; set; } + public int OrbitId { get; set; } + public float Radius { get; set; } + public Float4 Rotation { get; set; } } diff --git a/NebulaModel/Packets/Universe/Editor/DysonSwarmEditOrbit.cs b/NebulaModel/Packets/Universe/Editor/DysonSwarmEditOrbit.cs index db0860525..a9ff14129 100644 --- a/NebulaModel/Packets/Universe/Editor/DysonSwarmEditOrbit.cs +++ b/NebulaModel/Packets/Universe/Editor/DysonSwarmEditOrbit.cs @@ -1,30 +1,35 @@ -using NebulaAPI; +#region + +using NebulaAPI; using UnityEngine; -namespace NebulaModel.Packets.Universe +#endregion + +namespace NebulaModel.Packets.Universe; + +public class DysonSwarmEditOrbitPacket { - public class DysonSwarmEditOrbitPacket + public DysonSwarmEditOrbitPacket() { } + + public DysonSwarmEditOrbitPacket(int starIndex, int orbitId, float radius, Quaternion rotation) { - public int StarIndex { get; set; } - public int OrbitId { get; set; } - public float Radius { get; set; } - public Float4 Rotation { get; set; } - public Float4 Color { get; set; } + StarIndex = starIndex; + OrbitId = orbitId; + Radius = radius; + Rotation = new Float4(rotation); + } - public DysonSwarmEditOrbitPacket() { } - public DysonSwarmEditOrbitPacket(int starIndex, int orbitId, float radius, Quaternion rotation) - { - StarIndex = starIndex; - OrbitId = orbitId; - Radius = radius; - Rotation = new Float4(rotation); - } - public DysonSwarmEditOrbitPacket(int starIndex, int orbitId, Vector4 color) - { - StarIndex = starIndex; - OrbitId = orbitId; - Color = new Float4(color.x, color.y, color.z, color.w); - Radius = -1; - } + public DysonSwarmEditOrbitPacket(int starIndex, int orbitId, Vector4 color) + { + StarIndex = starIndex; + OrbitId = orbitId; + Color = new Float4(color.x, color.y, color.z, color.w); + Radius = -1; } + + public int StarIndex { get; set; } + public int OrbitId { get; set; } + public float Radius { get; set; } + public Float4 Rotation { get; set; } + public Float4 Color { get; set; } } diff --git a/NebulaModel/Packets/Universe/Editor/DysonSwarmRemoveOrbitPacket.cs b/NebulaModel/Packets/Universe/Editor/DysonSwarmRemoveOrbitPacket.cs index 938f15f01..f8411a922 100644 --- a/NebulaModel/Packets/Universe/Editor/DysonSwarmRemoveOrbitPacket.cs +++ b/NebulaModel/Packets/Universe/Editor/DysonSwarmRemoveOrbitPacket.cs @@ -1,25 +1,25 @@ -namespace NebulaModel.Packets.Universe -{ - public class DysonSwarmRemoveOrbitPacket - { - public int StarIndex { get; set; } - public int OrbitId { get; set; } - public SwarmRemoveOrbitEvent Event { get; set; } +namespace NebulaModel.Packets.Universe; - public DysonSwarmRemoveOrbitPacket() { } - public DysonSwarmRemoveOrbitPacket(int starIndex, int orbitId, SwarmRemoveOrbitEvent removeEvent) - { - StarIndex = starIndex; - OrbitId = orbitId; - Event = removeEvent; - } - } +public class DysonSwarmRemoveOrbitPacket +{ + public DysonSwarmRemoveOrbitPacket() { } - public enum SwarmRemoveOrbitEvent + public DysonSwarmRemoveOrbitPacket(int starIndex, int orbitId, SwarmRemoveOrbitEvent removeEvent) { - Remove, - Disable, - Enable, - RemoveSails + StarIndex = starIndex; + OrbitId = orbitId; + Event = removeEvent; } + + public int StarIndex { get; set; } + public int OrbitId { get; set; } + public SwarmRemoveOrbitEvent Event { get; set; } +} + +public enum SwarmRemoveOrbitEvent +{ + Remove, + Disable, + Enable, + RemoveSails } diff --git a/NebulaModel/Packets/Universe/NameInputPacket.cs b/NebulaModel/Packets/Universe/NameInputPacket.cs index 0401337d2..de6300b55 100644 --- a/NebulaModel/Packets/Universe/NameInputPacket.cs +++ b/NebulaModel/Packets/Universe/NameInputPacket.cs @@ -1,54 +1,58 @@ -using NebulaAPI; +#region + using System.Collections.Generic; +using NebulaAPI; + +#endregion -namespace NebulaModel.Packets.Universe +namespace NebulaModel.Packets.Universe; + +// Packet for name input for Planets and Stars +public class NameInputPacket { - // Packet for name input for Planets and Stars - public class NameInputPacket + public NameInputPacket() { } + + public NameInputPacket(string name, int starId, int planetId, int authorId) { - public string[] Names { get; set; } - public int[] PlanetIds { get; set; } - public int[] StarIds { get; set; } - public int AuthorId { get; set; } + Names = new string[1] { name }; + StarIds = new int[1] { starId }; + PlanetIds = new int[1] { planetId }; + AuthorId = authorId; + } - public NameInputPacket() { } - public NameInputPacket(string name, int starId, int planetId, int authorId) - { - Names = new string[1] { name }; - StarIds = new int[1] { starId }; - PlanetIds = new int[1] { planetId }; - AuthorId = authorId; - } + public NameInputPacket(in GalaxyData galaxy, int authorId) + { + var names = new List(); + var starIds = new List(); + var planetIds = new List(); - public NameInputPacket(in GalaxyData galaxy, int authorId) + foreach (var s in galaxy.stars) { - List names = new List(); - List starIds = new List(); - List planetIds = new List(); - - foreach (StarData s in galaxy.stars) + if (!string.IsNullOrEmpty(s.overrideName)) { - if (!string.IsNullOrEmpty(s.overrideName)) - { - names.Add(s.overrideName); - starIds.Add(s.id); - planetIds.Add(NebulaModAPI.PLANET_NONE); - } - foreach (PlanetData p in s.planets) + names.Add(s.overrideName); + starIds.Add(s.id); + planetIds.Add(NebulaModAPI.PLANET_NONE); + } + foreach (var p in s.planets) + { + if (!string.IsNullOrEmpty(p.overrideName)) { - if (!string.IsNullOrEmpty(p.overrideName)) - { - names.Add(p.overrideName); - starIds.Add(NebulaModAPI.STAR_NONE); - planetIds.Add(p.id); - } + names.Add(p.overrideName); + starIds.Add(NebulaModAPI.STAR_NONE); + planetIds.Add(p.id); } } - - Names = names.ToArray(); - StarIds = starIds.ToArray(); - PlanetIds = planetIds.ToArray(); - AuthorId = authorId; } + + Names = names.ToArray(); + StarIds = starIds.ToArray(); + PlanetIds = planetIds.ToArray(); + AuthorId = authorId; } + + public string[] Names { get; set; } + public int[] PlanetIds { get; set; } + public int[] StarIds { get; set; } + public int AuthorId { get; set; } } diff --git a/NebulaModel/Packets/Warning/WarningDataPacket.cs b/NebulaModel/Packets/Warning/WarningDataPacket.cs index 4ba74654b..b5ee9e08d 100644 --- a/NebulaModel/Packets/Warning/WarningDataPacket.cs +++ b/NebulaModel/Packets/Warning/WarningDataPacket.cs @@ -1,11 +1,8 @@ -namespace NebulaModel.Packets.Warning -{ - public class WarningDataPacket - { - public int ActiveWarningCount { get; set; } - public int Tick { get; set; } - public byte[] BinaryData { get; set; } +namespace NebulaModel.Packets.Warning; - public WarningDataPacket() { } - } +public class WarningDataPacket +{ + public int ActiveWarningCount { get; set; } + public int Tick { get; set; } + public byte[] BinaryData { get; set; } } diff --git a/NebulaModel/Packets/Warning/WarningDataRequest.cs b/NebulaModel/Packets/Warning/WarningDataRequest.cs index 51977bc3b..88eb1b2a2 100644 --- a/NebulaModel/Packets/Warning/WarningDataRequest.cs +++ b/NebulaModel/Packets/Warning/WarningDataRequest.cs @@ -1,19 +1,19 @@ -namespace NebulaModel.Packets.Warning -{ - public class WarningDataRequest - { - public WarningRequestEvent Event { get; set; } +namespace NebulaModel.Packets.Warning; - public WarningDataRequest() { } - public WarningDataRequest(WarningRequestEvent requestEvent) - { - Event = requestEvent; - } - } +public class WarningDataRequest +{ + public WarningDataRequest() { } - public enum WarningRequestEvent + public WarningDataRequest(WarningRequestEvent requestEvent) { - Signal = 0, - Data = 1 + Event = requestEvent; } + + public WarningRequestEvent Event { get; set; } +} + +public enum WarningRequestEvent +{ + Signal = 0, + Data = 1 } diff --git a/NebulaModel/Packets/Warning/WarningSignalPacket.cs b/NebulaModel/Packets/Warning/WarningSignalPacket.cs index 8275514a6..58a945fcd 100644 --- a/NebulaModel/Packets/Warning/WarningSignalPacket.cs +++ b/NebulaModel/Packets/Warning/WarningSignalPacket.cs @@ -1,18 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace NebulaModel.Packets.Warning; -namespace NebulaModel.Packets.Warning +public class WarningSignalPacket { - public class WarningSignalPacket - { - public int SignalCount { get; set; } - public int[] Signals { get; set; } - public int[] Counts { get; set; } - public int Tick { get; set; } - - public WarningSignalPacket() { } - } + public int SignalCount { get; set; } + public int[] Signals { get; set; } + public int[] Counts { get; set; } + public int Tick { get; set; } } diff --git a/NebulaModel/Player.cs b/NebulaModel/Player.cs index 4611827ae..0d2e0ded1 100644 --- a/NebulaModel/Player.cs +++ b/NebulaModel/Player.cs @@ -1,30 +1,34 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.DataStructures; using NebulaModel.Networking; -namespace NebulaModel +#endregion + +namespace NebulaModel; + +public class NebulaPlayer : INebulaPlayer { - public class NebulaPlayer : INebulaPlayer + public NebulaPlayer(NebulaConnection connection, PlayerData data) { - public INebulaConnection Connection { get; private set; } - public IPlayerData Data { get; private set; } - public ushort Id => Data.PlayerId; - public NebulaPlayer(NebulaConnection connection, PlayerData data) - { - Connection = connection; - Data = data; - } + Connection = connection; + Data = data; + } - public void SendPacket(T packet) where T : class, new() - { - Connection.SendPacket(packet); - } + public INebulaConnection Connection { get; } + public IPlayerData Data { get; private set; } + public ushort Id => Data.PlayerId; - public void LoadUserData(IPlayerData data) - { - ushort localId = Id; - Data = data; - Data.PlayerId = localId; - } + public void SendPacket(T packet) where T : class, new() + { + Connection.SendPacket(packet); + } + + public void LoadUserData(IPlayerData data) + { + var localId = Id; + Data = data; + Data.PlayerId = localId; } } diff --git a/NebulaModel/Utils/AssembliesUtils.cs b/NebulaModel/Utils/AssembliesUtils.cs index a1d7c8942..aae93feba 100644 --- a/NebulaModel/Utils/AssembliesUtils.cs +++ b/NebulaModel/Utils/AssembliesUtils.cs @@ -1,25 +1,28 @@ -using System; +#region + +using System; using System.Collections.Generic; using System.Linq; using System.Reflection; -namespace NebulaModel.Utils +#endregion + +namespace NebulaModel.Utils; + +public static class AssembliesUtils { - public static class AssembliesUtils + public static IEnumerable GetTypesWithAttributeInAssembly(Assembly assembly) where T : Attribute { - public static IEnumerable GetTypesWithAttributeInAssembly(Assembly assembly) where T : Attribute - { - return assembly.GetTypes().Where(t => t.GetCustomAttributes(typeof(T), true).Length > 0); - } + return assembly.GetTypes().Where(t => t.GetCustomAttributes(typeof(T), true).Length > 0); + } - public static IEnumerable GetNebulaAssemblies() - { - return AppDomain.CurrentDomain.GetAssemblies().Where(a => a.FullName.StartsWith("Nebula")); - } + public static IEnumerable GetNebulaAssemblies() + { + return AppDomain.CurrentDomain.GetAssemblies().Where(a => a.FullName.StartsWith("Nebula")); + } - public static Assembly GetAssemblyByName(string name) - { - return AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.FullName.StartsWith($"{name}.")); - } + public static Assembly GetAssemblyByName(string name) + { + return AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.FullName.StartsWith($"{name}.")); } } diff --git a/NebulaModel/Utils/ChatUtils.cs b/NebulaModel/Utils/ChatUtils.cs index 604734c15..67d9ffd7e 100644 --- a/NebulaModel/Utils/ChatUtils.cs +++ b/NebulaModel/Utils/ChatUtils.cs @@ -1,153 +1,155 @@ -using NebulaModel.DataStructures; -using NebulaModel.Packets.Players; +#region + using System; using System.Linq; using System.Text.RegularExpressions; +using NebulaModel.DataStructures; using TMPro; using UnityEngine; -namespace NebulaModel.Utils -{ - public static class ChatUtils - { - internal static readonly string[] AllowedTags = {"b", "i", "s", "u", "indent", "link", "mark", "sprite", "sub", "sup", "color"}; +#endregion - internal static readonly Vector2[] ChatMargins = { - new Vector2(10, 350), - new Vector2(10, 350), - new Vector2(10, 10), - new Vector2(10, 100) - }; +namespace NebulaModel.Utils; +public static class ChatUtils +{ + internal const float ReferenceX = 1920; + internal const float ReferenceY = 1080; - internal static readonly Vector2[] ChatSizes = { - new Vector2(500, 300), - new Vector2(700, 420), - new Vector2(800, 480) - }; + internal static readonly string[] AllowedTags = + { + "b", "i", "s", "u", "indent", "link", "mark", "sprite", "sub", "sup", "color" + }; - internal const float ReferenceX = 1920; - internal const float ReferenceY = 1080; + internal static readonly Vector2[] ChatMargins = { new(10, 350), new(10, 350), new(10, 10), new(10, 100) }; - public static Vector2 GetDefaultPosition(ChatPosition position, ChatSize size) - { - Vector2 chatSize = GetDefaultSize(size); - Vector2 margin = ChatMargins[(int)position]; - bool snapRight = ((int)position & 1) == 1; - bool snapTop = ((int)position & 2) == 2; - - float needXPos; - float needYPos; - - if (snapRight) - { - needXPos = ReferenceX - margin.x - chatSize.x; - } - else - { - needXPos = margin.x; - } - if (snapTop) - { - needYPos = -margin.y; - } - else - { - needYPos = -ReferenceY + margin.y + chatSize.y; - } + internal static readonly Vector2[] ChatSizes = { new(500, 300), new(700, 420), new(800, 480) }; - needXPos *= Screen.width / ReferenceX; - needYPos *= Screen.height / ReferenceY; + public static Vector2 GetDefaultPosition(ChatPosition position, ChatSize size) + { + var chatSize = GetDefaultSize(size); + var margin = ChatMargins[(int)position]; + var snapRight = ((int)position & 1) == 1; + var snapTop = ((int)position & 2) == 2; - return new Vector2(needXPos, needYPos); - } - - public static Vector2 GetDefaultSize(ChatSize size) + float needXPos; + float needYPos; + + if (snapRight) { - Vector2 chatSize = ChatSizes[(int)size]; - chatSize.x *= Screen.width / ReferenceX; - chatSize.y *= Screen.height / ReferenceY; - return chatSize; + needXPos = ReferenceX - margin.x - chatSize.x; } - - - public static string SanitizeText(string input) + else { - // Matches any valid rich text tag. For example: - Regex regex = new Regex(@"<([/\w]+)=?[""#]?\w*""?\s?[\s\w""=]*>"); + needXPos = margin.x; + } - return regex.Replace(input, match => - { - string tagName = match.Groups[1].Value; - if (AllowedTags.Contains(tagName) || AllowedTags.Contains(tagName.Substring(1))) - { - return match.Value; - } - return ""; - }); + if (snapTop) + { + needYPos = -margin.y; + } + else + { + needYPos = -ReferenceY + margin.y + chatSize.y; } - public static Color GetMessageColor(ChatMessageType messageType) + needXPos *= Screen.width / ReferenceX; + needYPos *= Screen.height / ReferenceY; + + return new Vector2(needXPos, needYPos); + } + + public static Vector2 GetDefaultSize(ChatSize size) + { + var chatSize = ChatSizes[(int)size]; + chatSize.x *= Screen.width / ReferenceX; + chatSize.y *= Screen.height / ReferenceY; + return chatSize; + } + + + public static string SanitizeText(string input) + { + // Matches any valid rich text tag. For example: + var regex = new Regex(@"<([/\w]+)=?[""#]?\w*""?\s?[\s\w""=]*>"); + + return regex.Replace(input, match => { - switch (messageType) + var tagName = match.Groups[1].Value; + if (AllowedTags.Contains(tagName) || AllowedTags.Contains(tagName.Substring(1))) { - case ChatMessageType.PlayerMessage: - return Color.white; - - case ChatMessageType.SystemInfoMessage: - return Color.cyan; - - case ChatMessageType.SystemWarnMessage: - return new Color(1,0.95f,0,1); - - case ChatMessageType.CommandUsageMessage: - return new Color(1,0.65f,0,1); - - case ChatMessageType.CommandOutputMessage: - return new Color(0.8f,0.8f,0.8f,1); - - case ChatMessageType.CommandErrorMessage: - return Color.red; - - case ChatMessageType.PlayerMessagePrivate: - return Color.green; - - default: - Console.WriteLine($"Requested color for unexpected chat message type {messageType}"); - return Color.white; + return match.Value; } - } + return ""; + }); + } - public static bool IsCommandMessage(this ChatMessageType type) - { - return type == ChatMessageType.CommandOutputMessage || - type == ChatMessageType.CommandUsageMessage || - type == ChatMessageType.CommandErrorMessage || - type == ChatMessageType.SystemWarnMessage || - type == ChatMessageType.SystemInfoMessage; - } - - public static bool Contains(this string source, string toCheck, StringComparison comp) + public static Color GetMessageColor(ChatMessageType messageType) + { + switch (messageType) { - return source?.IndexOf(toCheck, comp) >= 0; + case ChatMessageType.PlayerMessage: + return Color.white; + + case ChatMessageType.SystemInfoMessage: + return Color.cyan; + + case ChatMessageType.SystemWarnMessage: + return new Color(1, 0.95f, 0, 1); + + case ChatMessageType.CommandUsageMessage: + return new Color(1, 0.65f, 0, 1); + + case ChatMessageType.CommandOutputMessage: + return new Color(0.8f, 0.8f, 0.8f, 1); + + case ChatMessageType.CommandErrorMessage: + return Color.red; + + case ChatMessageType.PlayerMessagePrivate: + return Color.green; + + default: + Console.WriteLine($"Requested color for unexpected chat message type {messageType}"); + return Color.white; } + } - public static void Insert(this TMP_InputField field, string str) + public static bool IsCommandMessage(this ChatMessageType type) + { + return type == ChatMessageType.CommandOutputMessage || + type == ChatMessageType.CommandUsageMessage || + type == ChatMessageType.CommandErrorMessage || + type == ChatMessageType.SystemWarnMessage || + type == ChatMessageType.SystemInfoMessage; + } + + public static bool Contains(this string source, string toCheck, StringComparison comp) + { + return source?.IndexOf(toCheck, comp) >= 0; + } + + public static void Insert(this TMP_InputField field, string str) + { + if (field.m_ReadOnly) { - if (field.m_ReadOnly) return; + return; + } - field.Delete(); + field.Delete(); - // Can't go past the character limit - if (field.characterLimit > 0 && field.text.Length >= field.characterLimit) return; + // Can't go past the character limit + if (field.characterLimit > 0 && field.text.Length >= field.characterLimit) + { + return; + } - field.text = field.text.Insert(field.m_StringPosition, str); + field.text = field.text.Insert(field.m_StringPosition, str); - field.stringSelectPositionInternal = field.stringPositionInternal += str.Length; + field.stringSelectPositionInternal = field.stringPositionInternal += str.Length; - field.UpdateTouchKeyboardFromEditChanges(); - field.SendOnValueChanged(); - } + field.UpdateTouchKeyboardFromEditChanges(); + field.SendOnValueChanged(); } -} \ No newline at end of file +} diff --git a/NebulaModel/Utils/ChildProcessLinker.cs b/NebulaModel/Utils/ChildProcessLinker.cs index e021c6745..ed256d665 100644 --- a/NebulaModel/Utils/ChildProcessLinker.cs +++ b/NebulaModel/Utils/ChildProcessLinker.cs @@ -1,115 +1,130 @@ -using System; +#region + +using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; -namespace NebulaModel.Utils -{ +#endregion - // Adapted from https://stackoverflow.com/a/24012744/13620003 - public class ChildProcessLinker - { - // see http://csharptest.net/1051/managed-anti-debugging-how-to-prevent-users-from-attaching-a-debugger/ - // see https://stackoverflow.com/a/24012744/2982757 +namespace NebulaModel.Utils; - public Process ChildProcess { get; set; } +// Adapted from https://stackoverflow.com/a/24012744/13620003 +public class ChildProcessLinker +{ + private readonly Action _safeNullDebuggerExceptionHandler; - private Action _safeNullDebuggerExceptionHandler; + public ChildProcessLinker(Process childProcess, Action exceptionHandler = null) + { + ChildProcess = childProcess; + _safeNullDebuggerExceptionHandler = exceptionHandler; - public ChildProcessLinker(Process childProcess, Action exceptionHandler = null) - { - ChildProcess = childProcess; - _safeNullDebuggerExceptionHandler = exceptionHandler; + new Thread(_safeNullDebuggerExceptionHandler != null ? SafeNullDebugger : NullDebugger) { IsBackground = true }.Start( + ChildProcess.Id); + } + // see http://csharptest.net/1051/managed-anti-debugging-how-to-prevent-users-from-attaching-a-debugger/ + // see https://stackoverflow.com/a/24012744/2982757 - new Thread(_safeNullDebuggerExceptionHandler != null ? SafeNullDebugger : NullDebugger) { IsBackground = true }.Start(ChildProcess.Id); - } + public Process ChildProcess { get; set; } - private void NullDebugger(object arg) + private void NullDebugger(object arg) + { + // Attach to the process we provided the thread as an argument + if (DebugActiveProcess((int)arg)) { - // Attach to the process we provided the thread as an argument - if (DebugActiveProcess((int)arg)) + var debugEvent = new DEBUG_EVENT { bytes = new byte[1024] }; + while (!ChildProcess.HasExited) { - var debugEvent = new DEBUG_EVENT { bytes = new byte[1024] }; - while (!this.ChildProcess.HasExited) + if (WaitForDebugEvent(out debugEvent, 1000)) { - if (WaitForDebugEvent(out debugEvent, 1000)) + // return DBG_CONTINUE for all events but the exception type + var continueFlag = DBG_CONTINUE; + if (debugEvent.dwDebugEventCode == DebugEventType.EXCEPTION_DEBUG_EVENT) { - // return DBG_CONTINUE for all events but the exception type - var continueFlag = DBG_CONTINUE; - if (debugEvent.dwDebugEventCode == DebugEventType.EXCEPTION_DEBUG_EVENT) - continueFlag = DBG_EXCEPTION_NOT_HANDLED; - ContinueDebugEvent(debugEvent.dwProcessId, debugEvent.dwThreadId, continueFlag); + continueFlag = DBG_EXCEPTION_NOT_HANDLED; } + ContinueDebugEvent(debugEvent.dwProcessId, debugEvent.dwThreadId, continueFlag); } } - else - { - //we were not able to attach the debugger - //do the processes have the same bitness? - //throw ApplicationException("Unable to attach debugger") // Kill child? // Send Event? // Ignore? - throw new Exception("ChildProcessLinker was unable to attach NullDebugger!"); - } } - - private void SafeNullDebugger(object arg) + else { - try - { - NullDebugger(arg); - } catch (Exception ex) - { - _safeNullDebuggerExceptionHandler(ex); - } + //we were not able to attach the debugger + //do the processes have the same bitness? + //throw ApplicationException("Unable to attach debugger") // Kill child? // Send Event? // Ignore? + throw new Exception("ChildProcessLinker was unable to attach NullDebugger!"); } + } - #region "API imports" - - private const int DBG_CONTINUE = 0x00010002; - private const int DBG_EXCEPTION_NOT_HANDLED = unchecked((int)0x80010001); - - private enum DebugEventType : int + private void SafeNullDebugger(object arg) + { + try { - CREATE_PROCESS_DEBUG_EVENT = 3, - //Reports a create-process debugging event. The value of u.CreateProcessInfo specifies a CREATE_PROCESS_DEBUG_INFO structure. - CREATE_THREAD_DEBUG_EVENT = 2, - //Reports a create-thread debugging event. The value of u.CreateThread specifies a CREATE_THREAD_DEBUG_INFO structure. - EXCEPTION_DEBUG_EVENT = 1, - //Reports an exception debugging event. The value of u.Exception specifies an EXCEPTION_DEBUG_INFO structure. - EXIT_PROCESS_DEBUG_EVENT = 5, - //Reports an exit-process debugging event. The value of u.ExitProcess specifies an EXIT_PROCESS_DEBUG_INFO structure. - EXIT_THREAD_DEBUG_EVENT = 4, - //Reports an exit-thread debugging event. The value of u.ExitThread specifies an EXIT_THREAD_DEBUG_INFO structure. - LOAD_DLL_DEBUG_EVENT = 6, - //Reports a load-dynamic-link-library (DLL) debugging event. The value of u.LoadDll specifies a LOAD_DLL_DEBUG_INFO structure. - OUTPUT_DEBUG_STRING_EVENT = 8, - //Reports an output-debugging-string debugging event. The value of u.DebugString specifies an OUTPUT_DEBUG_STRING_INFO structure. - RIP_EVENT = 9, - //Reports a RIP-debugging event (system debugging error). The value of u.RipInfo specifies a RIP_INFO structure. - UNLOAD_DLL_DEBUG_EVENT = 7, - //Reports an unload-DLL debugging event. The value of u.UnloadDll specifies an UNLOAD_DLL_DEBUG_INFO structure. + NullDebugger(arg); } - - [StructLayout(LayoutKind.Sequential)] - private struct DEBUG_EVENT + catch (Exception ex) { - [MarshalAs(UnmanagedType.I4)] public DebugEventType dwDebugEventCode; - public int dwProcessId; - public int dwThreadId; - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1024)] public byte[] bytes; + _safeNullDebuggerExceptionHandler(ex); } + } + + #region "API imports" + + private const int DBG_CONTINUE = 0x00010002; + private const int DBG_EXCEPTION_NOT_HANDLED = unchecked((int)0x80010001); + + private enum DebugEventType + { + CREATE_PROCESS_DEBUG_EVENT = 3, + + //Reports a create-process debugging event. The value of u.CreateProcessInfo specifies a CREATE_PROCESS_DEBUG_INFO structure. + CREATE_THREAD_DEBUG_EVENT = 2, + + //Reports a create-thread debugging event. The value of u.CreateThread specifies a CREATE_THREAD_DEBUG_INFO structure. + EXCEPTION_DEBUG_EVENT = 1, + + //Reports an exception debugging event. The value of u.Exception specifies an EXCEPTION_DEBUG_INFO structure. + EXIT_PROCESS_DEBUG_EVENT = 5, - [DllImport("Kernel32.dll", SetLastError = true)] - private static extern bool DebugActiveProcess(int dwProcessId); + //Reports an exit-process debugging event. The value of u.ExitProcess specifies an EXIT_PROCESS_DEBUG_INFO structure. + EXIT_THREAD_DEBUG_EVENT = 4, - [DllImport("Kernel32.dll", SetLastError = true)] - private static extern bool WaitForDebugEvent([Out] out DEBUG_EVENT lpDebugEvent, int dwMilliseconds); + //Reports an exit-thread debugging event. The value of u.ExitThread specifies an EXIT_THREAD_DEBUG_INFO structure. + LOAD_DLL_DEBUG_EVENT = 6, - [DllImport("Kernel32.dll", SetLastError = true)] - private static extern bool ContinueDebugEvent(int dwProcessId, int dwThreadId, int dwContinueStatus); + //Reports a load-dynamic-link-library (DLL) debugging event. The value of u.LoadDll specifies a LOAD_DLL_DEBUG_INFO structure. + OUTPUT_DEBUG_STRING_EVENT = 8, - [DllImport("Kernel32.dll", SetLastError = true)] - public static extern bool IsDebuggerPresent(); + //Reports an output-debugging-string debugging event. The value of u.DebugString specifies an OUTPUT_DEBUG_STRING_INFO structure. + RIP_EVENT = 9, - #endregion + //Reports a RIP-debugging event (system debugging error). The value of u.RipInfo specifies a RIP_INFO structure. + UNLOAD_DLL_DEBUG_EVENT = 7 + //Reports an unload-DLL debugging event. The value of u.UnloadDll specifies an UNLOAD_DLL_DEBUG_INFO structure. } + + [StructLayout(LayoutKind.Sequential)] + private struct DEBUG_EVENT + { + [MarshalAs(UnmanagedType.I4)] public DebugEventType dwDebugEventCode; + public int dwProcessId; + public int dwThreadId; + + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1024)] + public byte[] bytes; + } + + [DllImport("Kernel32.dll", SetLastError = true)] + private static extern bool DebugActiveProcess(int dwProcessId); + + [DllImport("Kernel32.dll", SetLastError = true)] + private static extern bool WaitForDebugEvent([Out] out DEBUG_EVENT lpDebugEvent, int dwMilliseconds); + + [DllImport("Kernel32.dll", SetLastError = true)] + private static extern bool ContinueDebugEvent(int dwProcessId, int dwThreadId, int dwContinueStatus); + + [DllImport("Kernel32.dll", SetLastError = true)] + public static extern bool IsDebuggerPresent(); + + #endregion } diff --git a/NebulaModel/Utils/CryptoUtils.cs b/NebulaModel/Utils/CryptoUtils.cs index 33792f40f..7ce02f845 100644 --- a/NebulaModel/Utils/CryptoUtils.cs +++ b/NebulaModel/Utils/CryptoUtils.cs @@ -1,101 +1,105 @@ -using System; +#region + +using System; using System.IO; using System.Security.Cryptography; using System.Text; +using NebulaModel.Logger; + +#endregion + +namespace NebulaModel.Utils; -namespace NebulaModel.Utils +public static class CryptoUtils { - public static class CryptoUtils - { - // There are 2 places to store player.key: - // (1) Documents\Dyson Sphere Program\ - // (2) .\Dyson Sphere Program\ (if MyDocuments folder doesn't exist or is inaccessible) + // There are 2 places to store player.key: + // (1) Documents\Dyson Sphere Program\ + // (2) .\Dyson Sphere Program\ (if MyDocuments folder doesn't exist or is inaccessible) - private static readonly string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); - private static readonly string dataPath = Path.Combine(docPath, GameConfig.gameName); - private static readonly string keyFile = Path.Combine(docPath, dataPath, "player.key"); - private static readonly string dataPath2 = Path.Combine(GameConfig.gameName); - private static readonly string keyFile2 = Path.Combine(dataPath2, "player.key"); + private static readonly string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); + private static readonly string dataPath = Path.Combine(docPath, GameConfig.gameName); + private static readonly string keyFile = Path.Combine(docPath, dataPath, "player.key"); + private static readonly string dataPath2 = Path.Combine(GameConfig.gameName); + private static readonly string keyFile2 = Path.Combine(dataPath2, "player.key"); - public static RSA GetOrCreateUserCert() + public static RSA GetOrCreateUserCert() + { + if (string.IsNullOrEmpty(docPath)) { - if (string.IsNullOrEmpty(docPath)) + Log.Warn("Could not find documents folder! Using game directory."); + try { - Logger.Log.Warn("Could not find documents folder! Using game directory."); - try - { - Directory.CreateDirectory(dataPath); - } - catch - { - Logger.Log.Error($"Unable to create directory {dataPath}, permission denied."); - throw; - } + Directory.CreateDirectory(dataPath); } - - RSA rsa = RSA.Create(); - if (File.Exists(keyFile)) + catch { - rsa.FromXmlString(File.ReadAllText(keyFile)); + Log.Error($"Unable to create directory {dataPath}, permission denied."); + throw; } - else if (File.Exists(keyFile2)) + } + + var rsa = RSA.Create(); + if (File.Exists(keyFile)) + { + rsa.FromXmlString(File.ReadAllText(keyFile)); + } + else if (File.Exists(keyFile2)) + { + rsa.FromXmlString(File.ReadAllText(keyFile2)); + } + else + { + try { - rsa.FromXmlString(File.ReadAllText(keyFile2)); + Log.Info($"Store player key in {keyFile}"); + File.WriteAllText(keyFile, rsa.ToXmlString(true)); } - else + catch (Exception e) { - try + Log.Warn($"Unable to write to default path, reason: {e.GetType()}"); + if (!Directory.Exists(dataPath2)) { - Logger.Log.Info($"Store player key in {keyFile}"); - File.WriteAllText(keyFile, rsa.ToXmlString(true)); - } - catch (Exception e) - { - Logger.Log.Warn($"Unable to write to default path, reason: {e.GetType()}"); - if (!Directory.Exists(dataPath2)) - { - Logger.Log.Info($"Create directory {dataPath2}"); - Directory.CreateDirectory(dataPath2); - } - Logger.Log.Info($"Store player key in {keyFile2}"); - File.WriteAllText(keyFile2, rsa.ToXmlString(true)); + Log.Info($"Create directory {dataPath2}"); + Directory.CreateDirectory(dataPath2); } + Log.Info($"Store player key in {keyFile2}"); + File.WriteAllText(keyFile2, rsa.ToXmlString(true)); } - return rsa; } + return rsa; + } - public static byte[] GetPublicKey(RSA rsa) - { - return Convert.FromBase64String(rsa.ToXmlString(false).Substring(22, 172)); - } + public static byte[] GetPublicKey(RSA rsa) + { + return Convert.FromBase64String(rsa.ToXmlString(false).Substring(22, 172)); + } - public static string Hash(byte[] input) - { - byte[] hash = new SHA1Managed().ComputeHash(input); - return Convert.ToBase64String(hash); - } + public static string Hash(byte[] input) + { + var hash = new SHA1Managed().ComputeHash(input); + return Convert.ToBase64String(hash); + } - public static string Hash(string input) - { - byte[] hash = SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(input)); - return Convert.ToBase64String(hash); - } + public static string Hash(string input) + { + var hash = SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(input)); + return Convert.ToBase64String(hash); + } - public static string GetCurrentUserPublicKeyHash() - { - return Hash(GetPublicKey(GetOrCreateUserCert())); - } + public static string GetCurrentUserPublicKeyHash() + { + return Hash(GetPublicKey(GetOrCreateUserCert())); + } - public static string ToBase64(this string s) - { - var bytes = Encoding.UTF8.GetBytes(s); - return Convert.ToBase64String(bytes); - } + public static string ToBase64(this string s) + { + var bytes = Encoding.UTF8.GetBytes(s); + return Convert.ToBase64String(bytes); + } - public static string FromBase64(this string s) - { - var bytes = Convert.FromBase64String(s); - return Encoding.UTF8.GetString(bytes); - } + public static string FromBase64(this string s) + { + var bytes = Convert.FromBase64String(s); + return Encoding.UTF8.GetString(bytes); } } diff --git a/NebulaModel/Utils/IPUtils.cs b/NebulaModel/Utils/IPUtils.cs index 573774276..4ce1b5993 100644 --- a/NebulaModel/Utils/IPUtils.cs +++ b/NebulaModel/Utils/IPUtils.cs @@ -1,6 +1,7 @@ -using System; +#region + +using System; using System.Collections.Generic; -using System.Diagnostics; using System.IO; using System.Net; using System.Net.Http; @@ -8,215 +9,212 @@ using System.Text; using System.Threading.Tasks; using System.Timers; +using NebulaModel.Logger; + +#endregion + +namespace NebulaModel.Utils; -namespace NebulaModel.Utils +public static class IPUtils { - public static class IPUtils + public enum DataState { - static readonly HttpClient client = new(); + Unset, + Fresh, + Cached + } - public enum IPConfiguration - { - Both, - IPv4, - IPv6 - } + public enum IPConfiguration + { + Both, + IPv4, + IPv6 + } - public enum DataState - { - Unset, - Fresh, - Cached - } + public enum PortStatus + { + Open, + Closed + } - public enum Status - { - None, - Unsupported, - Unavailable - } + public enum Status + { + None, + Unsupported, + Unavailable + } - public enum PortStatus - { - Open, - Closed - } + private static readonly HttpClient client = new(); - public struct IpInfo - { - public string LANAddress; - public string WANv4Address; - public string WANv6Address; - public string PortStatus; - public DataState DataState; - } + private static IpInfo ipInfo; - static IpInfo ipInfo; + private static readonly Timer timer; + + static IPUtils() + { + timer = new Timer { Enabled = false, Interval = TimeSpan.FromMinutes(1).TotalMilliseconds }; + timer.Elapsed += (s, e) => { timer.Stop(); }; + client.Timeout = TimeSpan.FromSeconds(15); + } - static readonly Timer timer; + public static string GetLocalAddress() + { + using Socket socket = new(AddressFamily.InterNetwork, SocketType.Dgram, 0); + socket.Connect("8.8.8.8", 65530); + var endPoint = socket.LocalEndPoint as IPEndPoint; + return endPoint.Address.ToString(); + } - static IPUtils() + public static async Task GetWANv4Address() + { + try { - timer = new Timer() + var response = await client.GetStringAsync("https://api.ipify.org"); + + if (IsIPv4(response)) { - Enabled = false, - Interval = TimeSpan.FromMinutes(1).TotalMilliseconds, - }; - timer.Elapsed += (s, e) => { timer.Stop(); }; - client.Timeout = TimeSpan.FromSeconds(15); - } + return response; + } - public static string GetLocalAddress() + return Status.Unsupported.ToString(); + } + catch (Exception e) { - using Socket socket = new(AddressFamily.InterNetwork, SocketType.Dgram, 0); - socket.Connect("8.8.8.8", 65530); - IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint; - return endPoint.Address.ToString(); + Log.Warn(e); + return ipInfo.WANv4Address ?? Status.Unavailable.ToString(); } + } - public static async Task GetWANv4Address() + public static async Task GetWANv6Address() + { + try { - try - { - string response = await client.GetStringAsync("https://api.ipify.org"); - - if(IsIPv4(response)) - { - return response; - } + var response = await client.GetStringAsync("https://api64.ipify.org"); - return Status.Unsupported.ToString(); - } - catch(Exception e) + if (IsIPv6(response)) { - Logger.Log.Warn(e); - return ipInfo.WANv4Address ?? Status.Unavailable.ToString(); + return $"[{response}]"; } - } - public static async Task GetWANv6Address() + return Status.Unsupported.ToString(); + } + catch (Exception e) { - try - { - string response = await client.GetStringAsync("https://api64.ipify.org"); - - if(IsIPv6(response)) - { - return $"[{response}]"; - } - - return Status.Unsupported.ToString(); - } - catch (Exception e) - { - Logger.Log.Warn(e); - return ipInfo.WANv6Address ?? Status.Unavailable.ToString(); - } + Log.Warn(e); + return ipInfo.WANv6Address ?? Status.Unavailable.ToString(); } + } - public static async Task GetPortStatus(ushort port) + public static async Task GetPortStatus(ushort port) + { + try { + var response = await client.GetStringAsync($"https://ifconfig.co/port/{port}"); + var jObject = MiniJson.Deserialize(response) as Dictionary; + if (IsIPv4((string)jObject["ip"])) + { + return (bool)jObject["reachable"] ? PortStatus.Open.ToString() : PortStatus.Closed + "(IPv4)"; + } + // if client has IPv6, extra test for IPv4 port status + var result = ((bool)jObject["reachable"] ? PortStatus.Open.ToString() : PortStatus.Closed.ToString()) + "(IPv6) "; try { - string response = await client.GetStringAsync($"https://ifconfig.co/port/{port}"); - Dictionary jObject = MiniJson.Deserialize(response) as Dictionary; - if (IsIPv4((string)jObject["ip"])) - { - return (bool)jObject["reachable"] ? PortStatus.Open.ToString() : PortStatus.Closed.ToString() + "(IPv4)"; - } - else + IPAddress iPv4Address = null; + foreach (var ip in Dns.GetHostEntry(string.Empty).AddressList) { - // if client has IPv6, extra test for IPv4 port status - string result = ((bool)jObject["reachable"] ? PortStatus.Open.ToString() : PortStatus.Closed.ToString()) + "(IPv6) "; - try + if (ip.AddressFamily == AddressFamily.InterNetwork) { - IPAddress iPv4Address = null; - foreach (IPAddress ip in Dns.GetHostEntry(string.Empty).AddressList) - { - if (ip.AddressFamily == AddressFamily.InterNetwork) - { - string str = ip.ToString(); - if (!str.StartsWith("127.0") && !str.StartsWith("192.168")) - { - iPv4Address = ip; - break; - } - } - } - if (iPv4Address != null) + var str = ip.ToString(); + if (!str.StartsWith("127.0") && !str.StartsWith("192.168")) { - // TODO: More respect about rate limit? - HttpWebRequest httpWebRequest = HttpWebRequest.Create($"https://ifconfig.co/port/{port}") as HttpWebRequest; - httpWebRequest.Timeout = 5000; - httpWebRequest.ServicePoint.BindIPEndPointDelegate = (servicePoint, remoteEndPoint, retryCount) => new IPEndPoint(iPv4Address, 0); - - using WebResponse webResponse = await httpWebRequest.GetResponseAsync(); - using Stream stream = webResponse.GetResponseStream(); - using StreamReader readStream = new(stream, Encoding.UTF8); - response = readStream.ReadToEnd(); - jObject = MiniJson.Deserialize(response) as Dictionary; - result += ((bool)jObject["reachable"] ? PortStatus.Open.ToString() : PortStatus.Closed.ToString()) + "(IPv4)"; + iPv4Address = ip; + break; } } - catch(Exception e) - { - Logger.Log.Warn(e); - } - return result; + } + if (iPv4Address != null) + { + // TODO: More respect about rate limit? + var httpWebRequest = WebRequest.Create($"https://ifconfig.co/port/{port}") as HttpWebRequest; + httpWebRequest.Timeout = 5000; + httpWebRequest.ServicePoint.BindIPEndPointDelegate = (servicePoint, remoteEndPoint, retryCount) => + new IPEndPoint(iPv4Address, 0); + + using var webResponse = await httpWebRequest.GetResponseAsync(); + using var stream = webResponse.GetResponseStream(); + using StreamReader readStream = new(stream, Encoding.UTF8); + response = readStream.ReadToEnd(); + jObject = MiniJson.Deserialize(response) as Dictionary; + result += ((bool)jObject["reachable"] ? PortStatus.Open.ToString() : PortStatus.Closed.ToString()) + + "(IPv4)"; } } catch (Exception e) { - Logger.Log.Warn(e); - return ipInfo.PortStatus ?? Status.Unavailable.ToString(); + Log.Warn(e); } + return result; + } + catch (Exception e) + { + Log.Warn(e); + return ipInfo.PortStatus ?? Status.Unavailable.ToString(); } + } - public static async Task GetIPInfo(ushort port = default) + public static async Task GetIPInfo(ushort port = default) + { + if (timer.Enabled && ipInfo.DataState != DataState.Unset) { - if(timer.Enabled && ipInfo.DataState != DataState.Unset) - { - return ipInfo; - } + return ipInfo; + } - var rawInfo = new IpInfo() - { - LANAddress = GetLocalAddress().ToString(), - WANv4Address = await GetWANv4Address(), - WANv6Address = await GetWANv6Address(), - DataState = DataState.Fresh - }; + var rawInfo = new IpInfo + { + LANAddress = GetLocalAddress(), + WANv4Address = await GetWANv4Address(), + WANv6Address = await GetWANv6Address(), + DataState = DataState.Fresh + }; - rawInfo.PortStatus = await GetPortStatus(port); + rawInfo.PortStatus = await GetPortStatus(port); - ipInfo = rawInfo; - ipInfo.DataState = DataState.Cached; - timer.Start(); + ipInfo = rawInfo; + ipInfo.DataState = DataState.Cached; + timer.Start(); - return rawInfo; - } + return rawInfo; + } - public static bool IsIPv6(string ip) + public static bool IsIPv6(string ip) + { + if (IPAddress.TryParse(ip, out var ipAddress)) { - if (IPAddress.TryParse(ip, out IPAddress ipAddress)) - { - return ipAddress.AddressFamily == AddressFamily.InterNetworkV6; - } - return false; + return ipAddress.AddressFamily == AddressFamily.InterNetworkV6; } + return false; + } - public static bool IsIPv4(string ip) + public static bool IsIPv4(string ip) + { + if (IPAddress.TryParse(ip, out var ipAddress)) { - if (IPAddress.TryParse(ip, out IPAddress ipAddress)) - { - return ipAddress.AddressFamily == AddressFamily.InterNetwork; - } - return false; + return ipAddress.AddressFamily == AddressFamily.InterNetwork; } + return false; + } - public static async Task IsIPv6Supported() - { - return IsIPv6(await GetWANv6Address()); - } + public static async Task IsIPv6Supported() + { + return IsIPv6(await GetWANv6Address()); + } + + public struct IpInfo + { + public string LANAddress; + public string WANv4Address; + public string WANv6Address; + public string PortStatus; + public DataState DataState; } -} \ No newline at end of file +} diff --git a/NebulaModel/Utils/NativeInterop.cs b/NebulaModel/Utils/NativeInterop.cs index ed72c64c5..01705277d 100644 --- a/NebulaModel/Utils/NativeInterop.cs +++ b/NebulaModel/Utils/NativeInterop.cs @@ -1,69 +1,73 @@ -using System; -using System.Threading; +#region + +using System; using System.Runtime.InteropServices; +using System.Threading; using BepInEx; -namespace NebulaModel.Utils +#endregion + +namespace NebulaModel.Utils; + +public class NativeInterop { - public class NativeInterop - { - [DllImport("user32.dll")] - private static extern IntPtr GetActiveWindow(); + private const int SW_HIDE = 0; - [DllImport("user32.dll")] - private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); + [DllImport("user32.dll")] + private static extern IntPtr GetActiveWindow(); - private const int SW_HIDE = 0; + [DllImport("user32.dll")] + private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); - public static void HideWindow() - { - ShowWindow(GetActiveWindow(), SW_HIDE); - } + public static void HideWindow() + { + ShowWindow(GetActiveWindow(), SW_HIDE); + } - [DllImport("Kernel32")] - private static extern bool SetConsoleCtrlHandler(CtrlHandler handler, bool add); + [DllImport("Kernel32")] + private static extern bool SetConsoleCtrlHandler(CtrlHandler handler, bool add); - private delegate bool CtrlHandler(CtrlType sig); + private static bool Handler(CtrlType sig) + { + Console.WriteLine($"Exiting app due to {sig}"); - private enum CtrlType + switch (sig) { - CTRL_C_EVENT = 0, - CTRL_BREAK_EVENT = 1, - CTRL_CLOSE_EVENT = 2, - CTRL_LOGOFF_EVENT = 5, - CTRL_SHUTDOWN_EVENT = 6 + // Only CTRL_C, CTRL_BREAK events have no timeout + case CtrlType.CTRL_C_EVENT: + case CtrlType.CTRL_BREAK_EVENT: + Console.WriteLine("Start saving to last exit..."); + ManualResetEvent mre = new(false); + ThreadingHelper.Instance.StartSyncInvoke(() => + { + UIRoot.instance.uiGame.escMenu.OnButton6Click(); //ESC Menu - ExitProgram; + mre.Set(); + }); + mre.WaitOne(); + Console.WriteLine("Saving completed!"); + Thread.Sleep(1000); + return false; } + Thread.Sleep(500); + return false; + } - private static bool Handler(CtrlType sig) - { - Console.WriteLine($"Exiting app due to {sig}"); + public static void SetConsoleCtrlHandler() + { + // if the handler is no longer static, it can get GC'd because nothing is keeping a reference to the delegate. + var result = SetConsoleCtrlHandler(Handler, true); + Console.WriteLine("SetConsoleCtrlHandler: " + (result ? "Success" : "Fail")); + } - switch(sig) - { - // Only CTRL_C, CTRL_BREAK events have no timeout - case CtrlType.CTRL_C_EVENT: - case CtrlType.CTRL_BREAK_EVENT: - Console.WriteLine($"Start saving to last exit..."); - ManualResetEvent mre = new(false); - ThreadingHelper.Instance.StartSyncInvoke(() => { - UIRoot.instance.uiGame.escMenu.OnButton6Click(); //ESC Menu - ExitProgram; - mre.Set(); - }); - mre.WaitOne(); - Console.WriteLine($"Saving completed!"); - Thread.Sleep(1000); - return false; - } - Thread.Sleep(500); - return false; - } + private delegate bool CtrlHandler(CtrlType sig); - public static void SetConsoleCtrlHandler() - { - // if the handler is no longer static, it can get GC'd because nothing is keeping a reference to the delegate. - bool result = SetConsoleCtrlHandler(new CtrlHandler(Handler), true); - Console.WriteLine("SetConsoleCtrlHandler: " + (result ? "Success" : "Fail")); - } + private enum CtrlType + { + CTRL_C_EVENT = 0, + CTRL_BREAK_EVENT = 1, + CTRL_CLOSE_EVENT = 2, + CTRL_LOGOFF_EVENT = 5, + CTRL_SHUTDOWN_EVENT = 6 } } diff --git a/NebulaModel/Utils/ProtoUtils.cs b/NebulaModel/Utils/ProtoUtils.cs index 6fcb756f9..f6f8505a7 100644 --- a/NebulaModel/Utils/ProtoUtils.cs +++ b/NebulaModel/Utils/ProtoUtils.cs @@ -1,30 +1,29 @@ -namespace NebulaModel.Utils +namespace NebulaModel.Utils; + +public static class ProtoUtils { - public static class ProtoUtils + public static string GetSignalDisplayName(int signalId) { - public static string GetSignalDisplayName(int signalId) + if (signalId < 1000) { - if (signalId < 1000) - { - SignalProto signal = LDB.signals.Select(signalId); - return signal.name; - //return $"signal-{signalId}"; - } - if (signalId < 20000) - { - ItemProto proto = LDB.items.Select(signalId); - return proto.name; - } - if (signalId < 40000) - { - RecipeProto proto = LDB.recipes.Select(signalId - 20000); - return proto.name; - } - else - { - TechProto proto = LDB.techs.Select(signalId - 40000); - return proto.name; - } + var signal = LDB.signals.Select(signalId); + return signal.name; + //return $"signal-{signalId}"; + } + if (signalId < 20000) + { + var proto = LDB.items.Select(signalId); + return proto.name; + } + if (signalId < 40000) + { + var proto = LDB.recipes.Select(signalId - 20000); + return proto.name; + } + else + { + var proto = LDB.techs.Select(signalId - 40000); + return proto.name; } } -} \ No newline at end of file +} diff --git a/NebulaModel/Utils/SimpleJsonParser.cs b/NebulaModel/Utils/SimpleJsonParser.cs index 8a9d5904c..6f14a01b8 100644 --- a/NebulaModel/Utils/SimpleJsonParser.cs +++ b/NebulaModel/Utils/SimpleJsonParser.cs @@ -1,632 +1,592 @@ -/* - * Copyright (c) 2013 Calvin Rien - * - * Based on the JSON parser by Patrick van Bergen - * http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html - * - * Simplified it so that it doesn't throw exceptions - * and can be used in Unity iPhone with maximum code stripping. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ +#region + using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; -namespace NebulaModel.Utils +#endregion + +namespace NebulaModel.Utils; +// Example usage: +// +// using UnityEngine; +// using System.Collections; +// using System.Collections.Generic; +// using MiniJSON; +// +// public class MiniJSONTest : MonoBehaviour { +// void Start () { +// var jsonString = "{ \"array\": [1.44,2,3], " + +// "\"object\": {\"key1\":\"value1\", \"key2\":256}, " + +// "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " + +// "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " + +// "\"int\": 65536, " + +// "\"float\": 3.1415926, " + +// "\"bool\": true, " + +// "\"null\": null }"; +// +// var dict = Json.Deserialize(jsonString) as Dictionary; +// +// Debug.Log("deserialized: " + dict.GetType()); +// Debug.Log("dict['array'][0]: " + ((List) dict["array"])[0]); +// Debug.Log("dict['string']: " + (string) dict["string"]); +// Debug.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles +// Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs +// Debug.Log("dict['unicode']: " + (string) dict["unicode"]); +// +// var str = Json.Serialize(dict); +// +// Debug.Log("serialized: " + str); +// } +// } + +/// +/// This class encodes and decodes JSON strings. +/// Spec. details, see http://www.json.org/ +/// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary. +/// All numbers are parsed to doubles. +/// +public static class MiniJson { - // Example usage: - // - // using UnityEngine; - // using System.Collections; - // using System.Collections.Generic; - // using MiniJSON; - // - // public class MiniJSONTest : MonoBehaviour { - // void Start () { - // var jsonString = "{ \"array\": [1.44,2,3], " + - // "\"object\": {\"key1\":\"value1\", \"key2\":256}, " + - // "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " + - // "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " + - // "\"int\": 65536, " + - // "\"float\": 3.1415926, " + - // "\"bool\": true, " + - // "\"null\": null }"; - // - // var dict = Json.Deserialize(jsonString) as Dictionary; - // - // Debug.Log("deserialized: " + dict.GetType()); - // Debug.Log("dict['array'][0]: " + ((List) dict["array"])[0]); - // Debug.Log("dict['string']: " + (string) dict["string"]); - // Debug.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles - // Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs - // Debug.Log("dict['unicode']: " + (string) dict["unicode"]); - // - // var str = Json.Serialize(dict); - // - // Debug.Log("serialized: " + str); - // } - // } - /// - /// This class encodes and decodes JSON strings. - /// Spec. details, see http://www.json.org/ - /// - /// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary. - /// All numbers are parsed to doubles. + /// Parses the string json into a value /// - public static class MiniJson + /// A JSON string. + /// An List<object>, a Dictionary<string, object>, a double, an integer,a string, null, true, or false + public static object Deserialize(string json) { - /// - /// Parses the string json into a value - /// - /// A JSON string. - /// An List<object>, a Dictionary<string, object>, a double, an integer,a string, null, true, or false - public static object Deserialize(string json) + // save the string for debug information + if (json == null) { - // save the string for debug information - if (json == null) - { - return null; - } - - return Parser.Parse(json); + return null; } - sealed class Parser : IDisposable - { - const string WORD_BREAK = "{}[],:\""; + return Parser.Parse(json); + } - public static bool IsWordBreak(char c) - { - return Char.IsWhiteSpace(c) || WORD_BREAK.IndexOf(c) != -1; - } + /// + /// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string + /// + /// A Dictionary<string, object> / List<object> + /// A JSON encoded string, or null if object 'json' is not serializable + public static string Serialize(object obj) + { + return Serializer.Serialize(obj); + } - enum TOKEN - { - NONE, - CURLY_OPEN, - CURLY_CLOSE, - SQUARED_OPEN, - SQUARED_CLOSE, - COLON, - COMMA, - STRING, - NUMBER, - TRUE, - FALSE, - NULL - }; - - StringReader json; - - Parser(string jsonString) - { - json = new StringReader(jsonString); - } + private sealed class Parser : IDisposable + { + private const string WORD_BREAK = "{}[],:\""; - public static object Parse(string jsonString) - { - using (var instance = new Parser(jsonString)) - { - return instance.ParseValue(); - } - } + private StringReader json; - public void Dispose() - { - json.Dispose(); - json = null; - } + private Parser(string jsonString) + { + json = new StringReader(jsonString); + } - Dictionary ParseObject() - { - Dictionary table = new Dictionary(); + private char PeekChar => Convert.ToChar(json.Peek()); - // ditch opening brace - json.Read(); + private char NextChar => Convert.ToChar(json.Read()); + + private string NextWord + { + get + { + var word = new StringBuilder(); - // { - while (true) + while (!IsWordBreak(PeekChar)) { - switch (NextToken) + word.Append(NextChar); + + if (json.Peek() == -1) { - case TOKEN.NONE: - return null; - case TOKEN.COMMA: - continue; - case TOKEN.CURLY_CLOSE: - return table; - default: - // name - string name = ParseString(); - if (name == null) - { - return null; - } - - // : - if (NextToken != TOKEN.COLON) - { - return null; - } - // ditch the colon - json.Read(); - - // value - table[name] = ParseValue(); - break; + break; } } + + return word.ToString(); } + } - List ParseArray() + private TOKEN NextToken + { + get { - List array = new List(); + EatWhitespace(); - // ditch opening bracket - json.Read(); - - // [ - var parsing = true; - while (parsing) + if (json.Peek() == -1) { - TOKEN nextToken = NextToken; + return TOKEN.NONE; + } - switch (nextToken) - { - case TOKEN.NONE: - return null; - case TOKEN.COMMA: - continue; - case TOKEN.SQUARED_CLOSE: - parsing = false; - break; - default: - object value = ParseByToken(nextToken); + switch (PeekChar) + { + case '{': + return TOKEN.CURLY_OPEN; + case '}': + json.Read(); + return TOKEN.CURLY_CLOSE; + case '[': + return TOKEN.SQUARED_OPEN; + case ']': + json.Read(); + return TOKEN.SQUARED_CLOSE; + case ',': + json.Read(); + return TOKEN.COMMA; + case '"': + return TOKEN.STRING; + case ':': + return TOKEN.COLON; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '-': + return TOKEN.NUMBER; + } - array.Add(value); - break; - } + switch (NextWord) + { + case "false": + return TOKEN.FALSE; + case "true": + return TOKEN.TRUE; + case "null": + return TOKEN.NULL; } - return array; + return TOKEN.NONE; } + } + + public void Dispose() + { + json.Dispose(); + json = null; + } + + public static bool IsWordBreak(char c) + { + return char.IsWhiteSpace(c) || WORD_BREAK.IndexOf(c) != -1; + } - object ParseValue() + public static object Parse(string jsonString) + { + using (var instance = new Parser(jsonString)) { - TOKEN nextToken = NextToken; - return ParseByToken(nextToken); + return instance.ParseValue(); } + } + + private Dictionary ParseObject() + { + var table = new Dictionary(); - object ParseByToken(TOKEN token) + // ditch opening brace + json.Read(); + + // { + while (true) { - switch (token) + switch (NextToken) { - case TOKEN.STRING: - return ParseString(); - case TOKEN.NUMBER: - return ParseNumber(); - case TOKEN.CURLY_OPEN: - return ParseObject(); - case TOKEN.SQUARED_OPEN: - return ParseArray(); - case TOKEN.TRUE: - return true; - case TOKEN.FALSE: - return false; - case TOKEN.NULL: + case TOKEN.NONE: return null; + case TOKEN.COMMA: + continue; + case TOKEN.CURLY_CLOSE: + return table; default: - return null; - } - } - - string ParseString() - { - StringBuilder s = new StringBuilder(); - char c; - - // ditch opening quote - json.Read(); + // name + var name = ParseString(); + if (name == null) + { + return null; + } - bool parsing = true; - while (parsing) - { + // : + if (NextToken != TOKEN.COLON) + { + return null; + } + // ditch the colon + json.Read(); - if (json.Peek() == -1) - { - parsing = false; + // value + table[name] = ParseValue(); break; - } - - c = NextChar; - switch (c) - { - case '"': - parsing = false; - break; - case '\\': - if (json.Peek() == -1) - { - parsing = false; - break; - } - - c = NextChar; - switch (c) - { - case '"': - case '\\': - case '/': - s.Append(c); - break; - case 'b': - s.Append('\b'); - break; - case 'f': - s.Append('\f'); - break; - case 'n': - s.Append('\n'); - break; - case 'r': - s.Append('\r'); - break; - case 't': - s.Append('\t'); - break; - case 'u': - var hex = new char[4]; - - for (int i = 0; i < 4; i++) - { - hex[i] = NextChar; - } - - s.Append((char)Convert.ToInt32(new string(hex), 16)); - break; - } - break; - default: - s.Append(c); - break; - } } - - return s.ToString(); } + } - object ParseNumber() - { - string number = NextWord; - - if (number.IndexOf('.') == -1) - { - long parsedInt; - Int64.TryParse(number, out parsedInt); - return parsedInt; - } + private List ParseArray() + { + var array = new List(); - double parsedDouble; - Double.TryParse(number, out parsedDouble); - return parsedDouble; - } + // ditch opening bracket + json.Read(); - void EatWhitespace() + // [ + var parsing = true; + while (parsing) { - while (Char.IsWhiteSpace(PeekChar)) + var nextToken = NextToken; + + switch (nextToken) { - json.Read(); + case TOKEN.NONE: + return null; + case TOKEN.COMMA: + continue; + case TOKEN.SQUARED_CLOSE: + parsing = false; + break; + default: + var value = ParseByToken(nextToken); - if (json.Peek() == -1) - { + array.Add(value); break; - } } } - char PeekChar + return array; + } + + private object ParseValue() + { + var nextToken = NextToken; + return ParseByToken(nextToken); + } + + private object ParseByToken(TOKEN token) + { + switch (token) { - get - { - return Convert.ToChar(json.Peek()); - } + case TOKEN.STRING: + return ParseString(); + case TOKEN.NUMBER: + return ParseNumber(); + case TOKEN.CURLY_OPEN: + return ParseObject(); + case TOKEN.SQUARED_OPEN: + return ParseArray(); + case TOKEN.TRUE: + return true; + case TOKEN.FALSE: + return false; + case TOKEN.NULL: + return null; + default: + return null; } + } + + private string ParseString() + { + var s = new StringBuilder(); + char c; - char NextChar + // ditch opening quote + json.Read(); + + var parsing = true; + while (parsing) { - get + if (json.Peek() == -1) { - return Convert.ToChar(json.Read()); + parsing = false; + break; } - } - string NextWord - { - get + c = NextChar; + switch (c) { - StringBuilder word = new StringBuilder(); - - while (!IsWordBreak(PeekChar)) - { - word.Append(NextChar); - + case '"': + parsing = false; + break; + case '\\': if (json.Peek() == -1) { + parsing = false; break; } - } - return word.ToString(); + c = NextChar; + switch (c) + { + case '"': + case '\\': + case '/': + s.Append(c); + break; + case 'b': + s.Append('\b'); + break; + case 'f': + s.Append('\f'); + break; + case 'n': + s.Append('\n'); + break; + case 'r': + s.Append('\r'); + break; + case 't': + s.Append('\t'); + break; + case 'u': + var hex = new char[4]; + + for (var i = 0; i < 4; i++) + { + hex[i] = NextChar; + } + + s.Append((char)Convert.ToInt32(new string(hex), 16)); + break; + } + break; + default: + s.Append(c); + break; } } - TOKEN NextToken - { - get - { - EatWhitespace(); + return s.ToString(); + } - if (json.Peek() == -1) - { - return TOKEN.NONE; - } + private object ParseNumber() + { + var number = NextWord; - switch (PeekChar) - { - case '{': - return TOKEN.CURLY_OPEN; - case '}': - json.Read(); - return TOKEN.CURLY_CLOSE; - case '[': - return TOKEN.SQUARED_OPEN; - case ']': - json.Read(); - return TOKEN.SQUARED_CLOSE; - case ',': - json.Read(); - return TOKEN.COMMA; - case '"': - return TOKEN.STRING; - case ':': - return TOKEN.COLON; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - case '-': - return TOKEN.NUMBER; - } + if (number.IndexOf('.') == -1) + { + long parsedInt; + long.TryParse(number, out parsedInt); + return parsedInt; + } - switch (NextWord) - { - case "false": - return TOKEN.FALSE; - case "true": - return TOKEN.TRUE; - case "null": - return TOKEN.NULL; - } + double parsedDouble; + double.TryParse(number, out parsedDouble); + return parsedDouble; + } - return TOKEN.NONE; + private void EatWhitespace() + { + while (char.IsWhiteSpace(PeekChar)) + { + json.Read(); + + if (json.Peek() == -1) + { + break; } } } - /// - /// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string - /// - /// A Dictionary<string, object> / List<object> - /// A JSON encoded string, or null if object 'json' is not serializable + private enum TOKEN + { + NONE, + CURLY_OPEN, + CURLY_CLOSE, + SQUARED_OPEN, + SQUARED_CLOSE, + COLON, + COMMA, + STRING, + NUMBER, + TRUE, + FALSE, + NULL + } + } + + private sealed class Serializer + { + private readonly StringBuilder builder; + + private Serializer() + { + builder = new StringBuilder(); + } + public static string Serialize(object obj) { - return Serializer.Serialize(obj); + var instance = new Serializer(); + + instance.SerializeValue(obj); + + return instance.builder.ToString(); } - sealed class Serializer + private void SerializeValue(object value) { - StringBuilder builder; + IList asList; + IDictionary asDict; + string asStr; - Serializer() + if (value == null) { - builder = new StringBuilder(); + builder.Append("null"); } - - public static string Serialize(object obj) + else if ((asStr = value as string) != null) { - var instance = new Serializer(); - - instance.SerializeValue(obj); - - return instance.builder.ToString(); + SerializeString(asStr); } - - void SerializeValue(object value) + else if (value is bool) { - IList asList; - IDictionary asDict; - string asStr; - - if (value == null) - { - builder.Append("null"); - } - else if ((asStr = value as string) != null) - { - SerializeString(asStr); - } - else if (value is bool) - { - builder.Append((bool)value ? "true" : "false"); - } - else if ((asList = value as IList) != null) - { - SerializeArray(asList); - } - else if ((asDict = value as IDictionary) != null) - { - SerializeObject(asDict); - } - else if (value is char) - { - SerializeString(new string((char)value, 1)); - } - else - { - SerializeOther(value); - } + builder.Append((bool)value ? "true" : "false"); } - - void SerializeObject(IDictionary obj) + else if ((asList = value as IList) != null) + { + SerializeArray(asList); + } + else if ((asDict = value as IDictionary) != null) + { + SerializeObject(asDict); + } + else if (value is char) + { + SerializeString(new string((char)value, 1)); + } + else { - bool first = true; + SerializeOther(value); + } + } - builder.Append('{'); + private void SerializeObject(IDictionary obj) + { + var first = true; - foreach (object e in obj.Keys) - { - if (!first) - { - builder.Append(','); - } + builder.Append('{'); - SerializeString(e.ToString()); - builder.Append(':'); + foreach (var e in obj.Keys) + { + if (!first) + { + builder.Append(','); + } - SerializeValue(obj[e]); + SerializeString(e.ToString()); + builder.Append(':'); - first = false; - } + SerializeValue(obj[e]); - builder.Append('}'); + first = false; } - void SerializeArray(IList anArray) - { - builder.Append('['); - - bool first = true; + builder.Append('}'); + } - foreach (object obj in anArray) - { - if (!first) - { - builder.Append(','); - } + private void SerializeArray(IList anArray) + { + builder.Append('['); - SerializeValue(obj); + var first = true; - first = false; + foreach (var obj in anArray) + { + if (!first) + { + builder.Append(','); } - builder.Append(']'); + SerializeValue(obj); + + first = false; } - void SerializeString(string str) - { - builder.Append('\"'); + builder.Append(']'); + } - char[] charArray = str.ToCharArray(); - foreach (var c in charArray) + private void SerializeString(string str) + { + builder.Append('\"'); + + var charArray = str.ToCharArray(); + foreach (var c in charArray) + { + switch (c) { - switch (c) - { - case '"': - builder.Append("\\\""); - break; - case '\\': - builder.Append("\\\\"); - break; - case '\b': - builder.Append("\\b"); - break; - case '\f': - builder.Append("\\f"); - break; - case '\n': - builder.Append("\\n"); - break; - case '\r': - builder.Append("\\r"); - break; - case '\t': - builder.Append("\\t"); - break; - default: - int codepoint = Convert.ToInt32(c); - if ((codepoint >= 32) && (codepoint <= 126)) - { - builder.Append(c); - } - else - { - builder.Append("\\u"); - builder.Append(codepoint.ToString("x4")); - } - break; - } + case '"': + builder.Append("\\\""); + break; + case '\\': + builder.Append("\\\\"); + break; + case '\b': + builder.Append("\\b"); + break; + case '\f': + builder.Append("\\f"); + break; + case '\n': + builder.Append("\\n"); + break; + case '\r': + builder.Append("\\r"); + break; + case '\t': + builder.Append("\\t"); + break; + default: + var codepoint = Convert.ToInt32(c); + if (codepoint >= 32 && codepoint <= 126) + { + builder.Append(c); + } + else + { + builder.Append("\\u"); + builder.Append(codepoint.ToString("x4")); + } + break; } - - builder.Append('\"'); } - void SerializeOther(object value) + builder.Append('\"'); + } + + private void SerializeOther(object value) + { + // NOTE: decimals lose precision during serialization. + // They always have, I'm just letting you know. + // Previously floats and doubles lost precision too. + if (value is float) { - // NOTE: decimals lose precision during serialization. - // They always have, I'm just letting you know. - // Previously floats and doubles lost precision too. - if (value is float) - { - builder.Append(((float)value).ToString("R")); - } - else if (value is int - || value is uint - || value is long - || value is sbyte - || value is byte - || value is short - || value is ushort - || value is ulong) - { - builder.Append(value); - } - else if (value is double - || value is decimal) - { - builder.Append(Convert.ToDouble(value).ToString("R")); - } - else - { - SerializeString(value.ToString()); - } + builder.Append(((float)value).ToString("R")); + } + else if (value is int + || value is uint + || value is long + || value is sbyte + || value is byte + || value is short + || value is ushort + || value is ulong) + { + builder.Append(value); + } + else if (value is double + || value is decimal) + { + builder.Append(Convert.ToDouble(value).ToString("R")); + } + else + { + SerializeString(value.ToString()); } } } -} \ No newline at end of file +} diff --git a/NebulaModel/Utils/TimeUtils.cs b/NebulaModel/Utils/TimeUtils.cs index 1cbfd45b6..c8557dac4 100644 --- a/NebulaModel/Utils/TimeUtils.cs +++ b/NebulaModel/Utils/TimeUtils.cs @@ -1,14 +1,17 @@ -using System; +#region -namespace NebulaModel.Utils +using System; + +#endregion + +namespace NebulaModel.Utils; + +public class TimeUtils { - public class TimeUtils - { - private static readonly DateTime UNIX_EPOCH = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + private static readonly DateTime UNIX_EPOCH = new(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - public static long CurrentUnixTimestampMilliseconds() - { - return (long)(DateTime.UtcNow - UNIX_EPOCH).TotalMilliseconds; - } + public static long CurrentUnixTimestampMilliseconds() + { + return (long)(DateTime.UtcNow - UNIX_EPOCH).TotalMilliseconds; } } diff --git a/NebulaModel/Utils/UnityDispatchQueue.cs b/NebulaModel/Utils/UnityDispatchQueue.cs index 725f57e06..ecefbce97 100644 --- a/NebulaModel/Utils/UnityDispatchQueue.cs +++ b/NebulaModel/Utils/UnityDispatchQueue.cs @@ -1,54 +1,58 @@ -using System; +#region + +using System; using System.Collections.Generic; using UnityEngine; -namespace NebulaModel.Utils +#endregion + +namespace NebulaModel.Utils; + +public class UnityDispatchQueue : MonoBehaviour { - public class UnityDispatchQueue : MonoBehaviour + private static UnityDispatchQueue _instance; + + private readonly Queue actionsQueue = new(); + + private void Update() { - private static UnityDispatchQueue _instance; - private static UnityDispatchQueue GetInstance() + lock (actionsQueue) { - if (!_instance) + while (actionsQueue.Count > 0) { - _instance = FindObjectOfType(); + actionsQueue.Dequeue().Invoke(); } - - if (!_instance) - { - GameObject go = new GameObject(nameof(UnityDispatchQueue)); - _instance = go.AddComponent(); - DontDestroyOnLoad(_instance); - } - - return _instance; } + } - private readonly Queue actionsQueue = new Queue(); + private void OnDestroy() + { + _instance = null; + } - public static void RunOnMainThread(Action action) + private static UnityDispatchQueue GetInstance() + { + if (!_instance) { - UnityDispatchQueue instance = GetInstance(); - lock (instance.actionsQueue) - { - instance.actionsQueue.Enqueue(action); - } + _instance = FindObjectOfType(); } - private void Update() + if (!_instance) { - lock (actionsQueue) - { - while (actionsQueue.Count > 0) - { - actionsQueue.Dequeue().Invoke(); - } - } + var go = new GameObject(nameof(UnityDispatchQueue)); + _instance = go.AddComponent(); + DontDestroyOnLoad(_instance); } - private void OnDestroy() + return _instance; + } + + public static void RunOnMainThread(Action action) + { + var instance = GetInstance(); + lock (instance.actionsQueue) { - _instance = null; + instance.actionsQueue.Enqueue(action); } } } diff --git a/NebulaNetwork/Client.cs b/NebulaNetwork/Client.cs index a4aa5dfca..70631cfb7 100644 --- a/NebulaNetwork/Client.cs +++ b/NebulaNetwork/Client.cs @@ -1,4 +1,10 @@ -using HarmonyLib; +#region + +using System; +using System.IO; +using System.Net; +using System.Net.Sockets; +using HarmonyLib; using NebulaAPI; using NebulaModel; using NebulaModel.Logger; @@ -10,361 +16,363 @@ using NebulaModel.Utils; using NebulaWorld; using NebulaWorld.GameStates; -using System.IO; -using System.Net; -using System.Net.Sockets; -using System.Reflection; using UnityEngine; using UnityEngine.UI; using WebSocketSharp; -namespace NebulaNetwork +#endregion + +namespace NebulaNetwork; + +public class Client : NetworkProvider, IClient { - public class Client : NetworkProvider, IClient + private const float FRAGEMENT_UPDATE_INTERVAL = 0.1f; + private const float GAME_STATE_UPDATE_INTERVAL = 1f; + private const float MECHA_SYNCHONIZATION_INTERVAL = 30f; + + private readonly AccessTools.FieldRef fragmentsBufferRef = + AccessTools.FieldRefAccess("_fragmentsBuffer"); + + private readonly string serverPassword; + + private WebSocket clientSocket; + + private float fragmentUpdateTimer; + private float gameStateUpdateTimer; + private float mechaSynchonizationTimer; + private NebulaConnection serverConnection; + private bool websocketAuthenticationFailure; + + public Client(string url, int port, string password = "") + : this(new IPEndPoint(Dns.GetHostEntry(url).AddressList[0], port), password) { - private const float FRAGEMENT_UPDATE_INTERVAL = 0.1f; - private const float GAME_STATE_UPDATE_INTERVAL = 1f; - private const float MECHA_SYNCHONIZATION_INTERVAL = 30f; - - private readonly IPEndPoint serverEndpoint; - private readonly string serverPassword; - public IPEndPoint ServerEndpoint => serverEndpoint; - - private WebSocket clientSocket; - private NebulaConnection serverConnection; - private bool websocketAuthenticationFailure; - - private float fragmentUpdateTimer = 0f; - private float mechaSynchonizationTimer = 0f; - private float gameStateUpdateTimer = 0f; - - public Client(string url, int port, string password = "") - : this(new IPEndPoint(Dns.GetHostEntry(url).AddressList[0], port), password) - { - } + } - public Client(IPEndPoint endpoint, string password = "") : base(null) - { - serverEndpoint = endpoint; - serverPassword = password; + public Client(IPEndPoint endpoint, string password = "") : base(null) + { + ServerEndpoint = endpoint; + serverPassword = password; + } - } + public IPEndPoint ServerEndpoint { get; } - public override void Start() + public override void Start() + { + foreach (var assembly in AssembliesUtils.GetNebulaAssemblies()) { - foreach (Assembly assembly in AssembliesUtils.GetNebulaAssemblies()) - { - PacketUtils.RegisterAllPacketNestedTypesInAssembly(assembly, PacketProcessor); - } - PacketUtils.RegisterAllPacketProcessorsInCallingAssembly(PacketProcessor, false); + PacketUtils.RegisterAllPacketNestedTypesInAssembly(assembly, PacketProcessor); + } + PacketUtils.RegisterAllPacketProcessorsInCallingAssembly(PacketProcessor, false); - foreach (Assembly assembly in NebulaModAPI.TargetAssemblies) - { - PacketUtils.RegisterAllPacketNestedTypesInAssembly(assembly, PacketProcessor); - PacketUtils.RegisterAllPacketProcessorsInAssembly(assembly, PacketProcessor, false); - } + foreach (var assembly in NebulaModAPI.TargetAssemblies) + { + PacketUtils.RegisterAllPacketNestedTypesInAssembly(assembly, PacketProcessor); + PacketUtils.RegisterAllPacketProcessorsInAssembly(assembly, PacketProcessor, false); + } #if DEBUG - PacketProcessor.SimulateLatency = true; + PacketProcessor.SimulateLatency = true; #endif - clientSocket = new WebSocket($"ws://{serverEndpoint}/socket"); - clientSocket.Log.Level = LogLevel.Debug; - clientSocket.Log.Output = Log.SocketOutput; - clientSocket.OnOpen += ClientSocket_OnOpen; - clientSocket.OnClose += ClientSocket_OnClose; - clientSocket.OnMessage += ClientSocket_OnMessage; + clientSocket = new WebSocket($"ws://{ServerEndpoint}/socket"); + clientSocket.Log.Level = LogLevel.Debug; + clientSocket.Log.Output = Log.SocketOutput; + clientSocket.OnOpen += ClientSocket_OnOpen; + clientSocket.OnClose += ClientSocket_OnClose; + clientSocket.OnMessage += ClientSocket_OnMessage; - var currentLogOutput = clientSocket.Log.Output; - clientSocket.Log.Output = (logData, arg2) => - { - currentLogOutput(logData, arg2); - - // This method of detecting an authentication failure is super finicky, however there is no other way to do this in the websocket package we are currently using - if (logData.Level == LogLevel.Fatal && logData.Message == "Requires the authentication.") - { - websocketAuthenticationFailure = true; - } - }; + var currentLogOutput = clientSocket.Log.Output; + clientSocket.Log.Output = (logData, arg2) => + { + currentLogOutput(logData, arg2); - if (!string.IsNullOrWhiteSpace(serverPassword)) + // This method of detecting an authentication failure is super finicky, however there is no other way to do this in the websocket package we are currently using + if (logData.Level == LogLevel.Fatal && logData.Message == "Requires the authentication.") { - clientSocket.SetCredentials("nebula-player", serverPassword, true); + websocketAuthenticationFailure = true; } + }; - websocketAuthenticationFailure = false; - - clientSocket.Connect(); - - ((LocalPlayer)Multiplayer.Session.LocalPlayer).IsHost = false; + if (!string.IsNullOrWhiteSpace(serverPassword)) + { + clientSocket.SetCredentials("nebula-player", serverPassword, true); + } - if (Config.Options.RememberLastIP) - { - // We've successfully connected, set connection as last ip, cutting out "ws://" and "/socket" - Config.Options.LastIP = serverEndpoint.ToString(); - Config.SaveOptions(); - } + websocketAuthenticationFailure = false; - if (Config.Options.RememberLastClientPassword && !string.IsNullOrWhiteSpace(serverPassword)) - { - Config.Options.LastClientPassword = serverPassword; - Config.SaveOptions(); - } + clientSocket.Connect(); - try - { - NebulaModAPI.OnMultiplayerGameStarted?.Invoke(); - } - catch (System.Exception e) - { - Log.Error("NebulaModAPI.OnMultiplayerGameStarted error:\n" + e); - } - } + ((LocalPlayer)Multiplayer.Session.LocalPlayer).IsHost = false; - public override void Stop() + if (Config.Options.RememberLastIP) { - clientSocket?.Close((ushort)DisconnectionReason.ClientRequestedDisconnect, "Player left the game"); - - // load settings again to dispose the temp soil setting that could have been received from server - Config.LoadOptions(); - try - { - NebulaModAPI.OnMultiplayerGameEnded?.Invoke(); - } - catch (System.Exception e) - { - Log.Error("NebulaModAPI.OnMultiplayerGameEnded error:\n" + e); - } + // We've successfully connected, set connection as last ip, cutting out "ws://" and "/socket" + Config.Options.LastIP = ServerEndpoint.ToString(); + Config.SaveOptions(); } - public override void Dispose() + if (Config.Options.RememberLastClientPassword && !string.IsNullOrWhiteSpace(serverPassword)) { - Stop(); + Config.Options.LastClientPassword = serverPassword; + Config.SaveOptions(); } - public override void SendPacket(T packet) + try { - serverConnection?.SendPacket(packet); + NebulaModAPI.OnMultiplayerGameStarted?.Invoke(); } - public override void SendPacketExclude(T packet, INebulaConnection exclude) + catch (Exception e) { - // Only possible from host - throw new System.NotImplementedException(); + Log.Error("NebulaModAPI.OnMultiplayerGameStarted error:\n" + e); } + } - public override void SendPacketToLocalStar(T packet) - { - serverConnection?.SendPacket(new StarBroadcastPacket(PacketProcessor.Write(packet), GameMain.data.localStar?.id ?? -1)); - } + public override void Stop() + { + clientSocket?.Close((ushort)DisconnectionReason.ClientRequestedDisconnect, "Player left the game"); - public override void SendPacketToLocalPlanet(T packet) + // load settings again to dispose the temp soil setting that could have been received from server + Config.LoadOptions(); + try { - serverConnection?.SendPacket(new PlanetBroadcastPacket(PacketProcessor.Write(packet), GameMain.mainPlayer.planetId)); + NebulaModAPI.OnMultiplayerGameEnded?.Invoke(); } - - public override void SendPacketToPlanet(T packet, int planetId) + catch (Exception e) { - // Only possible from host - throw new System.NotImplementedException(); + Log.Error("NebulaModAPI.OnMultiplayerGameEnded error:\n" + e); } + } - public override void SendPacketToStar(T packet, int starId) - { - // Only possible from host - throw new System.NotImplementedException(); - } + public override void Dispose() + { + Stop(); + } - public override void SendPacketToStarExclude(T packet, int starId, INebulaConnection exclude) - { - // Only possible from host - throw new System.NotImplementedException(); - } + public override void SendPacket(T packet) + { + serverConnection?.SendPacket(packet); + } - public override void Update() - { - PacketProcessor.ProcessPacketQueue(); + public override void SendPacketExclude(T packet, INebulaConnection exclude) + { + // Only possible from host + throw new NotImplementedException(); + } - if (Multiplayer.Session.IsGameLoaded) - { - mechaSynchonizationTimer += Time.deltaTime; - if (mechaSynchonizationTimer > MECHA_SYNCHONIZATION_INTERVAL) - { - SendPacket(new PlayerMechaData(GameMain.mainPlayer)); - mechaSynchonizationTimer = 0f; - } + public override void SendPacketToLocalStar(T packet) + { + serverConnection?.SendPacket(new StarBroadcastPacket(PacketProcessor.Write(packet), GameMain.data.localStar?.id ?? -1)); + } - gameStateUpdateTimer += Time.deltaTime; - if (gameStateUpdateTimer >= GAME_STATE_UPDATE_INTERVAL) - { - if (!GameMain.isFullscreenPaused) - { - SendPacket(new GameStateRequest()); - } - gameStateUpdateTimer = 0f; - } + public override void SendPacketToLocalPlanet(T packet) + { + serverConnection?.SendPacket(new PlanetBroadcastPacket(PacketProcessor.Write(packet), GameMain.mainPlayer.planetId)); + } + + public override void SendPacketToPlanet(T packet, int planetId) + { + // Only possible from host + throw new NotImplementedException(); + } + + public override void SendPacketToStar(T packet, int starId) + { + // Only possible from host + throw new NotImplementedException(); + } + + public override void SendPacketToStarExclude(T packet, int starId, INebulaConnection exclude) + { + // Only possible from host + throw new NotImplementedException(); + } + + public override void Update() + { + PacketProcessor.ProcessPacketQueue(); + + if (Multiplayer.Session.IsGameLoaded) + { + mechaSynchonizationTimer += Time.deltaTime; + if (mechaSynchonizationTimer > MECHA_SYNCHONIZATION_INTERVAL) + { + SendPacket(new PlayerMechaData(GameMain.mainPlayer)); + mechaSynchonizationTimer = 0f; } - fragmentUpdateTimer += Time.deltaTime; - if (fragmentUpdateTimer >= FRAGEMENT_UPDATE_INTERVAL) + gameStateUpdateTimer += Time.deltaTime; + if (gameStateUpdateTimer >= GAME_STATE_UPDATE_INTERVAL) { - if (GameStatesManager.FragmentSize > 0) + if (!GameMain.isFullscreenPaused) { - GameStatesManager.UpdateBufferLength(GetFragmentBufferLength()); + SendPacket(new GameStateRequest()); } - fragmentUpdateTimer = 0f; + gameStateUpdateTimer = 0f; } } - private void ClientSocket_OnMessage(object sender, MessageEventArgs e) + fragmentUpdateTimer += Time.deltaTime; + if (fragmentUpdateTimer >= FRAGEMENT_UPDATE_INTERVAL) { - if (!Multiplayer.IsLeavingGame) + if (GameStatesManager.FragmentSize > 0) { - PacketProcessor.EnqueuePacketForProcessing(e.RawData, serverConnection); + GameStatesManager.UpdateBufferLength(GetFragmentBufferLength()); } + fragmentUpdateTimer = 0f; } + } - private void ClientSocket_OnOpen(object sender, System.EventArgs e) + private void ClientSocket_OnMessage(object sender, MessageEventArgs e) + { + if (!Multiplayer.IsLeavingGame) { - DisableNagleAlgorithm(clientSocket); - - Log.Info($"Server connection established"); - serverConnection = new NebulaConnection(clientSocket, serverEndpoint, PacketProcessor); + PacketProcessor.EnqueuePacketForProcessing(e.RawData, serverConnection); + } + } - //TODO: Maybe some challenge-response authentication mechanism? + private void ClientSocket_OnOpen(object sender, EventArgs e) + { + DisableNagleAlgorithm(clientSocket); - SendPacket(new LobbyRequest( - CryptoUtils.GetPublicKey(CryptoUtils.GetOrCreateUserCert()), - !string.IsNullOrWhiteSpace(Config.Options.Nickname) ? Config.Options.Nickname : GameMain.data.account.userName)); - } + Log.Info("Server connection established"); + serverConnection = new NebulaConnection(clientSocket, ServerEndpoint, PacketProcessor); - private void ClientSocket_OnClose(object sender, CloseEventArgs e) - { - serverConnection = null; + //TODO: Maybe some challenge-response authentication mechanism? - UnityDispatchQueue.RunOnMainThread(() => - { - // If the client is Quitting by himself, we don't have to inform him of his disconnection. - if (e.Code == (ushort)DisconnectionReason.ClientRequestedDisconnect) - { - return; - } + SendPacket(new LobbyRequest( + CryptoUtils.GetPublicKey(CryptoUtils.GetOrCreateUserCert()), + !string.IsNullOrWhiteSpace(Config.Options.Nickname) ? Config.Options.Nickname : GameMain.data.account.userName)); + } - // Opens the pause menu on disconnection to prevent NRE when leaving the game - if (Multiplayer.Session?.IsGameLoaded ?? false) - { - GameMain.instance._paused = true; - } + private void ClientSocket_OnClose(object sender, CloseEventArgs e) + { + serverConnection = null; - if (e.Code == (ushort)DisconnectionReason.ModIsMissing) - { - InGamePopup.ShowWarning( - "Mod Mismatch".Translate(), - string.Format("You are missing mod {0}".Translate(), e.Reason), - "OK".Translate(), - Multiplayer.LeaveGame); - return; - } + UnityDispatchQueue.RunOnMainThread(() => + { + // If the client is Quitting by himself, we don't have to inform him of his disconnection. + if (e.Code == (ushort)DisconnectionReason.ClientRequestedDisconnect) + { + return; + } - if (e.Code == (ushort)DisconnectionReason.ModIsMissingOnServer) - { - InGamePopup.ShowWarning( - "Mod Mismatch".Translate(), - string.Format("Server is missing mod {0}".Translate(), e.Reason), - "OK".Translate(), - Multiplayer.LeaveGame); - return; - } + // Opens the pause menu on disconnection to prevent NRE when leaving the game + if (Multiplayer.Session?.IsGameLoaded ?? false) + { + GameMain.instance._paused = true; + } - if (e.Code == (ushort)DisconnectionReason.ModVersionMismatch) - { - string[] versions = e.Reason.Split(';'); - InGamePopup.ShowWarning( - "Mod Version Mismatch".Translate(), - string.Format("Your mod {0} version is not the same as the Host version.\nYou:{1} - Remote:{2}".Translate(), versions[0], versions[1], versions[2]), - "OK".Translate(), - Multiplayer.LeaveGame); - return; - } + if (e.Code == (ushort)DisconnectionReason.ModIsMissing) + { + InGamePopup.ShowWarning( + "Mod Mismatch".Translate(), + string.Format("You are missing mod {0}".Translate(), e.Reason), + "OK".Translate(), + Multiplayer.LeaveGame); + return; + } - if (e.Code == (ushort)DisconnectionReason.GameVersionMismatch) - { - string[] versions = e.Reason.Split(';'); - InGamePopup.ShowWarning( - "Game Version Mismatch".Translate(), - string.Format("Your version of the game is not the same as the one used by the Host.\nYou:{0} - Remote:{1}".Translate(), versions[0], versions[1]), - "OK".Translate(), - Multiplayer.LeaveGame); - return; - } + if (e.Code == (ushort)DisconnectionReason.ModIsMissingOnServer) + { + InGamePopup.ShowWarning( + "Mod Mismatch".Translate(), + string.Format("Server is missing mod {0}".Translate(), e.Reason), + "OK".Translate(), + Multiplayer.LeaveGame); + return; + } - if (e.Code == (ushort)DisconnectionReason.ProtocolError && websocketAuthenticationFailure) - { - InGamePopup.AskInput( - "Server Requires Password".Translate(), - "Server is protected. Please enter the correct password:".Translate(), - InputField.ContentType.Password, - serverPassword, - (password) => - { - Multiplayer.ShouldReturnToJoinMenu = false; - Multiplayer.LeaveGame(); - Multiplayer.ShouldReturnToJoinMenu = true; - Multiplayer.JoinGame(new Client(serverEndpoint, password)); - }, - Multiplayer.LeaveGame - ); - return; - } + if (e.Code == (ushort)DisconnectionReason.ModVersionMismatch) + { + var versions = e.Reason.Split(';'); + InGamePopup.ShowWarning( + "Mod Version Mismatch".Translate(), + string.Format("Your mod {0} version is not the same as the Host version.\nYou:{1} - Remote:{2}".Translate(), + versions[0], versions[1], versions[2]), + "OK".Translate(), + Multiplayer.LeaveGame); + return; + } - if (e.Code == (ushort)DisconnectionReason.HostStillLoading) - { - InGamePopup.ShowWarning( - "Server Busy".Translate(), - "Server is not ready to join. Please try again later.".Translate(), - "OK".Translate(), - Multiplayer.LeaveGame); - return; - } + if (e.Code == (ushort)DisconnectionReason.GameVersionMismatch) + { + var versions = e.Reason.Split(';'); + InGamePopup.ShowWarning( + "Game Version Mismatch".Translate(), + string.Format( + "Your version of the game is not the same as the one used by the Host.\nYou:{0} - Remote:{1}" + .Translate(), versions[0], versions[1]), + "OK".Translate(), + Multiplayer.LeaveGame); + return; + } - if (Multiplayer.Session.IsGameLoaded || Multiplayer.Session.IsInLobby) - { - InGamePopup.ShowWarning( - "Connection Lost".Translate(), - "You have been disconnected from the server.".Translate() + "\n" + e.Reason, - "Quit", - Multiplayer.LeaveGame); - if (Multiplayer.Session.IsInLobby) + if (e.Code == (ushort)DisconnectionReason.ProtocolError && websocketAuthenticationFailure) + { + InGamePopup.AskInput( + "Server Requires Password".Translate(), + "Server is protected. Please enter the correct password:".Translate(), + InputField.ContentType.Password, + serverPassword, + password => { Multiplayer.ShouldReturnToJoinMenu = false; - Multiplayer.Session.IsInLobby = false; - UIRoot.instance.galaxySelect.CancelSelect(); - } - } - else + Multiplayer.LeaveGame(); + Multiplayer.ShouldReturnToJoinMenu = true; + Multiplayer.JoinGame(new Client(ServerEndpoint, password)); + }, + Multiplayer.LeaveGame + ); + return; + } + + if (e.Code == (ushort)DisconnectionReason.HostStillLoading) + { + InGamePopup.ShowWarning( + "Server Busy".Translate(), + "Server is not ready to join. Please try again later.".Translate(), + "OK".Translate(), + Multiplayer.LeaveGame); + return; + } + + if (Multiplayer.Session.IsGameLoaded || Multiplayer.Session.IsInLobby) + { + InGamePopup.ShowWarning( + "Connection Lost".Translate(), + "You have been disconnected from the server.".Translate() + "\n" + e.Reason, + "Quit", + Multiplayer.LeaveGame); + if (Multiplayer.Session.IsInLobby) { - Log.Warn("Disconnect code: " + e.Code + ", reason:" + e.Reason); - InGamePopup.ShowWarning( - "Server Unavailable".Translate(), - "Could not reach the server, please try again later.".Translate(), - "OK".Translate(), - Multiplayer.LeaveGame); + Multiplayer.ShouldReturnToJoinMenu = false; + Multiplayer.Session.IsInLobby = false; + UIRoot.instance.galaxySelect.CancelSelect(); } - }); - } - - private static void DisableNagleAlgorithm(WebSocket socket) - { - TcpClient tcpClient = AccessTools.FieldRefAccess("_tcpClient")(socket); - if (tcpClient != null) + } + else { - tcpClient.NoDelay = true; + Log.Warn("Disconnect code: " + e.Code + ", reason:" + e.Reason); + InGamePopup.ShowWarning( + "Server Unavailable".Translate(), + "Could not reach the server, please try again later.".Translate(), + "OK".Translate(), + Multiplayer.LeaveGame); } - } + }); + } - private readonly AccessTools.FieldRef fragmentsBufferRef = AccessTools.FieldRefAccess("_fragmentsBuffer"); - private int GetFragmentBufferLength() + private static void DisableNagleAlgorithm(WebSocket socket) + { + var tcpClient = AccessTools.FieldRefAccess("_tcpClient")(socket); + if (tcpClient != null) { - MemoryStream fragmentsBuffer = fragmentsBufferRef(clientSocket); - return (int)(fragmentsBuffer?.Length ?? 0); + tcpClient.NoDelay = true; } } + + private int GetFragmentBufferLength() + { + var fragmentsBuffer = fragmentsBufferRef(clientSocket); + return (int)(fragmentsBuffer?.Length ?? 0); + } } diff --git a/NebulaNetwork/NebulaNetwork.csproj b/NebulaNetwork/NebulaNetwork.csproj index 37424b59e..380c11046 100644 --- a/NebulaNetwork/NebulaNetwork.csproj +++ b/NebulaNetwork/NebulaNetwork.csproj @@ -1,19 +1,19 @@ - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/NebulaNetwork/Ngrok/NgrokManager.cs b/NebulaNetwork/Ngrok/NgrokManager.cs index 6660dde67..18305f35c 100644 --- a/NebulaNetwork/Ngrok/NgrokManager.cs +++ b/NebulaNetwork/Ngrok/NgrokManager.cs @@ -1,315 +1,329 @@ -using System; +#region + +using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Compression; +using System.Linq; using System.Net.Http; using System.Reflection; +using System.Text.RegularExpressions; using System.Threading.Tasks; using NebulaModel; +using NebulaModel.Logger; using NebulaModel.Utils; using NebulaWorld; -using System.Linq; -using System.Text.RegularExpressions; -namespace NebulaNetwork.Ngrok +#endregion + +namespace NebulaNetwork.Ngrok; + +public class NgrokManager { - public class NgrokManager - { - private readonly string _ngrokPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "ngrok-v3-stable-windows-amd64", "ngrok.exe"); - private readonly string _ngrokConfigPath; - private readonly int _port; - private readonly string _authtoken; - private readonly string _region; - private readonly TaskCompletionSource _ngrokAddressObtainedSource = new TaskCompletionSource(); + private readonly string _authtoken; + private readonly TaskCompletionSource _ngrokAddressObtainedSource = new(); + private readonly string _ngrokConfigPath; - private Process _ngrokProcess; - private string _ngrokAPIAddress; + private readonly string _ngrokPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), + "ngrok-v3-stable-windows-amd64", "ngrok.exe"); - public string NgrokAddress; - public string NgrokLastErrorCode; - public bool NgrokEnabled = Config.Options.EnableNgrok; + private readonly int _port; + private readonly string _region; + private string _ngrokAPIAddress; - public NgrokManager(int port, string authtoken = null, string region = null) - { - _ngrokConfigPath = Path.Combine(Path.GetDirectoryName(_ngrokPath), "ngrok.yml"); - _port = port; - _authtoken = authtoken ?? Config.Options.NgrokAuthtoken; - _region = region ?? Config.Options.NgrokRegion; + private Process _ngrokProcess; - if (!NgrokEnabled) - { - return; - } + public string NgrokAddress; + public bool NgrokEnabled = Config.Options.EnableNgrok; + public string NgrokLastErrorCode; - if (string.IsNullOrEmpty(_authtoken)) - { - NebulaModel.Logger.Log.WarnInform("Ngrok support was enabled, however no Authtoken was provided".Translate()); - return; - } + public NgrokManager(int port, string authtoken = null, string region = null) + { + _ngrokConfigPath = Path.Combine(Path.GetDirectoryName(_ngrokPath), "ngrok.yml"); + _port = port; + _authtoken = authtoken ?? Config.Options.NgrokAuthtoken; + _region = region ?? Config.Options.NgrokRegion; - // Validate the Ngrok region - string[] availableRegions = { "us", "eu", "au", "ap", "sa", "jp", "in" }; - if (!string.IsNullOrEmpty(_region) && !availableRegions.Any(_region.Contains)) - { - NebulaModel.Logger.Log.WarnInform("Unsupported Ngrok region was provided, defaulting to autodetection".Translate()); - _region = null; - } + if (!NgrokEnabled) + { + return; + } - // Start this stuff in it's own thread, as we require async and we dont want to freeze up the GUI when freeze up when Downloading and installing ngrok - Task.Run(async () => - { + if (string.IsNullOrEmpty(_authtoken)) + { + Log.WarnInform("Ngrok support was enabled, however no Authtoken was provided".Translate()); + return; + } - if (!IsNgrokInstalled()) - { - var downloadAndInstallConfirmationSource = new TaskCompletionSource(); + // Validate the Ngrok region + string[] availableRegions = { "us", "eu", "au", "ap", "sa", "jp", "in" }; + if (!string.IsNullOrEmpty(_region) && !availableRegions.Any(_region.Contains)) + { + Log.WarnInform("Unsupported Ngrok region was provided, defaulting to autodetection".Translate()); + _region = null; + } - UnityDispatchQueue.RunOnMainThread(() => - { - InGamePopup.ShowWarning( - "Ngrok download and installation confirmation".Translate(), - "Ngrok support is enabled, however it has not been downloaded and installed yet, do you want to automatically download and install Ngrok?".Translate(), - "Accept".Translate(), - "Reject".Translate(), - () => downloadAndInstallConfirmationSource.TrySetResult(true), - () => downloadAndInstallConfirmationSource.TrySetResult(false) - ); - }); - - var hasDownloadAndInstallBeenConfirmed = await downloadAndInstallConfirmationSource.Task; - if (!hasDownloadAndInstallBeenConfirmed) - { - NebulaModel.Logger.Log.Warn("Failed to download or install Ngrok, because user rejected Ngrok download and install confirmation!".Translate()); - return; - } - - try - { - await DownloadAndInstallNgrok(); - } - catch - { - NebulaModel.Logger.Log.WarnInform("Failed to download or install Ngrok!".Translate()); - throw; - } + // Start this stuff in it's own thread, as we require async and we dont want to freeze up the GUI when freeze up when Downloading and installing ngrok + Task.Run(async () => + { + if (!IsNgrokInstalled()) + { + var downloadAndInstallConfirmationSource = new TaskCompletionSource(); - } + UnityDispatchQueue.RunOnMainThread(() => + { + InGamePopup.ShowWarning( + "Ngrok download and installation confirmation".Translate(), + "Ngrok support is enabled, however it has not been downloaded and installed yet, do you want to automatically download and install Ngrok?" + .Translate(), + "Accept".Translate(), + "Reject".Translate(), + () => downloadAndInstallConfirmationSource.TrySetResult(true), + () => downloadAndInstallConfirmationSource.TrySetResult(false) + ); + }); - if (!StartNgrok()) + var hasDownloadAndInstallBeenConfirmed = await downloadAndInstallConfirmationSource.Task; + if (!hasDownloadAndInstallBeenConfirmed) { - NebulaModel.Logger.Log.WarnInform(string.Format("Failed to start Ngrok tunnel! LastErrorCode: {0}".Translate(), NgrokLastErrorCode)); + Log.Warn( + "Failed to download or install Ngrok, because user rejected Ngrok download and install confirmation!" + .Translate()); return; } - if (!IsNgrokActive()) + try { - NebulaModel.Logger.Log.WarnInform(string.Format("Ngrok tunnel has exited prematurely! LastErrorCode: {0}".Translate(), NgrokLastErrorCode)); - return; + await DownloadAndInstallNgrok(); + } + catch + { + Log.WarnInform("Failed to download or install Ngrok!".Translate()); + throw; } + } - }); + if (!StartNgrok()) + { + Log.WarnInform( + string.Format("Failed to start Ngrok tunnel! LastErrorCode: {0}".Translate(), NgrokLastErrorCode)); + return; + } - } + if (!IsNgrokActive()) + { + Log.WarnInform(string.Format("Ngrok tunnel has exited prematurely! LastErrorCode: {0}".Translate(), + NgrokLastErrorCode)); + } + }); + } - private async Task DownloadAndInstallNgrok() + private async Task DownloadAndInstallNgrok() + { + using (var client = new HttpClient()) { - using (var client = new HttpClient()) + using (var s = client.GetStreamAsync("https://bin.equinox.io/c/bNyj1mQVY4c/ngrok-v3-stable-windows-amd64.zip")) { - using (var s = client.GetStreamAsync("https://bin.equinox.io/c/bNyj1mQVY4c/ngrok-v3-stable-windows-amd64.zip")) + using (var zip = new ZipArchive(await s, ZipArchiveMode.Read)) { - using (var zip = new ZipArchive(await s, ZipArchiveMode.Read)) + if (File.Exists(_ngrokPath)) { - if (File.Exists(_ngrokPath)) - { - File.Delete(_ngrokPath); - } - zip.ExtractToDirectory(Path.GetDirectoryName(_ngrokPath)); + File.Delete(_ngrokPath); } + zip.ExtractToDirectory(Path.GetDirectoryName(_ngrokPath)); } } + } - File.WriteAllLines(_ngrokConfigPath, new string[] { "version: 2" }); + File.WriteAllLines(_ngrokConfigPath, new[] { "version: 2" }); - NebulaModel.Logger.Log.WarnInform("Ngrok install completed in the plugin folder".Translate()); - } + Log.WarnInform("Ngrok install completed in the plugin folder".Translate()); + } - private bool IsNgrokInstalled() - { - return File.Exists(_ngrokPath) && File.Exists(_ngrokConfigPath); - } + private bool IsNgrokInstalled() + { + return File.Exists(_ngrokPath) && File.Exists(_ngrokConfigPath); + } - private bool StartNgrok() - { - StopNgrok(); + private bool StartNgrok() + { + StopNgrok(); - _ngrokProcess = new Process(); - _ngrokProcess.StartInfo = new ProcessStartInfo - { - WindowStyle = ProcessWindowStyle.Hidden, - RedirectStandardOutput = true, - RedirectStandardError = true, - UseShellExecute = false, - CreateNoWindow = true, - FileName = _ngrokPath, - Arguments = $"tcp {_port} --authtoken {_authtoken} --log stdout --log-format json --config \"{_ngrokConfigPath}\"" + (!string.IsNullOrEmpty(_region) ? $" --region {_region}" : ""), - }; - - _ngrokProcess.OutputDataReceived += new DataReceivedEventHandler(OutputDataReceivedEventHandler); - _ngrokProcess.ErrorDataReceived += new DataReceivedEventHandler(ErrorDataReceivedEventHandler); - - var started = _ngrokProcess.Start(); - if (IsNgrokActive()) + _ngrokProcess = new Process(); + _ngrokProcess.StartInfo = new ProcessStartInfo + { + WindowStyle = ProcessWindowStyle.Hidden, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true, + FileName = _ngrokPath, + Arguments = + $"tcp {_port} --authtoken {_authtoken} --log stdout --log-format json --config \"{_ngrokConfigPath}\"" + + (!string.IsNullOrEmpty(_region) ? $" --region {_region}" : "") + }; + + _ngrokProcess.OutputDataReceived += OutputDataReceivedEventHandler; + _ngrokProcess.ErrorDataReceived += ErrorDataReceivedEventHandler; + + var started = _ngrokProcess.Start(); + if (IsNgrokActive()) + { + // This links the process as a child process by attaching a null debugger thus ensuring that the process is killed when its parent dies. + new ChildProcessLinker(_ngrokProcess, exception => { - // This links the process as a child process by attaching a null debugger thus ensuring that the process is killed when its parent dies. - new ChildProcessLinker(_ngrokProcess, (exception) => - { - NebulaModel.Logger.Log.Warn("Failed to link Ngrok process to DSP process as a child! (This might result in a left over ngrok process if the DSP process uncleanly killed)"); - }); - } + Log.Warn( + "Failed to link Ngrok process to DSP process as a child! (This might result in a left over ngrok process if the DSP process uncleanly killed)"); + }); + } - _ngrokProcess.BeginOutputReadLine(); - _ngrokProcess.BeginErrorReadLine(); + _ngrokProcess.BeginOutputReadLine(); + _ngrokProcess.BeginErrorReadLine(); - return started; - } + return started; + } - private void OutputDataReceivedEventHandler(object sender, DataReceivedEventArgs e) + private void OutputDataReceivedEventHandler(object sender, DataReceivedEventArgs e) + { + if (!string.IsNullOrEmpty(e.Data)) { - if (!string.IsNullOrEmpty(e.Data)) - { - NebulaModel.Logger.Log.Debug($"Ngrok Stdout: {e.Data}"); + Log.Debug($"Ngrok Stdout: {e.Data}"); - var json = MiniJson.Deserialize(e.Data) as Dictionary; - if (json != null) + var json = MiniJson.Deserialize(e.Data) as Dictionary; + if (json != null) + { + var lvl = json["lvl"] as string; + if (lvl == "info") { - var lvl = json["lvl"] as string; - if (lvl == "info") + var msg = json["msg"] as string; + if (msg == "starting web service") { - var msg = json["msg"] as string; - if (msg == "starting web service") - { - _ngrokAPIAddress = json["addr"] as string; - } else if (msg == "started tunnel") + _ngrokAPIAddress = json["addr"] as string; + } + else if (msg == "started tunnel") + { + var addr = json["addr"] as string; + var url = json["url"] as string; + if ( + (addr == $"//localhost:{_port}" || addr == $"//127.0.0.1:{_port}" || + addr == $"//0.0.0.0:{_port}") && + url.StartsWith("tcp://") + ) { - var addr = json["addr"] as string; - var url = json["url"] as string; - if ( - (addr == $"//localhost:{_port}" || addr == $"//127.0.0.1:{_port}" || addr == $"//0.0.0.0:{_port}") && - url.StartsWith("tcp://") - ) - { - NgrokAddress = url.Replace("tcp://", ""); - _ngrokAddressObtainedSource.TrySetResult(true); - } + NgrokAddress = url.Replace("tcp://", ""); + _ngrokAddressObtainedSource.TrySetResult(true); } } } } } + } - private void ErrorDataReceivedEventHandler(object sender, DataReceivedEventArgs e) + private void ErrorDataReceivedEventHandler(object sender, DataReceivedEventArgs e) + { + if (!string.IsNullOrEmpty(e.Data)) { - if (!string.IsNullOrEmpty(e.Data)) - { - NebulaModel.Logger.Log.Warn($"Ngrok Stderr: {e.Data}"); - - var errorCodeMatches = Regex.Matches(e.Data, @"ERR_NGROK_\d+"); - if (errorCodeMatches.Count > 0) - { - NgrokLastErrorCode = errorCodeMatches[errorCodeMatches.Count - 1].Value; - NebulaModel.Logger.Log.WarnInform(string.Format("Ngrok Error! Code: {0}".Translate(), NgrokLastErrorCode)); - } - } - } + Log.Warn($"Ngrok Stderr: {e.Data}"); - public void StopNgrok() - { - if (_ngrokProcess != null) + var errorCodeMatches = Regex.Matches(e.Data, @"ERR_NGROK_\d+"); + if (errorCodeMatches.Count > 0) { - _ngrokProcess.Refresh(); - if (!_ngrokProcess.HasExited) - { - _ngrokProcess.Kill(); - _ngrokProcess.Close(); - } - _ngrokProcess = null; + NgrokLastErrorCode = errorCodeMatches[errorCodeMatches.Count - 1].Value; + Log.WarnInform(string.Format("Ngrok Error! Code: {0}".Translate(), NgrokLastErrorCode)); } } + } - public bool IsNgrokActive() + public void StopNgrok() + { + if (_ngrokProcess != null) { - if (_ngrokProcess == null) + _ngrokProcess.Refresh(); + if (!_ngrokProcess.HasExited) { - return false; + _ngrokProcess.Kill(); + _ngrokProcess.Close(); } - - _ngrokProcess.Refresh(); - return !_ngrokProcess.HasExited; + _ngrokProcess = null; } + } - public Task GetNgrokAddressAsync() + public bool IsNgrokActive() + { + if (_ngrokProcess == null) { - return Task.Run(() => - { - if (!IsNgrokActive()) - { - throw new Exception($"Not able to get Ngrok tunnel address because Ngrok is not started (or exited prematurely)! LastErrorCode: {NgrokLastErrorCode}"); - } - - if (!_ngrokAddressObtainedSource.Task.Wait(TimeSpan.FromSeconds(15))) - { - throw new TimeoutException($"Not able to get Ngrok tunnel address because 15s timeout was exceeded! LastErrorCode: {NgrokLastErrorCode}"); - } - - return NgrokAddress; - }); + return false; } - public async Task GetTunnelAddressFromAPI() + _ngrokProcess.Refresh(); + return !_ngrokProcess.HasExited; + } + + public Task GetNgrokAddressAsync() + { + return Task.Run(() => { if (!IsNgrokActive()) { - throw new Exception($"Not able to get Ngrok tunnel address from API because Ngrok is not started (or exited prematurely)! LastErrorCode: {NgrokLastErrorCode}"); + throw new Exception( + $"Not able to get Ngrok tunnel address because Ngrok is not started (or exited prematurely)! LastErrorCode: {NgrokLastErrorCode}"); } - if (_ngrokAPIAddress == null) + if (!_ngrokAddressObtainedSource.Task.Wait(TimeSpan.FromSeconds(15))) { - throw new Exception($"Not able to get Ngrok tunnel address because Ngrok API address is not (yet) known!"); + throw new TimeoutException( + $"Not able to get Ngrok tunnel address because 15s timeout was exceeded! LastErrorCode: {NgrokLastErrorCode}"); } - using (var client = new HttpClient()) - { - var response = await client.GetAsync($"http://{_ngrokAPIAddress}/api/tunnels"); - if (response.IsSuccessStatusCode) - { - var body = await response.Content.ReadAsStringAsync(); + return NgrokAddress; + }); + } - var json = MiniJson.Deserialize(body) as Dictionary; + public async Task GetTunnelAddressFromAPI() + { + if (!IsNgrokActive()) + { + throw new Exception( + $"Not able to get Ngrok tunnel address from API because Ngrok is not started (or exited prematurely)! LastErrorCode: {NgrokLastErrorCode}"); + } - var tunnels = json["tunnels"] as List; + if (_ngrokAPIAddress == null) + { + throw new Exception("Not able to get Ngrok tunnel address because Ngrok API address is not (yet) known!"); + } - string publicUrl = null; - foreach (Dictionary tunnel in tunnels) - { - if (tunnel["proto"] as string == "tcp" && (tunnel["config"] as Dictionary)["addr"] as string == $"localhost:{_port}") - { - publicUrl = tunnel["public_url"] as string; - break; - } - } + using (var client = new HttpClient()) + { + var response = await client.GetAsync($"http://{_ngrokAPIAddress}/api/tunnels"); + if (response.IsSuccessStatusCode) + { + var body = await response.Content.ReadAsStringAsync(); + + var json = MiniJson.Deserialize(body) as Dictionary; - if (publicUrl == null) + var tunnels = json["tunnels"] as List; + + string publicUrl = null; + foreach (Dictionary tunnel in tunnels) + { + if (tunnel["proto"] as string == "tcp" && + (tunnel["config"] as Dictionary)["addr"] as string == $"localhost:{_port}") { - throw new Exception("Not able to get Ngrok tunnel address because no matching tunnel was found in API response"); + publicUrl = tunnel["public_url"] as string; + break; } + } - return publicUrl.Replace("tcp://", ""); - - } else + if (publicUrl == null) { - throw new Exception("Could not access the ngrok API"); + throw new Exception( + "Not able to get Ngrok tunnel address because no matching tunnel was found in API response"); } + + return publicUrl.Replace("tcp://", ""); } + throw new Exception("Could not access the ngrok API"); } } } diff --git a/NebulaNetwork/PacketProcessors/Chat/ChatCommandWhisperProcessor.cs b/NebulaNetwork/PacketProcessors/Chat/ChatCommandWhisperProcessor.cs index 55ea64700..bfc14e14d 100644 --- a/NebulaNetwork/PacketProcessors/Chat/ChatCommandWhisperProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Chat/ChatCommandWhisperProcessor.cs @@ -1,4 +1,6 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; @@ -6,39 +8,41 @@ using NebulaWorld; using NebulaWorld.Chat.Commands; -namespace NebulaNetwork.PacketProcessors.Players +#endregion + +namespace NebulaNetwork.PacketProcessors.Players; + +[RegisterPacketProcessor] +internal class ChatCommandWhisperProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class ChatCommandWhisperProcessor : PacketProcessor + public override void ProcessPacket(ChatCommandWhisperPacket packet, NebulaConnection conn) { - public override void ProcessPacket(ChatCommandWhisperPacket packet, NebulaConnection conn) + if (IsClient) + { + WhisperCommandHandler.SendWhisperToLocalPlayer(packet.SenderUsername, packet.Message); + } + else { - if (IsClient) + // two cases, simplest is that whisper is meant for host + if (Multiplayer.Session.LocalPlayer.Data.Username == packet.RecipientUsername) { WhisperCommandHandler.SendWhisperToLocalPlayer(packet.SenderUsername, packet.Message); + return; } - else - { - // two cases, simplest is that whisper is meant for host - if (Multiplayer.Session.LocalPlayer.Data.Username == packet.RecipientUsername) - { - WhisperCommandHandler.SendWhisperToLocalPlayer(packet.SenderUsername, packet.Message); - return; - } - - // second case, relay message to recipient - INebulaPlayer recipient = Multiplayer.Session.Network - .PlayerManager.GetConnectedPlayerByUsername(packet.RecipientUsername); - if (recipient == null) - { - Log.Warn($"Recipient not found {packet.RecipientUsername}"); - INebulaPlayer sender = Multiplayer.Session.Network.PlayerManager.GetPlayer(conn); - sender.SendPacket(new ChatCommandWhisperPacket("SYSTEM".Translate(), packet.SenderUsername, string.Format("User not found {0}".Translate(), packet.RecipientUsername))); - return; - } - recipient.SendPacket(packet); + // second case, relay message to recipient + INebulaPlayer recipient = Multiplayer.Session.Network + .PlayerManager.GetConnectedPlayerByUsername(packet.RecipientUsername); + if (recipient == null) + { + Log.Warn($"Recipient not found {packet.RecipientUsername}"); + INebulaPlayer sender = Multiplayer.Session.Network.PlayerManager.GetPlayer(conn); + sender.SendPacket(new ChatCommandWhisperPacket("SYSTEM".Translate(), packet.SenderUsername, + string.Format("User not found {0}".Translate(), packet.RecipientUsername))); + return; } + + recipient.SendPacket(packet); } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Chat/ChatCommandWhoProcessor.cs b/NebulaNetwork/PacketProcessors/Chat/ChatCommandWhoProcessor.cs index c8a87e75b..56b49ecd6 100644 --- a/NebulaNetwork/PacketProcessors/Chat/ChatCommandWhoProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Chat/ChatCommandWhoProcessor.cs @@ -1,4 +1,6 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.DataStructures; using NebulaModel.Logger; using NebulaModel.Networking; @@ -7,36 +9,33 @@ using NebulaWorld; using NebulaWorld.Chat.Commands; using NebulaWorld.MonoBehaviours.Local; +using NebulaWorld.MonoBehaviours.Local.Chat; + +#endregion + +namespace NebulaNetwork.PacketProcessors.Players; -namespace NebulaNetwork.PacketProcessors.Players +[RegisterPacketProcessor] +internal class ChatCommandWhoProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class ChatCommandWhoProcessor : PacketProcessor + public override void ProcessPacket(ChatCommandWhoPacket packet, NebulaConnection conn) { - - public ChatCommandWhoProcessor() + if (IsHost) { - } + IPlayerData[] playerDatas = Multiplayer.Session.Network.PlayerManager.GetAllPlayerDataIncludingHost(); + ILocalPlayer hostPlayer = Multiplayer.Session.LocalPlayer; + var resultPayload = WhoCommandHandler.BuildResultPayload(playerDatas, hostPlayer); - public override void ProcessPacket(ChatCommandWhoPacket packet, NebulaConnection conn) + INebulaPlayer recipient = Multiplayer.Session.Network.PlayerManager.GetPlayer(conn); + recipient.SendPacket(new ChatCommandWhoPacket(false, resultPayload)); + } + else { - if (IsHost) - { - IPlayerData[] playerDatas = Multiplayer.Session.Network.PlayerManager.GetAllPlayerDataIncludingHost(); - ILocalPlayer hostPlayer = Multiplayer.Session.LocalPlayer; - string resultPayload = WhoCommandHandler.BuildResultPayload(playerDatas, hostPlayer); - - INebulaPlayer recipient = Multiplayer.Session.Network.PlayerManager.GetPlayer(conn); - recipient.SendPacket(new ChatCommandWhoPacket(false, resultPayload)); - } - else + if (packet.IsRequest) { - if (packet.IsRequest) - { - Log.Warn("Request packet received for who response"); - } - ChatManager.Instance.SendChatMessage(packet.ResponsePayload, ChatMessageType.CommandOutputMessage); + Log.Warn("Request packet received for who response"); } + ChatManager.Instance.SendChatMessage(packet.ResponsePayload, ChatMessageType.CommandOutputMessage); } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Chat/NewChatMessageProcessor.cs b/NebulaNetwork/PacketProcessors/Chat/NewChatMessageProcessor.cs index 7300dbd3c..55ad954a7 100644 --- a/NebulaNetwork/PacketProcessors/Chat/NewChatMessageProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Chat/NewChatMessageProcessor.cs @@ -1,45 +1,45 @@ -using NebulaAPI; +#region + +using System; +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Players; using NebulaWorld; using NebulaWorld.MonoBehaviours.Local; -using System; +using NebulaWorld.MonoBehaviours.Local.Chat; -namespace NebulaNetwork.PacketProcessors.Players +#endregion + +namespace NebulaNetwork.PacketProcessors.Players; + +[RegisterPacketProcessor] +internal class NewChatMessageProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class NewChatMessageProcessor : PacketProcessor + public override void ProcessPacket(NewChatMessagePacket packet, NebulaConnection conn) { - - public NewChatMessageProcessor() + if (ChatManager.Instance == null) { + Log.Warn("Unable to process chat packet, chat window assets were not loaded properly"); + return; } - public override void ProcessPacket(NewChatMessagePacket packet, NebulaConnection conn) + if (IsHost) { - if (ChatManager.Instance == null) - { - Log.Warn($"Unable to process chat packet, chat window assets were not loaded properly"); - return; - } - - if (IsHost) - { - INebulaPlayer player = Multiplayer.Session.Network.PlayerManager?.GetPlayer(conn); - Multiplayer.Session.Network.PlayerManager?.SendPacketToOtherPlayers(packet, player); - } + INebulaPlayer player = Multiplayer.Session.Network.PlayerManager?.GetPlayer(conn); + Multiplayer.Session.Network.PlayerManager?.SendPacketToOtherPlayers(packet, player); + } - DateTime sentAt = packet.SentAt == 0 ? DateTime.Now : DateTime.FromBinary(packet.SentAt); - if (string.IsNullOrEmpty(packet.UserName)) - { - ChatManager.Instance.SendChatMessage($"[{sentAt:HH:mm}] {packet.MessageText}", packet.MessageType); - } - else - { - ChatManager.Instance.SendChatMessage($"[{sentAt:HH:mm}] [{packet.UserName}] : {packet.MessageText}", packet.MessageType); - } + var sentAt = packet.SentAt == 0 ? DateTime.Now : DateTime.FromBinary(packet.SentAt); + if (string.IsNullOrEmpty(packet.UserName)) + { + ChatManager.Instance.SendChatMessage($"[{sentAt:HH:mm}] {packet.MessageText}", packet.MessageType); + } + else + { + ChatManager.Instance.SendChatMessage($"[{sentAt:HH:mm}] [{packet.UserName}] : {packet.MessageText}", + packet.MessageType); } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Chat/RemoteServerCommmandProcessor.cs b/NebulaNetwork/PacketProcessors/Chat/RemoteServerCommmandProcessor.cs index da3d6436f..f612405f1 100644 --- a/NebulaNetwork/PacketProcessors/Chat/RemoteServerCommmandProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Chat/RemoteServerCommmandProcessor.cs @@ -1,4 +1,10 @@ -using NebulaAPI; +#region + +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using NebulaAPI; using NebulaModel; using NebulaModel.DataStructures; using NebulaModel.Logger; @@ -7,170 +13,164 @@ using NebulaModel.Packets.Players; using NebulaModel.Utils; using NebulaWorld; -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; +using NebulaWorld.Chat.Commands; +using NebulaWorld.GameStates; -namespace NebulaNetwork.PacketProcessors.Players +#endregion + +namespace NebulaNetwork.PacketProcessors.Players; + +[RegisterPacketProcessor] +internal class RemoteServerCommmandProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class RemoteServerCommmandProcessor : PacketProcessor + private const int SERVERSAVE_COOLDOWN = 60; + private const int SERVERLOGIN_COOLDOWN = 2; + private readonly HashSet allowedConnections = new(); + private DateTime LastLoginTime = DateTime.Now; + private DateTime LastSaveTime = DateTime.Now; + + public override void ProcessPacket(RemoteServerCommandPacket packet, NebulaConnection conn) { - DateTime LastSaveTime = DateTime.Now; - DateTime LastLoginTime = DateTime.Now; - const int SERVERSAVE_COOLDOWN = 60; - const int SERVERLOGIN_COOLDOWN = 2; - readonly HashSet allowedConnections = new(); + var respond = "Unknown command".Translate(); - public override void ProcessPacket(RemoteServerCommandPacket packet, NebulaConnection conn) + // Don't run remote save command if it is not available + if (!Config.Options.RemoteAccessEnabled || !Multiplayer.IsDedicated || !IsHost) { - string respond = "Unknown command".Translate(); + respond = "Remote server access is not enabled".Translate(); + conn.SendPacket(new NewChatMessagePacket(ChatMessageType.SystemWarnMessage, respond, DateTime.Now, "")); + return; + } - // Don't run remote save command if it is not available - if (!Config.Options.RemoteAccessEnabled || !Multiplayer.IsDedicated || !IsHost) + if (!allowedConnections.Contains(conn) && packet.Command != RemoteServerCommand.Login) + { + if (!string.IsNullOrWhiteSpace(Config.Options.RemoteAccessPassword)) { - respond = "Remote server access is not enabled".Translate(); + respond = "You need to login first!".Translate(); conn.SendPacket(new NewChatMessagePacket(ChatMessageType.SystemWarnMessage, respond, DateTime.Now, "")); return; } + allowedConnections.Add(conn); + } - if (!allowedConnections.Contains(conn) && packet.Command != RemoteServerCommand.Login) - { - if (!string.IsNullOrWhiteSpace(Config.Options.RemoteAccessPassword)) + switch (packet.Command) + { + case RemoteServerCommand.Login: + respond = Login(conn, packet.Content); + break; + + case RemoteServerCommand.ServerList: + respond = List(packet.Content); + break; + + case RemoteServerCommand.ServerSave: + respond = Save(packet.Content); + break; + + case RemoteServerCommand.ServerLoad: + respond = Load(packet.Content); + if (respond == null) { - respond = "You need to login first!".Translate(); - conn.SendPacket(new NewChatMessagePacket(ChatMessageType.SystemWarnMessage, respond, DateTime.Now, "")); + // if load success, don't send packet because the connection is reset return; } - else - { - allowedConnections.Add(conn); - } - } + break; - switch (packet.Command) - { - case RemoteServerCommand.Login: - respond = Login(conn, packet.Content); - break; - - case RemoteServerCommand.ServerList: - respond = List(packet.Content); - break; - - case RemoteServerCommand.ServerSave: - respond = Save(packet.Content); - break; - - case RemoteServerCommand.ServerLoad: - respond = Load(packet.Content); - if (respond == null) - { - // if load success, don't send packet because the connection is reset - return; - } - break; - - case RemoteServerCommand.ServerInfo: - Info(conn, packet.Content == "full"); - return; - } - conn.SendPacket(new NewChatMessagePacket(ChatMessageType.SystemInfoMessage, respond, DateTime.Now, "")); + case RemoteServerCommand.ServerInfo: + Info(conn, packet.Content == "full"); + return; } + conn.SendPacket(new NewChatMessagePacket(ChatMessageType.SystemInfoMessage, respond, DateTime.Now, "")); + } - private string Login(NebulaConnection conn, string passwordHash) + private string Login(NebulaConnection conn, string passwordHash) + { + if (allowedConnections.Contains(conn)) { - if (allowedConnections.Contains(conn)) - { - return "You have already logged in".Translate(); - } - if (!string.IsNullOrWhiteSpace(Config.Options.RemoteAccessPassword)) - { - int cdtime = SERVERLOGIN_COOLDOWN - (int)(DateTime.Now - LastLoginTime).TotalSeconds; - if (cdtime > 0) - { - return string.Format("Cooldown: {0}s".Translate(), cdtime); - } - LastLoginTime = DateTime.Now; - IPlayerData playerData = Multiplayer.Session.Network.PlayerManager.GetPlayer(conn)?.Data; - string salt = playerData != null ? playerData.Username + playerData.PlayerId : ""; - string hash = CryptoUtils.Hash(Config.Options.RemoteAccessPassword + salt); - if (hash != passwordHash) - { - return "Password incorrect!".Translate(); - } - } - allowedConnections.Add(conn); - return "Login success!".Translate(); + return "You have already logged in".Translate(); } - - private static string List(string numString) + if (!string.IsNullOrWhiteSpace(Config.Options.RemoteAccessPassword)) { - int num = 5; - if (int.TryParse(numString, out int result)) + var cdtime = SERVERLOGIN_COOLDOWN - (int)(DateTime.Now - LastLoginTime).TotalSeconds; + if (cdtime > 0) { - num = result; + return string.Format("Cooldown: {0}s".Translate(), cdtime); } - // From UILoadGameWindow.RefreshList() - string[] files = Directory.GetFiles(GameConfig.gameSaveFolder, "*" + GameSave.saveExt, SearchOption.TopDirectoryOnly); - string[] dates = new string[files.Length]; - string[] names = new string[files.Length]; - num = num < files.Length ? num : files.Length; - for (int i = 0; i < files.Length; i++) + LastLoginTime = DateTime.Now; + IPlayerData playerData = Multiplayer.Session.Network.PlayerManager.GetPlayer(conn)?.Data; + var salt = playerData != null ? playerData.Username + playerData.PlayerId : ""; + var hash = CryptoUtils.Hash(Config.Options.RemoteAccessPassword + salt); + if (hash != passwordHash) { - FileInfo fileInfo = new(files[i]); - dates[i] = string.Format("{0:yyyy-MM-dd HH:mm}", fileInfo.LastWriteTime); - names[i] = fileInfo.Name.Substring(0, fileInfo.Name.Length - GameSave.saveExt.Length); + return "Password incorrect!".Translate(); } - - Array.Sort(dates, names); - StringBuilder sb = new(); - sb.AppendLine(string.Format("Save list on server: ({0}/{1})".Translate(), num, files.Length)); - for (int i = files.Length - num; i < files.Length; i++) - { - sb.AppendLine($"{dates[i]} {names[i]}"); - } - return sb.ToString(); } + allowedConnections.Add(conn); + return "Login success!".Translate(); + } - private string Save(string saveName) + private static string List(string numString) + { + var num = 5; + if (int.TryParse(numString, out var result)) { - int countDown = SERVERSAVE_COOLDOWN - (int)(DateTime.Now - LastSaveTime).TotalSeconds; - if (countDown <= 0) - { - // Save game and report result to the client - LastSaveTime = DateTime.Now; - saveName = string.IsNullOrEmpty(saveName) ? GameSave.LastExit : saveName; - return string.Format("Save {0} : {1}".Translate(), saveName, GameSave.SaveCurrentGame(saveName) ? "Success".Translate() : "Fail".Translate()); - } - else - { - return string.Format("Cooldown: {0}s".Translate(), countDown); - } + num = result; + } + // From UILoadGameWindow.RefreshList() + var files = Directory.GetFiles(GameConfig.gameSaveFolder, "*" + GameSave.saveExt, SearchOption.TopDirectoryOnly); + var dates = new string[files.Length]; + var names = new string[files.Length]; + num = num < files.Length ? num : files.Length; + for (var i = 0; i < files.Length; i++) + { + FileInfo fileInfo = new(files[i]); + dates[i] = string.Format("{0:yyyy-MM-dd HH:mm}", fileInfo.LastWriteTime); + names[i] = fileInfo.Name.Substring(0, fileInfo.Name.Length - GameSave.saveExt.Length); } - private static string Load(string saveName) + Array.Sort(dates, names); + StringBuilder sb = new(); + sb.AppendLine(string.Format("Save list on server: ({0}/{1})".Translate(), num, files.Length)); + for (var i = files.Length - num; i < files.Length; i++) { - if (!GameSave.SaveExist(saveName)) - { - return string.Format("{0} doesn't exist".Translate(), saveName); - } + sb.AppendLine($"{dates[i]} {names[i]}"); + } + return sb.ToString(); + } - Log.Info($"Received command to load {saveName}"); - NebulaWorld.GameStates.GameStatesManager.ImportedSaveName = saveName; - UIRoot.instance.uiGame.escMenu.OnButton5Click(); - return null; + private string Save(string saveName) + { + var countDown = SERVERSAVE_COOLDOWN - (int)(DateTime.Now - LastSaveTime).TotalSeconds; + if (countDown <= 0) + { + // Save game and report result to the client + LastSaveTime = DateTime.Now; + saveName = string.IsNullOrEmpty(saveName) ? GameSave.LastExit : saveName; + return string.Format("Save {0} : {1}".Translate(), saveName, + GameSave.SaveCurrentGame(saveName) ? "Success".Translate() : "Fail".Translate()); } + return string.Format("Cooldown: {0}s".Translate(), countDown); + } - private static void Info(NebulaConnection conn, bool full) + private static string Load(string saveName) + { + if (!GameSave.SaveExist(saveName)) { - IServer server = Multiplayer.Session.Network as IServer; - IPUtils.GetIPInfo(server.Port).ContinueWith(async (ipInfo) => - { - string respond = NebulaWorld.Chat.Commands.InfoCommandHandler.GetServerInfoText(server, await ipInfo, full); - conn.SendPacket(new NewChatMessagePacket(ChatMessageType.SystemInfoMessage, respond, DateTime.Now, "")); - }); + return string.Format("{0} doesn't exist".Translate(), saveName); } + + Log.Info($"Received command to load {saveName}"); + GameStatesManager.ImportedSaveName = saveName; + UIRoot.instance.uiGame.escMenu.OnButton5Click(); + return null; + } + + private static void Info(NebulaConnection conn, bool full) + { + var server = Multiplayer.Session.Network as IServer; + IPUtils.GetIPInfo(server.Port).ContinueWith(async ipInfo => + { + var respond = InfoCommandHandler.GetServerInfoText(server, await ipInfo, full); + conn.SendPacket(new NewChatMessagePacket(ChatMessageType.SystemInfoMessage, respond, DateTime.Now, "")); + }); } } diff --git a/NebulaNetwork/PacketProcessors/Factory/Assembler/AssemblerRecipeEventProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Assembler/AssemblerRecipeEventProcessor.cs index 8d144eff2..d107e1bcc 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Assembler/AssemblerRecipeEventProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Assembler/AssemblerRecipeEventProcessor.cs @@ -1,26 +1,31 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Assembler; -namespace NebulaNetwork.PacketProcessors.Factory.Assembler +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Assembler; + +[RegisterPacketProcessor] +internal class AssemblerRecipeEventProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class AssemblerRecipeEventProcessor : PacketProcessor + public override void ProcessPacket(AssemblerRecipeEventPacket packet, NebulaConnection conn) { - public override void ProcessPacket(AssemblerRecipeEventPacket packet, NebulaConnection conn) + var pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factorySystem?.assemblerPool; + if (pool != null && packet.AssemblerIndex != -1 && packet.AssemblerIndex < pool.Length && + pool[packet.AssemblerIndex].id != -1) { - AssemblerComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factorySystem?.assemblerPool; - if (pool != null && packet.AssemblerIndex != -1 && packet.AssemblerIndex < pool.Length && pool[packet.AssemblerIndex].id != -1) + if (packet.RecipeId == -1) + { + pool[packet.AssemblerIndex].forceAccMode = !pool[packet.AssemblerIndex].forceAccMode; + } + else { - if (packet.RecipeId == -1) - { - pool[packet.AssemblerIndex].forceAccMode = !pool[packet.AssemblerIndex].forceAccMode; - } - else - { - pool[packet.AssemblerIndex].SetRecipe(packet.RecipeId, GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.entitySignPool); - } + pool[packet.AssemblerIndex].SetRecipe(packet.RecipeId, + GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.entitySignPool); } } } diff --git a/NebulaNetwork/PacketProcessors/Factory/Assembler/AssemblerUpdateProducesProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Assembler/AssemblerUpdateProducesProcessor.cs index 803ca9052..89d9cd9a4 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Assembler/AssemblerUpdateProducesProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Assembler/AssemblerUpdateProducesProcessor.cs @@ -1,20 +1,24 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Assembler; -namespace NebulaNetwork.PacketProcessors.Factory.Assembler +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Assembler; + +[RegisterPacketProcessor] +internal class AssemblerUpdateProducesProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class AssemblerUpdateProducesProcessor : PacketProcessor + public override void ProcessPacket(AssemblerUpdateProducesPacket packet, NebulaConnection conn) { - public override void ProcessPacket(AssemblerUpdateProducesPacket packet, NebulaConnection conn) + var pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factorySystem?.assemblerPool; + if (pool != null && packet.AssemblerIndex != -1 && packet.AssemblerIndex < pool.Length && + pool[packet.AssemblerIndex].id != -1) { - AssemblerComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factorySystem?.assemblerPool; - if (pool != null && packet.AssemblerIndex != -1 && packet.AssemblerIndex < pool.Length && pool[packet.AssemblerIndex].id != -1) - { - pool[packet.AssemblerIndex].produced[packet.ProducesIndex] = packet.ProducesValue; - } + pool[packet.AssemblerIndex].produced[packet.ProducesIndex] = packet.ProducesValue; } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Factory/Assembler/AssemblerUpdateStorageProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Assembler/AssemblerUpdateStorageProcessor.cs index 38672d393..fbad369b4 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Assembler/AssemblerUpdateStorageProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Assembler/AssemblerUpdateStorageProcessor.cs @@ -1,24 +1,28 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Assembler; -namespace NebulaNetwork.PacketProcessors.Factory.Assembler +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Assembler; + +[RegisterPacketProcessor] +internal class AssemblerUpdateStorageProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class AssemblerUpdateStorageProcessor : PacketProcessor + public override void ProcessPacket(AssemblerUpdateStoragePacket packet, NebulaConnection conn) { - public override void ProcessPacket(AssemblerUpdateStoragePacket packet, NebulaConnection conn) + var pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factorySystem?.assemblerPool; + if (pool != null && packet.AssemblerIndex != -1 && packet.AssemblerIndex < pool.Length && + pool[packet.AssemblerIndex].id != -1) { - AssemblerComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factorySystem?.assemblerPool; - if (pool != null && packet.AssemblerIndex != -1 && packet.AssemblerIndex < pool.Length && pool[packet.AssemblerIndex].id != -1) + for (var i = 0; i < packet.Served.Length; i++) { - for (int i = 0; i < packet.Served.Length; i++) - { - pool[packet.AssemblerIndex].served[i] = packet.Served[i]; - pool[packet.AssemblerIndex].incServed[i] = packet.IncServed[i]; - } + pool[packet.AssemblerIndex].served[i] = packet.Served[i]; + pool[packet.AssemblerIndex].incServed[i] = packet.IncServed[i]; } } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Factory/Belt/BeltReverseProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Belt/BeltReverseProcessor.cs index 66ed443bc..a9aaf065f 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Belt/BeltReverseProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Belt/BeltReverseProcessor.cs @@ -1,40 +1,45 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Packets.Factory.Belt; -namespace NebulaNetwork.PacketProcessors.Factory.Belt +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Belt; + +[RegisterPacketProcessor] +internal class BeltReverseProcessor : BasePacketProcessor { - [RegisterPacketProcessor] - internal class BeltReverseProcessor : BasePacketProcessor + public override void ProcessPacket(BeltReversePacket packet, INebulaConnection conn) { - public override void ProcessPacket(BeltReversePacket packet, INebulaConnection conn) + var factory = GameMain.galaxy.PlanetById(packet.PlanetId).factory; + if (factory == null) { - PlanetFactory factory = GameMain.galaxy.PlanetById(packet.PlanetId).factory; - if (factory == null) - return; + return; + } - using (NebulaModAPI.MultiplayerSession.Factories.IsIncomingRequest.On()) + using (NebulaModAPI.MultiplayerSession.Factories.IsIncomingRequest.On()) + { + NebulaModAPI.MultiplayerSession.Factories.EventFactory = factory; + NebulaModAPI.MultiplayerSession.Factories.TargetPlanet = packet.PlanetId; + if (NebulaModAPI.MultiplayerSession.LocalPlayer.IsHost) { - NebulaModAPI.MultiplayerSession.Factories.EventFactory = factory; - NebulaModAPI.MultiplayerSession.Factories.TargetPlanet = packet.PlanetId; - if (NebulaModAPI.MultiplayerSession.LocalPlayer.IsHost) - { - // Load planet model - NebulaModAPI.MultiplayerSession.Factories.AddPlanetTimer(packet.PlanetId); - } + // Load planet model + NebulaModAPI.MultiplayerSession.Factories.AddPlanetTimer(packet.PlanetId); + } - UIBeltWindow beltWindow = UIRoot.instance.uiGame.beltWindow; - beltWindow._Close(); // close the window first to avoid changing unwant variable when setting beltId - PlanetFactory tmpFactory = beltWindow.factory; - int tmpBeltId = beltWindow.beltId; - beltWindow.factory = factory; - beltWindow.beltId = packet.BeltId; - beltWindow.OnReverseButtonClick(0); - beltWindow.factory = tmpFactory; - beltWindow.beltId = tmpBeltId; + var beltWindow = UIRoot.instance.uiGame.beltWindow; + beltWindow._Close(); // close the window first to avoid changing unwant variable when setting beltId + var tmpFactory = beltWindow.factory; + var tmpBeltId = beltWindow.beltId; + beltWindow.factory = factory; + beltWindow.beltId = packet.BeltId; + beltWindow.OnReverseButtonClick(0); + beltWindow.factory = tmpFactory; + beltWindow.beltId = tmpBeltId; - NebulaModAPI.MultiplayerSession.Factories.EventFactory = null; - NebulaModAPI.MultiplayerSession.Factories.TargetPlanet = NebulaModAPI.PLANET_NONE; - } + NebulaModAPI.MultiplayerSession.Factories.EventFactory = null; + NebulaModAPI.MultiplayerSession.Factories.TargetPlanet = NebulaModAPI.PLANET_NONE; } } } diff --git a/NebulaNetwork/PacketProcessors/Factory/Belt/BeltSignalIconProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Belt/BeltSignalIconProcessor.cs index 8adba94bc..651258179 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Belt/BeltSignalIconProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Belt/BeltSignalIconProcessor.cs @@ -1,25 +1,28 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Belt; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Factory.Belt +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Belt; + +[RegisterPacketProcessor] +internal class BeltSignalIconProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class BeltSignalIconProcessor : PacketProcessor + public override void ProcessPacket(BeltSignalIconPacket packet, NebulaConnection conn) { - public override void ProcessPacket(BeltSignalIconPacket packet, NebulaConnection conn) + using (Multiplayer.Session.Factories.IsIncomingRequest.On()) { - using (Multiplayer.Session.Factories.IsIncomingRequest.On()) + var cargoTraffic = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.cargoTraffic; + if (cargoTraffic == null) { - CargoTraffic cargoTraffic = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.cargoTraffic; - if (cargoTraffic == null) - { - return; - } - cargoTraffic.SetBeltSignalIcon(packet.EntityId, packet.SignalId); + return; } + cargoTraffic.SetBeltSignalIcon(packet.EntityId, packet.SignalId); } } } diff --git a/NebulaNetwork/PacketProcessors/Factory/Belt/BeltSignalNumberProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Belt/BeltSignalNumberProcessor.cs index 55ca25855..1485920f3 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Belt/BeltSignalNumberProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Belt/BeltSignalNumberProcessor.cs @@ -1,25 +1,28 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Belt; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Factory.Belt +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Belt; + +[RegisterPacketProcessor] +internal class BeltSignalNumberProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class BeltSignalNumberProcessor : PacketProcessor + public override void ProcessPacket(BeltSignalNumberPacket packet, NebulaConnection conn) { - public override void ProcessPacket(BeltSignalNumberPacket packet, NebulaConnection conn) + using (Multiplayer.Session.Factories.IsIncomingRequest.On()) { - using (Multiplayer.Session.Factories.IsIncomingRequest.On()) + var cargoTraffic = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.cargoTraffic; + if (cargoTraffic == null) { - CargoTraffic cargoTraffic = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.cargoTraffic; - if (cargoTraffic == null) - { - return; - } - cargoTraffic.SetBeltSignalNumber(packet.EntityId, packet.Number); + return; } + cargoTraffic.SetBeltSignalNumber(packet.EntityId, packet.Number); } } } diff --git a/NebulaNetwork/PacketProcessors/Factory/Belt/BeltUpdatePickupItemsProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Belt/BeltUpdatePickupItemsProcessor.cs index 5c54176b0..f465287b0 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Belt/BeltUpdatePickupItemsProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Belt/BeltUpdatePickupItemsProcessor.cs @@ -1,50 +1,56 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Belt; -namespace NebulaNetwork.PacketProcessors.Factory.Belt +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Belt; + +[RegisterPacketProcessor] +internal class BeltUpdatePickupItemsProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class BeltUpdatePickupItemsProcessor : PacketProcessor + public override void ProcessPacket(BeltUpdatePickupItemsPacket packet, NebulaConnection conn) { - public override void ProcessPacket(BeltUpdatePickupItemsPacket packet, NebulaConnection conn) + var traffic = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.cargoTraffic; + if (traffic != null) { - CargoTraffic traffic = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.cargoTraffic; - if (traffic != null) + //Iterate though belt updates and remove target items + for (var i = 0; i < packet.BeltUpdates.Length; i++) { - //Iterate though belt updates and remove target items - for (int i = 0; i < packet.BeltUpdates.Length; i++) + if (packet.BeltUpdates[i].BeltId >= traffic.beltPool.Length) { - if (packet.BeltUpdates[i].BeltId >= traffic.beltPool.Length) - { - return; - } - BeltComponent beltComponent = traffic.beltPool[packet.BeltUpdates[i].BeltId]; - CargoPath cargoPath = traffic.GetCargoPath(beltComponent.segPathId); - int ItemId = packet.BeltUpdates[i].ItemId; - //Check if belt exists - if (cargoPath != null) + return; + } + var beltComponent = traffic.beltPool[packet.BeltUpdates[i].BeltId]; + var cargoPath = traffic.GetCargoPath(beltComponent.segPathId); + var ItemId = packet.BeltUpdates[i].ItemId; + //Check if belt exists + if (cargoPath != null) + { + // Search downstream for target item + for (var k = beltComponent.segIndex + beltComponent.segPivotOffset; + k <= beltComponent.segIndex + beltComponent.segLength - 1; + k++) { - // Search downstream for target item - for (int k = beltComponent.segIndex + beltComponent.segPivotOffset; k <= (beltComponent.segIndex + beltComponent.segLength - 1); k++) + if (cargoPath.TryPickItem(k - 4 - 1, 12, ItemId, out _, out _) != 0) { - if (cargoPath.TryPickItem(k - 4 - 1, 12, ItemId, out _, out _) != 0) - { - return; - } + return; } - // Search upstream for target item - for (int k = beltComponent.segIndex + beltComponent.segPivotOffset - 1; k >= beltComponent.segIndex; k--) + } + // Search upstream for target item + for (var k = beltComponent.segIndex + beltComponent.segPivotOffset - 1; k >= beltComponent.segIndex; k--) + { + if (cargoPath.TryPickItem(k - 4 - 1, 12, ItemId, out _, out _) != 0) { - if (cargoPath.TryPickItem(k - 4 - 1, 12, ItemId, out _, out _) != 0) - { - return; - } + return; } - Log.Warn($"BeltUpdatePickupItem: Cannot pick item{ItemId} on belt{packet.BeltUpdates[i].BeltId}, planet{packet.PlanetId}"); } + Log.Warn( + $"BeltUpdatePickupItem: Cannot pick item{ItemId} on belt{packet.BeltUpdates[i].BeltId}, planet{packet.PlanetId}"); } } } diff --git a/NebulaNetwork/PacketProcessors/Factory/Belt/BeltUpdatePutItemOnProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Belt/BeltUpdatePutItemOnProcessor.cs index bfb511661..c94878c41 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Belt/BeltUpdatePutItemOnProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Belt/BeltUpdatePutItemOnProcessor.cs @@ -1,21 +1,23 @@ -using NebulaAPI; -using NebulaModel.Logger; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Belt; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Factory.Belt +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Belt; + +[RegisterPacketProcessor] +internal class BeltUpdatePutItemOnProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class BeltUpdatePutItemOnProcessor : PacketProcessor + public override void ProcessPacket(BeltUpdatePutItemOnPacket packet, NebulaConnection conn) { - public override void ProcessPacket(BeltUpdatePutItemOnPacket packet, NebulaConnection conn) + if (!Multiplayer.Session.Belts.TryPutItemOnBelt(packet)) { - if (!Multiplayer.Session.Belts.TryPutItemOnBelt(packet)) - { - Multiplayer.Session.Belts.RegiserbeltPutdownPacket(packet); - } + Multiplayer.Session.Belts.RegiserbeltPutdownPacket(packet); } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Factory/Belt/ConnectToMonitorProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Belt/ConnectToMonitorProcessor.cs index aa7e8b351..d11f6b3e4 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Belt/ConnectToMonitorProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Belt/ConnectToMonitorProcessor.cs @@ -1,25 +1,28 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Belt; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Factory.Belt +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Belt; + +[RegisterPacketProcessor] +internal class ConnectToMonitorProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class ConnectToMonitorProcessor : PacketProcessor + public override void ProcessPacket(ConnectToMonitorPacket packet, NebulaConnection conn) { - public override void ProcessPacket(ConnectToMonitorPacket packet, NebulaConnection conn) + using (Multiplayer.Session.Factories.IsIncomingRequest.On()) { - using (Multiplayer.Session.Factories.IsIncomingRequest.On()) + var cargoTraffic = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.cargoTraffic; + if (cargoTraffic == null) { - CargoTraffic cargoTraffic = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.cargoTraffic; - if (cargoTraffic == null) - { - return; - } - cargoTraffic.ConnectToMonitor(packet.MonitorId, packet.BeltId, packet.Offset); + return; } + cargoTraffic.ConnectToMonitor(packet.MonitorId, packet.BeltId, packet.Offset); } } } diff --git a/NebulaNetwork/PacketProcessors/Factory/Belt/ConnectToSpraycoaterProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Belt/ConnectToSpraycoaterProcessor.cs index df2679be5..16133866f 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Belt/ConnectToSpraycoaterProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Belt/ConnectToSpraycoaterProcessor.cs @@ -1,25 +1,28 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Belt; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Factory.Belt +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Belt; + +[RegisterPacketProcessor] +internal class ConnectToSpraycoaterProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class ConnectToSpraycoaterProcessor : PacketProcessor + public override void ProcessPacket(ConnectToSpraycoaterPacket packet, NebulaConnection conn) { - public override void ProcessPacket(ConnectToSpraycoaterPacket packet, NebulaConnection conn) + using (Multiplayer.Session.Factories.IsIncomingRequest.On()) { - using (Multiplayer.Session.Factories.IsIncomingRequest.On()) + var cargoTraffic = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.cargoTraffic; + if (cargoTraffic == null) { - CargoTraffic cargoTraffic = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.cargoTraffic; - if (cargoTraffic == null) - { - return; - } - cargoTraffic.ConnectToSpraycoater(packet.SpraycoaterId, packet.CargoBeltId, packet.IncBeltId); + return; } + cargoTraffic.ConnectToSpraycoater(packet.SpraycoaterId, packet.CargoBeltId, packet.IncBeltId); } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Factory/Ejector/EjectorOrbitUpdateProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Ejector/EjectorOrbitUpdateProcessor.cs index fd03013f6..dc9fcfd32 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Ejector/EjectorOrbitUpdateProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Ejector/EjectorOrbitUpdateProcessor.cs @@ -1,20 +1,24 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Ejector; -namespace NebulaNetwork.PacketProcessors.Factory.Ejector +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Ejector; + +[RegisterPacketProcessor] +internal class EjectorOrbitUpdateProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class EjectorOrbitUpdateProcessor : PacketProcessor + public override void ProcessPacket(EjectorOrbitUpdatePacket packet, NebulaConnection conn) { - public override void ProcessPacket(EjectorOrbitUpdatePacket packet, NebulaConnection conn) + var pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factorySystem?.ejectorPool; + if (pool != null && packet.EjectorIndex != -1 && packet.EjectorIndex < pool.Length && + pool[packet.EjectorIndex].id != -1) { - EjectorComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factorySystem?.ejectorPool; - if (pool != null && packet.EjectorIndex != -1 && packet.EjectorIndex < pool.Length && pool[packet.EjectorIndex].id != -1) - { - pool[packet.EjectorIndex].SetOrbit(packet.NewOrbitIndex); - } + pool[packet.EjectorIndex].SetOrbit(packet.NewOrbitIndex); } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Factory/Ejector/EjectorStorageUpdateProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Ejector/EjectorStorageUpdateProcessor.cs index 1e700728b..496438c26 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Ejector/EjectorStorageUpdateProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Ejector/EjectorStorageUpdateProcessor.cs @@ -1,21 +1,25 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Ejector; -namespace NebulaNetwork.PacketProcessors.Factory.Ejector +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Ejector; + +[RegisterPacketProcessor] +internal class EjectorStorageUpdateProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class EjectorStorageUpdateProcessor : PacketProcessor + public override void ProcessPacket(EjectorStorageUpdatePacket packet, NebulaConnection conn) { - public override void ProcessPacket(EjectorStorageUpdatePacket packet, NebulaConnection conn) + var pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factorySystem?.ejectorPool; + if (pool != null && packet.EjectorIndex != -1 && packet.EjectorIndex < pool.Length && + pool[packet.EjectorIndex].id != -1) { - EjectorComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factorySystem?.ejectorPool; - if (pool != null && packet.EjectorIndex != -1 && packet.EjectorIndex < pool.Length && pool[packet.EjectorIndex].id != -1) - { - pool[packet.EjectorIndex].bulletCount = packet.ItemCount; - pool[packet.EjectorIndex].bulletInc = packet.ItemInc; - } + pool[packet.EjectorIndex].bulletCount = packet.ItemCount; + pool[packet.EjectorIndex].bulletInc = packet.ItemInc; } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Factory/Entity/BuildEntityRequestProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Entity/BuildEntityRequestProcessor.cs index 5927c4962..cf8bd7314 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Entity/BuildEntityRequestProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Entity/BuildEntityRequestProcessor.cs @@ -1,62 +1,71 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory; using NebulaWorld; +using NebulaWorld.Factory; +using NebulaWorld.Warning; + +#endregion -namespace NebulaNetwork.PacketProcessors.Factory.Entity +namespace NebulaNetwork.PacketProcessors.Factory.Entity; + +[RegisterPacketProcessor] +public class BuildEntityRequestProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class BuildEntityRequestProcessor : PacketProcessor + public override void ProcessPacket(BuildEntityRequest packet, NebulaConnection conn) { - public override void ProcessPacket(BuildEntityRequest packet, NebulaConnection conn) + if (IsHost && !Multiplayer.Session.Factories.ContainsPrebuildRequest(packet.PlanetId, packet.PrebuildId)) { - if (IsHost && !Multiplayer.Session.Factories.ContainsPrebuildRequest(packet.PlanetId, packet.PrebuildId)) - { - Log.Warn($"BuildEntityRequest received does not have a corresponding PrebuildRequest with the id {packet.PrebuildId} for the planet {packet.PlanetId}"); - return; - } + Log.Warn( + $"BuildEntityRequest received does not have a corresponding PrebuildRequest with the id {packet.PrebuildId} for the planet {packet.PlanetId}"); + return; + } - PlanetData planet = GameMain.galaxy.PlanetById(packet.PlanetId); + var planet = GameMain.galaxy.PlanetById(packet.PlanetId); - // We only execute the code if the client has loaded the factory at least once. - // Else it will get it once it goes to the planet for the first time. - if (planet.factory != null) + // We only execute the code if the client has loaded the factory at least once. + // Else it will get it once it goes to the planet for the first time. + if (planet.factory != null) + { + using (Multiplayer.Session.Factories.IsIncomingRequest.On()) { - using (Multiplayer.Session.Factories.IsIncomingRequest.On()) + Multiplayer.Session.Factories.EventFactory = planet.factory; + Multiplayer.Session.Factories.TargetPlanet = packet.PlanetId; + Multiplayer.Session.Factories.PacketAuthor = packet.AuthorId; + + Multiplayer.Session.Factories.AddPlanetTimer(packet.PlanetId); + + //Remove building from drone queue + GameMain.mainPlayer.mecha.droneLogic.serving.Remove(-packet.PrebuildId); + + // setting specifyPlanet here to avoid accessing a null object (see GPUInstancingManager activePlanet getter) + var pData = GameMain.gpuiManager.specifyPlanet; + + GameMain.gpuiManager.specifyPlanet = GameMain.galaxy.PlanetById(packet.PlanetId); + if (packet.EntityId != -1 && packet.EntityId != FactoryManager.GetNextEntityId(planet.factory)) { - Multiplayer.Session.Factories.EventFactory = planet.factory; - Multiplayer.Session.Factories.TargetPlanet = packet.PlanetId; - Multiplayer.Session.Factories.PacketAuthor = packet.AuthorId; - - Multiplayer.Session.Factories.AddPlanetTimer(packet.PlanetId); - - //Remove building from drone queue - GameMain.mainPlayer.mecha.droneLogic.serving.Remove(-packet.PrebuildId); - - // setting specifyPlanet here to avoid accessing a null object (see GPUInstancingManager activePlanet getter) - PlanetData pData = GameMain.gpuiManager.specifyPlanet; - - GameMain.gpuiManager.specifyPlanet = GameMain.galaxy.PlanetById(packet.PlanetId); - if (packet.EntityId != -1 && packet.EntityId != NebulaWorld.Factory.FactoryManager.GetNextEntityId(planet.factory)) - { - string warningText = string.Format("(Desync) EntityId mismatch {0} != {1} on planet {2}. Clients should reconnect!".Translate(), packet.EntityId, NebulaWorld.Factory.FactoryManager.GetNextEntityId(planet.factory), planet.displayName); - Log.WarnInform(warningText); - NebulaWorld.Warning.WarningManager.DisplayTemporaryWarning(warningText, 5000); - } - planet.factory.BuildFinally(GameMain.mainPlayer, packet.PrebuildId); - GameMain.gpuiManager.specifyPlanet = pData; - - if (IsClient) - { - Multiplayer.Session.Drones.RemoveBuildRequest(-packet.PrebuildId); - } - - Multiplayer.Session.Factories.EventFactory = null; - Multiplayer.Session.Factories.PacketAuthor = NebulaModAPI.AUTHOR_NONE; - Multiplayer.Session.Factories.TargetPlanet = NebulaModAPI.PLANET_NONE; + var warningText = + string.Format( + "(Desync) EntityId mismatch {0} != {1} on planet {2}. Clients should reconnect!".Translate(), + packet.EntityId, FactoryManager.GetNextEntityId(planet.factory), planet.displayName); + Log.WarnInform(warningText); + WarningManager.DisplayTemporaryWarning(warningText, 5000); } + planet.factory.BuildFinally(GameMain.mainPlayer, packet.PrebuildId); + GameMain.gpuiManager.specifyPlanet = pData; + + if (IsClient) + { + Multiplayer.Session.Drones.RemoveBuildRequest(-packet.PrebuildId); + } + + Multiplayer.Session.Factories.EventFactory = null; + Multiplayer.Session.Factories.PacketAuthor = NebulaModAPI.AUTHOR_NONE; + Multiplayer.Session.Factories.TargetPlanet = NebulaModAPI.PLANET_NONE; } } } diff --git a/NebulaNetwork/PacketProcessors/Factory/Entity/CreatePrebuildsRequestProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Entity/CreatePrebuildsRequestProcessor.cs index 896f87e2b..066362941 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Entity/CreatePrebuildsRequestProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Entity/CreatePrebuildsRequestProcessor.cs @@ -1,25 +1,28 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Factory.Entity +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Entity; + +[RegisterPacketProcessor] +internal class CreatePrebuildsRequestProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class CreatePrebuildsRequestProcessor : PacketProcessor + public override void ProcessPacket(CreatePrebuildsRequest packet, NebulaConnection conn) { - public override void ProcessPacket(CreatePrebuildsRequest packet, NebulaConnection conn) + using (Multiplayer.Session.Factories.IsIncomingRequest.On()) { - using (Multiplayer.Session.Factories.IsIncomingRequest.On()) - { - // setting specifyPlanet here to avoid accessing a null object (see GPUInstancingManager activePlanet getter) - PlanetData pData = GameMain.gpuiManager.specifyPlanet; + // setting specifyPlanet here to avoid accessing a null object (see GPUInstancingManager activePlanet getter) + var pData = GameMain.gpuiManager.specifyPlanet; - GameMain.gpuiManager.specifyPlanet = GameMain.galaxy.PlanetById(packet.PlanetId); - Multiplayer.Session.BuildTools.CreatePrebuildsRequest(packet); - GameMain.gpuiManager.specifyPlanet = pData; - } + GameMain.gpuiManager.specifyPlanet = GameMain.galaxy.PlanetById(packet.PlanetId); + Multiplayer.Session.BuildTools.CreatePrebuildsRequest(packet); + GameMain.gpuiManager.specifyPlanet = pData; } } } diff --git a/NebulaNetwork/PacketProcessors/Factory/Entity/DestructEntityRequestProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Entity/DestructEntityRequestProcessor.cs index 9a446f653..c706f4ab8 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Entity/DestructEntityRequestProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Entity/DestructEntityRequestProcessor.cs @@ -1,48 +1,51 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Factory.Entity +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Entity; + +[RegisterPacketProcessor] +public class DestructEntityRequestProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class DestructEntityRequestProcessor : PacketProcessor + public override void ProcessPacket(DestructEntityRequest packet, NebulaConnection conn) { - public override void ProcessPacket(DestructEntityRequest packet, NebulaConnection conn) + using (Multiplayer.Session.Factories.IsIncomingRequest.On()) { - using (Multiplayer.Session.Factories.IsIncomingRequest.On()) + var planet = GameMain.galaxy.PlanetById(packet.PlanetId); + var pab = GameMain.mainPlayer.controller != null ? GameMain.mainPlayer.controller.actionBuild : null; + + // We only execute the code if the client has loaded the factory at least once. + // Else they will get it once they go to the planet for the first time. + if (planet?.factory == null || pab == null) { - PlanetData planet = GameMain.galaxy.PlanetById(packet.PlanetId); - PlayerAction_Build pab = GameMain.mainPlayer.controller != null ? GameMain.mainPlayer.controller.actionBuild : null; - - // We only execute the code if the client has loaded the factory at least once. - // Else they will get it once they go to the planet for the first time. - if (planet?.factory == null || pab == null) - { - return; - } - - Multiplayer.Session.Factories.TargetPlanet = packet.PlanetId; - Multiplayer.Session.Factories.PacketAuthor = packet.AuthorId; - PlanetFactory tmpFactory = pab.factory; - pab.factory = planet.factory; - pab.noneTool.factory = planet.factory; - - Multiplayer.Session.Factories.AddPlanetTimer(packet.PlanetId); - - // setting specifyPlanet here to avoid accessing a null object (see GPUInstancingManager activePlanet getter) - PlanetData pData = GameMain.gpuiManager.specifyPlanet; - - GameMain.gpuiManager.specifyPlanet = GameMain.galaxy.PlanetById(packet.PlanetId); - pab.DoDismantleObject(packet.ObjId); - GameMain.gpuiManager.specifyPlanet = pData; - - pab.factory = tmpFactory; - pab.noneTool.factory = tmpFactory; - Multiplayer.Session.Factories.TargetPlanet = NebulaModAPI.PLANET_NONE; - Multiplayer.Session.Factories.PacketAuthor = NebulaModAPI.AUTHOR_NONE; + return; } + + Multiplayer.Session.Factories.TargetPlanet = packet.PlanetId; + Multiplayer.Session.Factories.PacketAuthor = packet.AuthorId; + var tmpFactory = pab.factory; + pab.factory = planet.factory; + pab.noneTool.factory = planet.factory; + + Multiplayer.Session.Factories.AddPlanetTimer(packet.PlanetId); + + // setting specifyPlanet here to avoid accessing a null object (see GPUInstancingManager activePlanet getter) + var pData = GameMain.gpuiManager.specifyPlanet; + + GameMain.gpuiManager.specifyPlanet = GameMain.galaxy.PlanetById(packet.PlanetId); + pab.DoDismantleObject(packet.ObjId); + GameMain.gpuiManager.specifyPlanet = pData; + + pab.factory = tmpFactory; + pab.noneTool.factory = tmpFactory; + Multiplayer.Session.Factories.TargetPlanet = NebulaModAPI.PLANET_NONE; + Multiplayer.Session.Factories.PacketAuthor = NebulaModAPI.AUTHOR_NONE; } } } diff --git a/NebulaNetwork/PacketProcessors/Factory/Entity/EntityBoostSwitchProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Entity/EntityBoostSwitchProcessor.cs index 85fd1b63e..ac872bcd5 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Entity/EntityBoostSwitchProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Entity/EntityBoostSwitchProcessor.cs @@ -1,56 +1,59 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory; -namespace NebulaNetwork.PacketProcessors.Factory.Entity +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Entity; + +[RegisterPacketProcessor] +internal class EntityBoostSwitchProcessor : PacketProcessor { - [RegisterPacketProcessor] - class EntityBoostSwitchProcessor : PacketProcessor + public override void ProcessPacket(EntityBoostSwitchPacket packet, NebulaConnection conn) { - public override void ProcessPacket(EntityBoostSwitchPacket packet, NebulaConnection conn) + var factory = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory; + if (factory == null) { - PlanetFactory factory = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory; - if (factory == null) - { - return; - } + return; + } - switch (packet.EntityType) - { - case EBoostEntityType.ArtificialStar: - if (packet.Id < factory.powerSystem.genCursor) + switch (packet.EntityType) + { + case EBoostEntityType.ArtificialStar: + if (packet.Id < factory.powerSystem.genCursor) + { + factory.powerSystem.genPool[packet.Id].SetBoost(packet.Enable); + if (UIRoot.instance.uiGame.generatorWindow.generatorId == packet.Id) { - factory.powerSystem.genPool[packet.Id].SetBoost(packet.Enable); - if (UIRoot.instance.uiGame.generatorWindow.generatorId == packet.Id) - { - UIRoot.instance.uiGame.generatorWindow.boostSwitch.SetToggleNoEvent(packet.Enable); - } + UIRoot.instance.uiGame.generatorWindow.boostSwitch.SetToggleNoEvent(packet.Enable); } - break; + } + break; - case EBoostEntityType.Ejector: - if (packet.Id < factory.factorySystem.ejectorCursor) + case EBoostEntityType.Ejector: + if (packet.Id < factory.factorySystem.ejectorCursor) + { + factory.factorySystem.ejectorPool[packet.Id].SetBoost(packet.Enable); + if (UIRoot.instance.uiGame.ejectorWindow.ejectorId == packet.Id) { - factory.factorySystem.ejectorPool[packet.Id].SetBoost(packet.Enable); - if (UIRoot.instance.uiGame.ejectorWindow.ejectorId == packet.Id) - { - UIRoot.instance.uiGame.ejectorWindow.boostSwitch.SetToggleNoEvent(packet.Enable); - } + UIRoot.instance.uiGame.ejectorWindow.boostSwitch.SetToggleNoEvent(packet.Enable); } - break; + } + break; - case EBoostEntityType.Silo: - if (packet.Id < factory.factorySystem.siloCursor) + case EBoostEntityType.Silo: + if (packet.Id < factory.factorySystem.siloCursor) + { + factory.factorySystem.siloPool[packet.Id].SetBoost(packet.Enable); + if (UIRoot.instance.uiGame.siloWindow.siloId == packet.Id) { - factory.factorySystem.siloPool[packet.Id].SetBoost(packet.Enable); - if (UIRoot.instance.uiGame.siloWindow.siloId == packet.Id) - { - UIRoot.instance.uiGame.siloWindow.boostSwitch.SetToggleNoEvent(packet.Enable); - } + UIRoot.instance.uiGame.siloWindow.boostSwitch.SetToggleNoEvent(packet.Enable); } - break; - } + } + break; } } } diff --git a/NebulaNetwork/PacketProcessors/Factory/Entity/EntityWarningSwitchProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Entity/EntityWarningSwitchProcessor.cs index d2e95be0b..0102ac99a 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Entity/EntityWarningSwitchProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Entity/EntityWarningSwitchProcessor.cs @@ -1,37 +1,40 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory; -namespace NebulaNetwork.PacketProcessors.Factory.Entity +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Entity; + +[RegisterPacketProcessor] +internal class EntityWarningSwitchProcessor : PacketProcessor { - [RegisterPacketProcessor] - class EntityWarningSwitchProcessor : PacketProcessor + public override void ProcessPacket(EntityWarningSwitchPacket packet, NebulaConnection conn) { - public override void ProcessPacket(EntityWarningSwitchPacket packet, NebulaConnection conn) + var factory = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory; + var pool = factory?.entityPool; + if (pool != null && packet.EntityId > 0 && packet.EntityId < pool.Length && pool[packet.EntityId].id == packet.EntityId) { - PlanetFactory factory = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory; - EntityData[] pool = factory?.entityPool; - if (pool != null && packet.EntityId > 0 && packet.EntityId < pool.Length && pool[packet.EntityId].id == packet.EntityId) + if (IsHost) { - if (IsHost) + if (packet.Enable && pool[packet.EntityId].warningId == 0) { - if (packet.Enable && pool[packet.EntityId].warningId == 0) - { - GameMain.data.warningSystem.NewWarningData(factory.index, packet.EntityId, 0); - } - else if (!packet.Enable) - { - GameMain.data.warningSystem.RemoveWarningData(pool[packet.EntityId].warningId); - pool[packet.EntityId].warningId = 0; - } + GameMain.data.warningSystem.NewWarningData(factory.index, packet.EntityId, 0); } - else + else if (!packet.Enable) { - //Use dummy warningId on client side - pool[packet.EntityId].warningId = packet.Enable ? 1 : 0; + GameMain.data.warningSystem.RemoveWarningData(pool[packet.EntityId].warningId); + pool[packet.EntityId].warningId = 0; } } + else + { + //Use dummy warningId on client side + pool[packet.EntityId].warningId = packet.Enable ? 1 : 0; + } } } } diff --git a/NebulaNetwork/PacketProcessors/Factory/Entity/PasteBuildingSettingUpdateProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Entity/PasteBuildingSettingUpdateProcessor.cs index c67b80436..b842c1a37 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Entity/PasteBuildingSettingUpdateProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Entity/PasteBuildingSettingUpdateProcessor.cs @@ -1,28 +1,32 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Factory.Entity +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Entity; + +// Processes pasting settings (e.g. item to make in an assembler) onto buildings events +[RegisterPacketProcessor] +internal class PasteBuildingSettingUpdateProcessor : PacketProcessor { - // Processes pasting settings (e.g. item to make in an assembler) onto buildings events - [RegisterPacketProcessor] - internal class PasteBuildingSettingUpdateProcessor : PacketProcessor + public override void ProcessPacket(PasteBuildingSettingUpdate packet, NebulaConnection conn) { - public override void ProcessPacket(PasteBuildingSettingUpdate packet, NebulaConnection conn) + if (GameMain.galaxy.PlanetById(packet.PlanetId)?.factory != null) { - if (GameMain.galaxy.PlanetById(packet.PlanetId)?.factory != null) + var backup = BuildingParameters.clipboard; + BuildingParameters.clipboard = packet.GetBuildingSettings(); + using (Multiplayer.Session.Factories.IsIncomingRequest.On()) { - BuildingParameters backup = BuildingParameters.clipboard; - BuildingParameters.clipboard = packet.GetBuildingSettings(); - using (Multiplayer.Session.Factories.IsIncomingRequest.On()) - { - // skip audio and realtimetip update - BuildingParameters.clipboard.PasteToFactoryObject(packet.ObjectId, GameMain.galaxy.PlanetById(packet.PlanetId).factory); - } - BuildingParameters.clipboard = backup; + // skip audio and realtimetip update + BuildingParameters.clipboard.PasteToFactoryObject(packet.ObjectId, + GameMain.galaxy.PlanetById(packet.PlanetId).factory); } + BuildingParameters.clipboard = backup; } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Factory/Entity/UpgradeEntityRequestProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Entity/UpgradeEntityRequestProcessor.cs index d21e0e705..88ca74576 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Entity/UpgradeEntityRequestProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Entity/UpgradeEntityRequestProcessor.cs @@ -1,45 +1,46 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory; using NebulaWorld; -using UnityEngine; -using NebulaModel.Logger; -namespace NebulaNetwork.PacketProcessors.Factory.Entity +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Entity; + +[RegisterPacketProcessor] +public class UpgradeEntityRequestProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class UpgradeEntityRequestProcessor : PacketProcessor + public override void ProcessPacket(UpgradeEntityRequest packet, NebulaConnection conn) { - public override void ProcessPacket(UpgradeEntityRequest packet, NebulaConnection conn) + using (Multiplayer.Session.Factories.IsIncomingRequest.On()) { - using (Multiplayer.Session.Factories.IsIncomingRequest.On()) - { - PlanetData planet = GameMain.galaxy.PlanetById(packet.PlanetId); + var planet = GameMain.galaxy.PlanetById(packet.PlanetId); - // We only execute the code if the client has loaded the factory at least once. - // Else they will get it once they go to the planet for the first time. - if (planet?.factory == null) - { - return; - } + // We only execute the code if the client has loaded the factory at least once. + // Else they will get it once they go to the planet for the first time. + if (planet?.factory == null) + { + return; + } - Multiplayer.Session.Factories.TargetPlanet = packet.PlanetId; - Multiplayer.Session.Factories.PacketAuthor = packet.AuthorId; + Multiplayer.Session.Factories.TargetPlanet = packet.PlanetId; + Multiplayer.Session.Factories.PacketAuthor = packet.AuthorId; - Multiplayer.Session.Factories.AddPlanetTimer(packet.PlanetId); - ItemProto itemProto = LDB.items.Select(packet.UpgradeProtoId); + Multiplayer.Session.Factories.AddPlanetTimer(packet.PlanetId); + var itemProto = LDB.items.Select(packet.UpgradeProtoId); - // setting specifyPlanet here to avoid accessing a null object (see GPUInstancingManager activePlanet getter) - PlanetData pData = GameMain.gpuiManager.specifyPlanet; + // setting specifyPlanet here to avoid accessing a null object (see GPUInstancingManager activePlanet getter) + var pData = GameMain.gpuiManager.specifyPlanet; - GameMain.gpuiManager.specifyPlanet = planet; - planet.factory.UpgradeFinally(GameMain.mainPlayer, packet.ObjId, itemProto); - GameMain.gpuiManager.specifyPlanet = pData; + GameMain.gpuiManager.specifyPlanet = planet; + planet.factory.UpgradeFinally(GameMain.mainPlayer, packet.ObjId, itemProto); + GameMain.gpuiManager.specifyPlanet = pData; - Multiplayer.Session.Factories.TargetPlanet = NebulaModAPI.PLANET_NONE; - Multiplayer.Session.Factories.PacketAuthor = NebulaModAPI.AUTHOR_NONE; - } + Multiplayer.Session.Factories.TargetPlanet = NebulaModAPI.PLANET_NONE; + Multiplayer.Session.Factories.PacketAuthor = NebulaModAPI.AUTHOR_NONE; } } } diff --git a/NebulaNetwork/PacketProcessors/Factory/Foundation/FoundationBuildUpdateProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Foundation/FoundationBuildUpdateProcessor.cs index f081bc0f9..265e718a9 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Foundation/FoundationBuildUpdateProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Foundation/FoundationBuildUpdateProcessor.cs @@ -1,70 +1,75 @@ -using NebulaAPI; +#region + +using System; +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Foundation; using NebulaWorld; -using System; using UnityEngine; -namespace NebulaNetwork.PacketProcessors.Factory.Foundation +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Foundation; + +[RegisterPacketProcessor] +internal class FoundationBuildUpdateProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class FoundationBuildUpdateProcessor : PacketProcessor - { - private Vector3[] reformPoints = new Vector3[100]; + private Vector3[] reformPoints = new Vector3[100]; - public override void ProcessPacket(FoundationBuildUpdatePacket packet, NebulaConnection conn) + public override void ProcessPacket(FoundationBuildUpdatePacket packet, NebulaConnection conn) + { + var planet = GameMain.galaxy.PlanetById(packet.PlanetId); + var factory = IsHost ? GameMain.data.GetOrCreateFactory(planet) : planet?.factory; + if (factory != null) { - PlanetData planet = GameMain.galaxy.PlanetById(packet.PlanetId); - PlanetFactory factory = IsHost ? GameMain.data.GetOrCreateFactory(planet) : planet?.factory; - if (factory != null) + // Increase reformPoints for mods that increase brush size over 10 + if (packet.ReformSize * packet.ReformSize > reformPoints.Length) { - // Increase reformPoints for mods that increase brush size over 10 - if (packet.ReformSize * packet.ReformSize > reformPoints.Length) - { - reformPoints = new Vector3[packet.ReformSize * packet.ReformSize]; - } - Array.Clear(reformPoints, 0, reformPoints.Length); + reformPoints = new Vector3[packet.ReformSize * packet.ReformSize]; + } + Array.Clear(reformPoints, 0, reformPoints.Length); - //Check if some mandatory variables are missing - if (factory.platformSystem.reformData == null) - { - factory.platformSystem.InitReformData(); - } + //Check if some mandatory variables are missing + if (factory.platformSystem.reformData == null) + { + factory.platformSystem.InitReformData(); + } - Multiplayer.Session.Factories.TargetPlanet = packet.PlanetId; - Multiplayer.Session.Factories.AddPlanetTimer(packet.PlanetId); - Multiplayer.Session.Factories.TargetPlanet = NebulaModAPI.PLANET_NONE; + Multiplayer.Session.Factories.TargetPlanet = packet.PlanetId; + Multiplayer.Session.Factories.AddPlanetTimer(packet.PlanetId); + Multiplayer.Session.Factories.TargetPlanet = NebulaModAPI.PLANET_NONE; - //Perform terrain operation - int reformPointsCount = factory.planet.aux.ReformSnap(packet.GroundTestPos.ToVector3(), packet.ReformSize, packet.ReformType, packet.ReformColor, reformPoints, packet.ReformIndices, factory.platformSystem, out Vector3 reformCenterPoint); - factory.ComputeFlattenTerrainReform(reformPoints, reformCenterPoint, packet.Radius, reformPointsCount, 3f, 1f); - using (Multiplayer.Session.Factories.IsIncomingRequest.On()) - { - factory.FlattenTerrainReform(reformCenterPoint, packet.Radius, packet.ReformSize, packet.VeinBuried, 3f); - } - int area = packet.ReformSize * packet.ReformSize; - for (int i = 0; i < area; i++) + //Perform terrain operation + var reformPointsCount = factory.planet.aux.ReformSnap(packet.GroundTestPos.ToVector3(), packet.ReformSize, + packet.ReformType, packet.ReformColor, reformPoints, packet.ReformIndices, factory.platformSystem, + out var reformCenterPoint); + factory.ComputeFlattenTerrainReform(reformPoints, reformCenterPoint, packet.Radius, reformPointsCount); + using (Multiplayer.Session.Factories.IsIncomingRequest.On()) + { + factory.FlattenTerrainReform(reformCenterPoint, packet.Radius, packet.ReformSize, packet.VeinBuried); + } + var area = packet.ReformSize * packet.ReformSize; + for (var i = 0; i < area; i++) + { + var num71 = packet.ReformIndices[i]; + var platformSystem = factory.platformSystem; + if (num71 >= 0) { - int num71 = packet.ReformIndices[i]; - PlatformSystem platformSystem = factory.platformSystem; - if (num71 >= 0) + var type = platformSystem.GetReformType(num71); + var color = platformSystem.GetReformColor(num71); + if (type != packet.ReformType || color != packet.ReformColor) { - int type = platformSystem.GetReformType(num71); - int color = platformSystem.GetReformColor(num71); - if (type != packet.ReformType || color != packet.ReformColor) - { - factory.platformSystem.SetReformType(num71, packet.ReformType); - factory.platformSystem.SetReformColor(num71, packet.ReformColor); - } + factory.platformSystem.SetReformType(num71, packet.ReformType); + factory.platformSystem.SetReformColor(num71, packet.ReformColor); } } } + } - if (IsHost) - { - Multiplayer.Session.Network.SendPacketToStar(packet, planet.star.id); - } + if (IsHost) + { + Multiplayer.Session.Network.SendPacketToStar(packet, planet.star.id); } } } diff --git a/NebulaNetwork/PacketProcessors/Factory/Foundation/PlanetReformProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Foundation/PlanetReformProcessor.cs index 2c505a35c..6465373ee 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Foundation/PlanetReformProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Foundation/PlanetReformProcessor.cs @@ -1,42 +1,45 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Foundation; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Factory.Foundation +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Foundation; + +[RegisterPacketProcessor] +internal class PlanetReformProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class PlanetReformProcessor : PacketProcessor + public override void ProcessPacket(PlanetReformPacket packet, NebulaConnection conn) { - public override void ProcessPacket(PlanetReformPacket packet, NebulaConnection conn) + using (Multiplayer.Session.Planets.IsIncomingRequest.On()) { - using (Multiplayer.Session.Planets.IsIncomingRequest.On()) + var planet = GameMain.galaxy.PlanetById(packet.PlanetId); + if (planet?.factory == null) { - PlanetData planet = GameMain.galaxy.PlanetById(packet.PlanetId); - if (planet?.factory == null) - { - return; - } - Multiplayer.Session.Factories.TargetPlanet = packet.PlanetId; - Multiplayer.Session.Factories.AddPlanetTimer(packet.PlanetId); - PlanetData pData = GameMain.gpuiManager.specifyPlanet; - GameMain.gpuiManager.specifyPlanet = planet; - - if (packet.IsReform) - { - // Reform whole planet - planet.factory.PlanetReformAll(packet.Type, packet.Color, packet.Bury); - } - else - { - // Revert whole planet - planet.factory.PlanetReformRevert(); - } + return; + } + Multiplayer.Session.Factories.TargetPlanet = packet.PlanetId; + Multiplayer.Session.Factories.AddPlanetTimer(packet.PlanetId); + var pData = GameMain.gpuiManager.specifyPlanet; + GameMain.gpuiManager.specifyPlanet = planet; - GameMain.gpuiManager.specifyPlanet = pData; - Multiplayer.Session.Factories.TargetPlanet = NebulaModAPI.PLANET_NONE; + if (packet.IsReform) + { + // Reform whole planet + planet.factory.PlanetReformAll(packet.Type, packet.Color, packet.Bury); + } + else + { + // Revert whole planet + planet.factory.PlanetReformRevert(); } + + GameMain.gpuiManager.specifyPlanet = pData; + Multiplayer.Session.Factories.TargetPlanet = NebulaModAPI.PLANET_NONE; } } } diff --git a/NebulaNetwork/PacketProcessors/Factory/Fractionator/FractionatorStorageUpdateProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Fractionator/FractionatorStorageUpdateProcessor.cs index dc4fc4a57..5de2b0a95 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Fractionator/FractionatorStorageUpdateProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Fractionator/FractionatorStorageUpdateProcessor.cs @@ -1,22 +1,26 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Fractionator; -namespace NebulaNetwork.PacketProcessors.Factory.Fractionator +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Fractionator; + +[RegisterPacketProcessor] +internal class FractionatorStorageUpdateProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class FractionatorStorageUpdateProcessor : PacketProcessor + public override void ProcessPacket(FractionatorStorageUpdatePacket packet, NebulaConnection conn) { - public override void ProcessPacket(FractionatorStorageUpdatePacket packet, NebulaConnection conn) + var pool = GameMain.galaxy.PlanetById(packet.PlanetId).factory?.factorySystem.fractionatorPool; + if (pool != null && packet.FractionatorId > 0 && packet.FractionatorId < pool.Length && + pool[packet.FractionatorId].id != -1) { - FractionatorComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId).factory?.factorySystem.fractionatorPool; - if (pool != null && packet.FractionatorId > 0 && packet.FractionatorId < pool.Length && pool[packet.FractionatorId].id != -1) - { - pool[packet.FractionatorId].productOutputCount = packet.ProductOutputCount; - pool[packet.FractionatorId].fluidOutputCount = packet.FluidOutputCount; - pool[packet.FractionatorId].fluidOutputInc = packet.FluidOutputInc; - } + pool[packet.FractionatorId].productOutputCount = packet.ProductOutputCount; + pool[packet.FractionatorId].fluidOutputCount = packet.FluidOutputCount; + pool[packet.FractionatorId].fluidOutputInc = packet.FluidOutputInc; } } } diff --git a/NebulaNetwork/PacketProcessors/Factory/Inserter/InserterFilterUpdateProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Inserter/InserterFilterUpdateProcessor.cs index c50c87eeb..f517ca512 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Inserter/InserterFilterUpdateProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Inserter/InserterFilterUpdateProcessor.cs @@ -1,23 +1,28 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Inserter; -namespace NebulaNetwork.PacketProcessors.Factory.Inserter +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Inserter; + +[RegisterPacketProcessor] +internal class InserterFilterUpdateProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class InserterFilterUpdateProcessor : PacketProcessor + public override void ProcessPacket(InserterFilterUpdatePacket packet, NebulaConnection conn) { - public override void ProcessPacket(InserterFilterUpdatePacket packet, NebulaConnection conn) + var pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factorySystem?.inserterPool; + if (pool != null && packet.InserterIndex != -1 && packet.InserterIndex < pool.Length && + pool[packet.InserterIndex].id != -1) { - InserterComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factorySystem?.inserterPool; - if (pool != null && packet.InserterIndex != -1 && packet.InserterIndex < pool.Length && pool[packet.InserterIndex].id != -1) - { - pool[packet.InserterIndex].filter = packet.ItemId; - int entityId = pool[packet.InserterIndex].entityId; - GameMain.galaxy.PlanetById(packet.PlanetId).factory.entitySignPool[entityId].iconId0 = (uint)packet.ItemId; - GameMain.galaxy.PlanetById(packet.PlanetId).factory.entitySignPool[entityId].iconType = ((packet.ItemId <= 0) ? 0U : 1U); - } + pool[packet.InserterIndex].filter = packet.ItemId; + var entityId = pool[packet.InserterIndex].entityId; + GameMain.galaxy.PlanetById(packet.PlanetId).factory.entitySignPool[entityId].iconId0 = (uint)packet.ItemId; + GameMain.galaxy.PlanetById(packet.PlanetId).factory.entitySignPool[entityId].iconType = + packet.ItemId <= 0 ? 0U : 1U; } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Factory/Inserter/InserterItemUpdatePacket.cs b/NebulaNetwork/PacketProcessors/Factory/Inserter/InserterItemUpdatePacket.cs index 50308f2c2..40ff10ef6 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Inserter/InserterItemUpdatePacket.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Inserter/InserterItemUpdatePacket.cs @@ -1,23 +1,27 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Inserter; -namespace NebulaNetwork.PacketProcessors.Factory.Inserter +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Inserter; + +[RegisterPacketProcessor] +internal class InserterItemUpdateProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class InserterItemUpdateProcessor : PacketProcessor + public override void ProcessPacket(InserterItemUpdatePacket packet, NebulaConnection conn) { - public override void ProcessPacket(InserterItemUpdatePacket packet, NebulaConnection conn) + var pool = GameMain.galaxy.PlanetById(packet.PlanetId).factory?.factorySystem.inserterPool; + if (pool != null && packet.InserterIndex != -1 && packet.InserterIndex < pool.Length && + pool[packet.InserterIndex].id != -1) { - InserterComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId).factory?.factorySystem.inserterPool; - if (pool != null && packet.InserterIndex != -1 && packet.InserterIndex < pool.Length && pool[packet.InserterIndex].id != -1) - { - pool[packet.InserterIndex].itemId = packet.ItemId; - pool[packet.InserterIndex].itemCount = packet.ItemCount; - pool[packet.InserterIndex].itemInc = packet.ItemInc; - pool[packet.InserterIndex].stackCount = packet.StackCount; - } + pool[packet.InserterIndex].itemId = packet.ItemId; + pool[packet.InserterIndex].itemCount = packet.ItemCount; + pool[packet.InserterIndex].itemInc = packet.ItemInc; + pool[packet.InserterIndex].stackCount = packet.StackCount; } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Factory/Inserter/InserterOffsetCorrectionProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Inserter/InserterOffsetCorrectionProcessor.cs index 770204aa8..69e026f36 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Inserter/InserterOffsetCorrectionProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Inserter/InserterOffsetCorrectionProcessor.cs @@ -1,20 +1,25 @@ -using NebulaAPI; +#region + +using NebulaAPI; +using NebulaModel.Logger; using NebulaModel.Packets.Factory.Inserter; -namespace NebulaNetwork.PacketProcessors.Factory.Inserter +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Inserter; + +[RegisterPacketProcessor] +internal class InserterOffsetCorrectionProcessor : BasePacketProcessor { - [RegisterPacketProcessor] - internal class InserterOffsetCorrectionProcessor : BasePacketProcessor + public override void ProcessPacket(InserterOffsetCorrectionPacket packet, INebulaConnection conn) { - public override void ProcessPacket(InserterOffsetCorrectionPacket packet, INebulaConnection conn) + var pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factorySystem?.inserterPool; + if (pool != null) { - InserterComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factorySystem?.inserterPool; - if (pool != null) - { - NebulaModel.Logger.Log.Warn($"{packet.PlanetId} Fix inserter{packet.InserterId} pickOffset->{packet.PickOffset} insertOffset->{packet.InsertOffset}"); - pool[packet.InserterId].pickOffset = packet.PickOffset; - pool[packet.InserterId].insertOffset = packet.InsertOffset; - } + Log.Warn( + $"{packet.PlanetId} Fix inserter{packet.InserterId} pickOffset->{packet.PickOffset} insertOffset->{packet.InsertOffset}"); + pool[packet.InserterId].pickOffset = packet.PickOffset; + pool[packet.InserterId].insertOffset = packet.InsertOffset; } } } diff --git a/NebulaNetwork/PacketProcessors/Factory/Inserter/NewSetInserterInsertTargetProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Inserter/NewSetInserterInsertTargetProcessor.cs index 1d7a74e3e..90d91c0fe 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Inserter/NewSetInserterInsertTargetProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Inserter/NewSetInserterInsertTargetProcessor.cs @@ -1,32 +1,35 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Inserter; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Factory.Inserter +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Inserter; + +[RegisterPacketProcessor] +internal class NewSetInserterInsertTargetProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class NewSetInserterInsertTargetProcessor : PacketProcessor + public override void ProcessPacket(NewSetInserterInsertTargetPacket packet, NebulaConnection conn) { - public override void ProcessPacket(NewSetInserterInsertTargetPacket packet, NebulaConnection conn) + var factory = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory; + if (factory != null) { - PlanetFactory factory = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory; - if (factory != null) - { - Multiplayer.Session.Factories.TargetPlanet = factory.planetId; - factory.WriteObjectConn(packet.ObjId, 0, true, packet.OtherObjId, -1); + Multiplayer.Session.Factories.TargetPlanet = factory.planetId; + factory.WriteObjectConn(packet.ObjId, 0, true, packet.OtherObjId, -1); - // setting specifyPlanet here to avoid accessing a null object (see GPUInstancingManager activePlanet getter) - PlanetData pData = GameMain.gpuiManager.specifyPlanet; + // setting specifyPlanet here to avoid accessing a null object (see GPUInstancingManager activePlanet getter) + var pData = GameMain.gpuiManager.specifyPlanet; - GameMain.gpuiManager.specifyPlanet = GameMain.galaxy.PlanetById(packet.PlanetId); - factory.factorySystem.SetInserterInsertTarget(packet.InserterId, packet.OtherObjId, packet.Offset); - GameMain.gpuiManager.specifyPlanet = pData; + GameMain.gpuiManager.specifyPlanet = GameMain.galaxy.PlanetById(packet.PlanetId); + factory.factorySystem.SetInserterInsertTarget(packet.InserterId, packet.OtherObjId, packet.Offset); + GameMain.gpuiManager.specifyPlanet = pData; - factory.factorySystem.inserterPool[packet.InserterId].pos2 = packet.PointPos.ToVector3(); - Multiplayer.Session.Factories.TargetPlanet = NebulaModAPI.PLANET_NONE; - } + factory.factorySystem.inserterPool[packet.InserterId].pos2 = packet.PointPos.ToVector3(); + Multiplayer.Session.Factories.TargetPlanet = NebulaModAPI.PLANET_NONE; } } } diff --git a/NebulaNetwork/PacketProcessors/Factory/Inserter/NewSetInserterPickTargetProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Inserter/NewSetInserterPickTargetProcessor.cs index e43192a80..dc00961e9 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Inserter/NewSetInserterPickTargetProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Inserter/NewSetInserterPickTargetProcessor.cs @@ -1,32 +1,35 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Inserter; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Factory.Inserter +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Inserter; + +[RegisterPacketProcessor] +internal class NewSetInserterPickTargetProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class NewSetInserterPickTargetProcessor : PacketProcessor + public override void ProcessPacket(NewSetInserterPickTargetPacket packet, NebulaConnection conn) { - public override void ProcessPacket(NewSetInserterPickTargetPacket packet, NebulaConnection conn) + var factory = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory; + if (factory != null) { - PlanetFactory factory = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory; - if (factory != null) - { - Multiplayer.Session.Factories.TargetPlanet = factory.planetId; - factory.WriteObjectConn(packet.ObjId, 1, false, packet.OtherObjId, -1); + Multiplayer.Session.Factories.TargetPlanet = factory.planetId; + factory.WriteObjectConn(packet.ObjId, 1, false, packet.OtherObjId, -1); - // setting specifyPlanet here to avoid accessing a null object (see GPUInstancingManager activePlanet getter) - PlanetData pData = GameMain.gpuiManager.specifyPlanet; + // setting specifyPlanet here to avoid accessing a null object (see GPUInstancingManager activePlanet getter) + var pData = GameMain.gpuiManager.specifyPlanet; - GameMain.gpuiManager.specifyPlanet = GameMain.galaxy.PlanetById(packet.PlanetId); - factory.factorySystem.SetInserterPickTarget(packet.InserterId, packet.OtherObjId, packet.Offset); - GameMain.gpuiManager.specifyPlanet = pData; + GameMain.gpuiManager.specifyPlanet = GameMain.galaxy.PlanetById(packet.PlanetId); + factory.factorySystem.SetInserterPickTarget(packet.InserterId, packet.OtherObjId, packet.Offset); + GameMain.gpuiManager.specifyPlanet = pData; - factory.entityPool[packet.ObjId].pos = packet.PointPos.ToVector3(); - Multiplayer.Session.Factories.TargetPlanet = NebulaModAPI.PLANET_NONE; - } + factory.entityPool[packet.ObjId].pos = packet.PointPos.ToVector3(); + Multiplayer.Session.Factories.TargetPlanet = NebulaModAPI.PLANET_NONE; } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Factory/Laboratory/LaboratoryUpdateCubesProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Laboratory/LaboratoryUpdateCubesProcessor.cs index 920ffcace..2f8b71f05 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Laboratory/LaboratoryUpdateCubesProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Laboratory/LaboratoryUpdateCubesProcessor.cs @@ -1,21 +1,24 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Laboratory; -namespace NebulaNetwork.PacketProcessors.Factory.Labratory +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Labratory; + +[RegisterPacketProcessor] +internal class LaboratoryUpdateCubesProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class LaboratoryUpdateCubesProcessor : PacketProcessor + public override void ProcessPacket(LaboratoryUpdateCubesPacket packet, NebulaConnection conn) { - public override void ProcessPacket(LaboratoryUpdateCubesPacket packet, NebulaConnection conn) + var pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factorySystem?.labPool; + if (pool != null && packet.LabIndex != -1 && packet.LabIndex < pool.Length && pool[packet.LabIndex].id != -1) { - LabComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factorySystem?.labPool; - if (pool != null && packet.LabIndex != -1 && packet.LabIndex < pool.Length && pool[packet.LabIndex].id != -1) - { - pool[packet.LabIndex].matrixServed[packet.Index] = packet.ItemCount; - pool[packet.LabIndex].matrixIncServed[packet.Index] = packet.ItemInc; - } + pool[packet.LabIndex].matrixServed[packet.Index] = packet.ItemCount; + pool[packet.LabIndex].matrixIncServed[packet.Index] = packet.ItemInc; } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Factory/Laboratory/LaboratoryUpdateEventProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Laboratory/LaboratoryUpdateEventProcessor.cs index 152902a53..5ac48b692 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Laboratory/LaboratoryUpdateEventProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Laboratory/LaboratoryUpdateEventProcessor.cs @@ -1,53 +1,57 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Laboratory; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Factory.Labratory +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Labratory; + +[RegisterPacketProcessor] +internal class LaboratoryUpdateEventProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class LaboratoryUpdateEventProcessor : PacketProcessor + public override void ProcessPacket(LaboratoryUpdateEventPacket packet, NebulaConnection conn) { - public override void ProcessPacket(LaboratoryUpdateEventPacket packet, NebulaConnection conn) + var factory = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory; + var pool = factory?.factorySystem?.labPool; + if (pool != null && packet.LabIndex != -1 && packet.LabIndex < pool.Length && pool[packet.LabIndex].id != -1) { - PlanetFactory factory = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory; - LabComponent[] pool = factory?.factorySystem?.labPool; - if (pool != null && packet.LabIndex != -1 && packet.LabIndex < pool.Length && pool[packet.LabIndex].id != -1) + using (Multiplayer.Session.Factories.IsIncomingRequest.On()) { - using (Multiplayer.Session.Factories.IsIncomingRequest.On()) + Multiplayer.Session.Factories.PacketAuthor = NebulaModAPI.AUTHOR_NONE; + if (packet.ProductId == -4) + { + pool[packet.LabIndex].forceAccMode = !pool[packet.LabIndex].forceAccMode; + } + else if (packet.ProductId == -3) + { + //Widthdraw produced cubes + pool[packet.LabIndex].produced[0] = 0; + } + else if (packet.ProductId == -2) + { + //Research recipe reseted + pool[packet.LabIndex].SetFunction(false, 0, 0, factory.entitySignPool); + } + else if (packet.ProductId == -1) + { + //Center chenged to research-mode + pool[packet.LabIndex].SetFunction(true, 0, GameMain.data.history.currentTech, factory.entitySignPool); + } + else { - Multiplayer.Session.Factories.PacketAuthor = NebulaModAPI.AUTHOR_NONE; - if (packet.ProductId == -4) - { - pool[packet.LabIndex].forceAccMode = !pool[packet.LabIndex].forceAccMode; - } - else if (packet.ProductId == -3) - { - //Widthdraw produced cubes - pool[packet.LabIndex].produced[0] = 0; - } - else if (packet.ProductId == -2) - { - //Research recipe reseted - pool[packet.LabIndex].SetFunction(false, 0, 0, factory.entitySignPool); - } - else if (packet.ProductId == -1) - { - //Center chenged to research-mode - pool[packet.LabIndex].SetFunction(true, 0, GameMain.data.history.currentTech, factory.entitySignPool); - } - else - { - //Cube Recipe changed - int[] matrixIds = LabComponent.matrixIds; - RecipeProto recipeProto = LDB.items.Select(matrixIds[packet.ProductId]).maincraft; - pool[packet.LabIndex].SetFunction(false, (recipeProto == null) ? 0 : recipeProto.ID, 0, factory.entitySignPool); - } - factory.factorySystem?.SyncLabFunctions(GameMain.mainPlayer, packet.LabIndex); - factory.factorySystem?.SyncLabForceAccMode(GameMain.mainPlayer, packet.LabIndex); + //Cube Recipe changed + var matrixIds = LabComponent.matrixIds; + var recipeProto = LDB.items.Select(matrixIds[packet.ProductId]).maincraft; + pool[packet.LabIndex] + .SetFunction(false, recipeProto == null ? 0 : recipeProto.ID, 0, factory.entitySignPool); } + factory.factorySystem?.SyncLabFunctions(GameMain.mainPlayer, packet.LabIndex); + factory.factorySystem?.SyncLabForceAccMode(GameMain.mainPlayer, packet.LabIndex); } } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Factory/Laboratory/LaboratoryUpdateStorageProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Laboratory/LaboratoryUpdateStorageProcessor.cs index cac1bb0df..ce2b07dc1 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Laboratory/LaboratoryUpdateStorageProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Laboratory/LaboratoryUpdateStorageProcessor.cs @@ -1,21 +1,24 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Laboratory; -namespace NebulaNetwork.PacketProcessors.Factory.Labratory +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Labratory; + +[RegisterPacketProcessor] +internal class LaboratoryUpdateStorageProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class LaboratoryUpdateStorageProcessor : PacketProcessor + public override void ProcessPacket(LaboratoryUpdateStoragePacket packet, NebulaConnection conn) { - public override void ProcessPacket(LaboratoryUpdateStoragePacket packet, NebulaConnection conn) + var pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factorySystem?.labPool; + if (pool != null && packet.LabIndex != -1 && packet.LabIndex < pool.Length && pool[packet.LabIndex].id != -1) { - LabComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factorySystem?.labPool; - if (pool != null && packet.LabIndex != -1 && packet.LabIndex < pool.Length && pool[packet.LabIndex].id != -1) - { - pool[packet.LabIndex].served[packet.Index] = packet.ItemCount; - pool[packet.LabIndex].incServed[packet.Index] = packet.ItemInc; - } + pool[packet.LabIndex].served[packet.Index] = packet.ItemCount; + pool[packet.LabIndex].incServed[packet.Index] = packet.ItemInc; } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Factory/Miner/MinerStoragePickupProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Miner/MinerStoragePickupProcessor.cs index d6a6d8b7b..7e7ffceb3 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Miner/MinerStoragePickupProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Miner/MinerStoragePickupProcessor.cs @@ -1,21 +1,24 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Miner; -namespace NebulaNetwork.PacketProcessors.Factory.Miner +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Miner; + +[RegisterPacketProcessor] +internal class MinerStoragePickupProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class MinerStoragePickupProcessor : PacketProcessor + public override void ProcessPacket(MinerStoragePickupPacket packet, NebulaConnection conn) { - public override void ProcessPacket(MinerStoragePickupPacket packet, NebulaConnection conn) + var pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factorySystem?.minerPool; + if (pool != null && packet.MinerIndex != -1 && packet.MinerIndex < pool.Length && pool[packet.MinerIndex].id != -1) { - MinerComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factorySystem?.minerPool; - if (pool != null && packet.MinerIndex != -1 && packet.MinerIndex < pool.Length && pool[packet.MinerIndex].id != -1) - { - pool[packet.MinerIndex].productCount = 0; - pool[packet.MinerIndex].productId = 0; - } + pool[packet.MinerIndex].productCount = 0; + pool[packet.MinerIndex].productId = 0; } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Factory/Monitor/MonitorSettingUpdateProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Monitor/MonitorSettingUpdateProcessor.cs index dbda8c372..8d1b51923 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Monitor/MonitorSettingUpdateProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Monitor/MonitorSettingUpdateProcessor.cs @@ -1,123 +1,122 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Monitor; using NebulaWorld; -using NebulaWorld.Warning; -using UnityEngine; -namespace NebulaNetwork.PacketProcessors.Factory.Monitor +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Monitor; + +[RegisterPacketProcessor] +internal class MonitorSettingUpdateProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class MonitorSettingUpdateProcessor : PacketProcessor + public override void ProcessPacket(MonitorSettingUpdatePacket packet, NebulaConnection conn) { - public override void ProcessPacket(MonitorSettingUpdatePacket packet, NebulaConnection conn) + var pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.cargoTraffic?.monitorPool; + if (pool != null && packet.MonitorId > 0 && packet.MonitorId < pool.Length && + pool[packet.MonitorId].id == packet.MonitorId) { - MonitorComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.cargoTraffic?.monitorPool; - if (pool != null && packet.MonitorId > 0 && packet.MonitorId < pool.Length && pool[packet.MonitorId].id == packet.MonitorId) + using (Multiplayer.Session.Warning.IsIncomingMonitorPacket.On()) { - using (Multiplayer.Session.Warning.IsIncomingMonitorPacket.On()) + switch (packet.Event) { - - switch (packet.Event) - { - case MonitorSettingEvent.SetPassColorId: - pool[packet.MonitorId].SetPassColorId((byte)packet.Parameter1); - break; + case MonitorSettingEvent.SetPassColorId: + pool[packet.MonitorId].SetPassColorId((byte)packet.Parameter1); + break; - case MonitorSettingEvent.SetFailColorId: - pool[packet.MonitorId].SetFailColorId((byte)packet.Parameter1); - break; + case MonitorSettingEvent.SetFailColorId: + pool[packet.MonitorId].SetFailColorId((byte)packet.Parameter1); + break; - case MonitorSettingEvent.SetPassOperator: - pool[packet.MonitorId].SetPassOperator((byte)packet.Parameter1); - break; + case MonitorSettingEvent.SetPassOperator: + pool[packet.MonitorId].SetPassOperator((byte)packet.Parameter1); + break; - case MonitorSettingEvent.SetMonitorMode: - pool[packet.MonitorId].SetMonitorMode((byte)packet.Parameter1); - break; + case MonitorSettingEvent.SetMonitorMode: + pool[packet.MonitorId].SetMonitorMode((byte)packet.Parameter1); + break; + + case MonitorSettingEvent.SetSystemWarningMode: + pool[packet.MonitorId].SetSystemWarningMode(packet.Parameter1); + break; + + case MonitorSettingEvent.SetSystemWarningSignalId: + pool[packet.MonitorId].SetSystemWarningSignalId(packet.Parameter1); + break; + + case MonitorSettingEvent.SetCargoFilter: + pool[packet.MonitorId].SetCargoFilter(packet.Parameter1); + break; + + case MonitorSettingEvent.SetTargetCargoBytes: + pool[packet.MonitorId].SetTargetCargoBytes(packet.Parameter1); + break; + + case MonitorSettingEvent.SetPeriodTickCount: + pool[packet.MonitorId].SetPeriodTickCount(packet.Parameter1); + break; + + case MonitorSettingEvent.SetTargetBelt: + pool[packet.MonitorId].SetTargetBelt(packet.Parameter1, packet.Parameter2); + break; + + case MonitorSettingEvent.SetSpawnOperator: + pool[packet.MonitorId].SetSpawnOperator((byte)packet.Parameter1); + break; + + default: + Log.Warn($"MonitorSettingUpdatePacket: Unkown MonitorSettingEvent {packet.Event}"); + break; + } - case MonitorSettingEvent.SetSystemWarningMode: - pool[packet.MonitorId].SetSystemWarningMode(packet.Parameter1); + //Update UI Window too if it is viewing the current monitor + var uIMonitor = UIRoot.instance.uiGame.monitorWindow; + if (uIMonitor.monitorId == packet.MonitorId && uIMonitor.factory != null && + uIMonitor.factory.planetId == packet.PlanetId) + { + switch (packet.Event) + { + case MonitorSettingEvent.SetMonitorMode: + if (packet.Parameter1 == 0) + { + uIMonitor.TryCloseSpeakerPanel(); + } + else + { + uIMonitor.TryOpenSpeakerPanel(); + } break; case MonitorSettingEvent.SetSystemWarningSignalId: - pool[packet.MonitorId].SetSystemWarningSignalId(packet.Parameter1); + var sprite = LDB.signals.IconSprite(packet.Parameter1); + uIMonitor.iconTagImage.sprite = sprite ?? uIMonitor.tagNotSelectedSprite; break; case MonitorSettingEvent.SetCargoFilter: - pool[packet.MonitorId].SetCargoFilter(packet.Parameter1); - break; - - case MonitorSettingEvent.SetTargetCargoBytes: - pool[packet.MonitorId].SetTargetCargoBytes(packet.Parameter1); + var sprite2 = LDB.items.Select(packet.Parameter1)?.iconSprite; + uIMonitor.cargoFilterImage.sprite = sprite2 ?? uIMonitor.cargoFilterNotSelectedSprite; break; case MonitorSettingEvent.SetPeriodTickCount: - pool[packet.MonitorId].SetPeriodTickCount(packet.Parameter1); - break; - - case MonitorSettingEvent.SetTargetBelt: - pool[packet.MonitorId].SetTargetBelt(packet.Parameter1, packet.Parameter2); + uIMonitor.updateTimestamp = 0L; break; case MonitorSettingEvent.SetSpawnOperator: - pool[packet.MonitorId].SetSpawnOperator((byte)packet.Parameter1); + uIMonitor.spawnToggle.isOn = packet.Parameter1 > 0; + uIMonitor.spawnSwitch.isOn = packet.Parameter1 == 1; break; - - default: - Log.Warn($"MonitorSettingUpdatePacket: Unkown MonitorSettingEvent {packet.Event}"); - break; - } - - //Update UI Window too if it is viewing the current monitor - UIMonitorWindow uIMonitor = UIRoot.instance.uiGame.monitorWindow; - if (uIMonitor.monitorId == packet.MonitorId && uIMonitor.factory != null && uIMonitor.factory.planetId == packet.PlanetId) - { - switch (packet.Event) - { - case MonitorSettingEvent.SetMonitorMode: - if (packet.Parameter1 == 0) - { - uIMonitor.TryCloseSpeakerPanel(); - } - else - { - uIMonitor.TryOpenSpeakerPanel(); - } - break; - - case MonitorSettingEvent.SetSystemWarningSignalId: - Sprite sprite = LDB.signals.IconSprite(packet.Parameter1); - uIMonitor.iconTagImage.sprite = sprite ?? uIMonitor.tagNotSelectedSprite; - break; - - case MonitorSettingEvent.SetCargoFilter: - Sprite sprite2 = LDB.items.Select(packet.Parameter1)?.iconSprite; - uIMonitor.cargoFilterImage.sprite = sprite2 ?? uIMonitor.cargoFilterNotSelectedSprite; - break; - - case MonitorSettingEvent.SetPeriodTickCount: - uIMonitor.updateTimestamp = 0L; - break; - - case MonitorSettingEvent.SetSpawnOperator: - uIMonitor.spawnToggle.isOn = packet.Parameter1 > 0; - uIMonitor.spawnSwitch.isOn = packet.Parameter1 == 1; - break; - - default: - break; - } - uIMonitor.RefreshMonitorWindow(); } + uIMonitor.RefreshMonitorWindow(); } } - else if (pool != null) - { - Log.Warn($"MonitorSettingUpdatePacket: Can't find monitor ({packet.PlanetId}, {packet.MonitorId})"); - } + } + else if (pool != null) + { + Log.Warn($"MonitorSettingUpdatePacket: Can't find monitor ({packet.PlanetId}, {packet.MonitorId})"); } } } diff --git a/NebulaNetwork/PacketProcessors/Factory/Monitor/SpeakerSettingUpdateProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Monitor/SpeakerSettingUpdateProcessor.cs index 55ec6ba6f..a385d5535 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Monitor/SpeakerSettingUpdateProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Monitor/SpeakerSettingUpdateProcessor.cs @@ -1,89 +1,91 @@ -using NebulaAPI; +#region + +using System; +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Monitor; using NebulaWorld; -using System; -namespace NebulaNetwork.PacketProcessors.Factory.Monitor +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Monitor; + +[RegisterPacketProcessor] +internal class SpeakerSettingUpdateProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class SpeakerSettingUpdateProcessor : PacketProcessor + public override void ProcessPacket(SpeakerSettingUpdatePacket packet, NebulaConnection conn) { - public override void ProcessPacket(SpeakerSettingUpdatePacket packet, NebulaConnection conn) + var pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.digitalSystem?.speakerPool; + if (pool != null && packet.SpeakerId > 0 && packet.SpeakerId < pool.Length && + pool[packet.SpeakerId].id == packet.SpeakerId) { - SpeakerComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.digitalSystem?.speakerPool; - if (pool != null && packet.SpeakerId > 0 && packet.SpeakerId < pool.Length && pool[packet.SpeakerId].id == packet.SpeakerId) + using (Multiplayer.Session.Warning.IsIncomingMonitorPacket.On()) { - using (Multiplayer.Session.Warning.IsIncomingMonitorPacket.On()) + switch (packet.Event) { + case SpeakerSettingEvent.SetTone: + pool[packet.SpeakerId].SetTone(packet.Parameter1); + break; - switch (packet.Event) - { - case SpeakerSettingEvent.SetTone: - pool[packet.SpeakerId].SetTone(packet.Parameter1); - break; + case SpeakerSettingEvent.SetVolume: + pool[packet.SpeakerId].SetVolume(packet.Parameter1); + break; - case SpeakerSettingEvent.SetVolume: - pool[packet.SpeakerId].SetVolume(packet.Parameter1); - break; + case SpeakerSettingEvent.SetPitch: + pool[packet.SpeakerId].SetPitch(packet.Parameter1); + break; - case SpeakerSettingEvent.SetPitch: - pool[packet.SpeakerId].SetPitch(packet.Parameter1); - break; + case SpeakerSettingEvent.SetLength: + var p0 = BitConverter.ToSingle(BitConverter.GetBytes(packet.Parameter1), 0); + pool[packet.SpeakerId].SetLength(p0); + break; - case SpeakerSettingEvent.SetLength: - float p0 = BitConverter.ToSingle(BitConverter.GetBytes(packet.Parameter1), 0); - pool[packet.SpeakerId].SetLength(p0); - break; + case SpeakerSettingEvent.SetRepeat: + pool[packet.SpeakerId].SetRepeat(packet.Parameter1 == 0 ? false : true); + break; + + case SpeakerSettingEvent.SetFalloffRadius: + var p1 = BitConverter.ToSingle(BitConverter.GetBytes(packet.Parameter1), 0); + var p2 = BitConverter.ToSingle(BitConverter.GetBytes(packet.Parameter2), 0); + pool[packet.SpeakerId].SetFalloffRadius(p1, p2); + break; + + default: + Log.Warn($"SpeakerSettingUpdatePacket: Unkown SpeakerSettingEvent {packet.Event}"); + break; + } + //Update UI Panel too if it is viewing the current speaker + var uISpeaker = UIRoot.instance.uiGame.monitorWindow.speakerPanel; + if (uISpeaker.speakerId == packet.SpeakerId && uISpeaker.factory != null && + uISpeaker.factory.planetId == packet.PlanetId) + { + switch (packet.Event) + { case SpeakerSettingEvent.SetRepeat: - pool[packet.SpeakerId].SetRepeat(packet.Parameter1 == 0 ? false : true); + case SpeakerSettingEvent.SetPitch: + case SpeakerSettingEvent.SetLength: + uISpeaker.valueChangeCountDown = 0.5f; break; case SpeakerSettingEvent.SetFalloffRadius: - float p1 = BitConverter.ToSingle(BitConverter.GetBytes(packet.Parameter1), 0); - float p2 = BitConverter.ToSingle(BitConverter.GetBytes(packet.Parameter2), 0); - pool[packet.SpeakerId].SetFalloffRadius(p1, p2); - break; - - default: - Log.Warn($"SpeakerSettingUpdatePacket: Unkown SpeakerSettingEvent {packet.Event}"); + if (uISpeaker.factory.entityPool != null) + { + var audioId = uISpeaker.factory.entityPool[pool[packet.SpeakerId].entityId].audioId; + uISpeaker.factory.planet.audio?.ChangeAudioDataFalloff(audioId, + pool[packet.SpeakerId].falloffRadius0, pool[packet.SpeakerId].falloffRadius1); + } break; } - - //Update UI Panel too if it is viewing the current speaker - UISpeakerPanel uISpeaker = UIRoot.instance.uiGame.monitorWindow.speakerPanel; - if (uISpeaker.speakerId == packet.SpeakerId && uISpeaker.factory != null && uISpeaker.factory.planetId == packet.PlanetId) - { - switch (packet.Event) - { - case SpeakerSettingEvent.SetRepeat: - case SpeakerSettingEvent.SetPitch: - case SpeakerSettingEvent.SetLength: - uISpeaker.valueChangeCountDown = 0.5f; - break; - - case SpeakerSettingEvent.SetFalloffRadius: - if (uISpeaker.factory.entityPool != null) - { - int audioId = uISpeaker.factory.entityPool[pool[packet.SpeakerId].entityId].audioId; - uISpeaker.factory.planet.audio?.ChangeAudioDataFalloff(audioId, pool[packet.SpeakerId].falloffRadius0, pool[packet.SpeakerId].falloffRadius1); - } - break; - - default: - break; - } - uISpeaker.RefreshSpeakerPanel(); - } + uISpeaker.RefreshSpeakerPanel(); } } - else if (pool != null) - { - Log.Warn($"SpeakerSettingUpdatePacket: Can't find speaker ({packet.PlanetId}, {packet.SpeakerId})"); - } + } + else if (pool != null) + { + Log.Warn($"SpeakerSettingUpdatePacket: Can't find speaker ({packet.PlanetId}, {packet.SpeakerId})"); } } } diff --git a/NebulaNetwork/PacketProcessors/Factory/PowerExchanger/PowerExchangerChangeModeProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/PowerExchanger/PowerExchangerChangeModeProcessor.cs index aee550e10..99893a953 100644 --- a/NebulaNetwork/PacketProcessors/Factory/PowerExchanger/PowerExchangerChangeModeProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/PowerExchanger/PowerExchangerChangeModeProcessor.cs @@ -1,20 +1,24 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.PowerExchanger; -namespace NebulaNetwork.PacketProcessors.Factory.PowerExchanger +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.PowerExchanger; + +[RegisterPacketProcessor] +internal class PowerExchangerChangeModeProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class PowerExchangerChangeModeProcessor : PacketProcessor + public override void ProcessPacket(PowerExchangerChangeModePacket packet, NebulaConnection conn) { - public override void ProcessPacket(PowerExchangerChangeModePacket packet, NebulaConnection conn) + var pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.powerSystem?.excPool; + if (pool != null && packet.PowerExchangerIndex != -1 && packet.PowerExchangerIndex < pool.Length && + pool[packet.PowerExchangerIndex].id != -1) { - PowerExchangerComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.powerSystem?.excPool; - if (pool != null && packet.PowerExchangerIndex != -1 && packet.PowerExchangerIndex < pool.Length && pool[packet.PowerExchangerIndex].id != -1) - { - pool[packet.PowerExchangerIndex].targetState = packet.Mode; - } + pool[packet.PowerExchangerIndex].targetState = packet.Mode; } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Factory/PowerExchanger/PowerExchangerStorageUpdateProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/PowerExchanger/PowerExchangerStorageUpdateProcessor.cs index 2766a24b4..ee97ae389 100644 --- a/NebulaNetwork/PacketProcessors/Factory/PowerExchanger/PowerExchangerStorageUpdateProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/PowerExchanger/PowerExchangerStorageUpdateProcessor.cs @@ -1,21 +1,25 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.PowerExchanger; -namespace NebulaNetwork.PacketProcessors.Factory.PowerExchanger +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.PowerExchanger; + +[RegisterPacketProcessor] +internal class PowerExchangerStorageUpdateProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class PowerExchangerStorageUpdateProcessor : PacketProcessor + public override void ProcessPacket(PowerExchangerStorageUpdatePacket packet, NebulaConnection conn) { - public override void ProcessPacket(PowerExchangerStorageUpdatePacket packet, NebulaConnection conn) + var pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.powerSystem?.excPool; + if (pool != null && packet.PowerExchangerIndex != -1 && packet.PowerExchangerIndex < pool.Length && + pool[packet.PowerExchangerIndex].id != -1) { - PowerExchangerComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.powerSystem?.excPool; - if (pool != null && packet.PowerExchangerIndex != -1 && packet.PowerExchangerIndex < pool.Length && pool[packet.PowerExchangerIndex].id != -1) - { - pool[packet.PowerExchangerIndex].SetEmptyCount(packet.EmptyAccumulatorCount); - pool[packet.PowerExchangerIndex].SetFullCount(packet.FullAccumulatorCount); - } + pool[packet.PowerExchangerIndex].SetEmptyCount(packet.EmptyAccumulatorCount); + pool[packet.PowerExchangerIndex].SetFullCount(packet.FullAccumulatorCount); } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Factory/PowerGenerator/PowerGeneratorFuelUpdateProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/PowerGenerator/PowerGeneratorFuelUpdateProcessor.cs index c5ebc41f5..230250817 100644 --- a/NebulaNetwork/PacketProcessors/Factory/PowerGenerator/PowerGeneratorFuelUpdateProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/PowerGenerator/PowerGeneratorFuelUpdateProcessor.cs @@ -1,26 +1,30 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.PowerGenerator; -namespace NebulaNetwork.PacketProcessors.Factory.PowerGenerator +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.PowerGenerator; + +[RegisterPacketProcessor] +internal class PowerGeneratorFuelUpdateProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class PowerGeneratorFuelUpdateProcessor : PacketProcessor + public override void ProcessPacket(PowerGeneratorFuelUpdatePacket packet, NebulaConnection conn) { - public override void ProcessPacket(PowerGeneratorFuelUpdatePacket packet, NebulaConnection conn) + var pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.powerSystem?.genPool; + if (pool != null && packet.PowerGeneratorIndex != -1 && packet.PowerGeneratorIndex < pool.Length && + pool[packet.PowerGeneratorIndex].id != -1) { - PowerGeneratorComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.powerSystem?.genPool; - if (pool != null && packet.PowerGeneratorIndex != -1 && packet.PowerGeneratorIndex < pool.Length && pool[packet.PowerGeneratorIndex].id != -1) + if (pool[packet.PowerGeneratorIndex].fuelId != packet.FuelId) + { + pool[packet.PowerGeneratorIndex].SetNewFuel(packet.FuelId, packet.FuelAmount, packet.FuelInc); + } + else { - if (pool[packet.PowerGeneratorIndex].fuelId != packet.FuelId) - { - pool[packet.PowerGeneratorIndex].SetNewFuel(packet.FuelId, packet.FuelAmount, packet.FuelInc); - } - else - { - pool[packet.PowerGeneratorIndex].fuelCount = packet.FuelAmount; - } + pool[packet.PowerGeneratorIndex].fuelCount = packet.FuelAmount; } } } diff --git a/NebulaNetwork/PacketProcessors/Factory/PowerGenerator/PowerGeneratorProductUpdateProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/PowerGenerator/PowerGeneratorProductUpdateProcessor.cs index 641bb54dd..869a3f685 100644 --- a/NebulaNetwork/PacketProcessors/Factory/PowerGenerator/PowerGeneratorProductUpdateProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/PowerGenerator/PowerGeneratorProductUpdateProcessor.cs @@ -1,20 +1,24 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.PowerGenerator; -namespace NebulaNetwork.PacketProcessors.Factory.PowerGenerator +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.PowerGenerator; + +[RegisterPacketProcessor] +internal class PowerGeneratorProductUpdateProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class PowerGeneratorProductUpdateProcessor : PacketProcessor + public override void ProcessPacket(PowerGeneratorProductUpdatePacket packet, NebulaConnection conn) { - public override void ProcessPacket(PowerGeneratorProductUpdatePacket packet, NebulaConnection conn) + var pool = GameMain.galaxy.PlanetById(packet.PlanetId).factory?.powerSystem.genPool; + if (pool != null && packet.PowerGeneratorIndex != -1 && packet.PowerGeneratorIndex < pool.Length && + pool[packet.PowerGeneratorIndex].id != -1) { - PowerGeneratorComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId).factory?.powerSystem.genPool; - if (pool != null && packet.PowerGeneratorIndex != -1 && packet.PowerGeneratorIndex < pool.Length && pool[packet.PowerGeneratorIndex].id != -1) - { - pool[packet.PowerGeneratorIndex].productCount = packet.ProductCount; - } + pool[packet.PowerGeneratorIndex].productCount = packet.ProductCount; } } } diff --git a/NebulaNetwork/PacketProcessors/Factory/PowerTower/PowerTowerUserLoadRequestProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/PowerTower/PowerTowerUserLoadRequestProcessor.cs index b8844754a..65c144cb9 100644 --- a/NebulaNetwork/PacketProcessors/Factory/PowerTower/PowerTowerUserLoadRequestProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/PowerTower/PowerTowerUserLoadRequestProcessor.cs @@ -1,48 +1,52 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.PowerTower; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Factory.PowerTower +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.PowerTower; + +[RegisterPacketProcessor] +public class PowerTowerUserLoadingRequestProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class PowerTowerUserLoadingRequestProcessor : PacketProcessor + public override void ProcessPacket(PowerTowerUserLoadingRequest packet, NebulaConnection conn) { - public override void ProcessPacket(PowerTowerUserLoadingRequest packet, NebulaConnection conn) + if (IsClient) { - if (IsClient) - { - return; - } + return; + } - PlanetFactory factory = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory; + var factory = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory; - if (factory?.powerSystem != null) + if (factory?.powerSystem != null) + { + var pNet = factory.powerSystem.netPool[packet.NetId]; + + if (packet.Charging) { - PowerNetwork pNet = factory.powerSystem.netPool[packet.NetId]; - - if (packet.Charging) - { - Multiplayer.Session.PowerTowers.AddExtraDemand(packet.PlanetId, packet.NetId, packet.NodeId, packet.PowerAmount); - } - else - { - Multiplayer.Session.PowerTowers.RemExtraDemand(packet.PlanetId, packet.NetId, packet.NodeId); - } - - Multiplayer.Session.Network.SendPacketToStar(new PowerTowerUserLoadingResponse(packet.PlanetId, - packet.NetId, - packet.NodeId, - packet.PowerAmount, - pNet.energyCapacity, - pNet.energyRequired, - pNet.energyServed, - pNet.energyAccumulated, - pNet.energyExchanged, - packet.Charging), - GameMain.galaxy.PlanetById(packet.PlanetId).star.id); + Multiplayer.Session.PowerTowers.AddExtraDemand(packet.PlanetId, packet.NetId, packet.NodeId, + packet.PowerAmount); } + else + { + Multiplayer.Session.PowerTowers.RemExtraDemand(packet.PlanetId, packet.NetId, packet.NodeId); + } + + Multiplayer.Session.Network.SendPacketToStar(new PowerTowerUserLoadingResponse(packet.PlanetId, + packet.NetId, + packet.NodeId, + packet.PowerAmount, + pNet.energyCapacity, + pNet.energyRequired, + pNet.energyServed, + pNet.energyAccumulated, + pNet.energyExchanged, + packet.Charging), + GameMain.galaxy.PlanetById(packet.PlanetId).star.id); } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Factory/PowerTower/PowerTowerUserLoadResponseProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/PowerTower/PowerTowerUserLoadResponseProcessor.cs index b80e17b1c..4d58ac960 100644 --- a/NebulaNetwork/PacketProcessors/Factory/PowerTower/PowerTowerUserLoadResponseProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/PowerTower/PowerTowerUserLoadResponseProcessor.cs @@ -1,42 +1,48 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.PowerTower; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Factory.PowerTower +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.PowerTower; + +[RegisterPacketProcessor] +internal class PowerTowerUserLoadResponseProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class PowerTowerUserLoadResponseProcessor : PacketProcessor + public override void ProcessPacket(PowerTowerUserLoadingResponse packet, NebulaConnection conn) { - public override void ProcessPacket(PowerTowerUserLoadingResponse packet, NebulaConnection conn) + var factory = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory; + if (factory != null && factory.powerSystem != null) { - PlanetFactory factory = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory; - if (factory != null && factory.powerSystem != null) - { - PowerNetwork pNet = factory.powerSystem.netPool[packet.NetId]; + var pNet = factory.powerSystem.netPool[packet.NetId]; - if (packet.Charging) + if (packet.Charging) + { + Multiplayer.Session.PowerTowers.AddExtraDemand(packet.PlanetId, packet.NetId, packet.NodeId, + packet.PowerAmount); + if (IsClient) { - Multiplayer.Session.PowerTowers.AddExtraDemand(packet.PlanetId, packet.NetId, packet.NodeId, packet.PowerAmount); - if (IsClient) + if (Multiplayer.Session.PowerTowers.DidRequest(packet.PlanetId, packet.NetId, packet.NodeId)) { - if (Multiplayer.Session.PowerTowers.DidRequest(packet.PlanetId, packet.NetId, packet.NodeId)) - { - int baseDemand = factory.powerSystem.nodePool[packet.NodeId].workEnergyPerTick - factory.powerSystem.nodePool[packet.NodeId].idleEnergyPerTick; - float mult = factory.powerSystem.networkServes[packet.NetId]; - Multiplayer.Session.PowerTowers.PlayerChargeAmount += (int)(mult * baseDemand); - } + var baseDemand = factory.powerSystem.nodePool[packet.NodeId].workEnergyPerTick - + factory.powerSystem.nodePool[packet.NodeId].idleEnergyPerTick; + var mult = factory.powerSystem.networkServes[packet.NetId]; + Multiplayer.Session.PowerTowers.PlayerChargeAmount += (int)(mult * baseDemand); } } - else - { - Multiplayer.Session.PowerTowers.RemExtraDemand(packet.PlanetId, packet.NetId, packet.NodeId); - } + } + else + { + Multiplayer.Session.PowerTowers.RemExtraDemand(packet.PlanetId, packet.NetId, packet.NodeId); + } - if (IsHost) - { - Multiplayer.Session.Network.SendPacketToStar(new PowerTowerUserLoadingResponse(packet.PlanetId, + if (IsHost) + { + Multiplayer.Session.Network.SendPacketToStar(new PowerTowerUserLoadingResponse(packet.PlanetId, packet.NetId, packet.NodeId, packet.PowerAmount, @@ -46,17 +52,15 @@ public override void ProcessPacket(PowerTowerUserLoadingResponse packet, NebulaC pNet.energyAccumulated, pNet.energyExchanged, packet.Charging), - GameMain.galaxy.PlanetById(packet.PlanetId).star.id); - } - else - { - pNet.energyCapacity = packet.EnergyCapacity; - pNet.energyRequired = packet.EnergyRequired; - pNet.energyAccumulated = packet.EnergyAccumulated; - pNet.energyExchanged = packet.EnergyExchanged; - pNet.energyServed = packet.EnergyServed; - } - + GameMain.galaxy.PlanetById(packet.PlanetId).star.id); + } + else + { + pNet.energyCapacity = packet.EnergyCapacity; + pNet.energyRequired = packet.EnergyRequired; + pNet.energyAccumulated = packet.EnergyAccumulated; + pNet.energyExchanged = packet.EnergyExchanged; + pNet.energyServed = packet.EnergyServed; } } } diff --git a/NebulaNetwork/PacketProcessors/Factory/RayReceiver/RayReceiverChangeLensProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/RayReceiver/RayReceiverChangeLensProcessor.cs index 9383e985d..2397a9c44 100644 --- a/NebulaNetwork/PacketProcessors/Factory/RayReceiver/RayReceiverChangeLensProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/RayReceiver/RayReceiverChangeLensProcessor.cs @@ -1,21 +1,24 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.RayReceiver; -namespace NebulaNetwork.PacketProcessors.Factory.RayReceiver +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.RayReceiver; + +[RegisterPacketProcessor] +internal class RayReceiverChangeLensProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class RayReceiverChangeLensProcessor : PacketProcessor + public override void ProcessPacket(RayReceiverChangeLensPacket packet, NebulaConnection conn) { - public override void ProcessPacket(RayReceiverChangeLensPacket packet, NebulaConnection conn) + var pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.powerSystem?.genPool; + if (pool != null && packet.GeneratorId != -1 && packet.GeneratorId < pool.Length && pool[packet.GeneratorId].id != -1) { - PowerGeneratorComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.powerSystem?.genPool; - if (pool != null && packet.GeneratorId != -1 && packet.GeneratorId < pool.Length && pool[packet.GeneratorId].id != -1) - { - pool[packet.GeneratorId].catalystPoint = packet.LensCount; - pool[packet.GeneratorId].catalystIncPoint = packet.LensInc; - } + pool[packet.GeneratorId].catalystPoint = packet.LensCount; + pool[packet.GeneratorId].catalystIncPoint = packet.LensInc; } } } diff --git a/NebulaNetwork/PacketProcessors/Factory/RayReceiver/RayReceiverChangeModeProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/RayReceiver/RayReceiverChangeModeProcessor.cs index 559711d78..0dc8b4084 100644 --- a/NebulaNetwork/PacketProcessors/Factory/RayReceiver/RayReceiverChangeModeProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/RayReceiver/RayReceiverChangeModeProcessor.cs @@ -1,28 +1,32 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.RayReceiver; -namespace NebulaNetwork.PacketProcessors.Factory.RayReceiver +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.RayReceiver; + +[RegisterPacketProcessor] +internal class RayReceiverChangeModeProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class RayReceiverChangeModeProcessor : PacketProcessor + public override void ProcessPacket(RayReceiverChangeModePacket packet, NebulaConnection conn) { - public override void ProcessPacket(RayReceiverChangeModePacket packet, NebulaConnection conn) + var pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.powerSystem.genPool; + if (pool != null && packet.GeneratorId != -1 && packet.GeneratorId < pool.Length && pool[packet.GeneratorId].id != -1) { - PowerGeneratorComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.powerSystem.genPool; - if (pool != null && packet.GeneratorId != -1 && packet.GeneratorId < pool.Length && pool[packet.GeneratorId].id != -1) + if (packet.Mode == RayReceiverMode.Electricity) + { + pool[packet.GeneratorId].productId = 0; + pool[packet.GeneratorId].productCount = 0f; + } + else if (packet.Mode == RayReceiverMode.Photon) { - if (packet.Mode == RayReceiverMode.Electricity) - { - pool[packet.GeneratorId].productId = 0; - pool[packet.GeneratorId].productCount = 0f; - } - else if (packet.Mode == RayReceiverMode.Photon) - { - ItemProto itemProto = LDB.items.Select((int)GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.entityPool[pool[packet.GeneratorId].entityId].protoId); - pool[packet.GeneratorId].productId = itemProto.prefabDesc.powerProductId; - } + var itemProto = LDB.items.Select((int)GameMain.galaxy.PlanetById(packet.PlanetId)?.factory + ?.entityPool[pool[packet.GeneratorId].entityId].protoId); + pool[packet.GeneratorId].productId = itemProto.prefabDesc.powerProductId; } } } diff --git a/NebulaNetwork/PacketProcessors/Factory/Silo/SiloStorageUpdateProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Silo/SiloStorageUpdateProcessor.cs index 4be52cbf6..afcfa5f65 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Silo/SiloStorageUpdateProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Silo/SiloStorageUpdateProcessor.cs @@ -1,21 +1,24 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Silo; -namespace NebulaNetwork.PacketProcessors.Factory.Silo +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Silo; + +[RegisterPacketProcessor] +internal class SiloStorageUpdateProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class SiloStorageUpdateProcessor : PacketProcessor + public override void ProcessPacket(SiloStorageUpdatePacket packet, NebulaConnection conn) { - public override void ProcessPacket(SiloStorageUpdatePacket packet, NebulaConnection conn) + var pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factorySystem?.siloPool; + if (pool != null && packet.SiloIndex != -1 && packet.SiloIndex < pool.Length && pool[packet.SiloIndex].id != -1) { - SiloComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factorySystem?.siloPool; - if (pool != null && packet.SiloIndex != -1 && packet.SiloIndex < pool.Length && pool[packet.SiloIndex].id != -1) - { - pool[packet.SiloIndex].bulletCount = packet.ItemCount; - pool[packet.SiloIndex].bulletInc = packet.ItemInc; - } + pool[packet.SiloIndex].bulletCount = packet.ItemCount; + pool[packet.SiloIndex].bulletInc = packet.ItemInc; } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Factory/Splitter/SplitterFilterChangeProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Splitter/SplitterFilterChangeProcessor.cs index 31ad2b8e5..082988f86 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Splitter/SplitterFilterChangeProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Splitter/SplitterFilterChangeProcessor.cs @@ -1,20 +1,24 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Splitter; -namespace NebulaNetwork.PacketProcessors.Factory.Splitter +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Splitter; + +[RegisterPacketProcessor] +internal class SplitterFilterChangeProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class SplitterFilterChangeProcessor : PacketProcessor + public override void ProcessPacket(SplitterFilterChangePacket packet, NebulaConnection conn) { - public override void ProcessPacket(SplitterFilterChangePacket packet, NebulaConnection conn) + var pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.cargoTraffic?.splitterPool; + if (pool != null && packet.SplitterIndex != -1 && packet.SplitterIndex < pool.Length && + pool[packet.SplitterIndex].id != -1) { - SplitterComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.cargoTraffic?.splitterPool; - if (pool != null && packet.SplitterIndex != -1 && packet.SplitterIndex < pool.Length && pool[packet.SplitterIndex].id != -1) - { - pool[packet.SplitterIndex].outFilter = packet.ItemId; - } + pool[packet.SplitterIndex].outFilter = packet.ItemId; } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Factory/Splitter/SplitterPriorityChangeProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Splitter/SplitterPriorityChangeProcessor.cs index a048d874c..f294f389a 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Splitter/SplitterPriorityChangeProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Splitter/SplitterPriorityChangeProcessor.cs @@ -1,20 +1,24 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Splitter; -namespace NebulaNetwork.PacketProcessors.Factory.Splitter +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Splitter; + +[RegisterPacketProcessor] +internal class SplitterPriorityChangeProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class SplitterPriorityChangeProcessor : PacketProcessor + public override void ProcessPacket(SplitterPriorityChangePacket packet, NebulaConnection conn) { - public override void ProcessPacket(SplitterPriorityChangePacket packet, NebulaConnection conn) + var pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.cargoTraffic.splitterPool; + if (pool != null && packet.SplitterIndex != -1 && packet.SplitterIndex < pool.Length && + pool[packet.SplitterIndex].id != -1) { - SplitterComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.cargoTraffic.splitterPool; - if (pool != null && packet.SplitterIndex != -1 && packet.SplitterIndex < pool.Length && pool[packet.SplitterIndex].id != -1) - { - pool[packet.SplitterIndex].SetPriority(packet.Slot, packet.IsPriority, packet.Filter); - } + pool[packet.SplitterIndex].SetPriority(packet.Slot, packet.IsPriority, packet.Filter); } } } diff --git a/NebulaNetwork/PacketProcessors/Factory/Storage/StorageSyncRealtimeChangeProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Storage/StorageSyncRealtimeChangeProcessor.cs index 18b91f129..f441e89ee 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Storage/StorageSyncRealtimeChangeProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Storage/StorageSyncRealtimeChangeProcessor.cs @@ -1,51 +1,54 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Storage; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Factory.Storage +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Storage; + +[RegisterPacketProcessor] +internal class StorageSyncRealtimeChangeProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class StorageSyncRealtimeChangeProcessor : PacketProcessor + public override void ProcessPacket(StorageSyncRealtimeChangePacket packet, NebulaConnection conn) { - public override void ProcessPacket(StorageSyncRealtimeChangePacket packet, NebulaConnection conn) + StorageComponent storage = null; + var pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factoryStorage?.storagePool; + if (pool != null && packet.StorageIndex != -1 && packet.StorageIndex < pool.Length) { - StorageComponent storage = null; - StorageComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factoryStorage?.storagePool; - if (pool != null && packet.StorageIndex != -1 && packet.StorageIndex < pool.Length) - { - storage = pool[packet.StorageIndex]; - } + storage = pool[packet.StorageIndex]; + } - if (storage != null) + if (storage != null) + { + using (Multiplayer.Session.Storage.IsIncomingRequest.On()) { - using (Multiplayer.Session.Storage.IsIncomingRequest.On()) + var itemId = packet.ItemId; + var count = packet.Count; + var inc = packet.Inc; + int dummyOut; + if (packet.StorageEvent == StorageSyncRealtimeChangeEvent.AddItem2) { - int itemId = packet.ItemId; - int count = packet.Count; - int inc = packet.Inc; - int dummyOut; - if (packet.StorageEvent == StorageSyncRealtimeChangeEvent.AddItem2) - { - storage.AddItem(itemId, count, packet.StartIndex, packet.Length, inc, out dummyOut); - } - else if (packet.StorageEvent == StorageSyncRealtimeChangeEvent.AddItemStacked) - { - storage.AddItemStacked(itemId, count, inc, out dummyOut); - } - else if (packet.StorageEvent == StorageSyncRealtimeChangeEvent.TakeItemFromGrid) - { - storage.TakeItemFromGrid(packet.Length, ref itemId, ref count, out dummyOut); - } + storage.AddItem(itemId, count, packet.StartIndex, packet.Length, inc, out dummyOut); + } + else if (packet.StorageEvent == StorageSyncRealtimeChangeEvent.AddItemStacked) + { + storage.AddItemStacked(itemId, count, inc, out dummyOut); + } + else if (packet.StorageEvent == StorageSyncRealtimeChangeEvent.TakeItemFromGrid) + { + storage.TakeItemFromGrid(packet.Length, ref itemId, ref count, out dummyOut); + } - if (IsHost) - { - int starId = GameMain.galaxy.PlanetById(packet.PlanetId).star.id; - Multiplayer.Session.Network.SendPacketToStarExclude(packet, starId, conn); - } + if (IsHost) + { + var starId = GameMain.galaxy.PlanetById(packet.PlanetId).star.id; + Multiplayer.Session.Network.SendPacketToStarExclude(packet, starId, conn); } } } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Factory/Storage/StorageSyncRequestProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Storage/StorageSyncRequestProcessor.cs index 7a6a86cd9..a8d098e50 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Storage/StorageSyncRequestProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Storage/StorageSyncRequestProcessor.cs @@ -1,30 +1,35 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Storage; -namespace NebulaNetwork.PacketProcessors.Factory.Storage +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Storage; + +[RegisterPacketProcessor] +internal class StorageSyncRequestProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class StorageSyncRequestProcessor : PacketProcessor + public override void ProcessPacket(StorageSyncRequestPacket packet, NebulaConnection conn) { - public override void ProcessPacket(StorageSyncRequestPacket packet, NebulaConnection conn) + if (IsClient) { - if (IsClient) - { - return; - } + return; + } - if (GameMain.galaxy.PlanetById(packet.PlanetId) != null) + if (GameMain.galaxy.PlanetById(packet.PlanetId) != null) + { + var storageComponent = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factoryStorage + ?.storagePool[packet.StorageId]; + if (storageComponent != null) { - StorageComponent storageComponent = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factoryStorage?.storagePool[packet.StorageId]; - if (storageComponent != null) + using (var writer = new BinaryUtils.Writer()) { - using (BinaryUtils.Writer writer = new BinaryUtils.Writer()) - { - storageComponent.Export(writer.BinaryWriter); - conn.SendPacket(new StorageSyncResponsePacket(packet.PlanetId, packet.StorageId, writer.CloseAndGetBytes())); - } + storageComponent.Export(writer.BinaryWriter); + conn.SendPacket(new StorageSyncResponsePacket(packet.PlanetId, packet.StorageId, + writer.CloseAndGetBytes())); } } } diff --git a/NebulaNetwork/PacketProcessors/Factory/Storage/StorageSyncResponseProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Storage/StorageSyncResponseProcessor.cs index 6504eef01..4c9773363 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Storage/StorageSyncResponseProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Storage/StorageSyncResponseProcessor.cs @@ -1,43 +1,50 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Storage; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Factory.Storage +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Storage; + +[RegisterPacketProcessor] +internal class StorageSyncResponseProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class StorageSyncResponseProcessor : PacketProcessor + public override void ProcessPacket(StorageSyncResponsePacket packet, NebulaConnection conn) { - public override void ProcessPacket(StorageSyncResponsePacket packet, NebulaConnection conn) + if (IsHost) { - if (IsHost) - { - return; - } + return; + } - StorageComponent storageComponent = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factoryStorage?.storagePool[packet.StorageIndex]; - if (storageComponent != null) + var storageComponent = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factoryStorage + ?.storagePool[packet.StorageIndex]; + if (storageComponent != null) + { + using (var reader = new BinaryUtils.Reader(packet.StorageComponent)) { - using (BinaryUtils.Reader reader = new BinaryUtils.Reader(packet.StorageComponent)) - { - storageComponent.Import(reader.BinaryReader); - } - ItemProto itemProto = LDB.items.Select((int)GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.entityPool[storageComponent.entityId].protoId); - - //Imitation of UIStorageWindow.OnStorageIdChange() - Multiplayer.Session.Storage.ActiveWindowTitle.text = itemProto.name; - Multiplayer.Session.Storage.ActiveUIStorageGrid._Free(); - Multiplayer.Session.Storage.ActiveUIStorageGrid._Init(storageComponent); - Multiplayer.Session.Storage.ActiveStorageComponent = storageComponent; - Multiplayer.Session.Storage.ActiveUIStorageGrid.SetStorageData(Multiplayer.Session.Storage.ActiveStorageComponent); - Multiplayer.Session.Storage.ActiveUIStorageGrid._Open(); - Multiplayer.Session.Storage.ActiveUIStorageGrid.OnStorageDataChanged(); - Multiplayer.Session.Storage.ActiveBansSlider.maxValue = storageComponent.size; - Multiplayer.Session.Storage.ActiveBansSlider.value = storageComponent.size - storageComponent.bans; - Multiplayer.Session.Storage.ActiveBansValueText.text = Multiplayer.Session.Storage.ActiveBansSlider.value.ToString(); - GameMain.galaxy.PlanetById(packet.PlanetId).factory.factoryStorage.storagePool[packet.StorageIndex] = storageComponent; + storageComponent.Import(reader.BinaryReader); } + var itemProto = LDB.items.Select((int)GameMain.galaxy.PlanetById(packet.PlanetId)?.factory + ?.entityPool[storageComponent.entityId].protoId); + + //Imitation of UIStorageWindow.OnStorageIdChange() + Multiplayer.Session.Storage.ActiveWindowTitle.text = itemProto.name; + Multiplayer.Session.Storage.ActiveUIStorageGrid._Free(); + Multiplayer.Session.Storage.ActiveUIStorageGrid._Init(storageComponent); + Multiplayer.Session.Storage.ActiveStorageComponent = storageComponent; + Multiplayer.Session.Storage.ActiveUIStorageGrid.SetStorageData(Multiplayer.Session.Storage.ActiveStorageComponent); + Multiplayer.Session.Storage.ActiveUIStorageGrid._Open(); + Multiplayer.Session.Storage.ActiveUIStorageGrid.OnStorageDataChanged(); + Multiplayer.Session.Storage.ActiveBansSlider.maxValue = storageComponent.size; + Multiplayer.Session.Storage.ActiveBansSlider.value = storageComponent.size - storageComponent.bans; + Multiplayer.Session.Storage.ActiveBansValueText.text = + Multiplayer.Session.Storage.ActiveBansSlider.value.ToString(); + GameMain.galaxy.PlanetById(packet.PlanetId).factory.factoryStorage.storagePool[packet.StorageIndex] = + storageComponent; } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Factory/Storage/StorageSyncSetBansProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Storage/StorageSyncSetBansProcessor.cs index 41f4555db..60e1cbaba 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Storage/StorageSyncSetBansProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Storage/StorageSyncSetBansProcessor.cs @@ -1,30 +1,33 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Storage; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Factory.Storage +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Storage; + +[RegisterPacketProcessor] +internal class StorageSyncSetBansProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class StorageSyncSetBansProcessor : PacketProcessor + public override void ProcessPacket(StorageSyncSetBansPacket packet, NebulaConnection conn) { - public override void ProcessPacket(StorageSyncSetBansPacket packet, NebulaConnection conn) + StorageComponent storage = null; + var pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factoryStorage?.storagePool; + if (pool != null && packet.StorageIndex != -1 && packet.StorageIndex < pool.Length) { - StorageComponent storage = null; - StorageComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factoryStorage?.storagePool; - if (pool != null && packet.StorageIndex != -1 && packet.StorageIndex < pool.Length) - { - storage = pool[packet.StorageIndex]; - } + storage = pool[packet.StorageIndex]; + } - if (storage != null) + if (storage != null) + { + using (Multiplayer.Session.Storage.IsIncomingRequest.On()) { - using (Multiplayer.Session.Storage.IsIncomingRequest.On()) - { - storage.SetBans(packet.Bans); - } + storage.SetBans(packet.Bans); } } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Factory/Storage/StorageSyncSortProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Storage/StorageSyncSortProcessor.cs index 798b0aadd..b434f9a04 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Storage/StorageSyncSortProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Storage/StorageSyncSortProcessor.cs @@ -1,30 +1,33 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Storage; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Factory.Storage +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Storage; + +[RegisterPacketProcessor] +internal class StorageSyncSortProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class StorageSyncSortProcessor : PacketProcessor + public override void ProcessPacket(StorageSyncSortPacket packet, NebulaConnection conn) { - public override void ProcessPacket(StorageSyncSortPacket packet, NebulaConnection conn) + StorageComponent storage = null; + var pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factoryStorage?.storagePool; + if (pool != null && packet.StorageIndex != -1 && packet.StorageIndex < pool.Length) { - StorageComponent storage = null; - StorageComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factoryStorage?.storagePool; - if (pool != null && packet.StorageIndex != -1 && packet.StorageIndex < pool.Length) - { - storage = pool[packet.StorageIndex]; - } + storage = pool[packet.StorageIndex]; + } - if (storage != null) + if (storage != null) + { + using (Multiplayer.Session.Storage.IsIncomingRequest.On()) { - using (Multiplayer.Session.Storage.IsIncomingRequest.On()) - { - storage.Sort(); - } + storage.Sort(); } } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Factory/Tank/SprayerStorageUpdateProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Tank/SprayerStorageUpdateProcessor.cs index d2469a5e3..9db93bffa 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Tank/SprayerStorageUpdateProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Tank/SprayerStorageUpdateProcessor.cs @@ -1,24 +1,27 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Tank; -namespace NebulaNetwork.PacketProcessors.Factory.Tank +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Tank; + +[RegisterPacketProcessor] +internal class SprayerStorageUpdateProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class SprayerStorageUpdateProcessor : PacketProcessor + public override void ProcessPacket(SprayerStorageUpdatePacket packet, NebulaConnection conn) { - public override void ProcessPacket(SprayerStorageUpdatePacket packet, NebulaConnection conn) + var pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.cargoTraffic.spraycoaterPool; + if (pool != null && packet.SprayerIndex >= 0 && packet.SprayerIndex < pool.Length && pool[packet.SprayerIndex].id != -1) { - SpraycoaterComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.cargoTraffic.spraycoaterPool; - if (pool != null && packet.SprayerIndex >= 0 && packet.SprayerIndex < pool.Length && pool[packet.SprayerIndex].id != -1) - { - pool[packet.SprayerIndex].incItemId = packet.IncItemId; - pool[packet.SprayerIndex].incAbility = packet.IncAbility; - pool[packet.SprayerIndex].incSprayTimes = packet.IncSprayTimes; - pool[packet.SprayerIndex].incCount = packet.IncCount; - pool[packet.SprayerIndex].extraIncCount = packet.ExtraIncCount; - } + pool[packet.SprayerIndex].incItemId = packet.IncItemId; + pool[packet.SprayerIndex].incAbility = packet.IncAbility; + pool[packet.SprayerIndex].incSprayTimes = packet.IncSprayTimes; + pool[packet.SprayerIndex].incCount = packet.IncCount; + pool[packet.SprayerIndex].extraIncCount = packet.ExtraIncCount; } } } diff --git a/NebulaNetwork/PacketProcessors/Factory/Tank/TankInputOutputSwitchProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Tank/TankInputOutputSwitchProcessor.cs index bdfdc7b07..d0e104dda 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Tank/TankInputOutputSwitchProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Tank/TankInputOutputSwitchProcessor.cs @@ -1,27 +1,30 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Tank; -namespace NebulaNetwork.PacketProcessors.Factory.Tank +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Tank; + +[RegisterPacketProcessor] +internal class TankInputOutputSwitchProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class TankInputOutputSwitchProcessor : PacketProcessor + public override void ProcessPacket(TankInputOutputSwitchPacket packet, NebulaConnection conn) { - public override void ProcessPacket(TankInputOutputSwitchPacket packet, NebulaConnection conn) + var pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factoryStorage?.tankPool; + if (pool != null && packet.TankIndex != -1 && packet.TankIndex < pool.Length && pool[packet.TankIndex].id != -1) { - TankComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factoryStorage?.tankPool; - if (pool != null && packet.TankIndex != -1 && packet.TankIndex < pool.Length && pool[packet.TankIndex].id != -1) + if (packet.IsInput) + { + pool[packet.TankIndex].inputSwitch = packet.IsClosed; + } + else { - if (packet.IsInput) - { - pool[packet.TankIndex].inputSwitch = packet.IsClosed; - } - else - { - pool[packet.TankIndex].outputSwitch = packet.IsClosed; - } + pool[packet.TankIndex].outputSwitch = packet.IsClosed; } } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Factory/Tank/TankStorageUpdateProcessor.cs b/NebulaNetwork/PacketProcessors/Factory/Tank/TankStorageUpdateProcessor.cs index 9d3b5b333..208af964b 100644 --- a/NebulaNetwork/PacketProcessors/Factory/Tank/TankStorageUpdateProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Factory/Tank/TankStorageUpdateProcessor.cs @@ -1,22 +1,25 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Factory.Tank; -namespace NebulaNetwork.PacketProcessors.Factory.Tank +#endregion + +namespace NebulaNetwork.PacketProcessors.Factory.Tank; + +[RegisterPacketProcessor] +internal class TankStorageUpdateProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class TankStorageUpdateProcessor : PacketProcessor + public override void ProcessPacket(TankStorageUpdatePacket packet, NebulaConnection conn) { - public override void ProcessPacket(TankStorageUpdatePacket packet, NebulaConnection conn) + var pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factoryStorage?.tankPool; + if (pool != null && packet.TankIndex != -1 && packet.TankIndex < pool.Length && pool[packet.TankIndex].id != -1) { - TankComponent[] pool = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory?.factoryStorage?.tankPool; - if (pool != null && packet.TankIndex != -1 && packet.TankIndex < pool.Length && pool[packet.TankIndex].id != -1) - { - pool[packet.TankIndex].fluidId = packet.FluidId; - pool[packet.TankIndex].fluidCount = packet.FluidCount; - pool[packet.TankIndex].fluidInc = packet.FluidInc; - } + pool[packet.TankIndex].fluidId = packet.FluidId; + pool[packet.TankIndex].fluidCount = packet.FluidCount; + pool[packet.TankIndex].fluidInc = packet.FluidInc; } } } diff --git a/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryDataResponseProcessor.cs b/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryDataResponseProcessor.cs index 123f0e882..ceac51d54 100644 --- a/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryDataResponseProcessor.cs +++ b/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryDataResponseProcessor.cs @@ -1,30 +1,33 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.GameHistory; -namespace NebulaNetwork.PacketProcessors.GameHistory +#endregion + +namespace NebulaNetwork.PacketProcessors.GameHistory; + +[RegisterPacketProcessor] +internal class GameHistoryDataResponseProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class GameHistoryDataResponseProcessor : PacketProcessor + public override void ProcessPacket(GameHistoryDataResponse packet, NebulaConnection conn) { - public override void ProcessPacket(GameHistoryDataResponse packet, NebulaConnection conn) + if (IsHost) { - if (IsHost) - { - return; - } + return; + } - //Reset all current values - GameMain.data.history.Init(GameMain.data); + //Reset all current values + GameMain.data.history.Init(GameMain.data); - Log.Info($"Parsing History data from the server."); - using (BinaryUtils.Reader reader = new BinaryUtils.Reader(packet.HistoryBinaryData)) - { - GameMain.data.history.Import(reader.BinaryReader); - } - GameMain.sandboxToolsEnabled = packet.SandboxToolsEnabled; + Log.Info("Parsing History data from the server."); + using (var reader = new BinaryUtils.Reader(packet.HistoryBinaryData)) + { + GameMain.data.history.Import(reader.BinaryReader); } + GameMain.sandboxToolsEnabled = packet.SandboxToolsEnabled; } } diff --git a/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryEnqueueTechProcessor.cs b/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryEnqueueTechProcessor.cs index 6412274bc..e32501152 100644 --- a/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryEnqueueTechProcessor.cs +++ b/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryEnqueueTechProcessor.cs @@ -1,43 +1,45 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.GameHistory; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.GameHistory +#endregion + +namespace NebulaNetwork.PacketProcessors.GameHistory; + +[RegisterPacketProcessor] +internal class GameHistoryEnqueueTechProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class GameHistoryEnqueueTechProcessor : PacketProcessor - { - private readonly IPlayerManager playerManager; + private readonly IPlayerManager playerManager; - public GameHistoryEnqueueTechProcessor() - { - playerManager = Multiplayer.Session.Network.PlayerManager; - } + public GameHistoryEnqueueTechProcessor() + { + playerManager = Multiplayer.Session.Network.PlayerManager; + } - public override void ProcessPacket(GameHistoryEnqueueTechPacket packet, NebulaConnection conn) + public override void ProcessPacket(GameHistoryEnqueueTechPacket packet, NebulaConnection conn) + { + if (IsHost) { - if (IsHost) - { - INebulaPlayer player = playerManager.GetPlayer(conn); - if (player != null) - { - using (Multiplayer.Session.History.IsIncomingRequest.On()) - { - GameMain.history.EnqueueTech(packet.TechId); - } - playerManager.SendPacketToOtherPlayers(packet, player); - } - } - else + var player = playerManager.GetPlayer(conn); + if (player != null) { using (Multiplayer.Session.History.IsIncomingRequest.On()) { GameMain.history.EnqueueTech(packet.TechId); } + playerManager.SendPacketToOtherPlayers(packet, player); + } + } + else + { + using (Multiplayer.Session.History.IsIncomingRequest.On()) + { + GameMain.history.EnqueueTech(packet.TechId); } - } } } diff --git a/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryFeatureKeyProcessor.cs b/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryFeatureKeyProcessor.cs index 719459ca8..9fa9ae85e 100644 --- a/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryFeatureKeyProcessor.cs +++ b/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryFeatureKeyProcessor.cs @@ -1,37 +1,41 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.GameHistory; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.GameHistory +#endregion + +namespace NebulaNetwork.PacketProcessors.GameHistory; + +[RegisterPacketProcessor] +internal class GameHistoryFeatureKeyProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class GameHistoryFeatureKeyProcessor : PacketProcessor + public override void ProcessPacket(GameHistoryFeatureKeyPacket packet, NebulaConnection conn) { - public override void ProcessPacket(GameHistoryFeatureKeyPacket packet, NebulaConnection conn) + if (IsHost) { - if (IsHost) + Multiplayer.Session.Network.SendPacketExclude(packet, conn); + } + + using (Multiplayer.Session.History.IsIncomingRequest.On()) + { + if (packet.Add) { - Multiplayer.Session.Network.SendPacketExclude(packet, conn); + GameMain.data.history.RegFeatureKey(packet.FeatureId); } - - using (Multiplayer.Session.History.IsIncomingRequest.On()) + else { - if (packet.Add) - { - GameMain.data.history.RegFeatureKey(packet.FeatureId); - } - else - { - GameMain.data.history.UnregFeatureKey(packet.FeatureId); - } + GameMain.data.history.UnregFeatureKey(packet.FeatureId); + } - if (packet.FeatureId == 1100002) - { - // Update Quick Build button in dyson editor - UIRoot.instance.uiGame.dysonEditor.controlPanel.inspector.overview.autoConstructSwitch.SetToggleNoEvent(packet.Add); - } + if (packet.FeatureId == 1100002) + { + // Update Quick Build button in dyson editor + UIRoot.instance.uiGame.dysonEditor.controlPanel.inspector.overview.autoConstructSwitch + .SetToggleNoEvent(packet.Add); } } } diff --git a/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryNotificationProcessor.cs b/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryNotificationProcessor.cs index 6bf5fde06..fcbb3c387 100644 --- a/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryNotificationProcessor.cs +++ b/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryNotificationProcessor.cs @@ -1,36 +1,39 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.GameHistory; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.GameHistory +#endregion + +namespace NebulaNetwork.PacketProcessors.GameHistory; + +[RegisterPacketProcessor] +internal class GameHistoryNotificationProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class GameHistoryNotificationProcessor : PacketProcessor + public override void ProcessPacket(GameHistoryNotificationPacket packet, NebulaConnection conn) { - public override void ProcessPacket(GameHistoryNotificationPacket packet, NebulaConnection conn) + if (IsHost && packet.Event != GameHistoryEvent.OneKeyUnlock) { - if (IsHost && packet.Event != GameHistoryEvent.OneKeyUnlock) - { - Multiplayer.Session.Network.SendPacketExclude(packet, conn); - } + Multiplayer.Session.Network.SendPacketExclude(packet, conn); + } - using (Multiplayer.Session.History.IsIncomingRequest.On()) + using (Multiplayer.Session.History.IsIncomingRequest.On()) + { + switch (packet.Event) { - switch (packet.Event) - { - case GameHistoryEvent.ResumeQueue: - GameMain.history.ResumeTechQueue(); - break; - case GameHistoryEvent.PauseQueue: - GameMain.history.PauseTechQueue(); - break; - case GameHistoryEvent.OneKeyUnlock: - UIRoot.instance.uiGame.techTree.Do1KeyUnlock(); - break; - } + case GameHistoryEvent.ResumeQueue: + GameMain.history.ResumeTechQueue(); + break; + case GameHistoryEvent.PauseQueue: + GameMain.history.PauseTechQueue(); + break; + case GameHistoryEvent.OneKeyUnlock: + UIRoot.instance.uiGame.techTree.Do1KeyUnlock(); + break; } } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryRemoveTechProcessor.cs b/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryRemoveTechProcessor.cs index 7fbe44fe7..33a0ef84d 100644 --- a/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryRemoveTechProcessor.cs +++ b/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryRemoveTechProcessor.cs @@ -1,51 +1,55 @@ -using NebulaAPI; +#region + +using System; +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.GameHistory; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.GameHistory +#endregion + +namespace NebulaNetwork.PacketProcessors.GameHistory; + +[RegisterPacketProcessor] +internal class GameHistoryRemoveTechProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class GameHistoryRemoveTechProcessor : PacketProcessor - { - private readonly IPlayerManager playerManager; + private readonly IPlayerManager playerManager; - public GameHistoryRemoveTechProcessor() - { - playerManager = Multiplayer.Session.Network.PlayerManager; - } + public GameHistoryRemoveTechProcessor() + { + playerManager = Multiplayer.Session.Network.PlayerManager; + } - public override void ProcessPacket(GameHistoryRemoveTechPacket packet, NebulaConnection conn) + public override void ProcessPacket(GameHistoryRemoveTechPacket packet, NebulaConnection conn) + { + var valid = true; + if (IsHost) { - bool valid = true; - if (IsHost) + var player = playerManager.GetPlayer(conn); + if (player != null) { - INebulaPlayer player = playerManager.GetPlayer(conn); - if (player != null) - { - playerManager.SendPacketToOtherPlayers(packet, player); - } - else - { - valid = false; - } + playerManager.SendPacketToOtherPlayers(packet, player); } + else + { + valid = false; + } + } - if (valid) + if (valid) + { + using (Multiplayer.Session.History.IsIncomingRequest.On()) { - using (Multiplayer.Session.History.IsIncomingRequest.On()) + var index = Array.IndexOf(GameMain.history.techQueue, packet.TechId); + //sanity: packet wanted to remove tech, which is not queued on this client, ignore it + if (index < 0) { - int index = System.Array.IndexOf(GameMain.history.techQueue, packet.TechId); - //sanity: packet wanted to remove tech, which is not queued on this client, ignore it - if (index < 0) - { - Log.Warn($"ProcessPacket: TechId: {packet.TechId} was not in queue, discarding packet"); - return; - } - GameMain.history.RemoveTechInQueue(index); + Log.Warn($"ProcessPacket: TechId: {packet.TechId} was not in queue, discarding packet"); + return; } + GameMain.history.RemoveTechInQueue(index); } } } diff --git a/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryResearchContributionProcessor.cs b/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryResearchContributionProcessor.cs index 0785ac7d9..c5131ab8d 100644 --- a/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryResearchContributionProcessor.cs +++ b/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryResearchContributionProcessor.cs @@ -1,35 +1,37 @@ -using NebulaAPI; -using NebulaModel; +#region + +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.GameHistory; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.GameHistory +#endregion + +namespace NebulaNetwork.PacketProcessors.GameHistory; + +[RegisterPacketProcessor] +internal class GameHistoryResearchContributionProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class GameHistoryResearchContributionProcessor : PacketProcessor + public override void ProcessPacket(GameHistoryResearchContributionPacket packet, NebulaConnection conn) { - public override void ProcessPacket(GameHistoryResearchContributionPacket packet, NebulaConnection conn) + if (IsClient) { - if (IsClient) - { - return; - } + return; + } - //Check if client is contributing to the correct Tech Research - if (packet.TechId == GameMain.history.currentTech) - { - GameMain.history.AddTechHash(packet.Hashes); - IPlayerManager playerManager = Multiplayer.Session.Network.PlayerManager; - Log.Debug($"ProcessPacket researchContribution: playerid by: {playerManager.GetPlayer(conn).Id} - hashes {packet.Hashes}"); - } - else - { - Log.Info($"ProcessPacket researchContribution: got package for different tech ({packet.TechId})"); - } + //Check if client is contributing to the correct Tech Research + if (packet.TechId == GameMain.history.currentTech) + { + GameMain.history.AddTechHash(packet.Hashes); + IPlayerManager playerManager = Multiplayer.Session.Network.PlayerManager; + Log.Debug( + $"ProcessPacket researchContribution: playerid by: {playerManager.GetPlayer(conn).Id} - hashes {packet.Hashes}"); + } + else + { + Log.Info($"ProcessPacket researchContribution: got package for different tech ({packet.TechId})"); } } } - diff --git a/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryResearchUpdateProcessor.cs b/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryResearchUpdateProcessor.cs index 360816324..6b8c673d2 100644 --- a/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryResearchUpdateProcessor.cs +++ b/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryResearchUpdateProcessor.cs @@ -1,29 +1,33 @@ -using NebulaAPI; +#region + +using NebulaAPI; +using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.GameHistory; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.GameHistory +#endregion + +namespace NebulaNetwork.PacketProcessors.GameHistory; + +[RegisterPacketProcessor] +internal class GameHistoryResearchUpdateProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class GameHistoryResearchUpdateProcessor : PacketProcessor + public override void ProcessPacket(GameHistoryResearchUpdatePacket packet, NebulaConnection conn) { - public override void ProcessPacket(GameHistoryResearchUpdatePacket packet, NebulaConnection conn) + var data = GameMain.data.history; + if (packet.TechId != data.currentTech) { - GameHistoryData data = GameMain.data.history; - if (packet.TechId != data.currentTech) - { - NebulaModel.Logger.Log.Warn($"CurrentTech mismatch! Server:{packet.TechId} Local:{data.currentTech}"); - //Replace currentTech to match with server - data.currentTech = packet.TechId; - data.techQueue[0] = packet.TechId; - } - TechState state = data.techStates[data.currentTech]; - state.hashUploaded = packet.HashUploaded; - state.hashNeeded = packet.HashNeeded; - data.techStates[data.currentTech] = state; - Multiplayer.Session.Statistics.TechHashedFor10Frames = packet.TechHashedFor10Frames; + Log.Warn($"CurrentTech mismatch! Server:{packet.TechId} Local:{data.currentTech}"); + //Replace currentTech to match with server + data.currentTech = packet.TechId; + data.techQueue[0] = packet.TechId; } + var state = data.techStates[data.currentTech]; + state.hashUploaded = packet.HashUploaded; + state.hashNeeded = packet.HashNeeded; + data.techStates[data.currentTech] = state; + Multiplayer.Session.Statistics.TechHashedFor10Frames = packet.TechHashedFor10Frames; } } diff --git a/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryTechRefundProcessor.cs b/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryTechRefundProcessor.cs index 2f274d61e..6b4dbd5cd 100644 --- a/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryTechRefundProcessor.cs +++ b/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryTechRefundProcessor.cs @@ -1,52 +1,54 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.GameHistory; -using System.Collections.Generic; -namespace NebulaNetwork.PacketProcessors.GameHistory +#endregion + +namespace NebulaNetwork.PacketProcessors.GameHistory; + +[RegisterPacketProcessor] +internal class GameHistoryTechRefundProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class GameHistoryTechRefundProcessor : PacketProcessor + public override void ProcessPacket(GameHistoryTechRefundPacket packet, NebulaConnection conn) { - public override void ProcessPacket(GameHistoryTechRefundPacket packet, NebulaConnection conn) - { - // TODO: TRY TO MERGE THESE BETTER + // TODO: TRY TO MERGE THESE BETTER - if (IsHost) + if (IsHost) + { + //only refund if we have contributed + if (packet.TechHashedContributed > 0) { - //only refund if we have contributed - if (packet.TechHashedContributed > 0) + //client should have the same research queued, seek currently needed itemIds and re-add points that were contributed + var itemPoints = GameMain.data.mainPlayer.mecha.lab.itemPoints; + foreach (var item in itemPoints.items) { - //client should have the same research queued, seek currently needed itemIds and re-add points that were contributed - ItemBundle itemPoints = GameMain.data.mainPlayer.mecha.lab.itemPoints; - foreach (KeyValuePair item in itemPoints.items) - { - itemPoints.Alter(item.Key, (int)packet.TechHashedContributed * 3600); - } - //let the default method give back the items - GameMain.mainPlayer.mecha.lab.ManageTakeback(); + itemPoints.Alter(item.Key, (int)packet.TechHashedContributed * 3600); } + //let the default method give back the items + GameMain.mainPlayer.mecha.lab.ManageTakeback(); } - else + } + else + { + //only refund if we have contributed + if (packet.TechHashedContributed > 0) { - //only refund if we have contributed - if (packet.TechHashedContributed > 0) - { - TechProto techProto = LDB.techs.Select(packet.TechIdContributed); - int[] items = techProto.Items; - int[] array = techProto.ItemPoints; + var techProto = LDB.techs.Select(packet.TechIdContributed); + var items = techProto.Items; + var array = techProto.ItemPoints; - //client should have the same research queued, seek currently needed itemIds and re-add points that were contributed - for (int i = 0; i < array.Length; i++) - { - int itemId = items[i]; - int contributedItems = (int)packet.TechHashedContributed * array[i]; - GameMain.data.mainPlayer.mecha.lab.itemPoints.Alter(itemId, contributedItems); - } - //let the default method give back the items - GameMain.mainPlayer.mecha.lab.ManageTakeback(); + //client should have the same research queued, seek currently needed itemIds and re-add points that were contributed + for (var i = 0; i < array.Length; i++) + { + var itemId = items[i]; + var contributedItems = (int)packet.TechHashedContributed * array[i]; + GameMain.data.mainPlayer.mecha.lab.itemPoints.Alter(itemId, contributedItems); } + //let the default method give back the items + GameMain.mainPlayer.mecha.lab.ManageTakeback(); } } } diff --git a/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryUnlockTechProcessor.cs b/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryUnlockTechProcessor.cs index 924f877a3..7114ce056 100644 --- a/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryUnlockTechProcessor.cs +++ b/NebulaNetwork/PacketProcessors/GameHistory/GameHistoryUnlockTechProcessor.cs @@ -1,31 +1,34 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.GameHistory; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.GameHistory +#endregion + +namespace NebulaNetwork.PacketProcessors.GameHistory; + +[RegisterPacketProcessor] +internal class GameHistoryUnlockTechProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class GameHistoryUnlockTechProcessor : PacketProcessor + public override void ProcessPacket(GameHistoryUnlockTechPacket packet, NebulaConnection conn) { - public override void ProcessPacket(GameHistoryUnlockTechPacket packet, NebulaConnection conn) + using (Multiplayer.Session.History.IsIncomingRequest.On()) { - using (Multiplayer.Session.History.IsIncomingRequest.On()) - { - // Let the default method give back the items - GameMain.mainPlayer.mecha.lab.ManageTakeback(); + // Let the default method give back the items + GameMain.mainPlayer.mecha.lab.ManageTakeback(); - // Update techState - TechState techState = GameMain.history.techStates[packet.TechId]; - Log.Info($"Unlocking tech={packet.TechId} local:{techState.curLevel} remote:{packet.Level}"); - techState.curLevel = packet.Level; - GameMain.history.techStates[packet.TechId] = techState; + // Update techState + var techState = GameMain.history.techStates[packet.TechId]; + Log.Info($"Unlocking tech={packet.TechId} local:{techState.curLevel} remote:{packet.Level}"); + techState.curLevel = packet.Level; + GameMain.history.techStates[packet.TechId] = techState; - GameMain.history.UnlockTechUnlimited(packet.TechId, false); - GameMain.history.DequeueTech(); - } + GameMain.history.UnlockTechUnlimited(packet.TechId, false); + GameMain.history.DequeueTech(); } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/GameStates/FragmentInfoProcessor.cs b/NebulaNetwork/PacketProcessors/GameStates/FragmentInfoProcessor.cs index 36ab1e2cd..48c3f0e84 100644 --- a/NebulaNetwork/PacketProcessors/GameStates/FragmentInfoProcessor.cs +++ b/NebulaNetwork/PacketProcessors/GameStates/FragmentInfoProcessor.cs @@ -1,20 +1,23 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.GameStates; using NebulaWorld.GameStates; -namespace NebulaNetwork.PacketProcessors.GameStates +#endregion + +namespace NebulaNetwork.PacketProcessors.GameStates; + +[RegisterPacketProcessor] +public class FragmentInfoProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class FragmentInfoProcessor : PacketProcessor + public override void ProcessPacket(FragmentInfo packet, NebulaConnection conn) { - public override void ProcessPacket(FragmentInfo packet, NebulaConnection conn) + if (IsClient) { - if (IsClient) - { - GameStatesManager.FragmentSize = packet.Size; - } + GameStatesManager.FragmentSize = packet.Size; } } } diff --git a/NebulaNetwork/PacketProcessors/GameStates/GameStateRequestProcessor.cs b/NebulaNetwork/PacketProcessors/GameStates/GameStateRequestProcessor.cs index 2ffa42097..56ae45ea5 100644 --- a/NebulaNetwork/PacketProcessors/GameStates/GameStateRequestProcessor.cs +++ b/NebulaNetwork/PacketProcessors/GameStates/GameStateRequestProcessor.cs @@ -1,24 +1,28 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.GameStates; using NebulaWorld.GameStates; -namespace NebulaNetwork.PacketProcessors.GameStates +#endregion + +namespace NebulaNetwork.PacketProcessors.GameStates; + +[RegisterPacketProcessor] +internal class GameStateRequestProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class GameStateRequestProcessor : PacketProcessor + public override void ProcessPacket(GameStateRequest packet, NebulaConnection conn) { - public override void ProcessPacket(GameStateRequest packet, NebulaConnection conn) + if (IsHost) + { + conn.SendPacket( + new GameStateUpdate(packet.SentTimestamp, GameStatesManager.RealGameTick, GameStatesManager.RealUPS)); + } + else { - if (IsHost) - { - conn.SendPacket(new GameStateUpdate(packet.SentTimestamp, GameStatesManager.RealGameTick, GameStatesManager.RealUPS)); - } - else - { - conn.SendPacket(packet); - } + conn.SendPacket(packet); } } } diff --git a/NebulaNetwork/PacketProcessors/GameStates/GameStateUpdateProcessor.cs b/NebulaNetwork/PacketProcessors/GameStates/GameStateUpdateProcessor.cs index 163c1dce2..62392ccb5 100644 --- a/NebulaNetwork/PacketProcessors/GameStates/GameStateUpdateProcessor.cs +++ b/NebulaNetwork/PacketProcessors/GameStates/GameStateUpdateProcessor.cs @@ -1,4 +1,7 @@ -using NebulaAPI; +#region + +using System; +using NebulaAPI; using NebulaModel; using NebulaModel.Logger; using NebulaModel.Networking; @@ -6,93 +9,94 @@ using NebulaModel.Packets.GameStates; using NebulaWorld; using NebulaWorld.GameStates; -using System; using UnityEngine; -namespace NebulaNetwork.PacketProcessors.GameStates +#endregion + +namespace NebulaNetwork.PacketProcessors.GameStates; + +[RegisterPacketProcessor] +public class GameStateUpdateProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class GameStateUpdateProcessor : PacketProcessor - { - public float BUFFERING_TIME = 30f; - public float BUFFERING_TICK = 60f; + private float avaerageUPS = 60f; - private int averageRTT; - private float avaerageUPS = 60f; - private bool hasChanged; + private int averageRTT; + public float BUFFERING_TICK = 60f; + public float BUFFERING_TIME = 30f; + private bool hasChanged; - public override void ProcessPacket(GameStateUpdate packet, NebulaConnection conn) - { - long rtt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - packet.SentTime; - averageRTT = (int)(averageRTT * 0.8 + rtt * 0.2); - avaerageUPS = avaerageUPS * 0.8f + packet.UnitsPerSecond * 0.2f; - Multiplayer.Session.World.UpdatePingIndicator($"Ping: {averageRTT}ms"); + public override void ProcessPacket(GameStateUpdate packet, NebulaConnection conn) + { + var rtt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - packet.SentTime; + averageRTT = (int)(averageRTT * 0.8 + rtt * 0.2); + avaerageUPS = avaerageUPS * 0.8f + packet.UnitsPerSecond * 0.2f; + Multiplayer.Session.World.UpdatePingIndicator($"Ping: {averageRTT}ms"); - // We offset the tick received to account for the time it took to receive the packet - long tickOffsetSinceSent = (long)Math.Round(packet.UnitsPerSecond * rtt / 2 / 1000); - long currentGameTick = packet.GameTick + tickOffsetSinceSent; - long diff = currentGameTick - GameMain.gameTick; + // We offset the tick received to account for the time it took to receive the packet + var tickOffsetSinceSent = (long)Math.Round(packet.UnitsPerSecond * rtt / 2 / 1000); + var currentGameTick = packet.GameTick + tickOffsetSinceSent; + var diff = currentGameTick - GameMain.gameTick; - // Discard abnormal packet (usually after host saving the file) - if (rtt > 2 * averageRTT || avaerageUPS - packet.UnitsPerSecond > 15) + // Discard abnormal packet (usually after host saving the file) + if (rtt > 2 * averageRTT || avaerageUPS - packet.UnitsPerSecond > 15) + { + // Initial connetion + if (GameMain.gameTick < 1200L) { - // Initial connetion - if (GameMain.gameTick < 1200L) - { - averageRTT = (int)rtt; - GameMain.gameTick = currentGameTick; - } - Log.Debug($"GameStateUpdate unstable. RTT:{rtt}(avg{averageRTT}) UPS:{packet.UnitsPerSecond:F2}(avg{avaerageUPS:F2})"); - return; + averageRTT = (int)rtt; + GameMain.gameTick = currentGameTick; } + Log.Debug( + $"GameStateUpdate unstable. RTT:{rtt}(avg{averageRTT}) UPS:{packet.UnitsPerSecond:F2}(avg{avaerageUPS:F2})"); + return; + } - if (!Config.Options.SyncUps) + if (!Config.Options.SyncUps) + { + // We allow for a small drift of 5 ticks since the tick offset using the ping is only an approximation + if (GameMain.gameTick > 0 && Mathf.Abs(diff) > 5) { - // We allow for a small drift of 5 ticks since the tick offset using the ping is only an approximation - if (GameMain.gameTick > 0 && Mathf.Abs(diff) > 5) - { - Log.Info($"Game Tick got updated since it was desynced, was {GameMain.gameTick}, diff={diff}"); - GameMain.gameTick = currentGameTick; - } - // Reset FixUPS when user turns off the option - if (hasChanged) - { - FPSController.SetFixUPS(0); - hasChanged = false; - } - return; + Log.Info($"Game Tick got updated since it was desynced, was {GameMain.gameTick}, diff={diff}"); + GameMain.gameTick = currentGameTick; } - - // Adjust client's UPS to match game tick with server, range 30~120 UPS - float UPS = diff / 1f + avaerageUPS; - long skipTick = 0; - if (UPS > GameStatesManager.MaxUPS) + // Reset FixUPS when user turns off the option + if (hasChanged) { - // Try to disturbute game tick difference into BUFFERING_TIME (seconds) - if (diff / BUFFERING_TIME + avaerageUPS > GameStatesManager.MaxUPS) - { - // The difference is too large, need to skip ticks to catch up - skipTick = (long)(UPS - GameStatesManager.MaxUPS); - } - UPS = GameStatesManager.MaxUPS; + FPSController.SetFixUPS(0); + hasChanged = false; } - else if (UPS < GameStatesManager.MinUPS) + return; + } + + // Adjust client's UPS to match game tick with server, range 30~120 UPS + var UPS = diff / 1f + avaerageUPS; + long skipTick = 0; + if (UPS > GameStatesManager.MaxUPS) + { + // Try to disturbute game tick difference into BUFFERING_TIME (seconds) + if (diff / BUFFERING_TIME + avaerageUPS > GameStatesManager.MaxUPS) { - if (diff + avaerageUPS - GameStatesManager.MinUPS < -BUFFERING_TICK) - { - skipTick = (long)(UPS - GameStatesManager.MinUPS); - } - UPS = GameStatesManager.MinUPS; + // The difference is too large, need to skip ticks to catch up + skipTick = (long)(UPS - GameStatesManager.MaxUPS); } - if (skipTick != 0) + UPS = GameStatesManager.MaxUPS; + } + else if (UPS < GameStatesManager.MinUPS) + { + if (diff + avaerageUPS - GameStatesManager.MinUPS < -BUFFERING_TICK) { - Log.Info($"Game Tick was desynced. skip={skipTick} diff={diff,2}, RTT={rtt}ms, UPS={packet.UnitsPerSecond:F2}"); - GameMain.gameTick += skipTick; + skipTick = (long)(UPS - GameStatesManager.MinUPS); } - FPSController.SetFixUPS(UPS); - hasChanged = true; - // Tick difference in the next second. Expose for other mods - GameStatesManager.NotifyTickDifference((diff / 1f + avaerageUPS) - UPS); + UPS = GameStatesManager.MinUPS; + } + if (skipTick != 0) + { + Log.Info($"Game Tick was desynced. skip={skipTick} diff={diff,2}, RTT={rtt}ms, UPS={packet.UnitsPerSecond:F2}"); + GameMain.gameTick += skipTick; } + FPSController.SetFixUPS(UPS); + hasChanged = true; + // Tick difference in the next second. Expose for other mods + GameStatesManager.NotifyTickDifference(diff / 1f + avaerageUPS - UPS); } } diff --git a/NebulaNetwork/PacketProcessors/Logistics/DispenserAddTakeProcessor.cs b/NebulaNetwork/PacketProcessors/Logistics/DispenserAddTakeProcessor.cs index ac45346eb..3fcaf98af 100644 --- a/NebulaNetwork/PacketProcessors/Logistics/DispenserAddTakeProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Logistics/DispenserAddTakeProcessor.cs @@ -1,53 +1,57 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Logistics; using NebulaWorld; -using System; -namespace NebulaNetwork.PacketProcessors.Logistics +#endregion + +namespace NebulaNetwork.PacketProcessors.Logistics; + +[RegisterPacketProcessor] +internal class DispenserAddTakeProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class DispenserAddTakeProcessor : PacketProcessor + public override void ProcessPacket(DispenserAddTakePacket packet, NebulaConnection conn) { - public override void ProcessPacket(DispenserAddTakePacket packet, NebulaConnection conn) + var factory = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory; + var pool = factory?.entityPool; + if (pool != null && packet.EntityId > 0 && packet.EntityId < pool.Length && pool[packet.EntityId].id == packet.EntityId) { - PlanetFactory factory = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory; - EntityData[] pool = factory?.entityPool; - if (pool != null && packet.EntityId > 0 && packet.EntityId < pool.Length && pool[packet.EntityId].id == packet.EntityId) + using (Multiplayer.Session.Storage.IsIncomingRequest.On()) { - using (Multiplayer.Session.Storage.IsIncomingRequest.On()) + switch (packet.AddTakeEvent) { - switch (packet.AddTakeEvent) - { - case EDispenserAddTakeEvent.ManualAdd: - factory.InsertIntoStorage(packet.EntityId, packet.ItemId, packet.ItemCount, packet.ItemInc, out int _, false); - break; + case EDispenserAddTakeEvent.ManualAdd: + factory.InsertIntoStorage(packet.EntityId, packet.ItemId, packet.ItemCount, packet.ItemInc, out var _, + false); + break; - case EDispenserAddTakeEvent.ManualTake: - factory.PickFromStorage(packet.EntityId, packet.ItemId, packet.ItemCount, out int _); - break; + case EDispenserAddTakeEvent.ManualTake: + factory.PickFromStorage(packet.EntityId, packet.ItemId, packet.ItemCount, out var _); + break; - case EDispenserAddTakeEvent.CourierAdd: - int addCount = factory.InsertIntoStorage(packet.EntityId, packet.ItemId, packet.ItemCount, packet.ItemInc, out int _, false); - int remainCount = packet.ItemCount - addCount; - if (remainCount > 0) - { - Log.Warn($"{GameMain.galaxy.PlanetById(packet.PlanetId)} - CourierAdd remain: {remainCount}"); - } - break; + case EDispenserAddTakeEvent.CourierAdd: + var addCount = factory.InsertIntoStorage(packet.EntityId, packet.ItemId, packet.ItemCount, + packet.ItemInc, out var _, false); + var remainCount = packet.ItemCount - addCount; + if (remainCount > 0) + { + Log.Warn($"{GameMain.galaxy.PlanetById(packet.PlanetId)} - CourierAdd remain: {remainCount}"); + } + break; - case EDispenserAddTakeEvent.CourierTake: - factory.PickFromStorage(packet.EntityId, packet.ItemId, packet.ItemCount, out int _); - break; - } + case EDispenserAddTakeEvent.CourierTake: + factory.PickFromStorage(packet.EntityId, packet.ItemId, packet.ItemCount, out var _); + break; } } - else if (pool != null) - { - Log.Warn($"DispenserSettingPacket: Can't find dispenser ({packet.PlanetId}, {packet.EntityId})"); - } + } + else if (pool != null) + { + Log.Warn($"DispenserSettingPacket: Can't find dispenser ({packet.PlanetId}, {packet.EntityId})"); } } } diff --git a/NebulaNetwork/PacketProcessors/Logistics/DispenserCourierProcessor.cs b/NebulaNetwork/PacketProcessors/Logistics/DispenserCourierProcessor.cs index b140de336..2332a8cde 100644 --- a/NebulaNetwork/PacketProcessors/Logistics/DispenserCourierProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Logistics/DispenserCourierProcessor.cs @@ -1,28 +1,32 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Logistics; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Logistics +#endregion + +namespace NebulaNetwork.PacketProcessors.Logistics; + +[RegisterPacketProcessor] +internal class DispenserCourierProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class DispenserCourierProcessor : PacketProcessor + public override void ProcessPacket(DispenserCourierPacket packet, NebulaConnection conn) { - public override void ProcessPacket(DispenserCourierPacket packet, NebulaConnection conn) + var factory = GameMain.mainPlayer.factory; + var pool = factory?.transport.dispenserPool; + if (GameMain.mainPlayer.planetId != packet.PlanetId || pool == null) + { + return; + } + if (packet.DispenserId > 0 && packet.DispenserId < pool.Length && pool[packet.DispenserId] != null) { - PlanetFactory factory = GameMain.mainPlayer.factory; - DispenserComponent[] pool = factory?.transport.dispenserPool; - if (GameMain.mainPlayer.planetId != packet.PlanetId || pool == null) - { - return; - } - if (packet.DispenserId > 0 && packet.DispenserId < pool.Length && pool[packet.DispenserId] != null) - { - DispenserComponent dispenser = pool[packet.DispenserId]; - Multiplayer.Session.Couriers.AddCourier(packet.PlayerId, factory.entityPool[dispenser.entityId].pos, packet.ItemId, packet.ItemCount); - dispenser.pulseSignal = 2; - } + var dispenser = pool[packet.DispenserId]; + Multiplayer.Session.Couriers.AddCourier(packet.PlayerId, factory.entityPool[dispenser.entityId].pos, packet.ItemId, + packet.ItemCount); + dispenser.pulseSignal = 2; } } } diff --git a/NebulaNetwork/PacketProcessors/Logistics/DispenserSettingProcessor.cs b/NebulaNetwork/PacketProcessors/Logistics/DispenserSettingProcessor.cs index ad8fbc40d..71599862f 100644 --- a/NebulaNetwork/PacketProcessors/Logistics/DispenserSettingProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Logistics/DispenserSettingProcessor.cs @@ -1,92 +1,98 @@ -using NebulaAPI; +#region + +using System; +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Logistics; using NebulaWorld; -using System; -namespace NebulaNetwork.PacketProcessors.Logistics +#endregion + +namespace NebulaNetwork.PacketProcessors.Logistics; + +[RegisterPacketProcessor] +internal class DispenserSettingProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class DispenserSettingProcessor : PacketProcessor + public override void ProcessPacket(DispenserSettingPacket packet, NebulaConnection conn) { - public override void ProcessPacket(DispenserSettingPacket packet, NebulaConnection conn) + var factory = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory; + var pool = factory?.transport.dispenserPool; + if (pool != null && packet.DispenserId > 0 && packet.DispenserId < pool.Length && + pool[packet.DispenserId].id == packet.DispenserId) { - PlanetFactory factory = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory; - DispenserComponent[] pool = factory?.transport.dispenserPool; - if (pool != null && packet.DispenserId > 0 && packet.DispenserId < pool.Length && pool[packet.DispenserId].id == packet.DispenserId) - { - ref DispenserComponent dispenserComponent = ref pool[packet.DispenserId]; + ref var dispenserComponent = ref pool[packet.DispenserId]; - using (Multiplayer.Session.StationsUI.IsIncomingRequest.On()) + using (Multiplayer.Session.StationsUI.IsIncomingRequest.On()) + { + switch (packet.Event) { - switch (packet.Event) - { - case EDispenserSettingEvent.SetCourierCount: - int newCourierCount = packet.Parameter1; - if (dispenserComponent.workCourierCount > newCourierCount) - { - string warnText = string.Format("{0} [{1}] Working courier decrease from {2} to {3}", - GameMain.galaxy.PlanetById(packet.PlanetId).displayName, packet.DispenserId, dispenserComponent.workCourierCount, newCourierCount); - Log.Debug(warnText); - dispenserComponent.workCourierCount = newCourierCount; - } - dispenserComponent.idleCourierCount = newCourierCount - dispenserComponent.workCourierCount; - break; + case EDispenserSettingEvent.SetCourierCount: + var newCourierCount = packet.Parameter1; + if (dispenserComponent.workCourierCount > newCourierCount) + { + var warnText = string.Format("{0} [{1}] Working courier decrease from {2} to {3}", + GameMain.galaxy.PlanetById(packet.PlanetId).displayName, packet.DispenserId, + dispenserComponent.workCourierCount, newCourierCount); + Log.Debug(warnText); + dispenserComponent.workCourierCount = newCourierCount; + } + dispenserComponent.idleCourierCount = newCourierCount - dispenserComponent.workCourierCount; + break; - case EDispenserSettingEvent.ToggleAutoReplenish: - dispenserComponent.courierAutoReplenish = packet.Parameter1 != 0; - break; + case EDispenserSettingEvent.ToggleAutoReplenish: + dispenserComponent.courierAutoReplenish = packet.Parameter1 != 0; + break; - case EDispenserSettingEvent.SetMaxChargePower: - float value = BitConverter.ToSingle(BitConverter.GetBytes(packet.Parameter1), 0); - factory.powerSystem.consumerPool[dispenserComponent.pcId].workEnergyPerTick = (long)(5000.0 * value + 0.5); - break; + case EDispenserSettingEvent.SetMaxChargePower: + var value = BitConverter.ToSingle(BitConverter.GetBytes(packet.Parameter1), 0); + factory.powerSystem.consumerPool[dispenserComponent.pcId].workEnergyPerTick = + (long)(5000.0 * value + 0.5); + break; - case EDispenserSettingEvent.SetFilter: - int filter = packet.Parameter1; - if (dispenserComponent.filter != filter) - { - dispenserComponent.filter = filter; - factory.transport.RefreshDispenserTraffic(packet.DispenserId); - } - break; + case EDispenserSettingEvent.SetFilter: + var filter = packet.Parameter1; + if (dispenserComponent.filter != filter) + { + dispenserComponent.filter = filter; + factory.transport.RefreshDispenserTraffic(packet.DispenserId); + } + break; - case EDispenserSettingEvent.SetPlayerDeliveryMode: - EPlayerDeliveryMode playerDeliveryMode = (EPlayerDeliveryMode)packet.Parameter1; - if (dispenserComponent.playerMode != playerDeliveryMode) - { - dispenserComponent.playerMode = playerDeliveryMode; - factory.transport.RefreshDispenserTraffic(packet.DispenserId); - } - break; + case EDispenserSettingEvent.SetPlayerDeliveryMode: + var playerDeliveryMode = (EPlayerDeliveryMode)packet.Parameter1; + if (dispenserComponent.playerMode != playerDeliveryMode) + { + dispenserComponent.playerMode = playerDeliveryMode; + factory.transport.RefreshDispenserTraffic(packet.DispenserId); + } + break; - case EDispenserSettingEvent.SetStorageDeliveryMode: - EStorageDeliveryMode storageDeliveryMode = (EStorageDeliveryMode)packet.Parameter1; - if (dispenserComponent.storageMode != storageDeliveryMode) - { - dispenserComponent.storageMode = storageDeliveryMode; - factory.transport.RefreshDispenserTraffic(packet.DispenserId); - } - break; + case EDispenserSettingEvent.SetStorageDeliveryMode: + var storageDeliveryMode = (EStorageDeliveryMode)packet.Parameter1; + if (dispenserComponent.storageMode != storageDeliveryMode) + { + dispenserComponent.storageMode = storageDeliveryMode; + factory.transport.RefreshDispenserTraffic(packet.DispenserId); + } + break; - default: - Log.Warn($"DispenserSettingPacket: Unkown DispenserSettingEvent {packet.Event}"); - break; - } + default: + Log.Warn($"DispenserSettingPacket: Unkown DispenserSettingEvent {packet.Event}"); + break; + } - UIDispenserWindow uiWindow = UIRoot.instance.uiGame.dispenserWindow; - if (uiWindow.dispenserId == packet.DispenserId && uiWindow.factory?.planetId == packet.PlanetId) - { - uiWindow.OnDispenserIdChange(); - } + var uiWindow = UIRoot.instance.uiGame.dispenserWindow; + if (uiWindow.dispenserId == packet.DispenserId && uiWindow.factory?.planetId == packet.PlanetId) + { + uiWindow.OnDispenserIdChange(); } } - else if (pool != null) - { - Log.Warn($"DispenserSettingPacket: Can't find dispenser ({packet.PlanetId}, {packet.DispenserId})"); - } + } + else if (pool != null) + { + Log.Warn($"DispenserSettingPacket: Can't find dispenser ({packet.PlanetId}, {packet.DispenserId})"); } } } diff --git a/NebulaNetwork/PacketProcessors/Logistics/DispenserStoreProcessor.cs b/NebulaNetwork/PacketProcessors/Logistics/DispenserStoreProcessor.cs index 83d7a0091..d55593928 100644 --- a/NebulaNetwork/PacketProcessors/Logistics/DispenserStoreProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Logistics/DispenserStoreProcessor.cs @@ -1,35 +1,40 @@ -using NebulaAPI; +#region + +using System; +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Logistics; -using System; -namespace NebulaNetwork.PacketProcessors.Logistics +#endregion + +namespace NebulaNetwork.PacketProcessors.Logistics; + +[RegisterPacketProcessor] +internal class DispenserStoreProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class DispenserStoreProcessor : PacketProcessor + public override void ProcessPacket(DispenserStorePacket packet, NebulaConnection conn) { - public override void ProcessPacket(DispenserStorePacket packet, NebulaConnection conn) + var factory = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory; + var pool = factory?.transport.dispenserPool; + if (pool != null && packet.DispenserId > 0 && packet.DispenserId < pool.Length && + pool[packet.DispenserId].id == packet.DispenserId) { - PlanetFactory factory = GameMain.galaxy.PlanetById(packet.PlanetId)?.factory; - DispenserComponent[] pool = factory?.transport.dispenserPool; - if (pool != null && packet.DispenserId > 0 && packet.DispenserId < pool.Length && pool[packet.DispenserId].id == packet.DispenserId) + ref var dispenser = ref pool[packet.DispenserId]; + dispenser.holdupItemCount = packet.HoldupItemCount; + for (var i = 0; i < packet.HoldupItemCount; i++) { - ref DispenserComponent dispenser = ref pool[packet.DispenserId]; - dispenser.holdupItemCount = packet.HoldupItemCount; - for (int i = 0; i < packet.HoldupItemCount; i++) - { - dispenser.holdupPackage[i].itemId = packet.ItemIds[i]; - dispenser.holdupPackage[i].count = packet.Counts[i]; - dispenser.holdupPackage[i].inc = packet.Incs[i]; - } - Array.Clear(dispenser.holdupPackage, dispenser.holdupItemCount, dispenser.holdupPackage.Length - dispenser.holdupItemCount); - } - else if (pool != null) - { - Log.Warn($"DispenserSettingPacket: Can't find dispenser ({packet.PlanetId}, {packet.DispenserId})"); + dispenser.holdupPackage[i].itemId = packet.ItemIds[i]; + dispenser.holdupPackage[i].count = packet.Counts[i]; + dispenser.holdupPackage[i].inc = packet.Incs[i]; } + Array.Clear(dispenser.holdupPackage, dispenser.holdupItemCount, + dispenser.holdupPackage.Length - dispenser.holdupItemCount); + } + else if (pool != null) + { + Log.Warn($"DispenserSettingPacket: Can't find dispenser ({packet.PlanetId}, {packet.DispenserId})"); } } } diff --git a/NebulaNetwork/PacketProcessors/Logistics/ILSAddStationComponentProcessor.cs b/NebulaNetwork/PacketProcessors/Logistics/ILSAddStationComponentProcessor.cs index 37709e727..857175c53 100644 --- a/NebulaNetwork/PacketProcessors/Logistics/ILSAddStationComponentProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Logistics/ILSAddStationComponentProcessor.cs @@ -1,37 +1,41 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Logistics; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Logistics +#endregion + +namespace NebulaNetwork.PacketProcessors.Logistics; + +[RegisterPacketProcessor] +public class ILSAddStationComponentProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class ILSAddStationComponentProcessor : PacketProcessor + public override void ProcessPacket(ILSAddStationComponent packet, NebulaConnection conn) { - public override void ProcessPacket(ILSAddStationComponent packet, NebulaConnection conn) - { - Log.Info($"ILSAddStationComponentProcessor processing packet for planet {packet.PlanetId}, station {packet.StationId} with gId of {packet.StationGId}"); + Log.Info( + $"ILSAddStationComponentProcessor processing packet for planet {packet.PlanetId}, station {packet.StationId} with gId of {packet.StationGId}"); - using (Multiplayer.Session.Ships.PatchLockILS.On()) + using (Multiplayer.Session.Ships.PatchLockILS.On()) + { + var galacticTransport = GameMain.data.galacticTransport; + var stationPool = GameMain.galaxy.PlanetById(packet.PlanetId).factory?.transport.stationPool; + if (stationPool != null) + { + // If we have loaded the factory where the new station was created on, should be able to find + // it in our PlanetTransport.stationPool + // Assgin gid here so this station will go to galacticTransport.stationPool[gid] + stationPool[packet.StationId].gid = packet.StationGId; + galacticTransport.AddStationComponent(packet.PlanetId, stationPool[packet.StationId]); + } + else { - GalacticTransport galacticTransport = GameMain.data.galacticTransport; - StationComponent[] stationPool = GameMain.galaxy.PlanetById(packet.PlanetId).factory?.transport.stationPool; - if (stationPool != null) - { - // If we have loaded the factory where the new station was created on, should be able to find - // it in our PlanetTransport.stationPool - // Assgin gid here so this station will go to galacticTransport.stationPool[gid] - stationPool[packet.StationId].gid = packet.StationGId; - galacticTransport.AddStationComponent(packet.PlanetId, stationPool[packet.StationId]); - } - else - { - // If we haven't loaded the factory the new station was create on, we need to create a - // "fake" station that we can put into the GalacticTransport.stationPool instead of a real on - Multiplayer.Session.Ships.CreateFakeStationComponent(packet.StationGId, packet.PlanetId, packet.MaxShipCount); - } + // If we haven't loaded the factory the new station was create on, we need to create a + // "fake" station that we can put into the GalacticTransport.stationPool instead of a real on + Multiplayer.Session.Ships.CreateFakeStationComponent(packet.StationGId, packet.PlanetId, packet.MaxShipCount); } } } diff --git a/NebulaNetwork/PacketProcessors/Logistics/ILSArriveStarPlanetRequestProcessor.cs b/NebulaNetwork/PacketProcessors/Logistics/ILSArriveStarPlanetRequestProcessor.cs index f02711c32..bb77cdd54 100644 --- a/NebulaNetwork/PacketProcessors/Logistics/ILSArriveStarPlanetRequestProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Logistics/ILSArriveStarPlanetRequestProcessor.cs @@ -1,111 +1,114 @@ -using NebulaAPI; +#region + +using System.Collections.Generic; +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Logistics; using NebulaWorld; -using System.Collections.Generic; + +#endregion /* * when a client arrives at a star he needs to sync the ILS storages as update events are sent only to corresponding stars * and also to sync the belt filters conencted to the ILS */ -namespace NebulaNetwork.PacketProcessors.Logistics +namespace NebulaNetwork.PacketProcessors.Logistics; + +[RegisterPacketProcessor] +internal class ILSArriveStarPlanetRequestProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class ILSArriveStarPlanetRequestProcessor : PacketProcessor + private readonly IPlayerManager playerManager; + + public ILSArriveStarPlanetRequestProcessor() { - private readonly IPlayerManager playerManager; + playerManager = Multiplayer.Session.Network.PlayerManager; + } - public ILSArriveStarPlanetRequestProcessor() + public override void ProcessPacket(ILSArriveStarPlanetRequest packet, NebulaConnection conn) + { + if (IsClient) { - playerManager = Multiplayer.Session.Network.PlayerManager; + return; } - public override void ProcessPacket(ILSArriveStarPlanetRequest packet, NebulaConnection conn) + var player = playerManager.GetPlayer(conn); + if (player == null) { - if (IsClient) - { - return; - } + player = playerManager.GetSyncingPlayer(conn); + } + if (player != null) + { + var stationGId = new List(); + var stationPId = new List(); + var stationMaxShips = new List(); + var storageLength = new List(); + var slotLength = new List(); + var arraySizeStorage = 0; + var arraySizeSlot = 0; + var offsetStorage = 0; + var offsetSlot = 0; - INebulaPlayer player = playerManager.GetPlayer(conn); - if (player == null) + foreach (var stationComponent in GameMain.data.galacticTransport.stationPool) { - player = playerManager.GetSyncingPlayer(conn); + if (stationComponent != null && GameMain.galaxy.PlanetById(stationComponent.planetId)?.star.id == packet.StarId) + { + stationGId.Add(stationComponent.gid); + stationPId.Add(stationComponent.planetId); + stationMaxShips.Add(stationComponent.workShipDatas.Length); + storageLength.Add(stationComponent.storage.Length); + slotLength.Add(stationComponent.slots.Length); + } } - if (player != null) + + if (stationGId.Count > 0) { - List stationGId = new List(); - List stationPId = new List(); - List stationMaxShips = new List(); - List storageLength = new List(); - List slotLength = new List(); - int arraySizeStorage = 0; - int arraySizeSlot = 0; - int offsetStorage = 0; - int offsetSlot = 0; + var gStationPool = GameMain.data.galacticTransport.stationPool; - foreach (StationComponent stationComponent in GameMain.data.galacticTransport.stationPool) + for (var i = 0; i < storageLength.Count; i++) { - if (stationComponent != null && GameMain.galaxy.PlanetById(stationComponent.planetId)?.star.id == packet.StarId) - { - stationGId.Add(stationComponent.gid); - stationPId.Add(stationComponent.planetId); - stationMaxShips.Add(stationComponent.workShipDatas.Length); - storageLength.Add(stationComponent.storage.Length); - slotLength.Add(stationComponent.slots.Length); - } + arraySizeStorage += storageLength[i]; } - - if (stationGId.Count > 0) + for (var i = 0; i < slotLength.Count; i++) { - StationComponent[] gStationPool = GameMain.data.galacticTransport.stationPool; - - for (int i = 0; i < storageLength.Count; i++) - { - arraySizeStorage += storageLength[i]; - } - for(int i = 0; i < slotLength.Count; i++) - { - arraySizeSlot += slotLength[i]; - } + arraySizeSlot += slotLength[i]; + } - int[] storageIdx = new int[arraySizeSlot]; + var storageIdx = new int[arraySizeSlot]; - int[] itemId = new int[arraySizeStorage]; - int[] count = new int[arraySizeStorage]; - int[] inc = new int[arraySizeStorage]; + var itemId = new int[arraySizeStorage]; + var count = new int[arraySizeStorage]; + var inc = new int[arraySizeStorage]; - for (int i = 0; i < stationGId.Count; i++) + for (var i = 0; i < stationGId.Count; i++) + { + for (var j = 0; j < slotLength[i]; j++) { - for(int j = 0; j < slotLength[i]; j++) - { - if (gStationPool[stationGId[i]].slots.Length > 0) // collectors dont have a slot for belts - { - storageIdx[offsetSlot + j] = gStationPool[stationGId[i]].slots[j].storageIdx; - } - } - offsetSlot += slotLength[i]; - - for (int j = 0; j < storageLength[i]; j++) + if (gStationPool[stationGId[i]].slots.Length > 0) // collectors dont have a slot for belts { - itemId[offsetStorage + j] = gStationPool[stationGId[i]].storage[j].itemId; - count[offsetStorage + j] = gStationPool[stationGId[i]].storage[j].count; - inc[offsetStorage + j] = gStationPool[stationGId[i]].storage[j].inc; + storageIdx[offsetSlot + j] = gStationPool[stationGId[i]].slots[j].storageIdx; } - offsetStorage += storageLength[i]; } + offsetSlot += slotLength[i]; - player.SendPacket(new ILSArriveStarPlanetResponse(stationGId.ToArray(), - stationPId.ToArray(), - stationMaxShips.ToArray(), - storageLength.ToArray(), - storageIdx, - slotLength.ToArray(), - itemId, - count, - inc)); + for (var j = 0; j < storageLength[i]; j++) + { + itemId[offsetStorage + j] = gStationPool[stationGId[i]].storage[j].itemId; + count[offsetStorage + j] = gStationPool[stationGId[i]].storage[j].count; + inc[offsetStorage + j] = gStationPool[stationGId[i]].storage[j].inc; + } + offsetStorage += storageLength[i]; } + + player.SendPacket(new ILSArriveStarPlanetResponse(stationGId.ToArray(), + stationPId.ToArray(), + stationMaxShips.ToArray(), + storageLength.ToArray(), + storageIdx, + slotLength.ToArray(), + itemId, + count, + inc)); } } } diff --git a/NebulaNetwork/PacketProcessors/Logistics/ILSArriveStarPlanetResponseProcessor.cs b/NebulaNetwork/PacketProcessors/Logistics/ILSArriveStarPlanetResponseProcessor.cs index 6692e9792..7a0536d64 100644 --- a/NebulaNetwork/PacketProcessors/Logistics/ILSArriveStarPlanetResponseProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Logistics/ILSArriveStarPlanetResponseProcessor.cs @@ -1,61 +1,65 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Logistics; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Logistics +#endregion + +namespace NebulaNetwork.PacketProcessors.Logistics; + +[RegisterPacketProcessor] +internal class ILSArriveStarPlanetResponseProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class ILSArriveStarPlanetResponseProcessor : PacketProcessor + public override void ProcessPacket(ILSArriveStarPlanetResponse packet, NebulaConnection conn) { - public override void ProcessPacket(ILSArriveStarPlanetResponse packet, NebulaConnection conn) + if (IsHost) + { + return; + } + + var gStationPool = GameMain.data.galacticTransport.stationPool; + + var offsetStorage = 0; + var offsetSlot = 0; + for (var i = 0; i < packet.StationGId.Length; i++) { - if (IsHost) + if (packet.StationGId[i] >= gStationPool.Length || gStationPool[packet.StationGId[i]] == null) { - return; + Multiplayer.Session.Ships.CreateFakeStationComponent(packet.StationGId[i], packet.StationPId[i], + packet.StationMaxShips[i]); } - StationComponent[] gStationPool = GameMain.data.galacticTransport.stationPool; - - int offsetStorage = 0; - int offsetSlot = 0; - for (int i = 0; i < packet.StationGId.Length; i++) + var stationComponent = gStationPool[packet.StationGId[i]]; + if (stationComponent.slots == null && !stationComponent.isCollector) { - if (packet.StationGId[i] >= gStationPool.Length || gStationPool[packet.StationGId[i]] == null) - { - Multiplayer.Session.Ships.CreateFakeStationComponent(packet.StationGId[i], packet.StationPId[i], packet.StationMaxShips[i]); - } + stationComponent.slots = new SlotData[packet.SlotLength[i]]; + } + if (stationComponent.storage.Length == 0) + { + stationComponent.storage = new StationStore[packet.StorageLength[i]]; + } + for (var j = 0; j < packet.SlotLength[i]; j++) + { + var index = offsetSlot + j; - StationComponent stationComponent = gStationPool[packet.StationGId[i]]; - if (stationComponent.slots == null && !stationComponent.isCollector) - { - stationComponent.slots = new SlotData[packet.SlotLength[i]]; - } - if (stationComponent.storage.Length == 0) + if (!stationComponent.isCollector) { - stationComponent.storage = new StationStore[packet.StorageLength[i]]; + stationComponent.slots[j].storageIdx = packet.StorageIdx[index]; } - for (int j = 0; j < packet.SlotLength[i]; j++) - { - int index = offsetSlot + j; - - if (!stationComponent.isCollector) - { - stationComponent.slots[j].storageIdx = packet.StorageIdx[index]; - } - } - offsetSlot += packet.SlotLength[i]; - for(int j = 0; j < packet.StorageLength[i]; j++) - { - int index = offsetStorage + j; + } + offsetSlot += packet.SlotLength[i]; + for (var j = 0; j < packet.StorageLength[i]; j++) + { + var index = offsetStorage + j; - stationComponent.storage[j].itemId = packet.ItemId[index]; - stationComponent.storage[j].count = packet.Count[index]; - stationComponent.storage[j].inc = packet.Inc[index]; - } - offsetStorage += packet.StorageLength[i]; + stationComponent.storage[j].itemId = packet.ItemId[index]; + stationComponent.storage[j].count = packet.Count[index]; + stationComponent.storage[j].inc = packet.Inc[index]; } + offsetStorage += packet.StorageLength[i]; } } } diff --git a/NebulaNetwork/PacketProcessors/Logistics/ILSIdleShipBackToWorkProcessor.cs b/NebulaNetwork/PacketProcessors/Logistics/ILSIdleShipBackToWorkProcessor.cs index e01c5ec1f..e0643113c 100644 --- a/NebulaNetwork/PacketProcessors/Logistics/ILSIdleShipBackToWorkProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Logistics/ILSIdleShipBackToWorkProcessor.cs @@ -1,27 +1,30 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Logistics; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Logistics +#endregion + +namespace NebulaNetwork.PacketProcessors.Logistics; + +[RegisterPacketProcessor] +public class ILSIdleShipBackToWorkProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class ILSIdleShipBackToWorkProcessor : PacketProcessor + public override void ProcessPacket(ILSIdleShipBackToWork packet, NebulaConnection conn) { - public override void ProcessPacket(ILSIdleShipBackToWork packet, NebulaConnection conn) + if (IsHost) { - if (IsHost) - { - return; - } + return; + } - if (IsClient) + if (IsClient) + { + using (Multiplayer.Session.Factories.IsIncomingRequest.On()) { - using (Multiplayer.Session.Factories.IsIncomingRequest.On()) - { - Multiplayer.Session.Ships.IdleShipGetToWork(packet); - } + Multiplayer.Session.Ships.IdleShipGetToWork(packet); } } } diff --git a/NebulaNetwork/PacketProcessors/Logistics/ILSRematchRemotePairsProcessor.cs b/NebulaNetwork/PacketProcessors/Logistics/ILSRematchRemotePairsProcessor.cs index b0fc52ef1..163d21343 100644 --- a/NebulaNetwork/PacketProcessors/Logistics/ILSRematchRemotePairsProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Logistics/ILSRematchRemotePairsProcessor.cs @@ -1,30 +1,33 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Logistics; +#endregion + /* * This packet updates the ships direction and is used when StationComponent.RematchRemotePairs() is called * This is used when a station is added or removed or a supply/demand chain is changed */ -namespace NebulaNetwork.PacketProcessors.Logistics +namespace NebulaNetwork.PacketProcessors.Logistics; + +[RegisterPacketProcessor] +internal class ILSRematchRemotePairsProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class ILSRematchRemotePairsProcessor : PacketProcessor + public override void ProcessPacket(ILSRematchRemotePairs packet, NebulaConnection conn) { - public override void ProcessPacket(ILSRematchRemotePairs packet, NebulaConnection conn) + var gTransport = GameMain.data.galacticTransport; + if (packet.GId < gTransport.stationCursor) { - GalacticTransport gTransport = GameMain.data.galacticTransport; - if (packet.GId < gTransport.stationCursor) + for (var i = 0; i < packet.ShipIndex.Length; i++) { - for (int i = 0; i < packet.ShipIndex.Length; i++) + if (gTransport.stationPool[packet.GId] != null) { - if (gTransport.stationPool[packet.GId] != null) - { - gTransport.stationPool[packet.GId].workShipDatas[packet.ShipIndex[i]].otherGId = packet.OtherGId[i]; - gTransport.stationPool[packet.GId].workShipDatas[packet.ShipIndex[i]].direction = packet.Direction[i]; - gTransport.stationPool[packet.GId].workShipDatas[packet.ShipIndex[i]].itemId = packet.ItemId[i]; - } + gTransport.stationPool[packet.GId].workShipDatas[packet.ShipIndex[i]].otherGId = packet.OtherGId[i]; + gTransport.stationPool[packet.GId].workShipDatas[packet.ShipIndex[i]].direction = packet.Direction[i]; + gTransport.stationPool[packet.GId].workShipDatas[packet.ShipIndex[i]].itemId = packet.ItemId[i]; } } } diff --git a/NebulaNetwork/PacketProcessors/Logistics/ILSRemoveStationComponentProcessor.cs b/NebulaNetwork/PacketProcessors/Logistics/ILSRemoveStationComponentProcessor.cs index 4de55cc2c..023db2ece 100644 --- a/NebulaNetwork/PacketProcessors/Logistics/ILSRemoveStationComponentProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Logistics/ILSRemoveStationComponentProcessor.cs @@ -1,36 +1,39 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Logistics; using NebulaWorld; +#endregion + /* * If client knows the planets factory we call the removal there, if not we call it on the gStationPool if possible */ -namespace NebulaNetwork.PacketProcessors.Logistics +namespace NebulaNetwork.PacketProcessors.Logistics; + +[RegisterPacketProcessor] +internal class ILSRemoveStationComponentProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class ILSRemoveStationComponentProcessor : PacketProcessor + public override void ProcessPacket(ILSRemoveStationComponent packet, NebulaConnection conn) { - public override void ProcessPacket(ILSRemoveStationComponent packet, NebulaConnection conn) + var pData = GameMain.galaxy.PlanetById(packet.PlanetId); + if (pData?.factory?.transport != null && packet.StationId < pData.factory.transport.stationPool.Length) { - PlanetData pData = GameMain.galaxy.PlanetById(packet.PlanetId); - if (pData?.factory?.transport != null && packet.StationId < pData.factory.transport.stationPool.Length) + using (Multiplayer.Session.Ships.PatchLockILS.On()) { - using (Multiplayer.Session.Ships.PatchLockILS.On()) - { - pData.factory.transport.RemoveStationComponent(packet.StationId); - } + pData.factory.transport.RemoveStationComponent(packet.StationId); } - else + } + else + { + var gStationPool = GameMain.data.galacticTransport.stationPool; + if (packet.StationGId < gStationPool.Length) { - StationComponent[] gStationPool = GameMain.data.galacticTransport.stationPool; - if (packet.StationGId < gStationPool.Length) + using (Multiplayer.Session.Ships.PatchLockILS.On()) { - using (Multiplayer.Session.Ships.PatchLockILS.On()) - { - GameMain.data.galacticTransport.RemoveStationComponent(packet.StationGId); - } + GameMain.data.galacticTransport.RemoveStationComponent(packet.StationGId); } } } diff --git a/NebulaNetwork/PacketProcessors/Logistics/ILSRequestShipDockProcessor.cs b/NebulaNetwork/PacketProcessors/Logistics/ILSRequestShipDockProcessor.cs index 80208741f..e465dd41f 100644 --- a/NebulaNetwork/PacketProcessors/Logistics/ILSRequestShipDockProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Logistics/ILSRequestShipDockProcessor.cs @@ -1,95 +1,100 @@ -using NebulaAPI; +#region + +using System.Collections.Generic; +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Logistics; using NebulaWorld; -using System.Collections.Generic; + +#endregion + /* * clients need to know the ship dock position for correct computation of the ship movement. * as clients dont have every PlanetFactory we use fake entries in gStationPool for ILS on planets that the client did not visit yet. * when they create a fake entry they also request the dock position, but we also need to tell the current ship * position and rotation for associated ships as they might have ben calculated wrong (without knowledge of dock position) */ -namespace NebulaNetwork.PacketProcessors.Logistics +namespace NebulaNetwork.PacketProcessors.Logistics; + +[RegisterPacketProcessor] +public class ILSRequestShipDockProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class ILSRequestShipDockProcessor : PacketProcessor + private readonly IPlayerManager playerManager; + + public ILSRequestShipDockProcessor() { - private readonly IPlayerManager playerManager; + playerManager = Multiplayer.Session.Network.PlayerManager; + } - public ILSRequestShipDockProcessor() + public override void ProcessPacket(ILSRequestShipDock packet, NebulaConnection conn) + { + if (IsClient) { - playerManager = Multiplayer.Session.Network.PlayerManager; + return; } - public override void ProcessPacket(ILSRequestShipDock packet, NebulaConnection conn) - { - if (IsClient) - { - return; - } + var player = playerManager.GetPlayer(conn); - INebulaPlayer player = playerManager.GetPlayer(conn); + if (player == null) + { + player = playerManager.GetSyncingPlayer(conn); + } + if (player != null && GameMain.data.galacticTransport.stationCapacity > packet.StationGId) + { + var shipOtherGId = new List(); + var shipIndex = new List(); + var shipPos = new List(); + var shipRot = new List(); + var shipPPosTemp = new List(); + var shipPRotTemp = new List(); - if (player == null) - { - player = playerManager.GetSyncingPlayer(conn); - } - if (player != null && GameMain.data.galacticTransport.stationCapacity > packet.StationGId) + // find ShipData that has otherGId set to packet.stationGId + for (var i = 0; i < GameMain.data.galacticTransport.stationCapacity; i++) { - List shipOtherGId = new List(); - List shipIndex = new List(); - List shipPos = new List(); - List shipRot = new List(); - List shipPPosTemp = new List(); - List shipPRotTemp = new List(); - - // find ShipData that has otherGId set to packet.stationGId - for (int i = 0; i < GameMain.data.galacticTransport.stationCapacity; i++) + if (GameMain.data.galacticTransport.stationPool[i] != null) { - if (GameMain.data.galacticTransport.stationPool[i] != null) - { - ShipData[] shipData = GameMain.data.galacticTransport.stationPool[i].workShipDatas; + var shipData = GameMain.data.galacticTransport.stationPool[i].workShipDatas; - for (int j = 0; j < shipData.Length; j++) + for (var j = 0; j < shipData.Length; j++) + { + if (shipData[j].otherGId == packet.StationGId) { - if (shipData[j].otherGId == packet.StationGId) - { - shipOtherGId.Add(shipData[j].otherGId); - shipIndex.Add(j); - shipPos.Add(new Double3(shipData[j].uPos.x, shipData[j].uPos.y, shipData[j].uPos.z)); - shipRot.Add(new Float4(shipData[j].uRot)); - shipPPosTemp.Add(new Double3(shipData[j].pPosTemp.x, shipData[j].pPosTemp.y, shipData[j].pPosTemp.z)); - shipPRotTemp.Add(new Float4(shipData[j].pRotTemp)); - } + shipOtherGId.Add(shipData[j].otherGId); + shipIndex.Add(j); + shipPos.Add(new Double3(shipData[j].uPos.x, shipData[j].uPos.y, shipData[j].uPos.z)); + shipRot.Add(new Float4(shipData[j].uRot)); + shipPPosTemp.Add( + new Double3(shipData[j].pPosTemp.x, shipData[j].pPosTemp.y, shipData[j].pPosTemp.z)); + shipPRotTemp.Add(new Float4(shipData[j].pRotTemp)); } } } - // also add add ships of current station as they use the dock pos too in the pos calculation - // NOTE: we need to set this stations gid as otherStationGId so that the client accesses the array in the right way - ShipData[] shipData2 = GameMain.data.galacticTransport.stationPool[packet.StationGId].workShipDatas; - - for (int i = 0; i < shipData2.Length; i++) - { - shipOtherGId.Add(packet.StationGId); - shipIndex.Add(i); - shipPos.Add(new Double3(shipData2[i].uPos.x, shipData2[i].uPos.y, shipData2[i].uPos.z)); - shipRot.Add(new Float4(shipData2[i].uRot)); - shipPPosTemp.Add(new Double3(shipData2[i].pPosTemp.x, shipData2[i].pPosTemp.y, shipData2[i].pPosTemp.z)); - shipPRotTemp.Add(new Float4(shipData2[i].pRotTemp)); - } + } + // also add add ships of current station as they use the dock pos too in the pos calculation + // NOTE: we need to set this stations gid as otherStationGId so that the client accesses the array in the right way + var shipData2 = GameMain.data.galacticTransport.stationPool[packet.StationGId].workShipDatas; - ILSShipDock packet2 = new ILSShipDock(packet.StationGId, - GameMain.data.galacticTransport.stationPool[packet.StationGId].shipDockPos, - GameMain.data.galacticTransport.stationPool[packet.StationGId].shipDockRot, - shipOtherGId.ToArray(), - shipIndex.ToArray(), - shipPos.ToArray(), - shipRot.ToArray(), - shipPPosTemp.ToArray(), - shipPRotTemp.ToArray()); - player.SendPacket(packet2); + for (var i = 0; i < shipData2.Length; i++) + { + shipOtherGId.Add(packet.StationGId); + shipIndex.Add(i); + shipPos.Add(new Double3(shipData2[i].uPos.x, shipData2[i].uPos.y, shipData2[i].uPos.z)); + shipRot.Add(new Float4(shipData2[i].uRot)); + shipPPosTemp.Add(new Double3(shipData2[i].pPosTemp.x, shipData2[i].pPosTemp.y, shipData2[i].pPosTemp.z)); + shipPRotTemp.Add(new Float4(shipData2[i].pRotTemp)); } + + var packet2 = new ILSShipDock(packet.StationGId, + GameMain.data.galacticTransport.stationPool[packet.StationGId].shipDockPos, + GameMain.data.galacticTransport.stationPool[packet.StationGId].shipDockRot, + shipOtherGId.ToArray(), + shipIndex.ToArray(), + shipPos.ToArray(), + shipRot.ToArray(), + shipPPosTemp.ToArray(), + shipPRotTemp.ToArray()); + player.SendPacket(packet2); } } } diff --git a/NebulaNetwork/PacketProcessors/Logistics/ILSResponseShipDockProcessor.cs b/NebulaNetwork/PacketProcessors/Logistics/ILSResponseShipDockProcessor.cs index 41a8e7978..0b0ba4f71 100644 --- a/NebulaNetwork/PacketProcessors/Logistics/ILSResponseShipDockProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Logistics/ILSResponseShipDockProcessor.cs @@ -1,61 +1,64 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Logistics; -using NebulaWorld; using UnityEngine; +#endregion + /* * In order for the StationComponent.InternalTickRemote() method to correctly animate ship movement it needs to know * the position of the stations docking disk. * as we use fake entries in gStationPool for clients that have not visited the planet yet we also need to sync that position. */ -namespace NebulaNetwork.PacketProcessors.Logistics +namespace NebulaNetwork.PacketProcessors.Logistics; + +[RegisterPacketProcessor] +internal class ILSResponseShipDockProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class ILSResponseShipDockProcessor : PacketProcessor + public override void ProcessPacket(ILSShipDock packet, NebulaConnection conn) { - public override void ProcessPacket(ILSShipDock packet, NebulaConnection conn) + if (IsHost) { - if (IsHost) - { - return; - } + return; + } - // a fake entry should already have been created - StationComponent stationComponent = GameMain.data.galacticTransport.stationPool[packet.stationGId]; + // a fake entry should already have been created + var stationComponent = GameMain.data.galacticTransport.stationPool[packet.stationGId]; - stationComponent.shipDockPos = packet.shipDockPos.ToVector3(); - stationComponent.shipDockRot = packet.shipDockRot.ToQuaternion(); + stationComponent.shipDockPos = packet.shipDockPos.ToVector3(); + stationComponent.shipDockRot = packet.shipDockRot.ToQuaternion(); - for (int i = 0; i < stationComponent.workShipDatas.Length; i++) - { - stationComponent.shipDiskRot[i] = Quaternion.Euler(0f, 360f / stationComponent.workShipDatas.Length * i, 0f); - stationComponent.shipDiskPos[i] = stationComponent.shipDiskRot[i] * new Vector3(0f, 0f, 11.5f); - } - for (int j = 0; j < stationComponent.workShipDatas.Length; j++) - { - stationComponent.shipDiskRot[j] = stationComponent.shipDockRot * stationComponent.shipDiskRot[j]; - stationComponent.shipDiskPos[j] = stationComponent.shipDockPos + stationComponent.shipDockRot * stationComponent.shipDiskPos[j]; - } + for (var i = 0; i < stationComponent.workShipDatas.Length; i++) + { + stationComponent.shipDiskRot[i] = Quaternion.Euler(0f, 360f / stationComponent.workShipDatas.Length * i, 0f); + stationComponent.shipDiskPos[i] = stationComponent.shipDiskRot[i] * new Vector3(0f, 0f, 11.5f); + } + for (var j = 0; j < stationComponent.workShipDatas.Length; j++) + { + stationComponent.shipDiskRot[j] = stationComponent.shipDockRot * stationComponent.shipDiskRot[j]; + stationComponent.shipDiskPos[j] = + stationComponent.shipDockPos + stationComponent.shipDockRot * stationComponent.shipDiskPos[j]; + } - // sync the current position of the ships as they might have been calculated wrong while we did not have the correct dock position and rotation. - for (int i = 0; i < packet.shipOtherGId.Length; i++) + // sync the current position of the ships as they might have been calculated wrong while we did not have the correct dock position and rotation. + for (var i = 0; i < packet.shipOtherGId.Length; i++) + { + /* + * fix for #251 + * for some reason shipOtherGId can be 0 in some cases. + * i thought about idle ships not having it set but im not sure. However checking for a 0 here fixes the issue. + */ + if (packet.shipOtherGId[i] > 0 && packet.shipOtherGId[i] < GameMain.data.galacticTransport.stationPool.Length) { - /* - * fix for #251 - * for some reason shipOtherGId can be 0 in some cases. - * i thought about idle ships not having it set but im not sure. However checking for a 0 here fixes the issue. - */ - if (packet.shipOtherGId[i] > 0 && packet.shipOtherGId[i] < GameMain.data.galacticTransport.stationPool.Length) - { - stationComponent = GameMain.data.galacticTransport.stationPool[packet.shipOtherGId[i]]; - - stationComponent.workShipDatas[packet.shipIndex[i]].uPos = packet.shipPos[i].ToVectorLF3(); - stationComponent.workShipDatas[packet.shipIndex[i]].uRot = packet.shipRot[i].ToQuaternion(); - stationComponent.workShipDatas[packet.shipIndex[i]].pPosTemp = packet.shipPPosTemp[i].ToVectorLF3(); - stationComponent.workShipDatas[packet.shipIndex[i]].pRotTemp = packet.shipPRotTemp[i].ToQuaternion(); - } + stationComponent = GameMain.data.galacticTransport.stationPool[packet.shipOtherGId[i]]; + + stationComponent.workShipDatas[packet.shipIndex[i]].uPos = packet.shipPos[i].ToVectorLF3(); + stationComponent.workShipDatas[packet.shipIndex[i]].uRot = packet.shipRot[i].ToQuaternion(); + stationComponent.workShipDatas[packet.shipIndex[i]].pPosTemp = packet.shipPPosTemp[i].ToVectorLF3(); + stationComponent.workShipDatas[packet.shipIndex[i]].pRotTemp = packet.shipPRotTemp[i].ToQuaternion(); } } } diff --git a/NebulaNetwork/PacketProcessors/Logistics/ILSShipAddTakeProcessor.cs b/NebulaNetwork/PacketProcessors/Logistics/ILSShipAddTakeProcessor.cs index cf28a6121..821e79433 100644 --- a/NebulaNetwork/PacketProcessors/Logistics/ILSShipAddTakeProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Logistics/ILSShipAddTakeProcessor.cs @@ -1,22 +1,25 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Logistics; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Logistics +#endregion + +namespace NebulaNetwork.PacketProcessors.Logistics; + +[RegisterPacketProcessor] +public class ILSShipAddTakeProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class ILSShipAddTakeProcessor : PacketProcessor + public override void ProcessPacket(ILSShipAddTake packet, NebulaConnection conn) { - public override void ProcessPacket(ILSShipAddTake packet, NebulaConnection conn) + if (IsHost) { - if (IsHost) - { - return; - } - - Multiplayer.Session.Ships.AddTakeItem(packet); + return; } + + Multiplayer.Session.Ships.AddTakeItem(packet); } } diff --git a/NebulaNetwork/PacketProcessors/Logistics/ILSShipEnterWarpProcessor.cs b/NebulaNetwork/PacketProcessors/Logistics/ILSShipEnterWarpProcessor.cs index f00499730..bd06735de 100644 --- a/NebulaNetwork/PacketProcessors/Logistics/ILSShipEnterWarpProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Logistics/ILSShipEnterWarpProcessor.cs @@ -1,24 +1,27 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Logistics; -namespace NebulaNetwork.PacketProcessors.Logistics +#endregion + +namespace NebulaNetwork.PacketProcessors.Logistics; + +[RegisterPacketProcessor] +public class ILSShipEnterWarpProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class ILSShipEnterWarpProcessor : PacketProcessor + public override void ProcessPacket(ILSShipEnterWarp packet, NebulaConnection conn) { - public override void ProcessPacket(ILSShipEnterWarp packet, NebulaConnection conn) + if (IsClient) { - if (IsClient) + if (packet.ThisGId <= GameMain.data.galacticTransport.stationCursor) { - if (packet.ThisGId <= GameMain.data.galacticTransport.stationCursor) + var stationComponent = GameMain.data.galacticTransport.stationPool[packet.ThisGId]; + if (stationComponent != null && packet.WorkShipIndex < stationComponent.workShipCount) { - StationComponent stationComponent = GameMain.data.galacticTransport.stationPool[packet.ThisGId]; - if (stationComponent != null && packet.WorkShipIndex < stationComponent.workShipCount) - { - stationComponent.workShipDatas[packet.WorkShipIndex].warpState += 0.016666668f; - } + stationComponent.workShipDatas[packet.WorkShipIndex].warpState += 0.016666668f; } } } diff --git a/NebulaNetwork/PacketProcessors/Logistics/ILSUpdateSlotDataProcessor.cs b/NebulaNetwork/PacketProcessors/Logistics/ILSUpdateSlotDataProcessor.cs index 50ac329b5..382f8add7 100644 --- a/NebulaNetwork/PacketProcessors/Logistics/ILSUpdateSlotDataProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Logistics/ILSUpdateSlotDataProcessor.cs @@ -1,17 +1,20 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Logistics; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Logistics +#endregion + +namespace NebulaNetwork.PacketProcessors.Logistics; + +[RegisterPacketProcessor] +internal class ILSUpdateSlotDataProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class ILSUpdateSlotDataProcessor : PacketProcessor + public override void ProcessPacket(ILSUpdateSlotData packet, NebulaConnection conn) { - public override void ProcessPacket(ILSUpdateSlotData packet, NebulaConnection conn) - { - Multiplayer.Session.Ships.UpdateSlotData(packet); - } + Multiplayer.Session.Ships.UpdateSlotData(packet); } } diff --git a/NebulaNetwork/PacketProcessors/Logistics/ILSUpdateStorageProcessor.cs b/NebulaNetwork/PacketProcessors/Logistics/ILSUpdateStorageProcessor.cs index 9275fb364..a9fc9a6d1 100644 --- a/NebulaNetwork/PacketProcessors/Logistics/ILSUpdateStorageProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Logistics/ILSUpdateStorageProcessor.cs @@ -1,22 +1,25 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Logistics; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Logistics +#endregion + +namespace NebulaNetwork.PacketProcessors.Logistics; + +[RegisterPacketProcessor] +public class ILSUpdateStorageProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class ILSUpdateStorageProcessor : PacketProcessor + public override void ProcessPacket(ILSUpdateStorage packet, NebulaConnection conn) { - public override void ProcessPacket(ILSUpdateStorage packet, NebulaConnection conn) + if (IsHost) { - if (IsHost) - { - return; - } - - Multiplayer.Session.Ships.UpdateStorage(packet); + return; } + + Multiplayer.Session.Ships.UpdateStorage(packet); } } diff --git a/NebulaNetwork/PacketProcessors/Logistics/ILSWorkShipBackToIdleProcessor.cs b/NebulaNetwork/PacketProcessors/Logistics/ILSWorkShipBackToIdleProcessor.cs index 92f2b6418..33810912f 100644 --- a/NebulaNetwork/PacketProcessors/Logistics/ILSWorkShipBackToIdleProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Logistics/ILSWorkShipBackToIdleProcessor.cs @@ -1,25 +1,28 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Logistics; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Logistics +#endregion + +namespace NebulaNetwork.PacketProcessors.Logistics; + +[RegisterPacketProcessor] +public class ILSWorkShipBackToIdleProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class ILSWorkShipBackToIdleProcessor : PacketProcessor + public override void ProcessPacket(ILSWorkShipBackToIdle packet, NebulaConnection conn) { - public override void ProcessPacket(ILSWorkShipBackToIdle packet, NebulaConnection conn) + if (IsHost) { - if (IsHost) - { - return; - } + return; + } - if (IsClient) - { - Multiplayer.Session.Ships.WorkShipBackToIdle(packet); - } + if (IsClient) + { + Multiplayer.Session.Ships.WorkShipBackToIdle(packet); } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Logistics/ILSgStationPoolSyncProcessor.cs b/NebulaNetwork/PacketProcessors/Logistics/ILSgStationPoolSyncProcessor.cs index 9ac25c0a8..9cdf8c89b 100644 --- a/NebulaNetwork/PacketProcessors/Logistics/ILSgStationPoolSyncProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Logistics/ILSgStationPoolSyncProcessor.cs @@ -1,93 +1,104 @@ -using NebulaAPI; +#region + +using System; +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Logistics; using NebulaWorld; using UnityEngine; +#endregion + /* * This packet is only sent one time when a client joins the game * it is used to sync the gStationPool to the clients including all ships. * This is needed to have the current state and position of ships */ -namespace NebulaNetwork.PacketProcessors.Logistics +namespace NebulaNetwork.PacketProcessors.Logistics; + +[RegisterPacketProcessor] +internal class ILSgStationPoolSyncProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class ILSgStationPoolSyncProcessor : PacketProcessor + public override void ProcessPacket(ILSgStationPoolSync packet, NebulaConnection conn) { - public override void ProcessPacket(ILSgStationPoolSync packet, NebulaConnection conn) + var gTransport = GameMain.data.galacticTransport; + var gStationPool = GameMain.data.galacticTransport.stationPool; + + var arrayStartPos = 0; + + for (var i = 0; i < packet.stationGId.Length; i++) { - GalacticTransport gTransport = GameMain.data.galacticTransport; - StationComponent[] gStationPool = GameMain.data.galacticTransport.stationPool; + Multiplayer.Session.Ships.CreateFakeStationComponent(packet.stationGId[i], packet.planetId[i], + packet.stationMaxShipCount[i], false); // handles array resizing + gStationPool = GameMain.data.galacticTransport.stationPool; // dont remove or you get an ArrayOutOfBounds + + gStationPool[packet.stationGId[i]].shipDockPos = packet.DockPos[i].ToVector3(); + + gStationPool[packet.stationGId[i]].shipDockRot = packet.DockRot[i].ToQuaternion(); + + gStationPool[packet.stationGId[i]].id = packet.stationId[i]; + gStationPool[packet.stationGId[i]].name = + string.IsNullOrEmpty(packet.stationName[i]) ? null : packet.stationName[i]; + gStationPool[packet.stationGId[i]].planetId = packet.planetId[i]; + gStationPool[packet.stationGId[i]].workShipCount = packet.workShipCount[i]; + gStationPool[packet.stationGId[i]].idleShipCount = packet.idleShipCount[i]; + gStationPool[packet.stationGId[i]].workShipIndices = packet.workShipIndices[i]; + gStationPool[packet.stationGId[i]].idleShipIndices = packet.idleShipIndices[i]; + gStationPool[packet.stationGId[i]].shipRenderers = new ShipRenderingData[packet.stationMaxShipCount[i]]; + gStationPool[packet.stationGId[i]].shipUIRenderers = new ShipUIRenderingData[packet.stationMaxShipCount[i]]; + gStationPool[packet.stationGId[i]].storage = Array.Empty(); // zero-length array for mod compatibility - int arrayStartPos = 0; + gStationPool[packet.stationGId[i]].shipDiskPos = new Vector3[packet.stationMaxShipCount[i]]; + gStationPool[packet.stationGId[i]].shipDiskRot = new Quaternion[packet.stationMaxShipCount[i]]; - for (int i = 0; i < packet.stationGId.Length; i++) + // these are the individual landing places for the ships on the station's disk at the top + for (var j = 0; j < packet.stationMaxShipCount[i]; j++) { - Multiplayer.Session.Ships.CreateFakeStationComponent(packet.stationGId[i], packet.planetId[i], packet.stationMaxShipCount[i], false); // handles array resizing - gStationPool = GameMain.data.galacticTransport.stationPool; // dont remove or you get an ArrayOutOfBounds - - gStationPool[packet.stationGId[i]].shipDockPos = packet.DockPos[i].ToVector3(); - - gStationPool[packet.stationGId[i]].shipDockRot = packet.DockRot[i].ToQuaternion(); - - gStationPool[packet.stationGId[i]].id = packet.stationId[i]; - gStationPool[packet.stationGId[i]].name = string.IsNullOrEmpty(packet.stationName[i]) ? null : packet.stationName[i]; - gStationPool[packet.stationGId[i]].planetId = packet.planetId[i]; - gStationPool[packet.stationGId[i]].workShipCount = packet.workShipCount[i]; - gStationPool[packet.stationGId[i]].idleShipCount = packet.idleShipCount[i]; - gStationPool[packet.stationGId[i]].workShipIndices = packet.workShipIndices[i]; - gStationPool[packet.stationGId[i]].idleShipIndices = packet.idleShipIndices[i]; - gStationPool[packet.stationGId[i]].shipRenderers = new ShipRenderingData[packet.stationMaxShipCount[i]]; - gStationPool[packet.stationGId[i]].shipUIRenderers = new ShipUIRenderingData[packet.stationMaxShipCount[i]]; - gStationPool[packet.stationGId[i]].storage = System.Array.Empty(); // zero-length array for mod compatibility - - gStationPool[packet.stationGId[i]].shipDiskPos = new Vector3[packet.stationMaxShipCount[i]]; - gStationPool[packet.stationGId[i]].shipDiskRot = new Quaternion[packet.stationMaxShipCount[i]]; - - // these are the individual landing places for the ships on the station's disk at the top - for (int j = 0; j < packet.stationMaxShipCount[i]; j++) - { - gStationPool[packet.stationGId[i]].shipDiskRot[j] = Quaternion.Euler(0f, 360f / packet.stationMaxShipCount[i] * j, 0f); - gStationPool[packet.stationGId[i]].shipDiskPos[j] = gStationPool[packet.stationGId[i]].shipDiskRot[j] * new Vector3(0f, 0f, 11.5f); - } - for (int j = 0; j < packet.stationMaxShipCount[i]; j++) - { - gStationPool[packet.stationGId[i]].shipDiskRot[j] = gStationPool[packet.stationGId[i]].shipDockRot * gStationPool[packet.stationGId[i]].shipDiskRot[j]; - gStationPool[packet.stationGId[i]].shipDiskPos[j] = gStationPool[packet.stationGId[i]].shipDockPos + gStationPool[packet.stationGId[i]].shipDockRot * gStationPool[packet.stationGId[i]].shipDiskPos[j]; - } - - for (int j = 0; j < packet.stationMaxShipCount[i]; j++) - { - int index = arrayStartPos + j; - ShipData shipData = gStationPool[packet.stationGId[i]].workShipDatas[j]; - shipData.stage = packet.shipStage[index]; - shipData.direction = packet.shipDirection[index]; - shipData.warpState = packet.shipWarpState[index]; - shipData.warperCnt = packet.shipWarperCnt[index]; - shipData.itemId = packet.shipItemID[index]; - shipData.itemCount = packet.shipItemCount[index]; - shipData.planetA = packet.shipPlanetA[index]; - shipData.planetB = packet.shipPlanetB[index]; - shipData.otherGId = packet.shipOtherGId[index]; - shipData.t = packet.shipT[index]; - shipData.shipIndex = packet.shipIndex[index]; - - shipData.uPos = packet.shipPos[index].ToVectorLF3(); - shipData.uRot = packet.shipRot[index].ToQuaternion(); - shipData.uVel = packet.shipVel[index].ToVector3(); - shipData.uSpeed = packet.shipSpeed[index]; - shipData.uAngularVel = packet.shipAngularVel[index].ToVector3(); - shipData.pPosTemp = packet.shipPPosTemp[index].ToVectorLF3(); - shipData.pRotTemp = packet.shipRot[index].ToQuaternion(); - - gStationPool[packet.stationGId[i]].workShipDatas[j] = shipData; - } - - arrayStartPos += packet.stationMaxShipCount[i]; + gStationPool[packet.stationGId[i]].shipDiskRot[j] = + Quaternion.Euler(0f, 360f / packet.stationMaxShipCount[i] * j, 0f); + gStationPool[packet.stationGId[i]].shipDiskPos[j] = + gStationPool[packet.stationGId[i]].shipDiskRot[j] * new Vector3(0f, 0f, 11.5f); } + for (var j = 0; j < packet.stationMaxShipCount[i]; j++) + { + gStationPool[packet.stationGId[i]].shipDiskRot[j] = gStationPool[packet.stationGId[i]].shipDockRot * + gStationPool[packet.stationGId[i]].shipDiskRot[j]; + gStationPool[packet.stationGId[i]].shipDiskPos[j] = gStationPool[packet.stationGId[i]].shipDockPos + + gStationPool[packet.stationGId[i]].shipDockRot * + gStationPool[packet.stationGId[i]].shipDiskPos[j]; + } + + for (var j = 0; j < packet.stationMaxShipCount[i]; j++) + { + var index = arrayStartPos + j; + var shipData = gStationPool[packet.stationGId[i]].workShipDatas[j]; + shipData.stage = packet.shipStage[index]; + shipData.direction = packet.shipDirection[index]; + shipData.warpState = packet.shipWarpState[index]; + shipData.warperCnt = packet.shipWarperCnt[index]; + shipData.itemId = packet.shipItemID[index]; + shipData.itemCount = packet.shipItemCount[index]; + shipData.planetA = packet.shipPlanetA[index]; + shipData.planetB = packet.shipPlanetB[index]; + shipData.otherGId = packet.shipOtherGId[index]; + shipData.t = packet.shipT[index]; + shipData.shipIndex = packet.shipIndex[index]; - gTransport.Arragement(); + shipData.uPos = packet.shipPos[index].ToVectorLF3(); + shipData.uRot = packet.shipRot[index].ToQuaternion(); + shipData.uVel = packet.shipVel[index].ToVector3(); + shipData.uSpeed = packet.shipSpeed[index]; + shipData.uAngularVel = packet.shipAngularVel[index].ToVector3(); + shipData.pPosTemp = packet.shipPPosTemp[index].ToVectorLF3(); + shipData.pRotTemp = packet.shipRot[index].ToQuaternion(); + + gStationPool[packet.stationGId[i]].workShipDatas[j] = shipData; + } + + arrayStartPos += packet.stationMaxShipCount[i]; } + + gTransport.Arragement(); } } diff --git a/NebulaNetwork/PacketProcessors/Logistics/ILSgStationPoolSyncRequestProcessor.cs b/NebulaNetwork/PacketProcessors/Logistics/ILSgStationPoolSyncRequestProcessor.cs index b5b7dbc27..812b33b89 100644 --- a/NebulaNetwork/PacketProcessors/Logistics/ILSgStationPoolSyncRequestProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Logistics/ILSgStationPoolSyncRequestProcessor.cs @@ -1,162 +1,167 @@ -using NebulaAPI; +#region + +using System.Collections.Generic; +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Logistics; using NebulaWorld; -using System.Collections.Generic; + +#endregion /* * Whenever a client connects we sync the current state of all ILS and ships to them * resulting in a quite large packet but its only sent one time upon client connect. */ -namespace NebulaNetwork.PacketProcessors.Logistics +namespace NebulaNetwork.PacketProcessors.Logistics; + +[RegisterPacketProcessor] +public class ILSgStationPoolSyncRequestProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class ILSgStationPoolSyncRequestProcessor : PacketProcessor + private readonly IPlayerManager playerManager; + + public ILSgStationPoolSyncRequestProcessor() { - private readonly IPlayerManager playerManager; - public ILSgStationPoolSyncRequestProcessor() + playerManager = Multiplayer.Session.Network.PlayerManager; + } + + public override void ProcessPacket(ILSRequestgStationPoolSync packet, NebulaConnection conn) + { + if (IsClient) + { + return; + } + + var player = playerManager.GetPlayer(conn); + if (player == null) { - playerManager = Multiplayer.Session.Network.PlayerManager; + player = playerManager.GetSyncingPlayer(conn); } - public override void ProcessPacket(ILSRequestgStationPoolSync packet, NebulaConnection conn) + if (player != null) { - if (IsClient) + var countILS = 0; + var iter = 0; + + foreach (var stationComponent in GameMain.data.galacticTransport.stationPool) { - return; + if (stationComponent != null) + { + countILS++; + } } - INebulaPlayer player = playerManager.GetPlayer(conn); - if (player == null) + if (countILS == 0) { - player = playerManager.GetSyncingPlayer(conn); + return; } - if (player != null) - { - int countILS = 0; - int iter = 0; - foreach (StationComponent stationComponent in GameMain.data.galacticTransport.stationPool) - { - if (stationComponent != null) - { - countILS++; - } - } + var stationGId = new int[countILS]; + var stationMaxShipCount = new int[countILS]; + var stationId = new int[countILS]; + var stationName = new string[countILS]; + var DockPos = new Float3[countILS]; + var DockRot = new Float4[countILS]; + var planetId = new int[countILS]; + var workShipCount = new int[countILS]; + var idleShipCount = new int[countILS]; + var workShipIndices = new ulong[countILS]; + var idleShipIndices = new ulong[countILS]; - if (countILS == 0) - { - return; - } + var shipStage = new List(); + var shipDirection = new List(); + var shipWarpState = new List(); + var shipWarperCnt = new List(); + var shipItemID = new List(); + var shipItemCount = new List(); + var shipPlanetA = new List(); + var shipPlanetB = new List(); + var shipOtherGId = new List(); + var shipT = new List(); + var shipIndex = new List(); + var shipPos = new List(); + var shipRot = new List(); + var shipVel = new List(); + var shipSpeed = new List(); + var shipAngularVel = new List(); + var shipPPosTemp = new List(); + var shipPRotTemp = new List(); - int[] stationGId = new int[countILS]; - int[] stationMaxShipCount = new int[countILS]; - int[] stationId = new int[countILS]; - string[] stationName = new string[countILS]; - Float3[] DockPos = new Float3[countILS]; - Float4[] DockRot = new Float4[countILS]; - int[] planetId = new int[countILS]; - int[] workShipCount = new int[countILS]; - int[] idleShipCount = new int[countILS]; - ulong[] workShipIndices = new ulong[countILS]; - ulong[] idleShipIndices = new ulong[countILS]; - - List shipStage = new List(); - List shipDirection = new List(); - List shipWarpState = new List(); - List shipWarperCnt = new List(); - List shipItemID = new List(); - List shipItemCount = new List(); - List shipPlanetA = new List(); - List shipPlanetB = new List(); - List shipOtherGId = new List(); - List shipT = new List(); - List shipIndex = new List(); - List shipPos = new List(); - List shipRot = new List(); - List shipVel = new List(); - List shipSpeed = new List(); - List shipAngularVel = new List(); - List shipPPosTemp = new List(); - List shipPRotTemp = new List(); - - foreach (StationComponent stationComponent in GameMain.data.galacticTransport.stationPool) + foreach (var stationComponent in GameMain.data.galacticTransport.stationPool) + { + if (stationComponent != null) { - if (stationComponent != null) + stationGId[iter] = stationComponent.gid; + stationMaxShipCount[iter] = stationComponent.workShipDatas.Length; + stationId[iter] = stationComponent.id; + stationName[iter] = stationComponent.name; + DockPos[iter] = new Float3(stationComponent.shipDockPos); + DockRot[iter] = new Float4(stationComponent.shipDockRot); + planetId[iter] = stationComponent.planetId; + workShipCount[iter] = stationComponent.workShipCount; + idleShipCount[iter] = stationComponent.idleShipCount; + workShipIndices[iter] = stationComponent.workShipIndices; + idleShipIndices[iter] = stationComponent.idleShipIndices; + + // ShipData is never null + for (var j = 0; j < stationComponent.workShipDatas.Length; j++) { - stationGId[iter] = stationComponent.gid; - stationMaxShipCount[iter] = stationComponent.workShipDatas.Length; - stationId[iter] = stationComponent.id; - stationName[iter] = stationComponent.name; - DockPos[iter] = new Float3(stationComponent.shipDockPos); - DockRot[iter] = new Float4(stationComponent.shipDockRot); - planetId[iter] = stationComponent.planetId; - workShipCount[iter] = stationComponent.workShipCount; - idleShipCount[iter] = stationComponent.idleShipCount; - workShipIndices[iter] = stationComponent.workShipIndices; - idleShipIndices[iter] = stationComponent.idleShipIndices; - - // ShipData is never null - for (int j = 0; j < stationComponent.workShipDatas.Length; j++) - { - ShipData shipData = stationComponent.workShipDatas[j]; - - shipStage.Add(shipData.stage); - shipDirection.Add(shipData.direction); - shipWarpState.Add(shipData.warpState); - shipWarperCnt.Add(shipData.warperCnt); - shipItemID.Add(shipData.itemId); - shipItemCount.Add(shipData.itemCount); - shipPlanetA.Add(shipData.planetA); - shipPlanetB.Add(shipData.planetB); - shipOtherGId.Add(shipData.otherGId); - shipT.Add(shipData.t); - shipIndex.Add(shipData.shipIndex); - shipPos.Add(new Double3(shipData.uPos.x, shipData.uPos.y, shipData.uPos.z)); - shipRot.Add(new Float4(shipData.uRot)); - shipVel.Add(new Float3(shipData.uVel)); - shipSpeed.Add(shipData.uSpeed); - shipAngularVel.Add(new Float3(shipData.uAngularVel)); - shipPPosTemp.Add(new Double3(shipData.pPosTemp.x, shipData.pPosTemp.y, shipData.pPosTemp.z)); - shipPRotTemp.Add(new Float4(shipData.pRotTemp)); - } - - iter++; + var shipData = stationComponent.workShipDatas[j]; + + shipStage.Add(shipData.stage); + shipDirection.Add(shipData.direction); + shipWarpState.Add(shipData.warpState); + shipWarperCnt.Add(shipData.warperCnt); + shipItemID.Add(shipData.itemId); + shipItemCount.Add(shipData.itemCount); + shipPlanetA.Add(shipData.planetA); + shipPlanetB.Add(shipData.planetB); + shipOtherGId.Add(shipData.otherGId); + shipT.Add(shipData.t); + shipIndex.Add(shipData.shipIndex); + shipPos.Add(new Double3(shipData.uPos.x, shipData.uPos.y, shipData.uPos.z)); + shipRot.Add(new Float4(shipData.uRot)); + shipVel.Add(new Float3(shipData.uVel)); + shipSpeed.Add(shipData.uSpeed); + shipAngularVel.Add(new Float3(shipData.uAngularVel)); + shipPPosTemp.Add(new Double3(shipData.pPosTemp.x, shipData.pPosTemp.y, shipData.pPosTemp.z)); + shipPRotTemp.Add(new Float4(shipData.pRotTemp)); } - } - ILSgStationPoolSync packet2 = new ILSgStationPoolSync( - stationGId, - stationMaxShipCount, - stationId, - stationName, - DockPos, - DockRot, - planetId, - workShipCount, - idleShipCount, - workShipIndices, - idleShipIndices, - shipStage.ToArray(), - shipDirection.ToArray(), - shipWarpState.ToArray(), - shipWarperCnt.ToArray(), - shipItemID.ToArray(), - shipItemCount.ToArray(), - shipPlanetA.ToArray(), - shipPlanetB.ToArray(), - shipOtherGId.ToArray(), - shipT.ToArray(), - shipIndex.ToArray(), - shipPos.ToArray(), - shipRot.ToArray(), - shipVel.ToArray(), - shipSpeed.ToArray(), - shipAngularVel.ToArray(), - shipPPosTemp.ToArray(), - shipPRotTemp.ToArray()); - player.SendPacket(packet2); + iter++; + } } + + var packet2 = new ILSgStationPoolSync( + stationGId, + stationMaxShipCount, + stationId, + stationName, + DockPos, + DockRot, + planetId, + workShipCount, + idleShipCount, + workShipIndices, + idleShipIndices, + shipStage.ToArray(), + shipDirection.ToArray(), + shipWarpState.ToArray(), + shipWarperCnt.ToArray(), + shipItemID.ToArray(), + shipItemCount.ToArray(), + shipPlanetA.ToArray(), + shipPlanetB.ToArray(), + shipOtherGId.ToArray(), + shipT.ToArray(), + shipIndex.ToArray(), + shipPos.ToArray(), + shipRot.ToArray(), + shipVel.ToArray(), + shipSpeed.ToArray(), + shipAngularVel.ToArray(), + shipPPosTemp.ToArray(), + shipPRotTemp.ToArray()); + player.SendPacket(packet2); } } } diff --git a/NebulaNetwork/PacketProcessors/Logistics/RemoteOrderUpdateProcessor.cs b/NebulaNetwork/PacketProcessors/Logistics/RemoteOrderUpdateProcessor.cs index 4610fd719..abb43fd01 100644 --- a/NebulaNetwork/PacketProcessors/Logistics/RemoteOrderUpdateProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Logistics/RemoteOrderUpdateProcessor.cs @@ -1,45 +1,47 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Logistics; -using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Logistics +#endregion + +namespace NebulaNetwork.PacketProcessors.Logistics; + +[RegisterPacketProcessor] +public class RemoteOrderUpdateProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class RemoteOrderUpdateProcessor : PacketProcessor + public override void ProcessPacket(RemoteOrderUpdate packet, NebulaConnection conn) { - public override void ProcessPacket(RemoteOrderUpdate packet, NebulaConnection conn) + if (IsHost) + { + var stationComponent = GameMain.data.galacticTransport.stationPool[packet.StationGId]; + var storage = stationComponent?.storage; + if (stationComponent == null || storage.Length == 0) + { + return; + } + var remoteOrder = new int[storage.Length]; + for (var i = 0; i < stationComponent.storage.Length; i++) + { + remoteOrder[i] = storage[i].remoteOrder; + } + packet.RemoteOrder = remoteOrder; + conn.SendPacket(packet); + } + if (IsClient) { - if (IsHost) + var stationComponent = GameMain.data.galacticTransport.stationPool[packet.StationGId]; + var storage = stationComponent?.storage; + if (stationComponent == null || storage.Length == 0) { - StationComponent stationComponent = GameMain.data.galacticTransport.stationPool[packet.StationGId]; - StationStore[] storage = stationComponent?.storage; - if (stationComponent == null || storage.Length == 0) - { - return; - } - int[] remoteOrder = new int[storage.Length]; - for (int i = 0; i < stationComponent.storage.Length; i++) - { - remoteOrder[i] = storage[i].remoteOrder; - } - packet.RemoteOrder = remoteOrder; - conn.SendPacket(packet); + return; } - if (IsClient) + for (var i = 0; i < storage.Length; i++) { - StationComponent stationComponent = GameMain.data.galacticTransport.stationPool[packet.StationGId]; - StationStore[] storage = stationComponent?.storage; - if (stationComponent == null || storage.Length == 0) - { - return; - } - for (int i = 0; i < storage.Length; i++) - { - storage[i].remoteOrder = packet.RemoteOrder[i]; - } + storage[i].remoteOrder = packet.RemoteOrder[i]; } } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Logistics/StationUIInitialSyncProcessor.cs b/NebulaNetwork/PacketProcessors/Logistics/StationUIInitialSyncProcessor.cs index 6b3e5d7af..c123db3f4 100644 --- a/NebulaNetwork/PacketProcessors/Logistics/StationUIInitialSyncProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Logistics/StationUIInitialSyncProcessor.cs @@ -1,71 +1,76 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Logistics; using NebulaWorld; +#endregion + /* * When the client opens the UI of a station (ILS/PLS/Collector) the contents gets updated and shown to * the player once this packet is received. He will see a loading text before that. */ -namespace NebulaNetwork.PacketProcessors.Logistics +namespace NebulaNetwork.PacketProcessors.Logistics; + +[RegisterPacketProcessor] +public class StationUIInitialSyncProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class StationUIInitialSyncProcessor : PacketProcessor + public override void ProcessPacket(StationUIInitialSync packet, NebulaConnection conn) { - public override void ProcessPacket(StationUIInitialSync packet, NebulaConnection conn) - { - StationComponent stationComponent = null; - StationComponent[] stationPool = GameMain.data.galaxy.PlanetById(packet.PlanetId).factory.transport.stationPool; - // Assume the requesting station is on a loaded planet - stationComponent = stationPool?[packet.StationId]; + StationComponent stationComponent = null; + var stationPool = GameMain.data.galaxy.PlanetById(packet.PlanetId).factory.transport.stationPool; + // Assume the requesting station is on a loaded planet + stationComponent = stationPool?[packet.StationId]; - if (stationComponent == null) - { - Log.Error($"StationUIInitialSyncProcessor: Unable to find requested station on planet {packet.PlanetId} with id {packet.StationId} and gid of {packet.StationGId}"); - return; - } - if (stationComponent.gid > 0 && stationComponent.gid != packet.StationGId) - { - Log.Error($"StationGid desync! Host:{packet.StationGId} Local:{stationComponent.gid}"); - } + if (stationComponent == null) + { + Log.Error( + $"StationUIInitialSyncProcessor: Unable to find requested station on planet {packet.PlanetId} with id {packet.StationId} and gid of {packet.StationGId}"); + return; + } + if (stationComponent.gid > 0 && stationComponent.gid != packet.StationGId) + { + Log.Error($"StationGid desync! Host:{packet.StationGId} Local:{stationComponent.gid}"); + } - stationComponent.tripRangeDrones = packet.TripRangeDrones; - stationComponent.tripRangeShips = packet.TripRangeShips; - stationComponent.deliveryDrones = packet.DeliveryDrones; - stationComponent.deliveryShips = packet.DeliveryShips; - stationComponent.warpEnableDist = packet.WarperEnableDistance; - stationComponent.warperNecessary = packet.WarperNecessary; - stationComponent.includeOrbitCollector = packet.IncludeOrbitCollector; - stationComponent.energy = packet.Energy; - stationComponent.energyPerTick = packet.EnergyPerTick; - stationComponent.pilerCount = packet.PilerCount; + stationComponent.tripRangeDrones = packet.TripRangeDrones; + stationComponent.tripRangeShips = packet.TripRangeShips; + stationComponent.deliveryDrones = packet.DeliveryDrones; + stationComponent.deliveryShips = packet.DeliveryShips; + stationComponent.warpEnableDist = packet.WarperEnableDistance; + stationComponent.warperNecessary = packet.WarperNecessary; + stationComponent.includeOrbitCollector = packet.IncludeOrbitCollector; + stationComponent.energy = packet.Energy; + stationComponent.energyPerTick = packet.EnergyPerTick; + stationComponent.pilerCount = packet.PilerCount; - for (int i = 0; i < packet.ItemId.Length; i++) + for (var i = 0; i < packet.ItemId.Length; i++) + { + if (stationComponent.storage.Length == 0) { - if (stationComponent.storage.Length == 0) - { - stationComponent.storage = new StationStore[packet.ItemId.Length]; - } - - stationComponent.storage[i].itemId = packet.ItemId[i]; - stationComponent.storage[i].max = packet.ItemCountMax[i]; - stationComponent.storage[i].count = packet.ItemCount[i]; - stationComponent.storage[i].inc = packet.ItemInc[i]; - stationComponent.storage[i].remoteOrder = packet.RemoteOrder[i]; - stationComponent.storage[i].localLogic = (ELogisticStorage)packet.LocalLogic[i]; - stationComponent.storage[i].remoteLogic = (ELogisticStorage)packet.RemoteLogic[i]; + stationComponent.storage = new StationStore[packet.ItemId.Length]; } - UIStationWindow stationWindow = UIRoot.instance.uiGame.stationWindow; - if (stationWindow.active && stationWindow.factory?.planetId == packet.PlanetId && stationWindow.stationId == packet.StationId) + stationComponent.storage[i].itemId = packet.ItemId[i]; + stationComponent.storage[i].max = packet.ItemCountMax[i]; + stationComponent.storage[i].count = packet.ItemCount[i]; + stationComponent.storage[i].inc = packet.ItemInc[i]; + stationComponent.storage[i].remoteOrder = packet.RemoteOrder[i]; + stationComponent.storage[i].localLogic = (ELogisticStorage)packet.LocalLogic[i]; + stationComponent.storage[i].remoteLogic = (ELogisticStorage)packet.RemoteLogic[i]; + } + + var stationWindow = UIRoot.instance.uiGame.stationWindow; + if (stationWindow.active && stationWindow.factory?.planetId == packet.PlanetId && + stationWindow.stationId == packet.StationId) + { + using (Multiplayer.Session.StationsUI.IsIncomingRequest.On()) { - using (Multiplayer.Session.StationsUI.IsIncomingRequest.On()) - { - //Trigger OnStationIdChange() to refresh window - stationWindow.OnStationIdChange(); - } + //Trigger OnStationIdChange() to refresh window + stationWindow.OnStationIdChange(); } } } diff --git a/NebulaNetwork/PacketProcessors/Logistics/StationUIInitialSyncRequestProcessor.cs b/NebulaNetwork/PacketProcessors/Logistics/StationUIInitialSyncRequestProcessor.cs index dd022b121..57199a58c 100644 --- a/NebulaNetwork/PacketProcessors/Logistics/StationUIInitialSyncRequestProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Logistics/StationUIInitialSyncRequestProcessor.cs @@ -1,79 +1,83 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Logistics; +#endregion + /* * When a client opens a stations UI we sync the complete state of settings and storage. * After that he will receive live updates while the UI is opened. */ -namespace NebulaNetwork.PacketProcessors.Logistics +namespace NebulaNetwork.PacketProcessors.Logistics; + +[RegisterPacketProcessor] +public class StationUIInitialSyncRequestProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class StationUIInitialSyncRequestProcessor : PacketProcessor + public override void ProcessPacket(StationUIInitialSyncRequest packet, NebulaConnection conn) { - public override void ProcessPacket(StationUIInitialSyncRequest packet, NebulaConnection conn) + if (IsClient) { - if (IsClient) - { - return; - } - - StationComponent stationComponent; - StationComponent[] stationPool = GameMain.data.galaxy?.PlanetById(packet.PlanetId)?.factory?.transport?.stationPool; + return; + } - stationComponent = stationPool?[packet.StationId]; + StationComponent stationComponent; + var stationPool = GameMain.data.galaxy?.PlanetById(packet.PlanetId)?.factory?.transport?.stationPool; - if (stationComponent == null) - { - Log.Error($"StationUIInitialSyncRequestProcessor: Unable to find requested station on planet {packet.PlanetId} with id {packet.StationId} and gid {packet.StationGId}"); - return; - } + stationComponent = stationPool?[packet.StationId]; - StationStore[] storage = stationComponent.storage; + if (stationComponent == null) + { + Log.Error( + $"StationUIInitialSyncRequestProcessor: Unable to find requested station on planet {packet.PlanetId} with id {packet.StationId} and gid {packet.StationGId}"); + return; + } - int[] itemId = new int[storage.Length]; - int[] itemCountMax = new int[storage.Length]; - int[] itemCount = new int[storage.Length]; - int[] itemInc = new int[storage.Length]; - int[] localLogic = new int[storage.Length]; - int[] remoteLogic = new int[storage.Length]; - int[] remoteOrder = new int[storage.Length]; + var storage = stationComponent.storage; - for (int i = 0; i < stationComponent.storage.Length; i++) - { - itemId[i] = storage[i].itemId; - itemCountMax[i] = storage[i].max; - itemCount[i] = storage[i].count; - itemInc[i] = storage[i].inc; - localLogic[i] = (int)storage[i].localLogic; - remoteLogic[i] = (int)storage[i].remoteLogic; - remoteOrder[i] = storage[i].remoteOrder; - } + var itemId = new int[storage.Length]; + var itemCountMax = new int[storage.Length]; + var itemCount = new int[storage.Length]; + var itemInc = new int[storage.Length]; + var localLogic = new int[storage.Length]; + var remoteLogic = new int[storage.Length]; + var remoteOrder = new int[storage.Length]; - conn.SendPacket(new StationUIInitialSync( - packet.PlanetId, - packet.StationId, - packet.StationGId, - stationComponent.tripRangeDrones, - stationComponent.tripRangeShips, - stationComponent.deliveryDrones, - stationComponent.deliveryShips, - stationComponent.warpEnableDist, - stationComponent.warperNecessary, - stationComponent.includeOrbitCollector, - stationComponent.energy, - stationComponent.energyPerTick, - stationComponent.pilerCount, - itemId, - itemCountMax, - itemCount, - itemInc, - localLogic, - remoteLogic, - remoteOrder - )); + for (var i = 0; i < stationComponent.storage.Length; i++) + { + itemId[i] = storage[i].itemId; + itemCountMax[i] = storage[i].max; + itemCount[i] = storage[i].count; + itemInc[i] = storage[i].inc; + localLogic[i] = (int)storage[i].localLogic; + remoteLogic[i] = (int)storage[i].remoteLogic; + remoteOrder[i] = storage[i].remoteOrder; } + + conn.SendPacket(new StationUIInitialSync( + packet.PlanetId, + packet.StationId, + packet.StationGId, + stationComponent.tripRangeDrones, + stationComponent.tripRangeShips, + stationComponent.deliveryDrones, + stationComponent.deliveryShips, + stationComponent.warpEnableDist, + stationComponent.warperNecessary, + stationComponent.includeOrbitCollector, + stationComponent.energy, + stationComponent.energyPerTick, + stationComponent.pilerCount, + itemId, + itemCountMax, + itemCount, + itemInc, + localLogic, + remoteLogic, + remoteOrder + )); } } diff --git a/NebulaNetwork/PacketProcessors/Logistics/StationUIProcessor.cs b/NebulaNetwork/PacketProcessors/Logistics/StationUIProcessor.cs index c3e27026d..eb252c7d4 100644 --- a/NebulaNetwork/PacketProcessors/Logistics/StationUIProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Logistics/StationUIProcessor.cs @@ -1,38 +1,40 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Logistics; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Logistics +#endregion + +namespace NebulaNetwork.PacketProcessors.Logistics; + +[RegisterPacketProcessor] +internal class StationUIProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class StationUIProcessor : PacketProcessor + public override void ProcessPacket(StationUI packet, NebulaConnection conn) { - - public override void ProcessPacket(StationUI packet, NebulaConnection conn) + if (IsHost) { - if (IsHost) - { - // always update values for host - packet.ShouldRefund = false; - Multiplayer.Session.StationsUI.UpdateStation(ref packet); + // always update values for host + packet.ShouldRefund = false; + Multiplayer.Session.StationsUI.UpdateStation(ref packet); - // broadcast to other clients - IPlayerManager playerManager = Multiplayer.Session.Network.PlayerManager; - INebulaPlayer player = playerManager.GetPlayer(conn); - playerManager.SendPacketToOtherPlayers(packet, player); + // broadcast to other clients + IPlayerManager playerManager = Multiplayer.Session.Network.PlayerManager; + var player = playerManager.GetPlayer(conn); + playerManager.SendPacketToOtherPlayers(packet, player); - // as we block the normal method for the client he must run it once he receives this packet. - // but only the one issued the request should get items refund - packet.ShouldRefund = true; - conn.SendPacket(packet); - } + // as we block the normal method for the client he must run it once he receives this packet. + // but only the one issued the request should get items refund + packet.ShouldRefund = true; + conn.SendPacket(packet); + } - if (IsClient) - { - Multiplayer.Session.StationsUI.UpdateStation(ref packet); - } + if (IsClient) + { + Multiplayer.Session.StationsUI.UpdateStation(ref packet); } } } diff --git a/NebulaNetwork/PacketProcessors/Logistics/StorageUIProcessor.cs b/NebulaNetwork/PacketProcessors/Logistics/StorageUIProcessor.cs index 8cf737cb4..6102a13c4 100644 --- a/NebulaNetwork/PacketProcessors/Logistics/StorageUIProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Logistics/StorageUIProcessor.cs @@ -1,42 +1,46 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Logistics; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Logistics +#endregion + +namespace NebulaNetwork.PacketProcessors.Logistics; + +[RegisterPacketProcessor] +internal class StorageUIProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class StorageUIProcessor : PacketProcessor + private readonly IPlayerManager playerManager; + + public StorageUIProcessor() { - private readonly IPlayerManager playerManager; - public StorageUIProcessor() + playerManager = Multiplayer.Session.Network.PlayerManager; + } + + public override void ProcessPacket(StorageUI packet, NebulaConnection conn) + { + if (IsHost) { - playerManager = Multiplayer.Session.Network.PlayerManager; + // always update values for host + packet.ShouldRefund = false; + Multiplayer.Session.StationsUI.UpdateStorage(packet); + + // broadcast to other clients + var player = playerManager.GetPlayer(conn); + playerManager.SendPacketToOtherPlayers(packet, player); + + // as we block some methods for the client he must run it once he receives this packet. + // but only the one issued the request should get items refund + packet.ShouldRefund = true; + conn.SendPacket(packet); } - public override void ProcessPacket(StorageUI packet, NebulaConnection conn) + if (IsClient) { - if (IsHost) - { - // always update values for host - packet.ShouldRefund = false; - Multiplayer.Session.StationsUI.UpdateStorage(packet); - - // broadcast to other clients - INebulaPlayer player = playerManager.GetPlayer(conn); - playerManager.SendPacketToOtherPlayers(packet, player); - - // as we block some methods for the client he must run it once he receives this packet. - // but only the one issued the request should get items refund - packet.ShouldRefund = true; - conn.SendPacket(packet); - } - - if (IsClient) - { - Multiplayer.Session.StationsUI.UpdateStorage(packet); - } + Multiplayer.Session.StationsUI.UpdateStorage(packet); } } } diff --git a/NebulaNetwork/PacketProcessors/Planet/FactoryDataProcessor.cs b/NebulaNetwork/PacketProcessors/Planet/FactoryDataProcessor.cs index dd4a0ded9..bbfd40f96 100644 --- a/NebulaNetwork/PacketProcessors/Planet/FactoryDataProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Planet/FactoryDataProcessor.cs @@ -1,4 +1,7 @@ -using NebulaAPI; +#region + +using NebulaAPI; +using NebulaModel; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; @@ -6,33 +9,34 @@ using NebulaWorld; using NebulaWorld.GameStates; -namespace NebulaNetwork.PacketProcessors.Planet +#endregion + +namespace NebulaNetwork.PacketProcessors.Planet; + +[RegisterPacketProcessor] +public class FactoryDataProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class FactoryDataProcessor : PacketProcessor + public override void ProcessPacket(FactoryData packet, NebulaConnection conn) { - public override void ProcessPacket(FactoryData packet, NebulaConnection conn) + if (IsHost) { - if (IsHost) - { - return; - } - // The whole fragment is received - GameStatesManager.FragmentSize = 0; + return; + } + // The whole fragment is received + GameStatesManager.FragmentSize = 0; - // Stop packet processing until factory is imported and loaded - ((NebulaModel.NetworkProvider)Multiplayer.Session.Network).PacketProcessor.Enable = false; - Log.Info($"Pause PacketProcessor (FactoryDataProcessor)"); + // Stop packet processing until factory is imported and loaded + ((NetworkProvider)Multiplayer.Session.Network).PacketProcessor.Enable = false; + Log.Info("Pause PacketProcessor (FactoryDataProcessor)"); - PlanetData planet = GameMain.galaxy.PlanetById(packet.PlanetId); - Multiplayer.Session.Planets.PendingFactories.Add(packet.PlanetId, packet.BinaryData); - Multiplayer.Session.Planets.PendingTerrainData.Add(packet.PlanetId, packet.TerrainModData); - Log.Info($"Parsing {packet.BinaryData.Length} bytes of data for factory {planet.name} (ID: {planet.id})"); + var planet = GameMain.galaxy.PlanetById(packet.PlanetId); + Multiplayer.Session.Planets.PendingFactories.Add(packet.PlanetId, packet.BinaryData); + Multiplayer.Session.Planets.PendingTerrainData.Add(packet.PlanetId, packet.TerrainModData); + Log.Info($"Parsing {packet.BinaryData.Length} bytes of data for factory {planet.name} (ID: {planet.id})"); - lock (PlanetModelingManager.fctPlanetReqList) - { - PlanetModelingManager.fctPlanetReqList.Enqueue(planet); - } + lock (PlanetModelingManager.fctPlanetReqList) + { + PlanetModelingManager.fctPlanetReqList.Enqueue(planet); } } } diff --git a/NebulaNetwork/PacketProcessors/Planet/FactoryLoadRequestProcessor.cs b/NebulaNetwork/PacketProcessors/Planet/FactoryLoadRequestProcessor.cs index fc4de9877..9f4eb62a4 100644 --- a/NebulaNetwork/PacketProcessors/Planet/FactoryLoadRequestProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Planet/FactoryLoadRequestProcessor.cs @@ -1,46 +1,49 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; -using NebulaModel.Packets.Planet; using NebulaModel.Packets.GameStates; +using NebulaModel.Packets.Planet; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Planet +#endregion + +namespace NebulaNetwork.PacketProcessors.Planet; + +[RegisterPacketProcessor] +public class FactoryLoadRequestProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class FactoryLoadRequestProcessor : PacketProcessor + public override void ProcessPacket(FactoryLoadRequest packet, NebulaConnection conn) { - public override void ProcessPacket(FactoryLoadRequest packet, NebulaConnection conn) + if (IsClient) { - if (IsClient) - { - return; - } + return; + } - PlanetData planet = GameMain.galaxy.PlanetById(packet.PlanetID); - PlanetFactory factory = GameMain.data.GetOrCreateFactory(planet); + var planet = GameMain.galaxy.PlanetById(packet.PlanetID); + var factory = GameMain.data.GetOrCreateFactory(planet); - using (BinaryUtils.Writer writer = new BinaryUtils.Writer()) - { - factory.Export(writer.BinaryWriter); - byte[] data = writer.CloseAndGetBytes(); - Log.Info($"Sent {data.Length} bytes of data for PlanetFactory {planet.name} (ID: {planet.id})"); - conn.SendPacket(new FragmentInfo(data.Length + planet.data.modData.Length)); - conn.SendPacket(new FactoryData(packet.PlanetID, data, planet.data.modData)); - } + using (var writer = new BinaryUtils.Writer()) + { + factory.Export(writer.BinaryWriter); + var data = writer.CloseAndGetBytes(); + Log.Info($"Sent {data.Length} bytes of data for PlanetFactory {planet.name} (ID: {planet.id})"); + conn.SendPacket(new FragmentInfo(data.Length + planet.data.modData.Length)); + conn.SendPacket(new FactoryData(packet.PlanetID, data, planet.data.modData)); + } - // Add requesting client to connected player, so he can receive following update - IPlayerManager playerManager = Multiplayer.Session.Network.PlayerManager; - INebulaPlayer player = playerManager.GetSyncingPlayer(conn); - if (player != null) + // Add requesting client to connected player, so he can receive following update + IPlayerManager playerManager = Multiplayer.Session.Network.PlayerManager; + var player = playerManager.GetSyncingPlayer(conn); + if (player != null) + { + player.Data.LocalPlanetId = packet.PlanetID; + player.Data.LocalStarId = GameMain.galaxy.PlanetById(packet.PlanetID).star.id; + using (playerManager.GetConnectedPlayers(out var connectedPlayers)) { - player.Data.LocalPlanetId = packet.PlanetID; - player.Data.LocalStarId = GameMain.galaxy.PlanetById(packet.PlanetID).star.id; - using (playerManager.GetConnectedPlayers(out System.Collections.Generic.Dictionary connectedPlayers)) - { - connectedPlayers.Add(player.Connection, player); - } + connectedPlayers.Add(player.Connection, player); } } } diff --git a/NebulaNetwork/PacketProcessors/Planet/PlanetDataRequestProcessor.cs b/NebulaNetwork/PacketProcessors/Planet/PlanetDataRequestProcessor.cs index 3869e9c4c..b8bb46d72 100644 --- a/NebulaNetwork/PacketProcessors/Planet/PlanetDataRequestProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Planet/PlanetDataRequestProcessor.cs @@ -1,81 +1,84 @@ -using BepInEx; +#region + +using BepInEx; using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Planet; -namespace NebulaNetwork.PacketProcessors.Planet +#endregion + +namespace NebulaNetwork.PacketProcessors.Planet; + +[RegisterPacketProcessor] +public class PlanetDataRequestProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class PlanetDataRequestProcessor : PacketProcessor + public override void ProcessPacket(PlanetDataRequest packet, NebulaConnection conn) { - public override void ProcessPacket(PlanetDataRequest packet, NebulaConnection conn) + if (IsClient) { - if (IsClient) - { - return; - } - - foreach (int planetId in packet.PlanetIDs) - { - ThreadingHelper.Instance.StartAsyncInvoke(() => - { - byte[] data = PlanetCompute(planetId); - // use callback to run in mainthread - return () => conn.SendPacket(new PlanetDataResponse(planetId, data)); - }); - } + return; } - public static void OnActivePlanetLoaded(PlanetData planet) + foreach (var planetId in packet.PlanetIDs) { - planet.Unload(); - planet.onLoaded -= OnActivePlanetLoaded; + ThreadingHelper.Instance.StartAsyncInvoke(() => + { + var data = PlanetCompute(planetId); + // use callback to run in mainthread + return () => conn.SendPacket(new PlanetDataResponse(planetId, data)); + }); } + } - private static byte[] PlanetCompute(int planetId) - { - PlanetData planet = GameMain.galaxy.PlanetById(planetId); - HighStopwatch highStopwatch = new HighStopwatch(); - highStopwatch.Begin(); + public static void OnActivePlanetLoaded(PlanetData planet) + { + planet.Unload(); + planet.onLoaded -= OnActivePlanetLoaded; + } - // NOTE: The following has been picked-n-mixed from "PlanetModelingManager.PlanetComputeThreadMain()" - // This method is **costly** - do not run it more than is required! - // It generates the planet on the host and then sends it to the client + private static byte[] PlanetCompute(int planetId) + { + var planet = GameMain.galaxy.PlanetById(planetId); + var highStopwatch = new HighStopwatch(); + highStopwatch.Begin(); - PlanetAlgorithm planetAlgorithm = PlanetModelingManager.Algorithm(planet); + // NOTE: The following has been picked-n-mixed from "PlanetModelingManager.PlanetComputeThreadMain()" + // This method is **costly** - do not run it more than is required! + // It generates the planet on the host and then sends it to the client - if (planet.data == null) - { - planet.data = new PlanetRawData(planet.precision); - planet.modData = planet.data.InitModData(planet.modData); - planet.data.CalcVerts(); - planet.aux = new PlanetAuxData(planet); - planetAlgorithm.GenerateTerrain(planet.mod_x, planet.mod_y); - planetAlgorithm.CalcWaterPercent(); + var planetAlgorithm = PlanetModelingManager.Algorithm(planet); - //Load planet meshes and register callback to unload unneccessary stuff - planet.wanted = true; - planet.onLoaded += OnActivePlanetLoaded; - PlanetModelingManager.modPlanetReqList.Enqueue(planet); + if (planet.data == null) + { + planet.data = new PlanetRawData(planet.precision); + planet.modData = planet.data.InitModData(planet.modData); + planet.data.CalcVerts(); + planet.aux = new PlanetAuxData(planet); + planetAlgorithm.GenerateTerrain(planet.mod_x, planet.mod_y); + planetAlgorithm.CalcWaterPercent(); - if (planet.type != EPlanetType.Gas) - { - planetAlgorithm.GenerateVegetables(); - planetAlgorithm.GenerateVeins(); - } - planet.CalculateVeinGroups(); - } + //Load planet meshes and register callback to unload unneccessary stuff + planet.wanted = true; + planet.onLoaded += OnActivePlanetLoaded; + PlanetModelingManager.modPlanetReqList.Enqueue(planet); - byte[] data; - using (BinaryUtils.Writer writer = new BinaryUtils.Writer()) + if (planet.type != EPlanetType.Gas) { - planet.ExportRuntime(writer.BinaryWriter); - data = writer.CloseAndGetBytes(); + planetAlgorithm.GenerateVegetables(); + planetAlgorithm.GenerateVeins(); } - Log.Info($"Returning terrain for {planet.name} (id:{planet.id} time:{highStopwatch.duration:F4}s)"); - return data; + planet.CalculateVeinGroups(); + } + + byte[] data; + using (var writer = new BinaryUtils.Writer()) + { + planet.ExportRuntime(writer.BinaryWriter); + data = writer.CloseAndGetBytes(); } + Log.Info($"Returning terrain for {planet.name} (id:{planet.id} time:{highStopwatch.duration:F4}s)"); + return data; } } diff --git a/NebulaNetwork/PacketProcessors/Planet/PlanetDataResponseProcessor.cs b/NebulaNetwork/PacketProcessors/Planet/PlanetDataResponseProcessor.cs index b189c754c..420648548 100644 --- a/NebulaNetwork/PacketProcessors/Planet/PlanetDataResponseProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Planet/PlanetDataResponseProcessor.cs @@ -1,62 +1,65 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Planet; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Planet +#endregion + +namespace NebulaNetwork.PacketProcessors.Planet; + +[RegisterPacketProcessor] +public class PlanetDataResponseProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class PlanetDataResponseProcessor : PacketProcessor + public override void ProcessPacket(PlanetDataResponse packet, NebulaConnection conn) { - public override void ProcessPacket(PlanetDataResponse packet, NebulaConnection conn) + if (IsHost) { - if (IsHost) - { - return; - } + return; + } - PlanetData planet = null; + PlanetData planet = null; - if (Multiplayer.Session.IsInLobby) - { - planet = UIRoot.instance.galaxySelect.starmap._galaxyData.PlanetById(packet.PlanetDataID); - } - else - { - planet = GameMain.galaxy.PlanetById(packet.PlanetDataID); - } + if (Multiplayer.Session.IsInLobby) + { + planet = UIRoot.instance.galaxySelect.starmap._galaxyData.PlanetById(packet.PlanetDataID); + } + else + { + planet = GameMain.galaxy.PlanetById(packet.PlanetDataID); + } - Log.Info($"Parsing {packet.PlanetDataByte.Length} bytes of data for planet {planet.name} (ID: {planet.id})"); + Log.Info($"Parsing {packet.PlanetDataByte.Length} bytes of data for planet {planet.name} (ID: {planet.id})"); - using (BinaryUtils.Reader reader = new BinaryUtils.Reader(packet.PlanetDataByte)) - { - planet.ImportRuntime(reader.BinaryReader); - } + using (var reader = new BinaryUtils.Reader(packet.PlanetDataByte)) + { + planet.ImportRuntime(reader.BinaryReader); + } - if (Multiplayer.Session.IsInLobby) - { - // Pretend planet is loaded to make planetDetail show resources - planet.loaded = true; - UIRoot.instance.uiGame.planetDetail.RefreshDynamicProperties(); - } - else + if (Multiplayer.Session.IsInLobby) + { + // Pretend planet is loaded to make planetDetail show resources + planet.loaded = true; + UIRoot.instance.uiGame.planetDetail.RefreshDynamicProperties(); + } + else + { + lock (PlanetModelingManager.genPlanetReqList) { - lock (PlanetModelingManager.genPlanetReqList) - { - PlanetModelingManager.genPlanetReqList.Enqueue(planet); + PlanetModelingManager.genPlanetReqList.Enqueue(planet); - int localPlanetId = Multiplayer.Session.LocalPlayer.Data.LocalPlanetId; - if (planet.id == localPlanetId) + int localPlanetId = Multiplayer.Session.LocalPlayer.Data.LocalPlanetId; + if (planet.id == localPlanetId) + { + // Make local planet load first + while (PlanetModelingManager.genPlanetReqList.Peek().id != localPlanetId) { - // Make local planet load first - while (PlanetModelingManager.genPlanetReqList.Peek().id != localPlanetId) - { - PlanetData tmp = PlanetModelingManager.genPlanetReqList.Dequeue(); - PlanetModelingManager.genPlanetReqList.Enqueue(tmp); - } + var tmp = PlanetModelingManager.genPlanetReqList.Dequeue(); + PlanetModelingManager.genPlanetReqList.Enqueue(tmp); } } } diff --git a/NebulaNetwork/PacketProcessors/Planet/PlanetDetailRequestProcessor.cs b/NebulaNetwork/PacketProcessors/Planet/PlanetDetailRequestProcessor.cs index 61d2df08a..b744b2ce7 100644 --- a/NebulaNetwork/PacketProcessors/Planet/PlanetDetailRequestProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Planet/PlanetDetailRequestProcessor.cs @@ -1,60 +1,65 @@ -using NebulaAPI; +#region + +using System; +using System.Threading.Tasks; +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Planet; -using System; -using System.Threading.Tasks; -namespace NebulaNetwork.PacketProcessors.Planet +#endregion + +namespace NebulaNetwork.PacketProcessors.Planet; + +[RegisterPacketProcessor] +public class PlanetDetailRequestProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class PlanetDetailRequestProcessor : PacketProcessor + public override void ProcessPacket(PlanetDetailRequest packet, NebulaConnection conn) { - public override void ProcessPacket(PlanetDetailRequest packet, NebulaConnection conn) + if (IsClient) { - if (IsClient) - { - return; - } - PlanetData planetData = GameMain.galaxy.PlanetById(packet.PlanetID); - if (!planetData.calculated) + return; + } + var planetData = GameMain.galaxy.PlanetById(packet.PlanetID); + if (!planetData.calculated) + { + planetData.calculating = true; + Task.Run(() => { - planetData.calculating = true; - Task.Run(() => + try { - try + // Modify from PlanetModelingManager.PlanetCalculateThreadMain() + var highStopwatch = new HighStopwatch(); + highStopwatch.Begin(); + planetData.data = new PlanetRawData(planetData.precision); + planetData.modData = planetData.data.InitModData(planetData.modData); + planetData.data.CalcVerts(); + planetData.aux = new PlanetAuxData(planetData); + var planetAlgorithm = PlanetModelingManager.Algorithm(planetData); + planetAlgorithm.GenerateTerrain(planetData.mod_x, planetData.mod_y); + planetAlgorithm.CalcWaterPercent(); + if (planetData.type != EPlanetType.Gas) { - // Modify from PlanetModelingManager.PlanetCalculateThreadMain() - HighStopwatch highStopwatch = new HighStopwatch(); - highStopwatch.Begin(); - planetData.data = new PlanetRawData(planetData.precision); - planetData.modData = planetData.data.InitModData(planetData.modData); - planetData.data.CalcVerts(); - planetData.aux = new PlanetAuxData(planetData); - PlanetAlgorithm planetAlgorithm = PlanetModelingManager.Algorithm(planetData); - planetAlgorithm.GenerateTerrain(planetData.mod_x, planetData.mod_y); - planetAlgorithm.CalcWaterPercent(); - if (planetData.type != EPlanetType.Gas) - { - planetAlgorithm.GenerateVegetables(); - planetAlgorithm.GenerateVeins(); - } - planetData.CalculateVeinGroups(); - planetData.GenBirthPoints(); - planetData.NotifyCalculated(); - conn.SendPacket(new PlanetDetailResponse(planetData.id, planetData.runtimeVeinGroups ?? Array.Empty(), planetData.landPercent)); - Log.Info($"PlanetCalculateThread:{planetData.displayName} time:{highStopwatch.duration:F4}s"); + planetAlgorithm.GenerateVegetables(); + planetAlgorithm.GenerateVeins(); } - catch (Exception e) - { - Log.Warn($"Error when calculating {planetData.displayName}"); - Log.Warn(e); - } - }); - return; - } - conn.SendPacket(new PlanetDetailResponse(planetData.id, planetData.runtimeVeinGroups ?? Array.Empty(), planetData.landPercent)); + planetData.CalculateVeinGroups(); + planetData.GenBirthPoints(); + planetData.NotifyCalculated(); + conn.SendPacket(new PlanetDetailResponse(planetData.id, + planetData.runtimeVeinGroups ?? Array.Empty(), planetData.landPercent)); + Log.Info($"PlanetCalculateThread:{planetData.displayName} time:{highStopwatch.duration:F4}s"); + } + catch (Exception e) + { + Log.Warn($"Error when calculating {planetData.displayName}"); + Log.Warn(e); + } + }); + return; } + conn.SendPacket(new PlanetDetailResponse(planetData.id, planetData.runtimeVeinGroups ?? Array.Empty(), + planetData.landPercent)); } } diff --git a/NebulaNetwork/PacketProcessors/Planet/PlanetDetailResponseProcessor.cs b/NebulaNetwork/PacketProcessors/Planet/PlanetDetailResponseProcessor.cs index 5c16137ef..212e89dfd 100644 --- a/NebulaNetwork/PacketProcessors/Planet/PlanetDetailResponseProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Planet/PlanetDetailResponseProcessor.cs @@ -1,52 +1,55 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Planet; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Planet +#endregion + +namespace NebulaNetwork.PacketProcessors.Planet; + +[RegisterPacketProcessor] +public class PlanetDetailResponseProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class PlanetDetailResponseProcessor : PacketProcessor + public override void ProcessPacket(PlanetDetailResponse packet, NebulaConnection conn) { - public override void ProcessPacket(PlanetDetailResponse packet, NebulaConnection conn) + if (IsHost) { - if (IsHost) - { - return; - } + return; + } - PlanetData planet = null; + PlanetData planet = null; - if (Multiplayer.Session.IsInLobby) - { - planet = UIRoot.instance.galaxySelect.starmap._galaxyData.PlanetById(packet.PlanetDataID); - } - else + if (Multiplayer.Session.IsInLobby) + { + planet = UIRoot.instance.galaxySelect.starmap._galaxyData.PlanetById(packet.PlanetDataID); + } + else + { + planet = GameMain.galaxy.PlanetById(packet.PlanetDataID); + } + + if (packet.VeinCounts.Length > 0) + { + if (planet.veinGroups == null || planet.veinGroups.Length != packet.VeinCounts.Length) { - planet = GameMain.galaxy.PlanetById(packet.PlanetDataID); + planet.veinGroups = new VeinGroup[packet.VeinCounts.Length]; } - - if (packet.VeinCounts.Length > 0) + for (var i = 1; i < planet.veinGroups.Length; i++) { - if (planet.veinGroups == null || planet.veinGroups.Length != packet.VeinCounts.Length) - { - planet.veinGroups = new VeinGroup[packet.VeinCounts.Length]; - } - for (int i = 1; i < planet.veinGroups.Length; i++) - { - planet.veinGroups[i].type = (EVeinType)packet.VeinTypes[i]; - planet.veinGroups[i].count = packet.VeinCounts[i]; - planet.veinGroups[i].amount = packet.VeinAmounts[i]; - } + planet.veinGroups[i].type = (EVeinType)packet.VeinTypes[i]; + planet.veinGroups[i].count = packet.VeinCounts[i]; + planet.veinGroups[i].amount = packet.VeinAmounts[i]; } - planet.landPercent = packet.LandPercent; - planet.landPercentDirty = false; - - //planet.NotifyCalculated(); - planet.calculating = false; - planet.calculated = true; } + planet.landPercent = packet.LandPercent; + planet.landPercentDirty = false; + + //planet.NotifyCalculated(); + planet.calculating = false; + planet.calculated = true; } } diff --git a/NebulaNetwork/PacketProcessors/Planet/VegeAddProcessor.cs b/NebulaNetwork/PacketProcessors/Planet/VegeAddProcessor.cs index ddc5e53f1..45ee59aef 100644 --- a/NebulaNetwork/PacketProcessors/Planet/VegeAddProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Planet/VegeAddProcessor.cs @@ -1,95 +1,101 @@ -using NebulaAPI; -using NebulaModel.Logger; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Planet; using NebulaWorld; using UnityEngine; -namespace NebulaNetwork.PacketProcessors.Planet -{ - // Processes events for adding vegetation or veins in sandbox mode - [RegisterPacketProcessor] - internal class VegeAddProcessor : PacketProcessor +#endregion + +namespace NebulaNetwork.PacketProcessors.Planet; + +// Processes events for adding vegetation or veins in sandbox mode +[RegisterPacketProcessor] +internal class VegeAddProcessor : PacketProcessor +{ + public override void ProcessPacket(VegeAddPacket packet, NebulaConnection conn) { - public override void ProcessPacket(VegeAddPacket packet, NebulaConnection conn) + using (Multiplayer.Session.Planets.IsIncomingRequest.On()) { - using (Multiplayer.Session.Planets.IsIncomingRequest.On()) + var planet = GameMain.galaxy.PlanetById(packet.PlanetId); + var factory = planet?.factory; + if (factory == null) { - PlanetData planet = GameMain.galaxy.PlanetById(packet.PlanetId); - PlanetFactory factory = planet?.factory; - if (factory == null) - { - return; - } - Multiplayer.Session.Factories.TargetPlanet = packet.PlanetId; - Multiplayer.Session.Factories.EventFactory = factory; - Multiplayer.Session.Factories.AddPlanetTimer(packet.PlanetId); - PlanetData pData = GameMain.gpuiManager.specifyPlanet; - GameMain.gpuiManager.specifyPlanet = planet; + return; + } + Multiplayer.Session.Factories.TargetPlanet = packet.PlanetId; + Multiplayer.Session.Factories.EventFactory = factory; + Multiplayer.Session.Factories.AddPlanetTimer(packet.PlanetId); + var pData = GameMain.gpuiManager.specifyPlanet; + GameMain.gpuiManager.specifyPlanet = planet; - if (packet.IsVein) + if (packet.IsVein) + { + VeinData veinData = new(); + using (BinaryUtils.Reader reader = new(packet.Data)) { - VeinData veinData = new(); - using (BinaryUtils.Reader reader = new (packet.Data)) - { - veinData.Import(reader.BinaryReader); - } + veinData.Import(reader.BinaryReader); + } - // Modify from PlayerAction_Plant.PlantVeinFinally - factory.AssignGroupIndexForNewVein(ref veinData); - int veinId = planet.factory.AddVeinData(veinData); - Quaternion rot = Quaternion.FromToRotation(Vector3.up, veinData.pos.normalized); - VeinData[] veinPool = planet.factory.veinPool; - if (planet == GameMain.localPlanet) - { - // Only add model on local planet - veinPool[veinId].modelId = planet.factoryModel.gpuiManager.AddModel(veinData.modelIndex, veinId, veinData.pos, rot, true); - } + // Modify from PlayerAction_Plant.PlantVeinFinally + factory.AssignGroupIndexForNewVein(ref veinData); + var veinId = planet.factory.AddVeinData(veinData); + var rot = Quaternion.FromToRotation(Vector3.up, veinData.pos.normalized); + var veinPool = planet.factory.veinPool; + if (planet == GameMain.localPlanet) + { + // Only add model on local planet + veinPool[veinId].modelId = + planet.factoryModel.gpuiManager.AddModel(veinData.modelIndex, veinId, veinData.pos, rot); + } - VeinProto veinProto = LDB.veins.Select((int)veinData.type); - ColliderData[] colliders = veinProto.prefabDesc.colliders; - int num2 = 0; - while (colliders != null && num2 < colliders.Length) - { - veinPool[veinId].colliderId = planet.physics.AddColliderData(colliders[num2].BindToObject(veinId, veinPool[veinId].colliderId, EObjectType.Vein, veinData.pos, rot)); - num2++; - } - factory.RefreshVeinMiningDisplay(veinId, 0, 0); - factory.RecalculateVeinGroup(veinData.groupIndex); + var veinProto = LDB.veins.Select((int)veinData.type); + var colliders = veinProto.prefabDesc.colliders; + var num2 = 0; + while (colliders != null && num2 < colliders.Length) + { + veinPool[veinId].colliderId = planet.physics.AddColliderData(colliders[num2] + .BindToObject(veinId, veinPool[veinId].colliderId, EObjectType.Vein, veinData.pos, rot)); + num2++; } - else + factory.RefreshVeinMiningDisplay(veinId, 0, 0); + factory.RecalculateVeinGroup(veinData.groupIndex); + } + else + { + VegeData vegeData = new(); + using (BinaryUtils.Reader reader = new(packet.Data)) { - VegeData vegeData = new(); - using (BinaryUtils.Reader reader = new(packet.Data)) - { - vegeData.Import(reader.BinaryReader); - } - - // Modify from PlayerAction_Plant.PlantVegeFinally - int num = planet.factory.AddVegeData(vegeData); - VegeData[] vegePool = planet.factory.vegePool; - if (planet == GameMain.localPlanet) - { - // Only add model on local planet - vegePool[num].modelId = planet.factoryModel.gpuiManager.AddModel(vegeData.modelIndex, num, vegeData.pos, vegeData.rot, true); - } + vegeData.Import(reader.BinaryReader); + } - VegeProto vegeProto = LDB.veges.Select(vegeData.protoId); - ColliderData[] colliders = vegeProto.prefabDesc.colliders; - int num2 = 0; - while (colliders != null && num2 < colliders.Length) - { - vegePool[num].colliderId = planet.physics.AddColliderData(colliders[num2].BindToObject(num, vegePool[num].colliderId, EObjectType.Vegetable, vegeData.pos, vegeData.rot, Vector3.one)); - num2++; - } - planet.physics.SetPlanetPhysicsColliderDirty(); + // Modify from PlayerAction_Plant.PlantVegeFinally + var num = planet.factory.AddVegeData(vegeData); + var vegePool = planet.factory.vegePool; + if (planet == GameMain.localPlanet) + { + // Only add model on local planet + vegePool[num].modelId = + planet.factoryModel.gpuiManager.AddModel(vegeData.modelIndex, num, vegeData.pos, vegeData.rot); } - GameMain.gpuiManager.specifyPlanet = pData; - Multiplayer.Session.Factories.TargetPlanet = NebulaModAPI.PLANET_NONE; - Multiplayer.Session.Factories.EventFactory = null; + var vegeProto = LDB.veges.Select(vegeData.protoId); + var colliders = vegeProto.prefabDesc.colliders; + var num2 = 0; + while (colliders != null && num2 < colliders.Length) + { + vegePool[num].colliderId = planet.physics.AddColliderData(colliders[num2].BindToObject(num, + vegePool[num].colliderId, EObjectType.Vegetable, vegeData.pos, vegeData.rot, Vector3.one)); + num2++; + } + planet.physics.SetPlanetPhysicsColliderDirty(); } + + GameMain.gpuiManager.specifyPlanet = pData; + Multiplayer.Session.Factories.TargetPlanet = NebulaModAPI.PLANET_NONE; + Multiplayer.Session.Factories.EventFactory = null; } - } + } } diff --git a/NebulaNetwork/PacketProcessors/Planet/VegeMinedProcessor.cs b/NebulaNetwork/PacketProcessors/Planet/VegeMinedProcessor.cs index ad12e850e..f2383bb88 100644 --- a/NebulaNetwork/PacketProcessors/Planet/VegeMinedProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Planet/VegeMinedProcessor.cs @@ -1,69 +1,74 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Planet; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Planet +#endregion + +namespace NebulaNetwork.PacketProcessors.Planet; + +// Processes events for mining vegetation or veins +[RegisterPacketProcessor] +internal class VegeMinedProcessor : PacketProcessor { - // Processes events for mining vegetation or veins - [RegisterPacketProcessor] - internal class VegeMinedProcessor : PacketProcessor + public override void ProcessPacket(VegeMinedPacket packet, NebulaConnection conn) { - public override void ProcessPacket(VegeMinedPacket packet, NebulaConnection conn) + var planetData = GameMain.galaxy.PlanetById(packet.PlanetId); + var factory = planetData?.factory; + if (factory != null && factory?.vegePool != null) { - PlanetData planetData = GameMain.galaxy.PlanetById(packet.PlanetId); - PlanetFactory factory = planetData?.factory; - if (factory != null && factory?.vegePool != null) + using (Multiplayer.Session.Planets.IsIncomingRequest.On()) { - using (Multiplayer.Session.Planets.IsIncomingRequest.On()) + if (packet.Amount == 0 && factory != null) { - if (packet.Amount == 0 && factory != null) + if (packet.IsVein) { - if (packet.IsVein) - { - VeinData veinData = factory.GetVeinData(packet.VegeId); - VeinProto veinProto = LDB.veins.Select((int)veinData.type); - - factory.RemoveVeinWithComponents(packet.VegeId); - - if (veinProto != null && GameMain.localPlanet == planetData) - { - VFEffectEmitter.Emit(veinProto.MiningEffect, veinData.pos, Maths.SphericalRotation(veinData.pos, 0f)); - VFAudio.Create(veinProto.MiningAudio, null, veinData.pos, true, 0, -1, -1L); - } - } - else - { - VegeData vegeData = factory.GetVegeData(packet.VegeId); - VegeProto vegeProto = LDB.veges.Select(vegeData.protoId); + var veinData = factory.GetVeinData(packet.VegeId); + var veinProto = LDB.veins.Select((int)veinData.type); - factory.RemoveVegeWithComponents(packet.VegeId); + factory.RemoveVeinWithComponents(packet.VegeId); - if (vegeProto != null && GameMain.localPlanet == planetData) - { - VFEffectEmitter.Emit(vegeProto.MiningEffect, vegeData.pos, Maths.SphericalRotation(vegeData.pos, 0f)); - VFAudio.Create(vegeProto.MiningAudio, null, vegeData.pos, true, 0, -1, -1L); - } + if (veinProto != null && GameMain.localPlanet == planetData) + { + VFEffectEmitter.Emit(veinProto.MiningEffect, veinData.pos, + Maths.SphericalRotation(veinData.pos, 0f)); + VFAudio.Create(veinProto.MiningAudio, null, veinData.pos, true); } } - else if (factory != null) - { - // Taken from if (!isInfiniteResource) part of PlayerAction_Mine.GameTick() - VeinData veinData = factory.GetVeinData(packet.VegeId); - VeinGroup[] veinGroups = factory.veinGroups; - short groupIndex = veinData.groupIndex; - - // must be a vein/oil patch (i think the game treats them same now as oil patches can run out too) - factory.veinPool[packet.VegeId].amount = packet.Amount; - veinGroups[groupIndex].amount = veinGroups[groupIndex].amount - 1L; - } else { - Log.Warn("Received VegeMinedPacket but could not do as i was told :C"); + var vegeData = factory.GetVegeData(packet.VegeId); + var vegeProto = LDB.veges.Select(vegeData.protoId); + + factory.RemoveVegeWithComponents(packet.VegeId); + + if (vegeProto != null && GameMain.localPlanet == planetData) + { + VFEffectEmitter.Emit(vegeProto.MiningEffect, vegeData.pos, + Maths.SphericalRotation(vegeData.pos, 0f)); + VFAudio.Create(vegeProto.MiningAudio, null, vegeData.pos, true); + } } } + else if (factory != null) + { + // Taken from if (!isInfiniteResource) part of PlayerAction_Mine.GameTick() + var veinData = factory.GetVeinData(packet.VegeId); + var veinGroups = factory.veinGroups; + var groupIndex = veinData.groupIndex; + + // must be a vein/oil patch (i think the game treats them same now as oil patches can run out too) + factory.veinPool[packet.VegeId].amount = packet.Amount; + veinGroups[groupIndex].amount = veinGroups[groupIndex].amount - 1L; + } + else + { + Log.Warn("Received VegeMinedPacket but could not do as i was told :C"); + } } } } diff --git a/NebulaNetwork/PacketProcessors/Players/NewDroneOrderProcessor.cs b/NebulaNetwork/PacketProcessors/Players/NewDroneOrderProcessor.cs index 471b0162b..e5b05b1fd 100644 --- a/NebulaNetwork/PacketProcessors/Players/NewDroneOrderProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Players/NewDroneOrderProcessor.cs @@ -1,46 +1,49 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Players; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Players +#endregion + +namespace NebulaNetwork.PacketProcessors.Players; + +[RegisterPacketProcessor] +internal class NewDroneOrderProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class NewDroneOrderProcessor : PacketProcessor + private readonly IPlayerManager playerManager; + + public NewDroneOrderProcessor() { - private readonly IPlayerManager playerManager; + playerManager = Multiplayer.Session.Network.PlayerManager; + } - public NewDroneOrderProcessor() + public override void ProcessPacket(NewDroneOrderPacket packet, NebulaConnection conn) + { + // Host does not need to know about flying drones of other players if he is not on the same planet + if (IsHost) { - playerManager = Multiplayer.Session.Network.PlayerManager; - } + if (GameMain.mainPlayer.planetId != packet.PlanetId) + { + return; + } - public override void ProcessPacket(NewDroneOrderPacket packet, NebulaConnection conn) - { - // Host does not need to know about flying drones of other players if he is not on the same planet - if (IsHost) + var player = playerManager.GetPlayer(conn); + if (player != null) { - if (GameMain.mainPlayer.planetId != packet.PlanetId) + if (packet.Stage == 1 || packet.Stage == 2) { - return; + Multiplayer.Session.Drones.AddPlayerDronePlan(player.Id, packet.EntityId); } - - INebulaPlayer player = playerManager.GetPlayer(conn); - if (player != null) + else if (packet.Stage == 3) { - if (packet.Stage == 1 || packet.Stage == 2) - { - Multiplayer.Session.Drones.AddPlayerDronePlan(player.Id, packet.EntityId); - } - else if (packet.Stage == 3) - { - Multiplayer.Session.Drones.RemovePlayerDronePlan(player.Id, packet.EntityId); - } + Multiplayer.Session.Drones.RemovePlayerDronePlan(player.Id, packet.EntityId); } } - - Multiplayer.Session.World.UpdateRemotePlayerDrone(packet); } + + Multiplayer.Session.World.UpdateRemotePlayerDrone(packet); } } diff --git a/NebulaNetwork/PacketProcessors/Players/PlayerMechaArmorProcessor.cs b/NebulaNetwork/PacketProcessors/Players/PlayerMechaArmorProcessor.cs index 6a3f7395a..74ffa1df1 100644 --- a/NebulaNetwork/PacketProcessors/Players/PlayerMechaArmorProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Players/PlayerMechaArmorProcessor.cs @@ -1,89 +1,91 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Players; using NebulaWorld; -using System.Collections.Generic; -namespace NebulaNetwork.PacketProcessors.Players +#endregion + +namespace NebulaNetwork.PacketProcessors.Players; + +[RegisterPacketProcessor] +public class PlayerMechaArmorProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class PlayerMechaArmorProcessor: PacketProcessor + private readonly IPlayerManager playerManager; + + public PlayerMechaArmorProcessor() { - private readonly IPlayerManager playerManager; + playerManager = Multiplayer.Session.Network.PlayerManager; + } - public PlayerMechaArmorProcessor() + public override void ProcessPacket(PlayerMechaArmor packet, NebulaConnection conn) + { + INebulaPlayer player = null; + if (IsHost) { - playerManager = Multiplayer.Session.Network.PlayerManager; + // broadcast to other players + player = playerManager.GetPlayer(conn); + if (player != null) + { + playerManager.SendPacketToOtherPlayers(packet, player); + } } - public override void ProcessPacket(PlayerMechaArmor packet, NebulaConnection conn) + using (var reader = new BinaryUtils.Reader(packet.AppearanceData)) { - INebulaPlayer player = null; - if (IsHost) + if (Multiplayer.Session.LocalPlayer.Id == packet.PlayerId) { - // broadcast to other players - player = playerManager.GetPlayer(conn); - if (player != null) - { - playerManager.SendPacketToOtherPlayers(packet, player); - } - } + GameMain.mainPlayer.mecha.appearance.Import(reader.BinaryReader); + GameMain.mainPlayer.mechaArmorModel.RefreshAllPartObjects(); + GameMain.mainPlayer.mechaArmorModel.RefreshAllBoneObjects(); + GameMain.mainPlayer.mecha.appearance.NotifyAllEvents(); + GameMain.mainPlayer.mechaArmorModel._Init(GameMain.mainPlayer); + GameMain.mainPlayer.mechaArmorModel._OnOpen(); - using (BinaryUtils.Reader reader = new BinaryUtils.Reader(packet.AppearanceData)) - { - if(Multiplayer.Session.LocalPlayer.Id == packet.PlayerId) + // and also load it in the mecha editor + var editor = UIRoot.instance.uiMechaEditor; + if (editor != null) { - GameMain.mainPlayer.mecha.appearance.Import(reader.BinaryReader); - GameMain.mainPlayer.mechaArmorModel.RefreshAllPartObjects(); - GameMain.mainPlayer.mechaArmorModel.RefreshAllBoneObjects(); - GameMain.mainPlayer.mecha.appearance.NotifyAllEvents(); - GameMain.mainPlayer.mechaArmorModel._Init(GameMain.mainPlayer); - GameMain.mainPlayer.mechaArmorModel._OnOpen(); - - // and also load it in the mecha editor - UIMechaEditor editor = UIRoot.instance.uiMechaEditor; - if(editor != null) + editor.selection.ClearSelection(); + editor.saveGroup._Close(); + if (editor.mecha.diyAppearance == null) { - editor.selection.ClearSelection(); - editor.saveGroup._Close(); - if(editor.mecha.diyAppearance == null) - { - editor.mecha.diyAppearance = new MechaAppearance(); - editor.mecha.diyAppearance.Init(); - } - GameMain.mainPlayer.mecha.appearance.CopyTo(editor.mecha.diyAppearance); - editor.mechaArmorModel.RefreshAllPartObjects(); - editor.mechaArmorModel.RefreshAllBoneObjects(); - editor.mecha.diyAppearance.NotifyAllEvents(); - editor._left_content_height_max = 0f; - editor.SetLeftScrollTop(); - editor.saveGroup._Open(); + editor.mecha.diyAppearance = new MechaAppearance(); + editor.mecha.diyAppearance.Init(); } + GameMain.mainPlayer.mecha.appearance.CopyTo(editor.mecha.diyAppearance); + editor.mechaArmorModel.RefreshAllPartObjects(); + editor.mechaArmorModel.RefreshAllBoneObjects(); + editor.mecha.diyAppearance.NotifyAllEvents(); + editor._left_content_height_max = 0f; + editor.SetLeftScrollTop(); + editor.saveGroup._Open(); } - else + } + else + { + using (Multiplayer.Session.World.GetRemotePlayersModels(out var remotePlayersModels)) { - using (Multiplayer.Session.World.GetRemotePlayersModels(out Dictionary remotePlayersModels)) + if (remotePlayersModels.TryGetValue(packet.PlayerId, out var playerModel)) { - if (remotePlayersModels.TryGetValue(packet.PlayerId, out RemotePlayerModel playerModel)) - { - playerModel.MechaInstance.appearance.Import(reader.BinaryReader); - playerModel.PlayerInstance.mechaArmorModel.RefreshAllPartObjects(); - playerModel.PlayerInstance.mechaArmorModel.RefreshAllBoneObjects(); - playerModel.MechaInstance.appearance.NotifyAllEvents(); - playerModel.PlayerInstance.mechaArmorModel._Init(playerModel.PlayerInstance); - playerModel.PlayerInstance.mechaArmorModel._OnOpen(); + playerModel.MechaInstance.appearance.Import(reader.BinaryReader); + playerModel.PlayerInstance.mechaArmorModel.RefreshAllPartObjects(); + playerModel.PlayerInstance.mechaArmorModel.RefreshAllBoneObjects(); + playerModel.MechaInstance.appearance.NotifyAllEvents(); + playerModel.PlayerInstance.mechaArmorModel._Init(playerModel.PlayerInstance); + playerModel.PlayerInstance.mechaArmorModel._OnOpen(); - // and store the appearance on the server - if (IsHost && player != null) + // and store the appearance on the server + if (IsHost && player != null) + { + if (player.Data.Appearance == null) { - if (player.Data.Appearance == null) - { - player.Data.Appearance = new MechaAppearance(); - player.Data.Appearance.Init(); - } - playerModel.MechaInstance.appearance.CopyTo(player.Data.Appearance); + player.Data.Appearance = new MechaAppearance(); + player.Data.Appearance.Init(); } + playerModel.MechaInstance.appearance.CopyTo(player.Data.Appearance); } } } diff --git a/NebulaNetwork/PacketProcessors/Players/PlayerMechaDIYArmorProcessor.cs b/NebulaNetwork/PacketProcessors/Players/PlayerMechaDIYArmorProcessor.cs index a86305d3f..1fdf57488 100644 --- a/NebulaNetwork/PacketProcessors/Players/PlayerMechaDIYArmorProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Players/PlayerMechaDIYArmorProcessor.cs @@ -1,83 +1,87 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Players; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Players +#endregion + +namespace NebulaNetwork.PacketProcessors.Players; + +[RegisterPacketProcessor] +public class PlayerMechaDIYArmorProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class PlayerMechaDIYArmorProcessor : PacketProcessor + private readonly IPlayerManager playerManager; + + public PlayerMechaDIYArmorProcessor() { - private readonly IPlayerManager playerManager; - public PlayerMechaDIYArmorProcessor() - { - playerManager = Multiplayer.Session.Network.PlayerManager; - } + playerManager = Multiplayer.Session.Network.PlayerManager; + } - public override void ProcessPacket(PlayerMechaDIYArmor packet, NebulaConnection conn) + public override void ProcessPacket(PlayerMechaDIYArmor packet, NebulaConnection conn) + { + // store DIYAppearance and items to serve them when player connects again + if (IsHost) { - // store DIYAppearance and items to serve them when player connects again - if (IsHost) + using (var reader = new BinaryUtils.Reader(packet.DIYAppearanceData)) { - using (BinaryUtils.Reader reader = new BinaryUtils.Reader(packet.DIYAppearanceData)) + var player = playerManager.GetPlayer(conn); + if (player != null) { - INebulaPlayer player = playerManager.GetPlayer(conn); - if(player != null) + if (player.Data.DIYAppearance == null) { - if(player.Data.DIYAppearance == null) - { - player.Data.DIYAppearance = new MechaAppearance(); - player.Data.DIYAppearance.Init(); - } - player.Data.DIYAppearance.Import(reader.BinaryReader); - - player.Data.DIYItemId = packet.DIYItemId; - player.Data.DIYItemValue = packet.DIYItemValue; + player.Data.DIYAppearance = new MechaAppearance(); + player.Data.DIYAppearance.Init(); } + player.Data.DIYAppearance.Import(reader.BinaryReader); + + player.Data.DIYItemId = packet.DIYItemId; + player.Data.DIYItemValue = packet.DIYItemValue; } } - else + } + else + { + // load DIYAppearance received from host to display in mecha appearance editor + using (var reader = new BinaryUtils.Reader(packet.DIYAppearanceData)) { - // load DIYAppearance received from host to display in mecha appearance editor - using (BinaryUtils.Reader reader = new BinaryUtils.Reader(packet.DIYAppearanceData)) - { - Player player = GameMain.mainPlayer; - UIMechaEditor editor = UIRoot.instance.uiMechaEditor; + var player = GameMain.mainPlayer; + var editor = UIRoot.instance.uiMechaEditor; - if (player.mecha.diyAppearance == null) - { - player.mecha.diyAppearance = new MechaAppearance(); - player.mecha.diyAppearance.Init(); - } - player.mecha.diyAppearance.Import(reader.BinaryReader); + if (player.mecha.diyAppearance == null) + { + player.mecha.diyAppearance = new MechaAppearance(); + player.mecha.diyAppearance.Init(); + } + player.mecha.diyAppearance.Import(reader.BinaryReader); - if(packet.DIYItemId.Length > 0) + if (packet.DIYItemId.Length > 0) + { + player.mecha.diyItems.Clear(); + for (var i = 0; i < packet.DIYItemId.Length; i++) { - player.mecha.diyItems.Clear(); - for(int i = 0; i < packet.DIYItemId.Length; i++) - { - player.mecha.diyItems.items[packet.DIYItemId[i]] = packet.DIYItemValue[i]; - } + player.mecha.diyItems.items[packet.DIYItemId[i]] = packet.DIYItemValue[i]; } + } - if (editor != null) + if (editor != null) + { + editor.selection.ClearSelection(); + editor.saveGroup._Close(); + if (editor.mecha.diyAppearance == null) { - editor.selection.ClearSelection(); - editor.saveGroup._Close(); - if (editor.mecha.diyAppearance == null) - { - editor.mecha.diyAppearance = new MechaAppearance(); - editor.mecha.diyAppearance.Init(); - } - GameMain.mainPlayer.mecha.diyAppearance.CopyTo(editor.mecha.diyAppearance); - editor.mechaArmorModel.RefreshAllPartObjects(); - editor.mechaArmorModel.RefreshAllBoneObjects(); - editor.mecha.diyAppearance.NotifyAllEvents(); - editor._left_content_height_max = 0f; - editor.SetLeftScrollTop(); - editor.saveGroup._Open(); + editor.mecha.diyAppearance = new MechaAppearance(); + editor.mecha.diyAppearance.Init(); } + GameMain.mainPlayer.mecha.diyAppearance.CopyTo(editor.mecha.diyAppearance); + editor.mechaArmorModel.RefreshAllPartObjects(); + editor.mechaArmorModel.RefreshAllBoneObjects(); + editor.mecha.diyAppearance.NotifyAllEvents(); + editor._left_content_height_max = 0f; + editor.SetLeftScrollTop(); + editor.saveGroup._Open(); } } } diff --git a/NebulaNetwork/PacketProcessors/Players/PlayerMechaDataProcessor.cs b/NebulaNetwork/PacketProcessors/Players/PlayerMechaDataProcessor.cs index b889e29a6..8cd443257 100644 --- a/NebulaNetwork/PacketProcessors/Players/PlayerMechaDataProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Players/PlayerMechaDataProcessor.cs @@ -1,29 +1,32 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Players; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Players +#endregion + +namespace NebulaNetwork.PacketProcessors.Players; + +[RegisterPacketProcessor] +internal class PlayerMechaDataProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class PlayerMechaDataProcessor : PacketProcessor + private readonly IPlayerManager playerManager; + + public PlayerMechaDataProcessor() { - private readonly IPlayerManager playerManager; + playerManager = Multiplayer.Session.Network.PlayerManager; + } - public PlayerMechaDataProcessor() + public override void ProcessPacket(PlayerMechaData packet, NebulaConnection conn) + { + if (IsClient) { - playerManager = Multiplayer.Session.Network.PlayerManager; + return; } - public override void ProcessPacket(PlayerMechaData packet, NebulaConnection conn) - { - if (IsClient) - { - return; - } - - playerManager.UpdateMechaData(packet.Data, conn); - } + playerManager.UpdateMechaData(packet.Data, conn); } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Players/PlayerMechaStatProcessor.cs b/NebulaNetwork/PacketProcessors/Players/PlayerMechaStatProcessor.cs index 0e393a867..5350af40e 100644 --- a/NebulaNetwork/PacketProcessors/Players/PlayerMechaStatProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Players/PlayerMechaStatProcessor.cs @@ -1,81 +1,84 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Players; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Players +#endregion + +namespace NebulaNetwork.PacketProcessors.Players; + +[RegisterPacketProcessor] +public class PlayerMechaStatProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class PlayerMechaStatProcessor : PacketProcessor + public override void ProcessPacket(PlayerMechaStat packet, NebulaConnection conn) { - public override void ProcessPacket(PlayerMechaStat packet, NebulaConnection conn) + if (IsClient) + { + return; + } + + var player = Multiplayer.Session.Network.PlayerManager.GetPlayer(conn); + if (player != null) { - if (IsClient) + var factory = GameMain.galaxy.PlanetById(player.Data.LocalPlanetId)?.factory; + if (factory == null) { - return; - } + // If client is in space, find the nearest planet factory base on its position + // code modfied from Player.get_nearestFactory - INebulaPlayer player = Multiplayer.Session.Network.PlayerManager.GetPlayer(conn); - if (player != null) - { - PlanetFactory factory = GameMain.galaxy.PlanetById(player.Data.LocalPlanetId)?.factory; - if (factory == null) + var uPosition = player.Data.UPosition.ToVectorLF3(); + if (player.Data.LocalStarId > 0) { - // If client is in space, find the nearest planet factory base on its position - // code modfied from Player.get_nearestFactory - - VectorLF3 uPosition = player.Data.UPosition.ToVectorLF3(); - if (player.Data.LocalStarId > 0) + // find the nearest planet in the star system + var minDistance = double.MaxValue; + var planets = GameMain.galaxy.StarById(player.Data.LocalStarId).planets; + for (var i = 0; i < planets.Length; i++) { - // find the nearest planet in the star system - double minDistance = double.MaxValue; - PlanetData[] planets = GameMain.galaxy.StarById(player.Data.LocalStarId).planets; - for (int i = 0; i < planets.Length; i++) + var planetData = planets[i]; + if (planetData.factory != null) { - PlanetData planetData = planets[i]; - if (planetData.factory != null) + var distance = (planetData.uPosition - uPosition).magnitude; + distance -= planetData.realRadius; + if (distance < minDistance) { - double distance = (planetData.uPosition - uPosition).magnitude; - distance -= planetData.realRadius; - if (distance < minDistance) - { - minDistance = distance; - factory = planetData.factory; - } + minDistance = distance; + factory = planetData.factory; } } } + } - if (factory == null) + if (factory == null) + { + // find the nearest planet from all factories + var minDistance = double.MaxValue; + var factories = GameMain.data.factories; + for (var i = 0; i < factories.Length; i++) { - // find the nearest planet from all factories - double minDistance = double.MaxValue; - PlanetFactory[] factories = GameMain.data.factories; - for (int i = 0; i < factories.Length; i++) + if (factories[i] != null) { - if (factories[i] != null) + var distance = (factories[i].planet.uPosition - uPosition).magnitude; + distance -= factories[i].planet.realRadius; + if (distance < minDistance) { - double distance = (factories[i].planet.uPosition - uPosition).magnitude; - distance -= factories[i].planet.realRadius; - if (distance < minDistance) - { - minDistance = distance; - factory = factories[i]; - } + minDistance = distance; + factory = factories[i]; } } } } + } - if (packet.ItemCount >= 0) - { - GameMain.mainPlayer.mecha.AddProductionStat(packet.ItemId, packet.ItemCount, factory); - } - else - { - GameMain.mainPlayer.mecha.AddConsumptionStat(packet.ItemId, -packet.ItemCount, factory); - } + if (packet.ItemCount >= 0) + { + GameMain.mainPlayer.mecha.AddProductionStat(packet.ItemId, packet.ItemCount, factory); + } + else + { + GameMain.mainPlayer.mecha.AddConsumptionStat(packet.ItemId, -packet.ItemCount, factory); } } } diff --git a/NebulaNetwork/PacketProcessors/Players/PlayerMovementProcessor.cs b/NebulaNetwork/PacketProcessors/Players/PlayerMovementProcessor.cs index ea74ef7d0..12beed83e 100644 --- a/NebulaNetwork/PacketProcessors/Players/PlayerMovementProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Players/PlayerMovementProcessor.cs @@ -1,47 +1,50 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Players; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Players +#endregion + +namespace NebulaNetwork.PacketProcessors.Players; + +[RegisterPacketProcessor] +public class PlayerMovementProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class PlayerMovementProcessor : PacketProcessor - { - private readonly IPlayerManager playerManager; + private readonly IPlayerManager playerManager; - public PlayerMovementProcessor() - { - playerManager = Multiplayer.Session.Network.PlayerManager; - } + public PlayerMovementProcessor() + { + playerManager = Multiplayer.Session.Network.PlayerManager; + } - public override void ProcessPacket(PlayerMovement packet, NebulaConnection conn) + public override void ProcessPacket(PlayerMovement packet, NebulaConnection conn) + { + var valid = true; + if (IsHost) { - bool valid = true; - if (IsHost) + var player = playerManager.GetPlayer(conn); + if (player != null) { - INebulaPlayer player = playerManager.GetPlayer(conn); - if (player != null) - { - player.Data.LocalPlanetId = packet.LocalPlanetId; - player.Data.UPosition = packet.UPosition; - player.Data.Rotation = packet.Rotation; - player.Data.BodyRotation = packet.BodyRotation; - player.Data.LocalPlanetPosition = packet.LocalPlanetPosition; - - playerManager.SendPacketToOtherPlayers(packet, player); - } - else - { - valid = false; - } - } + player.Data.LocalPlanetId = packet.LocalPlanetId; + player.Data.UPosition = packet.UPosition; + player.Data.Rotation = packet.Rotation; + player.Data.BodyRotation = packet.BodyRotation; + player.Data.LocalPlanetPosition = packet.LocalPlanetPosition; - if (valid) + playerManager.SendPacketToOtherPlayers(packet, player); + } + else { - Multiplayer.Session.World.UpdateRemotePlayerRealtimeState(packet); + valid = false; } } + + if (valid) + { + Multiplayer.Session.World.UpdateRemotePlayerRealtimeState(packet); + } } } diff --git a/NebulaNetwork/PacketProcessors/Players/PlayerSandCountProcessor.cs b/NebulaNetwork/PacketProcessors/Players/PlayerSandCountProcessor.cs index 3847ab5a3..d85139fac 100644 --- a/NebulaNetwork/PacketProcessors/Players/PlayerSandCountProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Players/PlayerSandCountProcessor.cs @@ -1,36 +1,39 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Players; -namespace NebulaNetwork.PacketProcessors.Players +#endregion + +namespace NebulaNetwork.PacketProcessors.Players; + +[RegisterPacketProcessor] +public class PlayerSandCountProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class PlayerSandCountProcessor: PacketProcessor + public override void ProcessPacket(PlayerSandCount packet, NebulaConnection conn) { - public override void ProcessPacket(PlayerSandCount packet, NebulaConnection conn) + if (IsHost) { - if (IsHost) - { - // when receive update request, host UpdateSyncedSandCount and send to other players - GameMain.mainPlayer.SetSandCount(packet.SandCount); - return; - } + // when receive update request, host UpdateSyncedSandCount and send to other players + GameMain.mainPlayer.SetSandCount(packet.SandCount); + return; + } - // taken from Player.SetSandCount() - int sandCount = packet.SandCount; - Player player = GameMain.mainPlayer; + // taken from Player.SetSandCount() + var sandCount = packet.SandCount; + var player = GameMain.mainPlayer; - if (sandCount > 1000000000) - { - sandCount = 1000000000; - } - int num = sandCount - player.sandCount; - player.sandCount = sandCount; - if (num != 0) - { - UIRoot.instance.uiGame.OnSandCountChanged(player.sandCount, num); - } + if (sandCount > 1000000000) + { + sandCount = 1000000000; + } + var num = sandCount - player.sandCount; + player.sandCount = sandCount; + if (num != 0) + { + UIRoot.instance.uiGame.OnSandCountChanged(player.sandCount, num); } } } diff --git a/NebulaNetwork/PacketProcessors/Players/PlayerUpdateLocalStarIdProcessor.cs b/NebulaNetwork/PacketProcessors/Players/PlayerUpdateLocalStarIdProcessor.cs index b19ab8db1..6f5a44250 100644 --- a/NebulaNetwork/PacketProcessors/Players/PlayerUpdateLocalStarIdProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Players/PlayerUpdateLocalStarIdProcessor.cs @@ -1,33 +1,36 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Players; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Players +#endregion + +namespace NebulaNetwork.PacketProcessors.Players; + +[RegisterPacketProcessor] +internal class PlayerUpdateLocalStarIdProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class PlayerUpdateLocalStarIdProcessor : PacketProcessor + private readonly IPlayerManager playerManager; + + public PlayerUpdateLocalStarIdProcessor() { - private readonly IPlayerManager playerManager; + playerManager = Multiplayer.Session.Network.PlayerManager; + } - public PlayerUpdateLocalStarIdProcessor() + public override void ProcessPacket(PlayerUpdateLocalStarId packet, NebulaConnection conn) + { + if (IsClient) { - playerManager = Multiplayer.Session.Network.PlayerManager; + return; } - public override void ProcessPacket(PlayerUpdateLocalStarId packet, NebulaConnection conn) + var player = playerManager.GetPlayer(conn); + if (player != null) { - if (IsClient) - { - return; - } - - INebulaPlayer player = playerManager.GetPlayer(conn); - if (player != null) - { - player.Data.LocalStarId = packet.StarId; - } + player.Data.LocalStarId = packet.StarId; } } } diff --git a/NebulaNetwork/PacketProcessors/Players/RemoveDroneOrdersProcessor.cs b/NebulaNetwork/PacketProcessors/Players/RemoveDroneOrdersProcessor.cs index c8cb3cb6b..f40110105 100644 --- a/NebulaNetwork/PacketProcessors/Players/RemoveDroneOrdersProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Players/RemoveDroneOrdersProcessor.cs @@ -1,20 +1,23 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; -namespace NebulaNetwork.PacketProcessors.Players +#endregion + +namespace NebulaNetwork.PacketProcessors.Players; + +[RegisterPacketProcessor] +internal class RemoveDroneOrdersProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class RemoveDroneOrdersProcessor : PacketProcessor + public override void ProcessPacket(RemoveDroneOrdersPacket packet, NebulaConnection conn) { - public override void ProcessPacket(RemoveDroneOrdersPacket packet, NebulaConnection conn) + if (packet.QueuedEntityIds != null) { - if (packet.QueuedEntityIds != null) + for (var i = 0; i < packet.QueuedEntityIds.Length; i++) { - for (int i = 0; i < packet.QueuedEntityIds.Length; i++) - { - GameMain.mainPlayer.mecha.droneLogic.serving.Remove(packet.QueuedEntityIds[i]); - } + GameMain.mainPlayer.mecha.droneLogic.serving.Remove(packet.QueuedEntityIds[i]); } } } diff --git a/NebulaNetwork/PacketProcessors/Routers/PlanetBroadcastProcessor.cs b/NebulaNetwork/PacketProcessors/Routers/PlanetBroadcastProcessor.cs index 65366780c..43209b2b3 100644 --- a/NebulaNetwork/PacketProcessors/Routers/PlanetBroadcastProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Routers/PlanetBroadcastProcessor.cs @@ -1,35 +1,41 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Routers; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Routers +#endregion + +namespace NebulaNetwork.PacketProcessors.Routers; + +[RegisterPacketProcessor] +internal class PlanetBroadcastProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class PlanetBroadcastProcessor : PacketProcessor + private readonly IPlayerManager playerManager; + + public PlanetBroadcastProcessor() { - private readonly IPlayerManager playerManager; - public PlanetBroadcastProcessor() + playerManager = Multiplayer.Session.Network.PlayerManager; + } + + public override void ProcessPacket(PlanetBroadcastPacket packet, NebulaConnection conn) + { + if (IsClient) { - playerManager = Multiplayer.Session.Network.PlayerManager; + return; } - public override void ProcessPacket(PlanetBroadcastPacket packet, NebulaConnection conn) - { - if (IsClient) - { - return; - } - INebulaPlayer player = playerManager.GetPlayer(conn); - if (player != null) - { - //Forward packet to other users - playerManager.SendRawPacketToPlanet(packet.PacketObject, packet.PlanetId, conn); - //Forward packet to the host - ((NetworkProvider)Multiplayer.Session.Network).PacketProcessor.EnqueuePacketForProcessing(packet.PacketObject, conn); - } + var player = playerManager.GetPlayer(conn); + if (player != null) + { + //Forward packet to other users + playerManager.SendRawPacketToPlanet(packet.PacketObject, packet.PlanetId, conn); + //Forward packet to the host + ((NetworkProvider)Multiplayer.Session.Network).PacketProcessor + .EnqueuePacketForProcessing(packet.PacketObject, conn); } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Routers/StarBroadcastProcessor.cs b/NebulaNetwork/PacketProcessors/Routers/StarBroadcastProcessor.cs index f638c4ebc..d7c344d93 100644 --- a/NebulaNetwork/PacketProcessors/Routers/StarBroadcastProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Routers/StarBroadcastProcessor.cs @@ -1,34 +1,40 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Routers; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Routers +#endregion + +namespace NebulaNetwork.PacketProcessors.Routers; + +[RegisterPacketProcessor] +internal class StarBroadcastProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class StarBroadcastProcessor : PacketProcessor + private readonly IPlayerManager playerManager; + + public StarBroadcastProcessor() { - private readonly IPlayerManager playerManager; - public StarBroadcastProcessor() + playerManager = Multiplayer.Session.Network.PlayerManager; + } + + public override void ProcessPacket(StarBroadcastPacket packet, NebulaConnection conn) + { + if (IsClient) { - playerManager = Multiplayer.Session.Network.PlayerManager; + return; } - public override void ProcessPacket(StarBroadcastPacket packet, NebulaConnection conn) - { - if (IsClient) - { - return; - } - INebulaPlayer player = playerManager.GetPlayer(conn); - if (player != null && packet.PacketObject != null) - { - //Forward packet to other users - playerManager.SendRawPacketToStar(packet.PacketObject, packet.StarId, conn); - ((NetworkProvider)Multiplayer.Session.Network).PacketProcessor.EnqueuePacketForProcessing(packet.PacketObject, conn); - } + var player = playerManager.GetPlayer(conn); + if (player != null && packet.PacketObject != null) + { + //Forward packet to other users + playerManager.SendRawPacketToStar(packet.PacketObject, packet.StarId, conn); + ((NetworkProvider)Multiplayer.Session.Network).PacketProcessor + .EnqueuePacketForProcessing(packet.PacketObject, conn); } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Session/GlobalGameDataRequestProcessor.cs b/NebulaNetwork/PacketProcessors/Session/GlobalGameDataRequestProcessor.cs index 3911d7e11..47ece3f5e 100644 --- a/NebulaNetwork/PacketProcessors/Session/GlobalGameDataRequestProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Session/GlobalGameDataRequestProcessor.cs @@ -1,4 +1,6 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.GameHistory; @@ -6,38 +8,39 @@ using NebulaModel.Packets.Statistics; using NebulaModel.Packets.Trash; -namespace NebulaNetwork.PacketProcessors.Session +#endregion + +namespace NebulaNetwork.PacketProcessors.Session; + +[RegisterPacketProcessor] +internal class GlobalGameDataRequestProcessor : PacketProcessor { - [RegisterPacketProcessor] - class GlobalGameDataRequestProcessor : PacketProcessor + public override void ProcessPacket(GlobalGameDataRequest packet, NebulaConnection conn) { - public override void ProcessPacket(GlobalGameDataRequest packet, NebulaConnection conn) + if (IsClient) + { + return; + } + + //Export GameHistoryData, TrashSystem, MilestoneSystem + //PlanetFactory, Dysonsphere, GalacticTransport will be handle else where + + using (var writer = new BinaryUtils.Writer()) + { + GameMain.history.Export(writer.BinaryWriter); + conn.SendPacket(new GameHistoryDataResponse(writer.CloseAndGetBytes(), GameMain.sandboxToolsEnabled)); + } + + using (var writer = new BinaryUtils.Writer()) + { + GameMain.data.trashSystem.Export(writer.BinaryWriter); + conn.SendPacket(new TrashSystemResponseDataPacket(writer.CloseAndGetBytes())); + } + + using (var writer = new BinaryUtils.Writer()) { - if (IsClient) - { - return; - } - - //Export GameHistoryData, TrashSystem, MilestoneSystem - //PlanetFactory, Dysonsphere, GalacticTransport will be handle else where - - using (BinaryUtils.Writer writer = new BinaryUtils.Writer()) - { - GameMain.history.Export(writer.BinaryWriter); - conn.SendPacket(new GameHistoryDataResponse(writer.CloseAndGetBytes(), GameMain.sandboxToolsEnabled)); - } - - using (BinaryUtils.Writer writer = new BinaryUtils.Writer()) - { - GameMain.data.trashSystem.Export(writer.BinaryWriter); - conn.SendPacket(new TrashSystemResponseDataPacket(writer.CloseAndGetBytes())); - } - - using (BinaryUtils.Writer writer = new BinaryUtils.Writer()) - { - GameMain.data.milestoneSystem.Export(writer.BinaryWriter); - conn.SendPacket(new MilestoneDataResponse(writer.CloseAndGetBytes())); - } + GameMain.data.milestoneSystem.Export(writer.BinaryWriter); + conn.SendPacket(new MilestoneDataResponse(writer.CloseAndGetBytes())); } } } diff --git a/NebulaNetwork/PacketProcessors/Session/HandshakeRequestProcessor.cs b/NebulaNetwork/PacketProcessors/Session/HandshakeRequestProcessor.cs index 262d2ce89..ca34545d5 100644 --- a/NebulaNetwork/PacketProcessors/Session/HandshakeRequestProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Session/HandshakeRequestProcessor.cs @@ -1,47 +1,50 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Session; using NebulaWorld; -using System.Collections.Generic; + +#endregion /* * This handler is only here to handle older clients and tell them to upgrade to a newer nebula version. (this packet was replaced by the lobby packets) */ -namespace NebulaNetwork.PacketProcessors.Session +namespace NebulaNetwork.PacketProcessors.Session; + +[RegisterPacketProcessor] +public class HandshakeRequestProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class HandshakeRequestProcessor: PacketProcessor + private readonly IPlayerManager playerManager; + + public HandshakeRequestProcessor() { - private readonly IPlayerManager playerManager; + playerManager = Multiplayer.Session.Network.PlayerManager; + } - public HandshakeRequestProcessor() + public override void ProcessPacket(HandshakeRequest packet, NebulaConnection conn) + { + if (IsClient) { - playerManager = Multiplayer.Session.Network.PlayerManager; + return; } - public override void ProcessPacket(HandshakeRequest packet, NebulaConnection conn) + INebulaPlayer player; + using (playerManager.GetPendingPlayers(out var pendingPlayers)) { - if (IsClient) + if (!pendingPlayers.TryGetValue(conn, out player)) { + conn.Disconnect(DisconnectionReason.InvalidData); + Log.Warn( + "WARNING: Player tried to handshake without being in the pending list. And he uses an outdated nebula version."); return; } - INebulaPlayer player; - using (playerManager.GetPendingPlayers(out Dictionary pendingPlayers)) - { - if (!pendingPlayers.TryGetValue(conn, out player)) - { - conn.Disconnect(DisconnectionReason.InvalidData); - Log.Warn("WARNING: Player tried to handshake without being in the pending list. And he uses an outdated nebula version."); - return; - } - - pendingPlayers.Remove(conn); - } - - conn.Disconnect(DisconnectionReason.ModVersionMismatch, $"Nebula;0.7.7 or earlier;0.7.8 or greater"); + pendingPlayers.Remove(conn); } + + conn.Disconnect(DisconnectionReason.ModVersionMismatch, "Nebula;0.7.7 or earlier;0.7.8 or greater"); } } diff --git a/NebulaNetwork/PacketProcessors/Session/HandshakeResponseProcessor.cs b/NebulaNetwork/PacketProcessors/Session/HandshakeResponseProcessor.cs index cf54afe14..f8851afde 100644 --- a/NebulaNetwork/PacketProcessors/Session/HandshakeResponseProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Session/HandshakeResponseProcessor.cs @@ -1,4 +1,5 @@ -using BepInEx; +#region + using BepInEx.Bootstrap; using NebulaAPI; using NebulaModel; @@ -8,46 +9,47 @@ using NebulaWorld; using NebulaWorld.SocialIntegration; -namespace NebulaNetwork.PacketProcessors.Session +#endregion + +namespace NebulaNetwork.PacketProcessors.Session; + +[RegisterPacketProcessor] +public class HandshakeResponseProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class HandshakeResponseProcessor : PacketProcessor + public override void ProcessPacket(HandshakeResponse packet, NebulaConnection conn) { - public override void ProcessPacket(HandshakeResponse packet, NebulaConnection conn) + using (var p = new BinaryUtils.Reader(packet.ModsSettings)) { - using (BinaryUtils.Reader p = new BinaryUtils.Reader(packet.ModsSettings)) + for (var i = 0; i < packet.ModsSettingsCount; i++) { - for (int i = 0; i < packet.ModsSettingsCount; i++) + var guid = p.BinaryReader.ReadString(); + var info = Chainloader.PluginInfos[guid]; + if (info.Instance is IMultiplayerModWithSettings mod) { - string guid = p.BinaryReader.ReadString(); - PluginInfo info = Chainloader.PluginInfos[guid]; - if (info.Instance is IMultiplayerModWithSettings mod) - { - mod.Import(p.BinaryReader); - } + mod.Import(p.BinaryReader); } } + } - // overwrite local setting with host setting, but dont save it as its a temp setting for this session - Config.Options.SyncSoil = packet.SyncSoil; + // overwrite local setting with host setting, but dont save it as its a temp setting for this session + Config.Options.SyncSoil = packet.SyncSoil; - ((LocalPlayer)Multiplayer.Session.LocalPlayer).IsHost = false; - ((LocalPlayer)Multiplayer.Session.LocalPlayer).SetPlayerData(packet.LocalPlayerData, packet.IsNewPlayer); + ((LocalPlayer)Multiplayer.Session.LocalPlayer).IsHost = false; + ((LocalPlayer)Multiplayer.Session.LocalPlayer).SetPlayerData(packet.LocalPlayerData, packet.IsNewPlayer); - Multiplayer.Session.IsInLobby = false; - Multiplayer.ShouldReturnToJoinMenu = false; + Multiplayer.Session.IsInLobby = false; + Multiplayer.ShouldReturnToJoinMenu = false; - // Using GameDesc.Import will break GS2, so use GameDesc.SetForNewGame instead - GameDesc gameDesc = new GameDesc(); - gameDesc.SetForNewGame(packet.GalaxyAlgo, packet.GalaxySeed, packet.StarCount, 1, packet.ResourceMultiplier); - gameDesc.savedThemeIds = packet.SavedThemeIds; - gameDesc.isSandboxMode = packet.IsSandboxMode; - DSPGame.StartGameSkipPrologue(gameDesc); + // Using GameDesc.Import will break GS2, so use GameDesc.SetForNewGame instead + var gameDesc = new GameDesc(); + gameDesc.SetForNewGame(packet.GalaxyAlgo, packet.GalaxySeed, packet.StarCount, 1, packet.ResourceMultiplier); + gameDesc.savedThemeIds = packet.SavedThemeIds; + gameDesc.isSandboxMode = packet.IsSandboxMode; + DSPGame.StartGameSkipPrologue(gameDesc); - InGamePopup.ShowInfo("Loading".Translate(), "Loading state from server, please wait".Translate(), null); + InGamePopup.ShowInfo("Loading".Translate(), "Loading state from server, please wait".Translate(), null); - Multiplayer.Session.NumPlayers = packet.NumPlayers; - DiscordManager.UpdateRichPresence(partyId: packet.DiscordPartyId); - } + Multiplayer.Session.NumPlayers = packet.NumPlayers; + DiscordManager.UpdateRichPresence(partyId: packet.DiscordPartyId); } } diff --git a/NebulaNetwork/PacketProcessors/Session/LobbyRequestProcessor.cs b/NebulaNetwork/PacketProcessors/Session/LobbyRequestProcessor.cs index 1732fc46e..fe292409c 100644 --- a/NebulaNetwork/PacketProcessors/Session/LobbyRequestProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Session/LobbyRequestProcessor.cs @@ -1,4 +1,8 @@ -using NebulaAPI; +#region + +using System.Collections.Generic; +using BepInEx.Bootstrap; +using NebulaAPI; using NebulaModel; using NebulaModel.DataStructures; using NebulaModel.Logger; @@ -10,240 +14,241 @@ using NebulaModel.Utils; using NebulaWorld; using NebulaWorld.SocialIntegration; -using System.Collections.Generic; -namespace NebulaNetwork.PacketProcessors.Session +#endregion + +namespace NebulaNetwork.PacketProcessors.Session; + +[RegisterPacketProcessor] +public class LobbyRequestProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class LobbyRequestProcessor: PacketProcessor + private readonly IPlayerManager playerManager; + + public LobbyRequestProcessor() { - private readonly IPlayerManager playerManager; - public LobbyRequestProcessor() + playerManager = Multiplayer.Session.Network.PlayerManager; + } + + public override void ProcessPacket(LobbyRequest packet, NebulaConnection conn) + { + if (IsClient) { - playerManager = Multiplayer.Session.Network.PlayerManager; + return; } - public override void ProcessPacket(LobbyRequest packet, NebulaConnection conn) + INebulaPlayer player; + using (playerManager.GetPendingPlayers(out var pendingPlayers)) { - if (IsClient) + if (!pendingPlayers.TryGetValue(conn, out player)) { + conn.Disconnect(DisconnectionReason.InvalidData); + Log.Warn("WARNING: Player tried to enter lobby without being in the pending list"); return; } - INebulaPlayer player; - using (playerManager.GetPendingPlayers(out Dictionary pendingPlayers)) + if (GameMain.isFullscreenPaused) { - if (!pendingPlayers.TryGetValue(conn, out player)) - { - conn.Disconnect(DisconnectionReason.InvalidData); - Log.Warn("WARNING: Player tried to enter lobby without being in the pending list"); - return; - } - - if (GameMain.isFullscreenPaused) - { - Log.Warn("Reject connection because server is still loading"); - conn.Disconnect(DisconnectionReason.HostStillLoading); - pendingPlayers.Remove(conn); - return; - } + Log.Warn("Reject connection because server is still loading"); + conn.Disconnect(DisconnectionReason.HostStillLoading); + pendingPlayers.Remove(conn); + return; + } - if (!ModsVersionCheck(packet, out DisconnectionReason disconnectionReason, out string reasonString)) - { - Log.Warn("Reject connection because mods mismatch"); - conn.Disconnect(disconnectionReason, reasonString); - pendingPlayers.Remove(conn); - return; - } + if (!ModsVersionCheck(packet, out var disconnectionReason, out var reasonString)) + { + Log.Warn("Reject connection because mods mismatch"); + conn.Disconnect(disconnectionReason, reasonString); + pendingPlayers.Remove(conn); + return; } + } - bool isNewUser = false; + var isNewUser = false; - //TODO: some validation of client cert / generating auth challenge for the client - // Load old data of the client - string clientCertHash = CryptoUtils.Hash(packet.ClientCert); - using (playerManager.GetSavedPlayerData(out Dictionary savedPlayerData)) + //TODO: some validation of client cert / generating auth challenge for the client + // Load old data of the client + var clientCertHash = CryptoUtils.Hash(packet.ClientCert); + using (playerManager.GetSavedPlayerData(out var savedPlayerData)) + { + if (savedPlayerData.TryGetValue(clientCertHash, out var value)) { - if (savedPlayerData.TryGetValue(clientCertHash, out IPlayerData value)) + var playerData = value; + using (playerManager.GetConnectedPlayers(out var connectedPlayers)) { - IPlayerData playerData = value; - using (playerManager.GetConnectedPlayers(out Dictionary connectedPlayers)) + foreach (var connectedPlayer in connectedPlayers.Values) { - foreach (INebulaPlayer connectedPlayer in connectedPlayers.Values) + if (connectedPlayer.Data == playerData) { - if (connectedPlayer.Data == playerData) - { - playerData = value.CreateCopyWithoutMechaData(); - Log.Warn($"Copy playerData for duplicated player{playerData.PlayerId} {playerData.Username}"); - } + playerData = value.CreateCopyWithoutMechaData(); + Log.Warn($"Copy playerData for duplicated player{playerData.PlayerId} {playerData.Username}"); } } - player.LoadUserData(playerData); - } - else - { - // store player data once he fully loaded into the game (SyncCompleteProcessor) - isNewUser = true; } + player.LoadUserData(playerData); + } + else + { + // store player data once he fully loaded into the game (SyncCompleteProcessor) + isNewUser = true; } + } - // Add the username to the player data - player.Data.Username = !string.IsNullOrWhiteSpace(packet.Username) ? packet.Username : $"Player {player.Id}"; + // Add the username to the player data + player.Data.Username = !string.IsNullOrWhiteSpace(packet.Username) ? packet.Username : $"Player {player.Id}"; - Multiplayer.Session.NumPlayers += 1; - DiscordManager.UpdateRichPresence(); + Multiplayer.Session.NumPlayers += 1; + DiscordManager.UpdateRichPresence(); - // if user is known and host is ingame dont put him into lobby but let him join the game - if (!isNewUser && Multiplayer.Session.IsGameLoaded) + // if user is known and host is ingame dont put him into lobby but let him join the game + if (!isNewUser && Multiplayer.Session.IsGameLoaded) + { + // Remove the new player from pending list + using (playerManager.GetPendingPlayers(out var pendingPlayers)) { - // Remove the new player from pending list - using (playerManager.GetPendingPlayers(out Dictionary pendingPlayers)) - { - pendingPlayers.Remove(conn); - } + pendingPlayers.Remove(conn); + } + + // Add the new player to the list + using (playerManager.GetSyncingPlayers(out var syncingPlayers)) + { + syncingPlayers.Add(conn, player); + } + + Multiplayer.Session.World.OnPlayerJoining(player.Data.Username); - // Add the new player to the list - using (playerManager.GetSyncingPlayers(out Dictionary syncingPlayers)) + // Make sure that each player that is currently in the game receives that a new player as join so they can create its RemotePlayerCharacter + var pdata = new PlayerJoining((PlayerData)player.Data.CreateCopyWithoutMechaData(), + Multiplayer.Session.NumPlayers); // Remove inventory from mecha data + using (playerManager.GetConnectedPlayers(out var connectedPlayers)) + { + foreach (var kvp in connectedPlayers) { - syncingPlayers.Add(conn, player); + kvp.Value.SendPacket(pdata); } + } - Multiplayer.Session.World.OnPlayerJoining(player.Data.Username); + //Add current tech bonuses to the connecting player based on the Host's mecha + ((MechaData)player.Data.Mecha).TechBonuses = new PlayerTechBonuses(GameMain.mainPlayer.mecha); - // Make sure that each player that is currently in the game receives that a new player as join so they can create its RemotePlayerCharacter - PlayerJoining pdata = new PlayerJoining((PlayerData)player.Data.CreateCopyWithoutMechaData(), Multiplayer.Session.NumPlayers); // Remove inventory from mecha data - using (playerManager.GetConnectedPlayers(out Dictionary connectedPlayers)) + using (var p = new BinaryUtils.Writer()) + { + var count = 0; + foreach (var pluginInfo in Chainloader.PluginInfos) { - foreach (KeyValuePair kvp in connectedPlayers) + if (pluginInfo.Value.Instance is IMultiplayerModWithSettings mod) { - kvp.Value.SendPacket(pdata); + p.BinaryWriter.Write(pluginInfo.Key); + mod.Export(p.BinaryWriter); + count++; } } - //Add current tech bonuses to the connecting player based on the Host's mecha - ((MechaData)player.Data.Mecha).TechBonuses = new PlayerTechBonuses(GameMain.mainPlayer.mecha); + var gameDesc = GameMain.data.gameDesc; + player.SendPacket(new HandshakeResponse(in gameDesc, isNewUser, (PlayerData)player.Data, p.CloseAndGetBytes(), + count, Config.Options.SyncSoil, Multiplayer.Session.NumPlayers, DiscordManager.GetPartyId())); + } + } + else + { + var gameDesc = Multiplayer.Session.IsGameLoaded ? GameMain.data.gameDesc : UIRoot.instance.galaxySelect.gameDesc; - using (BinaryUtils.Writer p = new BinaryUtils.Writer()) + using (var p = new BinaryUtils.Writer()) + { + var count = 0; + foreach (var pluginInfo in Chainloader.PluginInfos) { - int count = 0; - foreach (KeyValuePair pluginInfo in BepInEx.Bootstrap.Chainloader.PluginInfos) + if (pluginInfo.Value.Instance is IMultiplayerModWithSettings mod) { - if (pluginInfo.Value.Instance is IMultiplayerModWithSettings mod) - { - p.BinaryWriter.Write(pluginInfo.Key); - mod.Export(p.BinaryWriter); - count++; - } + p.BinaryWriter.Write(pluginInfo.Key); + mod.Export(p.BinaryWriter); + count++; } - - GameDesc gameDesc = GameMain.data.gameDesc; - player.SendPacket(new HandshakeResponse(in gameDesc, isNewUser, (PlayerData)player.Data, p.CloseAndGetBytes(), count, Config.Options.SyncSoil, Multiplayer.Session.NumPlayers, DiscordManager.GetPartyId())); } + + player.SendPacket(new LobbyResponse(in gameDesc, p.CloseAndGetBytes(), count, Multiplayer.Session.NumPlayers, + DiscordManager.GetPartyId())); } - else + + // Send overriden Planet and Star names + player.SendPacket(new NameInputPacket(GameMain.galaxy, Multiplayer.Session.LocalPlayer.Id)); + } + } + + + private bool ModsVersionCheck(in LobbyRequest packet, out DisconnectionReason reason, out string reasonString) + { + reason = DisconnectionReason.Normal; + reasonString = null; + var clientMods = new Dictionary(); + + using (var reader = new BinaryUtils.Reader(packet.ModsVersion)) + { + for (var i = 0; i < packet.ModsCount; i++) { - GameDesc gameDesc = Multiplayer.Session.IsGameLoaded ? GameMain.data.gameDesc : UIRoot.instance.galaxySelect.gameDesc; + var guid = reader.BinaryReader.ReadString(); + var version = reader.BinaryReader.ReadString(); - using (BinaryUtils.Writer p = new BinaryUtils.Writer()) + if (!Chainloader.PluginInfos.ContainsKey(guid)) { - int count = 0; - foreach (KeyValuePair pluginInfo in BepInEx.Bootstrap.Chainloader.PluginInfos) - { - if (pluginInfo.Value.Instance is IMultiplayerModWithSettings mod) - { - p.BinaryWriter.Write(pluginInfo.Key); - mod.Export(p.BinaryWriter); - count++; - } - } - - player.SendPacket(new LobbyResponse(in gameDesc, p.CloseAndGetBytes(), count, Multiplayer.Session.NumPlayers, DiscordManager.GetPartyId())); + reason = DisconnectionReason.ModIsMissingOnServer; + reasonString = guid; + return false; } - // Send overriden Planet and Star names - player.SendPacket(new NameInputPacket(GameMain.galaxy, Multiplayer.Session.LocalPlayer.Id)); + clientMods.Add(guid, version); } } - - - private bool ModsVersionCheck(in LobbyRequest packet, out DisconnectionReason reason, out string reasonString) - { - reason = DisconnectionReason.Normal; - reasonString = null; - Dictionary clientMods = new Dictionary(); - using (BinaryUtils.Reader reader = new BinaryUtils.Reader(packet.ModsVersion)) + foreach (var pluginInfo in Chainloader.PluginInfos) + { + if (pluginInfo.Value.Instance is IMultiplayerMod mod) { - for (int i = 0; i < packet.ModsCount; i++) + if (!clientMods.ContainsKey(pluginInfo.Key)) { - string guid = reader.BinaryReader.ReadString(); - string version = reader.BinaryReader.ReadString(); + reason = DisconnectionReason.ModIsMissing; + reasonString = pluginInfo.Key; + return false; + } - if (!BepInEx.Bootstrap.Chainloader.PluginInfos.ContainsKey(guid)) - { - reason = DisconnectionReason.ModIsMissingOnServer; - reasonString = guid; - return false; - } + var version = clientMods[pluginInfo.Key]; - clientMods.Add(guid, version); + if (mod.CheckVersion(mod.Version, version)) + { + continue; } - } - foreach (KeyValuePair pluginInfo in BepInEx.Bootstrap.Chainloader.PluginInfos) + reason = DisconnectionReason.ModVersionMismatch; + reasonString = $"{pluginInfo.Key};{version};{mod.Version}"; + return false; + } + foreach (var dependency in pluginInfo.Value.Dependencies) { - if (pluginInfo.Value.Instance is IMultiplayerMod mod) + if (dependency.DependencyGUID == NebulaModAPI.API_GUID) { + var hostVersion = pluginInfo.Value.Metadata.Version.ToString(); if (!clientMods.ContainsKey(pluginInfo.Key)) { reason = DisconnectionReason.ModIsMissing; reasonString = pluginInfo.Key; return false; } - - string version = clientMods[pluginInfo.Key]; - - if (mod.CheckVersion(mod.Version, version)) - { - continue; - } - - reason = DisconnectionReason.ModVersionMismatch; - reasonString = $"{pluginInfo.Key};{version};{mod.Version}"; - return false; - } - else - { - foreach (BepInEx.BepInDependency dependency in pluginInfo.Value.Dependencies) + if (clientMods[pluginInfo.Key] != hostVersion) { - if (dependency.DependencyGUID == NebulaModAPI.API_GUID) - { - string hostVersion = pluginInfo.Value.Metadata.Version.ToString(); - if (!clientMods.ContainsKey(pluginInfo.Key)) - { - reason = DisconnectionReason.ModIsMissing; - reasonString = pluginInfo.Key; - return false; - } - if (clientMods[pluginInfo.Key] != hostVersion) - { - reason = DisconnectionReason.ModVersionMismatch; - reasonString = $"{pluginInfo.Key};{clientMods[pluginInfo.Key]};{hostVersion}"; - return false; - } - } + reason = DisconnectionReason.ModVersionMismatch; + reasonString = $"{pluginInfo.Key};{clientMods[pluginInfo.Key]};{hostVersion}"; + return false; } } } + } - if (packet.GameVersionSig != GameConfig.gameVersion.sig) - { - reason = DisconnectionReason.GameVersionMismatch; - reasonString = $"{ packet.GameVersionSig };{ GameConfig.gameVersion.sig }"; - return false; - } + if (packet.GameVersionSig != GameConfig.gameVersion.sig) + { + reason = DisconnectionReason.GameVersionMismatch; + reasonString = $"{packet.GameVersionSig};{GameConfig.gameVersion.sig}"; + return false; + } - return true; - } + return true; } } diff --git a/NebulaNetwork/PacketProcessors/Session/LobbyResponseProcessor.cs b/NebulaNetwork/PacketProcessors/Session/LobbyResponseProcessor.cs index 39f32a07c..c5502d4cd 100644 --- a/NebulaNetwork/PacketProcessors/Session/LobbyResponseProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Session/LobbyResponseProcessor.cs @@ -1,4 +1,5 @@ -using BepInEx; +#region + using BepInEx.Bootstrap; using NebulaAPI; using NebulaModel.Networking; @@ -7,41 +8,42 @@ using NebulaWorld; using NebulaWorld.SocialIntegration; -namespace NebulaNetwork.PacketProcessors.Session +#endregion + +namespace NebulaNetwork.PacketProcessors.Session; + +[RegisterPacketProcessor] +internal class LobbyResponseProcessor : PacketProcessor { - [RegisterPacketProcessor] - class LobbyResponseProcessor: PacketProcessor + public override void ProcessPacket(LobbyResponse packet, NebulaConnection conn) { - public override void ProcessPacket(LobbyResponse packet, NebulaConnection conn) + using (var p = new BinaryUtils.Reader(packet.ModsSettings)) { - using (BinaryUtils.Reader p = new BinaryUtils.Reader(packet.ModsSettings)) + for (var i = 0; i < packet.ModsSettingsCount; i++) { - for (int i = 0; i < packet.ModsSettingsCount; i++) + var guid = p.BinaryReader.ReadString(); + var info = Chainloader.PluginInfos[guid]; + if (info.Instance is IMultiplayerModWithSettings mod) { - string guid = p.BinaryReader.ReadString(); - PluginInfo info = Chainloader.PluginInfos[guid]; - if (info.Instance is IMultiplayerModWithSettings mod) - { - mod.Import(p.BinaryReader); - } + mod.Import(p.BinaryReader); } } - ((LocalPlayer)Multiplayer.Session.LocalPlayer).IsHost = false; - Multiplayer.Session.NumPlayers = packet.NumPlayers; - Multiplayer.Session.IsInLobby = true; - DiscordManager.UpdateRichPresence(partyId: packet.DiscordPartyId); + } + ((LocalPlayer)Multiplayer.Session.LocalPlayer).IsHost = false; + Multiplayer.Session.NumPlayers = packet.NumPlayers; + Multiplayer.Session.IsInLobby = true; + DiscordManager.UpdateRichPresence(partyId: packet.DiscordPartyId); - UIRoot.instance.galaxySelect._Open(); - UIRoot.instance.uiMainMenu._Close(); + UIRoot.instance.galaxySelect._Open(); + UIRoot.instance.uiMainMenu._Close(); - GameDesc gameDesc = new GameDesc(); - gameDesc.SetForNewGame(packet.GalaxyAlgo, packet.GalaxySeed, packet.StarCount, 1, packet.ResourceMultiplier); - gameDesc.savedThemeIds = packet.SavedThemeIds; - gameDesc.isSandboxMode = packet.IsSandboxMode; + var gameDesc = new GameDesc(); + gameDesc.SetForNewGame(packet.GalaxyAlgo, packet.GalaxySeed, packet.StarCount, 1, packet.ResourceMultiplier); + gameDesc.savedThemeIds = packet.SavedThemeIds; + gameDesc.isSandboxMode = packet.IsSandboxMode; - UIRoot.instance.galaxySelect.gameDesc = gameDesc; - UIRoot.instance.galaxySelect.SetStarmapGalaxy(); - UIRoot.instance.galaxySelect.sandboxToggle.isOn = packet.IsSandboxMode; - } + UIRoot.instance.galaxySelect.gameDesc = gameDesc; + UIRoot.instance.galaxySelect.SetStarmapGalaxy(); + UIRoot.instance.galaxySelect.sandboxToggle.isOn = packet.IsSandboxMode; } } diff --git a/NebulaNetwork/PacketProcessors/Session/LobbyUpdateValuesProcessor.cs b/NebulaNetwork/PacketProcessors/Session/LobbyUpdateValuesProcessor.cs index 1d6809724..e7284ff6e 100644 --- a/NebulaNetwork/PacketProcessors/Session/LobbyUpdateValuesProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Session/LobbyUpdateValuesProcessor.cs @@ -1,27 +1,30 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Session; -namespace NebulaNetwork.PacketProcessors.Session +#endregion + +namespace NebulaNetwork.PacketProcessors.Session; + +[RegisterPacketProcessor] +internal class LobbyUpdateValuesProcessor : PacketProcessor { - [RegisterPacketProcessor] - class LobbyUpdateValuesProcessor:PacketProcessor + public override void ProcessPacket(LobbyUpdateValues packet, NebulaConnection conn) { - public override void ProcessPacket(LobbyUpdateValues packet, NebulaConnection conn) + if (IsHost) { - if (IsHost) - { - return; - } + return; + } - GameDesc gameDesc = new GameDesc(); - gameDesc.SetForNewGame(packet.GalaxyAlgo, packet.GalaxySeed, packet.StarCount, 1, packet.ResourceMultiplier); - gameDesc.isSandboxMode = packet.IsSandboxMode; + var gameDesc = new GameDesc(); + gameDesc.SetForNewGame(packet.GalaxyAlgo, packet.GalaxySeed, packet.StarCount, 1, packet.ResourceMultiplier); + gameDesc.isSandboxMode = packet.IsSandboxMode; - UIRoot.instance.galaxySelect.gameDesc = gameDesc; - UIRoot.instance.galaxySelect.SetStarmapGalaxy(); - UIRoot.instance.galaxySelect.sandboxToggle.isOn = packet.IsSandboxMode; - } + UIRoot.instance.galaxySelect.gameDesc = gameDesc; + UIRoot.instance.galaxySelect.SetStarmapGalaxy(); + UIRoot.instance.galaxySelect.sandboxToggle.isOn = packet.IsSandboxMode; } } diff --git a/NebulaNetwork/PacketProcessors/Session/PlayerDisconnectedProcessor.cs b/NebulaNetwork/PacketProcessors/Session/PlayerDisconnectedProcessor.cs index 901f96d71..05622ebc9 100644 --- a/NebulaNetwork/PacketProcessors/Session/PlayerDisconnectedProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Session/PlayerDisconnectedProcessor.cs @@ -1,20 +1,23 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Session; using NebulaWorld; using NebulaWorld.SocialIntegration; -namespace NebulaNetwork.PacketProcessors.Session +#endregion + +namespace NebulaNetwork.PacketProcessors.Session; + +[RegisterPacketProcessor] +public class PlayerDisconnectedProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class PlayerDisconnectedProcessor : PacketProcessor + public override void ProcessPacket(PlayerDisconnected packet, NebulaConnection conn) { - public override void ProcessPacket(PlayerDisconnected packet, NebulaConnection conn) - { - Multiplayer.Session.NumPlayers = packet.NumPlayers; - DiscordManager.UpdateRichPresence(); - Multiplayer.Session.World.DestroyRemotePlayerModel(packet.PlayerId); - } + Multiplayer.Session.NumPlayers = packet.NumPlayers; + DiscordManager.UpdateRichPresence(); + Multiplayer.Session.World.DestroyRemotePlayerModel(packet.PlayerId); } } diff --git a/NebulaNetwork/PacketProcessors/Session/PlayerJoiningProcessor.cs b/NebulaNetwork/PacketProcessors/Session/PlayerJoiningProcessor.cs index bba86dee5..0786e60e0 100644 --- a/NebulaNetwork/PacketProcessors/Session/PlayerJoiningProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Session/PlayerJoiningProcessor.cs @@ -1,21 +1,24 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Session; using NebulaWorld; using NebulaWorld.SocialIntegration; -namespace NebulaNetwork.PacketProcessors.Session +#endregion + +namespace NebulaNetwork.PacketProcessors.Session; + +[RegisterPacketProcessor] +public class PlayerJoiningProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class PlayerJoiningProcessor : PacketProcessor + public override void ProcessPacket(PlayerJoining packet, NebulaConnection conn) { - public override void ProcessPacket(PlayerJoining packet, NebulaConnection conn) - { - Multiplayer.Session.NumPlayers = packet.NumPlayers; - DiscordManager.UpdateRichPresence(); - Multiplayer.Session.World.SpawnRemotePlayerModel(packet.PlayerData); - Multiplayer.Session.World.OnPlayerJoining(packet.PlayerData.Username); - } + Multiplayer.Session.NumPlayers = packet.NumPlayers; + DiscordManager.UpdateRichPresence(); + Multiplayer.Session.World.SpawnRemotePlayerModel(packet.PlayerData); + Multiplayer.Session.World.OnPlayerJoining(packet.PlayerData.Username); } } diff --git a/NebulaNetwork/PacketProcessors/Session/StartGameMessageProcessor.cs b/NebulaNetwork/PacketProcessors/Session/StartGameMessageProcessor.cs index 68c59775f..145208d92 100644 --- a/NebulaNetwork/PacketProcessors/Session/StartGameMessageProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Session/StartGameMessageProcessor.cs @@ -1,4 +1,6 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel; using NebulaModel.DataStructures; using NebulaModel.Logger; @@ -7,86 +9,89 @@ using NebulaModel.Packets.Players; using NebulaModel.Packets.Session; using NebulaWorld; -using System.Collections.Generic; -namespace NebulaNetwork.PacketProcessors.Session +#endregion + +namespace NebulaNetwork.PacketProcessors.Session; + +[RegisterPacketProcessor] +internal class StartGameMessageProcessor : PacketProcessor { - [RegisterPacketProcessor] - class StartGameMessageProcessor: PacketProcessor + private readonly IPlayerManager playerManager; + + public StartGameMessageProcessor() { - private readonly IPlayerManager playerManager; - public StartGameMessageProcessor() - { - playerManager = Multiplayer.Session.Network.PlayerManager; - } + playerManager = Multiplayer.Session.Network.PlayerManager; + } - public override void ProcessPacket(StartGameMessage packet, NebulaConnection conn) + public override void ProcessPacket(StartGameMessage packet, NebulaConnection conn) + { + if (IsHost) { - if (IsHost) + if (Multiplayer.Session.IsGameLoaded && !GameMain.isFullscreenPaused) { - if (Multiplayer.Session.IsGameLoaded && !GameMain.isFullscreenPaused) + INebulaPlayer player; + using (playerManager.GetPendingPlayers(out var pendingPlayers)) { - INebulaPlayer player; - using (playerManager.GetPendingPlayers(out Dictionary pendingPlayers)) + if (!pendingPlayers.TryGetValue(conn, out player)) { - if (!pendingPlayers.TryGetValue(conn, out player)) - { - conn.Disconnect(DisconnectionReason.InvalidData); - Log.Warn("WARNING: Player tried to enter the game without being in the pending list"); - return; - } - - pendingPlayers.Remove(conn); + conn.Disconnect(DisconnectionReason.InvalidData); + Log.Warn("WARNING: Player tried to enter the game without being in the pending list"); + return; } - // Add the new player to the list - using (playerManager.GetSyncingPlayers(out Dictionary syncingPlayers)) - { - syncingPlayers.Add(conn, player); - } + pendingPlayers.Remove(conn); + } - Multiplayer.Session.World.OnPlayerJoining(player.Data.Username); + // Add the new player to the list + using (playerManager.GetSyncingPlayers(out var syncingPlayers)) + { + syncingPlayers.Add(conn, player); + } + + Multiplayer.Session.World.OnPlayerJoining(player.Data.Username); - // Make sure that each player that is currently in the game receives that a new player as join so they can create its RemotePlayerCharacter - PlayerJoining pdata = new PlayerJoining((PlayerData)player.Data.CreateCopyWithoutMechaData(), Multiplayer.Session.NumPlayers); // Remove inventory from mecha data - using (playerManager.GetConnectedPlayers(out Dictionary connectedPlayers)) + // Make sure that each player that is currently in the game receives that a new player as join so they can create its RemotePlayerCharacter + var pdata = new PlayerJoining((PlayerData)player.Data.CreateCopyWithoutMechaData(), + Multiplayer.Session.NumPlayers); // Remove inventory from mecha data + using (playerManager.GetConnectedPlayers(out var connectedPlayers)) + { + foreach (var kvp in connectedPlayers) { - foreach (KeyValuePair kvp in connectedPlayers) - { - kvp.Value.SendPacket(pdata); - } + kvp.Value.SendPacket(pdata); } + } - //Add current tech bonuses to the connecting player based on the Host's mecha - ((MechaData)player.Data.Mecha).TechBonuses = new PlayerTechBonuses(GameMain.mainPlayer.mecha); + //Add current tech bonuses to the connecting player based on the Host's mecha + ((MechaData)player.Data.Mecha).TechBonuses = new PlayerTechBonuses(GameMain.mainPlayer.mecha); - conn.SendPacket(new StartGameMessage(true, (PlayerData)player.Data, Config.Options.SyncSoil)); - } - else - { - conn.SendPacket(new StartGameMessage(false, null, false)); - } + conn.SendPacket(new StartGameMessage(true, (PlayerData)player.Data, Config.Options.SyncSoil)); } - else if(packet.IsAllowedToStart) + else { - // overwrite local setting with host setting, but dont save it as its a temp setting for this session - Config.Options.SyncSoil = packet.SyncSoil; + conn.SendPacket(new StartGameMessage(false, null, false)); + } + } + else if (packet.IsAllowedToStart) + { + // overwrite local setting with host setting, but dont save it as its a temp setting for this session + Config.Options.SyncSoil = packet.SyncSoil; - ((LocalPlayer)Multiplayer.Session.LocalPlayer).IsHost = false; - ((LocalPlayer)Multiplayer.Session.LocalPlayer).SetPlayerData(packet.LocalPlayerData, true); + ((LocalPlayer)Multiplayer.Session.LocalPlayer).IsHost = false; + ((LocalPlayer)Multiplayer.Session.LocalPlayer).SetPlayerData(packet.LocalPlayerData, true); - UIRoot.instance.uiGame.planetDetail.gameObject.SetActive(false); - Multiplayer.Session.IsInLobby = false; - Multiplayer.ShouldReturnToJoinMenu = false; + UIRoot.instance.uiGame.planetDetail.gameObject.SetActive(false); + Multiplayer.Session.IsInLobby = false; + Multiplayer.ShouldReturnToJoinMenu = false; - DSPGame.StartGameSkipPrologue(UIRoot.instance.galaxySelect.gameDesc); + DSPGame.StartGameSkipPrologue(UIRoot.instance.galaxySelect.gameDesc); - InGamePopup.ShowInfo("Loading".Translate(), "Loading state from server, please wait".Translate(), null); - } - else - { - InGamePopup.ShowInfo("Unavailable".Translate(), "The host is not ready to let you in, please wait!".Translate(), "OK".Translate()); - } + InGamePopup.ShowInfo("Loading".Translate(), "Loading state from server, please wait".Translate(), null); + } + else + { + InGamePopup.ShowInfo("Unavailable".Translate(), "The host is not ready to let you in, please wait!".Translate(), + "OK".Translate()); } } } diff --git a/NebulaNetwork/PacketProcessors/Session/SyncCompleteProcessor.cs b/NebulaNetwork/PacketProcessors/Session/SyncCompleteProcessor.cs index 0fa99bafc..fda4d64d9 100644 --- a/NebulaNetwork/PacketProcessors/Session/SyncCompleteProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Session/SyncCompleteProcessor.cs @@ -1,4 +1,7 @@ -using NebulaAPI; +#region + +using System.Collections.Generic; +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; @@ -6,130 +9,132 @@ using NebulaModel.Packets.Session; using NebulaModel.Utils; using NebulaWorld; -using System.Collections.Generic; -namespace NebulaNetwork.PacketProcessors.Session +#endregion + +namespace NebulaNetwork.PacketProcessors.Session; + +[RegisterPacketProcessor] +public class SyncCompleteProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class SyncCompleteProcessor : PacketProcessor + private readonly IPlayerManager playerManager; + + public SyncCompleteProcessor() { - private readonly IPlayerManager playerManager; + playerManager = Multiplayer.Session.Network.PlayerManager; + } - public SyncCompleteProcessor() + public override void ProcessPacket(SyncComplete packet, NebulaConnection conn) + { + if (IsHost) { - playerManager = Multiplayer.Session.Network.PlayerManager; - } + var player = playerManager.GetSyncingPlayer(conn); + if (player == null) + { + Log.Warn("Received a SyncComplete packet, but no player is joining."); + Multiplayer.Session.World.OnAllPlayersSyncCompleted(); + return; + } - public override void ProcessPacket(SyncComplete packet, NebulaConnection conn) - { - if (IsHost) + // store the player now, not when he enters the lobby. that would cause weird teleportations when clients reenter the lobby without ever having loaded into the game + var clientCertHash = CryptoUtils.Hash(packet.ClientCert); + using (playerManager.GetSavedPlayerData(out var savedPlayerData)) { - INebulaPlayer player = playerManager.GetSyncingPlayer(conn); - if (player == null) + if (!savedPlayerData.TryGetValue(clientCertHash, out var value)) { - Log.Warn("Received a SyncComplete packet, but no player is joining."); - Multiplayer.Session.World.OnAllPlayersSyncCompleted(); - return; + savedPlayerData.Add(clientCertHash, player.Data); } + } - // store the player now, not when he enters the lobby. that would cause weird teleportations when clients reenter the lobby without ever having loaded into the game - string clientCertHash = CryptoUtils.Hash(packet.ClientCert); - using (playerManager.GetSavedPlayerData(out Dictionary savedPlayerData)) - { - if (!savedPlayerData.TryGetValue(clientCertHash, out IPlayerData value)) - { - savedPlayerData.Add(clientCertHash, player.Data); - } - } + // Should these be locked together? - // Should these be locked together? + int syncingCount; + using (playerManager.GetSyncingPlayers(out var syncingPlayers)) + { + var removed = syncingPlayers.Remove(player.Connection); + syncingCount = syncingPlayers.Count; + } - int syncingCount; - using (playerManager.GetSyncingPlayers(out System.Collections.Generic.Dictionary syncingPlayers)) + using (playerManager.GetConnectedPlayers(out var connectedPlayers)) + { + if (!connectedPlayers.ContainsKey(player.Connection)) { - bool removed = syncingPlayers.Remove(player.Connection); - syncingCount = syncingPlayers.Count; + connectedPlayers.Add(player.Connection, player); } + } - using (playerManager.GetConnectedPlayers(out System.Collections.Generic.Dictionary connectedPlayers)) - { - if (!connectedPlayers.ContainsKey(player.Connection)) - { - connectedPlayers.Add(player.Connection, player); - } - } + // Since the player is now connected, we can safely spawn his player model + Multiplayer.Session.World.OnPlayerJoinedGame(player); - // Since the player is now connected, we can safely spawn his player model - Multiplayer.Session.World.OnPlayerJoinedGame(player); + if (syncingCount == 0) + { + var inGamePlayersDatas = playerManager.GetAllPlayerDataIncludingHost(); + playerManager.SendPacketToAllPlayers(new SyncComplete(inGamePlayersDatas)); - if (syncingCount == 0) + // Since the host is always in the game he could already have changed his mecha armor, so send it to the new player. + using (var writer = new BinaryUtils.Writer()) { - IPlayerData[] inGamePlayersDatas = playerManager.GetAllPlayerDataIncludingHost(); - playerManager.SendPacketToAllPlayers(new SyncComplete(inGamePlayersDatas)); + GameMain.mainPlayer.mecha.appearance.Export(writer.BinaryWriter); + player.SendPacket(new PlayerMechaArmor(Multiplayer.Session.LocalPlayer.Id, writer.CloseAndGetBytes())); + } - // Since the host is always in the game he could already have changed his mecha armor, so send it to the new player. - using (BinaryUtils.Writer writer = new BinaryUtils.Writer()) + // if the client had used a custom armor we should have saved a copy of it, so send it back + if (player.Data.Appearance != null) + { + using (var writer = new BinaryUtils.Writer()) { - GameMain.mainPlayer.mecha.appearance.Export(writer.BinaryWriter); - player.SendPacket(new PlayerMechaArmor(Multiplayer.Session.LocalPlayer.Id, writer.CloseAndGetBytes())); + player.Data.Appearance.Export(writer.BinaryWriter); + playerManager.SendPacketToAllPlayers(new PlayerMechaArmor(player.Id, writer.CloseAndGetBytes())); } - // if the client had used a custom armor we should have saved a copy of it, so send it back - if(player.Data.Appearance != null) + // and load custom appearance on host side too + // this is the code from PlayerMechaArmonrProcessor + using (Multiplayer.Session.World.GetRemotePlayersModels( + out Dictionary remotePlayersModels)) { - using (BinaryUtils.Writer writer = new BinaryUtils.Writer()) + if (remotePlayersModels.TryGetValue(player.Id, out var playerModel)) { - player.Data.Appearance.Export(writer.BinaryWriter); - playerManager.SendPacketToAllPlayers(new PlayerMechaArmor(player.Id, writer.CloseAndGetBytes())); - } - - // and load custom appearance on host side too - // this is the code from PlayerMechaArmonrProcessor - using (Multiplayer.Session.World.GetRemotePlayersModels(out Dictionary remotePlayersModels)) - { - if(remotePlayersModels.TryGetValue(player.Id, out RemotePlayerModel playerModel)) + if (playerModel.MechaInstance.appearance == null) { - if(playerModel.MechaInstance.appearance == null) - { - playerModel.MechaInstance.appearance = new MechaAppearance(); - playerModel.MechaInstance.appearance.Init(); - } - player.Data.Appearance.CopyTo(playerModel.MechaInstance.appearance); - playerModel.PlayerInstance.mechaArmorModel.RefreshAllPartObjects(); - playerModel.PlayerInstance.mechaArmorModel.RefreshAllBoneObjects(); - playerModel.MechaInstance.appearance.NotifyAllEvents(); - playerModel.PlayerInstance.mechaArmorModel._Init(playerModel.PlayerInstance); - playerModel.PlayerInstance.mechaArmorModel._OnOpen(); + playerModel.MechaInstance.appearance = new MechaAppearance(); + playerModel.MechaInstance.appearance.Init(); } + player.Data.Appearance.CopyTo(playerModel.MechaInstance.appearance); + playerModel.PlayerInstance.mechaArmorModel.RefreshAllPartObjects(); + playerModel.PlayerInstance.mechaArmorModel.RefreshAllBoneObjects(); + playerModel.MechaInstance.appearance.NotifyAllEvents(); + playerModel.PlayerInstance.mechaArmorModel._Init(playerModel.PlayerInstance); + playerModel.PlayerInstance.mechaArmorModel._OnOpen(); } } + } - // if the client has some changes made in his mecha editor send them back for them to load - if(player.Data.DIYAppearance != null) + // if the client has some changes made in his mecha editor send them back for them to load + if (player.Data.DIYAppearance != null) + { + using (var writer = new BinaryUtils.Writer()) { - using (BinaryUtils.Writer writer = new BinaryUtils.Writer()) - { - player.Data.DIYAppearance.Export(writer.BinaryWriter); - player.SendPacket(new PlayerMechaDIYArmor(writer.CloseAndGetBytes(), player.Data.DIYItemId, player.Data.DIYItemValue)); - } + player.Data.DIYAppearance.Export(writer.BinaryWriter); + player.SendPacket(new PlayerMechaDIYArmor(writer.CloseAndGetBytes(), player.Data.DIYItemId, + player.Data.DIYItemValue)); } - - Multiplayer.Session.World.OnAllPlayersSyncCompleted(); } + + Multiplayer.Session.World.OnAllPlayersSyncCompleted(); } - else // IsClient + } + else // IsClient + { + // Everyone is now connected, we can safely spawn the player model of all the other players that are currently connected + foreach (var playerData in packet.AllPlayers) { - // Everyone is now connected, we can safely spawn the player model of all the other players that are currently connected - foreach (NebulaModel.DataStructures.PlayerData playerData in packet.AllPlayers) + if (playerData.PlayerId != Multiplayer.Session.LocalPlayer.Id) { - if (playerData.PlayerId != Multiplayer.Session.LocalPlayer.Id) - { - Multiplayer.Session.World.SpawnRemotePlayerModel(playerData); - } + Multiplayer.Session.World.SpawnRemotePlayerModel(playerData); } - - Multiplayer.Session.World.OnAllPlayersSyncCompleted(); } + + Multiplayer.Session.World.OnAllPlayersSyncCompleted(); } } } diff --git a/NebulaNetwork/PacketProcessors/Statistics/MilestoneDataResponseProcessor.cs b/NebulaNetwork/PacketProcessors/Statistics/MilestoneDataResponseProcessor.cs index 8852d3dca..abc1d0fc0 100644 --- a/NebulaNetwork/PacketProcessors/Statistics/MilestoneDataResponseProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Statistics/MilestoneDataResponseProcessor.cs @@ -1,29 +1,32 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Statistics; -namespace NebulaNetwork.PacketProcessors.Statistics +#endregion + +namespace NebulaNetwork.PacketProcessors.Statistics; + +[RegisterPacketProcessor] +internal class MilestoneDataResponseProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class MilestoneDataResponseProcessor : PacketProcessor + public override void ProcessPacket(MilestoneDataResponse packet, NebulaConnection conn) { - public override void ProcessPacket(MilestoneDataResponse packet, NebulaConnection conn) + if (IsHost) { - if (IsHost) - { - return; - } + return; + } - //Reset all current values - GameMain.data.milestoneSystem.Init(GameMain.data); + //Reset all current values + GameMain.data.milestoneSystem.Init(GameMain.data); - Log.Info($"Parsing Milstone data from the server."); - using (BinaryUtils.Reader reader = new BinaryUtils.Reader(packet.BinaryData)) - { - GameMain.data.milestoneSystem.Import(reader.BinaryReader); - } + Log.Info("Parsing Milstone data from the server."); + using (var reader = new BinaryUtils.Reader(packet.BinaryData)) + { + GameMain.data.milestoneSystem.Import(reader.BinaryReader); } } } diff --git a/NebulaNetwork/PacketProcessors/Statistics/MilestoneUnlockProcessor.cs b/NebulaNetwork/PacketProcessors/Statistics/MilestoneUnlockProcessor.cs index 360f22166..71e5f76f9 100644 --- a/NebulaNetwork/PacketProcessors/Statistics/MilestoneUnlockProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Statistics/MilestoneUnlockProcessor.cs @@ -1,42 +1,45 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Statistics; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Statistics +#endregion + +namespace NebulaNetwork.PacketProcessors.Statistics; + +[RegisterPacketProcessor] +internal class MilestoneUnlockProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class MilestoneUnlockProcessor : PacketProcessor + public override void ProcessPacket(MilestoneUnlockPacket packet, NebulaConnection conn) { - public override void ProcessPacket(MilestoneUnlockPacket packet, NebulaConnection conn) - { - IPlayerManager playerManager = Multiplayer.Session.Network.PlayerManager; - bool valid = true; + IPlayerManager playerManager = Multiplayer.Session.Network.PlayerManager; + var valid = true; - if (IsHost) + if (IsHost) + { + var player = playerManager.GetPlayer(conn); + if (player != null) { - INebulaPlayer player = playerManager.GetPlayer(conn); - if (player != null) - { - playerManager.SendPacketToOtherPlayers(packet, player); - } - else - { - valid = false; - } + playerManager.SendPacketToOtherPlayers(packet, player); + } + else + { + valid = false; } + } - if (valid) + if (valid) + { + using (Multiplayer.Session.Statistics.IsIncomingRequest.On()) { - using (Multiplayer.Session.Statistics.IsIncomingRequest.On()) + if (GameMain.data.milestoneSystem.milestoneDatas.TryGetValue(packet.Id, out var milestoneData)) { - if (GameMain.data.milestoneSystem.milestoneDatas.TryGetValue(packet.Id, out MilestoneData milestoneData)) - { - milestoneData.journalData.patternId = packet.PatternId; - milestoneData.journalData.parameters = packet.Parameters; - GameMain.data.milestoneSystem.UnlockMilestone(packet.Id, packet.UnlockTick); - } + milestoneData.journalData.patternId = packet.PatternId; + milestoneData.journalData.parameters = packet.Parameters; + GameMain.data.milestoneSystem.UnlockMilestone(packet.Id, packet.UnlockTick); } } } diff --git a/NebulaNetwork/PacketProcessors/Statistics/StatisticsDataProcessor.cs b/NebulaNetwork/PacketProcessors/Statistics/StatisticsDataProcessor.cs index 80a9ea044..b645855a8 100644 --- a/NebulaNetwork/PacketProcessors/Statistics/StatisticsDataProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Statistics/StatisticsDataProcessor.cs @@ -1,20 +1,23 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Statistics; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Statistics +#endregion + +namespace NebulaNetwork.PacketProcessors.Statistics; + +[RegisterPacketProcessor] +internal class StatisticsDataProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class StatisticsDataProcessor : PacketProcessor + public override void ProcessPacket(StatisticsDataPacket packet, NebulaConnection conn) { - public override void ProcessPacket(StatisticsDataPacket packet, NebulaConnection conn) + using (var reader = new BinaryUtils.Reader(packet.StatisticsBinaryData)) { - using (BinaryUtils.Reader reader = new BinaryUtils.Reader(packet.StatisticsBinaryData)) - { - Multiplayer.Session.Statistics.ImportAllData(reader.BinaryReader); - } + Multiplayer.Session.Statistics.ImportAllData(reader.BinaryReader); } } } diff --git a/NebulaNetwork/PacketProcessors/Statistics/StatisticsRequestEventProcessor.cs b/NebulaNetwork/PacketProcessors/Statistics/StatisticsRequestEventProcessor.cs index 5c6345459..6861f4dbc 100644 --- a/NebulaNetwork/PacketProcessors/Statistics/StatisticsRequestEventProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Statistics/StatisticsRequestEventProcessor.cs @@ -1,46 +1,49 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Statistics; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Statistics +#endregion + +namespace NebulaNetwork.PacketProcessors.Statistics; + +[RegisterPacketProcessor] +internal class StatisticsRequestEventProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class StatisticsRequestEventProcessor : PacketProcessor + private readonly IPlayerManager playerManager; + + public StatisticsRequestEventProcessor() { - private readonly IPlayerManager playerManager; + playerManager = Multiplayer.Session.Network.PlayerManager; + } - public StatisticsRequestEventProcessor() + public override void ProcessPacket(StatisticsRequestEvent packet, NebulaConnection conn) + { + if (IsClient) { - playerManager = Multiplayer.Session.Network.PlayerManager; + return; } - public override void ProcessPacket(StatisticsRequestEvent packet, NebulaConnection conn) + var player = playerManager.GetPlayer(conn); + if (player != null) { - if (IsClient) + if (packet.Event == StatisticEvent.WindowOpened) { - return; - } + Multiplayer.Session.Statistics.RegisterPlayer(conn, player.Id); - INebulaPlayer player = playerManager.GetPlayer(conn); - if (player != null) - { - if (packet.Event == StatisticEvent.WindowOpened) - { - Multiplayer.Session.Statistics.RegisterPlayer(conn, player.Id); - - using (BinaryUtils.Writer writer = new BinaryUtils.Writer()) - { - Multiplayer.Session.Statistics.ExportAllData(writer.BinaryWriter); - conn.SendPacket(new StatisticsDataPacket(writer.CloseAndGetBytes())); - } - } - else if (packet.Event == StatisticEvent.WindowClosed) + using (var writer = new BinaryUtils.Writer()) { - Multiplayer.Session.Statistics.UnRegisterPlayer(player.Id); + Multiplayer.Session.Statistics.ExportAllData(writer.BinaryWriter); + conn.SendPacket(new StatisticsDataPacket(writer.CloseAndGetBytes())); } } + else if (packet.Event == StatisticEvent.WindowClosed) + { + Multiplayer.Session.Statistics.UnRegisterPlayer(player.Id); + } } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Statistics/StatisticsUpdateProcessor.cs b/NebulaNetwork/PacketProcessors/Statistics/StatisticsUpdateProcessor.cs index 5cb78a661..6be03684f 100644 --- a/NebulaNetwork/PacketProcessors/Statistics/StatisticsUpdateProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Statistics/StatisticsUpdateProcessor.cs @@ -1,75 +1,81 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.DataStructures; +using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Statistics; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Statistics +#endregion + +namespace NebulaNetwork.PacketProcessors.Statistics; + +[RegisterPacketProcessor] +internal class StatisticsUpdateProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class StatisticsUpdateProcessor : PacketProcessor + public override void ProcessPacket(StatisticUpdateDataPacket packet, NebulaConnection conn) { - public override void ProcessPacket(StatisticUpdateDataPacket packet, NebulaConnection conn) + StatisticalSnapShot snapshot; + using (Multiplayer.Session.Statistics.IsIncomingRequest.On()) { - StatisticalSnapShot snapshot; - using (Multiplayer.Session.Statistics.IsIncomingRequest.On()) + using (var reader = new BinaryUtils.Reader(packet.StatisticsBinaryData)) { - using (BinaryUtils.Reader reader = new BinaryUtils.Reader(packet.StatisticsBinaryData)) + var itemChanged = false; + ref var productionStats = ref GameMain.statistics.production.factoryStatPool; + var numOfSnapshots = reader.BinaryReader.ReadInt32(); + for (var i = 0; i < numOfSnapshots; i++) { - bool itemChanged = false; - ref FactoryProductionStat[] productionStats = ref GameMain.statistics.production.factoryStatPool; - int numOfSnapshots = reader.BinaryReader.ReadInt32(); - for (int i = 0; i < numOfSnapshots; i++) + //Load new snapshot + snapshot = new StatisticalSnapShot(reader.BinaryReader); + for (var factoryId = 0; factoryId < snapshot.ProductionChangesPerFactory.Length; factoryId++) { - //Load new snapshot - snapshot = new StatisticalSnapShot(reader.BinaryReader); - for (int factoryId = 0; factoryId < snapshot.ProductionChangesPerFactory.Length; factoryId++) + if (productionStats[factoryId] == null) { - if (productionStats[factoryId] == null) + productionStats[factoryId] = new FactoryProductionStat(); + productionStats[factoryId].Init(); + } + //Clear current statistical data + productionStats[factoryId].PrepareTick(); + + for (var changeId = 0; changeId < snapshot.ProductionChangesPerFactory[factoryId].Count; changeId++) + { + var productionChange = snapshot.ProductionChangesPerFactory[factoryId][changeId]; + if (productionChange.IsProduction) { - productionStats[factoryId] = new FactoryProductionStat(); - productionStats[factoryId].Init(); + productionStats[factoryId].productRegister[productionChange.ProductId] += + productionChange.Amount; } - //Clear current statistical data - productionStats[factoryId].PrepareTick(); - - for (int changeId = 0; changeId < snapshot.ProductionChangesPerFactory[factoryId].Count; changeId++) + else { - StatisticalSnapShot.ProductionChangeStruct productionChange = snapshot.ProductionChangesPerFactory[factoryId][changeId]; - if (productionChange.IsProduction) - { - productionStats[factoryId].productRegister[productionChange.ProductId] += productionChange.Amount; - } - else - { - productionStats[factoryId].consumeRegister[productionChange.ProductId] += productionChange.Amount; - } + productionStats[factoryId].consumeRegister[productionChange.ProductId] += + productionChange.Amount; } - //Import power system statistics - productionStats[factoryId].powerGenRegister = snapshot.PowerGenerationRegister[factoryId]; - productionStats[factoryId].powerConRegister = snapshot.PowerConsumptionRegister[factoryId]; - productionStats[factoryId].powerChaRegister = snapshot.PowerChargingRegister[factoryId]; - productionStats[factoryId].powerDisRegister = snapshot.PowerDischargingRegister[factoryId]; + } + //Import power system statistics + productionStats[factoryId].powerGenRegister = snapshot.PowerGenerationRegister[factoryId]; + productionStats[factoryId].powerConRegister = snapshot.PowerConsumptionRegister[factoryId]; + productionStats[factoryId].powerChaRegister = snapshot.PowerChargingRegister[factoryId]; + productionStats[factoryId].powerDisRegister = snapshot.PowerDischargingRegister[factoryId]; - //Import fake energy stored values - Multiplayer.Session.Statistics.PowerEnergyStoredData = snapshot.EnergyStored; + //Import fake energy stored values + Multiplayer.Session.Statistics.PowerEnergyStoredData = snapshot.EnergyStored; - //Import Research statistics - productionStats[factoryId].hashRegister = snapshot.HashRegister[factoryId]; + //Import Research statistics + productionStats[factoryId].hashRegister = snapshot.HashRegister[factoryId]; - //Processs changed registers. FactoryProductionStat.AfterTick() is empty currently so we ignore it. - productionStats[factoryId].GameTick(snapshot.CapturedGameTick); - itemChanged |= productionStats[factoryId].itemChanged; - } - } - //Trigger GameMain.statistics.production.onItemChange() event when itemChanged is true - if (itemChanged) - { - UIRoot.instance.uiGame.statWindow.OnItemChange(); - NebulaModel.Logger.Log.Debug("StatisticsUpdateProcessor: itemChanged"); + //Processs changed registers. FactoryProductionStat.AfterTick() is empty currently so we ignore it. + productionStats[factoryId].GameTick(snapshot.CapturedGameTick); + itemChanged |= productionStats[factoryId].itemChanged; } } + //Trigger GameMain.statistics.production.onItemChange() event when itemChanged is true + if (itemChanged) + { + UIRoot.instance.uiGame.statWindow.OnItemChange(); + Log.Debug("StatisticsUpdateProcessor: itemChanged"); + } } } } diff --git a/NebulaNetwork/PacketProcessors/Trash/TrashSystemClearAllTrashProcessor.cs b/NebulaNetwork/PacketProcessors/Trash/TrashSystemClearAllTrashProcessor.cs index 4d8e5b8d7..93af6a440 100644 --- a/NebulaNetwork/PacketProcessors/Trash/TrashSystemClearAllTrashProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Trash/TrashSystemClearAllTrashProcessor.cs @@ -1,44 +1,47 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Trash; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Trash +#endregion + +namespace NebulaNetwork.PacketProcessors.Trash; + +[RegisterPacketProcessor] +internal class TrashSystemClearAllTrashProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class TrashSystemClearAllTrashProcessor : PacketProcessor - { - private readonly IPlayerManager playerManager; + private readonly IPlayerManager playerManager; - public TrashSystemClearAllTrashProcessor() - { - playerManager = Multiplayer.Session.Network.PlayerManager; - } + public TrashSystemClearAllTrashProcessor() + { + playerManager = Multiplayer.Session.Network.PlayerManager; + } - public override void ProcessPacket(TrashSystemClearAllTrashPacket packet, NebulaConnection conn) + public override void ProcessPacket(TrashSystemClearAllTrashPacket packet, NebulaConnection conn) + { + var valid = true; + if (IsHost) { - bool valid = true; - if (IsHost) + var player = playerManager.GetPlayer(conn); + if (player != null) + { + playerManager.SendPacketToOtherPlayers(packet, player); + } + else { - INebulaPlayer player = playerManager.GetPlayer(conn); - if (player != null) - { - playerManager.SendPacketToOtherPlayers(packet, player); - } - else - { - valid = false; - } + valid = false; } + } - if (valid) + if (valid) + { + using (Multiplayer.Session.Trashes.ClearAllTrashFromOtherPlayers.On()) { - using (Multiplayer.Session.Trashes.ClearAllTrashFromOtherPlayers.On()) - { - GameMain.data.trashSystem.ClearAllTrash(); - } + GameMain.data.trashSystem.ClearAllTrash(); } } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Trash/TrashSystemNewTrashCreatedProcessor.cs b/NebulaNetwork/PacketProcessors/Trash/TrashSystemNewTrashCreatedProcessor.cs index 87cf2bae2..33f20499c 100644 --- a/NebulaNetwork/PacketProcessors/Trash/TrashSystemNewTrashCreatedProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Trash/TrashSystemNewTrashCreatedProcessor.cs @@ -1,47 +1,50 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Trash; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Trash +#endregion + +namespace NebulaNetwork.PacketProcessors.Trash; + +[RegisterPacketProcessor] +internal class TrashSystemNewTrashCreatedProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class TrashSystemNewTrashCreatedProcessor : PacketProcessor + private readonly IPlayerManager playerManager; + + public TrashSystemNewTrashCreatedProcessor() { - private readonly IPlayerManager playerManager; + playerManager = Multiplayer.Session.Network.PlayerManager; + } - public TrashSystemNewTrashCreatedProcessor() + public override void ProcessPacket(TrashSystemNewTrashCreatedPacket packet, NebulaConnection conn) + { + var valid = true; + if (IsHost) { - playerManager = Multiplayer.Session.Network.PlayerManager; + var player = playerManager.GetPlayer(conn); + if (player != null) + { + playerManager.SendPacketToOtherPlayers(packet, player); + } + else + { + valid = false; + } } - public override void ProcessPacket(TrashSystemNewTrashCreatedPacket packet, NebulaConnection conn) + if (valid) { - bool valid = true; - if (IsHost) - { - INebulaPlayer player = playerManager.GetPlayer(conn); - if (player != null) - { - playerManager.SendPacketToOtherPlayers(packet, player); - } - else - { - valid = false; - } - } + var myId = Multiplayer.Session.World.GenerateTrashOnPlayer(packet); - if (valid) + //Check if myID is same as the ID from the host + if (myId != packet.TrashId) { - int myId = Multiplayer.Session.World.GenerateTrashOnPlayer(packet); - - //Check if myID is same as the ID from the host - if (myId != packet.TrashId) - { - Multiplayer.Session.Trashes.SwitchTrashWithIds(myId, packet.TrashId); - } + Multiplayer.Session.Trashes.SwitchTrashWithIds(myId, packet.TrashId); } } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Trash/TrashSystemResponseDataProcessor.cs b/NebulaNetwork/PacketProcessors/Trash/TrashSystemResponseDataProcessor.cs index eb06a1d9f..00680b8ee 100644 --- a/NebulaNetwork/PacketProcessors/Trash/TrashSystemResponseDataProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Trash/TrashSystemResponseDataProcessor.cs @@ -1,30 +1,33 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Trash; -namespace NebulaNetwork.PacketProcessors.Trash +#endregion + +namespace NebulaNetwork.PacketProcessors.Trash; + +[RegisterPacketProcessor] +internal class TrashSystemResponseDataProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class TrashSystemResponseDataProcessor : PacketProcessor + public override void ProcessPacket(TrashSystemResponseDataPacket packet, NebulaConnection conn) { - public override void ProcessPacket(TrashSystemResponseDataPacket packet, NebulaConnection conn) + if (IsHost) { - if (IsHost) - { - return; - } + return; + } - using (BinaryUtils.Reader reader = new BinaryUtils.Reader(packet.TrashSystemData)) - { - GameMain.data.trashSystem.Import(reader.BinaryReader); - } - // Wait until WarningDataPacket to assign warningId - TrashContainer container = GameMain.data.trashSystem.container; - for (int i = 0; i < container.trashCursor; i++) - { - container.trashDataPool[i].warningId = -1; - } + using (var reader = new BinaryUtils.Reader(packet.TrashSystemData)) + { + GameMain.data.trashSystem.Import(reader.BinaryReader); + } + // Wait until WarningDataPacket to assign warningId + var container = GameMain.data.trashSystem.container; + for (var i = 0; i < container.trashCursor; i++) + { + container.trashDataPool[i].warningId = -1; } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Trash/TrashSystemTrashRemovedProcessor.cs b/NebulaNetwork/PacketProcessors/Trash/TrashSystemTrashRemovedProcessor.cs index 5b00e8ad7..9000710f6 100644 --- a/NebulaNetwork/PacketProcessors/Trash/TrashSystemTrashRemovedProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Trash/TrashSystemTrashRemovedProcessor.cs @@ -1,24 +1,27 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Trash; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Trash +#endregion + +namespace NebulaNetwork.PacketProcessors.Trash; + +[RegisterPacketProcessor] +internal class TrashSystemTrashRemovedProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class TrashSystemTrashRemovedProcessor : PacketProcessor + public override void ProcessPacket(TrashSystemTrashRemovedPacket packet, NebulaConnection conn) { - public override void ProcessPacket(TrashSystemTrashRemovedPacket packet, NebulaConnection conn) + if (IsHost) + { + Multiplayer.Session.Network.PlayerManager.SendPacketToOtherPlayers(packet, conn); + } + using (Multiplayer.Session.Trashes.RemoveTrashFromOtherPlayers.On()) { - if (IsHost) - { - Multiplayer.Session.Network.PlayerManager.SendPacketToOtherPlayers(packet, conn); - } - using (Multiplayer.Session.Trashes.RemoveTrashFromOtherPlayers.On()) - { - GameMain.data.trashSystem.RemoveTrash(packet.TrashId); - } + GameMain.data.trashSystem.RemoveTrash(packet.TrashId); } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Universe/DysonLaunchDataProcessor.cs b/NebulaNetwork/PacketProcessors/Universe/DysonLaunchDataProcessor.cs index 4e6579e9b..29d3e06f8 100644 --- a/NebulaNetwork/PacketProcessors/Universe/DysonLaunchDataProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Universe/DysonLaunchDataProcessor.cs @@ -1,21 +1,24 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Universe; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Universe +#endregion + +namespace NebulaNetwork.PacketProcessors.Universe; + +[RegisterPacketProcessor] +internal class DysonLaunchDataProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class DysonLaunchDataProcessor : PacketProcessor + public override void ProcessPacket(DysonLaunchDataPacket packet, NebulaConnection conn) { - public override void ProcessPacket(DysonLaunchDataPacket packet, NebulaConnection conn) + if (IsHost) { - if (IsHost) - { - return; - } - Multiplayer.Session.Launch.ImportPacket(packet); + return; } + Multiplayer.Session.Launch.ImportPacket(packet); } } diff --git a/NebulaNetwork/PacketProcessors/Universe/DysonSailDataProcessor.cs b/NebulaNetwork/PacketProcessors/Universe/DysonSailDataProcessor.cs index 29b6f520b..de05d26cf 100644 --- a/NebulaNetwork/PacketProcessors/Universe/DysonSailDataProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Universe/DysonSailDataProcessor.cs @@ -1,37 +1,40 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Universe; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Universe +#endregion + +namespace NebulaNetwork.PacketProcessors.Universe; + +[RegisterPacketProcessor] +internal class DysonSailDataProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class DysonSailDataProcessor : PacketProcessor + public override void ProcessPacket(DysonSailDataPacket packet, NebulaConnection conn) { - public override void ProcessPacket(DysonSailDataPacket packet, NebulaConnection conn) + var dysonSphere = GameMain.data.dysonSpheres[packet.StarIndex]; + if (dysonSphere == null) + { + return; + } + using (Multiplayer.Session.DysonSpheres.IncomingDysonSwarmPacket.On()) + { + DysonSail ss = default; + ss.px = packet.px; + ss.py = packet.py; + ss.pz = packet.pz; + ss.vx = packet.vx; + ss.vy = packet.vy; + ss.vz = packet.vz; + ss.gs = packet.gs; + dysonSphere.swarm.AddSolarSail(ss, packet.OrbitId, packet.ExpiryTime); + } + if (IsHost) { - DysonSphere dysonSphere = GameMain.data.dysonSpheres[packet.StarIndex]; - if (dysonSphere == null) - { - return; - } - using (Multiplayer.Session.DysonSpheres.IncomingDysonSwarmPacket.On()) - { - DysonSail ss = default; - ss.px = packet.px; - ss.py = packet.py; - ss.pz = packet.pz; - ss.vx = packet.vx; - ss.vy = packet.vy; - ss.vz = packet.vz; - ss.gs = packet.gs; - dysonSphere.swarm.AddSolarSail(ss, packet.OrbitId, packet.ExpiryTime); - } - if (IsHost) - { - Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); - } + Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); } } } diff --git a/NebulaNetwork/PacketProcessors/Universe/DysonSphereDataProcessor.cs b/NebulaNetwork/PacketProcessors/Universe/DysonSphereDataProcessor.cs index 0fde25756..25aac98e8 100644 --- a/NebulaNetwork/PacketProcessors/Universe/DysonSphereDataProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Universe/DysonSphereDataProcessor.cs @@ -1,94 +1,99 @@ -using NebulaAPI; +#region + +using System; +using System.Collections.Generic; +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Universe; using NebulaWorld; using NebulaWorld.GameStates; -using System.Collections.Generic; -using System.IO; -namespace NebulaNetwork.PacketProcessors.Universe +#endregion + +namespace NebulaNetwork.PacketProcessors.Universe; + +[RegisterPacketProcessor] +internal class DysonSphereDataProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class DysonSphereDataProcessor : PacketProcessor + public override void ProcessPacket(DysonSphereData packet, NebulaConnection conn) { - public override void ProcessPacket(DysonSphereData packet, NebulaConnection conn) + if (IsHost) { - if (IsHost) - { - return; - } + return; + } - switch (packet.Event) - { - case DysonSphereRespondEvent.List: - //Overwrite content assigned by UIDETopFunction.SetDysonComboBox() - UIComboBox dysonBox = UIRoot.instance.uiGame.dysonEditor.controlPanel.topFunction.dysonBox; - using (BinaryReader br = new BinaryUtils.Reader(packet.BinaryData).BinaryReader) + switch (packet.Event) + { + case DysonSphereRespondEvent.List: + //Overwrite content assigned by UIDETopFunction.SetDysonComboBox() + var dysonBox = UIRoot.instance.uiGame.dysonEditor.controlPanel.topFunction.dysonBox; + using (var br = new BinaryUtils.Reader(packet.BinaryData).BinaryReader) + { + dysonBox.Items = new List(); + dysonBox.ItemsData = new List(); + var count = br.ReadInt32(); + for (var i = 0; i < count; i++) { - dysonBox.Items = new List(); - dysonBox.ItemsData = new List(); - int count = br.ReadInt32(); - for (int i = 0; i < count; i++) - { - int starIndex = br.ReadInt32(); - dysonBox.Items.Add(GameMain.galaxy.stars[starIndex].displayName); - dysonBox.ItemsData.Add(starIndex); - } + var starIndex = br.ReadInt32(); + dysonBox.Items.Add(GameMain.galaxy.stars[starIndex].displayName); + dysonBox.ItemsData.Add(starIndex); } - int index = dysonBox.ItemsData.FindIndex(x => x == UIRoot.instance.uiGame.dysonEditor.selection.viewStar?.index); - dysonBox.itemIndex = index >= 0 ? index : 0; - break; + } + var index = dysonBox.ItemsData.FindIndex(x => + x == UIRoot.instance.uiGame.dysonEditor.selection.viewStar?.index); + dysonBox.itemIndex = index >= 0 ? index : 0; + break; - case DysonSphereRespondEvent.Load: - // The whole fragment is received - GameStatesManager.FragmentSize = 0; - //Failsafe, if client does not have instantiated sphere for the star, it will create dummy one that will be replaced during import - GameMain.data.dysonSpheres[packet.StarIndex] = new DysonSphere(); - GameMain.data.statistics.production.Init(GameMain.data); - //Another failsafe, DysonSphere import requires initialized factory statistics - if (GameMain.data.statistics.production.factoryStatPool[0] == null) - { - GameMain.data.statistics.production.factoryStatPool[0] = new FactoryProductionStat(); - GameMain.data.statistics.production.factoryStatPool[0].Init(); - } - GameMain.data.dysonSpheres[packet.StarIndex].Init(GameMain.data, GameMain.data.galaxy.stars[packet.StarIndex]); + case DysonSphereRespondEvent.Load: + // The whole fragment is received + GameStatesManager.FragmentSize = 0; + //Failsafe, if client does not have instantiated sphere for the star, it will create dummy one that will be replaced during import + GameMain.data.dysonSpheres[packet.StarIndex] = new DysonSphere(); + GameMain.data.statistics.production.Init(GameMain.data); + //Another failsafe, DysonSphere import requires initialized factory statistics + if (GameMain.data.statistics.production.factoryStatPool[0] == null) + { + GameMain.data.statistics.production.factoryStatPool[0] = new FactoryProductionStat(); + GameMain.data.statistics.production.factoryStatPool[0].Init(); + } + GameMain.data.dysonSpheres[packet.StarIndex].Init(GameMain.data, GameMain.data.galaxy.stars[packet.StarIndex]); - StarData star = GameMain.galaxy.stars[packet.StarIndex]; - Log.Info($"Parsing {packet.BinaryData.Length} bytes of data for DysonSphere {star.name} (INDEX: {star.id})"); - using (BinaryUtils.Reader reader = new BinaryUtils.Reader(packet.BinaryData)) - { - GameMain.data.dysonSpheres[packet.StarIndex].Import(reader.BinaryReader); - } - if (UIRoot.instance.uiGame.dysonEditor.active) - { - UIRoot.instance.uiGame.dysonEditor.selection.SetViewStar(GameMain.galaxy.stars[packet.StarIndex]); - UIComboBox dysonBox2 = UIRoot.instance.uiGame.dysonEditor.controlPanel.topFunction.dysonBox; - int index2 = dysonBox2.ItemsData.FindIndex(x => x == UIRoot.instance.uiGame.dysonEditor.selection.viewStar?.index); - dysonBox2.itemIndex = index2 >= 0 ? index2 : 0; - } - if (Multiplayer.Session.IsGameLoaded) - { - // Don't fade out when client is still joining - InGamePopup.FadeOut(); - } - Multiplayer.Session.DysonSpheres.RequestingIndex = -1; - Multiplayer.Session.DysonSpheres.IsNormal = true; + var star = GameMain.galaxy.stars[packet.StarIndex]; + Log.Info($"Parsing {packet.BinaryData.Length} bytes of data for DysonSphere {star.name} (INDEX: {star.id})"); + using (var reader = new BinaryUtils.Reader(packet.BinaryData)) + { + GameMain.data.dysonSpheres[packet.StarIndex].Import(reader.BinaryReader); + } + if (UIRoot.instance.uiGame.dysonEditor.active) + { + UIRoot.instance.uiGame.dysonEditor.selection.SetViewStar(GameMain.galaxy.stars[packet.StarIndex]); + var dysonBox2 = UIRoot.instance.uiGame.dysonEditor.controlPanel.topFunction.dysonBox; + var index2 = dysonBox2.ItemsData.FindIndex(x => + x == UIRoot.instance.uiGame.dysonEditor.selection.viewStar?.index); + dysonBox2.itemIndex = index2 >= 0 ? index2 : 0; + } + if (Multiplayer.Session.IsGameLoaded) + { + // Don't fade out when client is still joining + InGamePopup.FadeOut(); + } + Multiplayer.Session.DysonSpheres.RequestingIndex = -1; + Multiplayer.Session.DysonSpheres.IsNormal = true; - try - { - NebulaModAPI.OnDysonSphereLoadFinished?.Invoke(star.index); - } - catch (System.Exception e) - { - Log.Error("NebulaModAPI.OnDysonSphereLoadFinished error:\n" + e); - } - break; - case DysonSphereRespondEvent.Desync: - Multiplayer.Session.DysonSpheres.HandleDesync(packet.StarIndex, conn); - break; - } + try + { + NebulaModAPI.OnDysonSphereLoadFinished?.Invoke(star.index); + } + catch (Exception e) + { + Log.Error("NebulaModAPI.OnDysonSphereLoadFinished error:\n" + e); + } + break; + case DysonSphereRespondEvent.Desync: + Multiplayer.Session.DysonSpheres.HandleDesync(packet.StarIndex, conn); + break; } } } diff --git a/NebulaNetwork/PacketProcessors/Universe/DysonSphereRequestProcessor.cs b/NebulaNetwork/PacketProcessors/Universe/DysonSphereRequestProcessor.cs index 70608b63e..22c19b9db 100644 --- a/NebulaNetwork/PacketProcessors/Universe/DysonSphereRequestProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Universe/DysonSphereRequestProcessor.cs @@ -1,60 +1,64 @@ -using NebulaAPI; +#region + +using System.Collections.Generic; +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.GameStates; using NebulaModel.Packets.Universe; using NebulaWorld; -using System.Collections.Generic; -namespace NebulaNetwork.PacketProcessors.Universe +#endregion + +namespace NebulaNetwork.PacketProcessors.Universe; + +[RegisterPacketProcessor] +public class DysonSphereRequestProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class DysonSphereRequestProcessor : PacketProcessor + public override void ProcessPacket(DysonSphereLoadRequest packet, NebulaConnection conn) { - public override void ProcessPacket(DysonSphereLoadRequest packet, NebulaConnection conn) + if (IsClient) { - if (IsClient) - { - return; - } - switch (packet.Event) - { - case DysonSphereRequestEvent.List: - using (BinaryUtils.Writer writer = new BinaryUtils.Writer()) + return; + } + switch (packet.Event) + { + case DysonSphereRequestEvent.List: + using (var writer = new BinaryUtils.Writer()) + { + var list = new List(); + for (var i = 0; i < GameMain.data.dysonSpheres.Length; ++i) { - List list = new List(); - for (int i = 0; i < GameMain.data.dysonSpheres.Length; ++i) - { - if (GameMain.data.dysonSpheres[i] != null) - { - list.Add(i); - } - } - writer.BinaryWriter.Write(list.Count); - foreach(int starIndex in list) + if (GameMain.data.dysonSpheres[i] != null) { - writer.BinaryWriter.Write(starIndex); + list.Add(i); } - conn.SendPacket(new DysonSphereData(packet.StarIndex, writer.CloseAndGetBytes(), DysonSphereRespondEvent.List)); } - break; - case DysonSphereRequestEvent.Load: - DysonSphere dysonSphere = GameMain.data.CreateDysonSphere(packet.StarIndex); - using (BinaryUtils.Writer writer = new BinaryUtils.Writer()) + writer.BinaryWriter.Write(list.Count); + foreach (var starIndex in list) { - dysonSphere.Export(writer.BinaryWriter); - byte[] data = writer.CloseAndGetBytes(); - Log.Info($"Sent {data.Length} bytes of data for DysonSphereData (INDEX: {packet.StarIndex})"); - conn.SendPacket(new FragmentInfo(data.Length)); - conn.SendPacket(new DysonSphereData(packet.StarIndex, data, DysonSphereRespondEvent.Load)); - Multiplayer.Session.DysonSpheres.RegisterPlayer(conn, packet.StarIndex); + writer.BinaryWriter.Write(starIndex); } - break; - case DysonSphereRequestEvent.Unload: - Multiplayer.Session.DysonSpheres.UnRegisterPlayer(conn, packet.StarIndex); - break; - } + conn.SendPacket(new DysonSphereData(packet.StarIndex, writer.CloseAndGetBytes(), + DysonSphereRespondEvent.List)); + } + break; + case DysonSphereRequestEvent.Load: + var dysonSphere = GameMain.data.CreateDysonSphere(packet.StarIndex); + using (var writer = new BinaryUtils.Writer()) + { + dysonSphere.Export(writer.BinaryWriter); + var data = writer.CloseAndGetBytes(); + Log.Info($"Sent {data.Length} bytes of data for DysonSphereData (INDEX: {packet.StarIndex})"); + conn.SendPacket(new FragmentInfo(data.Length)); + conn.SendPacket(new DysonSphereData(packet.StarIndex, data, DysonSphereRespondEvent.Load)); + Multiplayer.Session.DysonSpheres.RegisterPlayer(conn, packet.StarIndex); + } + break; + case DysonSphereRequestEvent.Unload: + Multiplayer.Session.DysonSpheres.UnRegisterPlayer(conn, packet.StarIndex); + break; } } } diff --git a/NebulaNetwork/PacketProcessors/Universe/DysonSphereStatusProcessor.cs b/NebulaNetwork/PacketProcessors/Universe/DysonSphereStatusProcessor.cs index 664230bd2..694132182 100644 --- a/NebulaNetwork/PacketProcessors/Universe/DysonSphereStatusProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Universe/DysonSphereStatusProcessor.cs @@ -1,23 +1,26 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Universe; -namespace NebulaNetwork.PacketProcessors.Universe +#endregion + +namespace NebulaNetwork.PacketProcessors.Universe; + +[RegisterPacketProcessor] +internal class DysonSphereStatusProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class DysonSphereStatusProcessor : PacketProcessor + public override void ProcessPacket(DysonSphereStatusPacket packet, NebulaConnection conn) { - public override void ProcessPacket(DysonSphereStatusPacket packet, NebulaConnection conn) + var dysonSphere = GameMain.data.dysonSpheres[packet.StarIndex]; + if (IsHost || dysonSphere == null) { - DysonSphere dysonSphere = GameMain.data.dysonSpheres[packet.StarIndex]; - if (IsHost || dysonSphere == null) - { - return; - } - dysonSphere.grossRadius = packet.GrossRadius; - dysonSphere.energyReqCurrentTick = packet.EnergyReqCurrentTick; - dysonSphere.energyGenCurrentTick = packet.EnergyGenCurrentTick; + return; } + dysonSphere.grossRadius = packet.GrossRadius; + dysonSphere.energyReqCurrentTick = packet.EnergyReqCurrentTick; + dysonSphere.energyGenCurrentTick = packet.EnergyGenCurrentTick; } -} \ No newline at end of file +} diff --git a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonBlueprintProcessor.cs b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonBlueprintProcessor.cs index a6c85276d..c2170dd61 100644 --- a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonBlueprintProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonBlueprintProcessor.cs @@ -1,39 +1,42 @@ -using NebulaAPI; +#region + +using System.Text; +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Universe; using NebulaWorld; -using System.Text; -namespace NebulaNetwork.PacketProcessors.Universe +#endregion + +namespace NebulaNetwork.PacketProcessors.Universe; + +[RegisterPacketProcessor] +internal class DysonBlueprintProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class DysonBlueprintProcessor : PacketProcessor + public override void ProcessPacket(DysonBlueprintPacket packet, NebulaConnection conn) { - public override void ProcessPacket(DysonBlueprintPacket packet, NebulaConnection conn) + var sphere = GameMain.data.dysonSpheres[packet.StarIndex]; + if (sphere == null) + { + return; + } + using (Multiplayer.Session.DysonSpheres.IsIncomingRequest.On()) { - DysonSphere sphere = GameMain.data.dysonSpheres[packet.StarIndex]; - if (sphere == null) + var layer = sphere.GetLayer(packet.LayerId); + var str64Data = Encoding.ASCII.GetString(packet.BinaryData); + var err = new DysonBlueprintData().FromBase64String(str64Data, packet.BlueprintType, sphere, layer); + if (err != DysonBlueprintDataIOError.OK) { + Log.Warn($"DysonBlueprintData IO error: {err}"); + Multiplayer.Session.DysonSpheres.HandleDesync(packet.StarIndex, conn); return; } - using (Multiplayer.Session.DysonSpheres.IsIncomingRequest.On()) - { - DysonSphereLayer layer = sphere.GetLayer(packet.LayerId); - string str64Data = Encoding.ASCII.GetString(packet.BinaryData); - DysonBlueprintDataIOError err = new DysonBlueprintData().FromBase64String(str64Data, packet.BlueprintType, sphere, layer); - if (err != DysonBlueprintDataIOError.OK) - { - Log.Warn($"DysonBlueprintData IO error: {err}"); - Multiplayer.Session.DysonSpheres.HandleDesync(packet.StarIndex, conn); - return; - } - } - if (IsHost) - { - Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); - } + } + if (IsHost) + { + Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); } } } diff --git a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereAddFrameProcessor.cs b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereAddFrameProcessor.cs index 2082e9de7..6adf94a2c 100644 --- a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereAddFrameProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereAddFrameProcessor.cs @@ -1,37 +1,40 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Universe; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Universe +#endregion + +namespace NebulaNetwork.PacketProcessors.Universe; + +[RegisterPacketProcessor] +internal class DysonSphereAddFrameProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class DysonSphereAddFrameProcessor : PacketProcessor + public override void ProcessPacket(DysonSphereAddFramePacket packet, NebulaConnection conn) { - public override void ProcessPacket(DysonSphereAddFramePacket packet, NebulaConnection conn) + var layer = GameMain.data.dysonSpheres[packet.StarIndex]?.GetLayer(packet.LayerId); + if (layer == null) { - DysonSphereLayer layer = GameMain.data.dysonSpheres[packet.StarIndex]?.GetLayer(packet.LayerId); - if (layer == null) + return; + } + using (Multiplayer.Session.DysonSpheres.IsIncomingRequest.On()) + { + var frameId = layer.frameRecycleCursor > 0 ? layer.frameRecycle[layer.frameRecycleCursor - 1] : layer.frameCursor; + if (frameId != packet.FrameId || + layer.NewDysonFrame(packet.ProtoId, packet.NodeAId, packet.NodeBId, packet.Euler) == 0) { + Log.Warn($"Cannnot add frame[{packet.FrameId}] on layer[{layer.id}], starIndex[{packet.StarIndex}]"); + Multiplayer.Session.DysonSpheres.HandleDesync(packet.StarIndex, conn); return; } - using (Multiplayer.Session.DysonSpheres.IsIncomingRequest.On()) - { - int frameId = layer.frameRecycleCursor > 0 ? layer.frameRecycle[layer.frameRecycleCursor - 1] : layer.frameCursor; - if (frameId != packet.FrameId || layer.NewDysonFrame(packet.ProtoId, packet.NodeAId, packet.NodeBId, packet.Euler) == 0) - { - Log.Warn($"Cannnot add frame[{packet.FrameId}] on layer[{layer.id}], starIndex[{packet.StarIndex}]"); - Multiplayer.Session.DysonSpheres.HandleDesync(packet.StarIndex, conn); - return; - } - } - if (IsHost) - { - Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); - } + } + if (IsHost) + { + Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); } } } - diff --git a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereAddLayerProcessor.cs b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereAddLayerProcessor.cs index 84687f35b..31f79143c 100644 --- a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereAddLayerProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereAddLayerProcessor.cs @@ -1,34 +1,37 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Universe; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Universe +#endregion + +namespace NebulaNetwork.PacketProcessors.Universe; + +[RegisterPacketProcessor] +public class DysonSphereAddLayerProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class DysonSphereAddLayerProcessor : PacketProcessor + public override void ProcessPacket(DysonSphereAddLayerPacket packet, NebulaConnection conn) { - public override void ProcessPacket(DysonSphereAddLayerPacket packet, NebulaConnection conn) + var sphere = GameMain.data.dysonSpheres[packet.StarIndex]; + if (sphere == null) { - DysonSphere sphere = GameMain.data.dysonSpheres[packet.StarIndex]; - if (sphere == null) + return; + } + using (Multiplayer.Session.DysonSpheres.IsIncomingRequest.On()) + { + if (packet.LayerId != sphere.QueryLayerId()) { + Multiplayer.Session.DysonSpheres.HandleDesync(packet.StarIndex, conn); return; } - using (Multiplayer.Session.DysonSpheres.IsIncomingRequest.On()) - { - if (packet.LayerId != sphere.QueryLayerId()) - { - Multiplayer.Session.DysonSpheres.HandleDesync(packet.StarIndex, conn); - return; - } - sphere.AddLayer(packet.OrbitRadius, packet.OrbitRotation.ToQuaternion(), packet.OrbitAngularSpeed); - } - if (IsHost) - { - Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); - } + sphere.AddLayer(packet.OrbitRadius, packet.OrbitRotation.ToQuaternion(), packet.OrbitAngularSpeed); + } + if (IsHost) + { + Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); } } } diff --git a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereAddNodeProcessor.cs b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereAddNodeProcessor.cs index e68e3fb69..d8cc6b1b4 100644 --- a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereAddNodeProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereAddNodeProcessor.cs @@ -1,36 +1,39 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Universe; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Universe +#endregion + +namespace NebulaNetwork.PacketProcessors.Universe; + +[RegisterPacketProcessor] +internal class DysonSphereAddNodeProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class DysonSphereAddNodeProcessor : PacketProcessor + public override void ProcessPacket(DysonSphereAddNodePacket packet, NebulaConnection conn) { - public override void ProcessPacket(DysonSphereAddNodePacket packet, NebulaConnection conn) + var layer = GameMain.data.dysonSpheres[packet.StarIndex]?.GetLayer(packet.LayerId); + if (layer == null) { - DysonSphereLayer layer = GameMain.data.dysonSpheres[packet.StarIndex]?.GetLayer(packet.LayerId); - if (layer == null) + return; + } + using (Multiplayer.Session.DysonSpheres.IsIncomingRequest.On()) + { + var nodeId = layer.nodeRecycleCursor > 0 ? layer.nodeRecycle[layer.nodeRecycleCursor - 1] : layer.nodeCursor; + if (nodeId != packet.NodeId || layer.NewDysonNode(packet.NodeProtoId, packet.Position.ToVector3()) == 0) { + Log.Warn($"Cannnot add node[{packet.NodeId}] on layer[{layer.id}], starIndex[{packet.StarIndex}]"); + Multiplayer.Session.DysonSpheres.HandleDesync(packet.StarIndex, conn); return; } - using (Multiplayer.Session.DysonSpheres.IsIncomingRequest.On()) - { - int nodeId = layer.nodeRecycleCursor > 0 ? layer.nodeRecycle[layer.nodeRecycleCursor - 1] : layer.nodeCursor; - if (nodeId != packet.NodeId || layer.NewDysonNode(packet.NodeProtoId, packet.Position.ToVector3()) == 0) - { - Log.Warn($"Cannnot add node[{packet.NodeId}] on layer[{layer.id}], starIndex[{packet.StarIndex}]"); - Multiplayer.Session.DysonSpheres.HandleDesync(packet.StarIndex, conn); - return; - } - } - if (IsHost) - { - Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); - } + } + if (IsHost) + { + Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); } } } diff --git a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereAddShellProcessor.cs b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereAddShellProcessor.cs index f7147770f..2c2cfceef 100644 --- a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereAddShellProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereAddShellProcessor.cs @@ -1,37 +1,40 @@ -using NebulaAPI; +#region + +using System.Collections.Generic; +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Universe; using NebulaWorld; -using System.Collections.Generic; -namespace NebulaNetwork.PacketProcessors.Universe +#endregion + +namespace NebulaNetwork.PacketProcessors.Universe; + +[RegisterPacketProcessor] +internal class DysonSphereAddShellProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class DysonSphereAddShellProcessor : PacketProcessor + public override void ProcessPacket(DysonSphereAddShellPacket packet, NebulaConnection conn) { - public override void ProcessPacket(DysonSphereAddShellPacket packet, NebulaConnection conn) + var layer = GameMain.data.dysonSpheres[packet.StarIndex]?.GetLayer(packet.LayerId); + if (layer == null) + { + return; + } + using (Multiplayer.Session.DysonSpheres.IsIncomingRequest.On()) { - DysonSphereLayer layer = GameMain.data.dysonSpheres[packet.StarIndex]?.GetLayer(packet.LayerId); - if (layer == null) + var shellId = layer.shellRecycleCursor > 0 ? layer.shellRecycle[layer.shellRecycleCursor - 1] : layer.shellCursor; + if (shellId != packet.ShellId || layer.NewDysonShell(packet.ProtoId, new List(packet.NodeIds)) == 0) { + Log.Warn($"Cannnot add shell[{packet.ShellId}] on layer[{layer.id}], starIndex[{packet.StarIndex}]"); + Multiplayer.Session.DysonSpheres.HandleDesync(packet.StarIndex, conn); return; } - using (Multiplayer.Session.DysonSpheres.IsIncomingRequest.On()) - { - int shellId = layer.shellRecycleCursor > 0 ? layer.shellRecycle[layer.shellRecycleCursor - 1] : layer.shellCursor; - if (shellId != packet.ShellId || layer.NewDysonShell(packet.ProtoId, new List(packet.NodeIds)) == 0) - { - Log.Warn($"Cannnot add shell[{packet.ShellId}] on layer[{layer.id}], starIndex[{packet.StarIndex}]"); - Multiplayer.Session.DysonSpheres.HandleDesync(packet.StarIndex, conn); - return; - } - } - if (IsHost) - { - Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); - } + } + if (IsHost) + { + Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); } } } diff --git a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereColorChangeProcessor.cs b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereColorChangeProcessor.cs index 8df0ae5b5..dff0cff91 100644 --- a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereColorChangeProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereColorChangeProcessor.cs @@ -1,64 +1,66 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Universe; using NebulaWorld; -using UnityEngine; -namespace NebulaNetwork.PacketProcessors.Universe +#endregion + +namespace NebulaNetwork.PacketProcessors.Universe; + +[RegisterPacketProcessor] +public class DysonSphereColorChangeProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class DysonSphereColorChangeProcessor : PacketProcessor + public override void ProcessPacket(DysonSphereColorChangePacket packet, NebulaConnection conn) { - public override void ProcessPacket(DysonSphereColorChangePacket packet, NebulaConnection conn) + var sphere = GameMain.data.dysonSpheres[packet.StarIndex]; + if (sphere == null) + { + return; + } + using (Multiplayer.Session.DysonSpheres.IsIncomingRequest.On()) { - DysonSphere sphere = GameMain.data.dysonSpheres[packet.StarIndex]; - if (sphere == null) + var layer = sphere.GetLayer(packet.LayerId); + if (layer == null) { + Multiplayer.Session.DysonSpheres.HandleDesync(packet.StarIndex, conn); return; } - using (Multiplayer.Session.DysonSpheres.IsIncomingRequest.On()) + var color = packet.Color.ToColor32(); + switch (packet.Type) { - DysonSphereLayer layer = sphere.GetLayer(packet.LayerId); - if (layer == null) - { - Multiplayer.Session.DysonSpheres.HandleDesync(packet.StarIndex, conn); - return; - } - Color32 color = packet.Color.ToColor32(); - switch (packet.Type) - { - case DysonSphereColorChangePacket.ComponentType.Node: - DysonNode node = packet.Index < layer.nodeCursor ? layer.nodePool[packet.Index] : null; - if (node != null) - { - node.color = color; - sphere.UpdateColor(node); - } - break; + case DysonSphereColorChangePacket.ComponentType.Node: + var node = packet.Index < layer.nodeCursor ? layer.nodePool[packet.Index] : null; + if (node != null) + { + node.color = color; + sphere.UpdateColor(node); + } + break; - case DysonSphereColorChangePacket.ComponentType.Frame: - DysonFrame frame = packet.Index < layer.frameCursor ? layer.framePool[packet.Index] : null; - if (frame != null) - { - frame.color = color; - sphere.UpdateColor(frame); - } - break; + case DysonSphereColorChangePacket.ComponentType.Frame: + var frame = packet.Index < layer.frameCursor ? layer.framePool[packet.Index] : null; + if (frame != null) + { + frame.color = color; + sphere.UpdateColor(frame); + } + break; - case DysonSphereColorChangePacket.ComponentType.Shell: - DysonShell shell = packet.Index < layer.shellCursor ? layer.shellPool[packet.Index] : null; - if (shell != null) - { - shell.color = color; - } - break; - } - } - if (IsHost) - { - Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); + case DysonSphereColorChangePacket.ComponentType.Shell: + var shell = packet.Index < layer.shellCursor ? layer.shellPool[packet.Index] : null; + if (shell != null) + { + shell.color = color; + } + break; } } + if (IsHost) + { + Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); + } } } diff --git a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereEditLayerProcessor.cs b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereEditLayerProcessor.cs index 7af112feb..984152b89 100644 --- a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereEditLayerProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereEditLayerProcessor.cs @@ -1,36 +1,39 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Universe; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Universe +#endregion + +namespace NebulaNetwork.PacketProcessors.Universe; + +[RegisterPacketProcessor] +public class DysonSphereEditLayerProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class DysonSphereEditLayerProcessor : PacketProcessor + public override void ProcessPacket(DysonSphereEditLayerPacket packet, NebulaConnection conn) { - public override void ProcessPacket(DysonSphereEditLayerPacket packet, NebulaConnection conn) + var sphere = GameMain.data.dysonSpheres[packet.StarIndex]; + if (sphere == null) { - DysonSphere sphere = GameMain.data.dysonSpheres[packet.StarIndex]; - if (sphere == null) + return; + } + using (Multiplayer.Session.DysonSpheres.IsIncomingRequest.On()) + { + var layer = sphere.GetLayer(packet.LayerId); + if (layer == null) { + Multiplayer.Session.DysonSpheres.HandleDesync(packet.StarIndex, conn); return; } - using (Multiplayer.Session.DysonSpheres.IsIncomingRequest.On()) - { - DysonSphereLayer layer = sphere.GetLayer(packet.LayerId); - if (layer == null) - { - Multiplayer.Session.DysonSpheres.HandleDesync(packet.StarIndex, conn); - return; - } - layer.targetOrbitRotation = packet.OrbitRotation.ToQuaternion(); - layer.InitOrbitRotation(layer.orbitRotation, layer.targetOrbitRotation); - } - if (IsHost) - { - Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); - } + layer.targetOrbitRotation = packet.OrbitRotation.ToQuaternion(); + layer.InitOrbitRotation(layer.orbitRotation, layer.targetOrbitRotation); + } + if (IsHost) + { + Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); } } } diff --git a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSpherePaintCellsProcessor.cs b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSpherePaintCellsProcessor.cs index a77736ea2..841f70e9c 100644 --- a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSpherePaintCellsProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSpherePaintCellsProcessor.cs @@ -1,65 +1,68 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Universe; using NebulaWorld; using UnityEngine; -namespace NebulaNetwork.PacketProcessors.Universe +#endregion + +namespace NebulaNetwork.PacketProcessors.Universe; + +[RegisterPacketProcessor] +public class DysonSpherePaintCellsProcessor : PacketProcessor { - [RegisterPacketProcessor] - public class DysonSpherePaintCellsProcessor : PacketProcessor + public override void ProcessPacket(DysonSpherePaintCellsPacket packet, NebulaConnection conn) { - public override void ProcessPacket(DysonSpherePaintCellsPacket packet, NebulaConnection conn) + var sphere = GameMain.data.dysonSpheres[packet.StarIndex]; + if (sphere == null) { - DysonSphere sphere = GameMain.data.dysonSpheres[packet.StarIndex]; - if (sphere == null) + return; + } + using (Multiplayer.Session.DysonSpheres.IsIncomingRequest.On()) + { + var layer = sphere.GetLayer(packet.LayerId); + if (layer == null) { + Multiplayer.Session.DysonSpheres.HandleDesync(packet.StarIndex, conn); return; } - using (Multiplayer.Session.DysonSpheres.IsIncomingRequest.On()) - { - DysonSphereLayer layer = sphere.GetLayer(packet.LayerId); - if (layer == null) - { - Multiplayer.Session.DysonSpheres.HandleDesync(packet.StarIndex, conn); - return; - } - // UIDEPaintingbox.OpenGrid() - Color32[] cellColors; - if (layer.cellColors != null) - { - Assert.True(layer.cellColors.Length == packet.CellCount); - cellColors = layer.cellColors; - } - else - { - cellColors = new Color32[packet.CellCount]; - } + // UIDEPaintingbox.OpenGrid() + Color32[] cellColors; + if (layer.cellColors != null) + { + Assert.True(layer.cellColors.Length == packet.CellCount); + cellColors = layer.cellColors; + } + else + { + cellColors = new Color32[packet.CellCount]; + } - // UIDysonPaintingGrid.PaintCells() - Color32 paint = packet.Paint.ToColor32(); - for (int i = 0; i < packet.CursorCells.Length; i++) + // UIDysonPaintingGrid.PaintCells() + var paint = packet.Paint.ToColor32(); + for (var i = 0; i < packet.CursorCells.Length; i++) + { + var cid = packet.CursorCells[i]; + if (cid >= 0) { - int cid = packet.CursorCells[i]; - if (cid >= 0) - { - Color32 color = cellColors[cid]; - color.a -= (color.a <= 127) ? (byte)0 : (byte)127; - color.a *= 2; - Color32 color2 = Color32.Lerp(color, paint, packet.Strength); - color2.a /= 2; - color2.a += ((paint.a > 0) ? (packet.SuperBrightMode ? (byte)127 : (byte)0) : (byte)0); - cellColors[cid] = color2; - } + var color = cellColors[cid]; + color.a -= color.a <= 127 ? 0 : 127; + color.a *= 2; + var color2 = Color32.Lerp(color, paint, packet.Strength); + color2.a /= 2; + color2.a += paint.a > 0 ? packet.SuperBrightMode ? 127 : 0 : 0; + cellColors[cid] = color2; } - layer.SetPaintingData(cellColors); - } - if (IsHost) - { - Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); } + layer.SetPaintingData(cellColors); + } + if (IsHost) + { + Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); } } } diff --git a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereRemoveFrameProcessor.cs b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereRemoveFrameProcessor.cs index e132b27c7..379d2796a 100644 --- a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereRemoveFrameProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereRemoveFrameProcessor.cs @@ -1,78 +1,82 @@ -using NebulaAPI; +#region + +using System.Collections.Generic; +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Universe; using NebulaWorld; -using System.Collections.Generic; +using NebulaWorld.Universe; + +#endregion -namespace NebulaNetwork.PacketProcessors.Universe +namespace NebulaNetwork.PacketProcessors.Universe; + +[RegisterPacketProcessor] +internal class DysonSphereRemoveFrameProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class DysonSphereRemoveFrameProcessor : PacketProcessor + public override void ProcessPacket(DysonSphereRemoveFramePacket packet, NebulaConnection conn) { - public override void ProcessPacket(DysonSphereRemoveFramePacket packet, NebulaConnection conn) + var layer = GameMain.data.dysonSpheres[packet.StarIndex]?.GetLayer(packet.LayerId); + if (layer == null) + { + return; + } + using (Multiplayer.Session.DysonSpheres.IsIncomingRequest.On()) { - DysonSphereLayer layer = GameMain.data.dysonSpheres[packet.StarIndex]?.GetLayer(packet.LayerId); - if (layer == null) + if (!Check(layer, packet)) { + Log.Warn($"Cannnot remove frame[{packet.FrameId}] on layer[{layer.id}], starIndex[{packet.StarIndex}]"); + Multiplayer.Session.DysonSpheres.HandleDesync(packet.StarIndex, conn); return; } - using (Multiplayer.Session.DysonSpheres.IsIncomingRequest.On()) + //No need to remove if the frame is already null + if (layer.framePool[packet.FrameId] != null) { - if (!Check(layer, packet)) - { - Log.Warn($"Cannnot remove frame[{packet.FrameId}] on layer[{layer.id}], starIndex[{packet.StarIndex}]"); - Multiplayer.Session.DysonSpheres.HandleDesync(packet.StarIndex, conn); - return; - } - //No need to remove if the frame is already null - if (layer.framePool[packet.FrameId] != null) - { - layer.RemoveDysonFrame(packet.FrameId); - NebulaWorld.Universe.DysonSphereManager.ClearSelection(packet.StarIndex, layer.id); - } - } - if (IsHost) - { - Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); + layer.RemoveDysonFrame(packet.FrameId); + DysonSphereManager.ClearSelection(packet.StarIndex, layer.id); } } + if (IsHost) + { + Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); + } + } - private static bool Check(DysonSphereLayer layer, DysonSphereRemoveFramePacket packet) + private static bool Check(DysonSphereLayer layer, DysonSphereRemoveFramePacket packet) + { + if (packet.FrameId < 1 || packet.FrameId >= layer.frameCursor) { - if (packet.FrameId < 1 || packet.FrameId >= layer.frameCursor) - { - return false; - } - DysonFrame frame = layer.framePool[packet.FrameId]; - if (frame == null) - { - //Sender and receiver are in the same state, so it's ok to pass - return true; - } - //Make sure that shells connected to the frame are removed first. - //UIDysonBrush_Remove.DeleteSelectedNode() remove frames first, so we need to remove shells here. - List delShellList = new List(); - foreach (DysonShell shell in frame.nodeA.shells) - { - if (shell.frames.Contains(frame) && !delShellList.Contains(shell.id)) - { - delShellList.Add(shell.id); - } - } - foreach (DysonShell shell in frame.nodeB.shells) + return false; + } + var frame = layer.framePool[packet.FrameId]; + if (frame == null) + { + //Sender and receiver are in the same state, so it's ok to pass + return true; + } + //Make sure that shells connected to the frame are removed first. + //UIDysonBrush_Remove.DeleteSelectedNode() remove frames first, so we need to remove shells here. + var delShellList = new List(); + foreach (var shell in frame.nodeA.shells) + { + if (shell.frames.Contains(frame) && !delShellList.Contains(shell.id)) { - if (shell.frames.Contains(frame) && !delShellList.Contains(shell.id)) - { - delShellList.Add(shell.id); - } + delShellList.Add(shell.id); } - foreach (int shellId in delShellList) + } + foreach (var shell in frame.nodeB.shells) + { + if (shell.frames.Contains(frame) && !delShellList.Contains(shell.id)) { - layer.RemoveDysonShell(shellId); + delShellList.Add(shell.id); } - return true; } + foreach (var shellId in delShellList) + { + layer.RemoveDysonShell(shellId); + } + return true; } } diff --git a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereRemoveLayerProcessor.cs b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereRemoveLayerProcessor.cs index df79eaa28..272274422 100644 --- a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereRemoveLayerProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereRemoveLayerProcessor.cs @@ -1,30 +1,34 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Universe; using NebulaWorld; +using NebulaWorld.Universe; + +#endregion -namespace NebulaNetwork.PacketProcessors.Universe +namespace NebulaNetwork.PacketProcessors.Universe; + +[RegisterPacketProcessor] +internal class DysonSphereRemoveLayerProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class DysonSphereRemoveLayerProcessor : PacketProcessor + public override void ProcessPacket(DysonSphereRemoveLayerPacket packet, NebulaConnection conn) { - public override void ProcessPacket(DysonSphereRemoveLayerPacket packet, NebulaConnection conn) + var sphere = GameMain.data.dysonSpheres[packet.StarIndex]; + if (sphere == null) + { + return; + } + using (Multiplayer.Session.DysonSpheres.IsIncomingRequest.On()) + { + sphere.RemoveLayer(packet.LayerId); + DysonSphereManager.ClearSelection(packet.StarIndex); + } + if (IsHost) { - DysonSphere sphere = GameMain.data.dysonSpheres[packet.StarIndex]; - if (sphere == null) - { - return; - } - using (Multiplayer.Session.DysonSpheres.IsIncomingRequest.On()) - { - sphere.RemoveLayer(packet.LayerId); - NebulaWorld.Universe.DysonSphereManager.ClearSelection(packet.StarIndex); - } - if (IsHost) - { - Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); - } + Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); } } } diff --git a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereRemoveNodeProcessor.cs b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereRemoveNodeProcessor.cs index 47e8c476d..2f3a632bd 100644 --- a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereRemoveNodeProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereRemoveNodeProcessor.cs @@ -1,61 +1,65 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Universe; using NebulaWorld; +using NebulaWorld.Universe; + +#endregion + +namespace NebulaNetwork.PacketProcessors.Universe; -namespace NebulaNetwork.PacketProcessors.Universe +[RegisterPacketProcessor] +internal class DysonSphereRemoveNodeProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class DysonSphereRemoveNodeProcessor : PacketProcessor + public override void ProcessPacket(DysonSphereRemoveNodePacket packet, NebulaConnection conn) { - public override void ProcessPacket(DysonSphereRemoveNodePacket packet, NebulaConnection conn) + var layer = GameMain.data.dysonSpheres[packet.StarIndex]?.GetLayer(packet.LayerId); + if (layer == null) { - DysonSphereLayer layer = GameMain.data.dysonSpheres[packet.StarIndex]?.GetLayer(packet.LayerId); - if (layer == null) + return; + } + using (Multiplayer.Session.DysonSpheres.IsIncomingRequest.On()) + { + if (!Check(layer, packet)) { + Log.Warn($"Cannnot remove node[{packet.NodeId}] on layer[{layer.id}], starIndex[{packet.StarIndex}]"); + Multiplayer.Session.DysonSpheres.HandleDesync(packet.StarIndex, conn); return; } - using (Multiplayer.Session.DysonSpheres.IsIncomingRequest.On()) + //No need to remove if the node is already null + if (layer.nodePool[packet.NodeId] != null) { - if (!Check(layer, packet)) - { - Log.Warn($"Cannnot remove node[{packet.NodeId}] on layer[{layer.id}], starIndex[{packet.StarIndex}]"); - Multiplayer.Session.DysonSpheres.HandleDesync(packet.StarIndex, conn); - return; - } - //No need to remove if the node is already null - if (layer.nodePool[packet.NodeId] != null) - { - layer.RemoveDysonNode(packet.NodeId); - NebulaWorld.Universe.DysonSphereManager.ClearSelection(packet.StarIndex, layer.id); - } - } - if (IsHost) - { - Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); + layer.RemoveDysonNode(packet.NodeId); + DysonSphereManager.ClearSelection(packet.StarIndex, layer.id); } } + if (IsHost) + { + Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); + } + } - private static bool Check(DysonSphereLayer layer, DysonSphereRemoveNodePacket packet) + private static bool Check(DysonSphereLayer layer, DysonSphereRemoveNodePacket packet) + { + if (packet.NodeId < 1 || packet.NodeId >= layer.nodeCursor) { - if (packet.NodeId < 1 || packet.NodeId >= layer.nodeCursor) - { - return false; - } - DysonNode node = layer.nodePool[packet.NodeId]; - if (node == null) - { - //Sender and receiver are in the same state, so it's ok to pass - return true; - } - //Make sure that shells and frames connected to the node are removed first. - if (node.frames.Count > 0) - { - return false; - } + return false; + } + var node = layer.nodePool[packet.NodeId]; + if (node == null) + { + //Sender and receiver are in the same state, so it's ok to pass return true; } + //Make sure that shells and frames connected to the node are removed first. + if (node.frames.Count > 0) + { + return false; + } + return true; } } diff --git a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereRemoveShellProcessor.cs b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereRemoveShellProcessor.cs index 1e716ca0d..468032d86 100644 --- a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereRemoveShellProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSphereRemoveShellProcessor.cs @@ -1,41 +1,45 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Universe; using NebulaWorld; +using NebulaWorld.Universe; + +#endregion + +namespace NebulaNetwork.PacketProcessors.Universe; -namespace NebulaNetwork.PacketProcessors.Universe +[RegisterPacketProcessor] +internal class DysonSphereRemoveShellProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class DysonSphereRemoveShellProcessor : PacketProcessor + public override void ProcessPacket(DysonSphereRemoveShellPacket packet, NebulaConnection conn) { - public override void ProcessPacket(DysonSphereRemoveShellPacket packet, NebulaConnection conn) + var layer = GameMain.data.dysonSpheres[packet.StarIndex]?.GetLayer(packet.LayerId); + if (layer == null) + { + return; + } + using (Multiplayer.Session.DysonSpheres.IsIncomingRequest.On()) { - DysonSphereLayer layer = GameMain.data.dysonSpheres[packet.StarIndex]?.GetLayer(packet.LayerId); - if (layer == null) + if (packet.ShellId < 1 || packet.ShellId >= layer.shellCursor) { + Log.Warn($"Cannnot remove shell[{packet.ShellId}] on layer[{layer.id}], starIndex[{packet.StarIndex}]"); + Multiplayer.Session.DysonSpheres.HandleDesync(packet.StarIndex, conn); return; } - using (Multiplayer.Session.DysonSpheres.IsIncomingRequest.On()) + //No need to remove if the shell is already null + if (layer.shellPool[packet.ShellId] != null) { - if (packet.ShellId < 1 || packet.ShellId >= layer.shellCursor) - { - Log.Warn($"Cannnot remove shell[{packet.ShellId}] on layer[{layer.id}], starIndex[{packet.StarIndex}]"); - Multiplayer.Session.DysonSpheres.HandleDesync(packet.StarIndex, conn); - return; - } - //No need to remove if the shell is already null - if (layer.shellPool[packet.ShellId] != null) - { - layer.RemoveDysonShell(packet.ShellId); - NebulaWorld.Universe.DysonSphereManager.ClearSelection(packet.StarIndex, layer.id); - } - } - if (IsHost) - { - Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); + layer.RemoveDysonShell(packet.ShellId); + DysonSphereManager.ClearSelection(packet.StarIndex, layer.id); } } + if (IsHost) + { + Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); + } } } diff --git a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSwarmAddOrbitProcessor.cs b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSwarmAddOrbitProcessor.cs index 2bf84a30b..e4cbb4c6c 100644 --- a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSwarmAddOrbitProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSwarmAddOrbitProcessor.cs @@ -1,34 +1,38 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Universe; using NebulaWorld; +using NebulaWorld.Universe; + +#endregion + +namespace NebulaNetwork.PacketProcessors.Universe; -namespace NebulaNetwork.PacketProcessors.Universe +[RegisterPacketProcessor] +internal class DysonSwarmAddOrbitProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class DysonSwarmAddOrbitProcessor : PacketProcessor + public override void ProcessPacket(DysonSwarmAddOrbitPacket packet, NebulaConnection conn) { - public override void ProcessPacket(DysonSwarmAddOrbitPacket packet, NebulaConnection conn) + var sphere = GameMain.data.dysonSpheres[packet.StarIndex]; + if (sphere == null) { - DysonSphere sphere = GameMain.data.dysonSpheres[packet.StarIndex]; - if (sphere == null) + return; + } + using (Multiplayer.Session.DysonSpheres.IncomingDysonSwarmPacket.On()) + { + if (packet.OrbitId != DysonSphereManager.QueryOrbitId(sphere.swarm)) { + Multiplayer.Session.DysonSpheres.HandleDesync(packet.StarIndex, conn); return; } - using (Multiplayer.Session.DysonSpheres.IncomingDysonSwarmPacket.On()) - { - if (packet.OrbitId != NebulaWorld.Universe.DysonSphereManager.QueryOrbitId(sphere.swarm)) - { - Multiplayer.Session.DysonSpheres.HandleDesync(packet.StarIndex, conn); - return; - } - sphere.swarm.NewOrbit(packet.Radius, packet.Rotation.ToQuaternion()); - } - if (IsHost) - { - Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); - } + sphere.swarm.NewOrbit(packet.Radius, packet.Rotation.ToQuaternion()); + } + if (IsHost) + { + Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); } } } diff --git a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSwarmEditOrbitProcessor.cs b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSwarmEditOrbitProcessor.cs index 7a8942bbd..6beab0817 100644 --- a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSwarmEditOrbitProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSwarmEditOrbitProcessor.cs @@ -1,38 +1,46 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Universe; using NebulaWorld; using UnityEngine; -namespace NebulaNetwork.PacketProcessors.Universe +#endregion + +namespace NebulaNetwork.PacketProcessors.Universe; + +[RegisterPacketProcessor] +internal class DysonSwarmEditOrbitProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class DysonSwarmEditOrbitProcessor : PacketProcessor + public override void ProcessPacket(DysonSwarmEditOrbitPacket packet, NebulaConnection conn) { - public override void ProcessPacket(DysonSwarmEditOrbitPacket packet, NebulaConnection conn) + var sphere = GameMain.data.dysonSpheres[packet.StarIndex]; + if (sphere == null) { - DysonSphere sphere = GameMain.data.dysonSpheres[packet.StarIndex]; - if (sphere == null) + return; + } + using (Multiplayer.Session.DysonSpheres.IncomingDysonSwarmPacket.On()) + { + if (!sphere.swarm.OrbitExist(packet.OrbitId)) { + Multiplayer.Session.DysonSpheres.HandleDesync(packet.StarIndex, conn); return; } - using (Multiplayer.Session.DysonSpheres.IncomingDysonSwarmPacket.On()) + if (packet.Radius >= 0) { - if (!sphere.swarm.OrbitExist(packet.OrbitId)) - { - Multiplayer.Session.DysonSpheres.HandleDesync(packet.StarIndex, conn); - return; - } - if (packet.Radius >= 0) - sphere.swarm.EditOrbit(packet.OrbitId, packet.Radius, packet.Rotation.ToQuaternion()); - else - sphere.swarm.SetOrbitColor(packet.OrbitId, new Vector4(packet.Color.x, packet.Color.y, packet.Color.z, packet.Color.w)); + sphere.swarm.EditOrbit(packet.OrbitId, packet.Radius, packet.Rotation.ToQuaternion()); } - if (IsHost) + else { - Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); + sphere.swarm.SetOrbitColor(packet.OrbitId, + new Vector4(packet.Color.x, packet.Color.y, packet.Color.z, packet.Color.w)); } } + if (IsHost) + { + Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); + } } } diff --git a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSwarmRemoveOrbitProcessor.cs b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSwarmRemoveOrbitProcessor.cs index f3e23fac1..1cad228ec 100644 --- a/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSwarmRemoveOrbitProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Universe/Editor/DysonSwarmRemoveOrbitProcessor.cs @@ -1,41 +1,45 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Universe; using NebulaWorld; +using NebulaWorld.Universe; + +#endregion -namespace NebulaNetwork.PacketProcessors.Universe +namespace NebulaNetwork.PacketProcessors.Universe; + +[RegisterPacketProcessor] +internal class DysonSwarmRemoveOrbitProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class DysonSwarmRemoveOrbitProcessor : PacketProcessor + public override void ProcessPacket(DysonSwarmRemoveOrbitPacket packet, NebulaConnection conn) { - public override void ProcessPacket(DysonSwarmRemoveOrbitPacket packet, NebulaConnection conn) + var sphere = GameMain.data.dysonSpheres[packet.StarIndex]; + if (sphere == null) { - DysonSphere sphere = GameMain.data.dysonSpheres[packet.StarIndex]; - if (sphere == null) + return; + } + using (Multiplayer.Session.DysonSpheres.IncomingDysonSwarmPacket.On()) + { + if (packet.Event == SwarmRemoveOrbitEvent.Remove) { - return; + sphere.swarm.RemoveOrbit(packet.OrbitId); } - using (Multiplayer.Session.DysonSpheres.IncomingDysonSwarmPacket.On()) + else if (packet.Event == SwarmRemoveOrbitEvent.Enable || packet.Event == SwarmRemoveOrbitEvent.Disable) { - if (packet.Event == SwarmRemoveOrbitEvent.Remove) - { - sphere.swarm.RemoveOrbit(packet.OrbitId); - } - else if (packet.Event == SwarmRemoveOrbitEvent.Enable || packet.Event == SwarmRemoveOrbitEvent.Disable) - { - sphere.swarm.SetOrbitEnable(packet.OrbitId, packet.Event == SwarmRemoveOrbitEvent.Enable); - } - else if (packet.Event == SwarmRemoveOrbitEvent.RemoveSails) - { - sphere.swarm.RemoveSailsByOrbit(packet.OrbitId); - } - NebulaWorld.Universe.DysonSphereManager.ClearSelection(packet.StarIndex); + sphere.swarm.SetOrbitEnable(packet.OrbitId, packet.Event == SwarmRemoveOrbitEvent.Enable); } - if (IsHost) + else if (packet.Event == SwarmRemoveOrbitEvent.RemoveSails) { - Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); + sphere.swarm.RemoveSailsByOrbit(packet.OrbitId); } + DysonSphereManager.ClearSelection(packet.StarIndex); + } + if (IsHost) + { + Multiplayer.Session.DysonSpheres.SendPacketToDysonSphereExcept(packet, packet.StarIndex, conn); } } } diff --git a/NebulaNetwork/PacketProcessors/Universe/NameInputProcessor.cs b/NebulaNetwork/PacketProcessors/Universe/NameInputProcessor.cs index 6fdcbde77..5e66e4258 100644 --- a/NebulaNetwork/PacketProcessors/Universe/NameInputProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Universe/NameInputProcessor.cs @@ -1,69 +1,72 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Universe; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Universe +#endregion + +namespace NebulaNetwork.PacketProcessors.Universe; + +/* + * Receives change event for name of planet or star and applies the change + */ +[RegisterPacketProcessor] +internal class NameInputProcessor : PacketProcessor { - /* - * Receives change event for name of planet or star and applies the change - */ - [RegisterPacketProcessor] - internal class NameInputProcessor : PacketProcessor + private readonly IPlayerManager playerManager; + + public NameInputProcessor() { - private readonly IPlayerManager playerManager; + playerManager = Multiplayer.Session.Network.PlayerManager; + } - public NameInputProcessor() + public override void ProcessPacket(NameInputPacket packet, NebulaConnection conn) + { + if (IsHost) { - playerManager = Multiplayer.Session.Network.PlayerManager; + var player = playerManager.GetPlayer(conn); + if (player != null) + { + playerManager.SendPacketToOtherPlayers(packet, player); + } } - public override void ProcessPacket(NameInputPacket packet, NebulaConnection conn) + using (Multiplayer.Session.Factories.IsIncomingRequest.On()) { - if (IsHost) + // If in lobby, apply change to UI galaxy + var galaxyData = Multiplayer.Session.IsInLobby ? UIRoot.instance.galaxySelect.starmap.galaxyData : GameMain.galaxy; + if (galaxyData == null) { - INebulaPlayer player = playerManager.GetPlayer(conn); - if (player != null) - { - playerManager.SendPacketToOtherPlayers(packet, player); - } + return; } - using (Multiplayer.Session.Factories.IsIncomingRequest.On()) + for (var i = 0; i < packet.Names.Length; i++) { - // If in lobby, apply change to UI galaxy - GalaxyData galaxyData = Multiplayer.Session.IsInLobby ? UIRoot.instance.galaxySelect.starmap.galaxyData : GameMain.galaxy; - if (galaxyData == null) + if (packet.StarIds[i] != NebulaModAPI.STAR_NONE) { - return; + var star = galaxyData.StarById(packet.StarIds[i]); + star.overrideName = packet.Names[i]; + star.NotifyOnDisplayNameChange(); + Log.Debug($"star{star.id}: {star.name} -> {star.overrideName}"); } - - for (int i = 0; i < packet.Names.Length; i++) + else { - if (packet.StarIds[i] != NebulaModAPI.STAR_NONE) - { - StarData star = galaxyData.StarById(packet.StarIds[i]); - star.overrideName = packet.Names[i]; - star.NotifyOnDisplayNameChange(); - Log.Debug($"star{star.id}: {star.name} -> {star.overrideName}"); - } - else - { - PlanetData planet = galaxyData.PlanetById(packet.PlanetIds[i]); - planet.overrideName = packet.Names[i]; - planet.NotifyOnDisplayNameChange(); - Log.Debug($"planet{planet.id}: {planet.name} -> {planet.overrideName}"); - } - } - galaxyData.NotifyAstroNameChange(); - if (Multiplayer.Session.IsInLobby) - { - // Refresh star name in lobby - UIRoot.instance.galaxySelect.starmap.OnGalaxyDataReset(); + var planet = galaxyData.PlanetById(packet.PlanetIds[i]); + planet.overrideName = packet.Names[i]; + planet.NotifyOnDisplayNameChange(); + Log.Debug($"planet{planet.id}: {planet.name} -> {planet.overrideName}"); } } + galaxyData.NotifyAstroNameChange(); + if (Multiplayer.Session.IsInLobby) + { + // Refresh star name in lobby + UIRoot.instance.galaxySelect.starmap.OnGalaxyDataReset(); + } } } } diff --git a/NebulaNetwork/PacketProcessors/Warning/WarningDataProcessor.cs b/NebulaNetwork/PacketProcessors/Warning/WarningDataProcessor.cs index a625097b7..7692f12c8 100644 --- a/NebulaNetwork/PacketProcessors/Warning/WarningDataProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Warning/WarningDataProcessor.cs @@ -1,21 +1,24 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Warning; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Warning +#endregion + +namespace NebulaNetwork.PacketProcessors.Warning; + +[RegisterPacketProcessor] +internal class WarningDataProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class WarningDataProcessor : PacketProcessor + public override void ProcessPacket(WarningDataPacket packet, NebulaConnection conn) { - public override void ProcessPacket(WarningDataPacket packet, NebulaConnection conn) + Multiplayer.Session.Warning.TickData = packet.Tick; + using (var reader = new BinaryUtils.Reader(packet.BinaryData)) { - Multiplayer.Session.Warning.TickData = packet.Tick; - using (BinaryUtils.Reader reader = new BinaryUtils.Reader(packet.BinaryData)) - { - Multiplayer.Session.Warning.ImportBinaryData(reader.BinaryReader, packet.ActiveWarningCount); - } + Multiplayer.Session.Warning.ImportBinaryData(reader.BinaryReader, packet.ActiveWarningCount); } } } diff --git a/NebulaNetwork/PacketProcessors/Warning/WarningDataRequestProcessor.cs b/NebulaNetwork/PacketProcessors/Warning/WarningDataRequestProcessor.cs index bb85a1e3c..d2079776f 100644 --- a/NebulaNetwork/PacketProcessors/Warning/WarningDataRequestProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Warning/WarningDataRequestProcessor.cs @@ -1,17 +1,20 @@ -using NebulaAPI; +#region + +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Warning; using NebulaWorld; -namespace NebulaNetwork.PacketProcessors.Warning +#endregion + +namespace NebulaNetwork.PacketProcessors.Warning; + +[RegisterPacketProcessor] +internal class WarningDataRequestProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class WarningDataRequestProcessor : PacketProcessor + public override void ProcessPacket(WarningDataRequest packet, NebulaConnection conn) { - public override void ProcessPacket(WarningDataRequest packet, NebulaConnection conn) - { - Multiplayer.Session.Warning.HandleRequest(packet, conn); - } + Multiplayer.Session.Warning.HandleRequest(packet, conn); } } diff --git a/NebulaNetwork/PacketProcessors/Warning/WarningSignalProcessor.cs b/NebulaNetwork/PacketProcessors/Warning/WarningSignalProcessor.cs index 76eaf3ad6..6143c27dd 100644 --- a/NebulaNetwork/PacketProcessors/Warning/WarningSignalProcessor.cs +++ b/NebulaNetwork/PacketProcessors/Warning/WarningSignalProcessor.cs @@ -1,30 +1,33 @@ -using NebulaAPI; +#region + +using System; +using NebulaAPI; using NebulaModel.Networking; using NebulaModel.Packets; using NebulaModel.Packets.Warning; using NebulaWorld; -using System; -namespace NebulaNetwork.PacketProcessors.Warning +#endregion + +namespace NebulaNetwork.PacketProcessors.Warning; + +[RegisterPacketProcessor] +internal class WarningSignalProcessor : PacketProcessor { - [RegisterPacketProcessor] - internal class WarningSignalProcessor : PacketProcessor + public override void ProcessPacket(WarningSignalPacket packet, NebulaConnection conn) { - public override void ProcessPacket(WarningSignalPacket packet, NebulaConnection conn) - { - WarningSystem ws = GameMain.data.warningSystem; - Array.Clear(ws.warningCounts, 0, ws.warningCounts.Length); - Array.Clear(ws.warningSignals, 0, ws.warningSignalCount); - - ws.warningSignalCount = packet.SignalCount; - for (int i = 0; i < packet.SignalCount; i++) - { - int signalId = packet.Signals[i]; - ws.warningSignals[i] = signalId; - ws.warningCounts[signalId] = packet.Counts[i]; - } + var ws = GameMain.data.warningSystem; + Array.Clear(ws.warningCounts, 0, ws.warningCounts.Length); + Array.Clear(ws.warningSignals, 0, ws.warningSignalCount); - Multiplayer.Session.Warning.TickSignal = packet.Tick; + ws.warningSignalCount = packet.SignalCount; + for (var i = 0; i < packet.SignalCount; i++) + { + var signalId = packet.Signals[i]; + ws.warningSignals[i] = signalId; + ws.warningCounts[signalId] = packet.Counts[i]; } + + Multiplayer.Session.Warning.TickSignal = packet.Tick; } } diff --git a/NebulaNetwork/PlayerManager.cs b/NebulaNetwork/PlayerManager.cs index 7615bc28b..dbbc910d0 100644 --- a/NebulaNetwork/PlayerManager.cs +++ b/NebulaNetwork/PlayerManager.cs @@ -1,455 +1,461 @@ -using NebulaAPI; +#region + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using NebulaAPI; using NebulaModel; using NebulaModel.DataStructures; using NebulaModel.Logger; using NebulaModel.Networking; -using NebulaModel.Packets.GameHistory; using NebulaModel.Packets.Players; using NebulaModel.Packets.Session; using NebulaNetwork.PacketProcessors.Players; using NebulaWorld; using NebulaWorld.SocialIntegration; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -namespace NebulaNetwork +#endregion + +namespace NebulaNetwork; + +public class PlayerManager : IPlayerManager { - public class PlayerManager : IPlayerManager + private readonly ThreadSafe threadSafe = new(); + private int highestPlayerID; + + public Locker GetPendingPlayers(out Dictionary pendingPlayers) { - [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "TBD")] - private sealed class ThreadSafe - { - internal readonly Dictionary pendingPlayers = new Dictionary(); - internal readonly Dictionary syncingPlayers = new Dictionary(); - internal readonly Dictionary connectedPlayers = new Dictionary(); - internal readonly Dictionary savedPlayerData = new Dictionary(); - internal readonly Queue availablePlayerIds = new Queue(); - } + return threadSafe.pendingPlayers.GetLocked(out pendingPlayers); + } - private readonly ThreadSafe threadSafe = new ThreadSafe(); - private int highestPlayerID = 0; + public Locker GetSyncingPlayers(out Dictionary syncingPlayers) + { + return threadSafe.syncingPlayers.GetLocked(out syncingPlayers); + } - public Locker GetPendingPlayers(out Dictionary pendingPlayers) - { - return threadSafe.pendingPlayers.GetLocked(out pendingPlayers); - } + public Locker GetConnectedPlayers(out Dictionary connectedPlayers) + { + return threadSafe.connectedPlayers.GetLocked(out connectedPlayers); + } - public Locker GetSyncingPlayers(out Dictionary syncingPlayers) - { - return threadSafe.syncingPlayers.GetLocked(out syncingPlayers); - } + public Locker GetSavedPlayerData(out Dictionary savedPlayerData) + { + return threadSafe.savedPlayerData.GetLocked(out savedPlayerData); + } - public Locker GetConnectedPlayers(out Dictionary connectedPlayers) + public IPlayerData[] GetAllPlayerDataIncludingHost() + { + using (GetConnectedPlayers(out var connectedPlayers)) { - return threadSafe.connectedPlayers.GetLocked(out connectedPlayers); - } + var i = 0; + IPlayerData[] result; + if (Multiplayer.IsDedicated) + { + // If host is dedicated server, don't include it + result = new IPlayerData[connectedPlayers.Count]; + } + else + { + result = new IPlayerData[1 + connectedPlayers.Count]; + result[i++] = Multiplayer.Session.LocalPlayer.Data; + } + foreach (var kvp in connectedPlayers) + { + result[i++] = kvp.Value.Data; + } - public Locker GetSavedPlayerData(out Dictionary savedPlayerData) - { - return threadSafe.savedPlayerData.GetLocked(out savedPlayerData); + return result; } + } - public IPlayerData[] GetAllPlayerDataIncludingHost() + public INebulaPlayer GetPlayer(INebulaConnection conn) + { + using (GetConnectedPlayers(out var connectedPlayers)) { - using (GetConnectedPlayers(out Dictionary connectedPlayers)) + if (connectedPlayers.TryGetValue(conn, out var player)) { - int i = 0; - IPlayerData[] result; - if (Multiplayer.IsDedicated) - { - // If host is dedicated server, don't include it - result = new IPlayerData[connectedPlayers.Count]; - } - else - { - result = new IPlayerData[1 + connectedPlayers.Count]; - result[i++] = Multiplayer.Session.LocalPlayer.Data; - } - foreach (KeyValuePair kvp in connectedPlayers) - { - result[i++] = kvp.Value.Data; - } - - return result; + return player; } } - public INebulaPlayer GetPlayer(INebulaConnection conn) + return null; + } + + public INebulaPlayer GetPlayerById(ushort playerId) + { + INebulaPlayer player = null; + using (GetConnectedPlayers(out var connectedPlayers)) { - using (GetConnectedPlayers(out Dictionary connectedPlayers)) + if ((player = connectedPlayers.Values.FirstOrDefault(plr => plr.Id == playerId)) != null) { - if (connectedPlayers.TryGetValue(conn, out INebulaPlayer player)) - { - return player; - } + return player; } - - return null; } - - public INebulaPlayer GetPlayerById(ushort playerId) + using (GetSyncingPlayers(out var syncingPlayers)) { - INebulaPlayer player = null; - using (GetConnectedPlayers(out Dictionary connectedPlayers)) + if ((player = syncingPlayers.Values.FirstOrDefault(plr => plr.Id == playerId)) != null) { - if ((player = connectedPlayers.Values.FirstOrDefault(plr => plr.Id == playerId)) != null) - { - return player; - } - } - using (GetSyncingPlayers(out Dictionary syncingPlayers)) - { - if ((player = syncingPlayers.Values.FirstOrDefault(plr => plr.Id == playerId)) != null) - { - return player; - } + return player; } - using (GetPendingPlayers(out Dictionary pendingPlayers)) + } + using (GetPendingPlayers(out var pendingPlayers)) + { + if ((player = pendingPlayers.Values.FirstOrDefault(plr => plr.Id == playerId)) != null) { - if ((player = pendingPlayers.Values.FirstOrDefault(plr => plr.Id == playerId)) != null) - { - return player; - } + return player; } - return null; } + return null; + } - public INebulaPlayer GetConnectedPlayerByUsername(string username) + public INebulaPlayer GetConnectedPlayerByUsername(string username) + { + using (GetConnectedPlayers(out var connectedPlayers)) { - using (GetConnectedPlayers(out Dictionary connectedPlayers)) - { - return connectedPlayers.Values - .FirstOrDefault(plr => plr.Data != null && string.Equals(plr.Data.Username, username, StringComparison.InvariantCultureIgnoreCase)); - } + return connectedPlayers.Values + .FirstOrDefault(plr => + plr.Data != null && + string.Equals(plr.Data.Username, username, StringComparison.InvariantCultureIgnoreCase)); } + } - public INebulaPlayer GetSyncingPlayer(INebulaConnection conn) + public INebulaPlayer GetSyncingPlayer(INebulaConnection conn) + { + using (GetSyncingPlayers(out var syncingPlayers)) { - using (GetSyncingPlayers(out Dictionary syncingPlayers)) + if (syncingPlayers.TryGetValue(conn, out var player)) { - if (syncingPlayers.TryGetValue(conn, out INebulaPlayer player)) - { - return player; - } + return player; } - - return null; } - public void SendPacketToAllPlayers(T packet) where T : class, new() + return null; + } + + public void SendPacketToAllPlayers(T packet) where T : class, new() + { + using (GetConnectedPlayers(out var connectedPlayers)) { - using (GetConnectedPlayers(out Dictionary connectedPlayers)) + foreach (var kvp in connectedPlayers) { - foreach (KeyValuePair kvp in connectedPlayers) - { - INebulaPlayer player = kvp.Value; - player.SendPacket(packet); - } + var player = kvp.Value; + player.SendPacket(packet); } - } + } - public void SendPacketToLocalStar(T packet) where T : class, new() + public void SendPacketToLocalStar(T packet) where T : class, new() + { + using (GetConnectedPlayers(out var connectedPlayers)) { - using (GetConnectedPlayers(out Dictionary connectedPlayers)) + foreach (var kvp in connectedPlayers) { - foreach (KeyValuePair kvp in connectedPlayers) + var player = kvp.Value; + if (player.Data.LocalStarId == GameMain.data.localStar?.id) { - INebulaPlayer player = kvp.Value; - if (player.Data.LocalStarId == GameMain.data.localStar?.id) - { - player.SendPacket(packet); - } + player.SendPacket(packet); } } } + } - public void SendPacketToLocalPlanet(T packet) where T : class, new() + public void SendPacketToLocalPlanet(T packet) where T : class, new() + { + using (GetConnectedPlayers(out var connectedPlayers)) { - using (GetConnectedPlayers(out Dictionary connectedPlayers)) + foreach (var kvp in connectedPlayers) { - foreach (KeyValuePair kvp in connectedPlayers) + var player = kvp.Value; + if (player.Data.LocalPlanetId == GameMain.data.mainPlayer.planetId) { - INebulaPlayer player = kvp.Value; - if (player.Data.LocalPlanetId == GameMain.data.mainPlayer.planetId) - { - player.SendPacket(packet); - } + player.SendPacket(packet); } } } + } - public void SendPacketToPlanet(T packet, int planetId) where T : class, new() + public void SendPacketToPlanet(T packet, int planetId) where T : class, new() + { + using (GetConnectedPlayers(out var connectedPlayers)) { - using (GetConnectedPlayers(out Dictionary connectedPlayers)) + foreach (var kvp in connectedPlayers) { - foreach (KeyValuePair kvp in connectedPlayers) + var player = kvp.Value; + if (player.Data.LocalPlanetId == planetId) { - INebulaPlayer player = kvp.Value; - if (player.Data.LocalPlanetId == planetId) - { - player.SendPacket(packet); - } + player.SendPacket(packet); } } } + } - public void SendPacketToStar(T packet, int starId) where T : class, new() + public void SendPacketToStar(T packet, int starId) where T : class, new() + { + using (GetConnectedPlayers(out var connectedPlayers)) { - using (GetConnectedPlayers(out Dictionary connectedPlayers)) + foreach (var kvp in connectedPlayers) { - foreach (KeyValuePair kvp in connectedPlayers) + var player = kvp.Value; + if (player.Data.LocalStarId == starId) { - INebulaPlayer player = kvp.Value; - if (player.Data.LocalStarId == starId) - { - player.SendPacket(packet); - } + player.SendPacket(packet); } } } + } - public void SendPacketToStarExcept(T packet, int starId, INebulaConnection exclude) where T : class, new() + public void SendPacketToStarExcept(T packet, int starId, INebulaConnection exclude) where T : class, new() + { + using (GetConnectedPlayers(out var connectedPlayers)) { - using (GetConnectedPlayers(out Dictionary connectedPlayers)) + foreach (var kvp in connectedPlayers) { - foreach (KeyValuePair kvp in connectedPlayers) + var player = kvp.Value; + if (player.Data.LocalStarId == starId && player != GetPlayer(exclude)) { - INebulaPlayer player = kvp.Value; - if (player.Data.LocalStarId == starId && player != GetPlayer(exclude)) - { - player.SendPacket(packet); - } + player.SendPacket(packet); } } } + } - public void SendRawPacketToStar(byte[] rawPacket, int starId, INebulaConnection sender) + public void SendRawPacketToStar(byte[] rawPacket, int starId, INebulaConnection sender) + { + using (GetConnectedPlayers(out var connectedPlayers)) { - using (GetConnectedPlayers(out Dictionary connectedPlayers)) + foreach (var kvp in connectedPlayers) { - foreach (KeyValuePair kvp in connectedPlayers) + var player = kvp.Value; + if (player.Data.LocalStarId == starId && !player.Connection.Equals(sender)) { - INebulaPlayer player = kvp.Value; - if (player.Data.LocalStarId == starId && !player.Connection.Equals(sender)) - { - player.Connection.SendRawPacket(rawPacket); - } + player.Connection.SendRawPacket(rawPacket); } } } + } - public void SendRawPacketToPlanet(byte[] rawPacket, int planetId, INebulaConnection sender) + public void SendRawPacketToPlanet(byte[] rawPacket, int planetId, INebulaConnection sender) + { + using (GetConnectedPlayers(out var connectedPlayers)) { - using (GetConnectedPlayers(out Dictionary connectedPlayers)) + foreach (var kvp in connectedPlayers) { - foreach (KeyValuePair kvp in connectedPlayers) + var player = kvp.Value; + if (player.Data.LocalPlanetId == planetId && !player.Connection.Equals(sender)) { - INebulaPlayer player = kvp.Value; - if (player.Data.LocalPlanetId == planetId && !player.Connection.Equals(sender)) - { - player.Connection.SendRawPacket(rawPacket); - } + player.Connection.SendRawPacket(rawPacket); } } } + } - public void SendPacketToOtherPlayers(T packet, INebulaConnection exclude) where T : class, new() + public void SendPacketToOtherPlayers(T packet, INebulaConnection exclude) where T : class, new() + { + using (GetConnectedPlayers(out var connectedPlayers)) { - using (GetConnectedPlayers(out Dictionary connectedPlayers)) + foreach (var kvp in connectedPlayers) { - foreach (KeyValuePair kvp in connectedPlayers) + var player = kvp.Value; + if (!player.Connection.Equals(exclude)) { - INebulaPlayer player = kvp.Value; - if (!player.Connection.Equals(exclude)) - { - player.SendPacket(packet); - } + player.SendPacket(packet); } } } + } - public void SendPacketToOtherPlayers(T packet, INebulaPlayer sender) where T : class, new() + public void SendPacketToOtherPlayers(T packet, INebulaPlayer sender) where T : class, new() + { + using (GetConnectedPlayers(out var connectedPlayers)) { - using (GetConnectedPlayers(out Dictionary connectedPlayers)) + foreach (var kvp in connectedPlayers) { - foreach (KeyValuePair kvp in connectedPlayers) + var player = kvp.Value; + if (player != sender) { - INebulaPlayer player = kvp.Value; - if (player != sender) - { - player.SendPacket(packet); - } + player.SendPacket(packet); } } } + } + + public INebulaPlayer PlayerConnected(INebulaConnection conn) + { + // Generate new data for the player + var playerId = GetNextAvailablePlayerId(); + + var birthPlanet = GameMain.galaxy.PlanetById(GameMain.galaxy.birthPlanetId); + var playerData = new PlayerData(playerId, -1, + position: new Double3(birthPlanet.uPosition.x, birthPlanet.uPosition.y, birthPlanet.uPosition.z)); - public INebulaPlayer PlayerConnected(INebulaConnection conn) + INebulaPlayer newPlayer = new NebulaPlayer((NebulaConnection)conn, playerData); + using (GetPendingPlayers(out var pendingPlayers)) { - // Generate new data for the player - ushort playerId = GetNextAvailablePlayerId(); + pendingPlayers.Add(conn, newPlayer); + } - PlanetData birthPlanet = GameMain.galaxy.PlanetById(GameMain.galaxy.birthPlanetId); - PlayerData playerData = new PlayerData(playerId, -1, position: new Double3(birthPlanet.uPosition.x, birthPlanet.uPosition.y, birthPlanet.uPosition.z)); + return newPlayer; + } - INebulaPlayer newPlayer = new NebulaPlayer((NebulaConnection)conn, playerData); - using (GetPendingPlayers(out Dictionary pendingPlayers)) + public void PlayerDisconnected(INebulaConnection conn) + { + INebulaPlayer player = null; + var playerWasSyncing = false; + var playerWasConnected = false; + var syncCount = -1; + Multiplayer.Session.NumPlayers -= 1; + DiscordManager.UpdateRichPresence(); + + using (GetConnectedPlayers(out var connectedPlayers)) + { + if (connectedPlayers.TryGetValue(conn, out var removingPlayer)) { - pendingPlayers.Add(conn, newPlayer); + player = removingPlayer; + connectedPlayers.Remove(conn); + playerWasConnected = true; } - - return newPlayer; } - public void PlayerDisconnected(INebulaConnection conn) + using (GetPendingPlayers(out var pendingPlayers)) { - INebulaPlayer player = null; - bool playerWasSyncing = false; - bool playerWasConnected = false; - int syncCount = -1; - Multiplayer.Session.NumPlayers -= 1; - DiscordManager.UpdateRichPresence(); - - using (GetConnectedPlayers(out Dictionary connectedPlayers)) + if (pendingPlayers.TryGetValue(conn, out var removingPlayer)) { - if (connectedPlayers.TryGetValue(conn, out INebulaPlayer removingPlayer)) - { - player = removingPlayer; - connectedPlayers.Remove(conn); - playerWasConnected = true; - } + player = removingPlayer; + pendingPlayers.Remove(conn); } + } - using (GetPendingPlayers(out Dictionary pendingPlayers)) + using (GetSyncingPlayers(out var syncingPlayers)) + { + if (syncingPlayers.TryGetValue(conn, out var removingPlayer)) { - if (pendingPlayers.TryGetValue(conn, out INebulaPlayer removingPlayer)) - { - player = removingPlayer; - pendingPlayers.Remove(conn); - } + player = removingPlayer; + syncingPlayers.Remove(conn); + playerWasSyncing = true; + syncCount = syncingPlayers.Count; } + } - using (GetSyncingPlayers(out Dictionary syncingPlayers)) + if (player != null) + { + SendPacketToOtherPlayers(new PlayerDisconnected(player.Id, Multiplayer.Session.NumPlayers), player); + // For sync completed player who triggered OnPlayerJoinedGame() before + if (playerWasConnected && !playerWasSyncing) { - if (syncingPlayers.TryGetValue(conn, out INebulaPlayer removingPlayer)) - { - player = removingPlayer; - syncingPlayers.Remove(conn); - playerWasSyncing = true; - syncCount = syncingPlayers.Count; - } + Multiplayer.Session.World.OnPlayerLeftGame(player); } - - if (player != null) + using (threadSafe.availablePlayerIds.GetLocked(out var availablePlayerIds)) { - SendPacketToOtherPlayers(new PlayerDisconnected(player.Id, Multiplayer.Session.NumPlayers), player); - // For sync completed player who triggered OnPlayerJoinedGame() before - if (playerWasConnected && !playerWasSyncing) - { - Multiplayer.Session.World.OnPlayerLeftGame(player); - } - using (threadSafe.availablePlayerIds.GetLocked(out Queue availablePlayerIds)) - { - availablePlayerIds.Enqueue(player.Id); - } - Multiplayer.Session.Statistics.UnRegisterPlayer(player.Id); - Multiplayer.Session.DysonSpheres.UnRegisterPlayer(conn); + availablePlayerIds.Enqueue(player.Id); + } + Multiplayer.Session.Statistics.UnRegisterPlayer(player.Id); + Multiplayer.Session.DysonSpheres.UnRegisterPlayer(conn); - //Notify players about queued building plans for drones - int[] DronePlans = Multiplayer.Session.Drones.GetPlayerDronePlans(player.Id); - if (DronePlans != null && DronePlans.Length > 0 && player.Data.LocalPlanetId > 0) + //Notify players about queued building plans for drones + int[] DronePlans = Multiplayer.Session.Drones.GetPlayerDronePlans(player.Id); + if (DronePlans != null && DronePlans.Length > 0 && player.Data.LocalPlanetId > 0) + { + Multiplayer.Session.Network.SendPacketToPlanet(new RemoveDroneOrdersPacket(DronePlans), + player.Data.LocalPlanetId); + //Remove it also from host queue, if host is on the same planet + if (GameMain.mainPlayer.planetId == player.Data.LocalPlanetId) { - Multiplayer.Session.Network.SendPacketToPlanet(new RemoveDroneOrdersPacket(DronePlans), player.Data.LocalPlanetId); - //Remove it also from host queue, if host is on the same planet - if (GameMain.mainPlayer.planetId == player.Data.LocalPlanetId) + for (var i = 0; i < DronePlans.Length; i++) { - for (int i = 0; i < DronePlans.Length; i++) - { - GameMain.mainPlayer.mecha.droneLogic.serving.Remove(DronePlans[i]); - } + GameMain.mainPlayer.mecha.droneLogic.serving.Remove(DronePlans[i]); } } - - if (playerWasSyncing && syncCount == 0) - { - Multiplayer.Session.Network.SendPacket(new SyncComplete()); - Multiplayer.Session.World.OnAllPlayersSyncCompleted(); - } } - else + + if (playerWasSyncing && syncCount == 0) { - Log.Warn($"PlayerDisconnected NOT CALLED!"); + Multiplayer.Session.Network.SendPacket(new SyncComplete()); + Multiplayer.Session.World.OnAllPlayersSyncCompleted(); + } + } + else + { + Log.Warn("PlayerDisconnected NOT CALLED!"); - if (Config.Options.SyncSoil) + if (Config.Options.SyncSoil) + { + // now we need to recalculate the current sand amount :C + GameMain.mainPlayer.sandCount = Multiplayer.Session.LocalPlayer.Data.Mecha.SandCount; + using (GetConnectedPlayers(out var connectedPlayers)) { - // now we need to recalculate the current sand amount :C - GameMain.mainPlayer.sandCount = Multiplayer.Session.LocalPlayer.Data.Mecha.SandCount; - using (GetConnectedPlayers(out Dictionary connectedPlayers)) + foreach (var entry in connectedPlayers) { - foreach (KeyValuePair entry in connectedPlayers) - { - GameMain.mainPlayer.sandCount += entry.Value.Data.Mecha.SandCount; - } + GameMain.mainPlayer.sandCount += entry.Value.Data.Mecha.SandCount; } - UIRoot.instance.uiGame.OnSandCountChanged(GameMain.mainPlayer.sandCount, GameMain.mainPlayer.sandCount - Multiplayer.Session.LocalPlayer.Data.Mecha.SandCount); - Multiplayer.Session.Network.SendPacket(new PlayerSandCount(GameMain.mainPlayer.sandCount)); } + UIRoot.instance.uiGame.OnSandCountChanged(GameMain.mainPlayer.sandCount, + GameMain.mainPlayer.sandCount - Multiplayer.Session.LocalPlayer.Data.Mecha.SandCount); + Multiplayer.Session.Network.SendPacket(new PlayerSandCount(GameMain.mainPlayer.sandCount)); } } + } - public ushort GetNextAvailablePlayerId() + public ushort GetNextAvailablePlayerId() + { + using (threadSafe.availablePlayerIds.GetLocked(out var availablePlayerIds)) { - using (threadSafe.availablePlayerIds.GetLocked(out Queue availablePlayerIds)) + if (availablePlayerIds.Count > 0) { - if (availablePlayerIds.Count > 0) - { - return availablePlayerIds.Dequeue(); - } + return availablePlayerIds.Dequeue(); } - - return (ushort)Interlocked.Increment(ref highestPlayerID); // this is truncated to ushort.MaxValue } - public void UpdateMechaData(IMechaData mechaData, INebulaConnection conn) + return (ushort)Interlocked.Increment(ref highestPlayerID); // this is truncated to ushort.MaxValue + } + + public void UpdateMechaData(IMechaData mechaData, INebulaConnection conn) + { + if (mechaData == null) { - if (mechaData == null) - { - return; - } - using (GetConnectedPlayers(out Dictionary connectedPlayers)) + return; + } + using (GetConnectedPlayers(out var connectedPlayers)) + { + if (connectedPlayers.TryGetValue(conn, out var player)) { - if (connectedPlayers.TryGetValue(conn, out INebulaPlayer player)) + //Find correct player for data to update, preserve sand count if syncing is enabled + var sandCount = player.Data.Mecha.SandCount; + player.Data.Mecha = mechaData; + if (Config.Options.SyncSoil) { - //Find correct player for data to update, preserve sand count if syncing is enabled - int sandCount = player.Data.Mecha.SandCount; - player.Data.Mecha = mechaData; - if (Config.Options.SyncSoil) - { - player.Data.Mecha.SandCount = sandCount; - } + player.Data.Mecha.SandCount = sandCount; } } } + } - // add or take sand evenly from each connected player while soil is synced - public void UpdateSyncedSandCount(int deltaSandCount) + // add or take sand evenly from each connected player while soil is synced + public void UpdateSyncedSandCount(int deltaSandCount) + { + using (GetConnectedPlayers(out var connectedPlayers)) { - using (GetConnectedPlayers(out Dictionary connectedPlayers)) + foreach (var entry in connectedPlayers) { - foreach(KeyValuePair entry in connectedPlayers) + entry.Value.Data.Mecha.SandCount += deltaSandCount / (connectedPlayers.Count + 1); + // dont be too picky here, a little bit more or less sand is ignorable i guess + if (entry.Value.Data.Mecha.SandCount < 0) { - entry.Value.Data.Mecha.SandCount += deltaSandCount / (connectedPlayers.Count + 1); - // dont be too picky here, a little bit more or less sand is ignorable i guess - if(entry.Value.Data.Mecha.SandCount < 0) - { - entry.Value.Data.Mecha.SandCount = 0; - } + entry.Value.Data.Mecha.SandCount = 0; } - Multiplayer.Session.LocalPlayer.Data.Mecha.SandCount += deltaSandCount / (connectedPlayers.Count + 1); } + Multiplayer.Session.LocalPlayer.Data.Mecha.SandCount += deltaSandCount / (connectedPlayers.Count + 1); } } -} + [SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "TBD")] + private sealed class ThreadSafe + { + internal readonly Queue availablePlayerIds = new(); + internal readonly Dictionary connectedPlayers = new(); + internal readonly Dictionary pendingPlayers = new(); + internal readonly Dictionary savedPlayerData = new(); + internal readonly Dictionary syncingPlayers = new(); + } +} diff --git a/NebulaNetwork/SaveManager.cs b/NebulaNetwork/SaveManager.cs index 9029de4c2..46d729ed5 100644 --- a/NebulaNetwork/SaveManager.cs +++ b/NebulaNetwork/SaveManager.cs @@ -1,154 +1,157 @@ -using NebulaAPI; +#region + +using System; +using System.IO; +using NebulaAPI; using NebulaModel.DataStructures; using NebulaModel.Logger; using NebulaModel.Networking.Serialization; using NebulaModel.Utils; using NebulaWorld; -using System.Collections.Generic; -using System.IO; -namespace NebulaNetwork +#endregion + +namespace NebulaNetwork; + +public class SaveManager { - public class SaveManager + private const string FILE_EXTENSION = ".server"; + private const ushort REVISION = 7; + + public static void SaveServerData(string saveName) { - private const string FILE_EXTENSION = ".server"; - private const ushort REVISION = 7; + var path = GameConfig.gameSaveFolder + saveName + FILE_EXTENSION; + IPlayerManager playerManager = Multiplayer.Session.Network.PlayerManager; + var netDataWriter = new NetDataWriter(); + netDataWriter.Put("REV"); + netDataWriter.Put(REVISION); - public static void SaveServerData(string saveName) + using (playerManager.GetSavedPlayerData(out var savedPlayerData)) { - string path = GameConfig.gameSaveFolder + saveName + FILE_EXTENSION; - IPlayerManager playerManager = Multiplayer.Session.Network.PlayerManager; - NetDataWriter netDataWriter = new NetDataWriter(); - netDataWriter.Put("REV"); - netDataWriter.Put(REVISION); - - using (playerManager.GetSavedPlayerData(out Dictionary savedPlayerData)) + netDataWriter.Put(savedPlayerData.Count + 1); + //Add data about all players + foreach (var data in savedPlayerData) { - netDataWriter.Put(savedPlayerData.Count + 1); - //Add data about all players - foreach (KeyValuePair data in savedPlayerData) - { - string hash = data.Key; - netDataWriter.Put(hash); - data.Value.Serialize(netDataWriter); - } - Log.Info($"Saving server data to {saveName + FILE_EXTENSION}, Revision:{REVISION} PlayerCount:{savedPlayerData.Count}"); + var hash = data.Key; + netDataWriter.Put(hash); + data.Value.Serialize(netDataWriter); } + Log.Info( + $"Saving server data to {saveName + FILE_EXTENSION}, Revision:{REVISION} PlayerCount:{savedPlayerData.Count}"); + } - //Add host's data - netDataWriter.Put(CryptoUtils.GetCurrentUserPublicKeyHash()); - Multiplayer.Session.LocalPlayer.Data.Serialize(netDataWriter); + //Add host's data + netDataWriter.Put(CryptoUtils.GetCurrentUserPublicKeyHash()); + Multiplayer.Session.LocalPlayer.Data.Serialize(netDataWriter); - File.WriteAllBytes(path, netDataWriter.Data); + File.WriteAllBytes(path, netDataWriter.Data); - // If the saveName is the autoSave, we need to rotate the server autosave file. - if (saveName == GameSave.AutoSaveTmp) - { - HandleAutoSave(); - } + // If the saveName is the autoSave, we need to rotate the server autosave file. + if (saveName == GameSave.AutoSaveTmp) + { + HandleAutoSave(); } + } - private static void HandleAutoSave() - { - string str1 = GameConfig.gameSaveFolder + GameSave.AutoSaveTmp + FILE_EXTENSION; - string str2 = GameConfig.gameSaveFolder + GameSave.AutoSave0 + FILE_EXTENSION; - string str3 = GameConfig.gameSaveFolder + GameSave.AutoSave1 + FILE_EXTENSION; - string str4 = GameConfig.gameSaveFolder + GameSave.AutoSave2 + FILE_EXTENSION; - string str5 = GameConfig.gameSaveFolder + GameSave.AutoSave3 + FILE_EXTENSION; + private static void HandleAutoSave() + { + var str1 = GameConfig.gameSaveFolder + GameSave.AutoSaveTmp + FILE_EXTENSION; + var str2 = GameConfig.gameSaveFolder + GameSave.AutoSave0 + FILE_EXTENSION; + var str3 = GameConfig.gameSaveFolder + GameSave.AutoSave1 + FILE_EXTENSION; + var str4 = GameConfig.gameSaveFolder + GameSave.AutoSave2 + FILE_EXTENSION; + var str5 = GameConfig.gameSaveFolder + GameSave.AutoSave3 + FILE_EXTENSION; - if (File.Exists(str1)) + if (File.Exists(str1)) + { + if (File.Exists(str5)) { - if (File.Exists(str5)) - { - File.Delete(str5); - } - - if (File.Exists(str4)) - { - File.Move(str4, str5); - } + File.Delete(str5); + } - if (File.Exists(str3)) - { - File.Move(str3, str4); - } + if (File.Exists(str4)) + { + File.Move(str4, str5); + } - if (File.Exists(str2)) - { - File.Move(str2, str3); - } + if (File.Exists(str3)) + { + File.Move(str3, str4); + } - File.Move(str1, str2); + if (File.Exists(str2)) + { + File.Move(str2, str3); } + + File.Move(str1, str2); } + } + + public static void LoadServerData() + { + var path = GameConfig.gameSaveFolder + DSPGame.LoadFile + FILE_EXTENSION; - public static void LoadServerData() + IPlayerManager playerManager = Multiplayer.Session.Network.PlayerManager; + if (!File.Exists(path) || playerManager == null) { - string path = GameConfig.gameSaveFolder + DSPGame.LoadFile + FILE_EXTENSION; + return; + } - IPlayerManager playerManager = Multiplayer.Session.Network.PlayerManager; - if (!File.Exists(path) || playerManager == null) + var source = File.ReadAllBytes(path); + var netDataReader = new NetDataReader(source); + ushort revision = 0; + try + { + var revString = netDataReader.GetString(); + if (revString != "REV") { - return; + throw new Exception(); } - byte[] source = File.ReadAllBytes(path); - NetDataReader netDataReader = new NetDataReader(source); - ushort revision = 0; - try + revision = netDataReader.GetUShort(); + Log.Info($"Loading server data revision {revision} (Latest {REVISION})"); + if (revision != REVISION) { - string revString = netDataReader.GetString(); - if (revString != "REV") + // Supported revision: 5~7 + if (revision < 5 || revision > REVISION) { - throw new System.Exception(); - } - - revision = netDataReader.GetUShort(); - Log.Info($"Loading server data revision {revision} (Latest {REVISION})"); - if (revision != REVISION) - { - // Supported revision: 5~7 - if (revision < 5 || revision > REVISION) - { - throw new System.Exception(); - } + throw new Exception(); } } - catch (System.Exception) - { - Log.Warn("Skipping server data from unsupported Nebula version..."); - return; - } + } + catch (Exception) + { + Log.Warn("Skipping server data from unsupported Nebula version..."); + return; + } - int playerNum = netDataReader.GetInt(); + var playerNum = netDataReader.GetInt(); - using (playerManager.GetSavedPlayerData(out Dictionary savedPlayerData)) + using (playerManager.GetSavedPlayerData(out var savedPlayerData)) + { + for (var i = 0; i < playerNum; i++) { - for (int i = 0; i < playerNum; i++) + var hash = netDataReader.GetString(); + PlayerData playerData = null; + if (revision == REVISION) { - string hash = netDataReader.GetString(); - PlayerData playerData = null; - if (revision == REVISION) - { - playerData = netDataReader.Get(); - } - else if (revision >= 5) - { - playerData = new PlayerData(); - playerData.Import(netDataReader, revision); - } - - if (!savedPlayerData.ContainsKey(hash) && playerData != null) - { - savedPlayerData.Add(hash, playerData); - } - else if(playerData == null) - { - Log.Warn($"could not load player data from unsupported save file revision {revision}"); - } + playerData = netDataReader.Get(); + } + else if (revision >= 5) + { + playerData = new PlayerData(); + playerData.Import(netDataReader, revision); } - } + if (!savedPlayerData.ContainsKey(hash) && playerData != null) + { + savedPlayerData.Add(hash, playerData); + } + else if (playerData == null) + { + Log.Warn($"could not load player data from unsupported save file revision {revision}"); + } + } } } -} \ No newline at end of file +} diff --git a/NebulaNetwork/Server.cs b/NebulaNetwork/Server.cs index 627ed9235..420ea1966 100644 --- a/NebulaNetwork/Server.cs +++ b/NebulaNetwork/Server.cs @@ -1,4 +1,11 @@ -using HarmonyLib; +#region + +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Sockets; +using System.Threading.Tasks; +using HarmonyLib; using NebulaAPI; using NebulaModel; using NebulaModel.DataStructures; @@ -7,363 +14,373 @@ using NebulaModel.Networking.Serialization; using NebulaModel.Packets.GameHistory; using NebulaModel.Utils; +using NebulaNetwork.Ngrok; using NebulaWorld; -using Open.Nat; using NebulaWorld.SocialIntegration; -using System.Collections.Generic; -using System.Net.Sockets; -using System.Reflection; -using System.Threading.Tasks; +using Open.Nat; using UnityEngine; using WebSocketSharp; -using WebSocketSharp.Net; using WebSocketSharp.Server; +using AuthenticationSchemes = WebSocketSharp.Net.AuthenticationSchemes; +using NetworkCredential = WebSocketSharp.Net.NetworkCredential; -namespace NebulaNetwork -{ - public class Server : NetworkProvider, IServer - { - private const float GAME_RESEARCH_UPDATE_INTERVAL = 2; - private const float STATISTICS_UPDATE_INTERVAL = 1; - private const float LAUNCH_UPDATE_INTERVAL = 4; - private const float DYSONSPHERE_UPDATE_INTERVAL = 2; - private const float WARNING_UPDATE_INTERVAL = 1; - - private float gameResearchHashUpdateTimer = 0; - private float productionStatisticsUpdateTimer = 0; - private float dysonLaunchUpateTimer = 1; - private float dysonSphereUpdateTimer = 0; - private float warningUpdateTimer = 0; - - private WebSocketServer socket; - private Ngrok.NgrokManager ngrokManager; - - private readonly ushort port; - private readonly bool loadSaveFile; - - public ushort Port => port; - public string NgrokAddress => ngrokManager.NgrokAddress; - public bool NgrokActive => ngrokManager.IsNgrokActive(); - public bool NgrokEnabled => ngrokManager.NgrokEnabled; - public string NgrokLastErrorCode => ngrokManager.NgrokLastErrorCode; - - public Server(ushort port, bool loadSaveFile = false) : base(new PlayerManager()) - { - this.port = port; - this.loadSaveFile = loadSaveFile; - } +#endregion - public override void Start() - { - if (loadSaveFile) - { - SaveManager.LoadServerData(); - } +namespace NebulaNetwork; - foreach (Assembly assembly in AssembliesUtils.GetNebulaAssemblies()) - { - PacketUtils.RegisterAllPacketNestedTypesInAssembly(assembly, PacketProcessor); - } - PacketUtils.RegisterAllPacketProcessorsInCallingAssembly(PacketProcessor, true); +public class Server : NetworkProvider, IServer +{ + private const float GAME_RESEARCH_UPDATE_INTERVAL = 2; + private const float STATISTICS_UPDATE_INTERVAL = 1; + private const float LAUNCH_UPDATE_INTERVAL = 4; + private const float DYSONSPHERE_UPDATE_INTERVAL = 2; + private const float WARNING_UPDATE_INTERVAL = 1; + private readonly bool loadSaveFile; - foreach (Assembly assembly in NebulaModAPI.TargetAssemblies) - { - PacketUtils.RegisterAllPacketNestedTypesInAssembly(assembly, PacketProcessor); - PacketUtils.RegisterAllPacketProcessorsInAssembly(assembly, PacketProcessor, true); - } -#if DEBUG - PacketProcessor.SimulateLatency = true; -#endif + private float dysonLaunchUpateTimer = 1; + private float dysonSphereUpdateTimer; - if (Config.Options.EnableUPnpOrPmpSupport) - { - Task.Run(async () => { - var discoverer = new NatDiscoverer(); - try - { - var device = await discoverer.DiscoverDeviceAsync(); - await device.CreatePortMapAsync(new Mapping(Protocol.Tcp, port, port, "DSP nebula")); - Log.Info($"Successfully created UPnp or Pmp port mapping for {port}"); - } - catch (NatDeviceNotFoundException) - { - Log.WarnInform("No UPnp or Pmp compatible/enabled NAT device found".Translate()); - } - catch (MappingException) - { - Log.WarnInform("Could not create UPnp or Pmp port mapping".Translate()); - } - }); - } + private float gameResearchHashUpdateTimer; + private NgrokManager ngrokManager; + private float productionStatisticsUpdateTimer; - ngrokManager = new Ngrok.NgrokManager(port); + private WebSocketServer socket; + private float warningUpdateTimer; - socket = new WebSocketServer(System.Net.IPAddress.IPv6Any, port); - socket.Log.Level = LogLevel.Debug; - socket.Log.Output = Log.SocketOutput; - socket.AllowForwardedRequest = true; // This is required to make the websocket play nice with tunneling services like ngrok + public Server(ushort port, bool loadSaveFile = false) : base(new PlayerManager()) + { + this.Port = port; + this.loadSaveFile = loadSaveFile; + } - if (!string.IsNullOrWhiteSpace(Config.Options.ServerPassword)) - { - socket.AuthenticationSchemes = AuthenticationSchemes.Basic; - socket.UserCredentialsFinder = id => { - var name = id.Name; - - // Return user name, password, and roles. - return name == "nebula-player" - ? new NetworkCredential(name, Config.Options.ServerPassword) - : null; // If the user credentials are not found. - }; - } + public ushort Port { get; } - DisableNagleAlgorithm(socket); - WebSocketService.PacketProcessor = PacketProcessor; - WebSocketService.PlayerManager = PlayerManager; - socket.AddWebSocketService("/socket", wse => new WebSocketService()); - try - { - // Set wait time higher for high latency network - socket.WaitTime = System.TimeSpan.FromSeconds(20); - socket.KeepClean = Config.Options.CleanupInactiveSessions; - socket.Start(); - }catch(System.InvalidOperationException e) - { - InGamePopup.ShowError("Error", "An error occurred while hosting the game: ".Translate() + e.Message, "Close".Translate()); - Stop(); - Multiplayer.LeaveGame(); - return; - } + public string NgrokAddress => ngrokManager.NgrokAddress; + public bool NgrokActive => ngrokManager.IsNgrokActive(); + public bool NgrokEnabled => ngrokManager.NgrokEnabled; + public string NgrokLastErrorCode => ngrokManager.NgrokLastErrorCode; - ((LocalPlayer)Multiplayer.Session.LocalPlayer).IsHost = true; + public override void Start() + { + if (loadSaveFile) + { + SaveManager.LoadServerData(); + } - ((LocalPlayer)Multiplayer.Session.LocalPlayer).SetPlayerData(new PlayerData( - PlayerManager.GetNextAvailablePlayerId(), - GameMain.localPlanet?.id ?? -1, - !string.IsNullOrWhiteSpace(Config.Options.Nickname) ? Config.Options.Nickname : GameMain.data.account.userName), loadSaveFile); + foreach (var assembly in AssembliesUtils.GetNebulaAssemblies()) + { + PacketUtils.RegisterAllPacketNestedTypesInAssembly(assembly, PacketProcessor); + } + PacketUtils.RegisterAllPacketProcessorsInCallingAssembly(PacketProcessor, true); + foreach (var assembly in NebulaModAPI.TargetAssemblies) + { + PacketUtils.RegisterAllPacketNestedTypesInAssembly(assembly, PacketProcessor); + PacketUtils.RegisterAllPacketProcessorsInAssembly(assembly, PacketProcessor, true); + } +#if DEBUG + PacketProcessor.SimulateLatency = true; +#endif + + if (Config.Options.EnableUPnpOrPmpSupport) + { Task.Run(async () => { - if(ngrokManager.IsNgrokActive()) + var discoverer = new NatDiscoverer(); + try + { + var device = await discoverer.DiscoverDeviceAsync(); + await device.CreatePortMapAsync(new Mapping(Protocol.Tcp, Port, Port, "DSP nebula")); + Log.Info($"Successfully created UPnp or Pmp port mapping for {Port}"); + } + catch (NatDeviceNotFoundException) { - string ip = await ngrokManager.GetNgrokAddressAsync(); - DiscordManager.UpdateRichPresence(ip: ip, updateTimestamp: true); - if (Multiplayer.IsDedicated) - { - Log.Info($">> Ngrok address: {ip}"); - } + Log.WarnInform("No UPnp or Pmp compatible/enabled NAT device found".Translate()); } - else + catch (MappingException) { - DiscordManager.UpdateRichPresence(ip: $"{(Config.Options.IPConfiguration != IPUtils.IPConfiguration.IPv6 ? await IPUtils.GetWANv4Address() : string.Empty)};" + - $"{(Config.Options.IPConfiguration != IPUtils.IPConfiguration.IPv4 ? await IPUtils.GetWANv6Address() : string.Empty)};" + - $"{port}", - updateTimestamp: true); + Log.WarnInform("Could not create UPnp or Pmp port mapping".Translate()); } }); + } - try - { - NebulaModAPI.OnMultiplayerGameStarted?.Invoke(); - } - catch (System.Exception e) + ngrokManager = new NgrokManager(Port); + + socket = new WebSocketServer(IPAddress.IPv6Any, Port); + socket.Log.Level = LogLevel.Debug; + socket.Log.Output = Log.SocketOutput; + socket.AllowForwardedRequest = + true; // This is required to make the websocket play nice with tunneling services like ngrok + + if (!string.IsNullOrWhiteSpace(Config.Options.ServerPassword)) + { + socket.AuthenticationSchemes = AuthenticationSchemes.Basic; + socket.UserCredentialsFinder = id => { - Log.Error("NebulaModAPI.OnMultiplayerGameStarted error:\n" + e); - } + var name = id.Name; + + // Return user name, password, and roles. + return name == "nebula-player" + ? new NetworkCredential(name, Config.Options.ServerPassword) + : null; // If the user credentials are not found. + }; } - public override void Stop() + DisableNagleAlgorithm(socket); + WebSocketService.PacketProcessor = PacketProcessor; + WebSocketService.PlayerManager = PlayerManager; + socket.AddWebSocketService("/socket", wse => new WebSocketService()); + try + { + // Set wait time higher for high latency network + socket.WaitTime = TimeSpan.FromSeconds(20); + socket.KeepClean = Config.Options.CleanupInactiveSessions; + socket.Start(); + } + catch (InvalidOperationException e) { - socket?.Stop(); + InGamePopup.ShowError("Error", "An error occurred while hosting the game: ".Translate() + e.Message, + "Close".Translate()); + Stop(); + Multiplayer.LeaveGame(); + return; + } - ngrokManager?.StopNgrok(); + ((LocalPlayer)Multiplayer.Session.LocalPlayer).IsHost = true; - try + ((LocalPlayer)Multiplayer.Session.LocalPlayer).SetPlayerData(new PlayerData( + PlayerManager.GetNextAvailablePlayerId(), + GameMain.localPlanet?.id ?? -1, + !string.IsNullOrWhiteSpace(Config.Options.Nickname) ? Config.Options.Nickname : GameMain.data.account.userName), + loadSaveFile); + + Task.Run(async () => + { + if (ngrokManager.IsNgrokActive()) { - NebulaModAPI.OnMultiplayerGameEnded?.Invoke(); + var ip = await ngrokManager.GetNgrokAddressAsync(); + DiscordManager.UpdateRichPresence(ip, updateTimestamp: true); + if (Multiplayer.IsDedicated) + { + Log.Info($">> Ngrok address: {ip}"); + } } - catch (System.Exception e) + else { - Log.Error("NebulaModAPI.OnMultiplayerGameEnded error:\n" + e); + DiscordManager.UpdateRichPresence( + $"{(Config.Options.IPConfiguration != IPUtils.IPConfiguration.IPv6 ? await IPUtils.GetWANv4Address() : string.Empty)};" + + $"{(Config.Options.IPConfiguration != IPUtils.IPConfiguration.IPv4 ? await IPUtils.GetWANv6Address() : string.Empty)};" + + $"{Port}", + updateTimestamp: true); } - } + }); - public override void Dispose() + try { - Stop(); + NebulaModAPI.OnMultiplayerGameStarted?.Invoke(); } - - public override void SendPacket(T packet) + catch (Exception e) { - PlayerManager.SendPacketToAllPlayers(packet); + Log.Error("NebulaModAPI.OnMultiplayerGameStarted error:\n" + e); } + } - public override void SendPacketToLocalStar(T packet) - { - PlayerManager.SendPacketToLocalStar(packet); - } + public override void Stop() + { + socket?.Stop(); - public override void SendPacketToLocalPlanet(T packet) - { - PlayerManager.SendPacketToLocalPlanet(packet); - } + ngrokManager?.StopNgrok(); - public override void SendPacketToPlanet(T packet, int planetId) + try { - PlayerManager.SendPacketToPlanet(packet, planetId); + NebulaModAPI.OnMultiplayerGameEnded?.Invoke(); } - - public override void SendPacketToStar(T packet, int starId) + catch (Exception e) { - PlayerManager.SendPacketToStar(packet, starId); + Log.Error("NebulaModAPI.OnMultiplayerGameEnded error:\n" + e); } + } - public override void SendPacketExclude(T packet, INebulaConnection exclude) - { - PlayerManager.SendPacketToOtherPlayers(packet, exclude); - } + public override void Dispose() + { + Stop(); + } - public override void SendPacketToStarExclude(T packet, int starId, INebulaConnection exclude) - { - PlayerManager.SendPacketToStarExcept(packet, starId, exclude); - } + public override void SendPacket(T packet) + { + PlayerManager.SendPacketToAllPlayers(packet); + } + + public override void SendPacketToLocalStar(T packet) + { + PlayerManager.SendPacketToLocalStar(packet); + } + + public override void SendPacketToLocalPlanet(T packet) + { + PlayerManager.SendPacketToLocalPlanet(packet); + } + + public override void SendPacketToPlanet(T packet, int planetId) + { + PlayerManager.SendPacketToPlanet(packet, planetId); + } - public override void Update() + public override void SendPacketToStar(T packet, int starId) + { + PlayerManager.SendPacketToStar(packet, starId); + } + + public override void SendPacketExclude(T packet, INebulaConnection exclude) + { + PlayerManager.SendPacketToOtherPlayers(packet, exclude); + } + + public override void SendPacketToStarExclude(T packet, int starId, INebulaConnection exclude) + { + PlayerManager.SendPacketToStarExcept(packet, starId, exclude); + } + + public override void Update() + { + PacketProcessor.ProcessPacketQueue(); + + if (Multiplayer.Session.IsGameLoaded) { - PacketProcessor.ProcessPacketQueue(); + gameResearchHashUpdateTimer += Time.deltaTime; + productionStatisticsUpdateTimer += Time.deltaTime; + dysonLaunchUpateTimer += Time.deltaTime; + dysonSphereUpdateTimer += Time.deltaTime; + warningUpdateTimer += Time.deltaTime; - if (Multiplayer.Session.IsGameLoaded) + if (gameResearchHashUpdateTimer > GAME_RESEARCH_UPDATE_INTERVAL) { - gameResearchHashUpdateTimer += Time.deltaTime; - productionStatisticsUpdateTimer += Time.deltaTime; - dysonLaunchUpateTimer += Time.deltaTime; - dysonSphereUpdateTimer += Time.deltaTime; - warningUpdateTimer += Time.deltaTime; - - if (gameResearchHashUpdateTimer > GAME_RESEARCH_UPDATE_INTERVAL) + gameResearchHashUpdateTimer = 0; + if (GameMain.data.history.currentTech != 0) { - gameResearchHashUpdateTimer = 0; - if (GameMain.data.history.currentTech != 0) - { - TechState state = GameMain.data.history.techStates[GameMain.data.history.currentTech]; - SendPacket(new GameHistoryResearchUpdatePacket(GameMain.data.history.currentTech, state.hashUploaded, state.hashNeeded, GameMain.statistics.techHashedFor10Frames)); - } + var state = GameMain.data.history.techStates[GameMain.data.history.currentTech]; + SendPacket(new GameHistoryResearchUpdatePacket(GameMain.data.history.currentTech, state.hashUploaded, + state.hashNeeded, GameMain.statistics.techHashedFor10Frames)); } + } - if (productionStatisticsUpdateTimer > STATISTICS_UPDATE_INTERVAL) - { - productionStatisticsUpdateTimer = 0; - Multiplayer.Session.Statistics.SendBroadcastIfNeeded(); - } + if (productionStatisticsUpdateTimer > STATISTICS_UPDATE_INTERVAL) + { + productionStatisticsUpdateTimer = 0; + Multiplayer.Session.Statistics.SendBroadcastIfNeeded(); + } - if (dysonLaunchUpateTimer > LAUNCH_UPDATE_INTERVAL) - { - dysonLaunchUpateTimer = 0; - Multiplayer.Session.Launch.SendBroadcastIfNeeded(); - } + if (dysonLaunchUpateTimer > LAUNCH_UPDATE_INTERVAL) + { + dysonLaunchUpateTimer = 0; + Multiplayer.Session.Launch.SendBroadcastIfNeeded(); + } - if (dysonSphereUpdateTimer > DYSONSPHERE_UPDATE_INTERVAL) - { - dysonSphereUpdateTimer = 0; - Multiplayer.Session.DysonSpheres.UpdateSphereStatusIfNeeded(); - } + if (dysonSphereUpdateTimer > DYSONSPHERE_UPDATE_INTERVAL) + { + dysonSphereUpdateTimer = 0; + Multiplayer.Session.DysonSpheres.UpdateSphereStatusIfNeeded(); + } - if (warningUpdateTimer > WARNING_UPDATE_INTERVAL) - { - warningUpdateTimer = 0; - Multiplayer.Session.Warning.SendBroadcastIfNeeded(); - } - } + if (warningUpdateTimer > WARNING_UPDATE_INTERVAL) + { + warningUpdateTimer = 0; + Multiplayer.Session.Warning.SendBroadcastIfNeeded(); + } } + } + + private void DisableNagleAlgorithm(WebSocketServer socketServer) + { + var listener = AccessTools.FieldRefAccess("_listener")(socketServer); + listener.Server.NoDelay = true; + } + + private class WebSocketService : WebSocketBehavior + { + public static IPlayerManager PlayerManager; + public static NetPacketProcessor PacketProcessor; + public static readonly Dictionary ConnectionDictonary = new(); + + public WebSocketService() { } - private void DisableNagleAlgorithm(WebSocketServer socketServer) + public WebSocketService(IPlayerManager playerManager, NetPacketProcessor packetProcessor) { - TcpListener listener = AccessTools.FieldRefAccess("_listener")(socketServer); - listener.Server.NoDelay = true; + PlayerManager = playerManager; + PacketProcessor = packetProcessor; + ConnectionDictonary.Clear(); } - private class WebSocketService : WebSocketBehavior + protected override void OnOpen() { - public static IPlayerManager PlayerManager; - public static NetPacketProcessor PacketProcessor; - public static Dictionary ConnectionDictonary = new(); + if (Multiplayer.Session.IsGameLoaded == false && Multiplayer.Session.IsInLobby == false) + { + // Reject any connection that occurs while the host's game is loading. + Context.WebSocket.Close((ushort)DisconnectionReason.HostStillLoading, + "Host still loading, please try again later.".Translate()); + return; + } - public WebSocketService() { } + Log.Info($"Client connected ID: {ID}"); + var conn = new NebulaConnection(Context.WebSocket, Context.UserEndPoint, PacketProcessor); + PlayerManager.PlayerConnected(conn); + ConnectionDictonary.Add(Context.UserEndPoint.GetHashCode(), conn); + } - public WebSocketService(IPlayerManager playerManager, NetPacketProcessor packetProcessor) + protected override void OnMessage(MessageEventArgs e) + { + // Find created NebulaConnection + if (ConnectionDictonary.TryGetValue(Context.UserEndPoint.GetHashCode(), out var conn)) { - PlayerManager = playerManager; - PacketProcessor = packetProcessor; - ConnectionDictonary.Clear(); + PacketProcessor.EnqueuePacketForProcessing(e.RawData, conn); } - - protected override void OnOpen() + else { - if (Multiplayer.Session.IsGameLoaded == false && Multiplayer.Session.IsInLobby == false) - { - // Reject any connection that occurs while the host's game is loading. - Context.WebSocket.Close((ushort)DisconnectionReason.HostStillLoading, "Host still loading, please try again later.".Translate()); - return; - } - - Log.Info($"Client connected ID: {ID}"); - NebulaConnection conn = new NebulaConnection(Context.WebSocket, Context.UserEndPoint, PacketProcessor); - PlayerManager.PlayerConnected(conn); - ConnectionDictonary.Add(Context.UserEndPoint.GetHashCode(), conn); + Log.Warn($"Unregister socket {Context.UserEndPoint.GetHashCode()}"); } + } - protected override void OnMessage(MessageEventArgs e) + protected override void OnClose(CloseEventArgs e) + { + ConnectionDictonary.Remove(Context.UserEndPoint.GetHashCode()); + + // If the reason of a client disconnect is because we are still loading the game, + // we don't need to inform the other clients since the disconnected client never + // joined the game in the first place. + if (e.Code == (short)DisconnectionReason.HostStillLoading) { - // Find created NebulaConnection - if (ConnectionDictonary.TryGetValue(Context.UserEndPoint.GetHashCode(), out NebulaConnection conn)) - { - PacketProcessor.EnqueuePacketForProcessing(e.RawData, conn); - } - else - { - Log.Warn($"Unregister socket {Context.UserEndPoint.GetHashCode()}"); - } + return; } - protected override void OnClose(CloseEventArgs e) + Log.Info($"Client disconnected: {ID}, reason: {e.Reason}"); + UnityDispatchQueue.RunOnMainThread(() => { - ConnectionDictonary.Remove(Context.UserEndPoint.GetHashCode()); - - // If the reason of a client disconnect is because we are still loading the game, - // we don't need to inform the other clients since the disconnected client never - // joined the game in the first place. - if (e.Code == (short)DisconnectionReason.HostStillLoading) + // This is to make sure that we don't try to deal with player disconnection + // if it is because we have stopped the server and are not in a multiplayer game anymore. + if (Multiplayer.IsActive) { - return; + PlayerManager.PlayerDisconnected(new NebulaConnection(Context.WebSocket, Context.UserEndPoint, + PacketProcessor)); } + }); + } - Log.Info($"Client disconnected: {ID}, reason: {e.Reason}"); - UnityDispatchQueue.RunOnMainThread(() => - { - // This is to make sure that we don't try to deal with player disconnection - // if it is because we have stopped the server and are not in a multiplayer game anymore. - if (Multiplayer.IsActive) - { - PlayerManager.PlayerDisconnected(new NebulaConnection(Context.WebSocket, Context.UserEndPoint, PacketProcessor)); - } - }); - } + protected override void OnError(ErrorEventArgs e) + { + ConnectionDictonary.Remove(Context.UserEndPoint.GetHashCode()); - protected override void OnError(ErrorEventArgs e) + // TODO: seems like clients erroring out in the sync process can lock the host with the joining player message, maybe this fixes it + Log.Info($"Client disconnected because of an error: {ID}, reason: {e.Exception}"); + UnityDispatchQueue.RunOnMainThread(() => { - ConnectionDictonary.Remove(Context.UserEndPoint.GetHashCode()); - - // TODO: seems like clients erroring out in the sync process can lock the host with the joining player message, maybe this fixes it - Log.Info($"Client disconnected because of an error: {ID}, reason: {e.Exception}"); - UnityDispatchQueue.RunOnMainThread(() => + // This is to make sure that we don't try to deal with player disconnection + // if it is because we have stopped the server and are not in a multiplayer game anymore. + if (Multiplayer.IsActive) { - // This is to make sure that we don't try to deal with player disconnection - // if it is because we have stopped the server and are not in a multiplayer game anymore. - if (Multiplayer.IsActive) - { - PlayerManager.PlayerDisconnected(new NebulaConnection(Context.WebSocket, Context.UserEndPoint, PacketProcessor)); - } - }); - } + PlayerManager.PlayerDisconnected(new NebulaConnection(Context.WebSocket, Context.UserEndPoint, + PacketProcessor)); + } + }); } } } diff --git a/NebulaPatcher/GlobalSuppressions.cs b/NebulaPatcher/GlobalSuppressions.cs index 8b0260599..7184975db 100644 --- a/NebulaPatcher/GlobalSuppressions.cs +++ b/NebulaPatcher/GlobalSuppressions.cs @@ -1,8 +1,9 @@ -// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. +#region using System.Diagnostics.CodeAnalysis; -[assembly: SuppressMessage("CodeQuality", "IDE0079:Remove unnecessary suppression", Justification = "If warnings are suppressed it is necessary")] +#endregion + +[assembly: + SuppressMessage("CodeQuality", "IDE0079:Remove unnecessary suppression", + Justification = "If warnings are suppressed it is necessary")] diff --git a/NebulaPatcher/Logger/BepInExLogger.cs b/NebulaPatcher/Logger/BepInExLogger.cs index b9715baf1..b2383b2d2 100644 --- a/NebulaPatcher/Logger/BepInExLogger.cs +++ b/NebulaPatcher/Logger/BepInExLogger.cs @@ -1,35 +1,38 @@ -using BepInEx.Logging; +#region + +using BepInEx.Logging; using NebulaModel.Logger; -namespace NebulaPatcher.Logger +#endregion + +namespace NebulaPatcher.Logger; + +public class BepInExLogger : ILogger { - public class BepInExLogger : ILogger + private readonly ManualLogSource logger; + + public BepInExLogger(ManualLogSource logger) + { + this.logger = logger; + } + + public void LogDebug(object data) + { + logger.LogDebug(data); + } + + public void LogError(object data) + { + logger.LogError(data); + } + + public void LogInfo(object data) + { + logger.LogInfo(data); + } + + public void LogWarning(object data) { - private readonly ManualLogSource logger; - - public BepInExLogger(ManualLogSource logger) - { - this.logger = logger; - } - - public void LogDebug(object data) - { - logger.LogDebug(data); - } - - public void LogError(object data) - { - logger.LogError(data); - } - - public void LogInfo(object data) - { - logger.LogInfo(data); - } - - public void LogWarning(object data) - { - logger.LogWarning(data); - } + logger.LogWarning(data); } } diff --git a/NebulaPatcher/MonoBehaviours/NebulaBootstrapper.cs b/NebulaPatcher/MonoBehaviours/NebulaBootstrapper.cs index 98043f605..71c09d90a 100644 --- a/NebulaPatcher/MonoBehaviours/NebulaBootstrapper.cs +++ b/NebulaPatcher/MonoBehaviours/NebulaBootstrapper.cs @@ -1,29 +1,32 @@ -using NebulaWorld; +#region + +using NebulaWorld; using UnityEngine; -namespace NebulaPatcher.MonoBehaviours +#endregion + +namespace NebulaPatcher.MonoBehaviours; + +public class NebulaBootstrapper : MonoBehaviour { - public class NebulaBootstrapper : MonoBehaviour - { - internal static NebulaBootstrapper Instance; + internal static NebulaBootstrapper Instance; - private void Awake() - { - DontDestroyOnLoad(gameObject); - Instance = this; + private void Awake() + { + DontDestroyOnLoad(gameObject); + Instance = this; - // This makes sure that even if the game is minimized, it will still receive and send packets - Application.runInBackground = true; - // make sure chat window starts out closed - //InGameChatAssetLoader.ChatManager()?.Toggle(forceClosed: true); - } + // This makes sure that even if the game is minimized, it will still receive and send packets + Application.runInBackground = true; + // make sure chat window starts out closed + //InGameChatAssetLoader.ChatManager()?.Toggle(forceClosed: true); + } - private void LateUpdate() + private void LateUpdate() + { + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) - { - Multiplayer.Session.Network.Update(); - } + Multiplayer.Session.Network.Update(); } } -} \ No newline at end of file +} diff --git a/NebulaPatcher/NebulaPatcher.csproj b/NebulaPatcher/NebulaPatcher.csproj index 6a85a2498..ef959fb8d 100644 --- a/NebulaPatcher/NebulaPatcher.csproj +++ b/NebulaPatcher/NebulaPatcher.csproj @@ -1,9 +1,9 @@  - - - - - - + + + + + + \ No newline at end of file diff --git a/NebulaPatcher/NebulaPlugin.cs b/NebulaPatcher/NebulaPlugin.cs index e7c1e4bfa..cd61f4596 100644 --- a/NebulaPatcher/NebulaPlugin.cs +++ b/NebulaPatcher/NebulaPlugin.cs @@ -1,4 +1,9 @@ -using BepInEx; +#region + +using System; +using System.IO; +using System.Reflection; +using BepInEx; using HarmonyLib; using NebulaAPI; using NebulaModel.Logger; @@ -8,337 +13,334 @@ using NebulaPatcher.MonoBehaviours; using NebulaPatcher.Patches.Dynamic; using NebulaWorld; +using NebulaWorld.GameStates; using NebulaWorld.SocialIntegration; -using System; -using System.Net; -using System.IO; -using System.Reflection; using UnityEngine; -namespace NebulaPatcher +#endregion + +namespace NebulaPatcher; + +[BepInPlugin(PluginInfo.PLUGIN_ID, PluginInfo.PLUGIN_NAME, PluginInfo.PLUGIN_VERSION)] +[BepInDependency("dsp.common - api.CommonAPI", BepInDependency.DependencyFlags.SoftDependency)] +public class NebulaPlugin : BaseUnityPlugin, IMultiplayerMod { - [BepInPlugin(PluginInfo.PLUGIN_ID, PluginInfo.PLUGIN_NAME, PluginInfo.PLUGIN_VERSION)] - [BepInDependency("dsp.common - api.CommonAPI", BepInDependency.DependencyFlags.SoftDependency)] - public class NebulaPlugin : BaseUnityPlugin, IMultiplayerMod - { - static int command_ups = 0; + private static int command_ups; - private void Awake() - { - Log.Init(new BepInExLogger(Logger)); + private void Awake() + { + Log.Init(new BepInExLogger(Logger)); - NebulaModel.Config.ModInfo = Info; - NebulaModel.Config.LoadOptions(); + NebulaModel.Config.ModInfo = Info; + NebulaModel.Config.LoadOptions(); - // Read command-line arguments - string[] args = Environment.GetCommandLineArgs(); - bool batchmode = false; - (bool didLoad, bool loadArgExists, bool newgameArgExists, string saveName) = (false, false, false, string.Empty); - for (int i = 0; i < args.Length; i++) + // Read command-line arguments + var args = Environment.GetCommandLineArgs(); + var batchmode = false; + (var didLoad, var loadArgExists, var newgameArgExists, var saveName) = (false, false, false, string.Empty); + for (var i = 0; i < args.Length; i++) + { + if (args[i] == "-server") { - if (args[i] == "-server") - { - Multiplayer.IsDedicated = true; - Log.Info($">> Initializing dedicated server"); - } + Multiplayer.IsDedicated = true; + Log.Info(">> Initializing dedicated server"); + } - if (args[i] == "-batchmode") - { - batchmode = true; - } + if (args[i] == "-batchmode") + { + batchmode = true; + } - if (args[i] == "-newgame") + if (args[i] == "-newgame") + { + newgameArgExists = true; + if (i + 3 < args.Length) { - newgameArgExists = true; - if (i + 3 < args.Length) + if (!int.TryParse(args[i + 1], out var seed)) { - if (!int.TryParse(args[i + 1], out int seed)) - { - Log.Warn($">> Can't set galaxy seed: {args[i + 1]} is not a integer"); - } - else if (!int.TryParse(args[i + 2], out int starCount)) - { - Log.Warn($">> Can't set star count: {args[i + 2]} is not a integer"); - } - else if (!float.TryParse(args[i + 3], out float resourceMultiplier)) - { - Log.Warn($">> Can't set resource multiplier: {args[i + 3]} is not a floating point number"); - } - else - { - Log.Info($">> Creating new game ({seed}, {starCount}, {resourceMultiplier:F1})"); - GameDesc gameDesc = new GameDesc(); - gameDesc.SetForNewGame(UniverseGen.algoVersion, seed, starCount, 1, resourceMultiplier); - NebulaWorld.GameStates.GameStatesManager.NewGameDesc = gameDesc; - didLoad = true; - } + Log.Warn($">> Can't set galaxy seed: {args[i + 1]} is not a integer"); } - } - - if (args[i] == "-load" && i + 1 < args.Length) - { - loadArgExists = true; - saveName = args[i + 1]; - if (saveName.EndsWith(".dsv")) + else if (!int.TryParse(args[i + 2], out var starCount)) { - saveName = saveName.Remove(saveName.Length - 4); + Log.Warn($">> Can't set star count: {args[i + 2]} is not a integer"); } - if (GameSave.SaveExist(saveName)) + else if (!float.TryParse(args[i + 3], out var resourceMultiplier)) { - Log.Info($">> Loading save {saveName}"); - NebulaWorld.GameStates.GameStatesManager.ImportedSaveName = saveName; - didLoad = true; + Log.Warn($">> Can't set resource multiplier: {args[i + 3]} is not a floating point number"); } - } - - if (args[i] == "-load-latest") - { - loadArgExists = true; - string[] files = Directory.GetFiles(GameConfig.gameSaveFolder, "*" + GameSave.saveExt, SearchOption.TopDirectoryOnly); - long[] times = new long[files.Length]; - string[] names = new string[files.Length]; - for (int j = 0; j < files.Length; j++) - { - FileInfo fileInfo = new(files[j]); - times[j] = fileInfo.LastWriteTime.ToFileTime(); - names[j] = fileInfo.Name.Substring(0, fileInfo.Name.Length - GameSave.saveExt.Length); - } - if (files.Length > 0) + else { - Array.Sort(times, names); - saveName = names[files.Length - 1]; - Log.Info($">> Loading save {saveName}"); - NebulaWorld.GameStates.GameStatesManager.ImportedSaveName = saveName; + Log.Info($">> Creating new game ({seed}, {starCount}, {resourceMultiplier:F1})"); + var gameDesc = new GameDesc(); + gameDesc.SetForNewGame(UniverseGen.algoVersion, seed, starCount, 1, resourceMultiplier); + GameStatesManager.NewGameDesc = gameDesc; didLoad = true; } } + } - if (args[i] == "-ups" && i + 1 < args.Length) + if (args[i] == "-load" && i + 1 < args.Length) + { + loadArgExists = true; + saveName = args[i + 1]; + if (saveName.EndsWith(".dsv")) { - if (int.TryParse(args[i + 1], out int value)) - { - Log.Info($">> Set UPS {value}"); - command_ups = value; - } - else - { - Log.Warn($">> Can't set UPS, {args[i + 1]} is not a valid number"); - } + saveName = saveName.Remove(saveName.Length - 4); + } + if (GameSave.SaveExist(saveName)) + { + Log.Info($">> Loading save {saveName}"); + GameStatesManager.ImportedSaveName = saveName; + didLoad = true; } } - if (Multiplayer.IsDedicated && !didLoad) + if (args[i] == "-load-latest") { - if (loadArgExists) + loadArgExists = true; + var files = Directory.GetFiles(GameConfig.gameSaveFolder, "*" + GameSave.saveExt, + SearchOption.TopDirectoryOnly); + var times = new long[files.Length]; + var names = new string[files.Length]; + for (var j = 0; j < files.Length; j++) { - if (saveName != string.Empty) - { - Log.Error($">> Can't find save with name {saveName}! Exiting..."); - } - else - { - Log.Error($">> Can't find any save in the folder! Exiting..."); - } + FileInfo fileInfo = new(files[j]); + times[j] = fileInfo.LastWriteTime.ToFileTime(); + names[j] = fileInfo.Name.Substring(0, fileInfo.Name.Length - GameSave.saveExt.Length); + } + if (files.Length > 0) + { + Array.Sort(times, names); + saveName = names[files.Length - 1]; + Log.Info($">> Loading save {saveName}"); + GameStatesManager.ImportedSaveName = saveName; + didLoad = true; } - else if (newgameArgExists) + } + + if (args[i] == "-ups" && i + 1 < args.Length) + { + if (int.TryParse(args[i + 1], out var value)) { - Log.Error($">> New game parameters incorrect! Exiting...\nExpect: -newgame seed starCount resourceMltiplier"); + Log.Info($">> Set UPS {value}"); + command_ups = value; } else { - Log.Error(">> -load or -newgame argument missing! Exiting..."); + Log.Warn($">> Can't set UPS, {args[i + 1]} is not a valid number"); } - Application.Quit(); } + } - if (Multiplayer.IsDedicated) + if (Multiplayer.IsDedicated && !didLoad) + { + if (loadArgExists) { - if (!batchmode) + if (saveName != string.Empty) { - Log.Warn("Dedicate server should start with -batchmode argument"); + Log.Error($">> Can't find save with name {saveName}! Exiting..."); + } + else + { + Log.Error(">> Can't find any save in the folder! Exiting..."); } } - - try + else if (newgameArgExists) { - Initialize(); + Log.Error(">> New game parameters incorrect! Exiting...\nExpect: -newgame seed starCount resourceMltiplier"); } - catch (Exception ex) + else { - Log.Error("Unhandled exception occurred while initializing Nebula:", ex); + Log.Error(">> -load or -newgame argument missing! Exiting..."); } + Application.Quit(); } - private static void Initialize() + if (Multiplayer.IsDedicated) { - InitPatches(); - AddNebulaBootstrapper(); - DiscordManager.Setup(ActivityManager_OnActivityJoin); + if (!batchmode) + { + Log.Warn("Dedicate server should start with -batchmode argument"); + } } - public static void StartDedicatedServer(string saveName) + try { - // Mimic UI buttons clicking - UIMainMenu_Patch.OnMultiplayerButtonClick(); - if (GameSave.SaveExist(saveName)) - { - // Modified from DoLoadSelectedGame - Log.Info($"Starting dedicated server, loading save : {saveName}"); - DSPGame.StartGame(saveName); - Log.Info($"Listening server on port {NebulaModel.Config.Options.HostPort}"); - Multiplayer.HostGame(new Server(NebulaModel.Config.Options.HostPort, true)); - if (command_ups != 0) - { - FPSController.SetFixUPS(command_ups); - } - } + Initialize(); } + catch (Exception ex) + { + Log.Error("Unhandled exception occurred while initializing Nebula:", ex); + } + } - public static void StartDedicatedServer(GameDesc gameDesc) + private void Update() + { + if (GameMain.isRunning && UIRoot.instance.launchSplash.willdone) { - // Mimic UI buttons clicking - UIMainMenu_Patch.OnMultiplayerButtonClick(); - if (gameDesc != null) - { - // Modified from DoLoadSelectedGame - Log.Info($"Starting dedicated server, create new game from parameters:"); - Log.Info($"seed={gameDesc.galaxySeed} starCount={gameDesc.starCount} resourceMultiplier={gameDesc.resourceMultiplier:F1}"); - DSPGame.StartGameSkipPrologue(gameDesc); - Log.Info($"Listening server on port {NebulaModel.Config.Options.HostPort}"); - Multiplayer.HostGame(new Server(NebulaModel.Config.Options.HostPort, true)); - if (command_ups != 0) - { - FPSController.SetFixUPS(command_ups); - } - } + DiscordManager.Update(); } + } - private static async void ActivityManager_OnActivityJoin(string secret) + public string Version => NebulaModel.Config.ModVersion; + + public bool CheckVersion(string hostVersion, string clientVersion) + { + return hostVersion.Equals(clientVersion); + } + + private static void Initialize() + { + InitPatches(); + AddNebulaBootstrapper(); + DiscordManager.Setup(ActivityManager_OnActivityJoin); + } + + public static void StartDedicatedServer(string saveName) + { + // Mimic UI buttons clicking + UIMainMenu_Patch.OnMultiplayerButtonClick(); + if (GameSave.SaveExist(saveName)) { - if(Multiplayer.IsActive) + // Modified from DoLoadSelectedGame + Log.Info($"Starting dedicated server, loading save : {saveName}"); + DSPGame.StartGame(saveName); + Log.Info($"Listening server on port {NebulaModel.Config.Options.HostPort}"); + Multiplayer.HostGame(new Server(NebulaModel.Config.Options.HostPort, true)); + if (command_ups != 0) { - Log.Warn("Cannot join lobby from Discord, we are already in a lobby."); - return; + FPSController.SetFixUPS(command_ups); } + } + } - if(string.IsNullOrWhiteSpace(secret)) + public static void StartDedicatedServer(GameDesc gameDesc) + { + // Mimic UI buttons clicking + UIMainMenu_Patch.OnMultiplayerButtonClick(); + if (gameDesc != null) + { + // Modified from DoLoadSelectedGame + Log.Info("Starting dedicated server, create new game from parameters:"); + Log.Info( + $"seed={gameDesc.galaxySeed} starCount={gameDesc.starCount} resourceMultiplier={gameDesc.resourceMultiplier:F1}"); + DSPGame.StartGameSkipPrologue(gameDesc); + Log.Info($"Listening server on port {NebulaModel.Config.Options.HostPort}"); + Multiplayer.HostGame(new Server(NebulaModel.Config.Options.HostPort, true)); + if (command_ups != 0) { - Log.Warn("Received Discord invite without IP address."); - return; + FPSController.SetFixUPS(command_ups); } + } + } - var ipAddresses = secret.FromBase64().Split(';'); + private static async void ActivityManager_OnActivityJoin(string secret) + { + if (Multiplayer.IsActive) + { + Log.Warn("Cannot join lobby from Discord, we are already in a lobby."); + return; + } - if(ipAddresses.Length != 1 && ipAddresses.Length != 3) - { - Log.Warn("Received invalid discord invite."); - return; - } + if (string.IsNullOrWhiteSpace(secret)) + { + Log.Warn("Received Discord invite without IP address."); + return; + } - string ipAddress = string.Empty; + var ipAddresses = secret.FromBase64().Split(';'); - if(ipAddresses.Length == 1 && ipAddresses[0].Contains("ngrok")) - { - ipAddress = ipAddresses[0]; - } + if (ipAddresses.Length != 1 && ipAddresses.Length != 3) + { + Log.Warn("Received invalid discord invite."); + return; + } - if(string.IsNullOrWhiteSpace(ipAddress) && await IPUtils.IsIPv6Supported()) - { - if(ipAddresses.Length > 1) - { - if (IPUtils.IsIPv6(ipAddresses[1])) - { - ipAddress = $"{ipAddresses[1]}:{ipAddresses[2]}"; - } - } - } + var ipAddress = string.Empty; - if(string.IsNullOrWhiteSpace(ipAddress)) + if (ipAddresses.Length == 1 && ipAddresses[0].Contains("ngrok")) + { + ipAddress = ipAddresses[0]; + } + + if (string.IsNullOrWhiteSpace(ipAddress) && await IPUtils.IsIPv6Supported()) + { + if (ipAddresses.Length > 1) { - if (IPUtils.IsIPv4(ipAddresses[0])) + if (IPUtils.IsIPv6(ipAddresses[1])) { - ipAddress = $"{ipAddresses[0]}:{ipAddresses[2]}"; + ipAddress = $"{ipAddresses[1]}:{ipAddresses[2]}"; } } - - if(string.IsNullOrWhiteSpace(ipAddress)) - { - Log.Warn("Received Discord invite with invalid IP address."); - return; - } - - Log.Info("Joining lobby from Discord..."); - UIMainMenu_Patch.OnMultiplayerButtonClick(); - UIMainMenu_Patch.JoinGame($"{ipAddress}"); - DiscordManager.UpdateRichPresence(ip: secret, secretPassthrough: true, updateTimestamp: true); } - private void Update() + if (string.IsNullOrWhiteSpace(ipAddress)) { - if(GameMain.isRunning && UIRoot.instance.launchSplash.willdone) + if (IPUtils.IsIPv4(ipAddresses[0])) { - DiscordManager.Update(); + ipAddress = $"{ipAddresses[0]}:{ipAddresses[2]}"; } } - private static void InitPatches() + if (string.IsNullOrWhiteSpace(ipAddress)) { - Log.Info("Patching Dyson Sphere Program..."); + Log.Warn("Received Discord invite with invalid IP address."); + return; + } - try - { - Log.Info($"Applying patches from {PluginInfo.PLUGIN_NAME} {PluginInfo.PLUGIN_DISPLAY_VERSION}"); -#if DEBUG - if (Directory.Exists("./mmdump")) - { - foreach (FileInfo file in new DirectoryInfo("./mmdump").GetFiles()) - { - file.Delete(); - } + Log.Info("Joining lobby from Discord..."); + UIMainMenu_Patch.OnMultiplayerButtonClick(); + UIMainMenu_Patch.JoinGame($"{ipAddress}"); + DiscordManager.UpdateRichPresence(secret, secretPassthrough: true, updateTimestamp: true); + } - Environment.SetEnvironmentVariable("MONOMOD_DMD_TYPE", "cecil"); - Environment.SetEnvironmentVariable("MONOMOD_DMD_DUMP", "./mmdump"); - } -#endif - Harmony harmony = Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), PluginInfo.PLUGIN_ID); - if (Multiplayer.IsDedicated) + private static void InitPatches() + { + Log.Info("Patching Dyson Sphere Program..."); + + try + { + Log.Info($"Applying patches from {PluginInfo.PLUGIN_NAME} {PluginInfo.PLUGIN_DISPLAY_VERSION}"); +#if DEBUG + if (Directory.Exists("./mmdump")) + { + foreach (var file in new DirectoryInfo("./mmdump").GetFiles()) { - Log.Info("Patching for headless mode..."); - harmony.PatchAll(typeof(Dedicated_Server_Patch)); + file.Delete(); } -#if DEBUG - Environment.SetEnvironmentVariable("MONOMOD_DMD_DUMP", ""); -#endif - Log.Info("Patching completed successfully"); + Environment.SetEnvironmentVariable("MONOMOD_DMD_TYPE", "cecil"); + Environment.SetEnvironmentVariable("MONOMOD_DMD_DUMP", "./mmdump"); } - catch (Exception ex) +#endif + var harmony = Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), PluginInfo.PLUGIN_ID); + if (Multiplayer.IsDedicated) { - Log.Error("Unhandled exception occurred while patching the game:", ex); - // Show error in UIFatalErrorTip to inform normal users - Harmony.CreateAndPatchAll(typeof(UIFatalErrorTip_Patch)); - Log.Error($"Nebula Multiplayer Mod is incompatible\nUnhandled exception occurred while patching the game."); + Log.Info("Patching for headless mode..."); + harmony.PatchAll(typeof(Dedicated_Server_Patch)); } - } - - private static void AddNebulaBootstrapper() - { - Log.Info("Applying Nebula behaviours.."); - - GameObject nebulaRoot = new GameObject - { - name = "Nebula Multiplayer Mod" - }; - nebulaRoot.AddComponent(); +#if DEBUG + Environment.SetEnvironmentVariable("MONOMOD_DMD_DUMP", ""); +#endif - Log.Info("Behaviours applied."); + Log.Info("Patching completed successfully"); } - - public string Version => NebulaModel.Config.ModVersion; - public bool CheckVersion(string hostVersion, string clientVersion) + catch (Exception ex) { - return hostVersion.Equals(clientVersion); + Log.Error("Unhandled exception occurred while patching the game:", ex); + // Show error in UIFatalErrorTip to inform normal users + Harmony.CreateAndPatchAll(typeof(UIFatalErrorTip_Patch)); + Log.Error("Nebula Multiplayer Mod is incompatible\nUnhandled exception occurred while patching the game."); } + } + + private static void AddNebulaBootstrapper() + { + Log.Info("Applying Nebula behaviours.."); + + var nebulaRoot = new GameObject { name = "Nebula Multiplayer Mod" }; + nebulaRoot.AddComponent(); + Log.Info("Behaviours applied."); } } diff --git a/NebulaPatcher/Patches/Dynamic/BuildTool_Common_Patch.cs b/NebulaPatcher/Patches/Dynamic/BuildTool_Common_Patch.cs index 3550b0ea7..29db8ad56 100644 --- a/NebulaPatcher/Patches/Dynamic/BuildTool_Common_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/BuildTool_Common_Patch.cs @@ -1,77 +1,87 @@ -using HarmonyLib; +#region + +using System.Collections.Generic; +using System.Linq; +using HarmonyLib; using NebulaAPI; using NebulaModel.Packets.Factory; using NebulaWorld; -using System.Collections.Generic; -using System.Linq; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch] +internal class BuildTool_Common_Patch { - [HarmonyPatch] - internal class BuildTool_Common_Patch + [HarmonyPrefix] + [HarmonyPatch(typeof(BuildTool_Click), nameof(BuildTool_Click.CreatePrebuilds))] + [HarmonyPatch(typeof(BuildTool_Path), nameof(BuildTool_Path.CreatePrebuilds))] + [HarmonyPatch(typeof(BuildTool_Addon), nameof(BuildTool_Addon.CreatePrebuilds))] + [HarmonyPatch(typeof(BuildTool_Inserter), nameof(BuildTool_Inserter.CreatePrebuilds))] + [HarmonyPatch(typeof(BuildTool_BlueprintPaste), nameof(BuildTool_BlueprintPaste.CreatePrebuilds))] + public static bool CreatePrebuilds_Prefix(BuildTool __instance) { - [HarmonyPrefix] - [HarmonyPatch(typeof(BuildTool_Click), nameof(BuildTool_Click.CreatePrebuilds))] - [HarmonyPatch(typeof(BuildTool_Path), nameof(BuildTool_Path.CreatePrebuilds))] - [HarmonyPatch(typeof(BuildTool_Addon), nameof(BuildTool_Addon.CreatePrebuilds))] - [HarmonyPatch(typeof(BuildTool_Inserter), nameof(BuildTool_Inserter.CreatePrebuilds))] - [HarmonyPatch(typeof(BuildTool_BlueprintPaste), nameof(BuildTool_BlueprintPaste.CreatePrebuilds))] - public static bool CreatePrebuilds_Prefix(BuildTool __instance) + if (!Multiplayer.IsActive) { - if (!Multiplayer.IsActive) - { - return true; - } + return true; + } - List previews = __instance.buildPreviews; - if (__instance is BuildTool_BlueprintPaste) - { - BuildTool_BlueprintPaste bpInstance = __instance as BuildTool_BlueprintPaste; - previews = bpInstance.bpPool.Take(bpInstance.bpCursor).ToList(); - } - if(__instance is BuildTool_Addon) - { - // traffic monitors & sprayers cannot be drag build atm, so its always only one. - previews = new List(); - previews.Add(((BuildTool_Addon)__instance).handbp); - } + var previews = __instance.buildPreviews; + if (__instance is BuildTool_BlueprintPaste) + { + var bpInstance = __instance as BuildTool_BlueprintPaste; + previews = bpInstance.bpPool.Take(bpInstance.bpCursor).ToList(); + } + if (__instance is BuildTool_Addon) + { + // traffic monitors & sprayers cannot be drag build atm, so its always only one. + previews = new List(); + previews.Add(((BuildTool_Addon)__instance).handbp); + } - // Host will just broadcast event to other players - if (Multiplayer.Session.LocalPlayer.IsHost) - { - int planetId = Multiplayer.Session.Factories.EventFactory?.planetId ?? GameMain.localPlanet?.id ?? -1; - int authorId = Multiplayer.Session.Factories.PacketAuthor == NebulaModAPI.AUTHOR_NONE ? Multiplayer.Session.LocalPlayer.Id : Multiplayer.Session.Factories.PacketAuthor; - int prebuildId = Multiplayer.Session.Factories.GetNextPrebuildId(planetId); - Multiplayer.Session.Network.SendPacketToStar(new CreatePrebuildsRequest(planetId, previews, authorId, __instance.GetType().ToString(), prebuildId), GameMain.galaxy.PlanetById(planetId).star.id); - } + // Host will just broadcast event to other players + if (Multiplayer.Session.LocalPlayer.IsHost) + { + var planetId = Multiplayer.Session.Factories.EventFactory?.planetId ?? GameMain.localPlanet?.id ?? -1; + var authorId = Multiplayer.Session.Factories.PacketAuthor == NebulaModAPI.AUTHOR_NONE + ? Multiplayer.Session.LocalPlayer.Id + : Multiplayer.Session.Factories.PacketAuthor; + var prebuildId = Multiplayer.Session.Factories.GetNextPrebuildId(planetId); + Multiplayer.Session.Network.SendPacketToStar( + new CreatePrebuildsRequest(planetId, previews, authorId, __instance.GetType().ToString(), prebuildId), + GameMain.galaxy.PlanetById(planetId).star.id); + } - //If client builds, he need to first send request to the host and wait for reply - if (!Multiplayer.Session.LocalPlayer.IsHost && !Multiplayer.Session.Factories.IsIncomingRequest.Value) + //If client builds, he need to first send request to the host and wait for reply + if (!Multiplayer.Session.LocalPlayer.IsHost && !Multiplayer.Session.Factories.IsIncomingRequest.Value) + { + if (Multiplayer.Session.BuildTools.InitialCheck(previews[0].lpos)) { - if (Multiplayer.Session.BuildTools.InitialCheck(previews[0].lpos)) - { - int authorId = Multiplayer.Session.Factories.PacketAuthor == NebulaModAPI.AUTHOR_NONE ? Multiplayer.Session.LocalPlayer.Id : Multiplayer.Session.Factories.PacketAuthor; - Multiplayer.Session.Network.SendPacket(new CreatePrebuildsRequest(GameMain.localPlanet?.id ?? -1, previews, authorId, __instance.GetType().ToString(), -1)); - } - return false; + var authorId = Multiplayer.Session.Factories.PacketAuthor == NebulaModAPI.AUTHOR_NONE + ? Multiplayer.Session.LocalPlayer.Id + : Multiplayer.Session.Factories.PacketAuthor; + Multiplayer.Session.Network.SendPacket(new CreatePrebuildsRequest(GameMain.localPlanet?.id ?? -1, previews, + authorId, __instance.GetType().ToString(), -1)); } - return true; + return false; } + return true; + } - [HarmonyPrefix] - [HarmonyPatch(typeof(BuildTool_Click), nameof(BuildTool_Click.CheckBuildConditions))] - [HarmonyPatch(typeof(BuildTool_Path), nameof(BuildTool_Path.CheckBuildConditions))] - [HarmonyPatch(typeof(BuildTool_Addon), nameof(BuildTool_Addon.CheckBuildConditions))] - [HarmonyPatch(typeof(BuildTool_Inserter), nameof(BuildTool_Inserter.CheckBuildConditions))] - [HarmonyPatch(typeof(BuildTool_BlueprintPaste), nameof(BuildTool_BlueprintPaste.CheckBuildConditions))] - public static bool CheckBuildConditions(ref bool __result) + [HarmonyPrefix] + [HarmonyPatch(typeof(BuildTool_Click), nameof(BuildTool_Click.CheckBuildConditions))] + [HarmonyPatch(typeof(BuildTool_Path), nameof(BuildTool_Path.CheckBuildConditions))] + [HarmonyPatch(typeof(BuildTool_Addon), nameof(BuildTool_Addon.CheckBuildConditions))] + [HarmonyPatch(typeof(BuildTool_Inserter), nameof(BuildTool_Inserter.CheckBuildConditions))] + [HarmonyPatch(typeof(BuildTool_BlueprintPaste), nameof(BuildTool_BlueprintPaste.CheckBuildConditions))] + public static bool CheckBuildConditions(ref bool __result) + { + if (Multiplayer.IsActive && Multiplayer.Session.Factories.IsIncomingRequest.Value) { - if (Multiplayer.IsActive && Multiplayer.Session.Factories.IsIncomingRequest.Value) - { - __result = true; - return false; - } - return true; + __result = true; + return false; } + return true; } } diff --git a/NebulaPatcher/Patches/Dynamic/CargoTraffic_Patch.cs b/NebulaPatcher/Patches/Dynamic/CargoTraffic_Patch.cs index fbb4cf634..1a08ef564 100644 --- a/NebulaPatcher/Patches/Dynamic/CargoTraffic_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/CargoTraffic_Patch.cs @@ -1,134 +1,148 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaAPI; using NebulaModel.Packets.Factory.Belt; using NebulaWorld; -using UnityEngine; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(CargoTraffic))] +internal class CargoTraffic_Patch { - [HarmonyPatch(typeof(CargoTraffic))] - internal class CargoTraffic_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(CargoTraffic.PickupBeltItems))] + public static void PickupBeltItems_Prefix() { - [HarmonyPrefix] - [HarmonyPatch(nameof(CargoTraffic.PickupBeltItems))] - public static void PickupBeltItems_Prefix() + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) - { - Multiplayer.Session.Belts.BeltPickupStarted(); - } + Multiplayer.Session.Belts.BeltPickupStarted(); } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(CargoTraffic.PickupBeltItems))] - public static void PickupBeltItems_Postfix() + [HarmonyPostfix] + [HarmonyPatch(nameof(CargoTraffic.PickupBeltItems))] + public static void PickupBeltItems_Postfix() + { + if (Multiplayer.IsActive && GameMain.data.localPlanet != null) { - if (Multiplayer.IsActive && GameMain.data.localPlanet != null) - { - Multiplayer.Session.Belts.BeltPickupEnded(); - } + Multiplayer.Session.Belts.BeltPickupEnded(); } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(CargoTraffic.PutItemOnBelt))] - public static void PutItemOnBelt_Postfix(int beltId, int itemId, byte itemInc, bool __result) + [HarmonyPostfix] + [HarmonyPatch(nameof(CargoTraffic.PutItemOnBelt))] + public static void PutItemOnBelt_Postfix(int beltId, int itemId, byte itemInc, bool __result) + { + // Only send packet when insertion successes + if (Multiplayer.IsActive && __result && !Multiplayer.Session.Factories.IsIncomingRequest.Value) { - // Only send packet when insertion successes - if (Multiplayer.IsActive && __result && !Multiplayer.Session.Factories.IsIncomingRequest.Value) - { - Multiplayer.Session.Network.SendPacketToLocalStar(new BeltUpdatePutItemOnPacket(beltId, itemId, 1, itemInc, GameMain.data.localPlanet.id)); - } + Multiplayer.Session.Network.SendPacketToLocalStar(new BeltUpdatePutItemOnPacket(beltId, itemId, 1, itemInc, + GameMain.data.localPlanet.id)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(CargoTraffic.AlterBeltRenderer))] - public static bool AlterBeltRenderer_Prefix() - { - //Do not call renderer, if user is not on the planet as the request - return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; - } + [HarmonyPrefix] + [HarmonyPatch(nameof(CargoTraffic.AlterBeltRenderer))] + public static bool AlterBeltRenderer_Prefix() + { + //Do not call renderer, if user is not on the planet as the request + return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || + GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; + } - [HarmonyPrefix] - [HarmonyPatch(nameof(CargoTraffic.RemoveBeltRenderer))] - public static bool RemoveBeltRenderer_Prefix() - { - //Do not call renderer, if user is not on the planet as the request - return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; - } + [HarmonyPrefix] + [HarmonyPatch(nameof(CargoTraffic.RemoveBeltRenderer))] + public static bool RemoveBeltRenderer_Prefix() + { + //Do not call renderer, if user is not on the planet as the request + return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || + GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; + } - [HarmonyPrefix] - [HarmonyPatch(nameof(CargoTraffic.AlterPathRenderer))] - public static bool AlterPathRenderer_Prefix() - { - //Do not call renderer, if user is not on the planet as the request - return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; - } + [HarmonyPrefix] + [HarmonyPatch(nameof(CargoTraffic.AlterPathRenderer))] + public static bool AlterPathRenderer_Prefix() + { + //Do not call renderer, if user is not on the planet as the request + return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || + GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; + } + + [HarmonyPrefix] + [HarmonyPatch(nameof(CargoTraffic.RemovePathRenderer))] + public static bool RemovePathRenderer_Prefix() + { + //Do not call renderer, if user is not on the planet as the request + return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || + GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; + } - [HarmonyPrefix] - [HarmonyPatch(nameof(CargoTraffic.RemovePathRenderer))] - public static bool RemovePathRenderer_Prefix() + [HarmonyPrefix] + [HarmonyPatch(nameof(CargoTraffic.RefreshPathUV))] + public static bool RefreshPathUV_Prefix() + { + //Do not call renderer, if user is not on the planet as the request + return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || + GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; + } + + [HarmonyPostfix] + [HarmonyPatch(nameof(CargoTraffic.ConnectToMonitor))] + public static void ConnectToMonitor_Postfix(int monitorId, int targetBeltId, int offset) + { + if (!Multiplayer.IsActive) { - //Do not call renderer, if user is not on the planet as the request - return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; + return; } - - [HarmonyPrefix] - [HarmonyPatch(nameof(CargoTraffic.RefreshPathUV))] - public static bool RefreshPathUV_Prefix() + // If host build, or client receive his build request + if (Multiplayer.Session.LocalPlayer.IsHost && !Multiplayer.Session.Factories.IsIncomingRequest.Value || + Multiplayer.Session.Factories.PacketAuthor == Multiplayer.Session.LocalPlayer.Id) { - //Do not call renderer, if user is not on the planet as the request - return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; + Multiplayer.Session.Network.SendPacketToLocalStar(new ConnectToMonitorPacket(monitorId, targetBeltId, offset, + GameMain.data.localPlanet.id)); } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(CargoTraffic.ConnectToMonitor))] - public static void ConnectToMonitor_Postfix(int monitorId, int targetBeltId, int offset) + [HarmonyPostfix] + [HarmonyPatch(nameof(CargoTraffic.ConnectToSpraycoater))] + public static void ConnectToSpraycoater(int spraycoaterId, int cargoBeltId, int incBeltId) + { + if (!Multiplayer.IsActive) { - if (!Multiplayer.IsActive) - { - return; - } - // If host build, or client receive his build request - if((Multiplayer.Session.LocalPlayer.IsHost && !Multiplayer.Session.Factories.IsIncomingRequest.Value)|| Multiplayer.Session.Factories.PacketAuthor == Multiplayer.Session.LocalPlayer.Id) - { - Multiplayer.Session.Network.SendPacketToLocalStar(new ConnectToMonitorPacket(monitorId, targetBeltId, offset, GameMain.data.localPlanet.id)); - } + return; } - - [HarmonyPostfix] - [HarmonyPatch(nameof(CargoTraffic.ConnectToSpraycoater))] - public static void ConnectToSpraycoater(int spraycoaterId, int cargoBeltId, int incBeltId) + // If host build, or client receive his build request + if (Multiplayer.Session.LocalPlayer.IsHost && !Multiplayer.Session.Factories.IsIncomingRequest.Value || + Multiplayer.Session.Factories.PacketAuthor == Multiplayer.Session.LocalPlayer.Id) { - if (!Multiplayer.IsActive) - { - return; - } - // If host build, or client receive his build request - if ((Multiplayer.Session.LocalPlayer.IsHost && !Multiplayer.Session.Factories.IsIncomingRequest.Value) || Multiplayer.Session.Factories.PacketAuthor == Multiplayer.Session.LocalPlayer.Id) - { - Multiplayer.Session.Network.SendPacketToLocalStar(new ConnectToSpraycoaterPacket(spraycoaterId, cargoBeltId, incBeltId, GameMain.data.localPlanet.id)); - } + Multiplayer.Session.Network.SendPacketToLocalStar(new ConnectToSpraycoaterPacket(spraycoaterId, cargoBeltId, + incBeltId, GameMain.data.localPlanet.id)); } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(CargoTraffic.SetBeltSignalIcon))] - public static void SetBeltSignalIcon_Postfix(int entityId, int signalId) + [HarmonyPostfix] + [HarmonyPatch(nameof(CargoTraffic.SetBeltSignalIcon))] + public static void SetBeltSignalIcon_Postfix(int entityId, int signalId) + { + // Notify others about belt memo icon changes + if (Multiplayer.IsActive && !Multiplayer.Session.Factories.IsIncomingRequest.Value) { - // Notify others about belt memo icon changes - if (Multiplayer.IsActive && !Multiplayer.Session.Factories.IsIncomingRequest.Value) - { - Multiplayer.Session.Network.SendPacketToLocalStar(new BeltSignalIconPacket(entityId, signalId, GameMain.data.localPlanet.id)); - } + Multiplayer.Session.Network.SendPacketToLocalStar(new BeltSignalIconPacket(entityId, signalId, + GameMain.data.localPlanet.id)); } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(CargoTraffic.SetBeltSignalNumber))] - public static void SetBeltSignalNumber_Postfix(int entityId, float number) + [HarmonyPostfix] + [HarmonyPatch(nameof(CargoTraffic.SetBeltSignalNumber))] + public static void SetBeltSignalNumber_Postfix(int entityId, float number) + { + if (Multiplayer.IsActive && !Multiplayer.Session.Factories.IsIncomingRequest.Value) { - if (Multiplayer.IsActive && !Multiplayer.Session.Factories.IsIncomingRequest.Value) - { - Multiplayer.Session.Network.SendPacketToLocalStar(new BeltSignalNumberPacket(entityId, number, GameMain.data.localPlanet.id)); - } + Multiplayer.Session.Network.SendPacketToLocalStar(new BeltSignalNumberPacket(entityId, number, + GameMain.data.localPlanet.id)); } } } diff --git a/NebulaPatcher/Patches/Dynamic/DESelection_Patch.cs b/NebulaPatcher/Patches/Dynamic/DESelection_Patch.cs index 90da62ab1..e24ce50a6 100644 --- a/NebulaPatcher/Patches/Dynamic/DESelection_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/DESelection_Patch.cs @@ -1,64 +1,68 @@ -using HarmonyLib; -using NebulaModel.Logger; +#region + +using HarmonyLib; using NebulaModel.Packets.Universe; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(DESelection))] +internal class DESelection_Patch { - [HarmonyPatch(typeof(DESelection))] - internal class DESelection_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(DESelection.SetViewStar))] + public static bool SetViewStar_Prefix(DESelection __instance, ref StarData starData) { - [HarmonyPrefix] - [HarmonyPatch(nameof(DESelection.SetViewStar))] - public static bool SetViewStar_Prefix(DESelection __instance, ref StarData starData) + if (Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsClient) { - if (Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsClient) + //UIDysonEditor._OnOpen() + if (!UIRoot.instance.uiGame.dysonEditor.sceneGroup.activeSelf) { - //UIDysonEditor._OnOpen() - if (!UIRoot.instance.uiGame.dysonEditor.sceneGroup.activeSelf) + //Request the latest list of existing dyson spheres + Multiplayer.Session.Network.SendPacket(new DysonSphereLoadRequest(0, DysonSphereRequestEvent.List)); + if (GameMain.localStar == null) { - //Request the latest list of existing dyson spheres - Multiplayer.Session.Network.SendPacket(new DysonSphereLoadRequest(0, DysonSphereRequestEvent.List)); - if (GameMain.localStar == null) + //In outer space, set initial viewStar to the one that has dyson sphere + for (var i = 0; i < GameMain.data.dysonSpheres.Length; i++) { - //In outer space, set initial viewStar to the one that has dyson sphere - for (int i = 0; i < GameMain.data.dysonSpheres.Length; i++) + if (GameMain.data.dysonSpheres[i] != null) { - if (GameMain.data.dysonSpheres[i] != null) - { - starData = GameMain.data.dysonSpheres[i].starData; - return true; - } + starData = GameMain.data.dysonSpheres[i].starData; + return true; } - //No dyson sphere exist, close the UI - UIRoot.instance.uiGame.dysonEditor._Close(); - return false; - } - else if (GameMain.data.dysonSpheres[starData.index] == null) - { - //Local dyson sphere hasn't loaded yet, close the UI - UIRoot.instance.uiGame.dysonEditor._Close(); - return false; } + //No dyson sphere exist, close the UI + UIRoot.instance.uiGame.dysonEditor._Close(); + return false; } - if (starData != null && GameMain.data.dysonSpheres[starData.index] == null) + if (GameMain.data.dysonSpheres[starData.index] == null) { - if (Multiplayer.Session.DysonSpheres.RequestingIndex == -1) - { - Multiplayer.Session.DysonSpheres.RequestDysonSphere(starData.index); - } - else - { - InGamePopup.ShowInfo("Loading".Translate(), string.Format("Loading Dyson sphere {0}, please wait".Translate(), starData.displayName), null); - } - // Restore comboBox back to original star - UIComboBox dysonBox = UIRoot.instance.uiGame.dysonEditor.controlPanel.topFunction.dysonBox; - int index = dysonBox.ItemsData.FindIndex(x => x == UIRoot.instance.uiGame.dysonEditor.selection.viewStar?.index); - dysonBox.itemIndex = index >= 0 ? index : 0; + //Local dyson sphere hasn't loaded yet, close the UI + UIRoot.instance.uiGame.dysonEditor._Close(); return false; } } - return true; + if (starData != null && GameMain.data.dysonSpheres[starData.index] == null) + { + if (Multiplayer.Session.DysonSpheres.RequestingIndex == -1) + { + Multiplayer.Session.DysonSpheres.RequestDysonSphere(starData.index); + } + else + { + InGamePopup.ShowInfo("Loading".Translate(), + string.Format("Loading Dyson sphere {0}, please wait".Translate(), starData.displayName), null); + } + // Restore comboBox back to original star + var dysonBox = UIRoot.instance.uiGame.dysonEditor.controlPanel.topFunction.dysonBox; + var index = dysonBox.ItemsData.FindIndex(x => + x == UIRoot.instance.uiGame.dysonEditor.selection.viewStar?.index); + dysonBox.itemIndex = index >= 0 ? index : 0; + return false; + } } + return true; } } diff --git a/NebulaPatcher/Patches/Dynamic/Debugging.cs b/NebulaPatcher/Patches/Dynamic/Debugging.cs index a0be1c2ab..6460ebd47 100644 --- a/NebulaPatcher/Patches/Dynamic/Debugging.cs +++ b/NebulaPatcher/Patches/Dynamic/Debugging.cs @@ -1,160 +1,164 @@ #if DEBUG + +#region + using HarmonyLib; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(GameHistoryData))] +internal class Debug_GameHistoryData_Patch { - [HarmonyPatch(typeof(GameHistoryData))] - internal class Debug_GameHistoryData_Patch + [HarmonyPostfix] + [HarmonyPatch(nameof(GameHistoryData.EnqueueTech))] + public static void EnqueueTech_Postfix(GameHistoryData __instance, int techId) { - [HarmonyPostfix] - [HarmonyPatch(nameof(GameHistoryData.EnqueueTech))] - public static void EnqueueTech_Postfix(GameHistoryData __instance, int techId) + if (Multiplayer.IsActive && Multiplayer.Session.History.IsIncomingRequest) { - if (Multiplayer.IsActive && Multiplayer.Session.History.IsIncomingRequest) - { - //Do not run if this was triggered by incomming request - return; - } - __instance.UnlockTech(techId); - GameMain.mainPlayer.mecha.corePowerGen = 10000000; + //Do not run if this was triggered by incomming request + return; } + __instance.UnlockTech(techId); + GameMain.mainPlayer.mecha.corePowerGen = 10000000; + } - [HarmonyPrefix] - [HarmonyPatch(nameof(GameHistoryData.dysonSphereSystemUnlocked), MethodType.Getter)] - public static bool DysonSphereSystemUnlocked_Prefix(GameHistoryData __instance, ref bool __result) - { - __result = true; - return false; - } + [HarmonyPrefix] + [HarmonyPatch(nameof(GameHistoryData.dysonSphereSystemUnlocked), MethodType.Getter)] + public static bool DysonSphereSystemUnlocked_Prefix(GameHistoryData __instance, ref bool __result) + { + __result = true; + return false; + } - [HarmonyPostfix] - [HarmonyPatch(nameof(GameHistoryData.SetForNewGame))] - public static void SetForNewGame_Postfix(GameHistoryData __instance) - { - __instance.dysonNodeLatitude = 90f; - } + [HarmonyPostfix] + [HarmonyPatch(nameof(GameHistoryData.SetForNewGame))] + public static void SetForNewGame_Postfix(GameHistoryData __instance) + { + __instance.dysonNodeLatitude = 90f; } +} - [HarmonyPatch(typeof(Mecha))] - internal class Debug_Mecha_Patch +[HarmonyPatch(typeof(Mecha))] +internal class Debug_Mecha_Patch +{ + [HarmonyPostfix] + [HarmonyPatch(nameof(Mecha.UseWarper))] + public static void UseWarper_Postfix(ref bool __result) { - [HarmonyPostfix] - [HarmonyPatch(nameof(Mecha.UseWarper))] - public static void UseWarper_Postfix(ref bool __result) - { - __result = true; - } + __result = true; + } - [HarmonyPostfix] - [HarmonyPatch(nameof(Mecha.SetForNewGame))] - public static void SetForNewGame_Postfix(Mecha __instance) - { - int dummyOut; - __instance.coreEnergyCap = 30000000000; - __instance.coreEnergy = 30000000000; - __instance.corePowerGen = 5000000; - __instance.reactorPowerGen = 20000000; - __instance.coreLevel = 5; - __instance.thrusterLevel = 5; - __instance.maxSailSpeed = 2000f; - __instance.maxWarpSpeed = 1000000f; - __instance.walkSpeed = 25f; - __instance.player.package.AddItemStacked(1803, 40, 1, out dummyOut); //add antimatter - __instance.player.package.AddItemStacked(1501, 600, 1, out dummyOut); //add sails - __instance.player.package.AddItemStacked(1503, 60, 1, out dummyOut); //add rockets - __instance.player.package.AddItemStacked(2312, 10, 1, out dummyOut); //add launching silo - __instance.player.package.AddItemStacked(2210, 10, 1, out dummyOut); //add artifical sun - __instance.player.package.AddItemStacked(2311, 20, 1, out dummyOut); //add railgun - __instance.player.package.AddItemStacked(2001, 600, 1, out dummyOut); //add MK3 belts - __instance.player.package.AddItemStacked(2002, 600, 1, out dummyOut); //add MK3 belts - __instance.player.package.AddItemStacked(2003, 600, 1, out dummyOut); //add MK3 belts - __instance.player.package.AddItemStacked(2013, 100, 1, out dummyOut); //add MK3 inserters - __instance.player.package.AddItemStacked(2212, 20, 1, out dummyOut); //add satelite sub-station - } + [HarmonyPostfix] + [HarmonyPatch(nameof(Mecha.SetForNewGame))] + public static void SetForNewGame_Postfix(Mecha __instance) + { + int dummyOut; + __instance.coreEnergyCap = 30000000000; + __instance.coreEnergy = 30000000000; + __instance.corePowerGen = 5000000; + __instance.reactorPowerGen = 20000000; + __instance.coreLevel = 5; + __instance.thrusterLevel = 5; + __instance.maxSailSpeed = 2000f; + __instance.maxWarpSpeed = 1000000f; + __instance.walkSpeed = 25f; + __instance.player.package.AddItemStacked(1803, 40, 1, out dummyOut); //add antimatter + __instance.player.package.AddItemStacked(1501, 600, 1, out dummyOut); //add sails + __instance.player.package.AddItemStacked(1503, 60, 1, out dummyOut); //add rockets + __instance.player.package.AddItemStacked(2312, 10, 1, out dummyOut); //add launching silo + __instance.player.package.AddItemStacked(2210, 10, 1, out dummyOut); //add artifical sun + __instance.player.package.AddItemStacked(2311, 20, 1, out dummyOut); //add railgun + __instance.player.package.AddItemStacked(2001, 600, 1, out dummyOut); //add MK3 belts + __instance.player.package.AddItemStacked(2002, 600, 1, out dummyOut); //add MK3 belts + __instance.player.package.AddItemStacked(2003, 600, 1, out dummyOut); //add MK3 belts + __instance.player.package.AddItemStacked(2013, 100, 1, out dummyOut); //add MK3 inserters + __instance.player.package.AddItemStacked(2212, 20, 1, out dummyOut); //add satelite sub-station } +} - [HarmonyPatch(typeof(MechaForge))] - internal class Debug_MechaForge_Patch +[HarmonyPatch(typeof(MechaForge))] +internal class Debug_MechaForge_Patch +{ + [HarmonyPostfix] + [HarmonyPatch(nameof(MechaForge.TryAddTask))] + public static void TryAddTask_Postfix(ref bool __result) { - [HarmonyPostfix] - [HarmonyPatch(nameof(MechaForge.TryAddTask))] - public static void TryAddTask_Postfix(ref bool __result) - { - __result = true; - } + __result = true; + } - [HarmonyPrefix] - [HarmonyPatch(nameof(MechaForge.AddTaskIterate))] - public static bool AddTaskIterate_Prefix(MechaForge __instance, ForgeTask __result, int recipeId, int count) + [HarmonyPrefix] + [HarmonyPatch(nameof(MechaForge.AddTaskIterate))] + public static bool AddTaskIterate_Prefix(MechaForge __instance, ForgeTask __result, int recipeId, int count) + { + var recipe = new ForgeTask(recipeId, count); + int dummyOut; + for (var i = 0; i < recipe.productIds.Length; i++) { - ForgeTask recipe = new ForgeTask(recipeId, count); - int dummyOut; - for (int i = 0; i < recipe.productIds.Length; i++) - { - GameMain.mainPlayer.package.AddItemStacked(recipe.productIds[i], count, 1, out dummyOut); - } - __result = null; - return false; + GameMain.mainPlayer.package.AddItemStacked(recipe.productIds[i], count, 1, out dummyOut); } + __result = null; + return false; } +} - [HarmonyPatch(typeof(UIAdvisorTip))] - internal class Debug_UIAdvisorTip_Patch +[HarmonyPatch(typeof(UIAdvisorTip))] +internal class Debug_UIAdvisorTip_Patch +{ + [HarmonyPrefix] + [HarmonyPatch(nameof(UIAdvisorTip.PlayAdvisorTip))] + public static bool PlayAdvisorTip_Prefix() { - [HarmonyPrefix] - [HarmonyPatch(nameof(UIAdvisorTip.PlayAdvisorTip))] - public static bool PlayAdvisorTip_Prefix() - { - return false; - } + return false; + } - [HarmonyPrefix] - [HarmonyPatch(nameof(UIAdvisorTip.RunAdvisorTip))] - public static bool RunAdvisorTip_Prefix() - { - return false; - } + [HarmonyPrefix] + [HarmonyPatch(nameof(UIAdvisorTip.RunAdvisorTip))] + public static bool RunAdvisorTip_Prefix() + { + return false; } +} - [HarmonyPatch(typeof(UITutorialTip))] - internal class Debug_UITutorialTip_Patch +[HarmonyPatch(typeof(UITutorialTip))] +internal class Debug_UITutorialTip_Patch +{ + [HarmonyPrefix] + [HarmonyPatch(nameof(UITutorialTip.PopupTutorialTip))] + public static bool PopupTutorialTip_Prefix() { - [HarmonyPrefix] - [HarmonyPatch(nameof(UITutorialTip.PopupTutorialTip))] - public static bool PopupTutorialTip_Prefix() - { - return false; - } + return false; } +} - [HarmonyPatch(typeof(UIMechaEditor))] - internal class Debug_UIMechaEditor_Patch +[HarmonyPatch(typeof(UIMechaEditor))] +internal class Debug_UIMechaEditor_Patch +{ + [HarmonyPrefix] + [HarmonyPatch(nameof(UIMechaEditor.ApplyMechaAppearance))] + public static bool ApplyMechaAppearance_Prefix(UIMechaEditor __instance) { - [HarmonyPrefix] - [HarmonyPatch(nameof(UIMechaEditor.ApplyMechaAppearance))] - public static bool ApplyMechaAppearance_Prefix(UIMechaEditor __instance) - { - __instance.mecha.diyAppearance.CopyTo(__instance.mecha.appearance); - __instance.player.mechaArmorModel.RefreshAllPartObjects(); - __instance.player.mechaArmorModel.RefreshAllBoneObjects(); - __instance.mecha.appearance.NotifyAllEvents(); - __instance.CalcMechaProperty(); + __instance.mecha.diyAppearance.CopyTo(__instance.mecha.appearance); + __instance.player.mechaArmorModel.RefreshAllPartObjects(); + __instance.player.mechaArmorModel.RefreshAllBoneObjects(); + __instance.mecha.appearance.NotifyAllEvents(); + __instance.CalcMechaProperty(); - return false; - } + return false; } +} - [HarmonyPatch(typeof(UIMechaMatsGroup))] - internal class Debug_UIMechaMatsGroup_Patch +[HarmonyPatch(typeof(UIMechaMatsGroup))] +internal class Debug_UIMechaMatsGroup_Patch +{ + [HarmonyPrefix] + [HarmonyPatch(nameof(UIMechaMatsGroup.TestMaterialEnough))] + public static bool TestMaterialsEnough_Prefix(UIMechaMatsGroup __instance, ref bool __result) { - [HarmonyPrefix] - [HarmonyPatch(nameof(UIMechaMatsGroup.TestMaterialEnough))] - public static bool TestMaterialsEnough_Prefix(UIMechaMatsGroup __instance, ref bool __result) - { - __result = true; - return false; - } + __result = true; + return false; } } #endif diff --git a/NebulaPatcher/Patches/Dynamic/Dedicated_Server_Patch.cs b/NebulaPatcher/Patches/Dynamic/Dedicated_Server_Patch.cs index 73464d805..e6de506fd 100644 --- a/NebulaPatcher/Patches/Dynamic/Dedicated_Server_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/Dedicated_Server_Patch.cs @@ -1,143 +1,152 @@ -using HarmonyLib; -using NebulaModel; -using NebulaModel.Logger; -using NebulaWorld; +#region + using System; using System.Collections.Generic; using System.Reflection.Emit; +using HarmonyLib; +using NebulaModel; +using NebulaModel.Logger; +using NebulaWorld; using UnityEngine; +using UnityEngine.UI; +using Object = UnityEngine.Object; + +#endregion + +namespace NebulaPatcher.Patches.Dynamic; -namespace NebulaPatcher.Patches.Dynamic +// Collections of patches that need to make game run in nographics mode +// This part only get patch when Multiplayer.IsDedicated is true +internal class Dedicated_Server_Patch { - // Collections of patches that need to make game run in nographics mode - // This part only get patch when Multiplayer.IsDedicated is true - internal class Dedicated_Server_Patch + [HarmonyPostfix] + [HarmonyPatch(typeof(GameMain), nameof(GameMain.Begin))] + public static void GameMainBegin_Postfix() { - [HarmonyPostfix] - [HarmonyPatch(typeof(GameMain), nameof(GameMain.Begin))] - public static void GameMainBegin_Postfix() + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) + Log.Info($">> RemoteAccessEnabled: {Config.Options.RemoteAccessEnabled}"); + Log.Info(">> RemoteAccessPassword: " + + (string.IsNullOrWhiteSpace(Config.Options.RemoteAccessPassword) ? "None" : "Protected")); + Log.Info($">> AutoPauseEnabled: {Config.Options.AutoPauseEnabled}"); + if (Config.Options.AutoPauseEnabled) { - Log.Info($">> RemoteAccessEnabled: {Config.Options.RemoteAccessEnabled}"); - Log.Info($">> RemoteAccessPassword: " + (string.IsNullOrWhiteSpace(Config.Options.RemoteAccessPassword) ? "None" : "Protected")); - Log.Info($">> AutoPauseEnabled: {Config.Options.AutoPauseEnabled}"); - if (Config.Options.AutoPauseEnabled) - { - GameMain.Pause(); - } + GameMain.Pause(); } } + } - // Stop game rendering - [HarmonyPrefix] - [HarmonyPatch(typeof(GameData), nameof(GameData.OnDraw))] - [HarmonyPatch(typeof(GameData), nameof(GameData.OnPostDraw))] - [HarmonyPatch(typeof(FactoryModel), nameof(FactoryModel.LateUpdate))] - public static bool OnDraw_Prefix() - { - return false; - } + // Stop game rendering + [HarmonyPrefix] + [HarmonyPatch(typeof(GameData), nameof(GameData.OnDraw))] + [HarmonyPatch(typeof(GameData), nameof(GameData.OnPostDraw))] + [HarmonyPatch(typeof(FactoryModel), nameof(FactoryModel.LateUpdate))] + public static bool OnDraw_Prefix() + { + return false; + } - [HarmonyPrefix] - [HarmonyPatch(typeof(GameMain), nameof(GameMain.LateUpdate))] - public static bool OnLateUpdate() - { - // Because UIRoot._LateUpdate() doesn't run in headless mode, we need this to enable autosave - UIRoot.instance.uiGame.autoSave._LateUpdate(); - return false; - } + [HarmonyPrefix] + [HarmonyPatch(typeof(GameMain), nameof(GameMain.LateUpdate))] + public static bool OnLateUpdate() + { + // Because UIRoot._LateUpdate() doesn't run in headless mode, we need this to enable autosave + UIRoot.instance.uiGame.autoSave._LateUpdate(); + return false; + } - // Destory gameObject so Update() won't execute - [HarmonyPrefix] - [HarmonyPatch(typeof(PlanetAtmoBlur), nameof(PlanetAtmoBlur.Start))] - public static bool PlanetAtmoBlur_Start(PlanetAtmoBlur __instance) - { - UnityEngine.Object.Destroy(__instance.gameObject); - return false; - } + // Destory gameObject so Update() won't execute + [HarmonyPrefix] + [HarmonyPatch(typeof(PlanetAtmoBlur), nameof(PlanetAtmoBlur.Start))] + public static bool PlanetAtmoBlur_Start(PlanetAtmoBlur __instance) + { + Object.Destroy(__instance.gameObject); + return false; + } - // RenderTexture is not support, so disable all functions using the constructor - [HarmonyPrefix] - [HarmonyPatch(typeof(DysonMapCamera), nameof(DysonMapCamera.CheckOrCreateRTex))] - [HarmonyPatch(typeof(GameCamera), nameof(GameCamera.CaptureScreenShot), new Type[] { typeof(int), typeof(int) })] // Save won't have a img preview when disable - [HarmonyPatch(typeof(GameCamera), nameof(GameCamera.CaptureScreenShot), new Type[] { typeof(int), typeof(int), typeof(string) })] - [HarmonyPatch(typeof(MechaEditorCamera), nameof(MechaEditorCamera.CheckOrCreateRTex))] - [HarmonyPatch(typeof(UIDysonOrbitPreview), nameof(UIDysonOrbitPreview.CheckOrCreateRTex))] - [HarmonyPatch(typeof(UIMechaMaterialBall), nameof(UIMechaMaterialBall._OnCreate))] - [HarmonyPatch(typeof(UIMechaSaveGroup), nameof(UIMechaSaveGroup._OnCreate))] - [HarmonyPatch(typeof(UIMilkyWay), nameof(UIMilkyWay.CheckOrCreateRTex))] - [HarmonyPatch(typeof(UIMinimap3DControl), nameof(UIMinimap3DControl._OnCreate))] - [HarmonyPatch(typeof(UISplitterWindow), nameof(UISplitterWindow._OnCreate))] - [HarmonyPatch(typeof(UIStarmap), nameof(UIMilkyWay.CheckOrCreateRTex))] - [HarmonyPatch(typeof(TranslucentImageSource), nameof(TranslucentImageSource.CreateNewBlurredScreen))] - static bool RenderTexture_Prefix() - { - return false; - } + // RenderTexture is not support, so disable all functions using the constructor + [HarmonyPrefix] + [HarmonyPatch(typeof(DysonMapCamera), nameof(DysonMapCamera.CheckOrCreateRTex))] + [HarmonyPatch(typeof(GameCamera), nameof(GameCamera.CaptureScreenShot), typeof(int), + typeof(int))] // Save won't have a img preview when disable + [HarmonyPatch(typeof(GameCamera), nameof(GameCamera.CaptureScreenShot), typeof(int), typeof(int), typeof(string))] + [HarmonyPatch(typeof(MechaEditorCamera), nameof(MechaEditorCamera.CheckOrCreateRTex))] + [HarmonyPatch(typeof(UIDysonOrbitPreview), nameof(UIDysonOrbitPreview.CheckOrCreateRTex))] + [HarmonyPatch(typeof(UIMechaMaterialBall), nameof(UIMechaMaterialBall._OnCreate))] + [HarmonyPatch(typeof(UIMechaSaveGroup), nameof(UIMechaSaveGroup._OnCreate))] + [HarmonyPatch(typeof(UIMilkyWay), nameof(UIMilkyWay.CheckOrCreateRTex))] + [HarmonyPatch(typeof(UIMinimap3DControl), nameof(UIMinimap3DControl._OnCreate))] + [HarmonyPatch(typeof(UISplitterWindow), nameof(UISplitterWindow._OnCreate))] + [HarmonyPatch(typeof(UIStarmap), nameof(UIMilkyWay.CheckOrCreateRTex))] + [HarmonyPatch(typeof(TranslucentImageSource), nameof(TranslucentImageSource.CreateNewBlurredScreen))] + private static bool RenderTexture_Prefix() + { + return false; + } - [HarmonyPrefix] - [HarmonyPatch(typeof(ComputeShader), nameof(ComputeShader.FindKernel))] - [HarmonyPatch(typeof(ComputeShader), nameof(ComputeShader.GetKernelThreadGroupSizes))] - [HarmonyPatch(typeof(ComputeShader), nameof(ComputeShader.Dispatch))] - public static bool ComputeShader_Prefix() - { - return false; - } + [HarmonyPrefix] + [HarmonyPatch(typeof(ComputeShader), nameof(ComputeShader.FindKernel))] + [HarmonyPatch(typeof(ComputeShader), nameof(ComputeShader.GetKernelThreadGroupSizes))] + [HarmonyPatch(typeof(ComputeShader), nameof(ComputeShader.Dispatch))] + public static bool ComputeShader_Prefix() + { + return false; + } - [HarmonyPrefix] - [HarmonyPatch(typeof(ComputeBuffer), nameof(ComputeBuffer.SetData), new Type[] { typeof(Array) })] - [HarmonyPatch(typeof(ComputeBuffer), nameof(ComputeBuffer.GetData), new Type[] { typeof(Array), typeof(int), typeof(int), typeof(int) })] //DysonSwarm.Export - public static bool ComputeBuffer_Prefix() + [HarmonyPrefix] + [HarmonyPatch(typeof(ComputeBuffer), nameof(ComputeBuffer.SetData), typeof(Array))] + [HarmonyPatch(typeof(ComputeBuffer), nameof(ComputeBuffer.GetData), typeof(Array), typeof(int), typeof(int), + typeof(int))] //DysonSwarm.Export + public static bool ComputeBuffer_Prefix() + { + return false; + } + + [HarmonyTranspiler] + [HarmonyPatch(typeof(DysonSwarm), nameof(DysonSwarm.GameTick))] + private static IEnumerable DysonSwarmGameTick_Transpiler(IEnumerable instructions) + { + // Remove first part of the functions about computeShader + // (this.computeShader.Set..., this.Dispatch_UpdateVel, this.Dispatch_UpdatePos) + try { - return false; + var matcher = new CodeMatcher(instructions) + .MatchForward(false, + new CodeMatch(OpCodes.Call, AccessTools.Method(typeof(DysonSwarm), nameof(DysonSwarm.Dispatch_UpdatePos)))); + var num = matcher.Pos + 1; + matcher.Start() + .RemoveInstructions(num); + return matcher.InstructionEnumeration(); } - - [HarmonyTranspiler] - [HarmonyPatch(typeof(DysonSwarm), nameof(DysonSwarm.GameTick))] - private static IEnumerable DysonSwarmGameTick_Transpiler(IEnumerable instructions) + catch { - // Remove first part of the functions about computeShader - // (this.computeShader.Set..., this.Dispatch_UpdateVel, this.Dispatch_UpdatePos) - try - { - CodeMatcher matcher = new CodeMatcher(instructions) - .MatchForward(false, new CodeMatch(OpCodes.Call, AccessTools.Method(typeof(DysonSwarm), nameof(DysonSwarm.Dispatch_UpdatePos)))); - int num = matcher.Pos + 1; - matcher.Start() - .RemoveInstructions(num); - return matcher.InstructionEnumeration(); - } - catch - { - Log.Error("DysonSwarmGameTick_Transpiler failed. Mod version not compatible with game version."); - return instructions; - } + Log.Error("DysonSwarmGameTick_Transpiler failed. Mod version not compatible with game version."); + return instructions; } + } - [HarmonyPrefix] - [HarmonyPatch(typeof(DysonSwarm), nameof(DysonSwarm.SetSailCapacity))] - public static void DysonSwarmSetSailCapacity_Prefix(DysonSwarm __instance) + [HarmonyPrefix] + [HarmonyPatch(typeof(DysonSwarm), nameof(DysonSwarm.SetSailCapacity))] + public static void DysonSwarmSetSailCapacity_Prefix(DysonSwarm __instance) + { + // Skip the part of computeShader in if (this.swarmBuffer != null) + // (this.computeShader.SetBuffer(...), this.Dispatch_BlitBuffer()) + if (__instance.swarmBuffer != null) { - // Skip the part of computeShader in if (this.swarmBuffer != null) - // (this.computeShader.SetBuffer(...), this.Dispatch_BlitBuffer()) - if (__instance.swarmBuffer != null) - { - __instance.swarmBuffer.Release(); - __instance.swarmInfoBuffer.Release(); - __instance.swarmBuffer = null; - __instance.swarmInfoBuffer = null; - } + __instance.swarmBuffer.Release(); + __instance.swarmInfoBuffer.Release(); + __instance.swarmBuffer = null; + __instance.swarmInfoBuffer = null; } + } - // From user report - [HarmonyPrefix] - [HarmonyPatch(typeof(UnityEngine.UI.Graphic), nameof(UnityEngine.UI.Graphic.DoMeshGeneration))] - [HarmonyPatch(typeof(UnityEngine.UI.Graphic), nameof(UnityEngine.UI.Graphic.DoLegacyMeshGeneration))] - public static bool DoMeshGeneration_Prefix() - { - return false; - } + // From user report + [HarmonyPrefix] + [HarmonyPatch(typeof(Graphic), nameof(Graphic.DoMeshGeneration))] + [HarmonyPatch(typeof(Graphic), nameof(Graphic.DoLegacyMeshGeneration))] + public static bool DoMeshGeneration_Prefix() + { + return false; } } diff --git a/NebulaPatcher/Patches/Dynamic/DysonBlueprintData_Patch.cs b/NebulaPatcher/Patches/Dynamic/DysonBlueprintData_Patch.cs index ce3448048..74e6d2769 100644 --- a/NebulaPatcher/Patches/Dynamic/DysonBlueprintData_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/DysonBlueprintData_Patch.cs @@ -1,39 +1,42 @@ -using HarmonyLib; -using NebulaAPI; +#region + +using HarmonyLib; using NebulaModel.Packets.Universe; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(DysonBlueprintData))] +internal class DysonBlueprintData_Patch { - [HarmonyPatch(typeof(DysonBlueprintData))] - internal class DysonBlueprintData_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(DysonBlueprintData.FromBase64String))] + public static void FromBase64String_Prefix() { - [HarmonyPrefix] - [HarmonyPatch(nameof(DysonBlueprintData.FromBase64String))] - public static void FromBase64String_Prefix() + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) - { - Multiplayer.Session.DysonSpheres.InBlueprint = true; - } + Multiplayer.Session.DysonSpheres.InBlueprint = true; } + } #pragma warning disable Harmony003 - [HarmonyPostfix] - [HarmonyPatch(nameof(DysonBlueprintData.FromBase64String))] - public static void FromBase64String_Postfix(DysonBlueprintDataIOError __result, string str64Data, EDysonBlueprintType requestType, DysonSphere sphere, DysonSphereLayer layer) + [HarmonyPostfix] + [HarmonyPatch(nameof(DysonBlueprintData.FromBase64String))] + public static void FromBase64String_Postfix(DysonBlueprintDataIOError __result, string str64Data, + EDysonBlueprintType requestType, DysonSphere sphere, DysonSphereLayer layer) + { + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) + Multiplayer.Session.DysonSpheres.InBlueprint = false; + if (!Multiplayer.Session.DysonSpheres.IsIncomingRequest && __result == DysonBlueprintDataIOError.OK) { - Multiplayer.Session.DysonSpheres.InBlueprint = false; - if (!Multiplayer.Session.DysonSpheres.IsIncomingRequest && __result == DysonBlueprintDataIOError.OK) - { - int starIndex = sphere.starData.index; - int layerId = layer?.id ?? -1; - Multiplayer.Session.Network.SendPacket(new DysonBlueprintPacket(starIndex, layerId, requestType, str64Data)); - } + var starIndex = sphere.starData.index; + var layerId = layer?.id ?? -1; + Multiplayer.Session.Network.SendPacket(new DysonBlueprintPacket(starIndex, layerId, requestType, str64Data)); } } -#pragma warning restore Harmony003 } +#pragma warning restore Harmony003 } diff --git a/NebulaPatcher/Patches/Dynamic/DysonSphereLayer_Patch.cs b/NebulaPatcher/Patches/Dynamic/DysonSphereLayer_Patch.cs index 82fc8d3b5..ece63be39 100644 --- a/NebulaPatcher/Patches/Dynamic/DysonSphereLayer_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/DysonSphereLayer_Patch.cs @@ -1,89 +1,105 @@ -using HarmonyLib; +#region + +using System.Collections.Generic; +using HarmonyLib; using NebulaAPI; using NebulaModel.Packets.Universe; using NebulaWorld; -using System.Collections.Generic; using UnityEngine; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(DysonSphereLayer))] +internal class DysonSphereLayer_Patch { - [HarmonyPatch(typeof(DysonSphereLayer))] - internal class DysonSphereLayer_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(DysonSphereLayer.NewDysonNode))] + public static void NewDysonNode_Prefix(DysonSphereLayer __instance, int protoId, Vector3 pos) { - [HarmonyPrefix] - [HarmonyPatch(nameof(DysonSphereLayer.NewDysonNode))] - public static void NewDysonNode_Prefix(DysonSphereLayer __instance, int protoId, Vector3 pos) + if (Multiplayer.IsActive && !Multiplayer.Session.DysonSpheres.IsIncomingRequest) { - if (Multiplayer.IsActive && !Multiplayer.Session.DysonSpheres.IsIncomingRequest) - { - int nodeId = __instance.nodeRecycleCursor > 0 ? __instance.nodeRecycle[__instance.nodeRecycleCursor - 1] : __instance.nodeCursor; - Multiplayer.Session.Network.SendPacket(new DysonSphereAddNodePacket(__instance.starData.index, __instance.id, nodeId, protoId, new Float3(pos))); - } + var nodeId = __instance.nodeRecycleCursor > 0 + ? __instance.nodeRecycle[__instance.nodeRecycleCursor - 1] + : __instance.nodeCursor; + Multiplayer.Session.Network.SendPacket(new DysonSphereAddNodePacket(__instance.starData.index, __instance.id, + nodeId, protoId, new Float3(pos))); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(DysonSphereLayer.NewDysonFrame))] - public static void NewDysonFrame_Prefix(DysonSphereLayer __instance, int protoId, int nodeAId, int nodeBId, bool euler) + [HarmonyPrefix] + [HarmonyPatch(nameof(DysonSphereLayer.NewDysonFrame))] + public static void NewDysonFrame_Prefix(DysonSphereLayer __instance, int protoId, int nodeAId, int nodeBId, bool euler) + { + if (Multiplayer.IsActive && !Multiplayer.Session.DysonSpheres.IsIncomingRequest) { - if (Multiplayer.IsActive && !Multiplayer.Session.DysonSpheres.IsIncomingRequest) - { - int frameId = __instance.frameRecycleCursor > 0 ? __instance.frameRecycle[__instance.frameRecycleCursor - 1] : __instance.frameCursor; - Multiplayer.Session.Network.SendPacket(new DysonSphereAddFramePacket(__instance.starData.index, __instance.id, frameId, protoId, nodeAId, nodeBId, euler)); - } + var frameId = __instance.frameRecycleCursor > 0 + ? __instance.frameRecycle[__instance.frameRecycleCursor - 1] + : __instance.frameCursor; + Multiplayer.Session.Network.SendPacket(new DysonSphereAddFramePacket(__instance.starData.index, __instance.id, + frameId, protoId, nodeAId, nodeBId, euler)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(DysonSphereLayer.RemoveDysonFrame))] - public static void RemoveDysonFrame_Prefix(DysonSphereLayer __instance, int frameId) + [HarmonyPrefix] + [HarmonyPatch(nameof(DysonSphereLayer.RemoveDysonFrame))] + public static void RemoveDysonFrame_Prefix(DysonSphereLayer __instance, int frameId) + { + if (Multiplayer.IsActive && !Multiplayer.Session.DysonSpheres.IsIncomingRequest) { - if (Multiplayer.IsActive && !Multiplayer.Session.DysonSpheres.IsIncomingRequest) - { - Multiplayer.Session.Network.SendPacket(new DysonSphereRemoveFramePacket(__instance.starData.index, __instance.id, frameId)); - } + Multiplayer.Session.Network.SendPacket(new DysonSphereRemoveFramePacket(__instance.starData.index, __instance.id, + frameId)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(DysonSphereLayer.RemoveDysonNode))] - public static void RemoveDysonNode_Prefix(DysonSphereLayer __instance, int nodeId) + [HarmonyPrefix] + [HarmonyPatch(nameof(DysonSphereLayer.RemoveDysonNode))] + public static void RemoveDysonNode_Prefix(DysonSphereLayer __instance, int nodeId) + { + if (Multiplayer.IsActive && !Multiplayer.Session.DysonSpheres.IsIncomingRequest) { - if (Multiplayer.IsActive && !Multiplayer.Session.DysonSpheres.IsIncomingRequest) - { - Multiplayer.Session.Network.SendPacket(new DysonSphereRemoveNodePacket(__instance.starData.index, __instance.id, nodeId)); - } + Multiplayer.Session.Network.SendPacket(new DysonSphereRemoveNodePacket(__instance.starData.index, __instance.id, + nodeId)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(DysonSphereLayer.NewDysonShell))] - public static void NewDysonShell_Prefix(DysonSphereLayer __instance, int protoId, List nodeIds) + [HarmonyPrefix] + [HarmonyPatch(nameof(DysonSphereLayer.NewDysonShell))] + public static void NewDysonShell_Prefix(DysonSphereLayer __instance, int protoId, List nodeIds) + { + if (Multiplayer.IsActive && !Multiplayer.Session.DysonSpheres.IsIncomingRequest) { - if (Multiplayer.IsActive && !Multiplayer.Session.DysonSpheres.IsIncomingRequest) - { - int shellId = __instance.shellRecycleCursor > 0 ? __instance.shellRecycle[__instance.shellRecycleCursor - 1] : __instance.shellCursor; - Multiplayer.Session.Network.SendPacket(new DysonSphereAddShellPacket(__instance.starData.index, __instance.id, shellId, protoId, nodeIds)); - } + var shellId = __instance.shellRecycleCursor > 0 + ? __instance.shellRecycle[__instance.shellRecycleCursor - 1] + : __instance.shellCursor; + Multiplayer.Session.Network.SendPacket(new DysonSphereAddShellPacket(__instance.starData.index, __instance.id, + shellId, protoId, nodeIds)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(DysonSphereLayer.RemoveDysonShell))] - public static void RemoveDysonShell_Prefix(DysonSphereLayer __instance, int shellId) + [HarmonyPrefix] + [HarmonyPatch(nameof(DysonSphereLayer.RemoveDysonShell))] + public static void RemoveDysonShell_Prefix(DysonSphereLayer __instance, int shellId) + { + if (Multiplayer.IsActive && !Multiplayer.Session.DysonSpheres.IsIncomingRequest) { - if (Multiplayer.IsActive && !Multiplayer.Session.DysonSpheres.IsIncomingRequest) - { - Multiplayer.Session.Network.SendPacket(new DysonSphereRemoveShellPacket(__instance.starData.index, __instance.id, shellId)); - } + Multiplayer.Session.Network.SendPacket(new DysonSphereRemoveShellPacket(__instance.starData.index, __instance.id, + shellId)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(DysonSphereLayer.InitOrbitRotation))] - public static void InitOrbitRotation_Prefix(DysonSphereLayer __instance, Quaternion __1) + [HarmonyPrefix] + [HarmonyPatch(nameof(DysonSphereLayer.InitOrbitRotation))] + public static void InitOrbitRotation_Prefix(DysonSphereLayer __instance, Quaternion __1) + { + if (Multiplayer.IsActive && !Multiplayer.Session.DysonSpheres.IsIncomingRequest) { - if (Multiplayer.IsActive && !Multiplayer.Session.DysonSpheres.IsIncomingRequest) + //Send only when it's trigger by UIDELayerInfo.OnEditConfirmClick() + if (UIRoot.instance.uiGame.dysonEditor.controlPanel.inspector.layerInfo.orbitEditMode) { - //Send only when it's trigger by UIDELayerInfo.OnEditConfirmClick() - if (UIRoot.instance.uiGame.dysonEditor.controlPanel.inspector.layerInfo.orbitEditMode) - { - Multiplayer.Session.Network.SendPacket(new DysonSphereEditLayerPacket(__instance.starData.index, __instance.id, __1)); - } + Multiplayer.Session.Network.SendPacket(new DysonSphereEditLayerPacket(__instance.starData.index, __instance.id, + __1)); } } } diff --git a/NebulaPatcher/Patches/Dynamic/DysonSphere_Patch.cs b/NebulaPatcher/Patches/Dynamic/DysonSphere_Patch.cs index 0fe89d9fa..67bee960a 100644 --- a/NebulaPatcher/Patches/Dynamic/DysonSphere_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/DysonSphere_Patch.cs @@ -1,97 +1,102 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaModel.Packets.Universe; using NebulaWorld; -using System; using UnityEngine; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(DysonSphere))] +internal class DysonSphere_Patch { - [HarmonyPatch(typeof(DysonSphere))] - internal class DysonSphere_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(DysonSphere.BeforeGameTick))] + public static bool BeforeGameTick_Prefix(DysonSphere __instance, long times) { - [HarmonyPrefix] - [HarmonyPatch(nameof(DysonSphere.BeforeGameTick))] - public static bool BeforeGameTick_Prefix(DysonSphere __instance, long times) + if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) { - if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) - { - return true; - } - //Update swarm and layer energy generation stats every 120 frames - if (times % 120 == 0) + return true; + } + //Update swarm and layer energy generation stats every 120 frames + if (times % 120 == 0) + { + __instance.swarm.energyGenCurrentTick = __instance.swarm.sailCount * __instance.energyGenPerSail; + for (var i = 0; i < 10; i++) { - __instance.swarm.energyGenCurrentTick = __instance.swarm.sailCount * __instance.energyGenPerSail; - for (int i = 0; i < 10; i++) + var dysonSphereLayer = __instance.layersSorted[i]; + if (dysonSphereLayer != null) { - DysonSphereLayer dysonSphereLayer = __instance.layersSorted[i]; - if (dysonSphereLayer != null) + dysonSphereLayer.energyGenCurrentTick = 0L; + var nodePool = dysonSphereLayer.nodePool; + var shellPool = dysonSphereLayer.shellPool; + for (var j = 1; j < dysonSphereLayer.nodeCursor; j++) { - dysonSphereLayer.energyGenCurrentTick = 0L; - DysonNode[] nodePool = dysonSphereLayer.nodePool; - DysonShell[] shellPool = dysonSphereLayer.shellPool; - for (int j = 1; j < dysonSphereLayer.nodeCursor; j++) + if (nodePool[j] != null && nodePool[j].id == j) { - if (nodePool[j] != null && nodePool[j].id == j) - { - dysonSphereLayer.energyGenCurrentTick += nodePool[j].EnergyGenCurrentTick(__instance.energyGenPerNode, __instance.energyGenPerFrame, 0L); - } + dysonSphereLayer.energyGenCurrentTick += nodePool[j] + .EnergyGenCurrentTick(__instance.energyGenPerNode, __instance.energyGenPerFrame, 0L); } - for (int k = 1; k < dysonSphereLayer.shellCursor; k++) + } + for (var k = 1; k < dysonSphereLayer.shellCursor; k++) + { + if (shellPool[k] != null && shellPool[k].id == k) { - if (shellPool[k] != null && shellPool[k].id == k) - { - dysonSphereLayer.energyGenCurrentTick += shellPool[k].cellPoint * __instance.energyGenPerShell; - } + dysonSphereLayer.energyGenCurrentTick += shellPool[k].cellPoint * __instance.energyGenPerShell; } } } } - //Sync other Dyson sphere status related to ray receivers on client side by DysonSphereStatusPacket - return false; } + //Sync other Dyson sphere status related to ray receivers on client side by DysonSphereStatusPacket + return false; + } - [HarmonyPrefix] - [HarmonyPatch(nameof(DysonSphere.AddLayer))] - public static void AddLayer_Postfix(DysonSphere __instance, float orbitRadius, Quaternion orbitRotation, float orbitAngularSpeed) + [HarmonyPrefix] + [HarmonyPatch(nameof(DysonSphere.AddLayer))] + public static void AddLayer_Postfix(DysonSphere __instance, float orbitRadius, Quaternion orbitRotation, + float orbitAngularSpeed) + { + if (!Multiplayer.IsActive) { - if (!Multiplayer.IsActive) - { - return; - } - //If local is the author and not in the process of importing blueprint - if (!Multiplayer.Session.DysonSpheres.IsIncomingRequest && !Multiplayer.Session.DysonSpheres.InBlueprint) - { - Multiplayer.Session.Network.SendPacket(new DysonSphereAddLayerPacket(__instance.starData.index, __instance.QueryLayerId(), orbitRadius, orbitRotation, orbitAngularSpeed)); - } + return; + } + //If local is the author and not in the process of importing blueprint + if (!Multiplayer.Session.DysonSpheres.IsIncomingRequest && !Multiplayer.Session.DysonSpheres.InBlueprint) + { + Multiplayer.Session.Network.SendPacket(new DysonSphereAddLayerPacket(__instance.starData.index, + __instance.QueryLayerId(), orbitRadius, orbitRotation, orbitAngularSpeed)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(DysonSphere.RemoveLayer), new Type[] { typeof(int) })] - public static void RemoveLayer_Prefix(DysonSphere __instance, int id) + [HarmonyPrefix] + [HarmonyPatch(nameof(DysonSphere.RemoveLayer), typeof(int))] + public static void RemoveLayer_Prefix(DysonSphere __instance, int id) + { + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) - { - RemoveLayer(id, __instance.starData.index); - } + RemoveLayer(id, __instance.starData.index); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(DysonSphere.RemoveLayer), new Type[] { typeof(DysonSphereLayer) })] - public static void RemoveLayer_Prefix2(DysonSphere __instance, DysonSphereLayer layer) + [HarmonyPrefix] + [HarmonyPatch(nameof(DysonSphere.RemoveLayer), typeof(DysonSphereLayer))] + public static void RemoveLayer_Prefix2(DysonSphere __instance, DysonSphereLayer layer) + { + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) - { - RemoveLayer(layer.id, __instance.starData.index); - } + RemoveLayer(layer.id, __instance.starData.index); } + } - public static void RemoveLayer(int id, int starIndex) + public static void RemoveLayer(int id, int starIndex) + { + //If local is the author and not in the process of importing blueprint + if (!Multiplayer.Session.DysonSpheres.IsIncomingRequest && !Multiplayer.Session.DysonSpheres.InBlueprint) { - //If local is the author and not in the process of importing blueprint - if (!Multiplayer.Session.DysonSpheres.IsIncomingRequest && !Multiplayer.Session.DysonSpheres.InBlueprint) - { - Multiplayer.Session.Network.SendPacket(new DysonSphereRemoveLayerPacket(starIndex, id)); - } + Multiplayer.Session.Network.SendPacket(new DysonSphereRemoveLayerPacket(starIndex, id)); } } } diff --git a/NebulaPatcher/Patches/Dynamic/DysonSwarm_Patch.cs b/NebulaPatcher/Patches/Dynamic/DysonSwarm_Patch.cs index 06adc843a..ac34dddbc 100644 --- a/NebulaPatcher/Patches/Dynamic/DysonSwarm_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/DysonSwarm_Patch.cs @@ -1,98 +1,107 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaModel.Packets.Universe; using NebulaWorld; +using NebulaWorld.Universe; using UnityEngine; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(DysonSwarm))] +internal class DysonSwarm_Patch { - [HarmonyPatch(typeof(DysonSwarm))] - internal class DysonSwarm_Patch + private static Vector4 storedHsva; + + [HarmonyPrefix] + [HarmonyPatch(nameof(DysonSwarm.NewOrbit))] + public static void NewOrbit_Prefix(DysonSwarm __instance, float radius, Quaternion rotation) { - [HarmonyPrefix] - [HarmonyPatch(nameof(DysonSwarm.NewOrbit))] - public static void NewOrbit_Prefix(DysonSwarm __instance, float radius, Quaternion rotation) + if (!Multiplayer.IsActive) { - if (!Multiplayer.IsActive) - { - return; - } - //If local is the author and not in the process of importing blueprint - if (!Multiplayer.Session.DysonSpheres.IncomingDysonSwarmPacket && !Multiplayer.Session.DysonSpheres.InBlueprint) - { - int orbitId = NebulaWorld.Universe.DysonSphereManager.QueryOrbitId(__instance); - Multiplayer.Session.Network.SendPacket(new DysonSwarmAddOrbitPacket(__instance.starData.index, orbitId, radius, rotation)); - } + return; } - - [HarmonyPrefix] - [HarmonyPatch(nameof(DysonSwarm.RemoveOrbit))] - public static void RemoveOrbit_Prefix(DysonSwarm __instance, int orbitId) + //If local is the author and not in the process of importing blueprint + if (!Multiplayer.Session.DysonSpheres.IncomingDysonSwarmPacket && !Multiplayer.Session.DysonSpheres.InBlueprint) { - if (!Multiplayer.IsActive) - { - return; - } - //If local is the author and not in the process of importing blueprint - if (!Multiplayer.Session.DysonSpheres.IncomingDysonSwarmPacket && !Multiplayer.Session.DysonSpheres.InBlueprint) - { - Multiplayer.Session.Network.SendPacket(new DysonSwarmRemoveOrbitPacket(__instance.starData.index, orbitId, SwarmRemoveOrbitEvent.Remove)); - } + var orbitId = DysonSphereManager.QueryOrbitId(__instance); + Multiplayer.Session.Network.SendPacket(new DysonSwarmAddOrbitPacket(__instance.starData.index, orbitId, radius, + rotation)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(DysonSwarm.SetOrbitEnable))] - public static void SetOrbitEnable_Prefix(DysonSwarm __instance, int orbitId, bool enabled) + [HarmonyPrefix] + [HarmonyPatch(nameof(DysonSwarm.RemoveOrbit))] + public static void RemoveOrbit_Prefix(DysonSwarm __instance, int orbitId) + { + if (!Multiplayer.IsActive) { - if (!Multiplayer.IsActive) - { - return; - } - //Notify others that orbit for Dyson Swarm was enabled/disabled - if (!Multiplayer.Session.DysonSpheres.IncomingDysonSwarmPacket) - { - Multiplayer.Session.Network.SendPacket(new DysonSwarmRemoveOrbitPacket(__instance.starData.index, orbitId, enabled ? SwarmRemoveOrbitEvent.Enable : SwarmRemoveOrbitEvent.Disable)); - } + return; + } + //If local is the author and not in the process of importing blueprint + if (!Multiplayer.Session.DysonSpheres.IncomingDysonSwarmPacket && !Multiplayer.Session.DysonSpheres.InBlueprint) + { + Multiplayer.Session.Network.SendPacket(new DysonSwarmRemoveOrbitPacket(__instance.starData.index, orbitId, + SwarmRemoveOrbitEvent.Remove)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(DysonSwarm.RemoveSailsByOrbit))] - public static void RemoveSailsByOrbit_Prefix(DysonSwarm __instance, int orbitId) + [HarmonyPrefix] + [HarmonyPatch(nameof(DysonSwarm.SetOrbitEnable))] + public static void SetOrbitEnable_Prefix(DysonSwarm __instance, int orbitId, bool enabled) + { + if (!Multiplayer.IsActive) { - if (!Multiplayer.IsActive) - { - return; - } - // Notify others about manual sails cleaning. - // In DysonSwarm.GameTick() it will automatically clean every 21600 ticks - if (!Multiplayer.Session.DysonSpheres.IncomingDysonSwarmPacket && GameMain.gameTick % 21600L != 0L) - { - Multiplayer.Session.Network.SendPacket(new DysonSwarmRemoveOrbitPacket(__instance.starData.index, orbitId, SwarmRemoveOrbitEvent.RemoveSails)); - } + return; + } + //Notify others that orbit for Dyson Swarm was enabled/disabled + if (!Multiplayer.Session.DysonSpheres.IncomingDysonSwarmPacket) + { + Multiplayer.Session.Network.SendPacket(new DysonSwarmRemoveOrbitPacket(__instance.starData.index, orbitId, + enabled ? SwarmRemoveOrbitEvent.Enable : SwarmRemoveOrbitEvent.Disable)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(DysonSwarm.EditOrbit))] - public static void EditOrbit_Prefix(DysonSwarm __instance, int orbitId, float radius, Quaternion rotation) + [HarmonyPrefix] + [HarmonyPatch(nameof(DysonSwarm.RemoveSailsByOrbit))] + public static void RemoveSailsByOrbit_Prefix(DysonSwarm __instance, int orbitId) + { + if (!Multiplayer.IsActive) { - if (Multiplayer.IsActive && !Multiplayer.Session.DysonSpheres.IncomingDysonSwarmPacket) - { - Multiplayer.Session.Network.SendPacket(new DysonSwarmEditOrbitPacket(__instance.starData.index, orbitId, radius, rotation)); - } + return; } + // Notify others about manual sails cleaning. + // In DysonSwarm.GameTick() it will automatically clean every 21600 ticks + if (!Multiplayer.Session.DysonSpheres.IncomingDysonSwarmPacket && GameMain.gameTick % 21600L != 0L) + { + Multiplayer.Session.Network.SendPacket(new DysonSwarmRemoveOrbitPacket(__instance.starData.index, orbitId, + SwarmRemoveOrbitEvent.RemoveSails)); + } + } - static Vector4 storedHsva = default; + [HarmonyPrefix] + [HarmonyPatch(nameof(DysonSwarm.EditOrbit))] + public static void EditOrbit_Prefix(DysonSwarm __instance, int orbitId, float radius, Quaternion rotation) + { + if (Multiplayer.IsActive && !Multiplayer.Session.DysonSpheres.IncomingDysonSwarmPacket) + { + Multiplayer.Session.Network.SendPacket(new DysonSwarmEditOrbitPacket(__instance.starData.index, orbitId, radius, + rotation)); + } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(DysonSwarm.SetOrbitColor))] - public static void SetOrbitColor_Prefix(DysonSwarm __instance, int orbitId, Vector4 hsva) + [HarmonyPrefix] + [HarmonyPatch(nameof(DysonSwarm.SetOrbitColor))] + public static void SetOrbitColor_Prefix(DysonSwarm __instance, int orbitId, Vector4 hsva) + { + if (Multiplayer.IsActive && !Multiplayer.Session.DysonSpheres.IncomingDysonSwarmPacket) { - if (Multiplayer.IsActive && !Multiplayer.Session.DysonSpheres.IncomingDysonSwarmPacket) + if (storedHsva != hsva) { - if (storedHsva != hsva) - { - Multiplayer.Session.Network.SendPacket(new DysonSwarmEditOrbitPacket(__instance.starData.index, orbitId, hsva)); - storedHsva = hsva; - } + Multiplayer.Session.Network.SendPacket(new DysonSwarmEditOrbitPacket(__instance.starData.index, orbitId, hsva)); + storedHsva = hsva; } } } diff --git a/NebulaPatcher/Patches/Dynamic/EntitySignRenderer_Patch.cs b/NebulaPatcher/Patches/Dynamic/EntitySignRenderer_Patch.cs index 7523e9e8c..3f7cb6a87 100644 --- a/NebulaPatcher/Patches/Dynamic/EntitySignRenderer_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/EntitySignRenderer_Patch.cs @@ -1,23 +1,26 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaModel; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(EntitySignRenderer))] +internal class EntitySignRenderer_Patch { - [HarmonyPatch(typeof(EntitySignRenderer))] - internal class EntitySignRenderer_Patch + [HarmonyPostfix] + [HarmonyPatch(nameof(EntitySignRenderer.Init))] + public static void Init_Postfix() { - [HarmonyPostfix] - [HarmonyPatch(nameof(EntitySignRenderer.Init))] - public static void Init_Postfix() + if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) { - if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) - { - return; - } - - EntitySignRenderer.showIcon = Config.Options.BuildingIconEnabled; - EntitySignRenderer.showSign = Config.Options.BuildingWarningEnabled; + return; } + + EntitySignRenderer.showIcon = Config.Options.BuildingIconEnabled; + EntitySignRenderer.showSign = Config.Options.BuildingWarningEnabled; } } diff --git a/NebulaPatcher/Patches/Dynamic/FactoryAudio_Patch.cs b/NebulaPatcher/Patches/Dynamic/FactoryAudio_Patch.cs index 6151b7093..2b7fa09d1 100644 --- a/NebulaPatcher/Patches/Dynamic/FactoryAudio_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/FactoryAudio_Patch.cs @@ -1,50 +1,53 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaWorld; using UnityEngine; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(FactoryAudio))] +internal class FactoryAudio_Patch { - [HarmonyPatch(typeof(FactoryAudio))] - class FactoryAudio_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(FactoryAudio.OnEntityBuild))] + public static bool OnEntityBuild_Prefix(FactoryAudio __instance, int objId) { - [HarmonyPrefix] - [HarmonyPatch(nameof(FactoryAudio.OnEntityBuild))] - public static bool OnEntityBuild_Prefix(FactoryAudio __instance, int objId) + if (Multiplayer.IsActive && Multiplayer.Session.Factories.IsIncomingRequest.Value && objId > 0) { - if (Multiplayer.IsActive && Multiplayer.Session.Factories.IsIncomingRequest.Value && objId > 0) + var pos = __instance.planet.factory.entityPool[objId].pos; + if ((pos - GameMain.mainPlayer.position).sqrMagnitude > __instance.planet.radius * __instance.planet.radius / 4) { - Vector3 pos = __instance.planet.factory.entityPool[objId].pos; - if ((pos - GameMain.mainPlayer.position).sqrMagnitude > (__instance.planet.radius * __instance.planet.radius / 4)) - { - // Don't make sounds if distance is over half of the planet radius - return false; - } + // Don't make sounds if distance is over half of the planet radius + return false; } - return true; } + return true; + } - [HarmonyPrefix] - [HarmonyPatch(nameof(FactoryAudio.OnEntityDismantle))] - public static bool OnEntityDismantle_Prefix(FactoryAudio __instance, int objId) + [HarmonyPrefix] + [HarmonyPatch(nameof(FactoryAudio.OnEntityDismantle))] + public static bool OnEntityDismantle_Prefix(FactoryAudio __instance, int objId) + { + if (Multiplayer.IsActive && Multiplayer.Session.Factories.IsIncomingRequest.Value) { - if (Multiplayer.IsActive && Multiplayer.Session.Factories.IsIncomingRequest.Value) + Vector3 pos; + if (objId > 0) + { + pos = __instance.planet.factory.entityPool[objId].pos; + } + else + { + pos = __instance.planet.factory.prebuildPool[-objId].pos; + } + if ((pos - GameMain.mainPlayer.position).sqrMagnitude > __instance.planet.radius * __instance.planet.radius / 4) { - Vector3 pos; - if (objId > 0) - { - pos = __instance.planet.factory.entityPool[objId].pos; - } - else - { - pos = __instance.planet.factory.prebuildPool[-objId].pos; - } - if ((pos - GameMain.mainPlayer.position).sqrMagnitude > (__instance.planet.radius * __instance.planet.radius / 4)) - { - // Don't make sounds if distance is over half of the planet radius - return false; - } + // Don't make sounds if distance is over half of the planet radius + return false; } - return true; } + return true; } } diff --git a/NebulaPatcher/Patches/Dynamic/FactoryModel_Patch.cs b/NebulaPatcher/Patches/Dynamic/FactoryModel_Patch.cs index cae9ac46f..a0552814c 100644 --- a/NebulaPatcher/Patches/Dynamic/FactoryModel_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/FactoryModel_Patch.cs @@ -1,23 +1,26 @@ -using HarmonyLib; +#region -namespace NebulaPatcher.Patches.Dynamic +using HarmonyLib; + +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(FactoryModel))] +internal class FactoryModel_Patch { - [HarmonyPatch(typeof(FactoryModel))] - class FactoryModel_Patch + // if a custom birth planet is set we need to unload planet factory data as GameMain.data is destroyed while loading into the game + [HarmonyPrefix] + [HarmonyPatch(nameof(FactoryModel.SetGlobalRenderState))] + public static bool SetGlobalRenderState_Prefix(FactoryModel __instance) { - // if a custom birth planet is set we need to unload planet factory data as GameMain.data is destroyed while loading into the game - [HarmonyPrefix] - [HarmonyPatch(nameof(FactoryModel.SetGlobalRenderState))] - public static bool SetGlobalRenderState_Prefix(FactoryModel __instance) + if (GameMain.mainPlayer == null && GameMain.data == null) { - if (GameMain.mainPlayer == null && GameMain.data == null) - { - // GameMain.data is destroyed while loading into the game, but we had the planets factory loaded in galaxy select when selecting a custom birth planet. - // thus unload the data here to prevent nre spam. - __instance.planet.UnloadFactory(); - return false; - } - return true; + // GameMain.data is destroyed while loading into the game, but we had the planets factory loaded in galaxy select when selecting a custom birth planet. + // thus unload the data here to prevent nre spam. + __instance.planet.UnloadFactory(); + return false; } + return true; } } diff --git a/NebulaPatcher/Patches/Dynamic/FactoryProductionStat_Patch.cs b/NebulaPatcher/Patches/Dynamic/FactoryProductionStat_Patch.cs index f746cbb77..5d68e2ff4 100644 --- a/NebulaPatcher/Patches/Dynamic/FactoryProductionStat_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/FactoryProductionStat_Patch.cs @@ -1,29 +1,32 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(FactoryProductionStat))] +internal class FactoryProductionStat_Patch { - [HarmonyPatch(typeof(FactoryProductionStat))] - internal class FactoryProductionStat_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(FactoryProductionStat.GameTick))] + public static bool GameTick_Prefix(FactoryProductionStat __instance) { - [HarmonyPrefix] - [HarmonyPatch(nameof(FactoryProductionStat.GameTick))] - public static bool GameTick_Prefix(FactoryProductionStat __instance) + //Do not run in single player for host + if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) { - //Do not run in single player for host - if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) - { - return true; - } - - //Multiplayer clients should not include their own calculated statistics - if (!Multiplayer.Session.Statistics.IsIncomingRequest) - { - __instance.ClearRegisters(); - return false; - } - return true; } + + //Multiplayer clients should not include their own calculated statistics + if (!Multiplayer.Session.Statistics.IsIncomingRequest) + { + __instance.ClearRegisters(); + return false; + } + + return true; } } diff --git a/NebulaPatcher/Patches/Dynamic/FactoryStorage_Patch.cs b/NebulaPatcher/Patches/Dynamic/FactoryStorage_Patch.cs index a75e7875d..91440f46c 100644 --- a/NebulaPatcher/Patches/Dynamic/FactoryStorage_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/FactoryStorage_Patch.cs @@ -1,29 +1,32 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(FactoryStorage))] +internal class FactoryStorage_Patch { - [HarmonyPatch(typeof(FactoryStorage))] - internal class FactoryStorage_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(FactoryStorage.GameTick))] + public static void GameTick_Prefix() { - [HarmonyPrefix] - [HarmonyPatch(nameof(FactoryStorage.GameTick))] - public static void GameTick_Prefix() + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) - { - Multiplayer.Session.Storage.IsHumanInput = false; - } + Multiplayer.Session.Storage.IsHumanInput = false; } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(FactoryStorage.GameTick))] - public static void GameTick_Postfix() + [HarmonyPostfix] + [HarmonyPatch(nameof(FactoryStorage.GameTick))] + public static void GameTick_Postfix() + { + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) - { - Multiplayer.Session.Storage.IsHumanInput = true; - } + Multiplayer.Session.Storage.IsHumanInput = true; } } } diff --git a/NebulaPatcher/Patches/Dynamic/GPUInstancingManager_Patch.cs b/NebulaPatcher/Patches/Dynamic/GPUInstancingManager_Patch.cs index 4d96a8952..0061b6292 100644 --- a/NebulaPatcher/Patches/Dynamic/GPUInstancingManager_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/GPUInstancingManager_Patch.cs @@ -1,35 +1,40 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(GPUInstancingManager))] +internal class GPUInstancingManager_Patch { - [HarmonyPatch(typeof(GPUInstancingManager))] - internal class GPUInstancingManager_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(GPUInstancingManager.AddModel))] + public static bool AddModel_Prefix(GPUInstancingManager __instance, ref int __result) { - [HarmonyPrefix] - [HarmonyPatch(nameof(GPUInstancingManager.AddModel))] - public static bool AddModel_Prefix(GPUInstancingManager __instance, ref int __result) + //Do not add model to the GPU queue if player is not on the same planet as building that was build + if (Multiplayer.IsActive && Multiplayer.Session.Factories.EventFactory != null && + Multiplayer.Session.Factories.EventFactory.planet != GameMain.localPlanet) { - //Do not add model to the GPU queue if player is not on the same planet as building that was build - if (Multiplayer.IsActive && Multiplayer.Session.Factories.EventFactory != null && Multiplayer.Session.Factories.EventFactory.planet != GameMain.localPlanet) - { - __result = 0; - return false; - } - return true; + __result = 0; + return false; } + return true; + } - [HarmonyPrefix] - [HarmonyPatch(nameof(GPUInstancingManager.AddPrebuildModel))] - public static bool AddPrebuildModel_Prefix(GPUInstancingManager __instance, ref int __result) + [HarmonyPrefix] + [HarmonyPatch(nameof(GPUInstancingManager.AddPrebuildModel))] + public static bool AddPrebuildModel_Prefix(GPUInstancingManager __instance, ref int __result) + { + //Do not add model to the GPU queue if player is not on the same planet as building that was build + if (Multiplayer.IsActive && Multiplayer.Session.Factories.EventFactory != null && + Multiplayer.Session.Factories.EventFactory.planet != GameMain.localPlanet) { - //Do not add model to the GPU queue if player is not on the same planet as building that was build - if (Multiplayer.IsActive && Multiplayer.Session.Factories.EventFactory != null && Multiplayer.Session.Factories.EventFactory.planet != GameMain.localPlanet) - { - __result = 0; - return false; - } - return true; + __result = 0; + return false; } + return true; } } diff --git a/NebulaPatcher/Patches/Dynamic/GalacticTransport_Patch.cs b/NebulaPatcher/Patches/Dynamic/GalacticTransport_Patch.cs index af4876407..b9c4a3fdc 100644 --- a/NebulaPatcher/Patches/Dynamic/GalacticTransport_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/GalacticTransport_Patch.cs @@ -1,40 +1,43 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaModel.Packets.Logistics; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(GalacticTransport))] +internal class GalacticTransport_Patch { - [HarmonyPatch(typeof(GalacticTransport))] - internal class GalacticTransport_Patch + [HarmonyPostfix] + [HarmonyPatch(nameof(GalacticTransport.SetForNewGame))] + public static void SetForNewGame_Postfix() { - [HarmonyPostfix] - [HarmonyPatch(nameof(GalacticTransport.SetForNewGame))] - public static void SetForNewGame_Postfix() + if (Multiplayer.IsActive && !Multiplayer.Session.LocalPlayer.IsHost) { - if (Multiplayer.IsActive && !Multiplayer.Session.LocalPlayer.IsHost) - { - Multiplayer.Session.Network.SendPacket(new ILSRequestgStationPoolSync()); - } + Multiplayer.Session.Network.SendPacket(new ILSRequestgStationPoolSync()); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(GalacticTransport.AddStationComponent))] - public static bool AddStationComponent_Prefix(StationComponent station) + [HarmonyPrefix] + [HarmonyPatch(nameof(GalacticTransport.AddStationComponent))] + public static bool AddStationComponent_Prefix(StationComponent station) + { + if (Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsClient && station.gid == 0) { - if (Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsClient && station.gid == 0) - { - // When client build a new station (gid == 0), we will let host decide the value of gid - // ILS will be added when ILSAddStationComponent from host arrived - return false; - } - return true; + // When client build a new station (gid == 0), we will let host decide the value of gid + // ILS will be added when ILSAddStationComponent from host arrived + return false; } + return true; + } - [HarmonyPrefix] - [HarmonyPatch(nameof(GalacticTransport.RemoveStationComponent))] - public static bool RemoveStationComponent_Prefix() - { - return !Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost || Multiplayer.Session.Ships.PatchLockILS; - } + [HarmonyPrefix] + [HarmonyPatch(nameof(GalacticTransport.RemoveStationComponent))] + public static bool RemoveStationComponent_Prefix() + { + return !Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost || Multiplayer.Session.Ships.PatchLockILS; } } diff --git a/NebulaPatcher/Patches/Dynamic/GameCamera_Patch.cs b/NebulaPatcher/Patches/Dynamic/GameCamera_Patch.cs index f32c31ae1..620fd7eb2 100644 --- a/NebulaPatcher/Patches/Dynamic/GameCamera_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/GameCamera_Patch.cs @@ -1,18 +1,20 @@ -using HarmonyLib; -using NebulaWorld; +#region + +using HarmonyLib; using NebulaWorld.GameStates; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(GameCamera))] +public class GameCamera_Patch { - [HarmonyPatch(typeof(GameCamera))] - public class GameCamera_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(GameCamera.Logic))] + public static bool Logic_Prefix() { - [HarmonyPrefix] - [HarmonyPatch(nameof(GameCamera.Logic))] - public static bool Logic_Prefix() - { - // prevent NRE while doing a reconnect as a client issued through the chat command - return !(GameStatesManager.DuringReconnect && GameMain.mainPlayer == null); - } + // prevent NRE while doing a reconnect as a client issued through the chat command + return !(GameStatesManager.DuringReconnect && GameMain.mainPlayer == null); } } diff --git a/NebulaPatcher/Patches/Dynamic/GameData_Patch.cs b/NebulaPatcher/Patches/Dynamic/GameData_Patch.cs index 3f1740b70..eb48a2387 100644 --- a/NebulaPatcher/Patches/Dynamic/GameData_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/GameData_Patch.cs @@ -1,5 +1,11 @@ -using HarmonyLib; +#region + +using System; +using System.Threading; +using System.Threading.Tasks; +using HarmonyLib; using NebulaAPI; +using NebulaModel; using NebulaModel.Logger; using NebulaModel.Networking; using NebulaModel.Packets.Logistics; @@ -8,431 +14,435 @@ using NebulaPatcher.Patches.Transpilers; using NebulaWorld; using NebulaWorld.Warning; -using System; -using System.Threading; -using System.Threading.Tasks; using UnityEngine; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(GameData))] +internal class GameData_Patch { - [HarmonyPatch(typeof(GameData))] - internal class GameData_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(GameData.Update))] + public static void Update_Prefix() { - [HarmonyPrefix] - [HarmonyPatch(nameof(GameData.Update))] - public static void Update_Prefix() + if (!Multiplayer.IsActive || !Multiplayer.Session.IsGameLoaded) { - if (!Multiplayer.IsActive || !Multiplayer.Session.IsGameLoaded) - { - return; - } - - Multiplayer.Session.World.RenderPlayerNameTagsInGame(); + return; } - [HarmonyPrefix] - [HarmonyPatch(nameof(GameData.GetOrCreateFactory))] - public static bool GetOrCreateFactory_Prefix(GameData __instance, ref PlanetFactory __result, PlanetData planet) + Multiplayer.Session.World.RenderPlayerNameTagsInGame(); + } + + [HarmonyPrefix] + [HarmonyPatch(nameof(GameData.GetOrCreateFactory))] + public static bool GetOrCreateFactory_Prefix(GameData __instance, ref PlanetFactory __result, PlanetData planet) + { + // We want the original method to run on the host client or in single player games + if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) { - // We want the original method to run on the host client or in single player games - if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) - { - return true; - } + return true; + } - // Get the recieved bytes from the remote server that we will import - if (!Multiplayer.Session.Planets.PendingFactories.TryGetValue(planet.id, out byte[] factoryBytes)) - { - // We messed up, just defer to the default behaviour on the client (will cause desync but not outright crash) - Log.Error($"PendingFactories did not have value we wanted, factory will not be synced!"); - return true; - } + // Get the recieved bytes from the remote server that we will import + if (!Multiplayer.Session.Planets.PendingFactories.TryGetValue(planet.id, out var factoryBytes)) + { + // We messed up, just defer to the default behaviour on the client (will cause desync but not outright crash) + Log.Error("PendingFactories did not have value we wanted, factory will not be synced!"); + return true; + } - // Take it off the list, as we will process it now - Multiplayer.Session.Planets.PendingFactories.Remove(planet.id); + // Take it off the list, as we will process it now + Multiplayer.Session.Planets.PendingFactories.Remove(planet.id); - using (BinaryUtils.Reader reader = new BinaryUtils.Reader(factoryBytes)) + using (var reader = new BinaryUtils.Reader(factoryBytes)) + { + int factoryIndex; + // Import the factory from the given bytes, which will have been gotten or created on the host by the original function + if (planet.factory == null) { - int factoryIndex; - // Import the factory from the given bytes, which will have been gotten or created on the host by the original function - if (planet.factory == null) + factoryIndex = GameMain.data.factoryCount++; + planet.factoryIndex = factoryIndex; + __instance.factories[factoryIndex] = new PlanetFactory(); + try { - factoryIndex = GameMain.data.factoryCount++; - planet.factoryIndex = factoryIndex; - __instance.factories[factoryIndex] = new PlanetFactory(); - try - { - __instance.factories[factoryIndex].Import(factoryIndex, __instance, reader.BinaryReader); - } - catch(System.InvalidOperationException e) - { - HandleRemoteDataImportError(e); - return false; - } - planet.factory = __instance.factories[factoryIndex]; + __instance.factories[factoryIndex].Import(factoryIndex, __instance, reader.BinaryReader); } - else + catch (InvalidOperationException e) { - factoryIndex = planet.factoryIndex; - try - { - __instance.factories[factoryIndex].Import(factoryIndex, __instance, reader.BinaryReader); - } - catch (System.InvalidOperationException e) - { - HandleRemoteDataImportError(e); - return false; - } - planet.factory = __instance.factories[factoryIndex]; + HandleRemoteDataImportError(e); + return false; } - // Initial FactoryProductionStat for other in-game stats checking functions - if (GameMain.statistics.production.factoryStatPool[factoryIndex] == null) + planet.factory = __instance.factories[factoryIndex]; + } + else + { + factoryIndex = planet.factoryIndex; + try { - GameMain.statistics.production.factoryStatPool[factoryIndex] = new FactoryProductionStat(); - GameMain.statistics.production.factoryStatPool[factoryIndex].Init(); - //Skip the part of setting firstCreateIds + __instance.factories[factoryIndex].Import(factoryIndex, __instance, reader.BinaryReader); } + catch (InvalidOperationException e) + { + HandleRemoteDataImportError(e); + return false; + } + planet.factory = __instance.factories[factoryIndex]; } + // Initial FactoryProductionStat for other in-game stats checking functions + if (GameMain.statistics.production.factoryStatPool[factoryIndex] == null) + { + GameMain.statistics.production.factoryStatPool[factoryIndex] = new FactoryProductionStat(); + GameMain.statistics.production.factoryStatPool[factoryIndex].Init(); + //Skip the part of setting firstCreateIds + } + } - // Assign the factory to the result - __result = __instance.factories[planet.factoryIndex]; + // Assign the factory to the result + __result = __instance.factories[planet.factoryIndex]; - // Do not run the original method - return false; - } + // Do not run the original method + return false; + } + + // a user reported to receive an error regarding decompressing the lz4 data which breaks the game as the planet factory cant be loaded. + // it is not known what exactly caused the error but that client seemed to have an instable internet connection. + // so we give advice in this rare situation to issue a reconnect. + private static void HandleRemoteDataImportError(InvalidOperationException e) + { + WarningManager.DisplayCriticalWarning( + "Failed to properly decompress and import factory data.\nPlease do a reconnect.\nSee the logfile for more information."); + Log.Error( + $"There was an error while decompressing and importing factory data, probably due to an instable internet connection. See full error below.\n{e.StackTrace}"); + } - // a user reported to receive an error regarding decompressing the lz4 data which breaks the game as the planet factory cant be loaded. - // it is not known what exactly caused the error but that client seemed to have an instable internet connection. - // so we give advice in this rare situation to issue a reconnect. - private static void HandleRemoteDataImportError(System.InvalidOperationException e) + [HarmonyPrefix] + [HarmonyPatch(nameof(GameData.OnActivePlanetLoaded))] + public static bool OnActivePlanetLoaded_Prefix(GameData __instance, PlanetData planet) + { + // NOTE: this is part of the weird planet movement fix, see ArrivePlanet() patch for more information + + if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) { - WarningManager.DisplayCriticalWarning($"Failed to properly decompress and import factory data.\nPlease do a reconnect.\nSee the logfile for more information."); - Log.Error($"There was an error while decompressing and importing factory data, probably due to an instable internet connection. See full error below.\n{e.StackTrace}"); + return true; } - - [HarmonyPrefix] - [HarmonyPatch(nameof(GameData.OnActivePlanetLoaded))] - public static bool OnActivePlanetLoaded_Prefix(GameData __instance, PlanetData planet) + if (planet != null) { - // NOTE: this is part of the weird planet movement fix, see ArrivePlanet() patch for more information - - if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) + if (planet.factoryLoaded) { - return true; + __instance.OnActivePlanetFactoryLoaded(planet); } - if (planet != null) + else { - if (planet.factoryLoaded) + // triggers data request to server + planet.LoadFactory(); + planet.onFactoryLoaded += __instance.OnActivePlanetFactoryLoaded; + // lets player walk on empty planet without awkward graphic glitches + if (planet.physics == null) { - __instance.OnActivePlanetFactoryLoaded(planet); + planet.physics = new PlanetPhysics(planet); + planet.physics.Init(); } - else - { - // triggers data request to server - planet.LoadFactory(); - planet.onFactoryLoaded += __instance.OnActivePlanetFactoryLoaded; - // lets player walk on empty planet without awkward graphic glitches - if(planet.physics == null) - { - planet.physics = new PlanetPhysics(planet); - planet.physics.Init(); - } - } - RefreshMissingMeshes(); } - planet.onLoaded -= __instance.OnActivePlanetLoaded; - return false; + RefreshMissingMeshes(); } + planet.onLoaded -= __instance.OnActivePlanetLoaded; + return false; + } - [HarmonyPrefix] - [HarmonyPatch(nameof(GameData.OnActivePlanetFactoryLoaded))] - public static bool OnActivePlanetFactoryLoaded_Prefix(GameData __instance, PlanetData planet) + [HarmonyPrefix] + [HarmonyPatch(nameof(GameData.OnActivePlanetFactoryLoaded))] + public static bool OnActivePlanetFactoryLoaded_Prefix(GameData __instance, PlanetData planet) + { + if (!Multiplayer.IsActive) { - if (!Multiplayer.IsActive) - { - return true; - } - RefreshMissingMeshes(); - if (Multiplayer.Session.LocalPlayer.IsHost) + return true; + } + RefreshMissingMeshes(); + if (Multiplayer.Session.LocalPlayer.IsHost) + { + // Resume packet processing when local planet is loaded + ((NetworkProvider)Multiplayer.Session.Network).PacketProcessor.Enable = true; + Log.Info("Resume PacketProcessor (OnActivePlanetFactoryLoaded)"); + return true; + } + if (planet != null) + { + if (GameMain.gameTick == 0L && DSPGame.SkipPrologue) { - // Resume packet processing when local planet is loaded - ((NebulaModel.NetworkProvider)Multiplayer.Session.Network).PacketProcessor.Enable = true; - Log.Info($"Resume PacketProcessor (OnActivePlanetFactoryLoaded)"); - return true; + InitLandingPlace(__instance, planet); } - if (planet != null) - { - if (GameMain.gameTick == 0L && DSPGame.SkipPrologue) - { - InitLandingPlace(__instance, planet); - } - // now that we have the factory loaded update it in the planets physics - planet.physics.raycastLogic.factory = planet.factory; + // now that we have the factory loaded update it in the planets physics + planet.physics.raycastLogic.factory = planet.factory; - planet.onFactoryLoaded -= __instance.OnActivePlanetFactoryLoaded; + planet.onFactoryLoaded -= __instance.OnActivePlanetFactoryLoaded; - // If the game is still loading, we wait till the full loading is completed - if (Multiplayer.Session.IsGameLoaded) - { - ((NebulaModel.NetworkProvider)Multiplayer.Session.Network).PacketProcessor.Enable = true; - Log.Info($"Resume PacketProcessor (OnActivePlanetFactoryLoaded)"); - } + // If the game is still loading, we wait till the full loading is completed + if (Multiplayer.Session.IsGameLoaded) + { + ((NetworkProvider)Multiplayer.Session.Network).PacketProcessor.Enable = true; + Log.Info("Resume PacketProcessor (OnActivePlanetFactoryLoaded)"); + } - // Get the recieved bytes from the remote server that we will import - if (Multiplayer.Session.Planets.PendingTerrainData.TryGetValue(planet.id, out byte[] terrainBytes)) + // Get the recieved bytes from the remote server that we will import + if (Multiplayer.Session.Planets.PendingTerrainData.TryGetValue(planet.id, out var terrainBytes)) + { + // Apply terrian changes, code from PlanetFactory.FlattenTerrainReform() + if (planet.type != EPlanetType.Gas) { - // Apply terrian changes, code from PlanetFactory.FlattenTerrainReform() - if (planet.type != EPlanetType.Gas) + planet.data.modData = terrainBytes; + for (var i = 0; i < planet.dirtyFlags.Length; i++) { - planet.data.modData = terrainBytes; - for (int i = 0; i < planet.dirtyFlags.Length; i++) - { - planet.dirtyFlags[i] = true; - } - planet.landPercentDirty = true; - try - { - planet.UpdateDirtyMeshes(); - } - catch (Exception e) - { - Log.Warn(e); - } + planet.dirtyFlags[i] = true; + } + planet.landPercentDirty = true; + try + { + planet.UpdateDirtyMeshes(); + } + catch (Exception e) + { + Log.Warn(e); } - Multiplayer.Session.Planets.PendingTerrainData.Remove(planet.id); - } - Task.Run(() => - { - // This is to fix GS2 that sometimes client mecha will be stuck on ground - RefreshMissingMeshes(); - Thread.Sleep(1000); - RefreshMissingMeshes(); - }); - - try - { - NebulaModAPI.OnPlanetLoadFinished?.Invoke(planet.id); - } - catch (Exception e) - { - Log.Error("NebulaModAPI.OnPlanetLoadFinished error:\n" + e); } + Multiplayer.Session.Planets.PendingTerrainData.Remove(planet.id); } + Task.Run(() => + { + // This is to fix GS2 that sometimes client mecha will be stuck on ground + RefreshMissingMeshes(); + Thread.Sleep(1000); + RefreshMissingMeshes(); + }); - // call this here as it would not be called normally on the client, but its needed to set GameMain.data.galacticTransport.stationCursor - // Arragement() updates galacticTransport.stationCursor - // galacticTransport.shipRenderer.Update() can then update galacticTransport.shipRenderer.shipCount - // galacticTransport.shipRenderer.Draw() can then render ships - GameMain.data.galacticTransport.Arragement(); - return false; - } - - // this fixes werid planet movements while loading factory data from server - [HarmonyPostfix] - [HarmonyPatch(nameof(GameData.LateUpdate))] - public static void LateUpdate_Postfix() - { - if (Multiplayer.IsActive && !Multiplayer.Session.LocalPlayer.IsHost) + try { - if (GameMain.data.localPlanet != null && GameMain.data.localPlanet.factoryLoading && GameMain.data.localPlanet.physics != null) - { - GameMain.data.localPlanet.physics.LateUpdate(); - } + NebulaModAPI.OnPlanetLoadFinished?.Invoke(planet.id); + } + catch (Exception e) + { + Log.Error("NebulaModAPI.OnPlanetLoadFinished error:\n" + e); } } - [HarmonyPostfix] - [HarmonyPatch(nameof(GameData.SetForNewGame))] - public static void SetForNewGame_Postfix(GameData __instance) + // call this here as it would not be called normally on the client, but its needed to set GameMain.data.galacticTransport.stationCursor + // Arragement() updates galacticTransport.stationCursor + // galacticTransport.shipRenderer.Update() can then update galacticTransport.shipRenderer.shipCount + // galacticTransport.shipRenderer.Draw() can then render ships + GameMain.data.galacticTransport.Arragement(); + return false; + } + + // this fixes werid planet movements while loading factory data from server + [HarmonyPostfix] + [HarmonyPatch(nameof(GameData.LateUpdate))] + public static void LateUpdate_Postfix() + { + if (Multiplayer.IsActive && !Multiplayer.Session.LocalPlayer.IsHost) { - //Set starting star and planet to request from the server, except when client has set custom starting planet. - if (Multiplayer.IsActive && !Multiplayer.Session.LocalPlayer.IsHost) + if (GameMain.data.localPlanet != null && GameMain.data.localPlanet.factoryLoading && + GameMain.data.localPlanet.physics != null) { - //Request global part of GameData from host - Log.Info($"Requesting global GameData from the server"); - Multiplayer.Session.Network.SendPacket(new GlobalGameDataRequest()); - - //Update player's position before searching for closest planet (GS2: Modeler.ModelingCoroutine) - __instance.mainPlayer.uPosition = new VectorLF3(Multiplayer.Session.LocalPlayer.Data.UPosition.x, Multiplayer.Session.LocalPlayer.Data.UPosition.y, Multiplayer.Session.LocalPlayer.Data.UPosition.z); - - if (Multiplayer.Session.LocalPlayer.Data.LocalPlanetId != -1) - { - PlanetData planet = __instance.galaxy.PlanetById(Multiplayer.Session.LocalPlayer.Data.LocalPlanetId); - __instance.ArrivePlanet(planet); - } - else if(UIVirtualStarmap_Transpiler.customBirthPlanet == -1) - { - StarData nearestStar = null; - PlanetData nearestPlanet = null; - GameMain.data.GetNearestStarPlanet(ref nearestStar, ref nearestPlanet); - if (nearestStar == null) - { - // We are not in a planetary system and thus do not have a star, return. - return; - } - - __instance.ArriveStar(nearestStar); - } - else - { - PlanetData planet = __instance.galaxy.PlanetById(UIVirtualStarmap_Transpiler.customBirthPlanet); - __instance.ArrivePlanet(planet); - } + GameMain.data.localPlanet.physics.LateUpdate(); } } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(GameData.GameTick))] - public static void GameTick_Postfix(GameData __instance, long time) + [HarmonyPostfix] + [HarmonyPatch(nameof(GameData.SetForNewGame))] + public static void SetForNewGame_Postfix(GameData __instance) + { + //Set starting star and planet to request from the server, except when client has set custom starting planet. + if (Multiplayer.IsActive && !Multiplayer.Session.LocalPlayer.IsHost) { - if (!Multiplayer.IsActive) - { - return; - } + //Request global part of GameData from host + Log.Info("Requesting global GameData from the server"); + Multiplayer.Session.Network.SendPacket(new GlobalGameDataRequest()); - Multiplayer.Session.Couriers.GameTick(); - Multiplayer.Session.Belts.GameTick(); + //Update player's position before searching for closest planet (GS2: Modeler.ModelingCoroutine) + __instance.mainPlayer.uPosition = new VectorLF3(Multiplayer.Session.LocalPlayer.Data.UPosition.x, + Multiplayer.Session.LocalPlayer.Data.UPosition.y, Multiplayer.Session.LocalPlayer.Data.UPosition.z); - if (Multiplayer.Session.LocalPlayer.IsHost) + if (Multiplayer.Session.LocalPlayer.Data.LocalPlanetId != -1) { - Multiplayer.Session.Launch.CollectProjectile(); - return; + var planet = __instance.galaxy.PlanetById(Multiplayer.Session.LocalPlayer.Data.LocalPlanetId); + __instance.ArrivePlanet(planet); } - Multiplayer.Session.Launch.LaunchProjectile(); - // call StationComponent::InternalTickRemote() from here, see StationComponent_Patch.cs for info - int timeGene = (int)(time % 60L); - if (timeGene < 0) + else if (UIVirtualStarmap_Transpiler.customBirthPlanet == -1) { - timeGene += 60; - } - GameHistoryData history = GameMain.history; - float shipSailSpeed = history.logisticShipSailSpeedModified; - float shipWarpSpeed = (!history.logisticShipWarpDrive) ? shipSailSpeed : history.logisticShipWarpSpeedModified; - int shipCarries = history.logisticShipCarries; - StationComponent[] gStationPool = __instance.galacticTransport.stationPool; - AstroData[] astroPoses = __instance.galaxy.astrosData; - VectorLF3 relativePos = __instance.relativePos; - Quaternion relativeRot = __instance.relativeRot; - bool starmap = UIGame.viewMode == EViewMode.Starmap; - - foreach (StationComponent stationComponent in GameMain.data.galacticTransport.stationPool) - { - if (stationComponent != null && stationComponent.isStellar && !Multiplayer.Session.IsInLobby) + StarData nearestStar = null; + PlanetData nearestPlanet = null; + GameMain.data.GetNearestStarPlanet(ref nearestStar, ref nearestPlanet); + if (nearestStar == null) { - StationComponent_Transpiler.ILSUpdateShipPos(stationComponent, GameMain.galaxy.PlanetById(stationComponent.planetId).factory, timeGene, shipSailSpeed, shipWarpSpeed, shipCarries, gStationPool, astroPoses, ref relativePos, ref relativeRot, starmap, null); + // We are not in a planetary system and thus do not have a star, return. + return; } + + __instance.ArriveStar(nearestStar); + } + else + { + var planet = __instance.galaxy.PlanetById(UIVirtualStarmap_Transpiler.customBirthPlanet); + __instance.ArrivePlanet(planet); } } + } - private static void InitLandingPlace(GameData gameData, PlanetData planet) + [HarmonyPostfix] + [HarmonyPatch(nameof(GameData.GameTick))] + public static void GameTick_Postfix(GameData __instance, long time) + { + if (!Multiplayer.IsActive) { - Vector3 birthPoint = planet.birthPoint; - Quaternion quaternion = Maths.SphericalRotation(birthPoint, 0f); - gameData.mainPlayer.transform.localPosition = birthPoint; - gameData.mainPlayer.transform.localRotation = quaternion; - gameData.mainPlayer.transform.localScale = Vector3.one; - gameData.mainPlayer.uPosition = (Vector3)planet.uPosition + planet.runtimeRotation * birthPoint; - gameData.mainPlayer.uRotation = planet.runtimeRotation * quaternion; - gameData.mainPlayer.uVelocity = VectorLF3.zero; - gameData.mainPlayer.controller.velocityOnLanding = Vector3.zero; + return; } - [HarmonyPostfix] - [HarmonyPatch(nameof(GameData.OnDraw))] - public static void OnDraw_Postfix() + Multiplayer.Session.Couriers.GameTick(); + Multiplayer.Session.Belts.GameTick(); + + if (Multiplayer.Session.LocalPlayer.IsHost) + { + Multiplayer.Session.Launch.CollectProjectile(); + return; + } + Multiplayer.Session.Launch.LaunchProjectile(); + // call StationComponent::InternalTickRemote() from here, see StationComponent_Patch.cs for info + var timeGene = (int)(time % 60L); + if (timeGene < 0) + { + timeGene += 60; + } + var history = GameMain.history; + var shipSailSpeed = history.logisticShipSailSpeedModified; + var shipWarpSpeed = !history.logisticShipWarpDrive ? shipSailSpeed : history.logisticShipWarpSpeedModified; + var shipCarries = history.logisticShipCarries; + var gStationPool = __instance.galacticTransport.stationPool; + var astroPoses = __instance.galaxy.astrosData; + var relativePos = __instance.relativePos; + var relativeRot = __instance.relativeRot; + var starmap = UIGame.viewMode == EViewMode.Starmap; + + foreach (var stationComponent in GameMain.data.galacticTransport.stationPool) { - if (Multiplayer.IsActive) + if (stationComponent != null && stationComponent.isStellar && !Multiplayer.Session.IsInLobby) { - Multiplayer.Session.World.OnDronesDraw(); + StationComponent_Transpiler.ILSUpdateShipPos(stationComponent, + GameMain.galaxy.PlanetById(stationComponent.planetId).factory, timeGene, shipSailSpeed, shipWarpSpeed, + shipCarries, gStationPool, astroPoses, ref relativePos, ref relativeRot, starmap, null); } } + } + + private static void InitLandingPlace(GameData gameData, PlanetData planet) + { + var birthPoint = planet.birthPoint; + var quaternion = Maths.SphericalRotation(birthPoint, 0f); + gameData.mainPlayer.transform.localPosition = birthPoint; + gameData.mainPlayer.transform.localRotation = quaternion; + gameData.mainPlayer.transform.localScale = Vector3.one; + gameData.mainPlayer.uPosition = (Vector3)planet.uPosition + planet.runtimeRotation * birthPoint; + gameData.mainPlayer.uRotation = planet.runtimeRotation * quaternion; + gameData.mainPlayer.uVelocity = VectorLF3.zero; + gameData.mainPlayer.controller.velocityOnLanding = Vector3.zero; + } + + [HarmonyPostfix] + [HarmonyPatch(nameof(GameData.OnDraw))] + public static void OnDraw_Postfix() + { + if (Multiplayer.IsActive) + { + Multiplayer.Session.World.OnDronesDraw(); + } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(GameData.LeaveStar))] - public static void LeaveStar_Prefix(GameData __instance) + [HarmonyPrefix] + [HarmonyPatch(nameof(GameData.LeaveStar))] + public static void LeaveStar_Prefix(GameData __instance) + { + //Client should unload all factories once they leave the star system + if (Multiplayer.IsActive && !Multiplayer.Session.LocalPlayer.IsHost) { - //Client should unload all factories once they leave the star system - if (Multiplayer.IsActive && !Multiplayer.Session.LocalPlayer.IsHost) + using (Multiplayer.Session.Ships.PatchLockILS.On()) { - using (Multiplayer.Session.Ships.PatchLockILS.On()) + for (var i = 0; i < __instance.localStar.planetCount; i++) { - for (int i = 0; i < __instance.localStar.planetCount; i++) + if (__instance.localStar.planets != null && __instance.localStar.planets[i] != null) { - if (__instance.localStar.planets != null && __instance.localStar.planets[i] != null) + if (__instance.localStar.planets[i].factory != null) { - if (__instance.localStar.planets[i].factory != null) - { - __instance.localStar.planets[i].factory.Free(); - __instance.localStar.planets[i].factory = null; - GameMain.data.factoryCount--; - } + __instance.localStar.planets[i].factory.Free(); + __instance.localStar.planets[i].factory = null; + GameMain.data.factoryCount--; } } } - if (!Multiplayer.Session.IsInLobby) - { - Multiplayer.Session.Network.SendPacket(new PlayerUpdateLocalStarId(-1)); - } } - } - - [HarmonyPrefix] - [HarmonyPatch(nameof(GameData.ArriveStar))] - public static void ArriveStar_Prefix(StarData star) - { - //Client should unload all factories once they leave the star system - if (Multiplayer.IsActive && !Multiplayer.Session.LocalPlayer.IsHost && !Multiplayer.Session.IsInLobby && star != null) + if (!Multiplayer.Session.IsInLobby) { - Multiplayer.Session.Network.SendPacket(new PlayerUpdateLocalStarId(star.id)); - Multiplayer.Session.Network.SendPacket(new ILSArriveStarPlanetRequest(star.id)); + Multiplayer.Session.Network.SendPacket(new PlayerUpdateLocalStarId(-1)); } } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(GameData.LeavePlanet))] - public static void LeavePlanet_Prefix() + [HarmonyPrefix] + [HarmonyPatch(nameof(GameData.ArriveStar))] + public static void ArriveStar_Prefix(StarData star) + { + //Client should unload all factories once they leave the star system + if (Multiplayer.IsActive && !Multiplayer.Session.LocalPlayer.IsHost && !Multiplayer.Session.IsInLobby && star != null) { - //Players should clear the list of drone orders of other players when they leave the planet - if (Multiplayer.IsActive) - { - GameMain.mainPlayer.mecha.droneLogic.serving.Clear(); - } + Multiplayer.Session.Network.SendPacket(new PlayerUpdateLocalStarId(star.id)); + Multiplayer.Session.Network.SendPacket(new ILSArriveStarPlanetRequest(star.id)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(GameData.DetermineLocalPlanet))] - public static bool DetermineLocalPlanet_Prefix(GameData __instance, ref bool __result) + [HarmonyPrefix] + [HarmonyPatch(nameof(GameData.LeavePlanet))] + public static void LeavePlanet_Prefix() + { + //Players should clear the list of drone orders of other players when they leave the planet + if (Multiplayer.IsActive) { - if(UIVirtualStarmap_Transpiler.customBirthPlanet != -1 && (Multiplayer.IsActive && !Multiplayer.Session.IsGameLoaded)) - { - __result = false; - return false; - } - return true; + GameMain.mainPlayer.mecha.droneLogic.serving.Clear(); } + } - private static void RefreshMissingMeshes() + [HarmonyPrefix] + [HarmonyPatch(nameof(GameData.DetermineLocalPlanet))] + public static bool DetermineLocalPlanet_Prefix(GameData __instance, ref bool __result) + { + if (UIVirtualStarmap_Transpiler.customBirthPlanet != -1 && Multiplayer.IsActive && !Multiplayer.Session.IsGameLoaded) { - PlanetData planetData = GameMain.localPlanet; - bool flag = false; + __result = false; + return false; + } + return true; + } + + private static void RefreshMissingMeshes() + { + var planetData = GameMain.localPlanet; + var flag = false; - if (planetData.meshColliders != null) + if (planetData.meshColliders != null) + { + for (var i = 0; i < planetData.meshColliders.Length; i++) { - for (int i = 0; i < planetData.meshColliders.Length; i++) + if (planetData.meshColliders[i] != null && planetData.meshColliders[i].sharedMesh == null) { - if (planetData.meshColliders[i] != null && planetData.meshColliders[i].sharedMesh == null) - { - planetData.meshColliders[i].sharedMesh = planetData.meshes[i]; - flag = true; - } + planetData.meshColliders[i].sharedMesh = planetData.meshes[i]; + flag = true; } } + } - if (flag) - { - Log.Debug("RefreshMissingMeshes"); - } + if (flag) + { + Log.Debug("RefreshMissingMeshes"); } } } diff --git a/NebulaPatcher/Patches/Dynamic/GameHistoryData_Patch.cs b/NebulaPatcher/Patches/Dynamic/GameHistoryData_Patch.cs index bfba83ac7..bd36e8c60 100644 --- a/NebulaPatcher/Patches/Dynamic/GameHistoryData_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/GameHistoryData_Patch.cs @@ -1,145 +1,148 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaModel.Logger; using NebulaModel.Packets.GameHistory; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(GameHistoryData))] +internal class GameHistoryData_Patch { - [HarmonyPatch(typeof(GameHistoryData))] - internal class GameHistoryData_Patch + [HarmonyPostfix] + [HarmonyPatch(nameof(GameHistoryData.EnqueueTech))] + public static void EnqueueTech_Postfix(int techId) { - [HarmonyPostfix] - [HarmonyPatch(nameof(GameHistoryData.EnqueueTech))] - public static void EnqueueTech_Postfix(int techId) + if (!Multiplayer.IsActive) { - if (!Multiplayer.IsActive) - { - return; - } - //Do not run if this was triggered by incomming request - if (Multiplayer.Session.History.IsIncomingRequest) - { - return; - } - //Synchronize enqueueing techs by players - Log.Info($"Sending Enqueue Tech notification"); - Multiplayer.Session.Network.SendPacket(new GameHistoryEnqueueTechPacket(techId)); + return; } - - [HarmonyPrefix] - [HarmonyPatch(nameof(GameHistoryData.RemoveTechInQueue))] - public static void RemoveTechInQueue_Prefix(int index, out int __state) + //Do not run if this was triggered by incomming request + if (Multiplayer.Session.History.IsIncomingRequest) { - __state = GameMain.history.techQueue[index]; - Log.Info($"RemoveTechInQueue: remove tech at index {index} with techId { __state}"); + return; } + //Synchronize enqueueing techs by players + Log.Info("Sending Enqueue Tech notification"); + Multiplayer.Session.Network.SendPacket(new GameHistoryEnqueueTechPacket(techId)); + } - [HarmonyPostfix] - [HarmonyPatch(nameof(GameHistoryData.RemoveTechInQueue))] - public static void RemoveTechInQueue_Postfix(int index, int __state) - { - if (!Multiplayer.IsActive) - { - return; - } - //Do not run if this was triggered by incomming request - if (Multiplayer.Session.History.IsIncomingRequest) - { - return; - } - //Synchronize dequeueing techs by players and trigger refunds for all clients - Log.Info($"Sending Dequeue Tech notification: remove techID{__state}"); - Multiplayer.Session.Network.SendPacket(new GameHistoryRemoveTechPacket(__state)); - } + [HarmonyPrefix] + [HarmonyPatch(nameof(GameHistoryData.RemoveTechInQueue))] + public static void RemoveTechInQueue_Prefix(int index, out int __state) + { + __state = GameMain.history.techQueue[index]; + Log.Info($"RemoveTechInQueue: remove tech at index {index} with techId {__state}"); + } - [HarmonyPostfix] - [HarmonyPatch(nameof(GameHistoryData.PauseTechQueue))] - public static void PauseTechQueue_Postfix() + [HarmonyPostfix] + [HarmonyPatch(nameof(GameHistoryData.RemoveTechInQueue))] + public static void RemoveTechInQueue_Postfix(int index, int __state) + { + if (!Multiplayer.IsActive) { - if (!Multiplayer.IsActive) - { - return; - } - //Do not run if this was triggered by incomming request - if (Multiplayer.Session.History.IsIncomingRequest) - { - return; - } - //Synchronize pausing techs by players - Log.Info($"Sending Pause Tech queue notification"); - Multiplayer.Session.Network.SendPacket(new GameHistoryNotificationPacket(GameHistoryEvent.PauseQueue)); + return; } - - [HarmonyPostfix] - [HarmonyPatch(nameof(GameHistoryData.ResumeTechQueue))] - public static void ResumeTechQueue_Postfix() + //Do not run if this was triggered by incomming request + if (Multiplayer.Session.History.IsIncomingRequest) { - if (!Multiplayer.IsActive) - { - return; - } - //Do not run if this was triggered by incomming request - if (Multiplayer.Session.History.IsIncomingRequest) - { - return; - } - //Synchronize resuming techs by players - Log.Info($"Sending Resume Tech queue notification"); - Multiplayer.Session.Network.SendPacket(new GameHistoryNotificationPacket(GameHistoryEvent.ResumeQueue)); + return; } + //Synchronize dequeueing techs by players and trigger refunds for all clients + Log.Info($"Sending Dequeue Tech notification: remove techID{__state}"); + Multiplayer.Session.Network.SendPacket(new GameHistoryRemoveTechPacket(__state)); + } - [HarmonyPrefix] - [HarmonyPatch(nameof(GameHistoryData.UnlockRecipe))] - public static bool UnlockRecipe_Prefix() + [HarmonyPostfix] + [HarmonyPatch(nameof(GameHistoryData.PauseTechQueue))] + public static void PauseTechQueue_Postfix() + { + if (!Multiplayer.IsActive) { - //Wait for the authoritative packet for unlocking recipes in multiplayer for clients - return !Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost || Multiplayer.Session.History.IsIncomingRequest; + return; } - - [HarmonyPrefix] - [HarmonyPatch(nameof(GameHistoryData.UnlockTechFunction))] - public static bool UnlockTechFunction_Prefix() + //Do not run if this was triggered by incomming request + if (Multiplayer.Session.History.IsIncomingRequest) { - //Wait for the authoritative packet for unlocking tech features in multiplayer for clients - return !Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost || Multiplayer.Session.History.IsIncomingRequest; + return; } + //Synchronize pausing techs by players + Log.Info("Sending Pause Tech queue notification"); + Multiplayer.Session.Network.SendPacket(new GameHistoryNotificationPacket(GameHistoryEvent.PauseQueue)); + } - [HarmonyPrefix] - [HarmonyPatch(nameof(GameHistoryData.GainTechAwards))] - public static bool GainTechAwards_Prefix() + [HarmonyPostfix] + [HarmonyPatch(nameof(GameHistoryData.ResumeTechQueue))] + public static void ResumeTechQueue_Postfix() + { + if (!Multiplayer.IsActive) { - //Wait for the authoritative packet for gaining tech awards in multiplayer for clients - return !Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost || Multiplayer.Session.History.IsIncomingRequest; + return; } - - [HarmonyPatch(nameof(GameHistoryData.DequeueTech))] - public static bool DequeueTech_Prefix() + //Do not run if this was triggered by incomming request + if (Multiplayer.Session.History.IsIncomingRequest) { - ///Wait for the authoritative packet for dequeing tech in multiplayer for clients - return !Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost || Multiplayer.Session.History.IsIncomingRequest; + return; } + //Synchronize resuming techs by players + Log.Info("Sending Resume Tech queue notification"); + Multiplayer.Session.Network.SendPacket(new GameHistoryNotificationPacket(GameHistoryEvent.ResumeQueue)); + } - [HarmonyPrefix] - [HarmonyPatch(nameof(GameHistoryData.UnlockTech))] - public static bool UnlockTech_Prefix() - { - //Wait for the authoritative packet for unlocking tech features in multiplayer for clients - return !Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost || Multiplayer.Session.History.IsIncomingRequest; - } + [HarmonyPrefix] + [HarmonyPatch(nameof(GameHistoryData.UnlockRecipe))] + public static bool UnlockRecipe_Prefix() + { + //Wait for the authoritative packet for unlocking recipes in multiplayer for clients + return !Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost || Multiplayer.Session.History.IsIncomingRequest; + } - [HarmonyPostfix] - [HarmonyPatch(nameof(GameHistoryData.NotifyTechUnlock))] - public static void NotifyTechUnlock_Postfix(int _techId, int _level) + [HarmonyPrefix] + [HarmonyPatch(nameof(GameHistoryData.UnlockTechFunction))] + public static bool UnlockTechFunction_Prefix() + { + //Wait for the authoritative packet for unlocking tech features in multiplayer for clients + return !Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost || Multiplayer.Session.History.IsIncomingRequest; + } + + [HarmonyPrefix] + [HarmonyPatch(nameof(GameHistoryData.GainTechAwards))] + public static bool GainTechAwards_Prefix() + { + //Wait for the authoritative packet for gaining tech awards in multiplayer for clients + return !Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost || Multiplayer.Session.History.IsIncomingRequest; + } + + [HarmonyPatch(nameof(GameHistoryData.DequeueTech))] + public static bool DequeueTech_Prefix() + { + ///Wait for the authoritative packet for dequeing tech in multiplayer for clients + return !Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost || Multiplayer.Session.History.IsIncomingRequest; + } + + [HarmonyPrefix] + [HarmonyPatch(nameof(GameHistoryData.UnlockTech))] + public static bool UnlockTech_Prefix() + { + //Wait for the authoritative packet for unlocking tech features in multiplayer for clients + return !Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost || Multiplayer.Session.History.IsIncomingRequest; + } + + [HarmonyPostfix] + [HarmonyPatch(nameof(GameHistoryData.NotifyTechUnlock))] + public static void NotifyTechUnlock_Postfix(int _techId, int _level) + { + Log.Info($"NotifyTechUnlock techId={_techId} level={_level}"); + if (!Multiplayer.IsActive || !Multiplayer.Session.LocalPlayer.IsHost) { - Log.Info($"NotifyTechUnlock techId={_techId} level={_level}"); - if (!Multiplayer.IsActive || !Multiplayer.Session.LocalPlayer.IsHost) - { - return; - } - // Synchronize unlocking techs - Log.Info($"Sending Tech Unlocked notification"); - GameMain.mainPlayer.mecha.lab.itemPoints.Clear(); - Multiplayer.Session.Network.SendPacket(new GameHistoryUnlockTechPacket(_techId, _level)); + return; } + // Synchronize unlocking techs + Log.Info("Sending Tech Unlocked notification"); + GameMain.mainPlayer.mecha.lab.itemPoints.Clear(); + Multiplayer.Session.Network.SendPacket(new GameHistoryUnlockTechPacket(_techId, _level)); } -} \ No newline at end of file +} diff --git a/NebulaPatcher/Patches/Dynamic/GameLoader_Patch.cs b/NebulaPatcher/Patches/Dynamic/GameLoader_Patch.cs index 25073ef9f..ed0c0db80 100644 --- a/NebulaPatcher/Patches/Dynamic/GameLoader_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/GameLoader_Patch.cs @@ -1,22 +1,26 @@ -using HarmonyLib; +#region + +using HarmonyLib; +using NebulaModel.Logger; using NebulaWorld; using NebulaWorld.GameStates; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(GameLoader))] +internal class GameLoader_Patch { - [HarmonyPatch(typeof(GameLoader))] - internal class GameLoader_Patch + [HarmonyPostfix] + [HarmonyPatch(nameof(GameLoader.FixedUpdate))] + public static void FixedUpdate_Postfix(int ___frame) { - [HarmonyPostfix] - [HarmonyPatch(nameof(GameLoader.FixedUpdate))] - public static void FixedUpdate_Postfix(int ___frame) + var content = GameStatesManager.FragmentSize > 0 ? GameStatesManager.LoadingMessage() : Log.LastInfoMsg; + InGamePopup.UpdateMessage("Loading".Translate(), "Loading state from server, please wait".Translate() + "\n" + content); + if (Multiplayer.IsActive && ___frame >= 11) { - string content = GameStatesManager.FragmentSize > 0 ? GameStatesManager.LoadingMessage() : NebulaModel.Logger.Log.LastInfoMsg; - InGamePopup.UpdateMessage("Loading".Translate(), "Loading state from server, please wait".Translate() + "\n" + content); - if (Multiplayer.IsActive && ___frame >= 11) - { - Multiplayer.Session.OnGameLoadCompleted(); - } + Multiplayer.Session.OnGameLoadCompleted(); } } } diff --git a/NebulaPatcher/Patches/Dynamic/GameMain_Patch.cs b/NebulaPatcher/Patches/Dynamic/GameMain_Patch.cs index f6dcd2292..610adf3ac 100644 --- a/NebulaPatcher/Patches/Dynamic/GameMain_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/GameMain_Patch.cs @@ -1,23 +1,26 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaModel.Logger; using NebulaWorld; using NebulaWorld.SocialIntegration; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(GameMain))] +public class GameMain_Patch { - [HarmonyPatch(typeof(GameMain))] - public class GameMain_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(GameMain.HandleApplicationQuit))] + public static void HandleApplicationQuit_Prefix() { - [HarmonyPrefix] - [HarmonyPatch(nameof(GameMain.HandleApplicationQuit))] - public static void HandleApplicationQuit_Prefix() + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) - { - Log.Warn("Multiplayer is still running, closing now..."); - Multiplayer.LeaveGame(); - } - DiscordManager.Cleanup(); + Log.Warn("Multiplayer is still running, closing now..."); + Multiplayer.LeaveGame(); } + DiscordManager.Cleanup(); } } diff --git a/NebulaPatcher/Patches/Dynamic/GameSave_Patch.cs b/NebulaPatcher/Patches/Dynamic/GameSave_Patch.cs index 820d49dad..b12ffdc54 100644 --- a/NebulaPatcher/Patches/Dynamic/GameSave_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/GameSave_Patch.cs @@ -1,85 +1,88 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaModel; using NebulaNetwork; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(GameSave))] +internal class GameSave_Patch { - [HarmonyPatch(typeof(GameSave))] - internal class GameSave_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(GameSave.SaveCurrentGame))] + public static bool SaveCurrentGame_Prefix(string saveName) { - [HarmonyPrefix] - [HarmonyPatch(nameof(GameSave.SaveCurrentGame))] - public static bool SaveCurrentGame_Prefix(string saveName) + if (Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsHost) { - if (Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsHost) + // temp revert sand count back to original value before saving if we sync it (see SimulatedWorld.SetupInitialPlayerState() ) + if (Config.Options.SyncSoil) { - // temp revert sand count back to original value before saving if we sync it (see SimulatedWorld.SetupInitialPlayerState() ) - if (Config.Options.SyncSoil) - { - int tmp = GameMain.mainPlayer.sandCount; - GameMain.mainPlayer.sandCount = Multiplayer.Session.LocalPlayer.Data.Mecha.SandCount; - Multiplayer.Session.LocalPlayer.Data.Mecha.SandCount = tmp; - } - SaveManager.SaveServerData(saveName); + var tmp = GameMain.mainPlayer.sandCount; + GameMain.mainPlayer.sandCount = Multiplayer.Session.LocalPlayer.Data.Mecha.SandCount; + Multiplayer.Session.LocalPlayer.Data.Mecha.SandCount = tmp; } - - // Only save if in single player or if you are the host - return !Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost; + SaveManager.SaveServerData(saveName); } - [HarmonyPostfix] - [HarmonyPatch(nameof(GameSave.SaveCurrentGame))] - public static void SaveCurrentGame_Postfix(string saveName) + // Only save if in single player or if you are the host + return !Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost; + } + + [HarmonyPostfix] + [HarmonyPatch(nameof(GameSave.SaveCurrentGame))] + public static void SaveCurrentGame_Postfix(string saveName) + { + if (Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsHost) { - if(Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsHost) + // if we sync soil we need to revert changes from above after saving the game + if (Config.Options.SyncSoil) { - // if we sync soil we need to revert changes from above after saving the game - if (Config.Options.SyncSoil) - { - int tmp = GameMain.mainPlayer.sandCount; - GameMain.mainPlayer.sandCount = Multiplayer.Session.LocalPlayer.Data.Mecha.SandCount; - Multiplayer.Session.LocalPlayer.Data.Mecha.SandCount = tmp; - } + var tmp = GameMain.mainPlayer.sandCount; + GameMain.mainPlayer.sandCount = Multiplayer.Session.LocalPlayer.Data.Mecha.SandCount; + Multiplayer.Session.LocalPlayer.Data.Mecha.SandCount = tmp; } } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(GameSave.AutoSave))] - public static bool AutoSave_Prefix() - { - // Only save if in single player or if you are the host - return !Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost; - } + [HarmonyPrefix] + [HarmonyPatch(nameof(GameSave.AutoSave))] + public static bool AutoSave_Prefix() + { + // Only save if in single player or if you are the host + return !Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost; + } - [HarmonyPrefix] - [HarmonyPatch(nameof(GameSave.SaveAsLastExit))] - public static bool SaveAsLastExit_Prefix() - { - // Only save if in single player, since multiplayer requires to load from the Load Save Window - return (!Multiplayer.IsActive && !Multiplayer.IsLeavingGame); - } + [HarmonyPrefix] + [HarmonyPatch(nameof(GameSave.SaveAsLastExit))] + public static bool SaveAsLastExit_Prefix() + { + // Only save if in single player, since multiplayer requires to load from the Load Save Window + return !Multiplayer.IsActive && !Multiplayer.IsLeavingGame; + } - [HarmonyPostfix] - [HarmonyPatch(nameof(GameSave.LoadCurrentGame))] - public static void LoadCurrentGame_Postfix(bool __result) + [HarmonyPostfix] + [HarmonyPatch(nameof(GameSave.LoadCurrentGame))] + public static void LoadCurrentGame_Postfix(bool __result) + { + // If loading success, check and correct offset for all inserters + if (__result) { - // If loading success, check and correct offset for all inserters - if (__result) + for (var index = 0; index < GameMain.data.factoryCount; index++) { - for (int index = 0; index < GameMain.data.factoryCount; index++) + var factory = GameMain.data.factories[index]; + var entityPool = factory.entityPool; + var traffic = factory.factorySystem.traffic; + var beltPool = factory.factorySystem.traffic.beltPool; + for (var i = 1; i < factory.factorySystem.inserterCursor; i++) { - PlanetFactory factory = GameMain.data.factories[index]; - EntityData[] entityPool = factory.entityPool; - CargoTraffic traffic = factory.factorySystem.traffic; - BeltComponent[] beltPool = factory.factorySystem.traffic.beltPool; - for (int i = 1; i < factory.factorySystem.inserterCursor; i++) + ref var inserter = ref factory.factorySystem.inserterPool[i]; + if (inserter.id == i) { - ref InserterComponent inserter = ref factory.factorySystem.inserterPool[i]; - if (inserter.id == i) - { - inserter.InternalOffsetCorrection(entityPool, traffic, beltPool); - } + inserter.InternalOffsetCorrection(entityPool, traffic, beltPool); } } } diff --git a/NebulaPatcher/Patches/Dynamic/GameStatData_Patch.cs b/NebulaPatcher/Patches/Dynamic/GameStatData_Patch.cs index d675393a4..4fc431377 100644 --- a/NebulaPatcher/Patches/Dynamic/GameStatData_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/GameStatData_Patch.cs @@ -1,37 +1,40 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(GameStatData))] +internal class GameStatData_Patch { - [HarmonyPatch(typeof(GameStatData))] - internal class GameStatData_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(GameStatData.AfterTick))] + public static void AfterTick_Prefix(GameStatData __instance) { - [HarmonyPrefix] - [HarmonyPatch(nameof(GameStatData.AfterTick))] - public static void AfterTick_Prefix(GameStatData __instance) + if (Multiplayer.IsActive && !Multiplayer.Session.LocalPlayer.IsHost) { - if (Multiplayer.IsActive && !Multiplayer.Session.LocalPlayer.IsHost) + if (GameMain.history.currentTech != 0) { - if (GameMain.history.currentTech != 0) + var hostTechHashedFor10Frames = Multiplayer.Session.Statistics.TechHashedFor10Frames; + __instance.techHashedThisFrame = hostTechHashedFor10Frames / 10; + if (GameMain.gameTick % 10 < hostTechHashedFor10Frames % 10) { - int hostTechHashedFor10Frames = Multiplayer.Session.Statistics.TechHashedFor10Frames; - __instance.techHashedThisFrame = hostTechHashedFor10Frames / 10; - if (GameMain.gameTick % 10 < hostTechHashedFor10Frames % 10) - { - ++__instance.techHashedThisFrame; - } + ++__instance.techHashedThisFrame; } } } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(GameStatData.AfterTick))] - public static void AfterTick_Postfix() + [HarmonyPostfix] + [HarmonyPatch(nameof(GameStatData.AfterTick))] + public static void AfterTick_Postfix() + { + if (Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsHost) { - if (Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsHost) - { - Multiplayer.Session.Statistics.CaptureStatisticalSnapshot(); - } + Multiplayer.Session.Statistics.CaptureStatisticalSnapshot(); } } } diff --git a/NebulaPatcher/Patches/Dynamic/GuideMissionStandardMode_Patch.cs b/NebulaPatcher/Patches/Dynamic/GuideMissionStandardMode_Patch.cs index 464573f4a..0309ef1c2 100644 --- a/NebulaPatcher/Patches/Dynamic/GuideMissionStandardMode_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/GuideMissionStandardMode_Patch.cs @@ -1,17 +1,20 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(GuideMissionStandardMode))] +internal class GuideMissionStandardMode_Patch { - [HarmonyPatch(typeof(GuideMissionStandardMode))] - internal class GuideMissionStandardMode_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(GuideMissionStandardMode.Skip))] + public static bool Skip_Prefix() { - [HarmonyPrefix] - [HarmonyPatch(nameof(GuideMissionStandardMode.Skip))] - public static bool Skip_Prefix() - { - //This prevents spawning landing capsule and preparing spawn area for the clients in multiplayer. - return !Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost; - } + //This prevents spawning landing capsule and preparing spawn area for the clients in multiplayer. + return !Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost; } } diff --git a/NebulaPatcher/Patches/Dynamic/IconSet_Patch.cs b/NebulaPatcher/Patches/Dynamic/IconSet_Patch.cs index afaf02d57..26c4880fd 100644 --- a/NebulaPatcher/Patches/Dynamic/IconSet_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/IconSet_Patch.cs @@ -1,16 +1,19 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaWorld.Chat; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(IconSet))] +public static class IconSet_Patch { - [HarmonyPatch(typeof(IconSet))] - public static class IconSet_Patch + [HarmonyPatch(nameof(IconSet.Create))] + [HarmonyPostfix] + public static void Create_Postfix(IconSet __instance) { - [HarmonyPatch(nameof(IconSet.Create))] - [HarmonyPostfix] - public static void Create_Postfix(IconSet __instance) - { - ChatSpriteSheetManager.Create(__instance); - } + ChatSpriteSheetManager.Create(__instance); } -} \ No newline at end of file +} diff --git a/NebulaPatcher/Patches/Dynamic/InserterComponent_Patch.cs b/NebulaPatcher/Patches/Dynamic/InserterComponent_Patch.cs index 2a5529d57..6a082d766 100644 --- a/NebulaPatcher/Patches/Dynamic/InserterComponent_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/InserterComponent_Patch.cs @@ -1,72 +1,79 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaModel.Logger; using NebulaModel.Packets.Factory.Inserter; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(InserterComponent))] +internal class InserterComponent_Patch { - [HarmonyPatch(typeof(InserterComponent))] - internal class InserterComponent_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(InserterComponent.InternalOffsetCorrection))] + internal static bool InternalOffsetCorrection_Prefix(ref InserterComponent __instance, EntityData[] entityPool, + CargoTraffic traffic, BeltComponent[] beltPool) { - [HarmonyPrefix] - [HarmonyPatch(nameof(InserterComponent.InternalOffsetCorrection))] - internal static bool InternalOffsetCorrection_Prefix(ref InserterComponent __instance, EntityData[] entityPool, CargoTraffic traffic, BeltComponent[] beltPool) + var flag = false; + var beltId = entityPool[__instance.pickTarget].beltId; + if (beltId > 0) { - bool flag = false; - int beltId = entityPool[__instance.pickTarget].beltId; - if (beltId > 0) + var cargoPath = traffic.GetCargoPath(beltPool[beltId].segPathId); + if (cargoPath != null) { - CargoPath cargoPath = traffic.GetCargoPath(beltPool[beltId].segPathId); - if (cargoPath != null) + var num = beltPool[beltId].segPivotOffset + beltPool[beltId].segIndex; + var num2 = num + __instance.pickOffset; + if (num2 < 4) { - int num = beltPool[beltId].segPivotOffset + beltPool[beltId].segIndex; - int num2 = num + (int)__instance.pickOffset; - if (num2 < 4) - { - num2 = 4; - } - if (num2 + 5 >= cargoPath.pathLength) - { - num2 = cargoPath.pathLength - 5 - 1; - } - if (__instance.pickOffset != (short)(num2 - num)) - { - Log.Warn($"{traffic.factory.planetId} Fix inserter{__instance.id} pickOffset {__instance.pickOffset} -> {num2 - num}"); - __instance.pickOffset = (short)(num2 - num); - flag = true; - } + num2 = 4; } - } - int beltId2 = entityPool[__instance.insertTarget].beltId; - if (beltId2 > 0) - { - CargoPath cargoPath2 = traffic.GetCargoPath(beltPool[beltId2].segPathId); - if (cargoPath2 != null) + if (num2 + 5 >= cargoPath.pathLength) { - int num3 = beltPool[beltId2].segPivotOffset + beltPool[beltId2].segIndex; - int num4 = num3 + (int)__instance.insertOffset; - if (num4 < 4) - { - num4 = 4; - } - if (num4 + 5 >= cargoPath2.pathLength) - { - num4 = cargoPath2.pathLength - 5 - 1; - } - if (__instance.insertOffset != (short)(num4 - num3)) - { - Log.Warn($"{traffic.factory.planetId} Fix inserter{__instance.id} insertOffset {__instance.insertOffset} -> {num4 - num3}"); - __instance.insertOffset = (short)(num4 - num3); - flag = true; - } + num2 = cargoPath.pathLength - 5 - 1; + } + if (__instance.pickOffset != (short)(num2 - num)) + { + Log.Warn( + $"{traffic.factory.planetId} Fix inserter{__instance.id} pickOffset {__instance.pickOffset} -> {num2 - num}"); + __instance.pickOffset = (short)(num2 - num); + flag = true; } } - if (flag && Multiplayer.IsActive) + } + var beltId2 = entityPool[__instance.insertTarget].beltId; + if (beltId2 > 0) + { + var cargoPath2 = traffic.GetCargoPath(beltPool[beltId2].segPathId); + if (cargoPath2 != null) { - Multiplayer.Session.Network.SendPacketToLocalStar(new InserterOffsetCorrectionPacket(__instance.id, __instance.pickOffset, __instance.insertOffset, traffic.factory.planetId)); + var num3 = beltPool[beltId2].segPivotOffset + beltPool[beltId2].segIndex; + var num4 = num3 + __instance.insertOffset; + if (num4 < 4) + { + num4 = 4; + } + if (num4 + 5 >= cargoPath2.pathLength) + { + num4 = cargoPath2.pathLength - 5 - 1; + } + if (__instance.insertOffset != (short)(num4 - num3)) + { + Log.Warn( + $"{traffic.factory.planetId} Fix inserter{__instance.id} insertOffset {__instance.insertOffset} -> {num4 - num3}"); + __instance.insertOffset = (short)(num4 - num3); + flag = true; + } } - - return false; } + if (flag && Multiplayer.IsActive) + { + Multiplayer.Session.Network.SendPacketToLocalStar(new InserterOffsetCorrectionPacket(__instance.id, + __instance.pickOffset, __instance.insertOffset, traffic.factory.planetId)); + } + + return false; } } diff --git a/NebulaPatcher/Patches/Dynamic/InserterRenderer_Patch.cs b/NebulaPatcher/Patches/Dynamic/InserterRenderer_Patch.cs index 9bf612dca..37ae13a33 100644 --- a/NebulaPatcher/Patches/Dynamic/InserterRenderer_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/InserterRenderer_Patch.cs @@ -1,37 +1,45 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaAPI; using NebulaWorld; -using System; using UnityEngine; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(InserterRenderer))] +internal class InserterRenderer_Patch { - [HarmonyPatch(typeof(InserterRenderer))] - internal class InserterRenderer_Patch + [HarmonyPrefix] + [HarmonyPatch(typeof(InserterRenderer), nameof(InserterRenderer.AddInst), typeof(int), typeof(Vector3), typeof(Quaternion), + typeof(bool))] + [HarmonyPatch(typeof(InserterRenderer), nameof(InserterRenderer.AddInst), typeof(int), typeof(Vector3), typeof(Quaternion), + typeof(Vector3), typeof(Quaternion), typeof(int), typeof(int), typeof(bool))] + public static bool AddInst_Prefix() { - [HarmonyPrefix] - [HarmonyPatch(typeof(InserterRenderer), nameof(InserterRenderer.AddInst), new Type[] { typeof(int), typeof(Vector3), typeof(Quaternion), typeof(bool) })] - [HarmonyPatch(typeof(InserterRenderer), nameof(InserterRenderer.AddInst), new Type[] { typeof(int), typeof(Vector3), typeof(Quaternion), typeof(Vector3), typeof(Quaternion), typeof(int), typeof(int), typeof(bool) })] - public static bool AddInst_Prefix() - { - //Do not call renderer, if user is not on the planet as the request - return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; - } + //Do not call renderer, if user is not on the planet as the request + return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || + GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; + } - [HarmonyPrefix] - [HarmonyPatch(nameof(InserterRenderer.AlterInst), new Type[] { typeof(int), typeof(int), typeof(Vector3), typeof(Quaternion), typeof(bool) })] - public static bool AlterInst_Prefix() - { - //Do not call renderer, if user is not on the planet as the request - return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; - } + [HarmonyPrefix] + [HarmonyPatch(nameof(InserterRenderer.AlterInst), typeof(int), typeof(int), typeof(Vector3), typeof(Quaternion), + typeof(bool))] + public static bool AlterInst_Prefix() + { + //Do not call renderer, if user is not on the planet as the request + return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || + GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; + } - [HarmonyPrefix] - [HarmonyPatch(nameof(InserterRenderer.RemoveInst))] - public static bool RemoveInst_Prefix() - { - //Do not call renderer, if user is not on the planet as the request - return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; - } + [HarmonyPrefix] + [HarmonyPatch(nameof(InserterRenderer.RemoveInst))] + public static bool RemoveInst_Prefix() + { + //Do not call renderer, if user is not on the planet as the request + return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || + GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; } } diff --git a/NebulaPatcher/Patches/Dynamic/LabRenderer_Patch.cs b/NebulaPatcher/Patches/Dynamic/LabRenderer_Patch.cs index 0fa37c912..49f0f8942 100644 --- a/NebulaPatcher/Patches/Dynamic/LabRenderer_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/LabRenderer_Patch.cs @@ -1,37 +1,44 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaAPI; using NebulaWorld; -using System; using UnityEngine; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(LabRenderer))] +internal class LabRenderer_Patch { - [HarmonyPatch(typeof(LabRenderer))] - internal class LabRenderer_Patch + [HarmonyPrefix] + [HarmonyPatch(typeof(LabRenderer), nameof(LabRenderer.AddInst), typeof(int), typeof(Vector3), typeof(Quaternion), + typeof(bool))] + [HarmonyPatch(typeof(LabRenderer), nameof(LabRenderer.AddInst), typeof(int), typeof(Vector3), typeof(Quaternion), + typeof(uint), typeof(bool))] + public static bool AddInst_Prefix() { - [HarmonyPrefix] - [HarmonyPatch(typeof(LabRenderer), nameof(LabRenderer.AddInst), new Type[] { typeof(int), typeof(Vector3), typeof(Quaternion), typeof(bool) })] - [HarmonyPatch(typeof(LabRenderer), nameof(LabRenderer.AddInst), new Type[] { typeof(int), typeof(Vector3), typeof(Quaternion), typeof(uint), typeof(bool) })] - public static bool AddInst_Prefix() - { - //Do not call renderer, if user is not on the planet as the request - return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; - } + //Do not call renderer, if user is not on the planet as the request + return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || + GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; + } - [HarmonyPrefix] - [HarmonyPatch(nameof(LabRenderer.AlterInst), new Type[] { typeof(int), typeof(int), typeof(Vector3), typeof(Quaternion), typeof(bool) })] - public static bool AlterInst_Prefix() - { - //Do not call renderer, if user is not on the planet as the request - return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; - } + [HarmonyPrefix] + [HarmonyPatch(nameof(LabRenderer.AlterInst), typeof(int), typeof(int), typeof(Vector3), typeof(Quaternion), typeof(bool))] + public static bool AlterInst_Prefix() + { + //Do not call renderer, if user is not on the planet as the request + return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || + GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; + } - [HarmonyPrefix] - [HarmonyPatch(nameof(LabRenderer.RemoveInst))] - public static bool RemoveInst_Prefix() - { - //Do not call renderer, if user is not on the planet as the request - return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; - } + [HarmonyPrefix] + [HarmonyPatch(nameof(LabRenderer.RemoveInst))] + public static bool RemoveInst_Prefix() + { + //Do not call renderer, if user is not on the planet as the request + return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || + GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; } } diff --git a/NebulaPatcher/Patches/Dynamic/LogisticCourierRendererr_Patch.cs b/NebulaPatcher/Patches/Dynamic/LogisticCourierRendererr_Patch.cs index 80283c9df..0903dcf48 100644 --- a/NebulaPatcher/Patches/Dynamic/LogisticCourierRendererr_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/LogisticCourierRendererr_Patch.cs @@ -1,62 +1,66 @@ -using HarmonyLib; -using NebulaModel; -using NebulaWorld; +#region + using System; +using HarmonyLib; +using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(LogisticCourierRenderer))] +internal class LogisticCourierRendererr_Patch { - [HarmonyPatch(typeof(LogisticCourierRenderer))] - internal class LogisticCourierRendererr_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(LogisticCourierRenderer.Update))] + public static bool Update_Prefix(LogisticCourierRenderer __instance) { - [HarmonyPrefix] - [HarmonyPatch(nameof(LogisticCourierRenderer.Update))] - public static bool Update_Prefix(LogisticCourierRenderer __instance) + if (!Multiplayer.IsActive) { - if (!Multiplayer.IsActive) - { - return true; - } + return true; + } - __instance.courierCount = 0; - if (__instance.transport == null) - { - return false; - } - for (int i = 1; i < __instance.transport.dispenserCursor; i++) + __instance.courierCount = 0; + if (__instance.transport == null) + { + return false; + } + for (var i = 1; i < __instance.transport.dispenserCursor; i++) + { + var dispenserComponent = __instance.transport.dispenserPool[i]; + if (dispenserComponent != null && dispenserComponent.id == i) { - DispenserComponent dispenserComponent = __instance.transport.dispenserPool[i]; - if (dispenserComponent != null && dispenserComponent.id == i) + var num = __instance.courierCount + dispenserComponent.workCourierCount; + if (num > 0) { - int num = __instance.courierCount + dispenserComponent.workCourierCount; - if (num > 0) + while (__instance.capacity < num) { - while (__instance.capacity < num) - { - __instance.Expand2x(); - } - Array.Copy(dispenserComponent.workCourierDatas, 0, __instance.couriersArr, __instance.courierCount, dispenserComponent.workCourierCount); - __instance.courierCount = num; + __instance.Expand2x(); } + Array.Copy(dispenserComponent.workCourierDatas, 0, __instance.couriersArr, __instance.courierCount, + dispenserComponent.workCourierCount); + __instance.courierCount = num; } } + } - // Add remote couriers animation - int courierCount = __instance.courierCount + Multiplayer.Session.Couriers.CourierCount; - if (courierCount > 0) + // Add remote couriers animation + var courierCount = __instance.courierCount + Multiplayer.Session.Couriers.CourierCount; + if (courierCount > 0) + { + while (__instance.capacity < courierCount) { - while (__instance.capacity < courierCount) - { - __instance.Expand2x(); - } - Array.Copy(Multiplayer.Session.Couriers.CourierDatas, 0, __instance.couriersArr, __instance.courierCount, Multiplayer.Session.Couriers.CourierCount); - __instance.courierCount = courierCount; + __instance.Expand2x(); } + Array.Copy(Multiplayer.Session.Couriers.CourierDatas, 0, __instance.couriersArr, __instance.courierCount, + Multiplayer.Session.Couriers.CourierCount); + __instance.courierCount = courierCount; + } - if (__instance.couriersBuffer != null) - { - __instance.couriersBuffer.SetData(__instance.couriersArr, 0, 0, __instance.courierCount); - } - return false; + if (__instance.couriersBuffer != null) + { + __instance.couriersBuffer.SetData(__instance.couriersArr, 0, 0, __instance.courierCount); } + return false; } } diff --git a/NebulaPatcher/Patches/Dynamic/MechaDroneLogic_Patch.cs b/NebulaPatcher/Patches/Dynamic/MechaDroneLogic_Patch.cs index 371a62733..59941b75f 100644 --- a/NebulaPatcher/Patches/Dynamic/MechaDroneLogic_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/MechaDroneLogic_Patch.cs @@ -1,19 +1,22 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(MechaDroneLogic))] +internal class MechaDroneLogic_Patch { - [HarmonyPatch(typeof(MechaDroneLogic))] - internal class MechaDroneLogic_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(MechaDroneLogic.UpdateTargets))] + public static void UpdateTargets_Prefix() { - [HarmonyPrefix] - [HarmonyPatch(nameof(MechaDroneLogic.UpdateTargets))] - public static void UpdateTargets_Prefix() + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) - { - Multiplayer.Session.Drones.ClearCachedPositions(); - } + Multiplayer.Session.Drones.ClearCachedPositions(); } } } diff --git a/NebulaPatcher/Patches/Dynamic/Mecha_Patch.cs b/NebulaPatcher/Patches/Dynamic/Mecha_Patch.cs index d80826863..1a19570ab 100644 --- a/NebulaPatcher/Patches/Dynamic/Mecha_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/Mecha_Patch.cs @@ -1,69 +1,72 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaModel.Packets.Players; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(Mecha))] +internal class Mecha_Patch { - [HarmonyPatch(typeof(Mecha))] - internal class Mecha_Patch + [HarmonyPostfix] + [HarmonyPatch(nameof(Mecha.GameTick))] + public static void GameTick_Postfix(float dt) { - [HarmonyPostfix] - [HarmonyPatch(nameof(Mecha.GameTick))] - public static void GameTick_Postfix(float dt) + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) - { - Multiplayer.Session.World.OnDronesGameTick(dt); - } + Multiplayer.Session.World.OnDronesGameTick(dt); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(Mecha.GenerateEnergy))] - public static bool Mecha_GenerateEnergy_Prefix(Mecha __instance) + [HarmonyPrefix] + [HarmonyPatch(nameof(Mecha.GenerateEnergy))] + public static bool Mecha_GenerateEnergy_Prefix(Mecha __instance) + { + if (!Multiplayer.IsActive) { - if (!Multiplayer.IsActive) - { - return true; - } - - // some players managed to break the fuel chamber on clients. - // the game thought there is still fuel burning while not adding energy to the mecha and preventing new fuel from beeing added. - // this checks for this corner case and resets the reactor energy to 0 (empty fuel chamber as displayed to the player) - if (!Multiplayer.Session.LocalPlayer.IsHost && __instance.reactorEnergy > 0 && __instance.reactorItemId == 0) - { - __instance.reactorEnergy = 0; - } return true; } - // We can't do this as client as we won't be able to get_nearestPlanet() since we do not currently have all of the factory info - [HarmonyPrefix] - [HarmonyPatch(typeof(Mecha), nameof(Mecha.AddProductionStat))] - public static bool AddProductionStat_Prefix(int itemId, int itemCount) + // some players managed to break the fuel chamber on clients. + // the game thought there is still fuel burning while not adding energy to the mecha and preventing new fuel from beeing added. + // this checks for this corner case and resets the reactor energy to 0 (empty fuel chamber as displayed to the player) + if (!Multiplayer.Session.LocalPlayer.IsHost && __instance.reactorEnergy > 0 && __instance.reactorItemId == 0) { - if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) - { - return true; - } - - // Send packet to host to add stat - Multiplayer.Session.Network.SendPacket(new PlayerMechaStat(itemId, itemCount)); - return false; + __instance.reactorEnergy = 0; } + return true; + } - // We can't do this as client as we won't be able to get_nearestPlanet() since we do not currently have all of the factory info - [HarmonyPrefix] - [HarmonyPatch(typeof(Mecha), nameof(Mecha.AddConsumptionStat))] - public static bool AddConsumptionStat_Prefix(int itemId, int itemCount) + // We can't do this as client as we won't be able to get_nearestPlanet() since we do not currently have all of the factory info + [HarmonyPrefix] + [HarmonyPatch(typeof(Mecha), nameof(Mecha.AddProductionStat))] + public static bool AddProductionStat_Prefix(int itemId, int itemCount) + { + if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) { - if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) - { - return true; - } + return true; + } + + // Send packet to host to add stat + Multiplayer.Session.Network.SendPacket(new PlayerMechaStat(itemId, itemCount)); + return false; + } - // Use negative itemCount to indicate that it is consumption stat - Multiplayer.Session.Network.SendPacket(new PlayerMechaStat(itemId, -itemCount)); - return false; + // We can't do this as client as we won't be able to get_nearestPlanet() since we do not currently have all of the factory info + [HarmonyPrefix] + [HarmonyPatch(typeof(Mecha), nameof(Mecha.AddConsumptionStat))] + public static bool AddConsumptionStat_Prefix(int itemId, int itemCount) + { + if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) + { + return true; } + + // Use negative itemCount to indicate that it is consumption stat + Multiplayer.Session.Network.SendPacket(new PlayerMechaStat(itemId, -itemCount)); + return false; } } diff --git a/NebulaPatcher/Patches/Dynamic/MilestoneSystem_Patch.cs b/NebulaPatcher/Patches/Dynamic/MilestoneSystem_Patch.cs index d4ea5213d..b8503d05f 100644 --- a/NebulaPatcher/Patches/Dynamic/MilestoneSystem_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/MilestoneSystem_Patch.cs @@ -1,28 +1,30 @@ -using HarmonyLib; -using NebulaModel.Logger; +#region + +using HarmonyLib; using NebulaModel.Packets.Statistics; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(MilestoneSystem))] +internal class MilestoneSystem_Patch { - [HarmonyPatch(typeof(MilestoneSystem))] - internal class MilestoneSystem_Patch + [HarmonyPostfix] + [HarmonyPatch(nameof(MilestoneSystem.UnlockMilestone))] + public static void UnlockMilestone_Postfix(MilestoneSystem __instance, int id, long unlockTick) { - [HarmonyPostfix] - [HarmonyPatch(nameof(MilestoneSystem.UnlockMilestone))] - public static void UnlockMilestone_Postfix(MilestoneSystem __instance, int id, long unlockTick) + if (!Multiplayer.IsActive || Multiplayer.Session.Statistics.IsIncomingRequest) + { + return; + } + + if (__instance.milestoneDatas.TryGetValue(id, out var milestoneData)) { - if (!Multiplayer.IsActive || Multiplayer.Session.Statistics.IsIncomingRequest) - { - return; - } - - if (__instance.milestoneDatas.TryGetValue(id, out MilestoneData milestoneData)) - { - int patternId = milestoneData.journalData.patternId; - long[] parameters = milestoneData.journalData.parameters; - Multiplayer.Session.Network.SendPacket(new MilestoneUnlockPacket(id, unlockTick, patternId, parameters)); - } + var patternId = milestoneData.journalData.patternId; + var parameters = milestoneData.journalData.parameters; + Multiplayer.Session.Network.SendPacket(new MilestoneUnlockPacket(id, unlockTick, patternId, parameters)); } } } diff --git a/NebulaPatcher/Patches/Dynamic/MilkyWayWebClient_Patch.cs b/NebulaPatcher/Patches/Dynamic/MilkyWayWebClient_Patch.cs index 869711c26..62f69d851 100644 --- a/NebulaPatcher/Patches/Dynamic/MilkyWayWebClient_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/MilkyWayWebClient_Patch.cs @@ -1,17 +1,20 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(MilkyWayWebClient))] +internal class MilkyWayWebClient_Patch { - [HarmonyPatch(typeof(MilkyWayWebClient))] - internal class MilkyWayWebClient_Patch + [HarmonyPostfix] + [HarmonyPatch(nameof(MilkyWayWebClient.canUploadGame), MethodType.Getter)] + public static void Get_canUploadGame_Postfix(ref bool __result) { - [HarmonyPostfix] - [HarmonyPatch(nameof(MilkyWayWebClient.canUploadGame), MethodType.Getter)] - public static void Get_canUploadGame_Postfix(ref bool __result) - { - // We don't want to upload Milky Way data if we are playing MP - __result &= !Multiplayer.IsActive; - } + // We don't want to upload Milky Way data if we are playing MP + __result &= !Multiplayer.IsActive; } } diff --git a/NebulaPatcher/Patches/Dynamic/MonitorComponent_Patch.cs b/NebulaPatcher/Patches/Dynamic/MonitorComponent_Patch.cs index ea50fd95f..2925321f4 100644 --- a/NebulaPatcher/Patches/Dynamic/MonitorComponent_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/MonitorComponent_Patch.cs @@ -1,169 +1,173 @@ -using HarmonyLib; -using NebulaWorld; +#region + +using HarmonyLib; using NebulaModel.Packets.Factory.Monitor; +using NebulaWorld; using NebulaWorld.Warning; -using UnityEngine; -namespace NebulaPatcher.Patches.Dynamic -{ +#endregion + +namespace NebulaPatcher.Patches.Dynamic; #pragma warning disable Harmony003 // Harmony non-ref patch parameters modified - [HarmonyPatch(typeof(MonitorComponent))] - internal class MonitorComponent_Patch +[HarmonyPatch(typeof(MonitorComponent))] +internal class MonitorComponent_Patch +{ + [HarmonyPrefix] + [HarmonyPatch(nameof(MonitorComponent.SetPassColorId))] + public static void SetPassColorId_Prefix(MonitorComponent __instance, byte __0) { - [HarmonyPrefix] - [HarmonyPatch(nameof(MonitorComponent.SetPassColorId))] - public static void SetPassColorId_Prefix(MonitorComponent __instance, byte __0) + if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) { - if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) - { - //Assume the monitor is on local planet - int planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; - Multiplayer.Session.Network.SendPacketToLocalStar( - new MonitorSettingUpdatePacket(planetId, __instance.id, MonitorSettingEvent.SetPassColorId, __0)); - } + //Assume the monitor is on local planet + var planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; + Multiplayer.Session.Network.SendPacketToLocalStar( + new MonitorSettingUpdatePacket(planetId, __instance.id, MonitorSettingEvent.SetPassColorId, __0)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(MonitorComponent.SetFailColorId))] - public static void SetFailColorId_Prefix(MonitorComponent __instance, int __0) + [HarmonyPrefix] + [HarmonyPatch(nameof(MonitorComponent.SetFailColorId))] + public static void SetFailColorId_Prefix(MonitorComponent __instance, int __0) + { + if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) { - if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) - { - int planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; - Multiplayer.Session.Network.SendPacketToLocalStar( - new MonitorSettingUpdatePacket(planetId, __instance.id, MonitorSettingEvent.SetFailColorId, __0)); - } + var planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; + Multiplayer.Session.Network.SendPacketToLocalStar( + new MonitorSettingUpdatePacket(planetId, __instance.id, MonitorSettingEvent.SetFailColorId, __0)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(MonitorComponent.SetPassOperator))] - public static void SetPassOperator_Prefix(MonitorComponent __instance, int __0) + [HarmonyPrefix] + [HarmonyPatch(nameof(MonitorComponent.SetPassOperator))] + public static void SetPassOperator_Prefix(MonitorComponent __instance, int __0) + { + if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) { - if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) - { - int planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; - Multiplayer.Session.Network.SendPacketToLocalStar( - new MonitorSettingUpdatePacket(planetId, __instance.id, MonitorSettingEvent.SetPassOperator, __0)); - } + var planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; + Multiplayer.Session.Network.SendPacketToLocalStar( + new MonitorSettingUpdatePacket(planetId, __instance.id, MonitorSettingEvent.SetPassOperator, __0)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(MonitorComponent.SetSpawnOperator))] - public static void SetSpawnOperator_Prefix(MonitorComponent __instance, byte __0) + [HarmonyPrefix] + [HarmonyPatch(nameof(MonitorComponent.SetSpawnOperator))] + public static void SetSpawnOperator_Prefix(MonitorComponent __instance, byte __0) + { + if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) { - if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) + if (__0 == __instance.spawnItemOperator) { - if (__0 == __instance.spawnItemOperator) - { - // don't send the packet if spawnItemOperator is same - return; - } - int planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; - Multiplayer.Session.Network.SendPacketToLocalStar( - new MonitorSettingUpdatePacket(planetId, __instance.id, MonitorSettingEvent.SetSpawnOperator, __0)); + // don't send the packet if spawnItemOperator is same + return; } + var planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; + Multiplayer.Session.Network.SendPacketToLocalStar( + new MonitorSettingUpdatePacket(planetId, __instance.id, MonitorSettingEvent.SetSpawnOperator, __0)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(MonitorComponent.SetMonitorMode))] - public static void SetMonitorMode_Prefix(MonitorComponent __instance, int __0) + [HarmonyPrefix] + [HarmonyPatch(nameof(MonitorComponent.SetMonitorMode))] + public static void SetMonitorMode_Prefix(MonitorComponent __instance, int __0) + { + if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) { - if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) - { - int planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; - Multiplayer.Session.Network.SendPacketToLocalStar( - new MonitorSettingUpdatePacket(planetId, __instance.id, MonitorSettingEvent.SetMonitorMode, __0)); - } + var planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; + Multiplayer.Session.Network.SendPacketToLocalStar( + new MonitorSettingUpdatePacket(planetId, __instance.id, MonitorSettingEvent.SetMonitorMode, __0)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(MonitorComponent.SetSystemWarningMode))] - public static void SetSystemWarningMode_Prefix(MonitorComponent __instance, int __0) + [HarmonyPrefix] + [HarmonyPatch(nameof(MonitorComponent.SetSystemWarningMode))] + public static void SetSystemWarningMode_Prefix(MonitorComponent __instance, int __0) + { + if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) { - if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) - { - int planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; - Multiplayer.Session.Network.SendPacketToLocalStar( - new MonitorSettingUpdatePacket(planetId, __instance.id, MonitorSettingEvent.SetSystemWarningMode, __0)); - } + var planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; + Multiplayer.Session.Network.SendPacketToLocalStar( + new MonitorSettingUpdatePacket(planetId, __instance.id, MonitorSettingEvent.SetSystemWarningMode, __0)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(MonitorComponent.SetSystemWarningSignalId))] - public static void SetSystemWarningSignalId_Prefix(MonitorComponent __instance, int __0) + [HarmonyPrefix] + [HarmonyPatch(nameof(MonitorComponent.SetSystemWarningSignalId))] + public static void SetSystemWarningSignalId_Prefix(MonitorComponent __instance, int __0) + { + if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) { - if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) - { - int planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; - Multiplayer.Session.Network.SendPacketToLocalStar( - new MonitorSettingUpdatePacket(planetId, __instance.id, MonitorSettingEvent.SetSystemWarningSignalId, __0)); - } + var planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; + Multiplayer.Session.Network.SendPacketToLocalStar( + new MonitorSettingUpdatePacket(planetId, __instance.id, MonitorSettingEvent.SetSystemWarningSignalId, __0)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(MonitorComponent.SetCargoFilter))] - public static void SetCargoFilter_Prefix(MonitorComponent __instance, int __0) + [HarmonyPrefix] + [HarmonyPatch(nameof(MonitorComponent.SetCargoFilter))] + public static void SetCargoFilter_Prefix(MonitorComponent __instance, int __0) + { + if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) { - if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) - { - int planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; - Multiplayer.Session.Network.SendPacketToLocalStar( - new MonitorSettingUpdatePacket(planetId, __instance.id, MonitorSettingEvent.SetCargoFilter, __0)); - } - } + var planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; + Multiplayer.Session.Network.SendPacketToLocalStar( + new MonitorSettingUpdatePacket(planetId, __instance.id, MonitorSettingEvent.SetCargoFilter, __0)); + } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(MonitorComponent.SetTargetCargoBytes))] - public static void SSetTargetCargoBytes_Prefix(MonitorComponent __instance, int __0) + [HarmonyPrefix] + [HarmonyPatch(nameof(MonitorComponent.SetTargetCargoBytes))] + public static void SSetTargetCargoBytes_Prefix(MonitorComponent __instance, int __0) + { + if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) { - if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) - { - int planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; - Multiplayer.Session.Network.SendPacketToLocalStar( - new MonitorSettingUpdatePacket(planetId, __instance.id, MonitorSettingEvent.SetTargetCargoBytes, __0)); - } + var planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; + Multiplayer.Session.Network.SendPacketToLocalStar( + new MonitorSettingUpdatePacket(planetId, __instance.id, MonitorSettingEvent.SetTargetCargoBytes, __0)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(MonitorComponent.SetPeriodTickCount))] - public static void SetPeriodTickCount_Prefix(MonitorComponent __instance, int __0) + [HarmonyPrefix] + [HarmonyPatch(nameof(MonitorComponent.SetPeriodTickCount))] + public static void SetPeriodTickCount_Prefix(MonitorComponent __instance, int __0) + { + if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) { - if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) - { - int planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; - Multiplayer.Session.Network.SendPacketToLocalStar( - new MonitorSettingUpdatePacket(planetId, __instance.id, MonitorSettingEvent.SetPeriodTickCount, __0)); - } + var planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; + Multiplayer.Session.Network.SendPacketToLocalStar( + new MonitorSettingUpdatePacket(planetId, __instance.id, MonitorSettingEvent.SetPeriodTickCount, __0)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(MonitorComponent.SetTargetBelt))] - public static void SetTargetBelt_Prefix(MonitorComponent __instance, int __0, int __1) + [HarmonyPrefix] + [HarmonyPatch(nameof(MonitorComponent.SetTargetBelt))] + public static void SetTargetBelt_Prefix(MonitorComponent __instance, int __0, int __1) + { + //This is required for putting monitor over belt works properly + if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) { - //This is required for putting monitor over belt works properly - if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) - { - int planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; - Multiplayer.Session.Network.SendPacketToLocalStar( - new MonitorSettingUpdatePacket(planetId, __instance.id, MonitorSettingEvent.SetTargetBelt, __0, __1)); - } + var planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; + Multiplayer.Session.Network.SendPacketToLocalStar( + new MonitorSettingUpdatePacket(planetId, __instance.id, MonitorSettingEvent.SetTargetBelt, __0, __1)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(MonitorComponent.InternalUpdate))] - public static bool InternalUpdate_Prefix(MonitorComponent __instance, CargoTraffic _traffic, EntityData[] _entityPool, SpeakerComponent[] _speakerPool, AnimData[] _animPool) + [HarmonyPrefix] + [HarmonyPatch(nameof(MonitorComponent.InternalUpdate))] + public static bool InternalUpdate_Prefix(MonitorComponent __instance, CargoTraffic _traffic, EntityData[] _entityPool, + SpeakerComponent[] _speakerPool, AnimData[] _animPool) + { + if (Multiplayer.IsActive && __instance.targetBeltId > _traffic.beltPool.Length) { - if (Multiplayer.IsActive && __instance.targetBeltId > _traffic.beltPool.Length) + if (Multiplayer.Session.LocalPlayer.IsHost) { - if (Multiplayer.Session.LocalPlayer.IsHost) - { - _traffic.factory.RemoveEntityWithComponents(__instance.entityId); - WarningManager.DisplayTemporaryWarning($"Broken Traffic Monitor detected on {_traffic.factory.planet.displayName}\nIt was removed, clients should reconnect!", 15000); - } - return false; + _traffic.factory.RemoveEntityWithComponents(__instance.entityId); + WarningManager.DisplayTemporaryWarning( + $"Broken Traffic Monitor detected on {_traffic.factory.planet.displayName}\nIt was removed, clients should reconnect!", + 15000); } - return true; + return false; } + return true; } -#pragma warning restore Harmony003 // Harmony non-ref patch parameters modified } +#pragma warning restore Harmony003 // Harmony non-ref patch parameters modified diff --git a/NebulaPatcher/Patches/Dynamic/ObjectRenderer_Patch.cs b/NebulaPatcher/Patches/Dynamic/ObjectRenderer_Patch.cs index 450f6a890..3aefb8fff 100644 --- a/NebulaPatcher/Patches/Dynamic/ObjectRenderer_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/ObjectRenderer_Patch.cs @@ -1,44 +1,54 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaAPI; using NebulaWorld; -using System; using UnityEngine; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(ObjectRenderer))] +internal class ObjectRenderer_Patch { - [HarmonyPatch(typeof(ObjectRenderer))] - internal class ObjectRenderer_Patch + [HarmonyPrefix] + [HarmonyPatch(typeof(ObjectRenderer), nameof(ObjectRenderer.AddInst), typeof(int), typeof(Vector3), typeof(Quaternion), + typeof(bool))] + [HarmonyPatch(typeof(ObjectRenderer), nameof(ObjectRenderer.AddInst), typeof(int), typeof(Vector3), typeof(Quaternion), + typeof(uint), typeof(bool))] + public static bool AddInst_Prefix() + { + //Do not call renderer, if user is not on the planet as the request + return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || + GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; + } + + [HarmonyPrefix] + [HarmonyPatch(nameof(ObjectRenderer.AlterInst), typeof(int), typeof(int), typeof(Vector3), typeof(Quaternion), + typeof(bool))] + public static bool AlterInst_Prefix() { - [HarmonyPrefix] - [HarmonyPatch(typeof(ObjectRenderer), nameof(ObjectRenderer.AddInst), new Type[] { typeof(int), typeof(Vector3), typeof(Quaternion), typeof(bool) })] - [HarmonyPatch(typeof(ObjectRenderer), nameof(ObjectRenderer.AddInst), new Type[] { typeof(int), typeof(Vector3), typeof(Quaternion), typeof(uint), typeof(bool) })] - public static bool AddInst_Prefix() - { - //Do not call renderer, if user is not on the planet as the request - return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; - } + //Do not call renderer, if user is not on the planet as the request + return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || + GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; + } - [HarmonyPrefix] - [HarmonyPatch(nameof(ObjectRenderer.AlterInst), new Type[] { typeof(int), typeof(int), typeof(Vector3), typeof(Quaternion), typeof(bool) })] - public static bool AlterInst_Prefix() - { - //Do not call renderer, if user is not on the planet as the request - return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; - } - [HarmonyPrefix] - [HarmonyPatch(nameof(ObjectRenderer.AlterInst), new Type[] { typeof(int), typeof(int), typeof(Vector3), typeof(bool) })] - public static bool AlterInst_Prefix2() - { - //Do not call renderer, if user is not on the planet as the request - return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; - } + [HarmonyPrefix] + [HarmonyPatch(nameof(ObjectRenderer.AlterInst), typeof(int), typeof(int), typeof(Vector3), typeof(bool))] + public static bool AlterInst_Prefix2() + { + //Do not call renderer, if user is not on the planet as the request + return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || + GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; + } - [HarmonyPrefix] - [HarmonyPatch(nameof(ObjectRenderer.RemoveInst))] - public static bool RemoveInst_Prefix() - { - //Do not call renderer, if user is not on the planet as the request - return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; - } + [HarmonyPrefix] + [HarmonyPatch(nameof(ObjectRenderer.RemoveInst))] + public static bool RemoveInst_Prefix() + { + //Do not call renderer, if user is not on the planet as the request + return !Multiplayer.IsActive || Multiplayer.Session.Factories.TargetPlanet == NebulaModAPI.PLANET_NONE || + GameMain.mainPlayer.planetId == Multiplayer.Session.Factories.TargetPlanet; } } diff --git a/NebulaPatcher/Patches/Dynamic/PlanetData_Patch.cs b/NebulaPatcher/Patches/Dynamic/PlanetData_Patch.cs index 854abfd83..3b3fe1fa6 100644 --- a/NebulaPatcher/Patches/Dynamic/PlanetData_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/PlanetData_Patch.cs @@ -1,103 +1,110 @@ -using HarmonyLib; +#region + +using HarmonyLib; +using NebulaModel; using NebulaModel.Logger; using NebulaWorld; +using UnityEngine; + +#endregion -namespace NebulaPatcher.Patches.Dynamic +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(PlanetData))] +internal class PlanetData_Patch { - [HarmonyPatch(typeof(PlanetData))] - internal class PlanetData_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(PlanetData.LoadFactory))] + public static void LoadFactory_Prefix() { - [HarmonyPrefix] - [HarmonyPatch(nameof(PlanetData.LoadFactory))] - public static void LoadFactory_Prefix() + if (Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsHost) { - if (Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsHost) - { - // Stop packet processing for host until factory is loaded - ((NebulaModel.NetworkProvider)Multiplayer.Session.Network).PacketProcessor.Enable = false; - Log.Info($"Pause PacketProcessor (PlanetData.LoadFactory)"); - } + // Stop packet processing for host until factory is loaded + ((NetworkProvider)Multiplayer.Session.Network).PacketProcessor.Enable = false; + Log.Info("Pause PacketProcessor (PlanetData.LoadFactory)"); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(PlanetData.UpdateDirtyMesh))] - public static bool UpdateDirtyMesh_Prefix(PlanetData __instance, int dirtyIdx, ref bool __result) + [HarmonyPrefix] + [HarmonyPatch(nameof(PlanetData.UpdateDirtyMesh))] + public static bool UpdateDirtyMesh_Prefix(PlanetData __instance, int dirtyIdx, ref bool __result) + { + // Temporary fix: skip function when the mesh is null + if (__instance.dirtyFlags[dirtyIdx] && __instance.meshes[dirtyIdx] == null) { - // Temporary fix: skip function when the mesh is null - if (__instance.dirtyFlags[dirtyIdx] && __instance.meshes[dirtyIdx] == null) - { - Log.Warn(__instance == GameMain.localPlanet ? "Local" : "Remote" + $" PlanetData.UpdateDirtyMesh: meshes[{dirtyIdx}] is null"); - __result = false; - return false; - } - - return true; + Log.Warn(__instance == GameMain.localPlanet + ? "Local" + : "Remote" + $" PlanetData.UpdateDirtyMesh: meshes[{dirtyIdx}] is null"); + __result = false; + return false; } - [HarmonyPrefix] - [HarmonyPatch(nameof(PlanetData.UnloadMeshes))] - public static bool UnloadMeshes_Prefix(PlanetData __instance) - { - //Host should not unload planet meshes, since he need to permorm all terrain operations - if (Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsHost) - { - //Do not unload meshes, just hide them so it is not visible - UnloadVisuals(__instance); - return false; - } + return true; + } - return true; + [HarmonyPrefix] + [HarmonyPatch(nameof(PlanetData.UnloadMeshes))] + public static bool UnloadMeshes_Prefix(PlanetData __instance) + { + //Host should not unload planet meshes, since he need to permorm all terrain operations + if (Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsHost) + { + //Do not unload meshes, just hide them so it is not visible + UnloadVisuals(__instance); + return false; } - [HarmonyPrefix] - [HarmonyPatch(nameof(PlanetData.UnloadData))] - public static bool UnloadData_Prefix() - { - //Host should not unload planet data, since he need to permorm all operations from users - if (Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsHost) - { - return false; - } + return true; + } - return true; + [HarmonyPrefix] + [HarmonyPatch(nameof(PlanetData.UnloadData))] + public static bool UnloadData_Prefix() + { + //Host should not unload planet data, since he need to permorm all operations from users + if (Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsHost) + { + return false; } - public static void UnloadVisuals(PlanetData __instance) + return true; + } + + public static void UnloadVisuals(PlanetData __instance) + { + if (__instance.gameObject != null) + { + __instance.gameObject.SetActive(false); + } + if (__instance.terrainMaterial != null) + { + Object.Destroy(__instance.terrainMaterial); + __instance.terrainMaterial = null; + } + if (__instance.oceanMaterial != null) + { + Object.Destroy(__instance.oceanMaterial); + __instance.oceanMaterial = null; + } + if (__instance.atmosMaterial != null) + { + Object.Destroy(__instance.atmosMaterial); + __instance.atmosMaterial = null; + } + if (__instance.minimapMaterial != null) + { + Object.Destroy(__instance.minimapMaterial); + __instance.minimapMaterial = null; + } + if (__instance.reformMaterial0 != null) + { + Object.Destroy(__instance.reformMaterial0); + __instance.reformMaterial0 = null; + } + if (__instance.reformMaterial1 != null) { - if (__instance.gameObject != null) - { - __instance.gameObject.SetActive(false); - } - if (__instance.terrainMaterial != null) - { - UnityEngine.Object.Destroy(__instance.terrainMaterial); - __instance.terrainMaterial = null; - } - if (__instance.oceanMaterial != null) - { - UnityEngine.Object.Destroy(__instance.oceanMaterial); - __instance.oceanMaterial = null; - } - if (__instance.atmosMaterial != null) - { - UnityEngine.Object.Destroy(__instance.atmosMaterial); - __instance.atmosMaterial = null; - } - if (__instance.minimapMaterial != null) - { - UnityEngine.Object.Destroy(__instance.minimapMaterial); - __instance.minimapMaterial = null; - } - if (__instance.reformMaterial0 != null) - { - UnityEngine.Object.Destroy(__instance.reformMaterial0); - __instance.reformMaterial0 = null; - } - if (__instance.reformMaterial1 != null) - { - UnityEngine.Object.Destroy(__instance.reformMaterial1); - __instance.reformMaterial1 = null; - } + Object.Destroy(__instance.reformMaterial1); + __instance.reformMaterial1 = null; } } } diff --git a/NebulaPatcher/Patches/Dynamic/PlanetFactory_Patch.cs b/NebulaPatcher/Patches/Dynamic/PlanetFactory_Patch.cs index 26ca0b726..59d3d9d29 100644 --- a/NebulaPatcher/Patches/Dynamic/PlanetFactory_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/PlanetFactory_Patch.cs @@ -1,4 +1,6 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Networking; @@ -18,597 +20,655 @@ using NebulaModel.Packets.Logistics; using NebulaModel.Packets.Planet; using NebulaWorld; +using NebulaWorld.Factory; using UnityEngine; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(PlanetFactory))] +internal class PlanetFactory_patch { - [HarmonyPatch(typeof(PlanetFactory))] - internal class PlanetFactory_patch + [HarmonyPostfix] + [HarmonyPatch(nameof(PlanetFactory.AddPrebuildData))] + public static void AddPrebuildData_Postfix(PlanetFactory __instance, PrebuildData prebuild, ref int __result) { - [HarmonyPostfix] - [HarmonyPatch(nameof(PlanetFactory.AddPrebuildData))] - public static void AddPrebuildData_Postfix(PlanetFactory __instance, PrebuildData prebuild, ref int __result) + if (!Multiplayer.IsActive) { - if (!Multiplayer.IsActive) - { - return; - } + return; + } - // If the host game called the method, we need to compute the PrebuildId ourself - if (Multiplayer.Session.LocalPlayer.IsHost) - { - Multiplayer.Session.Factories.SetPrebuildRequest(__instance.planetId, __result, Multiplayer.Session.LocalPlayer.Id); - } + // If the host game called the method, we need to compute the PrebuildId ourself + if (Multiplayer.Session.LocalPlayer.IsHost) + { + Multiplayer.Session.Factories.SetPrebuildRequest(__instance.planetId, __result, Multiplayer.Session.LocalPlayer.Id); + } + } + + [HarmonyPrefix] + [HarmonyPatch(nameof(PlanetFactory.BuildFinally))] + public static bool BuildFinally_Prefix(PlanetFactory __instance, Player player, int prebuildId) + { + if (!Multiplayer.IsActive) + { + return true; } - [HarmonyPrefix] - [HarmonyPatch(nameof(PlanetFactory.BuildFinally))] - public static bool BuildFinally_Prefix(PlanetFactory __instance, Player player, int prebuildId) + if (Multiplayer.Session.LocalPlayer.IsHost) { - if (!Multiplayer.IsActive) + if (!Multiplayer.Session.Factories.ContainsPrebuildRequest(__instance.planetId, prebuildId)) { - return true; + // This prevents duplicating the entity when multiple players trigger the BuildFinally for the same entity at the same time. + // If it occurs in any other circumstances, it means that we have some desynchronization between clients and host prebuilds buffers. + Log.Warn( + $"BuildFinally was called without having a corresponding PrebuildRequest for the prebuild {prebuildId} on the planet {__instance.planetId}"); + return false; } - if (Multiplayer.Session.LocalPlayer.IsHost) - { - if (!Multiplayer.Session.Factories.ContainsPrebuildRequest(__instance.planetId, prebuildId)) - { - // This prevents duplicating the entity when multiple players trigger the BuildFinally for the same entity at the same time. - // If it occurs in any other circumstances, it means that we have some desynchronization between clients and host prebuilds buffers. - Log.Warn($"BuildFinally was called without having a corresponding PrebuildRequest for the prebuild {prebuildId} on the planet {__instance.planetId}"); - return false; - } + // Remove the prebuild request from the list since we will now convert it to a real building + Multiplayer.Session.Factories.RemovePrebuildRequest(__instance.planetId, prebuildId); + } - // Remove the prebuild request from the list since we will now convert it to a real building - Multiplayer.Session.Factories.RemovePrebuildRequest(__instance.planetId, prebuildId); - } + if (Multiplayer.Session.LocalPlayer.IsHost || !Multiplayer.Session.Factories.IsIncomingRequest.Value) + { + var author = Multiplayer.Session.Factories.PacketAuthor == NebulaModAPI.AUTHOR_NONE + ? Multiplayer.Session.LocalPlayer.Id + : Multiplayer.Session.Factories.PacketAuthor; + var entityId = Multiplayer.Session.LocalPlayer.IsHost ? FactoryManager.GetNextEntityId(__instance) : -1; + Multiplayer.Session.Network.SendPacket(new BuildEntityRequest(__instance.planetId, prebuildId, author, entityId)); + } - if (Multiplayer.Session.LocalPlayer.IsHost || !Multiplayer.Session.Factories.IsIncomingRequest.Value) - { - int author = Multiplayer.Session.Factories.PacketAuthor == NebulaModAPI.AUTHOR_NONE ? Multiplayer.Session.LocalPlayer.Id : Multiplayer.Session.Factories.PacketAuthor; - int entityId = Multiplayer.Session.LocalPlayer.IsHost ? NebulaWorld.Factory.FactoryManager.GetNextEntityId(__instance) : -1; - Multiplayer.Session.Network.SendPacket(new BuildEntityRequest(__instance.planetId, prebuildId, author, entityId)); - } + if (!Multiplayer.Session.LocalPlayer.IsHost && !Multiplayer.Session.Factories.IsIncomingRequest.Value && + !Multiplayer.Session.Drones.IsPendingBuildRequest(-prebuildId)) + { + Multiplayer.Session.Drones.AddBuildRequestSent(-prebuildId); + } - if (!Multiplayer.Session.LocalPlayer.IsHost && !Multiplayer.Session.Factories.IsIncomingRequest.Value && !Multiplayer.Session.Drones.IsPendingBuildRequest(-prebuildId)) - { - Multiplayer.Session.Drones.AddBuildRequestSent(-prebuildId); - } + return Multiplayer.Session.LocalPlayer.IsHost || Multiplayer.Session.Factories.IsIncomingRequest.Value; + } - return Multiplayer.Session.LocalPlayer.IsHost || Multiplayer.Session.Factories.IsIncomingRequest.Value; + [HarmonyPrefix] + [HarmonyPatch(nameof(PlanetFactory.UpgradeFinally))] + public static bool UpgradeFinally_Prefix(PlanetFactory __instance, Player player, int objId, ItemProto replace_item_proto) + { + if (!Multiplayer.IsActive) + { + return true; } - [HarmonyPrefix] - [HarmonyPatch(nameof(PlanetFactory.UpgradeFinally))] - public static bool UpgradeFinally_Prefix(PlanetFactory __instance, Player player, int objId, ItemProto replace_item_proto) + if (objId == 0 || replace_item_proto == null) { - if (!Multiplayer.IsActive) - { - return true; - } + return false; + } - if (objId == 0 || replace_item_proto == null) - { - return false; - } + if (Multiplayer.Session.LocalPlayer.IsHost || !Multiplayer.Session.Factories.IsIncomingRequest.Value) + { + Multiplayer.Session.Network.SendPacket(new UpgradeEntityRequest(__instance.planetId, objId, replace_item_proto.ID, + Multiplayer.Session.Factories.PacketAuthor == -1 + ? Multiplayer.Session.LocalPlayer.Id + : Multiplayer.Session.Factories.PacketAuthor)); + } - if (Multiplayer.Session.LocalPlayer.IsHost || !Multiplayer.Session.Factories.IsIncomingRequest.Value) - { - Multiplayer.Session.Network.SendPacket(new UpgradeEntityRequest(__instance.planetId, objId, replace_item_proto.ID, Multiplayer.Session.Factories.PacketAuthor == -1 ? Multiplayer.Session.LocalPlayer.Id : Multiplayer.Session.Factories.PacketAuthor)); - } + return Multiplayer.Session.LocalPlayer.IsHost || Multiplayer.Session.Factories.IsIncomingRequest.Value; + } - return Multiplayer.Session.LocalPlayer.IsHost || Multiplayer.Session.Factories.IsIncomingRequest.Value; + [HarmonyPrefix] + [HarmonyPatch(nameof(PlanetFactory.GameTick))] + public static bool InternalUpdate_Prefix() + { + if (Multiplayer.IsActive) + { + Multiplayer.Session.Storage.IsHumanInput = false; } + return true; + } - [HarmonyPrefix] - [HarmonyPatch(nameof(PlanetFactory.GameTick))] - public static bool InternalUpdate_Prefix() + [HarmonyPostfix] + [HarmonyPatch(nameof(PlanetFactory.GameTick))] + public static void InternalUpdate_Postfix() + { + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) - { - Multiplayer.Session.Storage.IsHumanInput = false; - } - return true; + Multiplayer.Session.Storage.IsHumanInput = true; } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(PlanetFactory.GameTick))] - public static void InternalUpdate_Postfix() + [HarmonyPrefix] + [HarmonyPatch(nameof(PlanetFactory.PasteBuildingSetting))] + public static void PasteBuildingSetting_Prefix(PlanetFactory __instance, int objectId) + { + if (Multiplayer.IsActive && !Multiplayer.Session.Factories.IsIncomingRequest.Value) { - if (Multiplayer.IsActive) - { - Multiplayer.Session.Storage.IsHumanInput = true; - } + Multiplayer.Session.Network.SendPacketToLocalStar(new PasteBuildingSettingUpdate(objectId, + BuildingParameters.clipboard, GameMain.localPlanet?.id ?? -1)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(PlanetFactory.PasteBuildingSetting))] - public static void PasteBuildingSetting_Prefix(PlanetFactory __instance, int objectId) + [HarmonyPrefix] + [HarmonyPatch(nameof(PlanetFactory.FlattenTerrainReform))] + public static void FlattenTerrainReform_Prefix(PlanetFactory __instance, Vector3 center, float radius, int reformSize, + bool veinBuried, float fade0) + { + if (Multiplayer.IsActive && !Multiplayer.Session.Factories.IsIncomingRequest.Value) { - if (Multiplayer.IsActive && !Multiplayer.Session.Factories.IsIncomingRequest.Value) - { - Multiplayer.Session.Network.SendPacketToLocalStar(new PasteBuildingSettingUpdate(objectId, BuildingParameters.clipboard, GameMain.localPlanet?.id ?? -1)); - } + Multiplayer.Session.Network.SendPacketToLocalStar( + new FoundationBuildUpdatePacket(radius, reformSize, veinBuried, fade0)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(PlanetFactory.FlattenTerrainReform))] - public static void FlattenTerrainReform_Prefix(PlanetFactory __instance, Vector3 center, float radius, int reformSize, bool veinBuried, float fade0) + [HarmonyPrefix] + [HarmonyPatch(nameof(PlanetFactory.PlanetReformAll))] + public static void PlanetReformAll_Prefix(PlanetFactory __instance, int type, int color, bool bury) + { + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive && !Multiplayer.Session.Factories.IsIncomingRequest.Value) + if (!Multiplayer.Session.Planets.IsIncomingRequest) { - Multiplayer.Session.Network.SendPacketToLocalStar(new FoundationBuildUpdatePacket(radius, reformSize, veinBuried, fade0)); + Multiplayer.Session.Network.SendPacketToLocalStar(new PlanetReformPacket(__instance.planetId, true, type, color, + bury)); } + // Stop VegeMinedPacket from sending + Multiplayer.Session.Planets.EnableVeinPacket = false; } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(PlanetFactory.PlanetReformAll))] - public static void PlanetReformAll_Prefix(PlanetFactory __instance, int type, int color, bool bury) + [HarmonyPostfix] + [HarmonyPatch(nameof(PlanetFactory.PlanetReformAll))] + public static void PlanetReformAll_Postfix() + { + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) - { - if (!Multiplayer.Session.Planets.IsIncomingRequest) - { - Multiplayer.Session.Network.SendPacketToLocalStar(new PlanetReformPacket(__instance.planetId, true, type, color, bury)); - } - // Stop VegeMinedPacket from sending - Multiplayer.Session.Planets.EnableVeinPacket = false; - } + Multiplayer.Session.Planets.EnableVeinPacket = true; } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(PlanetFactory.PlanetReformAll))] - public static void PlanetReformAll_Postfix() + [HarmonyPrefix] + [HarmonyPatch(nameof(PlanetFactory.PlanetReformRevert))] + public static void PlanetReformRevert_Prefix(PlanetFactory __instance) + { + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) + if (!Multiplayer.Session.Planets.IsIncomingRequest) { - Multiplayer.Session.Planets.EnableVeinPacket = true; + Multiplayer.Session.Network.SendPacketToLocalStar(new PlanetReformPacket(__instance.planetId, false)); } + // Stop VegeMinedPacket from sending + Multiplayer.Session.Planets.EnableVeinPacket = false; } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(PlanetFactory.PlanetReformRevert))] - public static void PlanetReformRevert_Prefix(PlanetFactory __instance) + [HarmonyPostfix] + [HarmonyPatch(nameof(PlanetFactory.PlanetReformRevert))] + public static void PlanetReformRevert_Postfix() + { + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) - { - if (!Multiplayer.Session.Planets.IsIncomingRequest) - { - Multiplayer.Session.Network.SendPacketToLocalStar(new PlanetReformPacket(__instance.planetId, false)); - } - // Stop VegeMinedPacket from sending - Multiplayer.Session.Planets.EnableVeinPacket = false; - } + Multiplayer.Session.Planets.EnableVeinPacket = true; } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(PlanetFactory.PlanetReformRevert))] - public static void PlanetReformRevert_Postfix() + [HarmonyPostfix] + [HarmonyPatch(nameof(PlanetFactory.AddVegeData))] + public static void AddVegeData_Postfix(PlanetFactory __instance, VegeData vege) + { + if (Multiplayer.IsActive && !Multiplayer.Session.Planets.IsIncomingRequest) { - if (Multiplayer.IsActive) + using (BinaryUtils.Writer writer = new()) { - Multiplayer.Session.Planets.EnableVeinPacket = true; + vege.Export(writer.BinaryWriter); + Multiplayer.Session.Network.SendPacketToLocalStar(new VegeAddPacket(__instance.planetId, false, + writer.CloseAndGetBytes())); } } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(PlanetFactory.AddVegeData))] - public static void AddVegeData_Postfix(PlanetFactory __instance, VegeData vege) + [HarmonyPostfix] + [HarmonyPatch(nameof(PlanetFactory.AddVeinData))] + public static void AddVeinData_Postfix(PlanetFactory __instance, VeinData vein) + { + if (Multiplayer.IsActive && !Multiplayer.Session.Planets.IsIncomingRequest) { - if (Multiplayer.IsActive && !Multiplayer.Session.Planets.IsIncomingRequest) + using (BinaryUtils.Writer writer = new()) { - using (BinaryUtils.Writer writer = new()) - { - vege.Export(writer.BinaryWriter); - Multiplayer.Session.Network.SendPacketToLocalStar(new VegeAddPacket(__instance.planetId, false, writer.CloseAndGetBytes())); - } + vein.Export(writer.BinaryWriter); + Multiplayer.Session.Network.SendPacketToLocalStar(new VegeAddPacket(__instance.planetId, true, + writer.CloseAndGetBytes())); } } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(PlanetFactory.AddVeinData))] - public static void AddVeinData_Postfix(PlanetFactory __instance, VeinData vein) + [HarmonyPostfix] + [HarmonyPatch(nameof(PlanetFactory.RemoveVegeWithComponents))] + public static void RemoveVegeWithComponents_Postfix(PlanetFactory __instance, int id) + { + if (Multiplayer.IsActive && !Multiplayer.Session.Planets.IsIncomingRequest && + Multiplayer.Session.Planets.EnableVeinPacket) { - if (Multiplayer.IsActive && !Multiplayer.Session.Planets.IsIncomingRequest) - { - using (BinaryUtils.Writer writer = new()) - { - vein.Export(writer.BinaryWriter); - Multiplayer.Session.Network.SendPacketToLocalStar(new VegeAddPacket(__instance.planetId, true, writer.CloseAndGetBytes())); - } - } + Multiplayer.Session.Network.SendPacketToLocalStar(new VegeMinedPacket(__instance.planetId, id, 0, false)); } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(PlanetFactory.RemoveVegeWithComponents))] - public static void RemoveVegeWithComponents_Postfix(PlanetFactory __instance, int id) + [HarmonyPostfix] + [HarmonyPatch(nameof(PlanetFactory.RemoveVeinWithComponents))] + public static void RemoveVeinWithComponents_Postfix(PlanetFactory __instance, int id) + { + if (Multiplayer.IsActive && !Multiplayer.Session.Planets.IsIncomingRequest && + Multiplayer.Session.Planets.EnableVeinPacket) { - if (Multiplayer.IsActive && !Multiplayer.Session.Planets.IsIncomingRequest && Multiplayer.Session.Planets.EnableVeinPacket) + if (Multiplayer.Session.LocalPlayer.IsHost) { - Multiplayer.Session.Network.SendPacketToLocalStar(new VegeMinedPacket(__instance.planetId, id, 0, false)); + Multiplayer.Session.Network.SendPacketToStar(new VegeMinedPacket(__instance.planetId, id, 0, true), + __instance.planet.star.id); } - } - - [HarmonyPostfix] - [HarmonyPatch(nameof(PlanetFactory.RemoveVeinWithComponents))] - public static void RemoveVeinWithComponents_Postfix(PlanetFactory __instance, int id) - { - if (Multiplayer.IsActive && !Multiplayer.Session.Planets.IsIncomingRequest && Multiplayer.Session.Planets.EnableVeinPacket) + else { - if (Multiplayer.Session.LocalPlayer.IsHost) - { - Multiplayer.Session.Network.SendPacketToStar(new VegeMinedPacket(__instance.planetId, id, 0, true), __instance.planet.star.id); - } - else - { - Multiplayer.Session.Network.SendPacketToLocalStar(new VegeMinedPacket(__instance.planetId, id, 0, true)); - } + Multiplayer.Session.Network.SendPacketToLocalStar(new VegeMinedPacket(__instance.planetId, id, 0, true)); } } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(PlanetFactory.EnableEntityWarning))] - public static void EnableEntityWarning_Postfix(PlanetFactory __instance, int entityId) + [HarmonyPostfix] + [HarmonyPatch(nameof(PlanetFactory.EnableEntityWarning))] + public static void EnableEntityWarning_Postfix(PlanetFactory __instance, int entityId) + { + if (Multiplayer.IsActive && entityId > 0 && __instance.entityPool[entityId].id == entityId) { - if (Multiplayer.IsActive && entityId > 0 && __instance.entityPool[entityId].id == entityId) + if (Multiplayer.Session.LocalPlayer.IsClient) { - if (Multiplayer.Session.LocalPlayer.IsClient) - { - //Becasue WarningSystem.NewWarningData is blocked on client, we give it a dummy warningId - __instance.entityPool[entityId].warningId = 1; - } - Multiplayer.Session.Network.SendPacketToLocalStar(new EntityWarningSwitchPacket(__instance.planetId, entityId, true)); + //Becasue WarningSystem.NewWarningData is blocked on client, we give it a dummy warningId + __instance.entityPool[entityId].warningId = 1; } + Multiplayer.Session.Network.SendPacketToLocalStar( + new EntityWarningSwitchPacket(__instance.planetId, entityId, true)); } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(PlanetFactory.DisableEntityWarning))] - public static void DisableEntityWarning_Postfix(PlanetFactory __instance, int entityId) + [HarmonyPostfix] + [HarmonyPatch(nameof(PlanetFactory.DisableEntityWarning))] + public static void DisableEntityWarning_Postfix(PlanetFactory __instance, int entityId) + { + if (Multiplayer.IsActive && entityId > 0 && __instance.entityPool[entityId].id == entityId) { - if (Multiplayer.IsActive && entityId > 0 && __instance.entityPool[entityId].id == entityId) - { - Multiplayer.Session.Network.SendPacketToLocalStar(new EntityWarningSwitchPacket(__instance.planetId, entityId, false)); - } + Multiplayer.Session.Network.SendPacketToLocalStar(new EntityWarningSwitchPacket(__instance.planetId, entityId, + false)); } + } + + [HarmonyPostfix] + [HarmonyPatch(nameof(PlanetFactory.EntityFastTakeOut))] + public static void EntityFastTakeOut_Postfix(PlanetFactory __instance, int entityId) + { + // belt, splitter, monitor, piler: handle by BeltFastTakeOut + // storage: sync in StorageComponent.TakeItemFromGrid + // powerNode, powerCon, powerAcc: no fill in interaction - [HarmonyPostfix] - [HarmonyPatch(nameof(PlanetFactory.EntityFastTakeOut))] - public static void EntityFastTakeOut_Postfix(PlanetFactory __instance, int entityId) + if (Multiplayer.IsActive && entityId > 0 && __instance.entityPool[entityId].id == entityId) { - // belt, splitter, monitor, piler: handle by BeltFastTakeOut - // storage: sync in StorageComponent.TakeItemFromGrid - // powerNode, powerCon, powerAcc: no fill in interaction + var entityData = __instance.entityPool[entityId]; - if (Multiplayer.IsActive && entityId > 0 && __instance.entityPool[entityId].id == entityId) + if (entityData.assemblerId > 0) { - EntityData entityData = __instance.entityPool[entityId]; - - if (entityData.assemblerId > 0) - { - int assemblerId = entityData.assemblerId; - AssemblerComponent[] assemblerPool = __instance.factorySystem.assemblerPool; - if (assemblerPool[assemblerId].recipeId > 0) - { - int[] produced = assemblerPool[assemblerId].produced; - for (int j = 0; j < produced.Length; j++) - { - Multiplayer.Session.Network.SendPacketToLocalStar(new AssemblerUpdateProducesPacket(j, produced[j], __instance.planetId, assemblerId)); - } - } - } - if (entityData.dispenserId > 0) - { - int dispenserId = entityData.dispenserId; - DispenserComponent[] dispenserPool = __instance.transport.dispenserPool; - Multiplayer.Session.Network.SendPacketToLocalStar(new DispenserStorePacket(__instance.planetId, in dispenserPool[dispenserId])); - } - if (entityData.ejectorId > 0) - { - int ejectorId = entityData.ejectorId; - EjectorComponent[] ejectorPool = __instance.factorySystem.ejectorPool; - Multiplayer.Session.Network.SendPacketToLocalStar(new EjectorStorageUpdatePacket(ejectorId, ejectorPool[ejectorId].bulletCount, ejectorPool[ejectorId].bulletInc, __instance.planetId)); - } - if (entityData.inserterId > 0) - { - int inserterId = entityData.inserterId; - InserterComponent[] inserterPool = __instance.factorySystem.inserterPool; - Multiplayer.Session.Network.SendPacketToLocalStar(new InserterItemUpdatePacket(in inserterPool[inserterId], __instance.planetId)); - } - if (entityData.fractionatorId > 0) - { - int fractionatorId = entityData.fractionatorId; - FractionatorComponent[] fractionatorPool = __instance.factorySystem.fractionatorPool; - Multiplayer.Session.Network.SendPacketToLocalStar(new FractionatorStorageUpdatePacket(in fractionatorPool[fractionatorId], __instance.planetId)); - } - if (entityData.labId > 0) + var assemblerId = entityData.assemblerId; + var assemblerPool = __instance.factorySystem.assemblerPool; + if (assemblerPool[assemblerId].recipeId > 0) { - int labId = entityData.labId; - LabComponent[] labPool = __instance.factorySystem.labPool; - if (labPool[labId].matrixMode) + var produced = assemblerPool[assemblerId].produced; + for (var j = 0; j < produced.Length; j++) { - Multiplayer.Session.Network.SendPacketToLocalStar(new LaboratoryUpdateEventPacket(-3, labId, __instance.planetId)); + Multiplayer.Session.Network.SendPacketToLocalStar( + new AssemblerUpdateProducesPacket(j, produced[j], __instance.planetId, assemblerId)); } } - if (entityData.minerId > 0) + } + if (entityData.dispenserId > 0) + { + var dispenserId = entityData.dispenserId; + var dispenserPool = __instance.transport.dispenserPool; + Multiplayer.Session.Network.SendPacketToLocalStar(new DispenserStorePacket(__instance.planetId, + in dispenserPool[dispenserId])); + } + if (entityData.ejectorId > 0) + { + var ejectorId = entityData.ejectorId; + var ejectorPool = __instance.factorySystem.ejectorPool; + Multiplayer.Session.Network.SendPacketToLocalStar(new EjectorStorageUpdatePacket(ejectorId, + ejectorPool[ejectorId].bulletCount, ejectorPool[ejectorId].bulletInc, __instance.planetId)); + } + if (entityData.inserterId > 0) + { + var inserterId = entityData.inserterId; + var inserterPool = __instance.factorySystem.inserterPool; + Multiplayer.Session.Network.SendPacketToLocalStar(new InserterItemUpdatePacket(in inserterPool[inserterId], + __instance.planetId)); + } + if (entityData.fractionatorId > 0) + { + var fractionatorId = entityData.fractionatorId; + var fractionatorPool = __instance.factorySystem.fractionatorPool; + Multiplayer.Session.Network.SendPacketToLocalStar( + new FractionatorStorageUpdatePacket(in fractionatorPool[fractionatorId], __instance.planetId)); + } + if (entityData.labId > 0) + { + var labId = entityData.labId; + var labPool = __instance.factorySystem.labPool; + if (labPool[labId].matrixMode) { - int minerId = entityData.minerId; - MinerComponent[] minerPool = __instance.factorySystem.minerPool; - Multiplayer.Session.Network.SendPacketToLocalStar(new MinerStoragePickupPacket(minerId, __instance.planetId)); + Multiplayer.Session.Network.SendPacketToLocalStar( + new LaboratoryUpdateEventPacket(-3, labId, __instance.planetId)); } - if (entityData.powerExcId > 0) + } + if (entityData.minerId > 0) + { + var minerId = entityData.minerId; + var minerPool = __instance.factorySystem.minerPool; + Multiplayer.Session.Network.SendPacketToLocalStar(new MinerStoragePickupPacket(minerId, __instance.planetId)); + } + if (entityData.powerExcId > 0) + { + var powerExcId = entityData.powerExcId; + var excPool = __instance.powerSystem.excPool; + Multiplayer.Session.Network.SendPacketToLocalStar(new PowerExchangerStorageUpdatePacket(powerExcId, + excPool[powerExcId].emptyCount, excPool[powerExcId].fullCount, __instance.planetId)); + } + if (entityData.powerGenId > 0) + { + var powerGenId = entityData.powerGenId; + var genPool = __instance.powerSystem.genPool; + Multiplayer.Session.Network.SendPacketToLocalStar(new PowerGeneratorFuelUpdatePacket(powerGenId, + genPool[powerGenId].fuelId, genPool[powerGenId].fuelCount, genPool[powerGenId].fuelInc, + __instance.planetId)); + if (genPool[powerGenId].productId > 0) { - int powerExcId = entityData.powerExcId; - PowerExchangerComponent[] excPool = __instance.powerSystem.excPool; - Multiplayer.Session.Network.SendPacketToLocalStar(new PowerExchangerStorageUpdatePacket(powerExcId, excPool[powerExcId].emptyCount, excPool[powerExcId].fullCount, __instance.planetId)); + Multiplayer.Session.Network.SendPacketToLocalStar( + new PowerGeneratorProductUpdatePacket(in genPool[powerGenId], __instance.planetId)); } - if (entityData.powerGenId > 0) + } + if (entityData.stationId > 0) + { + var stationId = entityData.stationId; + var stationComponent = __instance.transport.stationPool[stationId]; + for (var i = 0; i < stationComponent.storage.Length; i++) { - int powerGenId = entityData.powerGenId; - PowerGeneratorComponent[] genPool = __instance.powerSystem.genPool; - Multiplayer.Session.Network.SendPacketToLocalStar(new PowerGeneratorFuelUpdatePacket(powerGenId, genPool[powerGenId].fuelId, genPool[powerGenId].fuelCount, genPool[powerGenId].fuelInc, __instance.planetId)); - if (genPool[powerGenId].productId > 0) + if (stationComponent.storage[i].itemId > 0) { - Multiplayer.Session.Network.SendPacketToLocalStar(new PowerGeneratorProductUpdatePacket(in genPool[powerGenId], __instance.planetId)); + var packet = new StorageUI(__instance.planetId, stationComponent.id, stationComponent.gid, i, + stationComponent.storage[i].count, stationComponent.storage[i].inc); + Multiplayer.Session.Network.SendPacket(packet); } } - if (entityData.stationId > 0) + if (!stationComponent.isCollector && !stationComponent.isVeinCollector) { - int stationId = entityData.stationId; - StationComponent stationComponent = __instance.transport.stationPool[stationId]; - for (int i = 0; i < stationComponent.storage.Length; i++) - { - if (stationComponent.storage[i].itemId > 0) - { - StorageUI packet = new StorageUI(__instance.planetId, stationComponent.id, stationComponent.gid, i, stationComponent.storage[i].count, stationComponent.storage[i].inc); - Multiplayer.Session.Network.SendPacket(packet); - } - } - if (!stationComponent.isCollector && !stationComponent.isVeinCollector) - { - StationUI packet = new StationUI(__instance.planetId, stationComponent.id, stationComponent.gid, StationUI.EUISettings.SetDroneCount, stationComponent.idleDroneCount + stationComponent.workDroneCount); - Multiplayer.Session.Network.SendPacket(packet); - } - if (stationComponent.isStellar && !stationComponent.isCollector && !stationComponent.isVeinCollector) - { - StationUI packet = new StationUI(__instance.planetId, stationComponent.id, stationComponent.gid, StationUI.EUISettings.SetShipCount, stationComponent.idleShipCount + stationComponent.workShipCount); - Multiplayer.Session.Network.SendPacket(packet); - } - if (stationComponent.isStellar && !stationComponent.isCollector && !stationComponent.isVeinCollector && __instance.gameData.history.logisticShipWarpDrive) - { - StationUI packet = new StationUI(__instance.planetId, stationComponent.id, stationComponent.gid, StationUI.EUISettings.SetWarperCount, stationComponent.warperCount); - Multiplayer.Session.Network.SendPacket(packet); - } + var packet = new StationUI(__instance.planetId, stationComponent.id, stationComponent.gid, + StationUI.EUISettings.SetDroneCount, stationComponent.idleDroneCount + stationComponent.workDroneCount); + Multiplayer.Session.Network.SendPacket(packet); } - if (entityData.siloId > 0) + if (stationComponent.isStellar && !stationComponent.isCollector && !stationComponent.isVeinCollector) { - int siloId = entityData.siloId; - SiloComponent[] siloPool = __instance.factorySystem.siloPool; - Multiplayer.Session.Network.SendPacketToLocalStar(new SiloStorageUpdatePacket(siloId, siloPool[siloId].bulletCount, siloPool[siloId].bulletInc, __instance.planetId)); + var packet = new StationUI(__instance.planetId, stationComponent.id, stationComponent.gid, + StationUI.EUISettings.SetShipCount, stationComponent.idleShipCount + stationComponent.workShipCount); + Multiplayer.Session.Network.SendPacket(packet); } - if (entityData.tankId > 0) + if (stationComponent.isStellar && !stationComponent.isCollector && !stationComponent.isVeinCollector && + __instance.gameData.history.logisticShipWarpDrive) { - int tankId = entityData.tankId; - TankComponent[] tankPool = __instance.factoryStorage.tankPool; - Multiplayer.Session.Network.SendPacketToLocalStar(new TankStorageUpdatePacket(in tankPool[tankId], __instance.planetId)); + var packet = new StationUI(__instance.planetId, stationComponent.id, stationComponent.gid, + StationUI.EUISettings.SetWarperCount, stationComponent.warperCount); + Multiplayer.Session.Network.SendPacket(packet); } } + if (entityData.siloId > 0) + { + var siloId = entityData.siloId; + var siloPool = __instance.factorySystem.siloPool; + Multiplayer.Session.Network.SendPacketToLocalStar(new SiloStorageUpdatePacket(siloId, + siloPool[siloId].bulletCount, siloPool[siloId].bulletInc, __instance.planetId)); + } + if (entityData.tankId > 0) + { + var tankId = entityData.tankId; + var tankPool = __instance.factoryStorage.tankPool; + Multiplayer.Session.Network.SendPacketToLocalStar(new TankStorageUpdatePacket(in tankPool[tankId], + __instance.planetId)); + } } + } + + [HarmonyPostfix] + [HarmonyPatch(nameof(PlanetFactory.EntityFastFillIn))] + public static void EntityFastFillIn_Postfix(PlanetFactory __instance, int entityId) + { + // belt, splitter, monitor, miner, fractionator, piler: handle by BeltFastFillIn + // storage: sync in StorageComponent.AddItemStacked + // inserter, powerNode, powerCon, powerAcc: no fill in interaction - [HarmonyPostfix] - [HarmonyPatch(nameof(PlanetFactory.EntityFastFillIn))] - public static void EntityFastFillIn_Postfix(PlanetFactory __instance, int entityId) + if (Multiplayer.IsActive && entityId > 0 && __instance.entityPool[entityId].id == entityId) { - // belt, splitter, monitor, miner, fractionator, piler: handle by BeltFastFillIn - // storage: sync in StorageComponent.AddItemStacked - // inserter, powerNode, powerCon, powerAcc: no fill in interaction + var entityData = __instance.entityPool[entityId]; - if (Multiplayer.IsActive && entityId > 0 && __instance.entityPool[entityId].id == entityId) + if (entityData.tankId > 0) { - EntityData entityData = __instance.entityPool[entityId]; - - if (entityData.tankId > 0) + var tankId = entityData.tankId; + var tankPool = __instance.factoryStorage.tankPool; + Multiplayer.Session.Network.SendPacketToLocalStar(new TankStorageUpdatePacket(in tankPool[tankId], + __instance.planetId)); + } + if (entityData.assemblerId > 0) + { + var assemblerId = entityData.assemblerId; + var assemblerPool = __instance.factorySystem.assemblerPool; + if (assemblerPool[assemblerId].recipeId > 0) { - int tankId = entityData.tankId; - TankComponent[] tankPool = __instance.factoryStorage.tankPool; - Multiplayer.Session.Network.SendPacketToLocalStar(new TankStorageUpdatePacket(in tankPool[tankId], __instance.planetId)); + Multiplayer.Session.Network.SendPacketToLocalStar(new AssemblerUpdateStoragePacket(__instance.planetId, + assemblerId, assemblerPool[assemblerId].served, assemblerPool[assemblerId].incServed)); } - if (entityData.assemblerId > 0) + } + if (entityData.dispenserId > 0) + { + var dispenserId = entityData.dispenserId; + var dispenserPool = __instance.transport.dispenserPool; + var courierCount = dispenserPool[dispenserId].workCourierCount + dispenserPool[dispenserId].idleCourierCount; + Multiplayer.Session.Network.SendPacketToLocalStar(new DispenserSettingPacket(__instance.planetId, dispenserId, + EDispenserSettingEvent.SetCourierCount, courierCount)); + } + if (entityData.ejectorId > 0) + { + var ejectorId = entityData.ejectorId; + var ejectorPool = __instance.factorySystem.ejectorPool; + Multiplayer.Session.Network.SendPacketToLocalStar(new EjectorStorageUpdatePacket(ejectorId, + ejectorPool[ejectorId].bulletCount, ejectorPool[ejectorId].bulletInc, __instance.planetId)); + } + if (entityData.siloId > 0) + { + var siloId = entityData.siloId; + var siloPool = __instance.factorySystem.siloPool; + Multiplayer.Session.Network.SendPacketToLocalStar(new SiloStorageUpdatePacket(siloId, + siloPool[siloId].bulletCount, siloPool[siloId].bulletInc, __instance.planetId)); + } + if (entityData.labId > 0) + { + var labId = entityData.labId; + var labPool = __instance.factorySystem.labPool; + + if (labPool[labId].researchMode) { - int assemblerId = entityData.assemblerId; - AssemblerComponent[] assemblerPool = __instance.factorySystem.assemblerPool; - if (assemblerPool[assemblerId].recipeId > 0) + for (var matrixId = 0; matrixId < LabComponent.matrixIds.Length; matrixId++) { - Multiplayer.Session.Network.SendPacketToLocalStar(new AssemblerUpdateStoragePacket(__instance.planetId, assemblerId, assemblerPool[assemblerId].served, assemblerPool[assemblerId].incServed)); + Multiplayer.Session.Network.SendPacketToLocalStar(new LaboratoryUpdateCubesPacket( + labPool[labId].matrixServed[matrixId], labPool[labId].matrixIncServed[matrixId], matrixId, labId, + __instance.planetId)); } } - if (entityData.dispenserId > 0) + else if (labPool[labId].matrixMode) { - int dispenserId = entityData.dispenserId; - DispenserComponent[] dispenserPool = __instance.transport.dispenserPool; - int courierCount = dispenserPool[dispenserId].workCourierCount + dispenserPool[dispenserId].idleCourierCount; - Multiplayer.Session.Network.SendPacketToLocalStar(new DispenserSettingPacket(__instance.planetId, dispenserId, EDispenserSettingEvent.SetCourierCount, courierCount)); - } - if (entityData.ejectorId > 0) - { - int ejectorId = entityData.ejectorId; - EjectorComponent[] ejectorPool = __instance.factorySystem.ejectorPool; - Multiplayer.Session.Network.SendPacketToLocalStar(new EjectorStorageUpdatePacket(ejectorId, ejectorPool[ejectorId].bulletCount, ejectorPool[ejectorId].bulletInc, __instance.planetId)); - } - if (entityData.siloId > 0) - { - int siloId = entityData.siloId; - SiloComponent[] siloPool = __instance.factorySystem.siloPool; - Multiplayer.Session.Network.SendPacketToLocalStar(new SiloStorageUpdatePacket(siloId, siloPool[siloId].bulletCount, siloPool[siloId].bulletInc, __instance.planetId)); - } - if (entityData.labId > 0) - { - int labId = entityData.labId; - LabComponent[] labPool = __instance.factorySystem.labPool; - - if (labPool[labId].researchMode) + for (var m = 0; m < labPool[labId].served.Length; m++) { - for (int matrixId = 0; matrixId < LabComponent.matrixIds.Length; matrixId++) - { - Multiplayer.Session.Network.SendPacketToLocalStar(new LaboratoryUpdateCubesPacket(labPool[labId].matrixServed[matrixId], labPool[labId].matrixIncServed[matrixId], matrixId, labId, __instance.planetId)); - } - } - else if (labPool[labId].matrixMode) - { - for (int m = 0; m < labPool[labId].served.Length; m++) - { - Multiplayer.Session.Network.SendPacketToLocalStar(new LaboratoryUpdateStoragePacket(labPool[labId].served[m], labPool[labId].incServed[m], m, labId, __instance.planetId)); - } + Multiplayer.Session.Network.SendPacketToLocalStar( + new LaboratoryUpdateStoragePacket(labPool[labId].served[m], labPool[labId].incServed[m], m, labId, + __instance.planetId)); } } - if (entityData.stationId > 0) + } + if (entityData.stationId > 0) + { + var stationId = entityData.stationId; + var stationComponent = __instance.transport.stationPool[stationId]; + for (var i = 0; i < stationComponent.storage.Length; i++) { - int stationId = entityData.stationId; - StationComponent stationComponent = __instance.transport.stationPool[stationId]; - for (int i = 0; i < stationComponent.storage.Length; i++) + if (stationComponent.storage[i].itemId > 0) { - if (stationComponent.storage[i].itemId > 0) - { - StorageUI packet = new StorageUI(__instance.planetId, stationComponent.id, stationComponent.gid, i, stationComponent.storage[i].count, stationComponent.storage[i].inc); - Multiplayer.Session.Network.SendPacket(packet); - } - } - if (!stationComponent.isCollector && !stationComponent.isVeinCollector) - { - StationUI packet = new StationUI(__instance.planetId, stationComponent.id, stationComponent.gid, StationUI.EUISettings.SetDroneCount, stationComponent.idleDroneCount + stationComponent.workDroneCount); - Multiplayer.Session.Network.SendPacket(packet); - } - if (stationComponent.isStellar && !stationComponent.isCollector && !stationComponent.isVeinCollector) - { - StationUI packet = new StationUI(__instance.planetId, stationComponent.id, stationComponent.gid, StationUI.EUISettings.SetShipCount, stationComponent.idleShipCount + stationComponent.workShipCount); - Multiplayer.Session.Network.SendPacket(packet); - } - if (stationComponent.isStellar && !stationComponent.isCollector && !stationComponent.isVeinCollector && __instance.gameData.history.logisticShipWarpDrive) - { - StationUI packet = new StationUI(__instance.planetId, stationComponent.id, stationComponent.gid, StationUI.EUISettings.SetWarperCount, stationComponent.warperCount); + var packet = new StorageUI(__instance.planetId, stationComponent.id, stationComponent.gid, i, + stationComponent.storage[i].count, stationComponent.storage[i].inc); Multiplayer.Session.Network.SendPacket(packet); } } - if (entityData.powerGenId > 0) + if (!stationComponent.isCollector && !stationComponent.isVeinCollector) { - int powerGenId = entityData.powerGenId; - PowerGeneratorComponent[] genPool = __instance.powerSystem.genPool; - Multiplayer.Session.Network.SendPacketToLocalStar(new PowerGeneratorFuelUpdatePacket(powerGenId, genPool[powerGenId].fuelId, genPool[powerGenId].fuelCount, genPool[powerGenId].fuelInc, __instance.planetId)); - if (genPool[powerGenId].gamma) - { - Multiplayer.Session.Network.SendPacketToLocalStar(new RayReceiverChangeLensPacket(powerGenId, genPool[powerGenId].catalystPoint, genPool[powerGenId].catalystIncPoint, __instance.planetId)); - } + var packet = new StationUI(__instance.planetId, stationComponent.id, stationComponent.gid, + StationUI.EUISettings.SetDroneCount, stationComponent.idleDroneCount + stationComponent.workDroneCount); + Multiplayer.Session.Network.SendPacket(packet); } - if (entityData.powerExcId > 0) + if (stationComponent.isStellar && !stationComponent.isCollector && !stationComponent.isVeinCollector) { - int powerExcId = entityData.powerExcId; - PowerExchangerComponent[] excPool = __instance.powerSystem.excPool; - Multiplayer.Session.Network.SendPacketToLocalStar(new PowerExchangerStorageUpdatePacket(powerExcId, excPool[powerExcId].emptyCount, excPool[powerExcId].fullCount, __instance.planetId)); + var packet = new StationUI(__instance.planetId, stationComponent.id, stationComponent.gid, + StationUI.EUISettings.SetShipCount, stationComponent.idleShipCount + stationComponent.workShipCount); + Multiplayer.Session.Network.SendPacket(packet); } - if (entityData.spraycoaterId > 0) + if (stationComponent.isStellar && !stationComponent.isCollector && !stationComponent.isVeinCollector && + __instance.gameData.history.logisticShipWarpDrive) { - int spraycoaterId = entityData.spraycoaterId; - SpraycoaterComponent[] spraycoaterPool = __instance.cargoTraffic.spraycoaterPool; - Multiplayer.Session.Network.SendPacketToLocalStar(new SprayerStorageUpdatePacket(spraycoaterPool[spraycoaterId], __instance.planetId)); + var packet = new StationUI(__instance.planetId, stationComponent.id, stationComponent.gid, + StationUI.EUISettings.SetWarperCount, stationComponent.warperCount); + Multiplayer.Session.Network.SendPacket(packet); } } - } - - [HarmonyPrefix] - [HarmonyPatch(nameof(PlanetFactory.EntityAutoReplenishIfNeeded))] - [HarmonyPatch(nameof(PlanetFactory.StationAutoReplenishIfNeeded))] - public static bool EntityAutoReplenishIfNeeded_Prefix(PlanetFactory __instance, int entityId, ref (int, int, int, int) __state) - { - if (!Multiplayer.IsActive) + if (entityData.powerGenId > 0) { - return true; + var powerGenId = entityData.powerGenId; + var genPool = __instance.powerSystem.genPool; + Multiplayer.Session.Network.SendPacketToLocalStar(new PowerGeneratorFuelUpdatePacket(powerGenId, + genPool[powerGenId].fuelId, genPool[powerGenId].fuelCount, genPool[powerGenId].fuelInc, + __instance.planetId)); + if (genPool[powerGenId].gamma) + { + Multiplayer.Session.Network.SendPacketToLocalStar(new RayReceiverChangeLensPacket(powerGenId, + genPool[powerGenId].catalystPoint, genPool[powerGenId].catalystIncPoint, __instance.planetId)); + } } - - // Don't auto replenish if it is from other player's packet - if (Multiplayer.Session.Factories.IsIncomingRequest.Value && Multiplayer.Session.Factories.PacketAuthor != Multiplayer.Session.LocalPlayer.Id) + if (entityData.powerExcId > 0) { - return false; + var powerExcId = entityData.powerExcId; + var excPool = __instance.powerSystem.excPool; + Multiplayer.Session.Network.SendPacketToLocalStar(new PowerExchangerStorageUpdatePacket(powerExcId, + excPool[powerExcId].emptyCount, excPool[powerExcId].fullCount, __instance.planetId)); } - if (Multiplayer.Session.StationsUI.IsIncomingRequest.Value) + if (entityData.spraycoaterId > 0) { - return false; + var spraycoaterId = entityData.spraycoaterId; + var spraycoaterPool = __instance.cargoTraffic.spraycoaterPool; + Multiplayer.Session.Network.SendPacketToLocalStar( + new SprayerStorageUpdatePacket(spraycoaterPool[spraycoaterId], __instance.planetId)); } + } + } - __state.Item1 = 1; - ref EntityData ptr = ref __instance.entityPool[entityId]; - if (ptr.dispenserId > 0) - { - DispenserComponent dispenserComponent = __instance.transport.dispenserPool[ptr.dispenserId]; - __state.Item2 = dispenserComponent.idleCourierCount; - } - if (ptr.stationId > 0) - { - StationComponent stationComponent = __instance.transport.stationPool[ptr.stationId]; - __state.Item3 = stationComponent.idleDroneCount; - __state.Item4 = stationComponent.idleShipCount; - } + [HarmonyPrefix] + [HarmonyPatch(nameof(PlanetFactory.EntityAutoReplenishIfNeeded))] + [HarmonyPatch(nameof(PlanetFactory.StationAutoReplenishIfNeeded))] + public static bool EntityAutoReplenishIfNeeded_Prefix(PlanetFactory __instance, int entityId, + ref (int, int, int, int) __state) + { + if (!Multiplayer.IsActive) + { return true; } - [HarmonyPostfix] - [HarmonyPatch(nameof(PlanetFactory.EntityAutoReplenishIfNeeded))] - [HarmonyPatch(nameof(PlanetFactory.StationAutoReplenishIfNeeded))] - public static void EntityAutoReplenishIfNeeded_Postfix(PlanetFactory __instance, int entityId, ref (int, int, int, int) __state) + // Don't auto replenish if it is from other player's packet + if (Multiplayer.Session.Factories.IsIncomingRequest.Value && + Multiplayer.Session.Factories.PacketAuthor != Multiplayer.Session.LocalPlayer.Id) { - if (__state.Item1 != 1) + return false; + } + if (Multiplayer.Session.StationsUI.IsIncomingRequest.Value) + { + return false; + } + + __state.Item1 = 1; + ref var ptr = ref __instance.entityPool[entityId]; + if (ptr.dispenserId > 0) + { + var dispenserComponent = __instance.transport.dispenserPool[ptr.dispenserId]; + __state.Item2 = dispenserComponent.idleCourierCount; + } + if (ptr.stationId > 0) + { + var stationComponent = __instance.transport.stationPool[ptr.stationId]; + __state.Item3 = stationComponent.idleDroneCount; + __state.Item4 = stationComponent.idleShipCount; + } + return true; + } + + [HarmonyPostfix] + [HarmonyPatch(nameof(PlanetFactory.EntityAutoReplenishIfNeeded))] + [HarmonyPatch(nameof(PlanetFactory.StationAutoReplenishIfNeeded))] + public static void EntityAutoReplenishIfNeeded_Postfix(PlanetFactory __instance, int entityId, + ref (int, int, int, int) __state) + { + if (__state.Item1 != 1) + { + return; + } + + ref var ptr = ref __instance.entityPool[entityId]; + if (ptr.dispenserId > 0) + { + var dispenserComponent = __instance.transport.dispenserPool[ptr.dispenserId]; + if (__state.Item2 != dispenserComponent.idleCourierCount) { - return; + Multiplayer.Session.Network.SendPacketToLocalStar( + new DispenserSettingPacket(__instance.planetId, + ptr.dispenserId, + EDispenserSettingEvent.SetCourierCount, + dispenserComponent.workCourierCount + dispenserComponent.idleCourierCount)); } - - ref EntityData ptr = ref __instance.entityPool[entityId]; - if (ptr.dispenserId > 0) + } + if (ptr.stationId > 0) + { + var stationComponent = __instance.transport.stationPool[ptr.stationId]; + if (__state.Item3 != stationComponent.idleDroneCount) { - DispenserComponent dispenserComponent = __instance.transport.dispenserPool[ptr.dispenserId]; - if (__state.Item2 != dispenserComponent.idleCourierCount) + Multiplayer.Session.Network.SendPacket( + new StationUI(__instance.planetId, + stationComponent.id, + stationComponent.gid, + StationUI.EUISettings.SetDroneCount, + stationComponent.idleDroneCount + stationComponent.workDroneCount)); + + if (Multiplayer.Session.LocalPlayer.IsClient) { - Multiplayer.Session.Network.SendPacketToLocalStar( - new DispenserSettingPacket(__instance.planetId, - ptr.dispenserId, - EDispenserSettingEvent.SetCourierCount, - dispenserComponent.workCourierCount + dispenserComponent.idleCourierCount)); + // Revert drone count until host verify + stationComponent.idleDroneCount = __state.Item3; } } - if (ptr.stationId > 0) + + if (__state.Item4 != stationComponent.idleShipCount) { - StationComponent stationComponent = __instance.transport.stationPool[ptr.stationId]; - if (__state.Item3 != stationComponent.idleDroneCount) - { - Multiplayer.Session.Network.SendPacket( - new StationUI(__instance.planetId, - stationComponent.id, - stationComponent.gid, - StationUI.EUISettings.SetDroneCount, - stationComponent.idleDroneCount + stationComponent.workDroneCount)); - - if (Multiplayer.Session.LocalPlayer.IsClient) - { - // Revert drone count until host verify - stationComponent.idleDroneCount = __state.Item3; - } - } + Multiplayer.Session.Network.SendPacket( + new StationUI(__instance.planetId, + stationComponent.id, + stationComponent.gid, + StationUI.EUISettings.SetShipCount, + stationComponent.idleShipCount + stationComponent.workShipCount)); - if (__state.Item4 != stationComponent.idleShipCount) + if (Multiplayer.Session.LocalPlayer.IsClient) { - Multiplayer.Session.Network.SendPacket( - new StationUI(__instance.planetId, - stationComponent.id, - stationComponent.gid, - StationUI.EUISettings.SetShipCount, - stationComponent.idleShipCount + stationComponent.workShipCount)); - - if (Multiplayer.Session.LocalPlayer.IsClient) - { - // Revert drone count until host verify - stationComponent.idleShipCount = __state.Item4; - } + // Revert drone count until host verify + stationComponent.idleShipCount = __state.Item4; } } - } } } diff --git a/NebulaPatcher/Patches/Dynamic/PlanetModelingManager_Patch.cs b/NebulaPatcher/Patches/Dynamic/PlanetModelingManager_Patch.cs index 00309a289..47b5e40e3 100644 --- a/NebulaPatcher/Patches/Dynamic/PlanetModelingManager_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/PlanetModelingManager_Patch.cs @@ -1,193 +1,199 @@ -using HarmonyLib; +#region + +using System; +using System.Collections.Generic; +using System.Linq; +using HarmonyLib; using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Packets.Planet; using NebulaPatcher.Patches.Transpilers; using NebulaWorld; -using System.Collections.Generic; -using System.Linq; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(PlanetModelingManager))] +public class PlanetModelingManager_Patch { - [HarmonyPatch(typeof(PlanetModelingManager))] - public class PlanetModelingManager_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(PlanetModelingManager.RequestLoadPlanetFactory))] + public static bool RequestLoadPlanetFactory_Prefix(PlanetData planet) { - [HarmonyPrefix] - [HarmonyPatch(nameof(PlanetModelingManager.RequestLoadPlanetFactory))] - public static bool RequestLoadPlanetFactory_Prefix(PlanetData planet) + // Run the original method if this is the master client or in single player games + if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) { - // Run the original method if this is the master client or in single player games - if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) - { - return true; - } - - // Check to make sure it's not already loaded - if (planet.factoryLoaded || planet.factoryLoading) - { - return false; - } - - // if client is still in lobby we dont need the factory data at all, so dont request it. - if (Multiplayer.Session.IsInLobby) - { - return false; - } + return true; + } - // They appear to have conveniently left this flag in for us, but they don't use it anywhere - planet.factoryLoading = true; + // Check to make sure it's not already loaded + if (planet.factoryLoaded || planet.factoryLoading) + { + return false; + } - // do this here to match the patch in GPUInstancingManager_Patch.cs - // as we sync entity placement in realtime when players change something - // we only need to request the full factory if we never received it before - if (planet.factory != null) - { - PlanetModelingManager.currentFactingPlanet = planet; - PlanetModelingManager.currentFactingStage = 0; - return false; - } - try - { - NebulaModAPI.OnPlanetLoadRequest?.Invoke(planet.id); - } - catch (System.Exception e) - { - Log.Error("NebulaModAPI.OnPlanetLoadRequest error:\n" + e); - } + // if client is still in lobby we dont need the factory data at all, so dont request it. + if (Multiplayer.Session.IsInLobby) + { + return false; + } - // Request factory - Log.Info($"Requested factory for planet {planet.name} (ID: {planet.id}) from host"); - Multiplayer.Session.Network.SendPacket(new FactoryLoadRequest(planet.id)); + // They appear to have conveniently left this flag in for us, but they don't use it anywhere + planet.factoryLoading = true; - // Skip running the actual method + // do this here to match the patch in GPUInstancingManager_Patch.cs + // as we sync entity placement in realtime when players change something + // we only need to request the full factory if we never received it before + if (planet.factory != null) + { + PlanetModelingManager.currentFactingPlanet = planet; + PlanetModelingManager.currentFactingStage = 0; return false; } - - [HarmonyPrefix] - [HarmonyPatch(nameof(PlanetModelingManager.RequestLoadPlanet))] - public static bool RequestLoadPlanet_Prefix(PlanetData planet) + try + { + NebulaModAPI.OnPlanetLoadRequest?.Invoke(planet.id); + } + catch (Exception e) { - // NOTE: This does not appear to ever be called in the game code, but just in case, let's override it - // RequestLoadStar takes care of these instead currently + Log.Error("NebulaModAPI.OnPlanetLoadRequest error:\n" + e); + } - // Run the original method if this is the master client or in single player games - if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) - { - return true; - } + // Request factory + Log.Info($"Requested factory for planet {planet.name} (ID: {planet.id}) from host"); + Multiplayer.Session.Network.SendPacket(new FactoryLoadRequest(planet.id)); - InternalLoadPlanetsRequestGenerator(new[] { planet }); + // Skip running the actual method + return false; + } - return false; - } + [HarmonyPrefix] + [HarmonyPatch(nameof(PlanetModelingManager.RequestLoadPlanet))] + public static bool RequestLoadPlanet_Prefix(PlanetData planet) + { + // NOTE: This does not appear to ever be called in the game code, but just in case, let's override it + // RequestLoadStar takes care of these instead currently - [HarmonyPrefix] - [HarmonyPatch(nameof(PlanetModelingManager.RequestLoadStar))] - public static bool RequestLoadStar_Prefix(StarData star) + // Run the original method if this is the master client or in single player games + if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) { - // Run the original method if this is the master client or in single player games - if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) - { - return true; - } + return true; + } - InternalLoadPlanetsRequestGenerator(star.planets); + InternalLoadPlanetsRequestGenerator(new[] { planet }); - Multiplayer.Session.DysonSpheres.UnloadRemoteDysonSpheres(); - // Request initial dysonSphere data - if (GameMain.data.dysonSpheres[star.index] == null) - { - Multiplayer.Session.DysonSpheres.RequestDysonSphere(star.index, false); - } + return false; + } - try - { - NebulaModAPI.OnStarLoadRequest?.Invoke(star.index); - } - catch (System.Exception e) - { - Log.Error("NebulaModAPI.OnStarLoadRequest error:\n" + e); - } + [HarmonyPrefix] + [HarmonyPatch(nameof(PlanetModelingManager.RequestLoadStar))] + public static bool RequestLoadStar_Prefix(StarData star) + { + // Run the original method if this is the master client or in single player games + if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) + { + return true; + } - return false; + InternalLoadPlanetsRequestGenerator(star.planets); + + Multiplayer.Session.DysonSpheres.UnloadRemoteDysonSpheres(); + // Request initial dysonSphere data + if (GameMain.data.dysonSpheres[star.index] == null) + { + Multiplayer.Session.DysonSpheres.RequestDysonSphere(star.index, false); } - private static void InternalLoadPlanetsRequestGenerator(PlanetData[] planetsToLoad) + try { - lock (PlanetModelingManager.genPlanetReqList) - { - List planetsToRequest = new List(); + NebulaModAPI.OnStarLoadRequest?.Invoke(star.index); + } + catch (Exception e) + { + Log.Error("NebulaModAPI.OnStarLoadRequest error:\n" + e); + } + + return false; + } + + private static void InternalLoadPlanetsRequestGenerator(PlanetData[] planetsToLoad) + { + lock (PlanetModelingManager.genPlanetReqList) + { + var planetsToRequest = new List(); - foreach (PlanetData planet in planetsToLoad) + foreach (var planet in planetsToLoad) + { + planet.wanted = true; + if (planet.loaded || planet.loading) { - planet.wanted = true; - if (planet.loaded || planet.loading) - { - continue; - } + continue; + } - planet.loading = true; + planet.loading = true; - Log.Info($"Requesting planet model for {planet.name} (ID: {planet.id}) from host"); - planetsToRequest.Add(planet.id); + Log.Info($"Requesting planet model for {planet.name} (ID: {planet.id}) from host"); + planetsToRequest.Add(planet.id); + } + + if (planetsToRequest.Any()) + { + // Make local planet load first + var localPlanetId = Multiplayer.Session.LocalPlayer?.Data?.LocalPlanetId ?? -1; + if (localPlanetId == -1) + { + localPlanetId = UIVirtualStarmap_Transpiler.customBirthPlanet; } - if (planetsToRequest.Any()) + if (planetsToRequest.Remove(localPlanetId)) { - // Make local planet load first - int localPlanetId = Multiplayer.Session.LocalPlayer?.Data?.LocalPlanetId ?? -1; - if (localPlanetId == -1) - localPlanetId = UIVirtualStarmap_Transpiler.customBirthPlanet; - - if (planetsToRequest.Remove(localPlanetId)) - { - planetsToRequest.Insert(0, localPlanetId); - } - Multiplayer.Session.Network.SendPacket(new PlanetDataRequest(planetsToRequest.ToArray())); + planetsToRequest.Insert(0, localPlanetId); } + Multiplayer.Session.Network.SendPacket(new PlanetDataRequest(planetsToRequest.ToArray())); } } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(PlanetModelingManager.RequestCalcPlanet))] - public static bool RequestCalcPlanet_Prefix(PlanetData planet) + [HarmonyPrefix] + [HarmonyPatch(nameof(PlanetModelingManager.RequestCalcPlanet))] + public static bool RequestCalcPlanet_Prefix(PlanetData planet) + { + // Run the original method if this is the master client or in single player games + if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) { - // Run the original method if this is the master client or in single player games - if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) - { - return true; - } - - RequestCalcPlanet(planet); - return false; + return true; } - [HarmonyPrefix] - [HarmonyPatch(nameof(PlanetModelingManager.RequestCalcStar))] - public static bool RequestCalcStar_Prefix(StarData star) + RequestCalcPlanet(planet); + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(nameof(PlanetModelingManager.RequestCalcStar))] + public static bool RequestCalcStar_Prefix(StarData star) + { + // Run the original method if this is the master client or in single player games + if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) { - // Run the original method if this is the master client or in single player games - if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) - { - return true; - } + return true; + } - foreach (PlanetData planet in star.planets) - { - RequestCalcPlanet(planet); - } - return false; + foreach (var planet in star.planets) + { + RequestCalcPlanet(planet); } + return false; + } - private static void RequestCalcPlanet(PlanetData planet) + private static void RequestCalcPlanet(PlanetData planet) + { + if (!planet.calculated && !planet.calculating && planet.data == null) { - if (!planet.calculated && !planet.calculating && planet.data == null) + if (!planet.loaded && !planet.loading) { - if (!planet.loaded && !planet.loading) - { - planet.calculating = true; - Multiplayer.Session.Network.SendPacket(new PlanetDetailRequest(planet.id)); - } + planet.calculating = true; + Multiplayer.Session.Network.SendPacket(new PlanetDetailRequest(planet.id)); } } } diff --git a/NebulaPatcher/Patches/Dynamic/PlanetPhysics_Patch.cs b/NebulaPatcher/Patches/Dynamic/PlanetPhysics_Patch.cs index 4d21581ac..bde828e34 100644 --- a/NebulaPatcher/Patches/Dynamic/PlanetPhysics_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/PlanetPhysics_Patch.cs @@ -1,33 +1,36 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(PlanetPhysics))] +internal class PlanetPhysics_Patch { - [HarmonyPatch(typeof(PlanetPhysics))] - internal class PlanetPhysics_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(PlanetPhysics.RemoveLinkedColliderData))] + public static bool RemoveLinkedColliderData_Prefix(PlanetPhysics __instance) { - [HarmonyPrefix] - [HarmonyPatch(nameof(PlanetPhysics.RemoveLinkedColliderData))] - public static bool RemoveLinkedColliderData_Prefix(PlanetPhysics __instance) + //Collider does not need to be removed if player is not on the planet + if (Multiplayer.IsActive && __instance.planet.id != GameMain.mainPlayer.planetId) { - //Collider does not need to be removed if player is not on the planet - if (Multiplayer.IsActive && __instance.planet.id != GameMain.mainPlayer.planetId) - { - return false; - } - return true; + return false; } + return true; + } - [HarmonyPrefix] - [HarmonyPatch(nameof(PlanetPhysics.RemoveColliderData))] - public static bool RemoveColliderData_Prefix(PlanetPhysics __instance) + [HarmonyPrefix] + [HarmonyPatch(nameof(PlanetPhysics.RemoveColliderData))] + public static bool RemoveColliderData_Prefix(PlanetPhysics __instance) + { + //Collider does not need to be removed if player is not on the planet + if (Multiplayer.IsActive && __instance.planet.id != GameMain.mainPlayer.planetId) { - //Collider does not need to be removed if player is not on the planet - if (Multiplayer.IsActive && __instance.planet.id != GameMain.mainPlayer.planetId) - { - return false; - } - return true; + return false; } + return true; } } diff --git a/NebulaPatcher/Patches/Dynamic/PlanetTransport_Patch.cs b/NebulaPatcher/Patches/Dynamic/PlanetTransport_Patch.cs index 271191b23..a8f3cff6f 100644 --- a/NebulaPatcher/Patches/Dynamic/PlanetTransport_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/PlanetTransport_Patch.cs @@ -1,136 +1,150 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaModel.Logger; using NebulaModel.Packets.Logistics; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic -{ - [HarmonyPatch(typeof(PlanetTransport))] - internal class PlanetTransport_Patch - { - private static int RemovingStationGId = 0; - - [HarmonyPrefix] - [HarmonyPatch(nameof(PlanetTransport.SetStationStorage))] - public static bool SetStationStorage_Prefix(PlanetTransport __instance, int stationId, int storageIdx, int itemId, int itemCountMax, ELogisticStorage localLogic, ELogisticStorage remoteLogic) - { - if (Multiplayer.IsActive && !Multiplayer.Session.Ships.PatchLockILS) - { - StationComponent stationComponent = __instance.stationPool[stationId]; - - if (stationComponent != null) - { - StorageUI packet = new StorageUI(__instance.planet.id, stationComponent.id, stationComponent.gid, storageIdx, itemId, itemCountMax, localLogic, remoteLogic); - Multiplayer.Session.Network.SendPacket(packet); - } +#endregion - if (Multiplayer.Session.LocalPlayer.IsHost) - { - return true; - } +namespace NebulaPatcher.Patches.Dynamic; - return false; - } - return true; - } +[HarmonyPatch(typeof(PlanetTransport))] +internal class PlanetTransport_Patch +{ + private static int RemovingStationGId; - [HarmonyPostfix] - [HarmonyPatch(nameof(PlanetTransport.NewStationComponent))] - public static void NewStationComponent_Postfix(PlanetTransport __instance, StationComponent __result, PrefabDesc _desc) + [HarmonyPrefix] + [HarmonyPatch(nameof(PlanetTransport.SetStationStorage))] + public static bool SetStationStorage_Prefix(PlanetTransport __instance, int stationId, int storageIdx, int itemId, + int itemCountMax, ELogisticStorage localLogic, ELogisticStorage remoteLogic) + { + if (Multiplayer.IsActive && !Multiplayer.Session.Ships.PatchLockILS) { - if (!Multiplayer.IsActive) - { - return; - } + var stationComponent = __instance.stationPool[stationId]; - if (!__result.isStellar && __result.planetId == 0) + if (stationComponent != null) { - // for the PLS slot to sync properly the StationComponent of the PLS needs to have planetId set to the correct value. - // as the game does not do that for some reason, we need to do it here - __result.planetId = __instance.planet.id; + var packet = new StorageUI(__instance.planet.id, stationComponent.id, stationComponent.gid, storageIdx, itemId, + itemCountMax, localLogic, remoteLogic); + Multiplayer.Session.Network.SendPacket(packet); } - if (__result.gid > 0 && Multiplayer.Session.LocalPlayer.IsHost) + if (Multiplayer.Session.LocalPlayer.IsHost) { - // After host has added the StationComponent it has planetId, id and gId, now we can inform all clients about this station - // so they can add it to their GalacticTransport as they don't do that. Note that we're doing this in - // PlanetTransport.NewStationComponent and not GalacticTransport.AddStationComponent because stationId will be set at this point. - Log.Info($"Send AddStationComponen to all clients for planet {__result.planetId}, id {__result.id} with gId of {__result.gid}"); - Multiplayer.Session.Network.SendPacket(new ILSAddStationComponent(__result.planetId, __result.id, __result.gid, _desc.stationMaxShipCount)); + return true; } + + return false; } + return true; + } - [HarmonyPostfix] - [HarmonyPatch(nameof(PlanetTransport.Import))] - public static void Import_Postfix(PlanetTransport __instance) + [HarmonyPostfix] + [HarmonyPatch(nameof(PlanetTransport.NewStationComponent))] + public static void NewStationComponent_Postfix(PlanetTransport __instance, StationComponent __result, PrefabDesc _desc) + { + if (!Multiplayer.IsActive) { - if (!Multiplayer.IsActive) - { - return; - } - foreach (StationComponent stationComponent in __instance.stationPool) - { - if (stationComponent != null && stationComponent.planetId == 0 && !stationComponent.isStellar) - { - stationComponent.planetId = __instance.planet.id; - } - } + return; } - /* - * As clients need to access the StationComponent in gStationPool when RematchRemotePairs() is called (and this also gets called by RemoveStationComponent()) - * we need to prevent the call for client here to avoid a NRE and instead call it triggered by host after RematchRemotePairs() got called. - * basically in a Postfix of RemoveStationComponent() - */ - [HarmonyPrefix] - [HarmonyPatch(nameof(PlanetTransport.RemoveStationComponent))] - public static bool RemoveStationComponent_Prefix(PlanetTransport __instance, int id) + + if (!__result.isStellar && __result.planetId == 0) { - RemovingStationGId = __instance.stationPool[id].gid; // cache this as we need it in the postfix but its gone there already. - return !Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost || Multiplayer.Session.Ships.PatchLockILS; + // for the PLS slot to sync properly the StationComponent of the PLS needs to have planetId set to the correct value. + // as the game does not do that for some reason, we need to do it here + __result.planetId = __instance.planet.id; } - /* - * Host has called RematchRemotePairs() now and thus has send the ILSShipDataUpdate packet, so we can savely tell clients to remove the station component now. - */ - [HarmonyPostfix] - [HarmonyPatch(nameof(PlanetTransport.RemoveStationComponent))] - public static void RemoveStationComponent_Postfix(PlanetTransport __instance, int id) + if (__result.gid > 0 && Multiplayer.Session.LocalPlayer.IsHost) { - if (!Multiplayer.IsActive || !Multiplayer.Session.LocalPlayer.IsHost) + // After host has added the StationComponent it has planetId, id and gId, now we can inform all clients about this station + // so they can add it to their GalacticTransport as they don't do that. Note that we're doing this in + // PlanetTransport.NewStationComponent and not GalacticTransport.AddStationComponent because stationId will be set at this point. + Log.Info( + $"Send AddStationComponen to all clients for planet {__result.planetId}, id {__result.id} with gId of {__result.gid}"); + Multiplayer.Session.Network.SendPacket(new ILSAddStationComponent(__result.planetId, __result.id, __result.gid, + _desc.stationMaxShipCount)); + } + } + + [HarmonyPostfix] + [HarmonyPatch(nameof(PlanetTransport.Import))] + public static void Import_Postfix(PlanetTransport __instance) + { + if (!Multiplayer.IsActive) + { + return; + } + foreach (var stationComponent in __instance.stationPool) + { + if (stationComponent != null && stationComponent.planetId == 0 && !stationComponent.isStellar) { - return; + stationComponent.planetId = __instance.planet.id; } - Multiplayer.Session.Network.SendPacket(new ILSRemoveStationComponent(id, __instance.planet.id, RemovingStationGId)); } + } + + /* + * As clients need to access the StationComponent in gStationPool when RematchRemotePairs() is called (and this also gets called by RemoveStationComponent()) + * we need to prevent the call for client here to avoid a NRE and instead call it triggered by host after RematchRemotePairs() got called. + * basically in a Postfix of RemoveStationComponent() + */ + [HarmonyPrefix] + [HarmonyPatch(nameof(PlanetTransport.RemoveStationComponent))] + public static bool RemoveStationComponent_Prefix(PlanetTransport __instance, int id) + { + RemovingStationGId = + __instance.stationPool[id].gid; // cache this as we need it in the postfix but its gone there already. + return !Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost || Multiplayer.Session.Ships.PatchLockILS; + } - [HarmonyPrefix] - [HarmonyPatch(nameof(PlanetTransport.SetDispenserFilter))] - public static void SetDispenserFilter_Prefix(PlanetTransport __instance, int dispenserId, int filter) + /* + * Host has called RematchRemotePairs() now and thus has send the ILSShipDataUpdate packet, so we can savely tell clients to remove the station component now. + */ + [HarmonyPostfix] + [HarmonyPatch(nameof(PlanetTransport.RemoveStationComponent))] + public static void RemoveStationComponent_Postfix(PlanetTransport __instance, int id) + { + if (!Multiplayer.IsActive || !Multiplayer.Session.LocalPlayer.IsHost) { - if (Multiplayer.IsActive) - { - Multiplayer.Session.Network.SendPacketToLocalStar(new DispenserSettingPacket(__instance.planet.id, dispenserId, EDispenserSettingEvent.SetFilter, filter)); - } + return; } + Multiplayer.Session.Network.SendPacket(new ILSRemoveStationComponent(id, __instance.planet.id, RemovingStationGId)); + } - [HarmonyPrefix] - [HarmonyPatch(nameof(PlanetTransport.SetDispenserPlayerDeliveryMode))] - public static void SetDispenserPlayerDeliveryMode_Prefix(PlanetTransport __instance, int dispenserId, EPlayerDeliveryMode playerDeliveryMode) + [HarmonyPrefix] + [HarmonyPatch(nameof(PlanetTransport.SetDispenserFilter))] + public static void SetDispenserFilter_Prefix(PlanetTransport __instance, int dispenserId, int filter) + { + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) - { - Multiplayer.Session.Network.SendPacketToLocalStar(new DispenserSettingPacket(__instance.planet.id, dispenserId, EDispenserSettingEvent.SetPlayerDeliveryMode, (int)playerDeliveryMode)); - } + Multiplayer.Session.Network.SendPacketToLocalStar(new DispenserSettingPacket(__instance.planet.id, dispenserId, + EDispenserSettingEvent.SetFilter, filter)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(PlanetTransport.SetDispenserStorageDeliveryMode))] - public static void SetDispenserStorageDeliveryMode_Prefix(PlanetTransport __instance, int dispenserId, EStorageDeliveryMode storageDeliveryMode) + [HarmonyPrefix] + [HarmonyPatch(nameof(PlanetTransport.SetDispenserPlayerDeliveryMode))] + public static void SetDispenserPlayerDeliveryMode_Prefix(PlanetTransport __instance, int dispenserId, + EPlayerDeliveryMode playerDeliveryMode) + { + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) - { - Multiplayer.Session.Network.SendPacketToLocalStar(new DispenserSettingPacket(__instance.planet.id, dispenserId, EDispenserSettingEvent.SetStorageDeliveryMode, (int)storageDeliveryMode)); - } + Multiplayer.Session.Network.SendPacketToLocalStar(new DispenserSettingPacket(__instance.planet.id, dispenserId, + EDispenserSettingEvent.SetPlayerDeliveryMode, (int)playerDeliveryMode)); + } + } + + [HarmonyPrefix] + [HarmonyPatch(nameof(PlanetTransport.SetDispenserStorageDeliveryMode))] + public static void SetDispenserStorageDeliveryMode_Prefix(PlanetTransport __instance, int dispenserId, + EStorageDeliveryMode storageDeliveryMode) + { + if (Multiplayer.IsActive) + { + Multiplayer.Session.Network.SendPacketToLocalStar(new DispenserSettingPacket(__instance.planet.id, dispenserId, + EDispenserSettingEvent.SetStorageDeliveryMode, (int)storageDeliveryMode)); } } } diff --git a/NebulaPatcher/Patches/Dynamic/PlayerAction_Build_Patch.cs b/NebulaPatcher/Patches/Dynamic/PlayerAction_Build_Patch.cs index fca2ab839..71ac8207a 100644 --- a/NebulaPatcher/Patches/Dynamic/PlayerAction_Build_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/PlayerAction_Build_Patch.cs @@ -1,62 +1,73 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaAPI; using NebulaModel.Logger; using NebulaModel.Packets.Factory; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(PlayerAction_Build))] +internal class PlayerAction_Build_Patch { - [HarmonyPatch(typeof(PlayerAction_Build))] - internal class PlayerAction_Build_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(PlayerAction_Build.DoDismantleObject))] + public static bool DoDismantleObject_Prefix(PlayerAction_Build __instance, int objId) { - [HarmonyPrefix] - [HarmonyPatch(nameof(PlayerAction_Build.DoDismantleObject))] - public static bool DoDismantleObject_Prefix(PlayerAction_Build __instance, int objId) + if (!Multiplayer.IsActive) { - if (!Multiplayer.IsActive) - { - return true; - } - - int planetId = Multiplayer.Session.Factories.TargetPlanet != NebulaModAPI.PLANET_NONE ? Multiplayer.Session.Factories.TargetPlanet : __instance.planet?.id ?? -1; - // TODO: handle if 2 clients or if host and client trigger a destruct of the same object at the same time - - // If the object is a prebuild, remove it from the prebuild request list - if (Multiplayer.Session.LocalPlayer.IsHost && objId < 0) - { - if (!Multiplayer.Session.Factories.ContainsPrebuildRequest(planetId, -objId)) - { - Log.Warn($"DestructFinally was called without having a corresponding PrebuildRequest for the prebuild {-objId} on the planet {planetId}"); - return false; - } - - Multiplayer.Session.Factories.RemovePrebuildRequest(planetId, -objId); - } + return true; + } + var planetId = Multiplayer.Session.Factories.TargetPlanet != NebulaModAPI.PLANET_NONE + ? Multiplayer.Session.Factories.TargetPlanet + : __instance.planet?.id ?? -1; + // TODO: handle if 2 clients or if host and client trigger a destruct of the same object at the same time - if (Multiplayer.Session.LocalPlayer.IsHost || !Multiplayer.Session.Factories.IsIncomingRequest.Value) + // If the object is a prebuild, remove it from the prebuild request list + if (Multiplayer.Session.LocalPlayer.IsHost && objId < 0) + { + if (!Multiplayer.Session.Factories.ContainsPrebuildRequest(planetId, -objId)) { - Multiplayer.Session.Network.SendPacket(new DestructEntityRequest(planetId, objId, Multiplayer.Session.Factories.PacketAuthor == NebulaModAPI.AUTHOR_NONE ? Multiplayer.Session.LocalPlayer.Id : Multiplayer.Session.Factories.PacketAuthor)); + Log.Warn( + $"DestructFinally was called without having a corresponding PrebuildRequest for the prebuild {-objId} on the planet {planetId}"); + return false; } - return Multiplayer.Session.LocalPlayer.IsHost || Multiplayer.Session.Factories.IsIncomingRequest.Value; + Multiplayer.Session.Factories.RemovePrebuildRequest(planetId, -objId); } - [HarmonyPrefix] - [HarmonyPatch(nameof(PlayerAction_Build.SetFactoryReferences))] - public static bool SetFactoryReferences_Prefix() + + if (Multiplayer.Session.LocalPlayer.IsHost || !Multiplayer.Session.Factories.IsIncomingRequest.Value) { - if (!Multiplayer.IsActive) - { - return true; - } + Multiplayer.Session.Network.SendPacket(new DestructEntityRequest(planetId, objId, + Multiplayer.Session.Factories.PacketAuthor == NebulaModAPI.AUTHOR_NONE + ? Multiplayer.Session.LocalPlayer.Id + : Multiplayer.Session.Factories.PacketAuthor)); + } - if (Multiplayer.Session.Factories.IsIncomingRequest.Value && Multiplayer.Session.Factories.PacketAuthor != Multiplayer.Session.LocalPlayer.Id && Multiplayer.Session.Factories.TargetPlanet != GameMain.localPlanet?.id) - { - return false; - } + return Multiplayer.Session.LocalPlayer.IsHost || Multiplayer.Session.Factories.IsIncomingRequest.Value; + } + [HarmonyPrefix] + [HarmonyPatch(nameof(PlayerAction_Build.SetFactoryReferences))] + public static bool SetFactoryReferences_Prefix() + { + if (!Multiplayer.IsActive) + { return true; } + + if (Multiplayer.Session.Factories.IsIncomingRequest.Value && + Multiplayer.Session.Factories.PacketAuthor != Multiplayer.Session.LocalPlayer.Id && + Multiplayer.Session.Factories.TargetPlanet != GameMain.localPlanet?.id) + { + return false; + } + + return true; } } diff --git a/NebulaPatcher/Patches/Dynamic/Player_Patch.cs b/NebulaPatcher/Patches/Dynamic/Player_Patch.cs index 08e656344..f790a2763 100644 --- a/NebulaPatcher/Patches/Dynamic/Player_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/Player_Patch.cs @@ -1,77 +1,82 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaAPI; using NebulaModel; using NebulaModel.Packets.Players; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(Player))] +internal class Player_Patch { - [HarmonyPatch(typeof(Player))] - internal class Player_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(Player.SetSandCount))] + public static bool SetSandCount_Prefix(int newSandCount) { - [HarmonyPrefix] - [HarmonyPatch(nameof(Player.SetSandCount))] - public static bool SetSandCount_Prefix(int newSandCount) + if (Config.Options.SyncSoil) { - if (Config.Options.SyncSoil) + //Soil should be given in singleplayer or to the host who then syncs it back to all players. + if (Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsHost) { - //Soil should be given in singleplayer or to the host who then syncs it back to all players. - if(Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsHost) - { - Multiplayer.Session.Network.PlayerManager.UpdateSyncedSandCount(newSandCount - GameMain.mainPlayer.sandCount); - Multiplayer.Session.Network.SendPacket(new PlayerSandCount(newSandCount)); - } - //Or client that use reform tool - else if (Multiplayer.IsActive && GameMain.mainPlayer.controller.actionBuild.reformTool.drawing == true) - { - Multiplayer.Session.Network.SendPacket(new PlayerSandCount(newSandCount)); - } - return !Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost; + Multiplayer.Session.Network.PlayerManager.UpdateSyncedSandCount(newSandCount - GameMain.mainPlayer.sandCount); + Multiplayer.Session.Network.SendPacket(new PlayerSandCount(newSandCount)); } - else + //Or client that use reform tool + else if (Multiplayer.IsActive && GameMain.mainPlayer.controller.actionBuild.reformTool.drawing) { - //Soil should be given in singleplayer or to the player who is author of the "Build" request, or to the host if there is no author. - return !Multiplayer.IsActive || Multiplayer.Session.Factories.PacketAuthor == Multiplayer.Session.LocalPlayer.Id || (Multiplayer.Session.LocalPlayer.IsHost && Multiplayer.Session.Factories.PacketAuthor == NebulaModAPI.AUTHOR_NONE) || !Multiplayer.Session.Factories.IsIncomingRequest.Value; + Multiplayer.Session.Network.SendPacket(new PlayerSandCount(newSandCount)); } + return !Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost; } + //Soil should be given in singleplayer or to the player who is author of the "Build" request, or to the host if there is no author. + return !Multiplayer.IsActive || Multiplayer.Session.Factories.PacketAuthor == Multiplayer.Session.LocalPlayer.Id || + Multiplayer.Session.LocalPlayer.IsHost && + Multiplayer.Session.Factories.PacketAuthor == NebulaModAPI.AUTHOR_NONE || + !Multiplayer.Session.Factories.IsIncomingRequest.Value; + } - [HarmonyPrefix] - [HarmonyPatch(nameof(Player.TryAddItemToPackage))] - public static bool TryAddItemToPackage_Prefix(ref int __result) + [HarmonyPrefix] + [HarmonyPatch(nameof(Player.TryAddItemToPackage))] + public static bool TryAddItemToPackage_Prefix(ref int __result) + { + if (!Multiplayer.IsActive) { - if (!Multiplayer.IsActive) - { - return true; - } - - // We should only add items to player if player requested - if (Multiplayer.Session.Factories.IsIncomingRequest.Value && Multiplayer.Session.Factories.PacketAuthor != Multiplayer.Session.LocalPlayer.Id) - { - __result = 0; - return false; - } - return true; } - [HarmonyPrefix] - [HarmonyPatch(nameof(Player.UseHandItems))] - public static bool UseHandItems_Prefix(ref int __result) + // We should only add items to player if player requested + if (Multiplayer.Session.Factories.IsIncomingRequest.Value && + Multiplayer.Session.Factories.PacketAuthor != Multiplayer.Session.LocalPlayer.Id) { - // Run normally if we are not in an MP session or StorageComponent is not player package - if (!Multiplayer.IsActive) - { - return true; - } + __result = 0; + return false; + } - // We should only take items to player if player requested - if (Multiplayer.Session.Factories.IsIncomingRequest.Value && Multiplayer.Session.Factories.PacketAuthor != Multiplayer.Session.LocalPlayer.Id) - { - __result = 1; - return false; - } + return true; + } + [HarmonyPrefix] + [HarmonyPatch(nameof(Player.UseHandItems))] + public static bool UseHandItems_Prefix(ref int __result) + { + // Run normally if we are not in an MP session or StorageComponent is not player package + if (!Multiplayer.IsActive) + { return true; } + + // We should only take items to player if player requested + if (Multiplayer.Session.Factories.IsIncomingRequest.Value && + Multiplayer.Session.Factories.PacketAuthor != Multiplayer.Session.LocalPlayer.Id) + { + __result = 1; + return false; + } + + return true; } } diff --git a/NebulaPatcher/Patches/Dynamic/PostEffectController_Patch.cs b/NebulaPatcher/Patches/Dynamic/PostEffectController_Patch.cs index 80d5767b5..fbb5985c8 100644 --- a/NebulaPatcher/Patches/Dynamic/PostEffectController_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/PostEffectController_Patch.cs @@ -1,22 +1,25 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaModel; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(PostEffectController))] +internal class PostEffectController_Patch { - [HarmonyPatch(typeof(PostEffectController))] - internal class PostEffectController_Patch + [HarmonyPostfix] + [HarmonyPatch(nameof(PostEffectController.Start))] + public static void Start_Postfix() { - [HarmonyPostfix] - [HarmonyPatch(nameof(PostEffectController.Start))] - public static void Start_Postfix() + if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) { - if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) - { - return; - } - - PostEffectController.headlight = Config.Options.GuidingLightEnabled; + return; } + + PostEffectController.headlight = Config.Options.GuidingLightEnabled; } } diff --git a/NebulaPatcher/Patches/Dynamic/PowerSystemRenderer_Patch.cs b/NebulaPatcher/Patches/Dynamic/PowerSystemRenderer_Patch.cs index bf8834590..10be329aa 100644 --- a/NebulaPatcher/Patches/Dynamic/PowerSystemRenderer_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/PowerSystemRenderer_Patch.cs @@ -1,22 +1,25 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaModel; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(PowerSystemRenderer))] +internal class PowerSystemRenderer_Patch { - [HarmonyPatch(typeof(PowerSystemRenderer))] - internal class PowerSystemRenderer_Patch + [HarmonyPostfix] + [HarmonyPatch(nameof(PowerSystemRenderer.Init))] + public static void Init_Postfix() { - [HarmonyPostfix] - [HarmonyPatch(nameof(PowerSystemRenderer.Init))] - public static void Init_Postfix() + if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) { - if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) - { - return; - } - - PowerSystemRenderer.powerGraphOn = Config.Options.PowerGridEnabled; + return; } + + PowerSystemRenderer.powerGraphOn = Config.Options.PowerGridEnabled; } } diff --git a/NebulaPatcher/Patches/Dynamic/PowerSystem_Patch.cs b/NebulaPatcher/Patches/Dynamic/PowerSystem_Patch.cs index 0fa331dee..17f41854e 100644 --- a/NebulaPatcher/Patches/Dynamic/PowerSystem_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/PowerSystem_Patch.cs @@ -1,51 +1,54 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(PowerSystem))] +internal class PowerSystem_Patch { - [HarmonyPatch(typeof(PowerSystem))] - internal class PowerSystem_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(PowerSystem.GameTick))] + public static void PowerSystem_GameTick_Prefix(long time, ref bool isActive) { - [HarmonyPrefix] - [HarmonyPatch(nameof(PowerSystem.GameTick))] - public static void PowerSystem_GameTick_Prefix(long time, ref bool isActive) + //Enable signType update on remote planet every 64 tick + if ((time & 63) == 0 && Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsHost) { - //Enable signType update on remote planet every 64 tick - if ((time & 63) == 0 && Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsHost) - { - isActive |= true; - } + isActive |= true; } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(PowerSystem.GameTick))] - public static void PowerSystem_GameTick_Postfix(PowerSystem __instance, long time, bool isActive, bool isMultithreadMode) + [HarmonyPostfix] + [HarmonyPatch(nameof(PowerSystem.GameTick))] + public static void PowerSystem_GameTick_Postfix(PowerSystem __instance, long time, bool isActive, bool isMultithreadMode) + { + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) + for (var i = 1; i < __instance.netCursor; i++) { - for (int i = 1; i < __instance.netCursor; i++) - { - PowerNetwork pNet = __instance.netPool[i]; - pNet.energyRequired += Multiplayer.Session.PowerTowers.GetExtraDemand(__instance.planet.id, i); - } - Multiplayer.Session.PowerTowers.GivePlayerPower(); - Multiplayer.Session.PowerTowers.UpdateAllAnimations(__instance.planet.id); + var pNet = __instance.netPool[i]; + pNet.energyRequired += Multiplayer.Session.PowerTowers.GetExtraDemand(__instance.planet.id, i); } + Multiplayer.Session.PowerTowers.GivePlayerPower(); + Multiplayer.Session.PowerTowers.UpdateAllAnimations(__instance.planet.id); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(PowerSystem.RemoveNodeComponent))] - public static bool RemoveNodeComponent(PowerSystem __instance, int id) + [HarmonyPrefix] + [HarmonyPatch(nameof(PowerSystem.RemoveNodeComponent))] + public static bool RemoveNodeComponent(PowerSystem __instance, int id) + { + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) - { - // as the destruct is synced accross players this event is too - // and as such we can safely remove power demand for every player - PowerNodeComponent pComp = __instance.nodePool[id]; - Multiplayer.Session.PowerTowers.RemExtraDemand(__instance.planet.id, pComp.networkId, id); - } - - return true; + // as the destruct is synced accross players this event is too + // and as such we can safely remove power demand for every player + var pComp = __instance.nodePool[id]; + Multiplayer.Session.PowerTowers.RemExtraDemand(__instance.planet.id, pComp.networkId, id); } + + return true; } } diff --git a/NebulaPatcher/Patches/Dynamic/ProductionStatistics_Patch.cs b/NebulaPatcher/Patches/Dynamic/ProductionStatistics_Patch.cs index 90ad03430..64a2891e4 100644 --- a/NebulaPatcher/Patches/Dynamic/ProductionStatistics_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/ProductionStatistics_Patch.cs @@ -1,60 +1,60 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(ProductionStatistics))] +internal class ProductionStatistics_Patch { - [HarmonyPatch(typeof(ProductionStatistics))] - internal class ProductionStatistics_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(ProductionStatistics.PrepareTick))] + public static bool PrepareTick_Prefix(ProductionStatistics __instance) { - [HarmonyPrefix] - [HarmonyPatch(nameof(ProductionStatistics.PrepareTick))] - public static bool PrepareTick_Prefix(ProductionStatistics __instance) + if (Multiplayer.IsActive && !Multiplayer.Session.LocalPlayer.IsHost) { - if (Multiplayer.IsActive && !Multiplayer.Session.LocalPlayer.IsHost) - { - for (int i = 0; i < __instance.gameData.factoryCount; i++) - { - __instance.factoryStatPool[i]?.PrepareTick(); - } - return false; - } - else + for (var i = 0; i < __instance.gameData.factoryCount; i++) { - return true; + __instance.factoryStatPool[i]?.PrepareTick(); } + return false; } + return true; + } - [HarmonyPrefix] - [HarmonyPatch(nameof(ProductionStatistics.AfterTick))] - public static bool AfterTick_Prefix(ProductionStatistics __instance) + [HarmonyPrefix] + [HarmonyPatch(nameof(ProductionStatistics.AfterTick))] + public static bool AfterTick_Prefix(ProductionStatistics __instance) + { + if (Multiplayer.IsActive && !Multiplayer.Session.LocalPlayer.IsHost) { - if (Multiplayer.IsActive && !Multiplayer.Session.LocalPlayer.IsHost) + for (var i = 0; i < __instance.gameData.factoryCount; i++) { - for (int i = 0; i < __instance.gameData.factoryCount; i++) - { - __instance.factoryStatPool[i]?.AfterTick(); - } - return false; + __instance.factoryStatPool[i]?.AfterTick(); } - return true; + return false; } + return true; + } - [HarmonyPrefix] - [HarmonyPatch(nameof(ProductionStatistics.GameTick))] - public static bool GameTick_Prefix(ProductionStatistics __instance) + [HarmonyPrefix] + [HarmonyPatch(nameof(ProductionStatistics.GameTick))] + public static bool GameTick_Prefix(ProductionStatistics __instance) + { + if (Multiplayer.IsActive && !Multiplayer.Session.LocalPlayer.IsHost) { - if (Multiplayer.IsActive && !Multiplayer.Session.LocalPlayer.IsHost) + //Do not run on client if you do not have all data + for (var i = 0; i < __instance.gameData.factoryCount; i++) { - //Do not run on client if you do not have all data - for (int i = 0; i < __instance.gameData.factoryCount; i++) + if (__instance.factoryStatPool[i] == null) { - if (__instance.factoryStatPool[i] == null) - { - return false; - } + return false; } } - return true; } + return true; } } diff --git a/NebulaPatcher/Patches/Dynamic/RaycastLogic_Patch.cs b/NebulaPatcher/Patches/Dynamic/RaycastLogic_Patch.cs index 96addc70e..9842b16f2 100644 --- a/NebulaPatcher/Patches/Dynamic/RaycastLogic_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/RaycastLogic_Patch.cs @@ -1,25 +1,28 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(RaycastLogic))] +internal class RaycastLogic_Patch { - [HarmonyPatch(typeof(RaycastLogic))] - internal class RaycastLogic_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(RaycastLogic.GameTick))] + public static bool GameTick_Prefix(RaycastLogic __instance) { - [HarmonyPrefix] - [HarmonyPatch(nameof(RaycastLogic.GameTick))] - public static bool GameTick_Prefix(RaycastLogic __instance) + if (Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsClient) { - if (Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsClient) + if (__instance.factory == null) { - if(__instance.factory == null) - { - // while we wait for factory data from server this is still null, prevent running into NRE - return false; - } + // while we wait for factory data from server this is still null, prevent running into NRE + return false; } - - return true; } + + return true; } } diff --git a/NebulaPatcher/Patches/Dynamic/Resources_Patch.cs b/NebulaPatcher/Patches/Dynamic/Resources_Patch.cs index 34f89402f..8e8fdafbc 100644 --- a/NebulaPatcher/Patches/Dynamic/Resources_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/Resources_Patch.cs @@ -1,46 +1,50 @@ -using HarmonyLib; +#region + +using System; +using HarmonyLib; using NebulaModel.Logger; using NebulaWorld; -using System; using TMPro; using UnityEngine; using Object = UnityEngine.Object; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(Resources))] +public static class Resources_Patch { - [HarmonyPatch(typeof(Resources))] - public static class Resources_Patch + [HarmonyPatch(nameof(Resources.Load), typeof(string), typeof(Type))] + [HarmonyPrefix] + public static bool Prefix(ref string path, Type systemTypeInstance, ref Object __result) { - [HarmonyPatch(nameof(Resources.Load), typeof(string), typeof(Type))] - [HarmonyPrefix] - public static bool Prefix(ref string path, Type systemTypeInstance, ref Object __result) + if (path.Contains("TMP Settings")) { - if (path.Contains("TMP Settings")) + var asset = AssetLoader.AssetBundle.LoadAsset("Assets/Resources/TextMeshPro/TMP Settings.asset"); + if (asset != null) { - var asset = AssetLoader.AssetBundle.LoadAsset("Assets/Resources/TextMeshPro/TMP Settings.asset"); - if (asset != null) - { - __result = asset; - Log.Debug("Successfully loaded TMP Settings"); - return false; - } - - Log.Warn("Failed to load TMP Settings!"); - }else if (path.StartsWith("TextMeshPro")) + __result = asset; + Log.Debug("Successfully loaded TMP Settings"); + return false; + } + + Log.Warn("Failed to load TMP Settings!"); + } + else if (path.StartsWith("TextMeshPro")) + { + var asset = AssetLoader.AssetBundle.LoadAsset($"Assets/Resources/{path}"); + if (asset != null) { - var asset = AssetLoader.AssetBundle.LoadAsset($"Assets/Resources/{path}"); - if (asset != null) - { - __result = asset; - Log.Debug("Successfully loaded TMP asset"); - return false; - } - - Log.Warn($"Failed to load TMP asset: {path}!"); + __result = asset; + Log.Debug("Successfully loaded TMP asset"); + return false; } - - return true; + Log.Warn($"Failed to load TMP asset: {path}!"); } + + + return true; } -} \ No newline at end of file +} diff --git a/NebulaPatcher/Patches/Dynamic/STEAMX_Patch.cs b/NebulaPatcher/Patches/Dynamic/STEAMX_Patch.cs index a0b18a56e..98fa97997 100644 --- a/NebulaPatcher/Patches/Dynamic/STEAMX_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/STEAMX_Patch.cs @@ -1,17 +1,20 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(STEAMX))] +internal class STEAMX_Patch { - [HarmonyPatch(typeof(STEAMX))] - internal class STEAMX_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(STEAMX.UploadScoreToLeaderboard))] + public static bool UploadScoreToLeaderboard_Prefix() { - [HarmonyPrefix] - [HarmonyPatch(nameof(STEAMX.UploadScoreToLeaderboard))] - public static bool UploadScoreToLeaderboard_Prefix() - { - // We don't want to upload steam leaderboard data if we are playing MP - return !Multiplayer.IsActive; - } + // We don't want to upload steam leaderboard data if we are playing MP + return !Multiplayer.IsActive; } } diff --git a/NebulaPatcher/Patches/Dynamic/SpeakerComponent_Patch.cs b/NebulaPatcher/Patches/Dynamic/SpeakerComponent_Patch.cs index 3d9ff0fe1..f5ac15a15 100644 --- a/NebulaPatcher/Patches/Dynamic/SpeakerComponent_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/SpeakerComponent_Patch.cs @@ -1,90 +1,91 @@ -using HarmonyLib; -using NebulaWorld; -using NebulaModel.Packets.Factory.Monitor; -using NebulaModel.Logger; +#region + using System; +using HarmonyLib; +using NebulaModel.Packets.Factory.Monitor; +using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic -{ +#endregion + +namespace NebulaPatcher.Patches.Dynamic; #pragma warning disable Harmony003 // Harmony non-ref patch parameters modified - [HarmonyPatch(typeof(SpeakerComponent))] - internal class SpeakerComponent_Patch +[HarmonyPatch(typeof(SpeakerComponent))] +internal class SpeakerComponent_Patch +{ + [HarmonyPrefix] + [HarmonyPatch(nameof(SpeakerComponent.SetTone))] + public static void SetPassColorId_Prefix(MonitorComponent __instance, int __0) { - [HarmonyPrefix] - [HarmonyPatch(nameof(SpeakerComponent.SetTone))] - public static void SetPassColorId_Prefix(MonitorComponent __instance, int __0) + if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) { - if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) - { - //Assume the monitor is on local planet - int planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; - Multiplayer.Session.Network.SendPacketToLocalStar( - new SpeakerSettingUpdatePacket(planetId, __instance.id, SpeakerSettingEvent.SetTone, __0)); - } + //Assume the monitor is on local planet + var planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; + Multiplayer.Session.Network.SendPacketToLocalStar( + new SpeakerSettingUpdatePacket(planetId, __instance.id, SpeakerSettingEvent.SetTone, __0)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(SpeakerComponent.SetVolume))] - public static void SetVolume_Prefix(MonitorComponent __instance, int __0) + [HarmonyPrefix] + [HarmonyPatch(nameof(SpeakerComponent.SetVolume))] + public static void SetVolume_Prefix(MonitorComponent __instance, int __0) + { + if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) { - if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) - { - int planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; - Multiplayer.Session.Network.SendPacketToLocalStar( - new SpeakerSettingUpdatePacket(planetId, __instance.id, SpeakerSettingEvent.SetVolume, __0)); - } + var planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; + Multiplayer.Session.Network.SendPacketToLocalStar( + new SpeakerSettingUpdatePacket(planetId, __instance.id, SpeakerSettingEvent.SetVolume, __0)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(SpeakerComponent.SetPitch))] - public static void SetPitch_Prefix(MonitorComponent __instance, int __0) + [HarmonyPrefix] + [HarmonyPatch(nameof(SpeakerComponent.SetPitch))] + public static void SetPitch_Prefix(MonitorComponent __instance, int __0) + { + if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) { - if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) - { - int planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; - Multiplayer.Session.Network.SendPacketToLocalStar( - new SpeakerSettingUpdatePacket(planetId, __instance.id, SpeakerSettingEvent.SetPitch, __0)); - } + var planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; + Multiplayer.Session.Network.SendPacketToLocalStar( + new SpeakerSettingUpdatePacket(planetId, __instance.id, SpeakerSettingEvent.SetPitch, __0)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(SpeakerComponent.SetLength))] - public static void SetLength_Prefix(MonitorComponent __instance, float __0) + [HarmonyPrefix] + [HarmonyPatch(nameof(SpeakerComponent.SetLength))] + public static void SetLength_Prefix(MonitorComponent __instance, float __0) + { + if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) { - if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) - { - int planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; - int p1 = BitConverter.ToInt32(BitConverter.GetBytes(__0), 0); - Multiplayer.Session.Network.SendPacketToLocalStar( - new SpeakerSettingUpdatePacket(planetId, __instance.id, SpeakerSettingEvent.SetLength, p1)); - } + var planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; + var p1 = BitConverter.ToInt32(BitConverter.GetBytes(__0), 0); + Multiplayer.Session.Network.SendPacketToLocalStar( + new SpeakerSettingUpdatePacket(planetId, __instance.id, SpeakerSettingEvent.SetLength, p1)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(SpeakerComponent.SetRepeat))] - public static void SetLength_Prefix(MonitorComponent __instance, bool __0) + [HarmonyPrefix] + [HarmonyPatch(nameof(SpeakerComponent.SetRepeat))] + public static void SetLength_Prefix(MonitorComponent __instance, bool __0) + { + if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) { - if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) - { - int planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; - Multiplayer.Session.Network.SendPacketToLocalStar( - new SpeakerSettingUpdatePacket(planetId, __instance.id, SpeakerSettingEvent.SetRepeat, __0 ? 1 : 0)); - } + var planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; + Multiplayer.Session.Network.SendPacketToLocalStar( + new SpeakerSettingUpdatePacket(planetId, __instance.id, SpeakerSettingEvent.SetRepeat, __0 ? 1 : 0)); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(SpeakerComponent.SetFalloffRadius))] - public static void SetFalloffRadius_Prefix(MonitorComponent __instance, float __0, float __1) + [HarmonyPrefix] + [HarmonyPatch(nameof(SpeakerComponent.SetFalloffRadius))] + public static void SetFalloffRadius_Prefix(MonitorComponent __instance, float __0, float __1) + { + if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) { - if (Multiplayer.IsActive && !Multiplayer.Session.Warning.IsIncomingMonitorPacket) - { - int planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; - int p1 = BitConverter.ToInt32(BitConverter.GetBytes(__0), 0); - int p2 = BitConverter.ToInt32(BitConverter.GetBytes(__1), 0); - Multiplayer.Session.Network.SendPacketToLocalStar( - new SpeakerSettingUpdatePacket(planetId, __instance.id, SpeakerSettingEvent.SetFalloffRadius, p1, p2)); - } + var planetId = GameMain.data.localPlanet == null ? -1 : GameMain.data.localPlanet.id; + var p1 = BitConverter.ToInt32(BitConverter.GetBytes(__0), 0); + var p2 = BitConverter.ToInt32(BitConverter.GetBytes(__1), 0); + Multiplayer.Session.Network.SendPacketToLocalStar( + new SpeakerSettingUpdatePacket(planetId, __instance.id, SpeakerSettingEvent.SetFalloffRadius, p1, p2)); } } -#pragma warning restore Harmony003 // Harmony non-ref patch parameters modified } +#pragma warning restore Harmony003 // Harmony non-ref patch parameters modified diff --git a/NebulaPatcher/Patches/Dynamic/StationComponent_Patch.cs b/NebulaPatcher/Patches/Dynamic/StationComponent_Patch.cs index bdd6f1121..5a0fa51ba 100644 --- a/NebulaPatcher/Patches/Dynamic/StationComponent_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/StationComponent_Patch.cs @@ -1,96 +1,100 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaModel.Logger; using NebulaModel.Packets.Logistics; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(StationComponent))] +internal class StationComponent_Patch { - [HarmonyPatch(typeof(StationComponent))] - internal class StationComponent_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(StationComponent.InternalTickRemote))] + public static bool InternalTickRemote_Prefix(StationComponent __instance) { - [HarmonyPrefix] - [HarmonyPatch(nameof(StationComponent.InternalTickRemote))] - public static bool InternalTickRemote_Prefix(StationComponent __instance) + if (Multiplayer.IsActive && !Multiplayer.Session.LocalPlayer.IsHost) { - if (Multiplayer.IsActive && !Multiplayer.Session.LocalPlayer.IsHost) + // skip vanilla code entirely and use our modified version instead (which focuses on ship movement) + // call our InternalTickRemote() for every StationComponent in game. Normally this would be done by each PlanetFactory, but as a client + // we dont have every PlanetFactory at hand. + // so iterate over the GameMain.data.galacticTransport.stationPool array which should also include the fake entries for factories we have not loaded yet. + // but do this at another place to not trigger it more often than needed (GameData::GameTick()) + if (__instance.warperCount < __instance.warperMaxCount) { - // skip vanilla code entirely and use our modified version instead (which focuses on ship movement) - // call our InternalTickRemote() for every StationComponent in game. Normally this would be done by each PlanetFactory, but as a client - // we dont have every PlanetFactory at hand. - // so iterate over the GameMain.data.galacticTransport.stationPool array which should also include the fake entries for factories we have not loaded yet. - // but do this at another place to not trigger it more often than needed (GameData::GameTick()) - if (__instance.warperCount < __instance.warperMaxCount) + // refill warpers from ILS storage + for (var i = 0; i < __instance.storage.Length; i++) { - // refill warpers from ILS storage - for (int i = 0; i < __instance.storage.Length; i++) + if (__instance.storage[i].itemId == 1210 && __instance.storage[i].count > 0) { - if (__instance.storage[i].itemId == 1210 && __instance.storage[i].count > 0) + __instance.warperCount++; + lock (__instance.storage) { - __instance.warperCount++; - lock (__instance.storage) - { - int num = __instance.storage[i].inc / __instance.storage[i].count; - StationStore[] array = __instance.storage; - int num2 = i; - array[num2].count = array[num2].count - 1; - StationStore[] array2 = __instance.storage; - int num3 = i; - array2[num3].inc = array2[num3].inc - num; - } - break; + var num = __instance.storage[i].inc / __instance.storage[i].count; + var array = __instance.storage; + var num2 = i; + array[num2].count = array[num2].count - 1; + var array2 = __instance.storage; + var num3 = i; + array2[num3].inc = array2[num3].inc - num; } + break; } } - return false; } - return true; + return false; } + return true; + } - [HarmonyPrefix] - [HarmonyPatch(nameof(StationComponent.RematchRemotePairs))] - public static bool RematchRemotePairs_Prefix() + [HarmonyPrefix] + [HarmonyPatch(nameof(StationComponent.RematchRemotePairs))] + public static bool RematchRemotePairs_Prefix() + { + if (Multiplayer.IsActive && !Multiplayer.Session.LocalPlayer.IsHost) { - if (Multiplayer.IsActive && !Multiplayer.Session.LocalPlayer.IsHost) - { - // skip vanilla code entirely for clients as we do this event based triggered by the server - return false; - } - return true; + // skip vanilla code entirely for clients as we do this event based triggered by the server + return false; } + return true; + } - [HarmonyPostfix] - [HarmonyPatch(nameof(StationComponent.IdleShipGetToWork))] - public static void IdleShipGetToWork_Postfix(StationComponent __instance) + [HarmonyPostfix] + [HarmonyPatch(nameof(StationComponent.IdleShipGetToWork))] + public static void IdleShipGetToWork_Postfix(StationComponent __instance) + { + if (Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsHost) { - if (Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsHost) - { - ILSIdleShipBackToWork packet = new ILSIdleShipBackToWork(__instance.workShipDatas[__instance.workShipCount - 1], __instance.gid, __instance.workShipDatas.Length, __instance.warperCount); - Multiplayer.Session.Network.SendPacket(packet); - } + var packet = new ILSIdleShipBackToWork(__instance.workShipDatas[__instance.workShipCount - 1], __instance.gid, + __instance.workShipDatas.Length, __instance.warperCount); + Multiplayer.Session.Network.SendPacket(packet); } + } - // as we unload PlanetFactory objects when leaving the star system we need to prevent the call on ILS entries in the gStationPool array - [HarmonyPrefix] - [HarmonyPatch(nameof(StationComponent.Free))] - public static bool Free_Prefix(StationComponent __instance) + // as we unload PlanetFactory objects when leaving the star system we need to prevent the call on ILS entries in the gStationPool array + [HarmonyPrefix] + [HarmonyPatch(nameof(StationComponent.Free))] + public static bool Free_Prefix(StationComponent __instance) + { + if (!Multiplayer.IsActive || !Multiplayer.Session.Ships.PatchLockILS) { - if (!Multiplayer.IsActive || !Multiplayer.Session.Ships.PatchLockILS) - { - return true; - } - if (__instance.isStellar) - { - return false; - } return true; } - - [HarmonyPrefix] - [HarmonyPatch(nameof(StationComponent.Reset))] - public static bool Reset_Prefix(StationComponent __instance) + if (__instance.isStellar) { - Log.Debug($"Reset called on gid {__instance.gid}"); - return true; + return false; } + return true; + } + + [HarmonyPrefix] + [HarmonyPatch(nameof(StationComponent.Reset))] + public static bool Reset_Prefix(StationComponent __instance) + { + Log.Debug($"Reset called on gid {__instance.gid}"); + return true; } } diff --git a/NebulaPatcher/Patches/Dynamic/StorageComponent_Patch.cs b/NebulaPatcher/Patches/Dynamic/StorageComponent_Patch.cs index 99681f6b4..e10c32c92 100644 --- a/NebulaPatcher/Patches/Dynamic/StorageComponent_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/StorageComponent_Patch.cs @@ -1,111 +1,131 @@ -using HarmonyLib; -using NebulaModel.Packets.Factory; +#region + +using HarmonyLib; using NebulaModel.Packets.Factory.Storage; using NebulaWorld; -using System; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(StorageComponent))] +internal class StorageComponent_Patch { - [HarmonyPatch(typeof(StorageComponent))] - internal class StorageComponent_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(StorageComponent.AddItem), + new[] { typeof(int), typeof(int), typeof(int), typeof(int), typeof(int), typeof(int) }, + new[] + { + ArgumentType.Normal, ArgumentType.Normal, ArgumentType.Normal, ArgumentType.Normal, ArgumentType.Normal, + ArgumentType.Out + })] + public static bool AddItem_Prefix(StorageComponent __instance, int itemId, int count, int startIndex, int length, int inc, + out int remainInc) { - [HarmonyPrefix] - [HarmonyPatch(nameof(StorageComponent.AddItem), new Type[] { typeof(int), typeof(int), typeof(int), typeof(int), typeof(int), typeof(int) }, new ArgumentType[]{ArgumentType.Normal, ArgumentType.Normal, ArgumentType.Normal, ArgumentType.Normal, ArgumentType.Normal, ArgumentType.Out})] - public static bool AddItem_Prefix(StorageComponent __instance, int itemId, int count, int startIndex, int length, int inc, out int remainInc) + //Run only in MP, if it is not triggered remotly and if this event was triggered manually by an user + if (Multiplayer.IsActive && !Multiplayer.Session.Storage.IsIncomingRequest && + Multiplayer.Session.Storage.IsHumanInput && GameMain.data.localPlanet != null) { - //Run only in MP, if it is not triggered remotly and if this event was triggered manually by an user - if (Multiplayer.IsActive && !Multiplayer.Session.Storage.IsIncomingRequest && Multiplayer.Session.Storage.IsHumanInput && GameMain.data.localPlanet != null) - { - HandleUserInteraction(__instance, new StorageSyncRealtimeChangePacket(__instance.id, StorageSyncRealtimeChangeEvent.AddItem2, itemId, count, startIndex, length, inc)); - } - remainInc = inc; // this is what the game does anyways so it should not change the functionality of the method - return true; + HandleUserInteraction(__instance, + new StorageSyncRealtimeChangePacket(__instance.id, StorageSyncRealtimeChangeEvent.AddItem2, itemId, count, + startIndex, length, inc)); } + remainInc = inc; // this is what the game does anyways so it should not change the functionality of the method + return true; + } - [HarmonyPrefix] - [HarmonyPatch(nameof(StorageComponent.AddItemStacked))] - public static bool AddItemStacked_Prefix(StorageComponent __instance, int itemId, int count, int inc, out int remainInc) + [HarmonyPrefix] + [HarmonyPatch(nameof(StorageComponent.AddItemStacked))] + public static bool AddItemStacked_Prefix(StorageComponent __instance, int itemId, int count, int inc, out int remainInc) + { + //Run only in MP, if it is not triggered remotly and if this event was triggered manually by an user + if (Multiplayer.IsActive && !Multiplayer.Session.Storage.IsIncomingRequest && + Multiplayer.Session.Storage.IsHumanInput && GameMain.data.localPlanet != null) { - //Run only in MP, if it is not triggered remotly and if this event was triggered manually by an user - if (Multiplayer.IsActive && !Multiplayer.Session.Storage.IsIncomingRequest && Multiplayer.Session.Storage.IsHumanInput && GameMain.data.localPlanet != null) - { - HandleUserInteraction(__instance, new StorageSyncRealtimeChangePacket(__instance.id, StorageSyncRealtimeChangeEvent.AddItemStacked, itemId, count, inc)); - } - remainInc = inc; // this is what the game does anyways so it should not change the functionality of the method - return true; + HandleUserInteraction(__instance, + new StorageSyncRealtimeChangePacket(__instance.id, StorageSyncRealtimeChangeEvent.AddItemStacked, itemId, count, + inc)); + } + remainInc = inc; // this is what the game does anyways so it should not change the functionality of the method + return true; + } + [HarmonyPrefix] + [HarmonyPatch(nameof(StorageComponent.TakeItemFromGrid))] + public static bool TakeItemFromGrid_Prefix(StorageComponent __instance, int gridIndex, ref int itemId, ref int count, + out int inc) + { + //Run only in MP, if it is not triggered remotly and if this event was triggered manually by an user + if (Multiplayer.IsActive && !Multiplayer.Session.Storage.IsIncomingRequest && + Multiplayer.Session.Storage.IsHumanInput && GameMain.data.localPlanet != null) + { + HandleUserInteraction(__instance, + new StorageSyncRealtimeChangePacket(__instance.id, StorageSyncRealtimeChangeEvent.TakeItemFromGrid, gridIndex, + itemId, count, 0)); } + inc = 0; // this is what the game does anyways so it should not change the functionality of the method + return true; + } - [HarmonyPrefix] - [HarmonyPatch(nameof(StorageComponent.TakeItemFromGrid))] - public static bool TakeItemFromGrid_Prefix(StorageComponent __instance, int gridIndex, ref int itemId, ref int count, out int inc) + [HarmonyPostfix] + [HarmonyPatch(nameof(StorageComponent.SetBans))] + public static void SetBans_Postfix(StorageComponent __instance, int _bans) + { + if (Multiplayer.IsActive && !Multiplayer.Session.Storage.IsIncomingRequest && GameMain.data.localPlanet != null) { - //Run only in MP, if it is not triggered remotly and if this event was triggered manually by an user - if (Multiplayer.IsActive && !Multiplayer.Session.Storage.IsIncomingRequest && Multiplayer.Session.Storage.IsHumanInput && GameMain.data.localPlanet != null) - { - HandleUserInteraction(__instance, new StorageSyncRealtimeChangePacket(__instance.id, StorageSyncRealtimeChangeEvent.TakeItemFromGrid, gridIndex, itemId, count, 0)); - } - inc = 0; // this is what the game does anyways so it should not change the functionality of the method - return true; + HandleUserInteraction(__instance, new StorageSyncSetBansPacket(__instance.id, GameMain.data.localPlanet.id, _bans)); } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(StorageComponent.SetBans))] - public static void SetBans_Postfix(StorageComponent __instance, int _bans) + [HarmonyPostfix] + [HarmonyPatch(nameof(StorageComponent.Sort))] + public static void Sort_Postfix(StorageComponent __instance) + { + if (Multiplayer.IsActive && !Multiplayer.Session.Storage.IsIncomingRequest && GameMain.data.localPlanet != null) { - if (Multiplayer.IsActive && !Multiplayer.Session.Storage.IsIncomingRequest && GameMain.data.localPlanet != null) - { - HandleUserInteraction(__instance, new StorageSyncSetBansPacket(__instance.id, GameMain.data.localPlanet.id, _bans)); - } + HandleUserInteraction(__instance, new StorageSyncSortPacket(__instance.id, GameMain.data.localPlanet.id)); } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(StorageComponent.Sort))] - public static void Sort_Postfix(StorageComponent __instance) + [HarmonyPrefix] + [HarmonyPatch(typeof(StorageComponent), nameof(StorageComponent.TakeTailItems), + new[] { typeof(int), typeof(int), typeof(int), typeof(bool) }, + new[] { ArgumentType.Ref, ArgumentType.Ref, ArgumentType.Out, ArgumentType.Normal })] + public static bool TakeTailItems_Prefix(StorageComponent __instance, ref int count) + { + // Run normally if we are not in an MP session or StorageComponent is not player package + if (!Multiplayer.IsActive || __instance.id != GameMain.mainPlayer.package.id) { - if (Multiplayer.IsActive && !Multiplayer.Session.Storage.IsIncomingRequest && GameMain.data.localPlanet != null) - { - HandleUserInteraction(__instance, new StorageSyncSortPacket(__instance.id, GameMain.data.localPlanet.id)); - } + return true; } - [HarmonyPrefix] - [HarmonyPatch(typeof(StorageComponent), nameof(StorageComponent.TakeTailItems), new Type[] { typeof(int), typeof(int), typeof(int), typeof(bool) }, new ArgumentType[] { ArgumentType.Ref, ArgumentType.Ref, ArgumentType.Out, ArgumentType.Normal })] - public static bool TakeTailItems_Prefix(StorageComponent __instance, ref int count) + // We should only take items to player if player requested + if (Multiplayer.Session.Factories.IsIncomingRequest.Value && + Multiplayer.Session.Factories.PacketAuthor != Multiplayer.Session.LocalPlayer.Id) { - // Run normally if we are not in an MP session or StorageComponent is not player package - if (!Multiplayer.IsActive || __instance.id != GameMain.mainPlayer.package.id) - { - return true; - } + count = 1; + return false; + } - // We should only take items to player if player requested - if (Multiplayer.Session.Factories.IsIncomingRequest.Value && Multiplayer.Session.Factories.PacketAuthor != Multiplayer.Session.LocalPlayer.Id) - { - count = 1; - return false; - } + return true; + } - return true; + public static void HandleUserInteraction(StorageComponent __instance, T packet) where T : class, new() + { + //Skip if change was done in player's inventory + if (__instance.entityId == 0 && __instance.id == 0) + { + return; } - public static void HandleUserInteraction(StorageComponent __instance, T packet) where T : class, new() + if (Multiplayer.Session.LocalPlayer.IsHost) { - //Skip if change was done in player's inventory - if (__instance.entityId == 0 && __instance.id == 0) - { - return; - } - - if (Multiplayer.Session.LocalPlayer.IsHost) - { - // Assume storage is on the local planet, send to all clients in local star system who may have the factory loaded - Multiplayer.Session.Network.SendPacketToStar(packet, GameMain.localStar.id); - } - else - { - Multiplayer.Session.Network.SendPacket(packet); - } + // Assume storage is on the local planet, send to all clients in local star system who may have the factory loaded + Multiplayer.Session.Network.SendPacketToStar(packet, GameMain.localStar.id); + } + else + { + Multiplayer.Session.Network.SendPacket(packet); } } } diff --git a/NebulaPatcher/Patches/Dynamic/TrashContainer_Patch.cs b/NebulaPatcher/Patches/Dynamic/TrashContainer_Patch.cs index 16ffd6eb0..50e15ed9d 100644 --- a/NebulaPatcher/Patches/Dynamic/TrashContainer_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/TrashContainer_Patch.cs @@ -1,39 +1,45 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaModel.Packets.Trash; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(TrashContainer))] +public class TrashContainer_Patch { - [HarmonyPatch(typeof(TrashContainer))] - public class TrashContainer_Patch + [HarmonyPostfix] + [HarmonyPatch(nameof(TrashContainer.RemoveTrash))] + public static void RemoveTrash_Postfix(int index) { - [HarmonyPostfix] - [HarmonyPatch(nameof(TrashContainer.RemoveTrash))] - public static void RemoveTrash_Postfix(int index) + //Notify other that trash was removed + if (Multiplayer.IsActive && !Multiplayer.Session.Trashes.RemoveTrashFromOtherPlayers) { - //Notify other that trash was removed - if (Multiplayer.IsActive && !Multiplayer.Session.Trashes.RemoveTrashFromOtherPlayers) - { - Multiplayer.Session.Network.SendPacket(new TrashSystemTrashRemovedPacket(index)); - } + Multiplayer.Session.Network.SendPacket(new TrashSystemTrashRemovedPacket(index)); } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(TrashContainer.NewTrash))] - public static void NewTrash_Postfix(TrashContainer __instance, int __result, TrashObject trashObj, TrashData trashData) + [HarmonyPostfix] + [HarmonyPatch(nameof(TrashContainer.NewTrash))] + public static void NewTrash_Postfix(TrashContainer __instance, int __result, TrashObject trashObj, TrashData trashData) + { + //Notify other that trash was created + if (Multiplayer.IsActive && !Multiplayer.Session.Trashes.NewTrashFromOtherPlayers) + { + //Refresh trash to assign local planet Id and local position + GameMain.data.trashSystem.Gravity(ref trashData, GameMain.data.galaxy.astrosData, 0, 0, 0, + GameMain.data.localPlanet != null ? GameMain.data.localPlanet.id : 0, + GameMain.data.localPlanet != null ? GameMain.data.localPlanet.data : null); + Multiplayer.Session.Network.SendPacket(new TrashSystemNewTrashCreatedPacket(__result, trashObj, trashData, + Multiplayer.Session.LocalPlayer.Id, GameMain.mainPlayer.planetId)); + } + // Wait until WarningDataPacket to assign warningId + if (Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsClient) { - //Notify other that trash was created - if (Multiplayer.IsActive && !Multiplayer.Session.Trashes.NewTrashFromOtherPlayers) - { - //Refresh trash to assign local planet Id and local position - GameMain.data.trashSystem.Gravity(ref trashData, GameMain.data.galaxy.astrosData, 0, 0, 0, (GameMain.data.localPlanet != null) ? GameMain.data.localPlanet.id : 0, (GameMain.data.localPlanet != null) ? GameMain.data.localPlanet.data : null); - Multiplayer.Session.Network.SendPacket(new TrashSystemNewTrashCreatedPacket(__result, trashObj, trashData, Multiplayer.Session.LocalPlayer.Id, GameMain.mainPlayer.planetId)); - } - // Wait until WarningDataPacket to assign warningId - if (Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsClient) - { - __instance.trashDataPool[__result].warningId = -1; - } + __instance.trashDataPool[__result].warningId = -1; } } } diff --git a/NebulaPatcher/Patches/Dynamic/TrashSystem_Patch.cs b/NebulaPatcher/Patches/Dynamic/TrashSystem_Patch.cs index ffeb9315e..86b370ce5 100644 --- a/NebulaPatcher/Patches/Dynamic/TrashSystem_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/TrashSystem_Patch.cs @@ -1,21 +1,24 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaModel.Packets.Trash; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(TrashSystem))] +internal class TrashSystem_Patch { - [HarmonyPatch(typeof(TrashSystem))] - internal class TrashSystem_Patch + [HarmonyPostfix] + [HarmonyPatch(nameof(TrashSystem.ClearAllTrash))] + public static void ClearAllTrash_Postfix() { - [HarmonyPostfix] - [HarmonyPatch(nameof(TrashSystem.ClearAllTrash))] - public static void ClearAllTrash_Postfix() + //Send notification, that somebody clicked on "ClearAllTrash" + if (Multiplayer.IsActive && !Multiplayer.Session.Trashes.ClearAllTrashFromOtherPlayers) { - //Send notification, that somebody clicked on "ClearAllTrash" - if (Multiplayer.IsActive && !Multiplayer.Session.Trashes.ClearAllTrashFromOtherPlayers) - { - Multiplayer.Session.Network.SendPacket(new TrashSystemClearAllTrashPacket()); - } + Multiplayer.Session.Network.SendPacket(new TrashSystemClearAllTrashPacket()); } } } diff --git a/NebulaPatcher/Patches/Dynamic/UIAbnormalityTip.cs b/NebulaPatcher/Patches/Dynamic/UIAbnormalityTip.cs index 5b7cec495..e53fa30d1 100644 --- a/NebulaPatcher/Patches/Dynamic/UIAbnormalityTip.cs +++ b/NebulaPatcher/Patches/Dynamic/UIAbnormalityTip.cs @@ -1,21 +1,25 @@ -using HarmonyLib; +#region + +using System.Diagnostics.CodeAnalysis; +using HarmonyLib; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(UIAbnormalityTip))] +internal class UIAbnormalityTip_Patch { - [HarmonyPatch(typeof(UIAbnormalityTip))] - internal class UIAbnormalityTip_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(UIAbnormalityTip._OnOpen))] + [SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Original Function Name")] + public static void _OnOpen_Prefix(UIAbnormalityTip __instance) { - [HarmonyPrefix] - [HarmonyPatch(nameof(UIAbnormalityTip._OnOpen))] - [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Original Function Name")] - public static void _OnOpen_Prefix(UIAbnormalityTip __instance) + // Suppress runtime errror reports on client because client can't unlock achievements anyway in host's save + if (Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsClient) { - // Suppress runtime errror reports on client because client can't unlock achievements anyway in host's save - if (Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsClient) - { - __instance._Close(); - } + __instance._Close(); } } } diff --git a/NebulaPatcher/Patches/Dynamic/UIAssemblerWindow_Patch.cs b/NebulaPatcher/Patches/Dynamic/UIAssemblerWindow_Patch.cs index e892a5baf..593d59aeb 100644 --- a/NebulaPatcher/Patches/Dynamic/UIAssemblerWindow_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/UIAssemblerWindow_Patch.cs @@ -1,81 +1,92 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaModel.Packets.Factory.Assembler; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(UIAssemblerWindow))] +internal class UIAssemblerWindow_Patch { - [HarmonyPatch(typeof(UIAssemblerWindow))] - internal class UIAssemblerWindow_Patch + [HarmonyPostfix] + [HarmonyPatch(nameof(UIAssemblerWindow.OnRecipeResetClick))] + public static void OnRecipeResetClick_Postfix(UIAssemblerWindow __instance) { - [HarmonyPostfix] - [HarmonyPatch(nameof(UIAssemblerWindow.OnRecipeResetClick))] - public static void OnRecipeResetClick_Postfix(UIAssemblerWindow __instance) + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) - { - Multiplayer.Session.Network.SendPacketToLocalStar(new AssemblerRecipeEventPacket(GameMain.data.localPlanet.id, __instance.assemblerId, 0)); - } + Multiplayer.Session.Network.SendPacketToLocalStar(new AssemblerRecipeEventPacket(GameMain.data.localPlanet.id, + __instance.assemblerId, 0)); } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(UIAssemblerWindow.OnRecipePickerReturn))] - public static void OnRecipePickerReturn_Postfix(UIAssemblerWindow __instance, RecipeProto recipe) + [HarmonyPostfix] + [HarmonyPatch(nameof(UIAssemblerWindow.OnRecipePickerReturn))] + public static void OnRecipePickerReturn_Postfix(UIAssemblerWindow __instance, RecipeProto recipe) + { + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) - { - Multiplayer.Session.Network.SendPacketToLocalStar(new AssemblerRecipeEventPacket(GameMain.data.localPlanet.id, __instance.assemblerId, recipe.ID)); - } + Multiplayer.Session.Network.SendPacketToLocalStar(new AssemblerRecipeEventPacket(GameMain.data.localPlanet.id, + __instance.assemblerId, recipe.ID)); } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(UIAssemblerWindow.OnIncSwitchClick))] - public static void OnIncSwitchClick_Postfix(UIAssemblerWindow __instance) + [HarmonyPostfix] + [HarmonyPatch(nameof(UIAssemblerWindow.OnIncSwitchClick))] + public static void OnIncSwitchClick_Postfix(UIAssemblerWindow __instance) + { + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) - { - // Notify others about production switch - Multiplayer.Session.Network.SendPacketToLocalStar(new AssemblerRecipeEventPacket(GameMain.data.localPlanet.id, __instance.assemblerId, -1)); - } + // Notify others about production switch + Multiplayer.Session.Network.SendPacketToLocalStar(new AssemblerRecipeEventPacket(GameMain.data.localPlanet.id, + __instance.assemblerId, -1)); } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(UIAssemblerWindow.OnProductIcon0Click))] - public static void OnProductIcon0Click_Postfix(UIAssemblerWindow __instance) + [HarmonyPostfix] + [HarmonyPatch(nameof(UIAssemblerWindow.OnProductIcon0Click))] + public static void OnProductIcon0Click_Postfix(UIAssemblerWindow __instance) + { + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) - { - Multiplayer.Session.Network.SendPacketToLocalStar(new AssemblerUpdateProducesPacket(0, __instance.factorySystem.assemblerPool[__instance.assemblerId].produced[0], GameMain.data.localPlanet.id, __instance.assemblerId)); - } + Multiplayer.Session.Network.SendPacketToLocalStar(new AssemblerUpdateProducesPacket(0, + __instance.factorySystem.assemblerPool[__instance.assemblerId].produced[0], GameMain.data.localPlanet.id, + __instance.assemblerId)); } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(UIAssemblerWindow.OnProductIcon1Click))] - public static void OnProductIcon1Click_Postfix(UIAssemblerWindow __instance) + [HarmonyPostfix] + [HarmonyPatch(nameof(UIAssemblerWindow.OnProductIcon1Click))] + public static void OnProductIcon1Click_Postfix(UIAssemblerWindow __instance) + { + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) - { - Multiplayer.Session.Network.SendPacketToLocalStar(new AssemblerUpdateProducesPacket(1, __instance.factorySystem.assemblerPool[__instance.assemblerId].produced[1], GameMain.data.localPlanet.id, __instance.assemblerId)); - } + Multiplayer.Session.Network.SendPacketToLocalStar(new AssemblerUpdateProducesPacket(1, + __instance.factorySystem.assemblerPool[__instance.assemblerId].produced[1], GameMain.data.localPlanet.id, + __instance.assemblerId)); } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(UIAssemblerWindow.OnManualServingContentChange))] - public static void OnManualServingContentChange_Postfix(UIAssemblerWindow __instance) + [HarmonyPostfix] + [HarmonyPatch(nameof(UIAssemblerWindow.OnManualServingContentChange))] + public static void OnManualServingContentChange_Postfix(UIAssemblerWindow __instance) + { + if (!Multiplayer.IsActive) { - if (!Multiplayer.IsActive) - { - return; - } + return; + } - int[] served = new int[__instance.factorySystem.assemblerPool[__instance.assemblerId].served.Length]; - int[] incServed = new int[served.Length]; - StorageComponent assemblerStorage = __instance.servingStorage; - for (int i = 0; i < served.Length; i++) - { - served[i] = assemblerStorage.grids[i].count; - incServed[i] = assemblerStorage.grids[i].inc; - } - Multiplayer.Session.Network.SendPacketToLocalStar(new AssemblerUpdateStoragePacket(GameMain.data.localPlanet.id, __instance.assemblerId, served, incServed)); + var served = new int[__instance.factorySystem.assemblerPool[__instance.assemblerId].served.Length]; + var incServed = new int[served.Length]; + var assemblerStorage = __instance.servingStorage; + for (var i = 0; i < served.Length; i++) + { + served[i] = assemblerStorage.grids[i].count; + incServed[i] = assemblerStorage.grids[i].inc; } + Multiplayer.Session.Network.SendPacketToLocalStar(new AssemblerUpdateStoragePacket(GameMain.data.localPlanet.id, + __instance.assemblerId, served, incServed)); } -} \ No newline at end of file +} diff --git a/NebulaPatcher/Patches/Dynamic/UIAutoSave_Patch.cs b/NebulaPatcher/Patches/Dynamic/UIAutoSave_Patch.cs index 121823b45..f29f4c29f 100644 --- a/NebulaPatcher/Patches/Dynamic/UIAutoSave_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/UIAutoSave_Patch.cs @@ -1,35 +1,38 @@ -using HarmonyLib; +#region + +using System.Diagnostics.CodeAnalysis; +using HarmonyLib; using NebulaModel.Logger; using NebulaWorld; -using UnityEngine; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(UIAutoSave))] +internal class UIAutoSave_Patch { - [HarmonyPatch(typeof(UIAutoSave))] - internal class UIAutoSave_Patch + [HarmonyPostfix] + [HarmonyPatch(nameof(UIAutoSave._OnOpen))] + [SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Original Function Name")] + public static void _OnOpen_Postfix(UIAutoSave __instance) { - [HarmonyPostfix] - [HarmonyPatch(nameof(UIAutoSave._OnOpen))] - [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Original Function Name")] - public static void _OnOpen_Postfix(UIAutoSave __instance) + // Hide AutoSave failed message on clients, since client cannot save in multiplayer + var contentCanvas = __instance.contentCanvas; + if (contentCanvas == null) { - // Hide AutoSave failed message on clients, since client cannot save in multiplayer - CanvasGroup contentCanvas = __instance.contentCanvas; - if (contentCanvas == null) - { - return; - } - - contentCanvas.gameObject.SetActive(!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost); - Log.Warn($"UIAutoSave active: {contentCanvas.gameObject.activeSelf}"); + return; } - [HarmonyPrefix] - [HarmonyPatch(nameof(UIAutoSave._OnLateUpdate))] - [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Original Function Name")] - public static bool _OnLateUpdate_Prefix() - { - return !Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost; - } + contentCanvas.gameObject.SetActive(!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost); + Log.Warn($"UIAutoSave active: {contentCanvas.gameObject.activeSelf}"); + } + + [HarmonyPrefix] + [HarmonyPatch(nameof(UIAutoSave._OnLateUpdate))] + [SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Original Function Name")] + public static bool _OnLateUpdate_Prefix() + { + return !Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost; } } diff --git a/NebulaPatcher/Patches/Dynamic/UIBeltWindow_Patch.cs b/NebulaPatcher/Patches/Dynamic/UIBeltWindow_Patch.cs index 7ff875b4b..51878cbd8 100644 --- a/NebulaPatcher/Patches/Dynamic/UIBeltWindow_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/UIBeltWindow_Patch.cs @@ -1,21 +1,25 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaModel.Packets.Factory.Belt; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(UIBeltWindow))] +internal class UIBeltWindow_Patch { - [HarmonyPatch(typeof(UIBeltWindow))] - internal class UIBeltWindow_Patch + [HarmonyPostfix] + [HarmonyPatch(typeof(UIBeltWindow), nameof(UIBeltWindow.OnReverseButtonClick))] + public static void OnReverseButtonClick_Postfix(UIBeltWindow __instance) { - [HarmonyPostfix] - [HarmonyPatch(typeof(UIBeltWindow), nameof(UIBeltWindow.OnReverseButtonClick))] - public static void OnReverseButtonClick_Postfix(UIBeltWindow __instance) + // Notify others about belt direction reverse + if (Multiplayer.IsActive && !Multiplayer.Session.Factories.IsIncomingRequest.Value) { - // Notify others about belt direction reverse - if (Multiplayer.IsActive && !Multiplayer.Session.Factories.IsIncomingRequest.Value) - { - Multiplayer.Session.Network.SendPacketToLocalStar(new BeltReversePacket(__instance.beltId, __instance.factory.planetId)); - } + Multiplayer.Session.Network.SendPacketToLocalStar(new BeltReversePacket(__instance.beltId, + __instance.factory.planetId)); } } } diff --git a/NebulaPatcher/Patches/Dynamic/UIDEOverview_Patch.cs b/NebulaPatcher/Patches/Dynamic/UIDEOverview_Patch.cs index 7e0e2231c..6373ec56c 100644 --- a/NebulaPatcher/Patches/Dynamic/UIDEOverview_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/UIDEOverview_Patch.cs @@ -1,36 +1,41 @@ -using HarmonyLib; +#region + +using System.Diagnostics.CodeAnalysis; +using HarmonyLib; +using NebulaModel.Logger; using NebulaModel.Packets.GameHistory; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(UIDEOverview))] +internal class UIDEOverview_Patch { - [HarmonyPatch(typeof(UIDEOverview))] - internal class UIDEOverview_Patch + [HarmonyPostfix] + [HarmonyPatch(nameof(UIDEOverview._OnInit))] + [SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Original Function Name")] + public static void _OnInit_Postfix() { - [HarmonyPostfix] - [HarmonyPatch(nameof(UIDEOverview._OnInit))] - [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Original Function Name")] - public static void _OnInit_Postfix() - { - NebulaModel.Logger.Log.Debug("UIDEOverview._OnInit"); - UIRoot.instance.uiGame.dysonEditor.controlPanel.topFunction.pauseButton.button.interactable = !Multiplayer.IsActive; - } + Log.Debug("UIDEOverview._OnInit"); + UIRoot.instance.uiGame.dysonEditor.controlPanel.topFunction.pauseButton.button.interactable = !Multiplayer.IsActive; + } - [HarmonyPrefix] - [HarmonyPatch(nameof(UIDEOverview._OnUpdate))] - [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Original Function Name")] - public static void _OnUpdate_Prefix(UIDEOverview __instance) + [HarmonyPrefix] + [HarmonyPatch(nameof(UIDEOverview._OnUpdate))] + [SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Original Function Name")] + public static void _OnUpdate_Prefix(UIDEOverview __instance) + { + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) + if (__instance.autoConstructSwitch.isOn && !GameMain.data.history.HasFeatureKey(1100002)) + { + Multiplayer.Session.Network.SendPacket(new GameHistoryFeatureKeyPacket(1100002, true)); + } + else if (!__instance.autoConstructSwitch.isOn && GameMain.data.history.HasFeatureKey(1100002)) { - if (__instance.autoConstructSwitch.isOn && !GameMain.data.history.HasFeatureKey(1100002)) - { - Multiplayer.Session.Network.SendPacket(new GameHistoryFeatureKeyPacket(1100002, true)); - } - else if (!__instance.autoConstructSwitch.isOn && GameMain.data.history.HasFeatureKey(1100002)) - { - Multiplayer.Session.Network.SendPacket(new GameHistoryFeatureKeyPacket(1100002, false)); - } + Multiplayer.Session.Network.SendPacket(new GameHistoryFeatureKeyPacket(1100002, false)); } } } diff --git a/NebulaPatcher/Patches/Dynamic/UIDESphereInfo_Patch.cs b/NebulaPatcher/Patches/Dynamic/UIDESphereInfo_Patch.cs index 2529e63c8..4c8d2bf3d 100644 --- a/NebulaPatcher/Patches/Dynamic/UIDESphereInfo_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/UIDESphereInfo_Patch.cs @@ -1,47 +1,51 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(UIDESphereInfo))] +internal class UIDESphereInfo_Patch { - [HarmonyPatch(typeof(UIDESphereInfo))] - internal class UIDESphereInfo_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(UIDESphereInfo.CalculateSailLifeDistribution))] + public static bool CalculateSailLifeDistribution_Prefix(UIDESphereInfo __instance, int division, out float maxCount, + ref float[] __result) { - [HarmonyPrefix] - [HarmonyPatch(nameof(UIDESphereInfo.CalculateSailLifeDistribution))] - public static bool CalculateSailLifeDistribution_Prefix(UIDESphereInfo __instance, int division, out float maxCount, ref float[] __result) + maxCount = 0f; + if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) { - maxCount = 0f; - if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) - { - return true; - } + return true; + } - if (division <= 1 || __instance.dysonSphere.swarm == null) - { - __result = null; - return false; - } - ExpiryOrder[] expiryOrder = __instance.dysonSphere.swarm.expiryOrder; - long gameTick = GameMain.gameTick; - float[] array = new float[division]; - float gap = GameMain.history.solarSailLife * 60f / division; - for (int i = 0; i < expiryOrder.Length; i++) - { - if (expiryOrder[i].index != 0) - { - // Make sure index is not out of array - int index = (int)((expiryOrder[i].time - gameTick) / gap); - index = index >= 0 ? index : 0; - index = index < division ? index : division - 1; - array[index] += 1f; - } - } - for (int k = 0; k < array.Length; k++) + if (division <= 1 || __instance.dysonSphere.swarm == null) + { + __result = null; + return false; + } + var expiryOrder = __instance.dysonSphere.swarm.expiryOrder; + var gameTick = GameMain.gameTick; + var array = new float[division]; + var gap = GameMain.history.solarSailLife * 60f / division; + for (var i = 0; i < expiryOrder.Length; i++) + { + if (expiryOrder[i].index != 0) { - maxCount = ((maxCount > array[k]) ? maxCount : array[k]); + // Make sure index is not out of array + var index = (int)((expiryOrder[i].time - gameTick) / gap); + index = index >= 0 ? index : 0; + index = index < division ? index : division - 1; + array[index] += 1f; } - __result = array; - return false; } + for (var k = 0; k < array.Length; k++) + { + maxCount = maxCount > array[k] ? maxCount : array[k]; + } + __result = array; + return false; } } diff --git a/NebulaPatcher/Patches/Dynamic/UIDESwarmOrbitInfo.cs b/NebulaPatcher/Patches/Dynamic/UIDESwarmOrbitInfo.cs index 96fd6a13c..896bc7c42 100644 --- a/NebulaPatcher/Patches/Dynamic/UIDESwarmOrbitInfo.cs +++ b/NebulaPatcher/Patches/Dynamic/UIDESwarmOrbitInfo.cs @@ -1,47 +1,52 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(UIDESwarmOrbitInfo))] +internal class UIDESwarmOrbitInfo_Patch { - [HarmonyPatch(typeof(UIDESwarmOrbitInfo))] - internal class UIDESwarmOrbitInfo_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(UIDESwarmOrbitInfo.CalculateSailLifeDistribution))] + public static bool CalculateSailLifeDistribution_Prefix(UIDESwarmOrbitInfo __instance, int division, out float maxCount, + ref float[] __result) { - [HarmonyPrefix] - [HarmonyPatch(nameof(UIDESwarmOrbitInfo.CalculateSailLifeDistribution))] - public static bool CalculateSailLifeDistribution_Prefix(UIDESwarmOrbitInfo __instance, int division, out float maxCount, ref float[] __result) + maxCount = 0f; + if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) { - maxCount = 0f; - if (!Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost) - { - return true; - } + return true; + } - if (division <= 1 || __instance.swarm == null) - { - __result = null; - return false; - } - ExpiryOrder[] expiryOrder = __instance.swarm.expiryOrder; - long gameTick = GameMain.gameTick; - float[] array = new float[division]; - float gap = GameMain.history.solarSailLife * 60f / division; - for (int i = 0; i < expiryOrder.Length; i++) - { - if (expiryOrder[i].index != 0 && __instance.orbits.Contains((int)__instance.swarm.sailInfos[expiryOrder[i].index].orbit)) - { - // Make sure index is not out of array - int index = (int)((expiryOrder[i].time - gameTick) / gap); - index = index >= 0 ? index : 0; - index = index < division ? index : division - 1; - array[index] += 1f; - } - } - for (int k = 0; k < array.Length; k++) + if (division <= 1 || __instance.swarm == null) + { + __result = null; + return false; + } + var expiryOrder = __instance.swarm.expiryOrder; + var gameTick = GameMain.gameTick; + var array = new float[division]; + var gap = GameMain.history.solarSailLife * 60f / division; + for (var i = 0; i < expiryOrder.Length; i++) + { + if (expiryOrder[i].index != 0 && + __instance.orbits.Contains((int)__instance.swarm.sailInfos[expiryOrder[i].index].orbit)) { - maxCount = ((maxCount > array[k]) ? maxCount : array[k]); + // Make sure index is not out of array + var index = (int)((expiryOrder[i].time - gameTick) / gap); + index = index >= 0 ? index : 0; + index = index < division ? index : division - 1; + array[index] += 1f; } - __result = array; - return false; } + for (var k = 0; k < array.Length; k++) + { + maxCount = maxCount > array[k] ? maxCount : array[k]; + } + __result = array; + return false; } } diff --git a/NebulaPatcher/Patches/Dynamic/UIDEToolbox_Patch.cs b/NebulaPatcher/Patches/Dynamic/UIDEToolbox_Patch.cs index 87dafa1c3..930fbc8ca 100644 --- a/NebulaPatcher/Patches/Dynamic/UIDEToolbox_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/UIDEToolbox_Patch.cs @@ -1,34 +1,40 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaModel.Packets.Universe; using NebulaWorld; using UnityEngine; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(UIDEToolbox))] +internal class UIDEToolbox_Patch { - [HarmonyPatch(typeof(UIDEToolbox))] - internal class UIDEToolbox_Patch + [HarmonyPostfix] + [HarmonyPatch(nameof(UIDEToolbox.OnColorChange))] + public static void OnColorChange_Postfix(UIDEToolbox __instance, Color32 color) { - [HarmonyPostfix] - [HarmonyPatch(nameof(UIDEToolbox.OnColorChange))] - public static void OnColorChange_Postfix(UIDEToolbox __instance, Color32 color) + if (Multiplayer.IsActive && __instance.editor.selection.singleSelectedLayer != null) { - if (Multiplayer.IsActive && __instance.editor.selection.singleSelectedLayer != null) + var starIndex = __instance.editor.selection.viewStar.index; + var layerId = __instance.editor.selection.singleSelectedLayer.id; + color.a = byte.MaxValue; + foreach (var node in __instance.editor.selection.selectedNodes) + { + Multiplayer.Session.Network.SendPacket(new DysonSphereColorChangePacket(starIndex, layerId, color, + DysonSphereColorChangePacket.ComponentType.Node, node.id)); + } + foreach (var frame in __instance.editor.selection.selectedFrames) + { + Multiplayer.Session.Network.SendPacket(new DysonSphereColorChangePacket(starIndex, layerId, color, + DysonSphereColorChangePacket.ComponentType.Frame, frame.id)); + } + foreach (var shell in __instance.editor.selection.selectedShells) { - int starIndex = __instance.editor.selection.viewStar.index; - int layerId = __instance.editor.selection.singleSelectedLayer.id; - color.a = byte.MaxValue; - foreach (DysonNode node in __instance.editor.selection.selectedNodes) - { - Multiplayer.Session.Network.SendPacket(new DysonSphereColorChangePacket(starIndex, layerId, color, DysonSphereColorChangePacket.ComponentType.Node, node.id)); - } - foreach (DysonFrame frame in __instance.editor.selection.selectedFrames) - { - Multiplayer.Session.Network.SendPacket(new DysonSphereColorChangePacket(starIndex, layerId, color, DysonSphereColorChangePacket.ComponentType.Frame, frame.id)); - } - foreach (DysonShell shell in __instance.editor.selection.selectedShells) - { - Multiplayer.Session.Network.SendPacket(new DysonSphereColorChangePacket(starIndex, layerId, color, DysonSphereColorChangePacket.ComponentType.Shell, shell.id)); - } + Multiplayer.Session.Network.SendPacket(new DysonSphereColorChangePacket(starIndex, layerId, color, + DysonSphereColorChangePacket.ComponentType.Shell, shell.id)); } } } diff --git a/NebulaPatcher/Patches/Dynamic/UIDispenserWindow_Patch.cs b/NebulaPatcher/Patches/Dynamic/UIDispenserWindow_Patch.cs index b6a6a2a8b..16c5db6be 100644 --- a/NebulaPatcher/Patches/Dynamic/UIDispenserWindow_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/UIDispenserWindow_Patch.cs @@ -1,166 +1,172 @@ -using HarmonyLib; +#region + +using System; +using HarmonyLib; using NebulaModel.Packets.Logistics; using NebulaWorld; -using System; using UnityEngine; using UnityEngine.EventSystems; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(UIDispenserWindow))] +internal class UIDispenserWindow_Patch { - [HarmonyPatch(typeof(UIDispenserWindow))] - internal class UIDispenserWindow_Patch + [HarmonyPostfix] + [HarmonyPatch(nameof(UIDispenserWindow.OnCourierIconClick))] + public static void OnCourierIconClick_Postfix(UIDispenserWindow __instance) { - [HarmonyPostfix] - [HarmonyPatch(nameof(UIDispenserWindow.OnCourierIconClick))] - public static void OnCourierIconClick_Postfix(UIDispenserWindow __instance) + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) - { - DispenserComponent dispenserComponent = __instance.transport.dispenserPool[__instance.dispenserId]; - Multiplayer.Session.Network.SendPacketToLocalStar( - new DispenserSettingPacket(__instance.factory.planetId, - __instance.dispenserId, - EDispenserSettingEvent.SetCourierCount, - dispenserComponent.workCourierCount + dispenserComponent.idleCourierCount)); - } + var dispenserComponent = __instance.transport.dispenserPool[__instance.dispenserId]; + Multiplayer.Session.Network.SendPacketToLocalStar( + new DispenserSettingPacket(__instance.factory.planetId, + __instance.dispenserId, + EDispenserSettingEvent.SetCourierCount, + dispenserComponent.workCourierCount + dispenserComponent.idleCourierCount)); } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(UIDispenserWindow.OnCourierAutoReplenishButtonClick))] - public static void OnCourierAutoReplenishButtonClick_Postfix(UIDispenserWindow __instance) + [HarmonyPostfix] + [HarmonyPatch(nameof(UIDispenserWindow.OnCourierAutoReplenishButtonClick))] + public static void OnCourierAutoReplenishButtonClick_Postfix(UIDispenserWindow __instance) + { + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) - { - DispenserComponent dispenserComponent = __instance.transport.dispenserPool[__instance.dispenserId]; - Multiplayer.Session.Network.SendPacketToLocalStar( - new DispenserSettingPacket(__instance.factory.planetId, - __instance.dispenserId, - EDispenserSettingEvent.ToggleAutoReplenish, - dispenserComponent.courierAutoReplenish ? 1 : 0)); - } + var dispenserComponent = __instance.transport.dispenserPool[__instance.dispenserId]; + Multiplayer.Session.Network.SendPacketToLocalStar( + new DispenserSettingPacket(__instance.factory.planetId, + __instance.dispenserId, + EDispenserSettingEvent.ToggleAutoReplenish, + dispenserComponent.courierAutoReplenish ? 1 : 0)); } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(UIDispenserWindow.OnHoldupItemClick))] - public static void OnHoldupItemClick_Postfix(UIDispenserWindow __instance) + [HarmonyPostfix] + [HarmonyPatch(nameof(UIDispenserWindow.OnHoldupItemClick))] + public static void OnHoldupItemClick_Postfix(UIDispenserWindow __instance) + { + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) + var dispenserComponent = __instance.transport.dispenserPool[__instance.dispenserId]; + if (__instance.player.inhandItemId == 0 && __instance.player.inhandItemCount == 0) { - DispenserComponent dispenserComponent = __instance.transport.dispenserPool[__instance.dispenserId]; - if (__instance.player.inhandItemId == 0 && __instance.player.inhandItemCount == 0) - { - Multiplayer.Session.Network.SendPacketToLocalStar( - new DispenserStorePacket(__instance.factory.planetId, - in dispenserComponent)); - } + Multiplayer.Session.Network.SendPacketToLocalStar( + new DispenserStorePacket(__instance.factory.planetId, + in dispenserComponent)); } } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(UIDispenserWindow.OnMaxChargePowerSliderValueChange))] - public static void OnMaxChargePowerSliderValueChange_Postfix(UIDispenserWindow __instance, float value) + [HarmonyPostfix] + [HarmonyPatch(nameof(UIDispenserWindow.OnMaxChargePowerSliderValueChange))] + public static void OnMaxChargePowerSliderValueChange_Postfix(UIDispenserWindow __instance, float value) + { + if (Multiplayer.IsActive && !Multiplayer.Session.StationsUI.IsIncomingRequest.Value) { - if (Multiplayer.IsActive && !Multiplayer.Session.StationsUI.IsIncomingRequest.Value) - { - Multiplayer.Session.Network.SendPacketToLocalStar( - new DispenserSettingPacket(__instance.factory.planetId, - __instance.dispenserId, - EDispenserSettingEvent.SetMaxChargePower, - BitConverter.ToInt32(BitConverter.GetBytes(value), 0))); - } + Multiplayer.Session.Network.SendPacketToLocalStar( + new DispenserSettingPacket(__instance.factory.planetId, + __instance.dispenserId, + EDispenserSettingEvent.SetMaxChargePower, + BitConverter.ToInt32(BitConverter.GetBytes(value), 0))); } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(UIDispenserWindow.OnItemIconMouseDown))] - public static bool OnItemIconMouseDown_Prefix(UIDispenserWindow __instance, BaseEventData evt) + [HarmonyPrefix] + [HarmonyPatch(nameof(UIDispenserWindow.OnItemIconMouseDown))] + public static bool OnItemIconMouseDown_Prefix(UIDispenserWindow __instance, BaseEventData evt) + { + if (!Multiplayer.IsActive || __instance.dispenserId == 0 || __instance.factory == null) { - if (!Multiplayer.IsActive || __instance.dispenserId == 0 || __instance.factory == null) - { - return true; - } - DispenserComponent dispenserComponent = __instance.transport.dispenserPool[__instance.dispenserId]; - if (dispenserComponent == null || dispenserComponent.id != __instance.dispenserId) - { - return false; - } - PointerEventData pointerEventData = evt as PointerEventData; - if (pointerEventData == null) - { - return false; - } + return true; + } + var dispenserComponent = __instance.transport.dispenserPool[__instance.dispenserId]; + if (dispenserComponent == null || dispenserComponent.id != __instance.dispenserId) + { + return false; + } + var pointerEventData = evt as PointerEventData; + if (pointerEventData == null) + { + return false; + } - if (__instance.player.inhandItemId == 0) + if (__instance.player.inhandItemId == 0) + { + if (pointerEventData.button == PointerEventData.InputButton.Right) { - if (pointerEventData.button == PointerEventData.InputButton.Right) + __instance.CalculateStorageTotalCount(dispenserComponent, out var count, out var _); + if (count > 0) { - __instance.CalculateStorageTotalCount(dispenserComponent, out int count, out int _); - if (count > 0) - { - UIRoot.instance.uiGame.OpenGridSplit(dispenserComponent.filter, count, Input.mousePosition); - __instance.insplit = true; - return false; - } + UIRoot.instance.uiGame.OpenGridSplit(dispenserComponent.filter, count, Input.mousePosition); + __instance.insplit = true; + return false; } } - else if (__instance.player.inhandItemId == dispenserComponent.filter && dispenserComponent.filter > 0 && pointerEventData.button == PointerEventData.InputButton.Left) - { - int entityId = dispenserComponent.storage.bottomStorage.entityId; - int itemCount = __instance.factory.InsertIntoStorage(entityId, __instance.player.inhandItemId, __instance.player.inhandItemCount, __instance.player.inhandItemInc, out int handItemInc_Unsafe, false); + } + else if (__instance.player.inhandItemId == dispenserComponent.filter && dispenserComponent.filter > 0 && + pointerEventData.button == PointerEventData.InputButton.Left) + { + var entityId = dispenserComponent.storage.bottomStorage.entityId; + var itemCount = __instance.factory.InsertIntoStorage(entityId, __instance.player.inhandItemId, + __instance.player.inhandItemCount, __instance.player.inhandItemInc, out var handItemInc_Unsafe, false); - // Player put itemCount into storage, broadcast the change to all users - Multiplayer.Session.Network.SendPacketToLocalStar( - new DispenserAddTakePacket(__instance.factory.planetId, - entityId, - EDispenserAddTakeEvent.ManualAdd, - __instance.player.inhandItemId, itemCount, __instance.player.inhandItemInc)); + // Player put itemCount into storage, broadcast the change to all users + Multiplayer.Session.Network.SendPacketToLocalStar( + new DispenserAddTakePacket(__instance.factory.planetId, + entityId, + EDispenserAddTakeEvent.ManualAdd, + __instance.player.inhandItemId, itemCount, __instance.player.inhandItemInc)); - __instance.player.AddHandItemCount_Unsafe(-itemCount); - __instance.player.SetHandItemInc_Unsafe(handItemInc_Unsafe); - if (__instance.player.inhandItemCount <= 0) - { - __instance.player.SetHandItems(0, 0, 0); - } + __instance.player.AddHandItemCount_Unsafe(-itemCount); + __instance.player.SetHandItemInc_Unsafe(handItemInc_Unsafe); + if (__instance.player.inhandItemCount <= 0) + { + __instance.player.SetHandItems(0, 0); } + } + + return false; + } + [HarmonyPrefix] + [HarmonyPatch(nameof(UIDispenserWindow.OnItemIconMouseUp))] + public static bool OnItemIconMouseUp_Prefix(UIDispenserWindow __instance) + { + if (!Multiplayer.IsActive || __instance.dispenserId == 0 || __instance.factory == null) + { + return true; + } + var dispenserComponent = __instance.transport.dispenserPool[__instance.dispenserId]; + if (dispenserComponent == null || dispenserComponent.id != __instance.dispenserId) + { return false; } - [HarmonyPrefix] - [HarmonyPatch(nameof(UIDispenserWindow.OnItemIconMouseUp))] - public static bool OnItemIconMouseUp_Prefix(UIDispenserWindow __instance) + if (__instance.insplit) { - if (!Multiplayer.IsActive || __instance.dispenserId == 0 || __instance.factory == null) + var count = UIRoot.instance.uiGame.CloseGridSplit(); + if (__instance.player.inhandItemId == 0 && __instance.player.inhandItemCount == 0 && dispenserComponent.filter > 0) { - return true; - } - DispenserComponent dispenserComponent = __instance.transport.dispenserPool[__instance.dispenserId]; - if (dispenserComponent == null || dispenserComponent.id != __instance.dispenserId) - { - return false; - } + var entityId = dispenserComponent.storage.bottomStorage.entityId; + var handItemCount_Unsafe = __instance.factory.PickFromStorage(entityId, dispenserComponent.filter, count, + out var handItemInc_Unsafe); + __instance.player.SetHandItemId_Unsafe(dispenserComponent.filter); + __instance.player.SetHandItemCount_Unsafe(handItemCount_Unsafe); + __instance.player.SetHandItemInc_Unsafe(handItemInc_Unsafe); - if (__instance.insplit) - { - int count = UIRoot.instance.uiGame.CloseGridSplit(); - if (__instance.player.inhandItemId == 0 && __instance.player.inhandItemCount == 0 && dispenserComponent.filter > 0) - { - int entityId = dispenserComponent.storage.bottomStorage.entityId; - int handItemCount_Unsafe = __instance.factory.PickFromStorage(entityId, dispenserComponent.filter, count, out int handItemInc_Unsafe); - __instance.player.SetHandItemId_Unsafe(dispenserComponent.filter); - __instance.player.SetHandItemCount_Unsafe(handItemCount_Unsafe); - __instance.player.SetHandItemInc_Unsafe(handItemInc_Unsafe); - - // Player grab itemCount from storage, broadcast the change to all users - Multiplayer.Session.Network.SendPacketToLocalStar( - new DispenserAddTakePacket(__instance.factory.planetId, - entityId, - EDispenserAddTakeEvent.ManualTake, - __instance.player.inhandItemId, __instance.player.inhandItemCount, 0)); - } - __instance.insplit = false; + // Player grab itemCount from storage, broadcast the change to all users + Multiplayer.Session.Network.SendPacketToLocalStar( + new DispenserAddTakePacket(__instance.factory.planetId, + entityId, + EDispenserAddTakeEvent.ManualTake, + __instance.player.inhandItemId, __instance.player.inhandItemCount, 0)); } - - return false; + __instance.insplit = false; } + + return false; } } diff --git a/NebulaPatcher/Patches/Dynamic/UIDysonPaintingGrid_Patch.cs b/NebulaPatcher/Patches/Dynamic/UIDysonPaintingGrid_Patch.cs index f1bb725ad..903b28a08 100644 --- a/NebulaPatcher/Patches/Dynamic/UIDysonPaintingGrid_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/UIDysonPaintingGrid_Patch.cs @@ -1,24 +1,28 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaModel.Packets.Universe; using NebulaWorld; using UnityEngine; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(UIDysonPaintingGrid))] +internal class UIDysonPaintingGrid_Patch { - [HarmonyPatch(typeof(UIDysonPaintingGrid))] - internal class UIDysonPaintingGrid_Patch + [HarmonyPostfix] + [HarmonyPatch(nameof(UIDysonPaintingGrid.PaintCells))] + public static void PaintCells_Postfix(UIDysonPaintingGrid __instance, Color32 paint) { - [HarmonyPostfix] - [HarmonyPatch(nameof(UIDysonPaintingGrid.PaintCells))] - public static void PaintCells_Postfix(UIDysonPaintingGrid __instance, Color32 paint) + var layer = __instance.editor.selection.singleSelectedLayer; + if (Multiplayer.IsActive && __instance.cursorCells != null && layer != null) { - DysonSphereLayer layer = __instance.editor.selection.singleSelectedLayer; - if (Multiplayer.IsActive && __instance.cursorCells != null && layer != null) - { - float strength = __instance.editor.brush_paint.strength; - bool superBrightMode = __instance.editor.brush_paint.superBrightMode; - Multiplayer.Session.Network.SendPacket(new DysonSpherePaintCellsPacket(layer.starData.index, layer.id, paint, strength, superBrightMode, __instance.cursorCells, __instance.cellCount)); - } + var strength = __instance.editor.brush_paint.strength; + var superBrightMode = __instance.editor.brush_paint.superBrightMode; + Multiplayer.Session.Network.SendPacket(new DysonSpherePaintCellsPacket(layer.starData.index, layer.id, paint, + strength, superBrightMode, __instance.cursorCells, __instance.cellCount)); } } } diff --git a/NebulaPatcher/Patches/Dynamic/UIEjectorWindow_Patch.cs b/NebulaPatcher/Patches/Dynamic/UIEjectorWindow_Patch.cs index 88e94ca07..e9407eacf 100644 --- a/NebulaPatcher/Patches/Dynamic/UIEjectorWindow_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/UIEjectorWindow_Patch.cs @@ -1,60 +1,66 @@ -using HarmonyLib; +#region + +using System.Diagnostics.CodeAnalysis; +using HarmonyLib; using NebulaModel.Packets.Factory; using NebulaModel.Packets.Factory.Ejector; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(UIEjectorWindow))] +internal class UIEjectorWindow_Patch { - [HarmonyPatch(typeof(UIEjectorWindow))] - internal class UIEjectorWindow_Patch + private static bool boost; + + [HarmonyPostfix] + [HarmonyPatch(nameof(UIEjectorWindow.OnManualServingContentChange))] + public static void OnManualServingContentChange_Postfix(UIEjectorWindow __instance) { - [HarmonyPostfix] - [HarmonyPatch(nameof(UIEjectorWindow.OnManualServingContentChange))] - public static void OnManualServingContentChange_Postfix(UIEjectorWindow __instance) + //Notify about manual bullet inserting / withdrawing change + if (Multiplayer.IsActive) { - //Notify about manual bullet inserting / withdrawing change - if (Multiplayer.IsActive) - { - StorageComponent storage = __instance.servingStorage; - Multiplayer.Session.Network.SendPacketToLocalStar(new EjectorStorageUpdatePacket(__instance.ejectorId, storage.grids[0].count, storage.grids[0].inc, GameMain.localPlanet?.id ?? -1)); - } + var storage = __instance.servingStorage; + Multiplayer.Session.Network.SendPacketToLocalStar(new EjectorStorageUpdatePacket(__instance.ejectorId, + storage.grids[0].count, storage.grids[0].inc, GameMain.localPlanet?.id ?? -1)); } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(UIEjectorWindow.OnSetOrbit))] - public static void OnSetOrbit_Postfix(UIEjectorWindow __instance, int orbitId) + [HarmonyPostfix] + [HarmonyPatch(nameof(UIEjectorWindow.OnSetOrbit))] + public static void OnSetOrbit_Postfix(UIEjectorWindow __instance, int orbitId) + { + //Notify about target orbit change + if (Multiplayer.IsActive) { - //Notify about target orbit change - if (Multiplayer.IsActive) - { - Multiplayer.Session.Network.SendPacketToLocalStar(new EjectorOrbitUpdatePacket(__instance.ejectorId, orbitId, GameMain.localPlanet?.id ?? -1)); - } + Multiplayer.Session.Network.SendPacketToLocalStar(new EjectorOrbitUpdatePacket(__instance.ejectorId, orbitId, + GameMain.localPlanet?.id ?? -1)); } + } - static bool boost; - - [HarmonyPostfix] - [HarmonyPatch(nameof(UIEjectorWindow.OnEjectorIdChange))] - public static void OnEjectorIdChange_Postfix(UIEjectorWindow __instance) + [HarmonyPostfix] + [HarmonyPatch(nameof(UIEjectorWindow.OnEjectorIdChange))] + public static void OnEjectorIdChange_Postfix(UIEjectorWindow __instance) + { + if (Multiplayer.IsActive && __instance.active) { - if (Multiplayer.IsActive && __instance.active) - { - boost = __instance.boostSwitch.isOn; - } + boost = __instance.boostSwitch.isOn; } + } - [HarmonyPrefix] - [HarmonyPatch(nameof(UIEjectorWindow._OnUpdate))] - [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Original Function Name")] - public static void _OnUpdate_Prefix(UIEjectorWindow __instance) + [HarmonyPrefix] + [HarmonyPatch(nameof(UIEjectorWindow._OnUpdate))] + [SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Original Function Name")] + public static void _OnUpdate_Prefix(UIEjectorWindow __instance) + { + //Notify about boost change in sandbox mode + if (Multiplayer.IsActive && boost != __instance.boostSwitch.isOn) { - //Notify about boost change in sandbox mode - if (Multiplayer.IsActive && boost != __instance.boostSwitch.isOn) - { - boost = __instance.boostSwitch.isOn; - Multiplayer.Session.Network.SendPacketToLocalStar(new EntityBoostSwitchPacket - (GameMain.localPlanet?.id ?? -1, EBoostEntityType.Ejector, __instance.ejectorId, boost)); - } + boost = __instance.boostSwitch.isOn; + Multiplayer.Session.Network.SendPacketToLocalStar(new EntityBoostSwitchPacket + (GameMain.localPlanet?.id ?? -1, EBoostEntityType.Ejector, __instance.ejectorId, boost)); } } } diff --git a/NebulaPatcher/Patches/Dynamic/UIEscMenu_Patch.cs b/NebulaPatcher/Patches/Dynamic/UIEscMenu_Patch.cs index d13e1e313..b5b68bc05 100644 --- a/NebulaPatcher/Patches/Dynamic/UIEscMenu_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/UIEscMenu_Patch.cs @@ -1,70 +1,75 @@ -using HarmonyLib; +#region + +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using HarmonyLib; using NebulaModel.Packets.Players; using NebulaPatcher.Patches.Transpiler; using NebulaWorld; -using System.Threading; using UnityEngine; using UnityEngine.UI; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(UIEscMenu))] +internal class UIEscMenu_Patch { - [HarmonyPatch(typeof(UIEscMenu))] - internal class UIEscMenu_Patch + [HarmonyPrefix] + [HarmonyPatch(nameof(UIEscMenu._OnOpen))] + [SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Original Function Name")] + public static void _OnOpen_Prefix(UIEscMenu __instance) { - [HarmonyPrefix] - [HarmonyPatch(nameof(UIEscMenu._OnOpen))] - [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Original Function Name")] - public static void _OnOpen_Prefix(UIEscMenu __instance) - { - // Disable save game button if you are a client in a multiplayer session - Button saveGameWindowButton = __instance.button2; - SetButtonEnableState(saveGameWindowButton, !Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost); + // Disable save game button if you are a client in a multiplayer session + var saveGameWindowButton = __instance.button2; + SetButtonEnableState(saveGameWindowButton, !Multiplayer.IsActive || Multiplayer.Session.LocalPlayer.IsHost); - // Disable load game button if in a multiplayer session - Button loadGameWindowButton = __instance.button3; - SetButtonEnableState(loadGameWindowButton, !Multiplayer.IsActive); - } + // Disable load game button if in a multiplayer session + var loadGameWindowButton = __instance.button3; + SetButtonEnableState(loadGameWindowButton, !Multiplayer.IsActive); + } - [HarmonyPrefix] - [HarmonyPatch(nameof(UIEscMenu.OnButton5Click))] - public static void OnButton5Click_Prefix() - { - QuitGame(); - } + [HarmonyPrefix] + [HarmonyPatch(nameof(UIEscMenu.OnButton5Click))] + public static void OnButton5Click_Prefix() + { + QuitGame(); + } - [HarmonyPrefix] - [HarmonyPatch(nameof(UIEscMenu.OnButton6Click))] - public static void OnButton6Click_Prefix() - { - QuitGame(); - } + [HarmonyPrefix] + [HarmonyPatch(nameof(UIEscMenu.OnButton6Click))] + public static void OnButton6Click_Prefix() + { + QuitGame(); + } - public static void QuitGame() + public static void QuitGame() + { + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) + if (Multiplayer.Session.LocalPlayer.IsHost) { - if (Multiplayer.Session.LocalPlayer.IsHost) - { - // Because GameSave.SaveAsLastExit() is disable, we have to save game here to match the vanilla behavior. - GameSave.SaveCurrentGame(GameSave.LastExit); - } - else if (GameMain.mainPlayer?.mecha != null) - { - GameMain.mainPlayer.mecha.lab.ManageTakeback(); // Refund items to player package - Multiplayer.Session.Network.SendPacket(new PlayerMechaData(GameMain.mainPlayer)); - Thread.Sleep(100); // Wait for async packet send - } - PlanetFactory_Transpiler.CheckPopupPresent.Clear(); - PlanetFactory_Transpiler.FaultyVeins.Clear(); - Multiplayer.LeaveGame(); + // Because GameSave.SaveAsLastExit() is disable, we have to save game here to match the vanilla behavior. + GameSave.SaveCurrentGame(GameSave.LastExit); } + else if (GameMain.mainPlayer?.mecha != null) + { + GameMain.mainPlayer.mecha.lab.ManageTakeback(); // Refund items to player package + Multiplayer.Session.Network.SendPacket(new PlayerMechaData(GameMain.mainPlayer)); + Thread.Sleep(100); // Wait for async packet send + } + PlanetFactory_Transpiler.CheckPopupPresent.Clear(); + PlanetFactory_Transpiler.FaultyVeins.Clear(); + Multiplayer.LeaveGame(); } - private static void SetButtonEnableState(Button button, bool enable) - { - ColorBlock buttonColors = button.colors; - buttonColors.disabledColor = new Color(1f, 1f, 1f, 0.15f); - button.interactable = enable; - button.colors = buttonColors; - } + } + + private static void SetButtonEnableState(Button button, bool enable) + { + var buttonColors = button.colors; + buttonColors.disabledColor = new Color(1f, 1f, 1f, 0.15f); + button.interactable = enable; + button.colors = buttonColors; } } diff --git a/NebulaPatcher/Patches/Dynamic/UIFatalErrorTip_Patch.cs b/NebulaPatcher/Patches/Dynamic/UIFatalErrorTip_Patch.cs index 9aaef19f1..aa8ef7f4c 100644 --- a/NebulaPatcher/Patches/Dynamic/UIFatalErrorTip_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/UIFatalErrorTip_Patch.cs @@ -1,143 +1,151 @@ -using BepInEx.Bootstrap; +#region + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text; +using BepInEx.Bootstrap; using HarmonyLib; using NebulaModel.DataStructures; using NebulaModel.Logger; using NebulaModel.Packets.Players; using NebulaWorld; -using System; -using System.Text; using UnityEngine; using UnityEngine.UI; +using Object = UnityEngine.Object; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(UIFatalErrorTip))] +internal class UIFatalErrorTip_Patch { - [HarmonyPatch(typeof(UIFatalErrorTip))] - internal class UIFatalErrorTip_Patch + private static GameObject button; + + [HarmonyPostfix] + [HarmonyPatch(nameof(UIFatalErrorTip._OnRegEvent))] + [SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Original Function Name")] + public static void _OnRegEvent_Postfix() { - static GameObject button; + // If there is errer message before game begin, we will show to user here + if (Log.LastErrorMsg != null) + { + UIFatalErrorTip.instance.ShowError("[Nebula Error] " + Log.LastErrorMsg, ""); + Log.LastErrorMsg = null; + } + } - [HarmonyPostfix] - [HarmonyPatch(nameof(UIFatalErrorTip._OnRegEvent))] - [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Original Function Name")] - public static void _OnRegEvent_Postfix() + [HarmonyPostfix] + [HarmonyPatch(nameof(UIFatalErrorTip._OnOpen))] + [SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Original Function Name")] + public static void _OnOpen_Postfix(UIFatalErrorTip __instance) + { + try { - // If there is errer message before game begin, we will show to user here - if (Log.LastErrorMsg != null) + if (button == null) { - UIFatalErrorTip.instance.ShowError("[Nebula Error] " + Log.LastErrorMsg, ""); - Log.LastErrorMsg = null; + button = GameObject.Find( + "UI Root/Overlay Canvas/In Game/Windows/Dyson Sphere Editor/Dyson Editor Control Panel/hierarchy/layers/blueprint-group/blueprint-2/copy-button"); + var errorPanel = GameObject.Find("UI Root/Overlay Canvas/Fatal Error/errored-panel/"); + errorPanel.transform.Find("tip-text-0").GetComponent().text = Title(); + Object.Destroy(errorPanel.transform.Find("tip-text-0").GetComponent()); + errorPanel.transform.Find("tip-text-1").GetComponent().text = Title(); + Object.Destroy(errorPanel.transform.Find("tip-text-1").GetComponent()); + button = Object.Instantiate(button, errorPanel.transform); + button.name = "Copy & Close button"; + button.transform.localPosition = + errorPanel.transform.Find("icon").localPosition + new Vector3(30, -35, 0); //-885 -30 //-855 -60 + button.GetComponent().color = new Color(0.3113f, 0f, 0.0097f, 0.6f); + button.GetComponent().BindOnClickSafe(OnClick); + ref var tips = ref button.GetComponent().tips; + tips.tipTitle = "Copy & Close Error"; + tips.tipText = "Copy the message to clipboard and close error."; + tips.corner = 1; } - } - [HarmonyPostfix] - [HarmonyPatch(nameof(UIFatalErrorTip._OnOpen))] - [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Original Function Name")] - public static void _OnOpen_Postfix(UIFatalErrorTip __instance) + DedicatedServerReportError(); + } + catch (Exception e) { - try - { - if (button == null) - { - button = GameObject.Find("UI Root/Overlay Canvas/In Game/Windows/Dyson Sphere Editor/Dyson Editor Control Panel/hierarchy/layers/blueprint-group/blueprint-2/copy-button"); - GameObject errorPanel = GameObject.Find("UI Root/Overlay Canvas/Fatal Error/errored-panel/"); - errorPanel.transform.Find("tip-text-0").GetComponent().text = Title(); - GameObject.Destroy(errorPanel.transform.Find("tip-text-0").GetComponent()); - errorPanel.transform.Find("tip-text-1").GetComponent().text = Title(); - GameObject.Destroy(errorPanel.transform.Find("tip-text-1").GetComponent()); - button = GameObject.Instantiate(button, errorPanel.transform); - button.name = "Copy & Close button"; - button.transform.localPosition = errorPanel.transform.Find("icon").localPosition + new Vector3(30, -35, 0); //-885 -30 //-855 -60 - button.GetComponent().color = new Color(0.3113f, 0f, 0.0097f, 0.6f); - button.GetComponent().BindOnClickSafe(OnClick); - ref UIButton.TipSettings tips = ref button.GetComponent().tips; - tips.tipTitle = "Copy & Close Error"; - tips.tipText = "Copy the message to clipboard and close error."; - tips.corner = 1; - } + Log.Warn($"UIFatalErrorTip button did not patch! {e}"); + } + } - DedicatedServerReportError(); - } - catch (Exception e) - { - Log.Warn($"UIFatalErrorTip button did not patch! {e}"); - } + private static void DedicatedServerReportError() + { + // OnOpen only run once for the first error report + if (Multiplayer.IsDedicated && Multiplayer.IsActive) + { + var log = "Server report an error: \n" + UIFatalErrorTip.instance.errorLogText.text; + Log.Warn(log); + Multiplayer.Session.Network.SendPacket(new NewChatMessagePacket(ChatMessageType.SystemWarnMessage, log, + DateTime.Now, "")); } + } - private static void DedicatedServerReportError() + private static string Title() + { + var stringBuilder = new StringBuilder(); + stringBuilder.Append("An error has occurred! Game version "); + stringBuilder.Append(GameConfig.gameVersion.ToString()); + stringBuilder.Append('.'); + stringBuilder.Append(GameConfig.gameVersion.Build); + if (Multiplayer.IsActive) { - // OnOpen only run once for the first error report - if (Multiplayer.IsDedicated && Multiplayer.IsActive) - { - string log = "Server report an error: \n" + UIFatalErrorTip.instance.errorLogText.text; - Log.Warn(log); - Multiplayer.Session.Network.SendPacket(new NewChatMessagePacket(ChatMessageType.SystemWarnMessage, log, DateTime.Now, "")); - } + stringBuilder.Append(Multiplayer.Session.LocalPlayer.IsHost ? " (Host)" : " (Client)"); + } + stringBuilder.AppendLine(); + stringBuilder.Append(Chainloader.PluginInfos.Values.Count + " Mods used: "); + foreach (var pluginInfo in Chainloader.PluginInfos.Values) + { + stringBuilder.Append('['); + stringBuilder.Append(pluginInfo.Metadata.Name); + stringBuilder.Append(pluginInfo.Metadata.Version); + stringBuilder.Append("] "); } + return stringBuilder.ToString(); + } - private static string Title() + private static void OnClick(int id) + { + var stringBuilder = new StringBuilder(); + stringBuilder.AppendLine("```ini"); + stringBuilder.AppendLine(Title()); + var subs = UIFatalErrorTip.instance.errorLogText.text.Split('\n', '\r'); + foreach (var str in subs) { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.Append("An error has occurred! Game version "); - stringBuilder.Append(GameConfig.gameVersion.ToString()); - stringBuilder.Append('.'); - stringBuilder.Append(GameConfig.gameVersion.Build); - if (Multiplayer.IsActive) + if (string.IsNullOrEmpty(str)) { - stringBuilder.Append(Multiplayer.Session.LocalPlayer.IsHost ? " (Host)" : " (Client)"); + continue; } - stringBuilder.AppendLine(); - stringBuilder.Append(Chainloader.PluginInfos.Values.Count + " Mods used: "); - foreach (BepInEx.PluginInfo pluginInfo in Chainloader.PluginInfos.Values) + + // Nebula only: skip the message after PacketProcessor + if (str.StartsWith("NebulaModel.Packets.PacketProcessor")) { - stringBuilder.Append('['); - stringBuilder.Append(pluginInfo.Metadata.Name); - stringBuilder.Append(pluginInfo.Metadata.Version); - stringBuilder.Append("] "); + break; } - return stringBuilder.ToString(); - } - private static void OnClick(int id) - { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.AppendLine("```ini"); - stringBuilder.AppendLine(Title()); - string[] subs = UIFatalErrorTip.instance.errorLogText.text.Split('\n', '\r'); - foreach (string str in subs) + // Remove hash string + var start = str.LastIndexOf(" <"); + var end = str.LastIndexOf(">:"); + if (start != -1 && end > start) { - if (string.IsNullOrEmpty(str)) - { - continue; - } - - // Nebula only: skip the message after PacketProcessor - if (str.StartsWith("NebulaModel.Packets.PacketProcessor")) - { - break; - } - - // Remove hash string - int start = str.LastIndexOf(" <"); - int end = str.LastIndexOf(">:"); - if (start != -1 && end > start) - { - stringBuilder.AppendLine(str.Remove(start, end - start + 2)); - } - else - { - stringBuilder.AppendLine(str); - } + stringBuilder.AppendLine(str.Remove(start, end - start + 2)); + } + else + { + stringBuilder.AppendLine(str); } - // Apply format for ini code style - stringBuilder.Replace(" (at", ";("); - stringBuilder.Replace(" inIL_", " ;IL_"); - stringBuilder.AppendLine("```"); - - // Copy string to clipboard - GUIUtility.systemCopyBuffer = stringBuilder.ToString(); - UIFatalErrorTip.ClearError(); - GameObject.Destroy(button); - button = null; } + // Apply format for ini code style + stringBuilder.Replace(" (at", ";("); + stringBuilder.Replace(" inIL_", " ;IL_"); + stringBuilder.AppendLine("```"); + + // Copy string to clipboard + GUIUtility.systemCopyBuffer = stringBuilder.ToString(); + UIFatalErrorTip.ClearError(); + Object.Destroy(button); + button = null; } } diff --git a/NebulaPatcher/Patches/Dynamic/UIFractionatorWindow_Patch.cs b/NebulaPatcher/Patches/Dynamic/UIFractionatorWindow_Patch.cs index 18fc2b9cb..2016db03f 100644 --- a/NebulaPatcher/Patches/Dynamic/UIFractionatorWindow_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/UIFractionatorWindow_Patch.cs @@ -1,21 +1,25 @@ -using HarmonyLib; +#region + +using HarmonyLib; using NebulaModel.Packets.Factory.Fractionator; using NebulaWorld; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(UIFractionatorWindow))] +internal class UIFractionatorWindow_Patch { - [HarmonyPatch(typeof(UIFractionatorWindow))] - internal class UIFractionatorWindow_Patch + [HarmonyPostfix] + [HarmonyPatch(nameof(UIFractionatorWindow.OnProductUIButtonClick))] + public static void OnTakeBackPointerUp_Postfix(UIFractionatorWindow __instance) { - [HarmonyPostfix] - [HarmonyPatch(nameof(UIFractionatorWindow.OnProductUIButtonClick))] - public static void OnTakeBackPointerUp_Postfix(UIFractionatorWindow __instance) + if (Multiplayer.IsActive) { - if (Multiplayer.IsActive) - { - FractionatorComponent fractionator = __instance.factorySystem.fractionatorPool[__instance.fractionatorId]; - Multiplayer.Session.Network.SendPacketToLocalStar(new FractionatorStorageUpdatePacket(in fractionator, __instance.factory.planetId)); - } + var fractionator = __instance.factorySystem.fractionatorPool[__instance.fractionatorId]; + Multiplayer.Session.Network.SendPacketToLocalStar( + new FractionatorStorageUpdatePacket(in fractionator, __instance.factory.planetId)); } } } diff --git a/NebulaPatcher/Patches/Dynamic/UIGalaxySelect_Patch.cs b/NebulaPatcher/Patches/Dynamic/UIGalaxySelect_Patch.cs index 74852b0ff..c454122db 100644 --- a/NebulaPatcher/Patches/Dynamic/UIGalaxySelect_Patch.cs +++ b/NebulaPatcher/Patches/Dynamic/UIGalaxySelect_Patch.cs @@ -1,206 +1,220 @@ -using HarmonyLib; -using NebulaAPI; +#region + +using System.Diagnostics.CodeAnalysis; +using HarmonyLib; using NebulaModel; using NebulaModel.Logger; using NebulaModel.Packets.Session; using NebulaPatcher.Patches.Transpilers; using NebulaWorld; -using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; -namespace NebulaPatcher.Patches.Dynamic +#endregion + +namespace NebulaPatcher.Patches.Dynamic; + +[HarmonyPatch(typeof(UIGalaxySelect))] +internal class UIGalaxySelect_Patch { - [HarmonyPatch(typeof(UIGalaxySelect))] - internal class UIGalaxySelect_Patch - { - private static int MainMenuStarID = -1; + private static int MainMenuStarID = -1; - [HarmonyPostfix] - [HarmonyPatch(nameof(UIGalaxySelect._OnOpen))] - [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Original Function Name")] - public static void _OnOpen_Postfix(UIGalaxySelect __instance) + [HarmonyPostfix] + [HarmonyPatch(nameof(UIGalaxySelect._OnOpen))] + [SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Original Function Name")] + public static void _OnOpen_Postfix(UIGalaxySelect __instance) + { + if (Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsClient) { - if(Multiplayer.IsActive && Multiplayer.Session.LocalPlayer.IsClient) - { - RectTransform galaxySelectRect = __instance.gameObject.GetComponent(); - - galaxySelectRect.Find("star-count").gameObject.SetActive(false); - galaxySelectRect.Find("resource-multiplier").gameObject.SetActive(false); - galaxySelectRect.Find("galaxy-seed").GetComponentInChildren().enabled = false; - galaxySelectRect.Find("random-button").gameObject.SetActive(false); - galaxySelectRect.Find("property-multiplier").gameObject.SetActive(false); - galaxySelectRect.Find("seed-key").gameObject.SetActive(false); - galaxySelectRect.Find("sandbox-mode").gameObject.SetActive(false); - } - if (Multiplayer.IsActive) + var galaxySelectRect = __instance.gameObject.GetComponent(); + + galaxySelectRect.Find("star-count").gameObject.SetActive(false); + galaxySelectRect.Find("resource-multiplier").gameObject.SetActive(false); + galaxySelectRect.Find("galaxy-seed").GetComponentInChildren().enabled = false; + galaxySelectRect.Find("random-button").gameObject.SetActive(false); + galaxySelectRect.Find("property-multiplier").gameObject.SetActive(false); + galaxySelectRect.Find("seed-key").gameObject.SetActive(false); + galaxySelectRect.Find("sandbox-mode").gameObject.SetActive(false); + } + if (Multiplayer.IsActive) + { + // show lobby hints if needed + if (Config.Options.ShowLobbyHints) { - // show lobby hints if needed - if (Config.Options.ShowLobbyHints) + string message; + if ("Nebula_LobbyMessage".Translate() != "Nebula_LobbyMessage") // Translation exists { - string message; - if ("Nebula_LobbyMessage".Translate() != "Nebula_LobbyMessage") // Translation exists - message = "Nebula_LobbyMessage".Translate(); - else - message = "We changed the start of a new multiplayer game a bit and want to give you a quick overview of the new feature.\n\n" + + message = "Nebula_LobbyMessage".Translate(); + } + else + { + message = + "We changed the start of a new multiplayer game a bit and want to give you a quick overview of the new feature.\n\n" + "Clients can now join while the host is in the galaxy selection screen, and they will also land there if it is their first time connecting to the currently hosted save.\n\n" + "You can now click on any star to bring up the solar system preview. From there you can click on any planet to bring up its details.\n" + "Note that when using GalacticScale 2 this process can take a bit longer.\n\n" + "By clicking a planet while having its detail panel open you will set it as your birth planet.\n" + "By clicking into outer space you will go one detail level up. Scroll to zoom in/out. Press Alt to see star names.\n\n" + "Alt + ~ can open in-game chat. We hope you enjoy this new feature!"; - - InGamePopup.ShowInfo("The Lobby".Translate(), - message, - "Okay, cool :)", - CloseLobbyInfo); } - // prepare PlanetModelingManager for the use of its compute thread as we need that for the planet details view in the lobby - PlanetModelingManager.PrepareWorks(); - // store current star id because entering the solar system details view messes up the main menu background system. - if(MainMenuStarID == -1) - { - MainMenuStarID = GameMain.localStar.id; - } - Button button = GameObject.Find("UI Root/Overlay Canvas/Galaxy Select/start-button").GetComponent