1 /****************************************************************************
3 ** Copyright (C) 2015 The Qt Company Ltd.
4 ** Contact: http://www.qt.io/licensing/
6 ** This file is part of the demonstration applications of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and The Qt Company. For licensing terms
14 ** and conditions see http://www.qt.io/terms-conditions. For further
15 ** information use the contact form at http://www.qt.io/contact-us.
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 or version 3 as published by the Free
20 ** Software Foundation and appearing in the file LICENSE.LGPLv21 and
21 ** LICENSE.LGPLv3 included in the packaging of this file. Please review the
22 ** following information to ensure the GNU Lesser General Public License
23 ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
24 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
26 ** As a special exception, The Qt Company gives you certain additional
27 ** rights. These rights are described in The Qt Company LGPL Exception
28 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
30 ** GNU General Public License Usage
31 ** Alternatively, this file may be used under the terms of the GNU
32 ** General Public License version 3.0 as published by the Free Software
33 ** Foundation and appearing in the file LICENSE.GPL included in the
34 ** packaging of this file. Please review the following information to
35 ** ensure the GNU General Public License version 3.0 requirements will be
36 ** met: http://www.gnu.org/copyleft/gpl.html.
40 ****************************************************************************/
44 #include <QtGui/qmatrix4x4.h>
45 #include <QtGui/qvector3d.h>
47 #include "3rdparty/fbm.h"
49 void checkGLErrors(const QString& prefix)
51 switch (glGetError()) {
53 //qDebug() << prefix << tr("No error.");
56 qDebug() << prefix << QObject::tr("Invalid enum.");
58 case GL_INVALID_VALUE:
59 qDebug() << prefix << QObject::tr("Invalid value.");
61 case GL_INVALID_OPERATION:
62 qDebug() << prefix << QObject::tr("Invalid operation.");
64 case GL_STACK_OVERFLOW:
65 qDebug() << prefix << QObject::tr("Stack overflow.");
67 case GL_STACK_UNDERFLOW:
68 qDebug() << prefix << QObject::tr("Stack underflow.");
70 case GL_OUT_OF_MEMORY:
71 qDebug() << prefix << QObject::tr("Out of memory.");
74 qDebug() << prefix << QObject::tr("Unknown error.");
79 //============================================================================//
81 //============================================================================//
83 ColorEdit::ColorEdit(QRgb initialColor, int id)
84 : m_color(initialColor), m_id(id)
86 QHBoxLayout *layout = new QHBoxLayout;
88 layout->setContentsMargins(0, 0, 0, 0);
90 m_lineEdit = new QLineEdit(QString::number(m_color, 16));
91 layout->addWidget(m_lineEdit);
93 m_button = new QFrame;
94 QPalette palette = m_button->palette();
95 palette.setColor(QPalette::Window, QColor(m_color));
96 m_button->setPalette(palette);
97 m_button->setAutoFillBackground(true);
98 m_button->setMinimumSize(32, 0);
99 m_button->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
100 m_button->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
101 layout->addWidget(m_button);
103 connect(m_lineEdit, SIGNAL(editingFinished()), this, SLOT(editDone()));
106 void ColorEdit::editDone()
109 QRgb newColor = m_lineEdit->text().toUInt(&ok, 16);
114 void ColorEdit::mousePressEvent(QMouseEvent *event)
116 if (event->button() == Qt::LeftButton) {
117 QColor color(m_color);
118 QColorDialog dialog(color, 0);
119 dialog.setOption(QColorDialog::ShowAlphaChannel, true);
120 // The ifdef block is a workaround for the beta, TODO: remove when bug 238525 is fixed
122 dialog.setOption(QColorDialog::DontUseNativeDialog, true);
124 dialog.move(280, 120);
125 if (dialog.exec() == QDialog::Rejected)
127 QRgb newColor = dialog.selectedColor().rgba();
128 if (newColor == m_color)
134 void ColorEdit::setColor(QRgb color)
137 m_lineEdit->setText(QString::number(m_color, 16)); // "Clean up" text
138 QPalette palette = m_button->palette();
139 palette.setColor(QPalette::Window, QColor(m_color));
140 m_button->setPalette(palette);
141 emit colorChanged(m_color, m_id);
144 //============================================================================//
146 //============================================================================//
148 FloatEdit::FloatEdit(float initialValue, int id)
149 : m_value(initialValue), m_id(id)
151 QHBoxLayout *layout = new QHBoxLayout;
153 layout->setContentsMargins(0, 0, 0, 0);
155 m_lineEdit = new QLineEdit(QString::number(m_value));
156 layout->addWidget(m_lineEdit);
158 connect(m_lineEdit, SIGNAL(editingFinished()), this, SLOT(editDone()));
161 void FloatEdit::editDone()
164 float newValue = m_lineEdit->text().toFloat(&ok);
167 m_lineEdit->setText(QString::number(m_value)); // "Clean up" text
168 emit valueChanged(m_value, m_id);
172 //============================================================================//
173 // TwoSidedGraphicsWidget //
174 //============================================================================//
176 TwoSidedGraphicsWidget::TwoSidedGraphicsWidget(QGraphicsScene *scene)
182 for (int i = 0; i < 2; ++i)
183 m_proxyWidgets[i] = 0;
186 void TwoSidedGraphicsWidget::setWidget(int index, QWidget *widget)
188 if (index < 0 || index >= 2)
190 qWarning("TwoSidedGraphicsWidget::setWidget: Index out of bounds, index == %d", index);
194 GraphicsWidget *proxy = new GraphicsWidget;
195 proxy->setWidget(widget);
197 if (m_proxyWidgets[index])
198 delete m_proxyWidgets[index];
199 m_proxyWidgets[index] = proxy;
201 proxy->setCacheMode(QGraphicsItem::ItemCoordinateCache);
202 proxy->setZValue(1e30); // Make sure the dialog is drawn on top of all other (OpenGL) items
204 if (index != m_current)
205 proxy->setVisible(false);
207 qobject_cast<QGraphicsScene *>(parent())->addItem(proxy);
210 QWidget *TwoSidedGraphicsWidget::widget(int index)
212 if (index < 0 || index >= 2)
214 qWarning("TwoSidedGraphicsWidget::widget: Index out of bounds, index == %d", index);
217 return m_proxyWidgets[index]->widget();
220 void TwoSidedGraphicsWidget::flip()
222 m_delta = (m_current == 0 ? 9 : -9);
226 void TwoSidedGraphicsWidget::animateFlip()
232 m_proxyWidgets[old]->setVisible(false);
233 m_proxyWidgets[m_current]->setVisible(true);
234 m_proxyWidgets[m_current]->setGeometry(m_proxyWidgets[old]->geometry());
237 QRectF r = m_proxyWidgets[m_current]->boundingRect();
238 m_proxyWidgets[m_current]->setTransform(QTransform()
239 .translate(r.width() / 2, r.height() / 2)
240 .rotate(m_angle - 180 * m_current, Qt::YAxis)
241 .translate(-r.width() / 2, -r.height() / 2));
243 if ((m_current == 0 && m_angle > 0) || (m_current == 1 && m_angle < 180))
244 QTimer::singleShot(25, this, SLOT(animateFlip()));
247 QVariant GraphicsWidget::itemChange(GraphicsItemChange change, const QVariant &value)
249 if (change == ItemPositionChange && scene()) {
250 QRectF rect = boundingRect();
251 QPointF pos = value.toPointF();
252 QRectF sceneRect = scene()->sceneRect();
253 if (pos.x() + rect.left() < sceneRect.left())
254 pos.setX(sceneRect.left() - rect.left());
255 else if (pos.x() + rect.right() >= sceneRect.right())
256 pos.setX(sceneRect.right() - rect.right());
257 if (pos.y() + rect.top() < sceneRect.top())
258 pos.setY(sceneRect.top() - rect.top());
259 else if (pos.y() + rect.bottom() >= sceneRect.bottom())
260 pos.setY(sceneRect.bottom() - rect.bottom());
263 return QGraphicsProxyWidget::itemChange(change, value);
266 void GraphicsWidget::resizeEvent(QGraphicsSceneResizeEvent *event)
268 setCacheMode(QGraphicsItem::NoCache);
269 setCacheMode(QGraphicsItem::ItemCoordinateCache);
270 QGraphicsProxyWidget::resizeEvent(event);
273 void GraphicsWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
275 painter->setRenderHint(QPainter::Antialiasing, false);
276 QGraphicsProxyWidget::paint(painter, option, widget);
277 //painter->setRenderHint(QPainter::Antialiasing, true);
280 //============================================================================//
281 // RenderOptionsDialog //
282 //============================================================================//
284 RenderOptionsDialog::RenderOptionsDialog()
285 : QDialog(0, Qt::CustomizeWindowHint | Qt::WindowTitleHint)
287 setWindowOpacity(0.75);
288 setWindowTitle(tr("Options (double click to flip)"));
289 QGridLayout *layout = new QGridLayout;
291 layout->setColumnStretch(1, 1);
295 QCheckBox *check = new QCheckBox(tr("Dynamic cube map"));
296 check->setCheckState(Qt::Unchecked);
297 // Dynamic cube maps are only enabled when multi-texturing and render to texture are available.
298 check->setEnabled(glActiveTexture && glGenFramebuffersEXT);
299 connect(check, SIGNAL(stateChanged(int)), this, SIGNAL(dynamicCubemapToggled(int)));
300 layout->addWidget(check, 0, 0, 1, 2);
305 // Load all .par files
306 // .par files have a simple syntax for specifying user adjustable uniform variables.
307 QSet<QByteArray> uniforms;
308 QList<QString> filter = QStringList("*.par");
309 QList<QFileInfo> files = QDir(":/res/boxes/").entryInfoList(filter, QDir::Files | QDir::Readable);
311 foreach (QFileInfo fileInfo, files) {
312 QFile file(fileInfo.absoluteFilePath());
313 if (file.open(QIODevice::ReadOnly)) {
314 while (!file.atEnd()) {
315 QList<QByteArray> tokens = file.readLine().simplified().split(' ');
316 QList<QByteArray>::const_iterator it = tokens.begin();
317 if (it == tokens.end())
319 QByteArray type = *it;
320 if (++it == tokens.end())
322 QByteArray name = *it;
323 bool singleElement = (tokens.size() == 3); // type, name and one value
324 char counter[10] = "000000000";
325 int counterPos = 8; // position of last digit
326 while (++it != tokens.end()) {
327 m_parameterNames << name;
328 if (!singleElement) {
329 m_parameterNames.back() += "[";
330 m_parameterNames.back() += counter + counterPos;
331 m_parameterNames.back() += "]";
332 int j = 8; // position of last digit
334 while (j > 0 && counter[j] > '9') {
342 if (type == "color") {
343 layout->addWidget(new QLabel(m_parameterNames.back()));
345 ColorEdit *colorEdit = new ColorEdit(it->toUInt(&ok, 16), m_parameterNames.size() - 1);
346 m_parameterEdits << colorEdit;
347 layout->addWidget(colorEdit);
348 connect(colorEdit, SIGNAL(colorChanged(QRgb,int)), this, SLOT(setColorParameter(QRgb,int)));
350 } else if (type == "float") {
351 layout->addWidget(new QLabel(m_parameterNames.back()));
353 FloatEdit *floatEdit = new FloatEdit(it->toFloat(&ok), m_parameterNames.size() - 1);
354 m_parameterEdits << floatEdit;
355 layout->addWidget(floatEdit);
356 connect(floatEdit, SIGNAL(valueChanged(float,int)), this, SLOT(setFloatParameter(float,int)));
365 layout->addWidget(new QLabel(tr("Texture:")));
366 m_textureCombo = new QComboBox;
367 connect(m_textureCombo, SIGNAL(currentIndexChanged(int)), this, SIGNAL(textureChanged(int)));
368 layout->addWidget(m_textureCombo);
371 layout->addWidget(new QLabel(tr("Shader:")));
372 m_shaderCombo = new QComboBox;
373 connect(m_shaderCombo, SIGNAL(currentIndexChanged(int)), this, SIGNAL(shaderChanged(int)));
374 layout->addWidget(m_shaderCombo);
377 layout->setRowStretch(row, 1);
380 int RenderOptionsDialog::addTexture(const QString &name)
382 m_textureCombo->addItem(name);
383 return m_textureCombo->count() - 1;
386 int RenderOptionsDialog::addShader(const QString &name)
388 m_shaderCombo->addItem(name);
389 return m_shaderCombo->count() - 1;
392 void RenderOptionsDialog::emitParameterChanged()
394 foreach (ParameterEdit *edit, m_parameterEdits)
398 void RenderOptionsDialog::setColorParameter(QRgb color, int id)
400 emit colorParameterChanged(m_parameterNames[id], color);
403 void RenderOptionsDialog::setFloatParameter(float value, int id)
405 emit floatParameterChanged(m_parameterNames[id], value);
408 void RenderOptionsDialog::mouseDoubleClickEvent(QMouseEvent *event)
410 if (event->button() == Qt::LeftButton)
411 emit doubleClicked();
414 //============================================================================//
416 //============================================================================//
418 ItemDialog::ItemDialog()
419 : QDialog(0, Qt::CustomizeWindowHint | Qt::WindowTitleHint)
421 setWindowTitle(tr("Items (double click to flip)"));
422 setWindowOpacity(0.75);
425 QVBoxLayout *layout = new QVBoxLayout;
429 button = new QPushButton(tr("Add Qt box"));
430 layout->addWidget(button);
431 connect(button, SIGNAL(clicked()), this, SLOT(triggerNewQtBox()));
433 button = new QPushButton(tr("Add circle"));
434 layout->addWidget(button);
435 connect(button, SIGNAL(clicked()), this, SLOT(triggerNewCircleItem()));
437 button = new QPushButton(tr("Add square"));
438 layout->addWidget(button);
439 connect(button, SIGNAL(clicked()), this, SLOT(triggerNewSquareItem()));
441 layout->addStretch(1);
444 void ItemDialog::triggerNewQtBox()
446 emit newItemTriggered(QtBoxItem);
449 void ItemDialog::triggerNewCircleItem()
451 emit newItemTriggered(CircleItem);
454 void ItemDialog::triggerNewSquareItem()
456 emit newItemTriggered(SquareItem);
459 void ItemDialog::mouseDoubleClickEvent(QMouseEvent *event)
461 if (event->button() == Qt::LeftButton)
462 emit doubleClicked();
465 //============================================================================//
467 //============================================================================//
469 const static char environmentShaderText[] =
470 "uniform samplerCube env;"
472 "gl_FragColor = textureCube(env, gl_TexCoord[1].xyz);"
475 Scene::Scene(int width, int height, int maxTextureSize)
478 , m_maxTextureSize(maxTextureSize)
480 , m_currentTexture(0)
481 , m_dynamicCubemap(false)
482 , m_updateAllCubemaps(true)
485 , m_environmentShader(0)
486 , m_environmentProgram(0)
488 setSceneRect(0, 0, width, height);
490 m_trackBalls[0] = TrackBall(0.05f, QVector3D(0, 1, 0), TrackBall::Sphere);
491 m_trackBalls[1] = TrackBall(0.005f, QVector3D(0, 0, 1), TrackBall::Sphere);
492 m_trackBalls[2] = TrackBall(0.0f, QVector3D(0, 1, 0), TrackBall::Plane);
494 m_renderOptions = new RenderOptionsDialog;
495 m_renderOptions->move(20, 120);
496 m_renderOptions->resize(m_renderOptions->sizeHint());
498 connect(m_renderOptions, SIGNAL(dynamicCubemapToggled(int)), this, SLOT(toggleDynamicCubemap(int)));
499 connect(m_renderOptions, SIGNAL(colorParameterChanged(QString,QRgb)), this, SLOT(setColorParameter(QString,QRgb)));
500 connect(m_renderOptions, SIGNAL(floatParameterChanged(QString,float)), this, SLOT(setFloatParameter(QString,float)));
501 connect(m_renderOptions, SIGNAL(textureChanged(int)), this, SLOT(setTexture(int)));
502 connect(m_renderOptions, SIGNAL(shaderChanged(int)), this, SLOT(setShader(int)));
504 m_itemDialog = new ItemDialog;
505 connect(m_itemDialog, SIGNAL(newItemTriggered(ItemDialog::ItemType)), this, SLOT(newItem(ItemDialog::ItemType)));
507 TwoSidedGraphicsWidget *twoSided = new TwoSidedGraphicsWidget(this);
508 twoSided->setWidget(0, m_renderOptions);
509 twoSided->setWidget(1, m_itemDialog);
511 connect(m_renderOptions, SIGNAL(doubleClicked()), twoSided, SLOT(flip()));
512 connect(m_itemDialog, SIGNAL(doubleClicked()), twoSided, SLOT(flip()));
514 addItem(new QtBox(64, width - 64, height - 64));
515 addItem(new QtBox(64, width - 64, 64));
516 addItem(new QtBox(64, 64, height - 64));
517 addItem(new QtBox(64, 64, 64));
521 m_timer = new QTimer(this);
522 m_timer->setInterval(20);
523 connect(m_timer, SIGNAL(timeout()), this, SLOT(update()));
533 foreach (GLTexture *texture, m_textures)
534 if (texture) delete texture;
536 delete m_mainCubemap;
537 foreach (QGLShaderProgram *program, m_programs)
538 if (program) delete program;
540 delete m_vertexShader;
541 foreach (QGLShader *shader, m_fragmentShaders)
542 if (shader) delete shader;
543 foreach (GLRenderTargetCube *rt, m_cubemaps)
545 if (m_environmentShader)
546 delete m_environmentShader;
547 if (m_environmentProgram)
548 delete m_environmentProgram;
553 m_box = new GLRoundedBox(0.25f, 1.0f, 10);
555 m_vertexShader = new QGLShader(QGLShader::Vertex);
556 m_vertexShader->compileSourceFile(QLatin1String(":/res/boxes/basic.vsh"));
559 list << ":/res/boxes/cubemap_posx.jpg" << ":/res/boxes/cubemap_negx.jpg" << ":/res/boxes/cubemap_posy.jpg"
560 << ":/res/boxes/cubemap_negy.jpg" << ":/res/boxes/cubemap_posz.jpg" << ":/res/boxes/cubemap_negz.jpg";
561 m_environment = new GLTextureCube(list, qMin(1024, m_maxTextureSize));
562 m_environmentShader = new QGLShader(QGLShader::Fragment);
563 m_environmentShader->compileSourceCode(environmentShaderText);
564 m_environmentProgram = new QGLShaderProgram;
565 m_environmentProgram->addShader(m_vertexShader);
566 m_environmentProgram->addShader(m_environmentShader);
567 m_environmentProgram->link();
569 const int NOISE_SIZE = 128; // for a different size, B and BM in fbm.c must also be changed
570 m_noise = new GLTexture3D(NOISE_SIZE, NOISE_SIZE, NOISE_SIZE);
571 QRgb *data = new QRgb[NOISE_SIZE * NOISE_SIZE * NOISE_SIZE];
572 memset(data, 0, NOISE_SIZE * NOISE_SIZE * NOISE_SIZE * sizeof(QRgb));
575 for (int k = 0; k < NOISE_SIZE; ++k) {
576 pos[2] = k * (0x20 / (float)NOISE_SIZE);
577 for (int j = 0; j < NOISE_SIZE; ++j) {
578 for (int i = 0; i < NOISE_SIZE; ++i) {
579 for (int byte = 0; byte < 4; ++byte) {
580 pos[0] = (i + (byte & 1) * 16) * (0x20 / (float)NOISE_SIZE);
581 pos[1] = (j + (byte & 2) * 8) * (0x20 / (float)NOISE_SIZE);
582 *p |= (int)(128.0f * (noise3(pos) + 1.0f)) << (byte * 8);
588 m_noise->load(NOISE_SIZE, NOISE_SIZE, NOISE_SIZE, data);
591 m_mainCubemap = new GLRenderTargetCube(512);
594 QList<QFileInfo> files;
596 // Load all .png files as textures
597 m_currentTexture = 0;
598 filter = QStringList("*.png");
599 files = QDir(":/res/boxes/").entryInfoList(filter, QDir::Files | QDir::Readable);
601 foreach (QFileInfo file, files) {
602 GLTexture *texture = new GLTexture2D(file.absoluteFilePath(), qMin(256, m_maxTextureSize), qMin(256, m_maxTextureSize));
603 if (texture->failed()) {
607 m_textures << texture;
608 m_renderOptions->addTexture(file.baseName());
611 if (m_textures.size() == 0)
612 m_textures << new GLTexture2D(qMin(64, m_maxTextureSize), qMin(64, m_maxTextureSize));
614 // Load all .fsh files as fragment shaders
616 filter = QStringList("*.fsh");
617 files = QDir(":/res/boxes/").entryInfoList(filter, QDir::Files | QDir::Readable);
618 foreach (QFileInfo file, files) {
619 QGLShaderProgram *program = new QGLShaderProgram;
620 QGLShader* shader = new QGLShader(QGLShader::Fragment);
621 shader->compileSourceFile(file.absoluteFilePath());
622 // The program does not take ownership over the shaders, so store them in a vector so they can be deleted afterwards.
623 program->addShader(m_vertexShader);
624 program->addShader(shader);
625 if (!program->link()) {
626 qWarning("Failed to compile and link shader program");
627 qWarning("Vertex shader log:");
628 qWarning() << m_vertexShader->log();
629 qWarning() << "Fragment shader log ( file =" << file.absoluteFilePath() << "):";
630 qWarning() << shader->log();
631 qWarning("Shader program log:");
632 qWarning() << program->log();
639 m_fragmentShaders << shader;
640 m_programs << program;
641 m_renderOptions->addShader(file.baseName());
644 m_cubemaps << ((program->uniformLocation("env") != -1) ? new GLRenderTargetCube(qMin(256, m_maxTextureSize)) : 0);
648 if (m_programs.size() == 0)
649 m_programs << new QGLShaderProgram;
651 m_renderOptions->emitParameterChanged();
654 static void loadMatrix(const QMatrix4x4& m)
656 // static to prevent glLoadMatrixf to fail on certain drivers
657 static GLfloat mat[16];
658 const qreal *data = m.constData();
659 for (int index = 0; index < 16; ++index)
660 mat[index] = data[index];
664 static void multMatrix(const QMatrix4x4& m)
666 // static to prevent glMultMatrixf to fail on certain drivers
667 static GLfloat mat[16];
668 const qreal *data = m.constData();
669 for (int index = 0; index < 16; ++index)
670 mat[index] = data[index];
674 // If one of the boxes should not be rendered, set excludeBox to its index.
675 // If the main box should not be rendered, set excludeBox to -1.
676 void Scene::renderBoxes(const QMatrix4x4 &view, int excludeBox)
678 QMatrix4x4 invView = view.inverted();
680 // If multi-texturing is supported, use three saplers.
681 if (glActiveTexture) {
682 glActiveTexture(GL_TEXTURE0);
683 m_textures[m_currentTexture]->bind();
684 glActiveTexture(GL_TEXTURE2);
686 glActiveTexture(GL_TEXTURE1);
688 m_textures[m_currentTexture]->bind();
691 glDisable(GL_LIGHTING);
692 glDisable(GL_CULL_FACE);
694 QMatrix4x4 viewRotation(view);
695 viewRotation(3, 0) = viewRotation(3, 1) = viewRotation(3, 2) = 0.0f;
696 viewRotation(0, 3) = viewRotation(1, 3) = viewRotation(2, 3) = 0.0f;
697 viewRotation(3, 3) = 1.0f;
698 loadMatrix(viewRotation);
699 glScalef(20.0f, 20.0f, 20.0f);
701 // Don't render the environment if the environment texture can't be set for the correct sampler.
702 if (glActiveTexture) {
703 m_environment->bind();
704 m_environmentProgram->bind();
705 m_environmentProgram->setUniformValue("tex", GLint(0));
706 m_environmentProgram->setUniformValue("env", GLint(1));
707 m_environmentProgram->setUniformValue("noise", GLint(2));
709 m_environmentProgram->release();
710 m_environment->unbind();
715 glEnable(GL_CULL_FACE);
716 glEnable(GL_LIGHTING);
718 for (int i = 0; i < m_programs.size(); ++i) {
724 m.rotate(m_trackBalls[1].rotation());
727 glRotatef(360.0f * i / m_programs.size(), 0.0f, 0.0f, 1.0f);
728 glTranslatef(2.0f, 0.0f, 0.0f);
729 glScalef(0.3f, 0.6f, 0.6f);
731 if (glActiveTexture) {
732 if (m_dynamicCubemap && m_cubemaps[i])
733 m_cubemaps[i]->bind();
735 m_environment->bind();
737 m_programs[i]->bind();
738 m_programs[i]->setUniformValue("tex", GLint(0));
739 m_programs[i]->setUniformValue("env", GLint(1));
740 m_programs[i]->setUniformValue("noise", GLint(2));
741 m_programs[i]->setUniformValue("view", view);
742 m_programs[i]->setUniformValue("invView", invView);
744 m_programs[i]->release();
746 if (glActiveTexture) {
747 if (m_dynamicCubemap && m_cubemaps[i])
748 m_cubemaps[i]->unbind();
750 m_environment->unbind();
755 if (-1 != excludeBox) {
757 m.rotate(m_trackBalls[0].rotation());
760 if (glActiveTexture) {
761 if (m_dynamicCubemap)
762 m_mainCubemap->bind();
764 m_environment->bind();
767 m_programs[m_currentShader]->bind();
768 m_programs[m_currentShader]->setUniformValue("tex", GLint(0));
769 m_programs[m_currentShader]->setUniformValue("env", GLint(1));
770 m_programs[m_currentShader]->setUniformValue("noise", GLint(2));
771 m_programs[m_currentShader]->setUniformValue("view", view);
772 m_programs[m_currentShader]->setUniformValue("invView", invView);
774 m_programs[m_currentShader]->release();
776 if (glActiveTexture) {
777 if (m_dynamicCubemap)
778 m_mainCubemap->unbind();
780 m_environment->unbind();
784 if (glActiveTexture) {
785 glActiveTexture(GL_TEXTURE2);
787 glActiveTexture(GL_TEXTURE0);
789 m_textures[m_currentTexture]->unbind();
792 void Scene::setStates()
794 //glClearColor(0.25f, 0.25f, 0.5f, 1.0f);
796 glEnable(GL_DEPTH_TEST);
797 glEnable(GL_CULL_FACE);
798 glEnable(GL_LIGHTING);
799 //glEnable(GL_COLOR_MATERIAL);
800 glEnable(GL_TEXTURE_2D);
801 glEnable(GL_NORMALIZE);
803 glMatrixMode(GL_PROJECTION);
807 glMatrixMode(GL_MODELVIEW);
813 float materialSpecular[] = {0.5f, 0.5f, 0.5f, 1.0f};
814 glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, materialSpecular);
815 glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 32.0f);
818 void Scene::setLights()
820 glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
821 //float lightColour[] = {1.0f, 1.0f, 1.0f, 1.0f};
822 float lightDir[] = {0.0f, 0.0f, 1.0f, 0.0f};
823 //glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColour);
824 //glLightfv(GL_LIGHT0, GL_SPECULAR, lightColour);
825 glLightfv(GL_LIGHT0, GL_POSITION, lightDir);
826 glLightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER, 1.0f);
830 void Scene::defaultStates()
832 //glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
834 glDisable(GL_DEPTH_TEST);
835 glDisable(GL_CULL_FACE);
836 glDisable(GL_LIGHTING);
837 //glDisable(GL_COLOR_MATERIAL);
838 glDisable(GL_TEXTURE_2D);
839 glDisable(GL_LIGHT0);
840 glDisable(GL_NORMALIZE);
842 glMatrixMode(GL_MODELVIEW);
845 glMatrixMode(GL_PROJECTION);
848 glLightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER, 0.0f);
849 float defaultMaterialSpecular[] = {0.0f, 0.0f, 0.0f, 1.0f};
850 glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, defaultMaterialSpecular);
851 glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 0.0f);
854 void Scene::renderCubemaps()
856 // To speed things up, only update the cubemaps for the small cubes every N frames.
857 const int N = (m_updateAllCubemaps ? 1 : 3);
860 GLRenderTargetCube::getProjectionMatrix(mat, 0.1f, 100.0f);
862 glMatrixMode(GL_PROJECTION);
866 glMatrixMode(GL_MODELVIEW);
871 for (int i = m_frame % N; i < m_cubemaps.size(); i += N) {
872 if (0 == m_cubemaps[i])
875 float angle = 2.0f * PI * i / m_cubemaps.size();
877 center = m_trackBalls[1].rotation().rotatedVector(QVector3D(cos(angle), sin(angle), 0.0f));
879 for (int face = 0; face < 6; ++face) {
880 m_cubemaps[i]->begin(face);
882 GLRenderTargetCube::getViewMatrix(mat, face);
883 QVector4D v = QVector4D(-center.x(), -center.y(), -center.z(), 1.0);
884 mat.setColumn(3, mat * v);
886 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
889 m_cubemaps[i]->end();
893 for (int face = 0; face < 6; ++face) {
894 m_mainCubemap->begin(face);
895 GLRenderTargetCube::getViewMatrix(mat, face);
897 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
898 renderBoxes(mat, -1);
900 m_mainCubemap->end();
905 glMatrixMode(GL_PROJECTION);
908 m_updateAllCubemaps = false;
911 void Scene::drawBackground(QPainter *painter, const QRectF &)
913 float width = float(painter->device()->width());
914 float height = float(painter->device()->height());
916 painter->beginNativePainting();
919 if (m_dynamicCubemap)
922 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
924 glMatrixMode(GL_PROJECTION);
925 qgluPerspective(60.0, width / height, 0.01, 15.0);
927 glMatrixMode(GL_MODELVIEW);
930 view.rotate(m_trackBalls[2].rotation());
931 view(2, 3) -= 2.0f * exp(m_distExp / 1200.0f);
937 painter->endNativePainting();
940 QPointF Scene::pixelPosToViewPos(const QPointF& p)
942 return QPointF(2.0 * float(p.x()) / width() - 1.0,
943 1.0 - 2.0 * float(p.y()) / height());
946 void Scene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
948 QGraphicsScene::mouseMoveEvent(event);
949 if (event->isAccepted())
952 if (event->buttons() & Qt::LeftButton) {
953 m_trackBalls[0].move(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate());
956 m_trackBalls[0].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate());
959 if (event->buttons() & Qt::RightButton) {
960 m_trackBalls[1].move(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate());
963 m_trackBalls[1].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate());
966 if (event->buttons() & Qt::MidButton) {
967 m_trackBalls[2].move(pixelPosToViewPos(event->scenePos()), QQuaternion());
970 m_trackBalls[2].release(pixelPosToViewPos(event->scenePos()), QQuaternion());
974 void Scene::mousePressEvent(QGraphicsSceneMouseEvent *event)
976 QGraphicsScene::mousePressEvent(event);
977 if (event->isAccepted())
980 if (event->buttons() & Qt::LeftButton) {
981 m_trackBalls[0].push(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate());
985 if (event->buttons() & Qt::RightButton) {
986 m_trackBalls[1].push(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate());
990 if (event->buttons() & Qt::MidButton) {
991 m_trackBalls[2].push(pixelPosToViewPos(event->scenePos()), QQuaternion());
996 void Scene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
998 QGraphicsScene::mouseReleaseEvent(event);
999 if (event->isAccepted())
1002 if (event->button() == Qt::LeftButton) {
1003 m_trackBalls[0].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate());
1007 if (event->button() == Qt::RightButton) {
1008 m_trackBalls[1].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate());
1012 if (event->button() == Qt::MidButton) {
1013 m_trackBalls[2].release(pixelPosToViewPos(event->scenePos()), QQuaternion());
1018 void Scene::wheelEvent(QGraphicsSceneWheelEvent * event)
1020 QGraphicsScene::wheelEvent(event);
1021 if (!event->isAccepted()) {
1022 m_distExp += event->delta();
1023 if (m_distExp < -8 * 120)
1024 m_distExp = -8 * 120;
1025 if (m_distExp > 10 * 120)
1026 m_distExp = 10 * 120;
1031 void Scene::setShader(int index)
1033 if (index >= 0 && index < m_fragmentShaders.size())
1034 m_currentShader = index;
1037 void Scene::setTexture(int index)
1039 if (index >= 0 && index < m_textures.size())
1040 m_currentTexture = index;
1043 void Scene::toggleDynamicCubemap(int state)
1045 if ((m_dynamicCubemap = (state == Qt::Checked)))
1046 m_updateAllCubemaps = true;
1049 void Scene::setColorParameter(const QString &name, QRgb color)
1051 // set the color in all programs
1052 foreach (QGLShaderProgram *program, m_programs) {
1054 program->setUniformValue(program->uniformLocation(name), QColor(color));
1059 void Scene::setFloatParameter(const QString &name, float value)
1061 // set the color in all programs
1062 foreach (QGLShaderProgram *program, m_programs) {
1064 program->setUniformValue(program->uniformLocation(name), value);
1069 void Scene::newItem(ItemDialog::ItemType type)
1071 QSize size = sceneRect().size().toSize();
1073 case ItemDialog::QtBoxItem:
1074 addItem(new QtBox(64, rand() % (size.width() - 64) + 32, rand() % (size.height() - 64) + 32));
1076 case ItemDialog::CircleItem:
1077 addItem(new CircleItem(64, rand() % (size.width() - 64) + 32, rand() % (size.height() - 64) + 32));
1079 case ItemDialog::SquareItem:
1080 addItem(new SquareItem(64, rand() % (size.width() - 64) + 32, rand() % (size.height() - 64) + 32));