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#if defined(_WIN32) && defined(USE_EPOXY)
275 epoxy_handle_external_wglMakeCurrent();
276#endif
277
278#ifdef BUILD_GLES2
279 auto version = m_gl->format().version();
280 QStringList extensions = QString(reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS))).split(' ');
281 if (forceVersion != 1 && ((version == qMakePair(2, 1) && extensions.contains("GL_ARB_framebuffer_object")) || version.first > 2)) {
282 gl2Backend = static_cast<mGLES2Context*>(malloc(sizeof(mGLES2Context)));
283 mGLES2ContextCreate(gl2Backend);
284 m_backend = &gl2Backend->d;
285 m_supportsShaders = true;
286 }
287#endif
288
289#ifdef BUILD_GL
290 if (!m_backend) {
291 glBackend = static_cast<mGLContext*>(malloc(sizeof(mGLContext)));
292 mGLContextCreate(glBackend);
293 m_backend = &glBackend->d;
294 m_supportsShaders = false;
295 }
296#endif
297 m_backend->swap = [](VideoBackend* v) {
298 PainterGL* painter = static_cast<PainterGL*>(v->user);
299 if (!painter->m_gl->isValid()) {
300 return;
301 }
302 painter->m_gl->swapBuffers(painter->m_surface);
303 painter->m_gl->makeCurrent(painter->m_surface);
304#if defined(_WIN32) && defined(USE_EPOXY)
305 epoxy_handle_external_wglMakeCurrent();
306#endif
307 };
308
309 m_backend->init(m_backend, 0);
310#ifdef BUILD_GLES2
311 if (m_supportsShaders) {
312 m_shader.preprocessShader = static_cast<void*>(&reinterpret_cast<mGLES2Context*>(m_backend)->initialShader);
313 }
314#endif
315
316 m_backend->user = this;
317 m_backend->filter = false;
318 m_backend->lockAspectRatio = false;
319 m_backend->interframeBlending = false;
320
321 for (int i = 0; i < 2; ++i) {
322 m_free.append(new uint32_t[1024 * 2048]);
323 }
324}
325
326PainterGL::~PainterGL() {
327 while (!m_queue.isEmpty()) {
328 delete[] m_queue.dequeue();
329 }
330 for (auto item : m_free) {
331 delete[] item;
332 }
333 m_gl->makeCurrent(m_surface);
334#if defined(_WIN32) && defined(USE_EPOXY)
335 epoxy_handle_external_wglMakeCurrent();
336#endif
337#ifdef BUILD_GLES2
338 if (m_shader.passes) {
339 mGLES2ShaderFree(&m_shader);
340 }
341#endif
342 m_backend->deinit(m_backend);
343 m_gl->doneCurrent();
344 free(m_backend);
345 m_backend = nullptr;
346 delete m_window;
347}
348
349void PainterGL::setContext(std::shared_ptr<CoreController> context) {
350 m_context = context;
351 resizeContext();
352}
353
354void PainterGL::resizeContext() {
355 if (!m_context) {
356 return;
357 }
358
359 mCore* core = m_context->thread()->core;
360 core->reloadConfigOption(core, "videoScale", NULL);
361
362 QSize size = m_context->screenDimensions();
363 m_backend->setDimensions(m_backend, size.width(), size.height());
364}
365
366void PainterGL::setMessagePainter(MessagePainter* messagePainter) {
367 m_messagePainter = messagePainter;
368}
369
370void PainterGL::resize(const QSize& size) {
371 m_size = size;
372 m_window->setSize(m_size);
373 if (m_started && !m_active) {
374 forceDraw();
375 }
376}
377
378void PainterGL::lockAspectRatio(bool lock) {
379 m_backend->lockAspectRatio = lock;
380 resize(m_size);
381}
382
383void PainterGL::lockIntegerScaling(bool lock) {
384 m_backend->lockIntegerScaling = lock;
385 resize(m_size);
386}
387
388void PainterGL::interframeBlending(bool enable) {
389 m_backend->interframeBlending = enable;
390}
391
392void PainterGL::showOSD(bool enable) {
393 m_showOSD = enable;
394}
395
396void PainterGL::filter(bool filter) {
397 m_backend->filter = filter;
398 if (m_started && !m_active) {
399 forceDraw();
400 }
401}
402
403void PainterGL::start() {
404 m_gl->makeCurrent(m_surface);
405#if defined(_WIN32) && defined(USE_EPOXY)
406 epoxy_handle_external_wglMakeCurrent();
407#endif
408
409#ifdef BUILD_GLES2
410 if (m_supportsShaders && m_shader.passes) {
411 mGLES2ShaderAttach(reinterpret_cast<mGLES2Context*>(m_backend), static_cast<mGLES2Shader*>(m_shader.passes), m_shader.nPasses);
412 }
413#endif
414
415 m_active = true;
416 m_started = true;
417}
418
419void PainterGL::draw() {
420 if (!m_active || m_queue.isEmpty()) {
421 return;
422 }
423 mCoreSync* sync = &m_context->thread()->impl->sync;
424 mCoreSyncWaitFrameStart(sync);
425 dequeue();
426 if (!m_delayTimer.isValid()) {
427 m_delayTimer.start();
428 } else if (sync->audioWait || sync->videoFrameWait) {
429 while (m_delayTimer.nsecsElapsed() + 2000000 < 1000000000 / sync->fpsTarget) {
430 QThread::usleep(500);
431 }
432 m_delayTimer.restart();
433 }
434 mCoreSyncWaitFrameEnd(sync);
435
436 forceDraw();
437}
438
439void PainterGL::forceDraw() {
440 m_painter.begin(m_window);
441 performDraw();
442 m_painter.end();
443 if (!m_context->thread()->impl->sync.audioWait && !m_context->thread()->impl->sync.videoFrameWait) {
444 if (m_delayTimer.elapsed() < 1000 / m_surface->screen()->refreshRate()) {
445 return;
446 }
447 m_delayTimer.restart();
448 }
449 m_backend->swap(m_backend);
450}
451
452void PainterGL::stop() {
453 m_active = false;
454 m_started = false;
455 dequeueAll();
456 m_backend->clear(m_backend);
457 m_backend->swap(m_backend);
458 if (m_videoProxy) {
459 m_videoProxy->reset();
460 }
461 m_gl->doneCurrent();
462 m_gl->moveToThread(m_surface->thread());
463 m_context.reset();
464 moveToThread(m_gl->thread());
465 if (m_videoProxy) {
466 m_videoProxy->moveToThread(m_gl->thread());
467 }
468}
469
470void PainterGL::pause() {
471 m_active = false;
472}
473
474void PainterGL::unpause() {
475 m_active = true;
476}
477
478void PainterGL::performDraw() {
479 m_painter.beginNativePainting();
480 float r = m_surface->devicePixelRatio();
481 m_backend->resized(m_backend, m_size.width() * r, m_size.height() * r);
482 m_backend->drawFrame(m_backend);
483 m_painter.endNativePainting();
484 if (m_showOSD && m_messagePainter) {
485 m_messagePainter->paint(&m_painter);
486 }
487}
488
489void PainterGL::enqueue(const uint32_t* backing) {
490 m_mutex.lock();
491 uint32_t* buffer = nullptr;
492 if (backing) {
493 if (m_free.isEmpty()) {
494 buffer = m_queue.dequeue();
495 } else {
496 buffer = m_free.takeLast();
497 }
498 QSize size = m_context->screenDimensions();
499 memcpy(buffer, backing, size.width() * size.height() * BYTES_PER_PIXEL);
500 }
501 m_queue.enqueue(buffer);
502 m_mutex.unlock();
503}
504
505void PainterGL::dequeue() {
506 m_mutex.lock();
507 if (m_queue.isEmpty()) {
508 m_mutex.unlock();
509 return;
510 }
511 uint32_t* buffer = m_queue.dequeue();
512 if (buffer) {
513 m_backend->postFrame(m_backend, buffer);
514 m_free.append(buffer);
515 }
516 m_mutex.unlock();
517}
518
519void PainterGL::dequeueAll() {
520 uint32_t* buffer = 0;
521 m_mutex.lock();
522 while (!m_queue.isEmpty()) {
523 buffer = m_queue.dequeue();
524 if (buffer) {
525 m_free.append(buffer);
526 }
527 }
528 if (buffer) {
529 m_backend->postFrame(m_backend, buffer);
530 }
531 m_mutex.unlock();
532}
533
534void PainterGL::setVideoProxy(std::shared_ptr<VideoProxy> proxy) {
535 m_videoProxy = proxy;
536}
537
538void PainterGL::setShaders(struct VDir* dir) {
539 if (!supportsShaders()) {
540 return;
541 }
542#ifdef BUILD_GLES2
543 if (!m_started) {
544 m_gl->makeCurrent(m_surface);
545#if defined(_WIN32) && defined(USE_EPOXY)
546 epoxy_handle_external_wglMakeCurrent();
547#endif
548 }
549 if (m_shader.passes) {
550 mGLES2ShaderDetach(reinterpret_cast<mGLES2Context*>(m_backend));
551 mGLES2ShaderFree(&m_shader);
552 }
553 mGLES2ShaderLoad(&m_shader, dir);
554 if (m_started) {
555 mGLES2ShaderAttach(reinterpret_cast<mGLES2Context*>(m_backend), static_cast<mGLES2Shader*>(m_shader.passes), m_shader.nPasses);
556 } else {
557 m_gl->doneCurrent();
558 }
559#endif
560}
561
562void PainterGL::clearShaders() {
563 if (!supportsShaders()) {
564 return;
565 }
566#ifdef BUILD_GLES2
567 if (m_shader.passes) {
568 mGLES2ShaderDetach(reinterpret_cast<mGLES2Context*>(m_backend));
569 mGLES2ShaderFree(&m_shader);
570 }
571#endif
572}
573
574VideoShader* PainterGL::shaders() {
575 return &m_shader;
576}
577
578int PainterGL::glTex() {
579#ifdef BUILD_GLES2
580 if (supportsShaders()) {
581 mGLES2Context* gl2Backend = reinterpret_cast<mGLES2Context*>(m_backend);
582 return gl2Backend->tex;
583 }
584#endif
585#ifdef BUILD_GL
586 mGLContext* glBackend = reinterpret_cast<mGLContext*>(m_backend);
587 return glBackend->tex[0];
588#else
589 return -1;
590#endif
591}
592
593#endif