all repos — mgba @ 959f66a1a0faff37607a53c4da1ea7b508d6a43a

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