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