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 QtOpenGL 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 "qglgradientcache_p.h"
68 #include "qpaintengineex_opengl2_p.h"
70 #include <string.h> //for memcpy
73 #include <private/qgl_p.h>
74 #include <private/qmath_p.h>
75 #include <private/qpaintengineex_p.h>
76 #include <QPaintEngine>
77 #include <private/qpainter_p.h>
78 #include <private/qfontengine_p.h>
79 #include <private/qdatabuffer_p.h>
80 #include <private/qstatictext_p.h>
81 #include <private/qtriangulator_p.h>
83 #include "qglengineshadermanager_p.h"
84 #include "qgl2pexvertexarray_p.h"
85 #include "qtriangulatingstroker_p.h"
86 #include "qtextureglyphcache_gl_p.h"
93 extern Q_GUI_EXPORT bool qt_cleartype_enabled;
97 extern bool qt_applefontsmoothing_enabled;
100 Q_GUI_EXPORT QImage qt_imageForBrush(int brushStyle, bool invert);
102 ////////////////////////////////// Private Methods //////////////////////////////////////////
104 QGL2PaintEngineExPrivate::~QGL2PaintEngineExPrivate()
106 delete shaderManager;
108 while (pathCaches.size()) {
109 QVectorPath::CacheEntry *e = *(pathCaches.constBegin());
110 e->cleanup(e->engine, e->data);
115 if (elementIndicesVBOId != 0) {
116 glDeleteBuffers(1, &elementIndicesVBOId);
117 elementIndicesVBOId = 0;
121 void QGL2PaintEngineExPrivate::updateTextureFilter(GLenum target, GLenum wrapMode, bool smoothPixmapTransform, GLuint id)
123 // glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT); //### Is it always this texture unit?
124 if (id != GLuint(-1) && id == lastTextureUsed)
127 lastTextureUsed = id;
129 if (smoothPixmapTransform) {
130 glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
131 glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
133 glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
134 glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
136 glTexParameterf(target, GL_TEXTURE_WRAP_S, wrapMode);
137 glTexParameterf(target, GL_TEXTURE_WRAP_T, wrapMode);
141 inline QColor qt_premultiplyColor(QColor c, GLfloat opacity)
143 qreal alpha = c.alphaF() * opacity;
145 c.setRedF(c.redF() * alpha);
146 c.setGreenF(c.greenF() * alpha);
147 c.setBlueF(c.blueF() * alpha);
152 void QGL2PaintEngineExPrivate::setBrush(const QBrush& brush)
154 if (qbrush_fast_equals(currentBrush, brush))
157 const Qt::BrushStyle newStyle = qbrush_style(brush);
158 Q_ASSERT(newStyle != Qt::NoBrush);
160 currentBrush = brush;
161 if (!currentBrushPixmap.isNull())
162 currentBrushPixmap = QPixmap();
163 brushUniformsDirty = true; // All brushes have at least one uniform
165 if (newStyle > Qt::SolidPattern)
166 brushTextureDirty = true;
168 if (currentBrush.style() == Qt::TexturePattern
169 && qHasPixmapTexture(brush) && brush.texture().isQBitmap())
171 shaderManager->setSrcPixelType(QGLEngineShaderManager::TextureSrcWithPattern);
173 shaderManager->setSrcPixelType(newStyle);
175 shaderManager->optimiseForBrushTransform(currentBrush.transform().type());
179 void QGL2PaintEngineExPrivate::useSimpleShader()
181 shaderManager->useSimpleProgram();
187 void QGL2PaintEngineExPrivate::updateBrushTexture()
189 Q_Q(QGL2PaintEngineEx);
190 // qDebug("QGL2PaintEngineExPrivate::updateBrushTexture()");
191 Qt::BrushStyle style = currentBrush.style();
193 if ( (style >= Qt::Dense1Pattern) && (style <= Qt::DiagCrossPattern) ) {
194 // Get the image data for the pattern
195 QImage texImage = qt_imageForBrush(style, false);
197 glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
198 ctx->d_func()->bindTexture(texImage, GL_TEXTURE_2D, GL_RGBA, QGLContext::InternalBindOption);
199 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
201 else if (style >= Qt::LinearGradientPattern && style <= Qt::ConicalGradientPattern) {
202 // Gradiant brush: All the gradiants use the same texture
204 const QGradient* g = currentBrush.gradient();
206 // We apply global opacity in the fragment shaders, so we always pass 1.0
207 // for opacity to the cache.
208 GLuint texId = QGL2GradientCache::cacheForContext(ctx)->getBuffer(*g, 1.0);
210 glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
211 glBindTexture(GL_TEXTURE_2D, texId);
213 if (g->spread() == QGradient::RepeatSpread || g->type() == QGradient::ConicalGradient)
214 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
215 else if (g->spread() == QGradient::ReflectSpread)
216 updateTextureFilter(GL_TEXTURE_2D, GL_MIRRORED_REPEAT_IBM, q->state()->renderHints & QPainter::SmoothPixmapTransform);
218 updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE, q->state()->renderHints & QPainter::SmoothPixmapTransform);
220 else if (style == Qt::TexturePattern) {
221 currentBrushPixmap = currentBrush.texture();
223 int max_texture_size = ctx->d_func()->maxTextureSize();
224 if (currentBrushPixmap.width() > max_texture_size || currentBrushPixmap.height() > max_texture_size)
225 currentBrushPixmap = currentBrushPixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
227 glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT);
228 QGLTexture *tex = ctx->d_func()->bindTexture(currentBrushPixmap, GL_TEXTURE_2D, GL_RGBA,
229 QGLContext::InternalBindOption |
230 QGLContext::CanFlipNativePixmapBindOption);
231 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform);
232 textureInvertedY = tex->options & QGLContext::InvertedYBindOption ? -1 : 1;
234 brushTextureDirty = false;
238 void QGL2PaintEngineExPrivate::updateBrushUniforms()
240 // qDebug("QGL2PaintEngineExPrivate::updateBrushUniforms()");
241 Qt::BrushStyle style = currentBrush.style();
243 if (style == Qt::NoBrush)
246 QTransform brushQTransform = currentBrush.transform();
248 if (style == Qt::SolidPattern) {
249 QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
250 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::FragmentColor), col);
253 // All other brushes have a transform and thus need the translation point:
254 QPointF translationPoint;
256 if (style <= Qt::DiagCrossPattern) {
257 QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
259 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::PatternColor), col);
261 QVector2D halfViewportSize(width*0.5, height*0.5);
262 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::HalfViewportSize), halfViewportSize);
264 else if (style == Qt::LinearGradientPattern) {
265 const QLinearGradient *g = static_cast<const QLinearGradient *>(currentBrush.gradient());
267 QPointF realStart = g->start();
268 QPointF realFinal = g->finalStop();
269 translationPoint = realStart;
271 QPointF l = realFinal - realStart;
273 QVector3D linearData(
276 1.0f / (l.x() * l.x() + l.y() * l.y())
279 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::LinearData), linearData);
281 QVector2D halfViewportSize(width*0.5, height*0.5);
282 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::HalfViewportSize), halfViewportSize);
284 else if (style == Qt::ConicalGradientPattern) {
285 const QConicalGradient *g = static_cast<const QConicalGradient *>(currentBrush.gradient());
286 translationPoint = g->center();
288 GLfloat angle = -(g->angle() * 2 * Q_PI) / 360.0;
290 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::Angle), angle);
292 QVector2D halfViewportSize(width*0.5, height*0.5);
293 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::HalfViewportSize), halfViewportSize);
295 else if (style == Qt::RadialGradientPattern) {
296 const QRadialGradient *g = static_cast<const QRadialGradient *>(currentBrush.gradient());
297 QPointF realCenter = g->center();
298 QPointF realFocal = g->focalPoint();
299 qreal realRadius = g->centerRadius() - g->focalRadius();
300 translationPoint = realFocal;
302 QPointF fmp = realCenter - realFocal;
303 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::Fmp), fmp);
305 GLfloat fmp2_m_radius2 = -fmp.x() * fmp.x() - fmp.y() * fmp.y() + realRadius*realRadius;
306 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::Fmp2MRadius2), fmp2_m_radius2);
307 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::Inverse2Fmp2MRadius2),
308 GLfloat(1.0 / (2.0*fmp2_m_radius2)));
309 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::SqrFr),
310 GLfloat(g->focalRadius() * g->focalRadius()));
311 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::BRadius),
312 GLfloat(2 * (g->centerRadius() - g->focalRadius()) * g->focalRadius()),
314 g->centerRadius() - g->focalRadius());
316 QVector2D halfViewportSize(width*0.5, height*0.5);
317 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::HalfViewportSize), halfViewportSize);
319 else if (style == Qt::TexturePattern) {
320 const QPixmap& texPixmap = currentBrush.texture();
322 if (qHasPixmapTexture(currentBrush) && currentBrush.texture().isQBitmap()) {
323 QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
324 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::PatternColor), col);
327 QSizeF invertedTextureSize(1.0 / texPixmap.width(), 1.0 / texPixmap.height());
328 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::InvertedTextureSize), invertedTextureSize);
330 QVector2D halfViewportSize(width*0.5, height*0.5);
331 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::HalfViewportSize), halfViewportSize);
334 qWarning("QGL2PaintEngineEx: Unimplemented fill style");
336 const QPointF &brushOrigin = q->state()->brushOrigin;
337 QTransform matrix = q->state()->matrix;
338 matrix.translate(brushOrigin.x(), brushOrigin.y());
340 QTransform translate(1, 0, 0, 1, -translationPoint.x(), -translationPoint.y());
343 if (device->isFlipped()) {
347 QTransform gl_to_qt(1, 0, 0, m22, 0, dy);
348 QTransform inv_matrix;
349 if (style == Qt::TexturePattern && textureInvertedY == -1)
350 inv_matrix = gl_to_qt * (QTransform(1, 0, 0, -1, 0, currentBrush.texture().height()) * brushQTransform * matrix).inverted() * translate;
352 inv_matrix = gl_to_qt * (brushQTransform * matrix).inverted() * translate;
354 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::BrushTransform), inv_matrix);
355 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::BrushTexture), QT_BRUSH_TEXTURE_UNIT);
357 brushUniformsDirty = false;
361 // This assumes the shader manager has already setup the correct shader program
362 void QGL2PaintEngineExPrivate::updateMatrix()
364 // qDebug("QGL2PaintEngineExPrivate::updateMatrix()");
366 const QTransform& transform = q->state()->matrix;
368 // The projection matrix converts from Qt's coordinate system to GL's coordinate system
369 // * GL's viewport is 2x2, Qt's is width x height
370 // * GL has +y -> -y going from bottom -> top, Qt is the other way round
371 // * GL has [0,0] in the center, Qt has it in the top-left
373 // This results in the Projection matrix below, which is multiplied by the painter's
374 // transformation matrix, as shown below:
376 // Projection Matrix Painter Transform
377 // ------------------------------------------------ ------------------------
378 // | 2.0 / width | 0.0 | -1.0 | | m11 | m21 | dx |
379 // | 0.0 | -2.0 / height | 1.0 | * | m12 | m22 | dy |
380 // | 0.0 | 0.0 | 1.0 | | m13 | m23 | m33 |
381 // ------------------------------------------------ ------------------------
383 // NOTE: The resultant matrix is also transposed, as GL expects column-major matracies
385 const GLfloat wfactor = 2.0f / width;
386 GLfloat hfactor = -2.0f / height;
388 GLfloat dx = transform.dx();
389 GLfloat dy = transform.dy();
391 if (device->isFlipped()) {
396 // Non-integer translates can have strange effects for some rendering operations such as
397 // anti-aliased text rendering. In such cases, we snap the translate to the pixel grid.
398 if (snapToPixelGrid && transform.type() == QTransform::TxTranslate) {
399 // 0.50 needs to rounded down to 0.0 for consistency with raster engine:
400 dx = ceilf(dx - 0.5f);
401 dy = ceilf(dy - 0.5f);
403 pmvMatrix[0][0] = (wfactor * transform.m11()) - transform.m13();
404 pmvMatrix[1][0] = (wfactor * transform.m21()) - transform.m23();
405 pmvMatrix[2][0] = (wfactor * dx) - transform.m33();
406 pmvMatrix[0][1] = (hfactor * transform.m12()) + transform.m13();
407 pmvMatrix[1][1] = (hfactor * transform.m22()) + transform.m23();
408 pmvMatrix[2][1] = (hfactor * dy) + transform.m33();
409 pmvMatrix[0][2] = transform.m13();
410 pmvMatrix[1][2] = transform.m23();
411 pmvMatrix[2][2] = transform.m33();
413 // 1/10000 == 0.0001, so we have good enough res to cover curves
414 // that span the entire widget...
415 inverseScale = qMax(1 / qMax( qMax(qAbs(transform.m11()), qAbs(transform.m22())),
416 qMax(qAbs(transform.m12()), qAbs(transform.m21())) ),
420 matrixUniformDirty = true;
422 // Set the PMV matrix attribute. As we use an attributes rather than uniforms, we only
423 // need to do this once for every matrix change and persists across all shader programs.
424 glVertexAttrib3fv(QT_PMV_MATRIX_1_ATTR, pmvMatrix[0]);
425 glVertexAttrib3fv(QT_PMV_MATRIX_2_ATTR, pmvMatrix[1]);
426 glVertexAttrib3fv(QT_PMV_MATRIX_3_ATTR, pmvMatrix[2]);
428 dasher.setInvScale(inverseScale);
429 stroker.setInvScale(inverseScale);
433 void QGL2PaintEngineExPrivate::updateCompositionMode()
435 // NOTE: The entire paint engine works on pre-multiplied data - which is why some of these
436 // composition modes look odd.
437 // qDebug() << "QGL2PaintEngineExPrivate::updateCompositionMode() - Setting GL composition mode for " << q->state()->composition_mode;
438 switch(q->state()->composition_mode) {
439 case QPainter::CompositionMode_SourceOver:
440 glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
442 case QPainter::CompositionMode_DestinationOver:
443 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE);
445 case QPainter::CompositionMode_Clear:
446 glBlendFunc(GL_ZERO, GL_ZERO);
448 case QPainter::CompositionMode_Source:
449 glBlendFunc(GL_ONE, GL_ZERO);
451 case QPainter::CompositionMode_Destination:
452 glBlendFunc(GL_ZERO, GL_ONE);
454 case QPainter::CompositionMode_SourceIn:
455 glBlendFunc(GL_DST_ALPHA, GL_ZERO);
457 case QPainter::CompositionMode_DestinationIn:
458 glBlendFunc(GL_ZERO, GL_SRC_ALPHA);
460 case QPainter::CompositionMode_SourceOut:
461 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ZERO);
463 case QPainter::CompositionMode_DestinationOut:
464 glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_ALPHA);
466 case QPainter::CompositionMode_SourceAtop:
467 glBlendFunc(GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
469 case QPainter::CompositionMode_DestinationAtop:
470 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA);
472 case QPainter::CompositionMode_Xor:
473 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
475 case QPainter::CompositionMode_Plus:
476 glBlendFunc(GL_ONE, GL_ONE);
479 qWarning("Unsupported composition mode");
483 compositionModeDirty = false;
486 static inline void setCoords(GLfloat *coords, const QGLRect &rect)
488 coords[0] = rect.left;
489 coords[1] = rect.top;
490 coords[2] = rect.right;
491 coords[3] = rect.top;
492 coords[4] = rect.right;
493 coords[5] = rect.bottom;
494 coords[6] = rect.left;
495 coords[7] = rect.bottom;
498 void QGL2PaintEngineExPrivate::drawTexture(const QGLRect& dest, const QGLRect& src, const QSize &textureSize, bool opaque, bool pattern)
500 // Setup for texture drawing
501 currentBrush = noBrush;
502 shaderManager->setSrcPixelType(pattern ? QGLEngineShaderManager::PatternSrc : QGLEngineShaderManager::ImageSrc);
504 if (snapToPixelGrid) {
505 snapToPixelGrid = false;
509 if (prepareForDraw(opaque))
510 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::ImageTexture), QT_IMAGE_TEXTURE_UNIT);
513 QColor col = qt_premultiplyColor(q->state()->pen.color(), (GLfloat)q->state()->opacity);
514 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::PatternColor), col);
517 GLfloat dx = 1.0 / textureSize.width();
518 GLfloat dy = 1.0 / textureSize.height();
520 QGLRect srcTextureRect(src.left*dx, src.top*dy, src.right*dx, src.bottom*dy);
522 setCoords(staticVertexCoordinateArray, dest);
523 setCoords(staticTextureCoordinateArray, srcTextureRect);
525 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
528 void QGL2PaintEngineEx::beginNativePainting()
530 Q_D(QGL2PaintEngineEx);
532 d->transferMode(BrushDrawingMode);
534 d->nativePaintingActive = true;
536 QGLContext *ctx = d->ctx;
539 // Disable all the vertex attribute arrays:
540 for (int i = 0; i < QT_GL_VERTEX_ARRAY_TRACKED_COUNT; ++i)
541 glDisableVertexAttribArray(i);
543 #ifndef QT_OPENGL_ES_2
544 const QGLFormat &fmt = d->device->format();
545 if (fmt.majorVersion() < 3 || (fmt.majorVersion() == 3 && fmt.minorVersion() < 1)
546 || fmt.profile() == QGLFormat::CompatibilityProfile)
548 // be nice to people who mix OpenGL 1.x code with QPainter commands
549 // by setting modelview and projection matrices to mirror the GL 1
551 const QTransform& mtx = state()->matrix;
553 float mv_matrix[4][4] =
555 { float(mtx.m11()), float(mtx.m12()), 0, float(mtx.m13()) },
556 { float(mtx.m21()), float(mtx.m22()), 0, float(mtx.m23()) },
558 { float(mtx.dx()), float(mtx.dy()), 0, float(mtx.m33()) }
561 const QSize sz = d->device->size();
563 glMatrixMode(GL_PROJECTION);
565 glOrtho(0, sz.width(), sz.height(), 0, -999999, 999999);
567 glMatrixMode(GL_MODELVIEW);
568 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 QGL2PaintEngineExPrivate::resetGLState()
586 glActiveTexture(GL_TEXTURE0);
587 glDisable(GL_STENCIL_TEST);
588 glDisable(GL_DEPTH_TEST);
589 glDisable(GL_SCISSOR_TEST);
591 glDepthFunc(GL_LESS);
594 glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
595 glStencilFunc(GL_ALWAYS, 0, 0xff);
596 ctx->d_func()->setVertexAttribArrayEnabled(QT_TEXTURE_COORDS_ATTR, false);
597 ctx->d_func()->setVertexAttribArrayEnabled(QT_VERTEX_COORDS_ATTR, false);
598 ctx->d_func()->setVertexAttribArrayEnabled(QT_OPACITY_ATTR, false);
599 #ifndef QT_OPENGL_ES_2
600 // gl_Color, corresponding to vertex attribute 3, may have been changed
601 float color[] = { 1.0f, 1.0f, 1.0f, 1.0f };
602 glVertexAttrib4fv(3, color);
606 void QGL2PaintEngineEx::endNativePainting()
608 Q_D(QGL2PaintEngineEx);
610 d->nativePaintingActive = false;
613 void QGL2PaintEngineEx::invalidateState()
615 Q_D(QGL2PaintEngineEx);
619 bool QGL2PaintEngineEx::isNativePaintingActive() const {
620 Q_D(const QGL2PaintEngineEx);
621 return d->nativePaintingActive;
624 void QGL2PaintEngineExPrivate::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(QGLEngineShaderManager::NoMask);
657 struct QGL2PEVectorPathCache
659 #ifdef QT_OPENGL_CACHE_AS_VBOS
668 GLenum primitiveType;
672 void QGL2PaintEngineExPrivate::cleanupVectorPath(QPaintEngineEx *engine, void *data)
674 QGL2PEVectorPathCache *c = (QGL2PEVectorPathCache *) data;
675 #ifdef QT_OPENGL_CACHE_AS_VBOS
676 Q_ASSERT(engine->type() == QPaintEngine::OpenGL2);
677 static_cast<QGL2PaintEngineEx *>(engine)->d_func()->unusedVBOSToClean << c->vbo;
679 d->unusedIBOSToClean << c->ibo;
688 // Assumes everything is configured for the brush you want to use
689 void QGL2PaintEngineExPrivate::fill(const QVectorPath& path)
691 transferMode(BrushDrawingMode);
693 if (snapToPixelGrid) {
694 snapToPixelGrid = false;
698 // Might need to call updateMatrix to re-calculate inverseScale
702 const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
704 // Check to see if there's any hints
705 if (path.shape() == QVectorPath::RectangleHint) {
706 QGLRect rect(points[0].x(), points[0].y(), points[2].x(), points[2].y());
707 prepareForDraw(currentBrush.isOpaque());
709 } else if (path.isConvex()) {
711 if (path.isCacheable()) {
712 QVectorPath::CacheEntry *data = path.lookupCacheData(q);
713 QGL2PEVectorPathCache *cache;
715 bool updateCache = false;
718 cache = (QGL2PEVectorPathCache *) data->data;
719 // Check if scale factor is exceeded for curved paths and generate curves if so...
720 if (path.isCurved()) {
721 qreal scaleFactor = cache->iscale / inverseScale;
722 if (scaleFactor < 0.5 || scaleFactor > 2.0) {
723 #ifdef QT_OPENGL_CACHE_AS_VBOS
724 glDeleteBuffers(1, &cache->vbo);
726 Q_ASSERT(cache->ibo == 0);
728 qFree(cache->vertices);
729 Q_ASSERT(cache->indices == 0);
735 cache = new QGL2PEVectorPathCache;
736 data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
740 // Flatten the path at the current scale factor and fill it into the cache struct.
742 vertexCoordinateArray.clear();
743 vertexCoordinateArray.addPath(path, inverseScale, false);
744 int vertexCount = vertexCoordinateArray.vertexCount();
745 int floatSizeInBytes = vertexCount * 2 * sizeof(float);
746 cache->vertexCount = vertexCount;
747 cache->indexCount = 0;
748 cache->primitiveType = GL_TRIANGLE_FAN;
749 cache->iscale = inverseScale;
750 #ifdef QT_OPENGL_CACHE_AS_VBOS
751 glGenBuffers(1, &cache->vbo);
752 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
753 glBufferData(GL_ARRAY_BUFFER, floatSizeInBytes, vertexCoordinateArray.data(), GL_STATIC_DRAW);
756 cache->vertices = (float *) qMalloc(floatSizeInBytes);
757 memcpy(cache->vertices, vertexCoordinateArray.data(), floatSizeInBytes);
762 prepareForDraw(currentBrush.isOpaque());
763 #ifdef QT_OPENGL_CACHE_AS_VBOS
764 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
765 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, 0);
767 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, cache->vertices);
769 glDrawArrays(cache->primitiveType, 0, cache->vertexCount);
772 // printf(" - Marking path as cachable...\n");
773 // Tag it for later so that if the same path is drawn twice, it is assumed to be static and thus cachable
774 path.makeCacheable();
775 vertexCoordinateArray.clear();
776 vertexCoordinateArray.addPath(path, inverseScale, false);
777 prepareForDraw(currentBrush.isOpaque());
778 drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN);
782 bool useCache = path.isCacheable();
784 QRectF bbox = path.controlPointRect();
785 // If the path doesn't fit within these limits, it is possible that the triangulation will fail.
786 useCache &= (bbox.left() > -0x8000 * inverseScale)
787 && (bbox.right() < 0x8000 * inverseScale)
788 && (bbox.top() > -0x8000 * inverseScale)
789 && (bbox.bottom() < 0x8000 * inverseScale);
793 QVectorPath::CacheEntry *data = path.lookupCacheData(q);
794 QGL2PEVectorPathCache *cache;
796 bool updateCache = false;
799 cache = (QGL2PEVectorPathCache *) data->data;
800 // Check if scale factor is exceeded for curved paths and generate curves if so...
801 if (path.isCurved()) {
802 qreal scaleFactor = cache->iscale / inverseScale;
803 if (scaleFactor < 0.5 || scaleFactor > 2.0) {
804 #ifdef QT_OPENGL_CACHE_AS_VBOS
805 glDeleteBuffers(1, &cache->vbo);
806 glDeleteBuffers(1, &cache->ibo);
808 qFree(cache->vertices);
809 qFree(cache->indices);
815 cache = new QGL2PEVectorPathCache;
816 data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
820 // Flatten the path at the current scale factor and fill it into the cache struct.
822 QTriangleSet polys = qTriangulate(path, QTransform().scale(1 / inverseScale, 1 / inverseScale));
823 cache->vertexCount = polys.vertices.size() / 2;
824 cache->indexCount = polys.indices.size();
825 cache->primitiveType = GL_TRIANGLES;
826 cache->iscale = inverseScale;
827 #ifdef QT_OPENGL_CACHE_AS_VBOS
828 glGenBuffers(1, &cache->vbo);
829 glGenBuffers(1, &cache->ibo);
830 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
831 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cache->ibo);
833 if (QGLExtensions::glExtensions() & QGLExtensions::ElementIndexUint)
834 glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint32) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
836 glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint16) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
838 QVarLengthArray<float> vertices(polys.vertices.size());
839 for (int i = 0; i < polys.vertices.size(); ++i)
840 vertices[i] = float(inverseScale * polys.vertices.at(i));
841 glBufferData(GL_ARRAY_BUFFER, sizeof(float) * vertices.size(), vertices.data(), GL_STATIC_DRAW);
843 cache->vertices = (float *) qMalloc(sizeof(float) * polys.vertices.size());
844 if (QGLExtensions::glExtensions() & QGLExtensions::ElementIndexUint) {
845 cache->indices = (quint32 *) qMalloc(sizeof(quint32) * polys.indices.size());
846 memcpy(cache->indices, polys.indices.data(), sizeof(quint32) * polys.indices.size());
848 cache->indices = (quint16 *) qMalloc(sizeof(quint16) * polys.indices.size());
849 memcpy(cache->indices, polys.indices.data(), sizeof(quint16) * polys.indices.size());
851 for (int i = 0; i < polys.vertices.size(); ++i)
852 cache->vertices[i] = float(inverseScale * polys.vertices.at(i));
856 prepareForDraw(currentBrush.isOpaque());
857 #ifdef QT_OPENGL_CACHE_AS_VBOS
858 glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
859 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cache->ibo);
860 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, 0);
861 if (QGLExtensions::glExtensions() & QGLExtensions::ElementIndexUint)
862 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_INT, 0);
864 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_SHORT, 0);
865 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
866 glBindBuffer(GL_ARRAY_BUFFER, 0);
868 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, cache->vertices);
869 if (QGLExtensions::glExtensions() & QGLExtensions::ElementIndexUint)
870 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_INT, (qint32 *)cache->indices);
872 glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_SHORT, (qint16 *)cache->indices);
876 // printf(" - Marking path as cachable...\n");
877 // Tag it for later so that if the same path is drawn twice, it is assumed to be static and thus cachable
878 path.makeCacheable();
880 if (!device->format().stencil()) {
881 // If there is no stencil buffer, triangulate the path instead.
883 QRectF bbox = path.controlPointRect();
884 // If the path doesn't fit within these limits, it is possible that the triangulation will fail.
885 bool withinLimits = (bbox.left() > -0x8000 * inverseScale)
886 && (bbox.right() < 0x8000 * inverseScale)
887 && (bbox.top() > -0x8000 * inverseScale)
888 && (bbox.bottom() < 0x8000 * inverseScale);
890 QTriangleSet polys = qTriangulate(path, QTransform().scale(1 / inverseScale, 1 / inverseScale));
892 QVarLengthArray<float> vertices(polys.vertices.size());
893 for (int i = 0; i < polys.vertices.size(); ++i)
894 vertices[i] = float(inverseScale * polys.vertices.at(i));
896 prepareForDraw(currentBrush.isOpaque());
897 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, vertices.constData());
898 if (QGLExtensions::glExtensions() & QGLExtensions::ElementIndexUint)
899 glDrawElements(GL_TRIANGLES, polys.indices.size(), GL_UNSIGNED_INT, polys.indices.data());
901 glDrawElements(GL_TRIANGLES, polys.indices.size(), GL_UNSIGNED_SHORT, polys.indices.data());
903 // We can't handle big, concave painter paths with OpenGL without stencil buffer.
904 qWarning("Painter path exceeds +/-32767 pixels.");
909 // The path is too complicated & needs the stencil technique
910 vertexCoordinateArray.clear();
911 vertexCoordinateArray.addPath(path, inverseScale, false);
913 fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill());
916 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
918 if (q->state()->clipTestEnabled) {
919 // Pass when high bit is set, replace stencil value with current clip
920 glStencilFunc(GL_NOTEQUAL, q->state()->currentClip, GL_STENCIL_HIGH_BIT);
921 } else if (path.hasWindingFill()) {
922 // Pass when any bit is set, replace stencil value with 0
923 glStencilFunc(GL_NOTEQUAL, 0, 0xff);
925 // Pass when high bit is set, replace stencil value with 0
926 glStencilFunc(GL_NOTEQUAL, 0, GL_STENCIL_HIGH_BIT);
928 prepareForDraw(currentBrush.isOpaque());
930 // Stencil the brush onto the dest buffer
931 composite(vertexCoordinateArray.boundingRect());
933 updateClipScissorTest();
939 void QGL2PaintEngineExPrivate::fillStencilWithVertexArray(const float *data,
943 const QGLRect &bounds,
944 StencilFillMode mode)
946 Q_ASSERT(count || stops);
948 // qDebug("QGL2PaintEngineExPrivate::fillStencilWithVertexArray()");
949 glStencilMask(0xff); // Enable stencil writes
951 if (dirtyStencilRegion.intersects(currentScissorBounds)) {
952 QVector<QRect> clearRegion = dirtyStencilRegion.intersected(currentScissorBounds).rects();
953 glClearStencil(0); // Clear to zero
954 for (int i = 0; i < clearRegion.size(); ++i) {
955 #ifndef QT_GL_NO_SCISSOR_TEST
956 setScissor(clearRegion.at(i));
958 glClear(GL_STENCIL_BUFFER_BIT);
961 dirtyStencilRegion -= currentScissorBounds;
963 #ifndef QT_GL_NO_SCISSOR_TEST
964 updateClipScissorTest();
968 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); // Disable color writes
970 glEnable(GL_STENCIL_TEST); // For some reason, this has to happen _after_ the simple shader is use()'d
972 if (mode == WindingFillMode) {
973 Q_ASSERT(stops && !count);
974 if (q->state()->clipTestEnabled) {
975 // Flatten clip values higher than current clip, and set high bit to match current clip
976 glStencilFunc(GL_LEQUAL, GL_STENCIL_HIGH_BIT | q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
977 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
980 glStencilFunc(GL_EQUAL, GL_STENCIL_HIGH_BIT, GL_STENCIL_HIGH_BIT);
981 } else if (!stencilClean) {
982 // Clear stencil buffer within bounding rect
983 glStencilFunc(GL_ALWAYS, 0, 0xff);
984 glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO);
988 // Inc. for front-facing triangle
989 glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_INCR_WRAP, GL_INCR_WRAP);
990 // Dec. for back-facing "holes"
991 glStencilOpSeparate(GL_BACK, GL_KEEP, GL_DECR_WRAP, GL_DECR_WRAP);
992 glStencilMask(~GL_STENCIL_HIGH_BIT);
993 drawVertexArrays(data, stops, stopCount, GL_TRIANGLE_FAN);
995 if (q->state()->clipTestEnabled) {
996 // Clear high bit of stencil outside of path
997 glStencilFunc(GL_EQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
998 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
999 glStencilMask(GL_STENCIL_HIGH_BIT);
1002 } else if (mode == OddEvenFillMode) {
1003 glStencilMask(GL_STENCIL_HIGH_BIT);
1004 glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT); // Simply invert the stencil bit
1005 drawVertexArrays(data, stops, stopCount, GL_TRIANGLE_FAN);
1007 } else { // TriStripStrokeFillMode
1008 Q_ASSERT(count && !stops); // tristrips generated directly, so no vertexArray or stops
1009 glStencilMask(GL_STENCIL_HIGH_BIT);
1011 glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT); // Simply invert the stencil bit
1012 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, data);
1013 glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
1016 glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
1017 if (q->state()->clipTestEnabled) {
1018 glStencilFunc(GL_LEQUAL, q->state()->currentClip | GL_STENCIL_HIGH_BIT,
1019 ~GL_STENCIL_HIGH_BIT);
1021 glStencilFunc(GL_ALWAYS, GL_STENCIL_HIGH_BIT, 0xff);
1023 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, data);
1024 glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
1028 // Enable color writes & disable stencil writes
1029 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1033 If the maximum value in the stencil buffer is GL_STENCIL_HIGH_BIT - 1,
1034 restore the stencil buffer to a pristine state. The current clip region
1035 is set to 1, and the rest to 0.
1037 void QGL2PaintEngineExPrivate::resetClipIfNeeded()
1039 if (maxClip != (GL_STENCIL_HIGH_BIT - 1))
1042 Q_Q(QGL2PaintEngineEx);
1045 glEnable(GL_STENCIL_TEST);
1046 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1048 QRectF bounds = q->state()->matrix.inverted().mapRect(QRectF(0, 0, width, height));
1049 QGLRect rect(bounds.left(), bounds.top(), bounds.right(), bounds.bottom());
1051 // Set high bit on clip region
1052 glStencilFunc(GL_LEQUAL, q->state()->currentClip, 0xff);
1053 glStencilOp(GL_KEEP, GL_INVERT, GL_INVERT);
1054 glStencilMask(GL_STENCIL_HIGH_BIT);
1057 // Reset clipping to 1 and everything else to zero
1058 glStencilFunc(GL_NOTEQUAL, 0x01, GL_STENCIL_HIGH_BIT);
1059 glStencilOp(GL_ZERO, GL_REPLACE, GL_REPLACE);
1060 glStencilMask(0xff);
1063 q->state()->currentClip = 1;
1064 q->state()->canRestoreClip = false;
1069 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1072 bool QGL2PaintEngineExPrivate::prepareForDraw(bool srcPixelsAreOpaque)
1074 if (brushTextureDirty && mode != ImageDrawingMode && mode != ImageArrayDrawingMode)
1075 updateBrushTexture();
1077 if (compositionModeDirty)
1078 updateCompositionMode();
1083 const bool stateHasOpacity = q->state()->opacity < 0.99f;
1084 if (q->state()->composition_mode == QPainter::CompositionMode_Source
1085 || (q->state()->composition_mode == QPainter::CompositionMode_SourceOver
1086 && srcPixelsAreOpaque && !stateHasOpacity))
1088 glDisable(GL_BLEND);
1093 QGLEngineShaderManager::OpacityMode opacityMode;
1094 if (mode == ImageArrayDrawingMode) {
1095 opacityMode = QGLEngineShaderManager::AttributeOpacity;
1097 opacityMode = stateHasOpacity ? QGLEngineShaderManager::UniformOpacity
1098 : QGLEngineShaderManager::NoOpacity;
1099 if (stateHasOpacity && (mode != ImageDrawingMode)) {
1101 bool brushIsPattern = (currentBrush.style() >= Qt::Dense1Pattern) &&
1102 (currentBrush.style() <= Qt::DiagCrossPattern);
1104 if ((currentBrush.style() == Qt::SolidPattern) || brushIsPattern)
1105 opacityMode = QGLEngineShaderManager::NoOpacity; // Global opacity handled by srcPixel shader
1108 shaderManager->setOpacityMode(opacityMode);
1110 bool changed = shaderManager->useCorrectShaderProg();
1111 // If the shader program needs changing, we change it and mark all uniforms as dirty
1113 // The shader program has changed so mark all uniforms as dirty:
1114 brushUniformsDirty = true;
1115 opacityUniformDirty = true;
1116 matrixUniformDirty = true;
1119 if (brushUniformsDirty && mode != ImageDrawingMode && mode != ImageArrayDrawingMode)
1120 updateBrushUniforms();
1122 if (opacityMode == QGLEngineShaderManager::UniformOpacity && opacityUniformDirty) {
1123 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::GlobalOpacity), (GLfloat)q->state()->opacity);
1124 opacityUniformDirty = false;
1127 if (matrixUniformDirty && shaderManager->hasComplexGeometry()) {
1128 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::Matrix),
1130 matrixUniformDirty = false;
1136 void QGL2PaintEngineExPrivate::composite(const QGLRect& boundingRect)
1138 setCoords(staticVertexCoordinateArray, boundingRect);
1139 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, staticVertexCoordinateArray);
1140 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1143 // Draws the vertex array as a set of <vertexArrayStops.size()> triangle fans.
1144 void QGL2PaintEngineExPrivate::drawVertexArrays(const float *data, int *stops, int stopCount,
1147 // Now setup the pointer to the vertex array:
1148 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)data);
1150 int previousStop = 0;
1151 for (int i=0; i<stopCount; ++i) {
1152 int stop = stops[i];
1154 qDebug("Drawing triangle fan for vertecies %d -> %d:", previousStop, stop-1);
1155 for (int i=previousStop; i<stop; ++i)
1156 qDebug(" %02d: [%.2f, %.2f]", i, vertexArray.data()[i].x, vertexArray.data()[i].y);
1158 glDrawArrays(primitive, previousStop, stop - previousStop);
1159 previousStop = stop;
1163 /////////////////////////////////// Public Methods //////////////////////////////////////////
1165 QGL2PaintEngineEx::QGL2PaintEngineEx()
1166 : QPaintEngineEx(*(new QGL2PaintEngineExPrivate(this)))
1170 QGL2PaintEngineEx::~QGL2PaintEngineEx()
1174 void QGL2PaintEngineEx::fill(const QVectorPath &path, const QBrush &brush)
1176 Q_D(QGL2PaintEngineEx);
1178 if (qbrush_style(brush) == Qt::NoBrush)
1185 Q_GUI_EXPORT bool qt_scaleForTransform(const QTransform &transform, qreal *scale); // qtransform.cpp
1188 void QGL2PaintEngineEx::stroke(const QVectorPath &path, const QPen &pen)
1190 Q_D(QGL2PaintEngineEx);
1192 const QBrush &penBrush = qpen_brush(pen);
1193 if (qpen_style(pen) == Qt::NoPen || qbrush_style(penBrush) == Qt::NoBrush)
1196 QOpenGL2PaintEngineState *s = state();
1197 if (pen.isCosmetic() && !qt_scaleForTransform(s->transform(), 0)) {
1198 // QTriangulatingStroker class is not meant to support cosmetically sheared strokes.
1199 QPaintEngineEx::stroke(path, pen);
1204 d->setBrush(penBrush);
1205 d->stroke(path, pen);
1208 void QGL2PaintEngineExPrivate::stroke(const QVectorPath &path, const QPen &pen)
1210 const QOpenGL2PaintEngineState *s = q->state();
1211 if (snapToPixelGrid) {
1212 snapToPixelGrid = false;
1216 const Qt::PenStyle penStyle = qpen_style(pen);
1217 const QBrush &penBrush = qpen_brush(pen);
1218 const bool opaque = penBrush.isOpaque() && s->opacity > 0.99;
1220 transferMode(BrushDrawingMode);
1222 // updateMatrix() is responsible for setting the inverse scale on
1223 // the strokers, so we need to call it here and not wait for
1224 // prepareForDraw() down below.
1227 QRectF clip = q->state()->matrix.inverted().mapRect(q->state()->clipEnabled
1228 ? q->state()->rectangleClip
1229 : QRectF(0, 0, width, height));
1231 if (penStyle == Qt::SolidLine) {
1232 stroker.process(path, pen, clip);
1234 } else { // Some sort of dash
1235 dasher.process(path, pen, clip);
1237 QVectorPath dashStroke(dasher.points(),
1238 dasher.elementCount(),
1239 dasher.elementTypes());
1240 stroker.process(dashStroke, pen, clip);
1243 if (!stroker.vertexCount())
1247 prepareForDraw(opaque);
1248 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, stroker.vertices());
1249 glDrawArrays(GL_TRIANGLE_STRIP, 0, stroker.vertexCount() / 2);
1251 // QBrush b(Qt::green);
1253 // d->prepareForDraw(true);
1254 // glDrawArrays(GL_LINE_STRIP, 0, d->stroker.vertexCount() / 2);
1257 qreal width = qpen_widthf(pen) / 2;
1260 qreal extra = pen.joinStyle() == Qt::MiterJoin
1261 ? qMax(pen.miterLimit() * width, width)
1264 if (pen.isCosmetic())
1265 extra = extra * inverseScale;
1267 QRectF bounds = path.controlPointRect().adjusted(-extra, -extra, extra, extra);
1269 fillStencilWithVertexArray(stroker.vertices(), stroker.vertexCount() / 2,
1270 0, 0, bounds, QGL2PaintEngineExPrivate::TriStripStrokeFillMode);
1272 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
1274 // Pass when any bit is set, replace stencil value with 0
1275 glStencilFunc(GL_NOTEQUAL, 0, GL_STENCIL_HIGH_BIT);
1276 prepareForDraw(false);
1278 // Stencil the brush onto the dest buffer
1283 updateClipScissorTest();
1287 void QGL2PaintEngineEx::penChanged() { }
1288 void QGL2PaintEngineEx::brushChanged() { }
1289 void QGL2PaintEngineEx::brushOriginChanged() { }
1291 void QGL2PaintEngineEx::opacityChanged()
1293 // qDebug("QGL2PaintEngineEx::opacityChanged()");
1294 Q_D(QGL2PaintEngineEx);
1295 state()->opacityChanged = true;
1297 Q_ASSERT(d->shaderManager);
1298 d->brushUniformsDirty = true;
1299 d->opacityUniformDirty = true;
1302 void QGL2PaintEngineEx::compositionModeChanged()
1304 // qDebug("QGL2PaintEngineEx::compositionModeChanged()");
1305 Q_D(QGL2PaintEngineEx);
1306 state()->compositionModeChanged = true;
1307 d->compositionModeDirty = true;
1310 void QGL2PaintEngineEx::renderHintsChanged()
1312 state()->renderHintsChanged = true;
1314 #if !defined(QT_OPENGL_ES_2)
1315 if ((state()->renderHints & QPainter::Antialiasing)
1316 || (state()->renderHints & QPainter::HighQualityAntialiasing))
1317 glEnable(GL_MULTISAMPLE);
1319 glDisable(GL_MULTISAMPLE);
1322 Q_D(QGL2PaintEngineEx);
1323 d->lastTextureUsed = GLuint(-1);
1324 d->brushTextureDirty = true;
1325 // qDebug("QGL2PaintEngineEx::renderHintsChanged() not implemented!");
1328 void QGL2PaintEngineEx::transformChanged()
1330 Q_D(QGL2PaintEngineEx);
1331 d->matrixDirty = true;
1332 state()->matrixChanged = true;
1336 static const QRectF scaleRect(const QRectF &r, qreal sx, qreal sy)
1338 return QRectF(r.x() * sx, r.y() * sy, r.width() * sx, r.height() * sy);
1341 void QGL2PaintEngineEx::drawPixmap(const QRectF& dest, const QPixmap & pixmap, const QRectF & src)
1343 Q_D(QGL2PaintEngineEx);
1344 QGLContext *ctx = d->ctx;
1346 int max_texture_size = ctx->d_func()->maxTextureSize();
1347 if (pixmap.width() > max_texture_size || pixmap.height() > max_texture_size) {
1348 QPixmap scaled = pixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1350 const qreal sx = scaled.width() / qreal(pixmap.width());
1351 const qreal sy = scaled.height() / qreal(pixmap.height());
1353 drawPixmap(dest, scaled, scaleRect(src, sx, sy));
1358 d->transferMode(ImageDrawingMode);
1360 QGLContext::BindOptions bindOptions = QGLContext::InternalBindOption|QGLContext::CanFlipNativePixmapBindOption;
1361 #ifdef QGL_USE_TEXTURE_POOL
1362 bindOptions |= QGLContext::TemporarilyCachedBindOption;
1365 glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1366 QGLTexture *texture =
1367 ctx->d_func()->bindTexture(pixmap, GL_TEXTURE_2D, GL_RGBA, bindOptions);
1369 GLfloat top = texture->options & QGLContext::InvertedYBindOption ? (pixmap.height() - src.top()) : src.top();
1370 GLfloat bottom = texture->options & QGLContext::InvertedYBindOption ? (pixmap.height() - src.bottom()) : src.bottom();
1371 QGLRect srcRect(src.left(), top, src.right(), bottom);
1373 bool isBitmap = pixmap.isQBitmap();
1374 bool isOpaque = !isBitmap && !pixmap.hasAlpha();
1376 d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1377 state()->renderHints & QPainter::SmoothPixmapTransform, texture->id);
1378 d->drawTexture(dest, srcRect, pixmap.size(), isOpaque, isBitmap);
1380 if (texture->options&QGLContext::TemporarilyCachedBindOption) {
1381 // pixmap was temporarily cached as a QImage texture by pooling system
1382 // and should be destroyed immediately
1383 QGLTextureCache::instance()->remove(ctx, texture->id);
1387 void QGL2PaintEngineEx::drawImage(const QRectF& dest, const QImage& image, const QRectF& src,
1388 Qt::ImageConversionFlags)
1390 Q_D(QGL2PaintEngineEx);
1391 QGLContext *ctx = d->ctx;
1393 int max_texture_size = ctx->d_func()->maxTextureSize();
1394 if (image.width() > max_texture_size || image.height() > max_texture_size) {
1395 QImage scaled = image.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1397 const qreal sx = scaled.width() / qreal(image.width());
1398 const qreal sy = scaled.height() / qreal(image.height());
1400 drawImage(dest, scaled, scaleRect(src, sx, sy));
1405 d->transferMode(ImageDrawingMode);
1407 glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1409 QGLContext::BindOptions bindOptions = QGLContext::InternalBindOption;
1410 #ifdef QGL_USE_TEXTURE_POOL
1411 bindOptions |= QGLContext::TemporarilyCachedBindOption;
1414 QGLTexture *texture = ctx->d_func()->bindTexture(image, GL_TEXTURE_2D, GL_RGBA, bindOptions);
1415 GLuint id = texture->id;
1417 d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1418 state()->renderHints & QPainter::SmoothPixmapTransform, id);
1419 d->drawTexture(dest, src, image.size(), !image.hasAlphaChannel());
1421 if (texture->options&QGLContext::TemporarilyCachedBindOption) {
1422 // image was temporarily cached by texture pooling system
1423 // and should be destroyed immediately
1424 QGLTextureCache::instance()->remove(ctx, texture->id);
1428 void QGL2PaintEngineEx::drawStaticTextItem(QStaticTextItem *textItem)
1430 Q_D(QGL2PaintEngineEx);
1434 QPainterState *s = state();
1435 float det = s->matrix.determinant();
1437 // don't try to cache huge fonts or vastly transformed fonts
1438 QFontEngine *fontEngine = textItem->fontEngine();
1439 const qreal pixelSize = fontEngine->fontDef.pixelSize;
1440 if (shouldDrawCachedGlyphs(pixelSize, s->matrix) || det < 0.25f || det > 4.f) {
1441 QFontEngineGlyphCache::Type glyphType = fontEngine->glyphFormat >= 0
1442 ? QFontEngineGlyphCache::Type(textItem->fontEngine()->glyphFormat)
1443 : d->glyphCacheType;
1444 if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1445 if (d->device->alphaRequested() || s->matrix.type() > QTransform::TxTranslate
1446 || (s->composition_mode != QPainter::CompositionMode_Source
1447 && s->composition_mode != QPainter::CompositionMode_SourceOver))
1449 glyphType = QFontEngineGlyphCache::Raster_A8;
1453 d->drawCachedGlyphs(glyphType, textItem);
1455 QPaintEngineEx::drawStaticTextItem(textItem);
1459 bool QGL2PaintEngineEx::drawTexture(const QRectF &dest, GLuint textureId, const QSize &size, const QRectF &src)
1461 Q_D(QGL2PaintEngineEx);
1462 if (!d->shaderManager)
1466 d->transferMode(ImageDrawingMode);
1468 #ifndef QT_OPENGL_ES_2
1469 QGLContext *ctx = d->ctx;
1471 glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1472 glBindTexture(GL_TEXTURE_2D, textureId);
1474 QGLRect srcRect(src.left(), src.bottom(), src.right(), src.top());
1476 d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1477 state()->renderHints & QPainter::SmoothPixmapTransform, textureId);
1478 d->drawTexture(dest, srcRect, size, false);
1482 void QGL2PaintEngineEx::drawTextItem(const QPointF &p, const QTextItem &textItem)
1484 Q_D(QGL2PaintEngineEx);
1487 QOpenGL2PaintEngineState *s = state();
1489 const QTextItemInt &ti = static_cast<const QTextItemInt &>(textItem);
1491 QTransform::TransformationType txtype = s->matrix.type();
1493 float det = s->matrix.determinant();
1494 bool drawCached = txtype < QTransform::TxProject;
1496 // don't try to cache huge fonts or vastly transformed fonts
1497 const qreal pixelSize = ti.fontEngine->fontDef.pixelSize;
1498 if (shouldDrawCachedGlyphs(pixelSize, s->matrix) || det < 0.25f || det > 4.f)
1501 QFontEngineGlyphCache::Type glyphType = ti.fontEngine->glyphFormat >= 0
1502 ? QFontEngineGlyphCache::Type(ti.fontEngine->glyphFormat)
1503 : d->glyphCacheType;
1506 if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1507 if (d->device->alphaRequested() || txtype > QTransform::TxTranslate
1508 || (state()->composition_mode != QPainter::CompositionMode_Source
1509 && state()->composition_mode != QPainter::CompositionMode_SourceOver))
1511 glyphType = QFontEngineGlyphCache::Raster_A8;
1516 QVarLengthArray<QFixedPoint> positions;
1517 QVarLengthArray<glyph_t> glyphs;
1518 QTransform matrix = QTransform::fromTranslate(p.x(), p.y());
1519 ti.fontEngine->getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions);
1522 QStaticTextItem staticTextItem;
1523 staticTextItem.chars = const_cast<QChar *>(ti.chars);
1524 staticTextItem.setFontEngine(ti.fontEngine);
1525 staticTextItem.glyphs = glyphs.data();
1526 staticTextItem.numChars = ti.num_chars;
1527 staticTextItem.numGlyphs = glyphs.size();
1528 staticTextItem.glyphPositions = positions.data();
1530 d->drawCachedGlyphs(glyphType, &staticTextItem);
1535 QPaintEngineEx::drawTextItem(p, ti);
1540 class QOpenGLStaticTextUserData: public QStaticTextUserData
1543 QOpenGLStaticTextUserData()
1544 : QStaticTextUserData(OpenGLUserData), cacheSize(0, 0), cacheSerialNumber(0)
1548 ~QOpenGLStaticTextUserData()
1553 QGL2PEXVertexArray vertexCoordinateArray;
1554 QGL2PEXVertexArray textureCoordinateArray;
1555 QFontEngineGlyphCache::Type glyphType;
1556 int cacheSerialNumber;
1561 #if defined(Q_WS_WIN)
1562 static bool fontSmoothingApproximately(qreal target)
1564 extern Q_GUI_EXPORT qreal qt_fontsmoothing_gamma; // qapplication_win.cpp
1565 return (qAbs(qt_fontsmoothing_gamma - target) < 0.2);
1569 // #define QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO
1571 void QGL2PaintEngineExPrivate::drawCachedGlyphs(QFontEngineGlyphCache::Type glyphType,
1572 QStaticTextItem *staticTextItem)
1574 Q_Q(QGL2PaintEngineEx);
1576 QOpenGL2PaintEngineState *s = q->state();
1578 void *cacheKey = const_cast<QGLContext *>(QGLContextPrivate::contextGroup(ctx)->context());
1579 bool recreateVertexArrays = false;
1581 QGLTextureGlyphCache *cache =
1582 (QGLTextureGlyphCache *) staticTextItem->fontEngine()->glyphCache(cacheKey, glyphType, QTransform());
1583 if (!cache || cache->cacheType() != glyphType || cache->context() == 0) {
1584 cache = new QGLTextureGlyphCache(ctx, glyphType, QTransform());
1585 staticTextItem->fontEngine()->setGlyphCache(cacheKey, cache);
1586 cache->insert(ctx, cache);
1587 recreateVertexArrays = true;
1590 if (staticTextItem->userDataNeedsUpdate) {
1591 recreateVertexArrays = true;
1592 } else if (staticTextItem->userData() == 0) {
1593 recreateVertexArrays = true;
1594 } else if (staticTextItem->userData()->type != QStaticTextUserData::OpenGLUserData) {
1595 recreateVertexArrays = true;
1597 QOpenGLStaticTextUserData *userData = static_cast<QOpenGLStaticTextUserData *>(staticTextItem->userData());
1598 if (userData->glyphType != glyphType) {
1599 recreateVertexArrays = true;
1600 } else if (userData->cacheSerialNumber != cache->serialNumber()) {
1601 recreateVertexArrays = true;
1605 // We only need to update the cache with new glyphs if we are actually going to recreate the vertex arrays.
1606 // If the cache size has changed, we do need to regenerate the vertices, but we don't need to repopulate the
1607 // cache so this text is performed before we test if the cache size has changed.
1608 if (recreateVertexArrays) {
1609 cache->setPaintEnginePrivate(this);
1610 if (!cache->populate(staticTextItem->fontEngine(), staticTextItem->numGlyphs,
1611 staticTextItem->glyphs, staticTextItem->glyphPositions)) {
1612 // No space for glyphs in cache. We need to reset it and try again.
1614 cache->populate(staticTextItem->fontEngine(), staticTextItem->numGlyphs,
1615 staticTextItem->glyphs, staticTextItem->glyphPositions);
1617 cache->fillInPendingGlyphs();
1620 if (cache->width() == 0 || cache->height() == 0)
1623 transferMode(TextDrawingMode);
1625 int margin = cache->glyphMargin();
1627 GLfloat dx = 1.0 / cache->width();
1628 GLfloat dy = 1.0 / cache->height();
1630 // Use global arrays by default
1631 QGL2PEXVertexArray *vertexCoordinates = &vertexCoordinateArray;
1632 QGL2PEXVertexArray *textureCoordinates = &textureCoordinateArray;
1634 if (staticTextItem->useBackendOptimizations) {
1635 QOpenGLStaticTextUserData *userData = 0;
1637 if (staticTextItem->userData() == 0
1638 || staticTextItem->userData()->type != QStaticTextUserData::OpenGLUserData) {
1640 userData = new QOpenGLStaticTextUserData();
1641 staticTextItem->setUserData(userData);
1644 userData = static_cast<QOpenGLStaticTextUserData*>(staticTextItem->userData());
1647 userData->glyphType = glyphType;
1648 userData->cacheSerialNumber = cache->serialNumber();
1650 // Use cache if backend optimizations is turned on
1651 vertexCoordinates = &userData->vertexCoordinateArray;
1652 textureCoordinates = &userData->textureCoordinateArray;
1654 QSize size(cache->width(), cache->height());
1655 if (userData->cacheSize != size) {
1656 recreateVertexArrays = true;
1657 userData->cacheSize = size;
1661 if (recreateVertexArrays) {
1662 vertexCoordinates->clear();
1663 textureCoordinates->clear();
1665 bool supportsSubPixelPositions = staticTextItem->fontEngine()->supportsSubPixelPositions();
1666 for (int i=0; i<staticTextItem->numGlyphs; ++i) {
1667 QFixed subPixelPosition;
1668 if (supportsSubPixelPositions)
1669 subPixelPosition = cache->subPixelPositionForX(staticTextItem->glyphPositions[i].x);
1671 QTextureGlyphCache::GlyphAndSubPixelPosition glyph(staticTextItem->glyphs[i], subPixelPosition);
1673 const QTextureGlyphCache::Coord &c = cache->coords[glyph];
1677 int x = qFloor(staticTextItem->glyphPositions[i].x) + c.baseLineX - margin;
1678 int y = qFloor(staticTextItem->glyphPositions[i].y) - c.baseLineY - margin;
1680 vertexCoordinates->addQuad(QRectF(x, y, c.w, c.h));
1681 textureCoordinates->addQuad(QRectF(c.x*dx, c.y*dy, c.w * dx, c.h * dy));
1684 staticTextItem->userDataNeedsUpdate = false;
1687 int numGlyphs = vertexCoordinates->vertexCount() / 4;
1691 if (elementIndices.size() < numGlyphs*6) {
1692 Q_ASSERT(elementIndices.size() % 6 == 0);
1693 int j = elementIndices.size() / 6 * 4;
1694 while (j < numGlyphs*4) {
1695 elementIndices.append(j + 0);
1696 elementIndices.append(j + 0);
1697 elementIndices.append(j + 1);
1698 elementIndices.append(j + 2);
1699 elementIndices.append(j + 3);
1700 elementIndices.append(j + 3);
1705 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1706 if (elementIndicesVBOId == 0)
1707 glGenBuffers(1, &elementIndicesVBOId);
1709 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
1710 glBufferData(GL_ELEMENT_ARRAY_BUFFER, elementIndices.size() * sizeof(GLushort),
1711 elementIndices.constData(), GL_STATIC_DRAW);
1714 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1715 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
1719 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)vertexCoordinates->data());
1720 setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, (GLfloat*)textureCoordinates->data());
1722 if (!snapToPixelGrid) {
1723 snapToPixelGrid = true;
1727 QBrush pensBrush = q->state()->pen.brush();
1728 setBrush(pensBrush);
1730 if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1732 // Subpixel antialiasing without gamma correction
1734 QPainter::CompositionMode compMode = q->state()->composition_mode;
1735 Q_ASSERT(compMode == QPainter::CompositionMode_Source
1736 || compMode == QPainter::CompositionMode_SourceOver);
1738 shaderManager->setMaskType(QGLEngineShaderManager::SubPixelMaskPass1);
1740 if (pensBrush.style() == Qt::SolidPattern) {
1741 // Solid patterns can get away with only one pass.
1742 QColor c = pensBrush.color();
1743 qreal oldOpacity = q->state()->opacity;
1744 if (compMode == QPainter::CompositionMode_Source) {
1745 c = qt_premultiplyColor(c, q->state()->opacity);
1746 q->state()->opacity = 1;
1747 opacityUniformDirty = true;
1750 compositionModeDirty = false; // I can handle this myself, thank you very much
1751 prepareForDraw(false); // Text always causes src pixels to be transparent
1753 // prepareForDraw() have set the opacity on the current shader, so the opacity state can now be reset.
1754 if (compMode == QPainter::CompositionMode_Source) {
1755 q->state()->opacity = oldOpacity;
1756 opacityUniformDirty = true;
1760 glBlendFunc(GL_CONSTANT_COLOR, GL_ONE_MINUS_SRC_COLOR);
1761 glBlendColor(c.redF(), c.greenF(), c.blueF(), c.alphaF());
1763 // Other brush styles need two passes.
1765 qreal oldOpacity = q->state()->opacity;
1766 if (compMode == QPainter::CompositionMode_Source) {
1767 q->state()->opacity = 1;
1768 opacityUniformDirty = true;
1769 pensBrush = Qt::white;
1770 setBrush(pensBrush);
1773 compositionModeDirty = false; // I can handle this myself, thank you very much
1774 prepareForDraw(false); // Text always causes src pixels to be transparent
1776 glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR);
1778 glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
1779 glBindTexture(GL_TEXTURE_2D, cache->texture());
1780 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, false);
1782 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1783 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
1785 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, elementIndices.data());
1788 shaderManager->setMaskType(QGLEngineShaderManager::SubPixelMaskPass2);
1790 if (compMode == QPainter::CompositionMode_Source) {
1791 q->state()->opacity = oldOpacity;
1792 opacityUniformDirty = true;
1793 pensBrush = q->state()->pen.brush();
1794 setBrush(pensBrush);
1797 compositionModeDirty = false;
1798 prepareForDraw(false); // Text always causes src pixels to be transparent
1800 glBlendFunc(GL_ONE, GL_ONE);
1802 compositionModeDirty = true;
1804 // Greyscale/mono glyphs
1806 shaderManager->setMaskType(QGLEngineShaderManager::PixelMask);
1807 prepareForDraw(false); // Text always causes src pixels to be transparent
1810 QGLTextureGlyphCache::FilterMode filterMode = (s->matrix.type() > QTransform::TxTranslate)?QGLTextureGlyphCache::Linear:QGLTextureGlyphCache::Nearest;
1811 if (lastMaskTextureUsed != cache->texture() || cache->filterMode() != filterMode) {
1813 glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
1814 if (lastMaskTextureUsed != cache->texture()) {
1815 glBindTexture(GL_TEXTURE_2D, cache->texture());
1816 lastMaskTextureUsed = cache->texture();
1819 if (cache->filterMode() != filterMode) {
1820 if (filterMode == QGLTextureGlyphCache::Linear) {
1821 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1822 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1824 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1825 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1827 cache->setFilterMode(filterMode);
1831 bool srgbFrameBufferEnabled = false;
1832 if (ctx->d_ptr->extension_flags & QGLExtensions::SRGBFrameBuffer) {
1833 #if defined(Q_WS_MAC)
1834 if (glyphType == QFontEngineGlyphCache::Raster_RGBMask)
1835 #elif defined(Q_WS_WIN)
1836 if (glyphType != QFontEngineGlyphCache::Raster_RGBMask || fontSmoothingApproximately(2.1))
1841 glEnable(FRAMEBUFFER_SRGB_EXT);
1842 srgbFrameBufferEnabled = true;
1846 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1847 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
1848 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1850 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, elementIndices.data());
1853 if (srgbFrameBufferEnabled)
1854 glDisable(FRAMEBUFFER_SRGB_EXT);
1858 void QGL2PaintEngineEx::drawPixmapFragments(const QPainter::PixmapFragment *fragments, int fragmentCount, const QPixmap &pixmap,
1859 QPainter::PixmapFragmentHints hints)
1861 Q_D(QGL2PaintEngineEx);
1862 // Use fallback for extended composition modes.
1863 if (state()->composition_mode > QPainter::CompositionMode_Plus) {
1864 QPaintEngineEx::drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
1869 int max_texture_size = d->ctx->d_func()->maxTextureSize();
1870 if (pixmap.width() > max_texture_size || pixmap.height() > max_texture_size) {
1871 QPixmap scaled = pixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1872 d->drawPixmapFragments(fragments, fragmentCount, scaled, hints);
1874 d->drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
1879 void QGL2PaintEngineExPrivate::drawPixmapFragments(const QPainter::PixmapFragment *fragments,
1880 int fragmentCount, const QPixmap &pixmap,
1881 QPainter::PixmapFragmentHints hints)
1883 GLfloat dx = 1.0f / pixmap.size().width();
1884 GLfloat dy = 1.0f / pixmap.size().height();
1886 vertexCoordinateArray.clear();
1887 textureCoordinateArray.clear();
1888 opacityArray.reset();
1890 if (snapToPixelGrid) {
1891 snapToPixelGrid = false;
1895 bool allOpaque = true;
1897 for (int i = 0; i < fragmentCount; ++i) {
1900 if (fragments[i].rotation != 0) {
1901 s = qFastSin(fragments[i].rotation * Q_PI / 180);
1902 c = qFastCos(fragments[i].rotation * Q_PI / 180);
1905 qreal right = 0.5 * fragments[i].scaleX * fragments[i].width;
1906 qreal bottom = 0.5 * fragments[i].scaleY * fragments[i].height;
1907 QGLPoint bottomRight(right * c - bottom * s, right * s + bottom * c);
1908 QGLPoint bottomLeft(-right * c - bottom * s, -right * s + bottom * c);
1910 vertexCoordinateArray.addVertex(bottomRight.x + fragments[i].x, bottomRight.y + fragments[i].y);
1911 vertexCoordinateArray.addVertex(-bottomLeft.x + fragments[i].x, -bottomLeft.y + fragments[i].y);
1912 vertexCoordinateArray.addVertex(-bottomRight.x + fragments[i].x, -bottomRight.y + fragments[i].y);
1913 vertexCoordinateArray.addVertex(-bottomRight.x + fragments[i].x, -bottomRight.y + fragments[i].y);
1914 vertexCoordinateArray.addVertex(bottomLeft.x + fragments[i].x, bottomLeft.y + fragments[i].y);
1915 vertexCoordinateArray.addVertex(bottomRight.x + fragments[i].x, bottomRight.y + fragments[i].y);
1917 QGLRect src(fragments[i].sourceLeft * dx, fragments[i].sourceTop * dy,
1918 (fragments[i].sourceLeft + fragments[i].width) * dx,
1919 (fragments[i].sourceTop + fragments[i].height) * dy);
1921 textureCoordinateArray.addVertex(src.right, src.bottom);
1922 textureCoordinateArray.addVertex(src.right, src.top);
1923 textureCoordinateArray.addVertex(src.left, src.top);
1924 textureCoordinateArray.addVertex(src.left, src.top);
1925 textureCoordinateArray.addVertex(src.left, src.bottom);
1926 textureCoordinateArray.addVertex(src.right, src.bottom);
1928 qreal opacity = fragments[i].opacity * q->state()->opacity;
1929 opacityArray << opacity << opacity << opacity << opacity << opacity << opacity;
1930 allOpaque &= (opacity >= 0.99f);
1933 glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1934 QGLTexture *texture = ctx->d_func()->bindTexture(pixmap, GL_TEXTURE_2D, GL_RGBA,
1935 QGLContext::InternalBindOption
1936 | QGLContext::CanFlipNativePixmapBindOption);
1938 if (texture->options & QGLContext::InvertedYBindOption) {
1939 // Flip texture y-coordinate.
1940 QGLPoint *data = textureCoordinateArray.data();
1941 for (int i = 0; i < 6 * fragmentCount; ++i)
1942 data[i].y = 1 - data[i].y;
1945 transferMode(ImageArrayDrawingMode);
1947 bool isBitmap = pixmap.isQBitmap();
1948 bool isOpaque = !isBitmap && (!pixmap.hasAlpha() || (hints & QPainter::OpaqueHint)) && allOpaque;
1950 updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1951 q->state()->renderHints & QPainter::SmoothPixmapTransform, texture->id);
1953 // Setup for texture drawing
1954 currentBrush = noBrush;
1955 shaderManager->setSrcPixelType(isBitmap ? QGLEngineShaderManager::PatternSrc
1956 : QGLEngineShaderManager::ImageSrc);
1957 if (prepareForDraw(isOpaque))
1958 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::ImageTexture), QT_IMAGE_TEXTURE_UNIT);
1961 QColor col = qt_premultiplyColor(q->state()->pen.color(), (GLfloat)q->state()->opacity);
1962 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::PatternColor), col);
1965 glDrawArrays(GL_TRIANGLES, 0, 6 * fragmentCount);
1968 bool QGL2PaintEngineEx::begin(QPaintDevice *pdev)
1970 Q_D(QGL2PaintEngineEx);
1972 // qDebug("QGL2PaintEngineEx::begin()");
1973 if (pdev->devType() == QInternal::OpenGL)
1974 d->device = static_cast<QGLPaintDevice*>(pdev);
1976 d->device = QGLPaintDevice::getDevice(pdev);
1981 d->ctx = d->device->context();
1982 d->ctx->d_ptr->active_engine = this;
1984 const QSize sz = d->device->size();
1985 d->width = sz.width();
1986 d->height = sz.height();
1987 d->mode = BrushDrawingMode;
1988 d->brushTextureDirty = true;
1989 d->brushUniformsDirty = true;
1990 d->matrixUniformDirty = true;
1991 d->matrixDirty = true;
1992 d->compositionModeDirty = true;
1993 d->opacityUniformDirty = true;
1994 d->needsSync = true;
1995 d->useSystemClip = !systemClip().isEmpty();
1996 d->currentBrush = QBrush();
1998 d->dirtyStencilRegion = QRect(0, 0, d->width, d->height);
1999 d->stencilClean = true;
2001 // Calling begin paint should make the correct context current. So, any
2002 // code which calls into GL or otherwise needs a current context *must*
2003 // go after beginPaint:
2004 d->device->beginPaint();
2006 #if !defined(QT_OPENGL_ES_2)
2007 bool success = qt_resolve_version_2_0_functions(d->ctx)
2008 && qt_resolve_buffer_extensions(d->ctx);
2013 d->shaderManager = new QGLEngineShaderManager(d->ctx);
2015 glDisable(GL_STENCIL_TEST);
2016 glDisable(GL_DEPTH_TEST);
2017 glDisable(GL_SCISSOR_TEST);
2019 #if !defined(QT_OPENGL_ES_2)
2020 glDisable(GL_MULTISAMPLE);
2023 d->glyphCacheType = QFontEngineGlyphCache::Raster_A8;
2025 #if !defined(QT_OPENGL_ES_2)
2026 #if defined(Q_WS_WIN)
2027 if (qt_cleartype_enabled
2028 && (fontSmoothingApproximately(1.0) || fontSmoothingApproximately(2.1)))
2030 #if defined(Q_WS_MAC)
2031 if (qt_applefontsmoothing_enabled)
2033 d->glyphCacheType = QFontEngineGlyphCache::Raster_RGBMask;
2036 #if defined(QT_OPENGL_ES_2)
2037 // OpenGL ES can't switch MSAA off, so if the gl paint device is
2038 // multisampled, it's always multisampled.
2039 d->multisamplingAlwaysEnabled = d->device->format().sampleBuffers();
2041 d->multisamplingAlwaysEnabled = false;
2047 bool QGL2PaintEngineEx::end()
2049 Q_D(QGL2PaintEngineEx);
2050 QGLContext *ctx = d->ctx;
2053 d->transferMode(BrushDrawingMode);
2054 d->device->endPaint();
2056 #if defined(Q_WS_X11)
2057 // On some (probably all) drivers, deleting an X pixmap which has been bound to a texture
2058 // before calling glFinish/swapBuffers renders garbage. Presumably this is because X deletes
2059 // the pixmap behind the driver's back before it's had a chance to use it. To fix this, we
2060 // reference all QPixmaps which have been bound to stop them being deleted and only deref
2061 // them here, after swapBuffers, where they can be safely deleted.
2062 ctx->d_func()->boundPixmaps.clear();
2064 d->ctx->d_ptr->active_engine = 0;
2068 delete d->shaderManager;
2069 d->shaderManager = 0;
2070 d->currentBrush = QBrush();
2072 #ifdef QT_OPENGL_CACHE_AS_VBOS
2073 if (!d->unusedVBOSToClean.isEmpty()) {
2074 glDeleteBuffers(d->unusedVBOSToClean.size(), d->unusedVBOSToClean.constData());
2075 d->unusedVBOSToClean.clear();
2077 if (!d->unusedIBOSToClean.isEmpty()) {
2078 glDeleteBuffers(d->unusedIBOSToClean.size(), d->unusedIBOSToClean.constData());
2079 d->unusedIBOSToClean.clear();
2086 void QGL2PaintEngineEx::ensureActive()
2088 Q_D(QGL2PaintEngineEx);
2089 QGLContext *ctx = d->ctx;
2091 if (isActive() && ctx->d_ptr->active_engine != this) {
2092 ctx->d_ptr->active_engine = this;
2093 d->needsSync = true;
2096 d->device->ensureActiveTarget();
2099 d->transferMode(BrushDrawingMode);
2100 glViewport(0, 0, d->width, d->height);
2101 d->needsSync = false;
2102 d->lastMaskTextureUsed = 0;
2103 d->shaderManager->setDirty();
2104 d->ctx->d_func()->syncGlState();
2105 for (int i = 0; i < 3; ++i)
2106 d->vertexAttribPointers[i] = (GLfloat*)-1; // Assume the pointers are clobbered
2111 void QGL2PaintEngineExPrivate::updateClipScissorTest()
2113 Q_Q(QGL2PaintEngineEx);
2114 if (q->state()->clipTestEnabled) {
2115 glEnable(GL_STENCIL_TEST);
2116 glStencilFunc(GL_LEQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
2118 glDisable(GL_STENCIL_TEST);
2119 glStencilFunc(GL_ALWAYS, 0, 0xff);
2122 #ifdef QT_GL_NO_SCISSOR_TEST
2123 currentScissorBounds = QRect(0, 0, width, height);
2125 QRect bounds = q->state()->rectangleClip;
2126 if (!q->state()->clipEnabled) {
2128 bounds = systemClip.boundingRect();
2130 bounds = QRect(0, 0, width, height);
2133 bounds = bounds.intersected(systemClip.boundingRect());
2135 bounds = bounds.intersected(QRect(0, 0, width, height));
2138 currentScissorBounds = bounds;
2140 if (bounds == QRect(0, 0, width, height)) {
2141 glDisable(GL_SCISSOR_TEST);
2143 glEnable(GL_SCISSOR_TEST);
2149 void QGL2PaintEngineExPrivate::setScissor(const QRect &rect)
2151 const int left = rect.left();
2152 const int width = rect.width();
2153 int bottom = height - (rect.top() + rect.height());
2154 if (device->isFlipped()) {
2155 bottom = rect.top();
2157 const int height = rect.height();
2159 glScissor(left, bottom, width, height);
2162 void QGL2PaintEngineEx::clipEnabledChanged()
2164 Q_D(QGL2PaintEngineEx);
2166 state()->clipChanged = true;
2168 if (painter()->hasClipping())
2169 d->regenerateClip();
2171 d->systemStateChanged();
2174 void QGL2PaintEngineExPrivate::clearClip(uint value)
2176 dirtyStencilRegion -= currentScissorBounds;
2178 glStencilMask(0xff);
2179 glClearStencil(value);
2180 glClear(GL_STENCIL_BUFFER_BIT);
2183 q->state()->needsClipBufferClear = false;
2186 void QGL2PaintEngineExPrivate::writeClip(const QVectorPath &path, uint value)
2188 transferMode(BrushDrawingMode);
2190 if (snapToPixelGrid) {
2191 snapToPixelGrid = false;
2198 stencilClean = false;
2200 const bool singlePass = !path.hasWindingFill()
2201 && (((q->state()->currentClip == maxClip - 1) && q->state()->clipTestEnabled)
2202 || q->state()->needsClipBufferClear);
2203 const uint referenceClipValue = q->state()->needsClipBufferClear ? 1 : q->state()->currentClip;
2205 if (q->state()->needsClipBufferClear)
2208 if (path.isEmpty()) {
2209 glEnable(GL_STENCIL_TEST);
2210 glStencilFunc(GL_LEQUAL, value, ~GL_STENCIL_HIGH_BIT);
2214 if (q->state()->clipTestEnabled)
2215 glStencilFunc(GL_LEQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
2217 glStencilFunc(GL_ALWAYS, 0, 0xff);
2219 vertexCoordinateArray.clear();
2220 vertexCoordinateArray.addPath(path, inverseScale, false);
2223 fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill());
2225 glColorMask(false, false, false, false);
2226 glEnable(GL_STENCIL_TEST);
2230 // Under these conditions we can set the new stencil value in a single
2231 // pass, by using the current value and the "new value" as the toggles
2233 glStencilFunc(GL_LEQUAL, referenceClipValue, ~GL_STENCIL_HIGH_BIT);
2234 glStencilOp(GL_KEEP, GL_INVERT, GL_INVERT);
2235 glStencilMask(value ^ referenceClipValue);
2237 drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN);
2239 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
2240 glStencilMask(0xff);
2242 if (!q->state()->clipTestEnabled && path.hasWindingFill()) {
2243 // Pass when any clip bit is set, set high bit
2244 glStencilFunc(GL_NOTEQUAL, GL_STENCIL_HIGH_BIT, ~GL_STENCIL_HIGH_BIT);
2245 composite(vertexCoordinateArray.boundingRect());
2248 // Pass when high bit is set, replace stencil value with new clip value
2249 glStencilFunc(GL_NOTEQUAL, value, GL_STENCIL_HIGH_BIT);
2251 composite(vertexCoordinateArray.boundingRect());
2254 glStencilFunc(GL_LEQUAL, value, ~GL_STENCIL_HIGH_BIT);
2257 glColorMask(true, true, true, true);
2260 void QGL2PaintEngineEx::clip(const QVectorPath &path, Qt::ClipOperation op)
2262 // qDebug("QGL2PaintEngineEx::clip()");
2263 Q_D(QGL2PaintEngineEx);
2265 state()->clipChanged = true;
2269 if (op == Qt::ReplaceClip) {
2270 op = Qt::IntersectClip;
2271 if (d->hasClipOperations()) {
2272 d->systemStateChanged();
2273 state()->canRestoreClip = false;
2277 #ifndef QT_GL_NO_SCISSOR_TEST
2278 if (!path.isEmpty() && op == Qt::IntersectClip && (path.shape() == QVectorPath::RectangleHint)) {
2279 const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
2280 QRectF rect(points[0], points[2]);
2282 if (state()->matrix.type() <= QTransform::TxScale
2283 || (state()->matrix.type() == QTransform::TxRotate
2284 && qFuzzyIsNull(state()->matrix.m11())
2285 && qFuzzyIsNull(state()->matrix.m22())))
2287 state()->rectangleClip = state()->rectangleClip.intersected(state()->matrix.mapRect(rect).toRect());
2288 d->updateClipScissorTest();
2294 const QRect pathRect = state()->matrix.mapRect(path.controlPointRect()).toAlignedRect();
2298 if (d->useSystemClip) {
2299 state()->clipTestEnabled = true;
2300 state()->currentClip = 1;
2302 state()->clipTestEnabled = false;
2304 state()->rectangleClip = QRect(0, 0, d->width, d->height);
2305 state()->canRestoreClip = false;
2306 d->updateClipScissorTest();
2308 case Qt::IntersectClip:
2309 state()->rectangleClip = state()->rectangleClip.intersected(pathRect);
2310 d->updateClipScissorTest();
2311 d->resetClipIfNeeded();
2313 d->writeClip(path, d->maxClip);
2314 state()->currentClip = d->maxClip;
2315 state()->clipTestEnabled = true;
2322 void QGL2PaintEngineExPrivate::regenerateClip()
2324 systemStateChanged();
2325 replayClipOperations();
2328 void QGL2PaintEngineExPrivate::systemStateChanged()
2330 Q_Q(QGL2PaintEngineEx);
2332 q->state()->clipChanged = true;
2334 if (systemClip.isEmpty()) {
2335 useSystemClip = false;
2337 if (q->paintDevice()->devType() == QInternal::Widget && currentClipDevice) {
2338 QWidgetPrivate *widgetPrivate = qt_widget_private(static_cast<QWidget *>(currentClipDevice)->window());
2339 useSystemClip = widgetPrivate->extra && widgetPrivate->extra->inRenderWithPainter;
2341 useSystemClip = true;
2345 q->state()->clipTestEnabled = false;
2346 q->state()->needsClipBufferClear = true;
2348 q->state()->currentClip = 1;
2351 q->state()->rectangleClip = useSystemClip ? systemClip.boundingRect() : QRect(0, 0, width, height);
2352 updateClipScissorTest();
2354 if (systemClip.rectCount() == 1) {
2355 if (systemClip.boundingRect() == QRect(0, 0, width, height))
2356 useSystemClip = false;
2357 #ifndef QT_GL_NO_SCISSOR_TEST
2358 // scissoring takes care of the system clip
2363 if (useSystemClip) {
2367 path.addRegion(systemClip);
2369 q->state()->currentClip = 0;
2370 writeClip(qtVectorPathForPath(q->state()->matrix.inverted().map(path)), 1);
2371 q->state()->currentClip = 1;
2372 q->state()->clipTestEnabled = true;
2376 void QGL2PaintEngineEx::setState(QPainterState *new_state)
2378 // qDebug("QGL2PaintEngineEx::setState()");
2380 Q_D(QGL2PaintEngineEx);
2382 QOpenGL2PaintEngineState *s = static_cast<QOpenGL2PaintEngineState *>(new_state);
2383 QOpenGL2PaintEngineState *old_state = state();
2385 QPaintEngineEx::setState(s);
2388 // Newly created state object. The call to setState()
2389 // will either be followed by a call to begin(), or we are
2390 // setting the state as part of a save().
2395 // Setting the state as part of a restore().
2397 if (old_state == s || old_state->renderHintsChanged)
2398 renderHintsChanged();
2400 if (old_state == s || old_state->matrixChanged)
2401 d->matrixDirty = true;
2403 if (old_state == s || old_state->compositionModeChanged)
2404 d->compositionModeDirty = true;
2406 if (old_state == s || old_state->opacityChanged)
2407 d->opacityUniformDirty = true;
2409 if (old_state == s || old_state->clipChanged) {
2410 if (old_state && old_state != s && old_state->canRestoreClip) {
2411 d->updateClipScissorTest();
2412 glDepthFunc(GL_LEQUAL);
2414 d->regenerateClip();
2419 QPainterState *QGL2PaintEngineEx::createState(QPainterState *orig) const
2422 const_cast<QGL2PaintEngineEx *>(this)->ensureActive();
2424 QOpenGL2PaintEngineState *s;
2426 s = new QOpenGL2PaintEngineState();
2428 s = new QOpenGL2PaintEngineState(*static_cast<QOpenGL2PaintEngineState *>(orig));
2430 s->matrixChanged = false;
2431 s->compositionModeChanged = false;
2432 s->opacityChanged = false;
2433 s->renderHintsChanged = false;
2434 s->clipChanged = false;
2439 QOpenGL2PaintEngineState::QOpenGL2PaintEngineState(QOpenGL2PaintEngineState &other)
2440 : QPainterState(other)
2443 needsClipBufferClear = other.needsClipBufferClear;
2444 clipTestEnabled = other.clipTestEnabled;
2445 currentClip = other.currentClip;
2446 canRestoreClip = other.canRestoreClip;
2447 rectangleClip = other.rectangleClip;
2450 QOpenGL2PaintEngineState::QOpenGL2PaintEngineState()
2453 needsClipBufferClear = true;
2454 clipTestEnabled = false;
2455 canRestoreClip = true;
2458 QOpenGL2PaintEngineState::~QOpenGL2PaintEngineState()