-
Notifications
You must be signed in to change notification settings - Fork 461
Expand file tree
/
Copy pathNetworkTransform.cs
More file actions
1286 lines (1118 loc) · 53.3 KB
/
NetworkTransform.cs
File metadata and controls
1286 lines (1118 loc) · 53.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
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Unity.Netcode.Components
{
/// <summary>
/// A component for syncing transforms.
/// NetworkTransform will read the underlying transform and replicate it to clients.
/// The replicated value will be automatically be interpolated (if active) and applied to the underlying GameObject's transform.
/// </summary>
[DisallowMultipleComponent]
[AddComponentMenu("Netcode/" + nameof(NetworkTransform))]
[DefaultExecutionOrder(100000)] // this is needed to catch the update time after the transform was updated by user scripts
public class NetworkTransform : NetworkBehaviour
{
/// <summary>
/// The default position change threshold value.
/// Any changes above this threshold will be replicated.
/// </summary>
public const float PositionThresholdDefault = 0.001f;
/// <summary>
/// The default rotation angle change threshold value.
/// Any changes above this threshold will be replicated.
/// </summary>
public const float RotAngleThresholdDefault = 0.01f;
/// <summary>
/// The default scale change threshold value.
/// Any changes above this threshold will be replicated.
/// </summary>
public const float ScaleThresholdDefault = 0.01f;
/// <summary>
/// The handler delegate type that takes client requested changes and returns resulting changes handled by the server.
/// </summary>
/// <param name="pos">The position requested by the client.</param>
/// <param name="rot">The rotation requested by the client.</param>
/// <param name="scale">The scale requested by the client.</param>
/// <returns>The resulting position, rotation and scale changes after handling.</returns>
public delegate (Vector3 pos, Quaternion rotOut, Vector3 scale) OnClientRequestChangeDelegate(Vector3 pos, Quaternion rot, Vector3 scale);
/// <summary>
/// The handler that gets invoked when server receives a change from a client.
/// This handler would be useful for server to modify pos/rot/scale before applying client's request.
/// </summary>
public OnClientRequestChangeDelegate OnClientRequestChange;
internal struct NetworkTransformState : INetworkSerializable
{
private const int k_InLocalSpaceBit = 0;
private const int k_PositionXBit = 1;
private const int k_PositionYBit = 2;
private const int k_PositionZBit = 3;
private const int k_RotAngleXBit = 4;
private const int k_RotAngleYBit = 5;
private const int k_RotAngleZBit = 6;
private const int k_ScaleXBit = 7;
private const int k_ScaleYBit = 8;
private const int k_ScaleZBit = 9;
private const int k_TeleportingBit = 10;
// 11-15: <unused>
private ushort m_Bitset;
internal bool InLocalSpace
{
get => (m_Bitset & (1 << k_InLocalSpaceBit)) != 0;
set
{
if (value) { m_Bitset = (ushort)(m_Bitset | (1 << k_InLocalSpaceBit)); }
else { m_Bitset = (ushort)(m_Bitset & ~(1 << k_InLocalSpaceBit)); }
}
}
// Position
internal bool HasPositionX
{
get => (m_Bitset & (1 << k_PositionXBit)) != 0;
set
{
if (value) { m_Bitset = (ushort)(m_Bitset | (1 << k_PositionXBit)); }
else { m_Bitset = (ushort)(m_Bitset & ~(1 << k_PositionXBit)); }
}
}
internal bool HasPositionY
{
get => (m_Bitset & (1 << k_PositionYBit)) != 0;
set
{
if (value) { m_Bitset = (ushort)(m_Bitset | (1 << k_PositionYBit)); }
else { m_Bitset = (ushort)(m_Bitset & ~(1 << k_PositionYBit)); }
}
}
internal bool HasPositionZ
{
get => (m_Bitset & (1 << k_PositionZBit)) != 0;
set
{
if (value) { m_Bitset = (ushort)(m_Bitset | (1 << k_PositionZBit)); }
else { m_Bitset = (ushort)(m_Bitset & ~(1 << k_PositionZBit)); }
}
}
internal bool HasPositionChange
{
get
{
return HasPositionX | HasPositionY | HasPositionZ;
}
}
// RotAngles
internal bool HasRotAngleX
{
get => (m_Bitset & (1 << k_RotAngleXBit)) != 0;
set
{
if (value) { m_Bitset = (ushort)(m_Bitset | (1 << k_RotAngleXBit)); }
else { m_Bitset = (ushort)(m_Bitset & ~(1 << k_RotAngleXBit)); }
}
}
internal bool HasRotAngleY
{
get => (m_Bitset & (1 << k_RotAngleYBit)) != 0;
set
{
if (value) { m_Bitset = (ushort)(m_Bitset | (1 << k_RotAngleYBit)); }
else { m_Bitset = (ushort)(m_Bitset & ~(1 << k_RotAngleYBit)); }
}
}
internal bool HasRotAngleZ
{
get => (m_Bitset & (1 << k_RotAngleZBit)) != 0;
set
{
if (value) { m_Bitset = (ushort)(m_Bitset | (1 << k_RotAngleZBit)); }
else { m_Bitset = (ushort)(m_Bitset & ~(1 << k_RotAngleZBit)); }
}
}
internal bool HasRotAngleChange
{
get
{
return HasRotAngleX | HasRotAngleY | HasRotAngleZ;
}
}
// Scale
internal bool HasScaleX
{
get => (m_Bitset & (1 << k_ScaleXBit)) != 0;
set
{
if (value) { m_Bitset = (ushort)(m_Bitset | (1 << k_ScaleXBit)); }
else { m_Bitset = (ushort)(m_Bitset & ~(1 << k_ScaleXBit)); }
}
}
internal bool HasScaleY
{
get => (m_Bitset & (1 << k_ScaleYBit)) != 0;
set
{
if (value) { m_Bitset = (ushort)(m_Bitset | (1 << k_ScaleYBit)); }
else { m_Bitset = (ushort)(m_Bitset & ~(1 << k_ScaleYBit)); }
}
}
internal bool HasScaleZ
{
get => (m_Bitset & (1 << k_ScaleZBit)) != 0;
set
{
if (value) { m_Bitset = (ushort)(m_Bitset | (1 << k_ScaleZBit)); }
else { m_Bitset = (ushort)(m_Bitset & ~(1 << k_ScaleZBit)); }
}
}
internal bool HasScaleChange
{
get
{
return HasScaleX | HasScaleY | HasScaleZ;
}
}
internal bool IsTeleportingNextFrame
{
get => (m_Bitset & (1 << k_TeleportingBit)) != 0;
set
{
if (value) { m_Bitset = (ushort)(m_Bitset | (1 << k_TeleportingBit)); }
else { m_Bitset = (ushort)(m_Bitset & ~(1 << k_TeleportingBit)); }
}
}
internal float PositionX, PositionY, PositionZ;
internal float RotAngleX, RotAngleY, RotAngleZ;
internal float ScaleX, ScaleY, ScaleZ;
internal double SentTime;
// Authoritative and non-authoritative sides use this to determine if a NetworkTransformState is
// dirty or not.
internal bool IsDirty;
// Non-Authoritative side uses this for ending extrapolation of the last applied state
internal int EndExtrapolationTick;
/// <summary>
/// This will reset the NetworkTransform BitSet
/// </summary>
internal void ClearBitSetForNextTick()
{
// We need to preserve the local space settings for the current state
m_Bitset &= (ushort)(m_Bitset & (1 << k_InLocalSpaceBit));
IsDirty = false;
}
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
serializer.SerializeValue(ref SentTime);
// InLocalSpace + HasXXX Bits
serializer.SerializeValue(ref m_Bitset);
// Position Values
if (HasPositionX)
{
serializer.SerializeValue(ref PositionX);
}
if (HasPositionY)
{
serializer.SerializeValue(ref PositionY);
}
if (HasPositionZ)
{
serializer.SerializeValue(ref PositionZ);
}
// RotAngle Values
if (HasRotAngleX)
{
serializer.SerializeValue(ref RotAngleX);
}
if (HasRotAngleY)
{
serializer.SerializeValue(ref RotAngleY);
}
if (HasRotAngleZ)
{
serializer.SerializeValue(ref RotAngleZ);
}
// Scale Values
if (HasScaleX)
{
serializer.SerializeValue(ref ScaleX);
}
if (HasScaleY)
{
serializer.SerializeValue(ref ScaleY);
}
if (HasScaleZ)
{
serializer.SerializeValue(ref ScaleZ);
}
// Only if we are receiving state
if (serializer.IsReader)
{
// Go ahead and mark the local state dirty or not dirty as well
/// <see cref="TryCommitTransformToServer"/>
if (HasPositionChange || HasRotAngleChange || HasScaleChange)
{
IsDirty = true;
}
else
{
IsDirty = false;
}
}
}
}
/// <summary>
/// Whether or not x component of position will be replicated
/// </summary>
public bool SyncPositionX = true;
/// <summary>
/// Whether or not y component of position will be replicated
/// </summary>
public bool SyncPositionY = true;
/// <summary>
/// Whether or not z component of position will be replicated
/// </summary>
public bool SyncPositionZ = true;
private bool SynchronizePosition
{
get
{
return SyncPositionX || SyncPositionY || SyncPositionZ;
}
}
/// <summary>
/// Whether or not x component of rotation will be replicated
/// </summary>
public bool SyncRotAngleX = true;
/// <summary>
/// Whether or not y component of rotation will be replicated
/// </summary>
public bool SyncRotAngleY = true;
/// <summary>
/// Whether or not z component of rotation will be replicated
/// </summary>
public bool SyncRotAngleZ = true;
private bool SynchronizeRotation
{
get
{
return SyncRotAngleX || SyncRotAngleY || SyncRotAngleZ;
}
}
/// <summary>
/// Whether or not x component of scale will be replicated
/// </summary>
public bool SyncScaleX = true;
/// <summary>
/// Whether or not y component of scale will be replicated
/// </summary>
public bool SyncScaleY = true;
/// <summary>
/// Whether or not z component of scale will be replicated
/// </summary>
public bool SyncScaleZ = true;
private bool SynchronizeScale
{
get
{
return SyncScaleX || SyncScaleY || SyncScaleZ;
}
}
/// <summary>
/// The current position threshold value
/// Any changes to the position that exceeds the current threshold value will be replicated
/// </summary>
public float PositionThreshold = PositionThresholdDefault;
/// <summary>
/// The current rotation threshold value
/// Any changes to the rotation that exceeds the current threshold value will be replicated
/// Minimum Value: 0.001
/// Maximum Value: 360.0
/// </summary>
[Range(0.001f, 360.0f)]
public float RotAngleThreshold = RotAngleThresholdDefault;
/// <summary>
/// The current scale threshold value
/// Any changes to the scale that exceeds the current threshold value will be replicated
/// </summary>
public float ScaleThreshold = ScaleThresholdDefault;
/// <summary>
/// Sets whether the transform should be treated as local (true) or world (false) space.
/// </summary>
/// <remarks>
/// This should only be changed by the authoritative side during runtime. Non-authoritative
/// changes will be overridden upon the next state update.
/// </remarks>
[Tooltip("Sets whether this transform should sync in local space or in world space")]
public bool InLocalSpace = false;
/// <summary>
/// When enabled (default) interpolation is applied and when disabled no interpolation is applied
/// </summary>
public bool Interpolate = true;
/// <summary>
/// Used to determine who can write to this transform. Server only for this transform.
/// Changing this value alone in a child implementation will not allow you to create a NetworkTransform which can be written to by clients. See the ClientNetworkTransform Sample
/// in the package samples for how to implement a NetworkTransform with client write support.
/// If using different values, please use RPCs to write to the server. Netcode doesn't support client side network variable writing
/// </summary>
public bool CanCommitToTransform { get; protected set; }
/// <summary>
/// Internally used by <see cref="NetworkTransform"/> to keep track of whether this <see cref="NetworkBehaviour"/> derived class instance
/// was instantiated on the server side or not.
/// </summary>
protected bool m_CachedIsServer;
/// <summary>
/// Internally used by <see cref="NetworkTransform"/> to keep track of the <see cref="NetworkManager"/> instance assigned to this
/// this <see cref="NetworkBehaviour"/> derived class instance.
/// </summary>
protected NetworkManager m_CachedNetworkManager;
/// <summary>
/// We have two internal NetworkVariables.
/// One for server authoritative and one for "client/owner" authoritative.
/// </summary>
private readonly NetworkVariable<NetworkTransformState> m_ReplicatedNetworkStateServer = new NetworkVariable<NetworkTransformState>(new NetworkTransformState(), NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Server);
private readonly NetworkVariable<NetworkTransformState> m_ReplicatedNetworkStateOwner = new NetworkVariable<NetworkTransformState>(new NetworkTransformState(), NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
internal NetworkVariable<NetworkTransformState> ReplicatedNetworkState
{
get
{
if (!IsServerAuthoritative())
{
return m_ReplicatedNetworkStateOwner;
}
return m_ReplicatedNetworkStateServer;
}
}
// Used by both authoritative and non-authoritative instances.
// This represents the most recent local authoritative state.
private NetworkTransformState m_LocalAuthoritativeNetworkState;
private ClientRpcParams m_ClientRpcParams = new ClientRpcParams() { Send = new ClientRpcSendParams() };
private List<ulong> m_ClientIds = new List<ulong>() { 0 };
private BufferedLinearInterpolator<float> m_PositionXInterpolator;
private BufferedLinearInterpolator<float> m_PositionYInterpolator;
private BufferedLinearInterpolator<float> m_PositionZInterpolator;
private BufferedLinearInterpolator<Quaternion> m_RotationInterpolator; // rotation is a single Quaternion since each Euler axis will affect the quaternion's final value
private BufferedLinearInterpolator<float> m_ScaleXInterpolator;
private BufferedLinearInterpolator<float> m_ScaleYInterpolator;
private BufferedLinearInterpolator<float> m_ScaleZInterpolator;
private readonly List<BufferedLinearInterpolator<float>> m_AllFloatInterpolators = new List<BufferedLinearInterpolator<float>>(6);
// Used by integration test
private NetworkTransformState m_LastSentState;
internal NetworkTransformState GetLastSentState()
{
return m_LastSentState;
}
/// <summary>
/// Calculated when spawned, this is used to offset a newly received non-authority side state by 1 tick duration
/// in order to end the extrapolation for that state's values.
/// </summary>
/// <remarks>
/// Example:
/// NetworkState-A is received, processed, and measurements added
/// NetworkState-A is duplicated (NetworkState-A-Post) and its sent time is offset by the tick frequency
/// One tick later, NetworkState-A-Post is applied to end that delta's extrapolation.
/// <see cref="OnNetworkStateChanged"/> to see how NetworkState-A-Post doesn't get excluded/missed
/// </remarks>
private double m_TickFrequency;
/// <summary>
/// This will try to send/commit the current transform delta states (if any)
/// </summary>
/// <remarks>
/// Only client owners or the server should invoke this method
/// </remarks>
/// <param name="transformToCommit">the transform to be committed</param>
/// <param name="dirtyTime">time it was marked dirty</param>
protected void TryCommitTransformToServer(Transform transformToCommit, double dirtyTime)
{
// Only client owners or the server should invoke this method
if (!IsOwner && !m_CachedIsServer)
{
NetworkLog.LogError($"Non-owner instance, {name}, is trying to commit a transform!");
return;
}
// If we are authority, update the authoritative state
if (CanCommitToTransform)
{
UpdateAuthoritativeState(transform);
}
else // Non-Authority
{
// We are an owner requesting to update our state
if (!m_CachedIsServer)
{
SetStateServerRpc(transformToCommit.position, transformToCommit.rotation, transformToCommit.localScale, false);
}
else // Server is always authoritative (including owner authoritative)
{
SetStateClientRpc(transformToCommit.position, transformToCommit.rotation, transformToCommit.localScale, false);
}
}
}
/// <summary>
/// Authoritative side only
/// If there are any transform delta states, this method will synchronize the
/// state with all non-authority instances.
/// </summary>
private void TryCommitTransform(Transform transformToCommit, double dirtyTime)
{
if (!CanCommitToTransform && !IsOwner)
{
NetworkLog.LogError($"[{name}] is trying to commit the transform without authority!");
return;
}
// If the transform has deltas (returns dirty) then...
if (ApplyTransformToNetworkState(ref m_LocalAuthoritativeNetworkState, dirtyTime, transformToCommit))
{
// ...commit the state
ReplicatedNetworkState.Value = m_LocalAuthoritativeNetworkState;
}
}
private void ResetInterpolatedStateToCurrentAuthoritativeState()
{
var serverTime = NetworkManager.ServerTime.Time;
// TODO: Look into a better way to communicate the entire state for late joining clients.
// Since the replicated network state will just be the most recent deltas and not the entire state.
//m_PositionXInterpolator.ResetTo(m_LocalAuthoritativeNetworkState.PositionX, serverTime);
//m_PositionYInterpolator.ResetTo(m_LocalAuthoritativeNetworkState.PositionY, serverTime);
//m_PositionZInterpolator.ResetTo(m_LocalAuthoritativeNetworkState.PositionZ, serverTime);
//m_RotationInterpolator.ResetTo(Quaternion.Euler(m_LocalAuthoritativeNetworkState.RotAngleX, m_LocalAuthoritativeNetworkState.RotAngleY, m_LocalAuthoritativeNetworkState.RotAngleZ), serverTime);
//m_ScaleXInterpolator.ResetTo(m_LocalAuthoritativeNetworkState.ScaleX, serverTime);
//m_ScaleYInterpolator.ResetTo(m_LocalAuthoritativeNetworkState.ScaleY, serverTime);
//m_ScaleZInterpolator.ResetTo(m_LocalAuthoritativeNetworkState.ScaleZ, serverTime);
// NOTE ABOUT THIS CHANGE:
// !!! This will exclude any scale changes because we currently do not spawn network objects with scale !!!
// Regarding Scale: It will be the same scale as the default scale for the object being spawned.
var position = InLocalSpace ? transform.localPosition : transform.position;
m_PositionXInterpolator.ResetTo(position.x, serverTime);
m_PositionYInterpolator.ResetTo(position.y, serverTime);
m_PositionZInterpolator.ResetTo(position.z, serverTime);
var rotation = InLocalSpace ? transform.localRotation : transform.rotation;
m_RotationInterpolator.ResetTo(rotation, serverTime);
// TODO: (Create Jira Ticket) Synchronize local scale during NetworkObject synchronization
// (We will probably want to byte pack TransformData to offset the 3 float addition)
m_ScaleXInterpolator.ResetTo(transform.localScale.x, serverTime);
m_ScaleYInterpolator.ResetTo(transform.localScale.y, serverTime);
m_ScaleZInterpolator.ResetTo(transform.localScale.z, serverTime);
}
/// <summary>
/// Used for integration testing:
/// Will apply the transform to the LocalAuthoritativeNetworkState and get detailed dirty information returned
/// in the <see cref="NetworkTransformState"/> returned.
/// </summary>
/// <param name="transform">transform to apply</param>
/// <returns>NetworkTransformState</returns>
internal NetworkTransformState ApplyLocalNetworkState(Transform transform)
{
// Since we never commit these changes, we need to simulate that any changes were committed previously and the bitset
// value would already be reset prior to having the state applied
m_LocalAuthoritativeNetworkState.ClearBitSetForNextTick();
// Now check the transform for any threshold value changes
ApplyTransformToNetworkStateWithInfo(ref m_LocalAuthoritativeNetworkState, m_CachedNetworkManager.LocalTime.Time, transform);
// Return the entire state to be used by the integration test
return m_LocalAuthoritativeNetworkState;
}
/// <summary>
/// Used for integration testing
/// </summary>
internal bool ApplyTransformToNetworkState(ref NetworkTransformState networkState, double dirtyTime, Transform transformToUse)
{
return ApplyTransformToNetworkStateWithInfo(ref networkState, dirtyTime, transformToUse);
}
/// <summary>
/// Applies the transform to the <see cref="NetworkTransformState"/> specified.
/// </summary>
private bool ApplyTransformToNetworkStateWithInfo(ref NetworkTransformState networkState, double dirtyTime, Transform transformToUse)
{
var isDirty = false;
var isPositionDirty = false;
var isRotationDirty = false;
var isScaleDirty = false;
var position = InLocalSpace ? transformToUse.localPosition : transformToUse.position;
var rotAngles = InLocalSpace ? transformToUse.localEulerAngles : transformToUse.eulerAngles;
var scale = transformToUse.localScale;
if (InLocalSpace != networkState.InLocalSpace)
{
networkState.InLocalSpace = InLocalSpace;
isDirty = true;
}
if (SyncPositionX && Mathf.Abs(networkState.PositionX - position.x) >= PositionThreshold || networkState.IsTeleportingNextFrame)
{
networkState.PositionX = position.x;
networkState.HasPositionX = true;
isPositionDirty = true;
}
if (SyncPositionY && Mathf.Abs(networkState.PositionY - position.y) >= PositionThreshold || networkState.IsTeleportingNextFrame)
{
networkState.PositionY = position.y;
networkState.HasPositionY = true;
isPositionDirty = true;
}
if (SyncPositionZ && Mathf.Abs(networkState.PositionZ - position.z) >= PositionThreshold || networkState.IsTeleportingNextFrame)
{
networkState.PositionZ = position.z;
networkState.HasPositionZ = true;
isPositionDirty = true;
}
if (SyncRotAngleX && Mathf.Abs(Mathf.DeltaAngle(networkState.RotAngleX, rotAngles.x)) >= RotAngleThreshold || networkState.IsTeleportingNextFrame)
{
networkState.RotAngleX = rotAngles.x;
networkState.HasRotAngleX = true;
isRotationDirty = true;
}
if (SyncRotAngleY && Mathf.Abs(Mathf.DeltaAngle(networkState.RotAngleY, rotAngles.y)) >= RotAngleThreshold || networkState.IsTeleportingNextFrame)
{
networkState.RotAngleY = rotAngles.y;
networkState.HasRotAngleY = true;
isRotationDirty = true;
}
if (SyncRotAngleZ && Mathf.Abs(Mathf.DeltaAngle(networkState.RotAngleZ, rotAngles.z)) >= RotAngleThreshold || networkState.IsTeleportingNextFrame)
{
networkState.RotAngleZ = rotAngles.z;
networkState.HasRotAngleZ = true;
isRotationDirty = true;
}
if (SyncScaleX && Mathf.Abs(networkState.ScaleX - scale.x) >= ScaleThreshold || networkState.IsTeleportingNextFrame)
{
networkState.ScaleX = scale.x;
networkState.HasScaleX = true;
isScaleDirty = true;
}
if (SyncScaleY && Mathf.Abs(networkState.ScaleY - scale.y) >= ScaleThreshold || networkState.IsTeleportingNextFrame)
{
networkState.ScaleY = scale.y;
networkState.HasScaleY = true;
isScaleDirty = true;
}
if (SyncScaleZ && Mathf.Abs(networkState.ScaleZ - scale.z) >= ScaleThreshold || networkState.IsTeleportingNextFrame)
{
networkState.ScaleZ = scale.z;
networkState.HasScaleZ = true;
isScaleDirty = true;
}
isDirty |= isPositionDirty || isRotationDirty || isScaleDirty;
if (isDirty)
{
networkState.SentTime = dirtyTime;
}
/// We need to set this in order to know when we can reset our local authority state <see cref="Update"/>
/// If our state is already dirty or we just found deltas (i.e. isDirty == true)
networkState.IsDirty |= isDirty;
return isDirty;
}
/// <summary>
/// Applies the authoritative state to the transform
/// </summary>
private void ApplyAuthoritativeState()
{
var networkState = ReplicatedNetworkState.Value;
var adjustedPosition = networkState.InLocalSpace ? transform.localPosition : transform.position;
// TODO: We should store network state w/ quats vs. euler angles
var adjustedRotAngles = networkState.InLocalSpace ? transform.localEulerAngles : transform.eulerAngles;
var adjustedScale = transform.localScale;
// InLocalSpace Read:
InLocalSpace = networkState.InLocalSpace;
// NOTE ABOUT INTERPOLATING AND THE CODE BELOW:
// We always apply the interpolated state for any axis we are synchronizing even when the state has no deltas
// to assure we fully interpolate to our target even after we stop extrapolating 1 tick later.
var useInterpolatedValue = !networkState.IsTeleportingNextFrame && Interpolate;
if (useInterpolatedValue)
{
if (SyncPositionX) { adjustedPosition.x = m_PositionXInterpolator.GetInterpolatedValue(); }
if (SyncPositionY) { adjustedPosition.y = m_PositionYInterpolator.GetInterpolatedValue(); }
if (SyncPositionZ) { adjustedPosition.z = m_PositionZInterpolator.GetInterpolatedValue(); }
if (SyncScaleX) { adjustedScale.x = m_ScaleXInterpolator.GetInterpolatedValue(); }
if (SyncScaleY) { adjustedScale.y = m_ScaleYInterpolator.GetInterpolatedValue(); }
if (SyncScaleZ) { adjustedScale.z = m_ScaleZInterpolator.GetInterpolatedValue(); }
if (SynchronizeRotation)
{
var interpolatedEulerAngles = m_RotationInterpolator.GetInterpolatedValue().eulerAngles;
if (SyncRotAngleX) { adjustedRotAngles.x = interpolatedEulerAngles.x; }
if (SyncRotAngleY) { adjustedRotAngles.y = interpolatedEulerAngles.y; }
if (SyncRotAngleZ) { adjustedRotAngles.z = interpolatedEulerAngles.z; }
}
}
else
{
if (networkState.HasPositionX) { adjustedPosition.x = networkState.PositionX; }
if (networkState.HasPositionY) { adjustedPosition.y = networkState.PositionY; }
if (networkState.HasPositionZ) { adjustedPosition.z = networkState.PositionZ; }
if (networkState.HasScaleX) { adjustedScale.x = networkState.ScaleX; }
if (networkState.HasScaleY) { adjustedScale.y = networkState.ScaleY; }
if (networkState.HasScaleZ) { adjustedScale.z = networkState.ScaleZ; }
if (networkState.HasRotAngleX) { adjustedRotAngles.x = networkState.RotAngleX; }
if (networkState.HasRotAngleY) { adjustedRotAngles.y = networkState.RotAngleY; }
if (networkState.HasRotAngleZ) { adjustedRotAngles.z = networkState.RotAngleZ; }
}
// NOTE: The below conditional checks for applying axial values are required in order to
// prevent the non-authoritative side from making adjustments when interpolation is off.
// TODO: Determine if we want to enforce, frame by frame, the non-authoritative transform values.
// We would want save the position, rotation, and scale (each individually) after applying each
// authoritative transform state received. Otherwise, the non-authoritative side could make
// changes to an axial value (if interpolation is turned off) until authority sends an update for
// that same axial value. When interpolation is on, the state's values being synchronized are
// always applied each frame.
// Apply the new position if it has changed or we are interpolating and synchronizing position
if (networkState.HasPositionChange || (useInterpolatedValue && SynchronizePosition))
{
if (InLocalSpace)
{
transform.localPosition = adjustedPosition;
}
else
{
transform.position = adjustedPosition;
}
}
// Apply the new rotation if it has changed or we are interpolating and synchronizing rotation
if (networkState.HasRotAngleChange || (useInterpolatedValue && SynchronizeRotation))
{
if (InLocalSpace)
{
transform.localRotation = Quaternion.Euler(adjustedRotAngles);
}
else
{
transform.rotation = Quaternion.Euler(adjustedRotAngles);
}
}
// Apply the new scale if it has changed or we are interpolating and synchronizing scale
if (networkState.HasScaleChange || (useInterpolatedValue && SynchronizeScale))
{
transform.localScale = adjustedScale;
}
}
/// <summary>
/// Only non-authoritative instances should invoke this
/// </summary>
private void AddInterpolatedState(NetworkTransformState newState)
{
var sentTime = newState.SentTime;
var currentPosition = newState.InLocalSpace ? transform.localPosition : transform.position;
var currentRotation = newState.InLocalSpace ? transform.localRotation : transform.rotation;
var currentEulerAngles = currentRotation.eulerAngles;
// When there is a change in interpolation or if teleporting, we reset
if ((newState.InLocalSpace != InLocalSpace) || newState.IsTeleportingNextFrame)
{
InLocalSpace = newState.InLocalSpace;
var currentScale = transform.localScale;
// we should clear our float interpolators
foreach (var interpolator in m_AllFloatInterpolators)
{
interpolator.Clear();
}
// we should clear our quaternion interpolator
m_RotationInterpolator.Clear();
// Adjust based on which axis changed
if (newState.HasPositionX)
{
m_PositionXInterpolator.ResetTo(newState.PositionX, sentTime);
currentPosition.x = newState.PositionX;
}
if (newState.HasPositionY)
{
m_PositionYInterpolator.ResetTo(newState.PositionY, sentTime);
currentPosition.y = newState.PositionY;
}
if (newState.HasPositionZ)
{
m_PositionZInterpolator.ResetTo(newState.PositionZ, sentTime);
currentPosition.z = newState.PositionZ;
}
// Apply the position
if (newState.InLocalSpace)
{
transform.localPosition = currentPosition;
}
else
{
transform.position = currentPosition;
}
// Adjust based on which axis changed
if (newState.HasScaleX)
{
m_ScaleXInterpolator.ResetTo(newState.ScaleX, sentTime);
currentScale.x = newState.ScaleX;
}
if (newState.HasScaleY)
{
m_ScaleYInterpolator.ResetTo(newState.ScaleY, sentTime);
currentScale.y = newState.ScaleY;
}
if (newState.HasScaleZ)
{
m_ScaleZInterpolator.ResetTo(newState.ScaleZ, sentTime);
currentScale.z = newState.ScaleZ;
}
// Apply the adjusted scale
transform.localScale = currentScale;
// Adjust based on which axis changed
if (newState.HasRotAngleX)
{
currentEulerAngles.x = newState.RotAngleX;
}
if (newState.HasRotAngleY)
{
currentEulerAngles.y = newState.RotAngleY;
}
if (newState.HasRotAngleZ)
{
currentEulerAngles.z = newState.RotAngleZ;
}
// Apply the rotation
currentRotation.eulerAngles = currentEulerAngles;
transform.rotation = currentRotation;
// Reset the rotation interpolator
m_RotationInterpolator.ResetTo(currentRotation, sentTime);
return;
}
// Apply axial changes from the new state
if (newState.HasPositionX)
{
m_PositionXInterpolator.AddMeasurement(newState.PositionX, sentTime);
}
if (newState.HasPositionY)
{
m_PositionYInterpolator.AddMeasurement(newState.PositionY, sentTime);
}
if (newState.HasPositionZ)
{
m_PositionZInterpolator.AddMeasurement(newState.PositionZ, sentTime);
}
if (newState.HasScaleX)
{
m_ScaleXInterpolator.AddMeasurement(newState.ScaleX, sentTime);
}
if (newState.HasScaleY)
{
m_ScaleYInterpolator.AddMeasurement(newState.ScaleY, sentTime);
}
if (newState.HasScaleZ)
{
m_ScaleZInterpolator.AddMeasurement(newState.ScaleZ, sentTime);
}
// With rotation, we check if there are any changes first and
// if so then apply the changes to the current Euler rotation
// values.
if (newState.HasRotAngleChange)
{
if (newState.HasRotAngleX)
{
currentEulerAngles.x = newState.RotAngleX;
}
if (newState.HasRotAngleY)
{
currentEulerAngles.y = newState.RotAngleY;
}
if (newState.HasRotAngleZ)
{
currentEulerAngles.z = newState.RotAngleZ;
}
currentRotation.eulerAngles = currentEulerAngles;
m_RotationInterpolator.AddMeasurement(currentRotation, sentTime);
}
}
/// <summary>
/// Only non-authoritative instances should invoke this method
/// </summary>
private void OnNetworkStateChanged(NetworkTransformState oldState, NetworkTransformState newState)
{
if (!NetworkObject.IsSpawned)
{
return;
}
if (CanCommitToTransform)
{
// we're the authority, we ignore incoming changes
return;
}
if (Interpolate)
{
// Add measurements for the new state's deltas
AddInterpolatedState(newState);
}
}
/// <summary>
/// Will set the maximum interpolation boundary for the interpolators of this <see cref="NetworkTransform"/> instance.
/// This value roughly translates to the maximum value of 't' in <see cref="Mathf.Lerp(float, float, float)"/> and
/// <see cref="Mathf.LerpUnclamped(float, float, float)"/> for all transform elements being monitored by
/// <see cref="NetworkTransform"/> (i.e. Position, Rotation, and Scale)
/// </summary>
/// <param name="maxInterpolationBound">Maximum time boundary that can be used in a frame when interpolating between two values</param>
public void SetMaxInterpolationBound(float maxInterpolationBound)
{
m_PositionXInterpolator.MaxInterpolationBound = maxInterpolationBound;
m_PositionYInterpolator.MaxInterpolationBound = maxInterpolationBound;
m_PositionZInterpolator.MaxInterpolationBound = maxInterpolationBound;
m_RotationInterpolator.MaxInterpolationBound = maxInterpolationBound;
m_ScaleXInterpolator.MaxInterpolationBound = maxInterpolationBound;
m_ScaleYInterpolator.MaxInterpolationBound = maxInterpolationBound;
m_ScaleZInterpolator.MaxInterpolationBound = maxInterpolationBound;
}
/// <summary>
/// Create interpolators when first instantiated to avoid memory allocations if the
/// associated NetworkObject persists (i.e. despawned but not destroyed or pools)
/// </summary>
private void Awake()
{
// Rotation is a single Quaternion since each Euler axis will affect the quaternion's final value
m_RotationInterpolator = new BufferedLinearInterpolatorQuaternion();
// All other interpolators are BufferedLinearInterpolatorFloats
m_PositionXInterpolator = new BufferedLinearInterpolatorFloat();
m_PositionYInterpolator = new BufferedLinearInterpolatorFloat();
m_PositionZInterpolator = new BufferedLinearInterpolatorFloat();
m_ScaleXInterpolator = new BufferedLinearInterpolatorFloat();
m_ScaleYInterpolator = new BufferedLinearInterpolatorFloat();
m_ScaleZInterpolator = new BufferedLinearInterpolatorFloat();
// Used to quickly iteration over the BufferedLinearInterpolatorFloat
// instances