1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtGui module of the Qt Toolkit.
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.
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.
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.
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.
40 ****************************************************************************/
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
49 Updating uniforms should be cheap, so the overhead of updating up-to-date
50 uniforms should be minimal. It's also less complex.
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
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.
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.
65 // #define QT_OPENGL_CACHE_AS_VBOS
67 #include "qopenglgradientcache_p.h"
68 #include "qopengltexturecache_p.h"
69 #include "qopenglpaintengine_p.h"
71 #include <string.h> //for memcpy
74 #include <private/qopengl_p.h>
75 #include <private/qopenglcontext_p.h>
76 #include <private/qopenglextensions_p.h>
77 #include <private/qmath_p.h>
78 #include <private/qpaintengineex_p.h>
79 #include <QPaintEngine>
80 #include <private/qpainter_p.h>
81 #include <private/qfontengine_p.h>
82 #include <private/qdatabuffer_p.h>
83 #include <private/qstatictext_p.h>
84 #include <private/qtriangulator_p.h>
86 #include "qopenglengineshadermanager_p.h"
87 #include "qopengl2pexvertexarray_p.h"
88 #include "qopengltextureglyphcache_p.h"
96 Q_GUI_EXPORT QImage qt_imageForBrush(int brushStyle, bool invert);
98 ////////////////////////////////// Private Methods //////////////////////////////////////////
100 QOpenGL2PaintEngineExPrivate::~QOpenGL2PaintEngineExPrivate()
102 delete shaderManager;
104 while (pathCaches.size()) {
105 QVectorPath::CacheEntry *e = *(pathCaches.constBegin());
106 e->cleanup(e->engine, e->data);
111 if (elementIndicesVBOId != 0) {
112 funcs.glDeleteBuffers(1, &elementIndicesVBOId);
113 elementIndicesVBOId = 0;
117 void QOpenGL2PaintEngineExPrivate::updateTextureFilter(GLenum target, GLenum wrapMode, bool smoothPixmapTransform, GLuint id)
119 // funcs.glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT); //### Is it always this texture unit?
120 if (id != GLuint(-1) && id == lastTextureUsed)
123 lastTextureUsed = id;
125 if (smoothPixmapTransform) {
126 glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
127 glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
129 glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
130 glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
132 glTexParameteri(target, GL_TEXTURE_WRAP_S, wrapMode);
133 glTexParameteri(target, GL_TEXTURE_WRAP_T, wrapMode);
137 inline QColor qt_premultiplyColor(QColor c, GLfloat opacity)
139 qreal alpha = c.alphaF() * opacity;
141 c.setRedF(c.redF() * alpha);
142 c.setGreenF(c.greenF() * alpha);
143 c.setBlueF(c.blueF() * alpha);
148 void QOpenGL2PaintEngineExPrivate::setBrush(const QBrush& brush)
150 if (qbrush_fast_equals(currentBrush, brush))
153 const Qt::BrushStyle newStyle = qbrush_style(brush);
154 Q_ASSERT(newStyle != Qt::NoBrush);
156 currentBrush = brush;
157 if (!currentBrushPixmap.isNull())
158 currentBrushPixmap = QPixmap();
159 brushUniformsDirty = true; // All brushes have at least one uniform
161 if (newStyle > Qt::SolidPattern)
162 brushTextureDirty = true;
164 if (currentBrush.style() == Qt::TexturePattern
165 && qHasPixmapTexture(brush) && brush.texture().isQBitmap())
167 shaderManager->setSrcPixelType(QOpenGLEngineShaderManager::TextureSrcWithPattern);
169 shaderManager->setSrcPixelType(newStyle);
171 shaderManager->optimiseForBrushTransform(currentBrush.transform().type());
175 void QOpenGL2PaintEngineExPrivate::useSimpleShader()
177 shaderManager->useSimpleProgram();
183 void QOpenGL2PaintEngineExPrivate::updateBrushTexture()
185 Q_Q(QOpenGL2PaintEngineEx);
186 // qDebug("QOpenGL2PaintEngineExPrivate::updateBrushTexture()");
187 Qt::BrushStyle style = currentBrush.style();
189 if ( (style >= Qt::Dense1Pattern) && (style <= Qt::DiagCrossPattern) ) {
190 // Get the image data for the pattern
191 QImage texImage = qt_imageForBrush(style, false);
193 funcs.glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
194 QOpenGLTextureCache::cacheForContext(ctx)->bindTexture(ctx, texImage);
195 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
197 else if (style >= Qt::LinearGradientPattern && style <= Qt::ConicalGradientPattern) {
198 // Gradiant brush: All the gradiants use the same texture
200 const QGradient* g = currentBrush.gradient();
202 // We apply global opacity in the fragment shaders, so we always pass 1.0
203 // for opacity to the cache.
204 GLuint texId = QOpenGL2GradientCache::cacheForContext(ctx)->getBuffer(*g, 1.0);
206 funcs.glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
207 glBindTexture(GL_TEXTURE_2D, texId);
209 if (g->spread() == QGradient::RepeatSpread || g->type() == QGradient::ConicalGradient)
210 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
211 else if (g->spread() == QGradient::ReflectSpread)
212 updateTextureFilter(GL_TEXTURE_2D, GL_MIRRORED_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
214 updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE, q->state()->renderHints & QPainter::SmoothPixmapTransform);
216 else if (style == Qt::TexturePattern) {
217 currentBrushPixmap = currentBrush.texture();
219 int max_texture_size = ctx->d_func()->maxTextureSize();
220 if (currentBrushPixmap.width() > max_texture_size || currentBrushPixmap.height() > max_texture_size)
221 currentBrushPixmap = currentBrushPixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
223 funcs.glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
224 QOpenGLTextureCache::cacheForContext(ctx)->bindTexture(ctx, currentBrushPixmap);
225 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
226 textureInvertedY = false;
228 brushTextureDirty = false;
232 void QOpenGL2PaintEngineExPrivate::updateBrushUniforms()
234 // qDebug("QOpenGL2PaintEngineExPrivate::updateBrushUniforms()");
235 Qt::BrushStyle style = currentBrush.style();
237 if (style == Qt::NoBrush)
240 QTransform brushQTransform = currentBrush.transform();
242 if (style == Qt::SolidPattern) {
243 QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
244 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::FragmentColor), col);
247 // All other brushes have a transform and thus need the translation point:
248 QPointF translationPoint;
250 if (style <= Qt::DiagCrossPattern) {
251 QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
253 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::PatternColor), col);
255 QVector2D halfViewportSize(width*0.5, height*0.5);
256 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
258 else if (style == Qt::LinearGradientPattern) {
259 const QLinearGradient *g = static_cast<const QLinearGradient *>(currentBrush.gradient());
261 QPointF realStart = g->start();
262 QPointF realFinal = g->finalStop();
263 translationPoint = realStart;
265 QPointF l = realFinal - realStart;
267 QVector3D linearData(
270 1.0f / (l.x() * l.x() + l.y() * l.y())
273 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::LinearData), linearData);
275 QVector2D halfViewportSize(width*0.5, height*0.5);
276 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
278 else if (style == Qt::ConicalGradientPattern) {
279 const QConicalGradient *g = static_cast<const QConicalGradient *>(currentBrush.gradient());
280 translationPoint = g->center();
282 GLfloat angle = -(g->angle() * 2 * Q_PI) / 360.0;
284 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Angle), angle);
286 QVector2D halfViewportSize(width*0.5, height*0.5);
287 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
289 else if (style == Qt::RadialGradientPattern) {
290 const QRadialGradient *g = static_cast<const QRadialGradient *>(currentBrush.gradient());
291 QPointF realCenter = g->center();
292 QPointF realFocal = g->focalPoint();
293 qreal realRadius = g->centerRadius() - g->focalRadius();
294 translationPoint = realFocal;
296 QPointF fmp = realCenter - realFocal;
297 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Fmp), fmp);
299 GLfloat fmp2_m_radius2 = -fmp.x() * fmp.x() - fmp.y() * fmp.y() + realRadius*realRadius;
300 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Fmp2MRadius2), fmp2_m_radius2);
301 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Inverse2Fmp2MRadius2),
302 GLfloat(1.0 / (2.0*fmp2_m_radius2)));
303 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::SqrFr),
304 GLfloat(g->focalRadius() * g->focalRadius()));
305 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::BRadius),
306 GLfloat(2 * (g->centerRadius() - g->focalRadius()) * g->focalRadius()),
308 g->centerRadius() - g->focalRadius());
310 QVector2D halfViewportSize(width*0.5, height*0.5);
311 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
313 else if (style == Qt::TexturePattern) {
314 const QPixmap& texPixmap = currentBrush.texture();
316 if (qHasPixmapTexture(currentBrush) && currentBrush.texture().isQBitmap()) {
317 QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
318 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::PatternColor), col);
321 QSizeF invertedTextureSize(1.0 / texPixmap.width(), 1.0 / texPixmap.height());
322 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::InvertedTextureSize), invertedTextureSize);
324 QVector2D halfViewportSize(width*0.5, height*0.5);
325 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
328 qWarning("QOpenGL2PaintEngineEx: Unimplemented fill style");
330 const QPointF &brushOrigin = q->state()->brushOrigin;
331 QTransform matrix = q->state()->matrix;
332 matrix.translate(brushOrigin.x(), brushOrigin.y());
334 QTransform translate(1, 0, 0, 1, -translationPoint.x(), -translationPoint.y());
337 if (device->paintFlipped()) {
341 QTransform gl_to_qt(1, 0, 0, m22, 0, dy);
342 QTransform inv_matrix;
343 if (style == Qt::TexturePattern && textureInvertedY == -1)
344 inv_matrix = gl_to_qt * (QTransform(1, 0, 0, -1, 0, currentBrush.texture().height()) * brushQTransform * matrix).inverted() * translate;
346 inv_matrix = gl_to_qt * (brushQTransform * matrix).inverted() * translate;
348 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::BrushTransform), inv_matrix);
349 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::BrushTexture), QT_BRUSH_TEXTURE_UNIT);
351 brushUniformsDirty = false;
355 // This assumes the shader manager has already setup the correct shader program
356 void QOpenGL2PaintEngineExPrivate::updateMatrix()
358 // qDebug("QOpenGL2PaintEngineExPrivate::updateMatrix()");
360 const QTransform& transform = q->state()->matrix;
362 // The projection matrix converts from Qt's coordinate system to GL's coordinate system
363 // * GL's viewport is 2x2, Qt's is width x height
364 // * GL has +y -> -y going from bottom -> top, Qt is the other way round
365 // * GL has [0,0] in the center, Qt has it in the top-left
367 // This results in the Projection matrix below, which is multiplied by the painter's
368 // transformation matrix, as shown below:
370 // Projection Matrix Painter Transform
371 // ------------------------------------------------ ------------------------
372 // | 2.0 / width | 0.0 | -1.0 | | m11 | m21 | dx |
373 // | 0.0 | -2.0 / height | 1.0 | * | m12 | m22 | dy |
374 // | 0.0 | 0.0 | 1.0 | | m13 | m23 | m33 |
375 // ------------------------------------------------ ------------------------
377 // NOTE: The resultant matrix is also transposed, as GL expects column-major matracies
379 const GLfloat wfactor = 2.0f / width;
380 GLfloat hfactor = -2.0f / height;
382 GLfloat dx = transform.dx();
383 GLfloat dy = transform.dy();
385 if (device->paintFlipped()) {
390 // Non-integer translates can have strange effects for some rendering operations such as
391 // anti-aliased text rendering. In such cases, we snap the translate to the pixel grid.
392 if (snapToPixelGrid && transform.type() == QTransform::TxTranslate) {
393 // 0.50 needs to rounded down to 0.0 for consistency with raster engine:
394 dx = ceilf(dx - 0.5f);
395 dy = ceilf(dy - 0.5f);
397 pmvMatrix[0][0] = (wfactor * transform.m11()) - transform.m13();
398 pmvMatrix[1][0] = (wfactor * transform.m21()) - transform.m23();
399 pmvMatrix[2][0] = (wfactor * dx) - transform.m33();
400 pmvMatrix[0][1] = (hfactor * transform.m12()) + transform.m13();
401 pmvMatrix[1][1] = (hfactor * transform.m22()) + transform.m23();
402 pmvMatrix[2][1] = (hfactor * dy) + transform.m33();
403 pmvMatrix[0][2] = transform.m13();
404 pmvMatrix[1][2] = transform.m23();
405 pmvMatrix[2][2] = transform.m33();
407 // 1/10000 == 0.0001, so we have good enough res to cover curves
408 // that span the entire widget...
409 inverseScale = qMax(1 / qMax( qMax(qAbs(transform.m11()), qAbs(transform.m22())),
410 qMax(qAbs(transform.m12()), qAbs(transform.m21())) ),
414 matrixUniformDirty = true;
416 // Set the PMV matrix attribute. As we use an attributes rather than uniforms, we only
417 // need to do this once for every matrix change and persists across all shader programs.
418 funcs.glVertexAttrib3fv(QT_PMV_MATRIX_1_ATTR, pmvMatrix[0]);
419 funcs.glVertexAttrib3fv(QT_PMV_MATRIX_2_ATTR, pmvMatrix[1]);
420 funcs.glVertexAttrib3fv(QT_PMV_MATRIX_3_ATTR, pmvMatrix[2]);
422 dasher.setInvScale(inverseScale);
423 stroker.setInvScale(inverseScale);
427 void QOpenGL2PaintEngineExPrivate::updateCompositionMode()
429 // NOTE: The entire paint engine works on pre-multiplied data - which is why some of these
430 // composition modes look odd.
431 // qDebug() << "QOpenGL2PaintEngineExPrivate::updateCompositionMode() - Setting GL composition mode for " << q->state()->composition_mode;
432 switch(q->state()->composition_mode) {
433 case QPainter::CompositionMode_SourceOver:
434 glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
436 case QPainter::CompositionMode_DestinationOver:
437 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE);
439 case QPainter::CompositionMode_Clear:
440 glBlendFunc(GL_ZERO, GL_ZERO);
442 case QPainter::CompositionMode_Source:
443 glBlendFunc(GL_ONE, GL_ZERO);
445 case QPainter::CompositionMode_Destination:
446 glBlendFunc(GL_ZERO, GL_ONE);
448 case QPainter::CompositionMode_SourceIn:
449 glBlendFunc(GL_DST_ALPHA, GL_ZERO);
451 case QPainter::CompositionMode_DestinationIn:
452 glBlendFunc(GL_ZERO, GL_SRC_ALPHA);
454 case QPainter::CompositionMode_SourceOut:
455 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ZERO);
457 case QPainter::CompositionMode_DestinationOut:
458 glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_ALPHA);
460 case QPainter::CompositionMode_SourceAtop:
461 glBlendFunc(GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
463 case QPainter::CompositionMode_DestinationAtop:
464 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA);
466 case QPainter::CompositionMode_Xor:
467 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
469 case QPainter::CompositionMode_Plus:
470 glBlendFunc(GL_ONE, GL_ONE);
473 qWarning("Unsupported composition mode");
477 compositionModeDirty = false;
480 static inline void setCoords(GLfloat *coords, const QOpenGLRect &rect)
482 coords[0] = rect.left;
483 coords[1] = rect.top;
484 coords[2] = rect.right;
485 coords[3] = rect.top;
486 coords[4] = rect.right;
487 coords[5] = rect.bottom;
488 coords[6] = rect.left;
489 coords[7] = rect.bottom;
492 void QOpenGL2PaintEngineExPrivate::drawTexture(const QOpenGLRect& dest, const QOpenGLRect& src, const QSize &textureSize, bool opaque, bool pattern)
494 // Setup for texture drawing
495 currentBrush = noBrush;
496 shaderManager->setSrcPixelType(pattern ? QOpenGLEngineShaderManager::PatternSrc : QOpenGLEngineShaderManager::ImageSrc);
498 if (snapToPixelGrid) {
499 snapToPixelGrid = false;
503 if (prepareForDraw(opaque))
504 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::ImageTexture), QT_IMAGE_TEXTURE_UNIT);
507 QColor col = qt_premultiplyColor(q->state()->pen.color(), (GLfloat)q->state()->opacity);
508 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::PatternColor), col);
511 GLfloat dx = 1.0 / textureSize.width();
512 GLfloat dy = 1.0 / textureSize.height();
514 QOpenGLRect srcTextureRect(src.left*dx, src.top*dy, src.right*dx, src.bottom*dy);
516 setCoords(staticVertexCoordinateArray, dest);
517 setCoords(staticTextureCoordinateArray, srcTextureRect);
519 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
522 void QOpenGL2PaintEngineEx::beginNativePainting()
524 Q_D(QOpenGL2PaintEngineEx);
526 d->transferMode(BrushDrawingMode);
528 d->nativePaintingActive = true;
530 d->funcs.glUseProgram(0);
532 // Disable all the vertex attribute arrays:
533 for (int i = 0; i < QT_GL_VERTEX_ARRAY_TRACKED_COUNT; ++i)
534 d->funcs.glDisableVertexAttribArray(i);
536 #ifndef QT_OPENGL_ES_2
537 Q_ASSERT(QOpenGLContext::currentContext());
538 const QSurfaceFormat &fmt = d->device->context()->format();
539 if (fmt.majorVersion() < 3 || (fmt.majorVersion() == 3 && fmt.minorVersion() < 1)
540 || fmt.profile() == QSurfaceFormat::CompatibilityProfile)
542 // be nice to people who mix OpenGL 1.x code with QPainter commands
543 // by setting modelview and projection matrices to mirror the GL 1
545 const QTransform& mtx = state()->matrix;
547 float mv_matrix[4][4] =
549 { float(mtx.m11()), float(mtx.m12()), 0, float(mtx.m13()) },
550 { float(mtx.m21()), float(mtx.m22()), 0, float(mtx.m23()) },
552 { float(mtx.dx()), float(mtx.dy()), 0, float(mtx.m33()) }
555 const QSize sz = d->device->size();
557 glMatrixMode(GL_PROJECTION);
559 glOrtho(0, sz.width(), sz.height(), 0, -999999, 999999);
561 glMatrixMode(GL_MODELVIEW);
562 glLoadMatrixf(&mv_matrix[0][0]);
566 d->lastTextureUsed = GLuint(-1);
567 d->dirtyStencilRegion = QRect(0, 0, d->width, d->height);
570 d->shaderManager->setDirty();
575 void QOpenGL2PaintEngineExPrivate::resetGLState()
578 funcs.glActiveTexture(GL_TEXTURE0);
579 glDisable(GL_STENCIL_TEST);
580 glDisable(GL_DEPTH_TEST);
581 glDisable(GL_SCISSOR_TEST);
583 glDepthFunc(GL_LESS);
584 funcs.glClearDepthf(1);
586 glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
587 glStencilFunc(GL_ALWAYS, 0, 0xff);
588 setVertexAttribArrayEnabled(QT_TEXTURE_COORDS_ATTR, false);
589 setVertexAttribArrayEnabled(QT_VERTEX_COORDS_ATTR, false);
590 setVertexAttribArrayEnabled(QT_OPACITY_ATTR, false);
591 #ifndef QT_OPENGL_ES_2
592 // gl_Color, corresponding to vertex attribute 3, may have been changed
593 float color[] = { 1.0f, 1.0f, 1.0f, 1.0f };
594 funcs.glVertexAttrib4fv(3, color);
598 void QOpenGL2PaintEngineEx::endNativePainting()
600 Q_D(QOpenGL2PaintEngineEx);
602 d->nativePaintingActive = false;
605 void QOpenGL2PaintEngineEx::invalidateState()
607 Q_D(QOpenGL2PaintEngineEx);
611 bool QOpenGL2PaintEngineEx::isNativePaintingActive() const {
612 Q_D(const QOpenGL2PaintEngineEx);
613 return d->nativePaintingActive;
616 void QOpenGL2PaintEngineExPrivate::transferMode(EngineMode newMode)
621 if (mode == TextDrawingMode || mode == ImageDrawingMode || mode == ImageArrayDrawingMode) {
622 lastTextureUsed = GLuint(-1);
625 if (newMode == TextDrawingMode) {
626 shaderManager->setHasComplexGeometry(true);
628 shaderManager->setHasComplexGeometry(false);
631 if (newMode == ImageDrawingMode) {
632 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, staticVertexCoordinateArray);
633 setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, staticTextureCoordinateArray);
636 if (newMode == ImageArrayDrawingMode) {
637 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)vertexCoordinateArray.data());
638 setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, (GLfloat*)textureCoordinateArray.data());
639 setVertexAttributePointer(QT_OPACITY_ATTR, (GLfloat*)opacityArray.data());
642 // This needs to change when we implement high-quality anti-aliasing...
643 if (newMode != TextDrawingMode)
644 shaderManager->setMaskType(QOpenGLEngineShaderManager::NoMask);
649 struct QOpenGL2PEVectorPathCache
651 #ifdef QT_OPENGL_CACHE_AS_VBOS
660 GLenum primitiveType;
662 QVertexIndexVector::Type indexType;
665 void QOpenGL2PaintEngineExPrivate::cleanupVectorPath(QPaintEngineEx *engine, void *data)
667 QOpenGL2PEVectorPathCache *c = (QOpenGL2PEVectorPathCache *) data;
668 #ifdef QT_OPENGL_CACHE_AS_VBOS
669 Q_ASSERT(engine->type() == QPaintEngine::OpenGL2);
670 static_cast<QOpenGL2PaintEngineEx *>(engine)->d_func()->unusedVBOSToClean << c->vbo;
672 d->unusedIBOSToClean << c->ibo;
681 // Assumes everything is configured for the brush you want to use
682 void QOpenGL2PaintEngineExPrivate::fill(const QVectorPath& path)
684 transferMode(BrushDrawingMode);
686 if (snapToPixelGrid) {
687 snapToPixelGrid = false;
691 // Might need to call updateMatrix to re-calculate inverseScale
695 const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
697 // Check to see if there's any hints
698 if (path.shape() == QVectorPath::RectangleHint) {
699 QOpenGLRect rect(points[0].x(), points[0].y(), points[2].x(), points[2].y());
700 prepareForDraw(currentBrush.isOpaque());
702 } else if (path.isConvex()) {
704 if (path.isCacheable()) {
705 QVectorPath::CacheEntry *data = path.lookupCacheData(q);
706 QOpenGL2PEVectorPathCache *cache;
708 bool updateCache = false;
711 cache = (QOpenGL2PEVectorPathCache *) data->data;
712 // Check if scale factor is exceeded for curved paths and generate curves if so...
713 if (path.isCurved()) {
714 qreal scaleFactor = cache->iscale / inverseScale;
715 if (scaleFactor < 0.5 || scaleFactor > 2.0) {
716 #ifdef QT_OPENGL_CACHE_AS_VBOS
717 glDeleteBuffers(1, &cache->vbo);
719 Q_ASSERT(cache->ibo == 0);
721 free(cache->vertices);
722 Q_ASSERT(cache->indices == 0);
728 cache = new QOpenGL2PEVectorPathCache;
729 data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
733 // Flatten the path at the current scale factor and fill it into the cache struct.
735 vertexCoordinateArray.clear();
736 vertexCoordinateArray.addPath(path, inverseScale, false);
737 int vertexCount = vertexCoordinateArray.vertexCount();
738 int floatSizeInBytes = vertexCount * 2 * sizeof(float);
739 cache->vertexCount = vertexCount;
740 cache->indexCount = 0;
741 cache->primitiveType = GL_TRIANGLE_FAN;
742 cache->iscale = inverseScale;
743 #ifdef QT_OPENGL_CACHE_AS_VBOS
744 glGenBuffers(1, &cache->vbo);
745 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
746 glBufferData(GL_ARRAY_BUFFER, floatSizeInBytes, vertexCoordinateArray.data(), GL_STATIC_DRAW);
749 cache->vertices = (float *) malloc(floatSizeInBytes);
750 memcpy(cache->vertices, vertexCoordinateArray.data(), floatSizeInBytes);
755 prepareForDraw(currentBrush.isOpaque());
756 #ifdef QT_OPENGL_CACHE_AS_VBOS
757 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
758 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, 0);
760 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, cache->vertices);
762 glDrawArrays(cache->primitiveType, 0, cache->vertexCount);
765 // printf(" - Marking path as cachable...\n");
766 // Tag it for later so that if the same path is drawn twice, it is assumed to be static and thus cachable
767 path.makeCacheable();
768 vertexCoordinateArray.clear();
769 vertexCoordinateArray.addPath(path, inverseScale, false);
770 prepareForDraw(currentBrush.isOpaque());
771 drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN);
775 bool useCache = path.isCacheable();
777 QRectF bbox = path.controlPointRect();
778 // If the path doesn't fit within these limits, it is possible that the triangulation will fail.
779 useCache &= (bbox.left() > -0x8000 * inverseScale)
780 && (bbox.right() < 0x8000 * inverseScale)
781 && (bbox.top() > -0x8000 * inverseScale)
782 && (bbox.bottom() < 0x8000 * inverseScale);
786 QVectorPath::CacheEntry *data = path.lookupCacheData(q);
787 QOpenGL2PEVectorPathCache *cache;
789 bool updateCache = false;
792 cache = (QOpenGL2PEVectorPathCache *) data->data;
793 // Check if scale factor is exceeded for curved paths and generate curves if so...
794 if (path.isCurved()) {
795 qreal scaleFactor = cache->iscale / inverseScale;
796 if (scaleFactor < 0.5 || scaleFactor > 2.0) {
797 #ifdef QT_OPENGL_CACHE_AS_VBOS
798 glDeleteBuffers(1, &cache->vbo);
799 glDeleteBuffers(1, &cache->ibo);
801 free(cache->vertices);
802 free(cache->indices);
808 cache = new QOpenGL2PEVectorPathCache;
809 data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
813 // Flatten the path at the current scale factor and fill it into the cache struct.
815 QTriangleSet polys = qTriangulate(path, QTransform().scale(1 / inverseScale, 1 / inverseScale));
816 cache->vertexCount = polys.vertices.size() / 2;
817 cache->indexCount = polys.indices.size();
818 cache->primitiveType = GL_TRIANGLES;
819 cache->iscale = inverseScale;
820 cache->indexType = polys.indices.type();
821 #ifdef QT_OPENGL_CACHE_AS_VBOS
822 glGenBuffers(1, &cache->vbo);
823 glGenBuffers(1, &cache->ibo);
824 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
825 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cache->ibo);
827 if (polys.indices.type() == QVertexIndexVector::UnsignedInt)
828 funcs.glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint32) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
830 funcs.glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint16) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
832 QVarLengthArray<float> vertices(polys.vertices.size());
833 for (int i = 0; i < polys.vertices.size(); ++i)
834 vertices[i] = float(inverseScale * polys.vertices.at(i));
835 funcs.glBufferData(GL_ARRAY_BUFFER, sizeof(float) * vertices.size(), vertices.data(), GL_STATIC_DRAW);
837 cache->vertices = (float *) malloc(sizeof(float) * polys.vertices.size());
838 if (polys.indices.type() == QVertexIndexVector::UnsignedInt) {
839 cache->indices = (quint32 *) malloc(sizeof(quint32) * polys.indices.size());
840 memcpy(cache->indices, polys.indices.data(), sizeof(quint32) * polys.indices.size());
842 cache->indices = (quint16 *) malloc(sizeof(quint16) * polys.indices.size());
843 memcpy(cache->indices, polys.indices.data(), sizeof(quint16) * polys.indices.size());
845 for (int i = 0; i < polys.vertices.size(); ++i)
846 cache->vertices[i] = float(inverseScale * polys.vertices.at(i));
850 prepareForDraw(currentBrush.isOpaque());
851 #ifdef QT_OPENGL_CACHE_AS_VBOS
852 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
853 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cache->ibo);
854 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, 0);
855 if (cache->indexType == QVertexIndexVector::UnsignedInt)
856 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_INT, 0);
858 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_SHORT, 0);
859 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
860 glBindBuffer(GL_ARRAY_BUFFER, 0);
862 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, cache->vertices);
863 if (cache->indexType == QVertexIndexVector::UnsignedInt)
864 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_INT, (qint32 *)cache->indices);
866 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_SHORT, (qint16 *)cache->indices);
870 // printf(" - Marking path as cachable...\n");
871 // Tag it for later so that if the same path is drawn twice, it is assumed to be static and thus cachable
872 path.makeCacheable();
874 if (device->context()->format().stencilBufferSize() == 0) {
875 // If there is no stencil buffer, triangulate the path instead.
877 QRectF bbox = path.controlPointRect();
878 // If the path doesn't fit within these limits, it is possible that the triangulation will fail.
879 bool withinLimits = (bbox.left() > -0x8000 * inverseScale)
880 && (bbox.right() < 0x8000 * inverseScale)
881 && (bbox.top() > -0x8000 * inverseScale)
882 && (bbox.bottom() < 0x8000 * inverseScale);
884 QTriangleSet polys = qTriangulate(path, QTransform().scale(1 / inverseScale, 1 / inverseScale));
886 QVarLengthArray<float> vertices(polys.vertices.size());
887 for (int i = 0; i < polys.vertices.size(); ++i)
888 vertices[i] = float(inverseScale * polys.vertices.at(i));
890 prepareForDraw(currentBrush.isOpaque());
891 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, vertices.constData());
892 if (funcs.hasOpenGLExtension(QOpenGLExtensions::ElementIndexUint))
893 glDrawElements(GL_TRIANGLES, polys.indices.size(), GL_UNSIGNED_INT, polys.indices.data());
895 glDrawElements(GL_TRIANGLES, polys.indices.size(), GL_UNSIGNED_SHORT, polys.indices.data());
897 // We can't handle big, concave painter paths with OpenGL without stencil buffer.
898 qWarning("Painter path exceeds +/-32767 pixels.");
903 // The path is too complicated & needs the stencil technique
904 vertexCoordinateArray.clear();
905 vertexCoordinateArray.addPath(path, inverseScale, false);
907 fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill());
910 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
912 if (q->state()->clipTestEnabled) {
913 // Pass when high bit is set, replace stencil value with current clip
914 glStencilFunc(GL_NOTEQUAL, q->state()->currentClip, GL_STENCIL_HIGH_BIT);
915 } else if (path.hasWindingFill()) {
916 // Pass when any bit is set, replace stencil value with 0
917 glStencilFunc(GL_NOTEQUAL, 0, 0xff);
919 // Pass when high bit is set, replace stencil value with 0
920 glStencilFunc(GL_NOTEQUAL, 0, GL_STENCIL_HIGH_BIT);
922 prepareForDraw(currentBrush.isOpaque());
924 // Stencil the brush onto the dest buffer
925 composite(vertexCoordinateArray.boundingRect());
927 updateClipScissorTest();
933 void QOpenGL2PaintEngineExPrivate::fillStencilWithVertexArray(const float *data,
937 const QOpenGLRect &bounds,
938 StencilFillMode mode)
940 Q_ASSERT(count || stops);
942 // qDebug("QOpenGL2PaintEngineExPrivate::fillStencilWithVertexArray()");
943 glStencilMask(0xff); // Enable stencil writes
945 if (dirtyStencilRegion.intersects(currentScissorBounds)) {
946 QVector<QRect> clearRegion = dirtyStencilRegion.intersected(currentScissorBounds).rects();
947 glClearStencil(0); // Clear to zero
948 for (int i = 0; i < clearRegion.size(); ++i) {
949 #ifndef QT_GL_NO_SCISSOR_TEST
950 setScissor(clearRegion.at(i));
952 glClear(GL_STENCIL_BUFFER_BIT);
955 dirtyStencilRegion -= currentScissorBounds;
957 #ifndef QT_GL_NO_SCISSOR_TEST
958 updateClipScissorTest();
962 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); // Disable color writes
964 glEnable(GL_STENCIL_TEST); // For some reason, this has to happen _after_ the simple shader is use()'d
966 if (mode == WindingFillMode) {
967 Q_ASSERT(stops && !count);
968 if (q->state()->clipTestEnabled) {
969 // Flatten clip values higher than current clip, and set high bit to match current clip
970 glStencilFunc(GL_LEQUAL, GL_STENCIL_HIGH_BIT | q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
971 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
974 glStencilFunc(GL_EQUAL, GL_STENCIL_HIGH_BIT, GL_STENCIL_HIGH_BIT);
975 } else if (!stencilClean) {
976 // Clear stencil buffer within bounding rect
977 glStencilFunc(GL_ALWAYS, 0, 0xff);
978 glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO);
982 // Inc. for front-facing triangle
983 funcs.glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_INCR_WRAP, GL_INCR_WRAP);
984 // Dec. for back-facing "holes"
985 funcs.glStencilOpSeparate(GL_BACK, GL_KEEP, GL_DECR_WRAP, GL_DECR_WRAP);
986 glStencilMask(~GL_STENCIL_HIGH_BIT);
987 drawVertexArrays(data, stops, stopCount, GL_TRIANGLE_FAN);
989 if (q->state()->clipTestEnabled) {
990 // Clear high bit of stencil outside of path
991 glStencilFunc(GL_EQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
992 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
993 glStencilMask(GL_STENCIL_HIGH_BIT);
996 } else if (mode == OddEvenFillMode) {
997 glStencilMask(GL_STENCIL_HIGH_BIT);
998 glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT); // Simply invert the stencil bit
999 drawVertexArrays(data, stops, stopCount, GL_TRIANGLE_FAN);
1001 } else { // TriStripStrokeFillMode
1002 Q_ASSERT(count && !stops); // tristrips generated directly, so no vertexArray or stops
1003 glStencilMask(GL_STENCIL_HIGH_BIT);
1005 glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT); // Simply invert the stencil bit
1006 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, data);
1007 glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
1010 glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
1011 if (q->state()->clipTestEnabled) {
1012 glStencilFunc(GL_LEQUAL, q->state()->currentClip | GL_STENCIL_HIGH_BIT,
1013 ~GL_STENCIL_HIGH_BIT);
1015 glStencilFunc(GL_ALWAYS, GL_STENCIL_HIGH_BIT, 0xff);
1017 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, data);
1018 glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
1022 // Enable color writes & disable stencil writes
1023 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1027 If the maximum value in the stencil buffer is GL_STENCIL_HIGH_BIT - 1,
1028 restore the stencil buffer to a pristine state. The current clip region
1029 is set to 1, and the rest to 0.
1031 void QOpenGL2PaintEngineExPrivate::resetClipIfNeeded()
1033 if (maxClip != (GL_STENCIL_HIGH_BIT - 1))
1036 Q_Q(QOpenGL2PaintEngineEx);
1039 glEnable(GL_STENCIL_TEST);
1040 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1042 QRectF bounds = q->state()->matrix.inverted().mapRect(QRectF(0, 0, width, height));
1043 QOpenGLRect rect(bounds.left(), bounds.top(), bounds.right(), bounds.bottom());
1045 // Set high bit on clip region
1046 glStencilFunc(GL_LEQUAL, q->state()->currentClip, 0xff);
1047 glStencilOp(GL_KEEP, GL_INVERT, GL_INVERT);
1048 glStencilMask(GL_STENCIL_HIGH_BIT);
1051 // Reset clipping to 1 and everything else to zero
1052 glStencilFunc(GL_NOTEQUAL, 0x01, GL_STENCIL_HIGH_BIT);
1053 glStencilOp(GL_ZERO, GL_REPLACE, GL_REPLACE);
1054 glStencilMask(0xff);
1057 q->state()->currentClip = 1;
1058 q->state()->canRestoreClip = false;
1063 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1066 bool QOpenGL2PaintEngineExPrivate::prepareForDraw(bool srcPixelsAreOpaque)
1068 if (brushTextureDirty && mode != ImageDrawingMode && mode != ImageArrayDrawingMode)
1069 updateBrushTexture();
1071 if (compositionModeDirty)
1072 updateCompositionMode();
1077 const bool stateHasOpacity = q->state()->opacity < 0.99f;
1078 if (q->state()->composition_mode == QPainter::CompositionMode_Source
1079 || (q->state()->composition_mode == QPainter::CompositionMode_SourceOver
1080 && srcPixelsAreOpaque && !stateHasOpacity))
1082 glDisable(GL_BLEND);
1087 QOpenGLEngineShaderManager::OpacityMode opacityMode;
1088 if (mode == ImageArrayDrawingMode) {
1089 opacityMode = QOpenGLEngineShaderManager::AttributeOpacity;
1091 opacityMode = stateHasOpacity ? QOpenGLEngineShaderManager::UniformOpacity
1092 : QOpenGLEngineShaderManager::NoOpacity;
1093 if (stateHasOpacity && (mode != ImageDrawingMode)) {
1095 bool brushIsPattern = (currentBrush.style() >= Qt::Dense1Pattern) &&
1096 (currentBrush.style() <= Qt::DiagCrossPattern);
1098 if ((currentBrush.style() == Qt::SolidPattern) || brushIsPattern)
1099 opacityMode = QOpenGLEngineShaderManager::NoOpacity; // Global opacity handled by srcPixel shader
1102 shaderManager->setOpacityMode(opacityMode);
1104 bool changed = shaderManager->useCorrectShaderProg();
1105 // If the shader program needs changing, we change it and mark all uniforms as dirty
1107 // The shader program has changed so mark all uniforms as dirty:
1108 brushUniformsDirty = true;
1109 opacityUniformDirty = true;
1110 matrixUniformDirty = true;
1113 if (brushUniformsDirty && mode != ImageDrawingMode && mode != ImageArrayDrawingMode)
1114 updateBrushUniforms();
1116 if (opacityMode == QOpenGLEngineShaderManager::UniformOpacity && opacityUniformDirty) {
1117 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::GlobalOpacity), (GLfloat)q->state()->opacity);
1118 opacityUniformDirty = false;
1121 if (matrixUniformDirty && shaderManager->hasComplexGeometry()) {
1122 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Matrix),
1124 matrixUniformDirty = false;
1130 void QOpenGL2PaintEngineExPrivate::composite(const QOpenGLRect& boundingRect)
1132 setCoords(staticVertexCoordinateArray, boundingRect);
1133 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, staticVertexCoordinateArray);
1134 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1137 // Draws the vertex array as a set of <vertexArrayStops.size()> triangle fans.
1138 void QOpenGL2PaintEngineExPrivate::drawVertexArrays(const float *data, int *stops, int stopCount,
1141 // Now setup the pointer to the vertex array:
1142 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)data);
1144 int previousStop = 0;
1145 for (int i=0; i<stopCount; ++i) {
1146 int stop = stops[i];
1148 qDebug("Drawing triangle fan for vertecies %d -> %d:", previousStop, stop-1);
1149 for (int i=previousStop; i<stop; ++i)
1150 qDebug(" %02d: [%.2f, %.2f]", i, vertexArray.data()[i].x, vertexArray.data()[i].y);
1152 glDrawArrays(primitive, previousStop, stop - previousStop);
1153 previousStop = stop;
1157 /////////////////////////////////// Public Methods //////////////////////////////////////////
1159 QOpenGL2PaintEngineEx::QOpenGL2PaintEngineEx()
1160 : QPaintEngineEx(*(new QOpenGL2PaintEngineExPrivate(this)))
1164 QOpenGL2PaintEngineEx::~QOpenGL2PaintEngineEx()
1168 void QOpenGL2PaintEngineEx::fill(const QVectorPath &path, const QBrush &brush)
1170 Q_D(QOpenGL2PaintEngineEx);
1172 if (qbrush_style(brush) == Qt::NoBrush)
1179 Q_GUI_EXPORT bool qt_scaleForTransform(const QTransform &transform, qreal *scale); // qtransform.cpp
1182 void QOpenGL2PaintEngineEx::stroke(const QVectorPath &path, const QPen &pen)
1184 Q_D(QOpenGL2PaintEngineEx);
1186 const QBrush &penBrush = qpen_brush(pen);
1187 if (qpen_style(pen) == Qt::NoPen || qbrush_style(penBrush) == Qt::NoBrush)
1190 QOpenGL2PaintEngineState *s = state();
1191 if (pen.isCosmetic() && !qt_scaleForTransform(s->transform(), 0)) {
1192 // QTriangulatingStroker class is not meant to support cosmetically sheared strokes.
1193 QPaintEngineEx::stroke(path, pen);
1198 d->setBrush(penBrush);
1199 d->stroke(path, pen);
1202 void QOpenGL2PaintEngineExPrivate::stroke(const QVectorPath &path, const QPen &pen)
1204 const QOpenGL2PaintEngineState *s = q->state();
1205 if (snapToPixelGrid) {
1206 snapToPixelGrid = false;
1210 const Qt::PenStyle penStyle = qpen_style(pen);
1211 const QBrush &penBrush = qpen_brush(pen);
1212 const bool opaque = penBrush.isOpaque() && s->opacity > 0.99;
1214 transferMode(BrushDrawingMode);
1216 // updateMatrix() is responsible for setting the inverse scale on
1217 // the strokers, so we need to call it here and not wait for
1218 // prepareForDraw() down below.
1221 QRectF clip = q->state()->matrix.inverted().mapRect(q->state()->clipEnabled
1222 ? q->state()->rectangleClip
1223 : QRectF(0, 0, width, height));
1225 if (penStyle == Qt::SolidLine) {
1226 stroker.process(path, pen, clip);
1228 } else { // Some sort of dash
1229 dasher.process(path, pen, clip);
1231 QVectorPath dashStroke(dasher.points(),
1232 dasher.elementCount(),
1233 dasher.elementTypes());
1234 stroker.process(dashStroke, pen, clip);
1237 if (!stroker.vertexCount())
1241 prepareForDraw(opaque);
1242 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, stroker.vertices());
1243 glDrawArrays(GL_TRIANGLE_STRIP, 0, stroker.vertexCount() / 2);
1245 // QBrush b(Qt::green);
1247 // d->prepareForDraw(true);
1248 // glDrawArrays(GL_LINE_STRIP, 0, d->stroker.vertexCount() / 2);
1251 qreal width = qpen_widthf(pen) / 2;
1254 qreal extra = pen.joinStyle() == Qt::MiterJoin
1255 ? qMax(pen.miterLimit() * width, width)
1258 if (pen.isCosmetic())
1259 extra = extra * inverseScale;
1261 QRectF bounds = path.controlPointRect().adjusted(-extra, -extra, extra, extra);
1263 fillStencilWithVertexArray(stroker.vertices(), stroker.vertexCount() / 2,
1264 0, 0, bounds, QOpenGL2PaintEngineExPrivate::TriStripStrokeFillMode);
1266 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
1268 // Pass when any bit is set, replace stencil value with 0
1269 glStencilFunc(GL_NOTEQUAL, 0, GL_STENCIL_HIGH_BIT);
1270 prepareForDraw(false);
1272 // Stencil the brush onto the dest buffer
1277 updateClipScissorTest();
1281 void QOpenGL2PaintEngineEx::penChanged() { }
1282 void QOpenGL2PaintEngineEx::brushChanged() { }
1283 void QOpenGL2PaintEngineEx::brushOriginChanged() { }
1285 void QOpenGL2PaintEngineEx::opacityChanged()
1287 // qDebug("QOpenGL2PaintEngineEx::opacityChanged()");
1288 Q_D(QOpenGL2PaintEngineEx);
1289 state()->opacityChanged = true;
1291 Q_ASSERT(d->shaderManager);
1292 d->brushUniformsDirty = true;
1293 d->opacityUniformDirty = true;
1296 void QOpenGL2PaintEngineEx::compositionModeChanged()
1298 // qDebug("QOpenGL2PaintEngineEx::compositionModeChanged()");
1299 Q_D(QOpenGL2PaintEngineEx);
1300 state()->compositionModeChanged = true;
1301 d->compositionModeDirty = true;
1304 void QOpenGL2PaintEngineEx::renderHintsChanged()
1306 state()->renderHintsChanged = true;
1308 #if !defined(QT_OPENGL_ES_2)
1309 if ((state()->renderHints & QPainter::Antialiasing)
1310 || (state()->renderHints & QPainter::HighQualityAntialiasing))
1311 glEnable(GL_MULTISAMPLE);
1313 glDisable(GL_MULTISAMPLE);
1316 Q_D(QOpenGL2PaintEngineEx);
1317 d->lastTextureUsed = GLuint(-1);
1318 d->brushTextureDirty = true;
1319 // qDebug("QOpenGL2PaintEngineEx::renderHintsChanged() not implemented!");
1322 void QOpenGL2PaintEngineEx::transformChanged()
1324 Q_D(QOpenGL2PaintEngineEx);
1325 d->matrixDirty = true;
1326 state()->matrixChanged = true;
1330 static const QRectF scaleRect(const QRectF &r, qreal sx, qreal sy)
1332 return QRectF(r.x() * sx, r.y() * sy, r.width() * sx, r.height() * sy);
1335 void QOpenGL2PaintEngineEx::drawPixmap(const QRectF& dest, const QPixmap & pixmap, const QRectF & src)
1337 Q_D(QOpenGL2PaintEngineEx);
1338 QOpenGLContext *ctx = d->ctx;
1340 int max_texture_size = ctx->d_func()->maxTextureSize();
1341 if (pixmap.width() > max_texture_size || pixmap.height() > max_texture_size) {
1342 QPixmap scaled = pixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1344 const qreal sx = scaled.width() / qreal(pixmap.width());
1345 const qreal sy = scaled.height() / qreal(pixmap.height());
1347 drawPixmap(dest, scaled, scaleRect(src, sx, sy));
1352 d->transferMode(ImageDrawingMode);
1354 d->funcs.glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1355 GLuint id = QOpenGLTextureCache::cacheForContext(ctx)->bindTexture(ctx, pixmap);
1357 QOpenGLRect srcRect(src.left(), src.top(), src.right(), src.bottom());
1359 bool isBitmap = pixmap.isQBitmap();
1360 bool isOpaque = !isBitmap && !pixmap.hasAlpha();
1362 d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1363 state()->renderHints & QPainter::SmoothPixmapTransform, id);
1364 d->drawTexture(dest, srcRect, pixmap.size(), isOpaque, isBitmap);
1367 void QOpenGL2PaintEngineEx::drawImage(const QRectF& dest, const QImage& image, const QRectF& src,
1368 Qt::ImageConversionFlags)
1370 Q_D(QOpenGL2PaintEngineEx);
1371 QOpenGLContext *ctx = d->ctx;
1373 int max_texture_size = ctx->d_func()->maxTextureSize();
1374 if (image.width() > max_texture_size || image.height() > max_texture_size) {
1375 QImage scaled = image.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1377 const qreal sx = scaled.width() / qreal(image.width());
1378 const qreal sy = scaled.height() / qreal(image.height());
1380 drawImage(dest, scaled, scaleRect(src, sx, sy));
1385 d->transferMode(ImageDrawingMode);
1387 d->funcs.glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1389 GLuint id = QOpenGLTextureCache::cacheForContext(ctx)->bindTexture(ctx, image);
1391 d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1392 state()->renderHints & QPainter::SmoothPixmapTransform, id);
1393 d->drawTexture(dest, src, image.size(), !image.hasAlphaChannel());
1396 void QOpenGL2PaintEngineEx::drawStaticTextItem(QStaticTextItem *textItem)
1398 Q_D(QOpenGL2PaintEngineEx);
1402 QPainterState *s = state();
1403 float det = s->matrix.determinant();
1405 // don't try to cache huge fonts or vastly transformed fonts
1406 QFontEngine *fontEngine = textItem->fontEngine();
1407 if (shouldDrawCachedGlyphs(fontEngine, s->matrix) || det < 0.25f || det > 4.f) {
1408 QFontEngineGlyphCache::Type glyphType = fontEngine->glyphFormat >= 0
1409 ? QFontEngineGlyphCache::Type(textItem->fontEngine()->glyphFormat)
1410 : d->glyphCacheType;
1411 if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1412 if (d->device->context()->format().alphaBufferSize() > 0 || s->matrix.type() > QTransform::TxTranslate
1413 || (s->composition_mode != QPainter::CompositionMode_Source
1414 && s->composition_mode != QPainter::CompositionMode_SourceOver))
1416 glyphType = QFontEngineGlyphCache::Raster_A8;
1420 d->drawCachedGlyphs(glyphType, textItem);
1422 QPaintEngineEx::drawStaticTextItem(textItem);
1426 bool QOpenGL2PaintEngineEx::drawTexture(const QRectF &dest, GLuint textureId, const QSize &size, const QRectF &src)
1428 Q_D(QOpenGL2PaintEngineEx);
1429 if (!d->shaderManager)
1433 d->transferMode(ImageDrawingMode);
1435 d->funcs.glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1436 glBindTexture(GL_TEXTURE_2D, textureId);
1438 QOpenGLRect srcRect(src.left(), src.bottom(), src.right(), src.top());
1440 d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1441 state()->renderHints & QPainter::SmoothPixmapTransform, textureId);
1442 d->drawTexture(dest, srcRect, size, false);
1446 void QOpenGL2PaintEngineEx::drawTextItem(const QPointF &p, const QTextItem &textItem)
1448 Q_D(QOpenGL2PaintEngineEx);
1451 QOpenGL2PaintEngineState *s = state();
1453 const QTextItemInt &ti = static_cast<const QTextItemInt &>(textItem);
1455 QTransform::TransformationType txtype = s->matrix.type();
1457 float det = s->matrix.determinant();
1458 bool drawCached = txtype < QTransform::TxProject;
1460 // don't try to cache huge fonts or vastly transformed fonts
1461 if (shouldDrawCachedGlyphs(ti.fontEngine, s->matrix) || det < 0.25f || det > 4.f)
1464 QFontEngineGlyphCache::Type glyphType = ti.fontEngine->glyphFormat >= 0
1465 ? QFontEngineGlyphCache::Type(ti.fontEngine->glyphFormat)
1466 : d->glyphCacheType;
1469 if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1470 if (d->device->context()->format().alphaBufferSize() > 0 || txtype > QTransform::TxTranslate
1471 || (state()->composition_mode != QPainter::CompositionMode_Source
1472 && state()->composition_mode != QPainter::CompositionMode_SourceOver))
1474 glyphType = QFontEngineGlyphCache::Raster_A8;
1479 QVarLengthArray<QFixedPoint> positions;
1480 QVarLengthArray<glyph_t> glyphs;
1481 QTransform matrix = QTransform::fromTranslate(p.x(), p.y());
1482 ti.fontEngine->getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions);
1485 QStaticTextItem staticTextItem;
1486 staticTextItem.chars = const_cast<QChar *>(ti.chars);
1487 staticTextItem.setFontEngine(ti.fontEngine);
1488 staticTextItem.glyphs = glyphs.data();
1489 staticTextItem.numChars = ti.num_chars;
1490 staticTextItem.numGlyphs = glyphs.size();
1491 staticTextItem.glyphPositions = positions.data();
1493 d->drawCachedGlyphs(glyphType, &staticTextItem);
1498 QPaintEngineEx::drawTextItem(p, ti);
1503 class QOpenGLStaticTextUserData: public QStaticTextUserData
1506 QOpenGLStaticTextUserData()
1507 : QStaticTextUserData(OpenGLUserData), cacheSize(0, 0), cacheSerialNumber(0)
1511 ~QOpenGLStaticTextUserData()
1516 QOpenGL2PEXVertexArray vertexCoordinateArray;
1517 QOpenGL2PEXVertexArray textureCoordinateArray;
1518 QFontEngineGlyphCache::Type glyphType;
1519 int cacheSerialNumber;
1525 // #define QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO
1527 void QOpenGL2PaintEngineExPrivate::drawCachedGlyphs(QFontEngineGlyphCache::Type glyphType,
1528 QStaticTextItem *staticTextItem)
1530 Q_Q(QOpenGL2PaintEngineEx);
1532 QOpenGL2PaintEngineState *s = q->state();
1534 void *cacheKey = ctx->shareGroup();
1535 bool recreateVertexArrays = false;
1536 QFontEngine *fe = staticTextItem->fontEngine();
1538 QOpenGLTextureGlyphCache *cache =
1539 (QOpenGLTextureGlyphCache *) fe->glyphCache(cacheKey, glyphType, QTransform());
1540 if (!cache || cache->cacheType() != glyphType || cache->contextGroup() == 0) {
1541 cache = new QOpenGLTextureGlyphCache(glyphType, QTransform());
1542 fe->setGlyphCache(cacheKey, cache);
1543 recreateVertexArrays = true;
1546 if (staticTextItem->userDataNeedsUpdate) {
1547 recreateVertexArrays = true;
1548 } else if (staticTextItem->userData() == 0) {
1549 recreateVertexArrays = true;
1550 } else if (staticTextItem->userData()->type != QStaticTextUserData::OpenGLUserData) {
1551 recreateVertexArrays = true;
1553 QOpenGLStaticTextUserData *userData = static_cast<QOpenGLStaticTextUserData *>(staticTextItem->userData());
1554 if (userData->glyphType != glyphType) {
1555 recreateVertexArrays = true;
1556 } else if (userData->cacheSerialNumber != cache->serialNumber()) {
1557 recreateVertexArrays = true;
1561 // We only need to update the cache with new glyphs if we are actually going to recreate the vertex arrays.
1562 // If the cache size has changed, we do need to regenerate the vertices, but we don't need to repopulate the
1563 // cache so this text is performed before we test if the cache size has changed.
1564 if (recreateVertexArrays) {
1565 cache->setPaintEnginePrivate(this);
1566 if (!cache->populate(fe, staticTextItem->numGlyphs,
1567 staticTextItem->glyphs, staticTextItem->glyphPositions)) {
1568 // No space for glyphs in cache. We need to reset it and try again.
1570 cache->populate(fe, staticTextItem->numGlyphs,
1571 staticTextItem->glyphs, staticTextItem->glyphPositions);
1573 cache->fillInPendingGlyphs();
1576 if (cache->width() == 0 || cache->height() == 0)
1579 transferMode(TextDrawingMode);
1581 int margin = fe->glyphMargin(glyphType);
1583 GLfloat dx = 1.0 / cache->width();
1584 GLfloat dy = 1.0 / cache->height();
1586 // Use global arrays by default
1587 QOpenGL2PEXVertexArray *vertexCoordinates = &vertexCoordinateArray;
1588 QOpenGL2PEXVertexArray *textureCoordinates = &textureCoordinateArray;
1590 if (staticTextItem->useBackendOptimizations) {
1591 QOpenGLStaticTextUserData *userData = 0;
1593 if (staticTextItem->userData() == 0
1594 || staticTextItem->userData()->type != QStaticTextUserData::OpenGLUserData) {
1596 userData = new QOpenGLStaticTextUserData();
1597 staticTextItem->setUserData(userData);
1600 userData = static_cast<QOpenGLStaticTextUserData*>(staticTextItem->userData());
1603 userData->glyphType = glyphType;
1604 userData->cacheSerialNumber = cache->serialNumber();
1606 // Use cache if backend optimizations is turned on
1607 vertexCoordinates = &userData->vertexCoordinateArray;
1608 textureCoordinates = &userData->textureCoordinateArray;
1610 QSize size(cache->width(), cache->height());
1611 if (userData->cacheSize != size) {
1612 recreateVertexArrays = true;
1613 userData->cacheSize = size;
1617 if (recreateVertexArrays) {
1618 vertexCoordinates->clear();
1619 textureCoordinates->clear();
1621 bool supportsSubPixelPositions = fe->supportsSubPixelPositions();
1622 for (int i=0; i<staticTextItem->numGlyphs; ++i) {
1623 QFixed subPixelPosition;
1624 if (supportsSubPixelPositions)
1625 subPixelPosition = fe->subPixelPositionForX(staticTextItem->glyphPositions[i].x);
1627 QTextureGlyphCache::GlyphAndSubPixelPosition glyph(staticTextItem->glyphs[i], subPixelPosition);
1629 const QTextureGlyphCache::Coord &c = cache->coords[glyph];
1633 int x = qFloor(staticTextItem->glyphPositions[i].x) + c.baseLineX - margin;
1634 int y = qFloor(staticTextItem->glyphPositions[i].y) - c.baseLineY - margin;
1636 vertexCoordinates->addQuad(QRectF(x, y, c.w, c.h));
1637 textureCoordinates->addQuad(QRectF(c.x*dx, c.y*dy, c.w * dx, c.h * dy));
1640 staticTextItem->userDataNeedsUpdate = false;
1643 int numGlyphs = vertexCoordinates->vertexCount() / 4;
1647 if (elementIndices.size() < numGlyphs*6) {
1648 Q_ASSERT(elementIndices.size() % 6 == 0);
1649 int j = elementIndices.size() / 6 * 4;
1650 while (j < numGlyphs*4) {
1651 elementIndices.append(j + 0);
1652 elementIndices.append(j + 0);
1653 elementIndices.append(j + 1);
1654 elementIndices.append(j + 2);
1655 elementIndices.append(j + 3);
1656 elementIndices.append(j + 3);
1661 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1662 if (elementIndicesVBOId == 0)
1663 glGenBuffers(1, &elementIndicesVBOId);
1665 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
1666 glBufferData(GL_ELEMENT_ARRAY_BUFFER, elementIndices.size() * sizeof(GLushort),
1667 elementIndices.constData(), GL_STATIC_DRAW);
1670 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1671 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
1675 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)vertexCoordinates->data());
1676 setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, (GLfloat*)textureCoordinates->data());
1678 if (!snapToPixelGrid) {
1679 snapToPixelGrid = true;
1683 QBrush pensBrush = q->state()->pen.brush();
1684 setBrush(pensBrush);
1686 if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1688 // Subpixel antialiasing without gamma correction
1690 QPainter::CompositionMode compMode = q->state()->composition_mode;
1691 Q_ASSERT(compMode == QPainter::CompositionMode_Source
1692 || compMode == QPainter::CompositionMode_SourceOver);
1694 shaderManager->setMaskType(QOpenGLEngineShaderManager::SubPixelMaskPass1);
1696 if (pensBrush.style() == Qt::SolidPattern) {
1697 // Solid patterns can get away with only one pass.
1698 QColor c = pensBrush.color();
1699 qreal oldOpacity = q->state()->opacity;
1700 if (compMode == QPainter::CompositionMode_Source) {
1701 c = qt_premultiplyColor(c, q->state()->opacity);
1702 q->state()->opacity = 1;
1703 opacityUniformDirty = true;
1706 compositionModeDirty = false; // I can handle this myself, thank you very much
1707 prepareForDraw(false); // Text always causes src pixels to be transparent
1709 // prepareForDraw() have set the opacity on the current shader, so the opacity state can now be reset.
1710 if (compMode == QPainter::CompositionMode_Source) {
1711 q->state()->opacity = oldOpacity;
1712 opacityUniformDirty = true;
1716 glBlendFunc(GL_CONSTANT_COLOR, GL_ONE_MINUS_SRC_COLOR);
1717 funcs.glBlendColor(c.redF(), c.greenF(), c.blueF(), c.alphaF());
1719 // Other brush styles need two passes.
1721 qreal oldOpacity = q->state()->opacity;
1722 if (compMode == QPainter::CompositionMode_Source) {
1723 q->state()->opacity = 1;
1724 opacityUniformDirty = true;
1725 pensBrush = Qt::white;
1726 setBrush(pensBrush);
1729 compositionModeDirty = false; // I can handle this myself, thank you very much
1730 prepareForDraw(false); // Text always causes src pixels to be transparent
1732 glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR);
1734 funcs.glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
1735 glBindTexture(GL_TEXTURE_2D, cache->texture());
1736 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, false);
1738 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1739 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
1741 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, elementIndices.data());
1744 shaderManager->setMaskType(QOpenGLEngineShaderManager::SubPixelMaskPass2);
1746 if (compMode == QPainter::CompositionMode_Source) {
1747 q->state()->opacity = oldOpacity;
1748 opacityUniformDirty = true;
1749 pensBrush = q->state()->pen.brush();
1750 setBrush(pensBrush);
1753 compositionModeDirty = false;
1754 prepareForDraw(false); // Text always causes src pixels to be transparent
1756 glBlendFunc(GL_ONE, GL_ONE);
1758 compositionModeDirty = true;
1760 // Greyscale/mono glyphs
1762 shaderManager->setMaskType(QOpenGLEngineShaderManager::PixelMask);
1763 prepareForDraw(false); // Text always causes src pixels to be transparent
1766 QOpenGLTextureGlyphCache::FilterMode filterMode = (s->matrix.type() > QTransform::TxTranslate)?QOpenGLTextureGlyphCache::Linear:QOpenGLTextureGlyphCache::Nearest;
1767 if (lastMaskTextureUsed != cache->texture() || cache->filterMode() != filterMode) {
1769 funcs.glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
1770 if (lastMaskTextureUsed != cache->texture()) {
1771 glBindTexture(GL_TEXTURE_2D, cache->texture());
1772 lastMaskTextureUsed = cache->texture();
1775 if (cache->filterMode() != filterMode) {
1776 if (filterMode == QOpenGLTextureGlyphCache::Linear) {
1777 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1778 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1780 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1781 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1783 cache->setFilterMode(filterMode);
1787 bool srgbFrameBufferEnabled = false;
1788 if (funcs.hasOpenGLExtension(QOpenGLExtensions::SRGBFrameBuffer)) {
1791 glEnable(GL_FRAMEBUFFER_SRGB);
1792 srgbFrameBufferEnabled = true;
1796 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1797 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
1798 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1800 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, elementIndices.data());
1803 if (srgbFrameBufferEnabled)
1804 glDisable(GL_FRAMEBUFFER_SRGB);
1808 void QOpenGL2PaintEngineEx::drawPixmapFragments(const QPainter::PixmapFragment *fragments, int fragmentCount, const QPixmap &pixmap,
1809 QPainter::PixmapFragmentHints hints)
1811 Q_D(QOpenGL2PaintEngineEx);
1812 // Use fallback for extended composition modes.
1813 if (state()->composition_mode > QPainter::CompositionMode_Plus) {
1814 QPaintEngineEx::drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
1819 int max_texture_size = d->ctx->d_func()->maxTextureSize();
1820 if (pixmap.width() > max_texture_size || pixmap.height() > max_texture_size) {
1821 QPixmap scaled = pixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1822 d->drawPixmapFragments(fragments, fragmentCount, scaled, hints);
1824 d->drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
1829 void QOpenGL2PaintEngineExPrivate::drawPixmapFragments(const QPainter::PixmapFragment *fragments,
1830 int fragmentCount, const QPixmap &pixmap,
1831 QPainter::PixmapFragmentHints hints)
1833 GLfloat dx = 1.0f / pixmap.size().width();
1834 GLfloat dy = 1.0f / pixmap.size().height();
1836 vertexCoordinateArray.clear();
1837 textureCoordinateArray.clear();
1838 opacityArray.reset();
1840 if (snapToPixelGrid) {
1841 snapToPixelGrid = false;
1845 bool allOpaque = true;
1847 for (int i = 0; i < fragmentCount; ++i) {
1850 if (fragments[i].rotation != 0) {
1851 s = qFastSin(fragments[i].rotation * Q_PI / 180);
1852 c = qFastCos(fragments[i].rotation * Q_PI / 180);
1855 qreal right = 0.5 * fragments[i].scaleX * fragments[i].width;
1856 qreal bottom = 0.5 * fragments[i].scaleY * fragments[i].height;
1857 QOpenGLPoint bottomRight(right * c - bottom * s, right * s + bottom * c);
1858 QOpenGLPoint bottomLeft(-right * c - bottom * s, -right * s + bottom * c);
1860 vertexCoordinateArray.addVertex(bottomRight.x + fragments[i].x, bottomRight.y + fragments[i].y);
1861 vertexCoordinateArray.addVertex(-bottomLeft.x + fragments[i].x, -bottomLeft.y + fragments[i].y);
1862 vertexCoordinateArray.addVertex(-bottomRight.x + fragments[i].x, -bottomRight.y + fragments[i].y);
1863 vertexCoordinateArray.addVertex(-bottomRight.x + fragments[i].x, -bottomRight.y + fragments[i].y);
1864 vertexCoordinateArray.addVertex(bottomLeft.x + fragments[i].x, bottomLeft.y + fragments[i].y);
1865 vertexCoordinateArray.addVertex(bottomRight.x + fragments[i].x, bottomRight.y + fragments[i].y);
1867 QOpenGLRect src(fragments[i].sourceLeft * dx, fragments[i].sourceTop * dy,
1868 (fragments[i].sourceLeft + fragments[i].width) * dx,
1869 (fragments[i].sourceTop + fragments[i].height) * dy);
1871 textureCoordinateArray.addVertex(src.right, src.bottom);
1872 textureCoordinateArray.addVertex(src.right, src.top);
1873 textureCoordinateArray.addVertex(src.left, src.top);
1874 textureCoordinateArray.addVertex(src.left, src.top);
1875 textureCoordinateArray.addVertex(src.left, src.bottom);
1876 textureCoordinateArray.addVertex(src.right, src.bottom);
1878 qreal opacity = fragments[i].opacity * q->state()->opacity;
1879 opacityArray << opacity << opacity << opacity << opacity << opacity << opacity;
1880 allOpaque &= (opacity >= 0.99f);
1883 funcs.glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1884 GLuint id = QOpenGLTextureCache::cacheForContext(ctx)->bindTexture(ctx, pixmap);
1885 transferMode(ImageArrayDrawingMode);
1887 bool isBitmap = pixmap.isQBitmap();
1888 bool isOpaque = !isBitmap && (!pixmap.hasAlpha() || (hints & QPainter::OpaqueHint)) && allOpaque;
1890 updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1891 q->state()->renderHints & QPainter::SmoothPixmapTransform, id);
1893 // Setup for texture drawing
1894 currentBrush = noBrush;
1895 shaderManager->setSrcPixelType(isBitmap ? QOpenGLEngineShaderManager::PatternSrc
1896 : QOpenGLEngineShaderManager::ImageSrc);
1897 if (prepareForDraw(isOpaque))
1898 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::ImageTexture), QT_IMAGE_TEXTURE_UNIT);
1901 QColor col = qt_premultiplyColor(q->state()->pen.color(), (GLfloat)q->state()->opacity);
1902 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::PatternColor), col);
1905 glDrawArrays(GL_TRIANGLES, 0, 6 * fragmentCount);
1908 bool QOpenGL2PaintEngineEx::begin(QPaintDevice *pdev)
1910 Q_D(QOpenGL2PaintEngineEx);
1912 Q_ASSERT(pdev->devType() == QInternal::OpenGL);
1913 d->device = static_cast<QOpenGLPaintDevice*>(pdev);
1918 if (d->device->context() != QOpenGLContext::currentContext()) {
1919 qWarning("QPainter::begin(): QOpenGLPaintDevice's context needs to be current");
1923 d->ctx = QOpenGLContext::currentContext();
1924 d->ctx->d_func()->active_engine = this;
1926 d->funcs.initializeOpenGLFunctions();
1928 for (int i = 0; i < QT_GL_VERTEX_ARRAY_TRACKED_COUNT; ++i)
1929 d->vertexAttributeArraysEnabledState[i] = false;
1931 const QSize sz = d->device->size();
1932 d->width = sz.width();
1933 d->height = sz.height();
1934 d->mode = BrushDrawingMode;
1935 d->brushTextureDirty = true;
1936 d->brushUniformsDirty = true;
1937 d->matrixUniformDirty = true;
1938 d->matrixDirty = true;
1939 d->compositionModeDirty = true;
1940 d->opacityUniformDirty = true;
1941 d->needsSync = true;
1942 d->useSystemClip = !systemClip().isEmpty();
1943 d->currentBrush = QBrush();
1945 d->dirtyStencilRegion = QRect(0, 0, d->width, d->height);
1946 d->stencilClean = true;
1948 d->shaderManager = new QOpenGLEngineShaderManager(d->ctx);
1950 glDisable(GL_STENCIL_TEST);
1951 glDisable(GL_DEPTH_TEST);
1952 glDisable(GL_SCISSOR_TEST);
1954 #if !defined(QT_OPENGL_ES_2)
1955 glDisable(GL_MULTISAMPLE);
1958 d->glyphCacheType = QFontEngineGlyphCache::Raster_A8;
1960 #if !defined(QT_OPENGL_ES_2)
1961 d->glyphCacheType = QFontEngineGlyphCache::Raster_RGBMask;
1964 #if defined(QT_OPENGL_ES_2)
1965 // OpenGL ES can't switch MSAA off, so if the gl paint device is
1966 // multisampled, it's always multisampled.
1967 d->multisamplingAlwaysEnabled = d->device->context()->format().samples() > 1;
1969 d->multisamplingAlwaysEnabled = false;
1975 bool QOpenGL2PaintEngineEx::end()
1977 Q_D(QOpenGL2PaintEngineEx);
1979 QOpenGLContext *ctx = d->ctx;
1980 d->funcs.glUseProgram(0);
1981 d->transferMode(BrushDrawingMode);
1983 ctx->d_func()->active_engine = 0;
1987 delete d->shaderManager;
1988 d->shaderManager = 0;
1989 d->currentBrush = QBrush();
1991 #ifdef QT_OPENGL_CACHE_AS_VBOS
1992 if (!d->unusedVBOSToClean.isEmpty()) {
1993 glDeleteBuffers(d->unusedVBOSToClean.size(), d->unusedVBOSToClean.constData());
1994 d->unusedVBOSToClean.clear();
1996 if (!d->unusedIBOSToClean.isEmpty()) {
1997 glDeleteBuffers(d->unusedIBOSToClean.size(), d->unusedIBOSToClean.constData());
1998 d->unusedIBOSToClean.clear();
2005 void QOpenGL2PaintEngineEx::ensureActive()
2007 Q_D(QOpenGL2PaintEngineEx);
2008 QOpenGLContext *ctx = d->ctx;
2010 if (isActive() && ctx->d_func()->active_engine != this) {
2011 ctx->d_func()->active_engine = this;
2012 d->needsSync = true;
2016 d->transferMode(BrushDrawingMode);
2017 glViewport(0, 0, d->width, d->height);
2018 d->needsSync = false;
2019 d->lastMaskTextureUsed = 0;
2020 d->shaderManager->setDirty();
2022 for (int i = 0; i < 3; ++i)
2023 d->vertexAttribPointers[i] = (GLfloat*)-1; // Assume the pointers are clobbered
2028 void QOpenGL2PaintEngineExPrivate::updateClipScissorTest()
2030 Q_Q(QOpenGL2PaintEngineEx);
2031 if (q->state()->clipTestEnabled) {
2032 glEnable(GL_STENCIL_TEST);
2033 glStencilFunc(GL_LEQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
2035 glDisable(GL_STENCIL_TEST);
2036 glStencilFunc(GL_ALWAYS, 0, 0xff);
2039 #ifdef QT_GL_NO_SCISSOR_TEST
2040 currentScissorBounds = QRect(0, 0, width, height);
2042 QRect bounds = q->state()->rectangleClip;
2043 if (!q->state()->clipEnabled) {
2045 bounds = systemClip.boundingRect();
2047 bounds = QRect(0, 0, width, height);
2050 bounds = bounds.intersected(systemClip.boundingRect());
2052 bounds = bounds.intersected(QRect(0, 0, width, height));
2055 currentScissorBounds = bounds;
2057 if (bounds == QRect(0, 0, width, height)) {
2058 glDisable(GL_SCISSOR_TEST);
2060 glEnable(GL_SCISSOR_TEST);
2066 void QOpenGL2PaintEngineExPrivate::setScissor(const QRect &rect)
2068 const int left = rect.left();
2069 const int width = rect.width();
2070 int bottom = height - (rect.top() + rect.height());
2071 if (device->paintFlipped()) {
2072 bottom = rect.top();
2074 const int height = rect.height();
2076 glScissor(left, bottom, width, height);
2079 void QOpenGL2PaintEngineEx::clipEnabledChanged()
2081 Q_D(QOpenGL2PaintEngineEx);
2083 state()->clipChanged = true;
2085 if (painter()->hasClipping())
2086 d->regenerateClip();
2088 d->systemStateChanged();
2091 void QOpenGL2PaintEngineExPrivate::clearClip(uint value)
2093 dirtyStencilRegion -= currentScissorBounds;
2095 glStencilMask(0xff);
2096 glClearStencil(value);
2097 glClear(GL_STENCIL_BUFFER_BIT);
2100 q->state()->needsClipBufferClear = false;
2103 void QOpenGL2PaintEngineExPrivate::writeClip(const QVectorPath &path, uint value)
2105 transferMode(BrushDrawingMode);
2107 if (snapToPixelGrid) {
2108 snapToPixelGrid = false;
2115 stencilClean = false;
2117 const bool singlePass = !path.hasWindingFill()
2118 && (((q->state()->currentClip == maxClip - 1) && q->state()->clipTestEnabled)
2119 || q->state()->needsClipBufferClear);
2120 const uint referenceClipValue = q->state()->needsClipBufferClear ? 1 : q->state()->currentClip;
2122 if (q->state()->needsClipBufferClear)
2125 if (path.isEmpty()) {
2126 glEnable(GL_STENCIL_TEST);
2127 glStencilFunc(GL_LEQUAL, value, ~GL_STENCIL_HIGH_BIT);
2131 if (q->state()->clipTestEnabled)
2132 glStencilFunc(GL_LEQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
2134 glStencilFunc(GL_ALWAYS, 0, 0xff);
2136 vertexCoordinateArray.clear();
2137 vertexCoordinateArray.addPath(path, inverseScale, false);
2140 fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill());
2142 glColorMask(false, false, false, false);
2143 glEnable(GL_STENCIL_TEST);
2147 // Under these conditions we can set the new stencil value in a single
2148 // pass, by using the current value and the "new value" as the toggles
2150 glStencilFunc(GL_LEQUAL, referenceClipValue, ~GL_STENCIL_HIGH_BIT);
2151 glStencilOp(GL_KEEP, GL_INVERT, GL_INVERT);
2152 glStencilMask(value ^ referenceClipValue);
2154 drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN);
2156 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
2157 glStencilMask(0xff);
2159 if (!q->state()->clipTestEnabled && path.hasWindingFill()) {
2160 // Pass when any clip bit is set, set high bit
2161 glStencilFunc(GL_NOTEQUAL, GL_STENCIL_HIGH_BIT, ~GL_STENCIL_HIGH_BIT);
2162 composite(vertexCoordinateArray.boundingRect());
2165 // Pass when high bit is set, replace stencil value with new clip value
2166 glStencilFunc(GL_NOTEQUAL, value, GL_STENCIL_HIGH_BIT);
2168 composite(vertexCoordinateArray.boundingRect());
2171 glStencilFunc(GL_LEQUAL, value, ~GL_STENCIL_HIGH_BIT);
2174 glColorMask(true, true, true, true);
2177 void QOpenGL2PaintEngineEx::clip(const QVectorPath &path, Qt::ClipOperation op)
2179 // qDebug("QOpenGL2PaintEngineEx::clip()");
2180 Q_D(QOpenGL2PaintEngineEx);
2182 state()->clipChanged = true;
2186 if (op == Qt::ReplaceClip) {
2187 op = Qt::IntersectClip;
2188 if (d->hasClipOperations()) {
2189 d->systemStateChanged();
2190 state()->canRestoreClip = false;
2194 #ifndef QT_GL_NO_SCISSOR_TEST
2195 if (!path.isEmpty() && op == Qt::IntersectClip && (path.shape() == QVectorPath::RectangleHint)) {
2196 const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
2197 QRectF rect(points[0], points[2]);
2199 if (state()->matrix.type() <= QTransform::TxScale
2200 || (state()->matrix.type() == QTransform::TxRotate
2201 && qFuzzyIsNull(state()->matrix.m11())
2202 && qFuzzyIsNull(state()->matrix.m22())))
2204 state()->rectangleClip = state()->rectangleClip.intersected(state()->matrix.mapRect(rect).toRect());
2205 d->updateClipScissorTest();
2211 const QRect pathRect = state()->matrix.mapRect(path.controlPointRect()).toAlignedRect();
2215 if (d->useSystemClip) {
2216 state()->clipTestEnabled = true;
2217 state()->currentClip = 1;
2219 state()->clipTestEnabled = false;
2221 state()->rectangleClip = QRect(0, 0, d->width, d->height);
2222 state()->canRestoreClip = false;
2223 d->updateClipScissorTest();
2225 case Qt::IntersectClip:
2226 state()->rectangleClip = state()->rectangleClip.intersected(pathRect);
2227 d->updateClipScissorTest();
2228 d->resetClipIfNeeded();
2230 d->writeClip(path, d->maxClip);
2231 state()->currentClip = d->maxClip;
2232 state()->clipTestEnabled = true;
2239 void QOpenGL2PaintEngineExPrivate::regenerateClip()
2241 systemStateChanged();
2242 replayClipOperations();
2245 void QOpenGL2PaintEngineExPrivate::systemStateChanged()
2247 Q_Q(QOpenGL2PaintEngineEx);
2249 q->state()->clipChanged = true;
2251 if (systemClip.isEmpty()) {
2252 useSystemClip = false;
2254 if (q->paintDevice()->devType() == QInternal::Widget && currentClipDevice) {
2255 //QWidgetPrivate *widgetPrivate = qt_widget_private(static_cast<QWidget *>(currentClipDevice)->window());
2256 //useSystemClip = widgetPrivate->extra && widgetPrivate->extra->inRenderWithPainter;
2257 useSystemClip = true;
2259 useSystemClip = true;
2263 q->state()->clipTestEnabled = false;
2264 q->state()->needsClipBufferClear = true;
2266 q->state()->currentClip = 1;
2269 q->state()->rectangleClip = useSystemClip ? systemClip.boundingRect() : QRect(0, 0, width, height);
2270 updateClipScissorTest();
2272 if (systemClip.rectCount() == 1) {
2273 if (systemClip.boundingRect() == QRect(0, 0, width, height))
2274 useSystemClip = false;
2275 #ifndef QT_GL_NO_SCISSOR_TEST
2276 // scissoring takes care of the system clip
2281 if (useSystemClip) {
2285 path.addRegion(systemClip);
2287 q->state()->currentClip = 0;
2288 writeClip(qtVectorPathForPath(q->state()->matrix.inverted().map(path)), 1);
2289 q->state()->currentClip = 1;
2290 q->state()->clipTestEnabled = true;
2294 void QOpenGL2PaintEngineEx::setState(QPainterState *new_state)
2296 // qDebug("QOpenGL2PaintEngineEx::setState()");
2298 Q_D(QOpenGL2PaintEngineEx);
2300 QOpenGL2PaintEngineState *s = static_cast<QOpenGL2PaintEngineState *>(new_state);
2301 QOpenGL2PaintEngineState *old_state = state();
2303 QPaintEngineEx::setState(s);
2306 // Newly created state object. The call to setState()
2307 // will either be followed by a call to begin(), or we are
2308 // setting the state as part of a save().
2313 // Setting the state as part of a restore().
2315 if (old_state == s || old_state->renderHintsChanged)
2316 renderHintsChanged();
2318 if (old_state == s || old_state->matrixChanged)
2319 d->matrixDirty = true;
2321 if (old_state == s || old_state->compositionModeChanged)
2322 d->compositionModeDirty = true;
2324 if (old_state == s || old_state->opacityChanged)
2325 d->opacityUniformDirty = true;
2327 if (old_state == s || old_state->clipChanged) {
2328 if (old_state && old_state != s && old_state->canRestoreClip) {
2329 d->updateClipScissorTest();
2330 glDepthFunc(GL_LEQUAL);
2332 d->regenerateClip();
2337 QPainterState *QOpenGL2PaintEngineEx::createState(QPainterState *orig) const
2340 const_cast<QOpenGL2PaintEngineEx *>(this)->ensureActive();
2342 QOpenGL2PaintEngineState *s;
2344 s = new QOpenGL2PaintEngineState();
2346 s = new QOpenGL2PaintEngineState(*static_cast<QOpenGL2PaintEngineState *>(orig));
2348 s->matrixChanged = false;
2349 s->compositionModeChanged = false;
2350 s->opacityChanged = false;
2351 s->renderHintsChanged = false;
2352 s->clipChanged = false;
2357 QOpenGL2PaintEngineState::QOpenGL2PaintEngineState(QOpenGL2PaintEngineState &other)
2358 : QPainterState(other)
2361 needsClipBufferClear = other.needsClipBufferClear;
2362 clipTestEnabled = other.clipTestEnabled;
2363 currentClip = other.currentClip;
2364 canRestoreClip = other.canRestoreClip;
2365 rectangleClip = other.rectangleClip;
2368 QOpenGL2PaintEngineState::QOpenGL2PaintEngineState()
2371 needsClipBufferClear = true;
2372 clipTestEnabled = false;
2373 canRestoreClip = true;
2376 QOpenGL2PaintEngineState::~QOpenGL2PaintEngineState()
2380 void QOpenGL2PaintEngineExPrivate::setVertexAttribArrayEnabled(int arrayIndex, bool enabled)
2382 Q_ASSERT(arrayIndex < QT_GL_VERTEX_ARRAY_TRACKED_COUNT);
2384 if (vertexAttributeArraysEnabledState[arrayIndex] && !enabled)
2385 funcs.glDisableVertexAttribArray(arrayIndex);
2387 if (!vertexAttributeArraysEnabledState[arrayIndex] && enabled)
2388 funcs.glEnableVertexAttribArray(arrayIndex);
2390 vertexAttributeArraysEnabledState[arrayIndex] = enabled;
2393 void QOpenGL2PaintEngineExPrivate::syncGlState()
2395 for (int i = 0; i < QT_GL_VERTEX_ARRAY_TRACKED_COUNT; ++i) {
2396 if (vertexAttributeArraysEnabledState[i])
2397 funcs.glEnableVertexAttribArray(i);
2399 funcs.glDisableVertexAttribArray(i);