demos/boxes/scene.cpp
changeset 0 1918ee327afb
child 3 41300fa6a67c
equal deleted inserted replaced
-1:000000000000 0:1918ee327afb
       
     1 /****************************************************************************
       
     2 **
       
     3 ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
       
     4 ** All rights reserved.
       
     5 ** Contact: Nokia Corporation (qt-info@nokia.com)
       
     6 **
       
     7 ** This file is part of the demonstration applications of the Qt Toolkit.
       
     8 **
       
     9 ** $QT_BEGIN_LICENSE:LGPL$
       
    10 ** No Commercial Usage
       
    11 ** This file contains pre-release code and may not be distributed.
       
    12 ** You may use this file in accordance with the terms and conditions
       
    13 ** contained in the Technology Preview License Agreement accompanying
       
    14 ** this package.
       
    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 ** If you have questions regarding the use of this file, please contact
       
    29 ** Nokia at qt-info@nokia.com.
       
    30 **
       
    31 **
       
    32 **
       
    33 **
       
    34 **
       
    35 **
       
    36 **
       
    37 **
       
    38 ** $QT_END_LICENSE$
       
    39 **
       
    40 ****************************************************************************/
       
    41 
       
    42 #include <QDebug>
       
    43 #include "scene.h"
       
    44 #include <QtGui/qmatrix4x4.h>
       
    45 #include <QtGui/qvector3d.h>
       
    46 
       
    47 #include "3rdparty/fbm.h"
       
    48 
       
    49 void checkGLErrors(const QString& prefix)
       
    50 {
       
    51     switch (glGetError()) {
       
    52     case GL_NO_ERROR:
       
    53         //qDebug() << prefix << tr("No error.");
       
    54         break;
       
    55     case GL_INVALID_ENUM:
       
    56         qDebug() << prefix << QObject::tr("Invalid enum.");
       
    57         break;
       
    58     case GL_INVALID_VALUE:
       
    59         qDebug() << prefix << QObject::tr("Invalid value.");
       
    60         break;
       
    61     case GL_INVALID_OPERATION:
       
    62         qDebug() << prefix << QObject::tr("Invalid operation.");
       
    63         break;
       
    64     case GL_STACK_OVERFLOW:
       
    65         qDebug() << prefix << QObject::tr("Stack overflow.");
       
    66         break;
       
    67     case GL_STACK_UNDERFLOW:
       
    68         qDebug() << prefix << QObject::tr("Stack underflow.");
       
    69         break;
       
    70     case GL_OUT_OF_MEMORY:
       
    71         qDebug() << prefix << QObject::tr("Out of memory.");
       
    72         break;
       
    73     default:
       
    74         qDebug() << prefix << QObject::tr("Unknown error.");
       
    75         break;
       
    76     }
       
    77 }
       
    78 
       
    79 //============================================================================//
       
    80 //                                  ColorEdit                                 //
       
    81 //============================================================================//
       
    82 
       
    83 ColorEdit::ColorEdit(QRgb initialColor, int id)
       
    84     : m_color(initialColor), m_id(id)
       
    85 {
       
    86     QHBoxLayout *layout = new QHBoxLayout;
       
    87     setLayout(layout);
       
    88     layout->setContentsMargins(0, 0, 0, 0);
       
    89 
       
    90     m_lineEdit = new QLineEdit(QString::number(m_color, 16));
       
    91     layout->addWidget(m_lineEdit);
       
    92 
       
    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);
       
   102 
       
   103     connect(m_lineEdit, SIGNAL(editingFinished()), this, SLOT(editDone()));
       
   104 }
       
   105 
       
   106 void ColorEdit::editDone()
       
   107 {
       
   108     bool ok;
       
   109     QRgb newColor = m_lineEdit->text().toUInt(&ok, 16);
       
   110     if (ok)
       
   111         setColor(newColor);
       
   112 }
       
   113 
       
   114 void ColorEdit::mousePressEvent(QMouseEvent *event)
       
   115 {
       
   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
       
   121 #ifdef Q_WS_MAC
       
   122         dialog.setOption(QColorDialog::DontUseNativeDialog, true);
       
   123 #endif
       
   124         dialog.move(280, 120);
       
   125         if (dialog.exec() == QDialog::Rejected)
       
   126             return;
       
   127         QRgb newColor = dialog.selectedColor().rgba();
       
   128         if (newColor == m_color)
       
   129             return;
       
   130         setColor(newColor);
       
   131     }
       
   132 }
       
   133 
       
   134 void ColorEdit::setColor(QRgb color)
       
   135 {
       
   136     m_color = 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);
       
   142 }
       
   143 
       
   144 //============================================================================//
       
   145 //                                  FloatEdit                                 //
       
   146 //============================================================================//
       
   147 
       
   148 FloatEdit::FloatEdit(float initialValue, int id)
       
   149     : m_value(initialValue), m_id(id)
       
   150 {
       
   151     QHBoxLayout *layout = new QHBoxLayout;
       
   152     setLayout(layout);
       
   153     layout->setContentsMargins(0, 0, 0, 0);
       
   154 
       
   155     m_lineEdit = new QLineEdit(QString::number(m_value));
       
   156     layout->addWidget(m_lineEdit);
       
   157 
       
   158     connect(m_lineEdit, SIGNAL(editingFinished()), this, SLOT(editDone()));
       
   159 }
       
   160 
       
   161 void FloatEdit::editDone()
       
   162 {
       
   163     bool ok;
       
   164     float newValue = m_lineEdit->text().toFloat(&ok);
       
   165     if (ok) {
       
   166         m_value = newValue;
       
   167         m_lineEdit->setText(QString::number(m_value)); // "Clean up" text
       
   168         emit valueChanged(m_value, m_id);
       
   169     }
       
   170 }
       
   171 
       
   172 //============================================================================//
       
   173 //                           TwoSidedGraphicsWidget                           //
       
   174 //============================================================================//
       
   175 
       
   176 TwoSidedGraphicsWidget::TwoSidedGraphicsWidget(QGraphicsScene *scene)
       
   177     : QObject(scene)
       
   178     , m_current(0)
       
   179     , m_angle(0)
       
   180     , m_delta(0)
       
   181 {
       
   182     for (int i = 0; i < 2; ++i)
       
   183         m_proxyWidgets[i] = 0;
       
   184 }
       
   185 
       
   186 void TwoSidedGraphicsWidget::setWidget(int index, QWidget *widget)
       
   187 {
       
   188     if (index < 0 || index >= 2)
       
   189 	{
       
   190 		qWarning("TwoSidedGraphicsWidget::setWidget: Index out of bounds, index == %d", index);
       
   191 		return;
       
   192 	}
       
   193 
       
   194     GraphicsWidget *proxy = new GraphicsWidget;
       
   195     proxy->setWidget(widget);
       
   196 
       
   197     if (m_proxyWidgets[index])
       
   198         delete m_proxyWidgets[index];
       
   199     m_proxyWidgets[index] = proxy;
       
   200 
       
   201     proxy->setCacheMode(QGraphicsItem::ItemCoordinateCache);
       
   202     proxy->setZValue(1e30); // Make sure the dialog is drawn on top of all other (OpenGL) items
       
   203 
       
   204     if (index != m_current)
       
   205         proxy->setVisible(false);
       
   206 
       
   207     qobject_cast<QGraphicsScene *>(parent())->addItem(proxy);
       
   208 }
       
   209 
       
   210 QWidget *TwoSidedGraphicsWidget::widget(int index)
       
   211 {
       
   212     if (index < 0 || index >= 2)
       
   213 	{
       
   214 		qWarning("TwoSidedGraphicsWidget::widget: Index out of bounds, index == %d", index);
       
   215 		return 0;
       
   216 	}
       
   217     return m_proxyWidgets[index]->widget();
       
   218 }
       
   219 
       
   220 void TwoSidedGraphicsWidget::flip()
       
   221 {
       
   222     m_delta = (m_current == 0 ? 9 : -9);
       
   223     animateFlip();
       
   224 }
       
   225 
       
   226 void TwoSidedGraphicsWidget::animateFlip()
       
   227 {
       
   228     m_angle += m_delta;
       
   229     if (m_angle == 90) {
       
   230         int old = m_current;
       
   231         m_current ^= 1;
       
   232         m_proxyWidgets[old]->setVisible(false);
       
   233         m_proxyWidgets[m_current]->setVisible(true);
       
   234         m_proxyWidgets[m_current]->setGeometry(m_proxyWidgets[old]->geometry());
       
   235     }
       
   236 
       
   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));
       
   242 
       
   243     if ((m_current == 0 && m_angle > 0) || (m_current == 1 && m_angle < 180))
       
   244         QTimer::singleShot(25, this, SLOT(animateFlip()));
       
   245 }
       
   246 
       
   247 QVariant GraphicsWidget::itemChange(GraphicsItemChange change, const QVariant &value)
       
   248 {
       
   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());
       
   261         return pos;
       
   262     }
       
   263     return QGraphicsProxyWidget::itemChange(change, value);
       
   264 }
       
   265 
       
   266 void GraphicsWidget::resizeEvent(QGraphicsSceneResizeEvent *event)
       
   267 {
       
   268     setCacheMode(QGraphicsItem::NoCache);
       
   269     setCacheMode(QGraphicsItem::ItemCoordinateCache);
       
   270     QGraphicsProxyWidget::resizeEvent(event);
       
   271 }
       
   272 
       
   273 void GraphicsWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
       
   274 {
       
   275     painter->setRenderHint(QPainter::Antialiasing, false);
       
   276     QGraphicsProxyWidget::paint(painter, option, widget);
       
   277     //painter->setRenderHint(QPainter::Antialiasing, true);
       
   278 }
       
   279 
       
   280 //============================================================================//
       
   281 //                             RenderOptionsDialog                            //
       
   282 //============================================================================//
       
   283 
       
   284 RenderOptionsDialog::RenderOptionsDialog()
       
   285     : QDialog(0, Qt::CustomizeWindowHint | Qt::WindowTitleHint)
       
   286 {
       
   287     setWindowOpacity(0.75);
       
   288     setWindowTitle(tr("Options (double click to flip)"));
       
   289     QGridLayout *layout = new QGridLayout;
       
   290     setLayout(layout);
       
   291     layout->setColumnStretch(1, 1);
       
   292 
       
   293     int row = 0;
       
   294 
       
   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);
       
   301     ++row;
       
   302 
       
   303     QPalette palette;
       
   304 
       
   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);
       
   310 
       
   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())
       
   318                     continue;
       
   319                 QByteArray type = *it;
       
   320                 if (++it == tokens.end())
       
   321                     continue;
       
   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
       
   333                         ++counter[j];
       
   334                         while (j > 0 && counter[j] > '9') {
       
   335                             counter[j] = '0';
       
   336                             ++counter[--j];
       
   337                         }
       
   338                         if (j < counterPos)
       
   339                             counterPos = j;
       
   340                     }
       
   341 
       
   342                     if (type == "color") {
       
   343                         layout->addWidget(new QLabel(m_parameterNames.back()));
       
   344                         bool ok;
       
   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)));
       
   349                         ++row;
       
   350                     } else if (type == "float") {
       
   351                         layout->addWidget(new QLabel(m_parameterNames.back()));
       
   352                         bool ok;
       
   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)));
       
   357                         ++row;
       
   358                     }
       
   359                 }
       
   360             }
       
   361             file.close();
       
   362         }
       
   363     }
       
   364 
       
   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);
       
   369     ++row;
       
   370 
       
   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);
       
   375     ++row;
       
   376 
       
   377     layout->setRowStretch(row, 1);
       
   378 }
       
   379 
       
   380 int RenderOptionsDialog::addTexture(const QString &name)
       
   381 {
       
   382     m_textureCombo->addItem(name);
       
   383     return m_textureCombo->count() - 1;
       
   384 }
       
   385 
       
   386 int RenderOptionsDialog::addShader(const QString &name)
       
   387 {
       
   388     m_shaderCombo->addItem(name);
       
   389     return m_shaderCombo->count() - 1;
       
   390 }
       
   391 
       
   392 void RenderOptionsDialog::emitParameterChanged()
       
   393 {
       
   394     foreach (ParameterEdit *edit, m_parameterEdits)
       
   395         edit->emitChange();
       
   396 }
       
   397 
       
   398 void RenderOptionsDialog::setColorParameter(QRgb color, int id)
       
   399 {
       
   400     emit colorParameterChanged(m_parameterNames[id], color);
       
   401 }
       
   402 
       
   403 void RenderOptionsDialog::setFloatParameter(float value, int id)
       
   404 {
       
   405     emit floatParameterChanged(m_parameterNames[id], value);
       
   406 }
       
   407 
       
   408 void RenderOptionsDialog::mouseDoubleClickEvent(QMouseEvent *event)
       
   409 {
       
   410     if (event->button() == Qt::LeftButton)
       
   411         emit doubleClicked();
       
   412 }
       
   413 
       
   414 //============================================================================//
       
   415 //                                 ItemDialog                                 //
       
   416 //============================================================================//
       
   417 
       
   418 ItemDialog::ItemDialog()
       
   419     : QDialog(0, Qt::CustomizeWindowHint | Qt::WindowTitleHint)
       
   420 {
       
   421     setWindowTitle(tr("Items (double click to flip)"));
       
   422     setWindowOpacity(0.75);
       
   423     resize(160, 100);
       
   424 
       
   425     QVBoxLayout *layout = new QVBoxLayout;
       
   426     setLayout(layout);
       
   427     QPushButton *button;
       
   428 
       
   429     button = new QPushButton(tr("Add Qt box"));
       
   430     layout->addWidget(button);
       
   431     connect(button, SIGNAL(clicked()), this, SLOT(triggerNewQtBox()));
       
   432 
       
   433     button = new QPushButton(tr("Add circle"));
       
   434     layout->addWidget(button);
       
   435     connect(button, SIGNAL(clicked()), this, SLOT(triggerNewCircleItem()));
       
   436 
       
   437     button = new QPushButton(tr("Add square"));
       
   438     layout->addWidget(button);
       
   439     connect(button, SIGNAL(clicked()), this, SLOT(triggerNewSquareItem()));
       
   440 
       
   441     layout->addStretch(1);
       
   442 }
       
   443 
       
   444 void ItemDialog::triggerNewQtBox()
       
   445 {
       
   446     emit newItemTriggered(QtBoxItem);
       
   447 }
       
   448 
       
   449 void ItemDialog::triggerNewCircleItem()
       
   450 {
       
   451     emit newItemTriggered(CircleItem);
       
   452 }
       
   453 
       
   454 void ItemDialog::triggerNewSquareItem()
       
   455 {
       
   456     emit newItemTriggered(SquareItem);
       
   457 }
       
   458 
       
   459 void ItemDialog::mouseDoubleClickEvent(QMouseEvent *event)
       
   460 {
       
   461     if (event->button() == Qt::LeftButton)
       
   462         emit doubleClicked();
       
   463 }
       
   464 
       
   465 //============================================================================//
       
   466 //                                    Scene                                   //
       
   467 //============================================================================//
       
   468 
       
   469 const static char environmentShaderText[] =
       
   470     "uniform samplerCube env;"
       
   471     "void main() {"
       
   472         "gl_FragColor = textureCube(env, gl_TexCoord[1].xyz);"
       
   473     "}";
       
   474 
       
   475 Scene::Scene(int width, int height, int maxTextureSize)
       
   476     : m_distExp(600)
       
   477     , m_frame(0)
       
   478     , m_maxTextureSize(maxTextureSize)
       
   479     , m_currentShader(0)
       
   480     , m_currentTexture(0)
       
   481     , m_dynamicCubemap(false)
       
   482     , m_updateAllCubemaps(true)
       
   483     , m_box(0)
       
   484     , m_vertexShader(0)
       
   485     , m_environmentShader(0)
       
   486     , m_environmentProgram(0)
       
   487 {
       
   488     setSceneRect(0, 0, width, height);
       
   489 
       
   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);
       
   493 
       
   494     m_renderOptions = new RenderOptionsDialog;
       
   495     m_renderOptions->move(20, 120);
       
   496     m_renderOptions->resize(m_renderOptions->sizeHint());
       
   497 
       
   498     connect(m_renderOptions, SIGNAL(dynamicCubemapToggled(int)), this, SLOT(toggleDynamicCubemap(int)));
       
   499     connect(m_renderOptions, SIGNAL(colorParameterChanged(const QString &, QRgb)), this, SLOT(setColorParameter(const QString &, QRgb)));
       
   500     connect(m_renderOptions, SIGNAL(floatParameterChanged(const QString &, float)), this, SLOT(setFloatParameter(const QString &, float)));
       
   501     connect(m_renderOptions, SIGNAL(textureChanged(int)), this, SLOT(setTexture(int)));
       
   502     connect(m_renderOptions, SIGNAL(shaderChanged(int)), this, SLOT(setShader(int)));
       
   503 
       
   504     m_itemDialog = new ItemDialog;
       
   505     connect(m_itemDialog, SIGNAL(newItemTriggered(ItemDialog::ItemType)), this, SLOT(newItem(ItemDialog::ItemType)));
       
   506 
       
   507     TwoSidedGraphicsWidget *twoSided = new TwoSidedGraphicsWidget(this);
       
   508     twoSided->setWidget(0, m_renderOptions);
       
   509     twoSided->setWidget(1, m_itemDialog);
       
   510 
       
   511     connect(m_renderOptions, SIGNAL(doubleClicked()), twoSided, SLOT(flip()));
       
   512     connect(m_itemDialog, SIGNAL(doubleClicked()), twoSided, SLOT(flip()));
       
   513 
       
   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));
       
   518 
       
   519     initGL();
       
   520 
       
   521     m_timer = new QTimer(this);
       
   522     m_timer->setInterval(20);
       
   523     connect(m_timer, SIGNAL(timeout()), this, SLOT(update()));
       
   524     m_timer->start();
       
   525 
       
   526     m_time.start();
       
   527 }
       
   528 
       
   529 Scene::~Scene()
       
   530 {
       
   531     if (m_box)
       
   532         delete m_box;
       
   533     foreach (GLTexture *texture, m_textures)
       
   534         if (texture) delete texture;
       
   535     if (m_mainCubemap)
       
   536         delete m_mainCubemap;
       
   537     foreach (QGLShaderProgram *program, m_programs)
       
   538         if (program) delete program;
       
   539     if (m_vertexShader)
       
   540         delete m_vertexShader;
       
   541     foreach (QGLShader *shader, m_fragmentShaders)
       
   542         if (shader) delete shader;
       
   543     foreach (GLRenderTargetCube *rt, m_cubemaps)
       
   544         if (rt) delete rt;
       
   545     if (m_environmentShader)
       
   546         delete m_environmentShader;
       
   547     if (m_environmentProgram)
       
   548         delete m_environmentProgram;
       
   549 }
       
   550 
       
   551 void Scene::initGL()
       
   552 {
       
   553     m_box = new GLRoundedBox(0.25f, 1.0f, 10);
       
   554 
       
   555     m_vertexShader = new QGLShader(":/res/boxes/basic.vsh", QGLShader::VertexShader);
       
   556 
       
   557     QStringList list;
       
   558     list << ":/res/boxes/cubemap_posx.jpg" << ":/res/boxes/cubemap_negx.jpg" << ":/res/boxes/cubemap_posy.jpg"
       
   559          << ":/res/boxes/cubemap_negy.jpg" << ":/res/boxes/cubemap_posz.jpg" << ":/res/boxes/cubemap_negz.jpg";
       
   560     m_environment = new GLTextureCube(list, qMin(1024, m_maxTextureSize));
       
   561     m_environmentShader = new QGLShader(QGLShader::FragmentShader);
       
   562     m_environmentShader->compile(environmentShaderText);
       
   563     m_environmentProgram = new QGLShaderProgram;
       
   564     m_environmentProgram->addShader(m_vertexShader);
       
   565     m_environmentProgram->addShader(m_environmentShader);
       
   566     m_environmentProgram->link();
       
   567 
       
   568     const int NOISE_SIZE = 128; // for a different size, B and BM in fbm.c must also be changed
       
   569     m_noise = new GLTexture3D(NOISE_SIZE, NOISE_SIZE, NOISE_SIZE); 
       
   570     QRgb *data = new QRgb[NOISE_SIZE * NOISE_SIZE * NOISE_SIZE];
       
   571     memset(data, 0, NOISE_SIZE * NOISE_SIZE * NOISE_SIZE * sizeof(QRgb));
       
   572     QRgb *p = data;
       
   573     float pos[3];
       
   574     for (int k = 0; k < NOISE_SIZE; ++k) {
       
   575         pos[2] = k * (0x20 / (float)NOISE_SIZE);
       
   576         for (int j = 0; j < NOISE_SIZE; ++j) {
       
   577             for (int i = 0; i < NOISE_SIZE; ++i) {
       
   578                 for (int byte = 0; byte < 4; ++byte) {
       
   579                     pos[0] = (i + (byte & 1) * 16) * (0x20 / (float)NOISE_SIZE);
       
   580                     pos[1] = (j + (byte & 2) * 8) * (0x20 / (float)NOISE_SIZE);
       
   581                     *p |= (int)(128.0f * (noise3(pos) + 1.0f)) << (byte * 8);
       
   582                 }
       
   583                 ++p;
       
   584             }
       
   585         }
       
   586     }
       
   587     m_noise->load(NOISE_SIZE, NOISE_SIZE, NOISE_SIZE, data);
       
   588     delete[] data;
       
   589 
       
   590     m_mainCubemap = new GLRenderTargetCube(512);
       
   591 
       
   592     QStringList filter;
       
   593     QList<QFileInfo> files;
       
   594 
       
   595     // Load all .png files as textures
       
   596     m_currentTexture = 0;
       
   597     filter = QStringList("*.png");
       
   598     files = QDir(":/res/boxes/").entryInfoList(filter, QDir::Files | QDir::Readable);
       
   599 
       
   600     foreach (QFileInfo file, files) {
       
   601         GLTexture *texture = new GLTexture2D(file.absoluteFilePath(), qMin(256, m_maxTextureSize), qMin(256, m_maxTextureSize));
       
   602         if (texture->failed()) {
       
   603             delete texture;
       
   604             continue;
       
   605         }
       
   606         m_textures << texture;
       
   607         m_renderOptions->addTexture(file.baseName());
       
   608     }
       
   609 
       
   610     if (m_textures.size() == 0)
       
   611         m_textures << new GLTexture2D(qMin(64, m_maxTextureSize), qMin(64, m_maxTextureSize));
       
   612 
       
   613     // Load all .fsh files as fragment shaders
       
   614     m_currentShader = 0;
       
   615     filter = QStringList("*.fsh");
       
   616     files = QDir(":/res/boxes/").entryInfoList(filter, QDir::Files | QDir::Readable);
       
   617     foreach (QFileInfo file, files) {
       
   618         QGLShaderProgram *program = new QGLShaderProgram;
       
   619         QGLShader* shader = new QGLShader(file.absoluteFilePath(), QGLShader::FragmentShader);
       
   620         // The program does not take ownership over the shaders, so store them in a vector so they can be deleted afterwards.
       
   621         program->addShader(m_vertexShader);
       
   622         program->addShader(shader);
       
   623         if (!program->link()) {
       
   624             qWarning("Failed to compile and link shader program");
       
   625             qWarning("Vertex shader log:");
       
   626             qWarning() << m_vertexShader->log();
       
   627             qWarning() << "Fragment shader log ( file =" << file.absoluteFilePath() << "):";
       
   628             qWarning() << shader->log();
       
   629             qWarning("Shader program log:");
       
   630             qWarning() << program->log();
       
   631 
       
   632             delete shader;
       
   633             delete program;
       
   634             continue;
       
   635         }
       
   636 
       
   637         m_fragmentShaders << shader;
       
   638         m_programs << program;
       
   639         m_renderOptions->addShader(file.baseName());
       
   640 
       
   641         program->enable();
       
   642         m_cubemaps << ((program->uniformLocation("env") != -1) ? new GLRenderTargetCube(qMin(256, m_maxTextureSize)) : 0);
       
   643         program->disable();
       
   644     }
       
   645 
       
   646     if (m_programs.size() == 0)
       
   647         m_programs << new QGLShaderProgram;
       
   648 
       
   649     m_renderOptions->emitParameterChanged();
       
   650 }
       
   651 
       
   652 static void loadMatrix(const QMatrix4x4& m)
       
   653 {
       
   654     GLfloat mat[16];
       
   655     const qreal *data = m.constData();
       
   656     for (int index = 0; index < 16; ++index)
       
   657         mat[index] = data[index];
       
   658     glLoadMatrixf(mat);
       
   659 }
       
   660 
       
   661 static void multMatrix(const QMatrix4x4& m)
       
   662 {
       
   663     GLfloat mat[16];
       
   664     const qreal *data = m.constData();
       
   665     for (int index = 0; index < 16; ++index)
       
   666         mat[index] = data[index];
       
   667     glMultMatrixf(mat);
       
   668 }
       
   669 
       
   670 // If one of the boxes should not be rendered, set excludeBox to its index.
       
   671 // If the main box should not be rendered, set excludeBox to -1.
       
   672 void Scene::renderBoxes(const QMatrix4x4 &view, int excludeBox)
       
   673 {
       
   674     QMatrix4x4 invView = view.inverted();
       
   675 
       
   676     // If multi-texturing is supported, use three saplers.
       
   677     if (glActiveTexture) {
       
   678         glActiveTexture(GL_TEXTURE0);
       
   679         m_textures[m_currentTexture]->bind();
       
   680         glActiveTexture(GL_TEXTURE2);
       
   681         m_noise->bind();
       
   682         glActiveTexture(GL_TEXTURE1);
       
   683     } else {
       
   684         m_textures[m_currentTexture]->bind();
       
   685     }
       
   686 
       
   687     glDisable(GL_LIGHTING);
       
   688     glDisable(GL_CULL_FACE);
       
   689 
       
   690     QMatrix4x4 viewRotation(view);
       
   691     viewRotation(3, 0) = viewRotation(3, 1) = viewRotation(3, 2) = 0.0f;
       
   692     viewRotation(0, 3) = viewRotation(1, 3) = viewRotation(2, 3) = 0.0f;
       
   693     viewRotation(3, 3) = 1.0f;
       
   694     loadMatrix(viewRotation);
       
   695     glScalef(20.0f, 20.0f, 20.0f);
       
   696 
       
   697     // Don't render the environment if the environment texture can't be set for the correct sampler.
       
   698     if (glActiveTexture) {
       
   699         m_environment->bind();
       
   700         m_environmentProgram->enable();
       
   701         m_environmentProgram->setUniformValue("tex", GLint(0));
       
   702         m_environmentProgram->setUniformValue("env", GLint(1));
       
   703         m_environmentProgram->setUniformValue("noise", GLint(2));
       
   704         m_box->draw();
       
   705         m_environmentProgram->disable();
       
   706         m_environment->unbind();
       
   707     }
       
   708 
       
   709     loadMatrix(view);
       
   710 
       
   711     glEnable(GL_CULL_FACE);
       
   712     glEnable(GL_LIGHTING);
       
   713 
       
   714     for (int i = 0; i < m_programs.size(); ++i) {
       
   715         if (i == excludeBox)
       
   716             continue;
       
   717 
       
   718         glPushMatrix();
       
   719         QMatrix4x4 m;
       
   720         m.rotate(m_trackBalls[1].rotation());
       
   721         multMatrix(m);
       
   722 
       
   723         glRotatef(360.0f * i / m_programs.size(), 0.0f, 0.0f, 1.0f);
       
   724         glTranslatef(2.0f, 0.0f, 0.0f);
       
   725         glScalef(0.3f, 0.6f, 0.6f);
       
   726 
       
   727         if (glActiveTexture) {
       
   728             if (m_dynamicCubemap && m_cubemaps[i])
       
   729                 m_cubemaps[i]->bind();
       
   730             else
       
   731                 m_environment->bind();
       
   732         }
       
   733         m_programs[i]->enable();
       
   734         m_programs[i]->setUniformValue("tex", GLint(0));
       
   735         m_programs[i]->setUniformValue("env", GLint(1));
       
   736         m_programs[i]->setUniformValue("noise", GLint(2));
       
   737         m_programs[i]->setUniformValue("view", view);
       
   738         m_programs[i]->setUniformValue("invView", invView);
       
   739         m_box->draw();
       
   740         m_programs[i]->disable();
       
   741 
       
   742         if (glActiveTexture) {
       
   743             if (m_dynamicCubemap && m_cubemaps[i])
       
   744                 m_cubemaps[i]->unbind();
       
   745             else
       
   746                 m_environment->unbind();
       
   747         }
       
   748         glPopMatrix();
       
   749     }
       
   750 
       
   751     if (-1 != excludeBox) {
       
   752         QMatrix4x4 m;
       
   753         m.rotate(m_trackBalls[0].rotation());
       
   754         multMatrix(m);
       
   755 
       
   756         if (glActiveTexture) {
       
   757             if (m_dynamicCubemap)
       
   758                 m_mainCubemap->bind();
       
   759             else
       
   760                 m_environment->bind();
       
   761         }
       
   762 
       
   763         m_programs[m_currentShader]->enable();
       
   764         m_programs[m_currentShader]->setUniformValue("tex", GLint(0));
       
   765         m_programs[m_currentShader]->setUniformValue("env", GLint(1));
       
   766         m_programs[m_currentShader]->setUniformValue("noise", GLint(2));
       
   767         m_programs[m_currentShader]->setUniformValue("view", view);
       
   768         m_programs[m_currentShader]->setUniformValue("invView", invView);
       
   769         m_box->draw();
       
   770         m_programs[m_currentShader]->disable();
       
   771 
       
   772         if (glActiveTexture) {
       
   773             if (m_dynamicCubemap)
       
   774                 m_mainCubemap->unbind();
       
   775             else
       
   776                 m_environment->unbind();
       
   777         }
       
   778     }
       
   779 
       
   780     if (glActiveTexture) {
       
   781         glActiveTexture(GL_TEXTURE2);
       
   782         m_noise->unbind();
       
   783         glActiveTexture(GL_TEXTURE0);
       
   784     }
       
   785     m_textures[m_currentTexture]->unbind();
       
   786 }
       
   787 
       
   788 void Scene::setStates()
       
   789 {
       
   790     //glClearColor(0.25f, 0.25f, 0.5f, 1.0f);
       
   791 
       
   792     glEnable(GL_DEPTH_TEST);
       
   793     glEnable(GL_CULL_FACE);
       
   794     glEnable(GL_LIGHTING);
       
   795     //glEnable(GL_COLOR_MATERIAL);
       
   796     glEnable(GL_TEXTURE_2D);
       
   797     glEnable(GL_NORMALIZE);
       
   798 
       
   799     glMatrixMode(GL_PROJECTION);
       
   800     glPushMatrix();
       
   801     glLoadIdentity();
       
   802 
       
   803     glMatrixMode(GL_MODELVIEW);
       
   804     glPushMatrix();
       
   805     glLoadIdentity();
       
   806 
       
   807     setLights();
       
   808 
       
   809     float materialSpecular[] = {0.5f, 0.5f, 0.5f, 1.0f};
       
   810     glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, materialSpecular);
       
   811     glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 32.0f);
       
   812 }
       
   813 
       
   814 void Scene::setLights()
       
   815 {
       
   816     glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
       
   817     //float lightColour[] = {1.0f, 1.0f, 1.0f, 1.0f};
       
   818     float lightDir[] = {0.0f, 0.0f, 1.0f, 0.0f};
       
   819     //glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColour);
       
   820     //glLightfv(GL_LIGHT0, GL_SPECULAR, lightColour);
       
   821     glLightfv(GL_LIGHT0, GL_POSITION, lightDir);
       
   822     glLightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER, 1.0f);
       
   823     glEnable(GL_LIGHT0);
       
   824 }
       
   825 
       
   826 void Scene::defaultStates()
       
   827 {
       
   828     //glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
       
   829 
       
   830     glDisable(GL_DEPTH_TEST);
       
   831     glDisable(GL_CULL_FACE);
       
   832     glDisable(GL_LIGHTING);
       
   833     //glDisable(GL_COLOR_MATERIAL);
       
   834     glDisable(GL_TEXTURE_2D);
       
   835     glDisable(GL_LIGHT0);
       
   836     glDisable(GL_NORMALIZE);
       
   837 
       
   838     glMatrixMode(GL_MODELVIEW);
       
   839     glPopMatrix();
       
   840 
       
   841     glMatrixMode(GL_PROJECTION);
       
   842     glPopMatrix();
       
   843 
       
   844     glLightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER, 0.0f);
       
   845     float defaultMaterialSpecular[] = {0.0f, 0.0f, 0.0f, 1.0f};
       
   846     glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, defaultMaterialSpecular);
       
   847     glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 0.0f);
       
   848 }
       
   849 
       
   850 void Scene::renderCubemaps()
       
   851 {
       
   852     // To speed things up, only update the cubemaps for the small cubes every N frames.
       
   853     const int N = (m_updateAllCubemaps ? 1 : 3);
       
   854 
       
   855     QMatrix4x4 mat;
       
   856     GLRenderTargetCube::getProjectionMatrix(mat, 0.1f, 100.0f);
       
   857 
       
   858     glMatrixMode(GL_PROJECTION);
       
   859     glPushMatrix();
       
   860     loadMatrix(mat);
       
   861 
       
   862     glMatrixMode(GL_MODELVIEW);
       
   863     glPushMatrix();
       
   864 
       
   865     QVector3D center;
       
   866 
       
   867     for (int i = m_frame % N; i < m_cubemaps.size(); i += N) {
       
   868         if (0 == m_cubemaps[i])
       
   869             continue;
       
   870 
       
   871         float angle = 2.0f * PI * i / m_cubemaps.size();
       
   872 
       
   873         center = m_trackBalls[1].rotation().rotateVector(QVector3D(cos(angle), sin(angle), 0.0f));
       
   874 
       
   875         for (int face = 0; face < 6; ++face) {
       
   876             m_cubemaps[i]->begin(face);
       
   877 
       
   878             GLRenderTargetCube::getViewMatrix(mat, face);
       
   879             QVector4D v = QVector4D(-center.x(), -center.y(), -center.z(), 1.0);
       
   880             mat.setColumn(3, mat * v);
       
   881 
       
   882             glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
       
   883             renderBoxes(mat, i);
       
   884 
       
   885             m_cubemaps[i]->end();
       
   886         }
       
   887     }
       
   888 
       
   889     for (int face = 0; face < 6; ++face) {
       
   890         m_mainCubemap->begin(face);
       
   891         GLRenderTargetCube::getViewMatrix(mat, face);
       
   892 
       
   893         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
       
   894         renderBoxes(mat, -1);
       
   895 
       
   896         m_mainCubemap->end();
       
   897     }
       
   898 
       
   899     glPopMatrix();
       
   900 
       
   901     glMatrixMode(GL_PROJECTION);
       
   902     glPopMatrix();
       
   903 
       
   904     m_updateAllCubemaps = false;
       
   905 }
       
   906 
       
   907 void Scene::drawBackground(QPainter *painter, const QRectF &)
       
   908 {
       
   909     float width = float(painter->device()->width());
       
   910     float height = float(painter->device()->height());
       
   911 
       
   912     painter->beginNativePainting();
       
   913     setStates();
       
   914 
       
   915     if (m_dynamicCubemap)
       
   916         renderCubemaps();
       
   917 
       
   918     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
       
   919 
       
   920     glMatrixMode(GL_PROJECTION);
       
   921     gluPerspective(60.0, width / height, 0.01, 15.0);
       
   922 
       
   923     glMatrixMode(GL_MODELVIEW);
       
   924 
       
   925     QMatrix4x4 view;
       
   926     view.rotate(m_trackBalls[2].rotation());
       
   927     view(2, 3) -= 2.0f * exp(m_distExp / 1200.0f);
       
   928     renderBoxes(view);
       
   929 
       
   930     defaultStates();
       
   931     ++m_frame;
       
   932 
       
   933     painter->endNativePainting();
       
   934 }
       
   935 
       
   936 QPointF Scene::pixelPosToViewPos(const QPointF& p)
       
   937 {
       
   938     return QPointF(2.0 * float(p.x()) / width() - 1.0,
       
   939                    1.0 - 2.0 * float(p.y()) / height());
       
   940 }
       
   941 
       
   942 void Scene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
       
   943 {
       
   944     QGraphicsScene::mouseMoveEvent(event);
       
   945     if (event->isAccepted())
       
   946         return;
       
   947 
       
   948     if (event->buttons() & Qt::LeftButton) {
       
   949         m_trackBalls[0].move(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate());
       
   950         event->accept();
       
   951     } else {
       
   952         m_trackBalls[0].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate());
       
   953     }
       
   954 
       
   955     if (event->buttons() & Qt::RightButton) {
       
   956         m_trackBalls[1].move(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate());
       
   957         event->accept();
       
   958     } else {
       
   959         m_trackBalls[1].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate());
       
   960     }
       
   961 
       
   962     if (event->buttons() & Qt::MidButton) {
       
   963         m_trackBalls[2].move(pixelPosToViewPos(event->scenePos()), QQuaternion());
       
   964         event->accept();
       
   965     } else {
       
   966         m_trackBalls[2].release(pixelPosToViewPos(event->scenePos()), QQuaternion());
       
   967     }
       
   968 }
       
   969 
       
   970 void Scene::mousePressEvent(QGraphicsSceneMouseEvent *event)
       
   971 {
       
   972     QGraphicsScene::mousePressEvent(event);
       
   973     if (event->isAccepted())
       
   974         return;
       
   975 
       
   976     if (event->buttons() & Qt::LeftButton) {
       
   977         m_trackBalls[0].push(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate());
       
   978         event->accept();
       
   979     }
       
   980 
       
   981     if (event->buttons() & Qt::RightButton) {
       
   982         m_trackBalls[1].push(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate());
       
   983         event->accept();
       
   984     }
       
   985 
       
   986     if (event->buttons() & Qt::MidButton) {
       
   987         m_trackBalls[2].push(pixelPosToViewPos(event->scenePos()), QQuaternion());
       
   988         event->accept();
       
   989     }
       
   990 }
       
   991 
       
   992 void Scene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
       
   993 {
       
   994     QGraphicsScene::mouseReleaseEvent(event);
       
   995     if (event->isAccepted())
       
   996         return;
       
   997 
       
   998     if (event->button() == Qt::LeftButton) {
       
   999         m_trackBalls[0].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate());
       
  1000         event->accept();
       
  1001     }
       
  1002 
       
  1003     if (event->button() == Qt::RightButton) {
       
  1004         m_trackBalls[1].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate());
       
  1005         event->accept();
       
  1006     }
       
  1007 
       
  1008     if (event->button() == Qt::MidButton) {
       
  1009         m_trackBalls[2].release(pixelPosToViewPos(event->scenePos()), QQuaternion());
       
  1010         event->accept();
       
  1011     }
       
  1012 }
       
  1013 
       
  1014 void Scene::wheelEvent(QGraphicsSceneWheelEvent * event)
       
  1015 {
       
  1016     QGraphicsScene::wheelEvent(event);
       
  1017     if (!event->isAccepted()) {
       
  1018         m_distExp += event->delta();
       
  1019         if (m_distExp < -8 * 120)
       
  1020             m_distExp = -8 * 120;
       
  1021         if (m_distExp > 10 * 120)
       
  1022             m_distExp = 10 * 120;
       
  1023         event->accept();
       
  1024     }
       
  1025 }
       
  1026 
       
  1027 void Scene::setShader(int index)
       
  1028 {
       
  1029     if (index >= 0 && index < m_fragmentShaders.size())
       
  1030         m_currentShader = index;
       
  1031 }
       
  1032 
       
  1033 void Scene::setTexture(int index)
       
  1034 {
       
  1035     if (index >= 0 && index < m_textures.size())
       
  1036         m_currentTexture = index;
       
  1037 }
       
  1038 
       
  1039 void Scene::toggleDynamicCubemap(int state)
       
  1040 {
       
  1041     if ((m_dynamicCubemap = (state == Qt::Checked)))
       
  1042         m_updateAllCubemaps = true;
       
  1043 }
       
  1044 
       
  1045 void Scene::setColorParameter(const QString &name, QRgb color)
       
  1046 {
       
  1047     // set the color in all programs
       
  1048     foreach (QGLShaderProgram *program, m_programs) {
       
  1049         program->enable();
       
  1050         program->setUniformValue(program->uniformLocation(name), QColor(color));
       
  1051         program->disable();
       
  1052     }
       
  1053 }
       
  1054 
       
  1055 void Scene::setFloatParameter(const QString &name, float value)
       
  1056 {
       
  1057     // set the color in all programs
       
  1058     foreach (QGLShaderProgram *program, m_programs) {
       
  1059         program->enable();
       
  1060         program->setUniformValue(program->uniformLocation(name), value);
       
  1061         program->disable();
       
  1062     }
       
  1063 }
       
  1064 
       
  1065 void Scene::newItem(ItemDialog::ItemType type)
       
  1066 {
       
  1067     QSize size = sceneRect().size().toSize();
       
  1068     switch (type) {
       
  1069     case ItemDialog::QtBoxItem:
       
  1070         addItem(new QtBox(64, rand() % (size.width() - 64) + 32, rand() % (size.height() - 64) + 32));
       
  1071         break;
       
  1072     case ItemDialog::CircleItem:
       
  1073         addItem(new CircleItem(64, rand() % (size.width() - 64) + 32, rand() % (size.height() - 64) + 32));
       
  1074         break;
       
  1075     case ItemDialog::SquareItem:
       
  1076         addItem(new SquareItem(64, rand() % (size.width() - 64) + 32, rand() % (size.height() - 64) + 32));
       
  1077         break;
       
  1078     default:
       
  1079         break;
       
  1080     }
       
  1081 }