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