1/****************************************************************************
2**
3** Copyright (C) 2016 The Qt Company Ltd.
4** Contact: https://www.qt.io/licensing/
5**
6** This file is part of the examples of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:BSD$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and The Qt Company. For licensing terms
14** and conditions see https://www.qt.io/terms-conditions. For further
15** information use the contact form at https://www.qt.io/contact-us.
16**
17** BSD License Usage
18** Alternatively, you may use this file under the terms of the BSD license
19** as follows:
20**
21** "Redistribution and use in source and binary forms, with or without
22** modification, are permitted provided that the following conditions are
23** met:
24** * Redistributions of source code must retain the above copyright
25** notice, this list of conditions and the following disclaimer.
26** * Redistributions in binary form must reproduce the above copyright
27** notice, this list of conditions and the following disclaimer in
28** the documentation and/or other materials provided with the
29** distribution.
30** * Neither the name of The Qt Company Ltd nor the names of its
31** contributors may be used to endorse or promote products derived
32** from this software without specific prior written permission.
33**
34**
35** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
36** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
38** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
39** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
43** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
45** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
46**
47** $QT_END_LICENSE$
48**
49****************************************************************************/
50
51#include "glwidget.h"
52#include <qmath.h>
53#include <QGuiApplication>
54
55GLWidget::GLWidget(QWidget *parent)
56 : QOpenGLWidget(parent)
57{
58 setMinimumSize(minw: 300, minh: 250);
59
60 connect(sender: this, signal: &QOpenGLWidget::aboutToCompose, receiver: this, slot: &GLWidget::onAboutToCompose);
61 connect(sender: this, signal: &QOpenGLWidget::frameSwapped, receiver: this, slot: &GLWidget::onFrameSwapped);
62 connect(sender: this, signal: &QOpenGLWidget::aboutToResize, receiver: this, slot: &GLWidget::onAboutToResize);
63 connect(sender: this, signal: &QOpenGLWidget::resized, receiver: this, slot: &GLWidget::onResized);
64
65 m_thread = new QThread;
66 m_renderer = new Renderer(this);
67 m_renderer->moveToThread(thread: m_thread);
68 connect(sender: m_thread, signal: &QThread::finished, receiver: m_renderer, slot: &QObject::deleteLater);
69
70 connect(sender: this, signal: &GLWidget::renderRequested, receiver: m_renderer, slot: &Renderer::render);
71 connect(sender: m_renderer, signal: &Renderer::contextWanted, receiver: this, slot: &GLWidget::grabContext);
72
73 m_thread->start();
74}
75
76GLWidget::~GLWidget()
77{
78 m_renderer->prepareExit();
79 m_thread->quit();
80 m_thread->wait();
81 delete m_thread;
82}
83
84void GLWidget::onAboutToCompose()
85{
86 // We are on the gui thread here. Composition is about to
87 // begin. Wait until the render thread finishes.
88 m_renderer->lockRenderer();
89}
90
91void GLWidget::onFrameSwapped()
92{
93 m_renderer->unlockRenderer();
94 // Assuming a blocking swap, our animation is driven purely by the
95 // vsync in this example.
96 emit renderRequested();
97}
98
99void GLWidget::onAboutToResize()
100{
101 m_renderer->lockRenderer();
102}
103
104void GLWidget::onResized()
105{
106 m_renderer->unlockRenderer();
107}
108
109void GLWidget::grabContext()
110{
111 m_renderer->lockRenderer();
112 QMutexLocker lock(m_renderer->grabMutex());
113 context()->moveToThread(thread: m_thread);
114 m_renderer->grabCond()->wakeAll();
115 m_renderer->unlockRenderer();
116}
117
118Renderer::Renderer(GLWidget *w) : m_glwidget(w) {}
119
120void Renderer::paintQtLogo()
121{
122 vbo.bind();
123 program.setAttributeBuffer(location: vertexAttr, GL_FLOAT, offset: 0, tupleSize: 3);
124 program.setAttributeBuffer(location: normalAttr, GL_FLOAT, offset: vertices.count() * 3 * sizeof(GLfloat), tupleSize: 3);
125 vbo.release();
126
127 program.enableAttributeArray(location: vertexAttr);
128 program.enableAttributeArray(location: normalAttr);
129
130 glDrawArrays(GL_TRIANGLES, first: 0, count: vertices.size());
131
132 program.disableAttributeArray(location: normalAttr);
133 program.disableAttributeArray(location: vertexAttr);
134}
135
136// Some OpenGL implementations have serious issues with compiling and linking
137// shaders on multiple threads concurrently. Avoid this.
138Q_GLOBAL_STATIC(QMutex, initMutex)
139
140void Renderer::render()
141{
142 if (m_exiting)
143 return;
144
145 QOpenGLContext *ctx = m_glwidget->context();
146 if (!ctx) // QOpenGLWidget not yet initialized
147 return;
148
149 // Grab the context.
150 m_grabMutex.lock();
151 emit contextWanted();
152 m_grabCond.wait(lockedMutex: &m_grabMutex);
153 QMutexLocker lock(&m_renderMutex);
154 m_grabMutex.unlock();
155
156 if (m_exiting)
157 return;
158
159 Q_ASSERT(ctx->thread() == QThread::currentThread());
160
161 // Make the context (and an offscreen surface) current for this thread. The
162 // QOpenGLWidget's fbo is bound in the context.
163 m_glwidget->makeCurrent();
164
165 if (!m_inited) {
166 m_inited = true;
167 initializeOpenGLFunctions();
168
169 QMutexLocker initLock(initMutex());
170 QOpenGLShader *vshader = new QOpenGLShader(QOpenGLShader::Vertex, this);
171 const char *vsrc =
172 "attribute highp vec4 vertex;\n"
173 "attribute mediump vec3 normal;\n"
174 "uniform mediump mat4 matrix;\n"
175 "varying mediump vec4 color;\n"
176 "void main(void)\n"
177 "{\n"
178 " vec3 toLight = normalize(vec3(0.0, 0.3, 1.0));\n"
179 " float angle = max(dot(normal, toLight), 0.0);\n"
180 " vec3 col = vec3(0.40, 1.0, 0.0);\n"
181 " color = vec4(col * 0.2 + col * 0.8 * angle, 1.0);\n"
182 " color = clamp(color, 0.0, 1.0);\n"
183 " gl_Position = matrix * vertex;\n"
184 "}\n";
185 vshader->compileSourceCode(source: vsrc);
186
187 QOpenGLShader *fshader = new QOpenGLShader(QOpenGLShader::Fragment, this);
188 const char *fsrc =
189 "varying mediump vec4 color;\n"
190 "void main(void)\n"
191 "{\n"
192 " gl_FragColor = color;\n"
193 "}\n";
194 fshader->compileSourceCode(source: fsrc);
195
196 program.addShader(shader: vshader);
197 program.addShader(shader: fshader);
198 program.link();
199
200 vertexAttr = program.attributeLocation(name: "vertex");
201 normalAttr = program.attributeLocation(name: "normal");
202 matrixUniform = program.uniformLocation(name: "matrix");
203
204 m_fAngle = 0;
205 m_fScale = 1;
206 createGeometry();
207
208 vbo.create();
209 vbo.bind();
210 const int verticesSize = vertices.count() * 3 * sizeof(GLfloat);
211 vbo.allocate(count: verticesSize * 2);
212 vbo.write(offset: 0, data: vertices.constData(), count: verticesSize);
213 vbo.write(offset: verticesSize, data: normals.constData(), count: verticesSize);
214
215 m_elapsed.start();
216 }
217
218 //qDebug("%p elapsed %lld", QThread::currentThread(), m_elapsed.restart());
219
220 glClearColor(red: 0.1f, green: 0.2f, blue: 0.2f, alpha: 1.0f);
221 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
222
223 glFrontFace(GL_CW);
224 glCullFace(GL_FRONT);
225 glEnable(GL_CULL_FACE);
226 glEnable(GL_DEPTH_TEST);
227
228 QMatrix4x4 modelview;
229 modelview.rotate(angle: m_fAngle, x: 0.0f, y: 1.0f, z: 0.0f);
230 modelview.rotate(angle: m_fAngle, x: 1.0f, y: 0.0f, z: 0.0f);
231 modelview.rotate(angle: m_fAngle, x: 0.0f, y: 0.0f, z: 1.0f);
232 modelview.scale(factor: m_fScale);
233 modelview.translate(x: 0.0f, y: -0.2f, z: 0.0f);
234
235 program.bind();
236 program.setUniformValue(location: matrixUniform, value: modelview);
237 paintQtLogo();
238 program.release();
239
240 glDisable(GL_DEPTH_TEST);
241 glDisable(GL_CULL_FACE);
242
243 m_fAngle += 1.0f;
244
245 // Make no context current on this thread and move the QOpenGLWidget's
246 // context back to the gui thread.
247 m_glwidget->doneCurrent();
248 ctx->moveToThread(qGuiApp->thread());
249
250 // Schedule composition. Note that this will use QueuedConnection, meaning
251 // that update() will be invoked on the gui thread.
252 QMetaObject::invokeMethod(obj: m_glwidget, member: "update");
253}
254
255void Renderer::createGeometry()
256{
257 vertices.clear();
258 normals.clear();
259
260 qreal x1 = +0.06f;
261 qreal y1 = -0.14f;
262 qreal x2 = +0.14f;
263 qreal y2 = -0.06f;
264 qreal x3 = +0.08f;
265 qreal y3 = +0.00f;
266 qreal x4 = +0.30f;
267 qreal y4 = +0.22f;
268
269 quad(x1, y1, x2, y2, x3: y2, y3: x2, x4: y1, y4: x1);
270 quad(x1: x3, y1: y3, x2: x4, y2: y4, x3: y4, y3: x4, x4: y3, y4: x3);
271
272 extrude(x1, y1, x2, y2);
273 extrude(x1: x2, y1: y2, x2: y2, y2: x2);
274 extrude(x1: y2, y1: x2, x2: y1, y2: x1);
275 extrude(x1: y1, y1: x1, x2: x1, y2: y1);
276 extrude(x1: x3, y1: y3, x2: x4, y2: y4);
277 extrude(x1: x4, y1: y4, x2: y4, y2: x4);
278 extrude(x1: y4, y1: x4, x2: y3, y2: x3);
279
280 const int NumSectors = 100;
281 const qreal sectorAngle = 2 * qreal(M_PI) / NumSectors;
282
283 for (int i = 0; i < NumSectors; ++i) {
284 qreal angle = i * sectorAngle;
285 qreal x5 = 0.30 * sin(x: angle);
286 qreal y5 = 0.30 * cos(x: angle);
287 qreal x6 = 0.20 * sin(x: angle);
288 qreal y6 = 0.20 * cos(x: angle);
289
290 angle += sectorAngle;
291 qreal x7 = 0.20 * sin(x: angle);
292 qreal y7 = 0.20 * cos(x: angle);
293 qreal x8 = 0.30 * sin(x: angle);
294 qreal y8 = 0.30 * cos(x: angle);
295
296 quad(x1: x5, y1: y5, x2: x6, y2: y6, x3: x7, y3: y7, x4: x8, y4: y8);
297
298 extrude(x1: x6, y1: y6, x2: x7, y2: y7);
299 extrude(x1: x8, y1: y8, x2: x5, y2: y5);
300 }
301
302 for (int i = 0;i < vertices.size();i++)
303 vertices[i] *= 2.0f;
304}
305
306void Renderer::quad(qreal x1, qreal y1, qreal x2, qreal y2, qreal x3, qreal y3, qreal x4, qreal y4)
307{
308 vertices << QVector3D(x1, y1, -0.05f);
309 vertices << QVector3D(x2, y2, -0.05f);
310 vertices << QVector3D(x4, y4, -0.05f);
311
312 vertices << QVector3D(x3, y3, -0.05f);
313 vertices << QVector3D(x4, y4, -0.05f);
314 vertices << QVector3D(x2, y2, -0.05f);
315
316 QVector3D n = QVector3D::normal
317 (v1: QVector3D(x2 - x1, y2 - y1, 0.0f), v2: QVector3D(x4 - x1, y4 - y1, 0.0f));
318
319 normals << n;
320 normals << n;
321 normals << n;
322
323 normals << n;
324 normals << n;
325 normals << n;
326
327 vertices << QVector3D(x4, y4, 0.05f);
328 vertices << QVector3D(x2, y2, 0.05f);
329 vertices << QVector3D(x1, y1, 0.05f);
330
331 vertices << QVector3D(x2, y2, 0.05f);
332 vertices << QVector3D(x4, y4, 0.05f);
333 vertices << QVector3D(x3, y3, 0.05f);
334
335 n = QVector3D::normal
336 (v1: QVector3D(x2 - x4, y2 - y4, 0.0f), v2: QVector3D(x1 - x4, y1 - y4, 0.0f));
337
338 normals << n;
339 normals << n;
340 normals << n;
341
342 normals << n;
343 normals << n;
344 normals << n;
345}
346
347void Renderer::extrude(qreal x1, qreal y1, qreal x2, qreal y2)
348{
349 vertices << QVector3D(x1, y1, +0.05f);
350 vertices << QVector3D(x2, y2, +0.05f);
351 vertices << QVector3D(x1, y1, -0.05f);
352
353 vertices << QVector3D(x2, y2, -0.05f);
354 vertices << QVector3D(x1, y1, -0.05f);
355 vertices << QVector3D(x2, y2, +0.05f);
356
357 QVector3D n = QVector3D::normal
358 (v1: QVector3D(x2 - x1, y2 - y1, 0.0f), v2: QVector3D(0.0f, 0.0f, -0.1f));
359
360 normals << n;
361 normals << n;
362 normals << n;
363
364 normals << n;
365 normals << n;
366 normals << n;
367}
368

source code of qtbase/examples/opengl/threadedqopenglwidget/glwidget.cpp