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 m_wasPaused = isPaused();
538 if (!GBAThreadIsPaused(&m_threadContext)) {
539 GBAThreadPause(&m_threadContext);
540 }
541 m_rewindTimer.start();
542}
543
544void GameController::stopRewinding() {
545 if (!m_rewindTimer.isActive()) {
546 return;
547 }
548 m_rewindTimer.stop();
549 bool signalsBlocked = blockSignals(true);
550 setPaused(m_wasPaused);
551 blockSignals(signalsBlocked);
552}
553
554void GameController::keyPressed(int key) {
555 int mappedKey = 1 << key;
556 m_activeKeys |= mappedKey;
557 if (!m_inputController->allowOpposing()) {
558 if ((m_activeKeys & 0x30) == 0x30) {
559 m_inactiveKeys |= mappedKey ^ 0x30;
560 m_activeKeys ^= mappedKey ^ 0x30;
561 }
562 if ((m_activeKeys & 0xC0) == 0xC0) {
563 m_inactiveKeys |= mappedKey ^ 0xC0;
564 m_activeKeys ^= mappedKey ^ 0xC0;
565 }
566 }
567 updateKeys();
568}
569
570void GameController::keyReleased(int key) {
571 int mappedKey = 1 << key;
572 m_activeKeys &= ~mappedKey;
573 if (!m_inputController->allowOpposing()) {
574 if (mappedKey & 0x30) {
575 m_activeKeys |= m_inactiveKeys & (0x30 ^ mappedKey);
576 m_inactiveKeys &= ~0x30;
577 }
578 if (mappedKey & 0xC0) {
579 m_activeKeys |= m_inactiveKeys & (0xC0 ^ mappedKey);
580 m_inactiveKeys &= ~0xC0;
581 }
582 }
583 updateKeys();
584}
585
586void GameController::clearKeys() {
587 m_activeKeys = 0;
588 m_inactiveKeys = 0;
589 updateKeys();
590}
591
592void GameController::setAudioBufferSamples(int samples) {
593 if (m_audioProcessor) {
594 threadInterrupt();
595 redoSamples(samples);
596 threadContinue();
597 QMetaObject::invokeMethod(m_audioProcessor, "setBufferSamples", Q_ARG(int, samples));
598 }
599}
600
601void GameController::setAudioSampleRate(unsigned rate) {
602 if (!rate) {
603 return;
604 }
605 if (m_audioProcessor) {
606 threadInterrupt();
607 redoSamples(m_audioProcessor->getBufferSamples());
608 threadContinue();
609 QMetaObject::invokeMethod(m_audioProcessor, "requestSampleRate", Q_ARG(unsigned, rate));
610 }
611}
612
613void GameController::setAudioChannelEnabled(int channel, bool enable) {
614 if (channel > 5 || channel < 0) {
615 return;
616 }
617 m_audioChannels[channel] = enable;
618 if (m_gameOpen) {
619 switch (channel) {
620 case 0:
621 case 1:
622 case 2:
623 case 3:
624 m_threadContext.gba->audio.forceDisableCh[channel] = !enable;
625 break;
626 case 4:
627 m_threadContext.gba->audio.forceDisableChA = !enable;
628 break;
629 case 5:
630 m_threadContext.gba->audio.forceDisableChB = !enable;
631 break;
632 }
633 }
634}
635
636void GameController::setVideoLayerEnabled(int layer, bool enable) {
637 if (layer > 4 || layer < 0) {
638 return;
639 }
640 m_videoLayers[layer] = enable;
641 if (m_gameOpen) {
642 switch (layer) {
643 case 0:
644 case 1:
645 case 2:
646 case 3:
647 m_threadContext.gba->video.renderer->disableBG[layer] = !enable;
648 break;
649 case 4:
650 m_threadContext.gba->video.renderer->disableOBJ = !enable;
651 break;
652 }
653 }
654}
655
656void GameController::setFPSTarget(float fps) {
657 threadInterrupt();
658 m_fpsTarget = fps;
659 m_threadContext.fpsTarget = fps;
660 if (m_turbo && m_turboSpeed > 0) {
661 m_threadContext.fpsTarget *= m_turboSpeed;
662 }
663 if (m_audioProcessor) {
664 redoSamples(m_audioProcessor->getBufferSamples());
665 }
666 threadContinue();
667}
668
669void GameController::setSkipBIOS(bool set) {
670 threadInterrupt();
671 m_threadContext.skipBios = set;
672 threadContinue();
673}
674
675void GameController::setUseBIOS(bool use) {
676 if (use == m_useBios) {
677 return;
678 }
679 m_useBios = use;
680 if (m_gameOpen) {
681 closeGame();
682 openGame();
683 }
684}
685
686void GameController::loadState(int slot) {
687 if (slot > 0 && slot != m_stateSlot) {
688 m_stateSlot = slot;
689 m_backupSaveState.clear();
690 }
691 GBARunOnThread(&m_threadContext, [](GBAThread* context) {
692 GameController* controller = static_cast<GameController*>(context->userData);
693 if (!controller->m_backupLoadState) {
694 controller->m_backupLoadState = new GBASerializedState;
695 }
696 GBASerialize(context->gba, controller->m_backupLoadState);
697 if (GBALoadState(context, context->stateDir, controller->m_stateSlot)) {
698 controller->frameAvailable(controller->m_drawContext);
699 controller->stateLoaded(context);
700 }
701 });
702}
703
704void GameController::saveState(int slot) {
705 if (slot > 0) {
706 m_stateSlot = slot;
707 }
708 GBARunOnThread(&m_threadContext, [](GBAThread* context) {
709 GameController* controller = static_cast<GameController*>(context->userData);
710 VFile* vf = GBAGetState(context->gba, context->stateDir, controller->m_stateSlot, false);
711 if (vf) {
712 controller->m_backupSaveState.resize(vf->size(vf));
713 vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
714 vf->close(vf);
715 }
716 GBASaveState(context, context->stateDir, controller->m_stateSlot, true);
717 });
718}
719
720void GameController::loadBackupState() {
721 if (!m_backupLoadState) {
722 return;
723 }
724
725 GBARunOnThread(&m_threadContext, [](GBAThread* context) {
726 GameController* controller = static_cast<GameController*>(context->userData);
727 if (GBADeserialize(context->gba, controller->m_backupLoadState)) {
728 GBALog(context->gba, GBA_LOG_STATUS, "Undid state load");
729 controller->frameAvailable(controller->m_drawContext);
730 controller->stateLoaded(context);
731 }
732 delete controller->m_backupLoadState;
733 controller->m_backupLoadState = nullptr;
734 });
735}
736
737void GameController::saveBackupState() {
738 if (m_backupSaveState.isEmpty()) {
739 return;
740 }
741
742 GBARunOnThread(&m_threadContext, [](GBAThread* context) {
743 GameController* controller = static_cast<GameController*>(context->userData);
744 VFile* vf = GBAGetState(context->gba, context->stateDir, controller->m_stateSlot, true);
745 if (vf) {
746 vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
747 vf->close(vf);
748 GBALog(context->gba, GBA_LOG_STATUS, "Undid state save");
749 }
750 controller->m_backupSaveState.clear();
751 });
752}
753
754void GameController::setVideoSync(bool set) {
755 m_videoSync = set;
756 if (!m_turbo) {
757 threadInterrupt();
758 m_threadContext.sync.videoFrameWait = set;
759 threadContinue();
760 }
761}
762
763void GameController::setAudioSync(bool set) {
764 m_audioSync = set;
765 if (!m_turbo) {
766 threadInterrupt();
767 m_threadContext.sync.audioWait = set;
768 threadContinue();
769 }
770}
771
772void GameController::setFrameskip(int skip) {
773 m_threadContext.frameskip = skip;
774}
775
776void GameController::setVolume(int volume) {
777 threadInterrupt();
778 m_threadContext.volume = volume;
779 if (m_gameOpen) {
780 m_threadContext.gba->audio.masterVolume = volume;
781 }
782 threadContinue();
783}
784
785void GameController::setMute(bool mute) {
786 threadInterrupt();
787 m_threadContext.mute = mute;
788 if (m_gameOpen) {
789 m_threadContext.gba->audio.masterVolume = mute ? 0 : m_threadContext.volume;
790 }
791 threadContinue();
792}
793
794void GameController::setTurbo(bool set, bool forced) {
795 if (m_turboForced && !forced) {
796 return;
797 }
798 if (m_turbo == set && m_turboForced == forced) {
799 // Don't interrupt the thread if we don't need to
800 return;
801 }
802 m_turbo = set;
803 m_turboForced = set && forced;
804 enableTurbo();
805}
806
807void GameController::setTurboSpeed(float ratio) {
808 m_turboSpeed = ratio;
809 enableTurbo();
810}
811
812void GameController::enableTurbo() {
813 threadInterrupt();
814 if (!m_turbo) {
815 m_threadContext.fpsTarget = m_fpsTarget;
816 m_threadContext.sync.audioWait = m_audioSync;
817 m_threadContext.sync.videoFrameWait = m_videoSync;
818 } else if (m_turboSpeed <= 0) {
819 m_threadContext.fpsTarget = m_fpsTarget;
820 m_threadContext.sync.audioWait = false;
821 m_threadContext.sync.videoFrameWait = false;
822 } else {
823 m_threadContext.fpsTarget = m_fpsTarget * m_turboSpeed;
824 m_threadContext.sync.audioWait = true;
825 m_threadContext.sync.videoFrameWait = false;
826 }
827 if (m_audioProcessor) {
828 redoSamples(m_audioProcessor->getBufferSamples());
829 }
830 threadContinue();
831}
832
833void GameController::setAVStream(GBAAVStream* stream) {
834 threadInterrupt();
835 m_threadContext.stream = stream;
836 if (m_gameOpen) {
837 m_threadContext.gba->stream = stream;
838 }
839 threadContinue();
840}
841
842void GameController::clearAVStream() {
843 threadInterrupt();
844 m_threadContext.stream = nullptr;
845 if (m_gameOpen) {
846 m_threadContext.gba->stream = nullptr;
847 }
848 threadContinue();
849}
850
851#ifdef USE_PNG
852void GameController::screenshot() {
853 GBARunOnThread(&m_threadContext, GBAThreadTakeScreenshot);
854}
855#endif
856
857void GameController::reloadAudioDriver() {
858 int samples = 0;
859 unsigned sampleRate = 0;
860 if (m_audioProcessor) {
861 QMetaObject::invokeMethod(m_audioProcessor, "pause", Qt::BlockingQueuedConnection);
862 samples = m_audioProcessor->getBufferSamples();
863 sampleRate = m_audioProcessor->sampleRate();
864 delete m_audioProcessor;
865 }
866 m_audioProcessor = AudioProcessor::create();
867 if (samples) {
868 m_audioProcessor->setBufferSamples(samples);
869 }
870 if (sampleRate) {
871 m_audioProcessor->requestSampleRate(sampleRate);
872 }
873 m_audioProcessor->moveToThread(m_audioThread);
874 connect(this, SIGNAL(gameStarted(GBAThread*)), m_audioProcessor, SLOT(start()));
875 connect(this, SIGNAL(gameStopped(GBAThread*)), m_audioProcessor, SLOT(pause()));
876 connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
877 connect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));
878 if (isLoaded()) {
879 m_audioProcessor->setInput(&m_threadContext);
880 QMetaObject::invokeMethod(m_audioProcessor, "start");
881 }
882}
883
884void GameController::setLuminanceValue(uint8_t value) {
885 m_luxValue = value;
886 value = std::max<int>(value - 0x16, 0);
887 m_luxLevel = 10;
888 for (int i = 0; i < 10; ++i) {
889 if (value < GBA_LUX_LEVELS[i]) {
890 m_luxLevel = i;
891 break;
892 }
893 }
894 emit luminanceValueChanged(m_luxValue);
895}
896
897void GameController::setLuminanceLevel(int level) {
898 int value = 0x16;
899 level = std::max(0, std::min(10, level));
900 if (level > 0) {
901 value += GBA_LUX_LEVELS[level - 1];
902 }
903 setLuminanceValue(value);
904}
905
906void GameController::setRealTime() {
907 m_rtc.override = GBARTCGenericSource::RTC_NO_OVERRIDE;
908}
909
910void GameController::setFixedTime(const QDateTime& time) {
911 m_rtc.override = GBARTCGenericSource::RTC_FIXED;
912 m_rtc.value = time.toMSecsSinceEpoch() / 1000;
913}
914
915void GameController::setFakeEpoch(const QDateTime& time) {
916 m_rtc.override = GBARTCGenericSource::RTC_FAKE_EPOCH;
917 m_rtc.value = time.toMSecsSinceEpoch() / 1000;
918}
919
920void GameController::updateKeys() {
921 int activeKeys = m_activeKeys;
922 activeKeys |= m_activeButtons;
923 activeKeys &= ~m_inactiveKeys;
924 m_threadContext.activeKeys = activeKeys;
925}
926
927void GameController::redoSamples(int samples) {
928#if RESAMPLE_LIBRARY != RESAMPLE_BLIP_BUF
929 float sampleRate = 0x8000;
930 float ratio;
931 if (m_threadContext.gba) {
932 sampleRate = m_threadContext.gba->audio.sampleRate;
933 }
934 ratio = GBAAudioCalculateRatio(sampleRate, m_threadContext.fpsTarget, m_audioProcess->sampleRate());
935 m_threadContext.audioBuffers = ceil(samples / ratio);
936#else
937 m_threadContext.audioBuffers = samples;
938#endif
939 if (m_threadContext.gba) {
940 GBAAudioResizeBuffer(&m_threadContext.gba->audio, m_threadContext.audioBuffers);
941 }
942 QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
943}
944
945void GameController::setLogLevel(int levels) {
946 threadInterrupt();
947 m_logLevels = levels;
948 threadContinue();
949}
950
951void GameController::enableLogLevel(int levels) {
952 threadInterrupt();
953 m_logLevels |= levels;
954 threadContinue();
955}
956
957void GameController::disableLogLevel(int levels) {
958 threadInterrupt();
959 m_logLevels &= ~levels;
960 threadContinue();
961}
962
963void GameController::pollEvents() {
964 if (!m_inputController) {
965 return;
966 }
967
968 m_activeButtons = m_inputController->pollEvents();
969 updateKeys();
970}