summaryrefslogtreecommitdiffstats
path: root/demos/qt3d/pageflip/pageflip.cpp
blob: 904277cb23373f7ec9c4dc04e5ff2ff1d98c4d51 (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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtQuick3D module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QApplication>
#include <QTimer>
#include <QMouseEvent>
#include "qglpainter.h"
#include "qglabstracteffect.h"
#include "qgltexture2d.h"
#include "qglshaderprogrameffect.h"
#include <QtOpenGL/qglshaderprogram.h>
#include "pageflipmath_p.h"

class PageFlipGradientEffect;

class PageFlipView : public QWindow
{
    Q_OBJECT
public:
    PageFlipView(QWindow *parent = 0);
    ~PageFlipView();

    void setBlend(bool value) { blend = value; }
    void setVertical(bool value) { vertical = value; }

public Q_SLOTS:
    void update();

protected:
    void resizeGL(int width, int height);
    void initializeGL();
    void paintGL();

    void exposeEvent(QExposeEvent *e);
    void mousePressEvent(QMouseEvent *e);

private slots:
    void animate();

private:
    void ensureContext();
    void setAlphaValue(QGLPainter *painter, GLfloat value);

    bool blend;
    bool vertical;

    qreal posn;     // Position within the animation - 0...1
    QSize pageSize; // Size of a page within the window.

    QRect pageRect1;
    QRect pageRect2;

    QColor colors[4];
    int colorIndex;

    QGLTexture2D textures[4];

    QGLTexture2D gradientTexture;

    PageFlipMath pageFlipMath;

    PageFlipGradientEffect *effect;

    QOpenGLContext *context;
    bool initialised;
    QSurfaceFormat format;
    bool updateQueued;
};

class PageFlipGradientEffect : public QGLShaderProgramEffect
{
public:
    PageFlipGradientEffect();
    ~PageFlipGradientEffect();

    void setAlphaValue(GLfloat value);
};

PageFlipView::PageFlipView(QWindow *parent)
    : QWindow(parent)
    , context(0)
    , initialised(false)
    , updateQueued(false)
{
    format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
    format.setDepthBufferSize(24);
    setSurfaceType(QWindow::OpenGLSurface);
    setFormat(format);

    posn = 0.0f;
    blend = false;
    vertical = false;

    colors[0] = QColor(0, 192, 192, 255);
    colors[1] = QColor(192, 0, 0, 255);
    colors[2] = QColor(192, 192, 0, 255);
    colors[3] = QColor(128, 128, 0, 255);
    colorIndex = 0;

    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(animate()));
    timer->start(40);

    effect = new PageFlipGradientEffect();
}

PageFlipView::~PageFlipView()
{
    delete effect;
}

void PageFlipView::exposeEvent(QExposeEvent *e)
{
    Q_UNUSED(e);

    updateQueued = false;
    ensureContext();

    QRect rect = geometry();
    resizeGL(rect.width(), rect.height());

    if (!initialised)
        initializeGL();

    paintGL();

    if (format.swapBehavior() == QSurfaceFormat::DoubleBuffer)
        context->swapBuffers(this);
}

void PageFlipView::resizeGL(int width, int height)
{
    glViewport(0, 0, width, height);
}

void PageFlipView::initializeGL()
{
    QGLPainter painter(this);

    //QSize size = rect().size();
    //int width = size.width() / 3;
    //int height = (int)(width * 1.414f);
    int width = 227;
    int height = 320;
    pageSize = QSize(width, height);

    textures[0].setImage(QImage(QLatin1String(":/qqpage1.png")));
    textures[1].setImage(QImage(QLatin1String(":/qqpage2.png")));
    textures[2].setImage(QImage(QLatin1String(":/qqpage3.png")));
    textures[3].setImage(QImage(QLatin1String(":/qqpage4.png")));

    gradientTexture.setImage(QImage(QLatin1String(":/gradient.png")));

    if (painter.hasOpenGLFeature(QOpenGLFunctions::BlendColor))
        painter.glBlendColor(0, 0, 0, 0);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    if (painter.hasOpenGLFeature(QOpenGLFunctions::BlendEquation))
        painter.glBlendEquation(GL_FUNC_ADD);
    else if (painter.hasOpenGLFeature(QOpenGLFunctions::BlendEquationSeparate))
        painter.glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD);

    glEnable(GL_BLEND);

    if (vertical)
        pageFlipMath.setStartCorner(PageFlipMath::VerticalBottomRight);
    else
        pageFlipMath.setStartCorner(PageFlipMath::BottomRight);

    initialised = true;
}

void PageFlipView::paintGL()
{
    QGLPainter painter(this);

    QRect rect = this->geometry();
    int midx = rect.width() / 2;
    int topy = (rect.height() - pageSize.height()) / 2;

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    QMatrix4x4 projm;
    projm.ortho(rect);
    painter.projectionMatrix() = projm;
    painter.modelViewMatrix().setToIdentity();

    if (vertical) {
        pageRect2 = QRect(QPoint(midx - pageSize.width() / 2, topy), pageSize);
        pageRect1 = QRect(QPoint(pageRect2.x() - pageSize.width(), topy), pageSize);
    } else {
        pageRect1 = QRect(QPoint(midx - pageSize.width(), topy), pageSize);
        pageRect2 = QRect(QPoint(midx, topy), pageSize);
    }
    pageFlipMath.setPageRect(pageRect2);
    pageFlipMath.setShowPageReverse(false);
    pageFlipMath.compute(posn);

    QGLAttributeValue positions
        (2, GL_FLOAT, pageFlipMath.stride(), pageFlipMath.vertexArray());
    QGLAttributeValue texCoords
        (2, GL_FLOAT, pageFlipMath.stride(), pageFlipMath.vertexArray() + 2);
    QGLAttributeValue gradientCoords
        (1, GL_FLOAT, pageFlipMath.stride(), pageFlipMath.vertexArray() + 4);

    if (painter.isFixedFunction())
        painter.setStandardEffect(QGL::FlatReplaceTexture2D);
    else
        painter.setUserEffect(effect);
    painter.setColor(colors[colorIndex]);
    painter.glActiveTexture(GL_TEXTURE0);
    textures[colorIndex].bind();
    if (!painter.isFixedFunction()) {
        painter.glActiveTexture(GL_TEXTURE1);
        gradientTexture.bind();
    }
    painter.clearAttributes();
    painter.setVertexAttribute(QGL::Position, positions);
    painter.setVertexAttribute(QGL::TextureCoord0, texCoords);
    painter.setVertexAttribute(QGL::CustomVertex0, gradientCoords);
    setAlphaValue(&painter, 1.0f);
    painter.update();
    pageFlipMath.drawPage(0);

    painter.setColor(colors[(colorIndex + 1) % 4]);
    painter.glActiveTexture(GL_TEXTURE0);
    textures[(colorIndex + 1) % 4].bind();
    setAlphaValue(&painter, 1.0f);
    painter.update();
    pageFlipMath.drawPage(1);

    painter.setColor(colors[(colorIndex + 2) % 4]);
    if (!pageFlipMath.showPageReverse())
        textures[(colorIndex + 2) % 4].bind();
    if (blend)
        setAlphaValue(&painter, 0.75f);
    else
        setAlphaValue(&painter, 1.0f);
    painter.update();
    pageFlipMath.drawPage(2);

    painter.setColor(colors[(colorIndex + 3) % 4]);
    textures[(colorIndex + 3) % 4].bind();
    setAlphaValue(&painter, 1.0f);
    painter.update();
    pageFlipMath.drawPage(3);

    glBindTexture(GL_TEXTURE_2D, 0);
    painter.glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, 0);

    painter.setStandardEffect(QGL::FlatColor);
    painter.clearAttributes();
    painter.setVertexAttribute(QGL::Position, positions);
    painter.setVertexAttribute(QGL::TextureCoord0, texCoords);
    painter.setVertexAttribute(QGL::CustomVertex0, gradientCoords);
    painter.setColor(QColor(0, 0, 0, 255));
    painter.update();
    pageFlipMath.drawOutline(2);
}

void PageFlipView::mousePressEvent(QMouseEvent *e)
{
    int x = e->x();
    int y = e->y();
    bool changed = true;
    if (vertical) {
        if (x >= pageRect2.x() && x < (pageRect2.x() + 20) &&
                y >= pageRect2.y() && y < (pageRect2.y() + 20))
            pageFlipMath.setStartCorner(PageFlipMath::VerticalTopLeft);
        else if (x >= pageRect2.x() && x < (pageRect2.x() + 20) &&
                    y >= (pageRect2.bottom() - 20) && y <= pageRect2.bottom())
            pageFlipMath.setStartCorner(PageFlipMath::VerticalBottomLeft);
        else if (x >= (pageRect2.right() - 20) && x <= pageRect2.right() &&
                    y >= pageRect2.y() && y < (pageRect2.y() + 20))
            pageFlipMath.setStartCorner(PageFlipMath::VerticalTopRight);
        else if (x >= (pageRect2.right() - 20) && x <= pageRect2.right() &&
                    y >= (pageRect2.bottom() - 20) && y <= pageRect2.bottom())
            pageFlipMath.setStartCorner(PageFlipMath::VerticalBottomRight);
        else
            changed = false;
    } else {
        if (x >= pageRect1.x() && x < (pageRect1.x() + 20) &&
                y >= pageRect1.y() && y < (pageRect1.y() + 20))
            pageFlipMath.setStartCorner(PageFlipMath::TopLeft);
        else if (x >= pageRect1.x() && x < (pageRect1.x() + 20) &&
                    y >= (pageRect1.bottom() - 20) && y <= pageRect1.bottom())
            pageFlipMath.setStartCorner(PageFlipMath::BottomLeft);
        else if (x >= pageRect2.x() && x < (pageRect2.x() + 20) &&
                    y >= pageRect2.y() && y < (pageRect2.y() + 20))
            pageFlipMath.setStartCorner(PageFlipMath::TopLeftOnePage);
        else if (x >= pageRect2.x() && x < (pageRect2.x() + 20) &&
                    y >= (pageRect2.bottom() - 20) && y <= pageRect2.bottom())
            pageFlipMath.setStartCorner(PageFlipMath::BottomLeftOnePage);
        else if (x >= (pageRect2.right() - 20) && x <= pageRect2.right() &&
                    y >= pageRect2.y() && y < (pageRect2.y() + 20))
            pageFlipMath.setStartCorner(PageFlipMath::TopRight);
        else if (x >= (pageRect2.right() - 20) && x <= pageRect2.right() &&
                    y >= (pageRect2.bottom() - 20) && y <= pageRect2.bottom())
            pageFlipMath.setStartCorner(PageFlipMath::BottomRight);
        else
            changed = false;
    }
    if (changed)
        posn = 0.0f;
    QWindow::mousePressEvent(e);
}

void PageFlipView::animate()
{
    posn += 0.04f;
    if (posn >= 1.0f) {
        posn = 0.0f;
        colorIndex = (colorIndex + 2) % 4;
    }
    update();
}

void PageFlipView::update()
{
    if (!updateQueued)
    {
        updateQueued = true;
        QApplication::postEvent(this, new QExposeEvent(geometry()));
    }
}

void PageFlipView::setAlphaValue(QGLPainter *painter, GLfloat value)
{
    if (!painter->isFixedFunction())
        effect->setAlphaValue(value);
}

static char const gradientVertexShader[] =
    "attribute highp vec4 qt_Vertex;\n"
    "attribute highp vec4 qt_MultiTexCoord0;\n"
    "attribute highp float qt_Custom0;\n"
    "uniform mediump mat4 qt_ModelViewProjectionMatrix;\n"
    "varying highp vec4 qt_TexCoord0;\n"
    "varying highp float qGradCtrl;\n"
    "void main(void)\n"
    "{\n"
    "    gl_Position = qt_ModelViewProjectionMatrix * qt_Vertex;\n"
    "    qt_TexCoord0 = qt_MultiTexCoord0;\n"
    "    qGradCtrl = qt_Custom0;\n"
    "}\n";

static char const gradientFragmentShader[] =
    "uniform sampler2D qt_Texture0;\n"
    "uniform sampler2D qt_Texture1;\n"
    "uniform mediump float alphaValue;\n"
    "varying highp vec4 qt_TexCoord0;\n"
    "varying highp float qGradCtrl;\n"
    "void main(void)\n"
    "{\n"
    "    mediump vec4 col = texture2D(qt_Texture0, qt_TexCoord0.st);\n"
    "    mediump vec4 gradcol = texture2D(qt_Texture1, vec2(qGradCtrl, qt_TexCoord0.t));\n"
    "    gl_FragColor = vec4((col * gradcol).xyz, alphaValue);\n"
    "}\n";

PageFlipGradientEffect::PageFlipGradientEffect()
{
    setVertexShader(gradientVertexShader);
    setFragmentShader(gradientFragmentShader);
}

PageFlipGradientEffect::~PageFlipGradientEffect()
{
}

void PageFlipGradientEffect::setAlphaValue(GLfloat value)
{
    program()->setUniformValue("alphaValue", value);
}

inline void PageFlipView::ensureContext()
{
    if (!context)
    {
        context = new QOpenGLContext();
        context->setFormat(format);
#ifndef QT_NO_DEBUG_STREAM
        QSurfaceFormat oldFormat = format;
#endif
        context->create();
        // TODO: is it possible that the platform will downgrade the actual
        // format, or will it just fail if it can't deliver the actual format
        format = context->format();
#ifndef QT_NO_DEBUG_STREAM
        if (oldFormat != format)
            qWarning() << "Could not create context requested:\n"
                       << oldFormat << "\nactual format:\n" << format;
#endif
    }
    context->makeCurrent(this);
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    PageFlipView view;

    QStringList args = QCoreApplication::arguments();
    if (args.contains(QLatin1String("-blend")))
        view.setBlend(true);
    if (args.contains(QLatin1String("-vertical")))
        view.setVertical(true);

    int w_pos = args.indexOf("-width");
    int h_pos = args.indexOf("-height");
    if (w_pos >= 0 && h_pos >= 0)
    {
        bool ok = true;
        int w = args.at(w_pos + 1).toInt(&ok);
        if (!ok)
        {
            qWarning() << "Could not parse width argument:" << args;
            return 1;
        }
        int h = args.at(h_pos + 1).toInt(&ok);
        if (!ok)
        {
            qWarning() << "Could not parse height argument:" << args;
            return 1;
        }
        view.resize(w, h);
    }
    else
    {
        view.resize(800, 600);
    }
    view.show();

    return app.exec();
}

#include "pageflip.moc"