-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathphysics.cc
2027 lines (1822 loc) · 72.2 KB
/
physics.cc
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
// #include "DirectXMath.h"
/* #include "PhysX/physx/include/geometry/PxMeshQuery.h"
#include "geometry/PxCapsuleGeometry.h"
#include "foundation/PxTransform.h"
*/
#include "physics.h"
#include <string>
#include <iostream>
using namespace physx;
SimulationEventCallback2::SimulationEventCallback2() {}
SimulationEventCallback2::~SimulationEventCallback2() {}
void SimulationEventCallback2::onConstraintBreak(PxConstraintInfo *constraints, PxU32 count) {}
void SimulationEventCallback2::onWake(PxActor **actors, PxU32 count) {}
void SimulationEventCallback2::onSleep(PxActor **actors, PxU32 count) {}
void SimulationEventCallback2::onContact(const PxContactPairHeader& pairHeader, const PxContactPair* pairs, PxU32 nbPairs) {
PxActor *actor1 = pairHeader.actors[0];
PxActor *actor2 = pairHeader.actors[1];
unsigned int actor1Id = (unsigned int)actor1->userData;
unsigned int actor2Id = (unsigned int)actor2->userData;
stateBitfields[actor1Id] |= STATE_BITFIELD::STATE_BITFIELD_COLLIDED;
stateBitfields[actor2Id] |= STATE_BITFIELD::STATE_BITFIELD_COLLIDED;
for (uint32_t i = 0; i < nbPairs; i++) {
const PxContactPair &pair = pairs[i];
PxContactPairPoint contactPairPoints[32];
uint32_t numPoints = pair.extractContacts(contactPairPoints, sizeof(contactPairPoints) / sizeof(contactPairPoints[0]));
for (uint32_t j = 0; j < numPoints; j++) {
PxContactPairPoint &contactPairPoint = contactPairPoints[j];
if (contactPairPoint.normal.y >= 0.0001) { // from B to A is up
stateBitfields[actor1Id] |= STATE_BITFIELD::STATE_BITFIELD_GROUNDED;
}
if (contactPairPoint.normal.y <= -0.0001) { // from B to A is down
stateBitfields[actor2Id] |= STATE_BITFIELD::STATE_BITFIELD_GROUNDED;
}
}
}
/* PxContactPairPoint contactPoints[32];
auto numPoints = pairs->extractContacts(contactPoints, sizeof(contactPoints)/sizeof(contactPoints[0]));
for (auto i = 0; i < numPoints; i++) {
const PxContactPairPoint &contactPint = contactPoints[i];
} */
// std::cerr << "on contact" << std::endl;
}
void SimulationEventCallback2::onTrigger(PxTriggerPair *pairs, PxU32 count) {
this->triggerCount = count;
for (unsigned int i = 0; i < count; i++) {
TriggerEventInfo triggerEventInfo;
triggerEventInfo.status = pairs[i].status;
triggerEventInfo.triggerActorId = (unsigned int)pairs[i].triggerActor->userData;
triggerEventInfo.otherActorId = (unsigned int)pairs[i].otherActor->userData;
triggerEventInfos[i] = triggerEventInfo;
}
}
void SimulationEventCallback2::onAdvance(const PxRigidBody *const *bodyBuffer, const PxTransform *poseBuffer, const PxU32 count) {}
/*
CharacterControllerFilterCallback
This filters collisions for the character capsule and character skeletons
*/
CharacterControllerFilterCallback::CharacterControllerFilterCallback() {}
CharacterControllerFilterCallback::~CharacterControllerFilterCallback() {}
PxQueryHitType::Enum CharacterControllerFilterCallback::preFilter(
const PxFilterData &filterData,
const PxShape *shape,
const PxRigidActor *actor,
PxHitFlags &queryFlags
) {
const PxFilterData &filterDataShape = shape->getSimulationFilterData();
if (
(filterDataShape.word2 == 2) || // this is an avatar capsule
(filterDataShape.word3 == 3) // this is a skeleton bone
) {
return PxQueryHitType::eNONE; // do not collide
} else {
return PxQueryHitType::eBLOCK; // maybe collide
}
}
PxQueryHitType::Enum CharacterControllerFilterCallback::postFilter(const PxFilterData &filterData, const PxQueryHit &hit) {
// should never hit this since we are not using the postFilter flag
std::cerr << "CharacterControllerFilterCallback::postFilter not implemented!" << std::endl;
abort();
return PxQueryHitType::eNONE;
}
PxFilterFlags ccdFilterShader(
PxFilterObjectAttributes attributes0,
PxFilterData filterData0,
PxFilterObjectAttributes attributes1,
PxFilterData filterData1,
PxPairFlags& pairFlags,
const void* constantBlock,
PxU32 constantBlockSize
) {
PxFilterFlags result = physx::PxDefaultSimulationFilterShader(
attributes0,
filterData0,
attributes1,
filterData1,
pairFlags,
constantBlock,
constantBlockSize
);
if (
(filterData0.word2 == 2 || filterData1.word2 == 2) && // one of the objects is an avatar capsule
(filterData0.word3 == 3 || filterData1.word3 == 3) // one of the objects is a skeleton bone
) {
// do not colide
pairFlags &= ~PxPairFlag::eSOLVE_CONTACT;
pairFlags &= ~PxPairFlag::eNOTIFY_TOUCH_FOUND;
pairFlags &= ~PxPairFlag::eDETECT_DISCRETE_CONTACT;
pairFlags &= ~PxPairFlag::eDETECT_CCD_CONTACT;
} else {
// maybe colide
pairFlags |= PxPairFlag::eSOLVE_CONTACT;
pairFlags |= PxPairFlag::eNOTIFY_TOUCH_FOUND;
pairFlags |= PxPairFlag::eDETECT_DISCRETE_CONTACT;
pairFlags |= PxPairFlag::eDETECT_CCD_CONTACT;
}
/* if (filterData0.word1 == TYPE::TYPE_CAPSULE || filterData1.word1 == TYPE::TYPE_CAPSULE) {
pairFlags |= PxPairFlag::eNOTIFY_TOUCH_FOUND;
pairFlags |= PxPairFlag::eNOTIFY_TOUCH_PERSISTS;
pairFlags |= PxPairFlag::eNOTIFY_CONTACT_POINTS;
} */
return result;
}
enum PhysicsObjectFlags {
NONE = 0,
ENABLE_PHYSICS = 1,
ENABLE_CCD = 2,
};
//
constexpr size_t maxNumTouches = 32;
class OverlapCallback : public PxOverlapCallback {
public:
PxOverlapHit touches[maxNumTouches];
std::deque<PxOverlapHit> hits;
OverlapCallback() :
PxOverlapCallback(touches, maxNumTouches)
{
// hits.reserve(maxNumTouches);
}
PxAgain processTouches(const PxOverlapHit *buffer, PxU32 nbHits) {
for (PxU32 i = 0; i < nbHits; i++) {
hits.push_back(buffer[i]);
}
return hits.size() < maxNumTouches;
// return true;
// return false; // do not continue
}
};
class PenetrationDepth {
public:
PxRigidActor *actor;
PxVec3 direction;
float depth;
};
//
PScene::PScene() {
// tolerancesScale.length = 0.01;
{
// PxTolerancesScale tolerancesScale;
physics = PxCreatePhysics(PX_PHYSICS_VERSION, *(physicsBase->foundation), physicsBase->tolerancesScale);
}
{
simulationEventCallback = new SimulationEventCallback2();
}
{
// PxTolerancesScale tolerancesScale;
PxSceneDesc sceneDesc = PxSceneDesc(physicsBase->tolerancesScale);
sceneDesc.gravity = PxVec3(0.0f, -9.8f, 0.0f);
sceneDesc.flags |= PxSceneFlag::eENABLE_ACTIVE_ACTORS;
sceneDesc.flags |= PxSceneFlag::eENABLE_CCD;
sceneDesc.broadPhaseType = PxBroadPhaseType::eABP;
sceneDesc.simulationEventCallback = simulationEventCallback;
if (!sceneDesc.cpuDispatcher) {
physx::PxDefaultCpuDispatcher* mCpuDispatcher = physx::PxDefaultCpuDispatcherCreate(0);
if (!mCpuDispatcher) {
std::cerr << "PxDefaultCpuDispatcherCreate failed!" << std::endl;
}
sceneDesc.cpuDispatcher = mCpuDispatcher;
}
sceneDesc.filterShader = ccdFilterShader;
scene = physics->createScene(sceneDesc);
controllerManager = PxCreateControllerManager(*scene);
controllerManager->setOverlapRecoveryModule(true);
}
/* {
PxMaterial *material = physics->createMaterial(0.5f, 0.5f, 0.1f);
PxTransform transform(PxVec3(0, -10, 0));
PxCapsuleGeometry geometry(1, 1);
PxRigidDynamic *capsule = PxCreateDynamic(*physics, transform, geometry, *material, 1);
capsule->userData = (void *)0x1;
// capsule->setRigidDynamicFlag(PxRigidDynamicFlag::eKINEMATIC, true);
PxRigidBodyExt::updateMassAndInertia(*capsule, 1.0f);
scene->addActor(*capsule);
actors.push_back(capsule);
} */
/* {
PxMaterial *material = physics->createMaterial(0.5f, 0.5f, 0.1f);
PxTransform transform(PxVec3(0, -1, 0));
PxBoxGeometry geometry(30, 1, 30);
PxRigidStatic *floor = PxCreateStatic(*physics, transform, geometry, *material);
floor->userData = (void *)0x2;
scene->addActor(*floor);
actors.push_back(floor);
}
{
PxMaterial *material = physics->createMaterial(0.5f, 0.5f, 0.1f);
PxTransform transform(PxVec3(0, 5, 0));
PxBoxGeometry geometry(0.5, 0.5, 0.5);
PxRigidDynamic *box = PxCreateDynamic(*physics, transform, geometry, *material, 1);
box->userData = (void *)0x3;
PxRigidBodyExt::updateMassAndInertia(*box, 1.0f);
scene->addActor(*box);
actors.push_back(box);
} */
}
PScene::~PScene() {
std::cout << "scene destructor" << std::endl;
abort();
}
PxD6Joint *PScene::addJoint(unsigned int id1, unsigned int id2, float *position1, float *position2, float *quaternion1, float *quaternion2) {
PxRigidActor *actor1;
PxRigidActor *actor2;
PxRigidDynamic *body1;
PxRigidDynamic *body2;
auto actorIter1 = std::find_if(actors.begin(), actors.end(), [&](PxRigidActor *actor) -> bool {
return (unsigned int)actor->userData == id1;
});
if (actorIter1 != actors.end()) {
actor1 = *actorIter1;
body1 = dynamic_cast<PxRigidDynamic *>(actor1);
// std::cout << "add joint got id a" << id1 << std::endl;
} else {
std::cerr << "add joint unknown actor id a" << id1 << std::endl;
}
auto actorIter2 = std::find_if(actors.begin(), actors.end(), [&](PxRigidActor *actor) -> bool {
return (unsigned int)actor->userData == id2;
});
if (actorIter2 != actors.end()) {
actor2 = *actorIter2;
body2 = dynamic_cast<PxRigidDynamic *>(actor2);
// std::cout << "add joint got id b" << id2 << std::endl;
} else {
std::cerr << "add joint unknown actor id b" << id2 << std::endl;
}
// if (fixBody1) {
// body1->setRigidDynamicLockFlags(
// PxRigidDynamicLockFlag::eLOCK_LINEAR_X |
// PxRigidDynamicLockFlag::eLOCK_LINEAR_Y |
// PxRigidDynamicLockFlag::eLOCK_LINEAR_Z |
// PxRigidDynamicLockFlag::eLOCK_ANGULAR_X |
// PxRigidDynamicLockFlag::eLOCK_ANGULAR_Y |
// PxRigidDynamicLockFlag::eLOCK_ANGULAR_Z
// );
// }
PxTransform transform1(
PxVec3{position1[0], position1[1], position1[2]},
PxQuat{quaternion1[0], quaternion1[1], quaternion1[2], quaternion1[3]}
);
PxTransform transform2(
PxVec3{position2[0], position2[1], position2[2]},
PxQuat{quaternion2[0], quaternion2[1], quaternion2[2], quaternion2[3]}
);
PxD6Joint *joint = PxD6JointCreate(
*physics,
body1, transform1,
body2, transform2
);
return joint;
}
void PScene::setJointMotion(PxD6Joint *joint, PxD6Axis::Enum axis, PxD6Motion::Enum motion) {
joint->setMotion(axis, motion);
}
void PScene::setJointTwistLimit(PxD6Joint *joint, float lowerLimit, float upperLimit, float contactDist) {
joint->setTwistLimit(physx::PxJointAngularLimitPair(lowerLimit, upperLimit, contactDist));
}
void PScene::setJointSwingLimit(PxD6Joint *joint, float yLimitAngle, float zLimitAngle, float contactDist) {
joint->setSwingLimit(physx::PxJointLimitCone(yLimitAngle, zLimitAngle, contactDist));
}
bool PScene::updateMassAndInertia(unsigned int id, float shapeDensities) {
auto actorIter = std::find_if(actors.begin(), actors.end(), [&](PxRigidActor *actor) -> bool {
return (unsigned int)actor->userData == id;
});
if (actorIter != actors.end()) {
PxRigidActor *actor = *actorIter;
return PxRigidBodyExt::updateMassAndInertia(*(dynamic_cast<PxRigidBody *>(actor)), shapeDensities);
} else {
std::cerr << "updateMassAndInertia unknown actor id " << id << std::endl;
return false;
}
}
float PScene::getBodyMass(unsigned int id) {
auto actorIter = std::find_if(actors.begin(), actors.end(), [&](PxRigidActor *actor) -> bool {
return (unsigned int)actor->userData == id;
});
if (actorIter != actors.end()) {
PxRigidActor *actor = *actorIter;
return (dynamic_cast<PxRigidBody *>(actor))->getMass();
} else {
std::cerr << "getBodyMass unknown actor id " << id << std::endl;
return -1;
}
}
unsigned int PScene::simulate(unsigned int *ids, float *positions, float *quaternions, float *scales, unsigned int *stateBitfields, unsigned int numIds, float elapsedTime, float *velocities) {
for (unsigned int i = 0; i < numIds; i++) {
unsigned int id = ids[i];
//PxTransform transform(PxVec3(positions[i*3], positions[i*3+1], positions[i*3+2]), PxQuat(quaternions[i*4], quaternions[i*4+1], quaternions[i*4+2], quaternions[i*4+3]));
auto actorIter = std::find_if(actors.begin(), actors.end(), [&](PxRigidActor *actor) -> bool {
return (unsigned int)actor->userData == id;
});
if (actorIter != actors.end()) {
PxRigidActor *actor = *actorIter;
//actor->setGlobalPose(transform, true);
PxRigidDynamic *body = dynamic_cast<PxRigidDynamic *>(actor);
if (body) {
// std::cout << "reset" << std::endl;
body->setLinearVelocity(PxVec3(velocities[i*3], velocities[i*3+1], velocities[i*3+2]), true);
//body->setAngularVelocity(PxVec3(0, 0, 0), true);
// actor->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, true);
}
// actor->wakeUp();
} else {
std::cerr << "simulate unknown actor id " << id << std::endl;
}
}
simulationEventCallback->stateBitfields.clear();
scene->simulate(elapsedTime);
PxU32 error;
scene->fetchResults(true, &error);
if (error) {
std::cout << "scene simulate error " << error << std::endl;
}
PxU32 numActors;
PxRigidActor **actors = (PxRigidActor **)scene->getActiveActors(numActors);
for (unsigned int i = 0; i < numActors; i++) {
PxRigidActor *actor = actors[i];
const PxTransform &actor2World = actor->getGlobalPose();
const PxVec3 &p = actor2World.p;
const PxQuat &q = actor2World.q;
const unsigned int id = (unsigned int)actors[i]->userData;
ids[i] = id;
positions[i*3] = p.x;
positions[i*3+1] = p.y;
positions[i*3+2] = p.z;
quaternions[i*4] = q.x;
quaternions[i*4+1] = q.y;
quaternions[i*4+2] = q.z;
quaternions[i*4+3] = q.w;
{
PxVec3 s(1, 1, 1);
unsigned int numShapes = actor->getNbShapes();
if (numShapes == 1) {
PxShape *shapes[1];
actor->getShapes(shapes, sizeof(shapes)/sizeof(shapes[0]), 0);
PxShape *shape = shapes[0];
PxGeometryHolder geometryHolder = shape->getGeometry();
PxGeometryType::Enum geometryType = geometryHolder.getType();
switch (geometryType) {
case PxGeometryType::Enum::eBOX: {
const PxBoxGeometry &geometry = geometryHolder.box();
const PxVec3 &halfExtents = geometry.halfExtents;
s = halfExtents * 2;
break;
}
case PxGeometryType::Enum::eCONVEXMESH: {
PxConvexMeshGeometry &geometry = geometryHolder.convexMesh();
s = geometry.scale.scale;
break;
}
case PxGeometryType::Enum::eTRIANGLEMESH: {
PxTriangleMeshGeometry &geometry = geometryHolder.triangleMesh();
s = geometry.scale.scale;
break;
}
case PxGeometryType::Enum::eCAPSULE: {
PxCapsuleGeometry &geometry = geometryHolder.capsule();
s = PxVec3(geometry.radius * 2.0);
break;
}
default: {
std::cerr << "unknown geometry type for actor id " << id << " : " << (unsigned int)geometryType << std::endl;
break;
}
}
} else {
std::cerr << "no shapes for actor id " << id << " : " << numShapes << std::endl;
}
scales[i*3] = s.x;
scales[i*3+1] = s.y;
scales[i*3+2] = s.z;
// std::cout << "check bitfields 1" << std::endl;
stateBitfields[i] = simulationEventCallback->stateBitfields[id];
// std::cout << "check bitfields 2" << std::endl;
}
}
return numActors;
}
float PScene::setTrigger(unsigned int id) {
auto actorIter = std::find_if(actors.begin(), actors.end(), [&](PxRigidActor *actor) -> bool {
return (unsigned int)actor->userData == id;
});
if (actorIter != actors.end()) {
PxRigidActor *actor = *actorIter;
PxShape* shape;
actor->getShapes(&shape, 1);
shape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, false);
shape->setFlag(PxShapeFlag::eSCENE_QUERY_SHAPE, false);
shape->setFlag(PxShapeFlag::eTRIGGER_SHAPE, true);
return 1;
} else {
std::cerr << "setTrigger unknown actor id " << id << std::endl;
return -1;
}
}
unsigned int PScene::getTriggerEvents(unsigned int *scratchStack) {
unsigned int triggerCount = this->simulationEventCallback->triggerCount;
for (unsigned int i = 0; i < triggerCount; i++) {
scratchStack[i * 3 + 0] = this->simulationEventCallback->triggerEventInfos[i].status;
scratchStack[i * 3 + 1] = this->simulationEventCallback->triggerEventInfos[i].triggerActorId;
scratchStack[i * 3 + 2] = this->simulationEventCallback->triggerEventInfos[i].otherActorId;
}
// reset
this->simulationEventCallback->triggerCount = 0;
return triggerCount;
}
void PScene::addCapsuleGeometry(
float *position,
float *quaternion,
float radius,
float halfHeight,
unsigned int id,
PxMaterial *material,
unsigned int dynamic,
unsigned int flags
) {
PxTransform transform(PxVec3(position[0], position[1], position[2]), PxQuat(quaternion[0], quaternion[1], quaternion[2], quaternion[3]));
PxTransform relativePose(PxQuat(PxHalfPi, PxVec3(0,0,1)));
PxCapsuleGeometry geometry(radius, halfHeight);
// const bool physicsEnabled = (bool)(flags & PhysicsObjectFlags::ENABLE_PHYSICS);
const bool ccdEnabled = (bool)(flags & PhysicsObjectFlags::ENABLE_CCD);
PxRigidActor *actor;
if (dynamic) {
PxRigidDynamic *body = PxCreateDynamic(*physics, transform, geometry, *material, 1);
PxRigidBodyExt::updateMassAndInertia(*body, 1.0f);
if (ccdEnabled) {
body->setRigidBodyFlag(PxRigidBodyFlag::eENABLE_CCD, true);
}
actor = body;
} else {
PxRigidStatic *body = PxCreateStatic(*physics, transform, geometry, *material);
actor = body;
}
actor->userData = (void *)id;
scene->addActor(*actor);
actors.push_back(actor);
}
void PScene::addPlaneGeometry(float *position, float *quaternion, unsigned int id, PxMaterial *material, unsigned int dynamic) {
PxTransform transform(PxVec3(position[0], position[1], position[2]), PxQuat(quaternion[0], quaternion[1], quaternion[2], quaternion[3]));
PxPlaneGeometry geometry;
PxRigidActor *actor;
if (dynamic) {
PxRigidDynamic *plane = PxCreateDynamic(*physics, transform, geometry, *material, 1);
actor = plane;
} else {
PxRigidStatic *plane = PxCreateStatic(*physics, transform, geometry, *material);
actor = plane;
}
actor->userData = (void *)id;
scene->addActor(*actor);
actors.push_back(actor);
}
void PScene::addBoxGeometry(float *position, float *quaternion, float *size, unsigned int id, PxMaterial *material, unsigned int dynamic, int groupId) {
PxTransform transform(PxVec3(position[0], position[1], position[2]), PxQuat(quaternion[0], quaternion[1], quaternion[2], quaternion[3]));
PxBoxGeometry geometry(size[0], size[1], size[2]);
PxRigidActor *actor;
if (dynamic) {
PxRigidDynamic *box = PxCreateDynamic(*physics, transform, geometry, *material, 1);
PxRigidBodyExt::updateMassAndInertia(*box, 1.0f);
actor = box;
if (groupId != -1) {
// collision filter
unsigned int numShapes = box->getNbShapes();
if (numShapes == 1) {
PxShape *shapes[1];
box->getShapes(shapes, sizeof(shapes)/sizeof(shapes[0]), 0);
PxShape *shape = shapes[0];
PxFilterData filterData{};
filterData.word0 = groupId; // character id
filterData.word1 = groupId; // the unique bone id in the character
filterData.word3 = 3; // signal this is a character skeleton bone; used during filtering
shape->setSimulationFilterData(filterData);
} else {
std::cerr << "unexpected number of shapes: " << numShapes << std::endl;
}
}
} else {
PxRigidStatic *box = PxCreateStatic(*physics, transform, geometry, *material);
actor = box;
}
actor->userData = (void *)id;
scene->addActor(*actor);
actors.push_back(actor);
}
PxTriangleMesh *PScene::createShape(uint8_t *data, unsigned int length, PxDefaultMemoryOutputStream *releaseWriteStream) {
PxDefaultMemoryInputData readBuffer(data, length);
PxTriangleMesh *triangleMesh = physics->createTriangleMesh(readBuffer);
if (releaseWriteStream) {
delete releaseWriteStream;
}
return triangleMesh;
}
void PScene::destroyShape(PxTriangleMesh *triangleMesh) {
triangleMesh->release();
}
PxConvexMesh *PScene::createConvexShape(uint8_t *data, unsigned int length, PxDefaultMemoryOutputStream *releaseWriteStream) {
PxDefaultMemoryInputData readBuffer(data, length);
PxConvexMesh *convexMesh = physics->createConvexMesh(readBuffer);
if (releaseWriteStream) {
delete releaseWriteStream;
}
return convexMesh;
}
void PScene::destroyConvexShape(PxConvexMesh *convexMesh) {
convexMesh->release();
}
PxHeightField *PScene::createHeightField(uint8_t *data, unsigned int length, PxDefaultMemoryOutputStream *releaseWriteStream) {
PxDefaultMemoryInputData readBuffer(data, length);
PxHeightField *heightfield = physics->createHeightField(readBuffer);
if (releaseWriteStream) {
delete releaseWriteStream;
}
return heightfield;
}
PxMaterial *PScene::createMaterial(float *mat) {
PxMaterial *material = physics->createMaterial(mat[0], mat[1], mat[2]);
return material;
}
void PScene::destroyMaterial(PxMaterial *material) {
material->release();
}
void PScene::addGeometry(PxTriangleMesh *triangleMesh, float *position, float *quaternion, float *scale, unsigned int id, PxMaterial *material, unsigned int external, PxTriangleMesh *relaseTriangleMesh) {
// have acquire and unacquire arg here to avoid the memory leak
// the argument can be called "external" because it is not owned by the scene
PxTransform transform(PxVec3(position[0], position[1], position[2]), PxQuat(quaternion[0], quaternion[1], quaternion[2], quaternion[3]));
PxMeshScale scaleObject(PxVec3(scale[0], scale[1], scale[2]));
if (external != 0) {
triangleMesh->acquireReference();
}
PxTriangleMeshGeometry geometry(triangleMesh, scaleObject);
PxRigidStatic *mesh = PxCreateStatic(*physics, transform, geometry, *material);
mesh->userData = (void *)id;
scene->addActor(*mesh);
actors.push_back(mesh);
if (relaseTriangleMesh != nullptr) {
relaseTriangleMesh->release();
}
}
void PScene::addConvexGeometry(PxConvexMesh *convexMesh, float *position, float *quaternion, float *scale, unsigned int id, PxMaterial *material, unsigned int dynamic, unsigned int external, PxConvexMesh *releaseConvexMesh) {
PxTransform transform(PxVec3(position[0], position[1], position[2]), PxQuat(quaternion[0], quaternion[1], quaternion[2], quaternion[3]));
PxMeshScale scaleObject(PxVec3(scale[0], scale[1], scale[2]));
if (external != 0) {
convexMesh->acquireReference();
}
PxConvexMeshGeometry geometry(convexMesh, scaleObject);
PxRigidActor *mesh;
if (dynamic) {
mesh = PxCreateDynamic(*physics, transform, geometry, *material, 1);
} else {
mesh = PxCreateStatic(*physics, transform, geometry, *material);
}
mesh->userData = (void *)id;
scene->addActor(*mesh);
actors.push_back(mesh);
if (releaseConvexMesh != nullptr) {
releaseConvexMesh->release();
}
}
void PScene::addHeightFieldGeometry(
PxHeightField *heightField,
float *position,
float *quaternion,
float *scale,
float heightScale,
float rowScale,
float columnScale,
unsigned int id,
PxMaterial *material,
unsigned int dynamic,
unsigned int external,
PxHeightField *releaseHeightField
) {
PxTransform transform(
PxVec3(position[0], position[1], position[2]),
PxQuat(quaternion[0], quaternion[1], quaternion[2], quaternion[3])
);
PxHeightFieldGeometry geometry(
heightField,
PxMeshGeometryFlags(),
heightScale * scale[1],
rowScale * scale[0],
columnScale * scale[2]
);
PxRigidActor *mesh;
if (dynamic) {
mesh = PxCreateDynamic(*physics, transform, geometry, *material, 1);
} else {
mesh = PxCreateStatic(*physics, transform, geometry, *material);
}
mesh->userData = (void *)id;
scene->addActor(*mesh);
actors.push_back(mesh);
}
void PScene::enableActor(unsigned int id) {
auto actorIter = std::find_if(actors.begin(), actors.end(), [&](PxRigidActor *actor) -> bool {
return (unsigned int)actor->userData == id;
});
if (actorIter != actors.end()) {
PxRigidActor *actor = *actorIter;
PxScene *actorScene = actor->getScene();
if (actorScene == nullptr) {
scene->addActor(*actor);
} else {
std::cerr << "enable physics actor already had a scene " << id << std::endl;
}
} else {
std::cerr << "enable unknown actor id " << id << std::endl;
}
}
void PScene::disableActor(unsigned int id) {
auto actorIter = std::find_if(actors.begin(), actors.end(), [&](PxRigidActor *actor) -> bool {
return (unsigned int)actor->userData == id;
});
if (actorIter != actors.end()) {
PxRigidActor *actor = *actorIter;
PxScene *actorScene = actor->getScene();
if (actorScene != nullptr) {
actorScene->removeActor(*actor);
} else {
std::cerr << "disable physics actor id had no scene " << id << std::endl;
}
} else {
std::cerr << "disable physics actor id " << id << std::endl;
}
}
void PScene::disableGeometry(unsigned int id) {
auto actorIter = std::find_if(actors.begin(), actors.end(), [&](PxRigidActor *actor) -> bool {
return (unsigned int)actor->userData == id;
});
if (actorIter != actors.end()) {
PxRigidActor *actor = *actorIter;
// actor->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, true);
PxRigidBody *body = dynamic_cast<PxRigidBody *>(actor);
/* if (body) {
body->setLinearVelocity(PxVec3(0, 0, 0), false);
body->setAngularVelocity(PxVec3(0, 0, 0), false);
} */
PxShape *shapes[32];
for (int j = 0;; j++) {
memset(shapes, 0, sizeof(shapes));
if (actor->getShapes(shapes, 32, j * 32) == 0) {
break;
}
for (int i = 0; i < 32; ++i) {
if (shapes[i] == nullptr) {
break;
}
PxShape *rigidShape = shapes[i];
rigidShape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, false);
}
}
} else {
std::cerr << "disable unknown actor id " << id << std::endl;
}
}
void PScene::enableGeometry(unsigned int id) {
auto actorIter = std::find_if(actors.begin(), actors.end(), [&](PxRigidActor *actor) -> bool {
return (unsigned int)actor->userData == id;
});
if (actorIter != actors.end()) {
PxRigidActor *actor = *actorIter;
// actor->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, false);
PxShape *shapes[32];
for (int j = 0; ; j++) {
memset(shapes, 0, sizeof(shapes));
if (actor->getShapes(shapes, 32, j * 32) == 0) {
break;
}
for (int i = 0; i < 32; ++i) {
if (shapes[i] == nullptr) {
break;
}
PxShape *rigidShape = shapes[i];
rigidShape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, true);
}
}
} else {
std::cerr << "enable unknown actor id " << id << std::endl;
}
}
void PScene::disableGeometryQueries(unsigned int id) {
auto actorIter = std::find_if(actors.begin(), actors.end(), [&](PxRigidActor *actor) -> bool {
return (unsigned int)actor->userData == id;
});
if (actorIter != actors.end()) {
PxRigidActor *actor = *actorIter;
constexpr int numShapes = 32;
PxShape *shapes[numShapes];
for (int j = 0; ; j++) {
memset(shapes, 0, sizeof(shapes));
if (actor->getShapes(shapes, numShapes, j * numShapes) == 0) {
break;
}
for (int i = 0; i < numShapes; ++i) {
if (shapes[i] == nullptr) {
break;
}
PxShape *rigidShape = shapes[i];
rigidShape->setFlag(PxShapeFlag::eSCENE_QUERY_SHAPE, false);
// std::cout << "disable queries for shape " << (unsigned int)actor->userData << " " << (uint32_t)rigidShape << " " << rigidShape->getFlags().isSet(PxShapeFlag::eSCENE_QUERY_SHAPE) << std::endl; // XXX
}
}
} else {
std::cerr << "disable queries unknown actor id " << id << std::endl;
}
}
void PScene::enableGeometryQueries(unsigned int id) {
auto actorIter = std::find_if(actors.begin(), actors.end(), [&](PxRigidActor *actor) -> bool {
return (unsigned int)actor->userData == id;
});
if (actorIter != actors.end()) {
PxRigidActor *actor = *actorIter;
constexpr int numShapes = 32;
PxShape *shapes[numShapes];
for (int j = 0; ; j++) {
memset(shapes, 0, sizeof(shapes));
if (actor->getShapes(shapes, numShapes, j * numShapes) == 0) {
break;
}
for (int i = 0; i < numShapes; ++i) {
if (shapes[i] == nullptr) {
break;
}
PxShape *rigidShape = shapes[i];
rigidShape->setFlag(PxShapeFlag::eSCENE_QUERY_SHAPE, true);
}
}
} else {
std::cerr << "enable queries unknown actor id " << id << std::endl;
}
}
void PScene::setTransform(unsigned int id, float *positions, float *quaternions, float *scales, bool autoWake) {
auto actorIter = std::find_if(actors.begin(), actors.end(), [&](PxRigidActor *actor) -> bool {
return (unsigned int)actor->userData == id;
});
if (actorIter != actors.end()) {
PxRigidActor *actor = *actorIter;
PxTransform transform(
PxVec3(positions[0], positions[1], positions[2]),
PxQuat(quaternions[0], quaternions[1], quaternions[2], quaternions[3])
);
actor->setGlobalPose(transform, autoWake);
} else {
std::cerr << "set transform unknown actor id " << id << std::endl;
}
}
void PScene::setGeometryScale(unsigned int id, float *scale, PxDefaultMemoryOutputStream *writeStream) {
auto actorIter = std::find_if(actors.begin(), actors.end(), [&](PxRigidActor *actor) -> bool {
return (unsigned int)actor->userData == id;
});
if (actorIter != actors.end()) {
PxRigidActor *actor = *actorIter;
PxShape *shape;
actor->getShapes(&shape, 1);
if (shape->getFlags().isSet(PxShapeFlag::eSCENE_QUERY_SHAPE)) {
PxGeometryHolder geometryHolder = shape->getGeometry();
PxGeometryType::Enum geometryType = geometryHolder.getType();
switch (geometryType) {
case PxGeometryType::Enum::eBOX: {
PxBoxGeometry &geometry = geometryHolder.box();
geometry.halfExtents = PxVec3( scale[0], scale[1], scale[2] ) / 2;
shape->setGeometry( geometryHolder.any() );
break;
}
case PxGeometryType::Enum::eCAPSULE: {
PxCapsuleGeometry &geometry = geometryHolder.capsule();
geometry.radius = (std::max)( (std::max)( scale[0], scale[1] ), scale[2] ) / 2;
shape->setGeometry( geometryHolder.any() );
break;
}
case PxGeometryType::Enum::eCONVEXMESH: {
PxConvexMeshGeometry &geometry = geometryHolder.convexMesh();
geometry.scale.scale = PxVec3( scale[0], scale[1], scale[2] );
shape->setGeometry( geometryHolder.any() );
break;
}
case PxGeometryType::Enum::eTRIANGLEMESH: {
geometryHolder.triangleMesh().triangleMesh->acquireReference();
geometryHolder.triangleMesh().scale.scale = PxVec3( scale[0], scale[1], scale[2] );
shape->setGeometry( geometryHolder.any() );
geometryHolder.triangleMesh().triangleMesh->release();
break;
}
case PxGeometryType::Enum::eINVALID:
case PxGeometryType::Enum::eSPHERE:
case PxGeometryType::Enum::ePLANE:
case PxGeometryType::Enum::eHEIGHTFIELD:
case PxGeometryType::Enum::eGEOMETRY_COUNT:
case PxGeometryType::Enum::ePARTICLESYSTEM:
case PxGeometryType::Enum::eTETRAHEDRONMESH:
case PxGeometryType::Enum::eHAIRSYSTEM:
case PxGeometryType::Enum::eCUSTOM:
{
break;
}
}
}
}
if (writeStream) {
delete writeStream;
}
}
void PScene::getGlobalPosition(unsigned int id, float *positions) {
auto actorIter = std::find_if(actors.begin(), actors.end(), [&](PxRigidActor *actor) -> bool {
return (unsigned int)actor->userData == id;
});
if (actorIter != actors.end()) {
PxRigidActor *actor = *actorIter;
PxRigidBody *body = dynamic_cast<PxRigidBody *>(actor);
if (body) {
PxVec3 position = actor->getGlobalPose().p;
positions[0] = position[0];
positions[1] = position[1];
positions[2] = position[2];
}
} else {
std::cerr << "get position unknown actor id " << id << std::endl;
positions[0] = 0;
positions[1] = 0;
positions[2] = 0;
}
}
void PScene::getLinearVelocity(unsigned int id, float *velocities) {
auto actorIter = std::find_if(actors.begin(), actors.end(), [&](PxRigidActor *actor) -> bool {
return (unsigned int)actor->userData == id;
});
if (actorIter != actors.end()) {
PxRigidActor *actor = *actorIter;
PxRigidBody *body = dynamic_cast<PxRigidBody *>(actor);
if (body) {
PxVec3 linearVelocity = body->getLinearVelocity();
velocities[0] = linearVelocity.x;
velocities[1] = linearVelocity.y;
velocities[2] = linearVelocity.z;
}
} else {
std::cerr << "get linearVelocity unknown actor id " << id << std::endl;
velocities[0] = 0;
velocities[1] = 0;
velocities[2] = 0;
}
}
void PScene::getAngularVelocity(unsigned int id, float *velocities) {
auto actorIter = std::find_if(actors.begin(), actors.end(), [&](PxRigidActor *actor) -> bool {
return (unsigned int)actor->userData == id;
});
if (actorIter != actors.end()) {
PxRigidActor *actor = *actorIter;
PxRigidBody *body = dynamic_cast<PxRigidBody *>(actor);
if (body) {
PxVec3 angularVelocity = body->getAngularVelocity();
velocities[0] = angularVelocity.x;
velocities[1] = angularVelocity.y;
velocities[2] = angularVelocity.z;
}
} else {
std::cerr << "get angularVelocity unknown actor id " << id << std::endl;
velocities[0] = 0;
velocities[1] = 0;
velocities[2] = 0;
}
}
void PScene::addForceAtPos(unsigned int id, float *velocity, float *position, bool autoWake) {
auto actorIter = std::find_if(actors.begin(), actors.end(), [&](PxRigidActor *actor) -> bool {
return (unsigned int)actor->userData == id;
});
if (actorIter != actors.end()) {
PxRigidActor *actor = *actorIter;
PxRigidBody *body = dynamic_cast<PxRigidBody *>(actor);
if (body) {
PxRigidBodyExt::addForceAtPos(*body, PxVec3(velocity[0], velocity[1], velocity[2]),
PxVec3(position[0], position[1], position[2]), PxForceMode::eIMPULSE, autoWake);
}
} else {
std::cerr << "addForceAtPos unknown actor id " << id << std::endl;
}
}
void PScene::addForceAtLocalPos(unsigned int id, float *velocity, float *position, bool autoWake) {
auto actorIter = std::find_if(actors.begin(), actors.end(), [&](PxRigidActor *actor) -> bool {
return (unsigned int)actor->userData == id;
});
if (actorIter != actors.end()) {
PxRigidActor *actor = *actorIter;
PxRigidBody *body = dynamic_cast<PxRigidBody *>(actor);
if (body) {
PxRigidBodyExt::addForceAtLocalPos(*body, PxVec3(velocity[0], velocity[1], velocity[2]),