src/feature/gui/gui-runner.c (view raw)
1/* Copyright (c) 2013-2016 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 "core/core.h"
9#include "core/serialize.h"
10#include "feature/gui/gui-config.h"
11#include "gba/gba.h"
12#include "gba/input.h"
13#include "gba/interface.h"
14#include "util/gui/file-select.h"
15#include "util/gui/font.h"
16#include "util/gui/menu.h"
17#include "util/memory.h"
18#include "util/png-io.h"
19#include "util/vfs.h"
20
21#ifdef _3DS
22#include <3ds.h>
23#endif
24
25#include <sys/time.h>
26
27mLOG_DECLARE_CATEGORY(GUI_RUNNER);
28mLOG_DEFINE_CATEGORY(GUI_RUNNER, "GUI Runner");
29
30#define FPS_GRANULARITY 120
31#define FPS_BUFFER_SIZE 3
32
33enum {
34 RUNNER_CONTINUE = 1,
35 RUNNER_EXIT,
36 RUNNER_SAVE_STATE,
37 RUNNER_LOAD_STATE,
38 RUNNER_SCREENSHOT,
39 RUNNER_CONFIG,
40 RUNNER_RESET,
41 RUNNER_COMMAND_MASK = 0xFFFF,
42
43 RUNNER_STATE_1 = 0x10000,
44 RUNNER_STATE_2 = 0x20000,
45 RUNNER_STATE_3 = 0x30000,
46 RUNNER_STATE_4 = 0x40000,
47 RUNNER_STATE_5 = 0x50000,
48 RUNNER_STATE_6 = 0x60000,
49 RUNNER_STATE_7 = 0x70000,
50 RUNNER_STATE_8 = 0x80000,
51 RUNNER_STATE_9 = 0x90000,
52};
53
54static const struct mInputPlatformInfo _mGUIKeyInfo = {
55 .platformName = "gui",
56 .keyId = (const char*[GUI_INPUT_MAX]) {
57 "Select",
58 "Back",
59 "Cancel",
60 "Up",
61 "Down",
62 "Left",
63 "Right",
64 [mGUI_INPUT_INCREASE_BRIGHTNESS] = "Increase solar brightness",
65 [mGUI_INPUT_DECREASE_BRIGHTNESS] = "Decrease solar brightness",
66 [mGUI_INPUT_SCREEN_MODE] = "Screen mode",
67 [mGUI_INPUT_SCREENSHOT] = "Take screenshot",
68 [mGUI_INPUT_FAST_FORWARD] = "Fast forward",
69 },
70 .nKeys = GUI_INPUT_MAX
71};
72
73static void _log(struct mLogger*, int category, enum mLogLevel level, const char* format, va_list args);
74
75static struct mGUILogger {
76 struct mLogger d;
77 struct VFile* vf;
78 int logLevel;
79} logger = {
80 .d = {
81 .log = _log
82 },
83 .vf = NULL,
84 .logLevel = 0
85};
86
87static void _drawBackground(struct GUIBackground* background, void* context) {
88 UNUSED(context);
89 struct mGUIBackground* gbaBackground = (struct mGUIBackground*) background;
90 if (gbaBackground->p->drawFrame) {
91 gbaBackground->p->drawFrame(gbaBackground->p, true);
92 }
93}
94
95static void _drawState(struct GUIBackground* background, void* id) {
96 struct mGUIBackground* gbaBackground = (struct mGUIBackground*) background;
97 int stateId = ((int) id) >> 16;
98 if (gbaBackground->p->drawScreenshot) {
99 unsigned w, h;
100 gbaBackground->p->core->desiredVideoDimensions(gbaBackground->p->core, &w, &h);
101 if (gbaBackground->screenshot && gbaBackground->screenshotId == (int) id) {
102 gbaBackground->p->drawScreenshot(gbaBackground->p, gbaBackground->screenshot, w, h, true);
103 return;
104 }
105 struct VFile* vf = mCoreGetState(gbaBackground->p->core, stateId, false);
106 color_t* pixels = gbaBackground->screenshot;
107 if (!pixels) {
108 pixels = anonymousMemoryMap(w * h * 4);
109 gbaBackground->screenshot = pixels;
110 }
111 bool success = false;
112 if (vf && isPNG(vf) && pixels) {
113 png_structp png = PNGReadOpen(vf, PNG_HEADER_BYTES);
114 png_infop info = png_create_info_struct(png);
115 png_infop end = png_create_info_struct(png);
116 if (png && info && end) {
117 success = PNGReadHeader(png, info);
118 success = success && PNGReadPixels(png, info, pixels, w, h, w);
119 success = success && PNGReadFooter(png, end);
120 }
121 PNGReadClose(png, info, end);
122 }
123 if (vf) {
124 vf->close(vf);
125 }
126 if (success) {
127 gbaBackground->p->drawScreenshot(gbaBackground->p, pixels, w, h, true);
128 gbaBackground->screenshotId = (int) id;
129 } else if (gbaBackground->p->drawFrame) {
130 gbaBackground->p->drawFrame(gbaBackground->p, true);
131 }
132 }
133}
134
135static void _updateLux(struct GBALuminanceSource* lux) {
136 UNUSED(lux);
137}
138
139static uint8_t _readLux(struct GBALuminanceSource* lux) {
140 struct mGUIRunnerLux* runnerLux = (struct mGUIRunnerLux*) lux;
141 int value = 0x16;
142 if (runnerLux->luxLevel > 0) {
143 value += GBA_LUX_LEVELS[runnerLux->luxLevel - 1];
144 }
145 return 0xFF - value;
146}
147
148void mGUIInit(struct mGUIRunner* runner, const char* port) {
149 GUIInit(&runner->params);
150 runner->port = port;
151 runner->core = NULL;
152 runner->luminanceSource.d.readLuminance = _readLux;
153 runner->luminanceSource.d.sample = _updateLux;
154 runner->luminanceSource.luxLevel = 0;
155 runner->background.d.draw = _drawBackground;
156 runner->background.p = runner;
157 runner->fps = 0;
158 runner->lastFpsCheck = 0;
159 runner->totalDelta = 0;
160 CircleBufferInit(&runner->fpsBuffer, FPS_BUFFER_SIZE * sizeof(uint32_t));
161
162 mInputMapInit(&runner->params.keyMap, &_mGUIKeyInfo);
163 mCoreConfigInit(&runner->config, runner->port);
164 // TODO: Do we need to load more defaults?
165 mCoreConfigSetDefaultIntValue(&runner->config, "volume", 0x100);
166 mCoreConfigSetDefaultValue(&runner->config, "idleOptimization", "detect");
167 mCoreConfigLoad(&runner->config);
168
169 char path[PATH_MAX];
170 mCoreConfigDirectory(path, PATH_MAX);
171 strncat(path, PATH_SEP "log", PATH_MAX - strlen(path));
172 logger.vf = VFileOpen(path, O_CREAT | O_WRONLY | O_APPEND);
173 mLogSetDefaultLogger(&logger.d);
174}
175
176void mGUIDeinit(struct mGUIRunner* runner) {
177 if (runner->teardown) {
178 runner->teardown(runner);
179 }
180 CircleBufferDeinit(&runner->fpsBuffer);
181 mInputMapDeinit(&runner->params.keyMap);
182 mCoreConfigDeinit(&runner->config);
183 if (logger.vf) {
184 logger.vf->close(logger.vf);
185 logger.vf = NULL;
186 }
187}
188
189static void _log(struct mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args) {
190 struct mGUILogger* guiLogger = (struct mGUILogger*) logger;
191 if (!guiLogger->vf) {
192 return;
193 }
194 if (!(guiLogger->logLevel & level)) {
195 return;
196 }
197
198 char log[256] = {0};
199 vsnprintf(log, sizeof(log) - 1, format, args);
200 char log2[256] = {0};
201 size_t len = snprintf(log2, sizeof(log2) - 1, "%s: %s\n", mLogCategoryName(category), log);
202 if (len >= sizeof(log2)) {
203 len = sizeof(log2) - 1;
204 }
205 guiLogger->vf->write(guiLogger->vf, log2, len);
206}
207
208void mGUIRun(struct mGUIRunner* runner, const char* path) {
209 struct mGUIBackground drawState = {
210 .d = {
211 .draw = _drawState
212 },
213 .p = runner,
214 .screenshot = 0,
215 .screenshotId = 0
216 };
217 struct GUIMenu pauseMenu = {
218 .title = "Game Paused",
219 .index = 0,
220 .background = &runner->background.d
221 };
222 struct GUIMenu stateSaveMenu = {
223 .title = "Save state",
224 .index = 0,
225 .background = &drawState.d
226 };
227 struct GUIMenu stateLoadMenu = {
228 .title = "Load state",
229 .index = 0,
230 .background = &drawState.d
231 };
232 GUIMenuItemListInit(&pauseMenu.items, 0);
233 GUIMenuItemListInit(&stateSaveMenu.items, 9);
234 GUIMenuItemListInit(&stateLoadMenu.items, 9);
235 *GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Unpause", .data = (void*) RUNNER_CONTINUE };
236 *GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Save state", .submenu = &stateSaveMenu };
237 *GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Load state", .submenu = &stateLoadMenu };
238
239 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 1", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE_1) };
240 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 2", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE_2) };
241 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 3", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE_3) };
242 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 4", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE_4) };
243 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 5", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE_5) };
244 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 6", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE_6) };
245 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 7", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE_7) };
246 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 8", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE_8) };
247 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 9", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE_9) };
248
249 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 1", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE_1) };
250 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 2", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE_2) };
251 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 3", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE_3) };
252 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 4", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE_4) };
253 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 5", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE_5) };
254 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 6", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE_6) };
255 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 7", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE_7) };
256 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 8", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE_8) };
257 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 9", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE_9) };
258
259 *GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Take screenshot", .data = (void*) RUNNER_SCREENSHOT };
260 *GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Configure", .data = (void*) RUNNER_CONFIG };
261 *GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Reset game", .data = (void*) RUNNER_RESET };
262 *GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Exit game", .data = (void*) RUNNER_EXIT };
263
264 runner->params.drawStart();
265 if (runner->params.guiPrepare) {
266 runner->params.guiPrepare();
267 }
268 GUIFontPrint(runner->params.font, runner->params.width / 2, (GUIFontHeight(runner->params.font) + runner->params.height) / 2, GUI_ALIGN_HCENTER, 0xFFFFFFFF, "Loading...");
269 if (runner->params.guiFinish) {
270 runner->params.guiFinish();
271 }
272 runner->params.drawEnd();
273
274 bool found = false;
275 mLOG(GUI_RUNNER, INFO, "Attempting to load %s", path);
276 runner->core = mCoreFind(path);
277 if (runner->core) {
278 mLOG(GUI_RUNNER, INFO, "Found core");
279 runner->core->init(runner->core);
280 mInputMapInit(&runner->core->inputMap, &GBAInputInfo);
281 found = mCoreLoadFile(runner->core, path);
282 if (!found) {
283 mLOG(GUI_RUNNER, WARN, "Failed to load %s!", path);
284 runner->core->deinit(runner->core);
285 }
286 }
287
288 if (!found) {
289 mLOG(GUI_RUNNER, WARN, "Failed to find core for %s!", path);
290 GUIShowMessageBox(&runner->params, GUI_MESSAGE_BOX_OK, 240, "Load failed!");
291 return;
292 }
293 if (runner->core->platform(runner->core) == PLATFORM_GBA) {
294 ((struct GBA*) runner->core->board)->luminanceSource = &runner->luminanceSource.d;
295 }
296 mLOG(GUI_RUNNER, DEBUG, "Loading config...");
297 mCoreLoadForeignConfig(runner->core, &runner->config);
298 logger.logLevel = runner->core->opts.logLevel;
299
300 mLOG(GUI_RUNNER, DEBUG, "Loading save...");
301 mCoreAutoloadSave(runner->core);
302 if (runner->setup) {
303 mLOG(GUI_RUNNER, DEBUG, "Setting up runner...");
304 runner->setup(runner);
305 }
306 if (runner->config.port && runner->keySources) {
307 mLOG(GUI_RUNNER, DEBUG, "Loading key sources for %s...", runner->config.port);
308 size_t i;
309 for (i = 0; runner->keySources[i].id; ++i) {
310 mInputMapLoad(&runner->core->inputMap, runner->keySources[i].id, mCoreConfigGetInput(&runner->config));
311 }
312 }
313 mLOG(GUI_RUNNER, DEBUG, "Reseting...");
314 runner->core->reset(runner->core);
315 mLOG(GUI_RUNNER, DEBUG, "Reset!");
316 bool running = true;
317 if (runner->gameLoaded) {
318 runner->gameLoaded(runner);
319 }
320 mLOG(GUI_RUNNER, INFO, "Game starting");
321 while (running) {
322 CircleBufferClear(&runner->fpsBuffer);
323 runner->totalDelta = 0;
324 runner->fps = 0;
325 struct timeval tv;
326 gettimeofday(&tv, 0);
327 runner->lastFpsCheck = 1000000LL * tv.tv_sec + tv.tv_usec;
328
329 while (true) {
330#ifdef _3DS
331 running = aptMainLoop();
332 if (!running) {
333 break;
334 }
335#endif
336 uint32_t guiKeys;
337 uint32_t heldKeys;
338 GUIPollInput(&runner->params, &guiKeys, &heldKeys);
339 if (guiKeys & (1 << GUI_INPUT_CANCEL)) {
340 break;
341 }
342 if (guiKeys & (1 << mGUI_INPUT_INCREASE_BRIGHTNESS)) {
343 if (runner->luminanceSource.luxLevel < 10) {
344 ++runner->luminanceSource.luxLevel;
345 }
346 }
347 if (guiKeys & (1 << mGUI_INPUT_DECREASE_BRIGHTNESS)) {
348 if (runner->luminanceSource.luxLevel > 0) {
349 --runner->luminanceSource.luxLevel;
350 }
351 }
352 if (guiKeys & (1 << mGUI_INPUT_SCREEN_MODE) && runner->incrementScreenMode) {
353 runner->incrementScreenMode(runner);
354 }
355 if (guiKeys & (1 << mGUI_INPUT_SCREENSHOT)) {
356 mCoreTakeScreenshot(runner->core);
357 }
358 if (heldKeys & (1 << mGUI_INPUT_FAST_FORWARD)) {
359 runner->setFrameLimiter(runner, false);
360 } else {
361 runner->setFrameLimiter(runner, true);
362 }
363 uint16_t keys = runner->pollGameInput(runner);
364 if (runner->prepareForFrame) {
365 runner->prepareForFrame(runner);
366 }
367 runner->core->setKeys(runner->core, keys);
368 runner->core->runFrame(runner->core);
369 if (runner->drawFrame) {
370 int drawFps = false;
371 mCoreConfigGetIntValue(&runner->config, "fpsCounter", &drawFps);
372
373 runner->params.drawStart();
374 runner->drawFrame(runner, false);
375 if (drawFps) {
376 if (runner->params.guiPrepare) {
377 runner->params.guiPrepare();
378 }
379 GUIFontPrintf(runner->params.font, 0, GUIFontHeight(runner->params.font), GUI_ALIGN_LEFT, 0x7FFFFFFF, "%.2f fps", runner->fps);
380 if (runner->params.guiFinish) {
381 runner->params.guiFinish();
382 }
383 }
384 runner->params.drawEnd();
385
386 if (runner->core->frameCounter(runner->core) % FPS_GRANULARITY == 0) {
387 if (drawFps) {
388 struct timeval tv;
389 gettimeofday(&tv, 0);
390 uint64_t t = 1000000LL * tv.tv_sec + tv.tv_usec;
391 uint64_t delta = t - runner->lastFpsCheck;
392 runner->lastFpsCheck = t;
393 if (delta > 0x7FFFFFFFLL) {
394 CircleBufferClear(&runner->fpsBuffer);
395 runner->fps = 0;
396 }
397 if (CircleBufferSize(&runner->fpsBuffer) == CircleBufferCapacity(&runner->fpsBuffer)) {
398 int32_t last;
399 CircleBufferRead32(&runner->fpsBuffer, &last);
400 runner->totalDelta -= last;
401 }
402 CircleBufferWrite32(&runner->fpsBuffer, delta);
403 runner->totalDelta += delta;
404 runner->fps = (CircleBufferSize(&runner->fpsBuffer) * FPS_GRANULARITY * 1000000.0f) / (runner->totalDelta * sizeof(uint32_t));
405 }
406 }
407 }
408 }
409
410 if (runner->paused) {
411 runner->paused(runner);
412 }
413 GUIInvalidateKeys(&runner->params);
414 uint32_t keys = 0xFFFFFFFF; // Huge hack to avoid an extra variable!
415 struct GUIMenuItem* item;
416 enum GUIMenuExitReason reason = GUIShowMenu(&runner->params, &pauseMenu, &item);
417 if (reason == GUI_MENU_EXIT_ACCEPT) {
418 switch (((int) item->data) & RUNNER_COMMAND_MASK) {
419 case RUNNER_EXIT:
420 running = false;
421 keys = 0;
422 break;
423 case RUNNER_RESET:
424 runner->core->reset(runner->core);
425 break;
426 case RUNNER_SAVE_STATE:
427 mCoreSaveState(runner->core, ((int) item->data) >> 16, SAVESTATE_SCREENSHOT | SAVESTATE_SAVEDATA);
428 break;
429 case RUNNER_LOAD_STATE:
430 mCoreLoadState(runner->core, ((int) item->data) >> 16, SAVESTATE_SCREENSHOT);
431 break;
432 case RUNNER_SCREENSHOT:
433 mCoreTakeScreenshot(runner->core);
434 break;
435 case RUNNER_CONFIG:
436 mGUIShowConfig(runner, runner->configExtra, runner->nConfigExtra);
437 break;
438 case RUNNER_CONTINUE:
439 break;
440 }
441 }
442 int frames = 0;
443 GUIPollInput(&runner->params, 0, &keys);
444 while (keys && frames < 30) {
445 ++frames;
446 runner->params.drawStart();
447 runner->drawFrame(runner, true);
448 runner->params.drawEnd();
449 GUIPollInput(&runner->params, 0, &keys);
450 }
451 if (runner->unpaused) {
452 runner->unpaused(runner);
453 }
454 }
455 mLOG(GUI_RUNNER, DEBUG, "Shutting down...");
456 if (runner->gameUnloaded) {
457 runner->gameUnloaded(runner);
458 }
459 mLOG(GUI_RUNNER, DEBUG, "Unloading game...");
460 runner->core->unloadROM(runner->core);
461 drawState.screenshotId = 0;
462 if (drawState.screenshot) {
463 unsigned w, h;
464 runner->core->desiredVideoDimensions(runner->core, &w, &h);
465 mappedMemoryFree(drawState.screenshot, w * h * 4);
466 }
467
468 if (runner->config.port) {
469 mLOG(GUI_RUNNER, DEBUG, "Saving key sources...");
470 if (runner->keySources) {
471 size_t i;
472 for (i = 0; runner->keySources[i].id; ++i) {
473 mInputMapSave(&runner->core->inputMap, runner->keySources[i].id, mCoreConfigGetInput(&runner->config));
474 mInputMapSave(&runner->params.keyMap, runner->keySources[i].id, mCoreConfigGetInput(&runner->config));
475 }
476 }
477 mCoreConfigSave(&runner->config);
478 }
479 mInputMapDeinit(&runner->core->inputMap);
480 mLOG(GUI_RUNNER, DEBUG, "Deinitializing core...");
481 runner->core->deinit(runner->core);
482
483 GUIMenuItemListDeinit(&pauseMenu.items);
484 GUIMenuItemListDeinit(&stateSaveMenu.items);
485 GUIMenuItemListDeinit(&stateLoadMenu.items);
486 mLOG(GUI_RUNNER, INFO, "Game stopped!");
487}
488
489void mGUIRunloop(struct mGUIRunner* runner) {
490 if (runner->keySources) {
491 mLOG(GUI_RUNNER, DEBUG, "Loading key sources for %s...", runner->config.port);
492 size_t i;
493 for (i = 0; runner->keySources[i].id; ++i) {
494 mInputMapLoad(&runner->params.keyMap, runner->keySources[i].id, mCoreConfigGetInput(&runner->config));
495 }
496 }
497 while (true) {
498 char path[PATH_MAX];
499 if (!GUISelectFile(&runner->params, path, sizeof(path), 0)) {
500 break;
501 }
502 mGUIRun(runner, path);
503 }
504}