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