-
Notifications
You must be signed in to change notification settings - Fork 459
Expand file tree
/
Copy pathNetworkTransform.cs
More file actions
4758 lines (4307 loc) · 222 KB
/
NetworkTransform.cs
File metadata and controls
4758 lines (4307 loc) · 222 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 System.Runtime.CompilerServices;
using System.Text;
using Unity.Mathematics;
using Unity.Netcode.Runtime;
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/Network Transform")]
[HelpURL(HelpUrls.NetworkTransform)]
public class NetworkTransform : NetworkBehaviour
{
#if UNITY_EDITOR
internal virtual bool HideInterpolateValue => false;
[HideInInspector]
[SerializeField]
internal bool NetworkTransformExpanded;
#endif
#region NETWORK TRANSFORM STATE
/// <summary>
/// Data structure used to synchronize the <see cref="NetworkTransform"/>
/// </summary>
public struct NetworkTransformState : INetworkSerializable
{
// Persists between state updates (authority dictates if this is set)
private const int k_InLocalSpaceBit = 0x00000001;
private const int k_PositionXBit = 0x00000002;
private const int k_PositionYBit = 0x00000004;
private const int k_PositionZBit = 0x00000008;
private const int k_RotAngleXBit = 0x00000010;
private const int k_RotAngleYBit = 0x00000020;
private const int k_RotAngleZBit = 0x00000040;
private const int k_ScaleXBit = 0x00000080;
private const int k_ScaleYBit = 0x00000100;
private const int k_ScaleZBit = 0x00000200;
private const int k_TeleportingBit = 0x00000400;
// Persists between state updates (authority dictates if this is set)
private const int k_Interpolate = 0x00000800;
// Persists between state updates (authority dictates if this is set)
private const int k_QuaternionSync = 0x00001000;
// Persists between state updates (authority dictates if this is set)
private const int k_QuaternionCompress = 0x00002000;
// Persists between state updates (authority dictates if this is set)
private const int k_UseHalfFloats = 0x00004000;
private const int k_Synchronization = 0x00008000;
// Persists between state updates (authority dictates if this is set)
private const int k_PositionSlerp = 0x00010000;
// When parented and synchronizing, we need to have both lossy and local scale due to varying spawn order
private const int k_IsParented = 0x00020000;
private const int k_SynchBaseHalfFloat = 0x00040000;
private const int k_ReliableSequenced = 0x00080000;
private const int k_UseUnreliableDeltas = 0x00100000;
private const int k_UnreliableFrameSync = 0x00200000;
// (Internal Debugging) When set each state update will contain a state identifier
private const int k_TrackStateId = 0x10000000;
// Stores persistent and state relative flags
private uint m_Bitset;
internal uint BitSet
{
get { return m_Bitset; }
set { m_Bitset = value; }
}
// Used to store the tick calculated sent time
internal double SentTime;
// Used for full precision position updates
internal float PositionX, PositionY, PositionZ;
// Used for full precision Euler updates
internal float RotAngleX, RotAngleY, RotAngleZ;
// Used for full precision quaternion updates
internal Quaternion Rotation;
// Used for full precision scale updates
internal float ScaleX, ScaleY, ScaleZ;
// Used for half precision delta position updates
internal Vector3 CurrentPosition;
internal Vector3 DeltaPosition;
internal NetworkDeltaPosition NetworkDeltaPosition;
// Used for half precision scale
internal HalfVector3 HalfVectorScale;
internal Vector3 Scale;
internal Vector3 LossyScale;
// Used for half precision quaternion
internal HalfVector4 HalfVectorRotation;
// Used to store a compressed quaternion
internal uint QuaternionCompressed;
// Authoritative and non-authoritative sides use this to determine if a NetworkTransformState is
// dirty or not.
internal bool IsDirty { get; set; }
/// <summary>
/// The last byte size of the <see cref="NetworkTransformState"/> updated.
/// </summary>
public int LastSerializedSize { get; internal set; }
// Used for NetworkDeltaPosition delta position synchronization
internal int NetworkTick;
// Used when tracking by state ID is enabled
internal int StateId;
// Set when a state has been explicitly set (i.e. SetState)
internal bool ExplicitSet;
// Used during serialization
private FastBufferReader m_Reader;
private FastBufferWriter m_Writer;
/// <summary>
/// When set, the <see cref="NetworkTransform"/> is operates in local space
/// </summary>
public bool InLocalSpace
{
get => GetFlag(k_InLocalSpaceBit);
internal set
{
SetFlag(value, k_InLocalSpaceBit);
}
}
// Position
/// <summary>
/// When set, the X-Axis position value has changed
/// </summary>
public bool HasPositionX
{
get => GetFlag(k_PositionXBit);
internal set
{
SetFlag(value, k_PositionXBit);
}
}
/// <summary>
/// When set, the Y-Axis position value has changed
/// </summary>
public bool HasPositionY
{
get => GetFlag(k_PositionYBit);
internal set
{
SetFlag(value, k_PositionYBit);
}
}
/// <summary>
/// When set, the Z-Axis position value has changed
/// </summary>
public bool HasPositionZ
{
get => GetFlag(k_PositionZBit);
internal set
{
SetFlag(value, k_PositionZBit);
}
}
/// <summary>
/// When set, at least one of the position axis values has changed.
/// </summary>
public bool HasPositionChange
{
get
{
return HasPositionX | HasPositionY | HasPositionZ;
}
}
// RotAngles
/// <summary>
/// When set, the Euler rotation X-Axis value has changed.
/// </summary>
/// <remarks>
/// When quaternion synchronization is enabled all axis are always updated.
/// </remarks>
public bool HasRotAngleX
{
get => GetFlag(k_RotAngleXBit);
internal set
{
SetFlag(value, k_RotAngleXBit);
}
}
/// <summary>
/// When set, the Euler rotation Y-Axis value has changed.
/// </summary>
/// <remarks>
/// When quaternion synchronization is enabled all axis are always updated.
/// </remarks>
public bool HasRotAngleY
{
get => GetFlag(k_RotAngleYBit);
internal set
{
SetFlag(value, k_RotAngleYBit);
}
}
/// <summary>
/// When set, the Euler rotation Z-Axis value has changed.
/// </summary>
/// <remarks>
/// When quaternion synchronization is enabled all axis are always updated.
/// </remarks>
public bool HasRotAngleZ
{
get => GetFlag(k_RotAngleZBit);
internal set
{
SetFlag(value, k_RotAngleZBit);
}
}
/// <summary>
/// When set, at least one of the rotation axis values has changed.
/// </summary>
/// <remarks>
/// When quaternion synchronization is enabled all axis are always updated.
/// </remarks>
public bool HasRotAngleChange
{
get
{
return HasRotAngleX | HasRotAngleY | HasRotAngleZ;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal bool HasScale(int axisIndex)
{
return GetFlag(k_ScaleXBit << axisIndex);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void SetHasScale(int axisIndex, bool isSet)
{
SetFlag(isSet, k_ScaleXBit << axisIndex);
}
// Scale
/// <summary>
/// When set, the X-Axis scale value has changed.
/// </summary>
public bool HasScaleX
{
get => GetFlag(k_ScaleXBit);
internal set
{
SetFlag(value, k_ScaleXBit);
}
}
/// <summary>
/// When set, the Y-Axis scale value has changed.
/// </summary>
public bool HasScaleY
{
get => GetFlag(k_ScaleYBit);
internal set
{
SetFlag(value, k_ScaleYBit);
}
}
/// <summary>
/// When set, the Z-Axis scale value has changed.
/// </summary>
public bool HasScaleZ
{
get => GetFlag(k_ScaleZBit);
internal set
{
SetFlag(value, k_ScaleZBit);
}
}
/// <summary>
/// When set, at least one of the scale axis values has changed.
/// </summary>
public bool HasScaleChange
{
get
{
return HasScaleX | HasScaleY | HasScaleZ;
}
}
/// <summary>
/// When set, the current state will be treated as a teleport.
/// </summary>
/// <remarks>
/// When teleporting:
/// - Interpolation is reset.
/// - If using half precision, full precision values are used.
/// - All axis marked to be synchronized will be updated.
/// </remarks>
public bool IsTeleportingNextFrame
{
get => GetFlag(k_TeleportingBit);
internal set
{
SetFlag(value, k_TeleportingBit);
}
}
/// <summary>
/// When set the <see cref="NetworkTransform"/> is uses interpolation.
/// </summary>
/// <remarks>
/// Authority does not apply interpolation via <see cref="NetworkTransform"/>.
/// Authority should handle its own motion/rotation/scale smoothing locally.
/// </remarks>
public bool UseInterpolation
{
get => GetFlag(k_Interpolate);
internal set
{
SetFlag(value, k_Interpolate);
}
}
/// <summary>
/// When enabled, this <see cref="NetworkTransform"/> instance uses <see cref="Quaternion"/> synchronization.
/// </summary>
/// <remarks>
/// Use quaternion synchronization if you are nesting <see cref="NetworkTransform"/>s and rotation can occur on both the parent and child.
/// When quaternion synchronization is enabled, the entire quaternion is updated when there are any changes to any axial values.
/// You can use half float precision or quaternion compression to reduce the bandwidth cost.
/// </remarks>
public bool QuaternionSync
{
get => GetFlag(k_QuaternionSync);
internal set
{
SetFlag(value, k_QuaternionSync);
}
}
/// <summary>
/// When set <see cref="Quaternion"/>s will be compressed down to 4 bytes using a smallest three implementation.
/// </summary>
/// <remarks>
/// This only will be applied when <see cref="QuaternionSync"/> is enabled.
/// Half float precision provides a higher precision than quaternion compression but at the cost of 4 additional bytes per update.
/// - Quaternion Compression: 4 bytes per delta update
/// - Half float precision: 8 bytes per delta update
/// </remarks>
public bool QuaternionCompression
{
get => GetFlag(k_QuaternionCompress);
internal set
{
SetFlag(value, k_QuaternionCompress);
}
}
/// <summary>
/// When set, the <see cref="NetworkTransform"/> will use half float precision for position, rotation, and scale.
/// </summary>
/// <remarks>
/// Postion is synchronized through delta position updates in order to reduce precision loss/drift and to extend to positions beyond the limitation of half float maximum values.
/// Rotation and scale both use half float precision (<see cref="HalfVector4"/> and <see cref="HalfVector3"/>)
/// </remarks>
public bool UseHalfFloatPrecision
{
get => GetFlag(k_UseHalfFloats);
internal set
{
SetFlag(value, k_UseHalfFloats);
}
}
/// <summary>
/// When set, this indicates it is the first state being synchronized.
/// Typically when the associate <see cref="NetworkObject"/> is spawned or a client is being synchronized after connecting to a network session in progress.
/// </summary>
public bool IsSynchronizing
{
get => GetFlag(k_Synchronization);
internal set
{
SetFlag(value, k_Synchronization);
}
}
/// <summary>
/// Determines if position interpolation will Slerp towards its target position.
/// This is only really useful if you are moving around a point in a circular pattern.
/// </summary>
public bool UsePositionSlerp
{
get => GetFlag(k_PositionSlerp);
internal set
{
SetFlag(value, k_PositionSlerp);
}
}
/// <summary>
/// Returns whether this state update was a frame synchronization when
/// UseUnreliableDeltas is enabled. When set, the entire transform will
/// be or has been synchronized.
/// </summary>
/// <returns>true or false as to whether this state update was an unreliable frame synchronization.</returns>
public bool IsUnreliableFrameSync()
{
return UnreliableFrameSync;
}
/// <summary>
/// Returns true if this state was sent with reliable delivery.
/// If false, then it was sent with unreliable delivery.
/// </summary>
/// <remarks>
/// Unreliable delivery will only be used if <see cref="UseUnreliableDeltas"/> is set.
/// </remarks>
/// <returns>true or false as to whether this state update was sent with reliable delivery.</returns>
public bool IsReliableStateUpdate()
{
return ReliableSequenced;
}
internal bool IsParented
{
get => GetFlag(k_IsParented);
set
{
SetFlag(value, k_IsParented);
}
}
internal bool SynchronizeBaseHalfFloat
{
get => GetFlag(k_SynchBaseHalfFloat);
set
{
SetFlag(value, k_SynchBaseHalfFloat);
}
}
internal bool ReliableSequenced
{
get => GetFlag(k_ReliableSequenced);
set
{
SetFlag(value, k_ReliableSequenced);
}
}
internal bool UseUnreliableDeltas
{
get => GetFlag(k_UseUnreliableDeltas);
set
{
SetFlag(value, k_UseUnreliableDeltas);
}
}
internal bool UnreliableFrameSync
{
get => GetFlag(k_UnreliableFrameSync);
set
{
SetFlag(value, k_UnreliableFrameSync);
}
}
internal bool TrackByStateId
{
get => GetFlag(k_TrackStateId);
set
{
SetFlag(value, k_TrackStateId);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool GetFlag(int flag)
{
return (m_Bitset & flag) != 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void SetFlag(bool set, int flag)
{
if (set) { m_Bitset = m_Bitset | (uint)flag; }
else { m_Bitset = m_Bitset & (uint)~flag; }
}
internal void ClearBitSetForNextTick()
{
// Clear everything but flags that should persist between state updates until changed by authority
m_Bitset &= k_InLocalSpaceBit | k_Interpolate | k_UseHalfFloats | k_QuaternionSync | k_QuaternionCompress | k_PositionSlerp | k_UseUnreliableDeltas;
IsDirty = false;
}
/// <summary>
/// Returns the current state's rotation. If there is no change in the rotation,
/// then it will return <see cref="Quaternion.identity"/>.
/// </summary>
/// <remarks>
/// When there is no change in an updated state's rotation then there are no values to return.
/// Checking for <see cref="HasRotAngleChange"/> is one way to detect this.
/// </remarks>
/// <returns><see cref="Quaternion"/></returns>
public Quaternion GetRotation()
{
if (HasRotAngleChange)
{
if (QuaternionSync)
{
return Rotation;
}
else
{
return Quaternion.Euler(RotAngleX, RotAngleY, RotAngleZ);
}
}
return Quaternion.identity;
}
/// <summary>
/// Returns the current state's position. If there is no change in position,
/// then it returns <see cref="Vector3.zero"/>.
/// </summary>
/// <remarks>
/// When there is no change in an updated state's position then there are no values to return.
/// Checking for <see cref="HasPositionChange"/> is one way to detect this.
/// When used with half precision it returns the half precision delta position state update
/// which will not be the full position.
/// To get a NettworkTransform's full position, use <see cref="GetSpaceRelativePosition(bool)"/> and
/// pass true as the parameter.
/// </remarks>
/// <returns><see cref="Vector3"/></returns>
public Vector3 GetPosition()
{
if (HasPositionChange)
{
if (UseHalfFloatPrecision)
{
if (IsTeleportingNextFrame)
{
return CurrentPosition;
}
else
{
return NetworkDeltaPosition.GetFullPosition();
}
}
else
{
return new Vector3(PositionX, PositionY, PositionZ);
}
}
return Vector3.zero;
}
/// <summary>
/// Returns the current state's scale. If there is no change in scale,
/// then it returns <see cref="Vector3.zero"/>.
/// </summary>
/// <remarks>
/// When there is no change in an updated state's scale then there are no values to return.
/// Checking for <see cref="HasScaleChange"/> is one way to detect this.
/// </remarks>
/// <returns><see cref="Vector3"/></returns>
public Vector3 GetScale()
{
if (HasScaleChange)
{
if (UseHalfFloatPrecision)
{
if (IsTeleportingNextFrame)
{
return Scale;
}
else
{
return HalfVectorScale.ToVector3();
}
}
else
{
return new Vector3(ScaleX, ScaleY, ScaleZ);
}
}
return Vector3.zero;
}
/// <summary>
/// The network tick that this state was sent by the authoritative instance.
/// </summary>
/// <returns><see cref="int"/></returns>
public int GetNetworkTick()
{
return NetworkTick;
}
internal HalfVector3 HalfEulerRotation;
/// <inheritdoc />
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
// Used to calculate the LastSerializedSize value
var positionStart = 0;
var isWriting = serializer.IsWriter;
if (isWriting)
{
m_Writer = serializer.GetFastBufferWriter();
positionStart = m_Writer.Position;
}
else
{
m_Reader = serializer.GetFastBufferReader();
positionStart = m_Reader.Position;
}
// Synchronize State Flags and Network Tick
{
if (isWriting)
{
if (UseUnreliableDeltas)
{
// If teleporting, synchronizing, doing an axial frame sync, or using half float precision and we collapsed a delta into the base position
if (IsTeleportingNextFrame || IsSynchronizing || UnreliableFrameSync || (UseHalfFloatPrecision && NetworkDeltaPosition.CollapsedDeltaIntoBase))
{
// Send the message reliably
ReliableSequenced = true;
}
else
{
ReliableSequenced = false;
}
}
else // If not using UseUnreliableDeltas, then always use reliable fragmented sequenced
{
ReliableSequenced = true;
}
BytePacker.WriteValueBitPacked(m_Writer, m_Bitset);
// We use network ticks as opposed to absolute time as the authoritative
// side updates on every new tick.
BytePacker.WriteValueBitPacked(m_Writer, NetworkTick);
}
else
{
ByteUnpacker.ReadValueBitPacked(m_Reader, out m_Bitset);
// We use network ticks as opposed to absolute time as the authoritative
// side updates on every new tick.
ByteUnpacker.ReadValueBitPacked(m_Reader, out NetworkTick);
}
}
// If debugging states and track by state identifier is enabled, serialize the current state identifier
if (TrackByStateId)
{
serializer.SerializeValue(ref StateId);
}
// Synchronize Position
if (HasPositionChange)
{
if (UseHalfFloatPrecision)
{
NetworkDeltaPosition.SynchronizeBase = SynchronizeBaseHalfFloat;
// Apply which axis should be updated for both write/read (teleporting, synchronizing, or just updating)
NetworkDeltaPosition.HalfVector3.AxisToSynchronize[0] = HasPositionX;
NetworkDeltaPosition.HalfVector3.AxisToSynchronize[1] = HasPositionY;
NetworkDeltaPosition.HalfVector3.AxisToSynchronize[2] = HasPositionZ;
if (IsTeleportingNextFrame)
{
// **Always use full precision when teleporting and UseHalfFloatPrecision is enabled**
serializer.SerializeValue(ref CurrentPosition);
// If we are synchronizing, then include the half vector position's delta offset
if (IsSynchronizing)
{
serializer.SerializeValue(ref DeltaPosition);
if (!isWriting)
{
NetworkDeltaPosition.NetworkTick = NetworkTick;
NetworkDeltaPosition.NetworkSerialize(serializer);
}
else
{
serializer.SerializeNetworkSerializable(ref NetworkDeltaPosition);
}
}
}
else
{
if (!isWriting)
{
NetworkDeltaPosition.NetworkTick = NetworkTick;
NetworkDeltaPosition.NetworkSerialize(serializer);
}
else
{
serializer.SerializeNetworkSerializable(ref NetworkDeltaPosition);
}
}
}
else // Full precision axis specific position synchronization
{
if (HasPositionX)
{
serializer.SerializeValue(ref PositionX);
}
if (HasPositionY)
{
serializer.SerializeValue(ref PositionY);
}
if (HasPositionZ)
{
serializer.SerializeValue(ref PositionZ);
}
}
}
// Synchronize Rotation
if (HasRotAngleChange)
{
if (QuaternionSync)
{
// Always use the full quaternion if teleporting
if (IsTeleportingNextFrame)
{
serializer.SerializeValue(ref Rotation);
}
else
{
// Use the quaternion compressor if enabled
if (QuaternionCompression)
{
if (isWriting)
{
QuaternionCompressed = QuaternionCompressor.CompressQuaternion(ref Rotation);
}
serializer.SerializeValue(ref QuaternionCompressed);
if (!isWriting)
{
QuaternionCompressor.DecompressQuaternion(ref Rotation, QuaternionCompressed);
}
}
else
{
if (UseHalfFloatPrecision)
{
if (isWriting)
{
HalfVectorRotation.UpdateFrom(ref Rotation);
}
serializer.SerializeNetworkSerializable(ref HalfVectorRotation);
if (!isWriting)
{
Rotation = HalfVectorRotation.ToQuaternion();
}
}
else
{
serializer.SerializeValue(ref Rotation);
}
}
}
}
else // Euler Rotation Synchronization
{
// Half float precision (full precision when teleporting)
if (UseHalfFloatPrecision && !IsTeleportingNextFrame)
{
if (HasRotAngleChange)
{
// Apply which axis should be updated for both write/read
HalfEulerRotation.AxisToSynchronize[0] = HasRotAngleX;
HalfEulerRotation.AxisToSynchronize[1] = HasRotAngleY;
HalfEulerRotation.AxisToSynchronize[2] = HasRotAngleZ;
if (isWriting)
{
HalfEulerRotation.Set(RotAngleX, RotAngleY, RotAngleZ);
}
serializer.SerializeValue(ref HalfEulerRotation);
if (!isWriting)
{
var eulerRotation = HalfEulerRotation.ToVector3();
if (HasRotAngleX)
{
RotAngleX = eulerRotation.x;
}
if (HasRotAngleY)
{
RotAngleY = eulerRotation.y;
}
if (HasRotAngleZ)
{
RotAngleZ = eulerRotation.z;
}
}
}
}
else // Full precision Euler
{
// RotAngle Values
if (HasRotAngleX)
{
serializer.SerializeValue(ref RotAngleX);
}
if (HasRotAngleY)
{
serializer.SerializeValue(ref RotAngleY);
}
if (HasRotAngleZ)
{
serializer.SerializeValue(ref RotAngleZ);
}
}
}
}
// Synchronize Scale
if (HasScaleChange)
{
// If we are teleporting (which includes synchronizing) and the associated NetworkObject has a parent
// then we want to serialize the LossyScale since NetworkObject spawn order is not guaranteed
if (IsTeleportingNextFrame && IsParented)
{
serializer.SerializeValue(ref LossyScale);
}
// Half precision scale synchronization
if (UseHalfFloatPrecision)
{
if (IsTeleportingNextFrame)
{
serializer.SerializeValue(ref Scale);
}
else
{
// Apply which axis should be updated for both write/read
HalfVectorScale.AxisToSynchronize[0] = HasScaleX;
HalfVectorScale.AxisToSynchronize[1] = HasScaleY;
HalfVectorScale.AxisToSynchronize[2] = HasScaleZ;
// For scale, when half precision is enabled we can still only send the axis with deltas
if (isWriting)
{
HalfVectorScale.Set(Scale[0], Scale[1], Scale[2]);
}
serializer.SerializeValue(ref HalfVectorScale);
if (!isWriting)
{
Scale = HalfVectorScale.ToVector3();
if (HasScaleX)
{
ScaleX = Scale.x;
}
if (HasScaleY)
{
ScaleY = Scale.y;
}
if (HasScaleZ)
{
ScaleZ = Scale.x;
}
}
}
}
else // Full precision scale synchronization
{
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 (!isWriting)
{
// Go ahead and mark the local state dirty
IsDirty = HasPositionChange || HasRotAngleChange || HasScaleChange;
LastSerializedSize = m_Reader.Position - positionStart;
}
else
{
LastSerializedSize = m_Writer.Position - positionStart;
}
}
}
#endregion
#region PROPERTIES AND GENERAL METHODS
/// <summary>
/// Used on the authority side only.
/// This is the current network tick and is set within <see cref="NetworkManager.NetworkUpdate(NetworkUpdateStage)"/>.
/// </summary>
internal static int CurrentTick;
/// <summary>
/// Pertains to Owner Authority and Interpolation<br />
/// When enabled (default), 1 additional tick is added to the total number of ticks used to calculate the tick latency ("ticks ago") as a time.
/// This calculated time value is passed into the respective <see cref="BufferedLinearInterpolator{T}"/> and used to determine if any pending
/// state updates in the queue should be processed.
/// The additional tick value is only applied when:
/// <list type="bullet">
/// <item><description>The <see cref="NetworkTransform"/> is using a <see cref="AuthorityModes.Owner"/> authority mode.</description></item>
/// <item><description>The non-authority instance is a client (i.e. not host or server).</description></item>
/// <item><description>The network topology being used is <see cref="NetworkTopologyTypes.ClientServer"/>.</description></item>
/// </list>
/// </summary>
/// <remarks>
/// When calculating the total tick latency as time value, the <see cref="NetworkTimeSystem.TickLatency"/> is added to the <see cref="InterpolationBufferTickOffset"/>
/// and if this property is enabled (and the conditions above are met) an additional tick is added to the final resultant value. <br />
/// Note: The reason behind this additional tick latency value is due to the 2 RTT timespan when a client state update is sent to the host or server (1 RTT)
/// and the host or server relays this state update to all non-authority instances (1 RTT).
/// </remarks>
public bool AutoOwnerAuthorityTickOffset = true;
/// <summary>
/// The different interpolation types used with <see cref="BufferedLinearInterpolator{T}"/> to help smooth interpolation results.
/// Interpolation types can be changed during runtime.
/// </summary>
public enum InterpolationTypes
{
/// <summary>
/// Legacy Lerp (original NGO lerping model)<br />
/// Uses a 1 to 2 phase lerp approach where:<br />
/// <list type="bullet">
/// <item><description>The first phase lerps from the previous state update value to the next state update value.</description></item>
/// <item><description>The second phase (optional) performs lerp smoothing where the current respective transform value is lerped towards the result of the first phase at a rate of delta time divided by the respective max interpolation time.</description></item>
/// </list>
/// !!! NOTE !!!<br />
/// The legacy lerp interpolation type does not use <see cref="NetworkTimeSystem.TickLatency"/> to determine the buffer depth. This is to preserve the same interpolation results when lerp smoothing is enabled.<br />
/// </summary>
/// <remarks>
/// For more information:<br />
/// <list type="bullet">
/// <item><term><see cref="PositionMaxInterpolationTime"/></term></item>
/// <item><term><see cref="PositionLerpSmoothing"/></term></item>
/// <item><term><see cref="RotationMaxInterpolationTime"/></term></item>
/// <item><term><see cref="RotationLerpSmoothing"/></term></item>
/// <item><term><see cref="ScaleMaxInterpolationTime"/></term></item>
/// <item><term><see cref="ScaleLerpSmoothing"/></term></item>
/// </list>
/// </remarks>
LegacyLerp,
/// <summary>
/// Lerp (maintains time to target when <see cref="InterpolationBufferTickOffset"/> under higher <see cref="NetworkTimeSystem.TickLatency"/> conditions) <br />
/// Uses a 1 to 2 phase interpolation approach where:<br />
/// <list type="bullet">
/// <item><description>The first phase lerps from the previous state update value to the next state update value.</description></item>
/// <item><description>The second phase (optional) performs lerp smoothing where the current respective transform value is lerped towards the result of the first phase at a rate of 1.0 minus the respective maximum interpolation time.</description></item>
/// </list>