all repos — mgba @ 77f74a831f0616f37f27c4675d259a7471a85d55

mGBA Game Boy Advance Emulator

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