all repos — mgba @ 7f4ca56af8d543c1dbf7b8ce12c3d7c6f2ce05d6

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