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 if (m_threadContext.core->opts.rewindEnable && m_threadContext.core->opts.rewindBufferCapacity > 0) {
663 mCoreRewindContextDeinit(&m_threadContext.rewind);
664 }
665 m_threadContext.core->opts.rewindEnable = enable;
666 m_threadContext.core->opts.rewindBufferCapacity = capacity;
667 if (enable && capacity > 0) {
668 mCoreRewindContextInit(&m_threadContext.rewind, capacity);
669 }
670 threadContinue();
671 }
672}
673
674void GameController::rewind(int states) {
675 threadInterrupt();
676 if (!states) {
677 states = INT_MAX;
678 }
679 for (int i = 0; i < states; ++i) {
680 if (!mCoreRewindRestore(&m_threadContext.rewind, m_threadContext.core)) {
681 break;
682 }
683 }
684 threadContinue();
685 emit frameAvailable(m_drawContext);
686 emit rewound(&m_threadContext);
687}
688
689void GameController::startRewinding() {
690 if (!isLoaded()) {
691 return;
692 }
693 if (!m_threadContext.core->opts.rewindEnable) {
694 return;
695 }
696 if (m_multiplayer && m_multiplayer->attached() > 1) {
697 return;
698 }
699 if (m_wasPaused) {
700 setPaused(false);
701 m_wasPaused = true;
702 }
703 mCoreThreadSetRewinding(&m_threadContext, true);
704}
705
706void GameController::stopRewinding() {
707 if (!isLoaded()) {
708 return;
709 }
710 mCoreThreadSetRewinding(&m_threadContext, false);
711 bool signalsBlocked = blockSignals(true);
712 setPaused(m_wasPaused);
713 blockSignals(signalsBlocked);
714}
715
716void GameController::keyPressed(int key) {
717 int mappedKey = 1 << key;
718 m_activeKeys |= mappedKey;
719 if (!m_inputController->allowOpposing()) {
720 if ((m_activeKeys & 0x30) == 0x30) {
721 m_inactiveKeys |= mappedKey ^ 0x30;
722 m_activeKeys ^= mappedKey ^ 0x30;
723 }
724 if ((m_activeKeys & 0xC0) == 0xC0) {
725 m_inactiveKeys |= mappedKey ^ 0xC0;
726 m_activeKeys ^= mappedKey ^ 0xC0;
727 }
728 }
729 updateKeys();
730}
731
732void GameController::keyReleased(int key) {
733 int mappedKey = 1 << key;
734 m_activeKeys &= ~mappedKey;
735 if (!m_inputController->allowOpposing()) {
736 if (mappedKey & 0x30) {
737 m_activeKeys |= m_inactiveKeys & (0x30 ^ mappedKey);
738 m_inactiveKeys &= ~0x30;
739 }
740 if (mappedKey & 0xC0) {
741 m_activeKeys |= m_inactiveKeys & (0xC0 ^ mappedKey);
742 m_inactiveKeys &= ~0xC0;
743 }
744 }
745 updateKeys();
746}
747
748void GameController::clearKeys() {
749 m_activeKeys = 0;
750 m_inactiveKeys = 0;
751 updateKeys();
752}
753
754void GameController::setAutofire(int key, bool enable) {
755 if (key >= GBA_KEY_MAX || key < 0) {
756 return;
757 }
758
759 if (!enable && m_autofireStatus[key]) {
760 keyReleased(key);
761 }
762
763 m_autofire[key] = enable;
764 m_autofireStatus[key] = 0;
765}
766
767void GameController::setAudioBufferSamples(int samples) {
768 if (m_audioProcessor) {
769 threadInterrupt();
770 redoSamples(samples);
771 threadContinue();
772 QMetaObject::invokeMethod(m_audioProcessor, "setBufferSamples", Qt::BlockingQueuedConnection, Q_ARG(int, samples));
773 }
774}
775
776void GameController::setAudioSampleRate(unsigned rate) {
777 if (!rate) {
778 return;
779 }
780 if (m_audioProcessor) {
781 threadInterrupt();
782 redoSamples(m_audioProcessor->getBufferSamples());
783 threadContinue();
784 QMetaObject::invokeMethod(m_audioProcessor, "requestSampleRate", Q_ARG(unsigned, rate));
785 }
786}
787
788void GameController::setAudioChannelEnabled(int channel, bool enable) {
789 if (channel > 5 || channel < 0) {
790 return;
791 }
792#ifdef M_CORE_GBA
793 GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
794#endif
795#ifdef M_CORE_GB
796 GB* gb = static_cast<GB*>(m_threadContext.core->board);
797#endif
798 m_audioChannels[channel] = enable;
799 if (isLoaded()) {
800 switch (channel) {
801 case 0:
802 case 1:
803 case 2:
804 case 3:
805 switch (m_threadContext.core->platform(m_threadContext.core)) {
806#ifdef M_CORE_GBA
807 case PLATFORM_GBA:
808 gba->audio.psg.forceDisableCh[channel] = !enable;
809 break;
810#endif
811#ifdef M_CORE_GB
812 case PLATFORM_GB:
813 gb->audio.forceDisableCh[channel] = !enable;
814 break;
815#endif
816 default:
817 break;
818 }
819 break;
820#ifdef M_CORE_GBA
821 case 4:
822 if (m_threadContext.core->platform(m_threadContext.core) == PLATFORM_GBA) {
823 gba->audio.forceDisableChA = !enable;
824 }
825 break;
826 case 5:
827 if (m_threadContext.core->platform(m_threadContext.core) == PLATFORM_GBA) {
828 gba->audio.forceDisableChB = !enable;
829 }
830 break;
831#endif
832 }
833 }
834}
835
836void GameController::startAudio() {
837 bool started = false;
838 QMetaObject::invokeMethod(m_audioProcessor, "start", Qt::BlockingQueuedConnection, Q_RETURN_ARG(bool, started));
839 if (!started) {
840 LOG(QT, ERROR) << tr("Failed to start audio processor");
841 // Don't freeze!
842 m_audioSync = false;
843 m_videoSync = true;
844 m_threadContext.sync.audioWait = false;
845 m_threadContext.sync.videoFrameWait = true;
846 }
847}
848
849void GameController::setVideoLayerEnabled(int layer, bool enable) {
850 if (layer > 4 || layer < 0) {
851 return;
852 }
853 m_videoLayers[layer] = enable;
854#ifdef M_CORE_GBA
855 if (isLoaded() && m_threadContext.core->platform(m_threadContext.core) == PLATFORM_GBA) {
856 GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
857 switch (layer) {
858 case 0:
859 case 1:
860 case 2:
861 case 3:
862 gba->video.renderer->disableBG[layer] = !enable;
863 break;
864 case 4:
865 gba->video.renderer->disableOBJ = !enable;
866 break;
867 }
868 }
869#endif
870}
871
872void GameController::setFPSTarget(float fps) {
873 threadInterrupt();
874 m_fpsTarget = fps;
875 m_threadContext.sync.fpsTarget = fps;
876 if (m_turbo && m_turboSpeed > 0) {
877 m_threadContext.sync.fpsTarget *= m_turboSpeed;
878 }
879 if (m_audioProcessor) {
880 redoSamples(m_audioProcessor->getBufferSamples());
881 }
882 threadContinue();
883}
884
885void GameController::setUseBIOS(bool use) {
886 if (use == m_useBios) {
887 return;
888 }
889 m_useBios = use;
890 if (m_gameOpen) {
891 closeGame();
892 openGame();
893 }
894}
895
896void GameController::loadState(int slot) {
897 if (m_fname.isEmpty()) {
898 // We're in the BIOS
899 return;
900 }
901 if (slot > 0 && slot != m_stateSlot) {
902 m_stateSlot = slot;
903 m_backupSaveState.clear();
904 }
905 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
906 GameController* controller = static_cast<GameController*>(context->userData);
907 if (!controller->m_backupLoadState) {
908 controller->m_backupLoadState = VFileMemChunk(nullptr, 0);
909 }
910 mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
911 if (mCoreLoadState(context->core, controller->m_stateSlot, controller->m_loadStateFlags)) {
912 controller->frameAvailable(controller->m_drawContext);
913 controller->stateLoaded(context);
914 }
915 });
916}
917
918void GameController::saveState(int slot) {
919 if (m_fname.isEmpty()) {
920 // We're in the BIOS
921 return;
922 }
923 if (slot > 0) {
924 m_stateSlot = slot;
925 }
926 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
927 GameController* controller = static_cast<GameController*>(context->userData);
928 VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, false);
929 if (vf) {
930 controller->m_backupSaveState.resize(vf->size(vf));
931 vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
932 vf->close(vf);
933 }
934 mCoreSaveState(context->core, controller->m_stateSlot, controller->m_saveStateFlags);
935 });
936}
937
938void GameController::loadBackupState() {
939 if (!m_backupLoadState) {
940 return;
941 }
942
943 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
944 GameController* controller = static_cast<GameController*>(context->userData);
945 controller->m_backupLoadState->seek(controller->m_backupLoadState, 0, SEEK_SET);
946 if (mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_loadStateFlags)) {
947 mLOG(STATUS, INFO, "Undid state load");
948 controller->frameAvailable(controller->m_drawContext);
949 controller->stateLoaded(context);
950 }
951 controller->m_backupLoadState->close(controller->m_backupLoadState);
952 controller->m_backupLoadState = nullptr;
953 });
954}
955
956void GameController::saveBackupState() {
957 if (m_backupSaveState.isEmpty()) {
958 return;
959 }
960
961 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
962 GameController* controller = static_cast<GameController*>(context->userData);
963 VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, true);
964 if (vf) {
965 vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
966 vf->close(vf);
967 mLOG(STATUS, INFO, "Undid state save");
968 }
969 controller->m_backupSaveState.clear();
970 });
971}
972
973void GameController::setTurbo(bool set, bool forced) {
974 if (m_turboForced && !forced) {
975 return;
976 }
977 if (m_turbo == set && m_turboForced == (set && forced)) {
978 // Don't interrupt the thread if we don't need to
979 return;
980 }
981 if (!m_sync) {
982 return;
983 }
984 m_turbo = set;
985 m_turboForced = set && forced;
986 enableTurbo();
987}
988
989void GameController::setTurboSpeed(float ratio) {
990 m_turboSpeed = ratio;
991 enableTurbo();
992}
993
994void GameController::enableTurbo() {
995 threadInterrupt();
996 bool shouldRedoSamples = false;
997 if (!m_turbo) {
998 shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget;
999 m_threadContext.sync.fpsTarget = m_fpsTarget;
1000 m_threadContext.sync.audioWait = m_audioSync;
1001 m_threadContext.sync.videoFrameWait = m_videoSync;
1002 } else if (m_turboSpeed <= 0) {
1003 shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget;
1004 m_threadContext.sync.fpsTarget = m_fpsTarget;
1005 m_threadContext.sync.audioWait = false;
1006 m_threadContext.sync.videoFrameWait = false;
1007 } else {
1008 shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget * m_turboSpeed;
1009 m_threadContext.sync.fpsTarget = m_fpsTarget * m_turboSpeed;
1010 m_threadContext.sync.audioWait = true;
1011 m_threadContext.sync.videoFrameWait = false;
1012 }
1013 if (m_audioProcessor && shouldRedoSamples) {
1014 redoSamples(m_audioProcessor->getBufferSamples());
1015 }
1016 threadContinue();
1017}
1018
1019void GameController::setSync(bool enable) {
1020 m_turbo = false;
1021 m_turboForced = false;
1022 if (!enable) {
1023 m_threadContext.sync.audioWait = false;
1024 m_threadContext.sync.videoFrameWait = false;
1025 } else {
1026 m_threadContext.sync.audioWait = m_audioSync;
1027 m_threadContext.sync.videoFrameWait = m_videoSync;
1028 }
1029 m_sync = enable;
1030}
1031void GameController::setAVStream(mAVStream* stream) {
1032 threadInterrupt();
1033 m_stream = stream;
1034 if (isLoaded()) {
1035 m_threadContext.core->setAVStream(m_threadContext.core, stream);
1036 }
1037 threadContinue();
1038}
1039
1040void GameController::clearAVStream() {
1041 threadInterrupt();
1042 m_stream = nullptr;
1043 if (isLoaded()) {
1044 m_threadContext.core->setAVStream(m_threadContext.core, nullptr);
1045 }
1046 threadContinue();
1047}
1048
1049#ifdef USE_PNG
1050void GameController::screenshot() {
1051 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
1052 mCoreTakeScreenshot(context->core);
1053 });
1054}
1055#endif
1056
1057void GameController::reloadAudioDriver() {
1058 int samples = 0;
1059 unsigned sampleRate = 0;
1060 if (m_audioProcessor) {
1061 QMetaObject::invokeMethod(m_audioProcessor, "pause", Qt::BlockingQueuedConnection);
1062 samples = m_audioProcessor->getBufferSamples();
1063 sampleRate = m_audioProcessor->sampleRate();
1064 delete m_audioProcessor;
1065 }
1066 m_audioProcessor = AudioProcessor::create();
1067 if (samples) {
1068 m_audioProcessor->setBufferSamples(samples);
1069 }
1070 if (sampleRate) {
1071 m_audioProcessor->requestSampleRate(sampleRate);
1072 }
1073 m_audioProcessor->moveToThread(m_audioThread);
1074 connect(this, SIGNAL(gamePaused(mCoreThread*)), m_audioProcessor, SLOT(pause()));
1075 connect(this, SIGNAL(gameStarted(mCoreThread*, const QString&)), m_audioProcessor, SLOT(setInput(mCoreThread*)));
1076 if (isLoaded()) {
1077 m_audioProcessor->setInput(&m_threadContext);
1078 startAudio();
1079 }
1080}
1081
1082void GameController::setSaveStateExtdata(int flags) {
1083 m_saveStateFlags = flags;
1084}
1085
1086void GameController::setLoadStateExtdata(int flags) {
1087 m_loadStateFlags = flags;
1088}
1089
1090void GameController::setLuminanceValue(uint8_t value) {
1091 m_luxValue = value;
1092 value = std::max<int>(value - 0x16, 0);
1093 m_luxLevel = 10;
1094 for (int i = 0; i < 10; ++i) {
1095 if (value < GBA_LUX_LEVELS[i]) {
1096 m_luxLevel = i;
1097 break;
1098 }
1099 }
1100 emit luminanceValueChanged(m_luxValue);
1101}
1102
1103void GameController::setLuminanceLevel(int level) {
1104 int value = 0x16;
1105 level = std::max(0, std::min(10, level));
1106 if (level > 0) {
1107 value += GBA_LUX_LEVELS[level - 1];
1108 }
1109 setLuminanceValue(value);
1110}
1111
1112void GameController::setRealTime() {
1113 m_rtc.override = RTC_NO_OVERRIDE;
1114}
1115
1116void GameController::setFixedTime(const QDateTime& time) {
1117 m_rtc.override = RTC_FIXED;
1118 m_rtc.value = time.toMSecsSinceEpoch() / 1000;
1119}
1120
1121void GameController::setFakeEpoch(const QDateTime& time) {
1122 m_rtc.override = RTC_FAKE_EPOCH;
1123 m_rtc.value = time.toMSecsSinceEpoch() / 1000;
1124}
1125
1126void GameController::updateKeys() {
1127 int activeKeys = m_activeKeys;
1128 activeKeys |= m_activeButtons;
1129 activeKeys &= ~m_inactiveKeys;
1130 if (isLoaded()) {
1131 m_threadContext.core->setKeys(m_threadContext.core, activeKeys);
1132 }
1133}
1134
1135void GameController::redoSamples(int samples) {
1136 if (m_threadContext.core) {
1137 m_threadContext.core->setAudioBufferSize(m_threadContext.core, samples);
1138 }
1139 QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
1140}
1141
1142void GameController::setLogLevel(int levels) {
1143 threadInterrupt();
1144 m_logLevels = levels;
1145 threadContinue();
1146}
1147
1148void GameController::enableLogLevel(int levels) {
1149 threadInterrupt();
1150 m_logLevels |= levels;
1151 threadContinue();
1152}
1153
1154void GameController::disableLogLevel(int levels) {
1155 threadInterrupt();
1156 m_logLevels &= ~levels;
1157 threadContinue();
1158}
1159
1160void GameController::pollEvents() {
1161 if (!m_inputController) {
1162 return;
1163 }
1164
1165 m_activeButtons = m_inputController->pollEvents();
1166 updateKeys();
1167}
1168
1169void GameController::updateAutofire() {
1170 // TODO: Move all key events onto the CPU thread...somehow
1171 for (int k = 0; k < GBA_KEY_MAX; ++k) {
1172 if (!m_autofire[k]) {
1173 continue;
1174 }
1175 m_autofireStatus[k] ^= 1;
1176 if (m_autofireStatus[k]) {
1177 keyPressed(k);
1178 } else {
1179 keyReleased(k);
1180 }
1181 }
1182}