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