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