all repos — mgba @ 5f59ad4c43b530f0754c883e61c2afa8fdd6c3fb

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::clearKeys() {
 830	m_activeKeys = 0;
 831	m_inactiveKeys = 0;
 832	updateKeys();
 833}
 834
 835void GameController::setAutofire(int key, bool enable) {
 836	if (key >= GBA_KEY_MAX || key < 0) {
 837		return;
 838	}
 839
 840	if (!enable && m_autofireStatus[key]) {
 841		keyReleased(key);
 842	}
 843
 844	m_autofire[key] = enable;
 845	m_autofireStatus[key] = 0;
 846}
 847
 848void GameController::setAudioBufferSamples(int samples) {
 849	if (m_audioProcessor) {
 850		threadInterrupt();
 851		redoSamples(samples);
 852		threadContinue();
 853		QMetaObject::invokeMethod(m_audioProcessor, "setBufferSamples", Qt::BlockingQueuedConnection, Q_ARG(int, samples));
 854	}
 855}
 856
 857void GameController::setAudioSampleRate(unsigned rate) {
 858	if (!rate) {
 859		return;
 860	}
 861	if (m_audioProcessor) {
 862		threadInterrupt();
 863		redoSamples(m_audioProcessor->getBufferSamples());
 864		threadContinue();
 865		QMetaObject::invokeMethod(m_audioProcessor, "requestSampleRate", Q_ARG(unsigned, rate));
 866	}
 867}
 868
 869void GameController::setAudioChannelEnabled(int channel, bool enable) {
 870	if (channel > 5 || channel < 0) {
 871		return;
 872	}
 873#ifdef M_CORE_GBA
 874	GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
 875#endif
 876#ifdef M_CORE_GB
 877	GB* gb = static_cast<GB*>(m_threadContext.core->board);
 878#endif
 879	m_audioChannels[channel] = enable;
 880	if (isLoaded()) {
 881		switch (channel) {
 882		case 0:
 883		case 1:
 884		case 2:
 885		case 3:
 886			switch (m_threadContext.core->platform(m_threadContext.core)) {
 887#ifdef M_CORE_GBA
 888			case PLATFORM_GBA:
 889				gba->audio.psg.forceDisableCh[channel] = !enable;
 890				break;
 891#endif
 892#ifdef M_CORE_GB
 893			case PLATFORM_GB:
 894				gb->audio.forceDisableCh[channel] = !enable;
 895				break;
 896#endif
 897			default:
 898				break;
 899			}
 900			break;
 901#ifdef M_CORE_GBA
 902		case 4:
 903			if (m_threadContext.core->platform(m_threadContext.core) == PLATFORM_GBA) {
 904				gba->audio.forceDisableChA = !enable;
 905			}
 906			break;
 907		case 5:
 908			if (m_threadContext.core->platform(m_threadContext.core) == PLATFORM_GBA) {
 909				gba->audio.forceDisableChB = !enable;
 910			}
 911			break;
 912#endif
 913		}
 914	}
 915}
 916
 917void GameController::startAudio() {
 918	bool started = false;
 919	QMetaObject::invokeMethod(m_audioProcessor, "start", Qt::BlockingQueuedConnection, Q_RETURN_ARG(bool, started));
 920	if (!started) {
 921		LOG(QT, ERROR) << tr("Failed to start audio processor");
 922		// Don't freeze!
 923		m_audioSync = false;
 924		m_videoSync = true;
 925		m_threadContext.sync.audioWait = false;
 926		m_threadContext.sync.videoFrameWait = true;
 927	}
 928}
 929
 930void GameController::setVideoLayerEnabled(int layer, bool enable) {
 931	if (layer > 4 || layer < 0) {
 932		return;
 933	}
 934	m_videoLayers[layer] = enable;
 935#ifdef M_CORE_GBA
 936	if (isLoaded() && m_threadContext.core->platform(m_threadContext.core) == PLATFORM_GBA) {
 937		GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
 938		switch (layer) {
 939		case 0:
 940		case 1:
 941		case 2:
 942		case 3:
 943			gba->video.renderer->disableBG[layer] = !enable;
 944			break;
 945		case 4:
 946			gba->video.renderer->disableOBJ = !enable;
 947			break;
 948		}
 949	}
 950#endif
 951}
 952
 953void GameController::setFPSTarget(float fps) {
 954	Interrupter interrupter(this);
 955	m_fpsTarget = fps;
 956	m_threadContext.sync.fpsTarget = fps;
 957	if (m_turbo && m_turboSpeed > 0) {
 958		m_threadContext.sync.fpsTarget *= m_turboSpeed;
 959	}
 960	if (m_audioProcessor) {
 961		redoSamples(m_audioProcessor->getBufferSamples());
 962	}
 963}
 964
 965void GameController::setUseBIOS(bool use) {
 966	if (use == m_useBios) {
 967		return;
 968	}
 969	m_useBios = use;
 970	if (m_gameOpen) {
 971		closeGame();
 972		openGame();
 973	}
 974}
 975
 976void GameController::loadState(int slot) {
 977	if (m_fname.isEmpty()) {
 978		// We're in the BIOS
 979		return;
 980	}
 981	if (slot > 0 && slot != m_stateSlot) {
 982		m_stateSlot = slot;
 983		m_backupSaveState.clear();
 984	}
 985	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 986		GameController* controller = static_cast<GameController*>(context->userData);
 987		if (!controller->m_backupLoadState) {
 988			controller->m_backupLoadState = VFileMemChunk(nullptr, 0);
 989		}
 990		mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
 991		if (mCoreLoadState(context->core, controller->m_stateSlot, controller->m_loadStateFlags)) {
 992			controller->frameAvailable(controller->m_drawContext);
 993			controller->stateLoaded(context);
 994		}
 995	});
 996}
 997
 998void GameController::saveState(int slot) {
 999	if (m_fname.isEmpty()) {
1000		// We're in the BIOS
1001		return;
1002	}
1003	if (slot > 0) {
1004		m_stateSlot = slot;
1005	}
1006	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
1007		GameController* controller = static_cast<GameController*>(context->userData);
1008		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, false);
1009		if (vf) {
1010			controller->m_backupSaveState.resize(vf->size(vf));
1011			vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
1012			vf->close(vf);
1013		}
1014		mCoreSaveState(context->core, controller->m_stateSlot, controller->m_saveStateFlags);
1015	});
1016}
1017
1018void GameController::loadBackupState() {
1019	if (!m_backupLoadState) {
1020		return;
1021	}
1022
1023	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
1024		GameController* controller = static_cast<GameController*>(context->userData);
1025		controller->m_backupLoadState->seek(controller->m_backupLoadState, 0, SEEK_SET);
1026		if (mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_loadStateFlags)) {
1027			mLOG(STATUS, INFO, "Undid state load");
1028			controller->frameAvailable(controller->m_drawContext);
1029			controller->stateLoaded(context);
1030		}
1031		controller->m_backupLoadState->close(controller->m_backupLoadState);
1032		controller->m_backupLoadState = nullptr;
1033	});
1034}
1035
1036void GameController::saveBackupState() {
1037	if (m_backupSaveState.isEmpty()) {
1038		return;
1039	}
1040
1041	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
1042		GameController* controller = static_cast<GameController*>(context->userData);
1043		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, true);
1044		if (vf) {
1045			vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
1046			vf->close(vf);
1047			mLOG(STATUS, INFO, "Undid state save");
1048		}
1049		controller->m_backupSaveState.clear();
1050	});
1051}
1052
1053void GameController::setTurbo(bool set, bool forced) {
1054	if (m_turboForced && !forced) {
1055		return;
1056	}
1057	if (m_turbo == set && m_turboForced == (set && forced)) {
1058		// Don't interrupt the thread if we don't need to
1059		return;
1060	}
1061	if (!m_sync) {
1062		return;
1063	}
1064	m_turbo = set;
1065	m_turboForced = set && forced;
1066	enableTurbo();
1067}
1068
1069void GameController::setTurboSpeed(float ratio) {
1070	m_turboSpeed = ratio;
1071	enableTurbo();
1072}
1073
1074void GameController::enableTurbo() {
1075	Interrupter interrupter(this);
1076	bool shouldRedoSamples = false;
1077	if (!m_turbo) {
1078		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget;
1079		m_threadContext.sync.fpsTarget = m_fpsTarget;
1080		m_threadContext.sync.audioWait = m_audioSync;
1081		m_threadContext.sync.videoFrameWait = m_videoSync;
1082	} else if (m_turboSpeed <= 0) {
1083		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget;
1084		m_threadContext.sync.fpsTarget = m_fpsTarget;
1085		m_threadContext.sync.audioWait = false;
1086		m_threadContext.sync.videoFrameWait = false;
1087	} else {
1088		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget * m_turboSpeed;
1089		m_threadContext.sync.fpsTarget = m_fpsTarget * m_turboSpeed;
1090		m_threadContext.sync.audioWait = true;
1091		m_threadContext.sync.videoFrameWait = false;
1092	}
1093	if (m_audioProcessor && shouldRedoSamples) {
1094		redoSamples(m_audioProcessor->getBufferSamples());
1095	}
1096}
1097
1098void GameController::setSync(bool enable) {
1099	m_turbo = false;
1100	m_turboForced = false;
1101	if (!enable) {
1102		m_threadContext.sync.audioWait = false;
1103		m_threadContext.sync.videoFrameWait = false;
1104	} else {
1105		m_threadContext.sync.audioWait = m_audioSync;
1106		m_threadContext.sync.videoFrameWait = m_videoSync;
1107	}
1108	m_sync = enable;
1109}
1110void GameController::setAVStream(mAVStream* stream) {
1111	Interrupter interrupter(this);
1112	m_stream = stream;
1113	if (isLoaded()) {
1114		m_threadContext.core->setAVStream(m_threadContext.core, stream);
1115	}
1116}
1117
1118void GameController::clearAVStream() {
1119	Interrupter interrupter(this);
1120	m_stream = nullptr;
1121	if (isLoaded()) {
1122		m_threadContext.core->setAVStream(m_threadContext.core, nullptr);
1123	}
1124}
1125
1126#ifdef USE_PNG
1127void GameController::screenshot() {
1128	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
1129		mCoreTakeScreenshot(context->core);
1130	});
1131}
1132#endif
1133
1134void GameController::reloadAudioDriver() {
1135	int samples = 0;
1136	unsigned sampleRate = 0;
1137	if (m_audioProcessor) {
1138		QMetaObject::invokeMethod(m_audioProcessor, "pause", Qt::BlockingQueuedConnection);
1139		samples = m_audioProcessor->getBufferSamples();
1140		sampleRate = m_audioProcessor->sampleRate();
1141		delete m_audioProcessor;
1142	}
1143	m_audioProcessor = AudioProcessor::create();
1144	if (samples) {
1145		m_audioProcessor->setBufferSamples(samples);
1146	}
1147	if (sampleRate) {
1148		m_audioProcessor->requestSampleRate(sampleRate);
1149	}
1150	m_audioProcessor->moveToThread(m_audioThread);
1151	connect(this, SIGNAL(gamePaused(mCoreThread*)), m_audioProcessor, SLOT(pause()));
1152	connect(this, SIGNAL(gameStarted(mCoreThread*, const QString&)), m_audioProcessor, SLOT(setInput(mCoreThread*)));
1153	if (isLoaded()) {
1154		m_audioProcessor->setInput(&m_threadContext);
1155		startAudio();
1156	}
1157}
1158
1159void GameController::setSaveStateExtdata(int flags) {
1160	m_saveStateFlags = flags;
1161}
1162
1163void GameController::setLoadStateExtdata(int flags) {
1164	m_loadStateFlags = flags;
1165}
1166
1167void GameController::setLuminanceValue(uint8_t value) {
1168	m_luxValue = value;
1169	value = std::max<int>(value - 0x16, 0);
1170	m_luxLevel = 10;
1171	for (int i = 0; i < 10; ++i) {
1172		if (value < GBA_LUX_LEVELS[i]) {
1173			m_luxLevel = i;
1174			break;
1175		}
1176	}
1177	emit luminanceValueChanged(m_luxValue);
1178}
1179
1180void GameController::setLuminanceLevel(int level) {
1181	int value = 0x16;
1182	level = std::max(0, std::min(10, level));
1183	if (level > 0) {
1184		value += GBA_LUX_LEVELS[level - 1];
1185	}
1186	setLuminanceValue(value);
1187}
1188
1189void GameController::setRealTime() {
1190	if (!isLoaded()) {
1191		return;
1192	}
1193	m_threadContext.core->rtc.override = RTC_NO_OVERRIDE;
1194}
1195
1196void GameController::setFixedTime(const QDateTime& time) {
1197	if (!isLoaded()) {
1198		return;
1199	}
1200	m_threadContext.core->rtc.override = RTC_FIXED;
1201	m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
1202}
1203
1204void GameController::setFakeEpoch(const QDateTime& time) {
1205	if (!isLoaded()) {
1206		return;
1207	}
1208	m_threadContext.core->rtc.override = RTC_FAKE_EPOCH;
1209	m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
1210}
1211
1212void GameController::updateKeys() {
1213	int activeKeys = m_activeKeys;
1214	activeKeys |= m_activeButtons;
1215	activeKeys &= ~m_inactiveKeys;
1216	if (isLoaded()) {
1217		m_threadContext.core->setKeys(m_threadContext.core, activeKeys);
1218	}
1219}
1220
1221void GameController::redoSamples(int samples) {
1222	if (m_threadContext.core) {
1223		m_threadContext.core->setAudioBufferSize(m_threadContext.core, samples);
1224	}
1225	QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
1226}
1227
1228void GameController::setLogLevel(int levels) {
1229	Interrupter interrupter(this);
1230	m_logLevels = levels;
1231}
1232
1233void GameController::enableLogLevel(int levels) {
1234	Interrupter interrupter(this);
1235	m_logLevels |= levels;
1236}
1237
1238void GameController::disableLogLevel(int levels) {
1239	Interrupter interrupter(this);
1240	m_logLevels &= ~levels;
1241}
1242
1243void GameController::pollEvents() {
1244	if (!m_inputController) {
1245		return;
1246	}
1247
1248	m_activeButtons = m_inputController->pollEvents();
1249	updateKeys();
1250}
1251
1252void GameController::updateAutofire() {
1253	// TODO: Move all key events onto the CPU thread...somehow
1254	for (int k = 0; k < GBA_KEY_MAX; ++k) {
1255		if (!m_autofire[k]) {
1256			continue;
1257		}
1258		m_autofireStatus[k] ^= 1;
1259		if (m_autofireStatus[k]) {
1260			keyPressed(k);
1261		} else {
1262			keyReleased(k);
1263		}
1264	}
1265}
1266
1267std::shared_ptr<mTileCache> GameController::tileCache() {
1268	if (m_tileCache) {
1269		return m_tileCache;
1270	}
1271	switch (platform()) {
1272#ifdef M_CORE_GBA
1273	case PLATFORM_GBA: {
1274		Interrupter interrupter(this);
1275		GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
1276		m_tileCache = std::make_shared<mTileCache>();
1277		GBAVideoTileCacheInit(m_tileCache.get());
1278		GBAVideoTileCacheAssociate(m_tileCache.get(), &gba->video);
1279		mTileCacheSetPalette(m_tileCache.get(), 0);
1280		break;
1281	}
1282#endif
1283#ifdef M_CORE_GB
1284	case PLATFORM_GB: {
1285		Interrupter interrupter(this);
1286		GB* gb = static_cast<GB*>(m_threadContext.core->board);
1287		m_tileCache = std::make_shared<mTileCache>();
1288		GBVideoTileCacheInit(m_tileCache.get());
1289		GBVideoTileCacheAssociate(m_tileCache.get(), &gb->video);
1290		mTileCacheSetPalette(m_tileCache.get(), 0);
1291		break;
1292	}
1293#endif
1294	default:
1295		return nullptr;
1296	}
1297	return m_tileCache;
1298}
1299
1300GameController::Interrupter::Interrupter(GameController* parent, bool fromThread)
1301	: m_parent(parent)
1302	, m_fromThread(fromThread)
1303{
1304	if (!m_fromThread) {
1305		m_parent->threadInterrupt();
1306	} else {
1307		mCoreThreadInterruptFromThread(m_parent->thread());
1308	}
1309}
1310
1311GameController::Interrupter::~Interrupter() {
1312	if (!m_fromThread) {
1313		m_parent->threadContinue();
1314	} else {
1315		mCoreThreadContinue(m_parent->thread());
1316	}
1317}