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_autofire{}
54 , m_autofireStatus{}
55 , m_inputController(nullptr)
56 , m_multiplayer(nullptr)
57 , m_stateSlot(1)
58 , m_backupLoadState(nullptr)
59 , m_backupSaveState(nullptr)
60{
61 m_renderer = new GBAVideoSoftwareRenderer;
62 GBAVideoSoftwareRendererCreate(m_renderer);
63 m_renderer->outputBuffer = (color_t*) m_drawContext;
64 m_renderer->outputBufferStride = 256;
65
66 GBACheatDeviceCreate(&m_cheatDevice);
67
68 m_threadContext.state = THREAD_INITIALIZED;
69 m_threadContext.debugger = 0;
70 m_threadContext.frameskip = 0;
71 m_threadContext.bios = 0;
72 m_threadContext.renderer = &m_renderer->d;
73 m_threadContext.userData = this;
74 m_threadContext.rewindBufferCapacity = 0;
75 m_threadContext.cheats = &m_cheatDevice;
76 m_threadContext.logLevel = GBA_LOG_ALL;
77
78 m_lux.p = this;
79 m_lux.sample = [](GBALuminanceSource* context) {
80 GameControllerLux* lux = static_cast<GameControllerLux*>(context);
81 lux->value = 0xFF - lux->p->m_luxValue;
82 };
83
84 m_lux.readLuminance = [](GBALuminanceSource* context) {
85 GameControllerLux* lux = static_cast<GameControllerLux*>(context);
86 return lux->value;
87 };
88 setLuminanceLevel(0);
89
90 m_threadContext.startCallback = [](GBAThread* context) {
91 GameController* controller = static_cast<GameController*>(context->userData);
92 if (controller->m_audioProcessor) {
93 controller->m_audioProcessor->setInput(context);
94 }
95 context->gba->luminanceSource = &controller->m_lux;
96 GBARTCGenericSourceInit(&controller->m_rtc, context->gba);
97 context->gba->rtcSource = &controller->m_rtc.d;
98 context->gba->rumble = controller->m_inputController->rumble();
99 context->gba->rotationSource = controller->m_inputController->rotationSource();
100 context->gba->audio.forceDisableCh[0] = !controller->m_audioChannels[0];
101 context->gba->audio.forceDisableCh[1] = !controller->m_audioChannels[1];
102 context->gba->audio.forceDisableCh[2] = !controller->m_audioChannels[2];
103 context->gba->audio.forceDisableCh[3] = !controller->m_audioChannels[3];
104 context->gba->audio.forceDisableChA = !controller->m_audioChannels[4];
105 context->gba->audio.forceDisableChB = !controller->m_audioChannels[5];
106 context->gba->video.renderer->disableBG[0] = !controller->m_videoLayers[0];
107 context->gba->video.renderer->disableBG[1] = !controller->m_videoLayers[1];
108 context->gba->video.renderer->disableBG[2] = !controller->m_videoLayers[2];
109 context->gba->video.renderer->disableBG[3] = !controller->m_videoLayers[3];
110 context->gba->video.renderer->disableOBJ = !controller->m_videoLayers[4];
111 controller->m_fpsTarget = context->fpsTarget;
112
113 if (context->dirs.state && GBALoadState(context, context->dirs.state, 0, SAVESTATE_SCREENSHOT)) {
114 VFile* vf = GBAGetState(context->gba, context->dirs.state, 0, true);
115 if (vf) {
116 vf->truncate(vf, 0);
117 }
118 }
119 QMetaObject::invokeMethod(controller, "gameStarted", Q_ARG(GBAThread*, context));
120 };
121
122 m_threadContext.cleanCallback = [](GBAThread* context) {
123 GameController* controller = static_cast<GameController*>(context->userData);
124 QMetaObject::invokeMethod(controller, "gameStopped", Q_ARG(GBAThread*, context));
125 };
126
127 m_threadContext.frameCallback = [](GBAThread* context) {
128 GameController* controller = static_cast<GameController*>(context->userData);
129 memcpy(controller->m_frontBuffer, controller->m_drawContext, 256 * VIDEO_HORIZONTAL_PIXELS * BYTES_PER_PIXEL);
130 QMetaObject::invokeMethod(controller, "frameAvailable", Q_ARG(const uint32_t*, controller->m_frontBuffer));
131 if (controller->m_pauseAfterFrame.testAndSetAcquire(true, false)) {
132 GBAThreadPauseFromThread(context);
133 QMetaObject::invokeMethod(controller, "gamePaused", Q_ARG(GBAThread*, context));
134 }
135 };
136
137 m_threadContext.stopCallback = [](GBAThread* context) {
138 if (!context) {
139 return false;
140 }
141 GameController* controller = static_cast<GameController*>(context->userData);
142 if (!GBASaveState(context, context->dirs.state, 0, true)) {
143 return false;
144 }
145 QMetaObject::invokeMethod(controller, "closeGame");
146 return true;
147 };
148
149 m_threadContext.logHandler = [](GBAThread* context, enum GBALogLevel level, const char* format, va_list args) {
150 static const char* stubMessage = "Stub software interrupt: %02X";
151 static const char* savestateMessage = "State %i loaded";
152 static const char* savestateFailedMessage = "State %i failed to load";
153 if (!context) {
154 return;
155 }
156 GameController* controller = static_cast<GameController*>(context->userData);
157 if (level == GBA_LOG_STUB && strncmp(stubMessage, format, strlen(stubMessage)) == 0) {
158 va_list argc;
159 va_copy(argc, args);
160 int immediate = va_arg(argc, int);
161 va_end(argc);
162 QMetaObject::invokeMethod(controller, "unimplementedBiosCall", Q_ARG(int, immediate));
163 } else if (level == GBA_LOG_STATUS) {
164 // Slot 0 is reserved for suspend points
165 if (strncmp(savestateMessage, format, strlen(savestateMessage)) == 0) {
166 va_list argc;
167 va_copy(argc, args);
168 int slot = va_arg(argc, int);
169 va_end(argc);
170 if (slot == 0) {
171 format = "Loaded suspend state";
172 }
173 } else if (strncmp(savestateFailedMessage, format, strlen(savestateFailedMessage)) == 0) {
174 va_list argc;
175 va_copy(argc, args);
176 int slot = va_arg(argc, int);
177 va_end(argc);
178 if (slot == 0) {
179 return;
180 }
181 }
182 }
183 if (level == GBA_LOG_FATAL) {
184 QMetaObject::invokeMethod(controller, "crashGame", Q_ARG(const QString&, QString().vsprintf(format, args)));
185 } else if (!(controller->m_logLevels & level)) {
186 return;
187 }
188 QString message(QString().vsprintf(format, args));
189 if (level == GBA_LOG_STATUS) {
190 QMetaObject::invokeMethod(controller, "statusPosted", Q_ARG(const QString&, message));
191 }
192 QMetaObject::invokeMethod(controller, "postLog", Q_ARG(int, level), Q_ARG(const QString&, message));
193 };
194
195 connect(&m_rewindTimer, &QTimer::timeout, [this]() {
196 GBARewind(&m_threadContext, 1);
197 emit frameAvailable(m_drawContext);
198 emit rewound(&m_threadContext);
199 });
200 m_rewindTimer.setInterval(100);
201
202 m_audioThread->setObjectName("Audio Thread");
203 m_audioThread->start(QThread::TimeCriticalPriority);
204 m_audioProcessor->moveToThread(m_audioThread);
205 connect(this, SIGNAL(gameStarted(GBAThread*)), m_audioProcessor, SLOT(start()));
206 connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
207 connect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));
208 connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(pollEvents()));
209 connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(updateAutofire()));
210}
211
212GameController::~GameController() {
213 m_audioThread->quit();
214 m_audioThread->wait();
215 disconnect();
216 clearMultiplayerController();
217 closeGame();
218 GBACheatDeviceDestroy(&m_cheatDevice);
219 delete m_renderer;
220 delete[] m_drawContext;
221 delete[] m_frontBuffer;
222 delete m_backupLoadState;
223}
224
225void GameController::setMultiplayerController(MultiplayerController* controller) {
226 if (controller == m_multiplayer) {
227 return;
228 }
229 clearMultiplayerController();
230 m_multiplayer = controller;
231 controller->attachGame(this);
232}
233
234void GameController::clearMultiplayerController() {
235 if (!m_multiplayer) {
236 return;
237 }
238 m_multiplayer->detachGame(this);
239 m_multiplayer = nullptr;
240}
241
242void GameController::setOverride(const GBACartridgeOverride& override) {
243 m_threadContext.override = override;
244 m_threadContext.hasOverride = true;
245}
246
247void GameController::setOptions(const GBAOptions* opts) {
248 setFrameskip(opts->frameskip);
249 setAudioSync(opts->audioSync);
250 setVideoSync(opts->videoSync);
251 setSkipBIOS(opts->skipBios);
252 setUseBIOS(opts->useBios);
253 setRewind(opts->rewindEnable, opts->rewindBufferCapacity, opts->rewindBufferInterval);
254 setVolume(opts->volume);
255 setMute(opts->mute);
256
257 threadInterrupt();
258 m_threadContext.idleOptimization = opts->idleOptimization;
259 threadContinue();
260}
261
262#ifdef USE_GDB_STUB
263ARMDebugger* GameController::debugger() {
264 return m_threadContext.debugger;
265}
266
267void GameController::setDebugger(ARMDebugger* debugger) {
268 threadInterrupt();
269 if (m_threadContext.debugger && GBAThreadIsActive(&m_threadContext)) {
270 GBADetachDebugger(m_threadContext.gba);
271 }
272 m_threadContext.debugger = debugger;
273 if (m_threadContext.debugger && GBAThreadIsActive(&m_threadContext)) {
274 GBAAttachDebugger(m_threadContext.gba, m_threadContext.debugger);
275 }
276 threadContinue();
277}
278#endif
279
280void GameController::loadGame(const QString& path, bool dirmode) {
281 closeGame();
282 if (!dirmode) {
283 QFile file(path);
284 if (!file.open(QIODevice::ReadOnly)) {
285 postLog(GBA_LOG_ERROR, tr("Failed to open game file: %1").arg(path));
286 return;
287 }
288 file.close();
289 }
290
291 m_fname = path;
292 m_dirmode = dirmode;
293 openGame();
294}
295
296void GameController::bootBIOS() {
297 closeGame();
298 m_fname = QString();
299 m_dirmode = false;
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, 1024 * VIDEO_HORIZONTAL_PIXELS);
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}