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) {