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 <QtGui/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;
670 QVertexIndexVector::Type indexType;
673 void QGL2PaintEngineExPrivate::cleanupVectorPath(QPaintEngineEx *engine, void *data)
675 QGL2PEVectorPathCache *c = (QGL2PEVectorPathCache *) data;
676 #ifdef QT_OPENGL_CACHE_AS_VBOS
677 Q_ASSERT(engine->type() == QPaintEngine::OpenGL2);
678 static_cast<QGL2PaintEngineEx *>(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 QGL2PaintEngineExPrivate::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 QGLRect 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 QGL2PEVectorPathCache *cache;
716 bool updateCache = false;
719 cache = (QGL2PEVectorPathCache *) 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 QGL2PEVectorPathCache;
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 QGL2PEVectorPathCache *cache;
797 bool updateCache = false;
800 cache = (QGL2PEVectorPathCache *) 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 QGL2PEVectorPathCache;
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 glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint32) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
838 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 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->format().stencil()) {
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 (polys.indices.type() == QVertexIndexVector::UnsignedInt)
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 QGL2PaintEngineExPrivate::fillStencilWithVertexArray(const float *data,
945 const QGLRect &bounds,
946 StencilFillMode mode)
948 Q_ASSERT(count || stops);
950 // qDebug("QGL2PaintEngineExPrivate::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 glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_INCR_WRAP, GL_INCR_WRAP);
992 // Dec. for back-facing "holes"
993 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 QGL2PaintEngineExPrivate::resetClipIfNeeded()
1041 if (maxClip != (GL_STENCIL_HIGH_BIT - 1))
1044 Q_Q(QGL2PaintEngineEx);
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 QGLRect 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 QGL2PaintEngineExPrivate::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 QGLEngineShaderManager::OpacityMode opacityMode;
1096 if (mode == ImageArrayDrawingMode) {
1097 opacityMode = QGLEngineShaderManager::AttributeOpacity;
1099 opacityMode = stateHasOpacity ? QGLEngineShaderManager::UniformOpacity
1100 : QGLEngineShaderManager::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 = QGLEngineShaderManager::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 == QGLEngineShaderManager::UniformOpacity && opacityUniformDirty) {
1125 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::GlobalOpacity), (GLfloat)q->state()->opacity);
1126 opacityUniformDirty = false;
1129 if (matrixUniformDirty && shaderManager->hasComplexGeometry()) {
1130 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::Matrix),
1132 matrixUniformDirty = false;
1138 void QGL2PaintEngineExPrivate::composite(const QGLRect& 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 QGL2PaintEngineExPrivate::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 QGL2PaintEngineEx::QGL2PaintEngineEx()
1168 : QPaintEngineEx(*(new QGL2PaintEngineExPrivate(this)))
1172 QGL2PaintEngineEx::~QGL2PaintEngineEx()
1176 void QGL2PaintEngineEx::fill(const QVectorPath &path, const QBrush &brush)
1178 Q_D(QGL2PaintEngineEx);
1180 if (qbrush_style(brush) == Qt::NoBrush)
1187 Q_GUI_EXPORT bool qt_scaleForTransform(const QTransform &transform, qreal *scale); // qtransform.cpp
1190 void QGL2PaintEngineEx::stroke(const QVectorPath &path, const QPen &pen)
1192 Q_D(QGL2PaintEngineEx);
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 QGL2PaintEngineExPrivate::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, QGL2PaintEngineExPrivate::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 QGL2PaintEngineEx::penChanged() { }
1290 void QGL2PaintEngineEx::brushChanged() { }
1291 void QGL2PaintEngineEx::brushOriginChanged() { }
1293 void QGL2PaintEngineEx::opacityChanged()
1295 // qDebug("QGL2PaintEngineEx::opacityChanged()");
1296 Q_D(QGL2PaintEngineEx);
1297 state()->opacityChanged = true;
1299 Q_ASSERT(d->shaderManager);
1300 d->brushUniformsDirty = true;
1301 d->opacityUniformDirty = true;
1304 void QGL2PaintEngineEx::compositionModeChanged()
1306 // qDebug("QGL2PaintEngineEx::compositionModeChanged()");
1307 Q_D(QGL2PaintEngineEx);
1308 state()->compositionModeChanged = true;
1309 d->compositionModeDirty = true;
1312 void QGL2PaintEngineEx::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(QGL2PaintEngineEx);
1325 d->lastTextureUsed = GLuint(-1);
1326 d->brushTextureDirty = true;
1327 // qDebug("QGL2PaintEngineEx::renderHintsChanged() not implemented!");
1330 void QGL2PaintEngineEx::transformChanged()
1332 Q_D(QGL2PaintEngineEx);
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 QGL2PaintEngineEx::drawPixmap(const QRectF& dest, const QPixmap & pixmap, const QRectF & src)
1345 Q_D(QGL2PaintEngineEx);
1346 QGLContext *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 QGLContext::BindOptions bindOptions = QGLContext::InternalBindOption|QGLContext::CanFlipNativePixmapBindOption;
1363 #ifdef QGL_USE_TEXTURE_POOL
1364 bindOptions |= QGLContext::TemporarilyCachedBindOption;
1367 glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1368 QGLTexture *texture =
1369 ctx->d_func()->bindTexture(pixmap, GL_TEXTURE_2D, GL_RGBA, bindOptions);
1371 GLfloat top = texture->options & QGLContext::InvertedYBindOption ? (pixmap.height() - src.top()) : src.top();
1372 GLfloat bottom = texture->options & QGLContext::InvertedYBindOption ? (pixmap.height() - src.bottom()) : src.bottom();
1373 QGLRect srcRect(src.left(), top, src.right(), bottom);
1375 bool isBitmap = pixmap.isQBitmap();
1376 bool isOpaque = !isBitmap && !pixmap.hasAlpha();
1378 d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1379 state()->renderHints & QPainter::SmoothPixmapTransform, texture->id);
1380 d->drawTexture(dest, srcRect, pixmap.size(), isOpaque, isBitmap);
1382 if (texture->options&QGLContext::TemporarilyCachedBindOption) {
1383 // pixmap was temporarily cached as a QImage texture by pooling system
1384 // and should be destroyed immediately
1385 QGLTextureCache::instance()->remove(ctx, texture->id);
1389 void QGL2PaintEngineEx::drawImage(const QRectF& dest, const QImage& image, const QRectF& src,
1390 Qt::ImageConversionFlags)
1392 Q_D(QGL2PaintEngineEx);
1393 QGLContext *ctx = d->ctx;
1395 int max_texture_size = ctx->d_func()->maxTextureSize();
1396 if (image.width() > max_texture_size || image.height() > max_texture_size) {
1397 QImage scaled = image.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1399 const qreal sx = scaled.width() / qreal(image.width());
1400 const qreal sy = scaled.height() / qreal(image.height());
1402 drawImage(dest, scaled, scaleRect(src, sx, sy));
1407 d->transferMode(ImageDrawingMode);
1409 glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1411 QGLContext::BindOptions bindOptions = QGLContext::InternalBindOption;
1412 #ifdef QGL_USE_TEXTURE_POOL
1413 bindOptions |= QGLContext::TemporarilyCachedBindOption;
1416 QGLTexture *texture = ctx->d_func()->bindTexture(image, GL_TEXTURE_2D, GL_RGBA, bindOptions);
1417 GLuint id = texture->id;
1419 d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1420 state()->renderHints & QPainter::SmoothPixmapTransform, id);
1421 d->drawTexture(dest, src, image.size(), !image.hasAlphaChannel());
1423 if (texture->options&QGLContext::TemporarilyCachedBindOption) {
1424 // image was temporarily cached by texture pooling system
1425 // and should be destroyed immediately
1426 QGLTextureCache::instance()->remove(ctx, texture->id);
1430 void QGL2PaintEngineEx::drawStaticTextItem(QStaticTextItem *textItem)
1432 Q_D(QGL2PaintEngineEx);
1436 QPainterState *s = state();
1437 float det = s->matrix.determinant();
1439 // don't try to cache huge fonts or vastly transformed fonts
1440 QFontEngine *fontEngine = textItem->fontEngine();
1441 const qreal pixelSize = fontEngine->fontDef.pixelSize;
1442 if (shouldDrawCachedGlyphs(pixelSize, s->matrix) || det < 0.25f || det > 4.f) {
1443 QFontEngineGlyphCache::Type glyphType = fontEngine->glyphFormat >= 0
1444 ? QFontEngineGlyphCache::Type(textItem->fontEngine()->glyphFormat)
1445 : d->glyphCacheType;
1446 if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1447 if (d->device->alphaRequested() || s->matrix.type() > QTransform::TxTranslate
1448 || (s->composition_mode != QPainter::CompositionMode_Source
1449 && s->composition_mode != QPainter::CompositionMode_SourceOver))
1451 glyphType = QFontEngineGlyphCache::Raster_A8;
1455 d->drawCachedGlyphs(glyphType, textItem);
1457 QPaintEngineEx::drawStaticTextItem(textItem);
1461 bool QGL2PaintEngineEx::drawTexture(const QRectF &dest, GLuint textureId, const QSize &size, const QRectF &src)
1463 Q_D(QGL2PaintEngineEx);
1464 if (!d->shaderManager)
1468 d->transferMode(ImageDrawingMode);
1470 #ifndef QT_OPENGL_ES_2
1471 QGLContext *ctx = d->ctx;
1473 glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1474 glBindTexture(GL_TEXTURE_2D, textureId);
1476 QGLRect srcRect(src.left(), src.bottom(), src.right(), src.top());
1478 d->updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1479 state()->renderHints & QPainter::SmoothPixmapTransform, textureId);
1480 d->drawTexture(dest, srcRect, size, false);
1484 void QGL2PaintEngineEx::drawTextItem(const QPointF &p, const QTextItem &textItem)
1486 Q_D(QGL2PaintEngineEx);
1489 QOpenGL2PaintEngineState *s = state();
1491 const QTextItemInt &ti = static_cast<const QTextItemInt &>(textItem);
1493 QTransform::TransformationType txtype = s->matrix.type();
1495 float det = s->matrix.determinant();
1496 bool drawCached = txtype < QTransform::TxProject;
1498 // don't try to cache huge fonts or vastly transformed fonts
1499 const qreal pixelSize = ti.fontEngine->fontDef.pixelSize;
1500 if (shouldDrawCachedGlyphs(pixelSize, s->matrix) || det < 0.25f || det > 4.f)
1503 QFontEngineGlyphCache::Type glyphType = ti.fontEngine->glyphFormat >= 0
1504 ? QFontEngineGlyphCache::Type(ti.fontEngine->glyphFormat)
1505 : d->glyphCacheType;
1508 if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1509 if (d->device->alphaRequested() || txtype > QTransform::TxTranslate
1510 || (state()->composition_mode != QPainter::CompositionMode_Source
1511 && state()->composition_mode != QPainter::CompositionMode_SourceOver))
1513 glyphType = QFontEngineGlyphCache::Raster_A8;
1518 QVarLengthArray<QFixedPoint> positions;
1519 QVarLengthArray<glyph_t> glyphs;
1520 QTransform matrix = QTransform::fromTranslate(p.x(), p.y());
1521 ti.fontEngine->getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions);
1524 QStaticTextItem staticTextItem;
1525 staticTextItem.chars = const_cast<QChar *>(ti.chars);
1526 staticTextItem.setFontEngine(ti.fontEngine);
1527 staticTextItem.glyphs = glyphs.data();
1528 staticTextItem.numChars = ti.num_chars;
1529 staticTextItem.numGlyphs = glyphs.size();
1530 staticTextItem.glyphPositions = positions.data();
1532 d->drawCachedGlyphs(glyphType, &staticTextItem);
1537 QPaintEngineEx::drawTextItem(p, ti);
1542 class QOpenGLStaticTextUserData: public QStaticTextUserData
1545 QOpenGLStaticTextUserData()
1546 : QStaticTextUserData(OpenGLUserData), cacheSize(0, 0), cacheSerialNumber(0)
1550 ~QOpenGLStaticTextUserData()
1555 QGL2PEXVertexArray vertexCoordinateArray;
1556 QGL2PEXVertexArray textureCoordinateArray;
1557 QFontEngineGlyphCache::Type glyphType;
1558 int cacheSerialNumber;
1563 #if defined(Q_WS_WIN)
1564 static bool fontSmoothingApproximately(qreal target)
1566 extern Q_GUI_EXPORT qreal qt_fontsmoothing_gamma; // qapplication_win.cpp
1567 return (qAbs(qt_fontsmoothing_gamma - target) < 0.2);
1571 // #define QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO
1573 void QGL2PaintEngineExPrivate::drawCachedGlyphs(QFontEngineGlyphCache::Type glyphType,
1574 QStaticTextItem *staticTextItem)
1576 Q_Q(QGL2PaintEngineEx);
1578 QOpenGL2PaintEngineState *s = q->state();
1580 void *cacheKey = const_cast<QGLContext *>(QGLContextPrivate::contextGroup(ctx)->context());
1581 bool recreateVertexArrays = false;
1583 QGLTextureGlyphCache *cache =
1584 (QGLTextureGlyphCache *) staticTextItem->fontEngine()->glyphCache(cacheKey, glyphType, QTransform());
1585 if (!cache || cache->cacheType() != glyphType || cache->contextGroup() == 0) {
1586 cache = new QGLTextureGlyphCache(glyphType, QTransform());
1587 staticTextItem->fontEngine()->setGlyphCache(cacheKey, cache);
1588 recreateVertexArrays = true;
1591 if (staticTextItem->userDataNeedsUpdate) {
1592 recreateVertexArrays = true;
1593 } else if (staticTextItem->userData() == 0) {
1594 recreateVertexArrays = true;
1595 } else if (staticTextItem->userData()->type != QStaticTextUserData::OpenGLUserData) {
1596 recreateVertexArrays = true;
1598 QOpenGLStaticTextUserData *userData = static_cast<QOpenGLStaticTextUserData *>(staticTextItem->userData());
1599 if (userData->glyphType != glyphType) {
1600 recreateVertexArrays = true;
1601 } else if (userData->cacheSerialNumber != cache->serialNumber()) {
1602 recreateVertexArrays = true;
1606 // We only need to update the cache with new glyphs if we are actually going to recreate the vertex arrays.
1607 // If the cache size has changed, we do need to regenerate the vertices, but we don't need to repopulate the
1608 // cache so this text is performed before we test if the cache size has changed.
1609 if (recreateVertexArrays) {
1610 cache->setPaintEnginePrivate(this);
1611 if (!cache->populate(staticTextItem->fontEngine(), staticTextItem->numGlyphs,
1612 staticTextItem->glyphs, staticTextItem->glyphPositions)) {
1613 // No space for glyphs in cache. We need to reset it and try again.
1615 cache->populate(staticTextItem->fontEngine(), staticTextItem->numGlyphs,
1616 staticTextItem->glyphs, staticTextItem->glyphPositions);
1618 cache->fillInPendingGlyphs();
1621 if (cache->width() == 0 || cache->height() == 0)
1624 transferMode(TextDrawingMode);
1626 int margin = cache->glyphMargin();
1628 GLfloat dx = 1.0 / cache->width();
1629 GLfloat dy = 1.0 / cache->height();
1631 // Use global arrays by default
1632 QGL2PEXVertexArray *vertexCoordinates = &vertexCoordinateArray;
1633 QGL2PEXVertexArray *textureCoordinates = &textureCoordinateArray;
1635 if (staticTextItem->useBackendOptimizations) {
1636 QOpenGLStaticTextUserData *userData = 0;
1638 if (staticTextItem->userData() == 0
1639 || staticTextItem->userData()->type != QStaticTextUserData::OpenGLUserData) {
1641 userData = new QOpenGLStaticTextUserData();
1642 staticTextItem->setUserData(userData);
1645 userData = static_cast<QOpenGLStaticTextUserData*>(staticTextItem->userData());
1648 userData->glyphType = glyphType;
1649 userData->cacheSerialNumber = cache->serialNumber();
1651 // Use cache if backend optimizations is turned on
1652 vertexCoordinates = &userData->vertexCoordinateArray;
1653 textureCoordinates = &userData->textureCoordinateArray;
1655 QSize size(cache->width(), cache->height());
1656 if (userData->cacheSize != size) {
1657 recreateVertexArrays = true;
1658 userData->cacheSize = size;
1662 if (recreateVertexArrays) {
1663 vertexCoordinates->clear();
1664 textureCoordinates->clear();
1666 bool supportsSubPixelPositions = staticTextItem->fontEngine()->supportsSubPixelPositions();
1667 for (int i=0; i<staticTextItem->numGlyphs; ++i) {
1668 QFixed subPixelPosition;
1669 if (supportsSubPixelPositions)
1670 subPixelPosition = cache->subPixelPositionForX(staticTextItem->glyphPositions[i].x);
1672 QTextureGlyphCache::GlyphAndSubPixelPosition glyph(staticTextItem->glyphs[i], subPixelPosition);
1674 const QTextureGlyphCache::Coord &c = cache->coords[glyph];
1678 int x = qFloor(staticTextItem->glyphPositions[i].x) + c.baseLineX - margin;
1679 int y = qFloor(staticTextItem->glyphPositions[i].y) - c.baseLineY - margin;
1681 vertexCoordinates->addQuad(QRectF(x, y, c.w, c.h));
1682 textureCoordinates->addQuad(QRectF(c.x*dx, c.y*dy, c.w * dx, c.h * dy));
1685 staticTextItem->userDataNeedsUpdate = false;
1688 int numGlyphs = vertexCoordinates->vertexCount() / 4;
1692 if (elementIndices.size() < numGlyphs*6) {
1693 Q_ASSERT(elementIndices.size() % 6 == 0);
1694 int j = elementIndices.size() / 6 * 4;
1695 while (j < numGlyphs*4) {
1696 elementIndices.append(j + 0);
1697 elementIndices.append(j + 0);
1698 elementIndices.append(j + 1);
1699 elementIndices.append(j + 2);
1700 elementIndices.append(j + 3);
1701 elementIndices.append(j + 3);
1706 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1707 if (elementIndicesVBOId == 0)
1708 glGenBuffers(1, &elementIndicesVBOId);
1710 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
1711 glBufferData(GL_ELEMENT_ARRAY_BUFFER, elementIndices.size() * sizeof(GLushort),
1712 elementIndices.constData(), GL_STATIC_DRAW);
1715 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1716 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndicesVBOId);
1720 setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, (GLfloat*)vertexCoordinates->data());
1721 setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, (GLfloat*)textureCoordinates->data());
1723 if (!snapToPixelGrid) {
1724 snapToPixelGrid = true;
1728 QBrush pensBrush = q->state()->pen.brush();
1729 setBrush(pensBrush);
1731 if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) {
1733 // Subpixel antialiasing without gamma correction
1735 QPainter::CompositionMode compMode = q->state()->composition_mode;
1736 Q_ASSERT(compMode == QPainter::CompositionMode_Source
1737 || compMode == QPainter::CompositionMode_SourceOver);
1739 shaderManager->setMaskType(QGLEngineShaderManager::SubPixelMaskPass1);
1741 if (pensBrush.style() == Qt::SolidPattern) {
1742 // Solid patterns can get away with only one pass.
1743 QColor c = pensBrush.color();
1744 qreal oldOpacity = q->state()->opacity;
1745 if (compMode == QPainter::CompositionMode_Source) {
1746 c = qt_premultiplyColor(c, q->state()->opacity);
1747 q->state()->opacity = 1;
1748 opacityUniformDirty = true;
1751 compositionModeDirty = false; // I can handle this myself, thank you very much
1752 prepareForDraw(false); // Text always causes src pixels to be transparent
1754 // prepareForDraw() have set the opacity on the current shader, so the opacity state can now be reset.
1755 if (compMode == QPainter::CompositionMode_Source) {
1756 q->state()->opacity = oldOpacity;
1757 opacityUniformDirty = true;
1761 glBlendFunc(GL_CONSTANT_COLOR, GL_ONE_MINUS_SRC_COLOR);
1762 glBlendColor(c.redF(), c.greenF(), c.blueF(), c.alphaF());
1764 // Other brush styles need two passes.
1766 qreal oldOpacity = q->state()->opacity;
1767 if (compMode == QPainter::CompositionMode_Source) {
1768 q->state()->opacity = 1;
1769 opacityUniformDirty = true;
1770 pensBrush = Qt::white;
1771 setBrush(pensBrush);
1774 compositionModeDirty = false; // I can handle this myself, thank you very much
1775 prepareForDraw(false); // Text always causes src pixels to be transparent
1777 glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR);
1779 glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
1780 glBindTexture(GL_TEXTURE_2D, cache->texture());
1781 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, false);
1783 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1784 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
1786 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, elementIndices.data());
1789 shaderManager->setMaskType(QGLEngineShaderManager::SubPixelMaskPass2);
1791 if (compMode == QPainter::CompositionMode_Source) {
1792 q->state()->opacity = oldOpacity;
1793 opacityUniformDirty = true;
1794 pensBrush = q->state()->pen.brush();
1795 setBrush(pensBrush);
1798 compositionModeDirty = false;
1799 prepareForDraw(false); // Text always causes src pixels to be transparent
1801 glBlendFunc(GL_ONE, GL_ONE);
1803 compositionModeDirty = true;
1805 // Greyscale/mono glyphs
1807 shaderManager->setMaskType(QGLEngineShaderManager::PixelMask);
1808 prepareForDraw(false); // Text always causes src pixels to be transparent
1811 QGLTextureGlyphCache::FilterMode filterMode = (s->matrix.type() > QTransform::TxTranslate)?QGLTextureGlyphCache::Linear:QGLTextureGlyphCache::Nearest;
1812 if (lastMaskTextureUsed != cache->texture() || cache->filterMode() != filterMode) {
1814 glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT);
1815 if (lastMaskTextureUsed != cache->texture()) {
1816 glBindTexture(GL_TEXTURE_2D, cache->texture());
1817 lastMaskTextureUsed = cache->texture();
1820 if (cache->filterMode() != filterMode) {
1821 if (filterMode == QGLTextureGlyphCache::Linear) {
1822 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1823 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1825 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1826 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1828 cache->setFilterMode(filterMode);
1832 bool srgbFrameBufferEnabled = false;
1833 if (ctx->d_ptr->extension_flags & QGLExtensions::SRGBFrameBuffer) {
1834 #if defined(Q_WS_MAC)
1835 if (glyphType == QFontEngineGlyphCache::Raster_RGBMask)
1836 #elif defined(Q_WS_WIN)
1837 if (glyphType != QFontEngineGlyphCache::Raster_RGBMask || fontSmoothingApproximately(2.1))
1842 glEnable(FRAMEBUFFER_SRGB_EXT);
1843 srgbFrameBufferEnabled = true;
1847 #if defined(QT_OPENGL_DRAWCACHEDGLYPHS_INDEX_ARRAY_VBO)
1848 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, 0);
1849 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1851 glDrawElements(GL_TRIANGLE_STRIP, 6 * numGlyphs, GL_UNSIGNED_SHORT, elementIndices.data());
1854 if (srgbFrameBufferEnabled)
1855 glDisable(FRAMEBUFFER_SRGB_EXT);
1859 void QGL2PaintEngineEx::drawPixmapFragments(const QPainter::PixmapFragment *fragments, int fragmentCount, const QPixmap &pixmap,
1860 QPainter::PixmapFragmentHints hints)
1862 Q_D(QGL2PaintEngineEx);
1863 // Use fallback for extended composition modes.
1864 if (state()->composition_mode > QPainter::CompositionMode_Plus) {
1865 QPaintEngineEx::drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
1870 int max_texture_size = d->ctx->d_func()->maxTextureSize();
1871 if (pixmap.width() > max_texture_size || pixmap.height() > max_texture_size) {
1872 QPixmap scaled = pixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
1873 d->drawPixmapFragments(fragments, fragmentCount, scaled, hints);
1875 d->drawPixmapFragments(fragments, fragmentCount, pixmap, hints);
1880 void QGL2PaintEngineExPrivate::drawPixmapFragments(const QPainter::PixmapFragment *fragments,
1881 int fragmentCount, const QPixmap &pixmap,
1882 QPainter::PixmapFragmentHints hints)
1884 GLfloat dx = 1.0f / pixmap.size().width();
1885 GLfloat dy = 1.0f / pixmap.size().height();
1887 vertexCoordinateArray.clear();
1888 textureCoordinateArray.clear();
1889 opacityArray.reset();
1891 if (snapToPixelGrid) {
1892 snapToPixelGrid = false;
1896 bool allOpaque = true;
1898 for (int i = 0; i < fragmentCount; ++i) {
1901 if (fragments[i].rotation != 0) {
1902 s = qFastSin(fragments[i].rotation * Q_PI / 180);
1903 c = qFastCos(fragments[i].rotation * Q_PI / 180);
1906 qreal right = 0.5 * fragments[i].scaleX * fragments[i].width;
1907 qreal bottom = 0.5 * fragments[i].scaleY * fragments[i].height;
1908 QGLPoint bottomRight(right * c - bottom * s, right * s + bottom * c);
1909 QGLPoint bottomLeft(-right * c - bottom * s, -right * s + bottom * c);
1911 vertexCoordinateArray.addVertex(bottomRight.x + fragments[i].x, bottomRight.y + fragments[i].y);
1912 vertexCoordinateArray.addVertex(-bottomLeft.x + fragments[i].x, -bottomLeft.y + fragments[i].y);
1913 vertexCoordinateArray.addVertex(-bottomRight.x + fragments[i].x, -bottomRight.y + fragments[i].y);
1914 vertexCoordinateArray.addVertex(-bottomRight.x + fragments[i].x, -bottomRight.y + fragments[i].y);
1915 vertexCoordinateArray.addVertex(bottomLeft.x + fragments[i].x, bottomLeft.y + fragments[i].y);
1916 vertexCoordinateArray.addVertex(bottomRight.x + fragments[i].x, bottomRight.y + fragments[i].y);
1918 QGLRect src(fragments[i].sourceLeft * dx, fragments[i].sourceTop * dy,
1919 (fragments[i].sourceLeft + fragments[i].width) * dx,
1920 (fragments[i].sourceTop + fragments[i].height) * dy);
1922 textureCoordinateArray.addVertex(src.right, src.bottom);
1923 textureCoordinateArray.addVertex(src.right, src.top);
1924 textureCoordinateArray.addVertex(src.left, src.top);
1925 textureCoordinateArray.addVertex(src.left, src.top);
1926 textureCoordinateArray.addVertex(src.left, src.bottom);
1927 textureCoordinateArray.addVertex(src.right, src.bottom);
1929 qreal opacity = fragments[i].opacity * q->state()->opacity;
1930 opacityArray << opacity << opacity << opacity << opacity << opacity << opacity;
1931 allOpaque &= (opacity >= 0.99f);
1934 glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);
1935 QGLTexture *texture = ctx->d_func()->bindTexture(pixmap, GL_TEXTURE_2D, GL_RGBA,
1936 QGLContext::InternalBindOption
1937 | QGLContext::CanFlipNativePixmapBindOption);
1939 if (texture->options & QGLContext::InvertedYBindOption) {
1940 // Flip texture y-coordinate.
1941 QGLPoint *data = textureCoordinateArray.data();
1942 for (int i = 0; i < 6 * fragmentCount; ++i)
1943 data[i].y = 1 - data[i].y;
1946 transferMode(ImageArrayDrawingMode);
1948 bool isBitmap = pixmap.isQBitmap();
1949 bool isOpaque = !isBitmap && (!pixmap.hasAlpha() || (hints & QPainter::OpaqueHint)) && allOpaque;
1951 updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE,
1952 q->state()->renderHints & QPainter::SmoothPixmapTransform, texture->id);
1954 // Setup for texture drawing
1955 currentBrush = noBrush;
1956 shaderManager->setSrcPixelType(isBitmap ? QGLEngineShaderManager::PatternSrc
1957 : QGLEngineShaderManager::ImageSrc);
1958 if (prepareForDraw(isOpaque))
1959 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::ImageTexture), QT_IMAGE_TEXTURE_UNIT);
1962 QColor col = qt_premultiplyColor(q->state()->pen.color(), (GLfloat)q->state()->opacity);
1963 shaderManager->currentProgram()->setUniformValue(location(QGLEngineShaderManager::PatternColor), col);
1966 glDrawArrays(GL_TRIANGLES, 0, 6 * fragmentCount);
1969 bool QGL2PaintEngineEx::begin(QPaintDevice *pdev)
1971 Q_D(QGL2PaintEngineEx);
1973 // qDebug("QGL2PaintEngineEx::begin()");
1974 if (pdev->devType() == QInternal::OpenGL)
1975 d->device = static_cast<QGLPaintDevice*>(pdev);
1977 d->device = QGLPaintDevice::getDevice(pdev);
1982 d->ctx = d->device->context();
1983 d->ctx->d_ptr->active_engine = this;
1985 const QSize sz = d->device->size();
1986 d->width = sz.width();
1987 d->height = sz.height();
1988 d->mode = BrushDrawingMode;
1989 d->brushTextureDirty = true;
1990 d->brushUniformsDirty = true;
1991 d->matrixUniformDirty = true;
1992 d->matrixDirty = true;
1993 d->compositionModeDirty = true;
1994 d->opacityUniformDirty = true;
1995 d->needsSync = true;
1996 d->useSystemClip = !systemClip().isEmpty();
1997 d->currentBrush = QBrush();
1999 d->dirtyStencilRegion = QRect(0, 0, d->width, d->height);
2000 d->stencilClean = true;
2002 // Calling begin paint should make the correct context current. So, any
2003 // code which calls into GL or otherwise needs a current context *must*
2004 // go after beginPaint:
2005 d->device->beginPaint();
2007 #if !defined(QT_OPENGL_ES_2)
2008 bool success = qt_resolve_version_2_0_functions(d->ctx)
2009 && qt_resolve_buffer_extensions(d->ctx);
2014 d->shaderManager = new QGLEngineShaderManager(d->ctx);
2016 glDisable(GL_STENCIL_TEST);
2017 glDisable(GL_DEPTH_TEST);
2018 glDisable(GL_SCISSOR_TEST);
2020 #if !defined(QT_OPENGL_ES_2)
2021 glDisable(GL_MULTISAMPLE);
2024 d->glyphCacheType = QFontEngineGlyphCache::Raster_A8;
2026 #if !defined(QT_OPENGL_ES_2)
2027 #if defined(Q_WS_WIN)
2028 if (qt_cleartype_enabled
2029 && (fontSmoothingApproximately(1.0) || fontSmoothingApproximately(2.1)))
2031 #if defined(Q_WS_MAC)
2032 if (qt_applefontsmoothing_enabled)
2034 d->glyphCacheType = QFontEngineGlyphCache::Raster_RGBMask;
2037 #if defined(QT_OPENGL_ES_2)
2038 // OpenGL ES can't switch MSAA off, so if the gl paint device is
2039 // multisampled, it's always multisampled.
2040 d->multisamplingAlwaysEnabled = d->device->format().sampleBuffers();
2042 d->multisamplingAlwaysEnabled = false;
2048 bool QGL2PaintEngineEx::end()
2050 Q_D(QGL2PaintEngineEx);
2052 QGLContext *ctx = d->ctx;
2054 d->transferMode(BrushDrawingMode);
2055 d->device->endPaint();
2057 ctx->d_ptr->active_engine = 0;
2061 delete d->shaderManager;
2062 d->shaderManager = 0;
2063 d->currentBrush = QBrush();
2065 #ifdef QT_OPENGL_CACHE_AS_VBOS
2066 if (!d->unusedVBOSToClean.isEmpty()) {
2067 glDeleteBuffers(d->unusedVBOSToClean.size(), d->unusedVBOSToClean.constData());
2068 d->unusedVBOSToClean.clear();
2070 if (!d->unusedIBOSToClean.isEmpty()) {
2071 glDeleteBuffers(d->unusedIBOSToClean.size(), d->unusedIBOSToClean.constData());
2072 d->unusedIBOSToClean.clear();
2079 void QGL2PaintEngineEx::ensureActive()
2081 Q_D(QGL2PaintEngineEx);
2082 QGLContext *ctx = d->ctx;
2084 if (isActive() && ctx->d_ptr->active_engine != this) {
2085 ctx->d_ptr->active_engine = this;
2086 d->needsSync = true;
2089 d->device->ensureActiveTarget();
2092 d->transferMode(BrushDrawingMode);
2093 glViewport(0, 0, d->width, d->height);
2094 d->needsSync = false;
2095 d->lastMaskTextureUsed = 0;
2096 d->shaderManager->setDirty();
2097 d->ctx->d_func()->syncGlState();
2098 for (int i = 0; i < 3; ++i)
2099 d->vertexAttribPointers[i] = (GLfloat*)-1; // Assume the pointers are clobbered
2104 void QGL2PaintEngineExPrivate::updateClipScissorTest()
2106 Q_Q(QGL2PaintEngineEx);
2107 if (q->state()->clipTestEnabled) {
2108 glEnable(GL_STENCIL_TEST);
2109 glStencilFunc(GL_LEQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
2111 glDisable(GL_STENCIL_TEST);
2112 glStencilFunc(GL_ALWAYS, 0, 0xff);
2115 #ifdef QT_GL_NO_SCISSOR_TEST
2116 currentScissorBounds = QRect(0, 0, width, height);
2118 QRect bounds = q->state()->rectangleClip;
2119 if (!q->state()->clipEnabled) {
2121 bounds = systemClip.boundingRect();
2123 bounds = QRect(0, 0, width, height);
2126 bounds = bounds.intersected(systemClip.boundingRect());
2128 bounds = bounds.intersected(QRect(0, 0, width, height));
2131 currentScissorBounds = bounds;
2133 if (bounds == QRect(0, 0, width, height)) {
2134 glDisable(GL_SCISSOR_TEST);
2136 glEnable(GL_SCISSOR_TEST);
2142 void QGL2PaintEngineExPrivate::setScissor(const QRect &rect)
2144 const int left = rect.left();
2145 const int width = rect.width();
2146 int bottom = height - (rect.top() + rect.height());
2147 if (device->isFlipped()) {
2148 bottom = rect.top();
2150 const int height = rect.height();
2152 glScissor(left, bottom, width, height);
2155 void QGL2PaintEngineEx::clipEnabledChanged()
2157 Q_D(QGL2PaintEngineEx);
2159 state()->clipChanged = true;
2161 if (painter()->hasClipping())
2162 d->regenerateClip();
2164 d->systemStateChanged();
2167 void QGL2PaintEngineExPrivate::clearClip(uint value)
2169 dirtyStencilRegion -= currentScissorBounds;
2171 glStencilMask(0xff);
2172 glClearStencil(value);
2173 glClear(GL_STENCIL_BUFFER_BIT);
2176 q->state()->needsClipBufferClear = false;
2179 void QGL2PaintEngineExPrivate::writeClip(const QVectorPath &path, uint value)
2181 transferMode(BrushDrawingMode);
2183 if (snapToPixelGrid) {
2184 snapToPixelGrid = false;
2191 stencilClean = false;
2193 const bool singlePass = !path.hasWindingFill()
2194 && (((q->state()->currentClip == maxClip - 1) && q->state()->clipTestEnabled)
2195 || q->state()->needsClipBufferClear);
2196 const uint referenceClipValue = q->state()->needsClipBufferClear ? 1 : q->state()->currentClip;
2198 if (q->state()->needsClipBufferClear)
2201 if (path.isEmpty()) {
2202 glEnable(GL_STENCIL_TEST);
2203 glStencilFunc(GL_LEQUAL, value, ~GL_STENCIL_HIGH_BIT);
2207 if (q->state()->clipTestEnabled)
2208 glStencilFunc(GL_LEQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
2210 glStencilFunc(GL_ALWAYS, 0, 0xff);
2212 vertexCoordinateArray.clear();
2213 vertexCoordinateArray.addPath(path, inverseScale, false);
2216 fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill());
2218 glColorMask(false, false, false, false);
2219 glEnable(GL_STENCIL_TEST);
2223 // Under these conditions we can set the new stencil value in a single
2224 // pass, by using the current value and the "new value" as the toggles
2226 glStencilFunc(GL_LEQUAL, referenceClipValue, ~GL_STENCIL_HIGH_BIT);
2227 glStencilOp(GL_KEEP, GL_INVERT, GL_INVERT);
2228 glStencilMask(value ^ referenceClipValue);
2230 drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN);
2232 glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
2233 glStencilMask(0xff);
2235 if (!q->state()->clipTestEnabled && path.hasWindingFill()) {
2236 // Pass when any clip bit is set, set high bit
2237 glStencilFunc(GL_NOTEQUAL, GL_STENCIL_HIGH_BIT, ~GL_STENCIL_HIGH_BIT);
2238 composite(vertexCoordinateArray.boundingRect());
2241 // Pass when high bit is set, replace stencil value with new clip value
2242 glStencilFunc(GL_NOTEQUAL, value, GL_STENCIL_HIGH_BIT);
2244 composite(vertexCoordinateArray.boundingRect());
2247 glStencilFunc(GL_LEQUAL, value, ~GL_STENCIL_HIGH_BIT);
2250 glColorMask(true, true, true, true);
2253 void QGL2PaintEngineEx::clip(const QVectorPath &path, Qt::ClipOperation op)
2255 // qDebug("QGL2PaintEngineEx::clip()");
2256 Q_D(QGL2PaintEngineEx);
2258 state()->clipChanged = true;
2262 if (op == Qt::ReplaceClip) {
2263 op = Qt::IntersectClip;
2264 if (d->hasClipOperations()) {
2265 d->systemStateChanged();
2266 state()->canRestoreClip = false;
2270 #ifndef QT_GL_NO_SCISSOR_TEST
2271 if (!path.isEmpty() && op == Qt::IntersectClip && (path.shape() == QVectorPath::RectangleHint)) {
2272 const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
2273 QRectF rect(points[0], points[2]);
2275 if (state()->matrix.type() <= QTransform::TxScale
2276 || (state()->matrix.type() == QTransform::TxRotate
2277 && qFuzzyIsNull(state()->matrix.m11())
2278 && qFuzzyIsNull(state()->matrix.m22())))
2280 state()->rectangleClip = state()->rectangleClip.intersected(state()->matrix.mapRect(rect).toRect());
2281 d->updateClipScissorTest();
2287 const QRect pathRect = state()->matrix.mapRect(path.controlPointRect()).toAlignedRect();
2291 if (d->useSystemClip) {
2292 state()->clipTestEnabled = true;
2293 state()->currentClip = 1;
2295 state()->clipTestEnabled = false;
2297 state()->rectangleClip = QRect(0, 0, d->width, d->height);
2298 state()->canRestoreClip = false;
2299 d->updateClipScissorTest();
2301 case Qt::IntersectClip:
2302 state()->rectangleClip = state()->rectangleClip.intersected(pathRect);
2303 d->updateClipScissorTest();
2304 d->resetClipIfNeeded();
2306 d->writeClip(path, d->maxClip);
2307 state()->currentClip = d->maxClip;
2308 state()->clipTestEnabled = true;
2315 void QGL2PaintEngineExPrivate::regenerateClip()
2317 systemStateChanged();
2318 replayClipOperations();
2321 void QGL2PaintEngineExPrivate::systemStateChanged()
2323 Q_Q(QGL2PaintEngineEx);
2325 q->state()->clipChanged = true;
2327 if (systemClip.isEmpty()) {
2328 useSystemClip = false;
2330 if (q->paintDevice()->devType() == QInternal::Widget && currentClipDevice) {
2331 QWidgetPrivate *widgetPrivate = qt_widget_private(static_cast<QWidget *>(currentClipDevice)->window());
2332 useSystemClip = widgetPrivate->extra && widgetPrivate->extra->inRenderWithPainter;
2334 useSystemClip = true;
2338 q->state()->clipTestEnabled = false;
2339 q->state()->needsClipBufferClear = true;
2341 q->state()->currentClip = 1;
2344 q->state()->rectangleClip = useSystemClip ? systemClip.boundingRect() : QRect(0, 0, width, height);
2345 updateClipScissorTest();
2347 if (systemClip.rectCount() == 1) {
2348 if (systemClip.boundingRect() == QRect(0, 0, width, height))
2349 useSystemClip = false;
2350 #ifndef QT_GL_NO_SCISSOR_TEST
2351 // scissoring takes care of the system clip
2356 if (useSystemClip) {
2360 path.addRegion(systemClip);
2362 q->state()->currentClip = 0;
2363 writeClip(qtVectorPathForPath(q->state()->matrix.inverted().map(path)), 1);
2364 q->state()->currentClip = 1;
2365 q->state()->clipTestEnabled = true;
2369 void QGL2PaintEngineEx::setState(QPainterState *new_state)
2371 // qDebug("QGL2PaintEngineEx::setState()");
2373 Q_D(QGL2PaintEngineEx);
2375 QOpenGL2PaintEngineState *s = static_cast<QOpenGL2PaintEngineState *>(new_state);
2376 QOpenGL2PaintEngineState *old_state = state();
2378 QPaintEngineEx::setState(s);
2381 // Newly created state object. The call to setState()
2382 // will either be followed by a call to begin(), or we are
2383 // setting the state as part of a save().
2388 // Setting the state as part of a restore().
2390 if (old_state == s || old_state->renderHintsChanged)
2391 renderHintsChanged();
2393 if (old_state == s || old_state->matrixChanged)
2394 d->matrixDirty = true;
2396 if (old_state == s || old_state->compositionModeChanged)
2397 d->compositionModeDirty = true;
2399 if (old_state == s || old_state->opacityChanged)
2400 d->opacityUniformDirty = true;
2402 if (old_state == s || old_state->clipChanged) {
2403 if (old_state && old_state != s && old_state->canRestoreClip) {
2404 d->updateClipScissorTest();
2405 glDepthFunc(GL_LEQUAL);
2407 d->regenerateClip();
2412 QPainterState *QGL2PaintEngineEx::createState(QPainterState *orig) const
2415 const_cast<QGL2PaintEngineEx *>(this)->ensureActive();
2417 QOpenGL2PaintEngineState *s;
2419 s = new QOpenGL2PaintEngineState();
2421 s = new QOpenGL2PaintEngineState(*static_cast<QOpenGL2PaintEngineState *>(orig));
2423 s->matrixChanged = false;
2424 s->compositionModeChanged = false;
2425 s->opacityChanged = false;
2426 s->renderHintsChanged = false;
2427 s->clipChanged = false;
2432 QOpenGL2PaintEngineState::QOpenGL2PaintEngineState(QOpenGL2PaintEngineState &other)
2433 : QPainterState(other)
2436 needsClipBufferClear = other.needsClipBufferClear;
2437 clipTestEnabled = other.clipTestEnabled;
2438 currentClip = other.currentClip;
2439 canRestoreClip = other.canRestoreClip;
2440 rectangleClip = other.rectangleClip;
2443 QOpenGL2PaintEngineState::QOpenGL2PaintEngineState()
2446 needsClipBufferClear = true;
2447 clipTestEnabled = false;
2448 canRestoreClip = true;
2451 QOpenGL2PaintEngineState::~QOpenGL2PaintEngineState()