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