all repos — mgba @ d28fda120bb8a9500a33c93ef101ddc762fd009e

mGBA Game Boy Advance Emulator

src/platform/qt/FrameView.cpp (view raw)

  1/* Copyright (c) 2013-2019 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 "FrameView.h"
  7
  8#include <QMouseEvent>
  9#include <QPalette>
 10
 11#include <array>
 12#include <cmath>
 13
 14#include "CoreController.h"
 15#include "GBAApp.h"
 16
 17#include <mgba/core/core.h>
 18#include <mgba/feature/video-logger.h>
 19#ifdef M_CORE_GBA
 20#include <mgba/internal/gba/gba.h>
 21#include <mgba/internal/gba/io.h>
 22#include <mgba/internal/gba/memory.h>
 23#include <mgba/internal/gba/video.h>
 24#endif
 25#ifdef M_CORE_GB
 26#include <mgba/internal/gb/gb.h>
 27#include <mgba/internal/gb/io.h>
 28#include <mgba/internal/gb/memory.h>
 29#endif
 30
 31using namespace QGBA;
 32
 33FrameView::FrameView(std::shared_ptr<CoreController> controller, QWidget* parent)
 34	: AssetView(controller, parent)
 35{
 36	m_ui.setupUi(this);
 37
 38	m_glowTimer.setInterval(33);
 39	connect(&m_glowTimer, &QTimer::timeout, this, [this]() {
 40		++m_glowFrame;
 41		invalidateQueue();
 42	});
 43
 44	m_ui.compositedView->installEventFilter(this);
 45
 46	connect(m_ui.queue, &QListWidget::itemChanged, this, [this](QListWidgetItem* item) {
 47		Layer& layer = m_queue[item->data(Qt::UserRole).toInt()];
 48		layer.enabled = item->checkState() == Qt::Checked;
 49		if (layer.enabled) {
 50			m_disabled.remove(layer.id);
 51		} else {
 52			m_disabled.insert(layer.id);
 53		}
 54		invalidateQueue();
 55	});
 56	connect(m_ui.queue, &QListWidget::currentItemChanged, this, [this](QListWidgetItem* item) {
 57		if (item) {
 58			m_active = m_queue[item->data(Qt::UserRole).toInt()].id;
 59		} else {
 60			m_active = {};
 61		}
 62		invalidateQueue();
 63	});
 64	connect(m_ui.magnification, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, [this]() {
 65		invalidateQueue();
 66	});
 67	connect(m_ui.exportButton, &QAbstractButton::pressed, this, &FrameView::exportFrame);
 68	connect(m_ui.reset, &QAbstractButton::pressed, this, &FrameView::reset);
 69
 70	m_backdropPicker = ColorPicker(m_ui.backdrop, QColor(0, 0, 0, 0));
 71	connect(&m_backdropPicker, &ColorPicker::colorChanged, this, [this](const QColor& color) {
 72		m_overrideBackdrop = color;
 73	});
 74	m_controller->addFrameAction(std::bind(&FrameView::frameCallback, this, m_callbackLocker));
 75
 76	{
 77		CoreController::Interrupter interrupter(m_controller);
 78		refreshVl();
 79	}
 80	m_controller->frameAdvance();
 81}
 82
 83FrameView::~FrameView() {
 84	QMutexLocker locker(&m_mutex);
 85	*m_callbackLocker = false;
 86	if (m_vl) {
 87		m_vl->deinit(m_vl);
 88	}
 89}
 90
 91bool FrameView::lookupLayer(const QPointF& coord, Layer*& out) {
 92	for (Layer& layer : m_queue) {
 93		if (!layer.enabled || m_disabled.contains(layer.id)) {
 94			continue;
 95		}
 96		QPointF location = layer.location;
 97		QSizeF layerDims(layer.image.width(), layer.image.height());
 98		QRegion region;
 99		if (layer.repeats) {
100			if (location.x() + layerDims.width() < 0) {
101				location.setX(std::fmod(location.x(), layerDims.width()));
102			}
103			if (location.y() + layerDims.height() < 0) {
104				location.setY(std::fmod(location.y(), layerDims.height()));
105			}
106
107			region += layer.mask.translated(location.x(), location.y());
108			region += layer.mask.translated(location.x() + layerDims.width(), location.y());
109			region += layer.mask.translated(location.x(), location.y() + layerDims.height());
110			region += layer.mask.translated(location.x() + layerDims.width(), location.y() + layerDims.height());
111		} else {
112			region = layer.mask.translated(location.x(), location.y());
113		}
114
115		if (region.contains(QPoint(coord.x(), coord.y()))) {
116			out = &layer;
117			return true;
118		}
119	}
120	return false;
121}
122
123void FrameView::selectLayer(const QPointF& coord) {
124	Layer* layer;
125	if (!lookupLayer(coord, layer)) {
126		return;
127	}
128	if (layer->id == m_active) {
129		m_active = {};
130	} else {
131		m_active = layer->id;
132	}
133	m_glowFrame = 0;
134}
135
136void FrameView::disableLayer(const QPointF& coord) {
137	Layer* layer;
138	if (!lookupLayer(coord, layer)) {
139		return;
140	}
141	layer->enabled = false;
142	m_disabled.insert(layer->id);
143}
144
145#ifdef M_CORE_GBA
146void FrameView::updateTilesGBA(bool) {
147	if (m_ui.freeze->checkState() == Qt::Checked) {
148		return;
149	}
150	QMutexLocker locker(&m_mutex);
151	m_queue.clear();
152	{
153		CoreController::Interrupter interrupter(m_controller);
154
155		uint16_t* io = static_cast<GBA*>(m_controller->thread()->core->board)->memory.io;
156		QRgb backdrop = M_RGB5_TO_RGB8(static_cast<GBA*>(m_controller->thread()->core->board)->video.palette[0]);
157		GBARegisterDISPCNT gbaDispcnt = io[REG_DISPCNT >> 1];
158		int mode = GBARegisterDISPCNTGetMode(gbaDispcnt);
159
160		std::array<bool, 4> enabled{
161			bool(GBARegisterDISPCNTIsBg0Enable(gbaDispcnt)),
162			bool(GBARegisterDISPCNTIsBg1Enable(gbaDispcnt)),
163			bool(GBARegisterDISPCNTIsBg2Enable(gbaDispcnt)),
164			bool(GBARegisterDISPCNTIsBg3Enable(gbaDispcnt)),
165		};
166
167		if (GBARegisterDISPCNTIsWin0Enable(gbaDispcnt)) {
168			m_queue.append({
169				{ LayerId::WINDOW, 0 },
170				!m_disabled.contains({ LayerId::WINDOW, 0 }),
171				{},
172				{}, {0, 0}, true, false
173			});
174		}
175
176		if (GBARegisterDISPCNTIsWin1Enable(gbaDispcnt)) {
177			m_queue.append({
178				{ LayerId::WINDOW, 1 },
179				!m_disabled.contains({ LayerId::WINDOW, 1 }),
180				{},
181				{}, {0, 0}, true, false
182			});
183		}
184
185		if (GBARegisterDISPCNTIsObjwinEnable(gbaDispcnt)) {
186			m_queue.append({
187				{ LayerId::WINDOW, 2 },
188				!m_disabled.contains({ LayerId::WINDOW, 2 }),
189				{},
190				{}, {0, 0}, true, false
191			});
192
193		}
194
195		for (int priority = 0; priority < 4; ++priority) {
196			for (int sprite = 0; sprite < 128; ++sprite) {
197				ObjInfo info;
198				lookupObj(sprite, &info);
199
200				if (!info.enabled || info.priority != priority) {
201					continue;
202				}
203
204				QPointF offset(info.x, info.y);
205				QImage obj(compositeObj(info));
206				if (info.hflip || info.vflip) {
207					obj = obj.mirrored(info.hflip, info.vflip);
208				}
209				if (!info.xform.isIdentity()) {
210					offset += QPointF(obj.width(), obj.height()) / 2;
211					obj = obj.transformed(info.xform);
212					offset -= QPointF(obj.width() / 2, obj.height() / 2);
213				}
214				m_queue.append({
215					{ LayerId::SPRITE, sprite },
216					!m_disabled.contains({ LayerId::SPRITE, sprite }),
217					QPixmap::fromImage(obj),
218					{}, offset, false, false
219				});
220				if (m_queue.back().image.hasAlpha()) {
221					m_queue.back().mask = QRegion(m_queue.back().image.mask());
222				} else {
223					m_queue.back().mask = QRegion(0, 0, m_queue.back().image.width(), m_queue.back().image.height());
224				}
225			}
226
227			for (int bg = 0; bg < 4; ++bg) {
228				if (!enabled[bg]) {
229					continue;
230				}
231				if (GBARegisterBGCNTGetPriority(io[(REG_BG0CNT >> 1) + bg]) != priority) {
232					continue;
233				}
234
235				QPointF offset;
236				if (mode == 0) {
237					offset.setX(-(io[(REG_BG0HOFS >> 1) + (bg << 1)] & 0x1FF));
238					offset.setY(-(io[(REG_BG0VOFS >> 1) + (bg << 1)] & 0x1FF));
239				};
240				m_queue.append({
241					{ LayerId::BACKGROUND, bg },
242					!m_disabled.contains({ LayerId::BACKGROUND, bg }),
243					QPixmap::fromImage(compositeMap(bg, m_mapStatus[bg])),
244					{}, offset, true, false
245				});
246				if (m_queue.back().image.hasAlpha()) {
247					m_queue.back().mask = QRegion(m_queue.back().image.mask());
248				} else {
249					m_queue.back().mask = QRegion(0, 0, m_queue.back().image.width(), m_queue.back().image.height());
250				}
251			}
252		}
253		QImage backdropImage(QSize(GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS), QImage::Format_Mono);
254		backdropImage.fill(1);
255		backdropImage.setColorTable({backdrop, backdrop | 0xFF000000 });
256		m_queue.append({
257			{ LayerId::BACKDROP },
258			!m_disabled.contains({ LayerId::BACKDROP }),
259			QPixmap::fromImage(backdropImage),
260			{}, {0, 0}, false, true
261		});
262		updateRendered();
263	}
264	invalidateQueue(QSize(GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS));
265}
266
267void FrameView::injectGBA() {
268	mVideoLogger* logger = m_vl->videoLogger;
269	GBA* gba = static_cast<GBA*>(m_vl->board);
270	gba->video.renderer->highlightBG[0] = false;
271	gba->video.renderer->highlightBG[1] = false;
272	gba->video.renderer->highlightBG[2] = false;
273	gba->video.renderer->highlightBG[3] = false;
274	for (int i = 0; i < 128; ++i) {
275		gba->video.renderer->highlightOBJ[i] = false;
276	}
277	QPalette palette;
278	gba->video.renderer->highlightColor = M_RGB8_TO_NATIVE(palette.color(QPalette::Highlight).rgb());
279	gba->video.renderer->highlightAmount = sin(m_glowFrame * M_PI / 30) * 48 + 64;
280	if (!m_overrideBackdrop.isValid()) {
281		QRgb backdrop = M_RGB5_TO_RGB8(gba->video.palette[0]) | 0xFF000000;
282		m_backdropPicker.setColor(backdrop);
283	}
284
285	m_vl->reset(m_vl);
286	for (const Layer& layer : m_queue) {
287		switch (layer.id.type) {
288		case LayerId::SPRITE:
289			if (!layer.enabled) {
290				mVideoLoggerInjectOAM(logger, layer.id.index << 2, 0x200);
291			}
292			if (layer.id == m_active) {
293				gba->video.renderer->highlightOBJ[layer.id.index] = true;
294			}
295			break;
296		case LayerId::BACKGROUND:
297			m_vl->enableVideoLayer(m_vl, layer.id.index, layer.enabled);
298			if (layer.id == m_active) {
299				gba->video.renderer->highlightBG[layer.id.index] = true;
300			}
301			break;
302		case LayerId::WINDOW:
303			m_vl->enableVideoLayer(m_vl, GBA_LAYER_WIN0 + layer.id.index, layer.enabled);
304			break;
305		}
306	}
307	if (m_overrideBackdrop.isValid()) {
308		mVideoLoggerInjectPalette(logger, 0, M_RGB8_TO_RGB5(m_overrideBackdrop.rgb()));
309	}
310}
311#endif
312
313#ifdef M_CORE_GB
314void FrameView::updateTilesGB(bool) {
315	if (m_ui.freeze->checkState() == Qt::Checked) {
316		return;
317	}
318	m_queue.clear();
319	{
320		CoreController::Interrupter interrupter(m_controller);
321		QPointF origin;
322		GB* gb = static_cast<GB*>(m_controller->thread()->core->board);
323		if (gb->video.sgbBorders && (gb->model & GB_MODEL_SGB)) {
324			origin = QPointF(48, 40);
325		}
326		uint8_t* io = gb->memory.io;
327		GBRegisterLCDC lcdc = io[GB_REG_LCDC];
328
329		for (int sprite = 0; sprite < 40; ++sprite) {
330			ObjInfo info;
331			lookupObj(sprite, &info);
332
333			if (!info.enabled) {
334				continue;
335			}
336
337			QPointF offset(info.x, info.y);
338			QImage obj(compositeObj(info));
339			if (info.hflip || info.vflip) {
340				obj = obj.mirrored(info.hflip, info.vflip);
341			}
342			m_queue.append({
343				{ LayerId::SPRITE, sprite },
344				!m_disabled.contains({ LayerId::SPRITE, sprite }),
345				QPixmap::fromImage(obj),
346				{}, offset + origin, false, false
347			});
348			if (m_queue.back().image.hasAlpha()) {
349				m_queue.back().mask = QRegion(m_queue.back().image.mask());
350			} else {
351				m_queue.back().mask = QRegion(0, 0, m_queue.back().image.width(), m_queue.back().image.height());
352			}
353		}
354
355		if (GBRegisterLCDCIsWindow(lcdc)) {
356			m_queue.append({
357				{ LayerId::WINDOW },
358				!m_disabled.contains({ LayerId::WINDOW }),
359				{},
360				{}, origin, false, false
361			});
362		}
363
364		m_queue.append({
365			{ LayerId::BACKGROUND },
366			!m_disabled.contains({ LayerId::BACKGROUND }),
367			{},
368			{}, origin, false, false
369		});
370
371		updateRendered();
372	}
373	invalidateQueue(m_controller->screenDimensions());
374}
375
376void FrameView::injectGB() {
377	mVideoLogger* logger = m_vl->videoLogger;
378	GB* gb = static_cast<GB*>(m_vl->board);
379	gb->video.renderer->highlightBG = false;
380	gb->video.renderer->highlightWIN = false;
381	for (int i = 0; i < 40; ++i) {
382		gb->video.renderer->highlightOBJ[i] = false;
383	}
384	QPalette palette;
385	gb->video.renderer->highlightColor = M_RGB8_TO_NATIVE(palette.color(QPalette::Highlight).rgb());
386	gb->video.renderer->highlightAmount = sin(m_glowFrame * M_PI / 30) * 48 + 64;
387
388	m_vl->reset(m_vl);
389	for (const Layer& layer : m_queue) {
390		switch (layer.id.type) {
391		case LayerId::SPRITE:
392			if (!layer.enabled) {
393				mVideoLoggerInjectOAM(logger, layer.id.index << 2, 0);
394			}
395			if (layer.id == m_active) {
396				gb->video.renderer->highlightOBJ[layer.id.index] = true;
397			}
398			break;
399		case LayerId::BACKGROUND:
400			m_vl->enableVideoLayer(m_vl, GB_LAYER_BACKGROUND, layer.enabled);
401			if (layer.id == m_active) {
402				gb->video.renderer->highlightBG = true;
403			}
404			break;
405		case LayerId::WINDOW:
406			m_vl->enableVideoLayer(m_vl, GB_LAYER_WINDOW, layer.enabled);
407			if (layer.id == m_active) {
408				gb->video.renderer->highlightWIN = true;
409			}
410			break;
411		}
412	}
413}
414#endif
415
416void FrameView::invalidateQueue(const QSize& dims) {
417	if (dims.isValid()) {
418		m_dims = dims;
419	}
420	bool blockSignals = m_ui.queue->blockSignals(true);
421	QMutexLocker locker(&m_mutex);
422	if (m_vl) {
423		mVideoLogger* logger = m_vl->videoLogger;
424		mVideoLoggerInjectionPoint(logger, LOGGER_INJECTION_FIRST_SCANLINE);
425		switch (m_controller->platform()) {
426#ifdef M_CORE_GBA
427		case PLATFORM_GBA:
428			injectGBA();
429			break;
430#endif
431#ifdef M_CORE_GB
432		case PLATFORM_GB:
433			injectGB();
434			break;
435#endif
436		}
437		if (m_ui.disableScanline->checkState() == Qt::Checked) {
438			mVideoLoggerIgnoreAfterInjection(logger, (1 << DIRTY_PALETTE) | (1 << DIRTY_OAM) | (1 << DIRTY_REGISTER));
439		} else {
440			mVideoLoggerIgnoreAfterInjection(logger, 0);
441		}
442		m_vl->runFrame(m_vl);
443	}
444
445	for (int i = 0; i < m_queue.count(); ++i) {
446		const Layer& layer = m_queue[i];
447		QListWidgetItem* item;
448		if (i >= m_ui.queue->count()) {
449			item = new QListWidgetItem;
450			m_ui.queue->addItem(item);
451		} else {
452			item = m_ui.queue->item(i);
453		}
454		item->setText(layer.id.readable());
455		item->setFlags(Qt::ItemIsSelectable | (layer.fixed ? Qt::NoItemFlags : Qt::ItemIsUserCheckable) | Qt::ItemIsEnabled);
456		item->setCheckState(layer.enabled ? Qt::Checked : Qt::Unchecked);
457		item->setData(Qt::UserRole, i);
458		item->setSelected(layer.id == m_active);
459	}
460
461	while (m_ui.queue->count() > m_queue.count()) {
462		delete m_ui.queue->takeItem(m_queue.count());
463	}
464	m_ui.queue->blockSignals(blockSignals);
465
466	QPixmap composited;
467	if (m_framebuffer.isNull()) {
468		updateRendered();
469		composited = m_rendered;
470	} else {
471		QImage framebuffer(m_framebuffer);
472		m_ui.exportButton->setEnabled(true);
473		if (framebuffer.size() != m_dims) {
474			framebuffer = framebuffer.copy({QPoint(), m_dims});
475		}
476		composited.convertFromImage(framebuffer);
477	}
478	m_composited = composited.scaled(m_dims * m_ui.magnification->value());
479	m_ui.compositedView->setPixmap(m_composited);
480}
481
482void FrameView::updateRendered() {
483	if (m_ui.freeze->checkState() == Qt::Checked) {
484		return;
485	}
486	m_rendered.convertFromImage(m_controller->getPixels());
487}
488
489bool FrameView::eventFilter(QObject*, QEvent* event) {
490	QPointF pos;
491	switch (event->type()) {
492	case QEvent::MouseButtonPress:
493		pos = static_cast<QMouseEvent*>(event)->localPos();
494		pos /= m_ui.magnification->value();
495		selectLayer(pos);
496		return true;
497	case QEvent::MouseButtonDblClick:
498		pos = static_cast<QMouseEvent*>(event)->localPos();
499		pos /= m_ui.magnification->value();
500		disableLayer(pos);
501		return true;
502	default:
503		break;
504	}
505	return false;
506}
507
508void FrameView::refreshVl() {
509	QMutexLocker locker(&m_mutex);
510	m_currentFrame = m_nextFrame;
511	m_nextFrame = VFileMemChunk(nullptr, 0);
512	if (m_currentFrame) {
513		m_controller->endVideoLog(false);
514		QMetaObject::invokeMethod(this, "newVl");
515	}
516	m_controller->endVideoLog();
517	m_controller->startVideoLog(m_nextFrame, false);
518}
519
520void FrameView::newVl() {
521	if (!m_glowTimer.isActive()) {
522		m_glowTimer.start();
523	}
524	QMutexLocker locker(&m_mutex);
525	if (!m_currentFrame) {
526		return;
527	}
528	if (m_vl) {
529		m_vl->deinit(m_vl);
530	}
531	m_vl = mCoreFindVF(m_currentFrame);
532	m_vl->init(m_vl);
533	m_vl->loadROM(m_vl, m_currentFrame);
534	m_currentFrame = nullptr;
535	mCoreInitConfig(m_vl, nullptr);
536#ifdef M_CORE_GB
537	if (m_controller->platform() == PLATFORM_GB) {
538		mCoreConfigSetIntValue(&m_vl->config, "sgb.borders", static_cast<GB*>(m_controller->thread()->core->board)->video.sgbBorders);
539		m_vl->reloadConfigOption(m_vl, "sgb.borders", nullptr);
540	}
541#endif
542	unsigned width, height;
543	m_vl->desiredVideoDimensions(m_vl, &width, &height);
544	m_framebuffer = QImage(width, height, QImage::Format_RGBX8888);
545	m_vl->setVideoBuffer(m_vl, reinterpret_cast<color_t*>(m_framebuffer.bits()), width);
546	m_vl->reset(m_vl);
547}
548
549void FrameView::frameCallback(FrameView* viewer, std::shared_ptr<bool> lock) {
550	if (!*lock) {
551		return;
552	}
553	CoreController::Interrupter interrupter(viewer->m_controller);
554	viewer->refreshVl();
555	viewer->m_controller->addFrameAction(std::bind(&FrameView::frameCallback, viewer, lock));
556}
557
558void FrameView::exportFrame() {
559	QString filename = GBAApp::app()->getSaveFileName(this, tr("Export frame"),
560	                                                  tr("Portable Network Graphics (*.png)"));
561	CoreController::Interrupter interrupter(m_controller);
562	m_framebuffer.save(filename, "PNG");
563}
564
565void FrameView::reset() {
566	m_disabled.clear();
567	for (Layer& layer : m_queue) {
568		layer.enabled = true;
569	}
570	m_overrideBackdrop = QColor();
571	invalidateQueue();
572}
573
574QString FrameView::LayerId::readable() const {
575	QString typeStr;
576	switch (type) {
577	case NONE:
578		return tr("None");
579	case BACKGROUND:
580		typeStr = tr("Background");
581		break;
582	case WINDOW:
583		typeStr = tr("Window");
584#ifdef M_CORE_GBA
585		if (index == 2) {
586			return tr("Objwin");
587		}
588#endif
589		break;
590	case SPRITE:
591		typeStr = tr("Sprite");
592		break;
593	case BACKDROP:
594		typeStr = tr("Backdrop");
595		break;
596	case FRAME:
597		typeStr = tr("Frame");
598		break;
599	}
600	if (index < 0) {
601		return typeStr;
602	}
603	return tr("%1 %2").arg(typeStr).arg(index);
604}