all repos — mgba @ 331d92d36388ae2e2007b3be34c0889a246504a5

mGBA Game Boy Advance Emulator

src/gba/gui/gui-runner.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 "gui-runner.h"
  7
  8#include "gba/gui/gui-config.h"
  9#include "gba/interface.h"
 10#include "gba/serialize.h"
 11#include "util/gui/file-select.h"
 12#include "util/gui/font.h"
 13#include "util/gui/menu.h"
 14#include "util/memory.h"
 15#include "util/png-io.h"
 16#include "util/vfs.h"
 17
 18#include <sys/time.h>
 19
 20#define FPS_GRANULARITY 120
 21#define FPS_BUFFER_SIZE 3
 22
 23enum {
 24	RUNNER_CONTINUE = 1,
 25	RUNNER_EXIT,
 26	RUNNER_SAVE_STATE,
 27	RUNNER_LOAD_STATE,
 28	RUNNER_SCREENSHOT,
 29	RUNNER_CONFIG,
 30	RUNNER_RESET,
 31	RUNNER_COMMAND_MASK = 0xFFFF,
 32
 33	RUNNER_STATE_1 = 0x10000,
 34	RUNNER_STATE_2 = 0x20000,
 35	RUNNER_STATE_3 = 0x30000,
 36	RUNNER_STATE_4 = 0x40000,
 37	RUNNER_STATE_5 = 0x50000,
 38	RUNNER_STATE_6 = 0x60000,
 39	RUNNER_STATE_7 = 0x70000,
 40	RUNNER_STATE_8 = 0x80000,
 41	RUNNER_STATE_9 = 0x90000,
 42};
 43
 44static void _drawBackground(struct GUIBackground* background, void* context) {
 45	UNUSED(context);
 46	struct GBAGUIBackground* gbaBackground = (struct GBAGUIBackground*) background;
 47	if (gbaBackground->p->drawFrame) {
 48		gbaBackground->p->drawFrame(gbaBackground->p, true);
 49	}
 50}
 51
 52static void _drawState(struct GUIBackground* background, void* id) {
 53	struct GBAGUIBackground* gbaBackground = (struct GBAGUIBackground*) background;
 54	int stateId = ((int) id) >> 16;
 55	if (gbaBackground->p->drawScreenshot) {
 56		if (gbaBackground->screenshot && gbaBackground->screenshotId == (int) id) {
 57			gbaBackground->p->drawScreenshot(gbaBackground->p, gbaBackground->screenshot, true);
 58			return;
 59		}
 60		struct VFile* vf = GBAGetState(gbaBackground->p->context.gba, gbaBackground->p->context.dirs.state, stateId, false);
 61		uint32_t* pixels = gbaBackground->screenshot;
 62		if (!pixels) {
 63			pixels = anonymousMemoryMap(VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * 4);
 64			gbaBackground->screenshot = pixels;
 65		}
 66		bool success = false;
 67		if (vf && isPNG(vf) && pixels) {
 68			png_structp png = PNGReadOpen(vf, PNG_HEADER_BYTES);
 69			png_infop info = png_create_info_struct(png);
 70			png_infop end = png_create_info_struct(png);
 71			if (png && info && end) {
 72				success = PNGReadHeader(png, info);
 73				success = success && PNGReadPixels(png, info, pixels, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, VIDEO_HORIZONTAL_PIXELS);
 74				success = success && PNGReadFooter(png, end);
 75			}
 76			PNGReadClose(png, info, end);
 77		}
 78		if (vf) {
 79			vf->close(vf);
 80		}
 81		if (success) {
 82			gbaBackground->p->drawScreenshot(gbaBackground->p, pixels, true);
 83			gbaBackground->screenshotId = (int) id;
 84		} else if (gbaBackground->p->drawFrame) {
 85			gbaBackground->p->drawFrame(gbaBackground->p, true);
 86		}
 87	}
 88}
 89
 90static void _updateLux(struct GBALuminanceSource* lux) {
 91	UNUSED(lux);
 92}
 93
 94static uint8_t _readLux(struct GBALuminanceSource* lux) {
 95	struct GBAGUIRunnerLux* runnerLux = (struct GBAGUIRunnerLux*) lux;
 96	int value = 0x16;
 97	if (runnerLux->luxLevel > 0) {
 98		value += GBA_LUX_LEVELS[runnerLux->luxLevel - 1];
 99	}
100	return 0xFF - value;
101}
102
103void GBAGUIInit(struct GBAGUIRunner* runner, const char* port) {
104	GUIInit(&runner->params);
105	GBAContextInit(&runner->context, port);
106	runner->luminanceSource.d.readLuminance = _readLux;
107	runner->luminanceSource.d.sample = _updateLux;
108	runner->luminanceSource.luxLevel = 0;
109	runner->context.gba->luminanceSource = &runner->luminanceSource.d;
110	runner->background.d.draw = _drawBackground;
111	runner->background.p = runner;
112	runner->fps = 0;
113	runner->lastFpsCheck = 0;
114	runner->totalDelta = 0;
115	CircleBufferInit(&runner->fpsBuffer, FPS_BUFFER_SIZE * sizeof(uint32_t));
116	if (runner->setup) {
117		runner->setup(runner);
118	}
119
120	if (runner->context.config.port && runner->keySources) {
121		size_t i;
122		for (i = 0; runner->keySources[i].id; ++i) {
123			GBAInputMapLoad(&runner->context.inputMap, runner->keySources[i].id, GBAConfigGetInput(&runner->context.config));
124		}
125	}
126}
127
128void GBAGUIDeinit(struct GBAGUIRunner* runner) {
129	if (runner->teardown) {
130		runner->teardown(runner);
131	}
132	if (runner->context.config.port) {
133		if (runner->keySources) {
134			size_t i;
135			for (i = 0; runner->keySources[i].id; ++i) {
136				GBAInputMapSave(&runner->context.inputMap, runner->keySources[i].id, GBAConfigGetInput(&runner->context.config));
137			}
138		}
139		GBAConfigSave(&runner->context.config);
140	}
141	CircleBufferDeinit(&runner->fpsBuffer);
142	GBAContextDeinit(&runner->context);
143}
144
145void GBAGUIRun(struct GBAGUIRunner* runner, const char* path) {
146	struct GBAGUIBackground drawState = {
147		.d = {
148			.draw = _drawState
149		},
150		.p = runner,
151		.screenshot = 0,
152		.screenshotId = 0
153	};
154	struct GUIMenu pauseMenu = {
155		.title = "Game Paused",
156		.index = 0,
157		.background = &runner->background.d
158	};
159	struct GUIMenu stateSaveMenu = {
160		.title = "Save state",
161		.index = 0,
162		.background = &drawState.d
163	};
164	struct GUIMenu stateLoadMenu = {
165		.title = "Load state",
166		.index = 0,
167		.background = &drawState.d
168	};
169	GUIMenuItemListInit(&pauseMenu.items, 0);
170	GUIMenuItemListInit(&stateSaveMenu.items, 9);
171	GUIMenuItemListInit(&stateLoadMenu.items, 9);
172	*GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Unpause", .data = (void*) RUNNER_CONTINUE };
173	*GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Save state", .submenu = &stateSaveMenu };
174	*GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Load state", .submenu = &stateLoadMenu };
175
176	*GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 1", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE_1) };
177	*GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 2", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE_2) };
178	*GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 3", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE_3) };
179	*GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 4", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE_4) };
180	*GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 5", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE_5) };
181	*GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 6", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE_6) };
182	*GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 7", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE_7) };
183	*GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 8", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE_8) };
184	*GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 9", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE_9) };
185
186	*GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 1", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE_1) };
187	*GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 2", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE_2) };
188	*GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 3", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE_3) };
189	*GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 4", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE_4) };
190	*GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 5", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE_5) };
191	*GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 6", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE_6) };
192	*GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 7", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE_7) };
193	*GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 8", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE_8) };
194	*GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 9", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE_9) };
195
196	*GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Take screenshot", .data = (void*) RUNNER_SCREENSHOT };
197	*GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Configure", .data = (void*) RUNNER_CONFIG };
198	*GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Reset game", .data = (void*) RUNNER_RESET };
199	*GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Exit game", .data = (void*) RUNNER_EXIT };
200
201	// TODO: Message box API
202	runner->params.drawStart();
203	if (runner->params.guiPrepare) {
204		runner->params.guiPrepare();
205	}
206	GUIFontPrint(runner->params.font, runner->params.width / 2, (GUIFontHeight(runner->params.font) + runner->params.height) / 2, GUI_TEXT_CENTER, 0xFFFFFFFF, "Loading...");
207	if (runner->params.guiFinish) {
208		runner->params.guiFinish();
209	}
210	runner->params.drawEnd();
211
212	if (!GBAContextLoadROM(&runner->context, path, true)) {
213		int i;
214		for (i = 0; i < 300; ++i) {
215			runner->params.drawStart();
216			if (runner->params.guiPrepare) {
217				runner->params.guiPrepare();
218			}
219			GUIFontPrint(runner->params.font, runner->params.width / 2, (GUIFontHeight(runner->params.font) + runner->params.height) / 2, GUI_TEXT_CENTER, 0xFFFFFFFF, "Load failed!");
220			if (runner->params.guiFinish) {
221				runner->params.guiFinish();
222			}
223			runner->params.drawEnd();
224		}
225		return;
226	}
227	bool running = GBAContextStart(&runner->context);
228	if (runner->gameLoaded) {
229		runner->gameLoaded(runner);
230	}
231	while (running) {
232		CircleBufferClear(&runner->fpsBuffer);
233		runner->totalDelta = 0;
234		runner->fps = 0;
235		struct timeval tv;
236		gettimeofday(&tv, 0);
237		runner->lastFpsCheck = 1000000LL * tv.tv_sec + tv.tv_usec;
238
239		while (true) {
240			uint32_t guiKeys;
241			GUIPollInput(&runner->params, &guiKeys, 0);
242			if (guiKeys & (1 << GUI_INPUT_CANCEL)) {
243				break;
244			}
245			if (guiKeys & (1 << GBA_GUI_INPUT_INCREASE_BRIGHTNESS)) {
246				if (runner->luminanceSource.luxLevel < 10) {
247					++runner->luminanceSource.luxLevel;
248				}
249			}
250			if (guiKeys & (1 << GBA_GUI_INPUT_DECREASE_BRIGHTNESS)) {
251				if (runner->luminanceSource.luxLevel > 0) {
252					--runner->luminanceSource.luxLevel;
253				}
254			}
255			if (guiKeys & (1 << GBA_GUI_INPUT_SCREEN_MODE) && runner->incrementScreenMode) {
256				runner->incrementScreenMode(runner);
257			}
258			uint16_t keys = runner->pollGameInput(runner);
259			if (runner->prepareForFrame) {
260				runner->prepareForFrame(runner);
261			}
262			GBAContextFrame(&runner->context, keys);
263			if (runner->drawFrame) {
264				int drawFps = false;
265				GBAConfigGetIntValue(&runner->context.config, "fpsCounter", &drawFps);
266
267				runner->params.drawStart();
268				runner->drawFrame(runner, false);
269				if (drawFps) {
270					if (runner->params.guiPrepare) {
271						runner->params.guiPrepare();
272					}
273					GUIFontPrintf(runner->params.font, 0, GUIFontHeight(runner->params.font), GUI_TEXT_LEFT, 0x7FFFFFFF, "%.2f fps", runner->fps);
274					if (runner->params.guiFinish) {
275						runner->params.guiFinish();
276					}
277				}
278				runner->params.drawEnd();
279
280				if (runner->context.gba->video.frameCounter % FPS_GRANULARITY == 0) {
281					if (drawFps) {
282						struct timeval tv;
283						gettimeofday(&tv, 0);
284						uint64_t t = 1000000LL * tv.tv_sec + tv.tv_usec;
285						uint64_t delta = t - runner->lastFpsCheck;
286						runner->lastFpsCheck = t;
287						if (delta > 0x7FFFFFFFLL) {
288							CircleBufferClear(&runner->fpsBuffer);
289							runner->fps = 0;
290						}
291						if (CircleBufferSize(&runner->fpsBuffer) == CircleBufferCapacity(&runner->fpsBuffer)) {
292							int32_t last;
293							CircleBufferRead32(&runner->fpsBuffer, &last);
294							runner->totalDelta -= last;
295						}
296						CircleBufferWrite32(&runner->fpsBuffer, delta);
297						runner->totalDelta += delta;
298						runner->fps = (CircleBufferSize(&runner->fpsBuffer) * FPS_GRANULARITY * 1000000.0f) / (runner->totalDelta * sizeof(uint32_t));
299					}
300				}
301			}
302		}
303
304		if (runner->paused) {
305			runner->paused(runner);
306		}
307		GUIInvalidateKeys(&runner->params);
308		uint32_t keys = 0xFFFFFFFF; // Huge hack to avoid an extra variable!
309		struct GUIMenuItem* item;
310		enum GUIMenuExitReason reason = GUIShowMenu(&runner->params, &pauseMenu, &item);
311		if (reason == GUI_MENU_EXIT_ACCEPT) {
312			struct VFile* vf;
313			switch (((int) item->data) & RUNNER_COMMAND_MASK) {
314			case RUNNER_EXIT:
315				running = false;
316				keys = 0;
317				break;
318			case RUNNER_RESET:
319				GBAContextReset(&runner->context);
320				break;
321			case RUNNER_SAVE_STATE:
322				vf = GBAGetState(runner->context.gba, runner->context.dirs.state, ((int) item->data) >> 16, true);
323				if (vf) {
324					GBASaveStateNamed(runner->context.gba, vf, SAVESTATE_SCREENSHOT);
325					vf->close(vf);
326				}
327				break;
328			case RUNNER_LOAD_STATE:
329				vf = GBAGetState(runner->context.gba, runner->context.dirs.state, ((int) item->data) >> 16, false);
330				if (vf) {
331					GBALoadStateNamed(runner->context.gba, vf, SAVESTATE_SCREENSHOT);
332					vf->close(vf);
333				}
334				break;
335			case RUNNER_SCREENSHOT:
336				GBATakeScreenshot(runner->context.gba, runner->context.dirs.screenshot);
337				break;
338			case RUNNER_CONFIG:
339				GBAGUIShowConfig(runner, runner->configExtra, runner->nConfigExtra);
340				GBAConfigGetIntValue(&runner->context.config, "frameskip", &runner->context.gba->video.frameskip);
341				break;
342			case RUNNER_CONTINUE:
343				break;
344			}
345		}
346		int frames = 0;
347		GUIPollInput(&runner->params, 0, &keys);
348		while (keys && frames < 30) {
349			++frames;
350			runner->params.drawStart();
351			runner->drawFrame(runner, true);
352			runner->params.drawEnd();
353			GUIPollInput(&runner->params, 0, &keys);
354		}
355		if (runner->unpaused) {
356			runner->unpaused(runner);
357		}
358	}
359	GBAContextStop(&runner->context);
360	if (runner->gameUnloaded) {
361		runner->gameUnloaded(runner);
362	}
363	GBAContextUnloadROM(&runner->context);
364	drawState.screenshotId = 0;
365	if (drawState.screenshot) {
366		mappedMemoryFree(drawState.screenshot, VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * 4);
367	}
368	GUIMenuItemListDeinit(&pauseMenu.items);
369	GUIMenuItemListDeinit(&stateSaveMenu.items);
370	GUIMenuItemListDeinit(&stateLoadMenu.items);
371}
372
373void GBAGUIRunloop(struct GBAGUIRunner* runner) {
374	while (true) {
375		char path[PATH_MAX];
376		if (!GUISelectFile(&runner->params, path, sizeof(path), 0)) {
377			break;
378		}
379		GBAGUIRun(runner, path);
380	}
381}