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