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