all repos — mgba @ 592f6614aaa513e94905cafd74695397146bfaa9

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