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
qopenglengineshadermanager_p.h
Go to the documentation of this file.
1// Copyright (C) 2016 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
4//
5// W A R N I N G
6// -------------
7//
8// This file is not part of the Qt API. It exists purely as an
9// implementation detail. This header file may change from version to
10// version without notice, or even be removed.
11//
12// We mean it.
13//
14
15/*
16 VERTEX SHADERS
17 ==============
18
19 Vertex shaders are specified as multiple (partial) shaders. On desktop,
20 this works fine. On ES, QOpenGLShader & QOpenGLShaderProgram will make partial
21 shaders work by concatenating the source in each QOpenGLShader and compiling
22 it as a single shader. This is abstracted nicely by QOpenGLShaderProgram and
23 the GL2 engine doesn't need to worry about it.
24
25 Generally, there's two vertex shader objects. The position shaders are
26 the ones which set gl_Position. There's also two "main" vertex shaders,
27 one which just calls the position shader and another which also passes
28 through some texture coordinates from a vertex attribute array to a
29 varying. These texture coordinates are used for mask position in text
30 rendering and for the source coordinates in drawImage/drawPixmap. There's
31 also a "Simple" vertex shader for rendering a solid colour (used to render
32 into the stencil buffer where the actual colour value is discarded).
33
34 The position shaders for brushes look scary. This is because many of the
35 calculations which logically belong in the fragment shader have been moved
36 into the vertex shader to improve performance. This is why the position
37 calculation is in a separate shader. Not only does it calculate the
38 position, but it also calculates some data to be passed to the fragment
39 shader as a varying. It is optimal to move as much of the calculation as
40 possible into the vertex shader as this is executed less often.
41
42 The varyings passed to the fragment shaders are interpolated (which is
43 cheap). Unfortunately, GL will apply perspective correction to the
44 interpolation calusing errors. To get around this, the vertex shader must
45 apply perspective correction itself and set the w-value of gl_Position to
46 zero. That way, GL will be tricked into thinking it doesn't need to apply a
47 perspective correction and use linear interpolation instead (which is what
48 we want). Of course, if the brush transform is affeine, no perspective
49 correction is needed and a simpler vertex shader can be used instead.
50
51 So there are the following "main" vertex shaders:
52 qopenglslMainVertexShader
53 qopenglslMainWithTexCoordsVertexShader
54
55 And the following position vertex shaders:
56 qopenglslPositionOnlyVertexShader
57 qopenglslPositionWithTextureBrushVertexShader
58 qopenglslPositionWithPatternBrushVertexShader
59 qopenglslPositionWithLinearGradientBrushVertexShader
60 qopenglslPositionWithRadialGradientBrushVertexShader
61 qopenglslPositionWithConicalGradientBrushVertexShader
62 qopenglslAffinePositionWithTextureBrushVertexShader
63 qopenglslAffinePositionWithPatternBrushVertexShader
64 qopenglslAffinePositionWithLinearGradientBrushVertexShader
65 qopenglslAffinePositionWithRadialGradientBrushVertexShader
66 qopenglslAffinePositionWithConicalGradientBrushVertexShader
67
68 Leading to 23 possible vertex shaders
69
70
71 FRAGMENT SHADERS
72 ================
73
74 Fragment shaders are also specified as multiple (partial) shaders. The
75 different fragment shaders represent the different stages in Qt's fragment
76 pipeline. There are 1-3 stages in this pipeline: First stage is to get the
77 fragment's colour value. The next stage is to get the fragment's mask value
78 (coverage value for anti-aliasing) and the final stage is to blend the
79 incoming fragment with the background (for composition modes not supported
80 by GL).
81
82 Of these, the first stage will always be present. If Qt doesn't need to
83 apply anti-aliasing (because it's off or handled by multisampling) then
84 the coverage value doesn't need to be applied. (Note: There are two types
85 of mask, one for regular anti-aliasing and one for sub-pixel anti-
86 aliasing.) If the composition mode is one which GL supports natively then
87 the blending stage doesn't need to be applied.
88
89 As eash stage can have multiple implementations, they are abstracted as
90 GLSL function calls with the following signatures:
91
92 Brushes & image drawing are implementations of "qcolorp vec4 srcPixel()":
93 qopenglslImageSrcFragShader
94 qopenglslImageSrcWithPatternFragShader
95 qopenglslNonPremultipliedImageSrcFragShader
96 qopenglslSolidBrushSrcFragShader
97 qopenglslTextureBrushSrcFragShader
98 qopenglslTextureBrushWithPatternFragShader
99 qopenglslPatternBrushSrcFragShader
100 qopenglslLinearGradientBrushSrcFragShader
101 qopenglslRadialGradientBrushSrcFragShader
102 qopenglslConicalGradientBrushSrcFragShader
103 NOTE: It is assumed the colour returned by srcPixel() is pre-multiplied
104
105 Masks are implementations of "qcolorp vec4 applyMask(qcolorp vec4 src)":
106 qopenglslMaskFragmentShader
107 qopenglslRgbMaskFragmentShaderPass1
108 qopenglslRgbMaskFragmentShaderPass2
109 qopenglslRgbMaskWithGammaFragmentShader
110
111 Composition modes are "qcolorp vec4 compose(qcolorp vec4 src)":
112 qopenglslColorBurnCompositionModeFragmentShader
113 qopenglslColorDodgeCompositionModeFragmentShader
114 qopenglslDarkenCompositionModeFragmentShader
115 qopenglslDifferenceCompositionModeFragmentShader
116 qopenglslExclusionCompositionModeFragmentShader
117 qopenglslHardLightCompositionModeFragmentShader
118 qopenglslLightenCompositionModeFragmentShader
119 qopenglslMultiplyCompositionModeFragmentShader
120 qopenglslOverlayCompositionModeFragmentShader
121 qopenglslScreenCompositionModeFragmentShader
122 qopenglslSoftLightCompositionModeFragmentShader
123
124
125 Note: In the future, some GLSL compilers will support an extension allowing
126 a new 'color' precision specifier. To support this, qcolorp is used for
127 all color components so it can be defined to colorp or lowp depending upon
128 the implementation.
129
130 So there are different fragment shader main functions, depending on the
131 number & type of pipelines the fragment needs to go through.
132
133 The choice of which main() fragment shader string to use depends on:
134 - Use of global opacity
135 - Brush style (some brushes apply opacity themselves)
136 - Use & type of mask (TODO: Need to support high quality anti-aliasing & text)
137 - Use of non-GL Composition mode
138
139 Leading to the following fragment shader main functions:
140 gl_FragColor = compose(applyMask(srcPixel()*globalOpacity));
141 gl_FragColor = compose(applyMask(srcPixel()));
142 gl_FragColor = applyMask(srcPixel()*globalOpacity);
143 gl_FragColor = applyMask(srcPixel());
144 gl_FragColor = compose(srcPixel()*globalOpacity);
145 gl_FragColor = compose(srcPixel());
146 gl_FragColor = srcPixel()*globalOpacity;
147 gl_FragColor = srcPixel();
148
149 Called:
150 qopenglslMainFragmentShader_CMO
151 qopenglslMainFragmentShader_CM
152 qopenglslMainFragmentShader_MO
153 qopenglslMainFragmentShader_M
154 qopenglslMainFragmentShader_CO
155 qopenglslMainFragmentShader_C
156 qopenglslMainFragmentShader_O
157 qopenglslMainFragmentShader
158
159 Where:
160 M = Mask
161 C = Composition
162 O = Global Opacity
163
164
165 CUSTOM SHADER CODE
166 ==================
167
168 The use of custom shader code is supported by the engine for drawImage and
169 drawPixmap calls. This is implemented via hooks in the fragment pipeline.
170
171 The custom shader is passed to the engine as a partial fragment shader
172 (QOpenGLCustomShaderStage). The shader will implement a pre-defined method name
173 which Qt's fragment pipeline will call:
174
175 lowp vec4 customShader(lowp sampler2d imageTexture, highp vec2 textureCoords)
176
177 The provided src and srcCoords parameters can be used to sample from the
178 source image.
179
180 Transformations, clipping, opacity, and composition modes set using QPainter
181 will be respected when using the custom shader hook.
182*/
183
184#ifndef QOPENGLENGINE_SHADER_MANAGER_H
185#define QOPENGLENGINE_SHADER_MANAGER_H
186
187#include <QOpenGLShader>
188#include <QOpenGLShaderProgram>
189#include <QPainter>
190#include <private/qopenglcontext_p.h>
191#include <private/qopenglcustomshaderstage_p.h>
192
194
195
196
197/*
198struct QOpenGLEngineCachedShaderProg
199{
200 QOpenGLEngineCachedShaderProg(QOpenGLEngineShaderManager::ShaderName vertexMain,
201 QOpenGLEngineShaderManager::ShaderName vertexPosition,
202 QOpenGLEngineShaderManager::ShaderName fragMain,
203 QOpenGLEngineShaderManager::ShaderName pixelSrc,
204 QOpenGLEngineShaderManager::ShaderName mask,
205 QOpenGLEngineShaderManager::ShaderName composition);
206
207 int cacheKey;
208 QOpenGLShaderProgram* program;
209}
210*/
211
214static const GLuint QT_OPACITY_ATTR = 2;
218
220
221class Q_OPENGL_EXPORT QOpenGLEngineSharedShaders
222{
223 Q_GADGET
224 Q_DISABLE_COPY_MOVE(QOpenGLEngineSharedShaders)
225public:
226
227 enum SnippetName {
228 MainVertexShader,
229 MainWithTexCoordsVertexShader,
230 MainWithTexCoordsAndOpacityVertexShader,
231
232 // UntransformedPositionVertexShader must be first in the list:
233 UntransformedPositionVertexShader,
234 PositionOnlyVertexShader,
235 ComplexGeometryPositionOnlyVertexShader,
236 PositionWithPatternBrushVertexShader,
237 PositionWithLinearGradientBrushVertexShader,
238 PositionWithConicalGradientBrushVertexShader,
239 PositionWithRadialGradientBrushVertexShader,
240 PositionWithTextureBrushVertexShader,
241 AffinePositionWithPatternBrushVertexShader,
242 AffinePositionWithLinearGradientBrushVertexShader,
243 AffinePositionWithConicalGradientBrushVertexShader,
244 AffinePositionWithRadialGradientBrushVertexShader,
245 AffinePositionWithTextureBrushVertexShader,
246
247 // MainFragmentShader_CMO must be first in the list:
248 MainFragmentShader_MO,
249 MainFragmentShader_M,
250 MainFragmentShader_O,
251 MainFragmentShader,
252 MainFragmentShader_ImageArrays,
253
254 // ImageSrcFragmentShader must be first in the list::
255 ImageSrcFragmentShader,
256 ImageSrcWithPatternFragmentShader,
257 NonPremultipliedImageSrcFragmentShader,
258 GrayscaleImageSrcFragmentShader,
259 AlphaImageSrcFragmentShader,
260 CustomImageSrcFragmentShader,
261 SolidBrushSrcFragmentShader,
262 TextureBrushSrcFragmentShader,
263 TextureBrushSrcWithPatternFragmentShader,
264 PatternBrushSrcFragmentShader,
265 LinearGradientBrushSrcFragmentShader,
266 RadialGradientBrushSrcFragmentShader,
267 ConicalGradientBrushSrcFragmentShader,
268 ShockingPinkSrcFragmentShader,
269
270 // NoMaskFragmentShader must be first in the list:
271 NoMaskFragmentShader,
272 MaskFragmentShader,
273 RgbMaskFragmentShaderPass1,
274 RgbMaskFragmentShaderPass2,
275 RgbMaskWithGammaFragmentShader,
276
277 // NoCompositionModeFragmentShader must be first in the list:
278 NoCompositionModeFragmentShader,
279 MultiplyCompositionModeFragmentShader,
280 ScreenCompositionModeFragmentShader,
281 OverlayCompositionModeFragmentShader,
282 DarkenCompositionModeFragmentShader,
283 LightenCompositionModeFragmentShader,
284 ColorDodgeCompositionModeFragmentShader,
285 ColorBurnCompositionModeFragmentShader,
286 HardLightCompositionModeFragmentShader,
287 SoftLightCompositionModeFragmentShader,
288 DifferenceCompositionModeFragmentShader,
289 ExclusionCompositionModeFragmentShader,
290
291 TotalSnippetCount, InvalidSnippetName
292 };
293#if defined (QT_DEBUG)
294 Q_ENUM(SnippetName)
295 static QByteArray snippetNameStr(SnippetName snippetName);
296#endif
297
298/*
299 // These allow the ShaderName enum to be used as a cache key
300 const int mainVertexOffset = 0;
301 const int positionVertexOffset = (1<<2) - PositionOnlyVertexShader;
302 const int mainFragOffset = (1<<6) - MainFragmentShader_CMO;
303 const int srcPixelOffset = (1<<10) - ImageSrcFragmentShader;
304 const int maskOffset = (1<<14) - NoMaskShader;
305 const int compositionOffset = (1 << 16) - MultiplyCompositionModeFragmentShader;
306*/
307
308 QOpenGLEngineSharedShaders(QOpenGLContext *context);
309 ~QOpenGLEngineSharedShaders();
310
311 QOpenGLShaderProgram *simpleProgram() { return simpleShaderProg; }
312 QOpenGLShaderProgram *blitProgram() { return blitShaderProg; }
313 // Compile the program if it's not already in the cache, return the item in the cache.
314 QOpenGLEngineShaderProg *findProgramInCache(const QOpenGLEngineShaderProg &prog);
315 // Compile the custom shader if it's not already in the cache, return the item in the cache.
316
317 static QOpenGLEngineSharedShaders *shadersForContext(QOpenGLContext *context);
318
319 // Ideally, this would be static and cleanup all programs in all contexts which
320 // contain the custom code. Currently it is just a hint and we rely on deleted
321 // custom shaders being cleaned up by being kicked out of the cache when it's
322 // full.
323 void cleanupCustomStage(QOpenGLCustomShaderStage* stage);
324
325private:
326 QOpenGLShaderProgram *blitShaderProg;
327 QOpenGLShaderProgram *simpleShaderProg;
328 QList<QOpenGLEngineShaderProg*> cachedPrograms;
329
330 static const char* qShaderSnippets[TotalSnippetCount];
331};
332
333
335{
336public:
338
340 if (program)
341 delete program;
342 }
343
350
351 QByteArray customStageSource; //TODO: Decent cache key for custom stages
353
355
359
360 bool operator==(const QOpenGLEngineShaderProg& other) const {
361 // We don't care about the program
362 return ( mainVertexShader == other.mainVertexShader &&
363 positionVertexShader == other.positionVertexShader &&
364 mainFragShader == other.mainFragShader &&
365 srcPixelFragShader == other.srcPixelFragShader &&
366 maskFragShader == other.maskFragShader &&
367 compositionFragShader == other.compositionFragShader &&
368 customStageSource == other.customStageSource
369 );
370 }
371};
372
373class Q_OPENGL_EXPORT QOpenGLEngineShaderManager : public QObject
374{
375 Q_OBJECT
376public:
377 QOpenGLEngineShaderManager(QOpenGLContext* context);
378 ~QOpenGLEngineShaderManager();
379
380 enum MaskType {NoMask, PixelMask, SubPixelMaskPass1, SubPixelMaskPass2, SubPixelWithGammaMask};
381 enum PixelSrcType {
382 ImageSrc = Qt::TexturePattern+1,
383 NonPremultipliedImageSrc = Qt::TexturePattern+2,
384 PatternSrc = Qt::TexturePattern+3,
385 TextureSrcWithPattern = Qt::TexturePattern+4,
386 GrayscaleImageSrc = Qt::TexturePattern+5,
387 AlphaImageSrc = Qt::TexturePattern+6,
388 };
389
390 enum Uniform {
391 ImageTexture,
392 PatternColor,
393 GlobalOpacity,
394 Depth,
395 MaskTexture,
396 FragmentColor,
397 LinearData,
398 Angle,
399 HalfViewportSize,
400 Fmp,
401 Fmp2MRadius2,
402 Inverse2Fmp2MRadius2,
403 SqrFr,
404 BRadius,
405 InvertedTextureSize,
406 BrushTransform,
407 BrushTexture,
408 Matrix,
409 NumUniforms
410 };
411
412 enum OpacityMode {
413 NoOpacity,
414 UniformOpacity,
415 AttributeOpacity
416 };
417
418 // There are optimizations we can do, depending on the brush transform:
419 // 1) May not have to apply perspective-correction
420 // 2) Can use lower precision for matrix
421 void optimiseForBrushTransform(QTransform::TransformationType transformType);
422 void setSrcPixelType(Qt::BrushStyle);
423 void setSrcPixelType(PixelSrcType); // For non-brush sources, like pixmaps & images
424 void setOpacityMode(OpacityMode);
425 void setMaskType(MaskType);
426 void setCompositionMode(QPainter::CompositionMode);
427 void setCustomStage(QOpenGLCustomShaderStage* stage);
428 void removeCustomStage();
429
430 GLuint getUniformLocation(Uniform id);
431
432 void setDirty(); // someone has manually changed the current shader program
433 bool useCorrectShaderProg(); // returns true if the shader program needed to be changed
434
435 void useSimpleProgram();
436 void useBlitProgram();
437 void setHasComplexGeometry(bool hasComplexGeometry)
438 {
439 complexGeometry = hasComplexGeometry;
440 shaderProgNeedsChanging = true;
441 }
442 bool hasComplexGeometry() const
443 {
444 return complexGeometry;
445 }
446
447 QOpenGLShaderProgram* currentProgram(); // Returns pointer to the shader the manager has chosen
448 QOpenGLShaderProgram* simpleProgram(); // Used to draw into e.g. stencil buffers
449 QOpenGLShaderProgram* blitProgram(); // Used to blit a texture into the framebuffer
450
451 QOpenGLEngineSharedShaders* sharedShaders;
452
453private:
454 QOpenGLContext* ctx;
455 bool shaderProgNeedsChanging;
456 bool complexGeometry;
457
458 // Current state variables which influence the choice of shader:
459 QTransform brushTransform;
460 int srcPixelType;
461 OpacityMode opacityMode;
462 MaskType maskType;
463 QPainter::CompositionMode compositionMode;
464 QOpenGLCustomShaderStage* customSrcStage;
465
466 QOpenGLEngineShaderProg* currentShaderProg;
467};
468
469QT_END_NAMESPACE
470
471#endif //QOPENGLENGINE_SHADER_MANAGER_H
QPointer< QOpenGLEngineShaderManager > m_manager
virtual void setUniforms(QOpenGLShaderProgram *)
bool operator==(const QOpenGLEngineShaderProg &other) const
friend class QPainter
static const GLuint QT_TEXTURE_COORDS_ATTR
static const GLuint QT_PMV_MATRIX_2_ATTR
static const GLuint QT_OPACITY_ATTR
static const GLuint QT_PMV_MATRIX_1_ATTR
static QT_BEGIN_NAMESPACE const GLuint QT_VERTEX_COORDS_ATTR
static const GLuint QT_PMV_MATRIX_3_ATTR