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/gba.h"
23#include "gba/serialize.h"
24#include "gba/sharkport.h"
25#include "gba/renderers/video-software.h"
26#include "util/vfs.h"
27}
28
29using namespace QGBA;
30using namespace std;
31
32GameController::GameController(QObject* parent)
33 : QObject(parent)
34 , m_drawContext(new uint32_t[256 * VIDEO_HORIZONTAL_PIXELS])
35 , m_frontBuffer(new uint32_t[256 * 256])
36 , m_threadContext()
37 , m_activeKeys(0)
38 , m_inactiveKeys(0)
39 , m_logLevels(0)
40 , m_gameOpen(false)
41 , m_audioThread(new QThread(this))
42 , m_audioProcessor(AudioProcessor::create())
43 , m_pauseAfterFrame(false)
44 , m_videoSync(VIDEO_SYNC)
45 , m_audioSync(AUDIO_SYNC)
46 , m_fpsTarget(-1)
47 , m_turbo(false)
48 , m_turboForced(false)
49 , m_turboSpeed(-1)
50 , m_wasPaused(false)
51 , m_audioChannels{ true, true, true, true, true, true }
52 , m_videoLayers{ true, true, true, true, true }
53 , m_inputController(nullptr)
54 , m_multiplayer(nullptr)
55 , m_stateSlot(1)
56 , m_backupLoadState(nullptr)
57 , m_backupSaveState(nullptr)
58{
59 m_renderer = new GBAVideoSoftwareRenderer;
60 GBAVideoSoftwareRendererCreate(m_renderer);
61 m_renderer->outputBuffer = (color_t*) m_drawContext;
62 m_renderer->outputBufferStride = 256;
63
64 GBACheatDeviceCreate(&m_cheatDevice);
65
66 m_threadContext.state = THREAD_INITIALIZED;
67 m_threadContext.debugger = 0;
68 m_threadContext.frameskip = 0;
69 m_threadContext.bios = 0;
70 m_threadContext.renderer = &m_renderer->d;
71 m_threadContext.userData = this;
72 m_threadContext.rewindBufferCapacity = 0;
73 m_threadContext.cheats = &m_cheatDevice;
74 m_threadContext.logLevel = GBA_LOG_ALL;
75
76 m_lux.p = this;
77 m_lux.sample = [](GBALuminanceSource* context) {
78 GameControllerLux* lux = static_cast<GameControllerLux*>(context);
79 lux->value = 0xFF - lux->p->m_luxValue;
80 };
81
82 m_lux.readLuminance = [](GBALuminanceSource* context) {
83 GameControllerLux* lux = static_cast<GameControllerLux*>(context);
84 return lux->value;
85 };
86 setLuminanceLevel(0);
87
88 m_threadContext.startCallback = [](GBAThread* context) {
89 GameController* controller = static_cast<GameController*>(context->userData);
90 if (controller->m_audioProcessor) {
91 controller->m_audioProcessor->setInput(context);
92 }
93 context->gba->luminanceSource = &controller->m_lux;
94 GBARTCGenericSourceInit(&controller->m_rtc, context->gba);
95 context->gba->rtcSource = &controller->m_rtc.d;
96 context->gba->rumble = controller->m_inputController->rumble();
97 context->gba->rotationSource = controller->m_inputController->rotationSource();
98 context->gba->audio.forceDisableCh[0] = !controller->m_audioChannels[0];
99 context->gba->audio.forceDisableCh[1] = !controller->m_audioChannels[1];
100 context->gba->audio.forceDisableCh[2] = !controller->m_audioChannels[2];
101 context->gba->audio.forceDisableCh[3] = !controller->m_audioChannels[3];
102 context->gba->audio.forceDisableChA = !controller->m_audioChannels[4];
103 context->gba->audio.forceDisableChB = !controller->m_audioChannels[5];
104 context->gba->video.renderer->disableBG[0] = !controller->m_videoLayers[0];
105 context->gba->video.renderer->disableBG[1] = !controller->m_videoLayers[1];
106 context->gba->video.renderer->disableBG[2] = !controller->m_videoLayers[2];
107 context->gba->video.renderer->disableBG[3] = !controller->m_videoLayers[3];
108 context->gba->video.renderer->disableOBJ = !controller->m_videoLayers[4];
109 controller->m_fpsTarget = context->fpsTarget;
110
111 if (GBALoadState(context, context->stateDir, 0)) {
112 VFile* vf = GBAGetState(context->gba, context->stateDir, 0, true);
113 if (vf) {
114 vf->truncate(vf, 0);
115 }
116 }
117 QMetaObject::invokeMethod(controller, "gameStarted", Q_ARG(GBAThread*, context));
118 };
119
120 m_threadContext.cleanCallback = [](GBAThread* context) {
121 GameController* controller = static_cast<GameController*>(context->userData);
122 QMetaObject::invokeMethod(controller, "gameStopped", Q_ARG(GBAThread*, context));
123 };
124
125 m_threadContext.frameCallback = [](GBAThread* context) {
126 GameController* controller = static_cast<GameController*>(context->userData);
127 if (GBASyncDrawingFrame(&controller->m_threadContext.sync)) {
128 memcpy(controller->m_frontBuffer, controller->m_drawContext, 256 * VIDEO_HORIZONTAL_PIXELS * BYTES_PER_PIXEL);
129 QMetaObject::invokeMethod(controller, "frameAvailable", Q_ARG(const uint32_t*, controller->m_frontBuffer));
130 } else {
131 QMetaObject::invokeMethod(controller, "frameAvailable", Q_ARG(const uint32_t*, nullptr));
132 }
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->stateDir, 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(gameStopped(GBAThread*)), m_audioProcessor, SLOT(pause()));
209 connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
210 connect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));
211 connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(pollEvents()));
212}
213
214GameController::~GameController() {
215 m_audioThread->quit();
216 m_audioThread->wait();
217 disconnect();
218 clearMultiplayerController();
219 closeGame();
220 GBACheatDeviceDestroy(&m_cheatDevice);
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 m_threadContext.idleOptimization = opts->idleOptimization;
261 threadContinue();
262}
263
264#ifdef USE_GDB_STUB
265ARMDebugger* GameController::debugger() {
266 return m_threadContext.debugger;
267}
268
269void GameController::setDebugger(ARMDebugger* debugger) {
270 threadInterrupt();
271 if (m_threadContext.debugger && GBAThreadIsActive(&m_threadContext)) {
272 GBADetachDebugger(m_threadContext.gba);
273 }
274 m_threadContext.debugger = debugger;
275 if (m_threadContext.debugger && GBAThreadIsActive(&m_threadContext)) {
276 GBAAttachDebugger(m_threadContext.gba, m_threadContext.debugger);
277 }
278 threadContinue();
279}
280#endif
281
282void GameController::loadGame(const QString& path, bool dirmode) {
283 closeGame();
284 if (!dirmode) {
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
293 m_fname = path;
294 m_dirmode = dirmode;
295 openGame();
296}
297
298void GameController::bootBIOS() {
299 closeGame();
300 m_fname = QString();
301 m_dirmode = false;
302 openGame(true);
303}
304
305void GameController::openGame(bool biosOnly) {
306 if (biosOnly && (!m_useBios || m_bios.isNull())) {
307 return;
308 }
309
310 m_gameOpen = true;
311
312 m_pauseAfterFrame = false;
313
314 if (m_turbo) {
315 m_threadContext.sync.videoFrameWait = false;
316 m_threadContext.sync.audioWait = false;
317 } else {
318 m_threadContext.sync.videoFrameWait = m_videoSync;
319 m_threadContext.sync.audioWait = m_audioSync;
320 }
321
322 m_threadContext.gameDir = 0;
323 m_threadContext.bootBios = biosOnly;
324 if (biosOnly) {
325 m_threadContext.fname = nullptr;
326 } else {
327 m_threadContext.fname = strdup(m_fname.toUtf8().constData());
328 if (m_dirmode) {
329 m_threadContext.gameDir = VDirOpen(m_threadContext.fname);
330 m_threadContext.stateDir = m_threadContext.gameDir;
331 } else {
332 GBAThreadLoadROM(&m_threadContext, m_threadContext.fname);
333 }
334 }
335
336 if (!m_bios.isNull() && m_useBios) {
337 m_threadContext.bios = VFileDevice::open(m_bios, O_RDONLY);
338 } else {
339 m_threadContext.bios = nullptr;
340 }
341
342 if (!m_patch.isNull()) {
343 m_threadContext.patch = VFileDevice::open(m_patch, O_RDONLY);
344 }
345
346 m_inputController->recalibrateAxes();
347 memset(m_drawContext, 0xF8, 1024 * VIDEO_HORIZONTAL_PIXELS);
348
349 if (!GBAThreadStart(&m_threadContext)) {
350 m_gameOpen = false;
351 emit gameFailed();
352 }
353}
354
355void GameController::loadBIOS(const QString& path) {
356 if (m_bios == path) {
357 return;
358 }
359 m_bios = path;
360 if (m_gameOpen) {
361 closeGame();
362 openGame();
363 }
364}
365
366void GameController::yankPak() {
367 if (!m_gameOpen) {
368 return;
369 }
370 threadInterrupt();
371 GBAYankROM(m_threadContext.gba);
372 threadContinue();
373}
374
375void GameController::replaceGame(const QString& path) {
376 if (!m_gameOpen) {
377 return;
378 }
379
380 m_fname = path;
381 threadInterrupt();
382 m_threadContext.fname = strdup(m_fname.toLocal8Bit().constData());
383 GBAThreadReplaceROM(&m_threadContext, m_threadContext.fname);
384 threadContinue();
385}
386
387void GameController::loadPatch(const QString& path) {
388 if (m_gameOpen) {
389 closeGame();
390 m_patch = path;
391 openGame();
392 } else {
393 m_patch = path;
394 }
395}
396
397void GameController::importSharkport(const QString& path) {
398 if (!m_gameOpen) {
399 return;
400 }
401 VFile* vf = VFileDevice::open(path, O_RDONLY);
402 if (!vf) {
403 postLog(GBA_LOG_ERROR, tr("Failed to open snapshot file for reading: %1").arg(path));
404 return;
405 }
406 threadInterrupt();
407 GBASavedataImportSharkPort(m_threadContext.gba, vf, false);
408 threadContinue();
409 vf->close(vf);
410}
411
412void GameController::exportSharkport(const QString& path) {
413 if (!m_gameOpen) {
414 return;
415 }
416 VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
417 if (!vf) {
418 postLog(GBA_LOG_ERROR, tr("Failed to open snapshot file for writing: %1").arg(path));
419 return;
420 }
421 threadInterrupt();
422 GBASavedataExportSharkPort(m_threadContext.gba, vf);
423 threadContinue();
424 vf->close(vf);
425}
426
427void GameController::closeGame() {
428 if (!m_gameOpen) {
429 return;
430 }
431 m_rewindTimer.stop();
432 if (GBAThreadIsPaused(&m_threadContext)) {
433 GBAThreadUnpause(&m_threadContext);
434 }
435 GBAThreadEnd(&m_threadContext);
436 GBAThreadJoin(&m_threadContext);
437 if (m_threadContext.fname) {
438 free(const_cast<char*>(m_threadContext.fname));
439 m_threadContext.fname = nullptr;
440 }
441
442 m_patch = QString();
443
444 for (size_t i = 0; i < GBACheatSetsSize(&m_cheatDevice.cheats); ++i) {
445 GBACheatSet* set = *GBACheatSetsGetPointer(&m_cheatDevice.cheats, i);
446 GBACheatSetDeinit(set);
447 delete set;
448 }
449 GBACheatSetsClear(&m_cheatDevice.cheats);
450
451 m_gameOpen = false;
452 emit gameStopped(&m_threadContext);
453}
454
455void GameController::crashGame(const QString& crashMessage) {
456 closeGame();
457 emit gameCrashed(crashMessage);
458 emit gameStopped(&m_threadContext);
459}
460
461bool GameController::isPaused() {
462 if (!m_gameOpen) {
463 return false;
464 }
465 return GBAThreadIsPaused(&m_threadContext);
466}
467
468void GameController::setPaused(bool paused) {
469 if (!m_gameOpen || m_rewindTimer.isActive() || paused == GBAThreadIsPaused(&m_threadContext)) {
470 return;
471 }
472 if (paused) {
473 m_pauseAfterFrame.testAndSetRelaxed(false, true);
474 } else {
475 GBAThreadUnpause(&m_threadContext);
476 emit gameUnpaused(&m_threadContext);
477 }
478}
479
480void GameController::reset() {
481 GBAThreadReset(&m_threadContext);
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::setAudioBufferSamples(int samples) {
596 if (m_audioProcessor) {
597 threadInterrupt();
598 redoSamples(samples);
599 threadContinue();
600 QMetaObject::invokeMethod(m_audioProcessor, "setBufferSamples", Q_ARG(int, samples));
601 }
602}
603
604void GameController::setAudioSampleRate(unsigned rate) {
605 if (!rate) {
606 return;
607 }
608 if (m_audioProcessor) {
609 threadInterrupt();
610 redoSamples(m_audioProcessor->getBufferSamples());
611 threadContinue();
612 QMetaObject::invokeMethod(m_audioProcessor, "requestSampleRate", Q_ARG(unsigned, rate));
613 }
614}
615
616void GameController::setAudioChannelEnabled(int channel, bool enable) {
617 if (channel > 5 || channel < 0) {
618 return;
619 }
620 m_audioChannels[channel] = enable;
621 if (m_gameOpen) {
622 switch (channel) {
623 case 0:
624 case 1:
625 case 2:
626 case 3:
627 m_threadContext.gba->audio.forceDisableCh[channel] = !enable;
628 break;
629 case 4:
630 m_threadContext.gba->audio.forceDisableChA = !enable;
631 break;
632 case 5:
633 m_threadContext.gba->audio.forceDisableChB = !enable;
634 break;
635 }
636 }
637}
638
639void GameController::setVideoLayerEnabled(int layer, bool enable) {
640 if (layer > 4 || layer < 0) {
641 return;
642 }
643 m_videoLayers[layer] = enable;
644 if (m_gameOpen) {
645 switch (layer) {
646 case 0:
647 case 1:
648 case 2:
649 case 3:
650 m_threadContext.gba->video.renderer->disableBG[layer] = !enable;
651 break;
652 case 4:
653 m_threadContext.gba->video.renderer->disableOBJ = !enable;
654 break;
655 }
656 }
657}
658
659void GameController::setFPSTarget(float fps) {
660 threadInterrupt();
661 m_fpsTarget = fps;
662 m_threadContext.fpsTarget = fps;
663 if (m_turbo && m_turboSpeed > 0) {
664 m_threadContext.fpsTarget *= m_turboSpeed;
665 }
666 if (m_audioProcessor) {
667 redoSamples(m_audioProcessor->getBufferSamples());
668 }
669 threadContinue();
670}
671
672void GameController::setSkipBIOS(bool set) {
673 threadInterrupt();
674 m_threadContext.skipBios = set;
675 threadContinue();
676}
677
678void GameController::setUseBIOS(bool use) {
679 if (use == m_useBios) {
680 return;
681 }
682 m_useBios = use;
683 if (m_gameOpen) {
684 closeGame();
685 openGame();
686 }
687}
688
689void GameController::loadState(int slot) {
690 if (slot > 0 && slot != m_stateSlot) {
691 m_stateSlot = slot;
692 m_backupSaveState.clear();
693 }
694 GBARunOnThread(&m_threadContext, [](GBAThread* context) {
695 GameController* controller = static_cast<GameController*>(context->userData);
696 if (!controller->m_backupLoadState) {
697 controller->m_backupLoadState = new GBASerializedState;
698 }
699 GBASerialize(context->gba, controller->m_backupLoadState);
700 if (GBALoadState(context, context->stateDir, controller->m_stateSlot)) {
701 controller->frameAvailable(controller->m_drawContext);
702 controller->stateLoaded(context);
703 }
704 });
705}
706
707void GameController::saveState(int slot) {
708 if (slot > 0) {
709 m_stateSlot = slot;
710 }
711 GBARunOnThread(&m_threadContext, [](GBAThread* context) {
712 GameController* controller = static_cast<GameController*>(context->userData);
713 VFile* vf = GBAGetState(context->gba, context->stateDir, controller->m_stateSlot, false);
714 if (vf) {
715 controller->m_backupSaveState.resize(vf->size(vf));
716 vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
717 vf->close(vf);
718 }
719 GBASaveState(context, context->stateDir, controller->m_stateSlot, true);
720 });
721}
722
723void GameController::loadBackupState() {
724 if (!m_backupLoadState) {
725 return;
726 }
727
728 GBARunOnThread(&m_threadContext, [](GBAThread* context) {
729 GameController* controller = static_cast<GameController*>(context->userData);
730 if (GBADeserialize(context->gba, controller->m_backupLoadState)) {
731 GBALog(context->gba, GBA_LOG_STATUS, "Undid state load");
732 controller->frameAvailable(controller->m_drawContext);
733 controller->stateLoaded(context);
734 }
735 delete controller->m_backupLoadState;
736 controller->m_backupLoadState = nullptr;
737 });
738}
739
740void GameController::saveBackupState() {
741 if (m_backupSaveState.isEmpty()) {
742 return;
743 }
744
745 GBARunOnThread(&m_threadContext, [](GBAThread* context) {
746 GameController* controller = static_cast<GameController*>(context->userData);
747 VFile* vf = GBAGetState(context->gba, context->stateDir, controller->m_stateSlot, true);
748 if (vf) {
749 vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
750 vf->close(vf);
751 GBALog(context->gba, GBA_LOG_STATUS, "Undid state save");
752 }
753 controller->m_backupSaveState.clear();
754 });
755}
756
757void GameController::setVideoSync(bool set) {
758 m_videoSync = set;
759 if (!m_turbo) {
760 threadInterrupt();
761 m_threadContext.sync.videoFrameWait = set;
762 threadContinue();
763 }
764}
765
766void GameController::setAudioSync(bool set) {
767 m_audioSync = set;
768 if (!m_turbo) {
769 threadInterrupt();
770 m_threadContext.sync.audioWait = set;
771 threadContinue();
772 }
773}
774
775void GameController::setFrameskip(int skip) {
776 m_threadContext.frameskip = skip;
777}
778
779void GameController::setVolume(int volume) {
780 threadInterrupt();
781 m_threadContext.volume = volume;
782 if (m_gameOpen) {
783 m_threadContext.gba->audio.masterVolume = volume;
784 }
785 threadContinue();
786}
787
788void GameController::setMute(bool mute) {
789 threadInterrupt();
790 m_threadContext.mute = mute;
791 if (m_gameOpen) {
792 m_threadContext.gba->audio.masterVolume = mute ? 0 : m_threadContext.volume;
793 }
794 threadContinue();
795}
796
797void GameController::setTurbo(bool set, bool forced) {
798 if (m_turboForced && !forced) {
799 return;
800 }
801 if (m_turbo == set && m_turboForced == forced) {
802 // Don't interrupt the thread if we don't need to
803 return;
804 }
805 m_turbo = set;
806 m_turboForced = set && forced;
807 enableTurbo();
808}
809
810void GameController::setTurboSpeed(float ratio) {
811 m_turboSpeed = ratio;
812 enableTurbo();
813}
814
815void GameController::enableTurbo() {
816 threadInterrupt();
817 if (!m_turbo) {
818 m_threadContext.fpsTarget = m_fpsTarget;
819 m_threadContext.sync.audioWait = m_audioSync;
820 m_threadContext.sync.videoFrameWait = m_videoSync;
821 } else if (m_turboSpeed <= 0) {
822 m_threadContext.fpsTarget = m_fpsTarget;
823 m_threadContext.sync.audioWait = false;
824 m_threadContext.sync.videoFrameWait = false;
825 } else {
826 m_threadContext.fpsTarget = m_fpsTarget * m_turboSpeed;
827 m_threadContext.sync.audioWait = true;
828 m_threadContext.sync.videoFrameWait = false;
829 }
830 if (m_audioProcessor) {
831 redoSamples(m_audioProcessor->getBufferSamples());
832 }
833 threadContinue();
834}
835
836void GameController::setAVStream(GBAAVStream* stream) {
837 threadInterrupt();
838 m_threadContext.stream = stream;
839 if (m_gameOpen) {
840 m_threadContext.gba->stream = stream;
841 }
842 threadContinue();
843}
844
845void GameController::clearAVStream() {
846 threadInterrupt();
847 m_threadContext.stream = nullptr;
848 if (m_gameOpen) {
849 m_threadContext.gba->stream = nullptr;
850 }
851 threadContinue();
852}
853
854#ifdef USE_PNG
855void GameController::screenshot() {
856 GBARunOnThread(&m_threadContext, GBAThreadTakeScreenshot);
857}
858#endif
859
860void GameController::reloadAudioDriver() {
861 int samples = 0;
862 unsigned sampleRate = 0;
863 if (m_audioProcessor) {
864 QMetaObject::invokeMethod(m_audioProcessor, "pause", Qt::BlockingQueuedConnection);
865 samples = m_audioProcessor->getBufferSamples();
866 sampleRate = m_audioProcessor->sampleRate();
867 delete m_audioProcessor;
868 }
869 m_audioProcessor = AudioProcessor::create();
870 if (samples) {
871 m_audioProcessor->setBufferSamples(samples);
872 }
873 if (sampleRate) {
874 m_audioProcessor->requestSampleRate(sampleRate);
875 }
876 m_audioProcessor->moveToThread(m_audioThread);
877 connect(this, SIGNAL(gameStarted(GBAThread*)), m_audioProcessor, SLOT(start()));
878 connect(this, SIGNAL(gameStopped(GBAThread*)), m_audioProcessor, SLOT(pause()));
879 connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
880 connect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));
881 if (isLoaded()) {
882 m_audioProcessor->setInput(&m_threadContext);
883 QMetaObject::invokeMethod(m_audioProcessor, "start");
884 }
885}
886
887void GameController::setLuminanceValue(uint8_t value) {
888 m_luxValue = value;
889 value = std::max<int>(value - 0x16, 0);
890 m_luxLevel = 10;
891 for (int i = 0; i < 10; ++i) {
892 if (value < GBA_LUX_LEVELS[i]) {
893 m_luxLevel = i;
894 break;
895 }
896 }
897 emit luminanceValueChanged(m_luxValue);
898}
899
900void GameController::setLuminanceLevel(int level) {
901 int value = 0x16;
902 level = std::max(0, std::min(10, level));
903 if (level > 0) {
904 value += GBA_LUX_LEVELS[level - 1];
905 }
906 setLuminanceValue(value);
907}
908
909void GameController::setRealTime() {
910 m_rtc.override = GBARTCGenericSource::RTC_NO_OVERRIDE;
911}
912
913void GameController::setFixedTime(const QDateTime& time) {
914 m_rtc.override = GBARTCGenericSource::RTC_FIXED;
915 m_rtc.value = time.toMSecsSinceEpoch() / 1000;
916}
917
918void GameController::setFakeEpoch(const QDateTime& time) {
919 m_rtc.override = GBARTCGenericSource::RTC_FAKE_EPOCH;
920 m_rtc.value = time.toMSecsSinceEpoch() / 1000;
921}
922
923void GameController::updateKeys() {
924 int activeKeys = m_activeKeys;
925 activeKeys |= m_activeButtons;
926 activeKeys &= ~m_inactiveKeys;
927 m_threadContext.activeKeys = activeKeys;
928}
929
930void GameController::redoSamples(int samples) {
931#if RESAMPLE_LIBRARY != RESAMPLE_BLIP_BUF
932 float sampleRate = 0x8000;
933 float ratio;
934 if (m_threadContext.gba) {
935 sampleRate = m_threadContext.gba->audio.sampleRate;
936 }
937 ratio = GBAAudioCalculateRatio(sampleRate, m_threadContext.fpsTarget, m_audioProcess->sampleRate());
938 m_threadContext.audioBuffers = ceil(samples / ratio);
939#else
940 m_threadContext.audioBuffers = samples;
941#endif
942 if (m_threadContext.gba) {
943 GBAAudioResizeBuffer(&m_threadContext.gba->audio, m_threadContext.audioBuffers);
944 }
945 QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
946}
947
948void GameController::setLogLevel(int levels) {
949 threadInterrupt();
950 m_logLevels = levels;
951 threadContinue();
952}
953
954void GameController::enableLogLevel(int levels) {
955 threadInterrupt();
956 m_logLevels |= levels;
957 threadContinue();
958}
959
960void GameController::disableLogLevel(int levels) {
961 threadInterrupt();
962 m_logLevels &= ~levels;
963 threadContinue();
964}
965
966void GameController::pollEvents() {
967 if (!m_inputController) {
968 return;
969 }
970
971 m_activeButtons = m_inputController->pollEvents();
972 updateKeys();
973}