-
Notifications
You must be signed in to change notification settings - Fork 464
Expand file tree
/
Copy pathCustomSerializationDocsTests.cs
More file actions
213 lines (179 loc) · 8.83 KB
/
Copy pathCustomSerializationDocsTests.cs
File metadata and controls
213 lines (179 loc) · 8.83 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
using System.Collections;
using System.Text;
using Unity.Netcode;
using Unity.Netcode.TestHelpers.Runtime;
using UnityEngine;
using UnityEngine.TestTools;
namespace DocumentationCodeSamples
{
internal static class FastBufferExtensions
{
internal static void WriteValueSafe(this FastBufferWriter writer, in CustomSerializationDocsTests.Health health)
{
writer.WriteValueSafe(health.MaxHealth);
writer.WriteValueSafe(health.CurrentHealth);
}
internal static void ReadValueSafe(this FastBufferReader reader, out CustomSerializationDocsTests.Health health)
{
reader.ReadValueSafe(out uint max);
reader.ReadValueSafe(out int current);
health = new CustomSerializationDocsTests.Health { MaxHealth = max, CurrentHealth = current };
}
}
internal class CustomSerializationDocsTests : NetcodeIntegrationTest
{
#region HealthExample
public struct Health
{
public uint MaxHealth;
public int CurrentHealth;
// Register our custom serialization on load
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
public static void RegisterHealthSerialization()
{
// You can reuse the FastBufferWriter and FastBufferReader extension methods we wrote above
UserNetworkVariableSerialization<Health>.WriteValue = FastBufferExtensions.WriteValueSafe;
UserNetworkVariableSerialization<Health>.ReadValue = FastBufferExtensions.ReadValueSafe;
// Here is where you register your custom delta handling.
UserNetworkVariableSerialization<Health>.WriteDelta = WriteDelta;
UserNetworkVariableSerialization<Health>.ReadDelta = ReadDelta;
// You can also use lambda expressions to register functions
UserNetworkVariableSerialization<Health>.DuplicateValue = (in Health value, ref Health duplicatedValue) => { duplicatedValue = value; };
}
// We can use an enum to indicate which field has changed for the delta change.
// This lets us save bandwidth when only one value has changed.
// In the case of Health, we expect CurrentHealth to change much more often than MaxHealth
// Implementing WriteDelta saves us bandwidth on not sending the MaxHealth every time CurrentHealth changes.
private enum ChangeType : byte
{
MaxHealth,
CurrentHealth,
All,
}
public static void WriteDelta(FastBufferWriter writer, in Health value, in Health previousValue)
{
if (value.MaxHealth == previousValue.MaxHealth && value.CurrentHealth != previousValue.CurrentHealth)
{
// If only our CurrentHealth has changed, we can send the CurrentHealth enum with only the updated CurrentHealth value
writer.WriteValueSafe(ChangeType.CurrentHealth);
writer.WriteValueSafe(value.CurrentHealth);
}
else if (value.CurrentHealth == previousValue.CurrentHealth && value.MaxHealth != previousValue.MaxHealth)
{
// If only our MaxHealth has changed, we can send the MaxHealth enum with only the updated MaxHealth value
writer.WriteValueSafe(ChangeType.MaxHealth);
writer.WriteValueSafe(value.MaxHealth);
}
else
{
// If both values have changed, we need to serialize both values.
writer.WriteValueSafe(ChangeType.All);
writer.WriteValueSafe(value.MaxHealth);
writer.WriteValueSafe(value.CurrentHealth);
}
}
public static void ReadDelta(FastBufferReader reader, ref Health value)
{
// First we read what type of change we've received
reader.ReadValueSafe(out ChangeType changeType);
// Then we read the data in our delta message, based on what type of change we've received.
switch (changeType)
{
case ChangeType.CurrentHealth:
{
reader.ReadValueSafe(out value.CurrentHealth);
break;
}
case ChangeType.MaxHealth:
{
reader.ReadValueSafe(out value.MaxHealth);
break;
}
case ChangeType.All:
{
reader.ReadValueSafe(out value.MaxHealth);
reader.ReadValueSafe(out value.CurrentHealth);
break;
}
}
}
}
#endregion
internal class TestHealthBehaviour : NetworkBehaviour
{
internal readonly NetworkVariable<Health> HealthVar = new();
internal Health ReceivedFromRpc;
[Rpc(SendTo.Everyone)]
public void SendHealthRpc(Health health)
{
ReceivedFromRpc = health;
}
}
protected override int NumberOfClients => 1;
private GameObject m_PrefabToSpawn;
protected override void OnServerAndClientsCreated()
{
m_PrefabToSpawn = CreateNetworkObjectPrefab(nameof(TestHealthBehaviour));
m_PrefabToSpawn.AddComponent<TestHealthBehaviour>();
}
private Health m_ExpectedHealth;
private ulong m_NetworkObjectIdToTest;
private bool m_TestingRpc;
private bool ValidateAllAreEqual(StringBuilder errorLog)
{
foreach (var networkManager in m_NetworkManagers)
{
if (!networkManager.SpawnManager.SpawnedObjects.TryGetValue(m_NetworkObjectIdToTest, out NetworkObject localInstance))
{
errorLog.Append($"[Client-{networkManager.LocalClientId}] SpawnedObject not found!");
return false;
}
var healthInstance = localInstance.GetComponent<TestHealthBehaviour>();
if (healthInstance == null)
{
errorLog.Append($"[Client-{networkManager.LocalClientId}] Health instance is null!");
return false;
}
var received = m_TestingRpc ? healthInstance.ReceivedFromRpc : healthInstance.HealthVar.Value;
if (m_ExpectedHealth.MaxHealth != received.MaxHealth)
{
errorLog.Append($"[Client-{networkManager.LocalClientId}] MaxHealth values don't match! Expected {m_ExpectedHealth.MaxHealth}, Received {received.MaxHealth}");
return false;
}
if (m_ExpectedHealth.CurrentHealth != received.CurrentHealth)
{
errorLog.Append($"[Client-{networkManager.LocalClientId}] CurrentHealth values don't match! Expected {m_ExpectedHealth.CurrentHealth}, Received {received.CurrentHealth}");
return false;
}
}
return true;
}
[UnityTest]
public IEnumerator TestHealthCode()
{
var authority = GetAuthorityNetworkManager();
var authorityInstance = SpawnObject(m_PrefabToSpawn, authority).GetComponent<TestHealthBehaviour>();
m_NetworkObjectIdToTest = authorityInstance.NetworkObjectId;
yield return WaitForSpawnedOnAllOrTimeOut(authorityInstance.NetworkObjectId);
AssertOnTimeout("Failed to spawn network object");
var healthToTest = new Health { MaxHealth = 456, CurrentHealth = 23 };
m_ExpectedHealth = healthToTest;
m_TestingRpc = true;
authorityInstance.SendHealthRpc(healthToTest);
yield return WaitForConditionOrTimeOut(ValidateAllAreEqual);
AssertOnTimeout("RPC send failed");
m_TestingRpc = false;
healthToTest = new Health { MaxHealth = 123, CurrentHealth = 45 };
m_ExpectedHealth = healthToTest;
authorityInstance.HealthVar.Value = healthToTest;
yield return WaitForConditionOrTimeOut(ValidateAllAreEqual);
AssertOnTimeout("NetworkVariable assignment failed");
var current = authorityInstance.HealthVar.Value;
current.CurrentHealth -= 10;
authorityInstance.HealthVar.Value = current;
m_ExpectedHealth = current;
yield return WaitForConditionOrTimeOut(ValidateAllAreEqual);
AssertOnTimeout("NetworkVariable update failed");
}
}
}