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