This commit is contained in:
Mister_Nebula 2020-12-14 21:58:00 +00:00
parent eb9a6ced96
commit 77c92887ad
26 changed files with 726 additions and 1376 deletions

View File

@ -32,22 +32,22 @@ namespace QuantumUNET.Components
public void SetParameterAutoSend(int index, bool value) public void SetParameterAutoSend(int index, bool value)
{ {
if (value) if (value)
{
m_ParameterSendBits |= (uint)(1 << index); m_ParameterSendBits |= (uint)(1 << index);
}
else else
{
m_ParameterSendBits &= (uint)~(1 << index); m_ParameterSendBits &= (uint)~(1 << index);
}
} }
public bool GetParameterAutoSend(int index) public bool GetParameterAutoSend(int index) =>
{ ((int)m_ParameterSendBits & (1 << index)) != 0;
return ((int)m_ParameterSendBits & 1 << index) != 0;
}
public override void OnStartAuthority() public override void OnStartAuthority() =>
{
m_ParameterWriter = new QSBNetworkWriter(); m_ParameterWriter = new QSBNetworkWriter();
}
private void FixedUpdate() public void FixedUpdate()
{ {
if (m_ParameterWriter == null) if (m_ParameterWriter == null)
{ {
@ -134,7 +134,10 @@ namespace QuantumUNET.Components
else else
{ {
if (!IsServer || LocalPlayerAuthority) if (!IsServer || LocalPlayerAuthority)
{
return; return;
}
QSBNetworkServer.SendToReady(gameObject, 41, parametersMessage); QSBNetworkServer.SendToReady(gameObject, 41, parametersMessage);
} }
} }
@ -161,14 +164,11 @@ namespace QuantumUNET.Components
ReadParameters(reader, true); ReadParameters(reader, true);
} }
internal void HandleAnimTriggerMsg(int hash) internal void HandleAnimTriggerMsg(int hash) => m_Animator.SetTrigger(hash);
{
m_Animator.SetTrigger(hash);
}
private void WriteParameters(QSBNetworkWriter writer, bool autoSend) 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)) if (!autoSend || GetParameterAutoSend(index))
{ {
@ -193,7 +193,7 @@ namespace QuantumUNET.Components
private void ReadParameters(QSBNetworkReader reader, bool autoSend) 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)) if (!autoSend || GetParameterAutoSend(index))
{ {
@ -257,10 +257,7 @@ namespace QuantumUNET.Components
m_Animator.Play(stateNameHash, 0, normalizedTime); m_Animator.Play(stateNameHash, 0, normalizedTime);
} }
public void SetTrigger(string triggerName) public void SetTrigger(string triggerName) => SetTrigger(Animator.StringToHash(triggerName));
{
SetTrigger(Animator.StringToHash(triggerName));
}
public void SetTrigger(int hash) public void SetTrigger(int hash)
{ {
@ -338,10 +335,16 @@ namespace QuantumUNET.Components
netMsg.ReadMessage(AnimationMessage); netMsg.ReadMessage(AnimationMessage);
var localObject = QSBClientScene.FindLocalObject(AnimationMessage.netId); var localObject = QSBClientScene.FindLocalObject(AnimationMessage.netId);
if (localObject == null) if (localObject == null)
{
return; return;
}
var component = localObject.GetComponent<QSBNetworkAnimator>(); var component = localObject.GetComponent<QSBNetworkAnimator>();
if (component == null) if (component == null)
{
return; return;
}
var reader = new QSBNetworkReader(AnimationMessage.parameters); var reader = new QSBNetworkReader(AnimationMessage.parameters);
component.HandleAnimMsg(AnimationMessage, reader); component.HandleAnimMsg(AnimationMessage, reader);
} }
@ -351,10 +354,16 @@ namespace QuantumUNET.Components
netMsg.ReadMessage(ParametersMessage); netMsg.ReadMessage(ParametersMessage);
var localObject = QSBClientScene.FindLocalObject(ParametersMessage.netId); var localObject = QSBClientScene.FindLocalObject(ParametersMessage.netId);
if (localObject == null) if (localObject == null)
{
return; return;
}
var component = localObject.GetComponent<QSBNetworkAnimator>(); var component = localObject.GetComponent<QSBNetworkAnimator>();
if (component == null) if (component == null)
{
return; return;
}
var reader = new QSBNetworkReader(ParametersMessage.parameters); var reader = new QSBNetworkReader(ParametersMessage.parameters);
component.HandleAnimParamsMsg(ParametersMessage, reader); component.HandleAnimParamsMsg(ParametersMessage, reader);
} }
@ -364,10 +373,16 @@ namespace QuantumUNET.Components
netMsg.ReadMessage(TriggersMessage); netMsg.ReadMessage(TriggersMessage);
var localObject = QSBClientScene.FindLocalObject(TriggersMessage.netId); var localObject = QSBClientScene.FindLocalObject(TriggersMessage.netId);
if (localObject == null) if (localObject == null)
{
return; return;
}
var component = localObject.GetComponent<QSBNetworkAnimator>(); var component = localObject.GetComponent<QSBNetworkAnimator>();
if (component == null) if (component == null)
{
return; return;
}
component.HandleAnimTriggerMsg(TriggersMessage.hash); component.HandleAnimTriggerMsg(TriggersMessage.hash);
} }
} }

View File

@ -132,7 +132,7 @@ namespace QuantumUNET.Components
{ {
if (m_NetworkBehaviours == null) if (m_NetworkBehaviours == null)
{ {
m_NetworkBehaviours = base.GetComponents<QSBNetworkBehaviour>(); m_NetworkBehaviours = GetComponents<QSBNetworkBehaviour>();
} }
} }
@ -179,11 +179,11 @@ namespace QuantumUNET.Components
} }
} }
private void OnDestroy() public void OnDestroy()
{ {
if (m_IsServer && QSBNetworkServer.active) if (m_IsServer && QSBNetworkServer.active)
{ {
QSBNetworkServer.Destroy(base.gameObject); QSBNetworkServer.Destroy(gameObject);
} }
} }
@ -233,7 +233,7 @@ namespace QuantumUNET.Components
} }
if (QSBNetworkClient.active && QSBNetworkServer.localClientActive) if (QSBNetworkClient.active && QSBNetworkServer.localClientActive)
{ {
QSBClientScene.SetLocalObject(NetId, base.gameObject); QSBClientScene.SetLocalObject(NetId, gameObject);
OnStartClient(); OnStartClient();
} }
if (HasAuthority) if (HasAuthority)
@ -253,7 +253,7 @@ namespace QuantumUNET.Components
Debug.Log(string.Concat(new object[] Debug.Log(string.Concat(new object[]
{ {
"OnStartClient ", "OnStartClient ",
base.gameObject, gameObject,
" GUID:", " GUID:",
NetId, NetId,
" localPlayerAuthority:", " localPlayerAuthority:",
@ -355,7 +355,7 @@ namespace QuantumUNET.Components
{ {
if (!LocalPlayerAuthority) if (!LocalPlayerAuthority)
{ {
Debug.LogError("HandleClientAuthority " + base.gameObject + " does not have localPlayerAuthority"); Debug.LogError("HandleClientAuthority " + gameObject + " does not have localPlayerAuthority");
} }
else else
{ {
@ -384,7 +384,7 @@ namespace QuantumUNET.Components
"Found no behaviour for incoming [", "Found no behaviour for incoming [",
cmdHashHandlerName, cmdHashHandlerName,
"] on ", "] on ",
base.gameObject, gameObject,
", the server and client should have the same NetworkBehaviour instances [netId=", ", the server and client should have the same NetworkBehaviour instances [netId=",
NetId, NetId,
"]." "]."
@ -402,7 +402,7 @@ namespace QuantumUNET.Components
internal void HandleSyncEvent(int cmdHash, QSBNetworkReader reader) internal void HandleSyncEvent(int cmdHash, QSBNetworkReader reader)
{ {
if (base.gameObject == null) if (gameObject == null)
{ {
var cmdHashHandlerName = QSBNetworkBehaviour.GetCmdHashHandlerName(cmdHash); var cmdHashHandlerName = QSBNetworkBehaviour.GetCmdHashHandlerName(cmdHash);
Debug.LogWarning(string.Concat(new object[] Debug.LogWarning(string.Concat(new object[]
@ -422,7 +422,7 @@ namespace QuantumUNET.Components
"Found no receiver for incoming [", "Found no receiver for incoming [",
cmdHashHandlerName2, cmdHashHandlerName2,
"] on ", "] on ",
base.gameObject, gameObject,
", the server and client should have the same NetworkBehaviour instances [netId=", ", the server and client should have the same NetworkBehaviour instances [netId=",
NetId, NetId,
"]." "]."
@ -448,7 +448,7 @@ namespace QuantumUNET.Components
internal void HandleSyncList(int cmdHash, QSBNetworkReader reader) internal void HandleSyncList(int cmdHash, QSBNetworkReader reader)
{ {
if (base.gameObject == null) if (gameObject == null)
{ {
var cmdHashHandlerName = QSBNetworkBehaviour.GetCmdHashHandlerName(cmdHash); var cmdHashHandlerName = QSBNetworkBehaviour.GetCmdHashHandlerName(cmdHash);
Debug.LogWarning(string.Concat(new object[] Debug.LogWarning(string.Concat(new object[]
@ -468,7 +468,7 @@ namespace QuantumUNET.Components
"Found no receiver for incoming [", "Found no receiver for incoming [",
cmdHashHandlerName2, cmdHashHandlerName2,
"] on ", "] on ",
base.gameObject, gameObject,
", the server and client should have the same NetworkBehaviour instances [netId=", ", the server and client should have the same NetworkBehaviour instances [netId=",
NetId, NetId,
"]." "]."
@ -494,7 +494,7 @@ namespace QuantumUNET.Components
internal void HandleCommand(int cmdHash, QSBNetworkReader reader) internal void HandleCommand(int cmdHash, QSBNetworkReader reader)
{ {
if (base.gameObject == null) if (gameObject == null)
{ {
var cmdHashHandlerName = QSBNetworkBehaviour.GetCmdHashHandlerName(cmdHash); var cmdHashHandlerName = QSBNetworkBehaviour.GetCmdHashHandlerName(cmdHash);
Debug.LogWarning(string.Concat(new object[] Debug.LogWarning(string.Concat(new object[]
@ -514,7 +514,7 @@ namespace QuantumUNET.Components
"Found no receiver for incoming [", "Found no receiver for incoming [",
cmdHashHandlerName2, cmdHashHandlerName2,
"] on ", "] on ",
base.gameObject, gameObject,
", the server and client should have the same NetworkBehaviour instances [netId=", ", the server and client should have the same NetworkBehaviour instances [netId=",
NetId, NetId,
"]." "]."
@ -540,7 +540,7 @@ namespace QuantumUNET.Components
internal void HandleRPC(int cmdHash, QSBNetworkReader reader) internal void HandleRPC(int cmdHash, QSBNetworkReader reader)
{ {
if (base.gameObject == null) if (gameObject == null)
{ {
var cmdHashHandlerName = QSBNetworkBehaviour.GetCmdHashHandlerName(cmdHash); var cmdHashHandlerName = QSBNetworkBehaviour.GetCmdHashHandlerName(cmdHash);
Debug.LogWarning(string.Concat(new object[] Debug.LogWarning(string.Concat(new object[]
@ -560,7 +560,7 @@ namespace QuantumUNET.Components
"Found no receiver for incoming [", "Found no receiver for incoming [",
cmdHashHandlerName2, cmdHashHandlerName2,
"] on ", "] on ",
base.gameObject, gameObject,
", the server and client should have the same NetworkBehaviour instances [netId=", ", the server and client should have the same NetworkBehaviour instances [netId=",
NetId, NetId,
"]." "]."
@ -627,7 +627,7 @@ namespace QuantumUNET.Components
Debug.LogWarning(string.Concat(new object[] Debug.LogWarning(string.Concat(new object[]
{ {
"Large state update of ", "Large state update of ",
(int)(s_UpdateWriter.Position - position), s_UpdateWriter.Position - position,
" bytes for netId:", " bytes for netId:",
NetId, NetId,
" from script:", " from script:",
@ -639,7 +639,7 @@ namespace QuantumUNET.Components
if (flag) if (flag)
{ {
s_UpdateWriter.FinishMessage(); s_UpdateWriter.FinishMessage();
QSBNetworkServer.SendWriterToReady(base.gameObject, s_UpdateWriter, j); QSBNetworkServer.SendWriterToReady(gameObject, s_UpdateWriter, j);
} }
} }
IL_197: IL_197:
@ -654,7 +654,7 @@ namespace QuantumUNET.Components
{ {
if (initialState && m_NetworkBehaviours == null) if (initialState && m_NetworkBehaviours == null)
{ {
m_NetworkBehaviours = base.GetComponents<QSBNetworkBehaviour>(); m_NetworkBehaviours = GetComponents<QSBNetworkBehaviour>();
} }
for (var i = 0; i < m_NetworkBehaviours.Length; i++) for (var i = 0; i < m_NetworkBehaviours.Length; i++)
{ {
@ -668,7 +668,7 @@ namespace QuantumUNET.Components
ModConsole.OwmlConsole.WriteLine($"SetLocalPlayer {localPlayerControllerId}"); ModConsole.OwmlConsole.WriteLine($"SetLocalPlayer {localPlayerControllerId}");
IsLocalPlayer = true; IsLocalPlayer = true;
PlayerControllerId = localPlayerControllerId; PlayerControllerId = localPlayerControllerId;
var hasAuthority = this.HasAuthority; var hasAuthority = HasAuthority;
if (LocalPlayerAuthority) if (LocalPlayerAuthority)
{ {
HasAuthority = true; HasAuthority = true;
@ -723,7 +723,7 @@ namespace QuantumUNET.Components
{ {
if (m_Observers == null) 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)) else if (m_ObserverConnections.Contains(conn.connectionId))
{ {
@ -732,7 +732,7 @@ namespace QuantumUNET.Components
"Duplicate observer ", "Duplicate observer ",
conn.address, conn.address,
" added for ", " added for ",
base.gameObject gameObject
})); }));
} }
else else
@ -742,7 +742,7 @@ namespace QuantumUNET.Components
"Added observer ", "Added observer ",
conn.address, conn.address,
" added for ", " added for ",
base.gameObject gameObject
})); }));
m_Observers.Add(conn); m_Observers.Add(conn);
m_ObserverConnections.Add(conn.connectionId); m_ObserverConnections.Add(conn.connectionId);
@ -812,7 +812,7 @@ namespace QuantumUNET.Components
Debug.LogWarning(string.Concat(new object[] Debug.LogWarning(string.Concat(new object[]
{ {
"Observer is not ready for ", "Observer is not ready for ",
base.gameObject, gameObject,
" ", " ",
networkConnection3 networkConnection3
})); }));
@ -823,7 +823,7 @@ namespace QuantumUNET.Components
Debug.Log(string.Concat(new object[] Debug.Log(string.Concat(new object[]
{ {
"New Observer for ", "New Observer for ",
base.gameObject, gameObject,
" ", " ",
networkConnection3 networkConnection3
})); }));
@ -839,7 +839,7 @@ namespace QuantumUNET.Components
Debug.Log(string.Concat(new object[] Debug.Log(string.Concat(new object[]
{ {
"Removed Observer for ", "Removed Observer for ",
base.gameObject, gameObject,
" ", " ",
networkConnection4 networkConnection4
})); }));
@ -883,12 +883,12 @@ namespace QuantumUNET.Components
} }
else if (ClientAuthorityOwner == null) 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; return false;
} }
else if (ClientAuthorityOwner != conn) else if (ClientAuthorityOwner != conn)
{ {
Debug.LogError("RemoveClientAuthority for " + base.gameObject + " has different owner."); Debug.LogError("RemoveClientAuthority for " + gameObject + " has different owner.");
return false; return false;
} }
ClientAuthorityOwner.RemoveOwnedObject(this); ClientAuthorityOwner.RemoveOwnedObject(this);
@ -917,12 +917,12 @@ namespace QuantumUNET.Components
} }
else if (ClientAuthorityOwner != null && conn != ClientAuthorityOwner) 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; return false;
} }
else if (conn == null) 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; return false;
} }
ClientAuthorityOwner = conn; ClientAuthorityOwner = conn;

View File

@ -9,10 +9,7 @@ namespace QuantumUNET.Components
public int offsetX; public int offsetX;
public int offsetY; public int offsetY;
private void Awake() private void Awake() => manager = GetComponent<QSBNetworkManagerUNET>();
{
manager = GetComponent<QSBNetworkManagerUNET>();
}
private void OnGUI() private void OnGUI()
{ {

View File

@ -50,13 +50,7 @@ namespace QuantumUNET.Components
private static QSBNetworkConnection s_ClientReadyConnection; private static QSBNetworkConnection s_ClientReadyConnection;
private static string s_Address; private static string s_Address;
public List<Transform> startPositions public List<Transform> startPositions => s_StartPositions;
{
get
{
return s_StartPositions;
}
}
public bool customConfig { get; set; } public bool customConfig { get; set; }
@ -107,10 +101,7 @@ namespace QuantumUNET.Components
} }
} }
private void Awake() public void Awake() => InitializeSingleton();
{
InitializeSingleton();
}
private void InitializeSingleton() private void InitializeSingleton()
{ {
@ -121,14 +112,14 @@ namespace QuantumUNET.Components
if (singleton != null) 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."); 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; return;
} }
Debug.Log("NetworkManager created singleton (DontDestroyOnLoad)"); Debug.Log("NetworkManager created singleton (DontDestroyOnLoad)");
singleton = this; singleton = this;
if (Application.isPlaying) if (Application.isPlaying)
{ {
DontDestroyOnLoad(base.gameObject); DontDestroyOnLoad(gameObject);
} }
} }
else else
@ -157,10 +148,7 @@ namespace QuantumUNET.Components
QSBNetworkServer.RegisterHandler(QSBMsgType.Error, new QSBNetworkMessageDelegate(OnServerErrorInternal)); QSBNetworkServer.RegisterHandler(QSBMsgType.Error, new QSBNetworkMessageDelegate(OnServerErrorInternal));
} }
public bool StartServer() public bool StartServer() => StartServer(null, -1);
{
return StartServer(null, -1);
}
private bool StartServer(ConnectionConfig config, int maxConnections) private bool StartServer(ConnectionConfig config, int maxConnections)
{ {
@ -339,15 +327,9 @@ namespace QuantumUNET.Components
return client; return client;
} }
public QSBNetworkClient StartClient() public QSBNetworkClient StartClient() => StartClient(null);
{
return StartClient(null);
}
public QSBNetworkClient StartClient(ConnectionConfig config) public QSBNetworkClient StartClient(ConnectionConfig config) => StartClient(config, 0);
{
return StartClient(config, 0);
}
public virtual QSBNetworkClient StartHost(ConnectionConfig config, int maxConnections) public virtual QSBNetworkClient StartHost(ConnectionConfig config, int maxConnections)
{ {
@ -579,10 +561,7 @@ namespace QuantumUNET.Components
s_StartPositions.Remove(start); s_StartPositions.Remove(start);
} }
public bool IsClientConnected() public bool IsClientConnected() => client != null && client.isConnected;
{
return client != null && client.isConnected;
}
public static void Shutdown() public static void Shutdown()
{ {
@ -776,15 +755,9 @@ namespace QuantumUNET.Components
QSBNetworkServer.SetClientReady(conn); QSBNetworkServer.SetClientReady(conn);
} }
public virtual void OnServerAddPlayer(QSBNetworkConnection conn, short playerControllerId, NetworkReader extraMessageReader) public virtual void OnServerAddPlayer(QSBNetworkConnection conn, short playerControllerId, NetworkReader extraMessageReader) => OnServerAddPlayerInternal(conn, playerControllerId);
{
OnServerAddPlayerInternal(conn, playerControllerId);
}
public virtual void OnServerAddPlayer(QSBNetworkConnection conn, short playerControllerId) public virtual void OnServerAddPlayer(QSBNetworkConnection conn, short playerControllerId) => OnServerAddPlayerInternal(conn, playerControllerId);
{
OnServerAddPlayerInternal(conn, playerControllerId);
}
private void OnServerAddPlayerInternal(QSBNetworkConnection conn, short playerControllerId) private void OnServerAddPlayerInternal(QSBNetworkConnection conn, short playerControllerId)
{ {

View File

@ -29,65 +29,15 @@ namespace QuantumUNET.Components
public float LastSyncTime { get; private set; } public float LastSyncTime { get; private set; }
public Vector3 TargetSyncPosition public Vector3 TargetSyncPosition => m_TargetSyncPosition;
{
get
{
return m_TargetSyncPosition;
}
}
public Vector3 targetSyncVelocity public Vector3 targetSyncVelocity => m_TargetSyncVelocity;
{
get
{
return m_TargetSyncVelocity;
}
}
public Quaternion targetSyncRotation3D public Quaternion targetSyncRotation3D => m_TargetSyncRotation3D;
{
get
{
return m_TargetSyncRotation3D;
}
}
public bool Grounded { get; set; } = true; public bool Grounded { get; set; } = true;
private void OnValidate() public void Awake()
{
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()
{ {
m_PrevPosition = transform.position; m_PrevPosition = transform.position;
m_PrevRotation = transform.rotation; m_PrevRotation = transform.rotation;
@ -97,10 +47,7 @@ namespace QuantumUNET.Components
} }
} }
public override void OnStartServer() public override void OnStartServer() => LastSyncTime = 0f;
{
LastSyncTime = 0f;
}
public override bool OnSerialize(QSBNetworkWriter writer, bool initialState) public override bool OnSerialize(QSBNetworkWriter writer, bool initialState)
{ {
@ -336,12 +283,12 @@ namespace QuantumUNET.Components
} }
else else
{ {
result = (float)reader.ReadInt16(); result = reader.ReadInt16();
} }
} }
else else
{ {
result = (float)reader.ReadInt16(); result = reader.ReadInt16();
} }
} }
else else
@ -351,10 +298,8 @@ namespace QuantumUNET.Components
return result; 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); writer.Write(velocity);
}
public static void SerializeRotation3D(QSBNetworkWriter writer, Quaternion rot, AxisSyncMode mode, CompressionSyncMode compression) 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) public static Vector3 UnserializeVelocity3D(QSBNetworkReader reader, CompressionSyncMode compression) => reader.ReadVector3();
{
return reader.ReadVector3();
}
public static Quaternion UnserializeRotation3D(QSBNetworkReader reader, AxisSyncMode mode, CompressionSyncMode compression) public static Quaternion UnserializeRotation3D(QSBNetworkReader reader, AxisSyncMode mode, CompressionSyncMode compression)
{ {
@ -519,20 +461,11 @@ namespace QuantumUNET.Components
return zero; return zero;
} }
public override int GetNetworkChannel() public override int GetNetworkChannel() => 1;
{
return 1;
}
public override float GetNetworkSendInterval() public override float GetNetworkSendInterval() => SendInterval;
{
return SendInterval;
}
public override void OnStartAuthority() public override void OnStartAuthority() => LastSyncTime = 0f;
{
LastSyncTime = 0f;
}
private Vector3 m_TargetSyncPosition; private Vector3 m_TargetSyncPosition;

View File

@ -2,15 +2,9 @@
{ {
public class QSBErrorMessage : QSBMessageBase public class QSBErrorMessage : QSBMessageBase
{ {
public override void Deserialize(QSBNetworkReader reader) public override void Deserialize(QSBNetworkReader reader) => errorCode = reader.ReadUInt16();
{
this.errorCode = (int)reader.ReadUInt16();
}
public override void Serialize(QSBNetworkWriter writer) public override void Serialize(QSBNetworkWriter writer) => writer.Write((ushort)errorCode);
{
writer.Write((ushort)this.errorCode);
}
public int errorCode; public int errorCode;
} }

View File

@ -11,7 +11,7 @@
} }
else else
{ {
string text = msgLabels[(int)value]; var text = msgLabels[value];
if (string.IsNullOrEmpty(text)) if (string.IsNullOrEmpty(text))
{ {
text = "[" + value + "]"; text = "[" + value + "]";

View File

@ -17,9 +17,6 @@ namespace QuantumUNET.Messages
return result; return result;
} }
public void ReadMessage<TMsg>(TMsg msg) where TMsg : QSBMessageBase public void ReadMessage<TMsg>(TMsg msg) where TMsg : QSBMessageBase => msg.Deserialize(Reader);
{
msg.Deserialize(Reader);
}
} }
} }

View File

@ -6,14 +6,8 @@ namespace QuantumUNET.Messages
{ {
public NetworkInstanceId NetId; public NetworkInstanceId NetId;
public override void Deserialize(QSBNetworkReader reader) public override void Deserialize(QSBNetworkReader reader) => NetId = reader.ReadNetworkId();
{
NetId = reader.ReadNetworkId();
}
public override void Serialize(QSBNetworkWriter writer) public override void Serialize(QSBNetworkWriter writer) => writer.Write(NetId);
{
writer.Write(NetId);
}
} }
} }

View File

@ -4,14 +4,8 @@
{ {
public uint State; public uint State;
public override void Deserialize(QSBNetworkReader reader) public override void Deserialize(QSBNetworkReader reader) => State = reader.ReadPackedUInt32();
{
State = reader.ReadPackedUInt32();
}
public override void Serialize(QSBNetworkWriter writer) public override void Serialize(QSBNetworkWriter writer) => writer.WritePackedUInt32(State);
{
writer.WritePackedUInt32(State);
}
} }
} }

View File

@ -6,44 +6,44 @@ namespace QuantumUNET.Messages
{ {
public override void Deserialize(QSBNetworkReader reader) public override void Deserialize(QSBNetworkReader reader)
{ {
this.connectionId = (int)reader.ReadPackedUInt32(); connectionId = (int)reader.ReadPackedUInt32();
this.address = reader.ReadString(); address = reader.ReadString();
this.port = (int)reader.ReadPackedUInt32(); port = (int)reader.ReadPackedUInt32();
this.isHost = reader.ReadBoolean(); isHost = reader.ReadBoolean();
this.isYou = reader.ReadBoolean(); isYou = reader.ReadBoolean();
uint num = reader.ReadPackedUInt32(); var num = reader.ReadPackedUInt32();
if (num > 0U) if (num > 0U)
{ {
List<QSBPeerInfoPlayer> list = new List<QSBPeerInfoPlayer>(); var list = new List<QSBPeerInfoPlayer>();
for (uint num2 = 0U; num2 < num; num2 += 1U) for (var num2 = 0U; num2 < num; num2 += 1U)
{ {
QSBPeerInfoPlayer item; QSBPeerInfoPlayer item;
item.netId = reader.ReadNetworkId(); item.netId = reader.ReadNetworkId();
item.playerControllerId = (short)reader.ReadPackedUInt32(); item.playerControllerId = (short)reader.ReadPackedUInt32();
list.Add(item); list.Add(item);
} }
this.playerIds = list.ToArray(); playerIds = list.ToArray();
} }
} }
public override void Serialize(QSBNetworkWriter writer) public override void Serialize(QSBNetworkWriter writer)
{ {
writer.WritePackedUInt32((uint)this.connectionId); writer.WritePackedUInt32((uint)connectionId);
writer.Write(this.address); writer.Write(address);
writer.WritePackedUInt32((uint)this.port); writer.WritePackedUInt32((uint)port);
writer.Write(this.isHost); writer.Write(isHost);
writer.Write(this.isYou); writer.Write(isYou);
if (this.playerIds == null) if (playerIds == null)
{ {
writer.WritePackedUInt32(0U); writer.WritePackedUInt32(0U);
} }
else else
{ {
writer.WritePackedUInt32((uint)this.playerIds.Length); writer.WritePackedUInt32((uint)playerIds.Length);
for (int i = 0; i < this.playerIds.Length; i++) for (var i = 0; i < playerIds.Length; i++)
{ {
writer.Write(this.playerIds[i].netId); writer.Write(playerIds[i].netId);
writer.WritePackedUInt32((uint)this.playerIds[i].playerControllerId); writer.WritePackedUInt32((uint)playerIds[i].playerControllerId);
} }
} }
} }
@ -53,15 +53,15 @@ namespace QuantumUNET.Messages
return string.Concat(new object[] return string.Concat(new object[]
{ {
"PeerInfo conn:", "PeerInfo conn:",
this.connectionId, connectionId,
" addr:", " addr:",
this.address, address,
":", ":",
this.port, port,
" host:", " host:",
this.isHost, isHost,
" isYou:", " isYou:",
this.isYou isYou
}); });
} }

View File

@ -4,14 +4,8 @@
{ {
public short PlayerControllerId; public short PlayerControllerId;
public override void Deserialize(QSBNetworkReader reader) public override void Deserialize(QSBNetworkReader reader) => PlayerControllerId = (short)reader.ReadUInt16();
{
PlayerControllerId = (short)reader.ReadUInt16();
}
public override void Serialize(QSBNetworkWriter writer) public override void Serialize(QSBNetworkWriter writer) => writer.Write((ushort)PlayerControllerId);
{
writer.Write((ushort)PlayerControllerId);
}
} }
} }

View File

@ -8,18 +8,12 @@
public QSBStringMessage(string v) public QSBStringMessage(string v)
{ {
this.value = v; value = v;
} }
public override void Deserialize(QSBNetworkReader reader) public override void Deserialize(QSBNetworkReader reader) => value = reader.ReadString();
{
this.value = reader.ReadString();
}
public override void Serialize(QSBNetworkWriter writer) public override void Serialize(QSBNetworkWriter writer) => writer.Write(value);
{
writer.Write(this.value);
}
public string value; public string value;
} }

View File

@ -8,53 +8,43 @@ namespace QuantumUNET
{ {
public QSBChannelPacket(int packetSize, bool isReliable) public QSBChannelPacket(int packetSize, bool isReliable)
{ {
this.m_Position = 0; m_Position = 0;
this.m_Buffer = new byte[packetSize]; m_Buffer = new byte[packetSize];
this.m_IsReliable = isReliable; m_IsReliable = isReliable;
} }
public void Reset() public void Reset() => m_Position = 0;
{
this.m_Position = 0;
}
public bool IsEmpty() public bool IsEmpty() => m_Position == 0;
{
return this.m_Position == 0;
}
public void Write(byte[] bytes, int numBytes) public void Write(byte[] bytes, int numBytes)
{ {
Array.Copy(bytes, 0, this.m_Buffer, this.m_Position, numBytes); Array.Copy(bytes, 0, m_Buffer, m_Position, numBytes);
this.m_Position += numBytes; m_Position += numBytes;
} }
public bool HasSpace(int numBytes) public bool HasSpace(int numBytes) => m_Position + numBytes <= m_Buffer.Length;
{
return this.m_Position + numBytes <= this.m_Buffer.Length;
}
public bool SendToTransport(QSBNetworkConnection conn, int channelId) public bool SendToTransport(QSBNetworkConnection conn, int channelId)
{ {
bool result = true; var result = true;
byte b; if (!conn.TransportSend(m_Buffer, (ushort)m_Position, channelId, out var b))
if (!conn.TransportSend(this.m_Buffer, (int)((ushort)this.m_Position), channelId, out b))
{ {
if (!this.m_IsReliable || b != 4) if (!m_IsReliable || b != 4)
{ {
Debug.LogError(string.Concat(new object[] Debug.LogError(string.Concat(new object[]
{ {
"Failed to send internal buffer channel:", "Failed to send internal buffer channel:",
channelId, channelId,
" bytesToSend:", " bytesToSend:",
this.m_Position m_Position
})); }));
result = false; result = false;
} }
} }
if (b != 0) if (b != 0)
{ {
if (this.m_IsReliable && b == 4) if (m_IsReliable && b == 4)
{ {
return false; return false;
} }
@ -65,11 +55,11 @@ namespace QuantumUNET
" channel:", " channel:",
channelId, channelId,
" bytesToSend:", " bytesToSend:",
this.m_Position m_Position
})); }));
result = false; result = false;
} }
this.m_Position = 0; m_Position = 0;
return result; return result;
} }

View File

@ -54,7 +54,7 @@ namespace QuantumUNET
{ {
player = null; player = null;
bool result; bool result;
if ((int)playerControllerId >= localPlayers.Count) if (playerControllerId >= localPlayers.Count)
{ {
if (LogFilter.logWarn) if (LogFilter.logWarn)
{ {
@ -62,7 +62,7 @@ namespace QuantumUNET
} }
result = false; result = false;
} }
else if (localPlayers[(int)playerControllerId] == null) else if (localPlayers[playerControllerId] == null)
{ {
if (LogFilter.logWarn) if (LogFilter.logWarn)
{ {
@ -72,7 +72,7 @@ namespace QuantumUNET
} }
else else
{ {
player = localPlayers[(int)playerControllerId]; player = localPlayers[playerControllerId];
result = (player.Gameobject != null); result = (player.Gameobject != null);
} }
return result; return result;
@ -84,13 +84,13 @@ namespace QuantumUNET
{ {
Debug.LogWarning("ClientScene::InternalAddPlayer: playerControllerId : " + playerControllerId); Debug.LogWarning("ClientScene::InternalAddPlayer: playerControllerId : " + playerControllerId);
} }
if ((int)playerControllerId >= localPlayers.Count) if (playerControllerId >= localPlayers.Count)
{ {
if (LogFilter.logWarn) if (LogFilter.logWarn)
{ {
Debug.LogWarning("ClientScene::InternalAddPlayer: playerControllerId higher than expected: " + playerControllerId); Debug.LogWarning("ClientScene::InternalAddPlayer: playerControllerId higher than expected: " + playerControllerId);
} }
while ((int)playerControllerId >= localPlayers.Count) while (playerControllerId >= localPlayers.Count)
{ {
localPlayers.Add(new QSBPlayerController()); localPlayers.Add(new QSBPlayerController());
} }
@ -101,7 +101,7 @@ namespace QuantumUNET
PlayerControllerId = playerControllerId, PlayerControllerId = playerControllerId,
UnetView = view UnetView = view
}; };
localPlayers[(int)playerControllerId] = playerController; localPlayers[playerControllerId] = playerController;
readyConnection.SetPlayerController(playerController); readyConnection.SetPlayerController(playerController);
} }
@ -143,7 +143,7 @@ namespace QuantumUNET
Debug.LogWarning("ClientScene::AddPlayer: playerControllerId of " + playerControllerId + " is unusually high"); Debug.LogWarning("ClientScene::AddPlayer: playerControllerId of " + playerControllerId + " is unusually high");
} }
} }
while ((int)playerControllerId >= localPlayers.Count) while (playerControllerId >= localPlayers.Count)
{ {
localPlayers.Add(new QSBPlayerController()); localPlayers.Add(new QSBPlayerController());
} }
@ -194,7 +194,7 @@ namespace QuantumUNET
var networkWriter = new QSBNetworkWriter(); var networkWriter = new QSBNetworkWriter();
extraMessage.Serialize(networkWriter); extraMessage.Serialize(networkWriter);
addPlayerMessage.msgData = networkWriter.ToArray(); addPlayerMessage.msgData = networkWriter.ToArray();
addPlayerMessage.msgSize = (int)networkWriter.Position; addPlayerMessage.msgSize = networkWriter.Position;
} }
readyConnection.Send(37, addPlayerMessage); readyConnection.Send(37, addPlayerMessage);
result = true; result = true;
@ -224,8 +224,8 @@ namespace QuantumUNET
}; };
readyConnection.Send(38, removePlayerMessage); readyConnection.Send(38, removePlayerMessage);
readyConnection.RemovePlayerController(playerControllerId); readyConnection.RemovePlayerController(playerControllerId);
localPlayers[(int)playerControllerId] = new QSBPlayerController(); localPlayers[playerControllerId] = new QSBPlayerController();
UnityEngine.Object.Destroy(playerController.Gameobject); Object.Destroy(playerController.Gameobject);
result = true; result = true;
} }
else else
@ -346,29 +346,29 @@ namespace QuantumUNET
{ {
if (localClient) if (localClient)
{ {
client.RegisterHandlerSafe((short)1, new QSBNetworkMessageDelegate(OnLocalClientObjectDestroy)); client.RegisterHandlerSafe(1, new QSBNetworkMessageDelegate(OnLocalClientObjectDestroy));
client.RegisterHandlerSafe((short)13, new QSBNetworkMessageDelegate(OnLocalClientObjectHide)); client.RegisterHandlerSafe(13, new QSBNetworkMessageDelegate(OnLocalClientObjectHide));
client.RegisterHandlerSafe((short)3, new QSBNetworkMessageDelegate(OnLocalClientObjectSpawn)); client.RegisterHandlerSafe(3, new QSBNetworkMessageDelegate(OnLocalClientObjectSpawn));
client.RegisterHandlerSafe((short)10, new QSBNetworkMessageDelegate(OnLocalClientObjectSpawnScene)); client.RegisterHandlerSafe(10, new QSBNetworkMessageDelegate(OnLocalClientObjectSpawnScene));
client.RegisterHandlerSafe((short)15, new QSBNetworkMessageDelegate(OnClientAuthority)); client.RegisterHandlerSafe(15, new QSBNetworkMessageDelegate(OnClientAuthority));
} }
else else
{ {
client.RegisterHandlerSafe((short)3, new QSBNetworkMessageDelegate(OnObjectSpawn)); client.RegisterHandlerSafe(3, new QSBNetworkMessageDelegate(OnObjectSpawn));
client.RegisterHandlerSafe((short)10, new QSBNetworkMessageDelegate(OnObjectSpawnScene)); client.RegisterHandlerSafe(10, new QSBNetworkMessageDelegate(OnObjectSpawnScene));
client.RegisterHandlerSafe((short)12, new QSBNetworkMessageDelegate(OnObjectSpawnFinished)); client.RegisterHandlerSafe(12, new QSBNetworkMessageDelegate(OnObjectSpawnFinished));
client.RegisterHandlerSafe((short)1, new QSBNetworkMessageDelegate(OnObjectDestroy)); client.RegisterHandlerSafe(1, new QSBNetworkMessageDelegate(OnObjectDestroy));
client.RegisterHandlerSafe((short)13, new QSBNetworkMessageDelegate(OnObjectDestroy)); client.RegisterHandlerSafe(13, new QSBNetworkMessageDelegate(OnObjectDestroy));
client.RegisterHandlerSafe((short)8, new QSBNetworkMessageDelegate(OnUpdateVarsMessage)); client.RegisterHandlerSafe(8, new QSBNetworkMessageDelegate(OnUpdateVarsMessage));
client.RegisterHandlerSafe((short)4, new QSBNetworkMessageDelegate(OnOwnerMessage)); client.RegisterHandlerSafe(4, new QSBNetworkMessageDelegate(OnOwnerMessage));
client.RegisterHandlerSafe((short)9, new QSBNetworkMessageDelegate(OnSyncListMessage)); client.RegisterHandlerSafe(9, new QSBNetworkMessageDelegate(OnSyncListMessage));
client.RegisterHandlerSafe((short)40, new QSBNetworkMessageDelegate(QSBNetworkAnimator.OnAnimationClientMessage)); client.RegisterHandlerSafe(40, new QSBNetworkMessageDelegate(QSBNetworkAnimator.OnAnimationClientMessage));
client.RegisterHandlerSafe((short)41, new QSBNetworkMessageDelegate(QSBNetworkAnimator.OnAnimationParametersClientMessage)); client.RegisterHandlerSafe(41, new QSBNetworkMessageDelegate(QSBNetworkAnimator.OnAnimationParametersClientMessage));
client.RegisterHandlerSafe((short)15, new QSBNetworkMessageDelegate(OnClientAuthority)); client.RegisterHandlerSafe(15, new QSBNetworkMessageDelegate(OnClientAuthority));
} }
client.RegisterHandlerSafe((short)2, new QSBNetworkMessageDelegate(OnRPCMessage)); client.RegisterHandlerSafe(2, new QSBNetworkMessageDelegate(OnRPCMessage));
client.RegisterHandlerSafe((short)7, new QSBNetworkMessageDelegate(OnSyncEventMessage)); client.RegisterHandlerSafe(7, new QSBNetworkMessageDelegate(OnSyncEventMessage));
client.RegisterHandlerSafe((short)42, new QSBNetworkMessageDelegate(QSBNetworkAnimator.OnAnimationTriggerClientMessage)); client.RegisterHandlerSafe(42, new QSBNetworkMessageDelegate(QSBNetworkAnimator.OnAnimationTriggerClientMessage));
} }
internal static string GetStringForAssetId(NetworkHash128 assetId) internal static string GetStringForAssetId(NetworkHash128 assetId)
@ -449,7 +449,7 @@ namespace QuantumUNET
} }
else if (QSBNetworkScene.GetPrefab(s_ObjectSpawnMessage.assetId, out var original)) else if (QSBNetworkScene.GetPrefab(s_ObjectSpawnMessage.assetId, out var original))
{ {
GameObject gameObject = UnityEngine.Object.Instantiate<GameObject>(original, s_ObjectSpawnMessage.Position, s_ObjectSpawnMessage.Rotation); var gameObject = Object.Instantiate<GameObject>(original, s_ObjectSpawnMessage.Position, s_ObjectSpawnMessage.Rotation);
component = gameObject.GetComponent<QSBNetworkIdentity>(); component = gameObject.GetComponent<QSBNetworkIdentity>();
if (component == null) if (component == null)
{ {
@ -572,7 +572,7 @@ namespace QuantumUNET
{ {
if (networkIdentity.SceneId.IsEmpty()) if (networkIdentity.SceneId.IsEmpty())
{ {
UnityEngine.Object.Destroy(networkIdentity.gameObject); Object.Destroy(networkIdentity.gameObject);
} }
else else
{ {
@ -663,7 +663,7 @@ namespace QuantumUNET
} }
else if (LogFilter.logWarn) 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[] Debug.LogWarningFormat("Could not find target object with netId:{0} for RPC call {1}", new object[]
{ {
networkInstanceId, networkInstanceId,

View File

@ -14,7 +14,7 @@ namespace QuantumUNET
PostInternalMessage(33); PostInternalMessage(33);
m_Connected = false; m_Connected = false;
} }
m_AsyncConnect = QSBNetworkClient.ConnectState.Disconnected; m_AsyncConnect = ConnectState.Disconnected;
m_LocalServer.RemoveLocalClient(m_Connection); m_LocalServer.RemoveLocalClient(m_Connection);
} }
@ -31,11 +31,11 @@ namespace QuantumUNET
} }
m_LocalServer = QSBNetworkServer.instance; m_LocalServer = QSBNetworkServer.instance;
m_Connection = new QSBULocalConnectionToServer(m_LocalServer); m_Connection = new QSBULocalConnectionToServer(m_LocalServer);
base.SetHandlers(m_Connection); SetHandlers(m_Connection);
m_Connection.connectionId = m_LocalServer.AddLocalClient(this); m_Connection.connectionId = m_LocalServer.AddLocalClient(this);
m_AsyncConnect = QSBNetworkClient.ConnectState.Connected; m_AsyncConnect = ConnectState.Connected;
QSBNetworkClient.SetActive(true); SetActive(true);
base.RegisterSystemHandlers(true); RegisterSystemHandlers(true);
if (generateConnectMsg) if (generateConnectMsg)
{ {
PostInternalMessage(32); PostInternalMessage(32);
@ -108,11 +108,11 @@ namespace QuantumUNET
} }
s_InternalMessage.Reader.ReadInt16(); s_InternalMessage.Reader.ReadInt16();
s_InternalMessage.ChannelId = t.channelId; s_InternalMessage.ChannelId = t.channelId;
s_InternalMessage.Connection = base.connection; s_InternalMessage.Connection = connection;
s_InternalMessage.MsgType = s_InternalMessage.Reader.ReadInt16(); s_InternalMessage.MsgType = s_InternalMessage.Reader.ReadInt16();
m_Connection.InvokeHandler(s_InternalMessage); m_Connection.InvokeHandler(s_InternalMessage);
m_FreeMessages.Push(t); m_FreeMessages.Push(t);
base.connection.lastMessageTime = Time.time; connection.lastMessageTime = Time.time;
} }
m_InternalMsgs = internalMsgs; m_InternalMsgs = internalMsgs;
m_InternalMsgs.Clear(); m_InternalMsgs.Clear();

View File

@ -15,34 +15,22 @@ namespace QuantumUNET
m_Buffer = buffer; m_Buffer = buffer;
} }
public uint Position public uint Position { get; private set; }
{
get
{
return m_Pos;
}
}
public int Length public int Length => m_Buffer.Length;
{
get
{
return m_Buffer.Length;
}
}
public byte ReadByte() 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()); 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) 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[] throw new IndexOutOfRangeException(string.Concat(new object[]
{ {
@ -53,110 +41,107 @@ namespace QuantumUNET
})); }));
} }
ushort num = 0; 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; num += 1;
} }
m_Pos += count; Position += count;
} }
internal ArraySegment<byte> AsArraySegment() internal ArraySegment<byte> AsArraySegment() => new ArraySegment<byte>(m_Buffer, 0, (int)Position);
{
return new ArraySegment<byte>(m_Buffer, 0, (int)m_Pos);
}
public void WriteByte(byte value) public void WriteByte(byte value)
{ {
WriteCheckForSpace(1); WriteCheckForSpace(1);
m_Buffer[(int)((UIntPtr)m_Pos)] = value; m_Buffer[(int)((UIntPtr)Position)] = value;
m_Pos += 1U; Position += 1U;
} }
public void WriteByte2(byte value0, byte value1) public void WriteByte2(byte value0, byte value1)
{ {
WriteCheckForSpace(2); WriteCheckForSpace(2);
m_Buffer[(int)((UIntPtr)m_Pos)] = value0; m_Buffer[(int)((UIntPtr)Position)] = value0;
m_Buffer[(int)((UIntPtr)(m_Pos + 1U))] = value1; m_Buffer[(int)((UIntPtr)(Position + 1U))] = value1;
m_Pos += 2U; Position += 2U;
} }
public void WriteByte4(byte value0, byte value1, byte value2, byte value3) public void WriteByte4(byte value0, byte value1, byte value2, byte value3)
{ {
WriteCheckForSpace(4); WriteCheckForSpace(4);
m_Buffer[(int)((UIntPtr)m_Pos)] = value0; m_Buffer[(int)((UIntPtr)Position)] = value0;
m_Buffer[(int)((UIntPtr)(m_Pos + 1U))] = value1; m_Buffer[(int)((UIntPtr)(Position + 1U))] = value1;
m_Buffer[(int)((UIntPtr)(m_Pos + 2U))] = value2; m_Buffer[(int)((UIntPtr)(Position + 2U))] = value2;
m_Buffer[(int)((UIntPtr)(m_Pos + 3U))] = value3; m_Buffer[(int)((UIntPtr)(Position + 3U))] = value3;
m_Pos += 4U; Position += 4U;
} }
public void WriteByte8(byte value0, byte value1, byte value2, byte value3, byte value4, byte value5, byte value6, byte value7) public void WriteByte8(byte value0, byte value1, byte value2, byte value3, byte value4, byte value5, byte value6, byte value7)
{ {
WriteCheckForSpace(8); WriteCheckForSpace(8);
m_Buffer[(int)((UIntPtr)m_Pos)] = value0; m_Buffer[(int)((UIntPtr)Position)] = value0;
m_Buffer[(int)((UIntPtr)(m_Pos + 1U))] = value1; m_Buffer[(int)((UIntPtr)(Position + 1U))] = value1;
m_Buffer[(int)((UIntPtr)(m_Pos + 2U))] = value2; m_Buffer[(int)((UIntPtr)(Position + 2U))] = value2;
m_Buffer[(int)((UIntPtr)(m_Pos + 3U))] = value3; m_Buffer[(int)((UIntPtr)(Position + 3U))] = value3;
m_Buffer[(int)((UIntPtr)(m_Pos + 4U))] = value4; m_Buffer[(int)((UIntPtr)(Position + 4U))] = value4;
m_Buffer[(int)((UIntPtr)(m_Pos + 5U))] = value5; m_Buffer[(int)((UIntPtr)(Position + 5U))] = value5;
m_Buffer[(int)((UIntPtr)(m_Pos + 6U))] = value6; m_Buffer[(int)((UIntPtr)(Position + 6U))] = value6;
m_Buffer[(int)((UIntPtr)(m_Pos + 7U))] = value7; m_Buffer[(int)((UIntPtr)(Position + 7U))] = value7;
m_Pos += 8U; Position += 8U;
} }
public void WriteBytesAtOffset(byte[] buffer, ushort targetOffset, ushort count) public void WriteBytesAtOffset(byte[] buffer, ushort targetOffset, ushort count)
{ {
uint num = (uint)(count + targetOffset); var num = (uint)(count + targetOffset);
WriteCheckForSpace((ushort)num); 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 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) public void WriteBytes(byte[] buffer, ushort count)
{ {
WriteCheckForSpace(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 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) 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)); var num = (int)Math.Ceiling(m_Buffer.Length * 1.5f);
while ((ulong)(m_Pos + (uint)count) >= (ulong)((long)num)) while (Position + count >= (ulong)num)
{ {
num = (int)Math.Ceiling((double)((float)num * 1.5f)); num = (int)Math.Ceiling(num * 1.5f);
if (num > 134217728) if (num > 134217728)
{ {
Debug.LogWarning("NetworkBuffer size is " + num + " bytes!"); Debug.LogWarning("NetworkBuffer size is " + num + " bytes!");
} }
} }
byte[] array = new byte[num]; var array = new byte[num];
m_Buffer.CopyTo(array, 0); m_Buffer.CopyTo(array, 0);
m_Buffer = array; m_Buffer = array;
} }
@ -164,31 +149,22 @@ namespace QuantumUNET
public void FinishMessage() public void FinishMessage()
{ {
ushort num = (ushort)(m_Pos - 4U); var num = (ushort)(Position - 4U);
m_Buffer[0] = (byte)(num & 255); m_Buffer[0] = (byte)(num & 255);
m_Buffer[1] = (byte)(num >> 8 & 255); m_Buffer[1] = (byte)((num >> 8) & 255);
} }
public void SeekZero() public void SeekZero() => Position = 0U;
{
m_Pos = 0U;
}
public void Replace(byte[] buffer) public void Replace(byte[] buffer)
{ {
m_Buffer = buffer; m_Buffer = buffer;
m_Pos = 0U; Position = 0U;
} }
public override string ToString() public override string ToString() => string.Format("NetBuf sz:{0} pos:{1}", m_Buffer.Length, Position);
{
return string.Format("NetBuf sz:{0} pos:{1}", m_Buffer.Length, m_Pos);
}
private byte[] m_Buffer; private byte[] m_Buffer;
private uint m_Pos;
private const int k_InitialSize = 64; private const int k_InitialSize = 64;
private const float k_GrowthFactor = 1.5f; private const float k_GrowthFactor = 1.5f;

View File

@ -77,7 +77,7 @@ namespace QuantumUNET
} }
} }
writer.FinishMessage(); writer.FinishMessage();
QSBNetworkServer.SendWriterToReady(base.gameObject, writer, channelId); QSBNetworkServer.SendWriterToReady(gameObject, writer, channelId);
} }
protected void SendTargetRPCInternal(QSBNetworkConnection conn, QSBNetworkWriter writer, int channelId, string rpcName) protected void SendTargetRPCInternal(QSBNetworkConnection conn, QSBNetworkWriter writer, int channelId, string rpcName)
@ -434,7 +434,7 @@ namespace QuantumUNET
Debug.Log(string.Concat(new object[] Debug.Log(string.Concat(new object[]
{ {
"SetSyncVar GameObject ", "SetSyncVar GameObject ",
base.GetType().Name, GetType().Name,
" bit [", " bit [",
dirtyBit, dirtyBit,
"] netfieldId:", "] netfieldId:",

View File

@ -20,13 +20,7 @@ namespace QuantumUNET
} }
} }
public Dictionary<string, int> scripts public Dictionary<string, int> scripts { get; } = new Dictionary<string, int>();
{
get
{
return this.m_Scripts;
}
}
public static bool scriptCRCCheck public static bool scriptCRCCheck
{ {
@ -42,12 +36,12 @@ namespace QuantumUNET
public static void ReinitializeScriptCRCs(Assembly callingAssembly) public static void ReinitializeScriptCRCs(Assembly callingAssembly)
{ {
singleton.m_Scripts.Clear(); singleton.scripts.Clear();
foreach (Type type in callingAssembly.GetTypes()) foreach (var type in callingAssembly.GetTypes())
{ {
if (type.GetBaseType() == typeof(QSBNetworkBehaviour)) if (type.GetBaseType() == typeof(QSBNetworkBehaviour))
{ {
MethodInfo method = type.GetMethod(".cctor", BindingFlags.Static); var method = type.GetMethod(".cctor", BindingFlags.Static);
if (method != null) if (method != null)
{ {
method.Invoke(null, new object[0]); method.Invoke(null, new object[0]);
@ -56,31 +50,25 @@ namespace QuantumUNET
} }
} }
public static void RegisterBehaviour(string name, int channel) public static void RegisterBehaviour(string name, int channel) => singleton.scripts[name] = channel;
{
singleton.m_Scripts[name] = channel;
}
internal static bool Validate(QSBCRCMessageEntry[] scripts, int numChannels) internal static bool Validate(QSBCRCMessageEntry[] scripts, int numChannels) => singleton.ValidateInternal(scripts, numChannels);
{
return singleton.ValidateInternal(scripts, numChannels);
}
private bool ValidateInternal(QSBCRCMessageEntry[] remoteScripts, int numChannels) private bool ValidateInternal(QSBCRCMessageEntry[] remoteScripts, int numChannels)
{ {
bool result; bool result;
if (this.m_Scripts.Count != remoteScripts.Length) if (scripts.Count != remoteScripts.Length)
{ {
if (LogFilter.logWarn) if (LogFilter.logWarn)
{ {
Debug.LogWarning("Network configuration mismatch detected. The number of networked scripts on the client does not match the number of networked scripts on the server. This could be caused by lazy loading of scripts on the client. This warning can be disabled by the checkbox in NetworkManager Script CRC Check."); Debug.LogWarning("Network configuration mismatch detected. The number of networked scripts on the client does not match the number of networked scripts on the server. This could be caused by lazy loading of scripts on the client. This warning can be disabled by the checkbox in NetworkManager Script CRC Check.");
} }
this.Dump(remoteScripts); Dump(remoteScripts);
result = false; result = false;
} }
else else
{ {
foreach (QSBCRCMessageEntry crcmessageEntry in remoteScripts) foreach (var crcmessageEntry in remoteScripts)
{ {
if (LogFilter.logDebug) if (LogFilter.logDebug)
{ {
@ -92,10 +80,10 @@ namespace QuantumUNET
crcmessageEntry.channel crcmessageEntry.channel
})); }));
} }
if (this.m_Scripts.ContainsKey(crcmessageEntry.name)) if (scripts.ContainsKey(crcmessageEntry.name))
{ {
int num = this.m_Scripts[crcmessageEntry.name]; var num = scripts[crcmessageEntry.name];
if (num != (int)crcmessageEntry.channel) if (num != crcmessageEntry.channel)
{ {
if (LogFilter.logError) if (LogFilter.logError)
{ {
@ -109,11 +97,11 @@ namespace QuantumUNET
crcmessageEntry.channel crcmessageEntry.channel
})); }));
} }
this.Dump(remoteScripts); Dump(remoteScripts);
return false; return false;
} }
} }
if ((int)crcmessageEntry.channel >= numChannels) if (crcmessageEntry.channel >= numChannels)
{ {
if (LogFilter.logError) if (LogFilter.logError)
{ {
@ -125,7 +113,7 @@ namespace QuantumUNET
crcmessageEntry.channel crcmessageEntry.channel
})); }));
} }
this.Dump(remoteScripts); Dump(remoteScripts);
return false; return false;
} }
} }
@ -136,17 +124,17 @@ namespace QuantumUNET
private void Dump(QSBCRCMessageEntry[] remoteScripts) 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[] Debug.Log(string.Concat(new object[]
{ {
"CRC Local Dump ", "CRC Local Dump ",
text, text,
" : ", " : ",
this.m_Scripts[text] scripts[text]
})); }));
} }
foreach (QSBCRCMessageEntry crcmessageEntry in remoteScripts) foreach (var crcmessageEntry in remoteScripts)
{ {
Debug.Log(string.Concat(new object[] Debug.Log(string.Concat(new object[]
{ {
@ -159,9 +147,6 @@ namespace QuantumUNET
} }
internal static QSBNetworkCRC s_Singleton; internal static QSBNetworkCRC s_Singleton;
private Dictionary<string, int> m_Scripts = new Dictionary<string, int>();
private bool m_ScriptCRCCheck; private bool m_ScriptCRCCheck;
} }
} }

View File

@ -30,82 +30,25 @@ namespace QuantumUNET
RegisterSystemHandlers(false); RegisterSystemHandlers(false);
} }
public static List<QSBNetworkClient> allClients public static List<QSBNetworkClient> allClients { get; private set; } = new List<QSBNetworkClient>();
{
get
{
return s_Clients;
}
}
public static bool active public static bool active { get; private set; }
{
get
{
return s_IsActive;
}
}
internal void SetHandlers(QSBNetworkConnection conn) internal void SetHandlers(QSBNetworkConnection conn) => conn.SetHandlers(m_MessageHandlers);
{
conn.SetHandlers(m_MessageHandlers);
}
public string serverIp public string serverIp { get; private set; } = "";
{
get
{
return m_ServerIp;
}
}
public int serverPort public int serverPort { get; private set; }
{
get
{
return m_ServerPort;
}
}
public QSBNetworkConnection connection public QSBNetworkConnection connection => m_Connection;
{
get
{
return m_Connection;
}
}
internal int hostId internal int hostId { get; private set; } = -1;
{
get
{
return m_ClientId;
}
}
public Dictionary<short, QSBNetworkMessageDelegate> handlers public Dictionary<short, QSBNetworkMessageDelegate> handlers => m_MessageHandlers.GetHandlers();
{
get
{
return m_MessageHandlers.GetHandlers();
}
}
public int numChannels public int numChannels => hostTopology.DefaultConfig.ChannelCount;
{
get
{
return m_HostTopology.DefaultConfig.ChannelCount;
}
}
public HostTopology hostTopology public HostTopology hostTopology { get; private set; }
{
get
{
return m_HostTopology;
}
}
public int hostPort public int hostPort
{ {
@ -127,36 +70,21 @@ namespace QuantumUNET
} }
} }
public bool isConnected public bool isConnected => m_AsyncConnect == ConnectState.Connected;
{
get
{
return m_AsyncConnect == ConnectState.Connected;
}
}
public Type networkConnectionClass public Type networkConnectionClass { get; private set; } = typeof(QSBNetworkConnection);
{
get
{
return m_NetworkConnectionClass;
}
}
public void SetNetworkConnectionClass<T>() where T : QSBNetworkConnection public void SetNetworkConnectionClass<T>() where T : QSBNetworkConnection => networkConnectionClass = typeof(T);
{
m_NetworkConnectionClass = typeof(T);
}
public bool Configure(ConnectionConfig config, int maxConnections) public bool Configure(ConnectionConfig config, int maxConnections)
{ {
HostTopology topology = new HostTopology(config, maxConnections); var topology = new HostTopology(config, maxConnections);
return Configure(topology); return Configure(topology);
} }
public bool Configure(HostTopology topology) public bool Configure(HostTopology topology)
{ {
m_HostTopology = topology; hostTopology = topology;
return true; return true;
} }
@ -195,16 +123,16 @@ namespace QuantumUNET
QSBClientScene.ClearLocalPlayers(); QSBClientScene.ClearLocalPlayers();
m_Connection.Disconnect(); m_Connection.Disconnect();
m_Connection = null; m_Connection = null;
m_ClientId = NetworkTransport.AddHost(m_HostTopology, m_HostPort); hostId = NetworkTransport.AddHost(hostTopology, m_HostPort);
m_ServerPort = serverPort; this.serverPort = serverPort;
if (Application.platform == RuntimePlatform.WebGLPlayer) if (Application.platform == RuntimePlatform.WebGLPlayer)
{ {
m_ServerIp = serverIp; this.serverIp = serverIp;
m_AsyncConnect = ConnectState.Resolved; m_AsyncConnect = ConnectState.Resolved;
} }
else if (serverIp.Equals("127.0.0.1") || serverIp.Equals("localhost")) 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; m_AsyncConnect = ConnectState.Resolved;
} }
else else
@ -250,7 +178,7 @@ namespace QuantumUNET
QSBClientScene.ClearLocalPlayers(); QSBClientScene.ClearLocalPlayers();
m_Connection.Disconnect(); m_Connection.Disconnect();
m_Connection = null; m_Connection = null;
m_ClientId = NetworkTransport.AddHost(m_HostTopology, m_HostPort); hostId = NetworkTransport.AddHost(hostTopology, m_HostPort);
if (secureTunnelEndPoint == null) if (secureTunnelEndPoint == null)
{ {
if (LogFilter.logError) if (LogFilter.logError)
@ -271,11 +199,11 @@ namespace QuantumUNET
} }
else else
{ {
string fullName = secureTunnelEndPoint.GetType().FullName; var fullName = secureTunnelEndPoint.GetType().FullName;
if (fullName == "System.Net.IPEndPoint") if (fullName == "System.Net.IPEndPoint")
{ {
IPEndPoint ipendPoint = (IPEndPoint)secureTunnelEndPoint; var ipendPoint = (IPEndPoint)secureTunnelEndPoint;
this.Connect(ipendPoint.Address.ToString(), ipendPoint.Port); Connect(ipendPoint.Address.ToString(), ipendPoint.Port);
result = (m_AsyncConnect != ConnectState.Failed); result = (m_AsyncConnect != ConnectState.Failed);
} }
else if (fullName != "UnityEngine.XboxOne.XboxOneEndPoint" && fullName != "UnityEngine.PS4.SceEndPoint") else if (fullName != "UnityEngine.XboxOne.XboxOneEndPoint" && fullName != "UnityEngine.PS4.SceEndPoint")
@ -289,12 +217,12 @@ namespace QuantumUNET
} }
else else
{ {
byte b = 0;
m_RemoteEndPoint = secureTunnelEndPoint; m_RemoteEndPoint = secureTunnelEndPoint;
m_AsyncConnect = ConnectState.Connecting; m_AsyncConnect = ConnectState.Connecting;
byte b;
try 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) catch (Exception arg)
{ {
@ -316,9 +244,9 @@ namespace QuantumUNET
} }
else else
{ {
m_Connection = (QSBNetworkConnection)Activator.CreateInstance(m_NetworkConnectionClass); m_Connection = (QSBNetworkConnection)Activator.CreateInstance(networkConnectionClass);
m_Connection.SetHandlers(m_MessageHandlers); 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; result = true;
} }
} }
@ -337,7 +265,7 @@ namespace QuantumUNET
private static bool IsValidIpV6(string address) 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')) if (c != ':' && (c < '0' || c > '9') && (c < 'a' || c > 'f') && (c < 'A' || c > 'F'))
{ {
@ -357,20 +285,20 @@ namespace QuantumUNET
":", ":",
serverPort serverPort
})); }));
m_ServerPort = serverPort; this.serverPort = serverPort;
if (Application.platform == RuntimePlatform.WebGLPlayer) if (Application.platform == RuntimePlatform.WebGLPlayer)
{ {
m_ServerIp = serverIp; this.serverIp = serverIp;
m_AsyncConnect = ConnectState.Resolved; m_AsyncConnect = ConnectState.Resolved;
} }
else if (serverIp.Equals("127.0.0.1") || serverIp.Equals("localhost")) 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; m_AsyncConnect = ConnectState.Resolved;
} }
else if (serverIp.IndexOf(":") != -1 && IsValidIpV6(serverIp)) else if (serverIp.IndexOf(":") != -1 && IsValidIpV6(serverIp))
{ {
m_ServerIp = serverIp; this.serverIp = serverIp;
m_AsyncConnect = ConnectState.Resolved; m_AsyncConnect = ConnectState.Resolved;
} }
else else
@ -385,7 +313,7 @@ namespace QuantumUNET
public void Connect(EndPoint secureTunnelEndPoint) public void Connect(EndPoint secureTunnelEndPoint)
{ {
//bool usePlatformSpecificProtocols = NetworkTransport.DoesEndPointUsePlatformProtocols(secureTunnelEndPoint); //bool usePlatformSpecificProtocols = NetworkTransport.DoesEndPointUsePlatformProtocols(secureTunnelEndPoint);
bool usePlatformSpecificProtocols = false; var usePlatformSpecificProtocols = false;
PrepareForConnect(usePlatformSpecificProtocols); PrepareForConnect(usePlatformSpecificProtocols);
if (LogFilter.logDebug) if (LogFilter.logDebug)
{ {
@ -409,11 +337,11 @@ namespace QuantumUNET
} }
else else
{ {
string fullName = secureTunnelEndPoint.GetType().FullName; var fullName = secureTunnelEndPoint.GetType().FullName;
if (fullName == "System.Net.IPEndPoint") if (fullName == "System.Net.IPEndPoint")
{ {
IPEndPoint ipendPoint = (IPEndPoint)secureTunnelEndPoint; var ipendPoint = (IPEndPoint)secureTunnelEndPoint;
this.Connect(ipendPoint.Address.ToString(), ipendPoint.Port); Connect(ipendPoint.Address.ToString(), ipendPoint.Port);
} }
else if (fullName != "UnityEngine.XboxOne.XboxOneEndPoint" && fullName != "UnityEngine.PS4.SceEndPoint" && fullName != "UnityEngine.PSVita.SceEndPoint") else if (fullName != "UnityEngine.XboxOne.XboxOneEndPoint" && fullName != "UnityEngine.PS4.SceEndPoint" && fullName != "UnityEngine.PSVita.SceEndPoint")
{ {
@ -430,7 +358,7 @@ namespace QuantumUNET
m_AsyncConnect = ConnectState.Connecting; m_AsyncConnect = ConnectState.Connecting;
try 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) catch (Exception arg)
{ {
@ -451,39 +379,36 @@ namespace QuantumUNET
} }
else else
{ {
m_Connection = (QSBNetworkConnection)Activator.CreateInstance(m_NetworkConnectionClass); m_Connection = (QSBNetworkConnection)Activator.CreateInstance(networkConnectionClass);
m_Connection.SetHandlers(m_MessageHandlers); 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() private void PrepareForConnect() => PrepareForConnect(false);
{
PrepareForConnect(false);
}
private void PrepareForConnect(bool usePlatformSpecificProtocols) private void PrepareForConnect(bool usePlatformSpecificProtocols)
{ {
SetActive(true); SetActive(true);
RegisterSystemHandlers(false); RegisterSystemHandlers(false);
if (m_HostTopology == null) if (hostTopology == null)
{ {
ConnectionConfig connectionConfig = new ConnectionConfig(); var connectionConfig = new ConnectionConfig();
connectionConfig.AddChannel(QosType.ReliableSequenced); connectionConfig.AddChannel(QosType.ReliableSequenced);
connectionConfig.AddChannel(QosType.Unreliable); connectionConfig.AddChannel(QosType.Unreliable);
connectionConfig.UsePlatformSpecificProtocols = usePlatformSpecificProtocols; connectionConfig.UsePlatformSpecificProtocols = usePlatformSpecificProtocols;
m_HostTopology = new HostTopology(connectionConfig, 8); hostTopology = new HostTopology(connectionConfig, 8);
} }
if (m_UseSimulator) if (m_UseSimulator)
{ {
int num = m_SimulatedLatency / 3 - 1; var num = (m_SimulatedLatency / 3) - 1;
if (num < 1) if (num < 1)
{ {
num = 1; num = 1;
} }
int num2 = m_SimulatedLatency * 3; var num2 = m_SimulatedLatency * 3;
ModConsole.OwmlConsole.WriteLine(string.Concat(new object[] ModConsole.OwmlConsole.WriteLine(string.Concat(new object[]
{ {
"AddHost Using Simulator ", "AddHost Using Simulator ",
@ -491,11 +416,11 @@ namespace QuantumUNET
"/", "/",
num2 num2
})); }));
m_ClientId = NetworkTransport.AddHostWithSimulator(m_HostTopology, num, num2, m_HostPort); hostId = NetworkTransport.AddHostWithSimulator(hostTopology, num, num2, m_HostPort);
} }
else else
{ {
m_ClientId = NetworkTransport.AddHost(m_HostTopology, m_HostPort); hostId = NetworkTransport.AddHost(hostTopology, m_HostPort);
} }
} }
@ -503,8 +428,8 @@ namespace QuantumUNET
{ {
try try
{ {
IPAddress[] array = Dns.EndGetHostAddresses(ar); var array = Dns.EndGetHostAddresses(ar);
QSBNetworkClient networkClient = (QSBNetworkClient)ar.AsyncState; var networkClient = (QSBNetworkClient)ar.AsyncState;
if (array.Length == 0) if (array.Length == 0)
{ {
Debug.LogError("DNS lookup failed for:" + networkClient.m_RequestedServerHost); Debug.LogError("DNS lookup failed for:" + networkClient.m_RequestedServerHost);
@ -512,22 +437,22 @@ namespace QuantumUNET
} }
else else
{ {
networkClient.m_ServerIp = array[0].ToString(); networkClient.serverIp = array[0].ToString();
networkClient.m_AsyncConnect = ConnectState.Resolved; networkClient.m_AsyncConnect = ConnectState.Resolved;
Debug.Log(string.Concat(new string[] Debug.Log(string.Concat(new string[]
{ {
"Async DNS Result:", "Async DNS Result:",
networkClient.m_ServerIp, networkClient.serverIp,
" for ", " for ",
networkClient.m_RequestedServerHost, networkClient.m_RequestedServerHost,
": ", ": ",
networkClient.m_ServerIp networkClient.serverIp
})); }));
} }
} }
catch (SocketException ex) catch (SocketException ex)
{ {
QSBNetworkClient networkClient2 = (QSBNetworkClient)ar.AsyncState; var networkClient2 = (QSBNetworkClient)ar.AsyncState;
Debug.LogError("DNS resolution failed: " + ex.GetErrorCode()); Debug.LogError("DNS resolution failed: " + ex.GetErrorCode());
Debug.LogError("Exception:" + ex); Debug.LogError("Exception:" + ex);
networkClient2.m_AsyncConnect = ConnectState.Failed; networkClient2.m_AsyncConnect = ConnectState.Failed;
@ -538,7 +463,7 @@ namespace QuantumUNET
{ {
if (m_UseSimulator) if (m_UseSimulator)
{ {
int num = m_SimulatedLatency / 3; var num = m_SimulatedLatency / 3;
if (num < 1) if (num < 1)
{ {
num = 1; num = 1;
@ -550,18 +475,16 @@ namespace QuantumUNET
"/", "/",
m_SimulatedLatency m_SimulatedLatency
})); }));
ConnectionSimulatorConfig conf = new ConnectionSimulatorConfig(num, m_SimulatedLatency, num, m_SimulatedLatency, m_PacketLoss); var conf = new ConnectionSimulatorConfig(num, m_SimulatedLatency, num, m_SimulatedLatency, m_PacketLoss);
byte b; m_ClientConnectionId = NetworkTransport.ConnectWithSimulator(hostId, serverIp, serverPort, 0, out var b, conf);
m_ClientConnectionId = NetworkTransport.ConnectWithSimulator(m_ClientId, m_ServerIp, m_ServerPort, 0, out b, conf);
} }
else else
{ {
byte b; m_ClientConnectionId = NetworkTransport.Connect(hostId, serverIp, serverPort, 0, out var b);
m_ClientConnectionId = NetworkTransport.Connect(m_ClientId, m_ServerIp, m_ServerPort, 0, out b);
} }
m_Connection = (QSBNetworkConnection)Activator.CreateInstance(m_NetworkConnectionClass); m_Connection = (QSBNetworkConnection)Activator.CreateInstance(networkConnectionClass);
m_Connection.SetHandlers(m_MessageHandlers); 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() public virtual void Disconnect()
@ -573,10 +496,10 @@ namespace QuantumUNET
m_Connection.Disconnect(); m_Connection.Disconnect();
m_Connection.Dispose(); m_Connection.Dispose();
m_Connection = null; m_Connection = null;
if (m_ClientId != -1) if (hostId != -1)
{ {
NetworkTransport.RemoveHost(m_ClientId); NetworkTransport.RemoveHost(hostId);
m_ClientId = -1; hostId = -1;
} }
} }
} }
@ -745,15 +668,15 @@ namespace QuantumUNET
{ {
if (LogFilter.logDebug) 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); NetworkTransport.RemoveHost(hostId);
m_ClientId = -1; hostId = -1;
} }
RemoveClient(this); RemoveClient(this);
if (s_Clients.Count == 0) if (allClients.Count == 0)
{ {
SetActive(false); SetActive(false);
} }
@ -761,7 +684,7 @@ namespace QuantumUNET
internal virtual void Update() internal virtual void Update()
{ {
if (m_ClientId != -1) if (hostId != -1)
{ {
switch (m_AsyncConnect) switch (m_AsyncConnect)
{ {
@ -788,14 +711,11 @@ namespace QuantumUNET
m_StatResetTime = (int)Time.time; m_StatResetTime = (int)Time.time;
} }
} }
int num = 0; var num = 0;
byte b; byte b;
for (; ; ) for (; ; )
{ {
int num2; var networkEventType = NetworkTransport.ReceiveFromHost(hostId, out var num2, out var channelId, m_MsgBuffer, (ushort)m_MsgBuffer.Length, out var numBytes, out b);
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);
if (m_Connection != null) if (m_Connection != null)
{ {
m_Connection.LastError = (NetworkError)b; m_Connection.LastError = (NetworkError)b;
@ -834,7 +754,7 @@ namespace QuantumUNET
{ {
if (b != 6) if (b != 6)
{ {
GenerateDisconnectError((int)b); GenerateDisconnectError(b);
} }
} }
QSBClientScene.HandleClientDisconnect(m_Connection); QSBClientScene.HandleClientDisconnect(m_Connection);
@ -858,7 +778,7 @@ namespace QuantumUNET
{ {
goto Block_17; goto Block_17;
} }
if (m_ClientId == -1) if (hostId == -1)
{ {
goto Block_19; goto Block_19;
} }
@ -868,10 +788,10 @@ namespace QuantumUNET
} }
} }
Block_10: Block_10:
GenerateConnectError((int)b); GenerateConnectError(b);
return; return;
Block_11: Block_11:
GenerateDataError((int)b); GenerateDataError(b);
return; return;
Block_17: Block_17:
if (LogFilter.logDebug) if (LogFilter.logDebug)
@ -916,19 +836,21 @@ namespace QuantumUNET
private void GenerateError(int error) private void GenerateError(int error)
{ {
QSBNetworkMessageDelegate handler = m_MessageHandlers.GetHandler(34); var handler = m_MessageHandlers.GetHandler(34);
if (handler == null) if (handler == null)
{ {
handler = m_MessageHandlers.GetHandler(34); handler = m_MessageHandlers.GetHandler(34);
} }
if (handler != null) if (handler != null)
{ {
QSBErrorMessage errorMessage = new QSBErrorMessage(); var errorMessage = new QSBErrorMessage
errorMessage.errorCode = error; {
byte[] buffer = new byte[200]; errorCode = error
QSBNetworkWriter writer = new QSBNetworkWriter(buffer); };
var buffer = new byte[200];
var writer = new QSBNetworkWriter(buffer);
errorMessage.Serialize(writer); errorMessage.Serialize(writer);
QSBNetworkReader reader = new QSBNetworkReader(buffer); var reader = new QSBNetworkReader(buffer);
handler(new QSBNetworkMessage handler(new QSBNetworkMessage
{ {
MsgType = 34, MsgType = 34,
@ -986,14 +908,13 @@ namespace QuantumUNET
public int GetRTT() public int GetRTT()
{ {
int result; int result;
if (m_ClientId == -1) if (hostId == -1)
{ {
result = 0; result = 0;
} }
else else
{ {
byte b; result = NetworkTransport.GetCurrentRTT(hostId, m_ClientConnectionId, out var b);
result = NetworkTransport.GetCurrentRTT(m_ClientId, m_ClientConnectionId, out b);
} }
return result; return result;
} }
@ -1001,7 +922,7 @@ namespace QuantumUNET
internal void RegisterSystemHandlers(bool localClient) internal void RegisterSystemHandlers(bool localClient)
{ {
QSBClientScene.RegisterSystemHandlers(this, localClient); QSBClientScene.RegisterSystemHandlers(this, localClient);
this.RegisterHandlerSafe(14, new QSBNetworkMessageDelegate(OnCRC)); RegisterHandlerSafe(14, new QSBNetworkMessageDelegate(OnCRC));
} }
private void OnCRC(QSBNetworkMessage netMsg) private void OnCRC(QSBNetworkMessage netMsg)
@ -1010,33 +931,24 @@ namespace QuantumUNET
QSBNetworkCRC.Validate(s_CRCMessage.scripts, numChannels); QSBNetworkCRC.Validate(s_CRCMessage.scripts, numChannels);
} }
public void RegisterHandler(short msgType, QSBNetworkMessageDelegate handler) public void RegisterHandler(short msgType, QSBNetworkMessageDelegate handler) => m_MessageHandlers.RegisterHandler(msgType, handler);
{
m_MessageHandlers.RegisterHandler(msgType, handler);
}
public void RegisterHandlerSafe(short msgType, QSBNetworkMessageDelegate handler) public void RegisterHandlerSafe(short msgType, QSBNetworkMessageDelegate handler) => m_MessageHandlers.RegisterHandlerSafe(msgType, handler);
{
m_MessageHandlers.RegisterHandlerSafe(msgType, handler);
}
public void UnregisterHandler(short msgType) public void UnregisterHandler(short msgType) => m_MessageHandlers.UnregisterHandler(msgType);
{
m_MessageHandlers.UnregisterHandler(msgType);
}
public static Dictionary<short, QSBNetworkConnection.PacketStat> GetTotalConnectionStats() public static Dictionary<short, QSBNetworkConnection.PacketStat> GetTotalConnectionStats()
{ {
Dictionary<short, QSBNetworkConnection.PacketStat> dictionary = new Dictionary<short, QSBNetworkConnection.PacketStat>(); var dictionary = new Dictionary<short, QSBNetworkConnection.PacketStat>();
for (int i = 0; i < s_Clients.Count; i++) for (var i = 0; i < allClients.Count; i++)
{ {
QSBNetworkClient networkClient = s_Clients[i]; var networkClient = allClients[i];
Dictionary<short, QSBNetworkConnection.PacketStat> connectionStats = networkClient.GetConnectionStats(); var connectionStats = networkClient.GetConnectionStats();
foreach (short key in connectionStats.Keys) foreach (var key in connectionStats.Keys)
{ {
if (dictionary.ContainsKey(key)) if (dictionary.ContainsKey(key))
{ {
QSBNetworkConnection.PacketStat packetStat = dictionary[key]; var packetStat = dictionary[key];
packetStat.count += connectionStats[key].count; packetStat.count += connectionStats[key].count;
packetStat.bytes += connectionStats[key].bytes; packetStat.bytes += connectionStats[key].bytes;
dictionary[key] = packetStat; dictionary[key] = packetStat;
@ -1050,61 +962,46 @@ namespace QuantumUNET
return dictionary; return dictionary;
} }
internal static void AddClient(QSBNetworkClient client) internal static void AddClient(QSBNetworkClient client) => allClients.Add(client);
{
s_Clients.Add(client);
}
internal static bool RemoveClient(QSBNetworkClient client) internal static bool RemoveClient(QSBNetworkClient client) => allClients.Remove(client);
{
return s_Clients.Remove(client);
}
internal static void UpdateClients() 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 else
{ {
s_Clients.RemoveAt(i); allClients.RemoveAt(i);
} }
} }
} }
public static void ShutdownAll() public static void ShutdownAll()
{ {
while (s_Clients.Count != 0) while (allClients.Count != 0)
{ {
s_Clients[0].Shutdown(); allClients[0].Shutdown();
} }
s_Clients = new List<QSBNetworkClient>(); allClients = new List<QSBNetworkClient>();
s_IsActive = false; active = false;
QSBClientScene.Shutdown(); QSBClientScene.Shutdown();
} }
internal static void SetActive(bool state) internal static void SetActive(bool state)
{ {
if (!s_IsActive && state) if (!active && state)
{ {
NetworkTransport.Init(); NetworkTransport.Init();
} }
s_IsActive = state; active = state;
} }
private Type m_NetworkConnectionClass = typeof(QSBNetworkConnection);
private const int k_MaxEventsPerFrame = 500; private const int k_MaxEventsPerFrame = 500;
private static List<QSBNetworkClient> s_Clients = new List<QSBNetworkClient>();
private static bool s_IsActive;
private HostTopology m_HostTopology;
private int m_HostPort; private int m_HostPort;
private bool m_UseSimulator; private bool m_UseSimulator;
@ -1112,13 +1009,6 @@ namespace QuantumUNET
private int m_SimulatedLatency; private int m_SimulatedLatency;
private float m_PacketLoss; 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_ClientConnectionId = -1;
private int m_StatResetTime; private int m_StatResetTime;

View File

@ -47,7 +47,7 @@ namespace QuantumUNET
var bufferSize = packetSize; var bufferSize = packetSize;
if (channelQOS.QOS == QosType.ReliableFragmented || channelQOS.QOS == QosType.UnreliableFragmented) 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)); m_Channels[i] = new QSBChannelBuffer(this, bufferSize, (byte)i, IsReliableQoS(channelQOS.QOS), IsSequencedQoS(channelQOS.QOS));
} }
@ -102,8 +102,7 @@ namespace QuantumUNET
QSBClientScene.HandleClientDisconnect(this); QSBClientScene.HandleClientDisconnect(this);
if (hostId != -1) if (hostId != -1)
{ {
byte b; NetworkTransport.Disconnect(hostId, connectionId, out var b);
NetworkTransport.Disconnect(hostId, connectionId, out b);
RemoveObservers(); RemoveObservers();
} }
} }
@ -182,18 +181,18 @@ namespace QuantumUNET
internal void SetPlayerController(QSBPlayerController player) internal void SetPlayerController(QSBPlayerController player)
{ {
while ((int)player.PlayerControllerId >= PlayerControllers.Count) while (player.PlayerControllerId >= PlayerControllers.Count)
{ {
PlayerControllers.Add(new QSBPlayerController()); PlayerControllers.Add(new QSBPlayerController());
} }
PlayerControllers[(int)player.PlayerControllerId] = player; PlayerControllers[player.PlayerControllerId] = player;
} }
internal void RemovePlayerController(short playerControllerId) internal void RemovePlayerController(short playerControllerId)
{ {
for (var i = PlayerControllers.Count; i >= 0; i--) 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(); PlayerControllers[i] = new QSBPlayerController();
return; return;
@ -263,15 +262,9 @@ namespace QuantumUNET
return SendWriter(m_Writer, channelId); return SendWriter(m_Writer, channelId);
} }
public virtual bool SendBytes(byte[] bytes, int numBytes, int channelId) public virtual bool SendBytes(byte[] bytes, int numBytes, int channelId) => CheckChannel(channelId) && m_Channels[channelId].SendBytes(bytes, numBytes);
{
return CheckChannel(channelId) && m_Channels[channelId].SendBytes(bytes, numBytes);
}
public virtual bool SendWriter(QSBNetworkWriter writer, int channelId) public virtual bool SendWriter(QSBNetworkWriter writer, int channelId) => CheckChannel(channelId) && m_Channels[channelId].SendWriter(writer);
{
return CheckChannel(channelId) && m_Channels[channelId].SendWriter(writer);
}
private void LogSend(byte[] bytes) private void LogSend(byte[] bytes)
{ {
@ -279,7 +272,7 @@ namespace QuantumUNET
var num = networkReader.ReadUInt16(); var num = networkReader.ReadUInt16();
var num2 = networkReader.ReadUInt16(); var num2 = networkReader.ReadUInt16();
var stringBuilder = new StringBuilder(); 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]); stringBuilder.AppendFormat("{0:X2}", bytes[i]);
if (i > 150) if (i > 150)
@ -348,7 +341,7 @@ namespace QuantumUNET
{ {
var num = reader.ReadUInt16(); var num = reader.ReadUInt16();
var num2 = reader.ReadInt16(); var num2 = reader.ReadInt16();
var array = reader.ReadBytes((int)num); var array = reader.ReadBytes(num);
var reader2 = new QSBNetworkReader(array); var reader2 = new QSBNetworkReader(array);
QSBNetworkMessageDelegate networkMessageDelegate = null; QSBNetworkMessageDelegate networkMessageDelegate = null;
if (m_MessageHandlersDict.ContainsKey(num2)) if (m_MessageHandlersDict.ContainsKey(num2))

View File

@ -7,21 +7,13 @@ namespace QuantumUNET
{ {
internal class QSBNetworkScene internal class QSBNetworkScene
{ {
private Dictionary<NetworkInstanceId, QSBNetworkIdentity> m_LocalObjects = new Dictionary<NetworkInstanceId, QSBNetworkIdentity>();
internal static Dictionary<NetworkHash128, GameObject> guidToPrefab { get; } = new Dictionary<NetworkHash128, GameObject>(); internal static Dictionary<NetworkHash128, GameObject> guidToPrefab { get; } = new Dictionary<NetworkHash128, GameObject>();
internal static Dictionary<NetworkHash128, SpawnDelegate> spawnHandlers { get; } = new Dictionary<NetworkHash128, SpawnDelegate>(); internal static Dictionary<NetworkHash128, SpawnDelegate> spawnHandlers { get; } = new Dictionary<NetworkHash128, SpawnDelegate>();
internal static Dictionary<NetworkHash128, UnSpawnDelegate> unspawnHandlers { get; } = new Dictionary<NetworkHash128, UnSpawnDelegate>(); internal static Dictionary<NetworkHash128, UnSpawnDelegate> unspawnHandlers { get; } = new Dictionary<NetworkHash128, UnSpawnDelegate>();
internal Dictionary<NetworkInstanceId, QSBNetworkIdentity> localObjects internal Dictionary<NetworkInstanceId, QSBNetworkIdentity> localObjects { get; } = new Dictionary<NetworkInstanceId, QSBNetworkIdentity>();
{
get
{
return m_LocalObjects;
}
}
internal void Shutdown() internal void Shutdown()
{ {
@ -80,10 +72,7 @@ namespace QuantumUNET
return result; return result;
} }
internal bool RemoveLocalObject(NetworkInstanceId netId) internal bool RemoveLocalObject(NetworkInstanceId netId) => localObjects.Remove(netId);
{
return localObjects.Remove(netId);
}
internal bool RemoveLocalObjectAndDestroy(NetworkInstanceId netId) internal bool RemoveLocalObjectAndDestroy(NetworkInstanceId netId)
{ {
@ -91,7 +80,7 @@ namespace QuantumUNET
if (localObjects.ContainsKey(netId)) if (localObjects.ContainsKey(netId))
{ {
var networkIdentity = localObjects[netId]; var networkIdentity = localObjects[netId];
UnityEngine.Object.Destroy(networkIdentity.gameObject); Object.Destroy(networkIdentity.gameObject);
result = localObjects.Remove(netId); result = localObjects.Remove(netId);
} }
else else
@ -101,10 +90,7 @@ namespace QuantumUNET
return result; return result;
} }
internal void ClearLocalObjects() internal void ClearLocalObjects() => localObjects.Clear();
{
localObjects.Clear();
}
internal static void RegisterPrefab(GameObject prefab, NetworkHash128 newAssetId) internal static void RegisterPrefab(GameObject prefab, NetworkHash128 newAssetId)
{ {
@ -273,7 +259,7 @@ namespace QuantumUNET
{ {
if (networkIdentity.SceneId.IsEmpty()) if (networkIdentity.SceneId.IsEmpty())
{ {
UnityEngine.Object.Destroy(networkIdentity.gameObject); Object.Destroy(networkIdentity.gameObject);
} }
else else
{ {

View File

@ -21,61 +21,19 @@ namespace QuantumUNET
m_SimpleServerSimple = new ServerSimpleWrapper(this); m_SimpleServerSimple = new ServerSimpleWrapper(this);
} }
public static List<QSBNetworkConnection> localConnections public static List<QSBNetworkConnection> localConnections => instance.m_LocalConnectionsFakeList;
{
get
{
return instance.m_LocalConnectionsFakeList;
}
}
public static int listenPort public static int listenPort => instance.m_SimpleServerSimple.listenPort;
{
get
{
return instance.m_SimpleServerSimple.listenPort;
}
}
public static int serverHostId public static int serverHostId => instance.m_SimpleServerSimple.serverHostId;
{
get
{
return instance.m_SimpleServerSimple.serverHostId;
}
}
public static ReadOnlyCollection<QSBNetworkConnection> connections public static ReadOnlyCollection<QSBNetworkConnection> connections => instance.m_SimpleServerSimple.connections;
{
get
{
return instance.m_SimpleServerSimple.connections;
}
}
public static Dictionary<short, QSBNetworkMessageDelegate> handlers public static Dictionary<short, QSBNetworkMessageDelegate> handlers => instance.m_SimpleServerSimple.handlers;
{
get
{
return instance.m_SimpleServerSimple.handlers;
}
}
public static HostTopology hostTopology public static HostTopology hostTopology => instance.m_SimpleServerSimple.hostTopology;
{
get
{
return instance.m_SimpleServerSimple.hostTopology;
}
}
public static Dictionary<NetworkInstanceId, QSBNetworkIdentity> objects public static Dictionary<NetworkInstanceId, QSBNetworkIdentity> objects => instance.m_NetworkScene.localObjects;
{
get
{
return instance.m_NetworkScene.localObjects;
}
}
public static bool dontListen { get; set; } public static bool dontListen { get; set; }
@ -112,21 +70,9 @@ namespace QuantumUNET
public static bool active { get; private set; } public static bool active { get; private set; }
public static bool localClientActive public static bool localClientActive => instance.m_LocalClientActive;
{
get
{
return instance.m_LocalClientActive;
}
}
public static int numChannels public static int numChannels => instance.m_SimpleServerSimple.hostTopology.DefaultConfig.ChannelCount;
{
get
{
return instance.m_SimpleServerSimple.hostTopology.DefaultConfig.ChannelCount;
}
}
public static float maxDelay public static float maxDelay
{ {
@ -140,28 +86,13 @@ namespace QuantumUNET
} }
} }
public static Type networkConnectionClass public static Type networkConnectionClass => instance.m_SimpleServerSimple.networkConnectionClass;
{
get
{
return instance.m_SimpleServerSimple.networkConnectionClass;
}
}
public static void SetNetworkConnectionClass<T>() where T : QSBNetworkConnection public static void SetNetworkConnectionClass<T>() where T : QSBNetworkConnection => instance.m_SimpleServerSimple.SetNetworkConnectionClass<T>();
{
instance.m_SimpleServerSimple.SetNetworkConnectionClass<T>();
}
public static bool Configure(ConnectionConfig config, int maxConnections) public static bool Configure(ConnectionConfig config, int maxConnections) => instance.m_SimpleServerSimple.Configure(config, maxConnections);
{
return instance.m_SimpleServerSimple.Configure(config, maxConnections);
}
public static bool Configure(HostTopology topology) public static bool Configure(HostTopology topology) => instance.m_SimpleServerSimple.Configure(topology);
{
return instance.m_SimpleServerSimple.Configure(topology);
}
public static void Reset() public static void Reset()
{ {
@ -200,10 +131,7 @@ namespace QuantumUNET
maxPacketSize = hostTopology.DefaultConfig.PacketSize; maxPacketSize = hostTopology.DefaultConfig.PacketSize;
} }
public static void ListenRelay(string relayIp, int relayPort, NetworkID netGuid, SourceID sourceId, NodeID nodeId) public static void ListenRelay(string relayIp, int relayPort, NetworkID netGuid, SourceID sourceId, NodeID nodeId) => instance.InternalListenRelay(relayIp, relayPort, netGuid, sourceId, nodeId);
{
instance.InternalListenRelay(relayIp, relayPort, netGuid, sourceId, nodeId);
}
private void InternalListenRelay(string relayIp, int relayPort, NetworkID netGuid, SourceID sourceId, NodeID nodeId) private void InternalListenRelay(string relayIp, int relayPort, NetworkID netGuid, SourceID sourceId, NodeID nodeId)
{ {
@ -212,15 +140,9 @@ namespace QuantumUNET
RegisterMessageHandlers(); RegisterMessageHandlers();
} }
public static bool Listen(int serverPort) public static bool Listen(int serverPort) => instance.InternalListen(null, serverPort);
{
return instance.InternalListen(null, serverPort);
}
public static bool Listen(string ipAddress, int serverPort) public static bool Listen(string ipAddress, int serverPort) => instance.InternalListen(ipAddress, serverPort);
{
return instance.InternalListen(ipAddress, serverPort);
}
internal bool InternalListen(string ipAddress, int serverPort) internal bool InternalListen(string ipAddress, int serverPort)
{ {
@ -585,10 +507,7 @@ namespace QuantumUNET
return result; return result;
} }
public static void DisconnectAll() public static void DisconnectAll() => instance.InternalDisconnectAll();
{
instance.InternalDisconnectAll();
}
internal void InternalDisconnectAll() internal void InternalDisconnectAll()
{ {
@ -690,10 +609,7 @@ namespace QuantumUNET
conn.Dispose(); conn.Dispose();
} }
private void OnData(QSBNetworkConnection conn, int receivedSize, int channelId) private void OnData(QSBNetworkConnection conn, int receivedSize, int channelId) => conn.TransportReceive(m_SimpleServerSimple.messageBuffer, receivedSize, channelId);
{
conn.TransportReceive(m_SimpleServerSimple.messageBuffer, receivedSize, channelId);
}
private void GenerateConnectError(int error) private void GenerateConnectError(int error)
{ {
@ -734,8 +650,10 @@ namespace QuantumUNET
{ {
if (handlers.ContainsKey(34)) if (handlers.ContainsKey(34))
{ {
var errorMessage = new QSBErrorMessage(); var errorMessage = new QSBErrorMessage
errorMessage.errorCode = error; {
errorCode = error
};
var writer = new QSBNetworkWriter(); var writer = new QSBNetworkWriter();
errorMessage.Serialize(writer); errorMessage.Serialize(writer);
var reader = new QSBNetworkReader(writer); var reader = new QSBNetworkReader(writer);
@ -743,25 +661,13 @@ namespace QuantumUNET
} }
} }
public static void RegisterHandler(short msgType, QSBNetworkMessageDelegate handler) public static void RegisterHandler(short msgType, QSBNetworkMessageDelegate handler) => instance.m_SimpleServerSimple.RegisterHandler(msgType, handler);
{
instance.m_SimpleServerSimple.RegisterHandler(msgType, handler);
}
public static void UnregisterHandler(short msgType) public static void UnregisterHandler(short msgType) => instance.m_SimpleServerSimple.UnregisterHandler(msgType);
{
instance.m_SimpleServerSimple.UnregisterHandler(msgType);
}
public static void ClearHandlers() public static void ClearHandlers() => instance.m_SimpleServerSimple.ClearHandlers();
{
instance.m_SimpleServerSimple.ClearHandlers();
}
public static void ClearSpawners() public static void ClearSpawners() => QSBNetworkScene.ClearSpawners();
{
QSBNetworkScene.ClearSpawners();
}
public static void GetStatsOut(out int numMsgs, out int numBufferedMsgs, out int numBytes, out int lastBufferedPerSecond) 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]; var networkConnection = connections[i];
if (networkConnection != null) if (networkConnection != null)
{ {
int num; networkConnection.GetStatsOut(out var num, out var num2, out var num3, out var num4);
int num2;
int num3;
int num4;
networkConnection.GetStatsOut(out num, out num2, out num3, out num4);
numMsgs += num; numMsgs += num;
numBufferedMsgs += num2; numBufferedMsgs += num2;
numBytes += num3; numBytes += num3;
@ -796,9 +698,7 @@ namespace QuantumUNET
var networkConnection = connections[i]; var networkConnection = connections[i];
if (networkConnection != null) if (networkConnection != null)
{ {
int num; networkConnection.GetStatsIn(out var num, out var num2);
int num2;
networkConnection.GetStatsIn(out num, out num2);
numMsgs += num; numMsgs += num;
numBytes += num2; numBytes += num2;
} }
@ -846,16 +746,12 @@ namespace QuantumUNET
} }
} }
public static bool AddPlayerForConnection(QSBNetworkConnection conn, GameObject player, short playerControllerId) public static bool AddPlayerForConnection(QSBNetworkConnection conn, GameObject player, short playerControllerId) => instance.InternalAddPlayerForConnection(conn, player, playerControllerId);
{
return instance.InternalAddPlayerForConnection(conn, player, playerControllerId);
}
internal bool InternalAddPlayerForConnection(QSBNetworkConnection conn, GameObject playerGameObject, short playerControllerId) internal bool InternalAddPlayerForConnection(QSBNetworkConnection conn, GameObject playerGameObject, short playerControllerId)
{ {
QSBNetworkIdentity networkIdentity;
bool result; bool result;
if (!GetNetworkIdentity(playerGameObject, out networkIdentity)) if (!GetNetworkIdentity(playerGameObject, out var networkIdentity))
{ {
if (LogFilter.logError) if (LogFilter.logError)
{ {
@ -872,9 +768,8 @@ namespace QuantumUNET
} }
else else
{ {
QSBPlayerController playerController = null;
GameObject x = null; GameObject x = null;
if (conn.GetPlayerController(playerControllerId, out playerController)) if (conn.GetPlayerController(playerControllerId, out var playerController))
{ {
x = playerController.Gameobject; x = playerController.Gameobject;
} }
@ -963,9 +858,8 @@ namespace QuantumUNET
private bool SetupLocalPlayerForConnection(QSBNetworkConnection conn, QSBNetworkIdentity uv, QSBPlayerController newPlayerController) private bool SetupLocalPlayerForConnection(QSBNetworkConnection conn, QSBNetworkIdentity uv, QSBPlayerController newPlayerController)
{ {
Debug.Log("NetworkServer SetupLocalPlayerForConnection netID:" + uv.NetId); Debug.Log("NetworkServer SetupLocalPlayerForConnection netID:" + uv.NetId);
var ulocalConnectionToClient = conn as QSBULocalConnectionToClient;
bool result; bool result;
if (ulocalConnectionToClient != null) if (conn is QSBULocalConnectionToClient ulocalConnectionToClient)
{ {
Debug.Log("NetworkServer AddPlayer handling ULocalConnectionToClient"); Debug.Log("NetworkServer AddPlayer handling ULocalConnectionToClient");
if (uv.NetId.IsEmpty()) if (uv.NetId.IsEmpty())
@ -1002,9 +896,8 @@ namespace QuantumUNET
internal bool InternalReplacePlayerForConnection(QSBNetworkConnection conn, GameObject playerGameObject, short playerControllerId) internal bool InternalReplacePlayerForConnection(QSBNetworkConnection conn, GameObject playerGameObject, short playerControllerId)
{ {
QSBNetworkIdentity networkIdentity;
bool result; bool result;
if (!GetNetworkIdentity(playerGameObject, out networkIdentity)) if (!GetNetworkIdentity(playerGameObject, out var networkIdentity))
{ {
if (LogFilter.logError) if (LogFilter.logError)
{ {
@ -1019,8 +912,7 @@ namespace QuantumUNET
else else
{ {
Debug.Log("NetworkServer ReplacePlayer"); Debug.Log("NetworkServer ReplacePlayer");
QSBPlayerController playerController; if (conn.GetPlayerController(playerControllerId, out var playerController))
if (conn.GetPlayerController(playerControllerId, out playerController))
{ {
playerController.UnetView.SetNotLocalPlayer(); playerController.UnetView.SetNotLocalPlayer();
playerController.UnetView.ClearClientOwner(); playerController.UnetView.ClearClientOwner();
@ -1072,10 +964,7 @@ namespace QuantumUNET
return result; return result;
} }
public static void SetClientReady(QSBNetworkConnection conn) public static void SetClientReady(QSBNetworkConnection conn) => instance.SetClientReadyInternal(conn);
{
instance.SetClientReadyInternal(conn);
}
internal void SetClientReadyInternal(QSBNetworkConnection conn) internal void SetClientReadyInternal(QSBNetworkConnection conn)
{ {
@ -1100,15 +989,14 @@ namespace QuantumUNET
} }
} }
conn.isReady = true; conn.isReady = true;
var ulocalConnectionToClient = conn as QSBULocalConnectionToClient; if (conn is QSBULocalConnectionToClient ulocalConnectionToClient)
if (ulocalConnectionToClient != null)
{ {
Debug.Log("NetworkServer Ready handling ULocalConnectionToClient"); Debug.Log("NetworkServer Ready handling ULocalConnectionToClient");
foreach (var networkIdentity in objects.Values) foreach (var networkIdentity in objects.Values)
{ {
if (networkIdentity != null && networkIdentity.gameObject != null) if (networkIdentity != null && networkIdentity.gameObject != null)
{ {
bool flag = networkIdentity.OnCheckObserver(conn); var flag = networkIdentity.OnCheckObserver(conn);
if (flag) if (flag)
{ {
networkIdentity.AddObserver(conn); networkIdentity.AddObserver(conn);
@ -1133,8 +1021,10 @@ namespace QuantumUNET
conn.connectionId conn.connectionId
})); }));
} }
var objectSpawnFinishedMessage = new QSBObjectSpawnFinishedMessage(); var objectSpawnFinishedMessage = new QSBObjectSpawnFinishedMessage
objectSpawnFinishedMessage.State = 0U; {
State = 0U
};
conn.Send(12, objectSpawnFinishedMessage); conn.Send(12, objectSpawnFinishedMessage);
foreach (var networkIdentity2 in objects.Values) foreach (var networkIdentity2 in objects.Values)
{ {
@ -1157,7 +1047,7 @@ namespace QuantumUNET
networkIdentity2.NetId networkIdentity2.NetId
})); }));
} }
bool flag2 = networkIdentity2.OnCheckObserver(conn); var flag2 = networkIdentity2.OnCheckObserver(conn);
if (flag2) if (flag2)
{ {
networkIdentity2.AddObserver(conn); networkIdentity2.AddObserver(conn);
@ -1198,10 +1088,7 @@ namespace QuantumUNET
} }
} }
public static void SetClientNotReady(QSBNetworkConnection conn) public static void SetClientNotReady(QSBNetworkConnection conn) => instance.InternalSetClientNotReady(conn);
{
instance.InternalSetClientNotReady(conn);
}
internal void InternalSetClientNotReady(QSBNetworkConnection conn) internal void InternalSetClientNotReady(QSBNetworkConnection conn)
{ {
@ -1230,8 +1117,7 @@ namespace QuantumUNET
private static void OnRemovePlayerMessage(QSBNetworkMessage netMsg) private static void OnRemovePlayerMessage(QSBNetworkMessage netMsg)
{ {
netMsg.ReadMessage<QSBRemovePlayerMessage>(s_RemovePlayerMessage); netMsg.ReadMessage<QSBRemovePlayerMessage>(s_RemovePlayerMessage);
QSBPlayerController playerController = null; netMsg.Connection.GetPlayerController(s_RemovePlayerMessage.PlayerControllerId, out var playerController);
netMsg.Connection.GetPlayerController(s_RemovePlayerMessage.PlayerControllerId, out playerController);
if (playerController != null) if (playerController != null)
{ {
netMsg.Connection.RemovePlayerController(s_RemovePlayerMessage.PlayerControllerId); netMsg.Connection.RemovePlayerController(s_RemovePlayerMessage.PlayerControllerId);
@ -1302,12 +1188,11 @@ namespace QuantumUNET
internal void SpawnObject(GameObject obj) internal void SpawnObject(GameObject obj)
{ {
QSBNetworkIdentity networkIdentity;
if (!active) if (!active)
{ {
ModConsole.OwmlConsole.WriteLine("Error - SpawnObject for " + obj + ", NetworkServer is not active. Cannot spawn objects without an active server."); 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[] Debug.LogError(string.Concat(new object[]
{ {
@ -1331,11 +1216,13 @@ namespace QuantumUNET
{ {
if (uv.SceneId.IsEmpty()) if (uv.SceneId.IsEmpty())
{ {
var objectSpawnMessage = new QSBObjectSpawnMessage(); var objectSpawnMessage = new QSBObjectSpawnMessage
objectSpawnMessage.NetId = uv.NetId; {
objectSpawnMessage.assetId = uv.AssetId; NetId = uv.NetId,
objectSpawnMessage.Position = uv.transform.position; assetId = uv.AssetId,
objectSpawnMessage.Rotation = uv.transform.rotation; Position = uv.transform.position,
Rotation = uv.transform.rotation
};
var networkWriter = new QSBNetworkWriter(); var networkWriter = new QSBNetworkWriter();
uv.UNetSerializeAllVars(networkWriter); uv.UNetSerializeAllVars(networkWriter);
if (networkWriter.Position > 0) if (networkWriter.Position > 0)
@ -1353,10 +1240,12 @@ namespace QuantumUNET
} }
else else
{ {
var objectSpawnSceneMessage = new QSBObjectSpawnSceneMessage(); var objectSpawnSceneMessage = new QSBObjectSpawnSceneMessage
objectSpawnSceneMessage.NetId = uv.NetId; {
objectSpawnSceneMessage.SceneId = uv.SceneId; NetId = uv.NetId,
objectSpawnSceneMessage.Position = uv.transform.position; SceneId = uv.SceneId,
Position = uv.transform.position
};
var networkWriter2 = new QSBNetworkWriter(); var networkWriter2 = new QSBNetworkWriter();
uv.UNetSerializeAllVars(networkWriter2); uv.UNetSerializeAllVars(networkWriter2);
if (networkWriter2.Position > 0) if (networkWriter2.Position > 0)
@ -1416,30 +1305,25 @@ namespace QuantumUNET
private static void UnSpawnObject(GameObject obj) private static void UnSpawnObject(GameObject obj)
{ {
QSBNetworkIdentity uv;
if (obj == null) if (obj == null)
{ {
Debug.Log("NetworkServer UnspawnObject is null"); Debug.Log("NetworkServer UnspawnObject is null");
} }
else if (GetNetworkIdentity(obj, out uv)) else if (GetNetworkIdentity(obj, out var uv))
{ {
UnSpawnObject(uv); UnSpawnObject(uv);
} }
} }
private static void UnSpawnObject(QSBNetworkIdentity uv) private static void UnSpawnObject(QSBNetworkIdentity uv) => DestroyObject(uv, false);
{
DestroyObject(uv, false);
}
private static void DestroyObject(GameObject obj) private static void DestroyObject(GameObject obj)
{ {
QSBNetworkIdentity uv;
if (obj == null) if (obj == null)
{ {
Debug.Log("NetworkServer DestroyObject is null"); Debug.Log("NetworkServer DestroyObject is null");
} }
else if (GetNetworkIdentity(obj, out uv)) else if (GetNetworkIdentity(obj, out var uv))
{ {
DestroyObject(uv, true); DestroyObject(uv, true);
} }
@ -1459,8 +1343,10 @@ namespace QuantumUNET
{ {
uv.ClientAuthorityOwner.RemoveOwnedObject(uv); uv.ClientAuthorityOwner.RemoveOwnedObject(uv);
} }
var objectDestroyMessage = new QSBObjectDestroyMessage(); var objectDestroyMessage = new QSBObjectDestroyMessage
objectDestroyMessage.NetId = uv.NetId; {
NetId = uv.NetId
};
SendToObservers(uv.gameObject, 1, objectDestroyMessage); SendToObservers(uv.gameObject, 1, objectDestroyMessage);
uv.ClearObservers(); uv.ClearObservers();
if (QSBNetworkClient.active && instance.m_LocalClientActive) if (QSBNetworkClient.active && instance.m_LocalClientActive)
@ -1475,10 +1361,7 @@ namespace QuantumUNET
uv.MarkForReset(); uv.MarkForReset();
} }
public static void ClearLocalObjects() public static void ClearLocalObjects() => objects.Clear();
{
objects.Clear();
}
public static void Spawn(GameObject obj) public static void Spawn(GameObject obj)
{ {
@ -1488,10 +1371,7 @@ namespace QuantumUNET
} }
} }
private static bool CheckForPrefab(GameObject obj) private static bool CheckForPrefab(GameObject obj) => false;
{
return false;
}
private static bool VerifyCanSpawn(GameObject obj) private static bool VerifyCanSpawn(GameObject obj)
{ {
@ -1560,8 +1440,7 @@ namespace QuantumUNET
{ {
if (VerifyCanSpawn(obj)) if (VerifyCanSpawn(obj))
{ {
QSBNetworkIdentity networkIdentity; if (GetNetworkIdentity(obj, out var networkIdentity))
if (GetNetworkIdentity(obj, out networkIdentity))
{ {
networkIdentity.SetDynamicAssetId(assetId); networkIdentity.SetDynamicAssetId(assetId);
} }
@ -1569,15 +1448,9 @@ namespace QuantumUNET
} }
} }
public static void Destroy(GameObject obj) public static void Destroy(GameObject obj) => DestroyObject(obj);
{
DestroyObject(obj);
}
public static void UnSpawn(GameObject obj) public static void UnSpawn(GameObject obj) => UnSpawnObject(obj);
{
UnSpawnObject(obj);
}
internal bool InvokeBytes(QSBULocalConnectionToServer conn, byte[] buffer, int numBytes, int channelId) internal bool InvokeBytes(QSBULocalConnectionToServer conn, byte[] buffer, int numBytes, int channelId)
{ {
@ -1625,15 +1498,9 @@ namespace QuantumUNET
return result; return result;
} }
public static GameObject FindLocalObject(NetworkInstanceId netId) public static GameObject FindLocalObject(NetworkInstanceId netId) => instance.m_NetworkScene.FindLocalObject(netId);
{
return instance.m_NetworkScene.FindLocalObject(netId);
}
private static bool ValidateSceneObject(QSBNetworkIdentity netId) private static bool ValidateSceneObject(QSBNetworkIdentity netId) => netId.gameObject.hideFlags != HideFlags.NotEditable && netId.gameObject.hideFlags != HideFlags.HideAndDontSave && !netId.SceneId.IsEmpty();
{
return netId.gameObject.hideFlags != HideFlags.NotEditable && netId.gameObject.hideFlags != HideFlags.HideAndDontSave && !netId.SceneId.IsEmpty();
}
public static bool SpawnObjects() public static bool SpawnObjects()
{ {
@ -1684,7 +1551,7 @@ namespace QuantumUNET
{ {
var crcmessage = new QSBCRCMessage(); var crcmessage = new QSBCRCMessage();
var list = new List<QSBCRCMessageEntry>(); var list = new List<QSBCRCMessageEntry>();
foreach (string text in QSBNetworkCRC.singleton.scripts.Keys) foreach (var text in QSBNetworkCRC.singleton.scripts.Keys)
{ {
list.Add(new QSBCRCMessageEntry list.Add(new QSBCRCMessageEntry
{ {
@ -1733,35 +1600,17 @@ namespace QuantumUNET
m_Server = server; m_Server = server;
} }
public override void OnConnectError(int connectionId, byte error) public override void OnConnectError(int connectionId, byte error) => m_Server.GenerateConnectError(error);
{
m_Server.GenerateConnectError((int)error);
}
public override void OnDataError(QSBNetworkConnection conn, byte error) public override void OnDataError(QSBNetworkConnection conn, byte error) => m_Server.GenerateDataError(conn, error);
{
m_Server.GenerateDataError(conn, (int)error);
}
public override void OnDisconnectError(QSBNetworkConnection conn, byte error) public override void OnDisconnectError(QSBNetworkConnection conn, byte error) => m_Server.GenerateDisconnectError(conn, error);
{
m_Server.GenerateDisconnectError(conn, (int)error);
}
public override void OnConnected(QSBNetworkConnection conn) public override void OnConnected(QSBNetworkConnection conn) => m_Server.OnConnected(conn);
{
m_Server.OnConnected(conn);
}
public override void OnDisconnected(QSBNetworkConnection conn) public override void OnDisconnected(QSBNetworkConnection conn) => m_Server.OnDisconnected(conn);
{
m_Server.OnDisconnected(conn);
}
public override void OnData(QSBNetworkConnection conn, int receivedSize, int channelId) public override void OnData(QSBNetworkConnection conn, int receivedSize, int channelId) => m_Server.OnData(conn, receivedSize, channelId);
{
m_Server.OnData(conn, receivedSize, channelId);
}
private QSBNetworkServer m_Server; private QSBNetworkServer m_Server;
} }

View File

@ -12,112 +12,43 @@ namespace QuantumUNET
{ {
public QSBNetworkServerSimple() public QSBNetworkServerSimple()
{ {
this.m_ConnectionsReadOnly = new ReadOnlyCollection<QSBNetworkConnection>(this.m_Connections); connections = new ReadOnlyCollection<QSBNetworkConnection>(m_Connections);
} }
public int listenPort public int listenPort { get; set; }
{
get
{
return this.m_ListenPort;
}
set
{
this.m_ListenPort = value;
}
}
public int serverHostId public int serverHostId { get; set; } = -1;
{
get
{
return this.m_ServerHostId;
}
set
{
this.m_ServerHostId = value;
}
}
public HostTopology hostTopology public HostTopology hostTopology { get; private set; }
{
get
{
return this.m_HostTopology;
}
}
public bool useWebSockets public bool useWebSockets { get; set; }
{
get
{
return this.m_UseWebSockets;
}
set
{
this.m_UseWebSockets = value;
}
}
public ReadOnlyCollection<QSBNetworkConnection> connections public ReadOnlyCollection<QSBNetworkConnection> connections { get; }
{
get
{
return this.m_ConnectionsReadOnly;
}
}
public Dictionary<short, QSBNetworkMessageDelegate> handlers public Dictionary<short, QSBNetworkMessageDelegate> handlers => m_MessageHandlers.GetHandlers();
{
get
{
return this.m_MessageHandlers.GetHandlers();
}
}
public byte[] messageBuffer public byte[] messageBuffer { get; private set; } = null;
{
get
{
return this.m_MsgBuffer;
}
}
public NetworkReader messageReader public NetworkReader messageReader { get; private set; } = null;
{
get
{
return this.m_MsgReader;
}
}
public Type networkConnectionClass public Type networkConnectionClass { get; private set; } = typeof(QSBNetworkConnection);
{
get
{
return this.m_NetworkConnectionClass;
}
}
public void SetNetworkConnectionClass<T>() where T : QSBNetworkConnection public void SetNetworkConnectionClass<T>() where T : QSBNetworkConnection => networkConnectionClass = typeof(T);
{
this.m_NetworkConnectionClass = typeof(T);
}
public virtual void Initialize() public virtual void Initialize()
{ {
if (!this.m_Initialized) if (!m_Initialized)
{ {
this.m_Initialized = true; m_Initialized = true;
NetworkTransport.Init(); NetworkTransport.Init();
this.m_MsgBuffer = new byte[65535]; messageBuffer = new byte[65535];
this.m_MsgReader = new NetworkReader(this.m_MsgBuffer); messageReader = new NetworkReader(messageBuffer);
if (this.m_HostTopology == null) if (hostTopology == null)
{ {
ConnectionConfig connectionConfig = new ConnectionConfig(); var connectionConfig = new ConnectionConfig();
connectionConfig.AddChannel(QosType.ReliableSequenced); connectionConfig.AddChannel(QosType.ReliableSequenced);
connectionConfig.AddChannel(QosType.Unreliable); connectionConfig.AddChannel(QosType.Unreliable);
this.m_HostTopology = new HostTopology(connectionConfig, 8); hostTopology = new HostTopology(connectionConfig, 8);
} }
if (LogFilter.logDebug) if (LogFilter.logDebug)
{ {
@ -128,30 +59,30 @@ namespace QuantumUNET
public bool Configure(ConnectionConfig config, int maxConnections) public bool Configure(ConnectionConfig config, int maxConnections)
{ {
HostTopology topology = new HostTopology(config, maxConnections); var topology = new HostTopology(config, maxConnections);
return this.Configure(topology); return Configure(topology);
} }
public bool Configure(HostTopology topology) public bool Configure(HostTopology topology)
{ {
this.m_HostTopology = topology; hostTopology = topology;
return true; return true;
} }
public bool Listen(string ipAddress, int serverListenPort) public bool Listen(string ipAddress, int serverListenPort)
{ {
this.Initialize(); Initialize();
this.m_ListenPort = serverListenPort; listenPort = serverListenPort;
if (this.m_UseWebSockets) if (useWebSockets)
{ {
this.m_ServerHostId = NetworkTransport.AddWebsocketHost(this.m_HostTopology, serverListenPort, ipAddress); serverHostId = NetworkTransport.AddWebsocketHost(hostTopology, serverListenPort, ipAddress);
} }
else else
{ {
this.m_ServerHostId = NetworkTransport.AddHost(this.m_HostTopology, serverListenPort, ipAddress); serverHostId = NetworkTransport.AddHost(hostTopology, serverListenPort, ipAddress);
} }
bool result; bool result;
if (this.m_ServerHostId == -1) if (serverHostId == -1)
{ {
result = false; result = false;
} }
@ -164,7 +95,7 @@ namespace QuantumUNET
"NetworkServerSimple listen: ", "NetworkServerSimple listen: ",
ipAddress, ipAddress,
":", ":",
this.m_ListenPort listenPort
})); }));
} }
result = true; result = true;
@ -172,26 +103,23 @@ namespace QuantumUNET
return result; return result;
} }
public bool Listen(int serverListenPort) public bool Listen(int serverListenPort) => Listen(serverListenPort, hostTopology);
{
return this.Listen(serverListenPort, this.m_HostTopology);
}
public bool Listen(int serverListenPort, HostTopology topology) public bool Listen(int serverListenPort, HostTopology topology)
{ {
this.m_HostTopology = topology; hostTopology = topology;
this.Initialize(); Initialize();
this.m_ListenPort = serverListenPort; listenPort = serverListenPort;
if (this.m_UseWebSockets) if (useWebSockets)
{ {
this.m_ServerHostId = NetworkTransport.AddWebsocketHost(this.m_HostTopology, serverListenPort); serverHostId = NetworkTransport.AddWebsocketHost(hostTopology, serverListenPort);
} }
else else
{ {
this.m_ServerHostId = NetworkTransport.AddHost(this.m_HostTopology, serverListenPort); serverHostId = NetworkTransport.AddHost(hostTopology, serverListenPort);
} }
bool result; bool result;
if (this.m_ServerHostId == -1) if (serverHostId == -1)
{ {
result = false; result = false;
} }
@ -199,7 +127,7 @@ namespace QuantumUNET
{ {
if (LogFilter.logDebug) if (LogFilter.logDebug)
{ {
Debug.Log("NetworkServerSimple listen " + this.m_ListenPort); Debug.Log("NetworkServerSimple listen " + listenPort);
} }
result = true; result = true;
} }
@ -208,19 +136,18 @@ namespace QuantumUNET
public void ListenRelay(string relayIp, int relayPort, NetworkID netGuid, SourceID sourceId, NodeID nodeId) public void ListenRelay(string relayIp, int relayPort, NetworkID netGuid, SourceID sourceId, NodeID nodeId)
{ {
this.Initialize(); Initialize();
this.m_ServerHostId = NetworkTransport.AddHost(this.m_HostTopology, this.listenPort); serverHostId = NetworkTransport.AddHost(hostTopology, listenPort);
if (LogFilter.logDebug) if (LogFilter.logDebug)
{ {
Debug.Log("Server Host Slot Id: " + this.m_ServerHostId); Debug.Log("Server Host Slot Id: " + serverHostId);
} }
this.Update(); Update();
byte b; NetworkTransport.ConnectAsNetworkHost(serverHostId, relayIp, relayPort, netGuid, sourceId, nodeId, out var b);
NetworkTransport.ConnectAsNetworkHost(this.m_ServerHostId, relayIp, relayPort, netGuid, sourceId, nodeId, out b); m_RelaySlotId = 0;
this.m_RelaySlotId = 0;
if (LogFilter.logDebug) 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 "); Debug.Log("NetworkServerSimple stop ");
} }
NetworkTransport.RemoveHost(this.m_ServerHostId); NetworkTransport.RemoveHost(serverHostId);
this.m_ServerHostId = -1; serverHostId = -1;
} }
internal void RegisterHandlerSafe(short msgType, QSBNetworkMessageDelegate handler) internal void RegisterHandlerSafe(short msgType, QSBNetworkMessageDelegate handler) => m_MessageHandlers.RegisterHandlerSafe(msgType, handler);
{
m_MessageHandlers.RegisterHandlerSafe(msgType, handler);
}
public void RegisterHandler(short msgType, QSBNetworkMessageDelegate handler) public void RegisterHandler(short msgType, QSBNetworkMessageDelegate handler) => m_MessageHandlers.RegisterHandler(msgType, handler);
{
this.m_MessageHandlers.RegisterHandler(msgType, handler);
}
public void UnregisterHandler(short msgType) public void UnregisterHandler(short msgType) => m_MessageHandlers.UnregisterHandler(msgType);
{
this.m_MessageHandlers.UnregisterHandler(msgType);
}
public void ClearHandlers() public void ClearHandlers() => m_MessageHandlers.ClearMessageHandlers();
{
this.m_MessageHandlers.ClearMessageHandlers();
}
public void UpdateConnections() 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) if (networkConnection != null)
{ {
networkConnection.FlushChannels(); networkConnection.FlushChannels();
@ -268,13 +183,12 @@ namespace QuantumUNET
public void Update() public void Update()
{ {
if (this.m_ServerHostId != -1) if (serverHostId != -1)
{ {
NetworkEventType networkEventType; NetworkEventType networkEventType;
if (this.m_RelaySlotId != -1) if (m_RelaySlotId != -1)
{ {
byte b; networkEventType = NetworkTransport.ReceiveRelayEventFromHost(serverHostId, out var b);
networkEventType = NetworkTransport.ReceiveRelayEventFromHost(this.m_ServerHostId, out b);
if (networkEventType != NetworkEventType.Nothing) if (networkEventType != NetworkEventType.Nothing)
{ {
if (LogFilter.logDebug) if (LogFilter.logDebug)
@ -299,17 +213,13 @@ namespace QuantumUNET
} }
do do
{ {
byte b; networkEventType = NetworkTransport.ReceiveFromHost(serverHostId, out var connectionId, out var channelId, messageBuffer, messageBuffer.Length, out var receivedSize, out var 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);
if (networkEventType != NetworkEventType.Nothing) if (networkEventType != NetworkEventType.Nothing)
{ {
Debug.Log(string.Concat(new object[] Debug.Log(string.Concat(new object[]
{ {
"Server event: host=", "Server event: host=",
this.m_ServerHostId, serverHostId,
" event=", " event=",
networkEventType, networkEventType,
" error=", " error=",
@ -319,15 +229,15 @@ namespace QuantumUNET
switch (networkEventType) switch (networkEventType)
{ {
case NetworkEventType.DataEvent: case NetworkEventType.DataEvent:
this.HandleData(connectionId, channelId, receivedSize, b); HandleData(connectionId, channelId, receivedSize, b);
break; break;
case NetworkEventType.ConnectEvent: case NetworkEventType.ConnectEvent:
this.HandleConnect(connectionId, b); HandleConnect(connectionId, b);
break; break;
case NetworkEventType.DisconnectEvent: case NetworkEventType.DisconnectEvent:
this.HandleDisconnect(connectionId, b); HandleDisconnect(connectionId, b);
break; break;
case NetworkEventType.Nothing: case NetworkEventType.Nothing:
@ -342,39 +252,39 @@ namespace QuantumUNET
} }
} }
while (networkEventType != NetworkEventType.Nothing); while (networkEventType != NetworkEventType.Nothing);
this.UpdateConnections(); UpdateConnections();
} }
} }
public QSBNetworkConnection FindConnection(int connectionId) public QSBNetworkConnection FindConnection(int connectionId)
{ {
QSBNetworkConnection result; QSBNetworkConnection result;
if (connectionId < 0 || connectionId >= this.m_Connections.Count) if (connectionId < 0 || connectionId >= m_Connections.Count)
{ {
result = null; result = null;
} }
else else
{ {
result = this.m_Connections[connectionId]; result = m_Connections[connectionId];
} }
return result; return result;
} }
public bool SetConnectionAtIndex(QSBNetworkConnection conn) 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; bool result;
if (this.m_Connections[conn.connectionId] != null) if (m_Connections[conn.connectionId] != null)
{ {
result = false; result = false;
} }
else else
{ {
this.m_Connections[conn.connectionId] = conn; m_Connections[conn.connectionId] = conn;
conn.SetHandlers(this.m_MessageHandlers); conn.SetHandlers(m_MessageHandlers);
result = true; result = true;
} }
return result; return result;
@ -383,13 +293,13 @@ namespace QuantumUNET
public bool RemoveConnectionAtIndex(int connectionId) public bool RemoveConnectionAtIndex(int connectionId)
{ {
bool result; bool result;
if (connectionId < 0 || connectionId >= this.m_Connections.Count) if (connectionId < 0 || connectionId >= m_Connections.Count)
{ {
result = false; result = false;
} }
else else
{ {
this.m_Connections[connectionId] = null; m_Connections[connectionId] = null;
result = true; result = true;
} }
return result; return result;
@ -403,26 +313,21 @@ namespace QuantumUNET
} }
if (error != 0) if (error != 0)
{ {
this.OnConnectError(connectionId, error); OnConnectError(connectionId, error);
} }
else else
{ {
string networkAddress; NetworkTransport.GetConnectionInfo(serverHostId, connectionId, out var networkAddress, out var num, out var networkID, out var nodeID, out var lastError);
int num; var networkConnection = (QSBNetworkConnection)Activator.CreateInstance(networkConnectionClass);
NetworkID networkID; networkConnection.SetHandlers(m_MessageHandlers);
NodeID nodeID; networkConnection.Initialize(networkAddress, serverHostId, connectionId, hostTopology);
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);
networkConnection.LastError = (NetworkError)lastError; 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; m_Connections[connectionId] = networkConnection;
this.OnConnected(networkConnection); OnConnected(networkConnection);
} }
} }
@ -432,7 +337,7 @@ namespace QuantumUNET
{ {
Debug.Log("NetworkServerSimple disconnect client:" + connectionId); Debug.Log("NetworkServerSimple disconnect client:" + connectionId);
} }
QSBNetworkConnection networkConnection = this.FindConnection(connectionId); var networkConnection = FindConnection(connectionId);
if (networkConnection != null) if (networkConnection != null)
{ {
networkConnection.LastError = (NetworkError)error; networkConnection.LastError = (NetworkError)error;
@ -440,7 +345,7 @@ namespace QuantumUNET
{ {
if (error != 6) if (error != 6)
{ {
this.m_Connections[connectionId] = null; m_Connections[connectionId] = null;
if (LogFilter.logError) if (LogFilter.logError)
{ {
Debug.LogError(string.Concat(new object[] Debug.LogError(string.Concat(new object[]
@ -451,23 +356,23 @@ namespace QuantumUNET
(NetworkError)error (NetworkError)error
})); }));
} }
this.OnDisconnectError(networkConnection, error); OnDisconnectError(networkConnection, error);
return; return;
} }
} }
networkConnection.Disconnect(); networkConnection.Disconnect();
this.m_Connections[connectionId] = null; m_Connections[connectionId] = null;
if (LogFilter.logDebug) if (LogFilter.logDebug)
{ {
Debug.Log("Server lost client:" + connectionId); Debug.Log("Server lost client:" + connectionId);
} }
this.OnDisconnected(networkConnection); OnDisconnected(networkConnection);
} }
} }
private void HandleData(int connectionId, int channelId, int receivedSize, byte error) private void HandleData(int connectionId, int channelId, int receivedSize, byte error)
{ {
QSBNetworkConnection networkConnection = this.FindConnection(connectionId); var networkConnection = FindConnection(connectionId);
if (networkConnection == null) if (networkConnection == null)
{ {
if (LogFilter.logError) if (LogFilter.logError)
@ -480,19 +385,19 @@ namespace QuantumUNET
networkConnection.LastError = (NetworkError)error; networkConnection.LastError = (NetworkError)error;
if (error != 0) if (error != 0)
{ {
this.OnDataError(networkConnection, error); OnDataError(networkConnection, error);
} }
else else
{ {
this.m_MsgReader.SeekZero(); messageReader.SeekZero();
this.OnData(networkConnection, receivedSize, channelId); OnData(networkConnection, receivedSize, channelId);
} }
} }
} }
public void SendBytesTo(int connectionId, byte[] bytes, int numBytes, int channelId) public void SendBytesTo(int connectionId, byte[] bytes, int numBytes, int channelId)
{ {
QSBNetworkConnection networkConnection = this.FindConnection(connectionId); var networkConnection = FindConnection(connectionId);
if (networkConnection != null) if (networkConnection != null)
{ {
networkConnection.SendBytes(bytes, numBytes, channelId); networkConnection.SendBytes(bytes, numBytes, channelId);
@ -501,7 +406,7 @@ namespace QuantumUNET
public void SendWriterTo(int connectionId, QSBNetworkWriter writer, int channelId) public void SendWriterTo(int connectionId, QSBNetworkWriter writer, int channelId)
{ {
QSBNetworkConnection networkConnection = this.FindConnection(connectionId); var networkConnection = FindConnection(connectionId);
if (networkConnection != null) if (networkConnection != null)
{ {
networkConnection.SendWriter(writer, channelId); networkConnection.SendWriter(writer, channelId);
@ -510,19 +415,19 @@ namespace QuantumUNET
public void Disconnect(int connectionId) public void Disconnect(int connectionId)
{ {
QSBNetworkConnection networkConnection = this.FindConnection(connectionId); var networkConnection = FindConnection(connectionId);
if (networkConnection != null) if (networkConnection != null)
{ {
networkConnection.Disconnect(); networkConnection.Disconnect();
this.m_Connections[connectionId] = null; m_Connections[connectionId] = null;
} }
} }
public void DisconnectAllConnections() 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) if (networkConnection != null)
{ {
networkConnection.Disconnect(); networkConnection.Disconnect();
@ -531,58 +436,21 @@ namespace QuantumUNET
} }
} }
public virtual void OnConnectError(int connectionId, byte error) public virtual void OnConnectError(int connectionId, byte error) => Debug.LogError("OnConnectError error:" + error);
{
Debug.LogError("OnConnectError error:" + error);
}
public virtual void OnDataError(QSBNetworkConnection conn, byte error) public virtual void OnDataError(QSBNetworkConnection conn, byte error) => Debug.LogError("OnDataError error:" + error);
{
Debug.LogError("OnDataError error:" + error);
}
public virtual void OnDisconnectError(QSBNetworkConnection conn, byte error) public virtual void OnDisconnectError(QSBNetworkConnection conn, byte error) => Debug.LogError("OnDisconnectError error:" + error);
{
Debug.LogError("OnDisconnectError error:" + error);
}
public virtual void OnConnected(QSBNetworkConnection conn) public virtual void OnConnected(QSBNetworkConnection conn) => conn.InvokeHandlerNoData(32);
{
conn.InvokeHandlerNoData(32);
}
public virtual void OnDisconnected(QSBNetworkConnection conn) public virtual void OnDisconnected(QSBNetworkConnection conn) => conn.InvokeHandlerNoData(33);
{
conn.InvokeHandlerNoData(33);
}
public virtual void OnData(QSBNetworkConnection conn, int receivedSize, int channelId) public virtual void OnData(QSBNetworkConnection conn, int receivedSize, int channelId) => conn.TransportReceive(messageBuffer, receivedSize, channelId);
{
conn.TransportReceive(this.m_MsgBuffer, receivedSize, channelId);
}
private bool m_Initialized = false; private bool m_Initialized = false;
private int m_ListenPort;
private int m_ServerHostId = -1;
private int m_RelaySlotId = -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<QSBNetworkConnection> m_Connections = new List<QSBNetworkConnection>(); private List<QSBNetworkConnection> m_Connections = new List<QSBNetworkConnection>();
private ReadOnlyCollection<QSBNetworkConnection> m_ConnectionsReadOnly;
private QSBNetworkMessageHandlers m_MessageHandlers = new QSBNetworkMessageHandlers(); private QSBNetworkMessageHandlers m_MessageHandlers = new QSBNetworkMessageHandlers();
} }
} }

View File

@ -11,7 +11,7 @@ namespace QuantumUNET
{ {
public QSBNetworkWriter() public QSBNetworkWriter()
{ {
this.m_Buffer = new QSBNetBuffer(); m_Buffer = new QSBNetBuffer();
if (s_Encoding == null) if (s_Encoding == null)
{ {
s_Encoding = new UTF8Encoding(); s_Encoding = new UTF8Encoding();
@ -21,7 +21,7 @@ namespace QuantumUNET
public QSBNetworkWriter(byte[] buffer) public QSBNetworkWriter(byte[] buffer)
{ {
this.m_Buffer = new QSBNetBuffer(buffer); m_Buffer = new QSBNetBuffer(buffer);
if (s_Encoding == null) if (s_Encoding == null)
{ {
s_Encoding = new UTF8Encoding(); s_Encoding = new UTF8Encoding();
@ -29,62 +29,50 @@ namespace QuantumUNET
} }
} }
public short Position public short Position => (short)m_Buffer.Position;
{
get
{
return (short)this.m_Buffer.Position;
}
}
public byte[] ToArray() public byte[] ToArray()
{ {
byte[] array = new byte[this.m_Buffer.AsArraySegment().Count]; var array = new byte[m_Buffer.AsArraySegment().Count];
Array.Copy(this.m_Buffer.AsArraySegment().Array, array, this.m_Buffer.AsArraySegment().Count); Array.Copy(m_Buffer.AsArraySegment().Array, array, m_Buffer.AsArraySegment().Count);
return array; return array;
} }
public byte[] AsArray() public byte[] AsArray() => AsArraySegment().Array;
{
return this.AsArraySegment().Array;
}
internal ArraySegment<byte> AsArraySegment() internal ArraySegment<byte> AsArraySegment() => m_Buffer.AsArraySegment();
{
return this.m_Buffer.AsArraySegment();
}
public void WritePackedUInt32(uint value) public void WritePackedUInt32(uint value)
{ {
if (value <= 240U) if (value <= 240U)
{ {
this.Write((byte)value); Write((byte)value);
} }
else if (value <= 2287U) else if (value <= 2287U)
{ {
this.Write((byte)((value - 240U) / 256U + 241U)); Write((byte)(((value - 240U) / 256U) + 241U));
this.Write((byte)((value - 240U) % 256U)); Write((byte)((value - 240U) % 256U));
} }
else if (value <= 67823U) else if (value <= 67823U)
{ {
this.Write(249); Write(249);
this.Write((byte)((value - 2288U) / 256U)); Write((byte)((value - 2288U) / 256U));
this.Write((byte)((value - 2288U) % 256U)); Write((byte)((value - 2288U) % 256U));
} }
else if (value <= 16777215U) else if (value <= 16777215U)
{ {
this.Write(250); Write(250);
this.Write((byte)(value & 255U)); Write((byte)(value & 255U));
this.Write((byte)(value >> 8 & 255U)); Write((byte)((value >> 8) & 255U));
this.Write((byte)(value >> 16 & 255U)); Write((byte)((value >> 16) & 255U));
} }
else else
{ {
this.Write(251); Write(251);
this.Write((byte)(value & 255U)); Write((byte)(value & 255U));
this.Write((byte)(value >> 8 & 255U)); Write((byte)((value >> 8) & 255U));
this.Write((byte)(value >> 16 & 255U)); Write((byte)((value >> 16) & 255U));
this.Write((byte)(value >> 24 & 255U)); Write((byte)((value >> 24) & 255U));
} }
} }
@ -92,168 +80,129 @@ namespace QuantumUNET
{ {
if (value <= 240UL) if (value <= 240UL)
{ {
this.Write((byte)value); Write((byte)value);
} }
else if (value <= 2287UL) else if (value <= 2287UL)
{ {
this.Write((byte)((value - 240UL) / 256UL + 241UL)); Write((byte)(((value - 240UL) / 256UL) + 241UL));
this.Write((byte)((value - 240UL) % 256UL)); Write((byte)((value - 240UL) % 256UL));
} }
else if (value <= 67823UL) else if (value <= 67823UL)
{ {
this.Write(249); Write(249);
this.Write((byte)((value - 2288UL) / 256UL)); Write((byte)((value - 2288UL) / 256UL));
this.Write((byte)((value - 2288UL) % 256UL)); Write((byte)((value - 2288UL) % 256UL));
} }
else if (value <= 16777215UL) else if (value <= 16777215UL)
{ {
this.Write(250); Write(250);
this.Write((byte)(value & 255UL)); Write((byte)(value & 255UL));
this.Write((byte)(value >> 8 & 255UL)); Write((byte)((value >> 8) & 255UL));
this.Write((byte)(value >> 16 & 255UL)); Write((byte)((value >> 16) & 255UL));
} }
else if (value <= uint.MaxValue) else if (value <= uint.MaxValue)
{ {
this.Write(251); Write(251);
this.Write((byte)(value & 255UL)); Write((byte)(value & 255UL));
this.Write((byte)(value >> 8 & 255UL)); Write((byte)((value >> 8) & 255UL));
this.Write((byte)(value >> 16 & 255UL)); Write((byte)((value >> 16) & 255UL));
this.Write((byte)(value >> 24 & 255UL)); Write((byte)((value >> 24) & 255UL));
} }
else if (value <= 1099511627775UL) else if (value <= 1099511627775UL)
{ {
this.Write(252); Write(252);
this.Write((byte)(value & 255UL)); Write((byte)(value & 255UL));
this.Write((byte)(value >> 8 & 255UL)); Write((byte)((value >> 8) & 255UL));
this.Write((byte)(value >> 16 & 255UL)); Write((byte)((value >> 16) & 255UL));
this.Write((byte)(value >> 24 & 255UL)); Write((byte)((value >> 24) & 255UL));
this.Write((byte)(value >> 32 & 255UL)); Write((byte)((value >> 32) & 255UL));
} }
else if (value <= 281474976710655UL) else if (value <= 281474976710655UL)
{ {
this.Write(253); Write(253);
this.Write((byte)(value & 255UL)); Write((byte)(value & 255UL));
this.Write((byte)(value >> 8 & 255UL)); Write((byte)((value >> 8) & 255UL));
this.Write((byte)(value >> 16 & 255UL)); Write((byte)((value >> 16) & 255UL));
this.Write((byte)(value >> 24 & 255UL)); Write((byte)((value >> 24) & 255UL));
this.Write((byte)(value >> 32 & 255UL)); Write((byte)((value >> 32) & 255UL));
this.Write((byte)(value >> 40 & 255UL)); Write((byte)((value >> 40) & 255UL));
} }
else if (value <= 72057594037927935UL) else if (value <= 72057594037927935UL)
{ {
this.Write(254); Write(254);
this.Write((byte)(value & 255UL)); Write((byte)(value & 255UL));
this.Write((byte)(value >> 8 & 255UL)); Write((byte)((value >> 8) & 255UL));
this.Write((byte)(value >> 16 & 255UL)); Write((byte)((value >> 16) & 255UL));
this.Write((byte)(value >> 24 & 255UL)); Write((byte)((value >> 24) & 255UL));
this.Write((byte)(value >> 32 & 255UL)); Write((byte)((value >> 32) & 255UL));
this.Write((byte)(value >> 40 & 255UL)); Write((byte)((value >> 40) & 255UL));
this.Write((byte)(value >> 48 & 255UL)); Write((byte)((value >> 48) & 255UL));
} }
else else
{ {
this.Write(byte.MaxValue); Write(byte.MaxValue);
this.Write((byte)(value & 255UL)); Write((byte)(value & 255UL));
this.Write((byte)(value >> 8 & 255UL)); Write((byte)((value >> 8) & 255UL));
this.Write((byte)(value >> 16 & 255UL)); Write((byte)((value >> 16) & 255UL));
this.Write((byte)(value >> 24 & 255UL)); Write((byte)((value >> 24) & 255UL));
this.Write((byte)(value >> 32 & 255UL)); Write((byte)((value >> 32) & 255UL));
this.Write((byte)(value >> 40 & 255UL)); Write((byte)((value >> 40) & 255UL));
this.Write((byte)(value >> 48 & 255UL)); Write((byte)((value >> 48) & 255UL));
this.Write((byte)(value >> 56 & 255UL)); Write((byte)((value >> 56) & 255UL));
} }
} }
public void Write(NetworkInstanceId value) public void Write(NetworkInstanceId value) => WritePackedUInt32(value.Value);
{
this.WritePackedUInt32(value.Value);
}
public void Write(NetworkSceneId value) public void Write(NetworkSceneId value) => WritePackedUInt32(value.Value);
{
this.WritePackedUInt32(value.Value);
}
public void Write(char value) public void Write(char value) => m_Buffer.WriteByte((byte)value);
{
this.m_Buffer.WriteByte((byte)value);
}
public void Write(byte value) public void Write(byte value) => m_Buffer.WriteByte(value);
{
this.m_Buffer.WriteByte(value);
}
public void Write(sbyte value) public void Write(sbyte value) => m_Buffer.WriteByte((byte)value);
{
this.m_Buffer.WriteByte((byte)value);
}
public void Write(short value) public void Write(short value) => m_Buffer.WriteByte2((byte)(value & 255), (byte)((value >> 8) & 255));
{
this.m_Buffer.WriteByte2((byte)(value & 255), (byte)(value >> 8 & 255));
}
public void Write(ushort value) public void Write(ushort value) => m_Buffer.WriteByte2((byte)(value & 255), (byte)((value >> 8) & 255));
{
this.m_Buffer.WriteByte2((byte)(value & 255), (byte)(value >> 8 & 255));
}
public void Write(int value) public void Write(int value) => m_Buffer.WriteByte4((byte)(value & 255), (byte)((value >> 8) & 255), (byte)((value >> 16) & 255), (byte)((value >> 24) & 255));
{
this.m_Buffer.WriteByte4((byte)(value & 255), (byte)(value >> 8 & 255), (byte)(value >> 16 & 255), (byte)(value >> 24 & 255));
}
public void Write(uint value) public void Write(uint value) => m_Buffer.WriteByte4((byte)(value & 255U), (byte)((value >> 8) & 255U), (byte)((value >> 16) & 255U), (byte)((value >> 24) & 255U));
{
this.m_Buffer.WriteByte4((byte)(value & 255U), (byte)(value >> 8 & 255U), (byte)(value >> 16 & 255U), (byte)(value >> 24 & 255U));
}
public void Write(long value) 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));
{
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(ulong value) 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));
{
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(float value) public void Write(float value) => m_Buffer.WriteBytes(BitConverter.GetBytes(value), 4);
{
m_Buffer.WriteBytes(BitConverter.GetBytes(value), 4);
}
public void Write(double value) public void Write(double value) => m_Buffer.WriteBytes(BitConverter.GetBytes(value), 8);
{
m_Buffer.WriteBytes(BitConverter.GetBytes(value), 8);
}
public void Write(decimal value) public void Write(decimal value)
{ {
int[] bits = decimal.GetBits(value); var bits = decimal.GetBits(value);
this.Write(bits[0]); Write(bits[0]);
this.Write(bits[1]); Write(bits[1]);
this.Write(bits[2]); Write(bits[2]);
this.Write(bits[3]); Write(bits[3]);
} }
public void Write(string value) public void Write(string value)
{ {
if (value == null) if (value == null)
{ {
this.m_Buffer.WriteByte2(0, 0); m_Buffer.WriteByte2(0, 0);
} }
else else
{ {
int byteCount = s_Encoding.GetByteCount(value); var byteCount = s_Encoding.GetByteCount(value);
if (byteCount >= 32768) if (byteCount >= 32768)
{ {
throw new IndexOutOfRangeException("Serialize(string) too long: " + value.Length); throw new IndexOutOfRangeException("Serialize(string) too long: " + value.Length);
} }
this.Write((ushort)byteCount); Write((ushort)byteCount);
int bytes = s_Encoding.GetBytes(value, 0, value.Length, s_StringWriteBuffer, 0); var bytes = s_Encoding.GetBytes(value, 0, value.Length, s_StringWriteBuffer, 0);
this.m_Buffer.WriteBytes(s_StringWriteBuffer, (ushort)bytes); m_Buffer.WriteBytes(s_StringWriteBuffer, (ushort)bytes);
} }
} }
@ -261,11 +210,11 @@ namespace QuantumUNET
{ {
if (value) if (value)
{ {
this.m_Buffer.WriteByte(1); m_Buffer.WriteByte(1);
} }
else else
{ {
this.m_Buffer.WriteByte(0); m_Buffer.WriteByte(0);
} }
} }
@ -280,7 +229,7 @@ namespace QuantumUNET
} }
else else
{ {
this.m_Buffer.WriteBytes(buffer, (ushort)count); m_Buffer.WriteBytes(buffer, (ushort)count);
} }
} }
@ -295,7 +244,7 @@ namespace QuantumUNET
} }
else 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) if (buffer == null || count == 0)
{ {
this.Write(0); Write(0);
} }
else if (count > 65535) else if (count > 65535)
{ {
@ -314,8 +263,8 @@ namespace QuantumUNET
} }
else else
{ {
this.Write((ushort)count); Write((ushort)count);
this.m_Buffer.WriteBytes(buffer, (ushort)count); m_Buffer.WriteBytes(buffer, (ushort)count);
} }
} }
@ -323,7 +272,7 @@ namespace QuantumUNET
{ {
if (buffer == null) if (buffer == null)
{ {
this.Write(0); Write(0);
} }
else if (buffer.Length > 65535) else if (buffer.Length > 65535)
{ {
@ -334,125 +283,125 @@ namespace QuantumUNET
} }
else else
{ {
this.Write((ushort)buffer.Length); Write((ushort)buffer.Length);
this.m_Buffer.WriteBytes(buffer, (ushort)buffer.Length); m_Buffer.WriteBytes(buffer, (ushort)buffer.Length);
} }
} }
public void Write(Vector2 value) public void Write(Vector2 value)
{ {
this.Write(value.x); Write(value.x);
this.Write(value.y); Write(value.y);
} }
public void Write(Vector3 value) public void Write(Vector3 value)
{ {
this.Write(value.x); Write(value.x);
this.Write(value.y); Write(value.y);
this.Write(value.z); Write(value.z);
} }
public void Write(Vector4 value) public void Write(Vector4 value)
{ {
this.Write(value.x); Write(value.x);
this.Write(value.y); Write(value.y);
this.Write(value.z); Write(value.z);
this.Write(value.w); Write(value.w);
} }
public void Write(Color value) public void Write(Color value)
{ {
this.Write(value.r); Write(value.r);
this.Write(value.g); Write(value.g);
this.Write(value.b); Write(value.b);
this.Write(value.a); Write(value.a);
} }
public void Write(Color32 value) public void Write(Color32 value)
{ {
this.Write(value.r); Write(value.r);
this.Write(value.g); Write(value.g);
this.Write(value.b); Write(value.b);
this.Write(value.a); Write(value.a);
} }
public void Write(Quaternion value) public void Write(Quaternion value)
{ {
this.Write(value.x); Write(value.x);
this.Write(value.y); Write(value.y);
this.Write(value.z); Write(value.z);
this.Write(value.w); Write(value.w);
} }
public void Write(Rect value) public void Write(Rect value)
{ {
this.Write(value.xMin); Write(value.xMin);
this.Write(value.yMin); Write(value.yMin);
this.Write(value.width); Write(value.width);
this.Write(value.height); Write(value.height);
} }
public void Write(Plane value) public void Write(Plane value)
{ {
this.Write(value.normal); Write(value.normal);
this.Write(value.distance); Write(value.distance);
} }
public void Write(Ray value) public void Write(Ray value)
{ {
this.Write(value.direction); Write(value.direction);
this.Write(value.origin); Write(value.origin);
} }
public void Write(Matrix4x4 value) public void Write(Matrix4x4 value)
{ {
this.Write(value.m00); Write(value.m00);
this.Write(value.m01); Write(value.m01);
this.Write(value.m02); Write(value.m02);
this.Write(value.m03); Write(value.m03);
this.Write(value.m10); Write(value.m10);
this.Write(value.m11); Write(value.m11);
this.Write(value.m12); Write(value.m12);
this.Write(value.m13); Write(value.m13);
this.Write(value.m20); Write(value.m20);
this.Write(value.m21); Write(value.m21);
this.Write(value.m22); Write(value.m22);
this.Write(value.m23); Write(value.m23);
this.Write(value.m30); Write(value.m30);
this.Write(value.m31); Write(value.m31);
this.Write(value.m32); Write(value.m32);
this.Write(value.m33); Write(value.m33);
} }
public void Write(NetworkHash128 value) public void Write(NetworkHash128 value)
{ {
this.Write(value.i0); Write(value.i0);
this.Write(value.i1); Write(value.i1);
this.Write(value.i2); Write(value.i2);
this.Write(value.i3); Write(value.i3);
this.Write(value.i4); Write(value.i4);
this.Write(value.i5); Write(value.i5);
this.Write(value.i6); Write(value.i6);
this.Write(value.i7); Write(value.i7);
this.Write(value.i8); Write(value.i8);
this.Write(value.i9); Write(value.i9);
this.Write(value.i10); Write(value.i10);
this.Write(value.i11); Write(value.i11);
this.Write(value.i12); Write(value.i12);
this.Write(value.i13); Write(value.i13);
this.Write(value.i14); Write(value.i14);
this.Write(value.i15); Write(value.i15);
} }
public void Write(NetworkIdentity value) public void Write(NetworkIdentity value)
{ {
if (value == null) if (value == null)
{ {
this.WritePackedUInt32(0U); WritePackedUInt32(0U);
} }
else else
{ {
this.Write(value.netId); Write(value.netId);
} }
} }
@ -460,14 +409,14 @@ namespace QuantumUNET
{ {
if (value == null || value.gameObject == null) if (value == null || value.gameObject == null)
{ {
this.WritePackedUInt32(0U); WritePackedUInt32(0U);
} }
else else
{ {
NetworkIdentity component = value.gameObject.GetComponent<NetworkIdentity>(); var component = value.gameObject.GetComponent<NetworkIdentity>();
if (component != null) if (component != null)
{ {
this.Write(component.netId); Write(component.netId);
} }
else else
{ {
@ -475,7 +424,7 @@ namespace QuantumUNET
{ {
Debug.LogWarning("NetworkWriter " + value + " has no NetworkIdentity"); Debug.LogWarning("NetworkWriter " + value + " has no NetworkIdentity");
} }
this.WritePackedUInt32(0U); WritePackedUInt32(0U);
} }
} }
} }
@ -484,14 +433,14 @@ namespace QuantumUNET
{ {
if (value == null) if (value == null)
{ {
this.WritePackedUInt32(0U); WritePackedUInt32(0U);
} }
else else
{ {
QSBNetworkIdentity component = value.GetComponent<QSBNetworkIdentity>(); var component = value.GetComponent<QSBNetworkIdentity>();
if (component != null) if (component != null)
{ {
this.Write(component.NetId); Write(component.NetId);
} }
else else
{ {
@ -499,32 +448,23 @@ namespace QuantumUNET
{ {
Debug.LogWarning("NetworkWriter " + value + " has no NetworkIdentity"); Debug.LogWarning("NetworkWriter " + value + " has no NetworkIdentity");
} }
this.WritePackedUInt32(0U); WritePackedUInt32(0U);
} }
} }
} }
public void Write(QSBMessageBase msg) public void Write(QSBMessageBase msg) => msg.Serialize(this);
{
msg.Serialize(this);
}
public void SeekZero() public void SeekZero() => m_Buffer.SeekZero();
{
this.m_Buffer.SeekZero();
}
public void StartMessage(short msgType) public void StartMessage(short msgType)
{ {
this.SeekZero(); SeekZero();
this.m_Buffer.WriteByte2(0, 0); m_Buffer.WriteByte2(0, 0);
this.Write(msgType); Write(msgType);
} }
public void FinishMessage() public void FinishMessage() => m_Buffer.FinishMessage();
{
this.m_Buffer.FinishMessage();
}
private const int k_MaxStringLength = 32768; private const int k_MaxStringLength = 32768;

View File

@ -12,20 +12,11 @@ namespace QuantumUNET
m_LocalServer = localServer; m_LocalServer = localServer;
} }
public override bool Send(short msgType, QSBMessageBase msg) public override bool Send(short msgType, QSBMessageBase msg) => m_LocalServer.InvokeHandlerOnServer(this, msgType, msg, 0);
{
return m_LocalServer.InvokeHandlerOnServer(this, msgType, msg, 0);
}
public override bool SendUnreliable(short msgType, QSBMessageBase msg) public override bool SendUnreliable(short msgType, QSBMessageBase msg) => m_LocalServer.InvokeHandlerOnServer(this, msgType, msg, 1);
{
return m_LocalServer.InvokeHandlerOnServer(this, msgType, msg, 1);
}
public override bool SendByChannel(short msgType, QSBMessageBase msg, int channelId) public override bool SendByChannel(short msgType, QSBMessageBase msg, int channelId) => m_LocalServer.InvokeHandlerOnServer(this, msgType, msg, channelId);
{
return m_LocalServer.InvokeHandlerOnServer(this, msgType, msg, channelId);
}
public override bool SendBytes(byte[] bytes, int numBytes, int channelId) public override bool SendBytes(byte[] bytes, int numBytes, int channelId)
{ {
@ -45,10 +36,7 @@ namespace QuantumUNET
return result; return result;
} }
public override bool SendWriter(QSBNetworkWriter writer, int channelId) public override bool SendWriter(QSBNetworkWriter writer, int channelId) => m_LocalServer.InvokeBytes(this, writer.AsArray(), (short)writer.AsArray().Length, channelId);
{
return m_LocalServer.InvokeBytes(this, writer.AsArray(), (int)((short)writer.AsArray().Length), channelId);
}
public override void GetStatsOut(out int numMsgs, out int numBufferedMsgs, out int numBytes, out int lastBufferedPerSecond) public override void GetStatsOut(out int numMsgs, out int numBufferedMsgs, out int numBytes, out int lastBufferedPerSecond)
{ {