diff options
Diffstat (limited to 'examples/gui')
34 files changed, 1246 insertions, 788 deletions
diff --git a/examples/gui/CMakeLists.txt b/examples/gui/CMakeLists.txt index 7631777ef4..afc52ac3fa 100644 --- a/examples/gui/CMakeLists.txt +++ b/examples/gui/CMakeLists.txt @@ -1,7 +1,8 @@ -# Generated from gui.pro. +# Copyright (C) 2022 The Qt Company Ltd. +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause -if(NOT TARGET Qt::Gui) +if(NOT TARGET Qt6::Gui) return() endif() -add_subdirectory(analogclock) -add_subdirectory(rasterwindow) +qt_internal_add_example(rasterwindow) +qt_internal_add_example(rhiwindow) diff --git a/examples/gui/analogclock/.prev_CMakeLists.txt b/examples/gui/analogclock/.prev_CMakeLists.txt deleted file mode 100644 index b71892d1b8..0000000000 --- a/examples/gui/analogclock/.prev_CMakeLists.txt +++ /dev/null @@ -1,34 +0,0 @@ -# Generated from analogclock.pro. - -cmake_minimum_required(VERSION 3.14) -project(analogclock LANGUAGES CXX) - -set(CMAKE_INCLUDE_CURRENT_DIR ON) - -set(CMAKE_AUTOMOC ON) -set(CMAKE_AUTORCC ON) -set(CMAKE_AUTOUIC ON) - -set(INSTALL_EXAMPLEDIR "examples/gui/analogclock") - -find_package(Qt6 COMPONENTS Core) -find_package(Qt6 COMPONENTS Gui) - -add_qt_gui_executable(analogclock - ../rasterwindow/rasterwindow.cpp ../rasterwindow/rasterwindow.h - main.cpp -) -target_include_directories(analogclock PUBLIC - ../rasterwindow -) - -target_link_libraries(analogclock PUBLIC - Qt::Core - Qt::Gui -) - -install(TARGETS analogclock - RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}" - BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}" - LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}" -) diff --git a/examples/gui/analogclock/CMakeLists.txt b/examples/gui/analogclock/CMakeLists.txt deleted file mode 100644 index d5605ab8ba..0000000000 --- a/examples/gui/analogclock/CMakeLists.txt +++ /dev/null @@ -1,41 +0,0 @@ -# Generated from analogclock.pro. - -cmake_minimum_required(VERSION 3.14) -project(analogclock LANGUAGES CXX) - - -set(CMAKE_INCLUDE_CURRENT_DIR ON) - -set(CMAKE_AUTOMOC ON) -set(CMAKE_AUTORCC ON) -set(CMAKE_AUTOUIC ON) - -set(INSTALL_EXAMPLEDIR "examples/gui/gui_analogclock") # special case - -find_package(Qt6 COMPONENTS Core) -find_package(Qt6 COMPONENTS Gui) -find_package(Qt6 COMPONENTS Widgets) # special case: add - -add_qt_gui_executable(gui_analogclock # special case: renamed target - ../rasterwindow/rasterwindow.cpp ../rasterwindow/rasterwindow.h - main.cpp -) -target_include_directories(gui_analogclock PUBLIC # special case - ../rasterwindow -) -# special case begin -target_link_libraries(gui_analogclock PUBLIC # special case - Qt::Gui -) -# special case end - -target_link_libraries(gui_analogclock PUBLIC # special case - Qt::Core - Qt::Gui -) - -install(TARGETS gui_analogclock # special case - RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}" - BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}" - LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}" -) diff --git a/examples/gui/analogclock/analogclock.pro b/examples/gui/analogclock/analogclock.pro deleted file mode 100644 index eef17274f5..0000000000 --- a/examples/gui/analogclock/analogclock.pro +++ /dev/null @@ -1,10 +0,0 @@ -include(../rasterwindow/rasterwindow.pri) - -# work-around for QTBUG-13496 -CONFIG += no_batch - -SOURCES += \ - main.cpp - -target.path = $$[QT_INSTALL_EXAMPLES]/gui/analogclock -INSTALLS += target diff --git a/examples/gui/analogclock/main.cpp b/examples/gui/analogclock/main.cpp deleted file mode 100644 index 053ccb54b5..0000000000 --- a/examples/gui/analogclock/main.cpp +++ /dev/null @@ -1,170 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:BSD$ -** 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. -** -** BSD License Usage -** Alternatively, you may use this file under the terms of the BSD license -** as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of The Qt Company Ltd nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QtGui> - -#include "rasterwindow.h" - -//! [5] -class AnalogClockWindow : public RasterWindow -{ -public: - AnalogClockWindow(); - -protected: - void timerEvent(QTimerEvent *) override; - void render(QPainter *p) override; - -private: - int m_timerId; -}; -//! [5] - - -//! [6] -AnalogClockWindow::AnalogClockWindow() -{ - setTitle("Analog Clock"); - resize(200, 200); - - m_timerId = startTimer(1000); -} -//! [6] - -//! [7] -void AnalogClockWindow::timerEvent(QTimerEvent *event) -{ - if (event->timerId() == m_timerId) - renderLater(); -} -//! [7] - -//! [1] //! [14] -void AnalogClockWindow::render(QPainter *p) -{ -//! [14] -//! [8] - static const QPoint hourHand[3] = { - QPoint(7, 8), - QPoint(-7, 8), - QPoint(0, -40) - }; - static const QPoint minuteHand[3] = { - QPoint(7, 8), - QPoint(-7, 8), - QPoint(0, -70) - }; - - QColor hourColor(127, 0, 127); - QColor minuteColor(0, 127, 127, 191); -//! [8] - -//! [9] - p->setRenderHint(QPainter::Antialiasing); -//! [9] //! [10] - p->translate(width() / 2, height() / 2); - - int side = qMin(width(), height()); - p->scale(side / 200.0, side / 200.0); -//! [1] //! [10] - -//! [11] - p->setPen(Qt::NoPen); - p->setBrush(hourColor); -//! [11] - -//! [2] - QTime time = QTime::currentTime(); - - p->save(); - p->rotate(30.0 * ((time.hour() + time.minute() / 60.0))); - p->drawConvexPolygon(hourHand, 3); - p->restore(); -//! [2] - -//! [12] - p->setPen(hourColor); - - for (int i = 0; i < 12; ++i) { - p->drawLine(88, 0, 96, 0); - p->rotate(30.0); - } -//! [12] //! [13] - p->setPen(Qt::NoPen); - p->setBrush(minuteColor); -//! [13] - -//! [3] - p->save(); - p->rotate(6.0 * (time.minute() + time.second() / 60.0)); - p->drawConvexPolygon(minuteHand, 3); - p->restore(); -//! [3] - -//! [4] - p->setPen(minuteColor); - - for (int j = 0; j < 60; ++j) { - if ((j % 5) != 0) - p->drawLine(92, 0, 96, 0); - p->rotate(6.0); - } -//! [4] -} - -int main(int argc, char **argv) -{ - QGuiApplication app(argc, argv); - - AnalogClockWindow clock; - clock.show(); - - return app.exec(); -} diff --git a/examples/gui/doc/images/analogclock-window-example.png b/examples/gui/doc/images/analogclock-window-example.png Binary files differdeleted file mode 100644 index f5e92e400a..0000000000 --- a/examples/gui/doc/images/analogclock-window-example.png +++ /dev/null diff --git a/examples/gui/doc/images/analogclockwindow-viewport.png b/examples/gui/doc/images/analogclockwindow-viewport.png Binary files differdeleted file mode 100644 index 31ce0c3c6e..0000000000 --- a/examples/gui/doc/images/analogclockwindow-viewport.png +++ /dev/null diff --git a/examples/gui/doc/images/openglwindow-example.png b/examples/gui/doc/images/openglwindow-example.png Binary files differdeleted file mode 100644 index 63ba4ed2f4..0000000000 --- a/examples/gui/doc/images/openglwindow-example.png +++ /dev/null diff --git a/examples/gui/doc/images/rhiwindow_example.jpg b/examples/gui/doc/images/rhiwindow_example.jpg Binary files differnew file mode 100644 index 0000000000..ca1e44bada --- /dev/null +++ b/examples/gui/doc/images/rhiwindow_example.jpg diff --git a/examples/gui/doc/src/analogclockwindow.qdoc b/examples/gui/doc/src/analogclockwindow.qdoc deleted file mode 100644 index f13f7261aa..0000000000 --- a/examples/gui/doc/src/analogclockwindow.qdoc +++ /dev/null @@ -1,138 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** 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 Free Documentation License Usage -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. Please review the following information to ensure -** the GNU Free Documentation License version 1.3 requirements -** will be met: https://www.gnu.org/licenses/fdl-1.3.html. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \example analogclock - \title Analog Clock Window Example - - \brief The Analog Clock Window example shows how to draw the contents of - a custom window. - - \image analogclock-window-example.png Screenshot of the Analog - Clock Window example - - This example demonstrates how the transformation and scaling - features of QPainter can be used to make drawing easier. - - \section1 AnalogClockWindow Class Definition - - The \c AnalogClockWindow class provides a clock with hour and - minute hands that is automatically updated every few seconds. We - make use of the RasterWindow from the \l {Raster Window Example} - and reimplement the \c render function to draw the clock face: - - \snippet analogclock/main.cpp 5 - - \section1 AnalogClock Class Implementation - - \snippet analogclock/main.cpp 6 - - We set a title on the window and resize to a reasonable size. Then - we start a timer which we will use to redraw the clock every - second. - - \snippet analogclock/main.cpp 7 - - The timerEvent function is called every second as a result of - our startTimer call. Making use of the convenience in the base - class, we schedule the window to be repainted. - - Checking the timer's id is not strictly needed as we only have - one active timer in this instance, but it is good practice to do - so. - - \snippet analogclock/main.cpp 14 - \snippet analogclock/main.cpp 8 - - Before we set up the painter and draw the clock, we first define - two lists of \l {QPoint}s and two \l{QColor}s that will be used - for the hour and minute hands. The minute hand's color has an - alpha component of 191, meaning that it's 75% opaque. - - \snippet analogclock/main.cpp 9 - - We call QPainter::setRenderHint() with QPainter::Antialiasing to - turn on antialiasing. This makes drawing of diagonal lines much - smoother. - - \snippet analogclock/main.cpp 10 - - The translation moves the origin to the center of the window, and - the scale operation ensures that the following drawing operations - are scaled to fit within the window. We use a scale factor that - let's us use x and y coordinates between -100 and 100, and that - ensures that these lie within the length of the window's shortest - side. - - To make our code simpler, we will draw a fixed size clock face that will - be positioned and scaled so that it lies in the center of the window. - - We also determine the length of the window's shortest side so that we - can fit the clock face inside the window. - - The painter takes care of all the transformations made during the - rendering, and ensures that everything is drawn correctly. Letting - the painter handle transformations is often easier than performing - manual calculations. - - \image analogclockwindow-viewport.png - - We draw the hour hand first, using a formula that rotates the coordinate - system counterclockwise by a number of degrees determined by the current - hour and minute. This means that the hand will be shown rotated clockwise - by the required amount. - - \snippet analogclock/main.cpp 11 - - We set the pen to be Qt::NoPen because we don't want any outline, - and we use a solid brush with the color appropriate for - displaying hours. Brushes are used when filling in polygons and - other geometric shapes. - - \snippet analogclock/main.cpp 2 - - We save and restore the transformation matrix before and after the - rotation because we want to place the minute hand without having to - take into account any previous rotations. - - \snippet analogclock/main.cpp 12 - - We draw markers around the edge of the clock for each hour. We - draw each marker then rotate the coordinate system so that the - painter is ready for the next one. - - \snippet analogclock/main.cpp 13 - \snippet analogclock/main.cpp 3 - - The minute hand is rotated in a similar way to the hour hand. - - \snippet analogclock/main.cpp 4 - - Again, we draw markers around the edge of the clock, but this - time to indicate minutes. We skip multiples of 5 to avoid drawing - minute markers on top of hour markers. -*/ diff --git a/examples/gui/doc/src/openglwindow.qdoc b/examples/gui/doc/src/openglwindow.qdoc deleted file mode 100644 index f283c7cfc0..0000000000 --- a/examples/gui/doc/src/openglwindow.qdoc +++ /dev/null @@ -1,158 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** 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 Free Documentation License Usage -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. Please review the following information to ensure -** the GNU Free Documentation License version 1.3 requirements -** will be met: https://www.gnu.org/licenses/fdl-1.3.html. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \example openglwindow - \title OpenGL Window Example - - \brief This example shows how to create a minimal QWindow based application - for the purpose of using OpenGL. - - \image openglwindow-example.png Screenshot of the OpenGLWindow example - - \note This is a low level example of how to use QWindow with OpenGL. - In practice you should consider using the higher level QOpenGLWindow class. - - \section1 OpenGLWindow Super Class - - Our OpenGLWindow class acts as an API which is then subclassed to do the - actual rendering. It has functions to make a request for render() to be - called, either immediately with renderNow() or as soon as the event loop - has finished processing the current batch of events with renderLater(). - The OpenGLWindow subclass can either reimplement render() for OpenGL based - rendering, or render(QPainter *) for rendering with a QPainter. Use - OpenGLWindow::setAnimating(true) for render() to be called at the vertical - refresh rate, assuming vertical sync is enabled in the underlying OpenGL - drivers. - - In the class that does the OpenGL rendering you will typically want to - inherit from QOpenGLFunctions, as our OpenGLWindow does, in order to get - platform independent access to OpenGL ES 2.0 functions. By inheriting from - QOpenGLFunctions the OpenGL functions it contains will get precedence, and - you will not have to worry about resolving those functions if you want your - application to work with OpenGL as well as OpenGL ES 2.0. - - \snippet openglwindow/openglwindow.h 1 - - The window's surface type must be set to QSurface::OpenGLSurface to - indicate that the window is to be used for OpenGL rendering and not for - rendering raster content with QPainter using a QBackingStore. - - \snippet openglwindow/openglwindow.cpp 1 - - Any OpenGL initialization needed can be done by overriding the initialize() - function, which is called once before the first call to render(), with a - valid current QOpenGLContext. As can be seen in the following code snippet, - the default render(QPainter *) and initialize() implementations are empty, - whereas the default render() implementation initializes a - QOpenGLPaintDevice and then calls into render(QPainter *). - - \snippet openglwindow/openglwindow.cpp 2 - - The renderLater() function simply calls QWindow::requestUpdate() to schedule - an update for when the system is ready to repaint. - - We also call renderNow() when we get an expose event. The exposeEvent() is - the notification to the window that its exposure, meaning visibility, on - the screen has changed. When the expose event is received you can query - QWindow::isExposed() to find out whether or not the window is currently - exposed. Do not render to or call QOpenGLContext::swapBuffers() on a window - before it has received its first expose event, as before then its final - size might be unknown, and in addition what is rendered might not even end - up on the screen. - - \snippet openglwindow/openglwindow.cpp 3 - - In renderNow() we return if we are not currently exposed, in which case - rendering is delayed until we actually get an expose event. If we have not - yet done so, we create the QOpenGLContext with the same QSurfaceFormat as - was set on the OpenGLWindow, and call initialize() for the sake of the sub - class, and initializeOpenGLFunctions() in order for the QOpenGLFunctions - super class to be associated with the correct QOpenGLContext. In any case - we make the context current by calling QOpenGLContext::makeCurrent(), call - render() to do the actual rendering, and finally we schedule for the - rendered contents to be made visible by calling - QOpenGLContext::swapBuffers() with the OpenGLWindow as parameter. - - Once the rendering of a frame using an OpenGL context is initiated by - calling QOpenGLContext::makeCurrent(), giving the surface on which to - render as a parameter, OpenGL commands can be issued. The commands can be - issued either directly by including <qopengl.h>, which also includes the - system's OpenGL headers, or as by using QOpenGLFunctions, which can - either be inherited from for convenience, or accessed using - QOpenGLContext::functions(). QOpenGLFunctions gives access to all the - OpenGL ES 2.0 level OpenGL calls that are not already standard in both - OpenGL ES 2.0 and desktop OpenGL. For more information about the OpenGL and - OpenGL ES APIs, refer to the official \l{http://www.opengl.org/registry/}{OpenGL Registry} and - \l {http://www.khronos.org/registry/gles/}{Khronos OpenGL ES API Registry}. - - If animation has been enabled with OpenGLWindow::setAnimating(true), we - call renderLater() to schedule another update request. - - \snippet openglwindow/openglwindow.cpp 4 - - Enabling animation also schedules an update request as shown in the - following code snippet. - - \snippet openglwindow/openglwindow.cpp 5 - - \section1 Example OpenGL Rendering Sub Class - - Here we sub class OpenGLWindow to show how to do OpenGL to render a - rotating triangle. By indirectly sub classing QOpenGLFunctions we gain - access to all OpenGL ES 2.0 level functionality. - - \snippet openglwindow/main.cpp 1 - - In our main function we initialize QGuiApplication and instantiate our - TriangleOpenGLWindow. We give it a QSurfaceFormat specifying that we want - four samples of multisample antialiasing, as well as a default geometry. - Since we want to have animation we call the above mentioned setAnimating() - function with an argument of true. - - \snippet openglwindow/main.cpp 2 - - The following code snippet shows the OpenGL shader program used in this - example. The vertex and fragment shaders are relatively simple, doing - vertex transformation and interpolated vertex coloring. - - \snippet openglwindow/main.cpp 3 - - Here is the code that loads the shaders and initializes the shader program - By using QOpenGLShaderProgram instead of raw OpenGL we get the convenience - that strips out the highp, mediump, and lowp qualifiers on desktop OpenGL, - where they are not part of the standard. We store the attribute and uniform - locations in member variables to avoid having to do the location lookup - each frame. - - \snippet openglwindow/main.cpp 4 - - Finally, here is our render() function, where we use OpenGL to set up the - viewport, clear the background, and render a rotating triangle. - - \snippet openglwindow/main.cpp 5 -*/ diff --git a/examples/gui/doc/src/rasterwindow.qdoc b/examples/gui/doc/src/rasterwindow.qdoc index 0c52a62b8e..d30b4d7643 100644 --- a/examples/gui/doc/src/rasterwindow.qdoc +++ b/examples/gui/doc/src/rasterwindow.qdoc @@ -1,33 +1,10 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** 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 Free Documentation License Usage -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. Please review the following information to ensure -** the GNU Free Documentation License version 1.3 requirements -** will be met: https://www.gnu.org/licenses/fdl-1.3.html. -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only /*! \example rasterwindow \title Raster Window Example + \examplecategory {Graphics} \brief This example shows how to create a minimal QWindow based application using QPainter for rendering. diff --git a/examples/gui/doc/src/rhiwindow.qdoc b/examples/gui/doc/src/rhiwindow.qdoc new file mode 100644 index 0000000000..3ee33c8002 --- /dev/null +++ b/examples/gui/doc/src/rhiwindow.qdoc @@ -0,0 +1,445 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only + +/*! + \example rhiwindow + \title RHI Window Example + \examplecategory {Graphics} + + \brief This example shows how to create a minimal QWindow-based + application using QRhi. + + \image rhiwindow_example.jpg + + Qt 6.6 starts offering its accelerated 3D API and shader abstraction layer + for application use as well. Applications can now use the same 3D graphics + classes Qt itself uses to implement the Qt Quick scenegraph or the Qt Quick + 3D engine. In earlier Qt versions QRhi and the related classes were all + private APIs. From 6.6 on these classes are in a similar category as QPA + family of classes: neither fully public nor private, but something + in-between, with a more limited compatibility promise compared to public + APIs. On the other hand, QRhi and the related classes now come with full + documentation similarly to public APIs. + + There are multiple ways to use QRhi, the example here shows the most + low-level approach: targeting a QWindow, while not using Qt Quick, Qt Quick + 3D, or Widgets in any form, and setting up all the rendering and windowing + infrastructure in the application. + + In contrast, when writing a QML application with Qt Quick or Qt Quick 3D, + and wanting to add QRhi-based rendering to it, such an application is going + to rely on the window and rendering infrastructure Qt Quick has already + initialized, and it is likely going to query an existing QRhi instance from + the QQuickWindow. There dealing with QRhi::create(), platform/API specifics + such as \l{QVulkanInstance}{Vulkan instances}, or correctly handling + \l{QExposeEvent}{expose} and resize events for the window are all managed + by Qt Quick. Whereas in this example, all that is managed and taken care + of by the application itself. + + \note For QWidget-based applications in particular, it should be noted that + QWidget::createWindowContainer() allows embedding a QWindow (backed by a + native window) into the widget-based user interface. Therefore, the \c + HelloWindow class from this example is reusable in QWidget-based + applications, assuming the necessary initialization from \c main() is in + place as well. + + \section1 3D API Support + + The application supports all the current \l{QRhi::Implementation}{QRhi + backends}. When no command-line arguments are specified, platform-specific + defaults are used: Direct 3D 11 on Windows, OpenGL on Linux, Metal on + macOS/iOS. + + Running with \c{--help} shows the available command-line options: + + \list + \li -d or --d3d11 for Direct 3D 11 + \li -D or --d3d12 for Direct 3D 12 + \li -m or --metal for Metal + \li -v or --vulkan for Vulkan + \li -g or --opengl for OpenGL or OpenGL ES + \li -n or --null for the \l{QRhi::Null}{Null backend} + \endlist + + \section1 Build System Notes + + This application relies solely on the Qt GUI module. It does not use Qt + Widgets or Qt Quick. + + In order to access the RHI APIs, which are available to all Qt applications + but come with a limited compatibility promise, the \c target_link_libraries + CMake command lists \c{Qt6::GuiPrivate}. This is what enables the + \c{#include <rhi/qrhi.h>} include statement to compile successfully. + + \section1 Features + + The application features: + + \list + + \li A resizable QWindow, + + \li a swapchain and depth-stencil buffer that properly follows the size of + the window, + + \li logic to initialize, render, and tear down at the appropriate time + based on events such as \l QExposeEvent and \l QPlatformSurfaceEvent, + + \li rendering a fullscreen textured quad, using a texture the contents of + which is generated in a QImage via QPainter (using the raster paint engine, + i.e. the generating of the image's pixel data is all CPU-based, that data + is then uploaded into a GPU texture), + + \li rendering a triangle with blending and depth testing enabled, using a + perspective projection, while applying a model transform that changes on + every frame, + + \li an efficient, cross-platform render loop using + \l{QWindow::requestUpdate()}{requestUpdate()}. + + \endlist + + \section1 Shaders + + The application uses two sets of vertex and fragment shader pairs: + + \list + + \li one for the fullscreen quad, which uses no vertex inputs and the + fragment shader samples a texture (\c quad.vert, \c quad.frag), + + \li and another pair for the triangle, where vertex positions and colors + are provided in a vertex buffer and a modelview-projection matrix is + provided in a uniform buffer (\c color.vert, \c color.frag). + + \endlist + + The shaders are written as Vulkan-compatible GLSL source code. + + Due to being a Qt GUI module example, this example cannot have a dependency + on the \l{Qt Shader Tools} module. This means that CMake helper functions + such as \c{qt_add_shaders} are not available for use. Therefore, the + example has the pre-processed \c{.qsb} files included in the + \c{shaders/prebuilt} folder, and they are simply included within the + executable via \c{qt_add_resources}. This approach is not generally + recommended for applications, consider rather using \l{Qt Shader Tools + Build System Integration}{qt_add_shaders}, which avoids the need to + manually generate and manage the \c{.qsb} files. + + To generate the \c{.qsb} files for this example, the command \c{qsb --qt6 + color.vert -o prebuilt/color.vert.qsb} etc. was used. This leads to + compiling to \l{https://www.khronos.org/spir/}{SPIR-V} and than transpiling + into GLSL (\c{100 es} and \c 120), HLSL (5.0), and MSL (1.2). All the + shader versions are then packed together into a QShader and serialized to + disk. + + \section1 API-specific Initialization + + For some of the 3D APIs the main() function has to perform the appropriate + API-specific initialiation, e.g. to create a QVulkanInstance when using + Vulkan. For OpenGL we have to ensure a depth buffer is available, this is + done via QSurfaceFormat. These steps are not in the scope of QRhi since + QRhi backends for OpenGL or Vulkan build on the existing Qt facilities such + as QOpenGLContext or QVulkanInstance. + + \snippet rhiwindow/main.cpp api-setup + + \note For Vulkan, note how + QRhiVulkanInitParams::preferredInstanceExtensions() is taken into account + to ensure the appropriate extensions are enabled. + + \c HelloWindow is a subclass of \c RhiWindow, which in turn is a QWindow. + \c RhiWindow contains everything needed to manage a resizable window with + a\ swapchain (and depth-stencil buffer), and is potentially reusable in + other applications as well. \c HelloWindow contains the rendering logic + specific to this particular example application. + + In the QWindow subclass constructor the surface type is set based on the + selected 3D API. + + \snippet rhiwindow/rhiwindow.cpp rhiwindow-ctor + + Creating and initializing a QRhi object is implemented in + RhiWindow::init(). Note that this is invoked only when the window is + \c renderable, which is indicated by an \l{QExposeEvent}{expose event}. + + Depending on which 3D API we use, the appropriate InitParams struct needs + to be passed to QRhi::create(). With OpenGL for example, a + QOffscreenSurface (or some other QSurface) must be created by the + application and provided for use to the QRhi. With Vulkan, a successfully + initialized QVulkanInstance is required. Others, such as Direct 3D or Metal + need no additional information to be able to initialize. + + \snippet rhiwindow/rhiwindow.cpp rhi-init + + Apart from this, everything else, all the rendering code, is fully + cross-platform and has no branching or conditions specific to any of the 3D + API. + + \section1 Expose Events + + What \c renderable exactly means is platform-specific. For example, on + macOS a window that is fully obscured (fully behind some other window) is + not renderable, whereas on Windows obscuring has no significance. + Fortunately, the application needs no special knowledge about this: Qt's + platform plugins abstract the differences behind the expose event. However, + the \l{QWindow::exposeEvent()}{exposeEvent()} reimplementation also needs + to be aware that an empty output size (e.g. width and height of 0) is also + something that should be treated as a non-renderable situation. On Windows + for example, this is what is going to happen when minimizing the window. + Hence the check based on QRhiSwapChain::surfacePixelSize(). + + This implementation of expose event handling attempts to be robust, safe, + and portable. Qt Quick itself also implements a very similar logic in its + render loops. + + \snippet rhiwindow/rhiwindow.cpp expose + + In RhiWindow::render(), which is invoked in response to the + \l{QEvent::UpdateRequest}{UpdateRequest} event generated by + \l{QWindow::requestUpdate()}{requestUpdate()}, the following check is in + place, to prevent attempting to render when the swapchain initialization + failed, or when the window became non-renderable. + + \snippet rhiwindow/rhiwindow.cpp render-precheck + + \section1 Swapchain, Depth-Stencil buffer, and Resizing + + To render to the QWindow, a QRhiSwapChain is needed. In addition, a + QRhiRenderBuffer acting as the depth-stencil buffer is created as well + since the application demonstrates how depth testing can be enabled in a + graphics pipeline. With some legacy 3D APIs managing the depth/stencil + buffer for a window is part of the corresponding windowing system interface + API (EGL, WGL, GLX, etc., meaning the depth/stencil buffer is implicitly + managed together with the \c{window surface}), whereas with modern APIs + managing the depth-stencil buffer for a window-based render target is no + different from offscreen render targets. QRhi abstracts this, but for best + performance it still needs to be indicated that the QRhiRenderBuffer is + \l{QRhiRenderBuffer::UsedWithSwapChainOnly}{used with together with a + QRhiSwapChain}. + + The QRhiSwapChain is associated with the QWindow and the depth/stencil + buffer. + + \snippet rhiwindow/rhiwindow.h swapchain-data + \codeline + \snippet rhiwindow/rhiwindow.cpp swapchain-init + + When the window size changes, the swapchain needs to be resized as well. + This is implemented in resizeSwapChain(). + + \snippet rhiwindow/rhiwindow.cpp swapchain-resize + + Unlike other QRhiResource subclasses, QRhiSwapChain features slightly + different semantics when it comes to its create-function. As the name, + \l{QRhiSwapChain::createOrResize()}{createOrResize()}, suggests, this needs + to be called whenever it is known that the output window size may be out of + sync with what the swapchain was last initialized. The associated + QRhiRenderBuffer for depth-stencil gets its + \l{QRhiRenderBuffer::pixelSize()}{size} set automatically, and + \l{QRhiRenderBuffer::create()}{create()} is called on it implicitly from the + swapchain's createOrResize(). + + This is also a convenient place to (re)calculate the projection and view + matrices since the perspective projection we set up depends on the output + aspect ratio. + + \note To eliminate coordinate system differences, the + \l{QRhi::clipSpaceCorrMatrix()}{a backend/API-specific "correction" matrix} + is queried from QRhi and baked in to the projection matrix. This is what + allows the application to work with OpenGL-style vertex data, assuming a + coordinate system with the origin at the bottom-left. + + The resizeSwapChain() function is called from RhiWindow::render() when it + is discovered that the currently reported size is not the same anymore as + what the swapchain was last initialized with. + + See QRhiSwapChain::currentPixelSize() and QRhiSwapChain::surfacePixelSize() + for further details. + + High DPI support is built-in: the sizes, as the naming indicates, are + always in pixels, taking the window-specific + \l{QWindow::devicePixelRatio()}{scale factor} into account. On the QRhi + (and 3D API) level there is no concept of high DPI scaling, everything is + always in pixels. This means that a QWindow with a size() of 1280x720 and + a devicePixelRatio() of 2 is a render target (swapchain) with a (pixel) size + of 2560x1440. + + \snippet rhiwindow/rhiwindow.cpp render-resize + + \section1 Render Loop + + The application renders continuously, throttled by the presentation rate + (vsync). This is ensured by calling + \l{QWindow::requestUpdate()}{requestUpdate()} from RhiWindow::render() when + the currently recorded frame has been submitted. + + \snippet rhiwindow/rhiwindow.cpp request-update + + This eventually leads to getting a \l{QEvent::UpdateRequest}{UpdateRequest} + event. This is handled in the reimplementation of event(). + + \snippet rhiwindow/rhiwindow.cpp event + + \section1 Resource and Pipeline Setup + + The application records a single render pass that issues two draw calls, + with two different graphics pipelines. One is the "background", with the + texture containing the QPainter-generated image, then a single triangle is + rendered on top with blending enabled. + + The vertex and uniform buffer used with the triangle is created like this. + The size of the uniform buffer is 68 bytes since the shader specific a \c + mat4 and a \c float member in the uniform block. Watch out for the + \l{https://registry.khronos.org/OpenGL/specs/gl/glspec45.core.pdf#page=159}{std140 + layout rules}. This presents no surprises in this example since the \c + float member that follows the \c mat4 has the correct alignment without any + additional padding, but it may become relevant in other applications, + especially when working with types such as \c vec2 or \c vec3. When in + doubt, consider checking the QShaderDescription for the + \l{QShader::description()}{QShader}, or, what is often more convenient, run + the \c qsb tool on the \c{.qsb} file with the \c{-d} argument to inspect + the metadata in human-readable form. The printed information includes, + among other things, the uniform block member offsets, sizes, and the total + size in bytes of each uniform block. + + \snippet rhiwindow/rhiwindow.cpp render-init-1 + + The vertex and fragment shaders both need a uniform buffer at binding point + 0. This is ensured by the QRhiShaderResourceBindings object. The graphics + pipeline is then setup with the shaders and a number of additional + information. The example also relies on a number of convenient defaults, + e.g. the primitive topology is + \l{QRhiGraphicsPipeline::Triangles}{Triangles}, but that is the default, + and therefore it is not explicitly set. See QRhiGraphicsPipeline for + further details. + + In addition to specifying the topology and various state, the pipeline must + also be associated with: + + \list + + \li The vertex input layout in form of a QRhiVertexInputLayout. This + specifies the type and component count for each vertex input location, the + total stride in bytes per vertex, and other related data. + QRhiVertexInputLayout only holds data, not actual native resources, and is + copiable. + + \li A valid and successfully initialized QRhiShaderResourceBindings object. + This describes the layout of the resource bindings (uniform buffers, + textures, samplers) the shaders expect. This must either by the + QRhiShaderResourceBindings used when recording the draw calls, or another + that is + \l{QRhiShaderResourceBindings::isLayoutCompatible()}{layout-compatible with it}. + This simple application takes the former approach. + + \li A valid QRhiRenderPassDescriptor object. This must be retrieved from, + or \l{QRhiRenderPassDescriptor::isCompatible()}{be compatible with} the + render target. The example uses the former, by creating a + QRhiRenderPassDescriptor object via + QRhiSwapChain::newCompatibleRenderPassDescriptor(). + + \endlist + + \snippet rhiwindow/rhiwindow.cpp render-init-2 + + getShader() is a helper function that loads a \c{.qsb} file and + deserializes a QShader from it. + + \snippet rhiwindow/rhiwindow.cpp getshader + + The \c{color.vert} shader specifies the following as the vertex inputs: + + \badcode + layout(location = 0) in vec4 position; + layout(location = 1) in vec3 color; + \endcode + + The C++ code however provides vertex data as 2 floats for position, with 3 + floats for the color interleaved. (\c x, \c y, \c r, \c g, \c b for each + vertex) This is why the stride is \c{5 * sizeof(float)} and the inputs for + locations 0 and 1 are specified as \c Float2 and \c Float3, respectively. + This is valid, and the \c z and \c w of the \c vec4 position will get set + automatically. + + \section1 Rendering + + Recording a frame is started by calling \l{QRhi::beginFrame()} and finished + by calling \l{QRhi::endFrame()}. + + \snippet rhiwindow/rhiwindow.cpp beginframe + + Some of the resources (buffers, textures) have static data in the + application, meaning the content never changes. The vertex buffer's content + is provided in the initialization step for example, and is not changed + afterwards. These data update operations are recorded in \c + m_initialUpdates. When not yet done, the commands on this resource update + batch are merged into the per-frame batch. + + \snippet rhiwindow/rhiwindow.cpp render-1 + + Having a per-frame resource update batch is necessary since the uniform + buffer contents with the modelview-projection matrix and the opacity + changes on every frame. + + \snippet rhiwindow/rhiwindow.cpp render-rotation + + \snippet rhiwindow/rhiwindow.cpp render-opacity + + To begin recording the render pass, a QRhiCommandBuffer is queried, and the + output size is determined, which will be useful for setting up the viewport + and resizing our fullscreen texture, if needed. + + \snippet rhiwindow/rhiwindow.cpp render-cb + + Starting a render pass implies clearing the render target's color and + depth-stencil buffers (unless the render target flags indicate otherwise, + but that is only an option for texture-based render targets). Here we + specify black for color, 1.0f for depth, and 0 for stencil (unused). The + last argument, \c resourceUpdates, is what ensures that the data update + commands recorded on the batch get committed. Alternatively, we could have + used QRhiCommandBuffer::resourceUpdate() instead. The render pass targets a + swapchain, hence calling + \l{QRhiSwapChain::currentFrameRenderTarget()}{currentFrameRenderTarget()} + to get a valid QRhiRenderTarget. + + \snippet rhiwindow/rhiwindow.cpp render-pass + + Recording the draw call for the triangle is straightforward: set the + pipeline, set the shader resources, set the vertex/index buffer(s), and + record the draw call. Here we use a non-indexed draw with just 3 vertices. + + \snippet rhiwindow/rhiwindow.cpp render-pass-record + + The \l{QRhiCommandBuffer::setShaderResources()}{setShaderResources()} call + has no arguments given, which implies using \c m_colorTriSrb since that was + associated with the active QRhiGraphicsPipeline (\c m_colorPipeline). + + We will not dive into the details of the rendering of the fullscreen + background image. See the example source code for that. It is however worth + noting a common pattern for "resizing" a texture or buffer resource. There + is no such thing as changing the size of an existing native resource, so + changing a texture or buffer size must be followed by a call to create(), + to release and recreate the underlying native resources. To ensure that the + QRhiTexture always has the required size, the application implements the + following logic. Note that \c m_texture stays valid for the entire lifetime + of the window, which means object references to it, e.g. in a + QRhiShaderResourceBindings, continue to be valid all the time. It is only + the underlying native resources that come and go over time. + + Note also that we set a device pixel ratio on the image that matches + the window that we're drawing into. This ensures that the drawing code + can be DPR-agnostic, producing the same layout regardless of the DPR, + while also taking advantage of the additional pixels for improved fidelity. + + \snippet rhiwindow/rhiwindow.cpp ensure-texture + + Once a QImage is generated and the QPainter-based drawing into it has + finished, we use + \l{QRhiResourceUpdateBatch::uploadTexture()}{uploadTexture()} to record a + texture upload on the resource update batch: + + \snippet rhiwindow/rhiwindow.cpp ensure-texture-2 + + \sa QRhi, QRhiSwapChain, QWindow, QRhiCommandBuffer, QRhiResourceUpdateBatch, QRhiBuffer, QRhiTexture + */ diff --git a/examples/gui/gui.pro b/examples/gui/gui.pro index 275adc804d..0696458db1 100644 --- a/examples/gui/gui.pro +++ b/examples/gui/gui.pro @@ -4,5 +4,5 @@ TEMPLATE = subdirs QT_FOR_CONFIG += gui CONFIG += no_docs_target -SUBDIRS += analogclock -SUBDIRS += rasterwindow +SUBDIRS += rasterwindow \ + rhiwindow diff --git a/examples/gui/rasterwindow/.prev_CMakeLists.txt b/examples/gui/rasterwindow/.prev_CMakeLists.txt deleted file mode 100644 index 3f27ea597c..0000000000 --- a/examples/gui/rasterwindow/.prev_CMakeLists.txt +++ /dev/null @@ -1,34 +0,0 @@ -# Generated from rasterwindow.pro. - -cmake_minimum_required(VERSION 3.14) -project(rasterwindow LANGUAGES CXX) - -set(CMAKE_INCLUDE_CURRENT_DIR ON) - -set(CMAKE_AUTOMOC ON) -set(CMAKE_AUTORCC ON) -set(CMAKE_AUTOUIC ON) - -set(INSTALL_EXAMPLEDIR "examples/gui/rasterwindow") - -find_package(Qt6 COMPONENTS Core) -find_package(Qt6 COMPONENTS Gui) - -add_qt_gui_executable(rasterwindow - main.cpp - rasterwindow.cpp rasterwindow.h -) -target_include_directories(rasterwindow PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR} -) - -target_link_libraries(rasterwindow PUBLIC - Qt::Core - Qt::Gui -) - -install(TARGETS rasterwindow - RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}" - BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}" - LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}" -) diff --git a/examples/gui/rasterwindow/CMakeLists.txt b/examples/gui/rasterwindow/CMakeLists.txt index 555578725e..7fb00895c9 100644 --- a/examples/gui/rasterwindow/CMakeLists.txt +++ b/examples/gui/rasterwindow/CMakeLists.txt @@ -1,35 +1,37 @@ -# Generated from rasterwindow.pro. +# Copyright (C) 2022 The Qt Company Ltd. +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause -cmake_minimum_required(VERSION 3.14) +cmake_minimum_required(VERSION 3.16) project(rasterwindow LANGUAGES CXX) -find_package(Qt6 COMPONENTS Widgets) # special case: add +find_package(Qt6 REQUIRED COMPONENTS Core Gui) -set(CMAKE_INCLUDE_CURRENT_DIR ON) +qt_standard_project_setup() -set(CMAKE_AUTOMOC ON) -set(CMAKE_AUTORCC ON) -set(CMAKE_AUTOUIC ON) - -set(INSTALL_EXAMPLEDIR "examples/gui/rasterwindow") - -find_package(Qt6 COMPONENTS Core) -find_package(Qt6 COMPONENTS Gui) - -add_qt_gui_executable(rasterwindow +qt_add_executable(rasterwindow main.cpp rasterwindow.cpp rasterwindow.h ) -target_include_directories(rasterwindow PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR} + +set_target_properties(rasterwindow PROPERTIES + WIN32_EXECUTABLE TRUE + MACOSX_BUNDLE TRUE ) -target_link_libraries(rasterwindow PUBLIC - Qt::Core - Qt::Gui + +target_link_libraries(rasterwindow PRIVATE + Qt6::Core + Qt6::Gui ) install(TARGETS rasterwindow - RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}" - BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}" - LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}" + BUNDLE DESTINATION . + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} +) + +qt_generate_deploy_app_script( + TARGET rasterwindow + OUTPUT_SCRIPT deploy_script + NO_UNSUPPORTED_PLATFORM_ERROR ) +install(SCRIPT ${deploy_script}) diff --git a/examples/gui/rasterwindow/main.cpp b/examples/gui/rasterwindow/main.cpp index bd5c0df1fc..e70e98dcd5 100644 --- a/examples/gui/rasterwindow/main.cpp +++ b/examples/gui/rasterwindow/main.cpp @@ -1,52 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:BSD$ -** 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. -** -** BSD License Usage -** Alternatively, you may use this file under the terms of the BSD license -** as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of The Qt Company Ltd nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause #include "rasterwindow.h" diff --git a/examples/gui/rasterwindow/rasterwindow.cpp b/examples/gui/rasterwindow/rasterwindow.cpp index 4dd2ac25ca..185ea76734 100644 --- a/examples/gui/rasterwindow/rasterwindow.cpp +++ b/examples/gui/rasterwindow/rasterwindow.cpp @@ -1,52 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:BSD$ -** 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. -** -** BSD License Usage -** Alternatively, you may use this file under the terms of the BSD license -** as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of The Qt Company Ltd nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause #include "rasterwindow.h" diff --git a/examples/gui/rasterwindow/rasterwindow.h b/examples/gui/rasterwindow/rasterwindow.h index 2ccecbf704..504737dacf 100644 --- a/examples/gui/rasterwindow/rasterwindow.h +++ b/examples/gui/rasterwindow/rasterwindow.h @@ -1,64 +1,18 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:BSD$ -** 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. -** -** BSD License Usage -** Alternatively, you may use this file under the terms of the BSD license -** as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of The Qt Company Ltd nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause #ifndef RASTERWINDOW_H #define RASTERWINDOW_H //! [1] #include <QtGui> +#include <QScopedPointer> class RasterWindow : public QWindow { Q_OBJECT public: - explicit RasterWindow(QWindow *parent = 0); + explicit RasterWindow(QWindow *parent = nullptr); virtual void render(QPainter *painter); @@ -73,7 +27,7 @@ protected: void exposeEvent(QExposeEvent *event) override; private: - QBackingStore *m_backingStore; + QScopedPointer<QBackingStore> m_backingStore; }; //! [1] #endif // RASTERWINDOW_H diff --git a/examples/gui/rhiwindow/CMakeLists.txt b/examples/gui/rhiwindow/CMakeLists.txt new file mode 100644 index 0000000000..49b36286ee --- /dev/null +++ b/examples/gui/rhiwindow/CMakeLists.txt @@ -0,0 +1,60 @@ +# Copyright (C) 2023 The Qt Company Ltd. +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause + +cmake_minimum_required(VERSION 3.16) +project(rhiwindow LANGUAGES CXX) + +find_package(Qt6 REQUIRED COMPONENTS Core Gui) + +qt_standard_project_setup() + +qt_add_executable(rhiwindow + main.cpp + rhiwindow.cpp rhiwindow.h +) + +set_target_properties(rhiwindow PROPERTIES + WIN32_EXECUTABLE TRUE + MACOSX_BUNDLE TRUE +) + +target_link_libraries(rhiwindow PRIVATE + Qt6::Core + Qt6::Gui + Qt6::GuiPrivate +) + +set_source_files_properties("shaders/prebuilt/color.vert.qsb" + PROPERTIES QT_RESOURCE_ALIAS "color.vert.qsb" +) +set_source_files_properties("shaders/prebuilt/color.frag.qsb" + PROPERTIES QT_RESOURCE_ALIAS "color.frag.qsb" +) +set_source_files_properties("shaders/prebuilt/quad.vert.qsb" + PROPERTIES QT_RESOURCE_ALIAS "quad.vert.qsb" +) +set_source_files_properties("shaders/prebuilt/quad.frag.qsb" + PROPERTIES QT_RESOURCE_ALIAS "quad.frag.qsb" +) +qt_add_resources(rhiwindow "rhiwindow" + PREFIX + "/" + FILES + "shaders/prebuilt/color.vert.qsb" + "shaders/prebuilt/color.frag.qsb" + "shaders/prebuilt/quad.vert.qsb" + "shaders/prebuilt/quad.frag.qsb" +) + +install(TARGETS rhiwindow + BUNDLE DESTINATION . + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} +) + +qt_generate_deploy_app_script( + TARGET rhiwindow + OUTPUT_SCRIPT deploy_script + NO_UNSUPPORTED_PLATFORM_ERROR +) +install(SCRIPT ${deploy_script}) diff --git a/examples/gui/rhiwindow/main.cpp b/examples/gui/rhiwindow/main.cpp new file mode 100644 index 0000000000..37977e3a34 --- /dev/null +++ b/examples/gui/rhiwindow/main.cpp @@ -0,0 +1,110 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause + +#include <QGuiApplication> +#include <QCommandLineParser> +#include "rhiwindow.h" + +int main(int argc, char **argv) +{ + QGuiApplication app(argc, argv); + + QRhi::Implementation graphicsApi; + + // Use platform-specific defaults when no command-line arguments given. +#if defined(Q_OS_WIN) + graphicsApi = QRhi::D3D11; +#elif QT_CONFIG(metal) + graphicsApi = QRhi::Metal; +#elif QT_CONFIG(vulkan) + graphicsApi = QRhi::Vulkan; +#else + graphicsApi = QRhi::OpenGLES2; +#endif + + QCommandLineParser cmdLineParser; + cmdLineParser.addHelpOption(); + QCommandLineOption nullOption({ "n", "null" }, QLatin1String("Null")); + cmdLineParser.addOption(nullOption); + QCommandLineOption glOption({ "g", "opengl" }, QLatin1String("OpenGL")); + cmdLineParser.addOption(glOption); + QCommandLineOption vkOption({ "v", "vulkan" }, QLatin1String("Vulkan")); + cmdLineParser.addOption(vkOption); + QCommandLineOption d3d11Option({ "d", "d3d11" }, QLatin1String("Direct3D 11")); + cmdLineParser.addOption(d3d11Option); + QCommandLineOption d3d12Option({ "D", "d3d12" }, QLatin1String("Direct3D 12")); + cmdLineParser.addOption(d3d12Option); + QCommandLineOption mtlOption({ "m", "metal" }, QLatin1String("Metal")); + cmdLineParser.addOption(mtlOption); + + cmdLineParser.process(app); + if (cmdLineParser.isSet(nullOption)) + graphicsApi = QRhi::Null; + if (cmdLineParser.isSet(glOption)) + graphicsApi = QRhi::OpenGLES2; + if (cmdLineParser.isSet(vkOption)) + graphicsApi = QRhi::Vulkan; + if (cmdLineParser.isSet(d3d11Option)) + graphicsApi = QRhi::D3D11; + if (cmdLineParser.isSet(d3d12Option)) + graphicsApi = QRhi::D3D12; + if (cmdLineParser.isSet(mtlOption)) + graphicsApi = QRhi::Metal; + + //! [api-setup] + // For OpenGL, to ensure there is a depth/stencil buffer for the window. + // With other APIs this is under the application's control (QRhiRenderBuffer etc.) + // and so no special setup is needed for those. + QSurfaceFormat fmt; + fmt.setDepthBufferSize(24); + fmt.setStencilBufferSize(8); + // Special case macOS to allow using OpenGL there. + // (the default Metal is the recommended approach, though) + // gl_VertexID is a GLSL 130 feature, and so the default OpenGL 2.1 context + // we get on macOS is not sufficient. +#ifdef Q_OS_MACOS + fmt.setVersion(4, 1); + fmt.setProfile(QSurfaceFormat::CoreProfile); +#endif + QSurfaceFormat::setDefaultFormat(fmt); + + // For Vulkan. +#if QT_CONFIG(vulkan) + QVulkanInstance inst; + if (graphicsApi == QRhi::Vulkan) { + // Request validation, if available. This is completely optional + // and has a performance impact, and should be avoided in production use. + inst.setLayers({ "VK_LAYER_KHRONOS_validation" }); + // Play nice with QRhi. + inst.setExtensions(QRhiVulkanInitParams::preferredInstanceExtensions()); + if (!inst.create()) { + qWarning("Failed to create Vulkan instance, switching to OpenGL"); + graphicsApi = QRhi::OpenGLES2; + } + } +#endif +//! [api-setup] + + HelloWindow window(graphicsApi); + +#if QT_CONFIG(vulkan) + if (graphicsApi == QRhi::Vulkan) + window.setVulkanInstance(&inst); +#endif + window.resize(1280, 720); + window.setTitle(QCoreApplication::applicationName() + QLatin1String(" - ") + window.graphicsApiName()); + window.show(); + + int ret = app.exec(); + + // RhiWindow::event() will not get invoked when the + // PlatformSurfaceAboutToBeDestroyed event is sent during the QWindow + // destruction. That happens only when exiting via app::quit() instead of + // the more common QWindow::close(). Take care of it: if the QPlatformWindow + // is still around (there was no close() yet), get rid of the swapchain + // while it's not too late. + if (window.handle()) + window.releaseSwapChain(); + + return ret; +} diff --git a/examples/gui/rhiwindow/rhiwindow.cpp b/examples/gui/rhiwindow/rhiwindow.cpp new file mode 100644 index 0000000000..3ae6faa802 --- /dev/null +++ b/examples/gui/rhiwindow/rhiwindow.cpp @@ -0,0 +1,436 @@ +// Copyright (C) 2020 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause + +#include "rhiwindow.h" +#include <QPlatformSurfaceEvent> +#include <QPainter> +#include <QFile> +#include <rhi/qshader.h> + +//! [rhiwindow-ctor] +RhiWindow::RhiWindow(QRhi::Implementation graphicsApi) + : m_graphicsApi(graphicsApi) +{ + switch (graphicsApi) { + case QRhi::OpenGLES2: + setSurfaceType(OpenGLSurface); + break; + case QRhi::Vulkan: + setSurfaceType(VulkanSurface); + break; + case QRhi::D3D11: + case QRhi::D3D12: + setSurfaceType(Direct3DSurface); + break; + case QRhi::Metal: + setSurfaceType(MetalSurface); + break; + case QRhi::Null: + break; // RasterSurface + } +} +//! [rhiwindow-ctor] + +QString RhiWindow::graphicsApiName() const +{ + switch (m_graphicsApi) { + case QRhi::Null: + return QLatin1String("Null (no output)"); + case QRhi::OpenGLES2: + return QLatin1String("OpenGL"); + case QRhi::Vulkan: + return QLatin1String("Vulkan"); + case QRhi::D3D11: + return QLatin1String("Direct3D 11"); + case QRhi::D3D12: + return QLatin1String("Direct3D 12"); + case QRhi::Metal: + return QLatin1String("Metal"); + } + return QString(); +} + +//! [expose] +void RhiWindow::exposeEvent(QExposeEvent *) +{ + // initialize and start rendering when the window becomes usable for graphics purposes + if (isExposed() && !m_initialized) { + init(); + resizeSwapChain(); + m_initialized = true; + } + + const QSize surfaceSize = m_hasSwapChain ? m_sc->surfacePixelSize() : QSize(); + + // stop pushing frames when not exposed (or size is 0) + if ((!isExposed() || (m_hasSwapChain && surfaceSize.isEmpty())) && m_initialized && !m_notExposed) + m_notExposed = true; + + // Continue when exposed again and the surface has a valid size. Note that + // surfaceSize can be (0, 0) even though size() reports a valid one, hence + // trusting surfacePixelSize() and not QWindow. + if (isExposed() && m_initialized && m_notExposed && !surfaceSize.isEmpty()) { + m_notExposed = false; + m_newlyExposed = true; + } + + // always render a frame on exposeEvent() (when exposed) in order to update + // immediately on window resize. + if (isExposed() && !surfaceSize.isEmpty()) + render(); +} +//! [expose] + +//! [event] +bool RhiWindow::event(QEvent *e) +{ + switch (e->type()) { + case QEvent::UpdateRequest: + render(); + break; + + case QEvent::PlatformSurface: + // this is the proper time to tear down the swapchain (while the native window and surface are still around) + if (static_cast<QPlatformSurfaceEvent *>(e)->surfaceEventType() == QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed) + releaseSwapChain(); + break; + + default: + break; + } + + return QWindow::event(e); +} +//! [event] + +//! [rhi-init] +void RhiWindow::init() +{ + if (m_graphicsApi == QRhi::Null) { + QRhiNullInitParams params; + m_rhi.reset(QRhi::create(QRhi::Null, ¶ms)); + } + +#if QT_CONFIG(opengl) + if (m_graphicsApi == QRhi::OpenGLES2) { + m_fallbackSurface.reset(QRhiGles2InitParams::newFallbackSurface()); + QRhiGles2InitParams params; + params.fallbackSurface = m_fallbackSurface.get(); + params.window = this; + m_rhi.reset(QRhi::create(QRhi::OpenGLES2, ¶ms)); + } +#endif + +#if QT_CONFIG(vulkan) + if (m_graphicsApi == QRhi::Vulkan) { + QRhiVulkanInitParams params; + params.inst = vulkanInstance(); + params.window = this; + m_rhi.reset(QRhi::create(QRhi::Vulkan, ¶ms)); + } +#endif + +#ifdef Q_OS_WIN + if (m_graphicsApi == QRhi::D3D11) { + QRhiD3D11InitParams params; + // Enable the debug layer, if available. This is optional + // and should be avoided in production builds. + params.enableDebugLayer = true; + m_rhi.reset(QRhi::create(QRhi::D3D11, ¶ms)); + } else if (m_graphicsApi == QRhi::D3D12) { + QRhiD3D12InitParams params; + // Enable the debug layer, if available. This is optional + // and should be avoided in production builds. + params.enableDebugLayer = true; + m_rhi.reset(QRhi::create(QRhi::D3D12, ¶ms)); + } +#endif + +#if QT_CONFIG(metal) + if (m_graphicsApi == QRhi::Metal) { + QRhiMetalInitParams params; + m_rhi.reset(QRhi::create(QRhi::Metal, ¶ms)); + } +#endif + + if (!m_rhi) + qFatal("Failed to create RHI backend"); +//! [rhi-init] + +//! [swapchain-init] + m_sc.reset(m_rhi->newSwapChain()); + m_ds.reset(m_rhi->newRenderBuffer(QRhiRenderBuffer::DepthStencil, + QSize(), // no need to set the size here, due to UsedWithSwapChainOnly + 1, + QRhiRenderBuffer::UsedWithSwapChainOnly)); + m_sc->setWindow(this); + m_sc->setDepthStencil(m_ds.get()); + m_rp.reset(m_sc->newCompatibleRenderPassDescriptor()); + m_sc->setRenderPassDescriptor(m_rp.get()); +//! [swapchain-init] + + customInit(); +} + +//! [swapchain-resize] +void RhiWindow::resizeSwapChain() +{ + m_hasSwapChain = m_sc->createOrResize(); // also handles m_ds + + const QSize outputSize = m_sc->currentPixelSize(); + m_viewProjection = m_rhi->clipSpaceCorrMatrix(); + m_viewProjection.perspective(45.0f, outputSize.width() / (float) outputSize.height(), 0.01f, 1000.0f); + m_viewProjection.translate(0, 0, -4); +} +//! [swapchain-resize] + +void RhiWindow::releaseSwapChain() +{ + if (m_hasSwapChain) { + m_hasSwapChain = false; + m_sc->destroy(); + } +} + +//! [render-precheck] +void RhiWindow::render() +{ + if (!m_hasSwapChain || m_notExposed) + return; +//! [render-precheck] + +//! [render-resize] + // If the window got resized or newly exposed, resize the swapchain. (the + // newly-exposed case is not actually required by some platforms, but is + // here for robustness and portability) + // + // This (exposeEvent + the logic here) is the only safe way to perform + // resize handling. Note the usage of the RHI's surfacePixelSize(), and + // never QWindow::size(). (the two may or may not be the same under the hood, + // depending on the backend and platform) + // + if (m_sc->currentPixelSize() != m_sc->surfacePixelSize() || m_newlyExposed) { + resizeSwapChain(); + if (!m_hasSwapChain) + return; + m_newlyExposed = false; + } +//! [render-resize] + +//! [beginframe] + QRhi::FrameOpResult result = m_rhi->beginFrame(m_sc.get()); + if (result == QRhi::FrameOpSwapChainOutOfDate) { + resizeSwapChain(); + if (!m_hasSwapChain) + return; + result = m_rhi->beginFrame(m_sc.get()); + } + if (result != QRhi::FrameOpSuccess) { + qWarning("beginFrame failed with %d, will retry", result); + requestUpdate(); + return; + } + + customRender(); +//! [beginframe] + +//! [request-update] + m_rhi->endFrame(m_sc.get()); + + // Always request the next frame via requestUpdate(). On some platforms this is backed + // by a platform-specific solution, e.g. CVDisplayLink on macOS, which is potentially + // more efficient than a timer, queued metacalls, etc. + requestUpdate(); +} +//! [request-update] + +static float vertexData[] = { + // Y up (note clipSpaceCorrMatrix in m_viewProjection), CCW + 0.0f, 0.5f, 1.0f, 0.0f, 0.0f, + -0.5f, -0.5f, 0.0f, 1.0f, 0.0f, + 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, +}; + +//! [getshader] +static QShader getShader(const QString &name) +{ + QFile f(name); + if (f.open(QIODevice::ReadOnly)) + return QShader::fromSerialized(f.readAll()); + + return QShader(); +} +//! [getshader] + +HelloWindow::HelloWindow(QRhi::Implementation graphicsApi) + : RhiWindow(graphicsApi) +{ +} + +//! [ensure-texture] +void HelloWindow::ensureFullscreenTexture(const QSize &pixelSize, QRhiResourceUpdateBatch *u) +{ + if (m_texture && m_texture->pixelSize() == pixelSize) + return; + + if (!m_texture) + m_texture.reset(m_rhi->newTexture(QRhiTexture::RGBA8, pixelSize)); + else + m_texture->setPixelSize(pixelSize); + + m_texture->create(); + + QImage image(pixelSize, QImage::Format_RGBA8888_Premultiplied); + image.setDevicePixelRatio(devicePixelRatio()); +//! [ensure-texture] + QPainter painter(&image); + painter.fillRect(QRectF(QPointF(0, 0), size()), QColor::fromRgbF(0.4f, 0.7f, 0.0f, 1.0f)); + painter.setPen(Qt::transparent); + painter.setBrush({ QGradient(QGradient::DeepBlue) }); + painter.drawRoundedRect(QRectF(QPointF(20, 20), size() - QSize(40, 40)), 16, 16); + painter.setPen(Qt::black); + QFont font; + font.setPixelSize(0.05 * qMin(width(), height())); + painter.setFont(font); + painter.drawText(QRectF(QPointF(60, 60), size() - QSize(120, 120)), 0, + QLatin1String("Rendering with QRhi to a resizable QWindow.\nThe 3D API is %1.\nUse the command-line options to choose a different API.") + .arg(graphicsApiName())); + painter.end(); + + if (m_rhi->isYUpInNDC()) + image = image.mirrored(); + +//! [ensure-texture-2] + u->uploadTexture(m_texture.get(), image); +//! [ensure-texture-2] +} + +//! [render-init-1] +void HelloWindow::customInit() +{ + m_initialUpdates = m_rhi->nextResourceUpdateBatch(); + + m_vbuf.reset(m_rhi->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer, sizeof(vertexData))); + m_vbuf->create(); + m_initialUpdates->uploadStaticBuffer(m_vbuf.get(), vertexData); + + static const quint32 UBUF_SIZE = 68; + m_ubuf.reset(m_rhi->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, UBUF_SIZE)); + m_ubuf->create(); +//! [render-init-1] + + ensureFullscreenTexture(m_sc->surfacePixelSize(), m_initialUpdates); + + m_sampler.reset(m_rhi->newSampler(QRhiSampler::Linear, QRhiSampler::Linear, QRhiSampler::None, + QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge)); + m_sampler->create(); + + //! [render-init-2] + m_colorTriSrb.reset(m_rhi->newShaderResourceBindings()); + static const QRhiShaderResourceBinding::StageFlags visibility = + QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage; + m_colorTriSrb->setBindings({ + QRhiShaderResourceBinding::uniformBuffer(0, visibility, m_ubuf.get()) + }); + m_colorTriSrb->create(); + + m_colorPipeline.reset(m_rhi->newGraphicsPipeline()); + // Enable depth testing; not quite needed for a simple triangle, but we + // have a depth-stencil buffer so why not. + m_colorPipeline->setDepthTest(true); + m_colorPipeline->setDepthWrite(true); + // Blend factors default to One, OneOneMinusSrcAlpha, which is convenient. + QRhiGraphicsPipeline::TargetBlend premulAlphaBlend; + premulAlphaBlend.enable = true; + m_colorPipeline->setTargetBlends({ premulAlphaBlend }); + m_colorPipeline->setShaderStages({ + { QRhiShaderStage::Vertex, getShader(QLatin1String(":/color.vert.qsb")) }, + { QRhiShaderStage::Fragment, getShader(QLatin1String(":/color.frag.qsb")) } + }); + QRhiVertexInputLayout inputLayout; + inputLayout.setBindings({ + { 5 * sizeof(float) } + }); + inputLayout.setAttributes({ + { 0, 0, QRhiVertexInputAttribute::Float2, 0 }, + { 0, 1, QRhiVertexInputAttribute::Float3, 2 * sizeof(float) } + }); + m_colorPipeline->setVertexInputLayout(inputLayout); + m_colorPipeline->setShaderResourceBindings(m_colorTriSrb.get()); + m_colorPipeline->setRenderPassDescriptor(m_rp.get()); + m_colorPipeline->create(); +//! [render-init-2] + + m_fullscreenQuadSrb.reset(m_rhi->newShaderResourceBindings()); + m_fullscreenQuadSrb->setBindings({ + QRhiShaderResourceBinding::sampledTexture(0, QRhiShaderResourceBinding::FragmentStage, + m_texture.get(), m_sampler.get()) + }); + m_fullscreenQuadSrb->create(); + + m_fullscreenQuadPipeline.reset(m_rhi->newGraphicsPipeline()); + m_fullscreenQuadPipeline->setShaderStages({ + { QRhiShaderStage::Vertex, getShader(QLatin1String(":/quad.vert.qsb")) }, + { QRhiShaderStage::Fragment, getShader(QLatin1String(":/quad.frag.qsb")) } + }); + m_fullscreenQuadPipeline->setVertexInputLayout({}); + m_fullscreenQuadPipeline->setShaderResourceBindings(m_fullscreenQuadSrb.get()); + m_fullscreenQuadPipeline->setRenderPassDescriptor(m_rp.get()); + m_fullscreenQuadPipeline->create(); +} + +//! [render-1] +void HelloWindow::customRender() +{ + QRhiResourceUpdateBatch *resourceUpdates = m_rhi->nextResourceUpdateBatch(); + + if (m_initialUpdates) { + resourceUpdates->merge(m_initialUpdates); + m_initialUpdates->release(); + m_initialUpdates = nullptr; + } +//! [render-1] + +//! [render-rotation] + m_rotation += 1.0f; + QMatrix4x4 modelViewProjection = m_viewProjection; + modelViewProjection.rotate(m_rotation, 0, 1, 0); + resourceUpdates->updateDynamicBuffer(m_ubuf.get(), 0, 64, modelViewProjection.constData()); +//! [render-rotation] + +//! [render-opacity] + m_opacity += m_opacityDir * 0.005f; + if (m_opacity < 0.0f || m_opacity > 1.0f) { + m_opacityDir *= -1; + m_opacity = qBound(0.0f, m_opacity, 1.0f); + } + resourceUpdates->updateDynamicBuffer(m_ubuf.get(), 64, 4, &m_opacity); +//! [render-opacity] + +//! [render-cb] + QRhiCommandBuffer *cb = m_sc->currentFrameCommandBuffer(); + const QSize outputSizeInPixels = m_sc->currentPixelSize(); +//! [render-cb] + + // (re)create the texture with a size matching the output surface size, when necessary. + ensureFullscreenTexture(outputSizeInPixels, resourceUpdates); + +//! [render-pass] + cb->beginPass(m_sc->currentFrameRenderTarget(), Qt::black, { 1.0f, 0 }, resourceUpdates); +//! [render-pass] + + cb->setGraphicsPipeline(m_fullscreenQuadPipeline.get()); + cb->setViewport({ 0, 0, float(outputSizeInPixels.width()), float(outputSizeInPixels.height()) }); + cb->setShaderResources(); + cb->draw(3); + +//! [render-pass-record] + cb->setGraphicsPipeline(m_colorPipeline.get()); + cb->setShaderResources(); + const QRhiCommandBuffer::VertexInput vbufBinding(m_vbuf.get(), 0); + cb->setVertexInput(0, 1, &vbufBinding); + cb->draw(3); + + cb->endPass(); +//! [render-pass-record] +} diff --git a/examples/gui/rhiwindow/rhiwindow.h b/examples/gui/rhiwindow/rhiwindow.h new file mode 100644 index 0000000000..520c3e8c0a --- /dev/null +++ b/examples/gui/rhiwindow/rhiwindow.h @@ -0,0 +1,78 @@ +// Copyright (C) 2020 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause + +#ifndef WINDOW_H +#define WINDOW_H + +#include <QWindow> +#include <QOffscreenSurface> +#include <rhi/qrhi.h> + +class RhiWindow : public QWindow +{ +public: + RhiWindow(QRhi::Implementation graphicsApi); + QString graphicsApiName() const; + void releaseSwapChain(); + +protected: + virtual void customInit() = 0; + virtual void customRender() = 0; + + // destruction order matters to a certain degree: the fallbackSurface must + // outlive the rhi, the rhi must outlive all other resources. The resources + // need no special order when destroying. +#if QT_CONFIG(opengl) + std::unique_ptr<QOffscreenSurface> m_fallbackSurface; +#endif + std::unique_ptr<QRhi> m_rhi; +//! [swapchain-data] + std::unique_ptr<QRhiSwapChain> m_sc; + std::unique_ptr<QRhiRenderBuffer> m_ds; + std::unique_ptr<QRhiRenderPassDescriptor> m_rp; +//! [swapchain-data] + bool m_hasSwapChain = false; + QMatrix4x4 m_viewProjection; + +private: + void init(); + void resizeSwapChain(); + void render(); + + void exposeEvent(QExposeEvent *) override; + bool event(QEvent *) override; + + QRhi::Implementation m_graphicsApi; + bool m_initialized = false; + bool m_notExposed = false; + bool m_newlyExposed = false; +}; + +class HelloWindow : public RhiWindow +{ +public: + HelloWindow(QRhi::Implementation graphicsApi); + + void customInit() override; + void customRender() override; + +private: + void ensureFullscreenTexture(const QSize &pixelSize, QRhiResourceUpdateBatch *u); + + std::unique_ptr<QRhiBuffer> m_vbuf; + std::unique_ptr<QRhiBuffer> m_ubuf; + std::unique_ptr<QRhiTexture> m_texture; + std::unique_ptr<QRhiSampler> m_sampler; + std::unique_ptr<QRhiShaderResourceBindings> m_colorTriSrb; + std::unique_ptr<QRhiGraphicsPipeline> m_colorPipeline; + std::unique_ptr<QRhiShaderResourceBindings> m_fullscreenQuadSrb; + std::unique_ptr<QRhiGraphicsPipeline> m_fullscreenQuadPipeline; + + QRhiResourceUpdateBatch *m_initialUpdates = nullptr; + + float m_rotation = 0; + float m_opacity = 1; + int m_opacityDir = -1; +}; + +#endif diff --git a/examples/gui/rhiwindow/rhiwindow.pri b/examples/gui/rhiwindow/rhiwindow.pri new file mode 100644 index 0000000000..d0ef7a2699 --- /dev/null +++ b/examples/gui/rhiwindow/rhiwindow.pri @@ -0,0 +1,4 @@ +INCLUDEPATH += $$PWD +SOURCES += $$PWD/rhiwindow.cpp +HEADERS += $$PWD/rhiwindow.h +RESOURCES += $$PWD/rhiwindow.qrc diff --git a/examples/gui/rhiwindow/rhiwindow.pro b/examples/gui/rhiwindow/rhiwindow.pro new file mode 100644 index 0000000000..18f259aaf6 --- /dev/null +++ b/examples/gui/rhiwindow/rhiwindow.pro @@ -0,0 +1,9 @@ +include(rhiwindow.pri) + +QT += gui-private + +SOURCES += \ + main.cpp + +target.path = $$[QT_INSTALL_EXAMPLES]/gui/rhiwindow +INSTALLS += target diff --git a/examples/gui/rhiwindow/rhiwindow.qrc b/examples/gui/rhiwindow/rhiwindow.qrc new file mode 100644 index 0000000000..1009ec5dda --- /dev/null +++ b/examples/gui/rhiwindow/rhiwindow.qrc @@ -0,0 +1,8 @@ +<!DOCTYPE RCC><RCC version="1.0"> +<qresource> + <file alias="color.vert.qsb">shaders/prebuilt/color.vert.qsb</file> + <file alias="color.frag.qsb">shaders/prebuilt/color.frag.qsb</file> + <file alias="quad.vert.qsb">shaders/prebuilt/quad.vert.qsb</file> + <file alias="quad.frag.qsb">shaders/prebuilt/quad.frag.qsb</file> +</qresource> +</RCC> diff --git a/examples/gui/rhiwindow/shaders/color.frag b/examples/gui/rhiwindow/shaders/color.frag new file mode 100644 index 0000000000..6e0a3bc91f --- /dev/null +++ b/examples/gui/rhiwindow/shaders/color.frag @@ -0,0 +1,15 @@ +#version 440 + +layout(location = 0) in vec3 v_color; + +layout(location = 0) out vec4 fragColor; + +layout(std140, binding = 0) uniform buf { + mat4 mvp; + float opacity; +}; + +void main() +{ + fragColor = vec4(v_color * opacity, opacity); +} diff --git a/examples/gui/rhiwindow/shaders/color.vert b/examples/gui/rhiwindow/shaders/color.vert new file mode 100644 index 0000000000..70852ab86c --- /dev/null +++ b/examples/gui/rhiwindow/shaders/color.vert @@ -0,0 +1,17 @@ +#version 440 + +layout(location = 0) in vec4 position; +layout(location = 1) in vec3 color; + +layout(location = 0) out vec3 v_color; + +layout(std140, binding = 0) uniform buf { + mat4 mvp; + float opacity; +}; + +void main() +{ + v_color = color; + gl_Position = mvp * position; +} diff --git a/examples/gui/rhiwindow/shaders/prebuilt/color.frag.qsb b/examples/gui/rhiwindow/shaders/prebuilt/color.frag.qsb Binary files differnew file mode 100644 index 0000000000..b4db470e5b --- /dev/null +++ b/examples/gui/rhiwindow/shaders/prebuilt/color.frag.qsb diff --git a/examples/gui/rhiwindow/shaders/prebuilt/color.vert.qsb b/examples/gui/rhiwindow/shaders/prebuilt/color.vert.qsb Binary files differnew file mode 100644 index 0000000000..ab046b77f8 --- /dev/null +++ b/examples/gui/rhiwindow/shaders/prebuilt/color.vert.qsb diff --git a/examples/gui/rhiwindow/shaders/prebuilt/quad.frag.qsb b/examples/gui/rhiwindow/shaders/prebuilt/quad.frag.qsb Binary files differnew file mode 100644 index 0000000000..c2ea3cf251 --- /dev/null +++ b/examples/gui/rhiwindow/shaders/prebuilt/quad.frag.qsb diff --git a/examples/gui/rhiwindow/shaders/prebuilt/quad.vert.qsb b/examples/gui/rhiwindow/shaders/prebuilt/quad.vert.qsb Binary files differnew file mode 100644 index 0000000000..f0b64f7500 --- /dev/null +++ b/examples/gui/rhiwindow/shaders/prebuilt/quad.vert.qsb diff --git a/examples/gui/rhiwindow/shaders/quad.frag b/examples/gui/rhiwindow/shaders/quad.frag new file mode 100644 index 0000000000..65882a4292 --- /dev/null +++ b/examples/gui/rhiwindow/shaders/quad.frag @@ -0,0 +1,11 @@ +#version 440 + +layout(location = 0) in vec2 v_uv; +layout(location = 0) out vec4 fragColor; +layout(binding = 0) uniform sampler2D tex; + +void main() +{ + vec4 c = texture(tex, v_uv); + fragColor = vec4(c.rgb * c.a, c.a); +} diff --git a/examples/gui/rhiwindow/shaders/quad.vert b/examples/gui/rhiwindow/shaders/quad.vert new file mode 100644 index 0000000000..359896d080 --- /dev/null +++ b/examples/gui/rhiwindow/shaders/quad.vert @@ -0,0 +1,10 @@ +#version 440 + +layout (location = 0) out vec2 v_uv; + +void main() +{ + // https://www.saschawillems.de/blog/2016/08/13/vulkan-tutorial-on-rendering-a-fullscreen-quad-without-buffers/ + v_uv = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2); + gl_Position = vec4(v_uv * 2.0 - 1.0, 0.0, 1.0); +} |