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
qphysicsworld.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 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 "physxnode/qabstractphysxnode_p.h"
8#include "physxnode/qphysxworld_p.h"
12#include "joints/qjoint_p.h"
14#include "qboxshape_p.h"
15#include "qsphereshape_p.h"
20#include "qplaneshape_p.h"
21#include "qraycaster_p.h"
25#include "physxnode/qphysxgravity_p.h"
26#include "physxnode/qphysxgravityfield_p.h"
27
28#include "PxPhysicsAPI.h"
29#include "cooking/PxCooking.h"
30#include <foundation/PxSimpleTypes.h>
31
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>
38
39#include <QtCore/qvarlengtharray.h>
40#include <QtGui/qquaternion.h>
41
42#include <QtEnvironmentVariables>
43
44#include <algorithm>
45
47
48/*!
49 \qmltype PhysicsWorld
50 \inqmlmodule QtQuick3D.Physics
51 \since 6.4
52 \brief Controls the physics simulation.
53
54 The PhysicsWorld type controls the physics simulation. This node is used to create an instance of the physics world as well
55 as define its properties. There can only be one physics world. All collision nodes in the qml
56 will get added automatically to the physics world.
57
58 \section1 Simulation timestep
59
60 The simulation works in lockstep with the rendering, meaning a new
61 simulation frame will only be started after a rendered frame has completed.
62 This means that at most one simulation frame will run per rendered frame.
63 The timestep of a simulation frame is the time since the previous one, so
64 it follows the frame rate. A simulation frame is skipped if less than
65 \l minimumTimestep has passed, and the timestep is capped at
66 \l maximumTimestep.
67
68 The simulation is sensitive to very small and very large timesteps, and to
69 large variations between them. Uneven frame pacing, for example while the
70 window is being resized, can make the simulation jittery or unstable.
71 Keeping \l minimumTimestep and \l maximumTimestep close together gives a
72 steadier simulation.
73*/
74
75/*!
76 \qmlproperty vector3d PhysicsWorld::gravity
77 This property defines the gravity vector of the physics world.
78 The default value is \c (0, -981, 0). Set the value to \c{Qt.vector3d(0, -9.81, 0)} if your
79 unit of measurement is meters and you are simulating Earth gravity.
80*/
81
82/*!
83 \qmlproperty bool PhysicsWorld::running
84 This property starts or stops the physical simulation. The default value is \c true.
85*/
86
87/*!
88 \qmlproperty bool PhysicsWorld::forceDebugDraw
89 This property enables debug drawing of all active shapes in the physics world. The default value
90 is \c false.
91*/
92
93/*!
94 \qmlproperty bool PhysicsWorld::enableCCD
95 \deprecated [6.13] Use DynamicRigidBody::ccd instead.
96
97 This property enables continuous collision detection globally for every dynamic body
98 in the scene that does not explicitly set its own \l DynamicRigidBody::ccd mode.
99 It reduces the risk of fast-moving bodies passing through geometry at high velocities
100 (also known as tunnelling).
101
102 For non-kinematic dynamic bodies, enabling this property uses sweep-based CCD.
103 For kinematic bodies, it automatically uses speculative CCD, as sweep-based CCD
104 is not supported for them.
105
106 Continuous collision detection can also be configured per body via
107 \l DynamicRigidBody::ccd, which avoids paying its performance cost for
108 objects that do not need it.
109
110 \warning Using trigger bodies with CCD enabled is not supported and can
111 result in missing or false trigger reports.
112
113 \default false
114
115 \sa DynamicRigidBody::ccd
116*/
117
118/*!
119 \qmlproperty real PhysicsWorld::typicalLength
120 This property defines the approximate size of objects in the simulation. This is used to
121 estimate certain length-related tolerances. Objects much smaller or much larger than this
122 size may not behave properly. The default value is \c 100.
123
124 Range: \c{[0, inf]}
125*/
126
127/*!
128 \qmlproperty real PhysicsWorld::typicalSpeed
129 This property defines the typical magnitude of velocities of objects in simulation. This is used
130 to estimate whether a contact should be treated as bouncing or resting based on its impact
131 velocity, and a kinetic energy threshold below which the simulation may put objects to sleep.
132
133 For normal physical environments, a good choice is the approximate speed of an object falling
134 under gravity for one second. The default value is \c 1000.
135
136 Range: \c{[0, inf]}
137*/
138
139/*!
140 \qmlproperty real PhysicsWorld::defaultDensity
141 This property defines the default density of dynamic objects, measured in kilograms per cubic
142 unit. This is equal to the weight of a cube with side \c 1.
143
144 The default value is \c 0.001, corresponding to 1 g/cm³: the density of water. If your unit of
145 measurement is meters, a good value would be \c 1000. Note that only positive values are
146 allowed.
147
148 Range: \c{(0, inf]}
149*/
150
151/*!
152 \qmlproperty Node PhysicsWorld::viewport
153 This property defines the viewport where debug components will be drawn if \l{forceDebugDraw}
154 is enabled. If unset the \l{scene} node will be used.
155
156 \sa forceDebugDraw, scene
157*/
158
159/*!
160 \qmlproperty real PhysicsWorld::minimumTimestep
161 This property defines the minimum simulation timestep in milliseconds. The default value is
162 \c{1}.
163
164 Range: \c{[0, maximumTimestep]}
165
166 \sa {Simulation timestep}
167*/
168
169/*!
170 \qmlproperty real PhysicsWorld::maximumTimestep
171 This property defines the maximum simulation timestep in milliseconds. The default value is
172 \c{33.333}.
173
174 Range: \c{[0, inf]}
175
176 \sa {Simulation timestep}
177*/
178
179/*!
180 \qmlproperty Node PhysicsWorld::scene
181
182 This property defines the top-most Node that contains all the nodes of the physical
183 simulation. All physics objects that are an ancestor of this node will be seen as part of this
184 PhysicsWorld.
185
186 \note Using the same scene node for several PhysicsWorld is unsupported.
187*/
188
189/*!
190 \qmlsignal PhysicsWorld::frameDone(float timestep)
191 \since 6.5
192
193 This signal is emitted when the physical simulation is done simulating a frame. The \a timestep
194 parameter is how long in milliseconds the timestep was in the simulation.
195*/
196
197/*!
198 \qmlproperty int PhysicsWorld::numThreads
199 \since 6.7
200
201 This property defines the number of threads used for the physical simulation. This is how the
202 range of values are interpreted:
203
204 \table
205 \header
206 \li Value
207 \li Range
208 \li Description
209 \row
210 \li Negative
211 \li \c{[-inf, -1]}
212 \li Automatic thread count. The application will try to query the number of threads from the
213 system.
214 \row
215 \li Zero
216 \li \c{{0}}
217 \li No threading, simulation will run sequentially.
218 \row
219 \li Positive
220 \li \c{[1, 256]}
221 \li Specific thread count. Values above 256 are clamped.
222 \endtable
223
224 The default value is \c{-1}, meaning automatic thread count.
225
226 \note Once the scene has started running it is not possible to change the number of threads.
227*/
228
229/*!
230 \qmlproperty bool PhysicsWorld::reportKinematicKinematicCollisions
231 \since 6.7
232
233 This property controls if collisions between pairs of \e{kinematic} dynamic rigid bodies will
234 trigger a contact report.
235
236 The default value is \c{false}.
237
238 \note Once the scene has started running it is not possible to change this setting.
239 \sa PhysicsWorld::reportStaticKinematicCollisions
240 \sa DynamicRigidBody
241 \sa PhysicsNode::bodyContact
242*/
243
244/*!
245 \qmlproperty bool PhysicsWorld::reportStaticKinematicCollisions
246 \since 6.7
247
248 This property controls if collisions between a static rigid body and a \e{kinematic} dynamic
249 rigid body will trigger a contact report.
250
251 The default value is \c{false}.
252
253 \note Once the scene has started running it is not possible to change this setting.
254 \sa PhysicsWorld::reportKinematicKinematicCollisions
255 \sa StaticRigidBody
256 \sa DynamicRigidBody
257 \sa PhysicsNode::bodyContact
258*/
259
260/*!
261 \qmlproperty QueryStructure PhysicsWorld::staticQueryStructure
262 \since 6.13
263
264 The spatial pruning structure type used to accelerate scene queries
265 (raycasts, sweeps, overlaps - used in CharacterController and a \e{kinematic} dynamic rigid body)
266 against static actors in the physics scene. It has no effect on rigid-body
267 contact/collision detection during simulation.
268
269 The following values are available:
270
271 \value PhysicsWorld.StaticTree
272 Uses a pre-baked static AABB tree. Offers maximum scene query performance with zero per-frame management overhead.
273 Best for fully static, immutable scenes. Inserting or removing objects at runtime causes heavy scene rebuilds and frame spikes.
274 \value PhysicsWorld.DynamicTree
275 Uses a dynamic self-balancing AABB tree. Allows fast, local runtime insertion (logarithmic time) and removal of static objects without freezing the frame.
276 Ideal for seamless open-world streaming where static chunks are loaded dynamically.
277
278 \default PhysicsWorld.DynamicTree
279
280 \note Once the scene has started running it is not possible to change this setting.
281 \note PhysicsWorld.NoStructure is not supported for staticQueryStructure
282
283 \sa PhysicsWorld::dynamicQueryStructure
284
285*/
286
287/*!
288 \qmlproperty QueryStructure PhysicsWorld::dynamicQueryStructure
289 \since 6.13
290
291 The spatial pruning structure type used to accelerate scene queries
292 (raycasts, sweeps, overlaps - used in CharacterController and a \e{kinematic} dynamic rigid body)
293 against dynamic actors in the physics scene. It has no effect on rigid-body
294 contact/collision detection during simulation.
295
296 The following values are available:
297
298 \value PhysicsWorld.NoStructure
299 Disables the scene query acceleration structure for dynamic actors.
300 Eliminates CPU overhead for tree maintenance when objects move, spawn, or are destroyed.
301 Scene queries will fall back to a linear search. Ideal when scene queries are not needed for dynamic objects.
302 \value PhysicsWorld.StaticTree
303 Uses a static AABB tree. Offers faster scene queries for dynamic actors, but updating the tree when objects move or spawn is very expensive.
304 Best when dynamic actors rarely move or spend most of their time sleeping.
305 \value PhysicsWorld.DynamicTree
306 Uses a dynamic self-balancing AABB tree. Allows fast, local runtime insertion (logarithmic time), movement, and removal of dynamic objects without freezing the frame.
307 Ideal for active scenes with frequently moving or spawning dynamic actors.
308
309 \default PhysicsWorld.DynamicTree
310
311 \note Once the scene has started running it is not possible to change this setting.
312 \sa PhysicsWorld::staticQueryStructure
313*/
314
315/*!
316 \qmlmethod bool PhysicsWorld::testRaycastQuery(vector3d origin, vector3d direction,
317 real maxDistance,
318 bool includeStatic = true,
319 bool includeDynamic = true)
320 \since 6.13
321
322 Performs a fast occlusion check along a ray without computing precise hit
323 geometry or returning hit data.
324
325 Returns \c true if the ray hits a body within \a maxDistance; otherwise returns
326 \c false. The query stops at the first body it finds, which makes it the cheapest
327 of the raycast queries.
328
329 \list
330 \li \a origin is the starting position of the ray, in world space.
331 \li \a direction is the direction of the ray. It must not be a null vector and does
332 not need to be normalized; the query normalizes it.
333 \li \a maxDistance is the maximum distance along \a direction to cast the ray. It
334 must be greater than 0.
335 \li \a includeStatic includes static bodies in the query when \c true.
336 \li \a includeDynamic includes dynamic bodies in the query when \c true.
337 \endlist
338
339 \include qtquick3dphysics-queries.qdocinc include_flags
340
341 \include qtquick3dphysics-queries.qdocinc query_exclusions
342
343 \include qtquick3dphysics-queries.qdocinc mesh_raycast_limits
344
345 \sa singleRaycastQuery, multiRaycastQuery, {Qt Quick 3D Physics Scene Queries}
346*/
347
348/*!
349 \qmlmethod locationHit PhysicsWorld::singleRaycastQuery(vector3d origin,
350 vector3d direction,
351 real maxDistance,
352 bool includeStatic = true,
353 bool includeDynamic = true)
354 \since 6.13
355
356 Casts a ray through the physics scene and returns the closest body it hits.
357
358 The ray starts at \a origin and extends along \a direction up to \a maxDistance.
359 Returns a \l locationHit describing the closest intersection.
360
361 \list
362 \li \a origin is the starting position of the ray, in world space.
363 \li \a direction is the direction of the ray. It must not be a null vector and does
364 not need to be normalized; the query normalizes it.
365 \li \a maxDistance is the maximum distance along \a direction to cast the ray. It
366 must be greater than 0.
367 \li \a includeStatic includes static bodies in the query when \c true.
368 \li \a includeDynamic includes dynamic bodies in the query when \c true.
369 \endlist
370
371 \include qtquick3dphysics-queries.qdocinc include_flags
372
373 \include qtquick3dphysics-queries.qdocinc hit_miss_return
374
375 \include qtquick3dphysics-queries.qdocinc query_exclusions
376
377 \include qtquick3dphysics-queries.qdocinc mesh_raycast_limits
378
379 \sa testRaycastQuery, multiRaycastQuery, {Qt Quick 3D Physics Scene Queries}
380*/
381
382/*!
383 \qmlmethod list<locationHit> PhysicsWorld::multiRaycastQuery(vector3d origin,
384 vector3d direction,
385 real maxDistance,
386 bool includeStatic = true,
387 bool includeDynamic = true)
388 \since 6.13
389
390 Casts a ray through the physics scene and returns every body it passes through,
391 rather than stopping at the closest one.
392
393 The ray starts at \a origin and extends along \a direction up to \a maxDistance.
394 Returns a \l locationHit for each body hit, or an empty list if the ray hits
395 nothing.
396
397 \list
398 \li \a origin is the starting position of the ray, in world space.
399 \li \a direction is the direction of the ray. It must not be a null vector and does
400 not need to be normalized; the query normalizes it.
401 \li \a maxDistance is the maximum distance along \a direction to cast the ray. It
402 must be greater than 0.
403 \li \a includeStatic includes static bodies in the query when \c true.
404 \li \a includeDynamic includes dynamic bodies in the query when \c true.
405 \endlist
406
407 \include qtquick3dphysics-queries.qdocinc include_flags
408
409 \include qtquick3dphysics-queries.qdocinc query_exclusions
410
411 \include qtquick3dphysics-queries.qdocinc mesh_raycast_limits
412
413 \include qtquick3dphysics-queries.qdocinc mesh_multi_intersection
414
415 \include qtquick3dphysics-queries.qdocinc unordered_hits_note
416
417 \sa testRaycastQuery, singleRaycastQuery, {Qt Quick 3D Physics Scene Queries}
418*/
419
420/*!
421 \qmlmethod bool PhysicsWorld::testSweepQuery(CollisionShape shape, vector3d direction,
422 real maxDistance,
423 bool includeStatic = true,
424 bool includeDynamic = true)
425 \since 6.13
426
427 Sweeps a collision shape along a straight path and reports whether the path is
428 obstructed, without computing precise hit geometry.
429
430 Returns \c true if \a shape hits a body before travelling \a maxDistance; otherwise
431 returns \c false. The query stops at the first body it finds, which makes it the
432 cheapest of the sweep queries.
433
434 \list
435 \li \a shape is the \l CollisionShape to sweep through the scene.
436 \li \a direction is the direction of the sweep. It must not be a null vector and does
437 not need to be normalized; the query normalizes it.
438 \li \a maxDistance is the maximum distance along \a direction to travel. It must be
439 greater than 0.
440 \li \a includeStatic includes static bodies in the query when \c true.
441 \li \a includeDynamic includes dynamic bodies in the query when \c true.
442 \endlist
443
444 \include qtquick3dphysics-queries.qdocinc query_shape
445
446 \include qtquick3dphysics-queries.qdocinc include_flags
447
448 \include qtquick3dphysics-queries.qdocinc query_exclusions
449
450 \sa singleSweepQuery, multiSweepQuery, {Qt Quick 3D Physics Scene Queries}
451*/
452
453/*!
454 \qmlmethod locationHit PhysicsWorld::singleSweepQuery(CollisionShape shape,
455 vector3d direction,
456 real maxDistance,
457 bool includeStatic = true,
458 bool includeDynamic = true)
459 \since 6.13
460
461 Sweeps a collision shape along a straight path and returns the closest body it
462 hits.
463
464 Returns a \l locationHit describing the closest intersection encountered along the
465 sweep.
466
467 \list
468 \li \a shape is the \l CollisionShape to sweep through the scene.
469 \li \a direction is the direction of the sweep. It must not be a null vector and does
470 not need to be normalized; the query normalizes it.
471 \li \a maxDistance is the maximum distance along \a direction to travel. It must be
472 greater than 0.
473 \li \a includeStatic includes static bodies in the query when \c true.
474 \li \a includeDynamic includes dynamic bodies in the query when \c true.
475 \endlist
476
477 \include qtquick3dphysics-queries.qdocinc query_shape
478
479 \include qtquick3dphysics-queries.qdocinc include_flags
480
481 \include qtquick3dphysics-queries.qdocinc hit_miss_return
482
483 \include qtquick3dphysics-queries.qdocinc query_exclusions
484
485 \include qtquick3dphysics-queries.qdocinc mtd_overlap_note
486
487 \sa testSweepQuery, multiSweepQuery, {Qt Quick 3D Physics Scene Queries}
488*/
489
490/*!
491 \qmlmethod list<locationHit> PhysicsWorld::multiSweepQuery(CollisionShape shape,
492 vector3d direction,
493 real maxDistance,
494 bool includeStatic = true,
495 bool includeDynamic = true)
496 \since 6.13
497
498 Sweeps a collision shape along a straight path and returns every body it passes
499 through, rather than stopping at the closest one.
500
501 Returns a \l locationHit for each body hit, or an empty list if the sweep hits
502 nothing.
503
504 \list
505 \li \a shape is the \l CollisionShape to sweep through the scene.
506 \li \a direction is the direction of the sweep. It must not be a null vector and does
507 not need to be normalized; the query normalizes it.
508 \li \a maxDistance is the maximum distance along \a direction to travel. It must be
509 greater than 0.
510 \li \a includeStatic includes static bodies in the query when \c true.
511 \li \a includeDynamic includes dynamic bodies in the query when \c true.
512 \endlist
513
514 \include qtquick3dphysics-queries.qdocinc query_shape
515
516 \include qtquick3dphysics-queries.qdocinc include_flags
517
518 \include qtquick3dphysics-queries.qdocinc query_exclusions
519
520 \include qtquick3dphysics-queries.qdocinc mesh_multi_intersection
521
522 \include qtquick3dphysics-queries.qdocinc unordered_hits_note
523
524 \include qtquick3dphysics-queries.qdocinc mtd_overlap_note
525
526 \sa testSweepQuery, singleSweepQuery, {Qt Quick 3D Physics Scene Queries}
527*/
528
529/*!
530 \qmlmethod bool PhysicsWorld::testOverlapQuery(CollisionShape shape,
531 bool includeStatic = true,
532 bool includeDynamic = true)
533 \since 6.13
534
535 Reports whether any body occupies the volume of a stationary collision shape.
536
537 Returns \c true if \a shape overlaps a body; otherwise returns \c false. The query
538 stops at the first body it finds and builds no hit data, which makes it the cheapest
539 of the overlap queries.
540
541 \list
542 \li \a shape is the \l CollisionShape defining the overlap volume.
543 \li \a includeStatic includes static bodies in the query when \c true.
544 \li \a includeDynamic includes dynamic bodies in the query when \c true.
545 \endlist
546
547 \include qtquick3dphysics-queries.qdocinc query_shape
548
549 \include qtquick3dphysics-queries.qdocinc include_flags
550
551 \include qtquick3dphysics-queries.qdocinc query_exclusions
552
553 \sa multiOverlapQuery, {Qt Quick 3D Physics Scene Queries}
554*/
555
556/*!
557 \qmlmethod list<queryHit> PhysicsWorld::multiOverlapQuery(CollisionShape shape,
558 bool includeStatic = true,
559 bool includeDynamic = true)
560 \since 6.13
561
562 Returns every body that overlaps the volume of a stationary collision shape.
563
564 Returns a \l queryHit for each overlapping body, or an empty list if the volume is
565 unoccupied.
566
567 \list
568 \li \a shape is the \l CollisionShape defining the overlap volume.
569 \li \a includeStatic includes static bodies in the query when \c true.
570 \li \a includeDynamic includes dynamic bodies in the query when \c true.
571 \endlist
572
573 \include qtquick3dphysics-queries.qdocinc query_shape
574
575 \include qtquick3dphysics-queries.qdocinc include_flags
576
577 \include qtquick3dphysics-queries.qdocinc query_exclusions
578
579 \include qtquick3dphysics-queries.qdocinc mesh_multi_intersection
580
581 \include qtquick3dphysics-queries.qdocinc unordered_hits_note
582
583 \sa testOverlapQuery, {Qt Quick 3D Physics Scene Queries}
584*/
585
586Q_LOGGING_CATEGORY(lcQuick3dPhysics, "qt.quick3d.physics");
587
588// Setting QT_PHYSICS_TIMINGS_FILE to a filepath will generate a csv file with frame timings.
589// Note that if running several PhysicsWorld's the last one to be destructed will overwrite
590// the output file.
591//
592// To view it in gnuplot, run these two commands:
593//
594// set datafile separator ','
595// plot '<QT_PHYSICS_TIMINGS_FILE>' using 1:2 with lines
596//
597// Security note: This file is trusted since it is opened as write-only
598static const QString qtPhysicsTimingsFile = qEnvironmentVariable("QT_PHYSICS_TIMINGS_FILE");
599
600/////////////////////////////////////////////////////////////////////////////
601
602static bool validateQuery(const physx::PxScene *scene,
603 bool includeStatic,
604 bool includeDynamic)
605{
606 if (!scene) {
607 qWarning() << "QtQuick3DPhysics: cannot run a scene query before the physics world is "
608 "initialized.";
609 return false;
610 }
611
612 if (!(includeStatic || includeDynamic)) {
613 qWarning() << "QtQuick3DPhysics: a scene query needs includeStatic or includeDynamic to "
614 "be true.";
615 return false;
616 }
617
618 return true;
619}
620
621static bool raycastImpl(const physx::PxScene *scene,
622 const QVector3D &origin,
623 const QVector3D &direction,
624 float maxDistance,
625 bool includeStatic,
626 bool includeDynamic,
627 physx::PxRaycastCallback &hitCallback,
628 physx::PxHitFlags hitFlags,
629 physx::PxQueryFlags extraQueryFlags = {},
630 physx::PxQueryFilterCallback *filterCall = nullptr)
631{
632 if (!validateQuery(scene, includeStatic, includeDynamic))
633 return false;
634
635 const physx::PxVec3 pxOrigin = QPhysicsUtils::toPhysXType(origin);
636 if (!pxOrigin.isFinite()) {
637 qWarning() << "QtQuick3DPhysics: the query origin must be finite.";
638 return false;
639 }
640
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.";
644 return false;
645 }
646
647 if (!qIsFinite(maxDistance) || maxDistance <= 0) {
648 qWarning() << "QtQuick3DPhysics: the query distance must be finite and greater than 0.";
649 return false;
650 }
651
652 // Combine base flags with optional query flags (e.g., eANY_HIT or eNO_BLOCK)
653 physx::PxQueryFlags filter = extraQueryFlags;
654 if (includeStatic)
655 filter |= physx::PxQueryFlag::eSTATIC;
656 if (includeDynamic)
657 filter |= physx::PxQueryFlag::eDYNAMIC;
658
659 // Execute PhysX scene raycast
660 return scene->raycast(pxOrigin, pxDirection, maxDistance, hitCallback, hitFlags,
661 physx::PxQueryFilterData(filter), filterCall);
662}
663
664static const physx::PxGeometry *validateQueryShape(const physx::PxScene *scene,
665 QAbstractCollisionShape *shape,
666 bool includeStatic,
667 bool includeDynamic)
668{
669 if (!validateQuery(scene, includeStatic, includeDynamic)) {
670 return nullptr;
671 }
672
673 const physx::PxGeometry *geometry = shape ? shape->getPhysXGeometry() : nullptr;
674 if (!geometry) {
675 qWarning() << "QtQuick3DPhysics: the query shape has no geometry yet.";
676 return nullptr;
677 }
678
679 // PhysX only supports sphere, capsule, box and convex mesh as the query geometry. Anything
680 // else leaves Gu::ShapeData's bounds uninitialized in a release build.
681 switch (geometry->getType()) {
682 case physx::PxGeometryType::eSPHERE:
683 case physx::PxGeometryType::eCAPSULE:
684 case physx::PxGeometryType::eBOX:
685 case physx::PxGeometryType::eCONVEXMESH:
686 break;
687 default:
688 qWarning() << "QtQuick3DPhysics: sweep and overlap queries only support SphereShape, "
689 "CapsuleShape, BoxShape and ConvexMeshShape as the query shape.";
690 return nullptr;
691 }
692
693 return geometry;
694}
695
696static bool sweepImpl(const physx::PxScene *scene,
697 QAbstractCollisionShape *shape,
698 const QVector3D &direction,
699 float maxDistance,
700 bool includeStatic,
701 bool includeDynamic,
702 physx::PxSweepCallback &hitCallback,
703 physx::PxHitFlags hitFlags,
704 physx::PxQueryFlags extraQueryFlags = {})
705{
706 const physx::PxGeometry *geometry = validateQueryShape(scene, shape, includeStatic, includeDynamic);
707 if (!geometry) {
708 return false;
709 }
710
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.";
714 return false;
715 }
716
717 if (!qIsFinite(maxDistance) || maxDistance <= 0) {
718 qWarning() << "QtQuick3DPhysics: the query distance must be finite and greater than 0.";
719 return false;
720 }
721
722 // Combine base flags with optional query flags (e.g., eANY_HIT or eNO_BLOCK)
723 physx::PxQueryFlags filter = extraQueryFlags;
724 if (includeStatic)
725 filter |= physx::PxQueryFlag::eSTATIC;
726 if (includeDynamic)
727 filter |= physx::PxQueryFlag::eDYNAMIC;
728
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.";
733 return false;
734 }
735
736 // Execute PhysX scene sweep
737 return scene->sweep(*geometry, pose, pxDirection, maxDistance, hitCallback, hitFlags,
738 physx::PxQueryFilterData(filter));
739}
740
741static bool overlapImpl(const physx::PxScene *scene,
742 QAbstractCollisionShape *shape,
743 bool includeStatic,
744 bool includeDynamic,
745 physx::PxOverlapCallback &hitCallback,
746 physx::PxQueryFlags extraQueryFlags = {})
747{
748
749 const physx::PxGeometry *geometry = validateQueryShape(scene, shape, includeStatic, includeDynamic);
750 if (!geometry) {
751 return false;
752 }
753
754 // Combine base static/dynamic flags with query behavior flags (e.g., eANY_HIT or eNO_BLOCK)
755 physx::PxQueryFlags filter = extraQueryFlags;
756 if (includeStatic)
757 filter |= physx::PxQueryFlag::eSTATIC;
758 if (includeDynamic)
759 filter |= physx::PxQueryFlag::eDYNAMIC;
760
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.";
765 return false;
766 }
767
768 // Execute PhysX scene overlap query
769 return scene->overlap(*geometry, pose, hitCallback,
770 physx::PxQueryFilterData(filter));
771}
772
774{
776public:
778 {
779 // Needed to start the frame animation
780 classBegin();
782 }
783};
784
785namespace {
786
787// Passes over the actors a Raycaster must not report: the bodies it excludes, and any actor
788// whose body was deleted earlier in this frame, which stays in the scene until the next one
789// with nothing behind it. Filtering before a hit is recorded keeps the query blocking, so
790// PhysX still shortens the ray at the first surface that is kept.
791class ExcludedBodiesFilter : public physx::PxQueryFilterCallback
792{
793public:
794 explicit ExcludedBodiesFilter(QSpan<const QAbstractPhysicsNode *const> excludedBodies)
795 : m_excludedBodies(excludedBodies)
796 {
797 }
798
799 physx::PxQueryHitType::Enum preFilter(const physx::PxFilterData & /*filterData*/,
800 const physx::PxShape * /*shape*/,
801 const physx::PxRigidActor *actor,
802 physx::PxHitFlags & /*queryFlags*/) override
803 {
804 const auto *body = static_cast<const QAbstractPhysicsNode *>(actor->userData);
805 if (!body)
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;
810 }
811
812 physx::PxQueryHitType::Enum postFilter(const physx::PxFilterData & /*filterData*/,
813 const physx::PxQueryHit & /*hit*/,
814 const physx::PxShape * /*shape*/,
815 const physx::PxRigidActor * /*actor*/) override
816 {
817 return physx::PxQueryHitType::eBLOCK;
818 }
819
820private:
821 QSpan<const QAbstractPhysicsNode *const> m_excludedBodies;
822};
823
824// Collects every touching hit from a scene query. PhysX needs a caller-owned buffer to sort
825// into, and hands the hits over in batches of at most BufferSize once it fills up, so the
826// buffer stays and processTouches() appends each batch to hits.
827// A struct because the PhysX callback bases declare all their members public.
828template<class PxCbT, class HitT, class PxHitT, physx::PxU32 BufferSize = 16>
829struct DynamicQueryCallback : public PxCbT
830{
831 DynamicQueryCallback() : PxCbT(localBuffer, BufferSize) {}
832
833 physx::PxAgain processTouches(const PxHitT *buffer, physx::PxU32 nbHits) override
834 {
835 hits.reserve(hits.size() + nbHits);
836 for (physx::PxU32 i = 0; i < nbHits; ++i)
837 hits.emplaceBack(buffer[i], buffer[i]);
838 return true;
839 }
840
841 PxHitT localBuffer[BufferSize];
842 QList<HitT> hits;
843};
844
845} // namespace
846
847/////////////////////////////////////////////////////////////////////////////
848
849void QPhysicsWorld::DebugModelHolder::releaseMeshPointer()
850{
851 if (auto base = static_cast<physx::PxBase *>(ptr); base)
852 base->release();
853 ptr = nullptr;
854}
855
856const QVector3D &QPhysicsWorld::DebugModelHolder::halfExtents() const
857{
858 return data;
859}
860void QPhysicsWorld::DebugModelHolder::setHalfExtents(const QVector3D &halfExtents)
861{
862 data = halfExtents;
863}
864float QPhysicsWorld::DebugModelHolder::radius() const
865{
866 return data.x();
867}
868void QPhysicsWorld::DebugModelHolder::setRadius(float radius)
869{
870 data.setX(radius);
871}
872float QPhysicsWorld::DebugModelHolder::heightScale() const
873{
874 return data.x();
875}
876void QPhysicsWorld::DebugModelHolder::setHeightScale(float heightScale)
877{
878 data.setX(heightScale);
879}
880float QPhysicsWorld::DebugModelHolder::halfHeight() const
881{
882 return data.y();
883}
884void QPhysicsWorld::DebugModelHolder::setHalfHeight(float halfHeight)
885{
886 data.setY(halfHeight);
887}
888float QPhysicsWorld::DebugModelHolder::rowScale() const
889{
890 return data.y();
891}
892void QPhysicsWorld::DebugModelHolder::setRowScale(float rowScale)
893{
894 data.setY(rowScale);
895}
896float QPhysicsWorld::DebugModelHolder::columnScale() const
897{
898 return data.z();
899}
900void QPhysicsWorld::DebugModelHolder::setColumnScale(float columnScale)
901{
902 data.setZ(columnScale);
903}
904physx::PxConvexMesh *QPhysicsWorld::DebugModelHolder::getConvexMesh()
905{
906 return static_cast<physx::PxConvexMesh *>(ptr);
907}
908void QPhysicsWorld::DebugModelHolder::setConvexMesh(physx::PxConvexMesh *mesh)
909{
910 ptr = static_cast<void *>(mesh);
911}
912physx::PxTriangleMesh *QPhysicsWorld::DebugModelHolder::getTriangleMesh()
913{
914 return static_cast<physx::PxTriangleMesh *>(ptr);
915}
916void QPhysicsWorld::DebugModelHolder::setTriangleMesh(physx::PxTriangleMesh *mesh)
917{
918 ptr = static_cast<void *>(mesh);
919}
920physx::PxHeightField *QPhysicsWorld::DebugModelHolder::getHeightField()
921{
922 return static_cast<physx::PxHeightField *>(ptr);
923}
924void QPhysicsWorld::DebugModelHolder::setHeightField(physx::PxHeightField *hf)
925{
926 ptr = static_cast<physx::PxHeightField *>(hf);
927}
928
929/////////////////////////////////////////////////////////////////////////////
930
938
939static QWorldManager worldManager = QWorldManager {};
940
941void QPhysicsWorld::registerNode(QAbstractPhysicsNode *physicsNode)
942{
943 auto world = getWorld(physicsNode);
944 if (world) {
945 world->m_newPhysicsNodes.push_back(physicsNode);
946 } else {
947 worldManager.orphanNodes.push_back(physicsNode);
948 }
949}
950
951void QPhysicsWorld::deregisterNode(QAbstractPhysicsNode *physicsNode)
952{
953 // Before the backend is detached, while it still has what the field
954 // last acted on.
955 if (physicsNode->m_backendObject) {
956 for (auto world : std::as_const(worldManager.worlds))
957 world->releaseGravityField(physicsNode->m_backendObject);
958 }
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;
967 }
968 world->m_removedPhysicsNodes.insert(physicsNode);
969 }
970 worldManager.orphanNodes.removeAll(physicsNode);
971}
972
973void QPhysicsWorld::registerJoint(QPhysicsJoint *joint)
974{
975 auto world = getWorld(joint);
976 if (world) {
977 world->m_joints.push_back(joint);
978 } else {
979 worldManager.orphanJoints.push_back(joint);
980 }
981}
982
983void QPhysicsWorld::deregisterJoint(QPhysicsJoint *joint)
984{
985 for (auto world : worldManager.worlds) {
986 world->m_removedJoints.insert(joint->getPhysXBackend());
987
988 // Swap erase since order does not matter
989 qsizetype idx = world->m_joints.indexOf(joint);
990 if (idx != -1) {
991 world->m_joints.swapItemsAt(idx, world->m_joints.size() - 1);
992 world->m_joints.pop_back();
993 }
994 }
995 worldManager.orphanJoints.removeAll(joint);
996}
997
998void QPhysicsWorld::registerRaycaster(QRaycaster *raycaster)
999{
1000 if (auto *world = getWorld(raycaster))
1001 world->m_raycasters.push_back(raycaster);
1002 else
1003 worldManager.orphanRaycasters.push_back(raycaster);
1004}
1005
1006void QPhysicsWorld::deregisterRaycaster(QRaycaster *raycaster)
1007{
1008 for (auto *world : std::as_const(worldManager.worlds))
1009 world->m_raycasters.removeAll(raycaster);
1010 worldManager.orphanRaycasters.removeAll(raycaster);
1011}
1012
1013void QPhysicsWorld::registerGravityField(QPhysXGravityField *field)
1014{
1015 m_gravityFields.append(field);
1016}
1017
1018void QPhysicsWorld::registerContact(QAbstractPhysicsNode *sender, QAbstractPhysicsNode *receiver,
1019 const QVector<QVector3D> &positions,
1020 const QVector<QVector3D> &impulses,
1021 const QVector<QVector3D> &normals)
1022{
1023 // The callbacks come from fetchResults(), on this thread, but a contact is
1024 // between two nodes and reporting the first is free to delete the second.
1025 // So the contacts are saved and run at the end of the physics frame, when
1026 // it is known which of their nodes are still there.
1027
1028 BodyContact contact;
1029 contact.sender = sender;
1030 contact.receiver = receiver;
1031 contact.positions = positions;
1032 contact.impulses = impulses;
1033 contact.normals = normals;
1034
1035 m_registeredContacts.push_back(contact);
1036}
1037
1038QPhysicsWorld::QPhysicsWorld(QObject *parent) : QObject(parent)
1039{
1040 m_inDesignStudio = !qEnvironmentVariableIsEmpty("QML_PUPPET_MODE");
1041 m_physx = new QPhysXWorld;
1042 m_physx->createWorld();
1043
1044 worldManager.worlds.push_back(this);
1045 matchOrphanNodes();
1046 matchOrphanJoints();
1047 matchOrphanRaycasters();
1048
1049 m_frameAnimator = new FrameAnimator;
1050 connect(m_frameAnimator, &QQuickFrameAnimation::triggered, this,
1051 &QPhysicsWorld::simulateFrame);
1052}
1053
1054QPhysicsWorld::~QPhysicsWorld()
1055{
1056 if (m_frameAnimator) {
1057 m_frameAnimator->stop();
1058 delete m_frameAnimator;
1059 }
1060
1061 if (m_physx->scene && m_physx->isRunning && !m_frameFetched)
1062 m_physx->scene->fetchResults(true);
1063
1064 for (auto body : std::as_const(m_physXBodies)) {
1065 body->cleanup(m_physx);
1066 delete body;
1067 }
1068 m_physXBodies.clear();
1069 m_physx->deleteWorld();
1070 delete m_physx;
1071 worldManager.worlds.removeAll(this);
1072
1073 // A raycaster can outlive the world it was matched to, since it lives in the scene and
1074 // not in this list. Back to the orphans, so a later world over the same scene picks it
1075 // up again.
1076 worldManager.orphanRaycasters += m_raycasters;
1077 m_raycasters.clear();
1078
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';
1086 }
1087 csvFile.close();
1088 } else {
1089 qWarning() << "Could not open timings file " << qtPhysicsTimingsFile;
1090 }
1091 }
1092}
1093
1094void QPhysicsWorld::classBegin() {}
1095
1096void QPhysicsWorld::componentComplete()
1097{
1098 if ((!m_running && !m_inDesignStudio) || m_physicsInitialized)
1099 return;
1100 initPhysics();
1101}
1102
1103QVector3D QPhysicsWorld::gravity() const
1104{
1105 return m_gravity;
1106}
1107
1108bool QPhysicsWorld::running() const
1109{
1110 return m_running;
1111}
1112
1113bool QPhysicsWorld::forceDebugDraw() const
1114{
1115 return m_forceDebugDraw;
1116}
1117
1118bool QPhysicsWorld::enableCCD() const
1119{
1120 return m_enableCCD;
1121}
1122
1123float QPhysicsWorld::typicalLength() const
1124{
1125 return m_typicalLength;
1126}
1127
1128float QPhysicsWorld::typicalSpeed() const
1129{
1130 return m_typicalSpeed;
1131}
1132
1133bool QPhysicsWorld::isNodeRemoved(QAbstractPhysicsNode *object)
1134{
1135 return m_removedPhysicsNodes.contains(object);
1136}
1137
1138void QPhysicsWorld::setGravity(QVector3D gravity)
1139{
1140 if (m_gravity == gravity)
1141 return;
1142
1143 if (!QPhysicsUtils::isFinite(gravity)) {
1144 qWarning() << "Warning: 'gravity' must be finite, ignored";
1145 return;
1146 }
1147
1148 m_gravity = gravity;
1149 if (m_physx->scene) {
1150 m_physx->scene->setGravity(QPhysicsUtils::toPhysXType(m_gravity));
1151 }
1152 emit gravityChanged(m_gravity);
1153}
1154
1155void QPhysicsWorld::setRunning(bool running)
1156{
1157 if (m_running == running)
1158 return;
1159
1160 m_running = running;
1161 if (!m_inDesignStudio && m_running && !m_physicsInitialized)
1162 initPhysics();
1163
1164 if (running)
1165 m_frameAnimator->start();
1166 else
1167 m_frameAnimator->stop();
1168
1169 emit runningChanged(m_running);
1170}
1171
1172void QPhysicsWorld::setForceDebugDraw(bool forceDebugDraw)
1173{
1174 if (m_forceDebugDraw == forceDebugDraw)
1175 return;
1176
1177 m_forceDebugDraw = forceDebugDraw;
1178 if (!m_forceDebugDraw)
1179 disableDebugDraw();
1180 else
1181 updateDebugDraw();
1182 emit forceDebugDrawChanged(m_forceDebugDraw);
1183}
1184
1185QQuick3DNode *QPhysicsWorld::viewport() const
1186{
1187 return m_viewport;
1188}
1189
1190void QPhysicsWorld::setHasIndividualDebugDraw()
1191{
1192 m_hasIndividualDebugDraw = true;
1193}
1194
1195void QPhysicsWorld::setViewport(QQuick3DNode *viewport)
1196{
1197 if (m_viewport == viewport)
1198 return;
1199
1200 m_viewport = viewport;
1201
1202 // TODO: test this
1203 for (auto material : std::as_const(m_debugMaterials))
1204 delete material;
1205 m_debugMaterials.clear();
1206
1207 for (auto &holder : m_collisionShapeDebugModels) {
1208 holder.releaseMeshPointer();
1209 delete holder.model;
1210 }
1211 m_collisionShapeDebugModels.clear();
1212
1213 emit viewportChanged(m_viewport);
1214}
1215
1216void QPhysicsWorld::setMinimumTimestep(float minTimestep)
1217{
1218 if (qFuzzyCompare(m_minTimestep, minTimestep))
1219 return;
1220
1221 if (!qIsFinite(minTimestep)) {
1222 qWarning("Minimum timestep must be finite, ignoring");
1223 return;
1224 }
1225
1226 if (minTimestep > m_maxTimestep) {
1227 qWarning("Minimum timestep greater than maximum timestep, value clamped");
1228 minTimestep = qMin(minTimestep, m_maxTimestep);
1229 }
1230
1231 if (minTimestep < 0.f) {
1232 qWarning("Minimum timestep less than zero, value clamped");
1233 minTimestep = qMax(minTimestep, 0.f);
1234 }
1235
1236 if (qFuzzyCompare(m_minTimestep, minTimestep))
1237 return;
1238
1239 m_minTimestep = minTimestep;
1240 emit minimumTimestepChanged(m_minTimestep);
1241}
1242
1243void QPhysicsWorld::setMaximumTimestep(float maxTimestep)
1244{
1245 if (qFuzzyCompare(m_maxTimestep, maxTimestep))
1246 return;
1247
1248 if (!qIsFinite(maxTimestep)) {
1249 qWarning("Maximum timestep must be finite, ignoring");
1250 return;
1251 }
1252
1253 if (maxTimestep < 0.f) {
1254 qWarning("Maximum timestep less than zero, value clamped");
1255 maxTimestep = qMax(maxTimestep, 0.f);
1256 }
1257
1258 if (qFuzzyCompare(m_maxTimestep, maxTimestep))
1259 return;
1260
1261 m_maxTimestep = maxTimestep;
1262 emit maximumTimestepChanged(maxTimestep);
1263}
1264
1265void QPhysicsWorld::setupDebugMaterials(QQuick3DNode *sceneNode)
1266{
1267 if (!m_debugMaterials.isEmpty())
1268 return;
1269
1270 const int lineWidth = m_inDesignStudio ? 1 : 3;
1271
1272 // These colors match the indices of DebugDrawBodyType enum
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);
1284 }
1285}
1286
1287void QPhysicsWorld::updateDebugDraw()
1288{
1289 if (!(m_forceDebugDraw || m_hasIndividualDebugDraw)) {
1290 // Nothing to draw, trash all previous models (if any) and return
1291 for (auto &holder : m_collisionShapeDebugModels) {
1292 holder.releaseMeshPointer();
1293 delete holder.model;
1294 }
1295 m_collisionShapeDebugModels.clear();
1296 return;
1297 }
1298
1299 // Use scene node if no viewport has been specified
1300 auto sceneNode = m_viewport ? m_viewport : m_scene;
1301
1302 if (sceneNode == nullptr)
1303 return;
1304
1305 setupDebugMaterials(sceneNode);
1306 m_hasIndividualDebugDraw = false;
1307
1308 // Store the collision shapes we have now so we can clear out the removed ones
1309 QSet<QPair<QAbstractCollisionShape *, QAbstractPhysXNode *>> currentCollisionShapes;
1310 currentCollisionShapes.reserve(m_collisionShapeDebugModels.size());
1311
1312 for (QAbstractPhysXNode *node : std::as_const(m_physXBodies)) {
1313 // A node deleted from a report earlier in this frame keeps its backend
1314 // until the next one takes it out.
1315 if (!node->frontendNode || !node->debugGeometryCapability())
1316 continue;
1317
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];
1323
1324 if (!m_forceDebugDraw && !collisionShape->enableDebugDraw())
1325 continue;
1326
1327 DebugModelHolder &holder =
1328 m_collisionShapeDebugModels[std::make_pair(collisionShape, node)];
1329 auto &model = holder.model;
1330
1331 currentCollisionShapes.insert(std::make_pair(collisionShape, node));
1332
1333 m_hasIndividualDebugDraw =
1334 m_hasIndividualDebugDraw || collisionShape->enableDebugDraw();
1335
1336 // Create/Update debug view infrastructure
1337 if (!model) {
1338 model = new QQuick3DModel();
1339 model->setParentItem(sceneNode);
1340 model->setParent(sceneNode);
1341 model->setCastsShadows(false);
1342 model->setReceivesShadows(false);
1343 model->setCastsReflections(false);
1344 }
1345
1346 model->setVisible(true);
1347
1348 { // update or set material
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);
1354 }
1355 }
1356
1357 // Special handling of CharacterController since it has collision shapes,
1358 // but not PhysX shapes
1359 if (qobject_cast<QCharacterController *>(node->frontendNode)) {
1360 QCapsuleShape *capsuleShape = qobject_cast<QCapsuleShape *>(collisionShape);
1361 if (!capsuleShape)
1362 continue;
1363
1364 const float radius = capsuleShape->diameter() * 0.5;
1365 const float halfHeight = capsuleShape->height() * 0.5;
1366
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);
1374 }
1375
1376 model->setPosition(node->frontendNode->scenePosition());
1377 model->setRotation(node->frontendNode->sceneRotation()
1378 * QQuaternion::fromEulerAngles(0, 0, 90));
1379 continue;
1380 }
1381
1382 if (node->shapes.length() < length)
1383 continue;
1384
1385 const auto physXShape = node->shapes[idx];
1386 auto localPose = physXShape->getLocalPose();
1387
1388 const physx::PxGeometry &geometry = physXShape->getGeometry();
1389
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);
1400 }
1401
1402 }
1403 break;
1404
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);
1413 }
1414 }
1415 break;
1416
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();
1422
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);
1431 }
1432 }
1433 break;
1434
1435 case physx::PxGeometryType::ePLANE:{
1436 // Special rotation
1437 const QQuaternion rotation =
1438 QPhysicsUtils::kMinus90YawRotation * QPhysicsUtils::toQtType(localPose.q);
1439 localPose = physx::PxTransform(localPose.p, QPhysicsUtils::toPhysXType(rotation));
1440
1441 if (model->geometry() == nullptr) {
1442 auto geom = QDebugDrawHelper::generatePlaneGeometry();
1443 geom->setParent(model);
1444 model->setGeometry(geom);
1445 }
1446 }
1447 break;
1448
1449 // For heightfield, convex mesh and triangle mesh we increase its reference count
1450 // to make sure it does not get dereferenced and deleted so that the new mesh will
1451 // have another memory address so we know when it has changed.
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();
1458
1459 if (auto heightField = holder.getHeightField();
1460 heightField && heightField != heightFieldGeometry.heightField) {
1461 heightField->release();
1462 holder.setHeightField(nullptr);
1463 }
1464
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);
1472 }
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);
1481 }
1482 }
1483 break;
1484
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));
1491
1492 if (auto convexMesh = holder.getConvexMesh();
1493 convexMesh && convexMesh != convexMeshGeometry.convexMesh) {
1494 convexMesh->release();
1495 holder.setConvexMesh(nullptr);
1496 }
1497
1498 if (!model->geometry() || !holder.getConvexMesh()) {
1499 if (!holder.getConvexMesh()) {
1500 convexMeshGeometry.convexMesh->acquireReference();
1501 holder.setConvexMesh(convexMeshGeometry.convexMesh);
1502 }
1503 auto geom = QDebugDrawHelper::generateConvexMeshGeometry(
1504 convexMeshGeometry.convexMesh);
1505 geom->setParent(model);
1506 model->setGeometry(geom);
1507 }
1508 }
1509 break;
1510
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));
1517
1518 if (auto triangleMesh = holder.getTriangleMesh();
1519 triangleMesh && triangleMesh != triangleMeshGeometry.triangleMesh) {
1520 triangleMesh->release();
1521 holder.setTriangleMesh(nullptr);
1522 }
1523
1524 if (!model->geometry() || !holder.getTriangleMesh()) {
1525 if (!holder.getTriangleMesh()) {
1526 triangleMeshGeometry.triangleMesh->acquireReference();
1527 holder.setTriangleMesh(triangleMeshGeometry.triangleMesh);
1528 }
1529 auto geom = QDebugDrawHelper::generateTriangleMeshGeometry(
1530 triangleMeshGeometry.triangleMesh);
1531 geom->setParent(model);
1532 model->setGeometry(geom);
1533 }
1534 }
1535 break;
1536
1537 // Geometry types that no shape in Qt Quick 3D Physics can have
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:
1544 // should not happen
1545 Q_UNREACHABLE();
1546 }
1547
1548 auto globalPose = node->getGlobalPose();
1549 auto finalPose = globalPose.transform(localPose);
1550
1551 model->setRotation(QPhysicsUtils::toQtType(finalPose.q));
1552 model->setPosition(QPhysicsUtils::toQtType(finalPose.p));
1553 }
1554 }
1555
1556 // Remove old collision shapes
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();
1563 if (holder.model)
1564 delete holder.model;
1565 return true;
1566 }
1567 return false;
1568 });
1569}
1570
1571static void collectPhysicsNodes(QQuick3DObject *node, QList<QAbstractPhysicsNode *> &nodes)
1572{
1573 if (auto shape = qobject_cast<QAbstractPhysicsNode *>(node)) {
1574 nodes.push_back(shape);
1575 return;
1576 }
1577
1578 auto childItems = node->childItems();
1579 for (QQuick3DObject *child : std::as_const(childItems))
1580 collectPhysicsNodes(child, nodes);
1581}
1582
1583void QPhysicsWorld::updateDebugDrawDesignStudio()
1584{
1585 // Use scene node if no viewport has been specified
1586 auto sceneNode = m_viewport ? m_viewport : m_scene;
1587
1588 if (sceneNode == nullptr)
1589 return;
1590
1591 setupDebugMaterials(sceneNode);
1592
1593 // Store the collision shapes we have now so we can clear out the removed ones
1594 QSet<QPair<QAbstractCollisionShape *, QAbstractPhysicsNode *>> currentCollisionShapes;
1595 currentCollisionShapes.reserve(m_collisionShapeDebugModels.size());
1596
1597 QList<QAbstractPhysicsNode *> activePhysicsNodes;
1598 activePhysicsNodes.reserve(m_collisionShapeDebugModels.size());
1599 collectPhysicsNodes(m_scene, activePhysicsNodes);
1600
1601 for (QAbstractPhysicsNode *node : std::as_const(activePhysicsNodes)) {
1602
1603 const auto &collisionShapes = node->getCollisionShapesList();
1604 const int materialIdx = 0; // Just take first material
1605 const int length = collisionShapes.length();
1606
1607 const bool isCharacterController = qobject_cast<QCharacterController *>(node) != nullptr;
1608
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;
1614
1615 currentCollisionShapes.insert(std::make_pair(collisionShape, node));
1616
1617 m_hasIndividualDebugDraw =
1618 m_hasIndividualDebugDraw || collisionShape->enableDebugDraw();
1619
1620 // Create/Update debug view infrastructure
1621 {
1622 // Hack: we have to delete the model every frame so it shows up in QDS
1623 // whenever the code is updated, not sure why ¯\_(?)_/¯
1624 delete model;
1625 model = new QQuick3DModel();
1626 model->setParentItem(sceneNode);
1627 model->setParent(sceneNode);
1628 model->setCastsShadows(false);
1629 model->setReceivesShadows(false);
1630 model->setCastsReflections(false);
1631 }
1632
1633 const bool hasGeometry = holder.geometry != nullptr;
1634 QVector3D scenePosition = collisionShape->scenePosition();
1635 QQuaternion sceneRotation = collisionShape->sceneRotation();
1636 QQuick3DGeometry *newGeometry = nullptr;
1637
1638 if (isCharacterController)
1639 sceneRotation = sceneRotation * QQuaternion::fromEulerAngles(QVector3D(0, 0, 90));
1640
1641 { // update or set material
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);
1647 }
1648 }
1649
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);
1656 }
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);
1663 }
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;
1669
1670 if ((!qFuzzyCompare(radiusOld, radius) || !qFuzzyCompare(halfHeightOld, halfHeight))
1671 || !hasGeometry) {
1672 newGeometry = QDebugDrawHelper::generateCapsuleGeometry(radius, halfHeight);
1673 holder.setRadius(radius);
1674 holder.setHalfHeight(halfHeight);
1675 }
1676 } else if (qobject_cast<QPlaneShape *>(collisionShape)) {
1677 if (!hasGeometry)
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)
1691 || !hasGeometry) {
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);
1698 }
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";
1704 } else {
1705 model->setScale(QPhysicsUtils::toQtType(convexMeshGeometry->scale.scale));
1706
1707 if (!hasGeometry) {
1708 newGeometry = QDebugDrawHelper::generateConvexMeshGeometry(
1709 convexMeshGeometry->convexMesh);
1710 }
1711 }
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";
1717 } else {
1718 model->setScale(QPhysicsUtils::toQtType(triangleMeshGeometry->scale.scale));
1719
1720 if (!hasGeometry) {
1721 newGeometry = QDebugDrawHelper::generateTriangleMeshGeometry(
1722 triangleMeshGeometry->triangleMesh);
1723 }
1724 }
1725 }
1726
1727 if (newGeometry) {
1728 delete holder.geometry;
1729 holder.geometry = newGeometry;
1730 }
1731
1732 model->setGeometry(holder.geometry);
1733 model->setVisible(true);
1734
1735 model->setRotation(sceneRotation);
1736 model->setPosition(scenePosition);
1737 }
1738 }
1739
1740 // Remove old debug models
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();
1747 if (holder.model) {
1748 delete holder.geometry;
1749 delete holder.model;
1750 }
1751 return true;
1752 }
1753 return false;
1754 });
1755}
1756
1757void QPhysicsWorld::disableDebugDraw()
1758{
1759 m_hasIndividualDebugDraw = false;
1760
1761 for (QAbstractPhysXNode *body : std::as_const(m_physXBodies)) {
1762 if (!body->frontendNode)
1763 continue;
1764
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;
1771 return;
1772 }
1773 }
1774 }
1775}
1776
1777void QPhysicsWorld::setEnableCCD(bool enableCCD)
1778{
1779 if (m_enableCCD == enableCCD)
1780 return;
1781
1782 if (m_physicsInitialized) {
1783 qWarning()
1784 << "Warning: Changing 'enableCCD' after physics is initialized will have no effect";
1785 return;
1786 }
1787
1788 m_enableCCD = enableCCD;
1789 emit enableCCDChanged(m_enableCCD);
1790}
1791
1792void QPhysicsWorld::setTypicalLength(float typicalLength)
1793{
1794 if (qFuzzyCompare(typicalLength, m_typicalLength))
1795 return;
1796
1797 if (!qIsFinite(typicalLength) || typicalLength <= 0.f) {
1798 qWarning() << "Warning: 'typicalLength' value less than zero, ignored";
1799 return;
1800 }
1801
1802 if (m_physicsInitialized) {
1803 qWarning() << "Warning: Changing 'typicalLength' after physics is initialized will have "
1804 "no effect";
1805 return;
1806 }
1807
1808 m_typicalLength = typicalLength;
1809
1810 emit typicalLengthChanged(typicalLength);
1811}
1812
1813void QPhysicsWorld::setTypicalSpeed(float typicalSpeed)
1814{
1815 if (qFuzzyCompare(typicalSpeed, m_typicalSpeed))
1816 return;
1817
1818 if (!qIsFinite(typicalSpeed) || typicalSpeed <= 0.f) {
1819 qWarning() << "Warning: 'typicalSpeed' must be finite and greater than zero, ignored";
1820 return;
1821 }
1822
1823 if (m_physicsInitialized) {
1824 qWarning() << "Warning: Changing 'typicalSpeed' after physics is initialized will have "
1825 "no effect";
1826 return;
1827 }
1828
1829 m_typicalSpeed = typicalSpeed;
1830
1831 emit typicalSpeedChanged(typicalSpeed);
1832}
1833
1834float QPhysicsWorld::defaultDensity() const
1835{
1836 return m_defaultDensity;
1837}
1838
1839float QPhysicsWorld::minimumTimestep() const
1840{
1841 return m_minTimestep;
1842}
1843
1844float QPhysicsWorld::maximumTimestep() const
1845{
1846 return m_maxTimestep;
1847}
1848
1849void QPhysicsWorld::setDefaultDensity(float defaultDensity)
1850{
1851 defaultDensity = qBound(0.0000001f, defaultDensity, PX_MAX_F32);
1852
1853 if (qFuzzyCompare(m_defaultDensity, defaultDensity))
1854 return;
1855 m_defaultDensity = defaultDensity;
1856
1857 // Go through all dynamic rigid bodies and update the default density
1858 for (QAbstractPhysXNode *body : std::as_const(m_physXBodies)) {
1859 if (body->frontendNode)
1860 body->updateDefaultDensity(m_defaultDensity);
1861 }
1862
1863 emit defaultDensityChanged(defaultDensity);
1864}
1865
1866// Remove physics world items that no longer exist
1867
1868void QPhysicsWorld::cleanupRemovedNodes()
1869{
1870 m_physXBodies.removeIf([this](QAbstractPhysXNode *body) {
1871 return body->cleanupIfRemoved(m_physx);
1872 });
1873 m_removedPhysicsNodes.clear();
1874}
1875
1876// Tell the triggers which nodes have had their shapes replaced, and drop what
1877// the reports that followed the last such replacement did not mention
1878
1879void QPhysicsWorld::invalidateTriggerOverlaps(QSpan<QAbstractPhysXNode *const> rebuiltBodies)
1880{
1881 for (QAbstractPhysXNode *body : std::as_const(m_physXBodies)) {
1882 auto *trigger = qobject_cast<QAbstractTriggerRegion *>(body->frontendNode);
1883 if (!trigger)
1884 continue;
1885 for (QAbstractPhysXNode *rebuilt : rebuiltBodies) {
1886 // The rebuilt nodes are held as backends, which outlive the frame,
1887 // since syncing the frame can run a handler that deletes a node
1888 // that was rebuilt earlier in it. deregisterNode() takes the
1889 // frontend off the backend of whatever is deleted.
1890 if (rebuilt->frontendNode)
1891 trigger->invalidateOverlaps(rebuilt->frontendNode);
1892 }
1893 }
1894
1895 m_triggerOverlapsInvalidated = true;
1896}
1897
1898void QPhysicsWorld::dropUnreportedTriggerOverlaps()
1899{
1900 // Nothing is waiting to be reported again unless shapes were replaced, so
1901 // this stays off the frame of a scene that never rebuilds any.
1902 if (!m_triggerOverlapsInvalidated)
1903 return;
1904 m_triggerOverlapsInvalidated = false;
1905
1906 // A body reported as having left can be deleted from the handler, and so can
1907 // a trigger that has not been reached yet. deregisterNode() takes the
1908 // frontend off whatever is deleted, so what still has one here is what
1909 // is left.
1910 for (QAbstractPhysXNode *body : std::as_const(m_physXBodies)) {
1911 if (auto *trigger = qobject_cast<QAbstractTriggerRegion *>(body->frontendNode))
1912 trigger->dropUnreportedOverlaps();
1913 }
1914}
1915
1916void QPhysicsWorld::cleanupRemovedJoints()
1917{
1918 for (physx::PxJoint *joint : m_removedJoints) {
1919 if (joint)
1920 joint->release();
1921 }
1922 m_removedJoints.clear();
1923}
1924
1925void QPhysicsWorld::initPhysics()
1926{
1927 Q_ASSERT(!m_physicsInitialized);
1928
1929#if QT_CONFIG(thread)
1930 const unsigned int numThreads = m_numThreads >= 0 ? m_numThreads : qMax(0, QThread::idealThreadCount());
1931#else
1932 // PhysX cannot start worker threads, it would wait for them forever
1933 const unsigned int numThreads = 0;
1934#endif
1935 m_physx->createScene(m_typicalLength, m_typicalSpeed, m_gravity, this, numThreads);
1936 m_frameAnimator->start();
1937 m_physicsInitialized = true;
1938}
1939
1940void QPhysicsWorld::simulateFrame()
1941{
1942 constexpr double MILLIONTH = 0.000001;
1943 constexpr double THOUSANDTH = 0.001;
1944
1945 if (m_inDesignStudio) {
1946 frameFinishedDesignStudio();
1947 return;
1948 }
1949
1950 if (!m_physx->isRunning) {
1951 m_timer.start();
1952 m_physx->isRunning = true;
1953 const double minTimestepSecs = m_minTimestep * 0.001;
1954 m_physx->scene->simulate(minTimestepSecs);
1955 m_currTimeStep = minTimestepSecs;
1956 return;
1957 }
1958
1959 // Frame not ready yet
1960 if (!m_frameFetched && !m_physx->scene->checkResults()) {
1961 return;
1962 }
1963
1964 // Frame ready, fetch and finish it
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);
1972 }
1973 }
1974
1975 // Assuming: 0 <= minTimestep <= maxTimestep
1976 const double deltaMS = m_timer.nsecsElapsed() * MILLIONTH;
1977 if (deltaMS < m_minTimestep)
1978 return;
1979 const double deltaSecs = qMin<double>(deltaMS, m_maxTimestep) * THOUSANDTH;
1980 m_timer.restart();
1981 m_physx->scene->simulate(deltaSecs);
1982 m_frameFetched = false;
1983 m_currTimeStep = deltaSecs;
1984}
1985
1986void QPhysicsWorld::frameFinished(float deltaTime)
1987{
1988 matchOrphanNodes();
1989 matchOrphanJoints();
1990 matchOrphanRaycasters();
1991
1992 // One round of reports has been fetched since the shapes rebuilt below were
1993 // replaced, so whatever it did not mention is no longer overlapping. Kept
1994 // ahead of cleanupRemovedNodes(), like the contact callbacks, since a body
1995 // reported as having left can be deleted from the handler.
1996 dropUnreportedTriggerOverlaps();
1997
1998 emitContactCallbacks();
1999 cleanupRemovedNodes();
2000 cleanupRemovedJoints();
2001
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);
2006 }
2007 m_newPhysicsNodes.clear();
2008
2009 applyGravity();
2010
2011 QHash<QQuick3DNode *, QMatrix4x4> transformCache;
2012 QVarLengthArray<QAbstractPhysXNode *, 8> rebuiltBodies;
2013
2014 // TODO: Use dirty flag/dirty list to avoid redoing things that didn't change
2015 for (auto *physXBody : std::as_const(m_physXBodies)) {
2016 // Syncing runs a node's bindings, and a character controller reports
2017 // what it hits from here, so one can be deleted while this loop runs.
2018 if (!physXBody->frontendNode)
2019 continue;
2020
2021 physXBody->markDirtyShapes();
2022 const bool wasDirty = physXBody->shapesDirty();
2023 physXBody->rebuildDirtyShapes(this, m_physx);
2024
2025 // Rebuilding reports too, when it has to force a body kinematic.
2026 if (!physXBody->frontendNode)
2027 continue;
2028
2029 // Dirty before and clean after is the backend having replaced the shapes
2030 // of the node, which the triggers holding them need to hear about.
2031 if (wasDirty && !physXBody->shapesDirty())
2032 rebuiltBodies.append(physXBody);
2033 physXBody->updateFilters(m_physx);
2034
2035 // Sync the physics world and the scene
2036 physXBody->sync(deltaTime, transformCache);
2037 }
2038
2039 if (!rebuiltBodies.isEmpty())
2040 invalidateTriggerOverlaps(rebuiltBodies);
2041
2042 for (QPhysicsJoint *joint : std::as_const(m_joints)) {
2043 joint->updatePhysXBackend();
2044 }
2045
2046 const QList<QRaycaster *> raycasters = m_raycasters;
2047 for (QRaycaster *raycaster : raycasters) {
2048 if (m_raycasters.contains(raycaster))
2049 raycaster->updateRaycast(this);
2050 }
2051
2052 updateDebugDraw();
2053 emit frameDone(deltaTime * 1000);
2054}
2055
2056void QPhysicsWorld::frameFinishedDesignStudio()
2057{
2058 // Note sure if this is needed but do it anyway
2059 matchOrphanNodes();
2060 matchOrphanJoints();
2061 // Matched but never cast: no backends are created here, so the PhysX scene has no
2062 // bodies for a ray to hit.
2063 matchOrphanRaycasters();
2064 emitContactCallbacks();
2065 cleanupRemovedNodes();
2066 // Ignore new physics nodes, we find them from the scene node anyway
2067 m_newPhysicsNodes.clear();
2068
2069 updateDebugDrawDesignStudio();
2070}
2071
2072QPhysicsWorld *QPhysicsWorld::getWorld(QQuick3DNode *node)
2073{
2074 for (QPhysicsWorld *world : std::as_const(worldManager.worlds)) {
2075 if (!world->m_scene) {
2076 continue;
2077 }
2078
2079 QQuick3DNode *nodeCurr = node;
2080
2081 // Maybe pointless but check starting node
2082 if (nodeCurr == world->m_scene)
2083 return world;
2084
2085 while (nodeCurr->parentNode()) {
2086 nodeCurr = nodeCurr->parentNode();
2087 if (nodeCurr == world->m_scene)
2088 return world;
2089 }
2090 }
2091
2092 return nullptr;
2093}
2094
2095QPhysicsWorld *QPhysicsWorld::getWorld(QPhysicsJoint *joint)
2096{
2097 for (QPhysicsWorld *world : worldManager.worlds) {
2098 if (!world->m_scene) {
2099 continue;
2100 }
2101
2102 QObject *nodeCurr = joint;
2103
2104 while (nodeCurr->parent()) {
2105 nodeCurr = nodeCurr->parent();
2106 if (nodeCurr == world->m_scene) {
2107 return world;
2108 } else if (auto view3d = qobject_cast<QQuick3DViewport *>(nodeCurr);
2109 view3d && view3d->scene() == world->m_scene) {
2110 // HACK? if the parent is a view3d, check against its "implicit" scene
2111 return world;
2112 }
2113 }
2114 }
2115
2116 return nullptr;
2117}
2118
2119void QPhysicsWorld::matchOrphanNodes()
2120{
2121 // FIXME: does this need thread safety?
2122 if (worldManager.orphanNodes.isEmpty())
2123 return;
2124
2125 qsizetype numNodes = worldManager.orphanNodes.length();
2126 qsizetype idx = 0;
2127
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);
2133 // swap-erase
2134 worldManager.orphanNodes.swapItemsAt(idx, numNodes - 1);
2135 worldManager.orphanNodes.pop_back();
2136 numNodes--;
2137 } else {
2138 idx++;
2139 }
2140 }
2141}
2142
2143void QPhysicsWorld::matchOrphanJoints()
2144{
2145 if (worldManager.orphanJoints.isEmpty())
2146 return;
2147
2148 qsizetype numNodes = worldManager.orphanJoints.length();
2149 qsizetype idx = 0;
2150
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);
2156 // swap-erase
2157 worldManager.orphanJoints.swapItemsAt(idx, numNodes - 1);
2158 worldManager.orphanJoints.pop_back();
2159 numNodes--;
2160 } else {
2161 idx++;
2162 }
2163 }
2164}
2165
2166void QPhysicsWorld::matchOrphanRaycasters()
2167{
2168 qsizetype idx = 0;
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);
2174 } else {
2175 ++idx;
2176 }
2177 }
2178}
2179
2180void QPhysicsWorld::applyGravity()
2181{
2182 // Before the nodes are synced, so that a character controller spends what
2183 // it is given this frame, and on the poses the last step left everything
2184 // in. Nothing here runs QML. A scene without fields stops here.
2185 if (m_gravityFields.isEmpty() && m_staleGravityFilters.isEmpty()
2186 && m_gravityWakes.isEmpty()) {
2187 return;
2188 }
2189
2190 // What fields that have since been destroyed acted on inside their shapes.
2191 const auto wakes = std::exchange(m_gravityWakes, {});
2192 for (const QPointer<QAbstractPhysicsNode> &node : wakes) {
2193 if (node)
2194 QPhysXGravity::wake(node, node->m_backendObject);
2195 }
2196
2197 // A field with shapes acts on what is inside them by itself; one without
2198 // is applied to the bodies of the scene below.
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);
2203 }
2204
2205 // A body asleep under a gravity that has gone, or is no longer let
2206 // through to it, has to be woken to fall under what is left. Waking it is
2207 // all that is needed: it is then awake when the fields are applied below.
2208 const QList<QFilterData> staleFilters = std::exchange(m_staleGravityFilters, {});
2209
2210 if (sceneFields.isEmpty() && staleFilters.isEmpty())
2211 return;
2212
2213 for (QAbstractPhysXNode *backend : std::as_const(m_physXBodies)) {
2214 QAbstractPhysicsNode *node = backend->frontendNode;
2215 if (!node)
2216 continue;
2217 const auto target = QPhysicsGravity::targetOf(node);
2218 if (target == QPhysicsGravity::Target::None)
2219 continue;
2220 // What PhysX keeps out of the pairs of a field with shapes, a field
2221 // without keeps out itself.
2222 const QFilterData nodeFilterData = node->filterData();
2223
2224 // The filter groups of the body itself changing can let it in to a
2225 // field or keep it out of one. They are only written to the shapes
2226 // later this frame, so the change is still pending here. For fields
2227 // with shapes, PhysX refilters the body's pairs and reports it
2228 // entering or leaving, and the field wakes it in response, but a
2229 // field without shapes has no pair.
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);
2235 });
2236 if (bodyFilterChanged || lostField)
2237 QPhysXGravity::wake(node, backend);
2238
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);
2242 }
2243 }
2244}
2245
2246void QPhysicsWorld::releaseGravityField(QAbstractPhysXNode *backend)
2247{
2248 const auto it = std::find(m_gravityFields.begin(), m_gravityFields.end(), backend);
2249 if (it == m_gravityFields.end())
2250 return;
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);
2256}
2257
2258void QPhysicsWorld::findPhysicsNodes()
2259{
2260 // This method finds the physics nodes inside the scene pointed to by the
2261 // scene property. This method is necessary to run whenever the scene
2262 // property is changed.
2263 if (m_scene == nullptr)
2264 return;
2265
2266 // Recursively go through all children and add all QAbstractPhysicsNode's
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) {
2271 // This should never happen but check anyway.
2272 if (converted->m_backendObject != nullptr) {
2273 qWarning() << "Warning: physics node already associated with a backend node.";
2274 continue;
2275 }
2276
2277 m_newPhysicsNodes.push_back(converted);
2278 worldManager.orphanNodes.removeAll(converted); // No longer orphan
2279 }
2280 children.append(child->childItems());
2281 }
2282}
2283
2284void QPhysicsWorld::emitContactCallbacks()
2285{
2286 for (const QPhysicsWorld::BodyContact &contact : std::as_const(m_registeredContacts)) {
2287 if (m_removedPhysicsNodes.contains(contact.sender)
2288 || m_removedPhysicsNodes.contains(contact.receiver))
2289 continue;
2290 contact.receiver->registerContact(contact.sender, contact.positions, contact.impulses,
2291 contact.normals);
2292 }
2293
2294 m_registeredContacts.clear();
2295}
2296
2297physx::PxPhysics *QPhysicsWorld::getPhysics()
2298{
2299 return StaticPhysXObjects::getReference().physics;
2300}
2301
2302const physx::PxCookingParams *QPhysicsWorld::getCookingParams()
2303{
2304 // PhysX cooks meshes through free functions taking the parameters, instead of through a
2305 // cooking object, but they still need the foundation for allocation and error reporting,
2306 // so there is nothing to cook with until it has been created.
2307 if (!StaticPhysXObjects::getReference().foundationCreated)
2308 return nullptr;
2309
2310 // FIXME: does the tolerance matter?
2311 static const physx::PxCookingParams params { physx::PxTolerancesScale() };
2312 return &params;
2313}
2314
2315physx::PxControllerManager *QPhysicsWorld::controllerManager()
2316{
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;
2320 }
2321 return m_physx->controllerManager;
2322}
2323
2324QQuick3DNode *QPhysicsWorld::scene() const
2325{
2326 return m_scene;
2327}
2328
2329void QPhysicsWorld::setScene(QQuick3DNode *newScene)
2330{
2331 if (m_scene == newScene)
2332 return;
2333
2334 m_scene = newScene;
2335
2336 // Delete all nodes since they are associated with the previous scene. One
2337 // deleted from a report earlier in this frame has nothing left to
2338 // deregister.
2339 for (auto body : std::as_const(m_physXBodies)) {
2340 if (body->frontendNode)
2341 deregisterNode(body->frontendNode);
2342 }
2343
2344 // Raycasters are not physics nodes and have no backend to tear down, so hand them back
2345 // to be matched against the new scene below, without a hit from the old one. Clearing
2346 // reports to QML, where a handler can delete a raycaster, hence the check.
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();
2352 }
2353
2354 // Check if scene is already used by another world
2355 bool sceneOK = true;
2356 for (QPhysicsWorld *world : std::as_const(worldManager.worlds)) {
2357 if (world != this && world->scene() == newScene) {
2358 sceneOK = false;
2359 qWarning() << "Warning: scene already associated with physics world";
2360 }
2361 }
2362
2363 if (sceneOK) {
2364 findPhysicsNodes();
2365 matchOrphanRaycasters();
2366 }
2367 emit sceneChanged();
2368}
2369
2370int QPhysicsWorld::numThreads() const
2371{
2372 return m_numThreads;
2373}
2374
2375void QPhysicsWorld::setNumThreads(int newNumThreads)
2376{
2377 newNumThreads = qMin(newNumThreads, 256);
2378
2379 if (m_numThreads == newNumThreads)
2380 return;
2381
2382 m_numThreads = newNumThreads;
2383 emit numThreadsChanged();
2384}
2385
2386bool QPhysicsWorld::reportKinematicKinematicCollisions() const
2387{
2388 return m_reportKinematicKinematicCollisions;
2389}
2390
2391void QPhysicsWorld::setReportKinematicKinematicCollisions(
2392 bool newReportKinematicKinematicCollisions)
2393{
2394 if (m_reportKinematicKinematicCollisions == newReportKinematicKinematicCollisions)
2395 return;
2396 m_reportKinematicKinematicCollisions = newReportKinematicKinematicCollisions;
2397 emit reportKinematicKinematicCollisionsChanged();
2398}
2399
2400bool QPhysicsWorld::reportStaticKinematicCollisions() const
2401{
2402 return m_reportStaticKinematicCollisions;
2403}
2404
2405void QPhysicsWorld::setReportStaticKinematicCollisions(bool newReportStaticKinematicCollisions)
2406{
2407 if (m_reportStaticKinematicCollisions == newReportStaticKinematicCollisions)
2408 return;
2409 m_reportStaticKinematicCollisions = newReportStaticKinematicCollisions;
2410 emit reportStaticKinematicCollisionsChanged();
2411}
2412
2413QPhysicsWorld::QueryStructure QPhysicsWorld::staticQueryStructure() const
2414{
2415 return m_staticQueryStructure;
2416}
2417
2418void QPhysicsWorld::setStaticQueryStructure(QueryStructure newStaticQueryStructure)
2419{
2420 if (m_staticQueryStructure == newStaticQueryStructure)
2421 return;
2422
2423 if (newStaticQueryStructure == QueryStructure::NoStructure) {
2424 qWarning()
2425 << "Warning: The QueryStructure::NoStructure is not supported for staticQueryStructure. Available options: [StaticTree, DynamicTree]";
2426 return;
2427 }
2428
2429 if (m_physicsInitialized) {
2430 qWarning()
2431 << "Warning: Changing 'staticQueryStructure' after physics is initialized will have no effect";
2432 return;
2433 }
2434
2435 m_staticQueryStructure = newStaticQueryStructure;
2436 emit staticQueryStructureChanged();
2437}
2438
2439QPhysicsWorld::QueryStructure QPhysicsWorld::dynamicQueryStructure() const
2440{
2441 return m_dynamicQueryStructure;
2442}
2443
2444void QPhysicsWorld::setDynamicQueryStructure(QueryStructure newDynamicQueryStructure)
2445{
2446 if (m_dynamicQueryStructure == newDynamicQueryStructure)
2447 return;
2448
2449 if (m_physicsInitialized) {
2450 qWarning()
2451 << "Warning: Changing 'dynamicQueryStructure' after physics is initialized will have no effect";
2452 return;
2453 }
2454
2455 m_dynamicQueryStructure = newDynamicQueryStructure;
2456 emit dynamicQueryStructureChanged();
2457}
2458
2459bool QPhysicsWorld::testRaycastQuery(const QVector3D &origin,
2460 const QVector3D &direction,
2461 float maxDistance,
2462 bool includeStatic,
2463 bool includeDynamic) const
2464{
2465 physx::PxRaycastBuffer hitBuffer;
2466 return raycastImpl(m_physx->scene, origin, direction,
2467 maxDistance, includeStatic, includeDynamic,
2468 hitBuffer,
2469 physx::PxHitFlags(),
2470 physx::PxQueryFlag::eANY_HIT);
2471}
2472
2473QQuick3DPhysicsLocationHit QPhysicsWorld::singleRaycastQuery(const QVector3D &origin,
2474 const QVector3D &direction,
2475 float maxDistance,
2476 bool includeStatic,
2477 bool includeDynamic) const
2478{
2479 physx::PxRaycastBuffer hitBuffer;
2480 const bool status = raycastImpl(m_physx->scene, origin, direction,
2481 maxDistance, includeStatic, includeDynamic,
2482 hitBuffer,
2483 physx::PxHitFlag::eDEFAULT);
2484
2485 if (status && hitBuffer.hasBlock) {
2486 return QQuick3DPhysicsLocationHit(hitBuffer.block,
2487 hitBuffer.block);
2488 }
2489
2490 return {};
2491}
2492
2493QList<QQuick3DPhysicsLocationHit> QPhysicsWorld::multiRaycastQuery(const QVector3D &origin,
2494 const QVector3D &direction,
2495 float maxDistance,
2496 bool includeStatic,
2497 bool includeDynamic) const
2498{
2499 DynamicQueryCallback<physx::PxRaycastCallback,
2500 QQuick3DPhysicsLocationHit,
2501 physx::PxRaycastHit> hitBuffer;
2502
2503 if (raycastImpl(m_physx->scene, origin, direction,
2504 maxDistance, includeStatic, includeDynamic,
2505 hitBuffer,
2506 physx::PxHitFlag::eDEFAULT,
2507 physx::PxQueryFlag::eNO_BLOCK)) {
2508
2509 return hitBuffer.hits;
2510 }
2511
2512 return {};
2513}
2514
2515QQuick3DPhysicsLocationHit
2516QPhysicsWorld::closestRaycastHit(const QVector3D &origin, const QVector3D &direction,
2517 float maxDistance, bool includeStatic, bool includeDynamic,
2518 QSpan<const QAbstractPhysicsNode *const> excludedBodies) const
2519{
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);
2525
2526 if (status && hitBuffer.hasBlock)
2527 return QQuick3DPhysicsLocationHit(hitBuffer.block, hitBuffer.block);
2528
2529 return {};
2530}
2531
2532bool QPhysicsWorld::testSweepQuery(QAbstractCollisionShape *shape,
2533 const QVector3D &direction,
2534 float maxDistance,
2535 bool includeStatic,
2536 bool includeDynamic) const
2537{
2538 physx::PxSweepBuffer hitBuffer;
2539 return sweepImpl(m_physx->scene, shape, direction,
2540 maxDistance, includeStatic, includeDynamic,
2541 hitBuffer,
2542 physx::PxHitFlags(),
2543 physx::PxQueryFlag::eANY_HIT);
2544}
2545
2546QQuick3DPhysicsLocationHit QPhysicsWorld::singleSweepQuery(QAbstractCollisionShape *shape,
2547 const QVector3D &direction,
2548 float maxDistance,
2549 bool includeStatic,
2550 bool includeDynamic) const
2551{
2552 physx::PxSweepBuffer hitBuffer;
2553 const bool status = sweepImpl(m_physx->scene, shape,
2554 direction, maxDistance, includeStatic, includeDynamic,
2555 hitBuffer,
2556 physx::PxHitFlag::eDEFAULT | physx::PxHitFlag::eMTD);
2557
2558 if (status && hitBuffer.hasBlock) {
2559 return QQuick3DPhysicsLocationHit(hitBuffer.block, hitBuffer.block);
2560 }
2561
2562 return {};
2563}
2564
2565QList<QQuick3DPhysicsLocationHit> QPhysicsWorld::multiSweepQuery(QAbstractCollisionShape *shape,
2566 const QVector3D &direction,
2567 float maxDistance,
2568 bool includeStatic,
2569 bool includeDynamic) const
2570{
2571 DynamicQueryCallback<physx::PxSweepCallback,
2572 QQuick3DPhysicsLocationHit,
2573 physx::PxSweepHit> hitBuffer;
2574
2575 if (sweepImpl(m_physx->scene, shape,
2576 direction, maxDistance, includeStatic, includeDynamic,
2577 hitBuffer,
2578 physx::PxHitFlag::eDEFAULT | physx::PxHitFlag::eMTD,
2579 physx::PxQueryFlag::eNO_BLOCK)) {
2580 return hitBuffer.hits;
2581 }
2582
2583 return {};
2584}
2585
2586bool QPhysicsWorld::testOverlapQuery(QAbstractCollisionShape *shape,
2587 bool includeStatic,
2588 bool includeDynamic) const
2589{
2590 physx::PxOverlapBuffer hitBuffer;
2591 return overlapImpl(m_physx->scene,
2592 shape, includeStatic, includeDynamic,
2593 hitBuffer,
2594 physx::PxQueryFlag::eANY_HIT);
2595}
2596
2597QList<QQuick3DPhysicsQueryHit> QPhysicsWorld::multiOverlapQuery(QAbstractCollisionShape *shape,
2598 bool includeStatic,
2599 bool includeDynamic) const
2600{
2601 DynamicQueryCallback<physx::PxOverlapCallback,
2602 QQuick3DPhysicsQueryHit,
2603 physx::PxOverlapHit> hitBuffer;
2604
2605 if (overlapImpl(m_physx->scene,
2606 shape, includeStatic, includeDynamic,
2607 hitBuffer,
2608 physx::PxQueryFlag::eNO_BLOCK)) {
2609 return hitBuffer.hits;
2610 }
2611
2612 return {};
2613}
2614
2616
2617#include "qphysicsworld.moc"
Definition qlist.h:82
The QVector3D class represents a vector or vertex in 3D space.
Definition qvectornd.h:178
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
#define QT_END_NAMESPACE
#define Q_OBJECT
#define emit
QVector< QAbstractPhysicsNode * > orphanNodes
QVector< QPhysicsWorld * > worlds
QVector< QRaycaster * > orphanRaycasters
QVector< QPhysicsJoint * > orphanJoints