summaryrefslogtreecommitdiffstats
path: root/tools/qqem/fpshelper.cpp
blob: 808e95bea6e3b705290da109fc8caa8ea6674479 (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
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only

#include "fpshelper.h"

FpsHelper::FpsHelper()
{
    setFlag(QQuickItem::ItemHasContents);

    connect(this, &QQuickItem::enabledChanged, this, [this]() {
        if (isEnabled()) {
            m_frames = 0;
            m_timer.start();
            update();
        }
    });

    if (isEnabled())
        m_timer.start();
}

float FpsHelper::fps() const
{
    return m_fps;
}

QSGNode *FpsHelper::updatePaintNode(QSGNode *node, UpdatePaintNodeData *)
{
    m_frames++;
    qint64 nsElapsed = m_timer.nsecsElapsed();
    float ms = float(nsElapsed / 1000000.0);
    if (ms >= 1000.0f) {
        float fps = m_frames / (ms / 1000.0f);
        // Round to 0.2 accuracy
        fps = std::round(fps * 5.0f) / 5.0f;
        if (!qFuzzyCompare(fps, m_fps)) {
            m_fps = fps;
            Q_EMIT fpsChanged();
        }
        m_frames = 0;
        m_timer.restart();
    }

    // Call update in a loop if fps tracking is enabled
    if (isEnabled())
        update();

    return node;
}