source: trunk/src/opengl/qpaintengine_opengl.cpp@ 459

Last change on this file since 459 was 2, checked in by Dmitry A. Kuminov, 16 years ago

Initially imported qt-all-opensource-src-4.5.1 from Trolltech.

File size: 179.3 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
4** Contact: Qt Software Information ([email protected])
5**
6** This file is part of the QtOpenGL module of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial Usage
10** Licensees holding valid Qt Commercial licenses may use this file in
11** accordance with the Qt Commercial License Agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and Nokia.
14**
15** GNU Lesser General Public License Usage
16** Alternatively, this file may be used under the terms of the GNU Lesser
17** General Public License version 2.1 as published by the Free Software
18** Foundation and appearing in the file LICENSE.LGPL included in the
19** packaging of this file. Please review the following information to
20** ensure the GNU Lesser General Public License version 2.1 requirements
21** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
22**
23** In addition, as a special exception, Nokia gives you certain
24** additional rights. These rights are described in the Nokia Qt LGPL
25** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
26** package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you are unsure which license is appropriate for your use, please
37** contact the sales department at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include <private/qtextengine_p.h>
43#include <qdebug.h>
44#include <private/qfontengine_p.h>
45#include <qmath.h>
46#include <private/qmath_p.h>
47#include <private/qdrawhelper_p.h>
48#include <private/qpaintengine_p.h>
49#include "qapplication.h"
50#include "qbrush.h"
51#include "qgl.h"
52#include <private/qgl_p.h>
53#include <private/qpainter_p.h>
54#include "qmap.h"
55#include <private/qpaintengine_opengl_p.h>
56#include <private/qdatabuffer_p.h>
57#include "qpen.h"
58#include "qvarlengtharray.h"
59#include <private/qpainter_p.h>
60#include <qglpixelbuffer.h>
61#include <private/qglpixelbuffer_p.h>
62#include <private/qbezier_p.h>
63#include <qglframebufferobject.h>
64
65#include "private/qtessellator_p.h"
66#include "private/qwindowsurface_gl_p.h"
67
68#include "util/fragmentprograms_p.h"
69
70#ifdef Q_WS_QWS
71#include "private/qglpaintdevice_qws_p.h"
72#include "private/qglwindowsurface_qws_p.h"
73#include "qwsmanager_qws.h"
74#include "private/qwsmanager_p.h"
75#endif
76
77#ifdef QT_OPENGL_ES_1_CL
78#include "qgl_cl_p.h"
79#endif
80
81#define QGL_FUNC_CONTEXT QGLContext *ctx = const_cast<QGLContext *>(drawable.context());
82
83#include <stdlib.h>
84#include "qpaintengine_opengl_p.h"
85
86QT_BEGIN_NAMESPACE
87
88extern QImage qt_imageForBrush(int brushStyle, bool invert); //in qbrush.cpp
89#ifdef QT_MAC_USE_COCOA
90extern void *qt_current_nsopengl_context(); // qgl_mac.mm
91#endif
92
93#define QREAL_MAX 9e100
94#define QREAL_MIN -9e100
95
96extern int qt_next_power_of_two(int v);
97
98#define DISABLE_DEBUG_ONCE
99
100//#define DEBUG_DISPLAY_MASK_TEXTURE
101
102#ifdef DISABLE_DEBUG_ONCE
103#define DEBUG_OVERRIDE(state) ;
104#define DEBUG_ONCE_STR(str) ;
105#define DEBUG_ONCE if (0)
106#else
107static int DEBUG_OVERRIDE_FLAG = 0;
108static bool DEBUG_TEMP_FLAG;
109#define DEBUG_OVERRIDE(state) { state ? ++DEBUG_OVERRIDE_FLAG : --DEBUG_OVERRIDE_FLAG; }
110#define DEBUG_ONCE if ((DEBUG_TEMP_FLAG = DEBUG_OVERRIDE_FLAG) && 0) ; else for (static int DEBUG_ONCE_FLAG = false; !DEBUG_ONCE_FLAG || DEBUG_TEMP_FLAG; DEBUG_ONCE_FLAG = true, DEBUG_TEMP_FLAG = false)
111#define DEBUG_ONCE_STR(str) DEBUG_ONCE qDebug() << (str);
112#endif
113
114static inline void qt_glColor4ubv(unsigned char *col)
115{
116#ifdef QT_OPENGL_ES
117 glColor4f(col[0]/255.0, col[1]/255.0, col[2]/255.0, col[3]/255.0);
118#else
119 glColor4ubv(col);
120#endif
121}
122
123struct QT_PointF {
124 qreal x;
125 qreal y;
126};
127
128void qt_add_rect_to_array(const QRectF &r, q_vertexType *array)
129{
130 qreal left = r.left();
131 qreal right = r.right();
132 qreal top = r.top();
133 qreal bottom = r.bottom();
134
135 array[0] = f2vt(left);
136 array[1] = f2vt(top);
137 array[2] = f2vt(right);
138 array[3] = f2vt(top);
139 array[4] = f2vt(right);
140 array[5] = f2vt(bottom);
141 array[6] = f2vt(left);
142 array[7] = f2vt(bottom);
143}
144
145void qt_add_texcoords_to_array(qreal x1, qreal y1, qreal x2, qreal y2, q_vertexType *array)
146{
147 array[0] = f2vt(x1);
148 array[1] = f2vt(y1);
149 array[2] = f2vt(x2);
150 array[3] = f2vt(y1);
151 array[4] = f2vt(x2);
152 array[5] = f2vt(y2);
153 array[6] = f2vt(x1);
154 array[7] = f2vt(y2);
155}
156
157struct QGLTrapezoid
158{
159 QGLTrapezoid()
160 {}
161
162 QGLTrapezoid(qreal top_, qreal bottom_, qreal topLeftX_, qreal topRightX_, qreal bottomLeftX_, qreal bottomRightX_)
163 : top(top_),
164 bottom(bottom_),
165 topLeftX(topLeftX_),
166 topRightX(topRightX_),
167 bottomLeftX(bottomLeftX_),
168 bottomRightX(bottomRightX_)
169 {}
170
171 const QGLTrapezoid translated(const QPointF &delta) const;
172
173 qreal top;
174 qreal bottom;
175 qreal topLeftX;
176 qreal topRightX;
177 qreal bottomLeftX;
178 qreal bottomRightX;
179};
180
181const QGLTrapezoid QGLTrapezoid::translated(const QPointF &delta) const
182{
183 QGLTrapezoid trap(*this);
184 trap.top += delta.y();
185 trap.bottom += delta.y();
186 trap.topLeftX += delta.x();
187 trap.topRightX += delta.x();
188 trap.bottomLeftX += delta.x();
189 trap.bottomRightX += delta.x();
190 return trap;
191}
192
193class QGLDrawable {
194public:
195 QGLDrawable() : widget(0), buffer(0), fbo(0)
196 , wsurf(0)
197 {}
198 inline void setDevice(QPaintDevice *pdev);
199 inline void swapBuffers();
200 inline void makeCurrent();
201 inline void doneCurrent();
202 inline QSize size() const;
203 inline QGLFormat format() const;
204 inline GLuint bindTexture(const QImage &image, GLenum target = GL_TEXTURE_2D, GLint format = GL_RGBA);
205 inline GLuint bindTexture(const QPixmap &pixmap, GLenum target = GL_TEXTURE_2D, GLint format = GL_RGBA);
206 inline QColor backgroundColor() const;
207 inline QGLContext *context() const;
208 inline bool autoFillBackground() const;
209
210private:
211 bool wasBound;
212 QGLWidget *widget;
213 QGLPixelBuffer *buffer;
214 QGLFramebufferObject *fbo;
215#ifdef Q_WS_QWS
216 QWSGLWindowSurface *wsurf;
217#else
218 QGLWindowSurface *wsurf;
219#endif
220};
221
222void QGLDrawable::setDevice(QPaintDevice *pdev)
223{
224 wasBound = false;
225 widget = 0;
226 buffer = 0;
227 fbo = 0;
228#ifdef Q_WS_QWS
229 wsurf = 0;
230#endif
231 if (pdev->devType() == QInternal::Widget)
232 widget = static_cast<QGLWidget *>(pdev);
233 else if (pdev->devType() == QInternal::Pbuffer)
234 buffer = static_cast<QGLPixelBuffer *>(pdev);
235 else if (pdev->devType() == QInternal::FramebufferObject)
236 fbo = static_cast<QGLFramebufferObject *>(pdev);
237 else if (pdev->devType() == QInternal::UnknownDevice)
238#ifdef Q_WS_QWS
239 wsurf = static_cast<QWSGLPaintDevice*>(pdev)->windowSurface();
240#else
241 wsurf = static_cast<QGLWindowSurface *>(pdev);
242#endif
243}
244
245inline void QGLDrawable::swapBuffers()
246{
247 if (widget) {
248 if (widget->autoBufferSwap())
249 widget->swapBuffers();
250 } else {
251 glFlush();
252 }
253}
254
255inline void QGLDrawable::makeCurrent()
256{
257 if (widget)
258 widget->makeCurrent();
259 else if (buffer)
260 buffer->makeCurrent();
261 else if (wsurf)
262 wsurf->context()->makeCurrent();
263 else if (fbo) {
264 wasBound = fbo->isBound();
265 if (!wasBound)
266 fbo->bind();
267 }
268}
269
270inline void QGLDrawable::doneCurrent()
271{
272 if (fbo && !wasBound)
273 fbo->release();
274}
275
276inline QSize QGLDrawable::size() const
277{
278 if (widget) {
279 return QSize(widget->d_func()->glcx->device()->width(),
280 widget->d_func()->glcx->device()->height());
281 } else if (buffer) {
282 return buffer->size();
283 } else if (fbo) {
284 return fbo->size();
285 } else if (wsurf) {
286#ifdef Q_WS_QWS
287 return wsurf->window()->frameSize();
288#else
289 return QSize(wsurf->width(), wsurf->height());
290#endif
291 }
292 return QSize();
293}
294
295inline QGLFormat QGLDrawable::format() const
296{
297 if (widget)
298 return widget->format();
299 else if (buffer)
300 return buffer->format();
301 else if (wsurf)
302 return wsurf->context()->format();
303 else if (fbo && QGLContext::currentContext()) {
304 QGLFormat fmt = QGLContext::currentContext()->format();
305 fmt.setStencil(fbo->attachment() == QGLFramebufferObject::CombinedDepthStencil);
306 fmt.setDepth(fbo->attachment() != QGLFramebufferObject::NoAttachment);
307 return fmt;
308 }
309
310 return QGLFormat();
311}
312
313inline GLuint QGLDrawable::bindTexture(const QImage &image, GLenum target, GLint format)
314{
315 if (widget)
316 return widget->d_func()->glcx->d_func()->bindTexture(image, target, format, true);
317 else if (buffer)
318 return buffer->d_func()->qctx->d_func()->bindTexture(image, target, format, true);
319 else if (fbo && QGLContext::currentContext())
320 return const_cast<QGLContext *>(QGLContext::currentContext())->d_func()->bindTexture(image, target, format, true);
321 else if (wsurf)
322 return wsurf->context()->d_func()->bindTexture(image, target, format, true);
323 return 0;
324}
325
326inline GLuint QGLDrawable::bindTexture(const QPixmap &pixmap, GLenum target, GLint format)
327{
328 if (widget)
329 return widget->d_func()->glcx->d_func()->bindTexture(pixmap, target, format, true);
330 else if (buffer)
331 return buffer->d_func()->qctx->d_func()->bindTexture(pixmap, target, format, true);
332 else if (fbo && QGLContext::currentContext())
333 return const_cast<QGLContext *>(QGLContext::currentContext())->d_func()->bindTexture(pixmap, target, format, true);
334 else if (wsurf)
335 return wsurf->context()->d_func()->bindTexture(pixmap, target, format, true);
336 return 0;
337}
338
339inline QColor QGLDrawable::backgroundColor() const
340{
341 if (widget)
342 return widget->palette().brush(widget->backgroundRole()).color();
343 return QApplication::palette().brush(QPalette::Background).color();
344}
345
346inline QGLContext *QGLDrawable::context() const
347{
348 if (widget)
349 return widget->d_func()->glcx;
350 else if (buffer)
351 return buffer->d_func()->qctx;
352 else if (fbo)
353 return const_cast<QGLContext *>(QGLContext::currentContext());
354 else if (wsurf)
355 return wsurf->context();
356 return 0;
357}
358
359inline bool QGLDrawable::autoFillBackground() const
360{
361 if (widget)
362 return widget->autoFillBackground();
363 else
364 return false;
365}
366
367
368class QOpenGLImmediateModeTessellator;
369class QGLMaskGenerator;
370class QGLOffscreen;
371
372class QGLMaskTextureCache
373{
374public:
375 void setOffscreenSize(const QSize &offscreenSize);
376 void setDrawableSize(const QSize &drawableSize);
377
378 struct CacheLocation {
379 QRect rect;
380 int channel;
381
382 QRect screen_rect;
383 };
384
385 struct CacheInfo {
386 inline CacheInfo(const QPainterPath &p, const QTransform &m, qreal w = -1) :
387 path(p), matrix(m), stroke_width(w), age(0) {}
388
389 QPainterPath path;
390 QTransform matrix;
391 qreal stroke_width;
392
393 CacheLocation loc;
394
395 int age;
396 };
397
398 struct QuadTreeNode {
399 quint64 key;
400
401 int largest_available_block;
402 int largest_used_block;
403 };
404
405 CacheLocation getMask(QGLMaskGenerator &maskGenerator, QOpenGLPaintEnginePrivate *engine);
406
407 typedef QMultiHash<quint64, CacheInfo> QGLTextureCacheHash;
408
409 enum {block_size = 64};
410
411 // throw out keys that are too old
412 void maintainCache();
413 void clearCache();
414
415private:
416 quint64 hash(const QPainterPath &p, const QTransform &m, qreal w);
417
418 void createMask(quint64 key, CacheInfo &info, QGLMaskGenerator &maskGenerator);
419
420 QSize offscreenSize;
421 QSize drawableSize;
422
423 QGLTextureCacheHash cache;
424
425 QVector<QuadTreeNode> occupied_quadtree[4];
426
427 void quadtreeUpdate(int channel, int node, int current_block_size);
428 void quadtreeAllocate(quint64 key, const QSize &size, QRect *rect, int *channel);
429
430 bool quadtreeFindAvailableLocation(const QSize &size, QRect *rect, int *channel);
431 void quadtreeFindExistingLocation(const QSize &size, QRect *rect, int *channel);
432
433 void quadtreeInsert(int channel, quint64 key, const QRect &rect, int node = 0);
434 void quadtreeClear(int channel, const QRect &rect, int node = 0);
435
436 int quadtreeBlocksize(int node);
437 QPoint quadtreeLocation(int node);
438
439 QOpenGLPaintEnginePrivate *engine;
440};
441
442Q_GLOBAL_STATIC(QGLMaskTextureCache, qt_mask_texture_cache)
443
444class QGLOffscreen : public QObject
445{
446 Q_OBJECT
447public:
448 QGLOffscreen()
449 : QObject(),
450 offscreen(0),
451 ctx(0),
452 mask_dim(0),
453 activated(false),
454 bound(false)
455 {
456 connect(QGLSignalProxy::instance(),
457 SIGNAL(aboutToDestroyContext(const QGLContext *)),
458 SLOT(cleanupGLContextRefs(const QGLContext *)));
459 }
460
461 inline void setDevice(QPaintDevice *pdev);
462
463 void begin();
464 void end();
465
466 inline void bind();
467 inline void release();
468
469 inline bool isBound() const;
470
471 inline QSize drawableSize() const;
472 inline QSize offscreenSize() const;
473
474 inline GLuint offscreenTexture() const;
475
476 QGLContext *context() const;
477
478 static bool isSupported();
479
480 inline void initialize();
481
482 inline bool isValid() const;
483
484public Q_SLOTS:
485 void cleanupGLContextRefs(const QGLContext *context) {
486 if (context == ctx) {
487 delete offscreen;
488 ctx = 0;
489 offscreen = 0;
490 mask_dim = 0;
491 }
492 }
493
494private:
495 QGLDrawable drawable;
496
497 QGLFramebufferObject *offscreen;
498 QGLContext *ctx;
499
500 // dimensions of mask texture (square)
501 int mask_dim;
502 QSize last_failed_size;
503
504 bool drawable_fbo;
505
506 bool activated;
507 bool initialized;
508
509 bool bound;
510};
511
512inline void QGLOffscreen::setDevice(QPaintDevice *pdev)
513{
514 drawable.setDevice(pdev);
515
516 drawable_fbo = (pdev->devType() == QInternal::FramebufferObject);
517}
518
519void QGLOffscreen::begin()
520{
521#ifndef QT_OPENGL_ES
522 initialized = false;
523
524 if (activated)
525 initialize();
526#endif
527}
528
529void QGLOffscreen::initialize()
530{
531#ifndef QT_OPENGL_ES
532 if (initialized)
533 return;
534
535 activated = true;
536 initialized = true;
537
538 int dim = qMax(2048, static_cast<int>(qt_next_power_of_two(qMax(drawable.size().width(), drawable.size().height()))));
539
540 bool shared_context = qgl_share_reg()->checkSharing(drawable.context(), ctx);
541 bool would_fail = last_failed_size.isValid() &&
542 (drawable.size().width() >= last_failed_size.width() ||
543 drawable.size().height() >= last_failed_size.height());
544 bool needs_refresh = dim > mask_dim || !shared_context;
545
546 if (needs_refresh && !would_fail) {
547 DEBUG_ONCE qDebug() << "QGLOffscreen::initialize(): creating offscreen of size" << dim;
548 delete offscreen;
549 offscreen = new QGLFramebufferObject(dim, dim, GLenum(GL_TEXTURE_2D));
550 mask_dim = dim;
551
552 if (!offscreen->isValid()) {
553 qWarning("QGLOffscreen: Invalid offscreen fbo (size %dx%d)", mask_dim, mask_dim);
554 delete offscreen;
555 offscreen = 0;
556 mask_dim = 0;
557 last_failed_size = drawable.size();
558 }
559 }
560
561 qt_mask_texture_cache()->setOffscreenSize(offscreenSize());
562 qt_mask_texture_cache()->setDrawableSize(drawable.size());
563 ctx = drawable.context();
564#endif
565}
566
567inline bool QGLOffscreen::isValid() const
568{
569 return offscreen;
570}
571
572void QGLOffscreen::end()
573{
574 if (bound)
575 release();
576#ifdef DEBUG_DISPLAY_MASK_TEXTURE
577 glReadBuffer(GL_BACK);
578 glDrawBuffer(GL_BACK);
579 glMatrixMode(GL_MODELVIEW);
580 glLoadIdentity();
581 glColor4f(1, 1, 1, 1);
582 glDisable(GL_DEPTH_TEST);
583 glBlendFunc(GL_ONE, GL_ZERO);
584 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
585 glEnable(GL_TEXTURE_2D);
586 glBindTexture(GL_TEXTURE_2D, offscreen->texture());
587
588 glBegin(GL_QUADS);
589 glTexCoord2f(0.0, 1.0); glVertex2f(0.0, 0.0);
590 glTexCoord2f(1.0, 1.0); glVertex2f(drawable.size().width(), 0.0);
591 glTexCoord2f(1.0, 0.0); glVertex2f(drawable.size().width(), drawable.size().height());
592 glTexCoord2f(0.0, 0.0); glVertex2f(0.0, drawable.size().height());
593 glEnd();
594
595 glBindTexture(GL_TEXTURE_2D, 0);
596 glDisable(GL_TEXTURE_2D);
597#endif
598}
599
600inline void QGLOffscreen::bind()
601{
602#ifndef QT_OPENGL_ES
603 Q_ASSERT(initialized);
604
605 if (!offscreen || bound)
606 return;
607
608 DEBUG_ONCE qDebug() << "QGLOffscreen: binding offscreen";
609 offscreen->bind();
610
611 bound = true;
612
613 glViewport(0, 0, offscreenSize().width(), offscreenSize().height());
614
615 glMatrixMode(GL_PROJECTION);
616 glLoadIdentity();
617 glOrtho(0, offscreenSize().width(), offscreenSize().height(), 0, -999999, 999999);
618 glMatrixMode(GL_MODELVIEW);
619#endif
620}
621
622inline void QGLOffscreen::release()
623{
624#ifndef QT_OPENGL_ES
625 if (!offscreen || !bound)
626 return;
627
628#ifdef Q_WS_X11
629 // workaround for bug in nvidia driver versions 9x.xx
630 if (QGLExtensions::nvidiaFboNeedsFinish)
631 glFinish();
632#endif
633
634 DEBUG_ONCE_STR("QGLOffscreen: releasing offscreen");
635
636 if (drawable_fbo)
637 drawable.makeCurrent();
638 else
639 offscreen->release();
640
641 QSize sz(drawable.size());
642 glViewport(0, 0, sz.width(), sz.height());
643
644 glMatrixMode(GL_PROJECTION);
645 glLoadIdentity();
646#ifndef QT_OPENGL_ES
647 glOrtho(0, sz.width(), sz.height(), 0, -999999, 999999);
648#else
649 glOrthof(0, sz.width(), sz.height(), 0, -999999, 999999);
650#endif
651 glMatrixMode(GL_MODELVIEW);
652
653 bound = false;
654#endif
655}
656
657inline bool QGLOffscreen::isBound() const
658{
659 return bound;
660}
661
662inline QSize QGLOffscreen::drawableSize() const
663{
664 return drawable.size();
665}
666
667inline QSize QGLOffscreen::offscreenSize() const
668{
669 return QSize(mask_dim, mask_dim);
670}
671
672inline GLuint QGLOffscreen::offscreenTexture() const
673{
674 return offscreen ? offscreen->texture() : 0;
675}
676
677inline QGLContext *QGLOffscreen::context() const
678{
679 return ctx;
680}
681
682bool QGLOffscreen::isSupported()
683{
684 return (QGLExtensions::glExtensions & QGLExtensions::FramebufferObject); // for fbo
685}
686
687struct QDrawQueueItem
688{
689 QDrawQueueItem(qreal _opacity,
690 QBrush _brush,
691 const QPointF &_brush_origion,
692 QPainter::CompositionMode _composition_mode,
693 const QTransform &_matrix,
694 QGLMaskTextureCache::CacheLocation _location)
695 : opacity(_opacity),
696 brush(_brush),
697 brush_origin(_brush_origion),
698 composition_mode(_composition_mode),
699 matrix(_matrix),
700 location(_location) {}
701 qreal opacity;
702 QBrush brush;
703 QPointF brush_origin;
704 QPainter::CompositionMode composition_mode;
705
706 QTransform matrix;
707 QGLMaskTextureCache::CacheLocation location;
708};
709
710////////// GL program cache: start
711
712typedef struct {
713 int brush; // brush index or mask index
714 int mode; // composition mode index
715 bool mask;
716 GLuint program;
717} GLProgram;
718
719typedef QMultiHash<const QGLContext *, GLProgram> QGLProgramHash;
720
721class QGLProgramCache : public QObject
722{
723 Q_OBJECT
724public:
725 QGLProgramCache() {
726 // we have to know when a context is deleted so we can free
727 // any program handles it holds
728 connect(QGLSignalProxy::instance(), SIGNAL(aboutToDestroyContext(const QGLContext *)),
729 SLOT(cleanupPrograms(const QGLContext *)));
730
731 }
732 ~QGLProgramCache() {
733 // at this point the cache should contain 0 elements
734 // Q_ASSERT(program.size() == 0);
735 }
736
737 GLuint getProgram(const QGLContext *ctx, int brush, int mode, bool mask_mode)
738 {
739 // 1. see if we have an entry for the ctx context
740 QList<GLProgram> progs = programs.values(ctx);
741 for (int i=0; i<progs.size(); ++i) {
742 const GLProgram &prg = progs.at(i);
743 if (mask_mode) {
744 if (prg.mask && prg.brush == brush)
745 return prg.program;
746 } else {
747 if (!prg.mask && prg.brush == brush && prg.mode == mode)
748 return prg.program;
749 }
750 }
751
752 // 2. try to find a match in a shared context, and update the
753 // hash with the entry found
754 QList<const QGLContext *> contexts = programs.uniqueKeys();
755 for (int i=0; i<contexts.size(); ++i) {
756 const QGLContext *cx = contexts.at(i);
757 if (cx != ctx && qgl_share_reg()->checkSharing(cx, ctx)) {
758 QList<GLProgram> progs = programs.values(cx);
759 for (int k=0; k<progs.size(); ++k) {
760 const GLProgram &prg = progs.at(k);
761 if (mask_mode) {
762 if (prg.mask && prg.brush == brush) {
763 programs.insert(ctx, prg);
764 return prg.program;
765 }
766 } else {
767 if (!prg.mask && prg.brush == brush && prg.mode == mode) {
768 programs.insert(ctx, prg);
769 return prg.program;
770 }
771 }
772 }
773 }
774 }
775
776 // 3. compile a new program and place it into the cache
777 // NB! assumes ctx is the current GL context
778 GLProgram prg;
779 prg.brush = brush;
780 prg.mode = mode;
781 prg.mask = mask_mode;
782 glGenProgramsARB(1, &prg.program);
783 glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, prg.program);
784 const char *src = mask_mode
785 ? mask_fragment_program_sources[brush]
786 : painter_fragment_program_sources[brush][mode];
787 // necessary for .NET 2002, apparently
788 const GLbyte *gl_src = reinterpret_cast<const GLbyte *>(src);
789
790 while (glGetError() != GL_NO_ERROR) {} // reset error state
791 glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
792 int(strlen(src)), gl_src);
793 if (glGetError() != GL_NO_ERROR) {
794// qDebug() << "QGLProgramCache: Unable to compile fragment program.";
795 glDeleteProgramsARB(1, &prg.program);
796 return 0;
797 }
798
799// qDebug() << "QGLProgramCache: Creating GL program:" << prg.program << hex << ctx;
800 programs.insert(ctx, prg);
801 return prg.program;
802 }
803
804public Q_SLOTS:
805 void cleanupPrograms(const QGLContext *context)
806 {
807 QGLProgramHash::iterator it = programs.begin();
808 while (it != programs.end()) {
809 if (it.key() == context) {
810 if (!context->isSharing()) {
811 // the ctx variable below is needed for the glDeleteProgramARB call
812 // since it is resolved from our extension system
813 // NB! assumes context is the current GL context
814 const QGLContext *ctx = context;
815 // qDebug() << "QGLProgramHash: Deleting GL program:" << it.value().program << hex << it.key();
816 glDeleteProgramsARB(1, &it.value().program);
817 }
818 it = programs.erase(it);
819 } else {
820 ++it;
821 }
822 }
823 }
824
825private:
826 QGLProgramHash programs;
827};
828
829Q_GLOBAL_STATIC(QGLProgramCache, qt_gl_program_cache)
830
831////////// GL program cache: end
832
833class QOpenGLPaintEnginePrivate;
834class QGLPrivateCleanup : public QObject
835{
836 Q_OBJECT
837public:
838 QGLPrivateCleanup(QOpenGLPaintEnginePrivate *priv)
839 : p(priv)
840 {
841 connect(QGLSignalProxy::instance(),
842 SIGNAL(aboutToDestroyContext(const QGLContext *)),
843 SLOT(cleanupGLContextRefs(const QGLContext *)));
844 }
845
846public Q_SLOTS:
847 void cleanupGLContextRefs(const QGLContext *context);
848
849private:
850 QOpenGLPaintEnginePrivate *p;
851};
852
853class QOpenGLPaintEnginePrivate : public QPaintEngineExPrivate
854{
855 Q_DECLARE_PUBLIC(QOpenGLPaintEngine)
856public:
857 QOpenGLPaintEnginePrivate()
858 : opacity(1)
859 , composition_mode(QPainter::CompositionMode_SourceOver)
860 , has_fast_pen(false)
861 , use_stencil_method(false)
862 , dirty_drawable_texture(false)
863 , has_stencil_face_ext(false)
864 , use_fragment_programs(false)
865 , high_quality_antialiasing(false)
866 , use_smooth_pixmap_transform(false)
867 , use_emulation(false)
868 , txop(QTransform::TxNone)
869 , inverseScale(1)
870 , moveToCount(0)
871 , shader_ctx(0)
872 , grad_palette(0)
873 , drawable_texture(0)
874 , ref_cleaner(this)
875 {}
876
877 inline void setGLPen(const QColor &c) {
878 uint alpha = qRound(c.alpha() * opacity);
879 pen_color[0] = qt_div_255(c.red() * alpha);
880 pen_color[1] = qt_div_255(c.green() * alpha);
881 pen_color[2] = qt_div_255(c.blue() * alpha);
882 pen_color[3] = alpha;
883 }
884
885 inline void setGLBrush(const QColor &c) {
886 uint alpha = qRound(c.alpha() * opacity);
887 brush_color[0] = qt_div_255(c.red() * alpha);
888 brush_color[1] = qt_div_255(c.green() * alpha);
889 brush_color[2] = qt_div_255(c.blue() * alpha);
890 brush_color[3] = alpha;
891 }
892
893 inline void setGradientOps(const QBrush &brush, const QRectF &bounds);
894 void createGradientPaletteTexture(const QGradient& g);
895
896 void updateGradient(const QBrush &brush, const QRectF &bounds);
897
898 inline void lineToStencil(qreal x, qreal y);
899 inline void curveToStencil(const QPointF &cp1, const QPointF &cp2, const QPointF &ep);
900 void pathToVertexArrays(const QPainterPath &path);
901 void fillVertexArray(Qt::FillRule fillRule);
902 void drawVertexArrays();
903 void fillPath(const QPainterPath &path);
904 void fillPolygon_dev(const QPointF *polygonPoints, int pointCount,
905 Qt::FillRule fill);
906
907 void drawFastRect(const QRectF &rect);
908 void strokePath(const QPainterPath &path, bool use_cache);
909 void strokePathFastPen(const QPainterPath &path, bool needsResolving);
910 void strokeLines(const QPainterPath &path);
911
912 void updateDepthClip();
913 void systemStateChanged();
914
915 void cleanupGLContextRefs(const QGLContext *context) {
916 if (context == shader_ctx)
917 shader_ctx = 0;
918 }
919
920 inline void updateFastPen() {
921 qreal pen_width = cpen.widthF();
922 has_fast_pen =
923 ((pen_width == 0 || (pen_width <= 1 && matrix.type() <= QTransform::TxTranslate))
924 || cpen.isCosmetic())
925 && cpen.style() == Qt::SolidLine
926 && cpen.isSolid();
927
928 }
929
930 void disableClipping();
931 void enableClipping();
932 void ensureDrawableTexture();
933
934 QPen cpen;
935 QBrush cbrush;
936 Qt::BrushStyle brush_style;
937 QPointF brush_origin;
938 Qt::BrushStyle pen_brush_style;
939 qreal opacity;
940 QPainter::CompositionMode composition_mode;
941
942 Qt::BrushStyle current_style;
943
944 uint has_pen : 1;
945 uint has_brush : 1;
946 uint has_fast_pen : 1;
947 uint use_stencil_method : 1;
948 uint dirty_stencil : 1;
949 uint dirty_drawable_texture : 1;
950 uint has_stencil_face_ext : 1;
951 uint use_fragment_programs : 1;
952 uint high_quality_antialiasing : 1;
953 uint has_antialiasing : 1;
954 uint has_fast_composition_mode : 1;
955 uint use_smooth_pixmap_transform : 1;
956 uint use_system_clip : 1;
957 uint use_emulation : 1;
958
959 void updateUseEmulation();
960
961 QTransform matrix;
962 GLubyte pen_color[4];
963 GLubyte brush_color[4];
964 QTransform::TransformationType txop;
965 QGLDrawable drawable;
966 QGLOffscreen offscreen;
967
968 qreal inverseScale;
969
970 int moveToCount;
971 QPointF path_start;
972
973 bool isFastRect(const QRectF &r);
974
975 void drawImageAsPath(const QRectF &r, const QImage &img, const QRectF &sr);
976 void drawTiledImageAsPath(const QRectF &r, const QImage &img, qreal sx, qreal sy);
977
978 void drawOffscreenPath(const QPainterPath &path);
979
980 void composite(const QRectF &rect, const QPoint &maskOffset = QPoint());
981 void composite(GLuint primitive, const q_vertexType *vertexArray, int vertexCount, const QPoint &maskOffset = QPoint());
982
983 bool createFragmentPrograms();
984 void deleteFragmentPrograms();
985 void updateFragmentProgramData(int locations[]);
986
987 void cacheItemErased(int channel, const QRect &rect);
988
989 void addItem(const QGLMaskTextureCache::CacheLocation &location);
990 void drawItem(const QDrawQueueItem &item);
991 void flushDrawQueue();
992
993 void copyDrawable(const QRectF &rect);
994
995 void updateGLMatrix() const;
996
997 QGLContext *shader_ctx;
998 GLuint grad_palette;
999
1000 GLuint painter_fragment_programs[num_fragment_brushes][num_fragment_composition_modes];
1001 GLuint mask_fragment_programs[num_fragment_masks];
1002
1003 float inv_matrix_data[3][4];
1004 float fmp_data[4];
1005 float fmp2_m_radius2_data[4];
1006 float angle_data[4];
1007 float linear_data[4];
1008
1009 float porterduff_ab_data[4];
1010 float porterduff_xyz_data[4];
1011
1012 float mask_offset_data[4];
1013 float mask_channel_data[4];
1014
1015 FragmentBrushType fragment_brush;
1016 FragmentCompositionModeType fragment_composition_mode;
1017
1018 void setPorterDuffData(float a, float b, float x, float y, float z);
1019 void setInvMatrixData(const QTransform &inv_matrix);
1020
1021 qreal max_x;
1022 qreal max_y;
1023 qreal min_x;
1024 qreal min_y;
1025
1026 QDataBuffer<QPointF> tess_points;
1027 QVector<int> tess_points_stops;
1028
1029 GLdouble projection_matrix[4][4];
1030
1031#if defined(QT_OPENGL_ES_1) || defined(QT_OPENGL_ES_2)
1032 GLfloat mv_matrix[4][4];
1033#else
1034 GLdouble mv_matrix[4][4];
1035#endif
1036
1037 QList<QDrawQueueItem> drawQueue;
1038
1039 GLuint drawable_texture;
1040 QSize drawable_texture_size;
1041
1042 int max_texture_size;
1043
1044 QGLPrivateCleanup ref_cleaner;
1045 friend class QGLMaskTextureCache;
1046};
1047
1048class QOpenGLCoordinateOffset
1049{
1050public:
1051 QOpenGLCoordinateOffset(QOpenGLPaintEnginePrivate *d);
1052 ~QOpenGLCoordinateOffset();
1053
1054 static void enableOffset(QOpenGLPaintEnginePrivate *d);
1055 static void disableOffset(QOpenGLPaintEnginePrivate *d);
1056
1057private:
1058 QOpenGLPaintEnginePrivate *d;
1059};
1060
1061QOpenGLCoordinateOffset::QOpenGLCoordinateOffset(QOpenGLPaintEnginePrivate *d_)
1062 : d(d_)
1063{
1064 enableOffset(d);
1065}
1066
1067void QOpenGLCoordinateOffset::enableOffset(QOpenGLPaintEnginePrivate *d)
1068{
1069 if (!d->has_antialiasing) {
1070 glMatrixMode(GL_MODELVIEW);
1071 glPushMatrix();
1072 d->mv_matrix[3][0] += 0.5;
1073 d->mv_matrix[3][1] += 0.5;
1074 d->updateGLMatrix();
1075 }
1076}
1077
1078QOpenGLCoordinateOffset::~QOpenGLCoordinateOffset()
1079{
1080 disableOffset(d);
1081}
1082
1083void QOpenGLCoordinateOffset::disableOffset(QOpenGLPaintEnginePrivate *d)
1084{
1085 if (!d->has_antialiasing) {
1086 glMatrixMode(GL_MODELVIEW);
1087 glPopMatrix();
1088 d->mv_matrix[3][0] -= 0.5;
1089 d->mv_matrix[3][1] -= 0.5;
1090 }
1091}
1092
1093void QGLPrivateCleanup::cleanupGLContextRefs(const QGLContext *context)
1094{
1095 p->cleanupGLContextRefs(context);
1096}
1097
1098
1099static inline void updateTextureFilter(GLenum target, GLenum wrapMode, bool smoothPixmapTransform)
1100{
1101 if (smoothPixmapTransform) {
1102 glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1103 glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1104 } else {
1105 glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1106 glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1107 }
1108 glTexParameterf(target, GL_TEXTURE_WRAP_S, wrapMode);
1109 glTexParameterf(target, GL_TEXTURE_WRAP_T, wrapMode);
1110}
1111
1112static inline QPainterPath strokeForPath(const QPainterPath &path, const QPen &cpen) {
1113 QPainterPathStroker stroker;
1114 if (cpen.style() == Qt::CustomDashLine)
1115 stroker.setDashPattern(cpen.dashPattern());
1116 else
1117 stroker.setDashPattern(cpen.style());
1118
1119 stroker.setCapStyle(cpen.capStyle());
1120 stroker.setJoinStyle(cpen.joinStyle());
1121 stroker.setMiterLimit(cpen.miterLimit());
1122
1123 qreal width = cpen.widthF();
1124 if (width == 0)
1125 stroker.setWidth(1);
1126 else
1127 stroker.setWidth(width);
1128
1129 QPainterPath stroke = stroker.createStroke(path);
1130 stroke.setFillRule(Qt::WindingFill);
1131 return stroke;
1132}
1133
1134class QGLStrokeCache
1135{
1136 struct CacheInfo
1137 {
1138 inline CacheInfo(QPainterPath p, QPainterPath sp, QPen stroke_pen) :
1139 path(p), stroked_path(sp), pen(stroke_pen) {}
1140 QPainterPath path;
1141 QPainterPath stroked_path;
1142 QPen pen;
1143 };
1144
1145 typedef QMultiHash<quint64, CacheInfo> QGLStrokeTableHash;
1146
1147public:
1148 inline QPainterPath getStrokedPath(const QPainterPath &path, const QPen &pen) {
1149 quint64 hash_val = 0;
1150
1151 for (int i = 0; i < path.elementCount() && i <= 2; i++) {
1152 hash_val += quint64(path.elementAt(i).x);
1153 hash_val += quint64(path.elementAt(i).y);
1154 }
1155
1156 QGLStrokeTableHash::const_iterator it = cache.constFind(hash_val);
1157
1158 if (it == cache.constEnd())
1159 return addCacheElement(hash_val, path, pen);
1160 else {
1161 do {
1162 const CacheInfo &cache_info = it.value();
1163 if (cache_info.path == path && cache_info.pen == pen)
1164 return cache_info.stroked_path;
1165 ++it;
1166 } while (it != cache.constEnd() && it.key() == hash_val);
1167 // an exact match for this path was not found, create new cache element
1168 return addCacheElement(hash_val, path, pen);
1169 }
1170 }
1171
1172protected:
1173 inline int maxCacheSize() const { return 500; }
1174 QPainterPath addCacheElement(quint64 hash_val, QPainterPath path, const QPen &pen) {
1175 if (cache.size() == maxCacheSize()) {
1176 int elem_to_remove = qrand() % maxCacheSize();
1177 cache.remove(cache.keys()[elem_to_remove]); // may remove more than 1, but OK
1178 }
1179 QPainterPath stroke = strokeForPath(path, pen);
1180 CacheInfo cache_entry(path, stroke, pen);
1181 return cache.insert(hash_val, cache_entry).value().stroked_path;
1182 }
1183
1184 QGLStrokeTableHash cache;
1185};
1186
1187Q_GLOBAL_STATIC(QGLStrokeCache, qt_opengl_stroke_cache)
1188
1189class QGLGradientCache : public QObject
1190{
1191 Q_OBJECT
1192 struct CacheInfo
1193 {
1194 inline CacheInfo(QGradientStops s, qreal op, QGradient::InterpolationMode mode) :
1195 stops(s), opacity(op), interpolationMode(mode) {}
1196
1197 GLuint texId;
1198 QGradientStops stops;
1199 qreal opacity;
1200 QGradient::InterpolationMode interpolationMode;
1201 };
1202
1203 typedef QMultiHash<quint64, CacheInfo> QGLGradientColorTableHash;
1204
1205public:
1206 QGLGradientCache() : QObject(), buffer_ctx(0)
1207 {
1208 connect(QGLSignalProxy::instance(),
1209 SIGNAL(aboutToDestroyContext(const QGLContext *)),
1210 SLOT(cleanupGLContextRefs(const QGLContext *)));
1211 }
1212
1213 inline GLuint getBuffer(const QGradient &gradient, qreal opacity, QGLContext *ctx) {
1214 if (buffer_ctx && !qgl_share_reg()->checkSharing(buffer_ctx, ctx))
1215 cleanCache();
1216
1217 buffer_ctx = ctx;
1218
1219 quint64 hash_val = 0;
1220
1221 QGradientStops stops = gradient.stops();
1222 for (int i = 0; i < stops.size() && i <= 2; i++)
1223 hash_val += stops[i].second.rgba();
1224
1225 QGLGradientColorTableHash::const_iterator it = cache.constFind(hash_val);
1226
1227 if (it == cache.constEnd())
1228 return addCacheElement(hash_val, gradient, opacity);
1229 else {
1230 do {
1231 const CacheInfo &cache_info = it.value();
1232 if (cache_info.stops == stops && cache_info.opacity == opacity && cache_info.interpolationMode == gradient.interpolationMode()) {
1233 return cache_info.texId;
1234 }
1235 ++it;
1236 } while (it != cache.constEnd() && it.key() == hash_val);
1237 // an exact match for these stops and opacity was not found, create new cache
1238 return addCacheElement(hash_val, gradient, opacity);
1239 }
1240 }
1241
1242 inline int paletteSize() const { return 1024; }
1243
1244protected:
1245 inline int maxCacheSize() const { return 60; }
1246 inline void generateGradientColorTable(const QGradient& g,
1247 uint *colorTable,
1248 int size, qreal opacity) const;
1249 GLuint addCacheElement(quint64 hash_val, const QGradient &gradient, qreal opacity) {
1250 if (cache.size() == maxCacheSize()) {
1251 int elem_to_remove = qrand() % maxCacheSize();
1252 quint64 key = cache.keys()[elem_to_remove];
1253
1254 // need to call glDeleteTextures on each removed cache entry:
1255 QGLGradientColorTableHash::const_iterator it = cache.constFind(key);
1256 do {
1257 glDeleteTextures(1, &it.value().texId);
1258 } while (++it != cache.constEnd() && it.key() == key);
1259 cache.remove(key); // may remove more than 1, but OK
1260 }
1261 CacheInfo cache_entry(gradient.stops(), opacity, gradient.interpolationMode());
1262 uint buffer[1024];
1263 generateGradientColorTable(gradient, buffer, paletteSize(), opacity);
1264 glGenTextures(1, &cache_entry.texId);
1265#ifndef QT_OPENGL_ES
1266 glBindTexture(GL_TEXTURE_1D, cache_entry.texId);
1267 glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA, paletteSize(),
1268 0, GL_BGRA, GL_UNSIGNED_BYTE, buffer);
1269#else
1270 // create 2D one-line texture instead. This requires an impl of manual GL_TEXGEN for all primitives
1271#endif
1272 return cache.insert(hash_val, cache_entry).value().texId;
1273 }
1274
1275 void cleanCache() {
1276 QGLGradientColorTableHash::const_iterator it = cache.constBegin();
1277 for (; it != cache.constEnd(); ++it) {
1278 const CacheInfo &cache_info = it.value();
1279 glDeleteTextures(1, &cache_info.texId);
1280 }
1281 cache.clear();
1282 }
1283
1284 QGLGradientColorTableHash cache;
1285
1286 QGLContext *buffer_ctx;
1287
1288public Q_SLOTS:
1289 void cleanupGLContextRefs(const QGLContext *context) {
1290 if (context == buffer_ctx) {
1291 cleanCache();
1292 buffer_ctx = 0;
1293 }
1294 }
1295};
1296
1297static inline uint endianColor(uint c)
1298{
1299#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
1300 return c;
1301#else
1302 return ( (c << 24) & 0xff000000)
1303 | ((c >> 24) & 0x000000ff)
1304 | ((c << 8) & 0x00ff0000)
1305 | ((c >> 8) & 0x0000ff00);
1306#endif // Q_BYTE_ORDER
1307}
1308
1309void QGLGradientCache::generateGradientColorTable(const QGradient& gradient, uint *colorTable, int size, qreal opacity) const
1310{
1311 int pos = 0;
1312 QGradientStops s = gradient.stops();
1313 QVector<uint> colors(s.size());
1314
1315 for (int i = 0; i < s.size(); ++i)
1316 colors[i] = s[i].second.rgba();
1317
1318 bool colorInterpolation = (gradient.interpolationMode() == QGradient::ColorInterpolation);
1319
1320 uint alpha = qRound(opacity * 256);
1321 uint current_color = ARGB_COMBINE_ALPHA(colors[0], alpha);
1322 qreal incr = 1.0 / qreal(size);
1323 qreal fpos = 1.5 * incr;
1324 colorTable[pos++] = endianColor(PREMUL(current_color));
1325
1326 while (fpos <= s.first().first) {
1327 colorTable[pos] = colorTable[pos - 1];
1328 pos++;
1329 fpos += incr;
1330 }
1331
1332 if (colorInterpolation)
1333 current_color = PREMUL(current_color);
1334
1335 for (int i = 0; i < s.size() - 1; ++i) {
1336 qreal delta = 1/(s[i+1].first - s[i].first);
1337 uint next_color = ARGB_COMBINE_ALPHA(colors[i+1], alpha);
1338 if (colorInterpolation)
1339 next_color = PREMUL(next_color);
1340
1341 while (fpos < s[i+1].first && pos < size) {
1342 int dist = int(256 * ((fpos - s[i].first) * delta));
1343 int idist = 256 - dist;
1344 if (colorInterpolation)
1345 colorTable[pos] = endianColor(INTERPOLATE_PIXEL_256(current_color, idist, next_color, dist));
1346 else
1347 colorTable[pos] = endianColor(PREMUL(INTERPOLATE_PIXEL_256(current_color, idist, next_color, dist)));
1348 ++pos;
1349 fpos += incr;
1350 }
1351 current_color = next_color;
1352 }
1353
1354 Q_ASSERT(s.size() > 0);
1355
1356 uint last_color = endianColor(PREMUL(ARGB_COMBINE_ALPHA(colors[s.size() - 1], alpha)));
1357 for (;pos < size; ++pos)
1358 colorTable[pos] = last_color;
1359
1360 // Make sure the last color stop is represented at the end of the table
1361 colorTable[size-1] = last_color;
1362}
1363
1364#ifndef Q_WS_QWS
1365Q_GLOBAL_STATIC(QGLGradientCache, qt_opengl_gradient_cache)
1366#endif
1367
1368void QOpenGLPaintEnginePrivate::createGradientPaletteTexture(const QGradient& g)
1369{
1370#ifdef QT_OPENGL_ES //###
1371 Q_UNUSED(g);
1372#else
1373 GLuint texId = qt_opengl_gradient_cache()->getBuffer(g, opacity, drawable.context());
1374 glBindTexture(GL_TEXTURE_1D, texId);
1375 grad_palette = texId;
1376 if (g.spread() == QGradient::RepeatSpread || g.type() == QGradient::ConicalGradient)
1377 glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_REPEAT);
1378 else if (g.spread() == QGradient::ReflectSpread)
1379 glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT_IBM);
1380 else
1381 glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1382
1383 glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1384 glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1385
1386#endif
1387}
1388
1389
1390inline void QOpenGLPaintEnginePrivate::setGradientOps(const QBrush &brush, const QRectF &bounds)
1391{
1392 current_style = brush.style();
1393
1394 if (current_style < Qt::LinearGradientPattern || current_style > Qt::ConicalGradientPattern) {
1395 setGLBrush(brush.color());
1396 qt_glColor4ubv(brush_color);
1397 }
1398
1399 updateGradient(brush, bounds);
1400
1401#ifndef QT_OPENGL_ES //### GLES does not have GL_TEXTURE_GEN_ so we are falling back for gradients
1402 glDisable(GL_TEXTURE_GEN_S);
1403 glDisable(GL_TEXTURE_1D);
1404
1405 if (current_style == Qt::LinearGradientPattern) {
1406 if (high_quality_antialiasing || !has_fast_composition_mode) {
1407 fragment_brush = FRAGMENT_PROGRAM_BRUSH_LINEAR;
1408 } else {
1409 glEnable(GL_TEXTURE_GEN_S);
1410 glEnable(GL_TEXTURE_1D);
1411 }
1412 } else {
1413 if (use_fragment_programs) {
1414 if (current_style == Qt::RadialGradientPattern)
1415 fragment_brush = FRAGMENT_PROGRAM_BRUSH_RADIAL;
1416 else if (current_style == Qt::ConicalGradientPattern)
1417 fragment_brush = FRAGMENT_PROGRAM_BRUSH_CONICAL;
1418 else if (current_style == Qt::SolidPattern)
1419 fragment_brush = FRAGMENT_PROGRAM_BRUSH_SOLID;
1420 else if (current_style == Qt::TexturePattern)
1421 fragment_brush = FRAGMENT_PROGRAM_BRUSH_TEXTURE;
1422 else
1423 fragment_brush = FRAGMENT_PROGRAM_BRUSH_PATTERN;
1424 }
1425 }
1426#endif
1427}
1428
1429QOpenGLPaintEngine::QOpenGLPaintEngine()
1430 : QPaintEngineEx(*(new QOpenGLPaintEnginePrivate))
1431{
1432}
1433
1434QOpenGLPaintEngine::~QOpenGLPaintEngine()
1435{
1436}
1437
1438bool QOpenGLPaintEngine::begin(QPaintDevice *pdev)
1439{
1440 Q_D(QOpenGLPaintEngine);
1441
1442 d->drawable.setDevice(pdev);
1443 d->offscreen.setDevice(pdev);
1444 d->has_fast_pen = false;
1445 d->inverseScale = 1;
1446 d->opacity = 1;
1447 d->drawable.makeCurrent();
1448 d->matrix = QTransform();
1449 d->has_antialiasing = false;
1450 d->high_quality_antialiasing = false;
1451 d->dirty_stencil = true;
1452
1453 d->use_emulation = false;
1454
1455 for (int i = 0; i < 4; ++i)
1456 for (int j = 0; j < 4; ++j)
1457 d->mv_matrix[i][j] = (i == j ? qreal(1) : qreal(0));
1458
1459 bool has_frag_program = (QGLExtensions::glExtensions & QGLExtensions::FragmentProgram)
1460 && (pdev->devType() != QInternal::Pixmap);
1461
1462 QGLContext *ctx = const_cast<QGLContext *>(d->drawable.context());
1463 if (!ctx) {
1464 qWarning() << "QOpenGLPaintEngine: paint device doesn't have a valid GL context.";
1465 return false;
1466 }
1467
1468 if (has_frag_program)
1469 has_frag_program = qt_resolve_frag_program_extensions(ctx) && qt_resolve_version_1_3_functions(ctx);
1470
1471 d->use_stencil_method = d->drawable.format().stencil()
1472 && (QGLExtensions::glExtensions & QGLExtensions::StencilWrap);
1473 if (d->drawable.format().directRendering()
1474 && (d->use_stencil_method && QGLExtensions::glExtensions & QGLExtensions::StencilTwoSide))
1475 d->has_stencil_face_ext = qt_resolve_stencil_face_extension(ctx);
1476
1477#ifndef QT_OPENGL_ES
1478 if (!ctx->d_ptr->internal_context) {
1479 glGetDoublev(GL_PROJECTION_MATRIX, &d->projection_matrix[0][0]);
1480 glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS);
1481 glPushAttrib(GL_ALL_ATTRIB_BITS);
1482
1483 glDisableClientState(GL_EDGE_FLAG_ARRAY);
1484 glDisableClientState(GL_INDEX_ARRAY);
1485 glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1486 glDisable(GL_TEXTURE_1D);
1487 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
1488 glPixelTransferi(GL_MAP_COLOR, false);
1489 glPixelTransferi(GL_MAP_STENCIL, false);
1490 glDisable(GL_TEXTURE_GEN_S);
1491
1492 glPixelStorei(GL_PACK_SWAP_BYTES, false);
1493 glPixelStorei(GL_PACK_LSB_FIRST, false);
1494 glPixelStorei(GL_PACK_ROW_LENGTH, 0);
1495 glPixelStorei(GL_PACK_SKIP_ROWS, 0);
1496 glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
1497 glPixelStorei(GL_PACK_ALIGNMENT, 4);
1498
1499 glPixelStorei(GL_UNPACK_SWAP_BYTES, false);
1500 glPixelStorei(GL_UNPACK_LSB_FIRST, false);
1501 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
1502 glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
1503 glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
1504 glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
1505
1506 if (QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_1_2) {
1507 glPixelStorei(GL_PACK_IMAGE_HEIGHT, 0);
1508 glPixelStorei(GL_PACK_SKIP_IMAGES, 0);
1509 glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, 0);
1510 glPixelStorei(GL_UNPACK_SKIP_IMAGES, 0);
1511 }
1512 }
1513#endif
1514
1515 if (!ctx->d_ptr->internal_context) {
1516 glMatrixMode(GL_MODELVIEW);
1517 glPushMatrix();
1518 glMatrixMode(GL_TEXTURE);
1519 glPushMatrix();
1520 glLoadIdentity();
1521 glDisableClientState(GL_COLOR_ARRAY);
1522 glDisableClientState(GL_NORMAL_ARRAY);
1523 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
1524 glDisableClientState(GL_VERTEX_ARRAY);
1525
1526 if (QGLExtensions::glExtensions & QGLExtensions::SampleBuffers)
1527 glDisable(GL_MULTISAMPLE);
1528 glDisable(GL_TEXTURE_2D);
1529 if (QGLExtensions::glExtensions & QGLExtensions::TextureRectangle)
1530 glDisable(GL_TEXTURE_RECTANGLE_NV);
1531 glDisable(GL_STENCIL_TEST);
1532 glDisable(GL_CULL_FACE);
1533 glDisable(GL_LIGHTING);
1534 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1535 }
1536
1537 d->offscreen.begin();
1538
1539 const QColor &c = d->drawable.backgroundColor();
1540 glClearColor(c.redF(), c.greenF(), c.blueF(), 1.0);
1541 if (d->drawable.context()->d_func()->clear_on_painter_begin && d->drawable.autoFillBackground()) {
1542 GLbitfield clearBits = GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT;
1543#ifndef QT_OPENGL_ES
1544 clearBits |= GL_ACCUM_BUFFER_BIT;
1545#endif
1546 glClear(clearBits);
1547 }
1548
1549 QSize sz(d->drawable.size());
1550 glViewport(0, 0, sz.width(), sz.height()); // XXX (Embedded): We need a solution for GLWidgets that draw in a part or a bigger surface...
1551 glMatrixMode(GL_PROJECTION);
1552 glLoadIdentity();
1553#ifdef QT_OPENGL_ES
1554 glOrthof(0, sz.width(), sz.height(), 0, -999999, 999999);
1555#else
1556 glOrtho(0, sz.width(), sz.height(), 0, -999999, 999999);
1557#endif
1558 glMatrixMode(GL_MODELVIEW);
1559 glLoadIdentity();
1560 glEnable(GL_BLEND);
1561 d->composition_mode = QPainter::CompositionMode_SourceOver;
1562
1563#ifdef QT_OPENGL_ES
1564 d->max_texture_size = ctx->d_func()->maxTextureSize();
1565#else
1566 bool shared_ctx = qgl_share_reg()->checkSharing(d->drawable.context(), d->shader_ctx);
1567
1568 if (shared_ctx) {
1569 d->max_texture_size = d->shader_ctx->d_func()->maxTextureSize();
1570 } else {
1571 d->max_texture_size = ctx->d_func()->maxTextureSize();
1572
1573 if (d->shader_ctx) {
1574 d->shader_ctx->makeCurrent();
1575 glBindTexture(GL_TEXTURE_1D, 0);
1576 glDeleteTextures(1, &d->grad_palette);
1577
1578 if (has_frag_program && d->use_fragment_programs)
1579 glDeleteTextures(1, &d->drawable_texture);
1580 ctx->makeCurrent();
1581 }
1582 d->shader_ctx = d->drawable.context();
1583 glGenTextures(1, &d->grad_palette);
1584
1585 qt_mask_texture_cache()->clearCache();
1586 d->use_fragment_programs = has_frag_program;
1587 }
1588
1589 if (d->use_fragment_programs && (!shared_ctx || sz.width() > d->drawable_texture_size.width()
1590 || sz.height() > d->drawable_texture_size.height()))
1591 {
1592 // delete old texture if size has increased, otherwise it was deleted earlier
1593 if (shared_ctx)
1594 glDeleteTextures(1, &d->drawable_texture);
1595
1596 d->dirty_drawable_texture = true;
1597 d->drawable_texture_size = QSize(qt_next_power_of_two(sz.width()),
1598 qt_next_power_of_two(sz.height()));
1599 }
1600#endif
1601
1602 updateClipRegion(QRegion(), Qt::NoClip);
1603 penChanged();
1604 brushChanged();
1605 opacityChanged();
1606 compositionModeChanged();
1607 renderHintsChanged();
1608 transformChanged();
1609 return true;
1610}
1611
1612bool QOpenGLPaintEngine::end()
1613{
1614 Q_D(QOpenGLPaintEngine);
1615 d->flushDrawQueue();
1616 d->offscreen.end();
1617 QGLContext *ctx = const_cast<QGLContext *>(d->drawable.context());
1618 if (!ctx->d_ptr->internal_context) {
1619 glMatrixMode(GL_TEXTURE);
1620 glPopMatrix();
1621 glMatrixMode(GL_MODELVIEW);
1622 glPopMatrix();
1623 }
1624#ifndef QT_OPENGL_ES
1625 if (ctx->d_ptr->internal_context) {
1626 glDisable(GL_SCISSOR_TEST);
1627 } else {
1628 glMatrixMode(GL_PROJECTION);
1629 glLoadMatrixd(&d->projection_matrix[0][0]);
1630 glPopAttrib();
1631 glPopClientAttrib();
1632 }
1633#endif
1634 d->drawable.swapBuffers();
1635 d->drawable.doneCurrent();
1636 qt_mask_texture_cache()->maintainCache();
1637
1638 return true;
1639}
1640
1641void QOpenGLPaintEngine::updateState(const QPaintEngineState &state)
1642{
1643 Q_D(QOpenGLPaintEngine);
1644 QPaintEngine::DirtyFlags flags = state.state();
1645
1646 bool update_fast_pen = false;
1647
1648 if (flags & DirtyOpacity) {
1649 update_fast_pen = true;
1650 d->opacity = state.opacity();
1651 if (d->opacity > 1.0f)
1652 d->opacity = 1.0f;
1653 if (d->opacity < 0.f)
1654 d->opacity = 0.f;
1655 // force update
1656 flags |= DirtyPen;
1657 flags |= DirtyBrush;
1658 }
1659
1660 if (flags & DirtyTransform) {
1661 update_fast_pen = true;
1662 updateMatrix(state.transform());
1663 // brush setup depends on transform state
1664 if (state.brush().style() != Qt::NoBrush)
1665 flags |= DirtyBrush;
1666 }
1667
1668 if (flags & DirtyPen) {
1669 update_fast_pen = true;
1670 updatePen(state.pen());
1671 }
1672
1673 if (flags & (DirtyBrush | DirtyBrushOrigin)) {
1674 updateBrush(state.brush(), state.brushOrigin());
1675 }
1676
1677 if (flags & DirtyFont) {
1678 updateFont(state.font());
1679 }
1680
1681 if (state.state() & DirtyClipEnabled) {
1682 if (state.isClipEnabled())
1683 updateClipRegion(painter()->clipRegion(), Qt::ReplaceClip);
1684 else
1685 updateClipRegion(QRegion(), Qt::NoClip);
1686 }
1687
1688 if (flags & DirtyClipPath) {
1689 updateClipRegion(QRegion(state.clipPath().toFillPolygon().toPolygon(),
1690 state.clipPath().fillRule()),
1691 state.clipOperation());
1692 }
1693
1694 if (flags & DirtyClipRegion) {
1695 updateClipRegion(state.clipRegion(), state.clipOperation());
1696 }
1697
1698 if (flags & DirtyHints) {
1699 updateRenderHints(state.renderHints());
1700 }
1701
1702 if (flags & DirtyCompositionMode) {
1703 updateCompositionMode(state.compositionMode());
1704 }
1705
1706 if (update_fast_pen) {
1707 Q_D(QOpenGLPaintEngine);
1708 qreal pen_width = d->cpen.widthF();
1709 d->has_fast_pen =
1710 ((pen_width == 0 || (pen_width <= 1 && d->txop <= QTransform::TxTranslate))
1711 || d->cpen.isCosmetic())
1712 && d->cpen.style() == Qt::SolidLine
1713 && d->cpen.isSolid();
1714 }
1715}
1716
1717
1718void QOpenGLPaintEnginePrivate::setInvMatrixData(const QTransform &inv_matrix)
1719{
1720 inv_matrix_data[0][0] = inv_matrix.m11();
1721 inv_matrix_data[1][0] = inv_matrix.m21();
1722 inv_matrix_data[2][0] = inv_matrix.m31();
1723
1724 inv_matrix_data[0][1] = inv_matrix.m12();
1725 inv_matrix_data[1][1] = inv_matrix.m22();
1726 inv_matrix_data[2][1] = inv_matrix.m32();
1727
1728 inv_matrix_data[0][2] = inv_matrix.m13();
1729 inv_matrix_data[1][2] = inv_matrix.m23();
1730 inv_matrix_data[2][2] = inv_matrix.m33();
1731}
1732
1733
1734void QOpenGLPaintEnginePrivate::updateGradient(const QBrush &brush, const QRectF &)
1735{
1736#ifdef QT_OPENGL_ES
1737 Q_UNUSED(brush);
1738#else
1739 bool has_mirrored_repeat = QGLExtensions::glExtensions & QGLExtensions::MirroredRepeat;
1740 Qt::BrushStyle style = brush.style();
1741
1742 QTransform m = brush.transform();
1743
1744 if (has_mirrored_repeat && style == Qt::LinearGradientPattern) {
1745 const QLinearGradient *g = static_cast<const QLinearGradient *>(brush.gradient());
1746 QTransform m = brush.transform();
1747 QPointF realStart = g->start();
1748 QPointF realFinal = g->finalStop();
1749 QPointF start = m.map(realStart);
1750 QPointF stop;
1751
1752 if (qFuzzyCompare(m.m11(), m.m22()) && m.m12() == 0.0 && m.m21() == 0.0) {
1753 // It is a simple uniform scale and/or translation
1754 stop = m.map(realFinal);
1755 } else {
1756 // It is not enough to just transform the endpoints.
1757 // We have to make sure the _pattern_ is transformed correctly.
1758
1759 qreal odx = realFinal.x() - realStart.x();
1760 qreal ody = realFinal.y() - realStart.y();
1761
1762 // nx, ny and dx, dy are normal and gradient direction after transform:
1763 qreal nx = m.m11()*ody - m.m21()*odx;
1764 qreal ny = m.m12()*ody - m.m22()*odx;
1765
1766 qreal dx = m.m11()*odx + m.m21()*ody;
1767 qreal dy = m.m12()*odx + m.m22()*ody;
1768
1769 qreal lx = 1 / (dx - dy*nx/ny);
1770 qreal ly = 1 / (dy - dx*ny/nx);
1771 qreal l = 1 / qSqrt(lx*lx+ly*ly);
1772
1773 stop = start + QPointF(-ny, nx) * l/qSqrt(nx*nx+ny*ny);
1774 }
1775
1776 float tr[4], f;
1777 tr[0] = stop.x() - start.x();
1778 tr[1] = stop.y() - start.y();
1779 f = 1.0 / (tr[0]*tr[0] + tr[1]*tr[1]);
1780 tr[0] *= f;
1781 tr[1] *= f;
1782 tr[2] = 0;
1783 tr[3] = -(start.x()*tr[0] + start.y()*tr[1]);
1784 brush_color[0] = brush_color[1] = brush_color[2] = brush_color[3] = 255;
1785 qt_glColor4ubv(brush_color);
1786 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
1787 glTexGenfv(GL_S, GL_OBJECT_PLANE, tr);
1788 }
1789
1790 if (use_fragment_programs) {
1791 if (style == Qt::RadialGradientPattern) {
1792 const QRadialGradient *g = static_cast<const QRadialGradient *>(brush.gradient());
1793 QPointF realCenter = g->center();
1794 QPointF realFocal = g->focalPoint();
1795 qreal realRadius = g->radius();
1796 QTransform translate(1, 0, 0, 1, -realFocal.x(), -realFocal.y());
1797 QTransform gl_to_qt(1, 0, 0, -1, 0, pdev->height());
1798 QTransform inv_matrix = gl_to_qt * matrix.inverted() * brush.transform().inverted() * translate;
1799
1800 setInvMatrixData(inv_matrix);
1801
1802 fmp_data[0] = realCenter.x() - realFocal.x();
1803 fmp_data[1] = realCenter.y() - realFocal.y();
1804
1805 fmp2_m_radius2_data[0] = -fmp_data[0] * fmp_data[0] - fmp_data[1] * fmp_data[1] + realRadius * realRadius;
1806 } else if (style == Qt::ConicalGradientPattern) {
1807 const QConicalGradient *g = static_cast<const QConicalGradient *>(brush.gradient());
1808 QPointF realCenter = g->center();
1809 QTransform translate(1, 0, 0, 1, -realCenter.x(), -realCenter.y());
1810 QTransform gl_to_qt(1, 0, 0, -1, 0, pdev->height());
1811 QTransform inv_matrix = gl_to_qt * matrix.inverted() * brush.transform().inverted() * translate;
1812
1813 setInvMatrixData(inv_matrix);
1814
1815 angle_data[0] = -(g->angle() * 2 * Q_PI) / 360.0;
1816 } else if (style == Qt::LinearGradientPattern) {
1817 const QLinearGradient *g = static_cast<const QLinearGradient *>(brush.gradient());
1818
1819 QPointF realStart = g->start();
1820 QPointF realFinal = g->finalStop();
1821 QTransform translate(1, 0, 0, 1, -realStart.x(), -realStart.y());
1822 QTransform gl_to_qt(1, 0, 0, -1, 0, pdev->height());
1823
1824 QTransform inv_matrix = gl_to_qt * matrix.inverted() * brush.transform().inverted() * translate;
1825
1826 setInvMatrixData(inv_matrix);
1827
1828 QPointF l = realFinal - realStart;
1829
1830 linear_data[0] = l.x();
1831 linear_data[1] = l.y();
1832
1833 linear_data[2] = 1.0f / (l.x() * l.x() + l.y() * l.y());
1834 } else if (style != Qt::SolidPattern) {
1835 QTransform translate(1, 0, 0, 1, brush_origin.x(), brush_origin.y());
1836 QTransform gl_to_qt(1, 0, 0, -1, 0, pdev->height());
1837
1838 QTransform inv_matrix = gl_to_qt * matrix.inverted() * brush.transform().inverted() * translate;
1839
1840 setInvMatrixData(inv_matrix);
1841 }
1842 }
1843
1844 if (style >= Qt::LinearGradientPattern && style <= Qt::ConicalGradientPattern) {
1845 createGradientPaletteTexture(*brush.gradient());
1846 }
1847#endif
1848}
1849
1850
1851class QOpenGLTessellator : public QTessellator
1852{
1853public:
1854 QOpenGLTessellator() {}
1855 ~QOpenGLTessellator() { }
1856 QGLTrapezoid toGLTrapezoid(const Trapezoid &trap);
1857};
1858
1859QGLTrapezoid QOpenGLTessellator::toGLTrapezoid(const Trapezoid &trap)
1860{
1861 QGLTrapezoid t;
1862
1863 t.top = Q27Dot5ToDouble(trap.top);
1864 t.bottom = Q27Dot5ToDouble(trap.bottom);
1865
1866 Q27Dot5 y = trap.topLeft->y - trap.bottomLeft->y;
1867
1868 qreal topLeftY = Q27Dot5ToDouble(trap.topLeft->y);
1869
1870 qreal tx = Q27Dot5ToDouble(trap.topLeft->x);
1871 qreal m = (-tx + Q27Dot5ToDouble(trap.bottomLeft->x)) / Q27Dot5ToDouble(y);
1872 t.topLeftX = tx + m * (topLeftY - t.top);
1873 t.bottomLeftX = tx + m * (topLeftY - t.bottom);
1874
1875 y = trap.topRight->y - trap.bottomRight->y;
1876
1877 qreal topRightY = Q27Dot5ToDouble(trap.topRight->y);
1878
1879 tx = Q27Dot5ToDouble(trap.topRight->x);
1880 m = (-tx + Q27Dot5ToDouble(trap.bottomRight->x)) / Q27Dot5ToDouble(y);
1881
1882 t.topRightX = tx + m * (topRightY - Q27Dot5ToDouble(trap.top));
1883 t.bottomRightX = tx + m * (topRightY - Q27Dot5ToDouble(trap.bottom));
1884
1885 return t;
1886}
1887
1888class QOpenGLImmediateModeTessellator : public QOpenGLTessellator
1889{
1890public:
1891 void addTrap(const Trapezoid &trap);
1892 void tessellate(const QPointF *points, int nPoints, bool winding) {
1893 trapezoids.reserve(trapezoids.size() + nPoints);
1894 setWinding(winding);
1895 QTessellator::tessellate(points, nPoints);
1896 }
1897
1898 QVector<QGLTrapezoid> trapezoids;
1899};
1900
1901void QOpenGLImmediateModeTessellator::addTrap(const Trapezoid &trap)
1902{
1903 trapezoids.append(toGLTrapezoid(trap));
1904}
1905
1906#ifndef QT_OPENGL_ES
1907static void drawTrapezoid(const QGLTrapezoid &trap, const qreal offscreenHeight, QGLContext *ctx)
1908{
1909 qreal minX = qMin(trap.topLeftX, trap.bottomLeftX);
1910 qreal maxX = qMax(trap.topRightX, trap.bottomRightX);
1911
1912 if (qFuzzyCompare(trap.top, trap.bottom) || qFuzzyCompare(minX, maxX) ||
1913 (qFuzzyCompare(trap.topLeftX, trap.topRightX) && qFuzzyCompare(trap.bottomLeftX, trap.bottomRightX)))
1914 return;
1915
1916 const qreal xpadding = 1.0;
1917 const qreal ypadding = 1.0;
1918
1919 qreal topDist = offscreenHeight - trap.top;
1920 qreal bottomDist = offscreenHeight - trap.bottom;
1921
1922 qreal reciprocal = bottomDist / (bottomDist - topDist);
1923
1924 qreal leftB = trap.bottomLeftX + (trap.topLeftX - trap.bottomLeftX) * reciprocal;
1925 qreal rightB = trap.bottomRightX + (trap.topRightX - trap.bottomRightX) * reciprocal;
1926
1927 const bool topZero = qFuzzyCompare(topDist + 1, 1);
1928
1929 reciprocal = topZero ? 1.0 / bottomDist : 1.0 / topDist;
1930
1931 qreal leftA = topZero ? (trap.bottomLeftX - leftB) * reciprocal : (trap.topLeftX - leftB) * reciprocal;
1932 qreal rightA = topZero ? (trap.bottomRightX - rightB) * reciprocal : (trap.topRightX - rightB) * reciprocal;
1933
1934 qreal invLeftA = qFuzzyCompare(leftA + 1, 1) ? 0.0 : 1.0 / leftA;
1935 qreal invRightA = qFuzzyCompare(rightA + 1, 1) ? 0.0 : 1.0 / rightA;
1936
1937 // fragment program needs the negative of invRightA as it mirrors the line
1938 glTexCoord4f(topDist, bottomDist, invLeftA, -invRightA);
1939 glMultiTexCoord4f(GL_TEXTURE1, leftA, leftB, rightA, rightB);
1940
1941 qreal topY = trap.top - ypadding;
1942 qreal bottomY = trap.bottom + ypadding;
1943
1944 qreal bounds_bottomLeftX = leftA * (offscreenHeight - bottomY) + leftB;
1945 qreal bounds_bottomRightX = rightA * (offscreenHeight - bottomY) + rightB;
1946 qreal bounds_topLeftX = leftA * (offscreenHeight - topY) + leftB;
1947 qreal bounds_topRightX = rightA * (offscreenHeight - topY) + rightB;
1948
1949 QPointF leftNormal(1, -leftA);
1950 leftNormal /= qSqrt(leftNormal.x() * leftNormal.x() + leftNormal.y() * leftNormal.y());
1951 QPointF rightNormal(1, -rightA);
1952 rightNormal /= qSqrt(rightNormal.x() * rightNormal.x() + rightNormal.y() * rightNormal.y());
1953
1954 qreal left_padding = xpadding / qAbs(leftNormal.x());
1955 qreal right_padding = xpadding / qAbs(rightNormal.x());
1956
1957 glVertex2d(bounds_topLeftX - left_padding, topY);
1958 glVertex2d(bounds_topRightX + right_padding, topY);
1959 glVertex2d(bounds_bottomRightX + right_padding, bottomY);
1960 glVertex2d(bounds_bottomLeftX - left_padding, bottomY);
1961
1962 glTexCoord4f(0.0f, 0.0f, 0.0f, 1.0f);
1963}
1964#endif // !Q_WS_QWS
1965
1966class QOpenGLTrapezoidToArrayTessellator : public QOpenGLTessellator
1967{
1968public:
1969 QOpenGLTrapezoidToArrayTessellator() : vertices(0), allocated(0), size(0) {}
1970 ~QOpenGLTrapezoidToArrayTessellator() { free(vertices); }
1971 q_vertexType *vertices;
1972 int allocated;
1973 int size;
1974 QRectF bounds;
1975 void addTrap(const Trapezoid &trap);
1976 void tessellate(const QPointF *points, int nPoints, bool winding) {
1977 size = 0;
1978 setWinding(winding);
1979 bounds = QTessellator::tessellate(points, nPoints);
1980 }
1981};
1982
1983void QOpenGLTrapezoidToArrayTessellator::addTrap(const Trapezoid &trap)
1984{
1985 // On OpenGL ES we convert the trap to 2 triangles
1986#ifndef QT_OPENGL_ES_1
1987 if (size > allocated - 8) {
1988#else
1989 if (size > allocated - 12) {
1990#endif
1991 allocated = qMax(2*allocated, 512);
1992 vertices = (q_vertexType *)realloc(vertices, allocated * sizeof(q_vertexType));
1993 }
1994
1995 QGLTrapezoid t = toGLTrapezoid(trap);
1996
1997#ifndef QT_OPENGL_ES_1
1998 vertices[size++] = t.topLeftX;
1999 vertices[size++] = t.top;
2000 vertices[size++] = t.topRightX;
2001 vertices[size++] = t.top;
2002 vertices[size++] = t.bottomRightX;
2003 vertices[size++] = t.bottom;
2004 vertices[size++] = t.bottomLeftX;
2005 vertices[size++] = t.bottom;
2006#else
2007 // First triangle
2008 vertices[size++] = t.topLeftX;
2009 vertices[size++] = t.top;
2010 vertices[size++] = t.topRightX;
2011 vertices[size++] = t.top;
2012 vertices[size++] = t.bottomRightX;
2013 vertices[size++] = t.bottom;
2014
2015 // Second triangle
2016 vertices[size++] = t.bottomLeftX;
2017 vertices[size++] = t.bottom;
2018 vertices[size++] = t.topLeftX;
2019 vertices[size++] = t.top;
2020 vertices[size++] = t.bottomRightX;
2021 vertices[size++] = t.bottom;
2022#endif
2023}
2024
2025
2026void QOpenGLPaintEnginePrivate::fillPolygon_dev(const QPointF *polygonPoints, int pointCount,
2027 Qt::FillRule fill)
2028{
2029 QOpenGLTrapezoidToArrayTessellator tessellator;
2030 tessellator.tessellate(polygonPoints, pointCount, fill == Qt::WindingFill);
2031
2032 DEBUG_ONCE qDebug() << "QOpenGLPaintEnginePrivate: Drawing polygon with" << pointCount << "points using fillPolygon_dev";
2033
2034 setGradientOps(cbrush, tessellator.bounds);
2035
2036 bool fast_style = current_style == Qt::LinearGradientPattern
2037 || current_style == Qt::SolidPattern;
2038
2039#ifndef QT_OPENGL_ES
2040 GLenum geometry_mode = GL_QUADS;
2041#else
2042 GLenum geometry_mode = GL_TRIANGLES;
2043#endif
2044
2045 if (use_fragment_programs && !(fast_style && has_fast_composition_mode)) {
2046 composite(geometry_mode, tessellator.vertices, tessellator.size / 2);
2047 } else {
2048 glVertexPointer(2, q_vertexTypeEnum, 0, tessellator.vertices);
2049 glEnableClientState(GL_VERTEX_ARRAY);
2050 glDrawArrays(geometry_mode, 0, tessellator.size/2);
2051 glDisableClientState(GL_VERTEX_ARRAY);
2052 }
2053}
2054
2055
2056inline void QOpenGLPaintEnginePrivate::lineToStencil(qreal x, qreal y)
2057{
2058 tess_points.add(QPointF(x, y));
2059
2060 if (x > max_x)
2061 max_x = x;
2062 else if (x < min_x)
2063 min_x = x;
2064 if (y > max_y)
2065 max_y = y;
2066 else if (y < min_y)
2067 min_y = y;
2068}
2069
2070inline void QOpenGLPaintEnginePrivate::curveToStencil(const QPointF &cp1, const QPointF &cp2, const QPointF &ep)
2071{
2072 qreal inverseScaleHalf = inverseScale / 2;
2073
2074 QBezier beziers[32];
2075 beziers[0] = QBezier::fromPoints(tess_points.last(), cp1, cp2, ep);
2076 QBezier *b = beziers;
2077 while (b >= beziers) {
2078 // check if we can pop the top bezier curve from the stack
2079 qreal l = qAbs(b->x4 - b->x1) + qAbs(b->y4 - b->y1);
2080 qreal d;
2081 if (l > inverseScale) {
2082 d = qAbs( (b->x4 - b->x1)*(b->y1 - b->y2) - (b->y4 - b->y1)*(b->x1 - b->x2) )
2083 + qAbs( (b->x4 - b->x1)*(b->y1 - b->y3) - (b->y4 - b->y1)*(b->x1 - b->x3) );
2084 d /= l;
2085 } else {
2086 d = qAbs(b->x1 - b->x2) + qAbs(b->y1 - b->y2) +
2087 qAbs(b->x1 - b->x3) + qAbs(b->y1 - b->y3);
2088 }
2089 if (d < inverseScaleHalf || b == beziers + 31) {
2090 // good enough, we pop it off and add the endpoint
2091 lineToStencil(b->x4, b->y4);
2092 --b;
2093 } else {
2094 // split, second half of the polygon goes lower into the stack
2095 b->split(b+1, b);
2096 ++b;
2097 }
2098 }
2099}
2100
2101
2102void QOpenGLPaintEnginePrivate::pathToVertexArrays(const QPainterPath &path)
2103{
2104 const QPainterPath::Element &first = path.elementAt(0);
2105 min_x = max_x = first.x;
2106 min_y = max_y = first.y;
2107
2108 tess_points.reset();
2109 tess_points_stops.clear();
2110 lineToStencil(first.x, first.y);
2111
2112 for (int i=1; i<path.elementCount(); ++i) {
2113 const QPainterPath::Element &e = path.elementAt(i);
2114 switch (e.type) {
2115 case QPainterPath::MoveToElement:
2116 tess_points_stops.append(tess_points.size());
2117 lineToStencil(e.x, e.y);
2118 break;
2119 case QPainterPath::LineToElement:
2120 lineToStencil(e.x, e.y);
2121 break;
2122 case QPainterPath::CurveToElement:
2123 curveToStencil(e, path.elementAt(i+1), path.elementAt(i+2));
2124 i+=2;
2125 break;
2126 default:
2127 break;
2128 }
2129 }
2130 lineToStencil(first.x, first.y);
2131 tess_points_stops.append(tess_points.size());
2132}
2133
2134
2135void QOpenGLPaintEnginePrivate::drawVertexArrays()
2136{
2137 glEnableClientState(GL_VERTEX_ARRAY);
2138 glVertexPointer(2, GL_DOUBLE, 0, tess_points.data());
2139 int previous_stop = 0;
2140 foreach(int stop, tess_points_stops) {
2141 glDrawArrays(GL_TRIANGLE_FAN, previous_stop, stop-previous_stop);
2142 previous_stop = stop;
2143 }
2144 glDisableClientState(GL_VERTEX_ARRAY);
2145}
2146
2147void QOpenGLPaintEnginePrivate::fillVertexArray(Qt::FillRule fillRule)
2148{
2149 Q_Q(QOpenGLPaintEngine);
2150
2151 if (dirty_stencil) {
2152 disableClipping();
2153
2154 if (use_system_clip) {
2155 glEnable(GL_SCISSOR_TEST);
2156
2157 QRect rect = q->systemClip().boundingRect();
2158
2159 const int left = rect.left();
2160 const int width = rect.width();
2161 const int bottom = drawable.size().height() - (rect.bottom() + 1);
2162 const int height = rect.height();
2163
2164 glScissor(left, bottom, width, height);
2165 }
2166
2167 glClearStencil(0);
2168 glClear(GL_STENCIL_BUFFER_BIT);
2169 dirty_stencil = false;
2170
2171 if (use_system_clip)
2172 glDisable(GL_SCISSOR_TEST);
2173
2174 enableClipping();
2175 }
2176
2177 glStencilMask(~0);
2178
2179 // Enable stencil.
2180 glEnable(GL_STENCIL_TEST);
2181
2182 // Disable color writes.
2183 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
2184
2185 GLuint stencilMask = 0;
2186
2187 if (fillRule == Qt::OddEvenFill) {
2188 stencilMask = 1;
2189
2190 // Enable stencil writes.
2191 glStencilMask(stencilMask);
2192
2193 // Set stencil xor mode.
2194 glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT);
2195
2196 // Disable stencil func.
2197 glStencilFunc(GL_ALWAYS, 0, ~0);
2198
2199 drawVertexArrays();
2200 } else if (fillRule == Qt::WindingFill) {
2201 stencilMask = ~0;
2202
2203 if (has_stencil_face_ext) {
2204 QGL_FUNC_CONTEXT;
2205 glEnable(GL_STENCIL_TEST_TWO_SIDE_EXT);
2206
2207 glActiveStencilFaceEXT(GL_BACK);
2208 glStencilOp(GL_KEEP, GL_KEEP, GL_DECR_WRAP_EXT);
2209 glStencilFunc(GL_ALWAYS, 0, ~0);
2210
2211 glActiveStencilFaceEXT(GL_FRONT);
2212 glStencilOp(GL_KEEP, GL_KEEP, GL_INCR_WRAP_EXT);
2213 glStencilFunc(GL_ALWAYS, 0, ~0);
2214
2215 drawVertexArrays();
2216
2217 glDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);
2218 } else {
2219 glStencilFunc(GL_ALWAYS, 0, ~0);
2220 glEnable(GL_CULL_FACE);
2221
2222 glCullFace(GL_BACK);
2223 glStencilOp(GL_KEEP, GL_KEEP, GL_INCR_WRAP_EXT);
2224 drawVertexArrays();
2225
2226 glCullFace(GL_FRONT);
2227 glStencilOp(GL_KEEP, GL_KEEP, GL_DECR_WRAP_EXT);
2228 drawVertexArrays();
2229
2230 glDisable(GL_CULL_FACE);
2231 }
2232 }
2233
2234 // Enable color writes.
2235 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
2236 glStencilMask(0);
2237
2238 setGradientOps(cbrush, QRectF(QPointF(min_x, min_y), QSizeF(max_x - min_x, max_y - min_y)));
2239
2240 bool fast_fill = has_fast_composition_mode && (current_style == Qt::LinearGradientPattern || current_style == Qt::SolidPattern);
2241
2242 if (use_fragment_programs && !fast_fill) {
2243 DEBUG_ONCE qDebug() << "QOpenGLPaintEnginePrivate: Drawing polygon using stencil method (fragment programs)";
2244 QRectF rect(QPointF(min_x, min_y), QSizeF(max_x - min_x, max_y - min_y));
2245
2246 // Enable stencil func.
2247 glStencilFunc(GL_NOTEQUAL, 0, stencilMask);
2248 composite(rect);
2249 } else {
2250 DEBUG_ONCE qDebug() << "QOpenGLPaintEnginePrivate: Drawing polygon using stencil method (no fragment programs)";
2251
2252 // Enable stencil func.
2253 glStencilFunc(GL_NOTEQUAL, 0, stencilMask);
2254#ifndef QT_OPENGL_ES
2255 glBegin(GL_QUADS);
2256 glVertex2f(min_x, min_y);
2257 glVertex2f(max_x, min_y);
2258 glVertex2f(max_x, max_y);
2259 glVertex2f(min_x, max_y);
2260 glEnd();
2261#endif
2262 }
2263
2264 glStencilMask(~0);
2265 glStencilFunc(GL_ALWAYS, 0, 0);
2266 glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO);
2267
2268 // clear all stencil values to 0
2269 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
2270
2271#ifndef QT_OPENGL_ES
2272 glBegin(GL_QUADS);
2273 glVertex2f(min_x, min_y);
2274 glVertex2f(max_x, min_y);
2275 glVertex2f(max_x, max_y);
2276 glVertex2f(min_x, max_y);
2277 glEnd();
2278#endif
2279
2280 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
2281
2282 // Disable stencil writes.
2283 glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
2284 glStencilMask(0);
2285 glDisable(GL_STENCIL_TEST);
2286}
2287
2288void QOpenGLPaintEnginePrivate::fillPath(const QPainterPath &path)
2289{
2290 if (path.isEmpty())
2291 return;
2292
2293 if (use_stencil_method && !high_quality_antialiasing) {
2294 pathToVertexArrays(path);
2295 fillVertexArray(path.fillRule());
2296 return;
2297 }
2298
2299 glMatrixMode(GL_MODELVIEW);
2300 glLoadIdentity();
2301
2302 if (high_quality_antialiasing)
2303 drawOffscreenPath(path);
2304 else {
2305 QPolygonF poly = path.toFillPolygon(matrix);
2306 fillPolygon_dev(poly.data(), poly.count(),
2307 path.fillRule());
2308 }
2309
2310 updateGLMatrix();
2311}
2312
2313
2314static inline bool needsEmulation(Qt::BrushStyle style)
2315{
2316 return !(style == Qt::SolidPattern
2317 || (style == Qt::LinearGradientPattern
2318 && (QGLExtensions::glExtensions & QGLExtensions::MirroredRepeat)));
2319}
2320
2321void QOpenGLPaintEnginePrivate::updateUseEmulation()
2322{
2323 use_emulation = !use_fragment_programs
2324 && ((has_pen && needsEmulation(pen_brush_style))
2325 || (has_brush && needsEmulation(brush_style)));
2326}
2327
2328void QOpenGLPaintEngine::updatePen(const QPen &pen)
2329{
2330 Q_D(QOpenGLPaintEngine);
2331 Qt::PenStyle pen_style = pen.style();
2332 d->pen_brush_style = pen.brush().style();
2333 d->cpen = pen;
2334 d->has_pen = (pen_style != Qt::NoPen);
2335 d->updateUseEmulation();
2336
2337 if (pen.isCosmetic()) {
2338 GLfloat width = pen.widthF() == 0.0f ? 1.0f : pen.widthF();
2339 glLineWidth(width);
2340 glPointSize(width);
2341 }
2342
2343 if (d->pen_brush_style >= Qt::LinearGradientPattern
2344 && d->pen_brush_style <= Qt::ConicalGradientPattern)
2345 {
2346 d->setGLPen(Qt::white);
2347 } else {
2348 d->setGLPen(pen.color());
2349 }
2350
2351 d->updateFastPen();
2352}
2353
2354void QOpenGLPaintEngine::updateBrush(const QBrush &brush, const QPointF &origin)
2355{
2356 Q_D(QOpenGLPaintEngine);
2357 d->cbrush = brush;
2358 d->brush_style = brush.style();
2359 d->brush_origin = origin;
2360 d->has_brush = (d->brush_style != Qt::NoBrush);
2361 d->updateUseEmulation();
2362}
2363
2364void QOpenGLPaintEngine::updateFont(const QFont &)
2365{
2366}
2367
2368void QOpenGLPaintEngine::updateMatrix(const QTransform &mtx)
2369{
2370 Q_D(QOpenGLPaintEngine);
2371
2372 d->matrix = mtx;
2373
2374 d->mv_matrix[0][0] = mtx.m11();
2375 d->mv_matrix[0][1] = mtx.m12();
2376 d->mv_matrix[0][2] = 0;
2377 d->mv_matrix[0][3] = mtx.m13();
2378
2379 d->mv_matrix[1][0] = mtx.m21();
2380 d->mv_matrix[1][1] = mtx.m22();
2381 d->mv_matrix[1][2] = 0;
2382 d->mv_matrix[1][3] = mtx.m23();
2383
2384 d->mv_matrix[2][0] = 0;
2385 d->mv_matrix[2][1] = 0;
2386 d->mv_matrix[2][2] = 1;
2387 d->mv_matrix[2][3] = 0;
2388
2389 d->mv_matrix[3][0] = mtx.dx();
2390 d->mv_matrix[3][1] = mtx.dy();
2391 d->mv_matrix[3][2] = 0;
2392 d->mv_matrix[3][3] = mtx.m33();
2393
2394 d->txop = mtx.type();
2395
2396 // 1/10000 == 0.0001, so we have good enough res to cover curves
2397 // that span the entire widget...
2398 d->inverseScale = qMax(1 / qMax( qMax(qAbs(mtx.m11()), qAbs(mtx.m22())),
2399 qMax(qAbs(mtx.m12()), qAbs(mtx.m21())) ),
2400 qreal(0.0001));
2401
2402 d->updateGLMatrix();
2403 d->updateFastPen();
2404}
2405
2406void QOpenGLPaintEnginePrivate::updateGLMatrix() const
2407{
2408 glMatrixMode(GL_MODELVIEW);
2409#ifndef QT_OPENGL_ES
2410 glLoadMatrixd(&mv_matrix[0][0]);
2411#else
2412 glLoadMatrixf(&mv_matrix[0][0]);
2413#endif
2414}
2415
2416void QOpenGLPaintEnginePrivate::disableClipping()
2417{
2418 glDisable(GL_DEPTH_TEST);
2419 glDisable(GL_SCISSOR_TEST);
2420}
2421
2422void QOpenGLPaintEnginePrivate::enableClipping()
2423{
2424 Q_Q(QOpenGLPaintEngine);
2425 if (!q->state()->hasClipping)
2426 return;
2427
2428 if (q->state()->fastClip.isEmpty())
2429 glEnable(GL_DEPTH_TEST);
2430 else
2431 updateDepthClip(); // this will enable the scissor test
2432}
2433
2434void QOpenGLPaintEnginePrivate::updateDepthClip()
2435{
2436 Q_Q(QOpenGLPaintEngine);
2437
2438 glDisable(GL_DEPTH_TEST);
2439 glDisable(GL_SCISSOR_TEST);
2440
2441 if (!q->state()->hasClipping)
2442 return;
2443
2444 QRect fastClip;
2445 if (q->state()->clipEnabled) {
2446 fastClip = q->state()->fastClip;
2447 } else if (use_system_clip && q->systemClip().rects().count() == 1) {
2448 fastClip = q->systemClip().rects().at(0);
2449 }
2450
2451 if (!fastClip.isEmpty()) {
2452 glEnable(GL_SCISSOR_TEST);
2453
2454 const int left = fastClip.left();
2455 const int width = fastClip.width();
2456 const int bottom = drawable.size().height() - (fastClip.bottom() + 1);
2457 const int height = fastClip.height();
2458
2459 glScissor(left, bottom, width, height);
2460 return;
2461 }
2462
2463#ifndef QT_OPENGL_ES
2464 glClearDepth(0.0f);
2465#else
2466 glClearDepthf(0.0f);
2467#endif
2468 glEnable(GL_DEPTH_TEST);
2469 glDepthMask(GL_TRUE);
2470 glClear(GL_DEPTH_BUFFER_BIT);
2471
2472 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
2473 glDepthFunc(GL_ALWAYS);
2474
2475 const QVector<QRect> rects = q->state()->clipEnabled ? q->state()->clipRegion.rects() : q->systemClip().rects();
2476
2477 // rectangle count * 2 (triangles) * vertex count * component count (Z omitted)
2478 QDataBuffer<q_vertexType> clipVertex(rects.size()*2*3*2);
2479 for (int i = 0; i < rects.size(); ++i) {
2480 q_vertexType x = i2vt(rects.at(i).left());
2481 q_vertexType w = i2vt(rects.at(i).width());
2482 q_vertexType h = i2vt(rects.at(i).height());
2483 q_vertexType y = i2vt(rects.at(i).top());
2484
2485 // First triangle
2486 clipVertex.add(x);
2487 clipVertex.add(y);
2488
2489 clipVertex.add(x);
2490 clipVertex.add(y + h);
2491
2492 clipVertex.add(x + w);
2493 clipVertex.add(y);
2494
2495 // Second triangle
2496 clipVertex.add(x);
2497 clipVertex.add(y + h);
2498
2499 clipVertex.add(x + w);
2500 clipVertex.add(y + h);
2501
2502 clipVertex.add (x + w);
2503 clipVertex.add(y);
2504 }
2505
2506 if (rects.size()) {
2507 glMatrixMode(GL_MODELVIEW);
2508 glLoadIdentity();
2509
2510 glEnableClientState(GL_VERTEX_ARRAY);
2511 glVertexPointer(2, q_vertexTypeEnum, 0, clipVertex.data());
2512
2513 glDrawArrays(GL_TRIANGLES, 0, rects.size()*2*3);
2514 glDisableClientState(GL_VERTEX_ARRAY);
2515 updateGLMatrix();
2516 }
2517
2518 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
2519 glDepthMask(GL_FALSE);
2520 glDepthFunc(GL_LEQUAL);
2521}
2522
2523void QOpenGLPaintEnginePrivate::systemStateChanged()
2524{
2525 Q_Q(QOpenGLPaintEngine);
2526 if (q->state()->hasClipping)
2527 q->updateClipRegion(q->painter()->clipRegion(), Qt::ReplaceClip);
2528 else
2529 q->updateClipRegion(QRegion(), Qt::NoClip);
2530}
2531
2532void QOpenGLPaintEngine::updateClipRegion(const QRegion &clipRegion, Qt::ClipOperation op)
2533{
2534 Q_D(QOpenGLPaintEngine);
2535
2536 // clipping is only supported when a stencil or depth buffer is
2537 // available
2538 if (!d->drawable.format().depth())
2539 return;
2540
2541 d->use_system_clip = false;
2542 QRegion sysClip = systemClip();
2543 if (!sysClip.isEmpty()) {
2544 if (d->pdev->devType() != QInternal::Widget) {
2545 d->use_system_clip = true;
2546 } else {
2547#ifndef Q_WS_QWS
2548 // Only use the system clip if we're currently rendering a widget with a GL painter.
2549 if (d->currentClipWidget) {
2550 QWidgetPrivate *widgetPrivate = qt_widget_private(d->currentClipWidget->window());
2551 d->use_system_clip = widgetPrivate->extra && widgetPrivate->extra->inRenderWithPainter;
2552 }
2553#endif
2554 }
2555 }
2556
2557 d->flushDrawQueue();
2558
2559 if (op == Qt::NoClip && !d->use_system_clip) {
2560 state()->hasClipping = false;
2561 state()->clipRegion = QRegion();
2562 d->updateDepthClip();
2563 return;
2564 }
2565
2566 bool isScreenClip = false;
2567 if (!d->use_system_clip) {
2568 QVector<QRect> untransformedRects = clipRegion.rects();
2569
2570 if (untransformedRects.size() == 1) {
2571 QPainterPath path;
2572 path.addRect(untransformedRects[0]);
2573 path = d->matrix.map(path);
2574
2575 if (path.contains(QRectF(QPointF(), d->drawable.size())))
2576 isScreenClip = true;
2577 }
2578 }
2579
2580 QRegion region = isScreenClip ? QRegion() : clipRegion * d->matrix;
2581 switch (op) {
2582 case Qt::NoClip:
2583 if (!d->use_system_clip)
2584 break;
2585 state()->clipRegion = sysClip;
2586 break;
2587 case Qt::IntersectClip:
2588 if (isScreenClip)
2589 return;
2590 if (state()->hasClipping) {
2591 state()->clipRegion &= region;
2592 break;
2593 }
2594 // fall through
2595 case Qt::ReplaceClip:
2596 if (d->use_system_clip)
2597 state()->clipRegion = region & sysClip;
2598 else
2599 state()->clipRegion = region;
2600 break;
2601 case Qt::UniteClip:
2602 state()->clipRegion |= region;
2603 if (d->use_system_clip)
2604 state()->clipRegion &= sysClip;
2605 break;
2606 default:
2607 break;
2608 }
2609
2610 if (isScreenClip) {
2611 state()->hasClipping = false;
2612 state()->clipRegion = QRegion();
2613 } else {
2614 state()->hasClipping = op != Qt::NoClip || d->use_system_clip;
2615 }
2616
2617 if (state()->hasClipping && state()->clipRegion.rects().size() == 1)
2618 state()->fastClip = state()->clipRegion.rects().at(0);
2619 else
2620 state()->fastClip = QRect();
2621
2622 d->updateDepthClip();
2623}
2624
2625void QOpenGLPaintEngine::updateRenderHints(QPainter::RenderHints hints)
2626{
2627 Q_D(QOpenGLPaintEngine);
2628
2629 d->flushDrawQueue();
2630 d->use_smooth_pixmap_transform = bool(hints & QPainter::SmoothPixmapTransform);
2631 if ((hints & QPainter::Antialiasing) || (hints & QPainter::HighQualityAntialiasing)) {
2632 if (d->use_fragment_programs && QGLOffscreen::isSupported()
2633 && (hints & QPainter::HighQualityAntialiasing)) {
2634 d->high_quality_antialiasing = true;
2635 } else {
2636 d->high_quality_antialiasing = false;
2637 if (QGLExtensions::glExtensions & QGLExtensions::SampleBuffers)
2638 glEnable(GL_MULTISAMPLE);
2639 }
2640 } else {
2641 d->high_quality_antialiasing = false;
2642 if (QGLExtensions::glExtensions & QGLExtensions::SampleBuffers)
2643 glDisable(GL_MULTISAMPLE);
2644 }
2645
2646 if (d->high_quality_antialiasing) {
2647 d->offscreen.initialize();
2648
2649 if (!d->offscreen.isValid()) {
2650 DEBUG_ONCE_STR("Unable to initialize offscreen, disabling high quality antialiasing");
2651 d->high_quality_antialiasing = false;
2652 if (QGLExtensions::glExtensions & QGLExtensions::SampleBuffers)
2653 glEnable(GL_MULTISAMPLE);
2654 }
2655 }
2656
2657 d->has_antialiasing = d->high_quality_antialiasing
2658 || ((hints & QPainter::Antialiasing)
2659 && (QGLExtensions::glExtensions & QGLExtensions::SampleBuffers));
2660}
2661
2662
2663void QOpenGLPaintEnginePrivate::setPorterDuffData(float a, float b, float x, float y, float z)
2664{
2665 porterduff_ab_data[0] = a;
2666 porterduff_ab_data[1] = b;
2667
2668 porterduff_xyz_data[0] = x;
2669 porterduff_xyz_data[1] = y;
2670 porterduff_xyz_data[2] = z;
2671}
2672
2673
2674void QOpenGLPaintEngine::updateCompositionMode(QPainter::CompositionMode composition_mode)
2675{
2676 Q_D(QOpenGLPaintEngine);
2677
2678 if (!d->use_fragment_programs && composition_mode > QPainter::CompositionMode_Plus)
2679 composition_mode = QPainter::CompositionMode_SourceOver;
2680
2681 d->composition_mode = composition_mode;
2682
2683 d->has_fast_composition_mode = (!d->high_quality_antialiasing && composition_mode <= QPainter::CompositionMode_Plus)
2684 || composition_mode == QPainter::CompositionMode_SourceOver
2685 || composition_mode == QPainter::CompositionMode_Destination
2686 || composition_mode == QPainter::CompositionMode_DestinationOver
2687 || composition_mode == QPainter::CompositionMode_DestinationOut
2688 || composition_mode == QPainter::CompositionMode_SourceAtop
2689 || composition_mode == QPainter::CompositionMode_Xor
2690 || composition_mode == QPainter::CompositionMode_Plus;
2691
2692 if (d->has_fast_composition_mode)
2693 d->fragment_composition_mode = d->high_quality_antialiasing ? COMPOSITION_MODE_BLEND_MODE_MASK : COMPOSITION_MODE_BLEND_MODE_NOMASK;
2694 else if (composition_mode <= QPainter::CompositionMode_Plus)
2695 d->fragment_composition_mode = d->high_quality_antialiasing ? COMPOSITION_MODES_SIMPLE_PORTER_DUFF : COMPOSITION_MODES_SIMPLE_PORTER_DUFF_NOMASK;
2696 else
2697 switch (composition_mode) {
2698 case QPainter::CompositionMode_Multiply:
2699 d->fragment_composition_mode = d->high_quality_antialiasing ? COMPOSITION_MODES_MULTIPLY : COMPOSITION_MODES_MULTIPLY_NOMASK;
2700 break;
2701 case QPainter::CompositionMode_Screen:
2702 d->fragment_composition_mode = d->high_quality_antialiasing ? COMPOSITION_MODES_SCREEN : COMPOSITION_MODES_SCREEN_NOMASK;
2703 break;
2704 case QPainter::CompositionMode_Overlay:
2705 d->fragment_composition_mode = d->high_quality_antialiasing ? COMPOSITION_MODES_OVERLAY : COMPOSITION_MODES_OVERLAY_NOMASK;
2706 break;
2707 case QPainter::CompositionMode_Darken:
2708 d->fragment_composition_mode = d->high_quality_antialiasing ? COMPOSITION_MODES_DARKEN : COMPOSITION_MODES_DARKEN_NOMASK;
2709 break;
2710 case QPainter::CompositionMode_Lighten:
2711 d->fragment_composition_mode = d->high_quality_antialiasing ? COMPOSITION_MODES_LIGHTEN : COMPOSITION_MODES_LIGHTEN_NOMASK;
2712 break;
2713 case QPainter::CompositionMode_ColorDodge:
2714 d->fragment_composition_mode = d->high_quality_antialiasing ? COMPOSITION_MODES_COLORDODGE : COMPOSITION_MODES_COLORDODGE_NOMASK;
2715 break;
2716 case QPainter::CompositionMode_ColorBurn:
2717 d->fragment_composition_mode = d->high_quality_antialiasing ? COMPOSITION_MODES_COLORBURN : COMPOSITION_MODES_COLORBURN_NOMASK;
2718 break;
2719 case QPainter::CompositionMode_HardLight:
2720 d->fragment_composition_mode = d->high_quality_antialiasing ? COMPOSITION_MODES_HARDLIGHT : COMPOSITION_MODES_HARDLIGHT_NOMASK;
2721 break;
2722 case QPainter::CompositionMode_SoftLight:
2723 d->fragment_composition_mode = d->high_quality_antialiasing ? COMPOSITION_MODES_SOFTLIGHT : COMPOSITION_MODES_SOFTLIGHT_NOMASK;
2724 break;
2725 case QPainter::CompositionMode_Difference:
2726 d->fragment_composition_mode = d->high_quality_antialiasing ? COMPOSITION_MODES_DIFFERENCE : COMPOSITION_MODES_DIFFERENCE_NOMASK;
2727 break;
2728 case QPainter::CompositionMode_Exclusion:
2729 d->fragment_composition_mode = d->high_quality_antialiasing ? COMPOSITION_MODES_EXCLUSION : COMPOSITION_MODES_EXCLUSION_NOMASK;
2730 break;
2731 default:
2732 Q_ASSERT(false);
2733 }
2734
2735 switch(composition_mode) {
2736 case QPainter::CompositionMode_DestinationOver:
2737 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE);
2738 d->setPorterDuffData(0, 1, 1, 1, 1);
2739 break;
2740 case QPainter::CompositionMode_Clear:
2741 glBlendFunc(GL_ZERO, GL_ZERO);
2742 d->setPorterDuffData(0, 0, 0, 0, 0);
2743 break;
2744 case QPainter::CompositionMode_Source:
2745 glBlendFunc(GL_ONE, GL_ZERO);
2746 d->setPorterDuffData(1, 0, 1, 1, 0);
2747 break;
2748 case QPainter::CompositionMode_Destination:
2749 glBlendFunc(GL_ZERO, GL_ONE);
2750 d->setPorterDuffData(0, 1, 1, 0, 1);
2751 break;
2752 case QPainter::CompositionMode_SourceIn:
2753 glBlendFunc(GL_DST_ALPHA, GL_ZERO);
2754 d->setPorterDuffData(1, 0, 1, 0, 0);
2755 break;
2756 case QPainter::CompositionMode_DestinationIn:
2757 glBlendFunc(GL_ZERO, GL_SRC_ALPHA);
2758 d->setPorterDuffData(0, 1, 1, 0, 0);
2759 break;
2760 case QPainter::CompositionMode_SourceOut:
2761 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ZERO);
2762 d->setPorterDuffData(0, 0, 0, 1, 0);
2763 break;
2764 case QPainter::CompositionMode_DestinationOut:
2765 glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_ALPHA);
2766 d->setPorterDuffData(0, 0, 0, 0, 1);
2767 break;
2768 case QPainter::CompositionMode_SourceAtop:
2769 glBlendFunc(GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2770 d->setPorterDuffData(1, 0, 1, 0, 1);
2771 break;
2772 case QPainter::CompositionMode_DestinationAtop:
2773 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA);
2774 d->setPorterDuffData(0, 1, 1, 1, 0);
2775 break;
2776 case QPainter::CompositionMode_Xor:
2777 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2778 d->setPorterDuffData(0, 0, 0, 1, 1);
2779 break;
2780 case QPainter::CompositionMode_SourceOver:
2781 glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
2782 d->setPorterDuffData(1, 0, 1, 1, 1);
2783 break;
2784 case QPainter::CompositionMode_Plus:
2785 glBlendFunc(GL_ONE, GL_ONE);
2786 d->setPorterDuffData(1, 1, 1, 1, 1);
2787 break;
2788 default:
2789 break;
2790 }
2791}
2792
2793class QGLMaskGenerator
2794{
2795public:
2796 QGLMaskGenerator(const QPainterPath &path, const QTransform &matrix, qreal stroke_width = -1)
2797 : p(path),
2798 m(matrix),
2799 w(stroke_width)
2800 {
2801 }
2802
2803 virtual QRect screenRect() = 0;
2804 virtual void drawMask(const QRect &rect) = 0;
2805
2806 QPainterPath path() const { return p; }
2807 QTransform matrix() const { return m; }
2808 qreal strokeWidth() const { return w; }
2809
2810 virtual ~QGLMaskGenerator() {}
2811
2812private:
2813 QPainterPath p;
2814 QTransform m;
2815 qreal w;
2816};
2817
2818void QGLMaskTextureCache::setOffscreenSize(const QSize &sz)
2819{
2820 Q_ASSERT(sz.width() == sz.height());
2821
2822 if (offscreenSize != sz) {
2823 offscreenSize = sz;
2824 clearCache();
2825 }
2826}
2827
2828void QGLMaskTextureCache::clearCache()
2829{
2830 cache.clear();
2831
2832 int quad_tree_size = 1;
2833
2834 for (int i = block_size; i < offscreenSize.width(); i *= 2)
2835 quad_tree_size += quad_tree_size * 4;
2836
2837 for (int i = 0; i < 4; ++i) {
2838 occupied_quadtree[i].resize(quad_tree_size);
2839
2840 occupied_quadtree[i][0].key = 0;
2841 occupied_quadtree[i][0].largest_available_block = offscreenSize.width();
2842 occupied_quadtree[i][0].largest_used_block = 0;
2843
2844 DEBUG_ONCE qDebug() << "QGLMaskTextureCache:: created quad tree of size" << quad_tree_size;
2845 }
2846}
2847
2848void QGLMaskTextureCache::setDrawableSize(const QSize &sz)
2849{
2850 drawableSize = sz;
2851}
2852
2853void QGLMaskTextureCache::maintainCache()
2854{
2855 QGLTextureCacheHash::iterator it = cache.begin();
2856 QGLTextureCacheHash::iterator end = cache.end();
2857
2858 while (it != end) {
2859 CacheInfo &cache_info = it.value();
2860 ++cache_info.age;
2861
2862 if (cache_info.age > 1) {
2863 quadtreeInsert(cache_info.loc.channel, 0, cache_info.loc.rect);
2864 it = cache.erase(it);
2865 } else {
2866 ++it;
2867 }
2868 }
2869}
2870
2871//#define DISABLE_MASK_CACHE
2872
2873QGLMaskTextureCache::CacheLocation QGLMaskTextureCache::getMask(QGLMaskGenerator &maskGenerator, QOpenGLPaintEnginePrivate *e)
2874{
2875#ifndef DISABLE_MASK_CACHE
2876 engine = e;
2877
2878 quint64 key = hash(maskGenerator.path(), maskGenerator.matrix(), maskGenerator.strokeWidth());
2879
2880 if (key == 0)
2881 key = 1;
2882
2883 CacheInfo info(maskGenerator.path(), maskGenerator.matrix(), maskGenerator.strokeWidth());
2884
2885 QGLTextureCacheHash::iterator it = cache.find(key);
2886
2887 while (it != cache.end() && it.key() == key) {
2888 CacheInfo &cache_info = it.value();
2889 if (info.stroke_width == cache_info.stroke_width && info.matrix == cache_info.matrix && info.path == cache_info.path) {
2890 DEBUG_ONCE_STR("QGLMaskTextureCache::getMask(): Using cached mask");
2891
2892 cache_info.age = 0;
2893 return cache_info.loc;
2894 }
2895 ++it;
2896 }
2897
2898 // mask was not found, create new mask
2899
2900 DEBUG_ONCE_STR("QGLMaskTextureCache::getMask(): Creating new mask...");
2901
2902 createMask(key, info, maskGenerator);
2903
2904 cache.insert(key, info);
2905
2906 return info.loc;
2907#else
2908 CacheInfo info(maskGenerator.path(), maskGenerator.matrix());
2909 createMask(0, info, maskGenerator);
2910 return info.loc;
2911#endif
2912}
2913
2914#ifndef FloatToQuint64
2915#define FloatToQuint64(i) (quint64)((i) * 32)
2916#endif
2917
2918quint64 QGLMaskTextureCache::hash(const QPainterPath &p, const QTransform &m, qreal w)
2919{
2920 Q_ASSERT(sizeof(quint64) == 8);
2921
2922 quint64 h = 0;
2923
2924 for (int i = 0; i < p.elementCount(); ++i) {
2925 h += FloatToQuint64(p.elementAt(i).x) << 32;
2926 h += FloatToQuint64(p.elementAt(i).y);
2927 h += p.elementAt(i).type;
2928 }
2929
2930 h += FloatToQuint64(m.m11());
2931#ifndef Q_OS_WINCE // ###
2932 //Compiler crashes for arm on WinCE
2933 h += FloatToQuint64(m.m12()) << 4;
2934 h += FloatToQuint64(m.m13()) << 8;
2935 h += FloatToQuint64(m.m21()) << 12;
2936 h += FloatToQuint64(m.m22()) << 16;
2937 h += FloatToQuint64(m.m23()) << 20;
2938 h += FloatToQuint64(m.m31()) << 24;
2939 h += FloatToQuint64(m.m32()) << 28;
2940#endif
2941 h += FloatToQuint64(m.m33()) << 32;
2942
2943 h += FloatToQuint64(w);
2944
2945 return h;
2946}
2947
2948void QGLMaskTextureCache::createMask(quint64 key, CacheInfo &info, QGLMaskGenerator &maskGenerator)
2949{
2950 info.loc.screen_rect = maskGenerator.screenRect();
2951
2952 if (info.loc.screen_rect.isEmpty()) {
2953 info.loc.channel = 0;
2954 info.loc.rect = QRect();
2955 return;
2956 }
2957
2958 quadtreeAllocate(key, info.loc.screen_rect.size(), &info.loc.rect, &info.loc.channel);
2959
2960 int ch = info.loc.channel;
2961 glColorMask(ch == 0, ch == 1, ch == 2, ch == 3);
2962
2963 maskGenerator.drawMask(info.loc.rect);
2964
2965 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
2966}
2967
2968int QGLMaskTextureCache::quadtreeBlocksize(int node)
2969{
2970 DEBUG_ONCE qDebug() << "Offscreen size:" << offscreenSize.width();
2971
2972 int blocksize = offscreenSize.width();
2973
2974 while (node) {
2975 node = (node - 1) / 4;
2976 blocksize /= 2;
2977 }
2978
2979 return blocksize;
2980}
2981
2982QPoint QGLMaskTextureCache::quadtreeLocation(int node)
2983{
2984 QPoint location;
2985 int blocksize = quadtreeBlocksize(node);
2986
2987 while (node) {
2988 --node;
2989
2990 if (node & 1)
2991 location.setX(location.x() + blocksize);
2992
2993 if (node & 2)
2994 location.setY(location.y() + blocksize);
2995
2996 node /= 4;
2997 blocksize *= 2;
2998 }
2999
3000 return location;
3001}
3002
3003void QGLMaskTextureCache::quadtreeUpdate(int channel, int node, int current_block_size)
3004{
3005 while (node) {
3006 node = (node - 1) / 4;
3007
3008 int first_child = node * 4 + 1;
3009
3010 int largest_available = 0;
3011 int largest_used = 0;
3012
3013 bool all_empty = true;
3014
3015 for (int i = 0; i < 4; ++i) {
3016 largest_available = qMax(largest_available, occupied_quadtree[channel][first_child + i].largest_available_block);
3017 largest_used = qMax(largest_used, occupied_quadtree[channel][first_child + i].largest_used_block);
3018
3019 if (occupied_quadtree[channel][first_child + i].largest_available_block < current_block_size)
3020 all_empty = false;
3021 }
3022
3023 current_block_size *= 2;
3024
3025 if (all_empty) {
3026 occupied_quadtree[channel][node].largest_available_block = current_block_size;
3027 occupied_quadtree[channel][node].largest_used_block = 0;
3028 } else {
3029 occupied_quadtree[channel][node].largest_available_block = largest_available;
3030 occupied_quadtree[channel][node].largest_used_block = largest_used;
3031 }
3032 }
3033}
3034
3035void QGLMaskTextureCache::quadtreeInsert(int channel, quint64 key, const QRect &rect, int node)
3036{
3037 int current_block_size = quadtreeBlocksize(node);
3038 QPoint location = quadtreeLocation(node);
3039 QRect relative = rect.translated(-location);
3040
3041 if (relative.left() >= current_block_size || relative.top() >= current_block_size
3042 || relative.right() < 0 || relative.bottom() < 0)
3043 return;
3044
3045 if (current_block_size == block_size // no more refining possible
3046 || (relative.top() < block_size && relative.bottom() >= (current_block_size - block_size)
3047 && relative.left() < block_size && relative.right() >= (current_block_size - block_size)))
3048 {
3049 if (key != 0) {
3050 occupied_quadtree[channel][node].largest_available_block = 0;
3051 occupied_quadtree[channel][node].largest_used_block = rect.width() * rect.height();
3052 } else {
3053 occupied_quadtree[channel][node].largest_available_block = current_block_size;
3054 occupied_quadtree[channel][node].largest_used_block = 0;
3055 }
3056
3057 occupied_quadtree[channel][node].key = key;
3058
3059 quadtreeUpdate(channel, node, current_block_size);
3060 } else {
3061 if (key && occupied_quadtree[channel][node].largest_available_block == current_block_size) {
3062 // refining the quad tree, initialize child nodes
3063 int half_block_size = current_block_size / 2;
3064
3065 int temp = node * 4 + 1;
3066 for (int sibling = 0; sibling < 4; ++sibling) {
3067 occupied_quadtree[channel][temp + sibling].largest_available_block = half_block_size;
3068 occupied_quadtree[channel][temp + sibling].largest_used_block = 0;
3069 occupied_quadtree[channel][temp + sibling].key = 0;
3070 }
3071 }
3072
3073 node = node * 4 + 1;
3074
3075 for (int sibling = 0; sibling < 4; ++sibling)
3076 quadtreeInsert(channel, key, rect, node + sibling);
3077 }
3078}
3079
3080void QGLMaskTextureCache::quadtreeClear(int channel, const QRect &rect, int node)
3081{
3082 const quint64 &key = occupied_quadtree[channel][node].key;
3083
3084 int current_block_size = quadtreeBlocksize(node);
3085 QPoint location = quadtreeLocation(node);
3086
3087 QRect relative = rect.translated(-location);
3088
3089 if (relative.left() >= current_block_size || relative.top() >= current_block_size
3090 || relative.right() < 0 || relative.bottom() < 0)
3091 return;
3092
3093 if (key != 0) {
3094 QGLTextureCacheHash::iterator it = cache.find(key);
3095
3096 Q_ASSERT(it != cache.end());
3097
3098 while (it != cache.end() && it.key() == key) {
3099 const CacheInfo &cache_info = it.value();
3100
3101 if (cache_info.loc.channel == channel
3102 && cache_info.loc.rect.left() <= location.x()
3103 && cache_info.loc.rect.top() <= location.y()
3104 && cache_info.loc.rect.right() >= location.x()
3105 && cache_info.loc.rect.bottom() >= location.y())
3106 {
3107 quadtreeInsert(channel, 0, cache_info.loc.rect);
3108 engine->cacheItemErased(channel, cache_info.loc.rect);
3109 cache.erase(it);
3110 goto found;
3111 } else {
3112 ++it;
3113 }
3114 }
3115
3116 // if we don't find the key there's an error in the quadtree
3117 Q_ASSERT(false);
3118found:
3119 Q_ASSERT(occupied_quadtree[channel][node].key == 0);
3120 } else if (occupied_quadtree[channel][node].largest_available_block < current_block_size) {
3121 Q_ASSERT(current_block_size >= block_size);
3122
3123 node = node * 4 + 1;
3124
3125 for (int sibling = 0; sibling < 4; ++sibling)
3126 quadtreeClear(channel, rect, node + sibling);
3127 }
3128}
3129
3130bool QGLMaskTextureCache::quadtreeFindAvailableLocation(const QSize &size, QRect *rect, int *channel)
3131{
3132 int needed_block_size = qMax(1, qMax(size.width(), size.height()));
3133
3134 for (int i = 0; i < 4; ++i) {
3135 int current_block_size = offscreenSize.width();
3136
3137 if (occupied_quadtree[i][0].largest_available_block >= needed_block_size) {
3138 int node = 0;
3139
3140 while (current_block_size != occupied_quadtree[i][node].largest_available_block) {
3141 Q_ASSERT(current_block_size > block_size);
3142 Q_ASSERT(current_block_size > occupied_quadtree[i][node].largest_available_block);
3143
3144 node = node * 4 + 1;
3145 current_block_size /= 2;
3146
3147 int sibling = 0;
3148
3149 while (occupied_quadtree[i][node + sibling].largest_available_block < needed_block_size)
3150 ++sibling;
3151
3152 Q_ASSERT(sibling < 4);
3153 node += sibling;
3154 }
3155
3156 *channel = i;
3157 *rect = QRect(quadtreeLocation(node), size);
3158
3159 return true;
3160 }
3161 }
3162
3163 return false;
3164}
3165
3166void QGLMaskTextureCache::quadtreeFindExistingLocation(const QSize &size, QRect *rect, int *channel)
3167{
3168 // try to pick small masks to throw out, as large masks are more expensive to recompute
3169 *channel = qrand() % 4;
3170 for (int i = 0; i < 4; ++i)
3171 if (occupied_quadtree[i][0].largest_used_block < occupied_quadtree[*channel][0].largest_used_block)
3172 *channel = i;
3173
3174 int needed_block_size = qt_next_power_of_two(qMax(1, qMax(size.width(), size.height())));
3175
3176 int node = 0;
3177 int current_block_size = offscreenSize.width();
3178
3179 while (current_block_size > block_size
3180 && current_block_size >= needed_block_size * 2
3181 && occupied_quadtree[*channel][node].key == 0)
3182 {
3183 node = node * 4 + 1;
3184
3185 int sibling = 0;
3186
3187 for (int i = 1; i < 4; ++i) {
3188 if (occupied_quadtree[*channel][node + i].largest_used_block
3189 <= occupied_quadtree[*channel][node + sibling].largest_used_block)
3190 {
3191 sibling = i;
3192 }
3193 }
3194
3195 node += sibling;
3196 current_block_size /= 2;
3197 }
3198
3199 *rect = QRect(quadtreeLocation(node), size);
3200}
3201
3202void QGLMaskTextureCache::quadtreeAllocate(quint64 key, const QSize &size, QRect *rect, int *channel)
3203{
3204#ifndef DISABLE_MASK_CACHE
3205 if (!quadtreeFindAvailableLocation(size, rect, channel)) {
3206 quadtreeFindExistingLocation(size, rect, channel);
3207 quadtreeClear(*channel, *rect);
3208 }
3209
3210 quadtreeInsert(*channel, key, *rect);
3211#else
3212 *channel = 0;
3213 *rect = QRect(QPoint(), size);
3214#endif
3215}
3216
3217class QGLTrapezoidMaskGenerator : public QGLMaskGenerator
3218{
3219public:
3220 QGLTrapezoidMaskGenerator(const QPainterPath &path, const QTransform &matrix, QGLOffscreen &offscreen, GLuint maskFragmentProgram, qreal strokeWidth = -1.0);
3221
3222 QRect screenRect();
3223 void drawMask(const QRect &rect);
3224
3225private:
3226 QRect screen_rect;
3227 bool has_screen_rect;
3228
3229 QGLOffscreen *offscreen;
3230
3231 GLuint maskFragmentProgram;
3232
3233 virtual QVector<QGLTrapezoid> generateTrapezoids() = 0;
3234 virtual QRect computeScreenRect() = 0;
3235};
3236
3237class QGLPathMaskGenerator : public QGLTrapezoidMaskGenerator
3238{
3239public:
3240 QGLPathMaskGenerator(const QPainterPath &path, const QTransform &matrix, QGLOffscreen &offscreen, GLuint maskFragmentProgram);
3241
3242private:
3243 QVector<QGLTrapezoid> generateTrapezoids();
3244 QRect computeScreenRect();
3245
3246 QPolygonF poly;
3247};
3248
3249class QGLLineMaskGenerator : public QGLTrapezoidMaskGenerator
3250{
3251public:
3252 QGLLineMaskGenerator(const QPainterPath &path, const QTransform &matrix, qreal width, QGLOffscreen &offscreen, GLuint maskFragmentProgram);
3253
3254private:
3255 QVector<QGLTrapezoid> generateTrapezoids();
3256 QRect computeScreenRect();
3257
3258 QPainterPath transformedPath;
3259};
3260
3261class QGLRectMaskGenerator : public QGLTrapezoidMaskGenerator
3262{
3263public:
3264 QGLRectMaskGenerator(const QPainterPath &path, const QTransform &matrix, QGLOffscreen &offscreen, GLuint maskFragmentProgram);
3265
3266private:
3267 QVector<QGLTrapezoid> generateTrapezoids();
3268 QRect computeScreenRect();
3269
3270 QPainterPath transformedPath;
3271};
3272
3273class QGLEllipseMaskGenerator : public QGLMaskGenerator
3274{
3275public:
3276 QGLEllipseMaskGenerator(const QRectF &rect, const QTransform &matrix, QGLOffscreen &offscreen, GLuint maskFragmentProgram, int *maskVariableLocations);
3277
3278 QRect screenRect();
3279 void drawMask(const QRect &rect);
3280
3281private:
3282 QRect screen_rect;
3283
3284 QRectF ellipseRect;
3285
3286 QGLOffscreen *offscreen;
3287
3288 GLuint maskFragmentProgram;
3289
3290 int *maskVariableLocations;
3291
3292 float vertexArray[4 * 2];
3293};
3294
3295QGLTrapezoidMaskGenerator::QGLTrapezoidMaskGenerator(const QPainterPath &path, const QTransform &matrix, QGLOffscreen &offs, GLuint program, qreal stroke_width)
3296 : QGLMaskGenerator(path, matrix, stroke_width)
3297 , has_screen_rect(false)
3298 , offscreen(&offs)
3299 , maskFragmentProgram(program)
3300{
3301}
3302
3303void QGLTrapezoidMaskGenerator::drawMask(const QRect &rect)
3304{
3305#ifdef QT_OPENGL_ES
3306 Q_UNUSED(rect);
3307#else
3308 glMatrixMode(GL_MODELVIEW);
3309 glPushMatrix();
3310 glLoadIdentity();
3311
3312 QGLContext *ctx = offscreen->context();
3313 offscreen->bind();
3314
3315 glDisable(GL_TEXTURE_GEN_S);
3316 glDisable(GL_TEXTURE_1D);
3317
3318 GLfloat vertexArray[4 * 2];
3319 qt_add_rect_to_array(rect, vertexArray);
3320
3321 bool needs_scissor = rect != screen_rect;
3322
3323 if (needs_scissor) {
3324 glEnable(GL_SCISSOR_TEST);
3325 glScissor(rect.left(), offscreen->offscreenSize().height() - rect.bottom() - 1, rect.width(), rect.height());
3326 }
3327
3328 QVector<QGLTrapezoid> trapezoids = generateTrapezoids();
3329
3330 // clear mask
3331 glBlendFunc(GL_ZERO, GL_ZERO); // clear
3332 glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
3333 glEnableClientState(GL_VERTEX_ARRAY);
3334 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
3335 glDisableClientState(GL_VERTEX_ARRAY);
3336
3337 glBlendFunc(GL_ONE, GL_ONE); // add mask
3338 glEnable(GL_FRAGMENT_PROGRAM_ARB);
3339 glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, maskFragmentProgram);
3340
3341 QPoint delta = rect.topLeft() - screen_rect.topLeft();
3342 glBegin(GL_QUADS);
3343 for (int i = 0; i < trapezoids.size(); ++i)
3344 drawTrapezoid(trapezoids[i].translated(delta), offscreen->offscreenSize().height(), ctx);
3345 glEnd();
3346
3347 if (needs_scissor)
3348 glDisable(GL_SCISSOR_TEST);
3349
3350 glDisable(GL_FRAGMENT_PROGRAM_ARB);
3351
3352 glMatrixMode(GL_MODELVIEW);
3353 glPopMatrix();
3354#endif
3355}
3356
3357QRect QGLTrapezoidMaskGenerator::screenRect()
3358{
3359 if (!has_screen_rect) {
3360 screen_rect = computeScreenRect();
3361 has_screen_rect = true;
3362 }
3363
3364 screen_rect = screen_rect.intersected(QRect(QPoint(), offscreen->drawableSize()));
3365
3366 return screen_rect;
3367}
3368
3369QGLPathMaskGenerator::QGLPathMaskGenerator(const QPainterPath &path, const QTransform &matrix, QGLOffscreen &offs, GLuint program)
3370 : QGLTrapezoidMaskGenerator(path, matrix, offs, program)
3371{
3372}
3373
3374QRect QGLPathMaskGenerator::computeScreenRect()
3375{
3376 poly = path().toFillPolygon(matrix());
3377 return poly.boundingRect().toAlignedRect();
3378}
3379
3380QVector<QGLTrapezoid> QGLPathMaskGenerator::generateTrapezoids()
3381{
3382 QOpenGLImmediateModeTessellator tessellator;
3383 tessellator.tessellate(poly.data(), poly.count(), path().fillRule() == Qt::WindingFill);
3384 return tessellator.trapezoids;
3385}
3386
3387QGLRectMaskGenerator::QGLRectMaskGenerator(const QPainterPath &path, const QTransform &matrix, QGLOffscreen &offs, GLuint program)
3388 : QGLTrapezoidMaskGenerator(path, matrix, offs, program)
3389{
3390}
3391
3392QGLLineMaskGenerator::QGLLineMaskGenerator(const QPainterPath &path, const QTransform &matrix, qreal width, QGLOffscreen &offs, GLuint program)
3393 : QGLTrapezoidMaskGenerator(path, matrix, offs, program, width)
3394{
3395}
3396
3397QRect QGLRectMaskGenerator::computeScreenRect()
3398{
3399 transformedPath = matrix().map(path());
3400
3401 return transformedPath.controlPointRect().adjusted(-1, -1, 1, 1).toAlignedRect();
3402}
3403
3404QRect QGLLineMaskGenerator::computeScreenRect()
3405{
3406 transformedPath = matrix().map(path());
3407
3408 return transformedPath.controlPointRect().adjusted(-1, -1, 1, 1).toAlignedRect();
3409}
3410
3411QVector<QGLTrapezoid> QGLLineMaskGenerator::generateTrapezoids()
3412{
3413 QOpenGLImmediateModeTessellator tessellator;
3414 QPointF last;
3415 for (int i = 0; i < transformedPath.elementCount(); ++i) {
3416 QPainterPath::Element element = transformedPath.elementAt(i);
3417
3418 Q_ASSERT(!element.isCurveTo());
3419
3420 if (element.isLineTo())
3421 tessellator.tessellateRect(last, element, strokeWidth());
3422
3423 last = element;
3424 }
3425
3426 return tessellator.trapezoids;
3427}
3428
3429QVector<QGLTrapezoid> QGLRectMaskGenerator::generateTrapezoids()
3430{
3431 Q_ASSERT(transformedPath.elementCount() == 5);
3432
3433 QOpenGLImmediateModeTessellator tessellator;
3434 if (matrix().type() <= QTransform::TxScale) {
3435 QPointF a = transformedPath.elementAt(0);
3436 QPointF b = transformedPath.elementAt(1);
3437 QPointF c = transformedPath.elementAt(2);
3438 QPointF d = transformedPath.elementAt(3);
3439
3440 QPointF first = (a + d) * 0.5;
3441 QPointF last = (b + c) * 0.5;
3442
3443 QPointF delta = a - d;
3444
3445 // manhattan distance (no rotation)
3446 qreal width = qAbs(delta.x()) + qAbs(delta.y());
3447
3448 Q_ASSERT(qFuzzyCompare(delta.x() + 1, static_cast<qreal>(1))
3449 || qFuzzyCompare(delta.y() + 1, static_cast<qreal>(1)));
3450
3451 tessellator.tessellateRect(first, last, width);
3452 } else {
3453 QPointF points[5];
3454
3455 for (int i = 0; i < 5; ++i)
3456 points[i] = transformedPath.elementAt(i);
3457
3458 tessellator.tessellateConvex(points, 5);
3459 }
3460 return tessellator.trapezoids;
3461}
3462
3463static QPainterPath ellipseRectToPath(const QRectF &rect)
3464{
3465 QPainterPath path;
3466 path.addEllipse(rect);
3467 return path;
3468}
3469
3470QGLEllipseMaskGenerator::QGLEllipseMaskGenerator(const QRectF &rect, const QTransform &matrix, QGLOffscreen &offs, GLuint program, int *locations)
3471 : QGLMaskGenerator(ellipseRectToPath(rect), matrix),
3472 ellipseRect(rect),
3473 offscreen(&offs),
3474 maskFragmentProgram(program),
3475 maskVariableLocations(locations)
3476{
3477}
3478
3479QRect QGLEllipseMaskGenerator::screenRect()
3480{
3481 QPointF center = ellipseRect.center();
3482
3483 QPointF points[] = {
3484 QPointF(ellipseRect.left(), center.y()),
3485 QPointF(ellipseRect.right(), center.y()),
3486 QPointF(center.x(), ellipseRect.top()),
3487 QPointF(center.x(), ellipseRect.bottom())
3488 };
3489
3490 qreal min_screen_delta_len = QREAL_MAX;
3491
3492 for (int i = 0; i < 4; ++i) {
3493 QPointF delta = points[i] - center;
3494
3495 // normalize
3496 delta /= qSqrt(delta.x() * delta.x() + delta.y() * delta.y());
3497
3498 QPointF screen_delta(matrix().m11() * delta.x() + matrix().m21() * delta.y(),
3499 matrix().m12() * delta.x() + matrix().m22() * delta.y());
3500
3501 min_screen_delta_len = qMin(min_screen_delta_len,
3502 qreal(qSqrt(screen_delta.x() * screen_delta.x() + screen_delta.y() * screen_delta.y())));
3503 }
3504
3505 const qreal padding = 2.0f;
3506
3507 qreal grow = padding / min_screen_delta_len;
3508
3509 QRectF boundingRect = ellipseRect.adjusted(-grow, -grow, grow, grow);
3510
3511 boundingRect = matrix().mapRect(boundingRect);
3512
3513 QPointF p(0.5, 0.5);
3514
3515 screen_rect = QRect((boundingRect.topLeft() - p).toPoint(),
3516 (boundingRect.bottomRight() + p).toPoint());
3517
3518 return screen_rect;
3519}
3520
3521void QGLEllipseMaskGenerator::drawMask(const QRect &rect)
3522{
3523#ifdef QT_OPENGL_ES
3524 Q_UNUSED(rect);
3525#else
3526 QGLContext *ctx = offscreen->context();
3527 offscreen->bind();
3528
3529 glDisable(GL_TEXTURE_GEN_S);
3530 glDisable(GL_TEXTURE_1D);
3531
3532 // fragment program needs the inverse radii of the ellipse
3533 glTexCoord2f(1.0f / (ellipseRect.width() * 0.5f),
3534 1.0f / (ellipseRect.height() * 0.5f));
3535
3536 QTransform translate(1, 0, 0, 1, -ellipseRect.center().x(), -ellipseRect.center().y());
3537 QTransform gl_to_qt(1, 0, 0, -1, 0, offscreen->drawableSize().height());
3538 QTransform inv_matrix = gl_to_qt * matrix().inverted() * translate;
3539
3540 float m[3][4] = { { inv_matrix.m11(), inv_matrix.m12(), inv_matrix.m13() },
3541 { inv_matrix.m21(), inv_matrix.m22(), inv_matrix.m23() },
3542 { inv_matrix.m31(), inv_matrix.m32(), inv_matrix.m33() } };
3543
3544 QPoint offs(screen_rect.left() - rect.left(), (offscreen->drawableSize().height() - screen_rect.top())
3545 - (offscreen->offscreenSize().height() - rect.top()));
3546
3547 // last component needs to be 1.0f to avoid Nvidia bug on linux
3548 float ellipse_offset[4] = { offs.x(), offs.y(), 0.0f, 1.0f };
3549
3550 GLfloat vertexArray[4 * 2];
3551 qt_add_rect_to_array(rect, vertexArray);
3552
3553 glBlendFunc(GL_ONE, GL_ZERO); // set mask
3554 glEnable(GL_FRAGMENT_PROGRAM_ARB);
3555 glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, maskFragmentProgram);
3556
3557 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, maskVariableLocations[VAR_INV_MATRIX_M0], m[0]);
3558 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, maskVariableLocations[VAR_INV_MATRIX_M1], m[1]);
3559 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, maskVariableLocations[VAR_INV_MATRIX_M2], m[2]);
3560
3561 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, maskVariableLocations[VAR_ELLIPSE_OFFSET], ellipse_offset);
3562
3563 glEnableClientState(GL_VERTEX_ARRAY);
3564 glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
3565 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
3566 glDisableClientState(GL_VERTEX_ARRAY);
3567 glDisable(GL_FRAGMENT_PROGRAM_ARB);
3568#endif
3569}
3570
3571void QOpenGLPaintEnginePrivate::drawOffscreenPath(const QPainterPath &path)
3572{
3573#ifdef Q_WS_QWS
3574 Q_UNUSED(path);
3575#else
3576 DEBUG_ONCE_STR("QOpenGLPaintEnginePrivate::drawOffscreenPath()");
3577
3578 disableClipping();
3579
3580 GLuint program = qt_gl_program_cache()->getProgram(drawable.context(),
3581 FRAGMENT_PROGRAM_MASK_TRAPEZOID_AA, 0, true);
3582 QGLPathMaskGenerator maskGenerator(path, matrix, offscreen, program);
3583 addItem(qt_mask_texture_cache()->getMask(maskGenerator, this));
3584
3585 enableClipping();
3586#endif
3587}
3588
3589void QOpenGLPaintEnginePrivate::drawFastRect(const QRectF &r)
3590{
3591 Q_Q(QOpenGLPaintEngine);
3592 DEBUG_ONCE_STR("QOpenGLPaintEngine::drawRects(): drawing fast rect");
3593
3594 q_vertexType vertexArray[10];
3595 qt_add_rect_to_array(r, vertexArray);
3596
3597 if (has_pen)
3598 QOpenGLCoordinateOffset::enableOffset(this);
3599
3600 if (has_brush) {
3601 flushDrawQueue();
3602
3603 bool temp = high_quality_antialiasing;
3604 high_quality_antialiasing = false;
3605
3606 q->updateCompositionMode(composition_mode);
3607
3608 setGradientOps(cbrush, r);
3609
3610 bool fast_style = current_style == Qt::LinearGradientPattern
3611 || current_style == Qt::SolidPattern;
3612
3613 if (fast_style && has_fast_composition_mode) {
3614 glEnableClientState(GL_VERTEX_ARRAY);
3615 glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
3616 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
3617 glDisableClientState(GL_VERTEX_ARRAY);
3618 } else {
3619 composite(r);
3620 }
3621
3622 high_quality_antialiasing = temp;
3623
3624 q->updateCompositionMode(composition_mode);
3625 }
3626
3627 if (has_pen) {
3628 if (has_fast_pen && !high_quality_antialiasing) {
3629 setGradientOps(cpen.brush(), r);
3630
3631 vertexArray[8] = vertexArray[0];
3632 vertexArray[9] = vertexArray[1];
3633
3634 glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
3635 glEnableClientState(GL_VERTEX_ARRAY);
3636 glDrawArrays(GL_LINE_STRIP, 0, 5);
3637 glDisableClientState(GL_VERTEX_ARRAY);
3638 } else {
3639 QPainterPath path;
3640 path.setFillRule(Qt::WindingFill);
3641
3642 qreal left = r.left();
3643 qreal right = r.right();
3644 qreal top = r.top();
3645 qreal bottom = r.bottom();
3646
3647 path.moveTo(left, top);
3648 path.lineTo(right, top);
3649 path.lineTo(right, bottom);
3650 path.lineTo(left, bottom);
3651 path.lineTo(left, top);
3652
3653 strokePath(path, false);
3654 }
3655
3656 QOpenGLCoordinateOffset::disableOffset(this);
3657 }
3658}
3659
3660bool QOpenGLPaintEnginePrivate::isFastRect(const QRectF &rect)
3661{
3662 if (matrix.type() < QTransform::TxRotate) {
3663 QRectF r = matrix.mapRect(rect);
3664 return r.topLeft().toPoint() == r.topLeft()
3665 && r.bottomRight().toPoint() == r.bottomRight();
3666 }
3667
3668 return false;
3669}
3670
3671void QOpenGLPaintEngine::drawRects(const QRect *rects, int rectCount)
3672{
3673 struct RectF {
3674 qreal x;
3675 qreal y;
3676 qreal w;
3677 qreal h;
3678 };
3679 Q_ASSERT(sizeof(RectF) == sizeof(QRectF));
3680 RectF fr[256];
3681 while (rectCount) {
3682 int i = 0;
3683 while (i < rectCount && i < 256) {
3684 fr[i].x = rects[i].x();
3685 fr[i].y = rects[i].y();
3686 fr[i].w = rects[i].width();
3687 fr[i].h = rects[i].height();
3688 ++i;
3689 }
3690 drawRects((QRectF *)(void *)fr, i);
3691 rects += i;
3692 rectCount -= i;
3693 }
3694}
3695
3696void QOpenGLPaintEngine::drawRects(const QRectF *rects, int rectCount)
3697{
3698 Q_D(QOpenGLPaintEngine);
3699
3700 if (d->use_emulation) {
3701 QPaintEngineEx::drawRects(rects, rectCount);
3702 return;
3703 }
3704
3705 for (int i=0; i<rectCount; ++i) {
3706 const QRectF &r = rects[i];
3707
3708 // optimization for rects which can be drawn aliased
3709 if (!d->high_quality_antialiasing || d->isFastRect(r)) {
3710 d->drawFastRect(r);
3711 } else {
3712 QPainterPath path;
3713 path.addRect(r);
3714
3715 if (d->has_brush) {
3716 d->disableClipping();
3717 GLuint program = qt_gl_program_cache()->getProgram(d->drawable.context(),
3718 FRAGMENT_PROGRAM_MASK_TRAPEZOID_AA, 0, true);
3719 QGLRectMaskGenerator maskGenerator(path, d->matrix, d->offscreen, program);
3720 d->addItem(qt_mask_texture_cache()->getMask(maskGenerator, d));
3721
3722 d->enableClipping();
3723 }
3724
3725 if (d->has_pen) {
3726 if (d->has_fast_pen)
3727 d->strokeLines(path);
3728 else
3729 d->strokePath(path, false);
3730 }
3731 }
3732 }
3733}
3734
3735static void addQuadAsTriangle(q_vertexType *quad, q_vertexType *triangle)
3736{
3737 triangle[0] = quad[0];
3738 triangle[1] = quad[1];
3739
3740 triangle[2] = quad[2];
3741 triangle[3] = quad[3];
3742
3743 triangle[4] = quad[4];
3744 triangle[5] = quad[5];
3745
3746 triangle[6] = quad[4];
3747 triangle[7] = quad[5];
3748
3749 triangle[8] = quad[6];
3750 triangle[9] = quad[7];
3751
3752 triangle[10] = quad[0];
3753 triangle[11] = quad[1];
3754}
3755
3756void QOpenGLPaintEngine::drawPoints(const QPoint *points, int pointCount)
3757{
3758 Q_ASSERT(sizeof(QT_PointF) == sizeof(QPointF));
3759 QT_PointF fp[256];
3760 while (pointCount) {
3761 int i = 0;
3762 while (i < pointCount && i < 256) {
3763 fp[i].x = points[i].x();
3764 fp[i].y = points[i].y();
3765 ++i;
3766 }
3767 drawPoints((QPointF *)(void *)fp, i);
3768 points += i;
3769 pointCount -= i;
3770 }
3771}
3772
3773void QOpenGLPaintEngine::drawPoints(const QPointF *points, int pointCount)
3774{
3775 Q_D(QOpenGLPaintEngine);
3776
3777 if (d->use_emulation) {
3778 QPaintEngineEx::drawPoints(points, pointCount);
3779 return;
3780 }
3781
3782 d->setGradientOps(d->cpen.brush(), QRectF());
3783
3784 if (!d->cpen.isCosmetic() || d->high_quality_antialiasing) {
3785 Qt::PenCapStyle capStyle = d->cpen.capStyle();
3786 if (capStyle == Qt::FlatCap)
3787 d->cpen.setCapStyle(Qt::SquareCap);
3788 QPaintEngine::drawPoints(points, pointCount);
3789 d->cpen.setCapStyle(capStyle);
3790 return;
3791 }
3792
3793 d->flushDrawQueue();
3794
3795 if (d->has_fast_pen) {
3796 QVarLengthArray<q_vertexType> vertexArray(6 * pointCount);
3797
3798 glMatrixMode(GL_MODELVIEW);
3799 glPushMatrix();
3800 glLoadIdentity();
3801
3802 int j = 0;
3803 for (int i = 0; i < pointCount; ++i) {
3804 QPointF mapped = d->matrix.map(points[i]);
3805
3806 qreal xf = qRound(mapped.x());
3807 qreal yf = qRound(mapped.y());
3808
3809 q_vertexType x = f2vt(xf);
3810 q_vertexType y = f2vt(yf);
3811
3812 vertexArray[j++] = x;
3813 vertexArray[j++] = y - f2vt(0.5);
3814
3815 vertexArray[j++] = x + f2vt(1.5);
3816 vertexArray[j++] = y + f2vt(1.0);
3817
3818 vertexArray[j++] = x;
3819 vertexArray[j++] = y + f2vt(1.0);
3820 }
3821
3822 glEnableClientState(GL_VERTEX_ARRAY);
3823
3824 glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray.constData());
3825 glDrawArrays(GL_TRIANGLES, 0, pointCount*3);
3826
3827 glDisableClientState(GL_VERTEX_ARRAY);
3828
3829 glPopMatrix();
3830 return;
3831 }
3832
3833 const qreal *vertexArray = reinterpret_cast<const qreal*>(&points[0]);
3834
3835 if (sizeof(qreal) == sizeof(double)) {
3836 Q_ASSERT(sizeof(QPointF) == 16);
3837 glVertexPointer(2, GL_DOUBLE, 0, vertexArray);
3838 }
3839 else {
3840 Q_ASSERT(sizeof(QPointF) == 8);
3841 glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
3842 }
3843
3844 glEnableClientState(GL_VERTEX_ARRAY);
3845 glDrawArrays(GL_POINTS, 0, pointCount);
3846 glDisableClientState(GL_VERTEX_ARRAY);
3847}
3848
3849void QOpenGLPaintEngine::drawLines(const QLine *lines, int lineCount)
3850{
3851 struct PointF {
3852 qreal x;
3853 qreal y;
3854 };
3855 struct LineF {
3856 PointF p1;
3857 PointF p2;
3858 };
3859 Q_ASSERT(sizeof(PointF) == sizeof(QPointF));
3860 Q_ASSERT(sizeof(LineF) == sizeof(QLineF));
3861 LineF fl[256];
3862 while (lineCount) {
3863 int i = 0;
3864 while (i < lineCount && i < 256) {
3865 fl[i].p1.x = lines[i].x1();
3866 fl[i].p1.y = lines[i].y1();
3867 fl[i].p2.x = lines[i].x2();
3868 fl[i].p2.y = lines[i].y2();
3869 ++i;
3870 }
3871 drawLines((QLineF *)(void *)fl, i);
3872 lines += i;
3873 lineCount -= i;
3874 }
3875}
3876
3877void QOpenGLPaintEngine::drawLines(const QLineF *lines, int lineCount)
3878{
3879 Q_D(QOpenGLPaintEngine);
3880
3881 if (d->use_emulation) {
3882 QPaintEngineEx::drawLines(lines, lineCount);
3883 return;
3884 }
3885
3886 if (d->has_pen) {
3887 QOpenGLCoordinateOffset offset(d);
3888 if (d->has_fast_pen && !d->high_quality_antialiasing) {
3889 //### gradient resolving on lines isn't correct
3890 d->setGradientOps(d->cpen.brush(), QRectF());
3891
3892 bool useRects = false;
3893 // scale or 90 degree rotation?
3894 if (d->matrix.type() <= QTransform::TxTranslate
3895 || !d->cpen.isCosmetic()
3896 && (d->matrix.type() <= QTransform::TxScale
3897 || (d->matrix.type() == QTransform::TxRotate
3898 && d->matrix.m11() == 0 && d->matrix.m22() == 0))) {
3899 useRects = true;
3900 for (int i = 0; i < lineCount; ++i) {
3901 if (lines[i].p1().x() != lines[i].p2().x()
3902 && lines[i].p1().y() != lines[i].p2().y()) {
3903 useRects = false;
3904 break;
3905 }
3906 }
3907 }
3908
3909 q_vertexType endCap = f2vt(d->cpen.capStyle() == Qt::FlatCap ? 0 : 0.5);
3910 if (useRects) {
3911 QVarLengthArray<q_vertexType> vertexArray(12 * lineCount);
3912
3913 q_vertexType quad[8];
3914 for (int i = 0; i < lineCount; ++i) {
3915 q_vertexType x1 = f2vt(lines[i].x1());
3916 q_vertexType x2 = f2vt(lines[i].x2());
3917 q_vertexType y1 = f2vt(lines[i].y1());
3918 q_vertexType y2 = f2vt(lines[i].y2());
3919
3920 if (x1 == x2) {
3921 if (y1 > y2)
3922 qSwap(y1, y2);
3923
3924 quad[0] = x1 - f2vt(0.5);
3925 quad[1] = y1 - endCap;
3926
3927 quad[2] = x1 + f2vt(0.5);
3928 quad[3] = y1 - endCap;
3929
3930 quad[4] = x1 + f2vt(0.5);
3931 quad[5] = y2 + endCap;
3932
3933 quad[6] = x1 - f2vt(0.5);
3934 quad[7] = y2 + endCap;
3935 } else {
3936 if (x1 > x2)
3937 qSwap(x1, x2);
3938
3939 quad[0] = x1 - endCap;
3940 quad[1] = y1 + f2vt(0.5);
3941
3942 quad[2] = x1 - endCap;
3943 quad[3] = y1 - f2vt(0.5);
3944
3945 quad[4] = x2 + endCap;
3946 quad[5] = y1 - f2vt(0.5);
3947
3948 quad[6] = x2 + endCap;
3949 quad[7] = y1 + f2vt(0.5);
3950 }
3951
3952 addQuadAsTriangle(quad, &vertexArray[12*i]);
3953 }
3954
3955 glEnableClientState(GL_VERTEX_ARRAY);
3956
3957 glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray.constData());
3958 glDrawArrays(GL_TRIANGLES, 0, lineCount*6);
3959
3960 glDisableClientState(GL_VERTEX_ARRAY);
3961 } else {
3962 QVarLengthArray<q_vertexType> vertexArray(4 * lineCount);
3963 for (int i = 0; i < lineCount; ++i) {
3964 const QPointF a = lines[i].p1();
3965 vertexArray[4*i] = f2vt(lines[i].x1());
3966 vertexArray[4*i+1] = f2vt(lines[i].y1());
3967 vertexArray[4*i+2] = f2vt(lines[i].x2());
3968 vertexArray[4*i+3] = f2vt(lines[i].y2());
3969 }
3970
3971 glEnableClientState(GL_VERTEX_ARRAY);
3972
3973 glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray.constData());
3974 glDrawArrays(GL_LINES, 0, lineCount*2);
3975
3976 glVertexPointer(2, q_vertexTypeEnum, 4*sizeof(q_vertexType), vertexArray.constData() + 2);
3977 glDrawArrays(GL_POINTS, 0, lineCount);
3978
3979 glDisableClientState(GL_VERTEX_ARRAY);
3980 }
3981 } else {
3982 QPainterPath path;
3983 path.setFillRule(Qt::WindingFill);
3984 for (int i=0; i<lineCount; ++i) {
3985 const QLineF &l = lines[i];
3986
3987 if (l.p1() == l.p2()) {
3988 if (d->cpen.capStyle() != Qt::FlatCap) {
3989 QPointF p = l.p1();
3990 drawPoints(&p, 1);
3991 }
3992 continue;
3993 }
3994
3995 path.moveTo(l.x1(), l.y1());
3996 path.lineTo(l.x2(), l.y2());
3997 }
3998
3999 if (d->has_fast_pen && d->high_quality_antialiasing)
4000 d->strokeLines(path);
4001 else
4002 d->strokePath(path, false);
4003 }
4004 }
4005}
4006
4007void QOpenGLPaintEngine::drawPolygon(const QPoint *points, int pointCount, PolygonDrawMode mode)
4008{
4009 Q_ASSERT(sizeof(QT_PointF) == sizeof(QPointF));
4010 QVarLengthArray<QT_PointF> p(pointCount);
4011 for (int i=0; i<pointCount; ++i) {
4012 p[i].x = points[i].x();
4013 p[i].y = points[i].y();
4014 }
4015 drawPolygon((QPointF *)p.data(), pointCount, mode);
4016}
4017
4018void QOpenGLPaintEngine::drawPolygon(const QPointF *points, int pointCount, PolygonDrawMode mode)
4019{
4020 Q_D(QOpenGLPaintEngine);
4021 if(pointCount < 2)
4022 return;
4023
4024 if (d->use_emulation) {
4025 QPaintEngineEx::drawPolygon(points, pointCount, mode);
4026 return;
4027 }
4028
4029 QRectF bounds;
4030 if ((mode == ConvexMode && !d->high_quality_antialiasing && state()->brushNeedsResolving()) ||
4031 ((d->has_fast_pen && !d->high_quality_antialiasing) && state()->penNeedsResolving())) {
4032 qreal minx = points[0].x(), miny = points[0].y(),
4033 maxx = points[0].x(), maxy = points[0].y();
4034 for (int i = 1; i < pointCount; ++i) {
4035 const QPointF &pt = points[i];
4036 if (minx > pt.x())
4037 minx = pt.x();
4038 if (miny > pt.y())
4039 miny = pt.y();
4040 if (maxx < pt.x())
4041 maxx = pt.x();
4042 if (maxy < pt.y())
4043 maxy = pt.y();
4044 }
4045 bounds = QRectF(minx, maxx, maxx-minx, maxy-miny);
4046 }
4047
4048 QOpenGLCoordinateOffset offset(d);
4049
4050 if (d->has_brush && mode != PolylineMode) {
4051 if (mode == ConvexMode && !d->high_quality_antialiasing) {
4052 //### resolving on polygon from points isn't correct
4053 d->setGradientOps(d->cbrush, bounds);
4054
4055 const qreal *vertexArray = reinterpret_cast<const qreal*>(&points[0]);
4056
4057 if (sizeof(qreal) == sizeof(double)) {
4058 Q_ASSERT(sizeof(QPointF) == 16);
4059 glVertexPointer(2, GL_DOUBLE, 0, vertexArray);
4060 }
4061 else {
4062 Q_ASSERT(sizeof(QPointF) == 8);
4063 glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
4064 }
4065
4066 glEnableClientState(GL_VERTEX_ARRAY);
4067 glDrawArrays(GL_TRIANGLE_FAN, 0, pointCount);
4068 glDisableClientState(GL_VERTEX_ARRAY);
4069 } else {
4070 QPainterPath path;
4071 path.setFillRule(mode == WindingMode ? Qt::WindingFill : Qt::OddEvenFill);
4072 path.moveTo(points[0]);
4073 for (int i=1; i<pointCount; ++i)
4074 path.lineTo(points[i]);
4075 d->fillPath(path);
4076 }
4077 }
4078
4079 if (d->has_pen) {
4080 if (d->has_fast_pen && !d->high_quality_antialiasing) {
4081 d->setGradientOps(d->cpen.brush(), bounds);
4082 QVarLengthArray<q_vertexType> vertexArray(pointCount*2 + 2);
4083 glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray.constData());
4084 int i;
4085 for (i=0; i<pointCount; ++i) {
4086 vertexArray[i*2] = f2vt(points[i].x());
4087 vertexArray[i*2+1] = f2vt(points[i].y());
4088 }
4089
4090 glEnableClientState(GL_VERTEX_ARRAY);
4091 if (mode != PolylineMode) {
4092 vertexArray[i*2] = vertexArray[0];
4093 vertexArray[i*2+1] = vertexArray[1];
4094 glDrawArrays(GL_LINE_STRIP, 0, pointCount+1);
4095 } else {
4096 glDrawArrays(GL_LINE_STRIP, 0, pointCount);
4097 glDrawArrays(GL_POINTS, pointCount-1, 1);
4098 }
4099 glDisableClientState(GL_VERTEX_ARRAY);
4100 } else {
4101 QPainterPath path(points[0]);
4102 for (int i = 1; i < pointCount; ++i)
4103 path.lineTo(points[i]);
4104 if (mode != PolylineMode)
4105 path.lineTo(points[0]);
4106
4107 if (d->has_fast_pen)
4108 d->strokeLines(path);
4109 else
4110 d->strokePath(path, true);
4111 }
4112 }
4113}
4114
4115void QOpenGLPaintEnginePrivate::strokeLines(const QPainterPath &path)
4116{
4117 DEBUG_ONCE_STR("QOpenGLPaintEnginePrivate::strokeLines()");
4118
4119 qreal penWidth = cpen.widthF();
4120
4121 GLuint program = qt_gl_program_cache()->getProgram(drawable.context(),
4122 FRAGMENT_PROGRAM_MASK_TRAPEZOID_AA, 0, true);
4123 QGLLineMaskGenerator maskGenerator(path, matrix, penWidth == 0 ? 1.0 : penWidth,
4124 offscreen, program);
4125
4126 disableClipping();
4127
4128 QBrush temp = cbrush;
4129 QPointF origin = brush_origin;
4130
4131 cbrush = cpen.brush();
4132 brush_origin = QPointF();
4133
4134 addItem(qt_mask_texture_cache()->getMask(maskGenerator, this));
4135
4136 cbrush = temp;
4137 brush_origin = origin;
4138
4139 enableClipping();
4140}
4141
4142extern bool qt_scaleForTransform(const QTransform &transform, qreal *scale); // qtransform.cpp
4143
4144void QOpenGLPaintEnginePrivate::strokePath(const QPainterPath &path, bool use_cache)
4145{
4146 QBrush old_brush = cbrush;
4147 cbrush = cpen.brush();
4148
4149 qreal txscale = 1;
4150 if (cpen.isCosmetic() || (qt_scaleForTransform(matrix, &txscale) && txscale != 1)) {
4151 QTransform temp = matrix;
4152 matrix = QTransform();
4153 glPushMatrix();
4154
4155 if (has_antialiasing) {
4156 glLoadIdentity();
4157 } else {
4158 float offs_matrix[] =
4159 { 1, 0, 0, 0,
4160 0, 1, 0, 0,
4161 0, 0, 1, 0,
4162 0.5, 0.5, 0, 1 };
4163 glLoadMatrixf(offs_matrix);
4164 }
4165
4166 QPen pen = cpen;
4167 if (txscale != 1)
4168 pen.setWidthF(pen.width() * txscale);
4169 if (use_cache)
4170 fillPath(qt_opengl_stroke_cache()->getStrokedPath(temp.map(path), pen));
4171 else
4172 fillPath(strokeForPath(temp.map(path), pen));
4173
4174 glPopMatrix();
4175 matrix = temp;
4176 } else if (use_cache) {
4177 fillPath(qt_opengl_stroke_cache()->getStrokedPath(path, cpen));
4178 } else {
4179 fillPath(strokeForPath(path, cpen));
4180 }
4181
4182 cbrush = old_brush;
4183}
4184
4185void QOpenGLPaintEnginePrivate::strokePathFastPen(const QPainterPath &path, bool needsResolving)
4186{
4187#ifndef QT_OPENGL_ES
4188 QRectF bounds;
4189 if (needsResolving)
4190 bounds = path.controlPointRect();
4191 setGradientOps(cpen.brush(), bounds);
4192
4193 QBezier beziers[32];
4194 for (int i=0; i<path.elementCount(); ++i) {
4195 const QPainterPath::Element &e = path.elementAt(i);
4196 switch (e.type) {
4197 case QPainterPath::MoveToElement:
4198 if (i != 0)
4199 glEnd(); // GL_LINE_STRIP
4200 glBegin(GL_LINE_STRIP);
4201 glVertex2d(e.x, e.y);
4202
4203 break;
4204 case QPainterPath::LineToElement:
4205 glVertex2d(e.x, e.y);
4206 break;
4207
4208 case QPainterPath::CurveToElement:
4209 {
4210 QPointF sp = path.elementAt(i-1);
4211 QPointF cp2 = path.elementAt(i+1);
4212 QPointF ep = path.elementAt(i+2);
4213 i+=2;
4214
4215 qreal inverseScaleHalf = inverseScale / 2;
4216 beziers[0] = QBezier::fromPoints(sp, e, cp2, ep);
4217 QBezier *b = beziers;
4218 while (b >= beziers) {
4219 // check if we can pop the top bezier curve from the stack
4220 qreal l = qAbs(b->x4 - b->x1) + qAbs(b->y4 - b->y1);
4221 qreal d;
4222 if (l > inverseScale) {
4223 d = qAbs( (b->x4 - b->x1)*(b->y1 - b->y2)
4224 - (b->y4 - b->y1)*(b->x1 - b->x2) )
4225 + qAbs( (b->x4 - b->x1)*(b->y1 - b->y3)
4226 - (b->y4 - b->y1)*(b->x1 - b->x3) );
4227 d /= l;
4228 } else {
4229 d = qAbs(b->x1 - b->x2) + qAbs(b->y1 - b->y2) +
4230 qAbs(b->x1 - b->x3) + qAbs(b->y1 - b->y3);
4231 }
4232 if (d < inverseScaleHalf || b == beziers + 31) {
4233 // good enough, we pop it off and add the endpoint
4234 glVertex2d(b->x4, b->y4);
4235 --b;
4236 } else {
4237 // split, second half of the polygon goes lower into the stack
4238 b->split(b+1, b);
4239 ++b;
4240 }
4241 }
4242 } // case CurveToElement
4243 default:
4244 break;
4245 } // end of switch
4246 }
4247 glEnd(); // GL_LINE_STRIP
4248#else
4249 // have to use vertex arrays on embedded
4250 QRectF bounds;
4251 if (needsResolving)
4252 bounds = path.controlPointRect();
4253 setGradientOps(cpen.brush(), bounds);
4254
4255 glEnableClientState(GL_VERTEX_ARRAY);
4256 tess_points.reset();
4257 QBezier beziers[32];
4258 for (int i=0; i<path.elementCount(); ++i) {
4259 const QPainterPath::Element &e = path.elementAt(i);
4260 switch (e.type) {
4261 case QPainterPath::MoveToElement:
4262 if (i != 0) {
4263 glVertexPointer(2, q_vertexTypeEnum, 0, tess_points.data());
4264 glDrawArrays(GL_LINE_STRIP, 0, tess_points.size());
4265 tess_points.reset();
4266 }
4267 tess_points.add(QPointF(e.x, e.y));
4268
4269 break;
4270 case QPainterPath::LineToElement:
4271 tess_points.add(QPointF(e.x, e.y));
4272 break;
4273
4274 case QPainterPath::CurveToElement:
4275 {
4276 QPointF sp = path.elementAt(i-1);
4277 QPointF cp2 = path.elementAt(i+1);
4278 QPointF ep = path.elementAt(i+2);
4279 i+=2;
4280
4281 qreal inverseScaleHalf = inverseScale / 2;
4282 beziers[0] = QBezier::fromPoints(sp, e, cp2, ep);
4283 QBezier *b = beziers;
4284 while (b >= beziers) {
4285 // check if we can pop the top bezier curve from the stack
4286 qreal l = qAbs(b->x4 - b->x1) + qAbs(b->y4 - b->y1);
4287 qreal d;
4288 if (l > inverseScale) {
4289 d = qAbs( (b->x4 - b->x1)*(b->y1 - b->y2)
4290 - (b->y4 - b->y1)*(b->x1 - b->x2) )
4291 + qAbs( (b->x4 - b->x1)*(b->y1 - b->y3)
4292 - (b->y4 - b->y1)*(b->x1 - b->x3) );
4293 d /= l;
4294 } else {
4295 d = qAbs(b->x1 - b->x2) + qAbs(b->y1 - b->y2) +
4296 qAbs(b->x1 - b->x3) + qAbs(b->y1 - b->y3);
4297 }
4298 if (d < inverseScaleHalf || b == beziers + 31) {
4299 // good enough, we pop it off and add the endpoint
4300 tess_points.add(QPointF(b->x4, b->y4));
4301 --b;
4302 } else {
4303 // split, second half of the polygon goes lower into the stack
4304 b->split(b+1, b);
4305 ++b;
4306 }
4307 }
4308 } // case CurveToElement
4309 default:
4310 break;
4311 } // end of switch
4312 }
4313 glVertexPointer(2, q_vertexTypeEnum, 0, tess_points.data());
4314 glDrawArrays(GL_LINE_STRIP, 0, tess_points.size());
4315 glDisableClientState(GL_VERTEX_ARRAY);
4316#endif
4317}
4318
4319static bool pathClosed(const QPainterPath &path)
4320{
4321 QPointF lastMoveTo = path.elementAt(0);
4322 QPointF lastPoint = lastMoveTo;
4323
4324 for (int i = 1; i < path.elementCount(); ++i) {
4325 const QPainterPath::Element &e = path.elementAt(i);
4326 switch (e.type) {
4327 case QPainterPath::MoveToElement:
4328 if (lastMoveTo != lastPoint)
4329 return false;
4330 lastMoveTo = lastPoint = e;
4331 break;
4332 case QPainterPath::LineToElement:
4333 lastPoint = e;
4334 break;
4335 case QPainterPath::CurveToElement:
4336 lastPoint = path.elementAt(i + 2);
4337 i+=2;
4338 break;
4339 default:
4340 break;
4341 }
4342 }
4343
4344 return lastMoveTo == lastPoint;
4345}
4346
4347void QOpenGLPaintEngine::drawPath(const QPainterPath &path)
4348{
4349 Q_D(QOpenGLPaintEngine);
4350
4351 if (path.isEmpty())
4352 return;
4353
4354 if (d->use_emulation) {
4355 QPaintEngineEx::drawPath(path);
4356 return;
4357 }
4358
4359 QOpenGLCoordinateOffset offset(d);
4360
4361 if (d->has_brush) {
4362 bool path_closed = pathClosed(path);
4363
4364 bool has_thick_pen =
4365 path_closed
4366 && d->has_pen
4367 && d->cpen.style() == Qt::SolidLine
4368 && d->cpen.isSolid()
4369 && d->cpen.color().alpha() == 255
4370 && d->txop < QTransform::TxProject
4371 && d->cpen.widthF() >= 2 / qSqrt(qMin(d->matrix.m11() * d->matrix.m11()
4372 + d->matrix.m21() * d->matrix.m21(),
4373 d->matrix.m12() * d->matrix.m12()
4374 + d->matrix.m22() * d->matrix.m22()));
4375
4376 if (has_thick_pen) {
4377 DEBUG_ONCE qDebug() << "QOpenGLPaintEngine::drawPath(): Using thick pen optimization, style:" << d->cbrush.style();
4378
4379 d->flushDrawQueue();
4380
4381 bool temp = d->high_quality_antialiasing;
4382 d->high_quality_antialiasing = false;
4383
4384 updateCompositionMode(d->composition_mode);
4385
4386 d->fillPath(path);
4387
4388 d->high_quality_antialiasing = temp;
4389 updateCompositionMode(d->composition_mode);
4390 } else {
4391 d->fillPath(path);
4392 }
4393 }
4394
4395 if (d->has_pen) {
4396 if (d->has_fast_pen && !d->high_quality_antialiasing)
4397 d->strokePathFastPen(path, state()->penNeedsResolving());
4398 else
4399 d->strokePath(path, true);
4400 }
4401}
4402
4403void QOpenGLPaintEnginePrivate::drawImageAsPath(const QRectF &r, const QImage &img, const QRectF &sr)
4404{
4405 QBrush old_brush = cbrush;
4406 QPointF old_brush_origin = brush_origin;
4407
4408 qreal scaleX = r.width() / sr.width();
4409 qreal scaleY = r.height() / sr.height();
4410
4411 QTransform brush_matrix;
4412 brush_matrix.translate(r.left(), r.top());
4413 brush_matrix.scale(scaleX, scaleY);
4414 brush_matrix.translate(-sr.left(), -sr.top());
4415
4416 cbrush = QBrush(img);
4417 cbrush.setTransform(brush_matrix);
4418 brush_origin = QPointF();
4419
4420 QPainterPath p;
4421 p.addRect(r);
4422 fillPath(p);
4423
4424 cbrush = old_brush;
4425 brush_origin = old_brush_origin;
4426}
4427
4428void QOpenGLPaintEnginePrivate::drawTiledImageAsPath(const QRectF &r, const QImage &img, qreal sx, qreal sy)
4429{
4430 QBrush old_brush = cbrush;
4431 QPointF old_brush_origin = brush_origin;
4432
4433 QTransform brush_matrix;
4434 brush_matrix.translate(r.left(), r.top());
4435 brush_matrix.scale(sx, sy);
4436
4437 cbrush = QBrush(img);
4438 cbrush.setTransform(brush_matrix);
4439 brush_origin = QPointF();
4440
4441 QPainterPath p;
4442 p.addRect(r);
4443 fillPath(p);
4444
4445 cbrush = old_brush;
4446 brush_origin = old_brush_origin;
4447}
4448
4449static const QRectF scaleRect(const QRectF &r, qreal sx, qreal sy)
4450{
4451 return QRectF(r.x() * sx, r.y() * sy, r.width() * sx, r.height() * sy);
4452}
4453
4454template <typename T>
4455static const T qSubImage(const T &image, const QRectF &src, QRectF *srcNew)
4456{
4457 const int sx1 = qMax(0, qFloor(src.left()));
4458 const int sy1 = qMax(0, qFloor(src.top()));
4459 const int sx2 = qMin(image.width(), qCeil(src.right()));
4460 const int sy2 = qMin(image.height(), qCeil(src.bottom()));
4461
4462 const T sub = image.copy(sx1, sy1, sx2 - sx1, sy2 - sy1);
4463
4464 if (srcNew)
4465 *srcNew = src.translated(-sx1, -sy1);
4466
4467 return sub;
4468}
4469
4470void QOpenGLPaintEngine::drawPixmap(const QRectF &r, const QPixmap &pm, const QRectF &sr)
4471{
4472 Q_D(QOpenGLPaintEngine);
4473 if (pm.depth() == 1) {
4474 QPixmap tpx(pm.size());
4475 tpx.fill(Qt::transparent);
4476 QPainter p(&tpx);
4477 p.setPen(d->cpen);
4478 p.drawPixmap(0, 0, pm);
4479 p.end();
4480 drawPixmap(r, tpx, sr);
4481 return;
4482 }
4483
4484 const int sz = d->max_texture_size;
4485 if (pm.width() > sz || pm.height() > sz) {
4486 QRectF subsr;
4487 const QPixmap sub = qSubImage(pm, sr, &subsr);
4488
4489 if (sub.width() <= sz && sub.height() <= sz) {
4490 drawPixmap(r, sub, subsr);
4491 } else {
4492 const QPixmap scaled = sub.scaled(sz, sz, Qt::KeepAspectRatio);
4493 const qreal sx = scaled.width() / qreal(sub.width());
4494 const qreal sy = scaled.height() / qreal(sub.height());
4495
4496 drawPixmap(r, scaled, scaleRect(subsr, sx, sy));
4497 }
4498 return;
4499 }
4500
4501
4502 if (d->composition_mode > QPainter::CompositionMode_Plus || (d->high_quality_antialiasing && !d->isFastRect(r)))
4503 d->drawImageAsPath(r, pm.toImage(), sr);
4504 else {
4505 GLenum target = qt_gl_preferredTextureTarget();
4506 d->flushDrawQueue();
4507 d->drawable.bindTexture(pm, target);
4508 drawTextureRect(pm.width(), pm.height(), r, sr, target);
4509 }
4510}
4511
4512void QOpenGLPaintEngine::drawTiledPixmap(const QRectF &r, const QPixmap &pm, const QPointF &)
4513{
4514 Q_D(QOpenGLPaintEngine);
4515
4516 QImage scaled;
4517 const int sz = d->max_texture_size;
4518 if (pm.width() > sz || pm.height() > sz) {
4519 int rw = qCeil(r.width());
4520 int rh = qCeil(r.height());
4521 if (rw < pm.width() && rh < pm.height()) {
4522 drawTiledPixmap(r, pm.copy(0, 0, rw, rh), QPointF());
4523 return;
4524 }
4525
4526 scaled = pm.toImage().scaled(sz, sz, Qt::KeepAspectRatio);
4527 }
4528
4529 if (d->composition_mode > QPainter::CompositionMode_Plus || (d->high_quality_antialiasing && !d->isFastRect(r))) {
4530 if (scaled.isNull())
4531 d->drawTiledImageAsPath(r, pm.toImage(), 1, 1);
4532 else {
4533 const qreal sx = pm.width() / qreal(scaled.width());
4534 const qreal sy = pm.height() / qreal(scaled.height());
4535 d->drawTiledImageAsPath(r, scaled, sx, sy);
4536 }
4537 } else {
4538 d->flushDrawQueue();
4539
4540 if (scaled.isNull())
4541 d->drawable.bindTexture(pm);
4542 else
4543 d->drawable.bindTexture(scaled);
4544 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, d->use_smooth_pixmap_transform);
4545
4546#ifndef QT_OPENGL_ES
4547 glPushAttrib(GL_CURRENT_BIT);
4548 glDisable(GL_TEXTURE_GEN_S);
4549#endif
4550 glColor4f(d->opacity, d->opacity, d->opacity, d->opacity);
4551 glEnable(GL_TEXTURE_2D);
4552
4553 GLdouble tc_w = r.width()/pm.width();
4554 GLdouble tc_h = r.height()/pm.height();
4555
4556 // Rotate the texture so that it is aligned correctly and the
4557 // wrapping is done correctly
4558 glMatrixMode(GL_TEXTURE);
4559 glPushMatrix();
4560 glRotatef(180.0, 0.0, 1.0, 0.0);
4561 glRotatef(180.0, 0.0, 0.0, 1.0);
4562
4563 q_vertexType vertexArray[4*2];
4564 q_vertexType texCoordArray[4*2];
4565
4566 qt_add_rect_to_array(r, vertexArray);
4567 qt_add_texcoords_to_array(0, 0, tc_w, tc_h, texCoordArray);
4568
4569 glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
4570 glTexCoordPointer(2, q_vertexTypeEnum, 0, texCoordArray);
4571
4572 glEnableClientState(GL_VERTEX_ARRAY);
4573 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
4574 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
4575 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
4576 glDisableClientState(GL_VERTEX_ARRAY);
4577 glPopMatrix();
4578
4579 glDisable(GL_TEXTURE_2D);
4580#ifndef QT_OPENGL_ES
4581 glPopAttrib();
4582#endif
4583 }
4584}
4585
4586void QOpenGLPaintEngine::drawImage(const QRectF &r, const QImage &image, const QRectF &sr,
4587 Qt::ImageConversionFlags)
4588{
4589 Q_D(QOpenGLPaintEngine);
4590
4591 const int sz = d->max_texture_size;
4592 if (image.width() > sz || image.height() > sz) {
4593 QRectF subsr;
4594 const QImage sub = qSubImage(image, sr, &subsr);
4595
4596 if (sub.width() <= sz && sub.height() <= sz) {
4597 drawImage(r, sub, subsr, 0);
4598 } else {
4599 const QImage scaled = sub.scaled(sz, sz, Qt::KeepAspectRatio);
4600 const qreal sx = scaled.width() / qreal(sub.width());
4601 const qreal sy = scaled.height() / qreal(sub.height());
4602
4603 drawImage(r, scaled, scaleRect(subsr, sx, sy), 0);
4604 }
4605 return;
4606 }
4607
4608 if (d->composition_mode > QPainter::CompositionMode_Plus || (d->high_quality_antialiasing && !d->isFastRect(r)))
4609 d->drawImageAsPath(r, image, sr);
4610 else {
4611 GLenum target = qt_gl_preferredTextureTarget();
4612 d->flushDrawQueue();
4613 d->drawable.bindTexture(image, target);
4614 drawTextureRect(image.width(), image.height(), r, sr, target);
4615 }
4616}
4617
4618void QOpenGLPaintEngine::drawTextureRect(int tx_width, int tx_height, const QRectF &r,
4619 const QRectF &sr, GLenum target)
4620{
4621 Q_D(QOpenGLPaintEngine);
4622#ifndef QT_OPENGL_ES
4623 glPushAttrib(GL_CURRENT_BIT);
4624 glDisable(GL_TEXTURE_GEN_S);
4625#endif
4626 glColor4f(d->opacity, d->opacity, d->opacity, d->opacity);
4627 glEnable(target);
4628 updateTextureFilter(target, GL_CLAMP_TO_EDGE, d->use_smooth_pixmap_transform);
4629
4630 qreal x1, x2, y1, y2;
4631 if (target == GL_TEXTURE_2D) {
4632 x1 = sr.x() / tx_width;
4633 x2 = x1 + sr.width() / tx_width;
4634 y1 = 1.0 - (sr.bottom() / tx_height);
4635 y2 = 1.0 - (sr.y() / tx_height);
4636 } else {
4637 x1 = sr.x();
4638 x2 = sr.right();
4639 y1 = tx_height - sr.bottom();
4640 y2 = tx_height - sr.y();
4641 }
4642
4643 q_vertexType vertexArray[4*2];
4644 q_vertexType texCoordArray[4*2];
4645
4646 qt_add_rect_to_array(r, vertexArray);
4647 qt_add_texcoords_to_array(x1, y2, x2, y1, texCoordArray);
4648
4649 glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
4650 glTexCoordPointer(2, q_vertexTypeEnum, 0, texCoordArray);
4651
4652 glEnableClientState(GL_VERTEX_ARRAY);
4653 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
4654 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
4655 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
4656 glDisableClientState(GL_VERTEX_ARRAY);
4657
4658 glDisable(target);
4659#ifndef QT_OPENGL_ES
4660 glPopAttrib();
4661#endif
4662}
4663
4664#ifdef Q_WS_WIN
4665HDC
4666#else
4667Qt::HANDLE
4668#endif
4669QOpenGLPaintEngine::handle() const
4670{
4671 return 0;
4672}
4673
4674static const int x_margin = 1;
4675static const int y_margin = 0;
4676
4677struct QGLGlyphCoord {
4678 // stores the offset and size of a glyph texture
4679 qreal x;
4680 qreal y;
4681 qreal width;
4682 qreal height;
4683 qreal log_width;
4684 qreal log_height;
4685 QFixed x_offset;
4686 QFixed y_offset;
4687};
4688
4689struct QGLFontTexture {
4690 int x_offset; // glyph offset within the
4691 int y_offset;
4692 GLuint texture;
4693 int width;
4694 int height;
4695};
4696
4697typedef QHash<glyph_t, QGLGlyphCoord*> QGLGlyphHash;
4698typedef QHash<QFontEngine*, QGLGlyphHash*> QGLFontGlyphHash;
4699typedef QHash<quint64, QGLFontTexture*> QGLFontTexHash;
4700typedef QHash<const QGLContext*, QGLFontGlyphHash*> QGLContextHash;
4701
4702class QGLGlyphCache : public QObject
4703{
4704 Q_OBJECT
4705public:
4706 QGLGlyphCache() : QObject(0) { current_cache = 0; }
4707 ~QGLGlyphCache();
4708 QGLGlyphCoord *lookup(QFontEngine *, glyph_t);
4709 void cacheGlyphs(QGLContext *, const QTextItemInt &, const QVarLengthArray<glyph_t> &);
4710 void cleanCache();
4711 void allocTexture(int width, int height, GLuint texture);
4712
4713public slots:
4714 void cleanupContext(const QGLContext *);
4715 void fontEngineDestroyed(QObject *);
4716 void widgetDestroyed(QObject *);
4717
4718protected:
4719 QGLGlyphHash *current_cache;
4720 QGLFontTexHash qt_font_textures;
4721 QGLContextHash qt_context_cache;
4722};
4723
4724QGLGlyphCache::~QGLGlyphCache()
4725{
4726// qDebug() << "cleaning out the QGLGlyphCache";
4727 cleanCache();
4728}
4729
4730void QGLGlyphCache::fontEngineDestroyed(QObject *o)
4731{
4732// qDebug() << "fontEngineDestroyed()";
4733 QFontEngine *fe = static_cast<QFontEngine *>(o); // safe, since only the type is used
4734 QList<const QGLContext *> keys = qt_context_cache.keys();
4735 const QGLContext *ctx = 0;
4736
4737 for (int i=0; i < keys.size(); ++i) {
4738 QGLFontGlyphHash *font_cache = qt_context_cache.value(keys.at(i));
4739 if (font_cache->find(fe) != font_cache->end()) {
4740 ctx = keys.at(i);
4741 QGLGlyphHash *cache = font_cache->take(fe);
4742 delete cache;
4743 break;
4744 }
4745 }
4746
4747 quint64 font_key = (reinterpret_cast<quint64>(ctx) << 32) | reinterpret_cast<quint64>(fe);
4748 QGLFontTexture *tex = qt_font_textures.take(font_key);
4749 if (tex) {
4750#ifdef Q_WS_MAC
4751 if (
4752# ifndef QT_MAC_USE_COCOA
4753 aglGetCurrentContext() != 0
4754# else
4755 qt_current_nsopengl_context() != 0
4756# endif
4757 )
4758#endif
4759 glDeleteTextures(1, &tex->texture);
4760 delete tex;
4761 }
4762}
4763
4764void QGLGlyphCache::widgetDestroyed(QObject *)
4765{
4766// qDebug() << "widget destroyed";
4767 cleanCache(); // ###
4768}
4769
4770void QGLGlyphCache::cleanupContext(const QGLContext *ctx)
4771{
4772// qDebug() << "==> cleaning for: " << hex << ctx;
4773 QGLFontGlyphHash *font_cache = qt_context_cache.take(ctx);
4774
4775 if (font_cache) {
4776 QList<QFontEngine *> keys = font_cache->keys();
4777 for (int i=0; i < keys.size(); ++i) {
4778 QFontEngine *fe = keys.at(i);
4779 delete font_cache->take(fe);
4780 quint64 font_key = (reinterpret_cast<quint64>(ctx) << 32) | reinterpret_cast<quint64>(fe);
4781 QGLFontTexture *font_tex = qt_font_textures.take(font_key);
4782 if (font_tex) {
4783#ifdef Q_WS_MAC
4784 if (
4785# ifndef QT_MAC_USE_COCOA
4786 aglGetCurrentContext() == 0
4787# else
4788 qt_current_nsopengl_context() != 0
4789# endif
4790 )
4791#endif
4792 glDeleteTextures(1, &font_tex->texture);
4793 delete font_tex;
4794 }
4795 }
4796 delete font_cache;
4797 }
4798// qDebug() << "<=== done cleaning, num tex:" << qt_font_textures.size() << "num ctx:" << qt_context_cache.size();
4799}
4800
4801void QGLGlyphCache::cleanCache()
4802{
4803 QGLFontTexHash::const_iterator it = qt_font_textures.constBegin();
4804 if (QGLContext::currentContext()) {
4805 while (it != qt_font_textures.constEnd()) {
4806#if defined(Q_WS_MAC) && defined(QT_MAC_USE_COCOA)
4807 if (qt_current_nsopengl_context() == 0)
4808 break;
4809#endif
4810 glDeleteTextures(1, &it.value()->texture);
4811 ++it;
4812 }
4813 }
4814 qDeleteAll(qt_font_textures);
4815 qt_font_textures.clear();
4816
4817 QList<const QGLContext *> keys = qt_context_cache.keys();
4818 for (int i=0; i < keys.size(); ++i) {
4819 QGLFontGlyphHash *font_cache = qt_context_cache.value(keys.at(i));
4820 qDeleteAll(*font_cache);
4821 font_cache->clear();
4822 }
4823 qDeleteAll(qt_context_cache);
4824 qt_context_cache.clear();
4825}
4826
4827void QGLGlyphCache::allocTexture(int width, int height, GLuint texture)
4828{
4829 uchar *tex_data = (uchar *) malloc(width*height*2);
4830 memset(tex_data, 0, width*height*2);
4831 glBindTexture(GL_TEXTURE_2D, texture);
4832#ifndef QT_OPENGL_ES
4833 glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE8_ALPHA8,
4834 width, height, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, tex_data);
4835#else
4836 glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA,
4837 width, height, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, tex_data);
4838#endif
4839 free(tex_data);
4840}
4841
4842#if 0
4843// useful for debugging the glyph cache
4844static QImage getCurrentTexture(const QColor &color, QGLFontTexture *font_tex)
4845{
4846 ushort *old_tex_data = (ushort *) malloc(font_tex->width*font_tex->height*2);
4847 glGetTexImage(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, old_tex_data);
4848 QImage im(font_tex->width, font_tex->height, QImage::Format_ARGB32);
4849 for (int y=0; y<font_tex->height; ++y) {
4850 for (int x=0; x<font_tex->width; ++x) {
4851 im.setPixel(x, y, ((*(old_tex_data+x+y*font_tex->width)) << 24) | (0x00ffffff & color.rgb()));
4852 }
4853 }
4854 delete old_tex_data;
4855 return im;
4856}
4857#endif
4858
4859void QGLGlyphCache::cacheGlyphs(QGLContext *context, const QTextItemInt &ti,
4860 const QVarLengthArray<glyph_t> &glyphs)
4861{
4862 QGLContextHash::const_iterator dev_it = qt_context_cache.constFind(context);
4863 QGLFontGlyphHash *font_cache = 0;
4864 const QGLContext *context_key = 0;
4865
4866 if (dev_it == qt_context_cache.constEnd()) {
4867 // check for shared contexts
4868 QList<const QGLContext *> contexts = qt_context_cache.keys();
4869 for (int i=0; i<contexts.size(); ++i) {
4870 const QGLContext *ctx = contexts.at(i);
4871 if (ctx != context && qgl_share_reg()->checkSharing(context, ctx)) {
4872 context_key = ctx;
4873 dev_it = qt_context_cache.constFind(context_key);
4874 break;
4875 }
4876 }
4877 }
4878
4879 if (dev_it == qt_context_cache.constEnd()) {
4880 // no shared contexts either - create a new entry
4881 font_cache = new QGLFontGlyphHash;
4882// qDebug() << "new context" << context << font_cache;
4883 qt_context_cache.insert(context, font_cache);
4884 if (context->isValid() && context->device()->devType() == QInternal::Widget) {
4885 QWidget *widget = static_cast<QWidget *>(context->device());
4886 connect(widget, SIGNAL(destroyed(QObject*)), SLOT(widgetDestroyed(QObject*)));
4887 connect(QGLSignalProxy::instance(),
4888 SIGNAL(aboutToDestroyContext(const QGLContext *)),
4889 SLOT(cleanupContext(const QGLContext *)));
4890 }
4891 } else {
4892 font_cache = dev_it.value();
4893 }
4894 Q_ASSERT(font_cache != 0);
4895
4896 QGLFontGlyphHash::const_iterator cache_it = font_cache->constFind(ti.fontEngine);
4897 QGLGlyphHash *cache = 0;
4898 if (cache_it == font_cache->constEnd()) {
4899 cache = new QGLGlyphHash;
4900 font_cache->insert(ti.fontEngine, cache);
4901 connect(ti.fontEngine, SIGNAL(destroyed(QObject*)), SLOT(fontEngineDestroyed(QObject*)));
4902 } else {
4903 cache = cache_it.value();
4904 }
4905 current_cache = cache;
4906
4907 quint64 font_key = (reinterpret_cast<quint64>(context_key ? context_key : context) << 32)
4908 | reinterpret_cast<quint64>(ti.fontEngine);
4909 QGLFontTexHash::const_iterator it = qt_font_textures.constFind(font_key);
4910 QGLFontTexture *font_tex;
4911 if (it == qt_font_textures.constEnd()) {
4912 GLuint font_texture;
4913 glGenTextures(1, &font_texture);
4914 GLint tex_height = qt_next_power_of_two(qRound(ti.ascent.toReal() + ti.descent.toReal())+2);
4915 GLint tex_width = qt_next_power_of_two(tex_height*30); // ###
4916 GLint max_tex_size;
4917 glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_tex_size);
4918 Q_ASSERT(max_tex_size > 0);
4919 if (tex_width > max_tex_size)
4920 tex_width = max_tex_size;
4921 allocTexture(tex_width, tex_height, font_texture);
4922 font_tex = new QGLFontTexture;
4923 font_tex->texture = font_texture;
4924 font_tex->x_offset = x_margin;
4925 font_tex->y_offset = y_margin;
4926 font_tex->width = tex_width;
4927 font_tex->height = tex_height;
4928// qDebug() << "new font tex - width:" << tex_width << "height:"<< tex_height
4929// << hex << "tex id:" << font_tex->texture << "key:" << font_key << "num cached:" << qt_font_textures.size();
4930 qt_font_textures.insert(font_key, font_tex);
4931 } else {
4932 font_tex = it.value();
4933 glBindTexture(GL_TEXTURE_2D, font_tex->texture);
4934 }
4935
4936 for (int i=0; i< glyphs.size(); ++i) {
4937 QGLGlyphHash::const_iterator it = cache->constFind(glyphs[i]);
4938 if (it == cache->constEnd()) {
4939 // render new glyph and put it in the cache
4940 glyph_metrics_t metrics = ti.fontEngine->boundingBox(glyphs[i]);
4941 int glyph_width = qRound(metrics.width.toReal())+2;
4942 int glyph_height = qRound(ti.ascent.toReal() + ti.descent.toReal())+2;
4943
4944 if (font_tex->x_offset + glyph_width + x_margin > font_tex->width) {
4945 int strip_height = qt_next_power_of_two(qRound(ti.ascent.toReal() + ti.descent.toReal())+2);
4946 font_tex->x_offset = x_margin;
4947 font_tex->y_offset += strip_height;
4948 if (font_tex->y_offset >= font_tex->height) {
4949 // get hold of the old font texture
4950 uchar *old_tex_data = (uchar *) malloc(font_tex->width*font_tex->height*2);
4951 int old_tex_height = font_tex->height;
4952#ifndef QT_OPENGL_ES
4953 glGetTexImage(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, old_tex_data);
4954#endif
4955
4956 // realloc a larger texture
4957 glDeleteTextures(1, &font_tex->texture);
4958 glGenTextures(1, &font_tex->texture);
4959 font_tex->height = qt_next_power_of_two(font_tex->height + strip_height);
4960 allocTexture(font_tex->width, font_tex->height, font_tex->texture);
4961
4962 // write back the old texture data
4963 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, font_tex->width, old_tex_height,
4964 GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, old_tex_data);
4965 free(old_tex_data);
4966
4967 // update the texture coords and the y offset for the existing glyphs in
4968 // the cache, because of the texture size change
4969 QGLGlyphHash::iterator it = cache->begin();
4970 while (it != cache->end()) {
4971 it.value()->height = (it.value()->height * old_tex_height) / font_tex->height;
4972 it.value()->y = (it.value()->y * old_tex_height) / font_tex->height;
4973 ++it;
4974 }
4975 }
4976 }
4977
4978 QImage glyph_im(ti.fontEngine->alphaMapForGlyph(glyphs[i]).convertToFormat(QImage::Format_Indexed8));
4979 glyph_width = glyph_im.width();
4980 Q_ASSERT(glyph_width >= 0);
4981 // pad the glyph width to an even number
4982 if (glyph_width%2 != 0)
4983 ++glyph_width;
4984
4985 QGLGlyphCoord *qgl_glyph = new QGLGlyphCoord;
4986 qgl_glyph->x = qreal(font_tex->x_offset) / font_tex->width;
4987 qgl_glyph->y = qreal(font_tex->y_offset) / font_tex->height;
4988 qgl_glyph->width = qreal(glyph_width) / font_tex->width;
4989 qgl_glyph->height = qreal(glyph_height) / font_tex->height;
4990 qgl_glyph->log_width = qreal(glyph_width);
4991 qgl_glyph->log_height = qgl_glyph->height * font_tex->height;
4992#ifdef Q_WS_MAC
4993 qgl_glyph->x_offset = -metrics.x + 1;
4994 qgl_glyph->y_offset = metrics.y - 2;
4995#else
4996 qgl_glyph->x_offset = -metrics.x;
4997 qgl_glyph->y_offset = metrics.y;
4998#endif
4999
5000 if (!glyph_im.isNull()) {
5001
5002 int idx = 0;
5003 uchar *tex_data = (uchar *) malloc(glyph_width*glyph_im.height()*2);
5004 memset(tex_data, 0, glyph_width*glyph_im.height()*2);
5005
5006 for (int y=0; y<glyph_im.height(); ++y) {
5007 uchar *s = (uchar *) glyph_im.scanLine(y);
5008 for (int x=0; x<glyph_im.width(); ++x) {
5009 uchar alpha = qAlpha(glyph_im.color(*s));
5010 tex_data[idx] = alpha;
5011 tex_data[idx+1] = alpha;
5012 ++s;
5013 idx += 2;
5014 }
5015 if (glyph_im.width()%2 != 0)
5016 idx += 2;
5017 }
5018 glTexSubImage2D(GL_TEXTURE_2D, 0, font_tex->x_offset, font_tex->y_offset,
5019 glyph_width, glyph_im.height(),
5020 GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, tex_data);
5021 free(tex_data);
5022 }
5023 if (font_tex->x_offset + glyph_width + x_margin > font_tex->width) {
5024 font_tex->x_offset = x_margin;
5025 font_tex->y_offset += glyph_height + y_margin;
5026 } else {
5027 font_tex->x_offset += glyph_width + x_margin;
5028 }
5029
5030 cache->insert(glyphs[i], qgl_glyph);
5031 }
5032 }
5033}
5034
5035QGLGlyphCoord *QGLGlyphCache::lookup(QFontEngine *, glyph_t g)
5036{
5037 Q_ASSERT(current_cache != 0);
5038 // ### careful here
5039 QGLGlyphHash::const_iterator it = current_cache->constFind(g);
5040 if (it == current_cache->constEnd())
5041 return 0;
5042 else
5043 return it.value();
5044}
5045
5046Q_GLOBAL_STATIC(QGLGlyphCache, qt_glyph_cache)
5047
5048//
5049// assumption: the context that this is called for has to be the
5050// current context
5051//
5052void qgl_cleanup_glyph_cache(QGLContext *ctx)
5053{
5054 qt_glyph_cache()->cleanupContext(ctx);
5055}
5056
5057void QOpenGLPaintEngine::drawTextItem(const QPointF &p, const QTextItem &textItem)
5058{
5059 Q_D(QOpenGLPaintEngine);
5060
5061 const QTextItemInt &ti = static_cast<const QTextItemInt &>(textItem);
5062
5063 // fall back to drawing a polygon if the scale factor is large, or
5064 // we use a gradient pen
5065 if (ti.fontEngine->fontDef.pixelSize >= 64
5066 || (d->matrix.det() > 1) || (d->pen_brush_style >= Qt::LinearGradientPattern
5067 && d->pen_brush_style <= Qt::ConicalGradientPattern)) {
5068 QPaintEngine::drawTextItem(p, textItem);
5069 return;
5070 }
5071
5072 d->flushDrawQueue();
5073
5074 // add the glyphs used to the glyph texture cache
5075 QVarLengthArray<QFixedPoint> positions;
5076 QVarLengthArray<glyph_t> glyphs;
5077 QTransform matrix;
5078 matrix.translate(qRound(p.x()), qRound(p.y()));
5079 ti.fontEngine->getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions);
5080
5081 // make sure the glyphs we want to draw are in the cache
5082 qt_glyph_cache()->cacheGlyphs(d->drawable.context(), ti, glyphs);
5083
5084 d->setGradientOps(Qt::SolidPattern, QRectF()); // turns off gradient ops
5085 qt_glColor4ubv(d->pen_color);
5086 glEnable(GL_TEXTURE_2D);
5087
5088#ifdef Q_WS_QWS
5089 // XXX: it is necessary to disable alpha writes on GLES/embedded because we don't want
5090 // text rendering to update the alpha in the window surface.
5091 // XXX: This may not be needed as this behavior does seem to be caused by driver bug
5092 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE);
5093#endif
5094
5095 // do the actual drawing
5096 q_vertexType vertexArray[4*2];
5097 q_vertexType texCoordArray[4*2];
5098
5099 glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
5100 glTexCoordPointer(2, q_vertexTypeEnum, 0, texCoordArray);
5101
5102 glEnableClientState(GL_VERTEX_ARRAY);
5103 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
5104 bool antialias = !(ti.fontEngine->fontDef.styleStrategy & QFont::NoAntialias);
5105 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, antialias ? GL_LINEAR : GL_NEAREST);
5106 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, antialias ? GL_LINEAR : GL_NEAREST);
5107
5108 for (int i=0; i< glyphs.size(); ++i) {
5109 QGLGlyphCoord *g = qt_glyph_cache()->lookup(ti.fontEngine, glyphs[i]);
5110
5111 // we don't cache glyphs with no width/height
5112 if (!g)
5113 continue;
5114
5115 qreal x1, x2, y1, y2;
5116 x1 = g->x;
5117 y1 = g->y;
5118 x2 = x1 + g->width;
5119 y2 = y1 + g->height;
5120
5121 QPointF logical_pos((positions[i].x - g->x_offset).toReal(),
5122 (positions[i].y + g->y_offset).toReal());
5123
5124 qt_add_rect_to_array(QRectF(logical_pos, QSizeF(g->log_width, g->log_height)), vertexArray);
5125 qt_add_texcoords_to_array(x1, y1, x2, y2, texCoordArray);
5126
5127 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
5128 }
5129
5130 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
5131 glDisableClientState(GL_VERTEX_ARRAY);
5132
5133 glDisable(GL_TEXTURE_2D);
5134
5135#ifdef Q_WS_QWS
5136 // XXX: This may not be needed as this behavior does seem to be caused by driver bug
5137 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
5138#endif
5139}
5140
5141
5142void QOpenGLPaintEngine::drawEllipse(const QRectF &rect)
5143{
5144#ifndef Q_WS_QWS
5145 Q_D(QOpenGLPaintEngine);
5146
5147 if (d->use_emulation) {
5148 QPaintEngineEx::drawEllipse(rect);
5149 return;
5150 }
5151
5152 if (d->high_quality_antialiasing) {
5153 if (d->has_brush) {
5154 d->disableClipping();
5155
5156 glMatrixMode(GL_MODELVIEW);
5157 glPushMatrix();
5158 glLoadIdentity();
5159
5160 GLuint program = qt_gl_program_cache()->getProgram(d->drawable.context(),
5161 FRAGMENT_PROGRAM_MASK_ELLIPSE_AA, 0, true);
5162 QGLEllipseMaskGenerator maskGenerator(rect,
5163 d->matrix,
5164 d->offscreen,
5165 program,
5166 mask_variable_locations[FRAGMENT_PROGRAM_MASK_ELLIPSE_AA]);
5167
5168 d->addItem(qt_mask_texture_cache()->getMask(maskGenerator, d));
5169
5170 d->enableClipping();
5171
5172 glMatrixMode(GL_MODELVIEW);
5173 glPopMatrix();
5174 }
5175
5176 if (d->has_pen) {
5177 QPainterPath path;
5178 path.addEllipse(rect);
5179
5180 d->strokePath(path, false);
5181 }
5182 } else {
5183 DEBUG_ONCE_STR("QOpenGLPaintEngine::drawEllipse(): falling back to drawPath()");
5184
5185 QPainterPath path;
5186 path.addEllipse(rect);
5187 drawPath(path);
5188 }
5189#else
5190 QPaintEngineEx::drawEllipse(rect);
5191#endif
5192}
5193
5194
5195void QOpenGLPaintEnginePrivate::updateFragmentProgramData(int locations[])
5196{
5197#ifdef Q_WS_QWS
5198 Q_UNUSED(locations);
5199#else
5200 QGL_FUNC_CONTEXT;
5201
5202 QSize sz = offscreen.offscreenSize();
5203
5204 float inv_mask_size_data[4] = { 1.0f / sz.width(), 1.0f / sz.height(), 0.0f, 0.0f };
5205
5206 sz = drawable_texture_size;
5207
5208 float inv_dst_size_data[4] = { 1.0f / sz.width(), 1.0f / sz.height(), 0.0f, 0.0f };
5209
5210 // default inv size 0.125f == 1.0f / 8.0f for pattern brushes
5211 float inv_brush_texture_size_data[4] = { 0.125f, 0.125f };
5212
5213 // texture patterns have their own size
5214 if (current_style == Qt::TexturePattern) {
5215 QSize sz = cbrush.texture().size();
5216
5217 inv_brush_texture_size_data[0] = 1.0f / sz.width();
5218 inv_brush_texture_size_data[1] = 1.0f / sz.height();
5219 }
5220
5221 for (unsigned int i = 0; i < num_fragment_variables; ++i) {
5222 int location = locations[i];
5223
5224 if (location < 0)
5225 continue;
5226
5227 switch (i) {
5228 case VAR_ANGLE:
5229 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, location, angle_data);
5230 break;
5231 case VAR_LINEAR:
5232 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, location, linear_data);
5233 break;
5234 case VAR_FMP:
5235 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, location, fmp_data);
5236 break;
5237 case VAR_FMP2_M_RADIUS2:
5238 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, location, fmp2_m_radius2_data);
5239 break;
5240 case VAR_INV_MASK_SIZE:
5241 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, location, inv_mask_size_data);
5242 break;
5243 case VAR_INV_DST_SIZE:
5244 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, location, inv_dst_size_data);
5245 break;
5246 case VAR_INV_MATRIX_M0:
5247 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, location, inv_matrix_data[0]);
5248 break;
5249 case VAR_INV_MATRIX_M1:
5250 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, location, inv_matrix_data[1]);
5251 break;
5252 case VAR_INV_MATRIX_M2:
5253 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, location, inv_matrix_data[2]);
5254 break;
5255 case VAR_PORTERDUFF_AB:
5256 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, location, porterduff_ab_data);
5257 break;
5258 case VAR_PORTERDUFF_XYZ:
5259 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, location, porterduff_xyz_data);
5260 break;
5261 case VAR_INV_BRUSH_TEXTURE_SIZE:
5262 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, location, inv_brush_texture_size_data);
5263 break;
5264 case VAR_MASK_OFFSET:
5265 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, location, mask_offset_data);
5266 break;
5267 case VAR_MASK_CHANNEL:
5268 glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, location, mask_channel_data);
5269 break;
5270 case VAR_DST_TEXTURE:
5271 case VAR_MASK_TEXTURE:
5272 case VAR_PALETTE:
5273 case VAR_BRUSH_TEXTURE:
5274 // texture variables, not handled here
5275 break;
5276 default:
5277 qDebug() << "QOpenGLPaintEnginePrivate: Unhandled fragment variable:" << i;
5278 }
5279 }
5280#endif
5281}
5282
5283
5284void QOpenGLPaintEnginePrivate::copyDrawable(const QRectF &rect)
5285{
5286#ifdef Q_WS_QWS
5287 Q_UNUSED(rect);
5288#else
5289 ensureDrawableTexture();
5290
5291 DEBUG_ONCE qDebug() << "Refreshing drawable_texture for rectangle" << rect;
5292 QRectF screen_rect = rect.adjusted(-1, -1, 1, 1);
5293
5294 int left = qMax(0, static_cast<int>(screen_rect.left()));
5295 int width = qMin(drawable.size().width() - left, static_cast<int>(screen_rect.width()) + 1);
5296
5297 int bottom = qMax(0, static_cast<int>(drawable.size().height() - screen_rect.bottom()));
5298 int height = qMin(drawable.size().height() - bottom, static_cast<int>(screen_rect.height()) + 1);
5299
5300 glBindTexture(GL_TEXTURE_2D, drawable_texture);
5301 glCopyTexSubImage2D(GL_TEXTURE_2D, 0, left, bottom, left, bottom, width, height);
5302#endif
5303}
5304
5305
5306void QOpenGLPaintEnginePrivate::composite(const QRectF &rect, const QPoint &maskOffset)
5307{
5308#ifdef Q_WS_QWS
5309 Q_UNUSED(rect);
5310 Q_UNUSED(maskOffset);
5311#else
5312 q_vertexType vertexArray[8];
5313 qt_add_rect_to_array(rect, vertexArray);
5314
5315 composite(GL_TRIANGLE_FAN, vertexArray, 4, maskOffset);
5316#endif
5317}
5318
5319
5320void QOpenGLPaintEnginePrivate::composite(GLuint primitive, const q_vertexType *vertexArray, int vertexCount, const QPoint &maskOffset)
5321{
5322#ifdef QT_OPENGL_ES
5323 Q_UNUSED(primitive);
5324 Q_UNUSED(vertexArray);
5325 Q_UNUSED(vertexCount);
5326 Q_UNUSED(maskOffset);
5327#else
5328 Q_Q(QOpenGLPaintEngine);
5329 QGL_FUNC_CONTEXT;
5330
5331 if (current_style == Qt::NoBrush)
5332 return;
5333
5334 DEBUG_ONCE qDebug() << "QOpenGLPaintEnginePrivate: Using compositing program: fragment_brush ="
5335 << fragment_brush << ", fragment_composition_mode =" << fragment_composition_mode;
5336
5337 if (has_fast_composition_mode)
5338 q->updateCompositionMode(composition_mode);
5339 else {
5340 qreal minX = 1e9, minY = 1e9, maxX = -1e9, maxY = -1e9;
5341
5342 for (int i = 0; i < vertexCount; ++i) {
5343 qreal x = vt2f(vertexArray[2 * i]);
5344 qreal y = vt2f(vertexArray[2 * i + 1]);
5345
5346 qreal tx, ty;
5347 matrix.map(x, y, &tx, &ty);
5348
5349 minX = qMin(minX, tx);
5350 minY = qMin(minY, ty);
5351 maxX = qMax(maxX, tx);
5352 maxY = qMax(maxY, ty);
5353 }
5354
5355 QRectF r(minX, minY, maxX - minX, maxY - minY);
5356 copyDrawable(r);
5357
5358 glBlendFunc(GL_ONE, GL_ZERO);
5359 }
5360
5361 int *locations = painter_variable_locations[fragment_brush][fragment_composition_mode];
5362
5363 int texture_locations[] = { locations[VAR_DST_TEXTURE],
5364 locations[VAR_MASK_TEXTURE],
5365 locations[VAR_PALETTE] };
5366
5367 int brush_texture_location = locations[VAR_BRUSH_TEXTURE];
5368
5369 GLuint texture_targets[] = { GL_TEXTURE_2D,
5370 GL_TEXTURE_2D,
5371 GL_TEXTURE_1D };
5372
5373 GLuint textures[] = { drawable_texture,
5374 offscreen.offscreenTexture(),
5375 grad_palette };
5376
5377 const int num_textures = sizeof(textures) / sizeof(*textures);
5378
5379 Q_ASSERT(num_textures == sizeof(texture_locations) / sizeof(*texture_locations));
5380 Q_ASSERT(num_textures == sizeof(texture_targets) / sizeof(*texture_targets));
5381
5382 for (int i = 0; i < num_textures; ++i)
5383 if (texture_locations[i] >= 0) {
5384 glActiveTexture(GL_TEXTURE0 + texture_locations[i]);
5385 glBindTexture(texture_targets[i], textures[i]);
5386 }
5387
5388 if (brush_texture_location >= 0) {
5389 glActiveTexture(GL_TEXTURE0 + brush_texture_location);
5390
5391 if (current_style == Qt::TexturePattern)
5392 drawable.bindTexture(cbrush.textureImage());
5393 else
5394 drawable.bindTexture(qt_imageForBrush(current_style, true));
5395
5396 updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, use_smooth_pixmap_transform);
5397 }
5398
5399 glEnableClientState(GL_VERTEX_ARRAY);
5400 glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray);
5401 glEnable(GL_FRAGMENT_PROGRAM_ARB);
5402 GLuint program = qt_gl_program_cache()->getProgram(drawable.context(),
5403 fragment_brush,
5404 fragment_composition_mode, false);
5405 glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, program);
5406
5407 mask_offset_data[0] = maskOffset.x();
5408 mask_offset_data[1] = -maskOffset.y();
5409
5410 updateFragmentProgramData(locations);
5411
5412 glDrawArrays(primitive, 0, vertexCount);
5413
5414 glDisable(GL_FRAGMENT_PROGRAM_ARB);
5415 glDisableClientState(GL_VERTEX_ARRAY);
5416
5417 for (int i = 0; i < num_textures; ++i)
5418 if (texture_locations[i] >= 0) {
5419 glActiveTexture(GL_TEXTURE0 + texture_locations[i]);
5420 glBindTexture(texture_targets[i], 0);
5421 }
5422
5423 if (brush_texture_location >= 0) {
5424 glActiveTexture(GL_TEXTURE0 + brush_texture_location);
5425 glBindTexture(GL_TEXTURE_2D, 0);
5426 }
5427
5428 glActiveTexture(GL_TEXTURE0);
5429
5430 if (!has_fast_composition_mode)
5431 q->updateCompositionMode(composition_mode);
5432#endif
5433}
5434
5435void QOpenGLPaintEnginePrivate::cacheItemErased(int channel, const QRect &rect)
5436{
5437 bool isInDrawQueue = false;
5438
5439 foreach (const QDrawQueueItem &item, drawQueue) {
5440 if (item.location.channel == channel && item.location.rect == rect) {
5441 isInDrawQueue = true;
5442 break;
5443 }
5444 }
5445
5446 if (isInDrawQueue)
5447 flushDrawQueue();
5448}
5449
5450void QOpenGLPaintEnginePrivate::addItem(const QGLMaskTextureCache::CacheLocation &location)
5451{
5452 drawQueue << QDrawQueueItem(opacity, cbrush, brush_origin, composition_mode, matrix, location);
5453}
5454
5455void QOpenGLPaintEnginePrivate::drawItem(const QDrawQueueItem &item)
5456{
5457 Q_Q(QOpenGLPaintEngine);
5458
5459 opacity = item.opacity;
5460 brush_origin = item.brush_origin;
5461 q->updateCompositionMode(item.composition_mode);
5462 matrix = item.matrix;
5463 cbrush = item.brush;
5464 brush_style = item.brush.style();
5465
5466 mask_channel_data[0] = item.location.channel == 0;
5467 mask_channel_data[1] = item.location.channel == 1;
5468 mask_channel_data[2] = item.location.channel == 2;
5469 mask_channel_data[3] = item.location.channel == 3;
5470
5471 setGradientOps(item.brush, item.location.screen_rect);
5472
5473 composite(item.location.screen_rect, item.location.rect.topLeft() - item.location.screen_rect.topLeft()
5474 - QPoint(0, offscreen.offscreenSize().height() - drawable.size().height()));
5475}
5476
5477void QOpenGLPaintEnginePrivate::flushDrawQueue()
5478{
5479#ifndef QT_OPENGL_ES
5480 Q_Q(QOpenGLPaintEngine);
5481
5482 offscreen.release();
5483
5484 if (!drawQueue.isEmpty()) {
5485 DEBUG_ONCE qDebug() << "QOpenGLPaintEngine::flushDrawQueue():" << drawQueue.size() << "items";
5486
5487 glPushMatrix();
5488 glLoadIdentity();
5489 qreal old_opacity = opacity;
5490 QPointF old_brush_origin = brush_origin;
5491 QPainter::CompositionMode old_composition_mode = composition_mode;
5492 QTransform old_matrix = matrix;
5493 QBrush old_brush = cbrush;
5494
5495 bool hqaa_old = high_quality_antialiasing;
5496
5497 high_quality_antialiasing = true;
5498
5499 foreach (const QDrawQueueItem &item, drawQueue)
5500 drawItem(item);
5501
5502 opacity = old_opacity;
5503 brush_origin = old_brush_origin;
5504 q->updateCompositionMode(old_composition_mode);
5505 matrix = old_matrix;
5506 cbrush = old_brush;
5507 brush_style = old_brush.style();
5508
5509 high_quality_antialiasing = hqaa_old;
5510
5511 setGLBrush(old_brush.color());
5512 qt_glColor4ubv(brush_color);
5513
5514 drawQueue.clear();
5515
5516 glPopMatrix();
5517 }
5518#endif
5519}
5520
5521void QOpenGLPaintEngine::clipEnabledChanged()
5522{
5523 Q_D(QOpenGLPaintEngine);
5524
5525 d->updateDepthClip();
5526}
5527
5528void QOpenGLPaintEngine::penChanged()
5529{
5530 updatePen(state()->pen);
5531}
5532
5533void QOpenGLPaintEngine::brushChanged()
5534{
5535 updateBrush(state()->brush, state()->brushOrigin);
5536}
5537
5538void QOpenGLPaintEngine::brushOriginChanged()
5539{
5540 updateBrush(state()->brush, state()->brushOrigin);
5541}
5542
5543void QOpenGLPaintEngine::opacityChanged()
5544{
5545 Q_D(QOpenGLPaintEngine);
5546 QPainterState *s = state();
5547 d->opacity = s->opacity;
5548 updateBrush(s->brush, s->brushOrigin);
5549 updatePen(s->pen);
5550}
5551
5552void QOpenGLPaintEngine::compositionModeChanged()
5553{
5554 updateCompositionMode(state()->composition_mode);
5555}
5556
5557void QOpenGLPaintEngine::renderHintsChanged()
5558{
5559 updateRenderHints(state()->renderHints);
5560}
5561
5562void QOpenGLPaintEngine::transformChanged()
5563{
5564 updateMatrix(state()->matrix);
5565}
5566
5567static QPainterPath painterPathFromVectorPath(const QVectorPath &path)
5568{
5569 const qreal *points = path.points();
5570 const QPainterPath::ElementType *types = path.elements();
5571
5572 QPainterPath p;
5573 if (types) {
5574 int id = 0;
5575 for (int i=0; i<path.elementCount(); ++i) {
5576 switch(types[i]) {
5577 case QPainterPath::MoveToElement:
5578 p.moveTo(QPointF(points[id], points[id+1]));
5579 id+=2;
5580 break;
5581 case QPainterPath::LineToElement:
5582 p.lineTo(QPointF(points[id], points[id+1]));
5583 id+=2;
5584 break;
5585 case QPainterPath::CurveToElement: {
5586 QPointF p1(points[id], points[id+1]);
5587 QPointF p2(points[id+2], points[id+3]);
5588 QPointF p3(points[id+4], points[id+5]);
5589 p.cubicTo(p1, p2, p3);
5590 id+=6;
5591 break;
5592 }
5593 case QPainterPath::CurveToDataElement:
5594 ;
5595 break;
5596 }
5597 }
5598 } else {
5599 p.moveTo(QPointF(points[0], points[1]));
5600 int id = 2;
5601 for (int i=1; i<path.elementCount(); ++i) {
5602 p.lineTo(QPointF(points[id], points[id+1]));
5603 id+=2;
5604 }
5605 }
5606 if (path.hints() & QVectorPath::WindingFill)
5607 p.setFillRule(Qt::WindingFill);
5608
5609 return p;
5610}
5611
5612void QOpenGLPaintEngine::fill(const QVectorPath &path, const QBrush &brush)
5613{
5614 Q_D(QOpenGLPaintEngine);
5615
5616 if (brush.style() == Qt::NoBrush)
5617 return;
5618
5619 if (!d->use_fragment_programs && needsEmulation(brush.style())) {
5620 QPainter *p = painter();
5621 QBrush oldBrush = p->brush();
5622 p->setBrush(brush);
5623 qt_draw_helper(p->d_ptr, painterPathFromVectorPath(path), QPainterPrivate::FillDraw);
5624 p->setBrush(oldBrush);
5625 return;
5626 }
5627
5628 QBrush old_brush = state()->brush;
5629 updateBrush(brush, state()->brushOrigin);
5630
5631 const qreal *points = path.points();
5632 const QPainterPath::ElementType *types = path.elements();
5633 if (!types && path.shape() == QVectorPath::RectangleHint) {
5634 QRectF r(points[0], points[1], points[4]-points[0], points[5]-points[1]);
5635 QPen old_pen = state()->pen;
5636 updatePen(Qt::NoPen);
5637 drawRects(&r, 1);
5638 updatePen(old_pen);
5639 } else {
5640 d->fillPath(painterPathFromVectorPath(path));
5641 }
5642
5643 updateBrush(old_brush, state()->brushOrigin);
5644}
5645
5646template <typename T> static inline bool isRect(const T *pts, int elementCount) {
5647 return (elementCount == 5 // 5-point polygon, check for closed rect
5648 && pts[0] == pts[8] && pts[1] == pts[9] // last point == first point
5649 && pts[0] == pts[6] && pts[2] == pts[4] // x values equal
5650 && pts[1] == pts[3] && pts[5] == pts[7] // y values equal...
5651 ) ||
5652 (elementCount == 4 // 4-point polygon, check for unclosed rect
5653 && pts[0] == pts[6] && pts[2] == pts[4] // x values equal
5654 && pts[1] == pts[3] && pts[5] == pts[7] // y values equal...
5655 );
5656}
5657
5658void QOpenGLPaintEngine::clip(const QVectorPath &path, Qt::ClipOperation op)
5659{
5660 const qreal *points = path.points();
5661 const QPainterPath::ElementType *types = path.elements();
5662 if (!types && path.shape() == QVectorPath::RectangleHint) {
5663 QRectF r(points[0], points[1], points[4]-points[0], points[5]-points[1]);
5664 updateClipRegion(QRegion(r.toRect()), op);
5665 return;
5666 }
5667
5668 QPainterPath p;
5669 if (types) {
5670 int id = 0;
5671 for (int i=0; i<path.elementCount(); ++i) {
5672 switch(types[i]) {
5673 case QPainterPath::MoveToElement:
5674 p.moveTo(QPointF(points[id], points[id+1]));
5675 id+=2;
5676 break;
5677 case QPainterPath::LineToElement:
5678 p.lineTo(QPointF(points[id], points[id+1]));
5679 id+=2;
5680 break;
5681 case QPainterPath::CurveToElement: {
5682 QPointF p1(points[id], points[id+1]);
5683 QPointF p2(points[id+2], points[id+3]);
5684 QPointF p3(points[id+4], points[id+5]);
5685 p.cubicTo(p1, p2, p3);
5686 id+=6;
5687 break;
5688 }
5689 case QPainterPath::CurveToDataElement:
5690 ;
5691 break;
5692 }
5693 }
5694 } else if (!path.isEmpty()) {
5695 p.moveTo(QPointF(points[0], points[1]));
5696 int id = 2;
5697 for (int i=1; i<path.elementCount(); ++i) {
5698 p.lineTo(QPointF(points[id], points[id+1]));
5699 id+=2;
5700 }
5701 }
5702 if (path.hints() & QVectorPath::WindingFill)
5703 p.setFillRule(Qt::WindingFill);
5704
5705 updateClipRegion(QRegion(p.toFillPolygon().toPolygon(), p.fillRule()), op);
5706 return;
5707}
5708
5709void QOpenGLPaintEngine::setState(QPainterState *s)
5710{
5711 Q_D(QOpenGLPaintEngine);
5712 QPaintEngineEx::setState(s);
5713 if (isActive()) {
5714 d->updateDepthClip();
5715 penChanged();
5716 brushChanged();
5717 opacityChanged();
5718 compositionModeChanged();
5719 renderHintsChanged();
5720 transformChanged();
5721 }
5722}
5723
5724QPainterState *QOpenGLPaintEngine::createState(QPainterState *orig) const
5725{
5726 QOpenGLPaintEngineState *s;
5727 if (!orig)
5728 s = new QOpenGLPaintEngineState();
5729 else
5730 s = new QOpenGLPaintEngineState(*static_cast<QOpenGLPaintEngineState *>(orig));
5731
5732 return s;
5733}
5734
5735//
5736// QOpenGLPaintEngineState
5737//
5738
5739QOpenGLPaintEngineState::QOpenGLPaintEngineState(QOpenGLPaintEngineState &other)
5740 : QPainterState(other)
5741{
5742 clipRegion = other.clipRegion;
5743 hasClipping = other.hasClipping;
5744 fastClip = other.fastClip;
5745}
5746
5747QOpenGLPaintEngineState::QOpenGLPaintEngineState()
5748{
5749 hasClipping = false;
5750}
5751
5752QOpenGLPaintEngineState::~QOpenGLPaintEngineState()
5753{
5754}
5755
5756void QOpenGLPaintEnginePrivate::ensureDrawableTexture()
5757{
5758 if (!dirty_drawable_texture)
5759 return;
5760
5761 dirty_drawable_texture = false;
5762
5763#ifndef QT_OPENGL_ES
5764 glGenTextures(1, &drawable_texture);
5765 glBindTexture(GL_TEXTURE_2D, drawable_texture);
5766
5767 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8,
5768 drawable_texture_size.width(),
5769 drawable_texture_size.height(), 0,
5770 GL_RGBA, GL_UNSIGNED_BYTE, NULL);
5771
5772 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
5773 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
5774 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
5775 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
5776#endif
5777}
5778
5779QPixmapFilter *QOpenGLPaintEngine::createPixmapFilter(int type) const
5780{
5781 if (QGLContext::currentContext())
5782 return QGLContext::currentContext()->d_func()->createPixmapFilter(type);
5783 else
5784 return 0;
5785}
5786
5787
5788QT_END_NAMESPACE
5789
5790#include "qpaintengine_opengl.moc"
Note: See TracBrowser for help on using the repository browser.