source: trunk/src/opengl/qgl.cpp@ 754

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

trunk: Merged in qt 4.6.2 sources.

File size: 161.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#include "qapplication.h"
43#include "qplatformdefs.h"
44#include "qgl.h"
45#include <qdebug.h>
46
47#if defined(Q_WS_X11)
48#include "private/qt_x11_p.h"
49#include "private/qpixmap_x11_p.h"
50#define INT32 dummy_INT32
51#define INT8 dummy_INT8
52#if !defined(QT_OPENGL_ES)
53# include <GL/glx.h>
54#endif
55#undef INT32
56#undef INT8
57#include "qx11info_x11.h"
58#elif defined(Q_WS_MAC)
59# include <private/qt_mac_p.h>
60#endif
61
62#include <qdatetime.h>
63
64#include <stdlib.h> // malloc
65
66#include "qpixmap.h"
67#include "qimage.h"
68#include "qgl_p.h"
69
70#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL)
71#include "gl2paintengineex/qpaintengineex_opengl2_p.h"
72#endif
73
74#ifndef QT_OPENGL_ES_2
75#include <private/qpaintengine_opengl_p.h>
76#endif
77
78#ifdef Q_WS_QWS
79#include <private/qglwindowsurface_qws_p.h>
80#endif
81
82#include <qglpixelbuffer.h>
83#include <qglframebufferobject.h>
84
85#include <private/qimage_p.h>
86#include <private/qpixmapdata_p.h>
87#include <private/qpixmapdata_gl_p.h>
88#include <private/qglpixelbuffer_p.h>
89#include <private/qwindowsurface_gl_p.h>
90#include <private/qimagepixmapcleanuphooks_p.h>
91#include "qcolormap.h"
92#include "qfile.h"
93#include "qlibrary.h"
94
95
96QT_BEGIN_NAMESPACE
97
98#ifdef QT_OPENGL_ES_1_CL
99#include "qgl_cl_p.h"
100#endif
101
102
103#if defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QWS)
104QGLExtensionFuncs QGLContextPrivate::qt_extensionFuncs;
105#endif
106
107struct QGLThreadContext {
108 QGLContext *context;
109};
110
111static QThreadStorage<QGLThreadContext *> qgl_context_storage;
112
113Q_GLOBAL_STATIC(QGLFormat, qgl_default_format)
114
115class QGLDefaultOverlayFormat: public QGLFormat
116{
117public:
118 inline QGLDefaultOverlayFormat()
119 {
120 setOption(QGL::FormatOption(0xffff << 16)); // turn off all options
121 setOption(QGL::DirectRendering);
122 setPlane(1);
123 }
124};
125Q_GLOBAL_STATIC(QGLDefaultOverlayFormat, defaultOverlayFormatInstance)
126
127Q_GLOBAL_STATIC(QGLSignalProxy, theSignalProxy)
128QGLSignalProxy *QGLSignalProxy::instance()
129{
130 return theSignalProxy();
131}
132
133
134class QGLEngineSelector
135{
136public:
137 QGLEngineSelector() : engineType(QPaintEngine::MaxUser)
138 {
139 }
140
141 void setPreferredPaintEngine(QPaintEngine::Type type) {
142 if (type == QPaintEngine::OpenGL || type == QPaintEngine::OpenGL2)
143 engineType = type;
144 }
145
146 QPaintEngine::Type preferredPaintEngine() {
147#ifdef Q_WS_MAC
148 // The ATI X1600 driver for Mac OS X does not support return
149 // values from functions in GLSL. Since working around this in
150 // the GL2 engine would require a big, ugly rewrite, we're
151 // falling back to the GL 1 engine..
152 static bool mac_x1600_check_done = false;
153 if (!mac_x1600_check_done) {
154 QGLTemporaryContext *tmp = 0;
155 if (!QGLContext::currentContext())
156 tmp = new QGLTemporaryContext();
157 if (strstr((char *) glGetString(GL_RENDERER), "X1600"))
158 engineType = QPaintEngine::OpenGL;
159 if (tmp)
160 delete tmp;
161 mac_x1600_check_done = true;
162 }
163#endif
164 if (engineType == QPaintEngine::MaxUser) {
165 // No user-set engine - use the defaults
166#if defined(QT_OPENGL_ES_2)
167 engineType = QPaintEngine::OpenGL2;
168#else
169 // We can't do this in the constructor for this object because it
170 // needs to be called *before* the QApplication constructor.
171 // Also check for the FragmentShader extension in conjunction with
172 // the 2.0 version flag, to cover the case where we export the display
173 // from an old GL 1.1 server to a GL 2.x client. In that case we can't
174 // use GL 2.0.
175 if ((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_2_0)
176 && (QGLExtensions::glExtensions() & QGLExtensions::FragmentShader)
177 && qgetenv("QT_GL_USE_OPENGL1ENGINE").isEmpty())
178 engineType = QPaintEngine::OpenGL2;
179 else
180 engineType = QPaintEngine::OpenGL;
181#endif
182 }
183 return engineType;
184 }
185
186private:
187 QPaintEngine::Type engineType;
188};
189
190Q_GLOBAL_STATIC(QGLEngineSelector, qgl_engine_selector)
191
192
193bool qt_gl_preferGL2Engine()
194{
195 return qgl_engine_selector()->preferredPaintEngine() == QPaintEngine::OpenGL2;
196}
197
198
199/*!
200 \namespace QGL
201 \inmodule QtOpenGL
202
203 \brief The QGL namespace specifies miscellaneous identifiers used
204 in the Qt OpenGL module.
205
206 \ingroup painting-3D
207*/
208
209/*!
210 \enum QGL::FormatOption
211
212 This enum specifies the format options that can be used to configure an OpenGL
213 context. These are set using QGLFormat::setOption().
214
215 \value DoubleBuffer Specifies the use of double buffering.
216 \value DepthBuffer Enables the use of a depth buffer.
217 \value Rgba Specifies that the context should use RGBA as its pixel format.
218 \value AlphaChannel Enables the use of an alpha channel.
219 \value AccumBuffer Enables the use of an accumulation buffer.
220 \value StencilBuffer Enables the use of a stencil buffer.
221 \value StereoBuffers Enables the use of a stereo buffers for use with visualization hardware.
222 \value DirectRendering Specifies that the context is used for direct rendering to a display.
223 \value HasOverlay Enables the use of an overlay.
224 \value SampleBuffers Enables the use of sample buffers.
225 \value SingleBuffer Specifies the use of a single buffer, as opposed to double buffers.
226 \value NoDepthBuffer Disables the use of a depth buffer.
227 \value ColorIndex Specifies that the context should use a color index as its pixel format.
228 \value NoAlphaChannel Disables the use of an alpha channel.
229 \value NoAccumBuffer Disables the use of an accumulation buffer.
230 \value NoStencilBuffer Disables the use of a stencil buffer.
231 \value NoStereoBuffers Disables the use of stereo buffers.
232 \value IndirectRendering Specifies that the context is used for indirect rendering to a buffer.
233 \value NoOverlay Disables the use of an overlay.
234 \value NoSampleBuffers Disables the use of sample buffers.
235
236 \sa {Sample Buffers Example}
237*/
238
239/*!
240 \fn void QGL::setPreferredPaintEngine(QPaintEngine::Type engineType)
241
242 \since 4.6
243
244 Sets the preferred OpenGL paint engine that is used to draw onto
245 QGLWidget, QGLPixelBuffer and QGLFramebufferObject targets with QPainter
246 in Qt.
247
248 The \a engineType parameter specifies which of the GL engines to
249 use. Only \c QPaintEngine::OpenGL and \c QPaintEngine::OpenGL2 are
250 valid parameters to this function. All other values are ignored.
251
252 By default, the \c QPaintEngine::OpenGL2 engine is used if GL/GLES
253 version 2.0 is available, otherwise \c QPaintEngine::OpenGL is
254 used.
255
256 \warning This function must be called before the QApplication
257 constructor is called.
258*/
259void QGL::setPreferredPaintEngine(QPaintEngine::Type engineType)
260{
261 qgl_engine_selector()->setPreferredPaintEngine(engineType);
262}
263
264
265/*****************************************************************************
266 QGLFormat implementation
267 *****************************************************************************/
268
269
270/*!
271 \class QGLFormat
272 \brief The QGLFormat class specifies the display format of an OpenGL
273 rendering context.
274
275 \ingroup painting-3D
276
277 A display format has several characteristics:
278 \list
279 \i \link setDoubleBuffer() Double or single buffering.\endlink
280 \i \link setDepth() Depth buffer.\endlink
281 \i \link setRgba() RGBA or color index mode.\endlink
282 \i \link setAlpha() Alpha channel.\endlink
283 \i \link setAccum() Accumulation buffer.\endlink
284 \i \link setStencil() Stencil buffer.\endlink
285 \i \link setStereo() Stereo buffers.\endlink
286 \i \link setDirectRendering() Direct rendering.\endlink
287 \i \link setOverlay() Presence of an overlay.\endlink
288 \i \link setPlane() Plane of an overlay.\endlink
289 \i \link setSampleBuffers() Multisample buffers.\endlink
290 \endlist
291
292 You can also specify preferred bit depths for the color buffer,
293 depth buffer, alpha buffer, accumulation buffer and the stencil
294 buffer with the functions: setRedBufferSize(), setGreenBufferSize(),
295 setBlueBufferSize(), setDepthBufferSize(), setAlphaBufferSize(),
296 setAccumBufferSize() and setStencilBufferSize().
297
298 Note that even if you specify that you prefer a 32 bit depth
299 buffer (e.g. with setDepthBufferSize(32)), the format that is
300 chosen may not have a 32 bit depth buffer, even if there is a
301 format available with a 32 bit depth buffer. The main reason for
302 this is how the system dependant picking algorithms work on the
303 different platforms, and some format options may have higher
304 precedence than others.
305
306 You create and tell a QGLFormat object what rendering options you
307 want from an OpenGL rendering context.
308
309 OpenGL drivers or accelerated hardware may or may not support
310 advanced features such as alpha channel or stereographic viewing.
311 If you request some features that the driver/hardware does not
312 provide when you create a QGLWidget, you will get a rendering
313 context with the nearest subset of features.
314
315 There are different ways to define the display characteristics of
316 a rendering context. One is to create a QGLFormat and make it the
317 default for the entire application:
318 \snippet doc/src/snippets/code/src_opengl_qgl.cpp 0
319
320 Or you can specify the desired format when creating an object of
321 your QGLWidget subclass:
322 \snippet doc/src/snippets/code/src_opengl_qgl.cpp 1
323
324 After the widget has been created, you can find out which of the
325 requested features the system was able to provide:
326 \snippet doc/src/snippets/code/src_opengl_qgl.cpp 2
327
328 \legalese
329 OpenGL is a trademark of Silicon Graphics, Inc. in the
330 United States and other countries.
331 \endlegalese
332
333 \sa QGLContext, QGLWidget
334*/
335
336#ifndef QT_OPENGL_ES
337
338static inline void transform_point(GLdouble out[4], const GLdouble m[16], const GLdouble in[4])
339{
340#define M(row,col) m[col*4+row]
341 out[0] =
342 M(0, 0) * in[0] + M(0, 1) * in[1] + M(0, 2) * in[2] + M(0, 3) * in[3];
343 out[1] =
344 M(1, 0) * in[0] + M(1, 1) * in[1] + M(1, 2) * in[2] + M(1, 3) * in[3];
345 out[2] =
346 M(2, 0) * in[0] + M(2, 1) * in[1] + M(2, 2) * in[2] + M(2, 3) * in[3];
347 out[3] =
348 M(3, 0) * in[0] + M(3, 1) * in[1] + M(3, 2) * in[2] + M(3, 3) * in[3];
349#undef M
350}
351
352static inline GLint qgluProject(GLdouble objx, GLdouble objy, GLdouble objz,
353 const GLdouble model[16], const GLdouble proj[16],
354 const GLint viewport[4],
355 GLdouble * winx, GLdouble * winy, GLdouble * winz)
356{
357 GLdouble in[4], out[4];
358
359 in[0] = objx;
360 in[1] = objy;
361 in[2] = objz;
362 in[3] = 1.0;
363 transform_point(out, model, in);
364 transform_point(in, proj, out);
365
366 if (in[3] == 0.0)
367 return GL_FALSE;
368
369 in[0] /= in[3];
370 in[1] /= in[3];
371 in[2] /= in[3];
372
373 *winx = viewport[0] + (1 + in[0]) * viewport[2] / 2;
374 *winy = viewport[1] + (1 + in[1]) * viewport[3] / 2;
375
376 *winz = (1 + in[2]) / 2;
377 return GL_TRUE;
378}
379
380#endif // !QT_OPENGL_ES
381
382/*!
383 Constructs a QGLFormat object with the following default settings:
384 \list
385 \i \link setDoubleBuffer() Double buffer:\endlink Enabled.
386 \i \link setDepth() Depth buffer:\endlink Enabled.
387 \i \link setRgba() RGBA:\endlink Enabled (i.e., color index disabled).
388 \i \link setAlpha() Alpha channel:\endlink Disabled.
389 \i \link setAccum() Accumulator buffer:\endlink Disabled.
390 \i \link setStencil() Stencil buffer:\endlink Enabled.
391 \i \link setStereo() Stereo:\endlink Disabled.
392 \i \link setDirectRendering() Direct rendering:\endlink Enabled.
393 \i \link setOverlay() Overlay:\endlink Disabled.
394 \i \link setPlane() Plane:\endlink 0 (i.e., normal plane).
395 \i \link setSampleBuffers() Multisample buffers:\endlink Disabled.
396 \endlist
397*/
398
399QGLFormat::QGLFormat()
400{
401 d = new QGLFormatPrivate;
402}
403
404
405/*!
406 Creates a QGLFormat object that is a copy of the current
407 defaultFormat().
408
409 If \a options is not 0, the default format is modified by the
410 specified format options. The \a options parameter should be
411 QGL::FormatOption values OR'ed together.
412
413 This constructor makes it easy to specify a certain desired format
414 in classes derived from QGLWidget, for example:
415 \snippet doc/src/snippets/code/src_opengl_qgl.cpp 3
416
417 Note that there are QGL::FormatOption values to turn format settings
418 both on and off, e.g. QGL::DepthBuffer and QGL::NoDepthBuffer,
419 QGL::DirectRendering and QGL::IndirectRendering, etc.
420
421 The \a plane parameter defaults to 0 and is the plane which this
422 format should be associated with. Not all OpenGL implementations
423 supports overlay/underlay rendering planes.
424
425 \sa defaultFormat(), setOption(), setPlane()
426*/
427
428QGLFormat::QGLFormat(QGL::FormatOptions options, int plane)
429{
430 d = new QGLFormatPrivate;
431 QGL::FormatOptions newOpts = options;
432 d->opts = defaultFormat().d->opts;
433 d->opts |= (newOpts & 0xffff);
434 d->opts &= ~(newOpts >> 16);
435 d->pln = plane;
436}
437
438/*!
439 \internal
440*/
441void QGLFormat::detach()
442{
443 if (d->ref != 1) {
444 QGLFormatPrivate *newd = new QGLFormatPrivate(d);
445 if (!d->ref.deref())
446 delete d;
447 d = newd;
448 }
449}
450
451/*!
452 Constructs a copy of \a other.
453*/
454
455QGLFormat::QGLFormat(const QGLFormat &other)
456{
457 d = other.d;
458 d->ref.ref();
459}
460
461/*!
462 Assigns \a other to this object.
463*/
464
465QGLFormat &QGLFormat::operator=(const QGLFormat &other)
466{
467 if (d != other.d) {
468 other.d->ref.ref();
469 if (!d->ref.deref())
470 delete d;
471 d = other.d;
472 }
473 return *this;
474}
475
476/*!
477 Destroys the QGLFormat.
478*/
479QGLFormat::~QGLFormat()
480{
481 if (!d->ref.deref())
482 delete d;
483}
484
485/*!
486 \fn bool QGLFormat::doubleBuffer() const
487
488 Returns true if double buffering is enabled; otherwise returns
489 false. Double buffering is enabled by default.
490
491 \sa setDoubleBuffer()
492*/
493
494/*!
495 If \a enable is true sets double buffering; otherwise sets single
496 buffering.
497
498 Double buffering is enabled by default.
499
500 Double buffering is a technique where graphics are rendered on an
501 off-screen buffer and not directly to the screen. When the drawing
502 has been completed, the program calls a swapBuffers() function to
503 exchange the screen contents with the buffer. The result is
504 flicker-free drawing and often better performance.
505
506 \sa doubleBuffer(), QGLContext::swapBuffers(),
507 QGLWidget::swapBuffers()
508*/
509
510void QGLFormat::setDoubleBuffer(bool enable)
511{
512 setOption(enable ? QGL::DoubleBuffer : QGL::SingleBuffer);
513}
514
515
516/*!
517 \fn bool QGLFormat::depth() const
518
519 Returns true if the depth buffer is enabled; otherwise returns
520 false. The depth buffer is enabled by default.
521
522 \sa setDepth(), setDepthBufferSize()
523*/
524
525/*!
526 If \a enable is true enables the depth buffer; otherwise disables
527 the depth buffer.
528
529 The depth buffer is enabled by default.
530
531 The purpose of a depth buffer (or Z-buffering) is to remove hidden
532 surfaces. Pixels are assigned Z values based on the distance to
533 the viewer. A pixel with a high Z value is closer to the viewer
534 than a pixel with a low Z value. This information is used to
535 decide whether to draw a pixel or not.
536
537 \sa depth(), setDepthBufferSize()
538*/
539
540void QGLFormat::setDepth(bool enable)
541{
542 setOption(enable ? QGL::DepthBuffer : QGL::NoDepthBuffer);
543}
544
545
546/*!
547 \fn bool QGLFormat::rgba() const
548
549 Returns true if RGBA color mode is set. Returns false if color
550 index mode is set. The default color mode is RGBA.
551
552 \sa setRgba()
553*/
554
555/*!
556 If \a enable is true sets RGBA mode. If \a enable is false sets
557 color index mode.
558
559 The default color mode is RGBA.
560
561 RGBA is the preferred mode for most OpenGL applications. In RGBA
562 color mode you specify colors as red + green + blue + alpha
563 quadruplets.
564
565 In color index mode you specify an index into a color lookup
566 table.
567
568 \sa rgba()
569*/
570
571void QGLFormat::setRgba(bool enable)
572{
573 setOption(enable ? QGL::Rgba : QGL::ColorIndex);
574}
575
576
577/*!
578 \fn bool QGLFormat::alpha() const
579
580 Returns true if the alpha buffer in the framebuffer is enabled;
581 otherwise returns false. The alpha buffer is disabled by default.
582
583 \sa setAlpha(), setAlphaBufferSize()
584*/
585
586/*!
587 If \a enable is true enables the alpha buffer; otherwise disables
588 the alpha buffer.
589
590 The alpha buffer is disabled by default.
591
592 The alpha buffer is typically used for implementing transparency
593 or translucency. The A in RGBA specifies the transparency of a
594 pixel.
595
596 \sa alpha(), setAlphaBufferSize()
597*/
598
599void QGLFormat::setAlpha(bool enable)
600{
601 setOption(enable ? QGL::AlphaChannel : QGL::NoAlphaChannel);
602}
603
604
605/*!
606 \fn bool QGLFormat::accum() const
607
608 Returns true if the accumulation buffer is enabled; otherwise
609 returns false. The accumulation buffer is disabled by default.
610
611 \sa setAccum(), setAccumBufferSize()
612*/
613
614/*!
615 If \a enable is true enables the accumulation buffer; otherwise
616 disables the accumulation buffer.
617
618 The accumulation buffer is disabled by default.
619
620 The accumulation buffer is used to create blur effects and
621 multiple exposures.
622
623 \sa accum(), setAccumBufferSize()
624*/
625
626void QGLFormat::setAccum(bool enable)
627{
628 setOption(enable ? QGL::AccumBuffer : QGL::NoAccumBuffer);
629}
630
631
632/*!
633 \fn bool QGLFormat::stencil() const
634
635 Returns true if the stencil buffer is enabled; otherwise returns
636 false. The stencil buffer is enabled by default.
637
638 \sa setStencil(), setStencilBufferSize()
639*/
640
641/*!
642 If \a enable is true enables the stencil buffer; otherwise
643 disables the stencil buffer.
644
645 The stencil buffer is enabled by default.
646
647 The stencil buffer masks certain parts of the drawing area so that
648 masked parts are not drawn on.
649
650 \sa stencil(), setStencilBufferSize()
651*/
652
653void QGLFormat::setStencil(bool enable)
654{
655 setOption(enable ? QGL::StencilBuffer: QGL::NoStencilBuffer);
656}
657
658
659/*!
660 \fn bool QGLFormat::stereo() const
661
662 Returns true if stereo buffering is enabled; otherwise returns
663 false. Stereo buffering is disabled by default.
664
665 \sa setStereo()
666*/
667
668/*!
669 If \a enable is true enables stereo buffering; otherwise disables
670 stereo buffering.
671
672 Stereo buffering is disabled by default.
673
674 Stereo buffering provides extra color buffers to generate left-eye
675 and right-eye images.
676
677 \sa stereo()
678*/
679
680void QGLFormat::setStereo(bool enable)
681{
682 setOption(enable ? QGL::StereoBuffers : QGL::NoStereoBuffers);
683}
684
685
686/*!
687 \fn bool QGLFormat::directRendering() const
688
689 Returns true if direct rendering is enabled; otherwise returns
690 false.
691
692 Direct rendering is enabled by default.
693
694 \sa setDirectRendering()
695*/
696
697/*!
698 If \a enable is true enables direct rendering; otherwise disables
699 direct rendering.
700
701 Direct rendering is enabled by default.
702
703 Enabling this option will make OpenGL bypass the underlying window
704 system and render directly from hardware to the screen, if this is
705 supported by the system.
706
707 \sa directRendering()
708*/
709
710void QGLFormat::setDirectRendering(bool enable)
711{
712 setOption(enable ? QGL::DirectRendering : QGL::IndirectRendering);
713}
714
715/*!
716 \fn bool QGLFormat::sampleBuffers() const
717
718 Returns true if multisample buffer support is enabled; otherwise
719 returns false.
720
721 The multisample buffer is disabled by default.
722
723 \sa setSampleBuffers()
724*/
725
726/*!
727 If \a enable is true, a GL context with multisample buffer support
728 is picked; otherwise ignored.
729
730 \sa sampleBuffers(), setSamples(), samples()
731*/
732void QGLFormat::setSampleBuffers(bool enable)
733{
734 setOption(enable ? QGL::SampleBuffers : QGL::NoSampleBuffers);
735}
736
737/*!
738 Returns the number of samples per pixel when multisampling is
739 enabled. By default, the highest number of samples that is
740 available is used.
741
742 \sa setSampleBuffers(), sampleBuffers(), setSamples()
743*/
744int QGLFormat::samples() const
745{
746 return d->numSamples;
747}
748
749/*!
750 Set the preferred number of samples per pixel when multisampling
751 is enabled to \a numSamples. By default, the highest number of
752 samples available is used.
753
754 \sa setSampleBuffers(), sampleBuffers(), samples()
755*/
756void QGLFormat::setSamples(int numSamples)
757{
758 detach();
759 if (numSamples < 0) {
760 qWarning("QGLFormat::setSamples: Cannot have negative number of samples per pixel %d", numSamples);
761 return;
762 }
763 d->numSamples = numSamples;
764}
765
766/*!
767 \since 4.2
768
769 Set the preferred swap interval. This can be used to sync the GL
770 drawing into a system window to the vertical refresh of the screen.
771 Setting an \a interval value of 0 will turn the vertical refresh syncing
772 off, any value higher than 0 will turn the vertical syncing on.
773
774 Under Windows and under X11, where the \c{WGL_EXT_swap_control}
775 and \c{GLX_SGI_video_sync} extensions are used, the \a interval
776 parameter can be used to set the minimum number of video frames
777 that are displayed before a buffer swap will occur. In effect,
778 setting the \a interval to 10, means there will be 10 vertical
779 retraces between every buffer swap.
780
781 Under Windows the \c{WGL_EXT_swap_control} extension has to be present,
782 and under X11 the \c{GLX_SGI_video_sync} extension has to be present.
783*/
784void QGLFormat::setSwapInterval(int interval)
785{
786 detach();
787 d->swapInterval = interval;
788}
789
790/*!
791 \since 4.2
792
793 Returns the currently set swap interval. -1 is returned if setting
794 the swap interval isn't supported in the system GL implementation.
795*/
796int QGLFormat::swapInterval() const
797{
798 return d->swapInterval;
799}
800
801/*!
802 \fn bool QGLFormat::hasOverlay() const
803
804 Returns true if overlay plane is enabled; otherwise returns false.
805
806 Overlay is disabled by default.
807
808 \sa setOverlay()
809*/
810
811/*!
812 If \a enable is true enables an overlay plane; otherwise disables
813 the overlay plane.
814
815 Enabling the overlay plane will cause QGLWidget to create an
816 additional context in an overlay plane. See the QGLWidget
817 documentation for further information.
818
819 \sa hasOverlay()
820*/
821
822void QGLFormat::setOverlay(bool enable)
823{
824 setOption(enable ? QGL::HasOverlay : QGL::NoOverlay);
825}
826
827/*!
828 Returns the plane of this format. The default for normal formats
829 is 0, which means the normal plane. The default for overlay
830 formats is 1, which is the first overlay plane.
831
832 \sa setPlane(), defaultOverlayFormat()
833*/
834int QGLFormat::plane() const
835{
836 return d->pln;
837}
838
839/*!
840 Sets the requested plane to \a plane. 0 is the normal plane, 1 is
841 the first overlay plane, 2 is the second overlay plane, etc.; -1,
842 -2, etc. are underlay planes.
843
844 Note that in contrast to other format specifications, the plane
845 specifications will be matched exactly. This means that if you
846 specify a plane that the underlying OpenGL system cannot provide,
847 an \link QGLWidget::isValid() invalid\endlink QGLWidget will be
848 created.
849
850 \sa plane()
851*/
852void QGLFormat::setPlane(int plane)
853{
854 detach();
855 d->pln = plane;
856}
857
858/*!
859 Sets the format option to \a opt.
860
861 \sa testOption()
862*/
863
864void QGLFormat::setOption(QGL::FormatOptions opt)
865{
866 detach();
867 if (opt & 0xffff)
868 d->opts |= opt;
869 else
870 d->opts &= ~(opt >> 16);
871}
872
873
874
875/*!
876 Returns true if format option \a opt is set; otherwise returns false.
877
878 \sa setOption()
879*/
880
881bool QGLFormat::testOption(QGL::FormatOptions opt) const
882{
883 if (opt & 0xffff)
884 return (d->opts & opt) != 0;
885 else
886 return (d->opts & (opt >> 16)) == 0;
887}
888
889/*!
890 Set the minimum depth buffer size to \a size.
891
892 \sa depthBufferSize(), setDepth(), depth()
893*/
894void QGLFormat::setDepthBufferSize(int size)
895{
896 detach();
897 if (size < 0) {
898 qWarning("QGLFormat::setDepthBufferSize: Cannot set negative depth buffer size %d", size);
899 return;
900 }
901 d->depthSize = size;
902}
903
904/*!
905 Returns the depth buffer size.
906
907 \sa depth(), setDepth(), setDepthBufferSize()
908*/
909int QGLFormat::depthBufferSize() const
910{
911 return d->depthSize;
912}
913
914/*!
915 \since 4.2
916
917 Set the preferred red buffer size to \a size.
918
919 \sa setGreenBufferSize(), setBlueBufferSize(), setAlphaBufferSize()
920*/
921void QGLFormat::setRedBufferSize(int size)
922{
923 detach();
924 if (size < 0) {
925 qWarning("QGLFormat::setRedBufferSize: Cannot set negative red buffer size %d", size);
926 return;
927 }
928 d->redSize = size;
929}
930
931/*!
932 \since 4.2
933
934 Returns the red buffer size.
935
936 \sa setRedBufferSize()
937*/
938int QGLFormat::redBufferSize() const
939{
940 return d->redSize;
941}
942
943/*!
944 \since 4.2
945
946 Set the preferred green buffer size to \a size.
947
948 \sa setRedBufferSize(), setBlueBufferSize(), setAlphaBufferSize()
949*/
950void QGLFormat::setGreenBufferSize(int size)
951{
952 detach();
953 if (size < 0) {
954 qWarning("QGLFormat::setGreenBufferSize: Cannot set negative green buffer size %d", size);
955 return;
956 }
957 d->greenSize = size;
958}
959
960/*!
961 \since 4.2
962
963 Returns the green buffer size.
964
965 \sa setGreenBufferSize()
966*/
967int QGLFormat::greenBufferSize() const
968{
969 return d->greenSize;
970}
971
972/*!
973 \since 4.2
974
975 Set the preferred blue buffer size to \a size.
976
977 \sa setRedBufferSize(), setGreenBufferSize(), setAlphaBufferSize()
978*/
979void QGLFormat::setBlueBufferSize(int size)
980{
981 detach();
982 if (size < 0) {
983 qWarning("QGLFormat::setBlueBufferSize: Cannot set negative blue buffer size %d", size);
984 return;
985 }
986 d->blueSize = size;
987}
988
989/*!
990 \since 4.2
991
992 Returns the blue buffer size.
993
994 \sa setBlueBufferSize()
995*/
996int QGLFormat::blueBufferSize() const
997{
998 return d->blueSize;
999}
1000
1001/*!
1002 Set the preferred alpha buffer size to \a size.
1003 This function implicitly enables the alpha channel.
1004
1005 \sa setRedBufferSize(), setGreenBufferSize(), alphaBufferSize()
1006*/
1007void QGLFormat::setAlphaBufferSize(int size)
1008{
1009 detach();
1010 if (size < 0) {
1011 qWarning("QGLFormat::setAlphaBufferSize: Cannot set negative alpha buffer size %d", size);
1012 return;
1013 }
1014 d->alphaSize = size;
1015 setOption(QGL::AlphaChannel);
1016}
1017
1018/*!
1019 Returns the alpha buffer size.
1020
1021 \sa alpha(), setAlpha(), setAlphaBufferSize()
1022*/
1023int QGLFormat::alphaBufferSize() const
1024{
1025 return d->alphaSize;
1026}
1027
1028/*!
1029 Set the preferred accumulation buffer size, where \a size is the
1030 bit depth for each RGBA component.
1031
1032 \sa accum(), setAccum(), accumBufferSize()
1033*/
1034void QGLFormat::setAccumBufferSize(int size)
1035{
1036 detach();
1037 if (size < 0) {
1038 qWarning("QGLFormat::setAccumBufferSize: Cannot set negative accumulate buffer size %d", size);
1039 return;
1040 }
1041 d->accumSize = size;
1042}
1043
1044/*!
1045 Returns the accumulation buffer size.
1046
1047 \sa setAccumBufferSize(), accum(), setAccum()
1048*/
1049int QGLFormat::accumBufferSize() const
1050{
1051 return d->accumSize;
1052}
1053
1054/*!
1055 Set the preferred stencil buffer size to \a size.
1056
1057 \sa stencilBufferSize(), setStencil(), stencil()
1058*/
1059void QGLFormat::setStencilBufferSize(int size)
1060{
1061 detach();
1062 if (size < 0) {
1063 qWarning("QGLFormat::setStencilBufferSize: Cannot set negative stencil buffer size %d", size);
1064 return;
1065 }
1066 d->stencilSize = size;
1067}
1068
1069/*!
1070 Returns the stencil buffer size.
1071
1072 \sa stencil(), setStencil(), setStencilBufferSize()
1073*/
1074int QGLFormat::stencilBufferSize() const
1075{
1076 return d->stencilSize;
1077}
1078
1079/*!
1080 \fn bool QGLFormat::hasOpenGL()
1081
1082 Returns true if the window system has any OpenGL support;
1083 otherwise returns false.
1084
1085 \warning This function must not be called until the QApplication
1086 object has been created.
1087*/
1088
1089
1090
1091/*!
1092 \fn bool QGLFormat::hasOpenGLOverlays()
1093
1094 Returns true if the window system supports OpenGL overlays;
1095 otherwise returns false.
1096
1097 \warning This function must not be called until the QApplication
1098 object has been created.
1099*/
1100
1101QGLFormat::OpenGLVersionFlags Q_AUTOTEST_EXPORT qOpenGLVersionFlagsFromString(const QString &versionString)
1102{
1103 QGLFormat::OpenGLVersionFlags versionFlags = QGLFormat::OpenGL_Version_None;
1104
1105 if (versionString.startsWith(QLatin1String("OpenGL ES"))) {
1106 QStringList parts = versionString.split(QLatin1Char(' '));
1107 if (parts.size() >= 3) {
1108 if (parts[2].startsWith(QLatin1String("1."))) {
1109 if (parts[1].endsWith(QLatin1String("-CM"))) {
1110 versionFlags |= QGLFormat::OpenGL_ES_Common_Version_1_0 |
1111 QGLFormat::OpenGL_ES_CommonLite_Version_1_0;
1112 if (parts[2].startsWith(QLatin1String("1.1")))
1113 versionFlags |= QGLFormat::OpenGL_ES_Common_Version_1_1 |
1114 QGLFormat::OpenGL_ES_CommonLite_Version_1_1;
1115 }
1116 else {
1117 // Not -CM, must be CL, CommonLite
1118 versionFlags |= QGLFormat::OpenGL_ES_CommonLite_Version_1_0;
1119 if (parts[2].startsWith(QLatin1String("1.1")))
1120 versionFlags |= QGLFormat::OpenGL_ES_CommonLite_Version_1_1;
1121 }
1122 }
1123 else {
1124 // OpenGL ES version 2.0 or higher
1125 versionFlags |= QGLFormat::OpenGL_ES_Version_2_0;
1126 }
1127 }
1128 else {
1129 // if < 3 parts to the name, it is an unrecognised OpenGL ES
1130 qWarning("Unrecognised OpenGL ES version");
1131 }
1132 }
1133 else {
1134 // not ES, regular OpenGL, the version numbers are first in the string
1135 if (versionString.startsWith(QLatin1String("1."))) {
1136 switch (versionString[2].toAscii()) {
1137 case '5':
1138 versionFlags |= QGLFormat::OpenGL_Version_1_5;
1139 case '4':
1140 versionFlags |= QGLFormat::OpenGL_Version_1_4;
1141 case '3':
1142 versionFlags |= QGLFormat::OpenGL_Version_1_3;
1143 case '2':
1144 versionFlags |= QGLFormat::OpenGL_Version_1_2;
1145 case '1':
1146 versionFlags |= QGLFormat::OpenGL_Version_1_1;
1147 default:
1148 break;
1149 }
1150 }
1151 else if (versionString.startsWith(QLatin1String("2."))) {
1152 versionFlags |= QGLFormat::OpenGL_Version_1_1 |
1153 QGLFormat::OpenGL_Version_1_2 |
1154 QGLFormat::OpenGL_Version_1_3 |
1155 QGLFormat::OpenGL_Version_1_4 |
1156 QGLFormat::OpenGL_Version_1_5 |
1157 QGLFormat::OpenGL_Version_2_0;
1158 QString minorVersion = versionString.section(QLatin1Char(' '), 0, 0).section(QLatin1Char('.'), 1, 1);
1159 if (minorVersion == QChar(QLatin1Char('1')))
1160 versionFlags |= QGLFormat::OpenGL_Version_2_1;
1161 }
1162 else if (versionString.startsWith(QLatin1String("3."))) {
1163 versionFlags |= QGLFormat::OpenGL_Version_1_1 |
1164 QGLFormat::OpenGL_Version_1_2 |
1165 QGLFormat::OpenGL_Version_1_3 |
1166 QGLFormat::OpenGL_Version_1_4 |
1167 QGLFormat::OpenGL_Version_1_5 |
1168 QGLFormat::OpenGL_Version_2_0 |
1169 QGLFormat::OpenGL_Version_2_1 |
1170 QGLFormat::OpenGL_Version_3_0;
1171 }
1172 else
1173 qWarning("Unrecognised OpenGL version");
1174 }
1175 return versionFlags;
1176}
1177
1178/*!
1179 \enum QGLFormat::OpenGLVersionFlag
1180 \since 4.2
1181
1182 This enum describes the various OpenGL versions that are
1183 recognized by Qt. Use the QGLFormat::openGLVersionFlags() function
1184 to identify which versions that are supported at runtime.
1185
1186 \value OpenGL_Version_None If no OpenGL is present or if no OpenGL context is current.
1187
1188 \value OpenGL_Version_1_1 OpenGL version 1.1 or higher is present.
1189
1190 \value OpenGL_Version_1_2 OpenGL version 1.2 or higher is present.
1191
1192 \value OpenGL_Version_1_3 OpenGL version 1.3 or higher is present.
1193
1194 \value OpenGL_Version_1_4 OpenGL version 1.4 or higher is present.
1195
1196 \value OpenGL_Version_1_5 OpenGL version 1.5 or higher is present.
1197
1198 \value OpenGL_Version_2_0 OpenGL version 2.0 or higher is present.
1199 Note that version 2.0 supports all the functionality of version 1.5.
1200
1201 \value OpenGL_Version_2_1 OpenGL version 2.1 or higher is present.
1202
1203 \value OpenGL_Version_3_0 OpenGL version 3.0 or higher is present.
1204
1205 \value OpenGL_ES_CommonLite_Version_1_0 OpenGL ES version 1.0 Common Lite or higher is present.
1206
1207 \value OpenGL_ES_Common_Version_1_0 OpenGL ES version 1.0 Common or higher is present.
1208 The Common profile supports all the features of Common Lite.
1209
1210 \value OpenGL_ES_CommonLite_Version_1_1 OpenGL ES version 1.1 Common Lite or higher is present.
1211
1212 \value OpenGL_ES_Common_Version_1_1 OpenGL ES version 1.1 Common or higher is present.
1213 The Common profile supports all the features of Common Lite.
1214
1215 \value OpenGL_ES_Version_2_0 OpenGL ES version 2.0 or higher is present.
1216 Note that OpenGL ES version 2.0 does not support all the features of OpenGL ES 1.x.
1217 So if OpenGL_ES_Version_2_0 is returned, none of the ES 1.x flags are returned.
1218
1219 See also \l{http://www.opengl.org} for more information about the different
1220 revisions of OpenGL.
1221
1222 \sa openGLVersionFlags()
1223*/
1224
1225/*!
1226 \since 4.2
1227
1228 Identifies, at runtime, which OpenGL versions that are supported
1229 by the current platform.
1230
1231 Note that if OpenGL version 1.5 is supported, its predecessors
1232 (i.e., version 1.4 and lower) are also supported. To identify the
1233 support of a particular feature, like multi texturing, test for
1234 the version in which the feature was first introduced (i.e.,
1235 version 1.3 in the case of multi texturing) to adapt to the largest
1236 possible group of runtime platforms.
1237
1238 This function needs a valid current OpenGL context to work;
1239 otherwise it will return OpenGL_Version_None.
1240
1241 \sa hasOpenGL(), hasOpenGLOverlays()
1242*/
1243QGLFormat::OpenGLVersionFlags QGLFormat::openGLVersionFlags()
1244{
1245 static bool cachedDefault = false;
1246 static OpenGLVersionFlags defaultVersionFlags = OpenGL_Version_None;
1247 QGLContext *currentCtx = const_cast<QGLContext *>(QGLContext::currentContext());
1248 QGLTemporaryContext *tmpContext = 0;
1249
1250 if (currentCtx && currentCtx->d_func()->version_flags_cached)
1251 return currentCtx->d_func()->version_flags;
1252
1253 if (!currentCtx) {
1254 if (cachedDefault) {
1255 return defaultVersionFlags;
1256 } else {
1257 if (!hasOpenGL())
1258 return defaultVersionFlags;
1259 tmpContext = new QGLTemporaryContext;
1260 cachedDefault = true;
1261 }
1262 }
1263
1264 QString versionString(QLatin1String(reinterpret_cast<const char*>(glGetString(GL_VERSION))));
1265 OpenGLVersionFlags versionFlags = qOpenGLVersionFlagsFromString(versionString);
1266 if (currentCtx) {
1267 currentCtx->d_func()->version_flags_cached = true;
1268 currentCtx->d_func()->version_flags = versionFlags;
1269 }
1270 if (tmpContext) {
1271 defaultVersionFlags = versionFlags;
1272 delete tmpContext;
1273 }
1274
1275 return versionFlags;
1276}
1277
1278
1279/*!
1280 Returns the default QGLFormat for the application. All QGLWidget
1281 objects that are created use this format unless another format is
1282 specified, e.g. when they are constructed.
1283
1284 If no special default format has been set using
1285 setDefaultFormat(), the default format is the same as that created
1286 with QGLFormat().
1287
1288 \sa setDefaultFormat()
1289*/
1290
1291QGLFormat QGLFormat::defaultFormat()
1292{
1293 return *qgl_default_format();
1294}
1295
1296/*!
1297 Sets a new default QGLFormat for the application to \a f. For
1298 example, to set single buffering as the default instead of double
1299 buffering, your main() might contain code like this:
1300 \snippet doc/src/snippets/code/src_opengl_qgl.cpp 4
1301
1302 \sa defaultFormat()
1303*/
1304
1305void QGLFormat::setDefaultFormat(const QGLFormat &f)
1306{
1307 *qgl_default_format() = f;
1308}
1309
1310
1311/*!
1312 Returns the default QGLFormat for overlay contexts.
1313
1314 The default overlay format is:
1315 \list
1316 \i \link setDoubleBuffer() Double buffer:\endlink Disabled.
1317 \i \link setDepth() Depth buffer:\endlink Disabled.
1318 \i \link setRgba() RGBA:\endlink Disabled (i.e., color index enabled).
1319 \i \link setAlpha() Alpha channel:\endlink Disabled.
1320 \i \link setAccum() Accumulator buffer:\endlink Disabled.
1321 \i \link setStencil() Stencil buffer:\endlink Disabled.
1322 \i \link setStereo() Stereo:\endlink Disabled.
1323 \i \link setDirectRendering() Direct rendering:\endlink Enabled.
1324 \i \link setOverlay() Overlay:\endlink Disabled.
1325 \i \link setSampleBuffers() Multisample buffers:\endlink Disabled.
1326 \i \link setPlane() Plane:\endlink 1 (i.e., first overlay plane).
1327 \endlist
1328
1329 \sa setDefaultFormat()
1330*/
1331
1332QGLFormat QGLFormat::defaultOverlayFormat()
1333{
1334 return *defaultOverlayFormatInstance();
1335}
1336
1337/*!
1338 Sets a new default QGLFormat for overlay contexts to \a f. This
1339 format is used whenever a QGLWidget is created with a format that
1340 hasOverlay() enabled.
1341
1342 For example, to get a double buffered overlay context (if
1343 available), use code like this:
1344
1345 \snippet doc/src/snippets/code/src_opengl_qgl.cpp 5
1346
1347 As usual, you can find out after widget creation whether the
1348 underlying OpenGL system was able to provide the requested
1349 specification:
1350
1351 \snippet doc/src/snippets/code/src_opengl_qgl.cpp 6
1352
1353 \sa defaultOverlayFormat()
1354*/
1355
1356void QGLFormat::setDefaultOverlayFormat(const QGLFormat &f)
1357{
1358 QGLFormat *defaultFormat = defaultOverlayFormatInstance();
1359 *defaultFormat = f;
1360 // Make sure the user doesn't request that the overlays themselves
1361 // have overlays, since it is unlikely that the system supports
1362 // infinitely many planes...
1363 defaultFormat->setOverlay(false);
1364}
1365
1366
1367/*!
1368 Returns true if all the options of the two QGLFormat objects
1369 \a a and \a b are equal; otherwise returns false.
1370
1371 \relates QGLFormat
1372*/
1373
1374bool operator==(const QGLFormat& a, const QGLFormat& b)
1375{
1376 return (int) a.d->opts == (int) b.d->opts && a.d->pln == b.d->pln && a.d->alphaSize == b.d->alphaSize
1377 && a.d->accumSize == b.d->accumSize && a.d->stencilSize == b.d->stencilSize
1378 && a.d->depthSize == b.d->depthSize
1379 && a.d->redSize == b.d->redSize
1380 && a.d->greenSize == b.d->greenSize
1381 && a.d->blueSize == b.d->blueSize
1382 && a.d->numSamples == b.d->numSamples
1383 && a.d->swapInterval == b.d->swapInterval;
1384}
1385
1386
1387/*!
1388 Returns false if all the options of the two QGLFormat objects
1389 \a a and \a b are equal; otherwise returns true.
1390
1391 \relates QGLFormat
1392*/
1393
1394bool operator!=(const QGLFormat& a, const QGLFormat& b)
1395{
1396 return !(a == b);
1397}
1398
1399/*****************************************************************************
1400 QGLContext implementation
1401 *****************************************************************************/
1402
1403QGLContextGroup::~QGLContextGroup()
1404{
1405 // Clear any remaining QGLSharedResourceGuard objects on the group.
1406 QGLSharedResourceGuard *guard = m_guards;
1407 while (guard != 0) {
1408 guard->m_group = 0;
1409 guard->m_id = 0;
1410 guard = guard->m_next;
1411 }
1412}
1413
1414void QGLContextGroup::addGuard(QGLSharedResourceGuard *guard)
1415{
1416 if (m_guards)
1417 m_guards->m_prev = guard;
1418 guard->m_next = m_guards;
1419 guard->m_prev = 0;
1420 m_guards = guard;
1421}
1422
1423void QGLContextGroup::removeGuard(QGLSharedResourceGuard *guard)
1424{
1425 if (guard->m_next)
1426 guard->m_next->m_prev = guard->m_prev;
1427 if (guard->m_prev)
1428 guard->m_prev->m_next = guard->m_next;
1429 else
1430 m_guards = guard->m_next;
1431}
1432
1433const QGLContext *qt_gl_transfer_context(const QGLContext *ctx)
1434{
1435 if (!ctx)
1436 return 0;
1437 QList<const QGLContext *> shares
1438 (QGLContextPrivate::contextGroup(ctx)->shares());
1439 if (shares.size() >= 2)
1440 return (ctx == shares.at(0)) ? shares.at(1) : shares.at(0);
1441 else
1442 return 0;
1443}
1444
1445QGLContextPrivate::~QGLContextPrivate()
1446{
1447 if (!group->m_refs.deref()) {
1448 Q_ASSERT(group->context() == q_ptr);
1449 delete group;
1450 }
1451}
1452
1453void QGLContextPrivate::init(QPaintDevice *dev, const QGLFormat &format)
1454{
1455 Q_Q(QGLContext);
1456 glFormat = reqFormat = format;
1457 valid = false;
1458 q->setDevice(dev);
1459#if defined(Q_WS_X11)
1460 pbuf = 0;
1461 gpm = 0;
1462 vi = 0;
1463 screen = QX11Info::appScreen();
1464#endif
1465#if defined(Q_WS_WIN)
1466 dc = 0;
1467 win = 0;
1468 pixelFormatId = 0;
1469 cmap = 0;
1470 hbitmap = 0;
1471 hbitmap_hdc = 0;
1472#endif
1473#if defined(Q_WS_MAC)
1474# ifndef QT_MAC_USE_COCOA
1475 update = false;
1476# endif
1477 vi = 0;
1478#endif
1479#if defined(QT_OPENGL_ES)
1480 eglContext = 0;
1481 eglSurface = EGL_NO_SURFACE;
1482#endif
1483 fbo = 0;
1484 crWin = false;
1485 initDone = false;
1486 sharing = false;
1487 max_texture_size = -1;
1488 version_flags_cached = false;
1489 version_flags = QGLFormat::OpenGL_Version_None;
1490 extension_flags_cached = false;
1491 extension_flags = 0;
1492 current_fbo = 0;
1493 default_fbo = 0;
1494 active_engine = 0;
1495 for (int i = 0; i < QT_GL_VERTEX_ARRAY_TRACKED_COUNT; ++i)
1496 vertexAttributeArraysEnabledState[i] = false;
1497}
1498
1499QGLContext* QGLContext::currentCtx = 0;
1500
1501/*
1502 Read back the contents of the currently bound framebuffer, used in
1503 QGLWidget::grabFrameBuffer(), QGLPixelbuffer::toImage() and
1504 QGLFramebufferObject::toImage()
1505*/
1506
1507static void convertFromGLImage(QImage &img, int w, int h, bool alpha_format, bool include_alpha)
1508{
1509 if (QSysInfo::ByteOrder == QSysInfo::BigEndian) {
1510 // OpenGL gives RGBA; Qt wants ARGB
1511 uint *p = (uint*)img.bits();
1512 uint *end = p + w*h;
1513 if (alpha_format && include_alpha) {
1514 while (p < end) {
1515 uint a = *p << 24;
1516 *p = (*p >> 8) | a;
1517 p++;
1518 }
1519 } else {
1520 // This is an old legacy fix for PowerPC based Macs, which
1521 // we shouldn't remove
1522 while (p < end) {
1523 *p = 0xff000000 | (*p>>8);
1524 ++p;
1525 }
1526 }
1527 } else {
1528 // OpenGL gives ABGR (i.e. RGBA backwards); Qt wants ARGB
1529 for (int y = 0; y < h; y++) {
1530 uint *q = (uint*)img.scanLine(y);
1531 for (int x=0; x < w; ++x) {
1532 const uint pixel = *q;
1533 *q = ((pixel << 16) & 0xff0000) | ((pixel >> 16) & 0xff) | (pixel & 0xff00ff00);
1534 q++;
1535 }
1536 }
1537
1538 }
1539 img = img.mirrored();
1540}
1541
1542QImage qt_gl_read_framebuffer(const QSize &size, bool alpha_format, bool include_alpha)
1543{
1544 QImage img(size, alpha_format ? QImage::Format_ARGB32 : QImage::Format_RGB32);
1545 int w = size.width();
1546 int h = size.height();
1547 glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, img.bits());
1548 convertFromGLImage(img, w, h, alpha_format, include_alpha);
1549 return img;
1550}
1551
1552QImage qt_gl_read_texture(const QSize &size, bool alpha_format, bool include_alpha)
1553{
1554 QImage img(size, alpha_format ? QImage::Format_ARGB32_Premultiplied : QImage::Format_RGB32);
1555 int w = size.width();
1556 int h = size.height();
1557#if !defined(QT_OPENGL_ES_2) && !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL)
1558 //### glGetTexImage not in GL ES 2.0, need to do something else here!
1559 glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, img.bits());
1560#endif
1561 convertFromGLImage(img, w, h, alpha_format, include_alpha);
1562 return img;
1563}
1564
1565// returns the highest number closest to v, which is a power of 2
1566// NB! assumes 32 bit ints
1567int qt_next_power_of_two(int v)
1568{
1569 v--;
1570 v |= v >> 1;
1571 v |= v >> 2;
1572 v |= v >> 4;
1573 v |= v >> 8;
1574 v |= v >> 16;
1575 ++v;
1576 return v;
1577}
1578
1579typedef void (*_qt_pixmap_cleanup_hook_64)(qint64);
1580typedef void (*_qt_image_cleanup_hook_64)(qint64);
1581
1582extern Q_GUI_EXPORT _qt_pixmap_cleanup_hook_64 qt_pixmap_cleanup_hook_64;
1583extern Q_GUI_EXPORT _qt_image_cleanup_hook_64 qt_image_cleanup_hook_64;
1584
1585static QGLTextureCache *qt_gl_texture_cache = 0;
1586
1587QGLTextureCache::QGLTextureCache()
1588 : m_cache(64*1024) // cache ~64 MB worth of textures - this is not accurate though
1589{
1590 Q_ASSERT(qt_gl_texture_cache == 0);
1591 qt_gl_texture_cache = this;
1592
1593 QImagePixmapCleanupHooks::instance()->addPixmapDataModificationHook(cleanupTextures);
1594 QImagePixmapCleanupHooks::instance()->addPixmapDataDestructionHook(cleanupBeforePixmapDestruction);
1595 QImagePixmapCleanupHooks::instance()->addImageHook(imageCleanupHook);
1596}
1597
1598QGLTextureCache::~QGLTextureCache()
1599{
1600 qt_gl_texture_cache = 0;
1601
1602 QImagePixmapCleanupHooks::instance()->removePixmapDataModificationHook(cleanupTextures);
1603 QImagePixmapCleanupHooks::instance()->removePixmapDataDestructionHook(cleanupBeforePixmapDestruction);
1604 QImagePixmapCleanupHooks::instance()->removeImageHook(imageCleanupHook);
1605}
1606
1607void QGLTextureCache::insert(QGLContext* ctx, qint64 key, QGLTexture* texture, int cost)
1608{
1609 if (m_cache.totalCost() + cost > m_cache.maxCost()) {
1610 // the cache is full - make an attempt to remove something
1611 const QList<qint64> keys = m_cache.keys();
1612 int i = 0;
1613 while (i < m_cache.count()
1614 && (m_cache.totalCost() + cost > m_cache.maxCost())) {
1615 QGLTexture *tex = m_cache.object(keys.at(i));
1616 if (tex->context == ctx)
1617 m_cache.remove(keys.at(i));
1618 ++i;
1619 }
1620 }
1621 m_cache.insert(key, texture, cost);
1622}
1623
1624bool QGLTextureCache::remove(QGLContext* ctx, GLuint textureId)
1625{
1626 QList<qint64> keys = m_cache.keys();
1627 for (int i = 0; i < keys.size(); ++i) {
1628 QGLTexture *tex = m_cache.object(keys.at(i));
1629 if (tex->id == textureId && tex->context == ctx) {
1630 tex->options |= QGLContext::MemoryManagedBindOption; // forces a glDeleteTextures() call
1631 m_cache.remove(keys.at(i));
1632 return true;
1633 }
1634 }
1635 return false;
1636}
1637
1638void QGLTextureCache::removeContextTextures(QGLContext* ctx)
1639{
1640 QList<qint64> keys = m_cache.keys();
1641 for (int i = 0; i < keys.size(); ++i) {
1642 const qint64 &key = keys.at(i);
1643 if (m_cache.object(key)->context == ctx)
1644 m_cache.remove(key);
1645 }
1646}
1647
1648QGLTextureCache* QGLTextureCache::instance()
1649{
1650 if (!qt_gl_texture_cache)
1651 qt_gl_texture_cache = new QGLTextureCache;
1652
1653 return qt_gl_texture_cache;
1654}
1655
1656/*
1657 a hook that removes textures from the cache when a pixmap/image
1658 is deref'ed
1659*/
1660void QGLTextureCache::imageCleanupHook(qint64 cacheKey)
1661{
1662 // ### remove when the GL texture cache becomes thread-safe
1663 if (qApp->thread() != QThread::currentThread())
1664 return;
1665 QGLTexture *texture = instance()->getTexture(cacheKey);
1666 if (texture && texture->options & QGLContext::MemoryManagedBindOption)
1667 instance()->remove(cacheKey);
1668}
1669
1670
1671void QGLTextureCache::cleanupTextures(QPixmapData* pmd)
1672{
1673 // ### remove when the GL texture cache becomes thread-safe
1674 if (qApp->thread() == QThread::currentThread()) {
1675 const qint64 cacheKey = pmd->cacheKey();
1676 QGLTexture *texture = instance()->getTexture(cacheKey);
1677 if (texture && texture->options & QGLContext::MemoryManagedBindOption)
1678 instance()->remove(cacheKey);
1679 }
1680}
1681
1682void QGLTextureCache::cleanupBeforePixmapDestruction(QPixmapData* pmd)
1683{
1684 // Remove any bound textures first:
1685 cleanupTextures(pmd);
1686 Q_ASSERT(instance()->getTexture(pmd->cacheKey()) == 0);
1687
1688#if defined(Q_WS_X11)
1689 if (pmd->classId() == QPixmapData::X11Class) {
1690 Q_ASSERT(pmd->ref == 0); // Make sure reference counting isn't broken
1691 QGLContextPrivate::destroyGlSurfaceForPixmap(pmd);
1692 }
1693#endif
1694}
1695
1696void QGLTextureCache::deleteIfEmpty()
1697{
1698 if (instance()->size() == 0)
1699 delete instance();
1700}
1701
1702// DDS format structure
1703struct DDSFormat {
1704 quint32 dwSize;
1705 quint32 dwFlags;
1706 quint32 dwHeight;
1707 quint32 dwWidth;
1708 quint32 dwLinearSize;
1709 quint32 dummy1;
1710 quint32 dwMipMapCount;
1711 quint32 dummy2[11];
1712 struct {
1713 quint32 dummy3[2];
1714 quint32 dwFourCC;
1715 quint32 dummy4[5];
1716 } ddsPixelFormat;
1717};
1718
1719// compressed texture pixel formats
1720#define FOURCC_DXT1 0x31545844
1721#define FOURCC_DXT2 0x32545844
1722#define FOURCC_DXT3 0x33545844
1723#define FOURCC_DXT4 0x34545844
1724#define FOURCC_DXT5 0x35545844
1725
1726#ifndef GL_COMPRESSED_RGB_S3TC_DXT1_EXT
1727#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0
1728#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1
1729#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2
1730#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3
1731#endif
1732
1733#ifndef GL_GENERATE_MIPMAP_SGIS
1734#define GL_GENERATE_MIPMAP_SGIS 0x8191
1735#define GL_GENERATE_MIPMAP_HINT_SGIS 0x8192
1736#endif
1737
1738/*!
1739 \class QGLContext
1740 \brief The QGLContext class encapsulates an OpenGL rendering context.
1741
1742 \ingroup painting-3D
1743
1744 An OpenGL rendering context is a complete set of OpenGL state
1745 variables. The rendering context's \l {QGL::FormatOption} {format}
1746 is set in the constructor, but it can also be set later with
1747 setFormat(). The format options that are actually set are returned
1748 by format(); the options you asked for are returned by
1749 requestedFormat(). Note that after a QGLContext object has been
1750 constructed, the actual OpenGL context must be created by
1751 explicitly calling the \link create() create()\endlink
1752 function. The makeCurrent() function makes this context the
1753 current rendering context. You can make \e no context current
1754 using doneCurrent(). The reset() function will reset the context
1755 and make it invalid.
1756
1757 You can examine properties of the context with, e.g. isValid(),
1758 isSharing(), initialized(), windowCreated() and
1759 overlayTransparentColor().
1760
1761 If you're using double buffering you can swap the screen contents
1762 with the off-screen buffer using swapBuffers().
1763
1764 Please note that QGLContext is not thread safe.
1765*/
1766
1767/*!
1768 \enum QGLContext::BindOption
1769 \since 4.6
1770
1771 A set of options to decide how to bind a texture using bindTexture().
1772
1773 \value NoBindOption Don't do anything, pass the texture straight
1774 through.
1775
1776 \value InvertedYBindOption Specifies that the texture should be flipped
1777 over the X axis so that the texture coordinate 0,0 corresponds to
1778 the top left corner. Inverting the texture implies a deep copy
1779 prior to upload.
1780
1781 \value MipmapBindOption Specifies that bindTexture() should try
1782 to generate mipmaps. If the GL implementation supports the \c
1783 GL_SGIS_generate_mipmap extension, mipmaps will be automatically
1784 generated for the texture. Mipmap generation is only supported for
1785 the \c GL_TEXTURE_2D target.
1786
1787 \value PremultipliedAlphaBindOption Specifies that the image should be
1788 uploaded with premultiplied alpha and does a conversion accordingly.
1789
1790 \value LinearFilteringBindOption Specifies that the texture filtering
1791 should be set to GL_LINEAR. Default is GL_NEAREST. If mipmap is
1792 also enabled, filtering will be set to GL_LINEAR_MIPMAP_LINEAR.
1793
1794 \value DefaultBindOption In Qt 4.5 and earlier, bindTexture()
1795 would mirror the image and automatically generate mipmaps. This
1796 option helps preserve this default behavior.
1797
1798 \omitvalue CanFlipNativePixmapBindOption Used by x11 from pixmap to choose
1799 wether or not it can bind the pixmap upside down or not.
1800
1801 \omitvalue MemoryManagedBindOption Used by paint engines to
1802 indicate that the pixmap should be memory managed along side with
1803 the pixmap/image that it stems from, e.g. installing destruction
1804 hooks in them.
1805
1806 \omitvalue InternalBindOption
1807*/
1808
1809/*!
1810 \obsolete
1811
1812 Constructs an OpenGL context for the given paint \a device, which
1813 can be a widget or a pixmap. The \a format specifies several
1814 display options for the context.
1815
1816 If the underlying OpenGL/Window system cannot satisfy all the
1817 features requested in \a format, the nearest subset of features
1818 will be used. After creation, the format() method will return the
1819 actual format obtained.
1820
1821 Note that after a QGLContext object has been constructed, \l
1822 create() must be called explicitly to create the actual OpenGL
1823 context. The context will be \l {isValid()}{invalid} if it was not
1824 possible to obtain a GL context at all.
1825*/