Skip to content

Commit 60b3930

Browse files
refactor: channel internally represented with bytes vs. strings [MTT-236]
1 parent 528813a commit 60b3930

20 files changed

Lines changed: 158 additions & 131 deletions

com.unity.multiplayer.mlapi/Runtime/Core/MessageBatcher.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ class MessageBatcher
1313
{
1414
public class SendStream
1515
{
16-
public string channel;
16+
public byte channel;
1717
public PooledBitStream Stream = PooledBitStream.Get();
1818
public bool Empty = true;
1919
}

com.unity.multiplayer.mlapi/Runtime/Core/NetworkedBehaviour.cs

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
using MLAPI.Serialization;
1616
using MLAPI.Serialization.Pooled;
1717
using MLAPI.Spawning;
18+
using MLAPI.Transports;
1819
using BitStream = MLAPI.Serialization.BitStream;
1920
using Unity.Profiling;
2021

@@ -38,11 +39,6 @@ internal enum NExec
3839
Client = 2
3940
}
4041

41-
/// <summary>
42-
/// This is a temporary solution for channel names and the below hardcoded value might not be mandatory in the future.
43-
/// </summary>
44-
private const string StandardRpc_ChannelName = "STDRPC";
45-
4642
#pragma warning disable 414
4743
// RuntimeAccessModifiersILPP will make this `protected`
4844
internal NExec __nexec = NExec.None;
@@ -53,7 +49,7 @@ internal BitWriter BeginSendServerRpc(ServerRpcSendParams sendParams, bool isRel
5349
{
5450
var rpcQueueMananger = NetworkingManager.Singleton.rpcQueueContainer;
5551

56-
var writer = rpcQueueMananger.BeginAddQueueItemToOutboundFrame(RpcQueueContainer.QueueItemType.ServerRpc, Time.realtimeSinceStartup, StandardRpc_ChannelName, 0, NetworkingManager.Singleton.ServerClientId, null);
52+
var writer = rpcQueueMananger.BeginAddQueueItemToOutboundFrame(RpcQueueContainer.QueueItemType.ServerRpc, Time.realtimeSinceStartup, Transport.MLAPI_STDRPC_CHANNEL, 0, NetworkingManager.Singleton.ServerClientId, null);
5753
writer.WriteUInt64Packed(NetworkId); // NetworkObjectId
5854
writer.WriteUInt16Packed(GetBehaviourId()); // NetworkBehaviourId
5955
return writer;
@@ -74,7 +70,7 @@ internal BitWriter BeginSendClientRpc(ClientRpcSendParams sendParams, bool isRel
7470
//This will start a new queue item entry and will then return the writer to the current frame's stream
7571
var rpcQueueMananger = NetworkingManager.Singleton.rpcQueueContainer;
7672

77-
var writer = rpcQueueMananger.BeginAddQueueItemToOutboundFrame(RpcQueueContainer.QueueItemType.ClientRpc, Time.realtimeSinceStartup, StandardRpc_ChannelName, 0, NetworkId, sendParams.TargetClientIds ?? NetworkingManager.Singleton.ConnectedClientsList.Select(c => c.ClientId).ToArray());
73+
var writer = rpcQueueMananger.BeginAddQueueItemToOutboundFrame(RpcQueueContainer.QueueItemType.ClientRpc, Time.realtimeSinceStartup, Transport.MLAPI_STDRPC_CHANNEL, 0, NetworkId, sendParams.TargetClientIds ?? NetworkingManager.Singleton.ConnectedClientsList.Select(c => c.ClientId).ToArray());
7874
writer.WriteUInt64Packed(NetworkId); // NetworkObjectId
7975
writer.WriteUInt16Packed(GetBehaviourId()); // NetworkBehaviourId
8076
return writer;
@@ -271,7 +267,7 @@ protected NetworkedBehaviour GetBehaviour(ushort id)
271267
private bool varInit = false;
272268

273269
private readonly List<HashSet<int>> channelMappedNetworkedVarIndexes = new List<HashSet<int>>();
274-
private readonly List<string> channelsForNetworkedVarGroups = new List<string>();
270+
private readonly List<byte> channelsForNetworkedVarGroups = new List<byte>();
275271
internal readonly List<INetworkedVar> networkedVarFields = new List<INetworkedVar>();
276272

277273
private static HashSet<MLAPI.NetworkedObject> touched = new HashSet<MLAPI.NetworkedObject>();
@@ -336,12 +332,15 @@ internal void InitializeVars()
336332

337333
{
338334
// Create index map for channels
339-
Dictionary<string, int> firstLevelIndex = new Dictionary<string, int>();
335+
Dictionary<byte, int> firstLevelIndex = new Dictionary<byte, int>();
340336
int secondLevelCounter = 0;
341337

342338
for (int i = 0; i < networkedVarFields.Count; i++)
343339
{
344-
string channel = networkedVarFields[i].GetChannel(); // Cache this here. Some developers are stupid. You don't know what shit they will do in their methods
340+
// this could be cleaner. The GetChannel() methods look for the SendChannel string channel name
341+
// from the settings file.
342+
string channelName = networkedVarFields[i].GetChannel(); // Cache this here. Some developers are stupid. You don't know what shit they will do in their methods
343+
byte channel = Transport.GetChannelByte(channelName);
345344

346345
if (!firstLevelIndex.ContainsKey(channel))
347346
{

com.unity.multiplayer.mlapi/Runtime/Core/NetworkedObject.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
using MLAPI.Security;
1111
using MLAPI.Serialization.Pooled;
1212
using MLAPI.Spawning;
13+
using MLAPI.Transports;
1314
using Unity.Profiling;
1415
using UnityEngine;
1516

@@ -277,7 +278,7 @@ public static void NetworkShow(List<NetworkedObject> networkedObjects, ulong cli
277278
SpawnManager.WriteSpawnCallForObject(stream, clientId, networkedObjects[i], payload);
278279
}
279280

280-
InternalMessageSender.Send(clientId, MLAPIConstants.MLAPI_ADD_OBJECTS, "MLAPI_INTERNAL", stream, SecuritySendFlags.None);
281+
InternalMessageSender.Send(clientId, MLAPIConstants.MLAPI_ADD_OBJECTS, Transport.MLAPI_INTERNAL_CHANNEL, stream, SecuritySendFlags.None);
281282
}
282283
}
283284

@@ -317,7 +318,7 @@ public void NetworkHide(ulong clientId)
317318
{
318319
writer.WriteUInt64Packed(NetworkId);
319320

320-
InternalMessageSender.Send(clientId, MLAPIConstants.MLAPI_DESTROY_OBJECT, "MLAPI_INTERNAL", stream, SecuritySendFlags.None);
321+
InternalMessageSender.Send(clientId, MLAPIConstants.MLAPI_DESTROY_OBJECT, Transport.MLAPI_INTERNAL_CHANNEL, stream, SecuritySendFlags.None);
321322
}
322323
}
323324
}
@@ -369,7 +370,7 @@ public static void NetworkHide(List<NetworkedObject> networkedObjects, ulong cli
369370
}
370371
}
371372

372-
InternalMessageSender.Send(clientId, MLAPIConstants.MLAPI_DESTROY_OBJECTS, "MLAPI_INTERNAL", stream, SecuritySendFlags.None);
373+
InternalMessageSender.Send(clientId, MLAPIConstants.MLAPI_DESTROY_OBJECTS, Transport.MLAPI_INTERNAL_CHANNEL, stream, SecuritySendFlags.None);
373374
}
374375
}
375376

com.unity.multiplayer.mlapi/Runtime/Core/NetworkingManager.cs

Lines changed: 23 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -261,15 +261,15 @@ internal void InvokeOnIncomingCustomMessage(ulong clientId, Stream stream)
261261
/// <param name="channel">The channel to send the data on</param>
262262
/// <param name="security">The security settings to apply to the message</param>
263263
[Obsolete("Use CustomMessagingManager.SendUnnamedMessage instead")]
264-
public void SendCustomMessage(List<ulong> clientIds, BitStream stream, string channel = null, SecuritySendFlags security = SecuritySendFlags.None)
264+
public void SendCustomMessage(List<ulong> clientIds, BitStream stream, byte channel = Transport.MLAPI_INTERNAL_CHANNEL, SecuritySendFlags security = SecuritySendFlags.None)
265265
{
266266
if (!IsServer)
267267
{
268268
if (NetworkLog.CurrentLogLevel <= LogLevel.Error) NetworkLog.LogWarning("Can not send unnamed message to multiple users as a client");
269269
return;
270270
}
271271

272-
InternalMessageSender.Send(MLAPIConstants.MLAPI_UNNAMED_MESSAGE, string.IsNullOrEmpty(channel) ? "MLAPI_DEFAULT_MESSAGE" : channel, clientIds, stream, security);
272+
InternalMessageSender.Send(MLAPIConstants.MLAPI_UNNAMED_MESSAGE, channel, clientIds, stream, security);
273273
}
274274

275275
/// <summary>
@@ -280,9 +280,9 @@ public void SendCustomMessage(List<ulong> clientIds, BitStream stream, string ch
280280
/// <param name="channel">The channel tos end the data on</param>
281281
/// <param name="security">The security settings to apply to the message</param>
282282
[Obsolete("Use CustomMessagingManager.SendUnnamedMessage instead")]
283-
public void SendCustomMessage(ulong clientId, BitStream stream, string channel = null, SecuritySendFlags security = SecuritySendFlags.None)
283+
public void SendCustomMessage(ulong clientId, BitStream stream, byte channel = Transport.MLAPI_INTERNAL_CHANNEL, SecuritySendFlags security = SecuritySendFlags.None)
284284
{
285-
InternalMessageSender.Send(clientId, MLAPIConstants.MLAPI_UNNAMED_MESSAGE, string.IsNullOrEmpty(channel) ? "MLAPI_DEFAULT_MESSAGE" : channel, stream, security);
285+
InternalMessageSender.Send(clientId, MLAPIConstants.MLAPI_UNNAMED_MESSAGE, channel, stream, security);
286286
}
287287

288288
private void OnValidate()
@@ -732,7 +732,7 @@ private void NetworkPreUpdate()
732732
while (__loopbackRpcQueue.Count > 0)
733733
{
734734
var (payload, receiveTime) = __loopbackRpcQueue.Dequeue();
735-
HandleRawTransportPoll(NetEventType.Data, ServerClientId, "STDRPC", payload, receiveTime);
735+
HandleRawTransportPoll(NetEventType.Data, ServerClientId, Transport.MLAPI_STDRPC_CHANNEL, payload, receiveTime);
736736
}
737737
}
738738
// @mfatihmar (Unity) End: Temporary, inbound RPC queue will replace this workaround
@@ -748,7 +748,10 @@ private void NetworkPreUpdate()
748748
{
749749
processedEvents++;
750750
eventType = NetworkConfig.NetworkTransport.PollEvent(out ulong clientId, out string channelName, out ArraySegment<byte> payload, out float receiveTime);
751-
HandleRawTransportPoll(eventType, clientId, channelName, payload, receiveTime);
751+
// [MTT-443] This can be improved if the Transport implementations return the channel as a byte vs. string
752+
// Holding off on this; refactoring the Transport package will be a separate step
753+
byte channel = Transport.GetChannelByte(channelName);
754+
HandleRawTransportPoll(eventType, clientId, channel, payload, receiveTime);
752755

753756
// 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)
754757
} while (IsListening && (eventType != NetEventType.Nothing) && (NetworkConfig.MaxReceiveEventsPerTickRate <= 0 || processedEvents < NetworkConfig.MaxReceiveEventsPerTickRate));
@@ -881,7 +884,7 @@ internal void SendConnectionRequest()
881884
writer.WriteByteArray(NetworkConfig.ConnectionData);
882885
}
883886

884-
InternalMessageSender.Send(ServerClientId, MLAPIConstants.MLAPI_CONNECTION_REQUEST, "MLAPI_INTERNAL", stream, SecuritySendFlags.Authenticated | SecuritySendFlags.Encrypted);
887+
InternalMessageSender.Send(ServerClientId, MLAPIConstants.MLAPI_CONNECTION_REQUEST, Transport.MLAPI_INTERNAL_CHANNEL, stream, SecuritySendFlags.Authenticated | SecuritySendFlags.Encrypted);
885888
}
886889
}
887890

@@ -908,7 +911,7 @@ internal IEnumerator TimeOutSwitchSceneProgress(SceneSwitchProgress switchSceneP
908911
switchSceneProgress.SetTimedOut();
909912
}
910913

911-
private void HandleRawTransportPoll(NetEventType eventType, ulong clientId, string channelName, ArraySegment<byte> payload, float receiveTime)
914+
private void HandleRawTransportPoll(NetEventType eventType, ulong clientId, byte channel, ArraySegment<byte> payload, float receiveTime)
912915
{
913916
ProfilerStatManager.bytesRcvd.Record(payload.Count);
914917
switch (eventType)
@@ -917,7 +920,7 @@ private void HandleRawTransportPoll(NetEventType eventType, ulong clientId, stri
917920
#if DEVELOPMENT_BUILD || UNITY_EDITOR
918921
s_TransportConnect.Begin();
919922
#endif
920-
NetworkProfiler.StartEvent(TickType.Receive, (uint)payload.Count, channelName, "TRANSPORT_CONNECT");
923+
NetworkProfiler.StartEvent(TickType.Receive, (uint)payload.Count, channel, "TRANSPORT_CONNECT");
921924
if (IsServer)
922925
{
923926
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("Client Connected");
@@ -984,7 +987,7 @@ private void HandleRawTransportPoll(NetEventType eventType, ulong clientId, stri
984987
}
985988
}
986989
// Send the hail
987-
InternalMessageSender.Send(clientId, MLAPIConstants.MLAPI_CERTIFICATE_HAIL, "MLAPI_INTERNAL", hailStream, SecuritySendFlags.None, null);
990+
InternalMessageSender.Send(clientId, MLAPIConstants.MLAPI_CERTIFICATE_HAIL, Transport.MLAPI_INTERNAL_CHANNEL, hailStream, SecuritySendFlags.None);
988991
}
989992
}
990993
else
@@ -1016,14 +1019,14 @@ private void HandleRawTransportPoll(NetEventType eventType, ulong clientId, stri
10161019
case NetEventType.Data:
10171020
{
10181021
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo($"Incoming Data From {clientId} : {payload.Count} bytes");
1019-
HandleIncomingData(clientId, channelName, payload, receiveTime, true);
1022+
HandleIncomingData(clientId, channel, payload, receiveTime, true);
10201023
break;
10211024
}
10221025
case NetEventType.Disconnect:
10231026
#if DEVELOPMENT_BUILD || UNITY_EDITOR
10241027
s_TransportDisconnect.Begin();
10251028
#endif
1026-
NetworkProfiler.StartEvent(TickType.Receive, 0, "NONE", "TRANSPORT_DISCONNECT");
1029+
NetworkProfiler.StartEvent(TickType.Receive, 0, Transport.MLAPI_INTERNAL_CHANNEL, "TRANSPORT_DISCONNECT");
10271030

10281031
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("Disconnect Event From " + clientId);
10291032

@@ -1048,7 +1051,7 @@ private void HandleRawTransportPoll(NetEventType eventType, ulong clientId, stri
10481051
private readonly BitStream inputStreamWrapper = new BitStream(new byte[0]);
10491052
private MessageBatcher batcher = new MessageBatcher();
10501053

1051-
internal void HandleIncomingData(ulong clientId, string channelName, ArraySegment<byte> data, float receiveTime, bool allowBuffer)
1054+
internal void HandleIncomingData(ulong clientId, byte channel, ArraySegment<byte> data, float receiveTime, bool allowBuffer)
10521055
{
10531056
#if DEVELOPMENT_BUILD || UNITY_EDITOR
10541057
s_HandleIncomingData.Begin();
@@ -1073,7 +1076,7 @@ internal void HandleIncomingData(ulong clientId, string channelName, ArraySegmen
10731076
}
10741077

10751078
uint headerByteSize = (uint)Arithmetic.VarIntSize(messageType);
1076-
NetworkProfiler.StartEvent(TickType.Receive, (uint)(data.Count - headerByteSize), channelName, messageType);
1079+
NetworkProfiler.StartEvent(TickType.Receive, (uint)(data.Count - headerByteSize), channel, messageType);
10771080

10781081
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("Data Header: messageType=" + messageType);
10791082

@@ -1120,7 +1123,7 @@ internal void HandleIncomingData(ulong clientId, string channelName, ArraySegmen
11201123
InternalMessageHandler.HandleNetworkedVarDelta(clientId, messageStream, BufferCallback, new PreBufferPreset()
11211124
{
11221125
AllowBuffer = allowBuffer,
1123-
ChannelName = channelName,
1126+
Channel = channel,
11241127
ClientId = clientId,
11251128
Data = data,
11261129
MessageType = messageType,
@@ -1131,7 +1134,7 @@ internal void HandleIncomingData(ulong clientId, string channelName, ArraySegmen
11311134
InternalMessageHandler.HandleNetworkedVarUpdate(clientId, messageStream, BufferCallback, new PreBufferPreset()
11321135
{
11331136
AllowBuffer = allowBuffer,
1134-
ChannelName = channelName,
1137+
Channel = channel,
11351138
ClientId = clientId,
11361139
Data = data,
11371140
MessageType = messageType,
@@ -1266,7 +1269,7 @@ private void BufferCallback(ulong networkId, PreBufferPreset preset)
12661269
throw new InvalidOperationException("Cannot buffer on server.");
12671270
}
12681271

1269-
BufferManager.BufferMessageForNetworkId(networkId, preset.ClientId, preset.ChannelName, preset.ReceiveTime, preset.Data);
1272+
BufferManager.BufferMessageForNetworkId(networkId, preset.ClientId, preset.Channel, preset.ReceiveTime, preset.Data);
12701273
}
12711274

12721275
/// <summary>
@@ -1375,7 +1378,7 @@ private void SyncTime()
13751378
using (PooledBitWriter writer = PooledBitWriter.Get(stream))
13761379
{
13771380
writer.WriteSinglePacked(Time.realtimeSinceStartup);
1378-
InternalMessageSender.Send(MLAPIConstants.MLAPI_TIME_SYNC, "MLAPI_TIME_SYNC", stream, SecuritySendFlags.None);
1381+
InternalMessageSender.Send(MLAPIConstants.MLAPI_TIME_SYNC, Transport.MLAPI_TIME_SYNC_CHANNEL, stream, SecuritySendFlags.None);
13791382
}
13801383
}
13811384
#if DEVELOPMENT_BUILD || UNITY_EDITOR
@@ -1509,7 +1512,7 @@ internal void HandleApproval(ulong clientId, bool createPlayerObject, ulong? pla
15091512
}
15101513
}
15111514

1512-
InternalMessageSender.Send(clientId, MLAPIConstants.MLAPI_CONNECTION_APPROVED, "MLAPI_INTERNAL", stream, SecuritySendFlags.Encrypted | SecuritySendFlags.Authenticated);
1515+
InternalMessageSender.Send(clientId, MLAPIConstants.MLAPI_CONNECTION_APPROVED, Transport.MLAPI_INTERNAL_CHANNEL, stream, SecuritySendFlags.Encrypted | SecuritySendFlags.Authenticated);
15131516

15141517
if (OnClientConnectedCallback != null)
15151518
OnClientConnectedCallback.Invoke(clientId);
@@ -1571,7 +1574,7 @@ internal void HandleApproval(ulong clientId, bool createPlayerObject, ulong? pla
15711574
ConnectedClients[clientId].PlayerObject.WriteNetworkedVarData(stream, clientPair.Key);
15721575
}
15731576

1574-
InternalMessageSender.Send(clientPair.Key, MLAPIConstants.MLAPI_ADD_OBJECT, "MLAPI_INTERNAL", stream, SecuritySendFlags.None);
1577+
InternalMessageSender.Send(clientPair.Key, MLAPIConstants.MLAPI_ADD_OBJECT, Transport.MLAPI_INTERNAL_CHANNEL, stream, SecuritySendFlags.None);
15751578
}
15761579
}
15771580
}

com.unity.multiplayer.mlapi/Runtime/Core/RPCQueue/FrameQueueItem.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ public struct FrameQueueItem
1616
public RpcQueueContainer.QueueItemType queueItemType;
1717
public SecuritySendFlags sendFlags;
1818
public ulong networkId; //Sender's network Identifier
19-
public string channel;
19+
public byte channel;
2020
public ulong[] clientIds; //Server invoked Client RPCs only
2121
public long streamSize;
2222
public float timeStamp;

com.unity.multiplayer.mlapi/Runtime/Core/RPCQueue/QueueHistoryFrame.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ private FrameQueueItem GetCurrentQueueItem()
8585
if (m_QueueFrameType == QueueFrameType.Outbound)
8686
{
8787
//Outbound we care about both channel and clients
88-
m_CurrentQueueItem.channel = queueReader.ReadString().ToString();
88+
m_CurrentQueueItem.channel = queueReader.ReadByteDirect();
8989
int NumClients = queueReader.ReadInt32();
9090
if (NumClients > 0 && NumClients < m_MaximumClients)
9191
{

0 commit comments

Comments
 (0)