Debian Codegraph @

tests/manual/examples/opengl/qopenglwidget/glwidget.cpp

raw
1 // Copyright (C) 2016 The Qt Company Ltd.
2 // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
3
4 #include "glwidget.h"
5 #include <QPainter>
6 #include <QPaintEngine>
7 #include <QOpenGLShaderProgram>
8 #include <QOpenGLTexture>
9 #include <QRandomGenerator>
10 #include <QCoreApplication>
11 #include <qmath.h>
12
13 #include "mainwindow.h"
14 #include "bubble.h"
15
16 const int bubbleNum = 8;
17
18 #ifndef GL_SRGB8_ALPHA8
19 #define GL_SRGB8_ALPHA8 0x8C43
20 #endif
21
22 GLWidget::GLWidget(MainWindow *maybeMainWindow, const QColor &background)
23 : m_mainWindow(maybeMainWindow),
24 m_background(background)
25 {
26 setMinimumSize(300, 250);
27 if (QCoreApplication::arguments().contains(QStringLiteral("--srgb")))
28 setTextureFormat(GL_SRGB8_ALPHA8);
29 }
30
31 GLWidget::~GLWidget()
32 {
33 reset();
34 }
35
36 void GLWidget::reset()
37 {
38 qDeleteAll(m_bubbles);
39 // Leave everything in a state suitable for a subsequent call to
40 // initialize(). This matters when coming from the context's
41 // aboutToBeDestroyed signal, would not matter when invoked from the
42 // destructor.
43 m_bubbles.clear();
44
45 // And now release all OpenGL resources.
46 makeCurrent();
47 delete m_texture;
48 m_texture = nullptr;
49 delete m_program1;
50 m_program1 = nullptr;
51 delete m_program2;
52 m_program2 = nullptr;
53 delete m_vshader1;
54 m_vshader1 = nullptr;
55 delete m_fshader1;
56 m_fshader1 = nullptr;
57 delete m_vshader2;
58 m_vshader2 = nullptr;
59 delete m_fshader2;
60 m_fshader2 = nullptr;
61 m_vbo1.destroy();
62 m_vbo2.destroy();
63 doneCurrent();
64
65 // We are done with the current QOpenGLContext, forget it. If there is a
66 // subsequent initialize(), that will then connect to the new context.
67 QObject::disconnect(m_contextWatchConnection);
68 }
69
70 void GLWidget::setScaling(int scale)
71 {
72 if (scale > 30)
73 m_fScale = 1 + qreal(scale - 30) / 30 * 0.25;
74 else if (scale < 30)
75 m_fScale = 1 - (qreal(30 - scale) / 30 * 0.25);
76 else
77 m_fScale = 1;
78 }
79
80 void GLWidget::setLogo()
81 {
82 m_qtLogo = true;
83 }
84
85 void GLWidget::setTexture()
86 {
87 m_qtLogo = false;
88 }
89
90 void GLWidget::setShowBubbles(bool bubbles)
91 {
92 m_showBubbles = bubbles;
93 }
94
95 void GLWidget::paintQtLogo()
96 {
97 m_program1->enableAttributeArray(m_vertexAttr1);
98 m_program1->enableAttributeArray(m_normalAttr1);
99
100 m_vbo1.bind();
101 // The data in the buffer is placed like this:
102 // vertex1.x, vertex1.y, vertex1.z, normal1.x, normal1.y, normal1.z, vertex2.x, ...
103 m_program1->setAttributeBuffer(m_vertexAttr1, GL_FLOAT, 0, 3, 6 * sizeof(GLfloat));
104 m_program1->setAttributeBuffer(m_normalAttr1, GL_FLOAT, 3 * sizeof(GLfloat), 3, 6 * sizeof(GLfloat));
105 m_vbo1.release();
106
107 glDrawArrays(GL_TRIANGLES, 0, m_vertices.size());
108
109 m_program1->disableAttributeArray(m_normalAttr1);
110 m_program1->disableAttributeArray(m_vertexAttr1);
111 }
112
113 void GLWidget::paintTexturedCube()
114 {
115 m_texture->bind();
116
117 if (!m_vbo2.isCreated()) {
118 static GLfloat afVertices[] = {
119 -0.5, 0.5, 0.5, 0.5,-0.5,0.5,-0.5,-0.5,0.5,
120 0.5, -0.5, 0.5, -0.5,0.5,0.5,0.5,0.5,0.5,
121 -0.5, -0.5, -0.5, 0.5,-0.5,-0.5,-0.5,0.5,-0.5,
122 0.5, 0.5, -0.5, -0.5,0.5,-0.5,0.5,-0.5,-0.5,
123
124 0.5, -0.5, -0.5, 0.5,-0.5,0.5,0.5,0.5,-0.5,
125 0.5, 0.5, 0.5, 0.5,0.5,-0.5,0.5,-0.5,0.5,
126 -0.5, 0.5, -0.5, -0.5,-0.5,0.5,-0.5,-0.5,-0.5,
127 -0.5, -0.5, 0.5, -0.5,0.5,-0.5,-0.5,0.5,0.5,
128
129 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5,
130 -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5,
131 -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, 0.5, -0.5, -0.5,
132 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, -0.5, -0.5, 0.5
133 };
134
135 static GLfloat afTexCoord[] = {
136 0.0f,0.0f, 1.0f,1.0f, 1.0f,0.0f,
137 1.0f,1.0f, 0.0f,0.0f, 0.0f,1.0f,
138 1.0f,1.0f, 1.0f,0.0f, 0.0f,1.0f,
139 0.0f,0.0f, 0.0f,1.0f, 1.0f,0.0f,
140
141 1.0f,1.0f, 1.0f,0.0f, 0.0f,1.0f,
142 0.0f,0.0f, 0.0f,1.0f, 1.0f,0.0f,
143 0.0f,0.0f, 1.0f,1.0f, 1.0f,0.0f,
144 1.0f,1.0f, 0.0f,0.0f, 0.0f,1.0f,
145
146 0.0f,1.0f, 1.0f,0.0f, 1.0f,1.0f,
147 1.0f,0.0f, 0.0f,1.0f, 0.0f,0.0f,
148 1.0f,0.0f, 1.0f,1.0f, 0.0f,0.0f,
149 0.0f,1.0f, 0.0f,0.0f, 1.0f,1.0f
150 };
151
152 GLfloat afNormals[] = {
153
154 0,0,-1, 0,0,-1, 0,0,-1,
155 0,0,-1, 0,0,-1, 0,0,-1,
156 0,0,1, 0,0,1, 0,0,1,
157 0,0,1, 0,0,1, 0,0,1,
158
159 -1,0,0, -1,0,0, -1,0,0,
160 -1,0,0, -1,0,0, -1,0,0,
161 1,0,0, 1,0,0, 1,0,0,
162 1,0,0, 1,0,0, 1,0,0,
163
164 0,-1,0, 0,-1,0, 0,-1,0,
165 0,-1,0, 0,-1,0, 0,-1,0,
166 0,1,0, 0,1,0, 0,1,0,
167 0,1,0, 0,1,0, 0,1,0
168 };
169
170 m_vbo2.create();
171 m_vbo2.bind();
172 m_vbo2.allocate(36 * 8 * sizeof(GLfloat));
173 m_vbo2.write(0, afVertices, sizeof(afVertices));
174 m_vbo2.write(sizeof(afVertices), afTexCoord, sizeof(afTexCoord));
175 m_vbo2.write(sizeof(afVertices) + sizeof(afTexCoord), afNormals, sizeof(afNormals));
176 m_vbo2.release();
177 }
178
179 m_program2->setUniformValue(m_textureUniform2, 0); // use texture unit 0
180
181 m_program2->enableAttributeArray(m_vertexAttr2);
182 m_program2->enableAttributeArray(m_normalAttr2);
183 m_program2->enableAttributeArray(m_texCoordAttr2);
184
185 m_vbo2.bind();
186 // In the buffer we first have 36 vertices (3 floats for each), then 36 texture
187 // coordinates (2 floats for each), then 36 normals (3 floats for each).
188 m_program2->setAttributeBuffer(m_vertexAttr2, GL_FLOAT, 0, 3);
189 m_program2->setAttributeBuffer(m_texCoordAttr2, GL_FLOAT, 36 * 3 * sizeof(GLfloat), 2);
190 m_program2->setAttributeBuffer(m_normalAttr2, GL_FLOAT, 36 * 5 * sizeof(GLfloat), 3);
191 m_vbo2.release();
192
193 glDrawArrays(GL_TRIANGLES, 0, 36);
194
195 m_program2->disableAttributeArray(m_vertexAttr2);
196 m_program2->disableAttributeArray(m_normalAttr2);
197 m_program2->disableAttributeArray(m_texCoordAttr2);
198 }
199
200 void GLWidget::initializeGL()
201 {
202 initializeOpenGLFunctions();
203
204 m_texture = new QOpenGLTexture(QImage(":/qt.png"));
205
206 m_vshader1 = new QOpenGLShader(QOpenGLShader::Vertex);
207 const char *vsrc1 =
208 "attribute highp vec4 vertex;\n"
209 "attribute mediump vec3 normal;\n"
210 "uniform mediump mat4 matrix;\n"
211 "varying mediump vec4 color;\n"
212 "void main(void)\n"
213 "{\n"
214 " vec3 toLight = normalize(vec3(0.0, 0.3, 1.0));\n"
215 " float angle = max(dot(normal, toLight), 0.0);\n"
216 " vec3 col = vec3(0.40, 1.0, 0.0);\n"
217 " color = vec4(col * 0.2 + col * 0.8 * angle, 1.0);\n"
218 " color = clamp(color, 0.0, 1.0);\n"
219 " gl_Position = matrix * vertex;\n"
220 "}\n";
221 m_vshader1->compileSourceCode(vsrc1);
222
223 m_fshader1 = new QOpenGLShader(QOpenGLShader::Fragment);
224 const char *fsrc1 =
225 "varying mediump vec4 color;\n"
226 "void main(void)\n"
227 "{\n"
228 " gl_FragColor = color;\n"
229 "}\n";
230 m_fshader1->compileSourceCode(fsrc1);
231
232 m_program1 = new QOpenGLShaderProgram;
233 m_program1->addShader(m_vshader1);
234 m_program1->addShader(m_fshader1);
235 m_program1->link();
236
237 m_vertexAttr1 = m_program1->attributeLocation("vertex");
238 m_normalAttr1 = m_program1->attributeLocation("normal");
239 m_matrixUniform1 = m_program1->uniformLocation("matrix");
240
241 m_vshader2 = new QOpenGLShader(QOpenGLShader::Vertex);
242 const char *vsrc2 =
243 "attribute highp vec4 vertex;\n"
244 "attribute highp vec4 texCoord;\n"
245 "attribute mediump vec3 normal;\n"
246 "uniform mediump mat4 matrix;\n"
247 "varying highp vec4 texc;\n"
248 "varying mediump float angle;\n"
249 "void main(void)\n"
250 "{\n"
251 " vec3 toLight = normalize(vec3(0.0, 0.3, 1.0));\n"
252 " angle = max(dot(normal, toLight), 0.0);\n"
253 " gl_Position = matrix * vertex;\n"
254 " texc = texCoord;\n"
255 "}\n";
256 m_vshader2->compileSourceCode(vsrc2);
257
258 m_fshader2 = new QOpenGLShader(QOpenGLShader::Fragment);
259 const char *fsrc2 =
260 "varying highp vec4 texc;\n"
261 "uniform sampler2D tex;\n"
262 "varying mediump float angle;\n"
263 "void main(void)\n"
264 "{\n"
265 " highp vec3 color = texture2D(tex, texc.st).rgb;\n"
266 " color = color * 0.2 + color * 0.8 * angle;\n"
267 " gl_FragColor = vec4(clamp(color, 0.0, 1.0), 1.0);\n"
268 "}\n";
269 m_fshader2->compileSourceCode(fsrc2);
270
271 m_program2 = new QOpenGLShaderProgram;
272 m_program2->addShader(m_vshader2);
273 m_program2->addShader(m_fshader2);
274 m_program2->link();
275
276 m_vertexAttr2 = m_program2->attributeLocation("vertex");
277 m_normalAttr2 = m_program2->attributeLocation("normal");
278 m_texCoordAttr2 = m_program2->attributeLocation("texCoord");
279 m_matrixUniform2 = m_program2->uniformLocation("matrix");
280 m_textureUniform2 = m_program2->uniformLocation("tex");
281
282 m_fAngle = 0;
283 m_fScale = 1;
284
285 createGeometry();
286
287 // Use a vertex buffer object. Client-side pointers are old-school and should be avoided.
288 m_vbo1.create();
289 m_vbo1.bind();
290 // For the cube all the data belonging to the texture coordinates and
291 // normals is placed separately, after the vertices. Here, for the Qt logo,
292 // let's do something different and potentially more efficient: create a
293 // properly interleaved data set.
294 const int vertexCount = m_vertices.count();
295 QList<GLfloat> buf;
296 buf.resize(vertexCount * 3 * 2);
297 GLfloat *p = buf.data();
298 for (int i = 0; i < vertexCount; ++i) {
299 *p++ = m_vertices[i].x();
300 *p++ = m_vertices[i].y();
301 *p++ = m_vertices[i].z();
302 *p++ = m_normals[i].x();
303 *p++ = m_normals[i].y();
304 *p++ = m_normals[i].z();
305 }
306 m_vbo1.allocate(buf.constData(), buf.count() * sizeof(GLfloat));
307 m_vbo1.release();
308
309 createBubbles(bubbleNum - m_bubbles.count());
310
311 // A well-behaved QOpenGLWidget releases OpenGL resources not only upon
312 // destruction, but also when the associated OpenGL context disappears. If
313 // the widget continues to exist, the context's destruction will be
314 // followed by a call to initialize(). This is not strictly mandatory in
315 // widgets that never change their parents.
316 m_contextWatchConnection = QObject::connect(context(), &QOpenGLContext::aboutToBeDestroyed, context(), [this] { reset(); });
317 }
318
319 void GLWidget::paintGL()
320 {
321 createBubbles(bubbleNum - m_bubbles.count());
322
323 QPainter painter;
324 painter.begin(this);
325
326 painter.beginNativePainting();
327
328 glClearColor(m_background.redF(), m_background.greenF(), m_background.blueF(), m_transparent ? 0.0f : 1.0f);
329 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
330
331 glFrontFace(GL_CW);
332 glCullFace(GL_FRONT);
333 glEnable(GL_CULL_FACE);
334 glEnable(GL_DEPTH_TEST);
335
336 QMatrix4x4 modelview;
337 modelview.rotate(m_fAngle, 0.0f, 1.0f, 0.0f);
338 modelview.rotate(m_fAngle, 1.0f, 0.0f, 0.0f);
339 modelview.rotate(m_fAngle, 0.0f, 0.0f, 1.0f);
340 modelview.scale(m_fScale);
341 modelview.translate(0.0f, -0.2f, 0.0f);
342
343 if (m_qtLogo) {
344 m_program1->bind();
345 m_program1->setUniformValue(m_matrixUniform1, modelview);
346 paintQtLogo();
347 m_program1->release();
348 } else {
349 m_program2->bind();
350 m_program2->setUniformValue(m_matrixUniform2, modelview);
351 paintTexturedCube();
352 m_program2->release();
353 }
354
355 glDisable(GL_DEPTH_TEST);
356 glDisable(GL_CULL_FACE);
357
358 painter.endNativePainting();
359
360 if (m_showBubbles) {
361 for (Bubble *bubble : std::as_const(m_bubbles))
362 bubble->drawBubble(&painter);
363 }
364
365 if (const int elapsed = m_time.elapsed()) {
366 QString framesPerSecond;
367 framesPerSecond.setNum(m_frames /(elapsed / 1000.0), 'f', 2);
368 painter.setPen(m_transparent ? Qt::black : Qt::white);
369 painter.drawText(20, 40, framesPerSecond + " paintGL calls / s");
370 }
371
372 painter.end();
373
374 for (Bubble *bubble : std::as_const(m_bubbles))
375 bubble->move(rect());
376
377 if (!(m_frames % 100)) {
378 m_time.start();
379 m_frames = 0;
380 }
381 m_fAngle += 1.0f;
382 ++m_frames;
383
384 // When requested, follow the ideal way to animate: Rely on
385 // blocking swap and just schedule updates continuously.
386 if (!m_mainWindow || !m_mainWindow->timerEnabled())
387 update();
388 }
389
390 void GLWidget::createBubbles(int number)
391 {
392 for (int i = 0; i < number; ++i) {
393 QPointF position(width()*(0.1 + QRandomGenerator::global()->bounded(0.8)),
394 height()*(0.1 + QRandomGenerator::global()->bounded(0.8)));
395 qreal radius = qMin(width(), height())*(0.0175 + QRandomGenerator::global()->bounded(0.0875));
396 QPointF velocity(width()*0.0175*(-0.5 + QRandomGenerator::global()->bounded(1.0)),
397 height()*0.0175*(-0.5 + QRandomGenerator::global()->bounded(1.0)));
398
399 m_bubbles.append(new Bubble(position, radius, velocity));
400 }
401 }
402
403 void GLWidget::createGeometry()
404 {
405 m_vertices.clear();
406 m_normals.clear();
407
408 qreal x1 = +0.06f;
409 qreal y1 = -0.14f;
410 qreal x2 = +0.14f;
411 qreal y2 = -0.06f;
412 qreal x3 = +0.08f;
413 qreal y3 = +0.00f;
414 qreal x4 = +0.30f;
415 qreal y4 = +0.22f;
416
417 quad(x1, y1, x2, y2, y2, x2, y1, x1);
418 quad(x3, y3, x4, y4, y4, x4, y3, x3);
419
420 extrude(x1, y1, x2, y2);
421 extrude(x2, y2, y2, x2);
422 extrude(y2, x2, y1, x1);
423 extrude(y1, x1, x1, y1);
424 extrude(x3, y3, x4, y4);
425 extrude(x4, y4, y4, x4);
426 extrude(y4, x4, y3, x3);
427
428 const int NumSectors = 100;
429 const qreal sectorAngle = 2 * qreal(M_PI) / NumSectors;
430
431 for (int i = 0; i < NumSectors; ++i) {
432 qreal angle = i * sectorAngle;
433 qreal x5 = 0.30 * sin(angle);
434 qreal y5 = 0.30 * cos(angle);
435 qreal x6 = 0.20 * sin(angle);
436 qreal y6 = 0.20 * cos(angle);
437
438 angle += sectorAngle;
439 qreal x7 = 0.20 * sin(angle);
440 qreal y7 = 0.20 * cos(angle);
441 qreal x8 = 0.30 * sin(angle);
442 qreal y8 = 0.30 * cos(angle);
443
444 quad(x5, y5, x6, y6, x7, y7, x8, y8);
445
446 extrude(x6, y6, x7, y7);
447 extrude(x8, y8, x5, y5);
448 }
449
450 for (int i = 0;i < m_vertices.size();i++)
451 m_vertices[i] *= 2.0f;
452 }
453
454 void GLWidget::quad(qreal x1, qreal y1, qreal x2, qreal y2, qreal x3, qreal y3, qreal x4, qreal y4)
455 {
456 m_vertices << QVector3D(x1, y1, -0.05f);
457 m_vertices << QVector3D(x2, y2, -0.05f);
458 m_vertices << QVector3D(x4, y4, -0.05f);
459
460 m_vertices << QVector3D(x3, y3, -0.05f);
461 m_vertices << QVector3D(x4, y4, -0.05f);
462 m_vertices << QVector3D(x2, y2, -0.05f);
463
464 QVector3D n = QVector3D::normal
465 (QVector3D(x2 - x1, y2 - y1, 0.0f), QVector3D(x4 - x1, y4 - y1, 0.0f));
466
467 m_normals << n;
468 m_normals << n;
469 m_normals << n;
470
471 m_normals << n;
472 m_normals << n;
473 m_normals << n;
474
475 m_vertices << QVector3D(x4, y4, 0.05f);
476 m_vertices << QVector3D(x2, y2, 0.05f);
477 m_vertices << QVector3D(x1, y1, 0.05f);
478
479 m_vertices << QVector3D(x2, y2, 0.05f);
480 m_vertices << QVector3D(x4, y4, 0.05f);
481 m_vertices << QVector3D(x3, y3, 0.05f);
482
483 n = QVector3D::normal
484 (QVector3D(x2 - x4, y2 - y4, 0.0f), QVector3D(x1 - x4, y1 - y4, 0.0f));
485
486 m_normals << n;
487 m_normals << n;
488 m_normals << n;
489
490 m_normals << n;
491 m_normals << n;
492 m_normals << n;
493 }
494
495 void GLWidget::extrude(qreal x1, qreal y1, qreal x2, qreal y2)
496 {
497 m_vertices << QVector3D(x1, y1, +0.05f);
498 m_vertices << QVector3D(x2, y2, +0.05f);
499 m_vertices << QVector3D(x1, y1, -0.05f);
500
501 m_vertices << QVector3D(x2, y2, -0.05f);
502 m_vertices << QVector3D(x1, y1, -0.05f);
503 m_vertices << QVector3D(x2, y2, +0.05f);
504
505 QVector3D n = QVector3D::normal
506 (QVector3D(x2 - x1, y2 - y1, 0.0f), QVector3D(0.0f, 0.0f, -0.1f));
507
508 m_normals << n;
509 m_normals << n;
510 m_normals << n;
511
512 m_normals << n;
513 m_normals << n;
514 m_normals << n;
515 }
516
517 void GLWidget::setTransparent(bool transparent)
518 {
519 setAttribute(Qt::WA_AlwaysStackOnTop, transparent);
520 m_transparent = transparent;
521 // Call update() on the top-level window after toggling AlwayStackOnTop to make sure
522 // the entire backingstore is updated accordingly.
523 window()->update();
524 }
525
526 void GLWidget::resizeGL(int, int)
527 {
528 if (m_mainWindow) {
529 if (!m_btn) {
530 m_btn = new QPushButton("\nAdd widget\n", this);
531 connect(m_btn, &QPushButton::clicked, this, [this] { m_mainWindow->addNew(); });
532 }
533 m_btn->move(20, 80);
534 if (!m_btn2) {
535 m_btn2 = new QPushButton("\nI prefer tabbed widgets\n", this);
536 connect(m_btn2, &QPushButton::clicked, this, [this] { m_mainWindow->showNewWindow(); });
537 }
538 m_btn2->move(20, 160);
539 }
540 }