-
Notifications
You must be signed in to change notification settings - Fork 461
Expand file tree
/
Copy pathInternalMessageHandler.cs
More file actions
762 lines (675 loc) · 34.5 KB
/
InternalMessageHandler.cs
File metadata and controls
762 lines (675 loc) · 34.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
using System;
using System.IO;
using MLAPI.Configuration;
using MLAPI.Connection;
#if !DISABLE_CRYPTOGRAPHY
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
#endif
using MLAPI.Security;
using MLAPI.Logging;
using MLAPI.SceneManagement;
using MLAPI.Serialization.Pooled;
using MLAPI.Spawning;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using System.Collections.Generic;
using MLAPI.Messaging.Buffering;
using MLAPI.Profiling;
using Unity.Profiling;
using MLAPI.Serialization;
using MLAPI.Transports;
using BitStream = MLAPI.Serialization.BitStream;
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_HandleNetworkedVarDelta =
new ProfilerMarker("InternalMessageHandler.HandleNetworkedVarDelta");
static ProfilerMarker s_HandleNetworkedVarUpdate =
new ProfilerMarker("InternalMessageHandler.HandleNetworkedVarUpdate");
static ProfilerMarker s_HandleUnnamedMessage =
new ProfilerMarker("InternalMessageHandler.HandleUnnamedMessage");
static ProfilerMarker s_HandleNamedMessage =
new ProfilerMarker("InternalMessageHandler.HandleNamedMessage");
static ProfilerMarker s_HandleNetworkLog =
new ProfilerMarker("InternalMessageHandler.HandleNetworkLog");
#endif
#if !DISABLE_CRYPTOGRAPHY
// Runs on client
internal static void HandleHailRequest(ulong clientId, Stream stream)
{
X509Certificate2 certificate = null;
byte[] serverDiffieHellmanPublicPart = null;
using (PooledBitReader reader = PooledBitReader.Get(stream))
{
if (NetworkingManager.Singleton.NetworkConfig.EnableEncryption)
{
// Read the certificate
if (NetworkingManager.Singleton.NetworkConfig.SignKeyExchange)
{
// Allocation justification: This runs on client and only once, at initial connection
certificate = new X509Certificate2(reader.ReadByteArray());
if (CryptographyHelper.VerifyCertificate(certificate, NetworkingManager.Singleton.ConnectedHostname))
{
// The certificate is not valid :(
// Man in the middle.
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("Invalid certificate. Disconnecting");
NetworkingManager.Singleton.StopClient();
return;
}
else
{
NetworkingManager.Singleton.NetworkConfig.ServerX509Certificate = certificate;
}
}
// Read the ECDH
// Allocation justification: This runs on client and only once, at initial connection
serverDiffieHellmanPublicPart = reader.ReadByteArray();
// Verify the key exchange
if (NetworkingManager.Singleton.NetworkConfig.SignKeyExchange)
{
int signatureType = reader.ReadByte();
byte[] serverDiffieHellmanPublicPartSignature = reader.ReadByteArray();
if (signatureType == 0)
{
RSACryptoServiceProvider rsa = certificate.PublicKey.Key as RSACryptoServiceProvider;
if (rsa != null)
{
using (SHA256Managed sha = new SHA256Managed())
{
if (!rsa.VerifyData(serverDiffieHellmanPublicPart, sha, serverDiffieHellmanPublicPartSignature))
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("Invalid RSA signature. Disconnecting");
NetworkingManager.Singleton.StopClient();
return;
}
}
}
else
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("No RSA key found in certificate. Disconnecting");
NetworkingManager.Singleton.StopClient();
return;
}
}
else if (signatureType == 1)
{
DSACryptoServiceProvider dsa = certificate.PublicKey.Key as DSACryptoServiceProvider;
if (dsa != null)
{
using (SHA256Managed sha = new SHA256Managed())
{
if (!dsa.VerifyData(sha.ComputeHash(serverDiffieHellmanPublicPart), serverDiffieHellmanPublicPartSignature))
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("Invalid DSA signature. Disconnecting");
NetworkingManager.Singleton.StopClient();
return;
}
}
}
else
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("No DSA key found in certificate. Disconnecting");
NetworkingManager.Singleton.StopClient();
return;
}
}
else
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("Invalid signature type. Disconnecting");
NetworkingManager.Singleton.StopClient();
return;
}
}
}
}
using (PooledBitStream outStream = PooledBitStream.Get())
{
using (PooledBitWriter writer = PooledBitWriter.Get(outStream))
{
if (NetworkingManager.Singleton.NetworkConfig.EnableEncryption)
{
// Create a ECDH key
EllipticDiffieHellman diffieHellman = new EllipticDiffieHellman(EllipticDiffieHellman.DEFAULT_CURVE, EllipticDiffieHellman.DEFAULT_GENERATOR, EllipticDiffieHellman.DEFAULT_ORDER);
NetworkingManager.Singleton.clientAesKey = diffieHellman.GetSharedSecret(serverDiffieHellmanPublicPart);
byte[] diffieHellmanPublicKey = diffieHellman.GetPublicKey();
writer.WriteByteArray(diffieHellmanPublicKey);
}
}
// Send HailResponse
InternalMessageSender.Send(NetworkingManager.Singleton.ServerClientId, MLAPIConstants.MLAPI_CERTIFICATE_HAIL_RESPONSE, Channel.Internal, outStream, SecuritySendFlags.None);
}
}
// Ran on server
internal static void HandleHailResponse(ulong clientId, Stream stream)
{
if (!NetworkingManager.Singleton.PendingClients.ContainsKey(clientId) || NetworkingManager.Singleton.PendingClients[clientId].ConnectionState != PendingClient.State.PendingHail) return;
if (!NetworkingManager.Singleton.NetworkConfig.EnableEncryption) return;
using (PooledBitReader reader = PooledBitReader.Get(stream))
{
if (NetworkingManager.Singleton.PendingClients[clientId].KeyExchange != null)
{
byte[] diffieHellmanPublic = reader.ReadByteArray();
NetworkingManager.Singleton.PendingClients[clientId].AesKey = NetworkingManager.Singleton.PendingClients[clientId].KeyExchange.GetSharedSecret(diffieHellmanPublic);
}
}
NetworkingManager.Singleton.PendingClients[clientId].ConnectionState = PendingClient.State.PendingConnection;
NetworkingManager.Singleton.PendingClients[clientId].KeyExchange = null; // Give to GC
// Send greetings, they have passed all the handshakes
using (PooledBitStream outStream = PooledBitStream.Get())
{
using (PooledBitWriter writer = PooledBitWriter.Get(outStream))
{
writer.WriteInt64Packed(DateTime.Now.Ticks); // This serves no purpose.
}
InternalMessageSender.Send(clientId, MLAPIConstants.MLAPI_GREETINGS, Channel.Internal, outStream, SecuritySendFlags.None);
}
}
internal static void HandleGreetings(ulong clientId, Stream stream)
{
// Server greeted us, we can now initiate our request to connect.
NetworkingManager.Singleton.SendConnectionRequest();
}
#endif
internal static void HandleConnectionRequest(ulong clientId, Stream stream)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleConnectionRequest.Begin();
#endif
using (PooledBitReader reader = PooledBitReader.Get(stream))
{
ulong configHash = reader.ReadUInt64Packed();
if (!NetworkingManager.Singleton.NetworkConfig.CompareConfig(configHash))
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("NetworkConfiguration mismatch. The configuration between the server and client does not match");
NetworkingManager.Singleton.DisconnectClient(clientId);
return;
}
if (NetworkingManager.Singleton.NetworkConfig.ConnectionApproval)
{
byte[] connectionBuffer = reader.ReadByteArray();
NetworkingManager.Singleton.InvokeConnectionApproval(connectionBuffer, clientId, (createPlayerObject, playerPrefabHash, approved, position, rotation) =>
{
NetworkingManager.Singleton.HandleApproval(clientId, createPlayerObject, playerPrefabHash, approved, position, rotation);
});
}
else
{
NetworkingManager.Singleton.HandleApproval(clientId, NetworkingManager.Singleton.NetworkConfig.CreatePlayerPrefab, null, true, null, null);
}
}
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleConnectionRequest.End();
#endif
}
internal static void HandleConnectionApproved(ulong clientId, Stream stream, float receiveTime)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleConnectionApproved.Begin();
#endif
using (PooledBitReader reader = PooledBitReader.Get(stream))
{
NetworkingManager.Singleton.LocalClientId = reader.ReadUInt64Packed();
uint sceneIndex = 0;
Guid sceneSwitchProgressGuid = new Guid();
if (NetworkingManager.Singleton.NetworkConfig.EnableSceneManagement)
{
sceneIndex = reader.ReadUInt32Packed();
sceneSwitchProgressGuid = new Guid(reader.ReadByteArray());
}
bool sceneSwitch = NetworkingManager.Singleton.NetworkConfig.EnableSceneManagement && NetworkSceneManager.HasSceneMismatch(sceneIndex);
float netTime = reader.ReadSinglePacked();
NetworkingManager.Singleton.UpdateNetworkTime(clientId, netTime, receiveTime, true);
NetworkingManager.Singleton.ConnectedClients.Add(NetworkingManager.Singleton.LocalClientId, new NetworkedClient() { ClientId = NetworkingManager.Singleton.LocalClientId });
void DelayedSpawnAction(Stream continuationStream)
{
using (PooledBitReader continuationReader = PooledBitReader.Get(continuationStream))
{
if (!NetworkingManager.Singleton.NetworkConfig.EnableSceneManagement || NetworkingManager.Singleton.NetworkConfig.UsePrefabSync)
{
SpawnManager.DestroySceneObjects();
}
else
{
SpawnManager.ClientCollectSoftSyncSceneObjectSweep(null);
}
uint objectCount = continuationReader.ReadUInt32Packed();
for (int i = 0; i < objectCount; i++)
{
bool isPlayerObject = continuationReader.ReadBool();
ulong networkId = continuationReader.ReadUInt64Packed();
ulong ownerId = continuationReader.ReadUInt64Packed();
bool hasParent = continuationReader.ReadBool();
ulong? parentNetworkId = null;
if (hasParent)
{
parentNetworkId = continuationReader.ReadUInt64Packed();
}
ulong prefabHash;
ulong instanceId;
bool softSync;
if (!NetworkingManager.Singleton.NetworkConfig.EnableSceneManagement || NetworkingManager.Singleton.NetworkConfig.UsePrefabSync)
{
softSync = false;
instanceId = 0;
prefabHash = continuationReader.ReadUInt64Packed();
}
else
{
softSync = continuationReader.ReadBool();
if (softSync)
{
instanceId = continuationReader.ReadUInt64Packed();
prefabHash = 0;
}
else
{
prefabHash = continuationReader.ReadUInt64Packed();
instanceId = 0;
}
}
Vector3? pos = null;
Quaternion? rot = null;
if (continuationReader.ReadBool())
{
pos = new Vector3(continuationReader.ReadSinglePacked(), continuationReader.ReadSinglePacked(), continuationReader.ReadSinglePacked());
rot = Quaternion.Euler(continuationReader.ReadSinglePacked(), continuationReader.ReadSinglePacked(), continuationReader.ReadSinglePacked());
}
NetworkedObject netObject = SpawnManager.CreateLocalNetworkedObject(softSync, instanceId, prefabHash, parentNetworkId, pos, rot);
SpawnManager.SpawnNetworkedObjectLocally(netObject, networkId, softSync, isPlayerObject, ownerId, continuationStream, false, 0, true, false);
Queue<BufferManager.BufferedMessage> bufferQueue = BufferManager.ConsumeBuffersForNetworkId(networkId);
// Apply buffered messages
if (bufferQueue != null)
{
while (bufferQueue.Count > 0)
{
BufferManager.BufferedMessage message = bufferQueue.Dequeue();
NetworkingManager.Singleton.HandleIncomingData(message.sender, message.channel, new ArraySegment<byte>(message.payload.GetBuffer(), (int)message.payload.Position, (int)message.payload.Length), message.receiveTime, false);
BufferManager.RecycleConsumedBufferedMessage(message);
}
}
}
SpawnManager.CleanDiffedSceneObjects();
NetworkingManager.Singleton.IsConnectedClient = true;
NetworkingManager.Singleton.InvokeOnClientConnectedCallback(NetworkingManager.Singleton.LocalClientId);
}
}
if (sceneSwitch)
{
UnityAction<Scene, Scene> onSceneLoaded = null;
Serialization.BitStream continuationStream = new Serialization.BitStream();
continuationStream.CopyUnreadFrom(stream);
continuationStream.Position = 0;
void OnSceneLoadComplete()
{
SceneManager.activeSceneChanged -= onSceneLoaded;
NetworkSceneManager.isSpawnedObjectsPendingInDontDestroyOnLoad = false;
DelayedSpawnAction(continuationStream);
}
onSceneLoaded = (oldScene, newScene) => { OnSceneLoadComplete(); };
SceneManager.activeSceneChanged += onSceneLoaded;
NetworkSceneManager.OnFirstSceneSwitchSync(sceneIndex, sceneSwitchProgressGuid);
}
else
{
DelayedSpawnAction(stream);
}
}
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleConnectionApproved.End();
#endif
}
internal static void HandleAddObject(ulong clientId, Stream stream)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleAddObject.Begin();
#endif
using (PooledBitReader reader = PooledBitReader.Get(stream))
{
bool isPlayerObject = reader.ReadBool();
ulong networkId = reader.ReadUInt64Packed();
ulong ownerId = reader.ReadUInt64Packed();
bool hasParent = reader.ReadBool();
ulong? parentNetworkId = null;
if (hasParent)
{
parentNetworkId = reader.ReadUInt64Packed();
}
ulong prefabHash;
ulong instanceId;
bool softSync;
if (!NetworkingManager.Singleton.NetworkConfig.EnableSceneManagement || NetworkingManager.Singleton.NetworkConfig.UsePrefabSync)
{
softSync = false;
instanceId = 0;
prefabHash = reader.ReadUInt64Packed();
}
else
{
softSync = reader.ReadBool();
if (softSync)
{
instanceId = reader.ReadUInt64Packed();
prefabHash = 0;
}
else
{
prefabHash = reader.ReadUInt64Packed();
instanceId = 0;
}
}
Vector3? pos = null;
Quaternion? rot = null;
if (reader.ReadBool())
{
pos = new Vector3(reader.ReadSinglePacked(), reader.ReadSinglePacked(), reader.ReadSinglePacked());
rot = Quaternion.Euler(reader.ReadSinglePacked(), reader.ReadSinglePacked(), reader.ReadSinglePacked());
}
bool hasPayload = reader.ReadBool();
int payLoadLength = hasPayload ? reader.ReadInt32Packed() : 0;
NetworkedObject netObject = SpawnManager.CreateLocalNetworkedObject(softSync, instanceId, prefabHash, parentNetworkId, pos, rot);
SpawnManager.SpawnNetworkedObjectLocally(netObject, networkId, softSync, isPlayerObject, ownerId, stream, hasPayload, payLoadLength, true, false);
Queue<BufferManager.BufferedMessage> bufferQueue = BufferManager.ConsumeBuffersForNetworkId(networkId);
// Apply buffered messages
if (bufferQueue != null)
{
while (bufferQueue.Count > 0)
{
BufferManager.BufferedMessage message = bufferQueue.Dequeue();
NetworkingManager.Singleton.HandleIncomingData(message.sender, message.channel, new ArraySegment<byte>(message.payload.GetBuffer(), (int)message.payload.Position, (int)message.payload.Length), message.receiveTime, false);
BufferManager.RecycleConsumedBufferedMessage(message);
}
}
}
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleAddObject.End();
#endif
}
internal static void HandleDestroyObject(ulong clientId, Stream stream)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleDestroyObject.Begin();
#endif
using (PooledBitReader reader = PooledBitReader.Get(stream))
{
ulong networkId = reader.ReadUInt64Packed();
SpawnManager.OnDestroyObject(networkId, true);
}
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleDestroyObject.End();
#endif
}
internal static void HandleSwitchScene(ulong clientId, Stream stream)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleSwitchScene.Begin();
#endif
using (PooledBitReader reader = PooledBitReader.Get(stream))
{
uint sceneIndex = reader.ReadUInt32Packed();
Guid switchSceneGuid = new Guid(reader.ReadByteArray());
Serialization.BitStream objectStream = new Serialization.BitStream();
objectStream.CopyUnreadFrom(stream);
objectStream.Position = 0;
NetworkSceneManager.OnSceneSwitch(sceneIndex, switchSceneGuid, objectStream);
}
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleSwitchScene.End();
#endif
}
internal static void HandleClientSwitchSceneCompleted(ulong clientId, Stream stream)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleClientSwitchSceneCompleted.Begin();
#endif
using (PooledBitReader reader = PooledBitReader.Get(stream))
{
NetworkSceneManager.OnClientSwitchSceneCompleted(clientId, new Guid(reader.ReadByteArray()));
}
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleClientSwitchSceneCompleted.End();
#endif
}
internal static void HandleChangeOwner(ulong clientId, Stream stream)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleChangeOwner.Begin();
#endif
using (PooledBitReader reader = PooledBitReader.Get(stream))
{
ulong networkId = reader.ReadUInt64Packed();
ulong ownerClientId = reader.ReadUInt64Packed();
if (SpawnManager.SpawnedObjects[networkId].OwnerClientId == NetworkingManager.Singleton.LocalClientId)
{
//We are current owner.
SpawnManager.SpawnedObjects[networkId].InvokeBehaviourOnLostOwnership();
}
if (ownerClientId == NetworkingManager.Singleton.LocalClientId)
{
//We are new owner.
SpawnManager.SpawnedObjects[networkId].InvokeBehaviourOnGainedOwnership();
}
SpawnManager.SpawnedObjects[networkId].OwnerClientId = ownerClientId;
}
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleChangeOwner.End();
#endif
}
internal static void HandleAddObjects(ulong clientId, Stream stream)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleAddObjects.Begin();
#endif
using (PooledBitReader reader = PooledBitReader.Get(stream))
{
ushort objectCount = reader.ReadUInt16Packed();
for (int i = 0; i < objectCount; i++)
{
HandleAddObject(clientId, stream);
}
}
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleAddObjects.End();
#endif
}
internal static void HandleDestroyObjects(ulong clientId, Stream stream)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleDestroyObjects.Begin();
#endif
using (PooledBitReader reader = PooledBitReader.Get(stream))
{
ushort objectCount = reader.ReadUInt16Packed();
for (int i = 0; i < objectCount; i++)
{
HandleDestroyObject(clientId, stream);
}
}
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleDestroyObjects.End();
#endif
}
internal static void HandleTimeSync(ulong clientId, Stream stream, float receiveTime)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleTimeSync.Begin();
#endif
using (PooledBitReader reader = PooledBitReader.Get(stream))
{
float netTime = reader.ReadSinglePacked();
NetworkingManager.Singleton.UpdateNetworkTime(clientId, netTime, receiveTime);
}
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleTimeSync.End();
#endif
}
internal static void HandleNetworkedVarDelta(ulong clientId, Stream stream, Action<ulong, PreBufferPreset> bufferCallback, PreBufferPreset bufferPreset)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleNetworkedVarDelta.Begin();
#endif
if (!NetworkingManager.Singleton.NetworkConfig.EnableNetworkedVar)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("NetworkedVar delta received but EnableNetworkedVar is false");
return;
}
using (PooledBitReader reader = PooledBitReader.Get(stream))
{
ulong networkId = reader.ReadUInt64Packed();
ushort orderIndex = reader.ReadUInt16Packed();
if (SpawnManager.SpawnedObjects.ContainsKey(networkId))
{
NetworkedBehaviour instance = SpawnManager.SpawnedObjects[networkId].GetBehaviourAtOrderIndex(orderIndex);
if (instance == null)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("NetworkedVarDelta message received for a non-existent behaviour. NetworkId: " + networkId + ", behaviourIndex: " + orderIndex);
}
else
{
NetworkedBehaviour.HandleNetworkedVarDeltas(instance.networkedVarFields, stream, clientId, instance);
}
}
else if (NetworkingManager.Singleton.IsServer || !NetworkingManager.Singleton.NetworkConfig.EnableMessageBuffering)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("NetworkedVarDelta message received for a non-existent object with id: " + networkId + ". This delta was lost.");
}
else
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("NetworkedVarDelta message received for a non-existent object with id: " + networkId + ". This delta will be buffered and might be recovered.");
bufferCallback(networkId, bufferPreset);
}
}
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleNetworkedVarDelta.End();
#endif
}
internal static void HandleNetworkedVarUpdate(ulong clientId, Stream stream, Action<ulong, PreBufferPreset> bufferCallback, PreBufferPreset bufferPreset)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleNetworkedVarUpdate.Begin();
#endif
if (!NetworkingManager.Singleton.NetworkConfig.EnableNetworkedVar)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("NetworkedVar update received but EnableNetworkedVar is false");
return;
}
using (PooledBitReader reader = PooledBitReader.Get(stream))
{
ulong networkId = reader.ReadUInt64Packed();
ushort orderIndex = reader.ReadUInt16Packed();
if (SpawnManager.SpawnedObjects.ContainsKey(networkId))
{
NetworkedBehaviour instance = SpawnManager.SpawnedObjects[networkId].GetBehaviourAtOrderIndex(orderIndex);
if (instance == null)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("NetworkedVarUpdate message received for a non-existent behaviour. NetworkId: " + networkId + ", behaviourIndex: " + orderIndex);
}
else
{
NetworkedBehaviour.HandleNetworkedVarUpdate(instance.networkedVarFields, stream, clientId, instance);
}
}
else if (NetworkingManager.Singleton.IsServer || !NetworkingManager.Singleton.NetworkConfig.EnableMessageBuffering)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("NetworkedVarUpdate message received for a non-existent object with id: " + networkId + ". This delta was lost.");
}
else
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("NetworkedVarUpdate message received for a non-existent object with id: " + networkId + ". This delta will be buffered and might be recovered.");
bufferCallback(networkId, bufferPreset);
}
}
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleNetworkedVarUpdate.End();
#endif
}
/// <summary>
/// Converts the stream to a PerformanceQueueItem and adds it to the receive queue
/// </summary>
/// <param name="clientId"></param>
/// <param name="stream"></param>
/// <param name="receiveTime"></param>
internal static void RPCReceiveQueueItem(ulong clientId, Stream stream, float receiveTime, RpcQueueContainer.QueueItemType queueItemType)
{
if (NetworkingManager.Singleton.IsServer && clientId == NetworkingManager.Singleton.ServerClientId)
{
return;
}
ProfilerStatManager.rpcsRcvd.Record();
PerformanceDataManager.Increment(ProfilerConstants.NumberOfRPCsReceived.ToString());
var rpcQueueContainer = NetworkingManager.Singleton.rpcQueueContainer;
rpcQueueContainer.AddQueueItemToInboundFrame(queueItemType, receiveTime, clientId, (BitStream)stream);
}
internal static void HandleUnnamedMessage(ulong clientId, Stream stream)
{
PerformanceDataManager.Increment(ProfilerConstants.NumberOfUnnamedMessages.ToString());
ProfilerStatManager.unnamedMessage.Record();
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleUnnamedMessage.Begin();
#endif
CustomMessagingManager.InvokeUnnamedMessage(clientId, stream);
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleUnnamedMessage.End();
#endif
}
internal static void HandleNamedMessage(ulong clientId, Stream stream)
{
PerformanceDataManager.Increment(ProfilerConstants.NumberOfNamedMessages.ToString());
ProfilerStatManager.namedMessage.Record();
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleNamedMessage.Begin();
#endif
using (PooledBitReader reader = PooledBitReader.Get(stream))
{
ulong hash = reader.ReadUInt64Packed();
CustomMessagingManager.InvokeNamedMessage(hash, clientId, stream);
}
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleNamedMessage.End();
#endif
}
internal static void HandleNetworkLog(ulong clientId, Stream stream)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleNetworkLog.Begin();
#endif
using (PooledBitReader reader = PooledBitReader.Get(stream))
{
NetworkLog.LogType logType = (NetworkLog.LogType)reader.ReadByte();
string message = reader.ReadStringPacked().ToString();
switch (logType)
{
case NetworkLog.LogType.Info:
NetworkLog.LogInfoServerLocal(message, clientId);
break;
case NetworkLog.LogType.Warning:
NetworkLog.LogWarningServerLocal(message, clientId);
break;
case NetworkLog.LogType.Error:
NetworkLog.LogErrorServerLocal(message, clientId);
break;
}
}
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleNetworkLog.End();
#endif
}
}
}