all repos — mgba @ 0cc8046121def54e9fbb29ff28c137b4f3909841

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