all repos — mgba @ fcb5a4168fed46dffb4572d193182d6b25d71b39

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