source: trunk/src/opengl/qgl_p.h@ 755

Last change on this file since 755 was 651, checked in by Dmitry A. Kuminov, 15 years ago

trunk: Merged in qt 4.6.2 sources.

File size: 20.4 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation ([email protected])
6**
7** This file is part of the QtOpenGL module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this 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 have questions regarding the use of this file, please contact
37** Nokia at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#ifndef QGL_P_H
43#define QGL_P_H
44
45//
46// W A R N I N G
47// -------------
48//
49// This file is not part of the Qt API. It exists for the convenience
50// of the QGLWidget class. This header file may change from
51// version to version without notice, or even be removed.
52//
53// We mean it.
54//
55
56#include "QtOpenGL/qgl.h"
57#include "QtOpenGL/qglcolormap.h"
58#include "QtCore/qmap.h"
59#include "QtCore/qthread.h"
60#include "QtCore/qthreadstorage.h"
61#include "QtCore/qhash.h"
62#include "QtCore/qatomic.h"
63#include "private/qwidget_p.h"
64#include "qcache.h"
65#include "qglpaintdevice_p.h"
66
67#ifndef QT_OPENGL_ES_1_CL
68#define q_vertexType float
69#define q_vertexTypeEnum GL_FLOAT
70#define f2vt(f) (f)
71#define vt2f(x) (x)
72#define i2vt(i) (float(i))
73#else
74#define FLOAT2X(f) (int( (f) * (65536)))
75#define X2FLOAT(x) (float(x) / 65536.0f)
76#define f2vt(f) FLOAT2X(f)
77#define i2vt(i) ((i)*65536)
78#define vt2f(x) X2FLOAT(x)
79#define q_vertexType GLfixed
80#define q_vertexTypeEnum GL_FIXED
81#endif //QT_OPENGL_ES_1_CL
82
83#ifdef QT_OPENGL_ES
84QT_BEGIN_INCLUDE_NAMESPACE
85#if defined(QT_OPENGL_ES_2)
86#include <EGL/egl.h>
87#else
88#include <GLES/egl.h>
89#endif
90QT_END_INCLUDE_NAMESPACE
91#endif
92
93QT_BEGIN_NAMESPACE
94
95class QGLContext;
96class QGLOverlayWidget;
97class QPixmap;
98class QPixmapFilter;
99#ifdef Q_WS_MAC
100# ifdef qDebug
101# define old_qDebug qDebug
102# undef qDebug
103# endif
104QT_BEGIN_INCLUDE_NAMESPACE
105#ifndef QT_MAC_USE_COCOA
106# include <AGL/agl.h>
107#endif
108QT_END_INCLUDE_NAMESPACE
109# ifdef old_qDebug
110# undef qDebug
111# define qDebug QT_QDEBUG_MACRO
112# undef old_qDebug
113# endif
114class QMacWindowChangeEvent;
115#endif
116
117#ifdef Q_WS_QWS
118class QWSGLWindowSurface;
119#endif
120
121#if defined(QT_OPENGL_ES)
122class QEglContext;
123#endif
124
125QT_BEGIN_INCLUDE_NAMESPACE
126#include <QtOpenGL/private/qglextensions_p.h>
127QT_END_INCLUDE_NAMESPACE
128
129class QGLFormatPrivate
130{
131public:
132 QGLFormatPrivate()
133 : ref(1)
134 {
135 opts = QGL::DoubleBuffer | QGL::DepthBuffer | QGL::Rgba | QGL::DirectRendering | QGL::StencilBuffer;
136 pln = 0;
137 depthSize = accumSize = stencilSize = redSize = greenSize = blueSize = alphaSize = -1;
138 numSamples = -1;
139 swapInterval = -1;
140 }
141 QGLFormatPrivate(const QGLFormatPrivate *other)
142 : ref(1),
143 opts(other->opts),
144 pln(other->pln),
145 depthSize(other->depthSize),
146 accumSize(other->accumSize),
147 stencilSize(other->stencilSize),
148 redSize(other->redSize),
149 greenSize(other->greenSize),
150 blueSize(other->blueSize),
151 alphaSize(other->alphaSize),
152 numSamples(other->numSamples),
153 swapInterval(other->swapInterval)
154 {
155 }
156 QAtomicInt ref;
157 QGL::FormatOptions opts;
158 int pln;
159 int depthSize;
160 int accumSize;
161 int stencilSize;
162 int redSize;
163 int greenSize;
164 int blueSize;
165 int alphaSize;
166 int numSamples;
167 int swapInterval;
168};
169
170class QGLWidgetPrivate : public QWidgetPrivate
171{
172 Q_DECLARE_PUBLIC(QGLWidget)
173public:
174 QGLWidgetPrivate() : QWidgetPrivate()
175 , disable_clear_on_painter_begin(false)
176#ifdef Q_WS_QWS
177 , wsurf(0)
178#endif
179#if defined(Q_WS_X11) && defined(QT_OPENGL_ES)
180 , eglSurfaceWindowId(0)
181#endif
182 {}
183
184 ~QGLWidgetPrivate() {}
185
186 void init(QGLContext *context, const QGLWidget* shareWidget);
187 void initContext(QGLContext *context, const QGLWidget* shareWidget);
188 bool renderCxPm(QPixmap *pixmap);
189 void cleanupColormaps();
190
191 QGLContext *glcx;
192 QGLWidgetGLPaintDevice glDevice;
193 bool autoSwap;
194
195 QGLColormap cmap;
196#ifndef QT_OPENGL_ES
197 QMap<QString, int> displayListCache;
198#endif
199
200 bool disable_clear_on_painter_begin;
201
202#if defined(Q_WS_WIN)
203 void updateColormap();
204 QGLContext *olcx;
205#elif defined(Q_WS_X11)
206 QGLOverlayWidget *olw;
207#if defined(QT_OPENGL_ES)
208 void recreateEglSurface(bool force);
209 WId eglSurfaceWindowId;
210#endif
211#elif defined(Q_WS_MAC)
212 QGLContext *olcx;
213 void updatePaintDevice();
214#elif defined(Q_WS_QWS)
215 QWSGLWindowSurface *wsurf;
216#endif
217};
218
219class QGLContextResource;
220class QGLSharedResourceGuard;
221
222typedef QHash<QString, GLuint> QGLDDSCache;
223
224// QGLContextPrivate has the responsibility of creating context groups.
225// QGLContextPrivate maintains the reference counter and destroys
226// context groups when needed.
227class QGLContextGroup
228{
229public:
230 ~QGLContextGroup();
231
232 QGLExtensionFuncs &extensionFuncs() {return m_extensionFuncs;}
233 const QGLContext *context() const {return m_context;}
234 bool isSharing() const { return m_shares.size() >= 2; }
235 QList<const QGLContext *> shares() const { return m_shares; }
236
237 void addGuard(QGLSharedResourceGuard *guard);
238 void removeGuard(QGLSharedResourceGuard *guard);
239
240 static void addShare(const QGLContext *context, const QGLContext *share);
241 static void removeShare(const QGLContext *context);
242private:
243 QGLContextGroup(const QGLContext *context) : m_context(context), m_guards(0), m_refs(1) { }
244
245 QGLExtensionFuncs m_extensionFuncs;
246 const QGLContext *m_context; // context group's representative
247 QList<const QGLContext *> m_shares;
248 QHash<QGLContextResource *, void *> m_resources;
249 QGLSharedResourceGuard *m_guards; // double-linked list of active guards.
250 QAtomicInt m_refs;
251 QGLDDSCache m_dds_cache;
252
253 void cleanupResources(const QGLContext *ctx);
254
255 friend class QGLContext;
256 friend class QGLContextPrivate;
257 friend class QGLContextResource;
258};
259
260// Get the context that resources for "ctx" will transfer to once
261// "ctx" is destroyed. Returns null if nothing is sharing with ctx.
262Q_OPENGL_EXPORT const QGLContext *qt_gl_transfer_context(const QGLContext *);
263
264// GL extension definitions
265class QGLExtensions {
266public:
267 enum Extension {
268 TextureRectangle = 0x00000001,
269 SampleBuffers = 0x00000002,
270 GenerateMipmap = 0x00000004,
271 TextureCompression = 0x00000008,
272 FragmentProgram = 0x00000010,
273 MirroredRepeat = 0x00000020,
274 FramebufferObject = 0x00000040,
275 StencilTwoSide = 0x00000080,
276 StencilWrap = 0x00000100,
277 PackedDepthStencil = 0x00000200,
278 NVFloatBuffer = 0x00000400,
279 PixelBufferObject = 0x00000800,
280 FramebufferBlit = 0x00001000,
281 NPOTTextures = 0x00002000,
282 BGRATextureFormat = 0x00004000,
283 DDSTextureCompression = 0x00008000,
284 ETC1TextureCompression = 0x00010000,
285 PVRTCTextureCompression = 0x00020000,
286 FragmentShader = 0x00040000
287 };
288 Q_DECLARE_FLAGS(Extensions, Extension)
289
290 static Extensions glExtensions();
291
292private:
293 static Extensions currentContextExtensions();
294};
295
296/*
297 QGLTemporaryContext - the main objective of this class is to have a way of
298 creating a GL context and making it current, without going via QGLWidget
299 and friends. At certain points during GL initialization we need a current
300 context in order decide what GL features are available, and to resolve GL
301 extensions. Having a light-weight way of creating such a context saves
302 initial application startup time, and it doesn't wind up creating recursive
303 conflicts.
304 The class currently uses a private d pointer to hide the platform specific
305 types. This could possibly been done inline with #ifdef'ery, but it causes
306 major headaches on e.g. X11 due to namespace pollution.
307*/
308class QGLTemporaryContextPrivate;
309class QGLTemporaryContext {
310public:
311 QGLTemporaryContext(bool directRendering = true, QWidget *parent = 0);
312 ~QGLTemporaryContext();
313
314private:
315 QScopedPointer<QGLTemporaryContextPrivate> d;
316};
317
318class QGLTexture;
319
320// This probably needs to grow to GL_MAX_VERTEX_ATTRIBS, but 3 is ok for now as that's
321// all the GL2 engine uses:
322#define QT_GL_VERTEX_ARRAY_TRACKED_COUNT 3
323
324class QGLContextPrivate
325{
326 Q_DECLARE_PUBLIC(QGLContext)
327public:
328 explicit QGLContextPrivate(QGLContext *context) : internal_context(false), q_ptr(context) {group = new QGLContextGroup(context);}
329 ~QGLContextPrivate();
330 QGLTexture *bindTexture(const QImage &image, GLenum target, GLint format,
331 QGLContext::BindOptions options);
332 QGLTexture *bindTexture(const QImage &image, GLenum target, GLint format, const qint64 key,
333 QGLContext::BindOptions options);
334 QGLTexture *bindTexture(const QPixmap &pixmap, GLenum target, GLint format,
335 QGLContext::BindOptions options);
336 QGLTexture *textureCacheLookup(const qint64 key, GLenum target);
337 void init(QPaintDevice *dev, const QGLFormat &format);
338 QImage convertToGLFormat(const QImage &image, bool force_premul, GLenum texture_format);
339 int maxTextureSize();
340
341 void cleanup();
342
343 void setVertexAttribArrayEnabled(int arrayIndex, bool enabled = true);
344 void syncGlState(); // Makes sure the GL context's state is what we think it is
345
346#if defined(Q_WS_WIN)
347 HGLRC rc;
348 HDC dc;
349 WId win;
350 int pixelFormatId;
351 QGLCmap* cmap;
352 HBITMAP hbitmap;
353 HDC hbitmap_hdc;
354#endif
355#if defined(QT_OPENGL_ES)
356 QEglContext *eglContext;
357 EGLSurface eglSurface;
358 void destroyEglSurfaceForDevice();
359#elif defined(Q_WS_X11) || defined(Q_WS_MAC)
360 void* cx;
361#endif
362#if defined(Q_WS_X11) || defined(Q_WS_MAC)
363 void* vi;
364#endif
365#if defined(Q_WS_X11)
366 void* pbuf;
367 quint32 gpm;
368 int screen;
369 QHash<QPixmapData*, QPixmap> boundPixmaps;
370 QGLTexture *bindTextureFromNativePixmap(QPixmapData*, const qint64 key,
371 QGLContext::BindOptions options);
372 static void destroyGlSurfaceForPixmap(QPixmapData*);
373 static void unbindPixmapFromTexture(QPixmapData*);
374#endif
375#if defined(Q_WS_MAC)
376 bool update;
377 void *tryFormat(const QGLFormat &format);
378 void clearDrawable();
379#endif
380 QGLFormat glFormat;
381 QGLFormat reqFormat;
382 GLuint fbo;
383
384 uint valid : 1;
385 uint sharing : 1;
386 uint initDone : 1;
387 uint crWin : 1;
388 uint internal_context : 1;
389 uint version_flags_cached : 1;
390 uint extension_flags_cached : 1;
391 QPaintDevice *paintDevice;
392 QColor transpColor;
393 QGLContext *q_ptr;
394 QGLFormat::OpenGLVersionFlags version_flags;
395 QGLExtensions::Extensions extension_flags;
396
397 QGLContextGroup *group;
398 GLint max_texture_size;
399
400 GLuint current_fbo;
401 GLuint default_fbo;
402 QPaintEngine *active_engine;
403
404 bool vertexAttributeArraysEnabledState[QT_GL_VERTEX_ARRAY_TRACKED_COUNT];
405
406 static inline QGLContextGroup *contextGroup(const QGLContext *ctx) { return ctx->d_ptr->group; }
407
408#ifdef Q_WS_WIN
409 static inline QGLExtensionFuncs& extensionFuncs(const QGLContext *ctx) { return ctx->d_ptr->group->extensionFuncs(); }
410#endif
411
412#if defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QWS)
413 static QGLExtensionFuncs qt_extensionFuncs;
414 static inline QGLExtensionFuncs& extensionFuncs(const QGLContext *) { return qt_extensionFuncs; }
415#endif
416
417 static void setCurrentContext(QGLContext *context);
418};
419
420// ### make QGLContext a QObject in 5.0 and remove the proxy stuff
421class Q_OPENGL_EXPORT QGLSignalProxy : public QObject
422{
423 Q_OBJECT
424public:
425 QGLSignalProxy() : QObject() {}
426 void emitAboutToDestroyContext(const QGLContext *context) {
427 emit aboutToDestroyContext(context);
428 }
429 static QGLSignalProxy *instance();
430Q_SIGNALS:
431 void aboutToDestroyContext(const QGLContext *context);
432};
433
434Q_DECLARE_OPERATORS_FOR_FLAGS(QGLExtensions::Extensions)
435
436// Temporarily make a context current if not already current or
437// shared with the current contex. The previous context is made
438// current when the object goes out of scope.
439class Q_OPENGL_EXPORT QGLShareContextScope
440{
441public:
442 QGLShareContextScope(const QGLContext *ctx)
443 : m_oldContext(0)
444 {
445 QGLContext *currentContext = const_cast<QGLContext *>(QGLContext::currentContext());
446 if (currentContext != ctx && !QGLContext::areSharing(ctx, currentContext)) {
447 m_oldContext = currentContext;
448 m_ctx = const_cast<QGLContext *>(ctx);
449 m_ctx->makeCurrent();
450 } else {
451 m_ctx = currentContext;
452 }
453 }
454
455 operator QGLContext *()
456 {
457 return m_ctx;
458 }
459
460 QGLContext *operator->()
461 {
462 return m_ctx;
463 }
464
465 ~QGLShareContextScope()
466 {
467 if (m_oldContext)
468 m_oldContext->makeCurrent();
469 }
470
471private:
472 QGLContext *m_oldContext;
473 QGLContext *m_ctx;
474};
475
476class QGLTexture {
477public:
478 QGLTexture(QGLContext *ctx = 0, GLuint tx_id = 0, GLenum tx_target = GL_TEXTURE_2D,
479 QGLContext::BindOptions opt = QGLContext::DefaultBindOption)
480 : context(ctx),
481 id(tx_id),
482 target(tx_target),
483 options(opt)
484#if defined(Q_WS_X11)
485 , boundPixmap(0)
486#endif
487 {}
488
489 ~QGLTexture() {
490 if (options & QGLContext::MemoryManagedBindOption) {
491 Q_ASSERT(context);
492 QGLShareContextScope scope(context);
493#if defined(Q_WS_X11)
494 // Although glXReleaseTexImage is a glX call, it must be called while there
495 // is a current context - the context the pixmap was bound to a texture in.
496 // Otherwise the release doesn't do anything and you get BadDrawable errors
497 // when you come to delete the context.
498 if (boundPixmap)
499 QGLContextPrivate::unbindPixmapFromTexture(boundPixmap);
500#endif
501 glDeleteTextures(1, &id);
502 }
503 }
504
505 QGLContext *context;
506 GLuint id;
507 GLenum target;
508
509 QGLContext::BindOptions options;
510
511#if defined(Q_WS_X11)
512 QPixmapData* boundPixmap;
513#endif
514
515 bool canBindCompressedTexture
516 (const char *buf, int len, const char *format, bool *hasAlpha);
517 QSize bindCompressedTexture
518 (const QString& fileName, const char *format = 0);
519 QSize bindCompressedTexture
520 (const char *buf, int len, const char *format = 0);
521 QSize bindCompressedTextureDDS(const char *buf, int len);
522 QSize bindCompressedTexturePVR(const char *buf, int len);
523};
524
525class Q_AUTOTEST_EXPORT QGLTextureCache {
526public:
527 QGLTextureCache();
528 ~QGLTextureCache();
529
530 void insert(QGLContext *ctx, qint64 key, QGLTexture *texture, int cost);
531 void remove(quint64 key) { m_cache.remove(key); }
532 bool remove(QGLContext *ctx, GLuint textureId);
533 void removeContextTextures(QGLContext *ctx);
534 int size() { return m_cache.size(); }
535 void setMaxCost(int newMax) { m_cache.setMaxCost(newMax); }
536 int maxCost() {return m_cache.maxCost(); }
537 QGLTexture* getTexture(quint64 key) { return m_cache.object(key); }
538
539 static QGLTextureCache *instance();
540 static void deleteIfEmpty();
541 static void imageCleanupHook(qint64 cacheKey);
542 static void cleanupTextures(QPixmapData* pixmap);
543 static void cleanupBeforePixmapDestruction(QPixmapData* pixmap);
544
545private:
546 QCache<qint64, QGLTexture> m_cache;
547};
548
549
550extern Q_OPENGL_EXPORT QPaintEngine* qt_qgl_paint_engine();
551
552bool qt_gl_preferGL2Engine();
553
554inline GLenum qt_gl_preferredTextureFormat()
555{
556 return (QGLExtensions::glExtensions() & QGLExtensions::BGRATextureFormat) && QSysInfo::ByteOrder == QSysInfo::LittleEndian
557 ? GL_BGRA : GL_RGBA;
558}
559
560inline GLenum qt_gl_preferredTextureTarget()
561{
562#if defined(QT_OPENGL_ES_2)
563 return GL_TEXTURE_2D;
564#else
565 return (QGLExtensions::glExtensions() & QGLExtensions::TextureRectangle)
566 && !qt_gl_preferGL2Engine()
567 ? GL_TEXTURE_RECTANGLE_NV
568 : GL_TEXTURE_2D;
569#endif
570}
571
572// One resource per group of shared contexts.
573class Q_AUTOTEST_EXPORT QGLContextResource
574{
575public:
576 typedef void (*FreeFunc)(void *);
577 QGLContextResource(FreeFunc f);
578 ~QGLContextResource();
579 // Set resource 'value' for 'key' and all its shared contexts.
580 void insert(const QGLContext *key, void *value);
581 // Return resource for 'key' or a shared context.
582 void *value(const QGLContext *key);
583 // Cleanup 'value' in response to a context group being destroyed.
584 void cleanup(const QGLContext *ctx, void *value);
585private:
586 FreeFunc free;
587 QAtomicInt active;
588};
589
590// Put a guard around a GL object identifier and its context.
591// When the context goes away, a shared context will be used
592// in its place. If there are no more shared contexts, then
593// the identifier is returned as zero - it is assumed that the
594// context destruction cleaned up the identifier in this case.
595class Q_OPENGL_EXPORT QGLSharedResourceGuard
596{
597public:
598 QGLSharedResourceGuard(const QGLContext *context)
599 : m_group(0), m_id(0), m_next(0), m_prev(0)
600 {
601 setContext(context);
602 }
603 QGLSharedResourceGuard(const QGLContext *context, GLuint id)
604 : m_group(0), m_id(id), m_next(0), m_prev(0)
605 {
606 setContext(context);
607 }
608 ~QGLSharedResourceGuard();
609
610 const QGLContext *context() const
611 {
612 return m_group ? m_group->context() : 0;
613 }
614
615 void setContext(const QGLContext *context);
616
617 GLuint id() const
618 {
619 return m_id;
620 }
621
622 void setId(GLuint id)
623 {
624 m_id = id;
625 }
626
627private:
628 QGLContextGroup *m_group;
629 GLuint m_id;
630 QGLSharedResourceGuard *m_next;
631 QGLSharedResourceGuard *m_prev;
632
633 friend class QGLContextGroup;
634};
635
636
637// This class can be used to match GL extensions without doing any mallocs. The
638// class assumes that the GL extension string ends with a space character,
639// which it should do on all conformant platforms. Create the object and pass
640// in a pointer to the extension string, then call match() on each extension
641// that should be matched. The match() function takes the extension name
642// *without* the terminating space character as input.
643
644class QGLExtensionMatcher
645{
646public:
647 QGLExtensionMatcher(const char *str)
648 : gl_extensions(str), gl_extensions_length(qstrlen(str))
649 {}
650
651 bool match(const char *str) {
652 int str_length = qstrlen(str);
653 const char *extensions = gl_extensions;
654 int extensions_length = gl_extensions_length;
655
656 while (1) {
657 // the total length that needs to be matched is the str_length +
658 // the space character that terminates the extension name
659 if (extensions_length < str_length + 1)
660 return false;
661 if (qstrncmp(extensions, str, str_length) == 0 && extensions[str_length] == ' ')
662 return true;
663
664 int split_pos = 0;
665 while (split_pos < extensions_length && extensions[split_pos] != ' ')
666 ++split_pos;
667 ++split_pos; // added for the terminating space character
668 extensions += split_pos;
669 extensions_length -= split_pos;
670 }
671 return false;
672 }
673
674private:
675 const char *gl_extensions;
676 int gl_extensions_length;
677};
678
679QT_END_NAMESPACE
680
681#endif // QGL_P_H
Note: See TracBrowser for help on using the repository browser.