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.h"
18#include "gba-audio.h"
19#include "gba-serialize.h"
20#include "renderers/video-software.h"
21#include "util/vfs.h"
22}
23
24using namespace QGBA;
25using namespace std;
26
27GameController::GameController(QObject* parent)
28 : QObject(parent)
29 , m_drawContext(new uint32_t[256 * 256])
30 , m_threadContext()
31 , m_activeKeys(0)
32 , m_logLevels(0)
33 , m_gameOpen(false)
34 , m_audioThread(new QThread(this))
35 , m_audioProcessor(AudioProcessor::create())
36 , m_videoSync(VIDEO_SYNC)
37 , m_audioSync(AUDIO_SYNC)
38 , m_turbo(false)
39 , m_turboForced(false)
40 , m_inputController(nullptr)
41{
42 m_renderer = new GBAVideoSoftwareRenderer;
43 GBAVideoSoftwareRendererCreate(m_renderer);
44 m_renderer->outputBuffer = (color_t*) m_drawContext;
45 m_renderer->outputBufferStride = 256;
46 m_threadContext.state = THREAD_INITIALIZED;
47 m_threadContext.debugger = 0;
48 m_threadContext.frameskip = 0;
49 m_threadContext.bios = 0;
50 m_threadContext.renderer = &m_renderer->d;
51 m_threadContext.userData = this;
52 m_threadContext.rewindBufferCapacity = 0;
53 m_threadContext.logLevel = -1;
54
55 m_lux.p = this;
56 m_lux.sample = [] (GBALuminanceSource* context) {
57 GameControllerLux* lux = static_cast<GameControllerLux*>(context);
58 lux->value = 0xFF - lux->p->m_luxValue;
59 };
60
61 m_lux.readLuminance = [] (GBALuminanceSource* context) {
62 GameControllerLux* lux = static_cast<GameControllerLux*>(context);
63 return lux->value;
64 };
65
66 m_rtc.p = this;
67 m_rtc.override = GameControllerRTC::NO_OVERRIDE;
68 m_rtc.sample = [] (GBARTCSource* context) { };
69 m_rtc.unixTime = [] (GBARTCSource* context) -> time_t {
70 GameControllerRTC* rtc = static_cast<GameControllerRTC*>(context);
71 switch (rtc->override) {
72 case GameControllerRTC::NO_OVERRIDE:
73 default:
74 return time(nullptr);
75 case GameControllerRTC::FIXED:
76 return rtc->value;
77 case GameControllerRTC::FAKE_EPOCH:
78 return rtc->value + rtc->p->m_threadContext.gba->video.frameCounter * VIDEO_TOTAL_LENGTH / GBA_ARM7TDMI_FREQUENCY;
79 }
80 };
81
82 m_threadContext.startCallback = [] (GBAThread* context) {
83 GameController* controller = static_cast<GameController*>(context->userData);
84 controller->m_audioProcessor->setInput(context);
85 // Override the GBA object's log level to prevent stdout spew
86 context->gba->logLevel = GBA_LOG_FATAL;
87 context->gba->luminanceSource = &controller->m_lux;
88 context->gba->rtcSource = &controller->m_rtc;
89 controller->gameStarted(context);
90 };
91
92 m_threadContext.cleanCallback = [] (GBAThread* context) {
93 GameController* controller = static_cast<GameController*>(context->userData);
94 controller->gameStopped(context);
95 };
96
97 m_threadContext.frameCallback = [] (GBAThread* context) {
98 GameController* controller = static_cast<GameController*>(context->userData);
99 controller->m_pauseMutex.lock();
100 if (controller->m_pauseAfterFrame) {
101 GBAThreadPauseFromThread(context);
102 controller->m_pauseAfterFrame = false;
103 controller->gamePaused(&controller->m_threadContext);
104 }
105 controller->m_pauseMutex.unlock();
106 controller->frameAvailable(controller->m_drawContext);
107 };
108
109 m_threadContext.logHandler = [] (GBAThread* context, enum GBALogLevel level, const char* format, va_list args) {
110 GameController* controller = static_cast<GameController*>(context->userData);
111 if (level == GBA_LOG_FATAL) {
112 MutexLock(&controller->m_threadContext.stateMutex);
113 controller->m_threadContext.state = THREAD_EXITING;
114 MutexUnlock(&controller->m_threadContext.stateMutex);
115 QMetaObject::invokeMethod(controller, "crashGame", Q_ARG(const QString&, QString().vsprintf(format, args)));
116 } else if (!(controller->m_logLevels & level)) {
117 return;
118 }
119 controller->postLog(level, QString().vsprintf(format, args));
120 };
121
122 m_audioThread->start(QThread::TimeCriticalPriority);
123 m_audioProcessor->moveToThread(m_audioThread);
124 connect(this, SIGNAL(gameStarted(GBAThread*)), m_audioProcessor, SLOT(start()));
125 connect(this, SIGNAL(gameStopped(GBAThread*)), m_audioProcessor, SLOT(pause()));
126 connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
127 connect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));
128
129#ifdef BUILD_SDL
130 connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(testSDLEvents()));
131#endif
132}
133
134GameController::~GameController() {
135 m_audioThread->quit();
136 m_audioThread->wait();
137 disconnect();
138 closeGame();
139 delete m_renderer;
140 delete[] m_drawContext;
141}
142
143#ifdef USE_GDB_STUB
144ARMDebugger* GameController::debugger() {
145 return m_threadContext.debugger;
146}
147
148void GameController::setDebugger(ARMDebugger* debugger) {
149 bool wasPaused = isPaused();
150 setPaused(true);
151 if (m_threadContext.debugger && GBAThreadHasStarted(&m_threadContext)) {
152 GBADetachDebugger(m_threadContext.gba);
153 }
154 m_threadContext.debugger = debugger;
155 if (m_threadContext.debugger && GBAThreadHasStarted(&m_threadContext)) {
156 GBAAttachDebugger(m_threadContext.gba, m_threadContext.debugger);
157 }
158 setPaused(wasPaused);
159}
160#endif
161
162void GameController::loadGame(const QString& path, bool dirmode) {
163 closeGame();
164 if (!dirmode) {
165 QFile file(path);
166 if (!file.open(QIODevice::ReadOnly)) {
167 return;
168 }
169 file.close();
170 }
171
172 m_fname = path;
173 m_dirmode = dirmode;
174 openGame();
175}
176
177void GameController::openGame() {
178 m_gameOpen = true;
179
180 m_pauseAfterFrame = false;
181
182 if (m_turbo) {
183 m_threadContext.sync.videoFrameWait = false;
184 m_threadContext.sync.audioWait = false;
185 } else {
186 m_threadContext.sync.videoFrameWait = m_videoSync;
187 m_threadContext.sync.audioWait = m_audioSync;
188 }
189
190 m_threadContext.fname = strdup(m_fname.toLocal8Bit().constData());
191 if (m_dirmode) {
192 m_threadContext.gameDir = VDirOpen(m_threadContext.fname);
193 m_threadContext.stateDir = m_threadContext.gameDir;
194 } else {
195 m_threadContext.rom = VFileOpen(m_threadContext.fname, O_RDONLY);
196#if ENABLE_LIBZIP
197 m_threadContext.gameDir = VDirOpenZip(m_threadContext.fname, 0);
198#endif
199 }
200
201 if (!m_bios.isNull()) {
202 m_threadContext.bios = VFileOpen(m_bios.toLocal8Bit().constData(), O_RDONLY);
203 }
204
205 if (!m_patch.isNull()) {
206 m_threadContext.patch = VFileOpen(m_patch.toLocal8Bit().constData(), O_RDONLY);
207 }
208
209 if (!GBAThreadStart(&m_threadContext)) {
210 m_gameOpen = false;
211 }
212}
213
214void GameController::loadBIOS(const QString& path) {
215 if (m_bios == path) {
216 return;
217 }
218 m_bios = path;
219 if (m_gameOpen) {
220 closeGame();
221 openGame();
222 }
223}
224
225void GameController::loadPatch(const QString& path) {
226 m_patch = path;
227 if (m_gameOpen) {
228 closeGame();
229 openGame();
230 }
231}
232
233void GameController::closeGame() {
234 if (!m_gameOpen) {
235 return;
236 }
237 if (GBAThreadIsPaused(&m_threadContext)) {
238 GBAThreadUnpause(&m_threadContext);
239 }
240 GBAThreadEnd(&m_threadContext);
241 GBAThreadJoin(&m_threadContext);
242 if (m_threadContext.fname) {
243 free(const_cast<char*>(m_threadContext.fname));
244 m_threadContext.fname = nullptr;
245 }
246
247 m_patch = QString();
248
249 m_gameOpen = false;
250 emit gameStopped(&m_threadContext);
251}
252
253void GameController::crashGame(const QString& crashMessage) {
254 closeGame();
255 emit gameCrashed(crashMessage);
256}
257
258bool GameController::isPaused() {
259 if (!m_gameOpen) {
260 return false;
261 }
262 return GBAThreadIsPaused(&m_threadContext);
263}
264
265void GameController::setPaused(bool paused) {
266 if (paused == GBAThreadIsPaused(&m_threadContext)) {
267 return;
268 }
269 if (paused) {
270 GBAThreadPause(&m_threadContext);
271 emit gamePaused(&m_threadContext);
272 } else {
273 GBAThreadUnpause(&m_threadContext);
274 emit gameUnpaused(&m_threadContext);
275 }
276}
277
278void GameController::reset() {
279 GBAThreadReset(&m_threadContext);
280}
281
282void GameController::threadInterrupt() {
283 if (m_gameOpen) {
284 GBAThreadInterrupt(&m_threadContext);
285 }
286}
287
288void GameController::threadContinue() {
289 if (m_gameOpen) {
290 GBAThreadContinue(&m_threadContext);
291 }
292}
293
294void GameController::frameAdvance() {
295 m_pauseMutex.lock();
296 m_pauseAfterFrame = true;
297 setPaused(false);
298 m_pauseMutex.unlock();
299}
300
301void GameController::keyPressed(int key) {
302 int mappedKey = 1 << key;
303 m_activeKeys |= mappedKey;
304 updateKeys();
305}
306
307void GameController::keyReleased(int key) {
308 int mappedKey = 1 << key;
309 m_activeKeys &= ~mappedKey;
310 updateKeys();
311}
312
313void GameController::setAudioBufferSamples(int samples) {
314 threadInterrupt();
315 redoSamples(samples);
316 threadContinue();
317 QMetaObject::invokeMethod(m_audioProcessor, "setBufferSamples", Q_ARG(int, samples));
318}
319
320void GameController::setFPSTarget(float fps) {
321 threadInterrupt();
322 m_threadContext.fpsTarget = fps;
323 redoSamples(m_audioProcessor->getBufferSamples());
324 threadContinue();
325 QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
326}
327
328void GameController::setSkipBIOS(bool set) {
329 threadInterrupt();
330 m_threadContext.skipBios = set;
331 threadContinue();
332}
333
334void GameController::loadState(int slot) {
335 threadInterrupt();
336 GBALoadState(m_threadContext.gba, m_threadContext.stateDir, slot);
337 threadContinue();
338 emit stateLoaded(&m_threadContext);
339 emit frameAvailable(m_drawContext);
340}
341
342void GameController::saveState(int slot) {
343 threadInterrupt();
344 GBASaveState(m_threadContext.gba, m_threadContext.stateDir, slot, true);
345 threadContinue();
346}
347
348void GameController::setVideoSync(bool set) {
349 m_videoSync = set;
350 if (!m_turbo) {
351 threadInterrupt();
352 m_threadContext.sync.videoFrameWait = set;
353 threadContinue();
354 }
355}
356
357void GameController::setAudioSync(bool set) {
358 m_audioSync = set;
359 if (!m_turbo) {
360 threadInterrupt();
361 m_threadContext.sync.audioWait = set;
362 threadContinue();
363 }
364}
365
366void GameController::setFrameskip(int skip) {
367 m_threadContext.frameskip = skip;
368}
369
370void GameController::setTurbo(bool set, bool forced) {
371 if (m_turboForced && !forced) {
372 return;
373 }
374 m_turbo = set;
375 if (set) {
376 m_turboForced = forced;
377 } else {
378 m_turboForced = false;
379 }
380 threadInterrupt();
381 m_threadContext.sync.audioWait = set ? false : m_audioSync;
382 m_threadContext.sync.videoFrameWait = set ? false : m_videoSync;
383 threadContinue();
384}
385
386void GameController::setAVStream(GBAAVStream* stream) {
387 threadInterrupt();
388 m_threadContext.stream = stream;
389 threadContinue();
390}
391
392void GameController::clearAVStream() {
393 threadInterrupt();
394 m_threadContext.stream = nullptr;
395 threadContinue();
396}
397
398void GameController::setRealTime() {
399 m_rtc.override = GameControllerRTC::NO_OVERRIDE;
400}
401
402void GameController::setFixedTime(const QDateTime& time) {
403 m_rtc.override = GameControllerRTC::FIXED;
404 m_rtc.value = time.toMSecsSinceEpoch() / 1000;
405}
406
407void GameController::setFakeEpoch(const QDateTime& time) {
408 m_rtc.override = GameControllerRTC::FAKE_EPOCH;
409 m_rtc.value = time.toMSecsSinceEpoch() / 1000;
410}
411
412void GameController::updateKeys() {
413 int activeKeys = m_activeKeys;
414#ifdef BUILD_SDL
415 activeKeys |= m_activeButtons;
416#endif
417 m_threadContext.activeKeys = activeKeys;
418}
419
420void GameController::redoSamples(int samples) {
421#if RESAMPLE_LIBRARY != RESAMPLE_BLIP_BUF
422 float sampleRate = 0x8000;
423 float ratio;
424 if (m_threadContext.gba) {
425 sampleRate = m_threadContext.gba->audio.sampleRate;
426 }
427 ratio = GBAAudioCalculateRatio(sampleRate, m_threadContext.fpsTarget, 44100);
428 m_threadContext.audioBuffers = ceil(samples / ratio);
429#else
430 m_threadContext.audioBuffers = samples;
431#endif
432 if (m_threadContext.gba) {
433 GBAAudioResizeBuffer(&m_threadContext.gba->audio, m_threadContext.audioBuffers);
434 }
435}
436
437void GameController::setLogLevel(int levels) {
438 threadInterrupt();
439 m_logLevels = levels;
440 threadContinue();
441}
442
443void GameController::enableLogLevel(int levels) {
444 threadInterrupt();
445 m_logLevels |= levels;
446 threadContinue();
447}
448
449void GameController::disableLogLevel(int levels) {
450 threadInterrupt();
451 m_logLevels &= ~levels;
452 threadContinue();
453}
454
455#ifdef BUILD_SDL
456void GameController::testSDLEvents() {
457 if (!m_inputController) {
458 return;
459 }
460
461 m_activeButtons = m_inputController->testSDLEvents();
462 updateKeys();
463}
464#endif