Writing a custom Qt 3D aspect - part 1

Introduction

Qt 3D has a flexible and extensible architecture that allows us to easily add new functionality to it without breaking existing features. The functionality of Qt 3D is divided into so-called aspects, each of which encapsulates a specific subject area, such as rendering (Render Aspect), input (Input Aspect), or animation (Animation Aspect).

In this short series of articles, you'll walk through the process of adding a new aspect that provides component types and behavior for a new area not covered by Qt 3D out of the box. In this example, we decided to implement an aspect that allows us to calculate the current average frame rate. Of course, this could be added to the renderer, but it's simple enough to be a good example for our purposes today. The full source code for the example is available for download .


Review

The application we will build looks like this. This is a very simple Qt 3D scene, and a window showing the current average frame rate.

There are several parts that we need to consider when adding new functionality:

  • Aspect - is responsible for organizing any tasks that require the execution of each frame, and for managing the storage of any external objects.
  • Components - Provided by your library or application, which together give the final object a new behavior. Components are the main API you need to create.
  • Nodes (Nodes in the figure) - as for components, except that subclasses of QNode usually provide the ancillary data required by the component. For example, QAnimationClipLoader is a node that provides key frame animation data to the QClipAnimator component.
  • Backend Nodes (Backend Nodes in the picture) - Backend copies for any external components or nodes provided by your library/application. These are objects that are typically handled by jobs running on the thread pool, as dictated by the aspect itself.
  • Mapper - Custom maps that register with this aspect in mind and are responsible for creating, fetching and destroying internal nodes on demand. Mapper is used by QAbstractAspect and QAspectEngine to synchronize the lifetime of external and internal objects.
  • Jobs - created and scheduled by the aspect, process the base nodes. Jobs can also send events to external nodes and components if properties change.
  • Change arbiter - responsible for delivering events between frontend and backend objects. You don't have to do anything with it, but be aware of its existence.

Adding an aspect

Writing the original aspect is really trivial. Just inherit QAbstractAspect and register it with QAspectEngine:

customaspect.h

class CustomAspect : public Qt3DCore::QAbstractAspect
{
    Q_OBJECT
public:
    explicit CustomAspect(QObject *parent = nullptr)
        : Qt3DCore::QAbstractAspect(parent)
    {}

protected:
    QVector<Qt3DCore::QAspectJobPtr> jobsToExecute(qint64 time) override
    {
        qDebug() << Q_FUNC_INFO << "Frame time =" << time;
        return {};
    }
};

main.cpp

int main(int argc, char **argv)
{
    QGuiApplication app(argc, argv);
    Qt3DExtras::Quick::Qt3DQuickWindow view;

    view.engine()->aspectEngine()->registerAspect(new CustomAspect);

    view.setSource(QUrl("qrc:/main.qml"));
    view.show();
    return app.exec();
}

QAbstractAspect has virtual methods that you can override for initialization and deletion if you need them. However, for this simple example, all we need to do is implement the virtual method jobsToExecute(). We'll use it later to schedule a job on the thread pool every frame, but for now we're just printing debug text to return an empty vector (no jobs ready to run). Note that these virtual functions will only be called once the aspect has been registered with the QAspectEngine (see above) to be part of the simulation. We'll come back and finish this aspect a bit later.

FpsMonitor component

We want to add functionality that would display information about the average frame rate, averaged over a given number of frames. We can write an API like this:

fpsmonitor.h

class FpsMonitor : public Qt3DCore::QComponent
{
    Q_OBJECT
    Q_PROPERTY(int rollingMeanFrameCount READ rollingMeanFrameCount WRITE setRollingMeanFrameCount NOTIFY rollingMeanFrameCountChanged)
    Q_PROPERTY(float framesPerSecond READ framesPerSecond NOTIFY framesPerSecondChanged)

public:
    explicit FpsMonitor(Qt3DCore::QNode *parent = nullptr);

    float framesPerSecond() const;
    int rollingMeanFrameCount() const;

public slots:
    void setRollingMeanFrameCount(int rollingMeanFrameCount);

signals:
    void framesPerSecondChanged(float framesPerSecond);
    void rollingMeanFrameCountChanged(int rollingMeanFrameCount);

private:
    float m_framesPerSecond;
    int m_rollingMeanFrameCount;
};

Please note that we are using a property-based declarative API so that this class can be easily used from both QML and C++. The rollingMeanFrameCount property is a normal read/write property, and the implementation of the setter and getter functions is completely standard. This property will be used to control the number of frames over which we calculate the moving average frame rate. The framesPerSecond property is a read-only property that will later be set from a job we'll be writing to process FpsMonitor components in the Qt 3D thread pool.

Create a small test application

Before we can use our custom component from QML, we must register the type with the QML type system. This is a simple one line code that we can add to our main function:

main.cpp

qmlRegisterType<FpsMonitor>("CustomModule", 1, 0, "FpsMonitor");
rootContext->setContextProperty("_window", &view);

where we also took advantage of the ability to export the window to a QML context (we will need this at some point).

Once this is done, we can import the CustomModule QML module and use the FpsMonitor component just like any of the built-in types.

main.qml

Entity {
    components: [
        FpsMonitor {
            rollingMeanFrameCount: 20
            onFramesPerSecondChanged: {
                var fpsString = parseFloat(Math.round(framesPerSecond * 100) / 100).toFixed(2);
                _window.title = "CustomAspect: FPS = " + fpsString
                        + " (" + rollingMeanFrameCount + " frame average)"
            }
        }
    ]
}

Of course, at the moment FpsMonitor does nothing but set the value of the rollingMeanFrameCount property. Once we've finished the backend, the above code will update the window title to show the current average frame rate and the number of frames used to calculate it.

In the next part, we will implement the appropriate backend node for FpsMonitor and make sure it is created and destroyed on demand and sets up communication between the frontend and the backend.

Article written by: Sean Harmer | Saturday, November 25, 2017

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
AD

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10
Last comments
ИМ
Игорь МаксимовNov. 23, 2024, 1:51 a.m.
Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
Evgenii Legotckoi
Evgenii LegotckoiNov. 1, 2024, 3:37 a.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 9:19 p.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 8:51 p.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 6, 2024, 12:02 a.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Now discuss on the forum
Evgenii Legotckoi
Evgenii LegotckoiJune 25, 2024, 4:11 a.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 8:04 p.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
NSProject
NSProjectJune 4, 2022, 4:49 p.m.
Всё ещё разбираюсь с кешем. В следствии прочтения данной статьи. Я принял для себя решение сделать кеширование свойств менеджера модели LikeDislike. И так как установка evileg_core для меня не была возможна, ибо он писался…
9
9AnonimOct. 25, 2024, 10:10 p.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks