Debian Codegraph @

tests/manual/rhi/offscreen/offscreen.cpp

raw
1 /****************************************************************************
2 **
3 ** Copyright (C) 2018 The Qt Company Ltd.
4 ** Contact: https://www.qt.io/licensing/
5 **
6 ** This file is part of the examples of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:BSD$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and The Qt Company. For licensing terms
14 ** and conditions see https://www.qt.io/terms-conditions. For further
15 ** information use the contact form at https://www.qt.io/contact-us.
16 **
17 ** BSD License Usage
18 ** Alternatively, you may use this file under the terms of the BSD license
19 ** as follows:
20 **
21 ** "Redistribution and use in source and binary forms, with or without
22 ** modification, are permitted provided that the following conditions are
23 ** met:
24 ** * Redistributions of source code must retain the above copyright
25 ** notice, this list of conditions and the following disclaimer.
26 ** * Redistributions in binary form must reproduce the above copyright
27 ** notice, this list of conditions and the following disclaimer in
28 ** the documentation and/or other materials provided with the
29 ** distribution.
30 ** * Neither the name of The Qt Company Ltd nor the names of its
31 ** contributors may be used to endorse or promote products derived
32 ** from this software without specific prior written permission.
33 **
34 **
35 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
36 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
38 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
39 ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42 ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
43 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
45 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
46 **
47 ** $QT_END_LICENSE$
48 **
49 ****************************************************************************/
50
51 #include <QGuiApplication>
52 #include <QImage>
53 #include <QFileInfo>
54 #include <QFile>
55 #include <QLoggingCategory>
56 #include <QCommandLineParser>
57 #include <QtGui/private/qshader_p.h>
58
59 #include <QtGui/private/qrhinull_p.h>
60
61 #ifndef QT_NO_OPENGL
62 #include <QtGui/private/qrhigles2_p.h>
63 #include <QOffscreenSurface>
64 #endif
65
66 #if QT_CONFIG(vulkan)
67 #include <QLoggingCategory>
68 #include <QtGui/private/qrhivulkan_p.h>
69 #endif
70
71 #ifdef Q_OS_WIN
72 #include <QtGui/private/qrhid3d11_p.h>
73 #endif
74
75 #if defined(Q_OS_MACOS) || defined(Q_OS_IOS)
76 #include <QtGui/private/qrhimetal_p.h>
77 #endif
78
79 //#define TEST_FINISH
80
81 static float vertexData[] = { // Y up (note m_proj), CCW
82 0.0f, 0.5f, 1.0f, 0.0f, 0.0f,
83 -0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
84 0.5f, -0.5f, 0.0f, 0.0f, 1.0f,
85 };
86
87 static QShader getShader(const QString &name)
88 {
89 QFile f(name);
90 if (f.open(QIODevice::ReadOnly))
91 return QShader::fromSerialized(f.readAll());
92
93 return QShader();
94 }
95
96 enum GraphicsApi
97 {
98 OpenGL,
99 Vulkan,
100 D3D11,
101 Metal,
102 Null
103 };
104
105 GraphicsApi graphicsApi;
106
107 QString graphicsApiName()
108 {
109 switch (graphicsApi) {
110 case OpenGL:
111 return QLatin1String("OpenGL 2.x");
112 case Vulkan:
113 return QLatin1String("Vulkan");
114 case D3D11:
115 return QLatin1String("Direct3D 11");
116 case Metal:
117 return QLatin1String("Metal");
118 case Null:
119 return QLatin1String("Null");
120 default:
121 break;
122 }
123 return QString();
124 }
125
126 int main(int argc, char **argv)
127 {
128 QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
129 QGuiApplication app(argc, argv);
130
131 #if defined(Q_OS_WIN)
132 graphicsApi = D3D11;
133 #elif defined(Q_OS_MACOS) || defined(Q_OS_IOS)
134 graphicsApi = Metal;
135 #elif QT_CONFIG(vulkan)
136 graphicsApi = Vulkan;
137 #else
138 graphicsApi = OpenGL;
139 #endif
140
141 QCommandLineParser cmdLineParser;
142 cmdLineParser.addHelpOption();
143 QCommandLineOption glOption({ "g", "opengl" }, QLatin1String("OpenGL (2.x)"));
144 cmdLineParser.addOption(glOption);
145 QCommandLineOption vkOption({ "v", "vulkan" }, QLatin1String("Vulkan"));
146 cmdLineParser.addOption(vkOption);
147 QCommandLineOption d3dOption({ "d", "d3d11" }, QLatin1String("Direct3D 11"));
148 cmdLineParser.addOption(d3dOption);
149 QCommandLineOption mtlOption({ "m", "metal" }, QLatin1String("Metal"));
150 cmdLineParser.addOption(mtlOption);
151 QCommandLineOption nullOption({ "n", "null" }, QLatin1String("Null"));
152 cmdLineParser.addOption(nullOption);
153 cmdLineParser.process(app);
154 if (cmdLineParser.isSet(glOption))
155 graphicsApi = OpenGL;
156 if (cmdLineParser.isSet(vkOption))
157 graphicsApi = Vulkan;
158 if (cmdLineParser.isSet(d3dOption))
159 graphicsApi = D3D11;
160 if (cmdLineParser.isSet(mtlOption))
161 graphicsApi = Metal;
162 if (cmdLineParser.isSet(nullOption))
163 graphicsApi = Null;
164
165 qDebug("Selected graphics API is %s", qPrintable(graphicsApiName()));
166 qDebug("This is a multi-api example, use command line arguments to override:\n%s", qPrintable(cmdLineParser.helpText()));
167
168 QRhi *r = nullptr;
169
170 if (graphicsApi == Null) {
171 QRhiNullInitParams params;
172 r = QRhi::create(QRhi::Null, &params);
173 }
174
175 #if QT_CONFIG(vulkan)
176 QVulkanInstance inst;
177 if (graphicsApi == Vulkan) {
178 QLoggingCategory::setFilterRules(QStringLiteral("qt.vulkan=true"));
179 #ifndef Q_OS_ANDROID
180 inst.setLayers(QByteArrayList() << "VK_LAYER_LUNARG_standard_validation");
181 #else
182 inst.setLayers(QByteArrayList()
183 << "VK_LAYER_GOOGLE_threading"
184 << "VK_LAYER_LUNARG_parameter_validation"
185 << "VK_LAYER_LUNARG_object_tracker"
186 << "VK_LAYER_LUNARG_core_validation"
187 << "VK_LAYER_LUNARG_image"
188 << "VK_LAYER_LUNARG_swapchain"
189 << "VK_LAYER_GOOGLE_unique_objects");
190 #endif
191 if (inst.create()) {
192 QRhiVulkanInitParams params;
193 params.inst = &inst;
194 r = QRhi::create(QRhi::Vulkan, &params);
195 } else {
196 qWarning("Failed to create Vulkan instance, switching to OpenGL");
197 graphicsApi = OpenGL;
198 }
199 }
200 #endif
201
202 #ifndef QT_NO_OPENGL
203 QScopedPointer<QOffscreenSurface> offscreenSurface;
204 if (graphicsApi == OpenGL) {
205 offscreenSurface.reset(QRhiGles2InitParams::newFallbackSurface());
206 QRhiGles2InitParams params;
207 params.fallbackSurface = offscreenSurface.data();
208 r = QRhi::create(QRhi::OpenGLES2, &params);
209 }
210 #endif
211
212 #ifdef Q_OS_WIN
213 if (graphicsApi == D3D11) {
214 QRhiD3D11InitParams params;
215 params.enableDebugLayer = true;
216 r = QRhi::create(QRhi::D3D11, &params);
217 }
218 #endif
219
220 #if defined(Q_OS_MACOS) || defined(Q_OS_IOS)
221 if (graphicsApi == Metal) {
222 QRhiMetalInitParams params;
223 r = QRhi::create(QRhi::Metal, &params);
224 }
225 #endif
226
227 if (!r)
228 qFatal("Failed to initialize RHI");
229
230 QRhiTexture *tex = r->newTexture(QRhiTexture::RGBA8, QSize(1280, 720), 1, QRhiTexture::RenderTarget | QRhiTexture::UsedAsTransferSource);
231 tex->build();
232 QRhiTextureRenderTarget *rt = r->newTextureRenderTarget({ tex });
233 QRhiRenderPassDescriptor *rp = rt->newCompatibleRenderPassDescriptor();
234 rt->setRenderPassDescriptor(rp);
235 rt->build();
236
237 QMatrix4x4 proj = r->clipSpaceCorrMatrix();
238 proj.perspective(45.0f, 1280 / 720.f, 0.01f, 1000.0f);
239 proj.translate(0, 0, -4);
240
241 QRhiBuffer *vbuf = r->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer, sizeof(vertexData));
242 vbuf->build();
243
244 QRhiBuffer *ubuf = r->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, 68);
245 ubuf->build();
246
247 QRhiShaderResourceBindings *srb = r->newShaderResourceBindings();
248 srb->setBindings({
249 QRhiShaderResourceBinding::uniformBuffer(0, QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage, ubuf)
250 });
251 srb->build();
252
253 QRhiGraphicsPipeline *ps = r->newGraphicsPipeline();
254
255 QRhiGraphicsPipeline::TargetBlend premulAlphaBlend;
256 premulAlphaBlend.enable = true;
257 ps->setTargetBlends({ premulAlphaBlend });
258
259 const QShader vs = getShader(QLatin1String(":/color.vert.qsb"));
260 if (!vs.isValid())
261 qFatal("Failed to load shader pack (vertex)");
262 const QShader fs = getShader(QLatin1String(":/color.frag.qsb"));
263 if (!fs.isValid())
264 qFatal("Failed to load shader pack (fragment)");
265
266 ps->setShaderStages({
267 { QRhiShaderStage::Vertex, vs },
268 { QRhiShaderStage::Fragment, fs }
269 });
270
271 QRhiVertexInputLayout inputLayout;
272 inputLayout.setBindings({
273 { 5 * sizeof(float) }
274 });
275 inputLayout.setAttributes({
276 { 0, 0, QRhiVertexInputAttribute::Float2, 0 },
277 { 0, 1, QRhiVertexInputAttribute::Float3, 2 * sizeof(float) }
278 });
279
280 ps->setVertexInputLayout(inputLayout);
281 ps->setShaderResourceBindings(srb);
282 ps->setRenderPassDescriptor(rp);
283 ps->build();
284
285 int frame = 0;
286 for (; frame < 20; ++frame) {
287 QRhiCommandBuffer *cb;
288 if (r->beginOffscreenFrame(&cb) != QRhi::FrameOpSuccess)
289 break;
290
291 qDebug("Generating offscreen frame %d", frame);
292 QRhiResourceUpdateBatch *u = r->nextResourceUpdateBatch();
293 if (frame == 0)
294 u->uploadStaticBuffer(vbuf, vertexData);
295
296 static float rotation = 0.0f;
297 QMatrix4x4 mvp = proj;
298 mvp.rotate(rotation, 0, 1, 0);
299 u->updateDynamicBuffer(ubuf, 0, 64, mvp.constData());
300 rotation += 5.0f;
301 static float opacity = 1.0f;
302 static int opacityDir= 1;
303 u->updateDynamicBuffer(ubuf, 64, 4, &opacity);
304 opacity += opacityDir * 0.005f;
305 if (opacity < 0.0f || opacity > 1.0f) {
306 opacityDir *= -1;
307 opacity = qBound(0.0f, opacity, 1.0f);
308 }
309
310 cb->beginPass(rt, QColor::fromRgbF(0.0f, 1.0f, 0.0f, 1.0f), { 1, 0 }, u);
311 cb->setGraphicsPipeline(ps);
312 cb->setViewport({ 0, 0, 1280, 720 });
313 cb->setShaderResources();
314 const QRhiCommandBuffer::VertexInput vbufBinding(vbuf, 0);
315 cb->setVertexInput(0, 1, &vbufBinding);
316 cb->draw(3);
317
318 u = r->nextResourceUpdateBatch();
319 QRhiReadbackDescription rb(tex);
320 QRhiReadbackResult rbResult;
321 rbResult.completed = [frame] { qDebug(" - readback %d completed", frame); };
322 u->readBackTexture(rb, &rbResult);
323
324 cb->endPass(u);
325
326 qDebug("Submit and wait");
327 #ifdef TEST_FINISH
328 r->finish();
329 #else
330 r->endOffscreenFrame();
331 #endif
332 // The data should be ready either because endOffscreenFrame() waits
333 // for completion or because finish() did.
334 if (!rbResult.data.isEmpty()) {
335 const uchar *p = reinterpret_cast<const uchar *>(rbResult.data.constData());
336 QImage image(p, rbResult.pixelSize.width(), rbResult.pixelSize.height(), QImage::Format_RGBA8888);
337 QString fn = QString::asprintf("frame%d.png", frame);
338 fn = QFileInfo(fn).absoluteFilePath();
339 qDebug("Saving into %s", qPrintable(fn));
340 if (r->isYUpInFramebuffer())
341 image.mirrored().save(fn);
342 else
343 image.save(fn);
344 } else {
345 qWarning("Readback failed!");
346 }
347 #ifdef TEST_FINISH
348 r->endOffscreenFrame();
349 #endif
350 }
351
352 delete ps;
353 delete srb;
354 delete ubuf;
355 delete vbuf;
356
357 delete rt;
358 delete rp;
359 delete tex;
360
361 delete r;
362
363 qDebug("\nRendered and read back %d frames using %s", frame, qPrintable(graphicsApiName()));
364
365 return 0;
366 }