all repos — mgba @ fe2f67e2aa2246e8ec2c2599a480d6ff7557f3f7

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