all repos — mgba @ 50402c830729f2ba5a6fc3e6facfd8b258f7f97d

mGBA Game Boy Advance Emulator

src/platform/3ds/main.c (view raw)

  1/* Copyright (c) 2013-2015 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
  7#include "gba/renderers/video-software.h"
  8#include "gba/context/context.h"
  9#include "gba/gui/gui-runner.h"
 10#include "gba/video.h"
 11#include "util/gui.h"
 12#include "util/gui/file-select.h"
 13#include "util/gui/font.h"
 14#include "util/gui/menu.h"
 15#include "util/memory.h"
 16
 17#include "3ds-vfs.h"
 18#include "ctr-gpu.h"
 19
 20#include <3ds.h>
 21
 22static enum ScreenMode {
 23	SM_PA_BOTTOM,
 24	SM_AF_BOTTOM,
 25	SM_SF_BOTTOM,
 26	SM_PA_TOP,
 27	SM_AF_TOP,
 28	SM_SF_TOP,
 29	SM_MAX
 30} screenMode = SM_PA_TOP;
 31
 32#define AUDIO_SAMPLES 0x80
 33#define AUDIO_SAMPLE_BUFFER (AUDIO_SAMPLES * 24)
 34
 35FS_archive sdmcArchive;
 36
 37static struct GBA3DSRotationSource {
 38	struct GBARotationSource d;
 39	accelVector accel;
 40	angularRate gyro;
 41} rotation;
 42
 43static bool hasSound;
 44// TODO: Move into context
 45static struct GBAVideoSoftwareRenderer renderer;
 46static struct GBAAVStream stream;
 47static int16_t* audioLeft = 0;
 48static int16_t* audioRight = 0;
 49static size_t audioPos = 0;
 50static struct ctrTexture gbaOutputTexture;
 51static int guiDrawn;
 52static int screenCleanup;
 53
 54enum {
 55	GUI_ACTIVE = 1,
 56	GUI_THIS_FRAME = 2,
 57};
 58
 59enum {
 60	SCREEN_CLEANUP_TOP_1 = 1,
 61	SCREEN_CLEANUP_TOP_2 = 2,
 62	SCREEN_CLEANUP_TOP = SCREEN_CLEANUP_TOP_1 | SCREEN_CLEANUP_TOP_2,
 63	SCREEN_CLEANUP_BOTTOM_1 = 4,
 64	SCREEN_CLEANUP_BOTTOM_2 = 8,
 65	SCREEN_CLEANUP_BOTTOM = SCREEN_CLEANUP_BOTTOM_1 | SCREEN_CLEANUP_BOTTOM_2,
 66};
 67
 68extern bool allocateRomBuffer(void);
 69
 70static void _postAudioBuffer(struct GBAAVStream* stream, struct GBAAudio* audio);
 71
 72static void _drawStart(void) {
 73	ctrGpuBeginDrawing();
 74	if (screenMode < SM_PA_TOP || (guiDrawn & GUI_ACTIVE)) {
 75		ctrGpuBeginFrame(GFX_BOTTOM);
 76		ctrSetViewportSize(320, 240);
 77	} else {
 78		ctrGpuBeginFrame(GFX_TOP);
 79		ctrSetViewportSize(400, 240);
 80	}
 81	guiDrawn &= ~GUI_THIS_FRAME;
 82}
 83
 84static void _drawEnd(void) {
 85	int screen = screenMode < SM_PA_TOP ? GFX_BOTTOM : GFX_TOP;
 86	u16 width = 0, height = 0;
 87
 88	void* outputFramebuffer = gfxGetFramebuffer(screen, GFX_LEFT, &height, &width);
 89	ctrGpuEndFrame(screen, outputFramebuffer, width, height);
 90
 91	if (screen != GFX_BOTTOM) {
 92		if (guiDrawn & (GUI_THIS_FRAME | GUI_ACTIVE)) {
 93			void* outputFramebuffer = gfxGetFramebuffer(GFX_BOTTOM, GFX_LEFT, &height, &width);
 94			ctrGpuEndFrame(GFX_BOTTOM, outputFramebuffer, width, height);
 95		} else if (screenCleanup & SCREEN_CLEANUP_BOTTOM) {
 96			ctrGpuBeginFrame(GFX_BOTTOM);
 97			if (screenCleanup & SCREEN_CLEANUP_BOTTOM_1) {
 98				screenCleanup &= ~SCREEN_CLEANUP_BOTTOM_1;
 99			} else if (screenCleanup & SCREEN_CLEANUP_BOTTOM_2) {
100				screenCleanup &= ~SCREEN_CLEANUP_BOTTOM_2;
101			}
102			void* outputFramebuffer = gfxGetFramebuffer(GFX_BOTTOM, GFX_LEFT, &height, &width);
103			ctrGpuEndFrame(GFX_BOTTOM, outputFramebuffer, width, height);
104		}
105	}
106
107	if ((screenCleanup & SCREEN_CLEANUP_TOP) && screen != GFX_TOP) {
108		ctrGpuBeginFrame(GFX_TOP);
109		if (screenCleanup & SCREEN_CLEANUP_TOP_1) {
110			screenCleanup &= ~SCREEN_CLEANUP_TOP_1;
111		} else if (screenCleanup & SCREEN_CLEANUP_TOP_2) {
112			screenCleanup &= ~SCREEN_CLEANUP_TOP_2;
113		}
114		void* outputFramebuffer = gfxGetFramebuffer(GFX_TOP, GFX_LEFT, &height, &width);
115		ctrGpuEndFrame(GFX_TOP, outputFramebuffer, width, height);
116	}
117
118	ctrGpuEndDrawing();
119}
120
121static int _batteryState(void) {
122	u8 charge;
123	u8 adapter;
124	PTMU_GetBatteryLevel(0, &charge);
125	PTMU_GetBatteryChargeState(0, &adapter);
126	int state = 0;
127	if (adapter) {
128		state |= BATTERY_CHARGING;
129	}
130	if (charge > 0) {
131		--charge;
132	}
133	return state | charge;
134}
135
136static void _guiPrepare(void) {
137	guiDrawn = GUI_ACTIVE | GUI_THIS_FRAME;
138	int screen = screenMode < SM_PA_TOP ? GFX_BOTTOM : GFX_TOP;
139	if (screen == GFX_BOTTOM) {
140		return;
141	}
142
143	ctrFlushBatch();
144	ctrGpuBeginFrame(GFX_BOTTOM);
145	ctrSetViewportSize(320, 240);
146}
147
148static void _guiFinish(void) {
149	guiDrawn &= ~GUI_ACTIVE;
150	screenCleanup |= SCREEN_CLEANUP_BOTTOM;
151}
152
153static void _setup(struct GBAGUIRunner* runner) {
154	runner->context.gba->rotationSource = &rotation.d;
155	if (hasSound) {
156		runner->context.gba->stream = &stream;
157	}
158
159	GBAVideoSoftwareRendererCreate(&renderer);
160	renderer.outputBuffer = linearMemAlign(256 * VIDEO_VERTICAL_PIXELS * 2, 0x80);
161	renderer.outputBufferStride = 256;
162	runner->context.renderer = &renderer.d;
163
164	unsigned mode;
165	if (GBAConfigGetUIntValue(&runner->context.config, "screenMode", &mode) && mode < SM_MAX) {
166		screenMode = mode;
167	}
168
169	GBAAudioResizeBuffer(&runner->context.gba->audio, AUDIO_SAMPLES);
170}
171
172static void _gameLoaded(struct GBAGUIRunner* runner) {
173	if (runner->context.gba->memory.hw.devices & HW_TILT) {
174		HIDUSER_EnableAccelerometer();
175	}
176	if (runner->context.gba->memory.hw.devices & HW_GYRO) {
177		HIDUSER_EnableGyroscope();
178	}
179
180#if RESAMPLE_LIBRARY == RESAMPLE_BLIP_BUF
181	double ratio = GBAAudioCalculateRatio(1, 59.8260982880808, 1);
182	blip_set_rates(runner->context.gba->audio.left,  GBA_ARM7TDMI_FREQUENCY, 32768 * ratio);
183	blip_set_rates(runner->context.gba->audio.right, GBA_ARM7TDMI_FREQUENCY, 32768 * ratio);
184#endif
185	if (hasSound) {
186		memset(audioLeft, 0, AUDIO_SAMPLE_BUFFER * sizeof(int16_t));
187		memset(audioRight, 0, AUDIO_SAMPLE_BUFFER * sizeof(int16_t));
188		audioPos = 0;
189		csndPlaySound(0x8, SOUND_REPEAT | SOUND_FORMAT_16BIT, 32768, 1.0, -1.0, audioLeft, audioLeft, AUDIO_SAMPLE_BUFFER * sizeof(int16_t));
190		csndPlaySound(0x9, SOUND_REPEAT | SOUND_FORMAT_16BIT, 32768, 1.0, 1.0, audioRight, audioRight, AUDIO_SAMPLE_BUFFER * sizeof(int16_t));
191	}
192	unsigned mode;
193	if (GBAConfigGetUIntValue(&runner->context.config, "screenMode", &mode) && mode != screenMode) {
194		screenMode = mode;
195		screenCleanup |= SCREEN_CLEANUP_BOTTOM | SCREEN_CLEANUP_TOP;
196	}
197}
198
199static void _gameUnloaded(struct GBAGUIRunner* runner) {
200	if (hasSound) {
201		CSND_SetPlayState(8, 0);
202		CSND_SetPlayState(9, 0);
203		csndExecCmds(false);
204	}
205
206	if (runner->context.gba->memory.hw.devices & HW_TILT) {
207		HIDUSER_DisableAccelerometer();
208	}
209	if (runner->context.gba->memory.hw.devices & HW_GYRO) {
210		HIDUSER_DisableGyroscope();
211	}
212}
213
214static void _drawTex(bool faded) {
215	u32 color = faded ? 0x3FFFFFFF : 0xFFFFFFFF;
216
217	int screen_w = screenMode < SM_PA_TOP ? 320 : 400;
218	int screen_h = 240;
219
220	int w, h;
221
222	switch (screenMode) {
223	case SM_PA_TOP:
224	case SM_PA_BOTTOM:
225	default:
226		w = VIDEO_HORIZONTAL_PIXELS;
227		h = VIDEO_VERTICAL_PIXELS;
228		break;
229	case SM_AF_TOP:
230		w = 360;
231		h = 240;
232		break;
233	case SM_AF_BOTTOM:
234		// Largest possible size with 3:2 aspect ratio and integer dimensions
235		w = 318;
236		h = 212;
237		break;
238	case SM_SF_TOP:
239	case SM_SF_BOTTOM:
240		w = screen_w;
241		h = screen_h;
242		break;
243	}
244
245	int x = (screen_w - w) / 2;
246	int y = (screen_h - h) / 2;
247
248	ctrAddRectScaled(color, x, y, w, h, 0, 0, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
249}
250
251static void _drawFrame(struct GBAGUIRunner* runner, bool faded) {
252	UNUSED(runner);
253
254	void* outputBuffer = renderer.outputBuffer;
255	struct ctrTexture* tex = &gbaOutputTexture;
256
257	GSPGPU_FlushDataCache(NULL, outputBuffer, 256 * VIDEO_VERTICAL_PIXELS * 2);
258	GX_SetDisplayTransfer(NULL,
259			outputBuffer, GX_BUFFER_DIM(256, VIDEO_VERTICAL_PIXELS),
260			tex->data, GX_BUFFER_DIM(256, 256),
261			GX_TRANSFER_IN_FORMAT(GX_TRANSFER_FMT_RGB565) |
262				GX_TRANSFER_OUT_FORMAT(GX_TRANSFER_FMT_RGB565) |
263				GX_TRANSFER_OUT_TILED(1) | GX_TRANSFER_FLIP_VERT(1));
264
265#if RESAMPLE_LIBRARY == RESAMPLE_BLIP_BUF
266	if (!hasSound) {
267		blip_clear(runner->context.gba->audio.left);
268		blip_clear(runner->context.gba->audio.right);
269	}
270#endif
271
272	gspWaitForPPF();
273	ctrActivateTexture(tex);
274	_drawTex(faded);
275}
276
277static void _drawScreenshot(struct GBAGUIRunner* runner, const uint32_t* pixels, bool faded) {
278	UNUSED(runner);
279
280	struct ctrTexture* tex = &gbaOutputTexture;
281
282	u16* newPixels = linearMemAlign(256 * VIDEO_VERTICAL_PIXELS * sizeof(u32), 0x100);
283
284	// Convert image from RGBX8 to BGR565
285	for (unsigned y = 0; y < VIDEO_VERTICAL_PIXELS; ++y) {
286		for (unsigned x = 0; x < VIDEO_HORIZONTAL_PIXELS; ++x) {
287			// 0xXXBBGGRR -> 0bRRRRRGGGGGGBBBBB
288			u32 p = *pixels++;
289			newPixels[y * 256 + x] =
290				(p << 24 >> (24 + 3) << 11) | // R
291				(p << 16 >> (24 + 2) <<  5) | // G
292				(p <<  8 >> (24 + 3) <<  0);  // B
293		}
294		memset(&newPixels[y * 256 + VIDEO_HORIZONTAL_PIXELS], 0, (256 - VIDEO_HORIZONTAL_PIXELS) * sizeof(u32));
295	}
296
297	GSPGPU_FlushDataCache(NULL, (void*)newPixels, 256 * VIDEO_VERTICAL_PIXELS * sizeof(u32));
298	GX_SetDisplayTransfer(NULL,
299			(void*)newPixels, GX_BUFFER_DIM(256, VIDEO_VERTICAL_PIXELS),
300			tex->data, GX_BUFFER_DIM(256, 256),
301			GX_TRANSFER_IN_FORMAT(GX_TRANSFER_FMT_RGB565) |
302				GX_TRANSFER_OUT_FORMAT(GX_TRANSFER_FMT_RGB565) |
303				GX_TRANSFER_OUT_TILED(1) | GX_TRANSFER_FLIP_VERT(1));
304	gspWaitForPPF();
305	linearFree(newPixels);
306
307	ctrActivateTexture(tex);
308	_drawTex(faded);
309}
310
311static uint16_t _pollGameInput(struct GBAGUIRunner* runner) {
312	UNUSED(runner);
313
314	hidScanInput();
315	uint32_t activeKeys = hidKeysHeld() & 0xF00003FF;
316	activeKeys |= activeKeys >> 24;
317	return activeKeys;
318}
319
320static void _incrementScreenMode(struct GBAGUIRunner* runner) {
321	UNUSED(runner);
322	screenCleanup |= SCREEN_CLEANUP_TOP | SCREEN_CLEANUP_BOTTOM;
323	screenMode = (screenMode + 1) % SM_MAX;
324	GBAConfigSetUIntValue(&runner->context.config, "screenMode", screenMode);
325}
326
327static uint32_t _pollInput(void) {
328	hidScanInput();
329	uint32_t keys = 0;
330	int activeKeys = hidKeysHeld();
331	if (activeKeys & KEY_X) {
332		keys |= 1 << GUI_INPUT_CANCEL;
333	}
334	if (activeKeys & KEY_Y) {
335		keys |= 1 << GBA_GUI_INPUT_SCREEN_MODE;
336	}
337	if (activeKeys & KEY_B) {
338		keys |= 1 << GUI_INPUT_BACK;
339	}
340	if (activeKeys & KEY_A) {
341		keys |= 1 << GUI_INPUT_SELECT;
342	}
343	if (activeKeys & KEY_LEFT) {
344		keys |= 1 << GUI_INPUT_LEFT;
345	}
346	if (activeKeys & KEY_RIGHT) {
347		keys |= 1 << GUI_INPUT_RIGHT;
348	}
349	if (activeKeys & KEY_UP) {
350		keys |= 1 << GUI_INPUT_UP;
351	}
352	if (activeKeys & KEY_DOWN) {
353		keys |= 1 << GUI_INPUT_DOWN;
354	}
355	if (activeKeys & KEY_CSTICK_UP) {
356		keys |= 1 << GBA_GUI_INPUT_INCREASE_BRIGHTNESS;
357	}
358	if (activeKeys & KEY_CSTICK_DOWN) {
359		keys |= 1 << GBA_GUI_INPUT_DECREASE_BRIGHTNESS;
360	}
361	return keys;
362}
363
364static enum GUICursorState _pollCursor(int* x, int* y) {
365	hidScanInput();
366	if (!(hidKeysHeld() & KEY_TOUCH)) {
367		return GUI_CURSOR_NOT_PRESENT;
368	}
369	touchPosition pos;
370	hidTouchRead(&pos);
371	*x = pos.px;
372	*y = pos.py;
373	return GUI_CURSOR_DOWN;
374}
375
376static void _sampleRotation(struct GBARotationSource* source) {
377	struct GBA3DSRotationSource* rotation = (struct GBA3DSRotationSource*) source;
378	// Work around ctrulib getting the entries wrong
379	rotation->accel = *(accelVector*)& hidSharedMem[0x48];
380	rotation->gyro = *(angularRate*)& hidSharedMem[0x5C];
381}
382
383static int32_t _readTiltX(struct GBARotationSource* source) {
384	struct GBA3DSRotationSource* rotation = (struct GBA3DSRotationSource*) source;
385	return rotation->accel.x << 18L;
386}
387
388static int32_t _readTiltY(struct GBARotationSource* source) {
389	struct GBA3DSRotationSource* rotation = (struct GBA3DSRotationSource*) source;
390	return rotation->accel.y << 18L;
391}
392
393static int32_t _readGyroZ(struct GBARotationSource* source) {
394	struct GBA3DSRotationSource* rotation = (struct GBA3DSRotationSource*) source;
395	return rotation->gyro.y << 18L; // Yes, y
396}
397
398static void _postAudioBuffer(struct GBAAVStream* stream, struct GBAAudio* audio) {
399	UNUSED(stream);
400#if RESAMPLE_LIBRARY == RESAMPLE_BLIP_BUF
401	blip_read_samples(audio->left, &audioLeft[audioPos], AUDIO_SAMPLES, false);
402	blip_read_samples(audio->right, &audioRight[audioPos], AUDIO_SAMPLES, false);
403#elif RESAMPLE_LIBRARY == RESAMPLE_NN
404	GBAAudioCopy(audio, &audioLeft[audioPos], &audioRight[audioPos], AUDIO_SAMPLES);
405#endif
406	GSPGPU_FlushDataCache(0, (void*) &audioLeft[audioPos], AUDIO_SAMPLES * sizeof(int16_t));
407	GSPGPU_FlushDataCache(0, (void*) &audioRight[audioPos], AUDIO_SAMPLES * sizeof(int16_t));
408	audioPos = (audioPos + AUDIO_SAMPLES) % AUDIO_SAMPLE_BUFFER;
409	if (audioPos == AUDIO_SAMPLES * 3) {
410		u8 playing = 0;
411		csndIsPlaying(0x8, &playing);
412		if (!playing) {
413			CSND_SetPlayState(0x8, 1);
414			CSND_SetPlayState(0x9, 1);
415			csndExecCmds(false);
416		}
417	}
418}
419
420int main() {
421	ptmInit();
422	hasSound = !csndInit();
423
424	rotation.d.sample = _sampleRotation;
425	rotation.d.readTiltX = _readTiltX;
426	rotation.d.readTiltY = _readTiltY;
427	rotation.d.readGyroZ = _readGyroZ;
428
429	stream.postVideoFrame = 0;
430	stream.postAudioFrame = 0;
431	stream.postAudioBuffer = _postAudioBuffer;
432
433	if (!allocateRomBuffer()) {
434		return 1;
435	}
436
437	if (hasSound) {
438		audioLeft = linearMemAlign(AUDIO_SAMPLE_BUFFER * sizeof(int16_t), 0x80);
439		audioRight = linearMemAlign(AUDIO_SAMPLE_BUFFER * sizeof(int16_t), 0x80);
440	}
441
442	gfxInit(GSP_BGR8_OES, GSP_BGR8_OES, false);
443
444	if (ctrInitGpu() < 0) {
445		goto cleanup;
446	}
447
448	ctrTexture_Init(&gbaOutputTexture);
449	gbaOutputTexture.format = GPU_RGB565;
450	gbaOutputTexture.filter = GPU_LINEAR;
451	gbaOutputTexture.width = 256;
452	gbaOutputTexture.height = 256;
453	gbaOutputTexture.data = vramAlloc(256 * 256 * 2);
454	void* outputTextureEnd = (u8*)gbaOutputTexture.data + 256 * 256 * 2;
455
456	// Zero texture data to make sure no garbage around the border interferes with filtering
457	GX_SetMemoryFill(NULL,
458			gbaOutputTexture.data, 0x0000, outputTextureEnd, GX_FILL_16BIT_DEPTH | GX_FILL_TRIGGER,
459			NULL, 0, NULL, 0);
460	gspWaitForPSC0();
461
462	sdmcArchive = (FS_archive) {
463		ARCH_SDMC,
464		(FS_path) { PATH_EMPTY, 1, (const u8*)"" },
465		0, 0
466	};
467	FSUSER_OpenArchive(0, &sdmcArchive);
468
469	struct GUIFont* font = GUIFontCreate();
470
471	if (!font) {
472		goto cleanup;
473	}
474
475	struct GBAGUIRunner runner = {
476		.params = {
477			320, 240,
478			font, "/",
479			_drawStart, _drawEnd,
480			_pollInput, _pollCursor,
481			_batteryState,
482			_guiPrepare, _guiFinish,
483
484			GUI_PARAMS_TRAIL
485		},
486		.configExtra = (struct GUIMenuItem[]) {
487			{
488				.title = "Screen mode",
489				.data = "screenMode",
490				.submenu = 0,
491				.state = SM_PA_TOP,
492				.validStates = (const char*[]) {
493					"Pixel-Accurate/Bottom",
494					"Aspect-Ratio Fit/Bottom",
495					"Stretched/Bottom",
496					"Pixel-Accurate/Top",
497					"Aspect-Ratio Fit/Top",
498					"Stretched/Top",
499					0
500				}
501			}
502		},
503		.nConfigExtra = 1,
504		.setup = _setup,
505		.teardown = 0,
506		.gameLoaded = _gameLoaded,
507		.gameUnloaded = _gameUnloaded,
508		.prepareForFrame = 0,
509		.drawFrame = _drawFrame,
510		.drawScreenshot = _drawScreenshot,
511		.paused = _gameUnloaded,
512		.unpaused = _gameLoaded,
513		.incrementScreenMode = _incrementScreenMode,
514		.pollGameInput = _pollGameInput
515	};
516
517	GBAGUIInit(&runner, "3ds");
518	GBAGUIRunloop(&runner);
519	GBAGUIDeinit(&runner);
520
521cleanup:
522	linearFree(renderer.outputBuffer);
523
524	ctrDeinitGpu();
525	vramFree(gbaOutputTexture.data);
526
527	gfxExit();
528
529	if (hasSound) {
530		linearFree(audioLeft);
531		linearFree(audioRight);
532	}
533	csndExit();
534	ptmExit();
535	return 0;
536}