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 <mgba/core/core.h>
9#include <mgba/core/serialize.h>
10#include "feature/gui/gui-config.h"
11#include <mgba/internal/gba/gba.h>
12#include <mgba/internal/gba/input.h>
13#include <mgba/gba/interface.h>
14#include <mgba-util/gui/file-select.h>
15#include <mgba-util/gui/font.h>
16#include <mgba-util/gui/menu.h>
17#include <mgba-util/memory.h>
18#include <mgba-util/png-io.h>
19#include <mgba-util/vfs.h>
20
21#include <sys/time.h>
22
23mLOG_DECLARE_CATEGORY(GUI_RUNNER);
24mLOG_DEFINE_CATEGORY(GUI_RUNNER, "GUI Runner", "gui.runner");
25
26#define AUTOSAVE_GRANULARITY 600
27#define FPS_GRANULARITY 120
28#define FPS_BUFFER_SIZE 3
29
30enum {
31 RUNNER_CONTINUE = 1,
32 RUNNER_EXIT,
33 RUNNER_SAVE_STATE,
34 RUNNER_LOAD_STATE,
35 RUNNER_SCREENSHOT,
36 RUNNER_CONFIG,
37 RUNNER_RESET,
38 RUNNER_COMMAND_MASK = 0xFFFF
39};
40
41#define RUNNER_STATE(X) ((X) << 16)
42
43static const struct mInputPlatformInfo _mGUIKeyInfo = {
44 .platformName = "gui",
45 .keyId = (const char*[GUI_INPUT_MAX]) {
46 "Select",
47 "Back",
48 "Cancel",
49 "Up",
50 "Down",
51 "Left",
52 "Right",
53 [mGUI_INPUT_INCREASE_BRIGHTNESS] = "Increase solar brightness",
54 [mGUI_INPUT_DECREASE_BRIGHTNESS] = "Decrease solar brightness",
55 [mGUI_INPUT_SCREEN_MODE] = "Screen mode",
56 [mGUI_INPUT_SCREENSHOT] = "Take screenshot",
57 [mGUI_INPUT_FAST_FORWARD_HELD] = "Fast forward (held)",
58 [mGUI_INPUT_FAST_FORWARD_TOGGLE] = "Fast forward (toggle)",
59 },
60 .nKeys = GUI_INPUT_MAX
61};
62
63static void _log(struct mLogger*, int category, enum mLogLevel level, const char* format, va_list args);
64
65static struct mGUILogger {
66 struct mLogger d;
67 struct VFile* vf;
68 int logLevel;
69} logger = {
70 .d = {
71 .log = _log
72 },
73 .vf = NULL,
74 .logLevel = 0
75};
76
77static bool _testExtensions(const char* name) {
78 char ext[PATH_MAX] = {};
79 separatePath(name, NULL, NULL, ext);
80
81 if (!strncmp(ext, "sav", PATH_MAX)) {
82 return false;
83 }
84 if (!strncmp(ext, "png", PATH_MAX)) {
85 return false;
86 }
87 if (!strncmp(ext, "ini", PATH_MAX)) {
88 return false;
89 }
90 if (!strncmp(ext, "ss", 2)) {
91 return false;
92 }
93
94 return true;
95}
96
97static void _drawBackground(struct GUIBackground* background, void* context) {
98 UNUSED(context);
99 struct mGUIBackground* gbaBackground = (struct mGUIBackground*) background;
100 if (gbaBackground->p->drawFrame) {
101 gbaBackground->p->drawFrame(gbaBackground->p, true);
102 }
103}
104
105static void _drawState(struct GUIBackground* background, void* id) {
106 struct mGUIBackground* gbaBackground = (struct mGUIBackground*) background;
107 int stateId = ((int) id) >> 16;
108 if (gbaBackground->p->drawScreenshot) {
109 unsigned w, h;
110 gbaBackground->p->core->desiredVideoDimensions(gbaBackground->p->core, &w, &h);
111 if (gbaBackground->screenshot && gbaBackground->screenshotId == (int) id) {
112 gbaBackground->p->drawScreenshot(gbaBackground->p, gbaBackground->screenshot, w, h, true);
113 return;
114 }
115 struct VFile* vf = mCoreGetState(gbaBackground->p->core, stateId, false);
116 color_t* pixels = gbaBackground->screenshot;
117 if (!pixels) {
118 pixels = anonymousMemoryMap(w * h * 4);
119 gbaBackground->screenshot = pixels;
120 }
121 bool success = false;
122 if (vf && isPNG(vf) && pixels) {
123 png_structp png = PNGReadOpen(vf, PNG_HEADER_BYTES);
124 png_infop info = png_create_info_struct(png);
125 png_infop end = png_create_info_struct(png);
126 if (png && info && end) {
127 success = PNGReadHeader(png, info);
128 success = success && PNGReadPixels(png, info, pixels, w, h, w);
129 success = success && PNGReadFooter(png, end);
130 }
131 PNGReadClose(png, info, end);
132 }
133 if (vf) {
134 vf->close(vf);
135 }
136 if (success) {
137 gbaBackground->p->drawScreenshot(gbaBackground->p, pixels, w, h, true);
138 gbaBackground->screenshotId = (int) id;
139 } else if (gbaBackground->p->drawFrame) {
140 gbaBackground->p->drawFrame(gbaBackground->p, true);
141 }
142 }
143}
144
145static void _updateLux(struct GBALuminanceSource* lux) {
146 UNUSED(lux);
147}
148
149static uint8_t _readLux(struct GBALuminanceSource* lux) {
150 struct mGUIRunnerLux* runnerLux = (struct mGUIRunnerLux*) lux;
151 int value = 0x16;
152 if (runnerLux->luxLevel > 0) {
153 value += GBA_LUX_LEVELS[runnerLux->luxLevel - 1];
154 }
155 return 0xFF - value;
156}
157
158static void _tryAutosave(struct mGUIRunner* runner) {
159 int autosave = false;
160 mCoreConfigGetIntValue(&runner->config, "autosave", &autosave);
161 if (!autosave) {
162 return;
163 }
164
165#ifdef DISABLE_THREADING
166 mCoreSaveState(runner->core, 0, SAVESTATE_SAVEDATA | SAVESTATE_RTC | SAVESTATE_METADATA);
167#else
168 if (!runner->autosave.buffer) {
169 runner->autosave.buffer = VFileMemChunk(NULL, 0);
170 }
171 MutexLock(&runner->autosave.mutex);
172 runner->autosave.core = runner->core;
173 mCoreSaveStateNamed(runner->core, runner->autosave.buffer, SAVESTATE_SAVEDATA | SAVESTATE_RTC | SAVESTATE_METADATA);
174 ConditionWake(&runner->autosave.cond);
175 MutexUnlock(&runner->autosave.mutex);
176#endif
177}
178
179void mGUIInit(struct mGUIRunner* runner, const char* port) {
180 GUIInit(&runner->params);
181 runner->port = port;
182 runner->core = NULL;
183 runner->luminanceSource.d.readLuminance = _readLux;
184 runner->luminanceSource.d.sample = _updateLux;
185 runner->luminanceSource.luxLevel = 0;
186 runner->background.d.draw = _drawBackground;
187 runner->background.p = runner;
188 runner->fps = 0;
189 runner->lastFpsCheck = 0;
190 runner->totalDelta = 0;
191 CircleBufferInit(&runner->fpsBuffer, FPS_BUFFER_SIZE * sizeof(uint32_t));
192
193 mInputMapInit(&runner->params.keyMap, &_mGUIKeyInfo);
194 mCoreConfigInit(&runner->config, runner->port);
195 // TODO: Do we need to load more defaults?
196 mCoreConfigSetDefaultIntValue(&runner->config, "volume", 0x100);
197 mCoreConfigSetDefaultValue(&runner->config, "idleOptimization", "detect");
198 mCoreConfigSetDefaultIntValue(&runner->config, "autoload", true);
199#ifdef DISABLE_THREADING
200 mCoreConfigSetDefaultIntValue(&runner->config, "autosave", false);
201#else
202 mCoreConfigSetDefaultIntValue(&runner->config, "autosave", true);
203#endif
204 mCoreConfigLoad(&runner->config);
205 mCoreConfigGetIntValue(&runner->config, "logLevel", &logger.logLevel);
206
207 char path[PATH_MAX];
208 mCoreConfigDirectory(path, PATH_MAX);
209 strncat(path, PATH_SEP "log", PATH_MAX - strlen(path));
210 logger.vf = VFileOpen(path, O_CREAT | O_WRONLY | O_APPEND);
211 mLogSetDefaultLogger(&logger.d);
212
213 const char* lastPath = mCoreConfigGetValue(&runner->config, "lastDirectory");
214 if (lastPath) {
215 strncpy(runner->params.currentPath, lastPath, PATH_MAX - 1);
216 runner->params.currentPath[PATH_MAX - 1] = '\0';
217 }
218
219#ifndef DISABLE_THREADING
220 if (!runner->autosave.running) {
221 runner->autosave.running = true;
222 MutexInit(&runner->autosave.mutex);
223 ConditionInit(&runner->autosave.cond);
224 ThreadCreate(&runner->autosave.thread, mGUIAutosaveThread, &runner->autosave);
225 }
226#endif
227}
228
229void mGUIDeinit(struct mGUIRunner* runner) {
230#ifndef DISABLE_THREADING
231 MutexLock(&runner->autosave.mutex);
232 runner->autosave.running = false;
233 ConditionWake(&runner->autosave.cond);
234 MutexUnlock(&runner->autosave.mutex);
235
236 ThreadJoin(runner->autosave.thread);
237
238 ConditionDeinit(&runner->autosave.cond);
239 MutexDeinit(&runner->autosave.mutex);
240
241 if (runner->autosave.buffer) {
242 runner->autosave.buffer->close(runner->autosave.buffer);
243 }
244#endif
245
246 if (runner->teardown) {
247 runner->teardown(runner);
248 }
249 CircleBufferDeinit(&runner->fpsBuffer);
250 mInputMapDeinit(&runner->params.keyMap);
251 mCoreConfigDeinit(&runner->config);
252 if (logger.vf) {
253 logger.vf->close(logger.vf);
254 logger.vf = NULL;
255 }
256}
257
258static void _log(struct mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args) {
259 struct mGUILogger* guiLogger = (struct mGUILogger*) logger;
260 if (!guiLogger->vf) {
261 return;
262 }
263 if (!(guiLogger->logLevel & level)) {
264 return;
265 }
266
267 char log[256] = {0};
268 vsnprintf(log, sizeof(log) - 1, format, args);
269 char log2[256] = {0};
270 size_t len = snprintf(log2, sizeof(log2) - 1, "%s: %s\n", mLogCategoryName(category), log);
271 if (len >= sizeof(log2)) {
272 len = sizeof(log2) - 1;
273 }
274 if (guiLogger->vf->write(guiLogger->vf, log2, len) < 0) {
275 char path[PATH_MAX];
276 mCoreConfigDirectory(path, PATH_MAX);
277 strncat(path, PATH_SEP "log", PATH_MAX - strlen(path));
278 guiLogger->vf->close(guiLogger->vf);
279 guiLogger->vf = VFileOpen(path, O_CREAT | O_WRONLY | O_APPEND);
280 if (guiLogger->vf->write(guiLogger->vf, log2, len) < 0) {
281 guiLogger->vf->close(guiLogger->vf);
282 guiLogger->vf = NULL;
283 }
284 }
285}
286
287void mGUIRun(struct mGUIRunner* runner, const char* path) {
288 struct mGUIBackground drawState = {
289 .d = {
290 .draw = _drawState
291 },
292 .p = runner,
293 .screenshot = 0,
294 .screenshotId = 0
295 };
296 struct GUIMenu pauseMenu = {
297 .title = "Game Paused",
298 .index = 0,
299 .background = &runner->background.d
300 };
301 struct GUIMenu stateSaveMenu = {
302 .title = "Save state",
303 .index = 0,
304 .background = &drawState.d
305 };
306 struct GUIMenu stateLoadMenu = {
307 .title = "Load state",
308 .index = 0,
309 .background = &drawState.d
310 };
311 GUIMenuItemListInit(&pauseMenu.items, 0);
312 GUIMenuItemListInit(&stateSaveMenu.items, 9);
313 GUIMenuItemListInit(&stateLoadMenu.items, 9);
314 *GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Unpause", .data = (void*) RUNNER_CONTINUE };
315 *GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Save state", .submenu = &stateSaveMenu };
316 *GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Load state", .submenu = &stateLoadMenu };
317
318 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 1", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(1)) };
319 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 2", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(2)) };
320 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 3", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(3)) };
321 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 4", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(4)) };
322 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 5", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(5)) };
323 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 6", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(6)) };
324 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 7", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(7)) };
325 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 8", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(8)) };
326 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 9", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(9)) };
327
328 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "Autosave", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(0)) };
329 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 1", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(1)) };
330 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 2", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(2)) };
331 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 3", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(3)) };
332 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 4", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(4)) };
333 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 5", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(5)) };
334 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 6", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(6)) };
335 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 7", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(7)) };
336 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 8", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(8)) };
337 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 9", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(9)) };
338
339 *GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Take screenshot", .data = (void*) RUNNER_SCREENSHOT };
340 *GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Configure", .data = (void*) RUNNER_CONFIG };
341 *GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Reset game", .data = (void*) RUNNER_RESET };
342 *GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Exit game", .data = (void*) RUNNER_EXIT };
343
344 runner->params.drawStart();
345 if (runner->params.guiPrepare) {
346 runner->params.guiPrepare();
347 }
348 GUIFontPrint(runner->params.font, runner->params.width / 2, (GUIFontHeight(runner->params.font) + runner->params.height) / 2, GUI_ALIGN_HCENTER, 0xFFFFFFFF, "Loading...");
349 if (runner->params.guiFinish) {
350 runner->params.guiFinish();
351 }
352 runner->params.drawEnd();
353
354 bool found = false;
355 mLOG(GUI_RUNNER, INFO, "Attempting to load %s", path);
356 runner->core = mCoreFind(path);
357 if (runner->core) {
358 mLOG(GUI_RUNNER, INFO, "Found core");
359 runner->core->init(runner->core);
360 mCoreInitConfig(runner->core, runner->port);
361 mInputMapInit(&runner->core->inputMap, &GBAInputInfo);
362 found = mCoreLoadFile(runner->core, path);
363 if (!found) {
364 mLOG(GUI_RUNNER, WARN, "Failed to load %s!", path);
365 mCoreConfigDeinit(&runner->core->config);
366 runner->core->deinit(runner->core);
367 }
368 }
369
370 if (!found) {
371 mLOG(GUI_RUNNER, WARN, "Failed to find core for %s!", path);
372 GUIShowMessageBox(&runner->params, GUI_MESSAGE_BOX_OK, 240, "Load failed!");
373 return;
374 }
375 if (runner->core->platform(runner->core) == PLATFORM_GBA) {
376 runner->core->setPeripheral(runner->core, mPERIPH_GBA_LUMINANCE, &runner->luminanceSource.d);
377 }
378 mLOG(GUI_RUNNER, DEBUG, "Loading config...");
379 mCoreLoadForeignConfig(runner->core, &runner->config);
380
381 mLOG(GUI_RUNNER, DEBUG, "Loading save...");
382 mCoreAutoloadSave(runner->core);
383 mCoreAutoloadCheats(runner->core);
384 if (runner->setup) {
385 mLOG(GUI_RUNNER, DEBUG, "Setting up runner...");
386 runner->setup(runner);
387 }
388 if (runner->config.port && runner->keySources) {
389 mLOG(GUI_RUNNER, DEBUG, "Loading key sources for %s...", runner->config.port);
390 size_t i;
391 for (i = 0; runner->keySources[i].id; ++i) {
392 mInputMapLoad(&runner->core->inputMap, runner->keySources[i].id, mCoreConfigGetInput(&runner->config));
393 }
394 }
395 mLOG(GUI_RUNNER, DEBUG, "Reseting...");
396 runner->core->reset(runner->core);
397 mLOG(GUI_RUNNER, DEBUG, "Reset!");
398
399
400 int autoload = false;
401 mCoreConfigGetIntValue(&runner->config, "autoload", &autoload);
402 if (autoload) {
403 mCoreLoadState(runner->core, 0, SAVESTATE_SCREENSHOT | SAVESTATE_RTC);
404 }
405
406 bool running = true;
407
408#ifndef DISABLE_THREADING
409 MutexLock(&runner->autosave.mutex);
410 runner->autosave.core = runner->core;
411 MutexUnlock(&runner->autosave.mutex);
412#endif
413
414 if (runner->gameLoaded) {
415 runner->gameLoaded(runner);
416 }
417 mLOG(GUI_RUNNER, INFO, "Game starting");
418 while (running) {
419 CircleBufferClear(&runner->fpsBuffer);
420 runner->totalDelta = 0;
421 runner->fps = 0;
422 struct timeval tv;
423 gettimeofday(&tv, 0);
424 runner->lastFpsCheck = 1000000LL * tv.tv_sec + tv.tv_usec;
425
426 int frame = 0;
427 bool fastForward = false;
428 while (running) {
429 if (runner->running) {
430 running = runner->running(runner);
431 if (!running) {
432 break;
433 }
434 }
435 uint32_t guiKeys;
436 uint32_t heldKeys;
437 GUIPollInput(&runner->params, &guiKeys, &heldKeys);
438 if (guiKeys & (1 << GUI_INPUT_CANCEL)) {
439 break;
440 }
441 if (guiKeys & (1 << mGUI_INPUT_INCREASE_BRIGHTNESS)) {
442 if (runner->luminanceSource.luxLevel < 10) {
443 ++runner->luminanceSource.luxLevel;
444 }
445 }
446 if (guiKeys & (1 << mGUI_INPUT_DECREASE_BRIGHTNESS)) {
447 if (runner->luminanceSource.luxLevel > 0) {
448 --runner->luminanceSource.luxLevel;
449 }
450 }
451 if (guiKeys & (1 << mGUI_INPUT_SCREEN_MODE) && runner->incrementScreenMode) {
452 runner->incrementScreenMode(runner);
453 }
454 if (guiKeys & (1 << mGUI_INPUT_SCREENSHOT)) {
455 mCoreTakeScreenshot(runner->core);
456 }
457 if (runner->setFrameLimiter) {
458 if (guiKeys & (1 << mGUI_INPUT_FAST_FORWARD_TOGGLE)) {
459 fastForward = !fastForward;
460 }
461 if (fastForward || (heldKeys & (1 << mGUI_INPUT_FAST_FORWARD_HELD))) {
462 runner->setFrameLimiter(runner, false);
463 } else {
464 runner->setFrameLimiter(runner, true);
465 }
466 }
467 uint16_t keys = runner->pollGameInput(runner);
468 if (runner->prepareForFrame) {
469 runner->prepareForFrame(runner);
470 }
471 runner->core->setKeys(runner->core, keys);
472 runner->core->runFrame(runner->core);
473 if (runner->drawFrame) {
474 int drawFps = false;
475 mCoreConfigGetIntValue(&runner->config, "fpsCounter", &drawFps);
476
477 runner->params.drawStart();
478 runner->drawFrame(runner, false);
479 if (drawFps) {
480 if (runner->params.guiPrepare) {
481 runner->params.guiPrepare();
482 }
483 GUIFontPrintf(runner->params.font, 0, GUIFontHeight(runner->params.font), GUI_ALIGN_LEFT, 0x7FFFFFFF, "%.2f fps", runner->fps);
484 if (runner->params.guiFinish) {
485 runner->params.guiFinish();
486 }
487 }
488 runner->params.drawEnd();
489
490 if (runner->core->frameCounter(runner->core) % FPS_GRANULARITY == 0) {
491 if (drawFps) {
492 struct timeval tv;
493 gettimeofday(&tv, 0);
494 uint64_t t = 1000000LL * tv.tv_sec + tv.tv_usec;
495 uint64_t delta = t - runner->lastFpsCheck;
496 runner->lastFpsCheck = t;
497 if (delta > 0x7FFFFFFFLL) {
498 CircleBufferClear(&runner->fpsBuffer);
499 runner->fps = 0;
500 }
501 if (CircleBufferSize(&runner->fpsBuffer) == CircleBufferCapacity(&runner->fpsBuffer)) {
502 int32_t last;
503 CircleBufferRead32(&runner->fpsBuffer, &last);
504 runner->totalDelta -= last;
505 }
506 CircleBufferWrite32(&runner->fpsBuffer, delta);
507 runner->totalDelta += delta;
508 runner->fps = (CircleBufferSize(&runner->fpsBuffer) * FPS_GRANULARITY * 1000000.0f) / (runner->totalDelta * sizeof(uint32_t));
509 }
510 }
511 if (frame == AUTOSAVE_GRANULARITY) {
512 frame = 0;
513 _tryAutosave(runner);
514 }
515 ++frame;
516 }
517 }
518
519 if (runner->paused) {
520 runner->paused(runner);
521 }
522 if (runner->setFrameLimiter) {
523 runner->setFrameLimiter(runner, true);
524 }
525
526 GUIInvalidateKeys(&runner->params);
527 uint32_t keys = 0xFFFFFFFF; // Huge hack to avoid an extra variable!
528 struct GUIMenuItem* item;
529 enum GUIMenuExitReason reason = GUIShowMenu(&runner->params, &pauseMenu, &item);
530 if (reason == GUI_MENU_EXIT_ACCEPT) {
531 switch (((int) item->data) & RUNNER_COMMAND_MASK) {
532 case RUNNER_EXIT:
533 running = false;
534 keys = 0;
535 break;
536 case RUNNER_RESET:
537 runner->core->reset(runner->core);
538 break;
539 case RUNNER_SAVE_STATE:
540 mCoreSaveState(runner->core, ((int) item->data) >> 16, SAVESTATE_SCREENSHOT | SAVESTATE_SAVEDATA | SAVESTATE_RTC | SAVESTATE_METADATA);
541 break;
542 case RUNNER_LOAD_STATE:
543 mCoreLoadState(runner->core, ((int) item->data) >> 16, SAVESTATE_SCREENSHOT | SAVESTATE_RTC);
544 break;
545 case RUNNER_SCREENSHOT:
546 mCoreTakeScreenshot(runner->core);
547 break;
548 case RUNNER_CONFIG:
549 mGUIShowConfig(runner, runner->configExtra, runner->nConfigExtra);
550 break;
551 case RUNNER_CONTINUE:
552 break;
553 }
554 }
555 int frames = 0;
556 GUIPollInput(&runner->params, 0, &keys);
557 while (keys && frames < 30) {
558 ++frames;
559 runner->params.drawStart();
560 runner->drawFrame(runner, true);
561 runner->params.drawEnd();
562#ifdef _3DS
563 // XXX: Why does this fix #1294?
564 usleep(1000);
565#endif
566 GUIPollInput(&runner->params, 0, &keys);
567 }
568 if (runner->unpaused) {
569 runner->unpaused(runner);
570 }
571 }
572 mLOG(GUI_RUNNER, DEBUG, "Shutting down...");
573 if (runner->gameUnloaded) {
574 runner->gameUnloaded(runner);
575 }
576#ifndef DISABLE_THREADING
577 MutexLock(&runner->autosave.mutex);
578 runner->autosave.core = NULL;
579 MutexUnlock(&runner->autosave.mutex);
580#endif
581
582 int autosave = false;
583 mCoreConfigGetIntValue(&runner->config, "autosave", &autosave);
584 if (autosave) {
585 mCoreSaveState(runner->core, 0, SAVESTATE_SAVEDATA | SAVESTATE_RTC | SAVESTATE_METADATA);
586 }
587
588 mLOG(GUI_RUNNER, DEBUG, "Unloading game...");
589 runner->core->unloadROM(runner->core);
590 drawState.screenshotId = 0;
591 if (drawState.screenshot) {
592 unsigned w, h;
593 runner->core->desiredVideoDimensions(runner->core, &w, &h);
594 mappedMemoryFree(drawState.screenshot, w * h * 4);
595 }
596
597 if (runner->config.port) {
598 mLOG(GUI_RUNNER, DEBUG, "Saving key sources...");
599 if (runner->keySources) {
600 size_t i;
601 for (i = 0; runner->keySources[i].id; ++i) {
602 mInputMapSave(&runner->core->inputMap, runner->keySources[i].id, mCoreConfigGetInput(&runner->config));
603 mInputMapSave(&runner->params.keyMap, runner->keySources[i].id, mCoreConfigGetInput(&runner->config));
604 }
605 }
606 mCoreConfigSave(&runner->config);
607 }
608 mInputMapDeinit(&runner->core->inputMap);
609 mLOG(GUI_RUNNER, DEBUG, "Deinitializing core...");
610 mCoreConfigDeinit(&runner->core->config);
611 runner->core->deinit(runner->core);
612 runner->core = NULL;
613
614 GUIMenuItemListDeinit(&pauseMenu.items);
615 GUIMenuItemListDeinit(&stateSaveMenu.items);
616 GUIMenuItemListDeinit(&stateLoadMenu.items);
617 mLOG(GUI_RUNNER, INFO, "Game stopped!");
618}
619
620void mGUIRunloop(struct mGUIRunner* runner) {
621 if (runner->keySources) {
622 mLOG(GUI_RUNNER, DEBUG, "Loading key sources for %s...", runner->config.port);
623 size_t i;
624 for (i = 0; runner->keySources[i].id; ++i) {
625 mInputMapLoad(&runner->params.keyMap, runner->keySources[i].id, mCoreConfigGetInput(&runner->config));
626 }
627 }
628 while (true) {
629 char path[PATH_MAX];
630 if (!GUISelectFile(&runner->params, path, sizeof(path), _testExtensions, NULL)) {
631 break;
632 }
633 mCoreConfigSetValue(&runner->config, "lastDirectory", runner->params.currentPath);
634 mCoreConfigSave(&runner->config);
635 mGUIRun(runner, path);
636 }
637}
638
639#ifndef DISABLE_THREADING
640THREAD_ENTRY mGUIAutosaveThread(void* context) {
641 struct mGUIAutosaveContext* autosave = context;
642 MutexLock(&autosave->mutex);
643 while (autosave->running) {
644 ConditionWait(&autosave->cond, &autosave->mutex);
645 if (autosave->running && autosave->core) {
646 struct VFile* vf = mCoreGetState(autosave->core, 0, true);
647 void* mem = autosave->buffer->map(autosave->buffer, autosave->buffer->size(autosave->buffer), MAP_READ);
648 vf->write(vf, mem, autosave->buffer->size(autosave->buffer));
649 autosave->buffer->unmap(autosave->buffer, mem, autosave->buffer->size(autosave->buffer));
650 vf->close(vf);
651 }
652 }
653 MutexUnlock(&autosave->mutex);
654}
655#endif