Debian Codegraph @

tests/manual/rhi/rhiwidgetproto/rhiwidget.cpp

raw
1 // Copyright (C) 2021 The Qt Company Ltd.
2 // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
3
4 #include "rhiwidget_p.h"
5
6 #include <private/qguiapplication_p.h>
7 #include <qpa/qplatformintegration.h>
8 #include <private/qwidgetrepaintmanager_p.h>
9
10 /*!
11 \class QRhiWidget
12 \inmodule QtWidgets
13 \since 6.x
14
15 \brief The QRhiWidget class is a widget for rendering 3D graphics via an
16 accelerated grapics API, such as Vulkan, Metal, or Direct 3D.
17
18 QRhiWidget provides functionality for displaying 3D content rendered through
19 the QRhi APIs within a QWidget-based application.
20
21 QRhiWidget is expected to be subclassed. To render into the 2D texture that
22 is implicitly created and managed by the QRhiWidget, subclasses should
23 reimplement the virtual functions initialize() and render().
24
25 The size of the texture will by default adapt to the size of the item. If a
26 fixed size is preferred, set an explicit size specified in pixels by
27 calling setExplicitSize().
28
29 The QRhi for the widget's top-level window is configured to use a platform
30 specific backend and graphics API by default: Metal on macOS and iOS,
31 Direct 3D 11 on Windows, OpenGL otherwise. Call setApi() to override this.
32
33 \note A single widget window can only use one QRhi backend, and so graphics
34 API. If two QRhiWidget or QQuickWidget widgets in the window's widget
35 hierarchy request different APIs, only one of them will function correctly.
36 */
37
38 /*!
39 Constructs a widget which is a child of \a parent, with widget flags set to \a f.
40 */
41 QRhiWidget::QRhiWidget(QWidget *parent, Qt::WindowFlags f)
42 : QWidget(*(new QRhiWidgetPrivate), parent, f)
43 {
44 Q_D(QRhiWidget);
45 if (Q_UNLIKELY(!QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::RhiBasedRendering)))
46 qWarning("QRhiWidget: QRhi is not supported on this platform.");
47 else
48 d->setRenderToTexture();
49
50 d->config.setEnabled(true);
51 #if defined(Q_OS_DARWIN)
52 d->config.setApi(QPlatformBackingStoreRhiConfig::Metal);
53 #elif defined(Q_OS_WIN)
54 d->config.setApi(QPlatformBackingStoreRhiConfig::D3D11);
55 #else
56 d->config.setApi(QPlatformBackingStoreRhiConfig::OpenGL);
57 #endif
58 }
59
60 /*!
61 Destructor.
62 */
63 QRhiWidget::~QRhiWidget()
64 {
65 Q_D(QRhiWidget);
66 // rhi resources must be destroyed here, cannot be left to the private dtor
67 delete d->t;
68 d->offscreenRenderer.reset();
69 }
70
71 /*!
72 Handles resize events that are passed in the \a e event parameter. Calls
73 the virtual function initialize().
74
75 \note Avoid overriding this function in derived classes. If that is not
76 feasible, make sure that QRhiWidget's implementation is invoked too.
77 Otherwise the underlying texture object and related resources will not get
78 resized properly and will lead to incorrect rendering.
79 */
80 void QRhiWidget::resizeEvent(QResizeEvent *e)
81 {
82 Q_D(QRhiWidget);
83
84 if (e->size().isEmpty()) {
85 d->noSize = true;
86 return;
87 }
88 d->noSize = false;
89
90 d->sendPaintEvent(QRect(QPoint(0, 0), size()));
91 }
92
93 /*!
94 Handles paint events.
95
96 Calling QWidget::update() will lead to sending a paint event \a e, and thus
97 invoking this function. (NB this is asynchronous and will happen at some
98 point after returning from update()). This function will then, after some
99 preparation, call the virtual render() to update the contents of the
100 QRhiWidget's associated texture. The widget's top-level window will then
101 composite the texture with the rest of the window.
102 */
103 void QRhiWidget::paintEvent(QPaintEvent *)
104 {
105 Q_D(QRhiWidget);
106 if (!updatesEnabled() || d->noSize)
107 return;
108
109 d->ensureRhi();
110 if (!d->rhi) {
111 qWarning("QRhiWidget: No QRhi");
112 return;
113 }
114
115 const QSize prevSize = d->t ? d->t->pixelSize() : QSize();
116 d->ensureTexture();
117 if (!d->t)
118 return;
119 if (d->t->pixelSize() != prevSize)
120 initialize(d->rhi, d->t);
121
122 QRhiCommandBuffer *cb = nullptr;
123 d->rhi->beginOffscreenFrame(&cb);
124 render(cb);
125 d->rhi->endOffscreenFrame();
126 }
127
128 /*!
129 \reimp
130 */
131 bool QRhiWidget::event(QEvent *e)
132 {
133 Q_D(QRhiWidget);
134 switch (e->type()) {
135 case QEvent::WindowChangeInternal:
136 // the QRhi will almost certainly change, prevent texture() from
137 // returning the existing QRhiTexture in the meantime
138 d->textureInvalid = true;
139 break;
140 case QEvent::Show:
141 if (isVisible())
142 d->sendPaintEvent(QRect(QPoint(0, 0), size()));
143 break;
144 default:
145 break;
146 }
147 return QWidget::event(e);
148 }
149
150 QPlatformBackingStoreRhiConfig QRhiWidgetPrivate::rhiConfig() const
151 {
152 return config;
153 }
154
155 void QRhiWidgetPrivate::ensureRhi()
156 {
157 QRhi *currentRhi = QWidgetPrivate::rhi();
158 if (currentRhi && currentRhi->backend() != QBackingStoreRhiSupport::apiToRhiBackend(config.api())) {
159 qWarning("The top-level window is already using another graphics API for composition, "
160 "'%s' is not compatible with this widget",
161 currentRhi->backendName());
162 return;
163 }
164
165 if (currentRhi && rhi && rhi != currentRhi) {
166 // the texture belongs to the old rhi, drop it, this will also lead to
167 // initialize() being called again
168 delete t;
169 t = nullptr;
170 // if previously we created our own but now get a QRhi from the
171 // top-level, then drop what we have and start using the top-level's
172 if (rhi == offscreenRenderer.rhi())
173 offscreenRenderer.reset();
174 }
175
176 rhi = currentRhi;
177 }
178
179 void QRhiWidgetPrivate::ensureTexture()
180 {
181 Q_Q(QRhiWidget);
182
183 QSize newSize = explicitSize;
184 if (newSize.isEmpty())
185 newSize = q->size() * q->devicePixelRatio();
186
187 if (!t) {
188 if (!rhi->isTextureFormatSupported(format))
189 qWarning("QRhiWidget: The requested texture format is not supported by the graphics API implementation");
190 t = rhi->newTexture(format, newSize, 1, QRhiTexture::RenderTarget | QRhiTexture::UsedAsTransferSource);
191 if (!t->create()) {
192 qWarning("Failed to create backing texture for QRhiWidget");
193 delete t;
194 t = nullptr;
195 return;
196 }
197 }
198
199 if (t->pixelSize() != newSize) {
200 t->setPixelSize(newSize);
201 if (!t->create())
202 qWarning("Failed to rebuild texture for QRhiWidget after resizing");
203 }
204
205 textureInvalid = false;
206 }
207
208 /*!
209 \return the currently set graphics API (QRhi backend).
210
211 \sa setApi()
212 */
213 QRhiWidget::Api QRhiWidget::api() const
214 {
215 Q_D(const QRhiWidget);
216 switch (d->config.api()) {
217 case QPlatformBackingStoreRhiConfig::OpenGL:
218 return OpenGL;
219 case QPlatformBackingStoreRhiConfig::Metal:
220 return Metal;
221 case QPlatformBackingStoreRhiConfig::Vulkan:
222 return Vulkan;
223 case QPlatformBackingStoreRhiConfig::D3D11:
224 return D3D11;
225 default:
226 return Null;
227 }
228 }
229
230 /*!
231 Sets the graphics API and QRhi backend to use to \a api.
232
233 The default value depends on the platform: Metal on macOS and iOS, Direct
234 3D 11 on Windows, OpenGL otherwise.
235
236 \note This function must be called early enough, before the widget is added
237 to a widget hierarchy and displayed on screen. For example, aim to call the
238 function for the subclass constructor. If called too late, the function
239 will have no effect.
240
241 The \a api can only be set once for the widget and its top-level window,
242 once it is done and takes effect, the window can only use that API and QRhi
243 backend to render. Attempting to set another value, or to add another
244 QRhiWidget with a different \a api will not function as expected.
245
246 \sa setTextureFormat(), setDebugLayer(), api()
247 */
248 void QRhiWidget::setApi(Api api)
249 {
250 Q_D(QRhiWidget);
251 switch (api) {
252 case OpenGL:
253 d->config.setApi(QPlatformBackingStoreRhiConfig::OpenGL);
254 break;
255 case Metal:
256 d->config.setApi(QPlatformBackingStoreRhiConfig::Metal);
257 break;
258 case Vulkan:
259 d->config.setApi(QPlatformBackingStoreRhiConfig::Vulkan);
260 break;
261 case D3D11:
262 d->config.setApi(QPlatformBackingStoreRhiConfig::D3D11);
263 break;
264 default:
265 d->config.setApi(QPlatformBackingStoreRhiConfig::Null);
266 break;
267 }
268 }
269
270 /*!
271 \return true if a debug or validation layer will be requested if applicable
272 to the graphics API in use.
273
274 \sa setDebugLayer()
275 */
276 bool QRhiWidget::isDebugLayerEnabled() const
277 {
278 Q_D(const QRhiWidget);
279 return d->config.isDebugLayerEnabled();
280 }
281
282 /*!
283 Requests the debug or validation layer of the underlying graphics API
284 when \a enable is true.
285
286 Applicable for Vulkan and Direct 3D.
287
288 \note This function must be called early enough, before the widget is added
289 to a widget hierarchy and displayed on screen. For example, aim to call the
290 function for the subclass constructor. If called too late, the function
291 will have no effect.
292
293 By default this is disabled.
294
295 \sa setApi(), isDebugLayerEnabled()
296 */
297 void QRhiWidget::setDebugLayer(bool enable)
298 {
299 Q_D(QRhiWidget);
300 d->config.setDebugLayer(enable);
301 }
302
303 /*!
304 \return the currently set texture format.
305
306 The default value is QRhiTexture::RGBA8.
307
308 \sa setTextureFormat()
309 */
310 QRhiTexture::Format QRhiWidget::textureFormat() const
311 {
312 Q_D(const QRhiWidget);
313 return d->format;
314 }
315
316 /*!
317 Sets the associated texture's \a format.
318
319 The default value is QRhiTexture::RGBA8. Only formats that are reported as
320 supported from QRhi::isTextureFormatSupported() should be specified,
321 rendering will not be functional otherwise.
322
323 \note This function must be called early enough, before the widget is added
324 to a widget hierarchy and displayed on screen. For example, aim to call the
325 function for the subclass constructor. If called too late, the function
326 will have no effect.
327
328 \sa setApi(), textureFormat()
329 */
330 void QRhiWidget::setTextureFormat(QRhiTexture::Format format)
331 {
332 Q_D(QRhiWidget);
333 d->format = format;
334 }
335
336 /*!
337 \property QRhiWidget::explicitSize
338
339 The fixed size (in pixels) of the QRhiWidget's associated texture.
340
341 Only relevant when a fixed texture size is desired that does not depend on
342 the widget's size.
343
344 By default the value is a null QSize. A null or empty QSize means that the
345 texture's size follows the QRhiWidget's size. (\c{texture size} = \c{widget
346 size} * \c{device pixel ratio}).
347 */
348
349 QSize QRhiWidget::explicitSize() const
350 {
351 Q_D(const QRhiWidget);
352 return d->explicitSize;
353 }
354
355 void QRhiWidget::setExplicitSize(const QSize &pixelSize)
356 {
357 Q_D(QRhiWidget);
358 if (d->explicitSize != pixelSize) {
359 d->explicitSize = pixelSize;
360 emit explicitSizeChanged(pixelSize);
361 update();
362 }
363 }
364
365 /*!
366 Renders a new frame, reads the contents of the texture back, and returns it
367 as a QImage.
368
369 When an error occurs, a null QImage is returned.
370
371 \note This function only supports reading back QRhiTexture::RGBA8 textures
372 at the moment. For other formats, the implementer of render() should
373 implement their own readback logic as they see fit.
374
375 The returned QImage will have a format of QImage::Format_RGBA8888.
376 QRhiWidget does not know the renderer's approach to blending and
377 composition, and therefore cannot know if the output has alpha
378 premultiplied.
379
380 This function can also be called when the QRhiWidget is not added to a
381 widget hierarchy belonging to an on-screen top-level window. This allows
382 generating an image from a 3D rendering off-screen.
383
384 \sa setTextureFormat()
385 */
386 QImage QRhiWidget::grabTexture()
387 {
388 Q_D(QRhiWidget);
389 if (d->noSize)
390 return QImage();
391
392 if (d->format != QRhiTexture::RGBA8) {
393 qWarning("QRhiWidget::grabTexture() only supports RGBA8 textures");
394 return QImage();
395 }
396
397 d->ensureRhi();
398 if (!d->rhi) {
399 // The widget (and its parent chain, if any) may not be shown at
400 // all, yet one may still want to use it for grabs. This is
401 // ridiculous of course because the rendering infrastructure is
402 // tied to the top-level widget that initializes upon expose, but
403 // it has to be supported.
404 d->offscreenRenderer.setConfig(d->config);
405 // no window passed in, so no swapchain, but we get a functional QRhi which we own
406 d->offscreenRenderer.create();
407 d->rhi = d->offscreenRenderer.rhi();
408 if (!d->rhi) {
409 qWarning("QRhiWidget: Failed to create dedicated QRhi for grabbing");
410 return QImage();
411 }
412 }
413
414 const QSize prevSize = d->t ? d->t->pixelSize() : QSize();
415 d->ensureTexture();
416 if (!d->t)
417 return QImage();
418 if (d->t->pixelSize() != prevSize)
419 initialize(d->rhi, d->t);
420
421 QRhiReadbackResult readResult;
422 bool readCompleted = false;
423 readResult.completed = [&readCompleted] { readCompleted = true; };
424
425 QRhiCommandBuffer *cb = nullptr;
426 d->rhi->beginOffscreenFrame(&cb);
427 render(cb);
428 QRhiResourceUpdateBatch *readbackBatch = d->rhi->nextResourceUpdateBatch();
429 readbackBatch->readBackTexture(d->t, &readResult);
430 cb->resourceUpdate(readbackBatch);
431 d->rhi->endOffscreenFrame();
432
433 if (readCompleted) {
434 QImage wrapperImage(reinterpret_cast<const uchar *>(readResult.data.constData()),
435 readResult.pixelSize.width(), readResult.pixelSize.height(),
436 QImage::Format_RGBA8888);
437 QImage result = wrapperImage.copy();
438 result.setDevicePixelRatio(devicePixelRatio());
439 return result;
440 } else {
441 Q_UNREACHABLE();
442 }
443
444 return QImage();
445 }
446
447 /*!
448 Called when the widget is initialized, when the associated texture's size
449 changes, or when the QRhi and texture change for some reason.
450
451 The implementation should be prepared that both \a rhi and \a outputTexture
452 can change between invocations of this function, although this is not
453 always going to happen in practice. When the widget size changes, this
454 function is called with the same \a rhi and \a outputTexture as before, but
455 \a outputTexture may have been rebuilt, meaning its
456 \l{QRhiTexture::pixelSize()}{size} and the underlying native texture
457 resource may be different than in the last invocation.
458
459 One special case where the objects will be different is when performing a
460 grabTexture() with a widget that is not yet shown, and then making the
461 widget visible on-screen within a top-level widget. There the grab will
462 happen with a dedicated QRhi that is then replaced with the top-level
463 window's associated QRhi in subsequent initialize() and render()
464 invocations.
465
466 Another, more common case is when the widget is reparented so that it
467 belongs to a new top-level window. In this case \a rhi and \a outputTexture
468 will definitely be different in the subsequent call to this function. Is is
469 then important that all existing QRhi resources are destroyed because they
470 belong to the previous QRhi that should not be used by the widget anymore.
471
472 Implementations will typically create or rebuild a QRhiTextureRenderTarget
473 in order to allow the subsequent render() call to render into the texture.
474 When a depth buffer is necessary create a QRhiRenderBuffer as well. The
475 size if this must follow the size of \a outputTexture. A compact and
476 efficient way for this is the following:
477
478 \code
479 if (m_rhi != rhi) {
480 // reset all resources (incl. m_ds, m_rt, m_rp)
481 } else if (m_output != outputTexture) {
482 // reset m_rt and m_rp
483 }
484 m_rhi = rhi;
485 m_output = outputTexture;
486 if (!m_ds) {
487 // no depth-stencil buffer yet, create one
488 m_ds = m_rhi->newRenderBuffer(QRhiRenderBuffer::DepthStencil, m_output->pixelSize());
489 m_ds->create();
490 } else if (m_ds->pixelSize() != m_output->pixelSize()) {
491 // the size has changed, update the size and rebuild
492 m_ds->setPixelSize(m_output->pixelSize());
493 m_ds->create();
494 }
495 if (!m_rt) {
496 m_rt = m_rhi->newTextureRenderTarget({ { m_output }, m_ds });
497 m_rp = m_rt->newCompatibleRenderPassDescriptor();
498 m_rt->setRenderPassDescriptor(m_rp);
499 m_rt->create();
500 }
501 \endcode
502
503 The above snippet is also prepared for \a rhi and \a outputTexture changing
504 between invocations, via the checks at the beginning of the function.
505
506 The created resources are expected to be released in the destructor
507 implementation of the subclass. \a rhi and \a outputTexture are not owned
508 by, and are guaranteed to outlive the QRhiWidget.
509
510 \sa render()
511 */
512 void QRhiWidget::initialize(QRhi *rhi, QRhiTexture *outputTexture)
513 {
514 Q_UNUSED(rhi);
515 Q_UNUSED(outputTexture);
516 }
517
518 /*!
519 Called when the widget contents (i.e. the contents of the texture) need
520 updating.
521
522 There is always at least one call to initialize() before this function is
523 called.
524
525 To request updates, call QWidget::update(). Calling update() from within
526 render() will lead to updating continuously, throttled by vsync.
527
528 \a cb is the QRhiCommandBuffer for the current frame of the Qt Quick
529 scenegraph. The function is called with a frame being recorded, but without
530 an active render pass.
531
532 \sa initialize()
533 */
534 void QRhiWidget::render(QRhiCommandBuffer *cb)
535 {
536 Q_UNUSED(cb);
537 }