Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qphysxworld.cpp
Go to the documentation of this file.
1// Copyright (C) 2023 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
6
7#include "characterkinematic/PxControllerManager.h"
8#include "cooking/PxCooking.h"
9#include "extensions/PxDefaultCpuDispatcher.h"
10#include "pvd/PxPvdTransport.h"
11#include "PxFoundation.h"
12#include "PxPhysics.h"
13#include "PxPhysicsVersion.h"
14#include "PxRigidActor.h"
15#include "PxScene.h"
16#include "PxSimulationEventCallback.h"
17
22#include "qtriggerbody_p.h"
23
25
27{
28public:
29 SimulationEventCallback(QPhysicsWorld *worldIn) : world(worldIn) {};
30 virtual ~SimulationEventCallback() = default;
31
32 void onTrigger(physx::PxTriggerPair *pairs, physx::PxU32 count) override
33 {
34 QMutexLocker locker(&world->m_removedPhysicsNodesMutex);
35
36 for (physx::PxU32 i = 0; i < count; i++) {
37 // ignore pairs when shapes have been deleted
38 if (pairs[i].flags
39 & (physx::PxTriggerPairFlag::eREMOVED_SHAPE_TRIGGER
40 | physx::PxTriggerPairFlag::eREMOVED_SHAPE_OTHER))
41 continue;
42
43 QTriggerBody *triggerNode =
44 static_cast<QTriggerBody *>(pairs[i].triggerActor->userData);
45
46 QAbstractPhysicsNode *otherNode =
47 static_cast<QAbstractPhysicsNode *>(pairs[i].otherActor->userData);
48
49 if (!triggerNode || !otherNode) {
50 qWarning() << "QtQuick3DPhysics internal error: null pointer in trigger collision.";
51 continue;
52 }
53
54 if (world->isNodeRemoved(triggerNode) || world->isNodeRemoved(otherNode))
55 continue;
56
57 if (pairs->status == physx::PxPairFlag::eNOTIFY_TOUCH_FOUND) {
58 if (otherNode->sendTriggerReports()) {
59 triggerNode->registerCollision(otherNode);
60 }
61 if (otherNode->receiveTriggerReports()) {
62 emit otherNode->enteredTriggerBody(triggerNode);
63 }
64 } else if (pairs->status == physx::PxPairFlag::eNOTIFY_TOUCH_LOST) {
65 if (otherNode->sendTriggerReports()) {
66 triggerNode->deregisterCollision(otherNode);
67 }
68 if (otherNode->receiveTriggerReports()) {
69 emit otherNode->exitedTriggerBody(triggerNode);
70 }
71 }
72 }
73 }
74
75 void onConstraintBreak(physx::PxConstraintInfo * /*constraints*/,
76 physx::PxU32 /*count*/) override {};
77 void onWake(physx::PxActor ** /*actors*/, physx::PxU32 /*count*/) override {};
78 void onSleep(physx::PxActor ** /*actors*/, physx::PxU32 /*count*/) override {};
79 void onContact(const physx::PxContactPairHeader &pairHeader, const physx::PxContactPair *pairs,
80 physx::PxU32 nbPairs) override
81 {
82 QMutexLocker locker(&world->m_removedPhysicsNodesMutex);
83 constexpr physx::PxU32 bufferSize = 64;
84 physx::PxContactPairPoint contacts[bufferSize];
85
86 for (physx::PxU32 i = 0; i < nbPairs; i++) {
87 const physx::PxContactPair &contactPair = pairs[i];
88
89 if (contactPair.events & physx::PxPairFlag::eNOTIFY_TOUCH_FOUND) {
90 QAbstractPhysicsNode *trigger =
91 static_cast<QAbstractPhysicsNode *>(pairHeader.actors[0]->userData);
92 QAbstractPhysicsNode *other =
93 static_cast<QAbstractPhysicsNode *>(pairHeader.actors[1]->userData);
94
95 if (!trigger || !other || world->isNodeRemoved(trigger)
96 || world->isNodeRemoved(other) || !trigger->m_backendObject
97 || !other->m_backendObject)
98 continue;
99
100 const bool triggerReceive =
101 trigger->receiveContactReports() && other->sendContactReports();
102 const bool otherReceive =
103 other->receiveContactReports() && trigger->sendContactReports();
104
105 if (!triggerReceive && !otherReceive)
106 continue;
107
108 physx::PxU32 nbContacts = pairs[i].extractContacts(contacts, bufferSize);
109
110 QList<QVector3D> positions;
111 QList<QVector3D> impulses;
112 QList<QVector3D> normals;
113
114 positions.reserve(nbContacts);
115 impulses.reserve(nbContacts);
116 normals.reserve(nbContacts);
117
118 for (physx::PxU32 j = 0; j < nbContacts; j++) {
119 physx::PxVec3 position = contacts[j].position;
120 physx::PxVec3 impulse = contacts[j].impulse;
121 physx::PxVec3 normal = contacts[j].normal;
122
123 positions.push_back(QPhysicsUtils::toQtType(position));
124 impulses.push_back(QPhysicsUtils::toQtType(impulse));
125 normals.push_back(QPhysicsUtils::toQtType(normal));
126 }
127
128 QList<QVector3D> normalsInverted;
129 normalsInverted.reserve(normals.size());
130 for (const QVector3D &v : std::as_const(normals)) {
131 normalsInverted.push_back(QVector3D(-v.x(), -v.y(), -v.z()));
132 }
133
134 if (triggerReceive)
135 world->registerContact(other, trigger, positions, impulses, normals);
136 if (otherReceive)
137 world->registerContact(trigger, other, positions, impulses, normalsInverted);
138 }
139 }
140 };
141 void onAdvance(const physx::PxRigidBody *const * /*bodyBuffer*/,
142 const physx::PxTransform * /*poseBuffer*/,
143 const physx::PxU32 /*count*/) override {};
144
145private:
146 QPhysicsWorld *world = nullptr;
147};
148
149static constexpr bool isBitSet(quint32 value, quint32 position)
150{
151 Q_ASSERT(position <= 32);
152 return value & (1 << (position));
153}
154
155// If any 'id' bit is set in the other mask it means collisions should be ignored, i.e.
156static bool isFilteredOut(physx::PxFilterData filterData0, physx::PxFilterData filterData1)
157{
158 // First word is id, second is collision mask
159 const quint32 id0 = filterData0.word0;
160 const quint32 id1 = filterData1.word0;
161 const quint32 mask0 = filterData0.word1;
162 const quint32 mask1 = filterData1.word1;
163
164 return id0 < 32 && id1 < 32 && (isBitSet(mask0, id1) || isBitSet(mask1, id0));
165}
166
167static physx::PxFilterFlags
169 physx::PxFilterData filterData0,
170 physx::PxFilterObjectAttributes /*attributes1*/,
171 physx::PxFilterData filterData1, physx::PxPairFlags &pairFlags,
172 const void * /*constantBlock*/, physx::PxU32 /*constantBlockSize*/)
173{
174 if (isFilteredOut(filterData0, filterData1)) {
175 // We return a 'suppress' since that will still re-evaluate when filter data is changed.
176 return physx::PxFilterFlag::eSUPPRESS;
177 }
178
179 // Makes objects collide
180 const auto defaultCollisonFlags =
181 physx::PxPairFlag::eSOLVE_CONTACT |
182 physx::PxPairFlag::eDETECT_DISCRETE_CONTACT |
183 physx::PxPairFlag::eDETECT_CCD_CONTACT; // will be ignored by physX engine if the ccd is disabled
184
185 // For trigger body detection
186 const auto notifyTouchFlags =
187 physx::PxPairFlag::eNOTIFY_TOUCH_FOUND | physx::PxPairFlag::eNOTIFY_TOUCH_LOST;
188
189 // For contact detection
190 const auto notifyContactFlags = physx::PxPairFlag::eNOTIFY_CONTACT_POINTS;
191
192 pairFlags = defaultCollisonFlags | notifyTouchFlags | notifyContactFlags;
193 return physx::PxFilterFlag::eDEFAULT;
194}
195
196#define PHYSX_RELEASE(x)
197 if (x != nullptr) {
198 x->release();
199 x = nullptr;
200 }
201
203{
205 s_physx.foundationRefCount++;
206
207 if (s_physx.foundationCreated)
208 return;
209
210 s_physx.foundation = PxCreateFoundation(
211 PX_PHYSICS_VERSION, s_physx.defaultAllocatorCallback, s_physx.defaultErrorCallback);
212 if (!s_physx.foundation)
213 qFatal("PxCreateFoundation failed!");
214
215 s_physx.foundationCreated = true;
216
217#if PHYSX_ENABLE_PVD
218 s_physx.pvd = PxCreatePvd(*m_physx->foundation);
219 s_physx.transport = physx::PxDefaultPvdSocketTransportCreate("qt", 5425, 10);
220 s_physx.pvd->connect(*m_physx->transport, physx::PxPvdInstrumentationFlag::eALL);
221#endif
222
223 // FIXME: does the tolerance matter?
224 s_physx.cooking = PxCreateCooking(PX_PHYSICS_VERSION, *s_physx.foundation,
225 physx::PxCookingParams(physx::PxTolerancesScale()));
226
227}
228
230{
232 s_physx.foundationRefCount--;
233 if (s_physx.foundationRefCount == 0) {
237 PHYSX_RELEASE(s_physx.cooking);
239 PHYSX_RELEASE(s_physx.pvd);
240 PHYSX_RELEASE(s_physx.physics);
242
243 delete callback;
244 callback = nullptr;
245 s_physx.foundationCreated = false;
246 s_physx.physicsCreated = false;
247 } else {
248 delete callback;
249 callback = nullptr;
252 }
253}
254
255void QPhysXWorld::createScene(float typicalLength, float typicalSpeed, const QVector3D &gravity,
256 QPhysicsWorld *physicsWorld, unsigned int numThreads)
257{
258 if (scene) {
259 qWarning() << "Scene already created";
260 return;
261 }
262
263 physx::PxTolerancesScale scale;
264 scale.length = typicalLength;
265 scale.speed = typicalSpeed;
266
268
269 if (!s_physx.physicsCreated) {
270 constexpr bool recordMemoryAllocations = true;
271 s_physx.physics = PxCreatePhysics(PX_PHYSICS_VERSION, *s_physx.foundation, scale,
272 recordMemoryAllocations, s_physx.pvd);
273 if (!s_physx.physics)
274 qFatal("PxCreatePhysics failed!");
275
276 s_physx.dispatcher = physx::PxDefaultCpuDispatcherCreate(numThreads);
277 s_physx.physicsCreated = true;
278 }
279
280 callback = new SimulationEventCallback(physicsWorld);
281
282 physx::PxSceneDesc sceneDesc(scale);
283 sceneDesc.gravity = QPhysicsUtils::toPhysXType(gravity);
284 sceneDesc.cpuDispatcher = s_physx.dispatcher;
285
286 sceneDesc.filterShader = contactReportFilterShader;
287 // CCD is always enabled at the scene level. Since PhysX's CCD pass is cheap enough
288 // (see PxsCCDContext::updateCCD) when there are no CCD-enabled bodies in the scene,
289 // it makes the code simpler.
290 sceneDesc.flags |= physx::PxSceneFlag::eENABLE_CCD;
291 sceneDesc.solverType = physx::PxSolverType::eTGS;
292 sceneDesc.simulationEventCallback = callback;
293
294 if (physicsWorld->reportKinematicKinematicCollisions())
295 sceneDesc.kineKineFilteringMode = physx::PxPairFilteringMode::eKEEP;
296 if (physicsWorld->reportStaticKinematicCollisions())
297 sceneDesc.staticKineFilteringMode = physx::PxPairFilteringMode::eKEEP;
298
299 switch (physicsWorld->staticQueryStructure()) {
300 case QPhysicsWorld::QueryStructure::NoStructure: {
301 Q_ASSERT(false && "Unreachable: setStaticQueryStructure() rejects NoStructure");
302 break;
303 }
304
305 case QPhysicsWorld::QueryStructure::StaticTree: {
306 sceneDesc.staticStructure = physx::PxPruningStructureType::eSTATIC_AABB_TREE;
307 break;
308 }
309
310 case QPhysicsWorld::QueryStructure::DynamicTree: {
311 sceneDesc.staticStructure = physx::PxPruningStructureType::eDYNAMIC_AABB_TREE;
312 break;
313 }
314
315 }
316
317 switch (physicsWorld->dynamicQueryStructure()) {
318 case QPhysicsWorld::QueryStructure::NoStructure: {
319 sceneDesc.dynamicStructure = physx::PxPruningStructureType::eNONE;
320 break;
321 }
322
323 case QPhysicsWorld::QueryStructure::StaticTree: {
324 sceneDesc.dynamicStructure = physx::PxPruningStructureType::eSTATIC_AABB_TREE;
325 break;
326 }
327
328 case QPhysicsWorld::QueryStructure::DynamicTree: {
329 sceneDesc.dynamicStructure = physx::PxPruningStructureType::eDYNAMIC_AABB_TREE;
330 break;
331 }
332
333 }
334
335 scene = s_physx.physics->createScene(sceneDesc);
336}
337
void createScene(float typicalLength, float typicalSpeed, const QVector3D &gravity, QPhysicsWorld *physicsWorld, unsigned int numThreads)
void createWorld()
SimulationEventCallback * callback
void deleteWorld()
physx::PxScene * scene
physx::PxControllerManager * controllerManager
The QVector3D class represents a vector or vertex in 3D space.
Definition qvectornd.h:178
SimulationEventCallback(QPhysicsWorld *worldIn)
void onConstraintBreak(physx::PxConstraintInfo *, physx::PxU32) override
virtual ~SimulationEventCallback()=default
void onContact(const physx::PxContactPairHeader &pairHeader, const physx::PxContactPair *pairs, physx::PxU32 nbPairs) override
void onAdvance(const physx::PxRigidBody *const *, const physx::PxTransform *, const physx::PxU32) override
void onWake(physx::PxActor **, physx::PxU32) override
void onTrigger(physx::PxTriggerPair *pairs, physx::PxU32 count) override
void onSleep(physx::PxActor **, physx::PxU32) override
#define PHYSX_RELEASE(x)
static constexpr bool isBitSet(quint32 value, quint32 position)
static bool isFilteredOut(physx::PxFilterData filterData0, physx::PxFilterData filterData1)
static physx::PxFilterFlags contactReportFilterShader(physx::PxFilterObjectAttributes, physx::PxFilterData filterData0, physx::PxFilterObjectAttributes, physx::PxFilterData filterData1, physx::PxPairFlags &pairFlags, const void *, physx::PxU32)
#define QT_BEGIN_NAMESPACE
#define QT_END_NAMESPACE
physx::PxCooking * cooking
static StaticPhysXObjects & getReference()
physx::PxFoundation * foundation
physx::PxPvdTransport * transport
physx::PxDefaultCpuDispatcher * dispatcher
physx::PxPhysics * physics