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 "LogController.h"
11#include "MultiplayerController.h"
12#include "VFileDevice.h"
13
14#include <QDateTime>
15#include <QThread>
16
17#include <ctime>
18
19extern "C" {
20#include "gba/audio.h"
21#include "gba/context/config.h"
22#include "gba/context/directories.h"
23#include "gba/gba.h"
24#include "gba/serialize.h"
25#include "gba/sharkport.h"
26#include "gba/renderers/video-software.h"
27#include "util/vfs.h"
28}
29
30using namespace QGBA;
31using namespace std;
32
33GameController::GameController(QObject* parent)
34 : QObject(parent)
35 , m_drawContext(new uint32_t[VIDEO_VERTICAL_PIXELS * VIDEO_HORIZONTAL_PIXELS])
36 , m_frontBuffer(new uint32_t[VIDEO_VERTICAL_PIXELS * VIDEO_HORIZONTAL_PIXELS])
37 , m_threadContext()
38 , m_activeKeys(0)
39 , m_inactiveKeys(0)
40 , m_logLevels(0)
41 , m_gameOpen(false)
42 , m_audioThread(new QThread(this))
43 , m_audioProcessor(AudioProcessor::create())
44 , m_pauseAfterFrame(false)
45 , m_videoSync(VIDEO_SYNC)
46 , m_audioSync(AUDIO_SYNC)
47 , m_fpsTarget(-1)
48 , m_turbo(false)
49 , m_turboForced(false)
50 , m_turboSpeed(-1)
51 , m_wasPaused(false)
52 , m_audioChannels{ true, true, true, true, true, true }
53 , m_videoLayers{ true, true, true, true, true }
54 , m_autofire{}
55 , m_autofireStatus{}
56 , m_inputController(nullptr)
57 , m_multiplayer(nullptr)
58 , m_stateSlot(1)
59 , m_backupLoadState(nullptr)
60 , m_backupSaveState(nullptr)
61{
62 m_renderer = new GBAVideoSoftwareRenderer;
63 GBAVideoSoftwareRendererCreate(m_renderer);
64 m_renderer->outputBuffer = (color_t*) m_drawContext;
65 m_renderer->outputBufferStride = VIDEO_HORIZONTAL_PIXELS;
66
67 GBACheatDeviceCreate(&m_cheatDevice);
68
69 m_threadContext.state = THREAD_INITIALIZED;
70 m_threadContext.debugger = 0;
71 m_threadContext.frameskip = 0;
72 m_threadContext.bios = 0;
73 m_threadContext.renderer = &m_renderer->d;
74 m_threadContext.userData = this;
75 m_threadContext.rewindBufferCapacity = 0;
76 m_threadContext.cheats = &m_cheatDevice;
77 m_threadContext.logLevel = GBA_LOG_ALL;
78 GBADirectorySetInit(&m_threadContext.dirs);
79
80 m_lux.p = this;
81 m_lux.sample = [](GBALuminanceSource* context) {
82 GameControllerLux* lux = static_cast<GameControllerLux*>(context);
83 lux->value = 0xFF - lux->p->m_luxValue;
84 };
85
86 m_lux.readLuminance = [](GBALuminanceSource* context) {
87 GameControllerLux* lux = static_cast<GameControllerLux*>(context);
88 return lux->value;
89 };
90 setLuminanceLevel(0);
91
92 m_threadContext.startCallback = [](GBAThread* context) {
93 GameController* controller = static_cast<GameController*>(context->userData);
94 if (controller->m_audioProcessor) {
95 controller->m_audioProcessor->setInput(context);
96 }
97 context->gba->luminanceSource = &controller->m_lux;
98 GBARTCGenericSourceInit(&controller->m_rtc, context->gba);
99 context->gba->rtcSource = &controller->m_rtc.d;
100 context->gba->rumble = controller->m_inputController->rumble();
101 context->gba->rotationSource = controller->m_inputController->rotationSource();
102 context->gba->audio.forceDisableCh[0] = !controller->m_audioChannels[0];
103 context->gba->audio.forceDisableCh[1] = !controller->m_audioChannels[1];
104 context->gba->audio.forceDisableCh[2] = !controller->m_audioChannels[2];
105 context->gba->audio.forceDisableCh[3] = !controller->m_audioChannels[3];
106 context->gba->audio.forceDisableChA = !controller->m_audioChannels[4];
107 context->gba->audio.forceDisableChB = !controller->m_audioChannels[5];
108 context->gba->video.renderer->disableBG[0] = !controller->m_videoLayers[0];
109 context->gba->video.renderer->disableBG[1] = !controller->m_videoLayers[1];
110 context->gba->video.renderer->disableBG[2] = !controller->m_videoLayers[2];
111 context->gba->video.renderer->disableBG[3] = !controller->m_videoLayers[3];
112 context->gba->video.renderer->disableOBJ = !controller->m_videoLayers[4];
113 controller->m_fpsTarget = context->fpsTarget;
114
115 if (context->dirs.state && GBALoadState(context, context->dirs.state, 0, SAVESTATE_SCREENSHOT)) {
116 VFile* vf = GBAGetState(context->gba, context->dirs.state, 0, true);
117 if (vf) {
118 vf->truncate(vf, 0);
119 }
120 }
121 QMetaObject::invokeMethod(controller, "gameStarted", Q_ARG(GBAThread*, context));
122 };
123
124 m_threadContext.cleanCallback = [](GBAThread* context) {
125 GameController* controller = static_cast<GameController*>(context->userData);
126 QMetaObject::invokeMethod(controller, "gameStopped", Q_ARG(GBAThread*, context));
127 };
128
129 m_threadContext.frameCallback = [](GBAThread* context) {
130 GameController* controller = static_cast<GameController*>(context->userData);
131 memcpy(controller->m_frontBuffer, controller->m_drawContext, VIDEO_VERTICAL_PIXELS * VIDEO_HORIZONTAL_PIXELS * BYTES_PER_PIXEL);
132 QMetaObject::invokeMethod(controller, "frameAvailable", Q_ARG(const uint32_t*, controller->m_frontBuffer));
133 if (controller->m_pauseAfterFrame.testAndSetAcquire(true, false)) {
134 GBAThreadPauseFromThread(context);
135 QMetaObject::invokeMethod(controller, "gamePaused", Q_ARG(GBAThread*, context));
136 }
137 };
138
139 m_threadContext.stopCallback = [](GBAThread* context) {
140 if (!context) {
141 return false;
142 }
143 GameController* controller = static_cast<GameController*>(context->userData);
144 if (!GBASaveState(context, context->dirs.state, 0, true)) {
145 return false;
146 }
147 QMetaObject::invokeMethod(controller, "closeGame");
148 return true;
149 };
150
151 m_threadContext.logHandler = [](GBAThread* context, enum GBALogLevel level, const char* format, va_list args) {
152 static const char* stubMessage = "Stub software interrupt: %02X";
153 static const char* savestateMessage = "State %i loaded";
154 static const char* savestateFailedMessage = "State %i failed to load";
155 if (!context) {
156 return;
157 }
158 GameController* controller = static_cast<GameController*>(context->userData);
159 if (level == GBA_LOG_STUB && strncmp(stubMessage, format, strlen(stubMessage)) == 0) {
160 va_list argc;
161 va_copy(argc, args);
162 int immediate = va_arg(argc, int);
163 va_end(argc);
164 QMetaObject::invokeMethod(controller, "unimplementedBiosCall", Q_ARG(int, immediate));
165 } else if (level == GBA_LOG_STATUS) {
166 // Slot 0 is reserved for suspend points
167 if (strncmp(savestateMessage, format, strlen(savestateMessage)) == 0) {
168 va_list argc;
169 va_copy(argc, args);
170 int slot = va_arg(argc, int);
171 va_end(argc);
172 if (slot == 0) {
173 format = "Loaded suspend state";
174 }
175 } else if (strncmp(savestateFailedMessage, format, strlen(savestateFailedMessage)) == 0) {
176 va_list argc;
177 va_copy(argc, args);
178 int slot = va_arg(argc, int);
179 va_end(argc);
180 if (slot == 0) {
181 return;
182 }
183 }
184 }
185 if (level == GBA_LOG_FATAL) {
186 QMetaObject::invokeMethod(controller, "crashGame", Q_ARG(const QString&, QString().vsprintf(format, args)));
187 } else if (!(controller->m_logLevels & level)) {
188 return;
189 }
190 QString message(QString().vsprintf(format, args));
191 if (level == GBA_LOG_STATUS) {
192 QMetaObject::invokeMethod(controller, "statusPosted", Q_ARG(const QString&, message));
193 }
194 QMetaObject::invokeMethod(controller, "postLog", Q_ARG(int, level), Q_ARG(const QString&, message));
195 };
196
197 connect(&m_rewindTimer, &QTimer::timeout, [this]() {
198 GBARewind(&m_threadContext, 1);
199 emit frameAvailable(m_drawContext);
200 emit rewound(&m_threadContext);
201 });
202 m_rewindTimer.setInterval(100);
203
204 m_audioThread->setObjectName("Audio Thread");
205 m_audioThread->start(QThread::TimeCriticalPriority);
206 m_audioProcessor->moveToThread(m_audioThread);
207 connect(this, SIGNAL(gameStarted(GBAThread*)), m_audioProcessor, SLOT(start()));
208 connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
209 connect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));
210 connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(pollEvents()));
211 connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(updateAutofire()));
212}
213
214GameController::~GameController() {
215 m_audioThread->quit();
216 m_audioThread->wait();
217 disconnect();
218 clearMultiplayerController();
219 closeGame();
220 GBACheatDeviceDestroy(&m_cheatDevice);
221 GBADirectorySetDeinit(&m_threadContext.dirs);
222 delete m_renderer;
223 delete[] m_drawContext;
224 delete[] m_frontBuffer;
225 delete m_backupLoadState;
226}
227
228void GameController::setMultiplayerController(MultiplayerController* controller) {
229 if (controller == m_multiplayer) {
230 return;
231 }
232 clearMultiplayerController();
233 m_multiplayer = controller;
234 controller->attachGame(this);
235}
236
237void GameController::clearMultiplayerController() {
238 if (!m_multiplayer) {
239 return;
240 }
241 m_multiplayer->detachGame(this);
242 m_multiplayer = nullptr;
243}
244
245void GameController::setOverride(const GBACartridgeOverride& override) {
246 m_threadContext.override = override;
247 m_threadContext.hasOverride = true;
248}
249
250void GameController::setOptions(const GBAOptions* opts) {
251 setFrameskip(opts->frameskip);
252 setAudioSync(opts->audioSync);
253 setVideoSync(opts->videoSync);
254 setSkipBIOS(opts->skipBios);
255 setUseBIOS(opts->useBios);
256 setRewind(opts->rewindEnable, opts->rewindBufferCapacity, opts->rewindBufferInterval);
257 setVolume(opts->volume);
258 setMute(opts->mute);
259
260 threadInterrupt();
261 GBADirectorySetMapOptions(&m_threadContext.dirs, opts);
262 m_threadContext.idleOptimization = opts->idleOptimization;
263 threadContinue();
264}
265
266#ifdef USE_GDB_STUB
267ARMDebugger* GameController::debugger() {
268 return m_threadContext.debugger;
269}
270
271void GameController::setDebugger(ARMDebugger* debugger) {
272 threadInterrupt();
273 if (m_threadContext.debugger && GBAThreadIsActive(&m_threadContext)) {
274 GBADetachDebugger(m_threadContext.gba);
275 }
276 m_threadContext.debugger = debugger;
277 if (m_threadContext.debugger && GBAThreadIsActive(&m_threadContext)) {
278 GBAAttachDebugger(m_threadContext.gba, m_threadContext.debugger);
279 }
280 threadContinue();
281}
282#endif
283
284void GameController::loadGame(const QString& path) {
285 closeGame();
286 QFile file(path);
287 if (!file.open(QIODevice::ReadOnly)) {
288 postLog(GBA_LOG_ERROR, tr("Failed to open game file: %1").arg(path));
289 return;
290 }
291 file.close();
292
293 m_fname = path;
294 openGame();
295}
296
297void GameController::bootBIOS() {
298 closeGame();
299 m_fname = QString();
300 openGame(true);
301}
302
303void GameController::openGame(bool biosOnly) {
304 if (biosOnly && (!m_useBios || m_bios.isNull())) {
305 return;
306 }
307
308 m_gameOpen = true;
309
310 m_pauseAfterFrame = false;
311
312 if (m_turbo) {
313 m_threadContext.sync.videoFrameWait = false;
314 m_threadContext.sync.audioWait = false;
315 } else {
316 m_threadContext.sync.videoFrameWait = m_videoSync;
317 m_threadContext.sync.audioWait = m_audioSync;
318 }
319
320 m_threadContext.bootBios = biosOnly;
321 if (biosOnly) {
322 m_threadContext.fname = nullptr;
323 } else {
324 m_threadContext.fname = strdup(m_fname.toUtf8().constData());
325 GBAThreadLoadROM(&m_threadContext, m_threadContext.fname);
326 }
327
328 if (!m_bios.isNull() && m_useBios) {
329 m_threadContext.bios = VFileDevice::open(m_bios, O_RDONLY);
330 } else {
331 m_threadContext.bios = nullptr;
332 }
333
334 if (!m_patch.isNull()) {
335 m_threadContext.patch = VFileDevice::open(m_patch, O_RDONLY);
336 }
337
338 m_inputController->recalibrateAxes();
339 memset(m_drawContext, 0xF8, VIDEO_VERTICAL_PIXELS * VIDEO_HORIZONTAL_PIXELS * 4);
340
341 if (!GBAThreadStart(&m_threadContext)) {
342 m_gameOpen = false;
343 emit gameFailed();
344 }
345}
346
347void GameController::loadBIOS(const QString& path) {
348 if (m_bios == path) {
349 return;
350 }
351 m_bios = path;
352 if (m_gameOpen) {
353 closeGame();
354 openGame();
355 }
356}
357
358void GameController::yankPak() {
359 if (!m_gameOpen) {
360 return;
361 }
362 threadInterrupt();
363 GBAYankROM(m_threadContext.gba);
364 threadContinue();
365}
366
367void GameController::replaceGame(const QString& path) {
368 if (!m_gameOpen) {
369 return;
370 }
371
372 m_fname = path;
373 threadInterrupt();
374 m_threadContext.fname = strdup(m_fname.toLocal8Bit().constData());
375 GBAThreadReplaceROM(&m_threadContext, m_threadContext.fname);
376 threadContinue();
377}
378
379void GameController::loadPatch(const QString& path) {
380 if (m_gameOpen) {
381 closeGame();
382 m_patch = path;
383 openGame();
384 } else {
385 m_patch = path;
386 }
387}
388
389void GameController::importSharkport(const QString& path) {
390 if (!isLoaded()) {
391 return;
392 }
393 VFile* vf = VFileDevice::open(path, O_RDONLY);
394 if (!vf) {
395 postLog(GBA_LOG_ERROR, tr("Failed to open snapshot file for reading: %1").arg(path));
396 return;
397 }
398 threadInterrupt();
399 GBASavedataImportSharkPort(m_threadContext.gba, vf, false);
400 threadContinue();
401 vf->close(vf);
402}
403
404void GameController::exportSharkport(const QString& path) {
405 if (!isLoaded()) {
406 return;
407 }
408 VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
409 if (!vf) {
410 postLog(GBA_LOG_ERROR, tr("Failed to open snapshot file for writing: %1").arg(path));
411 return;
412 }
413 threadInterrupt();
414 GBASavedataExportSharkPort(m_threadContext.gba, vf);
415 threadContinue();
416 vf->close(vf);
417}
418
419void GameController::closeGame() {
420 if (!m_gameOpen) {
421 return;
422 }
423 m_rewindTimer.stop();
424 if (GBAThreadIsPaused(&m_threadContext)) {
425 GBAThreadUnpause(&m_threadContext);
426 }
427 m_audioProcessor->pause();
428 GBAThreadEnd(&m_threadContext);
429 GBAThreadJoin(&m_threadContext);
430 if (m_threadContext.fname) {
431 free(const_cast<char*>(m_threadContext.fname));
432 m_threadContext.fname = nullptr;
433 }
434
435 m_patch = QString();
436
437 for (size_t i = 0; i < GBACheatSetsSize(&m_cheatDevice.cheats); ++i) {
438 GBACheatSet* set = *GBACheatSetsGetPointer(&m_cheatDevice.cheats, i);
439 GBACheatSetDeinit(set);
440 delete set;
441 }
442 GBACheatSetsClear(&m_cheatDevice.cheats);
443
444 m_gameOpen = false;
445 emit gameStopped(&m_threadContext);
446}
447
448void GameController::crashGame(const QString& crashMessage) {
449 closeGame();
450 emit gameCrashed(crashMessage);
451 emit gameStopped(&m_threadContext);
452}
453
454bool GameController::isPaused() {
455 if (!m_gameOpen) {
456 return false;
457 }
458 return GBAThreadIsPaused(&m_threadContext);
459}
460
461void GameController::setPaused(bool paused) {
462 if (!isLoaded() || m_rewindTimer.isActive() || paused == GBAThreadIsPaused(&m_threadContext)) {
463 return;
464 }
465 if (paused) {
466 m_pauseAfterFrame.testAndSetRelaxed(false, true);
467 } else {
468 GBAThreadUnpause(&m_threadContext);
469 emit gameUnpaused(&m_threadContext);
470 }
471}
472
473void GameController::reset() {
474 if (!m_gameOpen) {
475 return;
476 }
477 bool wasPaused = isPaused();
478 setPaused(false);
479 GBAThreadReset(&m_threadContext);
480 if (wasPaused) {
481 setPaused(true);
482 }
483}
484
485void GameController::threadInterrupt() {
486 if (m_gameOpen) {
487 GBAThreadInterrupt(&m_threadContext);
488 }
489}
490
491void GameController::threadContinue() {
492 if (m_gameOpen) {
493 GBAThreadContinue(&m_threadContext);
494 }
495}
496
497void GameController::frameAdvance() {
498 if (m_rewindTimer.isActive()) {
499 return;
500 }
501 if (m_pauseAfterFrame.testAndSetRelaxed(false, true)) {
502 setPaused(false);
503 }
504}
505
506void GameController::setRewind(bool enable, int capacity, int interval) {
507 if (m_gameOpen) {
508 threadInterrupt();
509 GBARewindSettingsChanged(&m_threadContext, enable ? capacity : 0, enable ? interval : 0);
510 threadContinue();
511 } else {
512 if (enable) {
513 m_threadContext.rewindBufferInterval = interval;
514 m_threadContext.rewindBufferCapacity = capacity;
515 } else {
516 m_threadContext.rewindBufferInterval = 0;
517 m_threadContext.rewindBufferCapacity = 0;
518 }
519 }
520}
521
522void GameController::rewind(int states) {
523 threadInterrupt();
524 if (!states) {
525 GBARewindAll(&m_threadContext);
526 } else {
527 GBARewind(&m_threadContext, states);
528 }
529 threadContinue();
530 emit frameAvailable(m_drawContext);
531 emit rewound(&m_threadContext);
532}
533
534void GameController::startRewinding() {
535 if (!m_gameOpen || m_rewindTimer.isActive()) {
536 return;
537 }
538 if (m_multiplayer && m_multiplayer->attached() > 1) {
539 return;
540 }
541 m_wasPaused = isPaused();
542 if (!GBAThreadIsPaused(&m_threadContext)) {
543 GBAThreadPause(&m_threadContext);
544 }
545 m_rewindTimer.start();
546}
547
548void GameController::stopRewinding() {
549 if (!m_rewindTimer.isActive()) {
550 return;
551 }
552 m_rewindTimer.stop();
553 bool signalsBlocked = blockSignals(true);
554 setPaused(m_wasPaused);
555 blockSignals(signalsBlocked);
556}
557
558void GameController::keyPressed(int key) {
559 int mappedKey = 1 << key;
560 m_activeKeys |= mappedKey;
561 if (!m_inputController->allowOpposing()) {
562 if ((m_activeKeys & 0x30) == 0x30) {
563 m_inactiveKeys |= mappedKey ^ 0x30;
564 m_activeKeys ^= mappedKey ^ 0x30;
565 }
566 if ((m_activeKeys & 0xC0) == 0xC0) {
567 m_inactiveKeys |= mappedKey ^ 0xC0;
568 m_activeKeys ^= mappedKey ^ 0xC0;
569 }
570 }
571 updateKeys();
572}
573
574void GameController::keyReleased(int key) {
575 int mappedKey = 1 << key;
576 m_activeKeys &= ~mappedKey;
577 if (!m_inputController->allowOpposing()) {
578 if (mappedKey & 0x30) {
579 m_activeKeys |= m_inactiveKeys & (0x30 ^ mappedKey);
580 m_inactiveKeys &= ~0x30;
581 }
582 if (mappedKey & 0xC0) {
583 m_activeKeys |= m_inactiveKeys & (0xC0 ^ mappedKey);
584 m_inactiveKeys &= ~0xC0;
585 }
586 }
587 updateKeys();
588}
589
590void GameController::clearKeys() {
591 m_activeKeys = 0;
592 m_inactiveKeys = 0;
593 updateKeys();
594}
595
596void GameController::setAutofire(int key, bool enable) {
597 if (key >= GBA_KEY_MAX || key < 0) {
598 return;
599 }
600 m_autofire[key] = enable;
601 m_autofireStatus[key] = 0;
602}
603
604void GameController::setAudioBufferSamples(int samples) {
605 if (m_audioProcessor) {
606 threadInterrupt();
607 redoSamples(samples);
608 threadContinue();
609 QMetaObject::invokeMethod(m_audioProcessor, "setBufferSamples", Qt::BlockingQueuedConnection, Q_ARG(int, samples));
610 }
611}
612
613void GameController::setAudioSampleRate(unsigned rate) {
614 if (!rate) {
615 return;
616 }
617 if (m_audioProcessor) {
618 threadInterrupt();
619 redoSamples(m_audioProcessor->getBufferSamples());
620 threadContinue();
621 QMetaObject::invokeMethod(m_audioProcessor, "requestSampleRate", Q_ARG(unsigned, rate));
622 }
623}
624
625void GameController::setAudioChannelEnabled(int channel, bool enable) {
626 if (channel > 5 || channel < 0) {
627 return;
628 }
629 m_audioChannels[channel] = enable;
630 if (isLoaded()) {
631 switch (channel) {
632 case 0:
633 case 1:
634 case 2:
635 case 3:
636 m_threadContext.gba->audio.forceDisableCh[channel] = !enable;
637 break;
638 case 4:
639 m_threadContext.gba->audio.forceDisableChA = !enable;
640 break;
641 case 5:
642 m_threadContext.gba->audio.forceDisableChB = !enable;
643 break;
644 }
645 }
646}
647
648void GameController::setVideoLayerEnabled(int layer, bool enable) {
649 if (layer > 4 || layer < 0) {
650 return;
651 }
652 m_videoLayers[layer] = enable;
653 if (isLoaded()) {
654 switch (layer) {
655 case 0:
656 case 1:
657 case 2:
658 case 3:
659 m_threadContext.gba->video.renderer->disableBG[layer] = !enable;
660 break;
661 case 4:
662 m_threadContext.gba->video.renderer->disableOBJ = !enable;
663 break;
664 }
665 }
666}
667
668void GameController::setFPSTarget(float fps) {
669 threadInterrupt();
670 m_fpsTarget = fps;
671 m_threadContext.fpsTarget = fps;
672 if (m_turbo && m_turboSpeed > 0) {
673 m_threadContext.fpsTarget *= m_turboSpeed;
674 }
675 if (m_audioProcessor) {
676 redoSamples(m_audioProcessor->getBufferSamples());
677 }
678 threadContinue();
679}
680
681void GameController::setSkipBIOS(bool set) {
682 threadInterrupt();
683 m_threadContext.skipBios = set;
684 threadContinue();
685}
686
687void GameController::setUseBIOS(bool use) {
688 if (use == m_useBios) {
689 return;
690 }
691 m_useBios = use;
692 if (m_gameOpen) {
693 closeGame();
694 openGame();
695 }
696}
697
698void GameController::loadState(int slot) {
699 if (!m_threadContext.fname) {
700 // We're in the BIOS
701 return;
702 }
703 if (slot > 0 && slot != m_stateSlot) {
704 m_stateSlot = slot;
705 m_backupSaveState.clear();
706 }
707 GBARunOnThread(&m_threadContext, [](GBAThread* context) {
708 GameController* controller = static_cast<GameController*>(context->userData);
709 if (!controller->m_backupLoadState) {
710 controller->m_backupLoadState = new GBASerializedState;
711 }
712 GBASerialize(context->gba, controller->m_backupLoadState);
713 if (GBALoadState(context, context->dirs.state, controller->m_stateSlot, SAVESTATE_SCREENSHOT)) {
714 controller->frameAvailable(controller->m_drawContext);
715 controller->stateLoaded(context);
716 }
717 });
718}
719
720void GameController::saveState(int slot) {
721 if (!m_threadContext.fname) {
722 // We're in the BIOS
723 return;
724 }
725 if (slot > 0) {
726 m_stateSlot = slot;
727 }
728 GBARunOnThread(&m_threadContext, [](GBAThread* context) {
729 GameController* controller = static_cast<GameController*>(context->userData);
730 VFile* vf = GBAGetState(context->gba, context->dirs.state, controller->m_stateSlot, false);
731 if (vf) {
732 controller->m_backupSaveState.resize(vf->size(vf));
733 vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
734 vf->close(vf);
735 }
736 GBASaveState(context, context->dirs.state, controller->m_stateSlot, SAVESTATE_SCREENSHOT | EXTDATA_SAVEDATA);
737 });
738}
739
740void GameController::loadBackupState() {
741 if (!m_backupLoadState) {
742 return;
743 }
744
745 GBARunOnThread(&m_threadContext, [](GBAThread* context) {
746 GameController* controller = static_cast<GameController*>(context->userData);
747 if (GBADeserialize(context->gba, controller->m_backupLoadState)) {
748 GBALog(context->gba, GBA_LOG_STATUS, "Undid state load");
749 controller->frameAvailable(controller->m_drawContext);
750 controller->stateLoaded(context);
751 }
752 delete controller->m_backupLoadState;
753 controller->m_backupLoadState = nullptr;
754 });
755}
756
757void GameController::saveBackupState() {
758 if (m_backupSaveState.isEmpty()) {
759 return;
760 }
761
762 GBARunOnThread(&m_threadContext, [](GBAThread* context) {
763 GameController* controller = static_cast<GameController*>(context->userData);
764 VFile* vf = GBAGetState(context->gba, context->dirs.state, controller->m_stateSlot, true);
765 if (vf) {
766 vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
767 vf->close(vf);
768 GBALog(context->gba, GBA_LOG_STATUS, "Undid state save");
769 }
770 controller->m_backupSaveState.clear();
771 });
772}
773
774void GameController::setVideoSync(bool set) {
775 m_videoSync = set;
776 if (!m_turbo) {
777 threadInterrupt();
778 m_threadContext.sync.videoFrameWait = set;
779 threadContinue();
780 }
781}
782
783void GameController::setAudioSync(bool set) {
784 m_audioSync = set;
785 if (!m_turbo) {
786 threadInterrupt();
787 m_threadContext.sync.audioWait = set;
788 threadContinue();
789 }
790}
791
792void GameController::setFrameskip(int skip) {
793 threadInterrupt();
794 m_threadContext.frameskip = skip;
795 if (isLoaded()) {
796 m_threadContext.gba->video.frameskip = skip;
797 }
798 threadContinue();
799}
800
801void GameController::setVolume(int volume) {
802 threadInterrupt();
803 m_threadContext.volume = volume;
804 if (isLoaded()) {
805 m_threadContext.gba->audio.masterVolume = volume;
806 }
807 threadContinue();
808}
809
810void GameController::setMute(bool mute) {
811 threadInterrupt();
812 m_threadContext.mute = mute;
813 if (isLoaded()) {
814 m_threadContext.gba->audio.masterVolume = mute ? 0 : m_threadContext.volume;
815 }
816 threadContinue();
817}
818
819void GameController::setTurbo(bool set, bool forced) {
820 if (m_turboForced && !forced) {
821 return;
822 }
823 if (m_turbo == set && m_turboForced == forced) {
824 // Don't interrupt the thread if we don't need to
825 return;
826 }
827 m_turbo = set;
828 m_turboForced = set && forced;
829 enableTurbo();
830}
831
832void GameController::setTurboSpeed(float ratio) {
833 m_turboSpeed = ratio;
834 enableTurbo();
835}
836
837void GameController::enableTurbo() {
838 threadInterrupt();
839 if (!m_turbo) {
840 m_threadContext.fpsTarget = m_fpsTarget;
841 m_threadContext.sync.audioWait = m_audioSync;
842 m_threadContext.sync.videoFrameWait = m_videoSync;
843 } else if (m_turboSpeed <= 0) {
844 m_threadContext.fpsTarget = m_fpsTarget;
845 m_threadContext.sync.audioWait = false;
846 m_threadContext.sync.videoFrameWait = false;
847 } else {
848 m_threadContext.fpsTarget = m_fpsTarget * m_turboSpeed;
849 m_threadContext.sync.audioWait = true;
850 m_threadContext.sync.videoFrameWait = false;
851 }
852 if (m_audioProcessor) {
853 redoSamples(m_audioProcessor->getBufferSamples());
854 }
855 threadContinue();
856}
857
858void GameController::setAVStream(GBAAVStream* stream) {
859 threadInterrupt();
860 m_threadContext.stream = stream;
861 if (isLoaded()) {
862 m_threadContext.gba->stream = stream;
863 }
864 threadContinue();
865}
866
867void GameController::clearAVStream() {
868 threadInterrupt();
869 m_threadContext.stream = nullptr;
870 if (isLoaded()) {
871 m_threadContext.gba->stream = nullptr;
872 }
873 threadContinue();
874}
875
876#ifdef USE_PNG
877void GameController::screenshot() {
878 GBARunOnThread(&m_threadContext, GBAThreadTakeScreenshot);
879}
880#endif
881
882void GameController::reloadAudioDriver() {
883 int samples = 0;
884 unsigned sampleRate = 0;
885 if (m_audioProcessor) {
886 QMetaObject::invokeMethod(m_audioProcessor, "pause", Qt::BlockingQueuedConnection);
887 samples = m_audioProcessor->getBufferSamples();
888 sampleRate = m_audioProcessor->sampleRate();
889 delete m_audioProcessor;
890 }
891 m_audioProcessor = AudioProcessor::create();
892 if (samples) {
893 m_audioProcessor->setBufferSamples(samples);
894 }
895 if (sampleRate) {
896 m_audioProcessor->requestSampleRate(sampleRate);
897 }
898 m_audioProcessor->moveToThread(m_audioThread);
899 connect(this, SIGNAL(gameStarted(GBAThread*)), m_audioProcessor, SLOT(start()));
900 connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
901 connect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));
902 if (isLoaded()) {
903 m_audioProcessor->setInput(&m_threadContext);
904 QMetaObject::invokeMethod(m_audioProcessor, "start");
905 }
906}
907
908void GameController::setLuminanceValue(uint8_t value) {
909 m_luxValue = value;
910 value = std::max<int>(value - 0x16, 0);
911 m_luxLevel = 10;
912 for (int i = 0; i < 10; ++i) {
913 if (value < GBA_LUX_LEVELS[i]) {
914 m_luxLevel = i;
915 break;
916 }
917 }
918 emit luminanceValueChanged(m_luxValue);
919}
920
921void GameController::setLuminanceLevel(int level) {
922 int value = 0x16;
923 level = std::max(0, std::min(10, level));
924 if (level > 0) {
925 value += GBA_LUX_LEVELS[level - 1];
926 }
927 setLuminanceValue(value);
928}
929
930void GameController::setRealTime() {
931 m_rtc.override = GBARTCGenericSource::RTC_NO_OVERRIDE;
932}
933
934void GameController::setFixedTime(const QDateTime& time) {
935 m_rtc.override = GBARTCGenericSource::RTC_FIXED;
936 m_rtc.value = time.toMSecsSinceEpoch() / 1000;
937}
938
939void GameController::setFakeEpoch(const QDateTime& time) {
940 m_rtc.override = GBARTCGenericSource::RTC_FAKE_EPOCH;
941 m_rtc.value = time.toMSecsSinceEpoch() / 1000;
942}
943
944void GameController::updateKeys() {
945 int activeKeys = m_activeKeys;
946 activeKeys |= m_activeButtons;
947 activeKeys &= ~m_inactiveKeys;
948 m_threadContext.activeKeys = activeKeys;
949}
950
951void GameController::redoSamples(int samples) {
952#if RESAMPLE_LIBRARY != RESAMPLE_BLIP_BUF
953 float sampleRate = 0x8000;
954 float ratio;
955 if (m_threadContext.gba) {
956 sampleRate = m_threadContext.gba->audio.sampleRate;
957 }
958 ratio = GBAAudioCalculateRatio(sampleRate, m_threadContext.fpsTarget, m_audioProcess->sampleRate());
959 m_threadContext.audioBuffers = ceil(samples / ratio);
960#else
961 m_threadContext.audioBuffers = samples;
962#endif
963 if (m_threadContext.gba) {
964 GBAAudioResizeBuffer(&m_threadContext.gba->audio, m_threadContext.audioBuffers);
965 }
966 QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
967}
968
969void GameController::setLogLevel(int levels) {
970 threadInterrupt();
971 m_logLevels = levels;
972 threadContinue();
973}
974
975void GameController::enableLogLevel(int levels) {
976 threadInterrupt();
977 m_logLevels |= levels;
978 threadContinue();
979}
980
981void GameController::disableLogLevel(int levels) {
982 threadInterrupt();
983 m_logLevels &= ~levels;
984 threadContinue();
985}
986
987void GameController::pollEvents() {
988 if (!m_inputController) {
989 return;
990 }
991
992 m_activeButtons = m_inputController->pollEvents();
993 updateKeys();
994}
995
996void GameController::updateAutofire() {
997 // TODO: Move all key events onto the CPU thread...somehow
998 for (int k = 0; k < GBA_KEY_MAX; ++k) {
999 if (!m_autofire[k]) {
1000 continue;
1001 }
1002 m_autofireStatus[k] ^= 1;
1003 if (m_autofireStatus[k]) {
1004 keyPressed(k);
1005 } else {
1006 keyReleased(k);
1007 }
1008 }
1009}