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