/
CcdPhysicsController.cpp
2586 lines (2226 loc) · 78.2 KB
/
CcdPhysicsController.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
/** \file gameengine/Physics/Bullet/CcdPhysicsController.cpp
* \ingroup physbullet
*/
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef WIN32
#include <stdint.h>
#endif
#include "CM_Message.h"
#include "CcdPhysicsController.h"
#include "btBulletDynamicsCommon.h"
#include "BulletCollision/CollisionDispatch/btGhostObject.h"
#include "BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.h"
#include "BulletCollision/CollisionShapes/btTriangleIndexVertexArray.h"
#include "PHY_IMotionState.h"
#include "CcdPhysicsEnvironment.h"
#include "RAS_DisplayArray.h"
#include "RAS_MeshObject.h"
#include "RAS_Polygon.h"
#include "RAS_Deformer.h"
#include "KX_GameObject.h"
#include "BulletSoftBody/btSoftBody.h"
#include "BulletSoftBody/btSoftBodyInternals.h"
#include "BulletSoftBody/btSoftBodyHelpers.h"
#include "LinearMath/btConvexHull.h"
#include "BulletCollision/Gimpact/btGImpactShape.h"
#include "BulletSoftBody/btSoftRigidDynamicsWorld.h"
#include "DNA_mesh_types.h"
#include "DNA_meshdata_types.h"
extern "C" {
#include "BLI_utildefines.h"
#include "BKE_cdderivedmesh.h"
}
/// todo: fill all the empty CcdPhysicsController methods, hook them up to the btRigidBody class
//'temporarily' global variables
extern float gDeactivationTime;
extern bool gDisableDeactivation;
float gLinearSleepingTreshold;
float gAngularSleepingTreshold;
BlenderBulletCharacterController::BlenderBulletCharacterController(CcdPhysicsController *ctrl, btMotionState *motionState,
btPairCachingGhostObject *ghost, btConvexShape *shape, float stepHeight)
:btKinematicCharacterController(ghost, shape, stepHeight, 2),
m_ctrl(ctrl),
m_motionState(motionState),
m_jumps(0),
m_maxJumps(1)
{
}
void BlenderBulletCharacterController::updateAction(btCollisionWorld *collisionWorld, btScalar dt)
{
if (onGround())
m_jumps = 0;
btKinematicCharacterController::updateAction(collisionWorld, dt);
m_motionState->setWorldTransform(getGhostObject()->getWorldTransform());
}
unsigned char BlenderBulletCharacterController::getMaxJumps() const
{
return m_maxJumps;
}
void BlenderBulletCharacterController::setMaxJumps(unsigned char maxJumps)
{
m_maxJumps = maxJumps;
}
unsigned char BlenderBulletCharacterController::getJumpCount() const
{
return m_jumps;
}
bool BlenderBulletCharacterController::canJump() const
{
return (onGround() && m_maxJumps > 0) || m_jumps < m_maxJumps;
}
void BlenderBulletCharacterController::jump()
{
if (!canJump())
return;
m_verticalVelocity = m_jumpSpeed;
m_wasJumping = true;
m_jumps++;
}
const btVector3& BlenderBulletCharacterController::getWalkDirection()
{
return m_walkDirection;
}
float BlenderBulletCharacterController::GetFallSpeed() const
{
return m_fallSpeed;
}
void BlenderBulletCharacterController::SetFallSpeed(float fallSpeed)
{
setFallSpeed(fallSpeed);
}
float BlenderBulletCharacterController::GetJumpSpeed() const
{
return m_jumpSpeed;
}
void BlenderBulletCharacterController::SetJumpSpeed(float jumpSpeed)
{
setJumpSpeed(jumpSpeed);
}
void BlenderBulletCharacterController::SetVelocity(const btVector3& vel, float time, bool local)
{
btVector3 v = vel;
if (local) {
const btTransform xform = getGhostObject()->getWorldTransform();
v = xform.getBasis() * v;
}
// Avoid changing velocity and keeping previous time interval.
m_velocityTimeInterval = 0.0f;
setVelocityForTimeInterval(v, time);
}
void BlenderBulletCharacterController::SetVelocity(const MT_Vector3& vel, float time, bool local)
{
SetVelocity(ToBullet(vel), time, local);
}
void BlenderBulletCharacterController::Reset()
{
btCollisionWorld *world = m_ctrl->GetPhysicsEnvironment()->GetDynamicsWorld();
reset(world);
}
bool CleanPairCallback::processOverlap(btBroadphasePair &pair)
{
if ((pair.m_pProxy0 == m_cleanProxy) || (pair.m_pProxy1 == m_cleanProxy)) {
m_pairCache->cleanOverlappingPair(pair, m_dispatcher);
CcdPhysicsController *ctrl0 = (CcdPhysicsController *)(((btCollisionObject *)pair.m_pProxy0->m_clientObject)->getUserPointer());
CcdPhysicsController *ctrl1 = (CcdPhysicsController *)(((btCollisionObject *)pair.m_pProxy1->m_clientObject)->getUserPointer());
ctrl0->GetCollisionObject()->activate(false);
ctrl1->GetCollisionObject()->activate(false);
}
return false;
}
CcdPhysicsController::CcdPhysicsController(const CcdConstructionInfo& ci)
:m_cci(ci)
{
m_prototypeTransformInitialized = false;
m_softbodyMappingDone = false;
m_collisionDelay = 0;
m_newClientInfo = 0;
m_registerCount = 0;
m_softBodyTransformInitialized = false;
m_parentCtrl = 0;
// copy pointers locally to allow smart release
m_MotionState = ci.m_MotionState;
m_collisionShape = ci.m_collisionShape;
// apply scaling before creating rigid body
m_collisionShape->setLocalScaling(m_cci.m_scaling);
if (m_cci.m_mass)
m_collisionShape->calculateLocalInertia(m_cci.m_mass, m_cci.m_localInertiaTensor);
// shape info is shared, increment ref count
m_shapeInfo = ci.m_shapeInfo;
if (m_shapeInfo)
m_shapeInfo->AddRef();
m_bulletChildShape = nullptr;
m_bulletMotionState = 0;
m_characterController = 0;
m_savedCollisionFlags = 0;
m_savedCollisionFilterGroup = 0;
m_savedCollisionFilterMask = 0;
m_savedMass = 0.0f;
m_savedDyna = false;
m_suspended = false;
CreateRigidbody();
}
void CcdPhysicsController::addCcdConstraintRef(btTypedConstraint *c)
{
int index = m_ccdConstraintRefs.findLinearSearch(c);
if (index == m_ccdConstraintRefs.size())
m_ccdConstraintRefs.push_back(c);
}
void CcdPhysicsController::removeCcdConstraintRef(btTypedConstraint *c)
{
m_ccdConstraintRefs.remove(c);
}
btTypedConstraint *CcdPhysicsController::getCcdConstraintRef(int index)
{
return m_ccdConstraintRefs[index];
}
int CcdPhysicsController::getNumCcdConstraintRefs() const
{
return m_ccdConstraintRefs.size();
}
btTransform CcdPhysicsController::GetTransformFromMotionState(PHY_IMotionState *motionState)
{
const MT_Vector3 pos = motionState->GetWorldPosition();
const MT_Matrix3x3 mat = motionState->GetWorldOrientation();
return btTransform(ToBullet(mat), ToBullet(pos));
}
class BlenderBulletMotionState : public btMotionState
{
PHY_IMotionState *m_blenderMotionState;
public:
BlenderBulletMotionState(PHY_IMotionState *bms)
:m_blenderMotionState(bms)
{
}
void getWorldTransform(btTransform& worldTrans) const
{
const MT_Vector3 pos = m_blenderMotionState->GetWorldPosition();
const MT_Matrix3x3 mat = m_blenderMotionState->GetWorldOrientation();
worldTrans.setOrigin(ToBullet(pos));
worldTrans.setBasis(ToBullet(mat));
}
void setWorldTransform(const btTransform& worldTrans)
{
m_blenderMotionState->SetWorldPosition(ToMoto(worldTrans.getOrigin()));
m_blenderMotionState->SetWorldOrientation(ToMoto(worldTrans.getRotation()));
m_blenderMotionState->CalculateWorldTransformations();
}
};
btRigidBody *CcdPhysicsController::GetRigidBody()
{
return btRigidBody::upcast(m_object);
}
const btRigidBody *CcdPhysicsController::GetRigidBody() const
{
return btRigidBody::upcast(m_object);
}
btCollisionObject *CcdPhysicsController::GetCollisionObject()
{
return m_object;
}
btSoftBody *CcdPhysicsController::GetSoftBody()
{
return btSoftBody::upcast(m_object);
}
btKinematicCharacterController *CcdPhysicsController::GetCharacterController()
{
return m_characterController;
}
#include "BulletSoftBody/btSoftBodyHelpers.h"
bool CcdPhysicsController::CreateSoftbody()
{
int shapeType = m_cci.m_collisionShape ? m_cci.m_collisionShape->getShapeType() : 0;
//disable soft body until first sneak preview is ready
if (!m_cci.m_bSoft || !m_cci.m_collisionShape ||
((shapeType != CONVEX_HULL_SHAPE_PROXYTYPE) &&
(shapeType != TRIANGLE_MESH_SHAPE_PROXYTYPE) &&
(shapeType != SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE)))
{
return false;
}
btSoftBody *psb = nullptr;
btSoftBodyWorldInfo& worldInfo = m_cci.m_physicsEnv->GetDynamicsWorld()->getWorldInfo();
if (m_cci.m_collisionShape->getShapeType() == CONVEX_HULL_SHAPE_PROXYTYPE) {
btConvexHullShape *convexHull = (btConvexHullShape *)m_cci.m_collisionShape;
{
int nvertices = convexHull->getNumPoints();
const btVector3 *vertices = convexHull->getPoints();
HullDesc hdsc(QF_TRIANGLES, nvertices, vertices);
HullResult hres;
HullLibrary hlib;
hdsc.mMaxVertices = nvertices;
hlib.CreateConvexHull(hdsc, hres);
psb = new btSoftBody(&worldInfo, (int)hres.mNumOutputVertices,
&hres.m_OutputVertices[0], 0);
for (int i = 0; i < (int)hres.mNumFaces; ++i) {
const unsigned int idx[3] = {hres.m_Indices[i * 3 + 0],
hres.m_Indices[i * 3 + 1],
hres.m_Indices[i * 3 + 2]};
if (idx[0] < idx[1]) {
psb->appendLink(idx[0], idx[1]);
}
if (idx[1] < idx[2]) {
psb->appendLink(idx[1], idx[2]);
}
if (idx[2] < idx[0]) {
psb->appendLink(idx[2], idx[0]);
}
psb->appendFace(idx[0], idx[1], idx[2]);
}
hlib.ReleaseResult(hres);
}
}
else {
int numtris = 0;
if (m_cci.m_collisionShape->getShapeType() == SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE) {
btScaledBvhTriangleMeshShape *scaledtrimeshshape = (btScaledBvhTriangleMeshShape *)m_cci.m_collisionShape;
btBvhTriangleMeshShape *trimeshshape = scaledtrimeshshape->getChildShape();
///only deal with meshes that have 1 sub part/component, for now
if (trimeshshape->getMeshInterface()->getNumSubParts() == 1) {
unsigned char *vertexBase;
btScalar *scaledVertexBase;
btVector3 localScaling;
PHY_ScalarType vertexType;
int numverts;
int vertexstride;
unsigned char *indexbase;
int indexstride;
PHY_ScalarType indexType;
trimeshshape->getMeshInterface()->getLockedVertexIndexBase(&vertexBase, numverts, vertexType, vertexstride, &indexbase, indexstride, numtris, indexType);
localScaling = scaledtrimeshshape->getLocalScaling();
scaledVertexBase = new btScalar[numverts * 3];
for (int i = 0; i < numverts * 3; i += 3) {
scaledVertexBase[i] = ((const btScalar *)vertexBase)[i] * localScaling.getX();
scaledVertexBase[i + 1] = ((const btScalar *)vertexBase)[i + 1] * localScaling.getY();
scaledVertexBase[i + 2] = ((const btScalar *)vertexBase)[i + 2] * localScaling.getZ();
}
psb = btSoftBodyHelpers::CreateFromTriMesh(worldInfo, scaledVertexBase, (const int *)indexbase, numtris, false);
delete[] scaledVertexBase;
}
}
else {
btTriangleMeshShape *trimeshshape = (btTriangleMeshShape *)m_cci.m_collisionShape;
///only deal with meshes that have 1 sub part/component, for now
if (trimeshshape->getMeshInterface()->getNumSubParts() == 1) {
unsigned char *vertexBase;
PHY_ScalarType vertexType;
int numverts;
int vertexstride;
unsigned char *indexbase;
int indexstride;
PHY_ScalarType indexType;
trimeshshape->getMeshInterface()->getLockedVertexIndexBase(&vertexBase, numverts, vertexType, vertexstride, &indexbase, indexstride, numtris, indexType);
psb = btSoftBodyHelpers::CreateFromTriMesh(worldInfo, (const btScalar *)vertexBase, (const int *)indexbase, numtris, false);
}
}
// store face tag so that we can find our original face when doing ray casting
btSoftBody::Face *ft;
int i;
for (i = 0, ft = &psb->m_faces[0]; i < numtris; ++i, ++ft) {
// Hack!! use m_tag to store the face number, normally it is a pointer
// add 1 to make sure it is never 0
ft->m_tag = (void *)((uintptr_t)(i + 1));
}
}
if (m_cci.m_margin > 0.0f) {
psb->getCollisionShape()->setMargin(m_cci.m_margin);
psb->updateBounds();
}
m_object = psb;
btSoftBody::Material *pm = psb->m_materials[0];
pm->m_kLST = m_cci.m_soft_linStiff;
pm->m_kAST = m_cci.m_soft_angStiff;
pm->m_kVST = m_cci.m_soft_volume;
psb->m_cfg.collisions = 0;
if (m_cci.m_soft_collisionflags & CCD_BSB_COL_CL_RS) {
psb->m_cfg.collisions += btSoftBody::fCollision::CL_RS;
}
else {
psb->m_cfg.collisions += btSoftBody::fCollision::SDF_RS;
}
if (m_cci.m_soft_collisionflags & CCD_BSB_COL_CL_SS) {
psb->m_cfg.collisions += btSoftBody::fCollision::CL_SS;
}
else {
psb->m_cfg.collisions += btSoftBody::fCollision::VF_SS;
}
psb->m_cfg.kSRHR_CL = m_cci.m_soft_kSRHR_CL; // Soft vs rigid hardness [0,1] (cluster only)
psb->m_cfg.kSKHR_CL = m_cci.m_soft_kSKHR_CL; // Soft vs kinetic hardness [0,1] (cluster only)
psb->m_cfg.kSSHR_CL = m_cci.m_soft_kSSHR_CL; // Soft vs soft hardness [0,1] (cluster only)
psb->m_cfg.kSR_SPLT_CL = m_cci.m_soft_kSR_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only)
psb->m_cfg.kSK_SPLT_CL = m_cci.m_soft_kSK_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only)
psb->m_cfg.kSS_SPLT_CL = m_cci.m_soft_kSS_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only)
psb->m_cfg.kVCF = m_cci.m_soft_kVCF; // Velocities correction factor (Baumgarte)
psb->m_cfg.kDP = m_cci.m_soft_kDP; // Damping coefficient [0,1]
psb->m_cfg.kDG = m_cci.m_soft_kDG; // Drag coefficient [0,+inf]
psb->m_cfg.kLF = m_cci.m_soft_kLF; // Lift coefficient [0,+inf]
psb->m_cfg.kPR = m_cci.m_soft_kPR; // Pressure coefficient [-inf,+inf]
psb->m_cfg.kVC = m_cci.m_soft_kVC; // Volume conversation coefficient [0,+inf]
psb->m_cfg.kDF = m_cci.m_soft_kDF; // Dynamic friction coefficient [0,1]
psb->m_cfg.kMT = m_cci.m_soft_kMT; // Pose matching coefficient [0,1]
psb->m_cfg.kCHR = m_cci.m_soft_kCHR; // Rigid contacts hardness [0,1]
psb->m_cfg.kKHR = m_cci.m_soft_kKHR; // Kinetic contacts hardness [0,1]
psb->m_cfg.kSHR = m_cci.m_soft_kSHR; // Soft contacts hardness [0,1]
psb->m_cfg.kAHR = m_cci.m_soft_kAHR; // Anchors hardness [0,1]
if (m_cci.m_gamesoftFlag & CCD_BSB_BENDING_CONSTRAINTS) {
psb->generateBendingConstraints(m_cci.m_softBendingDistance, pm);
}
psb->m_cfg.piterations = m_cci.m_soft_piterations;
psb->m_cfg.viterations = m_cci.m_soft_viterations;
psb->m_cfg.diterations = m_cci.m_soft_diterations;
psb->m_cfg.citerations = m_cci.m_soft_citerations;
if (m_cci.m_gamesoftFlag & CCD_BSB_SHAPE_MATCHING) {
psb->setPose(false, true);
}
else {
psb->setPose(true, false);
}
psb->randomizeConstraints();
if (m_cci.m_soft_collisionflags & (CCD_BSB_COL_CL_RS + CCD_BSB_COL_CL_SS)) {
psb->generateClusters(m_cci.m_soft_numclusteriterations);
}
psb->setTotalMass(m_cci.m_mass);
psb->setCollisionFlags(0);
///create a mapping between graphics mesh vertices and soft body vertices
{
RAS_MeshObject *rasMesh = GetShapeInfo()->GetMesh();
if (rasMesh && !m_softbodyMappingDone) {
RAS_MeshMaterial *mmat;
//for each material
for (int m = 0; m < rasMesh->NumMaterials(); m++) {
mmat = rasMesh->GetMeshMaterial(m);
RAS_IDisplayArray *array = mmat->GetDisplayArray();
for (unsigned int i = 0, size = array->GetVertexCount(); i < size; ++i) {
RAS_IVertex *vertex = array->GetVertex(i);
RAS_VertexInfo& vertexInfo = array->GetVertexInfo(i);
//search closest index, and store it in vertex
vertexInfo.setSoftBodyIndex(0);
btScalar maxDistSqr = 1e30;
btSoftBody::tNodeArray& nodes(psb->m_nodes);
btVector3 xyz = ToBullet(vertex->xyz());
for (int n = 0; n < nodes.size(); n++) {
btScalar distSqr = (nodes[n].m_x - xyz).length2();
if (distSqr < maxDistSqr) {
maxDistSqr = distSqr;
vertexInfo.setSoftBodyIndex(n);
}
}
}
}
}
}
m_softbodyMappingDone = true;
btTransform startTrans;
m_bulletMotionState->getWorldTransform(startTrans);
m_MotionState->SetWorldPosition(ToMoto(startTrans.getOrigin()));
m_MotionState->SetWorldOrientation(MT_Quaternion(0.0f, 0.0f, 0.0f, 1.0f));
if (!m_prototypeTransformInitialized) {
m_prototypeTransformInitialized = true;
m_softBodyTransformInitialized = true;
psb->transform(startTrans);
}
m_object->setCollisionFlags(m_object->getCollisionFlags() | m_cci.m_collisionFlags);
if (m_cci.m_do_anisotropic)
m_object->setAnisotropicFriction(m_cci.m_anisotropicFriction);
return true;
}
bool CcdPhysicsController::CreateCharacterController()
{
if (!m_cci.m_bCharacter)
return false;
m_object = new btPairCachingGhostObject();
m_object->setCollisionShape(m_collisionShape);
m_object->setCollisionFlags(btCollisionObject::CF_CHARACTER_OBJECT);
btTransform trans;
m_bulletMotionState->getWorldTransform(trans);
m_object->setWorldTransform(trans);
m_characterController = new BlenderBulletCharacterController(this, m_bulletMotionState, (btPairCachingGhostObject *)m_object,
(btConvexShape *)m_collisionShape, m_cci.m_stepHeight);
m_characterController->setJumpSpeed(m_cci.m_jumpSpeed);
m_characterController->setFallSpeed(m_cci.m_fallSpeed);
m_characterController->setMaxJumps(m_cci.m_maxJumps);
return true;
}
void CcdPhysicsController::CreateRigidbody()
{
//btTransform trans = GetTransformFromMotionState(m_MotionState);
m_bulletMotionState = new BlenderBulletMotionState(m_MotionState);
///either create a btCollisionObject, btRigidBody or btSoftBody
if (CreateSoftbody() || CreateCharacterController())
// soft body created, done
return;
//create a rgid collision object
btRigidBody::btRigidBodyConstructionInfo rbci(m_cci.m_mass, m_bulletMotionState, m_collisionShape, m_cci.m_localInertiaTensor * m_cci.m_inertiaFactor);
rbci.m_linearDamping = m_cci.m_linearDamping;
rbci.m_angularDamping = m_cci.m_angularDamping;
rbci.m_friction = m_cci.m_friction;
rbci.m_rollingFriction = m_cci.m_rollingFriction;
rbci.m_restitution = m_cci.m_restitution;
m_object = new btRigidBody(rbci);
//
// init the rigidbody properly
//
//setMassProps this also sets collisionFlags
//convert collision flags!
//special case: a near/radar sensor controller should not be defined static or it will
//generate loads of static-static collision messages on the console
if (m_cci.m_bSensor) {
// reset the flags that have been set so far
GetCollisionObject()->setCollisionFlags(0);
// sensor must never go to sleep: they need to detect continously
GetCollisionObject()->setActivationState(DISABLE_DEACTIVATION);
}
GetCollisionObject()->setCollisionFlags(m_object->getCollisionFlags() | m_cci.m_collisionFlags);
btRigidBody *body = GetRigidBody();
if (body) {
body->setGravity(m_cci.m_gravity);
body->setDamping(m_cci.m_linearDamping, m_cci.m_angularDamping);
if (!m_cci.m_bRigid) {
body->setAngularFactor(0.0f);
}
// use bullet's default contact processing theshold, blender's old default of 1 is too small here.
// if there's really a need to change this, it should be exposed in the ui first.
// body->setContactProcessingThreshold(m_cci.m_contactProcessingThreshold);
body->setSleepingThresholds(gLinearSleepingTreshold, gAngularSleepingTreshold);
}
if (m_object && m_cci.m_do_anisotropic) {
m_object->setAnisotropicFriction(m_cci.m_anisotropicFriction);
}
}
MT_Vector3 CcdPhysicsController::GetGravity()
{
MT_Vector3 gravity(0.0f, 0.0f, 0.0f);
btRigidBody *body = GetRigidBody();
if (body) {
return ToMoto(body->getGravity());
}
return gravity;
}
void CcdPhysicsController::SetGravity(const MT_Vector3 &gravity)
{
btRigidBody *body = GetRigidBody();
if (body) {
body->setGravity(ToBullet(gravity));
}
}
static void DeleteBulletShape(btCollisionShape *shape, bool free)
{
if (shape->getShapeType() == SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE) {
/* If we use Bullet scaled shape (btScaledBvhTriangleMeshShape) we have to
* free the child of the unscaled shape (btTriangleMeshShape) here.
*/
btTriangleMeshShape *meshShape = ((btScaledBvhTriangleMeshShape *)shape)->getChildShape();
if (meshShape)
delete meshShape;
}
if (free) {
delete shape;
}
}
bool CcdPhysicsController::DeleteControllerShape()
{
if (m_collisionShape) {
// collision shape is always unique to the controller, can delete it here
if (m_collisionShape->isCompound()) {
// bullet does not delete the child shape, must do it here
btCompoundShape *compoundShape = (btCompoundShape *)m_collisionShape;
int numChild = compoundShape->getNumChildShapes();
for (int i = numChild - 1; i >= 0; i--) {
btCollisionShape *childShape = compoundShape->getChildShape(i);
DeleteBulletShape(childShape, true);
}
}
DeleteBulletShape(m_collisionShape, true);
return true;
}
return false;
}
bool CcdPhysicsController::ReplaceControllerShape(btCollisionShape *newShape)
{
if (m_collisionShape)
DeleteControllerShape();
// If newShape is nullptr it means to create a new Bullet shape.
if (!newShape)
newShape = m_shapeInfo->CreateBulletShape(m_cci.m_margin, m_cci.m_bGimpact, !m_cci.m_bSoft);
m_object->setCollisionShape(newShape);
m_collisionShape = newShape;
m_cci.m_collisionShape = newShape;
btSoftBody *softBody = GetSoftBody();
if (softBody) {
btSoftRigidDynamicsWorld *world = GetPhysicsEnvironment()->GetDynamicsWorld();
// remove the old softBody
world->removeSoftBody(softBody);
// soft body must be recreated
delete m_object;
m_object = nullptr;
// force complete reinitialization
m_softbodyMappingDone = false;
m_prototypeTransformInitialized = false;
m_softBodyTransformInitialized = false;
CreateSoftbody();
BLI_assert(m_object);
btSoftBody *newSoftBody = GetSoftBody();
// set the user
newSoftBody->setUserPointer(this);
// add the new softbody
world->addSoftBody(newSoftBody);
}
return true;
}
CcdPhysicsController::~CcdPhysicsController()
{
//will be reference counted, due to sharing
if (m_cci.m_physicsEnv)
m_cci.m_physicsEnv->RemoveCcdPhysicsController(this, true);
if (m_MotionState)
delete m_MotionState;
if (m_bulletMotionState)
delete m_bulletMotionState;
if (m_characterController)
delete m_characterController;
delete m_object;
DeleteControllerShape();
if (m_shapeInfo) {
m_shapeInfo->Release();
}
}
void CcdPhysicsController::SimulationTick(float timestep)
{
btRigidBody *body = GetRigidBody();
if (!body || body->isStaticObject())
return;
// Clamp linear velocity
if (m_cci.m_clamp_vel_max > 0.0f || m_cci.m_clamp_vel_min > 0.0f) {
const btVector3 &linvel = body->getLinearVelocity();
btScalar len = linvel.length();
if (m_cci.m_clamp_vel_max > 0.0f && len > m_cci.m_clamp_vel_max)
body->setLinearVelocity(linvel * (m_cci.m_clamp_vel_max / len));
else if (m_cci.m_clamp_vel_min > 0.0f && !btFuzzyZero(len) && len < m_cci.m_clamp_vel_min)
body->setLinearVelocity(linvel * (m_cci.m_clamp_vel_min / len));
}
// Clamp angular velocity
if (m_cci.m_clamp_angvel_max > 0.0f || m_cci.m_clamp_angvel_min > 0.0f) {
const btVector3 &angvel = body->getAngularVelocity();
btScalar len = angvel.length();
if (m_cci.m_clamp_angvel_max > 0.0f && len > m_cci.m_clamp_angvel_max)
body->setAngularVelocity(angvel * (m_cci.m_clamp_angvel_max / len));
else if (m_cci.m_clamp_angvel_min > 0.0f && !btFuzzyZero(len) && len < m_cci.m_clamp_angvel_min)
body->setAngularVelocity(angvel * (m_cci.m_clamp_angvel_min / len));
}
}
/**
* SynchronizeMotionStates ynchronizes dynas, kinematic and deformable entities (and do 'late binding')
*/
bool CcdPhysicsController::SynchronizeMotionStates(float time)
{
//sync non-static to motionstate, and static from motionstate (todo: add kinematic etc.)
btSoftBody *sb = GetSoftBody();
if (sb) {
if (sb->m_pose.m_bframe) {
btVector3 worldPos = sb->m_pose.m_com;
btQuaternion worldquat;
btMatrix3x3 trs = sb->m_pose.m_rot * sb->m_pose.m_scl;
trs.getRotation(worldquat);
m_MotionState->SetWorldPosition(ToMoto(worldPos));
m_MotionState->SetWorldOrientation(ToMoto(worldquat));
}
else {
btVector3 aabbMin, aabbMax;
sb->getAabb(aabbMin, aabbMax);
btVector3 worldPos = (aabbMax + aabbMin) * 0.5f;
m_MotionState->SetWorldPosition(ToMoto(worldPos));
}
m_MotionState->CalculateWorldTransformations();
return true;
}
btRigidBody *body = GetRigidBody();
if (body && !body->isStaticObject()) {
const btTransform& xform = body->getCenterOfMassTransform();
const btMatrix3x3& worldOri = xform.getBasis();
const btVector3& worldPos = xform.getOrigin();
m_MotionState->SetWorldOrientation(ToMoto(worldOri));
m_MotionState->SetWorldPosition(ToMoto(worldPos));
m_MotionState->CalculateWorldTransformations();
}
const MT_Vector3& scale = m_MotionState->GetWorldScaling();
GetCollisionShape()->setLocalScaling(ToBullet(scale));
return true;
}
/**
* WriteMotionStateToDynamics synchronizes dynas, kinematic and deformable entities (and do 'late binding')
*/
void CcdPhysicsController::WriteMotionStateToDynamics(bool nondynaonly)
{
btTransform xform = CcdPhysicsController::GetTransformFromMotionState(m_MotionState);
SetCenterOfMassTransform(xform);
}
void CcdPhysicsController::WriteDynamicsToMotionState()
{
}
// controller replication
void CcdPhysicsController::PostProcessReplica(class PHY_IMotionState *motionstate, class PHY_IPhysicsController *parentctrl)
{
SetParentCtrl((CcdPhysicsController *)parentctrl);
m_softBodyTransformInitialized = false;
m_MotionState = motionstate;
m_registerCount = 0;
m_collisionShape = nullptr;
// Clear all old constraints.
m_ccdConstraintRefs.clear();
// always create a new shape to avoid scaling bug
if (m_shapeInfo) {
m_shapeInfo->AddRef();
m_collisionShape = m_shapeInfo->CreateBulletShape(m_cci.m_margin, m_cci.m_bGimpact, !m_cci.m_bSoft);
if (m_collisionShape) {
// new shape has no scaling, apply initial scaling
//m_collisionShape->setMargin(m_cci.m_margin);
m_collisionShape->setLocalScaling(m_cci.m_scaling);
if (m_cci.m_mass)
m_collisionShape->calculateLocalInertia(m_cci.m_mass, m_cci.m_localInertiaTensor);
}
}
// load some characterists that are not
btRigidBody *oldbody = GetRigidBody();
m_object = 0;
CreateRigidbody();
btRigidBody *body = GetRigidBody();
if (body) {
if (m_cci.m_mass) {
body->setMassProps(m_cci.m_mass, m_cci.m_localInertiaTensor * m_cci.m_inertiaFactor);
}
if (oldbody) {
body->setLinearFactor(oldbody->getLinearFactor());
body->setAngularFactor(oldbody->getAngularFactor());
if (oldbody->getActivationState() == DISABLE_DEACTIVATION)
body->setActivationState(DISABLE_DEACTIVATION);
}
}
// sensor object are added when needed
if (!m_cci.m_bSensor)
m_cci.m_physicsEnv->AddCcdPhysicsController(this);
}
void CcdPhysicsController::SetPhysicsEnvironment(class PHY_IPhysicsEnvironment *env)
{
// can safely assume CCD environment
CcdPhysicsEnvironment *physicsEnv = static_cast<CcdPhysicsEnvironment *>(env);
if (m_cci.m_physicsEnv != physicsEnv) {
// since the environment is changing, we must also move the controler to the
// new environment. Note that we don't handle sensor explicitly: this
// function can be called on sensor but only when they are not registered
if (m_cci.m_physicsEnv->RemoveCcdPhysicsController(this, true))
{
physicsEnv->AddCcdPhysicsController(this);
// Set the object to be active so it can at least by evaluated once.
// This fixes issues with static objects not having their physics meshes
// in the right spot when lib loading.
this->GetCollisionObject()->setActivationState(ACTIVE_TAG);
}
m_cci.m_physicsEnv = physicsEnv;
}
}
void CcdPhysicsController::SetCenterOfMassTransform(btTransform& xform)
{
btRigidBody *body = GetRigidBody();
if (body) {
body->setCenterOfMassTransform(xform);
}
else {
//either collision object or soft body?
if (GetSoftBody()) {
}
else {
if (m_object->isStaticOrKinematicObject()) {
m_object->setInterpolationWorldTransform(m_object->getWorldTransform());
}
else {
m_object->setInterpolationWorldTransform(xform);
}
m_object->setWorldTransform(xform);
}
}
}
// kinematic methods
void CcdPhysicsController::RelativeTranslate(const MT_Vector3& dlocin, bool local)
{
if (m_object) {
m_object->activate(true);
if (m_object->isStaticObject()) {
if (!m_cci.m_bSensor)
m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
// kinematic object should not set the transform, it disturbs the velocity interpolation
return;
}
btVector3 dloc = ToBullet(dlocin);
btTransform xform = m_object->getWorldTransform();
if (local)
dloc = xform.getBasis() * dloc;
xform.setOrigin(xform.getOrigin() + dloc);
SetCenterOfMassTransform(xform);
}
}
void CcdPhysicsController::RelativeRotate(const MT_Matrix3x3& rotval, bool local)
{
if (m_object) {
m_object->activate(true);
if (m_object->isStaticObject()) {
if (!m_cci.m_bSensor)
m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
// kinematic object should not set the transform, it disturbs the velocity interpolation
return;
}
btMatrix3x3 drotmat = ToBullet(rotval);
btMatrix3x3 currentOrn;
GetWorldOrientation(currentOrn);
btTransform xform = m_object->getWorldTransform();
xform.setBasis(xform.getBasis() * (local ?
drotmat : (currentOrn.inverse() * drotmat * currentOrn)));
SetCenterOfMassTransform(xform);
}
}
void CcdPhysicsController::GetWorldOrientation(btMatrix3x3& mat)
{
const MT_Matrix3x3 ori = m_MotionState->GetWorldOrientation();
mat = ToBullet(ori);
}
MT_Matrix3x3 CcdPhysicsController::GetOrientation()
{
const btMatrix3x3 orn = m_object->getWorldTransform().getBasis();
return ToMoto(orn);
}
void CcdPhysicsController::SetOrientation(const MT_Matrix3x3& orn)
{
SetWorldOrientation(ToBullet(orn));
}
void CcdPhysicsController::SetWorldOrientation(const btMatrix3x3& orn)
{
if (m_object) {
m_object->activate(true);
if (m_object->isStaticObject() && !m_cci.m_bSensor) {
m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
}
btTransform xform = m_object->getWorldTransform();
xform.setBasis(orn);
SetCenterOfMassTransform(xform);
//only once!
if (!m_softBodyTransformInitialized && GetSoftBody()) {
m_softbodyStartTrans.setBasis(orn);
xform.setOrigin(m_softbodyStartTrans.getOrigin());
GetSoftBody()->transform(xform);
m_softBodyTransformInitialized = true;
}
}
}
void CcdPhysicsController::SetPosition(const MT_Vector3& pos)
{
if (m_object) {
m_object->activate(true);
if (m_object->isStaticObject()) {
if (!m_cci.m_bSensor)
m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
// kinematic object should not set the transform, it disturbs the velocity interpolation
return;
}
// not required, this function is only used to update the physic controller
//m_MotionState->setWorldPosition(posX,posY,posZ);
btTransform xform = m_object->getWorldTransform();
xform.setOrigin(ToBullet(pos));
SetCenterOfMassTransform(xform);
if (!m_softBodyTransformInitialized)
m_softbodyStartTrans.setOrigin(xform.getOrigin());
// not required
//m_bulletMotionState->setWorldTransform(xform);
}
}
void CcdPhysicsController::ForceWorldTransform(const btMatrix3x3& mat, const btVector3& pos)
{