all repos — mgba @ 38a4e9988f8c6c210b2fd70790ff1f0f7006515b

mGBA Game Boy Advance Emulator

src/platform/qt/GameController.cpp (view raw)

  1/* Copyright (c) 2013-2014 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 "GameController.h"
  7
  8#include "AudioProcessor.h"
  9#include "InputController.h"
 10
 11#include <QThread>
 12
 13extern "C" {
 14#include "gba.h"
 15#include "gba-audio.h"
 16#include "gba-serialize.h"
 17#include "renderers/video-software.h"
 18#include "util/vfs.h"
 19}
 20
 21using namespace QGBA;
 22
 23GameController::GameController(QObject* parent)
 24	: QObject(parent)
 25	, m_drawContext(new uint32_t[256 * 256])
 26	, m_threadContext()
 27	, m_activeKeys(0)
 28	, m_logLevels(0)
 29	, m_gameOpen(false)
 30	, m_audioThread(new QThread(this))
 31	, m_audioProcessor(AudioProcessor::create())
 32	, m_videoSync(VIDEO_SYNC)
 33	, m_audioSync(AUDIO_SYNC)
 34	, m_turbo(false)
 35	, m_turboForced(false)
 36	, m_inputController(nullptr)
 37{
 38	m_renderer = new GBAVideoSoftwareRenderer;
 39	GBAVideoSoftwareRendererCreate(m_renderer);
 40	m_renderer->outputBuffer = (color_t*) m_drawContext;
 41	m_renderer->outputBufferStride = 256;
 42	m_threadContext.state = THREAD_INITIALIZED;
 43	m_threadContext.debugger = 0;
 44	m_threadContext.frameskip = 0;
 45	m_threadContext.bios = 0;
 46	m_threadContext.renderer = &m_renderer->d;
 47	m_threadContext.userData = this;
 48	m_threadContext.rewindBufferCapacity = 0;
 49	m_threadContext.logLevel = -1;
 50
 51	m_lux.p = this;
 52	m_lux.sample = [] (GBALuminanceSource* context) {
 53		GameControllerLux* lux = static_cast<GameControllerLux*>(context);
 54		lux->value = 0xFF - lux->p->m_luxValue;
 55	};
 56
 57	m_lux.readLuminance = [] (GBALuminanceSource* context) {
 58		GameControllerLux* lux = static_cast<GameControllerLux*>(context);
 59		return lux->value;
 60	};
 61
 62	m_threadContext.startCallback = [] (GBAThread* context) {
 63		GameController* controller = static_cast<GameController*>(context->userData);
 64		controller->m_audioProcessor->setInput(context);
 65		context->gba->luminanceSource = &controller->m_lux;
 66		controller->gameStarted(context);
 67	};
 68
 69	m_threadContext.cleanCallback = [] (GBAThread* context) {
 70		GameController* controller = static_cast<GameController*>(context->userData);
 71		controller->gameStopped(context);
 72	};
 73
 74	m_threadContext.frameCallback = [] (GBAThread* context) {
 75		GameController* controller = static_cast<GameController*>(context->userData);
 76		controller->m_pauseMutex.lock();
 77		if (controller->m_pauseAfterFrame) {
 78			GBAThreadPauseFromThread(context);
 79			controller->m_pauseAfterFrame = false;
 80			controller->gamePaused(&controller->m_threadContext);
 81		}
 82		controller->m_pauseMutex.unlock();
 83		controller->frameAvailable(controller->m_drawContext);
 84	};
 85
 86	m_threadContext.logHandler = [] (GBAThread* context, enum GBALogLevel level, const char* format, va_list args) {
 87		GameController* controller = static_cast<GameController*>(context->userData);
 88		if (level == GBA_LOG_FATAL) {
 89			MutexLock(&controller->m_threadContext.stateMutex);
 90			controller->m_threadContext.state = THREAD_EXITING;
 91			MutexUnlock(&controller->m_threadContext.stateMutex);
 92			QMetaObject::invokeMethod(controller, "crashGame", Q_ARG(const QString&, QString().vsprintf(format, args)));
 93		} else if (!(controller->m_logLevels & level)) {
 94			return;
 95		}
 96		controller->postLog(level, QString().vsprintf(format, args));
 97	};
 98
 99	m_audioThread->start(QThread::TimeCriticalPriority);
100	m_audioProcessor->moveToThread(m_audioThread);
101	connect(this, SIGNAL(gameStarted(GBAThread*)), m_audioProcessor, SLOT(start()));
102	connect(this, SIGNAL(gameStopped(GBAThread*)), m_audioProcessor, SLOT(pause()));
103	connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
104	connect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));
105
106#ifdef BUILD_SDL
107	connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(testSDLEvents()));
108#endif
109}
110
111GameController::~GameController() {
112	m_audioThread->quit();
113	m_audioThread->wait();
114	disconnect();
115	closeGame();
116	delete m_renderer;
117	delete[] m_drawContext;
118}
119
120#ifdef USE_GDB_STUB
121ARMDebugger* GameController::debugger() {
122	return m_threadContext.debugger;
123}
124
125void GameController::setDebugger(ARMDebugger* debugger) {
126	bool wasPaused = isPaused();
127	setPaused(true);
128	if (m_threadContext.debugger && GBAThreadHasStarted(&m_threadContext)) {
129		GBADetachDebugger(m_threadContext.gba);
130	}
131	m_threadContext.debugger = debugger;
132	if (m_threadContext.debugger && GBAThreadHasStarted(&m_threadContext)) {
133		GBAAttachDebugger(m_threadContext.gba, m_threadContext.debugger);
134	}
135	setPaused(wasPaused);
136}
137#endif
138
139void GameController::loadGame(const QString& path, bool dirmode) {
140	closeGame();
141	if (!dirmode) {
142		QFile file(path);
143		if (!file.open(QIODevice::ReadOnly)) {
144			return;
145		}
146		file.close();
147	}
148
149	m_fname = path;
150	m_dirmode = dirmode;
151	openGame();
152}
153
154void GameController::openGame() {
155	m_gameOpen = true;
156
157	m_pauseAfterFrame = false;
158
159	if (m_turbo) {
160		m_threadContext.sync.videoFrameWait = false;
161		m_threadContext.sync.audioWait = false;
162	} else {
163		m_threadContext.sync.videoFrameWait = m_videoSync;
164		m_threadContext.sync.audioWait = m_audioSync;
165	}
166
167	m_threadContext.fname = strdup(m_fname.toLocal8Bit().constData());
168	if (m_dirmode) {
169		m_threadContext.gameDir = VDirOpen(m_threadContext.fname);
170		m_threadContext.stateDir = m_threadContext.gameDir;
171	} else {
172		m_threadContext.rom = VFileOpen(m_threadContext.fname, O_RDONLY);
173#if ENABLE_LIBZIP
174		m_threadContext.gameDir = VDirOpenZip(m_threadContext.fname, 0);
175#endif
176	}
177
178	if (!m_bios.isNull()) {
179		m_threadContext.bios = VFileOpen(m_bios.toLocal8Bit().constData(), O_RDONLY);
180	}
181
182	if (!m_patch.isNull()) {
183		m_threadContext.patch = VFileOpen(m_patch.toLocal8Bit().constData(), O_RDONLY);
184	}
185
186	if (!GBAThreadStart(&m_threadContext)) {
187		m_gameOpen = false;
188	}
189}
190
191void GameController::loadBIOS(const QString& path) {
192	if (m_bios == path) {
193		return;
194	}
195	m_bios = path;
196	if (m_gameOpen) {
197		closeGame();
198		openGame();
199	}
200}
201
202void GameController::loadPatch(const QString& path) {
203	m_patch = path;
204	if (m_gameOpen) {
205		closeGame();
206		openGame();
207	}
208}
209
210void GameController::closeGame() {
211	if (!m_gameOpen) {
212		return;
213	}
214	if (GBAThreadIsPaused(&m_threadContext)) {
215		GBAThreadUnpause(&m_threadContext);
216	}
217	GBAThreadEnd(&m_threadContext);
218	GBAThreadJoin(&m_threadContext);
219	if (m_threadContext.fname) {
220		free(const_cast<char*>(m_threadContext.fname));
221		m_threadContext.fname = nullptr;
222	}
223
224	m_patch = QString();
225
226	m_gameOpen = false;
227	emit gameStopped(&m_threadContext);
228}
229
230void GameController::crashGame(const QString& crashMessage) {
231	closeGame();
232	emit gameCrashed(crashMessage);
233}
234
235bool GameController::isPaused() {
236	if (!m_gameOpen) {
237		return false;
238	}
239	return GBAThreadIsPaused(&m_threadContext);
240}
241
242void GameController::setPaused(bool paused) {
243	if (paused == GBAThreadIsPaused(&m_threadContext)) {
244		return;
245	}
246	if (paused) {
247		GBAThreadPause(&m_threadContext);
248		emit gamePaused(&m_threadContext);
249	} else {
250		GBAThreadUnpause(&m_threadContext);
251		emit gameUnpaused(&m_threadContext);
252	}
253}
254
255void GameController::reset() {
256	GBAThreadReset(&m_threadContext);
257}
258
259void GameController::threadInterrupt() {
260	if (m_gameOpen) {
261		GBAThreadInterrupt(&m_threadContext);
262	}
263}
264
265void GameController::threadContinue() {
266	if (m_gameOpen) {
267		GBAThreadContinue(&m_threadContext);
268	}
269}
270
271void GameController::frameAdvance() {
272	m_pauseMutex.lock();
273	m_pauseAfterFrame = true;
274	setPaused(false);
275	m_pauseMutex.unlock();
276}
277
278void GameController::keyPressed(int key) {
279	int mappedKey = 1 << key;
280	m_activeKeys |= mappedKey;
281	updateKeys();
282}
283
284void GameController::keyReleased(int key) {
285	int mappedKey = 1 << key;
286	m_activeKeys &= ~mappedKey;
287	updateKeys();
288}
289
290void GameController::setAudioBufferSamples(int samples) {
291	threadInterrupt();
292	redoSamples(samples);
293	threadContinue();
294	QMetaObject::invokeMethod(m_audioProcessor, "setBufferSamples", Q_ARG(int, samples));
295}
296
297void GameController::setFPSTarget(float fps) {
298	threadInterrupt();
299	m_threadContext.fpsTarget = fps;
300	redoSamples(m_audioProcessor->getBufferSamples());
301	threadContinue();
302	QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
303}
304
305void GameController::setSkipBIOS(bool set) {
306	threadInterrupt();
307	m_threadContext.skipBios = set;
308	threadContinue();
309}
310
311void GameController::loadState(int slot) {
312	threadInterrupt();
313	GBALoadState(m_threadContext.gba, m_threadContext.stateDir, slot);
314	threadContinue();
315	emit stateLoaded(&m_threadContext);
316	emit frameAvailable(m_drawContext);
317}
318
319void GameController::saveState(int slot) {
320	threadInterrupt();
321	GBASaveState(m_threadContext.gba, m_threadContext.stateDir, slot, true);
322	threadContinue();
323}
324
325void GameController::setVideoSync(bool set) {
326	m_videoSync = set;
327	if (!m_turbo) {
328		threadInterrupt();
329		m_threadContext.sync.videoFrameWait = set;
330		threadContinue();
331	}
332}
333
334void GameController::setAudioSync(bool set) {
335	m_audioSync = set;
336	if (!m_turbo) {
337		threadInterrupt();
338		m_threadContext.sync.audioWait = set;
339		threadContinue();
340	}
341}
342
343void GameController::setFrameskip(int skip) {
344	m_threadContext.frameskip = skip;
345}
346
347void GameController::setTurbo(bool set, bool forced) {
348	if (m_turboForced && !forced) {
349		return;
350	}
351	m_turbo = set;
352	if (set) {
353		m_turboForced = forced;
354	} else {
355		m_turboForced = false;
356	}
357	threadInterrupt();
358	m_threadContext.sync.audioWait = set ? false : m_audioSync;
359	m_threadContext.sync.videoFrameWait = set ? false : m_videoSync;
360	threadContinue();
361}
362
363void GameController::setAVStream(GBAAVStream* stream) {
364	threadInterrupt();
365	m_threadContext.stream = stream;
366	threadContinue();
367}
368
369void GameController::clearAVStream() {
370	threadInterrupt();
371	m_threadContext.stream = nullptr;
372	threadContinue();
373}
374
375void GameController::updateKeys() {
376	int activeKeys = m_activeKeys;
377#ifdef BUILD_SDL
378	activeKeys |= m_activeButtons;
379#endif
380	m_threadContext.activeKeys = activeKeys;
381}
382
383void GameController::redoSamples(int samples) {
384#if RESAMPLE_LIBRARY != RESAMPLE_BLIP_BUF
385	float sampleRate = 0x8000;
386	float ratio;
387	if (m_threadContext.gba) {
388		sampleRate = m_threadContext.gba->audio.sampleRate;
389	}
390	ratio = GBAAudioCalculateRatio(sampleRate, m_threadContext.fpsTarget, 44100);
391	m_threadContext.audioBuffers = ceil(samples / ratio);
392#else
393	m_threadContext.audioBuffers = samples;
394#endif
395	if (m_threadContext.gba) {
396		GBAAudioResizeBuffer(&m_threadContext.gba->audio, m_threadContext.audioBuffers);
397	}
398}
399
400void GameController::setLogLevel(int levels) {
401	threadInterrupt();
402	m_logLevels = levels;
403	threadContinue();
404}
405
406void GameController::enableLogLevel(int levels) {
407	threadInterrupt();
408	m_logLevels |= levels;
409	threadContinue();
410}
411
412void GameController::disableLogLevel(int levels) {
413	threadInterrupt();
414	m_logLevels &= ~levels;
415	threadContinue();
416}
417
418#ifdef BUILD_SDL
419void GameController::testSDLEvents() {
420	if (!m_inputController) {
421		return;
422	}
423
424	m_activeButtons = m_inputController->testSDLEvents();
425	updateKeys();
426}
427#endif