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 "extensions/PxDefaultCpuDispatcher.h"
9#include "foundation/PxFoundation.h"
10#include "PxPhysics.h"
11#include "foundation/PxPhysicsVersion.h"
12#include "PxRigidActor.h"
13#include "PxScene.h"
14#include "PxShape.h"
15#include "PxSimulationEventCallback.h"
16
23
25
26// The shape a PhysX shape was built for, or null if it was not built for one.
27// Only ever compared, since the shape can be gone by the time it is looked at.
28static QAbstractCollisionShape *frontendShape(const physx::PxShape *shape)
29{
30 return shape ? static_cast<QAbstractCollisionShape *>(shape->userData) : nullptr;
31}
32
34{
35public:
36 SimulationEventCallback(QPhysicsWorld *worldIn) : world(worldIn) {};
37 virtual ~SimulationEventCallback() = default;
38
39 void onTrigger(physx::PxTriggerPair *pairs, physx::PxU32 count) override
40 {
41 // A body one of whose shapes leaves a region as another of them enters
42 // it has a lost and a found pair in the same batch, and taking the lost
43 // one first would report the body as having left and entered again. So
44 // the found pair is taken first, and only for the region and body that
45 // has both: every other pair is handled in the order PhysX gave it, so
46 // a body leaving one region as it enters another is still reported that
47 // way.
48 const auto replacesLostOverlap = [pairs, count](physx::PxU32 i) {
49 if (pairs[i].status != physx::PxPairFlag::eNOTIFY_TOUCH_FOUND)
50 return false;
51 for (physx::PxU32 j = 0; j < count; j++) {
52 if (pairs[j].status == physx::PxPairFlag::eNOTIFY_TOUCH_LOST
53 && pairs[j].triggerActor == pairs[i].triggerActor
54 && pairs[j].otherActor == pairs[i].otherActor) {
55 return true;
56 }
57 }
58 return false;
59 };
60
61 // Those first, then every pair in turn. Registering one of them again
62 // on the second pass does nothing: the body is inside already and the
63 // pair is one of its own already.
64 enum Pass { ReplacedOverlaps, EveryPair };
65 for (const Pass pass : { ReplacedOverlaps, EveryPair }) {
66 for (physx::PxU32 i = 0; i < count; i++) {
67 if (pass == ReplacedOverlaps && !replacesLostOverlap(i))
68 continue;
69
70 // ignore pairs when shapes have been deleted
71 if (pairs[i].flags
72 & (physx::PxTriggerPairFlag::eREMOVED_SHAPE_TRIGGER
73 | physx::PxTriggerPairFlag::eREMOVED_SHAPE_OTHER))
74 continue;
75
76 // Only cast, not read: what the actors point at may already have
77 // been deleted, and asking what it is dereferences it.
78 auto *triggerCandidate =
79 static_cast<QAbstractPhysicsNode *>(pairs[i].triggerActor->userData);
80
81 QAbstractPhysicsNode *otherNode =
82 static_cast<QAbstractPhysicsNode *>(pairs[i].otherActor->userData);
83
84 if (!triggerCandidate || !otherNode) {
85 qWarning() << "QtQuick3DPhysics internal error: null pointer in trigger "
86 "collision.";
87 continue;
88 }
89
90 // Asked per pair, since one batch can report the same node in
91 // several pairs and a handler run for one of them can delete a
92 // node a later one points at. Nothing else can: PhysX sends
93 // these from the thread that deletes nodes.
94 if (world->isNodeRemoved(triggerCandidate) || world->isNodeRemoved(otherNode))
95 continue;
96
97 // Safe to ask what it is now that it is known to still be there.
98 auto *triggerNode = qobject_cast<QAbstractTriggerRegion *>(triggerCandidate);
99 if (!triggerNode)
100 continue;
101
102 // Passed on so the region can tell one pair of a body from
103 // another: PhysX reports a pair of shapes and a body is several
104 // of those, so one of them stopping overlapping is not the body
105 // leaving.
106 const QAbstractTriggerRegion::ShapePair shapes {
107 frontendShape(pairs[i].triggerShape), frontendShape(pairs[i].otherShape)
108 };
109
110 // Whether a body is worth following, and what it is owed, is
111 // the region's to decide, once per body rather than once per
112 // pair: a body that changes its mind while inside would
113 // otherwise be half followed.
114 if (pairs[i].status == physx::PxPairFlag::eNOTIFY_TOUCH_FOUND)
115 triggerNode->registerCollision(otherNode, shapes);
116 else if (pairs[i].status == physx::PxPairFlag::eNOTIFY_TOUCH_LOST)
117 triggerNode->deregisterCollision(otherNode, shapes);
118 }
119 }
120 }
121
122 void onConstraintBreak(physx::PxConstraintInfo * /*constraints*/,
123 physx::PxU32 /*count*/) override {};
124 void onWake(physx::PxActor ** /*actors*/, physx::PxU32 /*count*/) override {};
125 void onSleep(physx::PxActor ** /*actors*/, physx::PxU32 /*count*/) override {};
126 void onContact(const physx::PxContactPairHeader &pairHeader, const physx::PxContactPair *pairs,
127 physx::PxU32 nbPairs) override
128 {
129 constexpr physx::PxU32 bufferSize = 64;
130 physx::PxContactPairPoint contacts[bufferSize];
131
132 for (physx::PxU32 i = 0; i < nbPairs; i++) {
133 const physx::PxContactPair &contactPair = pairs[i];
134
135 if (contactPair.events & physx::PxPairFlag::eNOTIFY_TOUCH_FOUND) {
136 QAbstractPhysicsNode *trigger =
137 static_cast<QAbstractPhysicsNode *>(pairHeader.actors[0]->userData);
138 QAbstractPhysicsNode *other =
139 static_cast<QAbstractPhysicsNode *>(pairHeader.actors[1]->userData);
140
141 if (!trigger || !other || world->isNodeRemoved(trigger)
142 || world->isNodeRemoved(other) || !trigger->m_backendObject
143 || !other->m_backendObject)
144 continue;
145
146 const bool triggerReceive =
147 trigger->receiveContactReports() && other->sendContactReports();
148 const bool otherReceive =
149 other->receiveContactReports() && trigger->sendContactReports();
150
151 if (!triggerReceive && !otherReceive)
152 continue;
153
154 physx::PxU32 nbContacts = pairs[i].extractContacts(contacts, bufferSize);
155
156 QList<QVector3D> positions;
157 QList<QVector3D> impulses;
158 QList<QVector3D> normals;
159
160 positions.reserve(nbContacts);
161 impulses.reserve(nbContacts);
162 normals.reserve(nbContacts);
163
164 for (physx::PxU32 j = 0; j < nbContacts; j++) {
165 physx::PxVec3 position = contacts[j].position;
166 physx::PxVec3 impulse = contacts[j].impulse;
167 physx::PxVec3 normal = contacts[j].normal;
168
169 positions.push_back(QPhysicsUtils::toQtType(position));
170 impulses.push_back(QPhysicsUtils::toQtType(impulse));
171 normals.push_back(QPhysicsUtils::toQtType(normal));
172 }
173
174 QList<QVector3D> normalsInverted;
175 normalsInverted.reserve(normals.size());
176 for (const QVector3D &v : std::as_const(normals)) {
177 normalsInverted.push_back(QVector3D(-v.x(), -v.y(), -v.z()));
178 }
179
180 if (triggerReceive)
181 world->registerContact(other, trigger, positions, impulses, normals);
182 if (otherReceive)
183 world->registerContact(trigger, other, positions, impulses, normalsInverted);
184 }
185 }
186 };
187 void onAdvance(const physx::PxRigidBody *const * /*bodyBuffer*/,
188 const physx::PxTransform * /*poseBuffer*/,
189 const physx::PxU32 /*count*/) override {};
190
191private:
192 QPhysicsWorld *world = nullptr;
193};
194
195static physx::PxFilterFlags
196contactReportFilterShader(physx::PxFilterObjectAttributes attributes0,
197 physx::PxFilterData filterData0,
198 physx::PxFilterObjectAttributes attributes1,
199 physx::PxFilterData filterData1, physx::PxPairFlags &pairFlags,
200 const void * /*constantBlock*/, physx::PxU32 /*constantBlockSize*/)
201{
202 if (QPhysicsUtils::isFilteredOut(QPhysicsUtils::toQtType(filterData0),
203 QPhysicsUtils::toQtType(filterData1))) {
204 // We return a 'suppress' since that will still re-evaluate when filter data is changed.
205 return physx::PxFilterFlag::eSUPPRESS;
206 }
207
208 // A trigger shape does not collide, it only reports what overlaps it, so
209 // there is nothing to solve and nothing for a continuous sweep to do. The
210 // scene has CCD enabled unconditionally (see below), and PhysX warns for
211 // every trigger pair that asks for a CCD contact, so ask only for what a
212 // trigger actually needs.
213 if (physx::PxFilterObjectIsTrigger(attributes0)
214 || physx::PxFilterObjectIsTrigger(attributes1)) {
215 pairFlags = physx::PxPairFlag::eTRIGGER_DEFAULT;
216 return physx::PxFilterFlag::eDEFAULT;
217 }
218
219 // Makes objects collide
220 const auto defaultCollisonFlags =
221 physx::PxPairFlag::eSOLVE_CONTACT |
222 physx::PxPairFlag::eDETECT_DISCRETE_CONTACT |
223 physx::PxPairFlag::eDETECT_CCD_CONTACT; // will be ignored by physX engine if the ccd is disabled
224
225 // For trigger body detection
226 const auto notifyTouchFlags =
227 physx::PxPairFlag::eNOTIFY_TOUCH_FOUND | physx::PxPairFlag::eNOTIFY_TOUCH_LOST;
228
229 // For contact detection
230 const auto notifyContactFlags = physx::PxPairFlag::eNOTIFY_CONTACT_POINTS;
231
232 pairFlags = defaultCollisonFlags | notifyTouchFlags | notifyContactFlags;
233 return physx::PxFilterFlag::eDEFAULT;
234}
235
236#define PHYSX_RELEASE(x)
237 if (x != nullptr) {
238 x->release();
239 x = nullptr;
240 }
241
243{
245 s_physx.foundationRefCount++;
246
247 if (s_physx.foundationCreated)
248 return;
249
250 s_physx.foundation = PxCreateFoundation(
251 PX_PHYSICS_VERSION, s_physx.defaultAllocatorCallback, s_physx.defaultErrorCallback);
252 if (!s_physx.foundation)
253 qFatal("PxCreateFoundation failed!");
254
255 s_physx.foundationCreated = true;
256}
257
259{
261 s_physx.foundationRefCount--;
262 if (s_physx.foundationRefCount == 0) {
266 // Every node releases its material when it is cleaned up, which happens before the
267 // last world is deleted, so nothing should be left to release here
268 Q_ASSERT(s_physx.materials.isEmpty());
269 s_physx.materials.clear();
270 PHYSX_RELEASE(s_physx.physics);
271 s_physx.physicsGeneration++;
273
274 delete callback;
275 callback = nullptr;
276 s_physx.foundationCreated = false;
277 s_physx.physicsCreated = false;
278 } else {
279 delete callback;
280 callback = nullptr;
283 }
284}
285
286void QPhysXWorld::createScene(float typicalLength, float typicalSpeed, const QVector3D &gravity,
287 QPhysicsWorld *physicsWorld, unsigned int numThreads)
288{
289 if (scene) {
290 qWarning() << "Scene already created";
291 return;
292 }
293
294 physx::PxTolerancesScale scale;
295 scale.length = typicalLength;
296 scale.speed = typicalSpeed;
297
299
300 if (!s_physx.physicsCreated) {
301 constexpr bool recordMemoryAllocations = true;
302 s_physx.physics = PxCreatePhysics(PX_PHYSICS_VERSION, *s_physx.foundation, scale,
303 recordMemoryAllocations);
304 if (!s_physx.physics)
305 qFatal("PxCreatePhysics failed!");
306
307 s_physx.dispatcher = physx::PxDefaultCpuDispatcherCreate(numThreads);
308 s_physx.physicsCreated = true;
309 }
310
311 callback = new SimulationEventCallback(physicsWorld);
312
313 physx::PxSceneDesc sceneDesc(scale);
314 sceneDesc.gravity = QPhysicsUtils::toPhysXType(gravity);
315 sceneDesc.cpuDispatcher = s_physx.dispatcher;
316
317 sceneDesc.filterShader = contactReportFilterShader;
318 // CCD is always enabled at the scene level. Since PhysX's CCD pass is cheap enough
319 // (see PxsCCDContext::updateCCD) when there are no CCD-enabled bodies in the scene,
320 // it makes the code simpler.
321 sceneDesc.flags |= physx::PxSceneFlag::eENABLE_CCD;
322 sceneDesc.solverType = physx::PxSolverType::eTGS;
323 sceneDesc.simulationEventCallback = callback;
324
325 if (physicsWorld->reportKinematicKinematicCollisions())
326 sceneDesc.kineKineFilteringMode = physx::PxPairFilteringMode::eKEEP;
327 if (physicsWorld->reportStaticKinematicCollisions())
328 sceneDesc.staticKineFilteringMode = physx::PxPairFilteringMode::eKEEP;
329
330 switch (physicsWorld->staticQueryStructure()) {
331 case QPhysicsWorld::QueryStructure::NoStructure: {
332 Q_ASSERT(false && "Unreachable: setStaticQueryStructure() rejects NoStructure");
333 break;
334 }
335
336 case QPhysicsWorld::QueryStructure::StaticTree: {
337 sceneDesc.staticStructure = physx::PxPruningStructureType::eSTATIC_AABB_TREE;
338 break;
339 }
340
341 case QPhysicsWorld::QueryStructure::DynamicTree: {
342 sceneDesc.staticStructure = physx::PxPruningStructureType::eDYNAMIC_AABB_TREE;
343 break;
344 }
345
346 }
347
348 switch (physicsWorld->dynamicQueryStructure()) {
349 case QPhysicsWorld::QueryStructure::NoStructure: {
350 sceneDesc.dynamicStructure = physx::PxPruningStructureType::eNONE;
351 break;
352 }
353
354 case QPhysicsWorld::QueryStructure::StaticTree: {
355 sceneDesc.dynamicStructure = physx::PxPruningStructureType::eSTATIC_AABB_TREE;
356 break;
357 }
358
359 case QPhysicsWorld::QueryStructure::DynamicTree: {
360 sceneDesc.dynamicStructure = physx::PxPruningStructureType::eDYNAMIC_AABB_TREE;
361 break;
362 }
363
364 }
365
366 scene = s_physx.physics->createScene(sceneDesc);
367}
368
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
PxTransformT< float > PxTransform
#define PHYSX_RELEASE(x)
static QT_BEGIN_NAMESPACE QAbstractCollisionShape * frontendShape(const physx::PxShape *shape)
static physx::PxFilterFlags contactReportFilterShader(physx::PxFilterObjectAttributes attributes0, physx::PxFilterData filterData0, physx::PxFilterObjectAttributes attributes1, physx::PxFilterData filterData1, physx::PxPairFlags &pairFlags, const void *, physx::PxU32)
#define QT_BEGIN_NAMESPACE
#define QT_END_NAMESPACE
static StaticPhysXObjects & getReference()
physx::PxFoundation * foundation
physx::PxDefaultCpuDispatcher * dispatcher
physx::PxPhysics * physics