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