all repos — mgba @ b55c873e3401b255cba436e6e85eea59f3d5293c

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		GameController* controller = static_cast<GameController*>(context->userData);
122		if (level == GBA_LOG_FATAL) {
123			QMetaObject::invokeMethod(controller, "crashGame", Q_ARG(const QString&, QString().vsprintf(format, args)));
124		} else if (!(controller->m_logLevels & level)) {
125			return;
126		}
127		controller->postLog(level, QString().vsprintf(format, args));
128	};
129
130	m_audioThread->start(QThread::TimeCriticalPriority);
131	m_audioProcessor->moveToThread(m_audioThread);
132	connect(this, SIGNAL(gameStarted(GBAThread*)), m_audioProcessor, SLOT(start()));
133	connect(this, SIGNAL(gameStopped(GBAThread*)), m_audioProcessor, SLOT(pause()));
134	connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
135	connect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));
136
137#ifdef BUILD_SDL
138	connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(testSDLEvents()));
139#endif
140}
141
142GameController::~GameController() {
143	m_audioThread->quit();
144	m_audioThread->wait();
145	disconnect();
146	clearMultiplayerController();
147	closeGame();
148	GBACheatDeviceDestroy(&m_cheatDevice);
149	delete m_renderer;
150	delete[] m_drawContext;
151}
152
153void GameController::setMultiplayerController(std::shared_ptr<MultiplayerController> controller) {
154	if (controller == m_multiplayer) {
155		return;
156	}
157	clearMultiplayerController();
158	m_multiplayer = controller;
159	controller->attachGame(this);
160}
161
162void GameController::clearMultiplayerController() {
163	if (!m_multiplayer) {
164		return;
165	}
166	m_multiplayer->detachGame(this);
167	m_multiplayer.reset();
168}
169
170void GameController::setOverride(const GBACartridgeOverride& override) {
171	m_threadContext.override = override;
172	m_threadContext.hasOverride = true;
173}
174
175void GameController::setOptions(const GBAOptions* opts) {
176	setFrameskip(opts->frameskip);
177	setAudioSync(opts->audioSync);
178	setVideoSync(opts->videoSync);
179	setSkipBIOS(opts->skipBios);
180	setUseBIOS(opts->useBios);
181	setRewind(opts->rewindEnable, opts->rewindBufferCapacity, opts->rewindBufferInterval);
182
183	threadInterrupt();
184	m_threadContext.idleOptimization = opts->idleOptimization;
185	threadContinue();
186}
187
188#ifdef USE_GDB_STUB
189ARMDebugger* GameController::debugger() {
190	return m_threadContext.debugger;
191}
192
193void GameController::setDebugger(ARMDebugger* debugger) {
194	threadInterrupt();
195	if (m_threadContext.debugger && GBAThreadIsActive(&m_threadContext)) {
196		GBADetachDebugger(m_threadContext.gba);
197	}
198	m_threadContext.debugger = debugger;
199	if (m_threadContext.debugger && GBAThreadIsActive(&m_threadContext)) {
200		GBAAttachDebugger(m_threadContext.gba, m_threadContext.debugger);
201	}
202	threadContinue();
203}
204#endif
205
206void GameController::loadGame(const QString& path, bool dirmode) {
207	closeGame();
208	if (!dirmode) {
209		QFile file(path);
210		if (!file.open(QIODevice::ReadOnly)) {
211			return;
212		}
213		file.close();
214	}
215
216	m_fname = path;
217	m_dirmode = dirmode;
218	openGame();
219}
220
221void GameController::openGame() {
222	m_gameOpen = true;
223
224	m_pauseAfterFrame = false;
225
226	if (m_turbo) {
227		m_threadContext.sync.videoFrameWait = false;
228		m_threadContext.sync.audioWait = false;
229	} else {
230		m_threadContext.sync.videoFrameWait = m_videoSync;
231		m_threadContext.sync.audioWait = m_audioSync;
232	}
233
234	m_threadContext.gameDir = 0;
235	m_threadContext.fname = strdup(m_fname.toLocal8Bit().constData());
236	if (m_dirmode) {
237		m_threadContext.gameDir = VDirOpen(m_threadContext.fname);
238		m_threadContext.stateDir = m_threadContext.gameDir;
239	} else {
240		m_threadContext.rom = VFileOpen(m_threadContext.fname, O_RDONLY);
241#if USE_LIBZIP
242		if (!m_threadContext.gameDir) {
243			m_threadContext.gameDir = VDirOpenZip(m_threadContext.fname, 0);
244		}
245#endif
246#if USE_LZMA
247		if (!m_threadContext.gameDir) {
248			m_threadContext.gameDir = VDirOpen7z(m_threadContext.fname, 0);
249		}
250#endif
251	}
252
253	if (!m_bios.isNull() &&m_useBios) {
254		m_threadContext.bios = VFileOpen(m_bios.toLocal8Bit().constData(), O_RDONLY);
255	} else {
256		m_threadContext.bios = nullptr;
257	}
258
259	if (!m_patch.isNull()) {
260		m_threadContext.patch = VFileOpen(m_patch.toLocal8Bit().constData(), O_RDONLY);
261	}
262
263	if (!GBAThreadStart(&m_threadContext)) {
264		m_gameOpen = false;
265		emit gameFailed();
266	}
267}
268
269void GameController::loadBIOS(const QString& path) {
270	if (m_bios == path) {
271		return;
272	}
273	m_bios = path;
274	if (m_gameOpen) {
275		closeGame();
276		openGame();
277	}
278}
279
280void GameController::loadPatch(const QString& path) {
281	if (m_gameOpen) {
282		closeGame();
283		m_patch = path;
284		openGame();
285	} else {
286		m_patch = path;
287	}
288}
289
290void GameController::closeGame() {
291	if (!m_gameOpen) {
292		return;
293	}
294	if (GBAThreadIsPaused(&m_threadContext)) {
295		GBAThreadUnpause(&m_threadContext);
296	}
297	GBAThreadEnd(&m_threadContext);
298	GBAThreadJoin(&m_threadContext);
299	if (m_threadContext.fname) {
300		free(const_cast<char*>(m_threadContext.fname));
301		m_threadContext.fname = nullptr;
302	}
303
304	m_patch = QString();
305
306	for (size_t i = 0; i < GBACheatSetsSize(&m_cheatDevice.cheats); ++i) {
307		GBACheatSet* set = *GBACheatSetsGetPointer(&m_cheatDevice.cheats, i);
308		GBACheatSetDeinit(set);
309		delete set;
310	}
311	GBACheatSetsClear(&m_cheatDevice.cheats);
312
313	m_gameOpen = false;
314	emit gameStopped(&m_threadContext);
315}
316
317void GameController::crashGame(const QString& crashMessage) {
318	closeGame();
319	emit gameCrashed(crashMessage);
320}
321
322bool GameController::isPaused() {
323	if (!m_gameOpen) {
324		return false;
325	}
326	return GBAThreadIsPaused(&m_threadContext);
327}
328
329void GameController::setPaused(bool paused) {
330	if (paused == GBAThreadIsPaused(&m_threadContext)) {
331		return;
332	}
333	if (paused) {
334		GBAThreadPause(&m_threadContext);
335		emit gamePaused(&m_threadContext);
336	} else {
337		GBAThreadUnpause(&m_threadContext);
338		emit gameUnpaused(&m_threadContext);
339	}
340}
341
342void GameController::reset() {
343	GBAThreadReset(&m_threadContext);
344}
345
346void GameController::threadInterrupt() {
347	if (m_gameOpen) {
348		GBAThreadInterrupt(&m_threadContext);
349	}
350}
351
352void GameController::threadContinue() {
353	if (m_gameOpen) {
354		GBAThreadContinue(&m_threadContext);
355	}
356}
357
358void GameController::frameAdvance() {
359	m_pauseMutex.lock();
360	m_pauseAfterFrame = true;
361	setPaused(false);
362	m_pauseMutex.unlock();
363}
364
365void GameController::setRewind(bool enable, int capacity, int interval) {
366	if (m_gameOpen) {
367		threadInterrupt();
368		GBARewindSettingsChanged(&m_threadContext, enable ? capacity : 0, enable ? interval : 0);
369		threadContinue();
370	} else {
371		if (enable) {
372			m_threadContext.rewindBufferInterval = interval;
373			m_threadContext.rewindBufferCapacity = capacity;
374		} else {
375			m_threadContext.rewindBufferInterval = 0;
376			m_threadContext.rewindBufferCapacity = 0;
377		}
378	}
379}
380
381void GameController::rewind(int states) {
382	threadInterrupt();
383	if (!states) {
384		GBARewindAll(&m_threadContext);
385	} else {
386		GBARewind(&m_threadContext, states);
387	}
388	threadContinue();
389}
390
391void GameController::keyPressed(int key) {
392	int mappedKey = 1 << key;
393	m_activeKeys |= mappedKey;
394	if (!m_inputController->allowOpposing()) {
395		if ((m_activeKeys & 0x30) == 0x30) {
396			m_inactiveKeys |= mappedKey ^ 0x30;
397			m_activeKeys ^= mappedKey ^ 0x30;
398		}
399		if ((m_activeKeys & 0xC0) == 0xC0) {
400			m_inactiveKeys |= mappedKey ^ 0xC0;
401			m_activeKeys ^= mappedKey ^ 0xC0;
402		}
403	}
404	updateKeys();
405}
406
407void GameController::keyReleased(int key) {
408	int mappedKey = 1 << key;
409	m_activeKeys &= ~mappedKey;
410	if (!m_inputController->allowOpposing()) {
411		if (mappedKey & 0x30) {
412			m_activeKeys |= m_inactiveKeys & (0x30 ^ mappedKey);
413			m_inactiveKeys &= ~0x30;
414		}
415		if (mappedKey & 0xC0) {
416			m_activeKeys |= m_inactiveKeys & (0xC0 ^ mappedKey);
417			m_inactiveKeys &= ~0xC0;
418		}
419	}
420	updateKeys();
421}
422
423void GameController::clearKeys() {
424	m_activeKeys = 0;
425	m_inactiveKeys = 0;
426	updateKeys();
427}
428
429void GameController::setAudioBufferSamples(int samples) {
430	threadInterrupt();
431	redoSamples(samples);
432	threadContinue();
433	QMetaObject::invokeMethod(m_audioProcessor, "setBufferSamples", Q_ARG(int, samples));
434}
435
436void GameController::setFPSTarget(float fps) {
437	threadInterrupt();
438	m_threadContext.fpsTarget = fps;
439	redoSamples(m_audioProcessor->getBufferSamples());
440	threadContinue();
441	QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
442}
443
444void GameController::setSkipBIOS(bool set) {
445	threadInterrupt();
446	m_threadContext.skipBios = set;
447	threadContinue();
448}
449
450void GameController::setUseBIOS(bool use) {
451	threadInterrupt();
452	m_useBios = use;
453	threadContinue();
454}
455
456void GameController::loadState(int slot) {
457	threadInterrupt();
458	GBALoadState(&m_threadContext, m_threadContext.stateDir, slot);
459	threadContinue();
460	emit stateLoaded(&m_threadContext);
461	emit frameAvailable(m_drawContext);
462}
463
464void GameController::saveState(int slot) {
465	threadInterrupt();
466	GBASaveState(&m_threadContext, m_threadContext.stateDir, slot, true);
467	threadContinue();
468}
469
470void GameController::setVideoSync(bool set) {
471	m_videoSync = set;
472	if (!m_turbo) {
473		threadInterrupt();
474		m_threadContext.sync.videoFrameWait = set;
475		threadContinue();
476	}
477}
478
479void GameController::setAudioSync(bool set) {
480	m_audioSync = set;
481	if (!m_turbo) {
482		threadInterrupt();
483		m_threadContext.sync.audioWait = set;
484		threadContinue();
485	}
486}
487
488void GameController::setFrameskip(int skip) {
489	m_threadContext.frameskip = skip;
490}
491
492void GameController::setTurbo(bool set, bool forced) {
493	if (m_turboForced && !forced) {
494		return;
495	}
496	m_turbo = set;
497	m_turboForced = set && forced;
498	threadInterrupt();
499	m_threadContext.sync.audioWait = set ? false : m_audioSync;
500	m_threadContext.sync.videoFrameWait = set ? false : m_videoSync;
501	threadContinue();
502}
503
504void GameController::setAVStream(GBAAVStream* stream) {
505	threadInterrupt();
506	m_threadContext.stream = stream;
507	threadContinue();
508}
509
510void GameController::clearAVStream() {
511	threadInterrupt();
512	m_threadContext.stream = nullptr;
513	threadContinue();
514}
515
516void GameController::reloadAudioDriver() {
517	QMetaObject::invokeMethod(m_audioProcessor, "pause", Qt::BlockingQueuedConnection);
518	int samples = m_audioProcessor->getBufferSamples();
519	delete m_audioProcessor;
520	m_audioProcessor = AudioProcessor::create();
521	m_audioProcessor->setBufferSamples(samples);
522	m_audioProcessor->moveToThread(m_audioThread);
523	connect(this, SIGNAL(gameStarted(GBAThread*)), m_audioProcessor, SLOT(start()));
524	connect(this, SIGNAL(gameStopped(GBAThread*)), m_audioProcessor, SLOT(pause()));
525	connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
526	connect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));
527	if (isLoaded()) {
528		m_audioProcessor->setInput(&m_threadContext);
529		QMetaObject::invokeMethod(m_audioProcessor, "start");
530	}
531}
532
533void GameController::setLuminanceValue(uint8_t value) {
534	m_luxValue = value;
535	value = std::max<int>(value - 0x16, 0);
536	m_luxLevel = 10;
537	for (int i = 0; i < 10; ++i) {
538		if (value < LUX_LEVELS[i]) {
539			m_luxLevel = i;
540			break;
541		}
542	}
543	emit luminanceValueChanged(m_luxValue);
544}
545
546void GameController::setLuminanceLevel(int level) {
547	int value = 0x16;
548	level = std::max(0, std::min(10, level));
549	if (level > 0) {
550		value += LUX_LEVELS[level - 1];
551	}
552	setLuminanceValue(value);
553}
554
555void GameController::setRealTime() {
556	m_rtc.override = GameControllerRTC::NO_OVERRIDE;
557}
558
559void GameController::setFixedTime(const QDateTime& time) {
560	m_rtc.override = GameControllerRTC::FIXED;
561	m_rtc.value = time.toMSecsSinceEpoch() / 1000;
562}
563
564void GameController::setFakeEpoch(const QDateTime& time) {
565	m_rtc.override = GameControllerRTC::FAKE_EPOCH;
566	m_rtc.value = time.toMSecsSinceEpoch() / 1000;
567}
568
569void GameController::updateKeys() {
570	int activeKeys = m_activeKeys;
571#ifdef BUILD_SDL
572	activeKeys |= m_activeButtons;
573#endif
574	activeKeys &= ~m_inactiveKeys;
575	m_threadContext.activeKeys = activeKeys;
576}
577
578void GameController::redoSamples(int samples) {
579#if RESAMPLE_LIBRARY != RESAMPLE_BLIP_BUF
580	float sampleRate = 0x8000;
581	float ratio;
582	if (m_threadContext.gba) {
583		sampleRate = m_threadContext.gba->audio.sampleRate;
584	}
585	ratio = GBAAudioCalculateRatio(sampleRate, m_threadContext.fpsTarget, 44100);
586	m_threadContext.audioBuffers = ceil(samples / ratio);
587#else
588	m_threadContext.audioBuffers = samples;
589#endif
590	if (m_threadContext.gba) {
591		GBAAudioResizeBuffer(&m_threadContext.gba->audio, m_threadContext.audioBuffers);
592	}
593}
594
595void GameController::setLogLevel(int levels) {
596	threadInterrupt();
597	m_logLevels = levels;
598	threadContinue();
599}
600
601void GameController::enableLogLevel(int levels) {
602	threadInterrupt();
603	m_logLevels |= levels;
604	threadContinue();
605}
606
607void GameController::disableLogLevel(int levels) {
608	threadInterrupt();
609	m_logLevels &= ~levels;
610	threadContinue();
611}
612
613#ifdef BUILD_SDL
614void GameController::testSDLEvents() {
615	if (!m_inputController) {
616		return;
617	}
618
619	m_activeButtons = m_inputController->testSDLEvents();
620	updateKeys();
621}
622#endif