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 emit gameStopped(&m_threadContext);
370}
371
372bool GameController::isPaused() {
373 if (!m_gameOpen) {
374 return false;
375 }
376 return GBAThreadIsPaused(&m_threadContext);
377}
378
379void GameController::setPaused(bool paused) {
380 if (!m_gameOpen || paused == GBAThreadIsPaused(&m_threadContext)) {
381 return;
382 }
383 if (paused) {
384 GBAThreadPause(&m_threadContext);
385 emit gamePaused(&m_threadContext);
386 } else {
387 GBAThreadUnpause(&m_threadContext);
388 emit gameUnpaused(&m_threadContext);
389 }
390}
391
392void GameController::reset() {
393 GBAThreadReset(&m_threadContext);
394}
395
396void GameController::threadInterrupt() {
397 if (m_gameOpen) {
398 GBAThreadInterrupt(&m_threadContext);
399 }
400}
401
402void GameController::threadContinue() {
403 if (m_gameOpen) {
404 GBAThreadContinue(&m_threadContext);
405 }
406}
407
408void GameController::frameAdvance() {
409 m_pauseMutex.lock();
410 m_pauseAfterFrame = true;
411 setPaused(false);
412 m_pauseMutex.unlock();
413}
414
415void GameController::setRewind(bool enable, int capacity, int interval) {
416 if (m_gameOpen) {
417 threadInterrupt();
418 GBARewindSettingsChanged(&m_threadContext, enable ? capacity : 0, enable ? interval : 0);
419 threadContinue();
420 } else {
421 if (enable) {
422 m_threadContext.rewindBufferInterval = interval;
423 m_threadContext.rewindBufferCapacity = capacity;
424 } else {
425 m_threadContext.rewindBufferInterval = 0;
426 m_threadContext.rewindBufferCapacity = 0;
427 }
428 }
429}
430
431void GameController::rewind(int states) {
432 threadInterrupt();
433 if (!states) {
434 GBARewindAll(&m_threadContext);
435 } else {
436 GBARewind(&m_threadContext, states);
437 }
438 threadContinue();
439 emit rewound(&m_threadContext);
440 emit frameAvailable(m_drawContext);
441}
442
443void GameController::keyPressed(int key) {
444 int mappedKey = 1 << key;
445 m_activeKeys |= mappedKey;
446 if (!m_inputController->allowOpposing()) {
447 if ((m_activeKeys & 0x30) == 0x30) {
448 m_inactiveKeys |= mappedKey ^ 0x30;
449 m_activeKeys ^= mappedKey ^ 0x30;
450 }
451 if ((m_activeKeys & 0xC0) == 0xC0) {
452 m_inactiveKeys |= mappedKey ^ 0xC0;
453 m_activeKeys ^= mappedKey ^ 0xC0;
454 }
455 }
456 updateKeys();
457}
458
459void GameController::keyReleased(int key) {
460 int mappedKey = 1 << key;
461 m_activeKeys &= ~mappedKey;
462 if (!m_inputController->allowOpposing()) {
463 if (mappedKey & 0x30) {
464 m_activeKeys |= m_inactiveKeys & (0x30 ^ mappedKey);
465 m_inactiveKeys &= ~0x30;
466 }
467 if (mappedKey & 0xC0) {
468 m_activeKeys |= m_inactiveKeys & (0xC0 ^ mappedKey);
469 m_inactiveKeys &= ~0xC0;
470 }
471 }
472 updateKeys();
473}
474
475void GameController::clearKeys() {
476 m_activeKeys = 0;
477 m_inactiveKeys = 0;
478 updateKeys();
479}
480
481void GameController::setAudioBufferSamples(int samples) {
482 threadInterrupt();
483 redoSamples(samples);
484 threadContinue();
485 QMetaObject::invokeMethod(m_audioProcessor, "setBufferSamples", Q_ARG(int, samples));
486}
487
488void GameController::setFPSTarget(float fps) {
489 threadInterrupt();
490 m_threadContext.fpsTarget = fps;
491 redoSamples(m_audioProcessor->getBufferSamples());
492 threadContinue();
493 QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
494}
495
496void GameController::setSkipBIOS(bool set) {
497 threadInterrupt();
498 m_threadContext.skipBios = set;
499 threadContinue();
500}
501
502void GameController::setUseBIOS(bool use) {
503 threadInterrupt();
504 m_useBios = use;
505 threadContinue();
506}
507
508void GameController::loadState(int slot) {
509 if (slot > 0) {
510 m_stateSlot = slot;
511 }
512 GBARunOnThread(&m_threadContext, [](GBAThread* context) {
513 GameController* controller = static_cast<GameController*>(context->userData);
514 GBALoadState(context, context->stateDir, controller->m_stateSlot);
515 controller->stateLoaded(context);
516 controller->frameAvailable(controller->m_drawContext);
517 });
518}
519
520void GameController::saveState(int slot) {
521 if (slot > 0) {
522 m_stateSlot = slot;
523 }
524 GBARunOnThread(&m_threadContext, [](GBAThread* context) {
525 GameController* controller = static_cast<GameController*>(context->userData);
526 GBASaveState(context, context->stateDir, controller->m_stateSlot, true);
527 });
528}
529
530void GameController::setVideoSync(bool set) {
531 m_videoSync = set;
532 if (!m_turbo) {
533 threadInterrupt();
534 m_threadContext.sync.videoFrameWait = set;
535 threadContinue();
536 }
537}
538
539void GameController::setAudioSync(bool set) {
540 m_audioSync = set;
541 if (!m_turbo) {
542 threadInterrupt();
543 m_threadContext.sync.audioWait = set;
544 threadContinue();
545 }
546}
547
548void GameController::setFrameskip(int skip) {
549 m_threadContext.frameskip = skip;
550}
551
552void GameController::setVolume(int volume) {
553 threadInterrupt();
554 m_threadContext.volume = volume;
555 if (m_gameOpen) {
556 m_threadContext.gba->audio.masterVolume = volume;
557 }
558 threadContinue();
559}
560
561void GameController::setMute(bool mute) {
562 threadInterrupt();
563 m_threadContext.mute = mute;
564 if (m_gameOpen) {
565 m_threadContext.gba->audio.masterVolume = mute ? 0 : m_threadContext.volume;
566 }
567 threadContinue();
568}
569
570void GameController::setTurbo(bool set, bool forced) {
571 if (m_turboForced && !forced) {
572 return;
573 }
574 if (m_turbo == set && m_turboForced == forced) {
575 // Don't interrupt the thread if we don't need to
576 return;
577 }
578 m_turbo = set;
579 m_turboForced = set && forced;
580 threadInterrupt();
581 m_threadContext.sync.audioWait = set ? false : m_audioSync;
582 m_threadContext.sync.videoFrameWait = set ? false : m_videoSync;
583 threadContinue();
584}
585
586void GameController::setAVStream(GBAAVStream* stream) {
587 threadInterrupt();
588 m_threadContext.stream = stream;
589 if (m_gameOpen) {
590 m_threadContext.gba->stream = stream;
591 }
592 threadContinue();
593}
594
595void GameController::clearAVStream() {
596 threadInterrupt();
597 m_threadContext.stream = nullptr;
598 if (m_gameOpen) {
599 m_threadContext.gba->stream = nullptr;
600 }
601 threadContinue();
602}
603
604#ifdef USE_PNG
605void GameController::screenshot() {
606 GBARunOnThread(&m_threadContext, GBAThreadTakeScreenshot);
607}
608#endif
609
610void GameController::reloadAudioDriver() {
611 QMetaObject::invokeMethod(m_audioProcessor, "pause", Qt::BlockingQueuedConnection);
612 int samples = m_audioProcessor->getBufferSamples();
613 delete m_audioProcessor;
614 m_audioProcessor = AudioProcessor::create();
615 m_audioProcessor->setBufferSamples(samples);
616 m_audioProcessor->moveToThread(m_audioThread);
617 connect(this, SIGNAL(gameStarted(GBAThread*)), m_audioProcessor, SLOT(start()));
618 connect(this, SIGNAL(gameStopped(GBAThread*)), m_audioProcessor, SLOT(pause()));
619 connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
620 connect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));
621 if (isLoaded()) {
622 m_audioProcessor->setInput(&m_threadContext);
623 QMetaObject::invokeMethod(m_audioProcessor, "start");
624 }
625}
626
627void GameController::setLuminanceValue(uint8_t value) {
628 m_luxValue = value;
629 value = std::max<int>(value - 0x16, 0);
630 m_luxLevel = 10;
631 for (int i = 0; i < 10; ++i) {
632 if (value < LUX_LEVELS[i]) {
633 m_luxLevel = i;
634 break;
635 }
636 }
637 emit luminanceValueChanged(m_luxValue);
638}
639
640void GameController::setLuminanceLevel(int level) {
641 int value = 0x16;
642 level = std::max(0, std::min(10, level));
643 if (level > 0) {
644 value += LUX_LEVELS[level - 1];
645 }
646 setLuminanceValue(value);
647}
648
649void GameController::setRealTime() {
650 m_rtc.override = GameControllerRTC::NO_OVERRIDE;
651}
652
653void GameController::setFixedTime(const QDateTime& time) {
654 m_rtc.override = GameControllerRTC::FIXED;
655 m_rtc.value = time.toMSecsSinceEpoch() / 1000;
656}
657
658void GameController::setFakeEpoch(const QDateTime& time) {
659 m_rtc.override = GameControllerRTC::FAKE_EPOCH;
660 m_rtc.value = time.toMSecsSinceEpoch() / 1000;
661}
662
663void GameController::updateKeys() {
664 int activeKeys = m_activeKeys;
665 activeKeys |= m_activeButtons;
666 activeKeys &= ~m_inactiveKeys;
667 m_threadContext.activeKeys = activeKeys;
668}
669
670void GameController::redoSamples(int samples) {
671#if RESAMPLE_LIBRARY != RESAMPLE_BLIP_BUF
672 float sampleRate = 0x8000;
673 float ratio;
674 if (m_threadContext.gba) {
675 sampleRate = m_threadContext.gba->audio.sampleRate;
676 }
677 ratio = GBAAudioCalculateRatio(sampleRate, m_threadContext.fpsTarget, 44100);
678 m_threadContext.audioBuffers = ceil(samples / ratio);
679#else
680 m_threadContext.audioBuffers = samples;
681#endif
682 if (m_threadContext.gba) {
683 GBAAudioResizeBuffer(&m_threadContext.gba->audio, m_threadContext.audioBuffers);
684 }
685}
686
687void GameController::setLogLevel(int levels) {
688 threadInterrupt();
689 m_logLevels = levels;
690 threadContinue();
691}
692
693void GameController::enableLogLevel(int levels) {
694 threadInterrupt();
695 m_logLevels |= levels;
696 threadContinue();
697}
698
699void GameController::disableLogLevel(int levels) {
700 threadInterrupt();
701 m_logLevels &= ~levels;
702 threadContinue();
703}
704
705void GameController::pollEvents() {
706 if (!m_inputController) {
707 return;
708 }
709
710 m_activeButtons = m_inputController->pollEvents();
711 updateKeys();
712}