diff --git a/com.unity.multiplayer.mlapi/Editor/CodeGen/CodeGenHelpers.cs b/com.unity.multiplayer.mlapi/Editor/CodeGen/CodeGenHelpers.cs index 6f6aa161af..a1e27afde6 100644 --- a/com.unity.multiplayer.mlapi/Editor/CodeGen/CodeGenHelpers.cs +++ b/com.unity.multiplayer.mlapi/Editor/CodeGen/CodeGenHelpers.cs @@ -88,9 +88,8 @@ public static bool HasInterface(this TypeReference typeReference, string Interfa } catch { + return false; } - - return false; } public static bool IsSerializable(this TypeReference typeReference) @@ -141,16 +140,12 @@ public static TypeReference GetEnumAsInt(this TypeReference typeReference) try { var typeDef = typeReference.Resolve(); - if (typeDef.IsEnum) - { - return typeDef.GetEnumUnderlyingType(); - } + return typeDef.IsEnum ? typeDef.GetEnumUnderlyingType() : null; } catch { + return null; } - - return null; } public static void AddError(this List diagnostics, string message) diff --git a/com.unity.multiplayer.mlapi/Editor/CodeGen/ILPostProcessorProgram.cs b/com.unity.multiplayer.mlapi/Editor/CodeGen/ILPostProcessorProgram.cs index 62ca3e47c5..d8a2dd8c5f 100644 --- a/com.unity.multiplayer.mlapi/Editor/CodeGen/ILPostProcessorProgram.cs +++ b/com.unity.multiplayer.mlapi/Editor/CodeGen/ILPostProcessorProgram.cs @@ -37,7 +37,7 @@ private static ILPostProcessor[] FindAllPostProcessors() } catch (Exception exception) { - Debug.LogError($"Could not create ILPostProcessor ({typeCollection.FullName}):{Environment.NewLine}{exception.StackTrace}"); + Debug.LogError($"Could not create {nameof(ILPostProcessor)} ({typeCollection.FullName}):{Environment.NewLine}{exception.StackTrace}"); } } @@ -185,22 +185,21 @@ void WriteAssembly(InMemoryAssembly inMemoryAssembly, string outputPath, string foreach (var i in s_ILPostProcessors) { var result = i.Process(targetCompiledAssembly); - if (result == null) - continue; + if (result == null) continue; if (result.Diagnostics.Count > 0) { - Debug.LogError($"ILPostProcessor - {i.GetType().Name} failed to run on {targetCompiledAssembly.Name}"); + Debug.LogError($"{nameof(ILPostProcessor)} - {i.GetType().Name} failed to run on {targetCompiledAssembly.Name}"); foreach (var message in result.Diagnostics) { switch (message.DiagnosticType) { case DiagnosticType.Error: - Debug.LogError($"ILPostProcessor Error - {message.MessageData} {message.File}:{message.Line}"); + Debug.LogError($"{nameof(ILPostProcessor)} Error - {message.MessageData} {message.File}:{message.Line}"); break; case DiagnosticType.Warning: - Debug.LogWarning($"ILPostProcessor Warning - {message.MessageData} {message.File}:{message.Line}"); + Debug.LogWarning($"{nameof(ILPostProcessor)} Warning - {message.MessageData} {message.File}:{message.Line}"); break; } } diff --git a/com.unity.multiplayer.mlapi/Editor/CodeGen/PostProcessorReflectionImporter.cs b/com.unity.multiplayer.mlapi/Editor/CodeGen/PostProcessorReflectionImporter.cs index 26d1244246..c1510b12c9 100644 --- a/com.unity.multiplayer.mlapi/Editor/CodeGen/PostProcessorReflectionImporter.cs +++ b/com.unity.multiplayer.mlapi/Editor/CodeGen/PostProcessorReflectionImporter.cs @@ -6,17 +6,17 @@ namespace MLAPI.Editor.CodeGen { internal class PostProcessorReflectionImporter : DefaultReflectionImporter { - private const string SystemPrivateCoreLib = "System.Private.CoreLib"; + private const string k_SystemPrivateCoreLib = "System.Private.CoreLib"; private readonly AssemblyNameReference m_CorrectCorlib; public PostProcessorReflectionImporter(ModuleDefinition module) : base(module) { - m_CorrectCorlib = module.AssemblyReferences.FirstOrDefault(a => a.Name == "mscorlib" || a.Name == "netstandard" || a.Name == SystemPrivateCoreLib); + m_CorrectCorlib = module.AssemblyReferences.FirstOrDefault(a => a.Name == "mscorlib" || a.Name == "netstandard" || a.Name == k_SystemPrivateCoreLib); } public override AssemblyNameReference ImportReference(AssemblyName reference) { - return m_CorrectCorlib != null && reference.Name == SystemPrivateCoreLib ? m_CorrectCorlib : base.ImportReference(reference); + return m_CorrectCorlib != null && reference.Name == k_SystemPrivateCoreLib ? m_CorrectCorlib : base.ImportReference(reference); } } } \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Editor/CodeGen/XXHash/XXHash.cs b/com.unity.multiplayer.mlapi/Editor/CodeGen/XXHash/XXHash.cs index 14d8b04623..8517a3b907 100644 --- a/com.unity.multiplayer.mlapi/Editor/CodeGen/XXHash/XXHash.cs +++ b/com.unity.multiplayer.mlapi/Editor/CodeGen/XXHash/XXHash.cs @@ -14,17 +14,17 @@ namespace MLAPI.Editor.CodeGen /// internal static class XXHash { - private const ulong prime64v1 = 11400714785074694791ul; - private const ulong prime64v2 = 14029467366897019727ul; - private const ulong prime64v3 = 1609587929392839161ul; - private const ulong prime64v4 = 9650029242287828579ul; - private const ulong prime64v5 = 2870177450012600261ul; - - private const uint prime32v1 = 2654435761u; - private const uint prime32v2 = 2246822519u; - private const uint prime32v3 = 3266489917u; - private const uint prime32v4 = 668265263u; - private const uint prime32v5 = 374761393u; + private const ulong k_Prime64v1 = 11400714785074694791ul; + private const ulong k_Prime64v2 = 14029467366897019727ul; + private const ulong k_Prime64v3 = 1609587929392839161ul; + private const ulong k_Prime64v4 = 9650029242287828579ul; + private const ulong k_Prime64v5 = 2870177450012600261ul; + + private const uint k_Prime32v1 = 2654435761u; + private const uint k_Prime32v2 = 2246822519u; + private const uint k_Prime32v3 = 3266489917u; + private const uint k_Prime32v4 = 668265263u; + private const uint k_Prime32v5 = 374761393u; /// /// Generate a 32-bit xxHash value. @@ -44,10 +44,10 @@ public static unsafe uint Hash32(byte* buffer, int bufferLength, uint seed = 0) byte* pInput = buffer; if (len >= stripeLength) { - uint acc1 = seed + prime32v1 + prime32v2; - uint acc2 = seed + prime32v2; + uint acc1 = seed + k_Prime32v1 + k_Prime32v2; + uint acc2 = seed + k_Prime32v2; uint acc3 = seed; - uint acc4 = seed - prime32v1; + uint acc4 = seed - k_Prime32v1; do { @@ -57,7 +57,7 @@ public static unsafe uint Hash32(byte* buffer, int bufferLength, uint seed = 0) } else { - acc = seed + prime32v5; + acc = seed + k_Prime32v5; } acc += (uint)len; @@ -84,10 +84,10 @@ public static unsafe ulong Hash64(byte* buffer, int bufferLength, ulong seed = 0 byte* pInput = buffer; if (len >= stripeLength) { - ulong acc1 = seed + prime64v1 + prime64v2; - ulong acc2 = seed + prime64v2; + ulong acc1 = seed + k_Prime64v1 + k_Prime64v2; + ulong acc2 = seed + k_Prime64v2; ulong acc3 = seed; - ulong acc4 = seed - prime64v1; + ulong acc4 = seed - k_Prime64v1; do { @@ -97,7 +97,7 @@ public static unsafe ulong Hash64(byte* buffer, int bufferLength, ulong seed = 0 } else { - acc = seed + prime64v5; + acc = seed + k_Prime64v5; } acc += (ulong)len; @@ -151,24 +151,24 @@ private static unsafe ulong processRemaining64( lane = *(ulong*)pInput; acc ^= round64(0, lane); - acc = Bits.RotateLeft(acc, 27) * prime64v1; - acc += prime64v4; + acc = Bits.RotateLeft(acc, 27) * k_Prime64v1; + acc += k_Prime64v4; } for (uint lane32; remainingLen >= 4; remainingLen -= 4, pInput += 4) { lane32 = *(uint*)pInput; - acc ^= lane32 * prime64v1; - acc = Bits.RotateLeft(acc, 23) * prime64v2; - acc += prime64v3; + acc ^= lane32 * k_Prime64v1; + acc = Bits.RotateLeft(acc, 23) * k_Prime64v2; + acc += k_Prime64v3; } for (byte lane8; remainingLen >= 1; remainingLen--, pInput++) { lane8 = *pInput; - acc ^= lane8 * prime64v5; - acc = Bits.RotateLeft(acc, 11) * prime64v1; + acc ^= lane8 * k_Prime64v5; + acc = Bits.RotateLeft(acc, 11) * k_Prime64v1; } return acc; @@ -178,9 +178,9 @@ private static unsafe ulong processRemaining64( private static ulong avalanche64(ulong acc) { acc ^= acc >> 33; - acc *= prime64v2; + acc *= k_Prime64v2; acc ^= acc >> 29; - acc *= prime64v3; + acc *= k_Prime64v3; acc ^= acc >> 32; return acc; } @@ -188,16 +188,16 @@ private static ulong avalanche64(ulong acc) [MethodImpl(MethodImplOptions.AggressiveInlining)] private static ulong round64(ulong accn, ulong lane) { - accn += lane * prime64v2; - return Bits.RotateLeft(accn, 31) * prime64v1; + accn += lane * k_Prime64v2; + return Bits.RotateLeft(accn, 31) * k_Prime64v1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void mergeAccumulator64(ref ulong acc, ulong accn) { acc ^= round64(0, accn); - acc *= prime64v1; - acc += prime64v4; + acc *= k_Prime64v1; + acc += k_Prime64v4; } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -236,15 +236,15 @@ private static unsafe uint processRemaining32( for (uint lane; remainingLen >= 4; remainingLen -= 4, pInput += 4) { lane = *(uint*)pInput; - acc += lane * prime32v3; - acc = Bits.RotateLeft(acc, 17) * prime32v4; + acc += lane * k_Prime32v3; + acc = Bits.RotateLeft(acc, 17) * k_Prime32v4; } for (byte lane; remainingLen >= 1; remainingLen--, pInput++) { lane = *pInput; - acc += lane * prime32v5; - acc = Bits.RotateLeft(acc, 11) * prime32v1; + acc += lane * k_Prime32v5; + acc = Bits.RotateLeft(acc, 11) * k_Prime32v1; } return acc; @@ -253,9 +253,9 @@ private static unsafe uint processRemaining32( [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint round32(uint accn, uint lane) { - accn += lane * prime32v2; + accn += lane * k_Prime32v2; accn = Bits.RotateLeft(accn, 13); - accn *= prime32v1; + accn *= k_Prime32v1; return accn; } @@ -263,9 +263,9 @@ private static uint round32(uint accn, uint lane) private static uint avalanche32(uint acc) { acc ^= acc >> 15; - acc *= prime32v2; + acc *= k_Prime32v2; acc ^= acc >> 13; - acc *= prime32v3; + acc *= k_Prime32v3; acc ^= acc >> 16; return acc; } diff --git a/com.unity.multiplayer.mlapi/Editor/MLAPIProfiler.cs b/com.unity.multiplayer.mlapi/Editor/MLAPIProfiler.cs index 677371f63d..930d7144db 100644 --- a/com.unity.multiplayer.mlapi/Editor/MLAPIProfiler.cs +++ b/com.unity.multiplayer.mlapi/Editor/MLAPIProfiler.cs @@ -16,7 +16,7 @@ public static void ShowWindow() } #endif - GUIStyle wrapStyle + private static GUIStyle s_WrapStyle { get { @@ -28,72 +28,79 @@ GUIStyle wrapStyle } } - float hoverAlpha = 0f; - float updateDelay = 1f; - int captureCount = 100; - float showMax = 0; - float showMin = 0; - AnimationCurve curve = AnimationCurve.Linear(0, 0, 1, 0); - readonly List currentTicks = new List(); - float lastDrawn = 0; - class ProfilerContainer + private float m_HoverAlpha = 0f; + private float m_UpdateDelay = 1f; + private int m_CaptureCount = 100; + private float m_ShowMax = 0; + private float m_ShowMin = 0; + private AnimationCurve m_Curve = AnimationCurve.Linear(0, 0, 1, 0); + private readonly List m_CurrentTicks = new List(); + private float m_LastDrawn = 0; + + private class ProfilerContainer { - public ProfilerTick[] ticks; + public ProfilerTick[] Ticks; public byte[] ToBytes() - { - NetworkBuffer buffer = new NetworkBuffer(); - NetworkWriter writer = new NetworkWriter(buffer); - writer.WriteUInt16Packed((ushort)ticks.Length); - - for (int i = 0; i < ticks.Length; i++) - { - ticks[i].SerializeToStream(buffer); - } - - return buffer.ToArray(); - } - - public static ProfilerContainer FromBytes(byte[] bytes) - { - ProfilerContainer container = new ProfilerContainer(); - NetworkBuffer buffer = new NetworkBuffer(bytes); - NetworkReader reader = new NetworkReader(buffer); - ushort count = reader.ReadUInt16Packed(); - container.ticks = new ProfilerTick[count]; + { + var buffer = new NetworkBuffer(); + var writer = new NetworkWriter(buffer); + + writer.WriteUInt16Packed((ushort)Ticks.Length); + + for (int i = 0; i < Ticks.Length; i++) + { + Ticks[i].SerializeToStream(buffer); + } + + return buffer.ToArray(); + } + + public static ProfilerContainer FromBytes(byte[] bytes) + { + var container = new ProfilerContainer(); + var buffer = new NetworkBuffer(bytes); + var reader = new NetworkReader(buffer); + var count = reader.ReadUInt16Packed(); + + container.Ticks = new ProfilerTick[count]; + for (int i = 0; i < count; i++) - { - container.ticks[i] = ProfilerTick.FromStream(buffer); - } + { + container.Ticks[i] = ProfilerTick.FromStream(buffer); + } - return container; - } - } + return container; + } + } - private void StopRecording() + private void StopRecording() { NetworkProfiler.Stop(); } private void StartRecording() { - if (NetworkProfiler.IsRunning) - StopRecording(); + if (NetworkProfiler.IsRunning) StopRecording(); if (NetworkProfiler.Ticks != null && NetworkProfiler.Ticks.Count >= 2) - curve = AnimationCurve.Constant(NetworkProfiler.Ticks.ElementAt(0).Frame, NetworkProfiler.Ticks.ElementAt(NetworkProfiler.Ticks.Count - 1).Frame, 0); + { + m_Curve = AnimationCurve.Constant(NetworkProfiler.Ticks.ElementAt(0).Frame, NetworkProfiler.Ticks.ElementAt(NetworkProfiler.Ticks.Count - 1).Frame, 0); + } else - curve = AnimationCurve.Constant(0, 1, 0); + { + m_Curve = AnimationCurve.Constant(0, 1, 0); + } - lastDrawn = 0; - NetworkProfiler.Start(captureCount); + m_LastDrawn = 0; + NetworkProfiler.Start(m_CaptureCount); } private void ClearDrawing() { - currentTicks.Clear(); - curve = AnimationCurve.Constant(0, 1, 0); - lastDrawn = 0; + m_CurrentTicks.Clear(); + m_Curve = AnimationCurve.Constant(0, 1, 0); + m_LastDrawn = 0; } private void ChangeRecordState() @@ -102,20 +109,23 @@ private void ChangeRecordState() else StartRecording(); } - TickEvent eventHover = null; - double lastSetup = 0; + private TickEvent m_EventHover = null; + private double m_LastSetup = 0; + private void OnGUI() { bool recording = NetworkProfiler.IsRunning; - float deltaTime = (float)(EditorApplication.timeSinceStartup - lastSetup); - lastSetup = EditorApplication.timeSinceStartup; + float deltaTime = (float)(EditorApplication.timeSinceStartup - m_LastSetup); + + m_LastSetup = EditorApplication.timeSinceStartup; //Draw top bar EditorGUILayout.BeginVertical(); EditorGUILayout.BeginHorizontal(); - if (GUILayout.Button(recording ? "Stop" : "Capture")) ChangeRecordState(); + if (GUILayout.Button(recording ? "Stop" : "Capture")) ChangeRecordState(); if (GUILayout.Button("Clear")) ClearDrawing(); + EditorGUILayout.Space(); EditorGUILayout.Space(); EditorGUILayout.Space(); @@ -125,110 +135,115 @@ private void OnGUI() string path = EditorUtility.OpenFilePanel("Choose a NetworkProfiler file", "", ""); if (!string.IsNullOrEmpty(path)) { - ProfilerTick[] ticks = ProfilerContainer.FromBytes(File.ReadAllBytes(path)).ticks; + var ticks = ProfilerContainer.FromBytes(File.ReadAllBytes(path)).Ticks; if (ticks.Length >= 2) { - curve = AnimationCurve.Constant(ticks[0].EventId, ticks[(ticks.Length - 1)].EventId, 0); - showMax = ticks.Length; - showMin = ticks.Length - Mathf.Clamp(100, 0, ticks.Length); + m_Curve = AnimationCurve.Constant(ticks[0].EventId, ticks[(ticks.Length - 1)].EventId, 0); + m_ShowMax = ticks.Length; + m_ShowMin = ticks.Length - Mathf.Clamp(100, 0, ticks.Length); } else - curve = AnimationCurve.Constant(0, 1, 0); - currentTicks.Clear(); + { + m_Curve = AnimationCurve.Constant(0, 1, 0); + } + + m_CurrentTicks.Clear(); for (int i = 0; i < ticks.Length; i++) { - currentTicks.Add(ticks[i]); + m_CurrentTicks.Add(ticks[i]); uint bytes = 0; if (ticks[i].Events.Count > 0) { for (int j = 0; j < ticks[i].Events.Count; j++) { - TickEvent tickEvent = ticks[i].Events[j]; + var tickEvent = ticks[i].Events[j]; bytes += tickEvent.Bytes; } } - curve.AddKey(ticks[i].EventId, bytes); + + m_Curve.AddKey(ticks[i].EventId, bytes); } } } if (GUILayout.Button("Export datafile")) { - int max = (int)showMax; - int min = (int)showMin; + int max = (int)m_ShowMax; + int min = (int)m_ShowMin; int ticksInRange = max - min; - ProfilerTick[] ticks = new ProfilerTick[ticksInRange]; - for (int i = min; i < max; i++) ticks[i - min] = currentTicks[i]; + var ticks = new ProfilerTick[ticksInRange]; + for (int i = min; i < max; i++) ticks[i - min] = m_CurrentTicks[i]; string path = EditorUtility.SaveFilePanel("Save NetworkProfiler data", "", "networkProfilerData", ""); - if (!string.IsNullOrEmpty(path)) File.WriteAllBytes(path, new ProfilerContainer() { ticks = ticks }.ToBytes()); + if (!string.IsNullOrEmpty(path)) File.WriteAllBytes(path, new ProfilerContainer { Ticks = ticks }.ToBytes()); } EditorGUILayout.EndHorizontal(); - float prevHis = captureCount; - captureCount = EditorGUILayout.DelayedIntField("History count", captureCount); - if (captureCount <= 0) - captureCount = 1; - updateDelay = EditorGUILayout.Slider("Refresh delay", updateDelay, 0.1f, 10f); + float prevHis = m_CaptureCount; + m_CaptureCount = EditorGUILayout.DelayedIntField("History count", m_CaptureCount); + if (m_CaptureCount <= 0) m_CaptureCount = 1; + m_UpdateDelay = EditorGUILayout.Slider("Refresh delay", m_UpdateDelay, 0.1f, 10f); EditorGUILayout.EndVertical(); - if (prevHis != captureCount) StartRecording(); + if (prevHis != m_CaptureCount) StartRecording(); //Cache if (NetworkProfiler.IsRunning) { - if (Time.unscaledTime - lastDrawn > updateDelay) + if (Time.unscaledTime - m_LastDrawn > m_UpdateDelay) { - lastDrawn = Time.unscaledTime; - currentTicks.Clear(); + m_LastDrawn = Time.unscaledTime; + m_CurrentTicks.Clear(); if (NetworkProfiler.Ticks.Count >= 2) - curve = AnimationCurve.Constant(NetworkProfiler.Ticks.ElementAt(0).EventId, NetworkProfiler.Ticks.ElementAt(NetworkProfiler.Ticks.Count - 1).EventId, 0); + { + m_Curve = AnimationCurve.Constant(NetworkProfiler.Ticks.ElementAt(0).EventId, NetworkProfiler.Ticks.ElementAt(NetworkProfiler.Ticks.Count - 1).EventId, 0); + } for (int i = 0; i < NetworkProfiler.Ticks.Count; i++) { - ProfilerTick tick = NetworkProfiler.Ticks.ElementAt(i); - currentTicks.Add(tick); + var tick = NetworkProfiler.Ticks.ElementAt(i); + m_CurrentTicks.Add(tick); uint bytes = 0; if (tick.Events.Count > 0) { for (int j = 0; j < tick.Events.Count; j++) { - TickEvent tickEvent = tick.Events[j]; + var tickEvent = tick.Events[j]; bytes += tickEvent.Bytes; } } - curve.AddKey(tick.EventId, bytes); + + m_Curve.AddKey(tick.EventId, bytes); } } } //Draw Animation curve and slider - curve = EditorGUILayout.CurveField(curve); - EditorGUILayout.MinMaxSlider(ref showMin, ref showMax, 0, currentTicks.Count); + m_Curve = EditorGUILayout.CurveField(m_Curve); + EditorGUILayout.MinMaxSlider(ref m_ShowMin, ref m_ShowMax, 0, m_CurrentTicks.Count); //Verify slider values - if (showMin < 0) - showMin = 0; - if (showMax > currentTicks.Count) - showMax = currentTicks.Count; - if (showMin <= 0 && showMax <= 0) + if (m_ShowMin < 0) m_ShowMin = 0; + if (m_ShowMax > m_CurrentTicks.Count) m_ShowMax = m_CurrentTicks.Count; + if (m_ShowMin <= 0 && m_ShowMax <= 0) { - showMin = 0; - showMax = currentTicks.Count; + m_ShowMin = 0; + m_ShowMax = m_CurrentTicks.Count; } //Draw main board bool hover = false; int nonEmptyTicks = 0; int largestTickCount = 0; - int totalTicks = ((int)showMax - (int)showMin); + int totalTicks = ((int)m_ShowMax - (int)m_ShowMin); - for (int i = (int)showMin; i < (int)showMax; i++) + for (int i = (int)m_ShowMin; i < (int)m_ShowMax; i++) { - if (currentTicks[i].Events.Count > 0) nonEmptyTicks++; //Count non empty ticks - if (currentTicks[i].Events.Count > largestTickCount) largestTickCount = currentTicks[i].Events.Count; //Get how many events the tick with most events has + if (m_CurrentTicks[i].Events.Count > 0) nonEmptyTicks++; //Count non empty ticks + if (m_CurrentTicks[i].Events.Count > largestTickCount) largestTickCount = m_CurrentTicks[i].Events.Count; //Get how many events the tick with most events has } + int emptyTicks = totalTicks - nonEmptyTicks; float equalWidth = position.width / totalTicks; @@ -237,19 +252,20 @@ private void OnGUI() float currentX = 0; int emptyStreak = 0; - for (int i = (int)showMin; i < (int)showMax; i++) + for (int i = (int)m_ShowMin; i < (int)m_ShowMax; i++) { - ProfilerTick tick = currentTicks[i]; + var tick = m_CurrentTicks[i]; if (tick.Events.Count == 0 && i != totalTicks - 1) { emptyStreak++; continue; } - else if (emptyStreak > 0 || i == totalTicks - 1) + + if (emptyStreak > 0 || i == totalTicks - 1) { - Rect dataRect = new Rect(currentX, 140f, propWidth * emptyStreak, position.height - 140f); + var dataRect = new Rect(currentX, 140f, propWidth * emptyStreak, position.height - 140f); currentX += propWidth * emptyStreak; - if (emptyStreak >= 2) EditorGUI.LabelField(new Rect(dataRect.x, dataRect.y, dataRect.width, dataRect.height), emptyStreak.ToString(), wrapStyle); + if (emptyStreak >= 2) EditorGUI.LabelField(new Rect(dataRect.x, dataRect.y, dataRect.width, dataRect.height), emptyStreak.ToString(), s_WrapStyle); emptyStreak = 0; } @@ -260,55 +276,57 @@ private void OnGUI() float currentY = 140f; for (int j = 0; j < tick.Events.Count; j++) { - TickEvent tickEvent = tick.Events[j]; - Rect dataRect = new Rect(currentX, currentY, widthPerTick, heightPerEvent); + var tickEvent = tick.Events[j]; + var dataRect = new Rect(currentX, currentY, widthPerTick, heightPerEvent); if (dataRect.Contains(Event.current.mousePosition)) { hover = true; - eventHover = tickEvent; + m_EventHover = tickEvent; } EditorGUI.DrawRect(dataRect, TickTypeToColor(tickEvent.EventType, true)); - EditorGUI.LabelField(new Rect(dataRect.x, dataRect.y, dataRect.width, dataRect.height / 2), tickEvent.EventType.ToString(), wrapStyle); - EditorGUI.LabelField(new Rect(dataRect.x, dataRect.y + dataRect.height / 2, dataRect.width, dataRect.height / 2), tickEvent.Bytes + "B", wrapStyle); + EditorGUI.LabelField(new Rect(dataRect.x, dataRect.y, dataRect.width, dataRect.height / 2), tickEvent.EventType.ToString(), s_WrapStyle); + EditorGUI.LabelField(new Rect(dataRect.x, dataRect.y + dataRect.height / 2, dataRect.width, dataRect.height / 2), tickEvent.Bytes + "B", s_WrapStyle); currentY += heightPerEvent + 5f; } } + EditorGUI.DrawRect(new Rect(currentX, 100, widthPerTick, 40), TickTypeToColor(tick.Type, false)); - EditorGUI.LabelField(new Rect(currentX, 100, widthPerTick, 20), tick.Type.ToString(), wrapStyle); - EditorGUI.LabelField(new Rect(currentX, 120, widthPerTick, 20), tick.Frame.ToString(), wrapStyle); + EditorGUI.LabelField(new Rect(currentX, 100, widthPerTick, 20), tick.Type.ToString(), s_WrapStyle); + EditorGUI.LabelField(new Rect(currentX, 120, widthPerTick, 20), tick.Frame.ToString(), s_WrapStyle); currentX += widthPerTick; } //Calculate alpha if (hover) { - hoverAlpha += deltaTime * 10f; + m_HoverAlpha += deltaTime * 10f; - if (hoverAlpha > 1f) hoverAlpha = 1f; - else if (hoverAlpha < 0f) hoverAlpha = 0f; + if (m_HoverAlpha > 1f) m_HoverAlpha = 1f; + else if (m_HoverAlpha < 0f) m_HoverAlpha = 0f; } else { - hoverAlpha -= deltaTime * 10f; - if (hoverAlpha > 1f) hoverAlpha = 1f; - else if (hoverAlpha < 0f) hoverAlpha = 0f; + m_HoverAlpha -= deltaTime * 10f; + if (m_HoverAlpha > 1f) m_HoverAlpha = 1f; + else if (m_HoverAlpha < 0f) m_HoverAlpha = 0f; } //Draw hover thingy - if (eventHover != null) + if (m_EventHover != null) { - Rect rect = new Rect(Event.current.mousePosition, new Vector2(500, 100)); - EditorGUI.DrawRect(rect, GetEditorColorWithAlpha(hoverAlpha)); + var rect = new Rect(Event.current.mousePosition, new Vector2(500, 100)); + EditorGUI.DrawRect(rect, GetEditorColorWithAlpha(m_HoverAlpha)); float heightPerField = (rect.height - 5) / 4; - EditorGUI.LabelField(new Rect(rect.x + 5, rect.y + 5, rect.width, rect.height), "EventType: " + eventHover.EventType.ToString(), GetStyleWithTextAlpha(EditorStyles.label, hoverAlpha)); - EditorGUI.LabelField(new Rect(rect.x + 5, rect.y + heightPerField * 1 + 5, rect.width, rect.height), "Size: " + eventHover.Bytes + "B", GetStyleWithTextAlpha(EditorStyles.label, hoverAlpha)); - EditorGUI.LabelField(new Rect(rect.x + 5, rect.y + heightPerField * 2 + 5, rect.width, rect.height), "Channel: " + eventHover.ChannelName, GetStyleWithTextAlpha(EditorStyles.label, hoverAlpha)); - EditorGUI.LabelField(new Rect(rect.x + 5, rect.y + heightPerField * 3 + 5, rect.width, rect.height), "MessageType: " + eventHover.MessageType, GetStyleWithTextAlpha(EditorStyles.label, hoverAlpha)); + EditorGUI.LabelField(new Rect(rect.x + 5, rect.y + 5, rect.width, rect.height), "EventType: " + m_EventHover.EventType, GetStyleWithTextAlpha(EditorStyles.label, m_HoverAlpha)); + EditorGUI.LabelField(new Rect(rect.x + 5, rect.y + heightPerField * 1 + 5, rect.width, rect.height), "Size: " + m_EventHover.Bytes + "B", GetStyleWithTextAlpha(EditorStyles.label, m_HoverAlpha)); + EditorGUI.LabelField(new Rect(rect.x + 5, rect.y + heightPerField * 2 + 5, rect.width, rect.height), "Channel: " + m_EventHover.ChannelName, GetStyleWithTextAlpha(EditorStyles.label, m_HoverAlpha)); + EditorGUI.LabelField(new Rect(rect.x + 5, rect.y + heightPerField * 3 + 5, rect.width, rect.height), "MessageType: " + m_EventHover.MessageType, GetStyleWithTextAlpha(EditorStyles.label, m_HoverAlpha)); } + Repaint(); } @@ -327,18 +345,9 @@ private Color TickTypeToColor(TickType type, bool alpha) } } - private Color EditorColor - { - get - { - return EditorGUIUtility.isProSkin ? new Color32(56, 56, 56, 255) : new Color32(194, 194, 194, 255); - } - } + private Color EditorColor => EditorGUIUtility.isProSkin ? new Color32(56, 56, 56, 255) : new Color32(194, 194, 194, 255); - private Color GetEditorColorWithAlpha(float alpha) - { - return EditorGUIUtility.isProSkin ? new Color(0.22f, 0.22f, 0.22f, alpha) : new Color(0.76f, 0.76f, 0.76f, alpha); - } + private Color GetEditorColorWithAlpha(float alpha) => EditorGUIUtility.isProSkin ? new Color(0.22f, 0.22f, 0.22f, alpha) : new Color(0.76f, 0.76f, 0.76f, alpha); private GUIStyle GetStyleWithTextAlpha(GUIStyle style, float alpha) { @@ -349,5 +358,4 @@ private GUIStyle GetStyleWithTextAlpha(GUIStyle style, float alpha) return newStyle; } } - -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Editor/MLAPIProfilerModule.cs b/com.unity.multiplayer.mlapi/Editor/MLAPIProfilerModule.cs index 2966071aea..456f22364d 100644 --- a/com.unity.multiplayer.mlapi/Editor/MLAPIProfilerModule.cs +++ b/com.unity.multiplayer.mlapi/Editor/MLAPIProfilerModule.cs @@ -11,9 +11,9 @@ namespace MLAPI internal static class MLAPIProfilerModule { #if UNITY_2020_2_OR_NEWER && ENABLE_PROFILER - const string RPCModuleName = "MLAPI RPCs"; - const string OperationModuleName = "MLAPI Operations"; - const string MessageModuleName = "MLAPI Messages"; + private const string k_RpcModuleName = "MLAPI RPCs"; + private const string k_OperationModuleName = "MLAPI Operations"; + private const string k_MessageModuleName = "MLAPI Messages"; /// /// This needs to be in synced with the internal dynamic module structure to provide our own counters @@ -44,28 +44,28 @@ private class MLAPIModules private static List CreateRPCCounters() => new List() { - new MLAPIProfilerCounter() { m_Name = ProfilerConstants.NumberOfRPCsSent, m_Category = ProfilerCategory.Network.Name }, - new MLAPIProfilerCounter() { m_Name = ProfilerConstants.NumberOfRPCsReceived, m_Category = ProfilerCategory.Network.Name }, - new MLAPIProfilerCounter() { m_Name = ProfilerConstants.NumberOfRPCBatchesSent, m_Category = ProfilerCategory.Network.Name }, - new MLAPIProfilerCounter() { m_Name = ProfilerConstants.NumberOfRPCBatchesReceived, m_Category = ProfilerCategory.Network.Name }, - new MLAPIProfilerCounter() { m_Name = ProfilerConstants.NumberOfRPCQueueProcessed, m_Category = ProfilerCategory.Network.Name }, - new MLAPIProfilerCounter() { m_Name = ProfilerConstants.NumberOfRPCsInQueueSize, m_Category = ProfilerCategory.Network.Name }, - new MLAPIProfilerCounter() { m_Name = ProfilerConstants.NumberOfRPCsOutQueueSize, m_Category = ProfilerCategory.Network.Name }, + new MLAPIProfilerCounter { m_Name = ProfilerConstants.NumberOfRPCsSent, m_Category = ProfilerCategory.Network.Name }, + new MLAPIProfilerCounter { m_Name = ProfilerConstants.NumberOfRPCsReceived, m_Category = ProfilerCategory.Network.Name }, + new MLAPIProfilerCounter { m_Name = ProfilerConstants.NumberOfRPCBatchesSent, m_Category = ProfilerCategory.Network.Name }, + new MLAPIProfilerCounter { m_Name = ProfilerConstants.NumberOfRPCBatchesReceived, m_Category = ProfilerCategory.Network.Name }, + new MLAPIProfilerCounter { m_Name = ProfilerConstants.NumberOfRPCQueueProcessed, m_Category = ProfilerCategory.Network.Name }, + new MLAPIProfilerCounter { m_Name = ProfilerConstants.NumberOfRPCsInQueueSize, m_Category = ProfilerCategory.Network.Name }, + new MLAPIProfilerCounter { m_Name = ProfilerConstants.NumberOfRPCsOutQueueSize, m_Category = ProfilerCategory.Network.Name }, }; private static List CreateOperationsCounters() => new List() { - new MLAPIProfilerCounter() { m_Name = ProfilerConstants.NumberOfConnections, m_Category = ProfilerCategory.Network.Name }, - new MLAPIProfilerCounter() { m_Name = ProfilerConstants.ReceiveTickRate, m_Category = ProfilerCategory.Network.Name }, + new MLAPIProfilerCounter { m_Name = ProfilerConstants.NumberOfConnections, m_Category = ProfilerCategory.Network.Name }, + new MLAPIProfilerCounter { m_Name = ProfilerConstants.ReceiveTickRate, m_Category = ProfilerCategory.Network.Name }, }; private static List CreateMessagesCounters() => new List() { - new MLAPIProfilerCounter() { m_Name = ProfilerConstants.NumberOfNamedMessages, m_Category = ProfilerCategory.Network.Name }, - new MLAPIProfilerCounter() { m_Name = ProfilerConstants.NumberOfUnnamedMessages, m_Category = ProfilerCategory.Network.Name }, - new MLAPIProfilerCounter() { m_Name = ProfilerConstants.NumberBytesSent, m_Category = ProfilerCategory.Network.Name }, - new MLAPIProfilerCounter() { m_Name = ProfilerConstants.NumberBytesReceived, m_Category = ProfilerCategory.Network.Name }, - new MLAPIProfilerCounter() { m_Name = ProfilerConstants.NumberNetworkVarsReceived, m_Category = ProfilerCategory.Network.Name }, + new MLAPIProfilerCounter { m_Name = ProfilerConstants.NumberOfNamedMessages, m_Category = ProfilerCategory.Network.Name }, + new MLAPIProfilerCounter { m_Name = ProfilerConstants.NumberOfUnnamedMessages, m_Category = ProfilerCategory.Network.Name }, + new MLAPIProfilerCounter { m_Name = ProfilerConstants.NumberBytesSent, m_Category = ProfilerCategory.Network.Name }, + new MLAPIProfilerCounter { m_Name = ProfilerConstants.NumberBytesReceived, m_Category = ProfilerCategory.Network.Name }, + new MLAPIProfilerCounter { m_Name = ProfilerConstants.NumberNetworkVarsReceived, m_Category = ProfilerCategory.Network.Name }, }; private delegate List CounterListFactoryDelegate(); @@ -91,14 +91,14 @@ static MLAPIProfilerModule() { #if UNITY_2020_2_OR_NEWER && ENABLE_PROFILER var dynamicModulesJson = EditorPrefs.GetString("ProfilerWindow.DynamicModules"); - var dynamicModules = JsonUtility.FromJson(dynamicModulesJson); if (dynamicModules != null) { - bool wasCreated = CreateMLAPIDynamicModule(ref dynamicModules, RPCModuleName, CreateRPCCounters); - wasCreated |= CreateMLAPIDynamicModule(ref dynamicModules, OperationModuleName, CreateOperationsCounters); - wasCreated |= CreateMLAPIDynamicModule(ref dynamicModules, MessageModuleName, CreateMessagesCounters); + bool wasCreated = CreateMLAPIDynamicModule(ref dynamicModules, k_RpcModuleName, CreateRPCCounters); + wasCreated |= CreateMLAPIDynamicModule(ref dynamicModules, k_OperationModuleName, CreateOperationsCounters); + wasCreated |= CreateMLAPIDynamicModule(ref dynamicModules, k_MessageModuleName, CreateMessagesCounters); + if (wasCreated) { EditorPrefs.SetString("ProfilerWindow.DynamicModules", JsonUtility.ToJson(dynamicModules)); @@ -106,7 +106,5 @@ static MLAPIProfilerModule() } #endif } - - } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Editor/NetworkBehaviourEditor.cs b/com.unity.multiplayer.mlapi/Editor/NetworkBehaviourEditor.cs index 1bf9d62665..c67a772a0f 100644 --- a/com.unity.multiplayer.mlapi/Editor/NetworkBehaviourEditor.cs +++ b/com.unity.multiplayer.mlapi/Editor/NetworkBehaviourEditor.cs @@ -11,114 +11,102 @@ namespace UnityEditor [CanEditMultipleObjects] public class NetworkBehaviourEditor : Editor { - private bool initialized; - private readonly List networkVariableNames = new List(); - private readonly Dictionary networkVariableFields = new Dictionary(); - private readonly Dictionary networkVariableObjects = new Dictionary(); + private bool m_Initialized; + private readonly List m_NetworkVariableNames = new List(); + private readonly Dictionary m_NetworkVariableFields = new Dictionary(); + private readonly Dictionary m_NetworkVariableObjects = new Dictionary(); - private GUIContent networkVariableLabelGuiContent; + private GUIContent m_NetworkVariableLabelGuiContent; private void Init(MonoScript script) { - initialized = true; - - networkVariableNames.Clear(); - networkVariableFields.Clear(); - networkVariableObjects.Clear(); + m_Initialized = true; - networkVariableLabelGuiContent = new GUIContent("NetworkVariable", "This variable is a NetworkVariable. It can not be serialized and can only be changed during runtime."); + m_NetworkVariableNames.Clear(); + m_NetworkVariableFields.Clear(); + m_NetworkVariableObjects.Clear(); - FieldInfo[] fields = script.GetClass().GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy); + m_NetworkVariableLabelGuiContent = new GUIContent("NetworkVariable", "This variable is a NetworkVariable. It can not be serialized and can only be changed during runtime."); + + var fields = script.GetClass().GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy); for (int i = 0; i < fields.Length; i++) { - Type ft = fields[i].FieldType; + var ft = fields[i].FieldType; if (ft.IsGenericType && ft.GetGenericTypeDefinition() == typeof(NetworkVariable<>) && !fields[i].IsDefined(typeof(HideInInspector), true)) { - networkVariableNames.Add(fields[i].Name); - networkVariableFields.Add(fields[i].Name, fields[i]); + m_NetworkVariableNames.Add(fields[i].Name); + m_NetworkVariableFields.Add(fields[i].Name, fields[i]); } } } - void RenderNetworkVariable(int index) + private void RenderNetworkVariable(int index) { - if (!networkVariableFields.ContainsKey(networkVariableNames[index])) + if (!m_NetworkVariableFields.ContainsKey(m_NetworkVariableNames[index])) { serializedObject.Update(); - SerializedProperty scriptProperty = serializedObject.FindProperty("m_Script"); - if (scriptProperty == null) - return; + var scriptProperty = serializedObject.FindProperty("m_Script"); + if (scriptProperty == null) return; - MonoScript targetScript = scriptProperty.objectReferenceValue as MonoScript; + var targetScript = scriptProperty.objectReferenceValue as MonoScript; Init(targetScript); } - object value = networkVariableFields[networkVariableNames[index]].GetValue(target); + object value = m_NetworkVariableFields[m_NetworkVariableNames[index]].GetValue(target); if (value == null) { - Type fieldType = networkVariableFields[networkVariableNames[index]].FieldType; - INetworkVariable var = (INetworkVariable) Activator.CreateInstance(fieldType, true); - networkVariableFields[networkVariableNames[index]].SetValue(target, var); + var fieldType = m_NetworkVariableFields[m_NetworkVariableNames[index]].FieldType; + var networkVariable = (INetworkVariable)Activator.CreateInstance(fieldType, true); + m_NetworkVariableFields[m_NetworkVariableNames[index]].SetValue(target, networkVariable); } - - Type type = networkVariableFields[networkVariableNames[index]].GetValue(target).GetType(); - Type genericType = type.GetGenericArguments()[0]; + + var type = m_NetworkVariableFields[m_NetworkVariableNames[index]].GetValue(target).GetType(); + var genericType = type.GetGenericArguments()[0]; EditorGUILayout.BeginHorizontal(); if (genericType == typeof(string)) { - NetworkVariable var = (NetworkVariable)networkVariableFields[networkVariableNames[index]].GetValue(target); - var.Value = EditorGUILayout.TextField(networkVariableNames[index], var.Value); + var networkVariable = (NetworkVariable)m_NetworkVariableFields[m_NetworkVariableNames[index]].GetValue(target); + networkVariable.Value = EditorGUILayout.TextField(m_NetworkVariableNames[index], networkVariable.Value); } else if (genericType.IsValueType) { - MethodInfo method = typeof(NetworkBehaviourEditor).GetMethod("RenderNetworkVariableValueType", BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.NonPublic); - MethodInfo genericMethod = method.MakeGenericMethod(genericType); + var method = typeof(NetworkBehaviourEditor).GetMethod("RenderNetworkVariableValueType", BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.NonPublic); + var genericMethod = method.MakeGenericMethod(genericType); genericMethod.Invoke(this, new[] { (object)index }); } else { EditorGUILayout.LabelField("Type not renderable"); } - GUILayout.Label(networkVariableLabelGuiContent, EditorStyles.miniLabel, GUILayout.Width(EditorStyles.miniLabel.CalcSize(networkVariableLabelGuiContent).x)); + + GUILayout.Label(m_NetworkVariableLabelGuiContent, EditorStyles.miniLabel, GUILayout.Width(EditorStyles.miniLabel.CalcSize(m_NetworkVariableLabelGuiContent).x)); EditorGUILayout.EndHorizontal(); } - void RenderNetworkVariableValueType(int index) where T : struct + private void RenderNetworkVariableValueType(int index) where T : struct { - NetworkVariable var = (NetworkVariable)networkVariableFields[networkVariableNames[index]].GetValue(target); - Type type = typeof(T); - object val = var.Value; - string name = networkVariableNames[index]; + var networkVariable = (NetworkVariable)m_NetworkVariableFields[m_NetworkVariableNames[index]].GetValue(target); + var type = typeof(T); + object val = networkVariable.Value; + string name = m_NetworkVariableNames[index]; if (NetworkManager.Singleton != null && NetworkManager.Singleton.IsListening) { - if (type == typeof(int)) - val = EditorGUILayout.IntField(name, (int)val); - else if (type == typeof(uint)) - val = (uint)EditorGUILayout.LongField(name, (long)((uint)val)); - else if (type == typeof(short)) - val = (short)EditorGUILayout.IntField(name, (int)((short)val)); - else if (type == typeof(ushort)) - val = (ushort)EditorGUILayout.IntField(name, (int)((ushort)val)); - else if (type == typeof(sbyte)) - val = (sbyte)EditorGUILayout.IntField(name, (int)((sbyte)val)); - else if (type == typeof(byte)) - val = (byte)EditorGUILayout.IntField(name, (int)((byte)val)); - else if (type == typeof(long)) - val = EditorGUILayout.LongField(name, (long)val); - else if (type == typeof(ulong)) - val = (ulong)EditorGUILayout.LongField(name, (long)((ulong)val)); - else if (type == typeof(bool)) - val = EditorGUILayout.Toggle(name, (bool)val); - else if (type == typeof(string)) - val = EditorGUILayout.TextField(name, (string)val); - else if (type.IsEnum) - val = EditorGUILayout.EnumPopup(name, (Enum) val); - else - EditorGUILayout.LabelField("Type not renderable"); - - var.Value = (T)val; + if (type == typeof(int)) val = EditorGUILayout.IntField(name, (int)val); + else if (type == typeof(uint)) val = (uint)EditorGUILayout.LongField(name, (long)((uint)val)); + else if (type == typeof(short)) val = (short)EditorGUILayout.IntField(name, (int)((short)val)); + else if (type == typeof(ushort)) val = (ushort)EditorGUILayout.IntField(name, (int)((ushort)val)); + else if (type == typeof(sbyte)) val = (sbyte)EditorGUILayout.IntField(name, (int)((sbyte)val)); + else if (type == typeof(byte)) val = (byte)EditorGUILayout.IntField(name, (int)((byte)val)); + else if (type == typeof(long)) val = EditorGUILayout.LongField(name, (long)val); + else if (type == typeof(ulong)) val = (ulong)EditorGUILayout.LongField(name, (long)((ulong)val)); + else if (type == typeof(bool)) val = EditorGUILayout.Toggle(name, (bool)val); + else if (type == typeof(string)) val = EditorGUILayout.TextField(name, (string)val); + else if (type.IsEnum) val = EditorGUILayout.EnumPopup(name, (Enum)val); + else EditorGUILayout.LabelField("Type not renderable"); + + networkVariable.Value = (T)val; } else { @@ -129,36 +117,35 @@ void RenderNetworkVariableValueType(int index) where T : struct public override void OnInspectorGUI() { - if (!initialized) + if (!m_Initialized) { serializedObject.Update(); - SerializedProperty scriptProperty = serializedObject.FindProperty("m_Script"); - if (scriptProperty == null) - return; + var scriptProperty = serializedObject.FindProperty("m_Script"); + if (scriptProperty == null) return; - MonoScript targetScript = scriptProperty.objectReferenceValue as MonoScript; + var targetScript = scriptProperty.objectReferenceValue as MonoScript; Init(targetScript); } EditorGUI.BeginChangeCheck(); serializedObject.Update(); - for (int i = 0; i < networkVariableNames.Count; i++) + for (int i = 0; i < m_NetworkVariableNames.Count; i++) + { RenderNetworkVariable(i); + } - SerializedProperty property = serializedObject.GetIterator(); + var property = serializedObject.GetIterator(); bool expanded = true; while (property.NextVisible(expanded)) { if (property.propertyType == SerializedPropertyType.ObjectReference) { - if (property.name == "m_Script") - EditorGUI.BeginDisabledGroup(true); + if (property.name == "m_Script") EditorGUI.BeginDisabledGroup(true); EditorGUILayout.PropertyField(property, true); - - if (property.name == "m_Script") - EditorGUI.EndDisabledGroup(); + + if (property.name == "m_Script") EditorGUI.EndDisabledGroup(); } else { @@ -166,10 +153,12 @@ public override void OnInspectorGUI() EditorGUILayout.PropertyField(property, true); EditorGUILayout.EndHorizontal(); } + expanded = false; } + serializedObject.ApplyModifiedProperties(); EditorGUI.EndChangeCheck(); } } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Editor/NetworkManagerEditor.cs b/com.unity.multiplayer.mlapi/Editor/NetworkManagerEditor.cs index 341be3f568..e4d9bd9f48 100644 --- a/com.unity.multiplayer.mlapi/Editor/NetworkManagerEditor.cs +++ b/com.unity.multiplayer.mlapi/Editor/NetworkManagerEditor.cs @@ -12,115 +12,113 @@ public class NetworkManagerEditor : Editor { // Properties - private SerializedProperty dontDestroyOnLoadProperty; - private SerializedProperty runInBackgroundProperty; - private SerializedProperty logLevelProperty; + private SerializedProperty m_DontDestroyOnLoadProperty; + private SerializedProperty m_RunInBackgroundProperty; + private SerializedProperty m_LogLevelProperty; // NetworkConfig - private SerializedProperty networkConfigProperty; + private SerializedProperty m_NetworkConfigProperty; // NetworkConfig fields - private SerializedProperty protocolVersionProperty; - private SerializedProperty allowRuntimeSceneChangesProperty; - private SerializedProperty networkTransportProperty; - private SerializedProperty receiveTickrateProperty; - private SerializedProperty maxReceiveEventsPerTickRateProperty; - private SerializedProperty eventTickrateProperty; - private SerializedProperty maxObjectUpdatesPerTickProperty; - private SerializedProperty clientConnectionBufferTimeoutProperty; - private SerializedProperty connectionApprovalProperty; - private SerializedProperty secondsHistoryProperty; - private SerializedProperty enableTimeResyncProperty; - private SerializedProperty timeResyncIntervalProperty; - private SerializedProperty enableNetworkVariableProperty; - private SerializedProperty ensureNetworkVariableLengthSafetyProperty; - private SerializedProperty createPlayerPrefabProperty; - private SerializedProperty forceSamePrefabsProperty; - private SerializedProperty usePrefabSyncProperty; - private SerializedProperty enableSceneManagementProperty; - private SerializedProperty recycleNetworkIdsProperty; - private SerializedProperty networkIdRecycleDelayProperty; - private SerializedProperty rpcHashSizeProperty; - private SerializedProperty loadSceneTimeOutProperty; - private SerializedProperty enableMessageBufferingProperty; - private SerializedProperty messageBufferTimeoutProperty; - - private ReorderableList networkPrefabsList; - private ReorderableList registeredScenesList; - - private NetworkManager networkManager; - private bool initialized; - - private readonly List transportTypes = new List(); - private string[] transportNames = { "Select transport..." }; + private SerializedProperty m_ProtocolVersionProperty; + private SerializedProperty m_AllowRuntimeSceneChangesProperty; + private SerializedProperty m_NetworkTransportProperty; + private SerializedProperty m_ReceiveTickrateProperty; + private SerializedProperty m_MaxReceiveEventsPerTickRateProperty; + private SerializedProperty m_EventTickrateProperty; + private SerializedProperty m_MaxObjectUpdatesPerTickProperty; + private SerializedProperty m_ClientConnectionBufferTimeoutProperty; + private SerializedProperty m_ConnectionApprovalProperty; + private SerializedProperty m_SecondsHistoryProperty; + private SerializedProperty m_EnableTimeResyncProperty; + private SerializedProperty m_TimeResyncIntervalProperty; + private SerializedProperty m_EnableNetworkVariableProperty; + private SerializedProperty m_EnsureNetworkVariableLengthSafetyProperty; + private SerializedProperty m_CreatePlayerPrefabProperty; + private SerializedProperty m_ForceSamePrefabsProperty; + private SerializedProperty m_UsePrefabSyncProperty; + private SerializedProperty m_EnableSceneManagementProperty; + private SerializedProperty m_RecycleNetworkIdsProperty; + private SerializedProperty m_NetworkIdRecycleDelayProperty; + private SerializedProperty m_RpcHashSizeProperty; + private SerializedProperty m_LoadSceneTimeOutProperty; + private SerializedProperty m_EnableMessageBufferingProperty; + private SerializedProperty m_MessageBufferTimeoutProperty; + + private ReorderableList m_NetworkPrefabsList; + private ReorderableList m_RegisteredScenesList; + + private NetworkManager m_NetworkManager; + private bool m_Initialized; + + private readonly List m_TransportTypes = new List(); + private string[] m_TransportNames = { "Select transport..." }; private void ReloadTransports() { - transportTypes.Clear(); + m_TransportTypes.Clear(); - Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); + var assemblies = AppDomain.CurrentDomain.GetAssemblies(); - foreach (Assembly assembly in assemblies) + foreach (var assembly in assemblies) { - Type[] types = assembly.GetTypes(); + var types = assembly.GetTypes(); - foreach (Type type in types) + foreach (var type in types) { if (type.IsSubclassOf(typeof(NetworkTransport))) { - transportTypes.Add(type); + m_TransportTypes.Add(type); } } } - transportNames = new string[transportTypes.Count + 1]; + m_TransportNames = new string[m_TransportTypes.Count + 1]; + m_TransportNames[0] = "Select transport..."; - transportNames[0] = "Select transport..."; - - for (int i = 0; i < transportTypes.Count; i++) + for (int i = 0; i < m_TransportTypes.Count; i++) { - transportNames[i + 1] = transportTypes[i].Name; + m_TransportNames[i + 1] = m_TransportTypes[i].Name; } } private void Init() { - if (initialized) - return; + if (m_Initialized) return; - initialized = true; - networkManager = (NetworkManager)target; + m_Initialized = true; + m_NetworkManager = (NetworkManager)target; // Base properties - dontDestroyOnLoadProperty = serializedObject.FindProperty("DontDestroy"); - runInBackgroundProperty = serializedObject.FindProperty("RunInBackground"); - logLevelProperty = serializedObject.FindProperty("LogLevel"); - networkConfigProperty = serializedObject.FindProperty("NetworkConfig"); + m_DontDestroyOnLoadProperty = serializedObject.FindProperty("DontDestroy"); + m_RunInBackgroundProperty = serializedObject.FindProperty("RunInBackground"); + m_LogLevelProperty = serializedObject.FindProperty("LogLevel"); + m_NetworkConfigProperty = serializedObject.FindProperty("NetworkConfig"); // NetworkConfig properties - protocolVersionProperty = networkConfigProperty.FindPropertyRelative("ProtocolVersion"); - allowRuntimeSceneChangesProperty = networkConfigProperty.FindPropertyRelative("AllowRuntimeSceneChanges"); - networkTransportProperty = networkConfigProperty.FindPropertyRelative("NetworkTransport"); - receiveTickrateProperty = networkConfigProperty.FindPropertyRelative("ReceiveTickrate"); - maxReceiveEventsPerTickRateProperty = networkConfigProperty.FindPropertyRelative("MaxReceiveEventsPerTickRate"); - eventTickrateProperty = networkConfigProperty.FindPropertyRelative("EventTickrate"); - clientConnectionBufferTimeoutProperty = networkConfigProperty.FindPropertyRelative("ClientConnectionBufferTimeout"); - connectionApprovalProperty = networkConfigProperty.FindPropertyRelative("ConnectionApproval"); - secondsHistoryProperty = networkConfigProperty.FindPropertyRelative("SecondsHistory"); - enableTimeResyncProperty = networkConfigProperty.FindPropertyRelative("EnableTimeResync"); - timeResyncIntervalProperty = networkConfigProperty.FindPropertyRelative("TimeResyncInterval"); - enableNetworkVariableProperty = networkConfigProperty.FindPropertyRelative("EnableNetworkVariable"); - ensureNetworkVariableLengthSafetyProperty = networkConfigProperty.FindPropertyRelative("EnsureNetworkVariableLengthSafety"); - createPlayerPrefabProperty = networkConfigProperty.FindPropertyRelative("CreatePlayerPrefab"); - forceSamePrefabsProperty = networkConfigProperty.FindPropertyRelative("ForceSamePrefabs"); - usePrefabSyncProperty = networkConfigProperty.FindPropertyRelative("UsePrefabSync"); - enableSceneManagementProperty = networkConfigProperty.FindPropertyRelative("EnableSceneManagement"); - recycleNetworkIdsProperty = networkConfigProperty.FindPropertyRelative("RecycleNetworkIds"); - networkIdRecycleDelayProperty = networkConfigProperty.FindPropertyRelative("NetworkIdRecycleDelay"); - rpcHashSizeProperty = networkConfigProperty.FindPropertyRelative("RpcHashSize"); - loadSceneTimeOutProperty = networkConfigProperty.FindPropertyRelative("LoadSceneTimeOut"); - enableMessageBufferingProperty = networkConfigProperty.FindPropertyRelative("EnableMessageBuffering"); - messageBufferTimeoutProperty = networkConfigProperty.FindPropertyRelative("MessageBufferTimeout"); + m_ProtocolVersionProperty = m_NetworkConfigProperty.FindPropertyRelative("ProtocolVersion"); + m_AllowRuntimeSceneChangesProperty = m_NetworkConfigProperty.FindPropertyRelative("AllowRuntimeSceneChanges"); + m_NetworkTransportProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTransport"); + m_ReceiveTickrateProperty = m_NetworkConfigProperty.FindPropertyRelative("ReceiveTickrate"); + m_MaxReceiveEventsPerTickRateProperty = m_NetworkConfigProperty.FindPropertyRelative("MaxReceiveEventsPerTickRate"); + m_EventTickrateProperty = m_NetworkConfigProperty.FindPropertyRelative("EventTickrate"); + m_ClientConnectionBufferTimeoutProperty = m_NetworkConfigProperty.FindPropertyRelative("ClientConnectionBufferTimeout"); + m_ConnectionApprovalProperty = m_NetworkConfigProperty.FindPropertyRelative("ConnectionApproval"); + m_SecondsHistoryProperty = m_NetworkConfigProperty.FindPropertyRelative("SecondsHistory"); + m_EnableTimeResyncProperty = m_NetworkConfigProperty.FindPropertyRelative("EnableTimeResync"); + m_TimeResyncIntervalProperty = m_NetworkConfigProperty.FindPropertyRelative("TimeResyncInterval"); + m_EnableNetworkVariableProperty = m_NetworkConfigProperty.FindPropertyRelative("EnableNetworkVariable"); + m_EnsureNetworkVariableLengthSafetyProperty = m_NetworkConfigProperty.FindPropertyRelative("EnsureNetworkVariableLengthSafety"); + m_CreatePlayerPrefabProperty = m_NetworkConfigProperty.FindPropertyRelative("CreatePlayerPrefab"); + m_ForceSamePrefabsProperty = m_NetworkConfigProperty.FindPropertyRelative("ForceSamePrefabs"); + m_UsePrefabSyncProperty = m_NetworkConfigProperty.FindPropertyRelative("UsePrefabSync"); + m_EnableSceneManagementProperty = m_NetworkConfigProperty.FindPropertyRelative("EnableSceneManagement"); + m_RecycleNetworkIdsProperty = m_NetworkConfigProperty.FindPropertyRelative("RecycleNetworkIds"); + m_NetworkIdRecycleDelayProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkIdRecycleDelay"); + m_RpcHashSizeProperty = m_NetworkConfigProperty.FindPropertyRelative("RpcHashSize"); + m_LoadSceneTimeOutProperty = m_NetworkConfigProperty.FindPropertyRelative("LoadSceneTimeOut"); + m_EnableMessageBufferingProperty = m_NetworkConfigProperty.FindPropertyRelative("EnableMessageBuffering"); + m_MessageBufferTimeoutProperty = m_NetworkConfigProperty.FindPropertyRelative("MessageBufferTimeout"); ReloadTransports(); @@ -129,43 +127,43 @@ private void Init() private void CheckNullProperties() { // Base properties - dontDestroyOnLoadProperty = serializedObject.FindProperty("DontDestroy"); - runInBackgroundProperty = serializedObject.FindProperty("RunInBackground"); - logLevelProperty = serializedObject.FindProperty("LogLevel"); - networkConfigProperty = serializedObject.FindProperty("NetworkConfig"); + m_DontDestroyOnLoadProperty = serializedObject.FindProperty("DontDestroy"); + m_RunInBackgroundProperty = serializedObject.FindProperty("RunInBackground"); + m_LogLevelProperty = serializedObject.FindProperty("LogLevel"); + m_NetworkConfigProperty = serializedObject.FindProperty("NetworkConfig"); // NetworkConfig properties - protocolVersionProperty = networkConfigProperty.FindPropertyRelative("ProtocolVersion"); - allowRuntimeSceneChangesProperty = networkConfigProperty.FindPropertyRelative("AllowRuntimeSceneChanges"); - networkTransportProperty = networkConfigProperty.FindPropertyRelative("NetworkTransport"); - receiveTickrateProperty = networkConfigProperty.FindPropertyRelative("ReceiveTickrate"); - maxReceiveEventsPerTickRateProperty = networkConfigProperty.FindPropertyRelative("MaxReceiveEventsPerTickRate"); - eventTickrateProperty = networkConfigProperty.FindPropertyRelative("EventTickrate"); - clientConnectionBufferTimeoutProperty = networkConfigProperty.FindPropertyRelative("ClientConnectionBufferTimeout"); - connectionApprovalProperty = networkConfigProperty.FindPropertyRelative("ConnectionApproval"); - secondsHistoryProperty = networkConfigProperty.FindPropertyRelative("SecondsHistory"); - enableTimeResyncProperty = networkConfigProperty.FindPropertyRelative("EnableTimeResync"); - timeResyncIntervalProperty = networkConfigProperty.FindPropertyRelative("TimeResyncInterval"); - enableNetworkVariableProperty = networkConfigProperty.FindPropertyRelative("EnableNetworkVariable"); - ensureNetworkVariableLengthSafetyProperty = networkConfigProperty.FindPropertyRelative("EnsureNetworkVariableLengthSafety"); - createPlayerPrefabProperty = networkConfigProperty.FindPropertyRelative("CreatePlayerPrefab"); - forceSamePrefabsProperty = networkConfigProperty.FindPropertyRelative("ForceSamePrefabs"); - usePrefabSyncProperty = networkConfigProperty.FindPropertyRelative("UsePrefabSync"); - enableSceneManagementProperty = networkConfigProperty.FindPropertyRelative("EnableSceneManagement"); - recycleNetworkIdsProperty = networkConfigProperty.FindPropertyRelative("RecycleNetworkIds"); - networkIdRecycleDelayProperty = networkConfigProperty.FindPropertyRelative("NetworkIdRecycleDelay"); - rpcHashSizeProperty = networkConfigProperty.FindPropertyRelative("RpcHashSize"); - loadSceneTimeOutProperty = networkConfigProperty.FindPropertyRelative("LoadSceneTimeOut"); - enableMessageBufferingProperty = networkConfigProperty.FindPropertyRelative("EnableMessageBuffering"); - messageBufferTimeoutProperty = networkConfigProperty.FindPropertyRelative("MessageBufferTimeout"); + m_ProtocolVersionProperty = m_NetworkConfigProperty.FindPropertyRelative("ProtocolVersion"); + m_AllowRuntimeSceneChangesProperty = m_NetworkConfigProperty.FindPropertyRelative("AllowRuntimeSceneChanges"); + m_NetworkTransportProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTransport"); + m_ReceiveTickrateProperty = m_NetworkConfigProperty.FindPropertyRelative("ReceiveTickrate"); + m_MaxReceiveEventsPerTickRateProperty = m_NetworkConfigProperty.FindPropertyRelative("MaxReceiveEventsPerTickRate"); + m_EventTickrateProperty = m_NetworkConfigProperty.FindPropertyRelative("EventTickrate"); + m_ClientConnectionBufferTimeoutProperty = m_NetworkConfigProperty.FindPropertyRelative("ClientConnectionBufferTimeout"); + m_ConnectionApprovalProperty = m_NetworkConfigProperty.FindPropertyRelative("ConnectionApproval"); + m_SecondsHistoryProperty = m_NetworkConfigProperty.FindPropertyRelative("SecondsHistory"); + m_EnableTimeResyncProperty = m_NetworkConfigProperty.FindPropertyRelative("EnableTimeResync"); + m_TimeResyncIntervalProperty = m_NetworkConfigProperty.FindPropertyRelative("TimeResyncInterval"); + m_EnableNetworkVariableProperty = m_NetworkConfigProperty.FindPropertyRelative("EnableNetworkVariable"); + m_EnsureNetworkVariableLengthSafetyProperty = m_NetworkConfigProperty.FindPropertyRelative("EnsureNetworkVariableLengthSafety"); + m_CreatePlayerPrefabProperty = m_NetworkConfigProperty.FindPropertyRelative("CreatePlayerPrefab"); + m_ForceSamePrefabsProperty = m_NetworkConfigProperty.FindPropertyRelative("ForceSamePrefabs"); + m_UsePrefabSyncProperty = m_NetworkConfigProperty.FindPropertyRelative("UsePrefabSync"); + m_EnableSceneManagementProperty = m_NetworkConfigProperty.FindPropertyRelative("EnableSceneManagement"); + m_RecycleNetworkIdsProperty = m_NetworkConfigProperty.FindPropertyRelative("RecycleNetworkIds"); + m_NetworkIdRecycleDelayProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkIdRecycleDelay"); + m_RpcHashSizeProperty = m_NetworkConfigProperty.FindPropertyRelative("RpcHashSize"); + m_LoadSceneTimeOutProperty = m_NetworkConfigProperty.FindPropertyRelative("LoadSceneTimeOut"); + m_EnableMessageBufferingProperty = m_NetworkConfigProperty.FindPropertyRelative("EnableMessageBuffering"); + m_MessageBufferTimeoutProperty = m_NetworkConfigProperty.FindPropertyRelative("MessageBufferTimeout"); } private void OnEnable() { - networkPrefabsList = new ReorderableList(serializedObject, serializedObject.FindProperty("NetworkConfig").FindPropertyRelative("NetworkPrefabs"), true, true, true, true); - networkPrefabsList.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => + m_NetworkPrefabsList = new ReorderableList(serializedObject, serializedObject.FindProperty("NetworkConfig").FindPropertyRelative("NetworkPrefabs"), true, true, true, true); + m_NetworkPrefabsList.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => { - SerializedProperty element = networkPrefabsList.serializedProperty.GetArrayElementAtIndex(index); + var element = m_NetworkPrefabsList.serializedProperty.GetArrayElementAtIndex(index); int firstLabelWidth = 50; int secondLabelWidth = 140; float secondFieldWidth = 10; @@ -179,9 +177,9 @@ private void OnEnable() int playerPrefabIndex = -1; - for (int i = 0; i < networkManager.NetworkConfig.NetworkPrefabs.Count; i++) + for (int i = 0; i < m_NetworkManager.NetworkConfig.NetworkPrefabs.Count; i++) { - if (networkManager.NetworkConfig.NetworkPrefabs[i].PlayerPrefab) + if (m_NetworkManager.NetworkConfig.NetworkPrefabs[i].PlayerPrefab) { playerPrefabIndex = i; break; @@ -195,27 +193,22 @@ private void OnEnable() } }; - networkPrefabsList.drawHeaderCallback = (Rect rect) => { - EditorGUI.LabelField(rect, "NetworkPrefabs"); - }; + m_NetworkPrefabsList.drawHeaderCallback = (Rect rect) => { EditorGUI.LabelField(rect, "NetworkPrefabs"); }; - registeredScenesList = new ReorderableList(serializedObject, serializedObject.FindProperty("NetworkConfig").FindPropertyRelative("RegisteredScenes"), true, true, true, true); - registeredScenesList.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => + m_RegisteredScenesList = new ReorderableList(serializedObject, serializedObject.FindProperty("NetworkConfig").FindPropertyRelative("RegisteredScenes"), true, true, true, true); + m_RegisteredScenesList.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => { - SerializedProperty element = registeredScenesList.serializedProperty.GetArrayElementAtIndex(index); + var element = m_RegisteredScenesList.serializedProperty.GetArrayElementAtIndex(index); int firstLabelWidth = 50; int padding = 20; EditorGUI.LabelField(new Rect(rect.x, rect.y, firstLabelWidth, EditorGUIUtility.singleLineHeight), "Name"); EditorGUI.PropertyField(new Rect(rect.x + firstLabelWidth, rect.y, rect.width - firstLabelWidth - padding, EditorGUIUtility.singleLineHeight), element, GUIContent.none); - }; - registeredScenesList.drawHeaderCallback = (Rect rect) => { - EditorGUI.LabelField(rect, "Registered Scene Names"); - }; + m_RegisteredScenesList.drawHeaderCallback = (Rect rect) => { EditorGUI.LabelField(rect, "Registered Scene Names"); }; } public override void OnInspectorGUI() @@ -224,7 +217,7 @@ public override void OnInspectorGUI() CheckNullProperties(); { - SerializedProperty iterator = serializedObject.GetIterator(); + var iterator = serializedObject.GetIterator(); for (bool enterChildren = true; iterator.NextVisible(enterChildren); enterChildren = false) { @@ -236,130 +229,130 @@ public override void OnInspectorGUI() } - if (!networkManager.IsServer && !networkManager.IsClient) + if (!m_NetworkManager.IsServer && !m_NetworkManager.IsClient) { serializedObject.Update(); - EditorGUILayout.PropertyField(dontDestroyOnLoadProperty); - EditorGUILayout.PropertyField(runInBackgroundProperty); - EditorGUILayout.PropertyField(logLevelProperty); + EditorGUILayout.PropertyField(m_DontDestroyOnLoadProperty); + EditorGUILayout.PropertyField(m_RunInBackgroundProperty); + EditorGUILayout.PropertyField(m_LogLevelProperty); EditorGUILayout.Space(); - networkPrefabsList.DoLayoutList(); + m_NetworkPrefabsList.DoLayoutList(); - using (new EditorGUI.DisabledScope(!networkManager.NetworkConfig.EnableSceneManagement)) + using (new EditorGUI.DisabledScope(!m_NetworkManager.NetworkConfig.EnableSceneManagement)) { - registeredScenesList.DoLayoutList(); + m_RegisteredScenesList.DoLayoutList(); EditorGUILayout.Space(); } EditorGUILayout.LabelField("General", EditorStyles.boldLabel); - EditorGUILayout.PropertyField(protocolVersionProperty); + EditorGUILayout.PropertyField(m_ProtocolVersionProperty); - EditorGUILayout.PropertyField(networkTransportProperty); + EditorGUILayout.PropertyField(m_NetworkTransportProperty); - if (networkTransportProperty.objectReferenceValue == null) + if (m_NetworkTransportProperty.objectReferenceValue == null) { EditorGUILayout.HelpBox("You have no transport selected. A transport is required for the MLAPI to work. Which one do you want?", MessageType.Warning); - int selection = EditorGUILayout.Popup(0, transportNames); + int selection = EditorGUILayout.Popup(0, m_TransportNames); if (selection > 0) { ReloadTransports(); - Component transport = networkManager.gameObject.GetComponent(transportTypes[selection - 1]); + var transportComponent = m_NetworkManager.gameObject.GetComponent(m_TransportTypes[selection - 1]); - if (transport == null) + if (ReferenceEquals(transportComponent, null)) { - transport = networkManager.gameObject.AddComponent(transportTypes[selection - 1]); + transportComponent = m_NetworkManager.gameObject.AddComponent(m_TransportTypes[selection - 1]); } - networkTransportProperty.objectReferenceValue = transport; + m_NetworkTransportProperty.objectReferenceValue = transportComponent; Repaint(); } } - EditorGUILayout.PropertyField(enableTimeResyncProperty); + EditorGUILayout.PropertyField(m_EnableTimeResyncProperty); - using (new EditorGUI.DisabledScope(!networkManager.NetworkConfig.EnableTimeResync)) + using (new EditorGUI.DisabledScope(!m_NetworkManager.NetworkConfig.EnableTimeResync)) { - EditorGUILayout.PropertyField(timeResyncIntervalProperty); + EditorGUILayout.PropertyField(m_TimeResyncIntervalProperty); } EditorGUILayout.LabelField("Performance", EditorStyles.boldLabel); - EditorGUILayout.PropertyField(receiveTickrateProperty); - EditorGUILayout.PropertyField(maxReceiveEventsPerTickRateProperty); - EditorGUILayout.PropertyField(eventTickrateProperty); - EditorGUILayout.PropertyField(enableNetworkVariableProperty); + EditorGUILayout.PropertyField(m_ReceiveTickrateProperty); + EditorGUILayout.PropertyField(m_MaxReceiveEventsPerTickRateProperty); + EditorGUILayout.PropertyField(m_EventTickrateProperty); + EditorGUILayout.PropertyField(m_EnableNetworkVariableProperty); - using (new EditorGUI.DisabledScope(!networkManager.NetworkConfig.EnableNetworkVariable)) + using (new EditorGUI.DisabledScope(!m_NetworkManager.NetworkConfig.EnableNetworkVariable)) { - if(maxObjectUpdatesPerTickProperty != null) + if (m_MaxObjectUpdatesPerTickProperty != null) { - EditorGUILayout.PropertyField(maxObjectUpdatesPerTickProperty); + EditorGUILayout.PropertyField(m_MaxObjectUpdatesPerTickProperty); } - EditorGUILayout.PropertyField(ensureNetworkVariableLengthSafetyProperty); + EditorGUILayout.PropertyField(m_EnsureNetworkVariableLengthSafetyProperty); } EditorGUILayout.LabelField("Connection", EditorStyles.boldLabel); - EditorGUILayout.PropertyField(connectionApprovalProperty); + EditorGUILayout.PropertyField(m_ConnectionApprovalProperty); - using (new EditorGUI.DisabledScope(!networkManager.NetworkConfig.ConnectionApproval)) + using (new EditorGUI.DisabledScope(!m_NetworkManager.NetworkConfig.ConnectionApproval)) { - EditorGUILayout.PropertyField(clientConnectionBufferTimeoutProperty); + EditorGUILayout.PropertyField(m_ClientConnectionBufferTimeoutProperty); } EditorGUILayout.LabelField("Lag Compensation", EditorStyles.boldLabel); - EditorGUILayout.PropertyField(secondsHistoryProperty); + EditorGUILayout.PropertyField(m_SecondsHistoryProperty); EditorGUILayout.LabelField("Spawning", EditorStyles.boldLabel); - EditorGUILayout.PropertyField(createPlayerPrefabProperty); - EditorGUILayout.PropertyField(forceSamePrefabsProperty); + EditorGUILayout.PropertyField(m_CreatePlayerPrefabProperty); + EditorGUILayout.PropertyField(m_ForceSamePrefabsProperty); - using (new EditorGUI.DisabledScope(!networkManager.NetworkConfig.EnableSceneManagement)) + using (new EditorGUI.DisabledScope(!m_NetworkManager.NetworkConfig.EnableSceneManagement)) { - bool value = networkManager.NetworkConfig.UsePrefabSync; + bool value = m_NetworkManager.NetworkConfig.UsePrefabSync; - if (!networkManager.NetworkConfig.EnableSceneManagement) + if (!m_NetworkManager.NetworkConfig.EnableSceneManagement) { - usePrefabSyncProperty.boolValue = true; + m_UsePrefabSyncProperty.boolValue = true; } - EditorGUILayout.PropertyField(usePrefabSyncProperty); + EditorGUILayout.PropertyField(m_UsePrefabSyncProperty); - if (!networkManager.NetworkConfig.EnableSceneManagement) + if (!m_NetworkManager.NetworkConfig.EnableSceneManagement) { - usePrefabSyncProperty.boolValue = value; + m_UsePrefabSyncProperty.boolValue = value; } } - EditorGUILayout.PropertyField(recycleNetworkIdsProperty); + EditorGUILayout.PropertyField(m_RecycleNetworkIdsProperty); - using (new EditorGUI.DisabledScope(!networkManager.NetworkConfig.RecycleNetworkIds)) + using (new EditorGUI.DisabledScope(!m_NetworkManager.NetworkConfig.RecycleNetworkIds)) { - EditorGUILayout.PropertyField(networkIdRecycleDelayProperty); + EditorGUILayout.PropertyField(m_NetworkIdRecycleDelayProperty); } - EditorGUILayout.PropertyField(enableMessageBufferingProperty); + EditorGUILayout.PropertyField(m_EnableMessageBufferingProperty); - using (new EditorGUI.DisabledScope(!networkManager.NetworkConfig.EnableMessageBuffering)) + using (new EditorGUI.DisabledScope(!m_NetworkManager.NetworkConfig.EnableMessageBuffering)) { - EditorGUILayout.PropertyField(messageBufferTimeoutProperty); + EditorGUILayout.PropertyField(m_MessageBufferTimeoutProperty); } EditorGUILayout.LabelField("Bandwidth", EditorStyles.boldLabel); - EditorGUILayout.PropertyField(rpcHashSizeProperty); + EditorGUILayout.PropertyField(m_RpcHashSizeProperty); EditorGUILayout.LabelField("Scene Management", EditorStyles.boldLabel); - EditorGUILayout.PropertyField(enableSceneManagementProperty); + EditorGUILayout.PropertyField(m_EnableSceneManagementProperty); - using (new EditorGUI.DisabledScope(!networkManager.NetworkConfig.EnableSceneManagement)) + using (new EditorGUI.DisabledScope(!m_NetworkManager.NetworkConfig.EnableSceneManagement)) { - EditorGUILayout.PropertyField(loadSceneTimeOutProperty); - EditorGUILayout.PropertyField(allowRuntimeSceneChangesProperty); + EditorGUILayout.PropertyField(m_LoadSceneTimeOutProperty); + EditorGUILayout.PropertyField(m_AllowRuntimeSceneChangesProperty); } serializedObject.ApplyModifiedProperties(); @@ -377,17 +370,17 @@ public override void OnInspectorGUI() if (GUILayout.Button(new GUIContent("Start Host", "Starts a host instance" + buttonDisabledReasonSuffix))) { - networkManager.StartHost(); + m_NetworkManager.StartHost(); } if (GUILayout.Button(new GUIContent("Start Server", "Starts a server instance" + buttonDisabledReasonSuffix))) { - networkManager.StartServer(); + m_NetworkManager.StartServer(); } if (GUILayout.Button(new GUIContent("Start Client", "Starts a client instance" + buttonDisabledReasonSuffix))) { - networkManager.StartClient(); + m_NetworkManager.StartClient(); } if (!EditorApplication.isPlaying) @@ -398,26 +391,20 @@ public override void OnInspectorGUI() } else { - string instanceType = ""; + string instanceType = string.Empty; - if (networkManager.IsHost) - instanceType = "Host"; - else if (networkManager.IsServer) - instanceType = "Server"; - else if (networkManager.IsClient) - instanceType = "Client"; + if (m_NetworkManager.IsHost) instanceType = "Host"; + else if (m_NetworkManager.IsServer) instanceType = "Server"; + else if (m_NetworkManager.IsClient) instanceType = "Client"; EditorGUILayout.HelpBox("You cannot edit the NetworkConfig when a " + instanceType + " is running.", MessageType.Info); if (GUILayout.Button(new GUIContent("Stop " + instanceType, "Stops the " + instanceType + " instance."))) { - if (networkManager.IsHost) - networkManager.StopHost(); - else if (networkManager.IsServer) - networkManager.StopServer(); - else if (networkManager.IsClient) - networkManager.StopClient(); + if (m_NetworkManager.IsHost) m_NetworkManager.StopHost(); + else if (m_NetworkManager.IsServer) m_NetworkManager.StopServer(); + else if (m_NetworkManager.IsClient) m_NetworkManager.StopClient(); } } } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Editor/NetworkObjectEditor.cs b/com.unity.multiplayer.mlapi/Editor/NetworkObjectEditor.cs index 1f66844613..11bf4f2b97 100644 --- a/com.unity.multiplayer.mlapi/Editor/NetworkObjectEditor.cs +++ b/com.unity.multiplayer.mlapi/Editor/NetworkObjectEditor.cs @@ -8,63 +8,68 @@ namespace UnityEditor [CanEditMultipleObjects] public class NetworkObjectEditor : Editor { - private bool initialized; - private NetworkObject networkObject; - private bool showObservers; + private bool m_Initialized; + private NetworkObject m_NetworkObject; + private bool m_ShowObservers; private void Init() { - if (initialized) - return; - initialized = true; - networkObject = (NetworkObject)target; + if (m_Initialized) return; + + m_Initialized = true; + m_NetworkObject = (NetworkObject)target; } public override void OnInspectorGUI() { Init(); - if (!networkObject.IsSpawned && NetworkManager.Singleton != null && NetworkManager.Singleton.IsServer) + if (!m_NetworkObject.IsSpawned && !ReferenceEquals(NetworkManager.Singleton, null) && NetworkManager.Singleton.IsServer) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(new GUIContent("Spawn", "Spawns the object across the network")); if (GUILayout.Toggle(false, "Spawn", EditorStyles.miniButtonLeft)) { - networkObject.Spawn(); + m_NetworkObject.Spawn(); EditorUtility.SetDirty(target); } + EditorGUILayout.EndHorizontal(); } - else if (networkObject.IsSpawned) + else if (m_NetworkObject.IsSpawned) { - EditorGUILayout.LabelField("PrefabHashGenerator: ", networkObject.PrefabHashGenerator, EditorStyles.label); - EditorGUILayout.LabelField("PrefabHash: ", networkObject.PrefabHash.ToString(), EditorStyles.label); - EditorGUILayout.LabelField("InstanceId: ", networkObject.NetworkInstanceId.ToString(), EditorStyles.label); - EditorGUILayout.LabelField("NetworkId: ", networkObject.NetworkObjectId.ToString(), EditorStyles.label); - EditorGUILayout.LabelField("OwnerId: ", networkObject.OwnerClientId.ToString(), EditorStyles.label); - EditorGUILayout.LabelField("IsSpawned: ", networkObject.IsSpawned.ToString(), EditorStyles.label); - EditorGUILayout.LabelField("IsLocalPlayer: ", networkObject.IsLocalPlayer.ToString(), EditorStyles.label); - EditorGUILayout.LabelField("IsOwner: ", networkObject.IsOwner.ToString(), EditorStyles.label); - EditorGUILayout.LabelField("IsOwnedByServer: ", networkObject.IsOwnedByServer.ToString(), EditorStyles.label); - EditorGUILayout.LabelField("IsPlayerObject: ", networkObject.IsPlayerObject.ToString(), EditorStyles.label); - EditorGUILayout.LabelField("IsSceneObject: ", (networkObject.IsSceneObject == null ? "Null" : networkObject.IsSceneObject.Value.ToString()), EditorStyles.label); + EditorGUILayout.LabelField("PrefabHashGenerator: ", m_NetworkObject.PrefabHashGenerator, EditorStyles.label); + EditorGUILayout.LabelField("PrefabHash: ", m_NetworkObject.PrefabHash.ToString(), EditorStyles.label); + EditorGUILayout.LabelField("InstanceId: ", m_NetworkObject.NetworkInstanceId.ToString(), EditorStyles.label); + EditorGUILayout.LabelField("NetworkId: ", m_NetworkObject.NetworkObjectId.ToString(), EditorStyles.label); + EditorGUILayout.LabelField("OwnerId: ", m_NetworkObject.OwnerClientId.ToString(), EditorStyles.label); + EditorGUILayout.LabelField("IsSpawned: ", m_NetworkObject.IsSpawned.ToString(), EditorStyles.label); + EditorGUILayout.LabelField("IsLocalPlayer: ", m_NetworkObject.IsLocalPlayer.ToString(), EditorStyles.label); + EditorGUILayout.LabelField("IsOwner: ", m_NetworkObject.IsOwner.ToString(), EditorStyles.label); + EditorGUILayout.LabelField("IsOwnedByServer: ", m_NetworkObject.IsOwnedByServer.ToString(), EditorStyles.label); + EditorGUILayout.LabelField("IsPlayerObject: ", m_NetworkObject.IsPlayerObject.ToString(), EditorStyles.label); + EditorGUILayout.LabelField("IsSceneObject: ", (m_NetworkObject.IsSceneObject == null ? "Null" : m_NetworkObject.IsSceneObject.Value.ToString()), EditorStyles.label); if (NetworkManager.Singleton != null && NetworkManager.Singleton.IsServer) { - showObservers = EditorGUILayout.Foldout(showObservers, "Observers"); + m_ShowObservers = EditorGUILayout.Foldout(m_ShowObservers, "Observers"); - if (showObservers) + if (m_ShowObservers) { - HashSet.Enumerator observerClientIds = networkObject.GetObservers(); + HashSet.Enumerator observerClientIds = m_NetworkObject.GetObservers(); EditorGUI.indentLevel += 1; while (observerClientIds.MoveNext()) { if (NetworkManager.Singleton.ConnectedClients[observerClientIds.Current].PlayerObject != null) + { EditorGUILayout.ObjectField("ClientId: " + observerClientIds.Current, NetworkManager.Singleton.ConnectedClients[observerClientIds.Current].PlayerObject, typeof(GameObject), false); + } else + { EditorGUILayout.TextField("ClientId: " + observerClientIds.Current, EditorStyles.label); + } } EditorGUI.indentLevel -= 1; @@ -74,9 +79,9 @@ public override void OnInspectorGUI() else { base.OnInspectorGUI(); - EditorGUILayout.LabelField("PrefabHash: ", networkObject.PrefabHash.ToString(), EditorStyles.label); - EditorGUILayout.LabelField("InstanceId: ", networkObject.NetworkInstanceId.ToString(), EditorStyles.label); + EditorGUILayout.LabelField("PrefabHash: ", m_NetworkObject.PrefabHash.ToString(), EditorStyles.label); + EditorGUILayout.LabelField("InstanceId: ", m_NetworkObject.NetworkInstanceId.ToString(), EditorStyles.label); } } } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Editor/PostProcessScene.cs b/com.unity.multiplayer.mlapi/Editor/PostProcessScene.cs index bcc6ef82d5..b2d748b40e 100644 --- a/com.unity.multiplayer.mlapi/Editor/PostProcessScene.cs +++ b/com.unity.multiplayer.mlapi/Editor/PostProcessScene.cs @@ -12,12 +12,12 @@ public class NetworkScenePostProcess : MonoBehaviour public static void ProcessScene() { //If we are in playmode (editor or stand alone) we do not want this to execute - if(Application.isPlaying) + if (Application.isPlaying) { return; } - List traverseSortedObjects = MonoBehaviour.FindObjectsOfType().ToList(); + var traverseSortedObjects = FindObjectsOfType().ToList(); traverseSortedObjects.Sort((x, y) => { @@ -27,10 +27,14 @@ public static void ProcessScene() while (xSiblingIndex.Count > 0 && ySiblingIndex.Count > 0) { if (xSiblingIndex[0] < ySiblingIndex[0]) + { return -1; + } if (xSiblingIndex[0] > ySiblingIndex[0]) + { return 1; + } xSiblingIndex.RemoveAt(0); ySiblingIndex.RemoveAt(0); @@ -40,7 +44,9 @@ public static void ProcessScene() }); for (ulong i = 0; i < (ulong)traverseSortedObjects.Count; i++) + { traverseSortedObjects[(int)i].NetworkInstanceId = i; + } } } @@ -48,9 +54,8 @@ internal static class PrefabHelpers { internal static List TraversedSiblingIndex(this NetworkObject networkObject) { - List paths = new List(); - - Transform transform = networkObject.transform; + var paths = new List(); + var transform = networkObject.transform; while (transform != null) { @@ -63,4 +68,4 @@ internal static List TraversedSiblingIndex(this NetworkObject networkObject return paths; } } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Editor/Properties.meta b/com.unity.multiplayer.mlapi/Editor/Properties.meta deleted file mode 100644 index 57388a161f..0000000000 --- a/com.unity.multiplayer.mlapi/Editor/Properties.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: bb658c776eb5f4f4e817ff46011e3533 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.multiplayer.mlapi/Editor/Properties/AssemblyInfo.cs b/com.unity.multiplayer.mlapi/Editor/Properties/AssemblyInfo.cs deleted file mode 100644 index 1975093105..0000000000 --- a/com.unity.multiplayer.mlapi/Editor/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using UnityEngine; - -[assembly: AssemblyIsEditorAssembly] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("a45dbd43-d640-4562-9f24-6745269cedf7")] diff --git a/com.unity.multiplayer.mlapi/Editor/Properties/AssemblyInfo.cs.meta b/com.unity.multiplayer.mlapi/Editor/Properties/AssemblyInfo.cs.meta deleted file mode 100644 index f50c142623..0000000000 --- a/com.unity.multiplayer.mlapi/Editor/Properties/AssemblyInfo.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 37462c81b27b57848ac42878d6fb1040 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.multiplayer.mlapi/Editor/TrackedObjectEditor.cs b/com.unity.multiplayer.mlapi/Editor/TrackedObjectEditor.cs index f7282f0008..bd6959959d 100644 --- a/com.unity.multiplayer.mlapi/Editor/TrackedObjectEditor.cs +++ b/com.unity.multiplayer.mlapi/Editor/TrackedObjectEditor.cs @@ -7,29 +7,30 @@ namespace UnityEditor [CanEditMultipleObjects] public class TrackedObjectEditor : Editor { - private TrackedObject trackedObject; - private bool initialized; + private TrackedObject m_TrackedObject; + private bool m_Initialized; private void Init() { - if (initialized) - return; + if (m_Initialized) return; - trackedObject = (TrackedObject)target; - initialized = true; + m_TrackedObject = (TrackedObject)target; + m_Initialized = true; } public override void OnInspectorGUI() { Init(); + base.OnInspectorGUI(); - if(NetworkManager.Singleton != null && NetworkManager.Singleton.IsServer) + if (!ReferenceEquals(NetworkManager.Singleton, null) && NetworkManager.Singleton.IsServer) { - EditorGUILayout.LabelField("Total points: ", trackedObject.TotalPoints.ToString(), EditorStyles.label); - EditorGUILayout.LabelField("Avg time between points: ", trackedObject.AvgTimeBetweenPointsMs.ToString() + " ms", EditorStyles.label); - EditorGUILayout.LabelField("Total history: ", trackedObject.TotalTimeHistory.ToString() + " seconds", EditorStyles.label); + EditorGUILayout.LabelField("Total points: ", m_TrackedObject.TotalPoints.ToString(), EditorStyles.label); + EditorGUILayout.LabelField("Avg time between points: ", m_TrackedObject.AvgTimeBetweenPointsMs + " ms", EditorStyles.label); + EditorGUILayout.LabelField("Total history: ", m_TrackedObject.TotalTimeHistory + " seconds", EditorStyles.label); } + Repaint(); } } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Properties/AssemblyInfo.cs b/com.unity.multiplayer.mlapi/Runtime/AssemblyInfo.cs similarity index 100% rename from com.unity.multiplayer.mlapi/Runtime/Properties/AssemblyInfo.cs rename to com.unity.multiplayer.mlapi/Runtime/AssemblyInfo.cs diff --git a/com.unity.multiplayer.mlapi/Runtime/Properties/AssemblyInfo.cs.meta b/com.unity.multiplayer.mlapi/Runtime/AssemblyInfo.cs.meta similarity index 100% rename from com.unity.multiplayer.mlapi/Runtime/Properties/AssemblyInfo.cs.meta rename to com.unity.multiplayer.mlapi/Runtime/AssemblyInfo.cs.meta diff --git a/com.unity.multiplayer.mlapi/Runtime/Collections/FixedQueue.cs b/com.unity.multiplayer.mlapi/Runtime/Collections/FixedQueue.cs index 8357c56a48..62cdb3a10f 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Collections/FixedQueue.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Collections/FixedQueue.cs @@ -8,27 +8,21 @@ namespace MLAPI.Collections /// The type of the queue public sealed class FixedQueue { - private readonly T[] queue; - private int queueCount = 0; - private int queueStart; + private readonly T[] m_Queue; + private int m_QueueCount = 0; + private int m_QueueStart; /// /// The amount of enqueued objects /// - public int Count { get => queueCount; } + public int Count => m_QueueCount; /// /// Gets the element at a given virtual index /// /// The virtual index to get the item from /// The element at the virtual index - public T this[int index] - { - get - { - return queue[(queueStart + index) % queue.Length]; - } - } + public T this[int index] => m_Queue[(m_QueueStart + index) % m_Queue.Length]; /// /// Creates a new FixedQueue with a given size @@ -36,8 +30,8 @@ public T this[int index] /// The size of the queue public FixedQueue(int maxSize) { - queue = new T[maxSize]; - queueStart = 0; + m_Queue = new T[maxSize]; + m_QueueStart = 0; } /// @@ -47,12 +41,13 @@ public FixedQueue(int maxSize) /// public bool Enqueue(T t) { - queue[(queueStart + queueCount) % queue.Length] = t; - if (++queueCount > queue.Length) + m_Queue[(m_QueueStart + m_QueueCount) % m_Queue.Length] = t; + if (++m_QueueCount > m_Queue.Length) { - --queueCount; + --m_QueueCount; return true; } + return false; } @@ -62,9 +57,9 @@ public bool Enqueue(T t) /// public T Dequeue() { - if (--queueCount == -1) throw new IndexOutOfRangeException("Cannot dequeue empty queue!"); - T res = queue[queueStart]; - queueStart = (queueStart + 1) % queue.Length; + if (--m_QueueCount == -1) throw new IndexOutOfRangeException("Cannot dequeue empty queue!"); + T res = m_Queue[m_QueueStart]; + m_QueueStart = (m_QueueStart + 1) % m_Queue.Length; return res; } @@ -73,6 +68,6 @@ public T Dequeue() /// /// The virtual index to get the item from /// The element at the virtual index - public T ElementAt(int index) => queue[(queueStart + index) % queue.Length]; + public T ElementAt(int index) => m_Queue[(m_QueueStart + index) % m_Queue.Length]; } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Configuration/HashSize.cs b/com.unity.multiplayer.mlapi/Runtime/Configuration/HashSize.cs index fc3446ec00..18292291cb 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Configuration/HashSize.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Configuration/HashSize.cs @@ -11,10 +11,12 @@ public enum HashSize /// Two byte hash /// VarIntTwoBytes, + /// /// Four byte hash /// VarIntFourBytes, + /// /// Eight byte hash /// diff --git a/com.unity.multiplayer.mlapi/Runtime/Configuration/NetworkConfig.cs b/com.unity.multiplayer.mlapi/Runtime/Configuration/NetworkConfig.cs index 87343f7912..690f2e0ba8 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Configuration/NetworkConfig.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Configuration/NetworkConfig.cs @@ -27,94 +27,112 @@ public class NetworkConfig /// [Tooltip("Use this to make two builds incompatible with each other")] public ushort ProtocolVersion = 0; + /// /// The transport hosts the sever uses /// [Tooltip("The NetworkTransport to use")] public NetworkTransport NetworkTransport = null; + /// /// A list of SceneNames that can be used during networked games. /// [Tooltip("The Scenes that can be switched to by the server")] public List RegisteredScenes = new List(); + /// /// Whether or not runtime scene changes should be allowed and expected. /// If this is true, clients with different initial configurations will not work together. /// [Tooltip("Whether or not runtime scene changes should be allowed and expected.\n " + - "If this is true, clients with different initial configurations will not work together.")] + "If this is true, clients with different initial configurations will not work together.")] public bool AllowRuntimeSceneChanges = false; + /// /// A list of spawnable prefabs /// [Tooltip("The prefabs that can be spawned across the network")] public List NetworkPrefabs = new List(); + /// /// The default player prefab /// [SerializeReference] internal NullableBoolSerializable PlayerPrefabHash; + /// /// Whether or not a player object should be created by default. This value can be overriden on a case by case basis with ConnectionApproval. /// [Tooltip("Whether or not a player object should be created by default. This value can be overriden on a case by case basis with ConnectionApproval.")] public bool CreatePlayerPrefab = true; + /// /// Amount of times per second the receive queue is emptied and all messages inside are processed. /// [Tooltip("The amount of times per second the receive queue is emptied from pending incoming messages")] public int ReceiveTickrate = 64; + /// /// The max amount of messages to process per ReceiveTickrate. This is to prevent flooding. /// [Tooltip("The maximum amount of Receive events to poll per Receive tick. This is to prevent flooding and freezing on the server")] public int MaxReceiveEventsPerTickRate = 500; + /// /// The amount of times per second internal frame events will occur, e.g. send checking. /// [Tooltip("The amount of times per second the internal event loop will run. This includes for example NetworkVariable checking and LagCompensation tracking")] public int EventTickrate = 64; + /// /// The amount of seconds to wait for handshake to complete before timing out a client /// [Tooltip("The amount of seconds to wait for the handshake to complete before the client times out")] public int ClientConnectionBufferTimeout = 10; + /// /// Whether or not to use connection approval /// [Tooltip("Whether or not to force clients to be approved before they connect")] public bool ConnectionApproval = false; + /// /// The data to send during connection which can be used to decide on if a client should get accepted /// [Tooltip("The connection data sent along with connection requests")] public byte[] ConnectionData = new byte[0]; + /// /// The amount of seconds to keep a lag compensation position history /// [Tooltip("The amount of seconds to keep lag compensation position history")] public int SecondsHistory = 5; + /// /// If your logic uses the NetworkTime, this should probably be turned off. If however it's needed to maximize accuracy, this is recommended to be turned on /// [Tooltip("Enable this to resync the NetworkTime after the initial sync")] public bool EnableTimeResync = false; + /// /// If time resync is turned on, this specifies the interval between syncs in seconds. /// [Tooltip("The amount of seconds between resyncs of NetworkTime, if enabled")] public int TimeResyncInterval = 30; + /// /// Whether or not to enable the NetworkVariable system. This system runs in the Update loop and will degrade performance, but it can be a huge convenience. /// Only turn it off if you have no need for the NetworkVariable system. /// [Tooltip("Whether or not to enable the NetworkVariable system")] public bool EnableNetworkVariable = true; + /// /// Whether or not to ensure that NetworkVariables can be read even if a client accidentally writes where its not allowed to. This costs some CPU and bandwdith. /// [Tooltip("Ensures that NetworkVariables can be read even if a client accidental writes where its not allowed to. This will cost some CPU time and bandwidth")] public bool EnsureNetworkVariableLengthSafety = false; + /// /// Enables scene management. This will allow network scene switches and automatic scene diff corrections upon connect. /// SoftSynced scene objects wont work with this disabled. That means that disabling SceneManagement also enables PrefabSync. @@ -122,12 +140,14 @@ public class NetworkConfig [Tooltip("Enables scene management. This will allow network scene switches and automatic scene diff corrections upon connect.\n" + "SoftSynced scene objects wont work with this disabled. That means that disabling SceneManagement also enables PrefabSync.")] public bool EnableSceneManagement = true; + /// /// Whether or not the MLAPI should check for differences in the prefabs at connection. /// If you dynamically add prefabs at runtime, turn this OFF /// [Tooltip("Whether or not the MLAPI should check for differences in the prefab lists at connection")] public bool ForceSamePrefabs = true; + /// /// If true, all NetworkObjects need to be prefabs and all scene objects will be replaced on server side which causes all serialization to be lost. Useful for multi project setups /// If false, Only non scene objects have to be prefabs. Scene objects will be matched using their PrefabInstanceId which can be precomputed globally for a scene at build time. Useful for single projects @@ -135,36 +155,43 @@ public class NetworkConfig [Tooltip("If true, all NetworkObjects need to be prefabs and all scene objects will be replaced on server side which causes all serialization to be lost. Useful for multi project setups\n" + "If false, Only non scene objects have to be prefabs. Scene objects will be matched using their PrefabInstanceId which can be precomputed globally for a scene at build time. Useful for single projects")] public bool UsePrefabSync = false; + /// /// If true, NetworkIds will be reused after the NetworkIdRecycleDelay. /// [Tooltip("If true, NetworkIds will be reused after the NetworkIdRecycleDelay")] public bool RecycleNetworkIds = true; + /// /// The amount of seconds a NetworkId has to be unused in order for it to be reused. /// [Tooltip("The amount of seconds a NetworkId has to unused in order for it to be reused")] public float NetworkIdRecycleDelay = 120f; + /// /// Decides how many bytes to use for Rpc messaging. Leave this to 2 bytes unless you are facing hash collisions /// [Tooltip("The maximum amount of bytes to use for RPC messages. Leave this to 2 unless you are facing hash collisions")] public HashSize RpcHashSize = HashSize.VarIntTwoBytes; + /// /// The amount of seconds to wait on all clients to load requested scene before the SwitchSceneProgress onComplete callback, that waits for all clients to complete loading, is called anyway. /// [Tooltip("The amount of seconds to wait for all clients to load a requested scene")] public int LoadSceneTimeOut = 120; + /// /// Whether or not message buffering should be enabled. This will resolve most out of order messages during spawn. /// [Tooltip("Whether or not message buffering should be enabled. This will resolve most out of order messages during spawn")] public bool EnableMessageBuffering = true; + /// /// The amount of time a message should be buffered for without being consumed. If it is not consumed within this time, it will be dropped. /// [Tooltip("The amount of time a message should be buffered for without being consumed. If it is not consumed within this time, it will be dropped")] public float MessageBufferTimeout = 20f; + /// /// Whether or not to enable network logs. /// @@ -182,41 +209,38 @@ private void Sort() public string ToBase64() { NetworkConfig config = this; - using (PooledNetworkBuffer buffer = PooledNetworkBuffer.Get()) + using (var buffer = PooledNetworkBuffer.Get()) + using (var writer = PooledNetworkWriter.Get(buffer)) { - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(buffer)) - { - writer.WriteUInt16Packed(config.ProtocolVersion); + writer.WriteUInt16Packed(config.ProtocolVersion); + writer.WriteUInt16Packed((ushort)config.RegisteredScenes.Count); - writer.WriteUInt16Packed((ushort)config.RegisteredScenes.Count); + for (int i = 0; i < config.RegisteredScenes.Count; i++) + { + writer.WriteString(config.RegisteredScenes[i]); + } - for (int i = 0; i < config.RegisteredScenes.Count; i++) - { - writer.WriteString(config.RegisteredScenes[i]); - } + writer.WriteInt32Packed(config.ReceiveTickrate); + writer.WriteInt32Packed(config.MaxReceiveEventsPerTickRate); + writer.WriteInt32Packed(config.EventTickrate); + writer.WriteInt32Packed(config.ClientConnectionBufferTimeout); + writer.WriteBool(config.ConnectionApproval); + writer.WriteInt32Packed(config.SecondsHistory); + writer.WriteInt32Packed(config.LoadSceneTimeOut); + writer.WriteBool(config.EnableTimeResync); + writer.WriteBool(config.EnsureNetworkVariableLengthSafety); + writer.WriteBits((byte)config.RpcHashSize, 2); + writer.WriteBool(ForceSamePrefabs); + writer.WriteBool(UsePrefabSync); + writer.WriteBool(EnableSceneManagement); + writer.WriteBool(RecycleNetworkIds); + writer.WriteSinglePacked(NetworkIdRecycleDelay); + writer.WriteBool(EnableNetworkVariable); + writer.WriteBool(AllowRuntimeSceneChanges); + writer.WriteBool(EnableNetworkLogs); + buffer.PadBuffer(); - writer.WriteInt32Packed(config.ReceiveTickrate); - writer.WriteInt32Packed(config.MaxReceiveEventsPerTickRate); - writer.WriteInt32Packed(config.EventTickrate); - writer.WriteInt32Packed(config.ClientConnectionBufferTimeout); - writer.WriteBool(config.ConnectionApproval); - writer.WriteInt32Packed(config.SecondsHistory); - writer.WriteInt32Packed(config.LoadSceneTimeOut); - writer.WriteBool(config.EnableTimeResync); - writer.WriteBool(config.EnsureNetworkVariableLengthSafety); - writer.WriteBits((byte)config.RpcHashSize, 2); - writer.WriteBool(ForceSamePrefabs); - writer.WriteBool(UsePrefabSync); - writer.WriteBool(EnableSceneManagement); - writer.WriteBool(RecycleNetworkIds); - writer.WriteSinglePacked(NetworkIdRecycleDelay); - writer.WriteBool(EnableNetworkVariable); - writer.WriteBool(AllowRuntimeSceneChanges); - writer.WriteBool(EnableNetworkLogs); - buffer.PadBuffer(); - - return Convert.ToBase64String(buffer.ToArray()); - } + return Convert.ToBase64String(buffer.ToArray()); } } @@ -228,44 +252,43 @@ public void FromBase64(string base64) { NetworkConfig config = this; byte[] binary = Convert.FromBase64String(base64); - using (NetworkBuffer buffer = new NetworkBuffer(binary)) + using (var buffer = new NetworkBuffer(binary)) + using (var reader = PooledNetworkReader.Get(buffer)) { - using (PooledNetworkReader reader = PooledNetworkReader.Get(buffer)) - { - config.ProtocolVersion = reader.ReadUInt16Packed(); - - ushort sceneCount = reader.ReadUInt16Packed(); - config.RegisteredScenes.Clear(); + config.ProtocolVersion = reader.ReadUInt16Packed(); - for (int i = 0; i < sceneCount; i++) - { - config.RegisteredScenes.Add(reader.ReadString().ToString()); - } + ushort sceneCount = reader.ReadUInt16Packed(); + config.RegisteredScenes.Clear(); - config.ReceiveTickrate = reader.ReadInt32Packed(); - config.MaxReceiveEventsPerTickRate = reader.ReadInt32Packed(); - config.EventTickrate = reader.ReadInt32Packed(); - config.ClientConnectionBufferTimeout = reader.ReadInt32Packed(); - config.ConnectionApproval = reader.ReadBool(); - config.SecondsHistory = reader.ReadInt32Packed(); - config.LoadSceneTimeOut = reader.ReadInt32Packed(); - config.EnableTimeResync = reader.ReadBool(); - config.EnsureNetworkVariableLengthSafety = reader.ReadBool(); - config.RpcHashSize = (HashSize)reader.ReadBits(2); - config.ForceSamePrefabs = reader.ReadBool(); - config.UsePrefabSync = reader.ReadBool(); - config.EnableSceneManagement = reader.ReadBool(); - config.RecycleNetworkIds = reader.ReadBool(); - config.NetworkIdRecycleDelay = reader.ReadSinglePacked(); - config.EnableNetworkVariable = reader.ReadBool(); - config.AllowRuntimeSceneChanges = reader.ReadBool(); - config.EnableNetworkLogs = reader.ReadBool(); + for (int i = 0; i < sceneCount; i++) + { + config.RegisteredScenes.Add(reader.ReadString().ToString()); } + + config.ReceiveTickrate = reader.ReadInt32Packed(); + config.MaxReceiveEventsPerTickRate = reader.ReadInt32Packed(); + config.EventTickrate = reader.ReadInt32Packed(); + config.ClientConnectionBufferTimeout = reader.ReadInt32Packed(); + config.ConnectionApproval = reader.ReadBool(); + config.SecondsHistory = reader.ReadInt32Packed(); + config.LoadSceneTimeOut = reader.ReadInt32Packed(); + config.EnableTimeResync = reader.ReadBool(); + config.EnsureNetworkVariableLengthSafety = reader.ReadBool(); + config.RpcHashSize = (HashSize)reader.ReadBits(2); + config.ForceSamePrefabs = reader.ReadBool(); + config.UsePrefabSync = reader.ReadBool(); + config.EnableSceneManagement = reader.ReadBool(); + config.RecycleNetworkIds = reader.ReadBool(); + config.NetworkIdRecycleDelay = reader.ReadSinglePacked(); + config.EnableNetworkVariable = reader.ReadBool(); + config.AllowRuntimeSceneChanges = reader.ReadBool(); + config.EnableNetworkLogs = reader.ReadBool(); } } - private ulong? ConfigHash = null; + private ulong? m_ConfigHash = null; + /// /// Gets a SHA256 hash of parts of the NetworkConfig instance /// @@ -273,51 +296,48 @@ public void FromBase64(string base64) /// public ulong GetConfig(bool cache = true) { - if (ConfigHash != null && cache) - return ConfigHash.Value; + if (m_ConfigHash != null && cache) return m_ConfigHash.Value; Sort(); - using (PooledNetworkBuffer buffer = PooledNetworkBuffer.Get()) + using (var buffer = PooledNetworkBuffer.Get()) + using (var writer = PooledNetworkWriter.Get(buffer)) { - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(buffer)) - { - writer.WriteUInt16Packed(ProtocolVersion); - writer.WriteString(NetworkConstants.PROTOCOL_VERSION); + writer.WriteUInt16Packed(ProtocolVersion); + writer.WriteString(NetworkConstants.PROTOCOL_VERSION); - if (EnableSceneManagement && !AllowRuntimeSceneChanges) + if (EnableSceneManagement && !AllowRuntimeSceneChanges) + { + for (int i = 0; i < RegisteredScenes.Count; i++) { - for (int i = 0; i < RegisteredScenes.Count; i++) - { - writer.WriteString(RegisteredScenes[i]); - } + writer.WriteString(RegisteredScenes[i]); } + } - if (ForceSamePrefabs) + if (ForceSamePrefabs) + { + var sortedPrefabList = NetworkPrefabs.OrderBy(x => x.Hash).ToList(); + for (int i = 0; i < sortedPrefabList.Count; i++) { - List sortedPrefabList = NetworkPrefabs.OrderBy(x => x.Hash).ToList(); - for (int i = 0; i < sortedPrefabList.Count; i++) - { - writer.WriteUInt64Packed(sortedPrefabList[i].Hash); - } + writer.WriteUInt64Packed(sortedPrefabList[i].Hash); } + } - writer.WriteBool(EnableNetworkVariable); - writer.WriteBool(ForceSamePrefabs); - writer.WriteBool(UsePrefabSync); - writer.WriteBool(EnableSceneManagement); - writer.WriteBool(EnsureNetworkVariableLengthSafety); - writer.WriteBits((byte)RpcHashSize, 2); - buffer.PadBuffer(); - - if (cache) - { - ConfigHash = buffer.ToArray().GetStableHash64(); - return ConfigHash.Value; - } + writer.WriteBool(EnableNetworkVariable); + writer.WriteBool(ForceSamePrefabs); + writer.WriteBool(UsePrefabSync); + writer.WriteBool(EnableSceneManagement); + writer.WriteBool(EnsureNetworkVariableLengthSafety); + writer.WriteBits((byte)RpcHashSize, 2); + buffer.PadBuffer(); - return buffer.ToArray().GetStableHash64(); + if (cache) + { + m_ConfigHash = buffer.ToArray().GetStableHash64(); + return m_ConfigHash.Value; } + + return buffer.ToArray().GetStableHash64(); } } @@ -331,4 +351,4 @@ public bool CompareConfig(ulong hash) return hash == GetConfig(); } } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Configuration/NetworkPrefab.cs b/com.unity.multiplayer.mlapi/Runtime/Configuration/NetworkPrefab.cs index 63d56ef3fe..51b305f9c7 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Configuration/NetworkPrefab.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Configuration/NetworkPrefab.cs @@ -16,14 +16,22 @@ internal ulong Hash { if (ReferenceEquals(Prefab, null)) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning($"{nameof(NetworkPrefab)} is not assigned"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarning($"{nameof(NetworkPrefab)} is not assigned"); + } + return 0; } var networkObject = Prefab.GetComponent(); if (ReferenceEquals(networkObject, null)) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning($"{nameof(NetworkPrefab)} {Prefab.name} does not have a {nameof(NetworkObject)}"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarning($"{nameof(NetworkPrefab)} {Prefab.name} does not have a {nameof(NetworkObject)}"); + } + return 0; } diff --git a/com.unity.multiplayer.mlapi/Runtime/Core/NetworkBehaviour.cs b/com.unity.multiplayer.mlapi/Runtime/Core/NetworkBehaviour.cs index f2de034603..6c95499eca 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Core/NetworkBehaviour.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Core/NetworkBehaviour.cs @@ -66,14 +66,14 @@ public NetworkSerializer __beginSendServerRpc(ServerRpcParams serverRpcParams, R { PooledNetworkWriter writer; - var rpcQueueContainer = NetworkManager.Singleton.rpcQueueContainer; + var rpcQueueContainer = NetworkManager.Singleton.RpcQueueContainer; var isUsingBatching = rpcQueueContainer.IsUsingBatching(); var transportChannel = rpcDelivery == RpcDelivery.Reliable ? NetworkChannel.ReliableRpc : NetworkChannel.UnreliableRpc; if (IsHost) { writer = rpcQueueContainer.BeginAddQueueItemToFrame(RpcQueueContainer.QueueItemType.ServerRpc, Time.realtimeSinceStartup, transportChannel, - NetworkManager.Singleton.ServerClientId, null, QueueHistoryFrame.QueueFrameType.Inbound, serverRpcParams.Send.UpdateStage); + NetworkManager.Singleton.ServerClientId, null, RpcQueueHistoryFrame.QueueFrameType.Inbound, serverRpcParams.Send.UpdateStage); if (!isUsingBatching) { @@ -83,7 +83,7 @@ public NetworkSerializer __beginSendServerRpc(ServerRpcParams serverRpcParams, R else { writer = rpcQueueContainer.BeginAddQueueItemToFrame(RpcQueueContainer.QueueItemType.ServerRpc, Time.realtimeSinceStartup, transportChannel, - NetworkManager.Singleton.ServerClientId, null, QueueHistoryFrame.QueueFrameType.Outbound, NetworkUpdateStage.PostLateUpdate); + NetworkManager.Singleton.ServerClientId, null, RpcQueueHistoryFrame.QueueFrameType.Outbound, NetworkUpdateStage.PostLateUpdate); if (!isUsingBatching) { writer.WriteByte(NetworkConstants.SERVER_RPC); // MessageType @@ -109,14 +109,14 @@ public void __endSendServerRpc(NetworkSerializer serializer, ServerRpcParams ser { if (serializer == null) return; - var rpcQueueContainer = NetworkManager.Singleton.rpcQueueContainer; + var rpcQueueContainer = NetworkManager.Singleton.RpcQueueContainer; if (IsHost) { - rpcQueueContainer.EndAddQueueItemToFrame(serializer.Writer, QueueHistoryFrame.QueueFrameType.Inbound, serverRpcParams.Send.UpdateStage); + rpcQueueContainer.EndAddQueueItemToFrame(serializer.Writer, RpcQueueHistoryFrame.QueueFrameType.Inbound, serverRpcParams.Send.UpdateStage); } else { - rpcQueueContainer.EndAddQueueItemToFrame(serializer.Writer, QueueHistoryFrame.QueueFrameType.Outbound, NetworkUpdateStage.PostLateUpdate); + rpcQueueContainer.EndAddQueueItemToFrame(serializer.Writer, RpcQueueHistoryFrame.QueueFrameType.Outbound, NetworkUpdateStage.PostLateUpdate); } } @@ -133,7 +133,7 @@ public NetworkSerializer __beginSendClientRpc(ClientRpcParams clientRpcParams, R PooledNetworkWriter writer; // This will start a new queue item entry and will then return the writer to the current frame's stream - var rpcQueueContainer = NetworkManager.Singleton.rpcQueueContainer; + var rpcQueueContainer = NetworkManager.Singleton.RpcQueueContainer; var isUsingBatching = rpcQueueContainer.IsUsingBatching(); var transportChannel = rpcDelivery == RpcDelivery.Reliable ? NetworkChannel.ReliableRpc : NetworkChannel.UnreliableRpc; @@ -152,7 +152,7 @@ public NetworkSerializer __beginSendClientRpc(ClientRpcParams clientRpcParams, R { //Always write to the next frame's inbound queue writer = rpcQueueContainer.BeginAddQueueItemToFrame(RpcQueueContainer.QueueItemType.ClientRpc, Time.realtimeSinceStartup, transportChannel, - NetworkManager.Singleton.ServerClientId, null, QueueHistoryFrame.QueueFrameType.Inbound, clientRpcParams.Send.UpdateStage); + NetworkManager.Singleton.ServerClientId, null, RpcQueueHistoryFrame.QueueFrameType.Inbound, clientRpcParams.Send.UpdateStage); //Handle sending to the other clients, if so the above notes explain why this code is here (a temporary patch-fix) if (ClientIds.Length > 1) @@ -162,7 +162,7 @@ public NetworkSerializer __beginSendClientRpc(ClientRpcParams clientRpcParams, R //Switch to the outbound queue writer = rpcQueueContainer.BeginAddQueueItemToFrame(RpcQueueContainer.QueueItemType.ClientRpc, Time.realtimeSinceStartup, NetworkChannel.ReliableRpc, NetworkObjectId, - ClientIds, QueueHistoryFrame.QueueFrameType.Outbound, NetworkUpdateStage.PostLateUpdate); + ClientIds, RpcQueueHistoryFrame.QueueFrameType.Outbound, NetworkUpdateStage.PostLateUpdate); if (!isUsingBatching) { @@ -180,7 +180,7 @@ public NetworkSerializer __beginSendClientRpc(ClientRpcParams clientRpcParams, R else { writer = rpcQueueContainer.BeginAddQueueItemToFrame(RpcQueueContainer.QueueItemType.ClientRpc, Time.realtimeSinceStartup, transportChannel, NetworkObjectId, - ClientIds, QueueHistoryFrame.QueueFrameType.Outbound, NetworkUpdateStage.PostLateUpdate); + ClientIds, RpcQueueHistoryFrame.QueueFrameType.Outbound, NetworkUpdateStage.PostLateUpdate); if (!isUsingBatching) { @@ -207,7 +207,7 @@ public void __endSendClientRpc(NetworkSerializer serializer, ClientRpcParams cli { if (serializer == null) return; - var rpcQueueContainer = NetworkManager.Singleton.rpcQueueContainer; + var rpcQueueContainer = NetworkManager.Singleton.RpcQueueContainer; if (IsHost) { @@ -220,12 +220,12 @@ public void __endSendClientRpc(NetworkSerializer serializer, ClientRpcParams cli var ContainsServerClientId = ClientIds.Contains(NetworkManager.Singleton.ServerClientId); if (ContainsServerClientId && ClientIds.Length == 1) { - rpcQueueContainer.EndAddQueueItemToFrame(serializer.Writer, QueueHistoryFrame.QueueFrameType.Inbound, clientRpcParams.Send.UpdateStage); + rpcQueueContainer.EndAddQueueItemToFrame(serializer.Writer, RpcQueueHistoryFrame.QueueFrameType.Inbound, clientRpcParams.Send.UpdateStage); return; } } - rpcQueueContainer.EndAddQueueItemToFrame(serializer.Writer, QueueHistoryFrame.QueueFrameType.Outbound, NetworkUpdateStage.PostLateUpdate); + rpcQueueContainer.EndAddQueueItemToFrame(serializer.Writer, RpcQueueHistoryFrame.QueueFrameType.Outbound, NetworkUpdateStage.PostLateUpdate); } /// @@ -312,7 +312,7 @@ public bool HasNetworkObject /// /// Gets NetworkId for this NetworkBehaviour from the owner NetworkObject /// - public ushort NetworkBehaviourId => NetworkObject.GetOrderIndex(this); + public ushort NetworkBehaviourId => NetworkObject.GetNetworkBehaviourOrderIndex(this); /// /// Returns a the NetworkBehaviour with a given BehaviourId for the current NetworkObject @@ -329,14 +329,14 @@ protected NetworkBehaviour GetNetworkBehaviour(ushort behaviourId) /// public ulong OwnerClientId => NetworkObject.OwnerClientId; - internal bool networkStartInvoked = false; - internal bool internalNetworkStartInvoked = false; + internal bool NetworkStartInvoked = false; + internal bool InternalNetworkStartInvoked = false; /// /// Stores the network tick at the NetworkBehaviourUpdate time /// This allows sending NetworkVariables not more often than once per network tick, regardless of the update rate /// - public static ushort currentTick { get; private set; } + public static ushort CurrentTick { get; private set; } /// /// Gets called when message handlers are ready to be registered and the network is setup @@ -369,23 +369,23 @@ public virtual void OnLostOwnership() { } #region NetworkVariable - private bool varInit = false; + private bool m_VarInit = false; - private readonly List> channelMappedNetworkVariableIndexes = new List>(); - private readonly List channelsForNetworkVariableGroups = new List(); - internal readonly List networkVariableFields = new List(); + private readonly List> m_ChannelMappedNetworkVariableIndexes = new List>(); + private readonly List m_ChannelsForNetworkVariableGroups = new List(); + internal readonly List NetworkVariableFields = new List(); - private static HashSet touched = new HashSet(); - private static readonly Dictionary fieldTypes = new Dictionary(); + private static HashSet s_Touched = new HashSet(); + private static Dictionary s_FieldTypes = new Dictionary(); private static FieldInfo[] GetFieldInfoForType(Type type) { - if (!fieldTypes.ContainsKey(type)) + if (!s_FieldTypes.ContainsKey(type)) { - fieldTypes.Add(type, GetFieldInfoForTypeRecursive(type)); + s_FieldTypes.Add(type, GetFieldInfoForTypeRecursive(type)); } - return fieldTypes[type]; + return s_FieldTypes[type]; } private static FieldInfo[] GetFieldInfoForTypeRecursive(Type type, List list = null) @@ -410,8 +410,8 @@ private static FieldInfo[] GetFieldInfoForTypeRecursive(Type type, List firstLevelIndex = new Dictionary(); + var firstLevelIndex = new Dictionary(); int secondLevelCounter = 0; - for (int i = 0; i < networkVariableFields.Count; i++) + for (int i = 0; i < NetworkVariableFields.Count; i++) { - NetworkChannel networkChannel = networkVariableFields[i].GetChannel(); + NetworkChannel networkChannel = NetworkVariableFields[i].GetChannel(); if (!firstLevelIndex.ContainsKey(networkChannel)) { firstLevelIndex.Add(networkChannel, secondLevelCounter); - channelsForNetworkVariableGroups.Add(networkChannel); + m_ChannelsForNetworkVariableGroups.Add(networkChannel); secondLevelCounter++; } - if (firstLevelIndex[networkChannel] >= channelMappedNetworkVariableIndexes.Count) + if (firstLevelIndex[networkChannel] >= m_ChannelMappedNetworkVariableIndexes.Count) { - channelMappedNetworkVariableIndexes.Add(new HashSet()); + m_ChannelMappedNetworkVariableIndexes.Add(new HashSet()); } - channelMappedNetworkVariableIndexes[firstLevelIndex[networkChannel]].Add(i); + m_ChannelMappedNetworkVariableIndexes[firstLevelIndex[networkChannel]].Add(i); } } } #if DEVELOPMENT_BUILD || UNITY_EDITOR - public static ProfilerMarker s_NetworkBehaviourUpdate = new ProfilerMarker(nameof(NetworkBehaviourUpdate)); + private static ProfilerMarker s_NetworkBehaviourUpdate = new ProfilerMarker($"{nameof(NetworkBehaviour)}.{nameof(NetworkBehaviourUpdate)}"); #endif internal static void NetworkBehaviourUpdate() { // Do not execute NetworkBehaviourUpdate more than once per network tick - ushort tick = NetworkManager.Singleton.networkTickSystem.GetTick(); - if (tick == currentTick) + ushort tick = NetworkManager.Singleton.NetworkTickSystem.GetTick(); + if (tick == CurrentTick) { return; } - currentTick = tick; + CurrentTick = tick; #if DEVELOPMENT_BUILD || UNITY_EDITOR s_NetworkBehaviourUpdate.Begin(); @@ -482,12 +482,12 @@ internal static void NetworkBehaviourUpdate() { if (IsServer) { - touched.Clear(); + s_Touched.Clear(); for (int i = 0; i < NetworkManager.Singleton.ConnectedClientsList.Count; i++) { var client = NetworkManager.Singleton.ConnectedClientsList[i]; var spawnedObjs = NetworkSpawnManager.SpawnedObjectsList; - touched.UnionWith(spawnedObjs); + s_Touched.UnionWith(spawnedObjs); foreach (var sobj in spawnedObjs) { // Sync just the variables for just the objects this client sees @@ -499,7 +499,7 @@ internal static void NetworkBehaviourUpdate() } // Now, reset all the no-longer-dirty variables - foreach (var sobj in touched) + foreach (var sobj in s_Touched) { for (int k = 0; k < sobj.ChildNetworkBehaviours.Count; k++) { @@ -540,51 +540,51 @@ internal static void NetworkBehaviourUpdate() internal void PreNetworkVariableWrite() { // reset our "which variables got written" data - networkVariableIndexesToReset.Clear(); - networkVariableIndexesToResetSet.Clear(); + m_NetworkVariableIndexesToReset.Clear(); + m_NetworkVariableIndexesToResetSet.Clear(); } internal void PostNetworkVariableWrite() { // mark any variables we wrote as no longer dirty - for (int i = 0; i < networkVariableIndexesToReset.Count; i++) + for (int i = 0; i < m_NetworkVariableIndexesToReset.Count; i++) { - networkVariableFields[networkVariableIndexesToReset[i]].ResetDirty(); + NetworkVariableFields[m_NetworkVariableIndexesToReset[i]].ResetDirty(); } } internal void VariableUpdate(ulong clientId) { - if (!varInit) InitializeVariables(); + if (!m_VarInit) InitializeVariables(); PreNetworkVariableWrite(); NetworkVariableUpdate(clientId); } - private readonly List networkVariableIndexesToReset = new List(); - private readonly HashSet networkVariableIndexesToResetSet = new HashSet(); + private readonly List m_NetworkVariableIndexesToReset = new List(); + private readonly HashSet m_NetworkVariableIndexesToResetSet = new HashSet(); private void NetworkVariableUpdate(ulong clientId) { if (!CouldHaveDirtyNetworkVariables()) return; - for (int j = 0; j < channelMappedNetworkVariableIndexes.Count; j++) + for (int j = 0; j < m_ChannelMappedNetworkVariableIndexes.Count; j++) { - using (PooledNetworkBuffer buffer = PooledNetworkBuffer.Get()) + using (var buffer = PooledNetworkBuffer.Get()) { - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(buffer)) + using (var writer = PooledNetworkWriter.Get(buffer)) { writer.WriteUInt64Packed(NetworkObjectId); - writer.WriteUInt16Packed(NetworkObject.GetOrderIndex(this)); + writer.WriteUInt16Packed(NetworkObject.GetNetworkBehaviourOrderIndex(this)); // Write the current tick frame // todo: this is currently done per channel, per tick. The snapshot system might improve on this - writer.WriteUInt16Packed(currentTick); + writer.WriteUInt16Packed(CurrentTick); bool writtenAny = false; - for (int k = 0; k < networkVariableFields.Count; k++) + for (int k = 0; k < NetworkVariableFields.Count; k++) { - if (!channelMappedNetworkVariableIndexes[j].Contains(k)) + if (!m_ChannelMappedNetworkVariableIndexes[j].Contains(k)) { // This var does not belong to the currently iterating channel group. if (NetworkManager.Singleton.NetworkConfig.EnsureNetworkVariableLengthSafety) @@ -599,11 +599,11 @@ private void NetworkVariableUpdate(ulong clientId) continue; } - bool isDirty = networkVariableFields[k].IsDirty(); // cache this here. You never know what operations users will do in the dirty methods + bool isDirty = NetworkVariableFields[k].IsDirty(); // cache this here. You never know what operations users will do in the dirty methods // if I'm dirty AND a client, write (server always has all permissions) // if I'm dirty AND the server AND the client can read me, send. - bool shouldWrite = isDirty && (!IsServer || networkVariableFields[k].CanClientRead(clientId)); + bool shouldWrite = isDirty && (!IsServer || NetworkVariableFields[k].CanClientRead(clientId)); if (NetworkManager.Singleton.NetworkConfig.EnsureNetworkVariableLengthSafety) { @@ -623,9 +623,9 @@ private void NetworkVariableUpdate(ulong clientId) if (NetworkManager.Singleton.NetworkConfig.EnsureNetworkVariableLengthSafety) { - using (PooledNetworkBuffer varBuffer = PooledNetworkBuffer.Get()) + using (var varBuffer = PooledNetworkBuffer.Get()) { - networkVariableFields[k].WriteDelta(varBuffer); + NetworkVariableFields[k].WriteDelta(varBuffer); varBuffer.PadBuffer(); writer.WriteUInt16Packed((ushort)varBuffer.Length); @@ -634,20 +634,20 @@ private void NetworkVariableUpdate(ulong clientId) } else { - networkVariableFields[k].WriteDelta(buffer); + NetworkVariableFields[k].WriteDelta(buffer); } - if (!networkVariableIndexesToResetSet.Contains(k)) + if (!m_NetworkVariableIndexesToResetSet.Contains(k)) { - networkVariableIndexesToResetSet.Add(k); - networkVariableIndexesToReset.Add(k); + m_NetworkVariableIndexesToResetSet.Add(k); + m_NetworkVariableIndexesToReset.Add(k); } } } if (writtenAny) { - InternalMessageSender.Send(clientId, NetworkConstants.NETWORK_VARIABLE_DELTA, channelsForNetworkVariableGroups[j], buffer); + InternalMessageSender.Send(clientId, NetworkConstants.NETWORK_VARIABLE_DELTA, m_ChannelsForNetworkVariableGroups[j], buffer); } } } @@ -657,10 +657,9 @@ private void NetworkVariableUpdate(ulong clientId) private bool CouldHaveDirtyNetworkVariables() { // TODO: There should be a better way by reading one dirty variable vs. 'n' - for (int i = 0; i < networkVariableFields.Count; i++) + for (int i = 0; i < NetworkVariableFields.Count; i++) { - if (networkVariableFields[i].IsDirty()) - return true; + if (NetworkVariableFields[i].IsDirty()) return true; } return false; @@ -668,7 +667,7 @@ private bool CouldHaveDirtyNetworkVariables() internal static void HandleNetworkVariableDeltas(List networkVariableList, Stream stream, ulong clientId, NetworkBehaviour logInstance) { - using (PooledNetworkReader reader = PooledNetworkReader.Get(stream)) + using (var reader = PooledNetworkReader.Get(stream)) { // read the remote network tick at which this variable was written. ushort remoteTick = reader.ReadUInt16Packed(); @@ -694,8 +693,8 @@ internal static void HandleNetworkVariableDeltas(List networkV { if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) { - NetworkLog.LogWarning("Client wrote to NetworkVariable without permission. " + (logInstance != null ? ("NetworkId: " + logInstance.NetworkObjectId + " BehaviourIndex: " + logInstance.NetworkObject.GetOrderIndex(logInstance) + " VariableIndex: " + i) : string.Empty)); - NetworkLog.LogError("[" + networkVariableList[i].GetType().Name + "]"); + NetworkLog.LogWarning($"Client wrote to {nameof(NetworkVariable)} without permission. => {(logInstance != null ? ($"{nameof(NetworkObjectId)}: {logInstance.NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {logInstance.NetworkObject.GetNetworkBehaviourOrderIndex(logInstance)} - VariableIndex: {i}") : string.Empty)}"); + NetworkLog.LogError($"[{networkVariableList[i].GetType().Name}]"); } stream.Position += varSize; @@ -712,8 +711,8 @@ internal static void HandleNetworkVariableDeltas(List networkV if (NetworkLog.CurrentLogLevel <= LogLevel.Error) { - NetworkLog.LogError("Client wrote to NetworkVariable without permission. No more variables can be read. This is critical. " + (logInstance != null ? ("NetworkId: " + logInstance.NetworkObjectId + " BehaviourIndex: " + logInstance.NetworkObject.GetOrderIndex(logInstance) + " VariableIndex: " + i) : string.Empty)); - NetworkLog.LogError("[" + networkVariableList[i].GetType().Name + "]"); + NetworkLog.LogError($"Client wrote to {nameof(NetworkVariable)} without permission. No more variables can be read. This is critical. => {(logInstance != null ? ($"{nameof(NetworkObjectId)}: {logInstance.NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {logInstance.NetworkObject.GetNetworkBehaviourOrderIndex(logInstance)} - VariableIndex: {i}") : string.Empty)}"); + NetworkLog.LogError($"[{networkVariableList[i].GetType().Name}]"); } return; @@ -728,7 +727,7 @@ internal static void HandleNetworkVariableDeltas(List networkV networkVariableList[i].ReadDelta(stream, IsServer, localTick, remoteTick); PerformanceDataManager.Increment(ProfilerConstants.NumberNetworkVarsReceived); - ProfilerStatManager.networkVarsRcvd.Record(); + ProfilerStatManager.NetworkVarsRcvd.Record(); if (NetworkManager.Singleton.NetworkConfig.EnsureNetworkVariableLengthSafety) { @@ -736,12 +735,20 @@ internal static void HandleNetworkVariableDeltas(List networkV if (stream.Position > (readStartPos + varSize)) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("Var delta read too far. " + (stream.Position - (readStartPos + varSize)) + " bytes." + (logInstance != null ? ("NetworkId: " + logInstance.NetworkObjectId + " BehaviourIndex: " + logInstance.NetworkObject.GetOrderIndex(logInstance) + " VariableIndex: " + i) : string.Empty)); + if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarning($"Var delta read too far. {stream.Position - (readStartPos + varSize)} bytes. => {(logInstance != null ? ($"{nameof(NetworkObjectId)}: {logInstance.NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {logInstance.NetworkObject.GetNetworkBehaviourOrderIndex(logInstance)} - VariableIndex: {i}") : string.Empty)}"); + } + stream.Position = readStartPos + varSize; } else if (stream.Position < (readStartPos + varSize)) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("Var delta read too little. " + ((readStartPos + varSize) - stream.Position) + " bytes." + (logInstance != null ? ("NetworkId: " + logInstance.NetworkObjectId + " BehaviourIndex: " + logInstance.NetworkObject.GetOrderIndex(logInstance) + " VariableIndex: " + i) : string.Empty)); + if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarning($"Var delta read too little. {(readStartPos + varSize) - stream.Position} bytes. => {(logInstance != null ? ($"{nameof(NetworkObjectId)}: {logInstance.NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {logInstance.NetworkObject.GetNetworkBehaviourOrderIndex(logInstance)} - VariableIndex: {i}") : string.Empty)}"); + } + stream.Position = readStartPos + varSize; } } @@ -751,7 +758,7 @@ internal static void HandleNetworkVariableDeltas(List networkV internal static void HandleNetworkVariableUpdate(List networkVariableList, Stream stream, ulong clientId, NetworkBehaviour logInstance) { - using (PooledNetworkReader reader = PooledNetworkReader.Get(stream)) + using (var reader = PooledNetworkReader.Get(stream)) { for (int i = 0; i < networkVariableList.Count; i++) { @@ -772,7 +779,11 @@ internal static void HandleNetworkVariableUpdate(List networkV { if (NetworkManager.Singleton.NetworkConfig.EnsureNetworkVariableLengthSafety) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("Client wrote to NetworkVariable without permission. " + (logInstance != null ? ("NetworkId: " + logInstance.NetworkObjectId + " BehaviourIndex: " + logInstance.NetworkObject.GetOrderIndex(logInstance) + " VariableIndex: " + i) : string.Empty)); + if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarning($"Client wrote to {nameof(NetworkVariable)} without permission. => {(logInstance != null ? ($"{nameof(NetworkObjectId)}: {logInstance.NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {logInstance.NetworkObject.GetNetworkBehaviourOrderIndex(logInstance)} - VariableIndex: {i}") : string.Empty)}"); + } + stream.Position += varSize; continue; } @@ -786,7 +797,7 @@ internal static void HandleNetworkVariableUpdate(List networkV // - TwoTen if (NetworkLog.CurrentLogLevel <= LogLevel.Error) { - NetworkLog.LogError("Client wrote to NetworkVariable without permission. No more variables can be read. This is critical. " + (logInstance != null ? ("NetworkId: " + logInstance.NetworkObjectId + " BehaviourIndex: " + logInstance.NetworkObject.GetOrderIndex(logInstance) + " VariableIndex: " + i) : string.Empty)); + NetworkLog.LogError($"Client wrote to {nameof(NetworkVariable)} without permission. No more variables can be read. This is critical. => {(logInstance != null ? ($"{nameof(NetworkObjectId)}: {logInstance.NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {logInstance.NetworkObject.GetNetworkBehaviourOrderIndex(logInstance)} - VariableIndex: {i}") : string.Empty)}"); } return; @@ -794,10 +805,10 @@ internal static void HandleNetworkVariableUpdate(List networkV long readStartPos = stream.Position; - networkVariableList[i].ReadField(stream, NetworkTickSystem.k_NoTick, NetworkTickSystem.k_NoTick); + networkVariableList[i].ReadField(stream, NetworkTickSystem.NoTick, NetworkTickSystem.NoTick); PerformanceDataManager.Increment(ProfilerConstants.NumberNetworkVarsReceived); - ProfilerStatManager.networkVarsRcvd.Record(); + ProfilerStatManager.NetworkVarsRcvd.Record(); if (NetworkManager.Singleton.NetworkConfig.EnsureNetworkVariableLengthSafety) { @@ -808,12 +819,20 @@ internal static void HandleNetworkVariableUpdate(List networkV if (stream.Position > (readStartPos + varSize)) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("Var update read too far. " + (stream.Position - (readStartPos + varSize)) + " bytes." + (logInstance != null ? ("NetworkId: " + logInstance.NetworkObjectId + " BehaviourIndex: " + logInstance.NetworkObject.GetOrderIndex(logInstance) + " VariableIndex: " + i) : string.Empty)); + if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarning($"Var update read too far. {stream.Position - (readStartPos + varSize)} bytes. => {(logInstance != null ? ($"{nameof(NetworkObjectId)}: {logInstance.NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {logInstance.NetworkObject.GetNetworkBehaviourOrderIndex(logInstance)} - VariableIndex: {i}") : string.Empty)}"); + } + stream.Position = readStartPos + varSize; } else if (stream.Position < (readStartPos + varSize)) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("Var update read too little. " + ((readStartPos + varSize) - stream.Position) + " bytes." + (logInstance != null ? ("NetworkId: " + logInstance.NetworkObjectId + " BehaviourIndex: " + logInstance.NetworkObject.GetOrderIndex(logInstance) + " VariableIndex: " + i) : string.Empty)); + if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarning($"Var update read too little. {(readStartPos + varSize) - stream.Position} bytes. => {(logInstance != null ? ($"{nameof(NetworkObjectId)}: {logInstance.NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {logInstance.NetworkObject.GetNetworkBehaviourOrderIndex(logInstance)} - VariableIndex: {i}") : string.Empty)}"); + } + stream.Position = readStartPos + varSize; } } @@ -826,7 +845,7 @@ internal static void WriteNetworkVariableData(List networkVari { if (networkVariableList.Count == 0) return; - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(stream)) + using (var writer = PooledNetworkWriter.Get(stream)) { for (int j = 0; j < networkVariableList.Count; j++) { @@ -848,7 +867,7 @@ internal static void WriteNetworkVariableData(List networkVari { if (NetworkManager.Singleton.NetworkConfig.EnsureNetworkVariableLengthSafety) { - using (PooledNetworkBuffer varBuffer = PooledNetworkBuffer.Get()) + using (var varBuffer = PooledNetworkBuffer.Get()) { networkVariableList[j].WriteField(varBuffer); varBuffer.PadBuffer(); @@ -870,7 +889,7 @@ internal static void SetNetworkVariableData(List networkVariab { if (networkVariableList.Count == 0) return; - using (PooledNetworkReader reader = PooledNetworkReader.Get(stream)) + using (var reader = PooledNetworkReader.Get(stream)) { for (int j = 0; j < networkVariableList.Count; j++) { @@ -889,7 +908,7 @@ internal static void SetNetworkVariableData(List networkVariab long readStartPos = stream.Position; - networkVariableList[j].ReadField(stream, NetworkTickSystem.k_NoTick, NetworkTickSystem.k_NoTick); + networkVariableList[j].ReadField(stream, NetworkTickSystem.NoTick, NetworkTickSystem.NoTick); if (NetworkManager.Singleton.NetworkConfig.EnsureNetworkVariableLengthSafety) { @@ -900,12 +919,20 @@ internal static void SetNetworkVariableData(List networkVariab if (stream.Position > (readStartPos + varSize)) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("Var data read too far. " + (stream.Position - (readStartPos + varSize)) + " bytes."); + if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarning($"Var data read too far. {stream.Position - (readStartPos + varSize)} bytes."); + } + stream.Position = readStartPos + varSize; } else if (stream.Position < (readStartPos + varSize)) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("Var data read too little. " + ((readStartPos + varSize) - stream.Position) + " bytes."); + if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarning($"Var data read too little. {(readStartPos + varSize) - stream.Position} bytes."); + } + stream.Position = readStartPos + varSize; } } diff --git a/com.unity.multiplayer.mlapi/Runtime/Core/NetworkManager.cs b/com.unity.multiplayer.mlapi/Runtime/Core/NetworkManager.cs index b108834917..bee29f2a39 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Core/NetworkManager.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Core/NetworkManager.cs @@ -19,7 +19,6 @@ using MLAPI.SceneManagement; using MLAPI.Serialization.Pooled; using MLAPI.Spawning; -using static MLAPI.Messaging.CustomMessagingManager; using MLAPI.Exceptions; using MLAPI.Transports.Tasks; using MLAPI.Messaging.Buffering; @@ -45,20 +44,18 @@ public class NetworkManager : MonoBehaviour, INetworkUpdateSystem #endif #if DEVELOPMENT_BUILD || UNITY_EDITOR - static ProfilerMarker s_EventTick = new ProfilerMarker("Event"); - static ProfilerMarker s_ReceiveTick = new ProfilerMarker("Receive"); - static ProfilerMarker s_SyncTime = new ProfilerMarker("SyncTime"); - static ProfilerMarker s_TransportConnect = new ProfilerMarker("TransportConnect"); - static ProfilerMarker s_HandleIncomingData = new ProfilerMarker("HandleIncomingData"); - static ProfilerMarker s_TransportDisconnect = new ProfilerMarker("TransportDisconnect"); - - static ProfilerMarker s_ServerRpcQueued = new ProfilerMarker("ServerRpcQueued"); - static ProfilerMarker s_ClientRpcQueued = new ProfilerMarker("ClientRpcQueued"); - - static ProfilerMarker s_InvokeRpc = new ProfilerMarker("InvokeRpc"); + private static ProfilerMarker s_EventTick = new ProfilerMarker($"{nameof(NetworkManager)}.EventTick"); + private static ProfilerMarker s_ReceiveTick = new ProfilerMarker($"{nameof(NetworkManager)}.ReceiveTick"); + private static ProfilerMarker s_SyncTime = new ProfilerMarker($"{nameof(NetworkManager)}.SyncTime"); + private static ProfilerMarker s_TransportConnect = new ProfilerMarker($"{nameof(NetworkManager)}.TransportConnect"); + private static ProfilerMarker s_HandleIncomingData = new ProfilerMarker($"{nameof(NetworkManager)}.{nameof(HandleIncomingData)}"); + private static ProfilerMarker s_TransportDisconnect = new ProfilerMarker($"{nameof(NetworkManager)}.TransportDisconnect"); + + private static ProfilerMarker s_InvokeRpc = new ProfilerMarker($"{nameof(NetworkManager)}.{nameof(InvokeRpc)}"); #endif - internal RpcQueueContainer rpcQueueContainer { get; private set; } - internal NetworkTickSystem networkTickSystem { get; private set; } + + internal RpcQueueContainer RpcQueueContainer { get; private set; } + internal NetworkTickSystem NetworkTickSystem { get; private set; } public delegate void PerformanceDataEventHandler(PerformanceTickData profilerData); @@ -67,10 +64,10 @@ public class NetworkManager : MonoBehaviour, INetworkUpdateSystem /// /// A synchronized time, represents the time in seconds since the server application started. Is replicated across all clients /// - public float NetworkTime => Time.unscaledTime + currentNetworkTimeOffset; + public float NetworkTime => Time.unscaledTime + m_CurrentNetworkTimeOffset; - private float networkTimeOffset; - private float currentNetworkTimeOffset; + private float m_NetworkTimeOffset; + private float m_CurrentNetworkTimeOffset; /// /// Gets or sets if the NetworkManager should be marked as DontDestroyOnLoad @@ -98,18 +95,18 @@ public class NetworkManager : MonoBehaviour, INetworkUpdateSystem /// /// Gets the networkId of the server /// - public ulong ServerClientId => NetworkConfig.NetworkTransport != null ? NetworkConfig.NetworkTransport.ServerClientId : throw new NullReferenceException("The transport in the active NetworkConfig is null"); + public ulong ServerClientId => NetworkConfig.NetworkTransport?.ServerClientId ?? throw new NullReferenceException($"The transport in the active {nameof(NetworkConfig)} is null"); /// /// The clientId the server calls the local client by, only valid for clients /// public ulong LocalClientId { - get => IsServer ? NetworkConfig.NetworkTransport.ServerClientId : localClientId; - internal set => localClientId = value; + get => IsServer ? NetworkConfig.NetworkTransport.ServerClientId : m_LocalClientId; + internal set => m_LocalClientId = value; } - private ulong localClientId; + private ulong m_LocalClientId; /// /// Gets a dictionary of connected clients and their clientId keys. This is only populated on the server. @@ -156,26 +153,14 @@ public ulong LocalClientId /// public event Action OnClientConnectedCallback = null; - internal void InvokeOnClientConnectedCallback(ulong clientId) - { - if (OnClientConnectedCallback != null) - { - OnClientConnectedCallback(clientId); - } - } + internal void InvokeOnClientConnectedCallback(ulong clientId) => OnClientConnectedCallback?.Invoke(clientId); /// /// The callback to invoke when a client disconnects. This callback is only ran on the server and on the local client that disconnects. /// public event Action OnClientDisconnectCallback = null; - internal void InvokeOnClientDisconnectCallback(ulong clientId) - { - if (OnClientDisconnectCallback != null) - { - OnClientDisconnectCallback(clientId); - } - } + internal void InvokeOnClientDisconnectCallback(ulong clientId) => OnClientDisconnectCallback?.Invoke(clientId); /// /// The callback to invoke once the server is ready @@ -197,13 +182,7 @@ internal void InvokeOnClientDisconnectCallback(ulong clientId) /// public event Action ConnectionApprovalCallback = null; - internal void InvokeConnectionApproval(byte[] payload, ulong clientId, ConnectionApprovedDelegate action) - { - if (ConnectionApprovalCallback != null) - { - ConnectionApprovalCallback(payload, clientId, action); - } - } + internal void InvokeConnectionApproval(byte[] payload, ulong clientId, ConnectionApprovedDelegate action) => ConnectionApprovalCallback?.Invoke(payload, clientId, action); /// /// The current NetworkConfig @@ -220,12 +199,14 @@ internal void InvokeConnectionApproval(byte[] payload, ulong clientId, Connectio private void OnValidate() { - if (NetworkConfig == null) - return; //May occur when the component is added + if (NetworkConfig == null) return; //May occur when the component is added if (GetComponentInChildren() != null) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning($"{nameof(NetworkManager)} cannot be a {nameof(NetworkObject)}. This will lead to weird side effects."); + if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarning($"{nameof(NetworkManager)} cannot be a {nameof(NetworkObject)}. This will lead to weird side effects."); + } } if (!NetworkConfig.RegisteredScenes.Contains(SceneManager.GetActiveScene().name)) @@ -240,7 +221,10 @@ private void OnValidate() { if (NetworkConfig.NetworkPrefabs[i].Prefab.GetComponent() == null) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning($"Network prefab [{i}] does not have a {nameof(NetworkObject)} component"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarning($"{nameof(NetworkPrefab)} [{i}] does not have a {nameof(NetworkObject)} component"); + } } else { @@ -250,7 +234,7 @@ private void OnValidate() } // TODO: Show which two prefab generators that collide - HashSet hashes = new HashSet(); + var hashes = new HashSet(); for (int i = 0; i < NetworkConfig.NetworkPrefabs.Count; i++) { @@ -259,7 +243,7 @@ private void OnValidate() if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) { var prefabHashGenerator = NetworkConfig.NetworkPrefabs[i].Prefab.GetComponent().PrefabHashGenerator; - NetworkLog.LogError($"PrefabHash collision! You have two prefabs with the same hash (PrefabHashGenerator = {prefabHashGenerator}). This is not supported"); + NetworkLog.LogError($"PrefabHash collision! You have two prefabs with the same hash ({nameof(NetworkObject.PrefabHashGenerator)} = {prefabHashGenerator}). This is not supported"); } } @@ -270,11 +254,17 @@ private void OnValidate() if (playerPrefabCount == 0 && !NetworkConfig.ConnectionApproval && NetworkConfig.CreatePlayerPrefab) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning($"There is no {nameof(NetworkPrefab)} marked as a PlayerPrefab"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarning($"There is no {nameof(NetworkPrefab)} marked as a {nameof(NetworkPrefab.PlayerPrefab)}"); + } } else if (playerPrefabCount > 1) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning($"Only one {nameof(NetworkPrefab)} can be marked as a PlayerPrefab"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarning($"Only one {nameof(NetworkPrefab)} can be marked as a {nameof(NetworkPrefab.PlayerPrefab)}"); + } } var networkPrefab = NetworkConfig.NetworkPrefabs.FirstOrDefault(x => x.PlayerPrefab); @@ -296,11 +286,11 @@ private void OnValidate() private void Init(bool server) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("Init()"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo(nameof(Init)); LocalClientId = 0; - networkTimeOffset = 0f; - currentNetworkTimeOffset = 0f; + m_NetworkTimeOffset = 0f; + m_CurrentNetworkTimeOffset = 0f; m_LastReceiveTickTime = 0f; m_LastReceiveTickTime = 0f; m_EventOvershootCounter = 0f; @@ -310,42 +300,43 @@ private void Init(bool server) NetworkSpawnManager.SpawnedObjects.Clear(); NetworkSpawnManager.SpawnedObjectsList.Clear(); - NetworkSpawnManager.releasedNetworkObjectIds.Clear(); - NetworkSpawnManager.pendingSoftSyncObjects.Clear(); - NetworkSceneManager.registeredSceneNames.Clear(); - NetworkSceneManager.sceneIndexToString.Clear(); - NetworkSceneManager.sceneNameToIndex.Clear(); - NetworkSceneManager.sceneSwitchProgresses.Clear(); - - if (NetworkConfig.NetworkTransport == null) + NetworkSpawnManager.ReleasedNetworkObjectIds.Clear(); + NetworkSpawnManager.PendingSoftSyncObjects.Clear(); + NetworkSceneManager.RegisteredSceneNames.Clear(); + NetworkSceneManager.SceneIndexToString.Clear(); + NetworkSceneManager.SceneNameToIndex.Clear(); + NetworkSceneManager.SceneSwitchProgresses.Clear(); + + if (ReferenceEquals(NetworkConfig.NetworkTransport, null)) { if (NetworkLog.CurrentLogLevel <= LogLevel.Error) NetworkLog.LogError("No transport has been selected!"); return; } //This 'if' should never enter - if (networkTickSystem != null) + if (NetworkTickSystem != null) { - networkTickSystem.Dispose(); + NetworkTickSystem.Dispose(); + NetworkTickSystem = null; } - networkTickSystem = new NetworkTickSystem(); + NetworkTickSystem = new NetworkTickSystem(); //This should never happen, but in the event that it does there should be (at a minimum) a unity error logged. - if (rpcQueueContainer != null) + if (RpcQueueContainer != null) { UnityEngine.Debug.LogError("Init was invoked, but rpcQueueContainer was already initialized! (destroying previous instance)"); - rpcQueueContainer.Shutdown(); - rpcQueueContainer = null; + RpcQueueContainer.Shutdown(); + RpcQueueContainer = null; } //The RpcQueueContainer must be initialized within the Init method ONLY //It should ONLY be shutdown and destroyed in the Shutdown method (other than just above) - rpcQueueContainer = new RpcQueueContainer(false); + RpcQueueContainer = new RpcQueueContainer(false); //Note: Since frame history is not being used, this is set to 0 //To test frame history, increase the number to (n) where n > 0 - rpcQueueContainer.Initialize(0); + RpcQueueContainer.Initialize(0); // Register INetworkUpdateSystem (always register this after rpcQueueContainer has been instantiated) this.RegisterNetworkUpdate(NetworkUpdateStage.EarlyUpdate); @@ -357,9 +348,9 @@ private void Init(bool server) for (int i = 0; i < NetworkConfig.RegisteredScenes.Count; i++) { - NetworkSceneManager.registeredSceneNames.Add(NetworkConfig.RegisteredScenes[i]); - NetworkSceneManager.sceneIndexToString.Add((uint)i, NetworkConfig.RegisteredScenes[i]); - NetworkSceneManager.sceneNameToIndex.Add(NetworkConfig.RegisteredScenes[i], (uint)i); + NetworkSceneManager.RegisteredSceneNames.Add(NetworkConfig.RegisteredScenes[i]); + NetworkSceneManager.SceneIndexToString.Add((uint)i, NetworkConfig.RegisteredScenes[i]); + NetworkSceneManager.SceneNameToIndex.Add(NetworkConfig.RegisteredScenes[i], (uint)i); } NetworkSceneManager.SetCurrentSceneIndex(); @@ -369,11 +360,17 @@ private void Init(bool server) { if (NetworkConfig.NetworkPrefabs[i] == null || ReferenceEquals(NetworkConfig.NetworkPrefabs[i].Prefab, null)) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Error) NetworkLog.LogError($"{nameof(NetworkPrefab)} cannot be null"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Error) + { + NetworkLog.LogError($"{nameof(NetworkPrefab)} cannot be null"); + } } else if (ReferenceEquals(NetworkConfig.NetworkPrefabs[i].Prefab.GetComponent(), null)) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Error) NetworkLog.LogError($"{nameof(NetworkPrefab)} is missing a {nameof(NetworkObject)} component"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Error) + { + NetworkLog.LogError($"{nameof(NetworkPrefab)} is missing a {nameof(NetworkObject)} component"); + } } else { @@ -410,7 +407,7 @@ public SocketTasks StartServer() Init(true); - SocketTasks tasks = NetworkConfig.NetworkTransport.StartServer(); + var socketTasks = NetworkConfig.NetworkTransport.StartServer(); IsServer = true; IsClient = false; @@ -418,10 +415,9 @@ public SocketTasks StartServer() NetworkSpawnManager.ServerSpawnSceneObjectsOnStartSweep(); - if (OnServerStarted != null) - OnServerStarted.Invoke(); + OnServerStarted?.Invoke(); - return tasks; + return socketTasks; } /// @@ -429,7 +425,7 @@ public SocketTasks StartServer() /// public SocketTasks StartClient() { - if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("StartClient()"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo(nameof(StartClient)); if (IsServer || IsClient) { @@ -439,13 +435,13 @@ public SocketTasks StartClient() Init(false); - SocketTasks tasks = NetworkConfig.NetworkTransport.StartClient(); + var socketTasks = NetworkConfig.NetworkTransport.StartClient(); IsServer = false; IsClient = true; IsListening = true; - return tasks; + return socketTasks; } /// @@ -453,8 +449,8 @@ public SocketTasks StartClient() /// public void StopServer() { - if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("StopServer()"); - HashSet disconnectedIds = new HashSet(); + if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo(nameof(StopServer)); + var disconnectedIds = new HashSet(); //Don't know if I have to disconnect the clients. I'm assuming the NetworkTransport does all the cleaning on shtudown. But this way the clients get a disconnect message from server (so long it does't get lost) foreach (KeyValuePair pair in ConnectedClients) @@ -475,8 +471,7 @@ public void StopServer() if (!disconnectedIds.Contains(pair.Key)) { disconnectedIds.Add(pair.Key); - if (pair.Key == NetworkConfig.NetworkTransport.ServerClientId) - continue; + if (pair.Key == NetworkConfig.NetworkTransport.ServerClientId) continue; NetworkConfig.NetworkTransport.DisconnectRemoteClient(pair.Key); } @@ -491,7 +486,7 @@ public void StopServer() /// public void StopHost() { - if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("StopHost()"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo(nameof(StopHost)); IsServer = false; IsClient = false; StopServer(); @@ -503,7 +498,7 @@ public void StopHost() /// public void StopClient() { - if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("StopClient()"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo(nameof(StopClient)); IsClient = false; NetworkConfig.NetworkTransport.DisconnectLocalClient(); IsConnectedClient = false; @@ -515,7 +510,7 @@ public void StopClient() /// public SocketTasks StartHost(Vector3? position = null, Quaternion? rotation = null, bool? createPlayerObject = null, ulong? prefabHash = null, Stream payloadStream = null) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("StartHost()"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo(nameof(StartHost)); if (IsServer || IsClient) { @@ -533,7 +528,7 @@ public SocketTasks StartHost(Vector3? position = null, Quaternion? rotation = nu Init(true); - SocketTasks tasks = NetworkConfig.NetworkTransport.StartServer(); + var socketTasks = NetworkConfig.NetworkTransport.StartServer(); IsServer = true; IsClient = true; @@ -550,12 +545,12 @@ public SocketTasks StartHost(Vector3? position = null, Quaternion? rotation = nu if ((createPlayerObject == null && NetworkConfig.CreatePlayerPrefab) || (createPlayerObject != null && createPlayerObject.Value)) { - NetworkObject netObject = NetworkSpawnManager.CreateLocalNetworkObject(false, 0, (prefabHash == null ? NetworkConfig.PlayerPrefabHash.Value : prefabHash.Value), null, position, rotation); - NetworkSpawnManager.SpawnNetworkObjectLocally(netObject, NetworkSpawnManager.GetNetworkObjectId(), false, true, hostClientId, payloadStream, payloadStream != null, payloadStream == null ? 0 : (int)payloadStream.Length, false, false); + var networkObject = NetworkSpawnManager.CreateLocalNetworkObject(false, 0, prefabHash ?? NetworkConfig.PlayerPrefabHash.Value, null, position, rotation); + NetworkSpawnManager.SpawnNetworkObjectLocally(networkObject, NetworkSpawnManager.GetNetworkObjectId(), false, true, hostClientId, payloadStream, payloadStream != null, payloadStream == null ? 0 : (int)payloadStream.Length, false, false); - if (netObject.CheckObjectVisibility == null || netObject.CheckObjectVisibility(hostClientId)) + if (networkObject.CheckObjectVisibility == null || networkObject.CheckObjectVisibility(hostClientId)) { - netObject.observers.Add(hostClientId); + networkObject.m_Observers.Add(hostClientId); } } @@ -563,15 +558,14 @@ public SocketTasks StartHost(Vector3? position = null, Quaternion? rotation = nu OnServerStarted?.Invoke(); - return tasks; + return socketTasks; } public void SetSingleton() { Singleton = this; - if (OnSingletonReady != null) - OnSingletonReady(); + OnSingletonReady?.Invoke(); } private void OnEnable() @@ -583,15 +577,14 @@ private void OnEnable() } SetSingleton(); - if (DontDestroy) - DontDestroyOnLoad(gameObject); - if (RunInBackground) - Application.runInBackground = true; + + if (DontDestroy) DontDestroyOnLoad(gameObject); + if (RunInBackground) Application.runInBackground = true; } private void OnDestroy() { - if (Singleton != null && Singleton == this) + if (!ReferenceEquals(Singleton, null) && Singleton == this) { Shutdown(); Singleton = null; @@ -600,25 +593,24 @@ private void OnDestroy() public void Shutdown() { - if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("Shutdown()"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo(nameof(Shutdown)); // Unregister INetworkUpdateSystem before shutting down the RpcQueueContainer this.UnregisterAllNetworkUpdates(); //If an instance of the RpcQueueContainer is still around, then shut it down and remove the reference - if (rpcQueueContainer != null) + if (RpcQueueContainer != null) { - rpcQueueContainer.Shutdown(); - rpcQueueContainer = null; + RpcQueueContainer.Shutdown(); + RpcQueueContainer = null; } - if (networkTickSystem != null) + if (NetworkTickSystem != null) { - networkTickSystem.Dispose(); + NetworkTickSystem.Dispose(); + NetworkTickSystem = null; } - networkTickSystem = null; - #if !UNITY_2020_2_OR_LATER NetworkProfiler.Stop(); #endif @@ -630,8 +622,7 @@ public void Shutdown() NetworkSpawnManager.ServerResetShudownStateForSceneObjects(); //The Transport is set during Init time, thus it is possible for the Transport to be null - if (NetworkConfig != null && NetworkConfig.NetworkTransport != null) - NetworkConfig.NetworkTransport.Shutdown(); + NetworkConfig?.NetworkTransport?.Shutdown(); } // INetworkUpdateSystem @@ -667,26 +658,26 @@ private void OnNetworkEarlyUpdate() if ((NetworkTime - m_LastReceiveTickTime >= (1f / NetworkConfig.ReceiveTickrate)) || NetworkConfig.ReceiveTickrate <= 0) { PerformanceDataManager.Increment(ProfilerConstants.ReceiveTickRate); - ProfilerStatManager.rcvTickRate.Record(); + ProfilerStatManager.RcvTickRate.Record(); #if DEVELOPMENT_BUILD || UNITY_EDITOR s_ReceiveTick.Begin(); #endif - var IsLoopBack = false; + var isLoopBack = false; #if !UNITY_2020_2_OR_LATER NetworkProfiler.StartTick(TickType.Receive); #endif //If we are in loopback mode, we don't need to touch the transport - if (!IsLoopBack) + if (!isLoopBack) { NetworkEvent networkEvent; int processedEvents = 0; do { processedEvents++; - networkEvent = NetworkConfig.NetworkTransport.PollEvent(out ulong clientId, out NetworkChannel channel, out ArraySegment payload, out float receiveTime); - HandleRawTransportPoll(networkEvent, clientId, channel, payload, receiveTime); + networkEvent = NetworkConfig.NetworkTransport.PollEvent(out ulong clientId, out NetworkChannel networkChannel, out ArraySegment payload, out float receiveTime); + HandleRawTransportPoll(networkEvent, clientId, networkChannel, payload, receiveTime); // Only do another iteration if: there are no more messages AND (there is no limit to max events or we have processed less than the maximum) } while (IsListening && (networkEvent != NetworkEvent.Nothing) && (NetworkConfig.MaxReceiveEventsPerTickRate <= 0 || processedEvents < NetworkConfig.MaxReceiveEventsPerTickRate)); @@ -772,12 +763,12 @@ private void OnNetworkPreUpdate() #endif } - if (!Mathf.Approximately(networkTimeOffset, currentNetworkTimeOffset)) + if (!Mathf.Approximately(m_NetworkTimeOffset, m_CurrentNetworkTimeOffset)) { // Smear network time adjustments by no more than 200ms per second. This should help code deal with // changes more gracefully, since the network time will always flow forward at a reasonable pace. float maxDelta = Mathf.Max(0.001f, 0.2f * Time.unscaledDeltaTime); - currentNetworkTimeOffset += Mathf.Clamp(networkTimeOffset - currentNetworkTimeOffset, -maxDelta, maxDelta); + m_CurrentNetworkTimeOffset += Mathf.Clamp(m_NetworkTimeOffset - m_CurrentNetworkTimeOffset, -maxDelta, maxDelta); } } @@ -793,25 +784,29 @@ private void OnNetworkPreUpdate() internal void UpdateNetworkTime(ulong clientId, float netTime, float receiveTime, bool warp = false) { float rtt = NetworkConfig.NetworkTransport.GetCurrentRtt(clientId) / 1000f; - networkTimeOffset = netTime - receiveTime + rtt / 2f; + m_NetworkTimeOffset = netTime - receiveTime + rtt / 2f; + if (warp) { - currentNetworkTimeOffset = networkTimeOffset; + m_CurrentNetworkTimeOffset = m_NetworkTimeOffset; } - if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo($"Received network time {netTime}, RTT to server is {rtt}, {(warp ? "setting" : "smearing")} offset to {networkTimeOffset} (delta {networkTimeOffset - currentNetworkTimeOffset})"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) + { + NetworkLog.LogInfo($"Received network time {netTime}, RTT to server is {rtt}, {(warp ? "setting" : "smearing")} offset to {m_NetworkTimeOffset} (delta {m_NetworkTimeOffset - m_CurrentNetworkTimeOffset})"); + } } - internal void SendConnectionRequest() + private void SendConnectionRequest() { - using (PooledNetworkBuffer buffer = PooledNetworkBuffer.Get()) + using (var buffer = PooledNetworkBuffer.Get()) + using (var writer = PooledNetworkWriter.Get(buffer)) { - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(buffer)) - { - writer.WriteUInt64Packed(NetworkConfig.GetConfig()); + writer.WriteUInt64Packed(NetworkConfig.GetConfig()); - if (NetworkConfig.ConnectionApproval) - writer.WriteByteArray(NetworkConfig.ConnectionData); + if (NetworkConfig.ConnectionApproval) + { + writer.WriteByteArray(NetworkConfig.ConnectionData); } InternalMessageSender.Send(ServerClientId, NetworkConstants.CONNECTION_REQUEST, NetworkChannel.Internal, buffer); @@ -821,6 +816,7 @@ internal void SendConnectionRequest() private IEnumerator ApprovalTimeout(ulong clientId) { float timeStarted = NetworkTime; + //We yield every frame incase a pending client disconnects and someone else gets its connection id while (NetworkTime - timeStarted < NetworkConfig.ClientConnectionBufferTimeout && PendingClients.ContainsKey(clientId)) { @@ -830,7 +826,11 @@ private IEnumerator ApprovalTimeout(ulong clientId) if (PendingClients.ContainsKey(clientId) && !ConnectedClients.ContainsKey(clientId)) { // Timeout - if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("Client " + clientId + " Handshake Timed Out"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) + { + NetworkLog.LogInfo($"Client {clientId} Handshake Timed Out"); + } + DisconnectClient(clientId); } } @@ -844,7 +844,8 @@ internal IEnumerator TimeOutSwitchSceneProgress(SceneSwitchProgress switchSceneP private void HandleRawTransportPoll(NetworkEvent networkEvent, ulong clientId, NetworkChannel networkChannel, ArraySegment payload, float receiveTime) { PerformanceDataManager.Increment(ProfilerConstants.NumberBytesReceived, payload.Count); - ProfilerStatManager.bytesRcvd.Record(payload.Count); + ProfilerStatManager.BytesRcvd.Record(payload.Count); + switch (networkEvent) { case NetworkEvent.Connect: @@ -856,18 +857,25 @@ private void HandleRawTransportPoll(NetworkEvent networkEvent, ulong clientId, N #endif if (IsServer) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("Client Connected"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) + { + NetworkLog.LogInfo("Client Connected"); + } PendingClients.Add(clientId, new PendingClient() { ClientId = clientId, ConnectionState = PendingClient.State.PendingConnection }); + StartCoroutine(ApprovalTimeout(clientId)); } else { - if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("Connected"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) + { + NetworkLog.LogInfo("Connected"); + } SendConnectionRequest(); StartCoroutine(ApprovalTimeout(clientId)); @@ -882,7 +890,11 @@ private void HandleRawTransportPoll(NetworkEvent networkEvent, ulong clientId, N break; case NetworkEvent.Data: { - if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo($"Incoming Data From {clientId} : {payload.Count} bytes"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) + { + NetworkLog.LogInfo($"Incoming Data From {clientId}: {payload.Count} bytes"); + } + HandleIncomingData(clientId, networkChannel, payload, receiveTime, true); break; } @@ -894,18 +906,19 @@ private void HandleRawTransportPoll(NetworkEvent networkEvent, ulong clientId, N NetworkProfiler.StartEvent(TickType.Receive, 0, NetworkChannel.Internal, "TRANSPORT_DISCONNECT"); #endif - if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("Disconnect Event From " + clientId); + if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) + { + NetworkLog.LogInfo($"Disconnect Event From {clientId}"); + } - if (IsServer) - OnClientDisconnectFromServer(clientId); + if (IsServer) OnClientDisconnectFromServer(clientId); else { IsConnectedClient = false; StopClient(); } - if (OnClientDisconnectCallback != null) - OnClientDisconnectCallback.Invoke(clientId); + OnClientDisconnectCallback?.Invoke(clientId); #if !UNITY_2020_2_OR_LATER NetworkProfiler.EndEvent(); @@ -925,7 +938,10 @@ internal void HandleIncomingData(ulong clientId, NetworkChannel networkChannel, #if DEVELOPMENT_BUILD || UNITY_EDITOR s_HandleIncomingData.Begin(); #endif - if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("Unwrapping Data Header"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) + { + NetworkLog.LogInfo("Unwrapping Data Header"); + } m_InputBufferWrapper.SetTarget(data.Array); m_InputBufferWrapper.SetLength(data.Count + data.Offset); @@ -935,13 +951,21 @@ internal void HandleIncomingData(ulong clientId, NetworkChannel networkChannel, { if (messageStream == null) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Error) NetworkLog.LogError("Message unwrap could not be completed. Was the header corrupt? Crypto error?"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Error) + { + NetworkLog.LogError("Message unwrap could not be completed. Was the header corrupt? Crypto error?"); + } + return; } if (messageType == NetworkConstants.INVALID) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Error) NetworkLog.LogError("Message unwrap read an invalid messageType"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Error) + { + NetworkLog.LogError($"Message unwrap read an invalid {nameof(messageType)}"); + } + return; } @@ -951,12 +975,19 @@ internal void HandleIncomingData(ulong clientId, NetworkChannel networkChannel, NetworkProfiler.StartEvent(TickType.Receive, (uint)(data.Count - headerByteSize), networkChannel, messageType); #endif - if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("Data Header: messageType=" + messageType); + if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) + { + NetworkLog.LogInfo($"Data Header: {nameof(messageType)}={messageType}"); + } // Client tried to send a network message that was not the connection request before he was accepted. if (PendingClients.ContainsKey(clientId) && PendingClients[clientId].ConnectionState == PendingClient.State.PendingConnection && messageType != NetworkConstants.CONNECTION_REQUEST) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("Message received from clientId " + clientId + " before it has been accepted"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarning($"Message received from {nameof(clientId)}={clientId} before it has been accepted"); + } + return; } @@ -1029,21 +1060,15 @@ internal void HandleIncomingData(ulong clientId, NetworkChannel networkChannel, { if (IsServer) { - if (rpcQueueContainer.IsUsingBatching()) + if (RpcQueueContainer.IsUsingBatching()) { m_RpcBatcher.ReceiveItems(messageStream, ReceiveCallback, RpcQueueContainer.QueueItemType.ServerRpc, clientId, receiveTime); - ProfilerStatManager.rpcBatchesRcvd.Record(); + ProfilerStatManager.RpcBatchesRcvd.Record(); PerformanceDataManager.Increment(ProfilerConstants.NumberOfRPCBatchesReceived); } else { -#if DEVELOPMENT_BUILD || UNITY_EDITOR - s_ServerRpcQueued.Begin(); -#endif InternalMessageHandler.RpcReceiveQueueItem(clientId, messageStream, receiveTime, RpcQueueContainer.QueueItemType.ServerRpc); -#if DEVELOPMENT_BUILD || UNITY_EDITOR - s_ServerRpcQueued.End(); -#endif } } @@ -1053,28 +1078,26 @@ internal void HandleIncomingData(ulong clientId, NetworkChannel networkChannel, { if (IsClient) { - if (rpcQueueContainer.IsUsingBatching()) + if (RpcQueueContainer.IsUsingBatching()) { m_RpcBatcher.ReceiveItems(messageStream, ReceiveCallback, RpcQueueContainer.QueueItemType.ClientRpc, clientId, receiveTime); - ProfilerStatManager.rpcBatchesRcvd.Record(); + ProfilerStatManager.RpcBatchesRcvd.Record(); PerformanceDataManager.Increment(ProfilerConstants.NumberOfRPCBatchesReceived); } else { -#if DEVELOPMENT_BUILD || UNITY_EDITOR - s_ClientRpcQueued.Begin(); -#endif InternalMessageHandler.RpcReceiveQueueItem(clientId, messageStream, receiveTime, RpcQueueContainer.QueueItemType.ClientRpc); -#if DEVELOPMENT_BUILD || UNITY_EDITOR - s_ClientRpcQueued.End(); -#endif } } break; } default: - if (NetworkLog.CurrentLogLevel <= LogLevel.Error) NetworkLog.LogError("Read unrecognized messageType " + messageType); + if (NetworkLog.CurrentLogLevel <= LogLevel.Error) + { + NetworkLog.LogError($"Read unrecognized {nameof(messageType)}={messageType}"); + } + break; } @@ -1091,27 +1114,7 @@ internal void HandleIncomingData(ulong clientId, NetworkChannel networkChannel, private static void ReceiveCallback(NetworkBuffer messageBuffer, RpcQueueContainer.QueueItemType messageType, ulong clientId, float receiveTime) { -#if DEVELOPMENT_BUILD || UNITY_EDITOR - if (messageType == RpcQueueContainer.QueueItemType.ServerRpc) - { - s_ServerRpcQueued.Begin(); - } - else - { - s_ClientRpcQueued.Begin(); - } -#endif InternalMessageHandler.RpcReceiveQueueItem(clientId, messageBuffer, receiveTime, messageType); -#if DEVELOPMENT_BUILD || UNITY_EDITOR - if (messageType == RpcQueueContainer.QueueItemType.ServerRpc) - { - s_ServerRpcQueued.End(); - } - else - { - s_ClientRpcQueued.End(); - } -#endif } /// @@ -1125,10 +1128,10 @@ internal static void InvokeRpc(RpcFrameQueueItem queueItem) #if DEVELOPMENT_BUILD || UNITY_EDITOR s_InvokeRpc.Begin(); #endif - var networkObjectId = queueItem.streamReader.ReadUInt64Packed(); - var networkBehaviourId = queueItem.streamReader.ReadUInt16Packed(); - var networkUpdateStage = queueItem.streamReader.ReadByteDirect(); - var networkMethodId = queueItem.streamReader.ReadUInt32Packed(); + var networkObjectId = queueItem.NetworkReader.ReadUInt64Packed(); + var networkBehaviourId = queueItem.NetworkReader.ReadUInt16Packed(); + var networkUpdateStage = queueItem.NetworkReader.ReadByteDirect(); + var networkMethodId = queueItem.NetworkReader.ReadUInt32Packed(); if (__ntable.ContainsKey(networkMethodId)) { @@ -1139,7 +1142,7 @@ internal static void InvokeRpc(RpcFrameQueueItem queueItem) if (ReferenceEquals(networkBehaviour, null)) return; var rpcParams = new __RpcParams(); - switch (queueItem.queueItemType) + switch (queueItem.QueueItemType) { case RpcQueueContainer.QueueItemType.ServerRpc: rpcParams.Server = new ServerRpcParams @@ -1147,7 +1150,7 @@ internal static void InvokeRpc(RpcFrameQueueItem queueItem) Receive = new ServerRpcReceiveParams { UpdateStage = (NetworkUpdateStage)networkUpdateStage, - SenderClientId = queueItem.networkId + SenderClientId = queueItem.NetworkId } }; break; @@ -1162,7 +1165,7 @@ internal static void InvokeRpc(RpcFrameQueueItem queueItem) break; } - __ntable[networkMethodId](networkBehaviour, new NetworkSerializer(queueItem.streamReader), rpcParams); + __ntable[networkMethodId](networkBehaviour, new NetworkSerializer(queueItem.NetworkReader), rpcParams); } #pragma warning restore 618 @@ -1176,7 +1179,11 @@ private void BufferCallback(ulong networkId, PreBufferPreset preset) if (!preset.AllowBuffer) { // This is to prevent recursive buffering - if (NetworkLog.CurrentLogLevel <= LogLevel.Error) NetworkLog.LogError("A message of type " + NetworkConstants.MESSAGE_NAMES[preset.MessageType] + " was recursivley buffered. It has been dropped."); + if (NetworkLog.CurrentLogLevel <= LogLevel.Error) + { + NetworkLog.LogError($"A message of type {NetworkConstants.MESSAGE_NAMES[preset.MessageType]} was recursivley buffered. It has been dropped."); + } + return; } @@ -1204,11 +1211,8 @@ public void DisconnectClient(ulong clientId) throw new NotServerException("Only server can disconnect remote clients. Use StopClient instead."); } - if (ConnectedClients.ContainsKey(clientId)) - ConnectedClients.Remove(clientId); - - if (PendingClients.ContainsKey(clientId)) - PendingClients.Remove(clientId); + if (ConnectedClients.ContainsKey(clientId)) ConnectedClients.Remove(clientId); + if (PendingClients.ContainsKey(clientId)) PendingClients.Remove(clientId); for (int i = ConnectedClientsList.Count - 1; i > -1; i--) { @@ -1216,7 +1220,7 @@ public void DisconnectClient(ulong clientId) { ConnectedClientsList.RemoveAt(i); PerformanceDataManager.Increment(ProfilerConstants.NumberOfConnections, -1); - ProfilerStatManager.connections.Record(-1); + ProfilerStatManager.Connections.Record(-1); } } @@ -1225,8 +1229,7 @@ public void DisconnectClient(ulong clientId) internal void OnClientDisconnectFromServer(ulong clientId) { - if (PendingClients.ContainsKey(clientId)) - PendingClients.Remove(clientId); + if (PendingClients.ContainsKey(clientId)) PendingClients.Remove(clientId); if (ConnectedClients.ContainsKey(clientId)) { @@ -1234,9 +1237,9 @@ internal void OnClientDisconnectFromServer(ulong clientId) { if (ConnectedClients[clientId].PlayerObject != null) { - if (NetworkSpawnManager.customDestroyHandlers.ContainsKey(ConnectedClients[clientId].PlayerObject.PrefabHash)) + if (NetworkSpawnManager.CustomDestroyHandlers.ContainsKey(ConnectedClients[clientId].PlayerObject.PrefabHash)) { - NetworkSpawnManager.customDestroyHandlers[ConnectedClients[clientId].PlayerObject.PrefabHash](ConnectedClients[clientId].PlayerObject); + NetworkSpawnManager.CustomDestroyHandlers[ConnectedClients[clientId].PlayerObject.PrefabHash](ConnectedClients[clientId].PlayerObject); NetworkSpawnManager.OnDestroyObject(ConnectedClients[clientId].PlayerObject.NetworkObjectId, false); } else @@ -1251,9 +1254,9 @@ internal void OnClientDisconnectFromServer(ulong clientId) { if (!ConnectedClients[clientId].OwnedObjects[i].DontDestroyWithOwner) { - if (NetworkSpawnManager.customDestroyHandlers.ContainsKey(ConnectedClients[clientId].OwnedObjects[i].PrefabHash)) + if (NetworkSpawnManager.CustomDestroyHandlers.ContainsKey(ConnectedClients[clientId].OwnedObjects[i].PrefabHash)) { - NetworkSpawnManager.customDestroyHandlers[ConnectedClients[clientId].OwnedObjects[i].PrefabHash](ConnectedClients[clientId].OwnedObjects[i]); + NetworkSpawnManager.CustomDestroyHandlers[ConnectedClients[clientId].OwnedObjects[i].PrefabHash](ConnectedClients[clientId].OwnedObjects[i]); NetworkSpawnManager.OnDestroyObject(ConnectedClients[clientId].OwnedObjects[i].NetworkObjectId, false); } else @@ -1272,7 +1275,7 @@ internal void OnClientDisconnectFromServer(ulong clientId) foreach (var sobj in NetworkSpawnManager.SpawnedObjectsList) { - sobj.observers.Remove(clientId); + sobj.m_Observers.Remove(clientId); } } @@ -1282,7 +1285,7 @@ internal void OnClientDisconnectFromServer(ulong clientId) { ConnectedClientsList.RemoveAt(i); PerformanceDataManager.Increment(ProfilerConstants.NumberOfConnections, -1); - ProfilerStatManager.connections.Record(-1); + ProfilerStatManager.Connections.Record(-1); break; } } @@ -1296,38 +1299,37 @@ private void SyncTime() #if DEVELOPMENT_BUILD || UNITY_EDITOR s_SyncTime.Begin(); #endif - if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("Syncing Time To Clients"); - using (PooledNetworkBuffer buffer = PooledNetworkBuffer.Get()) + if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) { - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(buffer)) - { - writer.WriteSinglePacked(Time.realtimeSinceStartup); - InternalMessageSender.Send(NetworkConstants.TIME_SYNC, NetworkChannel.SyncChannel, buffer); - } + NetworkLog.LogInfo("Syncing Time To Clients"); + } + + using (var buffer = PooledNetworkBuffer.Get()) + using (var writer = PooledNetworkWriter.Get(buffer)) + { + writer.WriteSinglePacked(Time.realtimeSinceStartup); + InternalMessageSender.Send(NetworkConstants.TIME_SYNC, NetworkChannel.SyncChannel, buffer); } #if DEVELOPMENT_BUILD || UNITY_EDITOR s_SyncTime.End(); #endif } - private readonly List _observedObjects = new List(); + private readonly List m_ObservedObjects = new List(); internal void HandleApproval(ulong clientId, bool createPlayerObject, ulong? playerPrefabHash, bool approved, Vector3? position, Quaternion? rotation) { if (approved) { // Inform new client it got approved - if (PendingClients.ContainsKey(clientId)) - PendingClients.Remove(clientId); - NetworkClient client = new NetworkClient() - { - ClientId = clientId, - }; + if (PendingClients.ContainsKey(clientId)) PendingClients.Remove(clientId); + + var client = new NetworkClient { ClientId = clientId, }; ConnectedClients.Add(clientId, client); ConnectedClientsList.Add(client); PerformanceDataManager.Increment(ProfilerConstants.NumberOfConnections); - ProfilerStatManager.connections.Record(); + ProfilerStatManager.Connections.Record(); // This packet is unreliable, but if it gets through it should provide a much better sync than the potentially huge approval message. SyncTime(); @@ -1335,108 +1337,105 @@ internal void HandleApproval(ulong clientId, bool createPlayerObject, ulong? pla if (createPlayerObject) { - NetworkObject netObject = NetworkSpawnManager.CreateLocalNetworkObject(false, 0, (playerPrefabHash == null ? NetworkConfig.PlayerPrefabHash.Value : playerPrefabHash.Value), null, position, rotation); - NetworkSpawnManager.SpawnNetworkObjectLocally(netObject, NetworkSpawnManager.GetNetworkObjectId(), false, true, clientId, null, false, 0, false, false); + var networkObject = NetworkSpawnManager.CreateLocalNetworkObject(false, 0, playerPrefabHash ?? NetworkConfig.PlayerPrefabHash.Value, null, position, rotation); + NetworkSpawnManager.SpawnNetworkObjectLocally(networkObject, NetworkSpawnManager.GetNetworkObjectId(), false, true, clientId, null, false, 0, false, false); - ConnectedClients[clientId].PlayerObject = netObject; + ConnectedClients[clientId].PlayerObject = networkObject; } - _observedObjects.Clear(); + m_ObservedObjects.Clear(); foreach (var sobj in NetworkSpawnManager.SpawnedObjectsList) { if (clientId == ServerClientId || sobj.CheckObjectVisibility == null || sobj.CheckObjectVisibility(clientId)) { - _observedObjects.Add(sobj); - sobj.observers.Add(clientId); + m_ObservedObjects.Add(sobj); + sobj.m_Observers.Add(clientId); } } - using (PooledNetworkBuffer buffer = PooledNetworkBuffer.Get()) + using (var buffer = PooledNetworkBuffer.Get()) + using (var writer = PooledNetworkWriter.Get(buffer)) { - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(buffer)) + writer.WriteUInt64Packed(clientId); + + if (NetworkConfig.EnableSceneManagement) { - writer.WriteUInt64Packed(clientId); + writer.WriteUInt32Packed(NetworkSceneManager.CurrentSceneIndex); + writer.WriteByteArray(NetworkSceneManager.CurrentSceneSwitchProgressGuid.ToByteArray()); + } - if (NetworkConfig.EnableSceneManagement) - { - writer.WriteUInt32Packed(NetworkSceneManager.currentSceneIndex); - writer.WriteByteArray(NetworkSceneManager.currentSceneSwitchProgressGuid.ToByteArray()); - } + writer.WriteSinglePacked(Time.realtimeSinceStartup); + writer.WriteUInt32Packed((uint)m_ObservedObjects.Count); - writer.WriteSinglePacked(Time.realtimeSinceStartup); + for (int i = 0; i < m_ObservedObjects.Count; i++) + { + var observedObject = m_ObservedObjects[i]; + writer.WriteBool(observedObject.IsPlayerObject); + writer.WriteUInt64Packed(observedObject.NetworkObjectId); + writer.WriteUInt64Packed(observedObject.OwnerClientId); - writer.WriteUInt32Packed((uint)_observedObjects.Count); + NetworkObject parent = null; - for (int i = 0; i < _observedObjects.Count; i++) + if (!observedObject.AlwaysReplicateAsRoot && observedObject.transform.parent != null) { - NetworkObject observedObject = _observedObjects[i]; - writer.WriteBool(observedObject.IsPlayerObject); - writer.WriteUInt64Packed(observedObject.NetworkObjectId); - writer.WriteUInt64Packed(observedObject.OwnerClientId); + parent = observedObject.transform.parent.GetComponent(); + } - NetworkObject parent = null; + if (parent == null) + { + writer.WriteBool(false); + } + else + { + writer.WriteBool(true); + writer.WriteUInt64Packed(parent.NetworkObjectId); + } - if (!observedObject.AlwaysReplicateAsRoot && observedObject.transform.parent != null) - { - parent = observedObject.transform.parent.GetComponent(); - } + if (!NetworkConfig.EnableSceneManagement || NetworkConfig.UsePrefabSync) + { + writer.WriteUInt64Packed(observedObject.PrefabHash); + } + else + { + // Is this a scene object that we will soft map + writer.WriteBool(observedObject.IsSceneObject ?? true); - if (parent == null) + if (observedObject.IsSceneObject == null || observedObject.IsSceneObject.Value) { - writer.WriteBool(false); + writer.WriteUInt64Packed(observedObject.NetworkInstanceId); } else - { - writer.WriteBool(true); - writer.WriteUInt64Packed(parent.NetworkObjectId); - } - - if (!NetworkConfig.EnableSceneManagement || NetworkConfig.UsePrefabSync) { writer.WriteUInt64Packed(observedObject.PrefabHash); } - else - { - // Is this a scene object that we will soft map - writer.WriteBool(observedObject.IsSceneObject == null ? true : observedObject.IsSceneObject.Value); + } - if (observedObject.IsSceneObject == null || observedObject.IsSceneObject.Value == true) - { - writer.WriteUInt64Packed(observedObject.NetworkInstanceId); - } - else - { - writer.WriteUInt64Packed(observedObject.PrefabHash); - } - } + if (observedObject.IncludeTransformWhenSpawning == null || observedObject.IncludeTransformWhenSpawning(clientId)) + { + writer.WriteBool(true); + writer.WriteSinglePacked(observedObject.transform.position.x); + writer.WriteSinglePacked(observedObject.transform.position.y); + writer.WriteSinglePacked(observedObject.transform.position.z); - if (observedObject.IncludeTransformWhenSpawning == null || observedObject.IncludeTransformWhenSpawning(clientId)) - { - writer.WriteBool(true); - writer.WriteSinglePacked(observedObject.transform.position.x); - writer.WriteSinglePacked(observedObject.transform.position.y); - writer.WriteSinglePacked(observedObject.transform.position.z); - - writer.WriteSinglePacked(observedObject.transform.rotation.eulerAngles.x); - writer.WriteSinglePacked(observedObject.transform.rotation.eulerAngles.y); - writer.WriteSinglePacked(observedObject.transform.rotation.eulerAngles.z); - } - else - { - writer.WriteBool(false); - } + writer.WriteSinglePacked(observedObject.transform.rotation.eulerAngles.x); + writer.WriteSinglePacked(observedObject.transform.rotation.eulerAngles.y); + writer.WriteSinglePacked(observedObject.transform.rotation.eulerAngles.z); + } + else + { + writer.WriteBool(false); + } - if (NetworkConfig.EnableNetworkVariable) - { - observedObject.WriteNetworkVariableData(buffer, clientId); - } + if (NetworkConfig.EnableNetworkVariable) + { + observedObject.WriteNetworkVariableData(buffer, clientId); } + } - InternalMessageSender.Send(clientId, NetworkConstants.CONNECTION_APPROVED, NetworkChannel.Internal, buffer); + InternalMessageSender.Send(clientId, NetworkConstants.CONNECTION_APPROVED, NetworkChannel.Internal, buffer); - OnClientConnectedCallback?.Invoke(clientId); - } + OnClientConnectedCallback?.Invoke(clientId); } if (!createPlayerObject || (playerPrefabHash == null && NetworkConfig.PlayerPrefabHash == null)) return; @@ -1445,56 +1444,56 @@ internal void HandleApproval(ulong clientId, bool createPlayerObject, ulong? pla foreach (KeyValuePair clientPair in ConnectedClients) { - if (clientPair.Key == clientId || ConnectedClients[clientId].PlayerObject == null || !ConnectedClients[clientId].PlayerObject.observers.Contains(clientPair.Key)) + if (clientPair.Key == clientId || + ConnectedClients[clientId].PlayerObject == null || + !ConnectedClients[clientId].PlayerObject.m_Observers.Contains(clientPair.Key)) continue; //The new client. - using (PooledNetworkBuffer buffer = PooledNetworkBuffer.Get()) + using (var buffer = PooledNetworkBuffer.Get()) + using (var writer = PooledNetworkWriter.Get(buffer)) { - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(buffer)) - { - writer.WriteBool(true); - writer.WriteUInt64Packed(ConnectedClients[clientId].PlayerObject.NetworkObjectId); - writer.WriteUInt64Packed(clientId); + writer.WriteBool(true); + writer.WriteUInt64Packed(ConnectedClients[clientId].PlayerObject.NetworkObjectId); + writer.WriteUInt64Packed(clientId); - //Does not have a parent - writer.WriteBool(false); + //Does not have a parent + writer.WriteBool(false); - if (!NetworkConfig.EnableSceneManagement || NetworkConfig.UsePrefabSync) - { - writer.WriteUInt64Packed(playerPrefabHash == null ? NetworkConfig.PlayerPrefabHash.Value : playerPrefabHash.Value); - } - else - { - // Not a softmap aka scene object - writer.WriteBool(false); - writer.WriteUInt64Packed(playerPrefabHash == null ? NetworkConfig.PlayerPrefabHash.Value : playerPrefabHash.Value); - } + if (!NetworkConfig.EnableSceneManagement || NetworkConfig.UsePrefabSync) + { + writer.WriteUInt64Packed(playerPrefabHash ?? NetworkConfig.PlayerPrefabHash.Value); + } + else + { + // Not a softmap aka scene object + writer.WriteBool(false); + writer.WriteUInt64Packed(playerPrefabHash ?? NetworkConfig.PlayerPrefabHash.Value); + } - if (ConnectedClients[clientId].PlayerObject.IncludeTransformWhenSpawning == null || ConnectedClients[clientId].PlayerObject.IncludeTransformWhenSpawning(clientId)) - { - writer.WriteBool(true); - writer.WriteSinglePacked(ConnectedClients[clientId].PlayerObject.transform.position.x); - writer.WriteSinglePacked(ConnectedClients[clientId].PlayerObject.transform.position.y); - writer.WriteSinglePacked(ConnectedClients[clientId].PlayerObject.transform.position.z); - - writer.WriteSinglePacked(ConnectedClients[clientId].PlayerObject.transform.rotation.eulerAngles.x); - writer.WriteSinglePacked(ConnectedClients[clientId].PlayerObject.transform.rotation.eulerAngles.y); - writer.WriteSinglePacked(ConnectedClients[clientId].PlayerObject.transform.rotation.eulerAngles.z); - } - else - { - writer.WriteBool(false); - } + if (ConnectedClients[clientId].PlayerObject.IncludeTransformWhenSpawning == null || ConnectedClients[clientId].PlayerObject.IncludeTransformWhenSpawning(clientId)) + { + writer.WriteBool(true); + writer.WriteSinglePacked(ConnectedClients[clientId].PlayerObject.transform.position.x); + writer.WriteSinglePacked(ConnectedClients[clientId].PlayerObject.transform.position.y); + writer.WriteSinglePacked(ConnectedClients[clientId].PlayerObject.transform.position.z); - writer.WriteBool(false); //No payload data + writer.WriteSinglePacked(ConnectedClients[clientId].PlayerObject.transform.rotation.eulerAngles.x); + writer.WriteSinglePacked(ConnectedClients[clientId].PlayerObject.transform.rotation.eulerAngles.y); + writer.WriteSinglePacked(ConnectedClients[clientId].PlayerObject.transform.rotation.eulerAngles.z); + } + else + { + writer.WriteBool(false); + } - if (NetworkConfig.EnableNetworkVariable) - { - ConnectedClients[clientId].PlayerObject.WriteNetworkVariableData(buffer, clientPair.Key); - } + writer.WriteBool(false); //No payload data - InternalMessageSender.Send(clientPair.Key, NetworkConstants.ADD_OBJECT, NetworkChannel.Internal, buffer); + if (NetworkConfig.EnableNetworkVariable) + { + ConnectedClients[clientId].PlayerObject.WriteNetworkVariableData(buffer, clientPair.Key); } + + InternalMessageSender.Send(clientPair.Key, NetworkConstants.ADD_OBJECT, NetworkChannel.Internal, buffer); } } } diff --git a/com.unity.multiplayer.mlapi/Runtime/Core/NetworkObject.cs b/com.unity.multiplayer.mlapi/Runtime/Core/NetworkObject.cs index d852041f75..8925de32fe 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Core/NetworkObject.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Core/NetworkObject.cs @@ -52,27 +52,29 @@ public ulong OwnerClientId { get { - if (_ownerClientId == null) + if (OwnerClientIdInternal == null) { return !ReferenceEquals(NetworkManager.Singleton, null) ? NetworkManager.Singleton.ServerClientId : 0; } - - return _ownerClientId.Value; + else + { + return OwnerClientIdInternal.Value; + } } internal set { if (!ReferenceEquals(NetworkManager.Singleton, null) && value == NetworkManager.Singleton.ServerClientId) { - _ownerClientId = null; + OwnerClientIdInternal = null; } else { - _ownerClientId = value; + OwnerClientIdInternal = value; } } } - internal ulong? _ownerClientId = null; + internal ulong? OwnerClientIdInternal = null; /// /// InstanceId is the id that is unique to the object and scene for a scene object when UsePrefabSync is false. @@ -111,17 +113,17 @@ internal set /// /// Gets if the object is the the personal clients player object /// - public bool IsLocalPlayer => NetworkManager.Singleton != null && IsPlayerObject && OwnerClientId == NetworkManager.Singleton.LocalClientId; + public bool IsLocalPlayer => !ReferenceEquals(NetworkManager.Singleton, null) && IsPlayerObject && OwnerClientId == NetworkManager.Singleton.LocalClientId; /// /// Gets if the object is owned by the local player or if the object is the local player object /// - public bool IsOwner => NetworkManager.Singleton != null && OwnerClientId == NetworkManager.Singleton.LocalClientId; + public bool IsOwner => !ReferenceEquals(NetworkManager.Singleton, null) && OwnerClientId == NetworkManager.Singleton.LocalClientId; /// /// Gets Whether or not the object is owned by anyone /// - public bool IsOwnedByServer => NetworkManager.Singleton != null && OwnerClientId == NetworkManager.Singleton.ServerClientId; + public bool IsOwnedByServer => !ReferenceEquals(NetworkManager.Singleton, null) && OwnerClientId == NetworkManager.Singleton.ServerClientId; /// /// Gets if the object has yet been spawned across the network @@ -166,7 +168,7 @@ internal set /// public bool DontDestroyWithOwner; - internal readonly HashSet observers = new HashSet(); + internal readonly HashSet m_Observers = new HashSet(); /// /// Returns Observers enumerator @@ -179,7 +181,7 @@ public HashSet.Enumerator GetObservers() throw new SpawnStateException("Object is not spawned"); } - return observers.GetEnumerator(); + return m_Observers.GetEnumerator(); } /// @@ -194,7 +196,7 @@ public bool IsNetworkVisibleTo(ulong clientId) throw new SpawnStateException("Object is not spawned"); } - return observers.Contains(clientId); + return m_Observers.Contains(clientId); } /// @@ -214,13 +216,13 @@ public void NetworkShow(ulong clientId, Stream payload = null) throw new NotServerException("Only server can change visibility"); } - if (observers.Contains(clientId)) + if (m_Observers.Contains(clientId)) { throw new VisibilityChangeException("The object is already visible"); } // Send spawn call - observers.Add(clientId); + m_Observers.Add(clientId); NetworkSpawnManager.SendSpawnCallForObject(clientId, this, payload); } @@ -246,23 +248,21 @@ public static void NetworkShow(List networkObjects, ulong clientI throw new SpawnStateException("Object is not spawned"); } - if (networkObjects[i].observers.Contains(clientId)) + if (networkObjects[i].m_Observers.Contains(clientId)) { throw new VisibilityChangeException($"{nameof(NetworkObject)} with NetworkId: {networkObjects[i].NetworkObjectId} is already visible"); } } - using (PooledNetworkBuffer buffer = PooledNetworkBuffer.Get()) + using (var buffer = PooledNetworkBuffer.Get()) + using (var writer = PooledNetworkWriter.Get(buffer)) { - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(buffer)) - { - writer.WriteUInt16Packed((ushort)networkObjects.Count); - } + writer.WriteUInt16Packed((ushort)networkObjects.Count); for (int i = 0; i < networkObjects.Count; i++) { // Send spawn call - networkObjects[i].observers.Add(clientId); + networkObjects[i].m_Observers.Add(clientId); NetworkSpawnManager.WriteSpawnCallForObject(buffer, clientId, networkObjects[i], payload); } @@ -287,7 +287,7 @@ public void NetworkHide(ulong clientId) throw new NotServerException("Only server can change visibility"); } - if (!observers.Contains(clientId)) + if (!m_Observers.Contains(clientId)) { throw new VisibilityChangeException("The object is already hidden"); } @@ -299,16 +299,14 @@ public void NetworkHide(ulong clientId) // Send destroy call - observers.Remove(clientId); + m_Observers.Remove(clientId); - using (PooledNetworkBuffer buffer = PooledNetworkBuffer.Get()) + using (var buffer = PooledNetworkBuffer.Get()) + using (var writer = PooledNetworkWriter.Get(buffer)) { - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(buffer)) - { - writer.WriteUInt64Packed(NetworkObjectId); + writer.WriteUInt64Packed(NetworkObjectId); - InternalMessageSender.Send(clientId, NetworkConstants.DESTROY_OBJECT, NetworkChannel.Internal, buffer); - } + InternalMessageSender.Send(clientId, NetworkConstants.DESTROY_OBJECT, NetworkChannel.Internal, buffer); } } @@ -337,26 +335,23 @@ public static void NetworkHide(List networkObjects, ulong clientI throw new SpawnStateException("Object is not spawned"); } - if (!networkObjects[i].observers.Contains(clientId)) + if (!networkObjects[i].m_Observers.Contains(clientId)) { - throw new VisibilityChangeException($"{nameof(NetworkObject)} with NetworkId: {networkObjects[i].NetworkObjectId} is already hidden"); + throw new VisibilityChangeException($"{nameof(NetworkObject)} with {nameof(NetworkObjectId)}: {networkObjects[i].NetworkObjectId} is already hidden"); } } - - using (PooledNetworkBuffer buffer = PooledNetworkBuffer.Get()) + using (var buffer = PooledNetworkBuffer.Get()) + using (var writer = PooledNetworkWriter.Get(buffer)) { - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(buffer)) - { - writer.WriteUInt16Packed((ushort)networkObjects.Count); + writer.WriteUInt16Packed((ushort)networkObjects.Count); - for (int i = 0; i < networkObjects.Count; i++) - { - // Send destroy call - networkObjects[i].observers.Remove(clientId); + for (int i = 0; i < networkObjects.Count; i++) + { + // Send destroy call + networkObjects[i].m_Observers.Remove(clientId); - writer.WriteUInt64Packed(networkObjects[i].NetworkObjectId); - } + writer.WriteUInt64Packed(networkObjects[i].NetworkObjectId); } InternalMessageSender.Send(clientId, NetworkConstants.DESTROY_OBJECTS, NetworkChannel.Internal, buffer); @@ -383,14 +378,13 @@ public void Spawn(Stream spawnPayload = null, bool destroyWithScene = false) throw new NotListeningException($"{nameof(NetworkManager)} isn't listening, start a server, client or host before spawning objects."); } - if (spawnPayload != null) - spawnPayload.Position = 0; + if (spawnPayload != null) spawnPayload.Position = 0; NetworkSpawnManager.SpawnNetworkObjectLocally(this, NetworkSpawnManager.GetNetworkObjectId(), false, false, null, spawnPayload, spawnPayload != null, spawnPayload == null ? 0 : (int)spawnPayload.Length, false, destroyWithScene); for (int i = 0; i < NetworkManager.Singleton.ConnectedClientsList.Count; i++) { - if (observers.Contains(NetworkManager.Singleton.ConnectedClientsList[i].ClientId)) + if (m_Observers.Contains(NetworkManager.Singleton.ConnectedClientsList[i].ClientId)) { NetworkSpawnManager.SendSpawnCallForObject(NetworkManager.Singleton.ConnectedClientsList[i].ClientId, this, spawnPayload); } @@ -413,14 +407,13 @@ public void Despawn(bool destroy = false) /// Should the object be destroyd when the scene is changed public void SpawnWithOwnership(ulong clientId, Stream spawnPayload = null, bool destroyWithScene = false) { - if (spawnPayload != null) - spawnPayload.Position = 0; + if (spawnPayload != null) spawnPayload.Position = 0; NetworkSpawnManager.SpawnNetworkObjectLocally(this, NetworkSpawnManager.GetNetworkObjectId(), false, false, clientId, spawnPayload, spawnPayload != null, spawnPayload == null ? 0 : (int)spawnPayload.Length, false, destroyWithScene); for (int i = 0; i < NetworkManager.Singleton.ConnectedClientsList.Count; i++) { - if (observers.Contains(NetworkManager.Singleton.ConnectedClientsList[i].ClientId)) + if (m_Observers.Contains(NetworkManager.Singleton.ConnectedClientsList[i].ClientId)) { NetworkSpawnManager.SendSpawnCallForObject(NetworkManager.Singleton.ConnectedClientsList[i].ClientId, this, spawnPayload); } @@ -435,14 +428,13 @@ public void SpawnWithOwnership(ulong clientId, Stream spawnPayload = null, bool /// Should the object be destroyd when the scene is changed public void SpawnAsPlayerObject(ulong clientId, Stream spawnPayload = null, bool destroyWithScene = false) { - if (spawnPayload != null) - spawnPayload.Position = 0; + if (spawnPayload != null) spawnPayload.Position = 0; NetworkSpawnManager.SpawnNetworkObjectLocally(this, NetworkSpawnManager.GetNetworkObjectId(), false, true, clientId, spawnPayload, spawnPayload != null, spawnPayload == null ? 0 : (int)spawnPayload.Length, false, destroyWithScene); for (int i = 0; i < NetworkManager.Singleton.ConnectedClientsList.Count; i++) { - if (observers.Contains(NetworkManager.Singleton.ConnectedClientsList[i].ClientId)) + if (m_Observers.Contains(NetworkManager.Singleton.ConnectedClientsList[i].ClientId)) { NetworkSpawnManager.SendSpawnCallForObject(NetworkManager.Singleton.ConnectedClientsList[i].ClientId, this, spawnPayload); } @@ -488,7 +480,7 @@ internal void ResetNetworkStartInvoked() { for (int i = 0; i < ChildNetworkBehaviours.Count; i++) { - ChildNetworkBehaviours[i].networkStartInvoked = false; + ChildNetworkBehaviours[i].NetworkStartInvoked = false; } } } @@ -498,16 +490,16 @@ internal void InvokeBehaviourNetworkSpawn(Stream stream) for (int i = 0; i < ChildNetworkBehaviours.Count; i++) { //We check if we are it's NetworkObject owner incase a NetworkObject exists as a child of our NetworkObject - if (!ChildNetworkBehaviours[i].networkStartInvoked) + if (!ChildNetworkBehaviours[i].NetworkStartInvoked) { - if (!ChildNetworkBehaviours[i].internalNetworkStartInvoked) + if (!ChildNetworkBehaviours[i].InternalNetworkStartInvoked) { ChildNetworkBehaviours[i].InternalNetworkStart(); - ChildNetworkBehaviours[i].internalNetworkStartInvoked = true; + ChildNetworkBehaviours[i].InternalNetworkStartInvoked = true; } ChildNetworkBehaviours[i].NetworkStart(stream); - ChildNetworkBehaviours[i].networkStartInvoked = true; + ChildNetworkBehaviours[i].NetworkStartInvoked = true; } } } @@ -518,14 +510,18 @@ internal List ChildNetworkBehaviours { get { - if (m_ChildNetworkBehaviours == null) + if (m_ChildNetworkBehaviours != null) + { + return m_ChildNetworkBehaviours; + } + + m_ChildNetworkBehaviours = new List(); + var networkBehaviours = GetComponentsInChildren(true); + for (int i = 0; i < networkBehaviours.Length; i++) { - m_ChildNetworkBehaviours = new List(); - NetworkBehaviour[] behaviours = GetComponentsInChildren(true); - for (int i = 0; i < behaviours.Length; i++) + if (networkBehaviours[i].NetworkObject == this) { - if (behaviours[i].NetworkObject == this) - m_ChildNetworkBehaviours.Add(behaviours[i]); + m_ChildNetworkBehaviours.Add(networkBehaviours[i]); } } @@ -538,7 +534,7 @@ internal void WriteNetworkVariableData(Stream stream, ulong clientId) for (int i = 0; i < ChildNetworkBehaviours.Count; i++) { ChildNetworkBehaviours[i].InitializeVariables(); - NetworkBehaviour.WriteNetworkVariableData(ChildNetworkBehaviours[i].networkVariableFields, stream, clientId); + NetworkBehaviour.WriteNetworkVariableData(ChildNetworkBehaviours[i].NetworkVariableFields, stream, clientId); } } @@ -547,16 +543,18 @@ internal void SetNetworkVariableData(Stream stream) for (int i = 0; i < ChildNetworkBehaviours.Count; i++) { ChildNetworkBehaviours[i].InitializeVariables(); - NetworkBehaviour.SetNetworkVariableData(ChildNetworkBehaviours[i].networkVariableFields, stream); + NetworkBehaviour.SetNetworkVariableData(ChildNetworkBehaviours[i].NetworkVariableFields, stream); } } - internal ushort GetOrderIndex(NetworkBehaviour instance) + internal ushort GetNetworkBehaviourOrderIndex(NetworkBehaviour instance) { for (ushort i = 0; i < ChildNetworkBehaviours.Count; i++) { if (ChildNetworkBehaviours[i] == instance) + { return i; + } } return 0; @@ -566,7 +564,11 @@ internal NetworkBehaviour GetNetworkBehaviourAtOrderIndex(ushort index) { if (index >= ChildNetworkBehaviours.Count) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Error) NetworkLog.LogError($"Behaviour index was out of bounds. Did you mess up the order of your {nameof(NetworkBehaviour)}s?"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Error) + { + NetworkLog.LogError($"Behaviour index was out of bounds. Did you mess up the order of your {nameof(NetworkBehaviour)}s?"); + } + return null; } diff --git a/com.unity.multiplayer.mlapi/Runtime/Core/NetworkTickSystem.cs b/com.unity.multiplayer.mlapi/Runtime/Core/NetworkTickSystem.cs index bc08ecdc76..91e59805c8 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Core/NetworkTickSystem.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Core/NetworkTickSystem.cs @@ -10,14 +10,15 @@ namespace MLAPI public class NetworkTickSystem : INetworkUpdateSystem, IDisposable { - private const float k_DefaultTickIntervalSec = 1/60f; // Defaults to 60 ticks second + private const float k_DefaultTickIntervalSec = 1 / 60f; // Defaults to 60 ticks second private readonly float m_TickIntervalSec; // Duration of a tick in seconds private int m_NetworkTickCount; // How many network ticks have passed? // special value to indicate "No tick information" - public const ushort k_NoTick = ushort.MaxValue; + public const ushort NoTick = ushort.MaxValue; + // Number of ticks over which the tick number wraps back to 0 - public const ushort k_TickPeriod = k_NoTick - 1; + public const ushort TickPeriod = NoTick - 1; /// /// Constructor @@ -47,7 +48,7 @@ public void Dispose() /// public ushort GetTick() { - return (ushort)(m_NetworkTickCount % k_TickPeriod); + return (ushort)(m_NetworkTickCount % TickPeriod); } /// @@ -79,4 +80,4 @@ public void NetworkUpdate(NetworkUpdateStage updateStage) } } } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Core/NetworkUpdateLoop.cs b/com.unity.multiplayer.mlapi/Runtime/Core/NetworkUpdateLoop.cs index f6d07bbc21..f8778668a8 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Core/NetworkUpdateLoop.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Core/NetworkUpdateLoop.cs @@ -34,19 +34,19 @@ public enum NetworkUpdateStage : byte /// public static class NetworkUpdateLoop { - private static readonly Dictionary> m_UpdateSystem_Sets; - private static readonly Dictionary m_UpdateSystem_Arrays; + private static Dictionary> s_UpdateSystem_Sets; + private static Dictionary s_UpdateSystem_Arrays; private const int k_UpdateSystem_InitialArrayCapacity = 1024; static NetworkUpdateLoop() { - m_UpdateSystem_Sets = new Dictionary>(); - m_UpdateSystem_Arrays = new Dictionary(); + s_UpdateSystem_Sets = new Dictionary>(); + s_UpdateSystem_Arrays = new Dictionary(); foreach (NetworkUpdateStage updateStage in Enum.GetValues(typeof(NetworkUpdateStage))) { - m_UpdateSystem_Sets.Add(updateStage, new HashSet()); - m_UpdateSystem_Arrays.Add(updateStage, new INetworkUpdateSystem[k_UpdateSystem_InitialArrayCapacity]); + s_UpdateSystem_Sets.Add(updateStage, new HashSet()); + s_UpdateSystem_Arrays.Add(updateStage, new INetworkUpdateSystem[k_UpdateSystem_InitialArrayCapacity]); } } @@ -66,19 +66,19 @@ public static void RegisterAllNetworkUpdates(this INetworkUpdateSystem updateSys /// public static void RegisterNetworkUpdate(this INetworkUpdateSystem updateSystem, NetworkUpdateStage updateStage = NetworkUpdateStage.Update) { - var sysSet = m_UpdateSystem_Sets[updateStage]; + var sysSet = s_UpdateSystem_Sets[updateStage]; if (!sysSet.Contains(updateSystem)) { sysSet.Add(updateSystem); int setLen = sysSet.Count; - var sysArr = m_UpdateSystem_Arrays[updateStage]; + var sysArr = s_UpdateSystem_Arrays[updateStage]; int arrLen = sysArr.Length; if (setLen > arrLen) { // double capacity - sysArr = m_UpdateSystem_Arrays[updateStage] = new INetworkUpdateSystem[arrLen *= 2]; + sysArr = s_UpdateSystem_Arrays[updateStage] = new INetworkUpdateSystem[arrLen *= 2]; } sysSet.CopyTo(sysArr); @@ -107,13 +107,13 @@ public static void UnregisterAllNetworkUpdates(this INetworkUpdateSystem updateS /// public static void UnregisterNetworkUpdate(this INetworkUpdateSystem updateSystem, NetworkUpdateStage updateStage = NetworkUpdateStage.Update) { - var sysSet = m_UpdateSystem_Sets[updateStage]; + var sysSet = s_UpdateSystem_Sets[updateStage]; if (sysSet.Contains(updateSystem)) { sysSet.Remove(updateSystem); int setLen = sysSet.Count; - var sysArr = m_UpdateSystem_Arrays[updateStage]; + var sysArr = s_UpdateSystem_Arrays[updateStage]; int arrLen = sysArr.Length; sysSet.CopyTo(sysArr); @@ -135,7 +135,7 @@ private static void RunNetworkUpdateStage(NetworkUpdateStage updateStage) { UpdateStage = updateStage; - var sysArr = m_UpdateSystem_Arrays[updateStage]; + var sysArr = s_UpdateSystem_Arrays[updateStage]; int arrLen = sysArr.Length; for (int curIdx = 0; curIdx < arrLen; curIdx++) { diff --git a/com.unity.multiplayer.mlapi/Runtime/Exceptions/NetworkConfigurationException.cs b/com.unity.multiplayer.mlapi/Runtime/Exceptions/NetworkConfigurationException.cs index e45437ed7b..b4b2f56121 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Exceptions/NetworkConfigurationException.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Exceptions/NetworkConfigurationException.cs @@ -10,28 +10,19 @@ public class NetworkConfigurationException : Exception /// /// Constructs a NetworkConfigurationException /// - public NetworkConfigurationException() - { - - } + public NetworkConfigurationException() { } /// /// Constructs a NetworkConfigurationException with a message /// /// The exception message - public NetworkConfigurationException(string message) : base(message) - { - - } + public NetworkConfigurationException(string message) : base(message) { } /// /// Constructs a NetworkConfigurationException with a message and a inner exception /// /// The exception message /// The inner exception - public NetworkConfigurationException(string message, Exception inner) : base(message, inner) - { - - } + public NetworkConfigurationException(string message, Exception inner) : base(message, inner) { } } } \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Exceptions/NotListeningException.cs b/com.unity.multiplayer.mlapi/Runtime/Exceptions/NotListeningException.cs index d92b2fce03..1d5400cf9b 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Exceptions/NotListeningException.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Exceptions/NotListeningException.cs @@ -10,28 +10,19 @@ public class NotListeningException : Exception /// /// Constructs a NotListeningException /// - public NotListeningException() - { - - } + public NotListeningException() { } /// /// Constructs a NotListeningException with a message /// /// The exception message - public NotListeningException(string message) : base(message) - { - - } + public NotListeningException(string message) : base(message) { } /// /// Constructs a NotListeningException with a message and a inner exception /// /// The exception message /// The inner exception - public NotListeningException(string message, Exception inner) : base(message, inner) - { - - } + public NotListeningException(string message, Exception inner) : base(message, inner) { } } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Exceptions/NotServerException.cs b/com.unity.multiplayer.mlapi/Runtime/Exceptions/NotServerException.cs index 26954abf39..7260a19aee 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Exceptions/NotServerException.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Exceptions/NotServerException.cs @@ -10,28 +10,19 @@ public class NotServerException : Exception /// /// Constructs a NotServerException /// - public NotServerException() - { - - } + public NotServerException() { } /// /// Constructs a NotServerException with a message /// /// The exception message - public NotServerException(string message) : base(message) - { - - } + public NotServerException(string message) : base(message) { } /// /// Constructs a NotServerException with a message and a inner exception /// /// The exception message /// The inner exception - public NotServerException(string message, Exception inner) : base(message, inner) - { - - } + public NotServerException(string message, Exception inner) : base(message, inner) { } } } \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Exceptions/SpawnStateException.cs b/com.unity.multiplayer.mlapi/Runtime/Exceptions/SpawnStateException.cs index 66b09b3c60..eb8ebd339e 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Exceptions/SpawnStateException.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Exceptions/SpawnStateException.cs @@ -10,36 +10,24 @@ public class SpawnStateException : Exception /// /// Constructs a SpawnStateException /// - public SpawnStateException() - { - - } + public SpawnStateException() { } /// /// Constructs a SpawnStateException with a message /// /// The exception message - public SpawnStateException(string message) : base(message) - { - - } + public SpawnStateException(string message) : base(message) { } /// /// Constructs a SpawnStateException with a message and a inner exception /// /// The exception message /// The inner exception - public SpawnStateException(string message, Exception inner) : base(message, inner) - { - - } + public SpawnStateException(string message, Exception inner) : base(message, inner) { } } public class InvalidChannelException : Exception { - public InvalidChannelException(string message) : base(message) - { - - } + public InvalidChannelException(string message) : base(message) { } } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Exceptions/VisibilityChangeException.cs b/com.unity.multiplayer.mlapi/Runtime/Exceptions/VisibilityChangeException.cs index 3a611e4f1c..07e8f22bd7 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Exceptions/VisibilityChangeException.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Exceptions/VisibilityChangeException.cs @@ -10,28 +10,19 @@ public class VisibilityChangeException : Exception /// /// Constructs a VisibilityChangeException /// - public VisibilityChangeException() - { - - } + public VisibilityChangeException() { } /// /// Constructs a VisibilityChangeException with a message /// /// The exception message - public VisibilityChangeException(string message) : base(message) - { - - } + public VisibilityChangeException(string message) : base(message) { } /// /// Constructs a VisibilityChangeException with a message and a inner exception /// /// The exception message /// The inner exception - public VisibilityChangeException(string message, Exception inner) : base(message, inner) - { - - } + public VisibilityChangeException(string message, Exception inner) : base(message, inner) { } } } \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Hashing/HashCode.cs b/com.unity.multiplayer.mlapi/Runtime/Hashing/HashCode.cs index 57e49a8a9a..c75ca6d625 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Hashing/HashCode.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Hashing/HashCode.cs @@ -5,11 +5,11 @@ /// internal static class HashCode { - private const uint FNV_offset_basis32 = 2166136261; - private const uint FNV_prime32 = 16777619; + private const uint k_FNV_offset_basis32 = 2166136261; + private const uint k_FNV_prime32 = 16777619; - private const ulong FNV_offset_basis64 = 14695981039346656037; - private const ulong FNV_prime64 = 1099511628211; + private const ulong k_FNV_offset_basis64 = 14695981039346656037; + private const ulong k_FNV_prime64 = 1099511628211; /// /// non cryptographic stable hash code, @@ -43,13 +43,14 @@ internal static uint GetStableHash32(this string txt) { unchecked { - uint hash = FNV_offset_basis32; + uint hash = k_FNV_offset_basis32; for (int i = 0; i < txt.Length; i++) { uint ch = txt[i]; - hash = hash * FNV_prime32; + hash = hash * k_FNV_prime32; hash = hash ^ ch; } + return hash; } } @@ -68,13 +69,14 @@ internal static ulong GetStableHash64(this string txt) { unchecked { - ulong hash = FNV_offset_basis64; + ulong hash = k_FNV_offset_basis64; for (int i = 0; i < txt.Length; i++) { ulong ch = txt[i]; - hash = hash * FNV_prime64; + hash = hash * k_FNV_prime64; hash = hash ^ ch; } + return hash; } } @@ -110,13 +112,14 @@ internal static uint GetStableHash32(this byte[] bytes) { unchecked { - uint hash = FNV_offset_basis32; + uint hash = k_FNV_offset_basis32; for (int i = 0; i < bytes.Length; i++) { uint bt = bytes[i]; - hash = hash * FNV_prime32; + hash = hash * k_FNV_prime32; hash = hash ^ bt; } + return hash; } } @@ -135,15 +138,16 @@ internal static ulong GetStableHash64(this byte[] bytes) { unchecked { - ulong hash = FNV_offset_basis64; + ulong hash = k_FNV_offset_basis64; for (int i = 0; i < bytes.Length; i++) { ulong bt = bytes[i]; - hash = hash * FNV_prime64; + hash = hash * k_FNV_prime64; hash = hash ^ bt; } + return hash; } } } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/LagCompensation/LagCompensationManager.cs b/com.unity.multiplayer.mlapi/Runtime/LagCompensation/LagCompensationManager.cs index 0b79b46355..2f98dda9ca 100644 --- a/com.unity.multiplayer.mlapi/Runtime/LagCompensation/LagCompensationManager.cs +++ b/com.unity.multiplayer.mlapi/Runtime/LagCompensation/LagCompensationManager.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.ComponentModel; using MLAPI.Exceptions; namespace MLAPI.LagCompensation @@ -15,7 +14,6 @@ public static class LagCompensationManager /// public static readonly List SimulationObjects = new List(); - /// /// Turns time back a given amount of seconds, invokes an action and turns it back /// diff --git a/com.unity.multiplayer.mlapi/Runtime/LagCompensation/TrackedObject.cs b/com.unity.multiplayer.mlapi/Runtime/LagCompensation/TrackedObject.cs index ac474cad19..be1f68f3a2 100644 --- a/com.unity.multiplayer.mlapi/Runtime/LagCompensation/TrackedObject.cs +++ b/com.unity.multiplayer.mlapi/Runtime/LagCompensation/TrackedObject.cs @@ -15,57 +15,30 @@ public class TrackedObject : MonoBehaviour { internal Dictionary FrameData = new Dictionary(); internal FixedQueue Framekeys; - private Vector3 savedPosition; - private Quaternion savedRotation; + private Vector3 m_SavedPosition; + private Quaternion m_SavedRotation; /// /// Gets the total amount of points stored in the component /// - public int TotalPoints - { - get - { - if (Framekeys == null) return 0; - else return Framekeys.Count; - } - } + public int TotalPoints => Framekeys?.Count ?? 0; /// /// Gets the average amount of time between the points in miliseconds /// - public float AvgTimeBetweenPointsMs - { - get - { - if (Framekeys == null || Framekeys.Count == 0) return 0; - else return ((Framekeys.ElementAt(Framekeys.Count - 1) - Framekeys.ElementAt(0)) / Framekeys.Count) * 1000f; - } - } + public float AvgTimeBetweenPointsMs => Framekeys == null || Framekeys.Count == 0 ? 0 : ((Framekeys.ElementAt(Framekeys.Count - 1) - Framekeys.ElementAt(0)) / Framekeys.Count) * 1000f; /// /// Gets the total time history we have for this object /// - public float TotalTimeHistory - { - get - { - if (Framekeys == null) return 0; - else return Framekeys.ElementAt(Framekeys.Count - 1) - Framekeys.ElementAt(0); - } - } + public float TotalTimeHistory => Framekeys == null ? 0 : Framekeys.ElementAt(Framekeys.Count - 1) - Framekeys.ElementAt(0); - private int maxPoints - { - get - { - return (int)(NetworkManager.Singleton.NetworkConfig.SecondsHistory / (1f / NetworkManager.Singleton.NetworkConfig.EventTickrate)); - } - } + private int m_MaxPoints => (int)(NetworkManager.Singleton.NetworkConfig.SecondsHistory / (1f / NetworkManager.Singleton.NetworkConfig.EventTickrate)); internal void ReverseTransform(float secondsAgo) { - savedPosition = transform.position; - savedRotation = transform.rotation; + m_SavedPosition = transform.position; + m_SavedRotation = transform.rotation; float currentTime = NetworkManager.Singleton.NetworkTime; float targetTime = currentTime - secondsAgo; @@ -79,45 +52,47 @@ internal void ReverseTransform(float secondsAgo) nextTime = Framekeys.ElementAt(i); break; } - else - previousTime = Framekeys.ElementAt(i); + + previousTime = Framekeys.ElementAt(i); } + float timeBetweenFrames = nextTime - previousTime; float timeAwayFromPrevious = currentTime - previousTime; float lerpProgress = timeAwayFromPrevious / timeBetweenFrames; - transform.position = Vector3.Lerp(FrameData[previousTime].position, FrameData[nextTime].position, lerpProgress); - transform.rotation = Quaternion.Slerp(FrameData[previousTime].rotation, FrameData[nextTime].rotation, lerpProgress); + transform.position = Vector3.Lerp(FrameData[previousTime].Position, FrameData[nextTime].Position, lerpProgress); + transform.rotation = Quaternion.Slerp(FrameData[previousTime].Rotation, FrameData[nextTime].Rotation, lerpProgress); } internal void ResetStateTransform() { - transform.position = savedPosition; - transform.rotation = savedRotation; + transform.position = m_SavedPosition; + transform.rotation = m_SavedRotation; } - void Start() + private void Start() { - Framekeys = new FixedQueue(maxPoints); + Framekeys = new FixedQueue(m_MaxPoints); Framekeys.Enqueue(0); + LagCompensationManager.SimulationObjects.Add(this); } - void OnDestroy() + private void OnDestroy() { LagCompensationManager.SimulationObjects.Remove(this); } internal void AddFrame() { - if (Framekeys.Count == maxPoints) - FrameData.Remove(Framekeys.Dequeue()); + if (Framekeys.Count == m_MaxPoints) FrameData.Remove(Framekeys.Dequeue()); FrameData.Add(NetworkManager.Singleton.NetworkTime, new TrackedPointData() { - position = transform.position, - rotation = transform.rotation + Position = transform.position, + Rotation = transform.rotation }); + Framekeys.Enqueue(NetworkManager.Singleton.NetworkTime); } } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/LagCompensation/TrackedPointData.cs b/com.unity.multiplayer.mlapi/Runtime/LagCompensation/TrackedPointData.cs index 48ebc3333c..b6001ceadf 100644 --- a/com.unity.multiplayer.mlapi/Runtime/LagCompensation/TrackedPointData.cs +++ b/com.unity.multiplayer.mlapi/Runtime/LagCompensation/TrackedPointData.cs @@ -4,7 +4,7 @@ namespace MLAPI.LagCompensation { internal struct TrackedPointData { - internal Vector3 position; - internal Quaternion rotation; + internal Vector3 Position; + internal Quaternion Rotation; } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Logging/LogLevel.cs b/com.unity.multiplayer.mlapi/Runtime/Logging/LogLevel.cs index 186d585679..1db0aa1867 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Logging/LogLevel.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Logging/LogLevel.cs @@ -9,14 +9,17 @@ public enum LogLevel /// Developer logging level, most verbose /// Developer, + /// /// Normal logging level, medium verbose /// Normal, + /// /// Error logging level, very quiet /// Error, + /// /// Nothing logging level, no logging will be done /// diff --git a/com.unity.multiplayer.mlapi/Runtime/Logging/NetworkLog.cs b/com.unity.multiplayer.mlapi/Runtime/Logging/NetworkLog.cs index 23fa91e510..0784ddc29d 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Logging/NetworkLog.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Logging/NetworkLog.cs @@ -15,32 +15,25 @@ public static class NetworkLog /// Gets the current log level. /// /// The current log level. - internal static LogLevel CurrentLogLevel - { - get - { - if (NetworkManager.Singleton == null) - return LogLevel.Normal; - else - return NetworkManager.Singleton.LogLevel; - } - } + internal static LogLevel CurrentLogLevel => ReferenceEquals(NetworkManager.Singleton, null) ? LogLevel.Normal : NetworkManager.Singleton.LogLevel; // MLAPI internal logging - internal static void LogInfo(string message) => Debug.Log("[MLAPI] " + message); - internal static void LogWarning(string message) => Debug.LogWarning("[MLAPI] " + message); - internal static void LogError(string message) => Debug.LogError("[MLAPI] " + message); + internal static void LogInfo(string message) => Debug.Log($"[MLAPI] {message}"); + internal static void LogWarning(string message) => Debug.LogWarning($"[MLAPI] {message}"); + internal static void LogError(string message) => Debug.LogError($"[MLAPI] {message}"); /// /// Logs an info log locally and on the server if possible. /// /// The message to log public static void LogInfoServer(string message) => LogServer(message, LogType.Info); + /// /// Logs a warning log locally and on the server if possible. /// /// The message to log public static void LogWarningServer(string message) => LogServer(message, LogType.Warning); + /// /// Logs an error log locally and on the server if possible. /// @@ -67,23 +60,20 @@ private static void LogServer(string message, LogType logType) if (NetworkManager.Singleton != null && !NetworkManager.Singleton.IsServer && NetworkManager.Singleton.NetworkConfig.EnableNetworkLogs) { - using (PooledNetworkBuffer buffer = PooledNetworkBuffer.Get()) + using (var buffer = PooledNetworkBuffer.Get()) + using (var writer = PooledNetworkWriter.Get(buffer)) { - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(buffer)) - { - writer.WriteByte((byte)logType); - - writer.WriteStringPacked(message); + writer.WriteByte((byte)logType); + writer.WriteStringPacked(message); - InternalMessageSender.Send(NetworkManager.Singleton.ServerClientId, NetworkConstants.SERVER_LOG, NetworkChannel.Internal, buffer); - } + InternalMessageSender.Send(NetworkManager.Singleton.ServerClientId, NetworkConstants.SERVER_LOG, NetworkChannel.Internal, buffer); } } } - internal static void LogInfoServerLocal(string message, ulong sender) => Debug.Log("[MLAPI_SERVER Sender=" + sender + "] " + message); - internal static void LogWarningServerLocal(string message, ulong sender) => Debug.LogWarning("[MLAPI_SERVER Sender=" + sender + "] " + message); - internal static void LogErrorServerLocal(string message, ulong sender) => Debug.LogError("[MLAPI_SERVER Sender=" + sender + "] " + message); + internal static void LogInfoServerLocal(string message, ulong sender) => Debug.Log($"[MLAPI_SERVER Sender={sender}] {message}"); + internal static void LogWarningServerLocal(string message, ulong sender) => Debug.LogWarning($"[MLAPI_SERVER Sender={sender}] {message}"); + internal static void LogErrorServerLocal(string message, ulong sender) => Debug.LogError($"[MLAPI_SERVER Sender={sender}] {message}"); internal enum LogType { @@ -93,4 +83,4 @@ internal enum LogType None } } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Messaging/Buffering/BufferManager.cs b/com.unity.multiplayer.mlapi/Runtime/Messaging/Buffering/BufferManager.cs index 4758ba141e..e6d5077192 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Messaging/Buffering/BufferManager.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Messaging/Buffering/BufferManager.cs @@ -10,27 +10,27 @@ namespace MLAPI.Messaging.Buffering internal static class BufferManager { #if DEVELOPMENT_BUILD || UNITY_EDITOR - public static ProfilerMarker s_CleanBuffer = new ProfilerMarker("MLAPI.BufferManager.CleanBuffer"); + private static ProfilerMarker s_CleanBuffer = new ProfilerMarker($"{nameof(BufferManager)}.{nameof(CleanBuffer)}"); #endif - private static readonly Dictionary> bufferQueues = new Dictionary>(); + private static Dictionary> s_BufferQueues = new Dictionary>(); internal struct BufferedMessage { - internal ulong sender; - internal NetworkChannel networkChannel; - internal PooledNetworkBuffer payload; - internal float receiveTime; - internal float bufferTime; + internal ulong SenderClientId; + internal NetworkChannel NetworkChannel; + internal PooledNetworkBuffer NetworkBuffer; + internal float ReceiveTime; + internal float BufferTime; } internal static Queue ConsumeBuffersForNetworkId(ulong networkId) { - if (bufferQueues.ContainsKey(networkId)) + if (s_BufferQueues.ContainsKey(networkId)) { - Queue message = bufferQueues[networkId]; + Queue message = s_BufferQueues[networkId]; - bufferQueues.Remove(networkId); + s_BufferQueues.Remove(networkId); return message; } @@ -42,42 +42,42 @@ internal static Queue ConsumeBuffersForNetworkId(ulong networkI internal static void RecycleConsumedBufferedMessage(BufferedMessage message) { - message.payload.Dispose(); + message.NetworkBuffer.Dispose(); } - internal static void BufferMessageForNetworkId(ulong networkId, ulong sender, NetworkChannel networkChannel, float receiveTime, ArraySegment payload) + internal static void BufferMessageForNetworkId(ulong networkId, ulong senderClientId, NetworkChannel networkChannel, float receiveTime, ArraySegment payload) { - if (!bufferQueues.ContainsKey(networkId)) + if (!s_BufferQueues.ContainsKey(networkId)) { - bufferQueues.Add(networkId, new Queue()); + s_BufferQueues.Add(networkId, new Queue()); } - Queue queue = bufferQueues[networkId]; - - PooledNetworkBuffer payloadBuffer = PooledNetworkBuffer.Get(); + Queue queue = s_BufferQueues[networkId]; + var payloadBuffer = PooledNetworkBuffer.Get(); payloadBuffer.Write(payload.Array, payload.Offset, payload.Count); payloadBuffer.Position = 0; queue.Enqueue(new BufferedMessage() { - bufferTime = Time.realtimeSinceStartup, - networkChannel = networkChannel, - payload = payloadBuffer, - receiveTime = receiveTime, - sender = sender + BufferTime = Time.realtimeSinceStartup, + NetworkChannel = networkChannel, + NetworkBuffer = payloadBuffer, + ReceiveTime = receiveTime, + SenderClientId = senderClientId }); } - private static readonly List _keysToDestroy = new List(); + private static List s_KeysToDestroy = new List(); + internal static void CleanBuffer() { #if DEVELOPMENT_BUILD || UNITY_EDITOR s_CleanBuffer.Begin(); #endif - foreach (KeyValuePair> pair in bufferQueues) + foreach (var pair in s_BufferQueues) { - while (pair.Value.Count > 0 && Time.realtimeSinceStartup - pair.Value.Peek().bufferTime >= NetworkManager.Singleton.NetworkConfig.MessageBufferTimeout) + while (pair.Value.Count > 0 && Time.realtimeSinceStartup - pair.Value.Peek().BufferTime >= NetworkManager.Singleton.NetworkConfig.MessageBufferTimeout) { BufferedMessage message = pair.Value.Dequeue(); @@ -86,19 +86,19 @@ internal static void CleanBuffer() if (pair.Value.Count == 0) { - _keysToDestroy.Add(pair.Key); + s_KeysToDestroy.Add(pair.Key); } } - for (int i = 0; i < _keysToDestroy.Count; i++) + for (int i = 0; i < s_KeysToDestroy.Count; i++) { - bufferQueues.Remove(_keysToDestroy[i]); + s_BufferQueues.Remove(s_KeysToDestroy[i]); } - _keysToDestroy.Clear(); + s_KeysToDestroy.Clear(); #if DEVELOPMENT_BUILD || UNITY_EDITOR s_CleanBuffer.End(); #endif } } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Messaging/Buffering/PreBufferPreset.cs b/com.unity.multiplayer.mlapi/Runtime/Messaging/Buffering/PreBufferPreset.cs index 61e77206f1..64c2b3fe73 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Messaging/Buffering/PreBufferPreset.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Messaging/Buffering/PreBufferPreset.cs @@ -12,4 +12,4 @@ internal struct PreBufferPreset public float ReceiveTime; public ArraySegment Data; } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Messaging/CustomMessageManager.cs b/com.unity.multiplayer.mlapi/Runtime/Messaging/CustomMessageManager.cs index 65be2a4bbe..4df95d0406 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Messaging/CustomMessageManager.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Messaging/CustomMessageManager.cs @@ -29,10 +29,7 @@ public static class CustomMessagingManager /// public static event UnnamedMessageDelegate OnUnnamedMessage; - internal static void InvokeUnnamedMessage(ulong clientId, Stream stream) - { - OnUnnamedMessage?.Invoke(clientId, stream); - } + internal static void InvokeUnnamedMessage(ulong clientId, Stream stream) => OnUnnamedMessage?.Invoke(clientId, stream); /// /// Sends unnamed message to a list of clients @@ -71,29 +68,28 @@ public static void SendUnnamedMessage(ulong clientId, NetworkBuffer buffer, Netw /// public delegate void HandleNamedMessageDelegate(ulong sender, Stream payload); - private static readonly Dictionary namedMessageHandlers16 = new Dictionary(); - private static readonly Dictionary namedMessageHandlers32 = new Dictionary(); - private static readonly Dictionary namedMessageHandlers64 = new Dictionary(); - + private static Dictionary s_NamedMessageHandlers16 = new Dictionary(); + private static Dictionary s_NamedMessageHandlers32 = new Dictionary(); + private static Dictionary s_NamedMessageHandlers64 = new Dictionary(); internal static void InvokeNamedMessage(ulong hash, ulong sender, Stream stream) { if (NetworkManager.Singleton == null) { // We dont know what size to use. Try every (more collision prone) - if (namedMessageHandlers16.ContainsKey(hash)) + if (s_NamedMessageHandlers16.ContainsKey(hash)) { - namedMessageHandlers16[hash](sender, stream); + s_NamedMessageHandlers16[hash](sender, stream); } - if (namedMessageHandlers32.ContainsKey(hash)) + if (s_NamedMessageHandlers32.ContainsKey(hash)) { - namedMessageHandlers32[hash](sender, stream); + s_NamedMessageHandlers32[hash](sender, stream); } - if (namedMessageHandlers64.ContainsKey(hash)) + if (s_NamedMessageHandlers64.ContainsKey(hash)) { - namedMessageHandlers64[hash](sender, stream); + s_NamedMessageHandlers64[hash](sender, stream); } } else @@ -101,23 +97,23 @@ internal static void InvokeNamedMessage(ulong hash, ulong sender, Stream stream) // Only check the right size. if (NetworkManager.Singleton.NetworkConfig.RpcHashSize == HashSize.VarIntTwoBytes) { - if (namedMessageHandlers16.ContainsKey(hash)) + if (s_NamedMessageHandlers16.ContainsKey(hash)) { - namedMessageHandlers16[hash](sender, stream); + s_NamedMessageHandlers16[hash](sender, stream); } } else if (NetworkManager.Singleton.NetworkConfig.RpcHashSize == HashSize.VarIntFourBytes) { - if (namedMessageHandlers32.ContainsKey(hash)) + if (s_NamedMessageHandlers32.ContainsKey(hash)) { - namedMessageHandlers32[hash](sender, stream); + s_NamedMessageHandlers32[hash](sender, stream); } } else if (NetworkManager.Singleton.NetworkConfig.RpcHashSize == HashSize.VarIntEightBytes) { - if (namedMessageHandlers64.ContainsKey(hash)) + if (s_NamedMessageHandlers64.ContainsKey(hash)) { - namedMessageHandlers64[hash](sender, stream); + s_NamedMessageHandlers64[hash](sender, stream); } } } @@ -130,9 +126,9 @@ internal static void InvokeNamedMessage(ulong hash, ulong sender, Stream stream) /// The callback to run when a named message is received. public static void RegisterNamedMessageHandler(string name, HandleNamedMessageDelegate callback) { - namedMessageHandlers16[name.GetStableHash16()] = callback; - namedMessageHandlers32[name.GetStableHash32()] = callback; - namedMessageHandlers64[name.GetStableHash64()] = callback; + s_NamedMessageHandlers16[name.GetStableHash16()] = callback; + s_NamedMessageHandlers32[name.GetStableHash32()] = callback; + s_NamedMessageHandlers64[name.GetStableHash64()] = callback; } /// @@ -141,9 +137,9 @@ public static void RegisterNamedMessageHandler(string name, HandleNamedMessageDe /// The name of the message. public static void UnregisterNamedMessageHandler(string name) { - namedMessageHandlers16.Remove(name.GetStableHash16()); - namedMessageHandlers32.Remove(name.GetStableHash32()); - namedMessageHandlers64.Remove(name.GetStableHash64()); + s_NamedMessageHandlers16.Remove(name.GetStableHash16()); + s_NamedMessageHandlers32.Remove(name.GetStableHash32()); + s_NamedMessageHandlers64.Remove(name.GetStableHash64()); } /// @@ -169,12 +165,10 @@ public static void SendNamedMessage(string name, ulong clientId, Stream stream, break; } - using (PooledNetworkBuffer messageBuffer = PooledNetworkBuffer.Get()) + using (var messageBuffer = PooledNetworkBuffer.Get()) + using (var writer = PooledNetworkWriter.Get(messageBuffer)) { - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(messageBuffer)) - { - writer.WriteUInt64Packed(hash); - } + writer.WriteUInt64Packed(hash); messageBuffer.CopyFrom(stream); @@ -205,12 +199,10 @@ public static void SendNamedMessage(string name, List clientIds, Stream s break; } - using (PooledNetworkBuffer messageBuffer = PooledNetworkBuffer.Get()) + using (var messageBuffer = PooledNetworkBuffer.Get()) + using (var writer = PooledNetworkWriter.Get(messageBuffer)) { - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(messageBuffer)) - { - writer.WriteUInt64Packed(hash); - } + writer.WriteUInt64Packed(hash); messageBuffer.CopyFrom(stream); diff --git a/com.unity.multiplayer.mlapi/Runtime/Messaging/InternalMessageHandler.cs b/com.unity.multiplayer.mlapi/Runtime/Messaging/InternalMessageHandler.cs index 7b308142a6..e94f9d11dc 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Messaging/InternalMessageHandler.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Messaging/InternalMessageHandler.cs @@ -9,6 +9,7 @@ using UnityEngine.Events; using UnityEngine.SceneManagement; using System.Collections.Generic; +using MLAPI.Configuration; using MLAPI.Messaging.Buffering; using MLAPI.Profiling; using MLAPI.Serialization; @@ -19,22 +20,23 @@ namespace MLAPI.Messaging internal static class InternalMessageHandler { #if DEVELOPMENT_BUILD || UNITY_EDITOR - static ProfilerMarker s_HandleConnectionRequest = new ProfilerMarker("InternalMessageHandler.HandleConnectionRequest"); - static ProfilerMarker s_HandleConnectionApproved = new ProfilerMarker("InternalMessageHandler.HandleConnectionApproved"); - static ProfilerMarker s_HandleAddObject = new ProfilerMarker("InternalMessageHandler.HandleAddObject"); - static ProfilerMarker s_HandleDestroyObject = new ProfilerMarker("InternalMessageHandler.HandleDestroyObject"); - static ProfilerMarker s_HandleSwitchScene = new ProfilerMarker("InternalMessageHandler.HandleSwitchScene"); - static ProfilerMarker s_HandleClientSwitchSceneCompleted = new ProfilerMarker("InternalMessageHandler.HandleClientSwitchSceneCompleted"); - static ProfilerMarker s_HandleChangeOwner = new ProfilerMarker("InternalMessageHandler.HandleChangeOwner"); - static ProfilerMarker s_HandleAddObjects = new ProfilerMarker("InternalMessageHandler.HandleAddObjects"); - static ProfilerMarker s_HandleDestroyObjects = new ProfilerMarker("InternalMessageHandler.HandleDestroyObjects"); - static ProfilerMarker s_HandleTimeSync = new ProfilerMarker("InternalMessageHandler.HandleTimeSync"); - static ProfilerMarker s_HandleNetworkVariableDelta = new ProfilerMarker("InternalMessageHandler.HandleNetworkVariableDelta"); - static ProfilerMarker s_HandleNetworkVariableUpdate = new ProfilerMarker("InternalMessageHandler.HandleNetworkVariableUpdate"); - static ProfilerMarker s_HandleUnnamedMessage = new ProfilerMarker("InternalMessageHandler.HandleUnnamedMessage"); - static ProfilerMarker s_HandleNamedMessage = new ProfilerMarker("InternalMessageHandler.HandleNamedMessage"); - static ProfilerMarker s_HandleNetworkLog = new ProfilerMarker("InternalMessageHandler.HandleNetworkLog"); - + private static ProfilerMarker s_HandleConnectionRequest = new ProfilerMarker($"{nameof(InternalMessageHandler)}.{nameof(HandleConnectionRequest)}"); + private static ProfilerMarker s_HandleConnectionApproved = new ProfilerMarker($"{nameof(InternalMessageHandler)}.{nameof(HandleConnectionApproved)}"); + private static ProfilerMarker s_HandleAddObject = new ProfilerMarker($"{nameof(InternalMessageHandler)}.{nameof(HandleAddObject)}"); + private static ProfilerMarker s_HandleDestroyObject = new ProfilerMarker($"{nameof(InternalMessageHandler)}.{nameof(HandleDestroyObject)}"); + private static ProfilerMarker s_HandleSwitchScene = new ProfilerMarker($"{nameof(InternalMessageHandler)}.{nameof(HandleSwitchScene)}"); + private static ProfilerMarker s_HandleClientSwitchSceneCompleted = new ProfilerMarker($"{nameof(InternalMessageHandler)}.{nameof(HandleClientSwitchSceneCompleted)}"); + private static ProfilerMarker s_HandleChangeOwner = new ProfilerMarker($"{nameof(InternalMessageHandler)}.{nameof(HandleChangeOwner)}"); + private static ProfilerMarker s_HandleAddObjects = new ProfilerMarker($"{nameof(InternalMessageHandler)}.{nameof(HandleAddObjects)}"); + private static ProfilerMarker s_HandleDestroyObjects = new ProfilerMarker($"{nameof(InternalMessageHandler)}.{nameof(HandleDestroyObjects)}"); + private static ProfilerMarker s_HandleTimeSync = new ProfilerMarker($"{nameof(InternalMessageHandler)}.{nameof(HandleTimeSync)}"); + private static ProfilerMarker s_HandleNetworkVariableDelta = new ProfilerMarker($"{nameof(InternalMessageHandler)}.{nameof(HandleNetworkVariableDelta)}"); + private static ProfilerMarker s_HandleNetworkVariableUpdate = new ProfilerMarker($"{nameof(InternalMessageHandler)}.{nameof(HandleNetworkVariableUpdate)}"); + private static ProfilerMarker s_HandleUnnamedMessage = new ProfilerMarker($"{nameof(InternalMessageHandler)}.{nameof(HandleUnnamedMessage)}"); + private static ProfilerMarker s_HandleNamedMessage = new ProfilerMarker($"{nameof(InternalMessageHandler)}.{nameof(HandleNamedMessage)}"); + private static ProfilerMarker s_HandleNetworkLog = new ProfilerMarker($"{nameof(InternalMessageHandler)}.{nameof(HandleNetworkLog)}"); + private static ProfilerMarker s_RpcReceiveQueueItemServerRpc = new ProfilerMarker($"{nameof(InternalMessageHandler)}.{nameof(RpcReceiveQueueItem)}.{nameof(RpcQueueContainer.QueueItemType.ServerRpc)}"); + private static ProfilerMarker s_RpcReceiveQueueItemClientRpc = new ProfilerMarker($"{nameof(InternalMessageHandler)}.{nameof(RpcReceiveQueueItem)}.{nameof(RpcQueueContainer.QueueItemType.ClientRpc)}"); #endif internal static void HandleConnectionRequest(ulong clientId, Stream stream) @@ -42,12 +44,16 @@ internal static void HandleConnectionRequest(ulong clientId, Stream stream) #if DEVELOPMENT_BUILD || UNITY_EDITOR s_HandleConnectionRequest.Begin(); #endif - using (PooledNetworkReader reader = PooledNetworkReader.Get(stream)) + using (var reader = PooledNetworkReader.Get(stream)) { ulong configHash = reader.ReadUInt64Packed(); if (!NetworkManager.Singleton.NetworkConfig.CompareConfig(configHash)) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("NetworkConfiguration mismatch. The configuration between the server and client does not match"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarning($"{nameof(NetworkConfig)} mismatch. The configuration between the server and client does not match"); + } + NetworkManager.Singleton.DisconnectClient(clientId); return; } @@ -55,10 +61,7 @@ internal static void HandleConnectionRequest(ulong clientId, Stream stream) if (NetworkManager.Singleton.NetworkConfig.ConnectionApproval) { byte[] connectionBuffer = reader.ReadByteArray(); - NetworkManager.Singleton.InvokeConnectionApproval(connectionBuffer, clientId, (createPlayerObject, playerPrefabHash, approved, position, rotation) => - { - NetworkManager.Singleton.HandleApproval(clientId, createPlayerObject, playerPrefabHash, approved, position, rotation); - }); + NetworkManager.Singleton.InvokeConnectionApproval(connectionBuffer, clientId, (createPlayerObject, playerPrefabHash, approved, position, rotation) => { NetworkManager.Singleton.HandleApproval(clientId, createPlayerObject, playerPrefabHash, approved, position, rotation); }); } else { @@ -75,7 +78,7 @@ internal static void HandleConnectionApproved(ulong clientId, Stream stream, flo #if DEVELOPMENT_BUILD || UNITY_EDITOR s_HandleConnectionApproved.Begin(); #endif - using (PooledNetworkReader reader = PooledNetworkReader.Get(stream)) + using (var reader = PooledNetworkReader.Get(stream)) { NetworkManager.Singleton.LocalClientId = reader.ReadUInt64Packed(); @@ -93,12 +96,12 @@ internal static void HandleConnectionApproved(ulong clientId, Stream stream, flo float netTime = reader.ReadSinglePacked(); NetworkManager.Singleton.UpdateNetworkTime(clientId, netTime, receiveTime, true); - NetworkManager.Singleton.ConnectedClients.Add(NetworkManager.Singleton.LocalClientId, new NetworkClient() { ClientId = NetworkManager.Singleton.LocalClientId }); + NetworkManager.Singleton.ConnectedClients.Add(NetworkManager.Singleton.LocalClientId, new NetworkClient { ClientId = NetworkManager.Singleton.LocalClientId }); void DelayedSpawnAction(Stream continuationStream) { - using (PooledNetworkReader continuationReader = PooledNetworkReader.Get(continuationStream)) + using (var continuationReader = PooledNetworkReader.Get(continuationStream)) { if (!NetworkManager.Singleton.NetworkConfig.EnableSceneManagement || NetworkManager.Singleton.NetworkConfig.UsePrefabSync) { @@ -157,8 +160,8 @@ void DelayedSpawnAction(Stream continuationStream) rot = Quaternion.Euler(continuationReader.ReadSinglePacked(), continuationReader.ReadSinglePacked(), continuationReader.ReadSinglePacked()); } - NetworkObject netObject = NetworkSpawnManager.CreateLocalNetworkObject(softSync, instanceId, prefabHash, parentNetworkId, pos, rot); - NetworkSpawnManager.SpawnNetworkObjectLocally(netObject, networkId, softSync, isPlayerObject, ownerId, continuationStream, false, 0, true, false); + var networkObject = NetworkSpawnManager.CreateLocalNetworkObject(softSync, instanceId, prefabHash, parentNetworkId, pos, rot); + NetworkSpawnManager.SpawnNetworkObjectLocally(networkObject, networkId, softSync, isPlayerObject, ownerId, continuationStream, false, 0, true, false); Queue bufferQueue = BufferManager.ConsumeBuffersForNetworkId(networkId); @@ -168,18 +171,14 @@ void DelayedSpawnAction(Stream continuationStream) while (bufferQueue.Count > 0) { BufferManager.BufferedMessage message = bufferQueue.Dequeue(); - - NetworkManager.Singleton.HandleIncomingData(message.sender, message.networkChannel, new ArraySegment(message.payload.GetBuffer(), (int)message.payload.Position, (int)message.payload.Length), message.receiveTime, false); - + NetworkManager.Singleton.HandleIncomingData(message.SenderClientId, message.NetworkChannel, new ArraySegment(message.NetworkBuffer.GetBuffer(), (int)message.NetworkBuffer.Position, (int)message.NetworkBuffer.Length), message.ReceiveTime, false); BufferManager.RecycleConsumedBufferedMessage(message); } } } NetworkSpawnManager.CleanDiffedSceneObjects(); - NetworkManager.Singleton.IsConnectedClient = true; - NetworkManager.Singleton.InvokeOnClientConnectedCallback(NetworkManager.Singleton.LocalClientId); } } @@ -195,14 +194,12 @@ void DelayedSpawnAction(Stream continuationStream) void OnSceneLoadComplete() { SceneManager.activeSceneChanged -= onSceneLoaded; - NetworkSceneManager.isSpawnedObjectsPendingInDontDestroyOnLoad = false; + NetworkSceneManager.IsSpawnedObjectsPendingInDontDestroyOnLoad = false; DelayedSpawnAction(continuationBuffer); } onSceneLoaded = (oldScene, newScene) => { OnSceneLoadComplete(); }; - SceneManager.activeSceneChanged += onSceneLoaded; - NetworkSceneManager.OnFirstSceneSwitchSync(sceneIndex, sceneSwitchProgressGuid); } else @@ -220,7 +217,7 @@ internal static void HandleAddObject(ulong clientId, Stream stream) #if DEVELOPMENT_BUILD || UNITY_EDITOR s_HandleAddObject.Begin(); #endif - using (PooledNetworkReader reader = PooledNetworkReader.Get(stream)) + using (var reader = PooledNetworkReader.Get(stream)) { bool isPlayerObject = reader.ReadBool(); ulong networkId = reader.ReadUInt64Packed(); @@ -270,8 +267,8 @@ internal static void HandleAddObject(ulong clientId, Stream stream) bool hasPayload = reader.ReadBool(); int payLoadLength = hasPayload ? reader.ReadInt32Packed() : 0; - NetworkObject netObject = NetworkSpawnManager.CreateLocalNetworkObject(softSync, instanceId, prefabHash, parentNetworkId, pos, rot); - NetworkSpawnManager.SpawnNetworkObjectLocally(netObject, networkId, softSync, isPlayerObject, ownerId, stream, hasPayload, payLoadLength, true, false); + var networkObject = NetworkSpawnManager.CreateLocalNetworkObject(softSync, instanceId, prefabHash, parentNetworkId, pos, rot); + NetworkSpawnManager.SpawnNetworkObjectLocally(networkObject, networkId, softSync, isPlayerObject, ownerId, stream, hasPayload, payLoadLength, true, false); Queue bufferQueue = BufferManager.ConsumeBuffersForNetworkId(networkId); @@ -281,9 +278,7 @@ internal static void HandleAddObject(ulong clientId, Stream stream) while (bufferQueue.Count > 0) { BufferManager.BufferedMessage message = bufferQueue.Dequeue(); - - NetworkManager.Singleton.HandleIncomingData(message.sender, message.networkChannel, new ArraySegment(message.payload.GetBuffer(), (int)message.payload.Position, (int)message.payload.Length), message.receiveTime, false); - + NetworkManager.Singleton.HandleIncomingData(message.SenderClientId, message.NetworkChannel, new ArraySegment(message.NetworkBuffer.GetBuffer(), (int)message.NetworkBuffer.Position, (int)message.NetworkBuffer.Length), message.ReceiveTime, false); BufferManager.RecycleConsumedBufferedMessage(message); } } @@ -298,7 +293,7 @@ internal static void HandleDestroyObject(ulong clientId, Stream stream) #if DEVELOPMENT_BUILD || UNITY_EDITOR s_HandleDestroyObject.Begin(); #endif - using (PooledNetworkReader reader = PooledNetworkReader.Get(stream)) + using (var reader = PooledNetworkReader.Get(stream)) { ulong networkId = reader.ReadUInt64Packed(); NetworkSpawnManager.OnDestroyObject(networkId, true); @@ -313,7 +308,7 @@ internal static void HandleSwitchScene(ulong clientId, Stream stream) #if DEVELOPMENT_BUILD || UNITY_EDITOR s_HandleSwitchScene.Begin(); #endif - using (PooledNetworkReader reader = PooledNetworkReader.Get(stream)) + using (var reader = PooledNetworkReader.Get(stream)) { uint sceneIndex = reader.ReadUInt32Packed(); Guid switchSceneGuid = new Guid(reader.ReadByteArray()); @@ -334,7 +329,7 @@ internal static void HandleClientSwitchSceneCompleted(ulong clientId, Stream str #if DEVELOPMENT_BUILD || UNITY_EDITOR s_HandleClientSwitchSceneCompleted.Begin(); #endif - using (PooledNetworkReader reader = PooledNetworkReader.Get(stream)) + using (var reader = PooledNetworkReader.Get(stream)) { NetworkSceneManager.OnClientSwitchSceneCompleted(clientId, new Guid(reader.ReadByteArray())); } @@ -348,7 +343,7 @@ internal static void HandleChangeOwner(ulong clientId, Stream stream) #if DEVELOPMENT_BUILD || UNITY_EDITOR s_HandleChangeOwner.Begin(); #endif - using (PooledNetworkReader reader = PooledNetworkReader.Get(stream)) + using (var reader = PooledNetworkReader.Get(stream)) { ulong networkId = reader.ReadUInt64Packed(); ulong ownerClientId = reader.ReadUInt64Packed(); @@ -377,7 +372,7 @@ internal static void HandleAddObjects(ulong clientId, Stream stream) #if DEVELOPMENT_BUILD || UNITY_EDITOR s_HandleAddObjects.Begin(); #endif - using (PooledNetworkReader reader = PooledNetworkReader.Get(stream)) + using (var reader = PooledNetworkReader.Get(stream)) { ushort objectCount = reader.ReadUInt16Packed(); @@ -396,7 +391,7 @@ internal static void HandleDestroyObjects(ulong clientId, Stream stream) #if DEVELOPMENT_BUILD || UNITY_EDITOR s_HandleDestroyObjects.Begin(); #endif - using (PooledNetworkReader reader = PooledNetworkReader.Get(stream)) + using (var reader = PooledNetworkReader.Get(stream)) { ushort objectCount = reader.ReadUInt16Packed(); @@ -415,7 +410,7 @@ internal static void HandleTimeSync(ulong clientId, Stream stream, float receive #if DEVELOPMENT_BUILD || UNITY_EDITOR s_HandleTimeSync.Begin(); #endif - using (PooledNetworkReader reader = PooledNetworkReader.Get(stream)) + using (var reader = PooledNetworkReader.Get(stream)) { float netTime = reader.ReadSinglePacked(); NetworkManager.Singleton.UpdateNetworkTime(clientId, netTime, receiveTime); @@ -432,36 +427,50 @@ internal static void HandleNetworkVariableDelta(ulong clientId, Stream stream, A #endif if (!NetworkManager.Singleton.NetworkConfig.EnableNetworkVariable) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("NetworkVariable delta received but EnableNetworkVariable is false"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarning($"{nameof(NetworkConstants.NETWORK_VARIABLE_DELTA)} received but {nameof(NetworkConfig.EnableNetworkVariable)} is false"); + } + return; } - using (PooledNetworkReader reader = PooledNetworkReader.Get(stream)) + using (var reader = PooledNetworkReader.Get(stream)) { - ulong networkId = reader.ReadUInt64Packed(); - ushort orderIndex = reader.ReadUInt16Packed(); + ulong networkObjectId = reader.ReadUInt64Packed(); + ushort networkBehaviourIndex = reader.ReadUInt16Packed(); - if (NetworkSpawnManager.SpawnedObjects.ContainsKey(networkId)) + if (NetworkSpawnManager.SpawnedObjects.ContainsKey(networkObjectId)) { - NetworkBehaviour instance = NetworkSpawnManager.SpawnedObjects[networkId].GetNetworkBehaviourAtOrderIndex(orderIndex); + NetworkBehaviour instance = NetworkSpawnManager.SpawnedObjects[networkObjectId].GetNetworkBehaviourAtOrderIndex(networkBehaviourIndex); if (instance == null) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("NetworkVariableDelta message received for a non-existent behaviour. NetworkId: " + networkId + ", behaviourIndex: " + orderIndex); + if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarning($"{nameof(NetworkConstants.NETWORK_VARIABLE_DELTA)} message received for a non-existent behaviour. {nameof(networkObjectId)}: {networkObjectId}, {nameof(networkBehaviourIndex)}: {networkBehaviourIndex}"); + } } else { - NetworkBehaviour.HandleNetworkVariableDeltas(instance.networkVariableFields, stream, clientId, instance); + NetworkBehaviour.HandleNetworkVariableDeltas(instance.NetworkVariableFields, stream, clientId, instance); } } else if (NetworkManager.Singleton.IsServer || !NetworkManager.Singleton.NetworkConfig.EnableMessageBuffering) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("NetworkVariableDelta message received for a non-existent object with id: " + networkId + ". This delta was lost."); + if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarning($"{nameof(NetworkConstants.NETWORK_VARIABLE_DELTA)} message received for a non-existent object with {nameof(networkObjectId)}: {networkObjectId}. This delta was lost."); + } } else { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("NetworkVariableDelta message received for a non-existent object with id: " + networkId + ". This delta will be buffered and might be recovered."); - bufferCallback(networkId, bufferPreset); + if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarning($"{nameof(NetworkConstants.NETWORK_VARIABLE_DELTA)} message received for a non-existent object with {nameof(networkObjectId)}: {networkObjectId}. This delta will be buffered and might be recovered."); + } + + bufferCallback(networkObjectId, bufferPreset); } } #if DEVELOPMENT_BUILD || UNITY_EDITOR @@ -476,36 +485,50 @@ internal static void HandleNetworkVariableUpdate(ulong clientId, Stream stream, #endif if (!NetworkManager.Singleton.NetworkConfig.EnableNetworkVariable) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("NetworkVariable update received but EnableNetworkVariable is false"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarning($"{nameof(NetworkConstants.NETWORK_VARIABLE_UPDATE)} update received but {nameof(NetworkConfig.EnableNetworkVariable)} is false"); + } + return; } - using (PooledNetworkReader reader = PooledNetworkReader.Get(stream)) + using (var reader = PooledNetworkReader.Get(stream)) { - ulong networkId = reader.ReadUInt64Packed(); - ushort orderIndex = reader.ReadUInt16Packed(); + ulong networkObjectId = reader.ReadUInt64Packed(); + ushort networkBehaviourIndex = reader.ReadUInt16Packed(); - if (NetworkSpawnManager.SpawnedObjects.ContainsKey(networkId)) + if (NetworkSpawnManager.SpawnedObjects.ContainsKey(networkObjectId)) { - NetworkBehaviour instance = NetworkSpawnManager.SpawnedObjects[networkId].GetNetworkBehaviourAtOrderIndex(orderIndex); + var networkBehaviour = NetworkSpawnManager.SpawnedObjects[networkObjectId].GetNetworkBehaviourAtOrderIndex(networkBehaviourIndex); - if (instance == null) + if (networkBehaviour == null) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("NetworkVariableUpdate message received for a non-existent behaviour. NetworkId: " + networkId + ", behaviourIndex: " + orderIndex); + if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarning($"{nameof(NetworkConstants.NETWORK_VARIABLE_UPDATE)} message received for a non-existent behaviour. {nameof(networkObjectId)}: {networkObjectId}, {nameof(networkBehaviourIndex)}: {networkBehaviourIndex}"); + } } else { - NetworkBehaviour.HandleNetworkVariableUpdate(instance.networkVariableFields, stream, clientId, instance); + NetworkBehaviour.HandleNetworkVariableUpdate(networkBehaviour.NetworkVariableFields, stream, clientId, networkBehaviour); } } else if (NetworkManager.Singleton.IsServer || !NetworkManager.Singleton.NetworkConfig.EnableMessageBuffering) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("NetworkVariableUpdate message received for a non-existent object with id: " + networkId + ". This delta was lost."); + if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarning($"{nameof(NetworkConstants.NETWORK_VARIABLE_UPDATE)} message received for a non-existent object with {nameof(networkObjectId)}: {networkObjectId}. This delta was lost."); + } } else { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("NetworkVariableUpdate message received for a non-existent object with id: " + networkId + ". This delta will be buffered and might be recovered."); - bufferCallback(networkId, bufferPreset); + if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarning($"{nameof(NetworkConstants.NETWORK_VARIABLE_UPDATE)} message received for a non-existent object with {nameof(networkObjectId)}: {networkObjectId}. This delta will be buffered and might be recovered."); + } + + bufferCallback(networkObjectId, bufferPreset); } } #if DEVELOPMENT_BUILD || UNITY_EDITOR @@ -526,17 +549,41 @@ internal static void RpcReceiveQueueItem(ulong clientId, Stream stream, float re return; } - ProfilerStatManager.rpcsRcvd.Record(); + ProfilerStatManager.RpcsRcvd.Record(); PerformanceDataManager.Increment(ProfilerConstants.NumberOfRPCsReceived); - var rpcQueueContainer = NetworkManager.Singleton.rpcQueueContainer; +#if DEVELOPMENT_BUILD || UNITY_EDITOR + switch (queueItemType) + { + case RpcQueueContainer.QueueItemType.ServerRpc: + s_RpcReceiveQueueItemServerRpc.Begin(); + break; + case RpcQueueContainer.QueueItemType.ClientRpc: + s_RpcReceiveQueueItemClientRpc.Begin(); + break; + } +#endif + + var rpcQueueContainer = NetworkManager.Singleton.RpcQueueContainer; rpcQueueContainer.AddQueueItemToInboundFrame(queueItemType, receiveTime, clientId, (NetworkBuffer)stream); + +#if DEVELOPMENT_BUILD || UNITY_EDITOR + switch (queueItemType) + { + case RpcQueueContainer.QueueItemType.ServerRpc: + s_RpcReceiveQueueItemServerRpc.End(); + break; + case RpcQueueContainer.QueueItemType.ClientRpc: + s_RpcReceiveQueueItemClientRpc.End(); + break; + } +#endif } internal static void HandleUnnamedMessage(ulong clientId, Stream stream) { PerformanceDataManager.Increment(ProfilerConstants.NumberOfUnnamedMessages); - ProfilerStatManager.unnamedMessage.Record(); + ProfilerStatManager.UnnamedMessage.Record(); #if DEVELOPMENT_BUILD || UNITY_EDITOR s_HandleUnnamedMessage.Begin(); #endif @@ -549,11 +596,11 @@ internal static void HandleUnnamedMessage(ulong clientId, Stream stream) internal static void HandleNamedMessage(ulong clientId, Stream stream) { PerformanceDataManager.Increment(ProfilerConstants.NumberOfNamedMessages); - ProfilerStatManager.namedMessage.Record(); + ProfilerStatManager.NamedMessage.Record(); #if DEVELOPMENT_BUILD || UNITY_EDITOR s_HandleNamedMessage.Begin(); #endif - using (PooledNetworkReader reader = PooledNetworkReader.Get(stream)) + using (var reader = PooledNetworkReader.Get(stream)) { ulong hash = reader.ReadUInt64Packed(); @@ -569,10 +616,10 @@ internal static void HandleNetworkLog(ulong clientId, Stream stream) #if DEVELOPMENT_BUILD || UNITY_EDITOR s_HandleNetworkLog.Begin(); #endif - using (PooledNetworkReader reader = PooledNetworkReader.Get(stream)) + using (var reader = PooledNetworkReader.Get(stream)) { NetworkLog.LogType logType = (NetworkLog.LogType)reader.ReadByte(); - string message = reader.ReadStringPacked().ToString(); + string message = reader.ReadStringPacked(); switch (logType) { diff --git a/com.unity.multiplayer.mlapi/Runtime/Messaging/InternalMessageSender.cs b/com.unity.multiplayer.mlapi/Runtime/Messaging/InternalMessageSender.cs index beee3d4165..cea62ad5f0 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Messaging/InternalMessageSender.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Messaging/InternalMessageSender.cs @@ -16,14 +16,12 @@ internal static void Send(ulong clientId, byte messageType, NetworkChannel netwo if (NetworkManager.Singleton.IsServer && clientId == NetworkManager.Singleton.ServerClientId) return; - using (NetworkBuffer buffer = MessagePacker.WrapMessage(messageType, messageBuffer)) + using (var buffer = MessagePacker.WrapMessage(messageType, messageBuffer)) { -#if !UNITY_2020_2_OR_LATER NetworkProfiler.StartEvent(TickType.Send, (uint)buffer.Length, networkChannel, NetworkConstants.MESSAGE_NAMES[messageType]); -#endif NetworkManager.Singleton.NetworkConfig.NetworkTransport.Send(clientId, new ArraySegment(buffer.GetBuffer(), 0, (int)buffer.Length), networkChannel); - ProfilerStatManager.bytesSent.Record((int)buffer.Length); + ProfilerStatManager.BytesSent.Record((int)buffer.Length); PerformanceDataManager.Increment(ProfilerConstants.NumberBytesSent, (int)buffer.Length); #if !UNITY_2020_2_OR_LATER @@ -36,7 +34,7 @@ internal static void Send(byte messageType, NetworkChannel networkChannel, Netwo { messageBuffer.PadBuffer(); - using (NetworkBuffer buffer = MessagePacker.WrapMessage(messageType, messageBuffer)) + using (var buffer = MessagePacker.WrapMessage(messageType, messageBuffer)) { #if !UNITY_2020_2_OR_LATER NetworkProfiler.StartEvent(TickType.Send, (uint)buffer.Length, networkChannel, NetworkConstants.MESSAGE_NAMES[messageType]); @@ -44,11 +42,10 @@ internal static void Send(byte messageType, NetworkChannel networkChannel, Netwo for (int i = 0; i < NetworkManager.Singleton.ConnectedClientsList.Count; i++) { - if (NetworkManager.Singleton.IsServer && NetworkManager.Singleton.ConnectedClientsList[i].ClientId == NetworkManager.Singleton.ServerClientId) - continue; + if (NetworkManager.Singleton.IsServer && NetworkManager.Singleton.ConnectedClientsList[i].ClientId == NetworkManager.Singleton.ServerClientId) continue; NetworkManager.Singleton.NetworkConfig.NetworkTransport.Send(NetworkManager.Singleton.ConnectedClientsList[i].ClientId, new ArraySegment(buffer.GetBuffer(), 0, (int)buffer.Length), networkChannel); - ProfilerStatManager.bytesSent.Record((int)buffer.Length); + ProfilerStatManager.BytesSent.Record((int)buffer.Length); PerformanceDataManager.Increment(ProfilerConstants.NumberBytesSent, (int)buffer.Length); } @@ -68,7 +65,7 @@ internal static void Send(byte messageType, NetworkChannel networkChannel, List< messageBuffer.PadBuffer(); - using (NetworkBuffer buffer = MessagePacker.WrapMessage(messageType, messageBuffer)) + using (var buffer = MessagePacker.WrapMessage(messageType, messageBuffer)) { #if !UNITY_2020_2_OR_LATER NetworkProfiler.StartEvent(TickType.Send, (uint)buffer.Length, networkChannel, NetworkConstants.MESSAGE_NAMES[messageType]); @@ -76,11 +73,10 @@ internal static void Send(byte messageType, NetworkChannel networkChannel, List< for (int i = 0; i < clientIds.Count; i++) { - if (NetworkManager.Singleton.IsServer && clientIds[i] == NetworkManager.Singleton.ServerClientId) - continue; + if (NetworkManager.Singleton.IsServer && clientIds[i] == NetworkManager.Singleton.ServerClientId) continue; NetworkManager.Singleton.NetworkConfig.NetworkTransport.Send(clientIds[i], new ArraySegment(buffer.GetBuffer(), 0, (int)buffer.Length), networkChannel); - ProfilerStatManager.bytesSent.Record((int)buffer.Length); + ProfilerStatManager.BytesSent.Record((int)buffer.Length); PerformanceDataManager.Increment(ProfilerConstants.NumberBytesSent, (int)buffer.Length); } @@ -94,7 +90,7 @@ internal static void Send(byte messageType, NetworkChannel networkChannel, ulong { messageBuffer.PadBuffer(); - using (NetworkBuffer buffer = MessagePacker.WrapMessage(messageType, messageBuffer)) + using (var buffer = MessagePacker.WrapMessage(messageType, messageBuffer)) { #if !UNITY_2020_2_OR_LATER NetworkProfiler.StartEvent(TickType.Send, (uint)buffer.Length, networkChannel, NetworkConstants.MESSAGE_NAMES[messageType]); @@ -104,10 +100,12 @@ internal static void Send(byte messageType, NetworkChannel networkChannel, ulong { if (NetworkManager.Singleton.ConnectedClientsList[i].ClientId == clientIdToIgnore || (NetworkManager.Singleton.IsServer && NetworkManager.Singleton.ConnectedClientsList[i].ClientId == NetworkManager.Singleton.ServerClientId)) + { continue; + } NetworkManager.Singleton.NetworkConfig.NetworkTransport.Send(NetworkManager.Singleton.ConnectedClientsList[i].ClientId, new ArraySegment(buffer.GetBuffer(), 0, (int)buffer.Length), networkChannel); - ProfilerStatManager.bytesSent.Record((int)buffer.Length); + ProfilerStatManager.BytesSent.Record((int)buffer.Length); PerformanceDataManager.Increment(ProfilerConstants.NumberBytesSent, (int)buffer.Length); } diff --git a/com.unity.multiplayer.mlapi/Runtime/Messaging/MessagePacker.cs b/com.unity.multiplayer.mlapi/Runtime/Messaging/MessagePacker.cs index 12aaeda425..d719a2130a 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Messaging/MessagePacker.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Messaging/MessagePacker.cs @@ -16,10 +16,12 @@ internal static NetworkBuffer UnwrapMessage(NetworkBuffer inputBuffer, out byte { if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogError("The incoming message was too small"); messageType = NetworkConstants.INVALID; + return null; } messageType = inputHeaderReader.ReadByteDirect(); + // The input stream is now ready to be read from. It's "safe" and has the correct position return inputBuffer; } diff --git a/com.unity.multiplayer.mlapi/Runtime/Messaging/RpcAttributes.cs b/com.unity.multiplayer.mlapi/Runtime/Messaging/RpcAttributes.cs index ad77bfed90..b985f8906b 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Messaging/RpcAttributes.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Messaging/RpcAttributes.cs @@ -47,7 +47,5 @@ public class ServerRpcAttribute : RpcAttribute /// A ClientRpc marked method will be fired by the server but executed on clients. /// [AttributeUsage(AttributeTargets.Method)] - public class ClientRpcAttribute : RpcAttribute - { - } + public class ClientRpcAttribute : RpcAttribute { } } \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Messaging/RpcBatcher.cs b/com.unity.multiplayer.mlapi/Runtime/Messaging/RpcBatcher.cs index 35ea988751..b590cf82f4 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Messaging/RpcBatcher.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Messaging/RpcBatcher.cs @@ -27,10 +27,10 @@ public SendStream() } // Stores the stream of batched RPC to send to each client, by ClientId - private readonly Dictionary SendDict = new Dictionary(); + private readonly Dictionary k_SendDict = new Dictionary(); // Used to store targets, internally - private ulong[] TargetList = new ulong[0]; + private ulong[] m_TargetList = new ulong[0]; // Used to mark longer lengths. Works because we can't have zero-sized messages private const byte k_LongLenMarker = 0; @@ -87,18 +87,18 @@ private int PopLength(in NetworkBuffer messageBuffer) /// the list to fill private static void FillTargetList(in RpcFrameQueueItem queueItem, ref ulong[] networkIdList) { - switch (queueItem.queueItemType) + switch (queueItem.QueueItemType) { // todo: revisit .resize() and .ToArry() usage, for performance case RpcQueueContainer.QueueItemType.ServerRpc: Array.Resize(ref networkIdList, 1); - networkIdList[0] = queueItem.networkId; + networkIdList[0] = queueItem.NetworkId; break; default: - // todo: consider the implications of default usage of queueItem.clientIds + // todo: consider the implications of default usage of queueItem.clientIds case RpcQueueContainer.QueueItemType.ClientRpc: // copy the list - networkIdList = queueItem.clientIds.ToArray(); + networkIdList = queueItem.ClientNetworkIds.ToArray(); break; } } @@ -110,49 +110,50 @@ private static void FillTargetList(in RpcFrameQueueItem queueItem, ref ulong[] n /// the threshold in bytes public void QueueItem(in RpcFrameQueueItem queueItem) { - FillTargetList(queueItem, ref TargetList); + FillTargetList(queueItem, ref m_TargetList); - foreach (ulong clientId in TargetList) + foreach (ulong clientId in m_TargetList) { - if (!SendDict.ContainsKey(clientId)) + if (!k_SendDict.ContainsKey(clientId)) { // todo: consider what happens if many clients join and leave the game consecutively // we probably need a cleanup mechanism at some point - SendDict[clientId] = new SendStream(); + k_SendDict[clientId] = new SendStream(); } - if (SendDict[clientId].IsEmpty) + if (k_SendDict[clientId].IsEmpty) { - SendDict[clientId].IsEmpty = false; - SendDict[clientId].NetworkChannel = queueItem.networkChannel; + k_SendDict[clientId].IsEmpty = false; + k_SendDict[clientId].NetworkChannel = queueItem.NetworkChannel; - switch (queueItem.queueItemType) + switch (queueItem.QueueItemType) { // 8 bits are used for the message type, which is an NetworkConstants case RpcQueueContainer.QueueItemType.ServerRpc: - SendDict[clientId].Writer.WriteByte(NetworkConstants.SERVER_RPC); // MessageType + k_SendDict[clientId].Writer.WriteByte(NetworkConstants.SERVER_RPC); // MessageType break; case RpcQueueContainer.QueueItemType.ClientRpc: - SendDict[clientId].Writer.WriteByte(NetworkConstants.CLIENT_RPC); // MessageType + k_SendDict[clientId].Writer.WriteByte(NetworkConstants.CLIENT_RPC); // MessageType break; } } // write the amounts of bytes that are coming up - PushLength(queueItem.messageData.Count, ref SendDict[clientId].Writer); + PushLength(queueItem.MessageData.Count, ref k_SendDict[clientId].Writer); // write the message to send - SendDict[clientId].Writer.WriteBytes(queueItem.messageData.Array, queueItem.messageData.Count, queueItem.messageData.Offset); + k_SendDict[clientId].Writer.WriteBytes(queueItem.MessageData.Array, queueItem.MessageData.Count, queueItem.MessageData.Offset); - ProfilerStatManager.bytesSent.Record(queueItem.messageData.Count); - ProfilerStatManager.rpcsSent.Record(); - PerformanceDataManager.Increment(ProfilerConstants.NumberBytesSent, queueItem.messageData.Count); + ProfilerStatManager.BytesSent.Record(queueItem.MessageData.Count); + ProfilerStatManager.RpcsSent.Record(); + PerformanceDataManager.Increment(ProfilerConstants.NumberBytesSent, queueItem.MessageData.Count); PerformanceDataManager.Increment(ProfilerConstants.NumberOfRPCsSent); } } public delegate void SendCallbackType(ulong clientId, SendStream messageStream); - public delegate void ReceiveCallbackType(NetworkBuffer messageBuffer, RpcQueueContainer.QueueItemType messageType, ulong clientId, float receiveTime); + + public delegate void ReceiveCallbackType(NetworkBuffer messageStream, RpcQueueContainer.QueueItemType messageType, ulong clientId, float receiveTime); /// /// SendItems @@ -162,12 +163,12 @@ public void QueueItem(in RpcFrameQueueItem queueItem) /// the function to call for sending the batch public void SendItems(int thresholdBytes, SendCallbackType sendCallback) { - foreach (KeyValuePair entry in SendDict) + foreach (KeyValuePair entry in k_SendDict) { if (!entry.Value.IsEmpty) { // read the queued message - int length = (int)SendDict[entry.Key].Buffer.Length; + int length = (int)k_SendDict[entry.Key].Buffer.Length; if (length >= thresholdBytes) { @@ -176,7 +177,7 @@ public void SendItems(int thresholdBytes, SendCallbackType sendCallback) entry.Value.Buffer.SetLength(0); entry.Value.Buffer.Position = 0; entry.Value.IsEmpty = true; - ProfilerStatManager.rpcBatchesSent.Record(); + ProfilerStatManager.RpcBatchesSent.Record(); PerformanceDataManager.Increment(ProfilerConstants.NumberOfRPCBatchesSent); } } @@ -221,4 +222,4 @@ public void ReceiveItems(in NetworkBuffer messageBuffer, ReceiveCallbackType rec } } } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Messaging/RpcQueue/RpcFrameQueueItem.cs b/com.unity.multiplayer.mlapi/Runtime/Messaging/RpcQueue/RpcFrameQueueItem.cs index cbaa7ae1ca..3a92d09ddd 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Messaging/RpcQueue/RpcFrameQueueItem.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Messaging/RpcQueue/RpcFrameQueueItem.cs @@ -2,7 +2,7 @@ using MLAPI.Transports; using MLAPI.Serialization.Pooled; -namespace MLAPI.Messaging +namespace MLAPI.Messaging { /// /// FrameQueueItem @@ -13,16 +13,16 @@ namespace MLAPI.Messaging /// internal struct RpcFrameQueueItem { - public NetworkUpdateStage updateStage; - public RpcQueueContainer.QueueItemType queueItemType; - public ulong networkId; //Sender's network Identifier - public NetworkChannel networkChannel; - public ulong[] clientIds; //Server invoked Client RPCs only - public long streamSize; - public float timeStamp; - public PooledNetworkWriter streamWriter; - public PooledNetworkReader streamReader; - public PooledNetworkBuffer itemBuffer; - public ArraySegment messageData; + public NetworkUpdateStage UpdateStage; + public RpcQueueContainer.QueueItemType QueueItemType; + public ulong NetworkId; //Sender's network Identifier + public NetworkChannel NetworkChannel; + public ulong[] ClientNetworkIds; //Server invoked Client RPCs only + public long StreamSize; + public float Timestamp; + public PooledNetworkWriter NetworkWriter; + public PooledNetworkReader NetworkReader; + public PooledNetworkBuffer NetworkBuffer; + public ArraySegment MessageData; } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Messaging/RpcQueue/RpcQueueContainer.cs b/com.unity.multiplayer.mlapi/Runtime/Messaging/RpcQueue/RpcQueueContainer.cs index 4d8577faff..8eb992129f 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Messaging/RpcQueue/RpcQueueContainer.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Messaging/RpcQueue/RpcQueueContainer.cs @@ -32,8 +32,8 @@ public enum RpcQueueProcessingTypes } // Inbound and Outbound QueueHistoryFrames - private readonly Dictionary>> QueueHistory = - new Dictionary>>(); + private readonly Dictionary>> QueueHistory = + new Dictionary>>(); private RpcQueueProcessor m_RpcQueueProcessor; @@ -73,9 +73,9 @@ public void NetworkUpdate(NetworkUpdateStage updateStage) /// /// /// number of frames procssed - public uint GetStreamBufferFrameCount(QueueHistoryFrame.QueueFrameType queueType) + public uint GetStreamBufferFrameCount(RpcQueueHistoryFrame.QueueFrameType queueType) { - return queueType == QueueHistoryFrame.QueueFrameType.Inbound ? m_InboundFramesProcessed : m_OutboundFramesProcessed; + return queueType == RpcQueueHistoryFrame.QueueFrameType.Inbound ? m_InboundFramesProcessed : m_OutboundFramesProcessed; } /// @@ -128,7 +128,7 @@ public void ProcessAndFlushRpcQueue(RpcQueueProcessingTypes queueType, NetworkUp /// /// /// QueueHistoryFrame - public QueueHistoryFrame GetCurrentFrame(QueueHistoryFrame.QueueFrameType qType, NetworkUpdateStage currentUpdateStage) + public RpcQueueHistoryFrame GetCurrentFrame(RpcQueueHistoryFrame.QueueFrameType qType, NetworkUpdateStage currentUpdateStage) { if (QueueHistory.ContainsKey(qType)) { @@ -152,9 +152,9 @@ public QueueHistoryFrame GetCurrentFrame(QueueHistoryFrame.QueueFrameType qType, /// /// /// - private int GetStreamBufferIndex(QueueHistoryFrame.QueueFrameType queueType) + private int GetStreamBufferIndex(RpcQueueHistoryFrame.QueueFrameType queueType) { - return queueType == QueueHistoryFrame.QueueFrameType.Inbound ? m_InboundStreamBufferIndex : m_OutBoundStreamBufferIndex; + return queueType == RpcQueueHistoryFrame.QueueFrameType.Inbound ? m_InboundStreamBufferIndex : m_OutBoundStreamBufferIndex; } /// @@ -163,44 +163,46 @@ private int GetStreamBufferIndex(QueueHistoryFrame.QueueFrameType queueType) /// All other frames other than the current frame is considered the live rollback history /// /// - public void AdvanceFrameHistory(QueueHistoryFrame.QueueFrameType queueType) + public void AdvanceFrameHistory(RpcQueueHistoryFrame.QueueFrameType queueType) { int StreamBufferIndex = GetStreamBufferIndex(queueType); if (!QueueHistory.ContainsKey(queueType)) { - UnityEngine.Debug.LogError("You must initialize the RpcQueueContainer before using MLAPI!"); + UnityEngine.Debug.LogError($"You must initialize the {nameof(RpcQueueContainer)} before using MLAPI!"); return; } if (!QueueHistory[queueType].ContainsKey(StreamBufferIndex)) { - UnityEngine.Debug.LogError("RpcQueueContainer " + queueType + " queue stream buffer index out of range! [" + StreamBufferIndex + "]"); + UnityEngine.Debug.LogError($"{nameof(RpcQueueContainer)} {queueType} queue stream buffer index out of range! [{StreamBufferIndex}]"); return; } - foreach (KeyValuePair queueHistoryByUpdates in QueueHistory[queueType][StreamBufferIndex]) + foreach (KeyValuePair queueHistoryByUpdates in QueueHistory[queueType][StreamBufferIndex]) { - QueueHistoryFrame queueHistoryItem = queueHistoryByUpdates.Value; + var rpcQueueHistoryItem = queueHistoryByUpdates.Value; + //This only gets reset when we advanced to next frame (do not reset this in the ResetQueueHistoryFrame) - queueHistoryItem.hasLoopbackData = false; - if (queueHistoryItem.queueItemOffsets.Count > 0) + rpcQueueHistoryItem.HasLoopbackData = false; + + if (rpcQueueHistoryItem.QueueItemOffsets.Count > 0) { - if (queueType == QueueHistoryFrame.QueueFrameType.Inbound) + if (queueType == RpcQueueHistoryFrame.QueueFrameType.Inbound) { - ProfilerStatManager.rpcInQueueSize.Record((int)queueHistoryItem.totalSize); - PerformanceDataManager.Increment(ProfilerConstants.NumberOfRPCsInQueueSize, (int)queueHistoryItem.totalSize); + ProfilerStatManager.RpcInQueueSize.Record((int)rpcQueueHistoryItem.TotalSize); + PerformanceDataManager.Increment(ProfilerConstants.NumberOfRPCsInQueueSize, (int)rpcQueueHistoryItem.TotalSize); } else { - ProfilerStatManager.rpcOutQueueSize.Record((int)queueHistoryItem.totalSize); - PerformanceDataManager.Increment(ProfilerConstants.NumberOfRPCsOutQueueSize, (int)queueHistoryItem.totalSize); + ProfilerStatManager.RpcOutQueueSize.Record((int)rpcQueueHistoryItem.TotalSize); + PerformanceDataManager.Increment(ProfilerConstants.NumberOfRPCsOutQueueSize, (int)rpcQueueHistoryItem.TotalSize); } } - ResetQueueHistoryFrame(queueHistoryItem); - IncrementAndSetQueueHistoryFrame(queueHistoryItem); + ResetQueueHistoryFrame(rpcQueueHistoryItem); + IncrementAndSetQueueHistoryFrame(rpcQueueHistoryItem); } //Roll to the next stream buffer @@ -212,7 +214,7 @@ public void AdvanceFrameHistory(QueueHistoryFrame.QueueFrameType queueType) StreamBufferIndex = 0; } - if (queueType == QueueHistoryFrame.QueueFrameType.Inbound) + if (queueType == RpcQueueHistoryFrame.QueueFrameType.Inbound) { m_InboundStreamBufferIndex = StreamBufferIndex; } @@ -226,10 +228,10 @@ public void AdvanceFrameHistory(QueueHistoryFrame.QueueFrameType queueType) /// IncrementAndSetQueueHistoryFrame /// Increments and sets frame count for this queue frame /// - /// QueueHistoryFrame to be reset - private void IncrementAndSetQueueHistoryFrame(QueueHistoryFrame queueFrame) + /// QueueHistoryFrame to be reset + private void IncrementAndSetQueueHistoryFrame(RpcQueueHistoryFrame rpcQueueFrame) { - if (queueFrame.GetQueueFrameType() == QueueHistoryFrame.QueueFrameType.Inbound) + if (rpcQueueFrame.GetQueueFrameType() == RpcQueueHistoryFrame.QueueFrameType.Inbound) { m_InboundFramesProcessed++; } @@ -243,17 +245,17 @@ private void IncrementAndSetQueueHistoryFrame(QueueHistoryFrame queueFrame) /// ResetQueueHistoryFrame /// Resets the queue history frame passed to this method /// - /// QueueHistoryFrame to be reset - private static void ResetQueueHistoryFrame(QueueHistoryFrame queueFrame) + /// QueueHistoryFrame to be reset + private static void ResetQueueHistoryFrame(RpcQueueHistoryFrame rpcQueueFrame) { //If we are dirt and have loopback data then don't clear this frame - if (queueFrame.isDirty && !queueFrame.hasLoopbackData) + if (rpcQueueFrame.IsDirty && !rpcQueueFrame.HasLoopbackData) { - queueFrame.totalSize = 0; - queueFrame.queueItemOffsets.Clear(); - queueFrame.queueBuffer.Position = 0; - queueFrame.MarkCurrentStreamPosition(); - queueFrame.isDirty = false; + rpcQueueFrame.TotalSize = 0; + rpcQueueFrame.QueueItemOffsets.Clear(); + rpcQueueFrame.QueueBuffer.Position = 0; + rpcQueueFrame.MarkCurrentStreamPosition(); + rpcQueueFrame.IsDirty = false; } } @@ -268,38 +270,38 @@ private static void ResetQueueHistoryFrame(QueueHistoryFrame queueFrame) internal void AddQueueItemToInboundFrame(QueueItemType qItemType, float timeStamp, ulong sourceNetworkId, NetworkBuffer message) { long originalPosition = message.Position; - PooledNetworkReader BR = PooledNetworkReader.Get(message); - var longValue = BR.ReadUInt64Packed(); // NetworkObjectId (temporary, we reset position just below) + NetworkUpdateStage updateStage; - var shortValue = BR.ReadUInt16Packed(); // NetworkBehaviourId (temporary, we reset position just below) - - var updateStage = (NetworkUpdateStage)BR.ReadByteDirect(); - BR.Dispose(); - BR = null; + using (var reader = PooledNetworkReader.Get(message)) + { + var longValue = reader.ReadUInt64Packed(); // NetworkObjectId (temporary, we reset position just below) + var shortValue = reader.ReadUInt16Packed(); // NetworkBehaviourId (temporary, we reset position just below) + updateStage = (NetworkUpdateStage)reader.ReadByteDirect(); + } message.Position = originalPosition; - QueueHistoryFrame queueHistoryItem = GetQueueHistoryFrame(QueueHistoryFrame.QueueFrameType.Inbound, updateStage); - queueHistoryItem.isDirty = true; + var rpcQueueHistoryItem = GetQueueHistoryFrame(RpcQueueHistoryFrame.QueueFrameType.Inbound, updateStage); + rpcQueueHistoryItem.IsDirty = true; - long StartPosition = queueHistoryItem.queueBuffer.Position; + long StartPosition = rpcQueueHistoryItem.QueueBuffer.Position; //Write the packed version of the queueItem to our current queue history buffer - queueHistoryItem.queueWriter.WriteUInt16((ushort)qItemType); - queueHistoryItem.queueWriter.WriteSingle(timeStamp); - queueHistoryItem.queueWriter.WriteUInt64(sourceNetworkId); + rpcQueueHistoryItem.QueueWriter.WriteUInt16((ushort)qItemType); + rpcQueueHistoryItem.QueueWriter.WriteSingle(timeStamp); + rpcQueueHistoryItem.QueueWriter.WriteUInt64(sourceNetworkId); //Inbound we copy the entire packet and store the position offset long streamSize = message.Length; - queueHistoryItem.queueWriter.WriteInt64(streamSize); - queueHistoryItem.queueWriter.WriteInt64(message.Position); - queueHistoryItem.queueWriter.WriteBytes(message.GetBuffer(), streamSize); + rpcQueueHistoryItem.QueueWriter.WriteInt64(streamSize); + rpcQueueHistoryItem.QueueWriter.WriteInt64(message.Position); + rpcQueueHistoryItem.QueueWriter.WriteBytes(message.GetBuffer(), streamSize); //Add the packed size to the offsets for parsing over various entries - queueHistoryItem.queueItemOffsets.Add((uint)queueHistoryItem.queueBuffer.Position); + rpcQueueHistoryItem.QueueItemOffsets.Add((uint)rpcQueueHistoryItem.QueueBuffer.Position); //Calculate the packed size based on stream progression - queueHistoryItem.totalSize += (uint)(queueHistoryItem.queueBuffer.Position - StartPosition); + rpcQueueHistoryItem.TotalSize += (uint)(rpcQueueHistoryItem.QueueBuffer.Position - StartPosition); } /// @@ -311,14 +313,14 @@ internal void AddQueueItemToInboundFrame(QueueItemType qItemType, float timeStam public void SetLoopBackFrameItem(NetworkUpdateStage updateStage) { //Get the next frame's inbound queue history frame - QueueHistoryFrame loopbackHistoryframe = GetQueueHistoryFrame(QueueHistoryFrame.QueueFrameType.Inbound,updateStage,true); + var loopbackHistoryframe = GetQueueHistoryFrame(RpcQueueHistoryFrame.QueueFrameType.Inbound, updateStage, true); //Get the current frame's outbound queue history frame - QueueHistoryFrame queueHistoryItem = GetQueueHistoryFrame(QueueHistoryFrame.QueueFrameType.Outbound, NetworkUpdateStage.PostLateUpdate, false); + var rpcQueueHistoryItem = GetQueueHistoryFrame(RpcQueueHistoryFrame.QueueFrameType.Outbound, NetworkUpdateStage.PostLateUpdate, false); - if (queueHistoryItem != null) + if (rpcQueueHistoryItem != null) { - queueHistoryItem.loopbackHistoryFrame = loopbackHistoryframe; + rpcQueueHistoryItem.LoopbackHistoryFrame = loopbackHistoryframe; } else { @@ -334,7 +336,7 @@ public void SetLoopBackFrameItem(NetworkUpdateStage updateStage) /// /// /// - public QueueHistoryFrame GetLoopBackHistoryFrame(QueueHistoryFrame.QueueFrameType queueFrameType, NetworkUpdateStage updateStage) + public RpcQueueHistoryFrame GetLoopBackHistoryFrame(RpcQueueHistoryFrame.QueueFrameType queueFrameType, NetworkUpdateStage updateStage) { return GetQueueHistoryFrame(queueFrameType, updateStage, false); } @@ -350,21 +352,21 @@ public QueueHistoryFrame GetLoopBackHistoryFrame(QueueHistoryFrame.QueueFrameTyp /// who the rpc is being sent to /// public PooledNetworkWriter BeginAddQueueItemToFrame(QueueItemType qItemType, float timeStamp, NetworkChannel networkChannel, ulong sourceNetworkId, ulong[] targetNetworkIds, - QueueHistoryFrame.QueueFrameType queueFrameType, NetworkUpdateStage updateStage) + RpcQueueHistoryFrame.QueueFrameType queueFrameType, NetworkUpdateStage updateStage) { - bool getNextFrame = NetworkManager.Singleton.IsHost && queueFrameType == QueueHistoryFrame.QueueFrameType.Inbound; + bool getNextFrame = NetworkManager.Singleton.IsHost && queueFrameType == RpcQueueHistoryFrame.QueueFrameType.Inbound; - QueueHistoryFrame queueHistoryItem = GetQueueHistoryFrame(queueFrameType, updateStage, getNextFrame); - queueHistoryItem.isDirty = true; + var rpcQueueHistoryItem = GetQueueHistoryFrame(queueFrameType, updateStage, getNextFrame); + rpcQueueHistoryItem.IsDirty = true; //Write the packed version of the queueItem to our current queue history buffer - queueHistoryItem.queueWriter.WriteUInt16((ushort)qItemType); - queueHistoryItem.queueWriter.WriteSingle(timeStamp); - queueHistoryItem.queueWriter.WriteUInt64(sourceNetworkId); + rpcQueueHistoryItem.QueueWriter.WriteUInt16((ushort)qItemType); + rpcQueueHistoryItem.QueueWriter.WriteSingle(timeStamp); + rpcQueueHistoryItem.QueueWriter.WriteUInt64(sourceNetworkId); - if (queueFrameType != QueueHistoryFrame.QueueFrameType.Inbound) + if (queueFrameType != RpcQueueHistoryFrame.QueueFrameType.Inbound) { - queueHistoryItem.queueWriter.WriteByte((byte)networkChannel); + rpcQueueHistoryItem.QueueWriter.WriteByte((byte)networkChannel); if (targetNetworkIds != null && targetNetworkIds.Length != 0) { @@ -382,7 +384,7 @@ public PooledNetworkWriter BeginAddQueueItemToFrame(QueueItemType qItemType, flo } //Write our total number of clients - queueHistoryItem.queueWriter.WriteInt32(numberOfClients); + rpcQueueHistoryItem.QueueWriter.WriteInt32(numberOfClients); //Now write the cliend ids for (int i = 0; i < targetNetworkIds.Length; i++) @@ -392,36 +394,37 @@ public PooledNetworkWriter BeginAddQueueItemToFrame(QueueItemType qItemType, flo continue; } - queueHistoryItem.queueWriter.WriteUInt64(targetNetworkIds[i]); + rpcQueueHistoryItem.QueueWriter.WriteUInt64(targetNetworkIds[i]); } } else { - queueHistoryItem.queueWriter.WriteInt32(0); + rpcQueueHistoryItem.QueueWriter.WriteInt32(0); } } //Mark where we started in the stream to later determine the actual RPC message size (position before writing RPC message vs position after write has completed) - queueHistoryItem.MarkCurrentStreamPosition(); + rpcQueueHistoryItem.MarkCurrentStreamPosition(); //Write a filler dummy size of 0 to hold this position in order to write to it once the RPC is done writing. - queueHistoryItem.queueWriter.WriteInt64(0); + rpcQueueHistoryItem.QueueWriter.WriteInt64(0); - if (NetworkManager.Singleton.IsHost && queueFrameType == QueueHistoryFrame.QueueFrameType.Inbound) + if (NetworkManager.Singleton.IsHost && queueFrameType == RpcQueueHistoryFrame.QueueFrameType.Inbound) { if (!IsUsingBatching()) { - queueHistoryItem.queueWriter.WriteInt64(1); + rpcQueueHistoryItem.QueueWriter.WriteInt64(1); } else { - queueHistoryItem.queueWriter.WriteInt64(0); + rpcQueueHistoryItem.QueueWriter.WriteInt64(0); } - queueHistoryItem.hasLoopbackData = true; //The only case for this is when it is the Host + + rpcQueueHistoryItem.HasLoopbackData = true; //The only case for this is when it is the Host } //Return the writer to the invoking method. - return queueHistoryItem.queueWriter; + return rpcQueueHistoryItem.QueueWriter; } /// @@ -430,102 +433,99 @@ public PooledNetworkWriter BeginAddQueueItemToFrame(QueueItemType qItemType, flo /// We store final MSG size and track the total current frame queue size /// /// writer that was used - public void EndAddQueueItemToFrame(NetworkWriter writer, QueueHistoryFrame.QueueFrameType queueFrameType, NetworkUpdateStage updateStage) + public void EndAddQueueItemToFrame(NetworkWriter writer, RpcQueueHistoryFrame.QueueFrameType queueFrameType, NetworkUpdateStage updateStage) { - bool getNextFrame = NetworkManager.Singleton.IsHost && queueFrameType == QueueHistoryFrame.QueueFrameType.Inbound; - - QueueHistoryFrame queueHistoryItem = GetQueueHistoryFrame(queueFrameType, updateStage, getNextFrame); - QueueHistoryFrame loopBackHistoryFrame = queueHistoryItem.loopbackHistoryFrame; + bool getNextFrame = NetworkManager.Singleton.IsHost && queueFrameType == RpcQueueHistoryFrame.QueueFrameType.Inbound; + var rpcQueueHistoryItem = GetQueueHistoryFrame(queueFrameType, updateStage, getNextFrame); + var loopBackHistoryFrame = rpcQueueHistoryItem.LoopbackHistoryFrame; - PooledNetworkWriter pbWriter = (PooledNetworkWriter)writer; - - //Sanity check - if (pbWriter != queueHistoryItem.queueWriter && !getNextFrame) + var pbWriter = (PooledNetworkWriter)writer; + if (pbWriter != rpcQueueHistoryItem.QueueWriter && !getNextFrame) { UnityEngine.Debug.LogError($"{nameof(RpcQueueContainer)} {queueFrameType} passed writer is not the same as the current {nameof(PooledNetworkWriter)} for the {queueFrameType}!"); } //The total size of the frame is the last known position of the stream - queueHistoryItem.totalSize = (uint)queueHistoryItem.queueBuffer.Position; + rpcQueueHistoryItem.TotalSize = (uint)rpcQueueHistoryItem.QueueBuffer.Position; - long CurrentPosition = queueHistoryItem.queueBuffer.Position; - ulong BitPosition = queueHistoryItem.queueBuffer.BitPosition; + long CurrentPosition = rpcQueueHistoryItem.QueueBuffer.Position; + ulong BitPosition = rpcQueueHistoryItem.QueueBuffer.BitPosition; ////////////////////////////////////////////////////////////// //>>>> REPOSITIONING STREAM TO RPC MESSAGE SIZE LOCATION <<<< ////////////////////////////////////////////////////////////// - queueHistoryItem.queueBuffer.Position = queueHistoryItem.GetCurrentMarkedPosition(); + rpcQueueHistoryItem.QueueBuffer.Position = rpcQueueHistoryItem.GetCurrentMarkedPosition(); long MSGOffset = 8; if (getNextFrame && IsUsingBatching()) { MSGOffset += 8; } + //subtracting 8 byte to account for the value of the size of the RPC - long MSGSize = (long)(queueHistoryItem.totalSize - (queueHistoryItem.GetCurrentMarkedPosition() + MSGOffset)); + long MSGSize = (long)(rpcQueueHistoryItem.TotalSize - (rpcQueueHistoryItem.GetCurrentMarkedPosition() + MSGOffset)); if (MSGSize > 0) { //Write the actual size of the RPC message - queueHistoryItem.queueWriter.WriteInt64(MSGSize); + rpcQueueHistoryItem.QueueWriter.WriteInt64(MSGSize); } else { UnityEngine.Debug.LogWarning("MSGSize of < zero detected!! Setting message size to zero!"); - queueHistoryItem.queueWriter.WriteInt64(0); + rpcQueueHistoryItem.QueueWriter.WriteInt64(0); } if (loopBackHistoryFrame != null) { if (MSGSize > 0) { - //Point to where the size of the message is stored - loopBackHistoryFrame.queueBuffer.Position = loopBackHistoryFrame.GetCurrentMarkedPosition(); + loopBackHistoryFrame.QueueBuffer.Position = loopBackHistoryFrame.GetCurrentMarkedPosition(); //Write the actual size of the RPC message - loopBackHistoryFrame.queueWriter.WriteInt64(MSGSize); + loopBackHistoryFrame.QueueWriter.WriteInt64(MSGSize); if (!IsUsingBatching()) { //Write the offset for the header info copied - loopBackHistoryFrame.queueWriter.WriteInt64(1); + loopBackHistoryFrame.QueueWriter.WriteInt64(1); } else { //Write the offset for the header info copied - loopBackHistoryFrame.queueWriter.WriteInt64(0); + loopBackHistoryFrame.QueueWriter.WriteInt64(0); } //Write RPC data - loopBackHistoryFrame.queueWriter.WriteBytes(queueHistoryItem.queueBuffer.GetBuffer(), MSGSize,(int)queueHistoryItem.queueBuffer.Position); + loopBackHistoryFrame.QueueWriter.WriteBytes(rpcQueueHistoryItem.QueueBuffer.GetBuffer(), MSGSize, (int)rpcQueueHistoryItem.QueueBuffer.Position); //Set the total size for this stream - loopBackHistoryFrame.totalSize = (uint)loopBackHistoryFrame.queueBuffer.Position; + loopBackHistoryFrame.TotalSize = (uint)loopBackHistoryFrame.QueueBuffer.Position; //Add the total size to the offsets for parsing over various entries - loopBackHistoryFrame.queueItemOffsets.Add((uint)loopBackHistoryFrame.queueBuffer.Position); - + loopBackHistoryFrame.QueueItemOffsets.Add((uint)loopBackHistoryFrame.QueueBuffer.Position); } else { UnityEngine.Debug.LogWarning("[LoopBack] MSGSize of < zero detected!! Setting message size to zero!"); //Write the actual size of the RPC message - loopBackHistoryFrame.queueWriter.WriteInt64(0); + loopBackHistoryFrame.QueueWriter.WriteInt64(0); } - queueHistoryItem.loopbackHistoryFrame = null; + + rpcQueueHistoryItem.LoopbackHistoryFrame = null; } ////////////////////////////////////////////////////////////// //<<<< REPOSITIONING STREAM BACK TO THE CURRENT TAIL >>>> ////////////////////////////////////////////////////////////// - queueHistoryItem.queueBuffer.Position = CurrentPosition; - queueHistoryItem.queueBuffer.BitPosition = BitPosition; + rpcQueueHistoryItem.QueueBuffer.Position = CurrentPosition; + rpcQueueHistoryItem.QueueBuffer.BitPosition = BitPosition; //Add the packed size to the offsets for parsing over various entries - queueHistoryItem.queueItemOffsets.Add((uint)queueHistoryItem.queueBuffer.Position); + rpcQueueHistoryItem.QueueItemOffsets.Add((uint)rpcQueueHistoryItem.QueueBuffer.Position); } /// @@ -534,7 +534,7 @@ public void EndAddQueueItemToFrame(NetworkWriter writer, QueueHistoryFrame.Queue /// /// inbound or outbound /// QueueHistoryFrame or null - public QueueHistoryFrame GetQueueHistoryFrame(QueueHistoryFrame.QueueFrameType frameType, NetworkUpdateStage updateStage, bool getNextFrame = false) + public RpcQueueHistoryFrame GetQueueHistoryFrame(RpcQueueHistoryFrame.QueueFrameType frameType, NetworkUpdateStage updateStage, bool getNextFrame = false) { int StreamBufferIndex = GetStreamBufferIndex(frameType); @@ -542,6 +542,7 @@ public QueueHistoryFrame GetQueueHistoryFrame(QueueHistoryFrame.QueueFrameType f if (getNextFrame) { StreamBufferIndex++; + //If we have hit our maximum history, roll back over to the first one if (StreamBufferIndex >= m_MaxFrameHistory) { @@ -557,19 +558,20 @@ public QueueHistoryFrame GetQueueHistoryFrame(QueueHistoryFrame.QueueFrameType f if (!QueueHistory[frameType].ContainsKey(StreamBufferIndex)) { - UnityEngine.Debug.LogError("RPCQueueManager " + frameType + " queue stream buffer index out of range! [" + StreamBufferIndex + "]"); + UnityEngine.Debug.LogError($"{nameof(RpcQueueContainer)} {frameType} queue stream buffer index out of range! [{StreamBufferIndex}]"); return null; } if (!QueueHistory[frameType][StreamBufferIndex].ContainsKey(updateStage)) { - UnityEngine.Debug.LogError("RPCQueueManager " + updateStage.ToString() + " update type does not exist!"); + UnityEngine.Debug.LogError($"{nameof(RpcQueueContainer)} {updateStage} update type does not exist!"); return null; } return QueueHistory[frameType][StreamBufferIndex][updateStage]; } +#if UNITY_EDITOR || DEVELOPMENT_BUILD /// /// LoopbackSendFrame /// Will copy the contents of the current outbound QueueHistoryFrame to the current inbound QueueHistoryFrame @@ -580,37 +582,38 @@ public void LoopbackSendFrame() //If we do not have loop back or testing mode enabled then ignore the call if (m_IsTestingEnabled) { - QueueHistoryFrame queueHistoryItemOutbound = GetQueueHistoryFrame(QueueHistoryFrame.QueueFrameType.Outbound, NetworkUpdateStage.PostLateUpdate); - if (queueHistoryItemOutbound.queueItemOffsets.Count > 0) + var rpcQueueHistoryItemOutbound = GetQueueHistoryFrame(RpcQueueHistoryFrame.QueueFrameType.Outbound, NetworkUpdateStage.PostLateUpdate); + if (rpcQueueHistoryItemOutbound.QueueItemOffsets.Count > 0) { //Reset inbound queues based on update stage foreach (NetworkUpdateStage netUpdateStage in Enum.GetValues(typeof(NetworkUpdateStage))) { - QueueHistoryFrame queueHistoryItemInbound = GetQueueHistoryFrame(QueueHistoryFrame.QueueFrameType.Inbound, netUpdateStage); - ResetQueueHistoryFrame(queueHistoryItemInbound); + var rpcQueueHistoryItemInbound = GetQueueHistoryFrame(RpcQueueHistoryFrame.QueueFrameType.Inbound, netUpdateStage); + ResetQueueHistoryFrame(rpcQueueHistoryItemInbound); } - PooledNetworkBuffer pooledNetworkBuffer = PooledNetworkBuffer.Get(); - RpcFrameQueueItem rpcFrameQueueItem = queueHistoryItemOutbound.GetFirstQueueItem(); + var pooledNetworkBuffer = PooledNetworkBuffer.Get(); + var rpcFrameQueueItem = rpcQueueHistoryItemOutbound.GetFirstQueueItem(); - while (rpcFrameQueueItem.queueItemType != QueueItemType.None) + while (rpcFrameQueueItem.QueueItemType != QueueItemType.None) { - pooledNetworkBuffer.SetLength(rpcFrameQueueItem.streamSize); + pooledNetworkBuffer.SetLength(rpcFrameQueueItem.StreamSize); pooledNetworkBuffer.Position = 0; - byte[] pooledNetworkBufferArray = pooledNetworkBuffer.GetBuffer(); - Buffer.BlockCopy(rpcFrameQueueItem.messageData.Array ?? Array.Empty(), rpcFrameQueueItem.messageData.Offset, pooledNetworkBufferArray, 0, (int)rpcFrameQueueItem.streamSize); + byte[] pooledNetworkStreamArray = pooledNetworkBuffer.GetBuffer(); + Buffer.BlockCopy(rpcFrameQueueItem.MessageData.Array ?? Array.Empty(), rpcFrameQueueItem.MessageData.Offset, pooledNetworkStreamArray, 0, (int)rpcFrameQueueItem.StreamSize); if (!IsUsingBatching()) { pooledNetworkBuffer.Position = 1; } - AddQueueItemToInboundFrame(rpcFrameQueueItem.queueItemType, UnityEngine.Time.realtimeSinceStartup, rpcFrameQueueItem.networkId, pooledNetworkBuffer); - rpcFrameQueueItem = queueHistoryItemOutbound.GetNextQueueItem(); + AddQueueItemToInboundFrame(rpcFrameQueueItem.QueueItemType, UnityEngine.Time.realtimeSinceStartup, rpcFrameQueueItem.NetworkId, pooledNetworkBuffer); + rpcFrameQueueItem = rpcQueueHistoryItemOutbound.GetNextQueueItem(); } } } } +#endif /// /// Initialize @@ -624,49 +627,48 @@ public void Initialize(uint maxFrameHistory) ClearParameters(); m_RpcQueueProcessor = new RpcQueueProcessor(); - m_MaxFrameHistory = maxFrameHistory + k_MinQueueHistory; - if (!QueueHistory.ContainsKey(QueueHistoryFrame.QueueFrameType.Inbound)) + if (!QueueHistory.ContainsKey(RpcQueueHistoryFrame.QueueFrameType.Inbound)) { - QueueHistory.Add(QueueHistoryFrame.QueueFrameType.Inbound, new Dictionary>()); + QueueHistory.Add(RpcQueueHistoryFrame.QueueFrameType.Inbound, new Dictionary>()); } - if (!QueueHistory.ContainsKey(QueueHistoryFrame.QueueFrameType.Outbound)) + if (!QueueHistory.ContainsKey(RpcQueueHistoryFrame.QueueFrameType.Outbound)) { - QueueHistory.Add(QueueHistoryFrame.QueueFrameType.Outbound, new Dictionary>()); + QueueHistory.Add(RpcQueueHistoryFrame.QueueFrameType.Outbound, new Dictionary>()); } for (int i = 0; i < m_MaxFrameHistory; i++) { - if (!QueueHistory[QueueHistoryFrame.QueueFrameType.Outbound].ContainsKey(i)) + if (!QueueHistory[RpcQueueHistoryFrame.QueueFrameType.Outbound].ContainsKey(i)) { - QueueHistory[QueueHistoryFrame.QueueFrameType.Outbound].Add(i, new Dictionary()); - var queueHistoryFrame = new QueueHistoryFrame(QueueHistoryFrame.QueueFrameType.Outbound, NetworkUpdateStage.PostLateUpdate); - queueHistoryFrame.queueBuffer = PooledNetworkBuffer.Get(); - queueHistoryFrame.queueBuffer.Position = 0; - queueHistoryFrame.queueWriter = PooledNetworkWriter.Get(queueHistoryFrame.queueBuffer); - queueHistoryFrame.queueReader = PooledNetworkReader.Get(queueHistoryFrame.queueBuffer); - queueHistoryFrame.queueItemOffsets = new List(); + QueueHistory[RpcQueueHistoryFrame.QueueFrameType.Outbound].Add(i, new Dictionary()); + var queueHistoryFrame = new RpcQueueHistoryFrame(RpcQueueHistoryFrame.QueueFrameType.Outbound, NetworkUpdateStage.PostLateUpdate); + queueHistoryFrame.QueueBuffer = PooledNetworkBuffer.Get(); + queueHistoryFrame.QueueBuffer.Position = 0; + queueHistoryFrame.QueueWriter = PooledNetworkWriter.Get(queueHistoryFrame.QueueBuffer); + queueHistoryFrame.QueueReader = PooledNetworkReader.Get(queueHistoryFrame.QueueBuffer); + queueHistoryFrame.QueueItemOffsets = new List(); //For now all outbound, we will always have a single update in which they are processed (LATEUPDATE) - QueueHistory[QueueHistoryFrame.QueueFrameType.Outbound][i].Add(NetworkUpdateStage.PostLateUpdate, queueHistoryFrame); + QueueHistory[RpcQueueHistoryFrame.QueueFrameType.Outbound][i].Add(NetworkUpdateStage.PostLateUpdate, queueHistoryFrame); } - if (!QueueHistory[QueueHistoryFrame.QueueFrameType.Inbound].ContainsKey(i)) + if (!QueueHistory[RpcQueueHistoryFrame.QueueFrameType.Inbound].ContainsKey(i)) { - QueueHistory[QueueHistoryFrame.QueueFrameType.Inbound].Add(i, new Dictionary()); + QueueHistory[RpcQueueHistoryFrame.QueueFrameType.Inbound].Add(i, new Dictionary()); //For inbound, we create a queue history frame per update stage foreach (NetworkUpdateStage netUpdateStage in Enum.GetValues(typeof(NetworkUpdateStage))) { - QueueHistoryFrame queueHistoryFrame = new QueueHistoryFrame(QueueHistoryFrame.QueueFrameType.Inbound, netUpdateStage); - queueHistoryFrame.queueBuffer = PooledNetworkBuffer.Get(); - queueHistoryFrame.queueBuffer.Position = 0; - queueHistoryFrame.queueWriter = PooledNetworkWriter.Get(queueHistoryFrame.queueBuffer); - queueHistoryFrame.queueReader = PooledNetworkReader.Get(queueHistoryFrame.queueBuffer); - queueHistoryFrame.queueItemOffsets = new List(); - QueueHistory[QueueHistoryFrame.QueueFrameType.Inbound][i].Add(netUpdateStage, queueHistoryFrame); + var rpcQueueHistoryFrame = new RpcQueueHistoryFrame(RpcQueueHistoryFrame.QueueFrameType.Inbound, netUpdateStage); + rpcQueueHistoryFrame.QueueBuffer = PooledNetworkBuffer.Get(); + rpcQueueHistoryFrame.QueueBuffer.Position = 0; + rpcQueueHistoryFrame.QueueWriter = PooledNetworkWriter.Get(rpcQueueHistoryFrame.QueueBuffer); + rpcQueueHistoryFrame.QueueReader = PooledNetworkReader.Get(rpcQueueHistoryFrame.QueueBuffer); + rpcQueueHistoryFrame.QueueItemOffsets = new List(); + QueueHistory[RpcQueueHistoryFrame.QueueFrameType.Inbound][i].Add(netUpdateStage, rpcQueueHistoryFrame); } } } @@ -719,15 +721,15 @@ public void Shutdown() m_RpcQueueProcessor.InternalMessagesSendAndFlush(); //Dispose of any readers and writers - foreach (KeyValuePair>> queueHistorySection in QueueHistory) + foreach (var queueHistorySection in QueueHistory) { - foreach (KeyValuePair> queueHistoryItemByStage in queueHistorySection.Value) + foreach (var queueHistoryItemByStage in queueHistorySection.Value) { - foreach (KeyValuePair queueHistoryItem in queueHistoryItemByStage.Value) + foreach (var queueHistoryItem in queueHistoryItemByStage.Value) { - queueHistoryItem.Value.queueWriter?.Dispose(); - queueHistoryItem.Value.queueReader?.Dispose(); - queueHistoryItem.Value.queueBuffer?.Dispose(); + queueHistoryItem.Value.QueueWriter?.Dispose(); + queueHistoryItem.Value.QueueReader?.Dispose(); + queueHistoryItem.Value.QueueBuffer?.Dispose(); } } } @@ -748,4 +750,4 @@ public RpcQueueContainer(bool processExternally) m_ProcessUpdateStagesExternally = processExternally; } } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Messaging/RpcQueue/QueueHistoryFrame.cs b/com.unity.multiplayer.mlapi/Runtime/Messaging/RpcQueue/RpcQueueHistoryFrame.cs similarity index 54% rename from com.unity.multiplayer.mlapi/Runtime/Messaging/RpcQueue/QueueHistoryFrame.cs rename to com.unity.multiplayer.mlapi/Runtime/Messaging/RpcQueue/RpcQueueHistoryFrame.cs index 6739333754..0e60fbcd96 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Messaging/RpcQueue/QueueHistoryFrame.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Messaging/RpcQueue/RpcQueueHistoryFrame.cs @@ -9,7 +9,7 @@ namespace MLAPI.Messaging /// Used by the RpcQueueContainer to hold queued RPCs /// All queued Rpcs end up in a PooledNetworkBuffer within a QueueHistoryFrame instance. /// - public class QueueHistoryFrame + public class RpcQueueHistoryFrame { public enum QueueFrameType { @@ -17,26 +17,26 @@ public enum QueueFrameType Outbound, } - public bool isDirty; //Used to determine if this queue history frame has been reset (cleaned) yet - public bool hasLoopbackData; //Used to determine if a dirt frame is dirty because rpcs are being looped back betwen HostClient and HostServer - public uint totalSize; - public List queueItemOffsets; + public bool IsDirty; //Used to determine if this queue history frame has been reset (cleaned) yet + public bool HasLoopbackData; //Used to determine if a dirt frame is dirty because rpcs are being looped back betwen HostClient and HostServer + public uint TotalSize; + public List QueueItemOffsets; - public PooledNetworkBuffer queueBuffer; - public PooledNetworkWriter queueWriter; - public QueueHistoryFrame loopbackHistoryFrame; //Temporary fix for Host mode loopback work around. + public PooledNetworkBuffer QueueBuffer; + public PooledNetworkWriter QueueWriter; + public RpcQueueHistoryFrame LoopbackHistoryFrame; //Temporary fix for Host mode loopback work around. - public PooledNetworkReader queueReader; + public PooledNetworkReader QueueReader; - private int m_QueueItemOffsetIndex; - private RpcFrameQueueItem m_CurrentQueueItem; - private readonly QueueFrameType m_QueueFrameType; - private int m_MaximumClients; - private long m_CurrentStreamSizeMark; - private NetworkUpdateStage m_StreamUpdateStage; //Update stage specific to RPCs (typically inbound has most potential for variation) - private const int m_MaxStreamBounds = 131072; - private const int m_MinStreamBounds = 0; + private int m_QueueItemOffsetIndex; + private RpcFrameQueueItem m_CurrentQueueItem; + private readonly QueueFrameType m_QueueFrameType; + private int m_MaximumClients; + private long m_CurrentStreamSizeMark; + private NetworkUpdateStage m_StreamUpdateStage; //Update stage specific to RPCs (typically inbound has most potential for variation) + private const int k_MaxStreamBounds = 131072; + private const int k_MinStreamBounds = 0; /// /// GetQueueFrameType @@ -54,9 +54,9 @@ public QueueFrameType GetQueueFrameType() /// public void MarkCurrentStreamPosition() { - if (queueBuffer != null) + if (QueueBuffer != null) { - m_CurrentStreamSizeMark = queueBuffer.Position; + m_CurrentStreamSizeMark = QueueBuffer.Position; } else { @@ -81,72 +81,72 @@ public long GetCurrentMarkedPosition() private RpcFrameQueueItem GetCurrentQueueItem() { //Write the packed version of the queueItem to our current queue history buffer - m_CurrentQueueItem.queueItemType = (RpcQueueContainer.QueueItemType)queueReader.ReadUInt16(); - m_CurrentQueueItem.timeStamp = queueReader.ReadSingle(); - m_CurrentQueueItem.networkId = queueReader.ReadUInt64(); + m_CurrentQueueItem.QueueItemType = (RpcQueueContainer.QueueItemType)QueueReader.ReadUInt16(); + m_CurrentQueueItem.Timestamp = QueueReader.ReadSingle(); + m_CurrentQueueItem.NetworkId = QueueReader.ReadUInt64(); //Clear out any current value for the client ids - m_CurrentQueueItem.clientIds = new ulong[0]; + m_CurrentQueueItem.ClientNetworkIds = new ulong[0]; //If outbound, determine if any client ids needs to be added if (m_QueueFrameType == QueueFrameType.Outbound) { //Outbound we care about both channel and clients - m_CurrentQueueItem.networkChannel = (NetworkChannel)queueReader.ReadByteDirect(); - int NumClients = queueReader.ReadInt32(); + m_CurrentQueueItem.NetworkChannel = (NetworkChannel)QueueReader.ReadByteDirect(); + int NumClients = QueueReader.ReadInt32(); if (NumClients > 0 && NumClients < m_MaximumClients) { ulong[] clientIdArray = new ulong[NumClients]; for (int i = 0; i < NumClients; i++) { - clientIdArray[i] = queueReader.ReadUInt64(); + clientIdArray[i] = QueueReader.ReadUInt64(); } - if (m_CurrentQueueItem.clientIds == null) + if (m_CurrentQueueItem.ClientNetworkIds == null) { - m_CurrentQueueItem.clientIds = clientIdArray; + m_CurrentQueueItem.ClientNetworkIds = clientIdArray; } else { - m_CurrentQueueItem.clientIds = clientIdArray; + m_CurrentQueueItem.ClientNetworkIds = clientIdArray; } } } - m_CurrentQueueItem.updateStage = m_StreamUpdateStage; + m_CurrentQueueItem.UpdateStage = m_StreamUpdateStage; //Get the stream size - m_CurrentQueueItem.streamSize = queueReader.ReadInt64(); + m_CurrentQueueItem.StreamSize = QueueReader.ReadInt64(); //Sanity checking for boundaries - if(m_CurrentQueueItem.streamSize < m_MaxStreamBounds && m_CurrentQueueItem.streamSize > m_MinStreamBounds) + if (m_CurrentQueueItem.StreamSize < k_MaxStreamBounds && m_CurrentQueueItem.StreamSize > k_MinStreamBounds) { //Inbound and Outbound message streams are handled differently if (m_QueueFrameType == QueueFrameType.Inbound) { //Get our offset - long Position = queueReader.ReadInt64(); + long Position = QueueReader.ReadInt64(); //Always make sure we are positioned at the start of the stream before we write - m_CurrentQueueItem.itemBuffer.Position = 0; + m_CurrentQueueItem.NetworkBuffer.Position = 0; //Write the entire message to the m_CurrentQueueItem stream (1 stream is re-used for all incoming RPCs) - m_CurrentQueueItem.streamWriter.ReadAndWrite(queueReader, m_CurrentQueueItem.streamSize); + m_CurrentQueueItem.NetworkWriter.ReadAndWrite(QueueReader, m_CurrentQueueItem.StreamSize); //Reset the position back to the offset so std rpc API can process the message properly //(i.e. minus the already processed header) - m_CurrentQueueItem.itemBuffer.Position = Position; + m_CurrentQueueItem.NetworkBuffer.Position = Position; } else { //Create a byte array segment for outbound sending - m_CurrentQueueItem.messageData = queueReader.CreateArraySegment((int)m_CurrentQueueItem.streamSize, (int)queueBuffer.Position); + m_CurrentQueueItem.MessageData = QueueReader.CreateArraySegment((int)m_CurrentQueueItem.StreamSize, (int)QueueBuffer.Position); } } else { - UnityEngine.Debug.LogWarning("CurrentQueueItem.StreamSize exceeds allowed size ( " + m_MaxStreamBounds.ToString() + " vs " + m_CurrentQueueItem.streamSize.ToString() + " )! Exiting Current RPC Queue Enumeration Loop! "); - m_CurrentQueueItem.queueItemType = RpcQueueContainer.QueueItemType.None; + UnityEngine.Debug.LogWarning($"{nameof(m_CurrentQueueItem)}.{nameof(RpcFrameQueueItem.StreamSize)} exceeds allowed size ({k_MaxStreamBounds} vs {m_CurrentQueueItem.StreamSize})! Exiting from the current RpcQueue enumeration loop!"); + m_CurrentQueueItem.QueueItemType = RpcQueueContainer.QueueItemType.None; } return m_CurrentQueueItem; @@ -160,11 +160,11 @@ private RpcFrameQueueItem GetCurrentQueueItem() /// FrameQueueItem internal RpcFrameQueueItem GetNextQueueItem() { - queueBuffer.Position = queueItemOffsets[m_QueueItemOffsetIndex]; + QueueBuffer.Position = QueueItemOffsets[m_QueueItemOffsetIndex]; m_QueueItemOffsetIndex++; - if (m_QueueItemOffsetIndex >= queueItemOffsets.Count) + if (m_QueueItemOffsetIndex >= QueueItemOffsets.Count) { - m_CurrentQueueItem.queueItemType = RpcQueueContainer.QueueItemType.None; + m_CurrentQueueItem.QueueItemType = RpcQueueContainer.QueueItemType.None; return m_CurrentQueueItem; } @@ -179,37 +179,34 @@ internal RpcFrameQueueItem GetNextQueueItem() /// FrameQueueItem internal RpcFrameQueueItem GetFirstQueueItem() { - if (queueBuffer.Position > 0) + if (QueueBuffer.Position > 0) { m_QueueItemOffsetIndex = 0; - queueBuffer.Position = 0; + QueueBuffer.Position = 0; if (m_QueueFrameType == QueueFrameType.Inbound) { - if(m_CurrentQueueItem.itemBuffer == null) + if (m_CurrentQueueItem.NetworkBuffer == null) { - m_CurrentQueueItem.itemBuffer = PooledNetworkBuffer.Get(); + m_CurrentQueueItem.NetworkBuffer = PooledNetworkBuffer.Get(); } - if(m_CurrentQueueItem.streamWriter == null) + if (m_CurrentQueueItem.NetworkWriter == null) { - m_CurrentQueueItem.streamWriter = PooledNetworkWriter.Get(m_CurrentQueueItem.itemBuffer); + m_CurrentQueueItem.NetworkWriter = PooledNetworkWriter.Get(m_CurrentQueueItem.NetworkBuffer); } - if(m_CurrentQueueItem.streamReader == null) + if (m_CurrentQueueItem.NetworkReader == null) { - m_CurrentQueueItem.streamReader = PooledNetworkReader.Get(m_CurrentQueueItem.itemBuffer); + m_CurrentQueueItem.NetworkReader = PooledNetworkReader.Get(m_CurrentQueueItem.NetworkBuffer); } - } return GetCurrentQueueItem(); } - else - { - m_CurrentQueueItem.queueItemType = RpcQueueContainer.QueueItemType.None; - return m_CurrentQueueItem; - } + + m_CurrentQueueItem.QueueItemType = RpcQueueContainer.QueueItemType.None; + return m_CurrentQueueItem; } /// @@ -220,22 +217,22 @@ internal RpcFrameQueueItem GetFirstQueueItem() /// public void CloseQueue() { - if (m_CurrentQueueItem.streamWriter != null) + if (m_CurrentQueueItem.NetworkWriter != null) { - m_CurrentQueueItem.streamWriter.Dispose(); - m_CurrentQueueItem.streamWriter = null; + m_CurrentQueueItem.NetworkWriter.Dispose(); + m_CurrentQueueItem.NetworkWriter = null; } - if (m_CurrentQueueItem.streamReader != null) + if (m_CurrentQueueItem.NetworkReader != null) { - m_CurrentQueueItem.streamReader.Dispose(); - m_CurrentQueueItem.streamReader = null; + m_CurrentQueueItem.NetworkReader.Dispose(); + m_CurrentQueueItem.NetworkReader = null; } - if (m_CurrentQueueItem.itemBuffer != null) + if (m_CurrentQueueItem.NetworkBuffer != null) { - m_CurrentQueueItem.itemBuffer.Dispose(); - m_CurrentQueueItem.itemBuffer = null; + m_CurrentQueueItem.NetworkBuffer.Dispose(); + m_CurrentQueueItem.NetworkBuffer = null; } } @@ -243,7 +240,7 @@ public void CloseQueue() /// QueueHistoryFrame Constructor /// /// type of queue history frame (Inbound/Outbound) - public QueueHistoryFrame(QueueFrameType queueType, NetworkUpdateStage updateStage, int maxClients = 512) + public RpcQueueHistoryFrame(QueueFrameType queueType, NetworkUpdateStage updateStage, int maxClients = 512) { m_MaximumClients = maxClients; m_QueueFrameType = queueType; @@ -251,4 +248,4 @@ public QueueHistoryFrame(QueueFrameType queueType, NetworkUpdateStage updateStag m_StreamUpdateStage = updateStage; } } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Messaging/RpcQueue/QueueHistoryFrame.cs.meta b/com.unity.multiplayer.mlapi/Runtime/Messaging/RpcQueue/RpcQueueHistoryFrame.cs.meta similarity index 100% rename from com.unity.multiplayer.mlapi/Runtime/Messaging/RpcQueue/QueueHistoryFrame.cs.meta rename to com.unity.multiplayer.mlapi/Runtime/Messaging/RpcQueue/RpcQueueHistoryFrame.cs.meta diff --git a/com.unity.multiplayer.mlapi/Runtime/Messaging/RpcQueue/RpcQueueProcessor.cs b/com.unity.multiplayer.mlapi/Runtime/Messaging/RpcQueue/RpcQueueProcessor.cs index 15c5aa699c..37e05ab5e4 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Messaging/RpcQueue/RpcQueueProcessor.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Messaging/RpcQueue/RpcQueueProcessor.cs @@ -16,8 +16,8 @@ namespace MLAPI.Messaging internal class RpcQueueProcessor { #if DEVELOPMENT_BUILD || UNITY_EDITOR - static ProfilerMarker s_RpcQueueProcess = new ProfilerMarker("RpcQueueProcess"); - static ProfilerMarker s_RpcQueueSend = new ProfilerMarker("RpcQueueSend"); + private static ProfilerMarker s_ProcessReceiveQueue = new ProfilerMarker($"{nameof(RpcQueueProcessor)}.{nameof(ProcessReceiveQueue)}"); + private static ProfilerMarker s_ProcessSendQueue = new ProfilerMarker($"{nameof(RpcQueueProcessor)}.{nameof(ProcessSendQueue)}"); #endif // Batcher object used to manage the RPC batching on the send side @@ -34,50 +34,51 @@ internal class RpcQueueProcessor /// public void ProcessReceiveQueue(NetworkUpdateStage currentStage) { - bool AdvanceFrameHistory = false; - var rpcQueueContainer = NetworkManager.Singleton.rpcQueueContainer; + bool advanceFrameHistory = false; + var rpcQueueContainer = NetworkManager.Singleton.RpcQueueContainer; if (rpcQueueContainer != null) { #if DEVELOPMENT_BUILD || UNITY_EDITOR - s_RpcQueueProcess.Begin(); + s_ProcessReceiveQueue.Begin(); #endif - var CurrentFrame = rpcQueueContainer.GetQueueHistoryFrame(QueueHistoryFrame.QueueFrameType.Inbound, currentStage); - var NextFrame = rpcQueueContainer.GetQueueHistoryFrame(QueueHistoryFrame.QueueFrameType.Inbound, currentStage, true); - if (NextFrame.isDirty && NextFrame.hasLoopbackData) + var currentFrame = rpcQueueContainer.GetQueueHistoryFrame(RpcQueueHistoryFrame.QueueFrameType.Inbound, currentStage); + var nextFrame = rpcQueueContainer.GetQueueHistoryFrame(RpcQueueHistoryFrame.QueueFrameType.Inbound, currentStage, true); + if (nextFrame.IsDirty && nextFrame.HasLoopbackData) { - AdvanceFrameHistory = true; + advanceFrameHistory = true; } - if (CurrentFrame != null && CurrentFrame.isDirty) + if (currentFrame != null && currentFrame.IsDirty) { - var currentQueueItem = CurrentFrame.GetFirstQueueItem(); - while (currentQueueItem.queueItemType != RpcQueueContainer.QueueItemType.None) + var currentQueueItem = currentFrame.GetFirstQueueItem(); + while (currentQueueItem.QueueItemType != RpcQueueContainer.QueueItemType.None) { - AdvanceFrameHistory = true; + advanceFrameHistory = true; if (rpcQueueContainer.IsTesting()) { - Debug.Log("RPC invoked during the " + currentStage.ToString() + " update stage."); + Debug.Log($"RPC invoked during the {currentStage} update stage."); } NetworkManager.InvokeRpc(currentQueueItem); - ProfilerStatManager.rpcsQueueProc.Record(); + ProfilerStatManager.RpcsQueueProc.Record(); PerformanceDataManager.Increment(ProfilerConstants.NumberOfRPCQueueProcessed); - currentQueueItem = CurrentFrame.GetNextQueueItem(); + currentQueueItem = currentFrame.GetNextQueueItem(); } //We call this to dispose of the shared stream writer and stream - CurrentFrame.CloseQueue(); + currentFrame.CloseQueue(); } - if (AdvanceFrameHistory) + if (advanceFrameHistory) { - rpcQueueContainer.AdvanceFrameHistory(QueueHistoryFrame.QueueFrameType.Inbound); + rpcQueueContainer.AdvanceFrameHistory(RpcQueueHistoryFrame.QueueFrameType.Inbound); } - } + #if DEVELOPMENT_BUILD || UNITY_EDITOR - s_RpcQueueProcess.End(); + s_ProcessReceiveQueue.End(); #endif + } } /// @@ -87,13 +88,13 @@ public void ProcessReceiveQueue(NetworkUpdateStage currentStage) public void ProcessSendQueue() { #if DEVELOPMENT_BUILD || UNITY_EDITOR - s_RpcQueueSend.Begin(); + s_ProcessSendQueue.Begin(); #endif RpcQueueSendAndFlush(); #if DEVELOPMENT_BUILD || UNITY_EDITOR - s_RpcQueueSend.End(); + s_ProcessSendQueue.End(); #endif InternalMessagesSendAndFlush(); } @@ -117,37 +118,36 @@ public void InternalMessagesSendAndFlush() { foreach (RpcFrameQueueItem queueItem in m_InternalMLAPISendQueue) { - - var PoolStream = queueItem.itemBuffer; - - if(NetworkManager.Singleton.IsListening) + var PoolStream = queueItem.NetworkBuffer; + if (NetworkManager.Singleton.IsListening) { - switch (queueItem.queueItemType) + switch (queueItem.QueueItemType) { case RpcQueueContainer.QueueItemType.CreateObject: { - foreach (ulong clientId in queueItem.clientIds) + foreach (ulong clientId in queueItem.ClientNetworkIds) { - InternalMessageSender.Send(clientId, NetworkConstants.ADD_OBJECT, queueItem.networkChannel, PoolStream); + InternalMessageSender.Send(clientId, NetworkConstants.ADD_OBJECT, queueItem.NetworkChannel, PoolStream); } - PerformanceDataManager.Increment(ProfilerConstants.NumberOfRPCsSent, queueItem.clientIds.Length); - ProfilerStatManager.rpcsSent.Record(queueItem.clientIds.Length); + PerformanceDataManager.Increment(ProfilerConstants.NumberOfRPCsSent, queueItem.ClientNetworkIds.Length); + ProfilerStatManager.RpcsSent.Record(queueItem.ClientNetworkIds.Length); break; } case RpcQueueContainer.QueueItemType.DestroyObject: { - foreach (ulong clientId in queueItem.clientIds) + foreach (ulong clientId in queueItem.ClientNetworkIds) { - InternalMessageSender.Send(clientId, NetworkConstants.DESTROY_OBJECT, queueItem.networkChannel, PoolStream); + InternalMessageSender.Send(clientId, NetworkConstants.DESTROY_OBJECT, queueItem.NetworkChannel, PoolStream); } - PerformanceDataManager.Increment(ProfilerConstants.NumberOfRPCsSent, queueItem.clientIds.Length); - ProfilerStatManager.rpcsSent.Record(queueItem.clientIds.Length); + PerformanceDataManager.Increment(ProfilerConstants.NumberOfRPCsSent, queueItem.ClientNetworkIds.Length); + ProfilerStatManager.RpcsSent.Record(queueItem.ClientNetworkIds.Length); break; } } } + PoolStream.Dispose(); } @@ -160,18 +160,17 @@ public void InternalMessagesSendAndFlush() /// private void RpcQueueSendAndFlush() { - var AdvanceFrameHistory = false; - var rpcQueueContainer = NetworkManager.Singleton.rpcQueueContainer; + var advanceFrameHistory = false; + var rpcQueueContainer = NetworkManager.Singleton.RpcQueueContainer; if (rpcQueueContainer != null) { - var CurrentFrame = rpcQueueContainer.GetCurrentFrame(QueueHistoryFrame.QueueFrameType.Outbound, NetworkUpdateStage.PostLateUpdate); - - if (CurrentFrame != null) + var currentFrame = rpcQueueContainer.GetCurrentFrame(RpcQueueHistoryFrame.QueueFrameType.Outbound, NetworkUpdateStage.PostLateUpdate); + if (currentFrame != null) { - var currentQueueItem = CurrentFrame.GetFirstQueueItem(); - while (currentQueueItem.queueItemType != RpcQueueContainer.QueueItemType.None) + var currentQueueItem = currentFrame.GetFirstQueueItem(); + while (currentQueueItem.QueueItemType != RpcQueueContainer.QueueItemType.None) { - AdvanceFrameHistory = true; + advanceFrameHistory = true; if (rpcQueueContainer.IsUsingBatching()) { m_RpcBatcher.QueueItem(currentQueueItem); @@ -182,20 +181,21 @@ private void RpcQueueSendAndFlush() { SendFrameQueueItem(currentQueueItem); } - currentQueueItem = CurrentFrame.GetNextQueueItem(); + + currentQueueItem = currentFrame.GetNextQueueItem(); } //If the size is < m_BatchThreshold then just send the messages - if (AdvanceFrameHistory && rpcQueueContainer.IsUsingBatching()) + if (advanceFrameHistory && rpcQueueContainer.IsUsingBatching()) { m_RpcBatcher.SendItems(0, SendCallback); } } //If we processed any RPCs, then advance to the next frame - if (AdvanceFrameHistory) + if (advanceFrameHistory) { - rpcQueueContainer.AdvanceFrameHistory(QueueHistoryFrame.QueueFrameType.Outbound); + rpcQueueContainer.AdvanceFrameHistory(RpcQueueHistoryFrame.QueueFrameType.Outbound); } } } @@ -212,7 +212,7 @@ private static void SendCallback(ulong clientId, RpcBatcher.SendStream sendStrea { var length = (int)sendStream.Buffer.Length; var bytes = sendStream.Buffer.GetBuffer(); - ArraySegment sendBuffer = new ArraySegment(bytes, 0, length); + var sendBuffer = new ArraySegment(bytes, 0, length); NetworkManager.Singleton.NetworkConfig.NetworkTransport.Send(clientId, sendBuffer, sendStream.NetworkChannel); } @@ -224,38 +224,38 @@ private static void SendCallback(ulong clientId, RpcBatcher.SendStream sendStrea /// Information on what to send private void SendFrameQueueItem(RpcFrameQueueItem queueItem) { - switch (queueItem.queueItemType) + switch (queueItem.QueueItemType) { case RpcQueueContainer.QueueItemType.ServerRpc: { - NetworkManager.Singleton.NetworkConfig.NetworkTransport.Send(queueItem.networkId, queueItem.messageData, queueItem.networkChannel); + NetworkManager.Singleton.NetworkConfig.NetworkTransport.Send(queueItem.NetworkId, queueItem.MessageData, queueItem.NetworkChannel); //For each packet sent, we want to record how much data we have sent - PerformanceDataManager.Increment(ProfilerConstants.NumberBytesSent, (int)queueItem.streamSize); + PerformanceDataManager.Increment(ProfilerConstants.NumberBytesSent, (int)queueItem.StreamSize); PerformanceDataManager.Increment(ProfilerConstants.NumberOfRPCsSent); - ProfilerStatManager.bytesSent.Record((int)queueItem.streamSize); - ProfilerStatManager.rpcsSent.Record(); + ProfilerStatManager.BytesSent.Record((int)queueItem.StreamSize); + ProfilerStatManager.RpcsSent.Record(); break; } case RpcQueueContainer.QueueItemType.ClientRpc: { - foreach (ulong clientid in queueItem.clientIds) + foreach (ulong clientid in queueItem.ClientNetworkIds) { - NetworkManager.Singleton.NetworkConfig.NetworkTransport.Send(clientid, queueItem.messageData, queueItem.networkChannel); + NetworkManager.Singleton.NetworkConfig.NetworkTransport.Send(clientid, queueItem.MessageData, queueItem.NetworkChannel); //For each packet sent, we want to record how much data we have sent - PerformanceDataManager.Increment(ProfilerConstants.NumberBytesSent, (int)queueItem.streamSize); - ProfilerStatManager.bytesSent.Record((int)queueItem.streamSize); + PerformanceDataManager.Increment(ProfilerConstants.NumberBytesSent, (int)queueItem.StreamSize); + ProfilerStatManager.BytesSent.Record((int)queueItem.StreamSize); } //For each client we send to, we want to record how many RPCs we have sent - PerformanceDataManager.Increment(ProfilerConstants.NumberOfRPCsSent, queueItem.clientIds.Length); - ProfilerStatManager.rpcsSent.Record(queueItem.clientIds.Length); + PerformanceDataManager.Increment(ProfilerConstants.NumberOfRPCsSent, queueItem.ClientNetworkIds.Length); + ProfilerStatManager.RpcsSent.Record(queueItem.ClientNetworkIds.Length); break; } } } } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/NetworkVariable/Collections/NetworkDictionary.cs b/com.unity.multiplayer.mlapi/Runtime/NetworkVariable/Collections/NetworkDictionary.cs index 419c5a4c2f..c013271d5a 100644 --- a/com.unity.multiplayer.mlapi/Runtime/NetworkVariable/Collections/NetworkDictionary.cs +++ b/com.unity.multiplayer.mlapi/Runtime/NetworkVariable/Collections/NetworkDictionary.cs @@ -23,9 +23,9 @@ public class NetworkDictionary : IDictionary, INetwo /// public readonly NetworkVariableSettings Settings = new NetworkVariableSettings(); - private readonly IDictionary dictionary = new Dictionary(); - private NetworkBehaviour networkBehaviour; - private readonly List> dirtyEvents = new List>(); + private readonly IDictionary m_Dictionary = new Dictionary(); + private NetworkBehaviour m_NetworkBehaviour; + private readonly List> m_DirtyEvents = new List>(); /// /// Delegate type for dictionary changed event @@ -61,7 +61,7 @@ public NetworkDictionary(NetworkVariableSettings settings) public NetworkDictionary(NetworkVariableSettings settings, IDictionary value) { Settings = settings; - dictionary = value; + m_Dictionary = value; } /// @@ -70,13 +70,13 @@ public NetworkDictionary(NetworkVariableSettings settings, IDictionaryThe initial value to use for the NetworkDictionary public NetworkDictionary(IDictionary value) { - dictionary = value; + m_Dictionary = value; } /// public void ResetDirty() { - dirtyEvents.Clear(); + m_DirtyEvents.Clear(); LastSyncedTime = NetworkManager.Singleton.NetworkTime; } @@ -89,142 +89,142 @@ public NetworkChannel GetChannel() /// public void ReadDelta(Stream stream, bool keepDirtyDelta, ushort localTick, ushort remoteTick) { - using (PooledNetworkReader reader = PooledNetworkReader.Get(stream)) + using (var reader = PooledNetworkReader.Get(stream)) { ushort deltaCount = reader.ReadUInt16Packed(); for (int i = 0; i < deltaCount; i++) { - NetworkDictionaryEvent.NetworkListEventType eventType = (NetworkDictionaryEvent.NetworkListEventType)reader.ReadBits(3); + NetworkDictionaryEvent.EventType eventType = (NetworkDictionaryEvent.EventType)reader.ReadBits(3); switch (eventType) { - case NetworkDictionaryEvent.NetworkListEventType.Add: + case NetworkDictionaryEvent.EventType.Add: { TKey key = (TKey)reader.ReadObjectPacked(typeof(TKey)); TValue value = (TValue)reader.ReadObjectPacked(typeof(TValue)); - dictionary.Add(key, value); + m_Dictionary.Add(key, value); if (OnDictionaryChanged != null) { OnDictionaryChanged(new NetworkDictionaryEvent { - eventType = eventType, - key = key, - value = value + Type = eventType, + Key = key, + Value = value }); } if (keepDirtyDelta) { - dirtyEvents.Add(new NetworkDictionaryEvent() + m_DirtyEvents.Add(new NetworkDictionaryEvent() { - eventType = eventType, - key = key, - value = value + Type = eventType, + Key = key, + Value = value }); } } break; - case NetworkDictionaryEvent.NetworkListEventType.Remove: + case NetworkDictionaryEvent.EventType.Remove: { TKey key = (TKey)reader.ReadObjectPacked(typeof(TKey)); TValue value; - dictionary.TryGetValue(key, out value); - dictionary.Remove(key); + m_Dictionary.TryGetValue(key, out value); + m_Dictionary.Remove(key); if (OnDictionaryChanged != null) { OnDictionaryChanged(new NetworkDictionaryEvent { - eventType = eventType, - key = key, - value = value + Type = eventType, + Key = key, + Value = value }); } if (keepDirtyDelta) { - dirtyEvents.Add(new NetworkDictionaryEvent() + m_DirtyEvents.Add(new NetworkDictionaryEvent() { - eventType = eventType, - key = key, - value = value + Type = eventType, + Key = key, + Value = value }); } } break; - case NetworkDictionaryEvent.NetworkListEventType.RemovePair: + case NetworkDictionaryEvent.EventType.RemovePair: { TKey key = (TKey)reader.ReadObjectPacked(typeof(TKey)); TValue value = (TValue)reader.ReadObjectPacked(typeof(TValue)); - dictionary.Remove(new KeyValuePair(key, value)); + m_Dictionary.Remove(new KeyValuePair(key, value)); if (OnDictionaryChanged != null) { OnDictionaryChanged(new NetworkDictionaryEvent { - eventType = eventType, - key = key, - value = value + Type = eventType, + Key = key, + Value = value }); } if (keepDirtyDelta) { - dirtyEvents.Add(new NetworkDictionaryEvent() + m_DirtyEvents.Add(new NetworkDictionaryEvent() { - eventType = eventType, - key = key, - value = value + Type = eventType, + Key = key, + Value = value }); } } break; - case NetworkDictionaryEvent.NetworkListEventType.Clear: + case NetworkDictionaryEvent.EventType.Clear: { //read nothing - dictionary.Clear(); + m_Dictionary.Clear(); if (OnDictionaryChanged != null) { OnDictionaryChanged(new NetworkDictionaryEvent { - eventType = eventType + Type = eventType }); } if (keepDirtyDelta) { - dirtyEvents.Add(new NetworkDictionaryEvent + m_DirtyEvents.Add(new NetworkDictionaryEvent { - eventType = eventType + Type = eventType }); } } break; - case NetworkDictionaryEvent.NetworkListEventType.Value: + case NetworkDictionaryEvent.EventType.Value: { TKey key = (TKey)reader.ReadObjectPacked(typeof(TKey)); TValue value = (TValue)reader.ReadObjectPacked(typeof(TValue)); - dictionary[key] = value; + m_Dictionary[key] = value; if (OnDictionaryChanged != null) { OnDictionaryChanged(new NetworkDictionaryEvent { - eventType = eventType, - key = key, - value = value + Type = eventType, + Key = key, + Value = value }); } if (keepDirtyDelta) { - dirtyEvents.Add(new NetworkDictionaryEvent() + m_DirtyEvents.Add(new NetworkDictionaryEvent() { - eventType = eventType, - key = key, - value = value + Type = eventType, + Key = key, + Value = value }); } } @@ -237,15 +237,15 @@ public void ReadDelta(Stream stream, bool keepDirtyDelta, ushort localTick, usho /// public void ReadField(Stream stream, ushort localTick, ushort remoteTick) { - using (PooledNetworkReader reader = PooledNetworkReader.Get(stream)) + using (var reader = PooledNetworkReader.Get(stream)) { - dictionary.Clear(); + m_Dictionary.Clear(); ushort entryCount = reader.ReadUInt16Packed(); for (int i = 0; i < entryCount; i++) { TKey key = (TKey)reader.ReadObjectPacked(typeof(TKey)); TValue value = (TValue)reader.ReadObjectPacked(typeof(TValue)); - dictionary.Add(key, value); + m_Dictionary.Add(key, value); } } } @@ -253,52 +253,52 @@ public void ReadField(Stream stream, ushort localTick, ushort remoteTick) /// public void SetNetworkBehaviour(NetworkBehaviour behaviour) { - networkBehaviour = behaviour; + m_NetworkBehaviour = behaviour; } /// public bool TryGetValue(TKey key, out TValue value) { - return dictionary.TryGetValue(key, out value); + return m_Dictionary.TryGetValue(key, out value); } /// public void WriteDelta(Stream stream) { - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(stream)) + using (var writer = PooledNetworkWriter.Get(stream)) { - writer.WriteUInt16Packed((ushort)dirtyEvents.Count); - for (int i = 0; i < dirtyEvents.Count; i++) + writer.WriteUInt16Packed((ushort)m_DirtyEvents.Count); + for (int i = 0; i < m_DirtyEvents.Count; i++) { - writer.WriteBits((byte)dirtyEvents[i].eventType, 3); - switch (dirtyEvents[i].eventType) + writer.WriteBits((byte)m_DirtyEvents[i].Type, 3); + switch (m_DirtyEvents[i].Type) { - case NetworkDictionaryEvent.NetworkListEventType.Add: + case NetworkDictionaryEvent.EventType.Add: { - writer.WriteObjectPacked(dirtyEvents[i].key); - writer.WriteObjectPacked(dirtyEvents[i].value); + writer.WriteObjectPacked(m_DirtyEvents[i].Key); + writer.WriteObjectPacked(m_DirtyEvents[i].Value); } break; - case NetworkDictionaryEvent.NetworkListEventType.Remove: + case NetworkDictionaryEvent.EventType.Remove: { - writer.WriteObjectPacked(dirtyEvents[i].key); + writer.WriteObjectPacked(m_DirtyEvents[i].Key); } break; - case NetworkDictionaryEvent.NetworkListEventType.RemovePair: + case NetworkDictionaryEvent.EventType.RemovePair: { - writer.WriteObjectPacked(dirtyEvents[i].key); - writer.WriteObjectPacked(dirtyEvents[i].value); + writer.WriteObjectPacked(m_DirtyEvents[i].Key); + writer.WriteObjectPacked(m_DirtyEvents[i].Value); } break; - case NetworkDictionaryEvent.NetworkListEventType.Clear: + case NetworkDictionaryEvent.EventType.Clear: { //write nothing } break; - case NetworkDictionaryEvent.NetworkListEventType.Value: + case NetworkDictionaryEvent.EventType.Value: { - writer.WriteObjectPacked(dirtyEvents[i].key); - writer.WriteObjectPacked(dirtyEvents[i].value); + writer.WriteObjectPacked(m_DirtyEvents[i].Key); + writer.WriteObjectPacked(m_DirtyEvents[i].Value); } break; } @@ -309,10 +309,10 @@ public void WriteDelta(Stream stream) /// public void WriteField(Stream stream) { - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(stream)) + using (var writer = PooledNetworkWriter.Get(stream)) { - writer.WriteUInt16Packed((ushort)dictionary.Count); - foreach (KeyValuePair pair in dictionary) + writer.WriteUInt16Packed((ushort)m_Dictionary.Count); + foreach (KeyValuePair pair in m_Dictionary) { writer.WriteObjectPacked(pair.Key); writer.WriteObjectPacked(pair.Value); @@ -330,7 +330,7 @@ public bool CanClientWrite(ulong clientId) case NetworkVariablePermission.ServerOnly: return false; case NetworkVariablePermission.OwnerOnly: - return networkBehaviour.OwnerClientId == clientId; + return m_NetworkBehaviour.OwnerClientId == clientId; case NetworkVariablePermission.Custom: { if (Settings.WritePermissionCallback == null) return false; @@ -351,7 +351,7 @@ public bool CanClientRead(ulong clientId) case NetworkVariablePermission.ServerOnly: return false; case NetworkVariablePermission.OwnerOnly: - return networkBehaviour.OwnerClientId == clientId; + return m_NetworkBehaviour.OwnerClientId == clientId; case NetworkVariablePermission.Custom: { if (Settings.ReadPermissionCallback == null) return false; @@ -365,7 +365,7 @@ public bool CanClientRead(ulong clientId) /// public bool IsDirty() { - if (dirtyEvents.Count == 0) return false; + if (m_DirtyEvents.Count == 0) return false; if (Settings.SendTickrate == 0) return true; if (Settings.SendTickrate < 0) return false; if (NetworkManager.Singleton.NetworkTime - LastSyncedTime >= (1f / Settings.SendTickrate)) return true; @@ -376,16 +376,16 @@ public bool IsDirty() /// public TValue this[TKey key] { - get => dictionary[key]; + get => m_Dictionary[key]; set { - if (NetworkManager.Singleton.IsServer) dictionary[key] = value; + if (NetworkManager.Singleton.IsServer) m_Dictionary[key] = value; NetworkDictionaryEvent dictionaryEvent = new NetworkDictionaryEvent() { - eventType = NetworkDictionaryEvent.NetworkListEventType.Value, - key = key, - value = value + Type = NetworkDictionaryEvent.EventType.Value, + Key = key, + Value = value }; HandleAddDictionaryEvent(dictionaryEvent); @@ -393,27 +393,27 @@ public TValue this[TKey key] } /// - public ICollection Keys => dictionary.Keys; + public ICollection Keys => m_Dictionary.Keys; /// - public ICollection Values => dictionary.Values; + public ICollection Values => m_Dictionary.Values; /// - public int Count => dictionary.Count; + public int Count => m_Dictionary.Count; /// - public bool IsReadOnly => dictionary.IsReadOnly; + public bool IsReadOnly => m_Dictionary.IsReadOnly; /// public void Add(TKey key, TValue value) { - if (NetworkManager.Singleton.IsServer) dictionary.Add(key, value); + if (NetworkManager.Singleton.IsServer) m_Dictionary.Add(key, value); NetworkDictionaryEvent dictionaryEvent = new NetworkDictionaryEvent() { - eventType = NetworkDictionaryEvent.NetworkListEventType.Add, - key = key, - value = value + Type = NetworkDictionaryEvent.EventType.Add, + Key = key, + Value = value }; HandleAddDictionaryEvent(dictionaryEvent); @@ -422,13 +422,13 @@ public void Add(TKey key, TValue value) /// public void Add(KeyValuePair item) { - if (NetworkManager.Singleton.IsServer) dictionary.Add(item); + if (NetworkManager.Singleton.IsServer) m_Dictionary.Add(item); NetworkDictionaryEvent dictionaryEvent = new NetworkDictionaryEvent() { - eventType = NetworkDictionaryEvent.NetworkListEventType.Add, - key = item.Key, - value = item.Value + Type = NetworkDictionaryEvent.EventType.Add, + Key = item.Key, + Value = item.Value }; HandleAddDictionaryEvent(dictionaryEvent); @@ -437,11 +437,11 @@ public void Add(KeyValuePair item) /// public void Clear() { - if (NetworkManager.Singleton.IsServer) dictionary.Clear(); + if (NetworkManager.Singleton.IsServer) m_Dictionary.Clear(); NetworkDictionaryEvent dictionaryEvent = new NetworkDictionaryEvent() { - eventType = NetworkDictionaryEvent.NetworkListEventType.Clear + Type = NetworkDictionaryEvent.EventType.Clear }; HandleAddDictionaryEvent(dictionaryEvent); @@ -450,41 +450,41 @@ public void Clear() /// public bool Contains(KeyValuePair item) { - return dictionary.Contains(item); + return m_Dictionary.Contains(item); } /// public bool ContainsKey(TKey key) { - return dictionary.ContainsKey(key); + return m_Dictionary.ContainsKey(key); } /// public void CopyTo(KeyValuePair[] array, int arrayIndex) { - dictionary.CopyTo(array, arrayIndex); + m_Dictionary.CopyTo(array, arrayIndex); } /// public IEnumerator> GetEnumerator() { - return dictionary.GetEnumerator(); + return m_Dictionary.GetEnumerator(); } /// public bool Remove(TKey key) { if (NetworkManager.Singleton.IsServer) - dictionary.Remove(key); + m_Dictionary.Remove(key); TValue value; - dictionary.TryGetValue(key, out value); + m_Dictionary.TryGetValue(key, out value); NetworkDictionaryEvent dictionaryEvent = new NetworkDictionaryEvent() { - eventType = NetworkDictionaryEvent.NetworkListEventType.Remove, - key = key, - value = value + Type = NetworkDictionaryEvent.EventType.Remove, + Key = key, + Value = value }; HandleAddDictionaryEvent(dictionaryEvent); @@ -496,13 +496,13 @@ public bool Remove(TKey key) /// public bool Remove(KeyValuePair item) { - if (NetworkManager.Singleton.IsServer) dictionary.Remove(item); + if (NetworkManager.Singleton.IsServer) m_Dictionary.Remove(item); NetworkDictionaryEvent dictionaryEvent = new NetworkDictionaryEvent() { - eventType = NetworkDictionaryEvent.NetworkListEventType.RemovePair, - key = item.Key, - value = item.Value + Type = NetworkDictionaryEvent.EventType.RemovePair, + Key = item.Key, + Value = item.Value }; HandleAddDictionaryEvent(dictionaryEvent); @@ -512,7 +512,7 @@ public bool Remove(KeyValuePair item) /// IEnumerator IEnumerable.GetEnumerator() { - return dictionary.GetEnumerator(); + return m_Dictionary.GetEnumerator(); } private void HandleAddDictionaryEvent(NetworkDictionaryEvent dictionaryEvent) @@ -521,14 +521,14 @@ private void HandleAddDictionaryEvent(NetworkDictionaryEvent dicti { if (NetworkManager.Singleton.ConnectedClients.Count > 0) { - dirtyEvents.Add(dictionaryEvent); + m_DirtyEvents.Add(dictionaryEvent); } OnDictionaryChanged?.Invoke(dictionaryEvent); } else { - dirtyEvents.Add(dictionaryEvent); + m_DirtyEvents.Add(dictionaryEvent); } } } @@ -543,7 +543,7 @@ public struct NetworkDictionaryEvent /// /// Enum representing the different operations available for triggering an event. /// - public enum NetworkListEventType + public enum EventType { /// /// Add @@ -574,16 +574,16 @@ public enum NetworkListEventType /// /// Enum representing the operation made to the dictionary. /// - public NetworkListEventType eventType; + public EventType Type; /// /// the key changed, added or removed if available. /// - public TKey key; + public TKey Key; /// /// The value changed, added or removed if available. /// - public TValue value; + public TValue Value; } } \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/NetworkVariable/Collections/NetworkList.cs b/com.unity.multiplayer.mlapi/Runtime/NetworkVariable/Collections/NetworkList.cs index 490ce63104..a103db4004 100644 --- a/com.unity.multiplayer.mlapi/Runtime/NetworkVariable/Collections/NetworkList.cs +++ b/com.unity.multiplayer.mlapi/Runtime/NetworkVariable/Collections/NetworkList.cs @@ -12,9 +12,9 @@ namespace MLAPI.NetworkVariable.Collections /// The type for the list public class NetworkList : IList, INetworkVariable { - private readonly IList list = new List(); - private readonly List> dirtyEvents = new List>(); - private NetworkBehaviour networkBehaviour; + private readonly IList m_List = new List(); + private readonly List> m_DirtyEvents = new List>(); + private NetworkBehaviour m_NetworkBehaviour; /// /// Gets the last time the variable was synced @@ -59,7 +59,7 @@ public NetworkList(NetworkVariableSettings settings) public NetworkList(NetworkVariableSettings settings, IList value) { Settings = settings; - list = value; + m_List = value; } /// @@ -68,20 +68,20 @@ public NetworkList(NetworkVariableSettings settings, IList value) /// The initial value to use for the NetworkList public NetworkList(IList value) { - list = value; + m_List = value; } /// public void ResetDirty() { - dirtyEvents.Clear(); + m_DirtyEvents.Clear(); LastSyncedTime = NetworkManager.Singleton.NetworkTime; } /// public bool IsDirty() { - if (dirtyEvents.Count == 0) return false; + if (m_DirtyEvents.Count == 0) return false; if (Settings.SendTickrate == 0) return true; if (Settings.SendTickrate < 0) return false; if (NetworkManager.Singleton.NetworkTime - LastSyncedTime >= (1f / Settings.SendTickrate)) return true; @@ -104,7 +104,7 @@ public bool CanClientWrite(ulong clientId) case NetworkVariablePermission.ServerOnly: return false; case NetworkVariablePermission.OwnerOnly: - return networkBehaviour.OwnerClientId == clientId; + return m_NetworkBehaviour.OwnerClientId == clientId; case NetworkVariablePermission.Custom: { if (Settings.WritePermissionCallback == null) return false; @@ -125,7 +125,7 @@ public bool CanClientRead(ulong clientId) case NetworkVariablePermission.ServerOnly: return false; case NetworkVariablePermission.OwnerOnly: - return networkBehaviour.OwnerClientId == clientId; + return m_NetworkBehaviour.OwnerClientId == clientId; case NetworkVariablePermission.Custom: { if (Settings.ReadPermissionCallback == null) return false; @@ -139,39 +139,39 @@ public bool CanClientRead(ulong clientId) /// public void WriteDelta(Stream stream) { - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(stream)) + using (var writer = PooledNetworkWriter.Get(stream)) { - writer.WriteUInt16Packed((ushort)dirtyEvents.Count); - for (int i = 0; i < dirtyEvents.Count; i++) + writer.WriteUInt16Packed((ushort)m_DirtyEvents.Count); + for (int i = 0; i < m_DirtyEvents.Count; i++) { - writer.WriteBits((byte)dirtyEvents[i].eventType, 3); - switch (dirtyEvents[i].eventType) + writer.WriteBits((byte)m_DirtyEvents[i].Type, 3); + switch (m_DirtyEvents[i].Type) { case NetworkListEvent.EventType.Add: { - writer.WriteObjectPacked(dirtyEvents[i].value); //BOX + writer.WriteObjectPacked(m_DirtyEvents[i].Value); //BOX } break; case NetworkListEvent.EventType.Insert: { - writer.WriteInt32Packed(dirtyEvents[i].index); - writer.WriteObjectPacked(dirtyEvents[i].value); //BOX + writer.WriteInt32Packed(m_DirtyEvents[i].Index); + writer.WriteObjectPacked(m_DirtyEvents[i].Value); //BOX } break; case NetworkListEvent.EventType.Remove: { - writer.WriteObjectPacked(dirtyEvents[i].value); //BOX + writer.WriteObjectPacked(m_DirtyEvents[i].Value); //BOX } break; case NetworkListEvent.EventType.RemoveAt: { - writer.WriteInt32Packed(dirtyEvents[i].index); + writer.WriteInt32Packed(m_DirtyEvents[i].Index); } break; case NetworkListEvent.EventType.Value: { - writer.WriteInt32Packed(dirtyEvents[i].index); - writer.WriteObjectPacked(dirtyEvents[i].value); //BOX + writer.WriteInt32Packed(m_DirtyEvents[i].Index); + writer.WriteObjectPacked(m_DirtyEvents[i].Value); //BOX } break; case NetworkListEvent.EventType.Clear: @@ -187,12 +187,12 @@ public void WriteDelta(Stream stream) /// public void WriteField(Stream stream) { - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(stream)) + using (var writer = PooledNetworkWriter.Get(stream)) { - writer.WriteUInt16Packed((ushort)list.Count); - for (int i = 0; i < list.Count; i++) + writer.WriteUInt16Packed((ushort)m_List.Count); + for (int i = 0; i < m_List.Count; i++) { - writer.WriteObjectPacked(list[i]); //BOX + writer.WriteObjectPacked(m_List[i]); //BOX } } } @@ -200,13 +200,13 @@ public void WriteField(Stream stream) /// public void ReadField(Stream stream, ushort localTick, ushort remoteTick) { - using (PooledNetworkReader reader = PooledNetworkReader.Get(stream)) + using (var reader = PooledNetworkReader.Get(stream)) { - list.Clear(); + m_List.Clear(); ushort count = reader.ReadUInt16Packed(); for (int i = 0; i < count; i++) { - list.Add((T)reader.ReadObjectPacked(typeof(T))); //BOX + m_List.Add((T)reader.ReadObjectPacked(typeof(T))); //BOX } } } @@ -214,7 +214,7 @@ public void ReadField(Stream stream, ushort localTick, ushort remoteTick) /// public void ReadDelta(Stream stream, bool keepDirtyDelta, ushort localTick, ushort remoteTick) { - using (PooledNetworkReader reader = PooledNetworkReader.Get(stream)) + using (var reader = PooledNetworkReader.Get(stream)) { ushort deltaCount = reader.ReadUInt16Packed(); for (int i = 0; i < deltaCount; i++) @@ -224,25 +224,25 @@ public void ReadDelta(Stream stream, bool keepDirtyDelta, ushort localTick, usho { case NetworkListEvent.EventType.Add: { - list.Add((T)reader.ReadObjectPacked(typeof(T))); //BOX + m_List.Add((T)reader.ReadObjectPacked(typeof(T))); //BOX if (OnListChanged != null) { OnListChanged(new NetworkListEvent { - eventType = eventType, - index = list.Count - 1, - value = list[list.Count - 1] + Type = eventType, + Index = m_List.Count - 1, + Value = m_List[m_List.Count - 1] }); } if (keepDirtyDelta) { - dirtyEvents.Add(new NetworkListEvent() + m_DirtyEvents.Add(new NetworkListEvent() { - eventType = eventType, - index = list.Count - 1, - value = list[list.Count - 1] + Type = eventType, + Index = m_List.Count - 1, + Value = m_List[m_List.Count - 1] }); } } @@ -250,25 +250,25 @@ public void ReadDelta(Stream stream, bool keepDirtyDelta, ushort localTick, usho case NetworkListEvent.EventType.Insert: { int index = reader.ReadInt32Packed(); - list.Insert(index, (T)reader.ReadObjectPacked(typeof(T))); //BOX + m_List.Insert(index, (T)reader.ReadObjectPacked(typeof(T))); //BOX if (OnListChanged != null) { OnListChanged(new NetworkListEvent { - eventType = eventType, - index = index, - value = list[index] + Type = eventType, + Index = index, + Value = m_List[index] }); } if (keepDirtyDelta) { - dirtyEvents.Add(new NetworkListEvent() + m_DirtyEvents.Add(new NetworkListEvent() { - eventType = eventType, - index = index, - value = list[index] + Type = eventType, + Index = index, + Value = m_List[index] }); } } @@ -276,26 +276,26 @@ public void ReadDelta(Stream stream, bool keepDirtyDelta, ushort localTick, usho case NetworkListEvent.EventType.Remove: { T value = (T)reader.ReadObjectPacked(typeof(T)); //BOX - int index = list.IndexOf(value); - list.RemoveAt(index); + int index = m_List.IndexOf(value); + m_List.RemoveAt(index); if (OnListChanged != null) { OnListChanged(new NetworkListEvent { - eventType = eventType, - index = index, - value = value + Type = eventType, + Index = index, + Value = value }); } if (keepDirtyDelta) { - dirtyEvents.Add(new NetworkListEvent() + m_DirtyEvents.Add(new NetworkListEvent() { - eventType = eventType, - index = index, - value = value + Type = eventType, + Index = index, + Value = value }); } } @@ -303,26 +303,26 @@ public void ReadDelta(Stream stream, bool keepDirtyDelta, ushort localTick, usho case NetworkListEvent.EventType.RemoveAt: { int index = reader.ReadInt32Packed(); - T value = list[index]; - list.RemoveAt(index); + T value = m_List[index]; + m_List.RemoveAt(index); if (OnListChanged != null) { OnListChanged(new NetworkListEvent { - eventType = eventType, - index = index, - value = value + Type = eventType, + Index = index, + Value = value }); } if (keepDirtyDelta) { - dirtyEvents.Add(new NetworkListEvent() + m_DirtyEvents.Add(new NetworkListEvent() { - eventType = eventType, - index = index, - value = value + Type = eventType, + Index = index, + Value = value }); } } @@ -331,25 +331,25 @@ public void ReadDelta(Stream stream, bool keepDirtyDelta, ushort localTick, usho { int index = reader.ReadInt32Packed(); T value = (T)reader.ReadObjectPacked(typeof(T)); //BOX - if (index < list.Count) list[index] = value; + if (index < m_List.Count) m_List[index] = value; if (OnListChanged != null) { OnListChanged(new NetworkListEvent { - eventType = eventType, - index = index, - value = value + Type = eventType, + Index = index, + Value = value }); } if (keepDirtyDelta) { - dirtyEvents.Add(new NetworkListEvent() + m_DirtyEvents.Add(new NetworkListEvent() { - eventType = eventType, - index = index, - value = value + Type = eventType, + Index = index, + Value = value }); } } @@ -357,21 +357,21 @@ public void ReadDelta(Stream stream, bool keepDirtyDelta, ushort localTick, usho case NetworkListEvent.EventType.Clear: { //Read nothing - list.Clear(); + m_List.Clear(); if (OnListChanged != null) { OnListChanged(new NetworkListEvent { - eventType = eventType, + Type = eventType, }); } if (keepDirtyDelta) { - dirtyEvents.Add(new NetworkListEvent() + m_DirtyEvents.Add(new NetworkListEvent() { - eventType = eventType + Type = eventType }); } } @@ -384,30 +384,30 @@ public void ReadDelta(Stream stream, bool keepDirtyDelta, ushort localTick, usho /// public void SetNetworkBehaviour(NetworkBehaviour behaviour) { - networkBehaviour = behaviour; + m_NetworkBehaviour = behaviour; } /// public IEnumerator GetEnumerator() { - return list.GetEnumerator(); + return m_List.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { - return ((IEnumerable)list).GetEnumerator(); + return ((IEnumerable)m_List).GetEnumerator(); } /// public void Add(T item) { - if (NetworkManager.Singleton.IsServer) list.Add(item); + if (NetworkManager.Singleton.IsServer) m_List.Add(item); NetworkListEvent listEvent = new NetworkListEvent() { - eventType = NetworkListEvent.EventType.Add, - value = item, - index = list.Count - 1 + Type = NetworkListEvent.EventType.Add, + Value = item, + Index = m_List.Count - 1 }; HandleAddListEvent(listEvent); @@ -416,11 +416,11 @@ public void Add(T item) /// public void Clear() { - if (NetworkManager.Singleton.IsServer) list.Clear(); + if (NetworkManager.Singleton.IsServer) m_List.Clear(); NetworkListEvent listEvent = new NetworkListEvent() { - eventType = NetworkListEvent.EventType.Clear + Type = NetworkListEvent.EventType.Clear }; HandleAddListEvent(listEvent); @@ -429,24 +429,24 @@ public void Clear() /// public bool Contains(T item) { - return list.Contains(item); + return m_List.Contains(item); } /// public void CopyTo(T[] array, int arrayIndex) { - list.CopyTo(array, arrayIndex); + m_List.CopyTo(array, arrayIndex); } /// public bool Remove(T item) { - if (NetworkManager.Singleton.IsServer) list.Remove(item); + if (NetworkManager.Singleton.IsServer) m_List.Remove(item); NetworkListEvent listEvent = new NetworkListEvent() { - eventType = NetworkListEvent.EventType.Remove, - value = item + Type = NetworkListEvent.EventType.Remove, + Value = item }; HandleAddListEvent(listEvent); @@ -454,27 +454,27 @@ public bool Remove(T item) } /// - public int Count => list.Count; + public int Count => m_List.Count; /// - public bool IsReadOnly => list.IsReadOnly; + public bool IsReadOnly => m_List.IsReadOnly; /// public int IndexOf(T item) { - return list.IndexOf(item); + return m_List.IndexOf(item); } /// public void Insert(int index, T item) { - if (NetworkManager.Singleton.IsServer) list.Insert(index, item); + if (NetworkManager.Singleton.IsServer) m_List.Insert(index, item); NetworkListEvent listEvent = new NetworkListEvent() { - eventType = NetworkListEvent.EventType.Insert, - index = index, - value = item + Type = NetworkListEvent.EventType.Insert, + Index = index, + Value = item }; HandleAddListEvent(listEvent); @@ -483,12 +483,12 @@ public void Insert(int index, T item) /// public void RemoveAt(int index) { - if (NetworkManager.Singleton.IsServer) list.RemoveAt(index); + if (NetworkManager.Singleton.IsServer) m_List.RemoveAt(index); NetworkListEvent listEvent = new NetworkListEvent() { - eventType = NetworkListEvent.EventType.RemoveAt, - index = index + Type = NetworkListEvent.EventType.RemoveAt, + Index = index }; HandleAddListEvent(listEvent); @@ -498,17 +498,17 @@ public void RemoveAt(int index) /// public T this[int index] { - get => list[index]; + get => m_List[index]; set { if (NetworkManager.Singleton.IsServer) - list[index] = value; + m_List[index] = value; NetworkListEvent listEvent = new NetworkListEvent() { - eventType = NetworkListEvent.EventType.Value, - index = index, - value = value + Type = NetworkListEvent.EventType.Value, + Index = index, + Value = value }; HandleAddListEvent(listEvent); @@ -521,14 +521,14 @@ private void HandleAddListEvent(NetworkListEvent listEvent) { if (NetworkManager.Singleton.ConnectedClients.Count > 0) { - dirtyEvents.Add(listEvent); + m_DirtyEvents.Add(listEvent); } OnListChanged?.Invoke(listEvent); } else { - dirtyEvents.Add(listEvent); + m_DirtyEvents.Add(listEvent); } } } @@ -578,16 +578,16 @@ public enum EventType /// /// Enum representing the operation made to the list. /// - public EventType eventType; + public EventType Type; /// /// The value changed, added or removed if available. /// - public T value; + public T Value; /// /// the index changed, added or removed if available /// - public int index; + public int Index; } } \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/NetworkVariable/Collections/NetworkSet.cs b/com.unity.multiplayer.mlapi/Runtime/NetworkVariable/Collections/NetworkSet.cs index 4a88fdc033..dc6f60b938 100644 --- a/com.unity.multiplayer.mlapi/Runtime/NetworkVariable/Collections/NetworkSet.cs +++ b/com.unity.multiplayer.mlapi/Runtime/NetworkVariable/Collections/NetworkSet.cs @@ -13,9 +13,9 @@ namespace MLAPI.NetworkVariable.Collections /// The type for the set public class NetworkSet : ISet, INetworkVariable { - private readonly ISet set = new HashSet(); - private readonly List> dirtyEvents = new List>(); - private NetworkBehaviour networkBehaviour; + private readonly ISet m_Set = new HashSet(); + private readonly List> m_DirtyEvents = new List>(); + private NetworkBehaviour m_NetworkBehaviour; /// /// Gets the last time the variable was synced @@ -60,7 +60,7 @@ public NetworkSet(NetworkVariableSettings settings) public NetworkSet(NetworkVariableSettings settings, ISet value) { Settings = settings; - set = value; + m_Set = value; } /// @@ -69,20 +69,20 @@ public NetworkSet(NetworkVariableSettings settings, ISet value) /// The initial value to use for the NetworkList public NetworkSet(ISet value) { - set = value; + m_Set = value; } /// public void ResetDirty() { - dirtyEvents.Clear(); + m_DirtyEvents.Clear(); LastSyncedTime = NetworkManager.Singleton.NetworkTime; } /// public bool IsDirty() { - if (dirtyEvents.Count == 0) return false; + if (m_DirtyEvents.Count == 0) return false; if (Settings.SendTickrate == 0) return true; if (Settings.SendTickrate < 0) return false; if (NetworkManager.Singleton.NetworkTime - LastSyncedTime >= (1f / Settings.SendTickrate)) return true; @@ -105,7 +105,7 @@ public bool CanClientWrite(ulong clientId) case NetworkVariablePermission.ServerOnly: return false; case NetworkVariablePermission.OwnerOnly: - return networkBehaviour.OwnerClientId == clientId; + return m_NetworkBehaviour.OwnerClientId == clientId; case NetworkVariablePermission.Custom: { if (Settings.WritePermissionCallback == null) return false; @@ -126,7 +126,7 @@ public bool CanClientRead(ulong clientId) case NetworkVariablePermission.ServerOnly: return false; case NetworkVariablePermission.OwnerOnly: - return networkBehaviour.OwnerClientId == clientId; + return m_NetworkBehaviour.OwnerClientId == clientId; case NetworkVariablePermission.Custom: { if (Settings.ReadPermissionCallback == null) return false; @@ -140,23 +140,23 @@ public bool CanClientRead(ulong clientId) /// public void WriteDelta(Stream stream) { - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(stream)) + using (var writer = PooledNetworkWriter.Get(stream)) { - writer.WriteUInt16Packed((ushort)dirtyEvents.Count); - for (int i = 0; i < dirtyEvents.Count; i++) + writer.WriteUInt16Packed((ushort)m_DirtyEvents.Count); + for (int i = 0; i < m_DirtyEvents.Count; i++) { - writer.WriteBits((byte)dirtyEvents[i].eventType, 2); + writer.WriteBits((byte)m_DirtyEvents[i].Type, 2); - switch (dirtyEvents[i].eventType) + switch (m_DirtyEvents[i].Type) { case NetworkSetEvent.EventType.Add: { - writer.WriteObjectPacked(dirtyEvents[i].value); //BOX + writer.WriteObjectPacked(m_DirtyEvents[i].Value); //BOX } break; case NetworkSetEvent.EventType.Remove: { - writer.WriteObjectPacked(dirtyEvents[i].value); //BOX + writer.WriteObjectPacked(m_DirtyEvents[i].Value); //BOX } break; case NetworkSetEvent.EventType.Clear: @@ -172,11 +172,11 @@ public void WriteDelta(Stream stream) /// public void WriteField(Stream stream) { - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(stream)) + using (var writer = PooledNetworkWriter.Get(stream)) { - writer.WriteUInt16Packed((ushort)set.Count); + writer.WriteUInt16Packed((ushort)m_Set.Count); - foreach (T value in set) + foreach (T value in m_Set) { writer.WriteObjectPacked(value); //BOX } @@ -186,14 +186,14 @@ public void WriteField(Stream stream) /// public void ReadField(Stream stream, ushort localTick, ushort remoteTick) { - using (PooledNetworkReader reader = PooledNetworkReader.Get(stream)) + using (var reader = PooledNetworkReader.Get(stream)) { - set.Clear(); + m_Set.Clear(); ushort count = reader.ReadUInt16Packed(); for (int i = 0; i < count; i++) { - set.Add((T)reader.ReadObjectPacked(typeof(T))); //BOX + m_Set.Add((T)reader.ReadObjectPacked(typeof(T))); //BOX } } } @@ -201,7 +201,7 @@ public void ReadField(Stream stream, ushort localTick, ushort remoteTick) /// public void ReadDelta(Stream stream, bool keepDirtyDelta, ushort localTick, ushort remoteTick) { - using (PooledNetworkReader reader = PooledNetworkReader.Get(stream)) + using (var reader = PooledNetworkReader.Get(stream)) { ushort deltaCount = reader.ReadUInt16Packed(); for (int i = 0; i < deltaCount; i++) @@ -212,23 +212,23 @@ public void ReadDelta(Stream stream, bool keepDirtyDelta, ushort localTick, usho case NetworkSetEvent.EventType.Add: { T value = (T)reader.ReadObjectPacked(typeof(T)); //BOX - set.Add(value); + m_Set.Add(value); if (OnSetChanged != null) { OnSetChanged(new NetworkSetEvent { - eventType = eventType, - value = value + Type = eventType, + Value = value }); } if (keepDirtyDelta) { - dirtyEvents.Add(new NetworkSetEvent() + m_DirtyEvents.Add(new NetworkSetEvent() { - eventType = eventType, - value = value + Type = eventType, + Value = value }); } } @@ -236,23 +236,23 @@ public void ReadDelta(Stream stream, bool keepDirtyDelta, ushort localTick, usho case NetworkSetEvent.EventType.Remove: { T value = (T)reader.ReadObjectPacked(typeof(T)); //BOX - set.Remove(value); + m_Set.Remove(value); if (OnSetChanged != null) { OnSetChanged(new NetworkSetEvent { - eventType = eventType, - value = value + Type = eventType, + Value = value }); } if (keepDirtyDelta) { - dirtyEvents.Add(new NetworkSetEvent() + m_DirtyEvents.Add(new NetworkSetEvent() { - eventType = eventType, - value = value + Type = eventType, + Value = value }); } } @@ -260,21 +260,21 @@ public void ReadDelta(Stream stream, bool keepDirtyDelta, ushort localTick, usho case NetworkSetEvent.EventType.Clear: { //Read nothing - set.Clear(); + m_Set.Clear(); if (OnSetChanged != null) { OnSetChanged(new NetworkSetEvent { - eventType = eventType, + Type = eventType, }); } if (keepDirtyDelta) { - dirtyEvents.Add(new NetworkSetEvent() + m_DirtyEvents.Add(new NetworkSetEvent() { - eventType = eventType + Type = eventType }); } } @@ -287,32 +287,32 @@ public void ReadDelta(Stream stream, bool keepDirtyDelta, ushort localTick, usho /// public void SetNetworkBehaviour(NetworkBehaviour behaviour) { - networkBehaviour = behaviour; + m_NetworkBehaviour = behaviour; } /// public IEnumerator GetEnumerator() { - return set.GetEnumerator(); + return m_Set.GetEnumerator(); } /// IEnumerator IEnumerable.GetEnumerator() { - return set.GetEnumerator(); + return m_Set.GetEnumerator(); } /// void ICollection.Add(T item) { - if (NetworkManager.Singleton.IsServer) set.Add(item); + if (NetworkManager.Singleton.IsServer) m_Set.Add(item); NetworkSetEvent setEvent = new NetworkSetEvent() { - eventType = NetworkSetEvent.EventType.Add, - value = item + Type = NetworkSetEvent.EventType.Add, + Value = item }; - dirtyEvents.Add(setEvent); + m_DirtyEvents.Add(setEvent); if (NetworkManager.Singleton.IsServer && OnSetChanged != null) OnSetChanged(setEvent); @@ -323,7 +323,7 @@ public void ExceptWith(IEnumerable other) { foreach (T value in other) { - if (set.Contains(value)) + if (m_Set.Contains(value)) { Remove(value); } @@ -335,7 +335,7 @@ public void IntersectWith(IEnumerable other) { HashSet otherSet = new HashSet(other); - foreach (T value in set) + foreach (T value in m_Set) { if (!otherSet.Contains(value)) { @@ -347,37 +347,37 @@ public void IntersectWith(IEnumerable other) /// public bool IsProperSubsetOf(IEnumerable other) { - return set.IsProperSubsetOf(other); + return m_Set.IsProperSubsetOf(other); } /// public bool IsProperSupersetOf(IEnumerable other) { - return set.IsProperSupersetOf(other); + return m_Set.IsProperSupersetOf(other); } /// public bool IsSubsetOf(IEnumerable other) { - return set.IsSubsetOf(other); + return m_Set.IsSubsetOf(other); } /// public bool IsSupersetOf(IEnumerable other) { - return set.IsSupersetOf(other); + return m_Set.IsSupersetOf(other); } /// public bool Overlaps(IEnumerable other) { - return set.Overlaps(other); + return m_Set.Overlaps(other); } /// public bool SetEquals(IEnumerable other) { - return set.SetEquals(other); + return m_Set.SetEquals(other); } /// @@ -385,20 +385,20 @@ public void SymmetricExceptWith(IEnumerable other) { foreach (T value in other) { - if (set.Contains(value)) + if (m_Set.Contains(value)) { Remove(value); } else { - if (NetworkManager.Singleton.IsServer) set.Add(value); + if (NetworkManager.Singleton.IsServer) m_Set.Add(value); NetworkSetEvent setEvent = new NetworkSetEvent() { - eventType = NetworkSetEvent.EventType.Add, - value = value + Type = NetworkSetEvent.EventType.Add, + Value = value }; - dirtyEvents.Add(setEvent); + m_DirtyEvents.Add(setEvent); if (NetworkManager.Singleton.IsServer && OnSetChanged != null) OnSetChanged(setEvent); @@ -411,16 +411,16 @@ public void UnionWith(IEnumerable other) { foreach (T value in other) { - if (!set.Contains(value)) + if (!m_Set.Contains(value)) { - if (NetworkManager.Singleton.IsServer) set.Add(value); + if (NetworkManager.Singleton.IsServer) m_Set.Add(value); NetworkSetEvent setEvent = new NetworkSetEvent() { - eventType = NetworkSetEvent.EventType.Add, - value = value + Type = NetworkSetEvent.EventType.Add, + Value = value }; - dirtyEvents.Add(setEvent); + m_DirtyEvents.Add(setEvent); if (NetworkManager.Singleton.IsServer && OnSetChanged != null) OnSetChanged(setEvent); @@ -431,14 +431,14 @@ public void UnionWith(IEnumerable other) /// bool ISet.Add(T item) { - if (NetworkManager.Singleton.IsServer) set.Add(item); + if (NetworkManager.Singleton.IsServer) m_Set.Add(item); NetworkSetEvent setEvent = new NetworkSetEvent() { - eventType = NetworkSetEvent.EventType.Add, - value = item + Type = NetworkSetEvent.EventType.Add, + Value = item }; - dirtyEvents.Add(setEvent); + m_DirtyEvents.Add(setEvent); if (NetworkManager.Singleton.IsServer && OnSetChanged != null) OnSetChanged(setEvent); @@ -449,13 +449,13 @@ bool ISet.Add(T item) /// public void Clear() { - if (NetworkManager.Singleton.IsServer) set.Clear(); + if (NetworkManager.Singleton.IsServer) m_Set.Clear(); NetworkSetEvent setEvent = new NetworkSetEvent() { - eventType = NetworkSetEvent.EventType.Clear + Type = NetworkSetEvent.EventType.Clear }; - dirtyEvents.Add(setEvent); + m_DirtyEvents.Add(setEvent); if (NetworkManager.Singleton.IsServer && OnSetChanged != null) OnSetChanged(setEvent); @@ -464,26 +464,26 @@ public void Clear() /// public bool Contains(T item) { - return set.Contains(item); + return m_Set.Contains(item); } /// public void CopyTo(T[] array, int arrayIndex) { - set.CopyTo(array, arrayIndex); + m_Set.CopyTo(array, arrayIndex); } /// public bool Remove(T item) { - if (NetworkManager.Singleton.IsServer) set.Remove(item); + if (NetworkManager.Singleton.IsServer) m_Set.Remove(item); NetworkSetEvent setEvent = new NetworkSetEvent() { - eventType = NetworkSetEvent.EventType.Remove, - value = item + Type = NetworkSetEvent.EventType.Remove, + Value = item }; - dirtyEvents.Add(setEvent); + m_DirtyEvents.Add(setEvent); if (NetworkManager.Singleton.IsServer && OnSetChanged != null) OnSetChanged(setEvent); @@ -492,10 +492,10 @@ public bool Remove(T item) } /// - public int Count => set.Count; + public int Count => m_Set.Count; /// - public bool IsReadOnly => set.IsReadOnly; + public bool IsReadOnly => m_Set.IsReadOnly; } /// @@ -528,12 +528,12 @@ public enum EventType /// /// Enum representing the operation made to the set. /// - public EventType eventType; + public EventType Type; /// /// The value changed, added or removed if available. /// - public T value; + public T Value; } } #endif \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/NetworkVariable/NetworkVariable.cs b/com.unity.multiplayer.mlapi/Runtime/NetworkVariable/NetworkVariable.cs index f3436f00bc..6795aa6269 100644 --- a/com.unity.multiplayer.mlapi/Runtime/NetworkVariable/NetworkVariable.cs +++ b/com.unity.multiplayer.mlapi/Runtime/NetworkVariable/NetworkVariable.cs @@ -13,14 +13,11 @@ namespace MLAPI.NetworkVariable [Serializable] public class NetworkVariable : INetworkVariable { - /// - /// Gets or sets Whether or not the variable needs to be delta synced - /// - public bool isDirty { get; set; } /// /// The settings for this var /// public readonly NetworkVariableSettings Settings = new NetworkVariableSettings(); + /// /// The last time the variable was written to locally /// @@ -39,14 +36,13 @@ public class NetworkVariable : INetworkVariable /// The callback to be invoked when the value gets changed /// public OnValueChangedDelegate OnValueChanged; - private NetworkBehaviour networkBehaviour; + + private NetworkBehaviour m_NetworkBehaviour; /// /// Creates a NetworkVariable with the default value and settings /// - public NetworkVariable() - { - } + public NetworkVariable() { } /// /// Creates a NetworkVariable with the default value and custom settings @@ -65,7 +61,7 @@ public NetworkVariable(NetworkVariableSettings settings) public NetworkVariable(NetworkVariableSettings settings, T value) { Settings = settings; - InternalValue = value; + m_InternalValue = value; } /// @@ -74,42 +70,53 @@ public NetworkVariable(NetworkVariableSettings settings, T value) /// The initial value to use for the NetworkVariable public NetworkVariable(T value) { - InternalValue = value; + m_InternalValue = value; } [SerializeField] - private T InternalValue; + private T m_InternalValue; + /// /// The value of the NetworkVariable container /// public T Value { - get => InternalValue; + get => m_InternalValue; set { - if (EqualityComparer.Default.Equals(InternalValue, value)) return; + if (EqualityComparer.Default.Equals(m_InternalValue, value)) return; // Setter is assumed to be called locally, by game code. // When used by the host, it is its responsibility to set the RemoteTick - RemoteTick = NetworkTickSystem.k_NoTick; + RemoteTick = NetworkTickSystem.NoTick; - isDirty = true; - T previousValue = InternalValue; - InternalValue = value; - OnValueChanged?.Invoke(previousValue, InternalValue); + m_IsDirty = true; + T previousValue = m_InternalValue; + m_InternalValue = value; + OnValueChanged?.Invoke(previousValue, m_InternalValue); } } - /// - public void ResetDirty() + private bool m_IsDirty = false; + + /// + /// Sets whether or not the variable needs to be delta synced + /// + public void SetDirty(bool isDirty) { - isDirty = false; + m_IsDirty = isDirty; } /// public bool IsDirty() { - return isDirty; + return m_IsDirty; + } + + /// + public void ResetDirty() + { + m_IsDirty = false; } /// @@ -122,7 +129,7 @@ public bool CanClientRead(ulong clientId) case NetworkVariablePermission.ServerOnly: return false; case NetworkVariablePermission.OwnerOnly: - return networkBehaviour.OwnerClientId == clientId; + return m_NetworkBehaviour.OwnerClientId == clientId; case NetworkVariablePermission.Custom: { if (Settings.ReadPermissionCallback == null) return false; @@ -159,7 +166,7 @@ public bool CanClientWrite(ulong clientId) case NetworkVariablePermission.ServerOnly: return false; case NetworkVariablePermission.OwnerOnly: - return networkBehaviour.OwnerClientId == clientId; + return m_NetworkBehaviour.OwnerClientId == clientId; case NetworkVariablePermission.Custom: { if (Settings.WritePermissionCallback == null) return false; @@ -184,19 +191,19 @@ public void ReadDelta(Stream stream, bool keepDirtyDelta, ushort localTick, usho using (var reader = PooledNetworkReader.Get(stream)) { - T previousValue = InternalValue; - InternalValue = (T)reader.ReadObjectPacked(typeof(T)); + T previousValue = m_InternalValue; + m_InternalValue = (T)reader.ReadObjectPacked(typeof(T)); - if (keepDirtyDelta) isDirty = true; + if (keepDirtyDelta) m_IsDirty = true; - OnValueChanged?.Invoke(previousValue, InternalValue); + OnValueChanged?.Invoke(previousValue, m_InternalValue); } } /// public void SetNetworkBehaviour(NetworkBehaviour behaviour) { - networkBehaviour = behaviour; + m_NetworkBehaviour = behaviour; } /// @@ -209,10 +216,10 @@ public void ReadField(Stream stream, ushort localTick, ushort remoteTick) public void WriteField(Stream stream) { // Store the local tick at which this NetworkVariable was modified - LocalTick = NetworkBehaviour.currentTick; - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(stream)) + LocalTick = NetworkBehaviour.CurrentTick; + using (var writer = PooledNetworkWriter.Get(stream)) { - writer.WriteObjectPacked(InternalValue); //BOX + writer.WriteObjectPacked(m_InternalValue); //BOX } } @@ -231,10 +238,13 @@ public class NetworkVariableString : NetworkVariable { /// public NetworkVariableString() : base(string.Empty) { } + /// public NetworkVariableString(NetworkVariableSettings settings) : base(settings, string.Empty) { } + /// public NetworkVariableString(string value) : base(value) { } + /// public NetworkVariableString(NetworkVariableSettings settings, string value) : base(settings, value) { } } @@ -247,10 +257,13 @@ public class NetworkVariableBool : NetworkVariable { /// public NetworkVariableBool() { } + /// public NetworkVariableBool(NetworkVariableSettings settings) : base(settings) { } + /// public NetworkVariableBool(bool value) : base(value) { } + /// public NetworkVariableBool(NetworkVariableSettings settings, bool value) : base(settings, value) { } } @@ -263,10 +276,13 @@ public class NetworkVariableByte : NetworkVariable { /// public NetworkVariableByte() { } + /// public NetworkVariableByte(NetworkVariableSettings settings) : base(settings) { } + /// public NetworkVariableByte(byte value) : base(value) { } + /// public NetworkVariableByte(NetworkVariableSettings settings, byte value) : base(settings, value) { } } @@ -279,10 +295,13 @@ public class NetworkVariableSByte : NetworkVariable { /// public NetworkVariableSByte() { } + /// public NetworkVariableSByte(NetworkVariableSettings settings) : base(settings) { } + /// public NetworkVariableSByte(sbyte value) : base(value) { } + /// public NetworkVariableSByte(NetworkVariableSettings settings, sbyte value) : base(settings, value) { } } @@ -295,10 +314,13 @@ public class NetworkVariableUShort : NetworkVariable { /// public NetworkVariableUShort() { } + /// public NetworkVariableUShort(NetworkVariableSettings settings) : base(settings) { } + /// public NetworkVariableUShort(ushort value) : base(value) { } + /// public NetworkVariableUShort(NetworkVariableSettings settings, ushort value) : base(settings, value) { } } @@ -311,10 +333,13 @@ public class NetworkVariableShort : NetworkVariable { /// public NetworkVariableShort() { } + /// public NetworkVariableShort(NetworkVariableSettings settings) : base(settings) { } + /// public NetworkVariableShort(short value) : base(value) { } + /// public NetworkVariableShort(NetworkVariableSettings settings, short value) : base(settings, value) { } } @@ -327,10 +352,13 @@ public class NetworkVariableUInt : NetworkVariable { /// public NetworkVariableUInt() { } + /// public NetworkVariableUInt(NetworkVariableSettings settings) : base(settings) { } + /// public NetworkVariableUInt(uint value) : base(value) { } + /// public NetworkVariableUInt(NetworkVariableSettings settings, uint value) : base(settings, value) { } } @@ -343,10 +371,13 @@ public class NetworkVariableInt : NetworkVariable { /// public NetworkVariableInt() { } + /// public NetworkVariableInt(NetworkVariableSettings settings) : base(settings) { } + /// public NetworkVariableInt(int value) : base(value) { } + /// public NetworkVariableInt(NetworkVariableSettings settings, int value) : base(settings, value) { } } @@ -359,10 +390,13 @@ public class NetworkVariableULong : NetworkVariable { /// public NetworkVariableULong() { } + /// public NetworkVariableULong(NetworkVariableSettings settings) : base(settings) { } + /// public NetworkVariableULong(ulong value) : base(value) { } + /// public NetworkVariableULong(NetworkVariableSettings settings, ulong value) : base(settings, value) { } } @@ -375,10 +409,13 @@ public class NetworkVariableLong : NetworkVariable { /// public NetworkVariableLong() { } + /// public NetworkVariableLong(NetworkVariableSettings settings) : base(settings) { } + /// public NetworkVariableLong(long value) : base(value) { } + /// public NetworkVariableLong(NetworkVariableSettings settings, long value) : base(settings, value) { } } @@ -391,10 +428,13 @@ public class NetworkVariableFloat : NetworkVariable { /// public NetworkVariableFloat() { } + /// public NetworkVariableFloat(NetworkVariableSettings settings) : base(settings) { } + /// public NetworkVariableFloat(float value) : base(value) { } + /// public NetworkVariableFloat(NetworkVariableSettings settings, float value) : base(settings, value) { } } @@ -407,10 +447,13 @@ public class NetworkVariableDouble : NetworkVariable { /// public NetworkVariableDouble() { } + /// public NetworkVariableDouble(NetworkVariableSettings settings) : base(settings) { } + /// public NetworkVariableDouble(double value) : base(value) { } + /// public NetworkVariableDouble(NetworkVariableSettings settings, double value) : base(settings, value) { } } @@ -423,10 +466,13 @@ public class NetworkVariableVector2 : NetworkVariable { /// public NetworkVariableVector2() { } + /// public NetworkVariableVector2(NetworkVariableSettings settings) : base(settings) { } + /// public NetworkVariableVector2(Vector2 value) : base(value) { } + /// public NetworkVariableVector2(NetworkVariableSettings settings, Vector2 value) : base(settings, value) { } } @@ -439,10 +485,13 @@ public class NetworkVariableVector3 : NetworkVariable { /// public NetworkVariableVector3() { } + /// public NetworkVariableVector3(NetworkVariableSettings settings) : base(settings) { } + /// public NetworkVariableVector3(Vector3 value) : base(value) { } + /// public NetworkVariableVector3(NetworkVariableSettings settings, Vector3 value) : base(settings, value) { } } @@ -455,10 +504,13 @@ public class NetworkVariableVector4 : NetworkVariable { /// public NetworkVariableVector4() { } + /// public NetworkVariableVector4(NetworkVariableSettings settings) : base(settings) { } + /// public NetworkVariableVector4(Vector4 value) : base(value) { } + /// public NetworkVariableVector4(NetworkVariableSettings settings, Vector4 value) : base(settings, value) { } } @@ -471,10 +523,13 @@ public class NetworkVariableColor : NetworkVariable { /// public NetworkVariableColor() { } + /// public NetworkVariableColor(NetworkVariableSettings settings) : base(settings) { } + /// public NetworkVariableColor(Color value) : base(value) { } + /// public NetworkVariableColor(NetworkVariableSettings settings, Color value) : base(settings, value) { } } @@ -487,10 +542,13 @@ public class NetworkVariableColor32 : NetworkVariable { /// public NetworkVariableColor32() { } + /// public NetworkVariableColor32(NetworkVariableSettings settings) : base(settings) { } + /// public NetworkVariableColor32(Color32 value) : base(value) { } + /// public NetworkVariableColor32(NetworkVariableSettings settings, Color32 value) : base(settings, value) { } } @@ -503,10 +561,13 @@ public class NetworkVariableRay : NetworkVariable { /// public NetworkVariableRay() { } + /// public NetworkVariableRay(NetworkVariableSettings settings) : base(settings) { } + /// public NetworkVariableRay(Ray value) : base(value) { } + /// public NetworkVariableRay(NetworkVariableSettings settings, Ray value) : base(settings, value) { } } @@ -519,10 +580,13 @@ public class NetworkVariableQuaternion : NetworkVariable { /// public NetworkVariableQuaternion() { } + /// public NetworkVariableQuaternion(NetworkVariableSettings settings) : base(settings) { } + /// public NetworkVariableQuaternion(Quaternion value) : base(value) { } + /// public NetworkVariableQuaternion(NetworkVariableSettings settings, Quaternion value) : base(settings, value) { } } diff --git a/com.unity.multiplayer.mlapi/Runtime/NetworkVariable/NetworkVariablePermission.cs b/com.unity.multiplayer.mlapi/Runtime/NetworkVariable/NetworkVariablePermission.cs index 987a72e770..2bef629b28 100644 --- a/com.unity.multiplayer.mlapi/Runtime/NetworkVariable/NetworkVariablePermission.cs +++ b/com.unity.multiplayer.mlapi/Runtime/NetworkVariable/NetworkVariablePermission.cs @@ -9,14 +9,17 @@ public enum NetworkVariablePermission /// Everyone /// Everyone, + /// /// Server-only operation /// ServerOnly, + /// /// Owner-ownly /// OwnerOnly, + /// /// Custom delegate /// diff --git a/com.unity.multiplayer.mlapi/Runtime/NetworkVariable/NetworkVariableSettings.cs b/com.unity.multiplayer.mlapi/Runtime/NetworkVariable/NetworkVariableSettings.cs index c70f832f2d..696650b19d 100644 --- a/com.unity.multiplayer.mlapi/Runtime/NetworkVariable/NetworkVariableSettings.cs +++ b/com.unity.multiplayer.mlapi/Runtime/NetworkVariable/NetworkVariableSettings.cs @@ -45,9 +45,6 @@ public class NetworkVariableSettings /// /// Constructs a new NetworkVariableSettings instance /// - public NetworkVariableSettings() - { - - } + public NetworkVariableSettings() { } } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Profiling/ITransportProfilerData.cs b/com.unity.multiplayer.mlapi/Runtime/Profiling/ITransportProfilerData.cs index fc8f757f8d..db94b69fc5 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Profiling/ITransportProfilerData.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Profiling/ITransportProfilerData.cs @@ -7,4 +7,4 @@ public interface ITransportProfilerData void BeginNewTick(); IReadOnlyDictionary GetTransportProfilerData(); } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Profiling/NetworkProfiler.cs b/com.unity.multiplayer.mlapi/Runtime/Profiling/NetworkProfiler.cs index c9b4ec0b1a..501a446616 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Profiling/NetworkProfiler.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Profiling/NetworkProfiler.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.ComponentModel; using MLAPI.Collections; using MLAPI.Configuration; using MLAPI.Transports; @@ -23,9 +21,9 @@ public static class NetworkProfiler /// public static bool IsRunning { get; private set; } - private static int tickHistory = 1024; - private static int EventIdCounter = 0; - private static ProfilerTick CurrentTick; + private static int s_TickHistory = 1024; + private static int s_EventIdCounter = 0; + private static ProfilerTick s_CurrentTick; /// /// Starts recording data for the Profiler @@ -33,12 +31,11 @@ public static class NetworkProfiler /// The amount of ticks to keep in memory public static void Start(int historyLength) { - if (IsRunning) - return; - EventIdCounter = 0; + if (IsRunning) return; + s_EventIdCounter = 0; Ticks = new FixedQueue(historyLength); - tickHistory = historyLength; - CurrentTick = null; + s_TickHistory = historyLength; + s_CurrentTick = null; IsRunning = true; } @@ -48,7 +45,7 @@ public static void Start(int historyLength) public static void Stop() { Ticks = null; //leave to GC - CurrentTick = null; //leave to GC + s_CurrentTick = null; //leave to GC IsRunning = false; } @@ -59,13 +56,12 @@ public static void Stop() /// The number of ticks recorded public static int Stop(ref ProfilerTick[] tickBuffer) { - if (!IsRunning) - return 0; + if (!IsRunning) return 0; int iteration = Ticks.Count > tickBuffer.Length ? tickBuffer.Length : Ticks.Count; for (int i = 0; i < iteration; i++) tickBuffer[i] = Ticks[i]; Ticks = null; //leave to GC - CurrentTick = null; //leave to GC + s_CurrentTick = null; //leave to GC IsRunning = false; return iteration; @@ -78,13 +74,13 @@ public static int Stop(ref ProfilerTick[] tickBuffer) /// The number of ticks recorded public static int Stop(ref List tickBuffer) { - if (!IsRunning) - return 0; + if (!IsRunning) return 0; + int iteration = Ticks.Count > tickBuffer.Count ? tickBuffer.Count : Ticks.Count; for (int i = 0; i < iteration; i++) tickBuffer[i] = Ticks[i]; Ticks = null; //leave to GC - CurrentTick = null; //leave to GC + s_CurrentTick = null; //leave to GC IsRunning = false; return iteration; @@ -92,62 +88,55 @@ public static int Stop(ref List tickBuffer) internal static void StartTick(TickType type) { - if (!IsRunning) - return; - if (Ticks.Count == tickHistory) + if (!IsRunning) return; + if (Ticks.Count == s_TickHistory) + { Ticks.Dequeue(); + } - ProfilerTick tick = new ProfilerTick() + var tick = new ProfilerTick() { Type = type, Frame = Time.frameCount, - EventId = EventIdCounter + EventId = s_EventIdCounter }; - EventIdCounter++; + s_EventIdCounter++; Ticks.Enqueue(tick); - CurrentTick = tick; + s_CurrentTick = tick; } internal static void EndTick() { - if (!IsRunning) - return; - if (CurrentTick == null) - return; - CurrentTick = null; + if (!IsRunning) return; + if (s_CurrentTick == null) return; + s_CurrentTick = null; } internal static void StartEvent(TickType eventType, uint bytes, NetworkChannel networkChannel, byte messageType) { - if (!IsRunning) - return; - if (CurrentTick == null) - return; + if (!IsRunning) return; + if (s_CurrentTick == null) return; string messageName = messageType < NetworkConstants.MESSAGE_NAMES.Length ? NetworkConstants.MESSAGE_NAMES[messageType] : "INVALID_MESSAGE_TYPE"; string channelName = networkChannel.ToString(); - CurrentTick.StartEvent(eventType, bytes, channelName, messageName); + s_CurrentTick.StartEvent(eventType, bytes, channelName, messageName); } internal static void StartEvent(TickType eventType, uint bytes, NetworkChannel networkChannel, string messageName) { - if (!IsRunning) - return; - if (CurrentTick == null) - return; + if (!IsRunning) return; + if (s_CurrentTick == null) return; string channelName = networkChannel.ToString(); - CurrentTick.StartEvent(eventType, bytes, channelName, messageName); + s_CurrentTick.StartEvent(eventType, bytes, channelName, messageName); } internal static void EndEvent() { - if (!IsRunning) - return; - if (CurrentTick == null) - return; - CurrentTick.EndEvent(); + if (!IsRunning) return; + if (s_CurrentTick == null) return; + s_CurrentTick.EndEvent(); } } } \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Profiling/PerformanceDataManager.cs b/com.unity.multiplayer.mlapi/Runtime/Profiling/PerformanceDataManager.cs index a2f5bccd50..830267b8f5 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Profiling/PerformanceDataManager.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Profiling/PerformanceDataManager.cs @@ -1,20 +1,19 @@ using System; using System.Collections.Generic; -using System.Linq; namespace MLAPI.Profiling { - static class PerformanceDataManager + internal static class PerformanceDataManager { - static PerformanceTickData s_ProfilerData; - static int s_TickID; + private static PerformanceTickData s_ProfilerData; + private static int s_TickId; internal static void BeginNewTick() { - s_TickID = Math.Max(s_TickID, 0); + s_TickId = Math.Max(s_TickId, 0); s_ProfilerData = new PerformanceTickData { - tickID = s_TickID++, + TickId = s_TickId++, }; } @@ -33,4 +32,4 @@ internal static PerformanceTickData GetData() return s_ProfilerData; } } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Profiling/PerformanceTickData.cs b/com.unity.multiplayer.mlapi/Runtime/Profiling/PerformanceTickData.cs index b3b9c4b8e2..dfb5729ea4 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Profiling/PerformanceTickData.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Profiling/PerformanceTickData.cs @@ -5,9 +5,9 @@ namespace MLAPI.Profiling { public class PerformanceTickData { - public int tickID; + public int TickId; - readonly ProfilingDataStore m_TickData = new ProfilingDataStore(); + private readonly ProfilingDataStore m_TickData = new ProfilingDataStore(); public void Increment(string fieldName, int count = 1) { @@ -16,8 +16,8 @@ public void Increment(string fieldName, int count = 1) public void AddNonDuplicateData(IReadOnlyDictionary transportProfilerData) { - IEnumerable> nonDuplicates = transportProfilerData.Where(entry => !m_TickData.HasData(entry.Key)); - foreach (KeyValuePair entry in nonDuplicates) + var nonDuplicates = transportProfilerData.Where(entry => !m_TickData.HasData(entry.Key)); + foreach (var entry in nonDuplicates) { m_TickData.Add(entry.Key, entry.Value); } @@ -28,4 +28,4 @@ public int GetData(string fieldName) return m_TickData.GetData(fieldName); } } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilerCounterUtility.cs b/com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilerCounterUtility.cs index 85ee977b90..49e398e6c2 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilerCounterUtility.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilerCounterUtility.cs @@ -1,16 +1,18 @@ using System; + #if UNITY_2020_2_OR_NEWER using Unity.Profiling.LowLevel; #endif namespace MLAPI.Profiling { - struct ProfilerCounterUtility + internal struct ProfilerCounterUtility { #if UNITY_2020_2_OR_NEWER && ENABLE_PROFILER public static byte GetProfilerMarkerDataType() { - switch (Type.GetTypeCode(typeof(T))) { + switch (Type.GetTypeCode(typeof(T))) + { case TypeCode.Int32: return (byte)ProfilerMarkerDataType.Int32; case TypeCode.UInt32: @@ -31,6 +33,4 @@ public static byte GetProfilerMarkerDataType() } #endif } -} - - +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilerCounterValue.cs b/com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilerCounterValue.cs index b4e17630c9..55b6c1bb8a 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilerCounterValue.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilerCounterValue.cs @@ -7,7 +7,6 @@ using Unity.Profiling.LowLevel; using Unity.Profiling.LowLevel.Unsafe; #endif -using UnityEngine; namespace MLAPI.Profiling { @@ -30,7 +29,8 @@ public ProfilerCounterValue(ProfilerCategory category, string name, ProfilerMark { #if ENABLE_PROFILER byte dataType = ProfilerCounterUtility.GetProfilerMarkerDataType(); - unsafe { + unsafe + { m_Value = (T*)ProfilerUnsafeUtility.CreateCounterValue(out var counterPtr, name, category, MarkerFlags.Default, dataType, (byte)dataUnit, UnsafeUtility.SizeOf(), counterOptions); } #endif @@ -39,9 +39,11 @@ public ProfilerCounterValue(ProfilerCategory category, string name, ProfilerMark public T Value { [MethodImpl(MethodImplOptions.AggressiveInlining)] - get { + get + { #if ENABLE_PROFILER - unsafe { + unsafe + { return *m_Value; } #else @@ -50,9 +52,11 @@ public T Value } [MethodImpl(MethodImplOptions.AggressiveInlining)] - set { + set + { #if ENABLE_PROFILER - unsafe { + unsafe + { *m_Value = value; } #endif @@ -60,6 +64,4 @@ public T Value } #endif } -} - - +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilerCountersInfo.cs b/com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilerCountersInfo.cs index 05c85057ca..4273cb04c5 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilerCountersInfo.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilerCountersInfo.cs @@ -1,4 +1,3 @@ -using System; #if UNITY_2020_2_OR_NEWER using Unity.Profiling; #endif @@ -6,98 +5,97 @@ namespace MLAPI.Profiling { - internal static class ProfilerCountersInfo { #if UNITY_2020_2_OR_NEWER && ENABLE_PROFILER // Operations - private static ProfilerCounterValue s_ConnectionsCounterValue = - new ProfilerCounterValue(ProfilerCategory.Network, ProfilerConstants.NumberOfConnections, - ProfilerMarkerDataUnit.Count, ProfilerCounterOptions.FlushOnEndOfFrame); + private static readonly ProfilerCounterValue k_ConnectionsCounterValue = + new ProfilerCounterValue(ProfilerCategory.Network, ProfilerConstants.NumberOfConnections, + ProfilerMarkerDataUnit.Count, ProfilerCounterOptions.FlushOnEndOfFrame); - private static ProfilerCounterValue s_TickRateCounterValue = + private static readonly ProfilerCounterValue k_TickRateCounterValue = new ProfilerCounterValue(ProfilerCategory.Network, ProfilerConstants.ReceiveTickRate, ProfilerMarkerDataUnit.Count, ProfilerCounterOptions.FlushOnEndOfFrame); - //Messages - private static ProfilerCounterValue s_NamedMessagesCounterValue = + // Messages + private static readonly ProfilerCounterValue k_NamedMessagesCounterValue = new ProfilerCounterValue(ProfilerCategory.Network, ProfilerConstants.NumberOfNamedMessages, ProfilerMarkerDataUnit.Count, ProfilerCounterOptions.FlushOnEndOfFrame); - private static ProfilerCounterValue s_UnnamedMessagesCounterValue = + private static readonly ProfilerCounterValue k_UnnamedMessagesCounterValue = new ProfilerCounterValue(ProfilerCategory.Network, ProfilerConstants.NumberOfUnnamedMessages, ProfilerMarkerDataUnit.Count, ProfilerCounterOptions.FlushOnEndOfFrame); - private static ProfilerCounterValue s_BytesSentCounterValue = + private static readonly ProfilerCounterValue k_BytesSentCounterValue = new ProfilerCounterValue(ProfilerCategory.Network, ProfilerConstants.NumberBytesSent, ProfilerMarkerDataUnit.Count, ProfilerCounterOptions.FlushOnEndOfFrame); - private static ProfilerCounterValue s_BytesReceivedCounterValue = + private static readonly ProfilerCounterValue k_BytesReceivedCounterValue = new ProfilerCounterValue(ProfilerCategory.Network, ProfilerConstants.NumberBytesReceived, ProfilerMarkerDataUnit.Count, ProfilerCounterOptions.FlushOnEndOfFrame); - private static ProfilerCounterValue s_NetworkVarsCounterValue = + private static readonly ProfilerCounterValue k_NetworkVarsCounterValue = new ProfilerCounterValue(ProfilerCategory.Network, ProfilerConstants.NumberNetworkVarsReceived, ProfilerMarkerDataUnit.Count, ProfilerCounterOptions.FlushOnEndOfFrame); - //RPCs - private static ProfilerCounterValue s_RPCsSentCounterValue = + // RPCs + private static readonly ProfilerCounterValue k_RPCsSentCounterValue = new ProfilerCounterValue(ProfilerCategory.Network, ProfilerConstants.NumberOfRPCsSent, ProfilerMarkerDataUnit.Count, ProfilerCounterOptions.FlushOnEndOfFrame); - private static ProfilerCounterValue s_RPCsReceivedCounterValue = + private static readonly ProfilerCounterValue k_RPCsReceivedCounterValue = new ProfilerCounterValue(ProfilerCategory.Network, ProfilerConstants.NumberOfRPCsReceived, ProfilerMarkerDataUnit.Count, ProfilerCounterOptions.FlushOnEndOfFrame); - private static ProfilerCounterValue s_RPCBatchesSentCounterValue = + private static readonly ProfilerCounterValue k_RPCBatchesSentCounterValue = new ProfilerCounterValue(ProfilerCategory.Network, ProfilerConstants.NumberOfRPCBatchesSent, ProfilerMarkerDataUnit.Count, ProfilerCounterOptions.FlushOnEndOfFrame); - private static ProfilerCounterValue s_RPCBatchesReceivedCounterValue = + private static readonly ProfilerCounterValue k_RPCBatchesReceivedCounterValue = new ProfilerCounterValue(ProfilerCategory.Network, ProfilerConstants.NumberOfRPCBatchesReceived, ProfilerMarkerDataUnit.Count, ProfilerCounterOptions.FlushOnEndOfFrame); - private static ProfilerCounterValue s_RPCQueueProcessedCounterValue = + private static readonly ProfilerCounterValue k_RPCQueueProcessedCounterValue = new ProfilerCounterValue(ProfilerCategory.Network, ProfilerConstants.NumberOfRPCQueueProcessed, ProfilerMarkerDataUnit.Count, ProfilerCounterOptions.FlushOnEndOfFrame); - private static ProfilerCounterValue s_RPCsInQueueSizeCounterValue = + private static readonly ProfilerCounterValue k_RPCsInQueueSizeCounterValue = new ProfilerCounterValue(ProfilerCategory.Network, ProfilerConstants.NumberOfRPCsInQueueSize, ProfilerMarkerDataUnit.Count, ProfilerCounterOptions.FlushOnEndOfFrame); - private static ProfilerCounterValue s_RPCsOutQueueSizeCounterValue = + private static readonly ProfilerCounterValue k_RPCsOutQueueSizeCounterValue = new ProfilerCounterValue(ProfilerCategory.Network, ProfilerConstants.NumberOfRPCsOutQueueSize, ProfilerMarkerDataUnit.Count, ProfilerCounterOptions.FlushOnEndOfFrame); [RuntimeInitializeOnLoadMethod] - static void RegisterMLAPIPerformanceEvent() + private static void RegisterMLAPIPerformanceEvent() { NetworkManager.OnPerformanceDataEvent += OnPerformanceTickData; } - static void OnPerformanceTickData(PerformanceTickData tickData) + private static void OnPerformanceTickData(PerformanceTickData tickData) { - //Operations - s_ConnectionsCounterValue.Value += tickData.GetData(ProfilerConstants.NumberOfConnections); - s_TickRateCounterValue.Value += tickData.GetData(ProfilerConstants.ReceiveTickRate); - - //Messages - s_NamedMessagesCounterValue.Value += tickData.GetData(ProfilerConstants.NumberOfNamedMessages); - s_UnnamedMessagesCounterValue.Value += tickData.GetData(ProfilerConstants.NumberOfUnnamedMessages); - s_BytesSentCounterValue.Value += tickData.GetData(ProfilerConstants.NumberBytesSent); - s_BytesReceivedCounterValue.Value += tickData.GetData(ProfilerConstants.NumberBytesReceived); - s_NetworkVarsCounterValue.Value += tickData.GetData(ProfilerConstants.NumberNetworkVarsReceived); - - //RPCs - s_RPCsSentCounterValue.Value += tickData.GetData(ProfilerConstants.NumberOfRPCsSent); - s_RPCsReceivedCounterValue.Value += tickData.GetData(ProfilerConstants.NumberOfRPCsReceived); - s_RPCBatchesSentCounterValue.Value += tickData.GetData(ProfilerConstants.NumberOfRPCBatchesSent); - s_RPCBatchesReceivedCounterValue.Value += tickData.GetData(ProfilerConstants.NumberOfRPCBatchesReceived); - s_RPCBatchesReceivedCounterValue.Value += tickData.GetData(ProfilerConstants.NumberOfRPCBatchesReceived); - s_RPCQueueProcessedCounterValue.Value += tickData.GetData(ProfilerConstants.NumberOfRPCQueueProcessed); - s_RPCsInQueueSizeCounterValue.Value += tickData.GetData(ProfilerConstants.NumberOfRPCsInQueueSize); - s_RPCsOutQueueSizeCounterValue.Value += tickData.GetData(ProfilerConstants.NumberOfRPCsOutQueueSize); + // Operations + k_ConnectionsCounterValue.Value += tickData.GetData(ProfilerConstants.NumberOfConnections); + k_TickRateCounterValue.Value += tickData.GetData(ProfilerConstants.ReceiveTickRate); + + // Messages + k_NamedMessagesCounterValue.Value += tickData.GetData(ProfilerConstants.NumberOfNamedMessages); + k_UnnamedMessagesCounterValue.Value += tickData.GetData(ProfilerConstants.NumberOfUnnamedMessages); + k_BytesSentCounterValue.Value += tickData.GetData(ProfilerConstants.NumberBytesSent); + k_BytesReceivedCounterValue.Value += tickData.GetData(ProfilerConstants.NumberBytesReceived); + k_NetworkVarsCounterValue.Value += tickData.GetData(ProfilerConstants.NumberNetworkVarsReceived); + + // RPCs + k_RPCsSentCounterValue.Value += tickData.GetData(ProfilerConstants.NumberOfRPCsSent); + k_RPCsReceivedCounterValue.Value += tickData.GetData(ProfilerConstants.NumberOfRPCsReceived); + k_RPCBatchesSentCounterValue.Value += tickData.GetData(ProfilerConstants.NumberOfRPCBatchesSent); + k_RPCBatchesReceivedCounterValue.Value += tickData.GetData(ProfilerConstants.NumberOfRPCBatchesReceived); + k_RPCBatchesReceivedCounterValue.Value += tickData.GetData(ProfilerConstants.NumberOfRPCBatchesReceived); + k_RPCQueueProcessedCounterValue.Value += tickData.GetData(ProfilerConstants.NumberOfRPCQueueProcessed); + k_RPCsInQueueSizeCounterValue.Value += tickData.GetData(ProfilerConstants.NumberOfRPCsInQueueSize); + k_RPCsOutQueueSizeCounterValue.Value += tickData.GetData(ProfilerConstants.NumberOfRPCsOutQueueSize); } #endif } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilerStat.cs b/com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilerStat.cs index 75ab44e6a5..879510de10 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilerStat.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilerStat.cs @@ -1,104 +1,107 @@ -using System; using System.Collections.Generic; using UnityEngine; -using static System.DateTime; namespace MLAPI.Profiling { - public struct Sample - { - public int count; - public float t_recorded; - } - - public class ProfilerStat - { - public ProfilerStat(string name) - { - prettyPrintName = name; - ProfilerStatManager.Add(this); - } - - public string prettyPrintName; - protected int maxSamples = 10; - - protected LinkedList data = new LinkedList(); - - private bool dirty = true; - - protected float lastCount; - protected float lastT; - - public virtual void Record(int amt = 1) - { - dirty = true; - var t_now = Time.time; - // 'Record' can get called many times in the same frame (for the same exact timestamp) - // This not only blows out the samples but makes the rate computation break since we - // have n samples with a time delta of zero. - // - // Instead, if we want to record a value at the same exact time as our last - // sample, just adjust that sample - if (data.First != null && data.First.Value.t_recorded == t_now) - { - data.First.Value = new Sample() {count = data.First.Value.count + amt, - t_recorded = data.First.Value.t_recorded}; - } - else - { - data.AddFirst(new Sample() {count = amt, t_recorded = Time.time}); - while (data.Count > maxSamples) - { - data.RemoveLast(); - } - } - } - - public virtual float SampleRate() - { - if (dirty) - { - LinkedListNode node = data.First; - lastCount = 0; - lastT = (data.Last != null) ? data.Last.Value.t_recorded : 0.0f; - - while (node != null) - { - lastCount += node.Value.count; - node = node.Next; - } - dirty = false; - } - - float delta = Time.time - lastT; - if (delta == 0.0f) - { - return 0.0f; - } - - return lastCount / delta; - } + public struct Sample + { + public int Count; + public float TimeRecorded; + } + + public class ProfilerStat + { + public ProfilerStat(string name) + { + PrettyPrintName = name; + ProfilerStatManager.Add(this); + } + + public string PrettyPrintName; + protected int MaxSamples = 10; + + protected LinkedList Data = new LinkedList(); + + private bool m_IsDirty = true; + + protected float LastCount; + protected float LastTime; + + public virtual void Record(int amt = 1) + { + m_IsDirty = true; + var t_now = Time.time; + // 'Record' can get called many times in the same frame (for the same exact timestamp) + // This not only blows out the samples but makes the rate computation break since we + // have n samples with a time delta of zero. + // + // Instead, if we want to record a value at the same exact time as our last + // sample, just adjust that sample + if (Data.First != null && Data.First.Value.TimeRecorded == t_now) + { + Data.First.Value = new Sample() + { + Count = Data.First.Value.Count + amt, + TimeRecorded = Data.First.Value.TimeRecorded + }; + } + else + { + Data.AddFirst(new Sample() { Count = amt, TimeRecorded = Time.time }); + while (Data.Count > MaxSamples) + { + Data.RemoveLast(); + } + } + } + + public virtual float SampleRate() + { + if (m_IsDirty) + { + LinkedListNode node = Data.First; + LastCount = 0; + LastTime = Data.Last?.Value.TimeRecorded ?? 0.0f; + + while (node != null) + { + LastCount += node.Value.Count; + node = node.Next; + } + + m_IsDirty = false; + } + + float delta = Time.time - LastTime; + if (delta == 0.0f) + { + return 0.0f; + } + + return LastCount / delta; + } } public class ProfilerIncStat : ProfilerStat { public ProfilerIncStat(string name) : base(name) { } - private float internalValue = 0f; + private float m_InternalValue = 0f; public override void Record(int amt = 1) { - data.AddFirst(new Sample() { count = amt, t_recorded = Time.time }); - while (data.Count > maxSamples) { - data.RemoveLast(); + Data.AddFirst(new Sample() { Count = amt, TimeRecorded = Time.time }); + while (Data.Count > MaxSamples) + { + Data.RemoveLast(); } - internalValue += amt; + m_InternalValue += amt; } public override float SampleRate() { - return internalValue; + return m_InternalValue; } } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilerStatManager.cs b/com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilerStatManager.cs index 047e6d0757..1f83e5a96c 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilerStatManager.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilerStatManager.cs @@ -4,28 +4,29 @@ namespace MLAPI.Profiling { public static class ProfilerStatManager { - public static List allStats = new List(); - public static ProfilerIncStat connections = new ProfilerIncStat("Connections"); - public static ProfilerStat bytesRcvd = new ProfilerStat("Bytes Rcvd"); - public static ProfilerStat bytesSent = new ProfilerStat("Bytes Sent"); - public static ProfilerStat rcvTickRate = new ProfilerStat("Rcv Tick Rate"); - public static ProfilerStat networkVarsRcvd = new ProfilerStat("Network Vars Rcvd"); - public static ProfilerStat namedMessage = new ProfilerStat("Named Message"); - public static ProfilerStat unnamedMessage = new ProfilerStat("UnNamed Message"); + public static List AllStats = new List(); - public static ProfilerStat rpcsRcvd = new ProfilerStat("RPCs Rcvd"); - public static ProfilerStat rpcsSent = new ProfilerStat("RPCs Sent"); - public static ProfilerStat rpcBatchesRcvd = new ProfilerStat("RPC Batches Rcvd"); - public static ProfilerStat rpcBatchesSent = new ProfilerStat("RPC Batches Sent"); - public static ProfilerStat rpcsQueueProc = new ProfilerStat("RPCS-Processed"); - public static ProfilerStat rpcInQueueSize = new ProfilerStat("InQFrameSize"); - public static ProfilerStat rpcOutQueueSize = new ProfilerStat("OutQFrameSize"); - public static ProfilerIncStat NetTranforms = new ProfilerIncStat("NetTransforms"); + public static readonly ProfilerIncStat Connections = new ProfilerIncStat("Connections"); + public static readonly ProfilerStat BytesRcvd = new ProfilerStat("Bytes Rcvd"); + public static readonly ProfilerStat BytesSent = new ProfilerStat("Bytes Sent"); + public static readonly ProfilerStat RcvTickRate = new ProfilerStat("Rcv Tick Rate"); + public static readonly ProfilerStat NetworkVarsRcvd = new ProfilerStat("Network Vars Rcvd"); + public static readonly ProfilerStat NamedMessage = new ProfilerStat("Named Message"); + public static readonly ProfilerStat UnnamedMessage = new ProfilerStat("UnNamed Message"); + + public static readonly ProfilerStat RpcsRcvd = new ProfilerStat("RPCs Rcvd"); + public static readonly ProfilerStat RpcsSent = new ProfilerStat("RPCs Sent"); + public static readonly ProfilerStat RpcBatchesRcvd = new ProfilerStat("RPC Batches Rcvd"); + public static readonly ProfilerStat RpcBatchesSent = new ProfilerStat("RPC Batches Sent"); + public static readonly ProfilerStat RpcsQueueProc = new ProfilerStat("RPCS-Processed"); + public static readonly ProfilerStat RpcInQueueSize = new ProfilerStat("InQFrameSize"); + public static readonly ProfilerStat RpcOutQueueSize = new ProfilerStat("OutQFrameSize"); + public static readonly ProfilerIncStat NetTranforms = new ProfilerIncStat("NetTransforms"); public static void Add(ProfilerStat s) { - allStats.Add(s); + AllStats.Add(s); } } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilerTickData.cs b/com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilerTickData.cs index 37975dd18c..1433e17e6f 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilerTickData.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilerTickData.cs @@ -4,24 +4,27 @@ namespace MLAPI.Profiling { - /// - /// The type of Tick - /// - public enum TickType + /// + /// The type of Tick + /// + public enum TickType { /// /// Event tick. During EventTick NetworkVars are flushed etc /// Event, + /// /// Receive tick. During ReceiveTick data is received from the transport /// Receive, + /// /// Send tick. During Send data is sent from Transport queue /// Send } + /// /// A tick in used for the Profiler /// @@ -31,14 +34,14 @@ public class ProfilerTick /// The events that occured during this tick /// public readonly List Events = new List(); - + /// /// Writes the current ProfilerTick to the stream /// /// The stream containing - public void SerializeToStream(Stream stream) - { - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(stream)) + public void SerializeToStream(Stream stream) + { + using (var writer = PooledNetworkWriter.Get(stream)) { writer.WriteUInt16Packed((ushort)Events.Count); @@ -47,18 +50,18 @@ public void SerializeToStream(Stream stream) Events[i].SerializeToStream(stream); } } - } + } /// /// Creates a ProfilerTick from data in the provided stream /// /// The stream containing the ProfilerTick data /// The ProfilerTick with data read from the stream - public static ProfilerTick FromStream(Stream stream) - { - ProfilerTick tick = new ProfilerTick(); + public static ProfilerTick FromStream(Stream stream) + { + var tick = new ProfilerTick(); - using (PooledNetworkReader reader = PooledNetworkReader.Get(stream)) + using (var reader = PooledNetworkReader.Get(stream)) { ushort count = reader.ReadUInt16Packed(); for (int i = 0; i < count; i++) @@ -68,9 +71,9 @@ public static ProfilerTick FromStream(Stream stream) return tick; } - } + } - internal void EndEvent() + internal void EndEvent() { for (int i = Events.Count - 1; i >= 0; i--) { @@ -84,7 +87,7 @@ internal void EndEvent() internal void StartEvent(TickType type, uint bytes, string channelName, string messageType) { - TickEvent tickEvent = new TickEvent() + var tickEvent = new TickEvent() { Bytes = bytes, ChannelName = string.IsNullOrEmpty(channelName) ? "NONE" : channelName, @@ -99,14 +102,17 @@ internal void StartEvent(TickType type, uint bytes, string channelName, string m /// The type of tick /// public TickType Type; + /// /// The frame the tick executed on /// public int Frame; + /// /// The id of the tick /// public int EventId; + /// /// The amount of bytes that were sent and / or received during this tick /// @@ -115,7 +121,11 @@ public uint Bytes get { uint bytes = 0; - for (int i = 0; i < Events.Count; i++) bytes += Events[i].Bytes; + for (int i = 0; i < Events.Count; i++) + { + bytes += Events[i].Bytes; + } + return bytes; } } @@ -130,18 +140,22 @@ public class TickEvent /// The type of evenmt /// public TickType EventType; + /// /// The amount of bytes sent or received /// public uint Bytes; + /// /// The name of the channel /// public string ChannelName; + /// /// The message type /// public string MessageType; + /// /// Whether or not the event is closed /// @@ -152,8 +166,8 @@ public class TickEvent /// /// The stream to write the TickEvent data to public void SerializeToStream(Stream stream) - { - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(stream)) + { + using (var writer = PooledNetworkWriter.Get(stream)) { writer.WriteByte((byte)EventType); writer.WriteUInt32Packed(Bytes); @@ -161,7 +175,7 @@ public void SerializeToStream(Stream stream) writer.WriteStringPacked(MessageType); writer.WriteBool(Closed); } - } + } /// /// Creates a TickEvent from data in the provided stream @@ -169,19 +183,20 @@ public void SerializeToStream(Stream stream) /// The stream containing the TickEvent data /// The TickEvent with data read from the stream public static TickEvent FromStream(Stream stream) - { - using (PooledNetworkReader reader = PooledNetworkReader.Get(stream)) + { + using (var reader = PooledNetworkReader.Get(stream)) { - TickEvent @event = new TickEvent + var tickEvent = new TickEvent { EventType = (TickType)reader.ReadByte(), Bytes = reader.ReadUInt32Packed(), - ChannelName = reader.ReadStringPacked().ToString(), - MessageType = reader.ReadStringPacked().ToString(), + ChannelName = reader.ReadStringPacked(), + MessageType = reader.ReadStringPacked(), Closed = reader.ReadBool() }; - return @event; + + return tickEvent; } } } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilingDataStore.cs b/com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilingDataStore.cs index f38532046b..5c18c842e8 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilingDataStore.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilingDataStore.cs @@ -1,11 +1,10 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; namespace MLAPI.Profiling { public class ProfilingDataStore { - readonly Dictionary m_Dictionary = new Dictionary(); + private readonly Dictionary m_Dictionary = new Dictionary(); public void Add(string fieldName, int value) { @@ -37,4 +36,4 @@ public IReadOnlyDictionary GetReadonly() return m_Dictionary; } } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Properties.meta b/com.unity.multiplayer.mlapi/Runtime/Properties.meta deleted file mode 100644 index 8708568f7c..0000000000 --- a/com.unity.multiplayer.mlapi/Runtime/Properties.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 702abb07d8bfb534997c514c3ed50212 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.multiplayer.mlapi/Runtime/Reflection/TypeExtensions.cs b/com.unity.multiplayer.mlapi/Runtime/Reflection/TypeExtensions.cs index c0fd9b2737..0221fd3c9d 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Reflection/TypeExtensions.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Reflection/TypeExtensions.cs @@ -6,20 +6,19 @@ internal static class TypeExtensions { internal static bool HasInterface(this Type type, Type interfaceType) { - Type[] interfaces = type.GetInterfaces(); - for (int i = 0; i < interfaces.Length; i++) + var ifaces = type.GetInterfaces(); + for (int i = 0; i < ifaces.Length; i++) { - if (interfaces[i] == interfaceType) - return true; + if (ifaces[i] == interfaceType) return true; } + return false; } - + internal static bool IsNullable(this Type type) { if (!type.IsValueType) return true; // ref-type - if (Nullable.GetUnderlyingType(type) != null) return true; // Nullable - return false; // value-type + return Nullable.GetUnderlyingType(type) != null; } } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/SceneManagement/NetworkSceneManager.cs b/com.unity.multiplayer.mlapi/Runtime/SceneManagement/NetworkSceneManager.cs index 8c9654d3ec..36825f57d6 100644 --- a/com.unity.multiplayer.mlapi/Runtime/SceneManagement/NetworkSceneManager.cs +++ b/com.unity.multiplayer.mlapi/Runtime/SceneManagement/NetworkSceneManager.cs @@ -23,39 +23,48 @@ public static class NetworkSceneManager /// Delegate for when the scene has been switched /// public delegate void SceneSwitchedDelegate(); + /// /// Delegate for when a scene switch has been initiated /// public delegate void SceneSwitchStartedDelegate(AsyncOperation operation); + /// /// Event that is invoked when the scene is switched /// public static event SceneSwitchedDelegate OnSceneSwitched; + /// /// Event that is invoked when a local scene switch has started /// public static event SceneSwitchStartedDelegate OnSceneSwitchStarted; - internal static readonly HashSet registeredSceneNames = new HashSet(); - internal static readonly Dictionary sceneNameToIndex = new Dictionary(); - internal static readonly Dictionary sceneIndexToString = new Dictionary(); - internal static readonly Dictionary sceneSwitchProgresses = new Dictionary(); - private static Scene lastScene; - private static string nextSceneName; - private static bool isSwitching = false; - internal static uint currentSceneIndex = 0; - internal static Guid currentSceneSwitchProgressGuid = new Guid(); - internal static bool isSpawnedObjectsPendingInDontDestroyOnLoad = false; + internal static readonly HashSet RegisteredSceneNames = new HashSet(); + internal static readonly Dictionary SceneNameToIndex = new Dictionary(); + internal static readonly Dictionary SceneIndexToString = new Dictionary(); + internal static readonly Dictionary SceneSwitchProgresses = new Dictionary(); + + private static Scene s_LastScene; + private static string s_NextSceneName; + private static bool s_IsSwitching = false; + internal static uint CurrentSceneIndex = 0; + internal static Guid CurrentSceneSwitchProgressGuid = new Guid(); + internal static bool IsSpawnedObjectsPendingInDontDestroyOnLoad = false; internal static void SetCurrentSceneIndex() { - if (!sceneNameToIndex.ContainsKey(SceneManager.GetActiveScene().name)) + if (!SceneNameToIndex.ContainsKey(SceneManager.GetActiveScene().name)) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("The current scene (" + SceneManager.GetActiveScene().name + ") is not regisered as a network scene."); + if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarning($"The current scene ({SceneManager.GetActiveScene().name}) is not regisered as a network scene."); + } + return; } - currentSceneIndex = sceneNameToIndex[SceneManager.GetActiveScene().name]; - CurrentActiveSceneIndex = currentSceneIndex; + + CurrentSceneIndex = SceneNameToIndex[SceneManager.GetActiveScene().name]; + CurrentActiveSceneIndex = CurrentSceneIndex; } internal static uint CurrentActiveSceneIndex { get; private set; } = 0; @@ -70,12 +79,12 @@ public static void AddRuntimeSceneName(string sceneName, uint index) { if (!NetworkManager.Singleton.NetworkConfig.AllowRuntimeSceneChanges) { - throw new NetworkConfigurationException("Cannot change the scene configuration when AllowRuntimeSceneChanges is false"); + throw new NetworkConfigurationException($"Cannot change the scene configuration when {nameof(NetworkConfig.AllowRuntimeSceneChanges)} is false"); } - registeredSceneNames.Add(sceneName); - sceneIndexToString.Add(index, sceneName); - sceneNameToIndex.Add(sceneName, index); + RegisteredSceneNames.Add(sceneName); + SceneIndexToString.Add(index, sceneName); + SceneNameToIndex.Add(sceneName, index); } /// @@ -88,43 +97,48 @@ public static SceneSwitchProgress SwitchScene(string sceneName) { throw new NotServerException("Only server can start a scene switch"); } - else if (isSwitching) + + if (s_IsSwitching) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("Scene switch already in progress"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarning("Scene switch already in progress"); + } + return null; } - else if (!registeredSceneNames.Contains(sceneName)) + + if (!RegisteredSceneNames.Contains(sceneName)) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("The scene " + sceneName + " is not registered as a switchable scene."); + if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarning($"The scene {sceneName} is not registered as a switchable scene."); + } + return null; } NetworkSpawnManager.ServerDestroySpawnedSceneObjects(); //Destroy current scene objects before switching. - isSwitching = true; - lastScene = SceneManager.GetActiveScene(); + s_IsSwitching = true; + s_LastScene = SceneManager.GetActiveScene(); - SceneSwitchProgress switchSceneProgress = new SceneSwitchProgress(); - sceneSwitchProgresses.Add(switchSceneProgress.guid, switchSceneProgress); - currentSceneSwitchProgressGuid = switchSceneProgress.guid; + var switchSceneProgress = new SceneSwitchProgress(); + SceneSwitchProgresses.Add(switchSceneProgress.Guid, switchSceneProgress); + CurrentSceneSwitchProgressGuid = switchSceneProgress.Guid; // Move ALL NetworkObjects to the temp scene MoveObjectsToDontDestroyOnLoad(); - isSpawnedObjectsPendingInDontDestroyOnLoad = true; + IsSpawnedObjectsPendingInDontDestroyOnLoad = true; // Switch scene AsyncOperation sceneLoad = SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Single); - nextSceneName = sceneName; - - sceneLoad.completed += (AsyncOperation asyncOp2) => { OnSceneLoaded(switchSceneProgress.guid, null); }; + s_NextSceneName = sceneName; + sceneLoad.completed += (AsyncOperation asyncOp2) => { OnSceneLoaded(switchSceneProgress.Guid, null); }; switchSceneProgress.SetSceneLoadOperation(sceneLoad); - - if (OnSceneSwitchStarted != null) - { - OnSceneSwitchStarted(sceneLoad); - } + OnSceneSwitchStarted?.Invoke(sceneLoad); return switchSceneProgress; } @@ -132,80 +146,80 @@ public static SceneSwitchProgress SwitchScene(string sceneName) // Called on client internal static void OnSceneSwitch(uint sceneIndex, Guid switchSceneGuid, Stream objectStream) { - if (!sceneIndexToString.ContainsKey(sceneIndex) || !registeredSceneNames.Contains(sceneIndexToString[sceneIndex])) + if (!SceneIndexToString.ContainsKey(sceneIndex) || !RegisteredSceneNames.Contains(SceneIndexToString[sceneIndex])) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("Server requested a scene switch to a non registered scene"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarning("Server requested a scene switch to a non-registered scene"); + } + return; } - lastScene = SceneManager.GetActiveScene(); + s_LastScene = SceneManager.GetActiveScene(); // Move ALL NetworkObjects to the temp scene MoveObjectsToDontDestroyOnLoad(); - isSpawnedObjectsPendingInDontDestroyOnLoad = true; - - string sceneName = sceneIndexToString[sceneIndex]; + IsSpawnedObjectsPendingInDontDestroyOnLoad = true; - AsyncOperation sceneLoad = SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Single); + string sceneName = SceneIndexToString[sceneIndex]; - nextSceneName = sceneName; + var sceneLoad = SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Single); - sceneLoad.completed += (AsyncOperation asyncOp2) => - { - OnSceneLoaded(switchSceneGuid, objectStream); - }; + s_NextSceneName = sceneName; - if (OnSceneSwitchStarted != null) - { - OnSceneSwitchStarted(sceneLoad); - } + sceneLoad.completed += asyncOp2 => OnSceneLoaded(switchSceneGuid, objectStream); + OnSceneSwitchStarted?.Invoke(sceneLoad); } internal static void OnFirstSceneSwitchSync(uint sceneIndex, Guid switchSceneGuid) { - if (!sceneIndexToString.ContainsKey(sceneIndex) || !registeredSceneNames.Contains(sceneIndexToString[sceneIndex])) + if (!SceneIndexToString.ContainsKey(sceneIndex) || !RegisteredSceneNames.Contains(SceneIndexToString[sceneIndex])) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("Server requested a scene switch to a non registered scene"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarning("Server requested a scene switch to a non-registered scene"); + } + return; } - else if (SceneManager.GetActiveScene().name == sceneIndexToString[sceneIndex]) + + if (SceneManager.GetActiveScene().name == SceneIndexToString[sceneIndex]) { return; //This scene is already loaded. This usually happends at first load } - lastScene = SceneManager.GetActiveScene(); - string sceneName = sceneIndexToString[sceneIndex]; - nextSceneName = sceneName; - CurrentActiveSceneIndex = sceneNameToIndex[sceneName]; + s_LastScene = SceneManager.GetActiveScene(); + string sceneName = SceneIndexToString[sceneIndex]; + s_NextSceneName = sceneName; + CurrentActiveSceneIndex = SceneNameToIndex[sceneName]; - isSpawnedObjectsPendingInDontDestroyOnLoad = true; + IsSpawnedObjectsPendingInDontDestroyOnLoad = true; SceneManager.LoadScene(sceneName); - using (PooledNetworkBuffer buffer = PooledNetworkBuffer.Get()) + using (var buffer = PooledNetworkBuffer.Get()) + using (var writer = PooledNetworkWriter.Get(buffer)) { - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(buffer)) - { - writer.WriteByteArray(switchSceneGuid.ToByteArray()); - InternalMessageSender.Send(NetworkManager.Singleton.ServerClientId, NetworkConstants.CLIENT_SWITCH_SCENE_COMPLETED, NetworkChannel.Internal, buffer); - } + writer.WriteByteArray(switchSceneGuid.ToByteArray()); + InternalMessageSender.Send(NetworkManager.Singleton.ServerClientId, NetworkConstants.CLIENT_SWITCH_SCENE_COMPLETED, NetworkChannel.Internal, buffer); } - isSwitching = false; + s_IsSwitching = false; } private static void OnSceneLoaded(Guid switchSceneGuid, Stream objectStream) { - CurrentActiveSceneIndex = sceneNameToIndex[nextSceneName]; - Scene nextScene = SceneManager.GetSceneByName(nextSceneName); + CurrentActiveSceneIndex = SceneNameToIndex[s_NextSceneName]; + var nextScene = SceneManager.GetSceneByName(s_NextSceneName); SceneManager.SetActiveScene(nextScene); // Move all objects to the new scene MoveObjectsToScene(nextScene); - isSpawnedObjectsPendingInDontDestroyOnLoad = false; + IsSpawnedObjectsPendingInDontDestroyOnLoad = false; - currentSceneIndex = CurrentActiveSceneIndex; + CurrentSceneIndex = CurrentActiveSceneIndex; if (NetworkManager.Singleton.IsServer) { @@ -237,68 +251,68 @@ private static void OnSceneUnloadServer(Guid switchSceneGuid) { if (NetworkManager.Singleton.ConnectedClientsList[j].ClientId != NetworkManager.Singleton.ServerClientId) { - using (PooledNetworkBuffer buffer = PooledNetworkBuffer.Get()) + using (var buffer = PooledNetworkBuffer.Get()) + using (var writer = PooledNetworkWriter.Get(buffer)) { - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(buffer)) - { - writer.WriteUInt32Packed(CurrentActiveSceneIndex); - writer.WriteByteArray(switchSceneGuid.ToByteArray()); + writer.WriteUInt32Packed(CurrentActiveSceneIndex); + writer.WriteByteArray(switchSceneGuid.ToByteArray()); - uint sceneObjectsToSpawn = 0; - for (int i = 0; i < newSceneObjects.Count; i++) + uint sceneObjectsToSpawn = 0; + for (int i = 0; i < newSceneObjects.Count; i++) + { + if (newSceneObjects[i].m_Observers.Contains(NetworkManager.Singleton.ConnectedClientsList[j].ClientId)) { - if (newSceneObjects[i].observers.Contains(NetworkManager.Singleton.ConnectedClientsList[j].ClientId)) - sceneObjectsToSpawn++; + sceneObjectsToSpawn++; } + } - writer.WriteUInt32Packed(sceneObjectsToSpawn); + writer.WriteUInt32Packed(sceneObjectsToSpawn); - for (int i = 0; i < newSceneObjects.Count; i++) + for (int i = 0; i < newSceneObjects.Count; i++) + { + if (newSceneObjects[i].m_Observers.Contains(NetworkManager.Singleton.ConnectedClientsList[j].ClientId)) { - if (newSceneObjects[i].observers.Contains(NetworkManager.Singleton.ConnectedClientsList[j].ClientId)) + writer.WriteBool(newSceneObjects[i].IsPlayerObject); + writer.WriteUInt64Packed(newSceneObjects[i].NetworkObjectId); + writer.WriteUInt64Packed(newSceneObjects[i].OwnerClientId); + + NetworkObject parentNetworkObject = null; + + if (!newSceneObjects[i].AlwaysReplicateAsRoot && newSceneObjects[i].transform.parent != null) + { + parentNetworkObject = newSceneObjects[i].transform.parent.GetComponent(); + } + + if (parentNetworkObject == null) + { + writer.WriteBool(false); + } + else + { + writer.WriteBool(true); + writer.WriteUInt64Packed(parentNetworkObject.NetworkObjectId); + } + + if (!NetworkManager.Singleton.NetworkConfig.EnableSceneManagement || NetworkManager.Singleton.NetworkConfig.UsePrefabSync) + { + writer.WriteUInt64Packed(newSceneObjects[i].PrefabHash); + + writer.WriteSinglePacked(newSceneObjects[i].transform.position.x); + writer.WriteSinglePacked(newSceneObjects[i].transform.position.y); + writer.WriteSinglePacked(newSceneObjects[i].transform.position.z); + + writer.WriteSinglePacked(newSceneObjects[i].transform.rotation.eulerAngles.x); + writer.WriteSinglePacked(newSceneObjects[i].transform.rotation.eulerAngles.y); + writer.WriteSinglePacked(newSceneObjects[i].transform.rotation.eulerAngles.z); + } + else { - writer.WriteBool(newSceneObjects[i].IsPlayerObject); - writer.WriteUInt64Packed(newSceneObjects[i].NetworkObjectId); - writer.WriteUInt64Packed(newSceneObjects[i].OwnerClientId); - - NetworkObject parent = null; - - if (!newSceneObjects[i].AlwaysReplicateAsRoot && newSceneObjects[i].transform.parent != null) - { - parent = newSceneObjects[i].transform.parent.GetComponent(); - } - - if (parent == null) - { - writer.WriteBool(false); - } - else - { - writer.WriteBool(true); - writer.WriteUInt64Packed(parent.NetworkObjectId); - } - - if (!NetworkManager.Singleton.NetworkConfig.EnableSceneManagement || NetworkManager.Singleton.NetworkConfig.UsePrefabSync) - { - writer.WriteUInt64Packed(newSceneObjects[i].PrefabHash); - - writer.WriteSinglePacked(newSceneObjects[i].transform.position.x); - writer.WriteSinglePacked(newSceneObjects[i].transform.position.y); - writer.WriteSinglePacked(newSceneObjects[i].transform.position.z); - - writer.WriteSinglePacked(newSceneObjects[i].transform.rotation.eulerAngles.x); - writer.WriteSinglePacked(newSceneObjects[i].transform.rotation.eulerAngles.y); - writer.WriteSinglePacked(newSceneObjects[i].transform.rotation.eulerAngles.z); - } - else - { - writer.WriteUInt64Packed(newSceneObjects[i].NetworkInstanceId); - } - - if (NetworkManager.Singleton.NetworkConfig.EnableNetworkVariable) - { - newSceneObjects[i].WriteNetworkVariableData(buffer, NetworkManager.Singleton.ConnectedClientsList[j].ClientId); - } + writer.WriteUInt64Packed(newSceneObjects[i].NetworkInstanceId); + } + + if (NetworkManager.Singleton.NetworkConfig.EnableNetworkVariable) + { + newSceneObjects[i].WriteNetworkVariableData(buffer, NetworkManager.Singleton.ConnectedClientsList[j].ClientId); } } } @@ -314,12 +328,9 @@ private static void OnSceneUnloadServer(Guid switchSceneGuid) OnClientSwitchSceneCompleted(NetworkManager.Singleton.LocalClientId, switchSceneGuid); } - isSwitching = false; + s_IsSwitching = false; - if (OnSceneSwitched != null) - { - OnSceneSwitched(); - } + OnSceneSwitched?.Invoke(); } private static void OnSceneUnloadClient(Guid switchSceneGuid, Stream objectStream) @@ -328,7 +339,7 @@ private static void OnSceneUnloadClient(Guid switchSceneGuid, Stream objectStrea { NetworkSpawnManager.DestroySceneObjects(); - using (PooledNetworkReader reader = PooledNetworkReader.Get(objectStream)) + using (var reader = PooledNetworkReader.Get(objectStream)) { uint newObjectsCount = reader.ReadUInt32Packed(); @@ -355,10 +366,10 @@ private static void OnSceneUnloadClient(Guid switchSceneGuid, Stream objectStrea rotation = Quaternion.Euler(reader.ReadSinglePacked(), reader.ReadSinglePacked(), reader.ReadSinglePacked()); } - NetworkObject networkObject = NetworkSpawnManager.CreateLocalNetworkObject(false, 0, prefabHash, parentNetworkId, position, rotation); + var networkObject = NetworkSpawnManager.CreateLocalNetworkObject(false, 0, prefabHash, parentNetworkId, position, rotation); NetworkSpawnManager.SpawnNetworkObjectLocally(networkObject, networkId, true, isPlayerObject, owner, objectStream, false, 0, true, false); - Queue bufferQueue = BufferManager.ConsumeBuffersForNetworkId(networkId); + var bufferQueue = BufferManager.ConsumeBuffersForNetworkId(networkId); // Apply buffered messages if (bufferQueue != null) @@ -366,9 +377,7 @@ private static void OnSceneUnloadClient(Guid switchSceneGuid, Stream objectStrea while (bufferQueue.Count > 0) { BufferManager.BufferedMessage message = bufferQueue.Dequeue(); - - NetworkManager.Singleton.HandleIncomingData(message.sender, message.networkChannel, new ArraySegment(message.payload.GetBuffer(), (int)message.payload.Position, (int)message.payload.Length), message.receiveTime, false); - + NetworkManager.Singleton.HandleIncomingData(message.SenderClientId, message.NetworkChannel, new ArraySegment(message.NetworkBuffer.GetBuffer(), (int)message.NetworkBuffer.Position, (int)message.NetworkBuffer.Length), message.ReceiveTime, false); BufferManager.RecycleConsumedBufferedMessage(message); } } @@ -380,7 +389,7 @@ private static void OnSceneUnloadClient(Guid switchSceneGuid, Stream objectStrea var networkObjects = MonoBehaviour.FindObjectsOfType(); NetworkSpawnManager.ClientCollectSoftSyncSceneObjectSweep(networkObjects); - using (PooledNetworkReader reader = PooledNetworkReader.Get(objectStream)) + using (var reader = PooledNetworkReader.Get(objectStream)) { uint newObjectsCount = reader.ReadUInt32Packed(); @@ -399,10 +408,10 @@ private static void OnSceneUnloadClient(Guid switchSceneGuid, Stream objectStrea ulong instanceId = reader.ReadUInt64Packed(); - NetworkObject networkObject = NetworkSpawnManager.CreateLocalNetworkObject(true, instanceId, 0, parentNetworkId, null, null); + var networkObject = NetworkSpawnManager.CreateLocalNetworkObject(true, instanceId, 0, parentNetworkId, null, null); NetworkSpawnManager.SpawnNetworkObjectLocally(networkObject, networkId, true, isPlayerObject, owner, objectStream, false, 0, true, false); - Queue bufferQueue = BufferManager.ConsumeBuffersForNetworkId(networkId); + var bufferQueue = BufferManager.ConsumeBuffersForNetworkId(networkId); // Apply buffered messages if (bufferQueue != null) @@ -410,9 +419,7 @@ private static void OnSceneUnloadClient(Guid switchSceneGuid, Stream objectStrea while (bufferQueue.Count > 0) { BufferManager.BufferedMessage message = bufferQueue.Dequeue(); - - NetworkManager.Singleton.HandleIncomingData(message.sender, message.networkChannel, new ArraySegment(message.payload.GetBuffer(), (int)message.payload.Position, (int)message.payload.Length), message.receiveTime, false); - + NetworkManager.Singleton.HandleIncomingData(message.SenderClientId, message.NetworkChannel, new ArraySegment(message.NetworkBuffer.GetBuffer(), (int)message.NetworkBuffer.Position, (int)message.NetworkBuffer.Length), message.ReceiveTime, false); BufferManager.RecycleConsumedBufferedMessage(message); } } @@ -420,27 +427,19 @@ private static void OnSceneUnloadClient(Guid switchSceneGuid, Stream objectStrea } } - using (PooledNetworkBuffer buffer = PooledNetworkBuffer.Get()) + using (var buffer = PooledNetworkBuffer.Get()) + using (var writer = PooledNetworkWriter.Get(buffer)) { - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(buffer)) - { - writer.WriteByteArray(switchSceneGuid.ToByteArray()); - InternalMessageSender.Send(NetworkManager.Singleton.ServerClientId, NetworkConstants.CLIENT_SWITCH_SCENE_COMPLETED, NetworkChannel.Internal, buffer); - } + writer.WriteByteArray(switchSceneGuid.ToByteArray()); + InternalMessageSender.Send(NetworkManager.Singleton.ServerClientId, NetworkConstants.CLIENT_SWITCH_SCENE_COMPLETED, NetworkChannel.Internal, buffer); } - isSwitching = false; + s_IsSwitching = false; - if (OnSceneSwitched != null) - { - OnSceneSwitched(); - } + OnSceneSwitched?.Invoke(); } - internal static bool HasSceneMismatch(uint sceneIndex) - { - return SceneManager.GetActiveScene().name != sceneIndexToString[sceneIndex]; - } + internal static bool HasSceneMismatch(uint sceneIndex) => SceneManager.GetActiveScene().name != SceneIndexToString[sceneIndex]; // Called on server internal static void OnClientSwitchSceneCompleted(ulong clientId, Guid switchSceneGuid) @@ -450,18 +449,19 @@ internal static void OnClientSwitchSceneCompleted(ulong clientId, Guid switchSce //If Guid is empty it means the client has loaded the start scene of the server and the server would never have a switchSceneProgresses created for the start scene. return; } - if (!sceneSwitchProgresses.ContainsKey(switchSceneGuid)) + + if (!SceneSwitchProgresses.ContainsKey(switchSceneGuid)) { return; } - sceneSwitchProgresses[switchSceneGuid].AddClientAsDone(clientId); + SceneSwitchProgresses[switchSceneGuid].AddClientAsDone(clientId); } internal static void RemoveClientFromSceneSwitchProgresses(ulong clientId) { - foreach (SceneSwitchProgress switchSceneProgress in sceneSwitchProgresses.Values) + foreach (var switchSceneProgress in SceneSwitchProgresses.Values) { switchSceneProgress.RemoveClientAsDone(clientId); } @@ -470,7 +470,7 @@ internal static void RemoveClientFromSceneSwitchProgresses(ulong clientId) private static void MoveObjectsToDontDestroyOnLoad() { // Move ALL NetworkObjects to the temp scene - HashSet objectsToKeep = NetworkSpawnManager.SpawnedObjectsList; + var objectsToKeep = NetworkSpawnManager.SpawnedObjectsList; foreach (var sobj in objectsToKeep) { @@ -487,7 +487,7 @@ private static void MoveObjectsToDontDestroyOnLoad() private static void MoveObjectsToScene(Scene scene) { // Move ALL NetworkObjects to the temp scene - HashSet objectsToKeep = NetworkSpawnManager.SpawnedObjectsList; + var objectsToKeep = NetworkSpawnManager.SpawnedObjectsList; foreach (var sobj in objectsToKeep) { @@ -501,4 +501,4 @@ private static void MoveObjectsToScene(Scene scene) } } } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/SceneManagement/SceneSwitchProgress.cs b/com.unity.multiplayer.mlapi/Runtime/SceneManagement/SceneSwitchProgress.cs index 6fd56744b6..4438a84fd6 100644 --- a/com.unity.multiplayer.mlapi/Runtime/SceneManagement/SceneSwitchProgress.cs +++ b/com.unity.multiplayer.mlapi/Runtime/SceneManagement/SceneSwitchProgress.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.ComponentModel; using UnityEngine; using AsyncOperation = UnityEngine.AsyncOperation; @@ -51,21 +50,20 @@ public class SceneSwitchProgress /// public event OnClientLoadedSceneDelegate OnClientLoadedScene; - internal Guid guid { get; } = Guid.NewGuid(); + internal Guid Guid { get; } = Guid.NewGuid(); - private Coroutine timeOutCoroutine; - private AsyncOperation sceneLoadOperation; + private Coroutine m_TimeOutCoroutine; + private AsyncOperation m_SceneLoadOperation; internal SceneSwitchProgress() { - timeOutCoroutine = NetworkManager.Singleton.StartCoroutine(NetworkManager.Singleton.TimeOutSwitchSceneProgress(this)); + m_TimeOutCoroutine = NetworkManager.Singleton.StartCoroutine(NetworkManager.Singleton.TimeOutSwitchSceneProgress(this)); } internal void AddClientAsDone(ulong clientId) { DoneClients.Add(clientId); - if (OnClientLoadedScene != null) - OnClientLoadedScene.Invoke(clientId); + OnClientLoadedScene?.Invoke(clientId); CheckCompletion(); } @@ -77,21 +75,20 @@ internal void RemoveClientAsDone(ulong clientId) internal void SetSceneLoadOperation(AsyncOperation sceneLoadOperation) { - this.sceneLoadOperation = sceneLoadOperation; - this.sceneLoadOperation.completed += (AsyncOperation operation) => { CheckCompletion(); }; + m_SceneLoadOperation = sceneLoadOperation; + m_SceneLoadOperation.completed += operation => CheckCompletion(); } internal void CheckCompletion() { - if (!IsCompleted && DoneClients.Count == NetworkManager.Singleton.ConnectedClientsList.Count && sceneLoadOperation.isDone) + if (!IsCompleted && DoneClients.Count == NetworkManager.Singleton.ConnectedClientsList.Count && m_SceneLoadOperation.isDone) { IsCompleted = true; IsAllClientsDoneLoading = true; - NetworkSceneManager.sceneSwitchProgresses.Remove(guid); - if (OnComplete != null) - OnComplete.Invoke(false); + NetworkSceneManager.SceneSwitchProgresses.Remove(Guid); + OnComplete?.Invoke(false); - NetworkManager.Singleton.StopCoroutine(timeOutCoroutine); + NetworkManager.Singleton.StopCoroutine(m_TimeOutCoroutine); } } @@ -100,9 +97,8 @@ internal void SetTimedOut() if (!IsCompleted) { IsCompleted = true; - NetworkSceneManager.sceneSwitchProgresses.Remove(guid); - if (OnComplete != null) - OnComplete.Invoke(true); + NetworkSceneManager.SceneSwitchProgresses.Remove(Guid); + OnComplete?.Invoke(true); } } } diff --git a/com.unity.multiplayer.mlapi/Runtime/Serialization/MemoryStructures/ByteBool.cs b/com.unity.multiplayer.mlapi/Runtime/Serialization/MemoryStructures/ByteBool.cs index fffed3c38d..a63614a287 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Serialization/MemoryStructures/ByteBool.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Serialization/MemoryStructures/ByteBool.cs @@ -6,27 +6,27 @@ namespace MLAPI.Serialization internal struct ByteBool { [FieldOffset(0)] - public bool boolValue; + public bool BoolValue; [FieldOffset(0)] - public byte byteValue; + public byte ByteValue; public byte Collapse() => - byteValue = (byte)(( + ByteValue = (byte)(( // Collapse all bits to position 1 and reassign as bit - (byteValue >> 7) | - (byteValue >> 6) | - (byteValue >> 5) | - (byteValue >> 4) | - (byteValue >> 3) | - (byteValue >> 2) | - (byteValue >> 1) | - byteValue + (ByteValue >> 7) | + (ByteValue >> 6) | + (ByteValue >> 5) | + (ByteValue >> 4) | + (ByteValue >> 3) | + (ByteValue >> 2) | + (ByteValue >> 1) | + ByteValue ) & 1); public byte Collapse(bool b) { - boolValue = b; + BoolValue = b; return Collapse(); } } diff --git a/com.unity.multiplayer.mlapi/Runtime/Serialization/MemoryStructures/UIntFloat.cs b/com.unity.multiplayer.mlapi/Runtime/Serialization/MemoryStructures/UIntFloat.cs index b91db0f241..102be81cfa 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Serialization/MemoryStructures/UIntFloat.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Serialization/MemoryStructures/UIntFloat.cs @@ -12,15 +12,15 @@ namespace MLAPI.Serialization internal struct UIntFloat { [FieldOffset(0)] - public float floatValue; + public float FloatValue; [FieldOffset(0)] - public uint uintValue; + public uint UIntValue; [FieldOffset(0)] - public double doubleValue; + public double DoubleValue; [FieldOffset(0)] - public ulong ulongValue; + public ulong ULongValue; } } \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Serialization/NetworkReader.cs b/com.unity.multiplayer.mlapi/Runtime/Serialization/NetworkReader.cs index 2b8d85eb2a..c0eb6d9aee 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Serialization/NetworkReader.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Serialization/NetworkReader.cs @@ -4,7 +4,6 @@ #define ARRAY_DIFF_ALLOW_RESIZE // Whether or not to permit writing diffs of differently sized arrays using System; -using System.ComponentModel; using System.IO; using System.Text; using MLAPI.Reflection; @@ -19,8 +18,8 @@ namespace MLAPI.Serialization /// public class NetworkReader { - private Stream source; - private NetworkBuffer networkSource; + private Stream m_Source; + private NetworkBuffer m_NetworkSource; /// /// Creates a new NetworkReader backed by a given stream @@ -28,8 +27,8 @@ public class NetworkReader /// The stream to read from public NetworkReader(Stream stream) { - source = stream; - networkSource = stream as NetworkBuffer; + m_Source = stream; + m_NetworkSource = stream as NetworkBuffer; } /// @@ -38,21 +37,21 @@ public NetworkReader(Stream stream) /// The stream to read from public void SetStream(Stream stream) { - source = stream; - networkSource = stream as NetworkBuffer; + m_Source = stream; + m_NetworkSource = stream as NetworkBuffer; } /// /// Reads a single byte /// /// The byte read as an integer - public int ReadByte() => source.ReadByte(); + public int ReadByte() => m_Source.ReadByte(); /// /// Reads a byte /// /// The byte read - public byte ReadByteDirect() => (byte)source.ReadByte(); + public byte ReadByteDirect() => (byte)m_Source.ReadByte(); /// /// Reads a single bit @@ -60,12 +59,12 @@ public void SetStream(Stream stream) /// The bit read public bool ReadBit() { - if (networkSource == null) + if (m_NetworkSource == null) { throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); } - return networkSource.ReadBit(); + return m_NetworkSource.ReadBit(); } /// @@ -74,9 +73,9 @@ public bool ReadBit() /// The bit read public bool ReadBool() { - if (networkSource == null) + if (m_NetworkSource == null) { - return source.ReadByte() != 0; + return m_Source.ReadByte() != 0; } // return ReadBit(); // old (buggy) @@ -88,12 +87,12 @@ public bool ReadBool() /// public void SkipPadBits() { - if (networkSource == null) + if (m_NetworkSource == null) { throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); } - while (!networkSource.BitAligned) ReadBit(); + while (!m_NetworkSource.BitAligned) ReadBit(); } /// @@ -113,7 +112,7 @@ public object ReadObjectPacked(Type type) } } - if (SerializationManager.TryDeserialize(source, type, out object obj)) return obj; + if (SerializationManager.TryDeserialize(m_Source, type, out object obj)) return obj; if (type.IsArray && type.HasElementType) { int size = ReadInt32Packed(); @@ -128,60 +127,39 @@ public object ReadObjectPacked(Type type) return array; } - if (type == typeof(byte)) - return ReadByteDirect(); - if (type == typeof(sbyte)) - return ReadSByte(); - if (type == typeof(ushort)) - return ReadUInt16Packed(); - if (type == typeof(short)) - return ReadInt16Packed(); - if (type == typeof(int)) - return ReadInt32Packed(); - if (type == typeof(uint)) - return ReadUInt32Packed(); - if (type == typeof(long)) - return ReadInt64Packed(); - if (type == typeof(ulong)) - return ReadUInt64Packed(); - if (type == typeof(float)) - return ReadSinglePacked(); - if (type == typeof(double)) - return ReadDoublePacked(); - if (type == typeof(string)) - return ReadStringPacked(); - if (type == typeof(bool)) - return ReadBool(); - if (type == typeof(Vector2)) - return ReadVector2Packed(); - if (type == typeof(Vector3)) - return ReadVector3Packed(); - if (type == typeof(Vector4)) - return ReadVector4Packed(); - if (type == typeof(Color)) - return ReadColorPacked(); - if (type == typeof(Color32)) - return ReadColor32(); - if (type == typeof(Ray)) - return ReadRayPacked(); - if (type == typeof(Quaternion)) - return ReadRotationPacked(); - if (type == typeof(char)) - return ReadCharPacked(); - if (type.IsEnum) - return ReadInt32Packed(); + if (type == typeof(byte)) return ReadByteDirect(); + if (type == typeof(sbyte)) return ReadSByte(); + if (type == typeof(ushort)) return ReadUInt16Packed(); + if (type == typeof(short)) return ReadInt16Packed(); + if (type == typeof(int)) return ReadInt32Packed(); + if (type == typeof(uint)) return ReadUInt32Packed(); + if (type == typeof(long)) return ReadInt64Packed(); + if (type == typeof(ulong)) return ReadUInt64Packed(); + if (type == typeof(float)) return ReadSinglePacked(); + if (type == typeof(double)) return ReadDoublePacked(); + if (type == typeof(string)) return ReadStringPacked(); + if (type == typeof(bool)) return ReadBool(); + if (type == typeof(Vector2)) return ReadVector2Packed(); + if (type == typeof(Vector3)) return ReadVector3Packed(); + if (type == typeof(Vector4)) return ReadVector4Packed(); + if (type == typeof(Color)) return ReadColorPacked(); + if (type == typeof(Color32)) return ReadColor32(); + if (type == typeof(Ray)) return ReadRayPacked(); + if (type == typeof(Quaternion)) return ReadRotationPacked(); + if (type == typeof(char)) return ReadCharPacked(); + if (type.IsEnum) return ReadInt32Packed(); if (type == typeof(GameObject)) { - ulong networkId = ReadUInt64Packed(); + ulong networkObjectId = ReadUInt64Packed(); - if (NetworkSpawnManager.SpawnedObjects.ContainsKey(networkId)) + if (NetworkSpawnManager.SpawnedObjects.ContainsKey(networkObjectId)) { - return NetworkSpawnManager.SpawnedObjects[networkId].gameObject; + return NetworkSpawnManager.SpawnedObjects[networkObjectId].gameObject; } if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) { - NetworkLog.LogWarning($"{nameof(NetworkReader)} cannot find the GameObject sent in the SpawnedObjects list, it may have been destroyed. NetworkId: {networkId}"); + NetworkLog.LogWarning($"{nameof(NetworkReader)} cannot find the {nameof(GameObject)} sent in the {nameof(NetworkSpawnManager.SpawnedObjects)} list, it may have been destroyed. {nameof(networkObjectId)}: {networkObjectId}"); } return null; @@ -189,16 +167,16 @@ public object ReadObjectPacked(Type type) if (type == typeof(NetworkObject)) { - ulong networkId = ReadUInt64Packed(); + ulong networkObjectId = ReadUInt64Packed(); - if (NetworkSpawnManager.SpawnedObjects.ContainsKey(networkId)) + if (NetworkSpawnManager.SpawnedObjects.ContainsKey(networkObjectId)) { - return NetworkSpawnManager.SpawnedObjects[networkId]; + return NetworkSpawnManager.SpawnedObjects[networkObjectId]; } if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) { - NetworkLog.LogWarning($"{nameof(NetworkReader)} cannot find the {nameof(NetworkObject)} sent in the SpawnedObjects list, it may have been destroyed. NetworkId: {networkId}"); + NetworkLog.LogWarning($"{nameof(NetworkReader)} cannot find the {nameof(NetworkObject)} sent in the {nameof(NetworkSpawnManager.SpawnedObjects)} list, it may have been destroyed. {nameof(networkObjectId)}: {networkObjectId}"); } return null; @@ -206,16 +184,16 @@ public object ReadObjectPacked(Type type) if (typeof(NetworkBehaviour).IsAssignableFrom(type)) { - ulong networkId = ReadUInt64Packed(); + ulong networkObjectId = ReadUInt64Packed(); ushort behaviourId = ReadUInt16Packed(); - if (NetworkSpawnManager.SpawnedObjects.ContainsKey(networkId)) + if (NetworkSpawnManager.SpawnedObjects.ContainsKey(networkObjectId)) { - return NetworkSpawnManager.SpawnedObjects[networkId].GetNetworkBehaviourAtOrderIndex(behaviourId); + return NetworkSpawnManager.SpawnedObjects[networkObjectId].GetNetworkBehaviourAtOrderIndex(behaviourId); } if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) { - NetworkLog.LogWarning($"{nameof(NetworkReader)} cannot find the {nameof(NetworkBehaviour)} sent in the SpawnedObjects list, it may have been destroyed. NetworkId: {networkId}"); + NetworkLog.LogWarning($"{nameof(NetworkReader)} cannot find the {nameof(NetworkBehaviour)} sent in the {nameof(NetworkSpawnManager.SpawnedObjects)} list, it may have been destroyed. {nameof(networkObjectId)}: {networkObjectId}"); } return null; @@ -242,50 +220,25 @@ public object ReadObjectPacked(Type type) /// Read a single-precision floating point value from the stream. /// /// The read value - public float ReadSingle() - { - return new UIntFloat - { - uintValue = ReadUInt32() - }.floatValue; - } - + public float ReadSingle() => new UIntFloat { UIntValue = ReadUInt32() }.FloatValue; /// /// Read a double-precision floating point value from the stream. /// /// The read value - public double ReadDouble() - { - return new UIntFloat - { - ulongValue = ReadUInt64() - }.doubleValue; - } + public double ReadDouble() => new UIntFloat { ULongValue = ReadUInt64() }.DoubleValue; /// /// Read a single-precision floating point value from the stream from a varint /// /// The read value - public float ReadSinglePacked() - { - return new UIntFloat - { - uintValue = ReadUInt32Packed() - }.floatValue; - } + public float ReadSinglePacked() => new UIntFloat { UIntValue = ReadUInt32Packed() }.FloatValue; /// /// Read a double-precision floating point value from the stream as a varint /// /// The read value - public double ReadDoublePacked() - { - return new UIntFloat - { - ulongValue = ReadUInt64Packed() - }.doubleValue; - } + public double ReadDoublePacked() => new UIntFloat { ULongValue = ReadUInt64Packed() }.DoubleValue; /// /// Read a Vector2 from the stream. @@ -434,9 +387,9 @@ public Quaternion ReadRotation() /// The bits that were read public ulong ReadBits(int bitCount) { - if (networkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); - if (bitCount > 64) throw new ArgumentOutOfRangeException("Cannot read more than 64 bits into a 64-bit value!"); - if (bitCount < 0) throw new ArgumentOutOfRangeException("Cannot read fewer than 0 bits!"); + if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); + if (bitCount > 64) throw new ArgumentOutOfRangeException(nameof(bitCount), "Cannot read more than 64 bits into a 64-bit value!"); + if (bitCount < 0) throw new ArgumentOutOfRangeException(nameof(bitCount), "Cannot read fewer than 0 bits!"); ulong read = 0; for (int i = 0; i + 8 < bitCount; i += 8) read |= (ulong)ReadByte() << i; read |= (ulong)ReadByteBits(bitCount & 7) << (bitCount & ~7); @@ -450,14 +403,13 @@ public ulong ReadBits(int bitCount) /// The bits that were read public byte ReadByteBits(int bitCount) { - if (networkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); - if (bitCount > 8) throw new ArgumentOutOfRangeException("Cannot read more than 8 bits into an 8-bit value!"); - if (bitCount < 0) throw new ArgumentOutOfRangeException("Cannot read fewer than 0 bits!"); + if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); + if (bitCount > 8) throw new ArgumentOutOfRangeException(nameof(bitCount), "Cannot read more than 8 bits into an 8-bit value!"); + if (bitCount < 0) throw new ArgumentOutOfRangeException(nameof(bitCount), "Cannot read fewer than 0 bits!"); int result = 0; ByteBool convert = new ByteBool(); - for (int i = 0; i < bitCount; ++i) - result |= convert.Collapse(ReadBit()) << i; + for (int i = 0; i < bitCount; ++i) result |= convert.Collapse(ReadBit()) << i; return (byte)result; } @@ -468,10 +420,11 @@ public byte ReadByteBits(int bitCount) /// The nibble that was read public byte ReadNibble(bool asUpper) { - if (networkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); + if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); ByteBool convert = new ByteBool(); - byte result = (byte)( + byte result = (byte) + ( convert.Collapse(ReadBit()) | (convert.Collapse(ReadBit()) << 1) | (convert.Collapse(ReadBit()) << 2) | @@ -488,9 +441,10 @@ public byte ReadNibble(bool asUpper) /// The nibble that was read public byte ReadNibble() { - if (networkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); + if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); ByteBool convert = new ByteBool(); - return (byte)( + return (byte) + ( convert.Collapse(ReadBit()) | (convert.Collapse(ReadBit()) << 1) | (convert.Collapse(ReadBit()) << 2) | @@ -538,7 +492,8 @@ public byte ReadNibble() /// Read an unsigned long (UInt64) from the stream. /// /// Value read from stream. - public ulong ReadUInt64() => ( + public ulong ReadUInt64() => + ( ((uint)ReadByte()) | ((ulong)ReadByte() << 8) | ((ulong)ReadByte() << 16) | @@ -628,8 +583,7 @@ public StringBuilder ReadString(StringBuilder builder = null, bool oneByteChars int expectedLength = (int)ReadUInt32Packed(); if (builder == null) builder = new StringBuilder(expectedLength); else if (builder.Capacity + builder.Length < expectedLength) builder.Capacity = expectedLength + builder.Length; - for (int i = 0; i < expectedLength; ++i) - builder.Insert(i, oneByteChars ? (char)ReadByte() : ReadChar()); + for (int i = 0; i < expectedLength; ++i) builder.Insert(i, oneByteChars ? (char)ReadByte() : ReadChar()); return builder; } @@ -643,8 +597,7 @@ public string ReadStringPacked(StringBuilder builder = null) int expectedLength = (int)ReadUInt32Packed(); if (builder == null) builder = new StringBuilder(expectedLength); else if (builder.Capacity + builder.Length < expectedLength) builder.Capacity = expectedLength + builder.Length; - for (int i = 0; i < expectedLength; ++i) - builder.Insert(i, ReadCharPacked()); + for (int i = 0; i < expectedLength; ++i) builder.Insert(i, ReadCharPacked()); return builder.ToString(); } @@ -665,34 +618,34 @@ public string ReadStringPacked(StringBuilder builder = null) /// If set to true one byte chars are used and only ASCII is supported. public StringBuilder ReadStringDiff(StringBuilder builder, string compare, bool oneByteChars = false) { - if (networkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); + if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); int expectedLength = (int)ReadUInt32Packed(); if (builder == null) builder = new StringBuilder(expectedLength); else if (builder.Capacity < expectedLength) builder.Capacity = expectedLength; - ulong dBlockStart = networkSource.BitPosition + (ulong)(compare == null ? 0 : Math.Min(expectedLength, compare.Length)); + ulong dBlockStart = m_NetworkSource.BitPosition + (ulong)(compare == null ? 0 : Math.Min(expectedLength, compare.Length)); ulong mapStart; - int compareLength = compare == null ? 0 : compare.Length; + int compareLength = compare?.Length ?? 0; for (int i = 0; i < expectedLength; ++i) { if (i >= compareLength || ReadBit()) { #if ARRAY_WRITE_PREMAP // Move to data section - mapStart = networkSource.BitPosition; - networkSource.BitPosition = dBlockStart; + mapStart = m_NetworkSource.BitPosition; + m_NetworkSource.BitPosition = dBlockStart; #endif // Read datum builder.Insert(i, oneByteChars ? (char)ReadByte() : ReadChar()); #if ARRAY_WRITE_PREMAP - dBlockStart = networkSource.BitPosition; + dBlockStart = m_NetworkSource.BitPosition; // Return to mapping section - networkSource.BitPosition = mapStart; + m_NetworkSource.BitPosition = mapStart; #endif } else if (i < compareLength) builder.Insert(i, compare[i]); } - networkSource.BitPosition = dBlockStart; + m_NetworkSource.BitPosition = dBlockStart; return builder; } @@ -704,11 +657,11 @@ public StringBuilder ReadStringDiff(StringBuilder builder, string compare, bool /// If set to true one byte chars will be used and only ASCII will be supported. public StringBuilder ReadStringDiff(StringBuilder compareAndBuffer, bool oneByteChars = false) { - if (networkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); + if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); int expectedLength = (int)ReadUInt32Packed(); - if (compareAndBuffer == null) throw new ArgumentNullException("Buffer cannot be null"); - else if (compareAndBuffer.Capacity < expectedLength) compareAndBuffer.Capacity = expectedLength; - ulong dBlockStart = networkSource.BitPosition + (ulong)Math.Min(expectedLength, compareAndBuffer.Length); + if (compareAndBuffer == null) throw new ArgumentNullException(nameof(compareAndBuffer), "Buffer cannot be null"); + if (compareAndBuffer.Capacity < expectedLength) compareAndBuffer.Capacity = expectedLength; + ulong dBlockStart = m_NetworkSource.BitPosition + (ulong)Math.Min(expectedLength, compareAndBuffer.Length); ulong mapStart; for (int i = 0; i < expectedLength; ++i) { @@ -716,21 +669,21 @@ public StringBuilder ReadStringDiff(StringBuilder compareAndBuffer, bool oneByte { #if ARRAY_WRITE_PREMAP // Move to data section - mapStart = networkSource.BitPosition; - networkSource.BitPosition = dBlockStart; + mapStart = m_NetworkSource.BitPosition; + m_NetworkSource.BitPosition = dBlockStart; #endif // Read datum compareAndBuffer.Remove(i, 1); compareAndBuffer.Insert(i, oneByteChars ? (char)ReadByte() : ReadChar()); #if ARRAY_WRITE_PREMAP - dBlockStart = networkSource.BitPosition; + dBlockStart = m_NetworkSource.BitPosition; // Return to mapping section - networkSource.BitPosition = mapStart; + m_NetworkSource.BitPosition = mapStart; #endif } } - networkSource.BitPosition = dBlockStart; + m_NetworkSource.BitPosition = dBlockStart; return compareAndBuffer; } @@ -749,34 +702,34 @@ public StringBuilder ReadStringDiff(StringBuilder compareAndBuffer, bool oneByte /// The version to compare the diff to. public StringBuilder ReadStringPackedDiff(StringBuilder builder, string compare) { - if (networkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); + if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); int expectedLength = (int)ReadUInt32Packed(); if (builder == null) builder = new StringBuilder(expectedLength); else if (builder.Capacity < expectedLength) builder.Capacity = expectedLength; - ulong dBlockStart = networkSource.BitPosition + (ulong)(compare == null ? 0 : Math.Min(expectedLength, compare.Length)); + ulong dBlockStart = m_NetworkSource.BitPosition + (ulong)(compare == null ? 0 : Math.Min(expectedLength, compare.Length)); ulong mapStart; - int compareLength = compare == null ? 0 : compare.Length; + int compareLength = compare?.Length ?? 0; for (int i = 0; i < expectedLength; ++i) { if (i >= compareLength || ReadBit()) { #if ARRAY_WRITE_PREMAP // Move to data section - mapStart = networkSource.BitPosition; - networkSource.BitPosition = dBlockStart; + mapStart = m_NetworkSource.BitPosition; + m_NetworkSource.BitPosition = dBlockStart; #endif // Read datum builder.Insert(i, ReadCharPacked()); #if ARRAY_WRITE_PREMAP - dBlockStart = networkSource.BitPosition; + dBlockStart = m_NetworkSource.BitPosition; // Return to mapping section - networkSource.BitPosition = mapStart; + m_NetworkSource.BitPosition = mapStart; #endif } else if (i < compareLength) builder.Insert(i, compare[i]); } - networkSource.BitPosition = dBlockStart; + m_NetworkSource.BitPosition = dBlockStart; return builder; } @@ -787,11 +740,11 @@ public StringBuilder ReadStringPackedDiff(StringBuilder builder, string compare) /// The builder containing the current version and that will also be used as the output buffer. public StringBuilder ReadStringPackedDiff(StringBuilder compareAndBuffer) { - if (networkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); + if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); int expectedLength = (int)ReadUInt32Packed(); - if (compareAndBuffer == null) throw new ArgumentNullException("Buffer cannot be null"); + if (compareAndBuffer == null) throw new ArgumentNullException(nameof(compareAndBuffer), "Buffer cannot be null"); if (compareAndBuffer.Capacity < expectedLength) compareAndBuffer.Capacity = expectedLength; - ulong dBlockStart = networkSource.BitPosition + (ulong)Math.Min(expectedLength, compareAndBuffer.Length); + ulong dBlockStart = m_NetworkSource.BitPosition + (ulong)Math.Min(expectedLength, compareAndBuffer.Length); ulong mapStart; for (int i = 0; i < expectedLength; ++i) { @@ -799,21 +752,21 @@ public StringBuilder ReadStringPackedDiff(StringBuilder compareAndBuffer) { #if ARRAY_WRITE_PREMAP // Move to data section - mapStart = networkSource.BitPosition; - networkSource.BitPosition = dBlockStart; + mapStart = m_NetworkSource.BitPosition; + m_NetworkSource.BitPosition = dBlockStart; #endif // Read datum compareAndBuffer.Remove(i, 1); compareAndBuffer.Insert(i, ReadCharPacked()); #if ARRAY_WRITE_PREMAP - dBlockStart = networkSource.BitPosition; + dBlockStart = m_NetworkSource.BitPosition; // Return to mapping section - networkSource.BitPosition = mapStart; + m_NetworkSource.BitPosition = mapStart; #endif } } - networkSource.BitPosition = dBlockStart; + m_NetworkSource.BitPosition = dBlockStart; return compareAndBuffer; } @@ -841,35 +794,35 @@ public byte[] ReadByteArray(byte[] readTo = null, long knownLength = -1) /// ArraySegment<byte> public ArraySegment CreateArraySegment(int sizeToCopy = -1, int offset = -1) { - if (networkSource != null) + if (m_NetworkSource != null) { //If no offset was passed, used the current position - int Offset = offset == -1 ? (int)networkSource.Position : offset; - int CopySize = sizeToCopy == -1 && offset == -1 ? (int)networkSource.Length : sizeToCopy; + int Offset = offset == -1 ? (int)m_NetworkSource.Position : offset; + int CopySize = sizeToCopy == -1 && offset == -1 ? (int)m_NetworkSource.Length : sizeToCopy; if (CopySize > 0) { //Check to make sure we won't be copying beyond our bounds - if ((networkSource.Length - Offset) >= CopySize) + if ((m_NetworkSource.Length - Offset) >= CopySize) { - return new ArraySegment(networkSource.GetBuffer(), Offset, CopySize); + return new ArraySegment(m_NetworkSource.GetBuffer(), Offset, CopySize); } //If we didn't pass anything in or passed the length of the buffer - if (CopySize == networkSource.Length) + if (CopySize == m_NetworkSource.Length) { Offset = 0; } else { - Debug.LogError($"CopySize ({CopySize}) exceeds bounds with an Offset of ({Offset})! "); + Debug.LogError($"{nameof(CopySize)} ({CopySize}) exceeds bounds with an {nameof(Offset)} of ({Offset})! "); return new ArraySegment(); } //Return the request array segment - return new ArraySegment(networkSource.GetBuffer(), Offset, CopySize); + return new ArraySegment(m_NetworkSource.GetBuffer(), Offset, CopySize); } - Debug.LogError($"CopySize ({CopySize}) is zero or less! "); + Debug.LogError($"{nameof(CopySize)} ({CopySize}) is zero or less! "); } else { @@ -887,33 +840,33 @@ public ArraySegment CreateArraySegment(int sizeToCopy = -1, int offset = - /// The length of the array if it's known. Otherwise -1 public byte[] ReadByteArrayDiff(byte[] readTo = null, long knownLength = -1) { - if (networkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); + if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); if (knownLength < 0) knownLength = (long)ReadUInt64Packed(); byte[] writeTo = readTo == null || readTo.LongLength != knownLength ? new byte[knownLength] : readTo; - ulong dBlockStart = networkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); + ulong dBlockStart = m_NetworkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); ulong mapStart; - long readToLength = readTo == null ? 0 : readTo.LongLength; + long readToLength = readTo?.LongLength ?? 0; for (long i = 0; i < knownLength; ++i) { if (i >= readToLength || ReadBit()) { #if ARRAY_WRITE_PREMAP // Move to data section - mapStart = networkSource.BitPosition; - networkSource.BitPosition = dBlockStart; + mapStart = m_NetworkSource.BitPosition; + m_NetworkSource.BitPosition = dBlockStart; #endif // Read datum writeTo[i] = ReadByteDirect(); #if ARRAY_WRITE_PREMAP - dBlockStart = networkSource.BitPosition; + dBlockStart = m_NetworkSource.BitPosition; // Return to mapping section - networkSource.BitPosition = mapStart; + m_NetworkSource.BitPosition = mapStart; #endif } else if (i < readTo.LongLength) writeTo[i] = readTo[i]; } - networkSource.BitPosition = dBlockStart; + m_NetworkSource.BitPosition = dBlockStart; return writeTo; } @@ -953,33 +906,33 @@ public short[] ReadShortArrayPacked(short[] readTo = null, long knownLength = -1 /// The known length or -1 if unknown public short[] ReadShortArrayDiff(short[] readTo = null, long knownLength = -1) { - if (networkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); + if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); if (knownLength < 0) knownLength = (long)ReadUInt64Packed(); short[] writeTo = readTo == null || readTo.LongLength != knownLength ? new short[knownLength] : readTo; - ulong dBlockStart = networkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); + ulong dBlockStart = m_NetworkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); ulong mapStart; - long readToLength = readTo == null ? 0 : readTo.LongLength; + long readToLength = readTo?.LongLength ?? 0; for (long i = 0; i < knownLength; ++i) { if (i >= readToLength || ReadBit()) { #if ARRAY_WRITE_PREMAP // Move to data section - mapStart = networkSource.BitPosition; - networkSource.BitPosition = dBlockStart; + mapStart = m_NetworkSource.BitPosition; + m_NetworkSource.BitPosition = dBlockStart; #endif // Read datum writeTo[i] = ReadInt16(); #if ARRAY_WRITE_PREMAP - dBlockStart = networkSource.BitPosition; + dBlockStart = m_NetworkSource.BitPosition; // Return to mapping section - networkSource.BitPosition = mapStart; + m_NetworkSource.BitPosition = mapStart; #endif } else if (i < readTo.LongLength) writeTo[i] = readTo[i]; } - networkSource.BitPosition = dBlockStart; + m_NetworkSource.BitPosition = dBlockStart; return writeTo; } @@ -991,33 +944,33 @@ public short[] ReadShortArrayDiff(short[] readTo = null, long knownLength = -1) /// The known length or -1 if unknown public short[] ReadShortArrayPackedDiff(short[] readTo = null, long knownLength = -1) { - if (networkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); + if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); if (knownLength < 0) knownLength = (long)ReadUInt64Packed(); short[] writeTo = readTo == null || readTo.LongLength != knownLength ? new short[knownLength] : readTo; - ulong data = networkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); + ulong data = m_NetworkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); ulong rset; - long readToLength = readTo == null ? 0 : readTo.LongLength; + long readToLength = readTo?.LongLength ?? 0; for (long i = 0; i < knownLength; ++i) { if (i >= readToLength || ReadBit()) { #if ARRAY_WRITE_PREMAP // Move to data section - rset = networkSource.BitPosition; - networkSource.BitPosition = data; + rset = m_NetworkSource.BitPosition; + m_NetworkSource.BitPosition = data; #endif // Read datum writeTo[i] = ReadInt16Packed(); #if ARRAY_WRITE_PREMAP // Return to mapping section - data = networkSource.BitPosition; - networkSource.BitPosition = rset; + data = m_NetworkSource.BitPosition; + m_NetworkSource.BitPosition = rset; #endif } else if (i < readTo.LongLength) writeTo[i] = readTo[i]; } - networkSource.BitPosition = data; + m_NetworkSource.BitPosition = data; return writeTo; } @@ -1057,33 +1010,33 @@ public ushort[] ReadUShortArrayPacked(ushort[] readTo = null, long knownLength = /// The known length or -1 if unknown public ushort[] ReadUShortArrayDiff(ushort[] readTo = null, long knownLength = -1) { - if (networkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); + if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); if (knownLength < 0) knownLength = (long)ReadUInt64Packed(); ushort[] writeTo = readTo == null || readTo.LongLength != knownLength ? new ushort[knownLength] : readTo; - ulong dBlockStart = networkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); + ulong dBlockStart = m_NetworkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); ulong mapStart; - long readToLength = readTo == null ? 0 : readTo.LongLength; + long readToLength = readTo?.LongLength ?? 0; for (long i = 0; i < knownLength; ++i) { if (i >= readToLength || ReadBit()) { #if ARRAY_WRITE_PREMAP // Move to data section - mapStart = networkSource.BitPosition; - networkSource.BitPosition = dBlockStart; + mapStart = m_NetworkSource.BitPosition; + m_NetworkSource.BitPosition = dBlockStart; #endif // Read datum writeTo[i] = ReadUInt16(); #if ARRAY_WRITE_PREMAP - dBlockStart = networkSource.BitPosition; + dBlockStart = m_NetworkSource.BitPosition; // Return to mapping section - networkSource.BitPosition = mapStart; + m_NetworkSource.BitPosition = mapStart; #endif } else if (i < readTo.LongLength) writeTo[i] = readTo[i]; } - networkSource.BitPosition = dBlockStart; + m_NetworkSource.BitPosition = dBlockStart; return writeTo; } @@ -1095,33 +1048,33 @@ public ushort[] ReadUShortArrayDiff(ushort[] readTo = null, long knownLength = - /// The known length or -1 if unknown public ushort[] ReadUShortArrayPackedDiff(ushort[] readTo = null, long knownLength = -1) { - if (networkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); + if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); if (knownLength < 0) knownLength = (long)ReadUInt64Packed(); ushort[] writeTo = readTo == null || readTo.LongLength != knownLength ? new ushort[knownLength] : readTo; - ulong data = networkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); + ulong data = m_NetworkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); ulong rset; - long readToLength = readTo == null ? 0 : readTo.LongLength; + long readToLength = readTo?.LongLength ?? 0; for (long i = 0; i < knownLength; ++i) { if (i >= readToLength || ReadBit()) { #if ARRAY_WRITE_PREMAP // Move to data section - rset = networkSource.BitPosition; - networkSource.BitPosition = data; + rset = m_NetworkSource.BitPosition; + m_NetworkSource.BitPosition = data; #endif // Read datum writeTo[i] = ReadUInt16Packed(); #if ARRAY_WRITE_PREMAP // Return to mapping section - data = networkSource.BitPosition; - networkSource.BitPosition = rset; + data = m_NetworkSource.BitPosition; + m_NetworkSource.BitPosition = rset; #endif } else if (i < readTo.LongLength) writeTo[i] = readTo[i]; } - networkSource.BitPosition = data; + m_NetworkSource.BitPosition = data; return writeTo; } @@ -1161,33 +1114,33 @@ public int[] ReadIntArrayPacked(int[] readTo = null, long knownLength = -1) /// The known length or -1 if unknown public int[] ReadIntArrayDiff(int[] readTo = null, long knownLength = -1) { - if (networkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); + if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); if (knownLength < 0) knownLength = (long)ReadUInt64Packed(); int[] writeTo = readTo == null || readTo.LongLength != knownLength ? new int[knownLength] : readTo; - ulong dBlockStart = networkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); + ulong dBlockStart = m_NetworkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); ulong mapStart; - long readToLength = readTo == null ? 0 : readTo.LongLength; + long readToLength = readTo?.LongLength ?? 0; for (long i = 0; i < knownLength; ++i) { if (i >= readToLength || ReadBit()) { #if ARRAY_WRITE_PREMAP // Move to data section - mapStart = networkSource.BitPosition; - networkSource.BitPosition = dBlockStart; + mapStart = m_NetworkSource.BitPosition; + m_NetworkSource.BitPosition = dBlockStart; #endif // Read datum writeTo[i] = ReadInt32(); #if ARRAY_WRITE_PREMAP - dBlockStart = networkSource.BitPosition; + dBlockStart = m_NetworkSource.BitPosition; // Return to mapping section - networkSource.BitPosition = mapStart; + m_NetworkSource.BitPosition = mapStart; #endif } else if (i < readTo.LongLength) writeTo[i] = readTo[i]; } - networkSource.BitPosition = dBlockStart; + m_NetworkSource.BitPosition = dBlockStart; return writeTo; } @@ -1199,33 +1152,33 @@ public int[] ReadIntArrayDiff(int[] readTo = null, long knownLength = -1) /// The known length or -1 if unknown public int[] ReadIntArrayPackedDiff(int[] readTo = null, long knownLength = -1) { - if (networkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); + if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); if (knownLength < 0) knownLength = (long)ReadUInt64Packed(); int[] writeTo = readTo == null || readTo.LongLength != knownLength ? new int[knownLength] : readTo; - ulong data = networkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); + ulong data = m_NetworkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); ulong rset; - long readToLength = readTo == null ? 0 : readTo.LongLength; + long readToLength = readTo?.LongLength ?? 0; for (long i = 0; i < knownLength; ++i) { if (i >= readToLength || ReadBit()) { #if ARRAY_WRITE_PREMAP // Move to data section - rset = networkSource.BitPosition; - networkSource.BitPosition = data; + rset = m_NetworkSource.BitPosition; + m_NetworkSource.BitPosition = data; #endif // Read datum writeTo[i] = ReadInt32Packed(); #if ARRAY_WRITE_PREMAP // Return to mapping section - data = networkSource.BitPosition; - networkSource.BitPosition = rset; + data = m_NetworkSource.BitPosition; + m_NetworkSource.BitPosition = rset; #endif } else if (i < readTo.LongLength) writeTo[i] = readTo[i]; } - networkSource.BitPosition = data; + m_NetworkSource.BitPosition = data; return writeTo; } @@ -1265,33 +1218,33 @@ public uint[] ReadUIntArrayPacked(uint[] readTo = null, long knownLength = -1) /// The known length or -1 if unknown public uint[] ReadUIntArrayDiff(uint[] readTo = null, long knownLength = -1) { - if (networkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); + if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); if (knownLength < 0) knownLength = (long)ReadUInt64Packed(); uint[] writeTo = readTo == null || readTo.LongLength != knownLength ? new uint[knownLength] : readTo; - ulong dBlockStart = networkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); + ulong dBlockStart = m_NetworkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); ulong mapStart; - long readToLength = readTo == null ? 0 : readTo.LongLength; + long readToLength = readTo?.LongLength ?? 0; for (long i = 0; i < knownLength; ++i) { if (i >= readToLength || ReadBit()) { #if ARRAY_WRITE_PREMAP // Move to data section - mapStart = networkSource.BitPosition; - networkSource.BitPosition = dBlockStart; + mapStart = m_NetworkSource.BitPosition; + m_NetworkSource.BitPosition = dBlockStart; #endif // Read datum writeTo[i] = ReadUInt32(); #if ARRAY_WRITE_PREMAP - dBlockStart = networkSource.BitPosition; + dBlockStart = m_NetworkSource.BitPosition; // Return to mapping section - networkSource.BitPosition = mapStart; + m_NetworkSource.BitPosition = mapStart; #endif } else if (i < readTo.LongLength) writeTo[i] = readTo[i]; } - networkSource.BitPosition = dBlockStart; + m_NetworkSource.BitPosition = dBlockStart; return writeTo; } @@ -1331,33 +1284,33 @@ public long[] ReadLongArrayPacked(long[] readTo = null, long knownLength = -1) /// The known length or -1 if unknown public long[] ReadLongArrayDiff(long[] readTo = null, long knownLength = -1) { - if (networkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); + if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); if (knownLength < 0) knownLength = (long)ReadUInt64Packed(); long[] writeTo = readTo == null || readTo.LongLength != knownLength ? new long[knownLength] : readTo; - ulong dBlockStart = networkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); + ulong dBlockStart = m_NetworkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); ulong mapStart; - long readToLength = readTo == null ? 0 : readTo.LongLength; + long readToLength = readTo?.LongLength ?? 0; for (long i = 0; i < knownLength; ++i) { if (i >= readToLength || ReadBit()) { #if ARRAY_WRITE_PREMAP // Move to data section - mapStart = networkSource.BitPosition; - networkSource.BitPosition = dBlockStart; + mapStart = m_NetworkSource.BitPosition; + m_NetworkSource.BitPosition = dBlockStart; #endif // Read datum writeTo[i] = ReadInt64(); #if ARRAY_WRITE_PREMAP - dBlockStart = networkSource.BitPosition; + dBlockStart = m_NetworkSource.BitPosition; // Return to mapping section - networkSource.BitPosition = mapStart; + m_NetworkSource.BitPosition = mapStart; #endif } else if (i < readTo.LongLength) writeTo[i] = readTo[i]; } - networkSource.BitPosition = dBlockStart; + m_NetworkSource.BitPosition = dBlockStart; return writeTo; } @@ -1369,33 +1322,33 @@ public long[] ReadLongArrayDiff(long[] readTo = null, long knownLength = -1) /// The known length or -1 if unknown public long[] ReadLongArrayPackedDiff(long[] readTo = null, long knownLength = -1) { - if (networkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); + if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); if (knownLength < 0) knownLength = (long)ReadUInt64Packed(); long[] writeTo = readTo == null || readTo.LongLength != knownLength ? new long[knownLength] : readTo; - ulong data = networkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); + ulong data = m_NetworkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); ulong rset; - long readToLength = readTo == null ? 0 : readTo.LongLength; + long readToLength = readTo?.LongLength ?? 0; for (long i = 0; i < knownLength; ++i) { if (i >= readToLength || ReadBit()) { #if ARRAY_WRITE_PREMAP // Move to data section - rset = networkSource.BitPosition; - networkSource.BitPosition = data; + rset = m_NetworkSource.BitPosition; + m_NetworkSource.BitPosition = data; #endif // Read datum writeTo[i] = ReadInt64Packed(); #if ARRAY_WRITE_PREMAP // Return to mapping section - data = networkSource.BitPosition; - networkSource.BitPosition = rset; + data = m_NetworkSource.BitPosition; + m_NetworkSource.BitPosition = rset; #endif } else if (i < readTo.LongLength) writeTo[i] = readTo[i]; } - networkSource.BitPosition = data; + m_NetworkSource.BitPosition = data; return writeTo; } @@ -1435,33 +1388,33 @@ public ulong[] ReadULongArrayPacked(ulong[] readTo = null, long knownLength = -1 /// The known length or -1 if unknown public ulong[] ReadULongArrayDiff(ulong[] readTo = null, long knownLength = -1) { - if (networkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); + if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); if (knownLength < 0) knownLength = (long)ReadUInt64Packed(); ulong[] writeTo = readTo == null || readTo.LongLength != knownLength ? new ulong[knownLength] : readTo; - ulong dBlockStart = networkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); + ulong dBlockStart = m_NetworkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); ulong mapStart; - long readToLength = readTo == null ? 0 : readTo.LongLength; + long readToLength = readTo?.LongLength ?? 0; for (long i = 0; i < knownLength; ++i) { if (i >= readToLength || ReadBit()) { #if ARRAY_WRITE_PREMAP // Move to data section - mapStart = networkSource.BitPosition; - networkSource.BitPosition = dBlockStart; + mapStart = m_NetworkSource.BitPosition; + m_NetworkSource.BitPosition = dBlockStart; #endif // Read datum writeTo[i] = ReadUInt64(); #if ARRAY_WRITE_PREMAP - dBlockStart = networkSource.BitPosition; + dBlockStart = m_NetworkSource.BitPosition; // Return to mapping section - networkSource.BitPosition = mapStart; + m_NetworkSource.BitPosition = mapStart; #endif } else if (i < readTo.LongLength) writeTo[i] = readTo[i]; } - networkSource.BitPosition = dBlockStart; + m_NetworkSource.BitPosition = dBlockStart; return writeTo; } @@ -1473,33 +1426,33 @@ public ulong[] ReadULongArrayDiff(ulong[] readTo = null, long knownLength = -1) /// The known length or -1 if unknown public ulong[] ReadULongArrayPackedDiff(ulong[] readTo = null, long knownLength = -1) { - if (networkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); + if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); if (knownLength < 0) knownLength = (long)ReadUInt64Packed(); ulong[] writeTo = readTo == null || readTo.LongLength != knownLength ? new ulong[knownLength] : readTo; - ulong data = networkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); + ulong data = m_NetworkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); ulong rset; - long readToLength = readTo == null ? 0 : readTo.LongLength; + long readToLength = readTo?.LongLength ?? 0; for (long i = 0; i < knownLength; ++i) { if (i >= readToLength || ReadBit()) { #if ARRAY_WRITE_PREMAP // Move to data section - rset = networkSource.BitPosition; - networkSource.BitPosition = data; + rset = m_NetworkSource.BitPosition; + m_NetworkSource.BitPosition = data; #endif // Read datum writeTo[i] = ReadUInt64Packed(); #if ARRAY_WRITE_PREMAP // Return to mapping section - data = networkSource.BitPosition; - networkSource.BitPosition = rset; + data = m_NetworkSource.BitPosition; + m_NetworkSource.BitPosition = rset; #endif } else if (i < readTo.LongLength) writeTo[i] = readTo[i]; } - networkSource.BitPosition = data; + m_NetworkSource.BitPosition = data; return writeTo; } @@ -1539,33 +1492,33 @@ public float[] ReadFloatArrayPacked(float[] readTo = null, long knownLength = -1 /// The known length or -1 if unknown public float[] ReadFloatArrayDiff(float[] readTo = null, long knownLength = -1) { - if (networkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); + if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); if (knownLength < 0) knownLength = (long)ReadUInt64Packed(); float[] writeTo = readTo == null || readTo.LongLength != knownLength ? new float[knownLength] : readTo; - ulong dBlockStart = networkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); + ulong dBlockStart = m_NetworkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); ulong mapStart; - long readToLength = readTo == null ? 0 : readTo.LongLength; + long readToLength = readTo?.LongLength ?? 0; for (long i = 0; i < knownLength; ++i) { if (i >= readToLength || ReadBit()) { #if ARRAY_WRITE_PREMAP // Move to data section - mapStart = networkSource.BitPosition; - networkSource.BitPosition = dBlockStart; + mapStart = m_NetworkSource.BitPosition; + m_NetworkSource.BitPosition = dBlockStart; #endif // Read datum writeTo[i] = ReadSingle(); #if ARRAY_WRITE_PREMAP - dBlockStart = networkSource.BitPosition; + dBlockStart = m_NetworkSource.BitPosition; // Return to mapping section - networkSource.BitPosition = mapStart; + m_NetworkSource.BitPosition = mapStart; #endif } else if (i < readTo.LongLength) writeTo[i] = readTo[i]; } - networkSource.BitPosition = dBlockStart; + m_NetworkSource.BitPosition = dBlockStart; return writeTo; } @@ -1577,33 +1530,33 @@ public float[] ReadFloatArrayDiff(float[] readTo = null, long knownLength = -1) /// The known length or -1 if unknown public float[] ReadFloatArrayPackedDiff(float[] readTo = null, long knownLength = -1) { - if (networkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); + if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); if (knownLength < 0) knownLength = (long)ReadUInt64Packed(); float[] writeTo = readTo == null || readTo.LongLength != knownLength ? new float[knownLength] : readTo; - ulong data = networkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); + ulong data = m_NetworkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); ulong rset; - long readToLength = readTo == null ? 0 : readTo.LongLength; + long readToLength = readTo?.LongLength ?? 0; for (long i = 0; i < knownLength; ++i) { if (i >= readToLength || ReadBit()) { #if ARRAY_WRITE_PREMAP // Move to data section - rset = networkSource.BitPosition; - networkSource.BitPosition = data; + rset = m_NetworkSource.BitPosition; + m_NetworkSource.BitPosition = data; #endif // Read datum readTo[i] = ReadSinglePacked(); #if ARRAY_WRITE_PREMAP // Return to mapping section - data = networkSource.BitPosition; - networkSource.BitPosition = rset; + data = m_NetworkSource.BitPosition; + m_NetworkSource.BitPosition = rset; #endif } else if (i < readTo.LongLength) writeTo[i] = readTo[i]; } - networkSource.BitPosition = data; + m_NetworkSource.BitPosition = data; return writeTo; } @@ -1643,33 +1596,33 @@ public double[] ReadDoubleArrayPacked(double[] readTo = null, long knownLength = /// The known length or -1 if unknown public double[] ReadDoubleArrayDiff(double[] readTo = null, long knownLength = -1) { - if (networkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); + if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); if (knownLength < 0) knownLength = (long)ReadUInt64Packed(); double[] writeTo = readTo == null || readTo.LongLength != knownLength ? new double[knownLength] : readTo; - ulong dBlockStart = networkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); + ulong dBlockStart = m_NetworkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); ulong mapStart; - long readToLength = readTo == null ? 0 : readTo.LongLength; + long readToLength = readTo?.LongLength ?? 0; for (long i = 0; i < knownLength; ++i) { if (i >= readToLength || ReadBit()) { #if ARRAY_WRITE_PREMAP // Move to data section - mapStart = networkSource.BitPosition; - networkSource.BitPosition = dBlockStart; + mapStart = m_NetworkSource.BitPosition; + m_NetworkSource.BitPosition = dBlockStart; #endif // Read datum writeTo[i] = ReadDouble(); #if ARRAY_WRITE_PREMAP - dBlockStart = networkSource.BitPosition; + dBlockStart = m_NetworkSource.BitPosition; // Return to mapping section - networkSource.BitPosition = mapStart; + m_NetworkSource.BitPosition = mapStart; #endif } else if (i < readTo.LongLength) writeTo[i] = readTo[i]; } - networkSource.BitPosition = dBlockStart; + m_NetworkSource.BitPosition = dBlockStart; return writeTo; } @@ -1681,33 +1634,33 @@ public double[] ReadDoubleArrayDiff(double[] readTo = null, long knownLength = - /// The known length or -1 if unknown public double[] ReadDoubleArrayPackedDiff(double[] readTo = null, long knownLength = -1) { - if (networkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); + if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream"); if (knownLength < 0) knownLength = (long)ReadUInt64Packed(); double[] writeTo = readTo == null || readTo.LongLength != knownLength ? new double[knownLength] : readTo; - ulong data = networkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); + ulong data = m_NetworkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength)); ulong rset; - long readToLength = readTo == null ? 0 : readTo.LongLength; + long readToLength = readTo?.LongLength ?? 0; for (long i = 0; i < knownLength; ++i) { if (i >= readToLength || ReadBit()) { #if ARRAY_WRITE_PREMAP // Move to data section - rset = networkSource.BitPosition; - networkSource.BitPosition = data; + rset = m_NetworkSource.BitPosition; + m_NetworkSource.BitPosition = data; #endif // Read datum writeTo[i] = ReadDoublePacked(); #if ARRAY_WRITE_PREMAP // Return to mapping section - data = networkSource.BitPosition; - networkSource.BitPosition = rset; + data = m_NetworkSource.BitPosition; + m_NetworkSource.BitPosition = rset; #endif } else if (i < readTo.LongLength) writeTo[i] = readTo[i]; } - networkSource.BitPosition = data; + m_NetworkSource.BitPosition = data; return writeTo; } } diff --git a/com.unity.multiplayer.mlapi/Runtime/Serialization/NetworkWriter.cs b/com.unity.multiplayer.mlapi/Runtime/Serialization/NetworkWriter.cs index 0ef4bc9364..ca9751bf21 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Serialization/NetworkWriter.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Serialization/NetworkWriter.cs @@ -4,7 +4,6 @@ #define ARRAY_DIFF_ALLOW_RESIZE // Whether or not to permit writing diffs of differently sized arrays using System; -using System.ComponentModel; using System.Diagnostics; using System.IO; using MLAPI.Reflection; @@ -18,8 +17,8 @@ namespace MLAPI.Serialization /// public class NetworkWriter { - private Stream sink; - private NetworkBuffer networkSink; + private Stream m_Sink; + private NetworkBuffer m_NetworkSink; /// /// Creates a new NetworkWriter backed by a given stream @@ -27,8 +26,8 @@ public class NetworkWriter /// The stream to use for writing public NetworkWriter(Stream stream) { - sink = stream; - networkSink = stream as NetworkBuffer; + m_Sink = stream; + m_NetworkSink = stream as NetworkBuffer; } /// @@ -37,13 +36,13 @@ public NetworkWriter(Stream stream) /// The stream to write to public void SetStream(Stream stream) { - sink = stream; - networkSink = stream as NetworkBuffer; + m_Sink = stream; + m_NetworkSink = stream as NetworkBuffer; } internal Stream GetStream() { - return sink; + return m_Sink; } /// @@ -65,14 +64,14 @@ public void WriteObjectPacked(object value) } } - if (SerializationManager.TrySerialize(sink, value)) + if (SerializationManager.TrySerialize(m_Sink, value)) { return; } if (value is Array array) { - Type elementType = value.GetType().GetElementType(); + var elementType = value.GetType().GetElementType(); if (SerializationManager.IsTypeSupported(elementType)) { @@ -196,12 +195,12 @@ public void WriteObjectPacked(object value) var networkObject = ((GameObject)value).GetComponent(); if (ReferenceEquals(networkObject, null)) { - throw new ArgumentException($"{nameof(NetworkWriter)} cannot write GameObject types that does not has a {nameof(NetworkObject)} component attached. GameObject: {((GameObject)value).name}"); + throw new ArgumentException($"{nameof(NetworkWriter)} cannot write {nameof(GameObject)} types that does not has a {nameof(NetworkObject)} component attached. {nameof(GameObject)}: {((GameObject)value).name}"); } if (!networkObject.IsSpawned) { - throw new ArgumentException($"{nameof(NetworkWriter)} cannot write {nameof(NetworkObject)} types that are not spawned. GameObject: {((GameObject)value).name}"); + throw new ArgumentException($"{nameof(NetworkWriter)} cannot write {nameof(NetworkObject)} types that are not spawned. {nameof(GameObject)}: {((GameObject)value).name}"); } WriteUInt64Packed(networkObject.NetworkObjectId); @@ -211,7 +210,7 @@ public void WriteObjectPacked(object value) { if (!((NetworkObject)value).IsSpawned) { - throw new ArgumentException($"{nameof(NetworkWriter)} cannot write {nameof(NetworkObject)} types that are not spawned. GameObject: {((GameObject)value).name}"); + throw new ArgumentException($"{nameof(NetworkWriter)} cannot write {nameof(NetworkObject)} types that are not spawned. {nameof(GameObject)}: {((GameObject)value).name}"); } WriteUInt64Packed(((NetworkObject)value).NetworkObjectId); @@ -221,7 +220,7 @@ public void WriteObjectPacked(object value) { if (!((NetworkBehaviour)value).HasNetworkObject || !((NetworkBehaviour)value).NetworkObject.IsSpawned) { - throw new ArgumentException($"{nameof(NetworkWriter)} cannot write {nameof(NetworkBehaviour)} types that are not spawned. GameObject: {((GameObject)value).name}"); + throw new ArgumentException($"{nameof(NetworkWriter)} cannot write {nameof(NetworkBehaviour)} types that are not spawned. {nameof(GameObject)}: {((GameObject)value).name}"); } WriteUInt64Packed(((NetworkBehaviour)value).NetworkObjectId); @@ -246,8 +245,8 @@ public void WriteSingle(float value) { WriteUInt32(new UIntFloat { - floatValue = value - }.uintValue); + FloatValue = value + }.UIntValue); } /// @@ -258,8 +257,8 @@ public void WriteDouble(double value) { WriteUInt64(new UIntFloat { - doubleValue = value - }.ulongValue); + DoubleValue = value + }.ULongValue); } /// @@ -270,8 +269,8 @@ public void WriteSinglePacked(float value) { WriteUInt32Packed(new UIntFloat { - floatValue = value - }.uintValue); + FloatValue = value + }.UIntValue); } /// @@ -282,8 +281,8 @@ public void WriteDoublePacked(double value) { WriteUInt64Packed(new UIntFloat { - doubleValue = value - }.ulongValue); + DoubleValue = value + }.ULongValue); } /// @@ -440,7 +439,7 @@ public void WriteRangedSingle(float value, float minValue, float maxValue, int b if (bytes < 1 || bytes > 4) throw new ArgumentOutOfRangeException("Result must occupy between 1 and 4 bytes!"); if (value < minValue || value > maxValue) throw new ArgumentOutOfRangeException("Given value does not match the given constraints!"); uint result = (uint)(((value + minValue) / (maxValue + minValue)) * ((0x100 * bytes) - 1)); - for (int i = 0; i < bytes; ++i) sink.WriteByte((byte)(result >> (i << 3))); + for (int i = 0; i < bytes; ++i) m_Sink.WriteByte((byte)(result >> (i << 3))); } /// @@ -496,8 +495,8 @@ public void WriteRotation(Quaternion rotation) /// public void WriteBit(bool bit) { - if (networkSink == null) throw new InvalidOperationException($"Cannot write bits on a non-{nameof(NetworkBuffer)} stream"); - networkSink.WriteBit(bit); + if (m_NetworkSink == null) throw new InvalidOperationException($"Cannot write bits on a non-{nameof(NetworkBuffer)} stream"); + m_NetworkSink.WriteBit(bit); } /// @@ -506,9 +505,9 @@ public void WriteBit(bool bit) /// public void WriteBool(bool value) { - if (networkSink == null) + if (m_NetworkSink == null) { - sink.WriteByte(value ? (byte)1 : (byte)0); + m_Sink.WriteByte(value ? (byte)1 : (byte)0); } else { @@ -522,7 +521,7 @@ public void WriteBool(bool value) /// public void WritePadBits() { - while (!networkSink.BitAligned) WriteBit(false); + while (!m_NetworkSink.BitAligned) WriteBit(false); } /// @@ -545,12 +544,12 @@ public void WritePadBits() /// Amount of bits to write public void WriteBits(ulong value, int bitCount) { - if (networkSink == null) throw new InvalidOperationException($"Cannot write bits on a non-{nameof(NetworkBuffer)} stream"); - if (bitCount > 64) throw new ArgumentOutOfRangeException("Cannot read more than 64 bits from a 64-bit value!"); - if (bitCount < 0) throw new ArgumentOutOfRangeException("Cannot read fewer than 0 bits!"); + if (m_NetworkSink == null) throw new InvalidOperationException($"Cannot write bits on a non-{nameof(NetworkBuffer)} stream"); + if (bitCount > 64) throw new ArgumentOutOfRangeException(nameof(bitCount), "Cannot read more than 64 bits from a 64-bit value!"); + if (bitCount < 0) throw new ArgumentOutOfRangeException(nameof(bitCount), "Cannot read fewer than 0 bits!"); int count = 0; - for (; count + 8 < bitCount; count += 8) networkSink.WriteByte((byte)(value >> count)); - for (; count < bitCount; ++count) networkSink.WriteBit((value & (1UL << count)) != 0); + for (; count + 8 < bitCount; count += 8) m_NetworkSink.WriteByte((byte)(value >> count)); + for (; count < bitCount; ++count) m_NetworkSink.WriteBit((value & (1UL << count)) != 0); } @@ -561,9 +560,8 @@ public void WriteBits(ulong value, int bitCount) /// Amount of bits to write. public void WriteBits(byte value, int bitCount) { - if (networkSink == null) throw new InvalidOperationException($"Cannot write bits on a non-{nameof(NetworkBuffer)} stream"); - for (int i = 0; i < bitCount; ++i) - networkSink.WriteBit(((value >> i) & 1) != 0); + if (m_NetworkSink == null) throw new InvalidOperationException($"Cannot write bits on a non-{nameof(NetworkBuffer)} stream"); + for (int i = 0; i < bitCount; ++i) m_NetworkSink.WriteBit(((value >> i) & 1) != 0); } /// @@ -584,8 +582,8 @@ public void WriteBits(byte value, int bitCount) /// Value to write public void WriteUInt16(ushort value) { - sink.WriteByte((byte)value); - sink.WriteByte((byte)(value >> 8)); + m_Sink.WriteByte((byte)value); + m_Sink.WriteByte((byte)(value >> 8)); } /// @@ -600,10 +598,10 @@ public void WriteUInt16(ushort value) /// Value to write public void WriteUInt32(uint value) { - sink.WriteByte((byte)value); - sink.WriteByte((byte)(value >> 8)); - sink.WriteByte((byte)(value >> 16)); - sink.WriteByte((byte)(value >> 24)); + m_Sink.WriteByte((byte)value); + m_Sink.WriteByte((byte)(value >> 8)); + m_Sink.WriteByte((byte)(value >> 16)); + m_Sink.WriteByte((byte)(value >> 24)); } /// @@ -618,14 +616,14 @@ public void WriteUInt32(uint value) /// Value to write public void WriteUInt64(ulong value) { - sink.WriteByte((byte)value); - sink.WriteByte((byte)(value >> 8)); - sink.WriteByte((byte)(value >> 16)); - sink.WriteByte((byte)(value >> 24)); - sink.WriteByte((byte)(value >> 32)); - sink.WriteByte((byte)(value >> 40)); - sink.WriteByte((byte)(value >> 48)); - sink.WriteByte((byte)(value >> 56)); + m_Sink.WriteByte((byte)value); + m_Sink.WriteByte((byte)(value >> 8)); + m_Sink.WriteByte((byte)(value >> 16)); + m_Sink.WriteByte((byte)(value >> 24)); + m_Sink.WriteByte((byte)(value >> 32)); + m_Sink.WriteByte((byte)(value >> 40)); + m_Sink.WriteByte((byte)(value >> 48)); + m_Sink.WriteByte((byte)(value >> 56)); } /// @@ -722,7 +720,7 @@ public void WriteUInt64Packed(ulong value) /// Value to write public void WriteByte(byte value) { - sink.WriteByte(value); + m_Sink.WriteByte(value); } // As it turns out, strings cannot be treated as char arrays, since strings use pointers to store data rather than C# arrays @@ -736,8 +734,10 @@ public void WriteString(string s, bool oneByteChars = false) WriteUInt32Packed((uint)s.Length); int target = s.Length; for (int i = 0; i < target; ++i) + { if (oneByteChars) WriteByte((byte)s[i]); else WriteChar(s[i]); + } } /// @@ -855,7 +855,7 @@ private ulong WriteArraySize(Array a1, Array a2, long length) public void WriteByteArray(byte[] b, long count = -1) { ulong target = WriteArraySize(b, null, count); - for (ulong i = 0; i < target; ++i) sink.WriteByte(b[i]); + for (ulong i = 0; i < target; ++i) m_Sink.WriteByte(b[i]); } @@ -1271,7 +1271,7 @@ public void WriteDoubleArrayDiff(double[] write, double[] compare, long count = /// The amount of elements to write public void WriteArrayPacked(Array a, long count = -1) { - Type arrayType = a.GetType(); + var arrayType = a.GetType(); #if ARRAY_WRITE_PERMISSIVE @@ -1298,7 +1298,7 @@ public void WriteArrayPacked(Array a, long count = -1) /// The amount of elements to write public void WriteArrayPackedDiff(Array write, Array compare, long count = -1) { - Type arrayType = write.GetType(); + var arrayType = write.GetType(); if (arrayType != compare.GetType()) throw new ArrayTypeMismatchException("Cannot write diff of two differing array types"); #if ARRAY_WRITE_PERMISSIVE diff --git a/com.unity.multiplayer.mlapi/Runtime/Serialization/Pooled/NetworkBufferPool.cs b/com.unity.multiplayer.mlapi/Runtime/Serialization/Pooled/NetworkBufferPool.cs index 02d636fc55..dc96d337e5 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Serialization/Pooled/NetworkBufferPool.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Serialization/Pooled/NetworkBufferPool.cs @@ -10,8 +10,8 @@ namespace MLAPI.Serialization.Pooled public static class NetworkBufferPool { private static uint s_CreatedBuffers = 0; - private static readonly Queue k_OverflowBuffers = new Queue(); - private static readonly Queue k_Buffers = new Queue(); + private static Queue s_OverflowBuffers = new Queue(); + private static Queue s_Buffers = new Queue(); private const uint k_MaxBitPoolBuffers = 1024; private const uint k_MaxCreatedDelta = 768; @@ -23,9 +23,9 @@ public static class NetworkBufferPool /// An expandable PooledNetworkBuffer public static PooledNetworkBuffer GetBuffer() { - if (k_Buffers.Count == 0) + if (s_Buffers.Count == 0) { - if (k_OverflowBuffers.Count > 0) + if (s_OverflowBuffers.Count > 0) { if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) { @@ -33,7 +33,7 @@ public static PooledNetworkBuffer GetBuffer() } object weakBuffer = null; - while (k_OverflowBuffers.Count > 0 && ((weakBuffer = k_OverflowBuffers.Dequeue().Target) == null)) ; + while (s_OverflowBuffers.Count > 0 && ((weakBuffer = s_OverflowBuffers.Dequeue().Target) == null)) ; if (weakBuffer != null) { @@ -55,7 +55,7 @@ public static PooledNetworkBuffer GetBuffer() return new PooledNetworkBuffer(); } - PooledNetworkBuffer buffer = k_Buffers.Dequeue(); + PooledNetworkBuffer buffer = s_Buffers.Dequeue(); buffer.SetLength(0); buffer.Position = 0; @@ -68,7 +68,7 @@ public static PooledNetworkBuffer GetBuffer() /// The buffer to put in the pool public static void PutBackInPool(PooledNetworkBuffer buffer) { - if (k_Buffers.Count > k_MaxCreatedDelta) + if (s_Buffers.Count > k_MaxCreatedDelta) { // The user just created lots of buffers without returning them in between. // Buffers are essentially byte array wrappers. This is valuable memory. @@ -79,11 +79,11 @@ public static void PutBackInPool(PooledNetworkBuffer buffer) NetworkLog.LogInfo($"Putting {nameof(PooledNetworkBuffer)} into overflow pool. Did you forget to dispose?"); } - k_OverflowBuffers.Enqueue(new WeakReference(buffer)); + s_OverflowBuffers.Enqueue(new WeakReference(buffer)); } else { - k_Buffers.Enqueue(buffer); + s_Buffers.Enqueue(buffer); } } } diff --git a/com.unity.multiplayer.mlapi/Runtime/Serialization/Pooled/NetworkReaderPool.cs b/com.unity.multiplayer.mlapi/Runtime/Serialization/Pooled/NetworkReaderPool.cs index 0b5668b789..96d248f6e4 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Serialization/Pooled/NetworkReaderPool.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Serialization/Pooled/NetworkReaderPool.cs @@ -9,8 +9,8 @@ namespace MLAPI.Serialization.Pooled /// public static class NetworkReaderPool { - private static byte createdReaders = 0; - private static readonly Queue readers = new Queue(); + private static byte s_CreatedReaders = 0; + private static Queue s_Readers = new Queue(); /// /// Retrieves a PooledNetworkReader @@ -19,18 +19,18 @@ public static class NetworkReaderPool /// A PooledNetworkReader public static PooledNetworkReader GetReader(Stream stream) { - if (readers.Count == 0) + if (s_Readers.Count == 0) { - if (createdReaders == 254) + if (s_CreatedReaders == 254) { if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("255 readers have been created. Did you forget to dispose?"); } - else if (createdReaders < 255) createdReaders++; + else if (s_CreatedReaders < 255) s_CreatedReaders++; return new PooledNetworkReader(stream); } - PooledNetworkReader reader = readers.Dequeue(); + PooledNetworkReader reader = s_Readers.Dequeue(); reader.SetStream(stream); return reader; @@ -42,7 +42,7 @@ public static PooledNetworkReader GetReader(Stream stream) /// The reader to put in the pool public static void PutBackInPool(PooledNetworkReader reader) { - if (readers.Count < 64) readers.Enqueue(reader); + if (s_Readers.Count < 64) s_Readers.Enqueue(reader); else if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) { NetworkLog.LogInfo($"{nameof(NetworkReaderPool)} already has 64 queued. Throwing to GC. Did you forget to dispose?"); diff --git a/com.unity.multiplayer.mlapi/Runtime/Serialization/Pooled/NetworkWriterPool.cs b/com.unity.multiplayer.mlapi/Runtime/Serialization/Pooled/NetworkWriterPool.cs index 830d38fb59..5e4b19ae13 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Serialization/Pooled/NetworkWriterPool.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Serialization/Pooled/NetworkWriterPool.cs @@ -9,8 +9,8 @@ namespace MLAPI.Serialization.Pooled /// public static class NetworkWriterPool { - private static byte createdWriters = 0; - private static readonly Queue writers = new Queue(); + private static byte s_CreatedWriters = 0; + private static Queue s_Writers = new Queue(); /// /// Retrieves a PooledNetworkWriter @@ -19,18 +19,18 @@ public static class NetworkWriterPool /// A PooledNetworkWriter public static PooledNetworkWriter GetWriter(Stream stream) { - if (writers.Count == 0) + if (s_Writers.Count == 0) { - if (createdWriters == 254) + if (s_CreatedWriters == 254) { if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("255 writers have been created. Did you forget to dispose?"); } - else if (createdWriters < 255) createdWriters++; + else if (s_CreatedWriters < 255) s_CreatedWriters++; return new PooledNetworkWriter(stream); } - PooledNetworkWriter writer = writers.Dequeue(); + PooledNetworkWriter writer = s_Writers.Dequeue(); writer.SetStream(stream); return writer; @@ -42,7 +42,7 @@ public static PooledNetworkWriter GetWriter(Stream stream) /// The writer to put in the pool public static void PutBackInPool(PooledNetworkWriter writer) { - if (writers.Count < 64) writers.Enqueue(writer); + if (s_Writers.Count < 64) s_Writers.Enqueue(writer); else if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) { NetworkLog.LogInfo($"{nameof(NetworkWriterPool)} already has 64 queued. Throwing to GC. Did you forget to dispose?"); diff --git a/com.unity.multiplayer.mlapi/Runtime/Serialization/Pooled/PooledNetworkReader.cs b/com.unity.multiplayer.mlapi/Runtime/Serialization/Pooled/PooledNetworkReader.cs index 94d1112ee3..b6477a2119 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Serialization/Pooled/PooledNetworkReader.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Serialization/Pooled/PooledNetworkReader.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using UnityEngine; namespace MLAPI.Serialization.Pooled { @@ -11,7 +12,7 @@ public sealed class PooledNetworkReader : NetworkReader, IDisposable private NetworkSerializer m_Serializer; public NetworkSerializer Serializer => m_Serializer ?? (m_Serializer = new NetworkSerializer(this)); - private bool isDisposed = false; + private bool m_IsDisposed = false; internal PooledNetworkReader(Stream stream) : base(stream) { } @@ -21,8 +22,8 @@ internal PooledNetworkReader(Stream stream) : base(stream) { } /// PooledNetworkReader public static PooledNetworkReader Get(Stream stream) { - PooledNetworkReader reader = NetworkReaderPool.GetReader(stream); - reader.isDisposed = false; + var reader = NetworkReaderPool.GetReader(stream); + reader.m_IsDisposed = false; return reader; } @@ -31,14 +32,14 @@ public static PooledNetworkReader Get(Stream stream) /// public void Dispose() { - if (!isDisposed) + if (!m_IsDisposed) { - isDisposed = true; + m_IsDisposed = true; NetworkReaderPool.PutBackInPool(this); } else { - UnityEngine.Debug.LogWarning("Disposing reader that thinks it is already disposed!"); + Debug.LogWarning("Disposing reader that thinks it is already disposed!"); } } } diff --git a/com.unity.multiplayer.mlapi/Runtime/Serialization/Pooled/PooledNetworkWriter.cs b/com.unity.multiplayer.mlapi/Runtime/Serialization/Pooled/PooledNetworkWriter.cs index 2e8489ad03..000ad5eb81 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Serialization/Pooled/PooledNetworkWriter.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Serialization/Pooled/PooledNetworkWriter.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using UnityEngine; namespace MLAPI.Serialization.Pooled { @@ -11,7 +12,7 @@ public sealed class PooledNetworkWriter : NetworkWriter, IDisposable private NetworkSerializer m_Serializer; public NetworkSerializer Serializer => m_Serializer ?? (m_Serializer = new NetworkSerializer(this)); - private bool isDisposed = false; + private bool m_IsDisposed = false; internal PooledNetworkWriter(Stream stream) : base(stream) { } @@ -21,8 +22,8 @@ internal PooledNetworkWriter(Stream stream) : base(stream) { } /// PooledNetworkWriter public static PooledNetworkWriter Get(Stream stream) { - PooledNetworkWriter writer = NetworkWriterPool.GetWriter(stream); - writer.isDisposed = false; + var writer = NetworkWriterPool.GetWriter(stream); + writer.m_IsDisposed = false; return writer; } @@ -31,14 +32,14 @@ public static PooledNetworkWriter Get(Stream stream) /// public void Dispose() { - if (!isDisposed) + if (!m_IsDisposed) { - isDisposed = true; + m_IsDisposed = true; NetworkWriterPool.PutBackInPool(this); } else { - UnityEngine.Debug.LogError("Writer is being disposed but thinks it is already disposed"); + Debug.LogError("Writer is being disposed but thinks it is already disposed"); } } } diff --git a/com.unity.multiplayer.mlapi/Runtime/Serialization/SerializationManager.cs b/com.unity.multiplayer.mlapi/Runtime/Serialization/SerializationManager.cs index b3dc15529b..b7dbf2b013 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Serialization/SerializationManager.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Serialization/SerializationManager.cs @@ -13,9 +13,9 @@ namespace MLAPI.Serialization /// public static class SerializationManager { - private static readonly Dictionary fieldCache = new Dictionary(); - private static readonly Dictionary cachedExternalSerializers = new Dictionary(); - private static readonly Dictionary cachedExternalDeserializers = new Dictionary(); + private static Dictionary s_FieldCache = new Dictionary(); + private static Dictionary s_CachedExternalSerializers = new Dictionary(); + private static Dictionary s_CachedExternalDeserializers = new Dictionary(); /// /// The delegate used when registering custom deserialization for a type. @@ -46,8 +46,8 @@ public static class SerializationManager /// The type to register. public static void RegisterSerializationHandlers(CustomSerializationDelegate onSerialize, CustomDeserializationDelegate onDeserialize) { - cachedExternalSerializers[typeof(T)] = (stream, instance) => onSerialize(stream, (T)instance); - cachedExternalDeserializers[typeof(T)] = stream => onDeserialize(stream); + s_CachedExternalSerializers[typeof(T)] = (stream, instance) => onSerialize(stream, (T)instance); + s_CachedExternalDeserializers[typeof(T)] = stream => onDeserialize(stream); } /// @@ -58,17 +58,17 @@ public static void RegisterSerializationHandlers(CustomSerializationDelegate< /// Whether or not either the serialization or deserialization handlers for the type was removed. public static bool RemoveSerializationHandlers() { - bool serializationRemoval = cachedExternalSerializers.Remove(typeof(T)); - bool deserializationRemoval = cachedExternalDeserializers.Remove(typeof(T)); + bool serializationRemoval = s_CachedExternalSerializers.Remove(typeof(T)); + bool deserializationRemoval = s_CachedExternalDeserializers.Remove(typeof(T)); return serializationRemoval || deserializationRemoval; } internal static bool TrySerialize(Stream stream, object obj) { - if (cachedExternalSerializers.ContainsKey(obj.GetType())) + if (s_CachedExternalSerializers.ContainsKey(obj.GetType())) { - cachedExternalSerializers[obj.GetType()](stream, obj); + s_CachedExternalSerializers[obj.GetType()](stream, obj); return true; } @@ -77,9 +77,9 @@ internal static bool TrySerialize(Stream stream, object obj) internal static bool TryDeserialize(Stream stream, Type type, out object obj) { - if (cachedExternalDeserializers.ContainsKey(type)) + if (s_CachedExternalDeserializers.ContainsKey(type)) { - obj = cachedExternalDeserializers[type](stream); + obj = s_CachedExternalDeserializers[type](stream); return true; } @@ -89,19 +89,19 @@ internal static bool TryDeserialize(Stream stream, Type type, out object obj) internal static FieldInfo[] GetFieldsForType(Type type) { - if (fieldCache.ContainsKey(type)) return fieldCache[type]; + if (s_FieldCache.ContainsKey(type)) return s_FieldCache[type]; FieldInfo[] fields = type .GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) .Where(x => (x.IsPublic || x.GetCustomAttributes(typeof(SerializeField), true).Length > 0) && IsTypeSupported(x.FieldType)) .OrderBy(x => x.Name, StringComparer.Ordinal).ToArray(); - fieldCache.Add(type, fields); + s_FieldCache.Add(type, fields); return fields; } - private static readonly HashSet SupportedTypes = new HashSet() + private static HashSet s_SupportedTypes = new HashSet() { typeof(byte), typeof(byte), @@ -136,8 +136,8 @@ internal static FieldInfo[] GetFieldsForType(Type type) /// Whether or not the type is supported public static bool IsTypeSupported(Type type) { - return type.IsEnum || SupportedTypes.Contains(type) || type.HasInterface(typeof(INetworkSerializable)) || - (cachedExternalSerializers.ContainsKey(type) && cachedExternalDeserializers.ContainsKey(type)) || + return type.IsEnum || s_SupportedTypes.Contains(type) || type.HasInterface(typeof(INetworkSerializable)) || + (s_CachedExternalSerializers.ContainsKey(type) && s_CachedExternalDeserializers.ContainsKey(type)) || (type.IsArray && type.HasElementType && IsTypeSupported(type.GetElementType())); } } diff --git a/com.unity.multiplayer.mlapi/Runtime/Spawning/NetworkSpawnManager.cs b/com.unity.multiplayer.mlapi/Runtime/Spawning/NetworkSpawnManager.cs index e34cb4bf90..9ac85e9f53 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Spawning/NetworkSpawnManager.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Spawning/NetworkSpawnManager.cs @@ -23,26 +23,30 @@ public static class NetworkSpawnManager /// The currently spawned objects /// public static readonly Dictionary SpawnedObjects = new Dictionary(); + // Pending SoftSync objects - internal static readonly Dictionary pendingSoftSyncObjects = new Dictionary(); + internal static readonly Dictionary PendingSoftSyncObjects = new Dictionary(); + /// /// A list of the spawned objects /// public static readonly HashSet SpawnedObjectsList = new HashSet(); + /// /// The delegate used when spawning a NetworkObject /// /// The position to spawn the object at /// The rotation to spawn the object with public delegate NetworkObject SpawnHandlerDelegate(Vector3 position, Quaternion rotation); + /// /// The delegate used when destroying NetworkObjects /// /// The NetworkObject to be destroy public delegate void DestroyHandlerDelegate(NetworkObject networkObject); - internal static readonly Dictionary customSpawnHandlers = new Dictionary(); - internal static readonly Dictionary customDestroyHandlers = new Dictionary(); + internal static readonly Dictionary CustomSpawnHandlers = new Dictionary(); + internal static readonly Dictionary CustomDestroyHandlers = new Dictionary(); /// /// Registers a delegate for spawning NetworkPrefabs, useful for object pooling @@ -51,13 +55,13 @@ public static class NetworkSpawnManager /// The delegate handler public static void RegisterSpawnHandler(ulong prefabHash, SpawnHandlerDelegate handler) { - if (customSpawnHandlers.ContainsKey(prefabHash)) + if (CustomSpawnHandlers.ContainsKey(prefabHash)) { - customSpawnHandlers[prefabHash] = handler; + CustomSpawnHandlers[prefabHash] = handler; } else { - customSpawnHandlers.Add(prefabHash, handler); + CustomSpawnHandlers.Add(prefabHash, handler); } } @@ -68,13 +72,13 @@ public static void RegisterSpawnHandler(ulong prefabHash, SpawnHandlerDelegate h /// The delegate handler public static void RegisterCustomDestroyHandler(ulong prefabHash, DestroyHandlerDelegate handler) { - if (customDestroyHandlers.ContainsKey(prefabHash)) + if (CustomDestroyHandlers.ContainsKey(prefabHash)) { - customDestroyHandlers[prefabHash] = handler; + CustomDestroyHandlers[prefabHash] = handler; } else { - customDestroyHandlers.Add(prefabHash, handler); + CustomDestroyHandlers.Add(prefabHash, handler); } } @@ -84,7 +88,7 @@ public static void RegisterCustomDestroyHandler(ulong prefabHash, DestroyHandler /// The prefab hash of the prefab spawn handler that is to be removed public static void RemoveCustomSpawnHandler(ulong prefabHash) { - customSpawnHandlers.Remove(prefabHash); + CustomSpawnHandlers.Remove(prefabHash); } /// @@ -93,22 +97,22 @@ public static void RemoveCustomSpawnHandler(ulong prefabHash) /// The prefab hash of the prefab destroy handler that is to be removed public static void RemoveCustomDestroyHandler(ulong prefabHash) { - customDestroyHandlers.Remove(prefabHash); + CustomDestroyHandlers.Remove(prefabHash); } - internal static readonly Queue releasedNetworkObjectIds = new Queue(); - private static ulong networkObjectIdCounter; + internal static readonly Queue ReleasedNetworkObjectIds = new Queue(); + private static ulong s_NetworkObjectIdCounter; + internal static ulong GetNetworkObjectId() { - if (releasedNetworkObjectIds.Count > 0 && NetworkManager.Singleton.NetworkConfig.RecycleNetworkIds && (Time.unscaledTime - releasedNetworkObjectIds.Peek().ReleaseTime) >= NetworkManager.Singleton.NetworkConfig.NetworkIdRecycleDelay) - { - return releasedNetworkObjectIds.Dequeue().NetworkId; - } - else + if (ReleasedNetworkObjectIds.Count > 0 && NetworkManager.Singleton.NetworkConfig.RecycleNetworkIds && (Time.unscaledTime - ReleasedNetworkObjectIds.Peek().ReleaseTime) >= NetworkManager.Singleton.NetworkConfig.NetworkIdRecycleDelay) { - networkObjectIdCounter++; - return networkObjectIdCounter; + return ReleasedNetworkObjectIds.Dequeue().NetworkId; } + + s_NetworkObjectIdCounter++; + + return s_NetworkObjectIdCounter; } /// @@ -121,7 +125,9 @@ public static int GetNetworkPrefabIndexOfHash(ulong hash) for (int i = 0; i < NetworkManager.Singleton.NetworkConfig.NetworkPrefabs.Count; i++) { if (NetworkManager.Singleton.NetworkConfig.NetworkPrefabs[i].Hash == hash) + { return i; + } } return -1; @@ -167,82 +173,82 @@ public static NetworkObject GetPlayerNetworkObject(ulong clientId) return NetworkManager.Singleton.ConnectedClients[clientId].PlayerObject; } - internal static void RemoveOwnership(NetworkObject netObject) + internal static void RemoveOwnership(NetworkObject networkObject) { if (!NetworkManager.Singleton.IsServer) { throw new NotServerException("Only the server can change ownership"); } - if (!netObject.IsSpawned) + if (!networkObject.IsSpawned) { throw new SpawnStateException("Object is not spawned"); } - for (int i = NetworkManager.Singleton.ConnectedClients[netObject.OwnerClientId].OwnedObjects.Count - 1; i > -1; i--) + for (int i = NetworkManager.Singleton.ConnectedClients[networkObject.OwnerClientId].OwnedObjects.Count - 1; i > -1; i--) { - if (NetworkManager.Singleton.ConnectedClients[netObject.OwnerClientId].OwnedObjects[i] == netObject) - NetworkManager.Singleton.ConnectedClients[netObject.OwnerClientId].OwnedObjects.RemoveAt(i); + if (NetworkManager.Singleton.ConnectedClients[networkObject.OwnerClientId].OwnedObjects[i] == networkObject) + { + NetworkManager.Singleton.ConnectedClients[networkObject.OwnerClientId].OwnedObjects.RemoveAt(i); + } } - netObject._ownerClientId = null; + networkObject.OwnerClientIdInternal = null; - using (PooledNetworkBuffer buffer = PooledNetworkBuffer.Get()) + using (var buffer = PooledNetworkBuffer.Get()) + using (var writer = PooledNetworkWriter.Get(buffer)) { - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(buffer)) - { - writer.WriteUInt64Packed(netObject.NetworkObjectId); - writer.WriteUInt64Packed(netObject.OwnerClientId); + writer.WriteUInt64Packed(networkObject.NetworkObjectId); + writer.WriteUInt64Packed(networkObject.OwnerClientId); - InternalMessageSender.Send(NetworkConstants.CHANGE_OWNER, NetworkChannel.Internal, buffer); - } + InternalMessageSender.Send(NetworkConstants.CHANGE_OWNER, NetworkChannel.Internal, buffer); } } - internal static void ChangeOwnership(NetworkObject netObject, ulong clientId) + internal static void ChangeOwnership(NetworkObject networkObject, ulong clientId) { if (!NetworkManager.Singleton.IsServer) { throw new NotServerException("Only the server can change ownership"); } - if (!netObject.IsSpawned) + if (!networkObject.IsSpawned) { throw new SpawnStateException("Object is not spawned"); } - if (NetworkManager.Singleton.ConnectedClients.ContainsKey(netObject.OwnerClientId)) + if (NetworkManager.Singleton.ConnectedClients.ContainsKey(networkObject.OwnerClientId)) { - for (int i = NetworkManager.Singleton.ConnectedClients[netObject.OwnerClientId].OwnedObjects.Count - 1; i >= 0; i--) + for (int i = NetworkManager.Singleton.ConnectedClients[networkObject.OwnerClientId].OwnedObjects.Count - 1; i >= 0; i--) { - if (NetworkManager.Singleton.ConnectedClients[netObject.OwnerClientId].OwnedObjects[i] == netObject) - NetworkManager.Singleton.ConnectedClients[netObject.OwnerClientId].OwnedObjects.RemoveAt(i); + if (NetworkManager.Singleton.ConnectedClients[networkObject.OwnerClientId].OwnedObjects[i] == networkObject) + { + NetworkManager.Singleton.ConnectedClients[networkObject.OwnerClientId].OwnedObjects.RemoveAt(i); + } } } - NetworkManager.Singleton.ConnectedClients[clientId].OwnedObjects.Add(netObject); - netObject.OwnerClientId = clientId; + NetworkManager.Singleton.ConnectedClients[clientId].OwnedObjects.Add(networkObject); + networkObject.OwnerClientId = clientId; - using (PooledNetworkBuffer buffer = PooledNetworkBuffer.Get()) + using (var buffer = PooledNetworkBuffer.Get()) + using (var writer = PooledNetworkWriter.Get(buffer)) { - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(buffer)) - { - writer.WriteUInt64Packed(netObject.NetworkObjectId); - writer.WriteUInt64Packed(clientId); + writer.WriteUInt64Packed(networkObject.NetworkObjectId); + writer.WriteUInt64Packed(clientId); - InternalMessageSender.Send(NetworkConstants.CHANGE_OWNER, NetworkChannel.Internal, buffer); - } + InternalMessageSender.Send(NetworkConstants.CHANGE_OWNER, NetworkChannel.Internal, buffer); } } // Only ran on Client internal static NetworkObject CreateLocalNetworkObject(bool softCreate, ulong instanceId, ulong prefabHash, ulong? parentNetworkId, Vector3? position, Quaternion? rotation) { - NetworkObject parent = null; + NetworkObject parentNetworkObject = null; if (parentNetworkId != null && SpawnedObjects.ContainsKey(parentNetworkId.Value)) { - parent = SpawnedObjects[parentNetworkId.Value]; + parentNetworkObject = SpawnedObjects[parentNetworkId.Value]; } else if (parentNetworkId != null) { @@ -252,16 +258,16 @@ internal static NetworkObject CreateLocalNetworkObject(bool softCreate, ulong in if (!NetworkManager.Singleton.NetworkConfig.EnableSceneManagement || NetworkManager.Singleton.NetworkConfig.UsePrefabSync || !softCreate) { // Create the object - if (customSpawnHandlers.ContainsKey(prefabHash)) + if (CustomSpawnHandlers.ContainsKey(prefabHash)) { - NetworkObject networkObject = customSpawnHandlers[prefabHash](position.GetValueOrDefault(Vector3.zero), rotation.GetValueOrDefault(Quaternion.identity)); + var networkObject = CustomSpawnHandlers[prefabHash](position.GetValueOrDefault(Vector3.zero), rotation.GetValueOrDefault(Quaternion.identity)); - if (!ReferenceEquals(parent, null)) + if (!ReferenceEquals(parentNetworkObject, null)) { - networkObject.transform.SetParent(parent.transform, true); + networkObject.transform.SetParent(parentNetworkObject.transform, true); } - if (NetworkSceneManager.isSpawnedObjectsPendingInDontDestroyOnLoad) + if (NetworkSceneManager.IsSpawnedObjectsPendingInDontDestroyOnLoad) { GameObject.DontDestroyOnLoad(networkObject.gameObject); } @@ -276,47 +282,47 @@ internal static NetworkObject CreateLocalNetworkObject(bool softCreate, ulong in { if (NetworkLog.CurrentLogLevel <= LogLevel.Error) { - NetworkLog.LogError("Failed to create object locally. [PrefabHash=" + prefabHash + "]. Hash could not be found. Is the prefab registered?"); + NetworkLog.LogError($"Failed to create object locally. [{nameof(prefabHash)}={prefabHash}]. Hash could not be found. Is the prefab registered?"); } return null; } - else - { - GameObject prefab = NetworkManager.Singleton.NetworkConfig.NetworkPrefabs[prefabIndex].Prefab; - NetworkObject networkObject = ((position == null && rotation == null) ? MonoBehaviour.Instantiate(prefab) : MonoBehaviour.Instantiate(prefab, position.GetValueOrDefault(Vector3.zero), rotation.GetValueOrDefault(Quaternion.identity))).GetComponent(); + var prefab = NetworkManager.Singleton.NetworkConfig.NetworkPrefabs[prefabIndex].Prefab; + var networkObject = ((position == null && rotation == null) ? MonoBehaviour.Instantiate(prefab) : MonoBehaviour.Instantiate(prefab, position.GetValueOrDefault(Vector3.zero), rotation.GetValueOrDefault(Quaternion.identity))).GetComponent(); - if (!ReferenceEquals(parent, null)) - { - networkObject.transform.SetParent(parent.transform, true); - } - - if (NetworkSceneManager.isSpawnedObjectsPendingInDontDestroyOnLoad) - { - GameObject.DontDestroyOnLoad(networkObject.gameObject); - } + if (!ReferenceEquals(parentNetworkObject, null)) + { + networkObject.transform.SetParent(parentNetworkObject.transform, true); + } - return networkObject; + if (NetworkSceneManager.IsSpawnedObjectsPendingInDontDestroyOnLoad) + { + GameObject.DontDestroyOnLoad(networkObject.gameObject); } + + return networkObject; } } else { // SoftSync them by mapping - if (!pendingSoftSyncObjects.ContainsKey(instanceId)) + if (!PendingSoftSyncObjects.ContainsKey(instanceId)) { // TODO: Fix this message - if (NetworkLog.CurrentLogLevel <= LogLevel.Error) NetworkLog.LogError("Cannot find pending soft sync object. Is the projects the same?"); + if (NetworkLog.CurrentLogLevel <= LogLevel.Error) + { + NetworkLog.LogError("Cannot find pending soft sync object. Is the projects the same?"); + } return null; } - NetworkObject networkObject = pendingSoftSyncObjects[instanceId]; - pendingSoftSyncObjects.Remove(instanceId); + var networkObject = PendingSoftSyncObjects[instanceId]; + PendingSoftSyncObjects.Remove(instanceId); - if (!ReferenceEquals(parent, null)) + if (!ReferenceEquals(parentNetworkObject, null)) { - networkObject.transform.SetParent(parent.transform, true); + networkObject.transform.SetParent(parentNetworkObject.transform, true); } return networkObject; @@ -324,37 +330,37 @@ internal static NetworkObject CreateLocalNetworkObject(bool softCreate, ulong in } // Ran on both server and client - internal static void SpawnNetworkObjectLocally(NetworkObject netObject, ulong networkId, bool sceneObject, bool playerObject, ulong? ownerClientId, Stream dataStream, bool readPayload, int payloadLength, bool readNetworkVariable, bool destroyWithScene) + internal static void SpawnNetworkObjectLocally(NetworkObject networkObject, ulong networkId, bool sceneObject, bool playerObject, ulong? ownerClientId, Stream dataStream, bool readPayload, int payloadLength, bool readNetworkVariable, bool destroyWithScene) { - if (ReferenceEquals(netObject, null)) + if (ReferenceEquals(networkObject, null)) { - throw new ArgumentNullException(nameof(netObject), "Cannot spawn null object"); + throw new ArgumentNullException(nameof(networkObject), "Cannot spawn null object"); } - if (netObject.IsSpawned) + if (networkObject.IsSpawned) { throw new SpawnStateException("Object is already spawned"); } if (readNetworkVariable && NetworkManager.Singleton.NetworkConfig.EnableNetworkVariable) { - netObject.SetNetworkVariableData(dataStream); + networkObject.SetNetworkVariableData(dataStream); } - if (SpawnedObjects.ContainsKey(netObject.NetworkObjectId)) return; + if (SpawnedObjects.ContainsKey(networkObject.NetworkObjectId)) return; - netObject.IsSpawned = true; + networkObject.IsSpawned = true; - netObject.IsSceneObject = sceneObject; - netObject.NetworkObjectId = networkId; + networkObject.IsSceneObject = sceneObject; + networkObject.NetworkObjectId = networkId; - netObject.DestroyWithScene = sceneObject || destroyWithScene; + networkObject.DestroyWithScene = sceneObject || destroyWithScene; - netObject._ownerClientId = ownerClientId; - netObject.IsPlayerObject = playerObject; + networkObject.OwnerClientIdInternal = ownerClientId; + networkObject.IsPlayerObject = playerObject; - SpawnedObjects.Add(netObject.NetworkObjectId, netObject); - SpawnedObjectsList.Add(netObject); + SpawnedObjects.Add(networkObject.NetworkObjectId, networkObject); + SpawnedObjectsList.Add(networkObject); if (ownerClientId != null) { @@ -362,16 +368,16 @@ internal static void SpawnNetworkObjectLocally(NetworkObject netObject, ulong ne { if (playerObject) { - NetworkManager.Singleton.ConnectedClients[ownerClientId.Value].PlayerObject = netObject; + NetworkManager.Singleton.ConnectedClients[ownerClientId.Value].PlayerObject = networkObject; } else { - NetworkManager.Singleton.ConnectedClients[ownerClientId.Value].OwnedObjects.Add(netObject); + NetworkManager.Singleton.ConnectedClients[ownerClientId.Value].OwnedObjects.Add(networkObject); } } else if (playerObject && ownerClientId.Value == NetworkManager.Singleton.LocalClientId) { - NetworkManager.Singleton.ConnectedClients[ownerClientId.Value].PlayerObject = netObject; + NetworkManager.Singleton.ConnectedClients[ownerClientId.Value].PlayerObject = networkObject; } } @@ -379,32 +385,32 @@ internal static void SpawnNetworkObjectLocally(NetworkObject netObject, ulong ne { for (int i = 0; i < NetworkManager.Singleton.ConnectedClientsList.Count; i++) { - if (netObject.CheckObjectVisibility == null || netObject.CheckObjectVisibility(NetworkManager.Singleton.ConnectedClientsList[i].ClientId)) + if (networkObject.CheckObjectVisibility == null || networkObject.CheckObjectVisibility(NetworkManager.Singleton.ConnectedClientsList[i].ClientId)) { - netObject.observers.Add(NetworkManager.Singleton.ConnectedClientsList[i].ClientId); + networkObject.m_Observers.Add(NetworkManager.Singleton.ConnectedClientsList[i].ClientId); } } } - netObject.ResetNetworkStartInvoked(); + networkObject.ResetNetworkStartInvoked(); if (readPayload) { - using (PooledNetworkBuffer payloadBuffer = PooledNetworkBuffer.Get()) + using (var payloadBuffer = PooledNetworkBuffer.Get()) { payloadBuffer.CopyUnreadFrom(dataStream, payloadLength); dataStream.Position += payloadLength; payloadBuffer.Position = 0; - netObject.InvokeBehaviourNetworkSpawn(payloadBuffer); + networkObject.InvokeBehaviourNetworkSpawn(payloadBuffer); } } else { - netObject.InvokeBehaviourNetworkSpawn(null); + networkObject.InvokeBehaviourNetworkSpawn(null); } } - internal static void SendSpawnCallForObject(ulong clientId, NetworkObject netObject, Stream payload) + internal static void SendSpawnCallForObject(ulong clientId, NetworkObject networkObject, Stream payload) { //Currently, if this is called and the clientId (destination) is the server's client Id, this case //will be checked within the below Send function. To avoid unwarranted allocation of a PooledNetworkBuffer @@ -414,77 +420,78 @@ internal static void SendSpawnCallForObject(ulong clientId, NetworkObject netObj return; } - RpcQueueContainer rpcQueueContainer = NetworkManager.Singleton.rpcQueueContainer; + var rpcQueueContainer = NetworkManager.Singleton.RpcQueueContainer; - var stream = PooledNetworkBuffer.Get(); - WriteSpawnCallForObject(stream, clientId, netObject, payload); + var buffer = PooledNetworkBuffer.Get(); + WriteSpawnCallForObject(buffer, clientId, networkObject, payload); var queueItem = new RpcFrameQueueItem { - updateStage = NetworkUpdateStage.Update, - queueItemType = RpcQueueContainer.QueueItemType.CreateObject, - networkId = 0, - itemBuffer = stream, - networkChannel = NetworkChannel.Internal, - clientIds = new[] {clientId} + UpdateStage = NetworkUpdateStage.Update, + QueueItemType = RpcQueueContainer.QueueItemType.CreateObject, + NetworkId = 0, + NetworkBuffer = buffer, + NetworkChannel = NetworkChannel.Internal, + ClientNetworkIds = new[] { clientId } }; rpcQueueContainer.AddToInternalMLAPISendQueue(queueItem); } - internal static void WriteSpawnCallForObject(Serialization.NetworkBuffer buffer, ulong clientId, NetworkObject netObject, Stream payload) + internal static void WriteSpawnCallForObject(Serialization.NetworkBuffer buffer, ulong clientId, NetworkObject networkObject, Stream payload) { - using (PooledNetworkWriter writer = PooledNetworkWriter.Get(buffer)) + using (var writer = PooledNetworkWriter.Get(buffer)) { - writer.WriteBool(netObject.IsPlayerObject); - writer.WriteUInt64Packed(netObject.NetworkObjectId); - writer.WriteUInt64Packed(netObject.OwnerClientId); + writer.WriteBool(networkObject.IsPlayerObject); + writer.WriteUInt64Packed(networkObject.NetworkObjectId); + writer.WriteUInt64Packed(networkObject.OwnerClientId); - NetworkObject parent = null; + NetworkObject parentNetworkObject = null; - if (!netObject.AlwaysReplicateAsRoot && netObject.transform.parent != null) + if (!networkObject.AlwaysReplicateAsRoot && !ReferenceEquals(networkObject.transform.parent, null)) { - parent = netObject.transform.parent.GetComponent(); + parentNetworkObject = networkObject.transform.parent.GetComponent(); } - if (parent == null) + if (ReferenceEquals(parentNetworkObject, null)) { writer.WriteBool(false); } else { writer.WriteBool(true); - writer.WriteUInt64Packed(parent.NetworkObjectId); + writer.WriteUInt64Packed(parentNetworkObject.NetworkObjectId); } if (!NetworkManager.Singleton.NetworkConfig.EnableSceneManagement || NetworkManager.Singleton.NetworkConfig.UsePrefabSync) { - writer.WriteUInt64Packed(netObject.PrefabHash); + writer.WriteUInt64Packed(networkObject.PrefabHash); } else { - writer.WriteBool(netObject.IsSceneObject == null ? true : netObject.IsSceneObject.Value); + writer.WriteBool(networkObject.IsSceneObject ?? true); - if (netObject.IsSceneObject == null || netObject.IsSceneObject.Value) + if (networkObject.IsSceneObject == null || networkObject.IsSceneObject.Value) { - writer.WriteUInt64Packed(netObject.NetworkInstanceId); + writer.WriteUInt64Packed(networkObject.NetworkInstanceId); } else { - writer.WriteUInt64Packed(netObject.PrefabHash); + writer.WriteUInt64Packed(networkObject.PrefabHash); } } - if (netObject.IncludeTransformWhenSpawning == null || netObject.IncludeTransformWhenSpawning(clientId)) + if (networkObject.IncludeTransformWhenSpawning == null || networkObject.IncludeTransformWhenSpawning(clientId)) { writer.WriteBool(true); - writer.WriteSinglePacked(netObject.transform.position.x); - writer.WriteSinglePacked(netObject.transform.position.y); - writer.WriteSinglePacked(netObject.transform.position.z); + writer.WriteSinglePacked(networkObject.transform.position.x); + writer.WriteSinglePacked(networkObject.transform.position.y); + writer.WriteSinglePacked(networkObject.transform.position.z); - writer.WriteSinglePacked(netObject.transform.rotation.eulerAngles.x); - writer.WriteSinglePacked(netObject.transform.rotation.eulerAngles.y); - writer.WriteSinglePacked(netObject.transform.rotation.eulerAngles.z); - } else + writer.WriteSinglePacked(networkObject.transform.rotation.eulerAngles.x); + writer.WriteSinglePacked(networkObject.transform.rotation.eulerAngles.y); + writer.WriteSinglePacked(networkObject.transform.rotation.eulerAngles.z); + } + else { writer.WriteBool(false); } @@ -493,21 +500,21 @@ internal static void WriteSpawnCallForObject(Serialization.NetworkBuffer buffer, if (payload != null) { - writer.WriteInt32Packed((int) payload.Length); + writer.WriteInt32Packed((int)payload.Length); } if (NetworkManager.Singleton.NetworkConfig.EnableNetworkVariable) { - netObject.WriteNetworkVariableData(buffer, clientId); + networkObject.WriteNetworkVariableData(buffer, clientId); } if (payload != null) buffer.CopyFrom(payload); } } - internal static void DespawnObject(NetworkObject netObject, bool destroyObject = false) + internal static void DespawnObject(NetworkObject networkObject, bool destroyObject = false) { - if (!netObject.IsSpawned) + if (!networkObject.IsSpawned) { throw new SpawnStateException("Object is not spawned"); } @@ -517,7 +524,7 @@ internal static void DespawnObject(NetworkObject netObject, bool destroyObject = throw new NotServerException("Only server can despawn objects"); } - OnDestroyObject(netObject.NetworkObjectId, destroyObject); + OnDestroyObject(networkObject.NetworkObjectId, destroyObject); } // Makes scene objects ready to be reused @@ -540,9 +547,9 @@ internal static void ServerDestroySpawnedSceneObjects() { if ((sobj.IsSceneObject != null && sobj.IsSceneObject == true) || sobj.DestroyWithScene) { - if (customDestroyHandlers.ContainsKey(sobj.PrefabHash)) + if (CustomDestroyHandlers.ContainsKey(sobj.PrefabHash)) { - customDestroyHandlers[sobj.PrefabHash](sobj); + CustomDestroyHandlers[sobj.PrefabHash](sobj); OnDestroyObject(sobj.NetworkObjectId, false); } else @@ -555,20 +562,20 @@ internal static void ServerDestroySpawnedSceneObjects() internal static void DestroyNonSceneObjects() { - NetworkObject[] netObjects = MonoBehaviour.FindObjectsOfType(); + var networkObjects = MonoBehaviour.FindObjectsOfType(); - for (int i = 0; i < netObjects.Length; i++) + for (int i = 0; i < networkObjects.Length; i++) { - if (netObjects[i].IsSceneObject != null && netObjects[i].IsSceneObject.Value == false) + if (networkObjects[i].IsSceneObject != null && networkObjects[i].IsSceneObject.Value == false) { - if (customDestroyHandlers.ContainsKey(netObjects[i].PrefabHash)) + if (CustomDestroyHandlers.ContainsKey(networkObjects[i].PrefabHash)) { - customDestroyHandlers[netObjects[i].PrefabHash](netObjects[i]); - OnDestroyObject(netObjects[i].NetworkObjectId, false); + CustomDestroyHandlers[networkObjects[i].PrefabHash](networkObjects[i]); + OnDestroyObject(networkObjects[i].NetworkObjectId, false); } else { - MonoBehaviour.Destroy(netObjects[i].gameObject); + MonoBehaviour.Destroy(networkObjects[i].gameObject); } } } @@ -576,20 +583,20 @@ internal static void DestroyNonSceneObjects() internal static void DestroySceneObjects() { - NetworkObject[] netObjects = MonoBehaviour.FindObjectsOfType(); + var networkObjects = MonoBehaviour.FindObjectsOfType(); - for (int i = 0; i < netObjects.Length; i++) + for (int i = 0; i < networkObjects.Length; i++) { - if (netObjects[i].IsSceneObject == null || netObjects[i].IsSceneObject.Value == true) + if (networkObjects[i].IsSceneObject == null || networkObjects[i].IsSceneObject.Value == true) { - if (customDestroyHandlers.ContainsKey(netObjects[i].PrefabHash)) + if (CustomDestroyHandlers.ContainsKey(networkObjects[i].PrefabHash)) { - customDestroyHandlers[netObjects[i].PrefabHash](netObjects[i]); - OnDestroyObject(netObjects[i].NetworkObjectId, false); + CustomDestroyHandlers[networkObjects[i].PrefabHash](networkObjects[i]); + OnDestroyObject(networkObjects[i].NetworkObjectId, false); } else { - MonoBehaviour.Destroy(netObjects[i].gameObject); + MonoBehaviour.Destroy(networkObjects[i].gameObject); } } } @@ -598,18 +605,18 @@ internal static void DestroySceneObjects() internal static void CleanDiffedSceneObjects() { // Clean up the diffed scene objects. I.E scene objects that have been destroyed - if (pendingSoftSyncObjects.Count > 0) + if (PendingSoftSyncObjects.Count > 0) { - List objectsToDestroy = new List(); + var networkObjectsToDestroy = new List(); - foreach (KeyValuePair pair in pendingSoftSyncObjects) + foreach (var pair in PendingSoftSyncObjects) { - objectsToDestroy.Add(pair.Value); + networkObjectsToDestroy.Add(pair.Value); } - for (int i = 0; i < objectsToDestroy.Count; i++) + for (int i = 0; i < networkObjectsToDestroy.Count; i++) { - MonoBehaviour.Destroy(objectsToDestroy[i].gameObject); + MonoBehaviour.Destroy(networkObjectsToDestroy[i].gameObject); } } } @@ -617,6 +624,7 @@ internal static void CleanDiffedSceneObjects() internal static void ServerSpawnSceneObjectsOnStartSweep() { var networkObjects = MonoBehaviour.FindObjectsOfType(); + for (int i = 0; i < networkObjects.Length; i++) { if (networkObjects[i].IsSceneObject == null) @@ -637,7 +645,7 @@ internal static void ClientCollectSoftSyncSceneObjectSweep(NetworkObject[] netwo { if (networkObjects[i].IsSceneObject == null) { - pendingSoftSyncObjects.Add(networkObjects[i].NetworkInstanceId, networkObjects[i]); + PendingSoftSyncObjects.Add(networkObjects[i].NetworkInstanceId, networkObjects[i]); } } } @@ -654,13 +662,16 @@ internal static void OnDestroyObject(ulong networkId, bool destroyGameObject) } var sobj = SpawnedObjects[networkId]; + if (!sobj.IsOwnedByServer && !sobj.IsPlayerObject && NetworkManager.Singleton.ConnectedClients.ContainsKey(sobj.OwnerClientId)) { //Someone owns it. for (int i = NetworkManager.Singleton.ConnectedClients[sobj.OwnerClientId].OwnedObjects.Count - 1; i > -1; i--) { if (NetworkManager.Singleton.ConnectedClients[sobj.OwnerClientId].OwnedObjects[i].NetworkObjectId == networkId) + { NetworkManager.Singleton.ConnectedClients[sobj.OwnerClientId].OwnedObjects.RemoveAt(i); + } } } @@ -670,35 +681,36 @@ internal static void OnDestroyObject(ulong networkId, bool destroyGameObject) { if (NetworkManager.Singleton.NetworkConfig.RecycleNetworkIds) { - releasedNetworkObjectIds.Enqueue(new ReleasedNetworkId() + ReleasedNetworkObjectIds.Enqueue(new ReleasedNetworkId() { NetworkId = networkId, ReleaseTime = Time.unscaledTime }); } - var rpcQueueContainer = NetworkManager.Singleton.rpcQueueContainer; + var rpcQueueContainer = NetworkManager.Singleton.RpcQueueContainer; if (rpcQueueContainer != null) { - if (sobj != null) + if (!ReferenceEquals(sobj, null)) { // As long as we have any remaining clients, then notify of the object being destroy. if (NetworkManager.Singleton.ConnectedClientsList.Count > 0) { - var stream = PooledNetworkBuffer.Get(); - using (var writer = PooledNetworkWriter.Get(stream)) + var buffer = PooledNetworkBuffer.Get(); + using (var writer = PooledNetworkWriter.Get(buffer)) { writer.WriteUInt64Packed(networkId); var queueItem = new RpcFrameQueueItem { - updateStage = NetworkUpdateStage.PostLateUpdate, - queueItemType = RpcQueueContainer.QueueItemType.DestroyObject, - networkId = networkId, - itemBuffer = stream, - networkChannel = NetworkChannel.Internal, - clientIds = NetworkManager.Singleton.ConnectedClientsList.Select(c => c.ClientId).ToArray() + UpdateStage = NetworkUpdateStage.PostLateUpdate, + QueueItemType = RpcQueueContainer.QueueItemType.DestroyObject, + NetworkId = networkId, + NetworkBuffer = buffer, + NetworkChannel = NetworkChannel.Internal, + ClientNetworkIds = NetworkManager.Singleton.ConnectedClientsList.Select(c => c.ClientId).ToArray() }; + rpcQueueContainer.AddToInternalMLAPISendQueue(queueItem); } } @@ -707,11 +719,12 @@ internal static void OnDestroyObject(ulong networkId, bool destroyGameObject) } var gobj = sobj.gameObject; - if (destroyGameObject && gobj != null) + + if (destroyGameObject && !ReferenceEquals(gobj, null)) { - if (customDestroyHandlers.ContainsKey(sobj.PrefabHash)) + if (CustomDestroyHandlers.ContainsKey(sobj.PrefabHash)) { - customDestroyHandlers[sobj.PrefabHash](sobj); + CustomDestroyHandlers[sobj.PrefabHash](sobj); OnDestroyObject(networkId, false); } else @@ -730,4 +743,4 @@ internal static void OnDestroyObject(ulong networkId, bool destroyGameObject) } } } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Transports/MultiplexTransportAdapter.cs b/com.unity.multiplayer.mlapi/Runtime/Transports/MultiplexTransportAdapter.cs index 0a0fe143fd..892930159c 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Transports/MultiplexTransportAdapter.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Transports/MultiplexTransportAdapter.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; using MLAPI.Transports.Tasks; namespace MLAPI.Transports.Multiplex @@ -21,22 +20,26 @@ public enum ConnectionIdSpreadMethod /// For incremental clientIds, this is the most space efficient assuming that every transport get used an equal amount. /// MakeRoomLastBits, + /// /// Drops the first few bits (left side) and replaces them with the transport index. /// Ensure that ALL transports dont use the first few bits in the produced clientId. /// ReplaceFirstBits, + /// /// Drops the last few bits (right side) and replaces them with the transport index. /// Ensure that ALL transports dont use the last bits in their produced clientId. /// This option is for advanced users and will not work with the official MLAPI transports as they use the last bits. /// ReplaceLastBits, + /// /// Drops the last few bits (right side) by shifting the transport clientId to the right and inserting the transportId in the first bits. /// Ensure that ALL transports dont use the first bits in their produced clientId. /// MakeRoomFirstBits, + /// /// Spreads the clientIds evenly among the transports. /// @@ -48,7 +51,7 @@ public enum ConnectionIdSpreadMethod public NetworkTransport[] Transports = new NetworkTransport[0]; public override ulong ServerClientId => 0; - private byte _lastProcessedTransportIndex; + private byte m_LastProcessedTransportIndex; public override bool IsSupported => true; @@ -84,16 +87,18 @@ public override void Init() public override NetworkEvent PollEvent(out ulong clientId, out NetworkChannel networkChannel, out ArraySegment payload, out float receiveTime) { - if (_lastProcessedTransportIndex >= Transports.Length - 1) - _lastProcessedTransportIndex = 0; + if (m_LastProcessedTransportIndex >= Transports.Length - 1) + { + m_LastProcessedTransportIndex = 0; + } - for (byte i = _lastProcessedTransportIndex; i < Transports.Length; i++) + for (byte i = m_LastProcessedTransportIndex; i < Transports.Length; i++) { - _lastProcessedTransportIndex = i; + m_LastProcessedTransportIndex = i; if (Transports[i].IsSupported) { - NetworkEvent networkEvent = Transports[i].PollEvent(out ulong connectionId, out networkChannel, out payload, out receiveTime); + var networkEvent = Transports[i].PollEvent(out ulong connectionId, out networkChannel, out payload, out receiveTime); if (networkEvent != NetworkEvent.Nothing) { @@ -132,7 +137,7 @@ public override void Shutdown() public override SocketTasks StartClient() { - List socketTasks = new List(); + var socketTasks = new List(); for (int i = 0; i < Transports.Length; i++) { @@ -142,15 +147,12 @@ public override SocketTasks StartClient() } } - return new SocketTasks() - { - Tasks = socketTasks.ToArray() - }; + return new SocketTasks { Tasks = socketTasks.ToArray() }; } public override SocketTasks StartServer() { - List socketTasks = new List(); + var socketTasks = new List(); for (int i = 0; i < Transports.Length; i++) { @@ -160,10 +162,7 @@ public override SocketTasks StartServer() } } - return new SocketTasks() - { - Tasks = socketTasks.ToArray() - }; + return new SocketTasks { Tasks = socketTasks.ToArray() }; } @@ -173,66 +172,64 @@ public ulong GetMLAPIClientId(byte transportId, ulong connectionId, bool isServe { return ServerClientId; } - else + + switch (SpreadMethod) { - switch (SpreadMethod) + case ConnectionIdSpreadMethod.ReplaceFirstBits: { - case ConnectionIdSpreadMethod.ReplaceFirstBits: - { - // Calculate bits to store transportId - byte bits = (byte)UnityEngine.Mathf.CeilToInt(UnityEngine.Mathf.Log(Transports.Length, 2)); + // Calculate bits to store transportId + byte bits = (byte)UnityEngine.Mathf.CeilToInt(UnityEngine.Mathf.Log(Transports.Length, 2)); - // Drop first bits of connectionId - ulong clientId = ((connectionId << bits) >> bits); + // Drop first bits of connectionId + ulong clientId = ((connectionId << bits) >> bits); - // Place transportId there - ulong shiftedTransportId = (ulong)transportId << ((sizeof(ulong) * 8) - bits); + // Place transportId there + ulong shiftedTransportId = (ulong)transportId << ((sizeof(ulong) * 8) - bits); - return (clientId | shiftedTransportId) + 1; - } - case ConnectionIdSpreadMethod.MakeRoomFirstBits: - { - // Calculate bits to store transportId - byte bits = (byte)UnityEngine.Mathf.CeilToInt(UnityEngine.Mathf.Log(Transports.Length, 2)); + return (clientId | shiftedTransportId) + 1; + } + case ConnectionIdSpreadMethod.MakeRoomFirstBits: + { + // Calculate bits to store transportId + byte bits = (byte)UnityEngine.Mathf.CeilToInt(UnityEngine.Mathf.Log(Transports.Length, 2)); - // Drop first bits of connectionId - ulong clientId = (connectionId >> bits); + // Drop first bits of connectionId + ulong clientId = (connectionId >> bits); - // Place transportId there - ulong shiftedTransportId = (ulong)transportId << ((sizeof(ulong) * 8) - bits); + // Place transportId there + ulong shiftedTransportId = (ulong)transportId << ((sizeof(ulong) * 8) - bits); - return (clientId | shiftedTransportId) + 1; - } - case ConnectionIdSpreadMethod.ReplaceLastBits: - { - // Calculate bits to store transportId - byte bits = (byte)UnityEngine.Mathf.CeilToInt(UnityEngine.Mathf.Log(Transports.Length, 2)); + return (clientId | shiftedTransportId) + 1; + } + case ConnectionIdSpreadMethod.ReplaceLastBits: + { + // Calculate bits to store transportId + byte bits = (byte)UnityEngine.Mathf.CeilToInt(UnityEngine.Mathf.Log(Transports.Length, 2)); - // Drop the last bits of connectionId - ulong clientId = ((connectionId >> bits) << bits); + // Drop the last bits of connectionId + ulong clientId = ((connectionId >> bits) << bits); - // Return the transport inserted at the end - return (clientId | transportId) + 1; - } - case ConnectionIdSpreadMethod.MakeRoomLastBits: - { - // Calculate bits to store transportId - byte bits = (byte)UnityEngine.Mathf.CeilToInt(UnityEngine.Mathf.Log(Transports.Length, 2)); + // Return the transport inserted at the end + return (clientId | transportId) + 1; + } + case ConnectionIdSpreadMethod.MakeRoomLastBits: + { + // Calculate bits to store transportId + byte bits = (byte)UnityEngine.Mathf.CeilToInt(UnityEngine.Mathf.Log(Transports.Length, 2)); - // Drop the last bits of connectionId - ulong clientId = (connectionId << bits); + // Drop the last bits of connectionId + ulong clientId = (connectionId << bits); - // Return the transport inserted at the end - return (clientId | transportId) + 1; - } - case ConnectionIdSpreadMethod.Spread: - { - return (connectionId * (ulong)Transports.Length + (ulong)transportId) + 1; - } - default: - { - return ServerClientId; - } + // Return the transport inserted at the end + return (clientId | transportId) + 1; + } + case ConnectionIdSpreadMethod.Spread: + { + return (connectionId * (ulong)Transports.Length + (ulong)transportId) + 1; + } + default: + { + return ServerClientId; } } } @@ -249,68 +246,68 @@ public void GetMultiplexTransportDetails(ulong clientId, out byte transportId, o switch (SpreadMethod) { case ConnectionIdSpreadMethod.ReplaceFirstBits: - { - // The first clientId is reserved. Thus every clientId is always offset by 1 - clientId--; + { + // The first clientId is reserved. Thus every clientId is always offset by 1 + clientId--; - // Calculate bits to store transportId - byte bits = (byte)UnityEngine.Mathf.CeilToInt(UnityEngine.Mathf.Log(Transports.Length, 2)); + // Calculate bits to store transportId + byte bits = (byte)UnityEngine.Mathf.CeilToInt(UnityEngine.Mathf.Log(Transports.Length, 2)); - transportId = (byte)(clientId >> ((sizeof(ulong) * 8) - bits)); - connectionId = ((clientId << bits) >> bits); - break; - } + transportId = (byte)(clientId >> ((sizeof(ulong) * 8) - bits)); + connectionId = ((clientId << bits) >> bits); + break; + } case ConnectionIdSpreadMethod.MakeRoomFirstBits: - { - // The first clientId is reserved. Thus every clientId is always offset by 1 - clientId--; + { + // The first clientId is reserved. Thus every clientId is always offset by 1 + clientId--; - // Calculate bits to store transportId - byte bits = (byte)UnityEngine.Mathf.CeilToInt(UnityEngine.Mathf.Log(Transports.Length, 2)); + // Calculate bits to store transportId + byte bits = (byte)UnityEngine.Mathf.CeilToInt(UnityEngine.Mathf.Log(Transports.Length, 2)); - transportId = (byte)(clientId >> ((sizeof(ulong) * 8) - bits)); - connectionId = (clientId << bits); - break; - } + transportId = (byte)(clientId >> ((sizeof(ulong) * 8) - bits)); + connectionId = (clientId << bits); + break; + } case ConnectionIdSpreadMethod.ReplaceLastBits: - { - // The first clientId is reserved. Thus every clientId is always offset by 1 - clientId--; + { + // The first clientId is reserved. Thus every clientId is always offset by 1 + clientId--; - // Calculate bits to store transportId - byte bits = (byte)UnityEngine.Mathf.CeilToInt(UnityEngine.Mathf.Log(Transports.Length, 2)); + // Calculate bits to store transportId + byte bits = (byte)UnityEngine.Mathf.CeilToInt(UnityEngine.Mathf.Log(Transports.Length, 2)); - transportId = (byte)((clientId << ((sizeof(ulong) * 8) - bits)) >> ((sizeof(ulong) * 8) - bits)); - connectionId = ((clientId >> bits) << bits); - break; - } + transportId = (byte)((clientId << ((sizeof(ulong) * 8) - bits)) >> ((sizeof(ulong) * 8) - bits)); + connectionId = ((clientId >> bits) << bits); + break; + } case ConnectionIdSpreadMethod.MakeRoomLastBits: - { - // The first clientId is reserved. Thus every clientId is always offset by 1 - clientId--; + { + // The first clientId is reserved. Thus every clientId is always offset by 1 + clientId--; - // Calculate bits to store transportId - byte bits = (byte)UnityEngine.Mathf.CeilToInt(UnityEngine.Mathf.Log(Transports.Length, 2)); + // Calculate bits to store transportId + byte bits = (byte)UnityEngine.Mathf.CeilToInt(UnityEngine.Mathf.Log(Transports.Length, 2)); - transportId = (byte)((clientId << ((sizeof(ulong) * 8) - bits)) >> ((sizeof(ulong) * 8) - bits)); - connectionId = (clientId >> bits); - break; - } + transportId = (byte)((clientId << ((sizeof(ulong) * 8) - bits)) >> ((sizeof(ulong) * 8) - bits)); + connectionId = (clientId >> bits); + break; + } case ConnectionIdSpreadMethod.Spread: - { - // The first clientId is reserved. Thus every clientId is always offset by 1 - clientId--; - - transportId = (byte)(clientId % (ulong)Transports.Length); - connectionId = (clientId / (ulong)Transports.Length); - break; - } + { + // The first clientId is reserved. Thus every clientId is always offset by 1 + clientId--; + + transportId = (byte)(clientId % (ulong)Transports.Length); + connectionId = (clientId / (ulong)Transports.Length); + break; + } default: - { - transportId = GetFirstSupportedTransportIndex(); - connectionId = Transports[transportId].ServerClientId; - break; - } + { + transportId = GetFirstSupportedTransportIndex(); + connectionId = Transports[transportId].ServerClientId; + break; + } } } } @@ -330,4 +327,4 @@ public byte GetFirstSupportedTransportIndex() #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Transports/NetworkTransport.cs b/com.unity.multiplayer.mlapi/Runtime/Transports/NetworkTransport.cs index 0c727a48ae..e3ef3b76c0 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Transports/NetworkTransport.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Transports/NetworkTransport.cs @@ -48,40 +48,37 @@ public abstract class NetworkTransport : MonoBehaviour /// true if is supported; otherwise, false. public virtual bool IsSupported => true; - private TransportChannel[] _channelsCache = null; + private TransportChannel[] m_ChannelsCache = null; internal void ResetChannelCache() { - _channelsCache = null; + m_ChannelsCache = null; } public TransportChannel[] MLAPI_CHANNELS { get { - if (_channelsCache == null) + if (m_ChannelsCache == null) { - List channels = new List(); + var transportChannels = new List(); - if (OnChannelRegistration != null) - { - OnChannelRegistration(channels); - } + OnChannelRegistration?.Invoke(transportChannels); - _channelsCache = new TransportChannel[MLAPI_INTERNAL_CHANNELS.Length + channels.Count]; + m_ChannelsCache = new TransportChannel[MLAPI_INTERNAL_CHANNELS.Length + transportChannels.Count]; for (int i = 0; i < MLAPI_INTERNAL_CHANNELS.Length; i++) { - _channelsCache[i] = MLAPI_INTERNAL_CHANNELS[i]; + m_ChannelsCache[i] = MLAPI_INTERNAL_CHANNELS[i]; } - for (int i = 0; i < channels.Count; i++) + for (int i = 0; i < transportChannels.Count; i++) { - _channelsCache[i + MLAPI_INTERNAL_CHANNELS.Length] = channels[i]; + m_ChannelsCache[i + MLAPI_INTERNAL_CHANNELS.Length] = transportChannels[i]; } } - return _channelsCache; + return m_ChannelsCache; } } @@ -182,4 +179,4 @@ protected void InvokeOnTransportEvent(NetworkEvent type, ulong clientId, Network /// public abstract void Init(); } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Transports/Tasks/SocketTask.cs b/com.unity.multiplayer.mlapi/Runtime/Transports/Tasks/SocketTask.cs index 88283d6906..ab581d3ce3 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Transports/Tasks/SocketTask.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Transports/Tasks/SocketTask.cs @@ -106,6 +106,7 @@ public class SocketTask /// /// true if is done; otherwise, false. public bool IsDone { get; set; } + /// /// Gets or sets a value indicating whether this is success. /// @@ -118,21 +119,25 @@ public class SocketTask /// /// The transport exception. public Exception TransportException { get; set; } + /// /// Gets or sets the socket error. /// /// The socket error. public SocketError SocketError { get; set; } + /// /// Gets or sets the transport code. /// /// The transport code. public int TransportCode { get; set; } + /// /// Gets or sets the message. /// /// The message. public string Message { get; set; } + /// /// Gets or sets the state. /// @@ -143,7 +148,7 @@ public class SocketTask /// Gets a done task. /// /// The done. - public static SocketTask Done => new SocketTask() + public static SocketTask Done => new SocketTask { IsDone = true, Message = null, @@ -158,7 +163,7 @@ public class SocketTask /// Gets a faulty task. /// /// The fault. - public static SocketTask Fault => new SocketTask() + public static SocketTask Fault => new SocketTask { IsDone = true, Message = null, @@ -173,7 +178,7 @@ public class SocketTask /// Gets a working task. /// /// The working. - public static SocketTask Working => new SocketTask() + public static SocketTask Working => new SocketTask { IsDone = false, Message = null, @@ -188,12 +193,6 @@ public class SocketTask /// Converts to a SocketTasks. /// /// The tasks. - public SocketTasks AsTasks() - { - return new SocketTasks() - { - Tasks = new SocketTask[] { this } - }; - } + public SocketTasks AsTasks() => new SocketTasks { Tasks = new SocketTask[] { this } }; } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Transports/Tests/Editor/TransportTest.cs b/com.unity.multiplayer.mlapi/Runtime/Transports/Tests/Editor/TransportTest.cs index c62d6edcdb..47e405d603 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Transports/Tests/Editor/TransportTest.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Transports/Tests/Editor/TransportTest.cs @@ -30,7 +30,7 @@ public void UNetCustomChannelRegistrationTest() NetworkManager nm = (NetworkManager)o.AddComponent(typeof(NetworkManager)); nm.SetSingleton(); nm.NetworkConfig = new NetworkConfig(); - UnetTransport ut = (UnetTransport)o.AddComponent(typeof(UnetTransport)); + UNetTransport ut = (UNetTransport)o.AddComponent(typeof(UNetTransport)); ut.ServerListenPort = 7777; nm.NetworkConfig.NetworkTransport = ut; @@ -38,7 +38,7 @@ public void UNetCustomChannelRegistrationTest() byte CustomChannel = 0; // test 1: add a legit channel. - ut.Channels.Add(new UnetChannel { Id = NetworkChannel.ChannelUnused + CustomChannel, Type = QosType.Unreliable }); + ut.Channels.Add(new UNetChannel { Id = NetworkChannel.ChannelUnused + CustomChannel, Type = QosType.Unreliable }); try { @@ -54,12 +54,12 @@ public void UNetCustomChannelRegistrationTest() ut.Channels.Clear(); // test 2: add a bogus channel (one that intersects with the MLAPI built-in ones.) Expect failure - ut.Channels.Add(new UnetChannel { Id = NetworkChannel.Internal, Type = QosType.Unreliable }); + ut.Channels.Add(new UNetChannel { Id = NetworkChannel.Internal, Type = QosType.Unreliable }); try { nm.StartServer(); - Assert.Fail("The Unet transport allowed registration of an MLAPI-reserved channel"); + Assert.Fail("The UNet transport allowed registration of an MLAPI-reserved channel"); } catch (Exception ex) { diff --git a/com.unity.multiplayer.mlapi/Runtime/Transports/UNET/ProfilerConstants.cs b/com.unity.multiplayer.mlapi/Runtime/Transports/UNET/ProfilerConstants.cs index 8ade384f09..a32e8b40a0 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Transports/UNET/ProfilerConstants.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Transports/UNET/ProfilerConstants.cs @@ -5,4 +5,4 @@ public static class ProfilerConstants public const string NumberOfTransportSends = nameof(NumberOfTransportSends); public const string NumberOfTransportSendQueues = nameof(NumberOfTransportSendQueues); } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Transports/UNET/RelayTransport.cs b/com.unity.multiplayer.mlapi/Runtime/Transports/UNET/RelayTransport.cs index f397c94097..a2676d0e7d 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Transports/UNET/RelayTransport.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Transports/UNET/RelayTransport.cs @@ -19,12 +19,12 @@ private enum MessageType AddressReport } - private static byte defaultChannelId; - private static int relayConnectionId; - private static bool isClient = false; - private static string address; - private static ushort port; - private static List channels = new List(); + private static byte s_DefaultChannelId; + private static int s_RelayConnectionId; + private static bool s_IsClient = false; + private static string s_Address; + private static ushort s_Port; + private static List s_Channels = new List(); public static bool Enabled { get; set; } = true; public static string RelayAddress { get; set; } = "127.0.0.1"; @@ -36,91 +36,93 @@ public static int Connect(int hostId, string serverAddress, int serverPort, int { if (!Enabled) return UnityEngine.Networking.NetworkTransport.Connect(hostId, serverAddress, serverPort, exceptionConnectionId, out error); - isClient = true; + s_IsClient = true; - RelayTransport.address = serverAddress; - RelayTransport.port = (ushort)serverPort; + s_Address = serverAddress; + s_Port = (ushort)serverPort; - relayConnectionId = UnityEngine.Networking.NetworkTransport.Connect(hostId, RelayAddress, RelayPort, exceptionConnectionId, out error); // Requests connection + s_RelayConnectionId = UnityEngine.Networking.NetworkTransport.Connect(hostId, RelayAddress, RelayPort, exceptionConnectionId, out error); // Requests connection - return relayConnectionId; + return s_RelayConnectionId; } public static int ConnectWithSimulator(int hostId, string serverAddress, int serverPort, int exceptionConnectionId, out byte error, ConnectionSimulatorConfig conf) { if (!Enabled) return UnityEngine.Networking.NetworkTransport.ConnectWithSimulator(hostId, serverAddress, serverPort, exceptionConnectionId, out error, conf); - isClient = true; + s_IsClient = true; - RelayTransport.address = serverAddress; - RelayTransport.port = (ushort)serverPort; + s_Address = serverAddress; + s_Port = (ushort)serverPort; - relayConnectionId = UnityEngine.Networking.NetworkTransport.ConnectWithSimulator(hostId, RelayAddress, RelayPort, exceptionConnectionId, out error, conf); // Requests connection + s_RelayConnectionId = UnityEngine.Networking.NetworkTransport.ConnectWithSimulator(hostId, RelayAddress, RelayPort, exceptionConnectionId, out error, conf); // Requests connection - return relayConnectionId; + return s_RelayConnectionId; } public static int ConnectEndPoint(int hostId, EndPoint endPoint, int exceptionConnectionId, out byte error) { if (!Enabled) return UnityEngine.Networking.NetworkTransport.ConnectEndPoint(hostId, endPoint, exceptionConnectionId, out error); - isClient = true; + s_IsClient = true; - RelayTransport.address = ((IPEndPoint)endPoint).Address.ToString(); - RelayTransport.port = (ushort)((IPEndPoint)endPoint).Port; + s_Address = ((IPEndPoint)endPoint).Address.ToString(); + s_Port = (ushort)((IPEndPoint)endPoint).Port; - relayConnectionId = UnityEngine.Networking.NetworkTransport.Connect(hostId, RelayAddress, RelayPort, exceptionConnectionId, out error); // Requests connection + s_RelayConnectionId = UnityEngine.Networking.NetworkTransport.Connect(hostId, RelayAddress, RelayPort, exceptionConnectionId, out error); // Requests connection - return relayConnectionId; + return s_RelayConnectionId; } - private static void SetChannelsFromTopology(HostTopology topology) => channels = topology.DefaultConfig.Channels; + private static void SetChannelsFromTopology(HostTopology topology) => s_Channels = topology.DefaultConfig.Channels; public static int AddHost(HostTopology topology, bool createServer) { if (!Enabled) return UnityEngine.Networking.NetworkTransport.AddHost(topology, 0, null); - isClient = !createServer; + s_IsClient = !createServer; - defaultChannelId = topology.DefaultConfig.AddChannel(QosType.ReliableSequenced); + s_DefaultChannelId = topology.DefaultConfig.AddChannel(QosType.ReliableSequenced); SetChannelsFromTopology(topology); int ret = UnityEngine.Networking.NetworkTransport.AddHost(topology, 0, null); - if (createServer) relayConnectionId = UnityEngine.Networking.NetworkTransport.Connect(ret, RelayAddress, RelayPort, 0, out byte b); + if (createServer) s_RelayConnectionId = UnityEngine.Networking.NetworkTransport.Connect(ret, RelayAddress, RelayPort, 0, out byte b); return ret; } + public static int AddHost(HostTopology topology, int port, bool createServer) { if (!Enabled) return UnityEngine.Networking.NetworkTransport.AddHost(topology, port); - isClient = !createServer; + s_IsClient = !createServer; - defaultChannelId = topology.DefaultConfig.AddChannel(QosType.ReliableSequenced); + s_DefaultChannelId = topology.DefaultConfig.AddChannel(QosType.ReliableSequenced); SetChannelsFromTopology(topology); int ret = UnityEngine.Networking.NetworkTransport.AddHost(topology, port); - if (createServer) relayConnectionId = UnityEngine.Networking.NetworkTransport.Connect(ret, RelayAddress, RelayPort, 0, out byte b); + if (createServer) s_RelayConnectionId = UnityEngine.Networking.NetworkTransport.Connect(ret, RelayAddress, RelayPort, 0, out byte b); return ret; } + public static int AddHost(HostTopology topology, int port, string ip, bool createServer) { if (!Enabled) return UnityEngine.Networking.NetworkTransport.AddHost(topology, port, ip); - isClient = !createServer; + s_IsClient = !createServer; - defaultChannelId = topology.DefaultConfig.AddChannel(QosType.ReliableSequenced); + s_DefaultChannelId = topology.DefaultConfig.AddChannel(QosType.ReliableSequenced); SetChannelsFromTopology(topology); int ret = UnityEngine.Networking.NetworkTransport.AddHost(topology, port, ip); - if (createServer) relayConnectionId = UnityEngine.Networking.NetworkTransport.Connect(ret, RelayAddress, RelayPort, 0, out byte b); + if (createServer) s_RelayConnectionId = UnityEngine.Networking.NetworkTransport.Connect(ret, RelayAddress, RelayPort, 0, out byte b); return ret; } @@ -129,15 +131,15 @@ public static int AddHostWithSimulator(HostTopology topology, int minTimeout, in { if (!Enabled) return UnityEngine.Networking.NetworkTransport.AddHostWithSimulator(topology, minTimeout, maxTimeout); - isClient = !createServer; + s_IsClient = !createServer; - defaultChannelId = topology.DefaultConfig.AddChannel(QosType.ReliableSequenced); + s_DefaultChannelId = topology.DefaultConfig.AddChannel(QosType.ReliableSequenced); SetChannelsFromTopology(topology); int ret = UnityEngine.Networking.NetworkTransport.AddHostWithSimulator(topology, minTimeout, maxTimeout, port, ip); - if (createServer) relayConnectionId = UnityEngine.Networking.NetworkTransport.Connect(ret, RelayAddress, RelayPort, 0, out byte b); + if (createServer) s_RelayConnectionId = UnityEngine.Networking.NetworkTransport.Connect(ret, RelayAddress, RelayPort, 0, out byte b); return ret; } @@ -146,15 +148,15 @@ public static int AddHostWithSimulator(HostTopology topology, int minTimeout, in { if (!Enabled) return UnityEngine.Networking.NetworkTransport.AddHostWithSimulator(topology, minTimeout, maxTimeout); - isClient = !createServer; + s_IsClient = !createServer; - defaultChannelId = topology.DefaultConfig.AddChannel(QosType.ReliableSequenced); + s_DefaultChannelId = topology.DefaultConfig.AddChannel(QosType.ReliableSequenced); SetChannelsFromTopology(topology); int ret = UnityEngine.Networking.NetworkTransport.AddHostWithSimulator(topology, minTimeout, maxTimeout); - if (createServer) relayConnectionId = UnityEngine.Networking.NetworkTransport.Connect(ret, RelayAddress, RelayPort, 0, out byte b); + if (createServer) s_RelayConnectionId = UnityEngine.Networking.NetworkTransport.Connect(ret, RelayAddress, RelayPort, 0, out byte b); return ret; } @@ -163,13 +165,13 @@ public static int AddHostWithSimulator(HostTopology topology, int minTimeout, in { if (!Enabled) return UnityEngine.Networking.NetworkTransport.AddHostWithSimulator(topology, minTimeout, maxTimeout, port); - isClient = !createServer; + s_IsClient = !createServer; SetChannelsFromTopology(topology); int ret = UnityEngine.Networking.NetworkTransport.AddHostWithSimulator(topology, minTimeout, maxTimeout, port); - if (createServer) relayConnectionId = UnityEngine.Networking.NetworkTransport.Connect(ret, RelayAddress, RelayPort, 0, out byte b); + if (createServer) s_RelayConnectionId = UnityEngine.Networking.NetworkTransport.Connect(ret, RelayAddress, RelayPort, 0, out byte b); return ret; } @@ -178,15 +180,15 @@ public static int AddWebsocketHost(HostTopology topology, int port, bool createS { if (!Enabled) return UnityEngine.Networking.NetworkTransport.AddWebsocketHost(topology, port); - isClient = !createServer; + s_IsClient = !createServer; - defaultChannelId = topology.DefaultConfig.AddChannel(QosType.ReliableSequenced); + s_DefaultChannelId = topology.DefaultConfig.AddChannel(QosType.ReliableSequenced); SetChannelsFromTopology(topology); int ret = UnityEngine.Networking.NetworkTransport.AddWebsocketHost(topology, port); - if (createServer) relayConnectionId = UnityEngine.Networking.NetworkTransport.Connect(ret, RelayAddress, RelayPort, 0, out byte b); + if (createServer) s_RelayConnectionId = UnityEngine.Networking.NetworkTransport.Connect(ret, RelayAddress, RelayPort, 0, out byte b); return ret; } @@ -195,29 +197,30 @@ public static int AddWebsocketHost(HostTopology topology, int port, string ip, b { if (!Enabled) return UnityEngine.Networking.NetworkTransport.AddWebsocketHost(topology, port, ip); - isClient = !createServer; + s_IsClient = !createServer; - defaultChannelId = topology.DefaultConfig.AddChannel(QosType.ReliableSequenced); + s_DefaultChannelId = topology.DefaultConfig.AddChannel(QosType.ReliableSequenced); SetChannelsFromTopology(topology); int ret = UnityEngine.Networking.NetworkTransport.AddWebsocketHost(topology, port, ip); - if (createServer) relayConnectionId = UnityEngine.Networking.NetworkTransport.Connect(ret, RelayAddress, RelayPort, 0, out byte b); + if (createServer) s_RelayConnectionId = UnityEngine.Networking.NetworkTransport.Connect(ret, RelayAddress, RelayPort, 0, out byte b); return ret; } private static readonly byte[] disconnectBuffer = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, (byte)MessageType.ClientDisconnect }; + public static bool Disconnect(int hostId, int connectionId, out byte error) { if (!Enabled) return UnityEngine.Networking.NetworkTransport.Disconnect(hostId, connectionId, out error); - if (!isClient) + if (!s_IsClient) { for (byte i = 0; i < sizeof(ulong); i++) disconnectBuffer[i] = ((byte)((ulong)connectionId >> (i * 8))); - return UnityEngine.Networking.NetworkTransport.Send(hostId, relayConnectionId, defaultChannelId, disconnectBuffer, 9, out error); + return UnityEngine.Networking.NetworkTransport.Send(hostId, s_RelayConnectionId, s_DefaultChannelId, disconnectBuffer, 9, out error); } return UnityEngine.Networking.NetworkTransport.Disconnect(hostId, connectionId, out error); @@ -229,7 +232,7 @@ public static bool Send(int hostId, int connectionId, int channelId, byte[] buff ++size; - if (!isClient) + if (!s_IsClient) { size += 8; @@ -240,7 +243,7 @@ public static bool Send(int hostId, int connectionId, int channelId, byte[] buff buffer[size - 1] = (byte)MessageType.Data; - return UnityEngine.Networking.NetworkTransport.Send(hostId, relayConnectionId, channelId, buffer, size, out error); + return UnityEngine.Networking.NetworkTransport.Send(hostId, s_RelayConnectionId, channelId, buffer, size, out error); } public static bool QueueMessageForSending(int hostId, int connectionId, int channelId, byte[] buffer, int size, out byte error) @@ -249,7 +252,7 @@ public static bool QueueMessageForSending(int hostId, int connectionId, int chan ++size; - if (!isClient) + if (!s_IsClient) { size += 8; @@ -260,32 +263,32 @@ public static bool QueueMessageForSending(int hostId, int connectionId, int chan buffer[size - 1] = (byte)MessageType.Data; - return UnityEngine.Networking.NetworkTransport.QueueMessageForSending(hostId, relayConnectionId, channelId, buffer, size, out error); + return UnityEngine.Networking.NetworkTransport.QueueMessageForSending(hostId, s_RelayConnectionId, channelId, buffer, size, out error); } public static bool SendQueuedMessages(int hostId, int connectionId, out byte error) { if (!Enabled) return UnityEngine.Networking.NetworkTransport.SendQueuedMessages(hostId, connectionId, out error); - return UnityEngine.Networking.NetworkTransport.SendQueuedMessages(hostId, relayConnectionId, out error); + return UnityEngine.Networking.NetworkTransport.SendQueuedMessages(hostId, s_RelayConnectionId, out error); } public static NetworkEventType ReceiveFromHost(int hostId, out int connectionId, out int channelId, byte[] buffer, int bufferSize, out int receivedSize, out byte error) { if (!Enabled) return UnityEngine.Networking.NetworkTransport.ReceiveFromHost(hostId, out connectionId, out channelId, buffer, bufferSize, out receivedSize, out error); - NetworkEventType @event = UnityEngine.Networking.NetworkTransport.ReceiveFromHost(hostId, out connectionId, out channelId, buffer, bufferSize, out receivedSize, out error); + var eventType = UnityEngine.Networking.NetworkTransport.ReceiveFromHost(hostId, out connectionId, out channelId, buffer, bufferSize, out receivedSize, out error); - return BaseReceive(@event, hostId, ref connectionId, ref channelId, buffer, bufferSize, ref receivedSize, ref error); + return BaseReceive(eventType, hostId, ref connectionId, ref channelId, buffer, bufferSize, ref receivedSize, ref error); } public static NetworkEventType Receive(out int hostId, out int connectionId, out int channelId, byte[] buffer, int bufferSize, out int receivedSize, out byte error) { if (!Enabled) return UnityEngine.Networking.NetworkTransport.Receive(out hostId, out connectionId, out channelId, buffer, bufferSize, out receivedSize, out error); - NetworkEventType @event = UnityEngine.Networking.NetworkTransport.Receive(out hostId, out connectionId, out channelId, buffer, bufferSize, out receivedSize, out error); + var eventType = UnityEngine.Networking.NetworkTransport.Receive(out hostId, out connectionId, out channelId, buffer, bufferSize, out receivedSize, out error); - return BaseReceive(@event, hostId, ref connectionId, ref channelId, buffer, bufferSize, ref receivedSize, ref error); + return BaseReceive(eventType, hostId, ref connectionId, ref channelId, buffer, bufferSize, ref receivedSize, ref error); } private static NetworkEventType BaseReceive(NetworkEventType netEvent, int hostId, ref int connectionId, ref int channelId, byte[] buffer, int bufferSize, ref int receivedSize, ref byte error) @@ -293,135 +296,136 @@ private static NetworkEventType BaseReceive(NetworkEventType netEvent, int hostI switch (netEvent) { case NetworkEventType.DataEvent: - { - MessageType messageType = (MessageType)buffer[receivedSize - 1]; + { + var messageType = (MessageType)buffer[receivedSize - 1]; - switch (messageType) - { - case MessageType.AddressReport: - { - byte[] addressBytes = new byte[16]; - - for (int i = 0; i < addressBytes.Length; i++) - addressBytes[i] = buffer[i]; - - ushort remotePort = (ushort)(((ushort)buffer[16]) | - ((ushort)buffer[17] << 8)); - - IPEndPoint remoteEndPoint = new IPEndPoint(new IPAddress(addressBytes), remotePort); - - if (OnRemoteEndpointReported != null) - { - OnRemoteEndpointReported(remoteEndPoint); - } - break; - } - case MessageType.ConnectToServer: // Connection approved - { - if (!isClient) - { - ulong _connectionId = (((ulong)buffer[receivedSize - 9]) | - ((ulong)buffer[receivedSize - 8] << 8) | - ((ulong)buffer[receivedSize - 7] << 16) | - ((ulong)buffer[receivedSize - 6] << 24) | - ((ulong)buffer[receivedSize - 5] << 32) | - ((ulong)buffer[receivedSize - 4] << 40) | - ((ulong)buffer[receivedSize - 3] << 48) | - ((ulong)buffer[receivedSize - 2] << 56)); - - connectionId = (int)_connectionId; - } - - return NetworkEventType.ConnectEvent; - } - case MessageType.Data: - { - // Implicitly remove header - if (isClient) --receivedSize; - else - { - receivedSize -= 9; - - ulong _connectionId = (((ulong)buffer[receivedSize]) | - ((ulong)buffer[receivedSize + 1] << 8) | - ((ulong)buffer[receivedSize + 2] << 16) | - ((ulong)buffer[receivedSize + 3] << 24) | - ((ulong)buffer[receivedSize + 4] << 32) | - ((ulong)buffer[receivedSize + 5] << 40) | - ((ulong)buffer[receivedSize + 6] << 48) | - ((ulong)buffer[receivedSize + 7] << 56)); - - connectionId = (int)_connectionId; - } - - return NetworkEventType.DataEvent; - } - case MessageType.ClientDisconnect: - { - ulong _connectionId = (((ulong)buffer[0]) | - ((ulong)buffer[1] << 8) | - ((ulong)buffer[2] << 16) | - ((ulong)buffer[3] << 24) | - ((ulong)buffer[4] << 32) | - ((ulong)buffer[5] << 40) | - ((ulong)buffer[6] << 48) | - ((ulong)buffer[7] << 56)); - - connectionId = (int)_connectionId; - - return NetworkEventType.DisconnectEvent; - } - } - } - break; - case NetworkEventType.ConnectEvent: + switch (messageType) { - if (isClient) + case MessageType.AddressReport: { - //Connect via relay - - byte[] ipv6AddressBuffer; - IPAddress ipAddress = IPAddress.Parse(address); + byte[] addressBytes = new byte[16]; - if (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) + for (int i = 0; i < addressBytes.Length; i++) { - ipv6AddressBuffer = ipAddress.GetAddressBytes(); + addressBytes[i] = buffer[i]; } - else if (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) + + ushort remotePort = (ushort)(((ushort)buffer[16]) | + ((ushort)buffer[17] << 8)); + + var remoteEndPoint = new IPEndPoint(new IPAddress(addressBytes), remotePort); + + OnRemoteEndpointReported?.Invoke(remoteEndPoint); + + break; + } + case MessageType.ConnectToServer: // Connection approved + { + if (!s_IsClient) { - byte[] ipv4Address = ipAddress.GetAddressBytes(); - ipv6AddressBuffer = new byte[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, ipv4Address[0], ipv4Address[1], ipv4Address[2], ipv4Address[3] }; + ulong _connectionId = (((ulong)buffer[receivedSize - 9]) | + ((ulong)buffer[receivedSize - 8] << 8) | + ((ulong)buffer[receivedSize - 7] << 16) | + ((ulong)buffer[receivedSize - 6] << 24) | + ((ulong)buffer[receivedSize - 5] << 32) | + ((ulong)buffer[receivedSize - 4] << 40) | + ((ulong)buffer[receivedSize - 3] << 48) | + ((ulong)buffer[receivedSize - 2] << 56)); + + connectionId = (int)_connectionId; } + + return NetworkEventType.ConnectEvent; + } + case MessageType.Data: + { + // Implicitly remove header + if (s_IsClient) --receivedSize; else { - // TODO: Throw wrong type - ipv6AddressBuffer = null; + receivedSize -= 9; + + ulong _connectionId = (((ulong)buffer[receivedSize]) | + ((ulong)buffer[receivedSize + 1] << 8) | + ((ulong)buffer[receivedSize + 2] << 16) | + ((ulong)buffer[receivedSize + 3] << 24) | + ((ulong)buffer[receivedSize + 4] << 32) | + ((ulong)buffer[receivedSize + 5] << 40) | + ((ulong)buffer[receivedSize + 6] << 48) | + ((ulong)buffer[receivedSize + 7] << 56)); + + connectionId = (int)_connectionId; } - // TODO: Throw if address is not 16 bytes. It should always be - for (int i = 0; i < ipv6AddressBuffer.Length; i++) buffer[i] = ipv6AddressBuffer[i]; - - for (byte i = 0; i < sizeof(ushort); i++) buffer[16 + i] = ((byte)(port >> (i * 8))); + return NetworkEventType.DataEvent; + } + case MessageType.ClientDisconnect: + { + ulong _connectionId = (((ulong)buffer[0]) | + ((ulong)buffer[1] << 8) | + ((ulong)buffer[2] << 16) | + ((ulong)buffer[3] << 24) | + ((ulong)buffer[4] << 32) | + ((ulong)buffer[5] << 40) | + ((ulong)buffer[6] << 48) | + ((ulong)buffer[7] << 56)); + + connectionId = (int)_connectionId; + + return NetworkEventType.DisconnectEvent; + } + } + } + break; + case NetworkEventType.ConnectEvent: + { + if (s_IsClient) + { + //Connect via relay - buffer[16 + 2] = (byte)MessageType.ConnectToServer; + byte[] ipv6AddressBuffer; + var ipAddress = IPAddress.Parse(s_Address); - UnityEngine.Networking.NetworkTransport.Send(hostId, connectionId, defaultChannelId, buffer, 16 + 2 + 1, out error); + if (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) + { + ipv6AddressBuffer = ipAddress.GetAddressBytes(); + } + else if (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) + { + byte[] ipv4Address = ipAddress.GetAddressBytes(); + ipv6AddressBuffer = new byte[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, ipv4Address[0], ipv4Address[1], ipv4Address[2], ipv4Address[3] }; } else { - //Register us as a server - buffer[0] = (byte)MessageType.StartServer; - - UnityEngine.Networking.NetworkTransport.Send(hostId, connectionId, defaultChannelId, buffer, 1, out error); + // TODO: Throw wrong type + ipv6AddressBuffer = null; } - return NetworkEventType.Nothing; // Connect event is ignored + + // TODO: Throw if address is not 16 bytes. It should always be + for (int i = 0; i < ipv6AddressBuffer.Length; i++) buffer[i] = ipv6AddressBuffer[i]; + + for (byte i = 0; i < sizeof(ushort); i++) buffer[16 + i] = ((byte)(s_Port >> (i * 8))); + + buffer[16 + 2] = (byte)MessageType.ConnectToServer; + + UnityEngine.Networking.NetworkTransport.Send(hostId, connectionId, s_DefaultChannelId, buffer, 16 + 2 + 1, out error); } - case NetworkEventType.DisconnectEvent: + else { - if ((NetworkError)error == NetworkError.CRCMismatch) Debug.LogError("[MLAPI.Relay] The MLAPI Relay detected a CRC mismatch. This could be due to the maxClients or other connectionConfig settings not being the same"); + //Register us as a server + buffer[0] = (byte)MessageType.StartServer; - return NetworkEventType.DisconnectEvent; + UnityEngine.Networking.NetworkTransport.Send(hostId, connectionId, s_DefaultChannelId, buffer, 1, out error); } + + return NetworkEventType.Nothing; // Connect event is ignored + } + case NetworkEventType.DisconnectEvent: + { + if ((NetworkError)error == NetworkError.CRCMismatch) Debug.LogError("[MLAPI.Relay] The MLAPI Relay detected a CRC mismatch. This could be due to the maxClients or other connectionConfig settings not being the same"); + + return NetworkEventType.DisconnectEvent; + } } return netEvent; @@ -435,4 +439,4 @@ public InvalidConfigException(string issue) : base(issue) { } } } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -#pragma warning restore 618 +#pragma warning restore 618 \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Transports/UNET/UnetChannel.cs b/com.unity.multiplayer.mlapi/Runtime/Transports/UNET/UNetChannel.cs similarity index 92% rename from com.unity.multiplayer.mlapi/Runtime/Transports/UNET/UnetChannel.cs rename to com.unity.multiplayer.mlapi/Runtime/Transports/UNET/UNetChannel.cs index eef2936537..0697621b70 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Transports/UNET/UnetChannel.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Transports/UNET/UNetChannel.cs @@ -7,7 +7,7 @@ namespace MLAPI.Transports /// A transport channel used by the MLAPI /// [Serializable] - public class UnetChannel + public class UNetChannel { /// /// The name of the channel @@ -19,4 +19,4 @@ public class UnetChannel /// public QosType Type; } -} +} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Transports/UNET/UnetChannel.cs.meta b/com.unity.multiplayer.mlapi/Runtime/Transports/UNET/UNetChannel.cs.meta similarity index 100% rename from com.unity.multiplayer.mlapi/Runtime/Transports/UNET/UnetChannel.cs.meta rename to com.unity.multiplayer.mlapi/Runtime/Transports/UNET/UNetChannel.cs.meta diff --git a/com.unity.multiplayer.mlapi/Runtime/Transports/UNET/UnetTransport.cs b/com.unity.multiplayer.mlapi/Runtime/Transports/UNET/UNetTransport.cs similarity index 63% rename from com.unity.multiplayer.mlapi/Runtime/Transports/UNET/UnetTransport.cs rename to com.unity.multiplayer.mlapi/Runtime/Transports/UNET/UNetTransport.cs index 443239ac43..040b6d6440 100644 --- a/com.unity.multiplayer.mlapi/Runtime/Transports/UNET/UnetTransport.cs +++ b/com.unity.multiplayer.mlapi/Runtime/Transports/UNET/UNetTransport.cs @@ -10,7 +10,7 @@ namespace MLAPI.Transports.UNET { - public class UnetTransport : NetworkTransport, ITransportProfilerData + public class UNetTransport : NetworkTransport, ITransportProfilerData { public enum SendMode { @@ -18,8 +18,8 @@ public enum SendMode Queued } - static readonly ProfilingDataStore k_TransportProfilerData = new ProfilingDataStore(); - public static bool profilerEnabled; + private static ProfilingDataStore s_TransportProfilerData = new ProfilingDataStore(); + public static bool ProfilerEnabled; // Inspector / settings public int MessageBufferSize = 1024 * 5; @@ -36,13 +36,13 @@ public enum SendMode // #define MY_CHANNEL 0 // ... // transport.Channels.Add( - // new UnetChannel() + // new UNetChannel() // { // Id = Channel.ChannelUnused + MY_CHANNEL, <<-- must offset from reserved channel offset in MLAPI SDK // Type = QosType.Unreliable // } // ); - public List Channels = new List(); + public List Channels = new List(); // Relay public bool UseMLAPIRelay = false; @@ -52,27 +52,31 @@ public enum SendMode public SendMode MessageSendMode = SendMode.Immediately; // Runtime / state - private byte[] messageBuffer; - private WeakReference temporaryBufferReference; + private byte[] m_MessageBuffer; + private WeakReference m_TemporaryBufferReference; // Lookup / translation - private readonly Dictionary channelNameToId = new Dictionary(); - private readonly Dictionary channelIdToName = new Dictionary(); - private int serverConnectionId; - private int serverHostId; + private readonly Dictionary m_ChannelNameToId = new Dictionary(); + private readonly Dictionary m_ChannelIdToName = new Dictionary(); + private int m_ServerConnectionId; + private int m_ServerHostId; - private SocketTask connectTask; + private SocketTask m_ConnectTask; public override ulong ServerClientId => GetMLAPIClientId(0, 0, true); protected void LateUpdate() { - if (UnityEngine.Networking.NetworkTransport.IsStarted && MessageSendMode == SendMode.Queued) { - if (NetworkManager.Singleton.IsServer) { - for (int i = 0; i < NetworkManager.Singleton.ConnectedClientsList.Count; i++) { + if (UnityEngine.Networking.NetworkTransport.IsStarted && MessageSendMode == SendMode.Queued) + { + if (NetworkManager.Singleton.IsServer) + { + for (int i = 0; i < NetworkManager.Singleton.ConnectedClientsList.Count; i++) + { SendQueued(NetworkManager.Singleton.ConnectedClientsList[i].ClientId); } } - else { + else + { SendQueued(NetworkManager.Singleton.LocalClientId); } } @@ -80,22 +84,22 @@ protected void LateUpdate() public override void Send(ulong clientId, ArraySegment data, NetworkChannel networkChannel) { - if (profilerEnabled) + if (ProfilerEnabled) { - k_TransportProfilerData.Increment(ProfilerConstants.NumberOfTransportSends); + s_TransportProfilerData.Increment(ProfilerConstants.NumberOfTransportSends); } - GetUnetConnectionDetails(clientId, out byte hostId, out ushort connectionId); + GetUNetConnectionDetails(clientId, out byte hostId, out ushort connectionId); int channelId = 0; - if (channelNameToId.ContainsKey(networkChannel)) + if (m_ChannelNameToId.ContainsKey(networkChannel)) { - channelId = channelNameToId[networkChannel]; + channelId = m_ChannelNameToId[networkChannel]; } else { - channelId = channelNameToId[NetworkChannel.Internal]; + channelId = m_ChannelNameToId[NetworkChannel.Internal]; } byte[] buffer; @@ -104,21 +108,21 @@ public override void Send(ulong clientId, ArraySegment data, NetworkChanne { // UNET cant handle this, do a copy - if (messageBuffer.Length >= data.Count) + if (m_MessageBuffer.Length >= data.Count) { - buffer = messageBuffer; + buffer = m_MessageBuffer; } else { object bufferRef = null; - if (temporaryBufferReference != null && ((bufferRef = temporaryBufferReference.Target) != null) && ((byte[])bufferRef).Length >= data.Count) + if (m_TemporaryBufferReference != null && ((bufferRef = m_TemporaryBufferReference.Target) != null) && ((byte[])bufferRef).Length >= data.Count) { buffer = (byte[])bufferRef; } else { buffer = new byte[data.Count]; - temporaryBufferReference = new WeakReference(buffer); + m_TemporaryBufferReference = new WeakReference(buffer); } } @@ -129,10 +133,12 @@ public override void Send(ulong clientId, ArraySegment data, NetworkChanne buffer = data.Array; } - if (MessageSendMode == SendMode.Queued) { + if (MessageSendMode == SendMode.Queued) + { RelayTransport.QueueMessageForSending(hostId, connectionId, channelId, buffer, data.Count, out byte error); } - else { + else + { RelayTransport.Send(hostId, connectionId, channelId, buffer, data.Count, out byte error); } } @@ -140,38 +146,36 @@ public override void Send(ulong clientId, ArraySegment data, NetworkChanne public void SendQueued(ulong clientId) { - if (profilerEnabled) + if (ProfilerEnabled) { - k_TransportProfilerData.Increment(ProfilerConstants.NumberOfTransportSendQueues); + s_TransportProfilerData.Increment(ProfilerConstants.NumberOfTransportSendQueues); } - GetUnetConnectionDetails(clientId, out byte hostId, out ushort connectionId); + GetUNetConnectionDetails(clientId, out byte hostId, out ushort connectionId); RelayTransport.SendQueuedMessages(hostId, connectionId, out byte error); } public override NetworkEvent PollEvent(out ulong clientId, out NetworkChannel networkChannel, out ArraySegment payload, out float receiveTime) { - NetworkEventType eventType = RelayTransport.Receive(out int hostId, out int connectionId, out int channelId, messageBuffer, messageBuffer.Length, out int receivedSize, out byte error); - - clientId = GetMLAPIClientId((byte) hostId, (ushort) connectionId, false); + var eventType = RelayTransport.Receive(out int hostId, out int connectionId, out int channelId, m_MessageBuffer, m_MessageBuffer.Length, out int receivedSize, out byte error); + clientId = GetMLAPIClientId((byte)hostId, (ushort)connectionId, false); receiveTime = UnityEngine.Time.realtimeSinceStartup; - NetworkError networkError = (NetworkError) error; - + var networkError = (NetworkError)error; if (networkError == NetworkError.MessageToLong) { byte[] tempBuffer; - if (temporaryBufferReference != null && temporaryBufferReference.IsAlive && ((byte[]) temporaryBufferReference.Target).Length >= receivedSize) + if (m_TemporaryBufferReference != null && m_TemporaryBufferReference.IsAlive && ((byte[])m_TemporaryBufferReference.Target).Length >= receivedSize) { - tempBuffer = (byte[])temporaryBufferReference.Target; + tempBuffer = (byte[])m_TemporaryBufferReference.Target; } else { tempBuffer = new byte[receivedSize]; - temporaryBufferReference = new WeakReference(tempBuffer); + m_TemporaryBufferReference = new WeakReference(tempBuffer); } eventType = RelayTransport.Receive(out hostId, out connectionId, out channelId, tempBuffer, tempBuffer.Length, out receivedSize, out error); @@ -179,45 +183,45 @@ public override NetworkEvent PollEvent(out ulong clientId, out NetworkChannel ne } else { - payload = new ArraySegment(messageBuffer, 0, receivedSize); + payload = new ArraySegment(m_MessageBuffer, 0, receivedSize); } - if (channelIdToName.ContainsKey(channelId)) + if (m_ChannelIdToName.ContainsKey(channelId)) { - networkChannel = channelIdToName[channelId]; + networkChannel = m_ChannelIdToName[channelId]; } else { networkChannel = NetworkChannel.Internal; } - if (connectTask != null && hostId == serverHostId && connectionId == serverConnectionId) + if (m_ConnectTask != null && hostId == m_ServerHostId && connectionId == m_ServerConnectionId) { if (eventType == NetworkEventType.ConnectEvent) { // We just got a response to our connect request. - connectTask.Message = null; - connectTask.SocketError = networkError == NetworkError.Ok ? System.Net.Sockets.SocketError.Success : System.Net.Sockets.SocketError.SocketError; - connectTask.State = null; - connectTask.Success = networkError == NetworkError.Ok; - connectTask.TransportCode = (byte)networkError; - connectTask.TransportException = null; - connectTask.IsDone = true; - - connectTask = null; + m_ConnectTask.Message = null; + m_ConnectTask.SocketError = networkError == NetworkError.Ok ? System.Net.Sockets.SocketError.Success : System.Net.Sockets.SocketError.SocketError; + m_ConnectTask.State = null; + m_ConnectTask.Success = networkError == NetworkError.Ok; + m_ConnectTask.TransportCode = (byte)networkError; + m_ConnectTask.TransportException = null; + m_ConnectTask.IsDone = true; + + m_ConnectTask = null; } else if (eventType == NetworkEventType.DisconnectEvent) { // We just got a response to our connect request. - connectTask.Message = null; - connectTask.SocketError = System.Net.Sockets.SocketError.SocketError; - connectTask.State = null; - connectTask.Success = false; - connectTask.TransportCode = (byte)networkError; - connectTask.TransportException = null; - connectTask.IsDone = true; - - connectTask = null; + m_ConnectTask.Message = null; + m_ConnectTask.SocketError = System.Net.Sockets.SocketError.SocketError; + m_ConnectTask.State = null; + m_ConnectTask.Success = false; + m_ConnectTask.TransportCode = (byte)networkError; + m_ConnectTask.TransportException = null; + m_ConnectTask.IsDone = true; + + m_ConnectTask = null; } } @@ -247,38 +251,38 @@ public override NetworkEvent PollEvent(out ulong clientId, out NetworkChannel ne public override SocketTasks StartClient() { - SocketTask task = SocketTask.Working; + var socketTask = SocketTask.Working; - serverHostId = RelayTransport.AddHost(new HostTopology(GetConfig(), 1), false); - serverConnectionId = RelayTransport.Connect(serverHostId, ConnectAddress, ConnectPort, 0, out byte error); + m_ServerHostId = RelayTransport.AddHost(new HostTopology(GetConfig(), 1), false); + m_ServerConnectionId = RelayTransport.Connect(m_ServerHostId, ConnectAddress, ConnectPort, 0, out byte error); - NetworkError connectError = (NetworkError)error; + var connectError = (NetworkError)error; switch (connectError) { case NetworkError.Ok: - task.Success = true; - task.TransportCode = error; - task.SocketError = System.Net.Sockets.SocketError.Success; - task.IsDone = false; + socketTask.Success = true; + socketTask.TransportCode = error; + socketTask.SocketError = System.Net.Sockets.SocketError.Success; + socketTask.IsDone = false; // We want to continue to wait for the successful connect - connectTask = task; + m_ConnectTask = socketTask; break; default: - task.Success = false; - task.TransportCode = error; - task.SocketError = System.Net.Sockets.SocketError.SocketError; - task.IsDone = true; + socketTask.Success = false; + socketTask.TransportCode = error; + socketTask.SocketError = System.Net.Sockets.SocketError.SocketError; + socketTask.IsDone = true; break; } - return task.AsTasks(); + return socketTask.AsTasks(); } public override SocketTasks StartServer() { - HostTopology topology = new HostTopology(GetConfig(), MaxConnections); + var topology = new HostTopology(GetConfig(), MaxConnections); if (SupportWebsocket) { @@ -290,7 +294,6 @@ public override SocketTasks StartServer() { if (NetworkLog.CurrentLogLevel <= LogLevel.Error) NetworkLog.LogError("Cannot create websocket host when using MLAPI relay"); } - } int normalHostId = RelayTransport.AddHost(topology, ServerListenPort, true); @@ -300,19 +303,19 @@ public override SocketTasks StartServer() public override void DisconnectRemoteClient(ulong clientId) { - GetUnetConnectionDetails(clientId, out byte hostId, out ushort connectionId); + GetUNetConnectionDetails(clientId, out byte hostId, out ushort connectionId); - RelayTransport.Disconnect((int) hostId, (int) connectionId, out byte error); + RelayTransport.Disconnect((int)hostId, (int)connectionId, out byte error); } public override void DisconnectLocalClient() { - RelayTransport.Disconnect(serverHostId, serverConnectionId, out byte error); + RelayTransport.Disconnect(m_ServerHostId, m_ServerConnectionId, out byte error); } public override ulong GetCurrentRtt(ulong clientId) { - GetUnetConnectionDetails(clientId, out byte hostId, out ushort connectionId); + GetUNetConnectionDetails(clientId, out byte hostId, out ushort connectionId); if (UseMLAPIRelay) { @@ -320,14 +323,14 @@ public override ulong GetCurrentRtt(ulong clientId) } else { - return (ulong)UnityEngine.Networking.NetworkTransport.GetCurrentRTT((int) hostId, (int) connectionId, out byte error); + return (ulong)UnityEngine.Networking.NetworkTransport.GetCurrentRTT((int)hostId, (int)connectionId, out byte error); } } public override void Shutdown() { - channelIdToName.Clear(); - channelNameToId.Clear(); + m_ChannelIdToName.Clear(); + m_ChannelNameToId.Clear(); UnityEngine.Networking.NetworkTransport.Shutdown(); } @@ -335,9 +338,9 @@ public override void Init() { UpdateRelay(); - messageBuffer = new byte[MessageBufferSize]; + m_MessageBuffer = new byte[MessageBufferSize]; - k_TransportProfilerData.Clear(); + s_TransportProfilerData.Clear(); UnityEngine.Networking.NetworkTransport.Init(); } @@ -354,49 +357,50 @@ public ulong GetMLAPIClientId(byte hostId, ushort connectionId, bool isServer) } } - public void GetUnetConnectionDetails(ulong clientId, out byte hostId, out ushort connectionId) + public void GetUNetConnectionDetails(ulong clientId, out byte hostId, out ushort connectionId) { if (clientId == 0) { - hostId = (byte)serverHostId; - connectionId = (ushort)serverConnectionId; + hostId = (byte)m_ServerHostId; + connectionId = (ushort)m_ServerConnectionId; } else { - hostId = (byte) ((clientId - 1) >> 16); - connectionId = (ushort) ((clientId - 1)); + hostId = (byte)((clientId - 1) >> 16); + connectionId = (ushort)((clientId - 1)); } } public ConnectionConfig GetConfig() { - ConnectionConfig config = new ConnectionConfig(); + var connectionConfig = new ConnectionConfig(); // MLAPI built-in channels for (int i = 0; i < MLAPI_CHANNELS.Length; i++) { - int channelId = AddMLAPIChannel(MLAPI_CHANNELS[i].Delivery, config); + int channelId = AddMLAPIChannel(MLAPI_CHANNELS[i].Delivery, connectionConfig); - channelIdToName.Add(channelId, MLAPI_CHANNELS[i].Channel); - channelNameToId.Add(MLAPI_CHANNELS[i].Channel, channelId); + m_ChannelIdToName.Add(channelId, MLAPI_CHANNELS[i].Channel); + m_ChannelNameToId.Add(MLAPI_CHANNELS[i].Channel, channelId); } // Custom user-added channels for (int i = 0; i < Channels.Count; i++) { - int channelId = AddUNETChannel(Channels[i].Type, config); + int channelId = AddUNETChannel(Channels[i].Type, connectionConfig); - if (channelNameToId.ContainsKey(Channels[i].Id)) + if (m_ChannelNameToId.ContainsKey(Channels[i].Id)) { - throw new InvalidChannelException("Channel " + channelId + " already exists"); + throw new InvalidChannelException($"Channel {channelId} already exists"); } - channelIdToName.Add(channelId, Channels[i].Id); - channelNameToId.Add(Channels[i].Id, channelId); + + m_ChannelIdToName.Add(channelId, Channels[i].Id); + m_ChannelNameToId.Add(Channels[i].Id, channelId); } - config.MaxSentMessageQueueSize = (ushort)MaxSentMessageQueueSize; + connectionConfig.MaxSentMessageQueueSize = (ushort)MaxSentMessageQueueSize; - return config; + return connectionConfig; } public int AddMLAPIChannel(NetworkDelivery type, ConnectionConfig config) @@ -458,14 +462,14 @@ private void UpdateRelay() public void BeginNewTick() { - k_TransportProfilerData.Clear(); + s_TransportProfilerData.Clear(); } public IReadOnlyDictionary GetTransportProfilerData() { - return k_TransportProfilerData.GetReadonly(); + return s_TransportProfilerData.GetReadonly(); } } } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -#pragma warning restore 618 +#pragma warning restore 618 \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/Runtime/Transports/UNET/UnetTransport.cs.meta b/com.unity.multiplayer.mlapi/Runtime/Transports/UNET/UNetTransport.cs.meta similarity index 100% rename from com.unity.multiplayer.mlapi/Runtime/Transports/UNET/UnetTransport.cs.meta rename to com.unity.multiplayer.mlapi/Runtime/Transports/UNET/UNetTransport.cs.meta diff --git a/com.unity.multiplayer.mlapi/Tests/Editor/RpcBatcherTests.cs b/com.unity.multiplayer.mlapi/Tests/Editor/RpcBatcherTests.cs index 22e4d9553f..340ea7d12e 100644 --- a/com.unity.multiplayer.mlapi/Tests/Editor/RpcBatcherTests.cs +++ b/com.unity.multiplayer.mlapi/Tests/Editor/RpcBatcherTests.cs @@ -23,11 +23,11 @@ public void SendWithThreshold() var randomData = Encoding.ASCII.GetBytes(Guid.NewGuid().ToString()); var queueItem = new RpcFrameQueueItem { - networkId = 123, - clientIds = new ulong[] { 123 }, - networkChannel = NetworkChannel.ChannelUnused + 123, - queueItemType = i % 2 == 0 ? RpcQueueContainer.QueueItemType.ServerRpc : RpcQueueContainer.QueueItemType.ClientRpc, - messageData = new ArraySegment(randomData, 0, randomData.Length) + NetworkId = 123, + ClientNetworkIds = new ulong[] { 123 }, + NetworkChannel = NetworkChannel.ChannelUnused + 123, + QueueItemType = i % 2 == 0 ? RpcQueueContainer.QueueItemType.ServerRpc : RpcQueueContainer.QueueItemType.ClientRpc, + MessageData = new ArraySegment(randomData, 0, randomData.Length) }; sendBatcher.QueueItem(queueItem); sendBatcher.SendItems(k_BatchThreshold, @@ -81,11 +81,11 @@ public void SendWithoutThreshold() var randomData = Encoding.ASCII.GetBytes(Guid.NewGuid().ToString()); var queueItem = new RpcFrameQueueItem { - networkId = 123, - clientIds = new ulong[] { 123 }, - networkChannel = NetworkChannel.ChannelUnused + 123, - queueItemType = i % 2 == 0 ? RpcQueueContainer.QueueItemType.ServerRpc : RpcQueueContainer.QueueItemType.ClientRpc, - messageData = new ArraySegment(randomData, 0, randomData.Length) + NetworkId = 123, + ClientNetworkIds = new ulong[] { 123 }, + NetworkChannel = NetworkChannel.ChannelUnused + 123, + QueueItemType = i % 2 == 0 ? RpcQueueContainer.QueueItemType.ServerRpc : RpcQueueContainer.QueueItemType.ClientRpc, + MessageData = new ArraySegment(randomData, 0, randomData.Length) }; sendBatcher.QueueItem(queueItem); sendBatcher.SendItems(k_BatchThreshold, diff --git a/com.unity.multiplayer.mlapi/Tests/Runtime/RpcQueueTests.cs b/com.unity.multiplayer.mlapi/Tests/Runtime/RpcQueueTests.cs index 5271e83100..db9eae713f 100644 --- a/com.unity.multiplayer.mlapi/Tests/Runtime/RpcQueueTests.cs +++ b/com.unity.multiplayer.mlapi/Tests/Runtime/RpcQueueTests.cs @@ -30,7 +30,7 @@ public IEnumerator RpcQueueUnitTest() #if UNITY_2020_2_OR_NEWER // Disabling this test on 2019.4 due to ILPP issues on Yamato CI/CD runs var networkManagerObject = new GameObject(nameof(NetworkManager)); m_NetworkManager = networkManagerObject.AddComponent(); - var unetTransport = networkManagerObject.AddComponent(); + var unetTransport = networkManagerObject.AddComponent(); m_NetworkManager.NetworkConfig = new Configuration.NetworkConfig { CreatePlayerPrefab = false, @@ -42,7 +42,7 @@ public IEnumerator RpcQueueUnitTest() unetTransport.ServerListenPort = 7777; unetTransport.MessageBufferSize = 65535; unetTransport.MaxConnections = 100; - unetTransport.MessageSendMode = UnetTransport.SendMode.Immediately; + unetTransport.MessageSendMode = UNetTransport.SendMode.Immediately; m_NetworkManager.NetworkConfig.NetworkTransport = unetTransport; var currentActiveScene = SceneManager.GetActiveScene(); diff --git a/com.unity.multiplayer.mlapi/ValidationExceptions.json b/com.unity.multiplayer.mlapi/ValidationExceptions.json deleted file mode 100644 index d13b7ae9ea..0000000000 --- a/com.unity.multiplayer.mlapi/ValidationExceptions.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "Exceptions": - [ - { - "ValidationTest": "Restricted File Type Validation", - "ExceptionError": "/Runtime/csc.rsp cannot be included in a package.", - "PackageVersion": "0.0.1-preview.1" - } - ] -} \ No newline at end of file diff --git a/com.unity.multiplayer.mlapi/ValidationExceptions.json.meta b/com.unity.multiplayer.mlapi/ValidationExceptions.json.meta deleted file mode 100644 index 9fc42c498f..0000000000 --- a/com.unity.multiplayer.mlapi/ValidationExceptions.json.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: 57c02ceaeb0fb9246b87ae346454c986 -TextScriptImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/testproject/Assets/Scripts/Testing/ManualNetworkVariableTest.cs b/testproject/Assets/Scripts/Testing/ManualNetworkVariableTest.cs index 0b1d6c55fc..d4639e17ea 100644 --- a/testproject/Assets/Scripts/Testing/ManualNetworkVariableTest.cs +++ b/testproject/Assets/Scripts/Testing/ManualNetworkVariableTest.cs @@ -15,12 +15,12 @@ public class ManualNetworkVariableTest : NetworkBehaviour private int m_MaxDelta = 0; private int m_LastRemoteTick = 0; private bool m_Valid = false; - private string m_Problems = ""; + private string m_Problems = string.Empty; private int m_Count = 0; // todo: address issue with initial values - private const int m_WaitIterations = 5; - private const int m_EndIterations = 1000; + private const int k_WaitIterations = 5; + private const int k_EndIterations = 1000; void Start() { @@ -49,12 +49,12 @@ private void ValueChanged(int before, int after) { // compute the delta in tick between client and server, // as seen from the client, when it receives a value not from itself - if (m_TestVar.LocalTick != NetworkTickSystem.k_NoTick) + if (m_TestVar.LocalTick != NetworkTickSystem.NoTick) { int delta = m_TestVar.LocalTick - m_TestVar.RemoteTick; m_Count++; - if (m_Count > m_WaitIterations) + if (m_Count > k_WaitIterations) { if (!m_Valid) { @@ -82,7 +82,7 @@ private void ValueChanged(int before, int after) } } - if (m_Count == m_EndIterations) + if (m_Count == k_EndIterations) { if (m_Problems == "" && Math.Abs(m_MaxDelta - m_MinDelta) < 3) { @@ -91,7 +91,7 @@ private void ValueChanged(int before, int after) else { Debug.Log("**** TEST FAILED ****"); - Debug.Log("Delta range: " + m_MinDelta + ", " + m_MaxDelta); + Debug.Log($"Delta range: {m_MinDelta}, {m_MaxDelta}"); if (m_Problems != "") { @@ -103,4 +103,4 @@ private void ValueChanged(int before, int after) } } } -} +} \ No newline at end of file