Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qrhigles2.cpp
Go to the documentation of this file.
1// Copyright (C) 2023 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#include "qrhigles2_p.h"
6#include <QOffscreenSurface>
7#include <QOpenGLContext>
8#include <QtCore/qendian.h>
9#include <QtCore/qmap.h>
10#include <QtGui/private/qguiapplication_p.h>
11#include <QtGui/private/qopenglextensions_p.h>
12#include <QtGui/private/qopenglprogrambinarycache_p.h>
13#include <QtGui/private/qwindow_p.h>
14#include <kernel/qplatformintegration.h>
15#include <qpa/qplatformopenglcontext.h>
16#include <qmath.h>
17
18#include <limits>
19
21
22/*
23 OpenGL backend. Binding vertex attribute locations and decomposing uniform
24 buffers into uniforms are handled transparently to the application via the
25 reflection data (QShaderDescription). Real uniform buffers are never used,
26 regardless of the GLSL version. Textures and buffers feature no special
27 logic, it's all just glTexSubImage2D and glBufferSubData (with "dynamic"
28 buffers set to GL_DYNAMIC_DRAW). The swapchain and the associated
29 renderbuffer for depth-stencil will be dummies since we have no control over
30 the underlying buffers here. While the baseline here is plain GLES 2.0, some
31 modern GL(ES) features like multisample renderbuffers, blits, and compute are
32 used when available. Also functional with core profile contexts.
33*/
34
35/*!
36 \class QRhiGles2InitParams
37 \inmodule QtGuiPrivate
38 \inheaderfile rhi/qrhi.h
39 \since 6.6
40 \brief OpenGL specific initialization parameters.
41
42 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
43 for details.
44
45 An OpenGL-based QRhi needs an already created QSurface that can be used in
46 combination with QOpenGLContext. Most commonly, this is a QOffscreenSurface
47 in practice. Additionally, while optional, it is recommended that the QWindow
48 the first QRhiSwapChain will target is passed in as well.
49
50 \badcode
51 QOffscreenSurface *fallbackSurface = QRhiGles2InitParams::newFallbackSurface();
52 QRhiGles2InitParams params;
53 params.fallbackSurface = fallbackSurface;
54 params.window = window;
55 rhi = QRhi::create(QRhi::OpenGLES2, &params);
56 \endcode
57
58 By default QRhi creates a QOpenGLContext on its own. This approach works
59 well in most cases, including threaded scenarios, where there is a dedicated
60 QRhi for each rendering thread. As there will be a QOpenGLContext for each
61 QRhi, the OpenGL context requirements (a context can only be current on one
62 thread) are satisfied. The implicitly created context is destroyed
63 automatically together with the QRhi.
64
65 The QSurfaceFormat for the context is specified in \c format. The
66 constructor sets this to QSurfaceFormat::defaultFormat() so applications
67 that call QSurfaceFormat::setDefaultFormat() with the appropriate settings
68 before the constructor runs will not need to change the value of \c format.
69
70 \note Remember to set the depth and stencil buffer sizes to 24 and 8 when
71 the renderer relies on depth or stencil testing, either in the global
72 default QSurfaceFormat, or, alternatively, separately in all the involved
73 QSurfaceFormat instances: in \c format, the format argument passed to
74 newFallbackSurface(), and on any QWindow that is used with the QRhi.
75
76 A QSurface has to be specified in \c fallbackSurface. In order to prevent
77 mistakes in threaded situations, this is never created automatically by the
78 QRhi because, like QWindow, instances of QSurface subclasses can often be
79 created on the gui/main thread only.
80
81 As a convenience, applications can use newFallbackSurface() which creates
82 and returns a QOffscreenSurface that is compatible with the QOpenGLContext
83 that is going to be created by the QRhi afterwards. Note that the ownership
84 of the returned QOffscreenSurface is transferred to the caller and the QRhi
85 will not destroy it.
86
87 \note With the OpenGL backend, QRhiSwapChain can only target QWindow
88 instances that have their surface type set to QSurface::OpenGLSurface.
89
90 \note \c window is optional. It is recommended to specify it whenever
91 possible, in order to avoid problems on multi-adapter and multi-screen
92 systems. When \c window is not set, the very first
93 QOpenGLContext::makeCurrent() happens with \c fallbackSurface which may be
94 an invisible window on some platforms (for example, Windows) and that may
95 trigger unexpected problems in some cases.
96
97 In case resource sharing with an existing QOpenGLContext is desired, \c
98 shareContext can be set to an existing QOpenGLContext. Alternatively,
99 Qt::AA_ShareOpenGLContexts is honored as well, when enabled.
100
101 \section1 Working with existing OpenGL contexts
102
103 When interoperating with another graphics engine, it may be necessary to
104 get a QRhi instance that uses the same OpenGL context. This can be achieved
105 by passing a pointer to a QRhiGles2NativeHandles to QRhi::create(). The
106 \c{QRhiGles2NativeHandles::context} must be set to a non-null value then.
107
108 An alternative approach is to create a QOpenGLContext that
109 \l{QOpenGLContext::setShareContext()}{shares resources} with the other
110 engine's context and passing in that context via QRhiGles2NativeHandles.
111
112 The QRhi does not take ownership of the QOpenGLContext passed in via
113 QRhiGles2NativeHandles.
114 */
115
116/*!
117 \variable QRhiGles2InitParams::format
118
119 The QSurfaceFormat, initialized to QSurfaceFormat::defaultFormat() by default.
120*/
121
122/*!
123 \variable QRhiGles2InitParams::fallbackSurface
124
125 A QSurface compatible with \l format. Typically a QOffscreenSurface.
126 Providing this is mandatory. Be aware of the threading implications: a
127 QOffscreenSurface, like QWindow, must only ever be created and destroyed on
128 the main (gui) thread, even if the QRhi is created and operates on another
129 thread.
130*/
131
132/*!
133 \variable QRhiGles2InitParams::window
134
135 Optional, but setting it is recommended when targeting a QWindow with the
136 QRhi.
137*/
138
139/*!
140 \variable QRhiGles2InitParams::shareContext
141
142 Optional, the QOpenGLContext to share resources with. QRhi creates its own
143 context, and setting this member to a valid QOpenGLContext leads to calling
144 \l{QOpenGLContext::setShareContext()}{setShareContext()} with it.
145*/
146
147/*!
148 \class QRhiGles2NativeHandles
149 \inmodule QtGuiPrivate
150 \inheaderfile rhi/qrhi.h
151 \since 6.6
152 \brief Holds the OpenGL context used by the QRhi.
153
154 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
155 for details.
156 */
157
158/*!
159 \variable QRhiGles2NativeHandles::context
160*/
161
162#ifndef GL_SRC1_COLOR
163#define GL_SRC1_COLOR 0x88F9
164#endif
165
166#ifndef GL_ONE_MINUS_SRC1_COLOR
167#define GL_ONE_MINUS_SRC1_COLOR 0x88FA
168#endif
169
170#ifndef GL_SRC1_ALPHA
171#define GL_SRC1_ALPHA 0x8589
172#endif
173
174#ifndef GL_ONE_MINUS_SRC1_ALPHA
175#define GL_ONE_MINUS_SRC1_ALPHA 0x88FB
176#endif
177
178#ifndef GL_BGRA
179#define GL_BGRA 0x80E1
180#endif
181
182#ifndef GL_R8
183#define GL_R8 0x8229
184#endif
185
186#ifndef GL_R8I
187#define GL_R8I 0x8231
188#endif
189
190#ifndef GL_R8UI
191#define GL_R8UI 0x8232
192#endif
193
194#ifndef GL_R32I
195#define GL_R32I 0x8235
196#endif
197
198#ifndef GL_R32UI
199#define GL_R32UI 0x8236
200#endif
201
202#ifndef GL_RG32I
203#define GL_RG32I 0x823B
204#endif
205
206#ifndef GL_RG32UI
207#define GL_RG32UI 0x823C
208#endif
209
210#ifndef GL_RGBA32I
211#define GL_RGBA32I 0x8D82
212#endif
213
214#ifndef GL_RGBA32UI
215#define GL_RGBA32UI 0x8D70
216#endif
217
218#ifndef GL_RG8
219#define GL_RG8 0x822B
220#endif
221
222#ifndef GL_RG
223#define GL_RG 0x8227
224#endif
225
226#ifndef GL_RG_INTEGER
227#define GL_RG_INTEGER 0x8228
228#endif
229
230#ifndef GL_R16
231#define GL_R16 0x822A
232#endif
233
234#ifndef GL_RG16
235#define GL_RG16 0x822C
236#endif
237
238#ifndef GL_RED
239#define GL_RED 0x1903
240#endif
241
242#ifndef GL_RED_INTEGER
243#define GL_RED_INTEGER 0x8D94
244#endif
245
246#ifndef GL_RGBA_INTEGER
247#define GL_RGBA_INTEGER 0x8D99
248#endif
249
250#ifndef GL_RGBA8
251#define GL_RGBA8 0x8058
252#endif
253
254#ifndef GL_RGBA32F
255#define GL_RGBA32F 0x8814
256#endif
257
258#ifndef GL_RGBA16F
259#define GL_RGBA16F 0x881A
260#endif
261
262#ifndef GL_R16F
263#define GL_R16F 0x822D
264#endif
265
266#ifndef GL_R32F
267#define GL_R32F 0x822E
268#endif
269
270#ifndef GL_HALF_FLOAT
271#define GL_HALF_FLOAT 0x140B
272#endif
273
274#ifndef GL_DEPTH_COMPONENT16
275#define GL_DEPTH_COMPONENT16 0x81A5
276#endif
277
278#ifndef GL_DEPTH_COMPONENT24
279#define GL_DEPTH_COMPONENT24 0x81A6
280#endif
281
282#ifndef GL_DEPTH_COMPONENT32F
283#define GL_DEPTH_COMPONENT32F 0x8CAC
284#endif
285
286#ifndef GL_DEPTH32F_STENCIL8
287#define GL_DEPTH32F_STENCIL8 0x8CAD
288#endif
289
290#ifndef GL_FLOAT_32_UNSIGNED_INT_24_8_REV
291#define GL_FLOAT_32_UNSIGNED_INT_24_8_REV 0x8DAD
292#endif
293
294#ifndef GL_UNSIGNED_INT_24_8
295#define GL_UNSIGNED_INT_24_8 0x84FA
296#endif
297
298#ifndef GL_STENCIL_INDEX
299#define GL_STENCIL_INDEX 0x1901
300#endif
301
302#ifndef GL_STENCIL_INDEX8
303#define GL_STENCIL_INDEX8 0x8D48
304#endif
305
306#ifndef GL_DEPTH24_STENCIL8
307#define GL_DEPTH24_STENCIL8 0x88F0
308#endif
309
310#ifndef GL_DEPTH_STENCIL_ATTACHMENT
311#define GL_DEPTH_STENCIL_ATTACHMENT 0x821A
312#endif
313
314#ifndef GL_DEPTH_STENCIL
315#define GL_DEPTH_STENCIL 0x84F9
316#endif
317
318#ifndef GL_PRIMITIVE_RESTART_FIXED_INDEX
319#define GL_PRIMITIVE_RESTART_FIXED_INDEX 0x8D69
320#endif
321
322#ifndef GL_FRAMEBUFFER_SRGB
323#define GL_FRAMEBUFFER_SRGB 0x8DB9
324#endif
325
326#ifndef GL_SRGB_ALPHA
327#define GL_SRGB_ALPHA 0x8C42
328#endif
329
330#ifndef GL_SRGB8_ALPHA8
331#define GL_SRGB8_ALPHA8 0x8C43
332#endif
333
334#ifndef GL_READ_FRAMEBUFFER
335#define GL_READ_FRAMEBUFFER 0x8CA8
336#endif
337
338#ifndef GL_DRAW_FRAMEBUFFER
339#define GL_DRAW_FRAMEBUFFER 0x8CA9
340#endif
341
342#ifndef GL_MAX_DRAW_BUFFERS
343#define GL_MAX_DRAW_BUFFERS 0x8824
344#endif
345
346#ifndef GL_TEXTURE_COMPARE_MODE
347#define GL_TEXTURE_COMPARE_MODE 0x884C
348#endif
349
350#ifndef GL_COMPARE_REF_TO_TEXTURE
351#define GL_COMPARE_REF_TO_TEXTURE 0x884E
352#endif
353
354#ifndef GL_TEXTURE_COMPARE_FUNC
355#define GL_TEXTURE_COMPARE_FUNC 0x884D
356#endif
357
358#ifndef GL_MAX_SAMPLES
359#define GL_MAX_SAMPLES 0x8D57
360#endif
361
362#ifndef GL_SHADER_STORAGE_BUFFER
363#define GL_SHADER_STORAGE_BUFFER 0x90D2
364#endif
365
366#ifndef GL_COPY_READ_BUFFER
367#define GL_COPY_READ_BUFFER 0x8F36
368#endif
369
370#ifndef GL_COPY_WRITE_BUFFER
371#define GL_COPY_WRITE_BUFFER 0x8F37
372#endif
373
374#ifndef GL_READ_ONLY
375#define GL_READ_ONLY 0x88B8
376#endif
377
378#ifndef GL_WRITE_ONLY
379#define GL_WRITE_ONLY 0x88B9
380#endif
381
382#ifndef GL_READ_WRITE
383#define GL_READ_WRITE 0x88BA
384#endif
385
386#ifndef GL_COMPUTE_SHADER
387#define GL_COMPUTE_SHADER 0x91B9
388#endif
389
390#ifndef GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT
391#define GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT 0x00000001
392#endif
393
394#ifndef GL_ELEMENT_ARRAY_BARRIER_BIT
395#define GL_ELEMENT_ARRAY_BARRIER_BIT 0x00000002
396#endif
397
398#ifndef GL_UNIFORM_BARRIER_BIT
399#define GL_UNIFORM_BARRIER_BIT 0x00000004
400#endif
401
402#ifndef GL_BUFFER_UPDATE_BARRIER_BIT
403#define GL_BUFFER_UPDATE_BARRIER_BIT 0x00000200
404#endif
405
406#ifndef GL_COMMAND_BARRIER_BIT
407#define GL_COMMAND_BARRIER_BIT 0x00000040
408#endif
409
410#ifndef GL_SHADER_STORAGE_BARRIER_BIT
411#define GL_SHADER_STORAGE_BARRIER_BIT 0x00002000
412#endif
413
414#ifndef GL_TEXTURE_FETCH_BARRIER_BIT
415#define GL_TEXTURE_FETCH_BARRIER_BIT 0x00000008
416#endif
417
418#ifndef GL_SHADER_IMAGE_ACCESS_BARRIER_BIT
419#define GL_SHADER_IMAGE_ACCESS_BARRIER_BIT 0x00000020
420#endif
421
422#ifndef GL_PIXEL_BUFFER_BARRIER_BIT
423#define GL_PIXEL_BUFFER_BARRIER_BIT 0x00000080
424#endif
425
426#ifndef GL_TEXTURE_UPDATE_BARRIER_BIT
427#define GL_TEXTURE_UPDATE_BARRIER_BIT 0x00000100
428#endif
429
430#ifndef GL_FRAMEBUFFER_BARRIER_BIT
431#define GL_FRAMEBUFFER_BARRIER_BIT 0x00000400
432#endif
433
434#ifndef GL_ALL_BARRIER_BITS
435#define GL_ALL_BARRIER_BITS 0xFFFFFFFF
436#endif
437
438#ifndef GL_VERTEX_PROGRAM_POINT_SIZE
439#define GL_VERTEX_PROGRAM_POINT_SIZE 0x8642
440#endif
441
442#ifndef GL_POINT_SPRITE
443#define GL_POINT_SPRITE 0x8861
444#endif
445
446#ifndef GL_MAP_READ_BIT
447#define GL_MAP_READ_BIT 0x0001
448#endif
449
450#ifndef GL_MAP_WRITE_BIT
451#define GL_MAP_WRITE_BIT 0x0002
452#endif
453
454#ifndef GL_MAP_INVALIDATE_BUFFER_BIT
455#define GL_MAP_INVALIDATE_BUFFER_BIT 0x0008
456#endif
457
458#ifndef GL_TEXTURE_2D_MULTISAMPLE
459#define GL_TEXTURE_2D_MULTISAMPLE 0x9100
460#endif
461
462#ifndef GL_TEXTURE_2D_MULTISAMPLE_ARRAY
463#define GL_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9102
464#endif
465
466#ifndef GL_TEXTURE_EXTERNAL_OES
467#define GL_TEXTURE_EXTERNAL_OES 0x8D65
468#endif
469
470#ifndef GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS
471#define GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS 0x90EB
472#endif
473
474#ifndef GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS
475#define GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS 0x90D6
476#endif
477
478#ifndef GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS
479#define GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS 0x90DA
480#endif
481
482#ifndef GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS
483#define GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS 0x90DD
484#endif
485
486#ifndef GL_MAX_COMPUTE_WORK_GROUP_COUNT
487#define GL_MAX_COMPUTE_WORK_GROUP_COUNT 0x91BE
488#endif
489
490#ifndef GL_MAX_COMPUTE_WORK_GROUP_SIZE
491#define GL_MAX_COMPUTE_WORK_GROUP_SIZE 0x91BF
492#endif
493
494#ifndef GL_TEXTURE_CUBE_MAP_SEAMLESS
495#define GL_TEXTURE_CUBE_MAP_SEAMLESS 0x884F
496#endif
497
498#ifndef GL_CONTEXT_LOST
499#define GL_CONTEXT_LOST 0x0507
500#endif
501
502#ifndef GL_PROGRAM_BINARY_LENGTH
503#define GL_PROGRAM_BINARY_LENGTH 0x8741
504#endif
505
506#ifndef GL_NUM_PROGRAM_BINARY_FORMATS
507#define GL_NUM_PROGRAM_BINARY_FORMATS 0x87FE
508#endif
509
511#define GL_UNPACK_ROW_LENGTH 0x0CF2
512#endif
513
514#ifndef GL_TEXTURE_3D
515#define GL_TEXTURE_3D 0x806F
516#endif
517
518#ifndef GL_TEXTURE_WRAP_R
519#define GL_TEXTURE_WRAP_R 0x8072
520#endif
521
522#ifndef GL_TEXTURE_RECTANGLE
523#define GL_TEXTURE_RECTANGLE 0x84F5
524#endif
525
526#ifndef GL_TEXTURE_2D_ARRAY
527#define GL_TEXTURE_2D_ARRAY 0x8C1A
528#endif
529
530#ifndef GL_MAX_ARRAY_TEXTURE_LAYERS
531#define GL_MAX_ARRAY_TEXTURE_LAYERS 0x88FF
532#endif
533
534#ifndef GL_MAX_VERTEX_UNIFORM_COMPONENTS
535#define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A
536#endif
537
538#ifndef GL_MAX_FRAGMENT_UNIFORM_COMPONENTS
539#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49
540#endif
541
542#ifndef GL_MAX_VERTEX_UNIFORM_VECTORS
543#define GL_MAX_VERTEX_UNIFORM_VECTORS 0x8DFB
544#endif
545
546#ifndef GL_MAX_FRAGMENT_UNIFORM_VECTORS
547#define GL_MAX_FRAGMENT_UNIFORM_VECTORS 0x8DFD
548#endif
549
550#ifndef GL_RGB10_A2
551#define GL_RGB10_A2 0x8059
552#endif
553
555#define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368
556#endif
557
558#ifndef GL_MAX_VARYING_COMPONENTS
559#define GL_MAX_VARYING_COMPONENTS 0x8B4B
560#endif
561
562#ifndef GL_MAX_VARYING_FLOATS
563#define GL_MAX_VARYING_FLOATS 0x8B4B
564#endif
565
566#ifndef GL_MAX_VARYING_VECTORS
567#define GL_MAX_VARYING_VECTORS 0x8DFC
568#endif
569
570#ifndef GL_TESS_CONTROL_SHADER
571#define GL_TESS_CONTROL_SHADER 0x8E88
572#endif
573
574#ifndef GL_TESS_EVALUATION_SHADER
575#define GL_TESS_EVALUATION_SHADER 0x8E87
576#endif
577
578#ifndef GL_PATCH_VERTICES
579#define GL_PATCH_VERTICES 0x8E72
580#endif
581
582#ifndef GL_LINE
583#define GL_LINE 0x1B01
584#endif
585
586#ifndef GL_FILL
587#define GL_FILL 0x1B02
588#endif
589
590#ifndef GL_PATCHES
591#define GL_PATCHES 0x000E
592#endif
593
594#ifndef GL_GEOMETRY_SHADER
595#define GL_GEOMETRY_SHADER 0x8DD9
596#endif
597
598#ifndef GL_BACK_LEFT
599#define GL_BACK_LEFT 0x0402
600#endif
601
602#ifndef GL_BACK_RIGHT
603#define GL_BACK_RIGHT 0x0403
604#endif
605
606#ifndef GL_TEXTURE_1D
607# define GL_TEXTURE_1D 0x0DE0
608#endif
609
610#ifndef GL_TEXTURE_1D_ARRAY
611# define GL_TEXTURE_1D_ARRAY 0x8C18
612#endif
613
614#ifndef GL_HALF_FLOAT
615#define GL_HALF_FLOAT 0x140B
616#endif
617
618#ifndef GL_MAX_VERTEX_OUTPUT_COMPONENTS
619#define GL_MAX_VERTEX_OUTPUT_COMPONENTS 0x9122
620#endif
621
622#ifndef GL_TIMESTAMP
623#define GL_TIMESTAMP 0x8E28
624#endif
625
626#ifndef GL_QUERY_RESULT
627#define GL_QUERY_RESULT 0x8866
628#endif
629
630#ifndef GL_QUERY_RESULT_AVAILABLE
631#define GL_QUERY_RESULT_AVAILABLE 0x8867
632#endif
633
634#ifndef GL_BUFFER
635#define GL_BUFFER 0x82E0
636#endif
637
638#ifndef GL_PROGRAM
639#define GL_PROGRAM 0x82E2
640#endif
641
642#ifndef GL_DEPTH_CLAMP
643#define GL_DEPTH_CLAMP 0x864F
644#endif
645
646#ifndef GL_DRAW_INDIRECT_BUFFER
647#define GL_DRAW_INDIRECT_BUFFER 0x8F3F
648#endif
649
650#ifndef GL_DISPATCH_INDIRECT_BUFFER
651#define GL_DISPATCH_INDIRECT_BUFFER 0x90EE
652#endif
653
654#ifndef GL_PARAMETER_BUFFER
655#define GL_PARAMETER_BUFFER 0x80EE
656#endif
657
658#ifndef GL_MAX_IMAGE_UNITS
659#define GL_MAX_IMAGE_UNITS 0x8F38
660#endif
661
662/*!
663 Constructs a new QRhiGles2InitParams.
664
665 \l format is set to QSurfaceFormat::defaultFormat().
666 */
667QRhiGles2InitParams::QRhiGles2InitParams()
668{
669 format = QSurfaceFormat::defaultFormat();
670}
671
672/*!
673 \return a new QOffscreenSurface that can be used with a QRhi by passing it
674 via a QRhiGles2InitParams.
675
676 When \a format is not specified, its default value is the global default
677 format settable via QSurfaceFormat::setDefaultFormat().
678
679 \a format is adjusted as appropriate in order to avoid having problems
680 afterwards due to an incompatible context and surface.
681
682 \note This function must only be called on the gui/main thread or if
683 the platform integration supports offscreen surfaces.
684
685 \note It is the application's responsibility to destroy the returned
686 QOffscreenSurface on the gui/main thread once the associated QRhi has been
687 destroyed. The QRhi will not destroy the QOffscreenSurface.
688 */
689QOffscreenSurface *QRhiGles2InitParams::newFallbackSurface(const QSurfaceFormat &format)
690{
691 Q_ASSERT(QThread::isMainThread()
692 || QGuiApplicationPrivate::platformIntegration()->hasCapability(
693 QPlatformIntegration::OffscreenSurface));
694
695 QSurfaceFormat fmt = format;
696
697 // To resolve all fields in the format as much as possible, create a context.
698 // This may be heavy, but allows avoiding BAD_MATCH on some systems.
699 QOpenGLContext tempContext;
700 tempContext.setFormat(fmt);
701 if (tempContext.create())
702 fmt = tempContext.format();
703 else
704 qWarning("QRhiGles2: Failed to create temporary context");
705
706 QOffscreenSurface *s = new QOffscreenSurface;
707 s->setFormat(fmt);
708 s->create();
709
710 return s;
711}
712
713QRhiGles2::QRhiGles2(QRhiGles2InitParams *params, QRhiGles2NativeHandles *importDevice)
714 : ofr(this)
715{
716 requestedFormat = params->format;
717 fallbackSurface = params->fallbackSurface;
718 maybeWindow = params->window; // may be null
719 maybeShareContext = params->shareContext; // may be null
720
721 importedContext = importDevice != nullptr;
722 if (importedContext) {
723 ctx = importDevice->context;
724 if (!ctx) {
725 qWarning("No OpenGL context given, cannot import");
726 importedContext = false;
727 }
728 }
729}
730
731static inline QSurface *currentSurfaceForCurrentContext(QOpenGLContext *ctx)
732{
733 static const bool doNotTrustCurrentContext =
734 qEnvironmentVariableIntValue("QT_GL_BROKEN_CONTEXT_TRACKING") != 0;
735 if (doNotTrustCurrentContext)
736 return nullptr; // -> makeCurrent all the time -> may have perf. implications
737
738 if (QOpenGLContext::currentContext() != ctx)
739 return nullptr;
740
741 QSurface *currentSurface = ctx->surface();
742 if (!currentSurface)
743 return nullptr;
744
745 if (currentSurface->surfaceClass() == QSurface::Window && !currentSurface->surfaceHandle())
746 return nullptr;
747
748 return currentSurface;
749}
750
752{
753 // With Apple's deprecated OpenGL support we need to minimize the usage of
754 // QOffscreenSurface since delicate problems can pop up with
755 // NSOpenGLContext and drawables.
756#if defined(Q_OS_MACOS)
757 return maybeWindow && maybeWindow->handle() ? static_cast<QSurface *>(maybeWindow) : fallbackSurface;
758#else
759 return fallbackSurface;
760#endif
761}
762
763bool QRhiGles2::ensureContext(QSurface *surface) const
764{
765 if (!surface) {
766 // null means any surface is good because not going to render
767
768 // Bail out if the makeCurrent is not necessary - important, given the
769 // frequency this is called at, and the varying implications of ending
770 // up in the EGL/GLX/etc. makeCurrent repeatedly (e.g., leading to,
771 // depending on the platform, unnecessary command stream flushes,
772 // ultimately degrading performance)
773 if (currentSurfaceForCurrentContext(ctx))
774 return true;
775
776 // if the context is not already current with a valid surface, use our
777 // fallback surface, but platform specific quirks may apply
778 surface = evaluateFallbackSurface();
779 } else if (surface->surfaceClass() == QSurface::Window && !surface->surfaceHandle()) {
780 // the window is not usable anymore (no native window underneath), behave as if offscreen
781 surface = evaluateFallbackSurface();
782 } else if (!needsMakeCurrentDueToSwap && currentSurfaceForCurrentContext(ctx) == surface) {
783 // bail out if the makeCurrent is not necessary; same perf. reason as above
784 return true;
785 }
787
788 if (!ctx->makeCurrent(surface)) {
789 if (ctx->isValid()) {
790 qWarning("QRhiGles2: Failed to make context current. Expect bad things to happen.");
791 } else {
792 qWarning("QRhiGles2: Context is lost.");
793 contextLost = true;
794 }
795 return false;
796 }
797
798 return true;
799}
800
801static inline GLenum toGlCompressedTextureFormat(QRhiTexture::Format format, QRhiTexture::Flags flags)
802{
803 const bool srgb = flags.testFlag(QRhiTexture::sRGB);
804 switch (format) {
805 case QRhiTexture::BC1:
806 return srgb ? 0x8C4C : 0x83F0;
807 case QRhiTexture::BC2:
808 return srgb ? 0x8C4E : 0x83F2;
809 case QRhiTexture::BC3:
810 return srgb ? 0x8C4F : 0x83F3;
811
812 case QRhiTexture::ETC2_RGB8:
813 return srgb ? 0x9275 : 0x9274;
814 case QRhiTexture::ETC2_RGB8A1:
815 return srgb ? 0x9277 : 0x9276;
816 case QRhiTexture::ETC2_RGBA8:
817 return srgb ? 0x9279 : 0x9278;
818
819 case QRhiTexture::ASTC_4x4:
820 return srgb ? 0x93D0 : 0x93B0;
821 case QRhiTexture::ASTC_5x4:
822 return srgb ? 0x93D1 : 0x93B1;
823 case QRhiTexture::ASTC_5x5:
824 return srgb ? 0x93D2 : 0x93B2;
825 case QRhiTexture::ASTC_6x5:
826 return srgb ? 0x93D3 : 0x93B3;
827 case QRhiTexture::ASTC_6x6:
828 return srgb ? 0x93D4 : 0x93B4;
829 case QRhiTexture::ASTC_8x5:
830 return srgb ? 0x93D5 : 0x93B5;
831 case QRhiTexture::ASTC_8x6:
832 return srgb ? 0x93D6 : 0x93B6;
833 case QRhiTexture::ASTC_8x8:
834 return srgb ? 0x93D7 : 0x93B7;
835 case QRhiTexture::ASTC_10x5:
836 return srgb ? 0x93D8 : 0x93B8;
837 case QRhiTexture::ASTC_10x6:
838 return srgb ? 0x93D9 : 0x93B9;
839 case QRhiTexture::ASTC_10x8:
840 return srgb ? 0x93DA : 0x93BA;
841 case QRhiTexture::ASTC_10x10:
842 return srgb ? 0x93DB : 0x93BB;
843 case QRhiTexture::ASTC_12x10:
844 return srgb ? 0x93DC : 0x93BC;
845 case QRhiTexture::ASTC_12x12:
846 return srgb ? 0x93DD : 0x93BD;
847
848 default:
849 return 0; // this is reachable, just return an invalid format
850 }
851}
852
853bool QRhiGles2::create(QRhi::Flags flags)
854{
855 Q_ASSERT(fallbackSurface);
856 rhiFlags = flags;
857
858 if (!importedContext) {
859 ctx = new QOpenGLContext;
860 ctx->setFormat(requestedFormat);
861 if (maybeShareContext) {
862 ctx->setShareContext(maybeShareContext);
863 if (maybeWindow)
864 ctx->setScreen(maybeWindow->screen());
865 else
866 ctx->setScreen(maybeShareContext->screen());
867 } else if (QOpenGLContext *shareContext = QOpenGLContext::globalShareContext()) {
868 ctx->setShareContext(shareContext);
869 if (maybeWindow)
870 ctx->setScreen(maybeWindow->screen());
871 else
872 ctx->setScreen(shareContext->screen());
873 } else if (maybeWindow) {
874 ctx->setScreen(maybeWindow->screen());
875 }
876 if (!ctx->create()) {
877 qWarning("QRhiGles2: Failed to create context");
878 delete ctx;
879 ctx = nullptr;
880 return false;
881 }
882 qCDebug(QRHI_LOG_INFO) << "Created OpenGL context" << ctx->format();
883 }
884
885 if (!ensureContext(maybeWindow ? maybeWindow : fallbackSurface)) // see 'window' discussion in QRhiGles2InitParams comments
886 return false;
887
888 f = static_cast<QOpenGLExtensions *>(ctx->extraFunctions());
889 const QSurfaceFormat actualFormat = ctx->format();
890 caps.gles = actualFormat.renderableType() == QSurfaceFormat::OpenGLES;
891
892 if (!caps.gles) {
893 glPolygonMode = reinterpret_cast<void(QOPENGLF_APIENTRYP)(GLenum, GLenum)>(
894 ctx->getProcAddress(QByteArrayLiteral("glPolygonMode")));
895
896 glTexImage1D = reinterpret_cast<void(QOPENGLF_APIENTRYP)(
897 GLenum, GLint, GLint, GLsizei, GLint, GLenum, GLenum, const void *)>(
898 ctx->getProcAddress(QByteArrayLiteral("glTexImage1D")));
899
900 glTexStorage1D = reinterpret_cast<void(QOPENGLF_APIENTRYP)(GLenum, GLint, GLenum, GLsizei)>(
901 ctx->getProcAddress(QByteArrayLiteral("glTexStorage1D")));
902
903 glTexImage2DMultisample = reinterpret_cast<void(QOPENGLF_APIENTRYP)(
904 GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLboolean)>(
905 ctx->getProcAddress(QByteArrayLiteral("glTexImage2DMultisample")));
906
907 glTexSubImage1D = reinterpret_cast<void(QOPENGLF_APIENTRYP)(
908 GLenum, GLint, GLint, GLsizei, GLenum, GLenum, const GLvoid *)>(
909 ctx->getProcAddress(QByteArrayLiteral("glTexSubImage1D")));
910
911 glCopyTexSubImage1D = reinterpret_cast<void(QOPENGLF_APIENTRYP)(GLenum, GLint, GLint, GLint,
912 GLint, GLsizei)>(
913 ctx->getProcAddress(QByteArrayLiteral("glCopyTexSubImage1D")));
914
915 glCompressedTexImage1D = reinterpret_cast<void(QOPENGLF_APIENTRYP)(
916 GLenum, GLint, GLenum, GLsizei, GLint, GLsizei, const GLvoid *)>(
917 ctx->getProcAddress(QByteArrayLiteral("glCompressedTexImage1D")));
918
919 glCompressedTexSubImage1D = reinterpret_cast<void(QOPENGLF_APIENTRYP)(
920 GLenum, GLint, GLint, GLsizei, GLenum, GLsizei, const GLvoid *)>(
921 ctx->getProcAddress(QByteArrayLiteral("glCompressedTexSubImage1D")));
922
924 reinterpret_cast<void(QOPENGLF_APIENTRYP)(GLenum, GLenum, GLenum, GLuint, GLint)>(
925 ctx->getProcAddress(QByteArrayLiteral("glFramebufferTexture1D")));
926 }
927
928 const char *vendor = reinterpret_cast<const char *>(f->glGetString(GL_VENDOR));
929 const char *renderer = reinterpret_cast<const char *>(f->glGetString(GL_RENDERER));
930 const char *version = reinterpret_cast<const char *>(f->glGetString(GL_VERSION));
931 if (vendor && renderer && version)
932 qCDebug(QRHI_LOG_INFO, "OpenGL VENDOR: %s RENDERER: %s VERSION: %s", vendor, renderer, version);
933
934 if (vendor) {
935 driverInfoStruct.deviceName += QByteArray(vendor);
936 driverInfoStruct.deviceName += ' ';
937 }
938 if (renderer) {
939 driverInfoStruct.deviceName += QByteArray(renderer);
940 driverInfoStruct.deviceName += ' ';
941 }
942 if (version)
943 driverInfoStruct.deviceName += QByteArray(version);
944
945 caps.ctxMajor = actualFormat.majorVersion();
946 caps.ctxMinor = actualFormat.minorVersion();
947 if (caps.gles) {
948 // This should check for GL_EXT_blend_func_extended, but support for
949 // that GLES extension is not that common. Also, there is no way to
950 // create GLSL ES shaders via qsb that have the necessary #extension
951 // enable directive. (for non-ES GLSL that is not necessary) So for now
952 // always report false on GLES.
953 caps.dualSourceBlending = false;
954 } else {
955 caps.dualSourceBlending = actualFormat.version() >= qMakePair(3, 3)
956 || ctx->hasExtension("GL_ARB_blend_func_extended");
957 }
958
959 if (caps.gles) {
960 caps.srgbTextureFormat = caps.ctxMajor >= 3 || ctx->hasExtension("GL_EXT_sRGB");
961 caps.srgbGenerateMipmap = caps.ctxMajor >= 3
962 || ctx->hasExtension("GL_NV_generate_mipmap_sRGB");
964 } else {
965 const bool hasCoreSrgbTexture = caps.ctxMajor > 2
966 || (caps.ctxMajor == 2 && caps.ctxMinor >= 1);
967 caps.srgbTextureFormat = hasCoreSrgbTexture
968 || ctx->hasExtension("GL_EXT_texture_sRGB");
970 // Before OpenGL 3.0, framebuffer sRGB extensions do not guarantee
971 // that an sRGB texture attached to an FBO is sRGB-capable.
972 caps.srgbTextureRenderTarget = caps.ctxMajor >= 3;
973 }
974
975 GLint n = 0;
976 f->glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &n);
977 if (n > 0) {
978 QVarLengthArray<GLint, 16> compressedTextureFormats(n);
979 f->glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, compressedTextureFormats.data());
980 for (GLint format : compressedTextureFormats)
981 supportedCompressedFormats.insert(format);
982
983 }
984 // The above looks nice, if only it worked always. With GLES the list we
985 // query is likely the full list of compressed formats (mostly anything
986 // that can be decoded). With OpenGL however the list is not required to
987 // include all formats due to the way the spec is worded. For instance, we
988 // cannot rely on ASTC formats being present in the list on non-ES. Some
989 // drivers do include them (Intel, NVIDIA), some don't (Mesa). On the other
990 // hand, relying on extension strings only is not ok: for example, Intel
991 // reports GL_KHR_texture_compression_astc_ldr whereas NVIDIA doesn't. So
992 // the only reasonable thing to do is to query the list always and then see
993 // if there is something we can add - if not already in there.
994 std::array<QRhiTexture::Flags, 2> textureVariantFlags;
995 textureVariantFlags[0] = {};
996 textureVariantFlags[1] = QRhiTexture::sRGB;
997 if (f->hasOpenGLExtension(QOpenGLExtensions::DDSTextureCompression)) {
998 for (QRhiTexture::Flags f : textureVariantFlags) {
999 supportedCompressedFormats.insert(toGlCompressedTextureFormat(QRhiTexture::BC1, f));
1000 supportedCompressedFormats.insert(toGlCompressedTextureFormat(QRhiTexture::BC2, f));
1001 supportedCompressedFormats.insert(toGlCompressedTextureFormat(QRhiTexture::BC3, f));
1002 }
1003 }
1004 if (f->hasOpenGLExtension(QOpenGLExtensions::ETC2TextureCompression)) {
1005 for (QRhiTexture::Flags f : textureVariantFlags) {
1006 supportedCompressedFormats.insert(toGlCompressedTextureFormat(QRhiTexture::ETC2_RGB8, f));
1007 supportedCompressedFormats.insert(toGlCompressedTextureFormat(QRhiTexture::ETC2_RGB8A1, f));
1008 supportedCompressedFormats.insert(toGlCompressedTextureFormat(QRhiTexture::ETC2_RGBA8, f));
1009 }
1010 }
1011 if (f->hasOpenGLExtension(QOpenGLExtensions::ASTCTextureCompression)) {
1012 for (QRhiTexture::Flags f : textureVariantFlags) {
1013 supportedCompressedFormats.insert(toGlCompressedTextureFormat(QRhiTexture::ASTC_4x4, f));
1014 supportedCompressedFormats.insert(toGlCompressedTextureFormat(QRhiTexture::ASTC_5x4, f));
1015 supportedCompressedFormats.insert(toGlCompressedTextureFormat(QRhiTexture::ASTC_5x5, f));
1016 supportedCompressedFormats.insert(toGlCompressedTextureFormat(QRhiTexture::ASTC_6x5, f));
1017 supportedCompressedFormats.insert(toGlCompressedTextureFormat(QRhiTexture::ASTC_6x6, f));
1018 supportedCompressedFormats.insert(toGlCompressedTextureFormat(QRhiTexture::ASTC_8x5, f));
1019 supportedCompressedFormats.insert(toGlCompressedTextureFormat(QRhiTexture::ASTC_8x6, f));
1020 supportedCompressedFormats.insert(toGlCompressedTextureFormat(QRhiTexture::ASTC_8x8, f));
1021 supportedCompressedFormats.insert(toGlCompressedTextureFormat(QRhiTexture::ASTC_10x5, f));
1022 supportedCompressedFormats.insert(toGlCompressedTextureFormat(QRhiTexture::ASTC_10x8, f));
1023 supportedCompressedFormats.insert(toGlCompressedTextureFormat(QRhiTexture::ASTC_10x10, f));
1024 supportedCompressedFormats.insert(toGlCompressedTextureFormat(QRhiTexture::ASTC_12x10, f));
1025 supportedCompressedFormats.insert(toGlCompressedTextureFormat(QRhiTexture::ASTC_12x12, f));
1026 }
1027 }
1028
1029 f->glGetIntegerv(GL_MAX_TEXTURE_SIZE, &caps.maxTextureSize);
1030
1031 if (!caps.gles || caps.ctxMajor >= 3) {
1032 // non-ES or ES 3.0+
1033 f->glGetIntegerv(GL_MAX_DRAW_BUFFERS, &caps.maxDrawBuffers);
1034 caps.hasDrawBuffersFunc = true;
1035 f->glGetIntegerv(GL_MAX_SAMPLES, &caps.maxSamples);
1036 caps.maxSamples = qMax(1, caps.maxSamples);
1037 } else {
1038 // ES 2.0 / WebGL 1
1039 caps.maxDrawBuffers = 1;
1040 caps.hasDrawBuffersFunc = false;
1041 // This does not mean MSAA is not supported, just that we cannot query
1042 // the supported sample counts. Assume that 4x is always supported.
1043 caps.maxSamples = 4;
1044 }
1045
1046 caps.msaaRenderBuffer = f->hasOpenGLExtension(QOpenGLExtensions::FramebufferMultisample)
1047 && f->hasOpenGLExtension(QOpenGLExtensions::FramebufferBlit);
1048
1049 caps.npotTextureFull = f->hasOpenGLFeature(QOpenGLFunctions::NPOTTextures)
1050 && f->hasOpenGLFeature(QOpenGLFunctions::NPOTTextureRepeat);
1051
1052 if (caps.gles)
1053 caps.fixedIndexPrimitiveRestart = caps.ctxMajor >= 3; // ES 3.0
1054 else
1055 caps.fixedIndexPrimitiveRestart = caps.ctxMajor > 4 || (caps.ctxMajor == 4 && caps.ctxMinor >= 3); // 4.3
1056
1058#ifdef Q_OS_WASM
1059 // WebGL 2 behaves as if GL_PRIMITIVE_RESTART_FIXED_INDEX was always
1060 // enabled (i.e. matching D3D/Metal), and the value cannot be passed to
1061 // glEnable, so skip the call.
1062#else
1064#endif
1065 }
1066
1067 caps.bgraExternalFormat = f->hasOpenGLExtension(QOpenGLExtensions::BGRATextureFormat);
1069 caps.r8Format = f->hasOpenGLFeature(QOpenGLFunctions::TextureRGFormats);
1070
1071 if (caps.gles)
1072 caps.r32uiFormat = (caps.ctxMajor > 3 || (caps.ctxMajor == 3 && caps.ctxMinor >= 1)) && caps.r8Format; // ES 3.1
1073 else
1074 caps.r32uiFormat = true;
1075
1076 if (caps.gles)
1077 caps.imageLoadStore = caps.r32uiFormat;
1078 else
1079 caps.imageLoadStore = (caps.ctxMajor > 4 || (caps.ctxMajor == 4 && caps.ctxMinor >= 2));
1080
1081 caps.r16Format = f->hasOpenGLExtension(QOpenGLExtensions::Sized16Formats);
1082 caps.floatFormats = caps.ctxMajor >= 3; // 3.0 or ES 3.0
1083 caps.rgb10Formats = caps.ctxMajor >= 3; // 3.0 or ES 3.0
1084 caps.depthTexture = caps.ctxMajor >= 3; // 3.0 or ES 3.0
1085 caps.packedDepthStencil = f->hasOpenGLExtension(QOpenGLExtensions::PackedDepthStencil);
1086#ifdef Q_OS_WASM
1087 caps.needsDepthStencilCombinedAttach = true;
1088#else
1090#endif
1091
1092 // QOpenGLExtensions::SRGBFrameBuffer is not useful here. We need to know if
1093 // controlling the sRGB-on-shader-write state is supported, not that if the
1094 // default framebuffer is sRGB-capable. And there are two different
1095 // extensions for desktop and ES.
1096 if (caps.gles) {
1097 caps.srgbWriteControl = ctx->hasExtension("GL_EXT_sRGB_write_control");
1098 } else {
1099 const bool hasCoreSrgbWriteControl = caps.ctxMajor >= 3;
1100 caps.srgbWriteControl = hasCoreSrgbWriteControl
1101 || ctx->hasExtension("GL_ARB_framebuffer_sRGB")
1102 || ctx->hasExtension("GL_EXT_framebuffer_sRGB");
1103 }
1104
1105 caps.coreProfile = actualFormat.profile() == QSurfaceFormat::CoreProfile;
1106
1107 // Core profile has no usable default vertex array object. On OpenGL ES
1108 // object 0 works for ordinary draws, but the indirect draw commands are
1109 // specified to fail with INVALID_OPERATION unless a non-zero one is bound.
1110 caps.vertexArrayObject = caps.coreProfile || (caps.gles && caps.ctxMajor >= 3); // ES 3.0
1111
1112 if (caps.gles)
1113 caps.uniformBuffers = caps.ctxMajor >= 3; // ES 3.0
1114 else
1115 caps.uniformBuffers = caps.ctxMajor > 3 || (caps.ctxMajor == 3 && caps.ctxMinor >= 1); // 3.1
1116
1117 caps.elementIndexUint = f->hasOpenGLExtension(QOpenGLExtensions::ElementIndexUint);
1118 caps.depth24 = !caps.gles || f->hasOpenGLExtension(QOpenGLExtensions::Depth24);
1119 caps.rgba8Format = f->hasOpenGLExtension(QOpenGLExtensions::Sized8Formats);
1120
1121 if (caps.gles)
1122 caps.instancing = caps.ctxMajor >= 3; // ES 3.0
1123 else
1124 caps.instancing = caps.ctxMajor > 3 || (caps.ctxMajor == 3 && caps.ctxMinor >= 3); // 3.3
1125
1126 caps.baseVertex = caps.ctxMajor > 3 || (caps.ctxMajor == 3 && caps.ctxMinor >= 2); // 3.2 or ES 3.2
1127
1128 if (caps.gles)
1129 caps.compute = caps.ctxMajor > 3 || (caps.ctxMajor == 3 && caps.ctxMinor >= 1); // ES 3.1
1130 else
1131 caps.compute = caps.ctxMajor > 4 || (caps.ctxMajor == 4 && caps.ctxMinor >= 3); // 4.3
1132
1133 if (caps.compute) {
1134 GLint ssboBindings = 0;
1135 f->glGetIntegerv(GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS, &ssboBindings);
1136 GLint blocks = 0;
1137 f->glGetIntegerv(GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS, &blocks);
1138 caps.maxVertexStorageBuffers = qMin(blocks, ssboBindings);
1139 blocks = 0;
1140 f->glGetIntegerv(GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS, &blocks);
1141 caps.maxFragmentStorageBuffers = qMin(blocks, ssboBindings);
1142 caps.maxStorageBufferBindings = ssboBindings;
1143 f->glGetIntegerv(GL_MAX_IMAGE_UNITS, &caps.maxStorageImageBindings);
1145 GLint tgPerDim[3];
1146 f->glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_COUNT, 0, &tgPerDim[0]);
1147 f->glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_COUNT, 1, &tgPerDim[1]);
1148 f->glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_COUNT, 2, &tgPerDim[2]);
1149 caps.maxThreadGroupsPerDimension = qMin(tgPerDim[0], qMin(tgPerDim[1], tgPerDim[2]));
1150 f->glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_SIZE, 0, &caps.maxThreadGroupsX);
1151 f->glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_SIZE, 1, &caps.maxThreadGroupsY);
1152 f->glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_SIZE, 2, &caps.maxThreadGroupsZ);
1153 }
1154
1155 if (caps.gles)
1156 caps.depthClamp = false;
1157 else
1158 caps.depthClamp = caps.ctxMajor > 3 || (caps.ctxMajor == 3 && caps.ctxMinor >= 2); // Desktop 3.2
1159 if (!caps.depthClamp)
1160 caps.depthClamp = ctx->hasExtension("GL_EXT_depth_clamp") || ctx->hasExtension("GL_ARB_depth_clamp");
1161
1162 if (caps.gles)
1163 caps.textureCompareMode = caps.ctxMajor >= 3; // ES 3.0
1164 else
1165 caps.textureCompareMode = true;
1166
1167 // proper as in ES 3.0 (glMapBufferRange), not the old glMapBuffer
1168 // extension(s) (which is not in ES 3.0...messy)
1169 caps.properMapBuffer = f->hasOpenGLExtension(QOpenGLExtensions::MapBufferRange);
1170
1171 if (caps.gles)
1172 caps.nonBaseLevelFramebufferTexture = caps.ctxMajor >= 3; // ES 3.0
1173 else
1175
1176 caps.texelFetch = caps.ctxMajor >= 3; // 3.0 or ES 3.0
1177 caps.intAttributes = caps.ctxMajor >= 3; // 3.0 or ES 3.0
1178 caps.screenSpaceDerivatives = f->hasOpenGLExtension(QOpenGLExtensions::StandardDerivatives);
1179
1180 if (caps.gles) {
1181 caps.multisampledTexture = caps.ctxMajor > 3 || (caps.ctxMajor == 3 && caps.ctxMinor >= 1); // ES 3.1
1183 } else {
1185 && (caps.ctxMajor > 3 || (caps.ctxMajor == 3 && caps.ctxMinor >= 2)); // 3.2
1187 || (caps.ctxMajor == 4 && caps.ctxMinor >= 3); // 4.3
1188 }
1189
1190 // Program binary support: only the core stuff, do not bother with the old
1191 // extensions like GL_OES_get_program_binary
1192 if (caps.gles)
1193 caps.programBinary = caps.ctxMajor >= 3; // ES 3.0
1194 else
1195 caps.programBinary = caps.ctxMajor > 4 || (caps.ctxMajor == 4 && caps.ctxMinor >= 1); // 4.1
1196
1197 if (caps.programBinary) {
1198 GLint fmtCount = 0;
1199 f->glGetIntegerv(GL_NUM_PROGRAM_BINARY_FORMATS, &fmtCount);
1200 if (fmtCount < 1)
1201 caps.programBinary = false;
1202 }
1203
1204 caps.texture3D = caps.ctxMajor >= 3; // 3.0
1205
1206 // Immutable texture storage. Needed to be able to allocate all mip levels
1207 // of a compressed texture without having data at hand.
1208 if (caps.gles)
1209 caps.textureStorage = caps.ctxMajor >= 3; // ES 3.0
1210 else
1211 caps.textureStorage = caps.ctxMajor > 4 || (caps.ctxMajor == 4 && caps.ctxMinor >= 2) // 4.2
1212 || ctx->hasExtension(QByteArrayLiteral("GL_ARB_texture_storage"));
1213
1214 if (caps.gles)
1215 caps.texture1D = false; // ES
1216 else
1217 caps.texture1D = glTexImage1D && (caps.ctxMajor >= 2); // 2.0
1218
1219 if (caps.gles)
1220 caps.tessellation = caps.ctxMajor > 3 || (caps.ctxMajor == 3 && caps.ctxMinor >= 2); // ES 3.2
1221 else
1222 caps.tessellation = caps.ctxMajor >= 4; // 4.0
1223
1224 if (caps.gles)
1225 caps.geometryShader = caps.ctxMajor > 3 || (caps.ctxMajor == 3 && caps.ctxMinor >= 2); // ES 3.2
1226 else
1227 caps.geometryShader = caps.ctxMajor > 3 || (caps.ctxMajor == 3 && caps.ctxMinor >= 2); // 3.2
1228
1229 if (caps.ctxMajor >= 3) { // 3.0 or ES 3.0
1230 GLint maxArraySize = 0;
1231 f->glGetIntegerv(GL_MAX_ARRAY_TEXTURE_LAYERS, &maxArraySize);
1232 caps.maxTextureArraySize = maxArraySize;
1233 } else {
1234 caps.maxTextureArraySize = 0;
1235 }
1236
1237 // The ES 2.0 spec only has MAX_xxxx_VECTORS. ES 3.0 and up has both
1238 // *VECTORS and *COMPONENTS. OpenGL 2.0-4.0 only has MAX_xxxx_COMPONENTS.
1239 // 4.1 and above has both. What a mess.
1240 if (caps.gles) {
1241 GLint maxVertexUniformVectors = 0;
1242 f->glGetIntegerv(GL_MAX_VERTEX_UNIFORM_VECTORS, &maxVertexUniformVectors);
1243 GLint maxFragmentUniformVectors = 0;
1244 f->glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_VECTORS, &maxFragmentUniformVectors);
1245 caps.maxUniformVectors = qMin(maxVertexUniformVectors, maxFragmentUniformVectors);
1246 } else {
1247 GLint maxVertexUniformComponents = 0;
1248 f->glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS, &maxVertexUniformComponents);
1249 GLint maxFragmentUniformComponents = 0;
1250 f->glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, &maxFragmentUniformComponents);
1251 caps.maxUniformVectors = qMin(maxVertexUniformComponents, maxFragmentUniformComponents) / 4;
1252 }
1253
1254 f->glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &caps.maxVertexInputs);
1255
1256 if (caps.gles) {
1257 f->glGetIntegerv(GL_MAX_VARYING_VECTORS, &caps.maxVertexOutputs);
1258 } else if (caps.ctxMajor >= 3) {
1259 GLint components = 0;
1260 f->glGetIntegerv(caps.coreProfile ? GL_MAX_VERTEX_OUTPUT_COMPONENTS : GL_MAX_VARYING_COMPONENTS, &components);
1261 caps.maxVertexOutputs = components / 4;
1262 } else {
1263 // OpenGL before 3.0 only has this, and not the same as
1264 // MAX_VARYING_COMPONENTS strictly speaking, but will do.
1265 GLint components = 0;
1266 f->glGetIntegerv(GL_MAX_VARYING_FLOATS, &components);
1267 if (components > 0)
1268 caps.maxVertexOutputs = components / 4;
1269 }
1270
1271 if (!caps.gles) {
1273 if (!caps.coreProfile)
1274 f->glEnable(GL_POINT_SPRITE);
1275 } // else (with gles) these are always on
1276
1277 // Match D3D and others when it comes to seamless cubemap filtering.
1278 // ES 3.0+ has this always enabled. (hopefully)
1279 // ES 2.0 and GL < 3.2 will not have it.
1280 if (!caps.gles && (caps.ctxMajor > 3 || (caps.ctxMajor == 3 && caps.ctxMinor >= 2)))
1282
1283 caps.halfAttributes = f->hasOpenGLExtension(QOpenGLExtensions::HalfFloatVertex);
1284
1285 // We always require GL_OVR_multiview2 for symmetry with other backends.
1286 caps.multiView = f->hasOpenGLExtension(QOpenGLExtensions::MultiView)
1287 && f->hasOpenGLExtension(QOpenGLExtensions::MultiViewExtended);
1288 if (caps.multiView) {
1290 reinterpret_cast<void(QOPENGLF_APIENTRYP)(GLenum, GLenum, GLuint, GLint, GLint, GLsizei)>(
1291 ctx->getProcAddress(QByteArrayLiteral("glFramebufferTextureMultiviewOVR")));
1292 }
1293
1294 // Only do timestamp queries on OpenGL 3.3+.
1295 caps.timestamps = !caps.gles && (caps.ctxMajor > 3 || (caps.ctxMajor == 3 && caps.ctxMinor >= 3));
1296 if (caps.timestamps) {
1297 glQueryCounter = reinterpret_cast<void(QOPENGLF_APIENTRYP)(GLuint, GLenum)>(
1298 ctx->getProcAddress(QByteArrayLiteral("glQueryCounter")));
1299 glGetQueryObjectui64v = reinterpret_cast<void(QOPENGLF_APIENTRYP)(GLuint, GLenum, quint64 *)>(
1300 ctx->getProcAddress(QByteArrayLiteral("glGetQueryObjectui64v")));
1302 caps.timestamps = false;
1303 }
1304
1305 // glObjectLabel is available on OpenGL ES 3.2+ and OpenGL 4.3+
1306 if (caps.gles)
1307 caps.objectLabel = caps.ctxMajor > 3 || (caps.ctxMajor == 3 && caps.ctxMinor >= 2);
1308 else
1309 caps.objectLabel = caps.ctxMajor > 4 || (caps.ctxMajor == 4 && caps.ctxMinor >= 3);
1310 if (caps.objectLabel) {
1311 glObjectLabel = reinterpret_cast<void(QOPENGLF_APIENTRYP)(GLenum, GLuint, GLsizei, const GLchar *)>(
1312 ctx->getProcAddress(QByteArrayLiteral("glObjectLabel")));
1313 }
1314
1315 if (caps.gles) {
1316 // This is the third way to get multisample rendering with GLES. (1. is
1317 // multisample render buffer -> resolve to texture; 2. is multisample
1318 // texture with GLES 3.1; 3. is this, avoiding the explicit multisample
1319 // buffer and should be more efficient with tiled architectures.
1320 // Interesting also because 2. does not seem to work in practice on
1321 // devices such as the Quest 3)
1322 caps.glesMultisampleRenderToTexture = ctx->hasExtension("GL_EXT_multisampled_render_to_texture");
1324 glFramebufferTexture2DMultisampleEXT = reinterpret_cast<void(QOPENGLF_APIENTRYP)(GLenum, GLenum, GLenum, GLuint, GLint, GLsizei)>(
1325 ctx->getProcAddress(QByteArrayLiteral("glFramebufferTexture2DMultisampleEXT")));
1326 glRenderbufferStorageMultisampleEXT = reinterpret_cast<void(QOPENGLF_APIENTRYP)(GLenum, GLsizei, GLenum, GLsizei, GLsizei)>(
1327 ctx->getProcAddress(QByteArrayLiteral("glRenderbufferStorageMultisampleEXT")));
1328 }
1329 caps.glesMultiviewMultisampleRenderToTexture = ctx->hasExtension("GL_OVR_multiview_multisampled_render_to_texture");
1331 glFramebufferTextureMultisampleMultiviewOVR = reinterpret_cast<void(QOPENGLF_APIENTRYP)(GLenum, GLenum, GLuint, GLint, GLsizei, GLint, GLsizei)>(
1332 ctx->getProcAddress(QByteArrayLiteral("glFramebufferTextureMultisampleMultiviewOVR")));
1333 }
1334 } else {
1337 }
1338
1339 caps.unpackRowLength = !caps.gles || caps.ctxMajor >= 3;
1340
1341 if (caps.gles)
1342 caps.perRenderTargetBlending = caps.ctxMajor > 3 || (caps.ctxMajor == 3 && caps.ctxMinor >= 2);
1343 else
1344 caps.perRenderTargetBlending = caps.ctxMajor >= 4;
1345
1346 if (caps.gles) {
1347 if (caps.ctxMajor == 3 && caps.ctxMinor < 2) {
1348 caps.sampleVariables = ctx->hasExtension("GL_OES_sample_variables");
1349 } else {
1350 caps.sampleVariables = caps.ctxMajor > 3 || (caps.ctxMajor == 3 && caps.ctxMinor >= 2);
1351 }
1352 } else {
1353 caps.sampleVariables = caps.ctxMajor >= 4;
1354 }
1355
1356 if (caps.gles)
1357 caps.drawIndirect = caps.ctxMajor > 3 || (caps.ctxMajor == 3 && caps.ctxMinor >= 1);
1358 else
1359 caps.drawIndirect = caps.ctxMajor >= 4;
1360 if (ctx->hasExtension(QByteArrayLiteral("GL_ARB_draw_indirect")))
1361 caps.drawIndirect = true;
1362
1363 // glDraw*BaseInstance: core in 4.2+, ARB on older desktop. Not enabled on
1364 // GLES even when GL_EXT_base_instance is present, for lack of testing.
1365 // Requires instancing as well: the ARB extension can be advertised on
1366 // contexts below 3.3, where the instanced draw path, including the
1367 // attribute divisors, is not taken at all.
1368 if (caps.gles) {
1369 caps.baseInstance = false;
1370 } else {
1371 caps.baseInstance = caps.instancing
1372 && (caps.ctxMajor > 4 || (caps.ctxMajor == 4 && caps.ctxMinor >= 2)
1373 || ctx->hasExtension(QByteArrayLiteral("GL_ARB_base_instance")));
1374 }
1375
1376 if (caps.baseInstance) {
1377 glDrawArraysInstancedBaseInstance = reinterpret_cast<decltype(glDrawArraysInstancedBaseInstance)>(
1378 ctx->getProcAddress(QByteArrayLiteral("glDrawArraysInstancedBaseInstance")));
1379 glDrawElementsInstancedBaseInstance = reinterpret_cast<decltype(glDrawElementsInstancedBaseInstance)>(
1380 ctx->getProcAddress(QByteArrayLiteral("glDrawElementsInstancedBaseInstance")));
1381 glDrawElementsInstancedBaseVertexBaseInstance = reinterpret_cast<decltype(glDrawElementsInstancedBaseVertexBaseInstance)>(
1382 ctx->getProcAddress(QByteArrayLiteral("glDrawElementsInstancedBaseVertexBaseInstance")));
1386 qWarning("Failed to resolve glDraw{Arrays,Elements}InstancedBaseInstance{,BaseVertex}; disabling base instance support.");
1387 caps.baseInstance = false;
1388 }
1389 }
1390
1391 if (caps.gles)
1392 caps.drawIndirectMulti = false;
1393 else
1394 caps.drawIndirectMulti = caps.ctxMajor > 4 || (caps.ctxMajor == 4 && caps.ctxMinor >= 3);
1395 if (ctx->hasExtension(QByteArrayLiteral("GL_ARB_multi_draw_indirect")) ||
1396 ctx->hasExtension(QByteArrayLiteral("GL_EXT_multi_draw_indirect")))
1397 caps.drawIndirectMulti = true;
1398
1399 if (caps.drawIndirectMulti) {
1400 glMultiDrawArraysIndirect = reinterpret_cast<decltype(glMultiDrawArraysIndirect)>(
1401 ctx->getProcAddress(QByteArrayLiteral("glMultiDrawArraysIndirect")));
1403 glMultiDrawArraysIndirect = reinterpret_cast<decltype(glMultiDrawArraysIndirect)>(
1404 ctx->getProcAddress(QByteArrayLiteral("glMultiDrawArraysIndirectARB")));
1406 glMultiDrawArraysIndirect = reinterpret_cast<decltype(glMultiDrawArraysIndirect)>(
1407 ctx->getProcAddress(QByteArrayLiteral("glMultiDrawArraysIndirectEXT")));
1408 glMultiDrawElementsIndirect = reinterpret_cast<decltype(glMultiDrawElementsIndirect)>(
1409 ctx->getProcAddress(QByteArrayLiteral("glMultiDrawElementsIndirect")));
1411 glMultiDrawElementsIndirect = reinterpret_cast<decltype(glMultiDrawElementsIndirect)>(
1412 ctx->getProcAddress(QByteArrayLiteral("glMultiDrawElementsIndirectARB")));
1414 glMultiDrawElementsIndirect = reinterpret_cast<decltype(glMultiDrawElementsIndirect)>(
1415 ctx->getProcAddress(QByteArrayLiteral("glMultiDrawElementsIndirectEXT")));
1417 qWarning("Failed to resolve glMultiDrawArraysIndirect or glMultiDrawElementsIndirect.");
1418 caps.drawIndirectMulti = false;
1419 }
1420 }
1421
1422 if (caps.gles)
1423 caps.shaderDrawParameters = false;
1424 else
1425 caps.shaderDrawParameters = caps.ctxMajor > 4 || (caps.ctxMajor == 4 && caps.ctxMinor >= 6);
1426 if (ctx->hasExtension(QByteArrayLiteral("GL_ARB_shader_draw_parameters")))
1427 caps.shaderDrawParameters = true;
1428 // glDispatchComputeIndirect was introduced together with the compute
1429 // pipeline in OpenGL 4.3 and OpenGL ES 3.1, so its availability matches
1430 // caps.compute. The function pointer is exposed by QOpenGLExtraFunctions.
1431 caps.dispatchIndirect = caps.compute;
1432
1433 // glCopyBufferSubData is core in OpenGL 3.1 and OpenGL ES 3.0, and is
1434 // available via GL_ARB_copy_buffer on older desktop versions. Either way
1435 // the function pointer is exposed by QOpenGLExtraFunctions, but only when
1436 // it can actually be resolved.
1437 if (caps.gles)
1438 caps.copyBuffer = caps.ctxMajor >= 3;
1439 else
1440 caps.copyBuffer = caps.ctxMajor > 3 || (caps.ctxMajor == 3 && caps.ctxMinor >= 1);
1441 if (!caps.copyBuffer && ctx->hasExtension(QByteArrayLiteral("GL_ARB_copy_buffer")))
1442 caps.copyBuffer = ctx->getProcAddress(QByteArrayLiteral("glCopyBufferSubData")) != nullptr;
1443
1444 if (!caps.gles
1445 && (caps.ctxMajor > 4 || (caps.ctxMajor == 4 && caps.ctxMinor >= 3)
1446 || ctx->hasExtension(QByteArrayLiteral("GL_ARB_clear_buffer_object"))))
1447 {
1448 glClearBufferSubData = reinterpret_cast<void(QOPENGLF_APIENTRYP)(GLenum, GLenum, GLintptr, GLsizeiptr,
1449 GLenum, GLenum, const void *)>(
1450 ctx->getProcAddress(QByteArrayLiteral("glClearBufferSubData")));
1451 caps.clearBuffer = glClearBufferSubData != nullptr;
1452 }
1453 if (qEnvironmentVariableIntValue("QT_GL_NO_CLEAR_BUFFER_SUBDATA"))
1454 caps.clearBuffer = false;
1455
1456 // glMultiDraw*IndirectCount: core in 4.6, ARB on older desktop.
1457 // No counterpart in OpenGL ES.
1458 if (caps.gles)
1459 caps.drawIndirectCount = false;
1460 else
1461 caps.drawIndirectCount = caps.ctxMajor > 4 || (caps.ctxMajor == 4 && caps.ctxMinor >= 6);
1462 if (ctx->hasExtension(QByteArrayLiteral("GL_ARB_indirect_parameters")))
1463 caps.drawIndirectCount = true;
1464
1465 if (caps.drawIndirectCount) {
1466 glMultiDrawArraysIndirectCount = reinterpret_cast<decltype(glMultiDrawArraysIndirectCount)>(
1467 ctx->getProcAddress(QByteArrayLiteral("glMultiDrawArraysIndirectCount")));
1469 glMultiDrawArraysIndirectCount = reinterpret_cast<decltype(glMultiDrawArraysIndirectCount)>(
1470 ctx->getProcAddress(QByteArrayLiteral("glMultiDrawArraysIndirectCountARB")));
1471 glMultiDrawElementsIndirectCount = reinterpret_cast<decltype(glMultiDrawElementsIndirectCount)>(
1472 ctx->getProcAddress(QByteArrayLiteral("glMultiDrawElementsIndirectCount")));
1474 glMultiDrawElementsIndirectCount = reinterpret_cast<decltype(glMultiDrawElementsIndirectCount)>(
1475 ctx->getProcAddress(QByteArrayLiteral("glMultiDrawElementsIndirectCountARB")));
1477 qWarning("Failed to resolve glMultiDrawArraysIndirectCount or glMultiDrawElementsIndirectCount.");
1478 caps.drawIndirectCount = false;
1479 }
1480 }
1481
1482 // glMemoryBarrierByRegion: ES 3.1 or 4.5
1483 if (caps.gles)
1485 else
1486 caps.memoryBarrierByRegion = caps.ctxMajor > 4 || (caps.ctxMajor == 4 && caps.ctxMinor >= 5);
1487
1488 nativeHandlesStruct.context = ctx;
1489
1490 contextLost = false;
1491
1492 return true;
1493}
1494
1496{
1497 if (!f)
1498 return;
1499
1500 if (ensureContext()) {
1502
1503 if (ofr.tsQueries[0]) {
1504 f->glDeleteQueries(2, ofr.tsQueries);
1505 ofr.tsQueries[0] = ofr.tsQueries[1] = 0;
1506 }
1507
1508 if (vao) {
1509 f->glDeleteVertexArrays(1, &vao);
1510 vao = 0;
1511 }
1512
1513 for (uint shader : std::as_const(m_shaderCache))
1514 f->glDeleteShader(shader);
1515 m_shaderCache.clear();
1516
1517 if (clearBufferProgram)
1518 f->glDeleteProgram(clearBufferProgram);
1519
1521 }
1522 clearBufferProgram = 0;
1524 bufferNameCacheCount = 0; // clear even when the context is lost
1525
1526 if (!importedContext) {
1527 delete ctx;
1528 ctx = nullptr;
1529 }
1530
1531 f = nullptr;
1532}
1533
1535{
1536 if (!bufferNameCacheCount) {
1537 bufferNameCache.fill(0);
1538 f->glGenBuffers(GLsizei(bufferNameCache.size()), bufferNameCache.data());
1539 bufferNameCacheCount = int(bufferNameCache.size());
1540 }
1541 return bufferNameCache[--bufferNameCacheCount];
1542}
1543
1545{
1547 f->glDeleteBuffers(GLsizei(bufferNameCacheCount), bufferNameCache.data());
1549 }
1550}
1551
1553{
1554 for (int i = releaseQueue.size() - 1; i >= 0; --i) {
1555 const QRhiGles2::DeferredReleaseEntry &e(releaseQueue[i]);
1556 switch (e.type) {
1558 f->glDeleteBuffers(1, &e.buffer.buffer);
1559 break;
1561 f->glDeleteProgram(e.pipeline.program);
1562 break;
1564 f->glDeleteTextures(1, &e.texture.texture);
1565 break;
1567 f->glDeleteRenderbuffers(1, &e.renderbuffer.renderbuffer);
1568 f->glDeleteRenderbuffers(1, &e.renderbuffer.renderbuffer2);
1569 break;
1571 f->glDeleteFramebuffers(1, &e.textureRenderTarget.framebuffer);
1572 f->glDeleteTextures(1, &e.textureRenderTarget.nonMsaaThrowawayDepthTexture);
1573 break;
1574 default:
1575 Q_UNREACHABLE();
1576 break;
1577 }
1578 releaseQueue.removeAt(i);
1579 }
1580}
1581
1583{
1584 if (supportedSampleCountList.isEmpty()) {
1585 // 1, 2, 4, 8, ...
1586 for (int i = 1; i <= caps.maxSamples; i *= 2)
1587 supportedSampleCountList.append(i);
1588 }
1589 return supportedSampleCountList;
1590}
1591
1593{
1594 Q_UNUSED(sampleCount);
1595 return { QSize(1, 1) };
1596}
1597
1599{
1600 return new QGles2SwapChain(this);
1601}
1602
1603QRhiBuffer *QRhiGles2::createBuffer(QRhiBuffer::Type type, QRhiBuffer::UsageFlags usage, quint32 size)
1604{
1605 return new QGles2Buffer(this, type, usage, size);
1606}
1607
1609{
1610 // No real uniform buffers are used so no need to pretend there is any
1611 // alignment requirement.
1612 return 1;
1613}
1614
1616{
1617 return true;
1618}
1619
1621{
1622 return true;
1623}
1624
1626{
1627 return false;
1628}
1629
1631{
1632 return QMatrix4x4(); // identity
1633}
1634
1635static inline void toGlTextureFormat(QRhiTexture::Format format, QRhiTexture::Flags flags,
1636 const QRhiGles2::Caps &caps,
1637 GLenum *glintformat, GLenum *glsizedintformat,
1638 GLenum *glformat, GLenum *gltype)
1639{
1640 const bool srgb = flags.testFlag(QRhiTexture::sRGB);
1641 const bool legacyGlesSrgb = srgb && caps.gles && caps.ctxMajor < 3;
1642 switch (format) {
1643 case QRhiTexture::RGBA8:
1644 *glintformat = srgb ? (legacyGlesSrgb ? GL_SRGB_ALPHA : GL_SRGB8_ALPHA8) : GL_RGBA;
1645 *glsizedintformat = srgb ? GL_SRGB8_ALPHA8 : (caps.rgba8Format ? GL_RGBA8 : GL_RGBA);
1646 *glformat = legacyGlesSrgb ? GL_SRGB_ALPHA : GL_RGBA;
1647 *gltype = GL_UNSIGNED_BYTE;
1648 break;
1649 case QRhiTexture::BGRA8:
1650 *glintformat = srgb ? GL_SRGB8_ALPHA8 : (caps.bgraInternalFormat ? GL_BGRA : GL_RGBA);
1651 *glsizedintformat = srgb ? GL_SRGB8_ALPHA8 : (caps.rgba8Format ? GL_RGBA8 : GL_RGBA);
1652 *glformat = GL_BGRA;
1653 *gltype = GL_UNSIGNED_BYTE;
1654 break;
1655 case QRhiTexture::R16:
1656 *glintformat = GL_R16;
1657 *glsizedintformat = *glintformat;
1658 *glformat = GL_RED;
1659 *gltype = GL_UNSIGNED_SHORT;
1660 break;
1661 case QRhiTexture::RG16:
1662 *glintformat = GL_RG16;
1663 *glsizedintformat = *glintformat;
1664 *glformat = GL_RG;
1665 *gltype = GL_UNSIGNED_SHORT;
1666 break;
1667 case QRhiTexture::R8:
1668 // GL_EXT_texture_rg on ES 2.0 only accepts unsized GL_RED here; same split as RGBA8 above.
1669 *glintformat = caps.gles && caps.ctxMajor < 3 ? GL_RED : GL_R8;
1670 *glsizedintformat = GL_R8;
1671 *glformat = GL_RED;
1672 *gltype = GL_UNSIGNED_BYTE;
1673 break;
1674 case QRhiTexture::R8SI:
1675 *glintformat = GL_R8I;
1676 *glsizedintformat = *glintformat;
1677 *glformat = GL_RED_INTEGER;
1678 *gltype = GL_BYTE;
1679 break;
1680 case QRhiTexture::R8UI:
1681 *glintformat = GL_R8UI;
1682 *glsizedintformat = *glintformat;
1683 *glformat = GL_RED_INTEGER;
1684 *gltype = GL_UNSIGNED_BYTE;
1685 break;
1686 case QRhiTexture::RG8:
1687 *glintformat = caps.gles && caps.ctxMajor < 3 ? GL_RG : GL_RG8;
1688 *glsizedintformat = GL_RG8;
1689 *glformat = GL_RG;
1690 *gltype = GL_UNSIGNED_BYTE;
1691 break;
1692 case QRhiTexture::RED_OR_ALPHA8:
1693 *glintformat = caps.coreProfile ? GL_R8 : GL_ALPHA;
1694 *glsizedintformat = *glintformat;
1695 *glformat = caps.coreProfile ? GL_RED : GL_ALPHA;
1696 *gltype = GL_UNSIGNED_BYTE;
1697 break;
1698 case QRhiTexture::RGBA16F:
1699 *glintformat = GL_RGBA16F;
1700 *glsizedintformat = *glintformat;
1701 *glformat = GL_RGBA;
1702 *gltype = GL_HALF_FLOAT;
1703 break;
1704 case QRhiTexture::RGBA32F:
1705 *glintformat = GL_RGBA32F;
1706 *glsizedintformat = *glintformat;
1707 *glformat = GL_RGBA;
1708 *gltype = GL_FLOAT;
1709 break;
1710 case QRhiTexture::R16F:
1711 *glintformat = GL_R16F;
1712 *glsizedintformat = *glintformat;
1713 *glformat = GL_RED;
1714 *gltype = GL_HALF_FLOAT;
1715 break;
1716 case QRhiTexture::R32F:
1717 *glintformat = GL_R32F;
1718 *glsizedintformat = *glintformat;
1719 *glformat = GL_RED;
1720 *gltype = GL_FLOAT;
1721 break;
1722 case QRhiTexture::RGB10A2:
1723 *glintformat = GL_RGB10_A2;
1724 *glsizedintformat = *glintformat;
1725 *glformat = GL_RGBA;
1727 break;
1728 case QRhiTexture::R32SI:
1729 *glintformat = GL_R32I;
1730 *glsizedintformat = *glintformat;
1731 *glformat = GL_RED_INTEGER;
1732 *gltype = GL_INT;
1733 break;
1734 case QRhiTexture::R32UI:
1735 *glintformat = GL_R32UI;
1736 *glsizedintformat = *glintformat;
1737 *glformat = GL_RED_INTEGER;
1738 *gltype = GL_UNSIGNED_INT;
1739 break;
1740 case QRhiTexture::RG32SI:
1741 *glintformat = GL_RG32I;
1742 *glsizedintformat = *glintformat;
1743 *glformat = GL_RG_INTEGER;
1744 *gltype = GL_INT;
1745 break;
1746 case QRhiTexture::RG32UI:
1747 *glintformat = GL_RG32UI;
1748 *glsizedintformat = *glintformat;
1749 *glformat = GL_RG_INTEGER;
1750 *gltype = GL_UNSIGNED_INT;
1751 break;
1752 case QRhiTexture::RGBA32SI:
1753 *glintformat = GL_RGBA32I;
1754 *glsizedintformat = *glintformat;
1755 *glformat = GL_RGBA_INTEGER;
1756 *gltype = GL_INT;
1757 break;
1758 case QRhiTexture::RGBA32UI:
1759 *glintformat = GL_RGBA32UI;
1760 *glsizedintformat = *glintformat;
1761 *glformat = GL_RGBA_INTEGER;
1762 *gltype = GL_UNSIGNED_INT;
1763 break;
1764 case QRhiTexture::D16:
1765 *glintformat = GL_DEPTH_COMPONENT16;
1766 *glsizedintformat = *glintformat;
1767 *glformat = GL_DEPTH_COMPONENT;
1768 *gltype = GL_UNSIGNED_SHORT;
1769 break;
1770 case QRhiTexture::D24:
1771 *glintformat = GL_DEPTH_COMPONENT24;
1772 *glsizedintformat = *glintformat;
1773 *glformat = GL_DEPTH_COMPONENT;
1774 *gltype = GL_UNSIGNED_INT;
1775 break;
1776 case QRhiTexture::D24S8:
1777 *glintformat = GL_DEPTH24_STENCIL8;
1778 *glsizedintformat = *glintformat;
1779 *glformat = GL_DEPTH_STENCIL;
1780 *gltype = GL_UNSIGNED_INT_24_8;
1781 break;
1782 case QRhiTexture::D32F:
1783 *glintformat = GL_DEPTH_COMPONENT32F;
1784 *glsizedintformat = *glintformat;
1785 *glformat = GL_DEPTH_COMPONENT;
1786 *gltype = GL_FLOAT;
1787 break;
1788 case QRhiTexture::D32FS8:
1789 *glintformat = GL_DEPTH32F_STENCIL8;
1790 *glsizedintformat = *glintformat;
1791 *glformat = GL_DEPTH_STENCIL;
1793 break;
1794 default:
1795 Q_UNREACHABLE();
1796 *glintformat = GL_RGBA;
1797 *glsizedintformat = caps.rgba8Format ? GL_RGBA8 : GL_RGBA;
1798 *glformat = GL_RGBA;
1799 *gltype = GL_UNSIGNED_BYTE;
1800 break;
1801 }
1802}
1803
1804static inline bool isDepthTextureFormat(QRhiTexture::Format format)
1805{
1806 switch (format) {
1807 case QRhiTexture::D16:
1808 case QRhiTexture::D24:
1809 case QRhiTexture::D24S8:
1810 case QRhiTexture::D32F:
1811 case QRhiTexture::D32FS8:
1812 return true;
1813 default:
1814 return false;
1815 }
1816}
1817
1818bool QRhiGles2::isTextureFormatSupported(QRhiTexture::Format format, QRhiTexture::Flags flags) const
1819{
1820 if (isCompressedFormat(format))
1821 return supportedCompressedFormats.contains(GLint(toGlCompressedTextureFormat(format, flags)));
1822
1823 if ((flags & QRhiTexture::UsedWithLoadStore) && !caps.imageLoadStore)
1824 return false;
1825
1826 if (flags.testFlag(QRhiTexture::sRGB)) {
1827 if (format != QRhiTexture::RGBA8 && format != QRhiTexture::BGRA8)
1828 return false;
1829 if (!caps.srgbTextureFormat || flags.testFlag(QRhiTexture::UsedWithLoadStore))
1830 return false;
1831 if (format == QRhiTexture::BGRA8 && caps.gles)
1832 return false;
1833 if (flags.testFlag(QRhiTexture::UsedWithGenerateMips) && !caps.srgbGenerateMipmap)
1834 return false;
1835 if (flags.testFlag(QRhiTexture::RenderTarget) && !caps.srgbTextureRenderTarget)
1836 return false;
1837 }
1838
1839 switch (format) {
1840 case QRhiTexture::D16:
1841 case QRhiTexture::D32F:
1842 case QRhiTexture::D32FS8:
1843 return caps.depthTexture;
1844
1845 case QRhiTexture::D24:
1846 return caps.depthTexture && caps.depth24;
1847
1848 case QRhiTexture::D24S8:
1849 return caps.depthTexture && caps.depth24 && caps.packedDepthStencil;
1850
1851 case QRhiTexture::BGRA8:
1852 return caps.bgraExternalFormat;
1853
1854 case QRhiTexture::R8:
1855 case QRhiTexture::R8SI:
1856 case QRhiTexture::R8UI:
1857 return caps.r8Format;
1858
1859 case QRhiTexture::R32SI:
1860 case QRhiTexture::R32UI:
1861 case QRhiTexture::RG32SI:
1862 case QRhiTexture::RG32UI:
1863 case QRhiTexture::RGBA32SI:
1864 case QRhiTexture::RGBA32UI:
1865 return caps.r32uiFormat;
1866
1867 case QRhiTexture::RG8:
1868 return caps.r8Format;
1869
1870 case QRhiTexture::R16:
1871 return caps.r16Format;
1872
1873 case QRhiTexture::RG16:
1874 return caps.r16Format;
1875
1876 case QRhiTexture::RGBA16F:
1877 case QRhiTexture::RGBA32F:
1878 return caps.floatFormats;
1879
1880 case QRhiTexture::R16F:
1881 case QRhiTexture::R32F:
1882 return caps.floatFormats;
1883
1884 case QRhiTexture::RGB10A2:
1885 return caps.rgb10Formats;
1886
1887 default:
1888 break;
1889 }
1890
1891 return true;
1892}
1893
1894bool QRhiGles2::isFeatureSupported(QRhi::Feature feature) const
1895{
1896 switch (feature) {
1897 case QRhi::MultisampleTexture:
1898 return caps.multisampledTexture;
1899 case QRhi::MultisampleRenderBuffer:
1900 return caps.msaaRenderBuffer;
1901 case QRhi::DebugMarkers:
1902 return false;
1903 case QRhi::Timestamps:
1904 return caps.timestamps;
1905 case QRhi::Instancing:
1906 return caps.instancing;
1907 case QRhi::CustomInstanceStepRate:
1908 return false;
1909 case QRhi::PrimitiveRestart:
1910 return caps.fixedIndexPrimitiveRestart;
1911 case QRhi::NonDynamicUniformBuffers:
1912 return true;
1913 case QRhi::NonFourAlignedEffectiveIndexBufferOffset:
1914 return true;
1915 case QRhi::NPOTTextureRepeat:
1916 return caps.npotTextureFull;
1917 case QRhi::RedOrAlpha8IsRed:
1918 return caps.coreProfile;
1919 case QRhi::ElementIndexUint:
1920 return caps.elementIndexUint;
1921 case QRhi::Compute:
1922 return caps.compute;
1923 case QRhi::FragmentStoresAndAtomics:
1924 return caps.compute && caps.maxFragmentStorageBuffers > 0;
1925 case QRhi::WideLines:
1926 return !caps.coreProfile;
1927 case QRhi::VertexShaderPointSize:
1928 return true;
1929 case QRhi::BaseVertex:
1930 return caps.baseVertex;
1931 case QRhi::BaseInstance:
1932 // gl_InstanceID on GL starts at 0 regardless of baseInstance, unlike
1933 // Vulkan's gl_InstanceIndex. QRhi::InstanceIndexIncludesBaseInstance
1934 // stays false on GL.
1935 return caps.baseInstance;
1936 case QRhi::TriangleFanTopology:
1937 return true;
1938 case QRhi::ReadBackNonUniformBuffer:
1939 return !caps.gles || caps.properMapBuffer;
1940 case QRhi::ReadBackNonBaseMipLevel:
1942 case QRhi::TexelFetch:
1943 return caps.texelFetch;
1944 case QRhi::RenderToNonBaseMipLevel:
1946 case QRhi::IntAttributes:
1947 return caps.intAttributes;
1948 case QRhi::ScreenSpaceDerivatives:
1949 return caps.screenSpaceDerivatives;
1950 case QRhi::ReadBackAnyTextureFormat:
1951 return false;
1952 case QRhi::PipelineCacheDataLoadSave:
1953 return caps.programBinary;
1954 case QRhi::ImageDataStride:
1955 return caps.unpackRowLength;
1956 case QRhi::RenderBufferImport:
1957 return true;
1958 case QRhi::ThreeDimensionalTextures:
1959 return caps.texture3D;
1960 case QRhi::RenderTo3DTextureSlice:
1961 return caps.texture3D;
1962 case QRhi::TextureArrays:
1963 return caps.maxTextureArraySize > 0;
1964 case QRhi::Tessellation:
1965 return caps.tessellation;
1966 case QRhi::GeometryShader:
1967 return caps.geometryShader;
1968 case QRhi::TextureArrayRange:
1969 return false;
1970 case QRhi::NonFillPolygonMode:
1971 return !caps.gles;
1972 case QRhi::OneDimensionalTextures:
1973 return caps.texture1D;
1974 case QRhi::OneDimensionalTextureMipmaps:
1975 return caps.texture1D;
1976 case QRhi::HalfAttributes:
1977 return caps.halfAttributes;
1978 case QRhi::RenderToOneDimensionalTexture:
1979 return caps.texture1D;
1980 case QRhi::ThreeDimensionalTextureMipmaps:
1981 return caps.texture3D;
1982 case QRhi::MultiView:
1983 return caps.multiView && caps.maxTextureArraySize > 0;
1984 case QRhi::TextureViewFormat:
1985 return false;
1986 case QRhi::ResolveDepthStencil:
1987 return true;
1988 case QRhi::VariableRateShading:
1989 return false;
1990 case QRhi::VariableRateShadingMap:
1991 case QRhi::VariableRateShadingMapWithTexture:
1992 return false;
1993 case QRhi::DualSourceBlend:
1994 return caps.dualSourceBlending;
1995 case QRhi::BaseInstanceIndirect:
1996 return caps.drawIndirect && caps.baseInstance;
1997 case QRhi::PerRenderTargetBlending:
1998 return caps.perRenderTargetBlending;
1999 case QRhi::SampleVariables:
2000 return caps.sampleVariables;
2001 case QRhi::InstanceIndexIncludesBaseInstance:
2002 return false; // gl_InstanceID always starts at 0 on GL
2003 case QRhi::DepthClamp:
2004 return caps.depthClamp;
2005 case QRhi::DrawIndirect:
2006 return caps.drawIndirect;
2007 case QRhi::DrawIndirectMulti:
2008 return caps.drawIndirectMulti;
2009 case QRhi::ShaderDrawParameters:
2010 return caps.shaderDrawParameters;
2011 case QRhi::DispatchIndirect:
2012 return caps.dispatchIndirect;
2013 case QRhi::PushConstants:
2014 return true;
2015 case QRhi::DrawIndirectCount:
2016 return caps.drawIndirectCount;
2017 case QRhi::BufferToBufferCopy:
2018 return caps.copyBuffer;
2019 case QRhi::StaticBuffersOnGpuTimeline:
2020 return true;
2021 default:
2022 Q_UNREACHABLE_RETURN(false);
2023 }
2024}
2025
2026int QRhiGles2::resourceLimit(QRhi::ResourceLimit limit) const
2027{
2028 switch (limit) {
2029 case QRhi::TextureSizeMin:
2030 return 1;
2031 case QRhi::TextureSizeMax:
2032 return caps.maxTextureSize;
2033 case QRhi::MaxColorAttachments:
2034 return caps.maxDrawBuffers;
2035 case QRhi::FramesInFlight:
2036 // From our perspective. What the GL impl does internally is another
2037 // question, but that's out of our hands and does not concern us here.
2038 return 1;
2039 case QRhi::MaxAsyncReadbackFrames:
2040 return 1;
2041 case QRhi::MaxThreadGroupsPerDimension:
2043 case QRhi::MaxThreadsPerThreadGroup:
2044 return caps.maxThreadsPerThreadGroup;
2045 case QRhi::MaxThreadGroupX:
2046 return caps.maxThreadGroupsX;
2047 case QRhi::MaxThreadGroupY:
2048 return caps.maxThreadGroupsY;
2049 case QRhi::MaxThreadGroupZ:
2050 return caps.maxThreadGroupsZ;
2051 case QRhi::TextureArraySizeMax:
2052 return 2048;
2053 case QRhi::MaxUniformBufferRange:
2054 return int(qMin<qint64>(INT_MAX, caps.maxUniformVectors * qint64(16)));
2055 case QRhi::MaxVertexInputs:
2056 return caps.maxVertexInputs;
2057 case QRhi::MaxVertexOutputs:
2058 return caps.maxVertexOutputs;
2059 case QRhi::MaxVertexStorageBuffers:
2060 return caps.maxVertexStorageBuffers;
2061 case QRhi::MaxPushConstantsSize:
2062 // Emulated with plain uniforms, so the real limit is the uniform
2063 // budget shared with everything else. Report the portable minimum.
2064 return int(MAX_PUSH_CONSTANTS_SIZE);
2065 case QRhi::MaxFragmentStorageBuffers:
2066 return caps.maxFragmentStorageBuffers;
2067 case QRhi::MaxStorageBufferBindings:
2068 return caps.maxStorageBufferBindings;
2069 case QRhi::MaxStorageImageBindings:
2070 return caps.maxStorageImageBindings;
2071 case QRhi::ShadingRateImageTileSize:
2072 return 0;
2073 default:
2074 Q_UNREACHABLE_RETURN(0);
2075 }
2076}
2077
2079{
2080 return &nativeHandlesStruct;
2081}
2082
2084{
2085 return driverInfoStruct;
2086}
2087
2089{
2090 QRhiStats result;
2091 result.totalPipelineCreationTime = totalPipelineCreationTime();
2092 return result;
2093}
2094
2096{
2097 if (inFrame && !ofr.active)
2098 return ensureContext(currentSwapChain->surface);
2099 else
2100 return ensureContext();
2101}
2102
2103void QRhiGles2::setQueueSubmitParams(QRhiNativeHandles *)
2104{
2105 // not applicable
2106}
2107
2109{
2110 if (!ensureContext())
2111 return;
2112
2113 for (uint shader : std::as_const(m_shaderCache))
2114 f->glDeleteShader(shader);
2115
2116 m_shaderCache.clear();
2117
2118 m_pipelineCache.clear();
2119
2121}
2122
2124{
2125 return contextLost;
2126}
2127
2136
2138{
2139 Q_STATIC_ASSERT(sizeof(QGles2PipelineCacheDataHeader) == 256);
2140
2141 if (m_pipelineCache.data.isEmpty())
2142 return QByteArray();
2143
2145 memset(&header, 0, sizeof(header));
2146 header.rhiId = pipelineCacheRhiId();
2147 header.arch = quint32(sizeof(void*));
2148 header.programBinaryCount = m_pipelineCache.data.size();
2149 const size_t driverStrLen = qMin(sizeof(header.driver) - 1, size_t(driverInfoStruct.deviceName.size()));
2150 if (driverStrLen)
2151 memcpy(header.driver, driverInfoStruct.deviceName.constData(), driverStrLen);
2152 header.driver[driverStrLen] = '\0';
2153
2154 const size_t dataOffset = sizeof(header);
2155 size_t dataSize = 0;
2156 for (auto it = m_pipelineCache.data.cbegin(), end = m_pipelineCache.data.cend(); it != end; ++it) {
2157 dataSize += sizeof(quint32) + it.key().size()
2158 + sizeof(quint32) + it->data.size()
2159 + sizeof(quint32);
2160 }
2161
2162 QByteArray buf(dataOffset + dataSize, Qt::Uninitialized);
2163 char *p = buf.data() + dataOffset;
2164 for (auto it = m_pipelineCache.data.cbegin(), end = m_pipelineCache.data.cend(); it != end; ++it) {
2165 const QByteArray key = it.key();
2166 const QByteArray data = it->data;
2167 const quint32 format = it->format;
2168
2169 quint32 i = key.size();
2170 memcpy(p, &i, 4);
2171 p += 4;
2172 memcpy(p, key.constData(), key.size());
2173 p += key.size();
2174
2175 i = data.size();
2176 memcpy(p, &i, 4);
2177 p += 4;
2178 memcpy(p, data.constData(), data.size());
2179 p += data.size();
2180
2181 memcpy(p, &format, 4);
2182 p += 4;
2183 }
2184 Q_ASSERT(p == buf.data() + dataOffset + dataSize);
2185
2186 header.dataSize = quint32(dataSize);
2187 memcpy(buf.data(), &header, sizeof(header));
2188
2189 return buf;
2190}
2191
2192void QRhiGles2::setPipelineCacheData(const QByteArray &data)
2193{
2194 if (data.isEmpty())
2195 return;
2196
2197 const size_t headerSize = sizeof(QGles2PipelineCacheDataHeader);
2198 if (data.size() < qsizetype(headerSize)) {
2199 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: Invalid blob size (header incomplete)");
2200 return;
2201 }
2202 const size_t dataOffset = headerSize;
2204 memcpy(&header, data.constData(), headerSize);
2205
2206 const quint32 rhiId = pipelineCacheRhiId();
2207 if (header.rhiId != rhiId) {
2208 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: The data is for a different QRhi version or backend (%u, %u)",
2209 rhiId, header.rhiId);
2210 return;
2211 }
2212 const quint32 arch = quint32(sizeof(void*));
2213 if (header.arch != arch) {
2214 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: Architecture does not match (%u, %u)",
2215 arch, header.arch);
2216 return;
2217 }
2218 if (header.programBinaryCount == 0)
2219 return;
2220
2221 const size_t driverStrLen = qMin(sizeof(header.driver) - 1, size_t(driverInfoStruct.deviceName.size()));
2222 if (strncmp(header.driver, driverInfoStruct.deviceName.constData(), driverStrLen)) {
2223 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: OpenGL vendor/renderer/version does not match");
2224 return;
2225 }
2226
2227 if (quint64(data.size()) < quint64(dataOffset) + header.dataSize) {
2228 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: Invalid blob size (data incomplete)");
2229 return;
2230 }
2231
2232 m_pipelineCache.clear();
2233
2234 QRhiPipelineCacheDataReader reader(data.constData() + dataOffset, header.dataSize);
2235 for (quint32 i = 0; i < header.programBinaryCount; ++i) {
2236 QByteArray key;
2237 QByteArray binary;
2238 quint32 format = 0;
2239 if (!reader.readByteArray(&key) || !reader.readByteArray(&binary) || !reader.readUInt32(&format)) {
2240 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: Invalid blob (truncated or corrupt program binary data)");
2241 m_pipelineCache.clear();
2242 return;
2243 }
2244 m_pipelineCache.insertWithCapacityLimit(key, { format, binary });
2245 }
2246
2247 qCDebug(QRHI_LOG_INFO, "Seeded pipeline cache with %d program binaries", int(m_pipelineCache.data.size()));
2248}
2249
2250QRhiRenderBuffer *QRhiGles2::createRenderBuffer(QRhiRenderBuffer::Type type, const QSize &pixelSize,
2251 int sampleCount, QRhiRenderBuffer::Flags flags,
2252 QRhiTexture::Format backingFormatHint)
2253{
2254 return new QGles2RenderBuffer(this, type, pixelSize, sampleCount, flags, backingFormatHint);
2255}
2256
2257QRhiTexture *QRhiGles2::createTexture(QRhiTexture::Format format,
2258 const QSize &pixelSize, int depth, int arraySize,
2259 int sampleCount, QRhiTexture::Flags flags)
2260{
2261 return new QGles2Texture(this, format, pixelSize, depth, arraySize, sampleCount, flags);
2262}
2263
2264QRhiSampler *QRhiGles2::createSampler(QRhiSampler::Filter magFilter, QRhiSampler::Filter minFilter,
2265 QRhiSampler::Filter mipmapMode,
2266 QRhiSampler::AddressMode u, QRhiSampler::AddressMode v, QRhiSampler::AddressMode w)
2267{
2268 return new QGles2Sampler(this, magFilter, minFilter, mipmapMode, u, v, w);
2269}
2270
2271QRhiShadingRateMap *QRhiGles2::createShadingRateMap()
2272{
2273 return nullptr;
2274}
2275
2276QRhiTextureRenderTarget *QRhiGles2::createTextureRenderTarget(const QRhiTextureRenderTargetDescription &desc,
2277 QRhiTextureRenderTarget::Flags flags)
2278{
2279 return new QGles2TextureRenderTarget(this, desc, flags);
2280}
2281
2283{
2284 return new QGles2GraphicsPipeline(this);
2285}
2286
2288{
2289 return new QGles2ShaderResourceBindings(this);
2290}
2291
2293{
2294 return new QGles2ComputePipeline(this);
2295}
2296
2297void QRhiGles2::setGraphicsPipeline(QRhiCommandBuffer *cb, QRhiGraphicsPipeline *ps)
2298{
2299 QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
2302 const bool pipelineChanged = cbD->currentGraphicsPipeline != ps || cbD->currentPipelineGeneration != psD->generation;
2303
2304 if (pipelineChanged) {
2305 cbD->currentGraphicsPipeline = ps;
2306 cbD->currentComputePipeline = nullptr;
2308 if (psD->lastUsedInFrameNo != frameNo) {
2310 psD->currentSrb = nullptr;
2312 }
2313
2314 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
2316 cmd.args.bindGraphicsPipeline.ps = ps;
2317 }
2318}
2319
2320// Whether a storage image or buffer that was already used in the pass needs a
2321// barrier before the next use: after an earlier write (read-after-write,
2322// write-after-write), or when a write follows an earlier read.
2325{
2326 const bool nextWrites = next == QRhiPassResourceTracker::TexStorageStore
2328 switch (prev) {
2331 return true;
2333 return nextWrites;
2334 default:
2335 return false;
2336 }
2337}
2338
2341{
2342 const bool nextWrites = next == QRhiPassResourceTracker::BufStorageStore
2344 switch (prev) {
2347 return true;
2349 return nextWrites;
2350 default:
2351 return false;
2352 }
2353}
2354
2355void QRhiGles2::setShaderResources(QRhiCommandBuffer *cb, QRhiShaderResourceBindings *srb,
2356 int dynamicOffsetCount,
2357 const QRhiCommandBuffer::DynamicOffset *dynamicOffsets)
2358{
2359 QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
2361 QGles2GraphicsPipeline *gfxPsD = QRHI_RES(QGles2GraphicsPipeline, cbD->currentGraphicsPipeline);
2362 QGles2ComputePipeline *compPsD = QRHI_RES(QGles2ComputePipeline, cbD->currentComputePipeline);
2363
2364 if (!srb) {
2365 if (gfxPsD)
2366 srb = gfxPsD->m_shaderResourceBindings;
2367 else
2368 srb = compPsD->m_shaderResourceBindings;
2369 }
2370
2372 // The storage images and buffers are tracked also in a pass begun with
2373 // DoNotTrackResourcesForCompute, so that the barriers between dependent
2374 // draws do not depend on the flag. Everything else is tracked only for
2375 // compute.
2376 const bool trackAll = cbD->passNeedsResourceTracking;
2377 if (trackAll || (caps.compute && srbD->hasStorageBinding)) {
2378 QRhiPassResourceTracker &passResTracker(cbD->passResTrackers[cbD->currentPassResTrackerIndex]);
2379 GLbitfield barriers = 0;
2380 for (int i = 0, ie = srbD->m_bindings.size(); i != ie; ++i) {
2381 const QRhiShaderResourceBinding::Data *b = shaderResourceBindingData(srbD->m_bindings.at(i));
2382 switch (b->type()) {
2383 case QRhiShaderResourceBinding::UniformBuffer:
2384 // no BufUniformRead / AccessUniform because no real uniform buffers are used
2385 break;
2386 case QRhiShaderResourceBinding::SampledTexture:
2387 case QRhiShaderResourceBinding::Texture:
2388 if (!trackAll)
2389 break;
2390 for (const auto &texSampler : b->stex().texSamplers) {
2391 QGles2Texture *texD = QRHI_RES(QGles2Texture, texSampler.tex);
2392 sanityCheckResourceOwnership(texD);
2393 trackedRegisterTexture(&passResTracker,
2394 texD,
2395 QRhiPassResourceTracker::TexSample,
2396 QRhiPassResourceTracker::toPassTrackerTextureStage(b->stage));
2397 }
2398 break;
2399 case QRhiShaderResourceBinding::ImageLoad:
2400 case QRhiShaderResourceBinding::ImageStore:
2401 case QRhiShaderResourceBinding::ImageLoadStore:
2402 {
2403 QGles2Texture *texD = QRHI_RES(QGles2Texture, b->simage().tex);
2404 sanityCheckResourceOwnership(texD);
2406 if (b->type() == QRhiShaderResourceBinding::ImageLoad)
2408 else if (b->type() == QRhiShaderResourceBinding::ImageStore)
2410 else
2412 if (gfxPsD) {
2413 const auto prev = passResTracker.textures().find(texD);
2414 if (prev != passResTracker.textures().end()
2415 && storageAccessNeedsBarrier(prev->second.access, access)) {
2417 }
2418 }
2419 trackedRegisterTexture(&passResTracker, texD, access,
2420 QRhiPassResourceTracker::toPassTrackerTextureStage(b->stage));
2421 }
2422 break;
2423 case QRhiShaderResourceBinding::BufferLoad:
2424 case QRhiShaderResourceBinding::BufferStore:
2425 case QRhiShaderResourceBinding::BufferLoadStore:
2426 {
2427 QGles2Buffer *bufD = QRHI_RES(QGles2Buffer, b->sbuf().buf);
2428 sanityCheckResourceOwnership(bufD);
2430 if (b->type() == QRhiShaderResourceBinding::BufferLoad)
2432 else if (b->type() == QRhiShaderResourceBinding::BufferStore)
2434 else
2436 if (gfxPsD) {
2437 const auto prev = passResTracker.buffers().find(bufD);
2438 if (prev != passResTracker.buffers().end()
2439 && storageAccessNeedsBarrier(prev->second.access, access)) {
2441 }
2442 }
2443 trackedRegisterBuffer(&passResTracker, bufD, access,
2444 QRhiPassResourceTracker::toPassTrackerBufferStage(b->stage));
2445 }
2446 break;
2447 default:
2448 break;
2449 }
2450 }
2451
2452 // Nothing orders the storage image and buffer accesses of the draws
2453 // in a render pass, so generate the barrier here based on what the
2454 // earlier setShaderResources() calls in the pass registered. Draws
2455 // that depend on each other must therefore have a
2456 // setShaderResources() call in between, also when the srb is the same.
2457 // Dispatches in a compute pass are handled in dispatch().
2458 if (gfxPsD && !srbD->storageBindingsFragmentOnly)
2460 if (barriers) {
2461 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
2462 // When all storage accesses in the pass so far, including the
2463 // ones from this srb, come from fragment shaders, a by-region
2464 // barrier is enough. Like VK_DEPENDENCY_BY_REGION_BIT with Vulkan,
2465 // this orders only the accesses to the same framebuffer region,
2466 // and is cheaper for tiled GPUs as it does not need to flush the
2467 // tiles.
2470 else
2472 cmd.args.barrier.barriers = barriers;
2473 }
2474 }
2475
2476 bool srbChanged = gfxPsD ? (cbD->currentGraphicsSrb != srb) : (cbD->currentComputeSrb != srb);
2477
2478 // The Command::BindShaderResources command generated below is what will
2479 // cause uniforms to be set (glUniformNxx). This needs some special
2480 // handling here in this backend without real uniform buffers, because,
2481 // like in other backends, we optimize out the setShaderResources when the
2482 // srb that was set before is attempted to be set again on the command
2483 // buffer, but that is incorrect if the same srb is now used with another
2484 // pipeline. (because that could mean a glUseProgram not followed by
2485 // up-to-date glUniform calls, i.e. with GL we have a strong dependency
2486 // between the pipeline (== program) and the srb, unlike other APIs) This
2487 // is the reason there is a second level of srb(+generation) tracking in
2488 // the pipeline objects.
2489 if (gfxPsD && (gfxPsD->currentSrb != srb || gfxPsD->currentSrbGeneration != srbD->generation)) {
2490 srbChanged = true;
2491 gfxPsD->currentSrb = srb;
2493 } else if (compPsD && (compPsD->currentSrb != srb || compPsD->currentSrbGeneration != srbD->generation)) {
2494 srbChanged = true;
2495 compPsD->currentSrb = srb;
2497 }
2498
2499 if (srbChanged || cbD->currentSrbGeneration != srbD->generation || srbD->hasDynamicOffset) {
2500 if (gfxPsD) {
2501 cbD->currentGraphicsSrb = srb;
2502 cbD->currentComputeSrb = nullptr;
2503 } else {
2504 cbD->currentGraphicsSrb = nullptr;
2505 cbD->currentComputeSrb = srb;
2506 }
2508
2509 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
2511 cmd.args.bindShaderResources.maybeGraphicsPs = gfxPsD;
2512 cmd.args.bindShaderResources.maybeComputePs = compPsD;
2513 cmd.args.bindShaderResources.srb = srb;
2514 cmd.args.bindShaderResources.dynamicOffsetCount = 0;
2515 cmd.args.bindShaderResources.dynamicOffsetPoolOffset = 0;
2516 if (srbD->hasDynamicOffset && dynamicOffsetCount > 0) {
2517 cmd.args.bindShaderResources.dynamicOffsetCount = dynamicOffsetCount;
2518 cmd.args.bindShaderResources.dynamicOffsetPoolOffset = quint32(cbD->dynamicOffsetPool.size());
2519 for (int i = 0; i < dynamicOffsetCount; ++i) {
2520 const QRhiCommandBuffer::DynamicOffset &dynOfs(dynamicOffsets[i]);
2521 cbD->dynamicOffsetPool.append(uint(dynOfs.first));
2522 cbD->dynamicOffsetPool.append(dynOfs.second);
2523 }
2524 }
2525 }
2526}
2527
2528void QRhiGles2::setVertexInput(QRhiCommandBuffer *cb,
2529 int startBinding, int bindingCount, const QRhiCommandBuffer::VertexInput *bindings,
2530 QRhiBuffer *indexBuf, quint32 indexOffset, QRhiCommandBuffer::IndexFormat indexFormat)
2531{
2532 QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
2534 QRhiPassResourceTracker &passResTracker(cbD->passResTrackers[cbD->currentPassResTrackerIndex]);
2535
2536 for (int i = 0; i < bindingCount; ++i) {
2537 QRhiBuffer *buf = bindings[i].first;
2538 quint32 ofs = bindings[i].second;
2539 QGles2Buffer *bufD = QRHI_RES(QGles2Buffer, buf);
2540 Q_ASSERT(bufD->m_usage.testFlag(QRhiBuffer::VertexBuffer));
2541
2542 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
2544 cmd.args.bindVertexBuffer.ps = cbD->currentGraphicsPipeline;
2545 cmd.args.bindVertexBuffer.buffer = bufD->buffer;
2546 cmd.args.bindVertexBuffer.offset = ofs;
2547 cmd.args.bindVertexBuffer.binding = startBinding + i;
2548
2552 }
2553 }
2554
2555 if (indexBuf) {
2556 QGles2Buffer *ibufD = QRHI_RES(QGles2Buffer, indexBuf);
2557 Q_ASSERT(ibufD->m_usage.testFlag(QRhiBuffer::IndexBuffer));
2558
2559 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
2561 cmd.args.bindIndexBuffer.buffer = ibufD->buffer;
2562 cmd.args.bindIndexBuffer.offset = indexOffset;
2563 cmd.args.bindIndexBuffer.type = indexFormat == QRhiCommandBuffer::IndexUInt16 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
2564
2568 }
2569 }
2570}
2571
2572void QRhiGles2::setViewport(QRhiCommandBuffer *cb, const QRhiViewport &viewport)
2573{
2574 QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
2576
2577 const std::array<float, 4> r = viewport.viewport();
2578 // A negative width or height is an error. A negative x or y is not.
2579 if (r[2] < 0.0f || r[3] < 0.0f)
2580 return;
2581
2582 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
2584 cmd.args.viewport.x = r[0];
2585 cmd.args.viewport.y = r[1];
2586 cmd.args.viewport.w = r[2];
2587 cmd.args.viewport.h = r[3];
2588 cmd.args.viewport.d0 = viewport.minDepth();
2589 cmd.args.viewport.d1 = viewport.maxDepth();
2590}
2591
2592void QRhiGles2::setScissor(QRhiCommandBuffer *cb, const QRhiScissor &scissor)
2593{
2594 QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
2596
2597 const std::array<int, 4> r = scissor.scissor();
2598 // A negative width or height is an error. A negative x or y is not.
2599 if (r[2] < 0 || r[3] < 0)
2600 return;
2601
2602 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
2604 cmd.args.scissor.x = r[0];
2605 cmd.args.scissor.y = r[1];
2606 cmd.args.scissor.w = r[2];
2607 cmd.args.scissor.h = r[3];
2608}
2609
2610void QRhiGles2::setBlendConstants(QRhiCommandBuffer *cb, const QColor &c)
2611{
2612 QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
2614
2615 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
2617 cmd.args.blendConstants.r = c.redF();
2618 cmd.args.blendConstants.g = c.greenF();
2619 cmd.args.blendConstants.b = c.blueF();
2620 cmd.args.blendConstants.a = c.alphaF();
2621}
2622
2623void QRhiGles2::setStencilRef(QRhiCommandBuffer *cb, quint32 refValue)
2624{
2625 QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
2627
2628 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
2630 cmd.args.stencilRef.ref = refValue;
2631 cmd.args.stencilRef.ps = cbD->currentGraphicsPipeline;
2632}
2633
2634void QRhiGles2::setPushConstants(QRhiCommandBuffer *cb, quint32 offset, quint32 size, const void *data)
2635{
2636 QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
2638
2639 QRhiGraphicsPipeline *maybeGraphicsPs = nullptr;
2640 QRhiComputePipeline *maybeComputePs = nullptr;
2641 quint32 blockSize = 0;
2643 QGles2ComputePipeline *psD = QRHI_RES(QGles2ComputePipeline, cbD->currentComputePipeline);
2644 if (!psD)
2645 return;
2646 maybeComputePs = cbD->currentComputePipeline;
2647 blockSize = psD->pushConstantSize;
2648 } else {
2649 QGles2GraphicsPipeline *psD = QRHI_RES(QGles2GraphicsPipeline, cbD->currentGraphicsPipeline);
2650 if (!psD)
2651 return;
2652 maybeGraphicsPs = cbD->currentGraphicsPipeline;
2653 blockSize = psD->pushConstantSize;
2654 }
2655 if (!blockSize) {
2656 qWarning("No pipeline with a push constant block is active; setPushConstants ignored");
2657 return;
2658 }
2659
2660 if (offset + size > MAX_PUSH_CONSTANTS_SIZE) {
2661 qWarning("Push constant data of %u bytes at offset %u exceeds the %u byte maximum; "
2662 "setPushConstants ignored", size, offset, MAX_PUSH_CONSTANTS_SIZE);
2663 return;
2664 }
2665
2666 // A partial update has to be honored, so the block is kept on the command
2667 // buffer and the whole of it is submitted every time.
2668 const quint32 total = qMin(qMax(blockSize, offset + size), MAX_PUSH_CONSTANTS_SIZE);
2669 if (quint32(cbD->pushConstantData.size()) < total)
2670 cbD->pushConstantData.resize(int(total), 0);
2671 memcpy(cbD->pushConstantData.data() + offset, data, size);
2672
2673 const quint32 dataOffset = quint32(cbD->pushConstantPool.size());
2674 cbD->pushConstantPool.append(cbD->pushConstantData.constData(), total);
2675
2676 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
2678 cmd.args.setPushConstants.maybeGraphicsPs = maybeGraphicsPs;
2679 cmd.args.setPushConstants.maybeComputePs = maybeComputePs;
2680 cmd.args.setPushConstants.dataOffset = dataOffset;
2681 cmd.args.setPushConstants.size = total;
2682}
2683
2684void QRhiGles2::setShadingRate(QRhiCommandBuffer *cb, const QSize &coarsePixelSize)
2685{
2686 Q_UNUSED(cb);
2687 Q_UNUSED(coarsePixelSize);
2688}
2689
2690void QRhiGles2::draw(QRhiCommandBuffer *cb, quint32 vertexCount,
2691 quint32 instanceCount, quint32 firstVertex, quint32 firstInstance)
2692{
2693 QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
2695
2696 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
2698 cmd.args.draw.ps = cbD->currentGraphicsPipeline;
2699 cmd.args.draw.vertexCount = vertexCount;
2700 cmd.args.draw.firstVertex = firstVertex;
2701 cmd.args.draw.instanceCount = instanceCount;
2702 cmd.args.draw.baseInstance = firstInstance;
2703}
2704
2705void QRhiGles2::drawIndexed(QRhiCommandBuffer *cb, quint32 indexCount,
2706 quint32 instanceCount, quint32 firstIndex, qint32 vertexOffset, quint32 firstInstance)
2707{
2708 QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
2710
2711 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
2713 cmd.args.drawIndexed.ps = cbD->currentGraphicsPipeline;
2714 cmd.args.drawIndexed.indexCount = indexCount;
2715 cmd.args.drawIndexed.firstIndex = firstIndex;
2716 cmd.args.drawIndexed.instanceCount = instanceCount;
2717 cmd.args.drawIndexed.baseInstance = firstInstance;
2718 cmd.args.drawIndexed.baseVertex = vertexOffset;
2719}
2720
2721void QRhiGles2::drawIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer,
2722 quint32 indirectBufferOffset, quint32 drawCount, quint32 stride)
2723{
2724 if (!caps.drawIndirect)
2725 return;
2726
2727 QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
2729
2730 QGles2Buffer *indirectBufD = QRHI_RES(QGles2Buffer, indirectBuffer);
2731
2733 QRhiPassResourceTracker &passResTracker(cbD->passResTrackers[cbD->currentPassResTrackerIndex]);
2734 trackedRegisterBuffer(&passResTracker, indirectBufD,
2737 }
2738
2739 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
2741 cmd.args.drawIndirect.ps = cbD->currentGraphicsPipeline;
2742 cmd.args.drawIndirect.buffer = indirectBufD->buffer;
2743 cmd.args.drawIndirect.offset = indirectBufferOffset;
2744 cmd.args.drawIndirect.drawCount = drawCount;
2745 cmd.args.drawIndirect.stride = stride;
2746}
2747
2748void QRhiGles2::drawIndexedIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer,
2749 quint32 indirectBufferOffset, quint32 drawCount, quint32 stride)
2750{
2751 if (!caps.drawIndirect)
2752 return;
2753
2754 QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
2756
2757 QGles2Buffer *indirectBufD = QRHI_RES(QGles2Buffer, indirectBuffer);
2758
2760 QRhiPassResourceTracker &passResTracker(cbD->passResTrackers[cbD->currentPassResTrackerIndex]);
2761 trackedRegisterBuffer(&passResTracker, indirectBufD,
2764 }
2765
2766 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
2768 cmd.args.drawIndexedIndirect.ps = cbD->currentGraphicsPipeline;
2769 cmd.args.drawIndexedIndirect.buffer = indirectBufD->buffer;
2770 cmd.args.drawIndexedIndirect.offset = indirectBufferOffset;
2771 cmd.args.drawIndexedIndirect.drawCount = drawCount;
2772 cmd.args.drawIndexedIndirect.stride = stride;
2773}
2774
2775void QRhiGles2::drawIndirectCount(QRhiCommandBuffer *cb,
2776 QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset,
2777 QRhiBuffer *countBuffer, quint32 countBufferOffset,
2778 quint32 maxDrawCount, quint32 stride)
2779{
2780 if (!caps.drawIndirectCount) {
2781 qWarning("drawIndirectCount called but the DrawIndirectCount feature is not supported");
2782 return;
2783 }
2784
2785 QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
2787
2788 QGles2Buffer *indirectBufD = QRHI_RES(QGles2Buffer, indirectBuffer);
2789 QGles2Buffer *countBufD = QRHI_RES(QGles2Buffer, countBuffer);
2790
2792 QRhiPassResourceTracker &passResTracker(cbD->passResTrackers[cbD->currentPassResTrackerIndex]);
2793 trackedRegisterBuffer(&passResTracker, indirectBufD,
2796 trackedRegisterBuffer(&passResTracker, countBufD,
2799 }
2800
2801 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
2803 cmd.args.drawIndirectCount.ps = cbD->currentGraphicsPipeline;
2804 cmd.args.drawIndirectCount.buffer = indirectBufD->buffer;
2805 cmd.args.drawIndirectCount.offset = indirectBufferOffset;
2806 cmd.args.drawIndirectCount.countBuffer = countBufD->buffer;
2807 cmd.args.drawIndirectCount.countOffset = countBufferOffset;
2808 cmd.args.drawIndirectCount.maxDrawCount = maxDrawCount;
2809 cmd.args.drawIndirectCount.stride = stride;
2810}
2811
2812void QRhiGles2::drawIndexedIndirectCount(QRhiCommandBuffer *cb,
2813 QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset,
2814 QRhiBuffer *countBuffer, quint32 countBufferOffset,
2815 quint32 maxDrawCount, quint32 stride)
2816{
2817 if (!caps.drawIndirectCount) {
2818 qWarning("drawIndexedIndirectCount called but the DrawIndirectCount feature is not supported");
2819 return;
2820 }
2821
2822 QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
2824
2825 QGles2Buffer *indirectBufD = QRHI_RES(QGles2Buffer, indirectBuffer);
2826 QGles2Buffer *countBufD = QRHI_RES(QGles2Buffer, countBuffer);
2827
2829 QRhiPassResourceTracker &passResTracker(cbD->passResTrackers[cbD->currentPassResTrackerIndex]);
2830 trackedRegisterBuffer(&passResTracker, indirectBufD,
2833 trackedRegisterBuffer(&passResTracker, countBufD,
2836 }
2837
2838 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
2840 cmd.args.drawIndexedIndirectCount.ps = cbD->currentGraphicsPipeline;
2841 cmd.args.drawIndexedIndirectCount.buffer = indirectBufD->buffer;
2842 cmd.args.drawIndexedIndirectCount.offset = indirectBufferOffset;
2843 cmd.args.drawIndexedIndirectCount.countBuffer = countBufD->buffer;
2844 cmd.args.drawIndexedIndirectCount.countOffset = countBufferOffset;
2845 cmd.args.drawIndexedIndirectCount.maxDrawCount = maxDrawCount;
2846 cmd.args.drawIndexedIndirectCount.stride = stride;
2847}
2848
2849void QRhiGles2::debugMarkBegin(QRhiCommandBuffer *cb, const QByteArray &name)
2850{
2851 if (!debugMarkers)
2852 return;
2853
2854 Q_UNUSED(cb);
2855 Q_UNUSED(name);
2856}
2857
2858void QRhiGles2::debugMarkEnd(QRhiCommandBuffer *cb)
2859{
2860 if (!debugMarkers)
2861 return;
2862
2863 Q_UNUSED(cb);
2864}
2865
2866void QRhiGles2::debugMarkMsg(QRhiCommandBuffer *cb, const QByteArray &msg)
2867{
2868 if (!debugMarkers)
2869 return;
2870
2871 Q_UNUSED(cb);
2872 Q_UNUSED(msg);
2873}
2874
2875const QRhiNativeHandles *QRhiGles2::nativeHandles(QRhiCommandBuffer *cb)
2876{
2877 Q_UNUSED(cb);
2878 return nullptr;
2879}
2880
2881static inline void addBoundaryCommand(QGles2CommandBuffer *cbD, QGles2CommandBuffer::Command::Cmd type, GLuint tsQuery = 0)
2882{
2883 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
2884 cmd.cmd = type;
2886 cmd.args.beginFrame.timestampQuery = tsQuery;
2888 cmd.args.endFrame.timestampQuery = tsQuery;
2889}
2890
2891void QRhiGles2::beginExternal(QRhiCommandBuffer *cb)
2892{
2893 if (ofr.active) {
2894 Q_ASSERT(!currentSwapChain);
2895 if (!ensureContext())
2896 return;
2897 } else {
2898 Q_ASSERT(currentSwapChain);
2899 if (!ensureContext(currentSwapChain->surface))
2900 return;
2901 }
2902
2903 QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
2904
2906 && !cbD->computePassState.writtenResources.isEmpty())
2907 {
2908 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
2910 cmd.args.barrier.barriers = GL_ALL_BARRIER_BITS;
2911 }
2912
2914
2916
2917 // ARRAY_BUFFER and SHADER_STORAGE_BUFFER are context state, not vertex
2918 // array object state, so going back to object 0 does not clear them.
2919 if (vao)
2920 f->glBindVertexArray(0);
2921 f->glBindBuffer(GL_ARRAY_BUFFER, 0);
2922 f->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
2923 if (caps.compute)
2924 f->glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
2925}
2926
2927void QRhiGles2::endExternal(QRhiCommandBuffer *cb)
2928{
2929 QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
2930 Q_ASSERT(cbD->commands.isEmpty() && cbD->currentPassResTrackerIndex == -1);
2931
2933
2935 // Commands that come after this point need a resource tracker and also
2936 // a BarriersForPass command enqueued. (the ones we had from
2937 // beginPass() are now gone since beginExternal() processed all that
2938 // due to calling executeCommandBuffer()).
2940 }
2941
2943
2944 if (cbD->currentTarget)
2945 enqueueBindFramebuffer(cbD->currentTarget, cbD);
2946}
2947
2948double QRhiGles2::lastCompletedGpuTime(QRhiCommandBuffer *cb)
2949{
2950 QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
2951 return cbD->lastGpuTime;
2952}
2953
2955{
2956 QGles2SwapChain *swapChainD = QRHI_RES(QGles2SwapChain, swapChain);
2957 if (!ensureContext(swapChainD->surface))
2958 return contextLost ? QRhi::FrameOpDeviceLost : QRhi::FrameOpError;
2959
2960 ctx->handle()->beginFrame();
2961
2962 currentSwapChain = swapChainD;
2963
2965 swapChainD->cb.resetState();
2966 frameNo += 1;
2967
2968 if (swapChainD->timestamps.active[swapChainD->currentTimestampPairIndex]) {
2969 double elapsedSec = 0;
2970 if (swapChainD->timestamps.tryQueryTimestamps(swapChainD->currentTimestampPairIndex, this, &elapsedSec))
2971 swapChainD->cb.lastGpuTime = elapsedSec;
2972 }
2973
2974 GLuint tsStart = swapChainD->timestamps.query[swapChainD->currentTimestampPairIndex * 2];
2975 GLuint tsEnd = swapChainD->timestamps.query[swapChainD->currentTimestampPairIndex * 2 + 1];
2976 const bool recordTimestamps = tsStart && tsEnd && !swapChainD->timestamps.active[swapChainD->currentTimestampPairIndex];
2977
2978 addBoundaryCommand(&swapChainD->cb, QGles2CommandBuffer::Command::BeginFrame, recordTimestamps ? tsStart : 0);
2979
2980 return QRhi::FrameOpSuccess;
2981}
2982
2983QRhi::FrameOpResult QRhiGles2::endFrame(QRhiSwapChain *swapChain, QRhi::EndFrameFlags flags)
2984{
2985 QGles2SwapChain *swapChainD = QRHI_RES(QGles2SwapChain, swapChain);
2986 Q_ASSERT(currentSwapChain == swapChainD);
2987
2988 GLuint tsStart = swapChainD->timestamps.query[swapChainD->currentTimestampPairIndex * 2];
2989 GLuint tsEnd = swapChainD->timestamps.query[swapChainD->currentTimestampPairIndex * 2 + 1];
2990 const bool recordTimestamps = tsStart && tsEnd && !swapChainD->timestamps.active[swapChainD->currentTimestampPairIndex];
2991 if (recordTimestamps) {
2992 swapChainD->timestamps.active[swapChainD->currentTimestampPairIndex] = true;
2994 }
2995
2996 addBoundaryCommand(&swapChainD->cb, QGles2CommandBuffer::Command::EndFrame, recordTimestamps ? tsEnd : 0);
2997
2998 if (!ensureContext(swapChainD->surface))
2999 return contextLost ? QRhi::FrameOpDeviceLost : QRhi::FrameOpError;
3000
3001 executeCommandBuffer(&swapChainD->cb);
3002
3003 if (swapChainD->surface && !flags.testFlag(QRhi::SkipPresent)) {
3004 ctx->swapBuffers(swapChainD->surface);
3006 } else {
3007 f->glFlush();
3008 }
3009
3010 currentSwapChain = nullptr;
3011
3012 ctx->handle()->endFrame();
3013
3014 return QRhi::FrameOpSuccess;
3015}
3016
3018{
3019 if (!ensureContext())
3020 return contextLost ? QRhi::FrameOpDeviceLost : QRhi::FrameOpError;
3021
3022 ofr.active = true;
3023
3025 ofr.cbWrapper.resetState();
3026
3027 if (rhiFlags.testFlag(QRhi::EnableTimestamps) && caps.timestamps) {
3028 if (!ofr.tsQueries[0])
3029 f->glGenQueries(2, ofr.tsQueries);
3030 }
3031
3032 addBoundaryCommand(&ofr.cbWrapper, QGles2CommandBuffer::Command::BeginFrame, ofr.tsQueries[0]);
3033 *cb = &ofr.cbWrapper;
3034
3035 return QRhi::FrameOpSuccess;
3036}
3037
3038QRhi::FrameOpResult QRhiGles2::endOffscreenFrame(QRhi::EndFrameFlags flags)
3039{
3040 Q_UNUSED(flags);
3041 Q_ASSERT(ofr.active);
3042 ofr.active = false;
3043
3044 addBoundaryCommand(&ofr.cbWrapper, QGles2CommandBuffer::Command::EndFrame, ofr.tsQueries[1]);
3045
3046 if (!ensureContext())
3047 return contextLost ? QRhi::FrameOpDeviceLost : QRhi::FrameOpError;
3048
3049 executeCommandBuffer(&ofr.cbWrapper);
3050
3051 // Just as endFrame() does a flush when skipping the swapBuffers(), do it
3052 // here as well. This has the added benefit of playing nice when rendering
3053 // to a texture from a context and then consuming that texture from
3054 // another, sharing context.
3055 f->glFlush();
3056
3057 if (ofr.tsQueries[0]) {
3058 quint64 timestamps[2];
3059 glGetQueryObjectui64v(ofr.tsQueries[1], GL_QUERY_RESULT, &timestamps[1]);
3060 glGetQueryObjectui64v(ofr.tsQueries[0], GL_QUERY_RESULT, &timestamps[0]);
3061 if (timestamps[1] >= timestamps[0]) {
3062 const quint64 nanoseconds = timestamps[1] - timestamps[0];
3063 ofr.cbWrapper.lastGpuTime = nanoseconds / 1000000000.0; // seconds
3064 }
3065 }
3066
3067 return QRhi::FrameOpSuccess;
3068}
3069
3071{
3072 if (inFrame) {
3073 if (ofr.active) {
3074 Q_ASSERT(!currentSwapChain);
3075 Q_ASSERT(ofr.cbWrapper.recordingPass == QGles2CommandBuffer::NoPass);
3076 if (!ensureContext())
3077 return contextLost ? QRhi::FrameOpDeviceLost : QRhi::FrameOpError;
3078 executeCommandBuffer(&ofr.cbWrapper);
3079 ofr.cbWrapper.resetCommands();
3080 } else {
3081 Q_ASSERT(currentSwapChain);
3082 Q_ASSERT(currentSwapChain->cb.recordingPass == QGles2CommandBuffer::NoPass);
3083 if (!ensureContext(currentSwapChain->surface))
3084 return contextLost ? QRhi::FrameOpDeviceLost : QRhi::FrameOpError;
3086 currentSwapChain->cb.resetCommands();
3087 }
3088 // Do an actual glFinish(). May seem superfluous, but this is what
3089 // matches most other backends e.g. Vulkan/Metal that do a heavyweight
3090 // wait-for-idle blocking in their finish(). More importantly, this
3091 // allows clients simply call finish() in threaded or shared context
3092 // situations where one explicitly needs to do a glFlush or Finish.
3093 f->glFinish();
3094 }
3095 return QRhi::FrameOpSuccess;
3096}
3097
3099{
3100 return access == QGles2Buffer::AccessStorageWrite
3102 || access == QGles2Buffer::AccessUpdate;
3103}
3104
3106{
3107 return access == QGles2Texture::AccessStorageWrite
3109 || access == QGles2Texture::AccessUpdate
3111}
3112
3122
3131
3133{
3134 Q_ASSERT(cbD->recordingPass == QGles2CommandBuffer::NoPass); // this is for resource updates only
3135 if (!bufD->m_usage.testFlag(QRhiBuffer::StorageBuffer))
3136 return;
3137
3138 const QGles2Buffer::Access prevAccess = bufD->usageState.access;
3139 if (access == prevAccess)
3140 return;
3141
3142 if (bufferAccessIsWrite(prevAccess)) {
3143 // Generating the minimal barrier set is way too complicated to do
3144 // correctly (prevAccess is overwritten so we won't have proper
3145 // tracking across multiple passes) so setting all barrier bits will do
3146 // for now.
3147 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
3149 cmd.args.barrier.barriers = barriersForBuffer();
3150 }
3151
3152 bufD->usageState.access = access;
3153}
3154
3156{
3157 Q_ASSERT(cbD->recordingPass == QGles2CommandBuffer::NoPass); // this is for resource updates only
3158 if (!texD->m_flags.testFlag(QRhiTexture::UsedWithLoadStore))
3159 return;
3160
3161 const QGles2Texture::Access prevAccess = texD->usageState.access;
3162 if (access == prevAccess)
3163 return;
3164
3165 if (textureAccessIsWrite(prevAccess)) {
3166 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
3168 cmd.args.barrier.barriers = barriersForTexture();
3169 }
3170
3171 texD->usageState.access = access;
3172}
3173
3175 int layer, int level, const QRhiTextureSubresourceUploadDescription &subresDesc)
3176{
3178 const bool isCompressed = isCompressedFormat(texD->m_format);
3179 const bool isCubeMap = texD->m_flags.testFlag(QRhiTexture::CubeMap);
3180 const bool is3D = texD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
3181 const bool is1D = texD->m_flags.testFlag(QRhiTexture::OneDimensional);
3182 const bool isArray = texD->m_flags.testFlag(QRhiTexture::TextureArray);
3183 const GLenum faceTargetBase = isCubeMap ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : texD->target;
3184 const GLenum effectiveTarget = faceTargetBase + (isCubeMap ? uint(layer) : 0u);
3185 const QPoint dp = subresDesc.destinationTopLeft();
3186 const QByteArray rawData = subresDesc.data();
3187
3188 auto setCmdByNotCompressedData = [&](const void* data, QSize size, quint32 dataStride)
3189 {
3190 quint32 bytesPerLine = 0;
3191 quint32 bytesPerPixel = 0;
3192 textureFormatInfo(texD->m_format, size, &bytesPerLine, nullptr, &bytesPerPixel);
3193
3194 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
3196 cmd.args.subImage.target = texD->target;
3197 cmd.args.subImage.texture = texD->texture;
3198 cmd.args.subImage.faceTarget = effectiveTarget;
3199 cmd.args.subImage.level = level;
3200 cmd.args.subImage.dx = dp.x();
3201 cmd.args.subImage.dy = is1D && isArray ? layer : dp.y();
3202 cmd.args.subImage.dz = is3D || isArray ? layer : 0;
3203 cmd.args.subImage.w = size.width();
3204 cmd.args.subImage.h = size.height();
3205 cmd.args.subImage.glformat = texD->glformat;
3206 cmd.args.subImage.gltype = texD->gltype;
3207
3208 if (dataStride == 0)
3209 dataStride = bytesPerLine;
3210
3211 cmd.args.subImage.rowStartAlign = (dataStride & 3) ? 1 : 4;
3212 cmd.args.subImage.rowLength = caps.unpackRowLength ? (bytesPerPixel ? dataStride / bytesPerPixel : 0) : 0;
3213
3214 cmd.args.subImage.data = data;
3215 };
3216
3217 if (!subresDesc.image().isNull()) {
3218 QImage img = subresDesc.image();
3219 QSize size = img.size();
3220 if (!subresDesc.sourceSize().isEmpty() || !subresDesc.sourceTopLeft().isNull()) {
3221 const QPoint sp = subresDesc.sourceTopLeft();
3222 if (!subresDesc.sourceSize().isEmpty())
3223 size = subresDesc.sourceSize();
3224 size = clampedSubResourceUploadSize(size, dp, level, texD->m_pixelSize);
3225 if (caps.unpackRowLength) {
3226 cbD->retainImage(img);
3227 // create a non-owning wrapper for the subimage
3228 const uchar *data = img.constBits() + sp.y() * img.bytesPerLine() + sp.x() * (qMax(1, img.depth() / 8));
3229 img = QImage(data, size.width(), size.height(), img.bytesPerLine(), img.format());
3230 } else {
3231 img = img.copy(sp.x(), sp.y(), size.width(), size.height());
3232 }
3233 } else {
3234 size = clampedSubResourceUploadSize(size, dp, level, texD->m_pixelSize);
3235 }
3236
3237 setCmdByNotCompressedData(cbD->retainImage(img), size, img.bytesPerLine());
3238 } else if (!rawData.isEmpty() && isCompressed) {
3239 const int depth = qMax(1, texD->m_depth);
3240 const int arraySize = qMax(0, texD->m_arraySize);
3241 // When create() could not allocate the storage up front, each mip
3242 // level is allocated upon the first upload touching it. For cubemaps
3243 // every face is a separate image, hence tracking per face as well.
3244 const int face = isCubeMap ? qBound(0, layer, 5) : 0;
3245 const QSize subresSize = q->sizeForMipLevel(level, texD->m_pixelSize);
3246 QSize size = subresDesc.sourceSize().isEmpty() ? subresSize : subresDesc.sourceSize();
3247 size = clampedSubResourceUploadSize(size, dp, level, texD->m_pixelSize);
3248 if (size.isEmpty())
3249 return;
3250
3251 // A single subresource upload for a 3D or array texture covers one
3252 // slice or layer only, so it can never allocate the mip level on its
3253 // own. Neither can an upload that does not cover the entire level.
3254 const bool coversWholeSubres = !is3D && !isArray && dp.isNull() && size == subresSize;
3255
3256 if (!texD->isLevelAllocated(face, level) && !coversWholeSubres) {
3257 // glCompressedTexImage* cannot take nullptr data, so allocate the
3258 // level with a zero-filled buffer. Any data is accepted here, but
3259 // what the areas not overwritten later decode to depends on the
3260 // format (e.g. an all-zero ASTC block is an illegal encoding, so
3261 // it gives the error color). The real data follows below via
3262 // glCompressedTexSubImage*.
3263 const int mipDepth = is3D ? q->sizeForMipLevel(level, QSize(depth, depth)).width() : 1;
3264 quint32 levelByteSize = 0;
3265 if (!compressedFormatInfo(texD->m_format, subresSize, nullptr, &levelByteSize, nullptr))
3266 return;
3267 quint64 byteSize = levelByteSize;
3268 if (is3D)
3269 byteSize *= quint64(mipDepth);
3270 if (isArray)
3271 byteSize *= quint64(arraySize);
3272 if (byteSize > quint64(std::numeric_limits<int>::max())) {
3273 qWarning("Compressed texture zero-initialization would need %llu bytes "
3274 "which is too large; skipping", byteSize);
3275 return;
3276 }
3277 QByteArray zeroBuf(qsizetype(byteSize), 0);
3278 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
3280 cmd.args.compressedImage.target = texD->target;
3281 cmd.args.compressedImage.texture = texD->texture;
3282 cmd.args.compressedImage.faceTarget = effectiveTarget;
3283 cmd.args.compressedImage.level = level;
3284 cmd.args.compressedImage.glintformat = texD->glintformat;
3285 cmd.args.compressedImage.w = subresSize.width();
3286 cmd.args.compressedImage.h = is1D && isArray ? arraySize : subresSize.height();
3287 cmd.args.compressedImage.depth = is3D ? mipDepth : (isArray ? arraySize : 0);
3288 cmd.args.compressedImage.size = int(byteSize);
3289 cmd.args.compressedImage.data = cbD->retainData(zeroBuf);
3290 texD->allocatedLevels[face] |= 1u << uint(level);
3291 }
3292
3293 if (texD->isLevelAllocated(face, level)) {
3294 const QSize clampedSize = clampedCompressedSubResourceUploadSizeForSourceData(texD->m_format,
3295 size,
3296 rawData.size());
3297 if (clampedSize.height() == 0)
3298 return;
3299 qsizetype imageSize = rawData.size();
3300 if (clampedSize != size) {
3301 quint32 byteSize = 0;
3302 compressedFormatInfo(texD->m_format, clampedSize, nullptr, &byteSize, nullptr);
3303 imageSize = byteSize;
3304 size = clampedSize;
3305 }
3306 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
3308 cmd.args.compressedSubImage.target = texD->target;
3309 cmd.args.compressedSubImage.texture = texD->texture;
3310 cmd.args.compressedSubImage.faceTarget = effectiveTarget;
3311 cmd.args.compressedSubImage.level = level;
3312 cmd.args.compressedSubImage.dx = dp.x();
3313 cmd.args.compressedSubImage.dy = is1D && isArray ? layer : dp.y();
3314 cmd.args.compressedSubImage.dz = is3D || isArray ? layer : 0;
3315 cmd.args.compressedSubImage.w = size.width();
3316 cmd.args.compressedSubImage.h = size.height();
3317 cmd.args.compressedSubImage.glintformat = texD->glintformat;
3318 cmd.args.compressedSubImage.size = int(imageSize);
3319 cmd.args.compressedSubImage.data = cbD->retainData(rawData);
3320 } else {
3321 // Allocate the level and upload the real data in one go. This
3322 // defines the level, so it cannot be shrunk to fit the data.
3323 quint32 byteSize = 0;
3324 compressedFormatInfo(texD->m_format, size, nullptr, &byteSize, nullptr);
3325 if (rawData.size() < qsizetype(byteSize)) {
3326 qWarning("Invalid compressed texture upload issued; %lld bytes of data cannot back "
3327 "the initial %dx%d upload (needs %u bytes); skipping",
3328 qint64(rawData.size()), size.width(), size.height(), byteSize);
3329 return;
3330 }
3331 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
3333 cmd.args.compressedImage.target = texD->target;
3334 cmd.args.compressedImage.texture = texD->texture;
3335 cmd.args.compressedImage.faceTarget = effectiveTarget;
3336 cmd.args.compressedImage.level = level;
3337 cmd.args.compressedImage.glintformat = texD->glintformat;
3338 cmd.args.compressedImage.w = size.width();
3339 cmd.args.compressedImage.h = size.height();
3340 cmd.args.compressedImage.depth = 0;
3341 cmd.args.compressedImage.size = rawData.size();
3342 cmd.args.compressedImage.data = cbD->retainData(rawData);
3343 texD->allocatedLevels[face] |= 1u << uint(level);
3344 }
3345 } else if (!rawData.isEmpty()) {
3346 QSize size = subresDesc.sourceSize().isEmpty() ? q->sizeForMipLevel(level, texD->m_pixelSize)
3347 : subresDesc.sourceSize();
3348 size = clampedSubResourceUploadSize(size, dp, level, texD->m_pixelSize);
3349 quint32 bytesPerPixel = 0;
3350 textureFormatInfo(texD->m_format, size, nullptr, nullptr, &bytesPerPixel);
3351 size = clampedSubResourceUploadSizeForSourceData(size, subresDesc.dataStride(),
3352 bytesPerPixel, rawData.size());
3353 if (size.isEmpty())
3354 return;
3355
3356 setCmdByNotCompressedData(cbD->retainData(rawData), size, subresDesc.dataStride());
3357 } else {
3358 qWarning("Invalid texture upload for %p layer=%d mip=%d", texD, layer, level);
3359 }
3360}
3361
3362void QRhiGles2::enqueueResourceUpdates(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
3363{
3364 QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
3366
3367 for (int opIdx = 0; opIdx < ud->activeBufferOpCount; ++opIdx) {
3368 const QRhiResourceUpdateBatchPrivate::BufferOp &u(ud->bufferOps[opIdx]);
3370 QGles2Buffer *bufD = QRHI_RES(QGles2Buffer, u.buf);
3371 Q_ASSERT(bufD->m_type == QRhiBuffer::Dynamic);
3372 if (bufD->m_usage.testFlag(QRhiBuffer::UniformBuffer)) {
3373 memcpy(bufD->data.data() + u.offset, u.data.constData(), size_t(u.data.size()));
3374 } else {
3376 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
3378 cmd.args.bufferSubData.target = bufD->targetForDataOps;
3379 cmd.args.bufferSubData.buffer = bufD->buffer;
3380 cmd.args.bufferSubData.offset = u.offset;
3381 cmd.args.bufferSubData.size = u.data.size();
3382 cmd.args.bufferSubData.data = cbD->retainBufferData(u.data);
3383 }
3385 QGles2Buffer *bufD = QRHI_RES(QGles2Buffer, u.buf);
3386 Q_ASSERT(bufD->m_type != QRhiBuffer::Dynamic);
3387 Q_ASSERT(u.offset + u.data.size() <= bufD->m_size);
3388 if (bufD->m_usage.testFlag(QRhiBuffer::UniformBuffer)) {
3389 memcpy(bufD->data.data() + u.offset, u.data.constData(), size_t(u.data.size()));
3390 } else {
3392 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
3394 cmd.args.bufferSubData.target = bufD->targetForDataOps;
3395 cmd.args.bufferSubData.buffer = bufD->buffer;
3396 cmd.args.bufferSubData.offset = u.offset;
3397 cmd.args.bufferSubData.size = u.data.size();
3398 cmd.args.bufferSubData.data = cbD->retainBufferData(u.data);
3399 }
3401 QGles2Buffer *bufD = QRHI_RES(QGles2Buffer, u.buf);
3402 if (bufD->m_usage.testFlag(QRhiBuffer::UniformBuffer)) {
3403 u.result->data.resize(u.readSize);
3404 memcpy(u.result->data.data(), bufD->data.constData() + u.offset, size_t(u.readSize));
3405 if (u.result->completed)
3406 u.result->completed();
3407 } else {
3408 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
3410 cmd.args.getBufferSubData.result = u.result;
3411 cmd.args.getBufferSubData.target = bufD->targetForDataOps;
3412 cmd.args.getBufferSubData.buffer = bufD->buffer;
3413 cmd.args.getBufferSubData.offset = u.offset;
3414 cmd.args.getBufferSubData.size = u.readSize;
3415 }
3417 if (!caps.copyBuffer)
3418 continue;
3419
3420 QGles2Buffer *dstD = QRHI_RES(QGles2Buffer, u.buf);
3421 QGles2Buffer *srcD = QRHI_RES(QGles2Buffer, u.src);
3422 Q_ASSERT(dstD->buffer && srcD->buffer);
3423
3426
3427 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
3429 cmd.args.copyBuf.srcBuffer = srcD->buffer;
3430 cmd.args.copyBuf.dstBuffer = dstD->buffer;
3431 cmd.args.copyBuf.srcOffset = u.srcOffset;
3432 cmd.args.copyBuf.dstOffset = u.offset;
3433 cmd.args.copyBuf.size = u.readSize;
3435 QGles2Buffer *bufD = QRHI_RES(QGles2Buffer, u.buf);
3436 Q_ASSERT(bufD->buffer);
3437
3439
3440 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
3441 if (caps.clearBuffer) {
3443 cmd.args.clearBufferSubData.target = bufD->targetForDataOps;
3444 cmd.args.clearBufferSubData.buffer = bufD->buffer;
3445 cmd.args.clearBufferSubData.offset = u.offset;
3446 cmd.args.clearBufferSubData.size = u.readSize;
3447 cmd.args.clearBufferSubData.value = u.fillValue;
3448 } else if (caps.compute && ensureClearBufferProgram()) {
3450 cmd.args.clearBufferCompute.buffer = bufD->buffer;
3451 cmd.args.clearBufferCompute.offsetWords = quint32(u.offset) / 4u;
3452 cmd.args.clearBufferCompute.countWords = quint32(u.readSize) / 4u;
3453 cmd.args.clearBufferCompute.value = u.fillValue32();
3454 } else {
3455 QRhiBufferData fillData;
3456 fillData.assign(QByteArray(u.readSize, char(u.fillValue)));
3458 cmd.args.bufferSubData.target = bufD->targetForDataOps;
3459 cmd.args.bufferSubData.buffer = bufD->buffer;
3460 cmd.args.bufferSubData.offset = u.offset;
3461 cmd.args.bufferSubData.size = u.readSize;
3462 cmd.args.bufferSubData.data = cbD->retainBufferData(fillData);
3463 }
3464 }
3465 }
3466
3467 for (int opIdx = 0; opIdx < ud->activeTextureOpCount; ++opIdx) {
3468 const QRhiResourceUpdateBatchPrivate::TextureOp &u(ud->textureOps[opIdx]);
3470 QGles2Texture *texD = QRHI_RES(QGles2Texture, u.dst);
3471 for (const auto &subres : u.subresDesc)
3472 enqueueSubresUpload(texD, cbD, subres.layer, subres.level, subres.desc);
3474 Q_ASSERT(u.src && u.dst);
3475 QGles2Texture *srcD = QRHI_RES(QGles2Texture, u.src);
3476 QGles2Texture *dstD = QRHI_RES(QGles2Texture, u.dst);
3477
3480
3481 const QSize mipSize = q->sizeForMipLevel(u.desc.sourceLevel(), srcD->m_pixelSize);
3482 const QSize copySize = u.desc.pixelSize().isEmpty() ? mipSize : u.desc.pixelSize();
3483 // do not translate coordinates, even if sp is bottom-left from gl's pov
3484 const QPoint sp = u.desc.sourceTopLeft();
3485 const QPoint dp = u.desc.destinationTopLeft();
3486
3487 const GLenum srcFaceTargetBase = srcD->m_flags.testFlag(QRhiTexture::CubeMap)
3488 ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : srcD->target;
3489 const GLenum dstFaceTargetBase = dstD->m_flags.testFlag(QRhiTexture::CubeMap)
3490 ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : dstD->target;
3491
3492 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
3494
3495 const bool srcHasZ = srcD->m_flags.testFlag(QRhiTexture::ThreeDimensional) || srcD->m_flags.testFlag(QRhiTexture::TextureArray);
3496 const bool dstHasZ = dstD->m_flags.testFlag(QRhiTexture::ThreeDimensional) || dstD->m_flags.testFlag(QRhiTexture::TextureArray);
3497 const bool dstIs1dArray = dstD->m_flags.testFlag(QRhiTexture::OneDimensional)
3498 && dstD->m_flags.testFlag(QRhiTexture::TextureArray);
3499
3500 cmd.args.copyTex.srcTarget = srcD->target;
3501 cmd.args.copyTex.srcFaceTarget = srcFaceTargetBase + (srcHasZ ? 0u : uint(u.desc.sourceLayer()));
3502 cmd.args.copyTex.srcTexture = srcD->texture;
3503 cmd.args.copyTex.srcLevel = u.desc.sourceLevel();
3504 cmd.args.copyTex.srcX = sp.x();
3505 cmd.args.copyTex.srcY = sp.y();
3506 cmd.args.copyTex.srcZ = srcHasZ ? u.desc.sourceLayer() : 0;
3507
3508 cmd.args.copyTex.dstTarget = dstD->target;
3509 cmd.args.copyTex.dstFaceTarget = dstFaceTargetBase + (dstHasZ ? 0u : uint(u.desc.destinationLayer()));
3510 cmd.args.copyTex.dstTexture = dstD->texture;
3511 cmd.args.copyTex.dstLevel = u.desc.destinationLevel();
3512 cmd.args.copyTex.dstX = dp.x();
3513 cmd.args.copyTex.dstY = dstIs1dArray ? u.desc.destinationLayer() : dp.y();
3514 cmd.args.copyTex.dstZ = dstHasZ ? u.desc.destinationLayer() : 0;
3515
3516 cmd.args.copyTex.w = copySize.width();
3517 cmd.args.copyTex.h = copySize.height();
3519 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
3521 cmd.args.readPixels.result = u.result;
3522 QGles2Texture *texD = QRHI_RES(QGles2Texture, u.rb.texture());
3523 if (texD)
3525 cmd.args.readPixels.texture = texD ? texD->texture : 0;
3526 cmd.args.readPixels.slice3D = -1;
3527 if (texD) {
3528 if (u.rb.rect().isValid()) {
3529 cmd.args.readPixels.x = u.rb.rect().x();
3530 cmd.args.readPixels.y = u.rb.rect().y();
3531 cmd.args.readPixels.w = u.rb.rect().width();
3532 cmd.args.readPixels.h = u.rb.rect().height();
3533 }
3534 else {
3535 const QSize readImageSize = q->sizeForMipLevel(u.rb.level(), texD->m_pixelSize);
3536 cmd.args.readPixels.x = 0;
3537 cmd.args.readPixels.y = 0;
3538 cmd.args.readPixels.w = readImageSize.width();
3539 cmd.args.readPixels.h = readImageSize.height();
3540 }
3541 cmd.args.readPixels.format = texD->m_format;
3542 if (texD->m_flags.testFlag(QRhiTexture::ThreeDimensional)
3543 || texD->m_flags.testFlag(QRhiTexture::TextureArray))
3544 {
3545 cmd.args.readPixels.readTarget = texD->target;
3546 cmd.args.readPixels.slice3D = u.rb.layer();
3547 } else {
3548 const GLenum faceTargetBase = texD->m_flags.testFlag(QRhiTexture::CubeMap)
3549 ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : texD->target;
3550 cmd.args.readPixels.readTarget = faceTargetBase + uint(u.rb.layer());
3551 }
3552 cmd.args.readPixels.level = u.rb.level();
3553 }
3554 else { // swapchain
3555 if (u.rb.rect().isValid()) {
3556 cmd.args.readPixels.x = u.rb.rect().x();
3557 cmd.args.readPixels.y = u.rb.rect().y();
3558 cmd.args.readPixels.w = u.rb.rect().width();
3559 cmd.args.readPixels.h = u.rb.rect().height();
3560 }
3561 else {
3562 cmd.args.readPixels.x = 0;
3563 cmd.args.readPixels.y = 0;
3564 cmd.args.readPixels.w = currentSwapChain->pixelSize.width();
3565 cmd.args.readPixels.h = currentSwapChain->pixelSize.height();
3566 }
3567 }
3569 QGles2Texture *texD = QRHI_RES(QGles2Texture, u.dst);
3571 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
3573 cmd.args.genMip.target = texD->target;
3574 cmd.args.genMip.texture = texD->texture;
3575 }
3576 }
3577
3578 ud->free();
3579}
3580
3581static inline GLenum toGlTopology(QRhiGraphicsPipeline::Topology t)
3582{
3583 switch (t) {
3584 case QRhiGraphicsPipeline::Triangles:
3585 return GL_TRIANGLES;
3586 case QRhiGraphicsPipeline::TriangleStrip:
3587 return GL_TRIANGLE_STRIP;
3588 case QRhiGraphicsPipeline::TriangleFan:
3589 return GL_TRIANGLE_FAN;
3590 case QRhiGraphicsPipeline::Lines:
3591 return GL_LINES;
3592 case QRhiGraphicsPipeline::LineStrip:
3593 return GL_LINE_STRIP;
3594 case QRhiGraphicsPipeline::Points:
3595 return GL_POINTS;
3596 case QRhiGraphicsPipeline::Patches:
3597 return GL_PATCHES;
3598 default:
3599 Q_UNREACHABLE_RETURN(GL_TRIANGLES);
3600 }
3601}
3602
3603static inline GLenum toGlCullMode(QRhiGraphicsPipeline::CullMode c)
3604{
3605 switch (c) {
3606 case QRhiGraphicsPipeline::Front:
3607 return GL_FRONT;
3608 case QRhiGraphicsPipeline::Back:
3609 return GL_BACK;
3610 default:
3611 Q_UNREACHABLE_RETURN(GL_BACK);
3612 }
3613}
3614
3615static inline GLenum toGlFrontFace(QRhiGraphicsPipeline::FrontFace f)
3616{
3617 switch (f) {
3618 case QRhiGraphicsPipeline::CCW:
3619 return GL_CCW;
3620 case QRhiGraphicsPipeline::CW:
3621 return GL_CW;
3622 default:
3623 Q_UNREACHABLE_RETURN(GL_CCW);
3624 }
3625}
3626
3627static inline GLenum toGlBlendFactor(QRhiGraphicsPipeline::BlendFactor f)
3628{
3629 switch (f) {
3630 case QRhiGraphicsPipeline::Zero:
3631 return GL_ZERO;
3632 case QRhiGraphicsPipeline::One:
3633 return GL_ONE;
3634 case QRhiGraphicsPipeline::SrcColor:
3635 return GL_SRC_COLOR;
3636 case QRhiGraphicsPipeline::OneMinusSrcColor:
3637 return GL_ONE_MINUS_SRC_COLOR;
3638 case QRhiGraphicsPipeline::DstColor:
3639 return GL_DST_COLOR;
3640 case QRhiGraphicsPipeline::OneMinusDstColor:
3641 return GL_ONE_MINUS_DST_COLOR;
3642 case QRhiGraphicsPipeline::SrcAlpha:
3643 return GL_SRC_ALPHA;
3644 case QRhiGraphicsPipeline::OneMinusSrcAlpha:
3645 return GL_ONE_MINUS_SRC_ALPHA;
3646 case QRhiGraphicsPipeline::DstAlpha:
3647 return GL_DST_ALPHA;
3648 case QRhiGraphicsPipeline::OneMinusDstAlpha:
3649 return GL_ONE_MINUS_DST_ALPHA;
3650 case QRhiGraphicsPipeline::ConstantColor:
3651 return GL_CONSTANT_COLOR;
3652 case QRhiGraphicsPipeline::OneMinusConstantColor:
3654 case QRhiGraphicsPipeline::ConstantAlpha:
3655 return GL_CONSTANT_ALPHA;
3656 case QRhiGraphicsPipeline::OneMinusConstantAlpha:
3658 case QRhiGraphicsPipeline::SrcAlphaSaturate:
3659 return GL_SRC_ALPHA_SATURATE;
3660 case QRhiGraphicsPipeline::Src1Color:
3661 return GL_SRC1_COLOR;
3662 case QRhiGraphicsPipeline::OneMinusSrc1Color:
3664 case QRhiGraphicsPipeline::Src1Alpha:
3665 return GL_SRC1_ALPHA;
3666 case QRhiGraphicsPipeline::OneMinusSrc1Alpha:
3668 default:
3669 Q_UNREACHABLE_RETURN(GL_ZERO);
3670 }
3671}
3672
3673static inline GLenum toGlBlendOp(QRhiGraphicsPipeline::BlendOp op)
3674{
3675 switch (op) {
3676 case QRhiGraphicsPipeline::Add:
3677 return GL_FUNC_ADD;
3678 case QRhiGraphicsPipeline::Subtract:
3679 return GL_FUNC_SUBTRACT;
3680 case QRhiGraphicsPipeline::ReverseSubtract:
3682 case QRhiGraphicsPipeline::Min:
3683 return GL_MIN;
3684 case QRhiGraphicsPipeline::Max:
3685 return GL_MAX;
3686 default:
3687 Q_UNREACHABLE_RETURN(GL_FUNC_ADD);
3688 }
3689}
3690
3691static inline GLenum toGlCompareOp(QRhiGraphicsPipeline::CompareOp op)
3692{
3693 switch (op) {
3694 case QRhiGraphicsPipeline::Never:
3695 return GL_NEVER;
3696 case QRhiGraphicsPipeline::Less:
3697 return GL_LESS;
3698 case QRhiGraphicsPipeline::Equal:
3699 return GL_EQUAL;
3700 case QRhiGraphicsPipeline::LessOrEqual:
3701 return GL_LEQUAL;
3702 case QRhiGraphicsPipeline::Greater:
3703 return GL_GREATER;
3704 case QRhiGraphicsPipeline::NotEqual:
3705 return GL_NOTEQUAL;
3706 case QRhiGraphicsPipeline::GreaterOrEqual:
3707 return GL_GEQUAL;
3708 case QRhiGraphicsPipeline::Always:
3709 return GL_ALWAYS;
3710 default:
3711 Q_UNREACHABLE_RETURN(GL_ALWAYS);
3712 }
3713}
3714
3715static inline GLenum toGlStencilOp(QRhiGraphicsPipeline::StencilOp op)
3716{
3717 switch (op) {
3718 case QRhiGraphicsPipeline::StencilZero:
3719 return GL_ZERO;
3720 case QRhiGraphicsPipeline::Keep:
3721 return GL_KEEP;
3722 case QRhiGraphicsPipeline::Replace:
3723 return GL_REPLACE;
3724 case QRhiGraphicsPipeline::IncrementAndClamp:
3725 return GL_INCR;
3726 case QRhiGraphicsPipeline::DecrementAndClamp:
3727 return GL_DECR;
3728 case QRhiGraphicsPipeline::Invert:
3729 return GL_INVERT;
3730 case QRhiGraphicsPipeline::IncrementAndWrap:
3731 return GL_INCR_WRAP;
3732 case QRhiGraphicsPipeline::DecrementAndWrap:
3733 return GL_DECR_WRAP;
3734 default:
3735 Q_UNREACHABLE_RETURN(GL_KEEP);
3736 }
3737}
3738
3739static inline GLenum toGlPolygonMode(QRhiGraphicsPipeline::PolygonMode mode)
3740{
3741 switch (mode) {
3742 case QRhiGraphicsPipeline::PolygonMode::Fill:
3743 return GL_FILL;
3744 case QRhiGraphicsPipeline::PolygonMode::Line:
3745 return GL_LINE;
3746 default:
3747 Q_UNREACHABLE_RETURN(GL_FILL);
3748 }
3749}
3750
3751static inline GLenum toGlMinFilter(QRhiSampler::Filter f, QRhiSampler::Filter m)
3752{
3753 switch (f) {
3754 case QRhiSampler::Nearest:
3755 if (m == QRhiSampler::None)
3756 return GL_NEAREST;
3757 else
3758 return m == QRhiSampler::Nearest ? GL_NEAREST_MIPMAP_NEAREST : GL_NEAREST_MIPMAP_LINEAR;
3759 case QRhiSampler::Linear:
3760 if (m == QRhiSampler::None)
3761 return GL_LINEAR;
3762 else
3763 return m == QRhiSampler::Nearest ? GL_LINEAR_MIPMAP_NEAREST : GL_LINEAR_MIPMAP_LINEAR;
3764 default:
3765 Q_UNREACHABLE_RETURN(GL_LINEAR);
3766 }
3767}
3768
3769static inline GLenum toGlMagFilter(QRhiSampler::Filter f)
3770{
3771 switch (f) {
3772 case QRhiSampler::Nearest:
3773 return GL_NEAREST;
3774 case QRhiSampler::Linear:
3775 return GL_LINEAR;
3776 default:
3777 Q_UNREACHABLE_RETURN(GL_LINEAR);
3778 }
3779}
3780
3781static inline GLenum toGlWrapMode(QRhiSampler::AddressMode m)
3782{
3783 switch (m) {
3784 case QRhiSampler::Repeat:
3785 return GL_REPEAT;
3786 case QRhiSampler::ClampToEdge:
3787 return GL_CLAMP_TO_EDGE;
3788 case QRhiSampler::Mirror:
3789 return GL_MIRRORED_REPEAT;
3790 default:
3791 Q_UNREACHABLE_RETURN(GL_CLAMP_TO_EDGE);
3792 }
3793}
3794
3795static inline GLenum toGlTextureCompareFunc(QRhiSampler::CompareOp op)
3796{
3797 switch (op) {
3798 case QRhiSampler::Never:
3799 return GL_NEVER;
3800 case QRhiSampler::Less:
3801 return GL_LESS;
3802 case QRhiSampler::Equal:
3803 return GL_EQUAL;
3804 case QRhiSampler::LessOrEqual:
3805 return GL_LEQUAL;
3806 case QRhiSampler::Greater:
3807 return GL_GREATER;
3808 case QRhiSampler::NotEqual:
3809 return GL_NOTEQUAL;
3810 case QRhiSampler::GreaterOrEqual:
3811 return GL_GEQUAL;
3812 case QRhiSampler::Always:
3813 return GL_ALWAYS;
3814 default:
3815 Q_UNREACHABLE_RETURN(GL_NEVER);
3816 }
3817}
3818
3842
3844{
3846 u.layout = 0; // N/A
3847 u.access = bufUsage.access;
3848 u.stage = 0; // N/A
3849 return u;
3850}
3851
3874
3876{
3878 u.layout = 0; // N/A
3879 u.access = texUsage.access;
3880 u.stage = 0; // N/A
3881 return u;
3882}
3883
3885 QGles2Buffer *bufD,
3888{
3890 passResTracker->registerBuffer(bufD, 0, &access, &stage, toPassTrackerUsageState(u));
3891 u.access = toGlAccess(access);
3892}
3893
3895 QGles2Texture *texD,
3898{
3900 passResTracker->registerTexture(texD, &access, &stage, toPassTrackerUsageState(u));
3901 u.access = toGlAccess(access);
3902}
3903
3905{
3906 GLenum indexType = GL_UNSIGNED_SHORT;
3911 struct {
3912 QRhiGraphicsPipeline *ps = nullptr;
3913 GLuint buffer = 0;
3914 quint32 offset = 0;
3915 int binding = 0;
3916 } lastBindVertexBuffer;
3917 static const int TRACKED_ATTRIB_COUNT = 16;
3922};
3923
3924// Helper that must be used in executeCommandBuffer() whenever changing the
3925// ARRAY or ELEMENT_ARRAY buffer binding outside of Command::BindVertexBuffer
3926// and Command::BindIndexBuffer.
3928 QOpenGLExtensions *f,
3929 GLenum target,
3930 GLuint buffer)
3931{
3932 state->currentArrayBuffer = 0;
3933 state->currentElementArrayBuffer = 0;
3934 state->lastBindVertexBuffer.buffer = 0;
3935 f->glBindBuffer(target, buffer);
3936}
3937
3938void QRhiGles2::executeCommandBuffer(QRhiCommandBuffer *cb)
3939{
3941 QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
3942
3943 for (auto it = cbD->commands.cbegin(), end = cbD->commands.cend(); it != end; ++it) {
3944 const QGles2CommandBuffer::Command &cmd(*it);
3945 switch (cmd.cmd) {
3947 if (cmd.args.beginFrame.timestampQuery)
3948 glQueryCounter(cmd.args.beginFrame.timestampQuery, GL_TIMESTAMP);
3949 if (caps.vertexArrayObject) {
3950 if (!vao)
3951 f->glGenVertexArrays(1, &vao);
3952 f->glBindVertexArray(vao);
3953 }
3954 break;
3956 if (state.instancedAttributesUsed) {
3957 for (int i = 0; i < CommandBufferExecTrackedState::TRACKED_ATTRIB_COUNT; ++i) {
3958 if (state.nonzeroAttribDivisor[i])
3959 f->glVertexAttribDivisor(GLuint(i), 0);
3960 }
3962 f->glVertexAttribDivisor(GLuint(i), 0);
3963 state.instancedAttributesUsed = false;
3964 }
3965 // The enables are vertex array object state, so without this they
3966 // would persist across frames, pointing into deleted buffers.
3967 for (int i = 0; i < CommandBufferExecTrackedState::TRACKED_ATTRIB_COUNT; ++i) {
3968 if (state.enabledAttribArrays[i]) {
3969 f->glDisableVertexAttribArray(GLuint(i));
3970 state.enabledAttribArrays[i] = false;
3971 }
3972 }
3973 if (vao)
3974 f->glBindVertexArray(0);
3975 f->glBindFramebuffer(GL_FRAMEBUFFER, ctx->defaultFramebufferObject());
3976 if (cmd.args.endFrame.timestampQuery)
3977 glQueryCounter(cmd.args.endFrame.timestampQuery, GL_TIMESTAMP);
3978 break;
3980 if (vao)
3981 f->glBindVertexArray(vao);
3982 break;
3984 f->glViewport(GLint(cmd.args.viewport.x), GLint(cmd.args.viewport.y), GLsizei(cmd.args.viewport.w), GLsizei(cmd.args.viewport.h));
3985 f->glDepthRangef(cmd.args.viewport.d0, cmd.args.viewport.d1);
3986 break;
3988 f->glScissor(cmd.args.scissor.x, cmd.args.scissor.y, cmd.args.scissor.w, cmd.args.scissor.h);
3989 break;
3991 f->glBlendColor(cmd.args.blendConstants.r, cmd.args.blendConstants.g, cmd.args.blendConstants.b, cmd.args.blendConstants.a);
3992 break;
3994 {
3995 QGles2GraphicsPipeline *psD = QRHI_RES(QGles2GraphicsPipeline, cmd.args.stencilRef.ps);
3996 if (psD) {
3997 const GLint ref = GLint(cmd.args.stencilRef.ref);
3998 f->glStencilFuncSeparate(GL_FRONT, toGlCompareOp(psD->m_stencilFront.compareOp), ref, psD->m_stencilReadMask);
3999 f->glStencilFuncSeparate(GL_BACK, toGlCompareOp(psD->m_stencilBack.compareOp), ref, psD->m_stencilReadMask);
4000 cbD->graphicsPassState.dynamic.stencilRef = ref;
4001 cbD->graphicsPassState.stencilRef = ref;
4002 } else {
4003 qWarning("No graphics pipeline active for setStencilRef; ignored");
4004 }
4005 }
4006 break;
4008 {
4009 QGles2GraphicsPipeline *psD = QRHI_RES(QGles2GraphicsPipeline, cmd.args.bindVertexBuffer.ps);
4010 if (psD) {
4011 if (state.lastBindVertexBuffer.ps == psD
4012 && state.lastBindVertexBuffer.buffer == cmd.args.bindVertexBuffer.buffer
4013 && state.lastBindVertexBuffer.offset == cmd.args.bindVertexBuffer.offset
4014 && state.lastBindVertexBuffer.binding == cmd.args.bindVertexBuffer.binding)
4015 {
4016 // The pipeline and so the vertex input layout is
4017 // immutable, no point in issuing the exact same set of
4018 // glVertexAttribPointer again and again for the same buffer.
4019 break;
4020 }
4021 state.lastBindVertexBuffer.ps = psD;
4022 state.lastBindVertexBuffer.buffer = cmd.args.bindVertexBuffer.buffer;
4023 state.lastBindVertexBuffer.offset = cmd.args.bindVertexBuffer.offset;
4024 state.lastBindVertexBuffer.binding = cmd.args.bindVertexBuffer.binding;
4025
4026 if (cmd.args.bindVertexBuffer.buffer != state.currentArrayBuffer) {
4027 state.currentArrayBuffer = cmd.args.bindVertexBuffer.buffer;
4028 // we do not support more than one vertex buffer
4029 f->glBindBuffer(GL_ARRAY_BUFFER, state.currentArrayBuffer);
4030 }
4031 for (auto it = psD->m_vertexInputLayout.cbeginAttributes(), itEnd = psD->m_vertexInputLayout.cendAttributes();
4032 it != itEnd; ++it)
4033 {
4034 const int bindingIdx = it->binding();
4035 if (bindingIdx != cmd.args.bindVertexBuffer.binding)
4036 continue;
4037
4038 const QRhiVertexInputBinding *inputBinding = psD->m_vertexInputLayout.bindingAt(bindingIdx);
4039 const int stride = int(inputBinding->stride());
4040 int size = 1;
4041 GLenum type = GL_FLOAT;
4042 bool normalize = false;
4043 switch (it->format()) {
4044 case QRhiVertexInputAttribute::Float4:
4045 type = GL_FLOAT;
4046 size = 4;
4047 break;
4048 case QRhiVertexInputAttribute::Float3:
4049 type = GL_FLOAT;
4050 size = 3;
4051 break;
4052 case QRhiVertexInputAttribute::Float2:
4053 type = GL_FLOAT;
4054 size = 2;
4055 break;
4056 case QRhiVertexInputAttribute::Float:
4057 type = GL_FLOAT;
4058 size = 1;
4059 break;
4060 case QRhiVertexInputAttribute::UNormByte4:
4061 type = GL_UNSIGNED_BYTE;
4062 normalize = true;
4063 size = 4;
4064 break;
4065 case QRhiVertexInputAttribute::UNormByte2:
4066 type = GL_UNSIGNED_BYTE;
4067 normalize = true;
4068 size = 2;
4069 break;
4070 case QRhiVertexInputAttribute::UNormByte:
4071 type = GL_UNSIGNED_BYTE;
4072 normalize = true;
4073 size = 1;
4074 break;
4075 case QRhiVertexInputAttribute::UInt4:
4076 type = GL_UNSIGNED_INT;
4077 size = 4;
4078 break;
4079 case QRhiVertexInputAttribute::UInt3:
4080 type = GL_UNSIGNED_INT;
4081 size = 3;
4082 break;
4083 case QRhiVertexInputAttribute::UInt2:
4084 type = GL_UNSIGNED_INT;
4085 size = 2;
4086 break;
4087 case QRhiVertexInputAttribute::UInt:
4088 type = GL_UNSIGNED_INT;
4089 size = 1;
4090 break;
4091 case QRhiVertexInputAttribute::SInt4:
4092 type = GL_INT;
4093 size = 4;
4094 break;
4095 case QRhiVertexInputAttribute::SInt3:
4096 type = GL_INT;
4097 size = 3;
4098 break;
4099 case QRhiVertexInputAttribute::SInt2:
4100 type = GL_INT;
4101 size = 2;
4102 break;
4103 case QRhiVertexInputAttribute::SInt:
4104 type = GL_INT;
4105 size = 1;
4106 break;
4107 case QRhiVertexInputAttribute::Half4:
4108 type = GL_HALF_FLOAT;
4109 size = 4;
4110 break;
4111 case QRhiVertexInputAttribute::Half3:
4112 type = GL_HALF_FLOAT;
4113 size = 3;
4114 break;
4115 case QRhiVertexInputAttribute::Half2:
4116 type = GL_HALF_FLOAT;
4117 size = 2;
4118 break;
4119 case QRhiVertexInputAttribute::Half:
4120 type = GL_HALF_FLOAT;
4121 size = 1;
4122 break;
4123 case QRhiVertexInputAttribute::UShort4:
4124 type = GL_UNSIGNED_SHORT;
4125 size = 4;
4126 break;
4127 case QRhiVertexInputAttribute::UShort3:
4128 type = GL_UNSIGNED_SHORT;
4129 size = 3;
4130 break;
4131 case QRhiVertexInputAttribute::UShort2:
4132 type = GL_UNSIGNED_SHORT;
4133 size = 2;
4134 break;
4135 case QRhiVertexInputAttribute::UShort:
4136 type = GL_UNSIGNED_SHORT;
4137 size = 1;
4138 break;
4139 case QRhiVertexInputAttribute::SShort4:
4140 type = GL_SHORT;
4141 size = 4;
4142 break;
4143 case QRhiVertexInputAttribute::SShort3:
4144 type = GL_SHORT;
4145 size = 3;
4146 break;
4147 case QRhiVertexInputAttribute::SShort2:
4148 type = GL_SHORT;
4149 size = 2;
4150 break;
4151 case QRhiVertexInputAttribute::SShort:
4152 type = GL_SHORT;
4153 size = 1;
4154 break;
4155 default:
4156 break;
4157 }
4158
4159 const int locationIdx = it->location();
4160 quint32 ofs = it->offset() + cmd.args.bindVertexBuffer.offset;
4161 if (type == GL_UNSIGNED_INT || type == GL_INT || type == GL_UNSIGNED_SHORT || type == GL_SHORT) {
4162 if (caps.intAttributes) {
4163 f->glVertexAttribIPointer(GLuint(locationIdx), size, type, stride,
4164 reinterpret_cast<const GLvoid *>(quintptr(ofs)));
4165 } else {
4166 qWarning("Current RHI backend does not support IntAttributes. Check supported features.");
4167 // This is a trick to disable this attribute
4169 state.enabledAttribArrays[locationIdx] = true;
4170 }
4171 } else {
4172 f->glVertexAttribPointer(GLuint(locationIdx), size, type, normalize, stride,
4173 reinterpret_cast<const GLvoid *>(quintptr(ofs)));
4174 }
4175 if (locationIdx >= CommandBufferExecTrackedState::TRACKED_ATTRIB_COUNT || !state.enabledAttribArrays[locationIdx]) {
4177 state.enabledAttribArrays[locationIdx] = true;
4178 f->glEnableVertexAttribArray(GLuint(locationIdx));
4179 }
4180 if (inputBinding->classification() == QRhiVertexInputBinding::PerInstance && caps.instancing) {
4181 f->glVertexAttribDivisor(GLuint(locationIdx), inputBinding->instanceStepRate());
4182 if (Q_LIKELY(locationIdx < CommandBufferExecTrackedState::TRACKED_ATTRIB_COUNT))
4183 state.nonzeroAttribDivisor[locationIdx] = true;
4184 else
4186 state.instancedAttributesUsed = true;
4188 && state.nonzeroAttribDivisor[locationIdx])
4189 || Q_UNLIKELY(locationIdx >= CommandBufferExecTrackedState::TRACKED_ATTRIB_COUNT
4190 && locationIdx <= state.maxUntrackedInstancedAttribute))
4191 {
4192 f->glVertexAttribDivisor(GLuint(locationIdx), 0);
4194 state.nonzeroAttribDivisor[locationIdx] = false;
4195 }
4196 }
4197 } else {
4198 qWarning("No graphics pipeline active for setVertexInput; ignored");
4199 }
4200 }
4201 break;
4203 state.indexType = cmd.args.bindIndexBuffer.type;
4204 state.indexStride = state.indexType == GL_UNSIGNED_SHORT ? sizeof(quint16) : sizeof(quint32);
4205 state.indexOffset = cmd.args.bindIndexBuffer.offset;
4206 if (state.currentElementArrayBuffer != cmd.args.bindIndexBuffer.buffer) {
4207 state.currentElementArrayBuffer = cmd.args.bindIndexBuffer.buffer;
4208 f->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, state.currentElementArrayBuffer);
4209 }
4210 break;
4212 {
4213 QGles2GraphicsPipeline *psD = QRHI_RES(QGles2GraphicsPipeline, cmd.args.draw.ps);
4214 if (psD) {
4215 const bool useBaseInstance = (cmd.args.draw.baseInstance != 0 && caps.baseInstance);
4216 // Same rationale as DrawIndexed below.
4217 const bool needsInstancedPath = caps.instancing
4218 && (cmd.args.draw.instanceCount != 1 || useBaseInstance);
4219
4220 if (!needsInstancedPath) {
4221 f->glDrawArrays(psD->drawMode, GLint(cmd.args.draw.firstVertex), GLsizei(cmd.args.draw.vertexCount));
4222 } else if (useBaseInstance) {
4224 GLint(cmd.args.draw.firstVertex),
4225 GLsizei(cmd.args.draw.vertexCount),
4226 GLsizei(cmd.args.draw.instanceCount),
4227 cmd.args.draw.baseInstance);
4228 } else {
4229 f->glDrawArraysInstanced(psD->drawMode, GLint(cmd.args.draw.firstVertex), GLsizei(cmd.args.draw.vertexCount),
4230 GLsizei(cmd.args.draw.instanceCount));
4231 }
4232 } else {
4233 qWarning("No graphics pipeline active for draw; ignored");
4234 }
4235 }
4236 break;
4238 {
4239 QGles2GraphicsPipeline *psD = QRHI_RES(QGles2GraphicsPipeline, cmd.args.drawIndexed.ps);
4240 if (psD) {
4241 const GLvoid *ofs = reinterpret_cast<const GLvoid *>(
4242 quintptr(cmd.args.drawIndexed.firstIndex * state.indexStride + state.indexOffset));
4243 const bool useBaseVertex = (cmd.args.drawIndexed.baseVertex != 0 && caps.baseVertex);
4244 const bool useBaseInstance = (cmd.args.drawIndexed.baseInstance != 0 && caps.baseInstance);
4245 // Take the *Instanced path with a non-zero baseInstance even
4246 // when instanceCount is 1: only those calls fetch per-instance
4247 // attributes at the base instance offset.
4248 const bool needsInstancedPath = caps.instancing
4249 && (cmd.args.drawIndexed.instanceCount != 1 || useBaseInstance);
4250
4251 if (!needsInstancedPath) {
4252 if (useBaseVertex) {
4253 f->glDrawElementsBaseVertex(psD->drawMode,
4254 GLsizei(cmd.args.drawIndexed.indexCount),
4255 state.indexType,
4256 ofs,
4257 cmd.args.drawIndexed.baseVertex);
4258 } else {
4259 f->glDrawElements(psD->drawMode,
4260 GLsizei(cmd.args.drawIndexed.indexCount),
4261 state.indexType,
4262 ofs);
4263 }
4264 } else if (useBaseInstance && useBaseVertex) {
4266 GLsizei(cmd.args.drawIndexed.indexCount),
4267 state.indexType,
4268 ofs,
4269 GLsizei(cmd.args.drawIndexed.instanceCount),
4270 cmd.args.drawIndexed.baseVertex,
4271 cmd.args.drawIndexed.baseInstance);
4272 } else if (useBaseInstance) {
4274 GLsizei(cmd.args.drawIndexed.indexCount),
4275 state.indexType,
4276 ofs,
4277 GLsizei(cmd.args.drawIndexed.instanceCount),
4278 cmd.args.drawIndexed.baseInstance);
4279 } else if (useBaseVertex) {
4280 f->glDrawElementsInstancedBaseVertex(psD->drawMode,
4281 GLsizei(cmd.args.drawIndexed.indexCount),
4282 state.indexType,
4283 ofs,
4284 GLsizei(cmd.args.drawIndexed.instanceCount),
4285 cmd.args.drawIndexed.baseVertex);
4286 } else {
4287 f->glDrawElementsInstanced(psD->drawMode,
4288 GLsizei(cmd.args.drawIndexed.indexCount),
4289 state.indexType,
4290 ofs,
4291 GLsizei(cmd.args.drawIndexed.instanceCount));
4292 }
4293 } else {
4294 qWarning("No graphics pipeline active for drawIndexed; ignored");
4295 }
4296 }
4297 break;
4299 {
4300 QGles2GraphicsPipeline *psD = QRHI_RES(QGles2GraphicsPipeline, cmd.args.drawIndirect.ps);
4301 if (psD) {
4302 f->glBindBuffer(GL_DRAW_INDIRECT_BUFFER, cmd.args.drawIndirect.buffer);
4304 const GLvoid *ofs = reinterpret_cast<const GLvoid *>(
4305 quintptr(cmd.args.drawIndirect.offset));
4306 glMultiDrawArraysIndirect(psD->drawMode,
4307 ofs,
4308 cmd.args.drawIndirect.drawCount,
4309 cmd.args.drawIndirect.stride);
4310 } else { // Fallback to issuing multiple single indirect draws
4311 for (quint32 i = 0; i < cmd.args.drawIndirect.drawCount; ++i) {
4312 const quintptr indirectOffset = quintptr(cmd.args.drawIndirect.offset)
4313 + quintptr(i) * cmd.args.drawIndirect.stride;
4314 const GLvoid *ofs = reinterpret_cast<const GLvoid *>(indirectOffset);
4315 f->glDrawArraysIndirect(psD->drawMode,
4316 ofs);
4317 }
4318 }
4319 f->glBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0);
4320 } else {
4321 qWarning("No graphics pipeline active for drawIndirect; ignored");
4322 }
4323 }
4324 break;
4326 {
4327 QGles2GraphicsPipeline *psD = QRHI_RES(QGles2GraphicsPipeline, cmd.args.drawIndexedIndirect.ps);
4328 if (psD) {
4329 f->glBindBuffer(GL_DRAW_INDIRECT_BUFFER, cmd.args.drawIndexedIndirect.buffer);
4331 const GLvoid *ofs = reinterpret_cast<const GLvoid *>(
4332 quintptr(cmd.args.drawIndexedIndirect.offset));
4334 state.indexType,
4335 ofs,
4336 cmd.args.drawIndexedIndirect.drawCount,
4337 cmd.args.drawIndexedIndirect.stride);
4338 } else { // Fallback to issuing multiple single indirect draws
4339 for (quint32 i = 0; i < cmd.args.drawIndexedIndirect.drawCount; ++i) {
4340 const quintptr indirectOffset = quintptr(cmd.args.drawIndexedIndirect.offset)
4341 + quintptr(i) * cmd.args.drawIndexedIndirect.stride;
4342 const GLvoid *ofs = reinterpret_cast<const GLvoid *>(indirectOffset);
4343 f->glDrawElementsIndirect(psD->drawMode,
4344 state.indexType,
4345 ofs);
4346 }
4347 }
4348 f->glBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0);
4349 } else {
4350 qWarning("No graphics pipeline active for drawIndexedIndirect; ignored");
4351 }
4352 }
4353 break;
4355 {
4356 QGles2GraphicsPipeline *psD = QRHI_RES(QGles2GraphicsPipeline, cmd.args.drawIndirectCount.ps);
4357 if (psD && glMultiDrawArraysIndirectCount) {
4358 f->glBindBuffer(GL_DRAW_INDIRECT_BUFFER, cmd.args.drawIndirectCount.buffer);
4359 f->glBindBuffer(GL_PARAMETER_BUFFER, cmd.args.drawIndirectCount.countBuffer);
4360 const GLvoid *ofs = reinterpret_cast<const GLvoid *>(
4361 quintptr(cmd.args.drawIndirectCount.offset));
4363 ofs,
4364 GLintptr(cmd.args.drawIndirectCount.countOffset),
4365 cmd.args.drawIndirectCount.maxDrawCount,
4366 cmd.args.drawIndirectCount.stride);
4367 f->glBindBuffer(GL_PARAMETER_BUFFER, 0);
4368 f->glBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0);
4369 } else {
4370 qWarning("No graphics pipeline active or glMultiDrawArraysIndirectCount unavailable; ignored");
4371 }
4372 }
4373 break;
4375 {
4376 QGles2GraphicsPipeline *psD = QRHI_RES(QGles2GraphicsPipeline, cmd.args.drawIndexedIndirectCount.ps);
4378 f->glBindBuffer(GL_DRAW_INDIRECT_BUFFER, cmd.args.drawIndexedIndirectCount.buffer);
4379 f->glBindBuffer(GL_PARAMETER_BUFFER, cmd.args.drawIndexedIndirectCount.countBuffer);
4380 const GLvoid *ofs = reinterpret_cast<const GLvoid *>(
4381 quintptr(cmd.args.drawIndexedIndirectCount.offset));
4383 state.indexType,
4384 ofs,
4385 GLintptr(cmd.args.drawIndexedIndirectCount.countOffset),
4386 cmd.args.drawIndexedIndirectCount.maxDrawCount,
4387 cmd.args.drawIndexedIndirectCount.stride);
4388 f->glBindBuffer(GL_PARAMETER_BUFFER, 0);
4389 f->glBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0);
4390 } else {
4391 qWarning("No graphics pipeline active or glMultiDrawElementsIndirectCount unavailable; ignored");
4392 }
4393 }
4394 break;
4396 executeBindGraphicsPipeline(cbD, QRHI_RES(QGles2GraphicsPipeline, cmd.args.bindGraphicsPipeline.ps));
4397 break;
4398 case QGles2CommandBuffer::Command::BindShaderResources:
4399 bindShaderResources(cbD,
4400 cmd.args.bindShaderResources.maybeGraphicsPs,
4401 cmd.args.bindShaderResources.maybeComputePs,
4402 cmd.args.bindShaderResources.srb,
4403 cbD->dynamicOffsetPool.constData() + cmd.args.bindShaderResources.dynamicOffsetPoolOffset,
4404 cmd.args.bindShaderResources.dynamicOffsetCount);
4405 break;
4407 {
4408 QRhiGraphicsPipeline *maybeGraphicsPs = cmd.args.setPushConstants.maybeGraphicsPs;
4409 QRhiComputePipeline *maybeComputePs = cmd.args.setPushConstants.maybeComputePs;
4410 const QGles2UniformDescriptionVector &uniforms(maybeGraphicsPs
4411 ? QRHI_RES(QGles2GraphicsPipeline, maybeGraphicsPs)->pushConstantUniforms
4412 : QRHI_RES(QGles2ComputePipeline, maybeComputePs)->pushConstantUniforms);
4413 QGles2UniformState *uniformState = maybeGraphicsPs
4414 ? QRHI_RES(QGles2GraphicsPipeline, maybeGraphicsPs)->uniformState.data()
4415 : QRHI_RES(QGles2ComputePipeline, maybeComputePs)->uniformState.data();
4416 setUniformsFromBlock(uniforms, -1,
4417 cbD->pushConstantPool.constData() + cmd.args.setPushConstants.dataOffset,
4418 cmd.args.setPushConstants.size, 0, uniformState);
4419 }
4420 break;
4422 {
4423 // Like with the other backends, each pass starts with a stencil
4424 // reference value of 0, regardless of what earlier passes set.
4425 cbD->graphicsPassState.dynamic.stencilRef = 0;
4426 QVarLengthArray<GLenum, 8> bufs;
4427 GLuint fbo = cmd.args.bindFramebuffer.fbo;
4428 if (!fbo)
4429 fbo = ctx->defaultFramebufferObject();
4430 f->glBindFramebuffer(GL_FRAMEBUFFER, fbo);
4431 if (fbo) {
4432 const int colorAttCount = cmd.args.bindFramebuffer.colorAttCount;
4433 bufs.append(colorAttCount > 0 ? GL_COLOR_ATTACHMENT0 : GL_NONE);
4434 if (caps.maxDrawBuffers > 1) {
4435 for (int i = 1; i < colorAttCount; ++i)
4436 bufs.append(GL_COLOR_ATTACHMENT0 + uint(i));
4437 }
4438 } else {
4439 if (cmd.args.bindFramebuffer.stereo && cmd.args.bindFramebuffer.stereoTarget == QRhiSwapChain::RightBuffer)
4440 bufs.append(GL_BACK_RIGHT);
4441 else
4442 bufs.append(caps.gles ? GL_BACK : GL_BACK_LEFT);
4443 }
4444 if (caps.hasDrawBuffersFunc)
4445 f->glDrawBuffers(bufs.count(), bufs.constData());
4446 if (caps.srgbWriteControl) {
4447 if (cmd.args.bindFramebuffer.srgb)
4448 f->glEnable(GL_FRAMEBUFFER_SRGB);
4449 else
4450 f->glDisable(GL_FRAMEBUFFER_SRGB);
4451 }
4452 }
4453 break;
4455 f->glDisable(GL_SCISSOR_TEST);
4456 if (cmd.args.clear.mask & GL_COLOR_BUFFER_BIT) {
4457 f->glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
4458 f->glClearColor(cmd.args.clear.c[0], cmd.args.clear.c[1], cmd.args.clear.c[2], cmd.args.clear.c[3]);
4459 }
4460 if (cmd.args.clear.mask & GL_DEPTH_BUFFER_BIT) {
4461 f->glDepthMask(GL_TRUE);
4462 f->glClearDepthf(cmd.args.clear.d);
4463 }
4464 if (cmd.args.clear.mask & GL_STENCIL_BUFFER_BIT) {
4465 f->glStencilMask(0xFF);
4466 f->glClearStencil(GLint(cmd.args.clear.s));
4467 }
4468 f->glClear(cmd.args.clear.mask);
4469 cbD->graphicsPassState.reset(); // altered depth/color write, invalidate in order to avoid confusing the state tracking
4470 break;
4472 bindVertexIndexBufferWithStateReset(&state, f, cmd.args.bufferSubData.target, cmd.args.bufferSubData.buffer);
4473 f->glBufferSubData(cmd.args.bufferSubData.target, cmd.args.bufferSubData.offset, cmd.args.bufferSubData.size,
4474 cmd.args.bufferSubData.data);
4475 break;
4477 bindVertexIndexBufferWithStateReset(&state, f, cmd.args.clearBufferSubData.target, cmd.args.clearBufferSubData.buffer);
4478 glClearBufferSubData(cmd.args.clearBufferSubData.target, GL_R8UI,
4479 cmd.args.clearBufferSubData.offset, cmd.args.clearBufferSubData.size,
4480 GL_RED_INTEGER, GL_UNSIGNED_BYTE, &cmd.args.clearBufferSubData.value);
4481 break;
4483 {
4484 const auto &a(cmd.args.clearBufferCompute);
4485 f->glUseProgram(clearBufferProgram);
4486 f->glUniform1ui(clearBufferUniformLoc[0], a.offsetWords);
4487 f->glUniform1ui(clearBufferUniformLoc[1], a.countWords);
4488 f->glUniform1ui(clearBufferUniformLoc[2], a.value);
4489 f->glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, a.buffer);
4490 const quint32 groups = qMin((a.countWords + 63u) / 64u,
4491 quint32(qMax(1, caps.maxThreadGroupsPerDimension)));
4492 f->glDispatchCompute(groups, 1, 1);
4493 f->glMemoryBarrier(barriersForBuffer());
4494 }
4495 break;
4497 {
4498 QRhiReadbackResult *result = cmd.args.getBufferSubData.result;
4499 bindVertexIndexBufferWithStateReset(&state, f, cmd.args.getBufferSubData.target, cmd.args.getBufferSubData.buffer);
4500 if (caps.gles) {
4501 if (caps.properMapBuffer) {
4502 void *p = f->glMapBufferRange(cmd.args.getBufferSubData.target,
4503 cmd.args.getBufferSubData.offset,
4504 cmd.args.getBufferSubData.size,
4506 if (p) {
4507 result->data.resize(cmd.args.getBufferSubData.size);
4508 memcpy(result->data.data(), p, size_t(cmd.args.getBufferSubData.size));
4509 f->glUnmapBuffer(cmd.args.getBufferSubData.target);
4510 }
4511 }
4512 } else {
4513 result->data.resize(cmd.args.getBufferSubData.size);
4514 f->glGetBufferSubData(cmd.args.getBufferSubData.target,
4515 cmd.args.getBufferSubData.offset,
4516 cmd.args.getBufferSubData.size,
4517 result->data.data());
4518 }
4519 if (result->completed)
4520 result->completed();
4521 }
4522 break;
4524 f->glBindBuffer(GL_COPY_READ_BUFFER, cmd.args.copyBuf.srcBuffer);
4525 f->glBindBuffer(GL_COPY_WRITE_BUFFER, cmd.args.copyBuf.dstBuffer);
4526 f->glCopyBufferSubData(GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER,
4527 cmd.args.copyBuf.srcOffset, cmd.args.copyBuf.dstOffset,
4528 cmd.args.copyBuf.size);
4529 f->glBindBuffer(GL_COPY_READ_BUFFER, 0);
4530 f->glBindBuffer(GL_COPY_WRITE_BUFFER, 0);
4531 break;
4533 {
4534 GLuint fbo;
4535 f->glGenFramebuffers(1, &fbo);
4536 f->glBindFramebuffer(GL_FRAMEBUFFER, fbo);
4537 if (cmd.args.copyTex.srcTarget == GL_TEXTURE_3D
4538 || cmd.args.copyTex.srcTarget == GL_TEXTURE_2D_ARRAY
4539 || cmd.args.copyTex.srcTarget == GL_TEXTURE_1D_ARRAY) {
4540 f->glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, cmd.args.copyTex.srcTexture,
4541 cmd.args.copyTex.srcLevel, cmd.args.copyTex.srcZ);
4542 } else if (cmd.args.copyTex.srcTarget == GL_TEXTURE_1D) {
4543 glFramebufferTexture1D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
4544 cmd.args.copyTex.srcTarget, cmd.args.copyTex.srcTexture,
4545 cmd.args.copyTex.srcLevel);
4546 } else {
4547 f->glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
4548 cmd.args.copyTex.srcFaceTarget, cmd.args.copyTex.srcTexture, cmd.args.copyTex.srcLevel);
4549 }
4550 f->glBindTexture(cmd.args.copyTex.dstTarget, cmd.args.copyTex.dstTexture);
4551 if (cmd.args.copyTex.dstTarget == GL_TEXTURE_3D || cmd.args.copyTex.dstTarget == GL_TEXTURE_2D_ARRAY) {
4552 f->glCopyTexSubImage3D(cmd.args.copyTex.dstTarget, cmd.args.copyTex.dstLevel,
4553 cmd.args.copyTex.dstX, cmd.args.copyTex.dstY, cmd.args.copyTex.dstZ,
4554 cmd.args.copyTex.srcX, cmd.args.copyTex.srcY,
4555 cmd.args.copyTex.w, cmd.args.copyTex.h);
4556 } else if (cmd.args.copyTex.dstTarget == GL_TEXTURE_1D) {
4557 glCopyTexSubImage1D(cmd.args.copyTex.dstTarget, cmd.args.copyTex.dstLevel,
4558 cmd.args.copyTex.dstX, cmd.args.copyTex.srcX,
4559 cmd.args.copyTex.srcY, cmd.args.copyTex.w);
4560 } else {
4561 f->glCopyTexSubImage2D(cmd.args.copyTex.dstFaceTarget, cmd.args.copyTex.dstLevel,
4562 cmd.args.copyTex.dstX, cmd.args.copyTex.dstY,
4563 cmd.args.copyTex.srcX, cmd.args.copyTex.srcY,
4564 cmd.args.copyTex.w, cmd.args.copyTex.h);
4565 }
4566 f->glBindFramebuffer(GL_FRAMEBUFFER, ctx->defaultFramebufferObject());
4567 f->glDeleteFramebuffers(1, &fbo);
4568 }
4569 break;
4571 {
4572 QRhiReadbackResult *result = cmd.args.readPixels.result;
4573 GLuint tex = cmd.args.readPixels.texture;
4574 GLuint fbo = 0;
4575 int mipLevel = 0;
4576 result->pixelSize = QSize(cmd.args.readPixels.w, cmd.args.readPixels.h);
4577 if (tex) {
4578 result->format = cmd.args.readPixels.format;
4579 mipLevel = cmd.args.readPixels.level;
4580 if (mipLevel == 0 || caps.nonBaseLevelFramebufferTexture) {
4581 f->glGenFramebuffers(1, &fbo);
4582 f->glBindFramebuffer(GL_FRAMEBUFFER, fbo);
4583 const auto attach = [&](GLenum attachment) {
4584 if (cmd.args.readPixels.slice3D >= 0) {
4585 f->glFramebufferTextureLayer(GL_FRAMEBUFFER, attachment,
4586 tex, mipLevel, cmd.args.readPixels.slice3D);
4587 } else if (cmd.args.readPixels.readTarget == GL_TEXTURE_1D) {
4588 glFramebufferTexture1D(GL_FRAMEBUFFER, attachment,
4589 cmd.args.readPixels.readTarget, tex, mipLevel);
4590 } else {
4591 f->glFramebufferTexture2D(GL_FRAMEBUFFER, attachment,
4592 cmd.args.readPixels.readTarget, tex, mipLevel);
4593 }
4594 };
4595 // A depth(-stencil) texture cannot be attached as a color attachment.
4596 if (isDepthTextureFormat(result->format)) {
4597 attach(GL_DEPTH_ATTACHMENT);
4598 if (isStencilSupportingFormat(result->format))
4599 attach(GL_STENCIL_ATTACHMENT);
4600 // There is no color attachment, which would make the FBO incomplete
4601 // on desktop GL < 4.1 unless the read buffer is set to none.
4602 if (!caps.gles)
4603 f->glReadBuffer(GL_NONE);
4604 } else {
4605 attach(GL_COLOR_ATTACHMENT0);
4606 }
4607 }
4608 } else {
4609 result->format = QRhiTexture::RGBA8;
4610 // readPixels handles multisample resolving implicitly
4611 }
4612 const int x = cmd.args.readPixels.x;
4613 const int y = cmd.args.readPixels.y;
4614 const int w = cmd.args.readPixels.w;
4615 const int h = cmd.args.readPixels.h;
4616 if (mipLevel == 0 || caps.nonBaseLevelFramebufferTexture) {
4617 // With GLES, GL_RGBA is the only mandated readback format, so stick with it.
4618 // (and that's why we return false for the ReadBackAnyTextureFormat feature)
4619 if (result->format == QRhiTexture::R8 || result->format == QRhiTexture::RED_OR_ALPHA8) {
4620 result->data.resizeForOverwrite(w * h);
4621 QByteArray tmpBuf;
4622 tmpBuf.resizeForOverwrite(w * h * 4);
4623 f->glReadPixels(x, y, w, h, GL_RGBA, GL_UNSIGNED_BYTE, tmpBuf.data());
4624 const quint8 *srcBase = reinterpret_cast<const quint8 *>(tmpBuf.constData());
4625 quint8 *dstBase = reinterpret_cast<quint8 *>(result->data.data());
4626 const int componentIndex = result->format == QRhiTexture::R8
4627 || isFeatureSupported(QRhi::RedOrAlpha8IsRed)
4628 ? 0
4629 : 3;
4630 for (int y = 0; y < h; ++y) {
4631 const quint8 *src = srcBase + y * w * 4;
4632 quint8 *dst = dstBase + y * w;
4633 int count = w;
4634 while (count-- > 0) {
4635 *dst++ = src[componentIndex];
4636 src += 4;
4637 }
4638 }
4639 } else {
4640 // For other formats try it because this can be relevant for some use cases;
4641 // if it works, then fine, if not, there's nothing we can do.
4642 [[maybe_unused]] GLenum glintformat;
4643 [[maybe_unused]] GLenum glsizedintformat;
4644 GLenum glformat;
4645 GLenum gltype;
4646 toGlTextureFormat(result->format, {}, caps,
4647 &glintformat, &glsizedintformat, &glformat, &gltype);
4648 quint32 byteSize;
4649 textureFormatInfo(result->format, result->pixelSize, nullptr, &byteSize, nullptr);
4650 result->data.resizeForOverwrite(byteSize);
4651 // The result is tightly packed, unlike with the default alignment of 4.
4652 f->glPixelStorei(GL_PACK_ALIGNMENT, 1);
4653 f->glReadPixels(x, y, w, h, glformat, gltype, result->data.data());
4654 f->glPixelStorei(GL_PACK_ALIGNMENT, 4);
4655 // QRhi guarantees the unused bits of a depth readback to be zero. With D24
4656 // the depth is normalized to 32 bits, but only the top 24 bits are
4657 // meaningful, with D32FS8 only the lowest 8 bits of the second word are.
4658 if (result->format == QRhiTexture::D24 || result->format == QRhiTexture::D32FS8) {
4659 const bool isD24 = result->format == QRhiTexture::D24;
4660 const quint32 mask = isD24 ? 0xFFFFFF00u : 0xFFu;
4661 char *p = result->data.data();
4662 for (qsizetype i = isD24 ? 0 : 1, count = result->data.size() / 4; i < count; i += isD24 ? 1 : 2)
4663 qToUnaligned(qFromUnaligned<quint32>(p + i * 4) & mask, p + i * 4);
4664 }
4665 }
4666 } else {
4667 // this level can't be read back; return a zero-filled image sized for the format
4668 quint32 byteSize = 0;
4669 textureFormatInfo(result->format, result->pixelSize, nullptr, &byteSize, nullptr);
4670 result->data.fill('\0', byteSize);
4671 }
4672 if (fbo) {
4673 f->glBindFramebuffer(GL_FRAMEBUFFER, ctx->defaultFramebufferObject());
4674 f->glDeleteFramebuffers(1, &fbo);
4675 }
4676 if (result->completed)
4677 result->completed();
4678 }
4679 break;
4681 f->glBindTexture(cmd.args.subImage.target, cmd.args.subImage.texture);
4682 if (cmd.args.subImage.rowStartAlign != 4)
4683 f->glPixelStorei(GL_UNPACK_ALIGNMENT, cmd.args.subImage.rowStartAlign);
4684 if (cmd.args.subImage.rowLength != 0)
4685 f->glPixelStorei(GL_UNPACK_ROW_LENGTH, cmd.args.subImage.rowLength);
4686 if (cmd.args.subImage.target == GL_TEXTURE_3D || cmd.args.subImage.target == GL_TEXTURE_2D_ARRAY) {
4687 f->glTexSubImage3D(cmd.args.subImage.target, cmd.args.subImage.level,
4688 cmd.args.subImage.dx, cmd.args.subImage.dy, cmd.args.subImage.dz,
4689 cmd.args.subImage.w, cmd.args.subImage.h, 1,
4690 cmd.args.subImage.glformat, cmd.args.subImage.gltype,
4691 cmd.args.subImage.data);
4692 } else if (cmd.args.subImage.target == GL_TEXTURE_1D) {
4693 glTexSubImage1D(cmd.args.subImage.target, cmd.args.subImage.level,
4694 cmd.args.subImage.dx, cmd.args.subImage.w,
4695 cmd.args.subImage.glformat, cmd.args.subImage.gltype,
4696 cmd.args.subImage.data);
4697 } else {
4698 f->glTexSubImage2D(cmd.args.subImage.faceTarget, cmd.args.subImage.level,
4699 cmd.args.subImage.dx, cmd.args.subImage.dy,
4700 cmd.args.subImage.w, cmd.args.subImage.h,
4701 cmd.args.subImage.glformat, cmd.args.subImage.gltype,
4702 cmd.args.subImage.data);
4703 }
4704 if (cmd.args.subImage.rowStartAlign != 4)
4705 f->glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
4706 if (cmd.args.subImage.rowLength != 0)
4707 f->glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
4708 break;
4710 f->glBindTexture(cmd.args.compressedImage.target, cmd.args.compressedImage.texture);
4711 if (cmd.args.compressedImage.target == GL_TEXTURE_3D || cmd.args.compressedImage.target == GL_TEXTURE_2D_ARRAY) {
4712 f->glCompressedTexImage3D(cmd.args.compressedImage.target, cmd.args.compressedImage.level,
4713 cmd.args.compressedImage.glintformat,
4714 cmd.args.compressedImage.w, cmd.args.compressedImage.h, cmd.args.compressedImage.depth,
4715 0, cmd.args.compressedImage.size, cmd.args.compressedImage.data);
4716 } else if (cmd.args.compressedImage.target == GL_TEXTURE_1D) {
4718 cmd.args.compressedImage.target, cmd.args.compressedImage.level,
4719 cmd.args.compressedImage.glintformat, cmd.args.compressedImage.w, 0,
4720 cmd.args.compressedImage.size, cmd.args.compressedImage.data);
4721 } else {
4722 f->glCompressedTexImage2D(cmd.args.compressedImage.faceTarget, cmd.args.compressedImage.level,
4723 cmd.args.compressedImage.glintformat,
4724 cmd.args.compressedImage.w, cmd.args.compressedImage.h,
4725 0, cmd.args.compressedImage.size, cmd.args.compressedImage.data);
4726 }
4727 break;
4729 f->glBindTexture(cmd.args.compressedSubImage.target, cmd.args.compressedSubImage.texture);
4730 if (cmd.args.compressedSubImage.target == GL_TEXTURE_3D || cmd.args.compressedSubImage.target == GL_TEXTURE_2D_ARRAY) {
4731 f->glCompressedTexSubImage3D(cmd.args.compressedSubImage.target, cmd.args.compressedSubImage.level,
4732 cmd.args.compressedSubImage.dx, cmd.args.compressedSubImage.dy, cmd.args.compressedSubImage.dz,
4733 cmd.args.compressedSubImage.w, cmd.args.compressedSubImage.h, 1,
4734 cmd.args.compressedSubImage.glintformat,
4735 cmd.args.compressedSubImage.size, cmd.args.compressedSubImage.data);
4736 } else if (cmd.args.compressedImage.target == GL_TEXTURE_1D) {
4738 cmd.args.compressedSubImage.target, cmd.args.compressedSubImage.level,
4739 cmd.args.compressedSubImage.dx, cmd.args.compressedSubImage.w,
4740 cmd.args.compressedSubImage.glintformat, cmd.args.compressedSubImage.size,
4741 cmd.args.compressedSubImage.data);
4742 } else {
4743 f->glCompressedTexSubImage2D(cmd.args.compressedSubImage.faceTarget, cmd.args.compressedSubImage.level,
4744 cmd.args.compressedSubImage.dx, cmd.args.compressedSubImage.dy,
4745 cmd.args.compressedSubImage.w, cmd.args.compressedSubImage.h,
4746 cmd.args.compressedSubImage.glintformat,
4747 cmd.args.compressedSubImage.size, cmd.args.compressedSubImage.data);
4748 }
4749 break;
4751 {
4752 // Altering the scissor state, so reset the stored state, although
4753 // not strictly required as long as blit is done in endPass() only.
4754 cbD->graphicsPassState.reset();
4755 f->glDisable(GL_SCISSOR_TEST);
4756 GLuint fbo[2];
4757 f->glGenFramebuffers(2, fbo);
4758 f->glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo[0]);
4759 const bool ds = cmd.args.blitFromRenderbuffer.isDepthStencil;
4760 const bool hasStencil = ds && cmd.args.blitFromRenderbuffer.hasStencil;
4761 if (ds) {
4762 f->glFramebufferRenderbuffer(GL_READ_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
4763 GL_RENDERBUFFER, cmd.args.blitFromRenderbuffer.renderbuffer);
4764 if (hasStencil) {
4765 // With a packed depth-stencil renderbuffer stencilRenderbuffer is 0.
4766 const GLuint srcStencilRb = cmd.args.blitFromRenderbuffer.stencilRenderbuffer
4767 ? cmd.args.blitFromRenderbuffer.stencilRenderbuffer
4768 : cmd.args.blitFromRenderbuffer.renderbuffer;
4769 f->glFramebufferRenderbuffer(GL_READ_FRAMEBUFFER, GL_STENCIL_ATTACHMENT,
4770 GL_RENDERBUFFER, srcStencilRb);
4771 }
4772 } else {
4773 f->glFramebufferRenderbuffer(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
4774 GL_RENDERBUFFER, cmd.args.blitFromRenderbuffer.renderbuffer);
4775 }
4776 f->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo[1]);
4777 if (cmd.args.blitFromRenderbuffer.target == GL_TEXTURE_3D || cmd.args.blitFromRenderbuffer.target == GL_TEXTURE_2D_ARRAY) {
4778 if (ds) {
4779 f->glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
4780 cmd.args.blitFromRenderbuffer.dstTexture,
4781 cmd.args.blitFromRenderbuffer.dstLevel,
4782 cmd.args.blitFromRenderbuffer.dstLayer);
4783 if (hasStencil) {
4784 f->glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT,
4785 cmd.args.blitFromRenderbuffer.dstTexture,
4786 cmd.args.blitFromRenderbuffer.dstLevel,
4787 cmd.args.blitFromRenderbuffer.dstLayer);
4788 }
4789 } else {
4790 f->glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
4791 cmd.args.blitFromRenderbuffer.dstTexture,
4792 cmd.args.blitFromRenderbuffer.dstLevel,
4793 cmd.args.blitFromRenderbuffer.dstLayer);
4794 }
4795 } else {
4796 if (ds) {
4797 f->glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, cmd.args.blitFromRenderbuffer.target,
4798 cmd.args.blitFromRenderbuffer.dstTexture, cmd.args.blitFromRenderbuffer.dstLevel);
4799 if (hasStencil) {
4800 f->glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, cmd.args.blitFromRenderbuffer.target,
4801 cmd.args.blitFromRenderbuffer.dstTexture, cmd.args.blitFromRenderbuffer.dstLevel);
4802 }
4803 } else {
4804 f->glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, cmd.args.blitFromRenderbuffer.target,
4805 cmd.args.blitFromRenderbuffer.dstTexture, cmd.args.blitFromRenderbuffer.dstLevel);
4806 }
4807 }
4808 if (ds && !caps.gles) {
4809 f->glReadBuffer(GL_NONE);
4810 const GLenum noBuf = GL_NONE;
4811 f->glDrawBuffers(1, &noBuf);
4812 }
4813 const GLbitfield rbBlitMask = ds ? (GL_DEPTH_BUFFER_BIT | (hasStencil ? GL_STENCIL_BUFFER_BIT : 0))
4814 : GL_COLOR_BUFFER_BIT;
4815 f->glBlitFramebuffer(0, 0, cmd.args.blitFromRenderbuffer.w, cmd.args.blitFromRenderbuffer.h,
4816 0, 0, cmd.args.blitFromRenderbuffer.w, cmd.args.blitFromRenderbuffer.h,
4817 rbBlitMask,
4818 GL_NEAREST); // Qt 5 used Nearest when resolving samples, stick to that
4819 f->glBindFramebuffer(GL_FRAMEBUFFER, ctx->defaultFramebufferObject());
4820 f->glDeleteFramebuffers(2, fbo);
4821 }
4822 break;
4824 {
4825 // Altering the scissor state, so reset the stored state, although
4826 // not strictly required as long as blit is done in endPass() only.
4827 cbD->graphicsPassState.reset();
4828 f->glDisable(GL_SCISSOR_TEST);
4829 GLuint fbo[2];
4830 f->glGenFramebuffers(2, fbo);
4831 f->glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo[0]);
4832 const bool ds = cmd.args.blitFromTexture.isDepthStencil;
4833 const bool hasStencil = ds && cmd.args.blitFromTexture.hasStencil;
4834 if (cmd.args.blitFromTexture.srcTarget == GL_TEXTURE_2D_MULTISAMPLE_ARRAY) {
4835 if (ds) {
4836 f->glFramebufferTextureLayer(GL_READ_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
4837 cmd.args.blitFromTexture.srcTexture,
4838 cmd.args.blitFromTexture.srcLevel,
4839 cmd.args.blitFromTexture.srcLayer);
4840 if (hasStencil) {
4841 f->glFramebufferTextureLayer(GL_READ_FRAMEBUFFER, GL_STENCIL_ATTACHMENT,
4842 cmd.args.blitFromTexture.srcTexture,
4843 cmd.args.blitFromTexture.srcLevel,
4844 cmd.args.blitFromTexture.srcLayer);
4845 }
4846 } else {
4847 f->glFramebufferTextureLayer(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
4848 cmd.args.blitFromTexture.srcTexture,
4849 cmd.args.blitFromTexture.srcLevel,
4850 cmd.args.blitFromTexture.srcLayer);
4851 }
4852 } else {
4853 if (ds) {
4854 f->glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, cmd.args.blitFromTexture.srcTarget,
4855 cmd.args.blitFromTexture.srcTexture, cmd.args.blitFromTexture.srcLevel);
4856 if (hasStencil) {
4857 f->glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, cmd.args.blitFromTexture.srcTarget,
4858 cmd.args.blitFromTexture.srcTexture, cmd.args.blitFromTexture.srcLevel);
4859 }
4860 } else {
4861 f->glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, cmd.args.blitFromTexture.srcTarget,
4862 cmd.args.blitFromTexture.srcTexture, cmd.args.blitFromTexture.srcLevel);
4863 }
4864 }
4865 f->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo[1]);
4866 if (cmd.args.blitFromTexture.dstTarget == GL_TEXTURE_3D || cmd.args.blitFromTexture.dstTarget == GL_TEXTURE_2D_ARRAY) {
4867 if (ds) {
4868 f->glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
4869 cmd.args.blitFromTexture.dstTexture,
4870 cmd.args.blitFromTexture.dstLevel,
4871 cmd.args.blitFromTexture.dstLayer);
4872 if (hasStencil) {
4873 f->glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT,
4874 cmd.args.blitFromTexture.dstTexture,
4875 cmd.args.blitFromTexture.dstLevel,
4876 cmd.args.blitFromTexture.dstLayer);
4877 }
4878 } else {
4879 f->glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
4880 cmd.args.blitFromTexture.dstTexture,
4881 cmd.args.blitFromTexture.dstLevel,
4882 cmd.args.blitFromTexture.dstLayer);
4883 }
4884 } else {
4885 if (ds) {
4886 f->glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, cmd.args.blitFromTexture.dstTarget,
4887 cmd.args.blitFromTexture.dstTexture, cmd.args.blitFromTexture.dstLevel);
4888 if (hasStencil) {
4889 f->glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, cmd.args.blitFromTexture.dstTarget,
4890 cmd.args.blitFromTexture.dstTexture, cmd.args.blitFromTexture.dstLevel);
4891 }
4892 } else {
4893 f->glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, cmd.args.blitFromTexture.dstTarget,
4894 cmd.args.blitFromTexture.dstTexture, cmd.args.blitFromTexture.dstLevel);
4895 }
4896 }
4897 if (ds && !caps.gles) {
4898 f->glReadBuffer(GL_NONE);
4899 const GLenum noBuf = GL_NONE;
4900 f->glDrawBuffers(1, &noBuf);
4901 }
4902 const GLbitfield texBlitMask = ds ? (GL_DEPTH_BUFFER_BIT | (hasStencil ? GL_STENCIL_BUFFER_BIT : 0))
4903 : GL_COLOR_BUFFER_BIT;
4904 f->glBlitFramebuffer(0, 0, cmd.args.blitFromTexture.w, cmd.args.blitFromTexture.h,
4905 0, 0, cmd.args.blitFromTexture.w, cmd.args.blitFromTexture.h,
4906 texBlitMask,
4907 GL_NEAREST); // Qt 5 used Nearest when resolving samples, stick to that
4908 f->glBindFramebuffer(GL_FRAMEBUFFER, ctx->defaultFramebufferObject());
4909 f->glDeleteFramebuffers(2, fbo);
4910 }
4911 break;
4913 f->glBindTexture(cmd.args.genMip.target, cmd.args.genMip.texture);
4914 f->glGenerateMipmap(cmd.args.genMip.target);
4915 break;
4917 {
4918 QGles2ComputePipeline *psD = QRHI_RES(QGles2ComputePipeline, cmd.args.bindComputePipeline.ps);
4919 f->glUseProgram(psD->program);
4920 }
4921 break;
4923 f->glDispatchCompute(cmd.args.dispatch.x, cmd.args.dispatch.y, cmd.args.dispatch.z);
4924 break;
4926 {
4927 f->glBindBuffer(GL_DISPATCH_INDIRECT_BUFFER, cmd.args.dispatchIndirect.buffer);
4928 f->glDispatchComputeIndirect(GLintptr(cmd.args.dispatchIndirect.offset));
4929 f->glBindBuffer(GL_DISPATCH_INDIRECT_BUFFER, 0);
4930 }
4931 break;
4933 {
4934 if (!caps.compute)
4935 break;
4936 GLbitfield barriers = 0;
4937 QRhiPassResourceTracker &tracker(cbD->passResTrackers[cmd.args.barriersForPass.trackerIndex]);
4938 // we only care about after-write, not any other accesses, and
4939 // cannot tell if something was written in a shader several passes
4940 // ago: now the previously written resource may be used with an
4941 // access that was not in the previous passes, result in a missing
4942 // barrier in theory. Hence setting all barrier bits whenever
4943 // something previously written is used for the first time in a
4944 // subsequent pass.
4945 for (const auto &[rhiB, trackedB]: tracker.buffers()) {
4946 Q_UNUSED(rhiB)
4947 QGles2Buffer::Access accessBeforePass = QGles2Buffer::Access(trackedB.stateAtPassBegin.access);
4948 if (bufferAccessIsWrite(accessBeforePass))
4949 barriers |= barriersForBuffer();
4950 }
4951 for (const auto &[rhiT, trackedT]: tracker.textures()) {
4952 Q_UNUSED(rhiT)
4953 QGles2Texture::Access accessBeforePass = QGles2Texture::Access(trackedT.stateAtPassBegin.access);
4954 if (textureAccessIsWrite(accessBeforePass))
4955 barriers |= barriersForTexture();
4956 }
4957 if (barriers)
4958 f->glMemoryBarrier(barriers);
4959 }
4960 break;
4962 if (caps.compute)
4963 f->glMemoryBarrier(cmd.args.barrier.barriers);
4964 break;
4966 if (caps.memoryBarrierByRegion)
4967 f->glMemoryBarrierByRegion(cmd.args.barrier.barriers);
4968 break;
4970 if (caps.gles && caps.ctxMajor >= 3) {
4971 f->glBindFramebuffer(GL_FRAMEBUFFER, cmd.args.invalidateFramebuffer.fbo);
4972 f->glInvalidateFramebuffer(GL_DRAW_FRAMEBUFFER,
4973 cmd.args.invalidateFramebuffer.attCount,
4974 cmd.args.invalidateFramebuffer.att);
4975 }
4976 break;
4977 default:
4978 break;
4979 }
4980 }
4981 if (state.instancedAttributesUsed) {
4982 for (int i = 0; i < CommandBufferExecTrackedState::TRACKED_ATTRIB_COUNT; ++i) {
4983 if (state.nonzeroAttribDivisor[i])
4984 f->glVertexAttribDivisor(GLuint(i), 0);
4985 }
4987 f->glVertexAttribDivisor(GLuint(i), 0);
4988 }
4989}
4990
4992{
4993 QGles2CommandBuffer::GraphicsPassState &state(cbD->graphicsPassState);
4994 const bool forceUpdate = !state.valid;
4995 state.valid = true;
4996
4997 const bool scissor = psD->m_flags.testFlag(QRhiGraphicsPipeline::UsesScissor);
4998 if (forceUpdate || scissor != state.scissor) {
4999 state.scissor = scissor;
5000 if (scissor)
5001 f->glEnable(GL_SCISSOR_TEST);
5002 else
5003 f->glDisable(GL_SCISSOR_TEST);
5004 }
5005
5006 const bool cullFace = psD->m_cullMode != QRhiGraphicsPipeline::None;
5007 const GLenum cullMode = cullFace ? toGlCullMode(psD->m_cullMode) : GL_NONE;
5008 if (forceUpdate || cullFace != state.cullFace || cullMode != state.cullMode) {
5009 state.cullFace = cullFace;
5010 state.cullMode = cullMode;
5011 if (cullFace) {
5012 f->glEnable(GL_CULL_FACE);
5013 f->glCullFace(cullMode);
5014 } else {
5015 f->glDisable(GL_CULL_FACE);
5016 }
5017 }
5018
5019 const GLenum frontFace = toGlFrontFace(psD->m_frontFace);
5020 if (forceUpdate || frontFace != state.frontFace) {
5021 state.frontFace = frontFace;
5022 f->glFrontFace(frontFace);
5023 }
5024
5025 const GLenum polygonMode = toGlPolygonMode(psD->m_polygonMode);
5026 if (glPolygonMode && (forceUpdate || polygonMode != state.polygonMode)) {
5027 state.polygonMode = polygonMode;
5028 glPolygonMode(GL_FRONT_AND_BACK, polygonMode);
5029 }
5030
5031 if (!psD->m_targetBlends.isEmpty()) {
5032 GLint buffer = 0;
5033 bool anyBlendEnabled = false;
5034 for (const auto targetBlend : psD->m_targetBlends) {
5035 const QGles2CommandBuffer::GraphicsPassState::ColorMask colorMask = {
5036 targetBlend.colorWrite.testFlag(QRhiGraphicsPipeline::R),
5037 targetBlend.colorWrite.testFlag(QRhiGraphicsPipeline::G),
5038 targetBlend.colorWrite.testFlag(QRhiGraphicsPipeline::B),
5039 targetBlend.colorWrite.testFlag(QRhiGraphicsPipeline::A)
5040 };
5041 if (forceUpdate || colorMask != state.colorMask[buffer]) {
5042 state.colorMask[buffer] = colorMask;
5043 if (caps.perRenderTargetBlending)
5044 f->glColorMaski(buffer, colorMask.r, colorMask.g, colorMask.b, colorMask.a);
5045 else
5046 f->glColorMask(colorMask.r, colorMask.g, colorMask.b, colorMask.a);
5047 }
5048
5049 const bool blendEnabled = targetBlend.enable;
5050 const QGles2CommandBuffer::GraphicsPassState::Blend blend = {
5051 toGlBlendFactor(targetBlend.srcColor),
5052 toGlBlendFactor(targetBlend.dstColor),
5053 toGlBlendFactor(targetBlend.srcAlpha),
5054 toGlBlendFactor(targetBlend.dstAlpha),
5055 toGlBlendOp(targetBlend.opColor),
5056 toGlBlendOp(targetBlend.opAlpha)
5057 };
5058 anyBlendEnabled |= blendEnabled;
5059 if (forceUpdate || blendEnabled != state.blendEnabled[buffer] || (blendEnabled && blend != state.blend[buffer])) {
5060 state.blendEnabled[buffer] = blendEnabled;
5061 if (blendEnabled) {
5062 state.blend[buffer] = blend;
5063 if (caps.perRenderTargetBlending) {
5064 f->glBlendFuncSeparatei(buffer, blend.srcColor, blend.dstColor, blend.srcAlpha, blend.dstAlpha);
5065 f->glBlendEquationSeparatei(buffer, blend.opColor, blend.opAlpha);
5066 } else {
5067 f->glBlendFuncSeparate(blend.srcColor, blend.dstColor, blend.srcAlpha, blend.dstAlpha);
5068 f->glBlendEquationSeparate(blend.opColor, blend.opAlpha);
5069 }
5070 }
5071 }
5072 buffer++;
5073 if (!caps.perRenderTargetBlending)
5074 break;
5075 }
5076 if (anyBlendEnabled)
5077 f->glEnable(GL_BLEND);
5078 else
5079 f->glDisable(GL_BLEND);
5080 } else {
5081 const QGles2CommandBuffer::GraphicsPassState::ColorMask colorMask = { true, true, true, true };
5082 if (forceUpdate || colorMask != state.colorMask[0]) {
5083 state.colorMask[0] = colorMask;
5084 f->glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
5085 }
5086 const bool blendEnabled = false;
5087 if (forceUpdate || blendEnabled != state.blendEnabled[0]) {
5088 state.blendEnabled[0] = blendEnabled;
5089 f->glDisable(GL_BLEND);
5090 }
5091 }
5092
5093 const bool depthTest = psD->m_depthTest;
5094 if (forceUpdate || depthTest != state.depthTest) {
5095 state.depthTest = depthTest;
5096 if (depthTest)
5097 f->glEnable(GL_DEPTH_TEST);
5098 else
5099 f->glDisable(GL_DEPTH_TEST);
5100 }
5101
5102 const bool depthWrite = psD->m_depthWrite;
5103 if (forceUpdate || depthWrite != state.depthWrite) {
5104 state.depthWrite = depthWrite;
5105 f->glDepthMask(depthWrite);
5106 }
5107
5108 const bool depthClamp = psD->m_depthClamp;
5109 if (caps.depthClamp && (forceUpdate || depthClamp != state.depthClamp)) {
5110 state.depthClamp = depthClamp;
5111 if (depthClamp)
5112 f->glEnable(GL_DEPTH_CLAMP);
5113 else
5114 f->glDisable(GL_DEPTH_CLAMP);
5115 }
5116
5117 const GLenum depthFunc = toGlCompareOp(psD->m_depthOp);
5118 if (forceUpdate || depthFunc != state.depthFunc) {
5119 state.depthFunc = depthFunc;
5120 f->glDepthFunc(depthFunc);
5121 }
5122
5123 const bool stencilTest = psD->m_stencilTest;
5124 const GLuint stencilReadMask = psD->m_stencilReadMask;
5125 const GLuint stencilWriteMask = psD->m_stencilWriteMask;
5126 // The stencil reference value is global state in OpenGL, but in QRhi it is
5127 // only dynamic for pipelines with UsesStencilRef.
5128 const GLint stencilRef = psD->m_flags.testFlag(QRhiGraphicsPipeline::UsesStencilRef)
5129 ? state.dynamic.stencilRef : 0;
5130 const QGles2CommandBuffer::GraphicsPassState::StencilFace stencilFront = {
5131 toGlCompareOp(psD->m_stencilFront.compareOp),
5132 toGlStencilOp(psD->m_stencilFront.failOp),
5133 toGlStencilOp(psD->m_stencilFront.depthFailOp),
5134 toGlStencilOp(psD->m_stencilFront.passOp)
5135 };
5136 const QGles2CommandBuffer::GraphicsPassState::StencilFace stencilBack = {
5137 toGlCompareOp(psD->m_stencilBack.compareOp),
5138 toGlStencilOp(psD->m_stencilBack.failOp),
5139 toGlStencilOp(psD->m_stencilBack.depthFailOp),
5140 toGlStencilOp(psD->m_stencilBack.passOp)
5141 };
5142 if (forceUpdate || stencilTest != state.stencilTest
5143 || (stencilTest
5144 && (stencilReadMask != state.stencilReadMask || stencilWriteMask != state.stencilWriteMask
5145 || stencilRef != state.stencilRef
5146 || stencilFront != state.stencil[0] || stencilBack != state.stencil[1])))
5147 {
5148 state.stencilTest = stencilTest;
5149 if (stencilTest) {
5150 state.stencilReadMask = stencilReadMask;
5151 state.stencilWriteMask = stencilWriteMask;
5152 state.stencilRef = stencilRef;
5153 state.stencil[0] = stencilFront;
5154 state.stencil[1] = stencilBack;
5155
5156 f->glEnable(GL_STENCIL_TEST);
5157
5158 f->glStencilFuncSeparate(GL_FRONT, stencilFront.func, stencilRef, stencilReadMask);
5159 f->glStencilOpSeparate(GL_FRONT, stencilFront.failOp, stencilFront.zfailOp, stencilFront.zpassOp);
5160 f->glStencilMaskSeparate(GL_FRONT, stencilWriteMask);
5161
5162 f->glStencilFuncSeparate(GL_BACK, stencilBack.func, stencilRef, stencilReadMask);
5163 f->glStencilOpSeparate(GL_BACK, stencilBack.failOp, stencilBack.zfailOp, stencilBack.zpassOp);
5164 f->glStencilMaskSeparate(GL_BACK, stencilWriteMask);
5165 } else {
5166 f->glDisable(GL_STENCIL_TEST);
5167 }
5168 }
5169
5170 const bool polyOffsetFill = psD->m_depthBias != 0 || !qFuzzyIsNull(psD->m_slopeScaledDepthBias);
5171 const float polyOffsetFactor = psD->m_slopeScaledDepthBias;
5172 const float polyOffsetUnits = psD->m_depthBias;
5173 if (forceUpdate || state.polyOffsetFill != polyOffsetFill
5174 || polyOffsetFactor != state.polyOffsetFactor || polyOffsetUnits != state.polyOffsetUnits)
5175 {
5176 state.polyOffsetFill = polyOffsetFill;
5177 state.polyOffsetFactor = polyOffsetFactor;
5178 state.polyOffsetUnits = polyOffsetUnits;
5179 if (polyOffsetFill) {
5180 f->glPolygonOffset(polyOffsetFactor, polyOffsetUnits);
5181 f->glEnable(GL_POLYGON_OFFSET_FILL);
5182 } else {
5183 f->glDisable(GL_POLYGON_OFFSET_FILL);
5184 }
5185 }
5186
5187 if (psD->m_topology == QRhiGraphicsPipeline::Lines || psD->m_topology == QRhiGraphicsPipeline::LineStrip) {
5188 const float lineWidth = psD->m_lineWidth;
5189 if (forceUpdate || lineWidth != state.lineWidth) {
5190 state.lineWidth = lineWidth;
5191 f->glLineWidth(lineWidth);
5192 }
5193 }
5194
5195 if (psD->m_topology == QRhiGraphicsPipeline::Patches) {
5196 const int cpCount = psD->m_patchControlPointCount;
5197 if (forceUpdate || cpCount != state.cpCount) {
5198 state.cpCount = cpCount;
5199 f->glPatchParameteri(GL_PATCH_VERTICES, qMax(1, cpCount));
5200 }
5201 }
5202
5203 f->glUseProgram(psD->program);
5204}
5205
5206// The source is a uniform block (std140) or a push constant block (std430)
5207// laid out for the GPU, which is not what glUniform* wants: there the values
5208// are tightly packed. srcStride is the distance in bytes between the array
5209// elements, or between the matrix columns for matrix types.
5210template <typename T>
5211static inline void qrhi_block_to_packed(T *dst, int vecSize, int elemCount, const void *src, quint32 srcStride)
5212{
5213 const char *p = reinterpret_cast<const char *>(src);
5214 for (int i = 0; i < elemCount; ++i) {
5215 const T *e = reinterpret_cast<const T *>(p);
5216 for (int j = 0; j < vecSize; ++j)
5217 dst[vecSize * i + j] = e[j];
5218 p += srcStride;
5219 }
5220}
5221
5222// The default stride for both the arrays and the matrix columns in an std140
5223// uniform block. Push constant blocks are std430, where an array of scalars or
5224// vec2 is tightly packed, and so is a mat2; there the reflection-provided
5225// stride is used instead.
5227
5229{
5230 return uniform.elemStride ? uniform.elemStride : QRHI_GL_STD140_STRIDE;
5231}
5232
5233static inline qint64 qrhi_uniform_read_size(QShaderDescription::VariableType type, int arrayDim, quint32 stride)
5234{
5235 if (!stride)
5236 stride = QRHI_GL_STD140_STRIDE;
5237
5238 qint64 elemSize;
5239 qint64 elemStride = stride;
5240
5241 switch (type) {
5242 case QShaderDescription::Float:
5243 case QShaderDescription::Int:
5244 case QShaderDescription::Uint:
5245 elemSize = 4;
5246 break;
5247 case QShaderDescription::Vec2:
5248 case QShaderDescription::Int2:
5249 case QShaderDescription::Uint2:
5250 elemSize = 8;
5251 break;
5252 case QShaderDescription::Vec3:
5253 case QShaderDescription::Int3:
5254 case QShaderDescription::Uint3:
5255 elemSize = 12;
5256 break;
5257 case QShaderDescription::Vec4:
5258 case QShaderDescription::Int4:
5259 case QShaderDescription::Uint4:
5260 elemSize = 16;
5261 break;
5262 case QShaderDescription::Mat2:
5263 // two columns, stride is the column stride (16 with std140)
5264 elemSize = stride + 8;
5265 elemStride = 2 * stride;
5266 break;
5267 case QShaderDescription::Mat3:
5268 // three columns
5269 elemSize = 2 * stride + 12;
5270 elemStride = 3 * stride;
5271 break;
5272 case QShaderDescription::Mat4:
5273 elemSize = 3 * stride + 16;
5274 elemStride = 4 * stride;
5275 break;
5276 case QShaderDescription::Bool:
5277 return 4;
5278 case QShaderDescription::Bool2:
5279 return 8;
5280 case QShaderDescription::Bool3:
5281 return 12;
5282 case QShaderDescription::Bool4:
5283 return 16;
5284 default:
5285 return 0;
5286 }
5287
5288 return arrayDim < 1 ? elemSize : (arrayDim - 1) * elemStride + elemSize;
5289}
5290
5291static inline bool isMultisampleTextureTarget(GLenum target)
5292{
5293 return target == GL_TEXTURE_2D_MULTISAMPLE || target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY;
5294}
5295
5297 void *ps, uint psGeneration, int glslLocation,
5298 int *texUnit, bool *activeTexUnitAltered)
5299{
5300 const bool samplerStateValid = texD->samplerState == samplerD->d;
5301 const bool cachedStateInRange = *texUnit < 16;
5302 bool updateTextureBinding = true;
5303 if (samplerStateValid && cachedStateInRange) {
5304 // If we already encountered the same texture with
5305 // the same pipeline for this texture unit in the
5306 // current pass, then the shader program already
5307 // has the uniform set. As in a 3D scene one model
5308 // often has more than one associated texture map,
5309 // the savings here can become significant,
5310 // depending on the scene.
5311 if (cbD->textureUnitState[*texUnit].ps == ps
5312 && cbD->textureUnitState[*texUnit].psGeneration == psGeneration
5313 && cbD->textureUnitState[*texUnit].texture == texD->texture)
5314 {
5315 updateTextureBinding = false;
5316 }
5317 }
5318 if (updateTextureBinding) {
5319 f->glActiveTexture(GL_TEXTURE0 + uint(*texUnit));
5320 *activeTexUnitAltered = true;
5321 f->glBindTexture(texD->target, texD->texture);
5322 f->glUniform1i(glslLocation, *texUnit);
5323 if (cachedStateInRange) {
5324 cbD->textureUnitState[*texUnit].ps = ps;
5325 cbD->textureUnitState[*texUnit].psGeneration = psGeneration;
5326 cbD->textureUnitState[*texUnit].texture = texD->texture;
5327 }
5328 }
5329 ++(*texUnit);
5330 if (!samplerStateValid) {
5331 // Multisample textures have no sampler state (they can only be read with
5332 // texelFetch), setting any of it is an INVALID_ENUM error.
5333 if (!isMultisampleTextureTarget(texD->target)) {
5334 f->glTexParameteri(texD->target, GL_TEXTURE_MIN_FILTER, GLint(samplerD->d.glminfilter));
5335 f->glTexParameteri(texD->target, GL_TEXTURE_MAG_FILTER, GLint(samplerD->d.glmagfilter));
5336 f->glTexParameteri(texD->target, GL_TEXTURE_WRAP_S, GLint(samplerD->d.glwraps));
5337 f->glTexParameteri(texD->target, GL_TEXTURE_WRAP_T, GLint(samplerD->d.glwrapt));
5338 if (caps.texture3D && texD->target == GL_TEXTURE_3D)
5339 f->glTexParameteri(texD->target, GL_TEXTURE_WRAP_R, GLint(samplerD->d.glwrapr));
5340 if (caps.textureCompareMode) {
5341 if (samplerD->d.gltexcomparefunc != GL_NEVER) {
5342 f->glTexParameteri(texD->target, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
5343 f->glTexParameteri(texD->target, GL_TEXTURE_COMPARE_FUNC, GLint(samplerD->d.gltexcomparefunc));
5344 } else {
5345 f->glTexParameteri(texD->target, GL_TEXTURE_COMPARE_MODE, GL_NONE);
5346 }
5347 }
5348 }
5349 texD->samplerState = samplerD->d;
5350 }
5351}
5352
5353void QRhiGles2::setUniformValue(const QGles2UniformDescription &uniform, const void *src, QGles2UniformState *uniformState)
5354{
5355 const quint32 stride = qrhi_uniform_stride(uniform);
5356
5357 switch (uniform.type) {
5358 case QShaderDescription::Float:
5359 {
5360 const int elemCount = uniform.arrayDim;
5361 if (elemCount < 1) {
5362 const float v = *reinterpret_cast<const float *>(src);
5363 if (uniform.stateIndex >= 0) {
5364 QGles2UniformState &thisUniformState(uniformState[uniform.stateIndex]);
5365 if (thisUniformState.componentCount != 1 || thisUniformState.v[0] != v) {
5366 thisUniformState.componentCount = 1;
5367 thisUniformState.v[0] = v;
5368 f->glUniform1f(uniform.glslLocation, v);
5369 }
5370 } else {
5371 f->glUniform1f(uniform.glslLocation, v);
5372 }
5373 } else {
5374 m_scratch.packedArray.resize(elemCount);
5375 qrhi_block_to_packed(&m_scratch.packedArray.data()->f, 1, elemCount, src, stride);
5376 f->glUniform1fv(uniform.glslLocation, elemCount, &m_scratch.packedArray.constData()->f);
5377 }
5378 }
5379 break;
5380 case QShaderDescription::Vec2:
5381 {
5382 const int elemCount = uniform.arrayDim;
5383 if (elemCount < 1) {
5384 const float *v = reinterpret_cast<const float *>(src);
5385 if (uniform.stateIndex >= 0) {
5386 QGles2UniformState &thisUniformState(uniformState[uniform.stateIndex]);
5387 if (thisUniformState.componentCount != 2
5388 || thisUniformState.v[0] != v[0]
5389 || thisUniformState.v[1] != v[1])
5390 {
5391 thisUniformState.componentCount = 2;
5392 thisUniformState.v[0] = v[0];
5393 thisUniformState.v[1] = v[1];
5394 f->glUniform2fv(uniform.glslLocation, 1, v);
5395 }
5396 } else {
5397 f->glUniform2fv(uniform.glslLocation, 1, v);
5398 }
5399 } else {
5400 m_scratch.packedArray.resize(elemCount * 2);
5401 qrhi_block_to_packed(&m_scratch.packedArray.data()->f, 2, elemCount, src, stride);
5402 f->glUniform2fv(uniform.glslLocation, elemCount, &m_scratch.packedArray.constData()->f);
5403 }
5404 }
5405 break;
5406 case QShaderDescription::Vec3:
5407 {
5408 const int elemCount = uniform.arrayDim;
5409 if (elemCount < 1) {
5410 const float *v = reinterpret_cast<const float *>(src);
5411 if (uniform.stateIndex >= 0) {
5412 QGles2UniformState &thisUniformState(uniformState[uniform.stateIndex]);
5413 if (thisUniformState.componentCount != 3
5414 || thisUniformState.v[0] != v[0]
5415 || thisUniformState.v[1] != v[1]
5416 || thisUniformState.v[2] != v[2])
5417 {
5418 thisUniformState.componentCount = 3;
5419 thisUniformState.v[0] = v[0];
5420 thisUniformState.v[1] = v[1];
5421 thisUniformState.v[2] = v[2];
5422 f->glUniform3fv(uniform.glslLocation, 1, v);
5423 }
5424 } else {
5425 f->glUniform3fv(uniform.glslLocation, 1, v);
5426 }
5427 } else {
5428 m_scratch.packedArray.resize(elemCount * 3);
5429 qrhi_block_to_packed(&m_scratch.packedArray.data()->f, 3, elemCount, src, stride);
5430 f->glUniform3fv(uniform.glslLocation, elemCount, &m_scratch.packedArray.constData()->f);
5431 }
5432 }
5433 break;
5434 case QShaderDescription::Vec4:
5435 {
5436 const int elemCount = uniform.arrayDim;
5437 if (elemCount < 1) {
5438 const float *v = reinterpret_cast<const float *>(src);
5439 if (uniform.stateIndex >= 0) {
5440 QGles2UniformState &thisUniformState(uniformState[uniform.stateIndex]);
5441 if (thisUniformState.componentCount != 4
5442 || thisUniformState.v[0] != v[0]
5443 || thisUniformState.v[1] != v[1]
5444 || thisUniformState.v[2] != v[2]
5445 || thisUniformState.v[3] != v[3])
5446 {
5447 thisUniformState.componentCount = 4;
5448 thisUniformState.v[0] = v[0];
5449 thisUniformState.v[1] = v[1];
5450 thisUniformState.v[2] = v[2];
5451 thisUniformState.v[3] = v[3];
5452 f->glUniform4fv(uniform.glslLocation, 1, v);
5453 }
5454 } else {
5455 f->glUniform4fv(uniform.glslLocation, 1, v);
5456 }
5457 } else if (stride == 16) {
5458 f->glUniform4fv(uniform.glslLocation, elemCount, reinterpret_cast<const float *>(src));
5459 } else {
5460 m_scratch.packedArray.resize(elemCount * 4);
5461 qrhi_block_to_packed(&m_scratch.packedArray.data()->f, 4, elemCount, src, stride);
5462 f->glUniform4fv(uniform.glslLocation, elemCount, &m_scratch.packedArray.constData()->f);
5463 }
5464 }
5465 break;
5466 case QShaderDescription::Mat2:
5467 {
5468 const int elemCount = uniform.arrayDim;
5469 m_scratch.packedArray.resize(qMax(1, elemCount) * 4);
5470 qrhi_block_to_packed(&m_scratch.packedArray.data()->f, 2, qMax(1, elemCount) * 2, src, stride);
5471 f->glUniformMatrix2fv(uniform.glslLocation, qMax(1, elemCount), GL_FALSE, &m_scratch.packedArray.constData()->f);
5472 }
5473 break;
5474 case QShaderDescription::Mat3:
5475 {
5476 const int elemCount = uniform.arrayDim;
5477 m_scratch.packedArray.resize(qMax(1, elemCount) * 9);
5478 qrhi_block_to_packed(&m_scratch.packedArray.data()->f, 3, qMax(1, elemCount) * 3, src, stride);
5479 f->glUniformMatrix3fv(uniform.glslLocation, qMax(1, elemCount), GL_FALSE, &m_scratch.packedArray.constData()->f);
5480 }
5481 break;
5482 case QShaderDescription::Mat4:
5483 if (stride == 16) {
5484 f->glUniformMatrix4fv(uniform.glslLocation, qMax(1, uniform.arrayDim), GL_FALSE, reinterpret_cast<const float *>(src));
5485 } else {
5486 const int elemCount = qMax(1, uniform.arrayDim);
5487 m_scratch.packedArray.resize(elemCount * 16);
5488 qrhi_block_to_packed(&m_scratch.packedArray.data()->f, 4, elemCount * 4, src, stride);
5489 f->glUniformMatrix4fv(uniform.glslLocation, elemCount, GL_FALSE, &m_scratch.packedArray.constData()->f);
5490 }
5491 break;
5492 case QShaderDescription::Int:
5493 {
5494 const int elemCount = uniform.arrayDim;
5495 if (elemCount < 1) {
5496 f->glUniform1i(uniform.glslLocation, *reinterpret_cast<const qint32 *>(src));
5497 } else {
5498 m_scratch.packedArray.resize(elemCount);
5499 qrhi_block_to_packed(&m_scratch.packedArray.data()->i, 1, elemCount, src, stride);
5500 f->glUniform1iv(uniform.glslLocation, elemCount, &m_scratch.packedArray.constData()->i);
5501 }
5502 }
5503 break;
5504 case QShaderDescription::Int2:
5505 {
5506 const int elemCount = uniform.arrayDim;
5507 if (elemCount < 1) {
5508 f->glUniform2iv(uniform.glslLocation, 1, reinterpret_cast<const qint32 *>(src));
5509 } else {
5510 m_scratch.packedArray.resize(elemCount * 2);
5511 qrhi_block_to_packed(&m_scratch.packedArray.data()->i, 2, elemCount, src, stride);
5512 f->glUniform2iv(uniform.glslLocation, elemCount, &m_scratch.packedArray.constData()->i);
5513 }
5514 }
5515 break;
5516 case QShaderDescription::Int3:
5517 {
5518 const int elemCount = uniform.arrayDim;
5519 if (elemCount < 1) {
5520 f->glUniform3iv(uniform.glslLocation, 1, reinterpret_cast<const qint32 *>(src));
5521 } else {
5522 m_scratch.packedArray.resize(elemCount * 3);
5523 qrhi_block_to_packed(&m_scratch.packedArray.data()->i, 3, elemCount, src, stride);
5524 f->glUniform3iv(uniform.glslLocation, elemCount, &m_scratch.packedArray.constData()->i);
5525 }
5526 }
5527 break;
5528 case QShaderDescription::Int4:
5529 if (uniform.arrayDim < 1 || stride == 16) {
5530 f->glUniform4iv(uniform.glslLocation, qMax(1, uniform.arrayDim), reinterpret_cast<const qint32 *>(src));
5531 } else {
5532 m_scratch.packedArray.resize(uniform.arrayDim * 4);
5533 qrhi_block_to_packed(&m_scratch.packedArray.data()->i, 4, uniform.arrayDim, src, stride);
5534 f->glUniform4iv(uniform.glslLocation, uniform.arrayDim, &m_scratch.packedArray.constData()->i);
5535 }
5536 break;
5537 case QShaderDescription::Uint:
5538 {
5539 const int elemCount = uniform.arrayDim;
5540 if (elemCount < 1) {
5541 f->glUniform1ui(uniform.glslLocation, *reinterpret_cast<const quint32 *>(src));
5542 } else {
5543 m_scratch.packedArray.resize(elemCount);
5544 qrhi_block_to_packed(&m_scratch.packedArray.data()->u, 1, elemCount, src, stride);
5545 f->glUniform1uiv(uniform.glslLocation, elemCount, &m_scratch.packedArray.constData()->u);
5546 }
5547 }
5548 break;
5549 case QShaderDescription::Uint2:
5550 {
5551 const int elemCount = uniform.arrayDim;
5552 if (elemCount < 1) {
5553 f->glUniform2uiv(uniform.glslLocation, 1, reinterpret_cast<const quint32 *>(src));
5554 } else {
5555 m_scratch.packedArray.resize(elemCount * 2);
5556 qrhi_block_to_packed(&m_scratch.packedArray.data()->u, 2, elemCount, src, stride);
5557 f->glUniform2uiv(uniform.glslLocation, elemCount, &m_scratch.packedArray.constData()->u);
5558 }
5559 }
5560 break;
5561 case QShaderDescription::Uint3:
5562 {
5563 const int elemCount = uniform.arrayDim;
5564 if (elemCount < 1) {
5565 f->glUniform3uiv(uniform.glslLocation, 1, reinterpret_cast<const quint32 *>(src));
5566 } else {
5567 m_scratch.packedArray.resize(elemCount * 3);
5568 qrhi_block_to_packed(&m_scratch.packedArray.data()->u, 3, elemCount, src, stride);
5569 f->glUniform3uiv(uniform.glslLocation, elemCount, &m_scratch.packedArray.constData()->u);
5570 }
5571 }
5572 break;
5573 case QShaderDescription::Uint4:
5574 if (uniform.arrayDim < 1 || stride == 16) {
5575 f->glUniform4uiv(uniform.glslLocation, qMax(1, uniform.arrayDim), reinterpret_cast<const quint32 *>(src));
5576 } else {
5577 m_scratch.packedArray.resize(uniform.arrayDim * 4);
5578 qrhi_block_to_packed(&m_scratch.packedArray.data()->u, 4, uniform.arrayDim, src, stride);
5579 f->glUniform4uiv(uniform.glslLocation, uniform.arrayDim, &m_scratch.packedArray.constData()->u);
5580 }
5581 break;
5582 case QShaderDescription::Bool: // a glsl bool is 4 bytes, like (u)int
5583 f->glUniform1i(uniform.glslLocation, *reinterpret_cast<const qint32 *>(src));
5584 break;
5585 case QShaderDescription::Bool2:
5586 f->glUniform2iv(uniform.glslLocation, 1, reinterpret_cast<const qint32 *>(src));
5587 break;
5588 case QShaderDescription::Bool3:
5589 f->glUniform3iv(uniform.glslLocation, 1, reinterpret_cast<const qint32 *>(src));
5590 break;
5591 case QShaderDescription::Bool4:
5592 f->glUniform4iv(uniform.glslLocation, 1, reinterpret_cast<const qint32 *>(src));
5593 break;
5594 default:
5595 qWarning("Uniform with binding %d, offset %u has unsupported type %d",
5596 uniform.binding, uniform.offset, uniform.type);
5597 break;
5598 }
5599}
5600
5601static inline bool qrhi_gl_isTrackedUniform(const QGles2UniformDescription &uniform)
5602{
5603 // The logic here must match setUniformValue().
5604
5605 if (uniform.arrayDim > 0)
5606 return false;
5607
5608 switch (uniform.type) {
5609 case QShaderDescription::Float:
5610 case QShaderDescription::Vec2:
5611 case QShaderDescription::Vec3:
5612 case QShaderDescription::Vec4:
5613 return true;
5614 default:
5615 return false;
5616 }
5617}
5618
5619void QRhiGles2::setupUniformStateTracking(QGles2UniformDescriptionVector *uniforms,
5620 QGles2UniformDescriptionVector *pushConstantUniforms,
5621 QGles2UniformStateVector *uniformState)
5622{
5623 int count = 0;
5624 for (QGles2UniformDescriptionVector *list : { uniforms, pushConstantUniforms }) {
5625 for (QGles2UniformDescription &uniform : *list)
5626 uniform.stateIndex = qrhi_gl_isTrackedUniform(uniform) ? count++ : -1;
5627 }
5628 uniformState->resize(count);
5629 if (count)
5630 memset(uniformState->data(), 0, size_t(count) * sizeof(QGles2UniformState));
5631}
5632
5633// Sets all uniforms belonging to one block. blockData is the start of the
5634// source data (the uniform buffer's contents, or the push constant block),
5635// blockOffset the offset the block starts at within it. Pass a binding of -1
5636// to take all entries of uniforms, which is what push constant blocks, having
5637// no binding, do.
5638void QRhiGles2::setUniformsFromBlock(const QGles2UniformDescriptionVector &uniforms, int binding,
5639 const char *blockData, qint64 blockSize, quint32 blockOffset,
5640 QGles2UniformState *uniformState)
5641{
5642 for (const QGles2UniformDescription &uniform : uniforms) {
5643 if (binding >= 0 && uniform.binding != binding)
5644 continue;
5645
5646 const qint64 readOffset = qint64(blockOffset) + uniform.offset;
5647 const qint64 readSize = qrhi_uniform_read_size(uniform.type, uniform.arrayDim, uniform.elemStride);
5648 if (readOffset < 0 || readOffset + readSize > blockSize) {
5649 qWarning("Uniform with binding %d, offset %u, type %d, array dimension %d would read "
5650 "outside of the %lld bytes of source data. Skipping.",
5651 uniform.binding, uniform.offset, uniform.type, uniform.arrayDim, blockSize);
5652 continue;
5653 }
5654
5655#ifndef QT_NO_DEBUG
5656 if (uniform.arrayDim > 0
5657 && uniform.type != QShaderDescription::Float
5658 && uniform.type != QShaderDescription::Vec2
5659 && uniform.type != QShaderDescription::Vec3
5660 && uniform.type != QShaderDescription::Vec4
5661 && uniform.type != QShaderDescription::Int
5662 && uniform.type != QShaderDescription::Int2
5663 && uniform.type != QShaderDescription::Int3
5664 && uniform.type != QShaderDescription::Int4
5665 && uniform.type != QShaderDescription::Uint
5666 && uniform.type != QShaderDescription::Uint2
5667 && uniform.type != QShaderDescription::Uint3
5668 && uniform.type != QShaderDescription::Uint4
5669 && uniform.type != QShaderDescription::Mat2
5670 && uniform.type != QShaderDescription::Mat3
5671 && uniform.type != QShaderDescription::Mat4)
5672 {
5673 qWarning("Uniform with binding %d, offset %u, type %d is an array, "
5674 "but arrays are only supported for float, vec2, vec3, vec4, int, "
5675 "ivec2, ivec3, ivec4, uint, uvec2, uvec3, uvec4, mat2, mat3 "
5676 "and mat4. "
5677 "Only the first element will be set.",
5678 uniform.binding, uniform.offset, uniform.type);
5679 }
5680#endif
5681
5682 // in both a uniform block and a push constant block everything is at
5683 // least 4 byte aligned, so this should not cause unaligned reads
5684 setUniformValue(uniform, blockData + readOffset, uniformState);
5685 }
5686}
5687
5689 QRhiGraphicsPipeline *maybeGraphicsPs, QRhiComputePipeline *maybeComputePs,
5690 QRhiShaderResourceBindings *srb,
5691 const uint *dynOfsPairs, int dynOfsCount)
5692{
5694 int texUnit = 1; // start from unit 1, keep 0 for resource mgmt stuff to avoid clashes
5695 bool activeTexUnitAltered = false;
5696 QGles2UniformDescriptionVector &uniforms(maybeGraphicsPs ? QRHI_RES(QGles2GraphicsPipeline, maybeGraphicsPs)->uniforms
5697 : QRHI_RES(QGles2ComputePipeline, maybeComputePs)->uniforms);
5698 QGles2UniformState *uniformState = maybeGraphicsPs ? QRHI_RES(QGles2GraphicsPipeline, maybeGraphicsPs)->uniformState.data()
5699 : QRHI_RES(QGles2ComputePipeline, maybeComputePs)->uniformState.data();
5700 m_scratch.separateTextureBindings.clear();
5701 m_scratch.separateSamplerBindings.clear();
5702
5703 for (int i = 0, ie = srbD->m_bindings.size(); i != ie; ++i) {
5704 const QRhiShaderResourceBinding::Data *b = shaderResourceBindingData(srbD->m_bindings.at(i));
5705
5706 switch (b->type()) {
5707 case QRhiShaderResourceBinding::UniformBuffer:
5708 {
5709 int viewOffset = b->ubuf().offset;
5710 for (int j = 0; j < dynOfsCount; ++j) {
5711 if (dynOfsPairs[2 * j] == uint(b->binding)) {
5712 viewOffset = int(dynOfsPairs[2 * j + 1]);
5713 break;
5714 }
5715 }
5716 QGles2Buffer *bufD = QRHI_RES(QGles2Buffer, b->ubuf().buf);
5717 setUniformsFromBlock(uniforms, b->binding, bufD->data.constData(), bufD->data.size(),
5718 quint32(viewOffset), uniformState);
5719 }
5720 break;
5721 case QRhiShaderResourceBinding::SampledTexture:
5722 {
5723 const QGles2SamplerDescriptionVector &samplers(maybeGraphicsPs ? QRHI_RES(QGles2GraphicsPipeline, maybeGraphicsPs)->samplers
5724 : QRHI_RES(QGles2ComputePipeline, maybeComputePs)->samplers);
5725 void *ps;
5726 uint psGeneration;
5727 if (maybeGraphicsPs) {
5728 ps = maybeGraphicsPs;
5729 psGeneration = QRHI_RES(QGles2GraphicsPipeline, maybeGraphicsPs)->generation;
5730 } else {
5731 ps = maybeComputePs;
5732 psGeneration = QRHI_RES(QGles2ComputePipeline, maybeComputePs)->generation;
5733 }
5734 const auto &texSamplers = b->stex().texSamplers;
5735 for (int elem = 0; elem < texSamplers.count(); ++elem) {
5736 QGles2Texture *texD = QRHI_RES(QGles2Texture, texSamplers[elem].tex);
5737 QGles2Sampler *samplerD = QRHI_RES(QGles2Sampler, texSamplers[elem].sampler);
5738 for (const QGles2SamplerDescription &shaderSampler : samplers) {
5739 if (shaderSampler.combinedBinding == b->binding) {
5740 const int loc = shaderSampler.glslLocation + elem;
5741 bindCombinedSampler(cbD, texD, samplerD, ps, psGeneration, loc, &texUnit, &activeTexUnitAltered);
5742 break;
5743 }
5744 }
5745 }
5746 }
5747 break;
5748 case QRhiShaderResourceBinding::Texture:
5749 {
5750 const auto &texSamplers = b->stex().texSamplers;
5751 for (int elem = 0; elem < texSamplers.count(); ++elem) {
5752 QGles2Texture *texD = QRHI_RES(QGles2Texture, texSamplers[elem].tex);
5753 m_scratch.separateTextureBindings.append({ texD, b->binding, elem });
5754 }
5755 }
5756 break;
5757 case QRhiShaderResourceBinding::Sampler:
5758 {
5759 QGles2Sampler *samplerD = QRHI_RES(QGles2Sampler, b->stex().texSamplers[0].sampler);
5760 m_scratch.separateSamplerBindings.append({ samplerD, b->binding });
5761 }
5762 break;
5763 case QRhiShaderResourceBinding::ImageLoad:
5764 case QRhiShaderResourceBinding::ImageStore:
5765 case QRhiShaderResourceBinding::ImageLoadStore:
5766 {
5767 QGles2Texture *texD = QRHI_RES(QGles2Texture, b->simage().tex);
5768 Q_ASSERT(texD->m_flags.testFlag(QRhiTexture::UsedWithLoadStore));
5769 // arrays, cubemaps, and 3D textures expose the whole texture with all layers/slices
5770 const bool layered = texD->m_flags.testFlag(QRhiTexture::CubeMap)
5771 || texD->m_flags.testFlag(QRhiTexture::ThreeDimensional)
5772 || texD->m_flags.testFlag(QRhiTexture::TextureArray);
5773 GLenum access = GL_READ_WRITE;
5774 if (b->type() == QRhiShaderResourceBinding::ImageLoad)
5775 access = GL_READ_ONLY;
5776 else if (b->type() == QRhiShaderResourceBinding::ImageStore)
5777 access = GL_WRITE_ONLY;
5778 f->glBindImageTexture(GLuint(b->binding), texD->texture,
5779 b->simage().level, layered, 0,
5780 access, texD->glsizedintformat);
5781 }
5782 break;
5783 case QRhiShaderResourceBinding::BufferLoad:
5784 case QRhiShaderResourceBinding::BufferStore:
5785 case QRhiShaderResourceBinding::BufferLoadStore:
5786 {
5787 QGles2Buffer *bufD = QRHI_RES(QGles2Buffer, b->sbuf().buf);
5788 Q_ASSERT(bufD->m_usage.testFlag(QRhiBuffer::StorageBuffer));
5789 if (b->sbuf().offset == 0 && b->sbuf().maybeSize == 0)
5790 f->glBindBufferBase(GL_SHADER_STORAGE_BUFFER, GLuint(b->binding), bufD->buffer);
5791 else
5792 f->glBindBufferRange(GL_SHADER_STORAGE_BUFFER, GLuint(b->binding), bufD->buffer,
5793 b->sbuf().offset, b->sbuf().maybeSize ? b->sbuf().maybeSize : bufD->m_size);
5794 }
5795 break;
5796 default:
5797 Q_UNREACHABLE();
5798 break;
5799 }
5800 }
5801
5802 if (!m_scratch.separateTextureBindings.isEmpty() || !m_scratch.separateSamplerBindings.isEmpty()) {
5803 const QGles2SamplerDescriptionVector &samplers(maybeGraphicsPs ? QRHI_RES(QGles2GraphicsPipeline, maybeGraphicsPs)->samplers
5804 : QRHI_RES(QGles2ComputePipeline, maybeComputePs)->samplers);
5805 void *ps;
5806 uint psGeneration;
5807 if (maybeGraphicsPs) {
5808 ps = maybeGraphicsPs;
5809 psGeneration = QRHI_RES(QGles2GraphicsPipeline, maybeGraphicsPs)->generation;
5810 } else {
5811 ps = maybeComputePs;
5812 psGeneration = QRHI_RES(QGles2ComputePipeline, maybeComputePs)->generation;
5813 }
5814 for (const QGles2SamplerDescription &shaderSampler : samplers) {
5815 if (shaderSampler.combinedBinding >= 0)
5816 continue;
5817 for (const Scratch::SeparateSampler &sepSampler : std::as_const(m_scratch.separateSamplerBindings)) {
5818 if (sepSampler.binding != shaderSampler.sbinding)
5819 continue;
5820 for (const Scratch::SeparateTexture &sepTex : std::as_const(m_scratch.separateTextureBindings)) {
5821 if (sepTex.binding != shaderSampler.tbinding)
5822 continue;
5823 const int loc = shaderSampler.glslLocation + sepTex.elem;
5824 bindCombinedSampler(cbD, sepTex.texture, sepSampler.sampler, ps, psGeneration,
5825 loc, &texUnit, &activeTexUnitAltered);
5826 }
5827 }
5828 }
5829 }
5830
5831 if (activeTexUnitAltered)
5832 f->glActiveTexture(GL_TEXTURE0);
5833}
5834
5835void QRhiGles2::resourceUpdate(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
5836{
5837 Q_ASSERT(QRHI_RES(QGles2CommandBuffer, cb)->recordingPass == QGles2CommandBuffer::NoPass);
5838
5839 enqueueResourceUpdates(cb, resourceUpdates);
5840}
5841
5842QGles2RenderTargetData *QRhiGles2::enqueueBindFramebuffer(QRhiRenderTarget *rt, QGles2CommandBuffer *cbD,
5843 bool *wantsColorClear, bool *wantsDsClear)
5844{
5845 QGles2RenderTargetData *rtD = nullptr;
5846 QRhiPassResourceTracker &passResTracker(cbD->passResTrackers[cbD->currentPassResTrackerIndex]);
5847
5848 QGles2CommandBuffer::Command &fbCmd(cbD->commands.get());
5849 fbCmd.cmd = QGles2CommandBuffer::Command::BindFramebuffer;
5850
5851 static const bool doClearBuffers = qEnvironmentVariableIntValue("QT_GL_NO_CLEAR_BUFFERS") == 0;
5852 static const bool doClearColorBuffer = qEnvironmentVariableIntValue("QT_GL_NO_CLEAR_COLOR_BUFFER") == 0;
5853
5854 switch (rt->resourceType()) {
5855 case QRhiResource::SwapChainRenderTarget:
5856 rtD = &QRHI_RES(QGles2SwapChainRenderTarget, rt)->d;
5857 if (wantsColorClear)
5858 *wantsColorClear = doClearBuffers && doClearColorBuffer;
5859 if (wantsDsClear)
5860 *wantsDsClear = doClearBuffers;
5861 fbCmd.args.bindFramebuffer.fbo = 0;
5862 fbCmd.args.bindFramebuffer.colorAttCount = 1;
5863 fbCmd.args.bindFramebuffer.stereo = rtD->stereoTarget.has_value();
5864 if (fbCmd.args.bindFramebuffer.stereo)
5865 fbCmd.args.bindFramebuffer.stereoTarget = rtD->stereoTarget.value();
5866 break;
5867 case QRhiResource::TextureRenderTarget:
5868 {
5869 QGles2TextureRenderTarget *rtTex = QRHI_RES(QGles2TextureRenderTarget, rt);
5870 rtD = &rtTex->d;
5871 if (wantsColorClear)
5872 *wantsColorClear = !rtTex->m_flags.testFlag(QRhiTextureRenderTarget::PreserveColorContents);
5873 if (wantsDsClear)
5874 *wantsDsClear = !rtTex->m_flags.testFlag(QRhiTextureRenderTarget::PreserveDepthStencilContents);
5875 fbCmd.args.bindFramebuffer.fbo = rtTex->framebuffer;
5876 fbCmd.args.bindFramebuffer.colorAttCount = rtD->colorAttCount;
5877 fbCmd.args.bindFramebuffer.stereo = false;
5878
5879 for (auto it = rtTex->m_desc.cbeginColorAttachments(), itEnd = rtTex->m_desc.cendColorAttachments();
5880 it != itEnd; ++it)
5881 {
5882 const QRhiColorAttachment &colorAtt(*it);
5883 QGles2Texture *texD = QRHI_RES(QGles2Texture, colorAtt.texture());
5884 QGles2Texture *resolveTexD = QRHI_RES(QGles2Texture, colorAtt.resolveTexture());
5885 if (texD && cbD->passNeedsResourceTracking) {
5886 trackedRegisterTexture(&passResTracker, texD,
5887 QRhiPassResourceTracker::TexColorOutput,
5888 QRhiPassResourceTracker::TexColorOutputStage);
5889 }
5890 if (resolveTexD && cbD->passNeedsResourceTracking) {
5891 trackedRegisterTexture(&passResTracker, resolveTexD,
5892 QRhiPassResourceTracker::TexColorOutput,
5893 QRhiPassResourceTracker::TexColorOutputStage);
5894 }
5895 // renderbuffers cannot be written in shaders (no image store) so
5896 // they do not matter here
5897 }
5898 if (rtTex->m_desc.depthTexture() && cbD->passNeedsResourceTracking) {
5899 trackedRegisterTexture(&passResTracker, QRHI_RES(QGles2Texture, rtTex->m_desc.depthTexture()),
5900 QRhiPassResourceTracker::TexDepthOutput,
5901 QRhiPassResourceTracker::TexDepthOutputStage);
5902 }
5903 }
5904 break;
5905 default:
5906 Q_UNREACHABLE();
5907 break;
5908 }
5909
5910 fbCmd.args.bindFramebuffer.srgb = rtD->srgbUpdateAndBlend;
5911
5912 return rtD;
5913}
5914
5916{
5917 cbD->passResTrackers.emplace_back();
5918 cbD->currentPassResTrackerIndex = cbD->passResTrackers.size() - 1;
5919 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
5921 cmd.args.barriersForPass.trackerIndex = cbD->currentPassResTrackerIndex;
5922}
5923
5924void QRhiGles2::beginPass(QRhiCommandBuffer *cb,
5925 QRhiRenderTarget *rt,
5926 const QColor &colorClearValue,
5927 const QRhiDepthStencilClearValue &depthStencilClearValue,
5928 QRhiResourceUpdateBatch *resourceUpdates,
5929 QRhiCommandBuffer::BeginPassFlags flags)
5930{
5931 QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
5933
5934 if (resourceUpdates)
5935 enqueueResourceUpdates(cb, resourceUpdates);
5936
5937 // Get a new resource tracker. Then add a command that will generate
5938 // glMemoryBarrier() calls based on that tracker when submitted.
5940
5941 if (rt->resourceType() == QRhiRenderTarget::TextureRenderTarget) {
5943 if (!QRhiRenderTargetAttachmentTracker::isUpToDate<QGles2Texture, QGles2RenderBuffer>(rtTex->description(), rtTex->d.currentResIdList))
5944 rtTex->create();
5945 }
5946
5947 bool wantsColorClear, wantsDsClear;
5948 QGles2RenderTargetData *rtD = enqueueBindFramebuffer(rt, cbD, &wantsColorClear, &wantsDsClear);
5949
5950 QGles2CommandBuffer::Command &clearCmd(cbD->commands.get());
5952 clearCmd.args.clear.mask = 0;
5953 if (rtD->colorAttCount && wantsColorClear)
5954 clearCmd.args.clear.mask |= GL_COLOR_BUFFER_BIT;
5955 if (rtD->dsAttCount && wantsDsClear)
5956 clearCmd.args.clear.mask |= GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT;
5957 clearCmd.args.clear.c[0] = colorClearValue.redF();
5958 clearCmd.args.clear.c[1] = colorClearValue.greenF();
5959 clearCmd.args.clear.c[2] = colorClearValue.blueF();
5960 clearCmd.args.clear.c[3] = colorClearValue.alphaF();
5961 clearCmd.args.clear.d = depthStencilClearValue.depthClearValue();
5962 clearCmd.args.clear.s = depthStencilClearValue.stencilClearValue();
5963
5965 cbD->passNeedsResourceTracking = !flags.testFlag(QRhiCommandBuffer::DoNotTrackResourcesForCompute) && caps.compute;
5967 cbD->currentTarget = rt;
5968
5970}
5971
5972void QRhiGles2::endPass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
5973{
5974 QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
5976
5977 if (cbD->currentTarget->resourceType() == QRhiResource::TextureRenderTarget) {
5978 QGles2TextureRenderTarget *rtTex = QRHI_RES(QGles2TextureRenderTarget, cbD->currentTarget);
5979 for (auto it = rtTex->m_desc.cbeginColorAttachments(), itEnd = rtTex->m_desc.cendColorAttachments();
5980 it != itEnd; ++it)
5981 {
5982 const QRhiColorAttachment &colorAtt(*it);
5983 if (!colorAtt.resolveTexture())
5984 continue;
5985
5986 QGles2Texture *resolveTexD = QRHI_RES(QGles2Texture, colorAtt.resolveTexture());
5987 const QSize size = resolveTexD->pixelSize();
5988 if (colorAtt.renderBuffer()) {
5989 QGles2RenderBuffer *rbD = QRHI_RES(QGles2RenderBuffer, colorAtt.renderBuffer());
5990 if (rbD->pixelSize() != size) {
5991 qWarning("Resolve source (%dx%d) and target (%dx%d) size does not match",
5992 rbD->pixelSize().width(), rbD->pixelSize().height(), size.width(), size.height());
5993 }
5995 // colorAtt.renderBuffer() is not actually used for anything if OpenGL ES'
5996 // auto-resolving GL_EXT_multisampled_render_to_texture is used.
5997 } else {
5998 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
6000 cmd.args.blitFromRenderbuffer.renderbuffer = rbD->renderbuffer;
6001 cmd.args.blitFromRenderbuffer.stencilRenderbuffer = 0;
6002 cmd.args.blitFromRenderbuffer.w = size.width();
6003 cmd.args.blitFromRenderbuffer.h = size.height();
6004 if (resolveTexD->m_flags.testFlag(QRhiTexture::CubeMap))
6005 cmd.args.blitFromRenderbuffer.target = GL_TEXTURE_CUBE_MAP_POSITIVE_X + uint(colorAtt.resolveLayer());
6006 else
6007 cmd.args.blitFromRenderbuffer.target = resolveTexD->target;
6008 cmd.args.blitFromRenderbuffer.dstTexture = resolveTexD->texture;
6009 cmd.args.blitFromRenderbuffer.dstLevel = colorAtt.resolveLevel();
6010 const bool hasZ = resolveTexD->m_flags.testFlag(QRhiTexture::ThreeDimensional)
6011 || resolveTexD->m_flags.testFlag(QRhiTexture::TextureArray);
6012 cmd.args.blitFromRenderbuffer.dstLayer = hasZ ? colorAtt.resolveLayer() : 0;
6013 cmd.args.blitFromRenderbuffer.isDepthStencil = false;
6014 cmd.args.blitFromRenderbuffer.hasStencil = false;
6015 }
6016 } else if (caps.glesMultisampleRenderToTexture) {
6017 // Nothing to do, resolving into colorAtt.resolveTexture() is automatic,
6018 // colorAtt.texture() is in fact not used for anything.
6019 } else {
6020 Q_ASSERT(colorAtt.texture());
6021 QGles2Texture *texD = QRHI_RES(QGles2Texture, colorAtt.texture());
6022 if (texD->pixelSize() != size) {
6023 qWarning("Resolve source (%dx%d) and target (%dx%d) size does not match",
6024 texD->pixelSize().width(), texD->pixelSize().height(), size.width(), size.height());
6025 }
6026 const int resolveCount = colorAtt.multiViewCount() >= 2 ? colorAtt.multiViewCount() : 1;
6027 for (int resolveIdx = 0; resolveIdx < resolveCount; ++resolveIdx) {
6028 const int srcLayer = colorAtt.layer() + resolveIdx;
6029 const int dstLayer = colorAtt.resolveLayer() + resolveIdx;
6030 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
6032 if (texD->m_flags.testFlag(QRhiTexture::CubeMap))
6033 cmd.args.blitFromTexture.srcTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X + uint(srcLayer);
6034 else
6035 cmd.args.blitFromTexture.srcTarget = texD->target;
6036 cmd.args.blitFromTexture.srcTexture = texD->texture;
6037 cmd.args.blitFromTexture.srcLevel = colorAtt.level();
6038 cmd.args.blitFromTexture.srcLayer = 0;
6039 if (texD->m_flags.testFlag(QRhiTexture::ThreeDimensional) || texD->m_flags.testFlag(QRhiTexture::TextureArray))
6040 cmd.args.blitFromTexture.srcLayer = srcLayer;
6041 cmd.args.blitFromTexture.w = size.width();
6042 cmd.args.blitFromTexture.h = size.height();
6043 if (resolveTexD->m_flags.testFlag(QRhiTexture::CubeMap))
6044 cmd.args.blitFromTexture.dstTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X + uint(dstLayer);
6045 else
6046 cmd.args.blitFromTexture.dstTarget = resolveTexD->target;
6047 cmd.args.blitFromTexture.dstTexture = resolveTexD->texture;
6048 cmd.args.blitFromTexture.dstLevel = colorAtt.resolveLevel();
6049 cmd.args.blitFromTexture.dstLayer = 0;
6050 if (resolveTexD->m_flags.testFlag(QRhiTexture::ThreeDimensional) || resolveTexD->m_flags.testFlag(QRhiTexture::TextureArray))
6051 cmd.args.blitFromTexture.dstLayer = dstLayer;
6052 cmd.args.blitFromTexture.isDepthStencil = false;
6053 cmd.args.blitFromTexture.hasStencil = false;
6054 }
6055 }
6056 }
6057
6058 if (rtTex->m_desc.depthResolveTexture()) {
6059 QGles2Texture *depthResolveTexD = QRHI_RES(QGles2Texture, rtTex->m_desc.depthResolveTexture());
6060 const QSize size = depthResolveTexD->pixelSize();
6061 if (rtTex->m_desc.depthStencilBuffer()) {
6062 QGles2RenderBuffer *rbD = QRHI_RES(QGles2RenderBuffer, rtTex->m_desc.depthStencilBuffer());
6063 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
6065 cmd.args.blitFromRenderbuffer.renderbuffer = rbD->renderbuffer;
6066 cmd.args.blitFromRenderbuffer.stencilRenderbuffer = rbD->stencilRenderbuffer;
6067 cmd.args.blitFromRenderbuffer.w = size.width();
6068 cmd.args.blitFromRenderbuffer.h = size.height();
6069 cmd.args.blitFromRenderbuffer.target = depthResolveTexD->target;
6070 cmd.args.blitFromRenderbuffer.dstTexture = depthResolveTexD->texture;
6071 cmd.args.blitFromRenderbuffer.dstLevel = 0;
6072 cmd.args.blitFromRenderbuffer.dstLayer = 0;
6073 cmd.args.blitFromRenderbuffer.isDepthStencil = true;
6074 // The renderbuffer always has stencil, but the destination may
6075 // be depth-only, in which case attaching it to
6076 // GL_STENCIL_ATTACHMENT would make the framebuffer incomplete.
6077 cmd.args.blitFromRenderbuffer.hasStencil = isStencilSupportingFormat(depthResolveTexD->format());
6078 } else if (caps.glesMultisampleRenderToTexture) {
6079 // Nothing to do, resolving into depthResolveTexture() is automatic.
6080 } else {
6081 QGles2Texture *depthTexD = QRHI_RES(QGles2Texture, rtTex->m_desc.depthTexture());
6082 // Only involve the stencil when both sides actually have it.
6083 const bool hasStencil = isStencilSupportingFormat(depthTexD->format()) && isStencilSupportingFormat(depthResolveTexD->format());
6084 const int resolveCount = depthTexD->arraySize() >= 2 ? depthTexD->arraySize() : 1;
6085 for (int resolveIdx = 0; resolveIdx < resolveCount; ++resolveIdx) {
6086 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
6088 cmd.args.blitFromTexture.srcTarget = depthTexD->target;
6089 cmd.args.blitFromTexture.srcTexture = depthTexD->texture;
6090 cmd.args.blitFromTexture.srcLevel = 0;
6091 cmd.args.blitFromTexture.srcLayer = resolveIdx;
6092 cmd.args.blitFromTexture.w = size.width();
6093 cmd.args.blitFromTexture.h = size.height();
6094 cmd.args.blitFromTexture.dstTarget = depthResolveTexD->target;
6095 cmd.args.blitFromTexture.dstTexture = depthResolveTexD->texture;
6096 cmd.args.blitFromTexture.dstLevel = 0;
6097 cmd.args.blitFromTexture.dstLayer = resolveIdx;
6098 cmd.args.blitFromTexture.isDepthStencil = true;
6099 cmd.args.blitFromTexture.hasStencil = hasStencil;
6100 }
6101 }
6102 }
6103
6104 const bool mayDiscardDepthStencil =
6105 (rtTex->m_desc.depthStencilBuffer()
6106 || (rtTex->m_desc.depthTexture() && rtTex->m_flags.testFlag(QRhiTextureRenderTarget::DoNotStoreDepthStencilContents)))
6107 && !rtTex->m_desc.depthResolveTexture();
6108 if (mayDiscardDepthStencil) {
6109 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
6111 cmd.args.invalidateFramebuffer.fbo = rtTex->framebuffer;
6113 cmd.args.invalidateFramebuffer.attCount = 1;
6114 cmd.args.invalidateFramebuffer.att[0] = GL_DEPTH_STENCIL_ATTACHMENT;
6115 } else {
6116 cmd.args.invalidateFramebuffer.attCount = 2;
6117 cmd.args.invalidateFramebuffer.att[0] = GL_DEPTH_ATTACHMENT;
6118 cmd.args.invalidateFramebuffer.att[1] = GL_STENCIL_ATTACHMENT;
6119 }
6120 }
6121 }
6122
6124 cbD->currentTarget = nullptr;
6125
6126 if (resourceUpdates)
6127 enqueueResourceUpdates(cb, resourceUpdates);
6128}
6129
6130void QRhiGles2::beginComputePass(QRhiCommandBuffer *cb,
6131 QRhiResourceUpdateBatch *resourceUpdates,
6133{
6134 QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
6136
6137 if (resourceUpdates)
6138 enqueueResourceUpdates(cb, resourceUpdates);
6139
6141
6143
6145}
6146
6147void QRhiGles2::endComputePass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
6148{
6149 QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
6151
6153
6154 if (resourceUpdates)
6155 enqueueResourceUpdates(cb, resourceUpdates);
6156}
6157
6158void QRhiGles2::setComputePipeline(QRhiCommandBuffer *cb, QRhiComputePipeline *ps)
6159{
6160 QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
6163 const bool pipelineChanged = cbD->currentComputePipeline != ps || cbD->currentPipelineGeneration != psD->generation;
6164
6165 if (pipelineChanged) {
6166 cbD->currentGraphicsPipeline = nullptr;
6167 cbD->currentComputePipeline = ps;
6169 if (psD->lastUsedInFrameNo != frameNo) {
6171 psD->currentSrb = nullptr;
6173 }
6174
6175 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
6177 cmd.args.bindComputePipeline.ps = ps;
6178 }
6179}
6180
6181template<typename T>
6182inline void qrhigl_accumulateComputeResource(T *writtenResources, QRhiResource *resource,
6183 QRhiShaderResourceBinding::Type bindingType,
6184 int loadTypeVal, int storeTypeVal, int loadStoreTypeVal)
6185{
6186 int access = 0;
6187 if (bindingType == loadTypeVal) {
6189 } else {
6191 if (bindingType == loadStoreTypeVal)
6193 }
6194 auto it = writtenResources->find(resource);
6195 if (it != writtenResources->end())
6196 it->first |= access;
6197 else if (bindingType == storeTypeVal || bindingType == loadStoreTypeVal)
6198 writtenResources->insert(resource, { access, true });
6199}
6200
6201// The glMemoryBarrier() bits needed based on what previous dispatches in the
6202// pass wrote. Updates writtenResources, so call once per dispatch.
6204{
6205 if (!cbD->currentComputeSrb)
6206 return 0;
6207
6208 GLbitfield barriers = 0;
6209
6210 // The key in the writtenResources map indicates that the resource was
6211 // written in a previous dispatch, whereas the value accumulates the
6212 // access mask in the current one.
6213 for (auto &accessAndIsNewFlag : cbD->computePassState.writtenResources)
6214 accessAndIsNewFlag = { 0, false };
6215
6217 const int bindingCount = srbD->m_bindings.size();
6218 for (int i = 0; i < bindingCount; ++i) {
6219 const QRhiShaderResourceBinding::Data *b = shaderResourceBindingData(srbD->m_bindings.at(i));
6220 switch (b->type()) {
6221 case QRhiShaderResourceBinding::ImageLoad:
6222 case QRhiShaderResourceBinding::ImageStore:
6223 case QRhiShaderResourceBinding::ImageLoadStore:
6224 qrhigl_accumulateComputeResource(&cbD->computePassState.writtenResources,
6225 b->simage().tex,
6226 b->type(),
6227 QRhiShaderResourceBinding::ImageLoad,
6228 QRhiShaderResourceBinding::ImageStore,
6229 QRhiShaderResourceBinding::ImageLoadStore);
6230 break;
6231 case QRhiShaderResourceBinding::BufferLoad:
6232 case QRhiShaderResourceBinding::BufferStore:
6233 case QRhiShaderResourceBinding::BufferLoadStore:
6234 qrhigl_accumulateComputeResource(&cbD->computePassState.writtenResources,
6235 b->sbuf().buf,
6236 b->type(),
6237 QRhiShaderResourceBinding::BufferLoad,
6238 QRhiShaderResourceBinding::BufferStore,
6239 QRhiShaderResourceBinding::BufferLoadStore);
6240 break;
6241 default:
6242 break;
6243 }
6244 }
6245
6246 for (auto it = cbD->computePassState.writtenResources.begin(); it != cbD->computePassState.writtenResources.end(); ) {
6247 const int accessInThisDispatch = it->first;
6248 const bool isNewInThisDispatch = it->second;
6249 if (accessInThisDispatch && !isNewInThisDispatch) {
6250 if (it.key()->resourceType() == QRhiResource::Texture)
6252 else
6254 }
6255 // Anything that was previously written, but is only read now, can be
6256 // removed from the written list (because that previous write got a
6257 // corresponding barrier now).
6258 if (accessInThisDispatch == QGles2CommandBuffer::ComputePassState::Read)
6259 it = cbD->computePassState.writtenResources.erase(it);
6260 else
6261 ++it;
6262 }
6263
6264 return barriers;
6265}
6266
6267void QRhiGles2::dispatch(QRhiCommandBuffer *cb, int x, int y, int z)
6268{
6269 QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
6271
6272 if (const GLbitfield barriers = barriersForNextDispatch(cbD)) {
6273 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
6275 cmd.args.barrier.barriers = barriers;
6276 }
6277
6278 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
6280 cmd.args.dispatch.x = GLuint(x);
6281 cmd.args.dispatch.y = GLuint(y);
6282 cmd.args.dispatch.z = GLuint(z);
6283}
6284
6285void QRhiGles2::dispatchIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer,
6286 quint32 indirectBufferOffset)
6287{
6288 if (!caps.dispatchIndirect) {
6289 qWarning("dispatchIndirect called but the DispatchIndirect feature is not supported");
6290 return;
6291 }
6292
6293 QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
6295
6296 // Sample before barriersForNextDispatch(), which drops entries for anything
6297 // the upcoming dispatch only reads - including this buffer, if the consuming
6298 // shader also binds it as a storage buffer.
6299 const bool indirectBufWrittenInThisPass =
6300 cbD->computePassState.writtenResources.contains(indirectBuffer);
6301
6302 GLbitfield barriers = barriersForNextDispatch(cbD);
6303
6304 // The work group counts are read via the command processor, not as a shader
6305 // storage read, hence GL_COMMAND_BARRIER_BIT.
6306 if (indirectBufWrittenInThisPass)
6307 barriers |= GL_COMMAND_BARRIER_BIT;
6308
6309 if (barriers) {
6310 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
6312 cmd.args.barrier.barriers = barriers;
6313 }
6314
6315 QGles2Buffer *indirectBufD = QRHI_RES(QGles2Buffer, indirectBuffer);
6316
6318 QRhiPassResourceTracker &passResTracker(cbD->passResTrackers[cbD->currentPassResTrackerIndex]);
6319 // When already registered - typically as the storage buffer the
6320 // arguments were generated into - registerBuffer() would reject the
6321 // differing access with a warning. Skipping it is fine because
6322 // BarriersForPass sets all buffer barrier bits anyway.
6323 if (!passResTracker.buffers().contains(indirectBufD)) {
6324 trackedRegisterBuffer(&passResTracker, indirectBufD,
6327 }
6328 }
6329
6330 QGles2CommandBuffer::Command &cmd(cbD->commands.get());
6332 cmd.args.dispatchIndirect.buffer = indirectBufD->buffer;
6333 cmd.args.dispatchIndirect.offset = indirectBufferOffset;
6334}
6335
6336static inline GLenum toGlShaderType(QRhiShaderStage::Type type)
6337{
6338 switch (type) {
6339 case QRhiShaderStage::Vertex:
6340 return GL_VERTEX_SHADER;
6341 case QRhiShaderStage::TessellationControl:
6343 case QRhiShaderStage::TessellationEvaluation:
6345 case QRhiShaderStage::Geometry:
6346 return GL_GEOMETRY_SHADER;
6347 case QRhiShaderStage::Fragment:
6348 return GL_FRAGMENT_SHADER;
6349 case QRhiShaderStage::Compute:
6350 return GL_COMPUTE_SHADER;
6351 default:
6352 Q_UNREACHABLE_RETURN(GL_VERTEX_SHADER);
6353 }
6354}
6355
6356static inline bool isGraphicsStage(const QRhiShaderStage &shaderStage)
6357{
6358 const QRhiShaderStage::Type t = shaderStage.type();
6359 return t == QRhiShaderStage::Vertex
6360 || t == QRhiShaderStage::TessellationControl
6361 || t == QRhiShaderStage::TessellationEvaluation
6362 || t == QRhiShaderStage::Geometry
6363 || t == QRhiShaderStage::Fragment;
6364}
6365
6367{
6368 QList<int> versionsToTry;
6369 if (caps.gles) {
6370 if (caps.ctxMajor > 3 || (caps.ctxMajor == 3 && caps.ctxMinor >= 2)) {
6371 versionsToTry << 320 << 310 << 300 << 100;
6372 } else if (caps.ctxMajor == 3 && caps.ctxMinor == 1) {
6373 versionsToTry << 310 << 300 << 100;
6374 } else if (caps.ctxMajor == 3 && caps.ctxMinor == 0) {
6375 versionsToTry << 300 << 100;
6376 } else {
6377 versionsToTry << 100;
6378 }
6379 } else {
6380 if (caps.ctxMajor > 4 || (caps.ctxMajor == 4 && caps.ctxMinor >= 6)) {
6381 versionsToTry << 460 << 450 << 440 << 430 << 420 << 410 << 400 << 330 << 150 << 140 << 130;
6382 } else if (caps.ctxMajor == 4 && caps.ctxMinor == 5) {
6383 versionsToTry << 450 << 440 << 430 << 420 << 410 << 400 << 330 << 150 << 140 << 130;
6384 } else if (caps.ctxMajor == 4 && caps.ctxMinor == 4) {
6385 versionsToTry << 440 << 430 << 420 << 410 << 400 << 330 << 150 << 140 << 130;
6386 } else if (caps.ctxMajor == 4 && caps.ctxMinor == 3) {
6387 versionsToTry << 430 << 420 << 410 << 400 << 330 << 150 << 140 << 130;
6388 } else if (caps.ctxMajor == 4 && caps.ctxMinor == 2) {
6389 versionsToTry << 420 << 410 << 400 << 330 << 150 << 140 << 130;
6390 } else if (caps.ctxMajor == 4 && caps.ctxMinor == 1) {
6391 versionsToTry << 410 << 400 << 330 << 150 << 140 << 130;
6392 } else if (caps.ctxMajor == 4 && caps.ctxMinor == 0) {
6393 versionsToTry << 400 << 330 << 150 << 140 << 130;
6394 } else if (caps.ctxMajor == 3 && caps.ctxMinor == 3) {
6395 versionsToTry << 330 << 150 << 140 << 130;
6396 } else if (caps.ctxMajor == 3 && caps.ctxMinor == 2) {
6397 versionsToTry << 150 << 140 << 130;
6398 } else if (caps.ctxMajor == 3 && caps.ctxMinor == 1) {
6399 versionsToTry << 140 << 130;
6400 } else if (caps.ctxMajor == 3 && caps.ctxMinor == 0) {
6401 versionsToTry << 130;
6402 }
6403 if (!caps.coreProfile)
6404 versionsToTry << 120;
6405 }
6406
6407 const QShaderVersion::Flags flags = caps.gles ? QShaderVersion::GlslEs : QShaderVersion::Flags();
6408 QList<QShaderVersion> versions;
6409 versions.reserve(versionsToTry.size());
6410 for (int v : std::as_const(versionsToTry))
6411 versions.append(QShaderVersion(v, flags));
6412 return versions;
6413}
6414
6415/*
6416 Returns the highest GLSL ES version all graphics stages in stages have code
6417 for, or nothing when they share none. GLSL ES cannot link shaders of
6418 different versions; non-es GLSL can, hence the caps.gles check.
6419*/
6421 int stageCount) const
6422{
6423 if (!caps.gles)
6424 return std::nullopt;
6425
6426 for (const QShaderVersion &ver : glslVersionsToTry()) {
6427 bool allStagesHaveIt = true;
6428 for (int i = 0; i < stageCount; ++i) {
6429 const QRhiShaderStage &stage(stages[i]);
6430 if (!isGraphicsStage(stage))
6431 continue;
6432 const QShaderKey key(QShader::GlslShader, ver, stage.shaderVariant());
6433 if (stage.shader().shader(key).shader().isEmpty()) {
6434 allStagesHaveIt = false;
6435 break;
6436 }
6437 }
6438 if (allStagesHaveIt)
6439 return ver;
6440 }
6441 return std::nullopt;
6442}
6443
6444QByteArray QRhiGles2::shaderSource(const QRhiShaderStage &shaderStage, QShaderVersion *shaderVersion,
6445 std::optional<QShaderVersion> commonVersion)
6446{
6447 const QShader bakedShader = shaderStage.shader();
6448 const QList<QShaderVersion> versionsToTry = commonVersion
6449 ? QList<QShaderVersion>{ *commonVersion }
6450 : glslVersionsToTry();
6451
6452 QByteArray source;
6453 for (const QShaderVersion &ver : versionsToTry) {
6454 source = bakedShader.shader({ QShader::GlslShader, ver, shaderStage.shaderVariant() }).shader();
6455 if (!source.isEmpty()) {
6456 if (shaderVersion)
6457 *shaderVersion = ver;
6458 break;
6459 }
6460 }
6461 if (source.isEmpty()) {
6462 qWarning() << "No GLSL shader code found (versions tried: " << versionsToTry
6463 << ") in baked shader" << bakedShader;
6464 }
6465 return source;
6466}
6467
6468bool QRhiGles2::compileShader(GLuint program, const QRhiShaderStage &shaderStage, QShaderVersion *shaderVersion,
6469 std::optional<QShaderVersion> commonVersion)
6470{
6471 QShaderVersion actualVersion;
6472 const QByteArray source = shaderSource(shaderStage, &actualVersion, commonVersion);
6473 if (source.isEmpty())
6474 return false;
6475 if (shaderVersion)
6476 *shaderVersion = actualVersion;
6477
6478 GLuint shader;
6479 const auto cacheKey = std::make_pair(shaderStage, actualVersion);
6480 auto cacheIt = m_shaderCache.constFind(cacheKey);
6481 if (cacheIt != m_shaderCache.constEnd()) {
6482 shader = *cacheIt;
6483 } else {
6484 shader = f->glCreateShader(toGlShaderType(shaderStage.type()));
6485 const char *srcStr = source.constData();
6486 const GLint srcLength = source.size();
6487 f->glShaderSource(shader, 1, &srcStr, &srcLength);
6488 f->glCompileShader(shader);
6489 GLint compiled = 0;
6490 f->glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
6491 if (!compiled) {
6492 GLint infoLogLength = 0;
6493 f->glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength);
6494 QByteArray log;
6495 if (infoLogLength > 1) {
6496 GLsizei length = 0;
6497 log.resize(infoLogLength);
6498 f->glGetShaderInfoLog(shader, infoLogLength, &length, log.data());
6499 }
6500 qWarning("Failed to compile shader: %s\nSource was:\n%s", log.constData(), source.constData());
6501 f->glDeleteShader(shader);
6502 return false;
6503 }
6504 if (m_shaderCache.size() >= MAX_SHADER_CACHE_ENTRIES) {
6505 // Use the simplest strategy: too many cached shaders -> drop them all.
6506 for (uint shader : std::as_const(m_shaderCache))
6507 f->glDeleteShader(shader); // does not actually get released yet when attached to a not-yet-released program
6508 m_shaderCache.clear();
6509 }
6510 m_shaderCache.insert(cacheKey, shader);
6511 }
6512
6513 f->glAttachShader(program, shader);
6514
6515 return true;
6516}
6517
6519{
6520 if (clearBufferProgram || clearBufferProgramFailed)
6521 return clearBufferProgram;
6522
6523 if (!ensureContext())
6524 return 0;
6525
6526 static const char body[] =
6527 "layout(local_size_x = 64) in;\n"
6528 "layout(std430, binding = 0) buffer Buf { uint data[]; };\n"
6529 "uniform uint offsetWords;\n"
6530 "uniform uint countWords;\n"
6531 "uniform uint value;\n"
6532 "void main() {\n"
6533 " uint stride = gl_NumWorkGroups.x * 64u;\n"
6534 " for (uint i = gl_GlobalInvocationID.x; i < countWords; i += stride)\n"
6535 " data[offsetWords + i] = value;\n"
6536 "}\n";
6537 const QByteArray source = QByteArray(caps.gles ? "#version 310 es\nprecision highp int;\n"
6538 : "#version 430\n") + body;
6539 const char *srcStr = source.constData();
6540
6541 GLuint shader = f->glCreateShader(GL_COMPUTE_SHADER);
6542 f->glShaderSource(shader, 1, &srcStr, nullptr);
6543 f->glCompileShader(shader);
6544 GLint compiled = 0;
6545 f->glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
6546 if (!compiled) {
6547 GLint infoLogLength = 0;
6548 f->glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength);
6549 QByteArray log;
6550 if (infoLogLength > 1) {
6551 GLsizei length = 0;
6552 log.resize(infoLogLength);
6553 f->glGetShaderInfoLog(shader, infoLogLength, &length, log.data());
6554 }
6555 qWarning("Failed to compile buffer clear shader, falling back to uploads: %s", log.constData());
6556 f->glDeleteShader(shader);
6558 return 0;
6559 }
6560
6561 GLuint program = f->glCreateProgram();
6562 f->glAttachShader(program, shader);
6563 const bool linked = linkProgram(program);
6564 f->glDeleteShader(shader);
6565 if (!linked) {
6566 f->glDeleteProgram(program);
6568 return 0;
6569 }
6570
6571 clearBufferUniformLoc[0] = f->glGetUniformLocation(program, "offsetWords");
6572 clearBufferUniformLoc[1] = f->glGetUniformLocation(program, "countWords");
6573 clearBufferUniformLoc[2] = f->glGetUniformLocation(program, "value");
6574 clearBufferProgram = program;
6575 return clearBufferProgram;
6576}
6577
6578bool QRhiGles2::linkProgram(GLuint program)
6579{
6580 f->glLinkProgram(program);
6581 GLint linked = 0;
6582 f->glGetProgramiv(program, GL_LINK_STATUS, &linked);
6583 if (!linked) {
6584 GLint infoLogLength = 0;
6585 f->glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLogLength);
6586 QByteArray log;
6587 if (infoLogLength > 1) {
6588 GLsizei length = 0;
6589 log.resize(infoLogLength);
6590 f->glGetProgramInfoLog(program, infoLogLength, &length, log.data());
6591 }
6592 qWarning("Failed to link shader program: %s", log.constData());
6593 return false;
6594 }
6595 return true;
6596}
6597
6598void QRhiGles2::registerUniformIfActive(const QShaderDescription::BlockVariable &var,
6599 const QByteArray &namePrefix,
6600 int binding,
6601 int baseOffset,
6602 GLuint program,
6603 ActiveUniformLocationTracker *activeUniformLocations,
6604 QGles2UniformDescriptionVector *dst)
6605{
6606 if (var.type == QShaderDescription::Struct) {
6607 qWarning("Nested structs are not supported at the moment. '%s' ignored.",
6608 var.name.constData());
6609 return;
6610 }
6612 uniform.type = var.type;
6613 const QByteArray name = namePrefix + var.name;
6614 // Here we expect that the OpenGL implementation has proper active uniform
6615 // handling, meaning that a uniform that is declared but not accessed
6616 // elsewhere in the code is reported as -1 when querying the location. If
6617 // that is not the case, it won't break anything, but we'll generate
6618 // unnecessary glUniform* calls then.
6619 uniform.glslLocation = f->glGetUniformLocation(program, name.constData());
6620 uniform.stateIndex = -1; // assigned later
6621 if (uniform.glslLocation >= 0 && !activeUniformLocations->hasSeen(uniform.glslLocation)) {
6622 if (var.arrayDims.size() > 1) {
6623 qWarning("Array '%s' has more than one dimension. This is not supported.",
6624 var.name.constData());
6625 return;
6626 }
6627 uniform.binding = binding;
6628 uniform.offset = uint(baseOffset + var.offset);
6629 uniform.size = var.size;
6630 uniform.arrayDim = var.arrayDims.isEmpty() ? 0 : var.arrayDims.first();
6631 // For matrices the distance between the columns is known from the
6632 // reflection. For arrays it has to be derived from the total size.
6633 // (std140 and std430 differ here: an array of scalars or vec2 is
6634 // tightly packed in the latter, which is what push constants use)
6635 if (var.matrixStride)
6636 uniform.elemStride = quint32(var.matrixStride);
6637 else if (uniform.arrayDim > 0 && var.size > 0)
6638 uniform.elemStride = quint32(var.size / uniform.arrayDim);
6639 else
6640 uniform.elemStride = 0;
6641 dst->append(uniform);
6642 }
6643}
6644
6646 const QByteArray &prefix,
6647 int binding,
6648 const QList<QShaderDescription::BlockVariable> &members,
6649 ActiveUniformLocationTracker *activeUniformLocations,
6650 QGles2UniformDescriptionVector *dst)
6651{
6652 for (const QShaderDescription::BlockVariable &blockMember : members) {
6653 if (blockMember.type == QShaderDescription::Struct) {
6654 QByteArray structPrefix = prefix + blockMember.name;
6655
6656 const int baseOffset = blockMember.offset;
6657 if (blockMember.arrayDims.isEmpty()) {
6658 for (const QShaderDescription::BlockVariable &structMember : blockMember.structMembers)
6659 registerUniformIfActive(structMember, structPrefix + ".", binding,
6660 baseOffset, program, activeUniformLocations, dst);
6661 } else {
6662 if (blockMember.arrayDims.size() > 1) {
6663 qWarning("Array of struct '%s' has more than one dimension. Only the first "
6664 "dimension is used.",
6665 blockMember.name.constData());
6666 }
6667 const int dim = blockMember.arrayDims.first();
6668 if (dim < 1) {
6669 qWarning("Array of struct '%s' has an invalid first dimension (%d). Ignored.",
6670 blockMember.name.constData(), dim);
6671 continue;
6672 }
6673 const int elemSize = blockMember.size / dim;
6674 int elemOffset = baseOffset;
6675 for (int di = 0; di < dim; ++di) {
6676 const QByteArray arrayPrefix = structPrefix + '[' + QByteArray::number(di) + ']' + '.';
6677 for (const QShaderDescription::BlockVariable &structMember : blockMember.structMembers)
6678 registerUniformIfActive(structMember, arrayPrefix, binding, elemOffset, program, activeUniformLocations, dst);
6679 elemOffset += elemSize;
6680 }
6681 }
6682 } else {
6683 registerUniformIfActive(blockMember, prefix, binding, 0, program, activeUniformLocations, dst);
6684 }
6685 }
6686}
6687
6688void QRhiGles2::gatherUniforms(GLuint program,
6689 const QShaderDescription::UniformBlock &ub,
6690 ActiveUniformLocationTracker *activeUniformLocations,
6691 QGles2UniformDescriptionVector *dst)
6692{
6693 gatherBlockMemberUniforms(program, ub.structName + '.', ub.binding, ub.members,
6694 activeUniformLocations, dst);
6695}
6696
6697void QRhiGles2::gatherPushConstantUniforms(GLuint program,
6698 const QShaderDescription::PushConstantBlock &pcb,
6699 ActiveUniformLocationTracker *activeUniformLocations,
6700 QGles2UniformDescriptionVector *dst)
6701{
6702 gatherBlockMemberUniforms(program, pcb.name + '.', -1, pcb.members, activeUniformLocations, dst);
6703}
6704
6705void QRhiGles2::gatherSamplers(GLuint program,
6706 const QShaderDescription::InOutVariable &v,
6707 QGles2SamplerDescriptionVector *dst)
6708{
6709 QGles2SamplerDescription sampler;
6710 sampler.glslLocation = f->glGetUniformLocation(program, v.name.constData());
6711 if (sampler.glslLocation >= 0) {
6712 sampler.combinedBinding = v.binding;
6713 sampler.tbinding = -1;
6714 sampler.sbinding = -1;
6715 dst->append(sampler);
6716 }
6717}
6718
6719void QRhiGles2::gatherGeneratedSamplers(GLuint program,
6720 const QShader::SeparateToCombinedImageSamplerMapping &mapping,
6721 QGles2SamplerDescriptionVector *dst)
6722{
6723 QGles2SamplerDescription sampler;
6724 sampler.glslLocation = f->glGetUniformLocation(program, mapping.combinedSamplerName.constData());
6725 if (sampler.glslLocation >= 0) {
6726 sampler.combinedBinding = -1;
6727 sampler.tbinding = mapping.textureBinding;
6728 sampler.sbinding = mapping.samplerBinding;
6729 dst->append(sampler);
6730 }
6731}
6732
6733void QRhiGles2::sanityCheckVertexFragmentInterface(const QShaderDescription &vsDesc, const QShaderDescription &fsDesc)
6734{
6735 if (!vsDesc.isValid() || !fsDesc.isValid())
6736 return;
6737
6738 // Print a warning if the fragment shader input for a given location uses a
6739 // name that does not match the vertex shader output at the same location.
6740 // This is not an error with any other API and not with GLSL >= 330 either,
6741 // but matters for older GLSL code that has no location qualifiers.
6742 const auto vsOutputs = vsDesc.outputVariables();
6743 const auto fsInputs = fsDesc.inputVariables();
6744 for (const QShaderDescription::InOutVariable &outVar : vsOutputs) {
6745 for (const QShaderDescription::InOutVariable &inVar : fsInputs) {
6746 if (inVar.location == outVar.location) {
6747 if (inVar.name != outVar.name) {
6748 qWarning("Vertex output name '%s' does not match fragment input '%s'. "
6749 "This should be avoided because it causes problems with older GLSL versions.",
6750 outVar.name.constData(), inVar.name.constData());
6751 }
6752 break;
6753 }
6754 }
6755 }
6756}
6757
6758bool QRhiGles2::isProgramBinaryDiskCacheEnabled() const
6759{
6760 static QOpenGLProgramBinarySupportCheckWrapper checker;
6761 return checker.get(ctx)->isSupported();
6762}
6763
6764Q_GLOBAL_STATIC(QOpenGLProgramBinaryCache, qrhi_programBinaryCache);
6765
6766static inline QShader::Stage toShaderStage(QRhiShaderStage::Type type)
6767{
6768 switch (type) {
6769 case QRhiShaderStage::Vertex:
6770 return QShader::VertexStage;
6771 case QRhiShaderStage::TessellationControl:
6772 return QShader::TessellationControlStage;
6773 case QRhiShaderStage::TessellationEvaluation:
6774 return QShader::TessellationEvaluationStage;
6775 case QRhiShaderStage::Geometry:
6776 return QShader::GeometryStage;
6777 case QRhiShaderStage::Fragment:
6778 return QShader::FragmentStage;
6779 case QRhiShaderStage::Compute:
6780 return QShader::ComputeStage;
6781 default:
6782 Q_UNREACHABLE_RETURN(QShader::VertexStage);
6783 }
6784}
6785
6786QRhiGles2::ProgramCacheResult QRhiGles2::tryLoadFromDiskOrPipelineCache(const QRhiShaderStage *stages,
6787 int stageCount,
6788 GLuint program,
6789 const QVector<QShaderDescription::InOutVariable> &inputVars,
6790 QByteArray *cacheKey,
6791 std::optional<QShaderVersion> commonVersion)
6792{
6793 Q_ASSERT(cacheKey);
6794
6795 // the traditional QOpenGL disk cache since Qt 5.9
6796 const bool legacyDiskCacheEnabled = isProgramBinaryDiskCacheEnabled();
6797
6798 // QRhi's own (set)PipelineCacheData()
6799 const bool pipelineCacheEnabled = caps.programBinary && !m_pipelineCache.data.isEmpty();
6800
6801 // calculating the cache key based on the source code is common for both types of caches
6802 if (legacyDiskCacheEnabled || pipelineCacheEnabled) {
6803 QOpenGLProgramBinaryCache::ProgramDesc binaryProgram;
6804 for (int i = 0; i < stageCount; ++i) {
6805 const QRhiShaderStage &stage(stages[i]);
6806 // commonVersion covers the graphics stages only.
6807 QByteArray source = shaderSource(stage, nullptr,
6808 isGraphicsStage(stage) ? commonVersion : std::nullopt);
6809 if (source.isEmpty())
6810 return QRhiGles2::ProgramCacheError;
6811
6812 if (stage.type() == QRhiShaderStage::Vertex) {
6813 // Now add something to the key that indicates the vertex input locations.
6814 // A GLSL shader lower than 330 (150, 140, ...) will not have location
6815 // qualifiers. This means that the shader source code is the same
6816 // regardless of what locations inputVars contains. This becomes a problem
6817 // because we'll glBindAttribLocation the shader based on inputVars, but
6818 // that's only when compiling/linking when there was no cache hit. Picking
6819 // from the cache afterwards should take the input locations into account
6820 // since if inputVars has now different locations for the attributes, then
6821 // it is not ok to reuse a program binary that used different attribute
6822 // locations. For a lot of clients this would not be an issue since they
6823 // typically hardcode and use the same vertex locations on every run. Some
6824 // systems that dynamically generate shaders may end up with a non-stable
6825 // order (and so location numbers), however. This is sub-optimal because
6826 // it makes caching inefficient, and said clients should be fixed, but in
6827 // any case this should not break rendering. Hence including the locations
6828 // in the cache key.
6829 QMap<QByteArray, int> inputLocations; // sorted by key when iterating
6830 for (const QShaderDescription::InOutVariable &var : inputVars)
6831 inputLocations.insert(var.name, var.location);
6832 source += QByteArrayLiteral("\n // "); // just to be nice; treated as an arbitrary string regardless
6833 for (auto it = inputLocations.cbegin(), end = inputLocations.cend(); it != end; ++it) {
6834 source += it.key();
6835 source += QByteArray::number(it.value());
6836 }
6837 source += QByteArrayLiteral("\n");
6838 }
6839
6840 binaryProgram.shaders.append(QOpenGLProgramBinaryCache::ShaderDesc(toShaderStage(stage.type()), source));
6841 }
6842
6843 *cacheKey = binaryProgram.cacheKey();
6844
6845 // Try our pipeline cache simulation first, if it got seeded with
6846 // setPipelineCacheData and there's a hit, then no need to go to the
6847 // filesystem at all.
6848 if (pipelineCacheEnabled) {
6849 auto it = m_pipelineCache.data.constFind(*cacheKey);
6850 if (it != m_pipelineCache.data.constEnd()) {
6851 GLenum err;
6852 for ( ; ; ) {
6853 err = f->glGetError();
6854 if (err == GL_NO_ERROR || err == GL_CONTEXT_LOST)
6855 break;
6856 }
6857 f->glProgramBinary(program, it->format, it->data.constData(), it->data.size());
6858 err = f->glGetError();
6859 if (err == GL_NO_ERROR) {
6860 GLint linkStatus = 0;
6861 f->glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
6862 if (linkStatus == GL_TRUE)
6863 return QRhiGles2::ProgramCacheHit;
6864 }
6865 }
6866 }
6867
6868 if (legacyDiskCacheEnabled && qrhi_programBinaryCache()->load(*cacheKey, program)) {
6869 // use the logging category QOpenGLShaderProgram would
6870 qCDebug(lcOpenGLProgramDiskCache, "Program binary received from cache, program %u, key %s",
6871 program, cacheKey->constData());
6872 return QRhiGles2::ProgramCacheHit;
6873 }
6874 }
6875
6876 return QRhiGles2::ProgramCacheMiss;
6877}
6878
6879void QRhiGles2::trySaveToDiskCache(GLuint program, const QByteArray &cacheKey)
6880{
6881 // This is only for the traditional QOpenGL disk cache since Qt 5.9.
6882
6883 if (isProgramBinaryDiskCacheEnabled()) {
6884 // use the logging category QOpenGLShaderProgram would
6885 qCDebug(lcOpenGLProgramDiskCache, "Saving program binary, program %u, key %s",
6886 program, cacheKey.constData());
6887 qrhi_programBinaryCache()->save(cacheKey, program);
6888 }
6889}
6890
6891void QRhiGles2::trySaveToPipelineCache(GLuint program, const QByteArray &cacheKey, bool force)
6892{
6893 // This handles our own simulated "pipeline cache". (specific to QRhi, not
6894 // shared with legacy QOpenGL* stuff)
6895
6896 if (caps.programBinary && (force || !m_pipelineCache.data.contains(cacheKey))) {
6897 GLint blobSize = 0;
6898 f->glGetProgramiv(program, GL_PROGRAM_BINARY_LENGTH, &blobSize);
6899 QByteArray blob(blobSize, Qt::Uninitialized);
6900 GLint outSize = 0;
6901 GLenum binaryFormat = 0;
6902 f->glGetProgramBinary(program, blobSize, &outSize, &binaryFormat, blob.data());
6903 if (blobSize == outSize)
6904 m_pipelineCache.insertWithCapacityLimit(cacheKey, { binaryFormat, blob });
6905 }
6906}
6907
6908QGles2Buffer::QGles2Buffer(QRhiImplementation *rhi, Type type, UsageFlags usage, quint32 size)
6909 : QRhiBuffer(rhi, type, usage, size)
6910{
6911}
6912
6913QGles2Buffer::~QGles2Buffer()
6914{
6915 destroy();
6916}
6917
6918void QGles2Buffer::destroy()
6919{
6920 data.clear();
6921 if (!buffer)
6922 return;
6923
6924 QRhiGles2::DeferredReleaseEntry e;
6925 e.type = QRhiGles2::DeferredReleaseEntry::Buffer;
6926
6927 e.buffer.buffer = buffer;
6928 buffer = 0;
6929
6930 QRHI_RES_RHI(QRhiGles2);
6931 if (rhiD) {
6932 rhiD->releaseQueue.append(e);
6933 rhiD->unregisterResource(this);
6934 }
6935}
6936
6937bool QGles2Buffer::create()
6938{
6939 if (buffer)
6940 destroy();
6941
6942 QRHI_RES_RHI(QRhiGles2);
6943
6944 nonZeroSize = m_size <= 0 ? 256 : m_size;
6945
6946 if (m_usage.testFlag(QRhiBuffer::UniformBuffer)) {
6947 if (int(m_usage) != QRhiBuffer::UniformBuffer) {
6948 qWarning("Uniform buffer: multiple usages specified, this is not supported by the OpenGL backend");
6949 return false;
6950 }
6951 data.resize(nonZeroSize);
6952 return true;
6953 }
6954
6955 if (!rhiD->ensureContext())
6956 return false;
6957
6958 targetForDataOps = GL_ARRAY_BUFFER;
6959 if (m_usage.testFlag(QRhiBuffer::IndexBuffer))
6960 targetForDataOps = GL_ELEMENT_ARRAY_BUFFER;
6961 else if (m_usage.testFlag(QRhiBuffer::StorageBuffer))
6962 targetForDataOps = GL_SHADER_STORAGE_BUFFER;
6963 else if (m_usage.testFlag(QRhiBuffer::IndirectBuffer))
6964 targetForDataOps = GL_DRAW_INDIRECT_BUFFER;
6965
6966 buffer = rhiD->genBuffer();
6967 rhiD->f->glBindBuffer(targetForDataOps, buffer);
6968 rhiD->f->glBufferData(targetForDataOps, nonZeroSize, nullptr, m_type == Dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);
6969
6970 if (rhiD->glObjectLabel)
6971 rhiD->glObjectLabel(GL_BUFFER, buffer, -1, m_objectName.constData());
6972
6973 usageState.access = AccessNone;
6974
6975 rhiD->registerResource(this);
6976 return true;
6977}
6978
6979QRhiBuffer::NativeBuffer QGles2Buffer::nativeBuffer()
6980{
6981 if (m_usage.testFlag(QRhiBuffer::UniformBuffer))
6982 return { {}, 0 };
6983
6984 return { { &buffer }, 1 };
6985}
6986
6987char *QGles2Buffer::beginFullDynamicBufferUpdateForCurrentFrame()
6988{
6989 Q_ASSERT(m_type == Dynamic);
6990 if (!m_usage.testFlag(UniformBuffer)) {
6991 QRHI_RES_RHI(QRhiGles2);
6992 rhiD->f->glBindBuffer(targetForDataOps, buffer);
6993 if (rhiD->caps.properMapBuffer) {
6994 return static_cast<char *>(rhiD->f->glMapBufferRange(targetForDataOps, 0, nonZeroSize,
6996 } else {
6997 // Need some storage for the data, use the otherwise unused 'data' member.
6998 if (data.isEmpty())
6999 data.resize(nonZeroSize);
7000 }
7001 }
7002 return data.data();
7003}
7004
7005void QGles2Buffer::endFullDynamicBufferUpdateForCurrentFrame()
7006{
7007 if (!m_usage.testFlag(UniformBuffer)) {
7008 QRHI_RES_RHI(QRhiGles2);
7009 rhiD->f->glBindBuffer(targetForDataOps, buffer);
7010 if (rhiD->caps.properMapBuffer)
7011 rhiD->f->glUnmapBuffer(targetForDataOps);
7012 else
7013 rhiD->f->glBufferSubData(targetForDataOps, 0, nonZeroSize, data.data());
7014 }
7015}
7016
7017void QGles2Buffer::fullDynamicBufferUpdateForCurrentFrame(const void *bufferData, quint32 size)
7018{
7019 const quint32 copySize = size > 0 ? size : m_size;
7020 if (!m_usage.testFlag(UniformBuffer)) {
7021 QRHI_RES_RHI(QRhiGles2);
7022 rhiD->f->glBindBuffer(targetForDataOps, buffer);
7023 rhiD->f->glBufferSubData(targetForDataOps, 0, copySize, bufferData);
7024 } else {
7025 memcpy(data.data(), bufferData, copySize);
7026 }
7027}
7028
7029QGles2RenderBuffer::QGles2RenderBuffer(QRhiImplementation *rhi, Type type, const QSize &pixelSize,
7030 int sampleCount, QRhiRenderBuffer::Flags flags,
7031 QRhiTexture::Format backingFormatHint)
7032 : QRhiRenderBuffer(rhi, type, pixelSize, sampleCount, flags, backingFormatHint)
7033{
7034}
7035
7036QGles2RenderBuffer::~QGles2RenderBuffer()
7037{
7038 destroy();
7039}
7040
7041void QGles2RenderBuffer::destroy()
7042{
7043 if (!renderbuffer)
7044 return;
7045
7046 QRhiGles2::DeferredReleaseEntry e;
7047 e.type = QRhiGles2::DeferredReleaseEntry::RenderBuffer;
7048
7049 e.renderbuffer.renderbuffer = renderbuffer;
7050 e.renderbuffer.renderbuffer2 = stencilRenderbuffer;
7051
7052 renderbuffer = 0;
7053 stencilRenderbuffer = 0;
7054
7055 QRHI_RES_RHI(QRhiGles2);
7056 if (rhiD) {
7057 if (owns)
7058 rhiD->releaseQueue.append(e);
7059 rhiD->unregisterResource(this);
7060 }
7061}
7062
7063bool QGles2RenderBuffer::create()
7064{
7065 if (renderbuffer)
7066 destroy();
7067
7068 QRHI_RES_RHI(QRhiGles2);
7069 samples = rhiD->effectiveSampleCount(m_sampleCount);
7070
7071 if (m_flags.testFlag(UsedWithSwapChainOnly)) {
7072 if (m_type == DepthStencil)
7073 return true;
7074
7075 qWarning("RenderBuffer: UsedWithSwapChainOnly is meaningless in combination with Color");
7076 }
7077
7078 if (!rhiD->ensureContext())
7079 return false;
7080
7081 rhiD->f->glGenRenderbuffers(1, &renderbuffer);
7082 rhiD->f->glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
7083
7084 const QSize size = m_pixelSize.isEmpty() ? QSize(1, 1) : m_pixelSize;
7085
7086 switch (m_type) {
7087 case QRhiRenderBuffer::DepthStencil:
7088 if (rhiD->caps.msaaRenderBuffer && samples > 1) {
7089 if (rhiD->caps.glesMultisampleRenderToTexture) {
7090 // Must match the logic in QGles2TextureRenderTarget::create().
7091 // EXT and non-EXT are not the same thing.
7092 rhiD->glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER, samples, GL_DEPTH24_STENCIL8,
7093 size.width(), size.height());
7094 } else {
7095 rhiD->f->glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, GL_DEPTH24_STENCIL8,
7096 size.width(), size.height());
7097 }
7098 stencilRenderbuffer = 0;
7099 } else if (rhiD->caps.packedDepthStencil || rhiD->caps.needsDepthStencilCombinedAttach) {
7100 const GLenum storage = rhiD->caps.needsDepthStencilCombinedAttach ? GL_DEPTH_STENCIL : GL_DEPTH24_STENCIL8;
7101 rhiD->f->glRenderbufferStorage(GL_RENDERBUFFER, storage,
7102 size.width(), size.height());
7103 stencilRenderbuffer = 0;
7104 } else {
7105 GLenum depthStorage = GL_DEPTH_COMPONENT;
7106 if (rhiD->caps.gles) {
7107 if (rhiD->caps.depth24)
7108 depthStorage = GL_DEPTH_COMPONENT24;
7109 else
7110 depthStorage = GL_DEPTH_COMPONENT16; // plain ES 2.0 only has this
7111 }
7112 const GLenum stencilStorage = rhiD->caps.gles ? GL_STENCIL_INDEX8 : GL_STENCIL_INDEX;
7113 rhiD->f->glRenderbufferStorage(GL_RENDERBUFFER, depthStorage,
7114 size.width(), size.height());
7115 rhiD->f->glGenRenderbuffers(1, &stencilRenderbuffer);
7116 rhiD->f->glBindRenderbuffer(GL_RENDERBUFFER, stencilRenderbuffer);
7117 rhiD->f->glRenderbufferStorage(GL_RENDERBUFFER, stencilStorage,
7118 size.width(), size.height());
7119 }
7120 break;
7121 case QRhiRenderBuffer::Color:
7122 {
7123 GLenum internalFormat = GL_RGBA4; // ES 2.0
7124 if (rhiD->caps.rgba8Format) {
7125 internalFormat = GL_RGBA8;
7126 if (m_backingFormatHint != QRhiTexture::UnknownFormat) {
7127 GLenum glintformat, glformat, gltype;
7128 // only care about the sized internal format, the rest is not used here
7129 toGlTextureFormat(m_backingFormatHint, {}, rhiD->caps,
7130 &glintformat, &internalFormat, &glformat, &gltype);
7131 }
7132 }
7133 if (rhiD->caps.msaaRenderBuffer && samples > 1) {
7134 rhiD->f->glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, internalFormat,
7135 size.width(), size.height());
7136 } else {
7137 rhiD->f->glRenderbufferStorage(GL_RENDERBUFFER, internalFormat,
7138 size.width(), size.height());
7139 }
7140 }
7141 break;
7142 default:
7143 Q_UNREACHABLE();
7144 break;
7145 }
7146
7147 if (rhiD->glObjectLabel)
7148 rhiD->glObjectLabel(GL_RENDERBUFFER, renderbuffer, -1, m_objectName.constData());
7149
7150 owns = true;
7151 generation += 1;
7152 rhiD->registerResource(this);
7153 return true;
7154}
7155
7156bool QGles2RenderBuffer::createFrom(NativeRenderBuffer src)
7157{
7158 if (!src.object)
7159 return false;
7160
7161 if (renderbuffer)
7162 destroy();
7163
7164 QRHI_RES_RHI(QRhiGles2);
7165 samples = rhiD->effectiveSampleCount(m_sampleCount);
7166
7167 if (m_flags.testFlag(UsedWithSwapChainOnly))
7168 qWarning("RenderBuffer: UsedWithSwapChainOnly is meaningless when importing an existing native object");
7169
7170 if (!rhiD->ensureContext())
7171 return false;
7172
7173 renderbuffer = src.object;
7174
7175 owns = false;
7176 generation += 1;
7177 rhiD->registerResource(this);
7178 return true;
7179}
7180
7181QRhiTexture::Format QGles2RenderBuffer::backingFormat() const
7182{
7183 if (m_backingFormatHint != QRhiTexture::UnknownFormat)
7184 return m_backingFormatHint;
7185 else
7186 return m_type == Color ? QRhiTexture::RGBA8 : QRhiTexture::UnknownFormat;
7187}
7188
7189QGles2Texture::QGles2Texture(QRhiImplementation *rhi, Format format, const QSize &pixelSize, int depth,
7190 int arraySize, int sampleCount, Flags flags)
7191 : QRhiTexture(rhi, format, pixelSize, depth, arraySize, sampleCount, flags)
7192{
7193}
7194
7195QGles2Texture::~QGles2Texture()
7196{
7197 destroy();
7198}
7199
7200void QGles2Texture::destroy()
7201{
7202 if (!texture)
7203 return;
7204
7205 QRhiGles2::DeferredReleaseEntry e;
7206 e.type = QRhiGles2::DeferredReleaseEntry::Texture;
7207
7208 e.texture.texture = texture;
7209
7210 texture = 0;
7211 specified = false;
7212 for (quint32 &levelMask : allocatedLevels)
7213 levelMask = 0;
7214
7215 QRHI_RES_RHI(QRhiGles2);
7216 if (rhiD) {
7217 if (owns)
7218 rhiD->releaseQueue.append(e);
7219 rhiD->unregisterResource(this);
7220 }
7221}
7222
7223bool QGles2Texture::prepareCreate(QSize *adjustedSize)
7224{
7225 if (texture)
7226 destroy();
7227
7228 QRHI_RES_RHI(QRhiGles2);
7229 if (!rhiD->ensureContext())
7230 return false;
7231 if (!rhiD->isTextureFormatSupported(m_format, m_flags))
7232 return false;
7233
7234 const bool isCube = m_flags.testFlag(CubeMap);
7235 const bool isArray = m_flags.testFlag(QRhiTexture::TextureArray);
7236 const bool is3D = m_flags.testFlag(ThreeDimensional);
7237 const bool hasMipMaps = m_flags.testFlag(MipMapped);
7238 const bool isCompressed = rhiD->isCompressedFormat(m_format);
7239 const bool is1D = m_flags.testFlag(OneDimensional);
7240
7241 const QSize size = is1D ? QSize(qMax(1, m_pixelSize.width()), 1)
7242 : (m_pixelSize.isEmpty() ? QSize(1, 1) : m_pixelSize);
7243
7244 samples = rhiD->effectiveSampleCount(m_sampleCount);
7245
7246 if (is3D && !rhiD->caps.texture3D) {
7247 qWarning("3D textures are not supported");
7248 return false;
7249 }
7250 if (isCube && is3D) {
7251 qWarning("Texture cannot be both cube and 3D");
7252 return false;
7253 }
7254 if (isArray && is3D) {
7255 qWarning("Texture cannot be both array and 3D");
7256 return false;
7257 }
7258 if (is1D && !rhiD->caps.texture1D) {
7259 qWarning("1D textures are not supported");
7260 return false;
7261 }
7262 if (is1D && is3D) {
7263 qWarning("Texture cannot be both 1D and 3D");
7264 return false;
7265 }
7266 if (is1D && isCube) {
7267 qWarning("Texture cannot be both 1D and cube");
7268 return false;
7269 }
7270
7271 if (m_depth > 1 && !is3D) {
7272 qWarning("Texture cannot have a depth of %d when it is not 3D", m_depth);
7273 return false;
7274 }
7275 if (m_arraySize > 0 && !isArray) {
7276 qWarning("Texture cannot have an array size of %d when it is not an array", m_arraySize);
7277 return false;
7278 }
7279 if (m_arraySize < 1 && isArray) {
7280 qWarning("Texture is an array but array size is %d", m_arraySize);
7281 return false;
7282 }
7283
7284 target = isCube ? GL_TEXTURE_CUBE_MAP
7286 : (is3D ? GL_TEXTURE_3D
7287 : (is1D ? (isArray ? GL_TEXTURE_1D_ARRAY : GL_TEXTURE_1D)
7288 : (isArray ? GL_TEXTURE_2D_ARRAY : GL_TEXTURE_2D)));
7289
7290 if (m_flags.testFlag(ExternalOES))
7291 target = GL_TEXTURE_EXTERNAL_OES;
7292 else if (m_flags.testFlag(TextureRectangleGL))
7293 target = GL_TEXTURE_RECTANGLE;
7294
7295 mipLevelCount = hasMipMaps ? rhiD->q->mipLevelsForSize(size) : 1;
7296 gltype = GL_UNSIGNED_BYTE;
7297
7298 if (isCompressed) {
7299 if (m_flags.testFlag(UsedWithLoadStore)) {
7300 qWarning("Compressed texture cannot be used with image load/store");
7301 return false;
7302 }
7303 glintformat = toGlCompressedTextureFormat(m_format, m_flags);
7304 if (!glintformat) {
7305 qWarning("Compressed format %d not mappable to GL compressed format", m_format);
7306 return false;
7307 }
7308 glsizedintformat = glintformat;
7309 glformat = GL_RGBA;
7310 } else {
7311 toGlTextureFormat(m_format, m_flags, rhiD->caps,
7312 &glintformat, &glsizedintformat, &glformat, &gltype);
7313 }
7314
7315 samplerState = QGles2SamplerData();
7316
7317 usageState.access = AccessNone;
7318
7319 if (!rhiD->textureFormatInfo(m_format, size, nullptr, nullptr, nullptr))
7320 return false;
7321
7322 if (adjustedSize)
7323 *adjustedSize = size;
7324
7325 return true;
7326}
7327
7328// glTexStorage2DMultisample is GLES 3.1 and OpenGL 4.3, use
7329// glTexImage2DMultisample (OpenGL 3.2) where it is not available.
7330static void specifyMultisampleTexture2D(QRhiGles2 *rhiD, GLenum target, int samples,
7331 GLenum internalFormat, const QSize &size)
7332{
7333 if (rhiD->caps.multisampledTextureStorage) {
7334 rhiD->f->glTexStorage2DMultisample(target, samples, internalFormat,
7335 size.width(), size.height(), GL_TRUE);
7336 } else if (rhiD->glTexImage2DMultisample) {
7337 rhiD->glTexImage2DMultisample(target, samples, internalFormat,
7338 size.width(), size.height(), GL_TRUE);
7339 }
7340}
7341
7342bool QGles2Texture::create()
7343{
7344 QSize size;
7345 if (!prepareCreate(&size))
7346 return false;
7347
7348 QRHI_RES_RHI(QRhiGles2);
7349 rhiD->f->glGenTextures(1, &texture);
7350
7351 const bool isCube = m_flags.testFlag(CubeMap);
7352 const bool isArray = m_flags.testFlag(QRhiTexture::TextureArray);
7353 const bool is3D = m_flags.testFlag(ThreeDimensional);
7354 const bool hasMipMaps = m_flags.testFlag(MipMapped);
7355 const bool isCompressed = rhiD->isCompressedFormat(m_format);
7356 const bool is1D = m_flags.testFlag(OneDimensional);
7357
7358 if (!isCompressed) {
7359 rhiD->f->glBindTexture(target, texture);
7360 if (!m_flags.testFlag(UsedWithLoadStore)) {
7361 if (is1D) {
7362 for (int level = 0; level < mipLevelCount; ++level) {
7363 const QSize mipSize = rhiD->q->sizeForMipLevel(level, size);
7364 if (isArray)
7365 rhiD->f->glTexImage2D(target, level, GLint(glintformat), mipSize.width(),
7366 qMax(0, m_arraySize), 0, glformat, gltype, nullptr);
7367 else
7368 rhiD->glTexImage1D(target, level, GLint(glintformat), mipSize.width(), 0,
7369 glformat, gltype, nullptr);
7370 }
7371 } else if (isArray) {
7372 const int layerCount = qMax(0, m_arraySize);
7373 if (hasMipMaps) {
7374 for (int level = 0; level != mipLevelCount; ++level) {
7375 const QSize mipSize = rhiD->q->sizeForMipLevel(level, size);
7376 rhiD->f->glTexImage3D(target, level, GLint(glintformat), mipSize.width(), mipSize.height(), layerCount,
7377 0, glformat, gltype, nullptr);
7378 }
7379 } else {
7380 rhiD->f->glTexImage3D(target, 0, GLint(glintformat), size.width(), size.height(), layerCount,
7381 0, glformat, gltype, nullptr);
7382 }
7383 } else if (is3D) {
7384 if (hasMipMaps) {
7385 const int depth = qMax(1, m_depth);
7386 for (int level = 0; level != mipLevelCount; ++level) {
7387 const QSize mipSize = rhiD->q->sizeForMipLevel(level, size);
7388 const int mipDepth = rhiD->q->sizeForMipLevel(level, QSize(depth, depth)).width();
7389 rhiD->f->glTexImage3D(target, level, GLint(glintformat), mipSize.width(), mipSize.height(), mipDepth,
7390 0, glformat, gltype, nullptr);
7391 }
7392 } else {
7393 rhiD->f->glTexImage3D(target, 0, GLint(glintformat), size.width(), size.height(), qMax(1, m_depth),
7394 0, glformat, gltype, nullptr);
7395 }
7396 } else if (hasMipMaps || isCube) {
7397 const GLenum faceTargetBase = isCube ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : target;
7398 for (int layer = 0, layerCount = isCube ? 6 : 1; layer != layerCount; ++layer) {
7399 for (int level = 0; level != mipLevelCount; ++level) {
7400 const QSize mipSize = rhiD->q->sizeForMipLevel(level, size);
7401 rhiD->f->glTexImage2D(faceTargetBase + uint(layer), level, GLint(glintformat),
7402 mipSize.width(), mipSize.height(), 0,
7403 glformat, gltype, nullptr);
7404 }
7405 }
7406 } else {
7407 // 2D texture. Multisample textures need a sized internal format.
7408 if (samples > 1 && rhiD->caps.multisampledTexture) {
7409 specifyMultisampleTexture2D(rhiD, target, samples, glsizedintformat, size);
7410 } else {
7411 rhiD->f->glTexImage2D(target, 0, GLint(glintformat), size.width(), size.height(),
7412 0, glformat, gltype, nullptr);
7413 }
7414 }
7415 } else {
7416 // Must be specified with immutable storage functions otherwise
7417 // bindImageTexture may fail. Also, the internal format must be a
7418 // sized format here.
7419 if (is1D && !isArray)
7420 rhiD->glTexStorage1D(target, mipLevelCount, glsizedintformat, size.width());
7421 else if (!is1D && (is3D || isArray))
7422 rhiD->f->glTexStorage3D(target, mipLevelCount, glsizedintformat, size.width(), size.height(),
7423 is3D ? qMax(1, m_depth) : qMax(0, m_arraySize));
7424 else if (samples > 1)
7425 specifyMultisampleTexture2D(rhiD, target, samples, glsizedintformat, size);
7426 else
7427 rhiD->f->glTexStorage2D(target, mipLevelCount, glsizedintformat, size.width(),
7428 is1D ? qMax(0, m_arraySize) : size.height());
7429 }
7430 // Make sure the min filter is set to something non-mipmap-based already
7431 // here, given the ridiculous default of GL. It is changed based on
7432 // the sampler later, but there could be cases when one pulls the native
7433 // object out via nativeTexture() right away.
7434 if (!isMultisampleTextureTarget(target))
7435 rhiD->f->glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
7436 specified = true;
7437 } else if (rhiD->caps.textureStorage && !m_flags.testFlag(ExternalOES)
7438 && (!is1D || isArray || rhiD->glTexStorage1D))
7439 {
7440 // A compressed format cannot be specified with glCompressedTexImage2D(nullptr),
7441 // but the immutable storage functions do not need data, so allocate all mip
7442 // levels up front. Some implementations reject certain compressed formats
7443 // here however (e.g. ASTC with the Android emulator), so check and fall back
7444 // to allocating each level upon the first upload touching it.
7445 rhiD->f->glBindTexture(target, texture);
7446 GLenum err;
7447 for ( ; ; ) {
7448 err = rhiD->f->glGetError();
7449 if (err == GL_NO_ERROR || err == GL_CONTEXT_LOST)
7450 break;
7451 }
7452 if (is1D && !isArray) {
7453 rhiD->glTexStorage1D(target, mipLevelCount, glsizedintformat, size.width());
7454 } else if (!is1D && (is3D || isArray)) {
7455 rhiD->f->glTexStorage3D(target, mipLevelCount, glsizedintformat, size.width(), size.height(),
7456 is3D ? qMax(1, m_depth) : qMax(0, m_arraySize));
7457 } else {
7458 rhiD->f->glTexStorage2D(target, mipLevelCount, glsizedintformat, size.width(),
7459 is1D ? qMax(0, m_arraySize) : size.height());
7460 }
7461 specified = rhiD->f->glGetError() == GL_NO_ERROR;
7462 if (specified) // min filter must not be mipmap-based, see above
7463 rhiD->f->glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
7464 } else {
7465 specified = false;
7466 }
7467
7468 if (rhiD->glObjectLabel)
7469 rhiD->glObjectLabel(GL_TEXTURE, texture, -1, m_objectName.constData());
7470
7471 owns = true;
7472
7473 generation += 1;
7474 rhiD->registerResource(this);
7475 return true;
7476}
7477
7478bool QGles2Texture::createFrom(QRhiTexture::NativeTexture src)
7479{
7480 const uint textureId = uint(src.object);
7481 if (textureId == 0)
7482 return false;
7483
7484 if (!prepareCreate())
7485 return false;
7486
7487 texture = textureId;
7488 specified = true;
7489
7490 owns = false;
7491
7492 generation += 1;
7493 QRHI_RES_RHI(QRhiGles2);
7494 rhiD->registerResource(this);
7495 return true;
7496}
7497
7498QRhiTexture::NativeTexture QGles2Texture::nativeTexture()
7499{
7500 return {texture, 0};
7501}
7502
7503QGles2Sampler::QGles2Sampler(QRhiImplementation *rhi, Filter magFilter, Filter minFilter, Filter mipmapMode,
7504 AddressMode u, AddressMode v, AddressMode w)
7505 : QRhiSampler(rhi, magFilter, minFilter, mipmapMode, u, v, w)
7506{
7507}
7508
7509QGles2Sampler::~QGles2Sampler()
7510{
7511 destroy();
7512}
7513
7514void QGles2Sampler::destroy()
7515{
7516 QRHI_RES_RHI(QRhiGles2);
7517 if (rhiD)
7518 rhiD->unregisterResource(this);
7519}
7520
7521bool QGles2Sampler::create()
7522{
7523 d.glminfilter = toGlMinFilter(m_minFilter, m_mipmapMode);
7524 d.glmagfilter = toGlMagFilter(m_magFilter);
7525 d.glwraps = toGlWrapMode(m_addressU);
7526 d.glwrapt = toGlWrapMode(m_addressV);
7527 d.glwrapr = toGlWrapMode(m_addressW);
7528 d.gltexcomparefunc = toGlTextureCompareFunc(m_compareOp);
7529
7530 generation += 1;
7531 QRHI_RES_RHI(QRhiGles2);
7532 rhiD->registerResource(this, false);
7533 return true;
7534}
7535
7536// dummy, no Vulkan-style RenderPass+Framebuffer concept here
7537QGles2RenderPassDescriptor::QGles2RenderPassDescriptor(QRhiImplementation *rhi)
7538 : QRhiRenderPassDescriptor(rhi)
7539{
7540}
7541
7542QGles2RenderPassDescriptor::~QGles2RenderPassDescriptor()
7543{
7544 destroy();
7545}
7546
7547void QGles2RenderPassDescriptor::destroy()
7548{
7549 QRHI_RES_RHI(QRhiGles2);
7550 if (rhiD)
7551 rhiD->unregisterResource(this);
7552}
7553
7554bool QGles2RenderPassDescriptor::isCompatible(const QRhiRenderPassDescriptor *other) const
7555{
7556 Q_UNUSED(other);
7557 return true;
7558}
7559
7560QRhiRenderPassDescriptor *QGles2RenderPassDescriptor::newCompatibleRenderPassDescriptor() const
7561{
7562 QGles2RenderPassDescriptor *rpD = new QGles2RenderPassDescriptor(m_rhi);
7563 QRHI_RES_RHI(QRhiGles2);
7564 rhiD->registerResource(rpD, false);
7565 return rpD;
7566}
7567
7568QVector<quint32> QGles2RenderPassDescriptor::serializedFormat() const
7569{
7570 return {};
7571}
7572
7573QGles2SwapChainRenderTarget::QGles2SwapChainRenderTarget(QRhiImplementation *rhi, QRhiSwapChain *swapchain)
7574 : QRhiSwapChainRenderTarget(rhi, swapchain),
7575 d(rhi)
7576{
7577}
7578
7579QGles2SwapChainRenderTarget::~QGles2SwapChainRenderTarget()
7580{
7581 destroy();
7582}
7583
7584void QGles2SwapChainRenderTarget::destroy()
7585{
7586 // nothing to do here
7587}
7588
7589QSize QGles2SwapChainRenderTarget::pixelSize() const
7590{
7591 return d.pixelSize;
7592}
7593
7594float QGles2SwapChainRenderTarget::devicePixelRatio() const
7595{
7596 return d.dpr;
7597}
7598
7599int QGles2SwapChainRenderTarget::sampleCount() const
7600{
7601 return d.sampleCount;
7602}
7603
7604QGles2TextureRenderTarget::QGles2TextureRenderTarget(QRhiImplementation *rhi,
7605 const QRhiTextureRenderTargetDescription &desc,
7606 Flags flags)
7607 : QRhiTextureRenderTarget(rhi, desc, flags),
7608 d(rhi)
7609{
7610}
7611
7612QGles2TextureRenderTarget::~QGles2TextureRenderTarget()
7613{
7614 destroy();
7615}
7616
7617void QGles2TextureRenderTarget::destroy()
7618{
7619 if (!framebuffer)
7620 return;
7621
7622 QRhiGles2::DeferredReleaseEntry e;
7623 e.type = QRhiGles2::DeferredReleaseEntry::TextureRenderTarget;
7624
7625 e.textureRenderTarget.framebuffer = framebuffer;
7626 e.textureRenderTarget.nonMsaaThrowawayDepthTexture = nonMsaaThrowawayDepthTexture;
7627
7628 framebuffer = 0;
7629 nonMsaaThrowawayDepthTexture = 0;
7630
7631 QRHI_RES_RHI(QRhiGles2);
7632 if (rhiD) {
7633 rhiD->releaseQueue.append(e);
7634 rhiD->unregisterResource(this);
7635 }
7636}
7637
7638QRhiRenderPassDescriptor *QGles2TextureRenderTarget::newCompatibleRenderPassDescriptor()
7639{
7640 QGles2RenderPassDescriptor *rpD = new QGles2RenderPassDescriptor(m_rhi);
7641 QRHI_RES_RHI(QRhiGles2);
7642 rhiD->registerResource(rpD, false);
7643 return rpD;
7644}
7645
7646bool QGles2TextureRenderTarget::create()
7647{
7648 QRHI_RES_RHI(QRhiGles2);
7649
7650 if (framebuffer)
7651 destroy();
7652
7653 const bool hasColorAttachments = m_desc.colorAttachmentCount() > 0;
7654 Q_ASSERT(hasColorAttachments || m_desc.depthTexture());
7655 Q_ASSERT(!m_desc.depthStencilBuffer() || !m_desc.depthTexture());
7656 const bool hasDepthStencil = m_desc.depthStencilBuffer() || m_desc.depthTexture();
7657
7658 if (hasColorAttachments) {
7659 const int count = int(m_desc.colorAttachmentCount());
7660 if (count > rhiD->caps.maxDrawBuffers) {
7661 qWarning("QGles2TextureRenderTarget: Too many color attachments (%d, max is %d)",
7662 count, rhiD->caps.maxDrawBuffers);
7663 }
7664 }
7665 if (m_desc.depthTexture() && !rhiD->caps.depthTexture)
7666 qWarning("QGles2TextureRenderTarget: Depth texture is not supported and will be ignored");
7667
7668 if (!rhiD->ensureContext())
7669 return false;
7670
7671 for (auto it = m_desc.cbeginColorAttachments(), itEnd = m_desc.cendColorAttachments();
7672 it != itEnd; ++it) {
7673 const QRhiColorAttachment &colorAtt(*it);
7674 const QRhiTexture *resolveTexture = colorAtt.resolveTexture();
7675 if (!resolveTexture)
7676 continue;
7677
7678 const QRhiTexture *texture = colorAtt.texture();
7679 const QRhiRenderBuffer *renderBuffer = colorAtt.renderBuffer();
7680 Q_ASSERT(texture || renderBuffer);
7681 const QRhiTexture::Format sourceFormat = texture ? texture->format()
7682 : renderBuffer->backingFormat();
7683 const bool sourceIsSrgb = texture && texture->flags().testFlag(QRhiTexture::sRGB);
7684 const bool resolveIsSrgb = resolveTexture->flags().testFlag(QRhiTexture::sRGB);
7685 if (sourceFormat != resolveTexture->format() || sourceIsSrgb != resolveIsSrgb) {
7686 qWarning("Multisample resolve between different formats "
7687 "(%d, sRGB %d) and (%d, sRGB %d) is not supported.",
7688 int(sourceFormat), int(sourceIsSrgb),
7689 int(resolveTexture->format()), int(resolveIsSrgb));
7690 return false;
7691 }
7692 }
7693
7694 rhiD->f->glGenFramebuffers(1, &framebuffer);
7695 rhiD->f->glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
7696
7697 d.colorAttCount = 0;
7698 d.srgbUpdateAndBlend = false;
7699 int attIndex = 0;
7700 int multiViewCount = 0;
7701 for (auto it = m_desc.cbeginColorAttachments(), itEnd = m_desc.cendColorAttachments(); it != itEnd; ++it, ++attIndex) {
7702 d.colorAttCount += 1;
7703 const QRhiColorAttachment &colorAtt(*it);
7704 QRhiTexture *texture = colorAtt.texture();
7705 QRhiRenderBuffer *renderBuffer = colorAtt.renderBuffer();
7706 Q_ASSERT(texture || renderBuffer);
7707 if (texture) {
7708 QGles2Texture *texD = QRHI_RES(QGles2Texture, texture);
7709 Q_ASSERT(texD->texture && texD->specified);
7710 d.srgbUpdateAndBlend |= texD->flags().testFlag(QRhiTexture::sRGB);
7711 if (colorAtt.resolveTexture())
7712 d.srgbUpdateAndBlend |= colorAtt.resolveTexture()->flags().testFlag(QRhiTexture::sRGB);
7713 if (texD->flags().testFlag(QRhiTexture::ThreeDimensional) || texD->flags().testFlag(QRhiTexture::TextureArray)) {
7714 if (colorAtt.multiViewCount() < 2) {
7715 rhiD->f->glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + uint(attIndex), texD->texture,
7716 colorAtt.level(), colorAtt.layer());
7717 } else {
7718 multiViewCount = colorAtt.multiViewCount();
7719 if (texD->samples > 1 && rhiD->caps.glesMultiviewMultisampleRenderToTexture && colorAtt.resolveTexture()) {
7720 // Special path for GLES and GL_OVR_multiview_multisampled_render_to_texture:
7721 // ignore the color attachment's (multisample) texture
7722 // array and give the resolve texture array to GL. (no
7723 // explicit resolving is needed by us later on)
7724 QGles2Texture *resolveTexD = QRHI_RES(QGles2Texture, colorAtt.resolveTexture());
7725 rhiD->glFramebufferTextureMultisampleMultiviewOVR(GL_FRAMEBUFFER,
7726 GL_COLOR_ATTACHMENT0 + uint(attIndex),
7727 resolveTexD->texture,
7728 colorAtt.resolveLevel(),
7729 texD->samples,
7730 colorAtt.resolveLayer(),
7731 multiViewCount);
7732 } else {
7733 rhiD->glFramebufferTextureMultiviewOVR(GL_FRAMEBUFFER,
7734 GL_COLOR_ATTACHMENT0 + uint(attIndex),
7735 texD->texture,
7736 colorAtt.level(),
7737 colorAtt.layer(),
7738 multiViewCount);
7739 }
7740 }
7741 } else if (texD->flags().testFlag(QRhiTexture::OneDimensional)) {
7742 rhiD->glFramebufferTexture1D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + uint(attIndex),
7743 texD->target + uint(colorAtt.layer()), texD->texture,
7744 colorAtt.level());
7745 } else {
7746 if (texD->samples > 1 && rhiD->caps.glesMultisampleRenderToTexture && colorAtt.resolveTexture()) {
7747 // Special path for GLES and GL_EXT_multisampled_render_to_texture:
7748 // ignore the color attachment's (multisample) texture and
7749 // give the resolve texture to GL. (no explicit resolving is
7750 // needed by us later on)
7751 QGles2Texture *resolveTexD = QRHI_RES(QGles2Texture, colorAtt.resolveTexture());
7752 const GLenum faceTargetBase = resolveTexD->flags().testFlag(QRhiTexture::CubeMap) ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : resolveTexD->target;
7753 rhiD->glFramebufferTexture2DMultisampleEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + uint(attIndex), faceTargetBase + uint(colorAtt.resolveLayer()),
7754 resolveTexD->texture, colorAtt.level(), texD->samples);
7755 } else {
7756 const GLenum faceTargetBase = texD->flags().testFlag(QRhiTexture::CubeMap) ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : texD->target;
7757 rhiD->f->glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + uint(attIndex), faceTargetBase + uint(colorAtt.layer()),
7758 texD->texture, colorAtt.level());
7759 }
7760 }
7761 if (attIndex == 0) {
7762 d.pixelSize = rhiD->q->sizeForMipLevel(colorAtt.level(), texD->pixelSize());
7763 d.sampleCount = texD->samples;
7764 }
7765 } else if (renderBuffer) {
7766 QGles2RenderBuffer *rbD = QRHI_RES(QGles2RenderBuffer, renderBuffer);
7767 if (colorAtt.resolveTexture())
7768 d.srgbUpdateAndBlend |= colorAtt.resolveTexture()->flags().testFlag(QRhiTexture::sRGB);
7769 if (rbD->samples > 1 && rhiD->caps.glesMultisampleRenderToTexture && colorAtt.resolveTexture()) {
7770 // Special path for GLES and GL_EXT_multisampled_render_to_texture: ignore
7771 // the (multisample) renderbuffer and give the resolve texture to GL. (so
7772 // no explicit resolve; depending on GL implementation internals, this may
7773 // play nicer with tiled architectures)
7774 QGles2Texture *resolveTexD = QRHI_RES(QGles2Texture, colorAtt.resolveTexture());
7775 const GLenum faceTargetBase = resolveTexD->flags().testFlag(QRhiTexture::CubeMap) ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : resolveTexD->target;
7776 rhiD->glFramebufferTexture2DMultisampleEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + uint(attIndex), faceTargetBase + uint(colorAtt.resolveLayer()),
7777 resolveTexD->texture, colorAtt.level(), rbD->samples);
7778 } else {
7779 rhiD->f->glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + uint(attIndex), GL_RENDERBUFFER, rbD->renderbuffer);
7780 }
7781 if (attIndex == 0) {
7782 d.pixelSize = rbD->pixelSize();
7783 d.sampleCount = rbD->samples;
7784 }
7785 }
7786 }
7787
7788 if (hasDepthStencil && m_desc.depthResolveTexture()) {
7789 const QRhiTexture::Format dstFormat = m_desc.depthResolveTexture()->format();
7790 QRhiTexture::Format srcFormat = QRhiTexture::UnknownFormat;
7791 if (m_desc.depthStencilBuffer())
7792 srcFormat = QRhiTexture::D24S8;
7793 else if (!rhiD->caps.glesMultisampleRenderToTexture)
7794 srcFormat = m_desc.depthTexture()->format();
7795 // else resolving is automatic
7796 if (srcFormat != QRhiTexture::UnknownFormat && srcFormat != dstFormat) {
7797 qWarning("Multisample depth-stencil source format %d does not match the "
7798 "depthResolveTexture format %d. OpenGL cannot blit between different depth formats; "
7799 "the depth contents will not be resolved.",
7800 int(srcFormat), int(dstFormat));
7801 }
7802 }
7803
7804 if (hasDepthStencil) {
7805 if (m_desc.depthStencilBuffer()) {
7806 QGles2RenderBuffer *depthRbD = QRHI_RES(QGles2RenderBuffer, m_desc.depthStencilBuffer());
7807 if (rhiD->caps.needsDepthStencilCombinedAttach) {
7808 rhiD->f->glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER,
7809 depthRbD->renderbuffer);
7810 } else {
7811 rhiD->f->glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER,
7812 depthRbD->renderbuffer);
7813 if (depthRbD->stencilRenderbuffer) {
7814 rhiD->f->glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER,
7815 depthRbD->stencilRenderbuffer);
7816 } else {
7817 // packed depth-stencil
7818 rhiD->f->glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER,
7819 depthRbD->renderbuffer);
7820 }
7821 }
7822 if (d.colorAttCount == 0) {
7823 d.pixelSize = depthRbD->pixelSize();
7824 d.sampleCount = depthRbD->samples;
7825 }
7826 } else {
7827 QGles2Texture *depthTexD = QRHI_RES(QGles2Texture, m_desc.depthTexture());
7828 if (multiViewCount < 2) {
7829 if (depthTexD->samples > 1 && rhiD->caps.glesMultisampleRenderToTexture && m_desc.depthResolveTexture()) {
7830 // Special path for GLES and
7831 // GL_EXT_multisampled_render_to_texture, for depth-stencil.
7832 // Relevant only when depthResolveTexture is set.
7833 QGles2Texture *depthResolveTexD = QRHI_RES(QGles2Texture, m_desc.depthResolveTexture());
7834 rhiD->glFramebufferTexture2DMultisampleEXT(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthResolveTexD->target,
7835 depthResolveTexD->texture, 0, depthTexD->samples);
7836 if (rhiD->isStencilSupportingFormat(depthResolveTexD->format())) {
7837 rhiD->glFramebufferTexture2DMultisampleEXT(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, depthResolveTexD->target,
7838 depthResolveTexD->texture, 0, depthTexD->samples);
7839 }
7840 } else if (rhiD->caps.ctxMajor >= 3 && depthTexD->flags().testFlag(QRhiTexture::TextureArray) && m_desc.depthLayer() >= 0) {
7841 rhiD->f->glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthTexD->texture,
7842 /*level*/0, m_desc.depthLayer());
7843 if (rhiD->isStencilSupportingFormat(depthTexD->format())) {
7844 rhiD->f->glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, depthTexD->texture,
7845 /*level*/0, m_desc.depthLayer());
7846 }
7847 } else {
7848 rhiD->f->glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthTexD->target,
7849 depthTexD->texture, 0);
7850 if (rhiD->isStencilSupportingFormat(depthTexD->format())) {
7851 rhiD->f->glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, depthTexD->target,
7852 depthTexD->texture, 0);
7853 }
7854 }
7855 } else {
7856 if (depthTexD->samples > 1 && rhiD->caps.glesMultiviewMultisampleRenderToTexture) {
7857 // And so it turns out
7858 // https://registry.khronos.org/OpenGL/extensions/OVR/OVR_multiview.txt
7859 // does not work with multisample 2D texture arrays. (at least
7860 // that's what Issue 30 in the extension spec seems to imply)
7861 //
7862 // There is https://registry.khronos.org/OpenGL/extensions/EXT/EXT_multiview_texture_multisample.txt
7863 // that seems to resolve that, but that does not seem to
7864 // work (or not available) on GLES devices such as the Quest 3.
7865 //
7866 // So instead, on GLES we can use the
7867 // multisample-multiview-auto-resolving version (which in
7868 // turn is not supported on desktop GL e.g. by NVIDIA), too
7869 // bad we have a multisample depth texture array here as
7870 // every other API out there requires that. So, in absence
7871 // of a depthResolveTexture, create a temporary one ignoring
7872 // what the user has already created.
7873 //
7874 if (!m_flags.testFlag(DoNotStoreDepthStencilContents) && !m_desc.depthResolveTexture()) {
7875 qWarning("Attempted to create a multiview+multisample QRhiTextureRenderTarget, but DoNotStoreDepthStencilContents was not set."
7876 " This path has no choice but to behave as if DoNotStoreDepthStencilContents was set, because QRhi is forced to create"
7877 " a throwaway non-multisample depth texture here. Set the flag to silence this warning, or set a depthResolveTexture.");
7878 }
7879 if (m_desc.depthResolveTexture()) {
7880 QGles2Texture *depthResolveTexD = QRHI_RES(QGles2Texture, m_desc.depthResolveTexture());
7881 rhiD->glFramebufferTextureMultisampleMultiviewOVR(GL_FRAMEBUFFER,
7882 GL_DEPTH_ATTACHMENT,
7883 depthResolveTexD->texture,
7884 0,
7885 depthTexD->samples,
7886 0,
7887 multiViewCount);
7888 if (rhiD->isStencilSupportingFormat(depthResolveTexD->format())) {
7889 rhiD->glFramebufferTextureMultisampleMultiviewOVR(GL_FRAMEBUFFER,
7890 GL_STENCIL_ATTACHMENT,
7891 depthResolveTexD->texture,
7892 0,
7893 depthTexD->samples,
7894 0,
7895 multiViewCount);
7896 }
7897 } else {
7898 if (!nonMsaaThrowawayDepthTexture) {
7899 rhiD->f->glGenTextures(1, &nonMsaaThrowawayDepthTexture);
7900 rhiD->f->glBindTexture(GL_TEXTURE_2D_ARRAY, nonMsaaThrowawayDepthTexture);
7901 rhiD->f->glTexStorage3D(GL_TEXTURE_2D_ARRAY, 1, GL_DEPTH24_STENCIL8,
7902 depthTexD->pixelSize().width(), depthTexD->pixelSize().height(), multiViewCount);
7903 }
7904 rhiD->glFramebufferTextureMultisampleMultiviewOVR(GL_FRAMEBUFFER,
7905 GL_DEPTH_ATTACHMENT,
7906 nonMsaaThrowawayDepthTexture,
7907 0,
7908 depthTexD->samples,
7909 0,
7910 multiViewCount);
7911 rhiD->glFramebufferTextureMultisampleMultiviewOVR(GL_FRAMEBUFFER,
7912 GL_STENCIL_ATTACHMENT,
7913 nonMsaaThrowawayDepthTexture,
7914 0,
7915 depthTexD->samples,
7916 0,
7917 multiViewCount);
7918 }
7919 } else {
7920 // The depth texture here must be an array with at least
7921 // multiViewCount elements, and the format should be D24 or D32F
7922 // for depth only, or D24S8 for depth and stencil.
7923 rhiD->glFramebufferTextureMultiviewOVR(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthTexD->texture,
7924 0, 0, multiViewCount);
7925 if (rhiD->isStencilSupportingFormat(depthTexD->format())) {
7926 rhiD->glFramebufferTextureMultiviewOVR(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, depthTexD->texture,
7927 0, 0, multiViewCount);
7928 }
7929 }
7930 }
7931 if (d.colorAttCount == 0) {
7932 d.pixelSize = depthTexD->pixelSize();
7933 d.sampleCount = depthTexD->samples;
7934 }
7935 }
7936 d.dsAttCount = 1;
7937 } else {
7938 d.dsAttCount = 0;
7939 }
7940
7941 d.dpr = 1;
7942 d.rp = QRHI_RES(QGles2RenderPassDescriptor, m_renderPassDesc);
7943
7944 GLenum status = rhiD->f->glCheckFramebufferStatus(GL_FRAMEBUFFER);
7945 if (status != GL_NO_ERROR && status != GL_FRAMEBUFFER_COMPLETE) {
7946 qWarning("Framebuffer incomplete: 0x%x", status);
7947 return false;
7948 }
7949
7950 if (rhiD->glObjectLabel)
7951 rhiD->glObjectLabel(GL_FRAMEBUFFER, framebuffer, -1, m_objectName.constData());
7952
7953 QRhiRenderTargetAttachmentTracker::updateResIdList<QGles2Texture, QGles2RenderBuffer>(m_desc, &d.currentResIdList);
7954
7955 rhiD->registerResource(this);
7956 return true;
7957}
7958
7959QSize QGles2TextureRenderTarget::pixelSize() const
7960{
7961 if (!QRhiRenderTargetAttachmentTracker::isUpToDate<QGles2Texture, QGles2RenderBuffer>(m_desc, d.currentResIdList))
7962 const_cast<QGles2TextureRenderTarget *>(this)->create();
7963
7964 return d.pixelSize;
7965}
7966
7967float QGles2TextureRenderTarget::devicePixelRatio() const
7968{
7969 return d.dpr;
7970}
7971
7972int QGles2TextureRenderTarget::sampleCount() const
7973{
7974 return d.sampleCount;
7975}
7976
7977QGles2ShaderResourceBindings::QGles2ShaderResourceBindings(QRhiImplementation *rhi)
7978 : QRhiShaderResourceBindings(rhi)
7979{
7980}
7981
7982QGles2ShaderResourceBindings::~QGles2ShaderResourceBindings()
7983{
7984 destroy();
7985}
7986
7987void QGles2ShaderResourceBindings::destroy()
7988{
7989 QRHI_RES_RHI(QRhiGles2);
7990 if (rhiD)
7991 rhiD->unregisterResource(this);
7992}
7993
7994bool QGles2ShaderResourceBindings::create()
7995{
7996 QRHI_RES_RHI(QRhiGles2);
7997 if (!rhiD->sanityCheckShaderResourceBindings(this))
7998 return false;
7999
8000 hasDynamicOffset = false;
8001 hasStorageBinding = false;
8002 storageBindingsFragmentOnly = true;
8003 for (int i = 0, ie = m_bindings.size(); i != ie; ++i) {
8004 const QRhiShaderResourceBinding::Data *b = QRhiImplementation::shaderResourceBindingData(m_bindings.at(i));
8005 switch (b->type()) {
8006 case QRhiShaderResourceBinding::UniformBuffer:
8007 if (b->ubuf().hasDynamicOffset)
8008 hasDynamicOffset = true;
8009 break;
8010 case QRhiShaderResourceBinding::ImageLoad:
8011 case QRhiShaderResourceBinding::ImageStore:
8012 case QRhiShaderResourceBinding::ImageLoadStore:
8013 case QRhiShaderResourceBinding::BufferLoad:
8014 case QRhiShaderResourceBinding::BufferStore:
8015 case QRhiShaderResourceBinding::BufferLoadStore:
8016 hasStorageBinding = true;
8017 if (b->stage != QRhiShaderResourceBinding::FragmentStage)
8018 storageBindingsFragmentOnly = false;
8019 break;
8020 default:
8021 break;
8022 }
8023 }
8024
8025 rhiD->updateLayoutDesc(this);
8026
8027 generation += 1;
8028 rhiD->registerResource(this, false);
8029 return true;
8030}
8031
8032void QGles2ShaderResourceBindings::updateResources(UpdateFlags flags)
8033{
8034 Q_UNUSED(flags);
8035 generation += 1;
8036}
8037
8038QGles2GraphicsPipeline::QGles2GraphicsPipeline(QRhiImplementation *rhi)
8039 : QRhiGraphicsPipeline(rhi)
8040{
8041}
8042
8043QGles2GraphicsPipeline::~QGles2GraphicsPipeline()
8044{
8045 destroy();
8046}
8047
8048void QGles2GraphicsPipeline::destroy()
8049{
8050 if (!program)
8051 return;
8052
8053 QRhiGles2::DeferredReleaseEntry e;
8054 e.type = QRhiGles2::DeferredReleaseEntry::Pipeline;
8055
8056 e.pipeline.program = program;
8057
8058 program = 0;
8059 uniforms.clear();
8060 pushConstantUniforms.clear();
8061 pushConstantSize = 0;
8062 samplers.clear();
8063 uniformState.clear();
8064
8065 QRHI_RES_RHI(QRhiGles2);
8066 if (rhiD) {
8067 rhiD->releaseQueue.append(e);
8068 rhiD->unregisterResource(this);
8069 }
8070}
8071
8072bool QGles2GraphicsPipeline::create()
8073{
8074 QRHI_RES_RHI(QRhiGles2);
8075
8076 if (program)
8077 destroy();
8078
8079 if (!rhiD->ensureContext())
8080 return false;
8081
8082 rhiD->pipelineCreationStart();
8083 if (!rhiD->sanityCheckGraphicsPipeline(this))
8084 return false;
8085
8086 drawMode = toGlTopology(m_topology);
8087
8088 program = rhiD->f->glCreateProgram();
8089
8090 enum {
8091 VtxIdx = 0,
8092 TCIdx,
8093 TEIdx,
8094 GeomIdx,
8095 FragIdx,
8096 LastIdx
8097 };
8098 const auto descIdxForStage = [](const QRhiShaderStage &shaderStage) {
8099 switch (shaderStage.type()) {
8100 case QRhiShaderStage::Vertex:
8101 return VtxIdx;
8102 case QRhiShaderStage::TessellationControl:
8103 return TCIdx;
8104 case QRhiShaderStage::TessellationEvaluation:
8105 return TEIdx;
8106 case QRhiShaderStage::Geometry:
8107 return GeomIdx;
8108 case QRhiShaderStage::Fragment:
8109 return FragIdx;
8110 default:
8111 break;
8112 }
8113 Q_UNREACHABLE_RETURN(VtxIdx);
8114 };
8115 const std::optional<QShaderVersion> commonVersion =
8116 rhiD->commonGlslEsVersion(m_shaderStages.constData(), m_shaderStages.size());
8117
8118 QShaderDescription desc[LastIdx];
8119 QShader::SeparateToCombinedImageSamplerMappingList samplerMappingList[LastIdx];
8120 bool vertexFragmentOnly = true;
8121 for (const QRhiShaderStage &shaderStage : std::as_const(m_shaderStages)) {
8122 if (isGraphicsStage(shaderStage)) {
8123 const int idx = descIdxForStage(shaderStage);
8124 if (idx != VtxIdx && idx != FragIdx)
8125 vertexFragmentOnly = false;
8126 QShader shader = shaderStage.shader();
8127 QShaderVersion shaderVersion;
8128 desc[idx] = shader.description();
8129 if (!rhiD->shaderSource(shaderStage, &shaderVersion, commonVersion).isEmpty()) {
8130 samplerMappingList[idx] = shader.separateToCombinedImageSamplerMappingList(
8131 { QShader::GlslShader, shaderVersion, shaderStage.shaderVariant() });
8132 }
8133 }
8134 }
8135
8136 QByteArray cacheKey;
8137 QRhiGles2::ProgramCacheResult cacheResult = rhiD->tryLoadFromDiskOrPipelineCache(m_shaderStages.constData(),
8138 m_shaderStages.size(),
8139 program,
8140 desc[VtxIdx].inputVariables(),
8141 &cacheKey,
8142 commonVersion);
8143 if (cacheResult == QRhiGles2::ProgramCacheError)
8144 return false;
8145
8146 if (cacheResult == QRhiGles2::ProgramCacheMiss) {
8147 if (rhiD->caps.gles && !commonVersion) {
8148 qWarning("The shader stages of this pipeline have no GLSL ES version in common; "
8149 "linking the program will fail");
8150 }
8151 for (const QRhiShaderStage &shaderStage : std::as_const(m_shaderStages)) {
8152 if (isGraphicsStage(shaderStage)) {
8153 if (!rhiD->compileShader(program, shaderStage, nullptr, commonVersion))
8154 return false;
8155 }
8156 }
8157
8158 // important when GLSL <= 150 is used that does not have location qualifiers
8159 const auto vtxInputVars = desc[VtxIdx].inputVariables();
8160 for (const QShaderDescription::InOutVariable &inVar : vtxInputVars)
8161 rhiD->f->glBindAttribLocation(program, GLuint(inVar.location), inVar.name);
8162
8163 if (vertexFragmentOnly)
8164 rhiD->sanityCheckVertexFragmentInterface(desc[VtxIdx], desc[FragIdx]);
8165
8166 if (!rhiD->linkProgram(program))
8167 return false;
8168
8169 if (rhiD->rhiFlags.testFlag(QRhi::EnablePipelineCacheDataSave)) {
8170 // force replacing existing cache entry (if there is one, then
8171 // something is wrong with it, as there was no hit)
8172 rhiD->trySaveToPipelineCache(program, cacheKey, true);
8173 } else {
8174 // legacy QOpenGLShaderProgram style behavior: the "pipeline cache"
8175 // was not enabled, so instead store to the Qt 5 disk cache
8176 rhiD->trySaveToDiskCache(program, cacheKey);
8177 }
8178 } else {
8179 Q_ASSERT(cacheResult == QRhiGles2::ProgramCacheHit);
8180 if (rhiD->rhiFlags.testFlag(QRhi::EnablePipelineCacheDataSave)) {
8181 // just so that it ends up in the pipeline cache also when the hit was
8182 // from the disk cache
8183 rhiD->trySaveToPipelineCache(program, cacheKey);
8184 }
8185 }
8186
8187 // Use the same work area for the vertex & fragment stages, thus ensuring
8188 // that we will not do superfluous glUniform calls for uniforms that are
8189 // present in both shaders.
8190 QRhiGles2::ActiveUniformLocationTracker activeUniformLocations;
8191
8192 for (const QRhiShaderStage &shaderStage : std::as_const(m_shaderStages)) {
8193 if (isGraphicsStage(shaderStage)) {
8194 const int idx = descIdxForStage(shaderStage);
8195 const auto uniformBlocks = desc[idx].uniformBlocks();
8196 for (const QShaderDescription::UniformBlock &ub : uniformBlocks)
8197 rhiD->gatherUniforms(program, ub, &activeUniformLocations, &uniforms);
8198 const auto pushConstantBlocks = desc[idx].pushConstantBlocks();
8199 for (const QShaderDescription::PushConstantBlock &pcb : pushConstantBlocks) {
8200 rhiD->gatherPushConstantUniforms(program, pcb, &activeUniformLocations, &pushConstantUniforms);
8201 pushConstantSize = qMax(pushConstantSize, quint32(pcb.size));
8202 }
8203 const auto combinedImageSamplers = desc[idx].combinedImageSamplers();
8204 for (const QShaderDescription::InOutVariable &v : combinedImageSamplers)
8205 rhiD->gatherSamplers(program, v, &samplers);
8206 for (const QShader::SeparateToCombinedImageSamplerMapping &mapping : std::as_const(samplerMappingList[idx]))
8207 rhiD->gatherGeneratedSamplers(program, mapping, &samplers);
8208 }
8209 }
8210
8211 std::sort(uniforms.begin(), uniforms.end(),
8212 [](const QGles2UniformDescription &a, const QGles2UniformDescription &b)
8213 {
8214 return a.offset < b.offset;
8215 });
8216
8217 QRhiGles2::setupUniformStateTracking(&uniforms, &pushConstantUniforms, &uniformState);
8218
8219 currentSrb = nullptr;
8220 currentSrbGeneration = 0;
8221
8222 if (rhiD->glObjectLabel)
8223 rhiD->glObjectLabel(GL_PROGRAM, program, -1, m_objectName.constData());
8224
8225 rhiD->pipelineCreationEnd();
8226 generation += 1;
8227 rhiD->registerResource(this);
8228 return true;
8229}
8230
8231QGles2ComputePipeline::QGles2ComputePipeline(QRhiImplementation *rhi)
8232 : QRhiComputePipeline(rhi)
8233{
8234}
8235
8236QGles2ComputePipeline::~QGles2ComputePipeline()
8237{
8238 destroy();
8239}
8240
8241void QGles2ComputePipeline::destroy()
8242{
8243 if (!program)
8244 return;
8245
8246 QRhiGles2::DeferredReleaseEntry e;
8247 e.type = QRhiGles2::DeferredReleaseEntry::Pipeline;
8248
8249 e.pipeline.program = program;
8250
8251 program = 0;
8252 uniforms.clear();
8253 pushConstantUniforms.clear();
8254 pushConstantSize = 0;
8255 samplers.clear();
8256 uniformState.clear();
8257
8258 QRHI_RES_RHI(QRhiGles2);
8259 if (rhiD) {
8260 rhiD->releaseQueue.append(e);
8261 rhiD->unregisterResource(this);
8262 }
8263}
8264
8265bool QGles2ComputePipeline::create()
8266{
8267 QRHI_RES_RHI(QRhiGles2);
8268
8269 if (program)
8270 destroy();
8271
8272 if (!rhiD->ensureContext())
8273 return false;
8274
8275 rhiD->pipelineCreationStart();
8276
8277 const QShaderDescription csDesc = m_shaderStage.shader().description();
8278 QShader::SeparateToCombinedImageSamplerMappingList csSamplerMappingList;
8279 QShaderVersion shaderVersion;
8280 if (!rhiD->shaderSource(m_shaderStage, &shaderVersion).isEmpty()) {
8281 csSamplerMappingList = m_shaderStage.shader().separateToCombinedImageSamplerMappingList(
8282 { QShader::GlslShader, shaderVersion, m_shaderStage.shaderVariant() });
8283 }
8284
8285 program = rhiD->f->glCreateProgram();
8286
8287 QByteArray cacheKey;
8288 QRhiGles2::ProgramCacheResult cacheResult = rhiD->tryLoadFromDiskOrPipelineCache(&m_shaderStage, 1, program, {}, &cacheKey);
8289 if (cacheResult == QRhiGles2::ProgramCacheError)
8290 return false;
8291
8292 if (cacheResult == QRhiGles2::ProgramCacheMiss) {
8293 if (!rhiD->compileShader(program, m_shaderStage, nullptr))
8294 return false;
8295
8296 if (!rhiD->linkProgram(program))
8297 return false;
8298
8299 if (rhiD->rhiFlags.testFlag(QRhi::EnablePipelineCacheDataSave)) {
8300 // force replacing existing cache entry (if there is one, then
8301 // something is wrong with it, as there was no hit)
8302 rhiD->trySaveToPipelineCache(program, cacheKey, true);
8303 } else {
8304 // legacy QOpenGLShaderProgram style behavior: the "pipeline cache"
8305 // was not enabled, so instead store to the Qt 5 disk cache
8306 rhiD->trySaveToDiskCache(program, cacheKey);
8307 }
8308 } else {
8309 Q_ASSERT(cacheResult == QRhiGles2::ProgramCacheHit);
8310 if (rhiD->rhiFlags.testFlag(QRhi::EnablePipelineCacheDataSave)) {
8311 // just so that it ends up in the pipeline cache also when the hit was
8312 // from the disk cache
8313 rhiD->trySaveToPipelineCache(program, cacheKey);
8314 }
8315 }
8316
8317 QRhiGles2::ActiveUniformLocationTracker activeUniformLocations;
8318 const auto csUniformBlocks = csDesc.uniformBlocks();
8319 for (const QShaderDescription::UniformBlock &ub : csUniformBlocks)
8320 rhiD->gatherUniforms(program, ub, &activeUniformLocations, &uniforms);
8321 const auto csPushConstantBlocks = csDesc.pushConstantBlocks();
8322 for (const QShaderDescription::PushConstantBlock &pcb : csPushConstantBlocks) {
8323 rhiD->gatherPushConstantUniforms(program, pcb, &activeUniformLocations, &pushConstantUniforms);
8324 pushConstantSize = qMax(pushConstantSize, quint32(pcb.size));
8325 }
8326 const auto csCombinedImageSamplers = csDesc.combinedImageSamplers();
8327 for (const QShaderDescription::InOutVariable &v : csCombinedImageSamplers)
8328 rhiD->gatherSamplers(program, v, &samplers);
8329 for (const QShader::SeparateToCombinedImageSamplerMapping &mapping : std::as_const(csSamplerMappingList))
8330 rhiD->gatherGeneratedSamplers(program, mapping, &samplers);
8331
8332 // storage images and buffers need no special steps here
8333
8334 QRhiGles2::setupUniformStateTracking(&uniforms, &pushConstantUniforms, &uniformState);
8335
8336 currentSrb = nullptr;
8337 currentSrbGeneration = 0;
8338
8339 rhiD->pipelineCreationEnd();
8340 generation += 1;
8341 rhiD->registerResource(this);
8342 return true;
8343}
8344
8345QGles2CommandBuffer::QGles2CommandBuffer(QRhiImplementation *rhi)
8346 : QRhiCommandBuffer(rhi)
8347{
8348 resetState();
8349}
8350
8351QGles2CommandBuffer::~QGles2CommandBuffer()
8352{
8353 destroy();
8354}
8355
8356void QGles2CommandBuffer::destroy()
8357{
8358 // nothing to do here
8359}
8360
8361QGles2SwapChain::QGles2SwapChain(QRhiImplementation *rhi)
8362 : QRhiSwapChain(rhi),
8363 rt(rhi, this),
8364 rtLeft(rhi, this),
8365 rtRight(rhi, this),
8366 cb(rhi)
8367{
8368}
8369
8370QGles2SwapChain::~QGles2SwapChain()
8371{
8372 destroy();
8373}
8374
8375void QGles2SwapChain::destroy()
8376{
8377 QRHI_RES_RHI(QRhiGles2);
8378 if (rhiD) {
8379 // Don't leave the window surface bound, the platform may destroy it next.
8380 if (surface && currentSurfaceForCurrentContext(rhiD->ctx) == surface)
8381 rhiD->ctx->doneCurrent();
8382 rhiD->unregisterResource(this);
8383 }
8384}
8385
8386QRhiCommandBuffer *QGles2SwapChain::currentFrameCommandBuffer()
8387{
8388 return &cb;
8389}
8390
8391QRhiRenderTarget *QGles2SwapChain::currentFrameRenderTarget()
8392{
8393 return &rt;
8394}
8395
8396QRhiRenderTarget *QGles2SwapChain::currentFrameRenderTarget(StereoTargetBuffer targetBuffer)
8397{
8398 if (targetBuffer == LeftBuffer)
8399 return rtLeft.d.isValid() ? &rtLeft : &rt;
8400 else if (targetBuffer == RightBuffer)
8401 return rtRight.d.isValid() ? &rtRight : &rt;
8402 else
8403 Q_UNREACHABLE_RETURN(nullptr);
8404}
8405
8406QSize QGles2SwapChain::surfacePixelSize()
8407{
8408 Q_ASSERT(m_window);
8409 if (QPlatformWindow *platformWindow = m_window->handle())
8410 // Prefer using QPlatformWindow geometry and DPR in order to avoid
8411 // errors due to rounded QWindow geometry.
8412 return platformWindow->geometry().size() * platformWindow->devicePixelRatio();
8413 else
8414 return m_window->size() * m_window->devicePixelRatio();
8415}
8416
8417bool QGles2SwapChain::isFormatSupported(Format f)
8418{
8419 return f == SDR;
8420}
8421
8422QRhiRenderPassDescriptor *QGles2SwapChain::newCompatibleRenderPassDescriptor()
8423{
8424 QGles2RenderPassDescriptor *rpD = new QGles2RenderPassDescriptor(m_rhi);
8425 QRHI_RES_RHI(QRhiGles2);
8426 rhiD->registerResource(rpD, false);
8427 return rpD;
8428}
8429
8430void QGles2SwapChain::initSwapChainRenderTarget(QGles2SwapChainRenderTarget *rt)
8431{
8432 rt->setRenderPassDescriptor(m_renderPassDesc); // for the public getter in QRhiRenderTarget
8433 rt->d.rp = QRHI_RES(QGles2RenderPassDescriptor, m_renderPassDesc);
8434 rt->d.pixelSize = pixelSize;
8435 rt->d.dpr = float(m_window->devicePixelRatio());
8436 rt->d.sampleCount = qBound(1, m_sampleCount, 64);
8437 rt->d.colorAttCount = 1;
8438 rt->d.dsAttCount = m_depthStencil ? 1 : 0;
8439 rt->d.srgbUpdateAndBlend = m_flags.testFlag(QRhiSwapChain::sRGB);
8440}
8441
8442bool QGles2SwapChain::createOrResize()
8443{
8444 // can be called multiple times due to window resizes
8445 if (surface && surface != m_window)
8446 destroy();
8447
8448 surface = m_window;
8449 m_currentPixelSize = surfacePixelSize();
8450 pixelSize = m_currentPixelSize;
8451
8452 if (m_depthStencil && m_depthStencil->flags().testFlag(QRhiRenderBuffer::UsedWithSwapChainOnly)
8453 && m_depthStencil->pixelSize() != pixelSize)
8454 {
8455 m_depthStencil->setPixelSize(pixelSize);
8456 m_depthStencil->create();
8457 }
8458
8459 initSwapChainRenderTarget(&rt);
8460
8461 if (m_window->format().stereo()) {
8462 initSwapChainRenderTarget(&rtLeft);
8463 rtLeft.d.stereoTarget = QRhiSwapChain::LeftBuffer;
8464 initSwapChainRenderTarget(&rtRight);
8465 rtRight.d.stereoTarget = QRhiSwapChain::RightBuffer;
8466 }
8467
8468 QRHI_RES_RHI(QRhiGles2);
8469 if (rhiD->rhiFlags.testFlag(QRhi::EnableTimestamps) && rhiD->caps.timestamps)
8470 timestamps.prepare(rhiD);
8471
8472 // The only reason to register this fairly fake gl swapchain
8473 // object with no native resources underneath is to be able to
8474 // implement a safe destroy().
8475 rhiD->registerResource(this, false);
8476
8477 return true;
8478}
8479
8480void QGles2SwapChainTimestamps::prepare(QRhiGles2 *rhiD)
8481{
8482 if (!query[0])
8483 rhiD->f->glGenQueries(TIMESTAMP_PAIRS * 2, query);
8484}
8485
8486void QGles2SwapChainTimestamps::destroy(QRhiGles2 *rhiD)
8487{
8488 rhiD->f->glDeleteQueries(TIMESTAMP_PAIRS * 2, query);
8489 memset(active, 0, sizeof(active));
8490 memset(query, 0, sizeof(query));
8491}
8492
8493bool QGles2SwapChainTimestamps::tryQueryTimestamps(int pairIndex, QRhiGles2 *rhiD, double *elapsedSec)
8494{
8495 if (!active[pairIndex])
8496 return false;
8497
8498 GLuint tsStart = query[pairIndex * 2];
8499 GLuint tsEnd = query[pairIndex * 2 + 1];
8500
8501 GLuint ready = GL_FALSE;
8502 rhiD->f->glGetQueryObjectuiv(tsEnd, GL_QUERY_RESULT_AVAILABLE, &ready);
8503
8504 if (!ready)
8505 return false;
8506
8507 bool result = false;
8508 quint64 timestamps[2];
8509 rhiD->glGetQueryObjectui64v(tsStart, GL_QUERY_RESULT, &timestamps[0]);
8510 rhiD->glGetQueryObjectui64v(tsEnd, GL_QUERY_RESULT, &timestamps[1]);
8511
8512 if (timestamps[1] >= timestamps[0]) {
8513 const quint64 nanoseconds = timestamps[1] - timestamps[0];
8514 *elapsedSec = nanoseconds / 1000000000.0;
8515 result = true;
8516 }
8517
8518 active[pairIndex] = false;
8519 return result;
8520}
8521
8522QT_END_NAMESPACE
const GLvoid const GLvoid GLenum
QRhiStats statistics() override
void releaseBufferNameCache()
bool contextLost
const QRhiNativeHandles * nativeHandles(QRhiCommandBuffer *cb) override
void drawIndexed(QRhiCommandBuffer *cb, quint32 indexCount, quint32 instanceCount, quint32 firstIndex, qint32 vertexOffset, quint32 firstInstance) override
void trackedBufferBarrier(QGles2CommandBuffer *cbD, QGles2Buffer *bufD, QGles2Buffer::Access access)
void gatherBlockMemberUniforms(GLuint program, const QByteArray &prefix, int binding, const QList< QShaderDescription::BlockVariable > &members, ActiveUniformLocationTracker *activeUniformLocations, QGles2UniformDescriptionVector *dst)
QRhi::FrameOpResult beginFrame(QRhiSwapChain *swapChain, QRhi::BeginFrameFlags flags) override
const GLvoid GLenum
std::optional< QShaderVersion > commonGlslEsVersion(const QRhiShaderStage *stages, int stageCount) const
void enqueueBarriersForPass(QGles2CommandBuffer *cbD)
void drawIndirectCount(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset, QRhiBuffer *countBuffer, quint32 countBufferOffset, quint32 maxDrawCount, quint32 stride) override
int resourceLimit(QRhi::ResourceLimit limit) const override
void setVertexInput(QRhiCommandBuffer *cb, int startBinding, int bindingCount, const QRhiCommandBuffer::VertexInput *bindings, QRhiBuffer *indexBuf, quint32 indexOffset, QRhiCommandBuffer::IndexFormat indexFormat) override
void(QOPENGLF_APIENTRYP glRenderbufferStorageMultisampleEXT)(GLenum
bool isFeatureSupported(QRhi::Feature feature) const override
QRhiGraphicsPipeline * createGraphicsPipeline() override
void bindShaderResources(QGles2CommandBuffer *cbD, QRhiGraphicsPipeline *maybeGraphicsPs, QRhiComputePipeline *maybeComputePs, QRhiShaderResourceBindings *srb, const uint *dynOfsPairs, int dynOfsCount)
bool create(QRhi::Flags flags) override
void trackedRegisterTexture(QRhiPassResourceTracker *passResTracker, QGles2Texture *texD, QRhiPassResourceTracker::TextureAccess access, QRhiPassResourceTracker::TextureStage stage)
void executeBindGraphicsPipeline(QGles2CommandBuffer *cbD, QGles2GraphicsPipeline *psD)
void dispatchIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset) override
int bufferNameCacheCount
QRhiDriverInfo driverInfo() const override
GLuint ensureClearBufferProgram()
void(QOPENGLF_APIENTRYP glFramebufferTextureMultisampleMultiviewOVR)(GLenum
bool needsMakeCurrentDueToSwap
QRhiShadingRateMap * createShadingRateMap() override
const void quint64 GLuint
void setUniformsFromBlock(const QGles2UniformDescriptionVector &uniforms, int binding, const char *blockData, qint64 blockSize, quint32 blockOffset, QGles2UniformState *uniformState)
void trackedImageBarrier(QGles2CommandBuffer *cbD, QGles2Texture *texD, QGles2Texture::Access access)
QOpenGLExtensions * f
void trackedRegisterBuffer(QRhiPassResourceTracker *passResTracker, QGles2Buffer *bufD, QRhiPassResourceTracker::BufferAccess access, QRhiPassResourceTracker::BufferStage stage)
void setShadingRate(QRhiCommandBuffer *cb, const QSize &coarsePixelSize) override
QRhiComputePipeline * createComputePipeline() override
QSurface * evaluateFallbackSurface() const
void resourceUpdate(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates) override
QMatrix4x4 clipSpaceCorrMatrix() const override
QRhi::FrameOpResult finish() override
void setComputePipeline(QRhiCommandBuffer *cb, QRhiComputePipeline *ps) override
const void * void(QOPENGLF_APIENTRYP glGetQueryObjectui64v)(GLuint
void(QOPENGLF_APIENTRYP glMultiDrawArraysIndirect)(GLenum
QList< int > supportedSampleCounts() const override
void(QOPENGLF_APIENTRYP glMultiDrawElementsIndirectCount)(GLenum
QRhiSwapChain * createSwapChain() override
GLuint genBuffer()
void dispatch(QRhiCommandBuffer *cb, int x, int y, int z) override
void destroy() override
void executeCommandBuffer(QRhiCommandBuffer *cb)
void setGraphicsPipeline(QRhiCommandBuffer *cb, QRhiGraphicsPipeline *ps) override
QList< QShaderVersion > glslVersionsToTry() const
QRhiGles2(QRhiGles2InitParams *params, QRhiGles2NativeHandles *importDevice=nullptr)
GLbitfield barriersForNextDispatch(QGles2CommandBuffer *cbD)
QList< QSize > supportedShadingRates(int sampleCount) const override
void drawIndexedIndirectCount(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset, QRhiBuffer *countBuffer, quint32 countBufferOffset, quint32 maxDrawCount, quint32 stride) override
void(QOPENGLF_APIENTRYP glTexSubImage1D)(GLenum
const void GLuint
QRhiTexture * createTexture(QRhiTexture::Format format, const QSize &pixelSize, int depth, int arraySize, int sampleCount, QRhiTexture::Flags flags) override
void bindCombinedSampler(QGles2CommandBuffer *cbD, QGles2Texture *texD, QGles2Sampler *samplerD, void *ps, uint psGeneration, int glslLocation, int *texUnit, bool *activeTexUnitAltered)
void setViewport(QRhiCommandBuffer *cb, const QRhiViewport &viewport) override
QRhiTextureRenderTarget * createTextureRenderTarget(const QRhiTextureRenderTargetDescription &desc, QRhiTextureRenderTarget::Flags flags) override
QByteArray shaderSource(const QRhiShaderStage &shaderStage, QShaderVersion *shaderVersion, std::optional< QShaderVersion > commonVersion=std::nullopt)
void(QOPENGLF_APIENTRYP glMultiDrawElementsIndirect)(GLenum
QRhiSampler * createSampler(QRhiSampler::Filter magFilter, QRhiSampler::Filter minFilter, QRhiSampler::Filter mipmapMode, QRhiSampler::AddressMode u, QRhiSampler::AddressMode v, QRhiSampler::AddressMode w) override
void beginPass(QRhiCommandBuffer *cb, QRhiRenderTarget *rt, const QColor &colorClearValue, const QRhiDepthStencilClearValue &depthStencilClearValue, QRhiResourceUpdateBatch *resourceUpdates, QRhiCommandBuffer::BeginPassFlags flags) override
QGles2SwapChain * currentSwapChain
bool isDeviceLost() const override
QRhiShaderResourceBindings * createShaderResourceBindings() override
void drawIndexedIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset, quint32 drawCount, quint32 stride) override
void drawIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset, quint32 drawCount, quint32 stride) override
bool isYUpInNDC() const override
void debugMarkBegin(QRhiCommandBuffer *cb, const QByteArray &name) override
void enqueueResourceUpdates(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
bool makeThreadLocalNativeContextCurrent() override
int ubufAlignment() const override
void beginExternal(QRhiCommandBuffer *cb) override
const GLvoid GLint
void endExternal(QRhiCommandBuffer *cb) override
bool isTextureFormatSupported(QRhiTexture::Format format, QRhiTexture::Flags flags) const override
void(QOPENGLF_APIENTRYP glCompressedTexImage1D)(GLenum
bool importedContext
void(QOPENGLF_APIENTRYP glDrawElementsInstancedBaseVertexBaseInstance)(GLenum
void setScissor(QRhiCommandBuffer *cb, const QRhiScissor &scissor) override
void setUniformValue(const QGles2UniformDescription &uniform, const void *src, QGles2UniformState *uniformState)
void setStencilRef(QRhiCommandBuffer *cb, quint32 refValue) override
bool ensureContext(QSurface *surface=nullptr) const
void draw(QRhiCommandBuffer *cb, quint32 vertexCount, quint32 instanceCount, quint32 firstVertex, quint32 firstInstance) override
void endComputePass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates) override
void(QOPENGLF_APIENTRYP glQueryCounter)(GLuint
void(QOPENGLF_APIENTRYP glDrawArraysInstancedBaseInstance)(GLenum
void beginComputePass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates, QRhiCommandBuffer::BeginPassFlags flags) override
void endPass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates) override
bool isYUpInFramebuffer() const override
bool linkProgram(GLuint program)
void debugMarkMsg(QRhiCommandBuffer *cb, const QByteArray &msg) override
void debugMarkEnd(QRhiCommandBuffer *cb) override
bool clearBufferProgramFailed
void setBlendConstants(QRhiCommandBuffer *cb, const QColor &c) override
void registerUniformIfActive(const QShaderDescription::BlockVariable &var, const QByteArray &namePrefix, int binding, int baseOffset, GLuint program, ActiveUniformLocationTracker *activeUniformLocations, QGles2UniformDescriptionVector *dst)
void setShaderResources(QRhiCommandBuffer *cb, QRhiShaderResourceBindings *srb, int dynamicOffsetCount, const QRhiCommandBuffer::DynamicOffset *dynamicOffsets) override
void releaseCachedResources() override
bool isClipDepthZeroToOne() const override
bool compileShader(GLuint program, const QRhiShaderStage &shaderStage, QShaderVersion *shaderVersion, std::optional< QShaderVersion > commonVersion=std::nullopt)
void executeDeferredReleases()
QByteArray pipelineCacheData() override
double lastCompletedGpuTime(QRhiCommandBuffer *cb) override
QRhi::FrameOpResult beginOffscreenFrame(QRhiCommandBuffer **cb, QRhi::BeginFrameFlags flags) override
void enqueueSubresUpload(QGles2Texture *texD, QGles2CommandBuffer *cbD, int layer, int level, const QRhiTextureSubresourceUploadDescription &subresDesc)
void setPushConstants(QRhiCommandBuffer *cb, quint32 offset, quint32 size, const void *data) override
QRhi::FrameOpResult endFrame(QRhiSwapChain *swapChain, QRhi::EndFrameFlags flags) override
void setPipelineCacheData(const QByteArray &data) override
QRhi::FrameOpResult endOffscreenFrame(QRhi::EndFrameFlags flags) override
const QRhiNativeHandles * nativeHandles() override
const QRhiPassResourceMap< QRhiTexture *, Texture, 12 > & textures() const
Definition qrhi_p.h:978
void registerBuffer(QRhiBuffer *buf, int slot, BufferAccess *access, BufferStage *stage, const UsageState &state)
Definition qrhi.cpp:13837
void registerTexture(QRhiTexture *tex, TextureAccess *access, TextureStage *stage, const UsageState &state)
Definition qrhi.cpp:13877
const QRhiPassResourceMap< QRhiBuffer *, Buffer, 12 > & buffers() const
Definition qrhi_p.h:970
static QRhiResourceUpdateBatchPrivate * get(QRhiResourceUpdateBatch *b)
Definition qrhi_p.h:756
\inmodule QtGui
Definition qshader.h:28
Combined button and popup list for selecting options.
#define GL_CONTEXT_LOST
Definition qopengl.cpp:30
#define QOPENGLF_APIENTRYP
Definition qopengl.h:275
#define GL_MAP_READ_BIT
#define GL_TEXTURE_3D
#define GL_TEXTURE_2D_MULTISAMPLE_ARRAY
#define GL_MAP_WRITE_BIT
#define GL_MIN
#define GL_TEXTURE_2D_MULTISAMPLE
#define GL_TEXTURE_2D_ARRAY
#define GL_MAX
#define GL_TEXTURE_EXTERNAL_OES
#define GL_PATCHES
#define GL_R32UI
#define GL_NUM_PROGRAM_BINARY_FORMATS
#define GL_TEXTURE_COMPARE_FUNC
Definition qopenglext.h:338
#define GL_DEPTH32F_STENCIL8
Definition qopenglext.h:995
#define GL_MAX_VARYING_VECTORS
#define GL_TEXTURE0
Definition qopenglext.h:129
#define GL_MAX_COMPUTE_WORK_GROUP_COUNT
#define GL_TEXTURE_WRAP_R
Definition qopenglext.h:87
#define GL_DEPTH_COMPONENT32F
Definition qopenglext.h:994
#define GL_GEOMETRY_SHADER
#define GL_DEPTH24_STENCIL8
#define GL_DEPTH_COMPONENT16
Definition qopenglext.h:328
#define GL_R16
#define GL_TEXTURE_CUBE_MAP
Definition qopenglext.h:170
#define GL_COPY_WRITE_BUFFER
#define GL_RG16
#define GL_R8
#define GL_PRIMITIVE_RESTART_FIXED_INDEX
#define GL_ONE_MINUS_CONSTANT_ALPHA
Definition qopenglext.h:367
#define GL_SHADER_IMAGE_ACCESS_BARRIER_BIT
#define GL_RG32UI
#define GL_SRC1_ALPHA
Definition qopenglext.h:508
#define GL_RGBA16F
Definition qopenglext.h:913
#define GL_COMPRESSED_TEXTURE_FORMATS
Definition qopenglext.h:186
#define GL_RGBA32UI
Definition qopenglext.h:948
#define GL_RED_INTEGER
Definition qopenglext.h:960
#define GL_RG8
#define GL_CONSTANT_COLOR
Definition qopenglext.h:364
#define GL_FRAMEBUFFER_SRGB
#define GL_TESS_CONTROL_SHADER
#define GL_R8I
#define GL_MAX_VERTEX_OUTPUT_COMPONENTS
#define GL_DEPTH_STENCIL_ATTACHMENT
#define GL_R8UI
#define GL_TEXTURE_CUBE_MAP_SEAMLESS
#define GL_BGRA
Definition qopenglext.h:97
#define GL_UNIFORM_BARRIER_BIT
#define GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS
#define GL_FLOAT_32_UNSIGNED_INT_24_8_REV
Definition qopenglext.h:996
#define GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS
#define GL_SRGB_ALPHA
Definition qopenglext.h:864
#define GL_TIMESTAMP
#define GL_QUERY_RESULT
Definition qopenglext.h:485
#define GL_COMPARE_REF_TO_TEXTURE
Definition qopenglext.h:894
#define GL_SHADER_STORAGE_BUFFER
#define GL_ALL_BARRIER_BITS
#define GL_R32F
#define GL_STENCIL_INDEX8
#define GL_ELEMENT_ARRAY_BARRIER_BIT
#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS
Definition qopenglext.h:611
#define GL_TEXTURE_FETCH_BARRIER_BIT
#define GL_UNSIGNED_INT_24_8
#define GL_COMMAND_BARRIER_BIT
#define GL_SRGB8_ALPHA8
Definition qopenglext.h:865
#define GL_RGBA32I
Definition qopenglext.h:954
#define GL_COMPUTE_SHADER
#define GL_SRC1_COLOR
#define GL_MAX_COMPUTE_WORK_GROUP_SIZE
#define GL_VERTEX_PROGRAM_POINT_SIZE
Definition qopenglext.h:582
#define GL_ONE_MINUS_SRC1_COLOR
#define GL_DRAW_FRAMEBUFFER
#define GL_PROGRAM_BINARY_LENGTH
#define GL_RG
#define GL_MAX_SAMPLES
#define GL_FUNC_REVERSE_SUBTRACT
Definition qopenglext.h:369
#define GL_RGBA_INTEGER
Definition qopenglext.h:964
#define GL_NUM_COMPRESSED_TEXTURE_FORMATS
Definition qopenglext.h:185
#define GL_TEXTURE_RECTANGLE
#define GL_TEXTURE_1D_ARRAY
Definition qopenglext.h:922
#define GL_R16F
#define GL_MAX_DRAW_BUFFERS
Definition qopenglext.h:588
#define GL_MAX_IMAGE_UNITS
#define GL_RG_INTEGER
#define GL_QUERY_RESULT_AVAILABLE
Definition qopenglext.h:486
#define GL_HALF_FLOAT
#define GL_TESS_EVALUATION_SHADER
#define GL_MAX_ARRAY_TEXTURE_LAYERS
Definition qopenglext.h:916
#define GL_READ_WRITE
Definition qopenglext.h:494
#define GL_PIXEL_BUFFER_BARRIER_BIT
#define GL_CONSTANT_ALPHA
Definition qopenglext.h:366
#define GL_ONE_MINUS_SRC1_ALPHA
#define GL_POINT_SPRITE
Definition qopenglext.h:657
#define GL_ONE_MINUS_CONSTANT_COLOR
Definition qopenglext.h:365
#define GL_MAX_VERTEX_UNIFORM_VECTORS
#define GL_DEPTH_STENCIL
#define GL_MAP_INVALIDATE_BUFFER_BIT
#define GL_TEXTURE_UPDATE_BARRIER_BIT
#define GL_WRITE_ONLY
Definition qopenglext.h:493
#define GL_READ_FRAMEBUFFER
#define GL_PARAMETER_BUFFER
#define GL_BUFFER_UPDATE_BARRIER_BIT
#define GL_TEXTURE_CUBE_MAP_POSITIVE_X
Definition qopenglext.h:172
#define GL_BUFFER
#define GL_MAX_FRAGMENT_UNIFORM_VECTORS
#define GL_DISPATCH_INDIRECT_BUFFER
#define GL_SHADER_STORAGE_BARRIER_BIT
#define GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS
#define GL_RGBA32F
Definition qopenglext.h:911
#define GL_PROGRAM
#define GL_FUNC_SUBTRACT
Definition qopenglext.h:370
#define GL_RG32I
#define GL_DEPTH_COMPONENT24
Definition qopenglext.h:329
#define GL_PATCH_VERTICES
#define GL_MAX_VERTEX_UNIFORM_COMPONENTS
Definition qopenglext.h:612
#define GL_DEPTH_CLAMP
#define GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT
#define GL_CLAMP_TO_EDGE
Definition qopenglext.h:100
#define GL_FRAMEBUFFER_BARRIER_BIT
#define GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS
#define GL_MAX_VARYING_COMPONENTS
Definition qopenglext.h:921
#define GL_R32I
#define GL_MAX_VARYING_FLOATS
Definition qopenglext.h:613
#define GL_FUNC_ADD
Definition qopenglext.h:368
#define GL_DRAW_INDIRECT_BUFFER
#define GL_TEXTURE_COMPARE_MODE
Definition qopenglext.h:337
#define GL_COPY_READ_BUFFER
#define GL_READ_ONLY
Definition qopenglext.h:492
#define GL_UNSIGNED_INT_2_10_10_10_REV
#define GL_UNPACK_ROW_LENGTH
#define QRHI_RES_RHI(t)
Definition qrhi_p.h:33
#define QRHI_RES(t, x)
Definition qrhi_p.h:32
static GLenum toGlMinFilter(QRhiSampler::Filter f, QRhiSampler::Filter m)
static QGles2Buffer::Access toGlAccess(QRhiPassResourceTracker::BufferAccess access)
static GLenum toGlCompressedTextureFormat(QRhiTexture::Format format, QRhiTexture::Flags flags)
static GLenum toGlTextureCompareFunc(QRhiSampler::CompareOp op)
static GLenum toGlCompareOp(QRhiGraphicsPipeline::CompareOp op)
static bool qrhi_gl_isTrackedUniform(const QGles2UniformDescription &uniform)
static quint32 qrhi_uniform_stride(const QGles2UniformDescription &uniform)
static GLenum toGlWrapMode(QRhiSampler::AddressMode m)
static GLenum toGlBlendFactor(QRhiGraphicsPipeline::BlendFactor f)
#define GL_RGBA8
static GLbitfield barriersForTexture()
static bool storageAccessNeedsBarrier(QRhiPassResourceTracker::TextureAccess prev, QRhiPassResourceTracker::TextureAccess next)
static GLenum toGlFrontFace(QRhiGraphicsPipeline::FrontFace f)
#define GL_BACK_LEFT
static void toGlTextureFormat(QRhiTexture::Format format, QRhiTexture::Flags flags, const QRhiGles2::Caps &caps, GLenum *glintformat, GLenum *glsizedintformat, GLenum *glformat, GLenum *gltype)
static void addBoundaryCommand(QGles2CommandBuffer *cbD, QGles2CommandBuffer::Command::Cmd type, GLuint tsQuery=0)
static QRhiPassResourceTracker::UsageState toPassTrackerUsageState(const QGles2Buffer::UsageState &bufUsage)
static bool bufferAccessIsWrite(QGles2Buffer::Access access)
static QGles2Texture::Access toGlAccess(QRhiPassResourceTracker::TextureAccess access)
#define GL_RED
static bool isMultisampleTextureTarget(GLenum target)
static void qrhi_block_to_packed(T *dst, int vecSize, int elemCount, const void *src, quint32 srcStride)
static bool isGraphicsStage(const QRhiShaderStage &shaderStage)
#define GL_FILL
static GLenum toGlBlendOp(QRhiGraphicsPipeline::BlendOp op)
static const quint32 QRHI_GL_STD140_STRIDE
static qint64 qrhi_uniform_read_size(QShaderDescription::VariableType type, int arrayDim, quint32 stride)
static QRhiPassResourceTracker::UsageState toPassTrackerUsageState(const QGles2Texture::UsageState &texUsage)
static GLenum toGlShaderType(QRhiShaderStage::Type type)
static GLenum toGlCullMode(QRhiGraphicsPipeline::CullMode c)
#define GL_LINE
static GLenum toGlStencilOp(QRhiGraphicsPipeline::StencilOp op)
static GLbitfield barriersForBuffer()
static GLenum toGlTopology(QRhiGraphicsPipeline::Topology t)
static bool isDepthTextureFormat(QRhiTexture::Format format)
void qrhigl_accumulateComputeResource(T *writtenResources, QRhiResource *resource, QRhiShaderResourceBinding::Type bindingType, int loadTypeVal, int storeTypeVal, int loadStoreTypeVal)
static void bindVertexIndexBufferWithStateReset(CommandBufferExecTrackedState *state, QOpenGLExtensions *f, GLenum target, GLuint buffer)
static bool textureAccessIsWrite(QGles2Texture::Access access)
#define GL_TEXTURE_1D
static GLenum toGlMagFilter(QRhiSampler::Filter f)
static bool storageAccessNeedsBarrier(QRhiPassResourceTracker::BufferAccess prev, QRhiPassResourceTracker::BufferAccess next)
#define GL_STENCIL_INDEX
static GLenum toGlPolygonMode(QRhiGraphicsPipeline::PolygonMode mode)
static QSurface * currentSurfaceForCurrentContext(QOpenGLContext *ctx)
#define GL_BACK_RIGHT
bool operator!=(const QGles2CommandBuffer::GraphicsPassState::ColorMask &a, const QGles2CommandBuffer::GraphicsPassState::ColorMask &b)
#define GL_FLOAT
#define GL_UNSIGNED_BYTE
#define GL_RGBA
bool enabledAttribArrays[TRACKED_ATTRIB_COUNT]
bool nonzeroAttribDivisor[TRACKED_ATTRIB_COUNT]
static const int TRACKED_ATTRIB_COUNT
@ AccessStorageReadWrite
Definition qrhigles2_p.h:55
UsageState usageState
Definition qrhigles2_p.h:62
bool passStorageAccessFragmentOnly
static const int TIMESTAMP_PAIRS
int currentTimestampPairIndex
bool create() override
Creates the corresponding native graphics resources.
bool isLevelAllocated(int face, int level) const
UsageState usageState
uint needsDepthStencilCombinedAttach
uint perRenderTargetBlending
int maxThreadGroupsPerDimension
uint glesMultisampleRenderToTexture
uint srgbTextureRenderTarget
uint multisampledTextureStorage
int maxFragmentStorageBuffers
uint fixedIndexPrimitiveRestart
uint screenSpaceDerivatives
uint nonBaseLevelFramebufferTexture
uint glesMultiviewMultisampleRenderToTexture
\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h
Definition qrhi.h:2016