Qt 6.x
The Qt SDK
Loading...
Searching...
No Matches
qsgcontext.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
4#include <QtQuick/private/qsgcontext_p.h>
5#include <QtQuick/private/qsgtexture_p.h>
6#include <QtQuick/private/qsgrenderer_p.h>
7#include <QtQuick/private/qquickpixmapcache_p.h>
8#include <QtQuick/private/qsgadaptationlayer_p.h>
9
10#include <QGuiApplication>
11#include <QScreen>
12#include <QQuickWindow>
13
14#include <private/qqmlglobal_p.h>
15
16#include <QtQuick/private/qsgtexture_p.h>
17#include <QtGui/private/qguiapplication_p.h>
18#include <QtCore/private/qabstractanimation_p.h>
19
20#include <private/qobject_p.h>
21#include <qmutex.h>
22
23/*
24 Comments about this class from Gunnar:
25
26 The QSGContext class is right now two things.. The first is the
27 adaptation layer and central storage ground for all the things
28 in the scene graph, like textures and materials. This part really
29 belongs inside the scene graph coreapi.
30
31 The other part is the QML adaptation classes, like how to implement
32 rectangle nodes. This is not part of the scene graph core API, but
33 more part of the QML adaptation of scene graph.
34
35 If we ever move the scene graph core API into its own thing, this class
36 needs to be split in two. Right now its one because we're lazy when it comes
37 to defining plugin interfaces..
38*/
39
41
42// Used for very high-level info about the renderering and gl context
43// Includes GL_VERSION, type of render loop, atlas size, etc.
44Q_LOGGING_CATEGORY(QSG_LOG_INFO, "qt.scenegraph.general")
45
46// Used to debug the renderloop logic. Primarily useful for platform integrators
47// and when investigating the render loop logic.
48Q_LOGGING_CATEGORY(QSG_LOG_RENDERLOOP, "qt.scenegraph.renderloop")
49
50
51// GLSL shader compilation
52Q_LOGGING_CATEGORY(QSG_LOG_TIME_COMPILATION, "qt.scenegraph.time.compilation")
53
54// polish, animations, sync, render and swap in the render loop
55Q_LOGGING_CATEGORY(QSG_LOG_TIME_RENDERLOOP, "qt.scenegraph.time.renderloop")
56
57// Texture uploads and swizzling
58Q_LOGGING_CATEGORY(QSG_LOG_TIME_TEXTURE, "qt.scenegraph.time.texture")
59
60// Glyph preparation (only for distance fields atm)
61Q_LOGGING_CATEGORY(QSG_LOG_TIME_GLYPH, "qt.scenegraph.time.glyph")
62
63// Timing inside the renderer base class
64Q_LOGGING_CATEGORY(QSG_LOG_TIME_RENDERER, "qt.scenegraph.time.renderer")
65
66// Applicable for render loops that install their own animation driver, such as
67// the 'threaded' loop. This env.var. is documented in the scenegraph docs.
68DEFINE_BOOL_CONFIG_OPTION(useElapsedTimerBasedAnimationDriver, QSG_USE_SIMPLE_ANIMATION_DRIVER);
69
71{
72 int use = -1;
73 if (use < 0) {
74 use = !qEnvironmentVariableIsEmpty("QSG_FIXED_ANIMATION_STEP") && qgetenv("QSG_FIXED_ANIMATION_STEP") != "no"
75 ? 1 : 0;
76 qCDebug(QSG_LOG_INFO, "Using %s", bool(use) ? "fixed animation steps" : "sg animation driver");
77 }
78 return bool(use);
79}
80
82{
83public:
86 {
88 if (screen) {
89 qreal refreshRate = screen->refreshRate();
90 // To work around that some platforms wrongfully return 0 or something
91 // bogus for the refresh rate.
92 if (refreshRate < 1)
93 refreshRate = 60;
94 m_vsync = 1000.0f / float(refreshRate);
95 } else {
96 m_vsync = 16.67f;
97 }
98 }
99
100 float vsyncInterval() const { return m_vsync; }
101
102 virtual bool isVSyncDependent() const = 0;
103
104protected:
105 float m_vsync = 0;
106};
107
108// default as in default for the threaded render loop
110{
112public:
113 enum Mode {
116 };
117
120 , m_time(0)
122 , m_lag(0)
123 , m_bad(0)
124 , m_good(0)
125 {
128 if (m_vsync <= 0)
130 } else {
134 }
135 if (m_mode == VSyncMode)
136 qCDebug(QSG_LOG_INFO, "Animation Driver: using vsync: %.2f ms", m_vsync);
137 else
138 qCDebug(QSG_LOG_INFO, "Animation Driver: using walltime");
139 }
140
141 void start() override
142 {
143 m_time = 0;
144 m_timer.start();
147 }
148
149 qint64 elapsed() const override
150 {
151 return m_mode == VSyncMode
152 ? qint64(m_time)
154 }
155
156 void advance() override
157 {
158 qint64 delta = m_timer.restart();
159
160 if (m_mode == VSyncMode) {
161 // If a frame is skipped, either because rendering was slow or because
162 // the QML was slow, we accept it and continue advancing with a single
163 // vsync tick. The reason for this is that by the time we notice this
164 // on the GUI thread, the temporal distortion has already gone to screen
165 // and by catching up, we will introduce a second distortion which will
166 // worse. We accept that the animation time falls behind wall time because
167 // it comes out looking better.
168 // Only when multiple bad frames are hit in a row, do we consider
169 // switching. A few really bad frames and we switch right away. For frames
170 // just above the vsync delta, we tolerate a bit more since a buffered
171 // driver can have vsync deltas on the form: 4, 21, 21, 2, 23, 16, and
172 // still manage to put the frames to screen at 16 ms intervals. In addition
173 // to that, we tolerate a 25% margin of error on the value of m_vsync
174 // reported from the system as this value is often not precise.
175
176 m_time += m_vsync;
177
178 if (delta > m_vsync * 1.25f) {
179 m_lag += (delta / m_vsync);
180 m_bad++;
181 // We tolerate one bad frame without resorting to timer based. This is
182 // done to cope with a slow loader frame followed by smooth animation.
183 // However, on the second frame with massive lag, we switch.
184 if (m_lag > 10 && m_bad > 2) {
186 qCDebug(QSG_LOG_INFO, "animation driver switched to timer mode");
188 }
189 } else {
190 m_lag = 0;
191 m_bad = 0;
192 }
193
194 } else {
195 if (delta < 1.25f * m_vsync) {
196 ++m_good;
197 } else {
198 m_good = 0;
199 }
200
201 // We've been solid for a while, switch back to vsync mode. Tolerance
202 // for switching back is lower than switching to timer mode, as we
203 // want to stay in vsync mode as much as possible.
204 if (m_good > 10 && !qsg_useConsistentTiming()) {
205 m_time = elapsed();
207 m_bad = 0;
208 m_lag = 0;
209 qCDebug(QSG_LOG_INFO, "animation driver switched to vsync mode");
210 }
211 }
212
214 }
215
216 bool isVSyncDependent() const override
217 {
218 return true;
219 }
220
221 double m_time;
225 float m_lag;
226 int m_bad;
228};
229
230// Advance based on QElapsedTimer. (so like the TimerMode of QSGDefaultAnimationDriver)
231// Does not depend on vsync-based throttling.
232//
233// NB this is not the same as not installing a QAnimationDriver: the built-in
234// approach in QtCore is to rely on 16 ms timer events which are potentially a
235// lot less accurate.
236//
237// This has the benefits of:
238// - not needing any of the infrastructure for falling back to a
239// QTimer when there are multiple windows,
240// - needing no heuristics trying determine if vsync-based throttling
241// is missing or broken,
242// - being compatible with any kind of temporal drifts in vsync throttling
243// which is reportedly happening in various environments and platforms
244// still,
245// - not being tied to the primary screen's refresh rate, i.e. this is
246// correct even if the window is on some secondary screen with a
247// different refresh rate,
248// - not having to worry about the potential effects of variable refresh
249// rate solutions,
250// - render thread animators work correctly regardless of vsync.
251//
252// On the downside, some animations might appear less smooth (compared to the
253// ideal single window case of QSGDefaultAnimationDriver).
254//
256{
257public:
260 {
261 qCDebug(QSG_LOG_INFO, "Animation Driver: using QElapsedTimer, thread %p %s",
263 QThread::currentThread() == qGuiApp->thread() ? "(gui/main thread)" : "(render thread)");
264 }
265
266 void start() override
267 {
268 m_wallTime.restart();
270 }
271
272 qint64 elapsed() const override
273 {
274 return m_wallTime.elapsed();
275 }
276
277 void advance() override
278 {
280 }
281
282 bool isVSyncDependent() const override
283 {
284 return false;
285 }
286
287private:
288 QElapsedTimer m_wallTime;
289};
290
304{
305}
306
308{
309}
310
312{
313}
314
316{
317}
318
319
324{
326 node->setRect(rect);
327 node->setColor(c);
328 node->update();
329 return node;
330}
331
338{
339 return nullptr;
340}
341
348{
349 return nullptr;
350}
351
356{
357 if (useElapsedTimerBasedAnimationDriver())
359
361}
362
368{
369 return static_cast<QSGAnimationDriver *>(driver)->vsyncInterval();
370}
371
376{
377 return static_cast<QSGAnimationDriver *>(driver)->isVSyncDependent();
378}
379
381{
382 return QSize(1, 1);
383}
384
400{
401 Q_UNUSED(renderContext);
402 qWarning("QSGRendererInterface not implemented");
403 return nullptr;
404}
405
407 : m_sg(context)
408{
409}
410
412{
413}
414
416{
418}
419
421{
422}
423
427{
428 Q_UNUSED(devicePixelRatio);
429 Q_UNUSED(cb);
431}
432
434 RenderPassCallback mainPassRecordingStart,
435 RenderPassCallback mainPassRecordingEnd,
436 void *callbackUserData)
437{
438 renderer->setRenderTarget(renderTarget);
439 Q_UNUSED(mainPassRecordingStart);
440 Q_UNUSED(mainPassRecordingEnd);
441 Q_UNUSED(callbackUserData);
442}
443
445{
447}
448
450{
453}
454
459{
460}
461
466{
467 return nullptr;
468}
469
471{
472
473}
474
476{
477 engine->ref.ref();
479}
480
482{
485}
486
488{
489 return nullptr;
490}
491
500{
501 if (!factory)
502 return nullptr;
503
504 m_mutex.lock();
506 m_mutex.unlock();
507
508 if (!texture) {
509 texture = factory->createTexture(window);
510
511 m_mutex.lock();
513 m_mutex.unlock();
514
516 }
517 return texture;
518}
519
521{
522 m_mutex.lock();
524 m_mutex.unlock();
525}
526
537{
538 return nullptr;
539}
540
542
543#include "qsgcontext.moc"
544#include "moc_qsgcontext_p.cpp"
\inmodule QtCore
void advanceAnimation()
Advances the animation.
The QColor class provides colors based on RGB, HSV or CMYK values.
Definition qcolor.h:31
\inmodule QtCore
qint64 elapsed() const noexcept
Returns the number of milliseconds since this QElapsedTimer was last started.
qint64 restart() noexcept
Restarts the timer and returns the number of milliseconds elapsed since the previous start.
void start() noexcept
Starts this timer.
QScreen * primaryScreen
the primary (or default) screen of the application.
T take(const Key &key)
Removes the item with the key from the hash and returns the value associated with it.
Definition qhash.h:975
T value(const Key &key) const noexcept
Definition qhash.h:1044
iterator insert(const Key &key, const T &value)
Inserts a new item with the key and a value of value.
Definition qhash.h:1283
void unlock() noexcept
Unlocks the mutex.
Definition qmutex.h:293
void lock() noexcept
Locks the mutex.
Definition qmutex.h:290
\inmodule QtCore
Definition qobject.h:90
QObject * parent() const
Returns a pointer to the parent object.
Definition qobject.h:311
static QMetaObject::Connection connect(const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
\threadsafe
Definition qobject.cpp:2823
void destroyed(QObject *=nullptr)
This signal is emitted immediately before the object obj is destroyed, after any instances of QPointe...
QQuickGraphicsConfiguration controls lower level graphics settings for the QQuickWindow.
The QQuickTextureFactory class provides an interface for loading custom textures from QML....
\qmltype Window \instantiates QQuickWindow \inqmlmodule QtQuick
The QRawFont class provides access to a single physical instance of a font.
Definition qrawfont.h:24
\inmodule QtCore\reentrant
Definition qrect.h:483
\inmodule QtGui
Definition qrhi.h:1614
\inmodule QtGui
Definition qrhi.h:1767
QSGAnimationDriver(QObject *parent)
float vsyncInterval() const
virtual bool isVSyncDependent() const =0
The QSGContext holds the scene graph entry points for one QML engine.
virtual void renderContextInitialized(QSGRenderContext *renderContext)
virtual float vsyncIntervalForAnimationDriver(QAnimationDriver *driver)
virtual QSGShaderEffectNode * createShaderEffectNode(QSGRenderContext *renderContext)
Creates a new shader effect node.
virtual bool isVSyncDependent(QAnimationDriver *driver)
~QSGContext() override
virtual QSGRendererInterface * rendererInterface(QSGRenderContext *renderContext)
Returns a pointer to the (presumably) global renderer interface.
virtual QSGInternalRectangleNode * createInternalRectangleNode()=0
virtual QAnimationDriver * createAnimationDriver(QObject *parent)
Creates a new animation driver.
QSGContext(QObject *parent=nullptr)
virtual QSGGuiThreadShaderEffectManager * createGuiThreadShaderEffectManager()
Creates a new shader effect helper instance.
virtual QSize minimumFBOSize() const
virtual void renderContextInvalidated(QSGRenderContext *renderContext)
qint64 elapsed() const override
Returns the number of milliseconds since the animations was started.
void advance() override
Advances the animation.
QSGDefaultAnimationDriver(QObject *parent)
bool isVSyncDependent() const override
QSGElapsedTimerAnimationDriver(QObject *parent)
bool isVSyncDependent() const override
qint64 elapsed() const override
Returns the number of milliseconds since the animations was started.
void advance() override
Advances the animation.
virtual void setRect(const QRectF &rect)=0
virtual void update()=0
virtual void setColor(const QColor &color)=0
void registerFontengineForCleanup(QFontEngine *engine)
QSGRenderContext(QSGContext *context)
QHash< QObject *, QSGTexture * > m_textures
virtual void endNextFrame(QSGRenderer *renderer)
QHash< QFontEngine *, int > m_fontEnginesToClean
virtual void initialize(const InitParams *params)
virtual void beginNextFrame(QSGRenderer *renderer, const QSGRenderTarget &renderTarget, RenderPassCallback mainPassRecordingStart, RenderPassCallback mainPassRecordingEnd, void *callbackUserData)
void textureFactoryDestroyed(QObject *o)
virtual void invalidateGlyphCaches()
virtual QSGDistanceFieldGlyphCache * distanceFieldGlyphCache(const QRawFont &font, int renderTypeQuality)
Factory function for scene graph backends of the distance-field glyph cache.
virtual void invalidate()
virtual void endSync()
void(*)(void *) RenderPassCallback
virtual void preprocess()
Do necessary preprocessing before the frame.
virtual QRhi * rhi() const
void unregisterFontengineForCleanup(QFontEngine *engine)
virtual void prepareSync(qreal devicePixelRatio, QRhiCommandBuffer *cb, const QQuickGraphicsConfiguration &config)
QSGTexture * textureForFactory(QQuickTextureFactory *factory, QQuickWindow *window)
Factory function for the scene graph renderers.
~QSGRenderContext() override
virtual QSGTexture * compressedTextureForFactory(const QSGCompressedTextureFactory *) const
Return the texture corresponding to a texture factory.
QSet< QSGTexture * > m_texturesToDelete
An interface providing access to some of the graphics API specific internals of the scenegraph.
The renderer class is the abstract baseclass used for rendering the QML scene graph.
\inmodule QtQuick
Definition qsgtexture.h:20
The QScreen class is used to query screen properties. \inmodule QtGui.
Definition qscreen.h:32
qreal refreshRate
the approximate vertical refresh rate of the screen in Hz
Definition qscreen.h:64
void clear()
Definition qset.h:61
\inmodule QtCore
Definition qsize.h:25
static QThread * currentThread()
Definition qthread.cpp:966
static QUnifiedTimer * instance()
void setConsistentTiming(bool consistent)
qDeleteAll(list.begin(), list.end())
rect
[4]
Combined button and popup list for selecting options.
@ DirectConnection
static void * context
EGLConfig config
#define qGuiApp
#define qWarning
Definition qlogging.h:162
#define Q_LOGGING_CATEGORY(name,...)
#define qCDebug(category,...)
#define SLOT(a)
Definition qobjectdefs.h:51
#define SIGNAL(a)
Definition qobjectdefs.h:52
GLenum GLuint texture
void ** params
const GLubyte * c
#define DEFINE_BOOL_CONFIG_OPTION(name, var)
#define Q_ASSERT(cond)
Definition qrandom.cpp:47
bool qsg_useConsistentTiming()
SSL_CTX int(* cb)(SSL *ssl, unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg)
QScreen * screen
[1]
Definition main.cpp:29
Q_CORE_EXPORT QByteArray qgetenv(const char *varName)
Q_CORE_EXPORT bool qEnvironmentVariableIsEmpty(const char *varName) noexcept
#define Q_OBJECT
#define Q_UNUSED(x)
long long qint64
Definition qtypes.h:55
double qreal
Definition qtypes.h:92
QItemEditorFactory * factory
aWidget window() -> setWindowTitle("New Window Title")
[2]
QJSEngine engine
[0]
QSvgRenderer * renderer
[0]
IUIAutomationTreeWalker __RPC__deref_out_opt IUIAutomationElement ** parent