1/****************************************************************************
2**
3** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB).
4** Contact: https://www.qt.io/licensing/
5**
6** This file is part of the Qt3D module of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and The Qt Company. For licensing terms
14** and conditions see https://www.qt.io/terms-conditions. For further
15** information use the contact form at https://www.qt.io/contact-us.
16**
17** GNU Lesser General Public License Usage
18** Alternatively, this file may be used under the terms of the GNU Lesser
19** General Public License version 3 as published by the Free Software
20** Foundation and appearing in the file LICENSE.LGPL3 included in the
21** packaging of this file. Please review the following information to
22** ensure the GNU Lesser General Public License version 3 requirements
23** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
24**
25** GNU General Public License Usage
26** Alternatively, this file may be used under the terms of the GNU
27** General Public License version 2.0 or (at your option) the GNU General
28** Public license version 3 or any later version approved by the KDE Free
29** Qt Foundation. The licenses are as published by the Free Software
30** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
31** included in the packaging of this file. Please review the following
32** information to ensure the GNU General Public License requirements will
33** be met: https://www.gnu.org/licenses/gpl-2.0.html and
34** https://www.gnu.org/licenses/gpl-3.0.html.
35**
36** $QT_END_LICENSE$
37**
38****************************************************************************/
39
40#include "qnode.h"
41#include "qnode_p.h"
42
43#include <Qt3DCore/QComponent>
44#include <Qt3DCore/qaspectengine.h>
45#include <Qt3DCore/qdynamicpropertyupdatedchange.h>
46#include <Qt3DCore/qentity.h>
47#include <Qt3DCore/qnodedestroyedchange.h>
48#include <Qt3DCore/qpropertynodeaddedchange.h>
49#include <Qt3DCore/qpropertynoderemovedchange.h>
50#include <Qt3DCore/qpropertyupdatedchange.h>
51#include <QtCore/QChildEvent>
52#include <QtCore/QEvent>
53#include <QtCore/QMetaObject>
54#include <QtCore/QMetaProperty>
55
56#include <Qt3DCore/private/corelogging_p.h>
57#include <Qt3DCore/private/qdestructionidandtypecollector_p.h>
58#include <Qt3DCore/private/qnodecreatedchangegenerator_p.h>
59#include <Qt3DCore/private/qnodevisitor_p.h>
60#include <Qt3DCore/private/qpostman_p.h>
61#include <Qt3DCore/private/qscene_p.h>
62#include <QtCore/private/qmetaobject_p.h>
63
64QT_BEGIN_NAMESPACE
65
66namespace Qt3DCore {
67
68QNodePrivate::QNodePrivate()
69 : QObjectPrivate()
70 , m_changeArbiter(nullptr)
71 , m_typeInfo(nullptr)
72 , m_scene(nullptr)
73 , m_id(QNodeId::createId())
74 , m_blockNotifications(false)
75 , m_hasBackendNode(false)
76 , m_enabled(true)
77 , m_notifiedParent(false)
78 , m_defaultPropertyTrackMode(QNode::TrackFinalValues)
79 , m_propertyChangesSetup(false)
80 , m_signals(this)
81{
82}
83
84QNodePrivate::~QNodePrivate()
85{
86}
87
88void QNodePrivate::init(QNode *parent)
89{
90 if (!parent)
91 return;
92
93 // If we have a QNode parent that has a scene (and hence change arbiter),
94 // copy these to this QNode. If valid, then also notify the backend
95 // in a deferred way when the object is fully constructed. This is delayed
96 // until the object is fully constructed as it involves calling a virtual
97 // function of QNode.
98 m_parentId = parent->id();
99 const auto parentPrivate = get(parent);
100 m_scene = parentPrivate->m_scene;
101 Q_Q(QNode);
102 if (m_scene) {
103 // schedule the backend notification and scene registering -> set observers through scene
104 m_scene->postConstructorInit()->addNode(q);
105 }
106}
107
108/*!
109 * \internal
110 *
111 * Sends QNodeCreatedChange events to the aspects.
112 */
113void QNodePrivate::notifyCreationChange()
114{
115 Q_Q(QNode);
116 // Do nothing if we already have already sent a node creation change
117 // and not a subsequent node destroyed change.
118 if (m_hasBackendNode || !m_scene)
119 return;
120 QNodeCreatedChangeGenerator generator(q);
121 const auto creationChanges = generator.creationChanges();
122 for (const auto &change : creationChanges)
123 notifyObservers(change);
124}
125
126/*!
127 * \internal
128 *
129 * Notify the backend that the parent lost this node as a child and
130 * that this node is being destroyed. We only send the node removed
131 * change for the parent's children property iff we have an id for
132 * a parent node. This is set/unset in the _q_addChild()/_q_removeChild()
133 * functions (and initialized in init() if there is a parent at
134 * construction time).
135 *
136 * Likewise, we only send the node destroyed change, iff we have
137 * previously sent a node created change. This is tracked via the
138 * m_hasBackendNode member.
139 */
140void QNodePrivate::notifyDestructionChangesAndRemoveFromScene()
141{
142 Q_Q(QNode);
143
144 // We notify the backend that the parent lost us as a child
145 if (m_changeArbiter != nullptr && !m_parentId.isNull()) {
146 const auto change = QPropertyNodeRemovedChangePtr::create(m_parentId, q);
147 change->setPropertyName("children");
148 notifyObservers(change);
149 }
150
151 // Tell the backend we are about to be destroyed
152 if (m_hasBackendNode) {
153 const QDestructionIdAndTypeCollector collector(q);
154 const auto destroyedChange = QNodeDestroyedChangePtr::create(q, collector.subtreeIdsAndTypes());
155 notifyObservers(destroyedChange);
156 }
157
158 // We unset the scene from the node as its backend node was/is about to be destroyed
159 QNodeVisitor visitor;
160 visitor.traverse(q, this, &QNodePrivate::unsetSceneHelper);
161}
162
163/*!
164 * \internal
165 *
166 * Sends a QNodeCreatedChange event to the aspects and then also notifies the
167 * parent backend node of its new child. This is called in a deferred manner
168 * by NodePostConstructorInit::processNodes to notify the backend of newly created
169 * nodes with a parent that is already part of the scene.
170 *
171 * Also notify the scene of this node, so it may set it's change arbiter.
172 */
173void QNodePrivate::_q_postConstructorInit()
174{
175 Q_Q(QNode);
176
177 // If we've already done the work then bail out. This can happen if the
178 // user creates a QNode subclass with an explicit parent, then immediately
179 // sets the new QNode as a property on another node. In this case, the
180 // property setter will call this function directly, but as we can't
181 // un-schedule a deferred invocation, this function will be called again
182 // the next time the event loop spins. So, catch this case and abort.
183 if (m_hasBackendNode)
184 return;
185
186 // Check that the parent hasn't been unset since this call was enqueued
187 auto parentNode = q->parentNode();
188 if (!parentNode)
189 return;
190
191 // Set the scene on this node and all children it references so that all
192 // children have a scene set since notifyCreationChanges will set
193 // m_hasBackendNode to true for all children, which would prevent them from
194 // ever having their scene set
195 if (m_scene) {
196 QNodeVisitor visitor;
197 visitor.traverse(q, parentNode->d_func(), &QNodePrivate::setSceneHelper);
198 }
199
200 // Let the backend know we have been added to the scene
201 notifyCreationChange();
202
203 // Let the backend parent know that they have a new child
204 Q_ASSERT(parentNode);
205 QNodePrivate::get(parentNode)->_q_addChild(q);
206}
207
208/*!
209 * \internal
210 *
211 * Called by _q_setParentHelper() or _q_postConstructorInit()
212 * on the main thread.
213 */
214void QNodePrivate::_q_addChild(QNode *childNode)
215{
216 Q_ASSERT(childNode);
217 Q_ASSERT_X(childNode->parent() == q_func(), Q_FUNC_INFO, "not a child of this node");
218
219 // Have we already notified the parent about its new child? If so, bail out
220 // early so that we do not send more than one new child event to the backend
221 QNodePrivate *childD = QNodePrivate::get(childNode);
222 if (childD->m_notifiedParent == true)
223 return;
224
225 // Store our id as the parentId in the child so that even if the child gets
226 // removed from the scene as part of the destruction of the parent, when the
227 // parent's children are deleted in the QObject dtor, we still have access to
228 // the parentId. If we didn't store this, we wouldn't have access at that time
229 // because the parent would then only be a QObject, the QNode part would have
230 // been destroyed already.
231 childD->m_parentId = m_id;
232
233 if (!m_scene)
234 return;
235
236 // We need to send a QPropertyNodeAddedChange to the backend
237 // to notify the backend that we have a new child
238 if (m_changeArbiter != nullptr) {
239 // Flag that we have notified the parent. We do this immediately before
240 // creating the change because that recurses back into this function and
241 // we need to catch that to avoid sending more than one new child event
242 // to the backend.
243 childD->m_notifiedParent = true;
244 const auto change = QPropertyNodeAddedChangePtr::create(m_id, childNode);
245 change->setPropertyName("children");
246 notifyObservers(change);
247 }
248
249 // Update the scene
250 // TODO: Fold this into the QNodeCreatedChangeGenerator so we don't have to
251 // traverse the sub tree three times!
252 QNodeVisitor visitor;
253 visitor.traverse(childNode, this, &QNodePrivate::addEntityComponentToScene);
254}
255
256/*!
257 * \internal
258 *
259 * Called by _q_setParentHelper on the main thread.
260 */
261void QNodePrivate::_q_removeChild(QNode *childNode)
262{
263 Q_ASSERT(childNode);
264 Q_ASSERT_X(childNode->parent() == q_func(), Q_FUNC_INFO, "not a child of this node");
265
266 QNodePrivate::get(childNode)->m_parentId = QNodeId();
267
268 // We notify the backend that we lost a child
269 if (m_changeArbiter != nullptr) {
270 const auto change = QPropertyNodeRemovedChangePtr::create(m_id, childNode);
271 change->setPropertyName("children");
272 notifyObservers(change);
273 }
274}
275
276/*!
277 * \internal
278 *
279 * Reparents the public QNode to \a parent. If the new parent is nullptr then this
280 * QNode is no longer part of the scene and so we notify the backend of its removal
281 * from its parent's list of children, and then send a QNodeDestroyedChange to the
282 * aspects so that the corresponding backend node is destroyed.
283 *
284 * If \a parent is not null, then we must tell its new parent about this QNode now
285 * being a child of it on the backend. If this QNode did not have a parent upon
286 * entry to this function, then we must first send a QNodeCreatedChange to the backend
287 * prior to sending the QPropertyNodeAddedChange to its parent.
288 *
289 * Note: This function should never be called from the ctor directly as the type may
290 * not be fully created yet and creating creation changes involves calling a virtual
291 * function on QNode. The function _q_notifyCreationAndChildChanges() is used
292 * for sending initial notification when a parent is passed to the QNode ctor.
293 * That function does a subset of this function with the assumption that the new object
294 * had no parent before (must be true as it is newly constructed).
295 */
296void QNodePrivate::_q_setParentHelper(QNode *parent)
297{
298 Q_Q(QNode);
299 QNode *oldParentNode = q->parentNode();
300
301 // If we had a parent, we let him know that we are about to change
302 // parent
303 if (oldParentNode && m_hasBackendNode) {
304 QNodePrivate::get(oldParentNode)->_q_removeChild(q);
305
306 // If we have an old parent but the new parent is null or if the new
307 // parent hasn't yet been added to the backend the backend node needs
308 // to be destroyed
309 // e.g:
310 // QEntity *child = new QEntity(some_parent);
311 // After some time, in a later event loop
312 // QEntity *newSubTreeRoot = new QEntity(someGlobalExisitingRoot)
313 // child->setParent(newSubTreeRoot)
314 if (!parent || !QNodePrivate::get(parent)->m_hasBackendNode)
315 notifyDestructionChangesAndRemoveFromScene();
316 }
317
318 // Flag that we need to notify any new parent
319 m_notifiedParent = false;
320
321 // Basically QObject::setParent but for QObjectPrivate
322 QObjectPrivate::setParent_helper(parent);
323
324 if (parent) {
325 // If we had no parent but are about to set one,
326 // we need to send a QNodeCreatedChange
327 QNodePrivate *newParentPrivate = QNodePrivate::get(parent);
328
329 // Set the scene helper / arbiter
330 if (newParentPrivate->m_scene) {
331 QNodeVisitor visitor;
332 visitor.traverse(q, parent->d_func(), &QNodePrivate::setSceneHelper);
333 }
334
335 // We want to make sure that subTreeRoot is always created before
336 // child.
337 // Given a case such as below
338 // QEntity *subTreeRoot = new QEntity(someGlobalExisitingRoot)
339 // QEntity *child = new QEntity();
340 // child->setParent(subTreeRoot)
341 // We need to take into account that subTreeRoot needs to be
342 // created in the backend before the child.
343 // Therefore we only call notifyCreationChanges if the parent
344 // hasn't been created yet as we know that when the parent will be
345 // fully created, it will also send the changes for all of its
346 // children
347
348 if (newParentPrivate->m_hasBackendNode)
349 notifyCreationChange();
350
351 // If we have a valid new parent, we let him know that we are its child
352 QNodePrivate::get(parent)->_q_addChild(q);
353 }
354}
355
356void QNodePrivate::registerNotifiedProperties()
357{
358 Q_Q(QNode);
359 if (m_propertyChangesSetup)
360 return;
361
362 const int offset = QNode::staticMetaObject.propertyOffset();
363 const int count = q->metaObject()->propertyCount();
364
365 for (int index = offset; index < count; index++)
366 m_signals.connectToPropertyChange(q, index);
367
368 m_propertyChangesSetup = true;
369}
370
371void QNodePrivate::unregisterNotifiedProperties()
372{
373 Q_Q(QNode);
374 if (!m_propertyChangesSetup)
375 return;
376
377 const int offset = QNode::staticMetaObject.propertyOffset();
378 const int count = q->metaObject()->propertyCount();
379
380 for (int index = offset; index < count; index++)
381 m_signals.disconnectFromPropertyChange(q, index);
382
383 m_propertyChangesSetup = false;
384}
385
386void QNodePrivate::propertyChanged(int propertyIndex)
387{
388 // Bail out early if we can to avoid the cost below
389 if (m_blockNotifications)
390 return;
391
392 const auto toBackendValue = [](const QVariant &data) -> QVariant
393 {
394 if (data.canConvert<QNode*>()) {
395 QNode *node = data.value<QNode*>();
396
397 // Ensure the node and all ancestors have issued their node creation changes.
398 // We can end up here if a newly created node with a parent is immediately set
399 // as a property on another node. In this case the deferred call to
400 // _q_postConstructorInit() will not have happened yet as the event
401 // loop will still be blocked. We need to do this for all ancestors,
402 // since the subtree of this node otherwise can end up on the backend
403 // with a reference to a non-existent parent.
404 if (node)
405 QNodePrivate::get(node)->_q_ensureBackendNodeCreated();
406
407 const QNodeId id = node ? node->id() : QNodeId();
408 return QVariant::fromValue(id);
409 }
410
411 return data;
412 };
413
414 Q_Q(QNode);
415
416 const QMetaProperty property = q->metaObject()->property(propertyIndex);
417
418 const QVariant data = property.read(q);
419
420 if (data.type() == QVariant::List) {
421 QSequentialIterable iterable = data.value<QSequentialIterable>();
422 QVariantList variants;
423 variants.reserve(iterable.size());
424 for (const auto &v : iterable)
425 variants.append(toBackendValue(v));
426 notifyPropertyChange(property.name(), variants);
427 } else {
428 notifyPropertyChange(property.name(), toBackendValue(data));
429 }
430}
431
432/*!
433 \internal
434 Recursively sets and adds the nodes in the subtree of base node \a root to the scene.
435 Also takes care of connecting Components and Entities together in the scene.
436 */
437void QNodePrivate::setSceneHelper(QNode *root)
438{
439 // Sets the scene
440 root->d_func()->setScene(m_scene);
441 // addObservable sets the QChangeArbiter
442 m_scene->addObservable(root);
443
444 // We also need to handle QEntity <-> QComponent relationships
445 if (QComponent *c = qobject_cast<QComponent *>(root)) {
446 const QVector<QEntity *> entities = c->entities();
447 for (QEntity *entity : entities) {
448 if (!m_scene->hasEntityForComponent(c->id(), entity->id())) {
449 if (!c->isShareable() && !m_scene->entitiesForComponent(c->id()).isEmpty())
450 qWarning() << "Trying to assign a non shareable component to more than one Entity";
451 m_scene->addEntityForComponent(c->id(), entity->id());
452 }
453 }
454 }
455}
456
457/*!
458 \internal
459
460 Recursively unsets and remove nodes in the subtree of base node \a root from
461 the scene. Also takes care of removing Components and Entities connections.
462 */
463void QNodePrivate::unsetSceneHelper(QNode *node)
464{
465 QNodePrivate *nodePrivate = QNodePrivate::get(node);
466
467 // We also need to handle QEntity <-> QComponent relationships removal
468 if (QComponent *c = qobject_cast<QComponent *>(node)) {
469 const QVector<QEntity *> entities = c->entities();
470 for (QEntity *entity : entities) {
471 if (nodePrivate->m_scene)
472 nodePrivate->m_scene->removeEntityForComponent(c->id(), entity->id());
473 }
474 }
475
476 if (nodePrivate->m_scene != nullptr)
477 nodePrivate->m_scene->removeObservable(node);
478 nodePrivate->setScene(nullptr);
479}
480
481/*!
482 \internal
483 */
484void QNodePrivate::addEntityComponentToScene(QNode *root)
485{
486 if (QEntity *e = qobject_cast<QEntity *>(root)) {
487 const auto components = e->components();
488 for (QComponent *c : components) {
489 if (!m_scene->hasEntityForComponent(c->id(), e->id()))
490 m_scene->addEntityForComponent(c->id(), e->id());
491 }
492 }
493}
494
495/*!
496 \internal
497 */
498// Called in the main thread by QScene -> following QEvent::childAdded / addChild
499void QNodePrivate::setArbiter(QLockableObserverInterface *arbiter)
500{
501 if (m_changeArbiter && m_changeArbiter != arbiter)
502 unregisterNotifiedProperties();
503 m_changeArbiter = static_cast<QAbstractArbiter *>(arbiter);
504 if (m_changeArbiter)
505 registerNotifiedProperties();
506}
507
508/*!
509 * \internal
510 * Makes sure this node has a backend by traversing the tree up to the most distant ancestor
511 * without a backend node and initializing that node. This is done to make sure the parent nodes
512 * are always created before the child nodes, since child nodes reference parent nodes at creation
513 * time.
514 */
515void QNodePrivate::_q_ensureBackendNodeCreated()
516{
517 if (m_hasBackendNode)
518 return;
519
520 Q_Q(QNode);
521
522 QNode *nextNode = q;
523 QNode *topNodeWithoutBackend = nullptr;
524 while (nextNode != nullptr && !QNodePrivate::get(nextNode)->m_hasBackendNode) {
525 topNodeWithoutBackend = nextNode;
526 nextNode = nextNode->parentNode();
527 }
528 QNodePrivate::get(topNodeWithoutBackend)->_q_postConstructorInit();
529}
530
531/*!
532 \class Qt3DCore::QNode
533 \inherits QObject
534
535 \inmodule Qt3DCore
536 \since 5.5
537
538 \brief QNode is the base class of all Qt3D node classes used to build a
539 Qt3D scene.
540
541 The owernship of QNode is determined by the QObject parent/child
542 relationship between nodes. By itself, a QNode has no visual appearance
543 and no particular meaning, it is there as a way of building a node based tree
544 structure.
545
546 The parent of a QNode instance can only be another QNode instance.
547
548 Each QNode instance has a unique id that allows it to be recognizable
549 from other instances.
550
551 When properties are defined on a QNode subclass, their NOTIFY signal
552 will automatically generate notifications that the Qt3D backend aspects will
553 receive.
554
555 \sa QEntity, QComponent
556*/
557
558/*!
559 * Sends the \a change QSceneChangePtr to any QBackendNodes in the registered
560 * aspects that correspond to this QNode.
561 *
562 * For the common case of a QObject property change, QNode handles this for you
563 * automatically by sending a QPropertyUpdatedChange event to the backend nodes.
564 * You only need to call this function if you wish to send a specific type of
565 * change in place of the automatic handling.
566 */
567void QNode::notifyObservers(const QSceneChangePtr &change)
568{
569 Q_D(QNode);
570 d->notifyObservers(change);
571}
572
573/*!
574 Called when one or more backend aspects sends a notification \a change to the
575 current Qt3DCore::QNode instance.
576
577 \note This method should be reimplemented in your subclasses to properly
578 handle the \a change.
579*/
580void QNode::sceneChangeEvent(const QSceneChangePtr &change)
581{
582 Q_UNUSED(change);
583 if (change->type() == Qt3DCore::PropertyUpdated) {
584 // TODO: Do this more efficiently. We could pass the metaobject and property
585 // index to the animation aspect via the QChannelMapping. This would
586 // allow us to avoid the propertyIndex lookup here by sending them in
587 // a new subclass of QPropertyUpdateChange.
588 // Try to find property and call setter
589 auto e = qSharedPointerCast<Qt3DCore::QPropertyUpdatedChange>(change);
590 const QMetaObject *mo = metaObject();
591 const int propertyIndex = mo->indexOfProperty(e->propertyName());
592 QMetaProperty mp = mo->property(propertyIndex);
593 bool wasBlocked = blockNotifications(true);
594 mp.write(this, e->value());
595 blockNotifications(wasBlocked);
596 } else {
597 // Nothing is handling this change, warn the user.
598 qWarning() << Q_FUNC_INFO << "sceneChangeEvent should have been subclassed";
599 }
600}
601
602/*!
603 \internal
604 */
605void QNodePrivate::setScene(QScene *scene)
606{
607 if (m_scene != scene) {
608 if (m_scene != nullptr)
609 m_scene->removePropertyTrackDataForNode(m_id);
610 m_scene = scene;
611 // set PropertyTrackData in the scene
612 updatePropertyTrackMode();
613 }
614}
615
616/*!
617 \internal
618 */
619QScene *QNodePrivate::scene() const
620{
621 return m_scene;
622}
623
624/*!
625 \internal
626 */
627void QNodePrivate::notifyPropertyChange(const char *name, const QVariant &value)
628{
629 // Bail out early if we can to avoid operator new
630 if (m_blockNotifications)
631 return;
632
633 auto e = QPropertyUpdatedChangePtr::create(m_id);
634 e->setPropertyName(name);
635 e->setValue(value);
636 notifyObservers(e);
637}
638
639void QNodePrivate::notifyDynamicPropertyChange(const QByteArray &name, const QVariant &value)
640{
641 // Bail out early if we can to avoid operator new
642 if (m_blockNotifications)
643 return;
644
645 auto e = QDynamicPropertyUpdatedChangePtr::create(m_id);
646 e->setPropertyName(name);
647 e->setValue(value);
648 notifyObservers(e);
649}
650
651/*!
652 \internal
653 */
654// Called by the main thread
655void QNodePrivate::notifyObservers(const QSceneChangePtr &change)
656{
657 Q_ASSERT(change);
658
659 // Don't send notifications if we are blocking
660 if (m_blockNotifications && change->type() == PropertyUpdated)
661 return;
662
663 if (m_changeArbiter != nullptr) {
664 QAbstractPostman *postman = m_changeArbiter->postman();
665 if (postman != nullptr)
666 postman->notifyBackend(change);
667 }
668}
669
670// Inserts this tree into the main Scene tree.
671// Needed when SceneLoaders provide a cloned tree from the backend
672// and need to insert it in the main scene tree
673// QNode *root;
674// QNode *subtree;
675// QNodePrivate::get(root)->insertTree(subtree);
676
677/*!
678 \internal
679 */
680void QNodePrivate::insertTree(QNode *treeRoot, int depth)
681{
682 if (m_scene != nullptr) {
683 treeRoot->d_func()->setScene(m_scene);
684 m_scene->addObservable(treeRoot);
685 }
686
687 for (QObject *c : treeRoot->children()) {
688 QNode *n = nullptr;
689 if ((n = qobject_cast<QNode *>(c)) != nullptr)
690 insertTree(n, depth + 1);
691 }
692
693 if (depth == 0)
694 treeRoot->setParent(q_func());
695}
696
697void QNodePrivate::updatePropertyTrackMode()
698{
699 if (m_scene != nullptr) {
700 QScene::NodePropertyTrackData trackData;
701 trackData.defaultTrackMode = m_defaultPropertyTrackMode;
702 trackData.trackedPropertiesOverrides = m_trackedPropertiesOverrides;
703 m_scene->setPropertyTrackDataForNode(m_id, trackData);
704 }
705}
706
707/*!
708 \internal
709 */
710QNodePrivate *QNodePrivate::get(QNode *q)
711{
712 return q->d_func();
713}
714
715/*!
716 \internal
717 */
718void QNodePrivate::nodePtrDeleter(QNode *q)
719{
720 QObject *p = q->parent();
721 if (p == nullptr)
722 p = q;
723 p->deleteLater();
724}
725
726/*!
727 \fn Qt3DCore::QNodeId Qt3DCore::qIdForNode(Qt3DCore::QNode *node)
728 \relates Qt3DCore::QNode
729 \return node id for \a node.
730*/
731
732/*!
733 \fn template<typename T> Qt3DCore::QNodeIdVector Qt3DCore::qIdsForNodes(const T &nodes)
734 \relates Qt3DCore::QNode
735 \return vector of node ids for \a nodes.
736*/
737
738/*!
739 \fn void Qt3DCore::QNodeCommand::setReplyToCommandId(CommandId id)
740
741 Sets the command \a id to which the message is a reply.
742
743*/
744/*!
745 \fn Qt3DCore::QNode::PropertyTrackingMode Qt3DCore::QNode::defaultPropertyTrackingMode() const
746
747 Returns the default property tracking mode which determines whether a
748 QNode should be listening for property updates.
749
750*/
751/*!
752 \fn Qt3DCore::QNode::clearPropertyTracking(const QString &propertyName)
753
754 Clears the tracking property called \a propertyName.
755*/
756/*!
757 \fn Qt3DCore::QNode::PropertyTrackingMode Qt3DCore::QNode::propertyTracking(const QString &propertyName) const
758
759 Returns the tracking mode of \a propertyName.
760*/
761
762/*!
763 \fn Qt3DCore::QNode::setPropertyTracking(const QString &propertyName, Qt3DCore::QNode::PropertyTrackingMode trackMode)
764
765 Sets the property tracking for \a propertyName and \a trackMode.
766*/
767
768/*!
769 Creates a new QNode instance with parent \a parent.
770
771 \note The backend aspects will be notified that a QNode instance is
772 part of the scene only if it has a parent; unless this is the root node of
773 the Qt3D scene.
774
775 \sa setParent()
776*/
777QNode::QNode(QNode *parent)
778 : QNode(*new QNodePrivate, parent) {}
779
780/*! \internal */
781QNode::QNode(QNodePrivate &dd, QNode *parent)
782 : QObject(dd, parent)
783{
784 Q_D(QNode);
785 d->init(parent);
786}
787
788/*!
789 \fn Qt3DCore::QNode::nodeDestroyed()
790 Emitted when the node is destroyed.
791*/
792
793/*! \internal */
794QNode::~QNode()
795{
796 Q_D(QNode);
797 // Disconnect each connection that was stored
798 for (auto it = d->m_destructionConnections.begin(), end = d->m_destructionConnections.end(); it != end; ++it)
799 QObject::disconnect(it.value());
800 d->m_destructionConnections.clear();
801
802 Q_EMIT nodeDestroyed();
803
804 // Notify the backend that the parent lost this node as a child and
805 // that this node is being destroyed.
806 d->notifyDestructionChangesAndRemoveFromScene();
807}
808
809/*!
810 Returns the id that uniquely identifies the QNode instance.
811*/
812QNodeId QNode::id() const
813{
814 Q_D(const QNode);
815 return d->m_id;
816}
817
818/*!
819 \property Qt3DCore::QNode::parent
820
821 Holds the immediate QNode parent, or null if the node has no parent.
822
823 Setting the parent will notify the backend aspects about current QNode
824 instance's parent change.
825
826 \note if \a parent happens to be null, this will actually notify that the
827 current QNode instance was removed from the scene.
828*/
829QNode *QNode::parentNode() const
830{
831 return qobject_cast<QNode*>(parent());
832}
833
834/*!
835 Returns \c true if aspect notifications are blocked; otherwise returns \c false.
836 By default, notifications are \e not blocked.
837
838 \sa blockNotifications()
839*/
840bool QNode::notificationsBlocked() const
841{
842 Q_D(const QNode);
843 return d->m_blockNotifications;
844}
845
846/*!
847 If \a block is \c true, property change notifications sent by this object
848 to aspects are blocked. If \a block is \c false, no such blocking will occur.
849
850 The return value is the previous value of notificationsBlocked().
851
852 Note that the other notification types will be sent even if the
853 notifications for this object have been blocked.
854
855 \sa notificationsBlocked()
856*/
857bool QNode::blockNotifications(bool block)
858{
859 Q_D(QNode);
860 bool previous = d->m_blockNotifications;
861 d->m_blockNotifications = block;
862 return previous;
863}
864
865// Note: should never be called from the ctor directly as the type may not be fully
866// created yet
867void QNode::setParent(QNode *parent)
868{
869 Q_D(QNode);
870
871 // If we already have a parent don't do anything. Be careful to ensure
872 // that QNode knows about the parent, not just QObject (by checking the ids)
873 if (parentNode() == parent &&
874 ((parent != nullptr && d->m_parentId == parentNode()->id()) || parent == nullptr))
875 return;
876
877 // remove ourself from postConstructorInit queue. The call to _q_setParentHelper
878 // will take care of creating the backend node if necessary depending on new parent.
879 if (d->m_scene)
880 d->m_scene->postConstructorInit()->removeNode(this);
881
882 d->_q_setParentHelper(parent);
883
884 // Block notifications as we want to let the _q_setParentHelper
885 // manually handle them
886 const bool blocked = blockNotifications(true);
887 emit parentChanged(parent);
888 blockNotifications(blocked);
889}
890
891/*!
892 \typedef Qt3DCore::QNodePtr
893 \relates Qt3DCore::QNode
894
895 A shared pointer for QNode.
896*/
897/*!
898 \typedef Qt3DCore::QNodeVector
899 \relates Qt3DCore::QNode
900
901 List of QNode pointers.
902*/
903
904/*!
905 * Returns a list filled with the QNode children of the current
906 * QNode instance.
907 */
908QNodeVector QNode::childNodes() const
909{
910 QNodeVector nodeChildrenList;
911 const QObjectList &objectChildrenList = QObject::children();
912 nodeChildrenList.reserve(objectChildrenList.size());
913
914 for (QObject *c : objectChildrenList) {
915 if (QNode *n = qobject_cast<QNode *>(c))
916 nodeChildrenList.push_back(n);
917 }
918
919 return nodeChildrenList;
920}
921void QNode::setEnabled(bool isEnabled)
922{
923 Q_D(QNode);
924
925 if (d->m_enabled == isEnabled)
926 return;
927
928 d->m_enabled = isEnabled;
929 emit enabledChanged(isEnabled);
930}
931
932void QNode::setDefaultPropertyTrackingMode(QNode::PropertyTrackingMode mode)
933{
934 Q_D(QNode);
935 if (d->m_defaultPropertyTrackMode == mode)
936 return;
937
938 d->m_defaultPropertyTrackMode = mode;
939 // The backend doesn't care about such notification
940 const bool blocked = blockNotifications(true);
941 emit defaultPropertyTrackingModeChanged(mode);
942 blockNotifications(blocked);
943 d->updatePropertyTrackMode();
944}
945
946/*!
947 \property Qt3DCore::QNode::enabled
948
949 Holds the QNode enabled flag.
950 By default a QNode is always enabled.
951
952 \note the interpretation of what enabled means is aspect-dependent. Even if
953 enabled is set to \c false, some aspects may still consider the node in
954 some manner. This is documented on a class by class basis.
955*/
956bool QNode::isEnabled() const
957{
958 Q_D(const QNode);
959 return d->m_enabled;
960}
961
962/*!
963 \property Qt3DCore::QNode::defaultPropertyTrackingMode
964
965 Holds the default property tracking mode which determines whether a QNode should
966 be listening for property updates. This only applies to properties which
967 haven't been overridden by a call to setPropertyTracking.
968
969 By default it is set to QNode::TrackFinalValues
970*/
971QNode::PropertyTrackingMode QNode::defaultPropertyTrackingMode() const
972{
973 Q_D(const QNode);
974 return d->m_defaultPropertyTrackMode;
975}
976
977void QNode::setPropertyTracking(const QString &propertyName, QNode::PropertyTrackingMode trackMode)
978{
979 Q_D(QNode);
980 d->m_trackedPropertiesOverrides.insert(propertyName, trackMode);
981 d->updatePropertyTrackMode();
982}
983
984QNode::PropertyTrackingMode QNode::propertyTracking(const QString &propertyName) const
985{
986 Q_D(const QNode);
987 return d->m_trackedPropertiesOverrides.value(propertyName, d->m_defaultPropertyTrackMode);
988}
989
990void QNode::clearPropertyTracking(const QString &propertyName)
991{
992 Q_D(QNode);
993 d->m_trackedPropertiesOverrides.remove(propertyName);
994 d->updatePropertyTrackMode();
995}
996
997void QNode::clearPropertyTrackings()
998{
999 Q_D(QNode);
1000 d->m_trackedPropertiesOverrides.clear();
1001 d->updatePropertyTrackMode();
1002}
1003
1004QNodeCreatedChangeBasePtr QNode::createNodeCreationChange() const
1005{
1006 // Uncomment this when implementing new frontend and backend types.
1007 // Any classes that don't override this function will be noticeable here.
1008 // Note that some classes actually don't need to override as they have
1009 // no additional data to send. In those cases this default implementation
1010 // is perfectly fine.
1011 // const QMetaObject *mo = metaObject();
1012 // qDebug() << Q_FUNC_INFO << mo->className();
1013 return QNodeCreatedChangeBasePtr::create(this);
1014}
1015
1016/*!
1017 \fn Qt3DCore::QNodeCommand::CommandId Qt3DCore::QNodeCommand::inReplyTo() const
1018
1019 Returns the id of the original QNodeCommand message that
1020 was sent to the backend.
1021
1022*/
1023/*!
1024 \fn void Qt3DCore::QNodeCommand::setData(const QVariant &data)
1025
1026 Sets the data (\a data) in the backend node to perform
1027 the operations requested.
1028*/
1029/*!
1030 \fn void Qt3DCore::QNodeCommand::setName(const QString &name)
1031
1032
1033 Sets the data (\a name) in the backend node to perform
1034 the operations requested.
1035*/
1036
1037/*!
1038 \enum Qt3DCore::QNode::PropertyTrackingMode
1039
1040 Indicates how a QNode listens for property updates.
1041
1042 \value TrackFinalValues
1043 Tracks final values
1044 \value DontTrackValues
1045 Does not track values
1046 \value TrackAllValues
1047 Tracks all values
1048*/
1049/*!
1050 \fn Qt3DCore::QNode::clearPropertyTrackings()
1051
1052 Erases all values that have been saved by the property tracking.
1053*/
1054/*!
1055 * \brief Sends a command message to the backend node
1056 *
1057 * Creates a QNodeCommand message and dispatches it to the backend node. The
1058 * command is given and a \a name and some \a data which can be used in the
1059 * backend node to perform various operations.
1060 * This returns a CommandId which can be used to identify the initial command
1061 * when receiving a message in reply. If the command message is to be sent in
1062 * reply to another command, \a replyTo contains the id of that command.
1063 *
1064 * \sa QNodeCommand, QNode::sendReply
1065 */
1066QNodeCommand::CommandId QNode::sendCommand(const QString &name,
1067 const QVariant &data,
1068 QNodeCommand::CommandId replyTo)
1069{
1070 Q_D(QNode);
1071
1072 // Bail out early, if we can, to avoid operator new
1073 if (d->m_blockNotifications)
1074 return QNodeCommand::CommandId(0);
1075
1076 auto e = QNodeCommandPtr::create(d->m_id);
1077 e->setName(name);
1078 e->setData(data);
1079 e->setReplyToCommandId(replyTo);
1080 d->notifyObservers(e);
1081 return e->commandId();
1082}
1083
1084/*!
1085 * \brief Send a \a command back to the backend node.
1086 *
1087 * Assumes the command is to be to sent back in reply to itself to the backend node.
1088 *
1089 * \sa QNodeCommand, QNode::sendCommand
1090 */
1091void QNode::sendReply(const QNodeCommandPtr &command)
1092{
1093 Q_D(QNode);
1094 command->setDeliveryFlags(QSceneChange::BackendNodes);
1095 d->notifyObservers(command);
1096}
1097
1098
1099namespace {
1100
1101/*! \internal */
1102inline const QMetaObjectPrivate *priv(const uint* data)
1103{
1104 return reinterpret_cast<const QMetaObjectPrivate*>(data);
1105}
1106
1107/*! \internal */
1108inline bool isDynamicMetaObject(const QMetaObject *mo)
1109{
1110 return (priv(mo->d.data)->flags & DynamicMetaObject);
1111}
1112
1113} // anonymous
1114
1115/*!
1116 * \internal
1117 *
1118 * Find the most derived metaobject that doesn't have a dynamic
1119 * metaobject farther up the chain.
1120 * TODO: Add support to QMetaObject to explicitly say if it's a dynamic
1121 * or static metaobject so we don't need this logic
1122 */
1123const QMetaObject *QNodePrivate::findStaticMetaObject(const QMetaObject *metaObject)
1124{
1125 const QMetaObject *lastStaticMetaobject = nullptr;
1126 auto mo = metaObject;
1127 while (mo) {
1128 const bool dynamicMetaObject = isDynamicMetaObject(mo);
1129 if (dynamicMetaObject)
1130 lastStaticMetaobject = nullptr;
1131
1132 if (!dynamicMetaObject && !lastStaticMetaobject)
1133 lastStaticMetaobject = mo;
1134
1135 mo = mo->superClass();
1136 }
1137 Q_ASSERT(lastStaticMetaobject);
1138 return lastStaticMetaobject;
1139}
1140
1141/*!
1142 * \internal
1143 *
1144 * NodePostConstructorInit handles calling QNode::_q_postConstructorInit for
1145 * all nodes. By keeping track of nodes that need initialization we can
1146 * create them all together ensuring they get sent to the backend in a single
1147 * batch.
1148 */
1149NodePostConstructorInit::NodePostConstructorInit(QObject *parent)
1150 : QObject(parent)
1151 , m_requestedProcessing(false)
1152{
1153}
1154
1155NodePostConstructorInit::~NodePostConstructorInit() {}
1156
1157/*!
1158 * \internal
1159 *
1160 * Add a node to the list of nodes needing a call to _q_postConstructorInit
1161 * We only add the node if it does not have an ancestor already in the queue
1162 * because initializing the ancestor will initialize all it's children.
1163 * This ensures that all backend nodes are created from the top-down, with
1164 * all parents created before their children
1165 *
1166 */
1167void NodePostConstructorInit::addNode(QNode *node)
1168{
1169 Q_ASSERT(node);
1170 QNode *nextNode = node;
1171 while (nextNode != nullptr && !m_nodesToConstruct.contains(QNodePrivate::get(nextNode)))
1172 nextNode = nextNode->parentNode();
1173
1174 if (!nextNode) {
1175 m_nodesToConstruct.append(QNodePrivate::get(node));
1176 if (!m_requestedProcessing){
1177 QMetaObject::invokeMethod(this, "processNodes", Qt::QueuedConnection);
1178 m_requestedProcessing = true;
1179 }
1180 }
1181}
1182
1183/*!
1184 * \internal
1185 *
1186 * Remove a node from the queue. This will ensure none of its
1187 * children get initialized
1188 */
1189void NodePostConstructorInit::removeNode(QNode *node)
1190{
1191 Q_ASSERT(node);
1192 m_nodesToConstruct.removeAll(QNodePrivate::get(node));
1193}
1194
1195/*!
1196 * \internal
1197 *
1198 * call _q_postConstructorInit for all nodes in the queue
1199 * and clear the queue
1200 */
1201void NodePostConstructorInit::processNodes()
1202{
1203 m_requestedProcessing = false;
1204 while (!m_nodesToConstruct.empty()) {
1205 auto node = m_nodesToConstruct.takeFirst();
1206 node->_q_postConstructorInit();
1207 }
1208}
1209
1210} // namespace Qt3DCore
1211
1212QT_END_NAMESPACE
1213
1214#include "moc_qnode.cpp"
1215