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