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