diff options
Diffstat (limited to 'examples')
62 files changed, 3014 insertions, 236 deletions
diff --git a/examples/examples.pro b/examples/examples.pro index a3851c6d81..4ec5ca60e2 100644 --- a/examples/examples.pro +++ b/examples/examples.pro @@ -14,7 +14,11 @@ qtHaveModule(concurrent): SUBDIRS += qtconcurrent qtHaveModule(sql): SUBDIRS += sql qtHaveModule(widgets): SUBDIRS += widgets qtHaveModule(xml): SUBDIRS += xml -qtHaveModule(gui): SUBDIRS += gui opengl +qtHaveModule(gui) { + SUBDIRS += gui + qtConfig(opengl): SUBDIRS += opengl + qtConfig(vulkan): SUBDIRS += vulkan +} aggregate.files = aggregate/examples.pro aggregate.path = $$[QT_INSTALL_EXAMPLES] diff --git a/examples/opengl/qopenglwidget/glwidget.cpp b/examples/opengl/qopenglwidget/glwidget.cpp index 21d922d713..bb7c952a26 100644 --- a/examples/opengl/qopenglwidget/glwidget.cpp +++ b/examples/opengl/qopenglwidget/glwidget.cpp @@ -61,6 +61,10 @@ const int bubbleNum = 8; +#ifndef GL_SRGB8_ALPHA8 +#define GL_SRGB8_ALPHA8 0x8C43 +#endif + GLWidget::GLWidget(MainWindow *mw, bool button, const QColor &background) : m_mainWindow(mw), m_showBubbles(true), @@ -75,6 +79,8 @@ GLWidget::GLWidget(MainWindow *mw, bool button, const QColor &background) m_background(background) { setMinimumSize(300, 250); + if (QCoreApplication::arguments().contains(QStringLiteral("--srgb"))) + setTextureFormat(GL_SRGB8_ALPHA8); } GLWidget::~GLWidget() diff --git a/examples/opengl/qopenglwidget/main.cpp b/examples/opengl/qopenglwidget/main.cpp index d7aa791142..f9b5731b8f 100644 --- a/examples/opengl/qopenglwidget/main.cpp +++ b/examples/opengl/qopenglwidget/main.cpp @@ -61,6 +61,8 @@ int main( int argc, char ** argv ) QSurfaceFormat format; format.setDepthBufferSize(24); format.setStencilBufferSize(8); + if (QCoreApplication::arguments().contains(QStringLiteral("--srgb"))) + format.setColorSpace(QSurfaceFormat::sRGBColorSpace); if (QCoreApplication::arguments().contains(QStringLiteral("--multisample"))) format.setSamples(4); QSurfaceFormat::setDefaultFormat(format); diff --git a/examples/touch/pinchzoom/mouse.cpp b/examples/touch/pinchzoom/mouse.cpp index f063e96654..3b8e6b5690 100644 --- a/examples/touch/pinchzoom/mouse.cpp +++ b/examples/touch/pinchzoom/mouse.cpp @@ -54,7 +54,7 @@ #include <QPainter> #include <QStyleOption> -#include <math.h> +#include <cmath> static const double Pi = 3.14159265358979323846264338327950288419717; static double TwoPi = 2.0 * Pi; @@ -139,9 +139,7 @@ void Mouse::timerEvent(QTimerEvent *) //! [5] QLineF lineToCenter(QPointF(0, 0), mapFromScene(0, 0)); if (lineToCenter.length() > 150) { - qreal angleToCenter = ::acos(lineToCenter.dx() / lineToCenter.length()); - if (lineToCenter.dy() < 0) - angleToCenter = TwoPi - angleToCenter; + qreal angleToCenter = std::atan2(lineToCenter.dy(), lineToCenter.dx()); angleToCenter = normalizeAngle((Pi - angleToCenter) + Pi / 2); if (angleToCenter < Pi && angleToCenter > Pi / 4) { @@ -170,9 +168,7 @@ void Mouse::timerEvent(QTimerEvent *) continue; QLineF lineToMouse(QPointF(0, 0), mapFromItem(item, 0, 0)); - qreal angleToMouse = ::acos(lineToMouse.dx() / lineToMouse.length()); - if (lineToMouse.dy() < 0) - angleToMouse = TwoPi - angleToMouse; + qreal angleToMouse = std::atan2(lineToMouse.dy(), lineToMouse.dx()); angleToMouse = normalizeAngle((Pi - angleToMouse) + Pi / 2); if (angleToMouse >= 0 && angleToMouse < Pi / 2) { diff --git a/examples/vulkan/doc/images/hellovulkantexture.png b/examples/vulkan/doc/images/hellovulkantexture.png Binary files differnew file mode 100644 index 0000000000..0cb47a70be --- /dev/null +++ b/examples/vulkan/doc/images/hellovulkantexture.png diff --git a/examples/vulkan/doc/images/hellovulkantriangle.png b/examples/vulkan/doc/images/hellovulkantriangle.png Binary files differnew file mode 100644 index 0000000000..f88b27a873 --- /dev/null +++ b/examples/vulkan/doc/images/hellovulkantriangle.png diff --git a/examples/vulkan/doc/images/hellovulkanwidget.png b/examples/vulkan/doc/images/hellovulkanwidget.png Binary files differnew file mode 100644 index 0000000000..b85d4dc596 --- /dev/null +++ b/examples/vulkan/doc/images/hellovulkanwidget.png diff --git a/examples/vulkan/doc/images/hellovulkanwindow.png b/examples/vulkan/doc/images/hellovulkanwindow.png Binary files differnew file mode 100644 index 0000000000..c55029312c --- /dev/null +++ b/examples/vulkan/doc/images/hellovulkanwindow.png diff --git a/examples/vulkan/doc/src/hellovulkantexture.qdoc b/examples/vulkan/doc/src/hellovulkantexture.qdoc new file mode 100644 index 0000000000..d0e0ca90a8 --- /dev/null +++ b/examples/vulkan/doc/src/hellovulkantexture.qdoc @@ -0,0 +1,41 @@ +/**************************************************************************** +** +** Copyright (C) 2017 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 hellovulkantexture + \ingroup examples-vulkan + \title Hello Vulkan Texture Vulkan Example + \brief Shows the basics of rendering with textures in a QVulkanWindow + + The \e{Hello Vulkan Texture Example} builds on \l hellovulkantriangle. Here + instead of drawing a single triangle, a triangle strip is drawn in order to + get a quad on the screen. This is then textured using a QImage loaded from + a .png image file. + + \image hellovulkantexture.png + \include examples-run.qdocinc +*/ diff --git a/examples/vulkan/doc/src/hellovulkantriangle.qdoc b/examples/vulkan/doc/src/hellovulkantriangle.qdoc new file mode 100644 index 0000000000..81af776ea1 --- /dev/null +++ b/examples/vulkan/doc/src/hellovulkantriangle.qdoc @@ -0,0 +1,49 @@ +/**************************************************************************** +** +** Copyright (C) 2017 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 hellovulkantriangle + \ingroup examples-vulkan + \title Hello Vulkan Triangle Example + \brief Shows the basics of rendering with QVulkanWindow and the Vulkan API + + The \e{Hello Vulkan Triangle Example} builds on \l hellovulkanwindow. This + time a full graphics pipeline is created, including a vertex and fragment + shader. This pipeline is then used to render a triangle. + + \image hellovulkantriangle.png + + The example also demonstrates multisample antialiasing. Based on the + supported sample counts reported by QVulkanWindow::supportedSampleCounts() + the example chooses between 8x, 4x, or no multisampling. Once configured + via QVulkanWindow::setSamples(), QVulkanWindow takes care of the rest: the + additional multisample color buffers are created automatically, and + resolving into the swapchain buffers is performed at the end of the default + render pass for each frame. + + \include examples-run.qdocinc +*/ diff --git a/examples/vulkan/doc/src/hellovulkanwidget.qdoc b/examples/vulkan/doc/src/hellovulkanwidget.qdoc new file mode 100644 index 0000000000..7987bdeff9 --- /dev/null +++ b/examples/vulkan/doc/src/hellovulkanwidget.qdoc @@ -0,0 +1,49 @@ +/**************************************************************************** +** +** Copyright (C) 2017 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 hellovulkanwidget + \ingroup examples-vulkan + \title Hello Vulkan Widget Example + \brief Shows the usage of QVulkanWindow in QWidget applications + + The \e{Hello Vulkan Widget Example} is a variant of \l hellovulkantriangle + that embeds the QVulkanWindow into a QWidget-based user interface using + QWidget::createWindowContainer(). + + \image hellovulkanwidget.png + + The code to set up the Vulkan pipeline and render the triangle is the same + as in \l hellovulkantriangle. In addition, this example demonstrates + another feature of QVulkanWindow: reading the image content back from the + color buffer into a QImage. By clicking the Grab button, the example + renders the next frame and follows it up with a transfer operation in order + to get the swapchain color buffer content copied into host accessible + memory. The image is then saved to disk via QImage::save(). + + \include examples-run.qdocinc +*/ diff --git a/examples/vulkan/doc/src/hellovulkanwindow.qdoc b/examples/vulkan/doc/src/hellovulkanwindow.qdoc new file mode 100644 index 0000000000..06cc9c1c28 --- /dev/null +++ b/examples/vulkan/doc/src/hellovulkanwindow.qdoc @@ -0,0 +1,101 @@ +/**************************************************************************** +** +** Copyright (C) 2017 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 hellovulkanwindow + \title Hello Vulkan Window Example + \ingroup examples-vulkan + \brief Shows the basics of using QVulkanWindow + + The \e{Hello Vulkan Window Example} shows the basics of using QVulkanWindow + in order to display rendering with the Vulkan graphics API on systems that + support this. + + \image hellovulkanwindow.png + + In this example there will be no actual rendering: it simply begins and + ends a render pass, which results in clearing the buffers to a fixed value. + The color buffer clear value changes on every frame. + + \section1 Startup + + Each Qt application using Vulkan will have to have a \c{Vulkan instance} + which encapsulates application-level state and initializes a Vulkan library. + + A QVulkanWindow must always be associated with a QVulkanInstance and hence + the example performs instance creation before the window. The + QVulkanInstance object must also outlive the window. + + \snippet hellovulkanwindow/main.cpp 0 + + The example enables validation layers, when supported. When the requested + layers are not present, the request will be ignored. Additional layers and + extensions can be enabled in a similar manner. + + \snippet hellovulkanwindow/main.cpp 1 + + Once the instance is ready, it is time to create a window. Note that \c w + lives on the stack and is declared after \c inst. + + \section1 The QVulkanWindow Subclass + + To add custom functionality to a QVulkanWindow, subclassing is used. This + follows the existing patterns from QOpenGLWindow and QOpenGLWidget. + However, QVulkanWindow utilizes a separate QVulkanWindowRenderer object. + This resembles QQuickFramebufferObject, and allows better separation of the + functions that are supposed to be reimplemented. + + \snippet hellovulkanwindow/hellovulkanwindow.h 0 + + The QVulkanWindow subclass reimplements the factory function + QVulkanWindow::createRenderer(). This simply returns a new instance of the + QVulkanWindowRenderer subclass. In order to be able to access various + Vulkan resources via the window object, a pointer to the window is passed + and stored via the constructor. + + \snippet hellovulkanwindow/hellovulkanwindow.cpp 0 + + Graphics resource creation and destruction is typically done in one of the + init - resource functions. + + \snippet hellovulkanwindow/hellovulkanwindow.cpp 1 + + \section1 The Actual Rendering + + QVulkanWindow subclasses queue their draw calls in their reimplementation + of QVulkanWindowRenderer::startNextFrame(). Once done, they are required to + call back QVulkanWindow::frameReady(). The example has no asynchronous + command generation, so the frameReady() call is made directly from + startNextFrame(). + + \snippet hellovulkanwindow/hellovulkanwindow.cpp 2 + + To get continuous updates, the example simply invokes + QWindow::requestUpdate() in order to schedule a repaint. + + \include examples-run.qdocinc +*/ diff --git a/examples/vulkan/hellovulkantexture/hellovulkantexture.cpp b/examples/vulkan/hellovulkantexture/hellovulkantexture.cpp new file mode 100644 index 0000000000..5e52d5e006 --- /dev/null +++ b/examples/vulkan/hellovulkantexture/hellovulkantexture.cpp @@ -0,0 +1,828 @@ +/**************************************************************************** +** +** Copyright (C) 2017 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 "hellovulkantexture.h" +#include <QVulkanFunctions> +#include <QCoreApplication> +#include <QFile> + +// Use a triangle strip to get a quad. +// +// Note that the vertex data and the projection matrix assume OpenGL. With +// Vulkan Y is negated in clip space and the near/far plane is at 0/1 instead +// of -1/1. These will be corrected for by an extra transformation when +// calculating the modelview-projection matrix. +static float vertexData[] = { + // x, y, z, u, v + -1, -1, 0, 0, 1, + -1, 1, 0, 0, 0, + 1, -1, 0, 1, 1, + 1, 1, 0, 1, 0 +}; + +static const int UNIFORM_DATA_SIZE = 16 * sizeof(float); + +static inline VkDeviceSize aligned(VkDeviceSize v, VkDeviceSize byteAlign) +{ + return (v + byteAlign - 1) & ~(byteAlign - 1); +} + +QVulkanWindowRenderer *VulkanWindow::createRenderer() +{ + return new VulkanRenderer(this); +} + +VulkanRenderer::VulkanRenderer(QVulkanWindow *w) + : m_window(w) +{ +} + +VkShaderModule VulkanRenderer::createShader(const QString &name) +{ + QFile file(name); + if (!file.open(QIODevice::ReadOnly)) { + qWarning("Failed to read shader %s", qPrintable(name)); + return VK_NULL_HANDLE; + } + QByteArray blob = file.readAll(); + file.close(); + + VkShaderModuleCreateInfo shaderInfo; + memset(&shaderInfo, 0, sizeof(shaderInfo)); + shaderInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + shaderInfo.codeSize = blob.size(); + shaderInfo.pCode = reinterpret_cast<const uint32_t *>(blob.constData()); + VkShaderModule shaderModule; + VkResult err = m_devFuncs->vkCreateShaderModule(m_window->device(), &shaderInfo, nullptr, &shaderModule); + if (err != VK_SUCCESS) { + qWarning("Failed to create shader module: %d", err); + return VK_NULL_HANDLE; + } + + return shaderModule; +} + +bool VulkanRenderer::createTexture(const QString &name) +{ + QImage img(name); + if (img.isNull()) { + qWarning("Failed to load image %s", qPrintable(name)); + return false; + } + + // Convert to byte ordered RGBA8. Use premultiplied alpha, see pColorBlendState in the pipeline. + img = img.convertToFormat(QImage::Format_RGBA8888_Premultiplied); + + QVulkanFunctions *f = m_window->vulkanInstance()->functions(); + VkDevice dev = m_window->device(); + + const bool srgb = QCoreApplication::arguments().contains(QStringLiteral("--srgb")); + if (srgb) + qDebug("sRGB swapchain was requested, making texture sRGB too"); + + m_texFormat = srgb ? VK_FORMAT_R8G8B8A8_SRGB : VK_FORMAT_R8G8B8A8_UNORM; + + // Now we can either map and copy the image data directly, or have to go + // through a staging buffer to copy and convert into the internal optimal + // tiling format. + VkFormatProperties props; + f->vkGetPhysicalDeviceFormatProperties(m_window->physicalDevice(), m_texFormat, &props); + const bool canSampleLinear = (props.linearTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT); + const bool canSampleOptimal = (props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT); + if (!canSampleLinear && !canSampleOptimal) { + qWarning("Neither linear nor optimal image sampling is supported for RGBA8"); + return false; + } + + static bool alwaysStage = qEnvironmentVariableIntValue("QT_VK_FORCE_STAGE_TEX"); + + if (canSampleLinear && !alwaysStage) { + if (!createTextureImage(img.size(), &m_texImage, &m_texMem, + VK_IMAGE_TILING_LINEAR, VK_IMAGE_USAGE_SAMPLED_BIT, + m_window->hostVisibleMemoryIndex())) + return false; + + if (!writeLinearImage(img, m_texImage, m_texMem)) + return false; + + m_texLayoutPending = true; + } else { + if (!createTextureImage(img.size(), &m_texStaging, &m_texStagingMem, + VK_IMAGE_TILING_LINEAR, VK_IMAGE_USAGE_TRANSFER_SRC_BIT, + m_window->hostVisibleMemoryIndex())) + return false; + + if (!createTextureImage(img.size(), &m_texImage, &m_texMem, + VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, + m_window->deviceLocalMemoryIndex())) + return false; + + if (!writeLinearImage(img, m_texStaging, m_texStagingMem)) + return false; + + m_texStagingPending = true; + } + + VkImageViewCreateInfo viewInfo; + memset(&viewInfo, 0, sizeof(viewInfo)); + viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + viewInfo.image = m_texImage; + viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; + viewInfo.format = m_texFormat; + viewInfo.components.r = VK_COMPONENT_SWIZZLE_R; + viewInfo.components.g = VK_COMPONENT_SWIZZLE_G; + viewInfo.components.b = VK_COMPONENT_SWIZZLE_B; + viewInfo.components.a = VK_COMPONENT_SWIZZLE_A; + viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + viewInfo.subresourceRange.levelCount = viewInfo.subresourceRange.layerCount = 1; + + VkResult err = m_devFuncs->vkCreateImageView(dev, &viewInfo, nullptr, &m_texView); + if (err != VK_SUCCESS) { + qWarning("Failed to create image view for texture: %d", err); + return false; + } + + m_texSize = img.size(); + + return true; +} + +bool VulkanRenderer::createTextureImage(const QSize &size, VkImage *image, VkDeviceMemory *mem, + VkImageTiling tiling, VkImageUsageFlags usage, uint32_t memIndex) +{ + VkDevice dev = m_window->device(); + + VkImageCreateInfo imageInfo; + memset(&imageInfo, 0, sizeof(imageInfo)); + imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + imageInfo.imageType = VK_IMAGE_TYPE_2D; + imageInfo.format = m_texFormat; + imageInfo.extent.width = size.width(); + imageInfo.extent.height = size.height(); + imageInfo.extent.depth = 1; + imageInfo.mipLevels = 1; + imageInfo.arrayLayers = 1; + imageInfo.samples = VK_SAMPLE_COUNT_1_BIT; + imageInfo.tiling = tiling; + imageInfo.usage = usage; + imageInfo.initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED; + + VkResult err = m_devFuncs->vkCreateImage(dev, &imageInfo, nullptr, image); + if (err != VK_SUCCESS) { + qWarning("Failed to create linear image for texture: %d", err); + return false; + } + + VkMemoryRequirements memReq; + m_devFuncs->vkGetImageMemoryRequirements(dev, *image, &memReq); + + VkMemoryAllocateInfo allocInfo = { + VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + nullptr, + memReq.size, + memIndex + }; + qDebug("allocating %u bytes for texture image", uint32_t(memReq.size)); + + err = m_devFuncs->vkAllocateMemory(dev, &allocInfo, nullptr, mem); + if (err != VK_SUCCESS) { + qWarning("Failed to allocate memory for linear image: %d", err); + return false; + } + + err = m_devFuncs->vkBindImageMemory(dev, *image, *mem, 0); + if (err != VK_SUCCESS) { + qWarning("Failed to bind linear image memory: %d", err); + return false; + } + + return true; +} + +bool VulkanRenderer::writeLinearImage(const QImage &img, VkImage image, VkDeviceMemory memory) +{ + VkDevice dev = m_window->device(); + + VkImageSubresource subres = { + VK_IMAGE_ASPECT_COLOR_BIT, + 0, // mip level + 0 + }; + VkSubresourceLayout layout; + m_devFuncs->vkGetImageSubresourceLayout(dev, image, &subres, &layout); + + uchar *p; + VkResult err = m_devFuncs->vkMapMemory(dev, memory, layout.offset, layout.size, 0, reinterpret_cast<void **>(&p)); + if (err != VK_SUCCESS) { + qWarning("Failed to map memory for linear image: %d", err); + return false; + } + + for (int y = 0; y < img.height(); ++y) { + const uchar *line = img.constScanLine(y); + memcpy(p, line, img.width() * 4); + p += layout.rowPitch; + } + + m_devFuncs->vkUnmapMemory(dev, memory); + return true; +} + +void VulkanRenderer::ensureTexture() +{ + if (!m_texLayoutPending && !m_texStagingPending) + return; + + Q_ASSERT(m_texLayoutPending != m_texStagingPending); + VkCommandBuffer cb = m_window->currentCommandBuffer(); + + VkImageMemoryBarrier barrier; + memset(&barrier, 0, sizeof(barrier)); + barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + barrier.subresourceRange.levelCount = barrier.subresourceRange.layerCount = 1; + + if (m_texLayoutPending) { + m_texLayoutPending = false; + + barrier.oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED; + barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; + barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + barrier.image = m_texImage; + + m_devFuncs->vkCmdPipelineBarrier(cb, + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, + 0, 0, nullptr, 0, nullptr, + 1, &barrier); + } else { + m_texStagingPending = false; + + barrier.oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED; + barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; + barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; + barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + barrier.image = m_texStaging; + m_devFuncs->vkCmdPipelineBarrier(cb, + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, 0, nullptr, 0, nullptr, + 1, &barrier); + + barrier.oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED; + barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + barrier.srcAccessMask = 0; + barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + barrier.image = m_texImage; + m_devFuncs->vkCmdPipelineBarrier(cb, + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, 0, nullptr, 0, nullptr, + 1, &barrier); + + VkImageCopy copyInfo; + memset(©Info, 0, sizeof(copyInfo)); + copyInfo.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + copyInfo.srcSubresource.layerCount = 1; + copyInfo.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + copyInfo.dstSubresource.layerCount = 1; + copyInfo.extent.width = m_texSize.width(); + copyInfo.extent.height = m_texSize.height(); + copyInfo.extent.depth = 1; + m_devFuncs->vkCmdCopyImage(cb, m_texStaging, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + m_texImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©Info); + + barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + barrier.image = m_texImage; + m_devFuncs->vkCmdPipelineBarrier(cb, + VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, + 0, 0, nullptr, 0, nullptr, + 1, &barrier); + } +} + +void VulkanRenderer::initResources() +{ + qDebug("initResources"); + + VkDevice dev = m_window->device(); + m_devFuncs = m_window->vulkanInstance()->deviceFunctions(dev); + + // The setup is similar to hellovulkantriangle. The difference is the + // presence of a second vertex attribute (texcoord), a sampler, and that we + // need blending. + + const int concurrentFrameCount = m_window->concurrentFrameCount(); + const VkPhysicalDeviceLimits *pdevLimits = &m_window->physicalDeviceProperties()->limits; + const VkDeviceSize uniAlign = pdevLimits->minUniformBufferOffsetAlignment; + qDebug("uniform buffer offset alignment is %u", (uint) uniAlign); + VkBufferCreateInfo bufInfo; + memset(&bufInfo, 0, sizeof(bufInfo)); + bufInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + // Our internal layout is vertex, uniform, uniform, ... with each uniform buffer start offset aligned to uniAlign. + const VkDeviceSize vertexAllocSize = aligned(sizeof(vertexData), uniAlign); + const VkDeviceSize uniformAllocSize = aligned(UNIFORM_DATA_SIZE, uniAlign); + bufInfo.size = vertexAllocSize + concurrentFrameCount * uniformAllocSize; + bufInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; + + VkResult err = m_devFuncs->vkCreateBuffer(dev, &bufInfo, nullptr, &m_buf); + if (err != VK_SUCCESS) + qFatal("Failed to create buffer: %d", err); + + VkMemoryRequirements memReq; + m_devFuncs->vkGetBufferMemoryRequirements(dev, m_buf, &memReq); + + VkMemoryAllocateInfo memAllocInfo = { + VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + nullptr, + memReq.size, + m_window->hostVisibleMemoryIndex() + }; + + err = m_devFuncs->vkAllocateMemory(dev, &memAllocInfo, nullptr, &m_bufMem); + if (err != VK_SUCCESS) + qFatal("Failed to allocate memory: %d", err); + + err = m_devFuncs->vkBindBufferMemory(dev, m_buf, m_bufMem, 0); + if (err != VK_SUCCESS) + qFatal("Failed to bind buffer memory: %d", err); + + quint8 *p; + err = m_devFuncs->vkMapMemory(dev, m_bufMem, 0, memReq.size, 0, reinterpret_cast<void **>(&p)); + if (err != VK_SUCCESS) + qFatal("Failed to map memory: %d", err); + memcpy(p, vertexData, sizeof(vertexData)); + QMatrix4x4 ident; + memset(m_uniformBufInfo, 0, sizeof(m_uniformBufInfo)); + for (int i = 0; i < concurrentFrameCount; ++i) { + const VkDeviceSize offset = vertexAllocSize + i * uniformAllocSize; + memcpy(p + offset, ident.constData(), 16 * sizeof(float)); + m_uniformBufInfo[i].buffer = m_buf; + m_uniformBufInfo[i].offset = offset; + m_uniformBufInfo[i].range = uniformAllocSize; + } + m_devFuncs->vkUnmapMemory(dev, m_bufMem); + + VkVertexInputBindingDescription vertexBindingDesc = { + 0, // binding + 5 * sizeof(float), + VK_VERTEX_INPUT_RATE_VERTEX + }; + VkVertexInputAttributeDescription vertexAttrDesc[] = { + { // position + 0, // location + 0, // binding + VK_FORMAT_R32G32B32_SFLOAT, + 0 + }, + { // texcoord + 1, + 0, + VK_FORMAT_R32G32_SFLOAT, + 3 * sizeof(float) + } + }; + + VkPipelineVertexInputStateCreateInfo vertexInputInfo; + vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; + vertexInputInfo.pNext = nullptr; + vertexInputInfo.flags = 0; + vertexInputInfo.vertexBindingDescriptionCount = 1; + vertexInputInfo.pVertexBindingDescriptions = &vertexBindingDesc; + vertexInputInfo.vertexAttributeDescriptionCount = 2; + vertexInputInfo.pVertexAttributeDescriptions = vertexAttrDesc; + + // Sampler. + VkSamplerCreateInfo samplerInfo; + memset(&samplerInfo, 0, sizeof(samplerInfo)); + samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; + samplerInfo.magFilter = VK_FILTER_NEAREST; + samplerInfo.minFilter = VK_FILTER_NEAREST; + samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + err = m_devFuncs->vkCreateSampler(dev, &samplerInfo, nullptr, &m_sampler); + if (err != VK_SUCCESS) + qFatal("Failed to create sampler: %d", err); + + // Texture. + if (!createTexture(QStringLiteral(":/qt256.png"))) + qFatal("Failed to create texture"); + + // Set up descriptor set and its layout. + VkDescriptorPoolSize descPoolSizes[2] = { + { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, uint32_t(concurrentFrameCount) }, + { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, uint32_t(concurrentFrameCount) } + }; + VkDescriptorPoolCreateInfo descPoolInfo; + memset(&descPoolInfo, 0, sizeof(descPoolInfo)); + descPoolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; + descPoolInfo.maxSets = concurrentFrameCount; + descPoolInfo.poolSizeCount = 2; + descPoolInfo.pPoolSizes = descPoolSizes; + err = m_devFuncs->vkCreateDescriptorPool(dev, &descPoolInfo, nullptr, &m_descPool); + if (err != VK_SUCCESS) + qFatal("Failed to create descriptor pool: %d", err); + + VkDescriptorSetLayoutBinding layoutBinding[2] = + { + { + 0, // binding + VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + 1, // descriptorCount + VK_SHADER_STAGE_VERTEX_BIT, + nullptr + }, + { + 1, // binding + VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + 1, // descriptorCount + VK_SHADER_STAGE_FRAGMENT_BIT, + nullptr + } + }; + VkDescriptorSetLayoutCreateInfo descLayoutInfo = { + VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, + nullptr, + 0, + 2, // bindingCount + layoutBinding + }; + err = m_devFuncs->vkCreateDescriptorSetLayout(dev, &descLayoutInfo, nullptr, &m_descSetLayout); + if (err != VK_SUCCESS) + qFatal("Failed to create descriptor set layout: %d", err); + + for (int i = 0; i < concurrentFrameCount; ++i) { + VkDescriptorSetAllocateInfo descSetAllocInfo = { + VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, + nullptr, + m_descPool, + 1, + &m_descSetLayout + }; + err = m_devFuncs->vkAllocateDescriptorSets(dev, &descSetAllocInfo, &m_descSet[i]); + if (err != VK_SUCCESS) + qFatal("Failed to allocate descriptor set: %d", err); + + VkWriteDescriptorSet descWrite[2]; + memset(descWrite, 0, sizeof(descWrite)); + descWrite[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descWrite[0].dstSet = m_descSet[i]; + descWrite[0].dstBinding = 0; + descWrite[0].descriptorCount = 1; + descWrite[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + descWrite[0].pBufferInfo = &m_uniformBufInfo[i]; + + VkDescriptorImageInfo descImageInfo = { + m_sampler, + m_texView, + VK_IMAGE_LAYOUT_GENERAL + }; + + descWrite[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descWrite[1].dstSet = m_descSet[i]; + descWrite[1].dstBinding = 1; + descWrite[1].descriptorCount = 1; + descWrite[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + descWrite[1].pImageInfo = &descImageInfo; + + m_devFuncs->vkUpdateDescriptorSets(dev, 2, descWrite, 0, nullptr); + } + + // Pipeline cache + VkPipelineCacheCreateInfo pipelineCacheInfo; + memset(&pipelineCacheInfo, 0, sizeof(pipelineCacheInfo)); + pipelineCacheInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO; + err = m_devFuncs->vkCreatePipelineCache(dev, &pipelineCacheInfo, nullptr, &m_pipelineCache); + if (err != VK_SUCCESS) + qFatal("Failed to create pipeline cache: %d", err); + + // Pipeline layout + VkPipelineLayoutCreateInfo pipelineLayoutInfo; + memset(&pipelineLayoutInfo, 0, sizeof(pipelineLayoutInfo)); + pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; + pipelineLayoutInfo.setLayoutCount = 1; + pipelineLayoutInfo.pSetLayouts = &m_descSetLayout; + err = m_devFuncs->vkCreatePipelineLayout(dev, &pipelineLayoutInfo, nullptr, &m_pipelineLayout); + if (err != VK_SUCCESS) + qFatal("Failed to create pipeline layout: %d", err); + + // Shaders + VkShaderModule vertShaderModule = createShader(QStringLiteral(":/texture_vert.spv")); + VkShaderModule fragShaderModule = createShader(QStringLiteral(":/texture_frag.spv")); + + // Graphics pipeline + VkGraphicsPipelineCreateInfo pipelineInfo; + memset(&pipelineInfo, 0, sizeof(pipelineInfo)); + pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; + + VkPipelineShaderStageCreateInfo shaderStages[2] = { + { + VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + nullptr, + 0, + VK_SHADER_STAGE_VERTEX_BIT, + vertShaderModule, + "main", + nullptr + }, + { + VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + nullptr, + 0, + VK_SHADER_STAGE_FRAGMENT_BIT, + fragShaderModule, + "main", + nullptr + } + }; + pipelineInfo.stageCount = 2; + pipelineInfo.pStages = shaderStages; + + pipelineInfo.pVertexInputState = &vertexInputInfo; + + VkPipelineInputAssemblyStateCreateInfo ia; + memset(&ia, 0, sizeof(ia)); + ia.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; + ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP; + pipelineInfo.pInputAssemblyState = &ia; + + // The viewport and scissor will be set dynamically via vkCmdSetViewport/Scissor. + // This way the pipeline does not need to be touched when resizing the window. + VkPipelineViewportStateCreateInfo vp; + memset(&vp, 0, sizeof(vp)); + vp.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; + vp.viewportCount = 1; + vp.scissorCount = 1; + pipelineInfo.pViewportState = &vp; + + VkPipelineRasterizationStateCreateInfo rs; + memset(&rs, 0, sizeof(rs)); + rs.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; + rs.polygonMode = VK_POLYGON_MODE_FILL; + rs.cullMode = VK_CULL_MODE_BACK_BIT; + rs.frontFace = VK_FRONT_FACE_CLOCKWISE; + rs.lineWidth = 1.0f; + pipelineInfo.pRasterizationState = &rs; + + VkPipelineMultisampleStateCreateInfo ms; + memset(&ms, 0, sizeof(ms)); + ms.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; + ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + pipelineInfo.pMultisampleState = &ms; + + VkPipelineDepthStencilStateCreateInfo ds; + memset(&ds, 0, sizeof(ds)); + ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; + ds.depthTestEnable = VK_TRUE; + ds.depthWriteEnable = VK_TRUE; + ds.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL; + pipelineInfo.pDepthStencilState = &ds; + + VkPipelineColorBlendStateCreateInfo cb; + memset(&cb, 0, sizeof(cb)); + cb.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; + // assume pre-multiplied alpha, blend, write out all of rgba + VkPipelineColorBlendAttachmentState att; + memset(&att, 0, sizeof(att)); + att.colorWriteMask = 0xF; + att.blendEnable = VK_TRUE; + att.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; + att.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; + att.colorBlendOp = VK_BLEND_OP_ADD; + att.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; + att.dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; + att.alphaBlendOp = VK_BLEND_OP_ADD; + cb.attachmentCount = 1; + cb.pAttachments = &att; + pipelineInfo.pColorBlendState = &cb; + + VkDynamicState dynEnable[] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; + VkPipelineDynamicStateCreateInfo dyn; + memset(&dyn, 0, sizeof(dyn)); + dyn.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; + dyn.dynamicStateCount = sizeof(dynEnable) / sizeof(VkDynamicState); + dyn.pDynamicStates = dynEnable; + pipelineInfo.pDynamicState = &dyn; + + pipelineInfo.layout = m_pipelineLayout; + pipelineInfo.renderPass = m_window->defaultRenderPass(); + + err = m_devFuncs->vkCreateGraphicsPipelines(dev, m_pipelineCache, 1, &pipelineInfo, nullptr, &m_pipeline); + if (err != VK_SUCCESS) + qFatal("Failed to create graphics pipeline: %d", err); + + if (vertShaderModule) + m_devFuncs->vkDestroyShaderModule(dev, vertShaderModule, nullptr); + if (fragShaderModule) + m_devFuncs->vkDestroyShaderModule(dev, fragShaderModule, nullptr); +} + +void VulkanRenderer::initSwapChainResources() +{ + qDebug("initSwapChainResources"); + + // Projection matrix + m_proj = *m_window->clipCorrectionMatrix(); // adjust for Vulkan-OpenGL clip space differences + const QSize sz = m_window->swapChainImageSize(); + m_proj.perspective(45.0f, sz.width() / (float) sz.height(), 0.01f, 100.0f); + m_proj.translate(0, 0, -4); +} + +void VulkanRenderer::releaseSwapChainResources() +{ + qDebug("releaseSwapChainResources"); +} + +void VulkanRenderer::releaseResources() +{ + qDebug("releaseResources"); + + VkDevice dev = m_window->device(); + + if (m_sampler) { + m_devFuncs->vkDestroySampler(dev, m_sampler, nullptr); + m_sampler = VK_NULL_HANDLE; + } + + if (m_texStaging) { + m_devFuncs->vkDestroyImage(dev, m_texStaging, nullptr); + m_texStaging = VK_NULL_HANDLE; + } + + if (m_texStagingMem) { + m_devFuncs->vkFreeMemory(dev, m_texStagingMem, nullptr); + m_texStagingMem = VK_NULL_HANDLE; + } + + if (m_texView) { + m_devFuncs->vkDestroyImageView(dev, m_texView, nullptr); + m_texView = VK_NULL_HANDLE; + } + + if (m_texImage) { + m_devFuncs->vkDestroyImage(dev, m_texImage, nullptr); + m_texImage = VK_NULL_HANDLE; + } + + if (m_texMem) { + m_devFuncs->vkFreeMemory(dev, m_texMem, nullptr); + m_texMem = VK_NULL_HANDLE; + } + + if (m_pipeline) { + m_devFuncs->vkDestroyPipeline(dev, m_pipeline, nullptr); + m_pipeline = VK_NULL_HANDLE; + } + + if (m_pipelineLayout) { + m_devFuncs->vkDestroyPipelineLayout(dev, m_pipelineLayout, nullptr); + m_pipelineLayout = VK_NULL_HANDLE; + } + + if (m_pipelineCache) { + m_devFuncs->vkDestroyPipelineCache(dev, m_pipelineCache, nullptr); + m_pipelineCache = VK_NULL_HANDLE; + } + + if (m_descSetLayout) { + m_devFuncs->vkDestroyDescriptorSetLayout(dev, m_descSetLayout, nullptr); + m_descSetLayout = VK_NULL_HANDLE; + } + + if (m_descPool) { + m_devFuncs->vkDestroyDescriptorPool(dev, m_descPool, nullptr); + m_descPool = VK_NULL_HANDLE; + } + + if (m_buf) { + m_devFuncs->vkDestroyBuffer(dev, m_buf, nullptr); + m_buf = VK_NULL_HANDLE; + } + + if (m_bufMem) { + m_devFuncs->vkFreeMemory(dev, m_bufMem, nullptr); + m_bufMem = VK_NULL_HANDLE; + } +} + +void VulkanRenderer::startNextFrame() +{ + VkDevice dev = m_window->device(); + VkCommandBuffer cb = m_window->currentCommandBuffer(); + const QSize sz = m_window->swapChainImageSize(); + + // Add the necessary barriers and do the host-linear -> device-optimal copy, if not yet done. + ensureTexture(); + + VkClearColorValue clearColor = { 0, 0, 0, 1 }; + VkClearDepthStencilValue clearDS = { 1, 0 }; + VkClearValue clearValues[2]; + memset(clearValues, 0, sizeof(clearValues)); + clearValues[0].color = clearColor; + clearValues[1].depthStencil = clearDS; + + VkRenderPassBeginInfo rpBeginInfo; + memset(&rpBeginInfo, 0, sizeof(rpBeginInfo)); + rpBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; + rpBeginInfo.renderPass = m_window->defaultRenderPass(); + rpBeginInfo.framebuffer = m_window->currentFramebuffer(); + rpBeginInfo.renderArea.extent.width = sz.width(); + rpBeginInfo.renderArea.extent.height = sz.height(); + rpBeginInfo.clearValueCount = 2; + rpBeginInfo.pClearValues = clearValues; + VkCommandBuffer cmdBuf = m_window->currentCommandBuffer(); + m_devFuncs->vkCmdBeginRenderPass(cmdBuf, &rpBeginInfo, VK_SUBPASS_CONTENTS_INLINE); + + quint8 *p; + VkResult err = m_devFuncs->vkMapMemory(dev, m_bufMem, m_uniformBufInfo[m_window->currentFrame()].offset, + UNIFORM_DATA_SIZE, 0, reinterpret_cast<void **>(&p)); + if (err != VK_SUCCESS) + qFatal("Failed to map memory: %d", err); + QMatrix4x4 m = m_proj; + m.rotate(m_rotation, 0, 0, 1); + memcpy(p, m.constData(), 16 * sizeof(float)); + m_devFuncs->vkUnmapMemory(dev, m_bufMem); + + // Not exactly a real animation system, just advance on every frame for now. + m_rotation += 1.0f; + + m_devFuncs->vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipeline); + m_devFuncs->vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipelineLayout, 0, 1, + &m_descSet[m_window->currentFrame()], 0, nullptr); + VkDeviceSize vbOffset = 0; + m_devFuncs->vkCmdBindVertexBuffers(cb, 0, 1, &m_buf, &vbOffset); + + VkViewport viewport; + viewport.x = viewport.y = 0; + viewport.width = sz.width(); + viewport.height = sz.height(); + viewport.minDepth = 0; + viewport.maxDepth = 1; + m_devFuncs->vkCmdSetViewport(cb, 0, 1, &viewport); + + VkRect2D scissor; + scissor.offset.x = scissor.offset.y = 0; + scissor.extent.width = viewport.width; + scissor.extent.height = viewport.height; + m_devFuncs->vkCmdSetScissor(cb, 0, 1, &scissor); + + m_devFuncs->vkCmdDraw(cb, 4, 1, 0, 0); + + m_devFuncs->vkCmdEndRenderPass(cmdBuf); + + m_window->frameReady(); + m_window->requestUpdate(); // render continuously, throttled by the presentation rate +} diff --git a/examples/vulkan/hellovulkantexture/hellovulkantexture.h b/examples/vulkan/hellovulkantexture/hellovulkantexture.h new file mode 100644 index 0000000000..a8c96d1987 --- /dev/null +++ b/examples/vulkan/hellovulkantexture/hellovulkantexture.h @@ -0,0 +1,108 @@ +/**************************************************************************** +** +** Copyright (C) 2017 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 <QVulkanWindow> +#include <QImage> + +class VulkanRenderer : public QVulkanWindowRenderer +{ +public: + VulkanRenderer(QVulkanWindow *w); + + void initResources() override; + void initSwapChainResources() override; + void releaseSwapChainResources() override; + void releaseResources() override; + + void startNextFrame() override; + +private: + VkShaderModule createShader(const QString &name); + bool createTexture(const QString &name); + bool createTextureImage(const QSize &size, VkImage *image, VkDeviceMemory *mem, + VkImageTiling tiling, VkImageUsageFlags usage, uint32_t memIndex); + bool writeLinearImage(const QImage &img, VkImage image, VkDeviceMemory memory); + void ensureTexture(); + + QVulkanWindow *m_window; + QVulkanDeviceFunctions *m_devFuncs; + + VkDeviceMemory m_bufMem = VK_NULL_HANDLE; + VkBuffer m_buf = VK_NULL_HANDLE; + VkDescriptorBufferInfo m_uniformBufInfo[QVulkanWindow::MAX_CONCURRENT_FRAME_COUNT]; + + VkDescriptorPool m_descPool = VK_NULL_HANDLE; + VkDescriptorSetLayout m_descSetLayout = VK_NULL_HANDLE; + VkDescriptorSet m_descSet[QVulkanWindow::MAX_CONCURRENT_FRAME_COUNT]; + + VkPipelineCache m_pipelineCache = VK_NULL_HANDLE; + VkPipelineLayout m_pipelineLayout = VK_NULL_HANDLE; + VkPipeline m_pipeline = VK_NULL_HANDLE; + + VkSampler m_sampler = VK_NULL_HANDLE; + VkImage m_texImage = VK_NULL_HANDLE; + VkDeviceMemory m_texMem = VK_NULL_HANDLE; + bool m_texLayoutPending = false; + VkImageView m_texView = VK_NULL_HANDLE; + VkImage m_texStaging = VK_NULL_HANDLE; + VkDeviceMemory m_texStagingMem = VK_NULL_HANDLE; + bool m_texStagingPending = false; + QSize m_texSize; + VkFormat m_texFormat; + + QMatrix4x4 m_proj; + float m_rotation = 0.0f; +}; + +class VulkanWindow : public QVulkanWindow +{ +public: + QVulkanWindowRenderer *createRenderer() override; +}; diff --git a/examples/vulkan/hellovulkantexture/hellovulkantexture.pro b/examples/vulkan/hellovulkantexture/hellovulkantexture.pro new file mode 100644 index 0000000000..59bfcda715 --- /dev/null +++ b/examples/vulkan/hellovulkantexture/hellovulkantexture.pro @@ -0,0 +1,7 @@ +HEADERS += hellovulkantexture.h +SOURCES += hellovulkantexture.cpp main.cpp +RESOURCES += hellovulkantexture.qrc + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/vulkan/hellovulkantexture +INSTALLS += target diff --git a/examples/vulkan/hellovulkantexture/hellovulkantexture.qrc b/examples/vulkan/hellovulkantexture/hellovulkantexture.qrc new file mode 100644 index 0000000000..04e7cda859 --- /dev/null +++ b/examples/vulkan/hellovulkantexture/hellovulkantexture.qrc @@ -0,0 +1,7 @@ +<!DOCTYPE RCC><RCC version="1.0"> +<qresource> + <file>texture_vert.spv</file> + <file>texture_frag.spv</file> + <file>qt256.png</file> +</qresource> +</RCC> diff --git a/examples/vulkan/hellovulkantexture/main.cpp b/examples/vulkan/hellovulkantexture/main.cpp new file mode 100644 index 0000000000..1144463b70 --- /dev/null +++ b/examples/vulkan/hellovulkantexture/main.cpp @@ -0,0 +1,91 @@ +/**************************************************************************** +** +** Copyright (C) 2017 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 <QGuiApplication> +#include <QVulkanInstance> +#include <QLoggingCategory> +#include "hellovulkantexture.h" + +Q_LOGGING_CATEGORY(lcVk, "qt.vulkan") + +int main(int argc, char *argv[]) +{ + QGuiApplication app(argc, argv); + + QLoggingCategory::setFilterRules(QStringLiteral("qt.vulkan=true")); + + QVulkanInstance inst; + +#ifndef Q_OS_ANDROID + inst.setLayers(QByteArrayList() << "VK_LAYER_LUNARG_standard_validation"); +#else + inst.setLayers(QByteArrayList() + << "VK_LAYER_GOOGLE_threading" + << "VK_LAYER_LUNARG_parameter_validation" + << "VK_LAYER_LUNARG_object_tracker" + << "VK_LAYER_LUNARG_core_validation" + << "VK_LAYER_LUNARG_image" + << "VK_LAYER_LUNARG_swapchain" + << "VK_LAYER_GOOGLE_unique_objects"); +#endif + + if (!inst.create()) + qFatal("Failed to create Vulkan instance: %d", inst.errorCode()); + + VulkanWindow w; + w.setVulkanInstance(&inst); + if (QCoreApplication::arguments().contains(QStringLiteral("--srgb"))) + w.setPreferredColorFormats(QVector<VkFormat>() << VK_FORMAT_B8G8R8A8_SRGB); + + w.resize(1024, 768); + w.show(); + + return app.exec(); +} diff --git a/examples/vulkan/hellovulkantexture/qt256.png b/examples/vulkan/hellovulkantexture/qt256.png Binary files differnew file mode 100644 index 0000000000..30c621c9c6 --- /dev/null +++ b/examples/vulkan/hellovulkantexture/qt256.png diff --git a/examples/vulkan/hellovulkantexture/texture.frag b/examples/vulkan/hellovulkantexture/texture.frag new file mode 100644 index 0000000000..e6021fe905 --- /dev/null +++ b/examples/vulkan/hellovulkantexture/texture.frag @@ -0,0 +1,12 @@ +#version 440 + +layout(location = 0) in vec2 v_texcoord; + +layout(location = 0) out vec4 fragColor; + +layout(binding = 1) uniform sampler2D tex; + +void main() +{ + fragColor = texture(tex, v_texcoord); +} diff --git a/examples/vulkan/hellovulkantexture/texture.vert b/examples/vulkan/hellovulkantexture/texture.vert new file mode 100644 index 0000000000..de486cb772 --- /dev/null +++ b/examples/vulkan/hellovulkantexture/texture.vert @@ -0,0 +1,18 @@ +#version 440 + +layout(location = 0) in vec4 position; +layout(location = 1) in vec2 texcoord; + +layout(location = 0) out vec2 v_texcoord; + +layout(std140, binding = 0) uniform buf { + mat4 mvp; +} ubuf; + +out gl_PerVertex { vec4 gl_Position; }; + +void main() +{ + v_texcoord = texcoord; + gl_Position = ubuf.mvp * position; +} diff --git a/examples/vulkan/hellovulkantexture/texture_frag.spv b/examples/vulkan/hellovulkantexture/texture_frag.spv Binary files differnew file mode 100644 index 0000000000..7521ef6eef --- /dev/null +++ b/examples/vulkan/hellovulkantexture/texture_frag.spv diff --git a/examples/vulkan/hellovulkantexture/texture_vert.spv b/examples/vulkan/hellovulkantexture/texture_vert.spv Binary files differnew file mode 100644 index 0000000000..6292c0de31 --- /dev/null +++ b/examples/vulkan/hellovulkantexture/texture_vert.spv diff --git a/examples/vulkan/hellovulkantriangle/hellovulkantriangle.pro b/examples/vulkan/hellovulkantriangle/hellovulkantriangle.pro new file mode 100644 index 0000000000..db016da3ac --- /dev/null +++ b/examples/vulkan/hellovulkantriangle/hellovulkantriangle.pro @@ -0,0 +1,12 @@ +HEADERS += \ + ../shared/trianglerenderer.h + +SOURCES += \ + main.cpp \ + ../shared/trianglerenderer.cpp + +RESOURCES += hellovulkantriangle.qrc + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/vulkan/hellovulkantriangle +INSTALLS += target diff --git a/examples/vulkan/hellovulkantriangle/hellovulkantriangle.qrc b/examples/vulkan/hellovulkantriangle/hellovulkantriangle.qrc new file mode 100644 index 0000000000..489fc7295a --- /dev/null +++ b/examples/vulkan/hellovulkantriangle/hellovulkantriangle.qrc @@ -0,0 +1,6 @@ +<!DOCTYPE RCC><RCC version="1.0"> +<qresource> + <file alias="color_vert.spv">../shared/color_vert.spv</file> + <file alias="color_frag.spv">../shared/color_frag.spv</file> +</qresource> +</RCC> diff --git a/examples/vulkan/hellovulkantriangle/main.cpp b/examples/vulkan/hellovulkantriangle/main.cpp new file mode 100644 index 0000000000..d3eef2e14a --- /dev/null +++ b/examples/vulkan/hellovulkantriangle/main.cpp @@ -0,0 +1,100 @@ +/**************************************************************************** +** +** Copyright (C) 2017 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 <QGuiApplication> +#include <QVulkanInstance> +#include <QLoggingCategory> +#include "../shared/trianglerenderer.h" + +Q_LOGGING_CATEGORY(lcVk, "qt.vulkan") + +class VulkanWindow : public QVulkanWindow +{ +public: + QVulkanWindowRenderer *createRenderer() override; +}; + +QVulkanWindowRenderer *VulkanWindow::createRenderer() +{ + return new TriangleRenderer(this, true); // try MSAA, when available +} + +int main(int argc, char *argv[]) +{ + QGuiApplication app(argc, argv); + + QLoggingCategory::setFilterRules(QStringLiteral("qt.vulkan=true")); + + QVulkanInstance inst; + +#ifndef Q_OS_ANDROID + inst.setLayers(QByteArrayList() << "VK_LAYER_LUNARG_standard_validation"); +#else + inst.setLayers(QByteArrayList() + << "VK_LAYER_GOOGLE_threading" + << "VK_LAYER_LUNARG_parameter_validation" + << "VK_LAYER_LUNARG_object_tracker" + << "VK_LAYER_LUNARG_core_validation" + << "VK_LAYER_LUNARG_image" + << "VK_LAYER_LUNARG_swapchain" + << "VK_LAYER_GOOGLE_unique_objects"); +#endif + + if (!inst.create()) + qFatal("Failed to create Vulkan instance: %d", inst.errorCode()); + + VulkanWindow w; + w.setVulkanInstance(&inst); + + w.resize(1024, 768); + w.show(); + + return app.exec(); +} diff --git a/examples/vulkan/hellovulkanwidget/hellovulkanwidget.cpp b/examples/vulkan/hellovulkanwidget/hellovulkanwidget.cpp new file mode 100644 index 0000000000..ecab104399 --- /dev/null +++ b/examples/vulkan/hellovulkanwidget/hellovulkanwidget.cpp @@ -0,0 +1,182 @@ +/**************************************************************************** +** +** Copyright (C) 2017 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 "hellovulkanwidget.h" +#include <QVulkanFunctions> +#include <QApplication> +#include <QVBoxLayout> +#include <QTextEdit> +#include <QPushButton> +#include <QLCDNumber> +#include <QFileDialog> +#include <QMessageBox> + +MainWindow::MainWindow(VulkanWindow *w) + : m_window(w) +{ + QWidget *wrapper = QWidget::createWindowContainer(w); + + m_info = new QTextEdit; + m_info->setReadOnly(true); + + m_number = new QLCDNumber(3); + m_number->setSegmentStyle(QLCDNumber::Filled); + + QPushButton *grabButton = new QPushButton(tr("&Grab")); + grabButton->setFocusPolicy(Qt::NoFocus); + + connect(grabButton, &QPushButton::clicked, this, &MainWindow::onGrabRequested); + + QPushButton *quitButton = new QPushButton(tr("&Quit")); + quitButton->setFocusPolicy(Qt::NoFocus); + + connect(quitButton, &QPushButton::clicked, qApp, &QCoreApplication::quit); + + QVBoxLayout *layout = new QVBoxLayout; + layout->addWidget(m_info, 2); + layout->addWidget(m_number, 1); + layout->addWidget(wrapper, 5); + layout->addWidget(grabButton, 1); + layout->addWidget(quitButton, 1); + setLayout(layout); +} + +void MainWindow::onVulkanInfoReceived(const QString &text) +{ + m_info->setText(text); +} + +void MainWindow::onFrameQueued(int colorValue) +{ + m_number->display(colorValue); +} + +void MainWindow::onGrabRequested() +{ + if (!m_window->supportsGrab()) { + QMessageBox::warning(this, tr("Cannot grab"), tr("This swapchain does not support readbacks.")); + return; + } + + QImage img = m_window->grab(); + + // Our startNextFrame() implementation is synchronous so img is ready to be + // used right here. + + QFileDialog fd(this); + fd.setAcceptMode(QFileDialog::AcceptSave); + fd.setDefaultSuffix("png"); + fd.selectFile("test.png"); + if (fd.exec() == QDialog::Accepted) + img.save(fd.selectedFiles().first()); +} + +QVulkanWindowRenderer *VulkanWindow::createRenderer() +{ + return new VulkanRenderer(this); +} + +VulkanRenderer::VulkanRenderer(VulkanWindow *w) + : TriangleRenderer(w) +{ +} + +void VulkanRenderer::initResources() +{ + TriangleRenderer::initResources(); + + QVulkanInstance *inst = m_window->vulkanInstance(); + m_devFuncs = inst->deviceFunctions(m_window->device()); + + QString info; + info += QString().sprintf("Number of physical devices: %d\n", m_window->availablePhysicalDevices().count()); + + QVulkanFunctions *f = inst->functions(); + VkPhysicalDeviceProperties props; + f->vkGetPhysicalDeviceProperties(m_window->physicalDevice(), &props); + info += QString().sprintf("Active physical device name: '%s' version %d.%d.%d\nAPI version %d.%d.%d\n", + props.deviceName, + VK_VERSION_MAJOR(props.driverVersion), VK_VERSION_MINOR(props.driverVersion), + VK_VERSION_PATCH(props.driverVersion), + VK_VERSION_MAJOR(props.apiVersion), VK_VERSION_MINOR(props.apiVersion), + VK_VERSION_PATCH(props.apiVersion)); + + info += QStringLiteral("Supported instance layers:\n"); + for (const QVulkanLayer &layer : inst->supportedLayers()) + info += QString().sprintf(" %s v%u\n", layer.name.constData(), layer.version); + info += QStringLiteral("Enabled instance layers:\n"); + for (const QByteArray &layer : inst->layers()) + info += QString().sprintf(" %s\n", layer.constData()); + + info += QStringLiteral("Supported instance extensions:\n"); + for (const QVulkanExtension &ext : inst->supportedExtensions()) + info += QString().sprintf(" %s v%u\n", ext.name.constData(), ext.version); + info += QStringLiteral("Enabled instance extensions:\n"); + for (const QByteArray &ext : inst->extensions()) + info += QString().sprintf(" %s\n", ext.constData()); + + info += QString().sprintf("Color format: %u\nDepth-stencil format: %u\n", + m_window->colorFormat(), m_window->depthStencilFormat()); + + info += QStringLiteral("Supported sample counts:"); + QList<int> sampleCounts = m_window->supportedSampleCounts().toList(); + std::sort(sampleCounts.begin(), sampleCounts.end()); + for (int count : sampleCounts) + info += QLatin1Char(' ') + QString::number(count); + info += QLatin1Char('\n'); + + emit static_cast<VulkanWindow *>(m_window)->vulkanInfoReceived(info); +} + +void VulkanRenderer::startNextFrame() +{ + TriangleRenderer::startNextFrame(); + emit static_cast<VulkanWindow *>(m_window)->frameQueued(int(m_rotation) % 360); +} diff --git a/examples/vulkan/hellovulkanwidget/hellovulkanwidget.h b/examples/vulkan/hellovulkanwidget/hellovulkanwidget.h new file mode 100644 index 0000000000..b1f4824006 --- /dev/null +++ b/examples/vulkan/hellovulkanwidget/hellovulkanwidget.h @@ -0,0 +1,98 @@ +/**************************************************************************** +** +** Copyright (C) 2017 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 "../shared/trianglerenderer.h" +#include <QWidget> + +class VulkanWindow; + +QT_BEGIN_NAMESPACE +class QTextEdit; +class QLCDNumber; +QT_END_NAMESPACE + +class MainWindow : public QWidget +{ + Q_OBJECT + +public: + MainWindow(VulkanWindow *w); + +public slots: + void onVulkanInfoReceived(const QString &text); + void onFrameQueued(int colorValue); + void onGrabRequested(); + +private: + VulkanWindow *m_window; + QTextEdit *m_info; + QLCDNumber *m_number; +}; + +class VulkanRenderer : public TriangleRenderer +{ +public: + VulkanRenderer(VulkanWindow *w); + + void initResources() override; + void startNextFrame() override; +}; + +class VulkanWindow : public QVulkanWindow +{ + Q_OBJECT + +public: + QVulkanWindowRenderer *createRenderer() override; + +signals: + void vulkanInfoReceived(const QString &text); + void frameQueued(int colorValue); +}; diff --git a/examples/vulkan/hellovulkanwidget/hellovulkanwidget.pro b/examples/vulkan/hellovulkanwidget/hellovulkanwidget.pro new file mode 100644 index 0000000000..7b87d7f210 --- /dev/null +++ b/examples/vulkan/hellovulkanwidget/hellovulkanwidget.pro @@ -0,0 +1,16 @@ +QT += widgets + +HEADERS += \ + hellovulkanwidget.h \ + ../shared/trianglerenderer.h + +SOURCES += \ + hellovulkanwidget.cpp \ + main.cpp \ + ../shared/trianglerenderer.cpp + +RESOURCES += hellovulkanwidget.qrc + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/vulkan/hellovulkanwidget +INSTALLS += target diff --git a/examples/vulkan/hellovulkanwidget/hellovulkanwidget.qrc b/examples/vulkan/hellovulkanwidget/hellovulkanwidget.qrc new file mode 100644 index 0000000000..489fc7295a --- /dev/null +++ b/examples/vulkan/hellovulkanwidget/hellovulkanwidget.qrc @@ -0,0 +1,6 @@ +<!DOCTYPE RCC><RCC version="1.0"> +<qresource> + <file alias="color_vert.spv">../shared/color_vert.spv</file> + <file alias="color_frag.spv">../shared/color_frag.spv</file> +</qresource> +</RCC> diff --git a/examples/vulkan/hellovulkanwidget/main.cpp b/examples/vulkan/hellovulkanwidget/main.cpp new file mode 100644 index 0000000000..320e015e67 --- /dev/null +++ b/examples/vulkan/hellovulkanwidget/main.cpp @@ -0,0 +1,93 @@ +/**************************************************************************** +** +** Copyright (C) 2017 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 <QApplication> +#include <QVulkanInstance> +#include <QLoggingCategory> +#include "hellovulkanwidget.h" + +Q_LOGGING_CATEGORY(lcVk, "qt.vulkan") + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + + QLoggingCategory::setFilterRules(QStringLiteral("qt.vulkan=true")); + + QVulkanInstance inst; + +#ifndef Q_OS_ANDROID + inst.setLayers(QByteArrayList() << "VK_LAYER_LUNARG_standard_validation"); +#else + inst.setLayers(QByteArrayList() + << "VK_LAYER_GOOGLE_threading" + << "VK_LAYER_LUNARG_parameter_validation" + << "VK_LAYER_LUNARG_object_tracker" + << "VK_LAYER_LUNARG_core_validation" + << "VK_LAYER_LUNARG_image" + << "VK_LAYER_LUNARG_swapchain" + << "VK_LAYER_GOOGLE_unique_objects"); +#endif + + if (!inst.create()) + qFatal("Failed to create Vulkan instance: %d", inst.errorCode()); + + VulkanWindow *vulkanWindow = new VulkanWindow; + vulkanWindow->setVulkanInstance(&inst); + + MainWindow mainWindow(vulkanWindow); + QObject::connect(vulkanWindow, &VulkanWindow::vulkanInfoReceived, &mainWindow, &MainWindow::onVulkanInfoReceived); + QObject::connect(vulkanWindow, &VulkanWindow::frameQueued, &mainWindow, &MainWindow::onFrameQueued); + + mainWindow.resize(1024, 768); + mainWindow.show(); + + return app.exec(); +} diff --git a/examples/vulkan/hellovulkanwindow/hellovulkanwindow.cpp b/examples/vulkan/hellovulkanwindow/hellovulkanwindow.cpp new file mode 100644 index 0000000000..0a7d1d4174 --- /dev/null +++ b/examples/vulkan/hellovulkanwindow/hellovulkanwindow.cpp @@ -0,0 +1,128 @@ +/**************************************************************************** +** +** Copyright (C) 2017 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 "hellovulkanwindow.h" +#include <QVulkanFunctions> + +//! [0] +QVulkanWindowRenderer *VulkanWindow::createRenderer() +{ + return new VulkanRenderer(this); +} + +VulkanRenderer::VulkanRenderer(QVulkanWindow *w) + : m_window(w) +{ +} +//! [0] + +//! [1] +void VulkanRenderer::initResources() +{ + qDebug("initResources"); + + m_devFuncs = m_window->vulkanInstance()->deviceFunctions(m_window->device()); +} +//! [1] + +void VulkanRenderer::initSwapChainResources() +{ + qDebug("initSwapChainResources"); +} + +void VulkanRenderer::releaseSwapChainResources() +{ + qDebug("releaseSwapChainResources"); +} + +void VulkanRenderer::releaseResources() +{ + qDebug("releaseResources"); +} + +//! [2] +void VulkanRenderer::startNextFrame() +{ + m_green += 0.005f; + if (m_green > 1.0f) + m_green = 0.0f; + + VkClearColorValue clearColor = { 0.0f, m_green, 0.0f, 1.0f }; + VkClearDepthStencilValue clearDS = { 1.0f, 0 }; + VkClearValue clearValues[2]; + memset(clearValues, 0, sizeof(clearValues)); + clearValues[0].color = clearColor; + clearValues[1].depthStencil = clearDS; + + VkRenderPassBeginInfo rpBeginInfo; + memset(&rpBeginInfo, 0, sizeof(rpBeginInfo)); + rpBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; + rpBeginInfo.renderPass = m_window->defaultRenderPass(); + rpBeginInfo.framebuffer = m_window->currentFramebuffer(); + const QSize sz = m_window->swapChainImageSize(); + rpBeginInfo.renderArea.extent.width = sz.width(); + rpBeginInfo.renderArea.extent.height = sz.height(); + rpBeginInfo.clearValueCount = 2; + rpBeginInfo.pClearValues = clearValues; + VkCommandBuffer cmdBuf = m_window->currentCommandBuffer(); + m_devFuncs->vkCmdBeginRenderPass(cmdBuf, &rpBeginInfo, VK_SUBPASS_CONTENTS_INLINE); + + // Do nothing else. We will just clear to green, changing the component on + // every invocation. This also helps verifying the rate to which the thread + // is throttled to. (The elapsed time between startNextFrame calls should + // typically be around 16 ms. Note that rendering is 2 frames ahead of what + // is displayed.) + + m_devFuncs->vkCmdEndRenderPass(cmdBuf); + + m_window->frameReady(); + m_window->requestUpdate(); // render continuously, throttled by the presentation rate +} +//! [2] diff --git a/examples/vulkan/hellovulkanwindow/hellovulkanwindow.h b/examples/vulkan/hellovulkanwindow/hellovulkanwindow.h new file mode 100644 index 0000000000..5f52e402ca --- /dev/null +++ b/examples/vulkan/hellovulkanwindow/hellovulkanwindow.h @@ -0,0 +1,77 @@ +/**************************************************************************** +** +** Copyright (C) 2017 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 <QVulkanWindow> + +//! [0] +class VulkanRenderer : public QVulkanWindowRenderer +{ +public: + VulkanRenderer(QVulkanWindow *w); + + void initResources() override; + void initSwapChainResources() override; + void releaseSwapChainResources() override; + void releaseResources() override; + + void startNextFrame() override; + +private: + QVulkanWindow *m_window; + QVulkanDeviceFunctions *m_devFuncs; + float m_green = 0; +}; + +class VulkanWindow : public QVulkanWindow +{ +public: + QVulkanWindowRenderer *createRenderer() override; +}; +//! [0] diff --git a/examples/vulkan/hellovulkanwindow/hellovulkanwindow.pro b/examples/vulkan/hellovulkanwindow/hellovulkanwindow.pro new file mode 100644 index 0000000000..8f7d9494e2 --- /dev/null +++ b/examples/vulkan/hellovulkanwindow/hellovulkanwindow.pro @@ -0,0 +1,6 @@ +HEADERS += hellovulkanwindow.h +SOURCES += hellovulkanwindow.cpp main.cpp + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/vulkan/hellovulkanwindow +INSTALLS += target diff --git a/examples/vulkan/hellovulkanwindow/main.cpp b/examples/vulkan/hellovulkanwindow/main.cpp new file mode 100644 index 0000000000..313c28f9e0 --- /dev/null +++ b/examples/vulkan/hellovulkanwindow/main.cpp @@ -0,0 +1,93 @@ +/**************************************************************************** +** +** Copyright (C) 2017 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 <QGuiApplication> +#include <QVulkanInstance> +#include <QLoggingCategory> +#include "hellovulkanwindow.h" + +Q_LOGGING_CATEGORY(lcVk, "qt.vulkan") + +int main(int argc, char *argv[]) +{ + QGuiApplication app(argc, argv); + + QLoggingCategory::setFilterRules(QStringLiteral("qt.vulkan=true")); + +//! [0] + QVulkanInstance inst; + +#ifndef Q_OS_ANDROID + inst.setLayers(QByteArrayList() << "VK_LAYER_LUNARG_standard_validation"); +#else + inst.setLayers(QByteArrayList() + << "VK_LAYER_GOOGLE_threading" + << "VK_LAYER_LUNARG_parameter_validation" + << "VK_LAYER_LUNARG_object_tracker" + << "VK_LAYER_LUNARG_core_validation" + << "VK_LAYER_LUNARG_image" + << "VK_LAYER_LUNARG_swapchain" + << "VK_LAYER_GOOGLE_unique_objects"); +#endif + + if (!inst.create()) + qFatal("Failed to create Vulkan instance: %d", inst.errorCode()); +//! [0] + +//! [1] + VulkanWindow w; + w.setVulkanInstance(&inst); + + w.resize(1024, 768); + w.show(); +//! [1] + + return app.exec(); +} diff --git a/examples/vulkan/shared/color.frag b/examples/vulkan/shared/color.frag new file mode 100644 index 0000000000..375587662f --- /dev/null +++ b/examples/vulkan/shared/color.frag @@ -0,0 +1,10 @@ +#version 440 + +layout(location = 0) in vec3 v_color; + +layout(location = 0) out vec4 fragColor; + +void main() +{ + fragColor = vec4(v_color, 1.0); +} diff --git a/examples/vulkan/shared/color.vert b/examples/vulkan/shared/color.vert new file mode 100644 index 0000000000..02492c0e65 --- /dev/null +++ b/examples/vulkan/shared/color.vert @@ -0,0 +1,18 @@ +#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; +} ubuf; + +out gl_PerVertex { vec4 gl_Position; }; + +void main() +{ + v_color = color; + gl_Position = ubuf.mvp * position; +} diff --git a/examples/vulkan/shared/color_frag.spv b/examples/vulkan/shared/color_frag.spv Binary files differnew file mode 100644 index 0000000000..30e33b76ca --- /dev/null +++ b/examples/vulkan/shared/color_frag.spv diff --git a/examples/vulkan/shared/color_vert.spv b/examples/vulkan/shared/color_vert.spv Binary files differnew file mode 100644 index 0000000000..a1f42e3119 --- /dev/null +++ b/examples/vulkan/shared/color_vert.spv diff --git a/examples/vulkan/shared/trianglerenderer.cpp b/examples/vulkan/shared/trianglerenderer.cpp new file mode 100644 index 0000000000..a0800080a0 --- /dev/null +++ b/examples/vulkan/shared/trianglerenderer.cpp @@ -0,0 +1,513 @@ +/**************************************************************************** +** +** Copyright (C) 2017 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 "trianglerenderer.h" +#include <QVulkanFunctions> +#include <QFile> + +// Note that the vertex data and the projection matrix assume OpenGL. With +// Vulkan Y is negated in clip space and the near/far plane is at 0/1 instead +// of -1/1. These will be corrected for by an extra transformation when +// calculating the modelview-projection matrix. +static float vertexData[] = { + 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 +}; + +static const int UNIFORM_DATA_SIZE = 16 * sizeof(float); + +static inline VkDeviceSize aligned(VkDeviceSize v, VkDeviceSize byteAlign) +{ + return (v + byteAlign - 1) & ~(byteAlign - 1); +} + +TriangleRenderer::TriangleRenderer(QVulkanWindow *w, bool msaa) + : m_window(w) +{ + if (msaa) { + QSet<int> counts = w->supportedSampleCounts(); + qDebug() << "Supported sample counts:" << counts; + for (int s = 16; s >= 4; s /= 2) { + if (counts.contains(s)) { + qDebug("Requesting sample count %d", s); + m_window->setSampleCount(s); + break; + } + } + } +} + +VkShaderModule TriangleRenderer::createShader(const QString &name) +{ + QFile file(name); + if (!file.open(QIODevice::ReadOnly)) { + qWarning("Failed to read shader %s", qPrintable(name)); + return VK_NULL_HANDLE; + } + QByteArray blob = file.readAll(); + file.close(); + + VkShaderModuleCreateInfo shaderInfo; + memset(&shaderInfo, 0, sizeof(shaderInfo)); + shaderInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + shaderInfo.codeSize = blob.size(); + shaderInfo.pCode = reinterpret_cast<const uint32_t *>(blob.constData()); + VkShaderModule shaderModule; + VkResult err = m_devFuncs->vkCreateShaderModule(m_window->device(), &shaderInfo, nullptr, &shaderModule); + if (err != VK_SUCCESS) { + qWarning("Failed to create shader module: %d", err); + return VK_NULL_HANDLE; + } + + return shaderModule; +} + +void TriangleRenderer::initResources() +{ + qDebug("initResources"); + + VkDevice dev = m_window->device(); + m_devFuncs = m_window->vulkanInstance()->deviceFunctions(dev); + + // Prepare the vertex and uniform data. The vertex data will never + // change so one buffer is sufficient regardless of the value of + // QVulkanWindow::CONCURRENT_FRAME_COUNT. Uniform data is changing per + // frame however so active frames have to have a dedicated copy. + + // Use just one memory allocation and one buffer. We will then specify the + // appropriate offsets for uniform buffers in the VkDescriptorBufferInfo. + // Have to watch out for + // VkPhysicalDeviceLimits::minUniformBufferOffsetAlignment, though. + + // The uniform buffer is not strictly required in this example, we could + // have used push constants as well since our single matrix (64 bytes) fits + // into the spec mandated minimum limit of 128 bytes. However, once that + // limit is not sufficient, the per-frame buffers, as shown below, will + // become necessary. + + const int concurrentFrameCount = m_window->concurrentFrameCount(); + const VkPhysicalDeviceLimits *pdevLimits = &m_window->physicalDeviceProperties()->limits; + const VkDeviceSize uniAlign = pdevLimits->minUniformBufferOffsetAlignment; + qDebug("uniform buffer offset alignment is %u", (uint) uniAlign); + VkBufferCreateInfo bufInfo; + memset(&bufInfo, 0, sizeof(bufInfo)); + bufInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + // Our internal layout is vertex, uniform, uniform, ... with each uniform buffer start offset aligned to uniAlign. + const VkDeviceSize vertexAllocSize = aligned(sizeof(vertexData), uniAlign); + const VkDeviceSize uniformAllocSize = aligned(UNIFORM_DATA_SIZE, uniAlign); + bufInfo.size = vertexAllocSize + concurrentFrameCount * uniformAllocSize; + bufInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; + + VkResult err = m_devFuncs->vkCreateBuffer(dev, &bufInfo, nullptr, &m_buf); + if (err != VK_SUCCESS) + qFatal("Failed to create buffer: %d", err); + + VkMemoryRequirements memReq; + m_devFuncs->vkGetBufferMemoryRequirements(dev, m_buf, &memReq); + + VkMemoryAllocateInfo memAllocInfo = { + VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + nullptr, + memReq.size, + m_window->hostVisibleMemoryIndex() + }; + + err = m_devFuncs->vkAllocateMemory(dev, &memAllocInfo, nullptr, &m_bufMem); + if (err != VK_SUCCESS) + qFatal("Failed to allocate memory: %d", err); + + err = m_devFuncs->vkBindBufferMemory(dev, m_buf, m_bufMem, 0); + if (err != VK_SUCCESS) + qFatal("Failed to bind buffer memory: %d", err); + + quint8 *p; + err = m_devFuncs->vkMapMemory(dev, m_bufMem, 0, memReq.size, 0, reinterpret_cast<void **>(&p)); + if (err != VK_SUCCESS) + qFatal("Failed to map memory: %d", err); + memcpy(p, vertexData, sizeof(vertexData)); + QMatrix4x4 ident; + memset(m_uniformBufInfo, 0, sizeof(m_uniformBufInfo)); + for (int i = 0; i < concurrentFrameCount; ++i) { + const VkDeviceSize offset = vertexAllocSize + i * uniformAllocSize; + memcpy(p + offset, ident.constData(), 16 * sizeof(float)); + m_uniformBufInfo[i].buffer = m_buf; + m_uniformBufInfo[i].offset = offset; + m_uniformBufInfo[i].range = uniformAllocSize; + } + m_devFuncs->vkUnmapMemory(dev, m_bufMem); + + VkVertexInputBindingDescription vertexBindingDesc = { + 0, // binding + 5 * sizeof(float), + VK_VERTEX_INPUT_RATE_VERTEX + }; + VkVertexInputAttributeDescription vertexAttrDesc[] = { + { // position + 0, // location + 0, // binding + VK_FORMAT_R32G32_SFLOAT, + 0 + }, + { // color + 1, + 0, + VK_FORMAT_R32G32B32_SFLOAT, + 2 * sizeof(float) + } + }; + + VkPipelineVertexInputStateCreateInfo vertexInputInfo; + vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; + vertexInputInfo.pNext = nullptr; + vertexInputInfo.flags = 0; + vertexInputInfo.vertexBindingDescriptionCount = 1; + vertexInputInfo.pVertexBindingDescriptions = &vertexBindingDesc; + vertexInputInfo.vertexAttributeDescriptionCount = 2; + vertexInputInfo.pVertexAttributeDescriptions = vertexAttrDesc; + + // Set up descriptor set and its layout. + VkDescriptorPoolSize descPoolSizes = { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, uint32_t(concurrentFrameCount) }; + VkDescriptorPoolCreateInfo descPoolInfo; + memset(&descPoolInfo, 0, sizeof(descPoolInfo)); + descPoolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; + descPoolInfo.maxSets = concurrentFrameCount; + descPoolInfo.poolSizeCount = 1; + descPoolInfo.pPoolSizes = &descPoolSizes; + err = m_devFuncs->vkCreateDescriptorPool(dev, &descPoolInfo, nullptr, &m_descPool); + if (err != VK_SUCCESS) + qFatal("Failed to create descriptor pool: %d", err); + + VkDescriptorSetLayoutBinding layoutBinding = { + 0, // binding + VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + 1, + VK_SHADER_STAGE_VERTEX_BIT, + nullptr + }; + VkDescriptorSetLayoutCreateInfo descLayoutInfo = { + VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, + nullptr, + 0, + 1, + &layoutBinding + }; + err = m_devFuncs->vkCreateDescriptorSetLayout(dev, &descLayoutInfo, nullptr, &m_descSetLayout); + if (err != VK_SUCCESS) + qFatal("Failed to create descriptor set layout: %d", err); + + for (int i = 0; i < concurrentFrameCount; ++i) { + VkDescriptorSetAllocateInfo descSetAllocInfo = { + VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, + nullptr, + m_descPool, + 1, + &m_descSetLayout + }; + err = m_devFuncs->vkAllocateDescriptorSets(dev, &descSetAllocInfo, &m_descSet[i]); + if (err != VK_SUCCESS) + qFatal("Failed to allocate descriptor set: %d", err); + + VkWriteDescriptorSet descWrite; + memset(&descWrite, 0, sizeof(descWrite)); + descWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descWrite.dstSet = m_descSet[i]; + descWrite.descriptorCount = 1; + descWrite.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + descWrite.pBufferInfo = &m_uniformBufInfo[i]; + m_devFuncs->vkUpdateDescriptorSets(dev, 1, &descWrite, 0, nullptr); + } + + // Pipeline cache + VkPipelineCacheCreateInfo pipelineCacheInfo; + memset(&pipelineCacheInfo, 0, sizeof(pipelineCacheInfo)); + pipelineCacheInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO; + err = m_devFuncs->vkCreatePipelineCache(dev, &pipelineCacheInfo, nullptr, &m_pipelineCache); + if (err != VK_SUCCESS) + qFatal("Failed to create pipeline cache: %d", err); + + // Pipeline layout + VkPipelineLayoutCreateInfo pipelineLayoutInfo; + memset(&pipelineLayoutInfo, 0, sizeof(pipelineLayoutInfo)); + pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; + pipelineLayoutInfo.setLayoutCount = 1; + pipelineLayoutInfo.pSetLayouts = &m_descSetLayout; + err = m_devFuncs->vkCreatePipelineLayout(dev, &pipelineLayoutInfo, nullptr, &m_pipelineLayout); + if (err != VK_SUCCESS) + qFatal("Failed to create pipeline layout: %d", err); + + // Shaders + VkShaderModule vertShaderModule = createShader(QStringLiteral(":/color_vert.spv")); + VkShaderModule fragShaderModule = createShader(QStringLiteral(":/color_frag.spv")); + + // Graphics pipeline + VkGraphicsPipelineCreateInfo pipelineInfo; + memset(&pipelineInfo, 0, sizeof(pipelineInfo)); + pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; + + VkPipelineShaderStageCreateInfo shaderStages[2] = { + { + VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + nullptr, + 0, + VK_SHADER_STAGE_VERTEX_BIT, + vertShaderModule, + "main", + nullptr + }, + { + VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + nullptr, + 0, + VK_SHADER_STAGE_FRAGMENT_BIT, + fragShaderModule, + "main", + nullptr + } + }; + pipelineInfo.stageCount = 2; + pipelineInfo.pStages = shaderStages; + + pipelineInfo.pVertexInputState = &vertexInputInfo; + + VkPipelineInputAssemblyStateCreateInfo ia; + memset(&ia, 0, sizeof(ia)); + ia.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; + ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + pipelineInfo.pInputAssemblyState = &ia; + + // The viewport and scissor will be set dynamically via vkCmdSetViewport/Scissor. + // This way the pipeline does not need to be touched when resizing the window. + VkPipelineViewportStateCreateInfo vp; + memset(&vp, 0, sizeof(vp)); + vp.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; + vp.viewportCount = 1; + vp.scissorCount = 1; + pipelineInfo.pViewportState = &vp; + + VkPipelineRasterizationStateCreateInfo rs; + memset(&rs, 0, sizeof(rs)); + rs.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; + rs.polygonMode = VK_POLYGON_MODE_FILL; + rs.cullMode = VK_CULL_MODE_NONE; // we want the back face as well + rs.frontFace = VK_FRONT_FACE_CLOCKWISE; + rs.lineWidth = 1.0f; + pipelineInfo.pRasterizationState = &rs; + + VkPipelineMultisampleStateCreateInfo ms; + memset(&ms, 0, sizeof(ms)); + ms.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; + // Enable multisampling. + ms.rasterizationSamples = m_window->sampleCountFlagBits(); + pipelineInfo.pMultisampleState = &ms; + + VkPipelineDepthStencilStateCreateInfo ds; + memset(&ds, 0, sizeof(ds)); + ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; + ds.depthTestEnable = VK_TRUE; + ds.depthWriteEnable = VK_TRUE; + ds.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL; + pipelineInfo.pDepthStencilState = &ds; + + VkPipelineColorBlendStateCreateInfo cb; + memset(&cb, 0, sizeof(cb)); + cb.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; + // no blend, write out all of rgba + VkPipelineColorBlendAttachmentState att; + memset(&att, 0, sizeof(att)); + att.colorWriteMask = 0xF; + cb.attachmentCount = 1; + cb.pAttachments = &att; + pipelineInfo.pColorBlendState = &cb; + + VkDynamicState dynEnable[] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; + VkPipelineDynamicStateCreateInfo dyn; + memset(&dyn, 0, sizeof(dyn)); + dyn.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; + dyn.dynamicStateCount = sizeof(dynEnable) / sizeof(VkDynamicState); + dyn.pDynamicStates = dynEnable; + pipelineInfo.pDynamicState = &dyn; + + pipelineInfo.layout = m_pipelineLayout; + pipelineInfo.renderPass = m_window->defaultRenderPass(); + + err = m_devFuncs->vkCreateGraphicsPipelines(dev, m_pipelineCache, 1, &pipelineInfo, nullptr, &m_pipeline); + if (err != VK_SUCCESS) + qFatal("Failed to create graphics pipeline: %d", err); + + if (vertShaderModule) + m_devFuncs->vkDestroyShaderModule(dev, vertShaderModule, nullptr); + if (fragShaderModule) + m_devFuncs->vkDestroyShaderModule(dev, fragShaderModule, nullptr); +} + +void TriangleRenderer::initSwapChainResources() +{ + qDebug("initSwapChainResources"); + + // Projection matrix + m_proj = *m_window->clipCorrectionMatrix(); // adjust for Vulkan-OpenGL clip space differences + const QSize sz = m_window->swapChainImageSize(); + m_proj.perspective(45.0f, sz.width() / (float) sz.height(), 0.01f, 100.0f); + m_proj.translate(0, 0, -4); +} + +void TriangleRenderer::releaseSwapChainResources() +{ + qDebug("releaseSwapChainResources"); +} + +void TriangleRenderer::releaseResources() +{ + qDebug("releaseResources"); + + VkDevice dev = m_window->device(); + + if (m_pipeline) { + m_devFuncs->vkDestroyPipeline(dev, m_pipeline, nullptr); + m_pipeline = VK_NULL_HANDLE; + } + + if (m_pipelineLayout) { + m_devFuncs->vkDestroyPipelineLayout(dev, m_pipelineLayout, nullptr); + m_pipelineLayout = VK_NULL_HANDLE; + } + + if (m_pipelineCache) { + m_devFuncs->vkDestroyPipelineCache(dev, m_pipelineCache, nullptr); + m_pipelineCache = VK_NULL_HANDLE; + } + + if (m_descSetLayout) { + m_devFuncs->vkDestroyDescriptorSetLayout(dev, m_descSetLayout, nullptr); + m_descSetLayout = VK_NULL_HANDLE; + } + + if (m_descPool) { + m_devFuncs->vkDestroyDescriptorPool(dev, m_descPool, nullptr); + m_descPool = VK_NULL_HANDLE; + } + + if (m_buf) { + m_devFuncs->vkDestroyBuffer(dev, m_buf, nullptr); + m_buf = VK_NULL_HANDLE; + } + + if (m_bufMem) { + m_devFuncs->vkFreeMemory(dev, m_bufMem, nullptr); + m_bufMem = VK_NULL_HANDLE; + } +} + +void TriangleRenderer::startNextFrame() +{ + VkDevice dev = m_window->device(); + VkCommandBuffer cb = m_window->currentCommandBuffer(); + const QSize sz = m_window->swapChainImageSize(); + + VkClearColorValue clearColor = { 0, 0, 0, 1 }; + VkClearDepthStencilValue clearDS = { 1, 0 }; + VkClearValue clearValues[3]; + memset(clearValues, 0, sizeof(clearValues)); + clearValues[0].color = clearValues[2].color = clearColor; + clearValues[1].depthStencil = clearDS; + + VkRenderPassBeginInfo rpBeginInfo; + memset(&rpBeginInfo, 0, sizeof(rpBeginInfo)); + rpBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; + rpBeginInfo.renderPass = m_window->defaultRenderPass(); + rpBeginInfo.framebuffer = m_window->currentFramebuffer(); + rpBeginInfo.renderArea.extent.width = sz.width(); + rpBeginInfo.renderArea.extent.height = sz.height(); + rpBeginInfo.clearValueCount = m_window->sampleCountFlagBits() > VK_SAMPLE_COUNT_1_BIT ? 3 : 2; + rpBeginInfo.pClearValues = clearValues; + VkCommandBuffer cmdBuf = m_window->currentCommandBuffer(); + m_devFuncs->vkCmdBeginRenderPass(cmdBuf, &rpBeginInfo, VK_SUBPASS_CONTENTS_INLINE); + + quint8 *p; + VkResult err = m_devFuncs->vkMapMemory(dev, m_bufMem, m_uniformBufInfo[m_window->currentFrame()].offset, + UNIFORM_DATA_SIZE, 0, reinterpret_cast<void **>(&p)); + if (err != VK_SUCCESS) + qFatal("Failed to map memory: %d", err); + QMatrix4x4 m = m_proj; + m.rotate(m_rotation, 0, 1, 0); + memcpy(p, m.constData(), 16 * sizeof(float)); + m_devFuncs->vkUnmapMemory(dev, m_bufMem); + + // Not exactly a real animation system, just advance on every frame for now. + m_rotation += 1.0f; + + m_devFuncs->vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipeline); + m_devFuncs->vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipelineLayout, 0, 1, + &m_descSet[m_window->currentFrame()], 0, nullptr); + VkDeviceSize vbOffset = 0; + m_devFuncs->vkCmdBindVertexBuffers(cb, 0, 1, &m_buf, &vbOffset); + + VkViewport viewport; + viewport.x = viewport.y = 0; + viewport.width = sz.width(); + viewport.height = sz.height(); + viewport.minDepth = 0; + viewport.maxDepth = 1; + m_devFuncs->vkCmdSetViewport(cb, 0, 1, &viewport); + + VkRect2D scissor; + scissor.offset.x = scissor.offset.y = 0; + scissor.extent.width = viewport.width; + scissor.extent.height = viewport.height; + m_devFuncs->vkCmdSetScissor(cb, 0, 1, &scissor); + + m_devFuncs->vkCmdDraw(cb, 3, 1, 0, 0); + + m_devFuncs->vkCmdEndRenderPass(cmdBuf); + + m_window->frameReady(); + m_window->requestUpdate(); // render continuously, throttled by the presentation rate +} diff --git a/examples/vulkan/shared/trianglerenderer.h b/examples/vulkan/shared/trianglerenderer.h new file mode 100644 index 0000000000..9a33291a95 --- /dev/null +++ b/examples/vulkan/shared/trianglerenderer.h @@ -0,0 +1,85 @@ +/**************************************************************************** +** +** Copyright (C) 2017 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 <QVulkanWindow> + +class TriangleRenderer : public QVulkanWindowRenderer +{ +public: + TriangleRenderer(QVulkanWindow *w, bool msaa = false); + + void initResources() override; + void initSwapChainResources() override; + void releaseSwapChainResources() override; + void releaseResources() override; + + void startNextFrame() override; + +protected: + VkShaderModule createShader(const QString &name); + + QVulkanWindow *m_window; + QVulkanDeviceFunctions *m_devFuncs; + + VkDeviceMemory m_bufMem = VK_NULL_HANDLE; + VkBuffer m_buf = VK_NULL_HANDLE; + VkDescriptorBufferInfo m_uniformBufInfo[QVulkanWindow::MAX_CONCURRENT_FRAME_COUNT]; + + VkDescriptorPool m_descPool = VK_NULL_HANDLE; + VkDescriptorSetLayout m_descSetLayout = VK_NULL_HANDLE; + VkDescriptorSet m_descSet[QVulkanWindow::MAX_CONCURRENT_FRAME_COUNT]; + + VkPipelineCache m_pipelineCache = VK_NULL_HANDLE; + VkPipelineLayout m_pipelineLayout = VK_NULL_HANDLE; + VkPipeline m_pipeline = VK_NULL_HANDLE; + + QMatrix4x4 m_proj; + float m_rotation = 0.0f; +}; diff --git a/examples/vulkan/vulkan.pro b/examples/vulkan/vulkan.pro new file mode 100644 index 0000000000..ef5496bcd4 --- /dev/null +++ b/examples/vulkan/vulkan.pro @@ -0,0 +1,7 @@ +TEMPLATE = subdirs + +SUBDIRS = hellovulkanwindow \ + hellovulkantriangle \ + hellovulkantexture + +qtHaveModule(widgets): SUBDIRS += hellovulkanwidget diff --git a/examples/widgets/graphicsview/collidingmice/mouse.cpp b/examples/widgets/graphicsview/collidingmice/mouse.cpp index b94c650c18..cc1a15cd82 100644 --- a/examples/widgets/graphicsview/collidingmice/mouse.cpp +++ b/examples/widgets/graphicsview/collidingmice/mouse.cpp @@ -54,7 +54,7 @@ #include <QPainter> #include <QStyleOption> -#include <math.h> +#include <cmath> static const double Pi = 3.14159265358979323846264338327950288419717; static double TwoPi = 2.0 * Pi; @@ -140,9 +140,7 @@ void Mouse::advance(int step) //! [5] QLineF lineToCenter(QPointF(0, 0), mapFromScene(0, 0)); if (lineToCenter.length() > 150) { - qreal angleToCenter = ::acos(lineToCenter.dx() / lineToCenter.length()); - if (lineToCenter.dy() < 0) - angleToCenter = TwoPi - angleToCenter; + qreal angleToCenter = std::atan2(lineToCenter.dy(), lineToCenter.dx()); angleToCenter = normalizeAngle((Pi - angleToCenter) + Pi / 2); if (angleToCenter < Pi && angleToCenter > Pi / 4) { @@ -171,9 +169,7 @@ void Mouse::advance(int step) continue; QLineF lineToMouse(QPointF(0, 0), mapFromItem(item, 0, 0)); - qreal angleToMouse = ::acos(lineToMouse.dx() / lineToMouse.length()); - if (lineToMouse.dy() < 0) - angleToMouse = TwoPi - angleToMouse; + qreal angleToMouse = std::atan2(lineToMouse.dy(), lineToMouse.dx()); angleToMouse = normalizeAngle((Pi - angleToMouse) + Pi / 2); if (angleToMouse >= 0 && angleToMouse < Pi / 2) { diff --git a/examples/widgets/graphicsview/diagramscene/arrow.cpp b/examples/widgets/graphicsview/diagramscene/arrow.cpp index 012b9ea2ed..ae7fa7af90 100644 --- a/examples/widgets/graphicsview/diagramscene/arrow.cpp +++ b/examples/widgets/graphicsview/diagramscene/arrow.cpp @@ -51,7 +51,7 @@ #include "arrow.h" -#include <math.h> +#include <cmath> #include <QPen> #include <QPainter> @@ -132,9 +132,7 @@ void Arrow::paint(QPainter *painter, const QStyleOptionGraphicsItem *, setLine(QLineF(intersectPoint, myStartItem->pos())); //! [5] //! [6] - double angle = ::acos(line().dx() / line().length()); - if (line().dy() >= 0) - angle = (Pi * 2) - angle; + double angle = std::atan2(-line().dy(), line().dx()); QPointF arrowP1 = line().p1() + QPointF(sin(angle + Pi / 3) * arrowSize, cos(angle + Pi / 3) * arrowSize); diff --git a/examples/widgets/graphicsview/elasticnodes/edge.cpp b/examples/widgets/graphicsview/elasticnodes/edge.cpp index e794e803cf..d9e4c62e34 100644 --- a/examples/widgets/graphicsview/elasticnodes/edge.cpp +++ b/examples/widgets/graphicsview/elasticnodes/edge.cpp @@ -51,12 +51,11 @@ #include "edge.h" #include "node.h" -#include <math.h> +#include <cmath> #include <QPainter> static const double Pi = 3.14159265358979323846264338327950288419717; -static double TwoPi = 2.0 * Pi; //! [0] Edge::Edge(Node *sourceNode, Node *destNode) @@ -139,9 +138,7 @@ void Edge::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) //! [6] // Draw the arrows - double angle = ::acos(line.dx() / line.length()); - if (line.dy() >= 0) - angle = TwoPi - angle; + double angle = std::atan2(-line.dy(), line.dx()); QPointF sourceArrowP1 = sourcePoint + QPointF(sin(angle + Pi / 3) * arrowSize, cos(angle + Pi / 3) * arrowSize); diff --git a/examples/widgets/itemviews/chart/pieview.cpp b/examples/widgets/itemviews/chart/pieview.cpp index fb439fae67..942bbe5ca5 100644 --- a/examples/widgets/itemviews/chart/pieview.cpp +++ b/examples/widgets/itemviews/chart/pieview.cpp @@ -125,9 +125,9 @@ QModelIndex PieView::indexAt(const QPoint &point) const return QModelIndex(); // Determine the angle of the point. - double angle = (180 / M_PI) * std::acos(cx / d); - if (cy < 0) - angle = 360 - angle; + double angle = (180 / M_PI) * std::atan2(cy, cx); + if (angle < 0) + angle = 360 + angle; // Find the relevant slice of the pie. double startAngle = 0.0; diff --git a/examples/widgets/mainwindows/mainwindow/mainwindow.cpp b/examples/widgets/mainwindows/mainwindow/mainwindow.cpp index 10e3dd045a..afceddfca1 100644 --- a/examples/widgets/mainwindows/mainwindow/mainwindow.cpp +++ b/examples/widgets/mainwindows/mainwindow/mainwindow.cpp @@ -63,7 +63,6 @@ #include <QFileDialog> #include <QDialogButtonBox> #include <QMessageBox> -#include <QSignalMapper> #include <QApplication> #include <QPainter> #include <QMouseEvent> diff --git a/examples/xml/dombookmarks/mainwindow.cpp b/examples/xml/dombookmarks/mainwindow.cpp index e0f208d336..fade2dfc96 100644 --- a/examples/xml/dombookmarks/mainwindow.cpp +++ b/examples/xml/dombookmarks/mainwindow.cpp @@ -58,13 +58,13 @@ MainWindow::MainWindow() xbelTree = new XbelTree; setCentralWidget(xbelTree); - createActions(); createMenus(); statusBar()->showMessage(tr("Ready")); setWindowTitle(tr("DOM Bookmarks")); - resize(480, 320); + const QSize availableSize = QApplication::desktop()->availableGeometry(this).size(); + resize(availableSize.width() / 2, availableSize.height() / 3); } void MainWindow::open() @@ -80,8 +80,8 @@ void MainWindow::open() if (!file.open(QFile::ReadOnly | QFile::Text)) { QMessageBox::warning(this, tr("SAX Bookmarks"), tr("Cannot read file %1:\n%2.") - .arg(fileName) - .arg(file.errorString())); + .arg(QDir::toNativeSeparators(fileName), + file.errorString())); return; } @@ -102,8 +102,8 @@ void MainWindow::saveAs() if (!file.open(QFile::WriteOnly | QFile::Text)) { QMessageBox::warning(this, tr("SAX Bookmarks"), tr("Cannot write file %1:\n%2.") - .arg(fileName) - .arg(file.errorString())); + .arg(QDir::toNativeSeparators(fileName), + file.errorString())); return; } @@ -119,37 +119,21 @@ void MainWindow::about() "documents.")); } -void MainWindow::createActions() +void MainWindow::createMenus() { - openAct = new QAction(tr("&Open..."), this); + QMenu *fileMenu = menuBar()->addMenu(tr("&File")); + QAction *openAct = fileMenu->addAction(tr("&Open..."), this, &MainWindow::open); openAct->setShortcuts(QKeySequence::Open); - connect(openAct, SIGNAL(triggered()), this, SLOT(open())); - saveAsAct = new QAction(tr("&Save As..."), this); + QAction *saveAsAct = fileMenu->addAction(tr("&Save As..."), this, &MainWindow::saveAs); saveAsAct->setShortcuts(QKeySequence::SaveAs); - connect(saveAsAct, SIGNAL(triggered()), this, SLOT(saveAs())); - exitAct = new QAction(tr("E&xit"), this); + QAction *exitAct = fileMenu->addAction(tr("E&xit"), this, &QWidget::close); exitAct->setShortcuts(QKeySequence::Quit); - connect(exitAct, SIGNAL(triggered()), this, SLOT(close())); - - aboutAct = new QAction(tr("&About"), this); - connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); - - aboutQtAct = new QAction(tr("About &Qt"), this); - connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt())); -} - -void MainWindow::createMenus() -{ - fileMenu = menuBar()->addMenu(tr("&File")); - fileMenu->addAction(openAct); - fileMenu->addAction(saveAsAct); - fileMenu->addAction(exitAct); menuBar()->addSeparator(); - helpMenu = menuBar()->addMenu(tr("&Help")); - helpMenu->addAction(aboutAct); - helpMenu->addAction(aboutQtAct); + QMenu *helpMenu = menuBar()->addMenu(tr("&Help")); + helpMenu->addAction(tr("&About"), this, &MainWindow::about); + helpMenu->addAction(tr("About &Qt"), qApp, &QCoreApplication::quit); } diff --git a/examples/xml/dombookmarks/mainwindow.h b/examples/xml/dombookmarks/mainwindow.h index 6d490caf64..0a8c7bdd82 100644 --- a/examples/xml/dombookmarks/mainwindow.h +++ b/examples/xml/dombookmarks/mainwindow.h @@ -68,18 +68,9 @@ public slots: void about(); private: - void createActions(); void createMenus(); XbelTree *xbelTree; - - QMenu *fileMenu; - QMenu *helpMenu; - QAction *openAct; - QAction *saveAsAct; - QAction *exitAct; - QAction *aboutAct; - QAction *aboutQtAct; }; #endif diff --git a/examples/xml/dombookmarks/xbeltree.cpp b/examples/xml/dombookmarks/xbeltree.cpp index 82afc48bd9..f7ff1de638 100644 --- a/examples/xml/dombookmarks/xbeltree.cpp +++ b/examples/xml/dombookmarks/xbeltree.cpp @@ -52,6 +52,18 @@ #include "xbeltree.h" +enum { DomElementRole = Qt::UserRole + 1 }; + +Q_DECLARE_METATYPE(QDomElement) + +static inline QString titleElement() { return QStringLiteral("title"); } +static inline QString folderElement() { return QStringLiteral("folder"); } +static inline QString bookmarkElement() { return QStringLiteral("bookmark"); } + +static inline QString versionAttribute() { return QStringLiteral("version"); } +static inline QString hrefAttribute() { return QStringLiteral("href"); } +static inline QString foldedAttribute() { return QStringLiteral("folded"); } + XbelTree::XbelTree(QWidget *parent) : QTreeWidget(parent) { @@ -68,6 +80,24 @@ XbelTree::XbelTree(QWidget *parent) bookmarkIcon.addPixmap(style()->standardPixmap(QStyle::SP_FileIcon)); } +#if !defined(QT_NO_CONTEXTMENU) && !defined(QT_NO_CLIPBOARD) +void XbelTree::contextMenuEvent(QContextMenuEvent *event) +{ + const QTreeWidgetItem *item = itemAt(event->pos()); + if (!item) + return; + const QString url = item->text(1); + QMenu contextMenu; + QAction *copyAction = contextMenu.addAction(tr("Copy Link to Clipboard")); + QAction *openAction = contextMenu.addAction(tr("Open")); + QAction *action = contextMenu.exec(event->globalPos()); + if (action == copyAction) + QGuiApplication::clipboard()->setText(url); + else if (action == openAction) + QDesktopServices::openUrl(QUrl(url)); +} +#endif // !QT_NO_CONTEXTMENU && !QT_NO_CLIPBOARD + bool XbelTree::read(QIODevice *device) { QString errorStr; @@ -89,8 +119,8 @@ bool XbelTree::read(QIODevice *device) QMessageBox::information(window(), tr("DOM Bookmarks"), tr("The file is not an XBEL file.")); return false; - } else if (root.hasAttribute("version") - && root.attribute("version") != "1.0") { + } else if (root.hasAttribute(versionAttribute()) + && root.attribute(versionAttribute()) != QLatin1String("1.0")) { QMessageBox::information(window(), tr("DOM Bookmarks"), tr("The file is not an XBEL version 1.0 " "file.")); @@ -99,22 +129,20 @@ bool XbelTree::read(QIODevice *device) clear(); - disconnect(this, SIGNAL(itemChanged(QTreeWidgetItem*,int)), - this, SLOT(updateDomElement(QTreeWidgetItem*,int))); + disconnect(this, &QTreeWidget::itemChanged, this, &XbelTree::updateDomElement); - QDomElement child = root.firstChildElement("folder"); + QDomElement child = root.firstChildElement(folderElement()); while (!child.isNull()) { parseFolderElement(child); - child = child.nextSiblingElement("folder"); + child = child.nextSiblingElement(folderElement()); } - connect(this, SIGNAL(itemChanged(QTreeWidgetItem*,int)), - this, SLOT(updateDomElement(QTreeWidgetItem*,int))); + connect(this, &QTreeWidget::itemChanged, this, &XbelTree::updateDomElement); return true; } -bool XbelTree::write(QIODevice *device) +bool XbelTree::write(QIODevice *device) const { const int IndentSize = 4; @@ -123,21 +151,21 @@ bool XbelTree::write(QIODevice *device) return true; } -void XbelTree::updateDomElement(QTreeWidgetItem *item, int column) +void XbelTree::updateDomElement(const QTreeWidgetItem *item, int column) { - QDomElement element = domElementForItem.value(item); + QDomElement element = item->data(0, DomElementRole).value<QDomElement>(); if (!element.isNull()) { if (column == 0) { - QDomElement oldTitleElement = element.firstChildElement("title"); - QDomElement newTitleElement = domDocument.createElement("title"); + QDomElement oldTitleElement = element.firstChildElement(titleElement()); + QDomElement newTitleElement = domDocument.createElement(titleElement()); QDomText newTitleText = domDocument.createTextNode(item->text(0)); newTitleElement.appendChild(newTitleText); element.replaceChild(newTitleElement, oldTitleElement); } else { - if (element.tagName() == "bookmark") - element.setAttribute("href", item->text(1)); + if (element.tagName() == bookmarkElement()) + element.setAttribute(hrefAttribute(), item->text(1)); } } } @@ -147,7 +175,7 @@ void XbelTree::parseFolderElement(const QDomElement &element, { QTreeWidgetItem *item = createItem(element, parentItem); - QString title = element.firstChildElement("title").text(); + QString title = element.firstChildElement(titleElement()).text(); if (title.isEmpty()) title = QObject::tr("Folder"); @@ -155,25 +183,25 @@ void XbelTree::parseFolderElement(const QDomElement &element, item->setIcon(0, folderIcon); item->setText(0, title); - bool folded = (element.attribute("folded") != "no"); + bool folded = (element.attribute(foldedAttribute()) != QLatin1String("no")); setItemExpanded(item, !folded); QDomElement child = element.firstChildElement(); while (!child.isNull()) { - if (child.tagName() == "folder") { + if (child.tagName() == folderElement()) { parseFolderElement(child, item); - } else if (child.tagName() == "bookmark") { + } else if (child.tagName() == bookmarkElement()) { QTreeWidgetItem *childItem = createItem(child, item); - QString title = child.firstChildElement("title").text(); + QString title = child.firstChildElement(titleElement()).text(); if (title.isEmpty()) title = QObject::tr("Folder"); childItem->setFlags(item->flags() | Qt::ItemIsEditable); childItem->setIcon(0, bookmarkIcon); childItem->setText(0, title); - childItem->setText(1, child.attribute("href")); - } else if (child.tagName() == "separator") { + childItem->setText(1, child.attribute(hrefAttribute())); + } else if (child.tagName() == QLatin1String("separator")) { QTreeWidgetItem *childItem = createItem(child, item); childItem->setFlags(item->flags() & ~(Qt::ItemIsSelectable | Qt::ItemIsEditable)); childItem->setText(0, QString(30, 0xB7)); @@ -191,6 +219,6 @@ QTreeWidgetItem *XbelTree::createItem(const QDomElement &element, } else { item = new QTreeWidgetItem(this); } - domElementForItem.insert(item, element); + item->setData(0, DomElementRole, QVariant::fromValue(element)); return item; } diff --git a/examples/xml/dombookmarks/xbeltree.h b/examples/xml/dombookmarks/xbeltree.h index bf4b55ea74..f6c7ef8bfe 100644 --- a/examples/xml/dombookmarks/xbeltree.h +++ b/examples/xml/dombookmarks/xbeltree.h @@ -52,7 +52,6 @@ #define XBELTREE_H #include <QDomDocument> -#include <QHash> #include <QIcon> #include <QTreeWidget> @@ -64,10 +63,15 @@ public: XbelTree(QWidget *parent = 0); bool read(QIODevice *device); - bool write(QIODevice *device); + bool write(QIODevice *device) const; + +protected: +#if !defined(QT_NO_CONTEXTMENU) && !defined(QT_NO_CLIPBOARD) + void contextMenuEvent(QContextMenuEvent *event) Q_DECL_OVERRIDE; +#endif private slots: - void updateDomElement(QTreeWidgetItem *item, int column); + void updateDomElement(const QTreeWidgetItem *item, int column); private: void parseFolderElement(const QDomElement &element, @@ -76,7 +80,6 @@ private: QTreeWidgetItem *parentItem = 0); QDomDocument domDocument; - QHash<QTreeWidgetItem *, QDomElement> domElementForItem; QIcon folderIcon; QIcon bookmarkIcon; }; diff --git a/examples/xml/saxbookmarks/mainwindow.cpp b/examples/xml/saxbookmarks/mainwindow.cpp index 2ce2b9a508..0583cd82cf 100644 --- a/examples/xml/saxbookmarks/mainwindow.cpp +++ b/examples/xml/saxbookmarks/mainwindow.cpp @@ -62,17 +62,40 @@ MainWindow::MainWindow() treeWidget = new QTreeWidget; treeWidget->header()->setSectionResizeMode(QHeaderView::Stretch); treeWidget->setHeaderLabels(labels); +#if !defined(QT_NO_CONTEXTMENU) && !defined(QT_NO_CLIPBOARD) + treeWidget->setContextMenuPolicy(Qt::CustomContextMenu); + connect(treeWidget, &QWidget::customContextMenuRequested, + this, &MainWindow::onCustomContextMenuRequested); +#endif setCentralWidget(treeWidget); - createActions(); createMenus(); statusBar()->showMessage(tr("Ready")); setWindowTitle(tr("SAX Bookmarks")); - resize(480, 320); + const QSize availableSize = QApplication::desktop()->availableGeometry(this).size(); + resize(availableSize.width() / 2, availableSize.height() / 3); } +#if !defined(QT_NO_CONTEXTMENU) && !defined(QT_NO_CLIPBOARD) +void MainWindow::onCustomContextMenuRequested(const QPoint &pos) +{ + const QTreeWidgetItem *item = treeWidget->itemAt(pos); + if (!item) + return; + const QString url = item->text(1); + QMenu contextMenu; + QAction *copyAction = contextMenu.addAction(tr("Copy Link to Clipboard")); + QAction *openAction = contextMenu.addAction(tr("Open")); + QAction *action = contextMenu.exec(treeWidget->viewport()->mapToGlobal(pos)); + if (action == copyAction) + QGuiApplication::clipboard()->setText(url); + else if (action == openAction) + QDesktopServices::openUrl(QUrl(url)); +} +#endif // !QT_NO_CONTEXTMENU && !QT_NO_CLIPBOARD + void MainWindow::open() { QString fileName = @@ -93,8 +116,8 @@ void MainWindow::open() if (!file.open(QFile::ReadOnly | QFile::Text)) { QMessageBox::warning(this, tr("SAX Bookmarks"), tr("Cannot read file %1:\n%2.") - .arg(fileName) - .arg(file.errorString())); + .arg(QDir::toNativeSeparators(fileName), + file.errorString())); return; } @@ -116,8 +139,8 @@ void MainWindow::saveAs() if (!file.open(QFile::WriteOnly | QFile::Text)) { QMessageBox::warning(this, tr("SAX Bookmarks"), tr("Cannot write file %1:\n%2.") - .arg(fileName) - .arg(file.errorString())); + .arg(QDir::toNativeSeparators(fileName), + file.errorString())); return; } @@ -134,37 +157,21 @@ void MainWindow::about() "hand.")); } -void MainWindow::createActions() +void MainWindow::createMenus() { - openAct = new QAction(tr("&Open..."), this); + QMenu *fileMenu = menuBar()->addMenu(tr("&File")); + QAction *openAct = fileMenu->addAction(tr("&Open..."), this, &MainWindow::open); openAct->setShortcuts(QKeySequence::Open); - connect(openAct, SIGNAL(triggered()), this, SLOT(open())); - saveAsAct = new QAction(tr("&Save As..."), this); + QAction *saveAsAct = fileMenu->addAction(tr("&Save As..."), this, &MainWindow::saveAs); saveAsAct->setShortcuts(QKeySequence::SaveAs); - connect(saveAsAct, SIGNAL(triggered()), this, SLOT(saveAs())); - exitAct = new QAction(tr("E&xit"), this); + QAction *exitAct = fileMenu->addAction(tr("E&xit"), this, &QWidget::close); exitAct->setShortcuts(QKeySequence::Quit); - connect(exitAct, SIGNAL(triggered()), this, SLOT(close())); - - aboutAct = new QAction(tr("&About"), this); - connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); - - aboutQtAct = new QAction(tr("About &Qt"), this); - connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt())); -} - -void MainWindow::createMenus() -{ - fileMenu = menuBar()->addMenu(tr("&File")); - fileMenu->addAction(openAct); - fileMenu->addAction(saveAsAct); - fileMenu->addAction(exitAct); menuBar()->addSeparator(); - helpMenu = menuBar()->addMenu(tr("&Help")); - helpMenu->addAction(aboutAct); - helpMenu->addAction(aboutQtAct); + QMenu *helpMenu = menuBar()->addMenu(tr("&Help")); + helpMenu->addAction(tr("&About"), this, &MainWindow::about); + helpMenu->addAction(tr("About &Qt"), qApp, &QCoreApplication::quit); } diff --git a/examples/xml/saxbookmarks/mainwindow.h b/examples/xml/saxbookmarks/mainwindow.h index 828a0ed14e..20a11bb202 100644 --- a/examples/xml/saxbookmarks/mainwindow.h +++ b/examples/xml/saxbookmarks/mainwindow.h @@ -68,20 +68,13 @@ public slots: void open(); void saveAs(); void about(); - +#if !defined(QT_NO_CONTEXTMENU) && !defined(QT_NO_CLIPBOARD) + void onCustomContextMenuRequested(const QPoint &pos); +#endif private: - void createActions(); void createMenus(); QTreeWidget *treeWidget; - - QMenu *fileMenu; - QMenu *helpMenu; - QAction *openAct; - QAction *saveAsAct; - QAction *exitAct; - QAction *aboutAct; - QAction *aboutQtAct; }; #endif diff --git a/examples/xml/saxbookmarks/xbelgenerator.cpp b/examples/xml/saxbookmarks/xbelgenerator.cpp index 30ce1428e6..ee6f113f9c 100644 --- a/examples/xml/saxbookmarks/xbelgenerator.cpp +++ b/examples/xml/saxbookmarks/xbelgenerator.cpp @@ -52,7 +52,7 @@ #include "xbelgenerator.h" -XbelGenerator::XbelGenerator(QTreeWidget *treeWidget) +XbelGenerator::XbelGenerator(const QTreeWidget *treeWidget) : treeWidget(treeWidget) { } @@ -81,25 +81,25 @@ QString XbelGenerator::indent(int depth) QString XbelGenerator::escapedText(const QString &str) { QString result = str; - result.replace("&", "&"); - result.replace("<", "<"); - result.replace(">", ">"); + result.replace('&', "&"); + result.replace('<', "<"); + result.replace('>', ">"); return result; } QString XbelGenerator::escapedAttribute(const QString &str) { QString result = escapedText(str); - result.replace("\"", """); + result.replace(QLatin1Char('"'), """); result.prepend(QLatin1Char('"')); result.append(QLatin1Char('"')); return result; } -void XbelGenerator::generateItem(QTreeWidgetItem *item, int depth) +void XbelGenerator::generateItem(const QTreeWidgetItem *item, int depth) { QString tagName = item->data(0, Qt::UserRole).toString(); - if (tagName == "folder") { + if (tagName == QLatin1String("folder")) { bool folded = !treeWidget->isItemExpanded(item); out << indent(depth) << "<folder folded=\"" << (folded ? "yes" : "no") << "\">\n" @@ -110,7 +110,7 @@ void XbelGenerator::generateItem(QTreeWidgetItem *item, int depth) generateItem(item->child(i), depth + 1); out << indent(depth) << "</folder>\n"; - } else if (tagName == "bookmark") { + } else if (tagName == QLatin1String("bookmark")) { out << indent(depth) << "<bookmark"; if (!item->text(1).isEmpty()) out << " href=" << escapedAttribute(item->text(1)); @@ -118,7 +118,7 @@ void XbelGenerator::generateItem(QTreeWidgetItem *item, int depth) << indent(depth + 1) << "<title>" << escapedText(item->text(0)) << "</title>\n" << indent(depth) << "</bookmark>\n"; - } else if (tagName == "separator") { + } else if (tagName == QLatin1String("separator")) { out << indent(depth) << "<separator/>\n"; } } diff --git a/examples/xml/saxbookmarks/xbelgenerator.h b/examples/xml/saxbookmarks/xbelgenerator.h index 44069599e2..abfabfd75c 100644 --- a/examples/xml/saxbookmarks/xbelgenerator.h +++ b/examples/xml/saxbookmarks/xbelgenerator.h @@ -61,7 +61,7 @@ QT_END_NAMESPACE class XbelGenerator { public: - XbelGenerator(QTreeWidget *treeWidget); + explicit XbelGenerator(const QTreeWidget *treeWidget); bool write(QIODevice *device); @@ -69,9 +69,9 @@ private: static QString indent(int indentLevel); static QString escapedText(const QString &str); static QString escapedAttribute(const QString &str); - void generateItem(QTreeWidgetItem *item, int depth); + void generateItem(const QTreeWidgetItem *item, int depth); - QTreeWidget *treeWidget; + const QTreeWidget *treeWidget; QTextStream out; }; diff --git a/examples/xml/saxbookmarks/xbelhandler.cpp b/examples/xml/saxbookmarks/xbelhandler.cpp index 03b16c81f1..7e2a9db3c2 100644 --- a/examples/xml/saxbookmarks/xbelhandler.cpp +++ b/examples/xml/saxbookmarks/xbelhandler.cpp @@ -52,6 +52,10 @@ #include "xbelhandler.h" +static inline QString versionAttribute() { return QStringLiteral("version"); } +static inline QString hrefAttribute() { return QStringLiteral("href"); } +static inline QString foldedAttribute() { return QStringLiteral("folded"); } + XbelHandler::XbelHandler(QTreeWidget *treeWidget) : treeWidget(treeWidget) { @@ -72,32 +76,32 @@ bool XbelHandler::startElement(const QString & /* namespaceURI */, const QString &qName, const QXmlAttributes &attributes) { - if (!metXbelTag && qName != "xbel") { + if (!metXbelTag && qName != QLatin1String("xbel")) { errorStr = QObject::tr("The file is not an XBEL file."); return false; } - if (qName == "xbel") { - QString version = attributes.value("version"); - if (!version.isEmpty() && version != "1.0") { + if (qName == QLatin1String("xbel")) { + QString version = attributes.value(versionAttribute()); + if (!version.isEmpty() && version != QLatin1String("1.0")) { errorStr = QObject::tr("The file is not an XBEL version 1.0 file."); return false; } metXbelTag = true; - } else if (qName == "folder") { + } else if (qName == QLatin1String("folder")) { item = createChildItem(qName); item->setFlags(item->flags() | Qt::ItemIsEditable); item->setIcon(0, folderIcon); item->setText(0, QObject::tr("Folder")); - bool folded = (attributes.value("folded") != "no"); + bool folded = (attributes.value(foldedAttribute()) != QLatin1String("no")); treeWidget->setItemExpanded(item, !folded); - } else if (qName == "bookmark") { + } else if (qName == QLatin1String("bookmark")) { item = createChildItem(qName); item->setFlags(item->flags() | Qt::ItemIsEditable); item->setIcon(0, bookmarkIcon); item->setText(0, QObject::tr("Unknown title")); - item->setText(1, attributes.value("href")); - } else if (qName == "separator") { + item->setText(1, attributes.value(hrefAttribute())); + } else if (qName == QLatin1String("separator")) { item = createChildItem(qName); item->setFlags(item->flags() & ~Qt::ItemIsSelectable); item->setText(0, QString(30, 0xB7)); @@ -111,11 +115,11 @@ bool XbelHandler::endElement(const QString & /* namespaceURI */, const QString & /* localName */, const QString &qName) { - if (qName == "title") { + if (qName == QLatin1String("title")) { if (item) item->setText(0, currentText); - } else if (qName == "folder" || qName == "bookmark" - || qName == "separator") { + } else if (qName == QLatin1String("folder") || qName == QLatin1String("bookmark") + || qName == QLatin1String("separator")) { item = item->parent(); } return true; diff --git a/examples/xml/streambookmarks/doc/src/qxmlstreambookmarks.qdoc b/examples/xml/streambookmarks/doc/src/qxmlstreambookmarks.qdoc index 0720e3eadd..ad093c2098 100644 --- a/examples/xml/streambookmarks/doc/src/qxmlstreambookmarks.qdoc +++ b/examples/xml/streambookmarks/doc/src/qxmlstreambookmarks.qdoc @@ -167,7 +167,7 @@ add them to the \c fileMenu and \c helpMenu. The connections are as shown below: - \snippet streambookmarks/mainwindow.cpp 4 + \snippet streambookmarks/mainwindow.cpp 5 The \c createMenus() function creates the \c fileMenu and \c helpMenu and adds the QAction objects to them in order to create the menu shown diff --git a/examples/xml/streambookmarks/mainwindow.cpp b/examples/xml/streambookmarks/mainwindow.cpp index 7c0fd8720d..c9a18fa3c4 100644 --- a/examples/xml/streambookmarks/mainwindow.cpp +++ b/examples/xml/streambookmarks/mainwindow.cpp @@ -63,18 +63,41 @@ MainWindow::MainWindow() treeWidget = new QTreeWidget; treeWidget->header()->setSectionResizeMode(QHeaderView::Stretch); treeWidget->setHeaderLabels(labels); +#if !defined(QT_NO_CONTEXTMENU) && !defined(QT_NO_CLIPBOARD) + treeWidget->setContextMenuPolicy(Qt::CustomContextMenu); + connect(treeWidget, &QWidget::customContextMenuRequested, + this, &MainWindow::onCustomContextMenuRequested); +#endif setCentralWidget(treeWidget); - createActions(); createMenus(); statusBar()->showMessage(tr("Ready")); setWindowTitle(tr("QXmlStream Bookmarks")); - resize(480, 320); + const QSize availableSize = QApplication::desktop()->availableGeometry(this).size(); + resize(availableSize.width() / 2, availableSize.height() / 3); } //! [0] +#if !defined(QT_NO_CONTEXTMENU) && !defined(QT_NO_CLIPBOARD) +void MainWindow::onCustomContextMenuRequested(const QPoint &pos) +{ + const QTreeWidgetItem *item = treeWidget->itemAt(pos); + if (!item) + return; + const QString url = item->text(1); + QMenu contextMenu; + QAction *copyAction = contextMenu.addAction(tr("Copy Link to Clipboard")); + QAction *openAction = contextMenu.addAction(tr("Open")); + QAction *action = contextMenu.exec(treeWidget->viewport()->mapToGlobal(pos)); + if (action == copyAction) + QGuiApplication::clipboard()->setText(url); + else if (action == openAction) + QDesktopServices::openUrl(QUrl(url)); +} +#endif // !QT_NO_CONTEXTMENU && !QT_NO_CLIPBOARD + //! [1] void MainWindow::open() { @@ -92,8 +115,8 @@ void MainWindow::open() if (!file.open(QFile::ReadOnly | QFile::Text)) { QMessageBox::warning(this, tr("QXmlStream Bookmarks"), tr("Cannot read file %1:\n%2.") - .arg(fileName) - .arg(file.errorString())); + .arg(QDir::toNativeSeparators(fileName), + file.errorString())); return; } @@ -101,8 +124,8 @@ void MainWindow::open() if (!reader.read(&file)) { QMessageBox::warning(this, tr("QXmlStream Bookmarks"), tr("Parse error in file %1:\n\n%2") - .arg(fileName) - .arg(reader.errorString())); + .arg(QDir::toNativeSeparators(fileName), + reader.errorString())); } else { statusBar()->showMessage(tr("File loaded"), 2000); } @@ -124,8 +147,8 @@ void MainWindow::saveAs() if (!file.open(QFile::WriteOnly | QFile::Text)) { QMessageBox::warning(this, tr("QXmlStream Bookmarks"), tr("Cannot write file %1:\n%2.") - .arg(fileName) - .arg(file.errorString())); + .arg(QDir::toNativeSeparators(fileName), + file.errorString())); return; } @@ -144,41 +167,23 @@ void MainWindow::about() } //! [3] -//! [4] -void MainWindow::createActions() +//! [5] +void MainWindow::createMenus() { - openAct = new QAction(tr("&Open..."), this); + QMenu *fileMenu = menuBar()->addMenu(tr("&File")); + QAction *openAct = fileMenu->addAction(tr("&Open..."), this, &MainWindow::open); openAct->setShortcuts(QKeySequence::Open); - connect(openAct, SIGNAL(triggered()), this, SLOT(open())); - saveAsAct = new QAction(tr("&Save As..."), this); + QAction *saveAsAct = fileMenu->addAction(tr("&Save As..."), this, &MainWindow::saveAs); saveAsAct->setShortcuts(QKeySequence::SaveAs); - connect(saveAsAct, SIGNAL(triggered()), this, SLOT(saveAs())); - exitAct = new QAction(tr("E&xit"), this); + QAction *exitAct = fileMenu->addAction(tr("E&xit"), this, &QWidget::close); exitAct->setShortcuts(QKeySequence::Quit); - connect(exitAct, SIGNAL(triggered()), this, SLOT(close())); - - aboutAct = new QAction(tr("&About"), this); - connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); - - aboutQtAct = new QAction(tr("About &Qt"), this); - connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt())); -} -//! [4] - -//! [5] -void MainWindow::createMenus() -{ - fileMenu = menuBar()->addMenu(tr("&File")); - fileMenu->addAction(openAct); - fileMenu->addAction(saveAsAct); - fileMenu->addAction(exitAct); menuBar()->addSeparator(); - helpMenu = menuBar()->addMenu(tr("&Help")); - helpMenu->addAction(aboutAct); - helpMenu->addAction(aboutQtAct); + QMenu *helpMenu = menuBar()->addMenu(tr("&Help")); + helpMenu->addAction(tr("&About"), this, &MainWindow::about); + helpMenu->addAction(tr("About &Qt"), qApp, &QCoreApplication::quit); } //! [5] diff --git a/examples/xml/streambookmarks/mainwindow.h b/examples/xml/streambookmarks/mainwindow.h index 2b6feeb26f..fbdc1e0c62 100644 --- a/examples/xml/streambookmarks/mainwindow.h +++ b/examples/xml/streambookmarks/mainwindow.h @@ -69,20 +69,13 @@ public slots: void open(); void saveAs(); void about(); - +#if !defined(QT_NO_CONTEXTMENU) && !defined(QT_NO_CLIPBOARD) + void onCustomContextMenuRequested(const QPoint &pos); +#endif private: - void createActions(); void createMenus(); QTreeWidget *treeWidget; - - QMenu *fileMenu; - QMenu *helpMenu; - QAction *openAct; - QAction *saveAsAct; - QAction *exitAct; - QAction *aboutAct; - QAction *aboutQtAct; }; //! [0] diff --git a/examples/xml/streambookmarks/xbelreader.cpp b/examples/xml/streambookmarks/xbelreader.cpp index 53d6b94ba0..099985d91e 100644 --- a/examples/xml/streambookmarks/xbelreader.cpp +++ b/examples/xml/streambookmarks/xbelreader.cpp @@ -72,10 +72,12 @@ bool XbelReader::read(QIODevice *device) xml.setDevice(device); if (xml.readNextStartElement()) { - if (xml.name() == "xbel" && xml.attributes().value("version") == "1.0") + if (xml.name() == QLatin1String("xbel") + && xml.attributes().value(versionAttribute()) == QLatin1String("1.0")) { readXBEL(); - else + } else { xml.raiseError(QObject::tr("The file is not an XBEL version 1.0 file.")); + } } return !xml.error(); @@ -95,14 +97,14 @@ QString XbelReader::errorString() const //! [3] void XbelReader::readXBEL() { - Q_ASSERT(xml.isStartElement() && xml.name() == "xbel"); + Q_ASSERT(xml.isStartElement() && xml.name() == QLatin1String("xbel")); while (xml.readNextStartElement()) { - if (xml.name() == "folder") + if (xml.name() == QLatin1String("folder")) readFolder(0); - else if (xml.name() == "bookmark") + else if (xml.name() == QLatin1String("bookmark")) readBookmark(0); - else if (xml.name() == "separator") + else if (xml.name() == QLatin1String("separator")) readSeparator(0); else xml.skipCurrentElement(); @@ -113,7 +115,7 @@ void XbelReader::readXBEL() //! [4] void XbelReader::readTitle(QTreeWidgetItem *item) { - Q_ASSERT(xml.isStartElement() && xml.name() == "title"); + Q_ASSERT(xml.isStartElement() && xml.name() == QLatin1String("title")); QString title = xml.readElementText(); item->setText(0, title); @@ -123,7 +125,7 @@ void XbelReader::readTitle(QTreeWidgetItem *item) //! [5] void XbelReader::readSeparator(QTreeWidgetItem *item) { - Q_ASSERT(xml.isStartElement() && xml.name() == "separator"); + Q_ASSERT(xml.isStartElement() && xml.name() == QLatin1String("separator")); QTreeWidgetItem *separator = createChildItem(item); separator->setFlags(item->flags() & ~Qt::ItemIsSelectable); @@ -134,20 +136,20 @@ void XbelReader::readSeparator(QTreeWidgetItem *item) void XbelReader::readFolder(QTreeWidgetItem *item) { - Q_ASSERT(xml.isStartElement() && xml.name() == "folder"); + Q_ASSERT(xml.isStartElement() && xml.name() == QLatin1String("folder")); QTreeWidgetItem *folder = createChildItem(item); - bool folded = (xml.attributes().value("folded") != "no"); + bool folded = (xml.attributes().value(foldedAttribute()) != QLatin1String("no")); treeWidget->setItemExpanded(folder, !folded); while (xml.readNextStartElement()) { - if (xml.name() == "title") + if (xml.name() == QLatin1String("title")) readTitle(folder); - else if (xml.name() == "folder") + else if (xml.name() == QLatin1String("folder")) readFolder(folder); - else if (xml.name() == "bookmark") + else if (xml.name() == QLatin1String("bookmark")) readBookmark(folder); - else if (xml.name() == "separator") + else if (xml.name() == QLatin1String("separator")) readSeparator(folder); else xml.skipCurrentElement(); @@ -156,16 +158,16 @@ void XbelReader::readFolder(QTreeWidgetItem *item) void XbelReader::readBookmark(QTreeWidgetItem *item) { - Q_ASSERT(xml.isStartElement() && xml.name() == "bookmark"); + Q_ASSERT(xml.isStartElement() && xml.name() == QLatin1String("bookmark")); QTreeWidgetItem *bookmark = createChildItem(item); bookmark->setFlags(bookmark->flags() | Qt::ItemIsEditable); bookmark->setIcon(0, bookmarkIcon); bookmark->setText(0, QObject::tr("Unknown title")); - bookmark->setText(1, xml.attributes().value("href").toString()); + bookmark->setText(1, xml.attributes().value(hrefAttribute()).toString()); while (xml.readNextStartElement()) { - if (xml.name() == "title") + if (xml.name() == QLatin1String("title")) readTitle(bookmark); else xml.skipCurrentElement(); diff --git a/examples/xml/streambookmarks/xbelreader.h b/examples/xml/streambookmarks/xbelreader.h index 3175441ddd..fd486a430f 100644 --- a/examples/xml/streambookmarks/xbelreader.h +++ b/examples/xml/streambookmarks/xbelreader.h @@ -71,6 +71,10 @@ public: QString errorString() const; + static inline QString versionAttribute() { return QStringLiteral("version"); } + static inline QString hrefAttribute() { return QStringLiteral("href"); } + static inline QString foldedAttribute() { return QStringLiteral("folded"); } + private: //! [2] void readXBEL(); diff --git a/examples/xml/streambookmarks/xbelwriter.cpp b/examples/xml/streambookmarks/xbelwriter.cpp index fdf2e1095e..2959680678 100644 --- a/examples/xml/streambookmarks/xbelwriter.cpp +++ b/examples/xml/streambookmarks/xbelwriter.cpp @@ -51,9 +51,14 @@ #include <QtWidgets> #include "xbelwriter.h" +#include "xbelreader.h" + +static inline QString yesValue() { return QStringLiteral("yes"); } +static inline QString noValue() { return QStringLiteral("no"); } +static inline QString titleElement() { return QStringLiteral("title"); } //! [0] -XbelWriter::XbelWriter(QTreeWidget *treeWidget) +XbelWriter::XbelWriter(const QTreeWidget *treeWidget) : treeWidget(treeWidget) { xml.setAutoFormatting(true); @@ -66,9 +71,9 @@ bool XbelWriter::writeFile(QIODevice *device) xml.setDevice(device); xml.writeStartDocument(); - xml.writeDTD("<!DOCTYPE xbel>"); - xml.writeStartElement("xbel"); - xml.writeAttribute("version", "1.0"); + xml.writeDTD(QStringLiteral("<!DOCTYPE xbel>")); + xml.writeStartElement(QStringLiteral("xbel")); + xml.writeAttribute(XbelReader::versionAttribute(), QStringLiteral("1.0")); for (int i = 0; i < treeWidget->topLevelItemCount(); ++i) writeItem(treeWidget->topLevelItem(i)); @@ -78,24 +83,24 @@ bool XbelWriter::writeFile(QIODevice *device) //! [1] //! [2] -void XbelWriter::writeItem(QTreeWidgetItem *item) +void XbelWriter::writeItem(const QTreeWidgetItem *item) { QString tagName = item->data(0, Qt::UserRole).toString(); - if (tagName == "folder") { + if (tagName == QLatin1String("folder")) { bool folded = !treeWidget->isItemExpanded(item); xml.writeStartElement(tagName); - xml.writeAttribute("folded", folded ? "yes" : "no"); - xml.writeTextElement("title", item->text(0)); + xml.writeAttribute(XbelReader::foldedAttribute(), folded ? yesValue() : noValue()); + xml.writeTextElement(titleElement(), item->text(0)); for (int i = 0; i < item->childCount(); ++i) writeItem(item->child(i)); xml.writeEndElement(); - } else if (tagName == "bookmark") { + } else if (tagName == QLatin1String("bookmark")) { xml.writeStartElement(tagName); if (!item->text(1).isEmpty()) - xml.writeAttribute("href", item->text(1)); - xml.writeTextElement("title", item->text(0)); + xml.writeAttribute(XbelReader::hrefAttribute(), item->text(1)); + xml.writeTextElement(titleElement(), item->text(0)); xml.writeEndElement(); - } else if (tagName == "separator") { + } else if (tagName == QLatin1String("separator")) { xml.writeEmptyElement(tagName); } } diff --git a/examples/xml/streambookmarks/xbelwriter.h b/examples/xml/streambookmarks/xbelwriter.h index b15bf60e31..465d8f0dc4 100644 --- a/examples/xml/streambookmarks/xbelwriter.h +++ b/examples/xml/streambookmarks/xbelwriter.h @@ -62,13 +62,13 @@ QT_END_NAMESPACE class XbelWriter { public: - XbelWriter(QTreeWidget *treeWidget); + explicit XbelWriter(const QTreeWidget *treeWidget); bool writeFile(QIODevice *device); private: - void writeItem(QTreeWidgetItem *item); + void writeItem(const QTreeWidgetItem *item); QXmlStreamWriter xml; - QTreeWidget *treeWidget; + const QTreeWidget *treeWidget; }; //! [0] |