-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPhysicsReplication.cpp
More file actions
3116 lines (2630 loc) · 149 KB
/
Copy pathPhysicsReplication.cpp
File metadata and controls
3116 lines (2630 loc) · 149 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
// Copyright Epic Games, Inc. All Rights Reserved.
/*=============================================================================
PhysicsReplication.cpp: Code for keeping replicated physics objects in sync with the server based on replicated server state data.
=============================================================================*/
#include "PhysicsReplication.h"
#include "PhysicsReplicationLOD.h"
#include "Physics/PhysicsReplicationQuantization.h"
#include "Engine/World.h"
#include "Components/SkeletalMeshComponent.h"
#include "DrawDebugHelpers.h"
#include "Physics/Experimental/PhysScene_Chaos.h"
#include "PhysicsEngine/PhysicsSettings.h"
#include "Chaos/PhysicsObjectInternalInterface.h"
#include "GameFramework/PlayerController.h"
#include "GameFramework/PlayerState.h"
#include "PhysicsProxy/SingleParticlePhysicsProxy.h"
#include "PBDRigidsSolver.h"
#include "Chaos/DebugDrawQueue.h"
#include "Chaos/Particles.h"
#include "Chaos/Island/IslandManager.h"
#include "RewindData.h"
namespace CharacterMovementCVars
{
extern int32 NetShowCorrections;
extern float NetCorrectionLifetime;
int32 SkipPhysicsReplication = 0;
static FAutoConsoleVariableRef CVarSkipPhysicsReplication(TEXT("p.SkipPhysicsReplication"), SkipPhysicsReplication, TEXT(""));
float NetPingExtrapolation = -1.0f;
static FAutoConsoleVariableRef CVarNetPingExtrapolation(TEXT("p.NetPingExtrapolation"), NetPingExtrapolation, TEXT(""));
float NetPingLimit = -1.f;
static FAutoConsoleVariableRef CVarNetPingLimit(TEXT("p.NetPingLimit"), NetPingLimit, TEXT(""));
float ErrorPerLinearDifference = -1.0f;
static FAutoConsoleVariableRef CVarErrorPerLinearDifference(TEXT("p.ErrorPerLinearDifference"), ErrorPerLinearDifference, TEXT(""));
float ErrorPerAngularDifference = -1.0f;
static FAutoConsoleVariableRef CVarErrorPerAngularDifference(TEXT("p.ErrorPerAngularDifference"), ErrorPerAngularDifference, TEXT(""));
float ErrorAccumulationSeconds = -1.0f;
static FAutoConsoleVariableRef CVarErrorAccumulation(TEXT("p.ErrorAccumulationSeconds"), ErrorAccumulationSeconds, TEXT(""));
float ErrorAccumulationDistanceSq = -1.0f;
static FAutoConsoleVariableRef CVarErrorAccumulationDistanceSq(TEXT("p.ErrorAccumulationDistanceSq"), ErrorAccumulationDistanceSq, TEXT(""));
float ErrorAccumulationSimilarity = -1.f;
static FAutoConsoleVariableRef CVarErrorAccumulationSimilarity(TEXT("p.ErrorAccumulationSimilarity"), ErrorAccumulationSimilarity, TEXT(""));
float MaxLinearHardSnapDistance = -1.f;
static FAutoConsoleVariableRef CVarMaxLinearHardSnapDistance(TEXT("p.MaxLinearHardSnapDistance"), MaxLinearHardSnapDistance, TEXT(""));
float MaxRestoredStateError = -1.0f;
static FAutoConsoleVariableRef CVarMaxRestoredStateError(TEXT("p.MaxRestoredStateError"), MaxRestoredStateError, TEXT(""));
float PositionLerp = -1.0f;
static FAutoConsoleVariableRef CVarLinSet(TEXT("p.PositionLerp"), PositionLerp, TEXT(""));
float LinearVelocityCoefficient = -1.0f;
static FAutoConsoleVariableRef CVarLinLerp(TEXT("p.LinearVelocityCoefficient"), LinearVelocityCoefficient, TEXT(""));
float AngleLerp = -1.0f;
static FAutoConsoleVariableRef CVarAngSet(TEXT("p.AngleLerp"), AngleLerp, TEXT(""));
float AngularVelocityCoefficient = -1.0f;
static FAutoConsoleVariableRef CVarAngLerp(TEXT("p.AngularVelocityCoefficient"), AngularVelocityCoefficient, TEXT(""));
int32 AlwaysHardSnap = 0;
static FAutoConsoleVariableRef CVarAlwaysHardSnap(TEXT("p.AlwaysHardSnap"), AlwaysHardSnap, TEXT(""));
int32 AlwaysResetPhysics = 0;
static FAutoConsoleVariableRef CVarAlwaysResetPhysics(TEXT("p.AlwaysResetPhysics"), AlwaysResetPhysics, TEXT(""));
int32 ApplyAsyncSleepState = 1;
static FAutoConsoleVariableRef CVarApplyAsyncSleepState(TEXT("p.ApplyAsyncSleepState"), ApplyAsyncSleepState, TEXT(""));
}
namespace RenderInterpolationCVars
{
bool bRenderInterpDebugDrawResimTrigger = false;
static FAutoConsoleVariableRef CVarRenderInterpDebugDrawResimTrigger(TEXT("p.RenderInterp.DebugDraw.ResimTrigger"), bRenderInterpDebugDrawResimTrigger, TEXT("Draw debug lines for physics render interpolation, also needs p.Chaos.DebugDraw.Enabled set"));
float RenderInterpDebugDrawResimBoxScale= 1.0f;
static FAutoConsoleVariableRef CVarRenderInterpDebugDrawResimBoxScale(TEXT("p.RenderInterp.DebugDraw.ResimBoxScale"), RenderInterpDebugDrawResimBoxScale, TEXT("Draw debug lines for physics render interpolation, also needs p.Chaos.DebugDraw.Enabled set"));
}
namespace PhysicsReplicationLODCVars
{
// Defined in PhysicsReplicationLOD.cpp.
extern int32 TransitionExtrapFrameMin;
extern float TransitionExtrapFraction;
extern bool bTransitionModeDebugLog;
}
namespace PhysicsReplicationCVars
{
int32 SkipSkeletalRepOptimization = 1;
static FAutoConsoleVariableRef CVarSkipSkeletalRepOptimization(TEXT("p.SkipSkeletalRepOptimization"), SkipSkeletalRepOptimization, TEXT("If true, we don't move the skeletal mesh component during replication. This is ok because the skeletal mesh already polls physx after its results"));
#if !UE_BUILD_SHIPPING
int32 LogPhysicsReplicationHardSnaps = 0;
static FAutoConsoleVariableRef CVarLogPhysicsReplicationHardSnaps(TEXT("p.LogPhysicsReplicationHardSnaps"), LogPhysicsReplicationHardSnaps, TEXT(""));
#endif
int32 EnableDefaultReplication = 0;
static FAutoConsoleVariableRef CVarEnableDefaultReplication(TEXT("np2.EnableDefaultReplication"), EnableDefaultReplication, TEXT("Enable default replication in the networked physics prediction flow."));
int32 DebugDrawShowRepMode = 0;
static FAutoConsoleVariableRef CVarPhysicsNetDebugDrawShowRepMode(TEXT("p.Net.DebugDraw.ShowRepMode"), DebugDrawShowRepMode, TEXT("Debug draw to show which physics replication mode is being used and where target states are being received. Green = Legacy Default, Light Blue = New Default, Yellow = Predictive Interpolation, Red = Resimulation, White = Something's Wrong. NOTE, Requires CVar p.Chaos.DebugDraw.Enabled 1"));
float DebugDrawLifeTime = 3.0f;
static FAutoConsoleVariableRef CVarPhysicsNetDebugDrawLifeTime(TEXT("p.Net.DebugDraw.LifeTime"), DebugDrawLifeTime, TEXT("Networked physics debug draw lifetime"));
namespace DefaultReplicationCVars
{
bool bHardsnapLegacyInPT = false;
static FAutoConsoleVariableRef CVarDefaultLegacyHardsnapInPT(TEXT("p.DefaultReplication.Legacy.HardsnapInPT"), bHardsnapLegacyInPT, TEXT("If default replication is used and it's running the legacy flow through Game Thread, allow hardsnapping to be performed on Physics Thread if async physics is enabled.."));
bool bCorrectConnectedBodies = false;
static FAutoConsoleVariableRef CVarDefaultCorrectConnectedBodies(TEXT("p.DefaultReplication.CorrectConnectedBodies"), bCorrectConnectedBodies, TEXT("When true, transform corrections will also apply to any connected physics object."));
bool bCorrectConnectedBodiesFriction = true;
static FAutoConsoleVariableRef CVarDefaultCorrectConnectedBodiesFriction(TEXT("p.DefaultReplication.CorrectConnectedBodiesFriction"), bCorrectConnectedBodiesFriction, TEXT("When true, transform correction on any connected physics object will also recalculate their friction."));
}
namespace ResimulationCVars
{
extern bool bApplyPredictiveInterpolationWhenBehindServer;
bool bResimulateSleepDesync = true;
static FAutoConsoleVariableRef CVarResimulateSleepDesync(TEXT("np2.Resim.ResimulateSleepDesync"), bResimulateSleepDesync, TEXT("Set if sleeping discrepancy between client and server should trigger a resimulation. Not enabling this can lead to client desyncing continuously if the server is sleeping and not sending data to client while the client object is still dynamic."));
bool bRuntimeCorrectionEnabled = false;
static FAutoConsoleVariableRef CVarResimRuntimeCorrectionEnabled(TEXT("np2.Resim.RuntimeCorrectionEnabled"), bRuntimeCorrectionEnabled, TEXT("Apply positional and rotational runtime corrections while within resim trigger distance."));
bool bRuntimeVelocityCorrection = false;
static FAutoConsoleVariableRef CVarResimRuntimeVelocityCorrection(TEXT("np2.Resim.RuntimeVelocityCorrection"), bRuntimeVelocityCorrection, TEXT("Apply linear and angular velocity corrections in runtime while within resim trigger distance. Used if RuntimeCorrectionEnabled is true."));
bool bRuntimeCorrectConnectedBodies = true;
static FAutoConsoleVariableRef CVarResimRuntimeCorrectConnectedBodies(TEXT("np2.Resim.RuntimeCorrectConnectedBodies"), bRuntimeCorrectConnectedBodies, TEXT("If true runtime position and rotation correction will also shift transform of any connected physics objects. Used if RuntimeCorrectionEnabled is true."));
bool bDisableReplicationOnInteraction = false;
static FAutoConsoleVariableRef CVarResimDisableReplicationOnInteraction(TEXT("np2.Resim.DisableReplicationOnInteraction"), bDisableReplicationOnInteraction, TEXT("If a resim object interacts with another object not running resimulation, deactivate that objects replication until interaction stops."));
bool bKeepResimStateForNonResimReplicatedObjects = false;
static FAutoConsoleVariableRef CVarResimKeepResimStateForNonResimReplicatedObjects(TEXT("np2.Resim.KeepResimStateForNonResimReplicatedObjects"), bKeepResimStateForNonResimReplicatedObjects, TEXT("When false, move objects back to their pre-resim state at the end of a resimulation if they are not set to use resimulation as replication mode."));
float PosStabilityMultiplier = 0.5f;
static FAutoConsoleVariableRef CVarResimPosStabilityMultiplier(TEXT("np2.Resim.PosStabilityMultiplier"), PosStabilityMultiplier, TEXT("Recommended range between 0.0-1.0. Lower value means more stable positional corrections."));
float RotStabilityMultiplier = 1.0f;
static FAutoConsoleVariableRef CVarResimRotStabilityMultiplier(TEXT("np2.Resim.RotStabilityMultiplier"), RotStabilityMultiplier, TEXT("Recommended range between 0.0-1.0. Lower value means more stable rotational corrections."));
float VelStabilityMultiplier = 0.5f;
static FAutoConsoleVariableRef CVarResimVelStabilityMultiplier(TEXT("np2.Resim.VelStabilityMultiplier"), VelStabilityMultiplier, TEXT("Recommended range between 0.0-1.0. Lower value means more stable linear velocity corrections."));
float AngVelStabilityMultiplier = 0.5f;
static FAutoConsoleVariableRef CVarResimAngVelStabilityMultiplier(TEXT("np2.Resim.AngVelStabilityMultiplier"), AngVelStabilityMultiplier, TEXT("Recommended range between 0.0-1.0. Lower value means more stable angular velocity corrections."));
bool bDrawDebug = false;
static FAutoConsoleVariableRef CVarResimDrawDebug(TEXT("np2.Resim.DrawDebug"), bDrawDebug, TEXT("Resimulation debug draw-calls"));
float LogOutOfBoundsTimeLimit = 5.0f;
static FAutoConsoleVariableRef CVarResimLogOutOfBoundsTimeLimit(TEXT("np2.Resim.LogOutOfBoundsTimeLimit"), LogOutOfBoundsTimeLimit, TEXT("Time that received targets needs to be within rewind bounds again before printing log that we are back in sync again. A new desync log will not be printed before an in-sync log has been printed."));
}
namespace PredictiveInterpolationCVars
{
float PosCorrectionTimeBase = 0.0f;
static FAutoConsoleVariableRef CVarPosCorrectionTimeBase(TEXT("np2.PredictiveInterpolation.PosCorrectionTimeBase"), PosCorrectionTimeBase, TEXT("Base time to correct positional offset over. RoundTripTime * PosCorrectionTimeMultiplier is added on top of this."));
float PosCorrectionTimeMin = 0.1f;
static FAutoConsoleVariableRef CVarPosCorrectionTimeMin(TEXT("np2.PredictiveInterpolation.PosCorrectionTimeMin"), PosCorrectionTimeMin, TEXT("Min time to correct positional offset over. DeltaSeconds is added on top of this."));
float PosCorrectionTimeMultiplier = 1.0f;
static FAutoConsoleVariableRef CVarPosCorrectionTimeMultiplier(TEXT("np2.PredictiveInterpolation.PosCorrectionTimeMultiplier"), PosCorrectionTimeMultiplier, TEXT("Multiplier to adjust how much of RoundTripTime to add to positional offset correction."));
float RotCorrectionTimeBase = 0.0f;
static FAutoConsoleVariableRef CVarRotCorrectionTimeBase(TEXT("np2.PredictiveInterpolation.RotCorrectionTimeBase"), RotCorrectionTimeBase, TEXT("Base time to correct rotational offset over. RoundTripTime * RotCorrectionTimeMultiplier is added on top of this."));
float RotCorrectionTimeMin = 0.1f;
static FAutoConsoleVariableRef CVarRotCorrectionTimeMin(TEXT("np2.PredictiveInterpolation.RotCorrectionTimeMin"), RotCorrectionTimeMin, TEXT("Min time to correct rotational offset over. DeltaSeconds is added on top of this."));
float RotCorrectionTimeMultiplier = 1.0f;
static FAutoConsoleVariableRef CVarRotCorrectionTimeMultiplier(TEXT("np2.PredictiveInterpolation.RotCorrectionTimeMultiplier"), RotCorrectionTimeMultiplier, TEXT("Multiplier to adjust how much of RoundTripTime to add to rotational offset correction."));
float PosInterpolationTimeMultiplier = 1.1f;
static FAutoConsoleVariableRef CVarInterpolationTimeMultiplier(TEXT("np2.PredictiveInterpolation.InterpolationTimeMultiplier"), PosInterpolationTimeMultiplier, TEXT("Multiplier to adjust the interpolation time which is based on the sendrate of state data from the server."));
float RotInterpolationTimeMultiplier = 1.25f;
static FAutoConsoleVariableRef CVarRotInterpolationTimeMultiplier(TEXT("np2.PredictiveInterpolation.RotInterpolationTimeMultiplier"), RotInterpolationTimeMultiplier, TEXT("Multiplier to adjust the rotational interpolation time which is based on the sendrate of state data from the server."));
float AverageReceiveIntervalSmoothing = 3.0f;
static FAutoConsoleVariableRef CVarAverageReceiveIntervalSmoothing(TEXT("np2.PredictiveInterpolation.AverageReceiveIntervalSmoothing"), AverageReceiveIntervalSmoothing, TEXT("Recommended range: 1.0 - 5.0. Higher value makes the average receive interval adjust itself slower, reducing spikes in InterpolationTime."));
float ExtrapolationTimeMultiplier = 3.0f;
static FAutoConsoleVariableRef CVarExtrapolationTimeMultiplier(TEXT("np2.PredictiveInterpolation.ExtrapolationTimeMultiplier"), ExtrapolationTimeMultiplier, TEXT("Multiplier to adjust the time to extrapolate the target forward over, the time is based on current send-rate."));
float ExtrapolationMinTime = 0.75f;
static FAutoConsoleVariableRef CVarExtrapolationMinTime(TEXT("np2.PredictiveInterpolation.ExtrapolationMinTime"), ExtrapolationMinTime, TEXT("Clamps minimum extrapolation time. Value in seconds. Disable minimum clamp by setting to 0."));
float MinExpectedDistanceCovered = 0.5f;
static FAutoConsoleVariableRef CVarMinExpectedDistanceCovered(TEXT("np2.PredictiveInterpolation.MinExpectedDistanceCovered"), MinExpectedDistanceCovered, TEXT("Value between 0-1, in percentage where 0.25 = 25%. How much of the expected distance based on replication velocity should the object have covered in a simulation tick to Not be considered stuck."));
float ErrorAccumulationDecreaseMultiplier = 0.5f;
static FAutoConsoleVariableRef CVarErrorAccumulationDecreaseMultiplier(TEXT("np2.PredictiveInterpolation.ErrorAccumulationDecreaseMultiplier"), ErrorAccumulationDecreaseMultiplier, TEXT("Multiplier to adjust how fast we decrease accumulated error time when we no longer accumulate error."));
float ErrorAccumulationSeconds = 3.0f;
static FAutoConsoleVariableRef CVarErrorAccumulationSeconds(TEXT("np2.PredictiveInterpolation.ErrorAccumulationSeconds"), ErrorAccumulationSeconds, TEXT("Perform a reposition if replication have not been able to cover the min expected distance towards the target for this amount of time."));
bool bDisableErrorVelocityLimits = false;
static FAutoConsoleVariableRef CVarDisableErrorVelocityLimits(TEXT("np2.PredictiveInterpolation.DisableErrorVelocityLimits"), bDisableErrorVelocityLimits, TEXT("Disable the velocity limit and allow error accumulation at any velocity."));
float ErrorAccLinVelMaxLimit = 50.0f;
static FAutoConsoleVariableRef CVarErrorAccLinVelMaxLimit(TEXT("np2.PredictiveInterpolation.ErrorAccLinVelMaxLimit"), ErrorAccLinVelMaxLimit, TEXT("If target velocity is below this limit we check for desync to trigger softsnap and accumulate time to build up to a hardsnap."));
float ErrorAccAngVelMaxLimit = 1.5f;
static FAutoConsoleVariableRef CVarErrorAccAngVelMaxLimit(TEXT("np2.PredictiveInterpolation.ErrorAccAngVelMaxLimit"), ErrorAccAngVelMaxLimit, TEXT("If target angular velocity (in radians) is below this limit we check for desync to trigger softsnap and accumulate time to build up to a hardsnap."));
float SoftSnapPosStrength = 0.5f;
static FAutoConsoleVariableRef CVarSoftSnapPosStrength(TEXT("np2.PredictiveInterpolation.SoftSnapPosStrength"), SoftSnapPosStrength, TEXT("Value in percent between 0.0 - 1.0 representing how much to softsnap each tick of the remaining positional distance."));
float SoftSnapRotStrength = 0.5f;
static FAutoConsoleVariableRef CVarSoftSnapRotStrength(TEXT("np2.PredictiveInterpolation.SoftSnapRotStrength"), SoftSnapRotStrength, TEXT("Value in percent between 0.0 - 1.0 representing how much to softsnap each tick of the remaining rotational distance."));
bool bSoftSnapToSource = false;
static FAutoConsoleVariableRef CVarSoftSnapToSource(TEXT("np2.PredictiveInterpolation.SoftSnapToSource"), bSoftSnapToSource, TEXT("If true, soft snap will be performed towards the source state of the current target instead of the predicted state of the current target."));
float EarlyOutDistanceSqr = 1.0f;
static FAutoConsoleVariableRef CVarEarlyOutDistanceSqr(TEXT("np2.PredictiveInterpolation.EarlyOutDistanceSqr"), EarlyOutDistanceSqr, TEXT("Squared value. If object is within this distance from the source target, early out from replication and apply sleep if replicated."));
float EarlyOutAngle = 1.5f;
static FAutoConsoleVariableRef CVarEarlyOutAngle(TEXT("np2.PredictiveInterpolation.EarlyOutAngle"), EarlyOutAngle, TEXT("If object is within this rotational angle (in degrees) from the source target, early out from replication and apply sleep if replicated."));
bool bEarlyOutWithVelocity = true;
static FAutoConsoleVariableRef CVarEarlyOutWithVelocity(TEXT("np2.PredictiveInterpolation.EarlyOutWithVelocity"), bEarlyOutWithVelocity, TEXT("If true, allow replication logic to early out if current velocities are driving replication well enough. If false, only early out if target velocity is zero."));
bool bSkipVelocityRepOnPosEarlyOut = true;
static FAutoConsoleVariableRef CVarSkipVelocityRepOnPosEarlyOut(TEXT("np2.PredictiveInterpolation.SkipVelocityRepOnPosEarlyOut"), bSkipVelocityRepOnPosEarlyOut, TEXT("If true, don't run linear velocity replication if position can early out but angular can't early out."));
bool bPostResimWaitForUpdate = false;
static FAutoConsoleVariableRef CVarPostResimWaitForUpdate(TEXT("np2.PredictiveInterpolation.PostResimWaitForUpdate"), bPostResimWaitForUpdate, TEXT("After a resimulation, wait for replicated states that correspond to post-resim state before processing replication again."));
bool bVelocityBased = true;
static FAutoConsoleVariableRef CVarVelocityBased(TEXT("np2.PredictiveInterpolation.VelocityBased"), bVelocityBased, TEXT("When true, predictive interpolation replication mode will move objects replicate by applying linear velocity and angular velocity. When false, objects will move by transform shifting towards the target state."));
bool bCorrectionAsVelocity = false;
static FAutoConsoleVariableRef CVarCorrectionAsVelocity(TEXT("np2.PredictiveInterpolation.CorrectionAsVelocity"), bCorrectionAsVelocity, TEXT("When true, predictive interpolation will apply positional and rotational offset correction as a velocity instead of as a transform shift."));
bool bCorrectConnectedBodies = false;
static FAutoConsoleVariableRef CVarCorrectConnectedBodies(TEXT("np2.PredictiveInterpolation.CorrectConnectedBodies"), bCorrectConnectedBodies, TEXT("When true, transform corrections will also apply to any connected physics object."));
bool bCorrectConnectedBodiesFriction = true;
static FAutoConsoleVariableRef CVarCorrectConnectedBodiesFriction(TEXT("np2.PredictiveInterpolation.CorrectConnectedBodiesFriction"), bCorrectConnectedBodiesFriction, TEXT("When true, transform correction on any connected physics object will also recalculate their friction."));
bool bSleepConnectedBodies = true;
static FAutoConsoleVariableRef CVarSleepConnectedBodies(TEXT("np2.PredictiveInterpolation.SleepConnectedBodies"), bSleepConnectedBodies, TEXT("When true, sleep state will be applied to any dynamic physics object connected to the replicated object."));
bool bKinematicPrediction = true;
static FAutoConsoleVariableRef CVarKinematicPrediction(TEXT("np2.PredictiveInterpolation.KinematicPrediction"), bKinematicPrediction, TEXT("When true, predictive interpolation will perform predictive movement instead of interpolation for kinematic objects."));
bool bKinematicHardSnap = false;
static FAutoConsoleVariableRef CVarKinematicHardSnap(TEXT("np2.PredictiveInterpolation.KinematicHardSnap"), bKinematicHardSnap, TEXT("When true, predictive interpolation will perform a hard snap for objects that are kinematic."));
bool bDisableSoftSnap = false;
static FAutoConsoleVariableRef CVarDisableSoftSnap(TEXT("np2.PredictiveInterpolation.DisableSoftSnap"), bDisableSoftSnap, TEXT("When true, predictive interpolation will not use softsnap to correct the replication with when velocity fails. Hardsnap will still eventually kick in if replication can't reach the target."));
bool bAlwaysHardSnap = false;
static FAutoConsoleVariableRef CVarAlwaysHardSnap(TEXT("np2.PredictiveInterpolation.AlwaysHardSnap"), bAlwaysHardSnap, TEXT("When true, predictive interpolation replication mode will always hard snap. Used as a backup measure"));
bool bSkipReplication = false;
static FAutoConsoleVariableRef CVarSkipReplication(TEXT("np2.PredictiveInterpolation.SkipReplication"), bSkipReplication, TEXT("When true, predictive interpolation is not applied anymore letting the object simulate freely instead"));
bool bDontClearTarget = false;
static FAutoConsoleVariableRef CVarDontClearTarget(TEXT("np2.PredictiveInterpolation.DontClearTarget"), bDontClearTarget, TEXT("When true, predictive interpolation will not lose track of the last replicated state after coming to rest."));
bool bDrawDebugTargets = false;
static FAutoConsoleVariableRef CVarDrawDebugTargets(TEXT("np2.PredictiveInterpolation.DrawDebugTargets"), bDrawDebugTargets, TEXT("Draw target states, color coded by which ServerFrame they originate from, replicated targets are large and extrapolated targets are small. There is a Z offset to the draw calls."));
bool bDrawDebugVectors = false;
static FAutoConsoleVariableRef CVarDrawDebugVectors(TEXT("np2.PredictiveInterpolation.DrawDebugVectors"), bDrawDebugVectors, TEXT("Draw replication vectors, target velocity, replicated velocity, velocity change between replication calls etc."));
float DrawDebugZOffset = 50.0f;
static FAutoConsoleVariableRef CVarDrawDebugZOffset(TEXT("np2.PredictiveInterpolation.DrawDebugZOffset"), DrawDebugZOffset, TEXT("Offset in Z axis for draw debug calls"));
float SleepSecondsClearTarget = 15.0f;
static FAutoConsoleVariableRef CVarSleepSecondsClearTarget(TEXT("np2.PredictiveInterpolation.SleepSecondsClearTarget"), SleepSecondsClearTarget, TEXT("Wait for the object to sleep for this many seconds before clearing the replication target, to ensure nothing wakes up the object just after it goes to sleep on the client."));
int32 TargetTickAlignmentClampMultiplier = 2;
static FAutoConsoleVariableRef CVarTargetTickAlignmentClampMultiplier(TEXT("np2.PredictiveInterpolation.TargetTickAlignmentClampMultiplier"), TargetTickAlignmentClampMultiplier, TEXT("Multiplier to adjust clamping of target alignment via TickCount. Multiplier is performed on AverageReceiveInterval."));
int32 TeleportDetectionEnabled = 1;
static FAutoConsoleVariableRef CVarTeleportDetectionEnabled(TEXT("np2.PredictiveInterpolation.TeleportDetection.Enabled"), TeleportDetectionEnabled, TEXT("Set to 1 to enable teleportation detection which hard snaps the replicated object if replication thinks a teleportation has happened. Disable by setting to 0 (or any other value currently, leaving room for adding more teleportation detection modes which will use incremental values)."));
float TeleportDetectionMinDistance = 200.0f;
static FAutoConsoleVariableRef CVarTeleportDetectionMinDistance(TEXT("np2.PredictiveInterpolation.TeleportDetection.MinDistance"), TeleportDetectionMinDistance, TEXT("Minimum positional distance between two received target states running teleportation detection."));
float TeleportDetectionVelocityMultiplier = 1.3f;
static FAutoConsoleVariableRef CVarTeleportDetectionVelocityMultiplier(TEXT("np2.PredictiveInterpolation.TeleportDetection.VelocityMultiplier"), TeleportDetectionVelocityMultiplier, TEXT("Multiplier to add leniency when checking if the previous or current velocity could cover the positional offset between previous and current target state. Higher value results in more lenient velocity comparison, i.e. less risk of triggering a hard snap when a teleport has not happened but also less likely to catch a teleport for objects that move while being teleported. Values under 1.0 are not recommended."));
}
}
namespace Chaos
{
extern CHAOS_API int32 RewindBeforeAdvance;
}
FPhysicsReplication::FPhysicsReplication(FPhysScene* InPhysicsScene)
: PhysScene(InPhysicsScene)
{
using namespace Chaos;
AsyncInput = nullptr;
PhysicsReplicationAsync = nullptr;
if (auto* Solver = PhysScene->GetSolver())
{
PhysicsReplicationAsync = Solver->CreateAndRegisterSimCallbackObject_External<FPhysicsReplicationAsync>();
PhysicsReplicationAsync->Setup(UPhysicsSettings::Get()->PhysicErrorCorrection);
}
}
FPhysicsReplication::~FPhysicsReplication()
{
if (PhysicsReplicationAsync)
{
if (auto* Solver = PhysScene->GetSolver())
{
Solver->UnregisterAndFreeSimCallbackObject_External(PhysicsReplicationAsync);
}
}
}
void FPhysicsReplication::SetReplicatedTarget(UPrimitiveComponent* Component, FName BoneName, const FRigidBodyState& ReplicatedTarget, int32 ServerFrame)
{
// If networked physics prediction is enabled, enforce the new physics replication flow via SetReplicatedTarget() using PhysicsObject instead of BodyInstance from BoneName.
AActor* Owner = Component->GetOwner();
if (Owner && (PhysicsReplicationCVars::EnableDefaultReplication || Owner->GetPhysicsReplicationMode() != EPhysicsReplicationMode::Default)) // For now, only opt in to the PhysicsObject flow if not using Default replication or if default is allowed via CVar.
{
const ENetRole OwnerRole = Owner->GetLocalRole();
const bool bIsSimulated = OwnerRole == ROLE_SimulatedProxy;
const bool bIsReplicatedAutonomous = OwnerRole == ROLE_AutonomousProxy && Component->bReplicatePhysicsToAutonomousProxy;
if (bIsSimulated || bIsReplicatedAutonomous)
{
Chaos::FConstPhysicsObjectHandle PhysicsObject = Component->GetPhysicsObjectByName(BoneName);
SetReplicatedTarget(PhysicsObject, ReplicatedTarget, ServerFrame, Owner->GetPhysicsReplicationMode());
return;
}
}
if (UWorld* OwningWorld = GetOwningWorld())
{
//TODO: there's a faster way to compare this
TWeakObjectPtr<UPrimitiveComponent> TargetKey(Component);
FReplicatedPhysicsTarget* Target = ComponentToTargets_DEPRECATED.Find(TargetKey);
if (!Target)
{
// First time we add a target, set it's previous and correction
// positions to the target position to avoid math with uninitialized
// memory.
Target = &ComponentToTargets_DEPRECATED.Add(TargetKey);
Target->PrevPos = ReplicatedTarget.Position;
Target->PrevPosTarget = ReplicatedTarget.Position;
}
Target->ServerFrame = ServerFrame;
Target->TargetState = ReplicatedTarget;
Target->BoneName = BoneName;
Target->ArrivedTimeSeconds = OwningWorld->GetTimeSeconds();
ensure(!Target->PrevPos.ContainsNaN());
ensure(!Target->PrevPosTarget.ContainsNaN());
ensure(!Target->TargetState.Position.ContainsNaN());
OnSetReplicatedTarget(Component, BoneName, ReplicatedTarget, ServerFrame, *Target);
}
}
void FPhysicsReplication::SetReplicatedTarget(Chaos::FConstPhysicsObjectHandle PhysicsObject, const FRigidBodyState& ReplicatedTarget, int32 ServerFrame, EPhysicsReplicationMode ReplicationMode)
{
if (!PhysicsObject)
{
return;
}
UWorld* OwningWorld = GetOwningWorld();
if (OwningWorld == nullptr)
{
return;
}
// TODO, Check if owning actor is ROLE_SimulatedProxy or ROLE_AutonomousProxy ?
FReplicatedPhysicsTarget Target(PhysicsObject);
Target.ReplicationMode = ReplicationMode;
Target.ServerFrame = ServerFrame;
Target.TargetState = ReplicatedTarget;
Target.ArrivedTimeSeconds = OwningWorld->GetTimeSeconds();
ensure(!Target.TargetState.Position.ContainsNaN());
ReplicatedTargetsQueue.Add(Target);
}
void FPhysicsReplication::RemoveReplicatedTarget(UPrimitiveComponent* Component)
{
if (Component == nullptr)
{
return;
}
// Remove from legacy flow
ComponentToTargets_DEPRECATED.Remove(Component);
// Remove from FPhysicsObject flow
Chaos::FConstPhysicsObjectHandle PhysicsObject = Component->GetPhysicsObjectByName(NAME_None);
RemoveReplicatedTarget(PhysicsObject);
}
void FPhysicsReplication::RemoveReplicatedTarget(Chaos::FConstPhysicsObjectHandle PhysicsObject)
{
// Remove from FPhysicsObject flow
if (!PhysicsObject)
{
return;
}
FReplicatedPhysicsTarget Target(PhysicsObject); // This creates a new but empty target and when it tries to update the current target in the async flow it will remove it from replication since it's empty.
ReplicatedTargetsQueue.Add(Target);
}
void FPhysicsReplication::Tick(float DeltaSeconds)
{
OnTick(DeltaSeconds, ComponentToTargets_DEPRECATED);
}
void FPhysicsReplication::OnTick(float DeltaSeconds, TMap<TWeakObjectPtr<UPrimitiveComponent>, FReplicatedPhysicsTarget>& ComponentsToTargets)
{
using namespace Chaos;
if (ShouldSkipPhysicsReplication())
{
return;
}
// Don't tick unless we have data to process
if (ComponentsToTargets.Num() == 0 && ReplicatedTargetsQueue.Num() == 0)
{
return;
}
NetworkPhysicsTickOffsetAssigned = false;
NetworkPhysicsTickOffset = 0; // LocalFrame = ServerFrame - NetworkPhysicsTickOffset;
if (UPhysicsSettings::Get()->PhysicsPrediction.bEnablePhysicsPrediction)
{
if (UWorld* World = GetOwningWorld())
{
if (APlayerController* PlayerController = World->GetFirstPlayerController())
{
NetworkPhysicsTickOffsetAssigned = PlayerController->GetNetworkPhysicsTickOffsetAssigned();
NetworkPhysicsTickOffset = PlayerController->GetNetworkPhysicsTickOffset();
}
}
}
const FRigidBodyErrorCorrection& PhysicErrorCorrection = UPhysicsSettings::Get()->PhysicErrorCorrection;
if (PhysicsReplicationAsync)
{
PrepareAsyncData_External(PhysicErrorCorrection);
if (ensure(AsyncInput))
{
AsyncInput->NetworkPhysicsTickOffsetAssigned = NetworkPhysicsTickOffsetAssigned;
AsyncInput->NetworkPhysicsTickOffset = NetworkPhysicsTickOffset;
}
}
// Get the ping between this PC & the server
const float LocalPing = GetLocalPing();
// BodyInstance replication flow, deprecated
for (auto Itr = ComponentsToTargets.CreateIterator(); Itr; ++Itr)
{
bool bRemoveItr = false;
if (UPrimitiveComponent* PrimComp = Itr.Key().Get())
{
if (PrimComp->GetAttachParent() == nullptr)
{
if (FBodyInstance* BI = PrimComp->GetBodyInstance(Itr.Value().BoneName))
{
FReplicatedPhysicsTarget& PhysicsTarget = Itr.Value();
FRigidBodyState& UpdatedState = PhysicsTarget.TargetState;
bool bUpdated = false;
if (AActor* OwningActor = PrimComp->GetOwner())
{
// Update actor replication settings overrides
SettingsCurrent = UNetworkPhysicsSettingsComponent::GetSettingsForActor(OwningActor);
const ENetRole OwnerRole = OwningActor->GetLocalRole();
const bool bIsSimulated = OwnerRole == ROLE_SimulatedProxy;
const bool bIsReplicatedAutonomous = OwnerRole == ROLE_AutonomousProxy && PrimComp->bReplicatePhysicsToAutonomousProxy;
if (bIsSimulated || bIsReplicatedAutonomous)
{
// Get the ping of this thing's owner. If nobody owns it,
// then it's server authoritative.
const float OwnerPing = GetOwnerPing(OwningActor, PhysicsTarget);
// Get the total ping - this approximates the time since the update was
// actually generated on the machine that is doing the authoritative sim.
// NOTE: We divide by 2 to approximate 1-way ping from 2-way ping.
const float PingSecondsOneWay = (LocalPing + OwnerPing) * 0.5f * 0.001f;
if (UpdatedState.Flags & ERigidBodyFlags::NeedsUpdate)
{
const int32 LocalFrame = PhysicsTarget.ServerFrame - NetworkPhysicsTickOffset;
const bool bRestoredState = ApplyRigidBodyState(DeltaSeconds, BI, PhysicsTarget, PhysicErrorCorrection, PingSecondsOneWay, LocalFrame, 0);
// Need to update the component to match new position.
if (PhysicsReplicationCVars::SkipSkeletalRepOptimization == 0 || Cast<USkeletalMeshComponent>(PrimComp) == nullptr) //simulated skeletal mesh does its own polling of physics results so we don't need to call this as it'll happen at the end of the physics sim
{
PrimComp->SyncComponentToRBPhysics();
}
if (bRestoredState)
{
bRemoveItr = true;
}
}
}
}
}
}
}
if (bRemoveItr)
{
OnTargetRestored(Itr.Key().Get(), Itr.Value());
PendingDeleteFromComponentsToTargets.Add(Itr.Key());
}
}
for (TWeakObjectPtr<UPrimitiveComponent>& PrimitiveComponent : PendingDeleteFromComponentsToTargets)
{
ComponentsToTargets.Remove(PrimitiveComponent);
}
PendingDeleteFromComponentsToTargets.Reset();
if (AsyncInput)
{
// PhysicsObject replication flow
for (FReplicatedPhysicsTarget& PhysicsTarget : ReplicatedTargetsQueue)
{
const float PingSecondsOneWay = LocalPing * 0.5f * 0.001f;
// Queue up the target state for async replication
FPhysicsRepAsyncInputData AsyncInputData(PhysicsTarget.PhysicsObject);
AsyncInputData.TargetState = PhysicsTarget.TargetState;
AsyncInputData.Proxy = nullptr;
AsyncInputData.RepMode = PhysicsTarget.ReplicationMode;
AsyncInputData.ServerFrame = PhysicsTarget.ServerFrame;
AsyncInputData.LatencyOneWay = PingSecondsOneWay;
AsyncInput->InputData.Add(AsyncInputData);
}
}
ReplicatedTargetsQueue.Reset();
AsyncInput = nullptr;
}
namespace
{
// Helper to return the deltas between current and target Position and Rotation
void ComputeDeltas(const FVector& CurrentPos, const FQuat& CurrentQuat, const FVector& TargetPos, const FQuat& TargetQuat, FVector& OutLinDiff, float& OutLinDiffSize,
FVector& OutAngDiffAxis, float& OutAngDiff, float& OutAngDiffSize)
{
OutLinDiff = TargetPos - CurrentPos;
OutLinDiffSize = OutLinDiff.Size();
const FQuat InvCurrentQuat = CurrentQuat.Inverse();
const FQuat DeltaQuat = TargetQuat * InvCurrentQuat;
DeltaQuat.ToAxisAndAngle(OutAngDiffAxis, OutAngDiff);
OutAngDiff = FMath::RadiansToDegrees(FMath::UnwindRadians(OutAngDiff));
OutAngDiffSize = FMath::Abs(OutAngDiff);
}
}
bool FPhysicsReplication::ApplyRigidBodyState(float DeltaSeconds, FBodyInstance* BI, FReplicatedPhysicsTarget& PhysicsTarget, const FRigidBodyErrorCorrection& ErrorCorrection, const float InPingSecondsOneWay, int32 LocalFrame, int32 NumPredictedFrames)
{
// Call into the old ApplyRigidBodyState function for now,
// Note that old ApplyRigidBodyState is overridden in other projects, so consider backwards compatible path
return ApplyRigidBodyState(DeltaSeconds, BI, PhysicsTarget, ErrorCorrection, InPingSecondsOneWay, nullptr);
}
bool FPhysicsReplication::ApplyRigidBodyState(float DeltaSeconds, FBodyInstance* BI, FReplicatedPhysicsTarget& PhysicsTarget, const FRigidBodyErrorCorrection& ErrorCorrection,
const float PingSecondsOneWay, bool* bDidHardSnap)
{
if (!BI->IsInstanceSimulatingPhysics())
{
return false;
}
//
// NOTES:
//
// The operation of this method has changed since 4.18.
//
// When a new remote physics state is received, this method will
// be called on tick until the local state is within an adequate
// tolerance of the new state.
//
// The received state is extrapolated based on ping, by some
// adjustable amount.
//
// A correction velocity is added new state's velocity, and assigned
// to the body. The correction velocity scales with the positional
// difference, so without the interference of external forces, this
// will result in an exponentially decaying correction.
//
// Generally it is not needed and will interrupt smoothness of
// the replication, but stronger corrections can be obtained by
// adjusting position lerping.
//
// If progress is not being made towards equilibrium, due to some
// divergence in physics states between the owning and local sims,
// an error value is accumulated, representing the amount of time
// spent in an unresolvable state.
//
// Once the error value has exceeded some threshold (0.5 seconds
// by default), a hard snap to the target physics state is applied.
//
bool bRestoredState = true;
const FRigidBodyState NewState = PhysicsTarget.TargetState;
const float NewQuatSizeSqr = NewState.Quaternion.SizeSquared();
// failure cases
if (!BI->IsInstanceSimulatingPhysics())
{
UE_LOGF(LogPhysics, Warning, "Physics replicating on non-simulated body. (%ls)", *BI->GetBodyDebugName());
return bRestoredState;
}
else if (NewQuatSizeSqr < UE_KINDA_SMALL_NUMBER)
{
UE_LOGF(LogPhysics, Warning, "Invalid zero quaternion set for body. (%ls)", *BI->GetBodyDebugName());
return bRestoredState;
}
else if (FMath::Abs(NewQuatSizeSqr - 1.f) > UE_KINDA_SMALL_NUMBER)
{
UE_LOGF(LogPhysics, Warning, "Quaternion (%f %f %f %f) with non-unit magnitude detected. (%ls)",
NewState.Quaternion.X, NewState.Quaternion.Y, NewState.Quaternion.Z, NewState.Quaternion.W, *BI->GetBodyDebugName());
return bRestoredState;
}
// Grab configuration variables from engine config or from CVars if overriding is turned on.
const float NetPingExtrapolation = CharacterMovementCVars::NetPingExtrapolation >= 0.0f ? CharacterMovementCVars::NetPingExtrapolation : ErrorCorrection.PingExtrapolation;
const float NetPingLimit = CharacterMovementCVars::NetPingLimit > 0.0f ? CharacterMovementCVars::NetPingLimit : ErrorCorrection.PingLimit;
const float ErrorPerLinearDiff = CharacterMovementCVars::ErrorPerLinearDifference >= 0.0f ? CharacterMovementCVars::ErrorPerLinearDifference : ErrorCorrection.ErrorPerLinearDifference;
const float ErrorPerAngularDiff = CharacterMovementCVars::ErrorPerAngularDifference >= 0.0f ? CharacterMovementCVars::ErrorPerAngularDifference : ErrorCorrection.ErrorPerAngularDifference;
const float MaxRestoredStateError = CharacterMovementCVars::MaxRestoredStateError >= 0.0f ? CharacterMovementCVars::MaxRestoredStateError : ErrorCorrection.MaxRestoredStateError;
const float ErrorAccumulationSeconds = CharacterMovementCVars::ErrorAccumulationSeconds >= 0.0f ? CharacterMovementCVars::ErrorAccumulationSeconds : ErrorCorrection.ErrorAccumulationSeconds;
const float ErrorAccumulationDistanceSq = CharacterMovementCVars::ErrorAccumulationDistanceSq >= 0.0f ? CharacterMovementCVars::ErrorAccumulationDistanceSq : ErrorCorrection.ErrorAccumulationDistanceSq;
const float ErrorAccumulationSimilarity = CharacterMovementCVars::ErrorAccumulationSimilarity >= 0.0f ? CharacterMovementCVars::ErrorAccumulationSimilarity : ErrorCorrection.ErrorAccumulationSimilarity;
const float PositionLerp = CharacterMovementCVars::PositionLerp >= 0.0f ? CharacterMovementCVars::PositionLerp : ErrorCorrection.PositionLerp;
const float LinearVelocityCoefficient = CharacterMovementCVars::LinearVelocityCoefficient >= 0.0f ? CharacterMovementCVars::LinearVelocityCoefficient : ErrorCorrection.LinearVelocityCoefficient;
const float AngleLerp = CharacterMovementCVars::AngleLerp >= 0.0f ? CharacterMovementCVars::AngleLerp : ErrorCorrection.AngleLerp;
const float AngularVelocityCoefficient = CharacterMovementCVars::AngularVelocityCoefficient >= 0.0f ? CharacterMovementCVars::AngularVelocityCoefficient : ErrorCorrection.AngularVelocityCoefficient;
float MaxLinearHardSnapDistance = CharacterMovementCVars::MaxLinearHardSnapDistance >= 0.f ? CharacterMovementCVars::MaxLinearHardSnapDistance : ErrorCorrection.MaxLinearHardSnapDistance;
bool bHardsnapLegacyInPT = PhysicsReplicationCVars::DefaultReplicationCVars::bHardsnapLegacyInPT;
bool bCorrectConnectedBodies = PhysicsReplicationCVars::DefaultReplicationCVars::bCorrectConnectedBodies;
bool bCorrectConnectedBodiesFriction = PhysicsReplicationCVars::DefaultReplicationCVars::bCorrectConnectedBodiesFriction;
// Assign per-actor settings from NetworkPhysicSettingsComponent if this actor has one
if (SettingsCurrent.IsValid())
{
const FNetworkPhysicsSettingsData& SettingsData = SettingsCurrent.Pin()->GetSettings();
MaxLinearHardSnapDistance = SettingsData.DefaultReplicationSettings.GetMaxLinearHardSnapDistance(MaxLinearHardSnapDistance);
bHardsnapLegacyInPT = SettingsData.DefaultReplicationSettings.GetHardsnapDefaultLegacyInPT();
bCorrectConnectedBodies = SettingsData.DefaultReplicationSettings.GetCorrectConnectedBodies();
bCorrectConnectedBodiesFriction = SettingsData.DefaultReplicationSettings.GetCorrectConnectedBodiesFriction();
}
// Get Current state
FRigidBodyState CurrentState;
BI->GetRigidBodyState(CurrentState);
/////// EXTRAPOLATE APPROXIMATE TARGET VALUES ///////
// Starting from the last known authoritative position, and
// extrapolate an approximation using the last known velocity
// and ping.
const float PingSeconds = FMath::Clamp(PingSecondsOneWay, 0.f, NetPingLimit);
const float ExtrapolationDeltaSeconds = PingSeconds * NetPingExtrapolation;
const FVector ExtrapolationDeltaPos = NewState.LinVel * ExtrapolationDeltaSeconds;
const FVector_NetQuantize100 TargetPos = NewState.Position + ExtrapolationDeltaPos;
float NewStateAngVel;
FVector NewStateAngVelAxis;
NewState.AngVel.FVector::ToDirectionAndLength(NewStateAngVelAxis, NewStateAngVel);
NewStateAngVel = FMath::DegreesToRadians(NewStateAngVel);
const FQuat ExtrapolationDeltaQuaternion = FQuat(NewStateAngVelAxis, NewStateAngVel * ExtrapolationDeltaSeconds);
FQuat TargetQuat = ExtrapolationDeltaQuaternion * NewState.Quaternion;
/////// COMPUTE DIFFERENCES ///////
FVector LinDiff;
float LinDiffSize;
FVector AngDiffAxis;
float AngDiff;
float AngDiffSize;
ComputeDeltas(CurrentState.Position, CurrentState.Quaternion, TargetPos, TargetQuat, LinDiff, LinDiffSize, AngDiffAxis, AngDiff, AngDiffSize);
/////// ACCUMULATE ERROR IF NOT APPROACHING SOLUTION ///////
// Store sleeping state
const bool bShouldSleep = (NewState.Flags & ERigidBodyFlags::Sleeping) != 0;
const bool bWasAwake = BI->IsInstanceAwake();
const bool bAutoWake = false;
const float Error = (LinDiffSize * ErrorPerLinearDiff) + (AngDiffSize * ErrorPerAngularDiff);
bRestoredState = Error < MaxRestoredStateError;
if (bRestoredState)
{
PhysicsTarget.AccumulatedErrorSeconds = 0.0f;
}
else
{
//
// The heuristic for error accumulation here is:
// 1. Did the physics tick from the previous step fail to
// move the body towards a resolved position?
// 2. Was the linear error in the same direction as the
// previous frame?
// 3. Is the linear error large enough to accumulate error?
//
// If these conditions are met, then "error" time will accumulate.
// Once error has accumulated for a certain number of seconds,
// a hard-snap to the target will be performed.
//
// TODO: Rotation while moving linearly can still mess up this
// heuristic. We need to account for it.
//
// Project the change in position from the previous tick onto the
// linear error from the previous tick. This value roughly represents
// how much correction was performed over the previous physics tick.
const float PrevProgress = FVector::DotProduct(
FVector(CurrentState.Position) - PhysicsTarget.PrevPos,
(PhysicsTarget.PrevPosTarget - PhysicsTarget.PrevPos).GetSafeNormal());
// Project the current linear error onto the linear error from the
// previous tick. This value roughly represents how little the direction
// of the linear error state has changed, and how big the error is.
const float PrevSimilarity = FVector::DotProduct(
TargetPos - FVector(CurrentState.Position),
PhysicsTarget.PrevPosTarget - PhysicsTarget.PrevPos);
// If the conditions from the heuristic outlined above are met, accumulate
// error. Otherwise, reduce it.
if (PrevProgress < ErrorAccumulationDistanceSq &&
PrevSimilarity > ErrorAccumulationSimilarity)
{
PhysicsTarget.AccumulatedErrorSeconds += DeltaSeconds;
}
else
{
PhysicsTarget.AccumulatedErrorSeconds = FMath::Max(PhysicsTarget.AccumulatedErrorSeconds - DeltaSeconds, 0.0f);
}
// Hard snap if error accumulation or linear error is big enough, and clear the error accumulator.
const bool bHardSnap =
LinDiffSize > MaxLinearHardSnapDistance ||
PhysicsTarget.AccumulatedErrorSeconds > ErrorAccumulationSeconds ||
CharacterMovementCVars::AlwaysHardSnap;
const FTransform IdealWorldTM(TargetQuat, TargetPos);
if (bHardSnap)
{
#if !UE_BUILD_SHIPPING
if (PhysicsReplicationCVars::LogPhysicsReplicationHardSnaps && GetOwningWorld())
{
UE_LOGF(LogTemp, Warning, "Simulated HARD SNAP - \nCurrent Pos - %ls, Target Pos - %ls\n CurrentState.LinVel - %ls, New Lin Vel - %ls\nTarget Extrapolation Delta - %ls, Is Replay? - %d, Is Asleep - %d, Prev Progress - %f, Prev Similarity - %f",
*CurrentState.Position.ToString(), *TargetPos.ToString(), *CurrentState.LinVel.ToString(), *NewState.LinVel.ToString(),
*ExtrapolationDeltaPos.ToString(), GetOwningWorld()->IsPlayingReplay(), !BI->IsInstanceAwake(), PrevProgress, PrevSimilarity);
if (bDidHardSnap)
{
*bDidHardSnap = true;
}
if (LinDiffSize > MaxLinearHardSnapDistance)
{
UE_LOGF(LogTemp, Warning, "Hard snap due to linear difference error");
}
else
{
UE_LOGF(LogTemp, Warning, "Hard snap due to accumulated error")
}
}
#endif
// Too much error so just snap state here and be done with it
PhysicsTarget.AccumulatedErrorSeconds = 0.0f;
bRestoredState = true;
// Hardsnap in physics thread
bool bPTHardSnapSuccess = false;
if (PhysicsReplicationAsync != nullptr)
{
if (bHardsnapLegacyInPT)
{
if (Chaos::FSingleParticlePhysicsProxy* Proxy = static_cast<Chaos::FSingleParticlePhysicsProxy*>(BI->GetPhysicsActor()))
{
if (Chaos::FPBDRigidsSolver* Solver = Proxy->GetSolver<Chaos::FPBDRigidsSolver>())
{
Solver->EnqueueCommandImmediate([Solver, Proxy, IdealWorldTM, NewState, bCorrectConnectedBodies, bCorrectConnectedBodiesFriction]()
{
Chaos::FRigidBodyHandle_Internal* Handle = Proxy->GetPhysicsThreadAPI();
// Set XRVW to hard snap dynamic object and force recalculation of friction
Solver->GetEvolution()->ApplyParticleTransformCorrection(Proxy->GetHandle_LowLevel(), IdealWorldTM.GetLocation(), IdealWorldTM.GetRotation(), bCorrectConnectedBodies, bCorrectConnectedBodiesFriction);
Handle->SetV(NewState.LinVel);
Handle->SetW(FMath::DegreesToRadians(NewState.AngVel));
});
bPTHardSnapSuccess = true;
}
}
}
}
if (!bPTHardSnapSuccess)
{
BI->SetBodyTransform(IdealWorldTM, ETeleportType::ResetPhysics, bAutoWake);
// Set the new velocities
BI->SetLinearVelocity(NewState.LinVel, false, bAutoWake);
BI->SetAngularVelocityInRadians(FMath::DegreesToRadians(NewState.AngVel), false, bAutoWake);
}
}
else
{
// Small enough error to interpolate
if (PhysicsReplicationAsync == nullptr) //sync case
{
const FVector NewLinVel = FVector(NewState.LinVel) + (LinDiff * LinearVelocityCoefficient * DeltaSeconds);
const FVector NewAngVel = FVector(NewState.AngVel) + (AngDiffAxis * AngDiff * AngularVelocityCoefficient * DeltaSeconds);
const FVector NewPos = FMath::Lerp(FVector(CurrentState.Position), FVector(TargetPos), PositionLerp);
const FQuat NewAng = FQuat::Slerp(CurrentState.Quaternion, TargetQuat, AngleLerp);
BI->SetBodyTransform(FTransform(NewAng, NewPos), ETeleportType::ResetPhysics);
BI->SetLinearVelocity(NewLinVel, false);
BI->SetAngularVelocityInRadians(FMath::DegreesToRadians(NewAngVel), false);
}
else
{
//If async is used, enqueue for callback
FPhysicsRepAsyncInputData AsyncInputData(nullptr);
AsyncInputData.TargetState = NewState;
AsyncInputData.TargetState.Position = IdealWorldTM.GetLocation();
AsyncInputData.TargetState.Quaternion = IdealWorldTM.GetRotation();
AsyncInputData.Proxy = static_cast<Chaos::FSingleParticlePhysicsProxy*>(BI->GetPhysicsActor());
AsyncInputData.ErrorCorrection = { ErrorCorrection.LinearVelocityCoefficient, ErrorCorrection.AngularVelocityCoefficient, ErrorCorrection.PositionLerp, ErrorCorrection.AngleLerp };
AsyncInputData.LatencyOneWay = PingSeconds;
AsyncInput->InputData.Add(AsyncInputData);
}
}
// Should we show the async part?
#if !UE_BUILD_SHIPPING
if (CharacterMovementCVars::NetShowCorrections != 0)
{
PhysicsTarget.ErrorHistory.bAutoAdjustMinMax = false;
PhysicsTarget.ErrorHistory.MinValue = 0.0f;
PhysicsTarget.ErrorHistory.MaxValue = 1.0f;
PhysicsTarget.ErrorHistory.AddSample(PhysicsTarget.AccumulatedErrorSeconds / ErrorAccumulationSeconds);
if (UWorld* OwningWorld = GetOwningWorld())
{
FColor Color = FColor::White;
DrawDebugDirectionalArrow(OwningWorld, CurrentState.Position, TargetPos, 5.0f, Color, false, CharacterMovementCVars::NetCorrectionLifetime, 0, 1.5f);
DrawDebugFloatHistory(*OwningWorld, PhysicsTarget.ErrorHistory, CurrentState.Position + FVector(0.0f, 0.0f, 100.0f), FVector2D(100.0f, 50.0f), FColor::White, false, 0, -1);
}
}
#endif
}
/////// SLEEP UPDATE ///////
if (bShouldSleep)
{
// In the async case, we apply sleep state in ApplyAsyncDesiredState
if (PhysicsReplicationAsync == nullptr)
{
BI->PutInstanceToSleep();
}
}
PhysicsTarget.PrevPosTarget = TargetPos;
PhysicsTarget.PrevPos = FVector(CurrentState.Position);
return bRestoredState;
}
void FPhysicsReplication::PrepareAsyncData_External(const FRigidBodyErrorCorrection& ErrorCorrection)
{
//todo move this logic into a common function?
const float PositionLerp = CharacterMovementCVars::PositionLerp >= 0.0f ? CharacterMovementCVars::PositionLerp : ErrorCorrection.PositionLerp;
const float LinearVelocityCoefficient = CharacterMovementCVars::LinearVelocityCoefficient >= 0.0f ? CharacterMovementCVars::LinearVelocityCoefficient : ErrorCorrection.LinearVelocityCoefficient;
const float AngleLerp = CharacterMovementCVars::AngleLerp >= 0.0f ? CharacterMovementCVars::AngleLerp : ErrorCorrection.AngleLerp;
const float AngularVelocityCoefficient = CharacterMovementCVars::AngularVelocityCoefficient >= 0.0f ? CharacterMovementCVars::AngularVelocityCoefficient : ErrorCorrection.AngularVelocityCoefficient;
AsyncInput = PhysicsReplicationAsync->GetProducerInputData_External();
AsyncInput->ErrorCorrection.PositionLerp = PositionLerp;
AsyncInput->ErrorCorrection.AngleLerp = AngleLerp;
AsyncInput->ErrorCorrection.LinearVelocityCoefficient = LinearVelocityCoefficient;
AsyncInput->ErrorCorrection.AngularVelocityCoefficient = AngularVelocityCoefficient;
}
#pragma region FPhysicsReplicationAsync
void FPhysicsReplicationAsync::OnPhysicsObjectUnregistered_Internal(Chaos::FConstPhysicsObjectHandle PhysicsObject)
{
RemoveObjectFromReplication(PhysicsObject);
// Only clear Settings when PhysicsObject unregister (not when it stops replicating, hence why it's not baked into RemoveObjectFromReplication())
ObjectToSettings.Remove(PhysicsObject);
RemoveParticleSimDecaySettings(PhysicsObject);
Chaos::FReadPhysicsObjectInterface_Internal Interface = Chaos::FPhysicsObjectInternalInterface::GetRead();
if (Chaos::FGeometryParticleHandle* Handle = Interface.GetParticle(PhysicsObject))
{
if (Chaos::FPhysicsSolverBase* SolverBase = GetSolver())
{
if (Chaos::FRewindData* RewindData = SolverBase->GetRewindData())
{
// Stop forcing resim as follower
RewindData->ForceResimAsFollower(Handle, false);
}
}
}
}
void FPhysicsReplicationAsync::RegisterSettings(Chaos::FConstPhysicsObjectHandle PhysicsObject, TWeakPtr<const FNetworkPhysicsSettingsData> InSettings)
{
if (PhysicsObject != nullptr)
{
TWeakPtr<const FNetworkPhysicsSettingsData>& Settings = ObjectToSettings.FindOrAdd(PhysicsObject);
Settings = InSettings;
}
}
TWeakPtr<FParticleSimDecaySettings> FPhysicsReplicationAsync::FindOrAddParticleSimDecaySettings(Chaos::FConstPhysicsObjectHandle PhysicsObject)
{
if (PhysicsObject == nullptr)
{
return nullptr;
}
// Caller writes directly into the returned element
TSharedPtr<FParticleSimDecaySettings>& Entry = ParticleSimDecaySettings.FindOrAdd(PhysicsObject);
if (!Entry.IsValid())
{
Entry = MakeShared<FParticleSimDecaySettings>();
}
return Entry.ToWeakPtr();
}
void FPhysicsReplicationAsync::RemoveParticleSimDecaySettings(Chaos::FConstPhysicsObjectHandle PhysicsObject)
{
ParticleSimDecaySettings.Remove(PhysicsObject);
}
void FPhysicsReplicationAsync::FetchObjectSettings(Chaos::FConstPhysicsObjectHandle PhysicsObject)
{
TWeakPtr<const FNetworkPhysicsSettingsData>* CustomSettings = ObjectToSettings.Find(PhysicsObject);
SettingsCurrent = (CustomSettings && (*CustomSettings).IsValid()) ? *(*CustomSettings).Pin().Get() : SettingsDefault;
}
void FPhysicsReplicationAsync::OnPostInitialize_Internal()
{
Chaos::FPBDRigidsSolver* RigidsSolver = static_cast<Chaos::FPBDRigidsSolver*>(GetSolver());
if (RigidsSolver == nullptr)
{
return;
}
RigidsSolver->SetPhysicsReplication_Internal(this);
}
void FPhysicsReplicationAsync::AddResimulationRequest_Internal(const float DeltaSeconds)
{
//NOTE: This gets called if Chaos::RewindBeforeAdvance != 0 before the current physics frame execute any logic or callbacks
if (FPhysicsReplication::ShouldSkipPhysicsReplication())
{
return;