forked from qt/qtbase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqopenglpaintengine.cpp
2709 lines (2215 loc) · 102 KB
/
qopenglpaintengine.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtOpenGL module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
/*
When the active program changes, we need to update it's uniforms.
We could track state for each program and only update stale uniforms
- Could lead to lots of overhead if there's a lot of programs
We could update all the uniforms when the program changes
- Could end up updating lots of uniforms which don't need updating
Updating uniforms should be cheap, so the overhead of updating up-to-date
uniforms should be minimal. It's also less complex.
Things which _may_ cause a different program to be used:
- Change in brush/pen style
- Change in painter opacity
- Change in composition mode
Whenever we set a mode on the shader manager - it needs to tell us if it had
to switch to a different program.
The shader manager should only switch when we tell it to. E.g. if we set a new
brush style and then switch to transparent painter, we only want it to compile
and use the correct program when we really need it.
*/
// #define QT_OPENGL_CACHE_AS_VBOS
#include <private/qopenglgradientcache_p.h>
#include <private/qopengltexturecache_p.h>
#include "qopenglpaintengine_p.h"
#include "qopenglpaintdevice_p.h"
#include <string.h> //for memcpy
#include <qmath.h>
#include <private/qopengl_p.h>
#include <private/qopenglcontext_p.h>
#include <private/qopenglextensions_p.h>
#include <private/qpaintengineex_p.h>
#include <QPaintEngine>
#include <private/qpainter_p.h>
#include <private/qfontengine_p.h>
#include <private/qdatabuffer_p.h>
#include <private/qstatictext_p.h>
#include <private/qtriangulator_p.h>
#include <private/qopenglengineshadermanager_p.h>
#include <private/qopengl2pexvertexarray_p.h>
#include <private/qopengltextureglyphcache_p.h>
#include <QDebug>
#include <qtopengl_tracepoints_p.h>
#ifndef GL_KHR_blend_equation_advanced
#define GL_KHR_blend_equation_advanced 1
#define GL_MULTIPLY_KHR 0x9294
#define GL_SCREEN_KHR 0x9295
#define GL_OVERLAY_KHR 0x9296
#define GL_DARKEN_KHR 0x9297
#define GL_LIGHTEN_KHR 0x9298
#define GL_COLORDODGE_KHR 0x9299
#define GL_COLORBURN_KHR 0x929A
#define GL_HARDLIGHT_KHR 0x929B
#define GL_SOFTLIGHT_KHR 0x929C
#define GL_DIFFERENCE_KHR 0x929E
#define GL_EXCLUSION_KHR 0x92A0
#endif /* GL_KHR_blend_equation_advanced */
#ifndef GL_KHR_blend_equation_advanced_coherent
#define GL_KHR_blend_equation_advanced_coherent 1
#define GL_BLEND_ADVANCED_COHERENT_KHR 0x9285
#endif /* GL_KHR_blend_equation_advanced_coherent */
QT_BEGIN_NAMESPACE
Q_OPENGL_EXPORT QImage qt_imageForBrush(int brushStyle, bool invert);
////////////////////////////////// Private Methods //////////////////////////////////////////
QOpenGL2PaintEngineExPrivate::~QOpenGL2PaintEngineExPrivate()
{
delete shaderManager;
vertexBuffer.destroy();
texCoordBuffer.destroy();
opacityBuffer.destroy();
indexBuffer.destroy();
vao.destroy();
if (elementIndicesVBOId != 0) {
funcs.glDeleteBuffers(1, &elementIndicesVBOId);
elementIndicesVBOId = 0;
}
}
inline QColor qt_premultiplyColor(QColor c, GLfloat opacity)
{
qreal alpha = c.alphaF() * opacity;
c.setAlphaF(alpha);
c.setRedF(c.redF() * alpha);
c.setGreenF(c.greenF() * alpha);
c.setBlueF(c.blueF() * alpha);
return c;
}
void QOpenGL2PaintEngineExPrivate::setBrush(const QBrush& brush)
{
if (qbrush_fast_equals(currentBrush, brush))
return;
const Qt::BrushStyle newStyle = qbrush_style(brush);
Q_ASSERT(newStyle != Qt::NoBrush);
currentBrush = brush;
if (!currentBrushImage.isNull())
currentBrushImage = QImage();
brushUniformsDirty = true; // All brushes have at least one uniform
if (newStyle > Qt::SolidPattern)
brushTextureDirty = true;
if (currentBrush.style() == Qt::TexturePattern
&& qHasPixmapTexture(brush) && brush.texture().isQBitmap())
{
shaderManager->setSrcPixelType(QOpenGLEngineShaderManager::TextureSrcWithPattern);
} else {
shaderManager->setSrcPixelType(newStyle);
}
shaderManager->optimiseForBrushTransform(currentBrush.transform().type());
}
void QOpenGL2PaintEngineExPrivate::useSimpleShader()
{
shaderManager->useSimpleProgram();
if (matrixDirty)
updateMatrix();
}
/*
Single entry-point for activating, binding, and setting properties.
Allows keeping track of (caching) the latest texture unit and bound
texture in a central place, so that we can skip re-binding unless
needed.
\note Any code or Qt API that internally activates or binds will
not affect the cache used by this function, which means they will
lead to inconsisent state. QPainter::beginNativePainting() takes
care of resetting the cache, so for user–code this is fine, but
internally in the paint engine care must be taken to not call
functions that may activate or bind under our feet.
*/
template<typename T>
void QOpenGL2PaintEngineExPrivate::updateTexture(GLenum textureUnit, const T &texture, GLenum wrapMode, GLenum filterMode, TextureUpdateMode updateMode)
{
static const GLenum target = GL_TEXTURE_2D;
activateTextureUnit(textureUnit);
GLuint textureId = bindTexture(texture);
if (updateMode == UpdateIfNeeded && textureId == lastTextureUsed)
return;
lastTextureUsed = textureId;
funcs.glTexParameteri(target, GL_TEXTURE_WRAP_S, wrapMode);
funcs.glTexParameteri(target, GL_TEXTURE_WRAP_T, wrapMode);
funcs.glTexParameteri(target, GL_TEXTURE_MAG_FILTER, filterMode);
funcs.glTexParameteri(target, GL_TEXTURE_MIN_FILTER, filterMode);
}
void QOpenGL2PaintEngineExPrivate::activateTextureUnit(GLenum textureUnit)
{
if (textureUnit != lastTextureUnitUsed) {
funcs.glActiveTexture(GL_TEXTURE0 + textureUnit);
lastTextureUnitUsed = textureUnit;
// We simplify things by keeping a single cached value of the last
// texture that was bound, instead of one per texture unit. This
// means that switching texture units could potentially mean we
// need a re-bind and corresponding parameter updates.
lastTextureUsed = GLuint(-1);
}
}
template<>
GLuint QOpenGL2PaintEngineExPrivate::bindTexture(const GLuint &textureId)
{
if (textureId != lastTextureUsed)
funcs.glBindTexture(GL_TEXTURE_2D, textureId);
return textureId;
}
template<>
GLuint QOpenGL2PaintEngineExPrivate::bindTexture(const QImage &image)
{
return QOpenGLTextureCache::cacheForContext(ctx)->bindTexture(ctx, image);
}
template<>
GLuint QOpenGL2PaintEngineExPrivate::bindTexture(const QPixmap &pixmap)
{
return QOpenGLTextureCache::cacheForContext(ctx)->bindTexture(ctx, pixmap);
}
template<>
GLuint QOpenGL2PaintEngineExPrivate::bindTexture(const QGradient &gradient)
{
// We apply global opacity in the fragment shaders, so we always pass 1.0
// for opacity to the cache.
GLuint textureId = QOpenGL2GradientCache::cacheForContext(ctx)->getBuffer(gradient, 1.0);
// QOpenGL2GradientCache::getBuffer() may bind and generate a new texture if it
// hasn't been cached yet, but will otherwise return an unbound texture id. To
// be sure that the texture is bound, we unfortunately have to bind again,
// which results in the initial generation of the texture doing two binds.
return bindTexture(textureId);
}
struct ImageWithBindOptions
{
const QImage ℑ
QOpenGLTextureUploader::BindOptions options;
};
template<>
GLuint QOpenGL2PaintEngineExPrivate::bindTexture(const ImageWithBindOptions &imageWithOptions)
{
return QOpenGLTextureCache::cacheForContext(ctx)->bindTexture(ctx, imageWithOptions.image, imageWithOptions.options);
}
inline static bool isPowerOfTwo(int x)
{
// Assumption: x >= 1
return x == (x & -x);
}
void QOpenGL2PaintEngineExPrivate::updateBrushTexture()
{
Q_Q(QOpenGL2PaintEngineEx);
// qDebug("QOpenGL2PaintEngineExPrivate::updateBrushTexture()");
Qt::BrushStyle style = currentBrush.style();
bool smoothPixmapTransform = q->state()->renderHints & QPainter::SmoothPixmapTransform;
GLenum filterMode = smoothPixmapTransform ? GL_LINEAR : GL_NEAREST;
if ( (style >= Qt::Dense1Pattern) && (style <= Qt::DiagCrossPattern) ) {
// Get the image data for the pattern
QImage textureImage = qt_imageForBrush(style, false);
updateTexture(QT_BRUSH_TEXTURE_UNIT, textureImage, GL_REPEAT, filterMode, ForceUpdate);
}
else if (style >= Qt::LinearGradientPattern && style <= Qt::ConicalGradientPattern) {
// Gradiant brush: All the gradiants use the same texture
const QGradient *gradient = currentBrush.gradient();
GLenum wrapMode = GL_CLAMP_TO_EDGE;
if (gradient->spread() == QGradient::RepeatSpread || gradient->type() == QGradient::ConicalGradient)
wrapMode = GL_REPEAT;
else if (gradient->spread() == QGradient::ReflectSpread)
wrapMode = GL_MIRRORED_REPEAT;
updateTexture(QT_BRUSH_TEXTURE_UNIT, *gradient, wrapMode, filterMode, ForceUpdate);
}
else if (style == Qt::TexturePattern) {
currentBrushImage = currentBrush.textureImage();
int max_texture_size = ctx->d_func()->maxTextureSize();
QSize newSize = currentBrushImage.size();
newSize = newSize.boundedTo(QSize(max_texture_size, max_texture_size));
if (!QOpenGLContext::currentContext()->functions()->hasOpenGLFeature(QOpenGLFunctions::NPOTTextureRepeat)) {
if (!isPowerOfTwo(newSize.width()) || !isPowerOfTwo(newSize.height())) {
newSize.setHeight(qNextPowerOfTwo(newSize.height() - 1));
newSize.setWidth(qNextPowerOfTwo(newSize.width() - 1));
}
}
if (currentBrushImage.size() != newSize)
currentBrushImage = currentBrushImage.scaled(newSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
GLuint wrapMode = GL_REPEAT;
updateTexture(QT_BRUSH_TEXTURE_UNIT, currentBrushImage, wrapMode, filterMode, ForceUpdate);
}
brushTextureDirty = false;
}
void QOpenGL2PaintEngineExPrivate::updateBrushUniforms()
{
// qDebug("QOpenGL2PaintEngineExPrivate::updateBrushUniforms()");
Qt::BrushStyle style = currentBrush.style();
if (style == Qt::NoBrush)
return;
QTransform brushQTransform = currentBrush.transform();
if (style == Qt::SolidPattern) {
QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::FragmentColor), col);
}
else {
// All other brushes have a transform and thus need the translation point:
QPointF translationPoint;
if (style <= Qt::DiagCrossPattern) {
QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::PatternColor), col);
QVector2D halfViewportSize(width*0.5, height*0.5);
shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
}
else if (style == Qt::LinearGradientPattern) {
const QLinearGradient *g = static_cast<const QLinearGradient *>(currentBrush.gradient());
QPointF realStart = g->start();
QPointF realFinal = g->finalStop();
translationPoint = realStart;
QPointF l = realFinal - realStart;
QVector3D linearData(
l.x(),
l.y(),
1.0f / (l.x() * l.x() + l.y() * l.y())
);
shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::LinearData), linearData);
QVector2D halfViewportSize(width*0.5, height*0.5);
shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
}
else if (style == Qt::ConicalGradientPattern) {
const QConicalGradient *g = static_cast<const QConicalGradient *>(currentBrush.gradient());
translationPoint = g->center();
GLfloat angle = -qDegreesToRadians(g->angle());
shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Angle), angle);
QVector2D halfViewportSize(width*0.5, height*0.5);
shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
}
else if (style == Qt::RadialGradientPattern) {
const QRadialGradient *g = static_cast<const QRadialGradient *>(currentBrush.gradient());
QPointF realCenter = g->center();
QPointF realFocal = g->focalPoint();
qreal realRadius = g->centerRadius() - g->focalRadius();
translationPoint = realFocal;
QPointF fmp = realCenter - realFocal;
shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Fmp), fmp);
GLfloat fmp2_m_radius2 = -fmp.x() * fmp.x() - fmp.y() * fmp.y() + realRadius*realRadius;
shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Fmp2MRadius2), fmp2_m_radius2);
shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Inverse2Fmp2MRadius2),
GLfloat(1.0 / (2.0*fmp2_m_radius2)));
shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::SqrFr),
GLfloat(g->focalRadius() * g->focalRadius()));
shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::BRadius),
GLfloat(2 * (g->centerRadius() - g->focalRadius()) * g->focalRadius()),
g->focalRadius(),
g->centerRadius() - g->focalRadius());
QVector2D halfViewportSize(width*0.5, height*0.5);
shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
}
else if (style == Qt::TexturePattern) {
const QPixmap& texPixmap = currentBrush.texture();
if (qHasPixmapTexture(currentBrush) && currentBrush.texture().isQBitmap()) {
QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::PatternColor), col);
}
QSizeF invertedTextureSize(1.0 / texPixmap.width(), 1.0 / texPixmap.height());
shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::InvertedTextureSize), invertedTextureSize);
QVector2D halfViewportSize(width*0.5, height*0.5);
shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
}
else
qWarning("QOpenGL2PaintEngineEx: Unimplemented fill style");
const QPointF &brushOrigin = q->state()->brushOrigin;
QTransform matrix = q->state()->matrix;
matrix.translate(brushOrigin.x(), brushOrigin.y());
QTransform translate(1, 0, 0, 1, -translationPoint.x(), -translationPoint.y());
qreal m22 = -1;
qreal dy = height;
if (device->paintFlipped()) {
m22 = 1;
dy = 0;
}
QTransform gl_to_qt(1, 0, 0, m22, 0, dy);
QTransform inv_matrix = gl_to_qt * (brushQTransform * matrix).inverted() * translate;
shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::BrushTransform), inv_matrix);
shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::BrushTexture), QT_BRUSH_TEXTURE_UNIT);
}
brushUniformsDirty = false;
}
// This assumes the shader manager has already setup the correct shader program
void QOpenGL2PaintEngineExPrivate::updateMatrix()
{
// qDebug("QOpenGL2PaintEngineExPrivate::updateMatrix()");
const QTransform& transform = q->state()->matrix;
// The projection matrix converts from Qt's coordinate system to GL's coordinate system
// * GL's viewport is 2x2, Qt's is width x height
// * GL has +y -> -y going from bottom -> top, Qt is the other way round
// * GL has [0,0] in the center, Qt has it in the top-left
//
// This results in the Projection matrix below, which is multiplied by the painter's
// transformation matrix, as shown below:
//
// Projection Matrix Painter Transform
// ------------------------------------------------ ------------------------
// | 2.0 / width | 0.0 | -1.0 | | m11 | m21 | dx |
// | 0.0 | -2.0 / height | 1.0 | * | m12 | m22 | dy |
// | 0.0 | 0.0 | 1.0 | | m13 | m23 | m33 |
// ------------------------------------------------ ------------------------
//
// NOTE: The resultant matrix is also transposed, as GL expects column-major matracies
const GLfloat wfactor = 2.0f / width;
GLfloat hfactor = -2.0f / height;
GLfloat dx = transform.dx();
GLfloat dy = transform.dy();
if (device->paintFlipped()) {
hfactor *= -1;
dy -= height;
}
// Non-integer translates can have strange effects for some rendering operations such as
// anti-aliased text rendering. In such cases, we snap the translate to the pixel grid.
if (snapToPixelGrid && transform.type() == QTransform::TxTranslate) {
// 0.50 needs to rounded down to 0.0 for consistency with raster engine:
dx = std::ceil(dx - 0.5f);
dy = std::ceil(dy - 0.5f);
}
pmvMatrix[0][0] = (wfactor * transform.m11()) - transform.m13();
pmvMatrix[1][0] = (wfactor * transform.m21()) - transform.m23();
pmvMatrix[2][0] = (wfactor * dx) - transform.m33();
pmvMatrix[0][1] = (hfactor * transform.m12()) + transform.m13();
pmvMatrix[1][1] = (hfactor * transform.m22()) + transform.m23();
pmvMatrix[2][1] = (hfactor * dy) + transform.m33();
pmvMatrix[0][2] = transform.m13();
pmvMatrix[1][2] = transform.m23();
pmvMatrix[2][2] = transform.m33();
// 1/10000 == 0.0001, so we have good enough res to cover curves
// that span the entire widget...
inverseScale = qMax(1 / qMax( qMax(qAbs(transform.m11()), qAbs(transform.m22())),
qMax(qAbs(transform.m12()), qAbs(transform.m21())) ),
qreal(0.0001));
matrixDirty = false;
matrixUniformDirty = true;
// Set the PMV matrix attribute. As we use an attributes rather than uniforms, we only
// need to do this once for every matrix change and persists across all shader programs.
funcs.glVertexAttrib3fv(QT_PMV_MATRIX_1_ATTR, pmvMatrix[0]);
funcs.glVertexAttrib3fv(QT_PMV_MATRIX_2_ATTR, pmvMatrix[1]);
funcs.glVertexAttrib3fv(QT_PMV_MATRIX_3_ATTR, pmvMatrix[2]);
dasher.setInvScale(inverseScale);
stroker.setInvScale(inverseScale);
}
void QOpenGL2PaintEngineExPrivate::updateCompositionMode()
{
// NOTE: The entire paint engine works on pre-multiplied data - which is why some of these
// composition modes look odd.
// qDebug() << "QOpenGL2PaintEngineExPrivate::updateCompositionMode() - Setting GL composition mode for " << q->state()->composition_mode;
if (ctx->functions()->hasOpenGLFeature(QOpenGLFunctions::BlendEquationAdvanced)) {
if (q->state()->composition_mode <= QPainter::CompositionMode_Plus) {
funcs.glDisable(GL_BLEND_ADVANCED_COHERENT_KHR);
funcs.glBlendEquation(GL_FUNC_ADD);
} else {
funcs.glEnable(GL_BLEND_ADVANCED_COHERENT_KHR);
}
shaderManager->setCompositionMode(q->state()->composition_mode);
} else {
if (q->state()->composition_mode > QPainter::CompositionMode_Plus) {
qWarning("Unsupported composition mode");
compositionModeDirty = false;
return;
}
}
switch(q->state()->composition_mode) {
case QPainter::CompositionMode_SourceOver:
funcs.glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
break;
case QPainter::CompositionMode_DestinationOver:
funcs.glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE);
break;
case QPainter::CompositionMode_Clear:
funcs.glBlendFunc(GL_ZERO, GL_ZERO);
break;
case QPainter::CompositionMode_Source:
funcs.glBlendFunc(GL_ONE, GL_ZERO);
break;
case QPainter::CompositionMode_Destination:
funcs.glBlendFunc(GL_ZERO, GL_ONE);
break;
case QPainter::CompositionMode_SourceIn:
funcs.glBlendFunc(GL_DST_ALPHA, GL_ZERO);
break;
case QPainter::CompositionMode_DestinationIn:
funcs.glBlendFunc(GL_ZERO, GL_SRC_ALPHA);
break;
case QPainter::CompositionMode_SourceOut:
funcs.glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ZERO);
break;
case QPainter::CompositionMode_DestinationOut:
funcs.glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_ALPHA);
break;
case QPainter::CompositionMode_SourceAtop:
funcs.glBlendFunc(GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
break;
case QPainter::CompositionMode_DestinationAtop:
funcs.glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA);
break;
case QPainter::CompositionMode_Xor:
funcs.glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
break;
case QPainter::CompositionMode_Plus:
funcs.glBlendFunc(GL_ONE, GL_ONE);
break;
case QPainter::CompositionMode_Multiply:
funcs.glBlendEquation(GL_MULTIPLY_KHR);
break;
case QPainter::CompositionMode_Screen:
funcs.glBlendEquation(GL_SCREEN_KHR);
break;
case QPainter::CompositionMode_Overlay:
funcs.glBlendEquation(GL_OVERLAY_KHR);
break;
case QPainter::CompositionMode_Darken:
funcs.glBlendEquation(GL_DARKEN_KHR);
break;
case QPainter::CompositionMode_Lighten:
funcs.glBlendEquation(GL_LIGHTEN_KHR);
break;
case QPainter::CompositionMode_ColorDodge:
funcs.glBlendEquation(GL_COLORDODGE_KHR);
break;
case QPainter::CompositionMode_ColorBurn:
funcs.glBlendEquation(GL_COLORBURN_KHR);
break;
case QPainter::CompositionMode_HardLight:
funcs.glBlendEquation(GL_HARDLIGHT_KHR);
break;
case QPainter::CompositionMode_SoftLight:
funcs.glBlendEquation(GL_SOFTLIGHT_KHR);
break;
case QPainter::CompositionMode_Difference:
funcs.glBlendEquation(GL_DIFFERENCE_KHR);
break;
case QPainter::CompositionMode_Exclusion:
funcs.glBlendEquation(GL_EXCLUSION_KHR);
break;
default:
qWarning("Unsupported composition mode");
break;
}
compositionModeDirty = false;
}
static inline void setCoords(GLfloat *coords, const QOpenGLRect &rect)
{
coords[0] = rect.left;
coords[1] = rect.top;
coords[2] = rect.right;
coords[3] = rect.top;
coords[4] = rect.right;
coords[5] = rect.bottom;
coords[6] = rect.left;
coords[7] = rect.bottom;
}
void QOpenGL2PaintEngineExPrivate::drawTexture(const QOpenGLRect& dest, const QOpenGLRect& src, const QSize &textureSize, bool opaque, bool pattern)
{
Q_TRACE_SCOPE(QOpenGL2PaintEngineExPrivate_drawTexture, dest, src, textureSize, opaque, pattern);
// Setup for texture drawing
currentBrush = noBrush;
if (snapToPixelGrid) {
snapToPixelGrid = false;
matrixDirty = true;
}
if (prepareForDraw(opaque))
shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::ImageTexture), QT_IMAGE_TEXTURE_UNIT);
if (pattern) {
QColor col = qt_premultiplyColor(q->state()->pen.color(), (GLfloat)q->state()->opacity);
shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::PatternColor), col);
}
GLfloat dx = 1.0 / textureSize.width();
GLfloat dy = 1.0 / textureSize.height();
QOpenGLRect srcTextureRect(src.left*dx, src.top*dy, src.right*dx, src.bottom*dy);
setCoords(staticVertexCoordinateArray, dest);
setCoords(staticTextureCoordinateArray, srcTextureRect);
setVertexAttribArrayEnabled(QT_VERTEX_COORDS_ATTR, true);
setVertexAttribArrayEnabled(QT_TEXTURE_COORDS_ATTR, true);
uploadData(QT_VERTEX_COORDS_ATTR, staticVertexCoordinateArray, 8);
uploadData(QT_TEXTURE_COORDS_ATTR, staticTextureCoordinateArray, 8);
funcs.glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
}
void QOpenGL2PaintEngineEx::beginNativePainting()
{
Q_D(QOpenGL2PaintEngineEx);
ensureActive();
d->transferMode(BrushDrawingMode);
d->nativePaintingActive = true;
d->funcs.glUseProgram(0);
// Disable all the vertex attribute arrays:
for (int i = 0; i < QT_GL_VERTEX_ARRAY_TRACKED_COUNT; ++i)
d->funcs.glDisableVertexAttribArray(i);
#if !QT_CONFIG(opengles2) && !defined(QT_OPENGL_DYNAMIC)
Q_ASSERT(QOpenGLContext::currentContext());
const QOpenGLContext *ctx = d->ctx;
const QSurfaceFormat &fmt = d->device->context()->format();
if (fmt.majorVersion() < 3 || (fmt.majorVersion() == 3 && fmt.minorVersion() < 1)
|| (fmt.majorVersion() == 3 && fmt.minorVersion() == 1 && ctx->hasExtension(QByteArrayLiteral("GL_ARB_compatibility")))
|| fmt.profile() == QSurfaceFormat::CompatibilityProfile)
{
// be nice to people who mix OpenGL 1.x code with QPainter commands
// by setting modelview and projection matrices to mirror the GL 1
// paint engine
const QTransform& mtx = state()->matrix;
float mv_matrix[4][4] =
{
{ float(mtx.m11()), float(mtx.m12()), 0, float(mtx.m13()) },
{ float(mtx.m21()), float(mtx.m22()), 0, float(mtx.m23()) },
{ 0, 0, 1, 0 },
{ float(mtx.dx()), float(mtx.dy()), 0, float(mtx.m33()) }
};
const QSize sz = d->device->size();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, sz.width(), sz.height(), 0, -999999, 999999);
glMatrixMode(GL_MODELVIEW);
glLoadMatrixf(&mv_matrix[0][0]);
}
#endif // !QT_CONFIG(opengles2)
d->resetGLState();
// We don't know what texture units and textures the native painting
// will activate and bind, so we can't assume anything when we return
// from the native painting.
d->lastTextureUnitUsed = QT_UNKNOWN_TEXTURE_UNIT;
d->lastTextureUsed = GLuint(-1);
d->dirtyStencilRegion = QRect(0, 0, d->width, d->height);
d->shaderManager->setDirty();
d->needsSync = true;
}
void QOpenGL2PaintEngineExPrivate::resetGLState()
{
activateTextureUnit(QT_DEFAULT_TEXTURE_UNIT);
funcs.glDisable(GL_BLEND);
funcs.glDisable(GL_STENCIL_TEST);
funcs.glDisable(GL_DEPTH_TEST);
funcs.glDisable(GL_SCISSOR_TEST);
funcs.glDepthMask(true);
funcs.glDepthFunc(GL_LESS);
funcs.glClearDepthf(1);
funcs.glStencilMask(0xff);
funcs.glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
funcs.glStencilFunc(GL_ALWAYS, 0, 0xff);
setVertexAttribArrayEnabled(QT_TEXTURE_COORDS_ATTR, false);
setVertexAttribArrayEnabled(QT_VERTEX_COORDS_ATTR, false);
setVertexAttribArrayEnabled(QT_OPACITY_ATTR, false);
if (!QOpenGLContext::currentContext()->isOpenGLES()) {
// gl_Color, corresponding to vertex attribute 3, may have been changed
float color[] = { 1.0f, 1.0f, 1.0f, 1.0f };
funcs.glVertexAttrib4fv(3, color);
}
if (vao.isCreated()) {
vao.release();
funcs.glBindBuffer(GL_ARRAY_BUFFER, 0);
funcs.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
}
void QOpenGL2PaintEngineEx::endNativePainting()
{
Q_D(QOpenGL2PaintEngineEx);
d->needsSync = true;
d->nativePaintingActive = false;
}
void QOpenGL2PaintEngineEx::invalidateState()
{
Q_D(QOpenGL2PaintEngineEx);
d->needsSync = true;
}
bool QOpenGL2PaintEngineEx::isNativePaintingActive() const {
Q_D(const QOpenGL2PaintEngineEx);
return d->nativePaintingActive;
}
void QOpenGL2PaintEngineExPrivate::transferMode(EngineMode newMode)
{
if (newMode == mode)
return;
if (newMode == TextDrawingMode) {
shaderManager->setHasComplexGeometry(true);
} else {
shaderManager->setHasComplexGeometry(false);
}
if (newMode == ImageDrawingMode) {
uploadData(QT_VERTEX_COORDS_ATTR, staticVertexCoordinateArray, 8);
uploadData(QT_TEXTURE_COORDS_ATTR, staticTextureCoordinateArray, 8);
}
if (newMode == ImageArrayDrawingMode || newMode == ImageOpacityArrayDrawingMode) {
uploadData(QT_VERTEX_COORDS_ATTR, (GLfloat*)vertexCoordinateArray.data(), vertexCoordinateArray.vertexCount() * 2);
uploadData(QT_TEXTURE_COORDS_ATTR, (GLfloat*)textureCoordinateArray.data(), textureCoordinateArray.vertexCount() * 2);
if (newMode == ImageOpacityArrayDrawingMode)
uploadData(QT_OPACITY_ATTR, (GLfloat*)opacityArray.data(), opacityArray.size());
}
// This needs to change when we implement high-quality anti-aliasing...
if (newMode != TextDrawingMode)
shaderManager->setMaskType(QOpenGLEngineShaderManager::NoMask);
mode = newMode;
}
struct QOpenGL2PEVectorPathCache
{
#ifdef QT_OPENGL_CACHE_AS_VBOS
GLuint vbo;
GLuint ibo;
#else
float *vertices;
void *indices;
#endif
int vertexCount;
int indexCount;
GLenum primitiveType;
qreal iscale;
QVertexIndexVector::Type indexType;
};
void QOpenGL2PaintEngineExPrivate::cleanupVectorPath(QPaintEngineEx *engine, void *data)
{
QOpenGL2PEVectorPathCache *c = (QOpenGL2PEVectorPathCache *) data;
#ifdef QT_OPENGL_CACHE_AS_VBOS
Q_ASSERT(engine->type() == QPaintEngine::OpenGL2);
static_cast<QOpenGL2PaintEngineEx *>(engine)->d_func()->unusedVBOSToClean << c->vbo;
if (c->ibo)
d->unusedIBOSToClean << c->ibo;
#else
Q_UNUSED(engine);
free(c->vertices);
free(c->indices);
#endif
delete c;
}
// Assumes everything is configured for the brush you want to use
void QOpenGL2PaintEngineExPrivate::fill(const QVectorPath& path)
{
transferMode(BrushDrawingMode);
if (snapToPixelGrid) {
snapToPixelGrid = false;
matrixDirty = true;
}
// Might need to call updateMatrix to re-calculate inverseScale
if (matrixDirty)
updateMatrix();
const bool supportsElementIndexUint = funcs.hasOpenGLExtension(QOpenGLExtensions::ElementIndexUint);
const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
// Check to see if there's any hints
if (path.shape() == QVectorPath::RectangleHint) {
QOpenGLRect rect(points[0].x(), points[0].y(), points[2].x(), points[2].y());
prepareForDraw(currentBrush.isOpaque());
composite(rect);
} else if (path.isConvex()) {
if (path.isCacheable()) {
QVectorPath::CacheEntry *data = path.lookupCacheData(q);
QOpenGL2PEVectorPathCache *cache;
bool updateCache = false;
if (data) {
cache = (QOpenGL2PEVectorPathCache *) data->data;
// Check if scale factor is exceeded and regenerate if so...
qreal scaleFactor = cache->iscale / inverseScale;
if (scaleFactor < 0.5 || scaleFactor > 2.0) {
#ifdef QT_OPENGL_CACHE_AS_VBOS
glDeleteBuffers(1, &cache->vbo);
cache->vbo = 0;
Q_ASSERT(cache->ibo == 0);
#else
free(cache->vertices);
Q_ASSERT(cache->indices == nullptr);
#endif
updateCache = true;
}
} else {
cache = new QOpenGL2PEVectorPathCache;
data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
updateCache = true;
}
// Flatten the path at the current scale factor and fill it into the cache struct.
if (updateCache) {
vertexCoordinateArray.clear();
vertexCoordinateArray.addPath(path, inverseScale, false);
int vertexCount = vertexCoordinateArray.vertexCount();
int floatSizeInBytes = vertexCount * 2 * sizeof(float);
cache->vertexCount = vertexCount;
cache->indexCount = 0;
cache->primitiveType = GL_TRIANGLE_FAN;
cache->iscale = inverseScale;
#ifdef QT_OPENGL_CACHE_AS_VBOS
funcs.glGenBuffers(1, &cache->vbo);
funcs.glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
funcs.glBufferData(GL_ARRAY_BUFFER, floatSizeInBytes, vertexCoordinateArray.data(), GL_STATIC_DRAW);
cache->ibo = 0;
#else
cache->vertices = (float *) malloc(floatSizeInBytes);
memcpy(cache->vertices, vertexCoordinateArray.data(), floatSizeInBytes);
cache->indices = nullptr;
#endif
}
prepareForDraw(currentBrush.isOpaque());
#ifdef QT_OPENGL_CACHE_AS_VBOS
funcs.glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
uploadData(QT_VERTEX_COORD_ATTR, 0, cache->vertexCount);
setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, 0);
#else
uploadData(QT_VERTEX_COORDS_ATTR, cache->vertices, cache->vertexCount * 2);
#endif
funcs.glDrawArrays(cache->primitiveType, 0, cache->vertexCount);
} else {
// printf(" - Marking path as cachable...\n");
// Tag it for later so that if the same path is drawn twice, it is assumed to be static and thus cachable
path.makeCacheable();
vertexCoordinateArray.clear();
vertexCoordinateArray.addPath(path, inverseScale, false);
prepareForDraw(currentBrush.isOpaque());
drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN);
}
} else {
bool useCache = path.isCacheable();
if (useCache) {
QRectF bbox = path.controlPointRect();
// If the path doesn't fit within these limits, it is possible that the triangulation will fail.
useCache &= (bbox.left() > -0x8000 * inverseScale)
&& (bbox.right() < 0x8000 * inverseScale)
&& (bbox.top() > -0x8000 * inverseScale)
&& (bbox.bottom() < 0x8000 * inverseScale);
}
if (useCache) {
QVectorPath::CacheEntry *data = path.lookupCacheData(q);
QOpenGL2PEVectorPathCache *cache;
bool updateCache = false;
if (data) {
cache = (QOpenGL2PEVectorPathCache *) data->data;
// Check if scale factor is exceeded and regenerate if so...
qreal scaleFactor = cache->iscale / inverseScale;
if (scaleFactor < 0.5 || scaleFactor > 2.0) {
#ifdef QT_OPENGL_CACHE_AS_VBOS
glDeleteBuffers(1, &cache->vbo);
glDeleteBuffers(1, &cache->ibo);
#else
free(cache->vertices);
free(cache->indices);
#endif
updateCache = true;
}
} else {
cache = new QOpenGL2PEVectorPathCache;
data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
updateCache = true;
}
// Flatten the path at the current scale factor and fill it into the cache struct.
if (updateCache) {
QTriangleSet polys = qTriangulate(path, QTransform().scale(1 / inverseScale, 1 / inverseScale), 1, supportsElementIndexUint);
cache->vertexCount = polys.vertices.size() / 2;
cache->indexCount = polys.indices.size();
cache->primitiveType = GL_TRIANGLES;
cache->iscale = inverseScale;
cache->indexType = polys.indices.type();
#ifdef QT_OPENGL_CACHE_AS_VBOS
funcs.glGenBuffers(1, &cache->vbo);
funcs.glGenBuffers(1, &cache->ibo);
funcs.glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
funcs.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cache->ibo);
if (polys.indices.type() == QVertexIndexVector::UnsignedInt)
funcs.glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint32) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
else
funcs.glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint16) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
QVarLengthArray<float> vertices(polys.vertices.size());
for (int i = 0; i < polys.vertices.size(); ++i)
vertices[i] = float(inverseScale * polys.vertices.at(i));
funcs.glBufferData(GL_ARRAY_BUFFER, sizeof(float) * vertices.size(), vertices.data(), GL_STATIC_DRAW);
#else