all repos — mgba @ cde4e1adee349cb162b12301c861de0a3460e7fb

mGBA Game Boy Advance Emulator

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	if (m_started) {
360		mCore* core = m_context->thread()->core;
361		core->reloadConfigOption(core, "videoScale", NULL);
362	}
363
364	QSize size = m_context->screenDimensions();
365	m_backend->setDimensions(m_backend, size.width(), size.height());
366}
367
368void PainterGL::setMessagePainter(MessagePainter* messagePainter) {
369	m_messagePainter = messagePainter;
370}
371
372void PainterGL::resize(const QSize& size) {
373	m_size = size;
374	m_window->setSize(m_size);
375	if (m_started && !m_active) {
376		forceDraw();
377	}
378}
379
380void PainterGL::lockAspectRatio(bool lock) {
381	m_backend->lockAspectRatio = lock;
382	resize(m_size);
383}
384
385void PainterGL::lockIntegerScaling(bool lock) {
386	m_backend->lockIntegerScaling = lock;
387	resize(m_size);
388}
389
390void PainterGL::interframeBlending(bool enable) {
391	m_backend->interframeBlending = enable;
392}
393
394void PainterGL::showOSD(bool enable) {
395	m_showOSD = enable;
396}
397
398void PainterGL::filter(bool filter) {
399	m_backend->filter = filter;
400	if (m_started && !m_active) {
401		forceDraw();
402	}
403}
404
405void PainterGL::start() {
406	m_gl->makeCurrent(m_surface);
407#if defined(_WIN32) && defined(USE_EPOXY)
408	epoxy_handle_external_wglMakeCurrent();
409#endif
410
411#ifdef BUILD_GLES2
412	if (m_supportsShaders && m_shader.passes) {
413		mGLES2ShaderAttach(reinterpret_cast<mGLES2Context*>(m_backend), static_cast<mGLES2Shader*>(m_shader.passes), m_shader.nPasses);
414	}
415#endif
416
417	m_active = true;
418	m_started = true;
419}
420
421void PainterGL::draw() {
422	if (!m_active || m_queue.isEmpty()) {
423		return;
424	}
425	mCoreSync* sync = &m_context->thread()->impl->sync;
426	mCoreSyncWaitFrameStart(sync);
427	dequeue();
428	if (!m_delayTimer.isValid()) {
429		m_delayTimer.start();
430	} else if (sync->audioWait || sync->videoFrameWait) {
431		while (m_delayTimer.nsecsElapsed() + 2000000 < 1000000000 / sync->fpsTarget) {
432			QThread::usleep(500);
433		}
434		m_delayTimer.restart();
435	}
436	mCoreSyncWaitFrameEnd(sync);
437
438	forceDraw();
439}
440
441void PainterGL::forceDraw() {
442	m_painter.begin(m_window);
443	performDraw();
444	m_painter.end();
445	if (!m_context->thread()->impl->sync.audioWait && !m_context->thread()->impl->sync.videoFrameWait) {
446		if (m_delayTimer.elapsed() < 1000 / m_surface->screen()->refreshRate()) {
447			return;
448		}
449		m_delayTimer.restart();
450	}
451	m_backend->swap(m_backend);
452}
453
454void PainterGL::stop() {
455	m_active = false;
456	m_started = false;
457	dequeueAll();
458	m_backend->clear(m_backend);
459	m_backend->swap(m_backend);
460	if (m_videoProxy) {
461		m_videoProxy->reset();
462	}
463	m_gl->doneCurrent();
464	m_gl->moveToThread(m_surface->thread());
465	m_context.reset();
466	moveToThread(m_gl->thread());
467	if (m_videoProxy) {
468		m_videoProxy->moveToThread(m_gl->thread());
469	}
470}
471
472void PainterGL::pause() {
473	m_active = false;
474}
475
476void PainterGL::unpause() {
477	m_active = true;
478}
479
480void PainterGL::performDraw() {
481	m_painter.beginNativePainting();
482	float r = m_surface->devicePixelRatio();
483	m_backend->resized(m_backend, m_size.width() * r, m_size.height() * r);
484	m_backend->drawFrame(m_backend);
485	m_painter.endNativePainting();
486	if (m_showOSD && m_messagePainter) {
487		m_messagePainter->paint(&m_painter);
488	}
489}
490
491void PainterGL::enqueue(const uint32_t* backing) {
492	m_mutex.lock();
493	uint32_t* buffer = nullptr;
494	if (backing) {
495		if (m_free.isEmpty()) {
496			buffer = m_queue.dequeue();
497		} else {
498			buffer = m_free.takeLast();
499		}
500		QSize size = m_context->screenDimensions();
501		memcpy(buffer, backing, size.width() * size.height() * BYTES_PER_PIXEL);
502	}
503	m_queue.enqueue(buffer);
504	m_mutex.unlock();
505}
506
507void PainterGL::dequeue() {
508	m_mutex.lock();
509	if (m_queue.isEmpty()) {
510		m_mutex.unlock();
511		return;
512	}
513	uint32_t* buffer = m_queue.dequeue();
514	if (buffer) {
515		m_backend->postFrame(m_backend, buffer);
516		m_free.append(buffer);
517	}
518	m_mutex.unlock();
519}
520
521void PainterGL::dequeueAll() {
522	uint32_t* buffer = 0;
523	m_mutex.lock();
524	while (!m_queue.isEmpty()) {
525		buffer = m_queue.dequeue();
526		if (buffer) {
527			m_free.append(buffer);
528		}
529	}
530	if (buffer) {
531		m_backend->postFrame(m_backend, buffer);
532	}
533	m_mutex.unlock();
534}
535
536void PainterGL::setVideoProxy(std::shared_ptr<VideoProxy> proxy) {
537	m_videoProxy = proxy;
538}
539
540void PainterGL::setShaders(struct VDir* dir) {
541	if (!supportsShaders()) {
542		return;
543	}
544#ifdef BUILD_GLES2
545	if (!m_started) {
546		m_gl->makeCurrent(m_surface);
547#if defined(_WIN32) && defined(USE_EPOXY)
548		epoxy_handle_external_wglMakeCurrent();
549#endif
550	}
551	if (m_shader.passes) {
552		mGLES2ShaderDetach(reinterpret_cast<mGLES2Context*>(m_backend));
553		mGLES2ShaderFree(&m_shader);
554	}
555	mGLES2ShaderLoad(&m_shader, dir);
556	if (m_started) {
557		mGLES2ShaderAttach(reinterpret_cast<mGLES2Context*>(m_backend), static_cast<mGLES2Shader*>(m_shader.passes), m_shader.nPasses);
558	} else {
559		m_gl->doneCurrent();
560	}
561#endif
562}
563
564void PainterGL::clearShaders() {
565	if (!supportsShaders()) {
566		return;
567	}
568#ifdef BUILD_GLES2
569	if (m_shader.passes) {
570		mGLES2ShaderDetach(reinterpret_cast<mGLES2Context*>(m_backend));
571		mGLES2ShaderFree(&m_shader);
572	}
573#endif
574}
575
576VideoShader* PainterGL::shaders() {
577	return &m_shader;
578}
579
580int PainterGL::glTex() {
581#ifdef BUILD_GLES2
582	if (supportsShaders()) {
583		mGLES2Context* gl2Backend = reinterpret_cast<mGLES2Context*>(m_backend);
584		return gl2Backend->tex;
585	}
586#endif
587#ifdef BUILD_GL
588	mGLContext* glBackend = reinterpret_cast<mGLContext*>(m_backend);
589	return glBackend->tex[0];
590#else
591	return -1;
592#endif
593}
594
595#endif