all repos — mgba @ 49a2a01f89a06839548d71b163534cd2d476d605

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