Merge remote-tracking branch 'upstream/tags/v4.8.0-rc1' into experimental
[qt:android-lighthouse.git] / src / opengl / gl2paintengineex / qpaintengineex_opengl2.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
6 **
7 ** This file is part of the QtOpenGL module of the Qt Toolkit.
8 **
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 **
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 **
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
29 **
30 ** Other Usage
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 /*
43     When the active program changes, we need to update it's uniforms.
44     We could track state for each program and only update stale uniforms
45         - Could lead to lots of overhead if there's a lot of programs
46     We could update all the uniforms when the program changes
47         - Could end up updating lots of uniforms which don't need updating
48
49     Updating uniforms should be cheap, so the overhead of updating up-to-date
50     uniforms should be minimal. It's also less complex.
51
52     Things which _may_ cause a different program to be used:
53         - Change in brush/pen style
54         - Change in painter opacity
55         - Change in composition mode
56
57     Whenever we set a mode on the shader manager - it needs to tell us if it had
58     to switch to a different program.
59
60     The shader manager should only switch when we tell it to. E.g. if we set a new
61     brush style and then switch to transparent painter, we only want it to compile
62     and use the correct program when we really need it.
63 */
64
65 // #define QT_OPENGL_CACHE_AS_VBOS
66
67 #include "qglgradientcache_p.h"
68 #include "qpaintengineex_opengl2_p.h"
69
70 #include <string.h> //for memcpy
71 #include <qmath.h>
72
73 #include <private/qgl_p.h>
74 #include <private/qmath_p.h>
75 #include <private/qpaintengineex_p.h>
76 #include <QPaintEngine>
77 #include <private/qpainter_p.h>
78 #include <private/qfontengine_p.h>
79 #include <private/qpixmapdata_gl_p.h>
80 #include <private/qdatabuffer_p.h>
81 #include <private/qstatictext_p.h>
82 #include <private/qtriangulator_p.h>
83
84 #include "qglengineshadermanager_p.h"
85 #include "qgl2pexvertexarray_p.h"
86 #include "qtriangulatingstroker_p.h"
87 #include "qtextureglyphcache_gl_p.h"
88
89 #include <QDebug>
90
91 QT_BEGIN_NAMESPACE
92
93 inline static bool isPowerOfTwo(uint x)
94 {
95     return x && !(x & (x - 1));
96 }
97
98 #if defined(Q_WS_WIN)
99 extern Q_GUI_EXPORT bool qt_cleartype_enabled;
100 #endif
101
102 #ifdef Q_WS_MAC
103 extern bool qt_applefontsmoothing_enabled;
104 #endif
105
106 #if !defined(QT_MAX_CACHED_GLYPH_SIZE)
107 #  define QT_MAX_CACHED_GLYPH_SIZE 64
108 #endif
109
110 Q_GUI_EXPORT QImage qt_imageForBrush(int brushStyle, bool invert);
111
112 ////////////////////////////////// Private Methods //////////////////////////////////////////
113
114 QGL2PaintEngineExPrivate::~QGL2PaintEngineExPrivate()
115 {
116     delete shaderManager;
117
118     while (pathCaches.size()) {
119         QVectorPath::CacheEntry *e = *(pathCaches.constBegin());
120         e->cleanup(e->engine, e->data);
121         e->data = 0;
122         e->engine = 0;
123     }
124
125     if (elementIndicesVBOId != 0) {
126         glDeleteBuffers(1, &elementIndicesVBOId);
127         elementIndicesVBOId = 0;
128     }
129 }
130
131 void QGL2PaintEngineExPrivate::updateTextureFilter(GLenum target, GLenum wrapMode, bool smoothPixmapTransform, GLuint id)
132 {
133 //    glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT); //### Is it always this texture unit?
134     if (id != GLuint(-1) && id == lastTextureUsed)
135         return;
136
137     lastTextureUsed = id;
138
139     if (smoothPixmapTransform) {
140         glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
141         glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
142     } else {
143         glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
144         glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
145     }
146     glTexParameterf(target, GL_TEXTURE_WRAP_S, wrapMode);
147     glTexParameterf(target, GL_TEXTURE_WRAP_T, wrapMode);
148 }
149
150
151 inline QColor qt_premultiplyColor(QColor c, GLfloat opacity)
152 {
153     qreal alpha = c.alphaF() * opacity;
154     c.setAlphaF(alpha);
155     c.setRedF(c.redF() * alpha);
156     c.setGreenF(c.greenF() * alpha);
157     c.setBlueF(c.blueF() * alpha);
158     return c;
159 }
160
161
162 void QGL2PaintEngineExPrivate::setBrush(const QBrush& brush)
163 {
164     if (qbrush_fast_equals(currentBrush, brush))
165         return;
166
167     const Qt::BrushStyle newStyle = qbrush_style(brush);
168     Q_ASSERT(newStyle != Qt::NoBrush);
169
170     currentBrush = brush;
171     if (!currentBrushPixmap.isNull())
172         currentBrushPixmap = QPixmap();
173     brushUniformsDirty = true; // All brushes have at least one uniform
174
175     if (newStyle > Qt::SolidPattern)
176         brushTextureDirty = true;
177
178     if (currentBrush.style() == Qt::TexturePattern
179         && qHasPixmapTexture(brush) && brush.texture().isQBitmap())
180     {
181         shaderManager->setSrcPixelType(QGLEngineShaderManager::TextureSrcWithPattern);
182     } else {
183         shaderManager->setSrcPixelType(newStyle);
184     }
185     shaderManager->optimiseForBrushTransform(currentBrush.transform().type());
186 }
187
188
189 void QGL2PaintEngineExPrivate::useSimpleShader()
190 {
191     shaderManager->useSimpleProgram();
192
193     if (matrixDirty)
194         updateMatrix();
195 }
196
197 void QGL2PaintEngineExPrivate::updateBrushTexture()
198 {
199     Q_Q(QGL2PaintEngineEx);
200 //     qDebug("QGL2PaintEngineExPrivate::updateBrushTexture()");
201     Qt::BrushStyle style = currentBrush.style();
202
203     if ( (style >= Qt::Dense1Pattern) && (style <= Qt::DiagCrossPattern) ) {
204         // Get the image data for the pattern
205         QImage texImage = qt_imageForBrush(style, false);
206
207         glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
208         ctx->d_func()->bindTexture(texImage, GL_TEXTURE_2D, GL_RGBA, QGLContext::InternalBindOption);
209 #if !defined(QT_NO_DEBUG) && defined(QT_OPENGL_ES_2)
210         QGLFunctions funcs(QGLContext::currentContext());
211         bool npotSupported = funcs.hasOpenGLFeature(QGLFunctions::NPOTTextures);
212         bool isNpot = !isPowerOfTwo(texImage.size().width())
213             || !isPowerOfTwo(texImage.size().height());
214         if (isNpot && !npotSupported) {
215             qWarning("GL2 Paint Engine: This system does not support the REPEAT wrap mode for non-power-of-two textures.");
216         }
217 #endif
218         updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
219     }
220     else if (style >= Qt::LinearGradientPattern && style <= Qt::ConicalGradientPattern) {
221         // Gradiant brush: All the gradiants use the same texture
222
223         const QGradient* g = currentBrush.gradient();
224
225         // We apply global opacity in the fragment shaders, so we always pass 1.0
226         // for opacity to the cache.
227         GLuint texId = QGL2GradientCache::cacheForContext(ctx)->getBuffer(*g, 1.0);
228
229         glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
230         glBindTexture(GL_TEXTURE_2D, texId);
231
232         if (g->spread() == QGradient::RepeatSpread || g->type() == QGradient::ConicalGradient)
233             updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
234         else if (g->spread() == QGradient::ReflectSpread)
235             updateTextureFilter(GL_TEXTURE_2D, GL_MIRRORED_REPEAT_IBM, q->state()->renderHints & QPainter::SmoothPixmapTransform);
236         else
237             updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE, q->state()->renderHints & QPainter::SmoothPixmapTransform);
238     }
239     else if (style == Qt::TexturePattern) {
240         currentBrushPixmap = currentBrush.texture();
241
242         int max_texture_size = ctx->d_func()->maxTextureSize();
243         if (currentBrushPixmap.width() > max_texture_size || currentBrushPixmap.height() > max_texture_size)
244             currentBrushPixmap = currentBrushPixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
245
246         glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
247         QGLTexture *tex = ctx->d_func()->bindTexture(currentBrushPixmap, GL_TEXTURE_2D, GL_RGBA,
248                                                      QGLContext::InternalBindOption |
249                                                      QGLContext::CanFlipNativePixmapBindOption);
250         GLenum wrapMode = GL_REPEAT;
251 #ifdef QT_OPENGL_ES_2
252         // should check for GL_OES_texture_npot or GL_IMG_texture_npot extension
253         if (!isPowerOfTwo(currentBrushPixmap.width()) || !isPowerOfTwo(currentBrushPixmap.height()))
254             wrapMode = GL_CLAMP_TO_EDGE;
255 #endif
256         updateTextureFilter(GL_TEXTURE_2D, wrapMode, q->state()->renderHints & QPainter::SmoothPixmapTransform);
257         textureInvertedY = tex->options & QGLContext::InvertedYBindOption ? -1 : 1;
258     }
259     brushTextureDirty = false;
260 }
261
262
263 void QGL2PaintEngineExPrivate::updateBrushUniforms()
264 {
265 //     qDebug("QGL2PaintEngineExPrivate::updateBrushUniforms()");
266     Qt::BrushStyle style = currentBrush.style();
267
268     if (style == Qt::NoBrush)
269         return;
270
271     QTransform brushQTransform = currentBrush.transform();
272
273     if (style == Qt::SolidPattern) {
274         QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
275         shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::FragmentColor), col);
276     }
277     else {
278         // All other brushes have a transform and thus need the translation point:
279         QPointF translationPoint;
280
281         if (style <= Qt::DiagCrossPattern) {
282             QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
283
284             shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::PatternColor), col);
285
286             QVector2D halfViewportSize(width*0.5, height*0.5);
287             shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::HalfViewportSize), halfViewportSize);
288         }
289         else if (style == Qt::LinearGradientPattern) {
290             const QLinearGradient *g = static_cast<const QLinearGradient *>(currentBrush.gradient());
291
292             QPointF realStart = g->start();
293             QPointF realFinal = g->finalStop();
294             translationPoint = realStart;
295
296             QPointF l = realFinal - realStart;
297
298             QVector3D linearData(
299                 l.x(),
300                 l.y(),
301                 1.0f / (l.x() * l.x() + l.y() * l.y())
302             );
303
304             shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::LinearData), linearData);
305
306             QVector2D halfViewportSize(width*0.5, height*0.5);
307             shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::HalfViewportSize), halfViewportSize);
308         }
309         else if (style == Qt::ConicalGradientPattern) {
310             const QConicalGradient *g = static_cast<const QConicalGradient *>(currentBrush.gradient());
311             translationPoint   = g->center();
312
313             GLfloat angle = -(g->angle() * 2 * Q_PI) / 360.0;
314
315             shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::Angle), angle);
316
317             QVector2D halfViewportSize(width*0.5, height*0.5);
318             shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::HalfViewportSize), halfViewportSize);
319         }
320         else if (style == Qt::RadialGradientPattern) {
321             const QRadialGradient *g = static_cast<const QRadialGradient *>(currentBrush.gradient());
322             QPointF realCenter = g->center();
323             QPointF realFocal  = g->focalPoint();
324             qreal   realRadius = g->centerRadius() - g->focalRadius();
325             translationPoint   = realFocal;
326
327             QPointF fmp = realCenter - realFocal;
328             shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::Fmp), fmp);
329
330             GLfloat fmp2_m_radius2 = -fmp.x() * fmp.x() - fmp.y() * fmp.y() + realRadius*realRadius;
331             shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::Fmp2MRadius2), fmp2_m_radius2);
332             shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::Inverse2Fmp2MRadius2),
333                                                              GLfloat(1.0 / (2.0*fmp2_m_radius2)));
334             shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::SqrFr),
335                                                              GLfloat(g->focalRadius() * g->focalRadius()));
336             shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::BRadius),
337                                                              GLfloat(2 * (g->centerRadius() - g->focalRadius()) * g->focalRadius()),
338                                                              g->focalRadius(),
339                                                              g->centerRadius() - g->focalRadius());
340
341             QVector2D halfViewportSize(width*0.5, height*0.5);
342             shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::HalfViewportSize), halfViewportSize);
343         }
344         else if (style == Qt::TexturePattern) {
345             const QPixmap& texPixmap = currentBrush.texture();
346
347             if (qHasPixmapTexture(currentBrush) && currentBrush.texture().isQBitmap()) {
348                 QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
349                 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::PatternColor), col);
350             }
351
352             QSizeF invertedTextureSize(1.0 / texPixmap.width(), 1.0 / texPixmap.height());
353             shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::InvertedTextureSize), invertedTextureSize);
354
355             QVector2D halfViewportSize(width*0.5, height*0.5);
356             shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::HalfViewportSize), halfViewportSize);
357         }
358         else
359             qWarning("QGL2PaintEngineEx: Unimplemented fill style");
360
361         const QPointF &brushOrigin = q->state()->brushOrigin;
362         QTransform matrix = q->state()->matrix;
363         matrix.translate(brushOrigin.x(), brushOrigin.y());
364
365         QTransform translate(1, 0, 0, 1, -translationPoint.x(), -translationPoint.y());
366         qreal m22 = -1;
367         qreal dy = height;
368         if (device->isFlipped()) {
369             m22 = 1;
370             dy = 0;
371         }
372         QTransform gl_to_qt(1, 0, 0, m22, 0, dy);
373         QTransform inv_matrix;
374         if (style == Qt::TexturePattern && textureInvertedY == -1)
375             inv_matrix = gl_to_qt * (QTransform(1, 0, 0, -1, 0, currentBrush.texture().height()) * brushQTransform * matrix).inverted() * translate;
376         else
377             inv_matrix = gl_to_qt * (brushQTransform * matrix).inverted() * translate;
378
379         shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::BrushTransform), inv_matrix);
380         shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::BrushTexture), QT_BRUSH_TEXTURE_UNIT);
381     }
382     brushUniformsDirty = false;
383 }
384
385
386 // This assumes the shader manager has already setup the correct shader program
387 void QGL2PaintEngineExPrivate::updateMatrix()
388 {
389 //     qDebug("QGL2PaintEngineExPrivate::updateMatrix()");
390
391     const QTransform& transform = q->state()->matrix;
392
393     // The projection matrix converts from Qt's coordinate system to GL's coordinate system
394     //    * GL's viewport is 2x2, Qt's is width x height
395     //    * GL has +y -> -y going from bottom -> top, Qt is the other way round
396     //    * GL has [0,0] in the center, Qt has it in the top-left
397     //
398     // This results in the Projection matrix below, which is multiplied by the painter's
399     // transformation matrix, as shown below:
400     //
401     //                Projection Matrix                      Painter Transform
402     // ------------------------------------------------   ------------------------
403     // | 2.0 / width  |      0.0      |     -1.0      |   |  m11  |  m21  |  dx  |
404     // |     0.0      | -2.0 / height |      1.0      | * |  m12  |  m22  |  dy  |
405     // |     0.0      |      0.0      |      1.0      |   |  m13  |  m23  |  m33 |
406     // ------------------------------------------------   ------------------------
407     //
408     // NOTE: The resultant matrix is also transposed, as GL expects column-major matracies
409
410     const GLfloat wfactor = 2.0f / width;
411     GLfloat hfactor = -2.0f / height;
412
413     GLfloat dx = transform.dx();
414     GLfloat dy = transform.dy();
415
416     if (device->isFlipped()) {
417         hfactor *= -1;
418         dy -= height;
419     }
420
421     // Non-integer translates can have strange effects for some rendering operations such as
422     // anti-aliased text rendering. In such cases, we snap the translate to the pixel grid.
423     if (snapToPixelGrid && transform.type() == QTransform::TxTranslate) {
424         // 0.50 needs to rounded down to 0.0 for consistency with raster engine:
425         dx = ceilf(dx - 0.5f);
426         dy = ceilf(dy - 0.5f);
427     }
428     pmvMatrix[0][0] = (wfactor * transform.m11())  - transform.m13();
429     pmvMatrix[1][0] = (wfactor * transform.m21())  - transform.m23();
430     pmvMatrix[2][0] = (wfactor * dx) - transform.m33();
431     pmvMatrix[0][1] = (hfactor * transform.m12())  + transform.m13();
432     pmvMatrix[1][1] = (hfactor * transform.m22())  + transform.m23();
433     pmvMatrix[2][1] = (hfactor * dy) + transform.m33();
434     pmvMatrix[0][2] = transform.m13();
435     pmvMatrix[1][2] = transform.m23();
436     pmvMatrix[2][2] = transform.m33();
437
438     // 1/10000 == 0.0001, so we have good enough res to cover curves
439     // that span the entire widget...
440     inverseScale = qMax(1 / qMax( qMax(qAbs(transform.m11()), qAbs(transform.m22())),
441                                   qMax(qAbs(transform.m12()), qAbs(transform.m21())) ),
442                         qreal(0.0001));
443
444     matrixDirty = false;
445     matrixUniformDirty = true;
446
447     // Set the PMV matrix attribute. As we use an attributes rather than uniforms, we only
448     // need to do this once for every matrix change and persists across all shader programs.
449     glVertexAttrib3fv(QT_PMV_MATRIX_1_ATTR, pmvMatrix[0]);
450     glVertexAttrib3fv(QT_PMV_MATRIX_2_ATTR, pmvMatrix[1]);
451     glVertexAttrib3fv(QT_PMV_MATRIX_3_ATTR, pmvMatrix[2]);
452
453     dasher.setInvScale(inverseScale);
454     stroker.setInvScale(inverseScale);
455 }
456
457
458 void QGL2PaintEngineExPrivate::updateCompositionMode()
459 {
460     // NOTE: The entire paint engine works on pre-multiplied data - which is why some of these
461     //       composition modes look odd.
462 //     qDebug() << "QGL2PaintEngineExPrivate::updateCompositionMode() - Setting GL composition mode for " << q->state()->composition_mode;
463     switch(q->state()->composition_mode) {
464     case QPainter::CompositionMode_SourceOver:
465         glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
466         break;
467     case QPainter::CompositionMode_DestinationOver:
468         glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE);
469         break;
470     case QPainter::CompositionMode_Clear:
471         glBlendFunc(GL_ZERO, GL_ZERO);
472         break;
473     case QPainter::CompositionMode_Source:
474         glBlendFunc(GL_ONE, GL_ZERO);
475         break;
476     case QPainter::CompositionMode_Destination:
477         glBlendFunc(GL_ZERO, GL_ONE);
478         break;
479     case QPainter::CompositionMode_SourceIn:
480         glBlendFunc(GL_DST_ALPHA, GL_ZERO);
481         break;
482     case QPainter::CompositionMode_DestinationIn:
483         glBlendFunc(GL_ZERO, GL_SRC_ALPHA);
484         break;
485     case QPainter::CompositionMode_SourceOut:
486         glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ZERO);
487         break;
488     case QPainter::CompositionMode_DestinationOut:
489         glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_ALPHA);
490         break;
491     case QPainter::CompositionMode_SourceAtop:
492         glBlendFunc(GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
493         break;
494     case QPainter::CompositionMode_DestinationAtop:
495         glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA);
496         break;
497     case QPainter::CompositionMode_Xor:
498         glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
499         break;
500     case QPainter::CompositionMode_Plus:
501         glBlendFunc(GL_ONE, GL_ONE);
502         break;
503     default:
504         qWarning("Unsupported composition mode");
505         break;
506     }
507
508     compositionModeDirty = false;
509 }
510
511 static inline void setCoords(GLfloat *coords, const QGLRect &rect)
512 {
513     coords[0] = rect.left;
514     coords[1] = rect.top;
515     coords[2] = rect.right;
516     coords[3] = rect.top;
517     coords[4] = rect.right;
518     coords[5] = rect.bottom;
519     coords[6] = rect.left;
520     coords[7] = rect.bottom;
521 }
522
523 void QGL2PaintEngineExPrivate::drawTexture(const QGLRect& dest, const QGLRect& src, const QSize &textureSize, bool opaque, bool pattern)
524 {
525     // Setup for texture drawing
526     currentBrush = noBrush;
527     shaderManager->setSrcPixelType(pattern ? QGLEngineShaderManager::PatternSrc : QGLEngineShaderManager::ImageSrc);
528
529     if (snapToPixelGrid) {
530         snapToPixelGrid = false;
531         matrixDirty = true;
532     }
533
534     if (prepareForDraw(opaque))
535         shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::ImageTexture), QT_IMAGE_TEXTURE_UNIT);
536
537     if (pattern) {
538         QColor col = qt_premultiplyColor(q->state()->pen.color(), (GLfloat)q->state()->opacity);
539         shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::PatternColor), col);
540     }
541
542     GLfloat dx = 1.0 / textureSize.width();
543     GLfloat dy = 1.0 / textureSize.height();
544
545     QGLRect srcTextureRect(src.left*dx, src.top*dy, src.right*dx, src.bottom*dy);
546
547     setCoords(staticVertexCoordinateArray, dest);
548     setCoords(staticTextureCoordinateArray, srcTextureRect);
549
550     glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
551 }
552
553 void QGL2PaintEngineEx::beginNativePainting()
554 {
555     Q_D(QGL2PaintEngineEx);
556     ensureActive();
557     d->transferMode(BrushDrawingMode);
558
559     d->nativePaintingActive = true;
560
561     QGLContext *ctx = d->ctx;
562     glUseProgram(0);
563
564     // Disable all the vertex attribute arrays:
565     for (int i = 0; i < QT_GL_VERTEX_ARRAY_TRACKED_COUNT; ++i)
566         glDisableVertexAttribArray(i);
567
568 #ifndef QT_OPENGL_ES_2
569     const QGLFormat &fmt = d->device->format();
570     if (fmt.majorVersion() < 3 || (fmt.majorVersion() == 3 && fmt.minorVersion() < 1)
571         || fmt.profile() == QGLFormat::CompatibilityProfile)
572     {
573         // be nice to people who mix OpenGL 1.x code with QPainter commands
574         // by setting modelview and projection matrices to mirror the GL 1
575         // paint engine
576         const QTransform& mtx = state()->matrix;
577
578         float mv_matrix[4][4] =
579         {
580             { float(mtx.m11()), float(mtx.m12()),     0, float(mtx.m13()) },
581             { float(mtx.m21()), float(mtx.m22()),     0, float(mtx.m23()) },
582             {                0,                0,     1,                0 },
583             {  float(mtx.dx()),  float(mtx.dy()),     0, float(mtx.m33()) }
584         };
585
586         const QSize sz = d->device->size();
587
588         glMatrixMode(GL_PROJECTION);
589         glLoadIdentity();
590         glOrtho(0, sz.width(), sz.height(), 0, -999999, 999999);
591
592         glMatrixMode(GL_MODELVIEW);
593         glLoadMatrixf(&mv_matrix[0][0]);
594     }
595 #else
596     Q_UNUSED(ctx);
597 #endif
598
599     d->lastTextureUsed = GLuint(-1);
600     d->dirtyStencilRegion = QRect(0, 0, d->width, d->height);
601     d->resetGLState();
602
603     d->shaderManager->setDirty();
604
605     d->needsSync = true;
606 }
607
608 void QGL2PaintEngineExPrivate::resetGLState()
609 {
610     glDisable(GL_BLEND);
611     glActiveTexture(GL_TEXTURE0);
612     glDisable(GL_STENCIL_TEST);
613     glDisable(GL_DEPTH_TEST);
614     glDisable(GL_SCISSOR_TEST);
615     glDepthMask(true);
616     glDepthFunc(GL_LESS);
617     glClearDepth(1);
618     glStencilMask(0xff);
619     glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
620     glStencilFunc(GL_ALWAYS, 0, 0xff);
621     ctx->d_func()->setVertexAttribArrayEnabled(QT_TEXTURE_COORDS_ATTR, false);
622     ctx->d_func()->setVertexAttribArrayEnabled(QT_VERTEX_COORDS_ATTR, false);
623     ctx->d_func()->setVertexAttribArrayEnabled(QT_OPACITY_ATTR, false);
624 #ifndef QT_OPENGL_ES_2
625     // gl_Color, corresponding to vertex attribute 3, may have been changed
626     float color[] = { 1.0f, 1.0f, 1.0f, 1.0f };
627     glVertexAttrib4fv(3, color);
628 #endif
629 }
630
631 void QGL2PaintEngineEx::endNativePainting()
632 {
633     Q_D(QGL2PaintEngineEx);
634     d->needsSync = true;
635     d->nativePaintingActive = false;
636 }
637
638 void QGL2PaintEngineEx::invalidateState()
639 {
640     Q_D(QGL2PaintEngineEx);
641     d->needsSync = true;
642 }
643
644 bool QGL2PaintEngineEx::isNativePaintingActive() const {
645     Q_D(const QGL2PaintEngineEx);
646     return d->nativePaintingActive;
647 }
648
649 void QGL2PaintEngineExPrivate::transferMode(EngineMode newMode)
650 {
651     if (newMode == mode)
652         return;
653
654     if (mode == TextDrawingMode || imageDrawingMode) {
655         lastTextureUsed = GLuint(-1);
656     }
657
658     if (newMode == TextDrawingMode) {
659         shaderManager->setHasComplexGeometry(true);
660     } else {
661         shaderManager->setHasComplexGeometry(false);
662     }
663
664     imageDrawingMode = false;
665
666     if (newMode == ImageDrawingMode) {
667         setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, staticVertexCoordinateArray);
668         setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, staticTextureCoordinateArray);
669         imageDrawingMode = true;
670     }
671
672     if (newMode == ImageArrayDrawingMode || newMode == ImageArrayWithOpacityDrawingMode) {
673         setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)vertexCoordinateArray.data());
674         setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, (GLfloat*)textureCoordinateArray.data());
675         imageDrawingMode = true;
676     }
677
678     if (newMode == ImageArrayWithOpacityDrawingMode) {
679         setVertexAttributePointer(QT_OPACITY_ATTR, (GLfloat*)opacityArray.data());
680     }
681
682     // This needs to change when we implement high-quality anti-aliasing...
683     if (newMode != TextDrawingMode)
684         shaderManager->setMaskType(QGLEngineShaderManager::NoMask);
685
686     mode = newMode;
687 }
688
689 struct QGL2PEVectorPathCache
690 {
691 #ifdef QT_OPENGL_CACHE_AS_VBOS
692     GLuint vbo;
693     GLuint ibo;
694 #else
695     float *vertices;
696     void *indices;
697 #endif
698     int vertexCount;
699     int indexCount;
700     GLenum primitiveType;
701     qreal iscale;
702 };
703
704 void QGL2PaintEngineExPrivate::cleanupVectorPath(QPaintEngineEx *engine, void *data)
705 {
706     QGL2PEVectorPathCache *c = (QGL2PEVectorPathCache *) data;
707 #ifdef QT_OPENGL_CACHE_AS_VBOS
708     Q_ASSERT(engine->type() == QPaintEngine::OpenGL2);
709     static_cast<QGL2PaintEngineEx *>(engine)->d_func()->unusedVBOSToClean << c->vbo;
710     if (c->ibo)
711         d->unusedIBOSToClean << c->ibo;
712 #else
713     Q_UNUSED(engine);
714     qFree(c->vertices);
715     qFree(c->indices);
716 #endif
717     delete c;
718 }
719
720 // Assumes everything is configured for the brush you want to use
721 void QGL2PaintEngineExPrivate::fill(const QVectorPath& path)
722 {
723     transferMode(BrushDrawingMode);
724
725     if (snapToPixelGrid) {
726         snapToPixelGrid = false;
727         matrixDirty = true;
728     }
729
730     // Might need to call updateMatrix to re-calculate inverseScale
731     if (matrixDirty)
732         updateMatrix();
733
734     const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
735
736     // Check to see if there's any hints
737     if (path.shape() == QVectorPath::RectangleHint) {
738         QGLRect rect(points[0].x(), points[0].y(), points[2].x(), points[2].y());
739         prepareForDraw(currentBrush.isOpaque());
740         composite(rect);
741     } else if (path.isConvex()) {
742
743         if (path.isCacheable()) {
744             QVectorPath::CacheEntry *data = path.lookupCacheData(q);
745             QGL2PEVectorPathCache *cache;
746
747             bool updateCache = false;
748
749             if (data) {
750                 cache = (QGL2PEVectorPathCache *) data->data;
751                 // Check if scale factor is exceeded for curved paths and generate curves if so...
752                 if (path.isCurved()) {
753                     qreal scaleFactor = cache->iscale / inverseScale;
754                     if (scaleFactor < 0.5 || scaleFactor > 2.0) {
755 #ifdef QT_OPENGL_CACHE_AS_VBOS
756                         glDeleteBuffers(1, &cache->vbo);
757                         cache->vbo = 0;
758                         Q_ASSERT(cache->ibo == 0);
759 #else
760                         qFree(cache->vertices);
761                         Q_ASSERT(cache->indices == 0);
762 #endif
763                         updateCache = true;
764                     }
765                 }
766             } else {
767                 cache = new QGL2PEVectorPathCache;
768                 data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
769                 updateCache = true;
770             }
771
772             // Flatten the path at the current scale factor and fill it into the cache struct.
773             if (updateCache) {
774                 vertexCoordinateArray.clear();
775                 vertexCoordinateArray.addPath(path, inverseScale, false);
776                 int vertexCount = vertexCoordinateArray.vertexCount();
777                 int floatSizeInBytes = vertexCount * 2 * sizeof(float);
778                 cache->vertexCount = vertexCount;
779                 cache->indexCount = 0;
780                 cache->primitiveType = GL_TRIANGLE_FAN;
781                 cache->iscale = inverseScale;
782 #ifdef QT_OPENGL_CACHE_AS_VBOS
783                 glGenBuffers(1, &cache->vbo);
784                 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
785                 glBufferData(GL_ARRAY_BUFFER, floatSizeInBytes, vertexCoordinateArray.data(), GL_STATIC_DRAW);
786                 cache->ibo = 0;
787 #else
788                 cache->vertices = (float *) qMalloc(floatSizeInBytes);
789                 memcpy(cache->vertices, vertexCoordinateArray.data(), floatSizeInBytes);
790                 cache->indices = 0;
791 #endif
792             }
793
794             prepareForDraw(currentBrush.isOpaque());
795 #ifdef QT_OPENGL_CACHE_AS_VBOS
796             glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
797             setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, 0);
798 #else
799             setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, cache->vertices);
800 #endif
801             glDrawArrays(cache->primitiveType, 0, cache->vertexCount);
802
803         } else {
804       //        printf(" - Marking path as cachable...\n");
805             // Tag it for later so that if the same path is drawn twice, it is assumed to be static and thus cachable
806             path.makeCacheable();
807             vertexCoordinateArray.clear();
808             vertexCoordinateArray.addPath(path, inverseScale, false);
809             prepareForDraw(currentBrush.isOpaque());
810             drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN);
811         }
812
813     } else {
814         bool useCache = path.isCacheable();
815         if (useCache) {
816             QRectF bbox = path.controlPointRect();
817             // If the path doesn't fit within these limits, it is possible that the triangulation will fail.
818             useCache &= (bbox.left() > -0x8000 * inverseScale)
819                      && (bbox.right() < 0x8000 * inverseScale)
820                      && (bbox.top() > -0x8000 * inverseScale)
821                      && (bbox.bottom() < 0x8000 * inverseScale);
822         }
823
824         if (useCache) {
825             QVectorPath::CacheEntry *data = path.lookupCacheData(q);
826             QGL2PEVectorPathCache *cache;
827
828             bool updateCache = false;
829
830             if (data) {
831                 cache = (QGL2PEVectorPathCache *) data->data;
832                 // Check if scale factor is exceeded for curved paths and generate curves if so...
833                 if (path.isCurved()) {
834                     qreal scaleFactor = cache->iscale / inverseScale;
835                     if (scaleFactor < 0.5 || scaleFactor > 2.0) {
836 #ifdef QT_OPENGL_CACHE_AS_VBOS
837                         glDeleteBuffers(1, &cache->vbo);
838                         glDeleteBuffers(1, &cache->ibo);
839 #else
840                         qFree(cache->vertices);
841                         qFree(cache->indices);
842 #endif
843                         updateCache = true;
844                     }
845                 }
846             } else {
847                 cache = new QGL2PEVectorPathCache;
848                 data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
849                 updateCache = true;
850             }
851
852             // Flatten the path at the current scale factor and fill it into the cache struct.
853             if (updateCache) {
854                 QTriangleSet polys = qTriangulate(path, QTransform().scale(1 / inverseScale, 1 / inverseScale));
855                 cache->vertexCount = polys.vertices.size() / 2;
856                 cache->indexCount = polys.indices.size();
857                 cache->primitiveType = GL_TRIANGLES;
858                 cache->iscale = inverseScale;
859 #ifdef QT_OPENGL_CACHE_AS_VBOS
860                 glGenBuffers(1, &cache->vbo);
861                 glGenBuffers(1, &cache->ibo);
862                 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
863                 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cache->ibo);
864
865                 if (QGLExtensions::glExtensions() & QGLExtensions::ElementIndexUint)
866                     glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint32) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
867                 else
868                     glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint16) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
869
870                 QVarLengthArray<float> vertices(polys.vertices.size());
871                 for (int i = 0; i < polys.vertices.size(); ++i)
872                     vertices[i] = float(inverseScale * polys.vertices.at(i));
873                 glBufferData(GL_ARRAY_BUFFER, sizeof(float) * vertices.size(), vertices.data(), GL_STATIC_DRAW);
874 #else
875                 cache->vertices = (float *) qMalloc(sizeof(float) * polys.vertices.size());
876                 if (QGLExtensions::glExtensions() & QGLExtensions::ElementIndexUint) {
877                     cache->indices = (quint32 *) qMalloc(sizeof(quint32) * polys.indices.size());
878                     memcpy(cache->indices, polys.indices.data(), sizeof(quint32) * polys.indices.size());
879                 } else {
880                     cache->indices = (quint16 *) qMalloc(sizeof(quint16) * polys.indices.size());
881                     memcpy(cache->indices, polys.indices.data(), sizeof(quint16) * polys.indices.size());
882                 }
883                 for (int i = 0; i < polys.vertices.size(); ++i)
884                     cache->vertices[i] = float(inverseScale * polys.vertices.at(i));
885 #endif
886             }
887
888             prepareForDraw(currentBrush.isOpaque());
889 #ifdef QT_OPENGL_CACHE_AS_VBOS
890             glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
891             glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cache->ibo);
892             setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, 0);
893             if (QGLExtensions::glExtensions() & QGLExtensions::ElementIndexUint)
894                 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_INT, 0);
895             else
896                 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_SHORT, 0);
897             glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
898             glBindBuffer(GL_ARRAY_BUFFER, 0);
899 #else
900             setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, cache->vertices);
901             if (QGLExtensions::glExtensions() & QGLExtensions::ElementIndexUint)
902                 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_INT, (qint32 *)cache->indices);
903             else
904                 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_SHORT, (qint16 *)cache->indices);
905 #endif
906
907         } else {
908       //        printf(" - Marking path as cachable...\n");
909             // Tag it for later so that if the same path is drawn twice, it is assumed to be static and thus cachable
910             path.makeCacheable();
911
912             if (!device->format().stencil()) {
913                 // If there is no stencil buffer, triangulate the path instead.
914
915                 QRectF bbox = path.controlPointRect();
916                 // If the path doesn't fit within these limits, it is possible that the triangulation will fail.
917                 bool withinLimits = (bbox.left() > -0x8000 * inverseScale)
918                                   && (bbox.right() < 0x8000 * inverseScale)
919                                   && (bbox.top() > -0x8000 * inverseScale)
920                                   && (bbox.bottom() < 0x8000 * inverseScale);
921                 if (withinLimits) {
922                     QTriangleSet polys = qTriangulate(path, QTransform().scale(1 / inverseScale, 1 / inverseScale));
923
924                     QVarLengthArray<float> vertices(polys.vertices.size());
925                     for (int i = 0; i < polys.vertices.size(); ++i)
926                         vertices[i] = float(inverseScale * polys.vertices.at(i));
927
928                     prepareForDraw(currentBrush.isOpaque());
929                     setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, vertices.constData());
930                     if (QGLExtensions::glExtensions() & QGLExtensions::ElementIndexUint)
931                         glDrawElements(GL_TRIANGLES, polys.indices.size(), GL_UNSIGNED_INT, polys.indices.data());
932                     else
933                         glDrawElements(GL_TRIANGLES, polys.indices.size(), GL_UNSIGNED_SHORT, polys.indices.data());
934                 } else {
935                     // We can't handle big, concave painter paths with OpenGL without stencil buffer.
936                     qWarning("Painter path exceeds +/-32767 pixels.");
937                 }
938                 return;
939             }
940
941             // The path is too complicated & needs the stencil technique
942             vertexCoordinateArray.clear();
943             vertexCoordinateArray.addPath(path, inverseScale, false);
944
945             fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill());
946
947             glStencilMask(0xff);
948             glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
949
950             if (q->state()->clipTestEnabled) {
951                 // Pass when high bit is set, replace stencil value with current clip
952                 glStencilFunc(GL_NOTEQUAL, q->state()->currentClip, GL_STENCIL_HIGH_BIT);
953             } else if (path.hasWindingFill()) {
954                 // Pass when any bit is set, replace stencil value with 0
955                 glStencilFunc(GL_NOTEQUAL, 0, 0xff);
956             } else {
957                 // Pass when high bit is set, replace stencil value with 0
958                 glStencilFunc(GL_NOTEQUAL, 0, GL_STENCIL_HIGH_BIT);
959             }
960             prepareForDraw(currentBrush.isOpaque());
961
962             // Stencil the brush onto the dest buffer
963             composite(vertexCoordinateArray.boundingRect());
964             glStencilMask(0);
965             updateClipScissorTest();
966         }
967     }
968 }
969
970
971 void QGL2PaintEngineExPrivate::fillStencilWithVertexArray(const float *data,
972                                                           int count,
973                                                           int *stops,
974                                                           int stopCount,
975                                                           const QGLRect &bounds,
976                                                           StencilFillMode mode)
977 {
978     Q_ASSERT(count || stops);
979
980 //     qDebug("QGL2PaintEngineExPrivate::fillStencilWithVertexArray()");
981     glStencilMask(0xff); // Enable stencil writes
982
983     if (dirtyStencilRegion.intersects(currentScissorBounds)) {
984         QVector<QRect> clearRegion = dirtyStencilRegion.intersected(currentScissorBounds).rects();
985         glClearStencil(0); // Clear to zero
986         for (int i = 0; i < clearRegion.size(); ++i) {
987 #ifndef QT_GL_NO_SCISSOR_TEST
988             setScissor(clearRegion.at(i));
989 #endif
990             glClear(GL_STENCIL_BUFFER_BIT);
991         }
992
993         dirtyStencilRegion -= currentScissorBounds;
994
995 #ifndef QT_GL_NO_SCISSOR_TEST
996         updateClipScissorTest();
997 #endif
998     }
999
1000     glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); // Disable color writes
1001     useSimpleShader();
1002     glEnable(GL_STENCIL_TEST); // For some reason, this has to happen _after_ the simple shader is use()'d
1003
1004     if (mode == WindingFillMode) {
1005         Q_ASSERT(stops && !count);
1006         if (q->state()->clipTestEnabled) {
1007             // Flatten clip values higher than current clip, and set high bit to match current clip
1008             glStencilFunc(GL_LEQUAL, GL_STENCIL_HIGH_BIT | q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
1009             glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
1010             composite(bounds);
1011
1012             glStencilFunc(GL_EQUAL, GL_STENCIL_HIGH_BIT, GL_STENCIL_HIGH_BIT);
1013         } else if (!stencilClean) {
1014             // Clear stencil buffer within bounding rect
1015             glStencilFunc(GL_ALWAYS, 0, 0xff);
1016             glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO);
1017             composite(bounds);
1018         }
1019
1020         // Inc. for front-facing triangle
1021         glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_INCR_WRAP, GL_INCR_WRAP);
1022         // Dec. for back-facing "holes"
1023         glStencilOpSeparate(GL_BACK, GL_KEEP, GL_DECR_WRAP, GL_DECR_WRAP);
1024         glStencilMask(~GL_STENCIL_HIGH_BIT);
1025         drawVertexArrays(data, stops, stopCount, GL_TRIANGLE_FAN);
1026
1027         if (q->state()->clipTestEnabled) {
1028             // Clear high bit of stencil outside of path
1029             glStencilFunc(GL_EQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
1030             glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
1031             glStencilMask(GL_STENCIL_HIGH_BIT);
1032             composite(bounds);
1033         }
1034     } else if (mode == OddEvenFillMode) {
1035         glStencilMask(GL_STENCIL_HIGH_BIT);
1036         glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT); // Simply invert the stencil bit
1037         drawVertexArrays(data, stops, stopCount, GL_TRIANGLE_FAN);
1038
1039     } else { // TriStripStrokeFillMode
1040         Q_ASSERT(count && !stops); // tristrips generated directly, so no vertexArray or stops
1041         glStencilMask(GL_STENCIL_HIGH_BIT);
1042 #if 0
1043         glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT); // Simply invert the stencil bit
1044         setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, data);
1045         glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
1046 #else
1047
1048         glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
1049         if (q->state()->clipTestEnabled) {
1050             glStencilFunc(GL_LEQUAL, q->state()->currentClip | GL_STENCIL_HIGH_BIT,
1051                           ~GL_STENCIL_HIGH_BIT);
1052         } else {
1053             glStencilFunc(GL_ALWAYS, GL_STENCIL_HIGH_BIT, 0xff);
1054         }
1055         setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, data);
1056         glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
1057 #endif
1058     }
1059
1060     // Enable color writes & disable stencil writes
1061     glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1062 }
1063
1064 /*
1065     If the maximum value in the stencil buffer is GL_STENCIL_HIGH_BIT - 1,
1066     restore the stencil buffer to a pristine state.  The current clip region
1067     is set to 1, and the rest to 0.
1068 */
1069 void QGL2PaintEngineExPrivate::resetClipIfNeeded()
1070 {
1071     if (maxClip != (GL_STENCIL_HIGH_BIT - 1))
1072         return;
1073
1074     Q_Q(QGL2PaintEngineEx);
1075
1076     useSimpleShader();
1077     glEnable(GL_STENCIL_TEST);
1078     glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1079
1080     QRectF bounds = q->state()->matrix.inverted().mapRect(QRectF(0, 0, width, height));
1081     QGLRect rect(bounds.left(), bounds.top(), bounds.right(), bounds.bottom());
1082
1083     // Set high bit on clip region
1084     glStencilFunc(GL_LEQUAL, q->state()->currentClip, 0xff);
1085     glStencilOp(GL_KEEP, GL_INVERT, GL_INVERT);
1086     glStencilMask(GL_STENCIL_HIGH_BIT);
1087     composite(rect);
1088
1089     // Reset clipping to 1 and everything else to zero
1090     glStencilFunc(GL_NOTEQUAL, 0x01, GL_STENCIL_HIGH_BIT);
1091     glStencilOp(GL_ZERO, GL_REPLACE, GL_REPLACE);
1092     glStencilMask(0xff);
1093     composite(rect);
1094
1095     q->state()->currentClip = 1;
1096     q->state()->canRestoreClip = false;
1097
1098     maxClip = 1;
1099
1100     glStencilMask(0x0);
1101     glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1102 }
1103
1104 bool QGL2PaintEngineExPrivate::prepareForDraw(bool srcPixelsAreOpaque)
1105 {
1106     if (brushTextureDirty && !imageDrawingMode)
1107         updateBrushTexture();
1108
1109     if (compositionModeDirty)
1110         updateCompositionMode();
1111
1112     if (matrixDirty)
1113         updateMatrix();
1114
1115     const bool stateHasOpacity = q->state()->opacity < 0.99f;
1116     if (q->state()->composition_mode == QPainter::CompositionMode_Source
1117         || (q->state()->composition_mode == QPainter::CompositionMode_SourceOver
1118             && srcPixelsAreOpaque && !stateHasOpacity))
1119     {
1120         glDisable(GL_BLEND);
1121     } else {
1122         glEnable(GL_BLEND);
1123     }
1124
1125     QGLEngineShaderManager::OpacityMode opacityMode;
1126     if (mode == ImageArrayWithOpacityDrawingMode) {
1127         opacityMode = QGLEngineShaderManager::AttributeOpacity;
1128     } else {
1129         opacityMode = stateHasOpacity ? QGLEngineShaderManager::UniformOpacity
1130                                       : QGLEngineShaderManager::NoOpacity;
1131         if (stateHasOpacity && !imageDrawingMode) {
1132             // Using a brush
1133             bool brushIsPattern = (currentBrush.style() >= Qt::Dense1Pattern) &&
1134                                   (currentBrush.style() <= Qt::DiagCrossPattern);
1135
1136             if ((currentBrush.style() == Qt::SolidPattern) || brushIsPattern)
1137                 opacityMode = QGLEngineShaderManager::NoOpacity; // Global opacity handled by srcPixel shader
1138         }
1139     }
1140     shaderManager->setOpacityMode(opacityMode);
1141
1142     bool changed = shaderManager->useCorrectShaderProg();
1143     // If the shader program needs changing, we change it and mark all uniforms as dirty
1144     if (changed) {
1145         // The shader program has changed so mark all uniforms as dirty:
1146         brushUniformsDirty = true;
1147         opacityUniformDirty = true;
1148         matrixUniformDirty = true;
1149     }
1150
1151     if (brushUniformsDirty && !imageDrawingMode)
1152         updateBrushUniforms();
1153
1154     if (opacityMode == QGLEngineShaderManager::UniformOpacity && opacityUniformDirty) {
1155         shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::GlobalOpacity), (GLfloat)q->state()->opacity);
1156         opacityUniformDirty = false;
1157     }
1158
1159     if (matrixUniformDirty && shaderManager->hasComplexGeometry()) {
1160         shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::Matrix),
1161                                                          pmvMatrix);
1162         matrixUniformDirty = false;
1163     }
1164
1165     return changed;
1166 }
1167
1168 void QGL2PaintEngineExPrivate::composite(const QGLRect& boundingRect)
1169 {
1170     setCoords(staticVertexCoordinateArray, boundingRect);
1171     setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, staticVertexCoordinateArray);
1172     glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1173 }
1174
1175 // Draws the vertex array as a set of <vertexArrayStops.size()> triangle fans.
1176 void QGL2PaintEngineExPrivate::drawVertexArrays(const float *data, int *stops, int stopCount,
1177                                                 GLenum primitive)
1178 {
1179     // Now setup the pointer to the vertex array:
1180     setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)data);
1181
1182     int previousStop = 0;
1183     for (int i=0; i<stopCount; ++i) {
1184         int stop = stops[i];
1185 /*
1186         qDebug("Drawing triangle fan for vertecies %d -> %d:", previousStop, stop-1);
1187         for (int i=previousStop; i<stop; ++i)
1188             qDebug("   %02d: [%.2f, %.2f]", i, vertexArray.data()[i].x, vertexArray.data()[i].y);
1189 */
1190         glDrawArrays(primitive, previousStop, stop - previousStop);
1191         previousStop = stop;
1192     }
1193 }
1194
1195 /////////////////////////////////// Public Methods //////////////////////////////////////////
1196
1197 QGL2PaintEngineEx::QGL2PaintEngineEx()
1198     : QPaintEngineEx(*(new QGL2PaintEngineExPrivate(this)))
1199 {
1200 }
1201
1202 QGL2PaintEngineEx::~QGL2PaintEngineEx()
1203 {
1204 }
1205
1206 void QGL2PaintEngineEx::fill(const QVectorPath &path, const QBrush &brush)
1207 {
1208     Q_D(QGL2PaintEngineEx);
1209
1210     if (qbrush_style(brush) == Qt::NoBrush)
1211         return;
1212     ensureActive();
1213     d->setBrush(brush);
1214     d->fill(path);
1215 }
1216
1217 Q_GUI_EXPORT bool qt_scaleForTransform(const QTransform &transform, qreal *scale); // qtransform.cpp
1218
1219
1220 void QGL2PaintEngineEx::stroke(const QVectorPath &path, const QPen &pen)
1221 {
1222     Q_D(QGL2PaintEngineEx);
1223
1224     const QBrush &penBrush = qpen_brush(pen);
1225     if (qpen_style(pen) == Qt::NoPen || qbrush_style(penBrush) == Qt::NoBrush)
1226         return;
1227
1228     QOpenGL2PaintEngineState *s = state();
1229     if (pen.isCosmetic() && !qt_scaleForTransform(s->transform(), 0)) {
1230         // QTriangulatingStroker class is not meant to support cosmetically sheared strokes.
1231         QPaintEngineEx::stroke(path, pen);
1232         return;
1233     }
1234
1235     ensureActive();
1236     d->setBrush(penBrush);
1237     d->stroke(path, pen);
1238 }
1239
1240 void QGL2PaintEngineExPrivate::stroke(const QVectorPath &path, const QPen &pen)
1241 {
1242     const QOpenGL2PaintEngineState *s = q->state();
1243     if (snapToPixelGrid) {
1244         snapToPixelGrid = false;
1245         matrixDirty = true;
1246     }
1247
1248     const Qt::PenStyle penStyle = qpen_style(pen);
1249     const QBrush &penBrush = qpen_brush(pen);
1250     const bool opaque = penBrush.isOpaque() && s->opacity > 0.99;
1251
1252     transferMode(BrushDrawingMode);
1253
1254     // updateMatrix() is responsible for setting the inverse scale on
1255     // the strokers, so we need to call it here and not wait for
1256     // prepareForDraw() down below.
1257     updateMatrix();
1258
1259     QRectF clip = q->state()->matrix.inverted().mapRect(q->state()->clipEnabled
1260                                                         ? q->state()->rectangleClip
1261                                                         : QRectF(0, 0, width, height));
1262
1263     if (penStyle == Qt::SolidLine) {
1264         stroker.process(path, pen, clip);
1265
1266     } else { // Some sort of dash
1267         dasher.process(path, pen, clip);
1268
1269         QVectorPath dashStroke(dasher.points(),
1270                                dasher.elementCount(),
1271                                dasher.elementTypes());
1272         stroker.process(dashStroke, pen, clip);
1273     }
1274
1275     if (!stroker.vertexCount())
1276         return;
1277
1278     if (opaque) {
1279         prepareForDraw(opaque);
1280         setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, stroker.vertices());
1281         glDrawArrays(GL_TRIANGLE_STRIP, 0, stroker.vertexCount() / 2);
1282
1283 //         QBrush b(Qt::green);
1284 //         d->setBrush(&b);
1285 //         d->prepareForDraw(true);
1286 //         glDrawArrays(GL_LINE_STRIP, 0, d->stroker.vertexCount() / 2);
1287
1288     } else {
1289         qreal width = qpen_widthf(pen) / 2;
1290         if (width == 0)
1291             width = 0.5;
1292         qreal extra = pen.joinStyle() == Qt::MiterJoin
1293                       ? qMax(pen.miterLimit() * width, width)
1294                       : width;
1295
1296         if (pen.isCosmetic())
1297             extra = extra * inverseScale;
1298
1299         QRectF bounds = path.controlPointRect().adjusted(-extra, -extra, extra, extra);
1300
1301         fillStencilWithVertexArray(stroker.vertices(), stroker.vertexCount() / 2,
1302                                       0, 0, bounds, QGL2PaintEngineExPrivate::TriStripStrokeFillMode);
1303
1304         glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
1305
1306         // Pass when any bit is set, replace stencil value with 0
1307         glStencilFunc(GL_NOTEQUAL, 0, GL_STENCIL_HIGH_BIT);
1308         prepareForDraw(false);
1309
1310         // Stencil the brush onto the dest buffer
1311         composite(bounds);
1312
1313         glStencilMask(0);
1314
1315         updateClipScissorTest();
1316     }
1317 }
1318
1319 void QGL2PaintEngineEx::penChanged() { }
1320 void QGL2PaintEngineEx::brushChanged() { }
1321 void QGL2PaintEngineEx::brushOriginChanged() { }
1322
1323 void QGL2PaintEngineEx::opacityChanged()
1324 {
1325 //    qDebug("QGL2PaintEngineEx::opacityChanged()");
1326     Q_D(QGL2PaintEngineEx);
1327     state()->opacityChanged = true;
1328
1329     Q_ASSERT(d->shaderManager);
1330     d->brushUniformsDirty = true;
1331     d->opacityUniformDirty = true;
1332 }
1333
1334 void QGL2PaintEngineEx::compositionModeChanged()
1335 {
1336 //     qDebug("QGL2PaintEngineEx::compositionModeChanged()");
1337     Q_D(QGL2PaintEngineEx);
1338     state()->compositionModeChanged = true;
1339     d->compositionModeDirty = true;
1340 }
1341
1342 void QGL2PaintEngineEx::renderHintsChanged()
1343 {
1344     state()->renderHintsChanged = true;
1345
1346 #if !defined(QT_OPENGL_ES_2)
1347     if ((state()->renderHints & QPainter::Antialiasing)
1348         || (state()->renderHints & QPainter::HighQualityAntialiasing))
1349         glEnable(GL_MULTISAMPLE);
1350     else
1351         glDisable(GL_MULTISAMPLE);
1352 #endif
1353
1354     Q_D(QGL2PaintEngineEx);
1355     d->lastTextureUsed = GLuint(-1);
1356     d->brushTextureDirty = true;
1357 //    qDebug("QGL2PaintEngineEx::renderHintsChanged() not implemented!");
1358 }
1359
1360 void QGL2PaintEngineEx::transformChanged()
1361 {
1362     Q_D(QGL2PaintEngineEx);
1363     d->matrixDirty = true;
1364     state()->matrixChanged = true;
1365 }
1366
1367
1368 static const QRectF scaleRect(const QRectF &r, qreal sx, qreal sy)
1369 {
1370     return QRectF(r.x() * sx, r.y() * sy, r.width() * sx, r.height() * sy);
1371 }
1372
1373 void QGL2PaintEngineEx::drawPixmap(const QRectF& dest, const QPixmap & pixmap, const QRectF & src)
1374 {
1375     Q_D(QGL2PaintEngineEx);
1376     QGLContext *ctx = d->ctx;
1377
1378     int max_texture_size = ctx->d_func()->maxTextureSize();
1379     if (pixmap.width() > max_texture_size || pixmap.height() > max_texture_size) {
1380         QPixmap scaled = pixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1381
1382         const qreal sx = scaled.width() / qreal(pixmap.width());
1383         const qreal sy = scaled.height() / qreal(pixmap.height());
1384
1385         drawPixmap(dest, scaled, scaleRect(src, sx, sy));
1386         return;
1387     }
1388
1389     ensureActive();
1390     d->transferMode(ImageDrawingMode);
1391
1392     glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1393     QGLTexture *texture =
1394         ctx->d_func()->bindTexture(pixmap, GL_TEXTURE_2D, GL_RGBA,
1395                                     QGLContext::InternalBindOption
1396                                     | QGLContext::CanFlipNativePixmapBindOption);
1397
1398     GLfloat top = texture->options & QGLContext::InvertedYBindOption ? (pixmap.height() - src.top()) : src.top();
1399     GLfloat bottom = texture->options & QGLContext::InvertedYBindOption ? (pixmap.height() - src.bottom()) : src.bottom();
1400     QGLRect srcRect(src.left(), top, src.right(), bottom);
1401
1402     bool isBitmap = pixmap.isQBitmap();
1403     bool isOpaque = !isBitmap && !pixmap.hasAlpha();
1404
1405     d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1406                            state()->renderHints & QPainter::SmoothPixmapTransform, texture->id);
1407     d->drawTexture(dest, srcRect, pixmap.size(), isOpaque, isBitmap);
1408 }
1409
1410 void QGL2PaintEngineEx::drawImage(const QRectF& dest, const QImage& image, const QRectF& src,
1411                         Qt::ImageConversionFlags)
1412 {
1413     Q_D(QGL2PaintEngineEx);
1414     QGLContext *ctx = d->ctx;
1415
1416     int max_texture_size = ctx->d_func()->maxTextureSize();
1417     if (image.width() > max_texture_size || image.height() > max_texture_size) {
1418         QImage scaled = image.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1419
1420         const qreal sx = scaled.width() / qreal(image.width());
1421         const qreal sy = scaled.height() / qreal(image.height());
1422
1423         drawImage(dest, scaled, scaleRect(src, sx, sy));
1424         return;
1425     }
1426
1427     ensureActive();
1428     d->transferMode(ImageDrawingMode);
1429
1430     glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1431
1432     QGLTexture *texture = ctx->d_func()->bindTexture(image, GL_TEXTURE_2D, GL_RGBA, QGLContext::InternalBindOption);
1433     GLuint id = texture->id;
1434
1435     d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1436                            state()->renderHints & QPainter::SmoothPixmapTransform, id);
1437     d->drawTexture(dest, src, image.size(), !image.hasAlphaChannel());
1438 }
1439
1440 void QGL2PaintEngineEx::drawStaticTextItem(QStaticTextItem *textItem)
1441 {
1442     Q_D(QGL2PaintEngineEx);
1443
1444     ensureActive();
1445
1446     QPainterState *s = state();
1447     float det = s->matrix.determinant();
1448
1449     // don't try to cache huge fonts or vastly transformed fonts
1450     QFontEngine *fontEngine = textItem->fontEngine();
1451     const qreal pixelSize = fontEngine->fontDef.pixelSize;
1452     if (pixelSize * pixelSize * qAbs(det) < QT_MAX_CACHED_GLYPH_SIZE * QT_MAX_CACHED_GLYPH_SIZE ||
1453         det < 0.25f || det > 4.f) {
1454         QFontEngineGlyphCache::Type glyphType = fontEngine->glyphFormat >= 0
1455                                                 ? QFontEngineGlyphCache::Type(textItem->fontEngine()->glyphFormat)
1456                                                 : d->glyphCacheType;
1457         if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1458             if (d->device->alphaRequested() || s->matrix.type() > QTransform::TxTranslate
1459                 || (s->composition_mode != QPainter::CompositionMode_Source
1460                 && s->composition_mode != QPainter::CompositionMode_SourceOver))
1461             {
1462                 glyphType = QFontEngineGlyphCache::Raster_A8;
1463             }
1464         }
1465
1466         d->drawCachedGlyphs(glyphType, textItem);
1467     } else {
1468         QPaintEngineEx::drawStaticTextItem(textItem);
1469     }
1470 }
1471
1472 bool QGL2PaintEngineEx::drawTexture(const QRectF &dest, GLuint textureId, const QSize &size, const QRectF &src)
1473 {
1474     Q_D(QGL2PaintEngineEx);
1475     if (!d->shaderManager)
1476         return false;
1477
1478     ensureActive();
1479     d->transferMode(ImageDrawingMode);
1480
1481 #ifndef QT_OPENGL_ES_2
1482     QGLContext *ctx = d->ctx;
1483 #endif
1484     glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1485     glBindTexture(GL_TEXTURE_2D, textureId);
1486
1487     QGLRect srcRect(src.left(), src.bottom(), src.right(), src.top());
1488
1489     d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1490                            state()->renderHints & QPainter::SmoothPixmapTransform, textureId);
1491     d->drawTexture(dest, srcRect, size, false);
1492     return true;
1493 }
1494
1495 void QGL2PaintEngineEx::drawTextItem(const QPointF &p, const QTextItem &textItem)
1496 {
1497     Q_D(QGL2PaintEngineEx);
1498
1499     ensureActive();
1500     QOpenGL2PaintEngineState *s = state();
1501
1502     const QTextItemInt &ti = static_cast<const QTextItemInt &>(textItem);
1503
1504     QTransform::TransformationType txtype = s->matrix.type();
1505
1506     float det = s->matrix.determinant();
1507     bool drawCached = txtype < QTransform::TxProject;
1508
1509     // don't try to cache huge fonts or vastly transformed fonts
1510     const qreal pixelSize = ti.fontEngine->fontDef.pixelSize;
1511     if (pixelSize * pixelSize * qAbs(det) >= QT_MAX_CACHED_GLYPH_SIZE * QT_MAX_CACHED_GLYPH_SIZE ||
1512         det < 0.25f || det > 4.f)
1513         drawCached = false;
1514
1515     QFontEngineGlyphCache::Type glyphType = ti.fontEngine->glyphFormat >= 0
1516                                             ? QFontEngineGlyphCache::Type(ti.fontEngine->glyphFormat)
1517                                             : d->glyphCacheType;
1518
1519
1520     if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1521         if (d->device->alphaRequested() || txtype > QTransform::TxTranslate
1522             || (state()->composition_mode != QPainter::CompositionMode_Source
1523             && state()->composition_mode != QPainter::CompositionMode_SourceOver))
1524         {
1525             glyphType = QFontEngineGlyphCache::Raster_A8;
1526         }
1527     }
1528
1529     if (drawCached) {
1530         QVarLengthArray<QFixedPoint> positions;
1531         QVarLengthArray<glyph_t> glyphs;
1532         QTransform matrix = QTransform::fromTranslate(p.x(), p.y());
1533         ti.fontEngine->getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions);
1534
1535         {
1536             QStaticTextItem staticTextItem;
1537             staticTextItem.chars = const_cast<QChar *>(ti.chars);
1538             staticTextItem.setFontEngine(ti.fontEngine);
1539             staticTextItem.glyphs = glyphs.data();
1540             staticTextItem.numChars = ti.num_chars;
1541             staticTextItem.numGlyphs = glyphs.size();
1542             staticTextItem.glyphPositions = positions.data();
1543
1544             d->drawCachedGlyphs(glyphType, &staticTextItem);
1545         }
1546         return;
1547     }
1548
1549     QPaintEngineEx::drawTextItem(p, ti);
1550 }
1551
1552 namespace {
1553
1554     class QOpenGLStaticTextUserData: public QStaticTextUserData
1555     {
1556     public:
1557         QOpenGLStaticTextUserData()
1558             : QStaticTextUserData(OpenGLUserData), cacheSize(0, 0), cacheSerialNumber(0)
1559         {
1560         }
1561
1562         ~QOpenGLStaticTextUserData()
1563         {
1564         }
1565
1566         QSize cacheSize;
1567         QGL2PEXVertexArray vertexCoordinateArray;
1568         QGL2PEXVertexArray textureCoordinateArray;
1569         QFontEngineGlyphCache::Type glyphType;
1570         int cacheSerialNumber;
1571     };
1572
1573 }
1574
1575 #if defined(Q_WS_WIN)
1576 static bool fontSmoothingApproximately(qreal target)
1577 {
1578     extern Q_GUI_EXPORT qreal qt_fontsmoothing_gamma; // qapplication_win.cpp
1579     return (qAbs(qt_fontsmoothing_gamma - target) < 0.2);
1580 }
1581 #endif
1582
1583 static inline qreal qt_sRGB_to_linear_RGB(qreal f)
1584 {
1585     return f > 0.04045 ? qPow((f + 0.055) / 1.055, 2.4) : f / 12.92;
1586 }
1587
1588 // #define QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO
1589
1590 void QGL2PaintEngineExPrivate::drawCachedGlyphs(QFontEngineGlyphCache::Type glyphType,
1591                                                 QStaticTextItem *staticTextItem)
1592 {
1593     Q_Q(QGL2PaintEngineEx);
1594
1595     QOpenGL2PaintEngineState *s = q->state();
1596
1597     void *cacheKey = const_cast<QGLContext *>(QGLContextPrivate::contextGroup(ctx)->context());
1598     bool recreateVertexArrays = false;
1599
1600     QGLTextureGlyphCache *cache =
1601             (QGLTextureGlyphCache *) staticTextItem->fontEngine()->glyphCache(cacheKey, glyphType, QTransform());
1602     if (!cache || cache->cacheType() != glyphType || cache->context() == 0) {
1603         cache = new QGLTextureGlyphCache(ctx, glyphType, QTransform());
1604         staticTextItem->fontEngine()->setGlyphCache(cacheKey, cache);
1605         cache->insert(ctx, cache);
1606         recreateVertexArrays = true;
1607     }
1608
1609     if (staticTextItem->userDataNeedsUpdate) {
1610         recreateVertexArrays = true;
1611     } else if (staticTextItem->userData() == 0) {
1612         recreateVertexArrays = true;
1613     } else if (staticTextItem->userData()->type != QStaticTextUserData::OpenGLUserData) {
1614         recreateVertexArrays = true;
1615     } else {
1616         QOpenGLStaticTextUserData *userData = static_cast<QOpenGLStaticTextUserData *>(staticTextItem->userData());
1617         if (userData->glyphType != glyphType) {
1618             recreateVertexArrays = true;
1619         } else if (userData->cacheSerialNumber != cache->serialNumber()) {
1620             recreateVertexArrays = true;
1621         }
1622     }
1623
1624     // We only need to update the cache with new glyphs if we are actually going to recreate the vertex arrays.
1625     // If the cache size has changed, we do need to regenerate the vertices, but we don't need to repopulate the
1626     // cache so this text is performed before we test if the cache size has changed.
1627     if (recreateVertexArrays) {
1628         cache->setPaintEnginePrivate(this);
1629         if (!cache->populate(staticTextItem->fontEngine(), staticTextItem->numGlyphs,
1630                              staticTextItem->glyphs, staticTextItem->glyphPositions)) {
1631             // No space for glyphs in cache. We need to reset it and try again.
1632             cache->clear();
1633             cache->populate(staticTextItem->fontEngine(), staticTextItem->numGlyphs,
1634                             staticTextItem->glyphs, staticTextItem->glyphPositions);
1635         }
1636         cache->fillInPendingGlyphs();
1637     }
1638
1639     if (cache->width() == 0 || cache->height() == 0)
1640         return;
1641
1642     transferMode(TextDrawingMode);
1643
1644     int margin = cache->glyphMargin();
1645
1646     GLfloat dx = 1.0 / cache->width();
1647     GLfloat dy = 1.0 / cache->height();
1648
1649     // Use global arrays by default
1650     QGL2PEXVertexArray *vertexCoordinates = &vertexCoordinateArray;
1651     QGL2PEXVertexArray *textureCoordinates = &textureCoordinateArray;
1652
1653     if (staticTextItem->useBackendOptimizations) {
1654         QOpenGLStaticTextUserData *userData = 0;
1655
1656         if (staticTextItem->userData() == 0
1657             || staticTextItem->userData()->type != QStaticTextUserData::OpenGLUserData) {
1658
1659             userData = new QOpenGLStaticTextUserData();
1660             staticTextItem->setUserData(userData);
1661
1662         } else {
1663             userData = static_cast<QOpenGLStaticTextUserData*>(staticTextItem->userData());
1664         }
1665
1666         userData->glyphType = glyphType;
1667         userData->cacheSerialNumber = cache->serialNumber();
1668
1669         // Use cache if backend optimizations is turned on
1670         vertexCoordinates = &userData->vertexCoordinateArray;
1671         textureCoordinates = &userData->textureCoordinateArray;
1672
1673         QSize size(cache->width(), cache->height());
1674         if (userData->cacheSize != size) {
1675             recreateVertexArrays = true;
1676             userData->cacheSize = size;
1677         }
1678     }
1679
1680     if (recreateVertexArrays) {
1681         vertexCoordinates->clear();
1682         textureCoordinates->clear();
1683
1684         bool supportsSubPixelPositions = staticTextItem->fontEngine()->supportsSubPixelPositions();
1685         for (int i=0; i<staticTextItem->numGlyphs; ++i) {
1686             QFixed subPixelPosition;
1687             if (supportsSubPixelPositions)
1688                 subPixelPosition = cache->subPixelPositionForX(staticTextItem->glyphPositions[i].x);
1689
1690             QTextureGlyphCache::GlyphAndSubPixelPosition glyph(staticTextItem->glyphs[i], subPixelPosition);
1691
1692             const QTextureGlyphCache::Coord &c = cache->coords[glyph];
1693             if (c.isNull())
1694                 continue;
1695
1696             int x = qFloor(staticTextItem->glyphPositions[i].x) + c.baseLineX - margin;
1697             int y = qFloor(staticTextItem->glyphPositions[i].y) - c.baseLineY - margin;
1698
1699             vertexCoordinates->addQuad(QRectF(x, y, c.w, c.h));
1700             textureCoordinates->addQuad(QRectF(c.x*dx, c.y*dy, c.w * dx, c.h * dy));
1701         }
1702
1703         staticTextItem->userDataNeedsUpdate = false;
1704     }
1705
1706     int numGlyphs = vertexCoordinates->vertexCount() / 4;
1707     if (numGlyphs == 0)
1708         return;
1709
1710     if (elementIndices.size() < numGlyphs*6) {
1711         Q_ASSERT(elementIndices.size() % 6 == 0);
1712         int j = elementIndices.size() / 6 * 4;
1713         while (j < numGlyphs*4) {
1714             elementIndices.append(j + 0);
1715             elementIndices.append(j + 0);
1716             elementIndices.append(j + 1);
1717             elementIndices.append(j + 2);
1718             elementIndices.append(j + 3);
1719             elementIndices.append(j + 3);
1720
1721             j += 4;
1722         }
1723
1724 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1725         if (elementIndicesVBOId == 0)
1726             glGenBuffers(1, &elementIndicesVBOId);
1727
1728         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
1729         glBufferData(GL_ELEMENT_ARRAY_BUFFER, elementIndices.size() * sizeof(GLushort),
1730                      elementIndices.constData(), GL_STATIC_DRAW);
1731 #endif
1732     } else {
1733 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1734         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
1735 #endif
1736     }
1737
1738     setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)vertexCoordinates->data());
1739     setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, (GLfloat*)textureCoordinates->data());
1740
1741     if (!snapToPixelGrid) {
1742         snapToPixelGrid = true;
1743         matrixDirty = true;
1744     }
1745
1746     QBrush pensBrush = q->state()->pen.brush();
1747
1748     bool srgbFrameBufferEnabled = false;
1749     if (pensBrush.style() == Qt::SolidPattern &&
1750         (ctx->d_ptr->extension_flags & QGLExtensions::SRGBFrameBuffer)) {
1751 #if defined(Q_WS_MAC)
1752         if (glyphType == QFontEngineGlyphCache::Raster_RGBMask)
1753 #elif defined(Q_WS_WIN)
1754         if (glyphType != QFontEngineGlyphCache::Raster_RGBMask || fontSmoothingApproximately(2.1))
1755 #else
1756         if (false)
1757 #endif
1758         {
1759             QColor c = pensBrush.color();
1760             qreal red = qt_sRGB_to_linear_RGB(c.redF());
1761             qreal green = qt_sRGB_to_linear_RGB(c.greenF());
1762             qreal blue = qt_sRGB_to_linear_RGB(c.blueF());
1763             c = QColor::fromRgbF(red, green, blue, c.alphaF());
1764             pensBrush.setColor(c);
1765
1766             glEnable(FRAMEBUFFER_SRGB_EXT);
1767             srgbFrameBufferEnabled = true;
1768         }
1769     }
1770
1771     setBrush(pensBrush);
1772
1773     if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1774         // Subpixel antialiasing with gamma correction
1775         QPainter::CompositionMode compMode = q->state()->composition_mode;
1776         Q_ASSERT(compMode == QPainter::CompositionMode_Source
1777             || compMode == QPainter::CompositionMode_SourceOver);
1778
1779         shaderManager->setMaskType(QGLEngineShaderManager::SubPixelMaskPass1);
1780
1781         if (pensBrush.style() == Qt::SolidPattern) {
1782             // Solid patterns can get away with only one pass.
1783             QColor c = pensBrush.color();
1784             qreal oldOpacity = q->state()->opacity;
1785             if (compMode == QPainter::CompositionMode_Source) {
1786                 c = qt_premultiplyColor(c, q->state()->opacity);
1787                 q->state()->opacity = 1;
1788                 opacityUniformDirty = true;
1789             }
1790
1791             compositionModeDirty = false; // I can handle this myself, thank you very much
1792             prepareForDraw(false); // Text always causes src pixels to be transparent
1793
1794             // prepareForDraw() have set the opacity on the current shader, so the opacity state can now be reset.
1795             if (compMode == QPainter::CompositionMode_Source) {
1796                 q->state()->opacity = oldOpacity;
1797                 opacityUniformDirty = true;
1798             }
1799
1800             glEnable(GL_BLEND);
1801             glBlendFunc(GL_CONSTANT_COLOR, GL_ONE_MINUS_SRC_COLOR);
1802             glBlendColor(c.redF(), c.greenF(), c.blueF(), c.alphaF());
1803         } else {
1804             // Other brush styles need two passes.
1805
1806             qreal oldOpacity = q->state()->opacity;
1807             if (compMode == QPainter::CompositionMode_Source) {
1808                 q->state()->opacity = 1;
1809                 opacityUniformDirty = true;
1810                 pensBrush = Qt::white;
1811                 setBrush(pensBrush);
1812             }
1813
1814             compositionModeDirty = false; // I can handle this myself, thank you very much
1815             prepareForDraw(false); // Text always causes src pixels to be transparent
1816             glEnable(GL_BLEND);
1817             glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR);
1818
1819             glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
1820             glBindTexture(GL_TEXTURE_2D, cache->texture());
1821 #if !defined(QT_NO_DEBUG) && defined(QT_OPENGL_ES_2)
1822             QGLFunctions funcs(QGLContext::currentContext());
1823             bool npotSupported = funcs.hasOpenGLFeature(QGLFunctions::NPOTTextures);
1824             bool isNpot = !isPowerOfTwo(cache->width())
1825                 || !isPowerOfTwo(cache->height());
1826             if (isNpot && !npotSupported) {
1827                 qWarning("GL2 Paint Engine: This system does not support the REPEAT wrap mode for non-power-of-two textures.");
1828             }
1829 #endif
1830             updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, false);
1831
1832 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1833             glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
1834 #else
1835             glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, elementIndices.data());
1836 #endif
1837
1838             shaderManager->setMaskType(QGLEngineShaderManager::SubPixelMaskPass2);
1839
1840             if (compMode == QPainter::CompositionMode_Source) {
1841                 q->state()->opacity = oldOpacity;
1842                 opacityUniformDirty = true;
1843                 pensBrush = q->state()->pen.brush();
1844                 setBrush(pensBrush);
1845             }
1846
1847             compositionModeDirty = false;
1848             prepareForDraw(false); // Text always causes src pixels to be transparent
1849             glEnable(GL_BLEND);
1850             glBlendFunc(GL_ONE, GL_ONE);
1851         }
1852         compositionModeDirty = true;
1853     } else {
1854         // Greyscale/mono glyphs
1855
1856         shaderManager->setMaskType(QGLEngineShaderManager::PixelMask);
1857         prepareForDraw(false); // Text always causes src pixels to be transparent
1858     }
1859
1860     QGLTextureGlyphCache::FilterMode filterMode = (s->matrix.type() > QTransform::TxTranslate)?QGLTextureGlyphCache::Linear:QGLTextureGlyphCache::Nearest;
1861     if (lastMaskTextureUsed != cache->texture() || cache->filterMode() != filterMode) {
1862
1863         glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
1864         if (lastMaskTextureUsed != cache->texture()) {
1865             glBindTexture(GL_TEXTURE_2D, cache->texture());
1866             lastMaskTextureUsed = cache->texture();
1867         }
1868
1869         if (cache->filterMode() != filterMode) {
1870             if (filterMode == QGLTextureGlyphCache::Linear) {
1871                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1872                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1873             } else {
1874                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1875                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1876             }
1877             cache->setFilterMode(filterMode);
1878         }
1879     }
1880
1881 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1882     glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
1883     glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1884 #else
1885     glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, elementIndices.data());
1886 #endif
1887
1888     if (srgbFrameBufferEnabled)
1889         glDisable(FRAMEBUFFER_SRGB_EXT);
1890
1891 }
1892
1893 void QGL2PaintEngineEx::drawPixmapFragments(const QPainter::PixmapFragment *fragments, int fragmentCount, const QPixmap &pixmap,
1894                                             QPainter::PixmapFragmentHints hints)
1895 {
1896     Q_D(QGL2PaintEngineEx);
1897     // Use fallback for extended composition modes.
1898     if (state()->composition_mode > QPainter::CompositionMode_Plus) {
1899         QPaintEngineEx::drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
1900         return;
1901     }
1902
1903     QSize size = pixmap.size();
1904
1905     ensureActive();
1906     int max_texture_size = d->ctx->d_func()->maxTextureSize();
1907     if (size.width() > max_texture_size || size.height() > max_texture_size) {
1908         QPixmap scaled = pixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1909         d->drawPixmapFragments(fragments, fragmentCount, scaled, size, hints);
1910     } else {
1911         d->drawPixmapFragments(fragments, fragmentCount, pixmap, size, hints);
1912     }
1913 }
1914
1915 void QGL2PaintEngineEx::drawPixmapFragments(const QRectF *targetRects, const QRectF *sourceRects, int fragmentCount, const QPixmap &pixmap,
1916                                             QPainter::PixmapFragmentHints hints)
1917 {
1918     Q_D(QGL2PaintEngineEx);
1919     // Use fallback for extended composition modes.
1920     if (state()->composition_mode > QPainter::CompositionMode_Plus) {
1921         QPaintEngineEx::drawPixmapFragments(targetRects, sourceRects, fragmentCount, pixmap, hints);
1922         return;
1923     }
1924
1925     QSize size = pixmap.size();
1926
1927     ensureActive();
1928     int max_texture_size = d->ctx->d_func()->maxTextureSize();
1929     if (size.width() > max_texture_size || size.height() > max_texture_size) {
1930         QPixmap scaled = pixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1931         d->drawPixmapFragments(targetRects, sourceRects, fragmentCount, scaled, size, hints);
1932     } else {
1933         d->drawPixmapFragments(targetRects, sourceRects, fragmentCount, pixmap, size, hints);
1934     }
1935 }
1936
1937 void QGL2PaintEngineExPrivate::drawPixmapFragments(const QPainter::PixmapFragment *fragments,
1938                                                    int fragmentCount, const QPixmap &pixmap,
1939                                                    const QSize &size, QPainter::PixmapFragmentHints hints)
1940 {
1941     GLfloat dx = 1.0f / size.width();
1942     GLfloat dy = 1.0f / size.height();
1943
1944     vertexCoordinateArray.clear();
1945     textureCoordinateArray.clear();
1946     opacityArray.reset();
1947
1948     if (snapToPixelGrid) {
1949         snapToPixelGrid = false;
1950         matrixDirty = true;
1951     }
1952
1953     bool allOpaque = true;
1954
1955     for (int i = 0; i < fragmentCount; ++i) {
1956         qreal s = 0;
1957         qreal c = 1;
1958         if (fragments[i].rotation != 0) {
1959             s = qFastSin(fragments[i].rotation * Q_PI / 180);
1960             c = qFastCos(fragments[i].rotation * Q_PI / 180);
1961         }
1962
1963         qreal right = 0.5 * fragments[i].scaleX * fragments[i].width;
1964         qreal bottom = 0.5 * fragments[i].scaleY * fragments[i].height;
1965         QGLPoint bottomRight(right * c - bottom * s, right * s + bottom * c);
1966         QGLPoint bottomLeft(-right * c - bottom * s, -right * s + bottom * c);
1967
1968         vertexCoordinateArray.addVertex(bottomRight.x + fragments[i].x, bottomRight.y + fragments[i].y);
1969         vertexCoordinateArray.addVertex(-bottomLeft.x + fragments[i].x, -bottomLeft.y + fragments[i].y);
1970         vertexCoordinateArray.addVertex(-bottomRight.x + fragments[i].x, -bottomRight.y + fragments[i].y);
1971         vertexCoordinateArray.addVertex(-bottomRight.x + fragments[i].x, -bottomRight.y + fragments[i].y);
1972         vertexCoordinateArray.addVertex(bottomLeft.x + fragments[i].x, bottomLeft.y + fragments[i].y);
1973         vertexCoordinateArray.addVertex(bottomRight.x + fragments[i].x, bottomRight.y + fragments[i].y);
1974
1975         QGLRect src(fragments[i].sourceLeft * dx, fragments[i].sourceTop * dy,
1976                     (fragments[i].sourceLeft + fragments[i].width) * dx,
1977                     (fragments[i].sourceTop + fragments[i].height) * dy);
1978
1979         textureCoordinateArray.addVertex(src.right, src.bottom);
1980         textureCoordinateArray.addVertex(src.right, src.top);
1981         textureCoordinateArray.addVertex(src.left, src.top);
1982         textureCoordinateArray.addVertex(src.left, src.top);
1983         textureCoordinateArray.addVertex(src.left, src.bottom);
1984         textureCoordinateArray.addVertex(src.right, src.bottom);
1985
1986         qreal opacity = fragments[i].opacity * q->state()->opacity;
1987         opacityArray << opacity << opacity << opacity << opacity << opacity << opacity;
1988         allOpaque &= (opacity >= 0.99f);
1989     }
1990
1991     glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1992     QGLTexture *texture = ctx->d_func()->bindTexture(pixmap, GL_TEXTURE_2D, GL_RGBA,
1993                                                      QGLContext::InternalBindOption
1994                                                      | QGLContext::CanFlipNativePixmapBindOption);
1995
1996     if (texture->options & QGLContext::InvertedYBindOption) {
1997         // Flip texture y-coordinate.
1998         QGLPoint *data = textureCoordinateArray.data();
1999         for (int i = 0; i < 6 * fragmentCount; ++i)
2000             data[i].y = 1 - data[i].y;
2001     }
2002
2003     transferMode(allOpaque ? ImageArrayDrawingMode : ImageArrayWithOpacityDrawingMode);
2004
2005     bool isBitmap = pixmap.isQBitmap();
2006     bool isOpaque = !isBitmap && (!pixmap.hasAlpha() || (hints & QPainter::OpaqueHint)) && allOpaque;
2007
2008     updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
2009                            q->state()->renderHints & QPainter::SmoothPixmapTransform, texture->id);
2010
2011     // Setup for texture drawing
2012     currentBrush = noBrush;
2013     shaderManager->setSrcPixelType(isBitmap ? QGLEngineShaderManager::PatternSrc
2014                                             : QGLEngineShaderManager::ImageSrc);
2015     if (prepareForDraw(isOpaque))
2016         shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::ImageTexture), QT_IMAGE_TEXTURE_UNIT);
2017
2018     if (isBitmap) {
2019         QColor col = qt_premultiplyColor(q->state()->pen.color(), (GLfloat)q->state()->opacity);
2020         shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::PatternColor), col);
2021     }
2022
2023     glDrawArrays(GL_TRIANGLES, 0, 6 * fragmentCount);
2024 }
2025
2026 void QGL2PaintEngineExPrivate::drawPixmapFragments(const QRectF *targetRects, const QRectF *sourceRects, int fragmentCount,
2027                                                    const QPixmap &pixmap, const QSize &size,
2028                                                    QPainter::PixmapFragmentHints hints)
2029 {
2030     GLfloat dx = 1.0f / size.width();
2031     GLfloat dy = 1.0f / size.height();
2032
2033     vertexCoordinateArray.clear();
2034     textureCoordinateArray.clear();
2035
2036     if (snapToPixelGrid) {
2037         snapToPixelGrid = false;
2038         matrixDirty = true;
2039     }
2040
2041     for (int i = 0; i < fragmentCount; ++i) {
2042         vertexCoordinateArray.addVertex(targetRects[i].right(), targetRects[i].bottom());
2043         vertexCoordinateArray.addVertex(targetRects[i].right(), targetRects[i].top());
2044         vertexCoordinateArray.addVertex(targetRects[i].left(), targetRects[i].top());
2045         vertexCoordinateArray.addVertex(targetRects[i].left(), targetRects[i].top());
2046         vertexCoordinateArray.addVertex(targetRects[i].left(), targetRects[i].bottom());
2047         vertexCoordinateArray.addVertex(targetRects[i].right(), targetRects[i].bottom());
2048
2049         QRectF sourceRect = sourceRects ? sourceRects[i] : QRectF(0, 0, size.width(), size.height());
2050
2051         QGLRect src(sourceRect.left() * dx, sourceRect.top() * dy,
2052                     sourceRect.right() * dx, sourceRect.bottom() * dy);
2053
2054         textureCoordinateArray.addVertex(src.right, src.bottom);
2055         textureCoordinateArray.addVertex(src.right, src.top);
2056         textureCoordinateArray.addVertex(src.left, src.top);
2057         textureCoordinateArray.addVertex(src.left, src.top);
2058         textureCoordinateArray.addVertex(src.left, src.bottom);
2059         textureCoordinateArray.addVertex(src.right, src.bottom);
2060     }
2061
2062     glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
2063     QGLTexture *texture = ctx->d_func()->bindTexture(pixmap, GL_TEXTURE_2D, GL_RGBA,
2064                                                      QGLContext::InternalBindOption
2065                                                      | QGLContext::CanFlipNativePixmapBindOption);
2066
2067     if (texture->options & QGLContext::InvertedYBindOption) {
2068         // Flip texture y-coordinate.
2069         QGLPoint *data = textureCoordinateArray.data();
2070         for (int i = 0; i < 6 * fragmentCount; ++i)
2071             data[i].y = 1 - data[i].y;
2072     }
2073
2074     transferMode(ImageArrayDrawingMode);
2075
2076     bool isBitmap = pixmap.isQBitmap();
2077     bool isOpaque = !isBitmap && (!pixmap.hasAlpha() || (hints & QPainter::OpaqueHint));
2078
2079     updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
2080                            q->state()->renderHints & QPainter::SmoothPixmapTransform, texture->id);
2081
2082     // Setup for texture drawing
2083     currentBrush = noBrush;
2084     shaderManager->setSrcPixelType(isBitmap ? QGLEngineShaderManager::PatternSrc
2085                                             : QGLEngineShaderManager::ImageSrc);
2086     if (prepareForDraw(isOpaque))
2087         shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::ImageTexture), QT_IMAGE_TEXTURE_UNIT);
2088
2089     if (isBitmap) {
2090         QColor col = qt_premultiplyColor(q->state()->pen.color(), (GLfloat)q->state()->opacity);
2091         shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::PatternColor), col);
2092     }
2093
2094     glDrawArrays(GL_TRIANGLES, 0, 6 * fragmentCount);
2095 }
2096
2097 bool QGL2PaintEngineEx::begin(QPaintDevice *pdev)
2098 {
2099     Q_D(QGL2PaintEngineEx);
2100
2101 //     qDebug("QGL2PaintEngineEx::begin()");
2102     if (pdev->devType() == QInternal::OpenGL)
2103         d->device = static_cast<QGLPaintDevice*>(pdev);
2104     else
2105         d->device = QGLPaintDevice::getDevice(pdev);
2106
2107     if (!d->device)
2108         return false;
2109
2110     d->ctx = d->device->context();
2111     d->ctx->d_ptr->active_engine = this;
2112
2113     const QSize sz = d->device->size();
2114     d->width = sz.width();
2115     d->height = sz.height();
2116     d->mode = BrushDrawingMode;
2117     d->imageDrawingMode = false;
2118     d->brushTextureDirty = true;
2119     d->brushUniformsDirty = true;
2120     d->matrixUniformDirty = true;
2121     d->matrixDirty = true;
2122     d->compositionModeDirty = true;
2123     d->opacityUniformDirty = true;
2124     d->needsSync = true;
2125     d->useSystemClip = !systemClip().isEmpty();
2126     d->currentBrush = QBrush();
2127
2128     d->dirtyStencilRegion = QRect(0, 0, d->width, d->height);
2129     d->stencilClean = true;
2130
2131     // Calling begin paint should make the correct context current. So, any
2132     // code which calls into GL or otherwise needs a current context *must*
2133     // go after beginPaint:
2134     d->device->beginPaint();
2135
2136 #if !defined(QT_OPENGL_ES_2)
2137     bool success = qt_resolve_version_2_0_functions(d->ctx)
2138                    && qt_resolve_buffer_extensions(d->ctx);
2139     Q_ASSERT(success);
2140     Q_UNUSED(success);
2141 #endif
2142
2143     d->shaderManager = new QGLEngineShaderManager(d->ctx);
2144
2145     glDisable(GL_STENCIL_TEST);
2146     glDisable(GL_DEPTH_TEST);
2147     glDisable(GL_SCISSOR_TEST);
2148
2149 #if !defined(QT_OPENGL_ES_2)
2150     glDisable(GL_MULTISAMPLE);
2151 #endif
2152
2153     d->glyphCacheType = QFontEngineGlyphCache::Raster_A8;
2154
2155 #if !defined(QT_OPENGL_ES_2)
2156 #if defined(Q_WS_WIN)
2157     if (qt_cleartype_enabled
2158         && (fontSmoothingApproximately(1.0) || fontSmoothingApproximately(2.1)))
2159 #endif
2160 #if defined(Q_WS_MAC)
2161     if (qt_applefontsmoothing_enabled)
2162 #endif
2163         d->glyphCacheType = QFontEngineGlyphCache::Raster_RGBMask;
2164 #endif
2165
2166 #if defined(QT_OPENGL_ES_2)
2167     // OpenGL ES can't switch MSAA off, so if the gl paint device is
2168     // multisampled, it's always multisampled.
2169     d->multisamplingAlwaysEnabled = d->device->format().sampleBuffers();
2170 #else
2171     d->multisamplingAlwaysEnabled = false;
2172 #endif
2173
2174     return true;
2175 }
2176
2177 bool QGL2PaintEngineEx::end()
2178 {
2179     Q_D(QGL2PaintEngineEx);
2180
2181     QGLContext *ctx = d->ctx;
2182     glUseProgram(0);
2183     d->transferMode(BrushDrawingMode);
2184     d->device->endPaint();
2185
2186 #if defined(Q_WS_X11)
2187     // On some (probably all) drivers, deleting an X pixmap which has been bound to a texture
2188     // before calling glFinish/swapBuffers renders garbage. Presumably this is because X deletes
2189     // the pixmap behind the driver's back before it's had a chance to use it. To fix this, we
2190     // reference all QPixmaps which have been bound to stop them being deleted and only deref
2191     // them here, after swapBuffers, where they can be safely deleted.
2192     ctx->d_func()->boundPixmaps.clear();
2193 #endif
2194     d->ctx->d_ptr->active_engine = 0;
2195
2196     d->resetGLState();
2197
2198     delete d->shaderManager;
2199     d->shaderManager = 0;
2200     d->currentBrush = QBrush();
2201
2202 #ifdef QT_OPENGL_CACHE_AS_VBOS
2203     if (!d->unusedVBOSToClean.isEmpty()) {
2204         glDeleteBuffers(d->unusedVBOSToClean.size(), d->unusedVBOSToClean.constData());
2205         d->unusedVBOSToClean.clear();
2206     }
2207     if (!d->unusedIBOSToClean.isEmpty()) {
2208         glDeleteBuffers(d->unusedIBOSToClean.size(), d->unusedIBOSToClean.constData());
2209         d->unusedIBOSToClean.clear();
2210     }
2211 #endif
2212
2213     return false;
2214 }
2215
2216 void QGL2PaintEngineEx::ensureActive()
2217 {
2218     Q_D(QGL2PaintEngineEx);
2219     QGLContext *ctx = d->ctx;
2220
2221     if (isActive() && ctx->d_ptr->active_engine != this) {
2222         ctx->d_ptr->active_engine = this;
2223         d->needsSync = true;
2224     }
2225
2226     d->device->ensureActiveTarget();
2227
2228     if (d->needsSync) {
2229         d->transferMode(BrushDrawingMode);
2230         glViewport(0, 0, d->width, d->height);
2231         d->needsSync = false;
2232         d->lastMaskTextureUsed = 0;
2233         d->shaderManager->setDirty();
2234         d->ctx->d_func()->syncGlState();
2235         for (int i = 0; i < 3; ++i)
2236             d->vertexAttribPointers[i] = (GLfloat*)-1; // Assume the pointers are clobbered
2237         setState(state());
2238     }
2239 }
2240
2241 void QGL2PaintEngineExPrivate::updateClipScissorTest()
2242 {
2243     Q_Q(QGL2PaintEngineEx);
2244     if (q->state()->clipTestEnabled) {
2245         glEnable(GL_STENCIL_TEST);
2246         glStencilFunc(GL_LEQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
2247     } else {
2248         glDisable(GL_STENCIL_TEST);
2249         glStencilFunc(GL_ALWAYS, 0, 0xff);
2250     }
2251
2252 #ifdef QT_GL_NO_SCISSOR_TEST
2253     currentScissorBounds = QRect(0, 0, width, height);
2254 #else
2255     QRect bounds = q->state()->rectangleClip;
2256     if (!q->state()->clipEnabled) {
2257         if (useSystemClip)
2258             bounds = systemClip.boundingRect();
2259         else
2260             bounds = QRect(0, 0, width, height);
2261     } else {
2262         if (useSystemClip)
2263             bounds = bounds.intersected(systemClip.boundingRect());
2264         else
2265             bounds = bounds.intersected(QRect(0, 0, width, height));
2266     }
2267
2268     currentScissorBounds = bounds;
2269
2270     if (bounds == QRect(0, 0, width, height)) {
2271         glDisable(GL_SCISSOR_TEST);
2272     } else {
2273         glEnable(GL_SCISSOR_TEST);
2274         setScissor(bounds);
2275     }
2276 #endif
2277 }
2278
2279 void QGL2PaintEngineExPrivate::setScissor(const QRect &rect)
2280 {
2281     const int left = rect.left();
2282     const int width = rect.width();
2283     int bottom = height - (rect.top() + rect.height());
2284     if (device->isFlipped()) {
2285         bottom = rect.top();
2286     }
2287     const int height = rect.height();
2288
2289     glScissor(left, bottom, width, height);
2290 }
2291
2292 void QGL2PaintEngineEx::clipEnabledChanged()
2293 {
2294     Q_D(QGL2PaintEngineEx);
2295
2296     state()->clipChanged = true;
2297
2298     if (painter()->hasClipping())
2299         d->regenerateClip();
2300     else
2301         d->systemStateChanged();
2302 }
2303
2304 void QGL2PaintEngineExPrivate::clearClip(uint value)
2305 {
2306     dirtyStencilRegion -= currentScissorBounds;
2307
2308     glStencilMask(0xff);
2309     glClearStencil(value);
2310     glClear(GL_STENCIL_BUFFER_BIT);
2311     glStencilMask(0x0);
2312
2313     q->state()->needsClipBufferClear = false;
2314 }
2315
2316 void QGL2PaintEngineExPrivate::writeClip(const QVectorPath &path, uint value)
2317 {
2318     transferMode(BrushDrawingMode);
2319
2320     if (snapToPixelGrid) {
2321         snapToPixelGrid = false;
2322         matrixDirty = true;
2323     }
2324
2325     if (matrixDirty)
2326         updateMatrix();
2327
2328     stencilClean = false;
2329
2330     const bool singlePass = !path.hasWindingFill()
2331         && (((q->state()->currentClip == maxClip - 1) && q->state()->clipTestEnabled)
2332             || q->state()->needsClipBufferClear);
2333     const uint referenceClipValue = q->state()->needsClipBufferClear ? 1 : q->state()->currentClip;
2334
2335     if (q->state()->needsClipBufferClear)
2336         clearClip(1);
2337
2338     if (path.isEmpty()) {
2339         glEnable(GL_STENCIL_TEST);
2340         glStencilFunc(GL_LEQUAL, value, ~GL_STENCIL_HIGH_BIT);
2341         return;
2342     }
2343
2344     if (q->state()->clipTestEnabled)
2345         glStencilFunc(GL_LEQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
2346     else
2347         glStencilFunc(GL_ALWAYS, 0, 0xff);
2348
2349     vertexCoordinateArray.clear();
2350     vertexCoordinateArray.addPath(path, inverseScale, false);
2351
2352     if (!singlePass)
2353         fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill());
2354
2355     glColorMask(false, false, false, false);
2356     glEnable(GL_STENCIL_TEST);
2357     useSimpleShader();
2358
2359     if (singlePass) {
2360         // Under these conditions we can set the new stencil value in a single
2361         // pass, by using the current value and the "new value" as the toggles
2362
2363         glStencilFunc(GL_LEQUAL, referenceClipValue, ~GL_STENCIL_HIGH_BIT);
2364         glStencilOp(GL_KEEP, GL_INVERT, GL_INVERT);
2365         glStencilMask(value ^ referenceClipValue);
2366
2367         drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN);
2368     } else {
2369         glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
2370         glStencilMask(0xff);
2371
2372         if (!q->state()->clipTestEnabled && path.hasWindingFill()) {
2373             // Pass when any clip bit is set, set high bit
2374             glStencilFunc(GL_NOTEQUAL, GL_STENCIL_HIGH_BIT, ~GL_STENCIL_HIGH_BIT);
2375             composite(vertexCoordinateArray.boundingRect());
2376         }
2377
2378         // Pass when high bit is set, replace stencil value with new clip value
2379         glStencilFunc(GL_NOTEQUAL, value, GL_STENCIL_HIGH_BIT);
2380
2381         composite(vertexCoordinateArray.boundingRect());
2382     }
2383
2384     glStencilFunc(GL_LEQUAL, value, ~GL_STENCIL_HIGH_BIT);
2385     glStencilMask(0);
2386
2387     glColorMask(true, true, true, true);
2388 }
2389
2390 void QGL2PaintEngineEx::clip(const QVectorPath &path, Qt::ClipOperation op)
2391 {
2392 //     qDebug("QGL2PaintEngineEx::clip()");
2393     Q_D(QGL2PaintEngineEx);
2394
2395     state()->clipChanged = true;
2396
2397     ensureActive();
2398
2399     if (op == Qt::ReplaceClip) {
2400         op = Qt::IntersectClip;
2401         if (d->hasClipOperations()) {
2402             d->systemStateChanged();
2403             state()->canRestoreClip = false;
2404         }
2405     }
2406
2407 #ifndef QT_GL_NO_SCISSOR_TEST
2408     if (!path.isEmpty() && op == Qt::IntersectClip && (path.shape() == QVectorPath::RectangleHint)) {
2409         const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
2410         QRectF rect(points[0], points[2]);
2411
2412         if (state()->matrix.type() <= QTransform::TxScale
2413             || (state()->matrix.type() == QTransform::TxRotate
2414                 && qFuzzyIsNull(state()->matrix.m11())
2415                 && qFuzzyIsNull(state()->matrix.m22())))
2416         {
2417             state()->rectangleClip = state()->rectangleClip.intersected(state()->matrix.mapRect(rect).toRect());
2418             d->updateClipScissorTest();
2419             return;
2420         }
2421     }
2422 #endif
2423
2424     const QRect pathRect = state()->matrix.mapRect(path.controlPointRect()).toAlignedRect();
2425
2426     switch (op) {
2427     case Qt::NoClip:
2428         if (d->useSystemClip) {
2429             state()->clipTestEnabled = true;
2430             state()->currentClip = 1;
2431         } else {
2432             state()->clipTestEnabled = false;
2433         }
2434         state()->rectangleClip = QRect(0, 0, d->width, d->height);
2435         state()->canRestoreClip = false;
2436         d->updateClipScissorTest();
2437         break;
2438     case Qt::IntersectClip:
2439         state()->rectangleClip = state()->rectangleClip.intersected(pathRect);
2440         d->updateClipScissorTest();
2441         d->resetClipIfNeeded();
2442         ++d->maxClip;
2443         d->writeClip(path, d->maxClip);
2444         state()->currentClip = d->maxClip;
2445         state()->clipTestEnabled = true;
2446         break;
2447     case Qt::UniteClip: {
2448         d->resetClipIfNeeded();
2449         ++d->maxClip;
2450         if (state()->rectangleClip.isValid()) {
2451             QPainterPath path;
2452             path.addRect(state()->rectangleClip);
2453
2454             // flush the existing clip rectangle to the depth buffer
2455             d->writeClip(qtVectorPathForPath(state()->matrix.inverted().map(path)), d->maxClip);
2456         }
2457
2458         state()->clipTestEnabled = false;
2459 #ifndef QT_GL_NO_SCISSOR_TEST
2460         QRect oldRectangleClip = state()->rectangleClip;
2461
2462         state()->rectangleClip = state()->rectangleClip.united(pathRect);
2463         d->updateClipScissorTest();
2464
2465         QRegion extendRegion = QRegion(state()->rectangleClip) - oldRectangleClip;
2466
2467         if (!extendRegion.isEmpty()) {
2468             QPainterPath extendPath;
2469             extendPath.addRegion(extendRegion);
2470
2471             // first clear the depth buffer in the extended region
2472             d->writeClip(qtVectorPathForPath(state()->matrix.inverted().map(extendPath)), 0);
2473         }
2474 #endif
2475         // now write the clip path
2476         d->writeClip(path, d->maxClip);
2477         state()->canRestoreClip = false;
2478         state()->currentClip = d->maxClip;
2479         state()->clipTestEnabled = true;
2480         break;
2481         }
2482     default:
2483         break;
2484     }
2485 }
2486
2487 void QGL2PaintEngineExPrivate::regenerateClip()
2488 {
2489     systemStateChanged();
2490     replayClipOperations();
2491 }
2492
2493 void QGL2PaintEngineExPrivate::systemStateChanged()
2494 {
2495     Q_Q(QGL2PaintEngineEx);
2496
2497     q->state()->clipChanged = true;
2498
2499     if (systemClip.isEmpty()) {
2500         useSystemClip = false;
2501     } else {
2502         if (q->paintDevice()->devType() == QInternal::Widget && currentClipWidget) {
2503             QWidgetPrivate *widgetPrivate = qt_widget_private(currentClipWidget->window());
2504             useSystemClip = widgetPrivate->extra && widgetPrivate->extra->inRenderWithPainter;
2505         } else {
2506             useSystemClip = true;
2507         }
2508     }
2509
2510     q->state()->clipTestEnabled = false;
2511     q->state()->needsClipBufferClear = true;
2512
2513     q->state()->currentClip = 1;
2514     maxClip = 1;
2515
2516     q->state()->rectangleClip = useSystemClip ? systemClip.boundingRect() : QRect(0, 0, width, height);
2517     updateClipScissorTest();
2518
2519     if (systemClip.rectCount() == 1) {
2520         if (systemClip.boundingRect() == QRect(0, 0, width, height))
2521             useSystemClip = false;
2522 #ifndef QT_GL_NO_SCISSOR_TEST
2523         // scissoring takes care of the system clip
2524         return;
2525 #endif
2526     }
2527
2528     if (useSystemClip) {
2529         clearClip(0);
2530
2531         QPainterPath path;
2532         path.addRegion(systemClip);
2533
2534         q->state()->currentClip = 0;
2535         writeClip(qtVectorPathForPath(q->state()->matrix.inverted().map(path)), 1);
2536         q->state()->currentClip = 1;
2537         q->state()->clipTestEnabled = true;
2538     }
2539 }
2540
2541 void QGL2PaintEngineEx::setState(QPainterState *new_state)
2542 {
2543     //     qDebug("QGL2PaintEngineEx::setState()");
2544
2545     Q_D(QGL2PaintEngineEx);
2546
2547     QOpenGL2PaintEngineState *s = static_cast<QOpenGL2PaintEngineState *>(new_state);
2548     QOpenGL2PaintEngineState *old_state = state();
2549
2550     QPaintEngineEx::setState(s);
2551
2552     if (s->isNew) {
2553         // Newly created state object.  The call to setState()
2554         // will either be followed by a call to begin(), or we are
2555         // setting the state as part of a save().
2556         s->isNew = false;
2557         return;
2558     }
2559
2560     // Setting the state as part of a restore().
2561
2562     if (old_state == s || old_state->renderHintsChanged)
2563         renderHintsChanged();
2564
2565     if (old_state == s || old_state->matrixChanged)
2566         d->matrixDirty = true;
2567
2568     if (old_state == s || old_state->compositionModeChanged)
2569         d->compositionModeDirty =&