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