all repos — mgba @ cb2a2126f293663d1607d0040250094da82b9a84

mGBA Game Boy Advance Emulator

src/platform/libretro/libretro.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#include "libretro.h"
  7
  8#include <mgba-util/common.h>
  9
 10#include <mgba/core/blip_buf.h>
 11#include <mgba/core/cheats.h>
 12#include <mgba/core/core.h>
 13#include <mgba/core/log.h>
 14#include <mgba/core/serialize.h>
 15#include <mgba/core/version.h>
 16#ifdef M_CORE_GB
 17#include <mgba/gb/core.h>
 18#include <mgba/internal/gb/gb.h>
 19#include <mgba/internal/gb/mbc.h>
 20#endif
 21#ifdef M_CORE_GBA
 22#include <mgba/gba/core.h>
 23#include <mgba/gba/interface.h>
 24#include <mgba/internal/gba/gba.h>
 25#endif
 26#include <mgba-util/memory.h>
 27#include <mgba-util/vfs.h>
 28
 29#include "libretro_core_options.h"
 30
 31#define SAMPLES 1024
 32#define RUMBLE_PWM 35
 33
 34static retro_environment_t environCallback;
 35static retro_video_refresh_t videoCallback;
 36static retro_audio_sample_batch_t audioCallback;
 37static retro_input_poll_t inputPollCallback;
 38static retro_input_state_t inputCallback;
 39static retro_log_printf_t logCallback;
 40static retro_set_rumble_state_t rumbleCallback;
 41
 42static void GBARetroLog(struct mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args);
 43
 44static void _postAudioBuffer(struct mAVStream*, blip_t* left, blip_t* right);
 45static void _setRumble(struct mRumble* rumble, int enable);
 46static uint8_t _readLux(struct GBALuminanceSource* lux);
 47static void _updateLux(struct GBALuminanceSource* lux);
 48static void _updateCamera(const uint32_t* buffer, unsigned width, unsigned height, size_t pitch);
 49static void _startImage(struct mImageSource*, unsigned w, unsigned h, int colorFormats);
 50static void _stopImage(struct mImageSource*);
 51static void _requestImage(struct mImageSource*, const void** buffer, size_t* stride, enum mColorFormat* colorFormat);
 52
 53static struct mCore* core;
 54static color_t* outputBuffer = NULL;
 55static void* data;
 56static size_t dataSize;
 57static void* savedata;
 58static struct mAVStream stream;
 59static int rumbleUp;
 60static int rumbleDown;
 61static struct mRumble rumble;
 62static struct GBALuminanceSource lux;
 63static int luxLevel;
 64static struct mLogger logger;
 65static struct retro_camera_callback cam;
 66static struct mImageSource imageSource;
 67static uint32_t* camData = NULL;
 68static unsigned camWidth;
 69static unsigned camHeight;
 70static unsigned imcapWidth;
 71static unsigned imcapHeight;
 72static size_t camStride;
 73
 74static void _reloadSettings(void) {
 75	struct mCoreOptions opts = {
 76		.useBios = true,
 77		.volume = 0x100,
 78	};
 79
 80	struct retro_variable var;
 81#ifdef M_CORE_GB
 82	enum GBModel model;
 83	const char* modelName;
 84
 85	var.key = "mgba_gb_model";
 86	var.value = 0;
 87	if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
 88		if (strcmp(var.value, "Game Boy") == 0) {
 89			model = GB_MODEL_DMG;
 90		} else if (strcmp(var.value, "Super Game Boy") == 0) {
 91			model = GB_MODEL_SGB;
 92		} else if (strcmp(var.value, "Game Boy Color") == 0) {
 93			model = GB_MODEL_CGB;
 94		} else if (strcmp(var.value, "Game Boy Advance") == 0) {
 95			model = GB_MODEL_AGB;
 96		} else {
 97			model = GB_MODEL_AUTODETECT;
 98		}
 99
100		modelName = GBModelToName(model);
101		mCoreConfigSetDefaultValue(&core->config, "gb.model", modelName);
102		mCoreConfigSetDefaultValue(&core->config, "sgb.model", modelName);
103		mCoreConfigSetDefaultValue(&core->config, "cgb.model", modelName);
104	}
105#endif
106
107	var.key = "mgba_use_bios";
108	var.value = 0;
109	if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
110		opts.useBios = strcmp(var.value, "ON") == 0;
111	}
112
113	var.key = "mgba_skip_bios";
114	var.value = 0;
115	if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
116		opts.skipBios = strcmp(var.value, "ON") == 0;
117	}
118
119#ifdef M_CORE_GB
120	var.key = "mgba_sgb_borders";
121	var.value = 0;
122	if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
123		mCoreConfigSetDefaultIntValue(&core->config, "sgb.borders", strcmp(var.value, "ON") == 0);
124	}
125#endif
126
127	var.key = "mgba_frameskip";
128	var.value = 0;
129	if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
130		opts.frameskip = strtol(var.value, NULL, 10);
131	}
132
133	var.key = "mgba_idle_optimization";
134	var.value = 0;
135	if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
136		if (strcmp(var.value, "Don't Remove") == 0) {
137			mCoreConfigSetDefaultValue(&core->config, "idleOptimization", "ignore");
138		} else if (strcmp(var.value, "Remove Known") == 0) {
139			mCoreConfigSetDefaultValue(&core->config, "idleOptimization", "remove");
140		} else if (strcmp(var.value, "Detect and Remove") == 0) {
141			mCoreConfigSetDefaultValue(&core->config, "idleOptimization", "detect");
142		}
143	}
144
145#ifdef M_CORE_GBA
146	var.key = "mgba_force_gbp";
147	var.value = 0;
148	if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
149		mCoreConfigSetDefaultIntValue(&core->config, "gba.forceGbp", strcmp(var.value, "ON") == 0);
150	}
151#endif
152
153	mCoreConfigLoadDefaults(&core->config, &opts);
154	mCoreLoadConfig(core);
155}
156
157unsigned retro_api_version(void) {
158	return RETRO_API_VERSION;
159}
160
161void retro_set_environment(retro_environment_t env) {
162	environCallback = env;
163
164	libretro_set_core_options(environCallback);
165}
166
167void retro_set_video_refresh(retro_video_refresh_t video) {
168	videoCallback = video;
169}
170
171void retro_set_audio_sample(retro_audio_sample_t audio) {
172	UNUSED(audio);
173}
174
175void retro_set_audio_sample_batch(retro_audio_sample_batch_t audioBatch) {
176	audioCallback = audioBatch;
177}
178
179void retro_set_input_poll(retro_input_poll_t inputPoll) {
180	inputPollCallback = inputPoll;
181}
182
183void retro_set_input_state(retro_input_state_t input) {
184	inputCallback = input;
185}
186
187void retro_get_system_info(struct retro_system_info* info) {
188	info->need_fullpath = false;
189#ifdef M_CORE_GB
190	info->valid_extensions = "gba|gb|gbc|sgb";
191#else
192	info->valid_extensions = "gba";
193#endif
194	info->library_version = projectVersion;
195	info->library_name = projectName;
196	info->block_extract = false;
197}
198
199void retro_get_system_av_info(struct retro_system_av_info* info) {
200	unsigned width, height;
201	core->desiredVideoDimensions(core, &width, &height);
202	info->geometry.base_width = width;
203	info->geometry.base_height = height;
204#ifdef M_CORE_GB
205	if (core->platform(core) == PLATFORM_GB) {
206		info->geometry.max_width = 256;
207		info->geometry.max_height = 224;
208	} else
209#endif
210	{
211		info->geometry.max_width = width;
212		info->geometry.max_height = height;
213	}
214
215	info->geometry.aspect_ratio = width / (double) height;
216	info->timing.fps = core->frequency(core) / (float) core->frameCycles(core);
217	info->timing.sample_rate = 32768;
218}
219
220void retro_init(void) {
221	enum retro_pixel_format fmt;
222#ifdef COLOR_16_BIT
223#ifdef COLOR_5_6_5
224	fmt = RETRO_PIXEL_FORMAT_RGB565;
225#else
226#warning This pixel format is unsupported. Please use -DCOLOR_16-BIT -DCOLOR_5_6_5
227	fmt = RETRO_PIXEL_FORMAT_0RGB1555;
228#endif
229#else
230#warning This pixel format is unsupported. Please use -DCOLOR_16-BIT -DCOLOR_5_6_5
231	fmt = RETRO_PIXEL_FORMAT_XRGB8888;
232#endif
233	environCallback(RETRO_ENVIRONMENT_SET_PIXEL_FORMAT, &fmt);
234
235	struct retro_input_descriptor inputDescriptors[] = {
236		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A, "A" },
237		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B, "B" },
238		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT, "Select" },
239		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START, "Start" },
240		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "Right" },
241		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT, "Left" },
242		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP, "Up" },
243		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN, "Down" },
244		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R, "R" },
245		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L, "L" },
246		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3, "Brighten Solar Sensor" },
247		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3, "Darken Solar Sensor" },
248		{ 0 }
249	};
250	environCallback(RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS, &inputDescriptors);
251
252	// TODO: RETRO_ENVIRONMENT_SET_SUPPORT_NO_GAME when BIOS booting is supported
253
254	struct retro_rumble_interface rumbleInterface;
255	if (environCallback(RETRO_ENVIRONMENT_GET_RUMBLE_INTERFACE, &rumbleInterface)) {
256		rumbleCallback = rumbleInterface.set_rumble_state;
257		rumble.setRumble = _setRumble;
258	} else {
259		rumbleCallback = 0;
260	}
261
262	luxLevel = 0;
263	lux.readLuminance = _readLux;
264	lux.sample = _updateLux;
265	_updateLux(&lux);
266
267	struct retro_log_callback log;
268	if (environCallback(RETRO_ENVIRONMENT_GET_LOG_INTERFACE, &log)) {
269		logCallback = log.log;
270	} else {
271		logCallback = 0;
272	}
273	logger.log = GBARetroLog;
274	mLogSetDefaultLogger(&logger);
275
276	stream.videoDimensionsChanged = 0;
277	stream.postAudioFrame = 0;
278	stream.postAudioBuffer = _postAudioBuffer;
279	stream.postVideoFrame = 0;
280
281	imageSource.startRequestImage = _startImage;
282	imageSource.stopRequestImage = _stopImage;
283	imageSource.requestImage = _requestImage;
284}
285
286void retro_deinit(void) {
287	free(outputBuffer);
288}
289
290void retro_run(void) {
291	uint16_t keys;
292	inputPollCallback();
293
294	bool updated = false;
295	if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) && updated) {
296		struct retro_variable var = {
297			.key = "mgba_allow_opposing_directions",
298			.value = 0
299		};
300		if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
301			mCoreConfigSetIntValue(&core->config, "allowOpposingDirections", strcmp(var.value, "yes") == 0);
302			core->reloadConfigOption(core, "allowOpposingDirections", NULL);
303		}
304
305		var.key = "mgba_frameskip";
306		var.value = 0;
307		if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
308			mCoreConfigSetIntValue(&core->config, "frameskip", strtol(var.value, NULL, 10));
309			core->reloadConfigOption(core, "frameskip", NULL);
310		}
311	}
312
313	keys = 0;
314	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A)) << 0;
315	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B)) << 1;
316	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT)) << 2;
317	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START)) << 3;
318	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT)) << 4;
319	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT)) << 5;
320	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP)) << 6;
321	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN)) << 7;
322	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R)) << 8;
323	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L)) << 9;
324	core->setKeys(core, keys);
325
326	static bool wasAdjustingLux = false;
327	if (wasAdjustingLux) {
328		wasAdjustingLux = inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3) ||
329		                  inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3);
330	} else {
331		if (inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3)) {
332			++luxLevel;
333			if (luxLevel > 10) {
334				luxLevel = 10;
335			}
336			wasAdjustingLux = true;
337		} else if (inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3)) {
338			--luxLevel;
339			if (luxLevel < 0) {
340				luxLevel = 0;
341			}
342			wasAdjustingLux = true;
343		}
344	}
345
346	core->runFrame(core);
347	unsigned width, height;
348	core->desiredVideoDimensions(core, &width, &height);
349	videoCallback(outputBuffer, width, height, BYTES_PER_PIXEL * 256);
350
351	if (rumbleCallback) {
352		if (rumbleUp) {
353			rumbleCallback(0, RETRO_RUMBLE_STRONG, rumbleUp * 0xFFFF / (rumbleUp + rumbleDown));
354			rumbleCallback(0, RETRO_RUMBLE_WEAK, rumbleUp * 0xFFFF / (rumbleUp + rumbleDown));
355		} else {
356			rumbleCallback(0, RETRO_RUMBLE_STRONG, 0);
357			rumbleCallback(0, RETRO_RUMBLE_WEAK, 0);
358		}
359		rumbleUp = 0;
360		rumbleDown = 0;
361	}
362}
363
364static void _setupMaps(struct mCore* core) {
365#ifdef M_CORE_GBA
366	if (core->platform(core) == PLATFORM_GBA) {
367		struct GBA* gba = core->board;
368		struct retro_memory_descriptor descs[11];
369		struct retro_memory_map mmaps;
370		size_t romSize = gba->memory.romSize + (gba->memory.romSize & 1);
371
372		memset(descs, 0, sizeof(descs));
373		size_t savedataSize = retro_get_memory_size(RETRO_MEMORY_SAVE_RAM);
374
375		/* Map internal working RAM */
376		descs[0].ptr    = gba->memory.iwram;
377		descs[0].start  = BASE_WORKING_IRAM;
378		descs[0].len    = SIZE_WORKING_IRAM;
379		descs[0].select = 0xFF000000;
380
381		/* Map working RAM */
382		descs[1].ptr    = gba->memory.wram;
383		descs[1].start  = BASE_WORKING_RAM;
384		descs[1].len    = SIZE_WORKING_RAM;
385		descs[1].select = 0xFF000000;
386
387		/* Map save RAM */
388		/* TODO: if SRAM is flash, use start=0 addrspace="S" instead */
389		descs[2].ptr    = savedataSize ? savedata : NULL;
390		descs[2].start  = BASE_CART_SRAM;
391		descs[2].len    = savedataSize;
392
393		/* Map ROM */
394		descs[3].ptr    = gba->memory.rom;
395		descs[3].start  = BASE_CART0;
396		descs[3].len    = romSize;
397		descs[3].flags  = RETRO_MEMDESC_CONST;
398
399		descs[4].ptr    = gba->memory.rom;
400		descs[4].start  = BASE_CART1;
401		descs[4].len    = romSize;
402		descs[4].flags  = RETRO_MEMDESC_CONST;
403
404		descs[5].ptr    = gba->memory.rom;
405		descs[5].start  = BASE_CART2;
406		descs[5].len    = romSize;
407		descs[5].flags  = RETRO_MEMDESC_CONST;
408
409		/* Map BIOS */
410		descs[6].ptr    = gba->memory.bios;
411		descs[6].start  = BASE_BIOS;
412		descs[6].len    = SIZE_BIOS;
413		descs[6].flags  = RETRO_MEMDESC_CONST;
414
415		/* Map VRAM */
416		descs[7].ptr    = gba->video.vram;
417		descs[7].start  = BASE_VRAM;
418		descs[7].len    = SIZE_VRAM;
419		descs[7].select = 0xFF000000;
420
421		/* Map palette RAM */
422		descs[8].ptr    = gba->video.palette;
423		descs[8].start  = BASE_PALETTE_RAM;
424		descs[8].len    = SIZE_PALETTE_RAM;
425		descs[8].select = 0xFF000000;
426
427		/* Map OAM */
428		descs[9].ptr    = &gba->video.oam; /* video.oam is a structure */
429		descs[9].start  = BASE_OAM;
430		descs[9].len    = SIZE_OAM;
431		descs[9].select = 0xFF000000;
432
433		/* Map mmapped I/O */
434		descs[10].ptr    = gba->memory.io;
435		descs[10].start  = BASE_IO;
436		descs[10].len    = SIZE_IO;
437
438		mmaps.descriptors = descs;
439		mmaps.num_descriptors = sizeof(descs) / sizeof(descs[0]);
440
441		bool yes = true;
442		environCallback(RETRO_ENVIRONMENT_SET_MEMORY_MAPS, &mmaps);
443		environCallback(RETRO_ENVIRONMENT_SET_SUPPORT_ACHIEVEMENTS, &yes);
444	}
445#endif
446#ifdef M_CORE_GB
447	if (core->platform(core) == PLATFORM_GB) {
448		struct GB* gb = core->board;
449		struct retro_memory_descriptor descs[11];
450		struct retro_memory_map mmaps;
451
452		memset(descs, 0, sizeof(descs));
453		size_t savedataSize = retro_get_memory_size(RETRO_MEMORY_SAVE_RAM);
454
455		unsigned i = 0;
456
457		/* Map ROM */
458		descs[i].ptr    = gb->memory.rom;
459		descs[i].start  = GB_BASE_CART_BANK0;
460		descs[i].len    = GB_SIZE_CART_BANK0;
461		descs[i].flags  = RETRO_MEMDESC_CONST;
462		i++;
463
464		descs[i].ptr    = gb->memory.rom;
465		descs[i].offset = GB_SIZE_CART_BANK0;
466		descs[i].start  = GB_BASE_CART_BANK1;
467		descs[i].len    = GB_SIZE_CART_BANK0;
468		descs[i].flags  = RETRO_MEMDESC_CONST;
469		i++;
470
471		/* Map VRAM */
472		descs[i].ptr    = gb->video.vram;
473		descs[i].start  = GB_BASE_VRAM;
474		descs[i].len    = GB_SIZE_VRAM_BANK0;
475		i++;
476
477		/* Map working RAM */
478		descs[i].ptr    = gb->memory.wram;
479		descs[i].start  = GB_BASE_WORKING_RAM_BANK0;
480		descs[i].len    = GB_SIZE_WORKING_RAM_BANK0;
481		i++;
482
483		descs[i].ptr    = gb->memory.wram;
484		descs[i].offset = GB_SIZE_WORKING_RAM_BANK0;
485		descs[i].start  = GB_BASE_WORKING_RAM_BANK1;
486		descs[i].len    = GB_SIZE_WORKING_RAM_BANK0;
487		i++;
488
489		/* Map OAM */
490		descs[i].ptr    = &gb->video.oam; /* video.oam is a structure */
491		descs[i].start  = GB_BASE_OAM;
492		descs[i].len    = GB_SIZE_OAM;
493		descs[i].select = 0xFFFFFF60;
494		i++;
495
496		/* Map mmapped I/O */
497		descs[i].ptr    = gb->memory.io;
498		descs[i].start  = GB_BASE_IO;
499		descs[i].len    = GB_SIZE_IO;
500		i++;
501
502		/* Map High RAM */
503		descs[i].ptr    = gb->memory.hram;
504		descs[i].start  = GB_BASE_HRAM;
505		descs[i].len    = GB_SIZE_HRAM;
506		descs[i].select = 0xFFFFFF80;
507		i++;
508
509		/* Map IE Register */
510		descs[i].ptr    = &gb->memory.ie;
511		descs[i].start  = GB_BASE_IE;
512		descs[i].len    = 1;
513		i++;
514
515		/* Map External RAM */
516		if (gb->memory.sram) {
517			descs[i].ptr    = gb->memory.sram;
518			descs[i].start  = GB_BASE_EXTERNAL_RAM;
519			descs[i].len    = savedataSize;
520			i++;
521		}
522
523		if (gb->model >= GB_MODEL_CGB) {
524			/* Map working RAM */
525			/* banks 2-7 of wram mapped in virtual address so it can be
526			 * accessed without bank switching, GBC only */
527			descs[i].ptr    = gb->memory.wram + 0x2000;
528			descs[i].start  = 0x10000;
529			descs[i].len    = GB_SIZE_WORKING_RAM - 0x2000;
530			descs[i].select = 0xFFFFA000;
531			i++;
532		}
533
534		mmaps.descriptors = descs;
535		mmaps.num_descriptors = i;
536
537		bool yes = true;
538		environCallback(RETRO_ENVIRONMENT_SET_MEMORY_MAPS, &mmaps);
539		environCallback(RETRO_ENVIRONMENT_SET_SUPPORT_ACHIEVEMENTS, &yes);
540	}
541#endif
542}
543
544void retro_reset(void) {
545	core->reset(core);
546	_setupMaps(core);
547
548	rumbleUp = 0;
549	rumbleDown = 0;
550}
551
552bool retro_load_game(const struct retro_game_info* game) {
553	struct VFile* rom;
554	if (game->data) {
555		data = anonymousMemoryMap(game->size);
556		dataSize = game->size;
557		memcpy(data, game->data, game->size);
558		rom = VFileFromMemory(data, game->size);
559	} else {
560		data = 0;
561		rom = VFileOpen(game->path, O_RDONLY);
562	}
563	if (!rom) {
564		return false;
565	}
566
567	core = mCoreFindVF(rom);
568	if (!core) {
569		rom->close(rom);
570		mappedMemoryFree(data, game->size);
571		return false;
572	}
573	mCoreInitConfig(core, NULL);
574	core->init(core);
575	core->setAVStream(core, &stream);
576
577	size_t size = 256 * 224 * BYTES_PER_PIXEL;
578	outputBuffer = malloc(size);
579	memset(outputBuffer, 0xFF, size);
580	core->setVideoBuffer(core, outputBuffer, 256);
581
582	core->setAudioBufferSize(core, SAMPLES);
583
584	blip_set_rates(core->getAudioChannel(core, 0), core->frequency(core), 32768);
585	blip_set_rates(core->getAudioChannel(core, 1), core->frequency(core), 32768);
586
587	core->setPeripheral(core, mPERIPH_RUMBLE, &rumble);
588
589	savedata = anonymousMemoryMap(SIZE_CART_FLASH1M);
590	memset(savedata, 0xFF, SIZE_CART_FLASH1M);
591	struct VFile* save = VFileFromMemory(savedata, SIZE_CART_FLASH1M);
592
593	_reloadSettings();
594	core->loadROM(core, rom);
595	core->loadSave(core, save);
596
597	const char* sysDir = 0;
598	const char* biosName = 0;
599	char biosPath[PATH_MAX];
600	environCallback(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY, &sysDir);
601
602#ifdef M_CORE_GBA
603	if (core->platform(core) == PLATFORM_GBA) {
604		core->setPeripheral(core, mPERIPH_GBA_LUMINANCE, &lux);
605		biosName = "gba_bios.bin";
606
607	}
608#endif
609
610#ifdef M_CORE_GB
611	if (core->platform(core) == PLATFORM_GB) {
612		memset(&cam, 0, sizeof(cam));
613		cam.height = GBCAM_HEIGHT;
614		cam.width = GBCAM_WIDTH;
615		cam.caps = 1 << RETRO_CAMERA_BUFFER_RAW_FRAMEBUFFER;
616		cam.frame_raw_framebuffer = _updateCamera;
617		if (environCallback(RETRO_ENVIRONMENT_GET_CAMERA_INTERFACE, &cam)) {
618			core->setPeripheral(core, mPERIPH_IMAGE_SOURCE, &imageSource);
619		}
620
621		const char* modelName = mCoreConfigGetValue(&core->config, "gb.model");
622		struct GB* gb = core->board;
623
624		if (modelName) {
625			gb->model = GBNameToModel(modelName);
626		} else {
627			GBDetectModel(gb);
628		}
629
630		switch (gb->model) {
631		case GB_MODEL_AGB:
632		case GB_MODEL_CGB:
633			biosName = "gbc_bios.bin";
634			break;
635		case GB_MODEL_SGB:
636			biosName = "sgb_bios.bin";
637			break;
638		case GB_MODEL_DMG:
639		default:
640			biosName = "gb_bios.bin";
641			break;
642		}
643	}
644#endif
645
646	if (core->opts.useBios && sysDir && biosName) {
647		snprintf(biosPath, sizeof(biosPath), "%s%s%s", sysDir, PATH_SEP, biosName);
648		struct VFile* bios = VFileOpen(biosPath, O_RDONLY);
649		if (bios) {
650			core->loadBIOS(core, bios, 0);
651		}
652	}
653
654	core->reset(core);
655	_setupMaps(core);
656
657	return true;
658}
659
660void retro_unload_game(void) {
661	if (!core) {
662		return;
663	}
664	mCoreConfigDeinit(&core->config);
665	core->deinit(core);
666	mappedMemoryFree(data, dataSize);
667	data = 0;
668	mappedMemoryFree(savedata, SIZE_CART_FLASH1M);
669	savedata = 0;
670}
671
672size_t retro_serialize_size(void) {
673	struct VFile* vfm = VFileMemChunk(NULL, 0);
674	mCoreSaveStateNamed(core, vfm, SAVESTATE_SAVEDATA | SAVESTATE_RTC);
675	size_t size = vfm->size(vfm);
676	vfm->close(vfm);
677	return size;
678}
679
680bool retro_serialize(void* data, size_t size) {
681	struct VFile* vfm = VFileMemChunk(NULL, 0);
682	mCoreSaveStateNamed(core, vfm, SAVESTATE_SAVEDATA | SAVESTATE_RTC);
683	if ((ssize_t) size > vfm->size(vfm)) {
684		size = vfm->size(vfm);
685	} else if ((ssize_t) size < vfm->size(vfm)) {
686		vfm->close(vfm);
687		return false;
688	}
689	vfm->seek(vfm, 0, SEEK_SET);
690	vfm->read(vfm, data, size);
691	vfm->close(vfm);
692	return true;
693}
694
695bool retro_unserialize(const void* data, size_t size) {
696	struct VFile* vfm = VFileFromConstMemory(data, size);
697	bool success = mCoreLoadStateNamed(core, vfm, SAVESTATE_RTC);
698	vfm->close(vfm);
699	return success;
700}
701
702void retro_cheat_reset(void) {
703	mCheatDeviceClear(core->cheatDevice(core));
704}
705
706void retro_cheat_set(unsigned index, bool enabled, const char* code) {
707	UNUSED(index);
708	UNUSED(enabled);
709	struct mCheatDevice* device = core->cheatDevice(core);
710	struct mCheatSet* cheatSet = NULL;
711	if (mCheatSetsSize(&device->cheats)) {
712		cheatSet = *mCheatSetsGetPointer(&device->cheats, 0);
713	} else {
714		cheatSet = device->createSet(device, NULL);
715		mCheatAddSet(device, cheatSet);
716	}
717// Convert the super wonky unportable libretro format to something normal
718#ifdef M_CORE_GBA
719	if (core->platform(core) == PLATFORM_GBA) {
720		char realCode[] = "XXXXXXXX XXXXXXXX";
721		size_t len = strlen(code) + 1; // Include null terminator
722		size_t i, pos;
723		for (i = 0, pos = 0; i < len; ++i) {
724			if (isspace((int) code[i]) || code[i] == '+') {
725				realCode[pos] = ' ';
726			} else {
727				realCode[pos] = code[i];
728			}
729			if ((pos == 13 && (realCode[pos] == ' ' || !realCode[pos])) || pos == 17) {
730				realCode[pos] = '\0';
731				mCheatAddLine(cheatSet, realCode, 0);
732				pos = 0;
733				continue;
734			}
735			++pos;
736		}
737	}
738#endif
739#ifdef M_CORE_GB
740	if (core->platform(core) == PLATFORM_GB) {
741		char realCode[] = "XXX-XXX-XXX";
742		size_t len = strlen(code) + 1; // Include null terminator
743		size_t i, pos;
744		for (i = 0, pos = 0; i < len; ++i) {
745			if (isspace((int) code[i]) || code[i] == '+') {
746				realCode[pos] = '\0';
747			} else {
748				realCode[pos] = code[i];
749			}
750			if (pos == 11 || !realCode[pos]) {
751				realCode[pos] = '\0';
752				mCheatAddLine(cheatSet, realCode, 0);
753				pos = 0;
754				continue;
755			}
756			++pos;
757		}
758	}
759#endif
760	cheatSet->refresh(cheatSet, device);
761}
762
763unsigned retro_get_region(void) {
764	return RETRO_REGION_NTSC; // TODO: This isn't strictly true
765}
766
767void retro_set_controller_port_device(unsigned port, unsigned device) {
768	UNUSED(port);
769	UNUSED(device);
770}
771
772bool retro_load_game_special(unsigned game_type, const struct retro_game_info* info, size_t num_info) {
773	UNUSED(game_type);
774	UNUSED(info);
775	UNUSED(num_info);
776	return false;
777}
778
779void* retro_get_memory_data(unsigned id) {
780	if (id != RETRO_MEMORY_SAVE_RAM) {
781		return 0;
782	}
783	return savedata;
784}
785
786size_t retro_get_memory_size(unsigned id) {
787	if (id != RETRO_MEMORY_SAVE_RAM) {
788		return 0;
789	}
790#ifdef M_CORE_GBA
791	if (core->platform(core) == PLATFORM_GBA) {
792		switch (((struct GBA*) core->board)->memory.savedata.type) {
793		case SAVEDATA_AUTODETECT:
794			return SIZE_CART_FLASH1M;
795		default:
796			return GBASavedataSize(&((struct GBA*) core->board)->memory.savedata);
797		}
798	}
799#endif
800#ifdef M_CORE_GB
801	if (core->platform(core) == PLATFORM_GB) {
802		return ((struct GB*) core->board)->sramSize;
803	}
804#endif
805	return 0;
806}
807
808void GBARetroLog(struct mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args) {
809	UNUSED(logger);
810	if (!logCallback) {
811		return;
812	}
813
814	char message[128];
815	vsnprintf(message, sizeof(message), format, args);
816
817	enum retro_log_level retroLevel = RETRO_LOG_INFO;
818	switch (level) {
819	case mLOG_ERROR:
820	case mLOG_FATAL:
821		retroLevel = RETRO_LOG_ERROR;
822		break;
823	case mLOG_WARN:
824		retroLevel = RETRO_LOG_WARN;
825		break;
826	case mLOG_INFO:
827		retroLevel = RETRO_LOG_INFO;
828		break;
829	case mLOG_GAME_ERROR:
830	case mLOG_STUB:
831#ifdef NDEBUG
832		return;
833#else
834		retroLevel = RETRO_LOG_DEBUG;
835		break;
836#endif
837	case mLOG_DEBUG:
838		retroLevel = RETRO_LOG_DEBUG;
839		break;
840	}
841#ifdef NDEBUG
842	static int biosCat = -1;
843	if (biosCat < 0) {
844		biosCat = mLogCategoryById("gba.bios");
845	}
846
847	if (category == biosCat) {
848		return;
849	}
850#endif
851	logCallback(retroLevel, "%s: %s\n", mLogCategoryName(category), message);
852}
853
854static void _postAudioBuffer(struct mAVStream* stream, blip_t* left, blip_t* right) {
855	UNUSED(stream);
856	int16_t samples[SAMPLES * 2];
857	blip_read_samples(left, samples, SAMPLES, true);
858	blip_read_samples(right, samples + 1, SAMPLES, true);
859	audioCallback(samples, SAMPLES);
860}
861
862static void _setRumble(struct mRumble* rumble, int enable) {
863	UNUSED(rumble);
864	if (!rumbleCallback) {
865		return;
866	}
867	if (enable) {
868		++rumbleUp;
869	} else {
870		++rumbleDown;
871	}
872}
873
874static void _updateLux(struct GBALuminanceSource* lux) {
875	UNUSED(lux);
876	struct retro_variable var = {
877		.key = "mgba_solar_sensor_level",
878		.value = 0
879	};
880
881	bool updated = false;
882	if (!environCallback(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) || !updated) {
883		return;
884	}
885	if (!environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || !var.value) {
886		return;
887	}
888
889	char* end;
890	int newLuxLevel = strtol(var.value, &end, 10);
891	if (!*end) {
892		if (newLuxLevel > 10) {
893			luxLevel = 10;
894		} else if (newLuxLevel < 0) {
895			luxLevel = 0;
896		} else {
897			luxLevel = newLuxLevel;
898		}
899	}
900}
901
902static uint8_t _readLux(struct GBALuminanceSource* lux) {
903	UNUSED(lux);
904	int value = 0x16;
905	if (luxLevel > 0) {
906		value += GBA_LUX_LEVELS[luxLevel - 1];
907	}
908	return 0xFF - value;
909}
910
911static void _updateCamera(const uint32_t* buffer, unsigned width, unsigned height, size_t pitch) {
912	if (!camData || width > camWidth || height > camHeight) {
913		if (camData) {
914			free(camData);
915			camData = NULL;
916		}
917		unsigned bufPitch = pitch / sizeof(*buffer);
918		unsigned bufHeight = height;
919		if (imcapWidth > bufPitch) {
920			bufPitch = imcapWidth;
921		}
922		if (imcapHeight > bufHeight) {
923			bufHeight = imcapHeight;
924		}
925		camData = malloc(sizeof(*buffer) * bufHeight * bufPitch);
926		memset(camData, 0xFF, sizeof(*buffer) * bufHeight * bufPitch);
927		camWidth = width;
928		camHeight = bufHeight;
929		camStride = bufPitch;
930	}
931	size_t i;
932	for (i = 0; i < height; ++i) {
933		memcpy(&camData[camStride * i], &buffer[pitch * i / sizeof(*buffer)], pitch);
934	}
935}
936
937static void _startImage(struct mImageSource* image, unsigned w, unsigned h, int colorFormats) {
938	UNUSED(image);
939	UNUSED(colorFormats);
940
941	if (camData) {
942		free(camData);
943	}
944	camData = NULL;
945	imcapWidth = w;
946	imcapHeight = h;
947	cam.start();
948}
949
950static void _stopImage(struct mImageSource* image) {
951	UNUSED(image);
952	cam.stop();	
953}
954
955static void _requestImage(struct mImageSource* image, const void** buffer, size_t* stride, enum mColorFormat* colorFormat) {
956	UNUSED(image);
957	if (!camData) {
958		cam.start();
959		*buffer = NULL;
960		return;
961	}
962	size_t offset = 0;
963	if (imcapWidth < camWidth) {
964		offset += (camWidth - imcapWidth) / 2;
965	}
966	if (imcapHeight < camHeight) {
967		offset += (camHeight - imcapHeight) / 2 * camStride;
968	}
969
970	*buffer = &camData[offset];
971	*stride = camStride;
972	*colorFormat = mCOLOR_XRGB8;
973}