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 memcpy(controller->m_frontBuffer, controller->m_drawContext, 256 * VIDEO_HORIZONTAL_PIXELS * BYTES_PER_PIXEL);
128 QMetaObject::invokeMethod(controller, "frameAvailable", Q_ARG(const uint32_t*, controller->m_frontBuffer));
129 if (controller->m_pauseAfterFrame.testAndSetAcquire(true, false)) {
130 GBAThreadPauseFromThread(context);
131 QMetaObject::invokeMethod(controller, "gamePaused", Q_ARG(GBAThread*, context));
132 }
133 };
134
135 m_threadContext.stopCallback = [](GBAThread* context) {
136 if (!context) {
137 return false;
138 }
139 GameController* controller = static_cast<GameController*>(context->userData);
140 if (!GBASaveState(context, context->stateDir, 0, true)) {
141 return false;
142 }
143 QMetaObject::invokeMethod(controller, "closeGame");
144 return true;
145 };
146
147 m_threadContext.logHandler = [](GBAThread* context, enum GBALogLevel level, const char* format, va_list args) {
148 static const char* stubMessage = "Stub software interrupt: %02X";
149 static const char* savestateMessage = "State %i loaded";
150 static const char* savestateFailedMessage = "State %i failed to load";
151 if (!context) {
152 return;
153 }
154 GameController* controller = static_cast<GameController*>(context->userData);
155 if (level == GBA_LOG_STUB && strncmp(stubMessage, format, strlen(stubMessage)) == 0) {
156 va_list argc;
157 va_copy(argc, args);
158 int immediate = va_arg(argc, int);
159 va_end(argc);
160 QMetaObject::invokeMethod(controller, "unimplementedBiosCall", Q_ARG(int, immediate));
161 } else if (level == GBA_LOG_STATUS) {
162 // Slot 0 is reserved for suspend points
163 if (strncmp(savestateMessage, format, strlen(savestateMessage)) == 0) {
164 va_list argc;
165 va_copy(argc, args);
166 int slot = va_arg(argc, int);
167 va_end(argc);
168 if (slot == 0) {
169 format = "Loaded suspend state";
170 }
171 } else if (strncmp(savestateFailedMessage, format, strlen(savestateFailedMessage)) == 0) {
172 va_list argc;
173 va_copy(argc, args);
174 int slot = va_arg(argc, int);
175 va_end(argc);
176 if (slot == 0) {
177 return;
178 }
179 }
180 }
181 if (level == GBA_LOG_FATAL) {
182 QMetaObject::invokeMethod(controller, "crashGame", Q_ARG(const QString&, QString().vsprintf(format, args)));
183 } else if (!(controller->m_logLevels & level)) {
184 return;
185 }
186 QString message(QString().vsprintf(format, args));
187 if (level == GBA_LOG_STATUS) {
188 QMetaObject::invokeMethod(controller, "statusPosted", Q_ARG(const QString&, message));
189 }
190 QMetaObject::invokeMethod(controller, "postLog", Q_ARG(int, level), Q_ARG(const QString&, message));
191 };
192
193 connect(&m_rewindTimer, &QTimer::timeout, [this]() {
194 GBARewind(&m_threadContext, 1);
195 emit frameAvailable(m_drawContext);
196 emit rewound(&m_threadContext);
197 });
198 m_rewindTimer.setInterval(100);
199
200 m_audioThread->setObjectName("Audio Thread");
201 m_audioThread->start(QThread::TimeCriticalPriority);
202 m_audioProcessor->moveToThread(m_audioThread);
203 connect(this, SIGNAL(gameStarted(GBAThread*)), m_audioProcessor, SLOT(start()));
204 connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
205 connect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));
206 connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(pollEvents()));
207}
208
209GameController::~GameController() {
210 m_audioThread->quit();
211 m_audioThread->wait();
212 disconnect();
213 clearMultiplayerController();
214 closeGame();
215 GBACheatDeviceDestroy(&m_cheatDevice);
216 delete m_renderer;
217 delete[] m_drawContext;
218 delete[] m_frontBuffer;
219 delete m_backupLoadState;
220}
221
222void GameController::setMultiplayerController(MultiplayerController* controller) {
223 if (controller == m_multiplayer) {
224 return;
225 }
226 clearMultiplayerController();
227 m_multiplayer = controller;
228 controller->attachGame(this);
229}
230
231void GameController::clearMultiplayerController() {
232 if (!m_multiplayer) {
233 return;
234 }
235 m_multiplayer->detachGame(this);
236 m_multiplayer = nullptr;
237}
238
239void GameController::setOverride(const GBACartridgeOverride& override) {
240 m_threadContext.override = override;
241 m_threadContext.hasOverride = true;
242}
243
244void GameController::setOptions(const GBAOptions* opts) {
245 setFrameskip(opts->frameskip);
246 setAudioSync(opts->audioSync);
247 setVideoSync(opts->videoSync);
248 setSkipBIOS(opts->skipBios);
249 setUseBIOS(opts->useBios);
250 setRewind(opts->rewindEnable, opts->rewindBufferCapacity, opts->rewindBufferInterval);
251 setVolume(opts->volume);
252 setMute(opts->mute);
253
254 threadInterrupt();
255 m_threadContext.idleOptimization = opts->idleOptimization;
256 threadContinue();
257}
258
259#ifdef USE_GDB_STUB
260ARMDebugger* GameController::debugger() {
261 return m_threadContext.debugger;
262}
263
264void GameController::setDebugger(ARMDebugger* debugger) {
265 threadInterrupt();
266 if (m_threadContext.debugger && GBAThreadIsActive(&m_threadContext)) {
267 GBADetachDebugger(m_threadContext.gba);
268 }
269 m_threadContext.debugger = debugger;
270 if (m_threadContext.debugger && GBAThreadIsActive(&m_threadContext)) {
271 GBAAttachDebugger(m_threadContext.gba, m_threadContext.debugger);
272 }
273 threadContinue();
274}
275#endif
276
277void GameController::loadGame(const QString& path, bool dirmode) {
278 closeGame();
279 if (!dirmode) {
280 QFile file(path);
281 if (!file.open(QIODevice::ReadOnly)) {
282 postLog(GBA_LOG_ERROR, tr("Failed to open game file: %1").arg(path));
283 return;
284 }
285 file.close();
286 }
287
288 m_fname = path;
289 m_dirmode = dirmode;
290 openGame();
291}
292
293void GameController::bootBIOS() {
294 closeGame();
295 m_fname = QString();
296 m_dirmode = false;
297 openGame(true);
298}
299
300void GameController::openGame(bool biosOnly) {
301 if (biosOnly && (!m_useBios || m_bios.isNull())) {
302 return;
303 }
304
305 m_gameOpen = true;
306
307 m_pauseAfterFrame = false;
308
309 if (m_turbo) {
310 m_threadContext.sync.videoFrameWait = false;
311 m_threadContext.sync.audioWait = false;
312 } else {
313 m_threadContext.sync.videoFrameWait = m_videoSync;
314 m_threadContext.sync.audioWait = m_audioSync;
315 }
316
317 m_threadContext.gameDir = 0;
318 m_threadContext.bootBios = biosOnly;
319 if (biosOnly) {
320 m_threadContext.fname = nullptr;
321 } else {
322 m_threadContext.fname = strdup(m_fname.toUtf8().constData());
323 if (m_dirmode) {
324 m_threadContext.gameDir = VDirOpen(m_threadContext.fname);
325 m_threadContext.stateDir = m_threadContext.gameDir;
326 } else {
327 GBAThreadLoadROM(&m_threadContext, m_threadContext.fname);
328 }
329 }
330
331 if (!m_bios.isNull() && m_useBios) {
332 m_threadContext.bios = VFileDevice::open(m_bios, O_RDONLY);
333 } else {
334 m_threadContext.bios = nullptr;
335 }
336
337 if (!m_patch.isNull()) {
338 m_threadContext.patch = VFileDevice::open(m_patch, O_RDONLY);
339 }
340
341 m_inputController->recalibrateAxes();
342 memset(m_drawContext, 0xF8, 1024 * VIDEO_HORIZONTAL_PIXELS);
343
344 if (!GBAThreadStart(&m_threadContext)) {
345 m_gameOpen = false;
346 emit gameFailed();
347 }
348}
349
350void GameController::loadBIOS(const QString& path) {
351 if (m_bios == path) {
352 return;
353 }
354 m_bios = path;
355 if (m_gameOpen) {
356 closeGame();
357 openGame();
358 }
359}
360
361void GameController::yankPak() {
362 if (!m_gameOpen) {
363 return;
364 }
365 threadInterrupt();
366 GBAYankROM(m_threadContext.gba);
367 threadContinue();
368}
369
370void GameController::replaceGame(const QString& path) {
371 if (!m_gameOpen) {
372 return;
373 }
374
375 m_fname = path;
376 threadInterrupt();
377 m_threadContext.fname = strdup(m_fname.toLocal8Bit().constData());
378 GBAThreadReplaceROM(&m_threadContext, m_threadContext.fname);
379 threadContinue();
380}
381
382void GameController::loadPatch(const QString& path) {
383 if (m_gameOpen) {
384 closeGame();
385 m_patch = path;
386 openGame();
387 } else {
388 m_patch = path;
389 }
390}
391
392void GameController::importSharkport(const QString& path) {
393 if (!isLoaded()) {
394 return;
395 }
396 VFile* vf = VFileDevice::open(path, O_RDONLY);
397 if (!vf) {
398 postLog(GBA_LOG_ERROR, tr("Failed to open snapshot file for reading: %1").arg(path));
399 return;
400 }
401 threadInterrupt();
402 GBASavedataImportSharkPort(m_threadContext.gba, vf, false);
403 threadContinue();
404 vf->close(vf);
405}
406
407void GameController::exportSharkport(const QString& path) {
408 if (!isLoaded()) {
409 return;
410 }
411 VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
412 if (!vf) {
413 postLog(GBA_LOG_ERROR, tr("Failed to open snapshot file for writing: %1").arg(path));
414 return;
415 }
416 threadInterrupt();
417 GBASavedataExportSharkPort(m_threadContext.gba, vf);
418 threadContinue();
419 vf->close(vf);
420}
421
422void GameController::closeGame() {
423 if (!m_gameOpen) {
424 return;
425 }
426 m_rewindTimer.stop();
427 if (GBAThreadIsPaused(&m_threadContext)) {
428 GBAThreadUnpause(&m_threadContext);
429 }
430 m_audioProcessor->pause();
431 GBAThreadEnd(&m_threadContext);
432 GBAThreadJoin(&m_threadContext);
433 if (m_threadContext.fname) {
434 free(const_cast<char*>(m_threadContext.fname));
435 m_threadContext.fname = nullptr;
436 }
437
438 m_patch = QString();
439
440 for (size_t i = 0; i < GBACheatSetsSize(&m_cheatDevice.cheats); ++i) {
441 GBACheatSet* set = *GBACheatSetsGetPointer(&m_cheatDevice.cheats, i);
442 GBACheatSetDeinit(set);
443 delete set;
444 }
445 GBACheatSetsClear(&m_cheatDevice.cheats);
446
447 m_gameOpen = false;
448 emit gameStopped(&m_threadContext);
449}
450
451void GameController::crashGame(const QString& crashMessage) {
452 closeGame();
453 emit gameCrashed(crashMessage);
454 emit gameStopped(&m_threadContext);
455}
456
457bool GameController::isPaused() {
458 if (!m_gameOpen) {
459 return false;
460 }
461 return GBAThreadIsPaused(&m_threadContext);
462}
463
464void GameController::setPaused(bool paused) {
465 if (!isLoaded() || m_rewindTimer.isActive() || paused == GBAThreadIsPaused(&m_threadContext)) {
466 return;
467 }
468 if (paused) {
469 m_pauseAfterFrame.testAndSetRelaxed(false, true);
470 } else {
471 GBAThreadUnpause(&m_threadContext);
472 emit gameUnpaused(&m_threadContext);
473 }
474}
475
476void GameController::reset() {
477 setPaused(false);
478 GBAThreadReset(&m_threadContext);
479}
480
481void GameController::threadInterrupt() {
482 if (m_gameOpen) {
483 GBAThreadInterrupt(&m_threadContext);
484 }
485}
486
487void GameController::threadContinue() {
488 if (m_gameOpen) {
489 GBAThreadContinue(&m_threadContext);
490 }
491}
492
493void GameController::frameAdvance() {
494 if (m_rewindTimer.isActive()) {
495 return;
496 }
497 if (m_pauseAfterFrame.testAndSetRelaxed(false, true)) {
498 setPaused(false);
499 }
500}
501
502void GameController::setRewind(bool enable, int capacity, int interval) {
503 if (m_gameOpen) {
504 threadInterrupt();
505 GBARewindSettingsChanged(&m_threadContext, enable ? capacity : 0, enable ? interval : 0);
506 threadContinue();
507 } else {
508 if (enable) {
509 m_threadContext.rewindBufferInterval = interval;
510 m_threadContext.rewindBufferCapacity = capacity;
511 } else {
512 m_threadContext.rewindBufferInterval = 0;
513 m_threadContext.rewindBufferCapacity = 0;
514 }
515 }
516}
517
518void GameController::rewind(int states) {
519 threadInterrupt();
520 if (!states) {
521 GBARewindAll(&m_threadContext);
522 } else {
523 GBARewind(&m_threadContext, states);
524 }
525 threadContinue();
526 emit frameAvailable(m_drawContext);
527 emit rewound(&m_threadContext);
528}
529
530void GameController::startRewinding() {
531 if (!m_gameOpen || m_rewindTimer.isActive()) {
532 return;
533 }
534 if (m_multiplayer && m_multiplayer->attached() > 1) {
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", Qt::BlockingQueuedConnection, 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 (isLoaded()) {
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 (isLoaded()) {
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 threadInterrupt();
774 m_threadContext.frameskip = skip;
775 if (isLoaded()) {
776 m_threadContext.gba->video.frameskip = skip;
777 }
778 threadContinue();
779}
780
781void GameController::setVolume(int volume) {
782 threadInterrupt();
783 m_threadContext.volume = volume;
784 if (isLoaded()) {
785 m_threadContext.gba->audio.masterVolume = volume;
786 }
787 threadContinue();
788}
789
790void GameController::setMute(bool mute) {
791 threadInterrupt();
792 m_threadContext.mute = mute;
793 if (isLoaded()) {
794 m_threadContext.gba->audio.masterVolume = mute ? 0 : m_threadContext.volume;
795 }
796 threadContinue();
797}
798
799void GameController::setTurbo(bool set, bool forced) {
800 if (m_turboForced && !forced) {
801 return;
802 }
803 if (m_turbo == set && m_turboForced == forced) {
804 // Don't interrupt the thread if we don't need to
805 return;
806 }
807 m_turbo = set;
808 m_turboForced = set && forced;
809 enableTurbo();
810}
811
812void GameController::setTurboSpeed(float ratio) {
813 m_turboSpeed = ratio;
814 enableTurbo();
815}
816
817void GameController::enableTurbo() {
818 threadInterrupt();
819 if (!m_turbo) {
820 m_threadContext.fpsTarget = m_fpsTarget;
821 m_threadContext.sync.audioWait = m_audioSync;
822 m_threadContext.sync.videoFrameWait = m_videoSync;
823 } else if (m_turboSpeed <= 0) {
824 m_threadContext.fpsTarget = m_fpsTarget;
825 m_threadContext.sync.audioWait = false;
826 m_threadContext.sync.videoFrameWait = false;
827 } else {
828 m_threadContext.fpsTarget = m_fpsTarget * m_turboSpeed;
829 m_threadContext.sync.audioWait = true;
830 m_threadContext.sync.videoFrameWait = false;
831 }
832 if (m_audioProcessor) {
833 redoSamples(m_audioProcessor->getBufferSamples());
834 }
835 threadContinue();
836}
837
838void GameController::setAVStream(GBAAVStream* stream) {
839 threadInterrupt();
840 m_threadContext.stream = stream;
841 if (isLoaded()) {
842 m_threadContext.gba->stream = stream;
843 }
844 threadContinue();
845}
846
847void GameController::clearAVStream() {
848 threadInterrupt();
849 m_threadContext.stream = nullptr;
850 if (isLoaded()) {
851 m_threadContext.gba->stream = nullptr;
852 }
853 threadContinue();
854}
855
856#ifdef USE_PNG
857void GameController::screenshot() {
858 GBARunOnThread(&m_threadContext, GBAThreadTakeScreenshot);
859}
860#endif
861
862void GameController::reloadAudioDriver() {
863 int samples = 0;
864 unsigned sampleRate = 0;
865 if (m_audioProcessor) {
866 QMetaObject::invokeMethod(m_audioProcessor, "pause", Qt::BlockingQueuedConnection);
867 samples = m_audioProcessor->getBufferSamples();
868 sampleRate = m_audioProcessor->sampleRate();
869 delete m_audioProcessor;
870 }
871 m_audioProcessor = AudioProcessor::create();
872 if (samples) {
873 m_audioProcessor->setBufferSamples(samples);
874 }
875 if (sampleRate) {
876 m_audioProcessor->requestSampleRate(sampleRate);
877 }
878 m_audioProcessor->moveToThread(m_audioThread);
879 connect(this, SIGNAL(gameStarted(GBAThread*)), m_audioProcessor, SLOT(start()));
880 connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
881 connect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));
882 if (isLoaded()) {
883 m_audioProcessor->setInput(&m_threadContext);
884 QMetaObject::invokeMethod(m_audioProcessor, "start");
885 }
886}
887
888void GameController::setLuminanceValue(uint8_t value) {
889 m_luxValue = value;
890 value = std::max<int>(value - 0x16, 0);
891 m_luxLevel = 10;
892 for (int i = 0; i < 10; ++i) {
893 if (value < GBA_LUX_LEVELS[i]) {
894 m_luxLevel = i;
895 break;
896 }
897 }
898 emit luminanceValueChanged(m_luxValue);
899}
900
901void GameController::setLuminanceLevel(int level) {
902 int value = 0x16;
903 level = std::max(0, std::min(10, level));
904 if (level > 0) {
905 value += GBA_LUX_LEVELS[level - 1];
906 }
907 setLuminanceValue(value);
908}
909
910void GameController::setRealTime() {
911 m_rtc.override = GBARTCGenericSource::RTC_NO_OVERRIDE;
912}
913
914void GameController::setFixedTime(const QDateTime& time) {
915 m_rtc.override = GBARTCGenericSource::RTC_FIXED;
916 m_rtc.value = time.toMSecsSinceEpoch() / 1000;
917}
918
919void GameController::setFakeEpoch(const QDateTime& time) {
920 m_rtc.override = GBARTCGenericSource::RTC_FAKE_EPOCH;
921 m_rtc.value = time.toMSecsSinceEpoch() / 1000;
922}
923
924void GameController::updateKeys() {
925 int activeKeys = m_activeKeys;
926 activeKeys |= m_activeButtons;
927 activeKeys &= ~m_inactiveKeys;
928 m_threadContext.activeKeys = activeKeys;
929}
930
931void GameController::redoSamples(int samples) {
932#if RESAMPLE_LIBRARY != RESAMPLE_BLIP_BUF
933 float sampleRate = 0x8000;
934 float ratio;
935 if (m_threadContext.gba) {
936 sampleRate = m_threadContext.gba->audio.sampleRate;
937 }
938 ratio = GBAAudioCalculateRatio(sampleRate, m_threadContext.fpsTarget, m_audioProcess->sampleRate());
939 m_threadContext.audioBuffers = ceil(samples / ratio);
940#else
941 m_threadContext.audioBuffers = samples;
942#endif
943 if (m_threadContext.gba) {
944 GBAAudioResizeBuffer(&m_threadContext.gba->audio, m_threadContext.audioBuffers);
945 }
946 QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
947}
948
949void GameController::setLogLevel(int levels) {
950 threadInterrupt();
951 m_logLevels = levels;
952 threadContinue();
953}
954
955void GameController::enableLogLevel(int levels) {
956 threadInterrupt();
957 m_logLevels |= levels;
958 threadContinue();
959}
960
961void GameController::disableLogLevel(int levels) {
962 threadInterrupt();
963 m_logLevels &= ~levels;
964 threadContinue();
965}
966
967void GameController::pollEvents() {
968 if (!m_inputController) {
969 return;
970 }
971
972 m_activeButtons = m_inputController->pollEvents();
973 updateKeys();
974}