From 77c92887ad31338d407c7a8c2f71d2b6551cf58c Mon Sep 17 00:00:00 2001 From: Mister_Nebula <41904486+misternebula@users.noreply.github.com> Date: Mon, 14 Dec 2020 21:58:00 +0000 Subject: [PATCH 01/10] cleanup --- QuantumUNET/Components/QSBNetworkAnimator.cs | 51 ++- QuantumUNET/Components/QSBNetworkIdentity.cs | 58 +-- .../Components/QSBNetworkManagerHUD.cs | 5 +- .../Components/QSBNetworkManagerUNET.cs | 47 +- QuantumUNET/Components/QSBNetworkTransform.cs | 91 +--- QuantumUNET/Messages/QSBErrorMessage.cs | 10 +- QuantumUNET/Messages/QSBMsgType.cs | 2 +- QuantumUNET/Messages/QSBNetworkMessage.cs | 5 +- .../Messages/QSBObjectDestroyMessage.cs | 10 +- .../Messages/QSBObjectSpawnFinishedMessage.cs | 10 +- QuantumUNET/Messages/QSBPeerInfoMessage.cs | 48 +- .../Messages/QSBRemovePlayerMessage.cs | 10 +- QuantumUNET/Messages/QSBStringMessage.cs | 12 +- QuantumUNET/QSBChannelPacket.cs | 40 +- QuantumUNET/QSBClientScene.cs | 64 +-- QuantumUNET/QSBLocalClient.cs | 14 +- QuantumUNET/QSBNetBuffer.cs | 124 +++--- QuantumUNET/QSBNetworkBehaviour.cs | 4 +- QuantumUNET/QSBNetworkCRC.cs | 51 +-- QuantumUNET/QSBNetworkClient.cs | 322 +++++--------- QuantumUNET/QSBNetworkConnection.cs | 25 +- QuantumUNET/QSBNetworkScene.cs | 24 +- QuantumUNET/QSBNetworkServer.cs | 309 ++++--------- QuantumUNET/QSBNetworkServerSimple.cs | 332 +++++--------- QuantumUNET/QSBNetworkWriter.cs | 414 ++++++++---------- QuantumUNET/QSBULocalConnectionToServer.cs | 20 +- 26 files changed, 726 insertions(+), 1376 deletions(-) diff --git a/QuantumUNET/Components/QSBNetworkAnimator.cs b/QuantumUNET/Components/QSBNetworkAnimator.cs index 4cfacf72..c124f646 100644 --- a/QuantumUNET/Components/QSBNetworkAnimator.cs +++ b/QuantumUNET/Components/QSBNetworkAnimator.cs @@ -32,22 +32,22 @@ namespace QuantumUNET.Components public void SetParameterAutoSend(int index, bool value) { if (value) + { m_ParameterSendBits |= (uint)(1 << index); + } else + { m_ParameterSendBits &= (uint)~(1 << index); + } } - public bool GetParameterAutoSend(int index) - { - return ((int)m_ParameterSendBits & 1 << index) != 0; - } + public bool GetParameterAutoSend(int index) => + ((int)m_ParameterSendBits & (1 << index)) != 0; - public override void OnStartAuthority() - { + public override void OnStartAuthority() => m_ParameterWriter = new QSBNetworkWriter(); - } - private void FixedUpdate() + public void FixedUpdate() { if (m_ParameterWriter == null) { @@ -134,7 +134,10 @@ namespace QuantumUNET.Components else { if (!IsServer || LocalPlayerAuthority) + { return; + } + QSBNetworkServer.SendToReady(gameObject, 41, parametersMessage); } } @@ -161,14 +164,11 @@ namespace QuantumUNET.Components ReadParameters(reader, true); } - internal void HandleAnimTriggerMsg(int hash) - { - m_Animator.SetTrigger(hash); - } + internal void HandleAnimTriggerMsg(int hash) => m_Animator.SetTrigger(hash); private void WriteParameters(QSBNetworkWriter writer, bool autoSend) { - for (int index = 0; index < m_Animator.parameters.Length; ++index) + for (var index = 0; index < m_Animator.parameters.Length; ++index) { if (!autoSend || GetParameterAutoSend(index)) { @@ -193,7 +193,7 @@ namespace QuantumUNET.Components private void ReadParameters(QSBNetworkReader reader, bool autoSend) { - for (int index = 0; index < m_Animator.parameters.Length; ++index) + for (var index = 0; index < m_Animator.parameters.Length; ++index) { if (!autoSend || GetParameterAutoSend(index)) { @@ -257,10 +257,7 @@ namespace QuantumUNET.Components m_Animator.Play(stateNameHash, 0, normalizedTime); } - public void SetTrigger(string triggerName) - { - SetTrigger(Animator.StringToHash(triggerName)); - } + public void SetTrigger(string triggerName) => SetTrigger(Animator.StringToHash(triggerName)); public void SetTrigger(int hash) { @@ -338,10 +335,16 @@ namespace QuantumUNET.Components netMsg.ReadMessage(AnimationMessage); var localObject = QSBClientScene.FindLocalObject(AnimationMessage.netId); if (localObject == null) + { return; + } + var component = localObject.GetComponent(); if (component == null) + { return; + } + var reader = new QSBNetworkReader(AnimationMessage.parameters); component.HandleAnimMsg(AnimationMessage, reader); } @@ -351,10 +354,16 @@ namespace QuantumUNET.Components netMsg.ReadMessage(ParametersMessage); var localObject = QSBClientScene.FindLocalObject(ParametersMessage.netId); if (localObject == null) + { return; + } + var component = localObject.GetComponent(); if (component == null) + { return; + } + var reader = new QSBNetworkReader(ParametersMessage.parameters); component.HandleAnimParamsMsg(ParametersMessage, reader); } @@ -364,10 +373,16 @@ namespace QuantumUNET.Components netMsg.ReadMessage(TriggersMessage); var localObject = QSBClientScene.FindLocalObject(TriggersMessage.netId); if (localObject == null) + { return; + } + var component = localObject.GetComponent(); if (component == null) + { return; + } + component.HandleAnimTriggerMsg(TriggersMessage.hash); } } diff --git a/QuantumUNET/Components/QSBNetworkIdentity.cs b/QuantumUNET/Components/QSBNetworkIdentity.cs index 28324cc4..c6b2860f 100644 --- a/QuantumUNET/Components/QSBNetworkIdentity.cs +++ b/QuantumUNET/Components/QSBNetworkIdentity.cs @@ -132,7 +132,7 @@ namespace QuantumUNET.Components { if (m_NetworkBehaviours == null) { - m_NetworkBehaviours = base.GetComponents(); + m_NetworkBehaviours = GetComponents(); } } @@ -179,11 +179,11 @@ namespace QuantumUNET.Components } } - private void OnDestroy() + public void OnDestroy() { if (m_IsServer && QSBNetworkServer.active) { - QSBNetworkServer.Destroy(base.gameObject); + QSBNetworkServer.Destroy(gameObject); } } @@ -233,7 +233,7 @@ namespace QuantumUNET.Components } if (QSBNetworkClient.active && QSBNetworkServer.localClientActive) { - QSBClientScene.SetLocalObject(NetId, base.gameObject); + QSBClientScene.SetLocalObject(NetId, gameObject); OnStartClient(); } if (HasAuthority) @@ -253,7 +253,7 @@ namespace QuantumUNET.Components Debug.Log(string.Concat(new object[] { "OnStartClient ", - base.gameObject, + gameObject, " GUID:", NetId, " localPlayerAuthority:", @@ -355,7 +355,7 @@ namespace QuantumUNET.Components { if (!LocalPlayerAuthority) { - Debug.LogError("HandleClientAuthority " + base.gameObject + " does not have localPlayerAuthority"); + Debug.LogError("HandleClientAuthority " + gameObject + " does not have localPlayerAuthority"); } else { @@ -384,7 +384,7 @@ namespace QuantumUNET.Components "Found no behaviour for incoming [", cmdHashHandlerName, "] on ", - base.gameObject, + gameObject, ", the server and client should have the same NetworkBehaviour instances [netId=", NetId, "]." @@ -402,7 +402,7 @@ namespace QuantumUNET.Components internal void HandleSyncEvent(int cmdHash, QSBNetworkReader reader) { - if (base.gameObject == null) + if (gameObject == null) { var cmdHashHandlerName = QSBNetworkBehaviour.GetCmdHashHandlerName(cmdHash); Debug.LogWarning(string.Concat(new object[] @@ -422,7 +422,7 @@ namespace QuantumUNET.Components "Found no receiver for incoming [", cmdHashHandlerName2, "] on ", - base.gameObject, + gameObject, ", the server and client should have the same NetworkBehaviour instances [netId=", NetId, "]." @@ -448,7 +448,7 @@ namespace QuantumUNET.Components internal void HandleSyncList(int cmdHash, QSBNetworkReader reader) { - if (base.gameObject == null) + if (gameObject == null) { var cmdHashHandlerName = QSBNetworkBehaviour.GetCmdHashHandlerName(cmdHash); Debug.LogWarning(string.Concat(new object[] @@ -468,7 +468,7 @@ namespace QuantumUNET.Components "Found no receiver for incoming [", cmdHashHandlerName2, "] on ", - base.gameObject, + gameObject, ", the server and client should have the same NetworkBehaviour instances [netId=", NetId, "]." @@ -494,7 +494,7 @@ namespace QuantumUNET.Components internal void HandleCommand(int cmdHash, QSBNetworkReader reader) { - if (base.gameObject == null) + if (gameObject == null) { var cmdHashHandlerName = QSBNetworkBehaviour.GetCmdHashHandlerName(cmdHash); Debug.LogWarning(string.Concat(new object[] @@ -514,7 +514,7 @@ namespace QuantumUNET.Components "Found no receiver for incoming [", cmdHashHandlerName2, "] on ", - base.gameObject, + gameObject, ", the server and client should have the same NetworkBehaviour instances [netId=", NetId, "]." @@ -540,7 +540,7 @@ namespace QuantumUNET.Components internal void HandleRPC(int cmdHash, QSBNetworkReader reader) { - if (base.gameObject == null) + if (gameObject == null) { var cmdHashHandlerName = QSBNetworkBehaviour.GetCmdHashHandlerName(cmdHash); Debug.LogWarning(string.Concat(new object[] @@ -560,7 +560,7 @@ namespace QuantumUNET.Components "Found no receiver for incoming [", cmdHashHandlerName2, "] on ", - base.gameObject, + gameObject, ", the server and client should have the same NetworkBehaviour instances [netId=", NetId, "]." @@ -627,7 +627,7 @@ namespace QuantumUNET.Components Debug.LogWarning(string.Concat(new object[] { "Large state update of ", - (int)(s_UpdateWriter.Position - position), + s_UpdateWriter.Position - position, " bytes for netId:", NetId, " from script:", @@ -639,7 +639,7 @@ namespace QuantumUNET.Components if (flag) { s_UpdateWriter.FinishMessage(); - QSBNetworkServer.SendWriterToReady(base.gameObject, s_UpdateWriter, j); + QSBNetworkServer.SendWriterToReady(gameObject, s_UpdateWriter, j); } } IL_197: @@ -654,7 +654,7 @@ namespace QuantumUNET.Components { if (initialState && m_NetworkBehaviours == null) { - m_NetworkBehaviours = base.GetComponents(); + m_NetworkBehaviours = GetComponents(); } for (var i = 0; i < m_NetworkBehaviours.Length; i++) { @@ -668,7 +668,7 @@ namespace QuantumUNET.Components ModConsole.OwmlConsole.WriteLine($"SetLocalPlayer {localPlayerControllerId}"); IsLocalPlayer = true; PlayerControllerId = localPlayerControllerId; - var hasAuthority = this.HasAuthority; + var hasAuthority = HasAuthority; if (LocalPlayerAuthority) { HasAuthority = true; @@ -723,7 +723,7 @@ namespace QuantumUNET.Components { if (m_Observers == null) { - Debug.LogError("AddObserver for " + base.gameObject + " observer list is null"); + Debug.LogError("AddObserver for " + gameObject + " observer list is null"); } else if (m_ObserverConnections.Contains(conn.connectionId)) { @@ -732,7 +732,7 @@ namespace QuantumUNET.Components "Duplicate observer ", conn.address, " added for ", - base.gameObject + gameObject })); } else @@ -742,7 +742,7 @@ namespace QuantumUNET.Components "Added observer ", conn.address, " added for ", - base.gameObject + gameObject })); m_Observers.Add(conn); m_ObserverConnections.Add(conn.connectionId); @@ -812,7 +812,7 @@ namespace QuantumUNET.Components Debug.LogWarning(string.Concat(new object[] { "Observer is not ready for ", - base.gameObject, + gameObject, " ", networkConnection3 })); @@ -823,7 +823,7 @@ namespace QuantumUNET.Components Debug.Log(string.Concat(new object[] { "New Observer for ", - base.gameObject, + gameObject, " ", networkConnection3 })); @@ -839,7 +839,7 @@ namespace QuantumUNET.Components Debug.Log(string.Concat(new object[] { "Removed Observer for ", - base.gameObject, + gameObject, " ", networkConnection4 })); @@ -883,12 +883,12 @@ namespace QuantumUNET.Components } else if (ClientAuthorityOwner == null) { - Debug.LogError("RemoveClientAuthority for " + base.gameObject + " has no clientAuthority owner."); + Debug.LogError("RemoveClientAuthority for " + gameObject + " has no clientAuthority owner."); return false; } else if (ClientAuthorityOwner != conn) { - Debug.LogError("RemoveClientAuthority for " + base.gameObject + " has different owner."); + Debug.LogError("RemoveClientAuthority for " + gameObject + " has different owner."); return false; } ClientAuthorityOwner.RemoveOwnedObject(this); @@ -917,12 +917,12 @@ namespace QuantumUNET.Components } else if (ClientAuthorityOwner != null && conn != ClientAuthorityOwner) { - ModConsole.OwmlConsole.WriteLine("AssignClientAuthority for " + base.gameObject + " already has an owner. Use RemoveClientAuthority() first."); + ModConsole.OwmlConsole.WriteLine("AssignClientAuthority for " + gameObject + " already has an owner. Use RemoveClientAuthority() first."); return false; } else if (conn == null) { - ModConsole.OwmlConsole.WriteLine("AssignClientAuthority for " + base.gameObject + " owner cannot be null. Use RemoveClientAuthority() instead."); + ModConsole.OwmlConsole.WriteLine("AssignClientAuthority for " + gameObject + " owner cannot be null. Use RemoveClientAuthority() instead."); return false; } ClientAuthorityOwner = conn; diff --git a/QuantumUNET/Components/QSBNetworkManagerHUD.cs b/QuantumUNET/Components/QSBNetworkManagerHUD.cs index 6541f612..a59376a2 100644 --- a/QuantumUNET/Components/QSBNetworkManagerHUD.cs +++ b/QuantumUNET/Components/QSBNetworkManagerHUD.cs @@ -9,10 +9,7 @@ namespace QuantumUNET.Components public int offsetX; public int offsetY; - private void Awake() - { - manager = GetComponent(); - } + private void Awake() => manager = GetComponent(); private void OnGUI() { diff --git a/QuantumUNET/Components/QSBNetworkManagerUNET.cs b/QuantumUNET/Components/QSBNetworkManagerUNET.cs index 2e6899da..ebf6da9d 100644 --- a/QuantumUNET/Components/QSBNetworkManagerUNET.cs +++ b/QuantumUNET/Components/QSBNetworkManagerUNET.cs @@ -50,13 +50,7 @@ namespace QuantumUNET.Components private static QSBNetworkConnection s_ClientReadyConnection; private static string s_Address; - public List startPositions - { - get - { - return s_StartPositions; - } - } + public List startPositions => s_StartPositions; public bool customConfig { get; set; } @@ -107,10 +101,7 @@ namespace QuantumUNET.Components } } - private void Awake() - { - InitializeSingleton(); - } + public void Awake() => InitializeSingleton(); private void InitializeSingleton() { @@ -121,14 +112,14 @@ namespace QuantumUNET.Components if (singleton != null) { Debug.Log("Multiple NetworkManagers detected in the scene. Only one NetworkManager can exist at a time. The duplicate NetworkManager will not be used."); - Destroy(base.gameObject); + Destroy(gameObject); return; } Debug.Log("NetworkManager created singleton (DontDestroyOnLoad)"); singleton = this; if (Application.isPlaying) { - DontDestroyOnLoad(base.gameObject); + DontDestroyOnLoad(gameObject); } } else @@ -157,10 +148,7 @@ namespace QuantumUNET.Components QSBNetworkServer.RegisterHandler(QSBMsgType.Error, new QSBNetworkMessageDelegate(OnServerErrorInternal)); } - public bool StartServer() - { - return StartServer(null, -1); - } + public bool StartServer() => StartServer(null, -1); private bool StartServer(ConnectionConfig config, int maxConnections) { @@ -339,15 +327,9 @@ namespace QuantumUNET.Components return client; } - public QSBNetworkClient StartClient() - { - return StartClient(null); - } + public QSBNetworkClient StartClient() => StartClient(null); - public QSBNetworkClient StartClient(ConnectionConfig config) - { - return StartClient(config, 0); - } + public QSBNetworkClient StartClient(ConnectionConfig config) => StartClient(config, 0); public virtual QSBNetworkClient StartHost(ConnectionConfig config, int maxConnections) { @@ -579,10 +561,7 @@ namespace QuantumUNET.Components s_StartPositions.Remove(start); } - public bool IsClientConnected() - { - return client != null && client.isConnected; - } + public bool IsClientConnected() => client != null && client.isConnected; public static void Shutdown() { @@ -776,15 +755,9 @@ namespace QuantumUNET.Components QSBNetworkServer.SetClientReady(conn); } - public virtual void OnServerAddPlayer(QSBNetworkConnection conn, short playerControllerId, NetworkReader extraMessageReader) - { - OnServerAddPlayerInternal(conn, playerControllerId); - } + public virtual void OnServerAddPlayer(QSBNetworkConnection conn, short playerControllerId, NetworkReader extraMessageReader) => OnServerAddPlayerInternal(conn, playerControllerId); - public virtual void OnServerAddPlayer(QSBNetworkConnection conn, short playerControllerId) - { - OnServerAddPlayerInternal(conn, playerControllerId); - } + public virtual void OnServerAddPlayer(QSBNetworkConnection conn, short playerControllerId) => OnServerAddPlayerInternal(conn, playerControllerId); private void OnServerAddPlayerInternal(QSBNetworkConnection conn, short playerControllerId) { diff --git a/QuantumUNET/Components/QSBNetworkTransform.cs b/QuantumUNET/Components/QSBNetworkTransform.cs index 66de6f11..7c6c0a66 100644 --- a/QuantumUNET/Components/QSBNetworkTransform.cs +++ b/QuantumUNET/Components/QSBNetworkTransform.cs @@ -29,65 +29,15 @@ namespace QuantumUNET.Components public float LastSyncTime { get; private set; } - public Vector3 TargetSyncPosition - { - get - { - return m_TargetSyncPosition; - } - } + public Vector3 TargetSyncPosition => m_TargetSyncPosition; - public Vector3 targetSyncVelocity - { - get - { - return m_TargetSyncVelocity; - } - } + public Vector3 targetSyncVelocity => m_TargetSyncVelocity; - public Quaternion targetSyncRotation3D - { - get - { - return m_TargetSyncRotation3D; - } - } + public Quaternion targetSyncRotation3D => m_TargetSyncRotation3D; public bool Grounded { get; set; } = true; - private void OnValidate() - { - if (SendInterval < 0f) - { - SendInterval = 0f; - } - if (SyncRotationAxis < AxisSyncMode.None || SyncRotationAxis > AxisSyncMode.AxisXYZ) - { - SyncRotationAxis = AxisSyncMode.None; - } - if (MovementTheshold < 0f) - { - MovementTheshold = 0f; - } - if (velocityThreshold < 0f) - { - velocityThreshold = 0f; - } - if (SnapThreshold < 0f) - { - SnapThreshold = 0.01f; - } - if (InterpolateRotation < 0f) - { - InterpolateRotation = 0.01f; - } - if (InterpolateMovement < 0f) - { - InterpolateMovement = 0.01f; - } - } - - private void Awake() + public void Awake() { m_PrevPosition = transform.position; m_PrevRotation = transform.rotation; @@ -97,10 +47,7 @@ namespace QuantumUNET.Components } } - public override void OnStartServer() - { - LastSyncTime = 0f; - } + public override void OnStartServer() => LastSyncTime = 0f; public override bool OnSerialize(QSBNetworkWriter writer, bool initialState) { @@ -336,12 +283,12 @@ namespace QuantumUNET.Components } else { - result = (float)reader.ReadInt16(); + result = reader.ReadInt16(); } } else { - result = (float)reader.ReadInt16(); + result = reader.ReadInt16(); } } else @@ -351,10 +298,8 @@ namespace QuantumUNET.Components return result; } - public static void SerializeVelocity3D(QSBNetworkWriter writer, Vector3 velocity, CompressionSyncMode compression) - { + public static void SerializeVelocity3D(QSBNetworkWriter writer, Vector3 velocity, CompressionSyncMode compression) => writer.Write(velocity); - } public static void SerializeRotation3D(QSBNetworkWriter writer, Quaternion rot, AxisSyncMode mode, CompressionSyncMode compression) { @@ -434,10 +379,7 @@ namespace QuantumUNET.Components } } - public static Vector3 UnserializeVelocity3D(QSBNetworkReader reader, CompressionSyncMode compression) - { - return reader.ReadVector3(); - } + public static Vector3 UnserializeVelocity3D(QSBNetworkReader reader, CompressionSyncMode compression) => reader.ReadVector3(); public static Quaternion UnserializeRotation3D(QSBNetworkReader reader, AxisSyncMode mode, CompressionSyncMode compression) { @@ -519,20 +461,11 @@ namespace QuantumUNET.Components return zero; } - public override int GetNetworkChannel() - { - return 1; - } + public override int GetNetworkChannel() => 1; - public override float GetNetworkSendInterval() - { - return SendInterval; - } + public override float GetNetworkSendInterval() => SendInterval; - public override void OnStartAuthority() - { - LastSyncTime = 0f; - } + public override void OnStartAuthority() => LastSyncTime = 0f; private Vector3 m_TargetSyncPosition; diff --git a/QuantumUNET/Messages/QSBErrorMessage.cs b/QuantumUNET/Messages/QSBErrorMessage.cs index 3a55c670..67951c84 100644 --- a/QuantumUNET/Messages/QSBErrorMessage.cs +++ b/QuantumUNET/Messages/QSBErrorMessage.cs @@ -2,15 +2,9 @@ { public class QSBErrorMessage : QSBMessageBase { - public override void Deserialize(QSBNetworkReader reader) - { - this.errorCode = (int)reader.ReadUInt16(); - } + public override void Deserialize(QSBNetworkReader reader) => errorCode = reader.ReadUInt16(); - public override void Serialize(QSBNetworkWriter writer) - { - writer.Write((ushort)this.errorCode); - } + public override void Serialize(QSBNetworkWriter writer) => writer.Write((ushort)errorCode); public int errorCode; } diff --git a/QuantumUNET/Messages/QSBMsgType.cs b/QuantumUNET/Messages/QSBMsgType.cs index 724bb9c3..763aaaff 100644 --- a/QuantumUNET/Messages/QSBMsgType.cs +++ b/QuantumUNET/Messages/QSBMsgType.cs @@ -11,7 +11,7 @@ } else { - string text = msgLabels[(int)value]; + var text = msgLabels[value]; if (string.IsNullOrEmpty(text)) { text = "[" + value + "]"; diff --git a/QuantumUNET/Messages/QSBNetworkMessage.cs b/QuantumUNET/Messages/QSBNetworkMessage.cs index f5b68c0d..b9de5999 100644 --- a/QuantumUNET/Messages/QSBNetworkMessage.cs +++ b/QuantumUNET/Messages/QSBNetworkMessage.cs @@ -17,9 +17,6 @@ namespace QuantumUNET.Messages return result; } - public void ReadMessage(TMsg msg) where TMsg : QSBMessageBase - { - msg.Deserialize(Reader); - } + public void ReadMessage(TMsg msg) where TMsg : QSBMessageBase => msg.Deserialize(Reader); } } \ No newline at end of file diff --git a/QuantumUNET/Messages/QSBObjectDestroyMessage.cs b/QuantumUNET/Messages/QSBObjectDestroyMessage.cs index 62a641c1..3f483e49 100644 --- a/QuantumUNET/Messages/QSBObjectDestroyMessage.cs +++ b/QuantumUNET/Messages/QSBObjectDestroyMessage.cs @@ -6,14 +6,8 @@ namespace QuantumUNET.Messages { public NetworkInstanceId NetId; - public override void Deserialize(QSBNetworkReader reader) - { - NetId = reader.ReadNetworkId(); - } + public override void Deserialize(QSBNetworkReader reader) => NetId = reader.ReadNetworkId(); - public override void Serialize(QSBNetworkWriter writer) - { - writer.Write(NetId); - } + public override void Serialize(QSBNetworkWriter writer) => writer.Write(NetId); } } \ No newline at end of file diff --git a/QuantumUNET/Messages/QSBObjectSpawnFinishedMessage.cs b/QuantumUNET/Messages/QSBObjectSpawnFinishedMessage.cs index 66f1c192..ebb68d39 100644 --- a/QuantumUNET/Messages/QSBObjectSpawnFinishedMessage.cs +++ b/QuantumUNET/Messages/QSBObjectSpawnFinishedMessage.cs @@ -4,14 +4,8 @@ { public uint State; - public override void Deserialize(QSBNetworkReader reader) - { - State = reader.ReadPackedUInt32(); - } + public override void Deserialize(QSBNetworkReader reader) => State = reader.ReadPackedUInt32(); - public override void Serialize(QSBNetworkWriter writer) - { - writer.WritePackedUInt32(State); - } + public override void Serialize(QSBNetworkWriter writer) => writer.WritePackedUInt32(State); } } \ No newline at end of file diff --git a/QuantumUNET/Messages/QSBPeerInfoMessage.cs b/QuantumUNET/Messages/QSBPeerInfoMessage.cs index a876df83..a38a00f0 100644 --- a/QuantumUNET/Messages/QSBPeerInfoMessage.cs +++ b/QuantumUNET/Messages/QSBPeerInfoMessage.cs @@ -6,44 +6,44 @@ namespace QuantumUNET.Messages { public override void Deserialize(QSBNetworkReader reader) { - this.connectionId = (int)reader.ReadPackedUInt32(); - this.address = reader.ReadString(); - this.port = (int)reader.ReadPackedUInt32(); - this.isHost = reader.ReadBoolean(); - this.isYou = reader.ReadBoolean(); - uint num = reader.ReadPackedUInt32(); + connectionId = (int)reader.ReadPackedUInt32(); + address = reader.ReadString(); + port = (int)reader.ReadPackedUInt32(); + isHost = reader.ReadBoolean(); + isYou = reader.ReadBoolean(); + var num = reader.ReadPackedUInt32(); if (num > 0U) { - List list = new List(); - for (uint num2 = 0U; num2 < num; num2 += 1U) + var list = new List(); + for (var num2 = 0U; num2 < num; num2 += 1U) { QSBPeerInfoPlayer item; item.netId = reader.ReadNetworkId(); item.playerControllerId = (short)reader.ReadPackedUInt32(); list.Add(item); } - this.playerIds = list.ToArray(); + playerIds = list.ToArray(); } } public override void Serialize(QSBNetworkWriter writer) { - writer.WritePackedUInt32((uint)this.connectionId); - writer.Write(this.address); - writer.WritePackedUInt32((uint)this.port); - writer.Write(this.isHost); - writer.Write(this.isYou); - if (this.playerIds == null) + writer.WritePackedUInt32((uint)connectionId); + writer.Write(address); + writer.WritePackedUInt32((uint)port); + writer.Write(isHost); + writer.Write(isYou); + if (playerIds == null) { writer.WritePackedUInt32(0U); } else { - writer.WritePackedUInt32((uint)this.playerIds.Length); - for (int i = 0; i < this.playerIds.Length; i++) + writer.WritePackedUInt32((uint)playerIds.Length); + for (var i = 0; i < playerIds.Length; i++) { - writer.Write(this.playerIds[i].netId); - writer.WritePackedUInt32((uint)this.playerIds[i].playerControllerId); + writer.Write(playerIds[i].netId); + writer.WritePackedUInt32((uint)playerIds[i].playerControllerId); } } } @@ -53,15 +53,15 @@ namespace QuantumUNET.Messages return string.Concat(new object[] { "PeerInfo conn:", - this.connectionId, + connectionId, " addr:", - this.address, + address, ":", - this.port, + port, " host:", - this.isHost, + isHost, " isYou:", - this.isYou + isYou }); } diff --git a/QuantumUNET/Messages/QSBRemovePlayerMessage.cs b/QuantumUNET/Messages/QSBRemovePlayerMessage.cs index 59d1d307..50190b79 100644 --- a/QuantumUNET/Messages/QSBRemovePlayerMessage.cs +++ b/QuantumUNET/Messages/QSBRemovePlayerMessage.cs @@ -4,14 +4,8 @@ { public short PlayerControllerId; - public override void Deserialize(QSBNetworkReader reader) - { - PlayerControllerId = (short)reader.ReadUInt16(); - } + public override void Deserialize(QSBNetworkReader reader) => PlayerControllerId = (short)reader.ReadUInt16(); - public override void Serialize(QSBNetworkWriter writer) - { - writer.Write((ushort)PlayerControllerId); - } + public override void Serialize(QSBNetworkWriter writer) => writer.Write((ushort)PlayerControllerId); } } \ No newline at end of file diff --git a/QuantumUNET/Messages/QSBStringMessage.cs b/QuantumUNET/Messages/QSBStringMessage.cs index 74dd198d..98c5ad07 100644 --- a/QuantumUNET/Messages/QSBStringMessage.cs +++ b/QuantumUNET/Messages/QSBStringMessage.cs @@ -8,18 +8,12 @@ public QSBStringMessage(string v) { - this.value = v; + value = v; } - public override void Deserialize(QSBNetworkReader reader) - { - this.value = reader.ReadString(); - } + public override void Deserialize(QSBNetworkReader reader) => value = reader.ReadString(); - public override void Serialize(QSBNetworkWriter writer) - { - writer.Write(this.value); - } + public override void Serialize(QSBNetworkWriter writer) => writer.Write(value); public string value; } diff --git a/QuantumUNET/QSBChannelPacket.cs b/QuantumUNET/QSBChannelPacket.cs index f6001ad6..32e55a62 100644 --- a/QuantumUNET/QSBChannelPacket.cs +++ b/QuantumUNET/QSBChannelPacket.cs @@ -8,53 +8,43 @@ namespace QuantumUNET { public QSBChannelPacket(int packetSize, bool isReliable) { - this.m_Position = 0; - this.m_Buffer = new byte[packetSize]; - this.m_IsReliable = isReliable; + m_Position = 0; + m_Buffer = new byte[packetSize]; + m_IsReliable = isReliable; } - public void Reset() - { - this.m_Position = 0; - } + public void Reset() => m_Position = 0; - public bool IsEmpty() - { - return this.m_Position == 0; - } + public bool IsEmpty() => m_Position == 0; public void Write(byte[] bytes, int numBytes) { - Array.Copy(bytes, 0, this.m_Buffer, this.m_Position, numBytes); - this.m_Position += numBytes; + Array.Copy(bytes, 0, m_Buffer, m_Position, numBytes); + m_Position += numBytes; } - public bool HasSpace(int numBytes) - { - return this.m_Position + numBytes <= this.m_Buffer.Length; - } + public bool HasSpace(int numBytes) => m_Position + numBytes <= m_Buffer.Length; public bool SendToTransport(QSBNetworkConnection conn, int channelId) { - bool result = true; - byte b; - if (!conn.TransportSend(this.m_Buffer, (int)((ushort)this.m_Position), channelId, out b)) + var result = true; + if (!conn.TransportSend(m_Buffer, (ushort)m_Position, channelId, out var b)) { - if (!this.m_IsReliable || b != 4) + if (!m_IsReliable || b != 4) { Debug.LogError(string.Concat(new object[] { "Failed to send internal buffer channel:", channelId, " bytesToSend:", - this.m_Position + m_Position })); result = false; } } if (b != 0) { - if (this.m_IsReliable && b == 4) + if (m_IsReliable && b == 4) { return false; } @@ -65,11 +55,11 @@ namespace QuantumUNET " channel:", channelId, " bytesToSend:", - this.m_Position + m_Position })); result = false; } - this.m_Position = 0; + m_Position = 0; return result; } diff --git a/QuantumUNET/QSBClientScene.cs b/QuantumUNET/QSBClientScene.cs index 0973f254..b9a73353 100644 --- a/QuantumUNET/QSBClientScene.cs +++ b/QuantumUNET/QSBClientScene.cs @@ -54,7 +54,7 @@ namespace QuantumUNET { player = null; bool result; - if ((int)playerControllerId >= localPlayers.Count) + if (playerControllerId >= localPlayers.Count) { if (LogFilter.logWarn) { @@ -62,7 +62,7 @@ namespace QuantumUNET } result = false; } - else if (localPlayers[(int)playerControllerId] == null) + else if (localPlayers[playerControllerId] == null) { if (LogFilter.logWarn) { @@ -72,7 +72,7 @@ namespace QuantumUNET } else { - player = localPlayers[(int)playerControllerId]; + player = localPlayers[playerControllerId]; result = (player.Gameobject != null); } return result; @@ -84,13 +84,13 @@ namespace QuantumUNET { Debug.LogWarning("ClientScene::InternalAddPlayer: playerControllerId : " + playerControllerId); } - if ((int)playerControllerId >= localPlayers.Count) + if (playerControllerId >= localPlayers.Count) { if (LogFilter.logWarn) { Debug.LogWarning("ClientScene::InternalAddPlayer: playerControllerId higher than expected: " + playerControllerId); } - while ((int)playerControllerId >= localPlayers.Count) + while (playerControllerId >= localPlayers.Count) { localPlayers.Add(new QSBPlayerController()); } @@ -101,7 +101,7 @@ namespace QuantumUNET PlayerControllerId = playerControllerId, UnetView = view }; - localPlayers[(int)playerControllerId] = playerController; + localPlayers[playerControllerId] = playerController; readyConnection.SetPlayerController(playerController); } @@ -143,7 +143,7 @@ namespace QuantumUNET Debug.LogWarning("ClientScene::AddPlayer: playerControllerId of " + playerControllerId + " is unusually high"); } } - while ((int)playerControllerId >= localPlayers.Count) + while (playerControllerId >= localPlayers.Count) { localPlayers.Add(new QSBPlayerController()); } @@ -194,7 +194,7 @@ namespace QuantumUNET var networkWriter = new QSBNetworkWriter(); extraMessage.Serialize(networkWriter); addPlayerMessage.msgData = networkWriter.ToArray(); - addPlayerMessage.msgSize = (int)networkWriter.Position; + addPlayerMessage.msgSize = networkWriter.Position; } readyConnection.Send(37, addPlayerMessage); result = true; @@ -224,8 +224,8 @@ namespace QuantumUNET }; readyConnection.Send(38, removePlayerMessage); readyConnection.RemovePlayerController(playerControllerId); - localPlayers[(int)playerControllerId] = new QSBPlayerController(); - UnityEngine.Object.Destroy(playerController.Gameobject); + localPlayers[playerControllerId] = new QSBPlayerController(); + Object.Destroy(playerController.Gameobject); result = true; } else @@ -346,29 +346,29 @@ namespace QuantumUNET { if (localClient) { - client.RegisterHandlerSafe((short)1, new QSBNetworkMessageDelegate(OnLocalClientObjectDestroy)); - client.RegisterHandlerSafe((short)13, new QSBNetworkMessageDelegate(OnLocalClientObjectHide)); - client.RegisterHandlerSafe((short)3, new QSBNetworkMessageDelegate(OnLocalClientObjectSpawn)); - client.RegisterHandlerSafe((short)10, new QSBNetworkMessageDelegate(OnLocalClientObjectSpawnScene)); - client.RegisterHandlerSafe((short)15, new QSBNetworkMessageDelegate(OnClientAuthority)); + client.RegisterHandlerSafe(1, new QSBNetworkMessageDelegate(OnLocalClientObjectDestroy)); + client.RegisterHandlerSafe(13, new QSBNetworkMessageDelegate(OnLocalClientObjectHide)); + client.RegisterHandlerSafe(3, new QSBNetworkMessageDelegate(OnLocalClientObjectSpawn)); + client.RegisterHandlerSafe(10, new QSBNetworkMessageDelegate(OnLocalClientObjectSpawnScene)); + client.RegisterHandlerSafe(15, new QSBNetworkMessageDelegate(OnClientAuthority)); } else { - client.RegisterHandlerSafe((short)3, new QSBNetworkMessageDelegate(OnObjectSpawn)); - client.RegisterHandlerSafe((short)10, new QSBNetworkMessageDelegate(OnObjectSpawnScene)); - client.RegisterHandlerSafe((short)12, new QSBNetworkMessageDelegate(OnObjectSpawnFinished)); - client.RegisterHandlerSafe((short)1, new QSBNetworkMessageDelegate(OnObjectDestroy)); - client.RegisterHandlerSafe((short)13, new QSBNetworkMessageDelegate(OnObjectDestroy)); - client.RegisterHandlerSafe((short)8, new QSBNetworkMessageDelegate(OnUpdateVarsMessage)); - client.RegisterHandlerSafe((short)4, new QSBNetworkMessageDelegate(OnOwnerMessage)); - client.RegisterHandlerSafe((short)9, new QSBNetworkMessageDelegate(OnSyncListMessage)); - client.RegisterHandlerSafe((short)40, new QSBNetworkMessageDelegate(QSBNetworkAnimator.OnAnimationClientMessage)); - client.RegisterHandlerSafe((short)41, new QSBNetworkMessageDelegate(QSBNetworkAnimator.OnAnimationParametersClientMessage)); - client.RegisterHandlerSafe((short)15, new QSBNetworkMessageDelegate(OnClientAuthority)); + client.RegisterHandlerSafe(3, new QSBNetworkMessageDelegate(OnObjectSpawn)); + client.RegisterHandlerSafe(10, new QSBNetworkMessageDelegate(OnObjectSpawnScene)); + client.RegisterHandlerSafe(12, new QSBNetworkMessageDelegate(OnObjectSpawnFinished)); + client.RegisterHandlerSafe(1, new QSBNetworkMessageDelegate(OnObjectDestroy)); + client.RegisterHandlerSafe(13, new QSBNetworkMessageDelegate(OnObjectDestroy)); + client.RegisterHandlerSafe(8, new QSBNetworkMessageDelegate(OnUpdateVarsMessage)); + client.RegisterHandlerSafe(4, new QSBNetworkMessageDelegate(OnOwnerMessage)); + client.RegisterHandlerSafe(9, new QSBNetworkMessageDelegate(OnSyncListMessage)); + client.RegisterHandlerSafe(40, new QSBNetworkMessageDelegate(QSBNetworkAnimator.OnAnimationClientMessage)); + client.RegisterHandlerSafe(41, new QSBNetworkMessageDelegate(QSBNetworkAnimator.OnAnimationParametersClientMessage)); + client.RegisterHandlerSafe(15, new QSBNetworkMessageDelegate(OnClientAuthority)); } - client.RegisterHandlerSafe((short)2, new QSBNetworkMessageDelegate(OnRPCMessage)); - client.RegisterHandlerSafe((short)7, new QSBNetworkMessageDelegate(OnSyncEventMessage)); - client.RegisterHandlerSafe((short)42, new QSBNetworkMessageDelegate(QSBNetworkAnimator.OnAnimationTriggerClientMessage)); + client.RegisterHandlerSafe(2, new QSBNetworkMessageDelegate(OnRPCMessage)); + client.RegisterHandlerSafe(7, new QSBNetworkMessageDelegate(OnSyncEventMessage)); + client.RegisterHandlerSafe(42, new QSBNetworkMessageDelegate(QSBNetworkAnimator.OnAnimationTriggerClientMessage)); } internal static string GetStringForAssetId(NetworkHash128 assetId) @@ -449,7 +449,7 @@ namespace QuantumUNET } else if (QSBNetworkScene.GetPrefab(s_ObjectSpawnMessage.assetId, out var original)) { - GameObject gameObject = UnityEngine.Object.Instantiate(original, s_ObjectSpawnMessage.Position, s_ObjectSpawnMessage.Rotation); + var gameObject = Object.Instantiate(original, s_ObjectSpawnMessage.Position, s_ObjectSpawnMessage.Rotation); component = gameObject.GetComponent(); if (component == null) { @@ -572,7 +572,7 @@ namespace QuantumUNET { if (networkIdentity.SceneId.IsEmpty()) { - UnityEngine.Object.Destroy(networkIdentity.gameObject); + Object.Destroy(networkIdentity.gameObject); } else { @@ -663,7 +663,7 @@ namespace QuantumUNET } else if (LogFilter.logWarn) { - string cmdHashHandlerName = QSBNetworkBehaviour.GetCmdHashHandlerName(num); + var cmdHashHandlerName = QSBNetworkBehaviour.GetCmdHashHandlerName(num); Debug.LogWarningFormat("Could not find target object with netId:{0} for RPC call {1}", new object[] { networkInstanceId, diff --git a/QuantumUNET/QSBLocalClient.cs b/QuantumUNET/QSBLocalClient.cs index ce65e123..98455474 100644 --- a/QuantumUNET/QSBLocalClient.cs +++ b/QuantumUNET/QSBLocalClient.cs @@ -14,7 +14,7 @@ namespace QuantumUNET PostInternalMessage(33); m_Connected = false; } - m_AsyncConnect = QSBNetworkClient.ConnectState.Disconnected; + m_AsyncConnect = ConnectState.Disconnected; m_LocalServer.RemoveLocalClient(m_Connection); } @@ -31,11 +31,11 @@ namespace QuantumUNET } m_LocalServer = QSBNetworkServer.instance; m_Connection = new QSBULocalConnectionToServer(m_LocalServer); - base.SetHandlers(m_Connection); + SetHandlers(m_Connection); m_Connection.connectionId = m_LocalServer.AddLocalClient(this); - m_AsyncConnect = QSBNetworkClient.ConnectState.Connected; - QSBNetworkClient.SetActive(true); - base.RegisterSystemHandlers(true); + m_AsyncConnect = ConnectState.Connected; + SetActive(true); + RegisterSystemHandlers(true); if (generateConnectMsg) { PostInternalMessage(32); @@ -108,11 +108,11 @@ namespace QuantumUNET } s_InternalMessage.Reader.ReadInt16(); s_InternalMessage.ChannelId = t.channelId; - s_InternalMessage.Connection = base.connection; + s_InternalMessage.Connection = connection; s_InternalMessage.MsgType = s_InternalMessage.Reader.ReadInt16(); m_Connection.InvokeHandler(s_InternalMessage); m_FreeMessages.Push(t); - base.connection.lastMessageTime = Time.time; + connection.lastMessageTime = Time.time; } m_InternalMsgs = internalMsgs; m_InternalMsgs.Clear(); diff --git a/QuantumUNET/QSBNetBuffer.cs b/QuantumUNET/QSBNetBuffer.cs index 8f879800..2c696159 100644 --- a/QuantumUNET/QSBNetBuffer.cs +++ b/QuantumUNET/QSBNetBuffer.cs @@ -15,34 +15,22 @@ namespace QuantumUNET m_Buffer = buffer; } - public uint Position - { - get - { - return m_Pos; - } - } + public uint Position { get; private set; } - public int Length - { - get - { - return m_Buffer.Length; - } - } + public int Length => m_Buffer.Length; public byte ReadByte() { - if ((ulong)m_Pos >= (ulong)((long)m_Buffer.Length)) + if (Position >= (ulong)m_Buffer.Length) { throw new IndexOutOfRangeException("NetworkReader:ReadByte out of range:" + ToString()); } - return m_Buffer[(int)((UIntPtr)(m_Pos++))]; + return m_Buffer[(int)((UIntPtr)(Position++))]; } public void ReadBytes(byte[] buffer, uint count) { - if ((ulong)(m_Pos + count) > (ulong)((long)m_Buffer.Length)) + if (Position + count > (ulong)m_Buffer.Length) { throw new IndexOutOfRangeException(string.Concat(new object[] { @@ -53,110 +41,107 @@ namespace QuantumUNET })); } ushort num = 0; - while ((uint)num < count) + while (num < count) { - buffer[(int)num] = m_Buffer[(int)((UIntPtr)(m_Pos + (uint)num))]; + buffer[num] = m_Buffer[(int)((UIntPtr)(Position + num))]; num += 1; } - m_Pos += count; + Position += count; } - internal ArraySegment AsArraySegment() - { - return new ArraySegment(m_Buffer, 0, (int)m_Pos); - } + internal ArraySegment AsArraySegment() => new ArraySegment(m_Buffer, 0, (int)Position); public void WriteByte(byte value) { WriteCheckForSpace(1); - m_Buffer[(int)((UIntPtr)m_Pos)] = value; - m_Pos += 1U; + m_Buffer[(int)((UIntPtr)Position)] = value; + Position += 1U; } public void WriteByte2(byte value0, byte value1) { WriteCheckForSpace(2); - m_Buffer[(int)((UIntPtr)m_Pos)] = value0; - m_Buffer[(int)((UIntPtr)(m_Pos + 1U))] = value1; - m_Pos += 2U; + m_Buffer[(int)((UIntPtr)Position)] = value0; + m_Buffer[(int)((UIntPtr)(Position + 1U))] = value1; + Position += 2U; } public void WriteByte4(byte value0, byte value1, byte value2, byte value3) { WriteCheckForSpace(4); - m_Buffer[(int)((UIntPtr)m_Pos)] = value0; - m_Buffer[(int)((UIntPtr)(m_Pos + 1U))] = value1; - m_Buffer[(int)((UIntPtr)(m_Pos + 2U))] = value2; - m_Buffer[(int)((UIntPtr)(m_Pos + 3U))] = value3; - m_Pos += 4U; + m_Buffer[(int)((UIntPtr)Position)] = value0; + m_Buffer[(int)((UIntPtr)(Position + 1U))] = value1; + m_Buffer[(int)((UIntPtr)(Position + 2U))] = value2; + m_Buffer[(int)((UIntPtr)(Position + 3U))] = value3; + Position += 4U; } public void WriteByte8(byte value0, byte value1, byte value2, byte value3, byte value4, byte value5, byte value6, byte value7) { WriteCheckForSpace(8); - m_Buffer[(int)((UIntPtr)m_Pos)] = value0; - m_Buffer[(int)((UIntPtr)(m_Pos + 1U))] = value1; - m_Buffer[(int)((UIntPtr)(m_Pos + 2U))] = value2; - m_Buffer[(int)((UIntPtr)(m_Pos + 3U))] = value3; - m_Buffer[(int)((UIntPtr)(m_Pos + 4U))] = value4; - m_Buffer[(int)((UIntPtr)(m_Pos + 5U))] = value5; - m_Buffer[(int)((UIntPtr)(m_Pos + 6U))] = value6; - m_Buffer[(int)((UIntPtr)(m_Pos + 7U))] = value7; - m_Pos += 8U; + m_Buffer[(int)((UIntPtr)Position)] = value0; + m_Buffer[(int)((UIntPtr)(Position + 1U))] = value1; + m_Buffer[(int)((UIntPtr)(Position + 2U))] = value2; + m_Buffer[(int)((UIntPtr)(Position + 3U))] = value3; + m_Buffer[(int)((UIntPtr)(Position + 4U))] = value4; + m_Buffer[(int)((UIntPtr)(Position + 5U))] = value5; + m_Buffer[(int)((UIntPtr)(Position + 6U))] = value6; + m_Buffer[(int)((UIntPtr)(Position + 7U))] = value7; + Position += 8U; } public void WriteBytesAtOffset(byte[] buffer, ushort targetOffset, ushort count) { - uint num = (uint)(count + targetOffset); + var num = (uint)(count + targetOffset); WriteCheckForSpace((ushort)num); - if (targetOffset == 0 && (int)count == buffer.Length) + if (targetOffset == 0 && count == buffer.Length) { - buffer.CopyTo(m_Buffer, (int)m_Pos); + buffer.CopyTo(m_Buffer, (int)Position); } else { - for (int i = 0; i < (int)count; i++) + for (var i = 0; i < count; i++) { - m_Buffer[(int)targetOffset + i] = buffer[i]; + m_Buffer[targetOffset + i] = buffer[i]; } } - if (num > m_Pos) + if (num > Position) { - m_Pos = num; + Position = num; } } public void WriteBytes(byte[] buffer, ushort count) { WriteCheckForSpace(count); - if ((int)count == buffer.Length) + if (count == buffer.Length) { - buffer.CopyTo(m_Buffer, (int)m_Pos); + buffer.CopyTo(m_Buffer, (int)Position); } else { - for (int i = 0; i < (int)count; i++) + for (var i = 0; i < count; i++) { - m_Buffer[(int)(checked((IntPtr)(unchecked((ulong)m_Pos + (ulong)((long)i)))))] = buffer[i]; + m_Buffer[(int)(checked((IntPtr)(unchecked(Position + (ulong)i))))] = buffer[i]; } } - m_Pos += (uint)count; + Position += count; } private void WriteCheckForSpace(ushort count) { - if ((ulong)(m_Pos + (uint)count) >= (ulong)((long)m_Buffer.Length)) + if (Position + count >= (ulong)m_Buffer.Length) { - int num = (int)Math.Ceiling((double)((float)m_Buffer.Length * 1.5f)); - while ((ulong)(m_Pos + (uint)count) >= (ulong)((long)num)) + var num = (int)Math.Ceiling(m_Buffer.Length * 1.5f); + while (Position + count >= (ulong)num) { - num = (int)Math.Ceiling((double)((float)num * 1.5f)); + num = (int)Math.Ceiling(num * 1.5f); if (num > 134217728) { Debug.LogWarning("NetworkBuffer size is " + num + " bytes!"); } } - byte[] array = new byte[num]; + var array = new byte[num]; m_Buffer.CopyTo(array, 0); m_Buffer = array; } @@ -164,31 +149,22 @@ namespace QuantumUNET public void FinishMessage() { - ushort num = (ushort)(m_Pos - 4U); + var num = (ushort)(Position - 4U); m_Buffer[0] = (byte)(num & 255); - m_Buffer[1] = (byte)(num >> 8 & 255); + m_Buffer[1] = (byte)((num >> 8) & 255); } - public void SeekZero() - { - m_Pos = 0U; - } + public void SeekZero() => Position = 0U; public void Replace(byte[] buffer) { m_Buffer = buffer; - m_Pos = 0U; + Position = 0U; } - public override string ToString() - { - return string.Format("NetBuf sz:{0} pos:{1}", m_Buffer.Length, m_Pos); - } + public override string ToString() => string.Format("NetBuf sz:{0} pos:{1}", m_Buffer.Length, Position); private byte[] m_Buffer; - - private uint m_Pos; - private const int k_InitialSize = 64; private const float k_GrowthFactor = 1.5f; diff --git a/QuantumUNET/QSBNetworkBehaviour.cs b/QuantumUNET/QSBNetworkBehaviour.cs index 202910c1..c243ce37 100644 --- a/QuantumUNET/QSBNetworkBehaviour.cs +++ b/QuantumUNET/QSBNetworkBehaviour.cs @@ -77,7 +77,7 @@ namespace QuantumUNET } } writer.FinishMessage(); - QSBNetworkServer.SendWriterToReady(base.gameObject, writer, channelId); + QSBNetworkServer.SendWriterToReady(gameObject, writer, channelId); } protected void SendTargetRPCInternal(QSBNetworkConnection conn, QSBNetworkWriter writer, int channelId, string rpcName) @@ -434,7 +434,7 @@ namespace QuantumUNET Debug.Log(string.Concat(new object[] { "SetSyncVar GameObject ", - base.GetType().Name, + GetType().Name, " bit [", dirtyBit, "] netfieldId:", diff --git a/QuantumUNET/QSBNetworkCRC.cs b/QuantumUNET/QSBNetworkCRC.cs index 0bf0643f..5f0e8938 100644 --- a/QuantumUNET/QSBNetworkCRC.cs +++ b/QuantumUNET/QSBNetworkCRC.cs @@ -20,13 +20,7 @@ namespace QuantumUNET } } - public Dictionary scripts - { - get - { - return this.m_Scripts; - } - } + public Dictionary scripts { get; } = new Dictionary(); public static bool scriptCRCCheck { @@ -42,12 +36,12 @@ namespace QuantumUNET public static void ReinitializeScriptCRCs(Assembly callingAssembly) { - singleton.m_Scripts.Clear(); - foreach (Type type in callingAssembly.GetTypes()) + singleton.scripts.Clear(); + foreach (var type in callingAssembly.GetTypes()) { if (type.GetBaseType() == typeof(QSBNetworkBehaviour)) { - MethodInfo method = type.GetMethod(".cctor", BindingFlags.Static); + var method = type.GetMethod(".cctor", BindingFlags.Static); if (method != null) { method.Invoke(null, new object[0]); @@ -56,31 +50,25 @@ namespace QuantumUNET } } - public static void RegisterBehaviour(string name, int channel) - { - singleton.m_Scripts[name] = channel; - } + public static void RegisterBehaviour(string name, int channel) => singleton.scripts[name] = channel; - internal static bool Validate(QSBCRCMessageEntry[] scripts, int numChannels) - { - return singleton.ValidateInternal(scripts, numChannels); - } + internal static bool Validate(QSBCRCMessageEntry[] scripts, int numChannels) => singleton.ValidateInternal(scripts, numChannels); private bool ValidateInternal(QSBCRCMessageEntry[] remoteScripts, int numChannels) { bool result; - if (this.m_Scripts.Count != remoteScripts.Length) + if (scripts.Count != remoteScripts.Length) { if (LogFilter.logWarn) { Debug.LogWarning("Network configuration mismatch detected. The number of networked scripts on the client does not match the number of networked scripts on the server. This could be caused by lazy loading of scripts on the client. This warning can be disabled by the checkbox in NetworkManager Script CRC Check."); } - this.Dump(remoteScripts); + Dump(remoteScripts); result = false; } else { - foreach (QSBCRCMessageEntry crcmessageEntry in remoteScripts) + foreach (var crcmessageEntry in remoteScripts) { if (LogFilter.logDebug) { @@ -92,10 +80,10 @@ namespace QuantumUNET crcmessageEntry.channel })); } - if (this.m_Scripts.ContainsKey(crcmessageEntry.name)) + if (scripts.ContainsKey(crcmessageEntry.name)) { - int num = this.m_Scripts[crcmessageEntry.name]; - if (num != (int)crcmessageEntry.channel) + var num = scripts[crcmessageEntry.name]; + if (num != crcmessageEntry.channel) { if (LogFilter.logError) { @@ -109,11 +97,11 @@ namespace QuantumUNET crcmessageEntry.channel })); } - this.Dump(remoteScripts); + Dump(remoteScripts); return false; } } - if ((int)crcmessageEntry.channel >= numChannels) + if (crcmessageEntry.channel >= numChannels) { if (LogFilter.logError) { @@ -125,7 +113,7 @@ namespace QuantumUNET crcmessageEntry.channel })); } - this.Dump(remoteScripts); + Dump(remoteScripts); return false; } } @@ -136,17 +124,17 @@ namespace QuantumUNET private void Dump(QSBCRCMessageEntry[] remoteScripts) { - foreach (string text in this.m_Scripts.Keys) + foreach (var text in scripts.Keys) { Debug.Log(string.Concat(new object[] { "CRC Local Dump ", text, " : ", - this.m_Scripts[text] + scripts[text] })); } - foreach (QSBCRCMessageEntry crcmessageEntry in remoteScripts) + foreach (var crcmessageEntry in remoteScripts) { Debug.Log(string.Concat(new object[] { @@ -159,9 +147,6 @@ namespace QuantumUNET } internal static QSBNetworkCRC s_Singleton; - - private Dictionary m_Scripts = new Dictionary(); - private bool m_ScriptCRCCheck; } } \ No newline at end of file diff --git a/QuantumUNET/QSBNetworkClient.cs b/QuantumUNET/QSBNetworkClient.cs index 04a5169c..8b4ee136 100644 --- a/QuantumUNET/QSBNetworkClient.cs +++ b/QuantumUNET/QSBNetworkClient.cs @@ -30,82 +30,25 @@ namespace QuantumUNET RegisterSystemHandlers(false); } - public static List allClients - { - get - { - return s_Clients; - } - } + public static List allClients { get; private set; } = new List(); - public static bool active - { - get - { - return s_IsActive; - } - } + public static bool active { get; private set; } - internal void SetHandlers(QSBNetworkConnection conn) - { - conn.SetHandlers(m_MessageHandlers); - } + internal void SetHandlers(QSBNetworkConnection conn) => conn.SetHandlers(m_MessageHandlers); - public string serverIp - { - get - { - return m_ServerIp; - } - } + public string serverIp { get; private set; } = ""; - public int serverPort - { - get - { - return m_ServerPort; - } - } + public int serverPort { get; private set; } - public QSBNetworkConnection connection - { - get - { - return m_Connection; - } - } + public QSBNetworkConnection connection => m_Connection; - internal int hostId - { - get - { - return m_ClientId; - } - } + internal int hostId { get; private set; } = -1; - public Dictionary handlers - { - get - { - return m_MessageHandlers.GetHandlers(); - } - } + public Dictionary handlers => m_MessageHandlers.GetHandlers(); - public int numChannels - { - get - { - return m_HostTopology.DefaultConfig.ChannelCount; - } - } + public int numChannels => hostTopology.DefaultConfig.ChannelCount; - public HostTopology hostTopology - { - get - { - return m_HostTopology; - } - } + public HostTopology hostTopology { get; private set; } public int hostPort { @@ -127,36 +70,21 @@ namespace QuantumUNET } } - public bool isConnected - { - get - { - return m_AsyncConnect == ConnectState.Connected; - } - } + public bool isConnected => m_AsyncConnect == ConnectState.Connected; - public Type networkConnectionClass - { - get - { - return m_NetworkConnectionClass; - } - } + public Type networkConnectionClass { get; private set; } = typeof(QSBNetworkConnection); - public void SetNetworkConnectionClass() where T : QSBNetworkConnection - { - m_NetworkConnectionClass = typeof(T); - } + public void SetNetworkConnectionClass() where T : QSBNetworkConnection => networkConnectionClass = typeof(T); public bool Configure(ConnectionConfig config, int maxConnections) { - HostTopology topology = new HostTopology(config, maxConnections); + var topology = new HostTopology(config, maxConnections); return Configure(topology); } public bool Configure(HostTopology topology) { - m_HostTopology = topology; + hostTopology = topology; return true; } @@ -195,16 +123,16 @@ namespace QuantumUNET QSBClientScene.ClearLocalPlayers(); m_Connection.Disconnect(); m_Connection = null; - m_ClientId = NetworkTransport.AddHost(m_HostTopology, m_HostPort); - m_ServerPort = serverPort; + hostId = NetworkTransport.AddHost(hostTopology, m_HostPort); + this.serverPort = serverPort; if (Application.platform == RuntimePlatform.WebGLPlayer) { - m_ServerIp = serverIp; + this.serverIp = serverIp; m_AsyncConnect = ConnectState.Resolved; } else if (serverIp.Equals("127.0.0.1") || serverIp.Equals("localhost")) { - m_ServerIp = "127.0.0.1"; + this.serverIp = "127.0.0.1"; m_AsyncConnect = ConnectState.Resolved; } else @@ -250,7 +178,7 @@ namespace QuantumUNET QSBClientScene.ClearLocalPlayers(); m_Connection.Disconnect(); m_Connection = null; - m_ClientId = NetworkTransport.AddHost(m_HostTopology, m_HostPort); + hostId = NetworkTransport.AddHost(hostTopology, m_HostPort); if (secureTunnelEndPoint == null) { if (LogFilter.logError) @@ -271,11 +199,11 @@ namespace QuantumUNET } else { - string fullName = secureTunnelEndPoint.GetType().FullName; + var fullName = secureTunnelEndPoint.GetType().FullName; if (fullName == "System.Net.IPEndPoint") { - IPEndPoint ipendPoint = (IPEndPoint)secureTunnelEndPoint; - this.Connect(ipendPoint.Address.ToString(), ipendPoint.Port); + var ipendPoint = (IPEndPoint)secureTunnelEndPoint; + Connect(ipendPoint.Address.ToString(), ipendPoint.Port); result = (m_AsyncConnect != ConnectState.Failed); } else if (fullName != "UnityEngine.XboxOne.XboxOneEndPoint" && fullName != "UnityEngine.PS4.SceEndPoint") @@ -289,12 +217,12 @@ namespace QuantumUNET } else { - byte b = 0; m_RemoteEndPoint = secureTunnelEndPoint; m_AsyncConnect = ConnectState.Connecting; + byte b; try { - m_ClientConnectionId = NetworkTransport.ConnectEndPoint(m_ClientId, m_RemoteEndPoint, 0, out b); + m_ClientConnectionId = NetworkTransport.ConnectEndPoint(hostId, m_RemoteEndPoint, 0, out b); } catch (Exception arg) { @@ -316,9 +244,9 @@ namespace QuantumUNET } else { - m_Connection = (QSBNetworkConnection)Activator.CreateInstance(m_NetworkConnectionClass); + m_Connection = (QSBNetworkConnection)Activator.CreateInstance(networkConnectionClass); m_Connection.SetHandlers(m_MessageHandlers); - m_Connection.Initialize(m_ServerIp, m_ClientId, m_ClientConnectionId, m_HostTopology); + m_Connection.Initialize(serverIp, hostId, m_ClientConnectionId, hostTopology); result = true; } } @@ -337,7 +265,7 @@ namespace QuantumUNET private static bool IsValidIpV6(string address) { - foreach (char c in address) + foreach (var c in address) { if (c != ':' && (c < '0' || c > '9') && (c < 'a' || c > 'f') && (c < 'A' || c > 'F')) { @@ -357,20 +285,20 @@ namespace QuantumUNET ":", serverPort })); - m_ServerPort = serverPort; + this.serverPort = serverPort; if (Application.platform == RuntimePlatform.WebGLPlayer) { - m_ServerIp = serverIp; + this.serverIp = serverIp; m_AsyncConnect = ConnectState.Resolved; } else if (serverIp.Equals("127.0.0.1") || serverIp.Equals("localhost")) { - m_ServerIp = "127.0.0.1"; + this.serverIp = "127.0.0.1"; m_AsyncConnect = ConnectState.Resolved; } else if (serverIp.IndexOf(":") != -1 && IsValidIpV6(serverIp)) { - m_ServerIp = serverIp; + this.serverIp = serverIp; m_AsyncConnect = ConnectState.Resolved; } else @@ -385,7 +313,7 @@ namespace QuantumUNET public void Connect(EndPoint secureTunnelEndPoint) { //bool usePlatformSpecificProtocols = NetworkTransport.DoesEndPointUsePlatformProtocols(secureTunnelEndPoint); - bool usePlatformSpecificProtocols = false; + var usePlatformSpecificProtocols = false; PrepareForConnect(usePlatformSpecificProtocols); if (LogFilter.logDebug) { @@ -409,11 +337,11 @@ namespace QuantumUNET } else { - string fullName = secureTunnelEndPoint.GetType().FullName; + var fullName = secureTunnelEndPoint.GetType().FullName; if (fullName == "System.Net.IPEndPoint") { - IPEndPoint ipendPoint = (IPEndPoint)secureTunnelEndPoint; - this.Connect(ipendPoint.Address.ToString(), ipendPoint.Port); + var ipendPoint = (IPEndPoint)secureTunnelEndPoint; + Connect(ipendPoint.Address.ToString(), ipendPoint.Port); } else if (fullName != "UnityEngine.XboxOne.XboxOneEndPoint" && fullName != "UnityEngine.PS4.SceEndPoint" && fullName != "UnityEngine.PSVita.SceEndPoint") { @@ -430,7 +358,7 @@ namespace QuantumUNET m_AsyncConnect = ConnectState.Connecting; try { - m_ClientConnectionId = NetworkTransport.ConnectEndPoint(m_ClientId, m_RemoteEndPoint, 0, out b); + m_ClientConnectionId = NetworkTransport.ConnectEndPoint(hostId, m_RemoteEndPoint, 0, out b); } catch (Exception arg) { @@ -451,39 +379,36 @@ namespace QuantumUNET } else { - m_Connection = (QSBNetworkConnection)Activator.CreateInstance(m_NetworkConnectionClass); + m_Connection = (QSBNetworkConnection)Activator.CreateInstance(networkConnectionClass); m_Connection.SetHandlers(m_MessageHandlers); - m_Connection.Initialize(m_ServerIp, m_ClientId, m_ClientConnectionId, m_HostTopology); + m_Connection.Initialize(serverIp, hostId, m_ClientConnectionId, hostTopology); } } } } - private void PrepareForConnect() - { - PrepareForConnect(false); - } + private void PrepareForConnect() => PrepareForConnect(false); private void PrepareForConnect(bool usePlatformSpecificProtocols) { SetActive(true); RegisterSystemHandlers(false); - if (m_HostTopology == null) + if (hostTopology == null) { - ConnectionConfig connectionConfig = new ConnectionConfig(); + var connectionConfig = new ConnectionConfig(); connectionConfig.AddChannel(QosType.ReliableSequenced); connectionConfig.AddChannel(QosType.Unreliable); connectionConfig.UsePlatformSpecificProtocols = usePlatformSpecificProtocols; - m_HostTopology = new HostTopology(connectionConfig, 8); + hostTopology = new HostTopology(connectionConfig, 8); } if (m_UseSimulator) { - int num = m_SimulatedLatency / 3 - 1; + var num = (m_SimulatedLatency / 3) - 1; if (num < 1) { num = 1; } - int num2 = m_SimulatedLatency * 3; + var num2 = m_SimulatedLatency * 3; ModConsole.OwmlConsole.WriteLine(string.Concat(new object[] { "AddHost Using Simulator ", @@ -491,11 +416,11 @@ namespace QuantumUNET "/", num2 })); - m_ClientId = NetworkTransport.AddHostWithSimulator(m_HostTopology, num, num2, m_HostPort); + hostId = NetworkTransport.AddHostWithSimulator(hostTopology, num, num2, m_HostPort); } else { - m_ClientId = NetworkTransport.AddHost(m_HostTopology, m_HostPort); + hostId = NetworkTransport.AddHost(hostTopology, m_HostPort); } } @@ -503,8 +428,8 @@ namespace QuantumUNET { try { - IPAddress[] array = Dns.EndGetHostAddresses(ar); - QSBNetworkClient networkClient = (QSBNetworkClient)ar.AsyncState; + var array = Dns.EndGetHostAddresses(ar); + var networkClient = (QSBNetworkClient)ar.AsyncState; if (array.Length == 0) { Debug.LogError("DNS lookup failed for:" + networkClient.m_RequestedServerHost); @@ -512,22 +437,22 @@ namespace QuantumUNET } else { - networkClient.m_ServerIp = array[0].ToString(); + networkClient.serverIp = array[0].ToString(); networkClient.m_AsyncConnect = ConnectState.Resolved; Debug.Log(string.Concat(new string[] { "Async DNS Result:", - networkClient.m_ServerIp, + networkClient.serverIp, " for ", networkClient.m_RequestedServerHost, ": ", - networkClient.m_ServerIp + networkClient.serverIp })); } } catch (SocketException ex) { - QSBNetworkClient networkClient2 = (QSBNetworkClient)ar.AsyncState; + var networkClient2 = (QSBNetworkClient)ar.AsyncState; Debug.LogError("DNS resolution failed: " + ex.GetErrorCode()); Debug.LogError("Exception:" + ex); networkClient2.m_AsyncConnect = ConnectState.Failed; @@ -538,7 +463,7 @@ namespace QuantumUNET { if (m_UseSimulator) { - int num = m_SimulatedLatency / 3; + var num = m_SimulatedLatency / 3; if (num < 1) { num = 1; @@ -550,18 +475,16 @@ namespace QuantumUNET "/", m_SimulatedLatency })); - ConnectionSimulatorConfig conf = new ConnectionSimulatorConfig(num, m_SimulatedLatency, num, m_SimulatedLatency, m_PacketLoss); - byte b; - m_ClientConnectionId = NetworkTransport.ConnectWithSimulator(m_ClientId, m_ServerIp, m_ServerPort, 0, out b, conf); + var conf = new ConnectionSimulatorConfig(num, m_SimulatedLatency, num, m_SimulatedLatency, m_PacketLoss); + m_ClientConnectionId = NetworkTransport.ConnectWithSimulator(hostId, serverIp, serverPort, 0, out var b, conf); } else { - byte b; - m_ClientConnectionId = NetworkTransport.Connect(m_ClientId, m_ServerIp, m_ServerPort, 0, out b); + m_ClientConnectionId = NetworkTransport.Connect(hostId, serverIp, serverPort, 0, out var b); } - m_Connection = (QSBNetworkConnection)Activator.CreateInstance(m_NetworkConnectionClass); + m_Connection = (QSBNetworkConnection)Activator.CreateInstance(networkConnectionClass); m_Connection.SetHandlers(m_MessageHandlers); - m_Connection.Initialize(m_ServerIp, m_ClientId, m_ClientConnectionId, m_HostTopology); + m_Connection.Initialize(serverIp, hostId, m_ClientConnectionId, hostTopology); } public virtual void Disconnect() @@ -573,10 +496,10 @@ namespace QuantumUNET m_Connection.Disconnect(); m_Connection.Dispose(); m_Connection = null; - if (m_ClientId != -1) + if (hostId != -1) { - NetworkTransport.RemoveHost(m_ClientId); - m_ClientId = -1; + NetworkTransport.RemoveHost(hostId); + hostId = -1; } } } @@ -745,15 +668,15 @@ namespace QuantumUNET { if (LogFilter.logDebug) { - Debug.Log("Shutting down client " + m_ClientId); + Debug.Log("Shutting down client " + hostId); } - if (m_ClientId != -1) + if (hostId != -1) { - NetworkTransport.RemoveHost(m_ClientId); - m_ClientId = -1; + NetworkTransport.RemoveHost(hostId); + hostId = -1; } RemoveClient(this); - if (s_Clients.Count == 0) + if (allClients.Count == 0) { SetActive(false); } @@ -761,7 +684,7 @@ namespace QuantumUNET internal virtual void Update() { - if (m_ClientId != -1) + if (hostId != -1) { switch (m_AsyncConnect) { @@ -788,14 +711,11 @@ namespace QuantumUNET m_StatResetTime = (int)Time.time; } } - int num = 0; + var num = 0; byte b; for (; ; ) { - int num2; - int channelId; - int numBytes; - NetworkEventType networkEventType = NetworkTransport.ReceiveFromHost(m_ClientId, out num2, out channelId, m_MsgBuffer, (int)((ushort)m_MsgBuffer.Length), out numBytes, out b); + var networkEventType = NetworkTransport.ReceiveFromHost(hostId, out var num2, out var channelId, m_MsgBuffer, (ushort)m_MsgBuffer.Length, out var numBytes, out b); if (m_Connection != null) { m_Connection.LastError = (NetworkError)b; @@ -834,7 +754,7 @@ namespace QuantumUNET { if (b != 6) { - GenerateDisconnectError((int)b); + GenerateDisconnectError(b); } } QSBClientScene.HandleClientDisconnect(m_Connection); @@ -858,7 +778,7 @@ namespace QuantumUNET { goto Block_17; } - if (m_ClientId == -1) + if (hostId == -1) { goto Block_19; } @@ -868,10 +788,10 @@ namespace QuantumUNET } } Block_10: - GenerateConnectError((int)b); + GenerateConnectError(b); return; Block_11: - GenerateDataError((int)b); + GenerateDataError(b); return; Block_17: if (LogFilter.logDebug) @@ -916,19 +836,21 @@ namespace QuantumUNET private void GenerateError(int error) { - QSBNetworkMessageDelegate handler = m_MessageHandlers.GetHandler(34); + var handler = m_MessageHandlers.GetHandler(34); if (handler == null) { handler = m_MessageHandlers.GetHandler(34); } if (handler != null) { - QSBErrorMessage errorMessage = new QSBErrorMessage(); - errorMessage.errorCode = error; - byte[] buffer = new byte[200]; - QSBNetworkWriter writer = new QSBNetworkWriter(buffer); + var errorMessage = new QSBErrorMessage + { + errorCode = error + }; + var buffer = new byte[200]; + var writer = new QSBNetworkWriter(buffer); errorMessage.Serialize(writer); - QSBNetworkReader reader = new QSBNetworkReader(buffer); + var reader = new QSBNetworkReader(buffer); handler(new QSBNetworkMessage { MsgType = 34, @@ -986,14 +908,13 @@ namespace QuantumUNET public int GetRTT() { int result; - if (m_ClientId == -1) + if (hostId == -1) { result = 0; } else { - byte b; - result = NetworkTransport.GetCurrentRTT(m_ClientId, m_ClientConnectionId, out b); + result = NetworkTransport.GetCurrentRTT(hostId, m_ClientConnectionId, out var b); } return result; } @@ -1001,7 +922,7 @@ namespace QuantumUNET internal void RegisterSystemHandlers(bool localClient) { QSBClientScene.RegisterSystemHandlers(this, localClient); - this.RegisterHandlerSafe(14, new QSBNetworkMessageDelegate(OnCRC)); + RegisterHandlerSafe(14, new QSBNetworkMessageDelegate(OnCRC)); } private void OnCRC(QSBNetworkMessage netMsg) @@ -1010,33 +931,24 @@ namespace QuantumUNET QSBNetworkCRC.Validate(s_CRCMessage.scripts, numChannels); } - public void RegisterHandler(short msgType, QSBNetworkMessageDelegate handler) - { - m_MessageHandlers.RegisterHandler(msgType, handler); - } + public void RegisterHandler(short msgType, QSBNetworkMessageDelegate handler) => m_MessageHandlers.RegisterHandler(msgType, handler); - public void RegisterHandlerSafe(short msgType, QSBNetworkMessageDelegate handler) - { - m_MessageHandlers.RegisterHandlerSafe(msgType, handler); - } + public void RegisterHandlerSafe(short msgType, QSBNetworkMessageDelegate handler) => m_MessageHandlers.RegisterHandlerSafe(msgType, handler); - public void UnregisterHandler(short msgType) - { - m_MessageHandlers.UnregisterHandler(msgType); - } + public void UnregisterHandler(short msgType) => m_MessageHandlers.UnregisterHandler(msgType); public static Dictionary GetTotalConnectionStats() { - Dictionary dictionary = new Dictionary(); - for (int i = 0; i < s_Clients.Count; i++) + var dictionary = new Dictionary(); + for (var i = 0; i < allClients.Count; i++) { - QSBNetworkClient networkClient = s_Clients[i]; - Dictionary connectionStats = networkClient.GetConnectionStats(); - foreach (short key in connectionStats.Keys) + var networkClient = allClients[i]; + var connectionStats = networkClient.GetConnectionStats(); + foreach (var key in connectionStats.Keys) { if (dictionary.ContainsKey(key)) { - QSBNetworkConnection.PacketStat packetStat = dictionary[key]; + var packetStat = dictionary[key]; packetStat.count += connectionStats[key].count; packetStat.bytes += connectionStats[key].bytes; dictionary[key] = packetStat; @@ -1050,61 +962,46 @@ namespace QuantumUNET return dictionary; } - internal static void AddClient(QSBNetworkClient client) - { - s_Clients.Add(client); - } + internal static void AddClient(QSBNetworkClient client) => allClients.Add(client); - internal static bool RemoveClient(QSBNetworkClient client) - { - return s_Clients.Remove(client); - } + internal static bool RemoveClient(QSBNetworkClient client) => allClients.Remove(client); internal static void UpdateClients() { - for (int i = 0; i < s_Clients.Count; i++) + for (var i = 0; i < allClients.Count; i++) { - if (s_Clients[i] != null) + if (allClients[i] != null) { - s_Clients[i].Update(); + allClients[i].Update(); } else { - s_Clients.RemoveAt(i); + allClients.RemoveAt(i); } } } public static void ShutdownAll() { - while (s_Clients.Count != 0) + while (allClients.Count != 0) { - s_Clients[0].Shutdown(); + allClients[0].Shutdown(); } - s_Clients = new List(); - s_IsActive = false; + allClients = new List(); + active = false; QSBClientScene.Shutdown(); } internal static void SetActive(bool state) { - if (!s_IsActive && state) + if (!active && state) { NetworkTransport.Init(); } - s_IsActive = state; + active = state; } - private Type m_NetworkConnectionClass = typeof(QSBNetworkConnection); - private const int k_MaxEventsPerFrame = 500; - - private static List s_Clients = new List(); - - private static bool s_IsActive; - - private HostTopology m_HostTopology; - private int m_HostPort; private bool m_UseSimulator; @@ -1112,13 +1009,6 @@ namespace QuantumUNET private int m_SimulatedLatency; private float m_PacketLoss; - - private string m_ServerIp = ""; - - private int m_ServerPort; - - private int m_ClientId = -1; - private int m_ClientConnectionId = -1; private int m_StatResetTime; diff --git a/QuantumUNET/QSBNetworkConnection.cs b/QuantumUNET/QSBNetworkConnection.cs index 8f9101c7..b74794ee 100644 --- a/QuantumUNET/QSBNetworkConnection.cs +++ b/QuantumUNET/QSBNetworkConnection.cs @@ -47,7 +47,7 @@ namespace QuantumUNET var bufferSize = packetSize; if (channelQOS.QOS == QosType.ReliableFragmented || channelQOS.QOS == QosType.UnreliableFragmented) { - bufferSize = (int)(hostTopology.DefaultConfig.FragmentSize * 128); + bufferSize = hostTopology.DefaultConfig.FragmentSize * 128; } m_Channels[i] = new QSBChannelBuffer(this, bufferSize, (byte)i, IsReliableQoS(channelQOS.QOS), IsSequencedQoS(channelQOS.QOS)); } @@ -102,8 +102,7 @@ namespace QuantumUNET QSBClientScene.HandleClientDisconnect(this); if (hostId != -1) { - byte b; - NetworkTransport.Disconnect(hostId, connectionId, out b); + NetworkTransport.Disconnect(hostId, connectionId, out var b); RemoveObservers(); } } @@ -182,18 +181,18 @@ namespace QuantumUNET internal void SetPlayerController(QSBPlayerController player) { - while ((int)player.PlayerControllerId >= PlayerControllers.Count) + while (player.PlayerControllerId >= PlayerControllers.Count) { PlayerControllers.Add(new QSBPlayerController()); } - PlayerControllers[(int)player.PlayerControllerId] = player; + PlayerControllers[player.PlayerControllerId] = player; } internal void RemovePlayerController(short playerControllerId) { for (var i = PlayerControllers.Count; i >= 0; i--) { - if ((int)playerControllerId == i && playerControllerId == PlayerControllers[i].PlayerControllerId) + if (playerControllerId == i && playerControllerId == PlayerControllers[i].PlayerControllerId) { PlayerControllers[i] = new QSBPlayerController(); return; @@ -263,15 +262,9 @@ namespace QuantumUNET return SendWriter(m_Writer, channelId); } - public virtual bool SendBytes(byte[] bytes, int numBytes, int channelId) - { - return CheckChannel(channelId) && m_Channels[channelId].SendBytes(bytes, numBytes); - } + public virtual bool SendBytes(byte[] bytes, int numBytes, int channelId) => CheckChannel(channelId) && m_Channels[channelId].SendBytes(bytes, numBytes); - public virtual bool SendWriter(QSBNetworkWriter writer, int channelId) - { - return CheckChannel(channelId) && m_Channels[channelId].SendWriter(writer); - } + public virtual bool SendWriter(QSBNetworkWriter writer, int channelId) => CheckChannel(channelId) && m_Channels[channelId].SendWriter(writer); private void LogSend(byte[] bytes) { @@ -279,7 +272,7 @@ namespace QuantumUNET var num = networkReader.ReadUInt16(); var num2 = networkReader.ReadUInt16(); var stringBuilder = new StringBuilder(); - for (var i = 4; i < (int)(4 + num); i++) + for (var i = 4; i < 4 + num; i++) { stringBuilder.AppendFormat("{0:X2}", bytes[i]); if (i > 150) @@ -348,7 +341,7 @@ namespace QuantumUNET { var num = reader.ReadUInt16(); var num2 = reader.ReadInt16(); - var array = reader.ReadBytes((int)num); + var array = reader.ReadBytes(num); var reader2 = new QSBNetworkReader(array); QSBNetworkMessageDelegate networkMessageDelegate = null; if (m_MessageHandlersDict.ContainsKey(num2)) diff --git a/QuantumUNET/QSBNetworkScene.cs b/QuantumUNET/QSBNetworkScene.cs index d3d94d17..782a8436 100644 --- a/QuantumUNET/QSBNetworkScene.cs +++ b/QuantumUNET/QSBNetworkScene.cs @@ -7,21 +7,13 @@ namespace QuantumUNET { internal class QSBNetworkScene { - private Dictionary m_LocalObjects = new Dictionary(); - internal static Dictionary guidToPrefab { get; } = new Dictionary(); internal static Dictionary spawnHandlers { get; } = new Dictionary(); internal static Dictionary unspawnHandlers { get; } = new Dictionary(); - internal Dictionary localObjects - { - get - { - return m_LocalObjects; - } - } + internal Dictionary localObjects { get; } = new Dictionary(); internal void Shutdown() { @@ -80,10 +72,7 @@ namespace QuantumUNET return result; } - internal bool RemoveLocalObject(NetworkInstanceId netId) - { - return localObjects.Remove(netId); - } + internal bool RemoveLocalObject(NetworkInstanceId netId) => localObjects.Remove(netId); internal bool RemoveLocalObjectAndDestroy(NetworkInstanceId netId) { @@ -91,7 +80,7 @@ namespace QuantumUNET if (localObjects.ContainsKey(netId)) { var networkIdentity = localObjects[netId]; - UnityEngine.Object.Destroy(networkIdentity.gameObject); + Object.Destroy(networkIdentity.gameObject); result = localObjects.Remove(netId); } else @@ -101,10 +90,7 @@ namespace QuantumUNET return result; } - internal void ClearLocalObjects() - { - localObjects.Clear(); - } + internal void ClearLocalObjects() => localObjects.Clear(); internal static void RegisterPrefab(GameObject prefab, NetworkHash128 newAssetId) { @@ -273,7 +259,7 @@ namespace QuantumUNET { if (networkIdentity.SceneId.IsEmpty()) { - UnityEngine.Object.Destroy(networkIdentity.gameObject); + Object.Destroy(networkIdentity.gameObject); } else { diff --git a/QuantumUNET/QSBNetworkServer.cs b/QuantumUNET/QSBNetworkServer.cs index 313e6e9d..702a465c 100644 --- a/QuantumUNET/QSBNetworkServer.cs +++ b/QuantumUNET/QSBNetworkServer.cs @@ -21,61 +21,19 @@ namespace QuantumUNET m_SimpleServerSimple = new ServerSimpleWrapper(this); } - public static List localConnections - { - get - { - return instance.m_LocalConnectionsFakeList; - } - } + public static List localConnections => instance.m_LocalConnectionsFakeList; - public static int listenPort - { - get - { - return instance.m_SimpleServerSimple.listenPort; - } - } + public static int listenPort => instance.m_SimpleServerSimple.listenPort; - public static int serverHostId - { - get - { - return instance.m_SimpleServerSimple.serverHostId; - } - } + public static int serverHostId => instance.m_SimpleServerSimple.serverHostId; - public static ReadOnlyCollection connections - { - get - { - return instance.m_SimpleServerSimple.connections; - } - } + public static ReadOnlyCollection connections => instance.m_SimpleServerSimple.connections; - public static Dictionary handlers - { - get - { - return instance.m_SimpleServerSimple.handlers; - } - } + public static Dictionary handlers => instance.m_SimpleServerSimple.handlers; - public static HostTopology hostTopology - { - get - { - return instance.m_SimpleServerSimple.hostTopology; - } - } + public static HostTopology hostTopology => instance.m_SimpleServerSimple.hostTopology; - public static Dictionary objects - { - get - { - return instance.m_NetworkScene.localObjects; - } - } + public static Dictionary objects => instance.m_NetworkScene.localObjects; public static bool dontListen { get; set; } @@ -112,21 +70,9 @@ namespace QuantumUNET public static bool active { get; private set; } - public static bool localClientActive - { - get - { - return instance.m_LocalClientActive; - } - } + public static bool localClientActive => instance.m_LocalClientActive; - public static int numChannels - { - get - { - return instance.m_SimpleServerSimple.hostTopology.DefaultConfig.ChannelCount; - } - } + public static int numChannels => instance.m_SimpleServerSimple.hostTopology.DefaultConfig.ChannelCount; public static float maxDelay { @@ -140,28 +86,13 @@ namespace QuantumUNET } } - public static Type networkConnectionClass - { - get - { - return instance.m_SimpleServerSimple.networkConnectionClass; - } - } + public static Type networkConnectionClass => instance.m_SimpleServerSimple.networkConnectionClass; - public static void SetNetworkConnectionClass() where T : QSBNetworkConnection - { - instance.m_SimpleServerSimple.SetNetworkConnectionClass(); - } + public static void SetNetworkConnectionClass() where T : QSBNetworkConnection => instance.m_SimpleServerSimple.SetNetworkConnectionClass(); - public static bool Configure(ConnectionConfig config, int maxConnections) - { - return instance.m_SimpleServerSimple.Configure(config, maxConnections); - } + public static bool Configure(ConnectionConfig config, int maxConnections) => instance.m_SimpleServerSimple.Configure(config, maxConnections); - public static bool Configure(HostTopology topology) - { - return instance.m_SimpleServerSimple.Configure(topology); - } + public static bool Configure(HostTopology topology) => instance.m_SimpleServerSimple.Configure(topology); public static void Reset() { @@ -200,10 +131,7 @@ namespace QuantumUNET maxPacketSize = hostTopology.DefaultConfig.PacketSize; } - public static void ListenRelay(string relayIp, int relayPort, NetworkID netGuid, SourceID sourceId, NodeID nodeId) - { - instance.InternalListenRelay(relayIp, relayPort, netGuid, sourceId, nodeId); - } + public static void ListenRelay(string relayIp, int relayPort, NetworkID netGuid, SourceID sourceId, NodeID nodeId) => instance.InternalListenRelay(relayIp, relayPort, netGuid, sourceId, nodeId); private void InternalListenRelay(string relayIp, int relayPort, NetworkID netGuid, SourceID sourceId, NodeID nodeId) { @@ -212,15 +140,9 @@ namespace QuantumUNET RegisterMessageHandlers(); } - public static bool Listen(int serverPort) - { - return instance.InternalListen(null, serverPort); - } + public static bool Listen(int serverPort) => instance.InternalListen(null, serverPort); - public static bool Listen(string ipAddress, int serverPort) - { - return instance.InternalListen(ipAddress, serverPort); - } + public static bool Listen(string ipAddress, int serverPort) => instance.InternalListen(ipAddress, serverPort); internal bool InternalListen(string ipAddress, int serverPort) { @@ -585,10 +507,7 @@ namespace QuantumUNET return result; } - public static void DisconnectAll() - { - instance.InternalDisconnectAll(); - } + public static void DisconnectAll() => instance.InternalDisconnectAll(); internal void InternalDisconnectAll() { @@ -690,10 +609,7 @@ namespace QuantumUNET conn.Dispose(); } - private void OnData(QSBNetworkConnection conn, int receivedSize, int channelId) - { - conn.TransportReceive(m_SimpleServerSimple.messageBuffer, receivedSize, channelId); - } + private void OnData(QSBNetworkConnection conn, int receivedSize, int channelId) => conn.TransportReceive(m_SimpleServerSimple.messageBuffer, receivedSize, channelId); private void GenerateConnectError(int error) { @@ -734,8 +650,10 @@ namespace QuantumUNET { if (handlers.ContainsKey(34)) { - var errorMessage = new QSBErrorMessage(); - errorMessage.errorCode = error; + var errorMessage = new QSBErrorMessage + { + errorCode = error + }; var writer = new QSBNetworkWriter(); errorMessage.Serialize(writer); var reader = new QSBNetworkReader(writer); @@ -743,25 +661,13 @@ namespace QuantumUNET } } - public static void RegisterHandler(short msgType, QSBNetworkMessageDelegate handler) - { - instance.m_SimpleServerSimple.RegisterHandler(msgType, handler); - } + public static void RegisterHandler(short msgType, QSBNetworkMessageDelegate handler) => instance.m_SimpleServerSimple.RegisterHandler(msgType, handler); - public static void UnregisterHandler(short msgType) - { - instance.m_SimpleServerSimple.UnregisterHandler(msgType); - } + public static void UnregisterHandler(short msgType) => instance.m_SimpleServerSimple.UnregisterHandler(msgType); - public static void ClearHandlers() - { - instance.m_SimpleServerSimple.ClearHandlers(); - } + public static void ClearHandlers() => instance.m_SimpleServerSimple.ClearHandlers(); - public static void ClearSpawners() - { - QSBNetworkScene.ClearSpawners(); - } + public static void ClearSpawners() => QSBNetworkScene.ClearSpawners(); public static void GetStatsOut(out int numMsgs, out int numBufferedMsgs, out int numBytes, out int lastBufferedPerSecond) { @@ -774,11 +680,7 @@ namespace QuantumUNET var networkConnection = connections[i]; if (networkConnection != null) { - int num; - int num2; - int num3; - int num4; - networkConnection.GetStatsOut(out num, out num2, out num3, out num4); + networkConnection.GetStatsOut(out var num, out var num2, out var num3, out var num4); numMsgs += num; numBufferedMsgs += num2; numBytes += num3; @@ -796,9 +698,7 @@ namespace QuantumUNET var networkConnection = connections[i]; if (networkConnection != null) { - int num; - int num2; - networkConnection.GetStatsIn(out num, out num2); + networkConnection.GetStatsIn(out var num, out var num2); numMsgs += num; numBytes += num2; } @@ -846,16 +746,12 @@ namespace QuantumUNET } } - public static bool AddPlayerForConnection(QSBNetworkConnection conn, GameObject player, short playerControllerId) - { - return instance.InternalAddPlayerForConnection(conn, player, playerControllerId); - } + public static bool AddPlayerForConnection(QSBNetworkConnection conn, GameObject player, short playerControllerId) => instance.InternalAddPlayerForConnection(conn, player, playerControllerId); internal bool InternalAddPlayerForConnection(QSBNetworkConnection conn, GameObject playerGameObject, short playerControllerId) { - QSBNetworkIdentity networkIdentity; bool result; - if (!GetNetworkIdentity(playerGameObject, out networkIdentity)) + if (!GetNetworkIdentity(playerGameObject, out var networkIdentity)) { if (LogFilter.logError) { @@ -872,9 +768,8 @@ namespace QuantumUNET } else { - QSBPlayerController playerController = null; GameObject x = null; - if (conn.GetPlayerController(playerControllerId, out playerController)) + if (conn.GetPlayerController(playerControllerId, out var playerController)) { x = playerController.Gameobject; } @@ -963,9 +858,8 @@ namespace QuantumUNET private bool SetupLocalPlayerForConnection(QSBNetworkConnection conn, QSBNetworkIdentity uv, QSBPlayerController newPlayerController) { Debug.Log("NetworkServer SetupLocalPlayerForConnection netID:" + uv.NetId); - var ulocalConnectionToClient = conn as QSBULocalConnectionToClient; bool result; - if (ulocalConnectionToClient != null) + if (conn is QSBULocalConnectionToClient ulocalConnectionToClient) { Debug.Log("NetworkServer AddPlayer handling ULocalConnectionToClient"); if (uv.NetId.IsEmpty()) @@ -1002,9 +896,8 @@ namespace QuantumUNET internal bool InternalReplacePlayerForConnection(QSBNetworkConnection conn, GameObject playerGameObject, short playerControllerId) { - QSBNetworkIdentity networkIdentity; bool result; - if (!GetNetworkIdentity(playerGameObject, out networkIdentity)) + if (!GetNetworkIdentity(playerGameObject, out var networkIdentity)) { if (LogFilter.logError) { @@ -1019,8 +912,7 @@ namespace QuantumUNET else { Debug.Log("NetworkServer ReplacePlayer"); - QSBPlayerController playerController; - if (conn.GetPlayerController(playerControllerId, out playerController)) + if (conn.GetPlayerController(playerControllerId, out var playerController)) { playerController.UnetView.SetNotLocalPlayer(); playerController.UnetView.ClearClientOwner(); @@ -1072,10 +964,7 @@ namespace QuantumUNET return result; } - public static void SetClientReady(QSBNetworkConnection conn) - { - instance.SetClientReadyInternal(conn); - } + public static void SetClientReady(QSBNetworkConnection conn) => instance.SetClientReadyInternal(conn); internal void SetClientReadyInternal(QSBNetworkConnection conn) { @@ -1100,15 +989,14 @@ namespace QuantumUNET } } conn.isReady = true; - var ulocalConnectionToClient = conn as QSBULocalConnectionToClient; - if (ulocalConnectionToClient != null) + if (conn is QSBULocalConnectionToClient ulocalConnectionToClient) { Debug.Log("NetworkServer Ready handling ULocalConnectionToClient"); foreach (var networkIdentity in objects.Values) { if (networkIdentity != null && networkIdentity.gameObject != null) { - bool flag = networkIdentity.OnCheckObserver(conn); + var flag = networkIdentity.OnCheckObserver(conn); if (flag) { networkIdentity.AddObserver(conn); @@ -1133,8 +1021,10 @@ namespace QuantumUNET conn.connectionId })); } - var objectSpawnFinishedMessage = new QSBObjectSpawnFinishedMessage(); - objectSpawnFinishedMessage.State = 0U; + var objectSpawnFinishedMessage = new QSBObjectSpawnFinishedMessage + { + State = 0U + }; conn.Send(12, objectSpawnFinishedMessage); foreach (var networkIdentity2 in objects.Values) { @@ -1157,7 +1047,7 @@ namespace QuantumUNET networkIdentity2.NetId })); } - bool flag2 = networkIdentity2.OnCheckObserver(conn); + var flag2 = networkIdentity2.OnCheckObserver(conn); if (flag2) { networkIdentity2.AddObserver(conn); @@ -1198,10 +1088,7 @@ namespace QuantumUNET } } - public static void SetClientNotReady(QSBNetworkConnection conn) - { - instance.InternalSetClientNotReady(conn); - } + public static void SetClientNotReady(QSBNetworkConnection conn) => instance.InternalSetClientNotReady(conn); internal void InternalSetClientNotReady(QSBNetworkConnection conn) { @@ -1230,8 +1117,7 @@ namespace QuantumUNET private static void OnRemovePlayerMessage(QSBNetworkMessage netMsg) { netMsg.ReadMessage(s_RemovePlayerMessage); - QSBPlayerController playerController = null; - netMsg.Connection.GetPlayerController(s_RemovePlayerMessage.PlayerControllerId, out playerController); + netMsg.Connection.GetPlayerController(s_RemovePlayerMessage.PlayerControllerId, out var playerController); if (playerController != null) { netMsg.Connection.RemovePlayerController(s_RemovePlayerMessage.PlayerControllerId); @@ -1302,12 +1188,11 @@ namespace QuantumUNET internal void SpawnObject(GameObject obj) { - QSBNetworkIdentity networkIdentity; if (!active) { ModConsole.OwmlConsole.WriteLine("Error - SpawnObject for " + obj + ", NetworkServer is not active. Cannot spawn objects without an active server."); } - else if (!GetNetworkIdentity(obj, out networkIdentity)) + else if (!GetNetworkIdentity(obj, out var networkIdentity)) { Debug.LogError(string.Concat(new object[] { @@ -1331,11 +1216,13 @@ namespace QuantumUNET { if (uv.SceneId.IsEmpty()) { - var objectSpawnMessage = new QSBObjectSpawnMessage(); - objectSpawnMessage.NetId = uv.NetId; - objectSpawnMessage.assetId = uv.AssetId; - objectSpawnMessage.Position = uv.transform.position; - objectSpawnMessage.Rotation = uv.transform.rotation; + var objectSpawnMessage = new QSBObjectSpawnMessage + { + NetId = uv.NetId, + assetId = uv.AssetId, + Position = uv.transform.position, + Rotation = uv.transform.rotation + }; var networkWriter = new QSBNetworkWriter(); uv.UNetSerializeAllVars(networkWriter); if (networkWriter.Position > 0) @@ -1353,10 +1240,12 @@ namespace QuantumUNET } else { - var objectSpawnSceneMessage = new QSBObjectSpawnSceneMessage(); - objectSpawnSceneMessage.NetId = uv.NetId; - objectSpawnSceneMessage.SceneId = uv.SceneId; - objectSpawnSceneMessage.Position = uv.transform.position; + var objectSpawnSceneMessage = new QSBObjectSpawnSceneMessage + { + NetId = uv.NetId, + SceneId = uv.SceneId, + Position = uv.transform.position + }; var networkWriter2 = new QSBNetworkWriter(); uv.UNetSerializeAllVars(networkWriter2); if (networkWriter2.Position > 0) @@ -1416,30 +1305,25 @@ namespace QuantumUNET private static void UnSpawnObject(GameObject obj) { - QSBNetworkIdentity uv; if (obj == null) { Debug.Log("NetworkServer UnspawnObject is null"); } - else if (GetNetworkIdentity(obj, out uv)) + else if (GetNetworkIdentity(obj, out var uv)) { UnSpawnObject(uv); } } - private static void UnSpawnObject(QSBNetworkIdentity uv) - { - DestroyObject(uv, false); - } + private static void UnSpawnObject(QSBNetworkIdentity uv) => DestroyObject(uv, false); private static void DestroyObject(GameObject obj) { - QSBNetworkIdentity uv; if (obj == null) { Debug.Log("NetworkServer DestroyObject is null"); } - else if (GetNetworkIdentity(obj, out uv)) + else if (GetNetworkIdentity(obj, out var uv)) { DestroyObject(uv, true); } @@ -1459,8 +1343,10 @@ namespace QuantumUNET { uv.ClientAuthorityOwner.RemoveOwnedObject(uv); } - var objectDestroyMessage = new QSBObjectDestroyMessage(); - objectDestroyMessage.NetId = uv.NetId; + var objectDestroyMessage = new QSBObjectDestroyMessage + { + NetId = uv.NetId + }; SendToObservers(uv.gameObject, 1, objectDestroyMessage); uv.ClearObservers(); if (QSBNetworkClient.active && instance.m_LocalClientActive) @@ -1475,10 +1361,7 @@ namespace QuantumUNET uv.MarkForReset(); } - public static void ClearLocalObjects() - { - objects.Clear(); - } + public static void ClearLocalObjects() => objects.Clear(); public static void Spawn(GameObject obj) { @@ -1488,10 +1371,7 @@ namespace QuantumUNET } } - private static bool CheckForPrefab(GameObject obj) - { - return false; - } + private static bool CheckForPrefab(GameObject obj) => false; private static bool VerifyCanSpawn(GameObject obj) { @@ -1560,8 +1440,7 @@ namespace QuantumUNET { if (VerifyCanSpawn(obj)) { - QSBNetworkIdentity networkIdentity; - if (GetNetworkIdentity(obj, out networkIdentity)) + if (GetNetworkIdentity(obj, out var networkIdentity)) { networkIdentity.SetDynamicAssetId(assetId); } @@ -1569,15 +1448,9 @@ namespace QuantumUNET } } - public static void Destroy(GameObject obj) - { - DestroyObject(obj); - } + public static void Destroy(GameObject obj) => DestroyObject(obj); - public static void UnSpawn(GameObject obj) - { - UnSpawnObject(obj); - } + public static void UnSpawn(GameObject obj) => UnSpawnObject(obj); internal bool InvokeBytes(QSBULocalConnectionToServer conn, byte[] buffer, int numBytes, int channelId) { @@ -1625,15 +1498,9 @@ namespace QuantumUNET return result; } - public static GameObject FindLocalObject(NetworkInstanceId netId) - { - return instance.m_NetworkScene.FindLocalObject(netId); - } + public static GameObject FindLocalObject(NetworkInstanceId netId) => instance.m_NetworkScene.FindLocalObject(netId); - private static bool ValidateSceneObject(QSBNetworkIdentity netId) - { - return netId.gameObject.hideFlags != HideFlags.NotEditable && netId.gameObject.hideFlags != HideFlags.HideAndDontSave && !netId.SceneId.IsEmpty(); - } + private static bool ValidateSceneObject(QSBNetworkIdentity netId) => netId.gameObject.hideFlags != HideFlags.NotEditable && netId.gameObject.hideFlags != HideFlags.HideAndDontSave && !netId.SceneId.IsEmpty(); public static bool SpawnObjects() { @@ -1684,7 +1551,7 @@ namespace QuantumUNET { var crcmessage = new QSBCRCMessage(); var list = new List(); - foreach (string text in QSBNetworkCRC.singleton.scripts.Keys) + foreach (var text in QSBNetworkCRC.singleton.scripts.Keys) { list.Add(new QSBCRCMessageEntry { @@ -1733,35 +1600,17 @@ namespace QuantumUNET m_Server = server; } - public override void OnConnectError(int connectionId, byte error) - { - m_Server.GenerateConnectError((int)error); - } + public override void OnConnectError(int connectionId, byte error) => m_Server.GenerateConnectError(error); - public override void OnDataError(QSBNetworkConnection conn, byte error) - { - m_Server.GenerateDataError(conn, (int)error); - } + public override void OnDataError(QSBNetworkConnection conn, byte error) => m_Server.GenerateDataError(conn, error); - public override void OnDisconnectError(QSBNetworkConnection conn, byte error) - { - m_Server.GenerateDisconnectError(conn, (int)error); - } + public override void OnDisconnectError(QSBNetworkConnection conn, byte error) => m_Server.GenerateDisconnectError(conn, error); - public override void OnConnected(QSBNetworkConnection conn) - { - m_Server.OnConnected(conn); - } + public override void OnConnected(QSBNetworkConnection conn) => m_Server.OnConnected(conn); - public override void OnDisconnected(QSBNetworkConnection conn) - { - m_Server.OnDisconnected(conn); - } + public override void OnDisconnected(QSBNetworkConnection conn) => m_Server.OnDisconnected(conn); - public override void OnData(QSBNetworkConnection conn, int receivedSize, int channelId) - { - m_Server.OnData(conn, receivedSize, channelId); - } + public override void OnData(QSBNetworkConnection conn, int receivedSize, int channelId) => m_Server.OnData(conn, receivedSize, channelId); private QSBNetworkServer m_Server; } diff --git a/QuantumUNET/QSBNetworkServerSimple.cs b/QuantumUNET/QSBNetworkServerSimple.cs index 5d9a1545..7a650723 100644 --- a/QuantumUNET/QSBNetworkServerSimple.cs +++ b/QuantumUNET/QSBNetworkServerSimple.cs @@ -12,112 +12,43 @@ namespace QuantumUNET { public QSBNetworkServerSimple() { - this.m_ConnectionsReadOnly = new ReadOnlyCollection(this.m_Connections); + connections = new ReadOnlyCollection(m_Connections); } - public int listenPort - { - get - { - return this.m_ListenPort; - } - set - { - this.m_ListenPort = value; - } - } + public int listenPort { get; set; } - public int serverHostId - { - get - { - return this.m_ServerHostId; - } - set - { - this.m_ServerHostId = value; - } - } + public int serverHostId { get; set; } = -1; - public HostTopology hostTopology - { - get - { - return this.m_HostTopology; - } - } + public HostTopology hostTopology { get; private set; } - public bool useWebSockets - { - get - { - return this.m_UseWebSockets; - } - set - { - this.m_UseWebSockets = value; - } - } + public bool useWebSockets { get; set; } - public ReadOnlyCollection connections - { - get - { - return this.m_ConnectionsReadOnly; - } - } + public ReadOnlyCollection connections { get; } - public Dictionary handlers - { - get - { - return this.m_MessageHandlers.GetHandlers(); - } - } + public Dictionary handlers => m_MessageHandlers.GetHandlers(); - public byte[] messageBuffer - { - get - { - return this.m_MsgBuffer; - } - } + public byte[] messageBuffer { get; private set; } = null; - public NetworkReader messageReader - { - get - { - return this.m_MsgReader; - } - } + public NetworkReader messageReader { get; private set; } = null; - public Type networkConnectionClass - { - get - { - return this.m_NetworkConnectionClass; - } - } + public Type networkConnectionClass { get; private set; } = typeof(QSBNetworkConnection); - public void SetNetworkConnectionClass() where T : QSBNetworkConnection - { - this.m_NetworkConnectionClass = typeof(T); - } + public void SetNetworkConnectionClass() where T : QSBNetworkConnection => networkConnectionClass = typeof(T); public virtual void Initialize() { - if (!this.m_Initialized) + if (!m_Initialized) { - this.m_Initialized = true; + m_Initialized = true; NetworkTransport.Init(); - this.m_MsgBuffer = new byte[65535]; - this.m_MsgReader = new NetworkReader(this.m_MsgBuffer); - if (this.m_HostTopology == null) + messageBuffer = new byte[65535]; + messageReader = new NetworkReader(messageBuffer); + if (hostTopology == null) { - ConnectionConfig connectionConfig = new ConnectionConfig(); + var connectionConfig = new ConnectionConfig(); connectionConfig.AddChannel(QosType.ReliableSequenced); connectionConfig.AddChannel(QosType.Unreliable); - this.m_HostTopology = new HostTopology(connectionConfig, 8); + hostTopology = new HostTopology(connectionConfig, 8); } if (LogFilter.logDebug) { @@ -128,30 +59,30 @@ namespace QuantumUNET public bool Configure(ConnectionConfig config, int maxConnections) { - HostTopology topology = new HostTopology(config, maxConnections); - return this.Configure(topology); + var topology = new HostTopology(config, maxConnections); + return Configure(topology); } public bool Configure(HostTopology topology) { - this.m_HostTopology = topology; + hostTopology = topology; return true; } public bool Listen(string ipAddress, int serverListenPort) { - this.Initialize(); - this.m_ListenPort = serverListenPort; - if (this.m_UseWebSockets) + Initialize(); + listenPort = serverListenPort; + if (useWebSockets) { - this.m_ServerHostId = NetworkTransport.AddWebsocketHost(this.m_HostTopology, serverListenPort, ipAddress); + serverHostId = NetworkTransport.AddWebsocketHost(hostTopology, serverListenPort, ipAddress); } else { - this.m_ServerHostId = NetworkTransport.AddHost(this.m_HostTopology, serverListenPort, ipAddress); + serverHostId = NetworkTransport.AddHost(hostTopology, serverListenPort, ipAddress); } bool result; - if (this.m_ServerHostId == -1) + if (serverHostId == -1) { result = false; } @@ -164,7 +95,7 @@ namespace QuantumUNET "NetworkServerSimple listen: ", ipAddress, ":", - this.m_ListenPort + listenPort })); } result = true; @@ -172,26 +103,23 @@ namespace QuantumUNET return result; } - public bool Listen(int serverListenPort) - { - return this.Listen(serverListenPort, this.m_HostTopology); - } + public bool Listen(int serverListenPort) => Listen(serverListenPort, hostTopology); public bool Listen(int serverListenPort, HostTopology topology) { - this.m_HostTopology = topology; - this.Initialize(); - this.m_ListenPort = serverListenPort; - if (this.m_UseWebSockets) + hostTopology = topology; + Initialize(); + listenPort = serverListenPort; + if (useWebSockets) { - this.m_ServerHostId = NetworkTransport.AddWebsocketHost(this.m_HostTopology, serverListenPort); + serverHostId = NetworkTransport.AddWebsocketHost(hostTopology, serverListenPort); } else { - this.m_ServerHostId = NetworkTransport.AddHost(this.m_HostTopology, serverListenPort); + serverHostId = NetworkTransport.AddHost(hostTopology, serverListenPort); } bool result; - if (this.m_ServerHostId == -1) + if (serverHostId == -1) { result = false; } @@ -199,7 +127,7 @@ namespace QuantumUNET { if (LogFilter.logDebug) { - Debug.Log("NetworkServerSimple listen " + this.m_ListenPort); + Debug.Log("NetworkServerSimple listen " + listenPort); } result = true; } @@ -208,19 +136,18 @@ namespace QuantumUNET public void ListenRelay(string relayIp, int relayPort, NetworkID netGuid, SourceID sourceId, NodeID nodeId) { - this.Initialize(); - this.m_ServerHostId = NetworkTransport.AddHost(this.m_HostTopology, this.listenPort); + Initialize(); + serverHostId = NetworkTransport.AddHost(hostTopology, listenPort); if (LogFilter.logDebug) { - Debug.Log("Server Host Slot Id: " + this.m_ServerHostId); + Debug.Log("Server Host Slot Id: " + serverHostId); } - this.Update(); - byte b; - NetworkTransport.ConnectAsNetworkHost(this.m_ServerHostId, relayIp, relayPort, netGuid, sourceId, nodeId, out b); - this.m_RelaySlotId = 0; + Update(); + NetworkTransport.ConnectAsNetworkHost(serverHostId, relayIp, relayPort, netGuid, sourceId, nodeId, out var b); + m_RelaySlotId = 0; if (LogFilter.logDebug) { - Debug.Log("Relay Slot Id: " + this.m_RelaySlotId); + Debug.Log("Relay Slot Id: " + m_RelaySlotId); } } @@ -230,35 +157,23 @@ namespace QuantumUNET { Debug.Log("NetworkServerSimple stop "); } - NetworkTransport.RemoveHost(this.m_ServerHostId); - this.m_ServerHostId = -1; + NetworkTransport.RemoveHost(serverHostId); + serverHostId = -1; } - internal void RegisterHandlerSafe(short msgType, QSBNetworkMessageDelegate handler) - { - m_MessageHandlers.RegisterHandlerSafe(msgType, handler); - } + internal void RegisterHandlerSafe(short msgType, QSBNetworkMessageDelegate handler) => m_MessageHandlers.RegisterHandlerSafe(msgType, handler); - public void RegisterHandler(short msgType, QSBNetworkMessageDelegate handler) - { - this.m_MessageHandlers.RegisterHandler(msgType, handler); - } + public void RegisterHandler(short msgType, QSBNetworkMessageDelegate handler) => m_MessageHandlers.RegisterHandler(msgType, handler); - public void UnregisterHandler(short msgType) - { - this.m_MessageHandlers.UnregisterHandler(msgType); - } + public void UnregisterHandler(short msgType) => m_MessageHandlers.UnregisterHandler(msgType); - public void ClearHandlers() - { - this.m_MessageHandlers.ClearMessageHandlers(); - } + public void ClearHandlers() => m_MessageHandlers.ClearMessageHandlers(); public void UpdateConnections() { - for (int i = 0; i < this.m_Connections.Count; i++) + for (var i = 0; i < m_Connections.Count; i++) { - QSBNetworkConnection networkConnection = this.m_Connections[i]; + var networkConnection = m_Connections[i]; if (networkConnection != null) { networkConnection.FlushChannels(); @@ -268,13 +183,12 @@ namespace QuantumUNET public void Update() { - if (this.m_ServerHostId != -1) + if (serverHostId != -1) { NetworkEventType networkEventType; - if (this.m_RelaySlotId != -1) + if (m_RelaySlotId != -1) { - byte b; - networkEventType = NetworkTransport.ReceiveRelayEventFromHost(this.m_ServerHostId, out b); + networkEventType = NetworkTransport.ReceiveRelayEventFromHost(serverHostId, out var b); if (networkEventType != NetworkEventType.Nothing) { if (LogFilter.logDebug) @@ -299,17 +213,13 @@ namespace QuantumUNET } do { - byte b; - int connectionId; - int channelId; - int receivedSize; - networkEventType = NetworkTransport.ReceiveFromHost(this.m_ServerHostId, out connectionId, out channelId, this.m_MsgBuffer, this.m_MsgBuffer.Length, out receivedSize, out b); + networkEventType = NetworkTransport.ReceiveFromHost(serverHostId, out var connectionId, out var channelId, messageBuffer, messageBuffer.Length, out var receivedSize, out var b); if (networkEventType != NetworkEventType.Nothing) { Debug.Log(string.Concat(new object[] { "Server event: host=", - this.m_ServerHostId, + serverHostId, " event=", networkEventType, " error=", @@ -319,15 +229,15 @@ namespace QuantumUNET switch (networkEventType) { case NetworkEventType.DataEvent: - this.HandleData(connectionId, channelId, receivedSize, b); + HandleData(connectionId, channelId, receivedSize, b); break; case NetworkEventType.ConnectEvent: - this.HandleConnect(connectionId, b); + HandleConnect(connectionId, b); break; case NetworkEventType.DisconnectEvent: - this.HandleDisconnect(connectionId, b); + HandleDisconnect(connectionId, b); break; case NetworkEventType.Nothing: @@ -342,39 +252,39 @@ namespace QuantumUNET } } while (networkEventType != NetworkEventType.Nothing); - this.UpdateConnections(); + UpdateConnections(); } } public QSBNetworkConnection FindConnection(int connectionId) { QSBNetworkConnection result; - if (connectionId < 0 || connectionId >= this.m_Connections.Count) + if (connectionId < 0 || connectionId >= m_Connections.Count) { result = null; } else { - result = this.m_Connections[connectionId]; + result = m_Connections[connectionId]; } return result; } public bool SetConnectionAtIndex(QSBNetworkConnection conn) { - while (this.m_Connections.Count <= conn.connectionId) + while (m_Connections.Count <= conn.connectionId) { - this.m_Connections.Add(null); + m_Connections.Add(null); } bool result; - if (this.m_Connections[conn.connectionId] != null) + if (m_Connections[conn.connectionId] != null) { result = false; } else { - this.m_Connections[conn.connectionId] = conn; - conn.SetHandlers(this.m_MessageHandlers); + m_Connections[conn.connectionId] = conn; + conn.SetHandlers(m_MessageHandlers); result = true; } return result; @@ -383,13 +293,13 @@ namespace QuantumUNET public bool RemoveConnectionAtIndex(int connectionId) { bool result; - if (connectionId < 0 || connectionId >= this.m_Connections.Count) + if (connectionId < 0 || connectionId >= m_Connections.Count) { result = false; } else { - this.m_Connections[connectionId] = null; + m_Connections[connectionId] = null; result = true; } return result; @@ -403,26 +313,21 @@ namespace QuantumUNET } if (error != 0) { - this.OnConnectError(connectionId, error); + OnConnectError(connectionId, error); } else { - string networkAddress; - int num; - NetworkID networkID; - NodeID nodeID; - byte lastError; - NetworkTransport.GetConnectionInfo(this.m_ServerHostId, connectionId, out networkAddress, out num, out networkID, out nodeID, out lastError); - QSBNetworkConnection networkConnection = (QSBNetworkConnection)Activator.CreateInstance(this.m_NetworkConnectionClass); - networkConnection.SetHandlers(this.m_MessageHandlers); - networkConnection.Initialize(networkAddress, this.m_ServerHostId, connectionId, this.m_HostTopology); + NetworkTransport.GetConnectionInfo(serverHostId, connectionId, out var networkAddress, out var num, out var networkID, out var nodeID, out var lastError); + var networkConnection = (QSBNetworkConnection)Activator.CreateInstance(networkConnectionClass); + networkConnection.SetHandlers(m_MessageHandlers); + networkConnection.Initialize(networkAddress, serverHostId, connectionId, hostTopology); networkConnection.LastError = (NetworkError)lastError; - while (this.m_Connections.Count <= connectionId) + while (m_Connections.Count <= connectionId) { - this.m_Connections.Add(null); + m_Connections.Add(null); } - this.m_Connections[connectionId] = networkConnection; - this.OnConnected(networkConnection); + m_Connections[connectionId] = networkConnection; + OnConnected(networkConnection); } } @@ -432,7 +337,7 @@ namespace QuantumUNET { Debug.Log("NetworkServerSimple disconnect client:" + connectionId); } - QSBNetworkConnection networkConnection = this.FindConnection(connectionId); + var networkConnection = FindConnection(connectionId); if (networkConnection != null) { networkConnection.LastError = (NetworkError)error; @@ -440,7 +345,7 @@ namespace QuantumUNET { if (error != 6) { - this.m_Connections[connectionId] = null; + m_Connections[connectionId] = null; if (LogFilter.logError) { Debug.LogError(string.Concat(new object[] @@ -451,23 +356,23 @@ namespace QuantumUNET (NetworkError)error })); } - this.OnDisconnectError(networkConnection, error); + OnDisconnectError(networkConnection, error); return; } } networkConnection.Disconnect(); - this.m_Connections[connectionId] = null; + m_Connections[connectionId] = null; if (LogFilter.logDebug) { Debug.Log("Server lost client:" + connectionId); } - this.OnDisconnected(networkConnection); + OnDisconnected(networkConnection); } } private void HandleData(int connectionId, int channelId, int receivedSize, byte error) { - QSBNetworkConnection networkConnection = this.FindConnection(connectionId); + var networkConnection = FindConnection(connectionId); if (networkConnection == null) { if (LogFilter.logError) @@ -480,19 +385,19 @@ namespace QuantumUNET networkConnection.LastError = (NetworkError)error; if (error != 0) { - this.OnDataError(networkConnection, error); + OnDataError(networkConnection, error); } else { - this.m_MsgReader.SeekZero(); - this.OnData(networkConnection, receivedSize, channelId); + messageReader.SeekZero(); + OnData(networkConnection, receivedSize, channelId); } } } public void SendBytesTo(int connectionId, byte[] bytes, int numBytes, int channelId) { - QSBNetworkConnection networkConnection = this.FindConnection(connectionId); + var networkConnection = FindConnection(connectionId); if (networkConnection != null) { networkConnection.SendBytes(bytes, numBytes, channelId); @@ -501,7 +406,7 @@ namespace QuantumUNET public void SendWriterTo(int connectionId, QSBNetworkWriter writer, int channelId) { - QSBNetworkConnection networkConnection = this.FindConnection(connectionId); + var networkConnection = FindConnection(connectionId); if (networkConnection != null) { networkConnection.SendWriter(writer, channelId); @@ -510,19 +415,19 @@ namespace QuantumUNET public void Disconnect(int connectionId) { - QSBNetworkConnection networkConnection = this.FindConnection(connectionId); + var networkConnection = FindConnection(connectionId); if (networkConnection != null) { networkConnection.Disconnect(); - this.m_Connections[connectionId] = null; + m_Connections[connectionId] = null; } } public void DisconnectAllConnections() { - for (int i = 0; i < this.m_Connections.Count; i++) + for (var i = 0; i < m_Connections.Count; i++) { - QSBNetworkConnection networkConnection = this.m_Connections[i]; + var networkConnection = m_Connections[i]; if (networkConnection != null) { networkConnection.Disconnect(); @@ -531,58 +436,21 @@ namespace QuantumUNET } } - public virtual void OnConnectError(int connectionId, byte error) - { - Debug.LogError("OnConnectError error:" + error); - } + public virtual void OnConnectError(int connectionId, byte error) => Debug.LogError("OnConnectError error:" + error); - public virtual void OnDataError(QSBNetworkConnection conn, byte error) - { - Debug.LogError("OnDataError error:" + error); - } + public virtual void OnDataError(QSBNetworkConnection conn, byte error) => Debug.LogError("OnDataError error:" + error); - public virtual void OnDisconnectError(QSBNetworkConnection conn, byte error) - { - Debug.LogError("OnDisconnectError error:" + error); - } + public virtual void OnDisconnectError(QSBNetworkConnection conn, byte error) => Debug.LogError("OnDisconnectError error:" + error); - public virtual void OnConnected(QSBNetworkConnection conn) - { - conn.InvokeHandlerNoData(32); - } + public virtual void OnConnected(QSBNetworkConnection conn) => conn.InvokeHandlerNoData(32); - public virtual void OnDisconnected(QSBNetworkConnection conn) - { - conn.InvokeHandlerNoData(33); - } + public virtual void OnDisconnected(QSBNetworkConnection conn) => conn.InvokeHandlerNoData(33); - public virtual void OnData(QSBNetworkConnection conn, int receivedSize, int channelId) - { - conn.TransportReceive(this.m_MsgBuffer, receivedSize, channelId); - } + public virtual void OnData(QSBNetworkConnection conn, int receivedSize, int channelId) => conn.TransportReceive(messageBuffer, receivedSize, channelId); private bool m_Initialized = false; - - private int m_ListenPort; - - private int m_ServerHostId = -1; - private int m_RelaySlotId = -1; - - private bool m_UseWebSockets; - - private byte[] m_MsgBuffer = null; - - private NetworkReader m_MsgReader = null; - - private Type m_NetworkConnectionClass = typeof(QSBNetworkConnection); - - private HostTopology m_HostTopology; - private List m_Connections = new List(); - - private ReadOnlyCollection m_ConnectionsReadOnly; - private QSBNetworkMessageHandlers m_MessageHandlers = new QSBNetworkMessageHandlers(); } } \ No newline at end of file diff --git a/QuantumUNET/QSBNetworkWriter.cs b/QuantumUNET/QSBNetworkWriter.cs index 86a95178..0256d3a8 100644 --- a/QuantumUNET/QSBNetworkWriter.cs +++ b/QuantumUNET/QSBNetworkWriter.cs @@ -11,7 +11,7 @@ namespace QuantumUNET { public QSBNetworkWriter() { - this.m_Buffer = new QSBNetBuffer(); + m_Buffer = new QSBNetBuffer(); if (s_Encoding == null) { s_Encoding = new UTF8Encoding(); @@ -21,7 +21,7 @@ namespace QuantumUNET public QSBNetworkWriter(byte[] buffer) { - this.m_Buffer = new QSBNetBuffer(buffer); + m_Buffer = new QSBNetBuffer(buffer); if (s_Encoding == null) { s_Encoding = new UTF8Encoding(); @@ -29,62 +29,50 @@ namespace QuantumUNET } } - public short Position - { - get - { - return (short)this.m_Buffer.Position; - } - } + public short Position => (short)m_Buffer.Position; public byte[] ToArray() { - byte[] array = new byte[this.m_Buffer.AsArraySegment().Count]; - Array.Copy(this.m_Buffer.AsArraySegment().Array, array, this.m_Buffer.AsArraySegment().Count); + var array = new byte[m_Buffer.AsArraySegment().Count]; + Array.Copy(m_Buffer.AsArraySegment().Array, array, m_Buffer.AsArraySegment().Count); return array; } - public byte[] AsArray() - { - return this.AsArraySegment().Array; - } + public byte[] AsArray() => AsArraySegment().Array; - internal ArraySegment AsArraySegment() - { - return this.m_Buffer.AsArraySegment(); - } + internal ArraySegment AsArraySegment() => m_Buffer.AsArraySegment(); public void WritePackedUInt32(uint value) { if (value <= 240U) { - this.Write((byte)value); + Write((byte)value); } else if (value <= 2287U) { - this.Write((byte)((value - 240U) / 256U + 241U)); - this.Write((byte)((value - 240U) % 256U)); + Write((byte)(((value - 240U) / 256U) + 241U)); + Write((byte)((value - 240U) % 256U)); } else if (value <= 67823U) { - this.Write(249); - this.Write((byte)((value - 2288U) / 256U)); - this.Write((byte)((value - 2288U) % 256U)); + Write(249); + Write((byte)((value - 2288U) / 256U)); + Write((byte)((value - 2288U) % 256U)); } else if (value <= 16777215U) { - this.Write(250); - this.Write((byte)(value & 255U)); - this.Write((byte)(value >> 8 & 255U)); - this.Write((byte)(value >> 16 & 255U)); + Write(250); + Write((byte)(value & 255U)); + Write((byte)((value >> 8) & 255U)); + Write((byte)((value >> 16) & 255U)); } else { - this.Write(251); - this.Write((byte)(value & 255U)); - this.Write((byte)(value >> 8 & 255U)); - this.Write((byte)(value >> 16 & 255U)); - this.Write((byte)(value >> 24 & 255U)); + Write(251); + Write((byte)(value & 255U)); + Write((byte)((value >> 8) & 255U)); + Write((byte)((value >> 16) & 255U)); + Write((byte)((value >> 24) & 255U)); } } @@ -92,168 +80,129 @@ namespace QuantumUNET { if (value <= 240UL) { - this.Write((byte)value); + Write((byte)value); } else if (value <= 2287UL) { - this.Write((byte)((value - 240UL) / 256UL + 241UL)); - this.Write((byte)((value - 240UL) % 256UL)); + Write((byte)(((value - 240UL) / 256UL) + 241UL)); + Write((byte)((value - 240UL) % 256UL)); } else if (value <= 67823UL) { - this.Write(249); - this.Write((byte)((value - 2288UL) / 256UL)); - this.Write((byte)((value - 2288UL) % 256UL)); + Write(249); + Write((byte)((value - 2288UL) / 256UL)); + Write((byte)((value - 2288UL) % 256UL)); } else if (value <= 16777215UL) { - this.Write(250); - this.Write((byte)(value & 255UL)); - this.Write((byte)(value >> 8 & 255UL)); - this.Write((byte)(value >> 16 & 255UL)); + Write(250); + Write((byte)(value & 255UL)); + Write((byte)((value >> 8) & 255UL)); + Write((byte)((value >> 16) & 255UL)); } else if (value <= uint.MaxValue) { - this.Write(251); - this.Write((byte)(value & 255UL)); - this.Write((byte)(value >> 8 & 255UL)); - this.Write((byte)(value >> 16 & 255UL)); - this.Write((byte)(value >> 24 & 255UL)); + Write(251); + Write((byte)(value & 255UL)); + Write((byte)((value >> 8) & 255UL)); + Write((byte)((value >> 16) & 255UL)); + Write((byte)((value >> 24) & 255UL)); } else if (value <= 1099511627775UL) { - this.Write(252); - this.Write((byte)(value & 255UL)); - this.Write((byte)(value >> 8 & 255UL)); - this.Write((byte)(value >> 16 & 255UL)); - this.Write((byte)(value >> 24 & 255UL)); - this.Write((byte)(value >> 32 & 255UL)); + Write(252); + Write((byte)(value & 255UL)); + Write((byte)((value >> 8) & 255UL)); + Write((byte)((value >> 16) & 255UL)); + Write((byte)((value >> 24) & 255UL)); + Write((byte)((value >> 32) & 255UL)); } else if (value <= 281474976710655UL) { - this.Write(253); - this.Write((byte)(value & 255UL)); - this.Write((byte)(value >> 8 & 255UL)); - this.Write((byte)(value >> 16 & 255UL)); - this.Write((byte)(value >> 24 & 255UL)); - this.Write((byte)(value >> 32 & 255UL)); - this.Write((byte)(value >> 40 & 255UL)); + Write(253); + Write((byte)(value & 255UL)); + Write((byte)((value >> 8) & 255UL)); + Write((byte)((value >> 16) & 255UL)); + Write((byte)((value >> 24) & 255UL)); + Write((byte)((value >> 32) & 255UL)); + Write((byte)((value >> 40) & 255UL)); } else if (value <= 72057594037927935UL) { - this.Write(254); - this.Write((byte)(value & 255UL)); - this.Write((byte)(value >> 8 & 255UL)); - this.Write((byte)(value >> 16 & 255UL)); - this.Write((byte)(value >> 24 & 255UL)); - this.Write((byte)(value >> 32 & 255UL)); - this.Write((byte)(value >> 40 & 255UL)); - this.Write((byte)(value >> 48 & 255UL)); + Write(254); + Write((byte)(value & 255UL)); + Write((byte)((value >> 8) & 255UL)); + Write((byte)((value >> 16) & 255UL)); + Write((byte)((value >> 24) & 255UL)); + Write((byte)((value >> 32) & 255UL)); + Write((byte)((value >> 40) & 255UL)); + Write((byte)((value >> 48) & 255UL)); } else { - this.Write(byte.MaxValue); - this.Write((byte)(value & 255UL)); - this.Write((byte)(value >> 8 & 255UL)); - this.Write((byte)(value >> 16 & 255UL)); - this.Write((byte)(value >> 24 & 255UL)); - this.Write((byte)(value >> 32 & 255UL)); - this.Write((byte)(value >> 40 & 255UL)); - this.Write((byte)(value >> 48 & 255UL)); - this.Write((byte)(value >> 56 & 255UL)); + Write(byte.MaxValue); + Write((byte)(value & 255UL)); + Write((byte)((value >> 8) & 255UL)); + Write((byte)((value >> 16) & 255UL)); + Write((byte)((value >> 24) & 255UL)); + Write((byte)((value >> 32) & 255UL)); + Write((byte)((value >> 40) & 255UL)); + Write((byte)((value >> 48) & 255UL)); + Write((byte)((value >> 56) & 255UL)); } } - public void Write(NetworkInstanceId value) - { - this.WritePackedUInt32(value.Value); - } + public void Write(NetworkInstanceId value) => WritePackedUInt32(value.Value); - public void Write(NetworkSceneId value) - { - this.WritePackedUInt32(value.Value); - } + public void Write(NetworkSceneId value) => WritePackedUInt32(value.Value); - public void Write(char value) - { - this.m_Buffer.WriteByte((byte)value); - } + public void Write(char value) => m_Buffer.WriteByte((byte)value); - public void Write(byte value) - { - this.m_Buffer.WriteByte(value); - } + public void Write(byte value) => m_Buffer.WriteByte(value); - public void Write(sbyte value) - { - this.m_Buffer.WriteByte((byte)value); - } + public void Write(sbyte value) => m_Buffer.WriteByte((byte)value); - public void Write(short value) - { - this.m_Buffer.WriteByte2((byte)(value & 255), (byte)(value >> 8 & 255)); - } + public void Write(short value) => m_Buffer.WriteByte2((byte)(value & 255), (byte)((value >> 8) & 255)); - public void Write(ushort value) - { - this.m_Buffer.WriteByte2((byte)(value & 255), (byte)(value >> 8 & 255)); - } + public void Write(ushort value) => m_Buffer.WriteByte2((byte)(value & 255), (byte)((value >> 8) & 255)); - public void Write(int value) - { - this.m_Buffer.WriteByte4((byte)(value & 255), (byte)(value >> 8 & 255), (byte)(value >> 16 & 255), (byte)(value >> 24 & 255)); - } + public void Write(int value) => m_Buffer.WriteByte4((byte)(value & 255), (byte)((value >> 8) & 255), (byte)((value >> 16) & 255), (byte)((value >> 24) & 255)); - public void Write(uint value) - { - this.m_Buffer.WriteByte4((byte)(value & 255U), (byte)(value >> 8 & 255U), (byte)(value >> 16 & 255U), (byte)(value >> 24 & 255U)); - } + public void Write(uint value) => m_Buffer.WriteByte4((byte)(value & 255U), (byte)((value >> 8) & 255U), (byte)((value >> 16) & 255U), (byte)((value >> 24) & 255U)); - public void Write(long value) - { - this.m_Buffer.WriteByte8((byte)(value & 255L), (byte)(value >> 8 & 255L), (byte)(value >> 16 & 255L), (byte)(value >> 24 & 255L), (byte)(value >> 32 & 255L), (byte)(value >> 40 & 255L), (byte)(value >> 48 & 255L), (byte)(value >> 56 & 255L)); - } + public void Write(long value) => m_Buffer.WriteByte8((byte)(value & 255L), (byte)((value >> 8) & 255L), (byte)((value >> 16) & 255L), (byte)((value >> 24) & 255L), (byte)((value >> 32) & 255L), (byte)((value >> 40) & 255L), (byte)((value >> 48) & 255L), (byte)((value >> 56) & 255L)); - public void Write(ulong value) - { - this.m_Buffer.WriteByte8((byte)(value & 255UL), (byte)(value >> 8 & 255UL), (byte)(value >> 16 & 255UL), (byte)(value >> 24 & 255UL), (byte)(value >> 32 & 255UL), (byte)(value >> 40 & 255UL), (byte)(value >> 48 & 255UL), (byte)(value >> 56 & 255UL)); - } + public void Write(ulong value) => m_Buffer.WriteByte8((byte)(value & 255UL), (byte)((value >> 8) & 255UL), (byte)((value >> 16) & 255UL), (byte)((value >> 24) & 255UL), (byte)((value >> 32) & 255UL), (byte)((value >> 40) & 255UL), (byte)((value >> 48) & 255UL), (byte)((value >> 56) & 255UL)); - public void Write(float value) - { - m_Buffer.WriteBytes(BitConverter.GetBytes(value), 4); - } + public void Write(float value) => m_Buffer.WriteBytes(BitConverter.GetBytes(value), 4); - public void Write(double value) - { - m_Buffer.WriteBytes(BitConverter.GetBytes(value), 8); - } + public void Write(double value) => m_Buffer.WriteBytes(BitConverter.GetBytes(value), 8); public void Write(decimal value) { - int[] bits = decimal.GetBits(value); - this.Write(bits[0]); - this.Write(bits[1]); - this.Write(bits[2]); - this.Write(bits[3]); + var bits = decimal.GetBits(value); + Write(bits[0]); + Write(bits[1]); + Write(bits[2]); + Write(bits[3]); } public void Write(string value) { if (value == null) { - this.m_Buffer.WriteByte2(0, 0); + m_Buffer.WriteByte2(0, 0); } else { - int byteCount = s_Encoding.GetByteCount(value); + var byteCount = s_Encoding.GetByteCount(value); if (byteCount >= 32768) { throw new IndexOutOfRangeException("Serialize(string) too long: " + value.Length); } - this.Write((ushort)byteCount); - int bytes = s_Encoding.GetBytes(value, 0, value.Length, s_StringWriteBuffer, 0); - this.m_Buffer.WriteBytes(s_StringWriteBuffer, (ushort)bytes); + Write((ushort)byteCount); + var bytes = s_Encoding.GetBytes(value, 0, value.Length, s_StringWriteBuffer, 0); + m_Buffer.WriteBytes(s_StringWriteBuffer, (ushort)bytes); } } @@ -261,11 +210,11 @@ namespace QuantumUNET { if (value) { - this.m_Buffer.WriteByte(1); + m_Buffer.WriteByte(1); } else { - this.m_Buffer.WriteByte(0); + m_Buffer.WriteByte(0); } } @@ -280,7 +229,7 @@ namespace QuantumUNET } else { - this.m_Buffer.WriteBytes(buffer, (ushort)count); + m_Buffer.WriteBytes(buffer, (ushort)count); } } @@ -295,7 +244,7 @@ namespace QuantumUNET } else { - this.m_Buffer.WriteBytesAtOffset(buffer, (ushort)offset, (ushort)count); + m_Buffer.WriteBytesAtOffset(buffer, (ushort)offset, (ushort)count); } } @@ -303,7 +252,7 @@ namespace QuantumUNET { if (buffer == null || count == 0) { - this.Write(0); + Write(0); } else if (count > 65535) { @@ -314,8 +263,8 @@ namespace QuantumUNET } else { - this.Write((ushort)count); - this.m_Buffer.WriteBytes(buffer, (ushort)count); + Write((ushort)count); + m_Buffer.WriteBytes(buffer, (ushort)count); } } @@ -323,7 +272,7 @@ namespace QuantumUNET { if (buffer == null) { - this.Write(0); + Write(0); } else if (buffer.Length > 65535) { @@ -334,125 +283,125 @@ namespace QuantumUNET } else { - this.Write((ushort)buffer.Length); - this.m_Buffer.WriteBytes(buffer, (ushort)buffer.Length); + Write((ushort)buffer.Length); + m_Buffer.WriteBytes(buffer, (ushort)buffer.Length); } } public void Write(Vector2 value) { - this.Write(value.x); - this.Write(value.y); + Write(value.x); + Write(value.y); } public void Write(Vector3 value) { - this.Write(value.x); - this.Write(value.y); - this.Write(value.z); + Write(value.x); + Write(value.y); + Write(value.z); } public void Write(Vector4 value) { - this.Write(value.x); - this.Write(value.y); - this.Write(value.z); - this.Write(value.w); + Write(value.x); + Write(value.y); + Write(value.z); + Write(value.w); } public void Write(Color value) { - this.Write(value.r); - this.Write(value.g); - this.Write(value.b); - this.Write(value.a); + Write(value.r); + Write(value.g); + Write(value.b); + Write(value.a); } public void Write(Color32 value) { - this.Write(value.r); - this.Write(value.g); - this.Write(value.b); - this.Write(value.a); + Write(value.r); + Write(value.g); + Write(value.b); + Write(value.a); } public void Write(Quaternion value) { - this.Write(value.x); - this.Write(value.y); - this.Write(value.z); - this.Write(value.w); + Write(value.x); + Write(value.y); + Write(value.z); + Write(value.w); } public void Write(Rect value) { - this.Write(value.xMin); - this.Write(value.yMin); - this.Write(value.width); - this.Write(value.height); + Write(value.xMin); + Write(value.yMin); + Write(value.width); + Write(value.height); } public void Write(Plane value) { - this.Write(value.normal); - this.Write(value.distance); + Write(value.normal); + Write(value.distance); } public void Write(Ray value) { - this.Write(value.direction); - this.Write(value.origin); + Write(value.direction); + Write(value.origin); } public void Write(Matrix4x4 value) { - this.Write(value.m00); - this.Write(value.m01); - this.Write(value.m02); - this.Write(value.m03); - this.Write(value.m10); - this.Write(value.m11); - this.Write(value.m12); - this.Write(value.m13); - this.Write(value.m20); - this.Write(value.m21); - this.Write(value.m22); - this.Write(value.m23); - this.Write(value.m30); - this.Write(value.m31); - this.Write(value.m32); - this.Write(value.m33); + Write(value.m00); + Write(value.m01); + Write(value.m02); + Write(value.m03); + Write(value.m10); + Write(value.m11); + Write(value.m12); + Write(value.m13); + Write(value.m20); + Write(value.m21); + Write(value.m22); + Write(value.m23); + Write(value.m30); + Write(value.m31); + Write(value.m32); + Write(value.m33); } public void Write(NetworkHash128 value) { - this.Write(value.i0); - this.Write(value.i1); - this.Write(value.i2); - this.Write(value.i3); - this.Write(value.i4); - this.Write(value.i5); - this.Write(value.i6); - this.Write(value.i7); - this.Write(value.i8); - this.Write(value.i9); - this.Write(value.i10); - this.Write(value.i11); - this.Write(value.i12); - this.Write(value.i13); - this.Write(value.i14); - this.Write(value.i15); + Write(value.i0); + Write(value.i1); + Write(value.i2); + Write(value.i3); + Write(value.i4); + Write(value.i5); + Write(value.i6); + Write(value.i7); + Write(value.i8); + Write(value.i9); + Write(value.i10); + Write(value.i11); + Write(value.i12); + Write(value.i13); + Write(value.i14); + Write(value.i15); } public void Write(NetworkIdentity value) { if (value == null) { - this.WritePackedUInt32(0U); + WritePackedUInt32(0U); } else { - this.Write(value.netId); + Write(value.netId); } } @@ -460,14 +409,14 @@ namespace QuantumUNET { if (value == null || value.gameObject == null) { - this.WritePackedUInt32(0U); + WritePackedUInt32(0U); } else { - NetworkIdentity component = value.gameObject.GetComponent(); + var component = value.gameObject.GetComponent(); if (component != null) { - this.Write(component.netId); + Write(component.netId); } else { @@ -475,7 +424,7 @@ namespace QuantumUNET { Debug.LogWarning("NetworkWriter " + value + " has no NetworkIdentity"); } - this.WritePackedUInt32(0U); + WritePackedUInt32(0U); } } } @@ -484,14 +433,14 @@ namespace QuantumUNET { if (value == null) { - this.WritePackedUInt32(0U); + WritePackedUInt32(0U); } else { - QSBNetworkIdentity component = value.GetComponent(); + var component = value.GetComponent(); if (component != null) { - this.Write(component.NetId); + Write(component.NetId); } else { @@ -499,32 +448,23 @@ namespace QuantumUNET { Debug.LogWarning("NetworkWriter " + value + " has no NetworkIdentity"); } - this.WritePackedUInt32(0U); + WritePackedUInt32(0U); } } } - public void Write(QSBMessageBase msg) - { - msg.Serialize(this); - } + public void Write(QSBMessageBase msg) => msg.Serialize(this); - public void SeekZero() - { - this.m_Buffer.SeekZero(); - } + public void SeekZero() => m_Buffer.SeekZero(); public void StartMessage(short msgType) { - this.SeekZero(); - this.m_Buffer.WriteByte2(0, 0); - this.Write(msgType); + SeekZero(); + m_Buffer.WriteByte2(0, 0); + Write(msgType); } - public void FinishMessage() - { - this.m_Buffer.FinishMessage(); - } + public void FinishMessage() => m_Buffer.FinishMessage(); private const int k_MaxStringLength = 32768; diff --git a/QuantumUNET/QSBULocalConnectionToServer.cs b/QuantumUNET/QSBULocalConnectionToServer.cs index 51d2d4db..09511661 100644 --- a/QuantumUNET/QSBULocalConnectionToServer.cs +++ b/QuantumUNET/QSBULocalConnectionToServer.cs @@ -12,20 +12,11 @@ namespace QuantumUNET m_LocalServer = localServer; } - public override bool Send(short msgType, QSBMessageBase msg) - { - return m_LocalServer.InvokeHandlerOnServer(this, msgType, msg, 0); - } + public override bool Send(short msgType, QSBMessageBase msg) => m_LocalServer.InvokeHandlerOnServer(this, msgType, msg, 0); - public override bool SendUnreliable(short msgType, QSBMessageBase msg) - { - return m_LocalServer.InvokeHandlerOnServer(this, msgType, msg, 1); - } + public override bool SendUnreliable(short msgType, QSBMessageBase msg) => m_LocalServer.InvokeHandlerOnServer(this, msgType, msg, 1); - public override bool SendByChannel(short msgType, QSBMessageBase msg, int channelId) - { - return m_LocalServer.InvokeHandlerOnServer(this, msgType, msg, channelId); - } + public override bool SendByChannel(short msgType, QSBMessageBase msg, int channelId) => m_LocalServer.InvokeHandlerOnServer(this, msgType, msg, channelId); public override bool SendBytes(byte[] bytes, int numBytes, int channelId) { @@ -45,10 +36,7 @@ namespace QuantumUNET return result; } - public override bool SendWriter(QSBNetworkWriter writer, int channelId) - { - return m_LocalServer.InvokeBytes(this, writer.AsArray(), (int)((short)writer.AsArray().Length), channelId); - } + public override bool SendWriter(QSBNetworkWriter writer, int channelId) => m_LocalServer.InvokeBytes(this, writer.AsArray(), (short)writer.AsArray().Length, channelId); public override void GetStatsOut(out int numMsgs, out int numBufferedMsgs, out int numBytes, out int lastBufferedPerSecond) { From 89a9a5247c73809cfa9ec790bf44d5b8fdf24050 Mon Sep 17 00:00:00 2001 From: Mister_Nebula <41904486+misternebula@users.noreply.github.com> Date: Mon, 14 Dec 2020 21:59:39 +0000 Subject: [PATCH 02/10] clean --- QuantumUNET/Components/QSBNetworkAnimator.cs | 2 +- QuantumUNET/Components/QSBNetworkTransform.cs | 2 +- QuantumUNET/QSBNetworkCRC.cs | 3 +-- QuantumUNET/QSBUtility.cs | 4 ++-- 4 files changed, 5 insertions(+), 6 deletions(-) diff --git a/QuantumUNET/Components/QSBNetworkAnimator.cs b/QuantumUNET/Components/QSBNetworkAnimator.cs index c124f646..81cd6fcc 100644 --- a/QuantumUNET/Components/QSBNetworkAnimator.cs +++ b/QuantumUNET/Components/QSBNetworkAnimator.cs @@ -41,7 +41,7 @@ namespace QuantumUNET.Components } } - public bool GetParameterAutoSend(int index) => + public bool GetParameterAutoSend(int index) => ((int)m_ParameterSendBits & (1 << index)) != 0; public override void OnStartAuthority() => diff --git a/QuantumUNET/Components/QSBNetworkTransform.cs b/QuantumUNET/Components/QSBNetworkTransform.cs index 7c6c0a66..099a81e7 100644 --- a/QuantumUNET/Components/QSBNetworkTransform.cs +++ b/QuantumUNET/Components/QSBNetworkTransform.cs @@ -298,7 +298,7 @@ namespace QuantumUNET.Components return result; } - public static void SerializeVelocity3D(QSBNetworkWriter writer, Vector3 velocity, CompressionSyncMode compression) => + public static void SerializeVelocity3D(QSBNetworkWriter writer, Vector3 velocity, CompressionSyncMode compression) => writer.Write(velocity); public static void SerializeRotation3D(QSBNetworkWriter writer, Quaternion rot, AxisSyncMode mode, CompressionSyncMode compression) diff --git a/QuantumUNET/QSBNetworkCRC.cs b/QuantumUNET/QSBNetworkCRC.cs index 5f0e8938..276200ba 100644 --- a/QuantumUNET/QSBNetworkCRC.cs +++ b/QuantumUNET/QSBNetworkCRC.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Reflection; using UnityEngine; using UnityEngine.Networking; diff --git a/QuantumUNET/QSBUtility.cs b/QuantumUNET/QSBUtility.cs index 57c80609..0bf04729 100644 --- a/QuantumUNET/QSBUtility.cs +++ b/QuantumUNET/QSBUtility.cs @@ -8,8 +8,8 @@ namespace QuantumUNET { private static readonly Dictionary _dictTokens = new Dictionary(); - public static SourceID GetSourceID() - => (SourceID)SystemInfo.deviceUniqueIdentifier.GetHashCode(); + public static SourceID GetSourceID() => + (SourceID)SystemInfo.deviceUniqueIdentifier.GetHashCode(); public static void SetAccessTokenForNetwork(NetworkID netId, NetworkAccessToken accessToken) { From 4c466dbe24511dcdbf674ed0e502792b2bdc802f Mon Sep 17 00:00:00 2001 From: Mister_Nebula <41904486+misternebula@users.noreply.github.com> Date: Mon, 14 Dec 2020 22:07:21 +0000 Subject: [PATCH 03/10] cleanup --- QuantumUNET/Messages/QSBAddPlayerMessage.cs | 12 +-- QuantumUNET/Messages/QSBErrorMessage.cs | 4 +- QuantumUNET/Messages/QSBMessageBase.cs | 8 +- QuantumUNET/Messages/QSBNetworkMessage.cs | 3 +- QuantumUNET/Messages/QSBPeerInfoMessage.cs | 80 ------------------- .../Messages/QSBRemovePlayerMessage.cs | 4 +- QuantumUNET/Messages/QSBStringMessage.cs | 8 +- QuantumUNET/QSBClientScene.cs | 14 ---- QuantumUNET/QSBNetBuffer.cs | 9 +-- QuantumUNET/QSBPeerInfoPlayer.cs | 11 --- QuantumUNET/QSBPlayerController.cs | 3 +- QuantumUNET/QSBULocalConnectionToServer.cs | 12 ++- QuantumUNET/QuantumUNET.csproj | 2 - 13 files changed, 27 insertions(+), 143 deletions(-) delete mode 100644 QuantumUNET/Messages/QSBPeerInfoMessage.cs delete mode 100644 QuantumUNET/QSBPeerInfoPlayer.cs diff --git a/QuantumUNET/Messages/QSBAddPlayerMessage.cs b/QuantumUNET/Messages/QSBAddPlayerMessage.cs index 34d65148..36920806 100644 --- a/QuantumUNET/Messages/QSBAddPlayerMessage.cs +++ b/QuantumUNET/Messages/QSBAddPlayerMessage.cs @@ -6,6 +6,12 @@ public int msgSize; public byte[] msgData; + public override void Serialize(QSBNetworkWriter writer) + { + writer.Write(playerControllerId); + writer.WriteBytesAndSize(msgData, msgSize); + } + public override void Deserialize(QSBNetworkReader reader) { playerControllerId = reader.ReadInt16(); @@ -19,11 +25,5 @@ msgSize = msgData.Length; } } - - public override void Serialize(QSBNetworkWriter writer) - { - writer.Write(playerControllerId); - writer.WriteBytesAndSize(msgData, msgSize); - } } } \ No newline at end of file diff --git a/QuantumUNET/Messages/QSBErrorMessage.cs b/QuantumUNET/Messages/QSBErrorMessage.cs index 67951c84..d7952f6b 100644 --- a/QuantumUNET/Messages/QSBErrorMessage.cs +++ b/QuantumUNET/Messages/QSBErrorMessage.cs @@ -2,10 +2,10 @@ { public class QSBErrorMessage : QSBMessageBase { - public override void Deserialize(QSBNetworkReader reader) => errorCode = reader.ReadUInt16(); + public int errorCode; public override void Serialize(QSBNetworkWriter writer) => writer.Write((ushort)errorCode); - public int errorCode; + public override void Deserialize(QSBNetworkReader reader) => errorCode = reader.ReadUInt16(); } } \ No newline at end of file diff --git a/QuantumUNET/Messages/QSBMessageBase.cs b/QuantumUNET/Messages/QSBMessageBase.cs index 241af116..501869d7 100644 --- a/QuantumUNET/Messages/QSBMessageBase.cs +++ b/QuantumUNET/Messages/QSBMessageBase.cs @@ -2,12 +2,8 @@ { public abstract class QSBMessageBase { - public virtual void Deserialize(QSBNetworkReader reader) - { - } + public virtual void Serialize(QSBNetworkWriter writer) { } - public virtual void Serialize(QSBNetworkWriter writer) - { - } + public virtual void Deserialize(QSBNetworkReader reader) { } } } \ No newline at end of file diff --git a/QuantumUNET/Messages/QSBNetworkMessage.cs b/QuantumUNET/Messages/QSBNetworkMessage.cs index b9de5999..4f7ca90c 100644 --- a/QuantumUNET/Messages/QSBNetworkMessage.cs +++ b/QuantumUNET/Messages/QSBNetworkMessage.cs @@ -17,6 +17,7 @@ namespace QuantumUNET.Messages return result; } - public void ReadMessage(TMsg msg) where TMsg : QSBMessageBase => msg.Deserialize(Reader); + public void ReadMessage(TMsg msg) where TMsg : QSBMessageBase => + msg.Deserialize(Reader); } } \ No newline at end of file diff --git a/QuantumUNET/Messages/QSBPeerInfoMessage.cs b/QuantumUNET/Messages/QSBPeerInfoMessage.cs deleted file mode 100644 index a38a00f0..00000000 --- a/QuantumUNET/Messages/QSBPeerInfoMessage.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System.Collections.Generic; - -namespace QuantumUNET.Messages -{ - public class QSBPeerInfoMessage : QSBMessageBase - { - public override void Deserialize(QSBNetworkReader reader) - { - connectionId = (int)reader.ReadPackedUInt32(); - address = reader.ReadString(); - port = (int)reader.ReadPackedUInt32(); - isHost = reader.ReadBoolean(); - isYou = reader.ReadBoolean(); - var num = reader.ReadPackedUInt32(); - if (num > 0U) - { - var list = new List(); - for (var num2 = 0U; num2 < num; num2 += 1U) - { - QSBPeerInfoPlayer item; - item.netId = reader.ReadNetworkId(); - item.playerControllerId = (short)reader.ReadPackedUInt32(); - list.Add(item); - } - playerIds = list.ToArray(); - } - } - - public override void Serialize(QSBNetworkWriter writer) - { - writer.WritePackedUInt32((uint)connectionId); - writer.Write(address); - writer.WritePackedUInt32((uint)port); - writer.Write(isHost); - writer.Write(isYou); - if (playerIds == null) - { - writer.WritePackedUInt32(0U); - } - else - { - writer.WritePackedUInt32((uint)playerIds.Length); - for (var i = 0; i < playerIds.Length; i++) - { - writer.Write(playerIds[i].netId); - writer.WritePackedUInt32((uint)playerIds[i].playerControllerId); - } - } - } - - public override string ToString() - { - return string.Concat(new object[] - { - "PeerInfo conn:", - connectionId, - " addr:", - address, - ":", - port, - " host:", - isHost, - " isYou:", - isYou - }); - } - - public int connectionId; - - public string address; - - public int port; - - public bool isHost; - - public bool isYou; - - public QSBPeerInfoPlayer[] playerIds; - } -} \ No newline at end of file diff --git a/QuantumUNET/Messages/QSBRemovePlayerMessage.cs b/QuantumUNET/Messages/QSBRemovePlayerMessage.cs index 50190b79..e36620c8 100644 --- a/QuantumUNET/Messages/QSBRemovePlayerMessage.cs +++ b/QuantumUNET/Messages/QSBRemovePlayerMessage.cs @@ -4,8 +4,8 @@ { public short PlayerControllerId; - public override void Deserialize(QSBNetworkReader reader) => PlayerControllerId = (short)reader.ReadUInt16(); - public override void Serialize(QSBNetworkWriter writer) => writer.Write((ushort)PlayerControllerId); + + public override void Deserialize(QSBNetworkReader reader) => PlayerControllerId = (short)reader.ReadUInt16(); } } \ No newline at end of file diff --git a/QuantumUNET/Messages/QSBStringMessage.cs b/QuantumUNET/Messages/QSBStringMessage.cs index 98c5ad07..547d1ec1 100644 --- a/QuantumUNET/Messages/QSBStringMessage.cs +++ b/QuantumUNET/Messages/QSBStringMessage.cs @@ -2,19 +2,15 @@ { public class QSBStringMessage : QSBMessageBase { - public QSBStringMessage() - { - } + public string value; public QSBStringMessage(string v) { value = v; } - public override void Deserialize(QSBNetworkReader reader) => value = reader.ReadString(); - public override void Serialize(QSBNetworkWriter writer) => writer.Write(value); - public string value; + public override void Deserialize(QSBNetworkReader reader) => value = reader.ReadString(); } } \ No newline at end of file diff --git a/QuantumUNET/QSBClientScene.cs b/QuantumUNET/QSBClientScene.cs index b9a73353..7076b9ce 100644 --- a/QuantumUNET/QSBClientScene.cs +++ b/QuantumUNET/QSBClientScene.cs @@ -8,18 +8,6 @@ namespace QuantumUNET { public class QSBClientScene { - private static bool HasMigrationPending() => reconnectId != -1; - - public static void SetReconnectId(int newReconnectId, QSBPeerInfoMessage[] peers) - { - reconnectId = newReconnectId; - s_Peers = peers; - if (LogFilter.logDebug) - { - Debug.Log("ClientScene::SetReconnectId: " + newReconnectId); - } - } - internal static void SetNotReady() => ready = false; public static List localPlayers { get; private set; } = new List(); @@ -811,8 +799,6 @@ namespace QuantumUNET public const int ReconnectIdHost = 0; - private static QSBPeerInfoMessage[] s_Peers; - private static List s_PendingOwnerIds = new List(); private struct PendingOwner diff --git a/QuantumUNET/QSBNetBuffer.cs b/QuantumUNET/QSBNetBuffer.cs index 2c696159..2cf25622 100644 --- a/QuantumUNET/QSBNetBuffer.cs +++ b/QuantumUNET/QSBNetBuffer.cs @@ -16,7 +16,6 @@ namespace QuantumUNET } public uint Position { get; private set; } - public int Length => m_Buffer.Length; public byte ReadByte() @@ -154,7 +153,8 @@ namespace QuantumUNET m_Buffer[1] = (byte)((num >> 8) & 255); } - public void SeekZero() => Position = 0U; + public void SeekZero() => + Position = 0U; public void Replace(byte[] buffer) { @@ -165,10 +165,5 @@ namespace QuantumUNET public override string ToString() => string.Format("NetBuf sz:{0} pos:{1}", m_Buffer.Length, Position); private byte[] m_Buffer; - private const int k_InitialSize = 64; - - private const float k_GrowthFactor = 1.5f; - - private const int k_BufferSizeWarning = 134217728; } } \ No newline at end of file diff --git a/QuantumUNET/QSBPeerInfoPlayer.cs b/QuantumUNET/QSBPeerInfoPlayer.cs deleted file mode 100644 index 77394469..00000000 --- a/QuantumUNET/QSBPeerInfoPlayer.cs +++ /dev/null @@ -1,11 +0,0 @@ -using UnityEngine.Networking; - -namespace QuantumUNET -{ - public struct QSBPeerInfoPlayer - { - public NetworkInstanceId netId; - - public short playerControllerId; - } -} \ No newline at end of file diff --git a/QuantumUNET/QSBPlayerController.cs b/QuantumUNET/QSBPlayerController.cs index 745ad2a3..908fafde 100644 --- a/QuantumUNET/QSBPlayerController.cs +++ b/QuantumUNET/QSBPlayerController.cs @@ -9,6 +9,7 @@ namespace QuantumUNET public QSBNetworkIdentity UnetView; public GameObject Gameobject; public const int MaxPlayersPerClient = 32; + public bool IsValid => PlayerControllerId != -1; internal const short kMaxLocalPlayers = 8; @@ -23,8 +24,6 @@ namespace QuantumUNET PlayerControllerId = playerControllerId; } - public bool IsValid => PlayerControllerId != -1; - public override string ToString() { return string.Format("ID={0} NetworkIdentity NetID={1} Player={2}", new object[] diff --git a/QuantumUNET/QSBULocalConnectionToServer.cs b/QuantumUNET/QSBULocalConnectionToServer.cs index 09511661..f6c9bef8 100644 --- a/QuantumUNET/QSBULocalConnectionToServer.cs +++ b/QuantumUNET/QSBULocalConnectionToServer.cs @@ -12,11 +12,14 @@ namespace QuantumUNET m_LocalServer = localServer; } - public override bool Send(short msgType, QSBMessageBase msg) => m_LocalServer.InvokeHandlerOnServer(this, msgType, msg, 0); + public override bool Send(short msgType, QSBMessageBase msg) => + m_LocalServer.InvokeHandlerOnServer(this, msgType, msg, 0); - public override bool SendUnreliable(short msgType, QSBMessageBase msg) => m_LocalServer.InvokeHandlerOnServer(this, msgType, msg, 1); + public override bool SendUnreliable(short msgType, QSBMessageBase msg) => + m_LocalServer.InvokeHandlerOnServer(this, msgType, msg, 1); - public override bool SendByChannel(short msgType, QSBMessageBase msg, int channelId) => m_LocalServer.InvokeHandlerOnServer(this, msgType, msg, channelId); + public override bool SendByChannel(short msgType, QSBMessageBase msg, int channelId) => + m_LocalServer.InvokeHandlerOnServer(this, msgType, msg, channelId); public override bool SendBytes(byte[] bytes, int numBytes, int channelId) { @@ -36,7 +39,8 @@ namespace QuantumUNET return result; } - public override bool SendWriter(QSBNetworkWriter writer, int channelId) => m_LocalServer.InvokeBytes(this, writer.AsArray(), (short)writer.AsArray().Length, channelId); + public override bool SendWriter(QSBNetworkWriter writer, int channelId) => + m_LocalServer.InvokeBytes(this, writer.AsArray(), (short)writer.AsArray().Length, channelId); public override void GetStatsOut(out int numMsgs, out int numBufferedMsgs, out int numBytes, out int lastBufferedPerSecond) { diff --git a/QuantumUNET/QuantumUNET.csproj b/QuantumUNET/QuantumUNET.csproj index 034ab304..2390b943 100644 --- a/QuantumUNET/QuantumUNET.csproj +++ b/QuantumUNET/QuantumUNET.csproj @@ -134,8 +134,6 @@ - - From 751fb9cf6c87e84ccd7db0623885bccbee633ffa Mon Sep 17 00:00:00 2001 From: Mister_Nebula <41904486+misternebula@users.noreply.github.com> Date: Mon, 14 Dec 2020 22:09:30 +0000 Subject: [PATCH 04/10] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d20c15ac..696229f8 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Quantum Space Buddies - Outer Wilds Online Multiplayer Mod -Quantum Space Buddies (QSB) is a multiplayer mod for Outer Wilds. The mod uses the OWML mod loader and customized UNET code (internally referred to as "QuantumUNET") for networking. +Quantum Space Buddies (QSB) is a multiplayer mod for Outer Wilds. The mod uses the OWML mod loader and customized UNET code (internally referred to as QNet or QuantumUNET) for networking. **Disclamer - The mod authors (misternebula, AmazingAlek and Raicuparta) take no responsibility for any damages that are caused through opening ports on your network, or connecting to servers. Do not attempt to change your router settings without prior knowledge of what you are doing. Only share your public IP with people you trust, and don't connect to IPs that you do not know the source of. It is good practice to close ports/firewall exceptions after you have finished playing.** From 7c87649d7e162bd5b65fd953dd243dd3e6f77d91 Mon Sep 17 00:00:00 2001 From: Mister_Nebula <41904486+misternebula@users.noreply.github.com> Date: Mon, 14 Dec 2020 22:15:10 +0000 Subject: [PATCH 05/10] more clean --- QSB/QSB.csproj | 1 - QSB/QSBNetworkManager.cs | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/QSB/QSB.csproj b/QSB/QSB.csproj index 7d77e6a6..f52a4342 100644 --- a/QSB/QSB.csproj +++ b/QSB/QSB.csproj @@ -191,7 +191,6 @@ - diff --git a/QSB/QSBNetworkManager.cs b/QSB/QSBNetworkManager.cs index 2aca29fe..22a034f7 100644 --- a/QSB/QSBNetworkManager.cs +++ b/QSB/QSBNetworkManager.cs @@ -43,6 +43,7 @@ namespace QSB public void Awake() { + base.Awake(); Instance = this; _lobby = gameObject.AddComponent(); From ea4e56b046f357d90f8a39f192e73e8a3a3c8f3a Mon Sep 17 00:00:00 2001 From: Mister_Nebula <41904486+misternebula@users.noreply.github.com> Date: Tue, 15 Dec 2020 09:30:55 +0000 Subject: [PATCH 06/10] cleanup --- QSB/Animation/AnimationSync.cs | 10 ++----- QuantumUNET/Messages/QSBReconnectMessage.cs | 30 ------------------- QuantumUNET/QSBUtility.cs | 32 --------------------- QuantumUNET/QuantumUNET.csproj | 2 -- 4 files changed, 2 insertions(+), 72 deletions(-) delete mode 100644 QuantumUNET/Messages/QSBReconnectMessage.cs delete mode 100644 QuantumUNET/QSBUtility.cs diff --git a/QSB/Animation/AnimationSync.cs b/QSB/Animation/AnimationSync.cs index 77614e78..02df29c9 100644 --- a/QSB/Animation/AnimationSync.cs +++ b/QSB/Animation/AnimationSync.cs @@ -145,15 +145,9 @@ namespace QSB.Animation private void OnBecomeUngrounded() => _netAnim.SetTrigger("Ungrounded"); - public void SendCrouch(float value = 0) - { - GlobalMessenger.FireEvent(EventNames.QSBCrouch, value); - } + public void SendCrouch(float value = 0) => GlobalMessenger.FireEvent(EventNames.QSBCrouch, value); - public void HandleCrouch(float value) - { - _crouchSync.CrouchParam.Target = value; - } + public void HandleCrouch(float value) => _crouchSync.CrouchParam.Target = value; private void SuitUp() { diff --git a/QuantumUNET/Messages/QSBReconnectMessage.cs b/QuantumUNET/Messages/QSBReconnectMessage.cs deleted file mode 100644 index f43c20f2..00000000 --- a/QuantumUNET/Messages/QSBReconnectMessage.cs +++ /dev/null @@ -1,30 +0,0 @@ -using UnityEngine.Networking; - -namespace QuantumUNET.Messages -{ - public class QSBReconnectMessage : QSBMessageBase - { - public int oldConnectionId; - public short playerControllerId; - public NetworkInstanceId netId; - public int msgSize; - public byte[] msgData; - - public override void Deserialize(QSBNetworkReader reader) - { - oldConnectionId = (int)reader.ReadPackedUInt32(); - playerControllerId = (short)reader.ReadPackedUInt32(); - netId = reader.ReadNetworkId(); - msgData = reader.ReadBytesAndSize(); - msgSize = msgData.Length; - } - - public override void Serialize(QSBNetworkWriter writer) - { - writer.WritePackedUInt32((uint)oldConnectionId); - writer.WritePackedUInt32((uint)playerControllerId); - writer.Write(netId); - writer.WriteBytesAndSize(msgData, msgSize); - } - } -} \ No newline at end of file diff --git a/QuantumUNET/QSBUtility.cs b/QuantumUNET/QSBUtility.cs deleted file mode 100644 index 0bf04729..00000000 --- a/QuantumUNET/QSBUtility.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System.Collections.Generic; -using UnityEngine; -using UnityEngine.Networking.Types; - -namespace QuantumUNET -{ - public class QSBUtility - { - private static readonly Dictionary _dictTokens = new Dictionary(); - - public static SourceID GetSourceID() => - (SourceID)SystemInfo.deviceUniqueIdentifier.GetHashCode(); - - public static void SetAccessTokenForNetwork(NetworkID netId, NetworkAccessToken accessToken) - { - if (_dictTokens.ContainsKey(netId)) - { - _dictTokens.Remove(netId); - } - _dictTokens.Add(netId, accessToken); - } - - public static NetworkAccessToken GetAccessTokenForNetwork(NetworkID netId) - { - if (!_dictTokens.TryGetValue(netId, out var result)) - { - result = new NetworkAccessToken(); - } - return result; - } - } -} \ No newline at end of file diff --git a/QuantumUNET/QuantumUNET.csproj b/QuantumUNET/QuantumUNET.csproj index 2390b943..3db8592e 100644 --- a/QuantumUNET/QuantumUNET.csproj +++ b/QuantumUNET/QuantumUNET.csproj @@ -136,12 +136,10 @@ - - From 6148bee639aa114914e4bb9280087311fb26accd Mon Sep 17 00:00:00 2001 From: Mister_Nebula <41904486+misternebula@users.noreply.github.com> Date: Tue, 15 Dec 2020 09:56:03 +0000 Subject: [PATCH 07/10] more clean --- QuantumUNET/Components/QSBNetworkIdentity.cs | 23 ++-- QuantumUNET/Messages/QSBAnimationMessage.cs | 6 +- .../Messages/QSBAnimationParametersMessage.cs | 6 +- .../Messages/QSBAnimationTriggerMessage.cs | 6 +- .../Messages/QSBClientAuthorityMessage.cs | 6 +- .../Messages/QSBObjectDestroyMessage.cs | 6 +- QuantumUNET/Messages/QSBObjectSpawnMessage.cs | 5 +- .../Messages/QSBObjectSpawnSceneMessage.cs | 5 +- QuantumUNET/Messages/QSBOwnerMessage.cs | 6 +- QuantumUNET/QSBClientScene.cs | 26 ++-- QuantumUNET/QSBNetworkBehaviour.cs | 8 +- QuantumUNET/QSBNetworkConnection.cs | 4 +- QuantumUNET/QSBNetworkHash128.cs | 125 ++++++++++++++++++ QuantumUNET/QSBNetworkInstanceId.cs | 41 ++++++ QuantumUNET/QSBNetworkReader.cs | 8 +- QuantumUNET/QSBNetworkScene.cs | 30 ++--- QuantumUNET/QSBNetworkSceneId.cs | 36 +++++ QuantumUNET/QSBNetworkServer.cs | 16 +-- QuantumUNET/QSBNetworkWriter.cs | 14 +- QuantumUNET/QuantumUNET.csproj | 3 + 20 files changed, 285 insertions(+), 95 deletions(-) create mode 100644 QuantumUNET/QSBNetworkHash128.cs create mode 100644 QuantumUNET/QSBNetworkInstanceId.cs create mode 100644 QuantumUNET/QSBNetworkSceneId.cs diff --git a/QuantumUNET/Components/QSBNetworkIdentity.cs b/QuantumUNET/Components/QSBNetworkIdentity.cs index c6b2860f..325b22d8 100644 --- a/QuantumUNET/Components/QSBNetworkIdentity.cs +++ b/QuantumUNET/Components/QSBNetworkIdentity.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using UnityEngine; -using UnityEngine.Networking; namespace QuantumUNET.Components { @@ -13,10 +12,10 @@ namespace QuantumUNET.Components public bool IsClient { get; private set; } public bool IsServer => m_IsServer && QSBNetworkServer.active && m_IsServer; public bool HasAuthority { get; private set; } - public NetworkInstanceId NetId { get; private set; } - public NetworkSceneId SceneId => m_SceneId; + public QSBNetworkInstanceId NetId { get; private set; } + public QSBNetworkSceneId SceneId => m_SceneId; public QSBNetworkConnection ClientAuthorityOwner { get; private set; } - public NetworkHash128 AssetId => m_AssetId; + public QSBNetworkHash128 AssetId => m_AssetId; public bool IsLocalPlayer { get; private set; } public short PlayerControllerId { get; private set; } = -1; public QSBNetworkConnection ConnectionToServer { get; private set; } @@ -64,7 +63,7 @@ namespace QuantumUNET.Components internal void RemoveSubIdentity(QSBNetworkIdentity identityToRemove) => SubIdentities.Remove(identityToRemove); - internal void SetDynamicAssetId(NetworkHash128 newAssetId) + internal void SetDynamicAssetId(QSBNetworkHash128 newAssetId) { if (!m_AssetId.IsValid() || m_AssetId.Equals(newAssetId)) { @@ -121,11 +120,11 @@ namespace QuantumUNET.Components } } - internal static NetworkInstanceId GetNextNetworkId() + internal static QSBNetworkInstanceId GetNextNetworkId() { var value = s_NextNetworkId; s_NextNetworkId += 1U; - return new NetworkInstanceId(value); + return new QSBNetworkInstanceId(value); } private void CacheBehaviours() @@ -144,7 +143,7 @@ namespace QuantumUNET.Components } } - internal void SetNetworkInstanceId(NetworkInstanceId newNetId) + internal void SetNetworkInstanceId(QSBNetworkInstanceId newNetId) { NetId = newNetId; if (newNetId.Value == 0U) @@ -153,7 +152,7 @@ namespace QuantumUNET.Components } } - public void ForceSceneId(int newSceneId) => m_SceneId = new NetworkSceneId((uint)newSceneId); + public void ForceSceneId(int newSceneId) => m_SceneId = new QSBNetworkSceneId((uint)newSceneId); internal void UpdateClientServer(bool isClientFlag, bool isServerFlag) { @@ -948,7 +947,7 @@ namespace QuantumUNET.Components m_IsServer = false; IsClient = false; HasAuthority = false; - NetId = (NetworkInstanceId)typeof(NetworkInstanceId).GetField("Zero", System.Reflection.BindingFlags.Static).GetValue(null); + NetId = (QSBNetworkInstanceId)typeof(QSBNetworkInstanceId).GetField("Zero", System.Reflection.BindingFlags.Static).GetValue(null); IsLocalPlayer = false; ConnectionToServer = null; ConnectionToClient = null; @@ -967,10 +966,10 @@ namespace QuantumUNET.Components } [SerializeField] - private NetworkSceneId m_SceneId; + private QSBNetworkSceneId m_SceneId; [SerializeField] - private NetworkHash128 m_AssetId; + private QSBNetworkHash128 m_AssetId; [SerializeField] private bool m_ServerOnly; diff --git a/QuantumUNET/Messages/QSBAnimationMessage.cs b/QuantumUNET/Messages/QSBAnimationMessage.cs index 7278d7a9..4edfcb97 100644 --- a/QuantumUNET/Messages/QSBAnimationMessage.cs +++ b/QuantumUNET/Messages/QSBAnimationMessage.cs @@ -1,10 +1,8 @@ -using UnityEngine.Networking; - -namespace QuantumUNET.Messages +namespace QuantumUNET.Messages { internal class QSBAnimationMessage : QSBMessageBase { - public NetworkInstanceId netId; + public QSBNetworkInstanceId netId; public int stateHash; public float normalizedTime; public byte[] parameters; diff --git a/QuantumUNET/Messages/QSBAnimationParametersMessage.cs b/QuantumUNET/Messages/QSBAnimationParametersMessage.cs index d28169e5..6dbc666d 100644 --- a/QuantumUNET/Messages/QSBAnimationParametersMessage.cs +++ b/QuantumUNET/Messages/QSBAnimationParametersMessage.cs @@ -1,10 +1,8 @@ -using UnityEngine.Networking; - -namespace QuantumUNET.Messages +namespace QuantumUNET.Messages { internal class QSBAnimationParametersMessage : QSBMessageBase { - public NetworkInstanceId netId; + public QSBNetworkInstanceId netId; public byte[] parameters; public override void Deserialize(QSBNetworkReader reader) diff --git a/QuantumUNET/Messages/QSBAnimationTriggerMessage.cs b/QuantumUNET/Messages/QSBAnimationTriggerMessage.cs index 832dfa57..78553379 100644 --- a/QuantumUNET/Messages/QSBAnimationTriggerMessage.cs +++ b/QuantumUNET/Messages/QSBAnimationTriggerMessage.cs @@ -1,10 +1,8 @@ -using UnityEngine.Networking; - -namespace QuantumUNET.Messages +namespace QuantumUNET.Messages { internal class QSBAnimationTriggerMessage : QSBMessageBase { - public NetworkInstanceId netId; + public QSBNetworkInstanceId netId; public int hash; public override void Deserialize(QSBNetworkReader reader) diff --git a/QuantumUNET/Messages/QSBClientAuthorityMessage.cs b/QuantumUNET/Messages/QSBClientAuthorityMessage.cs index 925bc3ee..6ea87813 100644 --- a/QuantumUNET/Messages/QSBClientAuthorityMessage.cs +++ b/QuantumUNET/Messages/QSBClientAuthorityMessage.cs @@ -1,10 +1,8 @@ -using UnityEngine.Networking; - -namespace QuantumUNET.Messages +namespace QuantumUNET.Messages { internal class QSBClientAuthorityMessage : QSBMessageBase { - public NetworkInstanceId netId; + public QSBNetworkInstanceId netId; public bool authority; public override void Deserialize(QSBNetworkReader reader) diff --git a/QuantumUNET/Messages/QSBObjectDestroyMessage.cs b/QuantumUNET/Messages/QSBObjectDestroyMessage.cs index 3f483e49..66b7e05e 100644 --- a/QuantumUNET/Messages/QSBObjectDestroyMessage.cs +++ b/QuantumUNET/Messages/QSBObjectDestroyMessage.cs @@ -1,10 +1,8 @@ -using UnityEngine.Networking; - -namespace QuantumUNET.Messages +namespace QuantumUNET.Messages { internal class QSBObjectDestroyMessage : QSBMessageBase { - public NetworkInstanceId NetId; + public QSBNetworkInstanceId NetId; public override void Deserialize(QSBNetworkReader reader) => NetId = reader.ReadNetworkId(); diff --git a/QuantumUNET/Messages/QSBObjectSpawnMessage.cs b/QuantumUNET/Messages/QSBObjectSpawnMessage.cs index 98f5fe6c..f5aa0f05 100644 --- a/QuantumUNET/Messages/QSBObjectSpawnMessage.cs +++ b/QuantumUNET/Messages/QSBObjectSpawnMessage.cs @@ -1,12 +1,11 @@ using UnityEngine; -using UnityEngine.Networking; namespace QuantumUNET.Messages { internal class QSBObjectSpawnMessage : QSBMessageBase { - public NetworkInstanceId NetId; - public NetworkHash128 assetId; + public QSBNetworkInstanceId NetId; + public QSBNetworkHash128 assetId; public Vector3 Position; public byte[] Payload; public Quaternion Rotation; diff --git a/QuantumUNET/Messages/QSBObjectSpawnSceneMessage.cs b/QuantumUNET/Messages/QSBObjectSpawnSceneMessage.cs index 88cb6825..579df965 100644 --- a/QuantumUNET/Messages/QSBObjectSpawnSceneMessage.cs +++ b/QuantumUNET/Messages/QSBObjectSpawnSceneMessage.cs @@ -1,12 +1,11 @@ using UnityEngine; -using UnityEngine.Networking; namespace QuantumUNET.Messages { internal class QSBObjectSpawnSceneMessage : QSBMessageBase { - public NetworkInstanceId NetId; - public NetworkSceneId SceneId; + public QSBNetworkInstanceId NetId; + public QSBNetworkSceneId SceneId; public Vector3 Position; public byte[] Payload; diff --git a/QuantumUNET/Messages/QSBOwnerMessage.cs b/QuantumUNET/Messages/QSBOwnerMessage.cs index 7ba81954..8fc1fdc7 100644 --- a/QuantumUNET/Messages/QSBOwnerMessage.cs +++ b/QuantumUNET/Messages/QSBOwnerMessage.cs @@ -1,10 +1,8 @@ -using UnityEngine.Networking; - -namespace QuantumUNET.Messages +namespace QuantumUNET.Messages { internal class QSBOwnerMessage : QSBMessageBase { - public NetworkInstanceId NetId; + public QSBNetworkInstanceId NetId; public short PlayerControllerId; public override void Deserialize(QSBNetworkReader reader) diff --git a/QuantumUNET/QSBClientScene.cs b/QuantumUNET/QSBClientScene.cs index 7076b9ce..ace9dc44 100644 --- a/QuantumUNET/QSBClientScene.cs +++ b/QuantumUNET/QSBClientScene.cs @@ -18,11 +18,11 @@ namespace QuantumUNET public static int reconnectId { get; private set; } = -1; - public static Dictionary Objects => s_NetworkScene.localObjects; + public static Dictionary Objects => s_NetworkScene.localObjects; - public static Dictionary Prefabs => QSBNetworkScene.guidToPrefab; + public static Dictionary Prefabs => QSBNetworkScene.guidToPrefab; - public static Dictionary SpawnableObjects { get; private set; } + public static Dictionary SpawnableObjects { get; private set; } internal static void Shutdown() { @@ -294,7 +294,7 @@ namespace QuantumUNET internal static void PrepareToSpawnSceneObjects() { - SpawnableObjects = new Dictionary(); + SpawnableObjects = new Dictionary(); foreach (var networkIdentity in Resources.FindObjectsOfTypeAll()) { if (!networkIdentity.gameObject.activeSelf) @@ -314,7 +314,7 @@ namespace QuantumUNET } } - internal static QSBNetworkIdentity SpawnSceneObject(NetworkSceneId sceneId) + internal static QSBNetworkIdentity SpawnSceneObject(QSBNetworkSceneId sceneId) { QSBNetworkIdentity result; if (SpawnableObjects.ContainsKey(sceneId)) @@ -359,7 +359,7 @@ namespace QuantumUNET client.RegisterHandlerSafe(42, new QSBNetworkMessageDelegate(QSBNetworkAnimator.OnAnimationTriggerClientMessage)); } - internal static string GetStringForAssetId(NetworkHash128 assetId) + internal static string GetStringForAssetId(QSBNetworkHash128 assetId) { string result; if (QSBNetworkScene.GetPrefab(assetId, out var gameObject)) @@ -377,7 +377,7 @@ namespace QuantumUNET return result; } - public static void RegisterPrefab(GameObject prefab, NetworkHash128 newAssetId) => QSBNetworkScene.RegisterPrefab(prefab, newAssetId); + public static void RegisterPrefab(GameObject prefab, QSBNetworkHash128 newAssetId) => QSBNetworkScene.RegisterPrefab(prefab, newAssetId); public static void RegisterPrefab(GameObject prefab) => QSBNetworkScene.RegisterPrefab(prefab); @@ -385,19 +385,19 @@ namespace QuantumUNET public static void UnregisterPrefab(GameObject prefab) => QSBNetworkScene.UnregisterPrefab(prefab); - public static void RegisterSpawnHandler(NetworkHash128 assetId, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) => QSBNetworkScene.RegisterSpawnHandler(assetId, spawnHandler, unspawnHandler); + public static void RegisterSpawnHandler(QSBNetworkHash128 assetId, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) => QSBNetworkScene.RegisterSpawnHandler(assetId, spawnHandler, unspawnHandler); - public static void UnregisterSpawnHandler(NetworkHash128 assetId) => QSBNetworkScene.UnregisterSpawnHandler(assetId); + public static void UnregisterSpawnHandler(QSBNetworkHash128 assetId) => QSBNetworkScene.UnregisterSpawnHandler(assetId); public static void ClearSpawners() => QSBNetworkScene.ClearSpawners(); public static void DestroyAllClientObjects() => s_NetworkScene.DestroyAllClientObjects(); - public static void SetLocalObject(NetworkInstanceId netId, GameObject obj) => s_NetworkScene.SetLocalObject(netId, obj, s_IsSpawnFinished, false); + public static void SetLocalObject(QSBNetworkInstanceId netId, GameObject obj) => s_NetworkScene.SetLocalObject(netId, obj, s_IsSpawnFinished, false); - public static GameObject FindLocalObject(NetworkInstanceId netId) => s_NetworkScene.FindLocalObject(netId); + public static GameObject FindLocalObject(QSBNetworkInstanceId netId) => s_NetworkScene.FindLocalObject(netId); - private static void ApplySpawnPayload(QSBNetworkIdentity uv, Vector3 position, byte[] payload, NetworkInstanceId netId, GameObject newGameObject) + private static void ApplySpawnPayload(QSBNetworkIdentity uv, Vector3 position, byte[] payload, QSBNetworkInstanceId netId, GameObject newGameObject) { if (!uv.gameObject.activeSelf) { @@ -803,7 +803,7 @@ namespace QuantumUNET private struct PendingOwner { - public NetworkInstanceId netId; + public QSBNetworkInstanceId netId; public short playerControllerId; } diff --git a/QuantumUNET/QSBNetworkBehaviour.cs b/QuantumUNET/QSBNetworkBehaviour.cs index c243ce37..f946b403 100644 --- a/QuantumUNET/QSBNetworkBehaviour.cs +++ b/QuantumUNET/QSBNetworkBehaviour.cs @@ -15,7 +15,7 @@ namespace QuantumUNET public bool IsClient => MyView.IsClient; public bool IsLocalPlayer => MyView.IsLocalPlayer; public bool HasAuthority => MyView.HasAuthority; - public NetworkInstanceId NetId => MyView.NetId; + public QSBNetworkInstanceId NetId => MyView.NetId; public QSBNetworkConnection ConnectionToServer => MyView.ConnectionToServer; public QSBNetworkConnection ConnectionToClient => MyView.ConnectionToClient; public short PlayerControllerId => MyView.PlayerControllerId; @@ -404,11 +404,11 @@ namespace QuantumUNET internal static string GetCmdHashListName(int cmdHash) => GetCmdHashPrefixName(cmdHash, "InvokeSyncList"); - protected void SetSyncVarGameObject(GameObject newGameObject, ref GameObject gameObjectField, uint dirtyBit, ref NetworkInstanceId netIdField) + protected void SetSyncVarGameObject(GameObject newGameObject, ref GameObject gameObjectField, uint dirtyBit, ref QSBNetworkInstanceId netIdField) { if (!SyncVarHookGuard) { - NetworkInstanceId networkInstanceId = default; + QSBNetworkInstanceId networkInstanceId = default; if (newGameObject != null) { var component = newGameObject.GetComponent(); @@ -424,7 +424,7 @@ namespace QuantumUNET } } } - NetworkInstanceId networkInstanceId2 = default; + QSBNetworkInstanceId networkInstanceId2 = default; if (gameObjectField != null) { networkInstanceId2 = gameObjectField.GetComponent().NetId; diff --git a/QuantumUNET/QSBNetworkConnection.cs b/QuantumUNET/QSBNetworkConnection.cs index b74794ee..16749a99 100644 --- a/QuantumUNET/QSBNetworkConnection.cs +++ b/QuantumUNET/QSBNetworkConnection.cs @@ -20,7 +20,7 @@ namespace QuantumUNET public List PlayerControllers { get; } = new List(); - public HashSet ClientOwnedObjects { get; private set; } + public HashSet ClientOwnedObjects { get; private set; } public bool isConnected => hostId != -1; @@ -439,7 +439,7 @@ namespace QuantumUNET { if (ClientOwnedObjects == null) { - ClientOwnedObjects = new HashSet(); + ClientOwnedObjects = new HashSet(); } ClientOwnedObjects.Add(obj.NetId); } diff --git a/QuantumUNET/QSBNetworkHash128.cs b/QuantumUNET/QSBNetworkHash128.cs new file mode 100644 index 00000000..b60370b3 --- /dev/null +++ b/QuantumUNET/QSBNetworkHash128.cs @@ -0,0 +1,125 @@ +using System; + +namespace QuantumUNET +{ + [Serializable] + public struct QSBNetworkHash128 + { + public byte i0; + public byte i1; + public byte i2; + public byte i3; + public byte i4; + public byte i5; + public byte i6; + public byte i7; + public byte i8; + public byte i9; + public byte i10; + public byte i11; + public byte i12; + public byte i13; + public byte i14; + public byte i15; + + public void Reset() + { + i0 = 0; + i1 = 0; + i2 = 0; + i3 = 0; + i4 = 0; + i5 = 0; + i6 = 0; + i7 = 0; + i8 = 0; + i9 = 0; + i10 = 0; + i11 = 0; + i12 = 0; + i13 = 0; + i14 = 0; + i15 = 0; + } + + public bool IsValid() + => (i0 | i1 | i2 | i3 | i4 | i5 | i6 | i7 | i8 | i9 | i10 | i11 | i12 | i13 | i14 | i15) != 0; + + private static int HexToNumber(char c) + { + int result; + if (c >= '0' && c <= '9') + { + result = c - '0'; + } + else if (c >= 'a' && c <= 'f') + { + result = c - 'a' + '\n'; + } + else if (c >= 'A' && c <= 'F') + { + result = c - 'A' + '\n'; + } + else + { + result = 0; + } + return result; + } + + public static QSBNetworkHash128 Parse(string text) + { + var length = text.Length; + if (length < 32) + { + var str = ""; + for (var i = 0; i < 32 - length; i++) + { + str += "0"; + } + text = str + text; + } + QSBNetworkHash128 result; + result.i0 = (byte)(HexToNumber(text[0]) * 16 + HexToNumber(text[1])); + result.i1 = (byte)(HexToNumber(text[2]) * 16 + HexToNumber(text[3])); + result.i2 = (byte)(HexToNumber(text[4]) * 16 + HexToNumber(text[5])); + result.i3 = (byte)(HexToNumber(text[6]) * 16 + HexToNumber(text[7])); + result.i4 = (byte)(HexToNumber(text[8]) * 16 + HexToNumber(text[9])); + result.i5 = (byte)(HexToNumber(text[10]) * 16 + HexToNumber(text[11])); + result.i6 = (byte)(HexToNumber(text[12]) * 16 + HexToNumber(text[13])); + result.i7 = (byte)(HexToNumber(text[14]) * 16 + HexToNumber(text[15])); + result.i8 = (byte)(HexToNumber(text[16]) * 16 + HexToNumber(text[17])); + result.i9 = (byte)(HexToNumber(text[18]) * 16 + HexToNumber(text[19])); + result.i10 = (byte)(HexToNumber(text[20]) * 16 + HexToNumber(text[21])); + result.i11 = (byte)(HexToNumber(text[22]) * 16 + HexToNumber(text[23])); + result.i12 = (byte)(HexToNumber(text[24]) * 16 + HexToNumber(text[25])); + result.i13 = (byte)(HexToNumber(text[26]) * 16 + HexToNumber(text[27])); + result.i14 = (byte)(HexToNumber(text[28]) * 16 + HexToNumber(text[29])); + result.i15 = (byte)(HexToNumber(text[30]) * 16 + HexToNumber(text[31])); + return result; + } + + public override string ToString() + { + return string.Format("{0:x2}{1:x2}{2:x2}{3:x2}{4:x2}{5:x2}{6:x2}{7:x2}{8:x2}{9:x2}{10:x2}{11:x2}{12:x2}{13:x2}{14:x2}{15:x2}", new object[] + { + i0, + i1, + i2, + i3, + i4, + i5, + i6, + i7, + i8, + i9, + i10, + i11, + i12, + i13, + i14, + i15 + }); + } + } +} diff --git a/QuantumUNET/QSBNetworkInstanceId.cs b/QuantumUNET/QSBNetworkInstanceId.cs new file mode 100644 index 00000000..1e165493 --- /dev/null +++ b/QuantumUNET/QSBNetworkInstanceId.cs @@ -0,0 +1,41 @@ +using System; +using UnityEngine; + +namespace QuantumUNET +{ + [Serializable] + public struct QSBNetworkInstanceId + { + public uint Value => m_Value; + + [SerializeField] + private readonly uint m_Value; + + public QSBNetworkInstanceId(uint value) + { + m_Value = value; + } + + public bool IsEmpty() + => m_Value == 0U; + + public override int GetHashCode() + => (int)m_Value; + + public override bool Equals(object obj) + => obj is QSBNetworkInstanceId id && this == id; + + public static bool operator ==(QSBNetworkInstanceId c1, QSBNetworkInstanceId c2) + => c1.m_Value == c2.m_Value; + + public static bool operator !=(QSBNetworkInstanceId c1, QSBNetworkInstanceId c2) + => c1.m_Value != c2.m_Value; + + public override string ToString() + => m_Value.ToString(); + + public static QSBNetworkInstanceId Invalid = new QSBNetworkInstanceId(uint.MaxValue); + + internal static QSBNetworkInstanceId Zero = new QSBNetworkInstanceId(0U); + } +} diff --git a/QuantumUNET/QSBNetworkReader.cs b/QuantumUNET/QSBNetworkReader.cs index afdb40e3..27f4a67c 100644 --- a/QuantumUNET/QSBNetworkReader.cs +++ b/QuantumUNET/QSBNetworkReader.cs @@ -162,9 +162,9 @@ namespace QuantumUNET return result; } - public NetworkInstanceId ReadNetworkId() => new NetworkInstanceId(ReadPackedUInt32()); + public QSBNetworkInstanceId ReadNetworkId() => new QSBNetworkInstanceId(ReadPackedUInt32()); - public NetworkSceneId ReadSceneId() => new NetworkSceneId(ReadPackedUInt32()); + public QSBNetworkSceneId ReadSceneId() => new QSBNetworkSceneId(ReadPackedUInt32()); public byte ReadByte() => m_buf.ReadByte(); @@ -363,9 +363,9 @@ namespace QuantumUNET }; } - public NetworkHash128 ReadNetworkHash128() + public QSBNetworkHash128 ReadNetworkHash128() { - NetworkHash128 result; + QSBNetworkHash128 result; result.i0 = ReadByte(); result.i1 = ReadByte(); result.i2 = ReadByte(); diff --git a/QuantumUNET/QSBNetworkScene.cs b/QuantumUNET/QSBNetworkScene.cs index 782a8436..e4b51499 100644 --- a/QuantumUNET/QSBNetworkScene.cs +++ b/QuantumUNET/QSBNetworkScene.cs @@ -7,13 +7,13 @@ namespace QuantumUNET { internal class QSBNetworkScene { - internal static Dictionary guidToPrefab { get; } = new Dictionary(); + internal static Dictionary guidToPrefab { get; } = new Dictionary(); - internal static Dictionary spawnHandlers { get; } = new Dictionary(); + internal static Dictionary spawnHandlers { get; } = new Dictionary(); - internal static Dictionary unspawnHandlers { get; } = new Dictionary(); + internal static Dictionary unspawnHandlers { get; } = new Dictionary(); - internal Dictionary localObjects { get; } = new Dictionary(); + internal Dictionary localObjects { get; } = new Dictionary(); internal void Shutdown() { @@ -21,7 +21,7 @@ namespace QuantumUNET ClearSpawners(); } - internal void SetLocalObject(NetworkInstanceId netId, GameObject obj, bool isClient, bool isServer) + internal void SetLocalObject(QSBNetworkInstanceId netId, GameObject obj, bool isClient, bool isServer) { if (obj == null) { @@ -43,7 +43,7 @@ namespace QuantumUNET } } - internal GameObject FindLocalObject(NetworkInstanceId netId) + internal GameObject FindLocalObject(QSBNetworkInstanceId netId) { if (localObjects.ContainsKey(netId)) { @@ -56,7 +56,7 @@ namespace QuantumUNET return null; } - internal bool GetNetworkIdentity(NetworkInstanceId netId, out QSBNetworkIdentity uv) + internal bool GetNetworkIdentity(QSBNetworkInstanceId netId, out QSBNetworkIdentity uv) { bool result; if (localObjects.ContainsKey(netId) && localObjects[netId] != null) @@ -72,9 +72,9 @@ namespace QuantumUNET return result; } - internal bool RemoveLocalObject(NetworkInstanceId netId) => localObjects.Remove(netId); + internal bool RemoveLocalObject(QSBNetworkInstanceId netId) => localObjects.Remove(netId); - internal bool RemoveLocalObjectAndDestroy(NetworkInstanceId netId) + internal bool RemoveLocalObjectAndDestroy(QSBNetworkInstanceId netId) { bool result; if (localObjects.ContainsKey(netId)) @@ -92,7 +92,7 @@ namespace QuantumUNET internal void ClearLocalObjects() => localObjects.Clear(); - internal static void RegisterPrefab(GameObject prefab, NetworkHash128 newAssetId) + internal static void RegisterPrefab(GameObject prefab, QSBNetworkHash128 newAssetId) { var component = prefab.GetComponent(); if (component) @@ -127,7 +127,7 @@ namespace QuantumUNET } } - internal static bool GetPrefab(NetworkHash128 assetId, out GameObject prefab) + internal static bool GetPrefab(QSBNetworkHash128 assetId, out GameObject prefab) { bool result; if (!assetId.IsValid()) @@ -155,13 +155,13 @@ namespace QuantumUNET unspawnHandlers.Clear(); } - public static void UnregisterSpawnHandler(NetworkHash128 assetId) + public static void UnregisterSpawnHandler(QSBNetworkHash128 assetId) { spawnHandlers.Remove(assetId); unspawnHandlers.Remove(assetId); } - internal static void RegisterSpawnHandler(NetworkHash128 assetId, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) + internal static void RegisterSpawnHandler(QSBNetworkHash128 assetId, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) { if (spawnHandler == null || unspawnHandler == null) { @@ -216,7 +216,7 @@ namespace QuantumUNET } } - internal static bool GetSpawnHandler(NetworkHash128 assetId, out SpawnDelegate handler) + internal static bool GetSpawnHandler(QSBNetworkHash128 assetId, out SpawnDelegate handler) { bool result; if (spawnHandlers.ContainsKey(assetId)) @@ -232,7 +232,7 @@ namespace QuantumUNET return result; } - internal static bool InvokeUnSpawnHandler(NetworkHash128 assetId, GameObject obj) + internal static bool InvokeUnSpawnHandler(QSBNetworkHash128 assetId, GameObject obj) { bool result; if (unspawnHandlers.ContainsKey(assetId) && unspawnHandlers[assetId] != null) diff --git a/QuantumUNET/QSBNetworkSceneId.cs b/QuantumUNET/QSBNetworkSceneId.cs new file mode 100644 index 00000000..c9872960 --- /dev/null +++ b/QuantumUNET/QSBNetworkSceneId.cs @@ -0,0 +1,36 @@ +using System; +using UnityEngine; + +namespace QuantumUNET +{ + [Serializable] + public struct QSBNetworkSceneId + { + public uint Value => m_Value; + + [SerializeField] + private uint m_Value; + + public QSBNetworkSceneId(uint value) + { + m_Value = value; + } + + public bool IsEmpty() + => m_Value == 0U; + + public override int GetHashCode() + => (int)m_Value; + + public override bool Equals(object obj) + => obj is QSBNetworkSceneId id && this == id; + + public static bool operator ==(QSBNetworkSceneId c1, QSBNetworkSceneId c2) + => c1.m_Value == c2.m_Value; + + public static bool operator !=(QSBNetworkSceneId c1, QSBNetworkSceneId c2) + => c1.m_Value != c2.m_Value; + + public override string ToString() => m_Value.ToString(); + } +} diff --git a/QuantumUNET/QSBNetworkServer.cs b/QuantumUNET/QSBNetworkServer.cs index 702a465c..5843883c 100644 --- a/QuantumUNET/QSBNetworkServer.cs +++ b/QuantumUNET/QSBNetworkServer.cs @@ -15,7 +15,7 @@ namespace QuantumUNET private QSBNetworkServer() { NetworkTransport.Init(); - m_RemoveList = new HashSet(); + m_RemoveList = new HashSet(); m_ExternalConnections = new HashSet(); m_NetworkScene = new QSBNetworkScene(); m_SimpleServerSimple = new ServerSimpleWrapper(this); @@ -33,7 +33,7 @@ namespace QuantumUNET public static HostTopology hostTopology => instance.m_SimpleServerSimple.hostTopology; - public static Dictionary objects => instance.m_NetworkScene.localObjects; + public static Dictionary objects => instance.m_NetworkScene.localObjects; public static bool dontListen { get; set; } @@ -215,7 +215,7 @@ namespace QuantumUNET m_SimpleServerSimple.RemoveConnectionAtIndex(0); } - internal void SetLocalObjectOnServer(NetworkInstanceId netId, GameObject obj) + internal void SetLocalObjectOnServer(QSBNetworkInstanceId netId, GameObject obj) { Debug.Log(string.Concat(new object[] { @@ -1277,7 +1277,7 @@ namespace QuantumUNET { if (conn.ClientOwnedObjects != null) { - var hashSet = new HashSet(conn.ClientOwnedObjects); + var hashSet = new HashSet(conn.ClientOwnedObjects); foreach (var netId in hashSet) { var gameObject = FindLocalObject(netId); @@ -1429,14 +1429,14 @@ namespace QuantumUNET return result; } - public static bool SpawnWithClientAuthority(GameObject obj, NetworkHash128 assetId, QSBNetworkConnection conn) + public static bool SpawnWithClientAuthority(GameObject obj, QSBNetworkHash128 assetId, QSBNetworkConnection conn) { Spawn(obj, assetId); var component = obj.GetComponent(); return !(component == null) && component.IsServer && component.AssignClientAuthority(conn); } - public static void Spawn(GameObject obj, NetworkHash128 assetId) + public static void Spawn(GameObject obj, QSBNetworkHash128 assetId) { if (VerifyCanSpawn(obj)) { @@ -1498,7 +1498,7 @@ namespace QuantumUNET return result; } - public static GameObject FindLocalObject(NetworkInstanceId netId) => instance.m_NetworkScene.FindLocalObject(netId); + public static GameObject FindLocalObject(QSBNetworkInstanceId netId) => instance.m_NetworkScene.FindLocalObject(netId); private static bool ValidateSceneObject(QSBNetworkIdentity netId) => netId.gameObject.hideFlags != HideFlags.NotEditable && netId.gameObject.hideFlags != HideFlags.HideAndDontSave && !netId.SceneId.IsEmpty(); @@ -1583,7 +1583,7 @@ namespace QuantumUNET private float m_MaxDelay = 0.1f; - private HashSet m_RemoveList; + private HashSet m_RemoveList; private int m_RemoveListCount; diff --git a/QuantumUNET/QSBNetworkWriter.cs b/QuantumUNET/QSBNetworkWriter.cs index 0256d3a8..90582ea6 100644 --- a/QuantumUNET/QSBNetworkWriter.cs +++ b/QuantumUNET/QSBNetworkWriter.cs @@ -152,9 +152,9 @@ namespace QuantumUNET } } - public void Write(NetworkInstanceId value) => WritePackedUInt32(value.Value); + public void Write(QSBNetworkInstanceId value) => WritePackedUInt32(value.Value); - public void Write(NetworkSceneId value) => WritePackedUInt32(value.Value); + public void Write(QSBNetworkSceneId value) => WritePackedUInt32(value.Value); public void Write(char value) => m_Buffer.WriteByte((byte)value); @@ -373,7 +373,7 @@ namespace QuantumUNET Write(value.m33); } - public void Write(NetworkHash128 value) + public void Write(QSBNetworkHash128 value) { Write(value.i0); Write(value.i1); @@ -393,7 +393,7 @@ namespace QuantumUNET Write(value.i15); } - public void Write(NetworkIdentity value) + public void Write(QSBNetworkIdentity value) { if (value == null) { @@ -401,7 +401,7 @@ namespace QuantumUNET } else { - Write(value.netId); + Write(value.NetId); } } @@ -413,10 +413,10 @@ namespace QuantumUNET } else { - var component = value.gameObject.GetComponent(); + var component = value.gameObject.GetComponent(); if (component != null) { - Write(component.netId); + Write(component.NetId); } else { diff --git a/QuantumUNET/QuantumUNET.csproj b/QuantumUNET/QuantumUNET.csproj index 3db8592e..51d050ee 100644 --- a/QuantumUNET/QuantumUNET.csproj +++ b/QuantumUNET/QuantumUNET.csproj @@ -121,9 +121,12 @@ + + + From a657c5ee6c37a26aaca32f6865403c02b08ccd1c Mon Sep 17 00:00:00 2001 From: Mister_Nebula <41904486+misternebula@users.noreply.github.com> Date: Tue, 15 Dec 2020 16:20:28 +0000 Subject: [PATCH 08/10] cleanup --- .../Components/QSBNetworkManagerUNET.cs | 85 +------------------ 1 file changed, 1 insertion(+), 84 deletions(-) diff --git a/QuantumUNET/Components/QSBNetworkManagerUNET.cs b/QuantumUNET/Components/QSBNetworkManagerUNET.cs index ebf6da9d..2067a547 100644 --- a/QuantumUNET/Components/QSBNetworkManagerUNET.cs +++ b/QuantumUNET/Components/QSBNetworkManagerUNET.cs @@ -31,7 +31,6 @@ namespace QuantumUNET.Components public float packetLossPercentage { get; set; } public float maxDelay { get; set; } = 0.01f; public GameObject playerPrefab { get; set; } - public PlayerSpawnMethod playerSpawnMethod { get; set; } public List spawnPrefabs { get; } = new List(); public QSBNetworkClient client; public int maxConnections { get; set; } = 4; @@ -41,8 +40,6 @@ namespace QuantumUNET.Components private GlobalConfig m_GlobalConfig; private int m_MaxBufferedPackets = 16; private bool m_AllowFragmentation = true; - private static List s_StartPositions = new List(); - private static int s_StartPositionIndex; private static QSBAddPlayerMessage s_AddPlayerMessage = new QSBAddPlayerMessage(); private static QSBRemovePlayerMessage s_RemovePlayerMessage = new QSBRemovePlayerMessage(); private static QSBErrorMessage s_ErrorMessage = new QSBErrorMessage(); @@ -50,8 +47,6 @@ namespace QuantumUNET.Components private static QSBNetworkConnection s_ClientReadyConnection; private static string s_Address; - public List startPositions => s_StartPositions; - public bool customConfig { get; set; } public ConnectionConfig connectionConfig @@ -446,8 +441,6 @@ namespace QuantumUNET.Components s_LoadingSceneAsync = SceneManager.LoadSceneAsync(newSceneName); var msg = new QSBStringMessage(networkSceneName); QSBNetworkServer.SendToAll(39, msg); - s_StartPositionIndex = 0; - s_StartPositions.Clear(); } } @@ -531,44 +524,12 @@ namespace QuantumUNET.Components } } - public static void RegisterStartPosition(Transform start) - { - if (LogFilter.logDebug) - { - Debug.Log(string.Concat(new object[] - { - "RegisterStartPosition: (", - start.gameObject.name, - ") ", - start.position - })); - } - s_StartPositions.Add(start); - } - - public static void UnRegisterStartPosition(Transform start) - { - if (LogFilter.logDebug) - { - Debug.Log(string.Concat(new object[] - { - "UnRegisterStartPosition: (", - start.gameObject.name, - ") ", - start.position - })); - } - s_StartPositions.Remove(start); - } - public bool IsClientConnected() => client != null && client.isConnected; public static void Shutdown() { if (!(singleton == null)) { - s_StartPositions.Clear(); - s_StartPositionIndex = 0; s_ClientReadyConnection = null; singleton.StopHost(); singleton = null; @@ -784,55 +745,11 @@ namespace QuantumUNET.Components } else { - var startPosition = GetStartPosition(); - GameObject player; - if (startPosition != null) - { - player = Instantiate(playerPrefab, startPosition.position, startPosition.rotation); - } - else - { - player = Instantiate(playerPrefab, Vector3.zero, Quaternion.identity); - } + var player = Instantiate(playerPrefab, Vector3.zero, Quaternion.identity); QSBNetworkServer.AddPlayerForConnection(conn, player, playerControllerId); } } - public Transform GetStartPosition() - { - if (s_StartPositions.Count > 0) - { - for (var i = s_StartPositions.Count - 1; i >= 0; i--) - { - if (s_StartPositions[i] == null) - { - s_StartPositions.RemoveAt(i); - } - } - } - Transform result; - if (playerSpawnMethod == PlayerSpawnMethod.Random && s_StartPositions.Count > 0) - { - var index = UnityEngine.Random.Range(0, s_StartPositions.Count); - result = s_StartPositions[index]; - } - else if (playerSpawnMethod == PlayerSpawnMethod.RoundRobin && s_StartPositions.Count > 0) - { - if (s_StartPositionIndex >= s_StartPositions.Count) - { - s_StartPositionIndex = 0; - } - var transform = s_StartPositions[s_StartPositionIndex]; - s_StartPositionIndex++; - result = transform; - } - else - { - result = null; - } - return result; - } - public virtual void OnServerRemovePlayer(QSBNetworkConnection conn, QSBPlayerController player) { if (player.Gameobject != null) From 9f4d88690306b4b330d265a436fde8d44e4733e1 Mon Sep 17 00:00:00 2001 From: Mister_Nebula <41904486+misternebula@users.noreply.github.com> Date: Tue, 15 Dec 2020 16:37:52 +0000 Subject: [PATCH 09/10] more --- .../Events/ConversationMessage.cs | 2 +- .../Events/ConversationStartEndMessage.cs | 2 +- .../Events/DialogueConditionMessage.cs | 2 +- QSB/Messaging/EnumMessage.cs | 2 +- QSB/Messaging/FloatMessage.cs | 2 +- QSB/Messaging/PlayerMessage.cs | 4 +- QSB/Messaging/ToggleMessage.cs | 2 +- QSB/OrbSync/Events/OrbSlotMessage.cs | 2 +- QSB/Player/Events/PlayerJoinMessage.cs | 2 +- QSB/Player/Events/PlayerStateMessage.cs | 2 +- QSB/TimeSync/Events/ServerTimeMessage.cs | 2 +- .../Events/BoolWorldObjectMessage.cs | 2 +- QSB/WorldSync/Events/WorldObjectMessage.cs | 2 +- QuantumUNET/Components/QSBNetworkAnimator.cs | 1 + QuantumUNET/Components/QSBNetworkIdentity.cs | 1 + .../Components/QSBNetworkManagerUNET.cs | 135 ++++-------------- QuantumUNET/Components/QSBNetworkTransform.cs | 20 +-- QuantumUNET/Messages/QSBAddPlayerMessage.cs | 4 +- QuantumUNET/Messages/QSBAnimationMessage.cs | 4 +- .../Messages/QSBAnimationParametersMessage.cs | 4 +- .../Messages/QSBAnimationTriggerMessage.cs | 4 +- QuantumUNET/Messages/QSBCRCMessage.cs | 4 +- .../Messages/QSBClientAuthorityMessage.cs | 4 +- QuantumUNET/Messages/QSBEmptyMessage.cs | 4 +- QuantumUNET/Messages/QSBErrorMessage.cs | 4 +- QuantumUNET/Messages/QSBMessageBase.cs | 4 +- QuantumUNET/Messages/QSBNetworkMessage.cs | 3 +- .../Messages/QSBObjectDestroyMessage.cs | 4 +- .../Messages/QSBObjectSpawnFinishedMessage.cs | 4 +- QuantumUNET/Messages/QSBObjectSpawnMessage.cs | 3 +- .../Messages/QSBObjectSpawnSceneMessage.cs | 3 +- QuantumUNET/Messages/QSBOwnerMessage.cs | 4 +- .../Messages/QSBRemovePlayerMessage.cs | 4 +- QuantumUNET/Messages/QSBSpawnDelegate.cs | 6 + QuantumUNET/Messages/QSBStringMessage.cs | 4 +- QuantumUNET/QSBClientScene.cs | 17 +-- QuantumUNET/QSBLocalClient.cs | 1 + QuantumUNET/QSBNetworkBehaviour.cs | 1 + QuantumUNET/QSBNetworkCRC.cs | 55 +++---- QuantumUNET/QSBNetworkClient.cs | 1 + QuantumUNET/QSBNetworkConnection.cs | 1 + QuantumUNET/QSBNetworkScene.cs | 8 +- QuantumUNET/QSBNetworkServer.cs | 1 + QuantumUNET/QSBNetworkServerSimple.cs | 1 + QuantumUNET/QSBULocalConnectionToClient.cs | 1 + QuantumUNET/QSBULocalConnectionToServer.cs | 1 + QuantumUNET/QuantumUNET.csproj | 11 +- .../{ => Transport}/QSBChannelBuffer.cs | 17 +-- .../{ => Transport}/QSBChannelPacket.cs | 2 +- QuantumUNET/{ => Transport}/QSBNetBuffer.cs | 2 +- .../{ => Transport}/QSBNetworkReader.cs | 2 +- .../{ => Transport}/QSBNetworkWriter.cs | 2 +- 52 files changed, 152 insertions(+), 228 deletions(-) create mode 100644 QuantumUNET/Messages/QSBSpawnDelegate.cs rename QuantumUNET/{ => Transport}/QSBChannelBuffer.cs (95%) rename QuantumUNET/{ => Transport}/QSBChannelPacket.cs (97%) rename QuantumUNET/{ => Transport}/QSBNetBuffer.cs (99%) rename QuantumUNET/{ => Transport}/QSBNetworkReader.cs (99%) rename QuantumUNET/{ => Transport}/QSBNetworkWriter.cs (99%) diff --git a/QSB/ConversationSync/Events/ConversationMessage.cs b/QSB/ConversationSync/Events/ConversationMessage.cs index 206072c0..9a5c85e4 100644 --- a/QSB/ConversationSync/Events/ConversationMessage.cs +++ b/QSB/ConversationSync/Events/ConversationMessage.cs @@ -1,5 +1,5 @@ using QSB.Messaging; -using QuantumUNET; +using QuantumUNET.Transport; namespace QSB.ConversationSync.Events { diff --git a/QSB/ConversationSync/Events/ConversationStartEndMessage.cs b/QSB/ConversationSync/Events/ConversationStartEndMessage.cs index 75db950d..c836868b 100644 --- a/QSB/ConversationSync/Events/ConversationStartEndMessage.cs +++ b/QSB/ConversationSync/Events/ConversationStartEndMessage.cs @@ -1,5 +1,5 @@ using QSB.Messaging; -using QuantumUNET; +using QuantumUNET.Transport; namespace QSB.ConversationSync.Events { diff --git a/QSB/DialogueConditionSync/Events/DialogueConditionMessage.cs b/QSB/DialogueConditionSync/Events/DialogueConditionMessage.cs index 3d4252e9..3e424967 100644 --- a/QSB/DialogueConditionSync/Events/DialogueConditionMessage.cs +++ b/QSB/DialogueConditionSync/Events/DialogueConditionMessage.cs @@ -1,5 +1,5 @@ using QSB.Messaging; -using QuantumUNET; +using QuantumUNET.Transport; namespace QSB.DialogueConditionSync.Events { diff --git a/QSB/Messaging/EnumMessage.cs b/QSB/Messaging/EnumMessage.cs index 0624f836..4886c66b 100644 --- a/QSB/Messaging/EnumMessage.cs +++ b/QSB/Messaging/EnumMessage.cs @@ -1,4 +1,4 @@ -using QuantumUNET; +using QuantumUNET.Transport; namespace QSB.Messaging { diff --git a/QSB/Messaging/FloatMessage.cs b/QSB/Messaging/FloatMessage.cs index 832c6a0c..5d1685f7 100644 --- a/QSB/Messaging/FloatMessage.cs +++ b/QSB/Messaging/FloatMessage.cs @@ -1,4 +1,4 @@ -using QuantumUNET; +using QuantumUNET.Transport; namespace QSB.Messaging { diff --git a/QSB/Messaging/PlayerMessage.cs b/QSB/Messaging/PlayerMessage.cs index 9fb00238..e5a2b1c5 100644 --- a/QSB/Messaging/PlayerMessage.cs +++ b/QSB/Messaging/PlayerMessage.cs @@ -1,5 +1,5 @@ -using QuantumUNET; -using QuantumUNET.Messages; +using QuantumUNET.Messages; +using QuantumUNET.Transport; namespace QSB.Messaging { diff --git a/QSB/Messaging/ToggleMessage.cs b/QSB/Messaging/ToggleMessage.cs index 0956b3b2..19299079 100644 --- a/QSB/Messaging/ToggleMessage.cs +++ b/QSB/Messaging/ToggleMessage.cs @@ -1,4 +1,4 @@ -using QuantumUNET; +using QuantumUNET.Transport; namespace QSB.Messaging { diff --git a/QSB/OrbSync/Events/OrbSlotMessage.cs b/QSB/OrbSync/Events/OrbSlotMessage.cs index c25da215..553d6dc8 100644 --- a/QSB/OrbSync/Events/OrbSlotMessage.cs +++ b/QSB/OrbSync/Events/OrbSlotMessage.cs @@ -1,5 +1,5 @@ using QSB.Messaging; -using QuantumUNET; +using QuantumUNET.Transport; namespace QSB.OrbSync.Events { diff --git a/QSB/Player/Events/PlayerJoinMessage.cs b/QSB/Player/Events/PlayerJoinMessage.cs index 0e695424..51f86cce 100644 --- a/QSB/Player/Events/PlayerJoinMessage.cs +++ b/QSB/Player/Events/PlayerJoinMessage.cs @@ -1,5 +1,5 @@ using QSB.Messaging; -using QuantumUNET; +using QuantumUNET.Transport; namespace QSB.Player.Events { diff --git a/QSB/Player/Events/PlayerStateMessage.cs b/QSB/Player/Events/PlayerStateMessage.cs index 7d2d341f..7317da16 100644 --- a/QSB/Player/Events/PlayerStateMessage.cs +++ b/QSB/Player/Events/PlayerStateMessage.cs @@ -1,5 +1,5 @@ using QSB.Messaging; -using QuantumUNET; +using QuantumUNET.Transport; namespace QSB.Player.Events { diff --git a/QSB/TimeSync/Events/ServerTimeMessage.cs b/QSB/TimeSync/Events/ServerTimeMessage.cs index 407d2bfc..1979069a 100644 --- a/QSB/TimeSync/Events/ServerTimeMessage.cs +++ b/QSB/TimeSync/Events/ServerTimeMessage.cs @@ -1,5 +1,5 @@ using QSB.Messaging; -using QuantumUNET; +using QuantumUNET.Transport; namespace QSB.TimeSync.Events { diff --git a/QSB/WorldSync/Events/BoolWorldObjectMessage.cs b/QSB/WorldSync/Events/BoolWorldObjectMessage.cs index 99f820cf..a5456a02 100644 --- a/QSB/WorldSync/Events/BoolWorldObjectMessage.cs +++ b/QSB/WorldSync/Events/BoolWorldObjectMessage.cs @@ -1,4 +1,4 @@ -using QuantumUNET; +using QuantumUNET.Transport; namespace QSB.WorldSync.Events { diff --git a/QSB/WorldSync/Events/WorldObjectMessage.cs b/QSB/WorldSync/Events/WorldObjectMessage.cs index 12ec48f8..f6f47fdf 100644 --- a/QSB/WorldSync/Events/WorldObjectMessage.cs +++ b/QSB/WorldSync/Events/WorldObjectMessage.cs @@ -1,5 +1,5 @@ using QSB.Messaging; -using QuantumUNET; +using QuantumUNET.Transport; namespace QSB.WorldSync.Events { diff --git a/QuantumUNET/Components/QSBNetworkAnimator.cs b/QuantumUNET/Components/QSBNetworkAnimator.cs index 81cd6fcc..e4865c05 100644 --- a/QuantumUNET/Components/QSBNetworkAnimator.cs +++ b/QuantumUNET/Components/QSBNetworkAnimator.cs @@ -1,4 +1,5 @@ using QuantumUNET.Messages; +using QuantumUNET.Transport; using UnityEngine; namespace QuantumUNET.Components diff --git a/QuantumUNET/Components/QSBNetworkIdentity.cs b/QuantumUNET/Components/QSBNetworkIdentity.cs index 325b22d8..8a42c841 100644 --- a/QuantumUNET/Components/QSBNetworkIdentity.cs +++ b/QuantumUNET/Components/QSBNetworkIdentity.cs @@ -1,5 +1,6 @@ using OWML.Logging; using QuantumUNET.Messages; +using QuantumUNET.Transport; using System; using System.Collections.Generic; using System.Collections.ObjectModel; diff --git a/QuantumUNET/Components/QSBNetworkManagerUNET.cs b/QuantumUNET/Components/QSBNetworkManagerUNET.cs index 2067a547..c0ecca70 100644 --- a/QuantumUNET/Components/QSBNetworkManagerUNET.cs +++ b/QuantumUNET/Components/QSBNetworkManagerUNET.cs @@ -176,26 +176,17 @@ namespace QuantumUNET.Components { if (!QSBNetworkServer.Listen(serverBindAddress, networkPort)) { - if (LogFilter.logError) - { - Debug.LogError("StartServer listen on " + serverBindAddress + " failed."); - } + Debug.LogError("StartServer listen on " + serverBindAddress + " failed."); return false; } } else if (!QSBNetworkServer.Listen(networkPort)) { - if (LogFilter.logError) - { - Debug.LogError("StartServer listen failed."); - } + Debug.LogError("StartServer listen failed."); return false; } RegisterServerMessages(); - if (LogFilter.logDebug) - { - Debug.Log("NetworkManager StartServer port:" + networkPort); - } + Debug.Log("NetworkManager StartServer port:" + networkPort); isNetworkActive = true; var name = SceneManager.GetSceneAt(0).name; if (!string.IsNullOrEmpty(onlineScene) && onlineScene != name && onlineScene != offlineScene) @@ -363,10 +354,7 @@ namespace QuantumUNET.Components private QSBNetworkClient ConnectLocalClient() { - if (LogFilter.logDebug) - { - Debug.Log("NetworkManager StartHost port:" + networkPort); - } + Debug.Log("NetworkManager StartHost port:" + networkPort); networkAddress = "localhost"; client = QSBClientScene.ConnectLocalServer(); RegisterClientMessages(client); @@ -385,10 +373,7 @@ namespace QuantumUNET.Components if (QSBNetworkServer.active) { OnStopServer(); - if (LogFilter.logDebug) - { - Debug.Log("NetworkManager StopServer"); - } + Debug.Log("NetworkManager StopServer"); isNetworkActive = false; QSBNetworkServer.Shutdown(); if (!string.IsNullOrEmpty(offlineScene)) @@ -402,10 +387,7 @@ namespace QuantumUNET.Components public void StopClient() { OnStopClient(); - if (LogFilter.logDebug) - { - Debug.Log("NetworkManager StopClient"); - } + Debug.Log("NetworkManager StopClient"); isNetworkActive = false; if (client != null) { @@ -425,17 +407,11 @@ namespace QuantumUNET.Components { if (string.IsNullOrEmpty(newSceneName)) { - if (LogFilter.logError) - { - Debug.LogError("ServerChangeScene empty scene name"); - } + Debug.LogError("ServerChangeScene empty scene name"); } else { - if (LogFilter.logDebug) - { - Debug.Log("ServerChangeScene " + newSceneName); - } + Debug.Log("ServerChangeScene " + newSceneName); QSBNetworkServer.SetAllClientsNotReady(); networkSceneName = newSceneName; s_LoadingSceneAsync = SceneManager.LoadSceneAsync(newSceneName); @@ -456,17 +432,11 @@ namespace QuantumUNET.Components { if (string.IsNullOrEmpty(newSceneName)) { - if (LogFilter.logError) - { - Debug.LogError("ClientChangeScene empty scene name"); - } + Debug.LogError("ClientChangeScene empty scene name"); } else { - if (LogFilter.logDebug) - { - Debug.Log("ClientChangeScene newSceneName:" + newSceneName + " networkSceneName:" + networkSceneName); - } + Debug.Log("ClientChangeScene newSceneName:" + newSceneName + " networkSceneName:" + networkSceneName); if (newSceneName == networkSceneName) { if (!forceReload) @@ -538,10 +508,7 @@ namespace QuantumUNET.Components internal void OnServerConnectInternal(QSBNetworkMessage netMsg) { - if (LogFilter.logDebug) - { - Debug.Log("NetworkManager:OnServerConnectInternal"); - } + Debug.Log("NetworkManager:OnServerConnectInternal"); netMsg.Connection.SetMaxDelay(maxDelay); if (m_MaxBufferedPackets != 512) { @@ -567,28 +534,19 @@ namespace QuantumUNET.Components internal void OnServerDisconnectInternal(QSBNetworkMessage netMsg) { - if (LogFilter.logDebug) - { - Debug.Log("NetworkManager:OnServerDisconnectInternal"); - } + Debug.Log("NetworkManager:OnServerDisconnectInternal"); OnServerDisconnect(netMsg.Connection); } internal void OnServerReadyMessageInternal(QSBNetworkMessage netMsg) { - if (LogFilter.logDebug) - { - Debug.Log("NetworkManager:OnServerReadyMessageInternal"); - } + Debug.Log("NetworkManager:OnServerReadyMessageInternal"); OnServerReady(netMsg.Connection); } internal void OnServerAddPlayerMessageInternal(QSBNetworkMessage netMsg) { - if (LogFilter.logDebug) - { - Debug.Log("NetworkManager:OnServerAddPlayerMessageInternal"); - } + Debug.Log("NetworkManager:OnServerAddPlayerMessageInternal"); netMsg.ReadMessage(s_AddPlayerMessage); if (s_AddPlayerMessage.msgSize != 0) { @@ -603,10 +561,7 @@ namespace QuantumUNET.Components internal void OnServerRemovePlayerMessageInternal(QSBNetworkMessage netMsg) { - if (LogFilter.logDebug) - { - Debug.Log("NetworkManager:OnServerRemovePlayerMessageInternal"); - } + Debug.Log("NetworkManager:OnServerRemovePlayerMessageInternal"); netMsg.ReadMessage(s_RemovePlayerMessage); netMsg.Connection.GetPlayerController(s_RemovePlayerMessage.PlayerControllerId, out var player); OnServerRemovePlayer(netMsg.Connection, player); @@ -615,20 +570,14 @@ namespace QuantumUNET.Components internal void OnServerErrorInternal(QSBNetworkMessage netMsg) { - if (LogFilter.logDebug) - { - Debug.Log("NetworkManager:OnServerErrorInternal"); - } + Debug.Log("NetworkManager:OnServerErrorInternal"); netMsg.ReadMessage(s_ErrorMessage); OnServerError(netMsg.Connection, s_ErrorMessage.errorCode); } internal void OnClientConnectInternal(QSBNetworkMessage netMsg) { - if (LogFilter.logDebug) - { - Debug.Log("NetworkManager:OnClientConnectInternal"); - } + Debug.Log("NetworkManager:OnClientConnectInternal"); netMsg.Connection.SetMaxDelay(maxDelay); var name = SceneManager.GetSceneAt(0).name; if (string.IsNullOrEmpty(onlineScene) || onlineScene == offlineScene || name == onlineScene) @@ -644,10 +593,7 @@ namespace QuantumUNET.Components internal void OnClientDisconnectInternal(QSBNetworkMessage netMsg) { - if (LogFilter.logDebug) - { - Debug.Log("NetworkManager:OnClientDisconnectInternal"); - } + Debug.Log("NetworkManager:OnClientDisconnectInternal"); if (!string.IsNullOrEmpty(offlineScene)) { ClientChangeScene(offlineScene, false); @@ -657,30 +603,21 @@ namespace QuantumUNET.Components internal void OnClientNotReadyMessageInternal(QSBNetworkMessage netMsg) { - if (LogFilter.logDebug) - { - Debug.Log("NetworkManager:OnClientNotReadyMessageInternal"); - } + Debug.Log("NetworkManager:OnClientNotReadyMessageInternal"); QSBClientScene.SetNotReady(); OnClientNotReady(netMsg.Connection); } internal void OnClientErrorInternal(QSBNetworkMessage netMsg) { - if (LogFilter.logDebug) - { - Debug.Log("NetworkManager:OnClientErrorInternal"); - } + Debug.Log("NetworkManager:OnClientErrorInternal"); netMsg.ReadMessage(s_ErrorMessage); OnClientError(netMsg.Connection, s_ErrorMessage.errorCode); } internal void OnClientSceneInternal(QSBNetworkMessage netMsg) { - if (LogFilter.logDebug) - { - Debug.Log("NetworkManager:OnClientSceneInternal"); - } + Debug.Log("NetworkManager:OnClientSceneInternal"); var newSceneName = netMsg.Reader.ReadString(); if (IsClientConnected() && !QSBNetworkServer.active) { @@ -697,10 +634,7 @@ namespace QuantumUNET.Components QSBNetworkServer.DestroyPlayersForConnection(conn); if (conn.LastError != NetworkError.Ok) { - if (LogFilter.logError) - { - Debug.LogError("ServerDisconnected due to error: " + conn.LastError); - } + Debug.LogError("ServerDisconnected due to error: " + conn.LastError); } } @@ -708,10 +642,7 @@ namespace QuantumUNET.Components { if (conn.PlayerControllers.Count == 0) { - if (LogFilter.logDebug) - { - Debug.Log("Ready with no player object"); - } + Debug.Log("Ready with no player object"); } QSBNetworkServer.SetClientReady(conn); } @@ -724,24 +655,15 @@ namespace QuantumUNET.Components { if (playerPrefab == null) { - if (LogFilter.logError) - { - ModConsole.OwmlConsole.WriteLine("Error - The PlayerPrefab is empty on the QSBNetworkManager. Please setup a PlayerPrefab object."); - } + ModConsole.OwmlConsole.WriteLine("Error - The PlayerPrefab is empty on the QSBNetworkManager. Please setup a PlayerPrefab object."); } else if (playerPrefab.GetComponent() == null) { - if (LogFilter.logError) - { - ModConsole.OwmlConsole.WriteLine("Error - The PlayerPrefab does not have a QSBNetworkIdentity. Please add a QSBNetworkIdentity to the player prefab."); - } + ModConsole.OwmlConsole.WriteLine("Error - The PlayerPrefab does not have a QSBNetworkIdentity. Please add a QSBNetworkIdentity to the player prefab."); } else if (playerControllerId < conn.PlayerControllers.Count && conn.PlayerControllers[playerControllerId].IsValid && conn.PlayerControllers[playerControllerId].Gameobject != null) { - if (LogFilter.logError) - { - ModConsole.OwmlConsole.WriteLine("Warning - There is already a player at that playerControllerId for this connections."); - } + ModConsole.OwmlConsole.WriteLine("Warning - There is already a player at that playerControllerId for this connections."); } else { @@ -783,10 +705,7 @@ namespace QuantumUNET.Components StopClient(); if (conn.LastError != NetworkError.Ok) { - if (LogFilter.logError) - { - Debug.LogError("ClientDisconnected due to error: " + conn.LastError); - } + Debug.LogError("ClientDisconnected due to error: " + conn.LastError); } } diff --git a/QuantumUNET/Components/QSBNetworkTransform.cs b/QuantumUNET/Components/QSBNetworkTransform.cs index 099a81e7..7c9b7aac 100644 --- a/QuantumUNET/Components/QSBNetworkTransform.cs +++ b/QuantumUNET/Components/QSBNetworkTransform.cs @@ -1,5 +1,6 @@ using OWML.Logging; using QuantumUNET.Messages; +using QuantumUNET.Transport; using UnityEngine; using UnityEngine.Networking; @@ -8,33 +9,19 @@ namespace QuantumUNET.Components public class QSBNetworkTransform : QSBNetworkBehaviour { public float SendInterval { get; set; } = 0.1f; - public AxisSyncMode SyncRotationAxis { get; set; } = AxisSyncMode.AxisXYZ; - public CompressionSyncMode RotationSyncCompression { get; set; } = CompressionSyncMode.None; - public bool SyncSpin { get; set; } - public float MovementTheshold { get; set; } = 0.001f; - public float velocityThreshold { get; set; } = 0.0001f; - public float SnapThreshold { get; set; } = 5f; - public float InterpolateRotation { get; set; } = 1f; - public float InterpolateMovement { get; set; } = 1f; - public ClientMoveCallback3D clientMoveCallback3D { get; set; } - public float LastSyncTime { get; private set; } - public Vector3 TargetSyncPosition => m_TargetSyncPosition; - public Vector3 targetSyncVelocity => m_TargetSyncVelocity; - public Quaternion targetSyncRotation3D => m_TargetSyncRotation3D; - public bool Grounded { get; set; } = true; public void Awake() @@ -241,10 +228,7 @@ namespace QuantumUNET.Components component.UnserializeModeTransform(netMsg.Reader, false); component.LastSyncTime = Time.time; } - else if (LogFilter.logWarn) - { - ModConsole.OwmlConsole.WriteLine("Warning - HandleTransform netId:" + networkInstanceId + " is not for a valid player"); - } + ModConsole.OwmlConsole.WriteLine("Warning - HandleTransform netId:" + networkInstanceId + " is not for a valid player"); } } diff --git a/QuantumUNET/Messages/QSBAddPlayerMessage.cs b/QuantumUNET/Messages/QSBAddPlayerMessage.cs index 36920806..48a4c9c2 100644 --- a/QuantumUNET/Messages/QSBAddPlayerMessage.cs +++ b/QuantumUNET/Messages/QSBAddPlayerMessage.cs @@ -1,4 +1,6 @@ -namespace QuantumUNET.Messages +using QuantumUNET.Transport; + +namespace QuantumUNET.Messages { internal class QSBAddPlayerMessage : QSBMessageBase { diff --git a/QuantumUNET/Messages/QSBAnimationMessage.cs b/QuantumUNET/Messages/QSBAnimationMessage.cs index 4edfcb97..16f7bc9f 100644 --- a/QuantumUNET/Messages/QSBAnimationMessage.cs +++ b/QuantumUNET/Messages/QSBAnimationMessage.cs @@ -1,4 +1,6 @@ -namespace QuantumUNET.Messages +using QuantumUNET.Transport; + +namespace QuantumUNET.Messages { internal class QSBAnimationMessage : QSBMessageBase { diff --git a/QuantumUNET/Messages/QSBAnimationParametersMessage.cs b/QuantumUNET/Messages/QSBAnimationParametersMessage.cs index 6dbc666d..c8013c38 100644 --- a/QuantumUNET/Messages/QSBAnimationParametersMessage.cs +++ b/QuantumUNET/Messages/QSBAnimationParametersMessage.cs @@ -1,4 +1,6 @@ -namespace QuantumUNET.Messages +using QuantumUNET.Transport; + +namespace QuantumUNET.Messages { internal class QSBAnimationParametersMessage : QSBMessageBase { diff --git a/QuantumUNET/Messages/QSBAnimationTriggerMessage.cs b/QuantumUNET/Messages/QSBAnimationTriggerMessage.cs index 78553379..d6c7d89e 100644 --- a/QuantumUNET/Messages/QSBAnimationTriggerMessage.cs +++ b/QuantumUNET/Messages/QSBAnimationTriggerMessage.cs @@ -1,4 +1,6 @@ -namespace QuantumUNET.Messages +using QuantumUNET.Transport; + +namespace QuantumUNET.Messages { internal class QSBAnimationTriggerMessage : QSBMessageBase { diff --git a/QuantumUNET/Messages/QSBCRCMessage.cs b/QuantumUNET/Messages/QSBCRCMessage.cs index df45dd7a..b0848085 100644 --- a/QuantumUNET/Messages/QSBCRCMessage.cs +++ b/QuantumUNET/Messages/QSBCRCMessage.cs @@ -1,4 +1,6 @@ -namespace QuantumUNET.Messages +using QuantumUNET.Transport; + +namespace QuantumUNET.Messages { internal class QSBCRCMessage : QSBMessageBase { diff --git a/QuantumUNET/Messages/QSBClientAuthorityMessage.cs b/QuantumUNET/Messages/QSBClientAuthorityMessage.cs index 6ea87813..11e9fe46 100644 --- a/QuantumUNET/Messages/QSBClientAuthorityMessage.cs +++ b/QuantumUNET/Messages/QSBClientAuthorityMessage.cs @@ -1,4 +1,6 @@ -namespace QuantumUNET.Messages +using QuantumUNET.Transport; + +namespace QuantumUNET.Messages { internal class QSBClientAuthorityMessage : QSBMessageBase { diff --git a/QuantumUNET/Messages/QSBEmptyMessage.cs b/QuantumUNET/Messages/QSBEmptyMessage.cs index 27dbc785..16f82deb 100644 --- a/QuantumUNET/Messages/QSBEmptyMessage.cs +++ b/QuantumUNET/Messages/QSBEmptyMessage.cs @@ -1,4 +1,6 @@ -namespace QuantumUNET.Messages +using QuantumUNET.Transport; + +namespace QuantumUNET.Messages { public class QSBEmptyMessage : QSBMessageBase { diff --git a/QuantumUNET/Messages/QSBErrorMessage.cs b/QuantumUNET/Messages/QSBErrorMessage.cs index d7952f6b..97d7ecaf 100644 --- a/QuantumUNET/Messages/QSBErrorMessage.cs +++ b/QuantumUNET/Messages/QSBErrorMessage.cs @@ -1,4 +1,6 @@ -namespace QuantumUNET.Messages +using QuantumUNET.Transport; + +namespace QuantumUNET.Messages { public class QSBErrorMessage : QSBMessageBase { diff --git a/QuantumUNET/Messages/QSBMessageBase.cs b/QuantumUNET/Messages/QSBMessageBase.cs index 501869d7..969dd732 100644 --- a/QuantumUNET/Messages/QSBMessageBase.cs +++ b/QuantumUNET/Messages/QSBMessageBase.cs @@ -1,4 +1,6 @@ -namespace QuantumUNET.Messages +using QuantumUNET.Transport; + +namespace QuantumUNET.Messages { public abstract class QSBMessageBase { diff --git a/QuantumUNET/Messages/QSBNetworkMessage.cs b/QuantumUNET/Messages/QSBNetworkMessage.cs index 4f7ca90c..a1d714ac 100644 --- a/QuantumUNET/Messages/QSBNetworkMessage.cs +++ b/QuantumUNET/Messages/QSBNetworkMessage.cs @@ -1,4 +1,5 @@ -using System; +using QuantumUNET.Transport; +using System; namespace QuantumUNET.Messages { diff --git a/QuantumUNET/Messages/QSBObjectDestroyMessage.cs b/QuantumUNET/Messages/QSBObjectDestroyMessage.cs index 66b7e05e..9a19c4f7 100644 --- a/QuantumUNET/Messages/QSBObjectDestroyMessage.cs +++ b/QuantumUNET/Messages/QSBObjectDestroyMessage.cs @@ -1,4 +1,6 @@ -namespace QuantumUNET.Messages +using QuantumUNET.Transport; + +namespace QuantumUNET.Messages { internal class QSBObjectDestroyMessage : QSBMessageBase { diff --git a/QuantumUNET/Messages/QSBObjectSpawnFinishedMessage.cs b/QuantumUNET/Messages/QSBObjectSpawnFinishedMessage.cs index ebb68d39..0ec53d1e 100644 --- a/QuantumUNET/Messages/QSBObjectSpawnFinishedMessage.cs +++ b/QuantumUNET/Messages/QSBObjectSpawnFinishedMessage.cs @@ -1,4 +1,6 @@ -namespace QuantumUNET.Messages +using QuantumUNET.Transport; + +namespace QuantumUNET.Messages { internal class QSBObjectSpawnFinishedMessage : QSBMessageBase { diff --git a/QuantumUNET/Messages/QSBObjectSpawnMessage.cs b/QuantumUNET/Messages/QSBObjectSpawnMessage.cs index f5aa0f05..ea4f61c4 100644 --- a/QuantumUNET/Messages/QSBObjectSpawnMessage.cs +++ b/QuantumUNET/Messages/QSBObjectSpawnMessage.cs @@ -1,4 +1,5 @@ -using UnityEngine; +using QuantumUNET.Transport; +using UnityEngine; namespace QuantumUNET.Messages { diff --git a/QuantumUNET/Messages/QSBObjectSpawnSceneMessage.cs b/QuantumUNET/Messages/QSBObjectSpawnSceneMessage.cs index 579df965..e1846f4a 100644 --- a/QuantumUNET/Messages/QSBObjectSpawnSceneMessage.cs +++ b/QuantumUNET/Messages/QSBObjectSpawnSceneMessage.cs @@ -1,4 +1,5 @@ -using UnityEngine; +using QuantumUNET.Transport; +using UnityEngine; namespace QuantumUNET.Messages { diff --git a/QuantumUNET/Messages/QSBOwnerMessage.cs b/QuantumUNET/Messages/QSBOwnerMessage.cs index 8fc1fdc7..89ce81c6 100644 --- a/QuantumUNET/Messages/QSBOwnerMessage.cs +++ b/QuantumUNET/Messages/QSBOwnerMessage.cs @@ -1,4 +1,6 @@ -namespace QuantumUNET.Messages +using QuantumUNET.Transport; + +namespace QuantumUNET.Messages { internal class QSBOwnerMessage : QSBMessageBase { diff --git a/QuantumUNET/Messages/QSBRemovePlayerMessage.cs b/QuantumUNET/Messages/QSBRemovePlayerMessage.cs index e36620c8..7bebaef3 100644 --- a/QuantumUNET/Messages/QSBRemovePlayerMessage.cs +++ b/QuantumUNET/Messages/QSBRemovePlayerMessage.cs @@ -1,4 +1,6 @@ -namespace QuantumUNET.Messages +using QuantumUNET.Transport; + +namespace QuantumUNET.Messages { public class QSBRemovePlayerMessage : QSBMessageBase { diff --git a/QuantumUNET/Messages/QSBSpawnDelegate.cs b/QuantumUNET/Messages/QSBSpawnDelegate.cs new file mode 100644 index 00000000..bd254952 --- /dev/null +++ b/QuantumUNET/Messages/QSBSpawnDelegate.cs @@ -0,0 +1,6 @@ +using UnityEngine; + +namespace QuantumUNET +{ + public delegate GameObject QSBSpawnDelegate(Vector3 position, QSBNetworkHash128 assetId); +} diff --git a/QuantumUNET/Messages/QSBStringMessage.cs b/QuantumUNET/Messages/QSBStringMessage.cs index 547d1ec1..7e52a4e9 100644 --- a/QuantumUNET/Messages/QSBStringMessage.cs +++ b/QuantumUNET/Messages/QSBStringMessage.cs @@ -1,4 +1,6 @@ -namespace QuantumUNET.Messages +using QuantumUNET.Transport; + +namespace QuantumUNET.Messages { public class QSBStringMessage : QSBMessageBase { diff --git a/QuantumUNET/QSBClientScene.cs b/QuantumUNET/QSBClientScene.cs index ace9dc44..bcc19a15 100644 --- a/QuantumUNET/QSBClientScene.cs +++ b/QuantumUNET/QSBClientScene.cs @@ -1,5 +1,6 @@ using QuantumUNET.Components; using QuantumUNET.Messages; +using QuantumUNET.Transport; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; @@ -102,24 +103,18 @@ namespace QuantumUNET bool result; if (playerControllerId < 0) { - if (LogFilter.logError) - { - Debug.LogError("ClientScene::AddPlayer: playerControllerId of " + playerControllerId + " is negative"); - } + Debug.LogError("ClientScene::AddPlayer: playerControllerId of " + playerControllerId + " is negative"); result = false; } else if (playerControllerId > 32) { - if (LogFilter.logError) + Debug.LogError(string.Concat(new object[] { - Debug.LogError(string.Concat(new object[] - { "ClientScene::AddPlayer: playerControllerId of ", playerControllerId, " is too high, max is ", 32 - })); - } + })); result = false; } else @@ -381,11 +376,11 @@ namespace QuantumUNET public static void RegisterPrefab(GameObject prefab) => QSBNetworkScene.RegisterPrefab(prefab); - public static void RegisterPrefab(GameObject prefab, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) => QSBNetworkScene.RegisterPrefab(prefab, spawnHandler, unspawnHandler); + public static void RegisterPrefab(GameObject prefab, QSBSpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) => QSBNetworkScene.RegisterPrefab(prefab, spawnHandler, unspawnHandler); public static void UnregisterPrefab(GameObject prefab) => QSBNetworkScene.UnregisterPrefab(prefab); - public static void RegisterSpawnHandler(QSBNetworkHash128 assetId, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) => QSBNetworkScene.RegisterSpawnHandler(assetId, spawnHandler, unspawnHandler); + public static void RegisterSpawnHandler(QSBNetworkHash128 assetId, QSBSpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) => QSBNetworkScene.RegisterSpawnHandler(assetId, spawnHandler, unspawnHandler); public static void UnregisterSpawnHandler(QSBNetworkHash128 assetId) => QSBNetworkScene.UnregisterSpawnHandler(assetId); diff --git a/QuantumUNET/QSBLocalClient.cs b/QuantumUNET/QSBLocalClient.cs index 98455474..42142c05 100644 --- a/QuantumUNET/QSBLocalClient.cs +++ b/QuantumUNET/QSBLocalClient.cs @@ -1,4 +1,5 @@ using QuantumUNET.Messages; +using QuantumUNET.Transport; using System.Collections.Generic; using UnityEngine; diff --git a/QuantumUNET/QSBNetworkBehaviour.cs b/QuantumUNET/QSBNetworkBehaviour.cs index f946b403..b7f0992d 100644 --- a/QuantumUNET/QSBNetworkBehaviour.cs +++ b/QuantumUNET/QSBNetworkBehaviour.cs @@ -1,5 +1,6 @@ using OWML.Logging; using QuantumUNET.Components; +using QuantumUNET.Transport; using System; using System.Collections.Generic; using System.Net.Sockets; diff --git a/QuantumUNET/QSBNetworkCRC.cs b/QuantumUNET/QSBNetworkCRC.cs index 276200ba..cb8ec27b 100644 --- a/QuantumUNET/QSBNetworkCRC.cs +++ b/QuantumUNET/QSBNetworkCRC.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using System.Reflection; using UnityEngine; -using UnityEngine.Networking; namespace QuantumUNET { @@ -58,10 +57,7 @@ namespace QuantumUNET bool result; if (scripts.Count != remoteScripts.Length) { - if (LogFilter.logWarn) - { - Debug.LogWarning("Network configuration mismatch detected. The number of networked scripts on the client does not match the number of networked scripts on the server. This could be caused by lazy loading of scripts on the client. This warning can be disabled by the checkbox in NetworkManager Script CRC Check."); - } + Debug.LogWarning("Network configuration mismatch detected. The number of networked scripts on the client does not match the number of networked scripts on the server. This could be caused by lazy loading of scripts on the client. This warning can be disabled by the checkbox in NetworkManager Script CRC Check."); Dump(remoteScripts); result = false; } @@ -69,49 +65,40 @@ namespace QuantumUNET { foreach (var crcmessageEntry in remoteScripts) { - if (LogFilter.logDebug) + Debug.Log(string.Concat(new object[] { - Debug.Log(string.Concat(new object[] - { - "Script: ", - crcmessageEntry.name, - " Channel: ", - crcmessageEntry.channel - })); - } + "Script: ", + crcmessageEntry.name, + " Channel: ", + crcmessageEntry.channel + })); if (scripts.ContainsKey(crcmessageEntry.name)) { var num = scripts[crcmessageEntry.name]; if (num != crcmessageEntry.channel) { - if (LogFilter.logError) + Debug.LogError(string.Concat(new object[] { - Debug.LogError(string.Concat(new object[] - { - "HLAPI CRC Channel Mismatch. Script: ", - crcmessageEntry.name, - " LocalChannel: ", - num, - " RemoteChannel: ", - crcmessageEntry.channel - })); - } + "HLAPI CRC Channel Mismatch. Script: ", + crcmessageEntry.name, + " LocalChannel: ", + num, + " RemoteChannel: ", + crcmessageEntry.channel + })); Dump(remoteScripts); return false; } } if (crcmessageEntry.channel >= numChannels) { - if (LogFilter.logError) + Debug.LogError(string.Concat(new object[] { - Debug.LogError(string.Concat(new object[] - { - "HLAPI CRC channel out of range! Script: ", - crcmessageEntry.name, - " Channel: ", - crcmessageEntry.channel - })); - } + "HLAPI CRC channel out of range! Script: ", + crcmessageEntry.name, + " Channel: ", + crcmessageEntry.channel + })); Dump(remoteScripts); return false; } diff --git a/QuantumUNET/QSBNetworkClient.cs b/QuantumUNET/QSBNetworkClient.cs index 8b4ee136..d9357724 100644 --- a/QuantumUNET/QSBNetworkClient.cs +++ b/QuantumUNET/QSBNetworkClient.cs @@ -1,5 +1,6 @@ using OWML.Logging; using QuantumUNET.Messages; +using QuantumUNET.Transport; using System; using System.Collections.Generic; using System.Net; diff --git a/QuantumUNET/QSBNetworkConnection.cs b/QuantumUNET/QSBNetworkConnection.cs index 16749a99..85f4e4ae 100644 --- a/QuantumUNET/QSBNetworkConnection.cs +++ b/QuantumUNET/QSBNetworkConnection.cs @@ -1,6 +1,7 @@ using OWML.Logging; using QuantumUNET.Components; using QuantumUNET.Messages; +using QuantumUNET.Transport; using System; using System.Collections.Generic; using System.Text; diff --git a/QuantumUNET/QSBNetworkScene.cs b/QuantumUNET/QSBNetworkScene.cs index e4b51499..337bed75 100644 --- a/QuantumUNET/QSBNetworkScene.cs +++ b/QuantumUNET/QSBNetworkScene.cs @@ -9,7 +9,7 @@ namespace QuantumUNET { internal static Dictionary guidToPrefab { get; } = new Dictionary(); - internal static Dictionary spawnHandlers { get; } = new Dictionary(); + internal static Dictionary spawnHandlers { get; } = new Dictionary(); internal static Dictionary unspawnHandlers { get; } = new Dictionary(); @@ -161,7 +161,7 @@ namespace QuantumUNET unspawnHandlers.Remove(assetId); } - internal static void RegisterSpawnHandler(QSBNetworkHash128 assetId, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) + internal static void RegisterSpawnHandler(QSBNetworkHash128 assetId, QSBSpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) { if (spawnHandler == null || unspawnHandler == null) { @@ -194,7 +194,7 @@ namespace QuantumUNET } } - internal static void RegisterPrefab(GameObject prefab, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) + internal static void RegisterPrefab(GameObject prefab, QSBSpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) { var component = prefab.GetComponent(); if (component == null) @@ -216,7 +216,7 @@ namespace QuantumUNET } } - internal static bool GetSpawnHandler(QSBNetworkHash128 assetId, out SpawnDelegate handler) + internal static bool GetSpawnHandler(QSBNetworkHash128 assetId, out QSBSpawnDelegate handler) { bool result; if (spawnHandlers.ContainsKey(assetId)) diff --git a/QuantumUNET/QSBNetworkServer.cs b/QuantumUNET/QSBNetworkServer.cs index 5843883c..cb0dff88 100644 --- a/QuantumUNET/QSBNetworkServer.cs +++ b/QuantumUNET/QSBNetworkServer.cs @@ -1,6 +1,7 @@ using OWML.Logging; using QuantumUNET.Components; using QuantumUNET.Messages; +using QuantumUNET.Transport; using System; using System.Collections.Generic; using System.Collections.ObjectModel; diff --git a/QuantumUNET/QSBNetworkServerSimple.cs b/QuantumUNET/QSBNetworkServerSimple.cs index 7a650723..451aceea 100644 --- a/QuantumUNET/QSBNetworkServerSimple.cs +++ b/QuantumUNET/QSBNetworkServerSimple.cs @@ -1,4 +1,5 @@ using QuantumUNET.Messages; +using QuantumUNET.Transport; using System; using System.Collections.Generic; using System.Collections.ObjectModel; diff --git a/QuantumUNET/QSBULocalConnectionToClient.cs b/QuantumUNET/QSBULocalConnectionToClient.cs index 041f781c..3c83fbe9 100644 --- a/QuantumUNET/QSBULocalConnectionToClient.cs +++ b/QuantumUNET/QSBULocalConnectionToClient.cs @@ -1,4 +1,5 @@ using QuantumUNET.Messages; +using QuantumUNET.Transport; namespace QuantumUNET { diff --git a/QuantumUNET/QSBULocalConnectionToServer.cs b/QuantumUNET/QSBULocalConnectionToServer.cs index f6c9bef8..90420f79 100644 --- a/QuantumUNET/QSBULocalConnectionToServer.cs +++ b/QuantumUNET/QSBULocalConnectionToServer.cs @@ -1,4 +1,5 @@ using QuantumUNET.Messages; +using QuantumUNET.Transport; using UnityEngine; using UnityEngine.Networking; diff --git a/QuantumUNET/QuantumUNET.csproj b/QuantumUNET/QuantumUNET.csproj index 51d050ee..5579360f 100644 --- a/QuantumUNET/QuantumUNET.csproj +++ b/QuantumUNET/QuantumUNET.csproj @@ -100,8 +100,8 @@ - - + + @@ -110,7 +110,7 @@ - + @@ -124,13 +124,13 @@ - + - + @@ -141,6 +141,7 @@ + diff --git a/QuantumUNET/QSBChannelBuffer.cs b/QuantumUNET/Transport/QSBChannelBuffer.cs similarity index 95% rename from QuantumUNET/QSBChannelBuffer.cs rename to QuantumUNET/Transport/QSBChannelBuffer.cs index 5f6d610f..92f010bc 100644 --- a/QuantumUNET/QSBChannelBuffer.cs +++ b/QuantumUNET/Transport/QSBChannelBuffer.cs @@ -4,7 +4,7 @@ using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; -namespace QuantumUNET +namespace QuantumUNET.Transport { internal class QSBChannelBuffer : IDisposable { @@ -99,26 +99,17 @@ namespace QuantumUNET } else if (!_currentPacket.IsEmpty() || _pendingPackets.Count > 0) { - if (LogFilter.logError) - { - Debug.LogError("Cannot set MaxPacketSize after sending data."); - } + Debug.LogError("Cannot set MaxPacketSize after sending data."); result = false; } else if (value <= 0) { - if (LogFilter.logError) - { - Debug.LogError("Cannot set MaxPacketSize less than one."); - } + Debug.LogError("Cannot set MaxPacketSize less than one."); result = false; } else if (value > _maxPacketSize) { - if (LogFilter.logError) - { - Debug.LogError("Cannot set MaxPacketSize to greater than the existing maximum (" + _maxPacketSize + ")."); - } + Debug.LogError("Cannot set MaxPacketSize to greater than the existing maximum (" + _maxPacketSize + ")."); result = false; } else diff --git a/QuantumUNET/QSBChannelPacket.cs b/QuantumUNET/Transport/QSBChannelPacket.cs similarity index 97% rename from QuantumUNET/QSBChannelPacket.cs rename to QuantumUNET/Transport/QSBChannelPacket.cs index 32e55a62..e3e61d0d 100644 --- a/QuantumUNET/QSBChannelPacket.cs +++ b/QuantumUNET/Transport/QSBChannelPacket.cs @@ -2,7 +2,7 @@ using UnityEngine; using UnityEngine.Networking; -namespace QuantumUNET +namespace QuantumUNET.Transport { internal struct QSBChannelPacket { diff --git a/QuantumUNET/QSBNetBuffer.cs b/QuantumUNET/Transport/QSBNetBuffer.cs similarity index 99% rename from QuantumUNET/QSBNetBuffer.cs rename to QuantumUNET/Transport/QSBNetBuffer.cs index 2cf25622..589c893c 100644 --- a/QuantumUNET/QSBNetBuffer.cs +++ b/QuantumUNET/Transport/QSBNetBuffer.cs @@ -1,7 +1,7 @@ using System; using UnityEngine; -namespace QuantumUNET +namespace QuantumUNET.Transport { internal class QSBNetBuffer { diff --git a/QuantumUNET/QSBNetworkReader.cs b/QuantumUNET/Transport/QSBNetworkReader.cs similarity index 99% rename from QuantumUNET/QSBNetworkReader.cs rename to QuantumUNET/Transport/QSBNetworkReader.cs index 27f4a67c..fcc03245 100644 --- a/QuantumUNET/QSBNetworkReader.cs +++ b/QuantumUNET/Transport/QSBNetworkReader.cs @@ -5,7 +5,7 @@ using System.Text; using UnityEngine; using UnityEngine.Networking; -namespace QuantumUNET +namespace QuantumUNET.Transport { public class QSBNetworkReader { diff --git a/QuantumUNET/QSBNetworkWriter.cs b/QuantumUNET/Transport/QSBNetworkWriter.cs similarity index 99% rename from QuantumUNET/QSBNetworkWriter.cs rename to QuantumUNET/Transport/QSBNetworkWriter.cs index 90582ea6..c7f559fb 100644 --- a/QuantumUNET/QSBNetworkWriter.cs +++ b/QuantumUNET/Transport/QSBNetworkWriter.cs @@ -5,7 +5,7 @@ using System.Text; using UnityEngine; using UnityEngine.Networking; -namespace QuantumUNET +namespace QuantumUNET.Transport { public class QSBNetworkWriter { From dda1f5b6a559bb8c36e209d7c301a94b08d58c57 Mon Sep 17 00:00:00 2001 From: Mister_Nebula <41904486+misternebula@users.noreply.github.com> Date: Wed, 16 Dec 2020 08:03:04 +0000 Subject: [PATCH 10/10] more cleanup --- QuantumUNET/Messages/QSBAnimationMessage.cs | 16 ++++---- QuantumUNET/Messages/QSBEmptyMessage.cs | 9 +---- QuantumUNET/Messages/QSBNetworkMessage.cs | 1 - .../Messages/QSBObjectDestroyMessage.cs | 4 +- .../Messages/QSBObjectSpawnFinishedMessage.cs | 4 +- QuantumUNET/Messages/QSBObjectSpawnMessage.cs | 18 ++++----- .../Messages/QSBObjectSpawnSceneMessage.cs | 16 ++++---- QuantumUNET/Messages/QSBOwnerMessage.cs | 12 +++--- QuantumUNET/Transport/QSBChannelBuffer.cs | 39 +++++-------------- QuantumUNET/Transport/QSBChannelPacket.cs | 28 +++---------- 10 files changed, 52 insertions(+), 95 deletions(-) diff --git a/QuantumUNET/Messages/QSBAnimationMessage.cs b/QuantumUNET/Messages/QSBAnimationMessage.cs index 16f7bc9f..a25714ac 100644 --- a/QuantumUNET/Messages/QSBAnimationMessage.cs +++ b/QuantumUNET/Messages/QSBAnimationMessage.cs @@ -9,14 +9,6 @@ namespace QuantumUNET.Messages public float normalizedTime; public byte[] parameters; - public override void Deserialize(QSBNetworkReader reader) - { - netId = reader.ReadNetworkId(); - stateHash = (int)reader.ReadPackedUInt32(); - normalizedTime = reader.ReadSingle(); - parameters = reader.ReadBytesAndSize(); - } - public override void Serialize(QSBNetworkWriter writer) { writer.Write(netId); @@ -31,5 +23,13 @@ namespace QuantumUNET.Messages writer.WriteBytesAndSize(parameters, parameters.Length); } } + + public override void Deserialize(QSBNetworkReader reader) + { + netId = reader.ReadNetworkId(); + stateHash = (int)reader.ReadPackedUInt32(); + normalizedTime = reader.ReadSingle(); + parameters = reader.ReadBytesAndSize(); + } } } \ No newline at end of file diff --git a/QuantumUNET/Messages/QSBEmptyMessage.cs b/QuantumUNET/Messages/QSBEmptyMessage.cs index 16f82deb..b89526b3 100644 --- a/QuantumUNET/Messages/QSBEmptyMessage.cs +++ b/QuantumUNET/Messages/QSBEmptyMessage.cs @@ -4,12 +4,7 @@ namespace QuantumUNET.Messages { public class QSBEmptyMessage : QSBMessageBase { - public override void Deserialize(QSBNetworkReader reader) - { - } - - public override void Serialize(QSBNetworkWriter writer) - { - } + public override void Serialize(QSBNetworkWriter writer) { } + public override void Deserialize(QSBNetworkReader reader) { } } } \ No newline at end of file diff --git a/QuantumUNET/Messages/QSBNetworkMessage.cs b/QuantumUNET/Messages/QSBNetworkMessage.cs index a1d714ac..16ca1065 100644 --- a/QuantumUNET/Messages/QSBNetworkMessage.cs +++ b/QuantumUNET/Messages/QSBNetworkMessage.cs @@ -5,7 +5,6 @@ namespace QuantumUNET.Messages { public class QSBNetworkMessage { - public const int MaxMessageSize = 65535; public short MsgType; public QSBNetworkConnection Connection; public QSBNetworkReader Reader; diff --git a/QuantumUNET/Messages/QSBObjectDestroyMessage.cs b/QuantumUNET/Messages/QSBObjectDestroyMessage.cs index 9a19c4f7..3310b383 100644 --- a/QuantumUNET/Messages/QSBObjectDestroyMessage.cs +++ b/QuantumUNET/Messages/QSBObjectDestroyMessage.cs @@ -6,8 +6,8 @@ namespace QuantumUNET.Messages { public QSBNetworkInstanceId NetId; - public override void Deserialize(QSBNetworkReader reader) => NetId = reader.ReadNetworkId(); - public override void Serialize(QSBNetworkWriter writer) => writer.Write(NetId); + + public override void Deserialize(QSBNetworkReader reader) => NetId = reader.ReadNetworkId(); } } \ No newline at end of file diff --git a/QuantumUNET/Messages/QSBObjectSpawnFinishedMessage.cs b/QuantumUNET/Messages/QSBObjectSpawnFinishedMessage.cs index 0ec53d1e..4255bccb 100644 --- a/QuantumUNET/Messages/QSBObjectSpawnFinishedMessage.cs +++ b/QuantumUNET/Messages/QSBObjectSpawnFinishedMessage.cs @@ -6,8 +6,8 @@ namespace QuantumUNET.Messages { public uint State; - public override void Deserialize(QSBNetworkReader reader) => State = reader.ReadPackedUInt32(); - public override void Serialize(QSBNetworkWriter writer) => writer.WritePackedUInt32(State); + + public override void Deserialize(QSBNetworkReader reader) => State = reader.ReadPackedUInt32(); } } \ No newline at end of file diff --git a/QuantumUNET/Messages/QSBObjectSpawnMessage.cs b/QuantumUNET/Messages/QSBObjectSpawnMessage.cs index ea4f61c4..30b3122d 100644 --- a/QuantumUNET/Messages/QSBObjectSpawnMessage.cs +++ b/QuantumUNET/Messages/QSBObjectSpawnMessage.cs @@ -11,6 +11,15 @@ namespace QuantumUNET.Messages public byte[] Payload; public Quaternion Rotation; + public override void Serialize(QSBNetworkWriter writer) + { + writer.Write(NetId); + writer.Write(assetId); + writer.Write(Position); + writer.WriteBytesFull(Payload); + writer.Write(Rotation); + } + public override void Deserialize(QSBNetworkReader reader) { NetId = reader.ReadNetworkId(); @@ -22,14 +31,5 @@ namespace QuantumUNET.Messages Rotation = reader.ReadQuaternion(); } } - - public override void Serialize(QSBNetworkWriter writer) - { - writer.Write(NetId); - writer.Write(assetId); - writer.Write(Position); - writer.WriteBytesFull(Payload); - writer.Write(Rotation); - } } } \ No newline at end of file diff --git a/QuantumUNET/Messages/QSBObjectSpawnSceneMessage.cs b/QuantumUNET/Messages/QSBObjectSpawnSceneMessage.cs index e1846f4a..b202ce27 100644 --- a/QuantumUNET/Messages/QSBObjectSpawnSceneMessage.cs +++ b/QuantumUNET/Messages/QSBObjectSpawnSceneMessage.cs @@ -10,14 +10,6 @@ namespace QuantumUNET.Messages public Vector3 Position; public byte[] Payload; - public override void Deserialize(QSBNetworkReader reader) - { - NetId = reader.ReadNetworkId(); - SceneId = reader.ReadSceneId(); - Position = reader.ReadVector3(); - Payload = reader.ReadBytesAndSize(); - } - public override void Serialize(QSBNetworkWriter writer) { writer.Write(NetId); @@ -25,5 +17,13 @@ namespace QuantumUNET.Messages writer.Write(Position); writer.WriteBytesFull(Payload); } + + public override void Deserialize(QSBNetworkReader reader) + { + NetId = reader.ReadNetworkId(); + SceneId = reader.ReadSceneId(); + Position = reader.ReadVector3(); + Payload = reader.ReadBytesAndSize(); + } } } \ No newline at end of file diff --git a/QuantumUNET/Messages/QSBOwnerMessage.cs b/QuantumUNET/Messages/QSBOwnerMessage.cs index 89ce81c6..624ee0ad 100644 --- a/QuantumUNET/Messages/QSBOwnerMessage.cs +++ b/QuantumUNET/Messages/QSBOwnerMessage.cs @@ -7,16 +7,16 @@ namespace QuantumUNET.Messages public QSBNetworkInstanceId NetId; public short PlayerControllerId; - public override void Deserialize(QSBNetworkReader reader) - { - NetId = reader.ReadNetworkId(); - PlayerControllerId = (short)reader.ReadPackedUInt32(); - } - public override void Serialize(QSBNetworkWriter writer) { writer.Write(NetId); writer.WritePackedUInt32((uint)PlayerControllerId); } + + public override void Deserialize(QSBNetworkReader reader) + { + NetId = reader.ReadNetworkId(); + PlayerControllerId = (short)reader.ReadPackedUInt32(); + } } } \ No newline at end of file diff --git a/QuantumUNET/Transport/QSBChannelBuffer.cs b/QuantumUNET/Transport/QSBChannelBuffer.cs index 92f010bc..f20095ee 100644 --- a/QuantumUNET/Transport/QSBChannelBuffer.cs +++ b/QuantumUNET/Transport/QSBChannelBuffer.cs @@ -131,16 +131,13 @@ namespace QuantumUNET.Transport } else if (value < 0 || value >= 512) { - if (LogFilter.logError) + Debug.LogError(string.Concat(new object[] { - Debug.LogError(string.Concat(new object[] - { "Invalid MaxPendingBuffers for channel ", _channelId, ". Must be greater than zero and less than ", 512 - })); - } + })); result = false; } else @@ -231,18 +228,12 @@ namespace QuantumUNET.Transport bool result; if (bytesToSend >= 65535) { - if (LogFilter.logError) - { - Debug.LogError("ChannelBuffer:SendBytes cannot send packet larger than " + ushort.MaxValue + " bytes"); - } + Debug.LogError("ChannelBuffer:SendBytes cannot send packet larger than " + ushort.MaxValue + " bytes"); result = false; } else if (bytesToSend <= 0) { - if (LogFilter.logError) - { - Debug.LogError("ChannelBuffer:SendBytes cannot send zero bytes"); - } + Debug.LogError("ChannelBuffer:SendBytes cannot send zero bytes"); result = false; } else if (bytesToSend > _maxPacketSize) @@ -253,18 +244,15 @@ namespace QuantumUNET.Transport } else { - if (LogFilter.logError) + Debug.LogError(string.Concat(new object[] { - Debug.LogError(string.Concat(new object[] - { "Failed to send big message of ", bytesToSend, " bytes. The maximum is ", _maxPacketSize, " bytes on channel:", _channelId - })); - } + })); result = false; } } @@ -285,10 +273,7 @@ namespace QuantumUNET.Transport { if (!_isBroken) { - if (LogFilter.logError) - { - Debug.LogError("ChannelBuffer buffer limit of " + _pendingPackets.Count + " packets reached."); - } + Debug.LogError("ChannelBuffer buffer limit of " + _pendingPackets.Count + " packets reached."); } _isBroken = true; result = false; @@ -302,10 +287,7 @@ namespace QuantumUNET.Transport } else if (!_currentPacket.SendToTransport(_connection, _channelId)) { - if (LogFilter.logError) - { - Debug.Log("ChannelBuffer SendBytes no space on unreliable channel " + _channelId); - } + Debug.Log("ChannelBuffer SendBytes no space on unreliable channel " + _channelId); result = false; } else @@ -371,10 +353,7 @@ namespace QuantumUNET.Transport FreePacket(channelPacket); if (_isBroken && _pendingPackets.Count < _maxPendingPacketCount / 2) { - if (LogFilter.logWarn) - { - Debug.LogWarning("ChannelBuffer recovered from overflow but data was lost."); - } + Debug.LogWarning("ChannelBuffer recovered from overflow but data was lost."); _isBroken = false; } } diff --git a/QuantumUNET/Transport/QSBChannelPacket.cs b/QuantumUNET/Transport/QSBChannelPacket.cs index e3e61d0d..253f93fe 100644 --- a/QuantumUNET/Transport/QSBChannelPacket.cs +++ b/QuantumUNET/Transport/QSBChannelPacket.cs @@ -6,6 +6,10 @@ namespace QuantumUNET.Transport { internal struct QSBChannelPacket { + private int m_Position; + private byte[] m_Buffer; + private bool m_IsReliable; + public QSBChannelPacket(int packetSize, bool isReliable) { m_Position = 0; @@ -32,13 +36,7 @@ namespace QuantumUNET.Transport { if (!m_IsReliable || b != 4) { - Debug.LogError(string.Concat(new object[] - { - "Failed to send internal buffer channel:", - channelId, - " bytesToSend:", - m_Position - })); + Debug.LogError($"Failed to send internal buffer channel:{channelId} bytesToSend:{m_Position}"); result = false; } } @@ -48,25 +46,11 @@ namespace QuantumUNET.Transport { return false; } - Debug.LogError(string.Concat(new object[] - { - "Send Error: ", - (NetworkError)b, - " channel:", - channelId, - " bytesToSend:", - m_Position - })); + Debug.LogError($"Send Error: {(NetworkError)b} channel:{channelId} bytesToSend:{m_Position}"); result = false; } m_Position = 0; return result; } - - private int m_Position; - - private byte[] m_Buffer; - - private bool m_IsReliable; } } \ No newline at end of file