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