Repository navigation
Expand file tree
/
Copy pathNetworkVariableTests.cs
More file actions
4919 lines (4472 loc) · 242 KB
/
Copy pathNetworkVariableTests.cs
File metadata and controls
4919 lines (4472 loc) · 242 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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#if !NGO_MINIMALPROJECT
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Unity.Collections;
using Unity.Netcode.TestHelpers.Runtime;
using UnityEngine;
using UnityEngine.TestTools;
namespace Unity.Netcode.RuntimeTests
{
internal struct TestStruct : INetworkSerializable, IEquatable<TestStruct>
{
public uint SomeInt;
public bool SomeBool;
public static bool NetworkSerializeCalledOnWrite;
public static bool NetworkSerializeCalledOnRead;
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
if (serializer.IsReader)
{
NetworkSerializeCalledOnRead = true;
}
else
{
NetworkSerializeCalledOnWrite = true;
}
serializer.SerializeValue(ref SomeInt);
serializer.SerializeValue(ref SomeBool);
}
public bool Equals(TestStruct other)
{
return SomeInt == other.SomeInt && SomeBool == other.SomeBool;
}
public override bool Equals(object obj)
{
return obj is TestStruct other && Equals(other);
}
public override int GetHashCode()
{
unchecked
{
return ((int)SomeInt * 397) ^ SomeBool.GetHashCode();
}
}
}
internal class TestClass : INetworkSerializable, IEquatable<TestClass>
{
public uint SomeInt;
public bool SomeBool;
public static bool NetworkSerializeCalledOnWrite;
public static bool NetworkSerializeCalledOnRead;
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
if (serializer.IsReader)
{
NetworkSerializeCalledOnRead = true;
}
else
{
NetworkSerializeCalledOnWrite = true;
}
serializer.SerializeValue(ref SomeInt);
serializer.SerializeValue(ref SomeBool);
}
public bool Equals(TestClass other)
{
return SomeInt == other.SomeInt && SomeBool == other.SomeBool;
}
public override bool Equals(object obj)
{
return obj is TestClass other && Equals(other);
}
public override int GetHashCode()
{
unchecked
{
return ((int)SomeInt * 397) ^ SomeBool.GetHashCode();
}
}
}
// Used just to create a NetworkVariable in the templated NetworkBehaviour type that isn't referenced anywhere else
// Please do not reference this class anywhere else!
internal class TestClass_ReferencedOnlyByTemplateNetworkBehaviourType : TestClass, IEquatable<TestClass_ReferencedOnlyByTemplateNetworkBehaviourType>
{
public bool Equals(TestClass_ReferencedOnlyByTemplateNetworkBehaviourType other)
{
return Equals((TestClass)other);
}
}
internal class NetworkVariableTest : NetworkBehaviour
{
public enum SomeEnum
{
A,
B,
C
}
public readonly NetworkVariable<int> TheScalar = new NetworkVariable<int>();
public readonly NetworkVariable<SomeEnum> TheEnum = new NetworkVariable<SomeEnum>();
public readonly NetworkVariable<FixedString32Bytes> FixedString32 = new NetworkVariable<FixedString32Bytes>();
public readonly NetworkVariable<TestStruct> TheStruct = new NetworkVariable<TestStruct>();
public readonly NetworkVariable<TestClass> TheClass = new NetworkVariable<TestClass>();
public NetworkVariable<UnmanagedTemplateNetworkSerializableType<TestStruct>> TheTemplateStruct = new NetworkVariable<UnmanagedTemplateNetworkSerializableType<TestStruct>>();
public NetworkVariable<ManagedTemplateNetworkSerializableType<TestClass>> TheTemplateClass = new NetworkVariable<ManagedTemplateNetworkSerializableType<TestClass>>();
public override void OnNetworkSpawn()
{
if (!IsServer)
{
NetworkVariableTests.ClientNetworkVariableTestSpawned(this);
}
base.OnNetworkSpawn();
}
}
internal class NetvarDespawnShutdown : NetworkBehaviour
{
private NetworkVariable<int> m_IntNetworkVariable = new NetworkVariable<int>();
private NetworkList<int> m_IntList;
private void Awake()
{
m_IntList = new NetworkList<int>();
}
public override void OnNetworkDespawn()
{
if (IsServer)
{
m_IntNetworkVariable.Value = 5;
for (int i = 0; i < 10; i++)
{
m_IntList.Add(i);
}
}
base.OnNetworkDespawn();
}
}
/// <summary>
/// Validates that setting values for NetworkVariable or NetworkList during the
/// OnNetworkDespawn method will not cause an exception to occur.
/// </summary>
internal class NetworkVariableModifyOnNetworkDespawn : NetcodeIntegrationTest
{
protected override int NumberOfClients => 1;
private GameObject m_TestPrefab;
protected override void OnOneTimeSetup()
{
NetworkVariableBase.IgnoreInitializeWarning = true;
base.OnOneTimeSetup();
}
protected override void OnOneTimeTearDown()
{
NetworkVariableBase.IgnoreInitializeWarning = false;
base.OnOneTimeTearDown();
}
protected override void OnServerAndClientsCreated()
{
m_TestPrefab = CreateNetworkObjectPrefab("NetVarDespawn");
m_TestPrefab.AddComponent<NetvarDespawnShutdown>();
base.OnServerAndClientsCreated();
}
private bool OnClientSpawnedTestPrefab(ulong networkObjectId)
{
var clientId = m_ClientNetworkManagers[0].LocalClientId;
if (!s_GlobalNetworkObjects.ContainsKey(clientId))
{
return false;
}
if (!s_GlobalNetworkObjects[clientId].ContainsKey(networkObjectId))
{
return false;
}
return true;
}
[UnityTest]
public IEnumerator ModifyNetworkVariableOrListOnNetworkDespawn()
{
var instance = SpawnObject(m_TestPrefab, m_ServerNetworkManager);
yield return WaitForConditionOrTimeOut(() => OnClientSpawnedTestPrefab(instance.GetComponent<NetworkObject>().NetworkObjectId));
m_ServerNetworkManager.Shutdown();
// As long as no excetptions occur, the test passes.
}
}
internal enum Serialization
{
EnsureLengthSafety,
Default,
}
[TestFixture(Serialization.EnsureLengthSafety)]
[TestFixture(Serialization.Default)]
internal class NetworkVariableTests : NetcodeIntegrationTest
{
private const string k_StringTestValue = "abcdefghijklmnopqrstuvwxyz";
private static readonly FixedString32Bytes k_FixedStringTestValue = k_StringTestValue;
protected override int NumberOfClients => 2;
private const uint k_TestUInt = 0x12345678;
private const int k_TestVal1 = 111;
protected override bool m_EnableTimeTravel => true;
protected override bool m_SetupIsACoroutine => false;
protected override bool m_TearDownIsACoroutine => false;
private static List<NetworkVariableTest> s_ClientNetworkVariableTestInstances = new List<NetworkVariableTest>();
public static void ClientNetworkVariableTestSpawned(NetworkVariableTest networkVariableTest)
{
s_ClientNetworkVariableTestInstances.Add(networkVariableTest);
}
// Player1 component on the server
private NetworkVariableTest m_Player1OnServer;
// Player1 component on client1
private NetworkVariableTest m_Player1OnClient1;
private readonly bool m_EnsureLengthSafety;
public NetworkVariableTests(Serialization serialization)
{
m_EnsureLengthSafety = serialization == Serialization.EnsureLengthSafety;
}
private bool m_CanStart = false;
protected override bool CanStartServerAndClients()
{
return m_CanStart;
}
protected override void OnInlineSetup()
{
m_CanStart = false;
base.OnInlineSetup();
}
protected override void OnOneTimeSetup()
{
NetworkVariableBase.IgnoreInitializeWarning = true;
base.OnOneTimeSetup();
}
protected override void OnOneTimeTearDown()
{
NetworkVariableBase.IgnoreInitializeWarning = false;
base.OnOneTimeTearDown();
}
/// <summary>
/// This is an adjustment to how the server and clients are started in order
/// to avoid timing issues when running in a stand alone test runner build.
/// </summary>
private void InitializeServerAndClients(HostOrServer useHost)
{
#if UNIFIED_NETCODE
// HostOrServer arrives as a test method parameter here, so the base class cannot filter the
// hybrid prefab cases NUnit generates from the enum. Do it before anything is started.
ApplyUnifiedTestFilter(useHost);
#endif
s_ClientNetworkVariableTestInstances.Clear();
m_PlayerPrefab.AddComponent<NetworkVariableTest>();
m_PlayerPrefab.AddComponent<ClassHavingNetworkBehaviour>();
m_PlayerPrefab.AddComponent<ClassHavingNetworkBehaviour2>();
m_PlayerPrefab.AddComponent<StructHavingNetworkBehaviour>();
m_UseHost = useHost == HostOrServer.DAHost || useHost == HostOrServer.Host;
m_NetworkTopologyType = useHost == HostOrServer.DAHost ? NetworkTopologyTypes.DistributedAuthority : NetworkTopologyTypes.ClientServer;
m_ServerNetworkManager.NetworkConfig.EnsureNetworkVariableLengthSafety = m_EnsureLengthSafety;
m_ServerNetworkManager.NetworkConfig.PlayerPrefab = m_PlayerPrefab;
SetDistributedAuthorityProperties(m_ServerNetworkManager);
foreach (var client in m_ClientNetworkManagers)
{
client.NetworkConfig.EnsureNetworkVariableLengthSafety = m_EnsureLengthSafety;
client.NetworkConfig.PlayerPrefab = m_PlayerPrefab;
SetDistributedAuthorityProperties(client);
}
var useServer = useHost == HostOrServer.Server;
Assert.True(NetcodeIntegrationTestHelpers.Start(!useServer, m_ServerNetworkManager, m_ClientNetworkManagers), "Failed to start server and client instances");
RegisterSceneManagerHandler();
// Wait for connection on client and server side
var success = WaitForClientsConnectedOrTimeOutWithTimeTravel();
Assert.True(success, $"Timed-out waiting for all clients to connect!");
// These are the *SERVER VERSIONS* of the *CLIENT PLAYER 1 & 2*
var result = new NetcodeIntegrationTestHelpers.ResultWrapper<NetworkObject>();
NetcodeIntegrationTestHelpers.GetNetworkObjectByRepresentationWithTimeTravel(
x => x.IsPlayerObject && x.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId,
m_ServerNetworkManager, result);
// Assign server-side client's player
var serverVersionOfPlayer = result.Result.GetComponent<NetworkVariableTest>();
// This is client1's view of itself
NetcodeIntegrationTestHelpers.GetNetworkObjectByRepresentationWithTimeTravel(
x => x.IsPlayerObject && x.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId,
m_ClientNetworkManagers[0], result);
// Assign client-side local player
var clientVersionOfPlayer = result.Result.GetComponent<NetworkVariableTest>();
// In distributed authority mode, the client is the authority of itself, rather than the server.
var authority = m_DistributedAuthority ? clientVersionOfPlayer : serverVersionOfPlayer;
var nonAuthority = m_DistributedAuthority ? serverVersionOfPlayer : clientVersionOfPlayer;
m_Player1OnServer = authority;
m_Player1OnClient1 = nonAuthority;
var instanceCount = useHost == HostOrServer.Server ? NumberOfClients * 2 : NumberOfClients * 3;
// Wait for the client-side to notify it is finished initializing and spawning.
success = WaitForConditionOrTimeOutWithTimeTravel(() => s_ClientNetworkVariableTestInstances.Count == instanceCount);
Assert.True(success, "Timed out waiting for all client NetworkVariableTest instances to register they have spawned!");
TimeTravelToNextTick();
}
/// <summary>
/// Runs generalized tests on all predefined NetworkVariable types
/// </summary>
[Test]
public void AllNetworkVariableTypes([Values] HostOrServer useHost)
{
#if UNIFIED_NETCODE
// Filter before CreateNetworkObjectPrefab, which routes to CreateHybridPrefab for hybrid cases.
ApplyUnifiedTestFilter(useHost);
#endif
var prefabToSpawn = CreateNetworkObjectPrefab("NetVarTest");
prefabToSpawn.AddComponent<NetworkVariableTestComponent>();
m_CanStart = true;
StartServerAndClientsWithTimeTravel();
var authority = GetAuthorityNetworkManager();
// Shutdown the other clients
foreach (var networkManager in m_NetworkManagers)
{
if (networkManager == authority)
{
continue;
}
StopOneClientWithTimeTravel(networkManager);
}
var instance = SpawnObject(prefabToSpawn, authority);
var networkVariableTestComponent = instance.GetComponent<NetworkVariableTestComponent>();
Assert.IsTrue(networkVariableTestComponent.IsSpawned, $"Failed to spawn {instance.name}!");
// Start Testing
networkVariableTestComponent.InitializeTest();
networkVariableTestComponent.EnableTesting = true;
var success = WaitForConditionOrTimeOutWithTimeTravel(() => true == networkVariableTestComponent.IsTestComplete());
Assert.True(success, "Timed out waiting for the test to complete!");
// Stop Testing
networkVariableTestComponent.EnableTesting = false;
Assert.IsTrue(networkVariableTestComponent.DidAllValuesChange());
networkVariableTestComponent.AssertAllValuesAreCorrect();
// Stop the authority NetworkManager instance
StopOneClientWithTimeTravel(authority);
}
[Test]
public void ClientWritePermissionTest([Values] HostOrServer useHost)
{
InitializeServerAndClients(useHost);
// client must not be allowed to write to a server auth variable
LogAssert.Expect(LogType.Error, m_Player1OnClient1.TheScalar.GetWritePermissionError());
m_Player1OnClient1.TheScalar.Value = k_TestVal1;
}
/// <summary>
/// Runs tests that network variables sync on client whatever the local value of <see cref="Time.timeScale"/>.
/// </summary>
[Test]
public void NetworkVariableSync_WithDifferentTimeScale([Values] HostOrServer useHost, [Values(0.0f, 1.0f, 2.0f)] float timeScale)
{
Time.timeScale = timeScale;
InitializeServerAndClients(useHost);
m_Player1OnServer.TheScalar.Value = k_TestVal1;
// Now wait for the client side version to be updated to k_TestVal1
var success = WaitForConditionOrTimeOutWithTimeTravel(() => m_Player1OnClient1.TheScalar.Value == k_TestVal1);
Assert.True(success, "Timed out waiting for client-side NetworkVariable to update!");
}
[Test]
public void FixedString32Test([Values] HostOrServer useHost)
{
InitializeServerAndClients(useHost);
m_Player1OnServer.FixedString32.Value = k_FixedStringTestValue;
// Now wait for the client side version to be updated to k_FixedStringTestValue
var success = WaitForConditionOrTimeOutWithTimeTravel(() => m_Player1OnClient1.FixedString32.Value == k_FixedStringTestValue);
Assert.True(success, "Timed out waiting for client-side NetworkVariable to update!");
}
[Test]
public void TestNetworkVariableClass([Values] HostOrServer useHost)
{
InitializeServerAndClients(useHost);
bool VerifyClass()
{
return m_Player1OnClient1.TheClass.Value != null &&
m_Player1OnClient1.TheClass.Value.SomeBool == m_Player1OnServer.TheClass.Value.SomeBool &&
m_Player1OnClient1.TheClass.Value.SomeInt == m_Player1OnServer.TheClass.Value.SomeInt;
}
m_Player1OnServer.TheClass.Value = new TestClass { SomeInt = k_TestUInt, SomeBool = false };
m_Player1OnServer.TheClass.SetDirty(true);
// Wait for the client-side to notify it is finished initializing and spawning.
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(VerifyClass));
}
[Test]
public void TestNetworkVariableTemplateClass([Values] HostOrServer useHost)
{
InitializeServerAndClients(useHost);
bool VerifyClass()
{
return m_Player1OnClient1.TheTemplateClass.Value.Value != null && m_Player1OnClient1.TheTemplateClass.Value.Value.SomeBool == m_Player1OnServer.TheTemplateClass.Value.Value.SomeBool &&
m_Player1OnClient1.TheTemplateClass.Value.Value.SomeInt == m_Player1OnServer.TheTemplateClass.Value.Value.SomeInt;
}
m_Player1OnServer.TheTemplateClass.Value = new ManagedTemplateNetworkSerializableType<TestClass> { Value = new TestClass { SomeInt = k_TestUInt, SomeBool = false } };
m_Player1OnServer.TheTemplateClass.SetDirty(true);
// Wait for the client-side to notify it is finished initializing and spawning.
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(VerifyClass));
}
[Test]
public void TestNetworkVariableStruct([Values] HostOrServer useHost)
{
InitializeServerAndClients(useHost);
bool VerifyStructure()
{
return m_Player1OnClient1.TheStruct.Value.SomeBool == m_Player1OnServer.TheStruct.Value.SomeBool &&
m_Player1OnClient1.TheStruct.Value.SomeInt == m_Player1OnServer.TheStruct.Value.SomeInt;
}
m_Player1OnServer.TheStruct.Value = new TestStruct { SomeInt = k_TestUInt, SomeBool = false };
m_Player1OnServer.TheStruct.SetDirty(true);
// Wait for the client-side to notify it is finished initializing and spawning.
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(VerifyStructure));
}
[Test]
public void TestNetworkVariableTemplateStruct([Values] HostOrServer useHost)
{
InitializeServerAndClients(useHost);
bool VerifyStructure()
{
return m_Player1OnClient1.TheTemplateStruct.Value.Value.SomeBool == m_Player1OnServer.TheTemplateStruct.Value.Value.SomeBool &&
m_Player1OnClient1.TheTemplateStruct.Value.Value.SomeInt == m_Player1OnServer.TheTemplateStruct.Value.Value.SomeInt;
}
m_Player1OnServer.TheTemplateStruct.Value = new UnmanagedTemplateNetworkSerializableType<TestStruct> { Value = new TestStruct { SomeInt = k_TestUInt, SomeBool = false } };
m_Player1OnServer.TheTemplateStruct.SetDirty(true);
// Wait for the client-side to notify it is finished initializing and spawning.
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(VerifyStructure));
}
[Test]
public void TestNetworkVariableTemplateBehaviourClass([Values] HostOrServer useHost)
{
InitializeServerAndClients(useHost);
bool VerifyClass()
{
return (m_Player1OnClient1.GetComponent<ClassHavingNetworkBehaviour>().TheVar.Value != null && m_Player1OnClient1.GetComponent<ClassHavingNetworkBehaviour>().TheVar.Value.SomeBool == m_Player1OnServer.GetComponent<ClassHavingNetworkBehaviour>().TheVar.Value.SomeBool &&
m_Player1OnClient1.GetComponent<ClassHavingNetworkBehaviour>().TheVar.Value.SomeInt == m_Player1OnServer.GetComponent<ClassHavingNetworkBehaviour>().TheVar.Value.SomeInt)
&& (m_Player1OnClient1.GetComponent<ClassHavingNetworkBehaviour>().TheVar2.Value != null && m_Player1OnClient1.GetComponent<ClassHavingNetworkBehaviour>().TheVar2.Value.SomeBool == m_Player1OnServer.GetComponent<ClassHavingNetworkBehaviour>().TheVar2.Value.SomeBool &&
m_Player1OnClient1.GetComponent<ClassHavingNetworkBehaviour>().TheVar2.Value.SomeInt == m_Player1OnServer.GetComponent<ClassHavingNetworkBehaviour>().TheVar2.Value.SomeInt);
}
m_Player1OnServer.GetComponent<ClassHavingNetworkBehaviour>().TheVar.Value = new TestClass { SomeInt = k_TestUInt, SomeBool = false };
m_Player1OnServer.GetComponent<ClassHavingNetworkBehaviour>().TheVar2.Value = new TestClass { SomeInt = k_TestUInt, SomeBool = false };
m_Player1OnServer.GetComponent<ClassHavingNetworkBehaviour>().TheVar.SetDirty(true);
m_Player1OnServer.GetComponent<ClassHavingNetworkBehaviour>().TheVar2.SetDirty(true);
// Wait for the client-side to notify it is finished initializing and spawning.
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(VerifyClass));
}
[Test]
public void TestNetworkVariableTemplateBehaviourClassNotReferencedElsewhere([Values] HostOrServer useHost)
{
InitializeServerAndClients(useHost);
bool VerifyClass()
{
return m_Player1OnClient1.GetComponent<ClassHavingNetworkBehaviour2>().TheVar.Value != null && m_Player1OnClient1.GetComponent<ClassHavingNetworkBehaviour2>().TheVar.Value.SomeBool == m_Player1OnServer.GetComponent<ClassHavingNetworkBehaviour2>().TheVar.Value.SomeBool &&
m_Player1OnClient1.GetComponent<ClassHavingNetworkBehaviour2>().TheVar.Value.SomeInt == m_Player1OnServer.GetComponent<ClassHavingNetworkBehaviour2>().TheVar.Value.SomeInt;
}
m_Player1OnServer.GetComponent<ClassHavingNetworkBehaviour2>().TheVar.Value = new TestClass_ReferencedOnlyByTemplateNetworkBehaviourType { SomeInt = k_TestUInt, SomeBool = false };
m_Player1OnServer.GetComponent<ClassHavingNetworkBehaviour2>().TheVar.SetDirty(true);
// Wait for the client-side to notify it is finished initializing and spawning.
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(VerifyClass));
}
[Test]
public void TestNetworkVariableTemplateBehaviourStruct([Values] HostOrServer useHost)
{
InitializeServerAndClients(useHost);
bool VerifyClass()
{
return m_Player1OnClient1.GetComponent<StructHavingNetworkBehaviour>().TheVar.Value.SomeBool == m_Player1OnServer.GetComponent<StructHavingNetworkBehaviour>().TheVar.Value.SomeBool &&
m_Player1OnClient1.GetComponent<StructHavingNetworkBehaviour>().TheVar.Value.SomeInt == m_Player1OnServer.GetComponent<StructHavingNetworkBehaviour>().TheVar.Value.SomeInt;
}
m_Player1OnServer.GetComponent<StructHavingNetworkBehaviour>().TheVar.Value = new TestStruct { SomeInt = k_TestUInt, SomeBool = false };
m_Player1OnServer.GetComponent<StructHavingNetworkBehaviour>().TheVar.SetDirty(true);
// Wait for the client-side to notify it is finished initializing and spawning.
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(VerifyClass));
}
[Test]
public void TestNetworkVariableEnum([Values] HostOrServer useHost)
{
InitializeServerAndClients(useHost);
bool VerifyStructure()
{
return m_Player1OnClient1.TheEnum.Value == NetworkVariableTest.SomeEnum.C;
}
m_Player1OnServer.TheEnum.Value = NetworkVariableTest.SomeEnum.C;
m_Player1OnServer.TheEnum.SetDirty(true);
// Wait for the client-side to notify it is finished initializing and spawning.
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(VerifyStructure));
}
[Test]
public void TestINetworkSerializableClassCallsNetworkSerialize([Values] HostOrServer useHost)
{
InitializeServerAndClients(useHost);
TestClass.NetworkSerializeCalledOnWrite = false;
TestClass.NetworkSerializeCalledOnRead = false;
m_Player1OnServer.TheClass.Value = new TestClass
{
SomeBool = true,
SomeInt = 32
};
static bool VerifyCallback() => TestClass.NetworkSerializeCalledOnWrite && TestClass.NetworkSerializeCalledOnRead;
// Wait for the client-side to notify it is finished initializing and spawning.
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(VerifyCallback));
}
[Test]
public void TestINetworkSerializableStructCallsNetworkSerialize([Values] HostOrServer useHost)
{
InitializeServerAndClients(useHost);
TestStruct.NetworkSerializeCalledOnWrite = false;
TestStruct.NetworkSerializeCalledOnRead = false;
m_Player1OnServer.TheStruct.Value = new TestStruct() { SomeInt = k_TestUInt, SomeBool = false };
static bool VerifyCallback() => TestStruct.NetworkSerializeCalledOnWrite && TestStruct.NetworkSerializeCalledOnRead;
// Wait for the client-side to notify it is finished initializing and spawning.
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(VerifyCallback));
}
[Test]
public void TestCustomGenericSerialization()
{
// Just verifies that the ILPP codegen initialized these values for this type.
Assert.AreEqual(typeof(UnmanagedTypeSerializer<TypeReferencedOnlyInCustomSerialization1>), NetworkVariableSerialization<TypeReferencedOnlyInCustomSerialization1>.Serializer.GetType());
Assert.AreEqual(typeof(UnmanagedTypeSerializer<TypeReferencedOnlyInCustomSerialization2>), NetworkVariableSerialization<TypeReferencedOnlyInCustomSerialization2>.Serializer.GetType());
Assert.AreEqual(typeof(UnmanagedTypeSerializer<TypeReferencedOnlyInCustomSerialization3>), NetworkVariableSerialization<TypeReferencedOnlyInCustomSerialization3>.Serializer.GetType());
Assert.AreEqual(typeof(UnmanagedTypeSerializer<TypeReferencedOnlyInCustomSerialization4>), NetworkVariableSerialization<TypeReferencedOnlyInCustomSerialization4>.Serializer.GetType());
Assert.AreEqual(typeof(UnmanagedTypeSerializer<TypeReferencedOnlyInCustomSerialization5>), NetworkVariableSerialization<TypeReferencedOnlyInCustomSerialization5>.Serializer.GetType());
Assert.AreEqual(typeof(UnmanagedTypeSerializer<TypeReferencedOnlyInCustomSerialization6>), NetworkVariableSerialization<TypeReferencedOnlyInCustomSerialization6>.Serializer.GetType());
Assert.IsNotNull(NetworkVariableSerialization<TypeReferencedOnlyInCustomSerialization1>.AreEqual);
Assert.IsNotNull(NetworkVariableSerialization<TypeReferencedOnlyInCustomSerialization2>.AreEqual);
Assert.IsNotNull(NetworkVariableSerialization<TypeReferencedOnlyInCustomSerialization3>.AreEqual);
Assert.IsNotNull(NetworkVariableSerialization<TypeReferencedOnlyInCustomSerialization4>.AreEqual);
Assert.IsNotNull(NetworkVariableSerialization<TypeReferencedOnlyInCustomSerialization5>.AreEqual);
Assert.IsNotNull(NetworkVariableSerialization<TypeReferencedOnlyInCustomSerialization6>.AreEqual);
// Verify no issues with generic values...
Assert.AreEqual(typeof(UnmanagedArraySerializer<TypeReferencedOnlyInCustomSerialization1>), NetworkVariableSerialization<NativeArray<TypeReferencedOnlyInCustomSerialization1>>.Serializer.GetType());
Assert.AreEqual(typeof(UnmanagedArraySerializer<TypeReferencedOnlyInCustomSerialization2>), NetworkVariableSerialization<NativeArray<TypeReferencedOnlyInCustomSerialization2>>.Serializer.GetType());
Assert.AreEqual(typeof(UnmanagedArraySerializer<TypeReferencedOnlyInCustomSerialization3>), NetworkVariableSerialization<NativeArray<TypeReferencedOnlyInCustomSerialization3>>.Serializer.GetType());
Assert.AreEqual(typeof(UnmanagedArraySerializer<TypeReferencedOnlyInCustomSerialization4>), NetworkVariableSerialization<NativeArray<TypeReferencedOnlyInCustomSerialization4>>.Serializer.GetType());
Assert.AreEqual(typeof(UnmanagedArraySerializer<TypeReferencedOnlyInCustomSerialization5>), NetworkVariableSerialization<NativeArray<TypeReferencedOnlyInCustomSerialization5>>.Serializer.GetType());
Assert.AreEqual(typeof(UnmanagedArraySerializer<TypeReferencedOnlyInCustomSerialization6>), NetworkVariableSerialization<NativeArray<TypeReferencedOnlyInCustomSerialization6>>.Serializer.GetType());
Assert.IsNotNull(NetworkVariableSerialization<NativeArray<TypeReferencedOnlyInCustomSerialization1>>.AreEqual);
Assert.IsNotNull(NetworkVariableSerialization<NativeArray<TypeReferencedOnlyInCustomSerialization2>>.AreEqual);
Assert.IsNotNull(NetworkVariableSerialization<NativeArray<TypeReferencedOnlyInCustomSerialization3>>.AreEqual);
Assert.IsNotNull(NetworkVariableSerialization<NativeArray<TypeReferencedOnlyInCustomSerialization4>>.AreEqual);
Assert.IsNotNull(NetworkVariableSerialization<NativeArray<TypeReferencedOnlyInCustomSerialization5>>.AreEqual);
Assert.IsNotNull(NetworkVariableSerialization<NativeArray<TypeReferencedOnlyInCustomSerialization6>>.AreEqual);
}
[Test]
public void TestUnsupportedManagedTypesThrowExceptions()
{
var variable = new NetworkVariable<string>();
using var writer = new FastBufferWriter(1024, Allocator.Temp);
using var reader = new FastBufferReader(writer, Allocator.None);
// Just making sure these are null, just in case.
UserNetworkVariableSerialization<string>.ReadValue = null;
UserNetworkVariableSerialization<string>.WriteValue = null;
UserNetworkVariableSerialization<string>.DuplicateValue = null;
Assert.Throws<ArgumentException>(() =>
{
variable.WriteField(writer);
});
Assert.Throws<ArgumentException>(() =>
{
variable.ReadField(reader);
});
}
[Test]
public void TestUnsupportedManagedTypesWithUserSerializationDoNotThrowExceptions()
{
var variable = new NetworkVariable<string>();
UserNetworkVariableSerialization<string>.ReadValue = (FastBufferReader reader, out string value) =>
{
reader.ReadValueSafe(out value);
};
UserNetworkVariableSerialization<string>.WriteValue = (FastBufferWriter writer, in string value) =>
{
writer.WriteValueSafe(value);
};
UserNetworkVariableSerialization<string>.DuplicateValue = (in string a, ref string b) =>
{
b = string.Copy(a);
};
try
{
using var writer = new FastBufferWriter(1024, Allocator.Temp);
variable.Value = "012345";
variable.WriteField(writer);
variable.Value = "";
using var reader = new FastBufferReader(writer, Allocator.None);
variable.ReadField(reader);
Assert.AreEqual("012345", variable.Value);
}
finally
{
UserNetworkVariableSerialization<string>.ReadValue = null;
UserNetworkVariableSerialization<string>.WriteValue = null;
UserNetworkVariableSerialization<string>.DuplicateValue = null;
}
}
[Test]
public void TestUnsupportedUnmanagedTypesThrowExceptions()
{
var variable = new NetworkVariable<Guid>();
using var writer = new FastBufferWriter(1024, Allocator.Temp);
using var reader = new FastBufferReader(writer, Allocator.None);
// Just making sure these are null, just in case.
UserNetworkVariableSerialization<Guid>.ReadValue = null;
UserNetworkVariableSerialization<Guid>.WriteValue = null;
UserNetworkVariableSerialization<Guid>.DuplicateValue = null;
Assert.Throws<ArgumentException>(() =>
{
variable.WriteField(writer);
});
Assert.Throws<ArgumentException>(() =>
{
variable.ReadField(reader);
});
}
[Test]
public void TestTypesReferencedInSubclassSerializeSuccessfully()
{
var variable = new NetworkVariableSubclass<TemplatedValueOnlyReferencedByNetworkVariableSubclass<int>>();
using var writer = new FastBufferWriter(1024, Allocator.Temp);
var value = new TemplatedValueOnlyReferencedByNetworkVariableSubclass<int> { Value = 12345 };
variable.Value = value;
variable.WriteField(writer);
variable.Value = new TemplatedValueOnlyReferencedByNetworkVariableSubclass<int> { Value = 54321 };
using var reader = new FastBufferReader(writer, Allocator.None);
variable.ReadField(reader);
Assert.AreEqual(value.Value, variable.Value.Value);
}
[Test]
public void TestUnsupportedUnmanagedTypesWithUserSerializationDoNotThrowExceptions()
{
var variable = new NetworkVariable<Guid>();
UserNetworkVariableSerialization<Guid>.ReadValue = (FastBufferReader reader, out Guid value) =>
{
var tmpValue = new ForceNetworkSerializeByMemcpy<Guid>();
reader.ReadValueSafe(out tmpValue);
value = tmpValue.Value;
};
UserNetworkVariableSerialization<Guid>.WriteValue = (FastBufferWriter writer, in Guid value) =>
{
var tmpValue = new ForceNetworkSerializeByMemcpy<Guid>(value);
writer.WriteValueSafe(tmpValue);
};
UserNetworkVariableSerialization<Guid>.DuplicateValue = (in Guid a, ref Guid b) =>
{
b = a;
};
try
{
using var writer = new FastBufferWriter(1024, Allocator.Temp);
var guid = Guid.NewGuid();
variable.Value = guid;
variable.WriteField(writer);
variable.Value = Guid.Empty;
using var reader = new FastBufferReader(writer, Allocator.None);
variable.ReadField(reader);
Assert.AreEqual(guid, variable.Value);
}
finally
{
UserNetworkVariableSerialization<Guid>.ReadValue = null;
UserNetworkVariableSerialization<Guid>.WriteValue = null;
UserNetworkVariableSerialization<Guid>.DuplicateValue = null;
}
}
[Test]
public void WhenCreatingAnArrayOfNetVars_InitializingVariablesDoesNotThrowAnException()
{
var testObjPrefab = CreateNetworkObjectPrefab($"NetVarArrayPrefab");
var testComp = testObjPrefab.AddComponent<NetworkBehaviourWithNetVarArray>();
testComp.InitializeVariables();
// Verify all variables were initialized
Assert.AreEqual(testComp.InitializedFieldCount, 5);
Assert.NotNull(testComp.Int0.GetBehaviour());
Assert.NotNull(testComp.Int1.GetBehaviour());
Assert.NotNull(testComp.Int2.GetBehaviour());
Assert.NotNull(testComp.Int3.GetBehaviour());
Assert.NotNull(testComp.Int4.GetBehaviour());
Assert.NotNull(testComp.Int0.Name);
Assert.NotNull(testComp.Int1.Name);
Assert.NotNull(testComp.Int2.Name);
Assert.NotNull(testComp.Int3.Name);
Assert.NotNull(testComp.Int4.Name);
Assert.AreNotEqual("", testComp.Int0.Name);
Assert.AreNotEqual("", testComp.Int1.Name);
Assert.AreNotEqual("", testComp.Int2.Name);
Assert.AreNotEqual("", testComp.Int3.Name);
Assert.AreNotEqual("", testComp.Int4.Name);
Assert.AreSame(testComp.AllInts[0], testComp.Int0);
Assert.AreSame(testComp.AllInts[1], testComp.Int1);
Assert.AreSame(testComp.AllInts[2], testComp.Int2);
Assert.AreSame(testComp.AllInts[3], testComp.Int3);
Assert.AreSame(testComp.AllInts[4], testComp.Int4);
}
[Test]
public void TestNetworkVariableChangeAndReturnInSameFrame([Values] HostOrServer useHost)
{
InitializeServerAndClients(useHost);
var serverOnValueChangedCount = 0;
var clientOnValueChangedCount = 0;
void ServerOnValueChanged(NetworkVariableTest.SomeEnum previous, NetworkVariableTest.SomeEnum next)
{
serverOnValueChangedCount++;
}
void ClientOnValueChanged(NetworkVariableTest.SomeEnum previous, NetworkVariableTest.SomeEnum next)
{
clientOnValueChangedCount++;
}
bool VerifyStructure()
{
return m_Player1OnClient1.TheEnum.Value == m_Player1OnServer.TheEnum.Value;
}
// Wait for the client-side to notify it is finished initializing and spawning.
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(VerifyStructure));
m_Player1OnServer.TheEnum.OnValueChanged += ServerOnValueChanged;
m_Player1OnClient1.TheEnum.OnValueChanged += ClientOnValueChanged;
// Change the value once in a frame
m_Player1OnServer.TheEnum.Value = NetworkVariableTest.SomeEnum.B;
// Wait for the value to sync and assert that both server and client had OnValueChanged called an equal number of times
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(VerifyStructure), "Timed out waiting for client and server values to match");
Assert.AreEqual(serverOnValueChangedCount, clientOnValueChangedCount, $"Expected OnValueChanged call count to be equal. Server OnValueChanged was called {serverOnValueChangedCount} times but client was called {clientOnValueChangedCount} times!");
// Change the value twice in a frame
m_Player1OnServer.TheEnum.Value = NetworkVariableTest.SomeEnum.A;
m_Player1OnServer.TheEnum.Value = NetworkVariableTest.SomeEnum.B;
// Wait for the value to sync and assert that the server had OnValueChanged called once more than the client
TimeTravelAdvanceTick();
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(VerifyStructure), "Timed out waiting for client and server values to match");
Assert.AreEqual(serverOnValueChangedCount - 1, clientOnValueChangedCount, $"Unexpected OnValueChanged call count. Server OnValueChanged was called {serverOnValueChangedCount} times but client was called {clientOnValueChangedCount} times!");
m_Player1OnServer.TheEnum.OnValueChanged -= ServerOnValueChanged;
m_Player1OnClient1.TheEnum.OnValueChanged -= ClientOnValueChanged;
}
private void TestValueType<T>(T testValue, T changedValue) where T : unmanaged
{
var serverVariable = new NetworkVariable<T>(testValue);
var clientVariable = new NetworkVariable<T>();
using var writer = new FastBufferWriter(1024, Allocator.Temp);
serverVariable.WriteField(writer);
Assert.IsFalse(NetworkVariableSerialization<T>.AreEqual(ref serverVariable.RefValue(), ref clientVariable.RefValue()));
using var reader = new FastBufferReader(writer, Allocator.None);
clientVariable.ReadField(reader);
Assert.IsTrue(NetworkVariableSerialization<T>.AreEqual(ref serverVariable.RefValue(), ref clientVariable.RefValue()));
serverVariable.Value = changedValue;
Assert.IsFalse(NetworkVariableSerialization<T>.AreEqual(ref serverVariable.RefValue(), ref clientVariable.RefValue()));
writer.Seek(0);
serverVariable.WriteDelta(writer);
Assert.IsFalse(NetworkVariableSerialization<T>.AreEqual(ref serverVariable.RefValue(), ref clientVariable.RefValue()));
using var reader2 = new FastBufferReader(writer, Allocator.None);
clientVariable.ReadDelta(reader2, false);
Assert.IsTrue(NetworkVariableSerialization<T>.AreEqual(ref serverVariable.RefValue(), ref clientVariable.RefValue()));
}
public void AssertArraysMatch<T>(ref NativeArray<T> a, ref NativeArray<T> b) where T : unmanaged
{
Assert.IsTrue(NetworkVariableSerialization<NativeArray<T>>.AreEqual(ref a, ref b),
$"Lists do not match: {ArrayStr(a)} != {ArrayStr(b)}");
}
public void AssertArraysDoNotMatch<T>(ref NativeArray<T> a, ref NativeArray<T> b) where T : unmanaged
{
Assert.IsFalse(NetworkVariableSerialization<NativeArray<T>>.AreEqual(ref a, ref b),
$"Lists match when they should not: {ArrayStr(a)} == {ArrayStr(b)}");
}
private void TestValueTypeNativeArray<T>(NativeArray<T> testValue, NativeArray<T> changedValue) where T : unmanaged
{
VerboseDebug($"Changing {ArrayStr(testValue)} to {ArrayStr(changedValue)}");
var serverVariable = new NetworkVariable<NativeArray<T>>(testValue);
var clientVariable = new NetworkVariable<NativeArray<T>>(new NativeArray<T>(1, Allocator.Persistent));
using var writer = new FastBufferWriter(1024, Allocator.Temp, int.MaxValue);
serverVariable.WriteField(writer);
AssertArraysDoNotMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue());
using var reader = new FastBufferReader(writer, Allocator.None);
clientVariable.ReadField(reader);
AssertArraysMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue());
serverVariable.ResetDirty();
serverVariable.Value.Dispose();
serverVariable.Value = changedValue;
AssertArraysDoNotMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue());
writer.Seek(0);
serverVariable.WriteDelta(writer);
AssertArraysDoNotMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue());
using var reader2 = new FastBufferReader(writer, Allocator.None);
clientVariable.ReadDelta(reader2, false);
AssertArraysMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue());
serverVariable.ResetDirty();
Assert.IsFalse(serverVariable.IsDirty());
var cachedValue = changedValue[0];
var differentValue = changedValue[0];
foreach (var checkValue in testValue)
{
var checkValueRef = checkValue;
if (!NetworkVariableSerialization<T>.AreEqual(ref checkValueRef, ref differentValue))
{
differentValue = checkValue;
break;
}
}
changedValue[0] = differentValue;
Assert.IsTrue(serverVariable.IsDirty());
serverVariable.ResetDirty();
Assert.IsFalse(serverVariable.IsDirty());
changedValue[0] = cachedValue;
Assert.IsTrue(serverVariable.IsDirty());
serverVariable.Dispose();
clientVariable.Dispose();
}
public void AssertListsMatch<T>(ref List<T> a, ref List<T> b)
{
Assert.IsTrue(NetworkVariableSerialization<List<T>>.AreEqual(ref a, ref b),
$"Lists do not match: {ListStr(a)} != {ListStr(b)}");
}
public void AssertListsDoNotMatch<T>(ref List<T> a, ref List<T> b)
{
Assert.IsFalse(NetworkVariableSerialization<List<T>>.AreEqual(ref a, ref b),
$"Lists match when they should not: {ListStr(a)} == {ListStr(b)}");
}
private void TestList<T>(List<T> testValue, List<T> changedValue)
{
VerboseDebug($"Changing {ListStr(testValue)} to {ListStr(changedValue)}");
var serverVariable = new NetworkVariable<List<T>>(testValue);
var inPlaceList = new List<T>();
var clientVariable = new NetworkVariable<List<T>>(inPlaceList);
using var writer = new FastBufferWriter(1024, Allocator.Temp, int.MaxValue);
serverVariable.WriteField(writer);
AssertListsDoNotMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue());
// Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure!
AssertListsMatch(ref clientVariable.RefValue(), ref inPlaceList);
using var reader = new FastBufferReader(writer, Allocator.None);
clientVariable.ReadField(reader);
AssertListsMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue());
// Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure!
AssertListsMatch(ref clientVariable.RefValue(), ref inPlaceList);
serverVariable.ResetDirty();
serverVariable.Value = changedValue;
AssertListsDoNotMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue());
// Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure!
AssertListsMatch(ref clientVariable.RefValue(), ref inPlaceList);
writer.Seek(0);
serverVariable.WriteDelta(writer);