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