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