qopenglpaintengine.cpp 98.2 KB
Newer Older
1
2
/****************************************************************************
**
Jani Heikkinen's avatar
Jani Heikkinen committed
3
4
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
5
6
7
**
** This file is part of the QtGui module of the Qt Toolkit.
**
Jani Heikkinen's avatar
Jani Heikkinen committed
8
** $QT_BEGIN_LICENSE:LGPL$
9
10
11
12
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
Jani Heikkinen's avatar
Jani Heikkinen committed
13
** a written agreement between you and The Qt Company. For licensing terms
Jani Heikkinen's avatar
Jani Heikkinen committed
14
15
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
16
**
17
** GNU Lesser General Public License Usage
18
** Alternatively, this file may be used under the terms of the GNU Lesser
Jani Heikkinen's avatar
Jani Heikkinen committed
19
20
21
22
23
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
24
**
Jani Heikkinen's avatar
Jani Heikkinen committed
25
26
27
28
29
30
31
32
33
34
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
**
** $QT_END_LICENSE$
**
****************************************************************************/

/*
    When the active program changes, we need to update it's uniforms.
    We could track state for each program and only update stale uniforms
        - Could lead to lots of overhead if there's a lot of programs
    We could update all the uniforms when the program changes
        - Could end up updating lots of uniforms which don't need updating

    Updating uniforms should be cheap, so the overhead of updating up-to-date
    uniforms should be minimal. It's also less complex.

    Things which _may_ cause a different program to be used:
        - Change in brush/pen style
        - Change in painter opacity
        - Change in composition mode

    Whenever we set a mode on the shader manager - it needs to tell us if it had
    to switch to a different program.

    The shader manager should only switch when we tell it to. E.g. if we set a new
    brush style and then switch to transparent painter, we only want it to compile
    and use the correct program when we really need it.
*/

// #define QT_OPENGL_CACHE_AS_VBOS

#include "qopenglgradientcache_p.h"
66
#include "qopengltexturecache_p.h"
67
#include "qopenglpaintengine_p.h"
68
#include "qopenglpaintdevice_p.h"
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

#include <string.h> //for memcpy
#include <qmath.h>

#include <private/qopengl_p.h>
#include <private/qopenglcontext_p.h>
#include <private/qopenglextensions_p.h>
#include <private/qpaintengineex_p.h>
#include <QPaintEngine>
#include <private/qpainter_p.h>
#include <private/qfontengine_p.h>
#include <private/qdatabuffer_p.h>
#include <private/qstatictext_p.h>
#include <private/qtriangulator_p.h>

#include "qopenglengineshadermanager_p.h"
#include "qopengl2pexvertexarray_p.h"
86
#include "qopengltextureglyphcache_p.h"
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101

#include <QDebug>

QT_BEGIN_NAMESPACE



Q_GUI_EXPORT QImage qt_imageForBrush(int brushStyle, bool invert);

////////////////////////////////// Private Methods //////////////////////////////////////////

QOpenGL2PaintEngineExPrivate::~QOpenGL2PaintEngineExPrivate()
{
    delete shaderManager;

102
103
104
105
106
107
    vertexBuffer.destroy();
    texCoordBuffer.destroy();
    opacityBuffer.destroy();
    indexBuffer.destroy();
    vao.destroy();

108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
    if (elementIndicesVBOId != 0) {
        funcs.glDeleteBuffers(1, &elementIndicesVBOId);
        elementIndicesVBOId = 0;
    }
}

inline QColor qt_premultiplyColor(QColor c, GLfloat opacity)
{
    qreal alpha = c.alphaF() * opacity;
    c.setAlphaF(alpha);
    c.setRedF(c.redF() * alpha);
    c.setGreenF(c.greenF() * alpha);
    c.setBlueF(c.blueF() * alpha);
    return c;
}


void QOpenGL2PaintEngineExPrivate::setBrush(const QBrush& brush)
{
    if (qbrush_fast_equals(currentBrush, brush))
        return;

    const Qt::BrushStyle newStyle = qbrush_style(brush);
    Q_ASSERT(newStyle != Qt::NoBrush);

    currentBrush = brush;
134
135
    if (!currentBrushImage.isNull())
        currentBrushImage = QImage();
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
    brushUniformsDirty = true; // All brushes have at least one uniform

    if (newStyle > Qt::SolidPattern)
        brushTextureDirty = true;

    if (currentBrush.style() == Qt::TexturePattern
        && qHasPixmapTexture(brush) && brush.texture().isQBitmap())
    {
        shaderManager->setSrcPixelType(QOpenGLEngineShaderManager::TextureSrcWithPattern);
    } else {
        shaderManager->setSrcPixelType(newStyle);
    }
    shaderManager->optimiseForBrushTransform(currentBrush.transform().type());
}


void QOpenGL2PaintEngineExPrivate::useSimpleShader()
{
    shaderManager->useSimpleProgram();

    if (matrixDirty)
        updateMatrix();
}

160
161
162
163
164
165
166
167
168
169
170
171
172
173
/*
    Single entry-point for activating, binding, and setting properties.

    Allows keeping track of (caching) the latest texture unit and bound
    texture in a central place, so that we can skip re-binding unless
    needed.

    \note Any code or Qt API that internally activates or binds will
    not affect the cache used by this function, which means they will
    lead to inconsisent state. QPainter::beginNativePainting() takes
    care of resetting the cache, so for user–code this is fine, but
    internally in the paint engine care must be taken to not call
    functions that may activate or bind under our feet.
*/
174
175
176
177
178
template<typename T>
void QOpenGL2PaintEngineExPrivate::updateTexture(GLenum textureUnit, const T &texture, GLenum wrapMode, GLenum filterMode, TextureUpdateMode updateMode)
{
    static const GLenum target = GL_TEXTURE_2D;

179
    activateTextureUnit(textureUnit);
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194

    GLuint textureId = bindTexture(texture);

    if (updateMode == UpdateIfNeeded && textureId == lastTextureUsed)
        return;

    lastTextureUsed = textureId;

    funcs.glTexParameteri(target, GL_TEXTURE_WRAP_S, wrapMode);
    funcs.glTexParameteri(target, GL_TEXTURE_WRAP_T, wrapMode);

    funcs.glTexParameteri(target, GL_TEXTURE_MAG_FILTER, filterMode);
    funcs.glTexParameteri(target, GL_TEXTURE_MIN_FILTER, filterMode);
}

195
196
197
198
199
200
201
202
203
204
205
206
207
208
void QOpenGL2PaintEngineExPrivate::activateTextureUnit(GLenum textureUnit)
{
    if (textureUnit != lastTextureUnitUsed) {
        funcs.glActiveTexture(GL_TEXTURE0 + textureUnit);
        lastTextureUnitUsed = textureUnit;

        // We simplify things by keeping a single cached value of the last
        // texture that was bound, instead of one per texture unit. This
        // means that switching texture units could potentially mean we
        // need a re-bind and corresponding parameter updates.
        lastTextureUsed = GLuint(-1);
    }
}

209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
template<>
GLuint QOpenGL2PaintEngineExPrivate::bindTexture(const GLuint &textureId)
{
    if (textureId != lastTextureUsed)
        funcs.glBindTexture(GL_TEXTURE_2D, textureId);

    return textureId;
}

template<>
GLuint QOpenGL2PaintEngineExPrivate::bindTexture(const QImage &image)
{
    return QOpenGLTextureCache::cacheForContext(ctx)->bindTexture(ctx, image);
}

template<>
GLuint QOpenGL2PaintEngineExPrivate::bindTexture(const QPixmap &pixmap)
{
    return QOpenGLTextureCache::cacheForContext(ctx)->bindTexture(ctx, pixmap);
}

230
231
232
233
234
235
236
237
238
239
240
241
242
243
template<>
GLuint QOpenGL2PaintEngineExPrivate::bindTexture(const QGradient &gradient)
{
    // We apply global opacity in the fragment shaders, so we always pass 1.0
    // for opacity to the cache.
    GLuint textureId = QOpenGL2GradientCache::cacheForContext(ctx)->getBuffer(gradient, 1.0);

    // QOpenGL2GradientCache::getBuffer() may bind and generate a new texture if it
    // hasn't been cached yet, but will otherwise return an unbound texture id. To
    // be sure that the texture is bound, we unfortunately have to bind again,
    // which results in the initial generation of the texture doing two binds.
    return bindTexture(textureId);
}

244
245
246
247
248
249
250
251
252
253
254
255
struct ImageWithBindOptions
{
    const QImage &image;
    QOpenGLTextureCache::BindOptions options;
};

template<>
GLuint QOpenGL2PaintEngineExPrivate::bindTexture(const ImageWithBindOptions &imageWithOptions)
{
    return QOpenGLTextureCache::cacheForContext(ctx)->bindTexture(ctx, imageWithOptions.image, imageWithOptions.options);
}

256
257
258
259
260
261
void QOpenGL2PaintEngineExPrivate::updateBrushTexture()
{
    Q_Q(QOpenGL2PaintEngineEx);
//     qDebug("QOpenGL2PaintEngineExPrivate::updateBrushTexture()");
    Qt::BrushStyle style = currentBrush.style();

262
263
264
    bool smoothPixmapTransform = q->state()->renderHints & QPainter::SmoothPixmapTransform;
    GLenum filterMode = smoothPixmapTransform ? GL_LINEAR : GL_NEAREST;

265
266
    if ( (style >= Qt::Dense1Pattern) && (style <= Qt::DiagCrossPattern) ) {
        // Get the image data for the pattern
267
        QImage textureImage = qt_imageForBrush(style, false);
268

269
        updateTexture(QT_BRUSH_TEXTURE_UNIT, textureImage, GL_REPEAT, filterMode, ForceUpdate);
270
271
272
273
    }
    else if (style >= Qt::LinearGradientPattern && style <= Qt::ConicalGradientPattern) {
        // Gradiant brush: All the gradiants use the same texture

274
        const QGradient *gradient = currentBrush.gradient();
275

276
        GLenum wrapMode = GL_CLAMP_TO_EDGE;
277
        if (gradient->spread() == QGradient::RepeatSpread || gradient->type() == QGradient::ConicalGradient)
278
            wrapMode = GL_REPEAT;
279
        else if (gradient->spread() == QGradient::ReflectSpread)
280
281
            wrapMode = GL_MIRRORED_REPEAT;

282
        updateTexture(QT_BRUSH_TEXTURE_UNIT, *gradient, wrapMode, filterMode, ForceUpdate);
283
284
    }
    else if (style == Qt::TexturePattern) {
285
        currentBrushImage = currentBrush.textureImage();
286
287

        int max_texture_size = ctx->d_func()->maxTextureSize();
288
289
        if (currentBrushImage.width() > max_texture_size || currentBrushImage.height() > max_texture_size)
            currentBrushImage = currentBrushImage.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);
290

291
        GLuint wrapMode = GL_REPEAT;
Laszlo Agocs's avatar
Laszlo Agocs committed
292
        if (QOpenGLContext::currentContext()->isOpenGLES()) {
Laszlo Agocs's avatar
Laszlo Agocs committed
293
294
295
296
297
298
            // OpenGL ES does not support GL_REPEAT wrap modes for NPOT textures. So instead,
            // we emulate GL_REPEAT by only taking the fractional part of the texture coords
            // in the qopenglslTextureBrushSrcFragmentShader program.
            wrapMode = GL_CLAMP_TO_EDGE;
        }

299
        updateTexture(QT_BRUSH_TEXTURE_UNIT, currentBrushImage, wrapMode, filterMode, ForceUpdate);
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
    }
    brushTextureDirty = false;
}


void QOpenGL2PaintEngineExPrivate::updateBrushUniforms()
{
//     qDebug("QOpenGL2PaintEngineExPrivate::updateBrushUniforms()");
    Qt::BrushStyle style = currentBrush.style();

    if (style == Qt::NoBrush)
        return;

    QTransform brushQTransform = currentBrush.transform();

    if (style == Qt::SolidPattern) {
        QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
        shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::FragmentColor), col);
    }
    else {
        // All other brushes have a transform and thus need the translation point:
        QPointF translationPoint;

        if (style <= Qt::DiagCrossPattern) {
            QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);

            shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::PatternColor), col);

            QVector2D halfViewportSize(width*0.5, height*0.5);
            shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
        }
        else if (style == Qt::LinearGradientPattern) {
            const QLinearGradient *g = static_cast<const QLinearGradient *>(currentBrush.gradient());

            QPointF realStart = g->start();
            QPointF realFinal = g->finalStop();
            translationPoint = realStart;

            QPointF l = realFinal - realStart;

            QVector3D linearData(
                l.x(),
                l.y(),
                1.0f / (l.x() * l.x() + l.y() * l.y())
            );

            shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::LinearData), linearData);

            QVector2D halfViewportSize(width*0.5, height*0.5);
            shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
        }
        else if (style == Qt::ConicalGradientPattern) {
            const QConicalGradient *g = static_cast<const QConicalGradient *>(currentBrush.gradient());
            translationPoint   = g->center();

355
            GLfloat angle = -qDegreesToRadians(g->angle());
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409

            shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Angle), angle);

            QVector2D halfViewportSize(width*0.5, height*0.5);
            shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
        }
        else if (style == Qt::RadialGradientPattern) {
            const QRadialGradient *g = static_cast<const QRadialGradient *>(currentBrush.gradient());
            QPointF realCenter = g->center();
            QPointF realFocal  = g->focalPoint();
            qreal   realRadius = g->centerRadius() - g->focalRadius();
            translationPoint   = realFocal;

            QPointF fmp = realCenter - realFocal;
            shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Fmp), fmp);

            GLfloat fmp2_m_radius2 = -fmp.x() * fmp.x() - fmp.y() * fmp.y() + realRadius*realRadius;
            shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Fmp2MRadius2), fmp2_m_radius2);
            shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Inverse2Fmp2MRadius2),
                                                             GLfloat(1.0 / (2.0*fmp2_m_radius2)));
            shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::SqrFr),
                                                             GLfloat(g->focalRadius() * g->focalRadius()));
            shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::BRadius),
                                                             GLfloat(2 * (g->centerRadius() - g->focalRadius()) * g->focalRadius()),
                                                             g->focalRadius(),
                                                             g->centerRadius() - g->focalRadius());

            QVector2D halfViewportSize(width*0.5, height*0.5);
            shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
        }
        else if (style == Qt::TexturePattern) {
            const QPixmap& texPixmap = currentBrush.texture();

            if (qHasPixmapTexture(currentBrush) && currentBrush.texture().isQBitmap()) {
                QColor col = qt_premultiplyColor(currentBrush.color(), (GLfloat)q->state()->opacity);
                shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::PatternColor), col);
            }

            QSizeF invertedTextureSize(1.0 / texPixmap.width(), 1.0 / texPixmap.height());
            shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::InvertedTextureSize), invertedTextureSize);

            QVector2D halfViewportSize(width*0.5, height*0.5);
            shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::HalfViewportSize), halfViewportSize);
        }
        else
            qWarning("QOpenGL2PaintEngineEx: Unimplemented fill style");

        const QPointF &brushOrigin = q->state()->brushOrigin;
        QTransform matrix = q->state()->matrix;
        matrix.translate(brushOrigin.x(), brushOrigin.y());

        QTransform translate(1, 0, 0, 1, -translationPoint.x(), -translationPoint.y());
        qreal m22 = -1;
        qreal dy = height;
410
        if (device->paintFlipped()) {
411
412
413
414
            m22 = 1;
            dy = 0;
        }
        QTransform gl_to_qt(1, 0, 0, m22, 0, dy);
415
        QTransform inv_matrix = gl_to_qt * (brushQTransform * matrix).inverted() * translate;
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453

        shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::BrushTransform), inv_matrix);
        shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::BrushTexture), QT_BRUSH_TEXTURE_UNIT);
    }
    brushUniformsDirty = false;
}


// This assumes the shader manager has already setup the correct shader program
void QOpenGL2PaintEngineExPrivate::updateMatrix()
{
//     qDebug("QOpenGL2PaintEngineExPrivate::updateMatrix()");

    const QTransform& transform = q->state()->matrix;

    // The projection matrix converts from Qt's coordinate system to GL's coordinate system
    //    * GL's viewport is 2x2, Qt's is width x height
    //    * GL has +y -> -y going from bottom -> top, Qt is the other way round
    //    * GL has [0,0] in the center, Qt has it in the top-left
    //
    // This results in the Projection matrix below, which is multiplied by the painter's
    // transformation matrix, as shown below:
    //
    //                Projection Matrix                      Painter Transform
    // ------------------------------------------------   ------------------------
    // | 2.0 / width  |      0.0      |     -1.0      |   |  m11  |  m21  |  dx  |
    // |     0.0      | -2.0 / height |      1.0      | * |  m12  |  m22  |  dy  |
    // |     0.0      |      0.0      |      1.0      |   |  m13  |  m23  |  m33 |
    // ------------------------------------------------   ------------------------
    //
    // NOTE: The resultant matrix is also transposed, as GL expects column-major matracies

    const GLfloat wfactor = 2.0f / width;
    GLfloat hfactor = -2.0f / height;

    GLfloat dx = transform.dx();
    GLfloat dy = transform.dy();

454
    if (device->paintFlipped()) {
455
456
457
458
459
460
461
462
        hfactor *= -1;
        dy -= height;
    }

    // Non-integer translates can have strange effects for some rendering operations such as
    // anti-aliased text rendering. In such cases, we snap the translate to the pixel grid.
    if (snapToPixelGrid && transform.type() == QTransform::TxTranslate) {
        // 0.50 needs to rounded down to 0.0 for consistency with raster engine:
463
464
        dx = std::ceil(dx - 0.5f);
        dy = std::ceil(dy - 0.5f);
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
    }
    pmvMatrix[0][0] = (wfactor * transform.m11())  - transform.m13();
    pmvMatrix[1][0] = (wfactor * transform.m21())  - transform.m23();
    pmvMatrix[2][0] = (wfactor * dx) - transform.m33();
    pmvMatrix[0][1] = (hfactor * transform.m12())  + transform.m13();
    pmvMatrix[1][1] = (hfactor * transform.m22())  + transform.m23();
    pmvMatrix[2][1] = (hfactor * dy) + transform.m33();
    pmvMatrix[0][2] = transform.m13();
    pmvMatrix[1][2] = transform.m23();
    pmvMatrix[2][2] = transform.m33();

    // 1/10000 == 0.0001, so we have good enough res to cover curves
    // that span the entire widget...
    inverseScale = qMax(1 / qMax( qMax(qAbs(transform.m11()), qAbs(transform.m22())),
                                  qMax(qAbs(transform.m12()), qAbs(transform.m21())) ),
                        qreal(0.0001));

    matrixDirty = false;
    matrixUniformDirty = true;

    // Set the PMV matrix attribute. As we use an attributes rather than uniforms, we only
    // need to do this once for every matrix change and persists across all shader programs.
    funcs.glVertexAttrib3fv(QT_PMV_MATRIX_1_ATTR, pmvMatrix[0]);
    funcs.glVertexAttrib3fv(QT_PMV_MATRIX_2_ATTR, pmvMatrix[1]);
    funcs.glVertexAttrib3fv(QT_PMV_MATRIX_3_ATTR, pmvMatrix[2]);

    dasher.setInvScale(inverseScale);
    stroker.setInvScale(inverseScale);
}


void QOpenGL2PaintEngineExPrivate::updateCompositionMode()
{
    // NOTE: The entire paint engine works on pre-multiplied data - which is why some of these
    //       composition modes look odd.
//     qDebug() << "QOpenGL2PaintEngineExPrivate::updateCompositionMode() - Setting GL composition mode for " << q->state()->composition_mode;
    switch(q->state()->composition_mode) {
    case QPainter::CompositionMode_SourceOver:
503
        funcs.glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
504
505
        break;
    case QPainter::CompositionMode_DestinationOver:
506
        funcs.glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE);
507
508
        break;
    case QPainter::CompositionMode_Clear:
509
        funcs.glBlendFunc(GL_ZERO, GL_ZERO);
510
511
        break;
    case QPainter::CompositionMode_Source:
512
        funcs.glBlendFunc(GL_ONE, GL_ZERO);
513
514
        break;
    case QPainter::CompositionMode_Destination:
515
        funcs.glBlendFunc(GL_ZERO, GL_ONE);
516
517
        break;
    case QPainter::CompositionMode_SourceIn:
518
        funcs.glBlendFunc(GL_DST_ALPHA, GL_ZERO);
519
520
        break;
    case QPainter::CompositionMode_DestinationIn:
521
        funcs.glBlendFunc(GL_ZERO, GL_SRC_ALPHA);
522
523
        break;
    case QPainter::CompositionMode_SourceOut:
524
        funcs.glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ZERO);
525
526
        break;
    case QPainter::CompositionMode_DestinationOut:
527
        funcs.glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_ALPHA);
528
529
        break;
    case QPainter::CompositionMode_SourceAtop:
530
        funcs.glBlendFunc(GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
531
532
        break;
    case QPainter::CompositionMode_DestinationAtop:
533
        funcs.glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA);
534
535
        break;
    case QPainter::CompositionMode_Xor:
536
        funcs.glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
537
538
        break;
    case QPainter::CompositionMode_Plus:
539
        funcs.glBlendFunc(GL_ONE, GL_ONE);
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
        break;
    default:
        qWarning("Unsupported composition mode");
        break;
    }

    compositionModeDirty = false;
}

static inline void setCoords(GLfloat *coords, const QOpenGLRect &rect)
{
    coords[0] = rect.left;
    coords[1] = rect.top;
    coords[2] = rect.right;
    coords[3] = rect.top;
    coords[4] = rect.right;
    coords[5] = rect.bottom;
    coords[6] = rect.left;
    coords[7] = rect.bottom;
}

void QOpenGL2PaintEngineExPrivate::drawTexture(const QOpenGLRect& dest, const QOpenGLRect& src, const QSize &textureSize, bool opaque, bool pattern)
{
    // Setup for texture drawing
    currentBrush = noBrush;

    if (snapToPixelGrid) {
        snapToPixelGrid = false;
        matrixDirty = true;
    }

    if (prepareForDraw(opaque))
        shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::ImageTexture), QT_IMAGE_TEXTURE_UNIT);

    if (pattern) {
        QColor col = qt_premultiplyColor(q->state()->pen.color(), (GLfloat)q->state()->opacity);
        shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::PatternColor), col);
    }

    GLfloat dx = 1.0 / textureSize.width();
    GLfloat dy = 1.0 / textureSize.height();

    QOpenGLRect srcTextureRect(src.left*dx, src.top*dy, src.right*dx, src.bottom*dy);

    setCoords(staticVertexCoordinateArray, dest);
    setCoords(staticTextureCoordinateArray, srcTextureRect);

587
588
589
590
591
592
    setVertexAttribArrayEnabled(QT_VERTEX_COORDS_ATTR, true);
    setVertexAttribArrayEnabled(QT_TEXTURE_COORDS_ATTR, true);

    uploadData(QT_VERTEX_COORDS_ATTR, staticVertexCoordinateArray, 8);
    uploadData(QT_TEXTURE_COORDS_ATTR, staticTextureCoordinateArray, 8);

593
    funcs.glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
}

void QOpenGL2PaintEngineEx::beginNativePainting()
{
    Q_D(QOpenGL2PaintEngineEx);
    ensureActive();
    d->transferMode(BrushDrawingMode);

    d->nativePaintingActive = true;

    d->funcs.glUseProgram(0);

    // Disable all the vertex attribute arrays:
    for (int i = 0; i < QT_GL_VERTEX_ARRAY_TRACKED_COUNT; ++i)
        d->funcs.glDisableVertexAttribArray(i);

610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
#if !defined(QT_OPENGL_ES_2) && !defined(QT_OPENGL_DYNAMIC)
    Q_ASSERT(QOpenGLContext::currentContext());
    const QOpenGLContext *ctx = d->ctx;
    const QSurfaceFormat &fmt = d->device->context()->format();
    if (fmt.majorVersion() < 3 || (fmt.majorVersion() == 3 && fmt.minorVersion() < 1)
        || (fmt.majorVersion() == 3 && fmt.minorVersion() == 1 && ctx->hasExtension(QByteArrayLiteral("GL_ARB_compatibility")))
        || fmt.profile() == QSurfaceFormat::CompatibilityProfile)
    {
        // be nice to people who mix OpenGL 1.x code with QPainter commands
        // by setting modelview and projection matrices to mirror the GL 1
        // paint engine
        const QTransform& mtx = state()->matrix;

        float mv_matrix[4][4] =
            {
                { float(mtx.m11()), float(mtx.m12()),     0, float(mtx.m13()) },
                { float(mtx.m21()), float(mtx.m22()),     0, float(mtx.m23()) },
                {                0,                0,     1,                0 },
                {  float(mtx.dx()),  float(mtx.dy()),     0, float(mtx.m33()) }
            };

        const QSize sz = d->device->size();

        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(0, sz.width(), sz.height(), 0, -999999, 999999);

        glMatrixMode(GL_MODELVIEW);
        glLoadMatrixf(&mv_matrix[0][0]);
639
    }
Laszlo Agocs's avatar
Laszlo Agocs committed
640
#endif // QT_OPENGL_ES_2
641

642
643
644
645
646
647
    d->resetGLState();

    // We don't know what texture units and textures the native painting
    // will activate and bind, so we can't assume anything when we return
    // from the native painting.
    d->lastTextureUnitUsed = QT_UNKNOWN_TEXTURE_UNIT;
648
    d->lastTextureUsed = GLuint(-1);
649

650
651
652
653
654
655
656
657
658
    d->dirtyStencilRegion = QRect(0, 0, d->width, d->height);

    d->shaderManager->setDirty();

    d->needsSync = true;
}

void QOpenGL2PaintEngineExPrivate::resetGLState()
{
659
660
    activateTextureUnit(QT_DEFAULT_TEXTURE_UNIT);

661
662
663
664
665
666
    funcs.glDisable(GL_BLEND);
    funcs.glDisable(GL_STENCIL_TEST);
    funcs.glDisable(GL_DEPTH_TEST);
    funcs.glDisable(GL_SCISSOR_TEST);
    funcs.glDepthMask(true);
    funcs.glDepthFunc(GL_LESS);
667
    funcs.glClearDepthf(1);
668
669
670
    funcs.glStencilMask(0xff);
    funcs.glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
    funcs.glStencilFunc(GL_ALWAYS, 0, 0xff);
671
672
673
    setVertexAttribArrayEnabled(QT_TEXTURE_COORDS_ATTR, false);
    setVertexAttribArrayEnabled(QT_VERTEX_COORDS_ATTR, false);
    setVertexAttribArrayEnabled(QT_OPACITY_ATTR, false);
Laszlo Agocs's avatar
Laszlo Agocs committed
674
    if (!QOpenGLContext::currentContext()->isOpenGLES()) {
Laszlo Agocs's avatar
Laszlo Agocs committed
675
676
677
678
        // gl_Color, corresponding to vertex attribute 3, may have been changed
        float color[] = { 1.0f, 1.0f, 1.0f, 1.0f };
        funcs.glVertexAttrib4fv(3, color);
    }
679
680
681
682
683
    if (vao.isCreated()) {
        vao.release();
        funcs.glBindBuffer(GL_ARRAY_BUFFER, 0);
        funcs.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    }
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
}

void QOpenGL2PaintEngineEx::endNativePainting()
{
    Q_D(QOpenGL2PaintEngineEx);
    d->needsSync = true;
    d->nativePaintingActive = false;
}

void QOpenGL2PaintEngineEx::invalidateState()
{
    Q_D(QOpenGL2PaintEngineEx);
    d->needsSync = true;
}

bool QOpenGL2PaintEngineEx::isNativePaintingActive() const {
    Q_D(const QOpenGL2PaintEngineEx);
    return d->nativePaintingActive;
}

void QOpenGL2PaintEngineExPrivate::transferMode(EngineMode newMode)
{
    if (newMode == mode)
        return;

    if (newMode == TextDrawingMode) {
        shaderManager->setHasComplexGeometry(true);
    } else {
        shaderManager->setHasComplexGeometry(false);
    }

    if (newMode == ImageDrawingMode) {
716
717
        uploadData(QT_VERTEX_COORDS_ATTR, staticVertexCoordinateArray, 8);
        uploadData(QT_TEXTURE_COORDS_ATTR, staticTextureCoordinateArray, 8);
718
719
    }

720
    if (newMode == ImageArrayDrawingMode || newMode == ImageOpacityArrayDrawingMode) {
721
722
        uploadData(QT_VERTEX_COORDS_ATTR, (GLfloat*)vertexCoordinateArray.data(), vertexCoordinateArray.vertexCount() * 2);
        uploadData(QT_TEXTURE_COORDS_ATTR, (GLfloat*)textureCoordinateArray.data(), textureCoordinateArray.vertexCount() * 2);
723
724

        if (newMode == ImageOpacityArrayDrawingMode)
725
            uploadData(QT_OPACITY_ATTR, (GLfloat*)opacityArray.data(), opacityArray.size());
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
    }

    // This needs to change when we implement high-quality anti-aliasing...
    if (newMode != TextDrawingMode)
        shaderManager->setMaskType(QOpenGLEngineShaderManager::NoMask);

    mode = newMode;
}

struct QOpenGL2PEVectorPathCache
{
#ifdef QT_OPENGL_CACHE_AS_VBOS
    GLuint vbo;
    GLuint ibo;
#else
    float *vertices;
    void *indices;
#endif
    int vertexCount;
    int indexCount;
    GLenum primitiveType;
    qreal iscale;
748
    QVertexIndexVector::Type indexType;
749
750
751
752
753
754
755
756
757
758
759
760
};

void QOpenGL2PaintEngineExPrivate::cleanupVectorPath(QPaintEngineEx *engine, void *data)
{
    QOpenGL2PEVectorPathCache *c = (QOpenGL2PEVectorPathCache *) data;
#ifdef QT_OPENGL_CACHE_AS_VBOS
    Q_ASSERT(engine->type() == QPaintEngine::OpenGL2);
    static_cast<QOpenGL2PaintEngineEx *>(engine)->d_func()->unusedVBOSToClean << c->vbo;
    if (c->ibo)
        d->unusedIBOSToClean << c->ibo;
#else
    Q_UNUSED(engine);
761
762
    free(c->vertices);
    free(c->indices);
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
#endif
    delete c;
}

// Assumes everything is configured for the brush you want to use
void QOpenGL2PaintEngineExPrivate::fill(const QVectorPath& path)
{
    transferMode(BrushDrawingMode);

    if (snapToPixelGrid) {
        snapToPixelGrid = false;
        matrixDirty = true;
    }

    // Might need to call updateMatrix to re-calculate inverseScale
    if (matrixDirty)
        updateMatrix();

781
782
    const bool supportsElementIndexUint = funcs.hasOpenGLExtension(QOpenGLExtensions::ElementIndexUint);

783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
    const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());

    // Check to see if there's any hints
    if (path.shape() == QVectorPath::RectangleHint) {
        QOpenGLRect rect(points[0].x(), points[0].y(), points[2].x(), points[2].y());
        prepareForDraw(currentBrush.isOpaque());
        composite(rect);
    } else if (path.isConvex()) {

        if (path.isCacheable()) {
            QVectorPath::CacheEntry *data = path.lookupCacheData(q);
            QOpenGL2PEVectorPathCache *cache;

            bool updateCache = false;

            if (data) {
                cache = (QOpenGL2PEVectorPathCache *) data->data;
                // Check if scale factor is exceeded for curved paths and generate curves if so...
                if (path.isCurved()) {
                    qreal scaleFactor = cache->iscale / inverseScale;
                    if (scaleFactor < 0.5 || scaleFactor > 2.0) {
#ifdef QT_OPENGL_CACHE_AS_VBOS
                        glDeleteBuffers(1, &cache->vbo);
                        cache->vbo = 0;
                        Q_ASSERT(cache->ibo == 0);
#else
809
                        free(cache->vertices);
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
                        Q_ASSERT(cache->indices == 0);
#endif
                        updateCache = true;
                    }
                }
            } else {
                cache = new QOpenGL2PEVectorPathCache;
                data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
                updateCache = true;
            }

            // Flatten the path at the current scale factor and fill it into the cache struct.
            if (updateCache) {
                vertexCoordinateArray.clear();
                vertexCoordinateArray.addPath(path, inverseScale, false);
                int vertexCount = vertexCoordinateArray.vertexCount();
                int floatSizeInBytes = vertexCount * 2 * sizeof(float);
                cache->vertexCount = vertexCount;
                cache->indexCount = 0;
                cache->primitiveType = GL_TRIANGLE_FAN;
                cache->iscale = inverseScale;
#ifdef QT_OPENGL_CACHE_AS_VBOS
832
833
834
                funcs.glGenBuffers(1, &cache->vbo);
                funcs.glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
                funcs.glBufferData(GL_ARRAY_BUFFER, floatSizeInBytes, vertexCoordinateArray.data(), GL_STATIC_DRAW);
835
836
                cache->ibo = 0;
#else
837
                cache->vertices = (float *) malloc(floatSizeInBytes);
838
839
840
841
842
843
844
                memcpy(cache->vertices, vertexCoordinateArray.data(), floatSizeInBytes);
                cache->indices = 0;
#endif
            }

            prepareForDraw(currentBrush.isOpaque());
#ifdef QT_OPENGL_CACHE_AS_VBOS
845
            funcs.glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
846
            uploadData(QT_VERTEX_COORD_ATTR, 0, cache->vertexCount);
847
848
            setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, 0);
#else
849
            uploadData(QT_VERTEX_COORDS_ATTR, cache->vertices, cache->vertexCount * 2);
850
#endif
851
            funcs.glDrawArrays(cache->primitiveType, 0, cache->vertexCount);
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889

        } else {
      //        printf(" - Marking path as cachable...\n");
            // Tag it for later so that if the same path is drawn twice, it is assumed to be static and thus cachable
            path.makeCacheable();
            vertexCoordinateArray.clear();
            vertexCoordinateArray.addPath(path, inverseScale, false);
            prepareForDraw(currentBrush.isOpaque());
            drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN);
        }

    } else {
        bool useCache = path.isCacheable();
        if (useCache) {
            QRectF bbox = path.controlPointRect();
            // If the path doesn't fit within these limits, it is possible that the triangulation will fail.
            useCache &= (bbox.left() > -0x8000 * inverseScale)
                     && (bbox.right() < 0x8000 * inverseScale)
                     && (bbox.top() > -0x8000 * inverseScale)
                     && (bbox.bottom() < 0x8000 * inverseScale);
        }

        if (useCache) {
            QVectorPath::CacheEntry *data = path.lookupCacheData(q);
            QOpenGL2PEVectorPathCache *cache;

            bool updateCache = false;

            if (data) {
                cache = (QOpenGL2PEVectorPathCache *) data->data;
                // Check if scale factor is exceeded for curved paths and generate curves if so...
                if (path.isCurved()) {
                    qreal scaleFactor = cache->iscale / inverseScale;
                    if (scaleFactor < 0.5 || scaleFactor > 2.0) {
#ifdef QT_OPENGL_CACHE_AS_VBOS
                        glDeleteBuffers(1, &cache->vbo);
                        glDeleteBuffers(1, &cache->ibo);
#else
890
891
                        free(cache->vertices);
                        free(cache->indices);
892
893
894
895
896
897
898
899
900
901
902
903
#endif
                        updateCache = true;
                    }
                }
            } else {
                cache = new QOpenGL2PEVectorPathCache;
                data = const_cast<QVectorPath &>(path).addCacheData(q, cache, cleanupVectorPath);
                updateCache = true;
            }

            // Flatten the path at the current scale factor and fill it into the cache struct.
            if (updateCache) {
904
                QTriangleSet polys = qTriangulate(path, QTransform().scale(1 / inverseScale, 1 / inverseScale), 1, supportsElementIndexUint);
905
906
907
908
                cache->vertexCount = polys.vertices.size() / 2;
                cache->indexCount = polys.indices.size();
                cache->primitiveType = GL_TRIANGLES;
                cache->iscale = inverseScale;
909
                cache->indexType = polys.indices.type();
910
#ifdef QT_OPENGL_CACHE_AS_VBOS
911
912
913
914
                funcs.glGenBuffers(1, &cache->vbo);
                funcs.glGenBuffers(1, &cache->ibo);
                funcs.glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
                funcs.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cache->ibo);
915

916
                if (polys.indices.type() == QVertexIndexVector::UnsignedInt)
917
918
919
920
921
922
923
924
925
                    funcs.glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint32) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);
                else
                    funcs.glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quint16) * polys.indices.size(), polys.indices.data(), GL_STATIC_DRAW);

                QVarLengthArray<float> vertices(polys.vertices.size());
                for (int i = 0; i < polys.vertices.size(); ++i)
                    vertices[i] = float(inverseScale * polys.vertices.at(i));
                funcs.glBufferData(GL_ARRAY_BUFFER, sizeof(float) * vertices.size(), vertices.data(), GL_STATIC_DRAW);
#else
926
                cache->vertices = (float *) malloc(sizeof(float) * polys.vertices.size());
927
                if (polys.indices.type() == QVertexIndexVector::UnsignedInt) {
928
                    cache->indices = (quint32 *) malloc(sizeof(quint32) * polys.indices.size());
929
930
                    memcpy(cache->indices, polys.indices.data(), sizeof(quint32) * polys.indices.size());
                } else {
931
                    cache->indices = (quint16 *) malloc(sizeof(quint16) * polys.indices.size());
932
933
934
935
936
937
938
939
940
                    memcpy(cache->indices, polys.indices.data(), sizeof(quint16) * polys.indices.size());
                }
                for (int i = 0; i < polys.vertices.size(); ++i)
                    cache->vertices[i] = float(inverseScale * polys.vertices.at(i));
#endif
            }

            prepareForDraw(currentBrush.isOpaque());
#ifdef QT_OPENGL_CACHE_AS_VBOS
941
942
            funcs.glBindBuffer(GL_ARRAY_BUFFER, cache->vbo);
            funcs.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cache->ibo);
943
            uploadData(QT_VERTEX_COORDS_ATTR, 0, cache->vertexCount);
944
            setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, 0);
945
            if (cache->indexType == QVertexIndexVector::UnsignedInt)
946
                funcs.glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_INT, 0);
947
            else
948
949
950
                funcs.glDrawElements(cache->primitiveType, cache->indexCount, GL_UNSIGNED_SHORT, 0);
            funcs.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
            funcs.glBindBuffer(GL_ARRAY_BUFFER, 0);
951
#else
952
953
954
955
            uploadData(QT_VERTEX_COORDS_ATTR, cache->vertices, cache->vertexCount * 2);
            const GLenum indexValueType = cache->indexType == QVertexIndexVector::UnsignedInt ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT;
            const bool useIndexVbo = uploadIndexData(cache->indices, indexValueType, cache->indexCount);
            funcs.glDrawElements(cache->primitiveType, cache->indexCount, indexValueType, useIndexVbo ? nullptr : cache->indices);
956
957
958
959
960
961
962
#endif

        } else {
      //        printf(" - Marking path as cachable...\n");
            // Tag it for later so that if the same path is drawn twice, it is assumed to be static and thus cachable
            path.makeCacheable();

963
            if (device->context()->format().stencilBufferSize() <= 0) {
964
965
966
967
968
969
970
971
972
                // If there is no stencil buffer, triangulate the path instead.

                QRectF bbox = path.controlPointRect();
                // If the path doesn't fit within these limits, it is possible that the triangulation will fail.
                bool withinLimits = (bbox.left() > -0x8000 * inverseScale)
                                  && (bbox.right() < 0x8000 * inverseScale)
                                  && (bbox.top() > -0x8000 * inverseScale)
                                  && (bbox.bottom() < 0x8000 * inverseScale);
                if (withinLimits) {
973
                    QTriangleSet polys = qTriangulate(path, QTransform().scale(1 / inverseScale, 1 / inverseScale), 1, supportsElementIndexUint);
974
975
976
977
978
979

                    QVarLengthArray<float> vertices(polys.vertices.size());
                    for (int i = 0; i < polys.vertices.size(); ++i)
                        vertices[i] = float(inverseScale * polys.vertices.at(i));

                    prepareForDraw(currentBrush.isOpaque());
980
981
982
983
                    uploadData(QT_VERTEX_COORDS_ATTR, vertices.constData(), vertices.size());
                    const GLenum indexValueType = funcs.hasOpenGLExtension(QOpenGLExtensions::ElementIndexUint) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT;
                    const bool useIndexVbo = uploadIndexData(polys.indices.data(), indexValueType, polys.indices.size());
                    funcs.glDrawElements(GL_TRIANGLES, polys.indices.size(), indexValueType, useIndexVbo ? nullptr : polys.indices.data());
984
985
986
987
988
989
990
991
992
993
994
995
996
                } else {
                    // We can't handle big, concave painter paths with OpenGL without stencil buffer.
                    qWarning("Painter path exceeds +/-32767 pixels.");
                }
                return;
            }

            // The path is too complicated & needs the stencil technique
            vertexCoordinateArray.clear();
            vertexCoordinateArray.addPath(path, inverseScale, false);

            fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill());

997
998
            funcs.glStencilMask(0xff);
            funcs.glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
999
1000
1001

            if (q->state()->clipTestEnabled) {
                // Pass when high bit is set, replace stencil value with current clip
1002
                funcs.glStencilFunc(GL_NOTEQUAL, q->state()->currentClip, GL_STENCIL_HIGH_BIT);
1003
1004
            } else if (path.hasWindingFill()) {
                // Pass when any bit is set, replace stencil value with 0
1005
                funcs.glStencilFunc(GL_NOTEQUAL, 0, 0xff);
1006
1007
            } else {
                // Pass when high bit is set, replace stencil value with 0
1008
                funcs.glStencilFunc(GL_NOTEQUAL, 0, GL_STENCIL_HIGH_BIT);
1009
1010
1011
1012
1013
            }
            prepareForDraw(currentBrush.isOpaque());

            // Stencil the brush onto the dest buffer
            composite(vertexCoordinateArray.boundingRect());
1014
            funcs.glStencilMask(0);
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
            updateClipScissorTest();
        }
    }
}


void QOpenGL2PaintEngineExPrivate::fillStencilWithVertexArray(const float *data,
                                                          int count,
                                                          int *stops,
                                                          int stopCount,
                                                          const QOpenGLRect &bounds,
                                                          StencilFillMode mode)
{
    Q_ASSERT(count || stops);

//     qDebug("QOpenGL2PaintEngineExPrivate::fillStencilWithVertexArray()");
1031
    funcs.glStencilMask(0xff); // Enable stencil writes
1032
1033

    if (dirtyStencilRegion.intersects(currentScissorBounds)) {
1034
        const QRegion clearRegion = dirtyStencilRegion.intersected(currentScissorBounds);
1035
        funcs.glClearStencil(0); // Clear to zero
1036
        for (const QRect &rect : clearRegion) {
1037
#ifndef QT_GL_NO_SCISSOR_TEST
1038
            setScissor(rect);
1039
#endif
1040
            funcs.glClear(GL_STENCIL_BUFFER_BIT);
1041
1042
1043
1044
1045
1046
1047
1048
1049
        }

        dirtyStencilRegion -= currentScissorBounds;

#ifndef QT_GL_NO_SCISSOR_TEST
        updateClipScissorTest();
#endif
    }

1050
    funcs.glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); // Disable color writes
1051
    useSimpleShader();
1052
    funcs.glEnable(GL_STENCIL_TEST); // For some reason, this has to happen _after_ the simple shader is use()'d
1053
1054
1055
1056
1057

    if (mode == WindingFillMode) {
        Q_ASSERT(stops && !count);
        if (q->state()->clipTestEnabled) {
            // Flatten clip values higher than current clip, and set high bit to match current clip
1058
1059
            funcs.glStencilFunc(GL_LEQUAL, GL_STENCIL_HIGH_BIT | q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
            funcs.glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
1060
1061
            composite(bounds);

1062
            funcs.glStencilFunc(GL_EQUAL, GL_STENCIL_HIGH_BIT, GL_STENCIL_HIGH_BIT);
1063
1064
        } else if (!stencilClean) {
            // Clear stencil buffer within bounding rect
1065
1066
            funcs.glStencilFunc(GL_ALWAYS, 0, 0xff);
            funcs.glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO);
1067
1068
1069
1070
1071
1072
1073
            composite(bounds);
        }

        // Inc. for front-facing triangle
        funcs.glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_INCR_WRAP, GL_INCR_WRAP);
        // Dec. for back-facing "holes"
        funcs.glStencilOpSeparate(GL_BACK, GL_KEEP, GL_DECR_WRAP, GL_DECR_WRAP);
1074
        funcs.glStencilMask(~GL_STENCIL_HIGH_BIT);
1075
1076
1077
1078
        drawVertexArrays(data, stops, stopCount, GL_TRIANGLE_FAN);

        if (q->state()->clipTestEnabled) {
            // Clear high bit of stencil outside of path
1079
1080
1081
            funcs.glStencilFunc(GL_EQUAL, q->state()->currentClip, ~GL_STENCIL_HIGH_BIT);
            funcs.glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
            funcs.glStencilMask(GL_STENCIL_HIGH_BIT);
1082
1083
1084
            composite(bounds);
        }
    } else if (mode == OddEvenFillMode) {
1085
1086
        funcs.glStencilMask(GL_STENCIL_HIGH_BIT);
        funcs.glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT); // Simply invert the stencil bit
1087
1088
1089
1090
        drawVertexArrays(data, stops, stopCount, GL_TRIANGLE_FAN);

    } else { // TriStripStrokeFillMode
        Q_ASSERT(count && !stops); // tristrips generated directly, so no vertexArray or stops
1091
        funcs.glStencilMask(GL_STENCIL_HIGH_BIT);
1092
#if 0
1093
        funcs.glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT); // Simply invert the stencil bit
1094
        setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, data);
1095
        funcs.glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
1096
1097
#else

1098
        funcs.glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
1099
        if (q->state()->clipTestEnabled) {
1100
1101
            funcs.glStencilFunc(GL_LEQUAL, q->state()->currentClip | GL_STENCIL_HIGH_BIT,
                                ~GL_STENCIL_HIGH_BIT);
1102
        } else {
1103
            funcs.glStencilFunc(GL_ALWAYS, GL_STENCIL_HIGH_BIT, 0xff);
1104
        }
1105
1106

        uploadData(QT_VERTEX_COORDS_ATTR, data, count * 2);
1107
        funcs.glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
1108
1109
1110
1111
#endif
    }

    // Enable color writes & disable stencil writes
1112
    funcs.glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
}

/*
    If the maximum value in the stencil buffer is GL_STENCIL_HIGH_BIT - 1,
    restore the stencil buffer to a pristine state.  The current clip region
    is set to 1, and the rest to 0.
*/
void QOpenGL2PaintEngineExPrivate::resetClipIfNeeded()
{
    if (maxClip != (GL_STENCIL_HIGH_BIT - 1))
        return;

    Q_Q(QOpenGL2PaintEngineEx);

    useSimpleShader();
1128
1129
    funcs.glEnable(GL_STENCIL_TEST);
    funcs.glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1130
1131
1132
1133
1134

    QRectF bounds = q->state()->matrix.inverted().mapRect(QRectF(0, 0, width, height));
    QOpenGLRect rect(bounds.left(), bounds.top(), bounds.right(), bounds.bottom());

    // Set high bit on clip region
1135
1136
1137
    funcs.glStencilFunc(GL_LEQUAL, q->state()->currentClip, 0xff);
    funcs.glStencilOp(GL_KEEP, GL_INVERT, GL_INVERT);
    funcs.glStencilMask(GL_STENCIL_HIGH_BIT);
1138
1139
1140
    composite(rect);

    // Reset clipping to 1 and everything else to zero
1141
1142
1143
    funcs.glStencilFunc(GL_NOTEQUAL, 0x01, GL_STENCIL_HIGH_BIT);
    funcs.glStencilOp(GL_ZERO, GL_REPLACE, GL_REPLACE);
    funcs.glStencilMask(0xff);
1144
1145
1146
1147
1148
1149
1150
    composite(rect);

    q->state()->currentClip = 1;
    q->state()->canRestoreClip = false;

    maxClip = 1;

1151
1152
    funcs.glStencilMask(0x0);
    funcs.glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1153
1154
}

1155
1156
1157
1158
bool QOpenGL2PaintEngineExPrivate::prepareForCachedGlyphDraw(const QFontEngineGlyphCache &cache)
{
    Q_Q(QOpenGL2PaintEngineEx);

1159
1160
    Q_ASSERT(cache.transform().type() <= QTransform::TxScale);

1161
1162
1163
1164
1165
1166
1167
1168
    QTransform &transform = q->state()->matrix;
    transform.scale(1.0 / cache.transform().m11(), 1.0 / cache.transform().m22());
    bool ret = prepareForDraw(false);
    transform.scale(cache.transform().m11(), cache.transform().m22());

    return ret;
}

1169
1170
bool QOpenGL2PaintEngineExPrivate::prepareForDraw(bool srcPixelsAreOpaque)
{
1171
    if (brushTextureDirty && (mode == TextDrawingMode || mode == BrushDrawingMode))
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
        updateBrushTexture();

    if (compositionModeDirty)
        updateCompositionMode();

    if (matrixDirty)
        updateMatrix();

    const bool stateHasOpacity = q->state()->opacity < 0.99f;
    if (q->state()->composition_mode == QPainter::CompositionMode_Source
        || (q->state()->composition_mode == QPainter::CompositionMode_SourceOver
            && srcPixelsAreOpaque && !stateHasOpacity))
    {
1185
        funcs.glDisable(GL_BLEND);
1186
    } else {
1187
        funcs.glEnable(GL_BLEND);
1188
1189
1190
    }

    QOpenGLEngineShaderManager::OpacityMode opacityMode;
1191
    if (mode == ImageOpacityArrayDrawingMode) {
1192
1193
1194
1195
        opacityMode = QOpenGLEngineShaderManager::AttributeOpacity;
    } else {
        opacityMode = stateHasOpacity ? QOpenGLEngineShaderManager::UniformOpacity
                                      : QOpenGLEngineShaderManager::NoOpacity;
1196
        if (stateHasOpacity && (mode != ImageDrawingMode && mode != ImageArrayDrawingMode)) {
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
            // Using a brush
            bool brushIsPattern = (currentBrush.style() >= Qt::Dense1Pattern) &&
                                  (currentBrush.style() <= Qt::DiagCrossPattern);

            if ((currentBrush.style() == Qt::SolidPattern) || brushIsPattern)
                opacityMode = QOpenGLEngineShaderManager::NoOpacity; // Global opacity handled by srcPixel shader
        }
    }
    shaderManager->setOpacityMode(opacityMode);

    bool changed = shaderManager->useCorrectShaderProg();
    // If the shader program needs changing, we change it and mark all uniforms as dirty
    if (changed) {
        // The shader program has changed so mark all uniforms as dirty:
        brushUniformsDirty = true;
        opacityUniformDirty = true;
        matrixUniformDirty = true;
    }

1216
    if (brushUniformsDirty && (mode == TextDrawingMode || mode == BrushDrawingMode))
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
        updateBrushUniforms();

    if (opacityMode == QOpenGLEngineShaderManager::UniformOpacity && opacityUniformDirty) {
        shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::GlobalOpacity), (GLfloat)q->state()->opacity);
        opacityUniformDirty = false;
    }

    if (matrixUniformDirty && shaderManager->hasComplexGeometry()) {
        shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::Matrix),
                                                         pmvMatrix);
        matrixUniformDirty = false;
    }

    return changed;
}

void QOpenGL2PaintEngineExPrivate::composite(const QOpenGLRect& boundingRect)
{
    setCoords(staticVertexCoordinateArray, boundingRect);
1236
1237

    uploadData(QT_VERTEX_COORDS_ATTR, staticVertexCoordinateArray, 8);
1238
    funcs.glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1239
1240
1241
1242
1243
1244
1245
}

// Draws the vertex array as a set of <vertexArrayStops.size()> triangle fans.
void QOpenGL2PaintEngineExPrivate::drawVertexArrays(const float *data, int *stops, int stopCount,
                                                GLenum primitive)
{
    // Now setup the pointer to the vertex array:
1246
    uploadData(QT_VERTEX_COORDS_ATTR, data, stops[stopCount-1] * 2);
1247
1248
1249
1250

    int previousStop = 0;
    for (int i=0; i<stopCount; ++i) {
        int stop = stops[i];
1251

1252
        funcs.glDrawArrays(primitive, previousStop, stop - previousStop);
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
        previousStop = stop;
    }
}

/////////////////////////////////// Public Methods //////////////////////////////////////////

QOpenGL2PaintEngineEx::QOpenGL2PaintEngineEx()
    : QPaintEngineEx(*(new QOpenGL2PaintEngineExPrivate(this)))
{
}

QOpenGL2PaintEngineEx::~QOpenGL2PaintEngineEx()
{
}

void QOpenGL2PaintEngineEx::fill(const QVectorPath &path, const QBrush &brush)
{
    Q_D(QOpenGL2PaintEngineEx);

    if (qbrush_style(brush) == Qt::NoBrush)
        return;
    ensureActive();
    d->setBrush(brush);
    d->fill(path);
}

Q_GUI_EXPORT bool qt_scaleForTransform(const QTransform &transform, qreal *scale); // qtransform.cpp


void QOpenGL2PaintEngineEx::stroke(const QVectorPath &path, const QPen &pen)
{
    Q_D(QOpenGL2PaintEngineEx);

    const QBrush &penBrush = qpen_brush(pen);
    if (qpen_style(pen) == Qt::NoPen || qbrush_style(penBrush) == Qt::NoBrush)
        return;

    QOpenGL2PaintEngineState *s = state();
1291
    if (qt_pen_is_cosmetic(pen, state()->renderHints) && !qt_scaleForTransform(s->transform(), 0)) {
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
        // QTriangulatingStroker class is not meant to support cosmetically sheared strokes.
        QPaintEngineEx::stroke(path, pen);
        return;
    }

    ensureActive();
    d->setBrush(penBrush);
    d->stroke(path, pen);
}

void QOpenGL2PaintEngineExPrivate::stroke(const QVectorPath &path, const QPen &pen)
{
    const QOpenGL2PaintEngineState *s = q->state();
    if (snapToPixelGrid) {
        snapToPixelGrid = false;
        matrixDirty = true;
    }

    const Qt::PenStyle penStyle = qpen_style(pen);
    const QBrush &penBrush = qpen_brush(pen);
    const bool opaque = penBrush.isOpaque() && s->opacity > 0.99;

    transferMode(BrushDrawingMode);

    // updateMatrix() is responsible for setting the inverse scale on
    // the strokers, so we need to call it here and not wait for
    // prepareForDraw() down below.
    updateMatrix();

    QRectF clip = q->state()->matrix.inverted().mapRect(q->state()->clipEnabled
                                                        ? q->state()->rectangleClip
                                                        : QRectF(0, 0, width, height));

    if (penStyle == Qt::SolidLine) {
1326
        stroker.process(path, pen, clip, s->renderHints);
1327
1328

    } else { // Some sort of dash
1329
        dasher.process(path, pen, clip, s->renderHints);
1330
1331
1332

        QVectorPath dashStroke(dasher.points(),
                               dasher.elementCount(),
1333
                               dasher.elementTypes());
1334
        stroker.process(dashStroke, pen, clip, s->renderHints);
1335
1336
1337
1338
1339
1340
1341
1342
    }

    if (!stroker.vertexCount())
        return;

    if (opaque) {
        prepareForDraw(opaque);

1343
1344
        uploadData(QT_VERTEX_COORDS_ATTR, stroker.vertices(), stroker.vertexCount());
        funcs.glDrawArrays(GL_TRIANGLE_STRIP, 0, stroker.vertexCount() / 2);
1345
1346
1347
1348
1349
1350
1351
1352
    } else {
        qreal width = qpen_widthf(pen) / 2;
        if (width == 0)
            width = 0.5;
        qreal extra = pen.joinStyle() == Qt::MiterJoin
                      ? qMax(pen.miterLimit() * width, width)
                      : width;

1353
        if (qt_pen_is_cosmetic(pen, q->state()->renderHints))
1354
1355
1356
1357
1358
1359
1360
            extra = extra * inverseScale;

        QRectF bounds = path.controlPointRect().adjusted(-extra, -extra, extra, extra);

        fillStencilWithVertexArray(stroker.vertices(), stroker.vertexCount() / 2,
                                      0, 0, bounds, QOpenGL2PaintEngineExPrivate::TriStripStrokeFillMode);

1361
        funcs.glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
1362
1363

        // Pass when any bit is set, replace stencil value with 0
1364
        funcs.glStencilFunc(GL_NOTEQUAL, 0, GL_STENCIL_HIGH_BIT);
1365
1366
1367
1368
1369
        prepareForDraw(false);

        // Stencil the brush onto the dest buffer
        composite(bounds);

1370
        funcs.glStencilMask(0);
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402

        updateClipScissorTest();
    }
}

void QOpenGL2PaintEngineEx::penChanged() { }
void QOpenGL2PaintEngineEx::brushChanged() { }
void QOpenGL2PaintEngineEx::brushOriginChanged() { }

void QOpenGL2PaintEngineEx::opacityChanged()
{
//    qDebug("QOpenGL2PaintEngineEx::opacityChanged()");
    Q_D(QOpenGL2PaintEngineEx);
    state()->opacityChanged = true;

    Q_ASSERT(d->shaderManager);
    d->brushUniformsDirty = true;
    d->opacityUniformDirty = true;
}

void QOpenGL2PaintEngineEx::compositionModeChanged()
{
//     qDebug("QOpenGL2PaintEngineEx::compositionModeChanged()");
    Q_D(QOpenGL2PaintEngineEx);
    state()->compositionModeChanged = true;
    d->compositionModeDirty = true;
}

void QOpenGL2PaintEngineEx::renderHintsChanged()
{
    state()->renderHintsChanged = true;

Laszlo Agocs's avatar
Laszlo Agocs committed
1403
#ifndef QT_OPENGL_ES_2
Laszlo Agocs's avatar
Laszlo Agocs committed
1404
    if (!QOpenGLContext::currentContext()->isOpenGLES()) {
1405
        Q_D(QOpenGL2PaintEngineEx);
Laszlo Agocs's avatar
Laszlo Agocs committed
1406
1407
        if ((state()->renderHints & QPainter::Antialiasing)
            || (state()->renderHints & QPainter::HighQualityAntialiasing))
1408
            d->funcs.glEnable(GL_MULTISAMPLE);
Laszlo Agocs's avatar
Laszlo Agocs committed
1409
        else
1410
            d->funcs.glDisable(GL_MULTISAMPLE);
Laszlo Agocs's avatar
Laszlo Agocs committed
1411
1412
    }
#endif // QT_OPENGL_ES_2
1413
1414

    Q_D(QOpenGL2PaintEngineEx);
1415
1416
1417
1418

    // This is a somewhat sneaky way of conceptually making the next call to
    // updateTexture() use FoceUpdate for the TextureUpdateMode. We need this
    // as new render hints may require updating the filter mode.
1419
    d->lastTextureUsed = GLuint(-1);
1420

1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
    d->brushTextureDirty = true;
//    qDebug("QOpenGL2PaintEngineEx::renderHintsChanged() not implemented!");
}

void QOpenGL2PaintEngineEx::transformChanged()
{
    Q_D(QOpenGL2PaintEngineEx);
    d->matrixDirty = true;
    state()->matrixChanged = true;
}


static const QRectF scaleRect(const QRectF &r, qreal sx, qreal sy)
{
    return QRectF(r.x() * sx, r.y() * sy, r.width() * sx, r.height() * sy);
}

void QOpenGL2PaintEngineEx::drawPixmap(const QRectF& dest, const QPixmap & pixmap, const QRectF & src)
{
    Q_D(QOpenGL2PaintEngineEx);
    QOpenGLContext *ctx = d->ctx;

1443
1444
1445
1446
1447
    // Draw pixmaps that are really images as images since drawImage has
    // better handling of non-default image formats.
    if (pixmap.paintEngine()->type() == QPaintEngine::Raster && !pixmap.isQBitmap())
        return drawImage(dest, pixmap.toImage(), src);

1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
    int max_texture_size = ctx->d_func()->maxTextureSize();
    if (pixmap.width() > max_texture_size || pixmap.height() > max_texture_size) {
        QPixmap scaled = pixmap.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);

        const qreal sx = scaled.width() / qreal(pixmap.width());
        const qreal sy = scaled.height() / qreal(pixmap.height());

        drawPixmap(dest, scaled, scaleRect(src, sx, sy));
        return;
    }

    ensureActive();
    d->transferMode(ImageDrawingMode);

1462
1463
    GLenum filterMode = state()->renderHints & QPainter::SmoothPixmapTransform ? GL_LINEAR : GL_NEAREST;
    d->updateTexture(QT_IMAGE_TEXTURE_UNIT, pixmap, GL_CLAMP_TO_EDGE, filterMode);
1464
1465
1466
1467

    bool isBitmap = pixmap.isQBitmap();
    bool isOpaque = !isBitmap && !pixmap.hasAlpha();

1468
    d->shaderManager->setSrcPixelType(isBitmap ? QOpenGLEngineShaderManager::PatternSrc : QOpenGLEngineShaderManager::ImageSrc);
1469
1470

    QOpenGLRect srcRect(src.left(), src.top(), src.right(), src.bottom());
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
    d->drawTexture(dest, srcRect, pixmap.size(), isOpaque, isBitmap);
}

void QOpenGL2PaintEngineEx::drawImage(const QRectF& dest, const QImage& image, const QRectF& src,
                        Qt::ImageConversionFlags)
{
    Q_D(QOpenGL2PaintEngineEx);
    QOpenGLContext *ctx = d->ctx;

    int max_texture_size = ctx->d_func()->maxTextureSize();
    if (image.width() > max_texture_size || image.height() > max_texture_size) {
        QImage scaled = image.scaled(max_texture_size, max_texture_size, Qt::KeepAspectRatio);

        const qreal sx = scaled.width() / qreal(image.width());
        const qreal sy = scaled.height() / qreal(image.height());

        drawImage(dest, scaled, scaleRect(src, sx, sy));
        return;
    }

    ensureActive();
    d->transferMode(ImageDrawingMode);