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