PageRenderTime 97ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/src/threed/painting/qglpainter.cpp

https://bitbucket.org/manctl/qt3d
C++ | 2366 lines | 1308 code | 148 blank | 910 comment | 222 complexity | ec43ac14b87db2d542b2b8f4bf4379f7 MD5 | raw file
Possible License(s): CC-BY-SA-4.0, LGPL-2.1, GPL-3.0, AGPL-3.0, LGPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. /****************************************************************************
  2. **
  3. ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
  4. ** Contact: http://www.qt-project.org/
  5. **
  6. ** This file is part of the Qt3D module of the Qt Toolkit.
  7. **
  8. ** $QT_BEGIN_LICENSE:LGPL$
  9. ** GNU Lesser General Public License Usage
  10. ** This file may be used under the terms of the GNU Lesser General Public
  11. ** License version 2.1 as published by the Free Software Foundation and
  12. ** appearing in the file LICENSE.LGPL included in the packaging of this
  13. ** file. Please review the following information to ensure the GNU Lesser
  14. ** General Public License version 2.1 requirements will be met:
  15. ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
  16. **
  17. ** In addition, as a special exception, Nokia gives you certain additional
  18. ** rights. These rights are described in the Nokia Qt LGPL Exception
  19. ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
  20. **
  21. ** GNU General Public License Usage
  22. ** Alternatively, this file may be used under the terms of the GNU General
  23. ** Public License version 3.0 as published by the Free Software Foundation
  24. ** and appearing in the file LICENSE.GPL included in the packaging of this
  25. ** file. Please review the following information to ensure the GNU General
  26. ** Public License version 3.0 requirements will be met:
  27. ** http://www.gnu.org/copyleft/gpl.html.
  28. **
  29. ** Other Usage
  30. ** Alternatively, this file may be used in accordance with the terms and
  31. ** conditions contained in a signed written agreement between you and Nokia.
  32. **
  33. **
  34. **
  35. **
  36. **
  37. **
  38. ** $QT_END_LICENSE$
  39. **
  40. ****************************************************************************/
  41. #include "qglpainter.h"
  42. #include "qglpainter_p.h"
  43. #include "qglabstracteffect.h"
  44. #include "qglext_p.h"
  45. #include <QOpenGLContext>
  46. #include <QOpenGLShaderProgram>
  47. #include <QOpenGLFramebufferObject>
  48. #include <QPainter>
  49. #include <QPaintEngine>
  50. #include <QVarLengthArray>
  51. #include <QMap>
  52. #include <QDebug>
  53. #if !defined(QT_NO_THREAD)
  54. #include <QThreadStorage>
  55. #include <QThread>
  56. #endif
  57. #include "qglflatcoloreffect_p.h"
  58. #include "qglflattextureeffect_p.h"
  59. #include "qgllitmaterialeffect_p.h"
  60. #include "qgllittextureeffect_p.h"
  61. #include "qglpickcolors_p.h"
  62. #include "qgltexture2d.h"
  63. #include "qgltexturecube.h"
  64. #include "qgeometrydata.h"
  65. #include "qglvertexbundle_p.h"
  66. #include "qmatrix4x4stack_p.h"
  67. #include "qglwindowsurface.h"
  68. #include "qglpaintersurface_p.h"
  69. #undef glActiveTexture
  70. QT_BEGIN_NAMESPACE
  71. /*!
  72. \class QGLPainter
  73. \brief The QGLPainter class provides portable API's for rendering into a GL context.
  74. \since 4.8
  75. \ingroup qt3d
  76. \ingroup qt3d::painting
  77. TBD - lots of TBD
  78. All QGLPainter instances on a context share the same context state:
  79. matrices, effects, vertex attributes, etc. For example, calling
  80. ortho() on one QGLPainter instance for a context will alter the
  81. projectionMatrix() as seen by the other QGLPainter instances.
  82. */
  83. /*!
  84. \enum QGLPainter::Update
  85. This enum defines the values that were changed since the last QGLPainter::update().
  86. \value UpdateColor The color has been updated.
  87. \value UpdateModelViewMatrix The modelview matrix has been updated.
  88. \value UpdateProjectionMatrix The projection matrix has been updated.
  89. \value UpdateMatrices The combination of UpdateModelViewMatrix and
  90. UpdateProjectionMatrix.
  91. \value UpdateLights The lights have been updated.
  92. \value UpdateMaterials The material parameters have been updated.
  93. \value UpdateViewport The viewport needs to be updated because the
  94. drawing surface has changed.
  95. \value UpdateAll All values have been updated. This is specified
  96. when an effect is activated.
  97. */
  98. #define QGLPAINTER_CHECK_PRIVATE() \
  99. Q_ASSERT_X(d, "QGLPainter", "begin() has not been called or it failed")
  100. QGLPainterPrivate::QGLPainterPrivate()
  101. : ref(1),
  102. badShaderCount(0),
  103. eye(QGL::NoEye),
  104. lightModel(0),
  105. defaultLightModel(0),
  106. defaultLight(0),
  107. frontMaterial(0),
  108. backMaterial(0),
  109. defaultMaterial(0),
  110. frontColorMaterial(0),
  111. backColorMaterial(0),
  112. viewingCube(QVector3D(-1, -1, -1), QVector3D(1, 1, 1)),
  113. color(255, 255, 255, 255),
  114. updates(QGLPainter::UpdateAll),
  115. pick(0),
  116. boundVertexBuffer(0),
  117. boundIndexBuffer(0),
  118. renderSequencer(0),
  119. isFixedFunction(true) // Updated by QGLPainter::begin()
  120. {
  121. context = 0;
  122. effect = 0;
  123. userEffect = 0;
  124. standardEffect = QGL::FlatColor;
  125. memset(stdeffects, 0, sizeof(stdeffects));
  126. }
  127. QGLPainterPrivate::~QGLPainterPrivate()
  128. {
  129. delete defaultLightModel;
  130. delete defaultLight;
  131. delete defaultMaterial;
  132. delete frontColorMaterial;
  133. delete backColorMaterial;
  134. for (int effect = 0; effect < QGL_MAX_STD_EFFECTS; ++effect)
  135. delete stdeffects[effect];
  136. delete pick;
  137. qDeleteAll(cachedPrograms);
  138. delete renderSequencer;
  139. }
  140. QGLPainterPickPrivate::QGLPainterPickPrivate()
  141. {
  142. isPicking = false;
  143. objectPickId = -1;
  144. pickColorIndex = -1;
  145. pickColor = 0;
  146. defaultPickEffect = new QGLFlatColorEffect();
  147. }
  148. QGLPainterPickPrivate::~QGLPainterPickPrivate()
  149. {
  150. delete defaultPickEffect;
  151. }
  152. #if !defined(QT_NO_THREAD)
  153. // QOpenGLContext's are thread-specific, so QGLPainterPrivateCache should be too.
  154. typedef QThreadStorage<QGLPainterPrivateCache *> QGLPainterPrivateStorage;
  155. Q_GLOBAL_STATIC(QGLPainterPrivateStorage, painterPrivateStorage)
  156. static QGLPainterPrivateCache *painterPrivateCache()
  157. {
  158. QGLPainterPrivateCache *cache = painterPrivateStorage()->localData();
  159. if (!cache) {
  160. cache = new QGLPainterPrivateCache();
  161. painterPrivateStorage()->setLocalData(cache);
  162. }
  163. return cache;
  164. }
  165. #else
  166. Q_GLOBAL_STATIC(QGLPainterPrivateCache, painterPrivateCache)
  167. #endif
  168. QGLPainterPrivateCache::QGLPainterPrivateCache()
  169. {
  170. }
  171. QGLPainterPrivateCache::~QGLPainterPrivateCache()
  172. {
  173. }
  174. QGLPainterPrivate *QGLPainterPrivateCache::fromContext(QOpenGLContext *context)
  175. {
  176. QGLPainterPrivate *priv = cache.value(context, 0);
  177. if (priv)
  178. return priv;
  179. #ifndef QT_NO_THREAD
  180. Q_ASSERT_X(context->thread() == QThread::currentThread(),
  181. Q_FUNC_INFO,
  182. "Attempt to fetch painter state for context outside contexts thread");
  183. #endif
  184. // since we assert this is the same thread then this is bound to be a direct
  185. // connection, not a queued (asynchronous) connection
  186. connect(context, SIGNAL(destroyed()), this, SLOT(contextDestroyed()));
  187. priv = new QGLPainterPrivate();
  188. priv->context = context;
  189. cache.insert(context, priv);
  190. return priv;
  191. }
  192. QGLPainterPrivateCache *QGLPainterPrivateCache::instance()
  193. {
  194. return painterPrivateCache();
  195. }
  196. void QGLPainterPrivateCache::contextDestroyed()
  197. {
  198. QOpenGLContext *context = qobject_cast<QOpenGLContext *>(sender());
  199. QGLPainterPrivate *priv = cache.value(context, 0);
  200. if (priv) {
  201. priv->context = 0;
  202. cache.remove(context);
  203. if (!priv->ref.deref())
  204. delete priv;
  205. }
  206. emit destroyedContext(context);
  207. }
  208. /*!
  209. Constructs a new GL painter. Call begin() to attach the
  210. painter to a GL context.
  211. \sa begin()
  212. */
  213. QGLPainter::QGLPainter()
  214. : d_ptr(0)
  215. {
  216. }
  217. /*!
  218. Constructs a new GL painter and attaches it to \a context.
  219. It is not necessary to call begin() after construction.
  220. \sa begin()
  221. */
  222. QGLPainter::QGLPainter(QOpenGLContext *context)
  223. : d_ptr(0)
  224. {
  225. begin(context);
  226. }
  227. /*!
  228. Constructs a new GL painter and attaches it to the GL
  229. context associated with \a window. It is not necessary to
  230. call begin() after construction.
  231. \sa begin(), isActive()
  232. */
  233. QGLPainter::QGLPainter(QWindow *window)
  234. : d_ptr(0)
  235. {
  236. begin(window);
  237. }
  238. /*!
  239. Constructs a new GL painter and attaches it to the GL context associated
  240. with \a painter. It is assumed that \a painter is the currently
  241. active painter and that it is associated with the current GL context.
  242. If \a painter is not using an OpenGL paint engine, then isActive()
  243. will return false; true otherwise.
  244. This constructor is typically used when mixing regular Qt painting
  245. operations and GL painting operations on a widget that is being
  246. drawn using the OpenGL graphics system.
  247. \sa begin(), isActive()
  248. */
  249. QGLPainter::QGLPainter(QPainter *painter)
  250. : d_ptr(0)
  251. {
  252. begin(painter);
  253. }
  254. /*!
  255. Constructs a new GL painter and attaches it to the GL context associated
  256. with \a surface.
  257. \sa begin(), isActive()
  258. */
  259. QGLPainter::QGLPainter(QGLAbstractSurface *surface)
  260. : d_ptr(0)
  261. {
  262. begin(surface);
  263. }
  264. /*!
  265. Destroys this GL painter.
  266. */
  267. QGLPainter::~QGLPainter()
  268. {
  269. end();
  270. }
  271. /*!
  272. Begins painting on the current GL context. Returns false
  273. if there is no GL context current.
  274. \sa end()
  275. */
  276. bool QGLPainter::begin()
  277. {
  278. return begin(QOpenGLContext::currentContext());
  279. }
  280. /*!
  281. Begins painting on \a context. If painting was already in progress,
  282. then this function will call end() first. The \a context will be
  283. made current if it is not already current.
  284. Returns true if painting can begin; false otherwise.
  285. All QGLPainter instances on a context share the same context state:
  286. matrices, the effect(), vertex attributes, etc. For example,
  287. calling ortho() on one QGLPainter instance for a context will
  288. alter the projectionMatrix() as seen by the other QGLPainter instances.
  289. \sa end(), isActive()
  290. */
  291. bool QGLPainter::begin(QOpenGLContext *context)
  292. {
  293. if (!context)
  294. return false;
  295. end();
  296. return begin(context, QGLAbstractSurface::createSurfaceForContext(context));
  297. }
  298. /*!
  299. \internal
  300. */
  301. bool QGLPainter::begin
  302. (QOpenGLContext *context, QGLAbstractSurface *surface,
  303. bool destroySurface)
  304. {
  305. // If we don't have a context specified, then use the one
  306. // that the surface just made current.
  307. if (!context)
  308. context = QOpenGLContext::currentContext();
  309. if (!context)
  310. {
  311. qWarning() << "##### Attempt to begin painter with no GL context!";
  312. return false;
  313. }
  314. // Initialize the QOpenGLFunctions parent class.
  315. initializeGLFunctions();
  316. // Determine if the OpenGL implementation is fixed-function or not.
  317. bool isFixedFunction = !hasOpenGLFeature(QOpenGLFunctions::Shaders);
  318. if (!isFixedFunction)
  319. isFixedFunction = !QOpenGLShaderProgram::hasOpenGLShaderPrograms();
  320. if (!isFixedFunction)
  321. {
  322. QOpenGLContext *ctx = QOpenGLContext::currentContext();
  323. QFunctionPointer res = ctx->getProcAddress("glCreateShader");
  324. if (!res)
  325. {
  326. res = ctx->getProcAddress("glCreateShaderObject");
  327. if (!res)
  328. {
  329. res = ctx->getProcAddress("glCreateShaderObjectARB");
  330. }
  331. }
  332. if (!res)
  333. isFixedFunction = !res;
  334. }
  335. // Find the QGLPainterPrivate for the context, or create a new one.
  336. d_ptr = painterPrivateCache()->fromContext(context);
  337. d_ptr->ref.ref();
  338. d_ptr->isFixedFunction = isFixedFunction;
  339. if (d_ptr->renderSequencer)
  340. {
  341. d_ptr->renderSequencer->reset();
  342. d_ptr->renderSequencer->setPainter(this);
  343. }
  344. // Activate the main surface for the context.
  345. QGLAbstractSurface *prevSurface;
  346. if (d_ptr->surfaceStack.isEmpty()) {
  347. prevSurface = 0;
  348. } else {
  349. // We are starting a nested begin()/end() scope, so switch
  350. // to the new main surface rather than activate from scratch.
  351. prevSurface = d_ptr->surfaceStack.last().surface;
  352. prevSurface->deactivate(surface);
  353. }
  354. if (!surface->activate(prevSurface)) {
  355. if (prevSurface)
  356. prevSurface->activate(surface);
  357. if (destroySurface)
  358. delete surface;
  359. if (!d_ptr->ref.deref())
  360. delete d_ptr;
  361. d_ptr = 0;
  362. return false;
  363. }
  364. // Push a main surface descriptor onto the surface stack.
  365. QGLPainterSurfaceInfo psurf;
  366. psurf.surface = surface;
  367. psurf.destroySurface = destroySurface;
  368. psurf.mainSurface = true;
  369. d_ptr->surfaceStack.append(psurf);
  370. // Force the matrices to be updated the first time we use them.
  371. d_ptr->modelViewMatrix.setDirty(true);
  372. d_ptr->projectionMatrix.setDirty(true);
  373. return true;
  374. }
  375. /*!
  376. Begins GL painting on \a widget. Returns false if \a widget is null.
  377. \sa end()
  378. */
  379. bool QGLPainter::begin(QWindow *window)
  380. {
  381. bool result = false;
  382. if (window)
  383. {
  384. end();
  385. result = begin(0, new QGLWindowSurface(window));
  386. }
  387. return result;
  388. }
  389. /*!
  390. Begins painting on the GL context associated with \a painter.
  391. Returns false if \a painter is not using an OpenGL paint engine.
  392. It is assumed that \a painter is the currently active painter
  393. and that it is associated with the current GL context.
  394. This function is typically used when mixing regular Qt painting
  395. operations and GL painting operations on a widget that is being
  396. drawn using the OpenGL graphics system.
  397. \sa end()
  398. */
  399. bool QGLPainter::begin(QPainter *painter)
  400. {
  401. // Validate that the painting is OpenGL-based.
  402. if (!painter)
  403. return false;
  404. QPaintEngine *engine = painter->paintEngine();
  405. if (!engine)
  406. return false;
  407. if (engine->type() != QPaintEngine::OpenGL &&
  408. engine->type() != QPaintEngine::OpenGL2)
  409. return false;
  410. // Begin GL painting operations.
  411. return begin(0, new QGLPainterSurface(painter));
  412. }
  413. /*!
  414. Begins painting to \a surface. Returns false if \a surface is
  415. null or could not be activated.
  416. \sa end(), QGLAbstractSurface::activate()
  417. */
  418. bool QGLPainter::begin(QGLAbstractSurface *surface)
  419. {
  420. if (!surface)
  421. return false;
  422. end();
  423. return begin(0, surface, false);
  424. }
  425. /*!
  426. Ends GL painting. Returns true if painting was ended successfully;
  427. false if this painter was not bound to a GL context.
  428. The GL context that was bound to this painter will not have
  429. QOpenGLContext::doneCurrent() called on it. It is the responsibility
  430. of the caller to terminate context operations.
  431. The effect() will be left active in the GL context and will be
  432. assumed to still be active the next time begin() is called.
  433. If this assumption doesn't apply, then call disableEffect()
  434. to disable the effect before calling end().
  435. This function will pop all surfaces from the surface stack,
  436. and return currentSurface() to null (the default drawing surface).
  437. \sa begin(), isActive(), disableEffect()
  438. */
  439. bool QGLPainter::end()
  440. {
  441. Q_D(QGLPainter);
  442. if (!d)
  443. return false;
  444. // Unbind the current vertex and index buffers.
  445. if (d->boundVertexBuffer) {
  446. QOpenGLBuffer::release(QOpenGLBuffer::VertexBuffer);
  447. d->boundVertexBuffer = 0;
  448. }
  449. if (d->boundIndexBuffer) {
  450. QOpenGLBuffer::release(QOpenGLBuffer::IndexBuffer);
  451. d->boundIndexBuffer = 0;
  452. }
  453. // Pop surfaces from the surface stack until we reach a
  454. // main surface. Then deactivate the main surface.
  455. int size = d->surfaceStack.size();
  456. while (size > 0) {
  457. --size;
  458. QGLPainterSurfaceInfo &surf = d->surfaceStack[size];
  459. if (surf.mainSurface) {
  460. if (size > 0) {
  461. // There are still other surfaces on the stack, probably
  462. // because we are within a nested begin()/end() scope.
  463. // Re-activate the next surface down in the outer scope.
  464. QGLPainterSurfaceInfo &nextSurf = d->surfaceStack[size - 1];
  465. surf.surface->switchTo(nextSurf.surface);
  466. } else {
  467. // Last surface on the stack, so deactivate it permanently.
  468. surf.surface->deactivate();
  469. }
  470. if (surf.destroySurface)
  471. delete surf.surface;
  472. break;
  473. } else if (size > 0) {
  474. surf.surface->deactivate(d->surfaceStack[size - 1].surface);
  475. }
  476. }
  477. d->surfaceStack.resize(size);
  478. // Force a viewport update if we are within a nested begin()/end().
  479. d->updates |= UpdateViewport;
  480. // Destroy the QGLPainterPrivate if this is the last reference.
  481. if (!d->ref.deref())
  482. delete d;
  483. d_ptr = 0;
  484. return true;
  485. }
  486. /*!
  487. Returns true if this painter is currently bound to a GL context;
  488. false otherwise.
  489. \sa begin(), end()
  490. */
  491. bool QGLPainter::isActive() const
  492. {
  493. return (d_ptr != 0 && d_ptr->context != 0);
  494. }
  495. /*!
  496. Returns the GL context that is bound to this painter, or null
  497. if it is not currently bound.
  498. */
  499. QOpenGLContext *QGLPainter::context() const
  500. {
  501. if (d_ptr)
  502. return d_ptr->context;
  503. else
  504. return 0;
  505. }
  506. /*!
  507. Returns true if the underlying OpenGL implementation is OpenGL 1.x
  508. or OpenGL/ES 1.x and only supports fixed-function OpenGL operations.
  509. Returns false if the underlying OpenGL implementation is using
  510. GLSL or GLSL/ES shaders.
  511. If this function returns false, then the built-in effects will
  512. use shaders and QGLPainter will not update the fixed-function
  513. matrices in the OpenGL context when update() is called.
  514. User-supplied effects will need to use shaders also or update
  515. the fixed-function matrices themselves or call updateFixedFunction().
  516. \sa update(), updateFixedFunction()
  517. */
  518. bool QGLPainter::isFixedFunction() const
  519. {
  520. #if defined(QT_OPENGL_ES_2)
  521. return false;
  522. #else
  523. Q_D(const QGLPainter);
  524. if (d)
  525. return d->isFixedFunction;
  526. else
  527. return true;
  528. #endif
  529. }
  530. /*!
  531. Sets the \a color to use to clear the color buffer when \c{glClear()}
  532. is called.
  533. */
  534. void QGLPainter::setClearColor(const QColor& color)
  535. {
  536. glClearColor(color.redF(), color.greenF(), color.blueF(), color.alphaF());
  537. }
  538. /*!
  539. Sets the scissor \a rect for the current drawing surface
  540. to use when \c{GL_SCISSOR_TEST} is enabled. If \a rect is empty,
  541. then the scissor will be set to clip away all drawing.
  542. Note that \a rect is in Qt co-ordinates with the origin
  543. at the top-left of the drawing surface's viewport rectangle.
  544. If the currentSurface() is an instance of QGLSubsurface,
  545. then \a rect will be adjusted relative to the subsurface's position.
  546. \sa currentSurface(), QGLAbstractSurface::viewportGL()
  547. */
  548. void QGLPainter::setScissor(const QRect& rect)
  549. {
  550. if (!rect.isEmpty()) {
  551. // Adjust the rectangle by the position of the surface viewport.
  552. QGLAbstractSurface *surface = currentSurface();
  553. QRect viewport = surface->viewportGL();
  554. QRect r(viewport.x() + rect.x(),
  555. viewport.y() + viewport.height() - (rect.y() + rect.height()),
  556. rect.width(), rect.height());
  557. if (!r.isEmpty())
  558. glScissor(r.x(), r.y(), r.width(), r.height());
  559. else
  560. glScissor(0, 0, 0, 0);
  561. } else {
  562. glScissor(0, 0, 0, 0);
  563. }
  564. }
  565. /*!
  566. Returns a reference to the projection matrix stack.
  567. It is recommended that setCamera() be used to set the projection
  568. matrix at the beginning of a scene rendering pass so that the
  569. eye position can be adjusted for stereo.
  570. \sa modelViewMatrix(), combinedMatrix(), setCamera()
  571. */
  572. QMatrix4x4Stack& QGLPainter::projectionMatrix()
  573. {
  574. Q_D(QGLPainter);
  575. QGLPAINTER_CHECK_PRIVATE();
  576. return d->projectionMatrix;
  577. }
  578. /*!
  579. Returns a reference to the modelview matrix stack.
  580. \sa projectionMatrix(), combinedMatrix(), normalMatrix(), setCamera()
  581. \sa worldMatrix()
  582. */
  583. QMatrix4x4Stack& QGLPainter::modelViewMatrix()
  584. {
  585. Q_D(QGLPainter);
  586. QGLPAINTER_CHECK_PRIVATE();
  587. return d->modelViewMatrix;
  588. }
  589. /*!
  590. \fn QMatrix4x4 QGLPainter::combinedMatrix() const
  591. Returns the result of multiplying the projectionMatrix()
  592. and the modelViewMatrix(). This combined matrix value is
  593. useful for setting uniform matrix values on shader programs.
  594. Calling this function is more efficient than calling
  595. projectionMatrix() and modelViewMatrix() separately and
  596. multiplying the return values.
  597. \sa projectionMatrix(), modelViewMatrix(), normalMatrix()
  598. */
  599. QMatrix4x4 QGLPainter::combinedMatrix() const
  600. {
  601. const QGLPainterPrivate *d = d_func();
  602. if (!d)
  603. return QMatrix4x4();
  604. const QMatrix4x4StackPrivate *proj = d->projectionMatrix.d_func();
  605. const QMatrix4x4StackPrivate *mv = d->modelViewMatrix.d_func();
  606. return proj->matrix * mv->matrix;
  607. }
  608. // Inverting the eye transformation will often result in values like
  609. // 1.5e-15 in the world matrix. Clamp these to zero to make worldMatrix()
  610. // more stable when removing the eye component of the modelViewMatrix().
  611. static inline qreal qt_gl_stablize_value(qreal value)
  612. {
  613. return (qAbs(value) >= 0.00001f) ? value : 0.0f;
  614. }
  615. static inline QMatrix4x4 qt_gl_stablize_matrix(const QMatrix4x4 &m)
  616. {
  617. return QMatrix4x4(qt_gl_stablize_value(m(0, 0)),
  618. qt_gl_stablize_value(m(0, 1)),
  619. qt_gl_stablize_value(m(0, 2)),
  620. qt_gl_stablize_value(m(0, 3)),
  621. qt_gl_stablize_value(m(1, 0)),
  622. qt_gl_stablize_value(m(1, 1)),
  623. qt_gl_stablize_value(m(1, 2)),
  624. qt_gl_stablize_value(m(1, 3)),
  625. qt_gl_stablize_value(m(2, 0)),
  626. qt_gl_stablize_value(m(2, 1)),
  627. qt_gl_stablize_value(m(2, 2)),
  628. qt_gl_stablize_value(m(2, 3)),
  629. qt_gl_stablize_value(m(3, 0)),
  630. qt_gl_stablize_value(m(3, 1)),
  631. qt_gl_stablize_value(m(3, 2)),
  632. qt_gl_stablize_value(m(3, 3)));
  633. }
  634. /*!
  635. Returns the world matrix, which is the modelViewMatrix() without
  636. the eye transformation that was set in the previous call to
  637. setCamera().
  638. In the following example, the \c{world} variable will be set to the
  639. translation and scale component of the modelview transformation,
  640. without the "look at" component from the camera:
  641. \code
  642. painter.setCamera(camera);
  643. painter.modelViewMatrix().translate(0.0f, 5.0f, 0.0f);
  644. painter.modelViewMatrix().scale(1.5f);
  645. QMatrix4x4 world = painter.worldMatrix();
  646. \endcode
  647. Note: the world matrix is determined by multiplying the inverse of
  648. the camera's look at component with the current modelview matrix.
  649. Thus, the result may not be precisely the same as constructing a
  650. matrix from translate and scale operations starting with the identity.
  651. \sa modelViewMatrix(), setCamera()
  652. */
  653. QMatrix4x4 QGLPainter::worldMatrix() const
  654. {
  655. Q_D(const QGLPainter);
  656. QGLPAINTER_CHECK_PRIVATE();
  657. return qt_gl_stablize_matrix
  658. (d->inverseEyeMatrix * d->modelViewMatrix.top());
  659. }
  660. /*!
  661. \fn QMatrix3x3 QGLPainter::normalMatrix() const
  662. Returns the normal matrix corresponding to modelViewMatrix().
  663. The normal matrix is the transpose of the inverse of the top-left
  664. 3x3 part of the 4x4 modelview matrix. If the 3x3 sub-matrix is not
  665. invertible, this function returns the identity.
  666. \sa modelViewMatrix(), combinedMatrix()
  667. */
  668. QMatrix3x3 QGLPainter::normalMatrix() const
  669. {
  670. const QGLPainterPrivate *d = d_func();
  671. if (!d)
  672. return QMatrix3x3();
  673. const QMatrix4x4StackPrivate *mv = d->modelViewMatrix.d_func();
  674. return mv->matrix.normalMatrix();
  675. }
  676. /*!
  677. Returns the camera eye that is currently being used for stereo
  678. rendering. The default is QGL::NoEye.
  679. The eye is used to adjust the camera position by a small amount
  680. when setCamera() is called.
  681. \sa setEye(), setCamera()
  682. */
  683. QGL::Eye QGLPainter::eye() const
  684. {
  685. Q_D(const QGLPainter);
  686. QGLPAINTER_CHECK_PRIVATE();
  687. return d->eye;
  688. }
  689. /*!
  690. Sets the camera \a eye that is currently being used for stereo
  691. rendering.
  692. The \a eye is used to adjust the camera position by a small amount
  693. when setCamera() is called.
  694. \sa eye(), setCamera()
  695. */
  696. void QGLPainter::setEye(QGL::Eye eye)
  697. {
  698. Q_D(QGLPainter);
  699. QGLPAINTER_CHECK_PRIVATE();
  700. d->eye = eye;
  701. }
  702. /*!
  703. Sets the modelViewMatrix() and projectionMatrix() to the view
  704. defined by \a camera. If eye() is not QGL::NoEye, then the view
  705. will be adjusted for the camera's eye separation.
  706. This function is typically called at the beginning of a scene rendering
  707. pass to initialize the modelview and projection matrices.
  708. Note that this does not cause the painter to take ownership of the camera
  709. and it does not save the pointer value. The \a camera may be safely
  710. deleted after calling this function.
  711. \sa eye(), modelViewMatrix(), projectionMatrix(), worldMatrix()
  712. */
  713. void QGLPainter::setCamera(const QGLCamera *camera)
  714. {
  715. Q_ASSERT(camera);
  716. Q_D(QGLPainter);
  717. QGLPAINTER_CHECK_PRIVATE();
  718. QMatrix4x4 lookAt = camera->modelViewMatrix(d->eye);
  719. d->modelViewMatrix = lookAt;
  720. d->projectionMatrix = camera->projectionMatrix(aspectRatio());
  721. d->inverseEyeMatrix = lookAt.inverted();
  722. }
  723. /*!
  724. Returns true if \a point is outside the current viewing volume.
  725. This is used to perform object culling checks.
  726. */
  727. bool QGLPainter::isCullable(const QVector3D& point) const
  728. {
  729. Q_D(const QGLPainter);
  730. QGLPAINTER_CHECK_PRIVATE();
  731. QVector3D projected = d->modelViewMatrix * point;
  732. projected = d->projectionMatrix * projected;
  733. return !d->viewingCube.contains(projected);
  734. }
  735. static inline uint outcode(const QVector4D &v)
  736. {
  737. // For a discussion of outcodes see pg 388 Dunn & Parberry.
  738. // For why you can't just test if the point is in a bounding box
  739. // consider the case where a view frustum with view-size 1.5 x 1.5
  740. // is tested against a 2x2 box which encloses the near-plane, while
  741. // all the points in the box are outside the frustum.
  742. // TODO: optimise this with assembler - according to D&P this can
  743. // be done in one line of assembler on some platforms
  744. uint code = 0;
  745. if (v.x() < -v.w()) code |= 0x01;
  746. if (v.x() > v.w()) code |= 0x02;
  747. if (v.y() < -v.w()) code |= 0x04;
  748. if (v.y() > v.w()) code |= 0x08;
  749. if (v.z() < -v.w()) code |= 0x10;
  750. if (v.z() > v.w()) code |= 0x20;
  751. return code;
  752. }
  753. /*!
  754. Returns true if \a box is completely outside the current viewing volume.
  755. This is used to perform object culling checks.
  756. */
  757. bool QGLPainter::isCullable(const QBox3D& box) const
  758. {
  759. Q_D(const QGLPainter);
  760. QGLPAINTER_CHECK_PRIVATE();
  761. // This function uses the technique of view frustum culling known as
  762. // clip space testing. Since the normal QVector3D representation
  763. // of the points throws away the w value needed, we convert the box
  764. // into a set of 8 points represented as QVector4D's and then apply
  765. // the test. The test is to transform the points into clip space
  766. // by applying the MV and Proj matrices, then test to see if the 4D
  767. // points are outside the clip space by testing x, y & z against w.
  768. QArray<QVector4D> box4d;
  769. QVector3D n = box.minimum();
  770. QVector3D x = box.maximum();
  771. box4d.append(QVector4D(n.x(), n.y(), x.z(), 1), QVector4D(x.x(), n.y(), x.z(), 1),
  772. QVector4D(x.x(), x.y(), x.z(), 1), QVector4D(n.x(), x.y(), x.z(), 1));
  773. box4d.append(QVector4D(n.x(), n.y(), n.z(), 1), QVector4D(x.x(), n.y(), n.z(), 1),
  774. QVector4D(x.x(), x.y(), n.z(), 1), QVector4D(n.x(), x.y(), n.z(), 1));
  775. QMatrix4x4 mvp = d->projectionMatrix.top() * d->modelViewMatrix.top();
  776. for (int i = 0; i < box4d.size(); ++i)
  777. {
  778. box4d[i] = mvp * box4d.at(i);
  779. }
  780. // if the logical AND of all the outcodes is non-zero then the BB is
  781. // definitely outside the view frustum.
  782. uint out = 0xff;
  783. for (int i = 0; i < box4d.size(); ++i)
  784. {
  785. out = out & outcode(box4d.at(i));
  786. }
  787. return out;
  788. }
  789. /*!
  790. Returns the current render order sequencer.
  791. \sa QGLRenderSequencer
  792. */
  793. QGLRenderSequencer *QGLPainter::renderSequencer()
  794. {
  795. Q_D(QGLPainter);
  796. if (!d->renderSequencer)
  797. d->renderSequencer = new QGLRenderSequencer(this);
  798. return d->renderSequencer;
  799. }
  800. /*!
  801. Returns the aspect ratio of the viewport for adjusting projection
  802. transformations.
  803. */
  804. qreal QGLPainter::aspectRatio() const
  805. {
  806. return currentSurface()->aspectRatio();
  807. }
  808. /*!
  809. Returns the current effect that is in use, which is userEffect()
  810. if it is not null, or the effect object associated with
  811. standardEffect() otherwise.
  812. If isPicking() is true, then this will return the effect object
  813. that is being used to generate pick colors.
  814. \sa userEffect(), standardEffect(), isPicking()
  815. */
  816. QGLAbstractEffect *QGLPainter::effect() const
  817. {
  818. Q_D(QGLPainter);
  819. QGLPAINTER_CHECK_PRIVATE();
  820. d->ensureEffect(const_cast<QGLPainter *>(this));
  821. return d->effect;
  822. }
  823. /*!
  824. Returns the user-defined effect that is being used for drawing
  825. operations, or null if standardEffect() is in use.
  826. \sa setUserEffect(), standardEffect(), effect()
  827. */
  828. QGLAbstractEffect *QGLPainter::userEffect() const
  829. {
  830. Q_D(QGLPainter);
  831. QGLPAINTER_CHECK_PRIVATE();
  832. return d->userEffect;
  833. }
  834. /*!
  835. Sets a user-defined \a effect to use for drawing operations
  836. in the current GL context. If \a effect is null, this will
  837. disable user-defined effects and return to using standardEffect().
  838. \sa effect(), draw(), setStandardEffect()
  839. */
  840. void QGLPainter::setUserEffect(QGLAbstractEffect *effect)
  841. {
  842. Q_D(QGLPainter);
  843. QGLPAINTER_CHECK_PRIVATE();
  844. if (d->userEffect == effect)
  845. return;
  846. if (d->effect)
  847. d->effect->setActive(this, false);
  848. d->userEffect = effect;
  849. if (effect && (!d->pick || !d->pick->isPicking)) {
  850. d->effect = effect;
  851. d->effect->setActive(this, true);
  852. d->updates = UpdateAll;
  853. } else {
  854. // Revert to the effect associated with standardEffect().
  855. d->effect = 0;
  856. d->ensureEffect(this);
  857. }
  858. }
  859. /*!
  860. Returns the standard effect to use for rendering fragments in
  861. the current GL context when userEffect() is null.
  862. \sa setStandardEffect(), userEffect()
  863. */
  864. QGL::StandardEffect QGLPainter::standardEffect() const
  865. {
  866. Q_D(QGLPainter);
  867. QGLPAINTER_CHECK_PRIVATE();
  868. return d->standardEffect;
  869. }
  870. /*!
  871. Sets a standard \a effect to use for rendering fragments
  872. in the current GL context. This will also set userEffect()
  873. to null. If \a effect is an invalid value, then the behavior
  874. of QGL::FlatColor will be used instead.
  875. \sa standardEffect(), setUserEffect()
  876. */
  877. void QGLPainter::setStandardEffect(QGL::StandardEffect effect)
  878. {
  879. Q_D(QGLPainter);
  880. QGLPAINTER_CHECK_PRIVATE();
  881. if (d->standardEffect == effect && d->effect && d->userEffect == 0)
  882. return;
  883. if (d->effect)
  884. d->effect->setActive(this, false);
  885. d->standardEffect = effect;
  886. d->userEffect = 0;
  887. d->effect = 0;
  888. d->ensureEffect(this);
  889. }
  890. /*!
  891. Disables the current effect and sets userEffect() to null.
  892. Unlike setUserEffect() this not activate the standardEffect()
  893. until the next time effect() is called.
  894. This function can be used to disable all effect-based drawing
  895. operations prior to performing raw GL calls. The next time
  896. effect() is called on this QGLPainter, the standardEffect()
  897. will be reactivated. An effect can also be reactivated by
  898. calling setUserEffect() or setStandardEffect().
  899. \sa userEffect(), standardEffect()
  900. */
  901. void QGLPainter::disableEffect()
  902. {
  903. Q_D(QGLPainter);
  904. QGLPAINTER_CHECK_PRIVATE();
  905. if (d->effect)
  906. d->effect->setActive(this, false);
  907. d->userEffect = 0;
  908. d->effect = 0;
  909. }
  910. /*!
  911. Returns the cached shader program associated with \a name; or null
  912. if \a name is not currently associated with a shader program.
  913. \sa setCachedProgram()
  914. */
  915. QOpenGLShaderProgram *QGLPainter::cachedProgram(const QString& name) const
  916. {
  917. Q_D(const QGLPainter);
  918. QGLPAINTER_CHECK_PRIVATE();
  919. return d->cachedPrograms.value(name, 0);
  920. }
  921. /*!
  922. Sets the cached shader \a program associated with \a name.
  923. Effect objects can use this function to store pre-compiled
  924. and pre-linked shader programs in the painter for future
  925. use by the same effect. The \a program will be destroyed
  926. when context() is destroyed.
  927. If \a program is null, then the program associated with \a name
  928. will be destroyed. If \a name is already present as a cached
  929. program, then it will be replaced with \a program.
  930. Names that start with "\c{qt.}" are reserved for use by Qt's
  931. internal effects.
  932. \sa cachedProgram()
  933. */
  934. void QGLPainter::setCachedProgram
  935. (const QString& name, QOpenGLShaderProgram *program)
  936. {
  937. Q_D(QGLPainter);
  938. QGLPAINTER_CHECK_PRIVATE();
  939. QOpenGLShaderProgram *current = d->cachedPrograms.value(name, 0);
  940. if (current != program) {
  941. if (program)
  942. d->cachedPrograms[name] = program;
  943. else
  944. d->cachedPrograms.remove(name);
  945. delete current;
  946. }
  947. }
  948. void QGLPainterPrivate::createEffect(QGLPainter *painter)
  949. {
  950. if (userEffect) {
  951. if (!pick || !pick->isPicking) {
  952. effect = userEffect;
  953. effect->setActive(painter, true);
  954. updates = QGLPainter::UpdateAll;
  955. return;
  956. }
  957. if (userEffect->supportsPicking()) {
  958. effect = userEffect;
  959. effect->setActive(painter, true);
  960. updates = QGLPainter::UpdateAll;
  961. return;
  962. }
  963. effect = pick->defaultPickEffect;
  964. effect->setActive(painter, true);
  965. updates = QGLPainter::UpdateAll;
  966. return;
  967. }
  968. if (uint(standardEffect) >= QGL_MAX_STD_EFFECTS)
  969. effect = stdeffects[int(QGL::FlatColor)];
  970. else
  971. effect = stdeffects[int(standardEffect)];
  972. if (!effect) {
  973. switch (standardEffect) {
  974. case QGL::FlatColor: default:
  975. effect = new QGLFlatColorEffect();
  976. break;
  977. case QGL::FlatPerVertexColor:
  978. effect = new QGLPerVertexColorEffect();
  979. break;
  980. case QGL::FlatReplaceTexture2D:
  981. effect = new QGLFlatTextureEffect();
  982. break;
  983. case QGL::FlatDecalTexture2D:
  984. effect = new QGLFlatDecalTextureEffect();
  985. break;
  986. case QGL::LitMaterial:
  987. effect = new QGLLitMaterialEffect();
  988. break;
  989. case QGL::LitDecalTexture2D:
  990. effect = new QGLLitDecalTextureEffect();
  991. break;
  992. case QGL::LitModulateTexture2D:
  993. effect = new QGLLitModulateTextureEffect();
  994. break;
  995. }
  996. if (uint(standardEffect) >= QGL_MAX_STD_EFFECTS)
  997. stdeffects[int(QGL::FlatColor)] = effect;
  998. else
  999. stdeffects[int(standardEffect)] = effect;
  1000. }
  1001. if (!pick || !pick->isPicking || effect->supportsPicking()) {
  1002. effect->setActive(painter, true);
  1003. } else {
  1004. effect = pick->defaultPickEffect;
  1005. effect->setActive(painter, true);
  1006. }
  1007. updates = QGLPainter::UpdateAll;
  1008. }
  1009. /*!
  1010. Returns the last color that was set with setColor(). The default
  1011. value is (1, 1, 1, 1).
  1012. \sa setColor()
  1013. */
  1014. QColor QGLPainter::color() const
  1015. {
  1016. Q_D(QGLPainter);
  1017. QGLPAINTER_CHECK_PRIVATE();
  1018. return d->color;
  1019. }
  1020. /*!
  1021. Sets the default fragment \a color for effects associated
  1022. with this painter. This function does not apply the color
  1023. to the effect until update() is called.
  1024. \sa color(), update()
  1025. */
  1026. void QGLPainter::setColor(const QColor& color)
  1027. {
  1028. Q_D(QGLPainter);
  1029. QGLPAINTER_CHECK_PRIVATE();
  1030. d->color = color;
  1031. d->updates |= UpdateColor;
  1032. }
  1033. static void qt_gl_setVertexAttribute(QGL::VertexAttribute attribute, const QGLAttributeValue& value)
  1034. {
  1035. #if !defined(QT_OPENGL_ES_2)
  1036. switch (attribute) {
  1037. case QGL::Position:
  1038. glVertexPointer(value.tupleSize(), value.type(),
  1039. value.stride(), value.data());
  1040. break;
  1041. case QGL::Normal:
  1042. if (value.tupleSize() == 3)
  1043. glNormalPointer(value.type(), value.stride(), value.data());
  1044. break;
  1045. case QGL::Color:
  1046. glColorPointer(value.tupleSize(), value.type(),
  1047. value.stride(), value.data());
  1048. break;
  1049. #ifdef GL_TEXTURE_COORD_ARRAY
  1050. case QGL::TextureCoord0:
  1051. case QGL::TextureCoord1:
  1052. case QGL::TextureCoord2:
  1053. {
  1054. int unit = (int)(attribute - QGL::TextureCoord0);
  1055. qt_gl_ClientActiveTexture(GL_TEXTURE0 + unit);
  1056. glTexCoordPointer(value.tupleSize(), value.type(),
  1057. value.stride(), value.data());
  1058. if (unit != 0) // Stay on unit 0 between requests.
  1059. qt_gl_ClientActiveTexture(GL_TEXTURE0);
  1060. }
  1061. break;
  1062. #endif
  1063. default: break;
  1064. }
  1065. #else
  1066. Q_UNUSED(attribute);
  1067. Q_UNUSED(value);
  1068. #endif
  1069. }
  1070. /*!
  1071. Returns the set of vertex attributes that have been set on the
  1072. painter state by setVertexAttribute() and setVertexBundle()
  1073. since the last call to clearAttributes().
  1074. The most common use for this function is to determine if specific
  1075. attributes have been supplied on the painter so as to adjust the
  1076. current drawing effect accordingly. The following example will
  1077. use a lit texture effect if texture co-ordinates were provided
  1078. in the vertex bundle, or a simple lit material effect if
  1079. texture co-ordinates were not provided:
  1080. \code
  1081. painter.clearAttributes();
  1082. painter.setVertexBundle(bundle);
  1083. if (painter.attributes().contains(QGL::TextureCoord0))
  1084. painter.setStandardEffect(QGL::LitModulateTexture2D);
  1085. else
  1086. painter.setStandardEffect(QGL::LitMaterial);
  1087. \endcode
  1088. It is important to clear the attributes before setting the vertex
  1089. bundle, so that attributes from a previous bundle will not leak
  1090. through. Multiple vertex bundles may be supplied if they contain
  1091. different parts of the same logical piece of geometry.
  1092. \sa clearAttributes(), setVertexBundle()
  1093. */
  1094. QGLAttributeSet QGLPainter::attributes() const
  1095. {
  1096. Q_D(const QGLPainter);
  1097. QGLPAINTER_CHECK_PRIVATE();
  1098. return d->attributeSet;
  1099. }
  1100. /*!
  1101. Clears the set of vertex attributes that have been set on the
  1102. painter state by setVertexAttribute() and setVertexBundle().
  1103. See the documentation for attributes() for more information.
  1104. \sa attributes()
  1105. */
  1106. void QGLPainter::clearAttributes()
  1107. {
  1108. Q_D(QGLPainter);
  1109. QGLPAINTER_CHECK_PRIVATE();
  1110. d->attributeSet.clear();
  1111. }
  1112. /*!
  1113. Sets a vertex \a attribute on the current GL context to \a value.
  1114. The vertex attribute is bound to the GL state on the index
  1115. corresponding to \a attribute. For example, QGL::Position
  1116. will be bound to index 0, QGL::TextureCoord0 will be bound
  1117. to index 3, etc.
  1118. Vertex attributes are independent of the effect() and can be
  1119. bound once and then used with multiple effects.
  1120. If this is the first attribute in a new piece of geometry,
  1121. it is recommended that clearAttributes() be called before this
  1122. function. This will inform QGLPainter that a new piece of geometry
  1123. is being provided and that the previous geometry is now invalid.
  1124. See the documentation for attributes() for more information.
  1125. \sa setVertexBundle(), draw(), clearAttributes(), attributes()
  1126. */
  1127. void QGLPainter::setVertexAttribute
  1128. (QGL::VertexAttribute attribute, const QGLAttributeValue& value)
  1129. {
  1130. Q_D(QGLPainter);
  1131. QGLPAINTER_CHECK_PRIVATE();
  1132. d->ensureEffect(this);
  1133. if (d->boundVertexBuffer) {
  1134. QOpenGLBuffer::release(QOpenGLBuffer::VertexBuffer);
  1135. d->boundVertexBuffer = 0;
  1136. }
  1137. if (d->isFixedFunction) {
  1138. qt_gl_setVertexAttribute(attribute, value);
  1139. } else {
  1140. glVertexAttribPointer(GLuint(attribute), value.tupleSize(),
  1141. value.type(), GL_TRUE,
  1142. value.stride(), value.data());
  1143. }
  1144. d->attributeSet.insert(attribute);
  1145. }
  1146. /*!
  1147. Sets the vertex attributes on the current GL context that are
  1148. stored in \a buffer.
  1149. The vertex attributes are bound to the GL state on the indexes
  1150. that are specified within \a buffer; QGL::Position will be
  1151. bound to index 0, QGL::TextureCoord0 will be bound to index 3, etc.
  1152. Vertex attributes are independent of the effect() and can be
  1153. bound once and then used with multiple effects.
  1154. It is recommended that clearAttributes() be called before this
  1155. function to inform QGLPainter that a new piece of geometry is
  1156. being provided and that the previous geometry is now invalid.
  1157. See the documentation for attributes() for more information.
  1158. \sa setVertexAttribute(), draw(), clearAttributes(), attributes()
  1159. */
  1160. void QGLPainter::setVertexBundle(const QGLVertexBundle& buffer)
  1161. {
  1162. Q_D(QGLPainter);
  1163. QGLPAINTER_CHECK_PRIVATE();
  1164. d->ensureEffect(this);
  1165. QGLVertexBundlePrivate *bd = const_cast<QGLVertexBundlePrivate *>(buffer.d_func());
  1166. if (bd->buffer.isCreated()) {
  1167. GLuint id = bd->buffer.bufferId();
  1168. if (id != d->boundVertexBuffer) {
  1169. bd->buffer.bind();
  1170. d->boundVertexBuffer = id;
  1171. }
  1172. } else if (d->boundVertexBuffer) {
  1173. QOpenGLBuffer::release(QOpenGLBuffer::VertexBuffer);
  1174. d->boundVertexBuffer = 0;
  1175. }
  1176. for (int index = 0; index < bd->attributes.size(); ++index) {
  1177. QGLVertexBundleAttribute *attr = bd->attributes[index];
  1178. if (d->isFixedFunction) {
  1179. qt_gl_setVertexAttribute(attr->attribute, attr->value);
  1180. } else {
  1181. glVertexAttribPointer(GLuint(attr->attribute),
  1182. attr->value.tupleSize(),
  1183. attr->value.type(), GL_TRUE,
  1184. attr->value.stride(), attr->value.data());
  1185. }
  1186. }
  1187. d->attributeSet.unite(buffer.attributes());
  1188. }
  1189. /*!
  1190. Updates the projection matrix, modelview matrix, and lighting
  1191. conditions in the currently active effect() object by calling
  1192. QGLAbstractEffect::update(). Also updates \c{glViewport()}
  1193. to cover the currentSurface() if necessary.
  1194. Normally this function is called automatically by draw().
  1195. However, if the user wishes to use raw GL functions to draw fragments,
  1196. it will be necessary to explicitly call this function to ensure that
  1197. the matrix state and lighting conditions have been set on the
  1198. active effect().
  1199. Note that this function informs the effect that an update is needed.
  1200. It does not change the GL state itself, except for \c{glViewport()}.
  1201. In particular, the modelview and projection matrices in the
  1202. fixed-function pipeline are not changed unless the effect or
  1203. application calls updateFixedFunction().
  1204. \sa setUserEffect(), projectionMatrix(), modelViewMatrix()
  1205. \sa draw(), updateFixedFunction()
  1206. */
  1207. void QGLPainter::update()
  1208. {
  1209. Q_D(QGLPainter);
  1210. QGLPAINTER_CHECK_PRIVATE();
  1211. d->ensureEffect(this);
  1212. QGLPainter::Updates updates = d->updates;
  1213. d->updates = 0;
  1214. if (d->modelViewMatrix.isDirty()) {
  1215. updates |= UpdateModelViewMatrix;
  1216. d->modelViewMatrix.setDirty(false);
  1217. }
  1218. if (d->projectionMatrix.isDirty()) {
  1219. updates |= UpdateProjectionMatrix;
  1220. d->projectionMatrix.setDirty(false);
  1221. }
  1222. if ((updates & UpdateViewport) != 0) {
  1223. QRect viewport = currentSurface()->viewportGL();
  1224. glViewport(0, 0, viewport.width(), viewport.height());
  1225. }
  1226. if (updates != 0)
  1227. d->effect->update(this, updates);
  1228. }
  1229. #if !defined(QT_OPENGL_ES_2)
  1230. static void setLight(int light, const QGLLightParameters *parameters,
  1231. const QMatrix4x4& transform)
  1232. {
  1233. GLfloat params[4];
  1234. QColor color = parameters->ambientColor();
  1235. params[0] = color.redF();
  1236. params[1] = color.greenF();
  1237. params[2] = color.blueF();
  1238. params[3] = color.alphaF();
  1239. glLightfv(light, GL_AMBIENT, params);
  1240. color = parameters->diffuseColor();
  1241. params[0] = color.redF();
  1242. params[1] = color.greenF();
  1243. params[2] = color.blueF();
  1244. params[3] = color.alphaF();
  1245. glLightfv(light, GL_DIFFUSE, params);
  1246. color = parameters->specularColor();
  1247. params[0] = color.redF();
  1248. params[1] = color.greenF();
  1249. params[2] = color.blueF();
  1250. params[3] = color.alphaF();
  1251. glLightfv(light, GL_SPECULAR, params);
  1252. QVector4D vector = parameters->eyePosition(transform);
  1253. params[0] = vector.x();
  1254. params[1] = vector.y();
  1255. params[2] = vector.z();
  1256. params[3] = vector.w();
  1257. glLightfv(light, GL_POSITION, params);
  1258. QVector3D spotDirection = parameters->eyeSpotDirection(transform);
  1259. params[0] = spotDirection.x();
  1260. params[1] = spotDirection.y();
  1261. params[2] = spotDirection.z();
  1262. glLightfv(light, GL_SPOT_DIRECTION, params);
  1263. params[0] = parameters->spotExponent();
  1264. glLightfv(light, GL_SPOT_EXPONENT, params);
  1265. params[0] = parameters->spotAngle();
  1266. glLightfv(light, GL_SPOT_CUTOFF, params);
  1267. params[0] = parameters->constantAttenuation();
  1268. glLightfv(light, GL_CONSTANT_ATTENUATION, params);
  1269. params[0] = parameters->linearAttenuation();
  1270. glLightfv(light, GL_LINEAR_ATTENUATION, params);
  1271. params[0] = parameters->quadraticAttenuation();
  1272. glLightfv(light, GL_QUADRATIC_ATTENUATION, params);
  1273. }
  1274. static void setMaterial(int face, const QGLMaterial *parameters)
  1275. {
  1276. GLfloat params[17];
  1277. QColor mcolor = parameters->ambientColor();
  1278. params[0] = mcolor.redF();
  1279. params[1] = mcolor.greenF();
  1280. params[2] = mcolor.blueF();
  1281. params[3] = mcolor.alphaF();
  1282. mcolor = parameters->diffuseColor();
  1283. params[4] = mcolor.redF();
  1284. params[5] = mcolor.greenF();
  1285. params[6] = mcolor.blueF();
  1286. params[7] = mcolor.alphaF();
  1287. mcolor = parameters->specularColor();
  1288. params[8] = mcolor.redF();
  1289. params[9] = mcolor.greenF();
  1290. params[10] = mcolor.blueF();
  1291. params[11] = mcolor.alphaF();
  1292. mcolor = parameters->emittedLight();
  1293. params[12] = mcolor.redF();
  1294. params[13] = mcolor.greenF();
  1295. params[14] = mcolor.blueF();
  1296. params[15] = mcolor.alphaF();
  1297. params[16] = parameters->shininess();
  1298. glMaterialfv(face, GL_AMBIENT, params);
  1299. glMaterialfv(face, GL_DIFFUSE, params + 4);
  1300. glMaterialfv(face, GL_SPECULAR, params + 8);
  1301. glMaterialfv(face, GL_EMISSION, params + 12);
  1302. glMaterialfv(face, GL_SHININESS, params + 16);
  1303. }
  1304. #endif // !QT_OPENGL_ES_2
  1305. /*!
  1306. Updates the fixed-function pipeline with the current painting
  1307. state according to the flags in \a updates.
  1308. This function is intended for use by effects in their
  1309. QGLAbstractEffect::update() override if they are using the
  1310. fixed-function pipeline. It can also be used by user
  1311. applications if they need the QGLPainter state to be
  1312. set in the fixed-function pipeline.
  1313. If the OpenGL implementation does not have a fixed-function
  1314. pipeline, e.g. OpenGL/ES 2.0, this function does nothing.
  1315. \sa update()
  1316. */
  1317. void QGLPainter::updateFixedFunction(QGLPainter::Updates updates)
  1318. {
  1319. #if defined(QT_OPENGL_ES_2)
  1320. Q_UNUSED(updates);
  1321. #else
  1322. Q_D(QGLPainter);
  1323. QGLPAINTER_CHECK_PRIVATE();
  1324. if ((updates & QGLPainter::UpdateColor) != 0) {
  1325. QColor color;
  1326. if (isPicking())
  1327. color = pickColor();
  1328. else
  1329. color = this->color();
  1330. glColor4f(color.redF(), color.greenF(), color.blueF(), color.alphaF());
  1331. }
  1332. if ((updates & QGLPainter::UpdateModelViewMatrix) != 0) {
  1333. const QMatrix4x4 &matrix = d->modelViewMatrix.top();
  1334. glMatrixMode(GL_MODELVIEW);
  1335. if (sizeof(qreal) == sizeof(GLfloat)) {
  1336. glLoadMatrixf(reinterpret_cast<const GLfloat *>
  1337. (matrix.constData()));
  1338. } else {
  1339. GLfloat mat[16];
  1340. const qreal *m = matrix.constData();
  1341. for (int index = 0; index < 16; ++index)
  1342. mat[index] = m[index];
  1343. glLoadMatrixf(mat);
  1344. }
  1345. }
  1346. if ((updates & QGLPainter::UpdateProjectionMatrix) != 0) {
  1347. const QMatrix4x4 &matrix = d->projectionMatrix.top();
  1348. glMatrixMode(GL_PROJECTION);
  1349. if (sizeof(qreal) == sizeof(GLfloat)) {
  1350. glLoadMatrixf(reinterpret_cast<const GLfloat *>
  1351. (matrix.constData()));
  1352. } else {
  1353. GLfloat mat[16];
  1354. const qreal *m = matrix.constData();
  1355. for (int index = 0; index < 16; ++index)
  1356. mat[index] = m[index];
  1357. glLoadMatrixf(mat);
  1358. }
  1359. }
  1360. if ((updates & QGLPainter::UpdateLights) != 0) {
  1361. // Save the current modelview matrix and load the identity.
  1362. // We need to apply the light in the modelview transformation
  1363. // that was active when the light was specified.
  1364. glMatrixMode(GL_MODELVIEW);
  1365. glPushMatrix();
  1366. glLoadIdentity();
  1367. // Enable the main light.
  1368. const QGLLightParameters *params = mainLight();
  1369. setLight(GL_LIGHT0, params, mainLightTransform());
  1370. // Restore the previous modelview transformation.
  1371. glPopMatrix();
  1372. // Set up the light model parameters if at least one light is enabled.
  1373. const QGLLightModel *lightModel = this->lightModel();
  1374. GLfloat values[4];
  1375. #ifdef GL_LIGHT_MODEL_TWO_SIDE
  1376. if (lightModel->model() == QGLLightModel::TwoSided)
  1377. values[0] = 1.0f;
  1378. else
  1379. values[0] = 0.0f;
  1380. glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, values);
  1381. #endif
  1382. #ifdef GL_LIGHT_MODEL_COLOR_CONTROL
  1383. if (lightModel->colorControl() == QGLLightModel::SeparateSpecularColor)
  1384. values[0] = GL_SEPARATE_SPECULAR_COLOR;
  1385. else
  1386. values[0] = GL_SINGLE_COLOR;
  1387. glLightModelfv(GL_LIGHT_MODEL_COLOR_CONTROL, values);
  1388. #endif
  1389. #ifdef GL_LIGHT_MODEL_LOCAL_VIEWER
  1390. if (lightModel->viewerPosition() == QGLLightModel::LocalViewer)
  1391. values[0] = 1.0f;
  1392. else
  1393. values[0] = 0.0f;
  1394. glLightModelfv(GL_LIGHT_MODEL_LOCAL_VIEWER, values);
  1395. #endif
  1396. #ifdef GL_LIGHT_MODEL_AMBIENT
  1397. QColor color = lightModel->ambientSceneColor();
  1398. values[0] = color.redF();
  1399. values[1] = color.blueF();
  1400. values[2] = color.greenF();

Large files files are truncated, but you can click here to view the full file