forked from perilouswithadollarsign/cstrike15_src
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsoftbody.cpp
4003 lines (3475 loc) · 138 KB
/
softbody.cpp
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 © Valve Corporation, All rights reserved. ============//
#include "softbody.h"
#include "vstdlib/jobthread.h"
#include "tier1/fmtstr.h"
#include "tier1/utlbuffer.h"
#include "mathlib/femodel.h"
#include "mathlib/femodel.inl"
#include "tier1/fmtstr.h"
#include "modellib/clothhelpers.h"
#include "mathlib/femodeldesc.h"
#include "mathlib/softbodyenvironment.h"
#include "tier0/miniprofiler.h"
#include "bitvec.h"
#include "filesystem.h"
#include "mathlib/dynamictree.h"
#include "engine/ivdebugoverlay.h"
#include "mathlib/vertexcolor.h"
#include "rubikon/param_types.h"
#include "materialsystem/imesh.h"
#include "mathlib/softbody.inl"
// #include "rnthread.h"
// #include "rnsimd.h"
// #include "modellib/model.h"
// #include "broadphase.h"
// #include "dynamictree.h"
// #include "sphereshape.h"
// #include "capsuleshape.h"
// #include "hullshape.h"
// #include "meshshape.h"
extern const CPUInformation &cpuInfo;
DECLARE_LOGGING_CHANNEL( LOG_PHYSICS );
enum ClothDebugFlagEnum_t
{
CLOTH_DEBUG_SIM_ANIM_POS = 1 << 0, // GetParticleTransforms() returns sim pos = anim pos
CLOTH_DEBUG_SIM_ANIM_ROT = 1 << 1,
CLOTH_DEBUG_SNAP_TO_ANIM = 1 << 2, // copy positions from GetAnim() in Post()
CLOTH_SKIP_FILTER_TRANSFORMS = 1 << 3,
CLOTH_FORCE_INTERPOLATION_1 = 1 << 4
};
const int g_nClothDebug = 0;
// the verlet integrator has some root differences from the explicit Euler that the old cloth system employs.
// The factor of 2 here reflects one of those (at^2/2 doesn't work the same for the implicit integrator)
const float g_flClothAttrVel = 2; // the 2nd substep in Source1 (SysIterateOverTime) is made with 1/2 timestep and the force computed from animation force attraction is double of the intended...
const float g_flClothAttrPos = 1;
const float g_flClothDampingMultiplier = 1;
float g_flClothNodeVelocityLimit = 1000000;
float g_flClothGroundPlaneThickness = 3;
static const float g_flStickyDist = 2.0f;
static const float g_flRopeSize = 20.0f;
static const float g_flTeleportDeltaSq = ( 200.0f * 200.0f );
static const float g_flNoTeleportDeltaSq = ( 100.0f * 100.0f );
MPROF_NODE( SoftbodyFilterTransforms, "Softbody:FilterTransforms", "Physics" );
MPROF_NODE( SoftbodyDraw, "Softbody:Draw", "Physics" );
MPROF_NODE( SoftbodyStep, "Softbody:Step", "Physics" );
MPROF_NODE( SoftbodyStepIntegrate, "Softbody:Step/Integrate", "Physics" )
MPROF_NODE( SoftbodyStepPredict, "Softbody:Step/Predict", "Physics" )
MPROF_NODE( SoftbodyStepCollide, "Softbody:Step/Collide", "Physics" )
MPROF_NODE( SoftbodyStepIterate, "Softbody:Step/Iterate", "Physics" )
MPROF_NODE( SoftbodyStepPost, "Softbody:Step/Post", "Physics" )
MPROF_NODE( FeRelaxRods, "Softbody:FeRelaxRods", "Physics" );
MPROF_NODE( FeRelaxQuads, "Softbody:FeRelaxQuads", "Physics" );
MPROF_NODE( SoftbodyStepCollideCompute, "Softbody:Step/Collide/Compute", "Physics" );
MPROF_NODE( SoftbodyStepCollideComputeOuter, "Softbody:Step/Collide/ComputeOuter", "Physics" );
//MPROF_NODE( SoftbodyTreeBounds, "Softbody:ComputeTreeBounds", "Physics" );
float g_flClothGuardThreshold = 1000;
int g_nClothWatch = 1;
class CRnSoftbodyChangeGuard
{
const CSoftbody *m_pSoftbody;
const char *m_pName;
AABB_t m_Box0, m_Box1;
public:
static float Difference( const AABB_t &a, const AABB_t &b )
{
return ( a.m_vMinBounds - b.m_vMinBounds ).Length() + ( a.m_vMaxBounds - b.m_vMaxBounds ).Length();
}
CRnSoftbodyChangeGuard( const CSoftbody *pSoftbody, const char *pName )
{
m_pSoftbody = pSoftbody;
m_pName = pName;
m_Box0 = GetAabb( pSoftbody->GetNodePositions( 0 ), pSoftbody->GetNodeCount() );
m_Box1 = GetAabb( pSoftbody->GetNodePositions( 1 ), pSoftbody->GetNodeCount() );
}
~CRnSoftbodyChangeGuard()
{
AABB_t box0 = GetAabb( m_pSoftbody->GetNodePositions( 0 ), m_pSoftbody->GetNodeCount() );
AABB_t box1 = GetAabb( m_pSoftbody->GetNodePositions( 1 ), m_pSoftbody->GetNodeCount() );
float flMove = Difference( m_Box0, box0 ) + Difference( m_Box1, box1 );
if ( flMove > g_flClothGuardThreshold )
{
if ( m_pSoftbody->GetIndexInWorld() == g_nClothWatch )
{
Log_Msg( LOG_PHYSICS, "Cloth %d %s in %s changed %g: from {%.0f,%.0f}\xB1{%.0f,%.0f} to {%.0f,%.0f}\xB1{%.0f,%.0f}\n", m_pSoftbody->m_nIndexInWorld, m_pSoftbody->m_DebugName.GetSafe(), m_pName, flMove,
box0.GetCenter().x, box0.GetCenter().y, box0.GetSize().x, box0.GetSize().y,
box1.GetCenter().x, box1.GetCenter().y, box1.GetSize().x, box1.GetSize().y
);
}
}
}
};
#if defined(_DEBUG)
#define CHANGE_GUARD() //CRnSoftbodyChangeGuard changeGuard( this, __FUNCTION__)
#else
#define CHANGE_GUARD()
#endif
CSoftbody::CSoftbody( void )
{
// this constructor prepares softbody for a snoop or deserialization
m_pEnvironment = NULL;
m_pPos0 = m_pPos1 = NULL;
m_pParticles = NULL;
m_flThreadStretch = 0;
m_flSurfaceStretch = 0;
InitDefaults( );
}
CSoftbody::CSoftbody( CSoftbodyEnvironment *pWorld, const CFeModel *pFeModel )
{
Init( pWorld, pFeModel , 0 );
}
void CSoftbody::Init( CSoftbodyEnvironment *pWorld, const CFeModel *pFeModel, int numModelBones )
{
m_pEnvironment = pWorld;
m_pFeModel = const_cast< CFeModel* >( pFeModel );
Init( numModelBones );
m_pEnvironment->Register( this );
}
CSoftbody::~CSoftbody()
{
Shutdown( );
}
void AddOrigin( matrix3x4a_t &tm, const Vector &vDelta )
{
tm.SetOrigin( tm.GetOrigin() + vDelta );
}
void CSoftbody::ReplaceFeModel( CFeModelReplaceContext &context )
{
uint8 *pOldBuffer = ( uint8* )m_pParticles;
matrix3x4a_t *pOldAnim = GetAnimatedTransforms(), *pOldSim = GetSimulatedTransforms();
VectorAligned *pOldPos0 = m_pPos0, *pOldPos1 = m_pPos1;
m_StickyBuffer.Clear();
m_pFeModel = const_cast< CFeModel* >( context.GetNew() );
InitFeModel();
Vector vSimOrigin = m_nAnimSpace == SOFTBODY_ANIM_SPACE_LOCAL ? vec3_origin : m_vSimOrigin;
// heuristics: sim origin is probably where the user expects to find new pieces of their new cloth
for ( int nNewNode = 0; nNewNode < ( int )m_nNodeCount; ++nNewNode )
{
// remap what little we can, shift what we can't
int nOldNode = context.NewToOldNode( nNewNode );
if ( nOldNode < 0 )
{
m_pPos0[ nNewNode ] += vSimOrigin;
m_pPos1[ nNewNode ] += vSimOrigin;
}
else
{
m_pPos0[ nNewNode ] = pOldPos0[ nOldNode ];
m_pPos1[ nNewNode ] = pOldPos1[ nOldNode ];
}
}
// and map the animations, too
for ( int nNewCtrl = 0; nNewCtrl < ( int )m_nParticleCount; ++nNewCtrl )
{
int nOldCtrl = context.NewToOldCtrl( nNewCtrl );
if ( nOldCtrl < 0 )
{
AddOrigin( GetAnim( nNewCtrl ), vSimOrigin );
AddOrigin( GetSim( nNewCtrl ), vSimOrigin );
}
else
{
GetAnim( nNewCtrl ) = pOldAnim[ nOldCtrl ];
GetSim( nNewCtrl ) = pOldSim[ nOldCtrl ];
}
}
GoWakeup(); // we could copy the old positions here, but I doubt anyone needs it
MemAlloc_FreeAligned( pOldBuffer );
}
uint Align4( uint a )
{
return ( a + 3 ) & ~3;
}
void CSoftbody::InitDefaults( )
{
m_nDebugSelection = 0;
m_nDebugDrawTreeEndLevel = 0;
m_nDebugDrawTreeBeginLevel = 0;
m_nDebugDrawTreeFlags = 0;
m_flVelAirDrag = m_flExpAirDrag = 0.0f;
m_flVelQuadAirDrag = m_flExpQuadAirDrag = 0.0f;
m_flVelRodAirDrag = m_flExpRodAirDrag = 0.0f;
m_flQuadVelocitySmoothRate = 0.0f;
m_flRodVelocitySmoothRate = 0.0f;
m_flVolumetricSolveAmount = 0.0f;
m_nRodVelocitySmoothIterations = 0;
m_nQuadVelocitySmoothIterations = 0;
m_nSimFlags = 0;
m_nAnimSpace = SOFTBODY_ANIM_SPACE_WORLD;
m_flLastTimestep = 1.0f / 60.0f;
m_flOverPredict = 0;
m_bAnimTransformChanged = false;
m_bSimTransformsOutdated = false;
m_bGravityDisabled = false;
m_bEnableAnimationAttraction = true;
m_bEnableFollowNodes = true;
m_bEnableInclusiveCollisionSpheres = true;
m_bEnableExclusiveCollisionSpheres = true;
m_bEnableCollisionPlanes = true;
m_bEnableGroundCollision = true;
m_bEnableGroundTrace = false;
m_bEnableFtlPass = false;
m_bEnableSprings = true;
m_bFrozen = false;
m_bDebugDraw = true;
m_bEnableSimd = GetCPUInformation().m_bSSE2;
m_nEnableWorldShapeCollision = 0;
m_nStepsSimulated = 0;
m_flGravityScale = 1.0f;
m_flModelScale = 1.0f;
m_flClothScale = 1.0f;
m_flVelocityDamping = 0.0f;
m_flStepUnderRelax = 0.0f;
m_flDampingMultiplier = 1.0f;
m_vGround = vec3_origin;
m_vSimOrigin = vec3_origin;
m_vSimAngles.Init( );
m_vRopeOffset = Vector( 0, -1, 0 ) * g_flRopeSize; // this is the "right" (?!) vector in dota heroes
m_nActivityState = STATE_DORMANT;
//m_nDebugNode = 0xFFFFFFFF;
/*
m_bTeleportOnNextSetAbsOrigin = true;
m_bTeleportOnNextSetAbsAngles = true;
*/
m_nStateCounter = 0;
}
void CSoftbody::SetInstanceSettings( void *pSettings )
{
if ( pSettings )
{
m_flClothScale = *( const float* ) pSettings;
}
}
void CSoftbody::Init( int numModelBones )
{
InitDefaults( );
V_memset( m_pUserData, 0, sizeof( m_pUserData ) );
InitFeModel( numModelBones );
if ( IsDebug() ) Post();
Validate();
}
void CSoftbody::InitFeModel( int numModelBones )
{
m_nNodeCount = m_pFeModel->m_nNodeCount;
m_nParticleCount = m_pFeModel->m_nCtrlCount;
m_flThreadStretch = m_pFeModel->m_flDefaultThreadStretch;
m_flSurfaceStretch = m_pFeModel->m_flDefaultSurfaceStretch;
m_flGravityScale = m_pFeModel->m_flDefaultGravityScale;
if ( m_flGravityScale == 0.0f )
{
Warning( "Graivty Scale 0, probably invalid default. Changing to 1\n" );
m_flGravityScale = 1.0f;
}
m_flVelAirDrag = m_pFeModel->m_flDefaultVelAirDrag;
m_flExpAirDrag = m_pFeModel->m_flDefaultExpAirDrag;
m_flVelQuadAirDrag = m_pFeModel->m_flDefaultVelQuadAirDrag;
m_flExpQuadAirDrag = m_pFeModel->m_flDefaultExpQuadAirDrag;
m_flVelRodAirDrag = m_pFeModel->m_flDefaultVelRodAirDrag;
m_flExpRodAirDrag = m_pFeModel->m_flDefaultExpRodAirDrag;
m_flQuadVelocitySmoothRate = m_pFeModel->m_flQuadVelocitySmoothRate;
m_flRodVelocitySmoothRate = m_pFeModel->m_flRodVelocitySmoothRate;
m_flVolumetricSolveAmount = m_pFeModel->m_flDefaultVolumetricSolveAmount;
m_nRodVelocitySmoothIterations = m_pFeModel->m_nRodVelocitySmoothIterations;
m_nQuadVelocitySmoothIterations = m_pFeModel->m_nQuadVelocitySmoothIterations;
uint bTreeCollisionCount = ( m_pFeModel->m_nTaperedCapsuleStretchCount | m_pFeModel->m_nTaperedCapsuleRigidCount | m_pFeModel->m_nSphereRigidCount | ( m_pFeModel->m_nDynamicNodeFlags & FE_FLAG_ENABLE_WORLD_SHAPE_COLLISION_MASK ) ) ;
uint bAnyCollisionCount = bTreeCollisionCount | m_pFeModel->m_nCollisionPlanes | m_pFeModel->m_nCollisionSpheres[ 0 ];
uint nAabbs = bTreeCollisionCount ? m_pFeModel->GetDynamicNodeCount() - 1 : 0;
uint nParticleGlue = bAnyCollisionCount ? m_pFeModel->GetDynamicNodeCount() : 0;
uint nMemSize = GetParticleArrayCount() * sizeof( matrix3x4a_t ) + m_nNodeCount * 2 * sizeof( VectorAligned ) + nAabbs * sizeof( FeAabb_t ) + nParticleGlue * sizeof( CParticleGlue );
if ( numModelBones )
{
nMemSize += numModelBones * sizeof( *m_pModelBoneToCtrl ) + m_pFeModel->m_nCtrlCount * sizeof( *m_pCtrlToModelBone );
}
CBufferStrider buffer( MemAlloc_AllocAligned( nMemSize, 16 ) );
V_memset( buffer.Get( ), 0, nMemSize );
uint8 *pMemEnd = buffer.Get( ) + nMemSize; NOTE_UNUSED( pMemEnd );
m_pParticles = buffer.Stride< matrix3x4a_t >( GetParticleArrayCount( ) );
m_pPos0 = buffer.Stride< VectorAligned >( m_nNodeCount );
m_pPos1 = buffer.Stride< VectorAligned >( m_nNodeCount );
m_pAabb = nAabbs ? buffer.Stride< FeAabb_t >( nAabbs ) : NULL;
if ( nParticleGlue )
{
m_StickyBuffer.EnsureBitExists( nParticleGlue - 1 );
m_pParticleGlue = buffer.Stride< CParticleGlue >( nParticleGlue );
}
else
{
m_pParticleGlue = NULL;
}
if ( numModelBones )
{
m_pModelBoneToCtrl = buffer.Stride< int16 >( numModelBones );
for ( int i = 0; i < numModelBones; ++i )
{
m_pModelBoneToCtrl[ i ] = -1;
}
m_pCtrlToModelBone = buffer.Stride< int16 >( m_pFeModel->m_nCtrlCount );
for ( uint i = 0; i < m_pFeModel->m_nCtrlCount; ++i )
{
m_pCtrlToModelBone[ i ] = -1;
}
}
else
{
m_pModelBoneToCtrl = NULL;
m_pCtrlToModelBone = NULL;
}
m_bEnableFtlPass = ( m_pFeModel->m_nDynamicNodeFlags & FE_FLAG_ENABLE_FTL ) != 0;
m_nEnableWorldShapeCollision = ( m_pFeModel->m_nDynamicNodeFlags >> FE_FLAG_ENABLE_WORLD_SHAPE_COLLISION_SHIFT ) & ( ( 1 << SHAPE_COUNT ) - 1 );
if ( !m_pFeModel->m_pNodeToCtrl && m_pFeModel->m_pInitPose )
{
AssertDbg( m_pFeModel->m_nCtrlCount == m_pFeModel->m_nNodeCount );
for ( int nNode = 0; nNode < m_nNodeCount; ++nNode )
{
m_pPos0[ nNode ] = m_pPos1[ nNode ] = m_pFeModel->m_pInitPose[ nNode ].GetOrigin( );
GetAnim( nNode ) = GetSim( nNode ) = TransformMatrix( m_pFeModel->m_pInitPose[ nNode ] );
}
}
else
{
// simple initialization
V_memset( m_pPos0, 0, m_nNodeCount * sizeof( *m_pPos0 ) );
V_memset( m_pPos1, 0, m_nNodeCount * sizeof( *m_pPos1 ) );
for ( int nCtrl = 0; nCtrl < GetParticleArrayCount( ); ++nCtrl )
{
m_pParticles[ nCtrl ] = g_MatrixIdentity;
}
}
AssertDbg( pMemEnd == buffer.Get( ) );
m_nSimFlags = m_pEnvironment->GetSoftbodySimulationFlags();
}
void CSoftbody::BindModelBoneToCtrl( int nModelBone, int nCtrl )
{
if ( nCtrl >= 0 )
{
m_pCtrlToModelBone[ nCtrl ] = nModelBone;
}
if ( nModelBone >= 0 )
{
m_pModelBoneToCtrl[ nModelBone ] = nCtrl;
}
}
void CSoftbody::SetSimFlags( uint nNewSimFlags )
{
uint nDiffFlags = m_nSimFlags ^ nNewSimFlags;
if ( nDiffFlags )
{
// reset?
m_nSimFlags = nNewSimFlags;
}
}
void CSoftbody::DebugDump( )
{
if ( IsDebug() && g_nClothDebug && m_nStepsSimulated < 7 )
{
CUtlString line;
AppendDebugInfo( line );
Msg( "%s\n", line.Get( ) );
}
}
void CSoftbody::AppendDebugInfo( CUtlString &line )
{
AABB_t bbox = BuildBounds( );
Vector c = bbox.GetCenter( ), e = bbox.GetSize( );
CUtlString desc;
const char *pActivityState = "Undefined";
switch ( m_nActivityState )
{
case STATE_ACTIVE:
pActivityState = "active";
break;
case STATE_DORMANT:
pActivityState = "dormant";
break;
case STATE_WAKEUP:
pActivityState = "wakeup";
break;
}
desc.Format( "Softbody #%d %s.%d %s (%.4g,%.4g)\xb1(%.4g,%.4g)", m_nIndexInWorld, pActivityState, m_nStateCounter, m_DebugName.GetSafe( ), c.x, c.y, e.x, e.y );
line += desc;
}
void CSoftbody::Validate()
{
if ( IsDebug( ) )
{
const matrix3x4a_t *pSim = m_pParticles + m_nParticleCount; NOTE_UNUSED( pSim );
for ( int nCtrl = 0; nCtrl < m_nParticleCount; ++nCtrl )
{
uint nNode = m_pFeModel->CtrlToNode( nCtrl ); NOTE_UNUSED( nNode );
bool bIsSimulated = ( nNode < m_nParticleCount && nNode > m_pFeModel->m_nStaticNodes ); NOTE_UNUSED( bIsSimulated );
AssertDbg( IsGoodWorldTransform( pSim[ nCtrl ] ) );
AssertDbg( IsGoodWorldTransform( Descale( m_pParticles[ nCtrl ] ) ) );
}
}
}
void CSoftbody::SetPose( const CTransform *pPose )
{
CHANGE_GUARD();
for ( int nParticle = 0; nParticle < m_nParticleCount; ++nParticle )
{
SetCtrl( nParticle, pPose[ nParticle ] );
}
Validate( );
m_bAnimTransformChanged = true;
m_bSimTransformsOutdated = false;
}
void CSoftbody::SetPose( const CTransform &tm, const CTransform *pPose )
{
CHANGE_GUARD();
AssertDbg( FloatsAreEqual( QuaternionLength( tm.m_orientation ), 1.0f, 1e-5f ) );
for ( int nParticle = 0; nParticle < m_nParticleCount; ++nParticle )
{
CTransform pose = ConcatTransforms( tm, pPose[ nParticle ] );
SetCtrl( nParticle, pose );
}
Validate( );
m_bAnimTransformChanged = true;
m_bSimTransformsOutdated = false;
}
void CSoftbody::SetCtrl( int nParticle, const CTransform &pose )
{
CHANGE_GUARD();
matrix3x4a_t tmPose = TransformMatrix( pose );
GetAnim( nParticle ) = tmPose;
uint nNode = m_pFeModel->CtrlToNode( nParticle );
if ( nNode < m_nNodeCount )
{
if ( m_pFeModel->m_pNodeIntegrator )
{
float flDamping = m_flLastTimestep * ( m_pFeModel->m_pNodeIntegrator[ nNode ].flPointDamping * m_flDampingMultiplier * g_flClothDampingMultiplier );
if ( flDamping < 1.0f )
{
GetSim( nParticle ).SetOrigin(
m_pPos0[ nNode ] = m_pPos1[ nNode ] =
pose.GetOrigin( ) * ( 1 - flDamping ) + m_pPos1[ nNode ] * flDamping
);
}
}
else
{
m_pPos0[ nNode ] = m_pPos1[ nNode ] = pose.GetOrigin( );
}
}
else
{
GetSim( nParticle ) = tmPose;
}
}
void CSoftbody::SetPoseFromBones( const int16 *pCtrlToBone, const matrix3x4a_t *pBones, float flScale )
{
CHANGE_GUARD();
if ( m_pFeModel->m_pCtrlToNode )
{
for ( int nParticle = 0; nParticle < m_nParticleCount; ++nParticle )
{
if ( pCtrlToBone[ nParticle ] < 0 )
continue;
const matrix3x4a_t &pose = pBones[ pCtrlToBone[ nParticle ] ];
AssertDbg( IsGoodWorldTransform( pose, flScale ) );
GetSim( nParticle ) = GetAnim( nParticle ) = ScaleMatrix3x3( pose, flScale ) ;
uint nNode = m_pFeModel->m_pCtrlToNode[ nParticle ];
if ( nNode < m_nNodeCount )
{
m_pPos0[ nNode ] = m_pPos1[ nNode ] = pose.GetOrigin( );
}
}
}
else
{
for ( int nParticle = 0; nParticle < m_nParticleCount; ++nParticle )
{
if ( pCtrlToBone[ nParticle ] < 0 )
continue;
const matrix3x4a_t &pose = pBones[ pCtrlToBone[ nParticle ] ];
const matrix3x4a_t poseNoScale = ScaleMatrix3x3( pose, flScale );
AssertDbg( IsGoodWorldTransform( poseNoScale, 1.0f ) );
GetSim( nParticle ) = GetAnim( nParticle ) = poseNoScale;
uint nNode = nParticle;
m_pPos0[ nNode ] = m_pPos1[ nNode ] = pose.GetOrigin( );
}
}
m_bAnimTransformChanged = true;
m_bSimTransformsOutdated = false;
Validate( );
}
uint CSoftbody::Step( float flTimeStep )
{
return Step( m_pEnvironment->GetSoftbodyIterations(), flTimeStep );
}
const float g_flClothStep = 1.0f;
const int g_nClothCompatibility = 1;
void CSoftbody::DebugPreStep(float flTimeStep )
{
#ifdef _DEBUG
static bool s_bRead = false;
CUtlString buf; NOTE_UNUSED( buf );
if ( g_nClothDebug )
{
buf = PrintParticleState();
}
if ( s_bRead )
{
CUtlBuffer buf( 0, 0, CUtlBuffer::TEXT_BUFFER );
if ( g_pFullFileSystem->ReadFile( "cloth.txt", NULL, buf ) )
{
ParseParticleState( buf, flTimeStep );
}
s_bRead = false;
}
#endif
}
uint CSoftbody::Step( int nIterations, float flTimeStep )
{
if ( m_bFrozen )
return 0;
CHANGE_GUARD();
MPROF_AUTO_FAST( SoftbodyStep );
flTimeStep *= g_flClothStep;
if ( m_nActivityState == STATE_ACTIVE && flTimeStep > 1e-5f )
{
Validate(); // DebugPreStep(flTimeStep);
RawSimulate( nIterations, flTimeStep );
m_bSimTransformsOutdated = true;
m_nStepsSimulated++;
Post( );
Validate( ); // DebugDump( );
return 1;
}
else
{
return 0;
}
}
uint CSoftbody::GetStateHash()const
{
CRC32_t hash;
CRC32_Init( &hash );
CRC32_ProcessBuffer( &hash, m_pPos0, sizeof( *m_pPos0 ) * m_pFeModel->m_nNodeCount );
CRC32_ProcessBuffer( &hash, m_pPos1, sizeof( *m_pPos1 ) * m_pFeModel->m_nNodeCount );
CRC32_Final( &hash );
return hash;
}
bool IsEqual( const CUtlVector< uint > &a, const CUtlVector< uint > & b )
{
if ( a.Count() != b.Count() ) return false;
for ( int nIndex = 0; nIndex < a.Count(); ++nIndex )
if ( a[ nIndex ] != b[ nIndex ] )
return false;
return true;
}
// check that RawSimulate is deterministic
void CSoftbody::ValidatingSimulate( int nIterations, float flTimeStep )
{
// remember the initial state
CUtlVector< VectorAligned > pos0, pos1;
int nNodes = m_pFeModel->m_nNodeCount;
pos0.CopyArray( m_pPos0, nNodes );
pos1.CopyArray( m_pPos1, nNodes );
bool bWasAnimTransformChanged = m_bAnimTransformChanged;
bool bRepeat = false;
for ( ;; )
{
RawSimulate( nIterations, flTimeStep );
CUtlVector< VectorAligned > res0, res1; // initial results
res0.CopyArray( m_pPos0, nNodes );
res1.CopyArray( m_pPos1, nNodes );
CUtlVector< VectorAligned > rep0, rep1; // repeat input state
rep0.CopyArray( pos0.Base(), nNodes );
rep1.CopyArray( pos1.Base(), nNodes );
VectorAligned *pSavePos0 = m_pPos0, *pSavePos1 = m_pPos1; // save the previous pointers
m_pPos0 = rep0.Base();
m_pPos1 = rep1.Base();
m_bAnimTransformChanged = bWasAnimTransformChanged;
RawSimulate( nIterations, flTimeStep ); // repeat simulation with the repeat input state
if ( m_pPos0 == rep1.Base() ) { rep0.Swap( rep1 ); } // m_Pos were swapped, swap rep
m_pPos0 = pSavePos0; // recover buffer pointers
m_pPos1 = pSavePos1;
// check that the initial results equal to repeat results
for ( int n = 0; n < nNodes; ++n )
{
Assert( res0[ n ] == rep0[ n ] );
Assert( res1[ n ] == rep1[ n ] );
}
if ( !bRepeat )
break;
m_bAnimTransformChanged = bWasAnimTransformChanged;
// start all over from the copied initial state
V_memcpy( m_pPos0, pos0.Base(), sizeof( VectorAligned ) * nNodes );
V_memcpy( m_pPos1, pos1.Base(), sizeof( VectorAligned ) * nNodes );
}
}
void CSoftbody::RawSimulate( int nIterations, float flTimeStep )
{
if ( g_nClothCompatibility >= 2 && ( m_pFeModel->m_nDynamicNodeFlags & FE_FLAG_UNINERTIAL_CONSTRAINTS ) )
{
Integrate_S1( flTimeStep );
ResolveStretch_S1( flTimeStep ); // this folds in the constraint iterator loop
ResolveAnimAttraction_S1( flTimeStep );
Collide();
}
else
{
Integrate( flTimeStep );
Predict( flTimeStep );
AddAnimationAttraction( flTimeStep );
Collide();
{
CConstraintIterator iterator( this );
iterator.Iterate( nIterations );
}
}
}
void CSoftbody::ParseParticleState( CUtlBuffer &buf, float flTimeStep )
{
char szName[ 300 ];
Vector vOrigin, vAnimTarget, vVelocity;
uint nTotalFound = 0; NOTE_UNUSED( nTotalFound );
while ( 10 == buf.Scanf( "%s %f %f %f %f %f %f %f %f %f\n", szName, &vOrigin.x, &vOrigin.y, &vOrigin.z, &vAnimTarget.x, &vAnimTarget.y, &vAnimTarget.z, &vVelocity.x, &vVelocity.y, &vVelocity.z ) )
{
// find this bone
bool bFound = false;
for ( uint nCtrl = 0; nCtrl < m_pFeModel->m_nCtrlCount; ++nCtrl )
{
if ( !V_stricmp( m_pFeModel->m_pCtrlName[ nCtrl ], szName ) )
{
uint nNode = m_pFeModel->CtrlToNode( nCtrl );
bFound = true;
m_pPos1[ nNode ] = vOrigin;
m_pPos0[ nNode ] = vOrigin - flTimeStep * vVelocity;
GetAnim( nCtrl ).SetOrigin( vAnimTarget );
break;
}
}
if ( bFound )
{
nTotalFound++;
}
else
{
Msg( "Not found: %s\n", szName );
}
}
Msg( "%d bones found and initialized\n", nTotalFound );
}
CUtlString CSoftbody::PrintParticleState( )const
{
CUtlString buf;
for ( uint nCtrl = 0; nCtrl < m_pFeModel->m_nCtrlCount ; ++nCtrl )
{
CUtlString line;
uint nNode = m_pFeModel->CtrlToNode( nCtrl );
const VectorAligned &vOrigin = m_pPos1[ nNode ];
Vector vAnimTarget = GetAnim( nCtrl ).GetOrigin(), vVelocity = ( m_pPos1[ nNode ] - m_pPos0[ nNode ] ) / m_flLastTimestep;
line.Format( "%s %g %g %g %g %g %g %g %g %g\n", m_pFeModel->m_pCtrlName[ nCtrl ],
vOrigin.x, vOrigin.y, vOrigin.z, vAnimTarget.x, vAnimTarget.y, vAnimTarget.z, vVelocity.x, vVelocity.y, vVelocity.z
);
buf += line;
}
return buf;
}
void CSoftbody::Integrate_S1( float flTimeStep )
{
const uint nStaticNodes = m_pFeModel->m_nStaticNodes;
const FeNodeIntegrator_t *pNodeIntegrator = m_pFeModel->m_pNodeIntegrator;
float flTickRate = 1.0f / flTimeStep, flPrevTickRate = 1.0f / m_flLastTimestep;
VectorAligned *pPos0 = m_pPos0, *pPos1 = m_pPos1;
if ( m_bAnimTransformChanged )
{
// <sergiy> Note that the animation is copied into static nodes in Source1 in CClothModelPiece::SetupBone(), cloth_system.cpp#36:3397
// it's probably a good idea to continue doing that regardless of the slight bug in source1 that overshot static bones slightly, unless artists unwittingly relied on that bug in some cases
{
for ( uint nStaticNode = 0; nStaticNode < nStaticNodes; ++nStaticNode )
{
uint nCtrl = m_pFeModel->NodeToCtrl( nStaticNode );
Assert( nCtrl < m_nParticleCount );
pPos0[ nStaticNode ] = pPos1[ nStaticNode ];
pPos1[ nStaticNode ] = GetAnim( nCtrl ).GetOrigin();
}
}
m_bAnimTransformChanged = false;
if ( m_bEnableFollowNodes )
{
for ( uint nFlwr = 0, nFollowers = m_pFeModel->m_nFollowNodeCount; nFlwr < nFollowers; ++nFlwr )
{
const FeFollowNode_t fn = m_pFeModel->m_pFollowNodes[ nFlwr ];
Vector vDelta = ( pPos1[ fn.nParentNode ] - pPos0[ fn.nParentNode ] ) * fn.flWeight;
// why pos0-=, and not pos1+=? because we're computing pos2=pos1 + ( pos1 - pos0 ) later, and advancing pos1 will have the effect of doubling the velocity of the child
pPos1[ fn.nChildNode ] += vDelta;
pPos0[ fn.nChildNode ] += vDelta;
}
}
}
else
{
// since we're double-buffering the positions, we need to copy the positions for at least one frame
// after animation stopped updating them. We can add another flag here to avoid memcpy if it ever becomes noticeable CPU drain
V_memcpy( m_pPos0, m_pPos1, sizeof( *m_pPos0 ) * nStaticNodes );
}
Vector vGravity( 0, 0, -( m_bGravityDisabled ? 0 : m_flGravityScale ) );
AssertDbg( !m_pFeModel->m_pCtrlToNode ); // it should be safe to assume we have no node-to-ctrl mapping on Source1-imported content
for ( uint nDynNode = nStaticNodes; nDynNode < m_nNodeCount; ++nDynNode )
{
// CClothParticleState::InitialForces()
VectorAligned &pos1 = pPos1[ nDynNode ], &pos0 = pPos0[ nDynNode ];
Vector vOrigin = pos1, vVelocity = ( pos1 - pos0 ) * flPrevTickRate;
float flInvMass = m_pFeModel->m_pNodeInvMasses[ nDynNode ];
Vector vForce;
// animation attraction
if ( pNodeIntegrator )
{
const FeNodeIntegrator_t &integrator = pNodeIntegrator[ nDynNode ];
vForce = vGravity * integrator.flGravity / flInvMass;
Vector vAnimPos = GetAnim( nDynNode ).GetOrigin();
Vector vDelta = vAnimPos - vOrigin;
float flAnimationForceAttraction = integrator.flAnimationForceAttraction / flInvMass; // this is predivided by mass in CAuthClothParser::ParseLegacyDotaNodeGrid(), line 1894
vForce += vDelta * ( flAnimationForceAttraction * g_flClothAttrVel * flTickRate );
vForce -= ( pNodeIntegrator[ nDynNode ].flPointDamping / flInvMass ) * vVelocity; // it's safe to assume S1-imported cloth has Unitless Damping = false, so all the damping values are premultiplied by mass
}
else
{
vForce = vGravity * 360 / flInvMass; // 360 is the default gravity, if there's no integrator, 360 is the assumed gravity per node
}
// CClothParticleState::Integrate()
float flDeltaTimeMass = flTimeStep * flInvMass;
vVelocity += vForce * flDeltaTimeMass;
pos1 = vOrigin + flTimeStep * vVelocity;
pos0 = vVelocity; // pos0 will temporarily store velocity!
}
m_flLastTimestep = flTimeStep;
}
void CSoftbody::ResolveStretch_S1( float flTimeStep )
{
VectorAligned *pVel = m_pPos0, *pPos = m_pPos1;
float flConstraintScale = m_flModelScale * m_flClothScale;
uint nStaticNodes = m_pFeModel->m_nStaticNodes;
const float *pStretchForce = m_pFeModel->m_pLegacyStretchForce;
for ( uint nRod = 0; nRod < m_pFeModel->m_nRodCount; ++nRod )
{
const FeRodConstraint_t &rod = m_pFeModel->m_pRods[ nRod ];
VectorAligned &vOrigin1 = pPos[ rod.nNode[ 0 ] ], &vOrigin2 = pPos[ rod.nNode[ 1 ] ];
VectorAligned &vVelocity1 = pVel[ rod.nNode[ 0 ] ], &vVelocity2 = pVel[ rod.nNode[ 1 ] ];
//
// CClothSpring::ResolveStretch()
//
Vector vDeltaOrigin = vOrigin1 - vOrigin2;
float flDistance = vDeltaOrigin.Length();
float flRestLength = rod.flMaxDist;
if ( flDistance > flRestLength )
{
// Note: CClothSpring::m_flStretchiness = 1 - SpringStretchiness from keyvalue file.
float flSpringStretchiness = rod.flRelaxationFactor;
vDeltaOrigin /= flDistance;
flDistance -= flRestLength;
flDistance *= flSpringStretchiness;
Vector vDeltaDistance = vDeltaOrigin * flDistance;
if ( ( rod.nNode[ 0 ] <= rod.nNode[ 1 ] || rod.nNode[ 0 ] < nStaticNodes ) && rod.nNode[1] >= nStaticNodes )
{
vOrigin2 += vDeltaDistance;
if ( pStretchForce )
{
Vector vDeltaVelocity = vDeltaDistance * pStretchForce[ rod.nNode[ 1 ] ];
vVelocity2 += vDeltaVelocity;
}
}
else if ( rod.nNode[ 0 ] >= nStaticNodes )
{
vOrigin1 -= vDeltaDistance;
if ( pStretchForce )
{
Vector vDeltaVelocity = vDeltaDistance * pStretchForce[ rod.nNode[ 0 ] ];
vVelocity1 -= vDeltaVelocity;
}
}
}
}
// the rest is forward compatibility stuff
float flRodStiffness = expf( -m_flThreadStretch );
float flSurfaceStiffness = expf( -m_flSurfaceStretch );
m_pFeModel->RelaxBend( pPos, flRodStiffness );
{
MPROF_AUTO_FAST( FeRelaxQuads );
if ( m_bEnableSimd )
{
m_pFeModel->RelaxSimdQuads( pPos, flSurfaceStiffness, flConstraintScale, m_nSimFlags & SOFTBODY_SIM_EXPERIMENTAL_1 );
m_pFeModel->RelaxSimdTris( pPos, flSurfaceStiffness, flConstraintScale );
}
else
{
m_pFeModel->RelaxQuads( pPos, flSurfaceStiffness, flConstraintScale, m_nSimFlags & SOFTBODY_SIM_EXPERIMENTAL_1 );
m_pFeModel->RelaxTris( pPos, flSurfaceStiffness, flConstraintScale );
}
}
}
void CSoftbody::ResolveAnimAttraction_S1( float flTimeStep )
{
VectorAligned *pPos = m_pPos1;
AssertDbg( !m_pFeModel->m_pNodeToCtrl );
if ( const FeNodeIntegrator_t *pIntegrator = m_pFeModel->m_pNodeIntegrator )
{
for ( uint nDynNode = m_pFeModel->m_nStaticNodes; nDynNode < m_nNodeCount; ++nDynNode )
{
VectorAligned &refParticleOrigin = pPos[ nDynNode ];
Vector vAnimPos = GetAnim( nDynNode ).GetOrigin();
Vector vDelta = vAnimPos - refParticleOrigin;
vDelta *= pIntegrator[ nDynNode ].flAnimationVertexAttraction * flTimeStep;
refParticleOrigin += vDelta;
}
}
// convert velocities back to positions for possible verlet integration on the next step
for ( uint nDynNode = m_pFeModel->m_nStaticNodes; nDynNode < m_nNodeCount; ++nDynNode )
{
m_pPos0[ nDynNode ] = pPos[ nDynNode ] - m_pPos0[ nDynNode ] * flTimeStep;
}
}
//-------------------------------------------------------------------------------------------------
FORCEINLINE AABB_t AsBounds3( const FeAabb_t &bbox )
{
AABB_t out;
out.m_vMinBounds = AsVector( bbox.m_vMinBounds );
out.m_vMaxBounds = AsVector( bbox.m_vMaxBounds );
return out;
}
void CSoftbody::Collide()
{
if ( !m_pAabb )
return; // no memory preallocated to compute AABBs, presumably because we don't have anything to collide with
CHANGE_GUARD();
//if ( !( ( m_nEnableWorldShapeCollision && m_pEnvironment ) | m_pFeModel->m_nTaperedCapsuleStretchCount | m_pFeModel->m_nTaperedCapsuleRigidCount | m_pFeModel->m_nSphereRigidCount ) )
// return; // nothing to collide with, let's not recompute AABBs
MPROF_AUTO_FAST( SoftbodyStepCollide );
m_pFeModel->ComputeCollisionTreeBounds( m_pPos1 + m_pFeModel->m_nStaticNodes, m_pAabb );
CollideWithRigidsInternal();
CollideWithWorldInternal();
}