summaryrefslogtreecommitdiffstats
path: root/openglscene.cpp
blob: 05e8ca37bcc43777b1ab327fb4245bd0ff736709 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
#include "openglscene.h"

#include "model.h"

#include <QtGui>
#include <QtOpenGL>

#ifndef QT_NO_CONCURRENT
#include <QFutureWatcher>
#endif

#ifndef GL_MULTISAMPLE
#define GL_MULTISAMPLE  0x809D
#endif

class Controls : public QGroupBox
{
    Q_OBJECT

public:
    Controls(OpenGLScene *scene);

private slots:
    void loadModel(const QString &model);
    void modelLoaded();
    void setModelColor(bool showDialog = true);
    void setBackgroundColor(bool showDialog = true);

private:
    OpenGLScene *m_scene;
#ifndef QT_NO_CONCURRENT
    QFutureWatcher<Model *> m_modelLoader;
#endif
    QComboBox *m_models;

    QRgb m_modelColor;
    QRgb m_backgroundColor;
    QDir m_dir;
};

Controls::Controls(OpenGLScene *scene)
    : m_scene(scene)
    , m_models(new QComboBox)
    , m_modelColor(qRgb(180, 100, 255))
    , m_backgroundColor(qRgb(0, 0, 0))
    , m_dir("models")
{
    QVBoxLayout *layout = new QVBoxLayout(this);

    layout->addWidget(new QLabel("Model:"));

    m_dir.setNameFilters(QStringList() << "*.obj");
    m_models->addItems(m_dir.entryList());
    connect(m_models, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(loadModel(const QString &)));
#ifndef QT_NO_CONCURRENT
    connect(&m_modelLoader, SIGNAL(finished()), this, SLOT(modelLoaded()));
#endif

    if (m_models->count() > 0)
        loadModel(m_models->currentText());
    layout->addWidget(m_models);

    QCheckBox *autoRotate = new QCheckBox("Auto-rotate");
    autoRotate->setChecked(true);
    connect(autoRotate, SIGNAL(toggled(bool)), m_scene, SLOT(enableAutoRotate(bool)));
    layout->addWidget(autoRotate);

    QCheckBox *wireframe = new QCheckBox("Render as wireframe");
    wireframe->setChecked(true);
    connect(wireframe, SIGNAL(toggled(bool)), m_scene, SLOT(enableWireframe(bool)));
    layout->addWidget(wireframe);

    QCheckBox *normals = new QCheckBox("Display normals vectors");
    wireframe->setChecked(false);
    connect(normals, SIGNAL(toggled(bool)), m_scene, SLOT(enableNormals(bool)));
    layout->addWidget(normals);

    layout->addWidget(new QLabel("Light position:"));
    QSlider *lightPosition = new QSlider(Qt::Horizontal);
    lightPosition->setRange(-100, 100);
    connect(lightPosition, SIGNAL(valueChanged(int)), m_scene, SLOT(setLightPosition(int)));
    layout->addWidget(lightPosition);

    m_scene->setLightPosition(lightPosition->value());

    QPushButton *colorButton = new QPushButton("Choose model color");
    connect(colorButton, SIGNAL(pressed()), this, SLOT(setModelColor()));
    layout->addWidget(colorButton);
    setModelColor(false);

    QPushButton *backgroundButton = new QPushButton("Choose background color");
    connect(backgroundButton, SIGNAL(pressed()), this, SLOT(setBackgroundColor()));
    layout->addWidget(backgroundButton);
    setBackgroundColor(false);
}

Model *loadModel(const QString &filename)
{
    return new Model(filename);
}

void Controls::loadModel(const QString &filename)
{
    m_models->setEnabled(false);
    QApplication::setOverrideCursor(Qt::BusyCursor);
#ifndef QT_NO_CONCURRENT
    m_modelLoader.setFuture(QtConcurrent::run(::loadModel, m_dir.filePath(filename)));
#else
    m_scene->setModel(::loadModel(filename));
    modelLoaded();
#endif
}

void Controls::modelLoaded()
{
#ifndef QT_NO_CONCURRENT
    m_scene->setModel(m_modelLoader.result());
#endif
    m_models->setEnabled(true);
    QApplication::restoreOverrideCursor();
}

void Controls::setModelColor(bool showDialog)
{
    if (showDialog)
        m_modelColor = QColorDialog::getRgba(m_modelColor);

    m_scene->setModelColor(m_modelColor);
}

void Controls::setBackgroundColor(bool showDialog)
{
    if (showDialog)
        m_backgroundColor = QColorDialog::getRgba(m_backgroundColor);

    m_scene->setBackgroundColor(m_backgroundColor);
}

OpenGLScene::OpenGLScene()
    : m_wireframeEnabled(true)
    , m_normalsEnabled(false)
    , m_autoRotate(true)
    , m_rotating(false)
    , m_axis(0.0f, 1.0f, 0.0f)
    , m_angle(20.0f)
    , m_distance(1.5f)
    , m_model(0)
    , m_lastTime(0)
{
    // set identity matrix
    for (int i = 0; i < 4; ++i)
        for (int j = 0; j < 4; ++j)
            m_matrix[i][j] = (i == j);

    Controls *controls = new Controls(this);
    controls->setWindowOpacity(0.8);

    QGraphicsProxyWidget *item = addWidget(controls);
    item->translate(10, 10);
    item->setCacheMode(QGraphicsItem::DeviceCoordinateCache);

    m_time.start();
}

void OpenGLScene::updateMatrix(qreal delta)
{
    if (!QGLContext::currentContext())
        return;

    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();
    glRotatef(m_angle * delta, m_axis.x, m_axis.y, m_axis.z);
    glMultMatrixf(&m_matrix[0][0]);
    glGetFloatv(GL_MODELVIEW_MATRIX, &m_matrix[0][0]);
    glPopMatrix();
}

void OpenGLScene::drawBackground(QPainter *painter, const QRectF &)
{
    if (painter->paintEngine()->type() != QPaintEngine::OpenGL) {
        qWarning() << "OpenGLScene: drawBackground needs a QGLWidget to be set as viewport on the graphics view";
        return;
    }

    glClearColor(qRed(m_backgroundColor)/255.0f, qGreen(m_backgroundColor)/255.0f, qBlue(m_backgroundColor)/255.0f, 1);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();
    gluPerspective(70, painter->device()->width() / float(painter->device()->height()), 0.01, 1000);

    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();
    float pos[] = { m_lightPos, 5, 2, 0 };
    glLightfv(GL_LIGHT0, GL_POSITION, pos);
    glColor4f(qRed(m_modelColor)/255.0f, qGreen(m_modelColor)/255.0f, qBlue(m_modelColor)/255.0f, 1.0f);

    unsigned int current = m_time.elapsed();
    unsigned int delta = current - m_lastTime;
    m_lastTime = current;

    if (m_autoRotate && !m_rotating)
        updateMatrix(delta / 1000.0);

    glLoadIdentity();
    glTranslatef(0, 0, -m_distance);
    glMultMatrixf(&m_matrix[0][0]);

    glEnable(GL_MULTISAMPLE);
    if (m_model)
        m_model->render(m_wireframeEnabled, m_normalsEnabled);
    glDisable(GL_MULTISAMPLE);

    glPopMatrix();

    glMatrixMode(GL_PROJECTION);
    glPopMatrix();

    if (m_autoRotate)
        QTimer::singleShot(20, this, SLOT(update()));

    painter->paintEngine()->setDirty(QPaintEngine::AllDirty);
    painter->paintEngine()->syncState();
}

void OpenGLScene::setModel(Model *model)
{
    delete m_model;
    m_model = model;
    update();
}

void OpenGLScene::enableAutoRotate(bool enabled)
{
    m_autoRotate = enabled;
    update();
}

void OpenGLScene::enableWireframe(bool enabled)
{
    m_wireframeEnabled = enabled;
}

void OpenGLScene::enableNormals(bool enabled)
{
    m_normalsEnabled = enabled;
}

void OpenGLScene::setLightPosition(int pos)
{
    m_lightPos = pos * 0.05;
    update();
}

void OpenGLScene::setModelColor(QRgb color)
{
    m_modelColor = color;
    update();
}

void OpenGLScene::setBackgroundColor(QRgb color)
{
    m_backgroundColor = color;
    update();
}

static Point3d spherical(const QPointF &point, qreal w, qreal h)
{
    qreal R = qMax(w, h);

    Point3d p;
    p.x = -(point.x() - w / 2);
    p.y = point.y() - h / 2;
    p.z = sqrt(R * R - p.x * p.x - p.y * p.y);

    p.x /= R;
    p.y /= R;
    p.z /= R;
    return p;
}

void OpenGLScene::updateRotation(const QPointF &last, const QPointF &current)
{
    Point3d pos = spherical(current, width(), height());
    Point3d lastPos = spherical(last, width(), height());

    m_axis.x = lastPos.y * pos.z - lastPos.z * pos.y;
    m_axis.y = lastPos.z * pos.x - lastPos.x * pos.z;
    m_axis.z = lastPos.x * pos.y - lastPos.y * pos.x;

    qreal length = sqrt(m_axis.x * m_axis.x + m_axis.y * m_axis.y + m_axis.z * m_axis.z);

    if (length == 0) {
        m_angle = 0;
    } else {
        m_angle = -10 * asin(sqrt(length));

        m_axis.x /= length;
        m_axis.y /= length;
        m_axis.z /= length;

        m_accumulated += m_angle;

        updateMatrix();
        update();
    }
}

void OpenGLScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    QGraphicsScene::mouseMoveEvent(event);
    if (event->isAccepted() || !m_rotating)
        return;

    updateRotation(event->lastScenePos(), event->scenePos());
    event->accept();
}

void OpenGLScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    QGraphicsScene::mousePressEvent(event);
    if (event->isAccepted())
        return;

    m_startTime = m_time.elapsed();
    m_accumulated = 0;

    event->accept();
    m_rotating = true;
}

void OpenGLScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    QGraphicsScene::mouseReleaseEvent(event);
    if (event->isAccepted())
        return;

    const unsigned int delta = m_time.elapsed() - m_startTime;
    m_angle = m_accumulated / (delta / 1000.0);

    event->accept();
    m_rotating = false;
}

void OpenGLScene::wheelEvent(QGraphicsSceneWheelEvent *event)
{
    QGraphicsScene::wheelEvent(event);
    if (event->isAccepted())
        return;

    m_distance *= qPow(1.2, -event->delta() / 120);
    event->accept();
    update();
}

#include "openglscene.moc"