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
qsgmaterialshader.cpp
Go to the documentation of this file.
1// Copyright (C) 2019 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 "qsgmaterial.h"
8#include <QtCore/QFile>
9#include <QtCore/qalgorithms.h>
10
12
13/*!
14 \class QSGMaterialShader
15 \brief The QSGMaterialShader class represents a graphics API independent shader program.
16 \inmodule QtQuick
17 \ingroup qtquick-scenegraph-materials
18 \since 5.14
19
20 QSGMaterialShader represents a combination of vertex and fragment shaders,
21 data that define the graphics pipeline state changes, and logic that
22 updates graphics resources, such as uniform buffers and textures.
23
24 \note All classes with QSG prefix should be used solely on the scene graph's
25 rendering thread. See \l {Scene Graph and Rendering} for more information.
26
27 The QSGMaterial and QSGMaterialShader form a tight relationship. For one
28 scene graph (including nested graphs), there is one unique
29 QSGMaterialShader instance that encapsulates the shaders and other data
30 the scene graph uses to render an object with that material. Each
31 QSGGeometryNode can have a unique QSGMaterial that defines how the graphics
32 pipeline must be configured while drawing the node. An instance of
33 QSGMaterialShader is never created explicitly by the user, it will be
34 created on demand by the scene graph through QSGMaterial::createShader().
35 The scene graph creates an instance of QSGMaterialShader by calling the
36 QSGMaterial::createShader() method, ensuring that there is only one
37 instance of each shader implementation.
38
39 In Qt 5, QSGMaterialShader was tied to OpenGL. It was built directly on
40 QOpenGLShaderProgram and had functions like \c updateState() that could
41 issue arbitrary OpenGL commands. This is no longer the case in Qt 6.
42 QSGMaterialShader is not strictly data-oriented, meaning it provides data
43 (shaders and the desired pipeline state changes) together with logic that
44 updates data in a uniform buffer. Graphics API access is not provided. This
45 means that a QSGMaterialShader cannot make OpenGL, Vulkan, Metal, or Direct
46 3D calls on its own. Together with the unified shader management, this
47 allows a QSGMaterialShader to be written once, and be functional with any of
48 the supported graphics APIs at run time.
49
50 The shaders set by calling the protected setShaderFileName() function
51 control what material does with the vertex data from the geometry, and how
52 the fragments are shaded. A QSGMaterialShader will typically set a vertex
53 and a fragment shader during construction. Changing the shaders afterwards
54 may not lead to the desired effect and must be avoided.
55
56 In Qt 6, the default approach is to ship \c{.qsb} files with the application,
57 typically embedded via the resource system, and referenced when calling
58 setShaderFileName(). The \c{.qsb} files are generated offline, or at latest
59 at application build time, from Vulkan-style GLSL source code using the \c
60 qsb tool from the Qt Shader Tools module.
61
62 There are three virtuals that can be overridden. These provide the data, or
63 the logic to generate the data, for uniform buffers, textures, and pipeline
64 state changes.
65
66 updateUniformData() is the function that is most commonly reimplemented in
67 subclasses. This function is expected to update the contents of a
68 QByteArray that will then be exposed to the shaders as a uniform buffer.
69 Any QSGMaterialShader that has a uniform block in its vertex or fragment
70 shader must reimplement updateUniformData().
71
72 updateSampledImage() is relevant when the shader code samples textures. The
73 function will be invoked for each sampler (or combined image sampler, in
74 APIs where relevant), giving it the option to specify which QSGTexture
75 should be exposed to the shader.
76
77 The shader pipeline state changes are less often used. One use case is
78 materials that wish to use a specific blend mode. The relevant function is
79 updateGraphicsPipelineState(). This function is not called unless the
80 QSGMaterialShader has opted in by setting the flag
81 UpdatesGraphicsPipelineState. The task of the function is to update the
82 GraphicsPipelineState struct instance that is passed to it with the
83 desired changes. Currently only blending and culling-related features are
84 available, other states cannot be controlled by materials.
85
86 A minimal example, that also includes texture support, could be the
87 following. Here we assume that Material is the QSGMaterial that creates an
88 instance of Shader in its \l{QSGMaterial::createShader()}{createShader()},
89 and that it holds a QSGTexture we want to sample in the fragment shader. The
90 vertex shader relies only on the modelview-projection matrix.
91
92 \code
93 class Shader : public QSGMaterialShader
94 {
95 public:
96 Shader()
97 {
98 setShaderFileName(VertexStage, QLatin1String(":/materialshader.vert.qsb"));
99 setShaderFileName(FragmentStage, QLatin1String(":/materialshader.frag.qsb"));
100 }
101
102 bool updateUniformData(RenderState &state, QSGMaterial *, QSGMaterial *)
103 {
104 bool changed = false;
105 QByteArray *buf = state.uniformData();
106 if (state.isMatrixDirty()) {
107 const QMatrix4x4 m = state.combinedMatrix();
108 memcpy(buf->data(), m.constData(), 64);
109 changed = true;
110 }
111 return changed;
112 }
113
114 void updateSampledImage(RenderState &, int binding, QSGTexture **texture, QSGMaterial *newMaterial, QSGMaterial *)
115 {
116 Material *mat = static_cast<Material *>(newMaterial);
117 if (binding == 1)
118 *texture = mat->texture();
119 }
120 };
121 \endcode
122
123 The Vulkan-style GLSL source code for the shaders could look like the
124 following. These are expected to be preprocessed offline using the \c qsb
125 tool, which generates the \c{.qsb} files referenced in the Shader()
126 constructor.
127
128 \badcode
129 #version 440
130 layout(location = 0) in vec4 aVertex;
131 layout(location = 1) in vec2 aTexCoord;
132 layout(location = 0) out vec2 vTexCoord;
133 layout(std140, binding = 0) uniform buf {
134 mat4 qt_Matrix;
135 } ubuf;
136 out gl_PerVertex { vec4 gl_Position; };
137 void main() {
138 gl_Position = ubuf.qt_Matrix * aVertex;
139 vTexCoord = aTexCoord;
140 }
141 \endcode
142
143 \badcode
144 #version 440
145 layout(location = 0) in vec2 vTexCoord;
146 layout(location = 0) out vec4 fragColor;
147 layout(binding = 1) uniform sampler2D srcTex;
148 void main() {
149 vec4 c = texture(srcTex, vTexCoord);
150 fragColor = vec4(c.rgb * 0.5, 1.0);
151 }
152 \endcode
153
154 \note All classes with QSG prefix should be used solely on the scene graph's
155 rendering thread. See \l {Scene Graph and Rendering} for more information.
156
157 \sa QSGMaterial, {Scene Graph - Custom Material}, {Scene Graph - Two Texture Providers}, {Scene Graph - Graph}
158 */
159
160/*!
161 \enum QSGMaterialShader::Flag
162 Flag values to indicate special material properties.
163
164 \value UpdatesGraphicsPipelineState Setting this flag enables calling
165 updateGraphicsPipelineState().
166 */
167
168QShader QSGMaterialShaderPrivate::loadShader(const QString &filename)
169{
170 QFile f(filename);
171 if (!f.open(QIODevice::ReadOnly)) {
172 qWarning() << "Failed to find shader" << filename;
173 return QShader();
174 }
175 return QShader::fromSerialized(f.readAll());
176}
177
178void QSGMaterialShaderPrivate::clearCachedRendererData()
179{
180 for (int i = 0; i < MAX_SHADER_RESOURCE_BINDINGS; ++i)
181 textureBindingTable[i].clear();
182 for (int i = 0; i < MAX_SHADER_RESOURCE_BINDINGS; ++i)
183 samplerBindingTable[i].clear();
184 for (auto &descs : samplerDescTable)
185 descs.clear();
186}
187
188static inline QRhiShaderResourceBinding::StageFlags toSrbStage(QShader::Stage stage)
189{
190 switch (stage) {
191 case QShader::VertexStage:
192 return QRhiShaderResourceBinding::VertexStage;
193 case QShader::FragmentStage:
194 return QRhiShaderResourceBinding::FragmentStage;
195 default:
196 Q_UNREACHABLE();
197 break;
198 }
199 return { };
200}
201
202void QSGMaterialShaderPrivate::prepare(QShader::Variant vertexShaderVariant)
203{
204 ubufBinding = -1;
205 ubufSize = 0;
206 ubufStages = { };
207 memset(static_cast<void *>(combinedImageSamplerBindings), 0, sizeof(combinedImageSamplerBindings));
208 memset(static_cast<void *>(combinedImageSamplerCount), 0, sizeof(combinedImageSamplerCount));
209 combinedImageSamplerMask = 0;
210 combinedImageSamplerSingle = true;
211 vertexShader = fragmentShader = nullptr;
212 masterUniformData.clear();
213
214 clearCachedRendererData();
215
216 for (QShader::Stage stage : { QShader::VertexStage, QShader::FragmentStage }) {
217 auto it = shaderFileNames.constFind(stage);
218 if (it != shaderFileNames.cend()) {
219 const QShader s = loadShader(*it);
220 if (!s.isValid())
221 continue;
222 shaders[stage] = ShaderStageData(s);
223 // load only once, subsequent prepare() calls will have it all in shaders already
224 shaderFileNames.erase(it);
225 }
226 }
227
228 auto vsIt = shaders.find(QShader::VertexStage);
229 if (vsIt != shaders.end()) {
230 vsIt->shaderVariant = vertexShaderVariant;
231 vsIt->vertexInputLocations.clear();
232 vsIt->qt_order_attrib_location = -1;
233
234 const QShaderDescription desc = vsIt->shader.description();
235 const QList<QShaderDescription::InOutVariable> vertexInputs = desc.inputVariables();
236 for (const QShaderDescription::InOutVariable &v : vertexInputs) {
237 if (vertexShaderVariant == QShader::BatchableVertexShader
238 && v.name == QByteArrayLiteral("_qt_order")) {
239 vsIt->qt_order_attrib_location = v.location;
240 } else {
241 vsIt->vertexInputLocations.append(v.location);
242 }
243 }
244
245 if (vsIt->vertexInputLocations.contains(vsIt->qt_order_attrib_location)) {
246 qWarning("Vertex input clash in rewritten (batchable) vertex shader at input location %d. "
247 "Vertex shaders must avoid using this location.", vsIt->qt_order_attrib_location);
248 }
249 }
250
251 for (auto it = shaders.begin(); it != shaders.end(); ++it) {
252 const QShaderDescription desc = it->shader.description();
253
254 const QList<QShaderDescription::UniformBlock> ubufs = desc.uniformBlocks();
255 const int ubufCount = ubufs.size();
256 if (ubufCount > 1) {
257 qWarning("Multiple uniform blocks found in shader. "
258 "This should be avoided as Qt Quick supports only one.");
259 }
260 for (int i = 0; i < ubufCount; ++i) {
261 const QShaderDescription::UniformBlock &ubuf(ubufs[i]);
262 if (ubuf.size <= 0) {
263 // QByteArray::fill() would treat a negative size as "keep the current
264 // size", leaving a buffer that every member offset then writes past.
265 qWarning("Uniform block %s has an invalid size (%d); ignored",
266 ubuf.blockName.constData(), ubuf.size);
267 continue;
268 }
269 if (ubufBinding == -1 && ubuf.binding >= 0) {
270 ubufBinding = ubuf.binding;
271 ubufSize = ubuf.size;
272 ubufStages |= toSrbStage(it->shader.stage());
273 masterUniformData.fill('\0', ubufSize);
274 } else if (ubufBinding == ubuf.binding && ubuf.binding >= 0) {
275 if (ubuf.size > ubufSize) {
276 ubufSize = ubuf.size;
277 masterUniformData.fill('\0', ubufSize);
278 }
279 ubufStages |= toSrbStage(it->shader.stage());
280 } else {
281 qWarning("Uniform block %s (binding %d) ignored", ubuf.blockName.constData(),
282 ubuf.binding);
283 }
284 }
285
286 const QList<QShaderDescription::InOutVariable> imageSamplers = desc.combinedImageSamplers();
287 const int imageSamplersCount = imageSamplers.size();
288 for (int i = 0; i < imageSamplersCount; ++i) {
289 const QShaderDescription::InOutVariable &var(imageSamplers[i]);
290
291 if (var.binding < 0)
292 continue;
293
294 if (var.binding < MAX_SHADER_RESOURCE_BINDINGS) {
295 combinedImageSamplerBindings[var.binding] |= toSrbStage(it->shader.stage());
296
297 int count = 1;
298 for (int dim : var.arrayDims)
299 count *= dim;
300
301 combinedImageSamplerCount[var.binding] = count;
302 combinedImageSamplerMask |= 1u << var.binding;
303 } else {
304 qWarning("Encountered invalid combined image sampler (%s) binding %d",
305 var.name.constData(), var.binding);
306 }
307 }
308
309 if (it.key() == QShader::VertexStage)
310 vertexShader = &it.value();
311 else if (it.key() == QShader::FragmentStage)
312 fragmentShader = &it.value();
313 }
314
315 samplerDescTable.resize(qPopulationCount(combinedImageSamplerMask));
316 combinedImageSamplerSingle = samplerDescTable.size() <= 1;
317 if (combinedImageSamplerMask)
318 combinedImageSamplerSingle &= combinedImageSamplerCount[qCountTrailingZeroBits(combinedImageSamplerMask)] == 1;
319
320 if (vertexShader && vertexShaderVariant == QShader::BatchableVertexShader && vertexShader->qt_order_attrib_location == -1)
321 qWarning("No rewriter-inserted attribute found, this should not happen.");
322}
323
324/*!
325 Constructs a new QSGMaterialShader.
326 */
327QSGMaterialShader::QSGMaterialShader()
328 : d_ptr(new QSGMaterialShaderPrivate(this))
329{
330}
331
332/*!
333 \internal
334 */
335QSGMaterialShader::QSGMaterialShader(QSGMaterialShaderPrivate &dd)
336 : d_ptr(&dd)
337{
338}
339
340/*!
341 \internal
342 */
343QSGMaterialShader::~QSGMaterialShader()
344{
345}
346
347// We have our own enum as QShader is not initially public. Internally
348// everything works with QShader::Stage however. So convert.
349static inline QShader::Stage toShaderStage(QSGMaterialShader::Stage stage)
350{
351 switch (stage) {
352 case QSGMaterialShader::VertexStage:
353 return QShader::VertexStage;
354 case QSGMaterialShader::FragmentStage:
355 return QShader::FragmentStage;
356 default:
357 Q_UNREACHABLE_RETURN(QShader::VertexStage);
358 }
359}
360
361/*!
362 Sets the \a shader for the specified \a stage.
363 */
364void QSGMaterialShader::setShader(Stage stage, const QShader &shader)
365{
366 Q_D(QSGMaterialShader);
367 d->shaders[toShaderStage(stage)] = QSGMaterialShaderPrivate::ShaderStageData(shader);
368}
369
370/*!
371 Sets the \a filename for the shader for the specified \a stage.
372
373 The file is expected to contain a serialized QShader.
374
375 \warning Shaders, including \c{.qsb} files, are assumed to be trusted
376 content. Application developers are advised to carefully consider the
377 potential implications before allowing the loading of user-provided content
378 that is not part of the application.
379 */
380void QSGMaterialShader::setShaderFileName(Stage stage, const QString &filename)
381{
382 Q_D(QSGMaterialShader);
383 d->shaderFileNames[toShaderStage(stage)] = filename;
384}
385
386/*!
387 Sets the \a filename for the shader for the specified \a stage.
388
389 The file is expected to contain a serialized QShader.
390
391 This overload is used when enabling \l{QSGMaterial::viewCount()}{multiview}
392 rendering, in particular when the \l{qt_add_shaders}
393 {build system's MULTIVIEW convenience option} is used.
394
395 \a viewCount should be 2, 3, or 4. The \a filename is adjusted automatically
396 based on this.
397
398 \warning Shaders, including \c{.qsb} files, are assumed to be trusted
399 content. Application developers are advised to carefully consider the
400 potential implications before allowing the loading of user-provided content
401 that is not part of the application.
402
403 \since 6.8
404 */
405void QSGMaterialShader::setShaderFileName(Stage stage, const QString &filename, int viewCount)
406{
407 Q_D(QSGMaterialShader);
408 if (viewCount == 2)
409 d->shaderFileNames[toShaderStage(stage)] = filename + QStringLiteral(".mv2qsb");
410 else if (viewCount == 3)
411 d->shaderFileNames[toShaderStage(stage)] = filename + QStringLiteral(".mv3qsb");
412 else if (viewCount == 4)
413 d->shaderFileNames[toShaderStage(stage)] = filename + QStringLiteral(".mv4qsb");
414 else
415 d->shaderFileNames[toShaderStage(stage)] = filename;
416}
417
418/*!
419 \return the currently set flags for this material shader.
420 */
421QSGMaterialShader::Flags QSGMaterialShader::flags() const
422{
423 Q_D(const QSGMaterialShader);
424 return d->flags;
425}
426
427/*!
428 Sets the \a flags on this material shader if \a on is true;
429 otherwise clears the specified flags.
430*/
431void QSGMaterialShader::setFlag(Flags flags, bool on)
432{
433 Q_D(QSGMaterialShader);
434 if (on)
435 d->flags |= flags;
436 else
437 d->flags &= ~flags;
438}
439
440/*!
441 Sets the \a flags for this material shader.
442 */
443void QSGMaterialShader::setFlags(Flags flags)
444{
445 Q_D(QSGMaterialShader);
446 d->flags = flags;
447}
448
449/*!
450 Returns the number of elements in the combined image sampler variable at \a
451 binding. This value is introspected from the shader code. The variable may
452 be an array, and may have more than one dimension.
453
454 The count reflects the total number of combined image sampler items in the
455 variable. In the following example, the count for \c{srcA} is 1, \c{srcB}
456 is 4, and \c{srcC} is 6.
457
458 \badcode
459 layout (binding = 0) uniform sampler2D srcA;
460 layout (binding = 1) uniform sampler2D srcB[4];
461 layout (binding = 2) uniform sampler2D srcC[2][3];
462 \endcode
463
464 This count is the number of QSGTexture pointers in the texture parameter
465 of \l{QSGMaterialShader::updateSampledImage}.
466
467 \sa QSGMaterialShader::updateSampledImage
468 \since 6.4
469 */
470int QSGMaterialShader::combinedImageSamplerCount(int binding) const
471{
472 Q_D(const QSGMaterialShader);
473
474 if (binding >= 0 && binding < d->MAX_SHADER_RESOURCE_BINDINGS)
475 return d->combinedImageSamplerCount[binding];
476
477 return 0;
478}
479
480/*!
481 This function is called by the scene graph to get the contents of the
482 shader program's uniform buffer updated. The implementation is not expected
483 to perform any real graphics operations, it is merely responsible for
484 copying data to the QByteArray returned from RenderState::uniformData().
485 The scene graph takes care of making that buffer visible in the shaders.
486
487 The current rendering \a state is passed from the scene graph. If the state
488 indicates that any relevant state is dirty, the implementation must update
489 the appropriate region in the buffer data that is accessible via
490 RenderState::uniformData(). When a state, such as, matrix or opacity, is
491 not dirty, there is no need to touch the corresponding region since the
492 data is persistent.
493
494 The return value must be \c true whenever any change was made to the uniform data.
495
496 The subclass specific state, such as the color of a flat color material,
497 should be extracted from \a newMaterial to update the relevant regions in
498 the buffer accordingly.
499
500 \a oldMaterial can be used to minimize buffer changes (which are typically
501 memcpy calls) when updating material states. When \a oldMaterial is null,
502 this shader was just activated.
503 */
504bool QSGMaterialShader::updateUniformData(RenderState &state,
505 QSGMaterial *newMaterial,
506 QSGMaterial *oldMaterial)
507{
508 Q_UNUSED(state);
509 Q_UNUSED(newMaterial);
510 Q_UNUSED(oldMaterial);
511 return false;
512}
513
514/*!
515 This function is called by the scene graph to prepare use of sampled images
516 in the shader, typically in the form of combined image samplers.
517
518 \a binding is the binding number of the sampler. The function is called for
519 each combined image sampler variable in the shader code associated with the
520 QSGMaterialShader.
521
522 \a{texture} is an array of QSGTexture pointers. The number of elements in
523 the array matches the number of elements in the image sampler variable
524 specified in the shader code. This variable may be an array, and may have
525 more than one dimension. The number of elements in the array may be
526 found via \l{QSGMaterialShader::combinedImageSamplerCount}
527
528 When an element in \a{texture} is null, it must be set to a valid
529 QSGTexture pointer before returning. When non-null, it is up to the
530 material to decide if a new \c{QSGTexture *} is stored to it, or if it
531 updates some parameters on the already known QSGTexture. The ownership of
532 the QSGTexture is not transferred.
533
534 The current rendering \a state is passed from the scene graph. Where
535 relevant, it is up to the material to trigger enqueuing texture data
536 uploads via QSGTexture::commitTextureOperations().
537
538 The subclass specific state can be extracted from \a newMaterial.
539
540 \a oldMaterial can be used to minimize changes. When \a oldMaterial is null,
541 this shader was just activated.
542
543 \sa QSGMaterialShader::combinedImageSamplerCount
544 */
545void QSGMaterialShader::updateSampledImage(RenderState &state,
546 int binding,
547 QSGTexture **texture,
548 QSGMaterial *newMaterial,
549 QSGMaterial *oldMaterial)
550{
551 Q_UNUSED(state);
552 Q_UNUSED(binding);
553 Q_UNUSED(texture);
554 Q_UNUSED(newMaterial);
555 Q_UNUSED(oldMaterial);
556}
557
558/*!
559 This function is called by the scene graph to enable the material to
560 provide a custom set of graphics state. The set of states that are
561 customizable by material is limited to blending and related settings.
562
563 \note This function is only called when the UpdatesGraphicsPipelineState
564 flag was enabled via setFlags(). By default it is not set, and so this
565 function is never called.
566
567 The return value must be \c true whenever a change was made to any of the
568 members in \a ps.
569
570 \note The contents of \a ps is not persistent between invocations of this
571 function.
572
573 The current rendering \a state is passed from the scene graph.
574
575 The subclass specific state can be extracted from \a newMaterial. When \a
576 oldMaterial is null, this shader was just activated.
577 */
578bool QSGMaterialShader::updateGraphicsPipelineState(RenderState &state, GraphicsPipelineState *ps,
579 QSGMaterial *newMaterial, QSGMaterial *oldMaterial)
580{
581 Q_UNUSED(state);
582 Q_UNUSED(ps);
583 Q_UNUSED(newMaterial);
584 Q_UNUSED(oldMaterial);
585 return false;
586}
587
588/*!
589 \class QSGMaterialShader::RenderState
590
591 \brief Encapsulates the current rendering state during a call to
592 QSGMaterialShader::updateUniformData() and the other \c update type of
593 functions.
594
595 \inmodule QtQuick
596 \since 5.14
597
598 The render state contains a number of accessors that the shader needs to
599 respect in order to conform to the current state of the scene graph.
600 */
601
602/*!
603 \enum QSGMaterialShader::RenderState::DirtyState
604
605 \value DirtyMatrix Used to indicate that the matrix has changed and must be
606 updated.
607
608 \value DirtyOpacity Used to indicate that the opacity has changed and must
609 be updated.
610
611 \value DirtyCachedMaterialData Used to indicate that the cached material
612 state has changed and must be updated.
613
614 \value DirtyAll Used to indicate that everything needs to be updated.
615 */
616
617/*!
618 \fn bool QSGMaterialShader::RenderState::isMatrixDirty() const
619
620 Returns \c true if the dirtyStates() contain the dirty matrix state,
621 otherwise returns \c false.
622 */
623
624/*!
625 \fn bool QSGMaterialShader::RenderState::isOpacityDirty() const
626
627 Returns \c true if the dirtyStates() contains the dirty opacity state,
628 otherwise returns \c false.
629 */
630
631/*!
632 \fn QSGMaterialShader::RenderState::DirtyStates QSGMaterialShader::RenderState::dirtyStates() const
633
634 Returns which rendering states that have changed and needs to be updated
635 for geometry rendered with this material to conform to the current
636 rendering state.
637 */
638
639/*!
640 \class QSGMaterialShader::GraphicsPipelineState
641
642 \brief Describes state changes that the material wants to apply to the
643 currently active graphics pipeline state.
644
645 \inmodule QtQuick
646 \since 5.14
647
648 Unlike QSGMaterialShader, directly issuing state change commands with the
649 underlying graphics API is not possible with QSGMaterialShader. This is
650 mainly because the concept of individually changeable states is considered
651 deprecated and not supported with modern graphics APIs.
652
653 Therefore, it is up to QSGMaterialShader to expose a data structure with
654 the set of supported states, which the material can change in its
655 updatePipelineState() implementation, if there is one. The scenegraph will
656 then internally apply these changes to the active graphics pipeline state,
657 then rolling them back as appropriate.
658
659 When updateGraphicsPipelineState() is called, the struct has all members
660 set to a valid value to reflect the renderer's current state. Not changing
661 any values (or not reimplementing the function) indicates that the material
662 is fine with the defaults (which are dynamic however, depending on
663 QSGMaterial flags, for example).
664 */
665
666/*!
667 \enum QSGMaterialShader::GraphicsPipelineState::BlendFactor
668 \since 5.14
669
670 \value Zero
671 \value One
672 \value SrcColor
673 \value OneMinusSrcColor
674 \value DstColor
675 \value OneMinusDstColor
676 \value SrcAlpha
677 \value OneMinusSrcAlpha
678 \value DstAlpha
679 \value OneMinusDstAlpha
680 \value ConstantColor
681 \value OneMinusConstantColor
682 \value ConstantAlpha
683 \value OneMinusConstantAlpha
684 \value SrcAlphaSaturate
685 \value Src1Color
686 \value OneMinusSrc1Color
687 \value Src1Alpha
688 \value OneMinusSrc1Alpha
689 */
690
691/*!
692 \enum QSGMaterialShader::GraphicsPipelineState::BlendOp
693 \since 6.8
694
695 \value Add
696 \value Subtract
697 \value ReverseSubtract
698 \value Min
699 \value Max
700 */
701
702/*!
703 \enum QSGMaterialShader::GraphicsPipelineState::ColorMaskComponent
704 \since 5.14
705
706 \value R
707 \value G
708 \value B
709 \value A
710 */
711
712/*!
713 \enum QSGMaterialShader::GraphicsPipelineState::CullMode
714 \since 5.14
715
716 \value CullNone
717 \value CullFront
718 \value CullBack
719 */
720
721/*!
722 \enum QSGMaterialShader::GraphicsPipelineState::PolygonMode
723 \since 6.4
724 \brief Specifies the polygon rasterization mode
725
726 Polygon Mode (Triangle Fill Mode in Metal, Fill Mode in D3D) specifies
727 the fill mode used when rasterizing polygons. Polygons may be drawn as
728 solids (Fill), or as a wire mesh (Line).
729
730 \warning OpenGL ES does not support the \c{Line} polygon mode. OpenGL ES
731 will rasterize all polygons as filled no matter what polygon mode is set.
732 Using \c{Line} will make your application non-portable.
733
734 \value Fill The interior of the polygon is filled (default)
735 \value Line Boundary edges of the polygon are drawn as line segments.
736 */
737
738/*!
739 \variable QSGMaterialShader::GraphicsPipelineState::blendEnable
740 \since 5.14
741 \brief Enables blending.
742
743 \note Changing this flag should be done with care, and is best avoided.
744 Rather, materials should always use the QSGMaterial::Blend flag to indicate
745 that they wish to use blending. Changing this value from false to true for
746 a material that did not declare QSGMaterial::Blend can lead to unexpected
747 visual results.
748 */
749
750/*!
751 \variable QSGMaterialShader::GraphicsPipelineState::srcColor
752 \since 5.14
753 \brief Source blending factor, either RGB or RGBA depending on separateBlendFactors.
754 */
755
756/*!
757 \variable QSGMaterialShader::GraphicsPipelineState::dstColor
758 \since 5.14
759 \brief Destination blending factor, either RGB or RGBA depending on separateBlendFactors.
760 */
761
762/*!
763 \variable QSGMaterialShader::GraphicsPipelineState::colorWrite
764 \since 5.14
765 \brief Color write mask.
766 */
767
768/*!
769 \variable QSGMaterialShader::GraphicsPipelineState::blendConstant
770 \since 5.14
771 \brief Blend constant applicable when a blending factor is set to use a constant value.
772 */
773
774/*!
775 \variable QSGMaterialShader::GraphicsPipelineState::cullMode
776 \since 5.14
777 \brief Cull mode.
778 */
779
780/*!
781 \variable QSGMaterialShader::GraphicsPipelineState::polygonMode
782 \since 6.4
783 \brief Polygon rasterization mode.
784 */
785
786/*!
787 \variable QSGMaterialShader::GraphicsPipelineState::separateBlendFactors
788 \since 6.5
789 \brief Indicates that alpha blending factors are specified separately.
790
791 False by default, meaning both RGB and alpha blending factors are defined
792 by srcColor and dstColor. When set to true, the alpha blending factors are
793 taken from srcAlpha and dstAlpha instead, and srcColor and dstColor applies
794 only to RGB.
795 */
796
797/*!
798 \variable QSGMaterialShader::GraphicsPipelineState::srcAlpha
799 \since 6.5
800 \brief Source alpha blending factor.
801
802 Applies only when separateBlendFactors is set to true.
803 */
804
805/*!
806 \variable QSGMaterialShader::GraphicsPipelineState::dstAlpha
807 \since 6.5
808 \brief Destination alpha blending factor.
809
810 Applies only when separateBlendFactors is set to true.
811 */
812
813/*!
814 \variable QSGMaterialShader::GraphicsPipelineState::opColor
815 \since 6.8
816 \brief RGB blending operation.
817 */
818
819/*!
820 \variable QSGMaterialShader::GraphicsPipelineState::opAlpha
821 \since 6.8
822 \brief Alpha blending operation.
823 */
824
825/*!
826 Returns the accumulated opacity to be used for rendering.
827 */
828float QSGMaterialShader::RenderState::opacity() const
829{
830 Q_ASSERT(m_data);
831 return float(static_cast<const QSGRenderer *>(m_data)->currentOpacity());
832}
833
834/*!
835 Returns the modelview determinant to be used for rendering.
836 */
837float QSGMaterialShader::RenderState::determinant() const
838{
839 Q_ASSERT(m_data);
840 return float(static_cast<const QSGRenderer *>(m_data)->determinant());
841}
842
843/*!
844 Returns the matrix combined of modelview matrix and project matrix.
845 */
846QMatrix4x4 QSGMaterialShader::RenderState::combinedMatrix() const
847{
848 Q_ASSERT(m_data);
849 return static_cast<const QSGRenderer *>(m_data)->currentCombinedMatrix(0);
850}
851
852/*!
853 \internal
854 */
855QMatrix4x4 QSGMaterialShader::RenderState::combinedMatrix(qsizetype index) const
856{
857 Q_ASSERT(m_data);
858 return static_cast<const QSGRenderer *>(m_data)->currentCombinedMatrix(index);
859}
860
861/*!
862 Returns the ratio between physical pixels and device-independent pixels
863 to be used for rendering.
864*/
865float QSGMaterialShader::RenderState::devicePixelRatio() const
866{
867 Q_ASSERT(m_data);
868 return float(static_cast<const QSGRenderer *>(m_data)->devicePixelRatio());
869}
870
871/*!
872 Returns the model view matrix.
873
874 If the material has the RequiresFullMatrix flag set, this is guaranteed to
875 be the complete transform matrix calculated from the scenegraph.
876
877 However, if this flag is not set, the renderer may choose to alter this
878 matrix. For example, it may pre-transform vertices on the CPU and set this
879 matrix to identity.
880
881 In a situation such as the above, it is still possible to retrieve the
882 actual matrix determinant by setting the RequiresDeterminant flag in the
883 material and calling the determinant() accessor.
884 */
885QMatrix4x4 QSGMaterialShader::RenderState::modelViewMatrix() const
886{
887 Q_ASSERT(m_data);
888 return static_cast<const QSGRenderer *>(m_data)->currentModelViewMatrix();
889}
890
891/*!
892 Returns the projection matrix.
893 */
894QMatrix4x4 QSGMaterialShader::RenderState::projectionMatrix() const
895{
896 Q_ASSERT(m_data);
897 return static_cast<const QSGRenderer *>(m_data)->currentProjectionMatrix(0);
898}
899
900/*!
901 \internal
902 */
903QMatrix4x4 QSGMaterialShader::RenderState::projectionMatrix(qsizetype index) const
904{
905 Q_ASSERT(m_data);
906 return static_cast<const QSGRenderer *>(m_data)->currentProjectionMatrix(index);
907}
908
909/*!
910 \internal
911 */
912qsizetype QSGMaterialShader::RenderState::projectionMatrixCount() const
913{
914 Q_ASSERT(m_data);
915 return static_cast<const QSGRenderer *>(m_data)->projectionMatrixCount();
916}
917
918/*!
919 Returns the viewport rect of the surface being rendered to.
920 */
921QRect QSGMaterialShader::RenderState::viewportRect() const
922{
923 Q_ASSERT(m_data);
924 return static_cast<const QSGRenderer *>(m_data)->viewportRect();
925}
926
927/*!
928 Returns the device rect of the surface being rendered to
929 */
930QRect QSGMaterialShader::RenderState::deviceRect() const
931{
932 Q_ASSERT(m_data);
933 return static_cast<const QSGRenderer *>(m_data)->deviceRect();
934}
935
936/*!
937 Returns a pointer to the data for the uniform (constant) buffer in the
938 shader. Uniform data must only be updated from
939 QSGMaterialShader::updateUniformData(). The return value is null in the
940 other reimplementable functions, such as,
941 QSGMaterialShader::updateSampledImage().
942
943 \note It is strongly recommended to declare the uniform block with \c
944 std140 in the shader, and to carefully study the standard uniform block
945 layout as described in section 7.6.2.2 of the OpenGL specification. It is
946 up to the QSGMaterialShader implementation to ensure data gets placed
947 at the right location in this QByteArray, taking alignment requirements
948 into account. Shader code translated to other shading languages is expected
949 to use the same offsets for block members, even when the target language
950 uses different packing rules by default.
951
952 \note Avoid copying from C++ POD types, such as, structs, in order to
953 update multiple members at once, unless it has been verified that the
954 layouts of the C++ struct and the GLSL uniform block match.
955 */
956QByteArray *QSGMaterialShader::RenderState::uniformData()
957{
958 Q_ASSERT(m_data);
959 return static_cast<const QSGRenderer *>(m_data)->currentUniformData();
960}
961
962/*!
963 Returns a resource update batch to which upload and copy operatoins can be
964 queued. This is typically used by
965 QSGMaterialShader::updateSampledImage() to enqueue texture image
966 content updates.
967 */
968QRhiResourceUpdateBatch *QSGMaterialShader::RenderState::resourceUpdateBatch()
969{
970 Q_ASSERT(m_data);
971 return static_cast<const QSGRenderer *>(m_data)->currentResourceUpdateBatch();
972}
973
974/*!
975 Returns the current QRhi.
976 */
977QRhi *QSGMaterialShader::RenderState::rhi()
978{
979 Q_ASSERT(m_data);
980 return static_cast<const QSGRenderer *>(m_data)->currentRhi();
981}
982
983QT_END_NAMESPACE
Combined button and popup list for selecting options.
static QShader::Stage toShaderStage(QSGMaterialShader::Stage stage)
static QRhiShaderResourceBinding::StageFlags toSrbStage(QShader::Stage stage)