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