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