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