all repos — mgba @ aa12eeef3a8ea3eaed3d6d863b9f5cdbc4b0a8f1

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