summaryrefslogtreecommitdiffstats
path: root/src/core/aspects/qaspectmanager.cpp
blob: 98fb982df81b415d3859567f393eccfc2e8282cc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
/****************************************************************************
**
** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB).
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt3D module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qaspectmanager_p.h"
#include "qabstractaspect.h"
#include "qabstractaspect_p.h"
#include "qchangearbiter_p.h"
// TODO Make the kind of job manager configurable (e.g. ThreadWeaver vs Intel TBB)
#include "qaspectjobmanager_p.h"
#include "qabstractaspectjobmanager_p.h"
#include "qentity.h"

#include <Qt3DCore/private/qservicelocator_p.h>

#include <Qt3DCore/private/qaspectjob_p.h>
#include <Qt3DCore/private/qthreadpooler_p.h>
#include <Qt3DCore/private/qtickclockservice_p.h>
#include <Qt3DCore/private/corelogging_p.h>
#include <Qt3DCore/private/qscheduler_p.h>
#include <Qt3DCore/private/qtickclock_p.h>
#include <Qt3DCore/private/qabstractframeadvanceservice_p.h>
#include <QEventLoop>
#include <QThread>
#include <QWaitCondition>
#include <QSurface>

#if defined(QT3D_CORE_JOB_TIMING)
#include <QElapsedTimer>
#endif

QT_BEGIN_NAMESPACE

namespace Qt3DCore {

QAspectManager::QAspectManager(QObject *parent)
    : QObject(parent)
    , m_root(nullptr)
    , m_scheduler(new QScheduler(this))
    , m_jobManager(new QAspectJobManager(this))
    , m_changeArbiter(new QChangeArbiter(this))
    , m_serviceLocator(new QServiceLocator())
    , m_waitForEndOfSimulationLoop(0)
    , m_waitForStartOfSimulationLoop(0)
    , m_waitForEndOfExecLoop(0)
    , m_waitForQuit(0)
{
    qRegisterMetaType<QSurface *>("QSurface*");
    m_runSimulationLoop.fetchAndStoreOrdered(0);
    m_runMainLoop.fetchAndStoreOrdered(1);
    qCDebug(Aspects) << Q_FUNC_INFO;
}

QAspectManager::~QAspectManager()
{
    delete m_changeArbiter;
    delete m_jobManager;
    delete m_scheduler;
}

// Main thread (called by QAspectEngine)
void QAspectManager::enterSimulationLoop()
{
    qCDebug(Aspects) << Q_FUNC_INFO;
    m_runSimulationLoop.fetchAndStoreOrdered(1);

    // We wait for the setRootEntity on the aspectManager to have completed
    // This ensures we cannot shutdown before the aspects have had a chance
    // to be initialized
    m_waitForStartOfSimulationLoop.acquire(1);
}

// Main thread (called by QAspectEngine)
void QAspectManager::exitSimulationLoop()
{
    qCDebug(Aspects) << Q_FUNC_INFO;

    // If this fails, simulation loop is already exited so nothing to do
    if (!m_runSimulationLoop.testAndSetOrdered(1, 0)) {
        qCDebug(Aspects) << "Simulation loop was not running. Nothing to do";
        return;
    }

    QAbstractFrameAdvanceService *frameAdvanceService =
            m_serviceLocator->service<QAbstractFrameAdvanceService>(QServiceLocator::FrameAdvanceService);
    if (frameAdvanceService)
        frameAdvanceService->stop();

    // Give any aspects a chance to unqueue any asynchronous work they
    // may have scheduled that would otherwise potentially deadlock or
    // cause races. For example, the QLogicAspect queues up a vector of
    // QNodeIds to be processed by a callback on the main thread. However,
    // if we don't unqueue this work and release its semaphore, the logic
    // aspect would cause a deadlock when trying to exit the inner loop.
    // This is because we call this function from the main thread and the
    // logic aspect is waiting for the main thread to execute the
    // QLogicComponent::onFrameUpdate() callback.
    for (QAbstractAspect *aspect : qAsConst(m_aspects))
        aspect->d_func()->onEngineAboutToShutdown();


    qCDebug(Aspects) << "exitSimulationLoop waiting for exec loop to terminate";
    // Wait until the simulation loop is fully exited and the aspects are done
    // processing any final changes and have had onEngineShutdown() called on them
    m_waitForEndOfSimulationLoop.acquire(1);
    qCDebug(Aspects) << "exitSimulationLoop completed";
}

bool QAspectManager::isShuttingDown() const
{
    return !m_runSimulationLoop.load();
}

/*!
    \internal

    Called by the QAspectThread's run() method immediately after the manager
    has been created
*/
void QAspectManager::initialize()
{
    qCDebug(Aspects) << Q_FUNC_INFO;
    m_jobManager->initialize();
    m_scheduler->setAspectManager(this);
    m_changeArbiter->initialize(m_jobManager);
}

/*!
    \internal

    Called by the QAspectThread's run() method immediately after the manager's
    exec() function has returned.
*/
void QAspectManager::shutdown()
{
    qCDebug(Aspects) << Q_FUNC_INFO;

    for (QAbstractAspect *aspect : qAsConst(m_aspects))
        m_changeArbiter->unregisterSceneObserver(aspect->d_func());

    // Aspects must be deleted in the Thread they were created in
}

// QAspectThread:: queued invoked by QAspectEngine::setRootEntity
void QAspectManager::setRootEntity(Qt3DCore::QEntity *root, const QVector<Qt3DCore::QNodeCreatedChangeBasePtr> &changes)
{
    qCDebug(Aspects) << Q_FUNC_INFO;

    if (root == m_root)
        return;

    if (m_root) {
        // TODO: Delete all backend nodes. This is to be symmetric with how
        // we create them below in the call to setRootAndCreateNodes
    }

    m_root = root;

    if (m_root) {
        for (QAbstractAspect *aspect : qAsConst(m_aspects))
            aspect->d_func()->setRootAndCreateNodes(m_root, changes);
    }
}

/*!
 * Registers a new \a aspect.
 */
void QAspectManager::registerAspect(QAbstractAspect *aspect)
{
    qCDebug(Aspects) << "Registering aspect";

    if (aspect != nullptr) {
        m_aspects.append(aspect);
        QAbstractAspectPrivate::get(aspect)->m_aspectManager = this;
        QAbstractAspectPrivate::get(aspect)->m_jobManager = m_jobManager;
        QAbstractAspectPrivate::get(aspect)->m_arbiter = m_changeArbiter;
        // Register sceneObserver with the QChangeArbiter
        m_changeArbiter->registerSceneObserver(aspect->d_func());

        // Allow the aspect to do some work now that it is registered
        aspect->onRegistered();
    }
    else {
        qCWarning(Aspects) << "Failed to register aspect";
    }
    qCDebug(Aspects) << "Completed registering aspect";
}

/*!
 * \internal
 *
 * Calls QAbstractAspect::onUnregistered(), unregisters the aspect from the
 * change arbiter and unsets the arbiter, job manager and aspect manager.
 * Operations are performed in the reverse order to registerAspect.
 */
void QAspectManager::unregisterAspect(Qt3DCore::QAbstractAspect *aspect)
{
    qCDebug(Aspects) << "Unregistering aspect";
    Q_ASSERT(aspect);
    aspect->onUnregistered();
    m_changeArbiter->unregisterSceneObserver(aspect->d_func());
    QAbstractAspectPrivate::get(aspect)->m_arbiter = nullptr;
    QAbstractAspectPrivate::get(aspect)->m_jobManager = nullptr;
    QAbstractAspectPrivate::get(aspect)->m_aspectManager = nullptr;
    m_aspects.removeOne(aspect);
    qCDebug(Aspects) << "Completed unregistering aspect";
}

void QAspectManager::exec()
{
    // Gentlemen, start your engines
    QEventLoop eventLoop;

    // Enter the engine loop
    qCDebug(Aspects) << Q_FUNC_INFO << "***** Entering main loop *****";
    while (m_runMainLoop.load()) {
        // Process any pending events, waiting for more to arrive if queue is empty
        eventLoop.processEvents(QEventLoop::AllEvents, 16);

        // Retrieve the frame advance service. Defaults to timer based if there is no renderer.
        QAbstractFrameAdvanceService *frameAdvanceService =
                m_serviceLocator->service<QAbstractFrameAdvanceService>(QServiceLocator::FrameAdvanceService);

        // Start the frameAdvanceService if we're about to enter the simulation loop
        bool needsShutdown = false;
        if (m_runSimulationLoop.load()) {
            needsShutdown = true;
            frameAdvanceService->start();

            // We are about to enter the simulation loop. Give aspects a chance to do any last
            // pieces of initialization
            qCDebug(Aspects) << "Calling onEngineStartup() for each aspect";
            for (QAbstractAspect *aspect : qAsConst(m_aspects)) {
                qCDebug(Aspects) << "\t" << aspect->objectName();
                aspect->onEngineStartup();
            }
            qCDebug(Aspects) << "Done calling onEngineStartup() for each aspect";
            m_waitForStartOfSimulationLoop.release(1);
        } else {
            continue;
            // Ensure we won't enter the simulation loop (in case the atomic was changed between
            // the last time we read it) without having performed the initialization first
        }

        // Only enter main simulation loop once the renderer and other aspects are initialized
        while (m_runSimulationLoop.load()) {
            qint64 t = frameAdvanceService->waitForNextFrame();

            // Distribute accumulated changes. This includes changes sent from the frontend
            // to the backend nodes. We call this before the call to m_scheduler->update() to ensure
            // that any property changes do not set dirty flags in a data race with the renderer's
            // submission thread which may be looking for dirty flags, acting upon them and then
            // clearing the dirty flags.
            //
            // Doing this as the first call in the new frame ensures the lock free approach works
            // without any such data race.
#ifdef QT3D_JOBS_RUN_STATS
            const quint32 arbiterId = 4096;
            JobRunStats changeArbiterStats;
            changeArbiterStats.jobId.typeAndInstance[0] = arbiterId;
            changeArbiterStats.jobId.typeAndInstance[1] = 0;
            changeArbiterStats.threadId = reinterpret_cast<quint64>(QThread::currentThreadId());
            changeArbiterStats.startTime = QThreadPooler::m_jobsStatTimer.nsecsElapsed();
#endif
            m_changeArbiter->syncChanges();
#ifdef QT3D_JOBS_RUN_STATS
            changeArbiterStats.endTime = QThreadPooler::m_jobsStatTimer.nsecsElapsed();
            QThreadPooler::addJobLogStatsEntry(changeArbiterStats);
#endif

            // For each Aspect
            // Ask them to launch set of jobs for the current frame
            // Updates matrices, bounding volumes, render bins ...
#if defined(QT3D_CORE_JOB_TIMING)
            QElapsedTimer timer;
            timer.start();
#endif
            m_scheduler->scheduleAndWaitForFrameAspectJobs(t);
#if defined(QT3D_CORE_JOB_TIMING)
            qDebug() << "Jobs took" << timer.nsecsElapsed() / 1.0e6;
#endif

            // Process any pending events
            eventLoop.processEvents();
        } // End of simulation loop

        if (needsShutdown) {
            // Process any pending changes from the frontend before we shut the aspects down
            m_changeArbiter->syncChanges();

            // Give aspects a chance to perform any shutdown actions. This may include unqueuing
            // any blocking work on the main thread that could potentially deadlock during shutdown.
            qCDebug(Aspects) << "Calling onEngineShutdown() for each aspect";
            for (QAbstractAspect *aspect : qAsConst(m_aspects)) {
                qCDebug(Aspects) << "\t" << aspect->objectName();
                aspect->onEngineShutdown();
            }
            qCDebug(Aspects) << "Done calling onEngineShutdown() for each aspect";

            // Wake up the main thread which is waiting for us inside of exitSimulationLoop()
            m_waitForEndOfSimulationLoop.release(1);
        }
    } // End of main loop
    qCDebug(Aspects) << Q_FUNC_INFO << "***** Exited main loop *****";

    m_waitForEndOfExecLoop.release(1);
    m_waitForQuit.acquire(1);
}

void QAspectManager::quit()
{
    qCDebug(Aspects) << Q_FUNC_INFO;

    Q_ASSERT_X(m_runSimulationLoop.load() == 0, "QAspectManagr::quit()", "Inner loop is still running");
    m_runMainLoop.fetchAndStoreOrdered(0);

    // We need to wait for the QAspectManager exec loop to terminate
    m_waitForEndOfExecLoop.acquire(1);
    m_waitForQuit.release(1);

    qCDebug(Aspects) << Q_FUNC_INFO << "Exiting";
}

const QVector<QAbstractAspect *> &QAspectManager::aspects() const
{
    return m_aspects;
}

QAbstractAspectJobManager *QAspectManager::jobManager() const
{
    return m_jobManager;
}

QChangeArbiter *QAspectManager::changeArbiter() const
{
    return m_changeArbiter;
}

QServiceLocator *QAspectManager::serviceLocator() const
{
    return m_serviceLocator.data();
}

} // namespace Qt3DCore

QT_END_NAMESPACE