all repos — mgba @ faadb5d6a6357c59a5b70ecbdf4fa204a9c96f9a

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	if (mCoreThreadIsPaused(&m_threadContext)) {
 627		mCoreThreadUnpause(&m_threadContext);
 628	}
 629	mCoreThreadEnd(&m_threadContext);
 630}
 631
 632void GameController::cleanGame() {
 633	if (!m_gameOpen || mCoreThreadIsActive(&m_threadContext)) {
 634		return;
 635	}
 636
 637	m_audioProcessor->pause();
 638	mCoreThreadJoin(&m_threadContext);
 639
 640	if (m_tileCache) {
 641		mTileCacheDeinit(m_tileCache.get());
 642		m_tileCache.reset();
 643	}
 644
 645	delete[] m_drawContext;
 646	delete[] m_frontBuffer;
 647
 648	m_threadContext.core->deinit(m_threadContext.core);
 649	m_threadContext.core = nullptr;
 650	m_gameOpen = false;
 651}
 652
 653void GameController::crashGame(const QString& crashMessage) {
 654	closeGame();
 655	emit gameCrashed(crashMessage);
 656}
 657
 658bool GameController::isPaused() {
 659	if (!m_gameOpen) {
 660		return false;
 661	}
 662	return mCoreThreadIsPaused(&m_threadContext);
 663}
 664
 665mPlatform GameController::platform() const {
 666	if (!m_gameOpen) {
 667		return PLATFORM_NONE;
 668	}
 669	return m_threadContext.core->platform(m_threadContext.core);
 670}
 671
 672QSize GameController::screenDimensions() const {
 673	if (!m_gameOpen) {
 674		return QSize();
 675	}
 676	unsigned width, height;
 677	m_threadContext.core->desiredVideoDimensions(m_threadContext.core, &width, &height);
 678
 679	return QSize(width, height);
 680}
 681
 682QPair<unsigned, unsigned> GameController::frameRate() const {
 683	if (!m_gameOpen) {
 684		return qMakePair(1U, 60U);
 685	}
 686	return qMakePair(m_threadContext.core->frameCycles(m_threadContext.core), m_threadContext.core->frequency(m_threadContext.core));
 687}
 688
 689void GameController::setPaused(bool paused) {
 690	if (!isLoaded() || paused == mCoreThreadIsPaused(&m_threadContext)) {
 691		return;
 692	}
 693	m_wasPaused = paused;
 694	if (paused) {
 695		m_pauseAfterFrame.testAndSetRelaxed(false, true);
 696	} else {
 697		mCoreThreadUnpause(&m_threadContext);
 698		startAudio();
 699		emit gameUnpaused(&m_threadContext);
 700	}
 701}
 702
 703void GameController::reset() {
 704	if (!m_gameOpen) {
 705		return;
 706	}
 707	bool wasPaused = isPaused();
 708	setPaused(false);
 709	Interrupter interrupter(this);
 710	mCoreThreadReset(&m_threadContext);
 711	if (wasPaused) {
 712		setPaused(true);
 713	}
 714}
 715
 716void GameController::threadInterrupt() {
 717	if (m_gameOpen) {
 718		mCoreThreadInterrupt(&m_threadContext);
 719	}
 720}
 721
 722void GameController::threadContinue() {
 723	if (m_gameOpen) {
 724		mCoreThreadContinue(&m_threadContext);
 725	}
 726}
 727
 728void GameController::frameAdvance() {
 729	if (m_pauseAfterFrame.testAndSetRelaxed(false, true)) {
 730		setPaused(false);
 731	}
 732}
 733
 734void GameController::setRewind(bool enable, int capacity, bool rewindSave) {
 735	if (m_gameOpen) {
 736		Interrupter interrupter(this);
 737		if (m_threadContext.core->opts.rewindEnable && m_threadContext.core->opts.rewindBufferCapacity > 0) {
 738			mCoreRewindContextDeinit(&m_threadContext.rewind);
 739		}
 740		m_threadContext.core->opts.rewindEnable = enable;
 741		m_threadContext.core->opts.rewindBufferCapacity = capacity;
 742		m_threadContext.core->opts.rewindSave = rewindSave;
 743		if (enable && capacity > 0) {
 744			mCoreRewindContextInit(&m_threadContext.rewind, capacity);
 745			 m_threadContext.rewind.stateFlags = rewindSave ? SAVESTATE_SAVEDATA : 0;
 746		}
 747	}
 748}
 749
 750void GameController::rewind(int states) {
 751	threadInterrupt();
 752	if (!states) {
 753		states = INT_MAX;
 754	}
 755	for (int i = 0; i < states; ++i) {
 756		if (!mCoreRewindRestore(&m_threadContext.rewind, m_threadContext.core)) {
 757			break;
 758		}
 759	}
 760	threadContinue();
 761	emit frameAvailable(m_drawContext);
 762	emit rewound(&m_threadContext);
 763}
 764
 765void GameController::startRewinding() {
 766	if (!isLoaded()) {
 767		return;
 768	}
 769	if (!m_threadContext.core->opts.rewindEnable) {
 770		return;
 771	}
 772	if (m_multiplayer && m_multiplayer->attached() > 1) {
 773		return;
 774	}
 775	if (m_wasPaused) {
 776		setPaused(false);
 777		m_wasPaused = true;
 778	}
 779	mCoreThreadSetRewinding(&m_threadContext, true);
 780}
 781
 782void GameController::stopRewinding() {
 783	if (!isLoaded()) {
 784		return;
 785	}
 786	mCoreThreadSetRewinding(&m_threadContext, false);
 787	bool signalsBlocked = blockSignals(true);
 788	setPaused(m_wasPaused);
 789	blockSignals(signalsBlocked);
 790}
 791
 792void GameController::keyPressed(int key) {
 793	int mappedKey = 1 << key;
 794	m_activeKeys |= mappedKey;
 795	if (!m_inputController->allowOpposing()) {
 796		if ((m_activeKeys & 0x30) == 0x30) {
 797			m_inactiveKeys |= mappedKey ^ 0x30;
 798			m_activeKeys ^= mappedKey ^ 0x30;
 799		}
 800		if ((m_activeKeys & 0xC0) == 0xC0) {
 801			m_inactiveKeys |= mappedKey ^ 0xC0;
 802			m_activeKeys ^= mappedKey ^ 0xC0;
 803		}
 804	}
 805	updateKeys();
 806}
 807
 808void GameController::keyReleased(int key) {
 809	int mappedKey = 1 << key;
 810	m_activeKeys &= ~mappedKey;
 811	if (!m_inputController->allowOpposing()) {
 812		if (mappedKey & 0x30) {
 813			m_activeKeys |= m_inactiveKeys & (0x30 ^ mappedKey);
 814			m_inactiveKeys &= ~0x30;
 815		}
 816		if (mappedKey & 0xC0) {
 817			m_activeKeys |= m_inactiveKeys & (0xC0 ^ mappedKey);
 818			m_inactiveKeys &= ~0xC0;
 819		}
 820	}
 821	updateKeys();
 822}
 823
 824void GameController::cursorLocation(int x, int y) {
 825	if (!isLoaded()) {
 826		return;
 827	}
 828	m_threadContext.core->setCursorLocation(m_threadContext.core, x, y);
 829}
 830
 831void GameController::cursorDown(bool down) {
 832	if (!isLoaded()) {
 833		return;
 834	}
 835	m_threadContext.core->setCursorDown(m_threadContext.core, down);
 836}
 837
 838void GameController::clearKeys() {
 839	m_activeKeys = 0;
 840	m_inactiveKeys = 0;
 841	updateKeys();
 842}
 843
 844void GameController::setAutofire(int key, bool enable) {
 845	if (key >= GBA_KEY_MAX || key < 0) {
 846		return;
 847	}
 848
 849	if (!enable && m_autofireStatus[key]) {
 850		keyReleased(key);
 851	}
 852
 853	m_autofire[key] = enable;
 854	m_autofireStatus[key] = 0;
 855}
 856
 857void GameController::setAudioBufferSamples(int samples) {
 858	if (m_audioProcessor) {
 859		threadInterrupt();
 860		redoSamples(samples);
 861		threadContinue();
 862		m_audioProcessor->setBufferSamples(samples);
 863	}
 864}
 865
 866void GameController::setAudioSampleRate(unsigned rate) {
 867	if (!rate) {
 868		return;
 869	}
 870	if (m_audioProcessor) {
 871		threadInterrupt();
 872		redoSamples(m_audioProcessor->getBufferSamples());
 873		threadContinue();
 874		m_audioProcessor->requestSampleRate(rate);
 875	}
 876}
 877
 878void GameController::setAudioChannelEnabled(int channel, bool enable) {
 879	if (channel > 5 || channel < 0) {
 880		return;
 881	}
 882	m_audioChannels.reserve(channel + 1);
 883	while (m_audioChannels.size() <= channel) {
 884		m_audioChannels.append(true);
 885	}
 886	m_audioChannels[channel] = enable;
 887	if (isLoaded()) {
 888		m_threadContext.core->enableAudioChannel(m_threadContext.core, channel, enable);
 889	}
 890}
 891
 892void GameController::startAudio() {
 893	if (!m_audioProcessor->start()) {
 894		LOG(QT, ERROR) << tr("Failed to start audio processor");
 895		// Don't freeze!
 896		m_audioSync = false;
 897		m_videoSync = true;
 898		m_threadContext.sync.audioWait = false;
 899		m_threadContext.sync.videoFrameWait = true;
 900	}
 901}
 902
 903void GameController::setVideoLayerEnabled(int layer, bool enable) {
 904	if (layer > 4 || layer < 0) {
 905		return;
 906	}
 907	m_videoLayers.reserve(layer + 1);
 908	while (m_videoLayers.size() <= layer) {
 909		m_videoLayers.append(true);
 910	}
 911	m_videoLayers[layer] = enable;
 912	if (isLoaded()) {
 913		m_threadContext.core->enableVideoLayer(m_threadContext.core, layer, enable);
 914	}
 915}
 916
 917void GameController::setFPSTarget(float fps) {
 918	Interrupter interrupter(this);
 919	m_fpsTarget = fps;
 920	m_threadContext.sync.fpsTarget = fps;
 921	if (m_turbo && m_turboSpeed > 0) {
 922		m_threadContext.sync.fpsTarget *= m_turboSpeed;
 923	}
 924	if (m_audioProcessor) {
 925		redoSamples(m_audioProcessor->getBufferSamples());
 926	}
 927}
 928
 929void GameController::setUseBIOS(bool use) {
 930	if (use == m_useBios) {
 931		return;
 932	}
 933	m_useBios = use;
 934	if (m_gameOpen) {
 935		closeGame();
 936		openGame();
 937	}
 938}
 939
 940void GameController::loadState(int slot) {
 941	if (m_fname.isEmpty()) {
 942		// We're in the BIOS
 943		return;
 944	}
 945	if (slot > 0 && slot != m_stateSlot) {
 946		m_stateSlot = slot;
 947		m_backupSaveState.clear();
 948	}
 949	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 950		GameController* controller = static_cast<GameController*>(context->userData);
 951		if (!controller->m_backupLoadState) {
 952			controller->m_backupLoadState = VFileMemChunk(nullptr, 0);
 953		}
 954		mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
 955		if (mCoreLoadState(context->core, controller->m_stateSlot, controller->m_loadStateFlags)) {
 956			controller->frameAvailable(controller->m_drawContext);
 957			controller->stateLoaded(context);
 958		}
 959	});
 960}
 961
 962void GameController::saveState(int slot) {
 963	if (m_fname.isEmpty()) {
 964		// We're in the BIOS
 965		return;
 966	}
 967	if (slot > 0) {
 968		m_stateSlot = slot;
 969	}
 970	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 971		GameController* controller = static_cast<GameController*>(context->userData);
 972		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, false);
 973		if (vf) {
 974			controller->m_backupSaveState.resize(vf->size(vf));
 975			vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
 976			vf->close(vf);
 977		}
 978		mCoreSaveState(context->core, controller->m_stateSlot, controller->m_saveStateFlags);
 979	});
 980}
 981
 982void GameController::loadBackupState() {
 983	if (!m_backupLoadState) {
 984		return;
 985	}
 986
 987	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 988		GameController* controller = static_cast<GameController*>(context->userData);
 989		controller->m_backupLoadState->seek(controller->m_backupLoadState, 0, SEEK_SET);
 990		if (mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_loadStateFlags)) {
 991			mLOG(STATUS, INFO, "Undid state load");
 992			controller->frameAvailable(controller->m_drawContext);
 993			controller->stateLoaded(context);
 994		}
 995		controller->m_backupLoadState->close(controller->m_backupLoadState);
 996		controller->m_backupLoadState = nullptr;
 997	});
 998}
 999
1000void GameController::saveBackupState() {
1001	if (m_backupSaveState.isEmpty()) {
1002		return;
1003	}
1004
1005	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
1006		GameController* controller = static_cast<GameController*>(context->userData);
1007		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, true);
1008		if (vf) {
1009			vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
1010			vf->close(vf);
1011			mLOG(STATUS, INFO, "Undid state save");
1012		}
1013		controller->m_backupSaveState.clear();
1014	});
1015}
1016
1017void GameController::setTurbo(bool set, bool forced) {
1018	if (m_turboForced && !forced) {
1019		return;
1020	}
1021	if (m_turbo == set && m_turboForced == (set && forced)) {
1022		// Don't interrupt the thread if we don't need to
1023		return;
1024	}
1025	if (!m_sync) {
1026		return;
1027	}
1028	m_turbo = set;
1029	m_turboForced = set && forced;
1030	enableTurbo();
1031}
1032
1033void GameController::setTurboSpeed(float ratio) {
1034	m_turboSpeed = ratio;
1035	enableTurbo();
1036}
1037
1038void GameController::enableTurbo() {
1039	Interrupter interrupter(this);
1040	bool shouldRedoSamples = false;
1041	if (!m_turbo) {
1042		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget;
1043		m_threadContext.sync.fpsTarget = m_fpsTarget;
1044		m_threadContext.sync.audioWait = m_audioSync;
1045		m_threadContext.sync.videoFrameWait = m_videoSync;
1046	} else if (m_turboSpeed <= 0) {
1047		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget;
1048		m_threadContext.sync.fpsTarget = m_fpsTarget;
1049		m_threadContext.sync.audioWait = false;
1050		m_threadContext.sync.videoFrameWait = false;
1051	} else {
1052		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget * m_turboSpeed;
1053		m_threadContext.sync.fpsTarget = m_fpsTarget * m_turboSpeed;
1054		m_threadContext.sync.audioWait = true;
1055		m_threadContext.sync.videoFrameWait = false;
1056	}
1057	if (m_audioProcessor && shouldRedoSamples) {
1058		redoSamples(m_audioProcessor->getBufferSamples());
1059	}
1060}
1061
1062void GameController::setSync(bool enable) {
1063	m_turbo = false;
1064	m_turboForced = false;
1065	if (!enable) {
1066		m_threadContext.sync.audioWait = false;
1067		m_threadContext.sync.videoFrameWait = false;
1068	} else {
1069		m_threadContext.sync.audioWait = m_audioSync;
1070		m_threadContext.sync.videoFrameWait = m_videoSync;
1071	}
1072	m_sync = enable;
1073}
1074
1075void GameController::setAudioSync(bool enable) {
1076	m_audioSync = enable;
1077	m_threadContext.sync.audioWait = enable;
1078}
1079
1080void GameController::setVideoSync(bool enable) {
1081	m_videoSync = enable;
1082	m_threadContext.sync.videoFrameWait = enable;
1083}
1084
1085void GameController::setAVStream(mAVStream* stream) {
1086	Interrupter interrupter(this);
1087	m_stream = stream;
1088	if (isLoaded()) {
1089		m_threadContext.core->setAVStream(m_threadContext.core, stream);
1090	}
1091}
1092
1093void GameController::clearAVStream() {
1094	Interrupter interrupter(this);
1095	m_stream = nullptr;
1096	if (isLoaded()) {
1097		m_threadContext.core->setAVStream(m_threadContext.core, nullptr);
1098	}
1099}
1100
1101#ifdef USE_PNG
1102void GameController::screenshot() {
1103	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
1104		mCoreTakeScreenshot(context->core);
1105	});
1106}
1107#endif
1108
1109void GameController::reloadAudioDriver() {
1110	int samples = 0;
1111	unsigned sampleRate = 0;
1112	if (m_audioProcessor) {
1113		m_audioProcessor->pause();
1114		samples = m_audioProcessor->getBufferSamples();
1115		sampleRate = m_audioProcessor->sampleRate();
1116		delete m_audioProcessor;
1117	}
1118	m_audioProcessor = AudioProcessor::create();
1119	if (samples) {
1120		m_audioProcessor->setBufferSamples(samples);
1121	}
1122	if (sampleRate) {
1123		m_audioProcessor->requestSampleRate(sampleRate);
1124	}
1125	connect(this, SIGNAL(gamePaused(mCoreThread*)), m_audioProcessor, SLOT(pause()));
1126	connect(this, SIGNAL(gameStarted(mCoreThread*, const QString&)), m_audioProcessor, SLOT(setInput(mCoreThread*)));
1127	if (isLoaded()) {
1128		m_audioProcessor->setInput(&m_threadContext);
1129		startAudio();
1130	}
1131}
1132
1133void GameController::setSaveStateExtdata(int flags) {
1134	m_saveStateFlags = flags;
1135}
1136
1137void GameController::setLoadStateExtdata(int flags) {
1138	m_loadStateFlags = flags;
1139}
1140
1141void GameController::setPreload(bool preload) {
1142	m_preload = preload;
1143}
1144
1145void GameController::setLuminanceValue(uint8_t value) {
1146	m_luxValue = value;
1147	value = std::max<int>(value - 0x16, 0);
1148	m_luxLevel = 10;
1149	for (int i = 0; i < 10; ++i) {
1150		if (value < GBA_LUX_LEVELS[i]) {
1151			m_luxLevel = i;
1152			break;
1153		}
1154	}
1155	emit luminanceValueChanged(m_luxValue);
1156}
1157
1158void GameController::setLuminanceLevel(int level) {
1159	int value = 0x16;
1160	level = std::max(0, std::min(10, level));
1161	if (level > 0) {
1162		value += GBA_LUX_LEVELS[level - 1];
1163	}
1164	setLuminanceValue(value);
1165}
1166
1167void GameController::setRealTime() {
1168	if (!isLoaded()) {
1169		return;
1170	}
1171	m_threadContext.core->rtc.override = RTC_NO_OVERRIDE;
1172}
1173
1174void GameController::setFixedTime(const QDateTime& time) {
1175	if (!isLoaded()) {
1176		return;
1177	}
1178	m_threadContext.core->rtc.override = RTC_FIXED;
1179	m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
1180}
1181
1182void GameController::setFakeEpoch(const QDateTime& time) {
1183	if (!isLoaded()) {
1184		return;
1185	}
1186	m_threadContext.core->rtc.override = RTC_FAKE_EPOCH;
1187	m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
1188}
1189
1190void GameController::updateKeys() {
1191	int activeKeys = m_activeKeys;
1192	activeKeys |= m_activeButtons;
1193	activeKeys &= ~m_inactiveKeys;
1194	if (isLoaded()) {
1195		m_threadContext.core->setKeys(m_threadContext.core, activeKeys);
1196	}
1197}
1198
1199void GameController::redoSamples(int samples) {
1200	if (m_gameOpen && m_threadContext.core) {
1201		m_threadContext.core->setAudioBufferSize(m_threadContext.core, samples);
1202	}
1203	m_audioProcessor->inputParametersChanged();
1204}
1205
1206void GameController::setLogLevel(int levels) {
1207	Interrupter interrupter(this);
1208	m_logLevels = levels;
1209}
1210
1211void GameController::enableLogLevel(int levels) {
1212	Interrupter interrupter(this);
1213	m_logLevels |= levels;
1214}
1215
1216void GameController::disableLogLevel(int levels) {
1217	Interrupter interrupter(this);
1218	m_logLevels &= ~levels;
1219}
1220
1221void GameController::pollEvents() {
1222	if (!m_inputController) {
1223		return;
1224	}
1225
1226	m_activeButtons = m_inputController->pollEvents();
1227	updateKeys();
1228}
1229
1230void GameController::updateAutofire() {
1231	// TODO: Move all key events onto the CPU thread...somehow
1232	for (int k = 0; k < GBA_KEY_MAX; ++k) {
1233		if (!m_autofire[k]) {
1234			continue;
1235		}
1236		m_autofireStatus[k] ^= 1;
1237		if (m_autofireStatus[k]) {
1238			keyPressed(k);
1239		} else {
1240			keyReleased(k);
1241		}
1242	}
1243}
1244
1245std::shared_ptr<mTileCache> GameController::tileCache() {
1246	if (m_tileCache) {
1247		return m_tileCache;
1248	}
1249	switch (platform()) {
1250#ifdef M_CORE_GBA
1251	case PLATFORM_GBA: {
1252		Interrupter interrupter(this);
1253		GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
1254		m_tileCache = std::make_shared<mTileCache>();
1255		GBAVideoTileCacheInit(m_tileCache.get());
1256		GBAVideoTileCacheAssociate(m_tileCache.get(), &gba->video);
1257		mTileCacheSetPalette(m_tileCache.get(), 0);
1258		break;
1259	}
1260#endif
1261#ifdef M_CORE_GB
1262	case PLATFORM_GB: {
1263		Interrupter interrupter(this);
1264		GB* gb = static_cast<GB*>(m_threadContext.core->board);
1265		m_tileCache = std::make_shared<mTileCache>();
1266		GBVideoTileCacheInit(m_tileCache.get());
1267		GBVideoTileCacheAssociate(m_tileCache.get(), &gb->video);
1268		mTileCacheSetPalette(m_tileCache.get(), 0);
1269		break;
1270	}
1271#endif
1272	default:
1273		return nullptr;
1274	}
1275	return m_tileCache;
1276}
1277
1278GameController::Interrupter::Interrupter(GameController* parent, bool fromThread)
1279	: m_parent(parent)
1280	, m_fromThread(fromThread)
1281{
1282	if (!m_fromThread) {
1283		m_parent->threadInterrupt();
1284	} else {
1285		mCoreThreadInterruptFromThread(m_parent->thread());
1286	}
1287}
1288
1289GameController::Interrupter::~Interrupter() {
1290	if (!m_fromThread) {
1291		m_parent->threadContinue();
1292	} else {
1293		mCoreThreadContinue(m_parent->thread());
1294	}
1295}