src/platform/qt/DisplayGL.cpp (view raw)
1/* Copyright (c) 2013-2019 Jeffrey Pfau
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6#include "DisplayGL.h"
7
8#if defined(BUILD_GL) || defined(BUILD_GLES2)
9
10#include "CoreController.h"
11
12#include <QApplication>
13#include <QOpenGLContext>
14#include <QOpenGLPaintDevice>
15#include <QMutexLocker>
16#include <QResizeEvent>
17#include <QScreen>
18#include <QTimer>
19#include <QWindow>
20
21#include <mgba/core/core.h>
22#include <mgba-util/math.h>
23#ifdef BUILD_GL
24#include "platform/opengl/gl.h"
25#endif
26#ifdef BUILD_GLES2
27#include "platform/opengl/gles2.h"
28#ifdef _WIN32
29#include <epoxy/wgl.h>
30#endif
31#endif
32
33using namespace QGBA;
34
35DisplayGL::DisplayGL(const QSurfaceFormat& format, QWidget* parent)
36 : Display(parent)
37 , m_gl(nullptr)
38{
39 setAttribute(Qt::WA_NativeWindow);
40 windowHandle()->create();
41
42 // This can spontaneously re-enter into this->resizeEvent before creation is done, so we
43 // need to make sure it's initialized to nullptr before we assign the new object to it
44 m_gl = new QOpenGLContext;
45 m_gl->setFormat(format);
46 m_gl->create();
47
48 m_gl->makeCurrent(windowHandle());
49#if defined(_WIN32) && defined(USE_EPOXY)
50 epoxy_handle_external_wglMakeCurrent();
51#endif
52 auto version = m_gl->format().version();
53 QStringList extensions = QString(reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS))).split(' ');
54
55 int forceVersion = 0;
56 if (format.majorVersion() < 2) {
57 forceVersion = 1;
58 }
59
60 if ((version == qMakePair(2, 1) && !extensions.contains("GL_ARB_framebuffer_object")) || version == qMakePair(2, 0)) {
61 QSurfaceFormat newFormat(format);
62 newFormat.setVersion(1, 4);
63 forceVersion = 1;
64 m_gl->setFormat(newFormat);
65 m_gl->create();
66 }
67
68 m_painter = new PainterGL(windowHandle(), m_gl, forceVersion);
69}
70
71DisplayGL::~DisplayGL() {
72 stopDrawing();
73 delete m_painter;
74 delete m_gl;
75}
76
77bool DisplayGL::supportsShaders() const {
78 return m_painter->supportsShaders();
79}
80
81VideoShader* DisplayGL::shaders() {
82 VideoShader* shaders = nullptr;
83 if (m_drawThread) {
84 QMetaObject::invokeMethod(m_painter, "shaders", Qt::BlockingQueuedConnection, Q_RETURN_ARG(VideoShader*, shaders));
85 } else {
86 shaders = m_painter->shaders();
87 }
88 return shaders;
89}
90
91void DisplayGL::startDrawing(std::shared_ptr<CoreController> controller) {
92 if (m_drawThread) {
93 return;
94 }
95 m_isDrawing = true;
96 m_painter->setContext(controller);
97 m_painter->setMessagePainter(messagePainter());
98 m_context = controller;
99 m_painter->resize(size());
100 m_drawThread = new QThread(this);
101 m_drawThread->setObjectName("Painter Thread");
102 m_gl->doneCurrent();
103 m_gl->moveToThread(m_drawThread);
104 m_painter->moveToThread(m_drawThread);
105 if (videoProxy()) {
106 videoProxy()->moveToThread(m_drawThread);
107 }
108 connect(m_drawThread, &QThread::started, m_painter, &PainterGL::start);
109 m_drawThread->start();
110
111 lockAspectRatio(isAspectRatioLocked());
112 lockIntegerScaling(isIntegerScalingLocked());
113 interframeBlending(hasInterframeBlending());
114 showOSDMessages(isShowOSD());
115 filter(isFiltered());
116#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
117 messagePainter()->resize(size(), isAspectRatioLocked(), devicePixelRatioF());
118#else
119 messagePainter()->resize(size(), isAspectRatioLocked(), devicePixelRatio());
120#endif
121 resizePainter();
122 setUpdatesEnabled(false);
123}
124
125void DisplayGL::stopDrawing() {
126 if (m_drawThread) {
127 m_isDrawing = false;
128 CoreController::Interrupter interrupter(m_context);
129 QMetaObject::invokeMethod(m_painter, "stop", Qt::BlockingQueuedConnection);
130 m_drawThread->exit();
131 m_drawThread->wait();
132 m_drawThread = nullptr;
133
134 m_gl->makeCurrent(windowHandle());
135#if defined(_WIN32) && defined(USE_EPOXY)
136 epoxy_handle_external_wglMakeCurrent();
137#endif
138 setUpdatesEnabled(true);
139 }
140 m_context.reset();
141}
142
143void DisplayGL::pauseDrawing() {
144 if (m_drawThread) {
145 m_isDrawing = false;
146 CoreController::Interrupter interrupter(m_context);
147 QMetaObject::invokeMethod(m_painter, "pause", Qt::BlockingQueuedConnection);
148 setUpdatesEnabled(true);
149 }
150}
151
152void DisplayGL::unpauseDrawing() {
153 if (m_drawThread) {
154 m_isDrawing = true;
155 CoreController::Interrupter interrupter(m_context);
156 QMetaObject::invokeMethod(m_painter, "unpause", Qt::BlockingQueuedConnection);
157 setUpdatesEnabled(false);
158 }
159}
160
161void DisplayGL::forceDraw() {
162 if (m_drawThread) {
163 QMetaObject::invokeMethod(m_painter, "forceDraw");
164 }
165}
166
167void DisplayGL::lockAspectRatio(bool lock) {
168 Display::lockAspectRatio(lock);
169 if (m_drawThread) {
170 QMetaObject::invokeMethod(m_painter, "lockAspectRatio", Q_ARG(bool, lock));
171 }
172}
173
174void DisplayGL::lockIntegerScaling(bool lock) {
175 Display::lockIntegerScaling(lock);
176 if (m_drawThread) {
177 QMetaObject::invokeMethod(m_painter, "lockIntegerScaling", Q_ARG(bool, lock));
178 }
179}
180
181void DisplayGL::interframeBlending(bool enable) {
182 Display::interframeBlending(enable);
183 if (m_drawThread) {
184 QMetaObject::invokeMethod(m_painter, "interframeBlending", Q_ARG(bool, enable));
185 }
186}
187
188void DisplayGL::showOSDMessages(bool enable) {
189 Display::showOSDMessages(enable);
190 if (m_drawThread) {
191 QMetaObject::invokeMethod(m_painter, "showOSD", Q_ARG(bool, enable));
192 }
193}
194
195void DisplayGL::filter(bool filter) {
196 Display::filter(filter);
197 if (m_drawThread) {
198 QMetaObject::invokeMethod(m_painter, "filter", Q_ARG(bool, filter));
199 }
200}
201
202void DisplayGL::framePosted() {
203 if (m_drawThread) {
204 m_painter->enqueue(m_context->drawContext());
205 QMetaObject::invokeMethod(m_painter, "draw");
206 }
207}
208
209void DisplayGL::setShaders(struct VDir* shaders) {
210 if (m_drawThread) {
211 QMetaObject::invokeMethod(m_painter, "setShaders", Qt::BlockingQueuedConnection, Q_ARG(struct VDir*, shaders));
212 } else {
213 m_painter->setShaders(shaders);
214 }
215}
216
217void DisplayGL::clearShaders() {
218 QMetaObject::invokeMethod(m_painter, "clearShaders");
219}
220
221void DisplayGL::resizeContext() {
222 if (m_drawThread) {
223 m_isDrawing = false;
224 CoreController::Interrupter interrupter(m_context);
225 QMetaObject::invokeMethod(m_painter, "resizeContext", Qt::BlockingQueuedConnection);
226 }
227}
228
229void DisplayGL::setVideoScale(int scale) {
230 if (m_drawThread) {
231 m_isDrawing = false;
232 CoreController::Interrupter interrupter(m_context);
233 mCoreConfigSetIntValue(&m_context->thread()->core->config, "videoScale", scale);
234 QMetaObject::invokeMethod(m_painter, "resizeContext", Qt::BlockingQueuedConnection);
235 }
236}
237
238void DisplayGL::resizeEvent(QResizeEvent* event) {
239 Display::resizeEvent(event);
240 resizePainter();
241}
242
243void DisplayGL::resizePainter() {
244 if (m_drawThread) {
245 QMetaObject::invokeMethod(m_painter, "resize", Qt::BlockingQueuedConnection, Q_ARG(QSize, size()));
246 }
247}
248
249void DisplayGL::setVideoProxy(std::shared_ptr<VideoProxy> proxy) {
250 Display::setVideoProxy(proxy);
251 if (m_drawThread && proxy) {
252 proxy->moveToThread(m_drawThread);
253 }
254 m_painter->setVideoProxy(proxy);
255}
256
257int DisplayGL::framebufferHandle() {
258 return m_painter->glTex();
259}
260
261PainterGL::PainterGL(QWindow* surface, QOpenGLContext* parent, int forceVersion)
262 : m_gl(parent)
263 , m_surface(surface)
264{
265#ifdef BUILD_GL
266 mGLContext* glBackend;
267#endif
268#ifdef BUILD_GLES2
269 mGLES2Context* gl2Backend;
270#endif
271
272 m_gl->makeCurrent(m_surface);
273 m_window = new QOpenGLPaintDevice;
274 {
275 // XXX: Qt creates TLS for OpenGL objects in the local thread
276 // We need to prevent that thread from being the painter thread
277 // Qt also caches the engine object on the device if a different
278 // engine is active, so let's make a temporary one
279 QOpenGLPaintDevice* fakeDevice = new QOpenGLPaintDevice;
280 QPainter fakePainter(fakeDevice);
281 m_window->paintEngine();
282 }
283#if defined(_WIN32) && defined(USE_EPOXY)
284 epoxy_handle_external_wglMakeCurrent();
285#endif
286
287#ifdef BUILD_GLES2
288 auto version = m_gl->format().version();
289 QStringList extensions = QString(reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS))).split(' ');
290 if (forceVersion != 1 && ((version == qMakePair(2, 1) && extensions.contains("GL_ARB_framebuffer_object")) || version.first > 2)) {
291 gl2Backend = static_cast<mGLES2Context*>(malloc(sizeof(mGLES2Context)));
292 mGLES2ContextCreate(gl2Backend);
293 m_backend = &gl2Backend->d;
294 m_supportsShaders = true;
295 }
296#endif
297
298#ifdef BUILD_GL
299 if (!m_backend) {
300 glBackend = static_cast<mGLContext*>(malloc(sizeof(mGLContext)));
301 mGLContextCreate(glBackend);
302 m_backend = &glBackend->d;
303 m_supportsShaders = false;
304 }
305#endif
306 m_backend->swap = [](VideoBackend* v) {
307 PainterGL* painter = static_cast<PainterGL*>(v->user);
308 if (!painter->m_gl->isValid()) {
309 return;
310 }
311 painter->m_gl->swapBuffers(painter->m_surface);
312 painter->m_gl->makeCurrent(painter->m_surface);
313#if defined(_WIN32) && defined(USE_EPOXY)
314 epoxy_handle_external_wglMakeCurrent();
315#endif
316 };
317
318 m_backend->init(m_backend, 0);
319#ifdef BUILD_GLES2
320 if (m_supportsShaders) {
321 m_shader.preprocessShader = static_cast<void*>(&reinterpret_cast<mGLES2Context*>(m_backend)->initialShader);
322 }
323#endif
324
325 m_backend->user = this;
326 m_backend->filter = false;
327 m_backend->lockAspectRatio = false;
328 m_backend->interframeBlending = false;
329
330 for (int i = 0; i < 3; ++i) {
331 m_free.append(new uint32_t[1024 * 2048]);
332 }
333}
334
335PainterGL::~PainterGL() {
336 while (!m_queue.isEmpty()) {
337 delete[] m_queue.dequeue();
338 }
339 for (auto item : m_free) {
340 delete[] item;
341 }
342 m_gl->makeCurrent(m_surface);
343#if defined(_WIN32) && defined(USE_EPOXY)
344 epoxy_handle_external_wglMakeCurrent();
345#endif
346#ifdef BUILD_GLES2
347 if (m_shader.passes) {
348 mGLES2ShaderFree(&m_shader);
349 }
350#endif
351 m_backend->deinit(m_backend);
352 m_gl->doneCurrent();
353 free(m_backend);
354 m_backend = nullptr;
355 delete m_window;
356}
357
358void PainterGL::setContext(std::shared_ptr<CoreController> context) {
359 m_context = context;
360 resizeContext();
361}
362
363void PainterGL::resizeContext() {
364 if (!m_context) {
365 return;
366 }
367
368 if (m_started) {
369 mCore* core = m_context->thread()->core;
370 core->reloadConfigOption(core, "videoScale", NULL);
371 }
372
373 QSize size = m_context->screenDimensions();
374 m_backend->setDimensions(m_backend, size.width(), size.height());
375}
376
377void PainterGL::setMessagePainter(MessagePainter* messagePainter) {
378 m_messagePainter = messagePainter;
379}
380
381void PainterGL::resize(const QSize& size) {
382 m_size = size;
383 m_window->setSize(m_size);
384 if (m_started && !m_active) {
385 forceDraw();
386 }
387}
388
389void PainterGL::lockAspectRatio(bool lock) {
390 m_backend->lockAspectRatio = lock;
391 resize(m_size);
392}
393
394void PainterGL::lockIntegerScaling(bool lock) {
395 m_backend->lockIntegerScaling = lock;
396 resize(m_size);
397}
398
399void PainterGL::interframeBlending(bool enable) {
400 m_backend->interframeBlending = enable;
401}
402
403void PainterGL::showOSD(bool enable) {
404 m_showOSD = enable;
405}
406
407void PainterGL::filter(bool filter) {
408 m_backend->filter = filter;
409 if (m_started && !m_active) {
410 forceDraw();
411 }
412}
413
414void PainterGL::start() {
415 m_gl->makeCurrent(m_surface);
416#if defined(_WIN32) && defined(USE_EPOXY)
417 epoxy_handle_external_wglMakeCurrent();
418#endif
419
420#ifdef BUILD_GLES2
421 if (m_supportsShaders && m_shader.passes) {
422 mGLES2ShaderAttach(reinterpret_cast<mGLES2Context*>(m_backend), static_cast<mGLES2Shader*>(m_shader.passes), m_shader.nPasses);
423 }
424#endif
425
426 m_buffer = nullptr;
427 m_active = true;
428 m_started = true;
429}
430
431void PainterGL::draw() {
432 if (!m_active || m_queue.isEmpty()) {
433 return;
434 }
435 mCoreSync* sync = &m_context->thread()->impl->sync;
436 mCoreSyncWaitFrameStart(sync);
437 dequeue();
438 if (!m_delayTimer.isValid()) {
439 m_delayTimer.start();
440 } else if (sync->audioWait || sync->videoFrameWait) {
441 while (m_delayTimer.nsecsElapsed() + 2000000 < 1000000000 / sync->fpsTarget) {
442 QThread::usleep(500);
443 }
444 m_delayTimer.restart();
445 }
446 mCoreSyncWaitFrameEnd(sync);
447
448 forceDraw();
449}
450
451void PainterGL::forceDraw() {
452 m_painter.begin(m_window);
453 performDraw();
454 m_painter.end();
455 if (!m_context->thread()->impl->sync.audioWait && !m_context->thread()->impl->sync.videoFrameWait) {
456 if (m_delayTimer.elapsed() < 1000 / m_surface->screen()->refreshRate()) {
457 return;
458 }
459 m_delayTimer.restart();
460 }
461 m_backend->swap(m_backend);
462}
463
464void PainterGL::stop() {
465 m_active = false;
466 m_started = false;
467 dequeueAll();
468 m_backend->clear(m_backend);
469 m_backend->swap(m_backend);
470 if (m_videoProxy) {
471 m_videoProxy->reset();
472 }
473 m_gl->doneCurrent();
474 m_gl->moveToThread(m_surface->thread());
475 m_context.reset();
476 moveToThread(m_gl->thread());
477 if (m_videoProxy) {
478 m_videoProxy->moveToThread(m_gl->thread());
479 }
480}
481
482void PainterGL::pause() {
483 m_active = false;
484}
485
486void PainterGL::unpause() {
487 m_active = true;
488}
489
490void PainterGL::performDraw() {
491 m_painter.beginNativePainting();
492 float r = m_surface->devicePixelRatio();
493 m_backend->resized(m_backend, m_size.width() * r, m_size.height() * r);
494 if (m_buffer) {
495 m_backend->postFrame(m_backend, m_buffer);
496 m_free.append(m_buffer);
497 m_buffer = nullptr;
498 }
499 m_backend->drawFrame(m_backend);
500 m_painter.endNativePainting();
501 if (m_showOSD && m_messagePainter) {
502 m_messagePainter->paint(&m_painter);
503 }
504}
505
506void PainterGL::enqueue(const uint32_t* backing) {
507 m_mutex.lock();
508 uint32_t* buffer = nullptr;
509 if (backing) {
510 if (m_free.isEmpty()) {
511 buffer = m_queue.dequeue();
512 } else {
513 buffer = m_free.takeLast();
514 }
515 QSize size = m_context->screenDimensions();
516 memcpy(buffer, backing, size.width() * size.height() * BYTES_PER_PIXEL);
517 }
518 m_queue.enqueue(buffer);
519 m_mutex.unlock();
520}
521
522void PainterGL::dequeue() {
523 m_mutex.lock();
524 if (m_queue.isEmpty()) {
525 m_mutex.unlock();
526 return;
527 }
528 uint32_t* buffer = m_queue.dequeue();
529 if (m_buffer) {
530 m_free.append(m_buffer);
531 m_buffer = nullptr;
532 }
533 if (buffer) {
534 m_buffer = buffer;
535 }
536 m_mutex.unlock();
537}
538
539void PainterGL::dequeueAll() {
540 uint32_t* buffer = 0;
541 m_mutex.lock();
542 while (!m_queue.isEmpty()) {
543 buffer = m_queue.dequeue();
544 if (buffer) {
545 m_free.append(buffer);
546 }
547 }
548 if (buffer) {
549 m_backend->postFrame(m_backend, buffer);
550 }
551 if (m_buffer) {
552 m_free.append(m_buffer);
553 m_buffer = nullptr;
554 }
555 m_mutex.unlock();
556}
557
558void PainterGL::setVideoProxy(std::shared_ptr<VideoProxy> proxy) {
559 m_videoProxy = proxy;
560}
561
562void PainterGL::setShaders(struct VDir* dir) {
563 if (!supportsShaders()) {
564 return;
565 }
566#ifdef BUILD_GLES2
567 if (!m_started) {
568 m_gl->makeCurrent(m_surface);
569#if defined(_WIN32) && defined(USE_EPOXY)
570 epoxy_handle_external_wglMakeCurrent();
571#endif
572 }
573 if (m_shader.passes) {
574 mGLES2ShaderDetach(reinterpret_cast<mGLES2Context*>(m_backend));
575 mGLES2ShaderFree(&m_shader);
576 }
577 mGLES2ShaderLoad(&m_shader, dir);
578 if (m_started) {
579 mGLES2ShaderAttach(reinterpret_cast<mGLES2Context*>(m_backend), static_cast<mGLES2Shader*>(m_shader.passes), m_shader.nPasses);
580 } else {
581 m_gl->doneCurrent();
582 }
583#endif
584}
585
586void PainterGL::clearShaders() {
587 if (!supportsShaders()) {
588 return;
589 }
590#ifdef BUILD_GLES2
591 if (!m_started) {
592 m_gl->makeCurrent(m_surface);
593#if defined(_WIN32) && defined(USE_EPOXY)
594 epoxy_handle_external_wglMakeCurrent();
595#endif
596 }
597 if (m_shader.passes) {
598 mGLES2ShaderDetach(reinterpret_cast<mGLES2Context*>(m_backend));
599 mGLES2ShaderFree(&m_shader);
600 }
601 if (!m_started) {
602 m_gl->doneCurrent();
603 }
604#endif
605}
606
607VideoShader* PainterGL::shaders() {
608 return &m_shader;
609}
610
611int PainterGL::glTex() {
612#ifdef BUILD_GLES2
613 if (supportsShaders()) {
614 mGLES2Context* gl2Backend = reinterpret_cast<mGLES2Context*>(m_backend);
615 return gl2Backend->tex;
616 }
617#endif
618#ifdef BUILD_GL
619 mGLContext* glBackend = reinterpret_cast<mGLContext*>(m_backend);
620 return glBackend->tex[0];
621#else
622 return -1;
623#endif
624}
625
626#endif