-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathApplication.cpp
More file actions
738 lines (572 loc) · 19.4 KB
/
Application.cpp
File metadata and controls
738 lines (572 loc) · 19.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
#include "Application.h"
#include "Control.h"
#include "LuaUtil.h"
#include "cheats/Cheats.h"
#include "gamecontrollerdb.h"
#include <imgui.h>
#include <imgui_impl_sdl.h>
#include <imgui_impl_opengl2.h>
#include <ProggyTiny.inl>
#include <FontAwesome4.inl>
#include <IconsFontAwesome4.h>
#include <stdlib.h>
#include <sys/stat.h>
extern "C" {
#include "lauxlib.h"
#include "lualib.h"
}
#define TAG "[HC ] "
static void const* readAll(hc::Logger* logger, char const* const path, size_t* const size) {
struct stat statbuf;
if (stat(path, &statbuf) != 0) {
logger->error(TAG "Error getting content info: %s", strerror(errno));
return nullptr;
}
void* const data = malloc(statbuf.st_size);
if (data == nullptr) {
logger->error(TAG "Out of memory allocating %zu bytes", statbuf.st_size);
return nullptr;
}
FILE* file = fopen(path, "rb");
if (file == nullptr) {
logger->error(TAG "Error opening content: %s", strerror(errno));
free(data);
return nullptr;
}
size_t numread = fread(data, 1, statbuf.st_size, file);
if (numread != (size_t)statbuf.st_size) {
logger->error(TAG "Error reading content: %s", strerror(errno));
fclose(file);
free(data);
return nullptr;
}
fclose(file);
logger->info(TAG "Loaded content from \"%s\", %zu bytes", path, numread);
*size = numread;
return data;
}
hc::Application::Application()
: _fsm(*this, lifeCycleVprintf, this)
, _logger(this)
, _config(this, &_memorySelector)
, _video(this)
, _led(this)
, _audio(this)
, _input(this)
, _perf(this)
, _control(this)
, _memorySelector(this)
, _devices(this)
, _repl(this, &_logger)
, _debugger(this, &_config, &_memorySelector)
{}
bool hc::Application::init(std::string const& title, int const width, int const height) {
class Undo {
public:
~Undo() {
for (size_t i = _list.size(); i != 0; i--) {
_list[i - 1]();
}
}
void add(std::function<void()> const& undo) {
_list.emplace_back(undo);
}
void clear() {
_list.clear();
}
protected:
std::vector<std::function<void()>> _list;
}
undo;
if (!_logger.init()) {
return false;
}
Desktop::init(&_logger);
addView(&_logger, true, false);
{
// Redirect SDL logs
SDL_LogSetOutputFunction(sdlPrint, this);
SDL_LogSetAllPriority(SDL_LOG_PRIORITY_VERBOSE);
// Setup SDL
if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
error(TAG "Error in SDL_Init: %s", SDL_GetError());
return false;
}
undo.add([]() { SDL_Quit(); });
// Setup window
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
Uint32 const windowFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_MAXIMIZED;
_window = SDL_CreateWindow(
title.c_str(),
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
width, height,
windowFlags
);
if (_window == nullptr) {
error(TAG "Error in SDL_CreateWindow: %s", SDL_GetError());
return false;
}
undo.add([this]() { SDL_DestroyWindow(_window); });
_glContext = SDL_GL_CreateContext(_window);
if (_glContext == nullptr) {
error(TAG "Error in SDL_GL_CreateContext: %s", SDL_GetError());
return false;
}
undo.add([this]() { SDL_GL_DeleteContext(_glContext); });
SDL_GL_MakeCurrent(_window, _glContext);
SDL_GL_SetSwapInterval(1);
// Init audio
SDL_AudioSpec want;
memset(&want, 0, sizeof(want));
want.freq = 44100;
want.format = AUDIO_S16SYS;
want.channels = 2;
want.samples = 1024;
want.callback = audioCallback;
want.userdata = this;
_audioDev = SDL_OpenAudioDevice(
nullptr, 0,
&want, &_audioSpec,
SDL_AUDIO_ALLOW_FREQUENCY_CHANGE | SDL_AUDIO_ALLOW_CHANNELS_CHANGE
);
if (_audioDev == 0) {
error(TAG "Error in SDL_OpenAudioDevice: %s", SDL_GetError());
return false;
}
undo.add([this]() { SDL_CloseAudioDevice(_audioDev); });
if (!_fifo.init(_audioSpec.size * 2)) {
error(TAG "Error in audio FIFO init");
return false;
}
undo.add([this]() { _fifo.destroy(); });
SDL_PauseAudioDevice(_audioDev, 0);
// Add controller mappings
SDL_RWops* const ctrldb = SDL_RWFromMem(
const_cast<void*>(static_cast<void const*>(gamecontrollerdb_txt)),
static_cast<int>(sizeof(gamecontrollerdb_txt))
);
if (SDL_GameControllerAddMappingsFromRW(ctrldb, 1) < 0) {
error(TAG "Error in SDL_GameControllerAddMappingsFromRW: %s", SDL_GetError());
return false;
}
}
{
// Setup ImGui
IMGUI_CHECKVERSION();
if (ImGui::CreateContext() == nullptr) {
error(TAG "Error creating ImGui context");
return false;
}
undo.add([]() { ImGui::DestroyContext(); });
ImGuiStyle& style = ImGui::GetStyle();
style.WindowRounding = 0.0f;
style.FrameRounding = 0.0f;
style.ScrollbarRounding = 0.0f;
style.GrabRounding = 0.0f;
style.TabRounding = 0.0f;
ImGuiIO& io = ImGui::GetIO();
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;
ImGui::StyleColorsDark();
if (!ImGui_ImplSDL2_InitForOpenGL(_window, _glContext)) {
error(TAG "Error initializing ImGui for OpenGL");
return false;
}
undo.add([]() { ImGui_ImplSDL2_Shutdown(); });
if (!ImGui_ImplOpenGL2_Init()) {
error(TAG "Error initializing ImGui OpenGL implementation");
return false;
}
undo.add([]() { ImGui_ImplOpenGL2_Shutdown(); });
// Set Proggy Tiny as the default font
io = ImGui::GetIO();
ImFont* const proggyTiny = io.Fonts->AddFontFromMemoryCompressedTTF(
ProggyTiny_compressed_data,
ProggyTiny_compressed_size,
10.0f
);
if (proggyTiny == nullptr) {
error(TAG "Error adding Proggy Tiny font");
return false;
}
// Add icons from Font Awesome
ImFontConfig config;
config.MergeMode = true;
config.PixelSnapH = true;
static ImWchar const ranges1[] = {ICON_MIN_FA, ICON_MAX_FA, 0};
ImFont* const fontAwesome = io.Fonts->AddFontFromMemoryCompressedTTF(
FontAwesome4_compressed_data,
FontAwesome4_compressed_size,
12.0f, &config, ranges1
);
if (fontAwesome == nullptr) {
error(TAG "Error adding Font Awesome 4 font");
return false;
}
}
{
// Initialize Lua
_L = luaL_newstate();
if (_L == nullptr) {
return false;
}
undo.add([this]() { lua_close(_L); });
static luaL_Reg const libs[] = {
{LUA_GNAME, luaopen_base},
{LUA_LOADLIBNAME, luaopen_package},
{LUA_COLIBNAME, luaopen_coroutine},
{LUA_TABLIBNAME, luaopen_table},
{LUA_IOLIBNAME, luaopen_io},
//{LUA_OSLIBNAME, luaopen_os},
{LUA_STRLIBNAME, luaopen_string},
{LUA_MATHLIBNAME, luaopen_math},
{LUA_UTF8LIBNAME, luaopen_utf8},
{LUA_DBLIBNAME, luaopen_debug},
{nullptr, nullptr}
};
for (luaL_Reg const* lib = libs; lib->func != nullptr; lib++) {
luaL_requiref(_L, lib->name, lib->func, 1);
lua_pop(_L, 1);
}
push(_L);
lua_pushvalue(_L, -1);
lua_setglobal(_L, "hc");
registerSearcher(_L);
}
{
// Initialize components (logger has already been initialized)
lrcpp::Frontend& frontend = lrcpp::Frontend::getInstance();
addView(&_config, true, false);
addView(&_video, true, false);
addView(&_led, true, false);
addView(&_audio, true, false);
addView(&_input, true, false);
addView(&_perf, true, false);
addView(&_control, true, false);
addView(&_memorySelector, true, false);
addView(&_devices, true, false);
addView(&_repl, true, false);
addView(&_debugger, true, false);
if (!_config.init()) {
return false;
}
_video.init();
_led.init();
_audio.init(_audioSpec.freq, &_fifo);
_input.init(&frontend);
_perf.init();
_control.init(&_fsm, &_logger);
_memorySelector.init();
_devices.init(&_video);
_repl.init();
_debugger.init();
_devices.addListener(&_input);
frontend.setLogger(&_logger);
frontend.setConfig(&_config);
frontend.setVideo(&_video);
frontend.setLed(&_led);
frontend.setAudio(&_audio);
frontend.setInput(&_input);
frontend.setPerf(&_perf);
}
{
// Run the autorun script
static auto const main = [](lua_State* const L) -> int {
char const* const path = luaL_checkstring(L, 1);
if (luaL_loadfilex(L, path, "t") != LUA_OK) {
return lua_error(L);
}
lua_call(L, 0, 0);
return 0;
};
std::string const& autorun = _config.getScriptsPath() + "autorun.lua";
lua_pushcfunction(_L, main);
lua_pushlstring(_L, autorun.c_str(), autorun.length());
info(TAG "Running \"%s\"", autorun.c_str());
if (!protectedCall(_L, 1, 0, &_logger)) {
return false;
}
}
undo.clear();
onStarted();
return true;
}
void hc::Application::destroy() {
Desktop::onQuit();
lua_close(_L);
ImGui_ImplOpenGL2_Shutdown();
ImGui_ImplSDL2_Shutdown();
ImGui::DestroyContext();
SDL_CloseAudioDevice(_audioDev);
_fifo.destroy();
SDL_GL_DeleteContext(_glContext);
SDL_DestroyWindow(_window);
SDL_Quit();
}
void hc::Application::run() {
bool done = false;
lrcpp::Frontend& frontend = lrcpp::Frontend::getInstance();
do {
SDL_Event event;
while (SDL_PollEvent(&event)) {
ImGui_ImplSDL2_ProcessEvent(&event);
_devices.process(&event);
if (event.type == SDL_QUIT) {
done = _fsm.quit();
}
}
if (_fsm.currentState() == LifeCycle::State::GameRunning) {
if (_runningTime.getTimeUs() >= _nextFrameTime) {
_nextFrameTime += _coreUsPerFrame;
_perf.start(&_runPerf);
frontend.run();
_perf.stop(&_runPerf);
_audio.flush();
onFrame();
}
}
ImGui_ImplOpenGL2_NewFrame();
ImGui_ImplSDL2_NewFrame(_window);
ImGui::NewFrame();
onDraw();
ImGui::Render();
glViewport(0, 0, (int)ImGui::GetIO().DisplaySize.x, (int)ImGui::GetIO().DisplaySize.y);
glClearColor(0.05f, 0.05f, 0.05f, 0);
glClear(GL_COLOR_BUFFER_BIT);
ImGui_ImplOpenGL2_RenderDrawData(ImGui::GetDrawData());
SDL_GL_SwapWindow(_window);
SDL_Delay(1);
}
while (!done);
}
bool hc::Application::loadCore(char const* path) {
info(TAG "Loading core \"%s\"", path);
lrcpp::Frontend& frontend = lrcpp::Frontend::getInstance();
if (!frontend.load(path)) {
return false;
}
retro_system_info sysinfo;
if (frontend.getSystemInfo(&sysinfo)) {
_control.setSystemInfo(&sysinfo);
}
info(TAG "System Info");
info(TAG " library_name = %s", sysinfo.library_name);
info(TAG " library_version = %s", sysinfo.library_version);
info(TAG " valid_extensions = %s", sysinfo.valid_extensions);
info(TAG " need_fullpath = %s", sysinfo.need_fullpath ? "true" : "false");
info(TAG " block_extract = %s", sysinfo.block_extract ? "true" : "false");
onCoreLoaded();
return true;
}
bool hc::Application::loadGame(char const* path) {
info(TAG "Loading game from \"%s\"", path);
lrcpp::Frontend& frontend = lrcpp::Frontend::getInstance();
retro_system_info sysinfo;
if (!frontend.getSystemInfo(&sysinfo)) {
return false;
}
bool ok = false;
if (sysinfo.need_fullpath) {
ok = frontend.loadGame(path);
}
else {
size_t size = 0;
void const* data = readAll(&_logger, path, &size);
if (data == nullptr) {
return false;
}
ok = frontend.loadGame(path, data, size);
free(const_cast<void*>(data));
}
if (!ok) {
return false;
}
static struct {char const* const name; unsigned const id;} memory[] = {
{"save", RETRO_MEMORY_SAVE_RAM},
{"rtc", RETRO_MEMORY_RTC},
{"sram", RETRO_MEMORY_SYSTEM_RAM},
{"vram", RETRO_MEMORY_VIDEO_RAM}
};
info(TAG "Core memory");
bool any = false;
for (size_t i = 0; i < sizeof(memory) / sizeof(memory[0]); i++) {
void* data = nullptr;
size_t size = 0;
if (frontend.getMemoryData(memory[i].id, &data) && frontend.getMemorySize(memory[i].id, &size) && size != 0) {
info(TAG " %-4s %p %zu bytes", memory[i].name, data, size);
any = true;
}
}
if (!any) {
info(TAG " No core memory exposed via the get_memory interface");
}
onGameLoaded();
return true;
}
bool hc::Application::pauseGame() {
SDL_GL_SetSwapInterval(1);
onGamePaused();
return true;
}
bool hc::Application::quit() {
onQuit();
return true;
}
bool hc::Application::resetGame() {
onGameReset();
return lrcpp::Frontend::getInstance().reset();
}
bool hc::Application::resumeGame() {
SDL_GL_SetSwapInterval(0);
onGameResumed();
return true;
}
bool hc::Application::startGame() {
SDL_GL_SetSwapInterval(0);
onGameStarted();
return true;
}
bool hc::Application::step() {
_perf.start(&_runPerf);
bool const ok = lrcpp::Frontend::getInstance().run();
_perf.stop(&_runPerf);
onFrame();
return ok;
}
bool hc::Application::unloadCore() {
if (lrcpp::Frontend::getInstance().unload()) {
onCoreUnloaded();
return true;
}
return false;
}
bool hc::Application::unloadGame() {
SDL_GL_SetSwapInterval(1);
if (lrcpp::Frontend::getInstance().unloadGame()) {
onGameUnloaded();
_runPerf.start = _runPerf.total = _runPerf.call_cnt = 0;
return true;
}
return false;
}
char const* hc::Application::getTitle() {
return ICON_FA_PLUG " Desktop";
}
void hc::Application::onCoreLoaded() {
// Perf has to unregister all counters when a core is unloaded so we
// register this here.
_runPerf.ident = "hc::retro_run";
_perf.register_(&_runPerf);
Desktop::onCoreLoaded();
}
void hc::Application::onGameLoaded() {
Desktop::onGameLoaded();
_coreUsPerFrame = 1000000.0 / _video.getCoreFps();
}
void hc::Application::onGameStarted() {
Desktop::onGameStarted();
_runningTime.start();
_nextFrameTime = _runningTime.getTimeUs();
}
void hc::Application::onGamePaused() {
Desktop::onGamePaused();
_runningTime.pause();
}
void hc::Application::onGameResumed() {
Desktop::onGameResumed();
_runningTime.resume();
_nextFrameTime = _runningTime.getTimeUs() + _coreUsPerFrame;
}
void hc::Application::onDraw() {
ImGui::DockSpaceOverViewport();
Desktop::onDraw();
}
void hc::Application::onGameUnloaded() {
Desktop::onGameUnloaded();
_runningTime.stop();
}
int hc::Application::push(lua_State* const L) {
static struct {char const* name; char const* value;} const stringConsts[] = {
{"_COPYRIGHT", "Copyright (c) 2020-2021 Andre Leiradella"},
{"_LICENSE", "MIT"},
{"_VERSION", "0.0.1"},
{"_NAME", "hc"},
{"_URL", "https://github.com/leiradel/hackable-console"},
{"_DESCRIPTION", "Hackable Console bindings"},
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
{"soExtension", "dll"}
#elif __linux__
{"soExtension", "so"}
#elif __APPLE__
{"soExtension", "dylib"}
#else
#error Unsupported platform
#endif
};
size_t const stringCount = sizeof(stringConsts) / sizeof(stringConsts[0]);
lua_createtable(L, 0, stringCount + 6);
_logger.push(L);
lua_setfield(L, -2, "logger");
_config.push(L);
lua_setfield(L, -2, "config");
_led.push(L);
lua_setfield(L, -2, "led");
_perf.push(L);
lua_setfield(L, -2, "perf");
_control.push(L);
lua_setfield(L, -2, "control");
_memorySelector.push(L);
lua_setfield(L, -2, "memory");
_repl.push(L);
lua_setfield(L, -2, "repl");
hc::cheats::push(_L);
lua_setfield(L, -2, "cheats");
for (size_t i = 0; i < stringCount; i++) {
lua_pushstring(L, stringConsts[i].value);
lua_setfield(L, -2, stringConsts[i].name);
}
return 1;
}
void hc::Application::sdlPrint(void* userdata, int category, SDL_LogPriority priority, char const* message) {
auto const self = static_cast<Application*>(userdata);
char const* categoryStr = "?";
switch (category) {
case SDL_LOG_CATEGORY_APPLICATION: categoryStr = "application"; break;
case SDL_LOG_CATEGORY_ERROR: categoryStr = "error"; break;
case SDL_LOG_CATEGORY_ASSERT: categoryStr = "assert"; break;
case SDL_LOG_CATEGORY_SYSTEM: categoryStr = "system"; break;
case SDL_LOG_CATEGORY_AUDIO: categoryStr = "audio"; break;
case SDL_LOG_CATEGORY_VIDEO: categoryStr = "video"; break;
case SDL_LOG_CATEGORY_RENDER: categoryStr = "render"; break;
case SDL_LOG_CATEGORY_INPUT: categoryStr = "input"; break;
case SDL_LOG_CATEGORY_TEST: categoryStr = "test"; break;
case SDL_LOG_CATEGORY_CUSTOM: categoryStr = "custom"; break;
}
switch (priority) {
case SDL_LOG_PRIORITY_VERBOSE:
case SDL_LOG_PRIORITY_DEBUG: self->debug("[SDL] (%s): %s", categoryStr, message); break;
case SDL_LOG_PRIORITY_INFO: self->info("[SDL] (%s): %s", categoryStr, message); break;
case SDL_LOG_PRIORITY_WARN: self->warn("[SDL] (%s): %s", categoryStr, message); break;
case SDL_LOG_PRIORITY_ERROR:
case SDL_LOG_PRIORITY_CRITICAL: self->error("[SDL] (%s): %s", categoryStr, message); break;
case SDL_NUM_LOG_PRIORITIES: self->error("[SDL] (%s): Invalid priority %d", categoryStr, priority); break;
}
}
void hc::Application::lifeCycleVprintf(void* ud, char const* fmt, va_list args) {
auto const self = static_cast<Application*>(ud);
self->vprintf(RETRO_LOG_DEBUG, fmt, args);
}
void hc::Application::audioCallback(void* const udata, Uint8* const stream, int const len) {
auto const self = static_cast<Application*>(udata);
size_t const avail = self->_fifo.occupied();
if (avail < (size_t)len) {
self->_fifo.read(static_cast<void*>(stream), avail);
memset(static_cast<void*>(stream + avail), 0, len - avail);
}
else {
self->_fifo.read(static_cast<void*>(stream), len);
}
}