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