-
Notifications
You must be signed in to change notification settings - Fork 459
Expand file tree
/
Copy pathNetworkAnimator.cs
More file actions
1845 lines (1668 loc) · 81.3 KB
/
NetworkAnimator.cs
File metadata and controls
1845 lines (1668 loc) · 81.3 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 COM_UNITY_MODULES_ANIMATION
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Netcode.Runtime;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor.Animations;
#endif
namespace Unity.Netcode.Components
{
internal class NetworkAnimatorStateChangeHandler : INetworkUpdateSystem
{
private NetworkAnimator m_NetworkAnimator;
private bool m_IsServer;
/// <summary>
/// This removes sending RPCs from within RPCs when the
/// server is forwarding updates from clients to clients
/// As well this handles newly connected client synchronization
/// of the existing Animator's state.
/// </summary>
private void FlushMessages()
{
foreach (var animationUpdate in m_SendAnimationUpdates)
{
if (m_NetworkAnimator.DistributedAuthorityMode)
{
m_NetworkAnimator.SendAnimStateRpc(animationUpdate.AnimationMessage);
}
else
{
m_NetworkAnimator.SendClientAnimStateRpc(animationUpdate.AnimationMessage, animationUpdate.RpcParams);
}
}
m_SendAnimationUpdates.Clear();
foreach (var sendEntry in m_SendParameterUpdates)
{
if (m_NetworkAnimator.DistributedAuthorityMode)
{
m_NetworkAnimator.SendParametersUpdateRpc(sendEntry.ParametersUpdateMessage);
}
else
{
m_NetworkAnimator.SendClientParametersUpdateRpc(sendEntry.ParametersUpdateMessage, sendEntry.RpcParams);
}
}
m_SendParameterUpdates.Clear();
foreach (var sendEntry in m_SendTriggerUpdates)
{
if (m_NetworkAnimator.DistributedAuthorityMode)
{
m_NetworkAnimator.SendAnimTriggerRpc(sendEntry.AnimationTriggerMessage);
}
else
{
if (!sendEntry.SendToServer)
{
m_NetworkAnimator.SendClientAnimTriggerRpc(sendEntry.AnimationTriggerMessage, sendEntry.RpcParams);
}
else
{
m_NetworkAnimator.SendServerAnimTriggerRpc(sendEntry.AnimationTriggerMessage);
}
}
}
m_SendTriggerUpdates.Clear();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool HasAuthority()
{
var isServerAuthority = m_NetworkAnimator.IsServerAuthoritative();
return (!isServerAuthority && m_NetworkAnimator.IsOwner) || (isServerAuthority && (m_NetworkAnimator.IsServer));
}
/// <inheritdoc />
public void NetworkUpdate(NetworkUpdateStage updateStage)
{
switch (updateStage)
{
case NetworkUpdateStage.PreUpdate:
{
// NOTE: This script has an order of operations requirement where
// the authority and/or server will flush messages first, parameter updates are applied
// for all instances, and then only the authority will check for animator changes. Changing
// the order could cause timing related issues.
var hasAuthority = HasAuthority();
// Only the authority or the server will send messages
// The only exception is server authoritative and owners that are sending animation triggers.
if (hasAuthority || m_IsServer || (m_NetworkAnimator.IsServerAuthoritative() && m_NetworkAnimator.IsOwner))
{
// Flush any pending messages
FlushMessages();
}
// Everyone applies any parameters updated
if (m_ProcessParameterUpdates.Count > 0)
{
for (int i = 0; i < m_ProcessParameterUpdates.Count; i++)
{
var parameterUpdate = m_ProcessParameterUpdates[i];
m_NetworkAnimator.UpdateParameters(ref parameterUpdate);
}
m_ProcessParameterUpdates.Clear();
}
// Only the authority checks for Animator changes
if (hasAuthority)
{
m_NetworkAnimator.CheckForAnimatorChanges();
}
break;
}
}
}
/// <summary>
/// A pending outgoing Animation update for (n) clients
/// </summary>
private struct AnimationUpdate
{
public RpcParams RpcParams;
public NetworkAnimator.AnimationMessage AnimationMessage;
}
private List<AnimationUpdate> m_SendAnimationUpdates = new List<AnimationUpdate>();
/// <summary>
/// Invoked when a server needs to forwarding an update to the animation state
/// </summary>
internal void SendAnimationUpdate(NetworkAnimator.AnimationMessage animationMessage, RpcParams rpcParams = default)
{
m_SendAnimationUpdates.Add(new AnimationUpdate() { RpcParams = rpcParams, AnimationMessage = animationMessage });
}
private struct ParameterUpdate
{
public RpcParams RpcParams;
public NetworkAnimator.ParametersUpdateMessage ParametersUpdateMessage;
}
private List<ParameterUpdate> m_SendParameterUpdates = new List<ParameterUpdate>();
/// <summary>
/// Invoked when a server needs to forwarding an update to the parameter state
/// </summary>
internal void SendParameterUpdate(NetworkAnimator.ParametersUpdateMessage parametersUpdateMessage, RpcParams rpcParams = default)
{
m_SendParameterUpdates.Add(new ParameterUpdate() { RpcParams = rpcParams, ParametersUpdateMessage = parametersUpdateMessage });
}
private List<NetworkAnimator.ParametersUpdateMessage> m_ProcessParameterUpdates = new List<NetworkAnimator.ParametersUpdateMessage>();
internal void ProcessParameterUpdate(NetworkAnimator.ParametersUpdateMessage parametersUpdateMessage)
{
m_ProcessParameterUpdates.Add(parametersUpdateMessage);
}
private struct TriggerUpdate
{
public bool SendToServer;
public RpcParams RpcParams;
public NetworkAnimator.AnimationTriggerMessage AnimationTriggerMessage;
}
private List<TriggerUpdate> m_SendTriggerUpdates = new List<TriggerUpdate>();
/// <summary>
/// Invoked when a server needs to forward an update to a Trigger state
/// </summary>
internal void QueueTriggerUpdateToClient(NetworkAnimator.AnimationTriggerMessage animationTriggerMessage, RpcParams clientRpcParams = default)
{
m_SendTriggerUpdates.Add(new TriggerUpdate() { RpcParams = clientRpcParams, AnimationTriggerMessage = animationTriggerMessage });
}
internal void QueueTriggerUpdateToServer(NetworkAnimator.AnimationTriggerMessage animationTriggerMessage)
{
m_SendTriggerUpdates.Add(new TriggerUpdate() { AnimationTriggerMessage = animationTriggerMessage, SendToServer = true });
}
internal void DeregisterUpdate()
{
NetworkUpdateLoop.UnregisterNetworkUpdate(this, NetworkUpdateStage.PreUpdate);
}
internal NetworkAnimatorStateChangeHandler(NetworkAnimator networkAnimator)
{
m_NetworkAnimator = networkAnimator;
m_IsServer = networkAnimator.NetworkManager.IsServer;
NetworkUpdateLoop.RegisterNetworkUpdate(this, NetworkUpdateStage.PreUpdate);
}
}
/// <summary>
/// NetworkAnimator enables remote synchronization of <see cref="UnityEngine.Animator"/> state for on network objects.
/// </summary>
[AddComponentMenu("Netcode/Network Animator")]
[HelpURL(HelpUrls.NetworkAnimator)]
public class NetworkAnimator : NetworkBehaviour, ISerializationCallbackReceiver
{
#if UNITY_EDITOR
[HideInInspector]
[SerializeField]
internal bool NetworkAnimatorExpanded;
#endif
[Serializable]
internal class TransitionStateinfo
{
public bool IsCrossFadeExit;
public int Layer;
public int OriginatingState;
public int DestinationState;
public float TransitionDuration;
public int TriggerNameHash;
public int TransitionIndex;
}
/// <summary>
/// Determines if the server or client owner pushes animation state updates.
/// </summary>
public enum AuthorityModes
{
/// <summary>
/// Server pushes animator state updates.
/// </summary>
Server,
/// <summary>
/// Client owner pushes animator state updates.
/// </summary>
Owner,
}
/// <summary>
/// Determines whether this <see cref="NetworkAnimator"/> instance will have state updates pushed by the server or the client owner.
/// <see cref="AuthorityModes"/>
/// </summary>
#if MULTIPLAYER_SERVICES_SDK_INSTALLED
[Tooltip("Selects who has authority(sends state updates) over the<see cref=\"NetworkAnimator\"/> instance.When the network topology is set to distributed authority, this always defaults to owner authority.If server (the default), then only server-side adjustments to the " +
"<see cref=\"NetworkAnimator\"> instance will be synchronized with clients. If owner (or client), then only the owner-side adjustments to the <see cref=\"NetworkAnimator\"/> instance will be synchronized with both the server and other clients.")]
#else
[Tooltip("Selects who has authority (sends state updates) over the <see cref=\"NetworkAnimator\"/> instance. If server (the default), then only server-side adjustments to the <see cref=\"NetworkAnimator\"/> instance will be synchronized with clients. If owner (or client), " +
"then only the owner-side adjustments to the <see cref=\"NetworkAnimator\"/> instance will be synchronized with both the server and other clients.")]
#endif
public AuthorityModes AuthorityMode;
[Tooltip("The animator that this NetworkAnimator component will be synchronizing.")]
[SerializeField] private Animator m_Animator;
/// <summary>
/// The <see cref="Animator"/> associated with this <see cref="NetworkAnimator"/> instance.
/// </summary>
public Animator Animator
{
get { return m_Animator; }
set
{
m_Animator = value;
}
}
/// <summary>
/// Used to build the destination state to transition info table
/// </summary>
[HideInInspector]
[SerializeField]
internal List<TransitionStateinfo> TransitionStateInfoList;
// Used to get the associated transition information required to synchronize late joining clients with transitions
// [Layer][DestinationState][TransitionStateInfo]
private Dictionary<int, Dictionary<int, TransitionStateinfo>> m_DestinationStateToTransitioninfo = new Dictionary<int, Dictionary<int, TransitionStateinfo>>();
// Named differently to avoid serialization conflicts with NetworkBehaviour
private NetworkManager m_LocalNetworkManager;
internal bool DistributedAuthorityMode;
/// <summary>
/// Builds the m_DestinationStateToTransitioninfo lookup table
/// </summary>
private void BuildDestinationToTransitionInfoTable()
{
foreach (var entry in TransitionStateInfoList)
{
if (!m_DestinationStateToTransitioninfo.ContainsKey(entry.Layer))
{
m_DestinationStateToTransitioninfo.Add(entry.Layer, new Dictionary<int, TransitionStateinfo>());
}
var destinationStateTransitionInfo = m_DestinationStateToTransitioninfo[entry.Layer];
if (!destinationStateTransitionInfo.ContainsKey(entry.DestinationState))
{
destinationStateTransitionInfo.Add(entry.DestinationState, entry);
}
}
}
[Serializable]
internal class AnimatorParameterEntry
{
#pragma warning disable IDE1006
[HideInInspector]
public string name;
#pragma warning restore IDE1006
public int NameHash;
public bool Synchronize;
public AnimatorControllerParameterType ParameterType;
}
[Serializable]
internal class AnimatorParametersListContainer
{
public List<AnimatorParameterEntry> ParameterEntries = new List<AnimatorParameterEntry>();
}
[SerializeField]
internal AnimatorParametersListContainer AnimatorParameterEntries;
internal Dictionary<int, AnimatorParameterEntry> AnimatorParameterEntryTable = new Dictionary<int, AnimatorParameterEntry>();
#if UNITY_EDITOR
[HideInInspector]
[SerializeField]
internal bool AnimatorParametersExpanded;
internal Dictionary<int, AnimatorControllerParameter> ParameterToNameLookup = new Dictionary<int, AnimatorControllerParameter>();
private void ParseStateMachineStates(int layerIndex, ref AnimatorController animatorController, ref AnimatorStateMachine stateMachine)
{
for (int y = 0; y < stateMachine.states.Length; y++)
{
var animatorState = stateMachine.states[y].state;
for (int z = 0; z < animatorState.transitions.Length; z++)
{
var transition = animatorState.transitions[z];
if (transition.conditions.Length == 0 && transition.isExit)
{
// We don't need to worry about exit transitions with no conditions
continue;
}
foreach (var condition in transition.conditions)
{
var parameterName = condition.parameter;
var parameters = animatorController.parameters;
// Find the associated parameter for the condition
foreach (var parameter in parameters)
{
// Only process the associated parameter(s)
if (parameter.name != parameterName)
{
continue;
}
switch (parameter.type)
{
case AnimatorControllerParameterType.Trigger:
{
if (transition.destinationStateMachine != null)
{
var destinationStateMachine = transition.destinationStateMachine;
ParseStateMachineStates(layerIndex, ref animatorController, ref destinationStateMachine);
}
else if (transition.destinationState != null)
{
var transitionInfo = new TransitionStateinfo()
{
Layer = layerIndex,
OriginatingState = animatorState.nameHash,
DestinationState = transition.destinationState.nameHash,
TransitionDuration = transition.duration,
TriggerNameHash = parameter.nameHash,
TransitionIndex = z
};
TransitionStateInfoList.Add(transitionInfo);
}
else
{
Debug.LogError($"[{name}][Conditional Transition for {animatorState.name}] Conditional triggered transition has neither a DestinationState nor a DestinationStateMachine! This transition is not likely to synchronize properly. " +
$"Please file a GitHub issue about this error with details about your Animator's setup.");
}
break;
}
default:
break;
}
}
}
}
}
}
/// <summary>
/// Creates the TransitionStateInfoList table
/// </summary>
private void BuildTransitionStateInfoList()
{
if (m_Animator == null)
{
return;
}
TransitionStateInfoList = new List<TransitionStateinfo>();
var animControllerType = m_Animator.runtimeAnimatorController.GetType();
var animatorController = (AnimatorController)null;
if (animControllerType == typeof(AnimatorOverrideController))
{
animatorController = ((AnimatorOverrideController)m_Animator.runtimeAnimatorController).runtimeAnimatorController as AnimatorController;
}
else if (animControllerType == typeof(AnimatorController))
{
animatorController = m_Animator.runtimeAnimatorController as AnimatorController;
}
if (animatorController == null)
{
return;
}
for (int x = 0; x < animatorController.layers.Length; x++)
{
var stateMachine = animatorController.layers[x].stateMachine;
ParseStateMachineStates(x, ref animatorController, ref stateMachine);
}
}
internal void ProcessParameterEntries()
{
if (!Animator)
{
if (AnimatorParameterEntries != null && AnimatorParameterEntries.ParameterEntries.Count > 0)
{
AnimatorParameterEntries.ParameterEntries.Clear();
}
return;
}
var animControllerType = m_Animator.runtimeAnimatorController.GetType();
var animatorController = (AnimatorController)null;
if (animControllerType == typeof(AnimatorOverrideController))
{
animatorController = ((AnimatorOverrideController)m_Animator.runtimeAnimatorController).runtimeAnimatorController as AnimatorController;
}
else if (animControllerType == typeof(AnimatorController))
{
animatorController = m_Animator.runtimeAnimatorController as AnimatorController;
}
if (animatorController == null)
{
return;
}
var parameters = animatorController.parameters;
var parametersToRemove = new List<AnimatorParameterEntry>();
ParameterToNameLookup.Clear();
foreach (var parameter in parameters)
{
ParameterToNameLookup.Add(parameter.nameHash, parameter);
}
// Rebuild the parameter entry table for the inspector view
AnimatorParameterEntryTable.Clear();
foreach (var parameterEntry in AnimatorParameterEntries.ParameterEntries)
{
// Check for removed parameters.
if (!ParameterToNameLookup.ContainsKey(parameterEntry.NameHash))
{
parametersToRemove.Add(parameterEntry);
// Skip this removed entry
continue;
}
// Build the list of known parameters
if (!AnimatorParameterEntryTable.ContainsKey(parameterEntry.NameHash))
{
AnimatorParameterEntryTable.Add(parameterEntry.NameHash, parameterEntry);
}
var parameter = ParameterToNameLookup[parameterEntry.NameHash];
parameterEntry.name = parameter.name;
parameterEntry.ParameterType = parameter.type;
}
// Update for removed parameters
foreach (var parameterEntry in parametersToRemove)
{
AnimatorParameterEntries.ParameterEntries.Remove(parameterEntry);
}
// Update any newly added parameters
foreach (var parameterLookUp in ParameterToNameLookup)
{
if (!AnimatorParameterEntryTable.ContainsKey(parameterLookUp.Value.nameHash))
{
var animatorParameterEntry = new AnimatorParameterEntry()
{
name = parameterLookUp.Value.name,
NameHash = parameterLookUp.Value.nameHash,
ParameterType = parameterLookUp.Value.type,
Synchronize = true,
};
AnimatorParameterEntries.ParameterEntries.Add(animatorParameterEntry);
AnimatorParameterEntryTable.Add(parameterLookUp.Value.nameHash, animatorParameterEntry);
}
}
}
/// <summary>
/// In-Editor Only
/// Virtual OnValidate method for custom derived NetworkAnimator classes.
/// </summary>
protected virtual void OnValidate()
{
BuildTransitionStateInfoList();
ProcessParameterEntries();
}
#endif
public void OnAfterDeserialize()
{
BuildDestinationToTransitionInfoTable();
}
public void OnBeforeSerialize()
{
// Do nothing when serializing (handled during OnValidate)
}
internal struct AnimationState : INetworkSerializable
{
// Not to be serialized, used for processing the animation state
internal bool HasBeenProcessed;
internal int StateHash;
internal float NormalizedTime;
internal int Layer;
internal float Weight;
internal float Duration;
// For synchronizing transitions
internal bool Transition;
internal bool CrossFade;
// Flags for bool states
private const byte k_IsTransition = 0x01;
private const byte k_IsCrossFade = 0x02;
// Used to serialize the bool states
private byte m_StateFlags;
// The StateHash is where the transition starts
// and the DestinationStateHash is the destination state
internal int DestinationStateHash;
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
if (serializer.IsWriter)
{
var writer = serializer.GetFastBufferWriter();
m_StateFlags = 0x00;
if (Transition)
{
m_StateFlags |= k_IsTransition;
}
if (CrossFade)
{
m_StateFlags |= k_IsCrossFade;
}
serializer.SerializeValue(ref m_StateFlags);
BytePacker.WriteValuePacked(writer, StateHash);
BytePacker.WriteValuePacked(writer, Layer);
if (Transition)
{
BytePacker.WriteValuePacked(writer, DestinationStateHash);
}
}
else
{
var reader = serializer.GetFastBufferReader();
serializer.SerializeValue(ref m_StateFlags);
Transition = (m_StateFlags & k_IsTransition) == k_IsTransition;
CrossFade = (m_StateFlags & k_IsCrossFade) == k_IsCrossFade;
ByteUnpacker.ReadValuePacked(reader, out StateHash);
ByteUnpacker.ReadValuePacked(reader, out Layer);
if (Transition)
{
ByteUnpacker.ReadValuePacked(reader, out DestinationStateHash);
}
}
serializer.SerializeValue(ref NormalizedTime);
serializer.SerializeValue(ref Weight);
// Cross fading includes the duration of the cross fade.
if (CrossFade)
{
serializer.SerializeValue(ref Duration);
}
}
}
internal struct AnimationMessage : INetworkSerializable
{
// Not to be serialized, used for processing the animation message
internal bool HasBeenProcessed;
// This is preallocated/populated in OnNetworkSpawn for all instances in the event ownership or
// authority changes. When serializing, IsDirtyCount determines how many AnimationState entries
// should be serialized from the list. When deserializing the list is created and populated with
// only the number of AnimationStates received which is dictated by the deserialized IsDirtyCount.
internal List<AnimationState> AnimationStates;
// Used to determine how many AnimationState entries we are sending or receiving
internal int IsDirtyCount;
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
var animationState = new AnimationState();
if (serializer.IsReader)
{
AnimationStates = new List<AnimationState>();
serializer.SerializeValue(ref IsDirtyCount);
// Since we create a new AnimationMessage when deserializing
// we need to create new animation states for each incoming
// AnimationState being updated
for (int i = 0; i < IsDirtyCount; i++)
{
animationState = new AnimationState();
serializer.SerializeValue(ref animationState);
AnimationStates.Add(animationState);
}
}
else
{
// When writing, only send the counted dirty animation states
serializer.SerializeValue(ref IsDirtyCount);
for (int i = 0; i < IsDirtyCount; i++)
{
animationState = AnimationStates[i];
serializer.SerializeNetworkSerializable(ref animationState);
}
}
}
}
internal struct ParametersUpdateMessage : INetworkSerializable
{
internal byte[] Parameters;
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
serializer.SerializeValue(ref Parameters);
}
}
internal struct AnimationTriggerMessage : INetworkSerializable
{
internal int Hash;
internal bool IsTriggerSet;
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
serializer.SerializeValue(ref Hash);
serializer.SerializeValue(ref IsTriggerSet);
}
}
/// <summary>
/// Determines whether the <see cref="NetworkAnimator"/> is <see cref="AuthorityModes.Server"/> or <see cref="AuthorityModes.Owner"/> based on the <see cref="AuthorityMode"/> field.
/// Optionally, you can still derive from <see cref="NetworkAnimator"/> and override the <see cref="OnIsServerAuthoritative"/> method.
/// </summary>
/// <returns><see cref="true"/> or <see cref="false"/></returns>
public bool IsServerAuthoritative()
{
return OnIsServerAuthoritative();
}
/// <summary>
/// Override this method and return false to switch to owner authoritative mode.<br />
/// Alternately, you can update the <see cref="AuthorityMode"/> field within the inspector view to select the authority mode.
/// </summary>
/// <remarks>
/// When using a distributed authority network topology, this will default to
/// owner authoritative.
/// </remarks>
protected virtual bool OnIsServerAuthoritative()
{
if (DistributedAuthorityMode)
{
return false;
}
return AuthorityMode == AuthorityModes.Server;
}
private int[] m_TransitionHash;
private int[] m_AnimationHash;
private float[] m_LayerWeights;
private static byte[] s_EmptyArray = new byte[] { };
private List<int> m_ParametersToUpdate;
private RpcParams m_RpcParams;
private RpcTargetGroup m_TargetGroup;
private AnimationMessage m_AnimationMessage;
private NetworkAnimatorStateChangeHandler m_NetworkAnimatorStateChangeHandler;
/// <summary>
/// Used for integration test purposes
/// </summary>
internal List<AnimatorStateInfo> SynchronizationStateInfo;
private unsafe struct AnimatorParamCache
{
internal bool Exclude;
internal int Hash;
internal int Type;
internal fixed byte Value[4]; // this is a max size of 4 bytes
}
// 128 bytes per Animator
private FastBufferWriter m_ParameterWriter;
private NativeArray<AnimatorParamCache> m_CachedAnimatorParameters;
// We cache these values because UnsafeUtility.EnumToInt uses direct IL that allows a non-boxing conversion
private struct AnimationParamEnumWrapper
{
internal static readonly int AnimatorControllerParameterInt;
internal static readonly int AnimatorControllerParameterFloat;
internal static readonly int AnimatorControllerParameterBool;
internal static readonly int AnimatorControllerParameterTriggerBool;
static AnimationParamEnumWrapper()
{
AnimatorControllerParameterInt = UnsafeUtility.EnumToInt(AnimatorControllerParameterType.Int);
AnimatorControllerParameterFloat = UnsafeUtility.EnumToInt(AnimatorControllerParameterType.Float);
AnimatorControllerParameterBool = UnsafeUtility.EnumToInt(AnimatorControllerParameterType.Bool);
AnimatorControllerParameterTriggerBool = UnsafeUtility.EnumToInt(AnimatorControllerParameterType.Trigger);
}
}
/// <summary>
/// Only things instantiated/created within OnNetworkSpawn should be
/// cleaned up here.
/// </summary>
private void SpawnCleanup()
{
m_NetworkAnimatorStateChangeHandler?.DeregisterUpdate();
m_NetworkAnimatorStateChangeHandler = null;
}
public override void OnDestroy()
{
SpawnCleanup();
m_TargetGroup?.Dispose();
if (m_CachedAnimatorParameters != null && m_CachedAnimatorParameters.IsCreated)
{
m_CachedAnimatorParameters.Dispose();
}
if (m_ParameterWriter.IsInitialized)
{
m_ParameterWriter.Dispose();
}
base.OnDestroy();
}
protected virtual void Awake()
{
if (!m_Animator)
{
#if !UNITY_EDITOR
Debug.LogError($"{nameof(NetworkAnimator)} {name} does not have an {nameof(UnityEngine.Animator)} assigned to it. The {nameof(NetworkAnimator)} will not initialize properly.");
#endif
return;
}
foreach (var parameterEntry in AnimatorParameterEntries.ParameterEntries)
{
AnimatorParameterEntryTable.TryAdd(parameterEntry.NameHash, parameterEntry);
}
int layers = m_Animator.layerCount;
// Initializing the below arrays for everyone handles an issue
// when running in owner authoritative mode and the owner changes.
m_TransitionHash = new int[layers];
m_AnimationHash = new int[layers];
m_LayerWeights = new float[layers];
// We initialize the m_AnimationMessage for all instances in the event that
// ownership or authority changes during runtime.
m_AnimationMessage = new AnimationMessage
{
AnimationStates = new List<AnimationState>()
};
// Store off our current layer weights and create our animation
// state entries per layer.
for (int layer = 0; layer < m_Animator.layerCount; layer++)
{
// We create an AnimationState per layer to preallocate the maximum
// number of possible AnimationState changes we could send in one
// AnimationMessage.
m_AnimationMessage.AnimationStates.Add(new AnimationState());
float layerWeightNow = m_Animator.GetLayerWeight(layer);
if (layerWeightNow != m_LayerWeights[layer])
{
m_LayerWeights[layer] = layerWeightNow;
}
}
// The total initialization size calculated for the m_ParameterWriter write buffer.
var totalParameterSize = sizeof(uint);
// Build our reference parameter values to detect when they change
var parameters = m_Animator.parameters;
m_CachedAnimatorParameters = new NativeArray<AnimatorParamCache>(parameters.Length, Allocator.Persistent);
m_ParametersToUpdate = new List<int>(parameters.Length);
// Include all parameters including any controlled by an AnimationCurve as this could change during runtime.
// We ignore changes to any parameter controlled by an AnimationCurve when we are checking for changes in
// the Animator's parameters.
for (var i = 0; i < parameters.Length; i++)
{
var parameter = parameters[i];
var synchronizeParameter = true;
if (AnimatorParameterEntryTable.ContainsKey(parameter.nameHash))
{
synchronizeParameter = AnimatorParameterEntryTable[parameter.nameHash].Synchronize;
}
var cacheParam = new AnimatorParamCache
{
Type = UnsafeUtility.EnumToInt(parameter.type),
Hash = parameter.nameHash,
Exclude = !synchronizeParameter
};
unsafe
{
switch (parameter.type)
{
case AnimatorControllerParameterType.Float:
var value = m_Animator.GetFloat(cacheParam.Hash);
UnsafeUtility.WriteArrayElement(cacheParam.Value, 0, value);
break;
case AnimatorControllerParameterType.Int:
var valueInt = m_Animator.GetInteger(cacheParam.Hash);
UnsafeUtility.WriteArrayElement(cacheParam.Value, 0, valueInt);
break;
case AnimatorControllerParameterType.Bool:
var valueBool = m_Animator.GetBool(cacheParam.Hash);
UnsafeUtility.WriteArrayElement(cacheParam.Value, 0, valueBool);
break;
default:
break;
}
}
m_CachedAnimatorParameters[i] = cacheParam;
// Calculate parameter sizes (index + type size)
switch (parameter.type)
{
case AnimatorControllerParameterType.Int:
{
totalParameterSize += sizeof(int) * 2;
break;
}
case AnimatorControllerParameterType.Bool:
case AnimatorControllerParameterType.Trigger:
{
// Bool is serialized to 1 byte
totalParameterSize += sizeof(int) + 1;
break;
}
case AnimatorControllerParameterType.Float:
{
totalParameterSize += sizeof(int) + sizeof(float);
break;
}
}
}
if (m_ParameterWriter.IsInitialized)
{
m_ParameterWriter.Dispose();
}
// Create our parameter write buffer for serialization
m_ParameterWriter = new FastBufferWriter(totalParameterSize, Allocator.Persistent);
}
/// <summary>
/// Used for integration test to validate that the
/// AnimationMessage.AnimationStates remains the same
/// size as the layer count.
/// </summary>
internal AnimationMessage GetAnimationMessage()
{
return m_AnimationMessage;
}
internal override void InternalOnNetworkPreSpawn(ref NetworkManager networkManager)
{
// Save internal state references
m_LocalNetworkManager = networkManager;
DistributedAuthorityMode = m_LocalNetworkManager.DistributedAuthorityMode;
}
/// <inheritdoc/>
public override void OnNetworkSpawn()
{
// If there is no assigned Animator then generate a server network warning (logged locally and if applicable on the server-host side as well).
if (m_Animator == null)
{
NetworkLog.LogWarningServer($"[{gameObject.name}][{nameof(NetworkAnimator)}] {nameof(Animator)} is not assigned! Animation synchronization will not work for this instance!");
}
m_TargetGroup = RpcTarget.Group(new List<ulong>(128), RpcTargetUse.Persistent) as RpcTargetGroup;
m_RpcParams = new RpcParams()
{
Send = new RpcSendParams()
{
Target = m_TargetGroup
}
};
// Create a handler for state changes
m_NetworkAnimatorStateChangeHandler = new NetworkAnimatorStateChangeHandler(this);
}
/// <inheritdoc/>
public override void OnNetworkDespawn()
{
SpawnCleanup();
}
/// <summary>
/// Writes all parameter and state information needed to initially synchronize a client
/// </summary>
private void WriteSynchronizationData<T>(ref BufferSerializer<T> serializer) where T : IReaderWriter
{
// Parameter synchronization
{
// We include all parameters for the initial synchronization
m_ParametersToUpdate.Clear();
for (int i = 0; i < m_CachedAnimatorParameters.Length; i++)
{
if (m_CachedAnimatorParameters[i].Exclude)
{
continue;
}
m_ParametersToUpdate.Add(i);
}
// Write, apply, and serialize
WriteParameters(ref m_ParameterWriter);
var parametersMessage = new ParametersUpdateMessage
{
Parameters = m_ParameterWriter.ToArray()
};
serializer.SerializeValue(ref parametersMessage);
}
// Animation state synchronization
{
// Reset the dirty count before synchronizing the newly connected client with all layers
m_AnimationMessage.IsDirtyCount = 0;
for (int layer = 0; layer < m_Animator.layerCount; layer++)
{
var synchronizationStateInfo = m_Animator.GetCurrentAnimatorStateInfo(layer);
SynchronizationStateInfo?.Add(synchronizationStateInfo);
var stateHash = synchronizationStateInfo.fullPathHash;
var normalizedTime = synchronizationStateInfo.normalizedTime;
var isInTransition = m_Animator.IsInTransition(layer);
// Grab one of the available AnimationState entries so we can fill it with the current
// layer's animation state.
var animationState = m_AnimationMessage.AnimationStates[layer];
// Synchronizing transitions with trigger conditions for late joining clients is now
// handled by cross fading between the late joining client's current layer's AnimationState
// and the transition's destination AnimationState.
if (isInTransition)
{
var tt = m_Animator.GetAnimatorTransitionInfo(layer);
var nextState = m_Animator.GetNextAnimatorStateInfo(layer);