1 /****************************************************************************
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the QtGui module of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
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 "qopenglpaintengine_p.h"
70 #include <string.h> //for memcpy
73 #include <private/qopengl_p.h>
74 #include <private/qopenglcontext_p.h>
75 #include <private/qopenglextensions_p.h>
76 #include <private/qmath_p.h>
77 #include <private/qpaintengineex_p.h>
78 #include <QPaintEngine>
79 #include <private/qpainter_p.h>
80 #include <private/qfontengine_p.h>
81 #include <private/qdatabuffer_p.h>
82 #include <private/qstatictext_p.h>
83 #include <private/qtriangulator_p.h>
85 #include "qopenglengineshadermanager_p.h"
86 #include "qopengl2pexvertexarray_p.h"
87 #include "qopengltriangulatingstroker_p.h"
88 #include "qopengltextureglyphcache_p.h"
95 extern Q_GUI_EXPORT bool qt_cleartype_enabled;
99 extern bool qt_applefontsmoothing_enabled;
102 Q_GUI_EXPORT QImage qt_imageForBrush(int brushStyle, bool invert);
104 ////////////////////////////////// Private Methods //////////////////////////////////////////
106 QOpenGL2PaintEngineExPrivate::~QOpenGL2PaintEngineExPrivate()
108 delete shaderManager;
110 while (pathCaches.size()) {
111 QVectorPath::CacheEntry *e = *(pathCaches.constBegin());
112 e->cleanup(e->engine, e->data);
117 if (elementIndicesVBOId != 0) {
118 funcs.glDeleteBuffers(1, &elementIndicesVBOId);
119 elementIndicesVBOId = 0;
123 void QOpenGL2PaintEngineExPrivate::updateTextureFilter(GLenum target, GLenum wrapMode, bool smoothPixmapTransform, GLuint id)
125 // funcs.glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT); //### Is it always this texture unit?
126 if (id != GLuint(-1) && id == lastTextureUsed)
129 lastTextureUsed = id;
131 if (smoothPixmapTransform) {
132 glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
133 glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
135 glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
136 glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
138 glTexParameterf(target, GL_TEXTURE_WRAP_S, wrapMode);
139 glTexParameterf(target, GL_TEXTURE_WRAP_T, wrapMode);
143 inline QColor qt_premultiplyColor(QColor c, GLfloat opacity)
145 qreal alpha = c.alphaF() * opacity;
147 c.setRedF(c.redF() * alpha);
148 c.setGreenF(c.greenF() * alpha);
149 c.setBlueF(c.blueF() * alpha);
154 void QOpenGL2PaintEngineExPrivate::setBrush(const QBrush& brush)
156 if (qbrush_fast_equals(currentBrush, brush))
159 const Qt::BrushStyle newStyle = qbrush_style(brush);
160 Q_ASSERT(newStyle != Qt::NoBrush);
162 currentBrush = brush;
163 if (!currentBrushPixmap.isNull())
164 currentBrushPixmap = QPixmap();
165 brushUniformsDirty = true; // All brushes have at least one uniform
167 if (newStyle > Qt::SolidPattern)
168 brushTextureDirty = true;
170 if (currentBrush.style() == Qt::TexturePattern
171 && qHasPixmapTexture(brush) && brush.texture().isQBitmap())
173 shaderManager->setSrcPixelType(QOpenGLEngineShaderManager::TextureSrcWithPattern);
175 shaderManager->setSrcPixelType(newStyle);
177 shaderManager->optimiseForBrushTransform(currentBrush.transform().type());
181 void QOpenGL2PaintEngineExPrivate::useSimpleShader()
183 shaderManager->useSimpleProgram();
189 void QOpenGL2PaintEngineExPrivate::updateBrushTexture()
191 Q_Q(QOpenGL2PaintEngineEx);
192 // qDebug("QOpenGL2PaintEngineExPrivate::updateBrushTexture()");
193 Qt::BrushStyle style = currentBrush.style();
195 if ( (style >= Qt::Dense1Pattern) && (style <= Qt::DiagCrossPattern) ) {
196 // Get the image data for the pattern
197 QImage texImage = qt_imageForBrush(style, false);
199 funcs.glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
200 //ctx->d_func()->bindTexture(texImage, GL_TEXTURE_2D, GL_RGBA, QOpenGLContext::InternalBindOption);
201 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
203 else if (style >= Qt::LinearGradientPattern && style <= Qt::ConicalGradientPattern) {
204 // Gradiant brush: All the gradiants use the same texture
206 const QGradient* g = currentBrush.gradient();
208 // We apply global opacity in the fragment shaders, so we always pass 1.0
209 // for opacity to the cache.
210 GLuint texId = QOpenGL2GradientCache::cacheForContext(ctx)->getBuffer(*g, 1.0);
212 funcs.glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
213 glBindTexture(GL_TEXTURE_2D, texId);
215 if (g->spread() == QGradient::RepeatSpread || g->type() == QGradient::ConicalGradient)
216 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
217 else if (g->spread() == QGradient::ReflectSpread)
218 updateTextureFilter(GL_TEXTURE_2D, GL_MIRRORED_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
220 updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE, q->state()->renderHints & QPainter::SmoothPixmapTransform);
222 else if (style == Qt::TexturePattern) {
223 currentBrushPixmap = currentBrush.texture();
225 int max_texture_size = ctx->d_func()->maxTextureSize();
226 if (currentBrushPixmap.width() > max_texture_size || currentBrushPixmap.height() > max_texture_size)
227 currentBrushPixmap = currentBrushPixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
229 funcs.glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
230 QOpenGLTexture *tex = 0;//ctx->d_func()->bindTexture(currentBrushPixmap, GL_TEXTURE_2D, GL_RGBA,
231 // QOpenGLContext::InternalBindOption |
232 // QOpenGLContext::CanFlipNativePixmapBindOption);
233 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
234 textureInvertedY = tex->invertedY();
236 brushTextureDirty = false;
240 void QOpenGL2PaintEngineExPrivate::updateBrushUniforms()
242 // qDebug("QOpenGL2PaintEngineExPrivate::updateBrushUniforms()");
243 Qt::BrushStyle style = currentBrush.style();
245 if (style == Qt::NoBrush)
248 QTransform brushQTransform = currentBrush.transform();
250 if (style == Qt::SolidPattern) {
251 QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
252 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::FragmentColor), col);
255 // All other brushes have a transform and thus need the translation point:
256 QPointF translationPoint;
258 if (style <= Qt::DiagCrossPattern) {
259 QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
261 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::PatternColor), col);
263 QVector2D halfViewportSize(width*0.5, height*0.5);
264 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
266 else if (style == Qt::LinearGradientPattern) {
267 const QLinearGradient *g = static_cast<const QLinearGradient *>(currentBrush.gradient());
269 QPointF realStart = g->start();
270 QPointF realFinal = g->finalStop();
271 translationPoint = realStart;
273 QPointF l = realFinal - realStart;
275 QVector3D linearData(
278 1.0f / (l.x() * l.x() + l.y() * l.y())
281 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::LinearData), linearData);
283 QVector2D halfViewportSize(width*0.5, height*0.5);
284 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
286 else if (style == Qt::ConicalGradientPattern) {
287 const QConicalGradient *g = static_cast<const QConicalGradient *>(currentBrush.gradient());
288 translationPoint = g->center();
290 GLfloat angle = -(g->angle() * 2 * Q_PI) / 360.0;
292 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Angle), angle);
294 QVector2D halfViewportSize(width*0.5, height*0.5);
295 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
297 else if (style == Qt::RadialGradientPattern) {
298 const QRadialGradient *g = static_cast<const QRadialGradient *>(currentBrush.gradient());
299 QPointF realCenter = g->center();
300 QPointF realFocal = g->focalPoint();
301 qreal realRadius = g->centerRadius() - g->focalRadius();
302 translationPoint = realFocal;
304 QPointF fmp = realCenter - realFocal;
305 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Fmp), fmp);
307 GLfloat fmp2_m_radius2 = -fmp.x() * fmp.x() - fmp.y() * fmp.y() + realRadius*realRadius;
308 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Fmp2MRadius2), fmp2_m_radius2);
309 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Inverse2Fmp2MRadius2),
310 GLfloat(1.0 / (2.0*fmp2_m_radius2)));
311 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::SqrFr),
312 GLfloat(g->focalRadius() * g->focalRadius()));
313 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::BRadius),
314 GLfloat(2 * (g->centerRadius() - g->focalRadius()) * g->focalRadius()),
316 g->centerRadius() - g->focalRadius());
318 QVector2D halfViewportSize(width*0.5, height*0.5);
319 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
321 else if (style == Qt::TexturePattern) {
322 const QPixmap& texPixmap = currentBrush.texture();
324 if (qHasPixmapTexture(currentBrush) && currentBrush.texture().isQBitmap()) {
325 QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
326 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::PatternColor), col);
329 QSizeF invertedTextureSize(1.0 / texPixmap.width(), 1.0 / texPixmap.height());
330 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::InvertedTextureSize), invertedTextureSize);
332 QVector2D halfViewportSize(width*0.5, height*0.5);
333 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
336 qWarning("QOpenGL2PaintEngineEx: Unimplemented fill style");
338 const QPointF &brushOrigin = q->state()->brushOrigin;
339 QTransform matrix = q->state()->matrix;
340 matrix.translate(brushOrigin.x(), brushOrigin.y());
342 QTransform translate(1, 0, 0, 1, -translationPoint.x(), -translationPoint.y());
345 if (device->paintFlipped()) {
349 QTransform gl_to_qt(1, 0, 0, m22, 0, dy);
350 QTransform inv_matrix;
351 if (style == Qt::TexturePattern && textureInvertedY == -1)
352 inv_matrix = gl_to_qt * (QTransform(1, 0, 0, -1, 0, currentBrush.texture().height()) * brushQTransform * matrix).inverted() * translate;
354 inv_matrix = gl_to_qt * (brushQTransform * matrix).inverted() * translate;
356 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::BrushTransform), inv_matrix);
357 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::BrushTexture), QT_BRUSH_TEXTURE_UNIT);
359 brushUniformsDirty = false;
363 // This assumes the shader manager has already setup the correct shader program
364 void QOpenGL2PaintEngineExPrivate::updateMatrix()
366 // qDebug("QOpenGL2PaintEngineExPrivate::updateMatrix()");
368 const QTransform& transform = q->state()->matrix;
370 // The projection matrix converts from Qt's coordinate system to GL's coordinate system
371 // * GL's viewport is 2x2, Qt's is width x height
372 // * GL has +y -> -y going from bottom -> top, Qt is the other way round
373 // * GL has [0,0] in the center, Qt has it in the top-left
375 // This results in the Projection matrix below, which is multiplied by the painter's
376 // transformation matrix, as shown below:
378 // Projection Matrix Painter Transform
379 // ------------------------------------------------ ------------------------
380 // | 2.0 / width | 0.0 | -1.0 | | m11 | m21 | dx |
381 // | 0.0 | -2.0 / height | 1.0 | * | m12 | m22 | dy |
382 // | 0.0 | 0.0 | 1.0 | | m13 | m23 | m33 |
383 // ------------------------------------------------ ------------------------
385 // NOTE: The resultant matrix is also transposed, as GL expects column-major matracies
387 const GLfloat wfactor = 2.0f / width;
388 GLfloat hfactor = -2.0f / height;
390 GLfloat dx = transform.dx();
391 GLfloat dy = transform.dy();
393 if (device->paintFlipped()) {
398 // Non-integer translates can have strange effects for some rendering operations such as
399 // anti-aliased text rendering. In such cases, we snap the translate to the pixel grid.
400 if (snapToPixelGrid && transform.type() == QTransform::TxTranslate) {
401 // 0.50 needs to rounded down to 0.0 for consistency with raster engine:
402 dx = ceilf(dx - 0.5f);
403 dy = ceilf(dy - 0.5f);
405 pmvMatrix[0][0] = (wfactor * transform.m11()) - transform.m13();
406 pmvMatrix[1][0] = (wfactor * transform.m21()) - transform.m23();
407 pmvMatrix[2][0] = (wfactor * dx) - transform.m33();
408 pmvMatrix[0][1] = (hfactor * transform.m12()) + transform.m13();
409 pmvMatrix[1][1] = (hfactor * transform.m22()) + transform.m23();
410 pmvMatrix[2][1] = (hfactor * dy) + transform.m33();
411 pmvMatrix[0][2] = transform.m13();
412 pmvMatrix[1][2] = transform.m23();
413 pmvMatrix[2][2] = transform.m33();
415 // 1/10000 == 0.0001, so we have good enough res to cover curves
416 // that span the entire widget...
417 inverseScale = qMax(1 / qMax( qMax(qAbs(transform.m11()), qAbs(transform.m22())),
418 qMax(qAbs(transform.m12()), qAbs(transform.m21())) ),
422 matrixUniformDirty = true;
424 // Set the PMV matrix attribute. As we use an attributes rather than uniforms, we only
425 // need to do this once for every matrix change and persists across all shader programs.
426 funcs.glVertexAttrib3fv(QT_PMV_MATRIX_1_ATTR, pmvMatrix[0]);
427 funcs.glVertexAttrib3fv(QT_PMV_MATRIX_2_ATTR, pmvMatrix[1]);
428 funcs.glVertexAttrib3fv(QT_PMV_MATRIX_3_ATTR, pmvMatrix[2]);
430 dasher.setInvScale(inverseScale);
431 stroker.setInvScale(inverseScale);
435 void QOpenGL2PaintEngineExPrivate::updateCompositionMode()
437 // NOTE: The entire paint engine works on pre-multiplied data - which is why some of these
438 // composition modes look odd.
439 // qDebug() << "QOpenGL2PaintEngineExPrivate::updateCompositionMode() - Setting GL composition mode for " << q->state()->composition_mode;
440 switch(q->state()->composition_mode) {
441 case QPainter::CompositionMode_SourceOver:
442 glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
444 case QPainter::CompositionMode_DestinationOver:
445 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE);
447 case QPainter::CompositionMode_Clear:
448 glBlendFunc(GL_ZERO, GL_ZERO);
450 case QPainter::CompositionMode_Source:
451 glBlendFunc(GL_ONE, GL_ZERO);
453 case QPainter::CompositionMode_Destination:
454 glBlendFunc(GL_ZERO, GL_ONE);
456 case QPainter::CompositionMode_SourceIn:
457 glBlendFunc(GL_DST_ALPHA, GL_ZERO);
459 case QPainter::CompositionMode_DestinationIn:
460 glBlendFunc(GL_ZERO, GL_SRC_ALPHA);
462 case QPainter::CompositionMode_SourceOut:
463 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ZERO);
465 case QPainter::CompositionMode_DestinationOut:
466 glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_ALPHA);
468 case QPainter::CompositionMode_SourceAtop:
469 glBlendFunc(GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
471 case QPainter::CompositionMode_DestinationAtop:
472 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA);
474 case QPainter::CompositionMode_Xor:
475 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
477 case QPainter::CompositionMode_Plus:
478 glBlendFunc(GL_ONE, GL_ONE);
481 qWarning("Unsupported composition mode");
485 compositionModeDirty = false;
488 static inline void setCoords(GLfloat *coords, const QOpenGLRect &rect)
490 coords[0] = rect.left;
491 coords[1] = rect.top;
492 coords[2] = rect.right;
493 coords[3] = rect.top;
494 coords[4] = rect.right;
495 coords[5] = rect.bottom;
496 coords[6] = rect.left;
497 coords[7] = rect.bottom;
500 void QOpenGL2PaintEngineExPrivate::drawTexture(const QOpenGLRect& dest, const QOpenGLRect& src, const QSize &textureSize, bool opaque, bool pattern)
502 // Setup for texture drawing
503 currentBrush = noBrush;
504 shaderManager->setSrcPixelType(pattern ? QOpenGLEngineShaderManager::PatternSrc : QOpenGLEngineShaderManager::ImageSrc);
506 if (snapToPixelGrid) {
507 snapToPixelGrid = false;
511 if (prepareForDraw(opaque))
512 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::ImageTexture), QT_IMAGE_TEXTURE_UNIT);
515 QColor col = qt_premultiplyColor(q->state()->pen.color(), (GLfloat)q->state()->opacity);
516 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::PatternColor), col);
519 GLfloat dx = 1.0 / textureSize.width();
520 GLfloat dy = 1.0 / textureSize.height();
522 QOpenGLRect srcTextureRect(src.left*dx, src.top*dy, src.right*dx, src.bottom*dy);
524 setCoords(staticVertexCoordinateArray, dest);
525 setCoords(staticTextureCoordinateArray, srcTextureRect);
527 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
530 void QOpenGL2PaintEngineEx::beginNativePainting()
532 Q_D(QOpenGL2PaintEngineEx);
534 d->transferMode(BrushDrawingMode);
536 d->nativePaintingActive = true;
538 d->funcs.glUseProgram(0);
540 // Disable all the vertex attribute arrays:
541 for (int i = 0; i < QT_GL_VERTEX_ARRAY_TRACKED_COUNT; ++i)
542 d->funcs.glDisableVertexAttribArray(i);
544 #ifndef QT_OPENGL_ES_2
545 Q_ASSERT(QOpenGLContext::currentContext());
546 const QSurfaceFormat &fmt = d->device->context()->format();
547 if (fmt.majorVersion() < 3 || (fmt.majorVersion() == 3 && fmt.minorVersion() < 1)
548 || fmt.profile() == QSurfaceFormat::CompatibilityProfile)
550 // be nice to people who mix OpenGL 1.x code with QPainter commands
551 // by setting modelview and projection matrices to mirror the GL 1
553 const QTransform& mtx = state()->matrix;
555 float mv_matrix[4][4] =
557 { float(mtx.m11()), float(mtx.m12()), 0, float(mtx.m13()) },
558 { float(mtx.m21()), float(mtx.m22()), 0, float(mtx.m23()) },
560 { float(mtx.dx()), float(mtx.dy()), 0, float(mtx.m33()) }
563 const QSize sz = d->device->size();
565 glMatrixMode(GL_PROJECTION);
567 glOrtho(0, sz.width(), sz.height(), 0, -999999, 999999);
569 glMatrixMode(GL_MODELVIEW);
570 glLoadMatrixf(&mv_matrix[0][0]);
574 d->lastTextureUsed = GLuint(-1);
575 d->dirtyStencilRegion = QRect(0, 0, d->width, d->height);
578 d->shaderManager->setDirty();
583 void QOpenGL2PaintEngineExPrivate::resetGLState()
586 funcs.glActiveTexture(GL_TEXTURE0);
587 glDisable(GL_STENCIL_TEST);
588 glDisable(GL_DEPTH_TEST);
589 glDisable(GL_SCISSOR_TEST);
591 glDepthFunc(GL_LESS);
592 funcs.glClearDepthf(1);
594 glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
595 glStencilFunc(GL_ALWAYS, 0, 0xff);
596 setVertexAttribArrayEnabled(QT_TEXTURE_COORDS_ATTR, false);
597 setVertexAttribArrayEnabled(QT_VERTEX_COORDS_ATTR, false);
598 setVertexAttribArrayEnabled(QT_OPACITY_ATTR, false);
599 #ifndef QT_OPENGL_ES_2
600 // gl_Color, corresponding to vertex attribute 3, may have been changed
601 float color[] = { 1.0f, 1.0f, 1.0f, 1.0f };
602 funcs.glVertexAttrib4fv(3, color);
606 void QOpenGL2PaintEngineEx::endNativePainting()
608 Q_D(QOpenGL2PaintEngineEx);
610 d->nativePaintingActive = false;
613 void QOpenGL2PaintEngineEx::invalidateState()
615 Q_D(QOpenGL2PaintEngineEx);
619 bool QOpenGL2PaintEngineEx::isNativePaintingActive() const {
620 Q_D(const QOpenGL2PaintEngineEx);
621 return d->nativePaintingActive;
624 void QOpenGL2PaintEngineExPrivate::transferMode(EngineMode newMode)
629 if (mode == TextDrawingMode || mode == ImageDrawingMode || mode == ImageArrayDrawingMode) {
630 lastTextureUsed = GLuint(-1);
633 if (newMode == TextDrawingMode) {
634 shaderManager->setHasComplexGeometry(true);
636 shaderManager->setHasComplexGeometry(false);
639 if (newMode == ImageDrawingMode) {
640 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, staticVertexCoordinateArray);
641 setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, staticTextureCoordinateArray);
644 if (newMode == ImageArrayDrawingMode) {
645 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)vertexCoordinateArray.data());
646 setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, (GLfloat*)textureCoordinateArray.data());
647 setVertexAttributePointer(QT_OPACITY_ATTR, (GLfloat*)opacityArray.data());
650 // This needs to change when we implement high-quality anti-aliasing...
651 if (newMode != TextDrawingMode)
652 shaderManager->setMaskType(QOpenGLEngineShaderManager::NoMask);
657 struct QOpenGL2PEVectorPathCache
659 #ifdef QT_OPENGL_CACHE_AS_VBOS
668 GLenum primitiveType;
670 QVertexIndexVector::Type indexType;
673 void QOpenGL2PaintEngineExPrivate::cleanupVectorPath(QPaintEngineEx *engine, void *data)
675 QOpenGL2PEVectorPathCache *c = (QOpenGL2PEVectorPathCache *) data;
676 #ifdef QT_OPENGL_CACHE_AS_VBOS
677 Q_ASSERT(engine->type() == QPaintEngine::OpenGL2);
678 static_cast<QOpenGL2PaintEngineEx *>(engine)->d_func()->unusedVBOSToClean << c->vbo;
680 d->unusedIBOSToClean << c->ibo;
689 // Assumes everything is configured for the brush you want to use
690 void QOpenGL2PaintEngineExPrivate::fill(const QVectorPath& path)
692 transferMode(BrushDrawingMode);
694 if (snapToPixelGrid) {
695 snapToPixelGrid = false;
699 // Might need to call updateMatrix to re-calculate inverseScale
703 const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
705 // Check to see if there's any hints
706 if (path.shape() == QVectorPath::RectangleHint) {
707 QOpenGLRect rect(points[0].x(), points[0].y(), points[2].x(), points[2].y());
708 prepareForDraw(currentBrush.isOpaque());
710 } else if (path.isConvex()) {
712 if (path.isCacheable()) {
713 QVectorPath::CacheEntry *data = path.lookupCacheData(q);
714 QOpenGL2PEVectorPathCache *cache;
716 bool updateCache = false;
719 cache = (QOpenGL2PEVectorPathCache *) data->data;
720 // Check if scale factor is exceeded for curved paths and generate curves if so...
721 if (path.isCurved()) {
722 qreal scaleFactor = cache->iscale / inverseScale;
723 if (scaleFactor < 0.5 || scaleFactor > 2.0) {
724 #ifdef QT_OPENGL_CACHE_AS_VBOS
725 glDeleteBuffers(1, &cache->vbo);
727 Q_ASSERT(cache->ibo == 0);
729 qFree(cache->vertices);
730 Q_ASSERT(cache->indices == 0);
736 cache = new QOpenGL2PEVectorPathCache;
737 data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
741 // Flatten the path at the current scale factor and fill it into the cache struct.
743 vertexCoordinateArray.clear();
744 vertexCoordinateArray.addPath(path, inverseScale, false);
745 int vertexCount = vertexCoordinateArray.vertexCount();
746 int floatSizeInBytes = vertexCount * 2 * sizeof(float);
747 cache->vertexCount = vertexCount;
748 cache->indexCount = 0;
749 cache->primitiveType = GL_TRIANGLE_FAN;
750 cache->iscale = inverseScale;
751 #ifdef QT_OPENGL_CACHE_AS_VBOS
752 glGenBuffers(1, &cache->vbo);
753 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
754 glBufferData(GL_ARRAY_BUFFER, floatSizeInBytes, vertexCoordinateArray.data(), GL_STATIC_DRAW);
757 cache->vertices = (float *) qMalloc(floatSizeInBytes);
758 memcpy(cache->vertices, vertexCoordinateArray.data(), floatSizeInBytes);
763 prepareForDraw(currentBrush.isOpaque());
764 #ifdef QT_OPENGL_CACHE_AS_VBOS
765 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
766 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, 0);
768 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, cache->vertices);
770 glDrawArrays(cache->primitiveType, 0, cache->vertexCount);
773 // printf(" - Marking path as cachable...\n");
774 // Tag it for later so that if the same path is drawn twice, it is assumed to be static and thus cachable
775 path.makeCacheable();
776 vertexCoordinateArray.clear();
777 vertexCoordinateArray.addPath(path, inverseScale, false);
778 prepareForDraw(currentBrush.isOpaque());
779 drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN);
783 bool useCache = path.isCacheable();
785 QRectF bbox = path.controlPointRect();
786 // If the path doesn't fit within these limits, it is possible that the triangulation will fail.
787 useCache &= (bbox.left() > -0x8000 * inverseScale)
788 && (bbox.right() < 0x8000 * inverseScale)
789 && (bbox.top() > -0x8000 * inverseScale)
790 && (bbox.bottom() < 0x8000 * inverseScale);
794 QVectorPath::CacheEntry *data = path.lookupCacheData(q);
795 QOpenGL2PEVectorPathCache *cache;
797 bool updateCache = false;
800 cache = (QOpenGL2PEVectorPathCache *) data->data;
801 // Check if scale factor is exceeded for curved paths and generate curves if so...
802 if (path.isCurved()) {
803 qreal scaleFactor = cache->iscale / inverseScale;
804 if (scaleFactor < 0.5 || scaleFactor > 2.0) {
805 #ifdef QT_OPENGL_CACHE_AS_VBOS
806 glDeleteBuffers(1, &cache->vbo);
807 glDeleteBuffers(1, &cache->ibo);
809 qFree(cache->vertices);
810 qFree(cache->indices);
816 cache = new QOpenGL2PEVectorPathCache;
817 data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
821 // Flatten the path at the current scale factor and fill it into the cache struct.
823 QTriangleSet polys = qTriangulate(path, QTransform().scale(1 / inverseScale, 1 / inverseScale));
824 cache->vertexCount = polys.vertices.size() / 2;
825 cache->indexCount = polys.indices.size();
826 cache->primitiveType = GL_TRIANGLES;
827 cache->iscale = inverseScale;
828 cache->indexType = polys.indices.type();
829 #ifdef QT_OPENGL_CACHE_AS_VBOS
830 glGenBuffers(1, &cache->vbo);
831 glGenBuffers(1, &cache->ibo);
832 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
833 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cache->ibo);
835 if (polys.indices.type() == QVertexIndexVector::UnsignedInt)
836 funcs.glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint32) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
838 funcs.glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint16) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
840 QVarLengthArray<float> vertices(polys.vertices.size());
841 for (int i = 0; i < polys.vertices.size(); ++i)
842 vertices[i] = float(inverseScale * polys.vertices.at(i));
843 funcs.glBufferData(GL_ARRAY_BUFFER, sizeof(float) * vertices.size(), vertices.data(), GL_STATIC_DRAW);
845 cache->vertices = (float *) qMalloc(sizeof(float) * polys.vertices.size());
846 if (polys.indices.type() == QVertexIndexVector::UnsignedInt) {
847 cache->indices = (quint32 *) qMalloc(sizeof(quint32) * polys.indices.size());
848 memcpy(cache->indices, polys.indices.data(), sizeof(quint32) * polys.indices.size());
850 cache->indices = (quint16 *) qMalloc(sizeof(quint16) * polys.indices.size());
851 memcpy(cache->indices, polys.indices.data(), sizeof(quint16) * polys.indices.size());
853 for (int i = 0; i < polys.vertices.size(); ++i)
854 cache->vertices[i] = float(inverseScale * polys.vertices.at(i));
858 prepareForDraw(currentBrush.isOpaque());
859 #ifdef QT_OPENGL_CACHE_AS_VBOS
860 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
861 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cache->ibo);
862 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, 0);
863 if (cache->indexType == QVertexIndexVector::UnsignedInt)
864 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_INT, 0);
866 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_SHORT, 0);
867 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
868 glBindBuffer(GL_ARRAY_BUFFER, 0);
870 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, cache->vertices);
871 if (cache->indexType == QVertexIndexVector::UnsignedInt)
872 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_INT, (qint32 *)cache->indices);
874 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_SHORT, (qint16 *)cache->indices);
878 // printf(" - Marking path as cachable...\n");
879 // Tag it for later so that if the same path is drawn twice, it is assumed to be static and thus cachable
880 path.makeCacheable();
882 if (device->context()->format().stencilBufferSize() == 0) {
883 // If there is no stencil buffer, triangulate the path instead.
885 QRectF bbox = path.controlPointRect();
886 // If the path doesn't fit within these limits, it is possible that the triangulation will fail.
887 bool withinLimits = (bbox.left() > -0x8000 * inverseScale)
888 && (bbox.right() < 0x8000 * inverseScale)
889 && (bbox.top() > -0x8000 * inverseScale)
890 && (bbox.bottom() < 0x8000 * inverseScale);
892 QTriangleSet polys = qTriangulate(path, QTransform().scale(1 / inverseScale, 1 / inverseScale));
894 QVarLengthArray<float> vertices(polys.vertices.size());
895 for (int i = 0; i < polys.vertices.size(); ++i)
896 vertices[i] = float(inverseScale * polys.vertices.at(i));
898 prepareForDraw(currentBrush.isOpaque());
899 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, vertices.constData());
900 if (funcs.hasOpenGLExtension(QOpenGLExtensions::ElementIndexUint))
901 glDrawElements(GL_TRIANGLES, polys.indices.size(), GL_UNSIGNED_INT, polys.indices.data());
903 glDrawElements(GL_TRIANGLES, polys.indices.size(), GL_UNSIGNED_SHORT, polys.indices.data());
905 // We can't handle big, concave painter paths with OpenGL without stencil buffer.
906 qWarning("Painter path exceeds +/-32767 pixels.");
911 // The path is too complicated & needs the stencil technique
912 vertexCoordinateArray.clear();
913 vertexCoordinateArray.addPath(path, inverseScale, false);
915 fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill());
918 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
920 if (q->state()->clipTestEnabled) {
921 // Pass when high bit is set, replace stencil value with current clip
922 glStencilFunc(GL_NOTEQUAL, q->state()->currentClip, GL_STENCIL_HIGH_BIT);
923 } else if (path.hasWindingFill()) {
924 // Pass when any bit is set, replace stencil value with 0
925 glStencilFunc(GL_NOTEQUAL, 0, 0xff);
927 // Pass when high bit is set, replace stencil value with 0
928 glStencilFunc(GL_NOTEQUAL, 0, GL_STENCIL_HIGH_BIT);
930 prepareForDraw(currentBrush.isOpaque());
932 // Stencil the brush onto the dest buffer
933 composite(vertexCoordinateArray.boundingRect());
935 updateClipScissorTest();
941 void QOpenGL2PaintEngineExPrivate::fillStencilWithVertexArray(const float *data,
945 const QOpenGLRect &bounds,
946 StencilFillMode mode)
948 Q_ASSERT(count || stops);
950 // qDebug("QOpenGL2PaintEngineExPrivate::fillStencilWithVertexArray()");
951 glStencilMask(0xff); // Enable stencil writes
953 if (dirtyStencilRegion.intersects(currentScissorBounds)) {
954 QVector<QRect> clearRegion = dirtyStencilRegion.intersected(currentScissorBounds).rects();
955 glClearStencil(0); // Clear to zero
956 for (int i = 0; i < clearRegion.size(); ++i) {
957 #ifndef QT_GL_NO_SCISSOR_TEST
958 setScissor(clearRegion.at(i));
960 glClear(GL_STENCIL_BUFFER_BIT);
963 dirtyStencilRegion -= currentScissorBounds;
965 #ifndef QT_GL_NO_SCISSOR_TEST
966 updateClipScissorTest();
970 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); // Disable color writes
972 glEnable(GL_STENCIL_TEST); // For some reason, this has to happen _after_ the simple shader is use()'d
974 if (mode == WindingFillMode) {
975 Q_ASSERT(stops && !count);
976 if (q->state()->clipTestEnabled) {
977 // Flatten clip values higher than current clip, and set high bit to match current clip
978 glStencilFunc(GL_LEQUAL, GL_STENCIL_HIGH_BIT | q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
979 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
982 glStencilFunc(GL_EQUAL, GL_STENCIL_HIGH_BIT, GL_STENCIL_HIGH_BIT);
983 } else if (!stencilClean) {
984 // Clear stencil buffer within bounding rect
985 glStencilFunc(GL_ALWAYS, 0, 0xff);
986 glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO);
990 // Inc. for front-facing triangle
991 funcs.glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_INCR_WRAP, GL_INCR_WRAP);
992 // Dec. for back-facing "holes"
993 funcs.glStencilOpSeparate(GL_BACK, GL_KEEP, GL_DECR_WRAP, GL_DECR_WRAP);
994 glStencilMask(~GL_STENCIL_HIGH_BIT);
995 drawVertexArrays(data, stops, stopCount, GL_TRIANGLE_FAN);
997 if (q->state()->clipTestEnabled) {
998 // Clear high bit of stencil outside of path
999 glStencilFunc(GL_EQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
1000 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
1001 glStencilMask(GL_STENCIL_HIGH_BIT);
1004 } else if (mode == OddEvenFillMode) {
1005 glStencilMask(GL_STENCIL_HIGH_BIT);
1006 glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT); // Simply invert the stencil bit
1007 drawVertexArrays(data, stops, stopCount, GL_TRIANGLE_FAN);
1009 } else { // TriStripStrokeFillMode
1010 Q_ASSERT(count && !stops); // tristrips generated directly, so no vertexArray or stops
1011 glStencilMask(GL_STENCIL_HIGH_BIT);
1013 glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT); // Simply invert the stencil bit
1014 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, data);
1015 glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
1018 glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
1019 if (q->state()->clipTestEnabled) {
1020 glStencilFunc(GL_LEQUAL, q->state()->currentClip | GL_STENCIL_HIGH_BIT,
1021 ~GL_STENCIL_HIGH_BIT);
1023 glStencilFunc(GL_ALWAYS, GL_STENCIL_HIGH_BIT, 0xff);
1025 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, data);
1026 glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
1030 // Enable color writes & disable stencil writes
1031 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1035 If the maximum value in the stencil buffer is GL_STENCIL_HIGH_BIT - 1,
1036 restore the stencil buffer to a pristine state. The current clip region
1037 is set to 1, and the rest to 0.
1039 void QOpenGL2PaintEngineExPrivate::resetClipIfNeeded()
1041 if (maxClip != (GL_STENCIL_HIGH_BIT - 1))
1044 Q_Q(QOpenGL2PaintEngineEx);
1047 glEnable(GL_STENCIL_TEST);
1048 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1050 QRectF bounds = q->state()->matrix.inverted().mapRect(QRectF(0, 0, width, height));
1051 QOpenGLRect rect(bounds.left(), bounds.top(), bounds.right(), bounds.bottom());
1053 // Set high bit on clip region
1054 glStencilFunc(GL_LEQUAL, q->state()->currentClip, 0xff);
1055 glStencilOp(GL_KEEP, GL_INVERT, GL_INVERT);
1056 glStencilMask(GL_STENCIL_HIGH_BIT);
1059 // Reset clipping to 1 and everything else to zero
1060 glStencilFunc(GL_NOTEQUAL, 0x01, GL_STENCIL_HIGH_BIT);
1061 glStencilOp(GL_ZERO, GL_REPLACE, GL_REPLACE);
1062 glStencilMask(0xff);
1065 q->state()->currentClip = 1;
1066 q->state()->canRestoreClip = false;
1071 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1074 bool QOpenGL2PaintEngineExPrivate::prepareForDraw(bool srcPixelsAreOpaque)
1076 if (brushTextureDirty && mode != ImageDrawingMode && mode != ImageArrayDrawingMode)
1077 updateBrushTexture();
1079 if (compositionModeDirty)
1080 updateCompositionMode();
1085 const bool stateHasOpacity = q->state()->opacity < 0.99f;
1086 if (q->state()->composition_mode == QPainter::CompositionMode_Source
1087 || (q->state()->composition_mode == QPainter::CompositionMode_SourceOver
1088 && srcPixelsAreOpaque && !stateHasOpacity))
1090 glDisable(GL_BLEND);
1095 QOpenGLEngineShaderManager::OpacityMode opacityMode;
1096 if (mode == ImageArrayDrawingMode) {
1097 opacityMode = QOpenGLEngineShaderManager::AttributeOpacity;
1099 opacityMode = stateHasOpacity ? QOpenGLEngineShaderManager::UniformOpacity
1100 : QOpenGLEngineShaderManager::NoOpacity;
1101 if (stateHasOpacity && (mode != ImageDrawingMode)) {
1103 bool brushIsPattern = (currentBrush.style() >= Qt::Dense1Pattern) &&
1104 (currentBrush.style() <= Qt::DiagCrossPattern);
1106 if ((currentBrush.style() == Qt::SolidPattern) || brushIsPattern)
1107 opacityMode = QOpenGLEngineShaderManager::NoOpacity; // Global opacity handled by srcPixel shader
1110 shaderManager->setOpacityMode(opacityMode);
1112 bool changed = shaderManager->useCorrectShaderProg();
1113 // If the shader program needs changing, we change it and mark all uniforms as dirty
1115 // The shader program has changed so mark all uniforms as dirty:
1116 brushUniformsDirty = true;
1117 opacityUniformDirty = true;
1118 matrixUniformDirty = true;
1121 if (brushUniformsDirty && mode != ImageDrawingMode && mode != ImageArrayDrawingMode)
1122 updateBrushUniforms();
1124 if (opacityMode == QOpenGLEngineShaderManager::UniformOpacity && opacityUniformDirty) {
1125 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::GlobalOpacity), (GLfloat)q->state()->opacity);
1126 opacityUniformDirty = false;
1129 if (matrixUniformDirty && shaderManager->hasComplexGeometry()) {
1130 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Matrix),
1132 matrixUniformDirty = false;
1138 void QOpenGL2PaintEngineExPrivate::composite(const QOpenGLRect& boundingRect)
1140 setCoords(staticVertexCoordinateArray, boundingRect);
1141 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, staticVertexCoordinateArray);
1142 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1145 // Draws the vertex array as a set of <vertexArrayStops.size()> triangle fans.
1146 void QOpenGL2PaintEngineExPrivate::drawVertexArrays(const float *data, int *stops, int stopCount,
1149 // Now setup the pointer to the vertex array:
1150 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)data);
1152 int previousStop = 0;
1153 for (int i=0; i<stopCount; ++i) {
1154 int stop = stops[i];
1156 qDebug("Drawing triangle fan for vertecies %d -> %d:", previousStop, stop-1);
1157 for (int i=previousStop; i<stop; ++i)
1158 qDebug(" %02d: [%.2f, %.2f]", i, vertexArray.data()[i].x, vertexArray.data()[i].y);
1160 glDrawArrays(primitive, previousStop, stop - previousStop);
1161 previousStop = stop;
1165 /////////////////////////////////// Public Methods //////////////////////////////////////////
1167 QOpenGL2PaintEngineEx::QOpenGL2PaintEngineEx()
1168 : QPaintEngineEx(*(new QOpenGL2PaintEngineExPrivate(this)))
1172 QOpenGL2PaintEngineEx::~QOpenGL2PaintEngineEx()
1176 void QOpenGL2PaintEngineEx::fill(const QVectorPath &path, const QBrush &brush)
1178 Q_D(QOpenGL2PaintEngineEx);
1180 if (qbrush_style(brush) == Qt::NoBrush)
1187 Q_GUI_EXPORT bool qt_scaleForTransform(const QTransform &transform, qreal *scale); // qtransform.cpp
1190 void QOpenGL2PaintEngineEx::stroke(const QVectorPath &path, const QPen &pen)
1192 Q_D(QOpenGL2PaintEngineEx);
1194 const QBrush &penBrush = qpen_brush(pen);
1195 if (qpen_style(pen) == Qt::NoPen || qbrush_style(penBrush) == Qt::NoBrush)
1198 QOpenGL2PaintEngineState *s = state();
1199 if (pen.isCosmetic() && !qt_scaleForTransform(s->transform(), 0)) {
1200 // QTriangulatingStroker class is not meant to support cosmetically sheared strokes.
1201 QPaintEngineEx::stroke(path, pen);
1206 d->setBrush(penBrush);
1207 d->stroke(path, pen);
1210 void QOpenGL2PaintEngineExPrivate::stroke(const QVectorPath &path, const QPen &pen)
1212 const QOpenGL2PaintEngineState *s = q->state();
1213 if (snapToPixelGrid) {
1214 snapToPixelGrid = false;
1218 const Qt::PenStyle penStyle = qpen_style(pen);
1219 const QBrush &penBrush = qpen_brush(pen);
1220 const bool opaque = penBrush.isOpaque() && s->opacity > 0.99;
1222 transferMode(BrushDrawingMode);
1224 // updateMatrix() is responsible for setting the inverse scale on
1225 // the strokers, so we need to call it here and not wait for
1226 // prepareForDraw() down below.
1229 QRectF clip = q->state()->matrix.inverted().mapRect(q->state()->clipEnabled
1230 ? q->state()->rectangleClip
1231 : QRectF(0, 0, width, height));
1233 if (penStyle == Qt::SolidLine) {
1234 stroker.process(path, pen, clip);
1236 } else { // Some sort of dash
1237 dasher.process(path, pen, clip);
1239 QVectorPath dashStroke(dasher.points(),
1240 dasher.elementCount(),
1241 dasher.elementTypes());
1242 stroker.process(dashStroke, pen, clip);
1245 if (!stroker.vertexCount())
1249 prepareForDraw(opaque);
1250 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, stroker.vertices());
1251 glDrawArrays(GL_TRIANGLE_STRIP, 0, stroker.vertexCount() / 2);
1253 // QBrush b(Qt::green);
1255 // d->prepareForDraw(true);
1256 // glDrawArrays(GL_LINE_STRIP, 0, d->stroker.vertexCount() / 2);
1259 qreal width = qpen_widthf(pen) / 2;
1262 qreal extra = pen.joinStyle() == Qt::MiterJoin
1263 ? qMax(pen.miterLimit() * width, width)
1266 if (pen.isCosmetic())
1267 extra = extra * inverseScale;
1269 QRectF bounds = path.controlPointRect().adjusted(-extra, -extra, extra, extra);
1271 fillStencilWithVertexArray(stroker.vertices(), stroker.vertexCount() / 2,
1272 0, 0, bounds, QOpenGL2PaintEngineExPrivate::TriStripStrokeFillMode);
1274 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
1276 // Pass when any bit is set, replace stencil value with 0
1277 glStencilFunc(GL_NOTEQUAL, 0, GL_STENCIL_HIGH_BIT);
1278 prepareForDraw(false);
1280 // Stencil the brush onto the dest buffer
1285 updateClipScissorTest();
1289 void QOpenGL2PaintEngineEx::penChanged() { }
1290 void QOpenGL2PaintEngineEx::brushChanged() { }
1291 void QOpenGL2PaintEngineEx::brushOriginChanged() { }
1293 void QOpenGL2PaintEngineEx::opacityChanged()
1295 // qDebug("QOpenGL2PaintEngineEx::opacityChanged()");
1296 Q_D(QOpenGL2PaintEngineEx);
1297 state()->opacityChanged = true;
1299 Q_ASSERT(d->shaderManager);
1300 d->brushUniformsDirty = true;
1301 d->opacityUniformDirty = true;
1304 void QOpenGL2PaintEngineEx::compositionModeChanged()
1306 // qDebug("QOpenGL2PaintEngineEx::compositionModeChanged()");
1307 Q_D(QOpenGL2PaintEngineEx);
1308 state()->compositionModeChanged = true;
1309 d->compositionModeDirty = true;
1312 void QOpenGL2PaintEngineEx::renderHintsChanged()
1314 state()->renderHintsChanged = true;
1316 #if !defined(QT_OPENGL_ES_2)
1317 if ((state()->renderHints & QPainter::Antialiasing)
1318 || (state()->renderHints & QPainter::HighQualityAntialiasing))
1319 glEnable(GL_MULTISAMPLE);
1321 glDisable(GL_MULTISAMPLE);
1324 Q_D(QOpenGL2PaintEngineEx);
1325 d->lastTextureUsed = GLuint(-1);
1326 d->brushTextureDirty = true;
1327 // qDebug("QOpenGL2PaintEngineEx::renderHintsChanged() not implemented!");
1330 void QOpenGL2PaintEngineEx::transformChanged()
1332 Q_D(QOpenGL2PaintEngineEx);
1333 d->matrixDirty = true;
1334 state()->matrixChanged = true;
1338 static const QRectF scaleRect(const QRectF &r, qreal sx, qreal sy)
1340 return QRectF(r.x() * sx, r.y() * sy, r.width() * sx, r.height() * sy);
1343 void QOpenGL2PaintEngineEx::drawPixmap(const QRectF& dest, const QPixmap & pixmap, const QRectF & src)
1345 Q_D(QOpenGL2PaintEngineEx);
1346 QOpenGLContext *ctx = d->ctx;
1348 int max_texture_size = ctx->d_func()->maxTextureSize();
1349 if (pixmap.width() > max_texture_size || pixmap.height() > max_texture_size) {
1350 QPixmap scaled = pixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1352 const qreal sx = scaled.width() / qreal(pixmap.width());
1353 const qreal sy = scaled.height() / qreal(pixmap.height());
1355 drawPixmap(dest, scaled, scaleRect(src, sx, sy));
1360 d->transferMode(ImageDrawingMode);
1362 d->funcs.glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1363 QOpenGLTexture *texture = 0;
1364 // ctx->d_func()->bindTexture(pixmap, GL_TEXTURE_2D, GL_RGBA, bindOptions);
1366 GLfloat top = texture->invertedY() ? (pixmap.height() - src.top()) : src.top();
1367 GLfloat bottom = texture->invertedY() ? (pixmap.height() - src.bottom()) : src.bottom();
1368 QOpenGLRect srcRect(src.left(), top, src.right(), bottom);
1370 bool isBitmap = pixmap.isQBitmap();
1371 bool isOpaque = !isBitmap && !pixmap.hasAlpha();
1373 d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1374 state()->renderHints & QPainter::SmoothPixmapTransform, texture->id());
1375 d->drawTexture(dest, srcRect, pixmap.size(), isOpaque, isBitmap);
1378 void QOpenGL2PaintEngineEx::drawImage(const QRectF& dest, const QImage& image, const QRectF& src,
1379 Qt::ImageConversionFlags)
1381 Q_D(QOpenGL2PaintEngineEx);
1382 QOpenGLContext *ctx = d->ctx;
1384 int max_texture_size = ctx->d_func()->maxTextureSize();
1385 if (image.width() > max_texture_size || image.height() > max_texture_size) {
1386 QImage scaled = image.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1388 const qreal sx = scaled.width() / qreal(image.width());
1389 const qreal sy = scaled.height() / qreal(image.height());
1391 drawImage(dest, scaled, scaleRect(src, sx, sy));
1396 d->transferMode(ImageDrawingMode);
1398 d->funcs.glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1400 QOpenGLTexture *texture = 0;//ctx->d_func()->bindTexture(image, GL_TEXTURE_2D, GL_RGBA, bindOptions);
1401 GLuint id = texture->id();
1403 d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1404 state()->renderHints & QPainter::SmoothPixmapTransform, id);
1405 d->drawTexture(dest, src, image.size(), !image.hasAlphaChannel());
1408 void QOpenGL2PaintEngineEx::drawStaticTextItem(QStaticTextItem *textItem)
1410 Q_D(QOpenGL2PaintEngineEx);
1414 QPainterState *s = state();
1415 float det = s->matrix.determinant();
1417 // don't try to cache huge fonts or vastly transformed fonts
1418 QFontEngine *fontEngine = textItem->fontEngine();
1419 const qreal pixelSize = fontEngine->fontDef.pixelSize;
1420 if (shouldDrawCachedGlyphs(pixelSize, s->matrix) || det < 0.25f || det > 4.f) {
1421 QFontEngineGlyphCache::Type glyphType = fontEngine->glyphFormat >= 0
1422 ? QFontEngineGlyphCache::Type(textItem->fontEngine()->glyphFormat)
1423 : d->glyphCacheType;
1424 if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1425 if (d->device->context()->format().alphaBufferSize() > 0 || s->matrix.type() > QTransform::TxTranslate
1426 || (s->composition_mode != QPainter::CompositionMode_Source
1427 && s->composition_mode != QPainter::CompositionMode_SourceOver))
1429 glyphType = QFontEngineGlyphCache::Raster_A8;
1433 d->drawCachedGlyphs(glyphType, textItem);
1435 QPaintEngineEx::drawStaticTextItem(textItem);
1439 bool QOpenGL2PaintEngineEx::drawTexture(const QRectF &dest, GLuint textureId, const QSize &size, const QRectF &src)
1441 Q_D(QOpenGL2PaintEngineEx);
1442 if (!d->shaderManager)
1446 d->transferMode(ImageDrawingMode);
1448 d->funcs.glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1449 glBindTexture(GL_TEXTURE_2D, textureId);
1451 QOpenGLRect srcRect(src.left(), src.bottom(), src.right(), src.top());
1453 d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1454 state()->renderHints & QPainter::SmoothPixmapTransform, textureId);
1455 d->drawTexture(dest, srcRect, size, false);
1459 void QOpenGL2PaintEngineEx::drawTextItem(const QPointF &p, const QTextItem &textItem)
1461 Q_D(QOpenGL2PaintEngineEx);
1464 QOpenGL2PaintEngineState *s = state();
1466 const QTextItemInt &ti = static_cast<const QTextItemInt &>(textItem);
1468 QTransform::TransformationType txtype = s->matrix.type();
1470 float det = s->matrix.determinant();
1471 bool drawCached = txtype < QTransform::TxProject;
1473 // don't try to cache huge fonts or vastly transformed fonts
1474 const qreal pixelSize = ti.fontEngine->fontDef.pixelSize;
1475 if (shouldDrawCachedGlyphs(pixelSize, s->matrix) || det < 0.25f || det > 4.f)
1478 QFontEngineGlyphCache::Type glyphType = ti.fontEngine->glyphFormat >= 0
1479 ? QFontEngineGlyphCache::Type(ti.fontEngine->glyphFormat)
1480 : d->glyphCacheType;
1483 if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1484 if (d->device->context()->format().alphaBufferSize() > 0 || txtype > QTransform::TxTranslate
1485 || (state()->composition_mode != QPainter::CompositionMode_Source
1486 && state()->composition_mode != QPainter::CompositionMode_SourceOver))
1488 glyphType = QFontEngineGlyphCache::Raster_A8;
1493 QVarLengthArray<QFixedPoint> positions;
1494 QVarLengthArray<glyph_t> glyphs;
1495 QTransform matrix = QTransform::fromTranslate(p.x(), p.y());
1496 ti.fontEngine->getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions);
1499 QStaticTextItem staticTextItem;
1500 staticTextItem.chars = const_cast<QChar *>(ti.chars);
1501 staticTextItem.setFontEngine(ti.fontEngine);
1502 staticTextItem.glyphs = glyphs.data();
1503 staticTextItem.numChars = ti.num_chars;
1504 staticTextItem.numGlyphs = glyphs.size();
1505 staticTextItem.glyphPositions = positions.data();
1507 d->drawCachedGlyphs(glyphType, &staticTextItem);
1512 QPaintEngineEx::drawTextItem(p, ti);
1517 class QOpenGLStaticTextUserData: public QStaticTextUserData
1520 QOpenGLStaticTextUserData()
1521 : QStaticTextUserData(OpenGLUserData), cacheSize(0, 0), cacheSerialNumber(0)
1525 ~QOpenGLStaticTextUserData()
1530 QOpenGL2PEXVertexArray vertexCoordinateArray;
1531 QOpenGL2PEXVertexArray textureCoordinateArray;
1532 QFontEngineGlyphCache::Type glyphType;
1533 int cacheSerialNumber;
1538 #if defined(Q_WS_WIN)
1539 static bool fontSmoothingApproximately(qreal target)
1541 extern Q_GUI_EXPORT qreal qt_fontsmoothing_gamma; // qapplication_win.cpp
1542 return (qAbs(qt_fontsmoothing_gamma - target) < 0.2);
1546 // #define QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO
1548 void QOpenGL2PaintEngineExPrivate::drawCachedGlyphs(QFontEngineGlyphCache::Type glyphType,
1549 QStaticTextItem *staticTextItem)
1551 Q_Q(QOpenGL2PaintEngineEx);
1553 QOpenGL2PaintEngineState *s = q->state();
1555 void *cacheKey = ctx->shareGroup();
1556 bool recreateVertexArrays = false;
1558 QOpenGLTextureGlyphCache *cache =
1559 (QOpenGLTextureGlyphCache *) staticTextItem->fontEngine()->glyphCache(cacheKey, glyphType, QTransform());
1560 if (!cache || cache->cacheType() != glyphType || cache->contextGroup() == 0) {
1561 cache = new QOpenGLTextureGlyphCache(glyphType, QTransform());
1562 staticTextItem->fontEngine()->setGlyphCache(cacheKey, cache);
1563 recreateVertexArrays = true;
1566 if (staticTextItem->userDataNeedsUpdate) {
1567 recreateVertexArrays = true;
1568 } else if (staticTextItem->userData() == 0) {
1569 recreateVertexArrays = true;
1570 } else if (staticTextItem->userData()->type != QStaticTextUserData::OpenGLUserData) {
1571 recreateVertexArrays = true;
1573 QOpenGLStaticTextUserData *userData = static_cast<QOpenGLStaticTextUserData *>(staticTextItem->userData());
1574 if (userData->glyphType != glyphType) {
1575 recreateVertexArrays = true;
1576 } else if (userData->cacheSerialNumber != cache->serialNumber()) {
1577 recreateVertexArrays = true;
1581 // We only need to update the cache with new glyphs if we are actually going to recreate the vertex arrays.
1582 // If the cache size has changed, we do need to regenerate the vertices, but we don't need to repopulate the
1583 // cache so this text is performed before we test if the cache size has changed.
1584 if (recreateVertexArrays) {
1585 cache->setPaintEnginePrivate(this);
1586 if (!cache->populate(staticTextItem->fontEngine(), staticTextItem->numGlyphs,
1587 staticTextItem->glyphs, staticTextItem->glyphPositions)) {
1588 // No space for glyphs in cache. We need to reset it and try again.
1590 cache->populate(staticTextItem->fontEngine(), staticTextItem->numGlyphs,
1591 staticTextItem->glyphs, staticTextItem->glyphPositions);
1593 cache->fillInPendingGlyphs();
1596 if (cache->width() == 0 || cache->height() == 0)
1599 transferMode(TextDrawingMode);
1601 int margin = cache->glyphMargin();
1603 GLfloat dx = 1.0 / cache->width();
1604 GLfloat dy = 1.0 / cache->height();
1606 // Use global arrays by default
1607 QOpenGL2PEXVertexArray *vertexCoordinates = &vertexCoordinateArray;
1608 QOpenGL2PEXVertexArray *textureCoordinates = &textureCoordinateArray;
1610 if (staticTextItem->useBackendOptimizations) {
1611 QOpenGLStaticTextUserData *userData = 0;
1613 if (staticTextItem->userData() == 0
1614 || staticTextItem->userData()->type != QStaticTextUserData::OpenGLUserData) {
1616 userData = new QOpenGLStaticTextUserData();
1617 staticTextItem->setUserData(userData);
1620 userData = static_cast<QOpenGLStaticTextUserData*>(staticTextItem->userData());
1623 userData->glyphType = glyphType;
1624 userData->cacheSerialNumber = cache->serialNumber();
1626 // Use cache if backend optimizations is turned on
1627 vertexCoordinates = &userData->vertexCoordinateArray;
1628 textureCoordinates = &userData->textureCoordinateArray;
1630 QSize size(cache->width(), cache->height());
1631 if (userData->cacheSize != size) {
1632 recreateVertexArrays = true;
1633 userData->cacheSize = size;
1637 if (recreateVertexArrays) {
1638 vertexCoordinates->clear();
1639 textureCoordinates->clear();
1641 bool supportsSubPixelPositions = staticTextItem->fontEngine()->supportsSubPixelPositions();
1642 for (int i=0; i<staticTextItem->numGlyphs; ++i) {
1643 QFixed subPixelPosition;
1644 if (supportsSubPixelPositions)
1645 subPixelPosition = cache->subPixelPositionForX(staticTextItem->glyphPositions[i].x);
1647 QTextureGlyphCache::GlyphAndSubPixelPosition glyph(staticTextItem->glyphs[i], subPixelPosition);
1649 const QTextureGlyphCache::Coord &c = cache->coords[glyph];
1653 int x = qFloor(staticTextItem->glyphPositions[i].x) + c.baseLineX - margin;
1654 int y = qFloor(staticTextItem->glyphPositions[i].y) - c.baseLineY - margin;
1656 vertexCoordinates->addQuad(QRectF(x, y, c.w, c.h));
1657 textureCoordinates->addQuad(QRectF(c.x*dx, c.y*dy, c.w * dx, c.h * dy));
1660 staticTextItem->userDataNeedsUpdate = false;
1663 int numGlyphs = vertexCoordinates->vertexCount() / 4;
1667 if (elementIndices.size() < numGlyphs*6) {
1668 Q_ASSERT(elementIndices.size() % 6 == 0);
1669 int j = elementIndices.size() / 6 * 4;
1670 while (j < numGlyphs*4) {
1671 elementIndices.append(j + 0);
1672 elementIndices.append(j + 0);
1673 elementIndices.append(j + 1);
1674 elementIndices.append(j + 2);
1675 elementIndices.append(j + 3);
1676 elementIndices.append(j + 3);
1681 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1682 if (elementIndicesVBOId == 0)
1683 glGenBuffers(1, &elementIndicesVBOId);
1685 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
1686 glBufferData(GL_ELEMENT_ARRAY_BUFFER, elementIndices.size() * sizeof(GLushort),
1687 elementIndices.constData(), GL_STATIC_DRAW);
1690 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1691 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
1695 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)vertexCoordinates->data());
1696 setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, (GLfloat*)textureCoordinates->data());
1698 if (!snapToPixelGrid) {
1699 snapToPixelGrid = true;
1703 QBrush pensBrush = q->state()->pen.brush();
1704 setBrush(pensBrush);
1706 if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1708 // Subpixel antialiasing without gamma correction
1710 QPainter::CompositionMode compMode = q->state()->composition_mode;
1711 Q_ASSERT(compMode == QPainter::CompositionMode_Source
1712 || compMode == QPainter::CompositionMode_SourceOver);
1714 shaderManager->setMaskType(QOpenGLEngineShaderManager::SubPixelMaskPass1);
1716 if (pensBrush.style() == Qt::SolidPattern) {
1717 // Solid patterns can get away with only one pass.
1718 QColor c = pensBrush.color();
1719 qreal oldOpacity = q->state()->opacity;
1720 if (compMode == QPainter::CompositionMode_Source) {
1721 c = qt_premultiplyColor(c, q->state()->opacity);
1722 q->state()->opacity = 1;
1723 opacityUniformDirty = true;
1726 compositionModeDirty = false; // I can handle this myself, thank you very much
1727 prepareForDraw(false); // Text always causes src pixels to be transparent
1729 // prepareForDraw() have set the opacity on the current shader, so the opacity state can now be reset.
1730 if (compMode == QPainter::CompositionMode_Source) {
1731 q->state()->opacity = oldOpacity;
1732 opacityUniformDirty = true;
1736 glBlendFunc(GL_CONSTANT_COLOR, GL_ONE_MINUS_SRC_COLOR);
1737 funcs.glBlendColor(c.redF(), c.greenF(), c.blueF(), c.alphaF());
1739 // Other brush styles need two passes.
1741 qreal oldOpacity = q->state()->opacity;
1742 if (compMode == QPainter::CompositionMode_Source) {
1743 q->state()->opacity = 1;
1744 opacityUniformDirty = true;
1745 pensBrush = Qt::white;
1746 setBrush(pensBrush);
1749 compositionModeDirty = false; // I can handle this myself, thank you very much
1750 prepareForDraw(false); // Text always causes src pixels to be transparent
1752 glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR);
1754 funcs.glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
1755 glBindTexture(GL_TEXTURE_2D, cache->texture());
1756 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, false);
1758 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1759 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
1761 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, elementIndices.data());
1764 shaderManager->setMaskType(QOpenGLEngineShaderManager::SubPixelMaskPass2);
1766 if (compMode == QPainter::CompositionMode_Source) {
1767 q->state()->opacity = oldOpacity;
1768 opacityUniformDirty = true;
1769 pensBrush = q->state()->pen.brush();
1770 setBrush(pensBrush);
1773 compositionModeDirty = false;
1774 prepareForDraw(false); // Text always causes src pixels to be transparent
1776 glBlendFunc(GL_ONE, GL_ONE);
1778 compositionModeDirty = true;
1780 // Greyscale/mono glyphs
1782 shaderManager->setMaskType(QOpenGLEngineShaderManager::PixelMask);
1783 prepareForDraw(false); // Text always causes src pixels to be transparent
1786 QOpenGLTextureGlyphCache::FilterMode filterMode = (s->matrix.type() > QTransform::TxTranslate)?QOpenGLTextureGlyphCache::Linear:QOpenGLTextureGlyphCache::Nearest;
1787 if (lastMaskTextureUsed != cache->texture() || cache->filterMode() != filterMode) {
1789 funcs.glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
1790 if (lastMaskTextureUsed != cache->texture()) {
1791 glBindTexture(GL_TEXTURE_2D, cache->texture());
1792 lastMaskTextureUsed = cache->texture();
1795 if (cache->filterMode() != filterMode) {
1796 if (filterMode == QOpenGLTextureGlyphCache::Linear) {
1797 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1798 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1800 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1801 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1803 cache->setFilterMode(filterMode);
1807 bool srgbFrameBufferEnabled = false;
1808 if (funcs.hasOpenGLExtension(QOpenGLExtensions::SRGBFrameBuffer)) {
1809 #if defined(Q_WS_MAC)
1810 if (glyphType == QFontEngineGlyphCache::Raster_RGBMask)
1811 #elif defined(Q_WS_WIN)
1812 if (glyphType != QFontEngineGlyphCache::Raster_RGBMask || fontSmoothingApproximately(2.1))
1817 glEnable(GL_FRAMEBUFFER_SRGB);
1818 srgbFrameBufferEnabled = true;
1822 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1823 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
1824 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1826 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, elementIndices.data());
1829 if (srgbFrameBufferEnabled)
1830 glDisable(GL_FRAMEBUFFER_SRGB);
1834 void QOpenGL2PaintEngineEx::drawPixmapFragments(const QPainter::PixmapFragment *fragments, int fragmentCount, const QPixmap &pixmap,
1835 QPainter::PixmapFragmentHints hints)
1837 Q_D(QOpenGL2PaintEngineEx);
1838 // Use fallback for extended composition modes.
1839 if (state()->composition_mode > QPainter::CompositionMode_Plus) {
1840 QPaintEngineEx::drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
1845 int max_texture_size = d->ctx->d_func()->maxTextureSize();
1846 if (pixmap.width() > max_texture_size || pixmap.height() > max_texture_size) {
1847 QPixmap scaled = pixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1848 d->drawPixmapFragments(fragments, fragmentCount, scaled, hints);
1850 d->drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
1855 void QOpenGL2PaintEngineExPrivate::drawPixmapFragments(const QPainter::PixmapFragment *fragments,
1856 int fragmentCount, const QPixmap &pixmap,
1857 QPainter::PixmapFragmentHints hints)
1859 GLfloat dx = 1.0f / pixmap.size().width();
1860 GLfloat dy = 1.0f / pixmap.size().height();
1862 vertexCoordinateArray.clear();
1863 textureCoordinateArray.clear();
1864 opacityArray.reset();
1866 if (snapToPixelGrid) {
1867 snapToPixelGrid = false;
1871 bool allOpaque = true;
1873 for (int i = 0; i < fragmentCount; ++i) {
1876 if (fragments[i].rotation != 0) {
1877 s = qFastSin(fragments[i].rotation * Q_PI / 180);
1878 c = qFastCos(fragments[i].rotation * Q_PI / 180);
1881 qreal right = 0.5 * fragments[i].scaleX * fragments[i].width;
1882 qreal bottom = 0.5 * fragments[i].scaleY * fragments[i].height;
1883 QOpenGLPoint bottomRight(right * c - bottom * s, right * s + bottom * c);
1884 QOpenGLPoint bottomLeft(-right * c - bottom * s, -right * s + bottom * c);
1886 vertexCoordinateArray.addVertex(bottomRight.x + fragments[i].x, bottomRight.y + fragments[i].y);
1887 vertexCoordinateArray.addVertex(-bottomLeft.x + fragments[i].x, -bottomLeft.y + fragments[i].y);
1888 vertexCoordinateArray.addVertex(-bottomRight.x + fragments[i].x, -bottomRight.y + fragments[i].y);
1889 vertexCoordinateArray.addVertex(-bottomRight.x + fragments[i].x, -bottomRight.y + fragments[i].y);
1890 vertexCoordinateArray.addVertex(bottomLeft.x + fragments[i].x, bottomLeft.y + fragments[i].y);
1891 vertexCoordinateArray.addVertex(bottomRight.x + fragments[i].x, bottomRight.y + fragments[i].y);
1893 QOpenGLRect src(fragments[i].sourceLeft * dx, fragments[i].sourceTop * dy,
1894 (fragments[i].sourceLeft + fragments[i].width) * dx,
1895 (fragments[i].sourceTop + fragments[i].height) * dy);
1897 textureCoordinateArray.addVertex(src.right, src.bottom);
1898 textureCoordinateArray.addVertex(src.right, src.top);
1899 textureCoordinateArray.addVertex(src.left, src.top);
1900 textureCoordinateArray.addVertex(src.left, src.top);
1901 textureCoordinateArray.addVertex(src.left, src.bottom);
1902 textureCoordinateArray.addVertex(src.right, src.bottom);
1904 qreal opacity = fragments[i].opacity * q->state()->opacity;
1905 opacityArray << opacity << opacity << opacity << opacity << opacity << opacity;
1906 allOpaque &= (opacity >= 0.99f);
1909 funcs.glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1910 QOpenGLTexture *texture = 0;//ctx->d_func()->bindTexture(pixmap, GL_TEXTURE_2D, GL_RGBA,
1911 // QOpenGLContext::InternalBindOption
1912 // | QOpenGLContext::CanFlipNativePixmapBindOption);
1914 if (texture->invertedY()) {
1915 // Flip texture y-coordinate.
1916 QOpenGLPoint *data = textureCoordinateArray.data();
1917 for (int i = 0; i < 6 * fragmentCount; ++i)
1918 data[i].y = 1 - data[i].y;
1921 transferMode(ImageArrayDrawingMode);
1923 bool isBitmap = pixmap.isQBitmap();
1924 bool isOpaque = !isBitmap && (!pixmap.hasAlpha() || (hints & QPainter::OpaqueHint)) && allOpaque;
1926 updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1927 q->state()->renderHints & QPainter::SmoothPixmapTransform, texture->id());
1929 // Setup for texture drawing
1930 currentBrush = noBrush;
1931 shaderManager->setSrcPixelType(isBitmap ? QOpenGLEngineShaderManager::PatternSrc
1932 : QOpenGLEngineShaderManager::ImageSrc);
1933 if (prepareForDraw(isOpaque))
1934 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::ImageTexture), QT_IMAGE_TEXTURE_UNIT);
1937 QColor col = qt_premultiplyColor(q->state()->pen.color(), (GLfloat)q->state()->opacity);
1938 shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::PatternColor), col);
1941 glDrawArrays(GL_TRIANGLES, 0, 6 * fragmentCount);
1944 bool QOpenGL2PaintEngineEx::begin(QPaintDevice *pdev)
1946 Q_D(QOpenGL2PaintEngineEx);
1948 Q_ASSERT(pdev->devType() == QInternal::OpenGL);
1949 d->device = static_cast<QOpenGLPaintDevice*>(pdev);
1954 if (d->device->context() != QOpenGLContext::currentContext()) {
1955 qWarning("QPainter::begin(): QOpenGLPaintDevice's context needs to be current");
1959 d->ctx = QOpenGLContext::currentContext();
1960 d->ctx->d_func()->active_engine = this;
1962 d->funcs.initializeGLFunctions();
1964 for (int i = 0; i < QT_GL_VERTEX_ARRAY_TRACKED_COUNT; ++i)
1965 d->vertexAttributeArraysEnabledState[i] = false;
1967 const QSize sz = d->device->size();
1968 d->width = sz.width();
1969 d->height = sz.height();
1970 d->mode = BrushDrawingMode;
1971 d->brushTextureDirty = true;
1972 d->brushUniformsDirty = true;
1973 d->matrixUniformDirty = true;
1974 d->matrixDirty = true;
1975 d->compositionModeDirty = true;
1976 d->opacityUniformDirty = true;
1977 d->needsSync = true;
1978 d->useSystemClip = !systemClip().isEmpty();
1979 d->currentBrush = QBrush();
1981 d->dirtyStencilRegion = QRect(0, 0, d->width, d->height);
1982 d->stencilClean = true;
1984 d->shaderManager = new QOpenGLEngineShaderManager(d->ctx);
1986 glDisable(GL_STENCIL_TEST);
1987 glDisable(GL_DEPTH_TEST);
1988 glDisable(GL_SCISSOR_TEST);
1990 #if !defined(QT_OPENGL_ES_2)
1991 glDisable(GL_MULTISAMPLE);
1994 d->glyphCacheType = QFontEngineGlyphCache::Raster_A8;
1996 #if !defined(QT_OPENGL_ES_2)
1997 #if defined(Q_WS_WIN)
1998 if (qt_cleartype_enabled
1999 && (fontSmoothingApproximately(1.0) || fontSmoothingApproximately(2.1)))
2001 #if defined(Q_WS_MAC)
2002 if (qt_applefontsmoothing_enabled)
2004 d->glyphCacheType = QFontEngineGlyphCache::Raster_RGBMask;
2007 #if defined(QT_OPENGL_ES_2)
2008 // OpenGL ES can't switch MSAA off, so if the gl paint device is
2009 // multisampled, it's always multisampled.
2010 d->multisamplingAlwaysEnabled = d->device->context()->format().samples() > 1;
2012 d->multisamplingAlwaysEnabled = false;
2018 bool QOpenGL2PaintEngineEx::end()
2020 Q_D(QOpenGL2PaintEngineEx);
2022 QOpenGLContext *ctx = d->ctx;
2023 d->funcs.glUseProgram(0);
2024 d->transferMode(BrushDrawingMode);
2026 ctx->d_func()->active_engine = 0;
2030 delete d->shaderManager;
2031 d->shaderManager = 0;
2032 d->currentBrush = QBrush();
2034 #ifdef QT_OPENGL_CACHE_AS_VBOS
2035 if (!d->unusedVBOSToClean.isEmpty()) {
2036 glDeleteBuffers(d->unusedVBOSToClean.size(), d->unusedVBOSToClean.constData());
2037 d->unusedVBOSToClean.clear();
2039 if (!d->unusedIBOSToClean.isEmpty()) {
2040 glDeleteBuffers(d->unusedIBOSToClean.size(), d->unusedIBOSToClean.constData());
2041 d->unusedIBOSToClean.clear();
2048 void QOpenGL2PaintEngineEx::ensureActive()
2050 Q_D(QOpenGL2PaintEngineEx);
2051 QOpenGLContext *ctx = d->ctx;
2053 if (isActive() && ctx->d_func()->active_engine != this) {
2054 ctx->d_func()->active_engine = this;
2055 d->needsSync = true;
2059 d->transferMode(BrushDrawingMode);
2060 glViewport(0, 0, d->width, d->height);
2061 d->needsSync = false;
2062 d->lastMaskTextureUsed = 0;
2063 d->shaderManager->setDirty();
2065 for (int i = 0; i < 3; ++i)
2066 d->vertexAttribPointers[i] = (GLfloat*)-1; // Assume the pointers are clobbered
2071 void QOpenGL2PaintEngineExPrivate::updateClipScissorTest()
2073 Q_Q(QOpenGL2PaintEngineEx);
2074 if (q->state()->clipTestEnabled) {
2075 glEnable(GL_STENCIL_TEST);
2076 glStencilFunc(GL_LEQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
2078 glDisable(GL_STENCIL_TEST);
2079 glStencilFunc(GL_ALWAYS, 0, 0xff);
2082 #ifdef QT_GL_NO_SCISSOR_TEST
2083 currentScissorBounds = QRect(0, 0, width, height);
2085 QRect bounds = q->state()->rectangleClip;
2086 if (!q->state()->clipEnabled) {
2088 bounds = systemClip.boundingRect();
2090 bounds = QRect(0, 0, width, height);
2093 bounds = bounds.intersected(systemClip.boundingRect());
2095 bounds = bounds.intersected(QRect(0, 0, width, height));
2098 currentScissorBounds = bounds;
2100 if (bounds == QRect(0, 0, width, height)) {
2101 glDisable(GL_SCISSOR_TEST);
2103 glEnable(GL_SCISSOR_TEST);
2109 void QOpenGL2PaintEngineExPrivate::setScissor(const QRect &rect)
2111 const int left = rect.left();
2112 const int width = rect.width();
2113 int bottom = height - (rect.top() + rect.height());
2114 if (device->paintFlipped()) {
2115 bottom = rect.top();
2117 const int height = rect.height();
2119 glScissor(left, bottom, width, height);
2122 void QOpenGL2PaintEngineEx::clipEnabledChanged()
2124 Q_D(QOpenGL2PaintEngineEx);
2126 state()->clipChanged = true;
2128 if (painter()->hasClipping())
2129 d->regenerateClip();
2131 d->systemStateChanged();
2134 void QOpenGL2PaintEngineExPrivate::clearClip(uint value)
2136 dirtyStencilRegion -= currentScissorBounds;
2138 glStencilMask(0xff);
2139 glClearStencil(value);
2140 glClear(GL_STENCIL_BUFFER_BIT);
2143 q->state()->needsClipBufferClear = false;
2146 void QOpenGL2PaintEngineExPrivate::writeClip(const QVectorPath &path, uint value)
2148 transferMode(BrushDrawingMode);
2150 if (snapToPixelGrid) {
2151 snapToPixelGrid = false;
2158 stencilClean = false;
2160 const bool singlePass = !path.hasWindingFill()
2161 && (((q->state()->currentClip == maxClip - 1) && q->state()->clipTestEnabled)
2162 || q->state()->needsClipBufferClear);
2163 const uint referenceClipValue = q->state()->needsClipBufferClear ? 1 : q->state()->currentClip;
2165 if (q->state()->needsClipBufferClear)
2168 if (path.isEmpty()) {
2169 glEnable(GL_STENCIL_TEST);
2170 glStencilFunc(GL_LEQUAL, value, ~GL_STENCIL_HIGH_BIT);
2174 if (q->state()->clipTestEnabled)
2175 glStencilFunc(GL_LEQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
2177 glStencilFunc(GL_ALWAYS, 0, 0xff);
2179 vertexCoordinateArray.clear();
2180 vertexCoordinateArray.addPath(path, inverseScale, false);
2183 fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill());
2185 glColorMask(false, false, false, false);
2186 glEnable(GL_STENCIL_TEST);
2190 // Under these conditions we can set the new stencil value in a single
2191 // pass, by using the current value and the "new value" as the toggles
2193 glStencilFunc(GL_LEQUAL, referenceClipValue, ~GL_STENCIL_HIGH_BIT);
2194 glStencilOp(GL_KEEP, GL_INVERT, GL_INVERT);
2195 glStencilMask(value ^ referenceClipValue);
2197 drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN);
2199 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
2200 glStencilMask(0xff);
2202 if (!q->state()->clipTestEnabled && path.hasWindingFill()) {
2203 // Pass when any clip bit is set, set high bit
2204 glStencilFunc(GL_NOTEQUAL, GL_STENCIL_HIGH_BIT, ~GL_STENCIL_HIGH_BIT);
2205 composite(vertexCoordinateArray.boundingRect());
2208 // Pass when high bit is set, replace stencil value with new clip value
2209 glStencilFunc(GL_NOTEQUAL, value, GL_STENCIL_HIGH_BIT);
2211 composite(vertexCoordinateArray.boundingRect());
2214 glStencilFunc(GL_LEQUAL, value, ~GL_STENCIL_HIGH_BIT);
2217 glColorMask(true, true, true, true);
2220 void QOpenGL2PaintEngineEx::clip(const QVectorPath &path, Qt::ClipOperation op)
2222 // qDebug("QOpenGL2PaintEngineEx::clip()");
2223 Q_D(QOpenGL2PaintEngineEx);
2225 state()->clipChanged = true;
2229 if (op == Qt::ReplaceClip) {
2230 op = Qt::IntersectClip;
2231 if (d->hasClipOperations()) {
2232 d->systemStateChanged();
2233 state()->canRestoreClip = false;
2237 #ifndef QT_GL_NO_SCISSOR_TEST
2238 if (!path.isEmpty() && op == Qt::IntersectClip && (path.shape() == QVectorPath::RectangleHint)) {
2239 const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
2240 QRectF rect(points[0], points[2]);
2242 if (state()->matrix.type() <= QTransform::TxScale
2243 || (state()->matrix.type() == QTransform::TxRotate
2244 && qFuzzyIsNull(state()->matrix.m11())
2245 && qFuzzyIsNull(state()->matrix.m22())))
2247 state()->rectangleClip = state()->rectangleClip.intersected(state()->matrix.mapRect(rect).toRect());
2248 d->updateClipScissorTest();
2254 const QRect pathRect = state()->matrix.mapRect(path.controlPointRect()).toAlignedRect();
2258 if (d->useSystemClip) {
2259 state()->clipTestEnabled = true;
2260 state()->currentClip = 1;
2262 state()->clipTestEnabled = false;
2264 state()->rectangleClip = QRect(0, 0, d->width, d->height);
2265 state()->canRestoreClip = false;
2266 d->updateClipScissorTest();
2268 case Qt::IntersectClip:
2269 state()->rectangleClip = state()->rectangleClip.intersected(pathRect);
2270 d->updateClipScissorTest();
2271 d->resetClipIfNeeded();
2273 d->writeClip(path, d->maxClip);
2274 state()->currentClip = d->maxClip;
2275 state()->clipTestEnabled = true;
2282 void QOpenGL2PaintEngineExPrivate::regenerateClip()
2284 systemStateChanged();
2285 replayClipOperations();
2288 void QOpenGL2PaintEngineExPrivate::systemStateChanged()
2290 Q_Q(QOpenGL2PaintEngineEx);
2292 q->state()->clipChanged = true;
2294 if (systemClip.isEmpty()) {
2295 useSystemClip = false;
2297 if (q->paintDevice()->devType() == QInternal::Widget && currentClipDevice) {
2298 //QWidgetPrivate *widgetPrivate = qt_widget_private(static_cast<QWidget *>(currentClipDevice)->window());
2299 //useSystemClip = widgetPrivate->extra && widgetPrivate->extra->inRenderWithPainter;
2300 useSystemClip = true;
2302 useSystemClip = true;
2306 q->state()->clipTestEnabled = false;
2307 q->state()->needsClipBufferClear = true;
2309 q->state()->currentClip = 1;
2312 q->state()->rectangleClip = useSystemClip ? systemClip.boundingRect() : QRect(0, 0, width, height);
2313 updateClipScissorTest();
2315 if (systemClip.rectCount() == 1) {
2316 if (systemClip.boundingRect() == QRect(0, 0, width, height))
2317 useSystemClip = false;
2318 #ifndef QT_GL_NO_SCISSOR_TEST
2319 // scissoring takes care of the system clip
2324 if (useSystemClip) {
2328 path.addRegion(systemClip);
2330 q->state()->currentClip = 0;
2331 writeClip(qtVectorPathForPath(q->state()->matrix.inverted().map(path)), 1);
2332 q->state()->currentClip = 1;
2333 q->state()->clipTestEnabled = true;
2337 void QOpenGL2PaintEngineEx::setState(QPainterState *new_state)
2339 // qDebug("QOpenGL2PaintEngineEx::setState()");
2341 Q_D(QOpenGL2PaintEngineEx);
2343 QOpenGL2PaintEngineState *s = static_cast<QOpenGL2PaintEngineState *>(new_state);
2344 QOpenGL2PaintEngineState *old_state = state();
2346 QPaintEngineEx::setState(s);
2349 // Newly created state object. The call to setState()
2350 // will either be followed by a call to begin(), or we are
2351 // setting the state as part of a save().
2356 // Setting the state as part of a restore().
2358 if (old_state == s || old_state->renderHintsChanged)
2359 renderHintsChanged();
2361 if (old_state == s || old_state->matrixChanged)
2362 d->matrixDirty = true;
2364 if (old_state == s || old_state->compositionModeChanged)
2365 d->compositionModeDirty = true;
2367 if (old_state == s || old_state->opacityChanged)
2368 d->opacityUniformDirty = true;
2370 if (old_state == s || old_state->clipChanged) {
2371 if (old_state && old_state != s && old_state->canRestoreClip) {
2372 d->updateClipScissorTest();
2373 glDepthFunc(GL_LEQUAL);
2375 d->regenerateClip();
2380 QPainterState *QOpenGL2PaintEngineEx::createState(QPainterState *orig) const
2383 const_cast<QOpenGL2PaintEngineEx *>(this)->ensureActive();
2385 QOpenGL2PaintEngineState *s;
2387 s = new QOpenGL2PaintEngineState();
2389 s = new QOpenGL2PaintEngineState(*static_cast<QOpenGL2PaintEngineState *>(orig));
2391 s->matrixChanged = false;
2392 s->compositionModeChanged = false;
2393 s->opacityChanged = false;
2394 s->renderHintsChanged = false;
2395 s->clipChanged = false;
2400 QOpenGL2PaintEngineState::QOpenGL2PaintEngineState(QOpenGL2PaintEngineState &other)
2401 : QPainterState(other)
2404 needsClipBufferClear = other.needsClipBufferClear;
2405 clipTestEnabled = other.clipTestEnabled;
2406 currentClip = other.currentClip;
2407 canRestoreClip = other.canRestoreClip;
2408 rectangleClip = other.rectangleClip;
2411 QOpenGL2PaintEngineState::QOpenGL2PaintEngineState()
2414 needsClipBufferClear = true;
2415 clipTestEnabled = false;
2416 canRestoreClip = true;
2419 QOpenGL2PaintEngineState::~QOpenGL2PaintEngineState()
2423 void QOpenGL2PaintEngineExPrivate::setVertexAttribArrayEnabled(int arrayIndex, bool enabled)
2425 Q_ASSERT(arrayIndex < QT_GL_VERTEX_ARRAY_TRACKED_COUNT);
2427 if (vertexAttributeArraysEnabledState[arrayIndex] && !enabled)
2428 funcs.glDisableVertexAttribArray(arrayIndex);
2430 if (!vertexAttributeArraysEnabledState[arrayIndex] && enabled)
2431 funcs.glEnableVertexAttribArray(arrayIndex);
2433 vertexAttributeArraysEnabledState[arrayIndex] = enabled;
2436 void QOpenGL2PaintEngineExPrivate::syncGlState()
2438 for (int i = 0; i < QT_GL_VERTEX_ARRAY_TRACKED_COUNT; ++i) {
2439 if (vertexAttributeArraysEnabledState[i])
2440 funcs.glEnableVertexAttribArray(i);
2442 funcs.glDisableVertexAttribArray(i);