7#include "physxnode/qabstractphysxnode_p.h"
8#include "physxnode/qphysxworld_p.h"
12#include "joints/qjoint_p.h"
25#include "physxnode/qphysxgravity_p.h"
26#include "physxnode/qphysxgravityfield_p.h"
28#include "PxPhysicsAPI.h"
29#include "cooking/PxCooking.h"
30#include <foundation/PxSimpleTypes.h>
32#include <QtQuick/private/qquickframeanimation_p.h>
33#include <QtQuick3D/private/qquick3dobject_p.h>
34#include <QtQuick3D/private/qquick3dnode_p.h>
35#include <QtQuick3D/private/qquick3dmodel_p.h>
36#include <QtQuick3D/private/qquick3dprincipledmaterial_p.h>
37#include <QtQuick3DUtils/private/qssgutils_p.h>
39#include <QtCore/qvarlengtharray.h>
40#include <QtGui/qquaternion.h>
42#include <QtEnvironmentVariables>
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
76
77
78
79
80
83
84
85
88
89
90
91
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
119
120
121
122
123
124
125
128
129
130
131
132
133
134
135
136
137
140
141
142
143
144
145
146
147
148
149
152
153
154
155
156
157
160
161
162
163
164
165
166
167
170
171
172
173
174
175
176
177
180
181
182
183
184
185
186
187
190
191
192
193
194
195
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
230
231
232
233
234
235
236
237
238
239
240
241
242
245
246
247
248
249
250
251
252
253
254
255
256
257
258
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
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
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
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
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
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
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
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
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
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
607 qWarning() <<
"QtQuick3DPhysics: cannot run a scene query before the physics world is "
612 if (!(includeStatic || includeDynamic)) {
613 qWarning() <<
"QtQuick3DPhysics: a scene query needs includeStatic or includeDynamic to "
627 physx::PxRaycastCallback &hitCallback,
628 physx::PxHitFlags hitFlags,
629 physx::PxQueryFlags extraQueryFlags = {},
630 physx::PxQueryFilterCallback *filterCall =
nullptr)
635 const physx::PxVec3 pxOrigin = QPhysicsUtils::toPhysXType(origin);
636 if (!pxOrigin.isFinite()) {
637 qWarning() <<
"QtQuick3DPhysics: the query origin must be finite.";
641 const physx::PxVec3 pxDirection = QPhysicsUtils::toPhysXType(direction.normalized());
642 if (!pxDirection.isNormalized()) {
643 qWarning() <<
"QtQuick3DPhysics: the query direction must be a non-null, finite vector.";
647 if (!qIsFinite(maxDistance) || maxDistance <= 0) {
648 qWarning() <<
"QtQuick3DPhysics: the query distance must be finite and greater than 0.";
653 physx::PxQueryFlags filter = extraQueryFlags;
655 filter |= physx::PxQueryFlag::eSTATIC;
657 filter |= physx::PxQueryFlag::eDYNAMIC;
660 return scene->raycast(pxOrigin, pxDirection, maxDistance, hitCallback, hitFlags,
661 physx::PxQueryFilterData(filter), filterCall);
665 QAbstractCollisionShape *shape,
673 const physx::PxGeometry *geometry = shape ? shape->getPhysXGeometry() :
nullptr;
675 qWarning() <<
"QtQuick3DPhysics: the query shape has no geometry yet.";
681 switch (geometry->getType()) {
682 case physx::PxGeometryType::eSPHERE:
683 case physx::PxGeometryType::eCAPSULE:
684 case physx::PxGeometryType::eBOX:
685 case physx::PxGeometryType::eCONVEXMESH:
688 qWarning() <<
"QtQuick3DPhysics: sweep and overlap queries only support SphereShape, "
689 "CapsuleShape, BoxShape and ConvexMeshShape as the query shape.";
697 QAbstractCollisionShape *shape,
702 physx::PxSweepCallback &hitCallback,
703 physx::PxHitFlags hitFlags,
704 physx::PxQueryFlags extraQueryFlags = {})
706 const physx::PxGeometry *geometry = validateQueryShape(scene, shape, includeStatic, includeDynamic);
711 const physx::PxVec3 pxDirection = QPhysicsUtils::toPhysXType(direction.normalized());
712 if (!pxDirection.isNormalized()) {
713 qWarning() <<
"QtQuick3DPhysics: the query direction must be a non-null, finite vector.";
717 if (!qIsFinite(maxDistance) || maxDistance <= 0) {
718 qWarning() <<
"QtQuick3DPhysics: the query distance must be finite and greater than 0.";
723 physx::PxQueryFlags filter = extraQueryFlags;
725 filter |= physx::PxQueryFlag::eSTATIC;
727 filter |= physx::PxQueryFlag::eDYNAMIC;
729 const physx::
PxTransform pose(QPhysicsUtils::toPhysXType(shape->scenePosition()),
730 QPhysicsUtils::toPhysXType(shape->sceneRotation()));
731 if (!pose.isSane()) {
732 qWarning() <<
"QtQuick3DPhysics: the query position/rotation is not finite.";
737 return scene->sweep(*geometry, pose, pxDirection, maxDistance, hitCallback, hitFlags,
738 physx::PxQueryFilterData(filter));
742 QAbstractCollisionShape *shape,
745 physx::PxOverlapCallback &hitCallback,
746 physx::PxQueryFlags extraQueryFlags = {})
749 const physx::PxGeometry *geometry = validateQueryShape(scene, shape, includeStatic, includeDynamic);
755 physx::PxQueryFlags filter = extraQueryFlags;
757 filter |= physx::PxQueryFlag::eSTATIC;
759 filter |= physx::PxQueryFlag::eDYNAMIC;
761 const physx::
PxTransform pose(QPhysicsUtils::toPhysXType(shape->scenePosition()),
762 QPhysicsUtils::toPhysXType(shape->sceneRotation()));
763 if (!pose.isSane()) {
764 qWarning() <<
"QtQuick3DPhysics: the query position/rotation is not finite.";
769 return scene->overlap(*geometry, pose, hitCallback,
770 physx::PxQueryFilterData(filter));
791class ExcludedBodiesFilter :
public physx::PxQueryFilterCallback
794 explicit ExcludedBodiesFilter(QSpan<
const QAbstractPhysicsNode *
const> excludedBodies)
795 : m_excludedBodies(excludedBodies)
799 physx::PxQueryHitType::Enum preFilter(
const physx::PxFilterData & ,
800 const physx::PxShape * ,
801 const physx::PxRigidActor *actor,
802 physx::PxHitFlags & ) override
804 const auto *body =
static_cast<
const QAbstractPhysicsNode *>(actor->userData);
806 return physx::PxQueryHitType::eNONE;
807 const bool excluded = std::find(m_excludedBodies.begin(), m_excludedBodies.end(), body)
808 != m_excludedBodies.end();
809 return excluded ? physx::PxQueryHitType::eNONE : physx::PxQueryHitType::eBLOCK;
812 physx::PxQueryHitType::Enum postFilter(
const physx::PxFilterData & ,
813 const physx::PxQueryHit & ,
814 const physx::PxShape * ,
815 const physx::PxRigidActor * ) override
817 return physx::PxQueryHitType::eBLOCK;
821 QSpan<
const QAbstractPhysicsNode *
const> m_excludedBodies;
828template<
class PxCbT,
class HitT,
class PxHitT, physx::PxU32 BufferSize = 16>
829struct DynamicQueryCallback :
public PxCbT
831 DynamicQueryCallback() : PxCbT(localBuffer, BufferSize) {}
833 physx::PxAgain processTouches(
const PxHitT *buffer, physx::PxU32 nbHits)
override
835 hits.reserve(hits.size() + nbHits);
836 for (physx::PxU32 i = 0; i < nbHits; ++i)
837 hits.emplaceBack(buffer[i], buffer[i]);
841 PxHitT localBuffer[BufferSize];
849void QPhysicsWorld::DebugModelHolder::releaseMeshPointer()
851 if (
auto base =
static_cast<physx::PxBase *>(ptr); base)
856const QVector3D &QPhysicsWorld::DebugModelHolder::halfExtents()
const
860void QPhysicsWorld::DebugModelHolder::setHalfExtents(
const QVector3D &halfExtents)
864float QPhysicsWorld::DebugModelHolder::radius()
const
868void QPhysicsWorld::DebugModelHolder::setRadius(
float radius)
872float QPhysicsWorld::DebugModelHolder::heightScale()
const
876void QPhysicsWorld::DebugModelHolder::setHeightScale(
float heightScale)
878 data.setX(heightScale);
880float QPhysicsWorld::DebugModelHolder::halfHeight()
const
884void QPhysicsWorld::DebugModelHolder::setHalfHeight(
float halfHeight)
886 data.setY(halfHeight);
888float QPhysicsWorld::DebugModelHolder::rowScale()
const
892void QPhysicsWorld::DebugModelHolder::setRowScale(
float rowScale)
896float QPhysicsWorld::DebugModelHolder::columnScale()
const
900void QPhysicsWorld::DebugModelHolder::setColumnScale(
float columnScale)
902 data.setZ(columnScale);
904physx::PxConvexMesh *QPhysicsWorld::DebugModelHolder::getConvexMesh()
906 return static_cast<physx::PxConvexMesh *>(ptr);
908void QPhysicsWorld::DebugModelHolder::setConvexMesh(physx::PxConvexMesh *mesh)
910 ptr =
static_cast<
void *>(mesh);
912physx::PxTriangleMesh *QPhysicsWorld::DebugModelHolder::getTriangleMesh()
914 return static_cast<physx::PxTriangleMesh *>(ptr);
916void QPhysicsWorld::DebugModelHolder::setTriangleMesh(physx::PxTriangleMesh *mesh)
918 ptr =
static_cast<
void *>(mesh);
920physx::PxHeightField *QPhysicsWorld::DebugModelHolder::getHeightField()
922 return static_cast<physx::PxHeightField *>(ptr);
924void QPhysicsWorld::DebugModelHolder::setHeightField(physx::PxHeightField *hf)
926 ptr =
static_cast<physx::PxHeightField *>(hf);
941void QPhysicsWorld::registerNode(QAbstractPhysicsNode *physicsNode)
943 auto world = getWorld(physicsNode);
945 world->m_newPhysicsNodes.push_back(physicsNode);
947 worldManager.orphanNodes.push_back(physicsNode);
951void QPhysicsWorld::deregisterNode(QAbstractPhysicsNode *physicsNode)
955 if (physicsNode->m_backendObject) {
956 for (
auto world : std::as_const(worldManager.worlds))
957 world->releaseGravityField(physicsNode->m_backendObject);
959 for (
auto world : std::as_const(worldManager.worlds)) {
960 world->m_newPhysicsNodes.removeAll(physicsNode);
961 if (physicsNode->m_backendObject) {
962 Q_ASSERT(physicsNode->m_backendObject->frontendNode == physicsNode);
963 physicsNode->m_backendObject->detachFrontend();
964 physicsNode->m_backendObject->frontendNode =
nullptr;
965 physicsNode->m_backendObject->isRemoved =
true;
966 physicsNode->m_backendObject =
nullptr;
968 world->m_removedPhysicsNodes.insert(physicsNode);
970 worldManager.orphanNodes.removeAll(physicsNode);
973void QPhysicsWorld::registerJoint(QPhysicsJoint *joint)
975 auto world = getWorld(joint);
977 world->m_joints.push_back(joint);
979 worldManager.orphanJoints.push_back(joint);
983void QPhysicsWorld::deregisterJoint(QPhysicsJoint *joint)
985 for (
auto world : worldManager.worlds) {
986 world->m_removedJoints.insert(joint->getPhysXBackend());
989 qsizetype idx = world->m_joints.indexOf(joint);
991 world->m_joints.swapItemsAt(idx, world->m_joints.size() - 1);
992 world->m_joints.pop_back();
995 worldManager.orphanJoints.removeAll(joint);
998void QPhysicsWorld::registerRaycaster(QRaycaster *raycaster)
1000 if (
auto *world = getWorld(raycaster))
1001 world->m_raycasters.push_back(raycaster);
1003 worldManager.orphanRaycasters.push_back(raycaster);
1006void QPhysicsWorld::deregisterRaycaster(QRaycaster *raycaster)
1008 for (
auto *world : std::as_const(worldManager.worlds))
1009 world->m_raycasters.removeAll(raycaster);
1010 worldManager.orphanRaycasters.removeAll(raycaster);
1013void QPhysicsWorld::registerGravityField(QPhysXGravityField *field)
1015 m_gravityFields.append(field);
1018void QPhysicsWorld::registerContact(QAbstractPhysicsNode *sender, QAbstractPhysicsNode *receiver,
1019 const QVector<QVector3D> &positions,
1020 const QVector<QVector3D> &impulses,
1021 const QVector<QVector3D> &normals)
1028 BodyContact contact;
1029 contact.sender = sender;
1030 contact.receiver = receiver;
1031 contact.positions = positions;
1032 contact.impulses = impulses;
1033 contact.normals = normals;
1035 m_registeredContacts.push_back(contact);
1038QPhysicsWorld::QPhysicsWorld(QObject *parent) : QObject(parent)
1040 m_inDesignStudio = !qEnvironmentVariableIsEmpty(
"QML_PUPPET_MODE");
1041 m_physx =
new QPhysXWorld;
1042 m_physx->createWorld();
1044 worldManager.worlds.push_back(
this);
1046 matchOrphanJoints();
1047 matchOrphanRaycasters();
1049 m_frameAnimator =
new FrameAnimator;
1050 connect(m_frameAnimator, &QQuickFrameAnimation::triggered,
this,
1051 &QPhysicsWorld::simulateFrame);
1054QPhysicsWorld::~QPhysicsWorld()
1056 if (m_frameAnimator) {
1057 m_frameAnimator->stop();
1058 delete m_frameAnimator;
1061 if (m_physx->scene && m_physx->isRunning && !m_frameFetched)
1062 m_physx->scene->fetchResults(
true);
1064 for (
auto body : std::as_const(m_physXBodies)) {
1065 body->cleanup(m_physx);
1068 m_physXBodies.clear();
1069 m_physx->deleteWorld();
1071 worldManager.worlds.removeAll(
this);
1076 worldManager.orphanRaycasters += m_raycasters;
1077 m_raycasters.clear();
1079 if (!qtPhysicsTimingsFile.isEmpty()) {
1080 if (m_frameTimings.isEmpty()) {
1081 qWarning() <<
"No frame timings saved.";
1082 }
else if (
auto csvFile = QFile(qtPhysicsTimingsFile); csvFile.open(QIODevice::WriteOnly)) {
1083 QTextStream out(&csvFile);
1084 for (
int i = 1; i < m_frameTimings.size(); i++) {
1085 out << i <<
"," << m_frameTimings[i] <<
'\n';
1089 qWarning() <<
"Could not open timings file " << qtPhysicsTimingsFile;
1094void QPhysicsWorld::classBegin() {}
1096void QPhysicsWorld::componentComplete()
1098 if ((!m_running && !m_inDesignStudio) || m_physicsInitialized)
1103QVector3D QPhysicsWorld::gravity()
const
1108bool QPhysicsWorld::running()
const
1113bool QPhysicsWorld::forceDebugDraw()
const
1115 return m_forceDebugDraw;
1118bool QPhysicsWorld::enableCCD()
const
1123float QPhysicsWorld::typicalLength()
const
1125 return m_typicalLength;
1128float QPhysicsWorld::typicalSpeed()
const
1130 return m_typicalSpeed;
1133bool QPhysicsWorld::isNodeRemoved(QAbstractPhysicsNode *object)
1135 return m_removedPhysicsNodes.contains(object);
1138void QPhysicsWorld::setGravity(QVector3D gravity)
1140 if (m_gravity == gravity)
1143 if (!QPhysicsUtils::isFinite(gravity)) {
1144 qWarning() <<
"Warning: 'gravity' must be finite, ignored";
1148 m_gravity = gravity;
1149 if (m_physx->scene) {
1150 m_physx->scene->setGravity(QPhysicsUtils::toPhysXType(m_gravity));
1152 emit gravityChanged(m_gravity);
1155void QPhysicsWorld::setRunning(
bool running)
1157 if (m_running == running)
1160 m_running = running;
1161 if (!m_inDesignStudio && m_running && !m_physicsInitialized)
1165 m_frameAnimator->start();
1167 m_frameAnimator->stop();
1169 emit runningChanged(m_running);
1172void QPhysicsWorld::setForceDebugDraw(
bool forceDebugDraw)
1174 if (m_forceDebugDraw == forceDebugDraw)
1177 m_forceDebugDraw = forceDebugDraw;
1178 if (!m_forceDebugDraw)
1182 emit forceDebugDrawChanged(m_forceDebugDraw);
1185QQuick3DNode *QPhysicsWorld::viewport()
const
1190void QPhysicsWorld::setHasIndividualDebugDraw()
1192 m_hasIndividualDebugDraw =
true;
1195void QPhysicsWorld::setViewport(QQuick3DNode *viewport)
1197 if (m_viewport == viewport)
1200 m_viewport = viewport;
1203 for (
auto material : std::as_const(m_debugMaterials))
1205 m_debugMaterials.clear();
1207 for (
auto &holder : m_collisionShapeDebugModels) {
1208 holder.releaseMeshPointer();
1209 delete holder.model;
1211 m_collisionShapeDebugModels.clear();
1213 emit viewportChanged(m_viewport);
1216void QPhysicsWorld::setMinimumTimestep(
float minTimestep)
1218 if (qFuzzyCompare(m_minTimestep, minTimestep))
1221 if (!qIsFinite(minTimestep)) {
1222 qWarning(
"Minimum timestep must be finite, ignoring");
1226 if (minTimestep > m_maxTimestep) {
1227 qWarning(
"Minimum timestep greater than maximum timestep, value clamped");
1228 minTimestep = qMin(minTimestep, m_maxTimestep);
1231 if (minTimestep < 0.f) {
1232 qWarning(
"Minimum timestep less than zero, value clamped");
1233 minTimestep = qMax(minTimestep, 0.f);
1236 if (qFuzzyCompare(m_minTimestep, minTimestep))
1239 m_minTimestep = minTimestep;
1240 emit minimumTimestepChanged(m_minTimestep);
1243void QPhysicsWorld::setMaximumTimestep(
float maxTimestep)
1245 if (qFuzzyCompare(m_maxTimestep, maxTimestep))
1248 if (!qIsFinite(maxTimestep)) {
1249 qWarning(
"Maximum timestep must be finite, ignoring");
1253 if (maxTimestep < 0.f) {
1254 qWarning(
"Maximum timestep less than zero, value clamped");
1255 maxTimestep = qMax(maxTimestep, 0.f);
1258 if (qFuzzyCompare(m_maxTimestep, maxTimestep))
1261 m_maxTimestep = maxTimestep;
1262 emit maximumTimestepChanged(maxTimestep);
1265void QPhysicsWorld::setupDebugMaterials(QQuick3DNode *sceneNode)
1267 if (!m_debugMaterials.isEmpty())
1270 const int lineWidth = m_inDesignStudio ? 1 : 3;
1273 for (
auto color : { QColorConstants::Svg::chartreuse, QColorConstants::Svg::cyan,
1274 QColorConstants::Svg::lightsalmon, QColorConstants::Svg::red,
1275 QColorConstants::Svg::blueviolet, QColorConstants::Svg::black }) {
1276 auto debugMaterial =
new QQuick3DPrincipledMaterial();
1277 debugMaterial->setLineWidth(lineWidth);
1278 debugMaterial->setParentItem(sceneNode);
1279 debugMaterial->setParent(sceneNode);
1280 debugMaterial->setBaseColor(color);
1281 debugMaterial->setLighting(QQuick3DPrincipledMaterial::NoLighting);
1282 debugMaterial->setCullMode(QQuick3DMaterial::NoCulling);
1283 m_debugMaterials.push_back(debugMaterial);
1287void QPhysicsWorld::updateDebugDraw()
1289 if (!(m_forceDebugDraw || m_hasIndividualDebugDraw)) {
1291 for (
auto &holder : m_collisionShapeDebugModels) {
1292 holder.releaseMeshPointer();
1293 delete holder.model;
1295 m_collisionShapeDebugModels.clear();
1300 auto sceneNode = m_viewport ? m_viewport : m_scene;
1302 if (sceneNode ==
nullptr)
1305 setupDebugMaterials(sceneNode);
1306 m_hasIndividualDebugDraw =
false;
1309 QSet<QPair<QAbstractCollisionShape *, QAbstractPhysXNode *>> currentCollisionShapes;
1310 currentCollisionShapes.reserve(m_collisionShapeDebugModels.size());
1312 for (QAbstractPhysXNode *node : std::as_const(m_physXBodies)) {
1315 if (!node->frontendNode || !node->debugGeometryCapability())
1318 const auto &collisionShapes = node->frontendNode->getCollisionShapesList();
1319 const int materialIdx =
static_cast<
int>(node->getDebugDrawBodyType());
1320 const int length = collisionShapes.length();
1321 for (
int idx = 0; idx < length; idx++) {
1322 const auto collisionShape = collisionShapes[idx];
1324 if (!m_forceDebugDraw && !collisionShape->enableDebugDraw())
1327 DebugModelHolder &holder =
1328 m_collisionShapeDebugModels[std::make_pair(collisionShape, node)];
1329 auto &model = holder.model;
1331 currentCollisionShapes.insert(std::make_pair(collisionShape, node));
1333 m_hasIndividualDebugDraw =
1334 m_hasIndividualDebugDraw || collisionShape->enableDebugDraw();
1338 model =
new QQuick3DModel();
1339 model->setParentItem(sceneNode);
1340 model->setParent(sceneNode);
1341 model->setCastsShadows(
false);
1342 model->setReceivesShadows(
false);
1343 model->setCastsReflections(
false);
1346 model->setVisible(
true);
1349 auto material = m_debugMaterials[materialIdx];
1350 QQmlListReference materialsRef(model,
"materials");
1351 if (materialsRef.count() == 0 || materialsRef.at(0) != material) {
1352 materialsRef.clear();
1353 materialsRef.append(material);
1359 if (qobject_cast<QCharacterController *>(node->frontendNode)) {
1360 QCapsuleShape *capsuleShape = qobject_cast<QCapsuleShape *>(collisionShape);
1364 const float radius = capsuleShape->diameter() * 0.5;
1365 const float halfHeight = capsuleShape->height() * 0.5;
1367 if (!qFuzzyCompare(radius, holder.radius())
1368 || !qFuzzyCompare(halfHeight, holder.halfHeight())) {
1369 auto geom = QDebugDrawHelper::generateCapsuleGeometry(radius, halfHeight);
1370 geom->setParent(model);
1371 model->setGeometry(geom);
1372 holder.setRadius(radius);
1373 holder.setHalfHeight(halfHeight);
1376 model->setPosition(node->frontendNode->scenePosition());
1377 model->setRotation(node->frontendNode->sceneRotation()
1378 * QQuaternion::fromEulerAngles(0, 0, 90));
1382 if (node->shapes.length() < length)
1385 const auto physXShape = node->shapes[idx];
1386 auto localPose = physXShape->getLocalPose();
1388 const physx::PxGeometry &geometry = physXShape->getGeometry();
1390 switch (geometry.getType()) {
1391 case physx::PxGeometryType::eBOX: {
1392 const auto &boxGeometry =
static_cast<
const physx::PxBoxGeometry &>(geometry);
1393 const auto &halfExtentsOld = holder.halfExtents();
1394 const auto halfExtents = QPhysicsUtils::toQtType(boxGeometry.halfExtents);
1395 if (!qFuzzyCompare(halfExtentsOld, halfExtents)) {
1396 auto geom = QDebugDrawHelper::generateBoxGeometry(halfExtents);
1397 geom->setParent(model);
1398 model->setGeometry(geom);
1399 holder.setHalfExtents(halfExtents);
1405 case physx::PxGeometryType::eSPHERE: {
1406 const auto &sphereGeometry =
static_cast<
const physx::PxSphereGeometry &>(geometry);
1407 const float radius = holder.radius();
1408 if (!qFuzzyCompare(sphereGeometry.radius, radius)) {
1409 auto geom = QDebugDrawHelper::generateSphereGeometry(sphereGeometry.radius);
1410 geom->setParent(model);
1411 model->setGeometry(geom);
1412 holder.setRadius(sphereGeometry.radius);
1417 case physx::PxGeometryType::eCAPSULE: {
1418 const auto &capsuleGeometry =
1419 static_cast<
const physx::PxCapsuleGeometry &>(geometry);
1420 const float radius = holder.radius();
1421 const float halfHeight = holder.halfHeight();
1423 if (!qFuzzyCompare(capsuleGeometry.radius, radius)
1424 || !qFuzzyCompare(capsuleGeometry.halfHeight, halfHeight)) {
1425 auto geom = QDebugDrawHelper::generateCapsuleGeometry(
1426 capsuleGeometry.radius, capsuleGeometry.halfHeight);
1427 geom->setParent(model);
1428 model->setGeometry(geom);
1429 holder.setRadius(capsuleGeometry.radius);
1430 holder.setHalfHeight(capsuleGeometry.halfHeight);
1435 case physx::PxGeometryType::ePLANE:{
1437 const QQuaternion rotation =
1438 QPhysicsUtils::kMinus90YawRotation * QPhysicsUtils::toQtType(localPose.q);
1439 localPose = physx::PxTransform(localPose.p, QPhysicsUtils::toPhysXType(rotation));
1441 if (model->geometry() ==
nullptr) {
1442 auto geom = QDebugDrawHelper::generatePlaneGeometry();
1443 geom->setParent(model);
1444 model->setGeometry(geom);
1452 case physx::PxGeometryType::eHEIGHTFIELD: {
1453 const auto &heightFieldGeometry =
1454 static_cast<
const physx::PxHeightFieldGeometry &>(geometry);
1455 const float heightScale = holder.heightScale();
1456 const float rowScale = holder.rowScale();
1457 const float columnScale = holder.columnScale();
1459 if (
auto heightField = holder.getHeightField();
1460 heightField && heightField != heightFieldGeometry.heightField) {
1461 heightField->release();
1462 holder.setHeightField(
nullptr);
1465 if (!qFuzzyCompare(heightFieldGeometry.heightScale, heightScale)
1466 || !qFuzzyCompare(heightFieldGeometry.rowScale, rowScale)
1467 || !qFuzzyCompare(heightFieldGeometry.columnScale, columnScale)
1468 || !holder.getHeightField()) {
1469 if (!holder.getHeightField()) {
1470 heightFieldGeometry.heightField->acquireReference();
1471 holder.setHeightField(heightFieldGeometry.heightField);
1473 auto geom = QDebugDrawHelper::generateHeightFieldGeometry(
1474 heightFieldGeometry.heightField, heightFieldGeometry.heightScale,
1475 heightFieldGeometry.rowScale, heightFieldGeometry.columnScale);
1476 geom->setParent(model);
1477 model->setGeometry(geom);
1478 holder.setHeightScale(heightFieldGeometry.heightScale);
1479 holder.setRowScale(heightFieldGeometry.rowScale);
1480 holder.setColumnScale(heightFieldGeometry.columnScale);
1485 case physx::PxGeometryType::eCONVEXMESH: {
1486 const auto &convexMeshGeometry =
1487 static_cast<
const physx::PxConvexMeshGeometry &>(geometry);
1488 const auto rotation = convexMeshGeometry.scale.rotation * localPose.q;
1489 localPose = physx::PxTransform(localPose.p, rotation);
1490 model->setScale(QPhysicsUtils::toQtType(convexMeshGeometry.scale.scale));
1492 if (
auto convexMesh = holder.getConvexMesh();
1493 convexMesh && convexMesh != convexMeshGeometry.convexMesh) {
1494 convexMesh->release();
1495 holder.setConvexMesh(
nullptr);
1498 if (!model->geometry() || !holder.getConvexMesh()) {
1499 if (!holder.getConvexMesh()) {
1500 convexMeshGeometry.convexMesh->acquireReference();
1501 holder.setConvexMesh(convexMeshGeometry.convexMesh);
1503 auto geom = QDebugDrawHelper::generateConvexMeshGeometry(
1504 convexMeshGeometry.convexMesh);
1505 geom->setParent(model);
1506 model->setGeometry(geom);
1511 case physx::PxGeometryType::eTRIANGLEMESH: {
1512 const auto &triangleMeshGeometry =
1513 static_cast<
const physx::PxTriangleMeshGeometry &>(geometry);
1514 const auto rotation = triangleMeshGeometry.scale.rotation * localPose.q;
1515 localPose = physx::PxTransform(localPose.p, rotation);
1516 model->setScale(QPhysicsUtils::toQtType(triangleMeshGeometry.scale.scale));
1518 if (
auto triangleMesh = holder.getTriangleMesh();
1519 triangleMesh && triangleMesh != triangleMeshGeometry.triangleMesh) {
1520 triangleMesh->release();
1521 holder.setTriangleMesh(
nullptr);
1524 if (!model->geometry() || !holder.getTriangleMesh()) {
1525 if (!holder.getTriangleMesh()) {
1526 triangleMeshGeometry.triangleMesh->acquireReference();
1527 holder.setTriangleMesh(triangleMeshGeometry.triangleMesh);
1529 auto geom = QDebugDrawHelper::generateTriangleMeshGeometry(
1530 triangleMeshGeometry.triangleMesh);
1531 geom->setParent(model);
1532 model->setGeometry(geom);
1538 case physx::PxGeometryType::eCONVEXCORE:
1539 case physx::PxGeometryType::ePARTICLESYSTEM:
1540 case physx::PxGeometryType::eTETRAHEDRONMESH:
1541 case physx::PxGeometryType::eCUSTOM:
1542 case physx::PxGeometryType::eINVALID:
1543 case physx::PxGeometryType::eGEOMETRY_COUNT:
1548 auto globalPose = node->getGlobalPose();
1549 auto finalPose = globalPose.transform(localPose);
1551 model->setRotation(QPhysicsUtils::toQtType(finalPose.q));
1552 model->setPosition(QPhysicsUtils::toQtType(finalPose.p));
1557 m_collisionShapeDebugModels.removeIf(
1558 [&](QHash<QPair<QAbstractCollisionShape *, QAbstractPhysXNode *>,
1559 DebugModelHolder>::iterator it) {
1560 if (!currentCollisionShapes.contains(it.key())) {
1561 auto holder = it.value();
1562 holder.releaseMeshPointer();
1564 delete holder.model;
1573 if (
auto shape = qobject_cast<QAbstractPhysicsNode *>(node)) {
1574 nodes.push_back(shape);
1578 auto childItems = node->childItems();
1579 for (QQuick3DObject *child : std::as_const(childItems))
1580 collectPhysicsNodes(child, nodes);
1583void QPhysicsWorld::updateDebugDrawDesignStudio()
1586 auto sceneNode = m_viewport ? m_viewport : m_scene;
1588 if (sceneNode ==
nullptr)
1591 setupDebugMaterials(sceneNode);
1594 QSet<QPair<QAbstractCollisionShape *, QAbstractPhysicsNode *>> currentCollisionShapes;
1595 currentCollisionShapes.reserve(m_collisionShapeDebugModels.size());
1597 QList<QAbstractPhysicsNode *> activePhysicsNodes;
1598 activePhysicsNodes.reserve(m_collisionShapeDebugModels.size());
1599 collectPhysicsNodes(m_scene, activePhysicsNodes);
1601 for (QAbstractPhysicsNode *node : std::as_const(activePhysicsNodes)) {
1603 const auto &collisionShapes = node->getCollisionShapesList();
1604 const int materialIdx = 0;
1605 const int length = collisionShapes.length();
1607 const bool isCharacterController = qobject_cast<QCharacterController *>(node) !=
nullptr;
1609 for (
int idx = 0; idx < length; idx++) {
1610 QAbstractCollisionShape *collisionShape = collisionShapes[idx];
1611 DebugModelHolder &holder =
1612 m_DesignStudioDebugModels[std::make_pair(collisionShape, node)];
1613 auto &model = holder.model;
1615 currentCollisionShapes.insert(std::make_pair(collisionShape, node));
1617 m_hasIndividualDebugDraw =
1618 m_hasIndividualDebugDraw || collisionShape->enableDebugDraw();
1625 model =
new QQuick3DModel();
1626 model->setParentItem(sceneNode);
1627 model->setParent(sceneNode);
1628 model->setCastsShadows(
false);
1629 model->setReceivesShadows(
false);
1630 model->setCastsReflections(
false);
1633 const bool hasGeometry = holder.geometry !=
nullptr;
1634 QVector3D scenePosition = collisionShape->scenePosition();
1635 QQuaternion sceneRotation = collisionShape->sceneRotation();
1636 QQuick3DGeometry *newGeometry =
nullptr;
1638 if (isCharacterController)
1639 sceneRotation = sceneRotation * QQuaternion::fromEulerAngles(QVector3D(0, 0, 90));
1642 auto material = m_debugMaterials[materialIdx];
1643 QQmlListReference materialsRef(model,
"materials");
1644 if (materialsRef.count() == 0 || materialsRef.at(0) != material) {
1645 materialsRef.clear();
1646 materialsRef.append(material);
1650 if (
auto shape = qobject_cast<QBoxShape *>(collisionShape)) {
1651 const auto &halfExtentsOld = holder.halfExtents();
1652 const auto halfExtents = shape->sceneScale() * shape->extents() * 0.5f;
1653 if (!qFuzzyCompare(halfExtentsOld, halfExtents) || !hasGeometry) {
1654 newGeometry = QDebugDrawHelper::generateBoxGeometry(halfExtents);
1655 holder.setHalfExtents(halfExtents);
1657 }
else if (
auto shape = qobject_cast<QSphereShape *>(collisionShape)) {
1658 const float radiusOld = holder.radius();
1659 const float radius = shape->sceneScale().x() * shape->diameter() * 0.5f;
1660 if (!qFuzzyCompare(radiusOld, radius) || !hasGeometry) {
1661 newGeometry = QDebugDrawHelper::generateSphereGeometry(radius);
1662 holder.setRadius(radius);
1664 }
else if (
auto shape = qobject_cast<QCapsuleShape *>(collisionShape)) {
1665 const float radiusOld = holder.radius();
1666 const float halfHeightOld = holder.halfHeight();
1667 const float radius = shape->sceneScale().y() * shape->diameter() * 0.5f;
1668 const float halfHeight = shape->sceneScale().x() * shape->height() * 0.5f;
1670 if ((!qFuzzyCompare(radiusOld, radius) || !qFuzzyCompare(halfHeightOld, halfHeight))
1672 newGeometry = QDebugDrawHelper::generateCapsuleGeometry(radius, halfHeight);
1673 holder.setRadius(radius);
1674 holder.setHalfHeight(halfHeight);
1676 }
else if (qobject_cast<QPlaneShape *>(collisionShape)) {
1678 newGeometry = QDebugDrawHelper::generatePlaneGeometry();
1679 }
else if (
auto shape = qobject_cast<QHeightFieldShape *>(collisionShape)) {
1680 physx::PxHeightFieldGeometry *heightFieldGeometry =
1681 static_cast<physx::PxHeightFieldGeometry *>(shape->getPhysXGeometry());
1682 const float heightScale = holder.heightScale();
1683 const float rowScale = holder.rowScale();
1684 const float columnScale = holder.columnScale();
1685 scenePosition += shape->hfOffset();
1686 if (!heightFieldGeometry) {
1687 qWarning() <<
"Could not get height field";
1688 }
else if (!qFuzzyCompare(heightFieldGeometry->heightScale, heightScale)
1689 || !qFuzzyCompare(heightFieldGeometry->rowScale, rowScale)
1690 || !qFuzzyCompare(heightFieldGeometry->columnScale, columnScale)
1692 newGeometry = QDebugDrawHelper::generateHeightFieldGeometry(
1693 heightFieldGeometry->heightField, heightFieldGeometry->heightScale,
1694 heightFieldGeometry->rowScale, heightFieldGeometry->columnScale);
1695 holder.setHeightScale(heightFieldGeometry->heightScale);
1696 holder.setRowScale(heightFieldGeometry->rowScale);
1697 holder.setColumnScale(heightFieldGeometry->columnScale);
1699 }
else if (
auto shape = qobject_cast<QConvexMeshShape *>(collisionShape)) {
1700 auto convexMeshGeometry =
1701 static_cast<physx::PxConvexMeshGeometry *>(shape->getPhysXGeometry());
1702 if (!convexMeshGeometry) {
1703 qWarning() <<
"Could not get convex mesh";
1705 model->setScale(QPhysicsUtils::toQtType(convexMeshGeometry->scale.scale));
1708 newGeometry = QDebugDrawHelper::generateConvexMeshGeometry(
1709 convexMeshGeometry->convexMesh);
1712 }
else if (
auto shape = qobject_cast<QTriangleMeshShape *>(collisionShape)) {
1713 physx::PxTriangleMeshGeometry *triangleMeshGeometry =
1714 static_cast<physx::PxTriangleMeshGeometry *>(shape->getPhysXGeometry());
1715 if (!triangleMeshGeometry) {
1716 qWarning() <<
"Could not get triangle mesh";
1718 model->setScale(QPhysicsUtils::toQtType(triangleMeshGeometry->scale.scale));
1721 newGeometry = QDebugDrawHelper::generateTriangleMeshGeometry(
1722 triangleMeshGeometry->triangleMesh);
1728 delete holder.geometry;
1729 holder.geometry = newGeometry;
1732 model->setGeometry(holder.geometry);
1733 model->setVisible(
true);
1735 model->setRotation(sceneRotation);
1736 model->setPosition(scenePosition);
1741 m_DesignStudioDebugModels.removeIf(
1742 [&](QHash<QPair<QAbstractCollisionShape *, QAbstractPhysicsNode *>,
1743 DebugModelHolder>::iterator it) {
1744 if (!currentCollisionShapes.contains(it.key())) {
1745 auto holder = it.value();
1746 holder.releaseMeshPointer();
1748 delete holder.geometry;
1749 delete holder.model;
1757void QPhysicsWorld::disableDebugDraw()
1759 m_hasIndividualDebugDraw =
false;
1761 for (QAbstractPhysXNode *body : std::as_const(m_physXBodies)) {
1762 if (!body->frontendNode)
1765 const auto &collisionShapes = body->frontendNode->getCollisionShapesList();
1766 const int length = collisionShapes.length();
1767 for (
int idx = 0; idx < length; idx++) {
1768 const auto collisionShape = collisionShapes[idx];
1769 if (collisionShape->enableDebugDraw()) {
1770 m_hasIndividualDebugDraw =
true;
1777void QPhysicsWorld::setEnableCCD(
bool enableCCD)
1779 if (m_enableCCD == enableCCD)
1782 if (m_physicsInitialized) {
1784 <<
"Warning: Changing 'enableCCD' after physics is initialized will have no effect";
1788 m_enableCCD = enableCCD;
1789 emit enableCCDChanged(m_enableCCD);
1792void QPhysicsWorld::setTypicalLength(
float typicalLength)
1794 if (qFuzzyCompare(typicalLength, m_typicalLength))
1797 if (!qIsFinite(typicalLength) || typicalLength <= 0.f) {
1798 qWarning() <<
"Warning: 'typicalLength' value less than zero, ignored";
1802 if (m_physicsInitialized) {
1803 qWarning() <<
"Warning: Changing 'typicalLength' after physics is initialized will have "
1808 m_typicalLength = typicalLength;
1810 emit typicalLengthChanged(typicalLength);
1813void QPhysicsWorld::setTypicalSpeed(
float typicalSpeed)
1815 if (qFuzzyCompare(typicalSpeed, m_typicalSpeed))
1818 if (!qIsFinite(typicalSpeed) || typicalSpeed <= 0.f) {
1819 qWarning() <<
"Warning: 'typicalSpeed' must be finite and greater than zero, ignored";
1823 if (m_physicsInitialized) {
1824 qWarning() <<
"Warning: Changing 'typicalSpeed' after physics is initialized will have "
1829 m_typicalSpeed = typicalSpeed;
1831 emit typicalSpeedChanged(typicalSpeed);
1834float QPhysicsWorld::defaultDensity()
const
1836 return m_defaultDensity;
1839float QPhysicsWorld::minimumTimestep()
const
1841 return m_minTimestep;
1844float QPhysicsWorld::maximumTimestep()
const
1846 return m_maxTimestep;
1849void QPhysicsWorld::setDefaultDensity(
float defaultDensity)
1851 defaultDensity = qBound(0.0000001f, defaultDensity, PX_MAX_F32);
1853 if (qFuzzyCompare(m_defaultDensity, defaultDensity))
1855 m_defaultDensity = defaultDensity;
1858 for (QAbstractPhysXNode *body : std::as_const(m_physXBodies)) {
1859 if (body->frontendNode)
1860 body->updateDefaultDensity(m_defaultDensity);
1863 emit defaultDensityChanged(defaultDensity);
1868void QPhysicsWorld::cleanupRemovedNodes()
1870 m_physXBodies.removeIf([
this](QAbstractPhysXNode *body) {
1871 return body->cleanupIfRemoved(m_physx);
1873 m_removedPhysicsNodes.clear();
1879void QPhysicsWorld::invalidateTriggerOverlaps(QSpan<QAbstractPhysXNode *
const> rebuiltBodies)
1881 for (QAbstractPhysXNode *body : std::as_const(m_physXBodies)) {
1882 auto *trigger = qobject_cast<QAbstractTriggerRegion *>(body->frontendNode);
1885 for (QAbstractPhysXNode *rebuilt : rebuiltBodies) {
1890 if (rebuilt->frontendNode)
1891 trigger->invalidateOverlaps(rebuilt->frontendNode);
1895 m_triggerOverlapsInvalidated =
true;
1898void QPhysicsWorld::dropUnreportedTriggerOverlaps()
1902 if (!m_triggerOverlapsInvalidated)
1904 m_triggerOverlapsInvalidated =
false;
1910 for (QAbstractPhysXNode *body : std::as_const(m_physXBodies)) {
1911 if (
auto *trigger = qobject_cast<QAbstractTriggerRegion *>(body->frontendNode))
1912 trigger->dropUnreportedOverlaps();
1916void QPhysicsWorld::cleanupRemovedJoints()
1918 for (physx::PxJoint *joint : m_removedJoints) {
1922 m_removedJoints.clear();
1925void QPhysicsWorld::initPhysics()
1927 Q_ASSERT(!m_physicsInitialized);
1930 const unsigned int numThreads = m_numThreads >= 0 ? m_numThreads : qMax(0, QThread::idealThreadCount());
1933 const unsigned int numThreads = 0;
1935 m_physx->createScene(m_typicalLength, m_typicalSpeed, m_gravity,
this, numThreads);
1936 m_frameAnimator->start();
1937 m_physicsInitialized =
true;
1940void QPhysicsWorld::simulateFrame()
1942 constexpr double MILLIONTH = 0.000001;
1943 constexpr double THOUSANDTH = 0.001;
1945 if (m_inDesignStudio) {
1946 frameFinishedDesignStudio();
1950 if (!m_physx->isRunning) {
1952 m_physx->isRunning =
true;
1953 const double minTimestepSecs = m_minTimestep * 0.001;
1954 m_physx->scene->simulate(minTimestepSecs);
1955 m_currTimeStep = minTimestepSecs;
1960 if (!m_frameFetched && !m_physx->scene->checkResults()) {
1965 if (!m_frameFetched) {
1966 m_physx->scene->fetchResults(
true);
1967 frameFinished(m_currTimeStep);
1968 m_frameFetched =
true;
1969 if (Q_UNLIKELY(!qtPhysicsTimingsFile.isEmpty())) {
1970 const double deltaMS = m_timer.nsecsElapsed() * MILLIONTH;
1971 m_frameTimings.append(deltaMS);
1976 const double deltaMS = m_timer.nsecsElapsed() * MILLIONTH;
1977 if (deltaMS < m_minTimestep)
1979 const double deltaSecs = qMin<
double>(deltaMS, m_maxTimestep) * THOUSANDTH;
1981 m_physx->scene->simulate(deltaSecs);
1982 m_frameFetched =
false;
1983 m_currTimeStep = deltaSecs;
1986void QPhysicsWorld::frameFinished(
float deltaTime)
1989 matchOrphanJoints();
1990 matchOrphanRaycasters();
1996 dropUnreportedTriggerOverlaps();
1998 emitContactCallbacks();
1999 cleanupRemovedNodes();
2000 cleanupRemovedJoints();
2002 for (
auto *node : std::as_const(m_newPhysicsNodes)) {
2003 auto *body = node->createPhysXBackend();
2004 body->init(
this, m_physx);
2005 m_physXBodies.push_back(body);
2007 m_newPhysicsNodes.clear();
2011 QHash<QQuick3DNode *, QMatrix4x4> transformCache;
2012 QVarLengthArray<QAbstractPhysXNode *, 8> rebuiltBodies;
2015 for (
auto *physXBody : std::as_const(m_physXBodies)) {
2018 if (!physXBody->frontendNode)
2021 physXBody->markDirtyShapes();
2022 const bool wasDirty = physXBody->shapesDirty();
2023 physXBody->rebuildDirtyShapes(
this, m_physx);
2026 if (!physXBody->frontendNode)
2031 if (wasDirty && !physXBody->shapesDirty())
2032 rebuiltBodies.append(physXBody);
2033 physXBody->updateFilters(m_physx);
2036 physXBody->sync(deltaTime, transformCache);
2039 if (!rebuiltBodies.isEmpty())
2040 invalidateTriggerOverlaps(rebuiltBodies);
2042 for (QPhysicsJoint *joint : std::as_const(m_joints)) {
2043 joint->updatePhysXBackend();
2046 const QList<QRaycaster *> raycasters = m_raycasters;
2047 for (QRaycaster *raycaster : raycasters) {
2048 if (m_raycasters.contains(raycaster))
2049 raycaster->updateRaycast(
this);
2053 emit frameDone(deltaTime * 1000);
2056void QPhysicsWorld::frameFinishedDesignStudio()
2060 matchOrphanJoints();
2063 matchOrphanRaycasters();
2064 emitContactCallbacks();
2065 cleanupRemovedNodes();
2067 m_newPhysicsNodes.clear();
2069 updateDebugDrawDesignStudio();
2072QPhysicsWorld *QPhysicsWorld::getWorld(QQuick3DNode *node)
2074 for (QPhysicsWorld *world : std::as_const(worldManager.worlds)) {
2075 if (!world->m_scene) {
2079 QQuick3DNode *nodeCurr = node;
2082 if (nodeCurr == world->m_scene)
2085 while (nodeCurr->parentNode()) {
2086 nodeCurr = nodeCurr->parentNode();
2087 if (nodeCurr == world->m_scene)
2095QPhysicsWorld *QPhysicsWorld::getWorld(QPhysicsJoint *joint)
2097 for (QPhysicsWorld *world : worldManager.worlds) {
2098 if (!world->m_scene) {
2102 QObject *nodeCurr = joint;
2104 while (nodeCurr->parent()) {
2105 nodeCurr = nodeCurr->parent();
2106 if (nodeCurr == world->m_scene) {
2108 }
else if (
auto view3d = qobject_cast<QQuick3DViewport *>(nodeCurr);
2109 view3d && view3d->scene() == world->m_scene) {
2119void QPhysicsWorld::matchOrphanNodes()
2122 if (worldManager.orphanNodes.isEmpty())
2125 qsizetype numNodes = worldManager.orphanNodes.length();
2128 while (idx < numNodes) {
2129 auto node = worldManager.orphanNodes[idx];
2130 auto world = getWorld(node);
2131 if (world ==
this) {
2132 world->m_newPhysicsNodes.push_back(node);
2134 worldManager.orphanNodes.swapItemsAt(idx, numNodes - 1);
2135 worldManager.orphanNodes.pop_back();
2143void QPhysicsWorld::matchOrphanJoints()
2145 if (worldManager.orphanJoints.isEmpty())
2148 qsizetype numNodes = worldManager.orphanJoints.length();
2151 while (idx < numNodes) {
2152 auto node = worldManager.orphanJoints[idx];
2153 auto world = getWorld(node);
2154 if (world ==
this) {
2155 world->m_joints.push_back(node);
2157 worldManager.orphanJoints.swapItemsAt(idx, numNodes - 1);
2158 worldManager.orphanJoints.pop_back();
2166void QPhysicsWorld::matchOrphanRaycasters()
2169 while (idx < worldManager.orphanRaycasters.size()) {
2170 QRaycaster *raycaster = worldManager.orphanRaycasters.at(idx);
2171 if (getWorld(raycaster) ==
this) {
2172 m_raycasters.push_back(raycaster);
2173 worldManager.orphanRaycasters.removeAt(idx);
2180void QPhysicsWorld::applyGravity()
2185 if (m_gravityFields.isEmpty() && m_staleGravityFilters.isEmpty()
2186 && m_gravityWakes.isEmpty()) {
2191 const auto wakes = std::exchange(m_gravityWakes, {});
2192 for (
const QPointer<QAbstractPhysicsNode> &node : wakes) {
2194 QPhysXGravity::wake(node, node->m_backendObject);
2199 QVarLengthArray<QPhysXGravityField::SceneGravity, 4> sceneFields;
2200 for (QPhysXGravityField *field : std::as_const(m_gravityFields)) {
2201 if (
const auto scene = field->applyGravity(m_staleGravityFilters))
2202 sceneFields.append(*scene);
2208 const QList<QFilterData> staleFilters = std::exchange(m_staleGravityFilters, {});
2210 if (sceneFields.isEmpty() && staleFilters.isEmpty())
2213 for (QAbstractPhysXNode *backend : std::as_const(m_physXBodies)) {
2214 QAbstractPhysicsNode *node = backend->frontendNode;
2217 const auto target = QPhysicsGravity::targetOf(node);
2218 if (target == QPhysicsGravity::Target::None)
2222 const QFilterData nodeFilterData = node->filterData();
2230 const bool bodyFilterChanged = !sceneFields.isEmpty() && backend->filtersDirty();
2231 const bool lostField = std::any_of(staleFilters.cbegin(), staleFilters.cend(),
2232 [&nodeFilterData](
const QFilterData &filter) {
2233 return !QPhysicsUtils::isFilteredOut(
2234 filter, nodeFilterData);
2236 if (bodyFilterChanged || lostField)
2237 QPhysXGravity::wake(node, backend);
2239 for (
const QPhysXGravityField::SceneGravity &field : std::as_const(sceneFields)) {
2240 if (!QPhysicsUtils::isFilteredOut(field.filterData, nodeFilterData))
2241 QPhysXGravity::apply(field.gravity, target, node, backend, field.wake);
2246void QPhysicsWorld::releaseGravityField(QAbstractPhysXNode *backend)
2248 const auto it = std::find(m_gravityFields.begin(), m_gravityFields.end(), backend);
2249 if (it == m_gravityFields.end())
2251 QPhysXGravityField *field = *it;
2252 m_gravityFields.erase(it);
2253 m_gravityWakes.append(std::exchange(field->wakesOnRemoval, {}));
2254 if (field->staleFilterOnRemoval)
2255 m_staleGravityFilters.append(*field->staleFilterOnRemoval);
2258void QPhysicsWorld::findPhysicsNodes()
2263 if (m_scene ==
nullptr)
2267 QList<QQuick3DObject *> children = m_scene->childItems();
2268 while (!children.empty()) {
2269 auto child = children.takeFirst();
2270 if (
auto converted = qobject_cast<QAbstractPhysicsNode *>(child); converted !=
nullptr) {
2272 if (converted->m_backendObject !=
nullptr) {
2273 qWarning() <<
"Warning: physics node already associated with a backend node.";
2277 m_newPhysicsNodes.push_back(converted);
2278 worldManager.orphanNodes.removeAll(converted);
2280 children.append(child->childItems());
2284void QPhysicsWorld::emitContactCallbacks()
2286 for (
const QPhysicsWorld::BodyContact &contact : std::as_const(m_registeredContacts)) {
2287 if (m_removedPhysicsNodes.contains(contact.sender)
2288 || m_removedPhysicsNodes.contains(contact.receiver))
2290 contact.receiver->registerContact(contact.sender, contact.positions, contact.impulses,
2294 m_registeredContacts.clear();
2297physx::PxPhysics *QPhysicsWorld::getPhysics()
2299 return StaticPhysXObjects::getReference().physics;
2302const physx::PxCookingParams *QPhysicsWorld::getCookingParams()
2307 if (!StaticPhysXObjects::getReference().foundationCreated)
2311 static const physx::PxCookingParams params { physx::PxTolerancesScale() };
2315physx::PxControllerManager *QPhysicsWorld::controllerManager()
2317 if (m_physx->scene && !m_physx->controllerManager) {
2318 m_physx->controllerManager = PxCreateControllerManager(*m_physx->scene);
2319 qCDebug(lcQuick3dPhysics) <<
"Created controller manager" << m_physx->controllerManager;
2321 return m_physx->controllerManager;
2324QQuick3DNode *QPhysicsWorld::scene()
const
2329void QPhysicsWorld::setScene(QQuick3DNode *newScene)
2331 if (m_scene == newScene)
2339 for (
auto body : std::as_const(m_physXBodies)) {
2340 if (body->frontendNode)
2341 deregisterNode(body->frontendNode);
2347 const QList<QRaycaster *> raycasters = std::exchange(m_raycasters, {});
2348 worldManager.orphanRaycasters += raycasters;
2349 for (QRaycaster *raycaster : raycasters) {
2350 if (worldManager.orphanRaycasters.contains(raycaster))
2351 raycaster->clearHit();
2355 bool sceneOK =
true;
2356 for (QPhysicsWorld *world : std::as_const(worldManager.worlds)) {
2357 if (world !=
this && world->scene() == newScene) {
2359 qWarning() <<
"Warning: scene already associated with physics world";
2365 matchOrphanRaycasters();
2367 emit sceneChanged();
2370int QPhysicsWorld::numThreads()
const
2372 return m_numThreads;
2375void QPhysicsWorld::setNumThreads(
int newNumThreads)
2377 newNumThreads = qMin(newNumThreads, 256);
2379 if (m_numThreads == newNumThreads)
2382 m_numThreads = newNumThreads;
2383 emit numThreadsChanged();
2386bool QPhysicsWorld::reportKinematicKinematicCollisions()
const
2388 return m_reportKinematicKinematicCollisions;
2391void QPhysicsWorld::setReportKinematicKinematicCollisions(
2392 bool newReportKinematicKinematicCollisions)
2394 if (m_reportKinematicKinematicCollisions == newReportKinematicKinematicCollisions)
2396 m_reportKinematicKinematicCollisions = newReportKinematicKinematicCollisions;
2397 emit reportKinematicKinematicCollisionsChanged();
2400bool QPhysicsWorld::reportStaticKinematicCollisions()
const
2402 return m_reportStaticKinematicCollisions;
2405void QPhysicsWorld::setReportStaticKinematicCollisions(
bool newReportStaticKinematicCollisions)
2407 if (m_reportStaticKinematicCollisions == newReportStaticKinematicCollisions)
2409 m_reportStaticKinematicCollisions = newReportStaticKinematicCollisions;
2410 emit reportStaticKinematicCollisionsChanged();
2413QPhysicsWorld::QueryStructure QPhysicsWorld::staticQueryStructure()
const
2415 return m_staticQueryStructure;
2418void QPhysicsWorld::setStaticQueryStructure(QueryStructure newStaticQueryStructure)
2420 if (m_staticQueryStructure == newStaticQueryStructure)
2423 if (newStaticQueryStructure == QueryStructure::NoStructure) {
2425 <<
"Warning: The QueryStructure::NoStructure is not supported for staticQueryStructure. Available options: [StaticTree, DynamicTree]";
2429 if (m_physicsInitialized) {
2431 <<
"Warning: Changing 'staticQueryStructure' after physics is initialized will have no effect";
2435 m_staticQueryStructure = newStaticQueryStructure;
2436 emit staticQueryStructureChanged();
2439QPhysicsWorld::QueryStructure QPhysicsWorld::dynamicQueryStructure()
const
2441 return m_dynamicQueryStructure;
2444void QPhysicsWorld::setDynamicQueryStructure(QueryStructure newDynamicQueryStructure)
2446 if (m_dynamicQueryStructure == newDynamicQueryStructure)
2449 if (m_physicsInitialized) {
2451 <<
"Warning: Changing 'dynamicQueryStructure' after physics is initialized will have no effect";
2455 m_dynamicQueryStructure = newDynamicQueryStructure;
2456 emit dynamicQueryStructureChanged();
2459bool QPhysicsWorld::testRaycastQuery(
const QVector3D &origin,
2460 const QVector3D &direction,
2463 bool includeDynamic)
const
2465 physx::PxRaycastBuffer hitBuffer;
2466 return raycastImpl(m_physx->scene, origin, direction,
2467 maxDistance, includeStatic, includeDynamic,
2469 physx::PxHitFlags(),
2470 physx::PxQueryFlag::eANY_HIT);
2473QQuick3DPhysicsLocationHit QPhysicsWorld::singleRaycastQuery(
const QVector3D &origin,
2474 const QVector3D &direction,
2477 bool includeDynamic)
const
2479 physx::PxRaycastBuffer hitBuffer;
2480 const bool status = raycastImpl(m_physx->scene, origin, direction,
2481 maxDistance, includeStatic, includeDynamic,
2483 physx::PxHitFlag::eDEFAULT);
2485 if (status && hitBuffer.hasBlock) {
2486 return QQuick3DPhysicsLocationHit(hitBuffer.block,
2493QList<QQuick3DPhysicsLocationHit> QPhysicsWorld::multiRaycastQuery(
const QVector3D &origin,
2494 const QVector3D &direction,
2497 bool includeDynamic)
const
2499 DynamicQueryCallback<physx::PxRaycastCallback,
2500 QQuick3DPhysicsLocationHit,
2501 physx::PxRaycastHit> hitBuffer;
2503 if (raycastImpl(m_physx->scene, origin, direction,
2504 maxDistance, includeStatic, includeDynamic,
2506 physx::PxHitFlag::eDEFAULT,
2507 physx::PxQueryFlag::eNO_BLOCK)) {
2509 return hitBuffer.hits;
2515QQuick3DPhysicsLocationHit
2516QPhysicsWorld::closestRaycastHit(
const QVector3D &origin,
const QVector3D &direction,
2517 float maxDistance,
bool includeStatic,
bool includeDynamic,
2518 QSpan<
const QAbstractPhysicsNode *
const> excludedBodies)
const
2520 ExcludedBodiesFilter filter(excludedBodies);
2521 physx::PxRaycastBuffer hitBuffer;
2522 const bool status = raycastImpl(m_physx->scene, origin, direction, maxDistance, includeStatic,
2523 includeDynamic, hitBuffer, physx::PxHitFlag::eDEFAULT,
2524 physx::PxQueryFlag::ePREFILTER, &filter);
2526 if (status && hitBuffer.hasBlock)
2527 return QQuick3DPhysicsLocationHit(hitBuffer.block, hitBuffer.block);
2532bool QPhysicsWorld::testSweepQuery(QAbstractCollisionShape *shape,
2533 const QVector3D &direction,
2536 bool includeDynamic)
const
2538 physx::PxSweepBuffer hitBuffer;
2539 return sweepImpl(m_physx->scene, shape, direction,
2540 maxDistance, includeStatic, includeDynamic,
2542 physx::PxHitFlags(),
2543 physx::PxQueryFlag::eANY_HIT);
2546QQuick3DPhysicsLocationHit QPhysicsWorld::singleSweepQuery(QAbstractCollisionShape *shape,
2547 const QVector3D &direction,
2550 bool includeDynamic)
const
2552 physx::PxSweepBuffer hitBuffer;
2553 const bool status = sweepImpl(m_physx->scene, shape,
2554 direction, maxDistance, includeStatic, includeDynamic,
2556 physx::PxHitFlag::eDEFAULT | physx::PxHitFlag::eMTD);
2558 if (status && hitBuffer.hasBlock) {
2559 return QQuick3DPhysicsLocationHit(hitBuffer.block, hitBuffer.block);
2565QList<QQuick3DPhysicsLocationHit> QPhysicsWorld::multiSweepQuery(QAbstractCollisionShape *shape,
2566 const QVector3D &direction,
2569 bool includeDynamic)
const
2571 DynamicQueryCallback<physx::PxSweepCallback,
2572 QQuick3DPhysicsLocationHit,
2573 physx::PxSweepHit> hitBuffer;
2575 if (sweepImpl(m_physx->scene, shape,
2576 direction, maxDistance, includeStatic, includeDynamic,
2578 physx::PxHitFlag::eDEFAULT | physx::PxHitFlag::eMTD,
2579 physx::PxQueryFlag::eNO_BLOCK)) {
2580 return hitBuffer.hits;
2586bool QPhysicsWorld::testOverlapQuery(QAbstractCollisionShape *shape,
2588 bool includeDynamic)
const
2590 physx::PxOverlapBuffer hitBuffer;
2591 return overlapImpl(m_physx->scene,
2592 shape, includeStatic, includeDynamic,
2594 physx::PxQueryFlag::eANY_HIT);
2597QList<QQuick3DPhysicsQueryHit> QPhysicsWorld::multiOverlapQuery(QAbstractCollisionShape *shape,
2599 bool includeDynamic)
const
2601 DynamicQueryCallback<physx::PxOverlapCallback,
2602 QQuick3DPhysicsQueryHit,
2603 physx::PxOverlapHit> hitBuffer;
2605 if (overlapImpl(m_physx->scene,
2606 shape, includeStatic, includeDynamic,
2608 physx::PxQueryFlag::eNO_BLOCK)) {
2609 return hitBuffer.hits;
2617#include "qphysicsworld.moc"
The QVector3D class represents a vector or vertex in 3D space.
PxTransformT< float > PxTransform
Q_LOGGING_CATEGORY(lcEventDispatcher, "qt.eventdispatcher")
static QWorldManager worldManager
static bool raycastImpl(const physx::PxScene *scene, const QVector3D &origin, const QVector3D &direction, float maxDistance, bool includeStatic, bool includeDynamic, physx::PxRaycastCallback &hitCallback, physx::PxHitFlags hitFlags, physx::PxQueryFlags extraQueryFlags={}, physx::PxQueryFilterCallback *filterCall=nullptr)
static bool validateQuery(const physx::PxScene *scene, bool includeStatic, bool includeDynamic)
static const physx::PxGeometry * validateQueryShape(const physx::PxScene *scene, QAbstractCollisionShape *shape, bool includeStatic, bool includeDynamic)
static void collectPhysicsNodes(QQuick3DObject *node, QList< QAbstractPhysicsNode * > &nodes)
static const QString qtPhysicsTimingsFile
static bool sweepImpl(const physx::PxScene *scene, QAbstractCollisionShape *shape, const QVector3D &direction, float maxDistance, bool includeStatic, bool includeDynamic, physx::PxSweepCallback &hitCallback, physx::PxHitFlags hitFlags, physx::PxQueryFlags extraQueryFlags={})
static bool overlapImpl(const physx::PxScene *scene, QAbstractCollisionShape *shape, bool includeStatic, bool includeDynamic, physx::PxOverlapCallback &hitCallback, physx::PxQueryFlags extraQueryFlags={})
#define QT_CONFIG(feature)
#define QT_BEGIN_NAMESPACE
QVector< QAbstractPhysicsNode * > orphanNodes
QVector< QPhysicsWorld * > worlds
QVector< QRaycaster * > orphanRaycasters
QVector< QPhysicsJoint * > orphanJoints