all repos — mgba @ 2a9a738bfb76d540f39d8145d014170d8b095f52

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#include "MultiplayerController.h"
 11
 12#include <QDateTime>
 13#include <QThread>
 14
 15#include <ctime>
 16
 17extern "C" {
 18#include "gba/audio.h"
 19#include "gba/gba.h"
 20#include "gba/serialize.h"
 21#include "gba/renderers/video-software.h"
 22#include "gba/supervisor/config.h"
 23#include "util/vfs.h"
 24}
 25
 26using namespace QGBA;
 27using namespace std;
 28
 29const int GameController::LUX_LEVELS[10] = { 5, 11, 18, 27, 42, 62, 84, 109, 139, 183 };
 30
 31GameController::GameController(QObject* parent)
 32	: QObject(parent)
 33	, m_drawContext(new uint32_t[256 * 256])
 34	, m_threadContext()
 35	, m_activeKeys(0)
 36	, m_inactiveKeys(0)
 37	, m_logLevels(0)
 38	, m_gameOpen(false)
 39	, m_audioThread(new QThread(this))
 40	, m_audioProcessor(AudioProcessor::create())
 41	, m_videoSync(VIDEO_SYNC)
 42	, m_audioSync(AUDIO_SYNC)
 43	, m_turbo(false)
 44	, m_turboForced(false)
 45	, m_inputController(nullptr)
 46	, m_multiplayer(nullptr)
 47{
 48	m_renderer = new GBAVideoSoftwareRenderer;
 49	GBAVideoSoftwareRendererCreate(m_renderer);
 50	m_renderer->outputBuffer = (color_t*) m_drawContext;
 51	m_renderer->outputBufferStride = 256;
 52
 53	GBACheatDeviceCreate(&m_cheatDevice);
 54
 55	m_threadContext.state = THREAD_INITIALIZED;
 56	m_threadContext.debugger = 0;
 57	m_threadContext.frameskip = 0;
 58	m_threadContext.bios = 0;
 59	m_threadContext.renderer = &m_renderer->d;
 60	m_threadContext.userData = this;
 61	m_threadContext.rewindBufferCapacity = 0;
 62	m_threadContext.cheats = &m_cheatDevice;
 63	m_threadContext.logLevel = -1;
 64
 65	m_lux.p = this;
 66	m_lux.sample = [] (GBALuminanceSource* context) {
 67		GameControllerLux* lux = static_cast<GameControllerLux*>(context);
 68		lux->value = 0xFF - lux->p->m_luxValue;
 69	};
 70
 71	m_lux.readLuminance = [] (GBALuminanceSource* context) {
 72		GameControllerLux* lux = static_cast<GameControllerLux*>(context);
 73		return lux->value;
 74	};
 75	setLuminanceLevel(0);
 76
 77	m_rtc.p = this;
 78	m_rtc.override = GameControllerRTC::NO_OVERRIDE;
 79	m_rtc.sample = [] (GBARTCSource* context) { };
 80	m_rtc.unixTime = [] (GBARTCSource* context) -> time_t {
 81		GameControllerRTC* rtc = static_cast<GameControllerRTC*>(context);
 82		switch (rtc->override) {
 83		case GameControllerRTC::NO_OVERRIDE:
 84		default:
 85			return time(nullptr);
 86		case GameControllerRTC::FIXED:
 87			return rtc->value;
 88		case GameControllerRTC::FAKE_EPOCH:
 89			return rtc->value + rtc->p->m_threadContext.gba->video.frameCounter * (int64_t) VIDEO_TOTAL_LENGTH / GBA_ARM7TDMI_FREQUENCY;
 90		}
 91	};
 92
 93	m_threadContext.startCallback = [] (GBAThread* context) {
 94		GameController* controller = static_cast<GameController*>(context->userData);
 95		controller->m_audioProcessor->setInput(context);
 96		// Override the GBA object's log level to prevent stdout spew
 97		context->gba->logLevel = GBA_LOG_FATAL;
 98		context->gba->luminanceSource = &controller->m_lux;
 99		context->gba->rtcSource = &controller->m_rtc;
100		controller->gameStarted(context);
101	};
102
103	m_threadContext.cleanCallback = [] (GBAThread* context) {
104		GameController* controller = static_cast<GameController*>(context->userData);
105		controller->gameStopped(context);
106	};
107
108	m_threadContext.frameCallback = [] (GBAThread* context) {
109		GameController* controller = static_cast<GameController*>(context->userData);
110		controller->m_pauseMutex.lock();
111		if (controller->m_pauseAfterFrame) {
112			GBAThreadPauseFromThread(context);
113			controller->m_pauseAfterFrame = false;
114			controller->gamePaused(&controller->m_threadContext);
115		}
116		controller->m_pauseMutex.unlock();
117		controller->frameAvailable(controller->m_drawContext);
118	};
119
120	m_threadContext.logHandler = [] (GBAThread* context, enum GBALogLevel level, const char* format, va_list args) {
121		static const char* stubMessage = "Stub software interrupt";
122		GameController* controller = static_cast<GameController*>(context->userData);
123		if (level == GBA_LOG_STUB && strncmp(stubMessage, format, strlen(stubMessage)) == 0) {
124			va_list argc;
125			va_copy(argc, args);
126			int immediate = va_arg(argc, int);
127			controller->unimplementedBiosCall(immediate);
128		}
129		if (level == GBA_LOG_FATAL) {
130			QMetaObject::invokeMethod(controller, "crashGame", Q_ARG(const QString&, QString().vsprintf(format, args)));
131		} else if (!(controller->m_logLevels & level)) {
132			return;
133		}
134		controller->postLog(level, QString().vsprintf(format, args));
135	};
136
137	m_audioThread->start(QThread::TimeCriticalPriority);
138	m_audioProcessor->moveToThread(m_audioThread);
139	connect(this, SIGNAL(gameStarted(GBAThread*)), m_audioProcessor, SLOT(start()));
140	connect(this, SIGNAL(gameStopped(GBAThread*)), m_audioProcessor, SLOT(pause()));
141	connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
142	connect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));
143
144#ifdef BUILD_SDL
145	connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(testSDLEvents()));
146#endif
147}
148
149GameController::~GameController() {
150	m_audioThread->quit();
151	m_audioThread->wait();
152	disconnect();
153	clearMultiplayerController();
154	closeGame();
155	GBACheatDeviceDestroy(&m_cheatDevice);
156	delete m_renderer;
157	delete[] m_drawContext;
158}
159
160void GameController::setMultiplayerController(std::shared_ptr<MultiplayerController> controller) {
161	if (controller == m_multiplayer) {
162		return;
163	}
164	clearMultiplayerController();
165	m_multiplayer = controller;
166	controller->attachGame(this);
167}
168
169void GameController::clearMultiplayerController() {
170	if (!m_multiplayer) {
171		return;
172	}
173	m_multiplayer->detachGame(this);
174	m_multiplayer.reset();
175}
176
177void GameController::setOverride(const GBACartridgeOverride& override) {
178	m_threadContext.override = override;
179	m_threadContext.hasOverride = true;
180}
181
182void GameController::setOptions(const GBAOptions* opts) {
183	setFrameskip(opts->frameskip);
184	setAudioSync(opts->audioSync);
185	setVideoSync(opts->videoSync);
186	setSkipBIOS(opts->skipBios);
187	setUseBIOS(opts->useBios);
188	setRewind(opts->rewindEnable, opts->rewindBufferCapacity, opts->rewindBufferInterval);
189	setVolume(opts->volume);
190	setMute(opts->mute);
191
192	threadInterrupt();
193	m_threadContext.idleOptimization = opts->idleOptimization;
194	threadContinue();
195}
196
197#ifdef USE_GDB_STUB
198ARMDebugger* GameController::debugger() {
199	return m_threadContext.debugger;
200}
201
202void GameController::setDebugger(ARMDebugger* debugger) {
203	threadInterrupt();
204	if (m_threadContext.debugger && GBAThreadIsActive(&m_threadContext)) {
205		GBADetachDebugger(m_threadContext.gba);
206	}
207	m_threadContext.debugger = debugger;
208	if (m_threadContext.debugger && GBAThreadIsActive(&m_threadContext)) {
209		GBAAttachDebugger(m_threadContext.gba, m_threadContext.debugger);
210	}
211	threadContinue();
212}
213#endif
214
215void GameController::loadGame(const QString& path, bool dirmode) {
216	closeGame();
217	if (!dirmode) {
218		QFile file(path);
219		if (!file.open(QIODevice::ReadOnly)) {
220			return;
221		}
222		file.close();
223	}
224
225	m_fname = path;
226	m_dirmode = dirmode;
227	openGame();
228}
229
230void GameController::openGame() {
231	m_gameOpen = true;
232
233	m_pauseAfterFrame = false;
234
235	if (m_turbo) {
236		m_threadContext.sync.videoFrameWait = false;
237		m_threadContext.sync.audioWait = false;
238	} else {
239		m_threadContext.sync.videoFrameWait = m_videoSync;
240		m_threadContext.sync.audioWait = m_audioSync;
241	}
242
243	m_threadContext.gameDir = 0;
244	m_threadContext.fname = strdup(m_fname.toLocal8Bit().constData());
245	if (m_dirmode) {
246		m_threadContext.gameDir = VDirOpen(m_threadContext.fname);
247		m_threadContext.stateDir = m_threadContext.gameDir;
248	} else {
249		m_threadContext.rom = VFileOpen(m_threadContext.fname, O_RDONLY);
250#if USE_LIBZIP
251		if (!m_threadContext.gameDir) {
252			m_threadContext.gameDir = VDirOpenZip(m_threadContext.fname, 0);
253		}
254#endif
255#if USE_LZMA
256		if (!m_threadContext.gameDir) {
257			m_threadContext.gameDir = VDirOpen7z(m_threadContext.fname, 0);
258		}
259#endif
260	}
261
262	if (!m_bios.isNull() &&m_useBios) {
263		m_threadContext.bios = VFileOpen(m_bios.toLocal8Bit().constData(), O_RDONLY);
264	} else {
265		m_threadContext.bios = nullptr;
266	}
267
268	if (!m_patch.isNull()) {
269		m_threadContext.patch = VFileOpen(m_patch.toLocal8Bit().constData(), O_RDONLY);
270	}
271
272	if (!GBAThreadStart(&m_threadContext)) {
273		m_gameOpen = false;
274		emit gameFailed();
275	}
276}
277
278void GameController::loadBIOS(const QString& path) {
279	if (m_bios == path) {
280		return;
281	}
282	m_bios = path;
283	if (m_gameOpen) {
284		closeGame();
285		openGame();
286	}
287}
288
289void GameController::loadPatch(const QString& path) {
290	if (m_gameOpen) {
291		closeGame();
292		m_patch = path;
293		openGame();
294	} else {
295		m_patch = path;
296	}
297}
298
299void GameController::closeGame() {
300	if (!m_gameOpen) {
301		return;
302	}
303	if (GBAThreadIsPaused(&m_threadContext)) {
304		GBAThreadUnpause(&m_threadContext);
305	}
306	GBAThreadEnd(&m_threadContext);
307	GBAThreadJoin(&m_threadContext);
308	if (m_threadContext.fname) {
309		free(const_cast<char*>(m_threadContext.fname));
310		m_threadContext.fname = nullptr;
311	}
312
313	m_patch = QString();
314
315	for (size_t i = 0; i < GBACheatSetsSize(&m_cheatDevice.cheats); ++i) {
316		GBACheatSet* set = *GBACheatSetsGetPointer(&m_cheatDevice.cheats, i);
317		GBACheatSetDeinit(set);
318		delete set;
319	}
320	GBACheatSetsClear(&m_cheatDevice.cheats);
321
322	m_gameOpen = false;
323	emit gameStopped(&m_threadContext);
324}
325
326void GameController::crashGame(const QString& crashMessage) {
327	closeGame();
328	emit gameCrashed(crashMessage);
329}
330
331bool GameController::isPaused() {
332	if (!m_gameOpen) {
333		return false;
334	}
335	return GBAThreadIsPaused(&m_threadContext);
336}
337
338void GameController::setPaused(bool paused) {
339	if (!m_gameOpen || paused == GBAThreadIsPaused(&m_threadContext)) {
340		return;
341	}
342	if (paused) {
343		GBAThreadPause(&m_threadContext);
344		emit gamePaused(&m_threadContext);
345	} else {
346		GBAThreadUnpause(&m_threadContext);
347		emit gameUnpaused(&m_threadContext);
348	}
349}
350
351void GameController::reset() {
352	GBAThreadReset(&m_threadContext);
353}
354
355void GameController::threadInterrupt() {
356	if (m_gameOpen) {
357		GBAThreadInterrupt(&m_threadContext);
358	}
359}
360
361void GameController::threadContinue() {
362	if (m_gameOpen) {
363		GBAThreadContinue(&m_threadContext);
364	}
365}
366
367void GameController::frameAdvance() {
368	m_pauseMutex.lock();
369	m_pauseAfterFrame = true;
370	setPaused(false);
371	m_pauseMutex.unlock();
372}
373
374void GameController::setRewind(bool enable, int capacity, int interval) {
375	if (m_gameOpen) {
376		threadInterrupt();
377		GBARewindSettingsChanged(&m_threadContext, enable ? capacity : 0, enable ? interval : 0);
378		threadContinue();
379	} else {
380		if (enable) {
381			m_threadContext.rewindBufferInterval = interval;
382			m_threadContext.rewindBufferCapacity = capacity;
383		} else {
384			m_threadContext.rewindBufferInterval = 0;
385			m_threadContext.rewindBufferCapacity = 0;
386		}
387	}
388}
389
390void GameController::rewind(int states) {
391	threadInterrupt();
392	if (!states) {
393		GBARewindAll(&m_threadContext);
394	} else {
395		GBARewind(&m_threadContext, states);
396	}
397	threadContinue();
398}
399
400void GameController::keyPressed(int key) {
401	int mappedKey = 1 << key;
402	m_activeKeys |= mappedKey;
403	if (!m_inputController->allowOpposing()) {
404		if ((m_activeKeys & 0x30) == 0x30) {
405			m_inactiveKeys |= mappedKey ^ 0x30;
406			m_activeKeys ^= mappedKey ^ 0x30;
407		}
408		if ((m_activeKeys & 0xC0) == 0xC0) {
409			m_inactiveKeys |= mappedKey ^ 0xC0;
410			m_activeKeys ^= mappedKey ^ 0xC0;
411		}
412	}
413	updateKeys();
414}
415
416void GameController::keyReleased(int key) {
417	int mappedKey = 1 << key;
418	m_activeKeys &= ~mappedKey;
419	if (!m_inputController->allowOpposing()) {
420		if (mappedKey & 0x30) {
421			m_activeKeys |= m_inactiveKeys & (0x30 ^ mappedKey);
422			m_inactiveKeys &= ~0x30;
423		}
424		if (mappedKey & 0xC0) {
425			m_activeKeys |= m_inactiveKeys & (0xC0 ^ mappedKey);
426			m_inactiveKeys &= ~0xC0;
427		}
428	}
429	updateKeys();
430}
431
432void GameController::clearKeys() {
433	m_activeKeys = 0;
434	m_inactiveKeys = 0;
435	updateKeys();
436}
437
438void GameController::setAudioBufferSamples(int samples) {
439	threadInterrupt();
440	redoSamples(samples);
441	threadContinue();
442	QMetaObject::invokeMethod(m_audioProcessor, "setBufferSamples", Q_ARG(int, samples));
443}
444
445void GameController::setFPSTarget(float fps) {
446	threadInterrupt();
447	m_threadContext.fpsTarget = fps;
448	redoSamples(m_audioProcessor->getBufferSamples());
449	threadContinue();
450	QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
451}
452
453void GameController::setSkipBIOS(bool set) {
454	threadInterrupt();
455	m_threadContext.skipBios = set;
456	threadContinue();
457}
458
459void GameController::setUseBIOS(bool use) {
460	threadInterrupt();
461	m_useBios = use;
462	threadContinue();
463}
464
465void GameController::loadState(int slot) {
466	threadInterrupt();
467	GBALoadState(&m_threadContext, m_threadContext.stateDir, slot);
468	threadContinue();
469	emit stateLoaded(&m_threadContext);
470	emit frameAvailable(m_drawContext);
471}
472
473void GameController::saveState(int slot) {
474	threadInterrupt();
475	GBASaveState(&m_threadContext, m_threadContext.stateDir, slot, true);
476	threadContinue();
477}
478
479void GameController::setVideoSync(bool set) {
480	m_videoSync = set;
481	if (!m_turbo) {
482		threadInterrupt();
483		m_threadContext.sync.videoFrameWait = set;
484		threadContinue();
485	}
486}
487
488void GameController::setAudioSync(bool set) {
489	m_audioSync = set;
490	if (!m_turbo) {
491		threadInterrupt();
492		m_threadContext.sync.audioWait = set;
493		threadContinue();
494	}
495}
496
497void GameController::setFrameskip(int skip) {
498	m_threadContext.frameskip = skip;
499}
500
501void GameController::setVolume(int volume) {
502	threadInterrupt();
503	m_threadContext.volume = volume;
504	if (m_gameOpen) {
505		m_threadContext.gba->audio.masterVolume = volume;
506	}
507	threadContinue();
508}
509
510void GameController::setMute(bool mute) {
511	threadInterrupt();
512	m_threadContext.mute = mute;
513	if (m_gameOpen) {
514		m_threadContext.gba->audio.masterVolume = mute ? 0 : m_threadContext.volume;
515	}
516	threadContinue();
517}
518
519void GameController::setTurbo(bool set, bool forced) {
520	if (m_turboForced && !forced) {
521		return;
522	}
523	m_turbo = set;
524	m_turboForced = set && forced;
525	threadInterrupt();
526	m_threadContext.sync.audioWait = set ? false : m_audioSync;
527	m_threadContext.sync.videoFrameWait = set ? false : m_videoSync;
528	threadContinue();
529}
530
531void GameController::setAVStream(GBAAVStream* stream) {
532	threadInterrupt();
533	m_threadContext.stream = stream;
534	if (m_gameOpen) {
535		m_threadContext.gba->stream = stream;
536	}
537	threadContinue();
538}
539
540void GameController::clearAVStream() {
541	threadInterrupt();
542	m_threadContext.stream = nullptr;
543	if (m_gameOpen) {
544		m_threadContext.gba->stream = nullptr;
545	}
546	threadContinue();
547}
548
549#ifdef USE_PNG
550void GameController::screenshot() {
551	GBAThreadInterrupt(&m_threadContext);
552	GBAThreadTakeScreenshot(&m_threadContext);
553	GBAThreadContinue(&m_threadContext);
554}
555#endif
556
557void GameController::reloadAudioDriver() {
558	QMetaObject::invokeMethod(m_audioProcessor, "pause", Qt::BlockingQueuedConnection);
559	int samples = m_audioProcessor->getBufferSamples();
560	delete m_audioProcessor;
561	m_audioProcessor = AudioProcessor::create();
562	m_audioProcessor->setBufferSamples(samples);
563	m_audioProcessor->moveToThread(m_audioThread);
564	connect(this, SIGNAL(gameStarted(GBAThread*)), m_audioProcessor, SLOT(start()));
565	connect(this, SIGNAL(gameStopped(GBAThread*)), m_audioProcessor, SLOT(pause()));
566	connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
567	connect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));
568	if (isLoaded()) {
569		m_audioProcessor->setInput(&m_threadContext);
570		QMetaObject::invokeMethod(m_audioProcessor, "start");
571	}
572}
573
574void GameController::setLuminanceValue(uint8_t value) {
575	m_luxValue = value;
576	value = std::max<int>(value - 0x16, 0);
577	m_luxLevel = 10;
578	for (int i = 0; i < 10; ++i) {
579		if (value < LUX_LEVELS[i]) {
580			m_luxLevel = i;
581			break;
582		}
583	}
584	emit luminanceValueChanged(m_luxValue);
585}
586
587void GameController::setLuminanceLevel(int level) {
588	int value = 0x16;
589	level = std::max(0, std::min(10, level));
590	if (level > 0) {
591		value += LUX_LEVELS[level - 1];
592	}
593	setLuminanceValue(value);
594}
595
596void GameController::setRealTime() {
597	m_rtc.override = GameControllerRTC::NO_OVERRIDE;
598}
599
600void GameController::setFixedTime(const QDateTime& time) {
601	m_rtc.override = GameControllerRTC::FIXED;
602	m_rtc.value = time.toMSecsSinceEpoch() / 1000;
603}
604
605void GameController::setFakeEpoch(const QDateTime& time) {
606	m_rtc.override = GameControllerRTC::FAKE_EPOCH;
607	m_rtc.value = time.toMSecsSinceEpoch() / 1000;
608}
609
610void GameController::updateKeys() {
611	int activeKeys = m_activeKeys;
612#ifdef BUILD_SDL
613	activeKeys |= m_activeButtons;
614#endif
615	activeKeys &= ~m_inactiveKeys;
616	m_threadContext.activeKeys = activeKeys;
617}
618
619void GameController::redoSamples(int samples) {
620#if RESAMPLE_LIBRARY != RESAMPLE_BLIP_BUF
621	float sampleRate = 0x8000;
622	float ratio;
623	if (m_threadContext.gba) {
624		sampleRate = m_threadContext.gba->audio.sampleRate;
625	}
626	ratio = GBAAudioCalculateRatio(sampleRate, m_threadContext.fpsTarget, 44100);
627	m_threadContext.audioBuffers = ceil(samples / ratio);
628#else
629	m_threadContext.audioBuffers = samples;
630#endif
631	if (m_threadContext.gba) {
632		GBAAudioResizeBuffer(&m_threadContext.gba->audio, m_threadContext.audioBuffers);
633	}
634}
635
636void GameController::setLogLevel(int levels) {
637	threadInterrupt();
638	m_logLevels = levels;
639	threadContinue();
640}
641
642void GameController::enableLogLevel(int levels) {
643	threadInterrupt();
644	m_logLevels |= levels;
645	threadContinue();
646}
647
648void GameController::disableLogLevel(int levels) {
649	threadInterrupt();
650	m_logLevels &= ~levels;
651	threadContinue();
652}
653
654#ifdef BUILD_SDL
655void GameController::testSDLEvents() {
656	if (!m_inputController) {
657		return;
658	}
659
660	m_activeButtons = m_inputController->testSDLEvents();
661	updateKeys();
662}
663#endif