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