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