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
qquick3dscenemanager.cpp
Go to the documentation of this file.
1// Copyright (C) 2019 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5
10
11#include <QtQuick/QQuickWindow>
12
13#include <QtQuick3DRuntimeRender/private/qssgrenderlayer_p.h>
14#include <ssg/qssgrendercontextcore.h>
15#include <QtQuick3DRuntimeRender/private/qssgrendermodel_p.h>
16#include <QtQuick3DRuntimeRender/private/qssgrenderer_p.h>
17#include <QtQuick3DRuntimeRender/private/qssgrenderimage_p.h>
18#include <QtQuick3DRuntimeRender/private/qssgrenderlayer_p.h>
19#include <QtQuick3DRuntimeRender/private/qssgrenderroot_p.h>
20#include <QtQuick3DRuntimeRender/ssg/qssgrenderextensions.h>
21#include <QtQuick3DRuntimeRender/private/qssgrenderuserpass_p.h>
22#include <QtQuick3DRuntimeRender/private/qssgrendercomputepass_p.h>
23
24#include <QtQuick3DUtils/private/qssgassert_p.h>
25
27
29
30// NOTE: Another indiraction to try to clean-up resource in a nice way.
31QSSGCleanupObject::QSSGCleanupObject(std::shared_ptr<QSSGRenderContextInterface> rci, QList<QSSGRenderGraphObject *> resourceCleanupQueue, QQuickWindow *window)
32 : QObject(window)
33 , m_rci(rci)
34 , m_window(window)
35 , m_resourceCleanupQueue(resourceCleanupQueue)
36{
37 Q_ASSERT(window != nullptr && rci); // We need a window and a rci for this!
38
39 if (QSGRenderContext *rc = QQuickWindowPrivate::get(window)->context) {
40 connect(rc, &QSGRenderContext::releaseCachedResourcesRequested, this, &QSSGCleanupObject::cleanupResources, Qt::DirectConnection);
41 connect(rc, &QSGRenderContext::invalidated, this, &QSSGCleanupObject::cleanupResources, Qt::DirectConnection);
42 } else {
43 qWarning() << "No QSGRenderContext, cannot cleanup resources!";
44 }
45}
46
48{
49 QSSG_CHECK(QSSG_DEBUG_COND(m_resourceCleanupQueue.isEmpty()));
50}
51
53{
54 m_rci->renderer()->cleanupResources(m_resourceCleanupQueue);
55 deleteLater();
56}
57
58static constexpr char qtQQ3DWAPropName[] { "_qtquick3dWindowAttachment" };
59
60static void detachDirtyList(QQuick3DObject **head, size_t count)
61{
62 for (size_t i = 0; i < count; ++i) {
63 QQuick3DObject *item = head[i];
64 while (item) {
65 QQuick3DObjectPrivate *p = QQuick3DObjectPrivate::get(item);
66 QQuick3DObject *next = p->nextDirtyItem;
67 p->prevDirtyItem = nullptr;
68 p->nextDirtyItem = nullptr;
69 item = next;
70 }
71 head[i] = nullptr;
72 }
73}
74
75QQuick3DSceneManager::QQuick3DSceneManager(QObject *parent)
76 : QObject(parent)
77{
78}
79
80// Should be deleted by QQuick3DWindowAttachment to ensure it's done
81// on the render thread.
82QQuick3DSceneManager::~QQuick3DSceneManager()
83{
84 cleanupNodes();
85 if (wattached)
86 wattached->unregisterSceneManager(*this);
87
88 // Objects still on one of our dirty lists hold a 'prevDirtyItem' pointer into the arrays
89 // below, which are freed together with this manager. Detach them now so a later
90 // removeFromDirtyList(), e.g. when the front-end object is itself destroyed, is a safe
91 // no-op instead of writing through a stale pointer. The normal per-frame drain only
92 // happens for active managers in synchronize(), not for one that was queued for cleanup.
93 //
94 // NOTE!!!: If these dirty objects are shared they will be re-queued by the surviving manager,
95 // but if they are not shared they will be dropped on the floor, which is fine, because they're not
96 // active and will either be destroyed or added to a new scene.
97 // The re-adoption happens because the destroyed() signal of this manager is connected to
98 // QQuick3DViewport::updateSceneManagerForImportScene(), which calls refSceneManager() on any
99 // surviving view, which in turn calls dirty() on any shared objects, which adds them to the
100 // dirty list if they're not already in one.
101 detachDirtyList(dirtyResources, std::size(dirtyResources));
102 detachDirtyList(dirtyNodes, std::size(dirtyNodes));
103 detachDirtyList(dirtyExtensions, std::size(dirtyExtensions));
104}
105
106void QQuick3DSceneManager::setWindow(QQuickWindow *window)
107{
108 if (window == m_window)
109 return;
110
111 if (window != m_window) {
112 if (wattached) {
113 // Unregister from old windows attached object
114 wattached->unregisterSceneManager(*this);
115 wattached = nullptr;
116 }
117 m_window = window;
118 if (m_window) {
119 wattached = getOrSetWindowAttachment(*m_window);
120 if (wattached)
121 wattached->registerSceneManager(*this);
122 }
123
124 emit windowChanged();
125 }
126}
127
128QQuickWindow *QQuick3DSceneManager::window()
129{
130 return m_window;
131}
132
133void QQuick3DSceneManager::dirtyItem(QQuick3DObject *item)
134{
135 Q_UNUSED(item);
136 emit needsUpdate();
137}
138
139void QQuick3DSceneManager::requestUpdate()
140{
141 emit needsUpdate();
142}
143
144void QQuick3DSceneManager::cleanup(QSSGRenderGraphObject *item)
145{
146 cleanupNodeList.insert(item);
147
148 if (auto front = m_nodeMap[item]) {
149 auto *po = QQuick3DObjectPrivate::get(front);
150 sharedResourceRemoved |= po->sharedResource;
151 po->spatialNode = nullptr;
152
153 // The front-end object is no longer reachable (destroyed) so make sure we don't return it
154 // when doing a node look-up.
155 m_nodeMap[item] = nullptr;
156 }
157}
158
159void QQuick3DSceneManager::polishItems()
160{
161
162}
163
164void QQuick3DSceneManager::forcePolish()
165{
166
167}
168
169void QQuick3DSceneManager::sync()
170{
171
172}
173
174void QQuick3DSceneManager::updateBoundingBoxes(QSSGBufferManager &mgr)
175{
176 if (lightmapSourceTracker.isDirty) {
177 mgr.setLightmapSource(lightmapSourceTracker.lightmapSource);
178 lightmapSourceTracker.isDirty = false;
179 }
180
181 for (auto *object : std::as_const(dirtyBoundingBoxList)) {
182 QQuick3DObjectPrivate *itemPriv = QQuick3DObjectPrivate::get(object);
183 if (itemPriv->sceneManager == nullptr)
184 continue;
185 auto model = static_cast<QSSGRenderModel *>(itemPriv->spatialNode);
186 if (model) {
187 QSSGBounds3 bounds = mgr.getModelBounds(model);
188 static_cast<QQuick3DModel *>(object)->setBounds(bounds.minimum, bounds.maximum);
189 }
190 }
191
192 dirtyBoundingBoxList.clear();
193}
194
195QQuick3DSceneManager::SyncResult QQuick3DSceneManager::updateDirtyResourceNodes()
196{
197 SyncResult ret = SyncResultFlag::None;
198
199 auto it = std::begin(dirtyResources);
200 const auto end = std::end(dirtyResources);
201 for (; it != end; ++it)
202 ret |= updateResources(it);
203
204 return ret;
205}
206
207void QQuick3DSceneManager::updateDirtySpatialNodes()
208{
209 auto it = std::begin(dirtyNodes);
210 const auto end = std::end(dirtyNodes);
211 for (; it != end; ++it)
212 updateNodes(it);
213}
214
215QQuick3DSceneManager::SyncResult QQuick3DSceneManager::updateDiryExtensions()
216{
217 SyncResult ret = SyncResultFlag::None;
218
219 auto it = std::begin(dirtyExtensions);
220 const auto end = std::end(dirtyExtensions);
221 for (; it != end; ++it)
222 ret |= updateExtensions(it);
223
224 return ret;
225}
226
227QQuick3DSceneManager::SyncResult QQuick3DSceneManager::updateDirtyResourceSecondPass()
228{
229 const auto updateDirtyResourceNode = [this](QQuick3DObject *resource) {
230 QQuick3DObjectPrivate *po = QQuick3DObjectPrivate::get(resource);
231 po->dirtyAttributes = 0; // Not used, but we should still reset it.
232 po->secondaryUpdateRequested = false;
233 QSSGRenderGraphObject *node = po->spatialNode;
234 po->spatialNode = resource->updateSpatialNode(node);
235 if (po->spatialNode)
236 m_nodeMap.insert(po->spatialNode, resource);
237 return po->sharedResource ? SyncResultFlag::SharedResourcesDirty : SyncResultFlag::None;
238 };
239
240 SyncResult res = SyncResultFlag::None;
241 auto it = dirtySecondPassResources.constBegin();
242 const auto end = dirtySecondPassResources.constEnd();
243 for (; it != end; ++it)
244 res |= updateDirtyResourceNode(*it);
245
246 // Expectation is that we won't get here often, for other updates the
247 // backend nodes should have been realized and we won't get here, so
248 // just release space used by the set.
249 dirtySecondPassResources = {};
250
251 return res;
252}
253
254void QQuick3DSceneManager::updateDirtyResource(QQuick3DObject *resourceObject)
255{
256 QQuick3DObjectPrivate *itemPriv = QQuick3DObjectPrivate::get(resourceObject);
257 quint32 dirty = itemPriv->dirtyAttributes;
258 Q_UNUSED(dirty);
259 itemPriv->dirtyAttributes = 0;
260 QSSGRenderGraphObject *oldNode = itemPriv->spatialNode;
261 QSSGRenderGraphObject *newNode = resourceObject->updateSpatialNode(itemPriv->spatialNode);
262
263 const bool backendNodeChanged = oldNode != newNode;
264
265 // If the backend resource object changed, we need to clean up the old one.
266 if (oldNode && backendNodeChanged)
267 cleanup(oldNode);
268
269 // NOTE: cleanup() will remove the item from the node map and set the spatial node to nullptr.
270 // so we need to set it here.
271 itemPriv->spatialNode = newNode;
272
273 if (itemPriv->spatialNode) {
274 m_nodeMap.insert(itemPriv->spatialNode, resourceObject);
275 if (itemPriv->spatialNode->type == QSSGRenderGraphObject::Type::ResourceLoader) {
276 resourceLoaders.insert(itemPriv->spatialNode);
277 } else if (itemPriv->spatialNode->type == QQuick3DObjectPrivate::Type::Image2D && backendNodeChanged) {
278 ++inputHandlingEnabled;
279 } else if (QSSGRenderGraphObjectUtils::isUserRenderPass(itemPriv->type) && itemPriv->spatialNode) {
280 auto *userRenderPass = static_cast<QSSGRenderUserPassBase *>(itemPriv->spatialNode);
281 if (const auto idx = userRenderPasses.indexOf(userRenderPass); idx == -1) {
282 userRenderPasses.push_back(userRenderPass);
283 userRenderPassesDirty = true;
284 }
285 }
286 }
287
288 if (itemPriv->hasFlag(QQuick3DObjectPrivate::Flags::RequiresSecondaryUpdate) && itemPriv->secondaryUpdateRequested)
289 dirtySecondPassResources.insert(resourceObject);
290
291 // resource nodes dont go in the tree, so we dont need to parent them
292}
293
294void QQuick3DSceneManager::updateDirtySpatialNode(QQuick3DNode *spatialNode)
295{
296 const auto prepNewSpatialNode = [this](QSSGRenderNode *node) {
297 if (node) {
298 node->rootNodeRef = wattached->rootNode()->rootNodeRef;
299 Q_ASSERT(QSSGRenderRoot::get(node->rootNodeRef) != nullptr);
300 }
301 };
302
303 QQuick3DObjectPrivate *itemPriv = QQuick3DObjectPrivate::get(spatialNode);
304 quint32 dirty = itemPriv->dirtyAttributes;
305 itemPriv->dirtyAttributes = 0;
306 QSSGRenderGraphObject *oldNode = itemPriv->spatialNode;
307 QSSGRenderGraphObject *newNode = spatialNode->updateSpatialNode(oldNode);
308
309 const bool backendNodeChanged = oldNode != newNode;
310
311 // If the backend node changed, we need to clean up the old one.
312 if (oldNode && backendNodeChanged)
313 cleanup(oldNode);
314
315 // NOTE: cleanup() will remove the item from the node map and set the spatial node to nullptr.
316 // so we need to set it here.
317 itemPriv->spatialNode = newNode;
318 prepNewSpatialNode(static_cast<QSSGRenderNode *>(itemPriv->spatialNode));
319
320 // NOTE: We always update the node map, as we can end-up with the a node map where the mapping
321 // has been 'disconnected', e.g., the front-end object removed from the scene only to be later
322 // re-used.
323 if (itemPriv->spatialNode) {
324 m_nodeMap.insert(itemPriv->spatialNode, spatialNode);
325 if (itemPriv->type == QQuick3DObjectPrivate::Type::Item2D && itemPriv->spatialNode != oldNode)
326 ++inputHandlingEnabled;
327 }
328
329 QSSGRenderNode *graphNode = static_cast<QSSGRenderNode *>(itemPriv->spatialNode);
330
331 if (graphNode && graphNode->parent && dirty & QQuick3DObjectPrivate::ParentChanged) {
332 QQuick3DNode *nodeParent = qobject_cast<QQuick3DNode *>(spatialNode->parentItem());
333 if (nodeParent) {
334 QSSGRenderNode *parentGraphNode = static_cast<QSSGRenderNode *>(
335 QQuick3DObjectPrivate::get(nodeParent)->spatialNode);
336 if (parentGraphNode) {
337 graphNode->parent->removeChild(*graphNode);
338 parentGraphNode->addChild(*graphNode);
339 }
340 }
341 }
342
343 if (graphNode && graphNode->parent == nullptr) {
344 QQuick3DNode *nodeParent = qobject_cast<QQuick3DNode *>(spatialNode->parentItem());
345 if (nodeParent) {
346 QSSGRenderNode *parentGraphNode = static_cast<QSSGRenderNode *>(QQuick3DObjectPrivate::get(nodeParent)->spatialNode);
347 if (!parentGraphNode) {
348 // The parent spatial node hasn't been created yet
349 auto parentNode = QQuick3DObjectPrivate::get(nodeParent);
350 parentNode->spatialNode = nodeParent->updateSpatialNode(parentNode->spatialNode);
351 if (parentNode->spatialNode)
352 m_nodeMap.insert(parentNode->spatialNode, nodeParent);
353 parentGraphNode = static_cast<QSSGRenderNode *>(parentNode->spatialNode);
354 prepNewSpatialNode(parentGraphNode);
355 }
356 if (parentGraphNode)
357 parentGraphNode->addChild(*graphNode);
358 } else {
359 QQuick3DViewport *viewParent = qobject_cast<QQuick3DViewport *>(spatialNode->parent());
360 if (viewParent) {
361 auto sceneRoot = QQuick3DObjectPrivate::get(viewParent->scene());
362 if (!sceneRoot->spatialNode) // must have a scene root spatial node first
363 sceneRoot->spatialNode = viewParent->scene()->updateSpatialNode(sceneRoot->spatialNode);
364 if (sceneRoot->spatialNode) {
365 auto *sceneRootNode = static_cast<QSSGRenderNode *>(sceneRoot->spatialNode);
366 prepNewSpatialNode(sceneRootNode);
367 m_nodeMap.insert(sceneRootNode, viewParent->scene());
368 sceneRootNode->addChild(*graphNode);
369 }
370 }
371 }
372 }
373}
374
375QQuick3DObject *QQuick3DSceneManager::lookUpNode(const QSSGRenderGraphObject *node) const
376{
377 return m_nodeMap[const_cast<QSSGRenderGraphObject *>(node)];
378}
379
380QQuick3DWindowAttachment *QQuick3DSceneManager::getOrSetWindowAttachment(QQuickWindow &window)
381{
382
383 QQuick3DWindowAttachment *wa = nullptr;
384 if (auto aProperty = window.property(qtQQ3DWAPropName); aProperty.isValid())
385 wa = aProperty.value<QQuick3DWindowAttachment *>();
386
387 if (!wa) {
388 // WindowAttachment will not be created under 'window'.
389 // It should be deleted after all the cleanups related with 'window',
390 // otherwise some resourses deleted after it, will not be cleaned correctly.
391 wa = new QQuick3DWindowAttachment(&window);
392 window.setProperty(qtQQ3DWAPropName, QVariant::fromValue(wa));
393 }
394
395 return wa;
396}
397
398QQuick3DSceneManager::SyncResult QQuick3DSceneManager::cleanupNodes()
399{
400 SyncResult res = sharedResourceRemoved ? SyncResultFlag::SharedResourcesDirty : SyncResultFlag::None;
401 // Reset the shared resource removed value.
402 sharedResourceRemoved = false;
403 for (auto node : std::as_const(cleanupNodeList)) {
404 // Remove "spatial" nodes from scenegraph
405 if (QSSGRenderGraphObject::isNodeType(node->type)) {
406 QSSGRenderNode *spatialNode = static_cast<QSSGRenderNode *>(node);
407 spatialNode->removeFromGraph();
408 }
409
410 if (node->type == QQuick3DObjectPrivate::Type::Item2D) {
411 --inputHandlingEnabled;
412 } else if (node->type == QQuick3DObjectPrivate::Type::Image2D) {
413 auto image = static_cast<QSSGRenderImage *>(node);
414 if (image && image->m_qsgTexture != nullptr ) {
415 --inputHandlingEnabled;
416 }
417 }
418
419 // Remove all nodes from the node map because they will no
420 // longer be usable from this point from the frontend
421 m_nodeMap.remove(node);
422
423 if (QSSGRenderGraphObjectUtils::hasInternalFlag(*node, QSSGRenderGraphObjectUtils::InternalFlags::AutoRegisterExtension)) {
424 autoRegisteredExtensions.removeAll(node);
425 autoRegisteredExtensionsDirty = true;
426 }
427
428 if (QSSGRenderGraphObjectUtils::isUserRenderPass(node->type)) {
429 auto *userRenderPass = static_cast<QSSGRenderUserPassBase *>(node);
430 if (qsizetype idx = userRenderPasses.indexOf(userRenderPass); idx != -1) {
431 userRenderPasses.remove(idx);
432 userRenderPassesDirty = true;
433 }
434 }
435
436 // Some nodes will trigger resource cleanups that need to
437 // happen at a specified time (when graphics backend is active)
438 // So build another queue for graphics assets marked for removal
439 if (node->hasGraphicsResources()) {
440 wattached->queueForCleanup(node);
441 if (node->type == QSSGRenderGraphObject::Type::ResourceLoader)
442 resourceLoaders.remove(node);
443 } else {
444 delete node;
445 }
446 }
447
448 // Nodes are now "cleaned up" so clear the cleanup list
449 cleanupNodeList.clear();
450
451 return res;
452}
453
454QQuick3DSceneManager::SyncResult QQuick3DSceneManager::updateResources(QQuick3DObject **listHead)
455{
456 SyncResult res = SyncResultFlag::None;
457
458 // Detach the current list head first, and consume all reachable entries.
459 // New entries may be added to the new list while traversing, which will be
460 // visited on the next updateDirtyNodes() call.
461 bool hasSharedResources = false;
462 QQuick3DObject *updateList = *listHead;
463 *listHead = nullptr;
464 if (updateList)
465 QQuick3DObjectPrivate::get(updateList)->prevDirtyItem = &updateList;
466
467 QQuick3DObject *item = updateList;
468 while (item) {
469 // Different processing for resource nodes vs hierarchical nodes etc.
470 Q_ASSERT(!QSSGRenderGraphObject::isNodeType(QQuick3DObjectPrivate::get(item)->type) || !QSSGRenderGraphObject::isExtension(QQuick3DObjectPrivate::get(item)->type));
471 // handle hierarchical nodes
472 auto *po = QQuick3DObjectPrivate::get(item);
473 // Unlink before calling updateSpatialNode() below: if that call re-enters dirty() on
474 // this very object (e.g. via a QML binding evaluated as a side effect of the update),
475 // dirty() needs prevDirtyItem to already be null so it re-links the object via its own
476 // addToDirtyList() call, onto the (already emptied) scene manager list.
477 po->removeFromDirtyList();
478 updateDirtyResource(item);
479 hasSharedResources |= po->sharedResource;
480 item = updateList;
481 }
482
483 if (hasSharedResources)
484 res |= SyncResultFlag::SharedResourcesDirty;
485
486 return res;
487}
488
489void QQuick3DSceneManager::updateNodes(QQuick3DObject **listHead)
490{
491 // Detach the current list head first, and consume all reachable entries.
492 // New entries may be added to the new list while traversing, which will be
493 // visited on the next updateDirtyNodes() call.
494 QQuick3DObject *updateList = *listHead;
495 *listHead = nullptr;
496 if (updateList)
497 QQuick3DObjectPrivate::get(updateList)->prevDirtyItem = &updateList;
498
499 QQuick3DObject *item = updateList;
500 while (item) {
501 // Different processing for resource nodes vs hierarchical nodes (anything that's _not_ a resource)
502 Q_ASSERT(QSSGRenderGraphObject::isNodeType(QQuick3DObjectPrivate::get(item)->type));
503 // handle hierarchical nodes
504 // See the matching comment in updateResources() about the removeFromDirtyList()/
505 // updateSpatialNode() ordering.
506 QQuick3DObjectPrivate::get(item)->removeFromDirtyList();
507 updateDirtySpatialNode(static_cast<QQuick3DNode *>(item));
508 item = updateList;
509 }
510}
511
512QQuick3DSceneManager::SyncResult QQuick3DSceneManager::updateExtensions(QQuick3DObject **listHead)
513{
514 SyncResult ret = SyncResultFlag::None;
515
516 const auto updateDirtyExtensionNode = [this, &ret](QQuick3DObject *extension) {
517 QQuick3DObjectPrivate *po = QQuick3DObjectPrivate::get(extension);
518 po->dirtyAttributes = 0; // Not used, but we should still reset it.
519 QSSGRenderGraphObject *oldNode = po->spatialNode;
520 QSSGRenderGraphObject *newNode = extension->updateSpatialNode(oldNode);
521
522 const bool backendNodeChanged = oldNode != newNode;
523
524 if (backendNodeChanged)
525 ret |= SyncResultFlag::ExtensionsDiry;
526
527 // If the backend node changed, we need to clean up the old one.
528 if (oldNode && backendNodeChanged)
529 cleanup(oldNode);
530
531 // NOTE: cleanup() will remove the item from the node map and set the spatial node to nullptr.
532 // so we need to set it here.
533 po->spatialNode = newNode;
534
535 if (po->spatialNode)
536 m_nodeMap.insert(po->spatialNode, extension);
537
538 if (newNode && QSSGRenderGraphObjectUtils::hasInternalFlag(*newNode, QSSGRenderGraphObjectUtils::InternalFlags::AutoRegisterExtension)) {
539 const bool shouldInsert = autoRegisteredExtensions.indexOf(static_cast<QSSGRenderExtension *>(newNode)) == -1;
540 if (shouldInsert) {
541 autoRegisteredExtensions.push_back(static_cast<QSSGRenderExtension *>(newNode));
542 autoRegisteredExtensionsDirty = true;
543 }
544 }
545 };
546
547 // Detach the current list head first, and consume all reachable entries.
548 // New entries may be added to the new list while traversing, which will be
549 // visited on the next updateDirtyNodes() call.
550 QQuick3DObject *updateList = *listHead;
551 *listHead = nullptr;
552 if (updateList)
553 QQuick3DObjectPrivate::get(updateList)->prevDirtyItem = &updateList;
554
555 QQuick3DObject *item = updateList;
556 while (item) {
557 // Different processing for resource nodes vs hierarchical nodes (anything that's _not_ a resource)
558 Q_ASSERT(QSSGRenderGraphObject::isExtension(QQuick3DObjectPrivate::get(item)->type));
559 // handle hierarchical nodes
560 // See the matching comment in updateResources() about the removeFromDirtyList()/
561 // updateSpatialNode() ordering.
562 QQuick3DObjectPrivate::get(item)->removeFromDirtyList();
563 updateDirtyExtensionNode(item);
564 item = updateList;
565 }
566
567 return ret;
568}
569
570void QQuick3DSceneManager::preSync()
571{
572 for (auto it = std::begin(dirtyResources), end = std::end(dirtyResources); it != end; ++it) {
573 QQuick3DObject *next = *it;
574 while (next) {
575 next->preSync();
576 next = QQuick3DObjectPrivate::get(next)->nextDirtyItem;
577 }
578 }
579
580 for (auto it = std::begin(dirtyNodes), end = std::end(dirtyNodes); it != end; ++it) {
581 QQuick3DObject *next = *it;
582 while (next) {
583 next->preSync();
584 next = QQuick3DObjectPrivate::get(next)->nextDirtyItem;
585 }
586 }
587
588 for (auto it = std::begin(dirtyExtensions), end = std::end(dirtyExtensions); it != end; ++it) {
589 QQuick3DObject *next = *it;
590 while (next) {
591 next->preSync();
592 next = QQuick3DObjectPrivate::get(next)->nextDirtyItem;
593 }
594 }
595}
596
597////////
598/// QQuick3DWindowAttachment
599////////
600
601QQuick3DWindowAttachment::QQuick3DWindowAttachment(QQuickWindow *window)
602 : m_window(window)
603 , m_rootNode(new QSSGRenderRoot)
604{
605 if (window) {
606 // Act when the application calls window->releaseResources() and the
607 // render loop emits the corresponding signal in order to forward the
608 // event to us as well. (do not confuse with other release-resources
609 // type of functions, this is about dropping pipeline and other resource
610 // caches than can be automatically recreated if needed on the next frame)
611 QQuickWindowPrivate *wd = QQuickWindowPrivate::get(window);
612 QSGRenderContext *rc = wd->context;
613 if (QSSG_GUARD_X(rc, "QQuickWindow has no QSGRenderContext, this should not happen")) {
614 // QSGRenderContext signals are emitted on the render thread, if there is one; use DirectConnection
615 connect(rc, &QSGRenderContext::releaseCachedResourcesRequested, this, &QQuick3DWindowAttachment::onReleaseCachedResources, Qt::DirectConnection);
616 connect(rc, &QSGRenderContext::invalidated, this, &QQuick3DWindowAttachment::onInvalidated, Qt::DirectConnection);
617 }
618
619 // Do a final lifetime eval when the window is destroyed.
620 connect(window, &QQuickWindow::destroyed, this, &QQuick3DWindowAttachment::evaluateEol);
621 // afterAnimating is emitted on the main thread.
622 connect(window, &QQuickWindow::afterAnimating, this, &QQuick3DWindowAttachment::preSync);
623 // afterFrameEnd is emitted on render thread.
624 connect(window, &QQuickWindow::afterFrameEnd, this, &QQuick3DWindowAttachment::cleanupResources, Qt::DirectConnection);
625 }
626}
627
628QQuick3DWindowAttachment::~QQuick3DWindowAttachment()
629{
630 for (auto *manager : std::as_const(sceneManagerCleanupQueue)) {
631 sceneManagers.removeOne(manager);
632 delete manager;
633 }
634 // remaining sceneManagers should also be removed
635 qDeleteAll(sceneManagers);
636 QSSG_CHECK(QSSG_DEBUG_COND(resourceCleanupQueue.isEmpty()));
637
638 if (!pendingResourceCleanupQueue.isEmpty()) {
639 // Let's try to recover from this situation. Most likely this is some loader usage
640 // situation, where all View3Ds have been destroyed while the window still lives and might
641 // eventually just create a new View3D. We cannot release the resources here, as we'll need
642 // to do that on the render thread. Instaed we'll transform the pendingResourceCleanupQueue
643 // to a cleanup object that can be called on the render thread.
644 if (m_rci && m_window) {
645 new QSSGCleanupObject(m_rci, std::move(pendingResourceCleanupQueue), m_window);
646 QMetaObject::invokeMethod(m_window, &QQuickWindow::releaseResources, Qt::QueuedConnection);
647 } else {
648 qWarning() << "Pending resource cleanup queue not empty, but no RCI or window to clean it up!";
649 }
650 }
651
652 if (m_window)
653 m_window->setProperty(qtQQ3DWAPropName, QVariant());
654
655 delete m_rootNode;
656}
657
658void QQuick3DWindowAttachment::preSync()
659{
660 for (auto &sceneManager : std::as_const(sceneManagers))
661 sceneManager->preSync();
662}
663
664// Called from the render thread
665void QQuick3DWindowAttachment::cleanupResources()
666{
667 // Pass the scene managers list of resources marked for
668 // removal to the render context for deletion
669 // The render context will take ownership of the nodes
670 // and clear the list
671
672 // In special cases there is no rci because synchronize() is never called.
673 // This can happen when running with the software backend of Qt Quick.
674 // Handle this gracefully.
675 if (!m_rci)
676 return;
677
678 // Check if there's orphaned resources that needs to be
679 // cleaned out first.
680 if (resourceCleanupQueue.size() != 0)
681 m_rci->renderer()->cleanupResources(resourceCleanupQueue);
682
683 m_rci->bufferManager()->frameEnded();
684}
685
686// Called on the render thread, if there is one
687void QQuick3DWindowAttachment::onReleaseCachedResources()
688{
689 if (m_rci)
690 m_rci->releaseCachedResources();
691 Q_EMIT releaseCachedResources();
692}
693
694void QQuick3DWindowAttachment::onInvalidated()
695{
696 // Find all objects that have graphics resources and queue them
697 // for cleanup.
698 // 1. We'll need to manually go through the nodes of each scene manager and mark
699 // objects with graphics resources for deletion.
700 // The scene graph is invalidated so we need to release graphics resources now, on the render thread.
701 for (auto &sceneManager : std::as_const(sceneManagers)) {
702 const auto objects = sceneManager->m_nodeMap.keys();
703 for (QSSGRenderGraphObject *obj : objects) {
704 if (obj->hasGraphicsResources())
705 sceneManager->cleanup(obj);
706 }
707 }
708
709 // Start: follow the normal clean-up procedure
710 for (auto &sceneManager : std::as_const(sceneManagers))
711 sceneManager->cleanupNodes();
712
713 for (QSSGRenderLayer *layers : std::as_const(pendingLayerCleanupQueue))
714 delete layers;
715 pendingLayerCleanupQueue.clear();
716
717 for (const auto &pr : std::as_const(pendingResourceCleanupQueue))
718 resourceCleanupQueue.insert(pr);
719 pendingResourceCleanupQueue.clear();
720
721 // NOTE!: It's essential that we release the cached resources before we
722 // call cleanupResources(), to avoid the expensive bookkeeping code involved
723 // for models. This is achieved by dropping the data to avoid expensive look-ups; it's going away anyways.
724 // (In the future, if/when cleanupDrawCallData() is improved, then this step might not be necessary).
725 onReleaseCachedResources();
726
727 cleanupResources();
728 // end
729
730 // If the SG RenderContex is invalidated and we're the only one holding onto the SSG
731 // RenderContextInterface then just release it. If the application is not going down
732 // a new RCI will be created/set during the next sync.
733 if (m_rci.use_count() == 1) {
734 m_rci.reset();
735 emit renderContextInterfaceChanged();
736 }
737}
738
739QQuick3DWindowAttachment::SyncResult QQuick3DWindowAttachment::synchronize(QSet<QSSGRenderGraphObject *> &resourceLoaders)
740{
741 // Terminate old scene managers
742 for (auto *manager : std::as_const(sceneManagerCleanupQueue)) {
743 sceneManagers.removeOne(manager);
744 delete manager;
745 }
746 // Terminate old scene managers
747 sceneManagerCleanupQueue = {};
748
749 SyncResult syncResult = SyncResultFlag::None;
750
751 // Cleanup
752 for (auto &sceneManager : std::as_const(sceneManagers))
753 syncResult |= sceneManager->cleanupNodes();
754
755 for (QSSGRenderLayer *layers : std::as_const(pendingLayerCleanupQueue))
756 delete layers;
757 pendingLayerCleanupQueue.clear();
758
759 // Resources
760 for (auto &sceneManager : std::as_const(sceneManagers))
761 syncResult |= sceneManager->updateDirtyResourceNodes();
762 // Spatial Nodes
763 for (auto &sceneManager : std::as_const(sceneManagers))
764 sceneManager->updateDirtySpatialNodes();
765 for (auto &sceneManager : std::as_const(sceneManagers))
766 syncResult |= sceneManager->updateDiryExtensions();
767 for (auto &sceneManager : std::as_const(sceneManagers))
768 syncResult |= sceneManager->updateDirtyResourceSecondPass();
769 // Bounding Boxes
770 for (auto &sceneManager : std::as_const(sceneManagers))
771 sceneManager->updateBoundingBoxes(*m_rci->bufferManager());
772 // Resource Loaders
773 for (auto &sceneManager : std::as_const(sceneManagers))
774 resourceLoaders.unite(sceneManager->resourceLoaders);
775
776 if ((syncResult & SyncResultFlag::SharedResourcesDirty)) {
777 // We know there are shared resources in the scene, so notify the "world".
778 // Ideally we should be more targeted, but for now this will do the job.
779 for (auto &sceneManager : std::as_const(sceneManagers))
780 sceneManager->requestUpdate();
781 }
782
783 // Prepare pending (adopted) resources for clean-up (will happen as a result of afterFrameEnd()).
784 for (const auto &pr : std::as_const(pendingResourceCleanupQueue))
785 resourceCleanupQueue.insert(pr);
786 pendingResourceCleanupQueue.clear();
787
788 return syncResult;
789}
790
791void QQuick3DWindowAttachment::requestUpdate()
792{
793 for (const auto &sm : std::as_const(sceneManagers))
794 sm->requestUpdate();
795}
796
797void QQuick3DWindowAttachment::evaluateEol()
798{
799 // NOTE: We'll re-iterate this list either on the next sync or if there's no sceneManagers left.
800 // See: sync and dtor.
801 for (QQuick3DSceneManager *manager : std::as_const(sceneManagerCleanupQueue))
802 sceneManagers.removeOne(manager);
803
804 // Keep the attachment, and the QSSGRenderRoot it owns, alive for as long as the window is,
805 // even when no scene managers remain. Nodes reference the root via rootNodeRef (e.g. imported
806 // scenes shared across views), and those references must stay valid across View3D create and
807 // destroy cycles within the same window; deleting the root here would leave them dangling.
808 // When the window goes away the attachment is deleted through the QQuickWindow::destroyed ->
809 // evaluateEol connection set up in the constructor
810 // (NOTE: QPointers are cleared out before the destroyed signal is sent).
811 if (sceneManagers.isEmpty() && m_window.isNull())
812 delete this;
813}
814
815QQuickWindow *QQuick3DWindowAttachment::window() const { return m_window; }
816
817void QQuick3DWindowAttachment::setRci(const std::shared_ptr<QSSGRenderContextInterface> &rciptr)
818{
819 QSSG_CHECK_X(m_rci == nullptr || m_rci.use_count() == 1, "Old render context was not released!");
820 m_rci = rciptr;
821
822 // For convenience we'll also set the SG rendere context here.
823 if (m_rci && m_window)
824 QSSGRendererPrivate::setSgRenderContext(*m_rci->renderer(), QQuickWindowPrivate::get(m_window)->context);
825
826 emit renderContextInterfaceChanged();
827}
828
829void QQuick3DWindowAttachment::registerSceneManager(QQuick3DSceneManager &manager)
830{
831 if (!sceneManagers.contains(&manager))
832 sceneManagers.push_back(&manager);
833}
834
835void QQuick3DWindowAttachment::unregisterSceneManager(QQuick3DSceneManager &manager)
836{
837 sceneManagers.removeOne(&manager);
838}
839
840void QQuick3DWindowAttachment::queueForCleanup(QSSGRenderGraphObject *obj)
841{
842 Q_ASSERT(obj->hasGraphicsResources());
843 pendingResourceCleanupQueue.push_back(obj);
844}
845
846void QQuick3DWindowAttachment::queueForCleanup(QQuick3DSceneManager *manager)
847{
848 if (!sceneManagerCleanupQueue.contains(manager))
849 sceneManagerCleanupQueue.push_back(manager);
850}
851
852void QQuick3DWindowAttachment::queueForCleanup(QSSGRenderLayer *layer)
853{
854 if (QSSGRenderRoot *lr = QSSGRenderRoot::get(layer->rootNodeRef); lr != m_rootNode) {
855 qWarning("Attempted to queue layer for cleanup that is not part of the current window!");
856 return;
857 }
858
859 if (!pendingLayerCleanupQueue.contains(layer)) {
860 layer->removeFromGraph();
861 pendingLayerCleanupQueue.push_back(layer);
862 }
863}
864
865QT_END_NAMESPACE
Q_INVOKABLE void cleanupResources()
Combined button and popup list for selecting options.
static void detachDirtyList(QQuick3DObject **head, size_t count)
static constexpr char qtQQ3DWAPropName[]