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