-
Notifications
You must be signed in to change notification settings - Fork 17
/
nanoarch.c
601 lines (443 loc) · 14.1 KB
/
nanoarch.c
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
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdbool.h>
#include <errno.h>
#include <dlfcn.h>
#include "libretro.h"
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <alsa/asoundlib.h>
static GLFWwindow *g_win = NULL;
static snd_pcm_t *g_pcm = NULL;
static float g_scale = 3;
static GLfloat g_vertex[] = {
-1.0f, -1.0f, // left-bottom
-1.0f, 1.0f, // left-top
1.0f, -1.0f, // right-bottom
1.0f, 1.0f, // right-top
};
static GLfloat g_texcoords[] ={
0.0f, 1.0f,
0.0f, 0.0f,
1.0f, 1.0f,
1.0f, 0.0f,
};
static struct {
GLuint tex_id;
GLuint pitch;
GLint tex_w, tex_h;
GLuint clip_w, clip_h;
GLuint pixfmt;
GLuint pixtype;
GLuint bpp;
} g_video = {0};
static struct {
void *handle;
bool initialized;
void (*retro_init)(void);
void (*retro_deinit)(void);
unsigned (*retro_api_version)(void);
void (*retro_get_system_info)(struct retro_system_info *info);
void (*retro_get_system_av_info)(struct retro_system_av_info *info);
void (*retro_set_controller_port_device)(unsigned port, unsigned device);
void (*retro_reset)(void);
void (*retro_run)(void);
size_t (*retro_serialize_size)(void);
bool (*retro_serialize)(void *data, size_t size);
bool (*retro_unserialize)(const void *data, size_t size);
// void retro_cheat_reset(void);
// void retro_cheat_set(unsigned index, bool enabled, const char *code);
bool (*retro_load_game)(const struct retro_game_info *game);
// bool retro_load_game_special(unsigned game_type, const struct retro_game_info *info, size_t num_info);
void (*retro_unload_game)(void);
// unsigned retro_get_region(void);
// void *retro_get_memory_data(unsigned id);
// size_t retro_get_memory_size(unsigned id);
} g_retro;
struct keymap {
unsigned k;
unsigned rk;
};
struct keymap g_binds[] = {
{ GLFW_KEY_X, RETRO_DEVICE_ID_JOYPAD_A },
{ GLFW_KEY_Z, RETRO_DEVICE_ID_JOYPAD_B },
{ GLFW_KEY_A, RETRO_DEVICE_ID_JOYPAD_Y },
{ GLFW_KEY_S, RETRO_DEVICE_ID_JOYPAD_X },
{ GLFW_KEY_Q, RETRO_DEVICE_ID_JOYPAD_L },
{ GLFW_KEY_W, RETRO_DEVICE_ID_JOYPAD_R },
{ GLFW_KEY_UP, RETRO_DEVICE_ID_JOYPAD_UP },
{ GLFW_KEY_DOWN, RETRO_DEVICE_ID_JOYPAD_DOWN },
{ GLFW_KEY_LEFT, RETRO_DEVICE_ID_JOYPAD_LEFT },
{ GLFW_KEY_RIGHT, RETRO_DEVICE_ID_JOYPAD_RIGHT },
{ GLFW_KEY_ENTER, RETRO_DEVICE_ID_JOYPAD_START },
{ GLFW_KEY_BACKSPACE, RETRO_DEVICE_ID_JOYPAD_SELECT },
{ 0, 0 }
};
static unsigned g_joy[RETRO_DEVICE_ID_JOYPAD_R3+1] = { 0 };
#define load_sym(V, S) do {\
if (!((*(void**)&V) = dlsym(g_retro.handle, #S))) \
die("Failed to load symbol '" #S "'': %s", dlerror()); \
} while (0)
#define load_retro_sym(S) load_sym(g_retro.S, S)
static void die(const char *fmt, ...) {
char buffer[4096];
va_list va;
va_start(va, fmt);
vsnprintf(buffer, sizeof(buffer), fmt, va);
va_end(va);
fputs(buffer, stderr);
fputc('\n', stderr);
fflush(stderr);
exit(EXIT_FAILURE);
}
static void refresh_vertex_data() {
assert(g_video.tex_w);
assert(g_video.tex_h);
assert(g_video.clip_w);
assert(g_video.clip_h);
GLfloat *coords = g_texcoords;
coords[1] = coords[5] = (float)g_video.clip_h / g_video.tex_h;
coords[4] = coords[6] = (float)g_video.clip_w / g_video.tex_w;
}
static void resize_cb(GLFWwindow *win, int w, int h) {
glViewport(0, 0, w, h);
}
static void create_window(int width, int height) {
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
g_win = glfwCreateWindow(width, height, "nanoarch", NULL, NULL);
if (!g_win)
die("Failed to create window.");
glfwSetFramebufferSizeCallback(g_win, resize_cb);
glfwMakeContextCurrent(g_win);
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK)
die("Failed to initialize glew");
glfwSwapInterval(1);
printf("GLSL Version: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
glEnable(GL_TEXTURE_2D);
// refresh_vertex_data();
resize_cb(g_win, width, height);
}
static void resize_to_aspect(double ratio, int sw, int sh, int *dw, int *dh) {
*dw = sw;
*dh = sh;
if (ratio <= 0)
ratio = (double)sw / sh;
if ((float)sw / sh < 1)
*dw = *dh * ratio;
else
*dh = *dw / ratio;
}
static void video_configure(const struct retro_game_geometry *geom) {
int nwidth, nheight;
resize_to_aspect(geom->aspect_ratio, geom->base_width * 1, geom->base_height * 1, &nwidth, &nheight);
nwidth *= g_scale;
nheight *= g_scale;
if (!g_win)
create_window(nwidth, nheight);
if (g_video.tex_id)
glDeleteTextures(1, &g_video.tex_id);
g_video.tex_id = 0;
if (!g_video.pixfmt)
g_video.pixfmt = GL_UNSIGNED_SHORT_5_5_5_1;
glfwSetWindowSize(g_win, nwidth, nheight);
glfwSetWindowAttrib(g_win, GLFW_RESIZABLE, GLFW_TRUE);
glfwSetWindowAspectRatio(g_win, nwidth, nheight);
glGenTextures(1, &g_video.tex_id);
if (!g_video.tex_id)
die("Failed to create the video texture");
g_video.pitch = geom->base_width * g_video.bpp;
glBindTexture(GL_TEXTURE_2D, g_video.tex_id);
// glPixelStorei(GL_UNPACK_ALIGNMENT, s_video.pixfmt == GL_UNSIGNED_INT_8_8_8_8_REV ? 4 : 2);
// glPixelStorei(GL_UNPACK_ROW_LENGTH, s_video.pitch / s_video.bpp);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, geom->max_width, geom->max_height, 0,
g_video.pixtype, g_video.pixfmt, NULL);
glBindTexture(GL_TEXTURE_2D, 0);
g_video.tex_w = geom->max_width;
g_video.tex_h = geom->max_height;
g_video.clip_w = geom->base_width;
g_video.clip_h = geom->base_height;
refresh_vertex_data();
}
static bool video_set_pixel_format(unsigned format) {
if (g_video.tex_id)
die("Tried to change pixel format after initialization.");
switch (format) {
case RETRO_PIXEL_FORMAT_0RGB1555:
g_video.pixfmt = GL_UNSIGNED_SHORT_5_5_5_1;
g_video.pixtype = GL_BGRA;
g_video.bpp = sizeof(uint16_t);
break;
case RETRO_PIXEL_FORMAT_XRGB8888:
g_video.pixfmt = GL_UNSIGNED_INT_8_8_8_8_REV;
g_video.pixtype = GL_BGRA;
g_video.bpp = sizeof(uint32_t);
break;
case RETRO_PIXEL_FORMAT_RGB565:
g_video.pixfmt = GL_UNSIGNED_SHORT_5_6_5;
g_video.pixtype = GL_RGB;
g_video.bpp = sizeof(uint16_t);
break;
default:
die("Unknown pixel type %u", format);
}
return true;
}
static void video_refresh(const void *data, unsigned width, unsigned height, unsigned pitch) {
if (g_video.clip_w != width || g_video.clip_h != height) {
g_video.clip_h = height;
g_video.clip_w = width;
refresh_vertex_data();
}
glBindTexture(GL_TEXTURE_2D, g_video.tex_id);
if (pitch != g_video.pitch) {
g_video.pitch = pitch;
glPixelStorei(GL_UNPACK_ROW_LENGTH, g_video.pitch / g_video.bpp);
}
if (data) {
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height,
g_video.pixtype, g_video.pixfmt, data);
}
}
static void video_render() {
glBindTexture(GL_TEXTURE_2D, g_video.tex_id);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, g_vertex);
glTexCoordPointer(2, GL_FLOAT, 0, g_texcoords);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
static void video_deinit() {
if (g_video.tex_id)
glDeleteTextures(1, &g_video.tex_id);
g_video.tex_id = 0;
}
static void audio_init(int frequency) {
int err;
if ((err = snd_pcm_open(&g_pcm, "default", SND_PCM_STREAM_PLAYBACK, 0)) < 0)
die("Failed to open playback device: %s", snd_strerror(err));
err = snd_pcm_set_params(g_pcm, SND_PCM_FORMAT_S16, SND_PCM_ACCESS_RW_INTERLEAVED, 2, frequency, 1, 64 * 1000);
if (err < 0)
die("Failed to configure playback device: %s", snd_strerror(err));
}
static void audio_deinit() {
snd_pcm_close(g_pcm);
}
static size_t audio_write(const void *buf, unsigned frames) {
if (!g_pcm)
return 0;
int written = snd_pcm_writei(g_pcm, buf, frames);
if (written < 0) {
printf("Alsa warning/error #%i: ", -written);
snd_pcm_recover(g_pcm, written, 0);
return 0;
}
return written;
}
static void core_log(enum retro_log_level level, const char *fmt, ...) {
char buffer[4096] = {0};
static const char * levelstr[] = { "dbg", "inf", "wrn", "err" };
va_list va;
va_start(va, fmt);
vsnprintf(buffer, sizeof(buffer), fmt, va);
va_end(va);
if (level == 0)
return;
fprintf(stderr, "[%s] %s", levelstr[level], buffer);
fflush(stderr);
if (level == RETRO_LOG_ERROR)
exit(EXIT_FAILURE);
}
static bool core_environment(unsigned cmd, void *data) {
bool *bval;
switch (cmd) {
case RETRO_ENVIRONMENT_GET_LOG_INTERFACE: {
struct retro_log_callback *cb = (struct retro_log_callback *)data;
cb->log = core_log;
break;
}
case RETRO_ENVIRONMENT_GET_CAN_DUPE:
bval = (bool*)data;
*bval = true;
break;
case RETRO_ENVIRONMENT_SET_PIXEL_FORMAT: {
const enum retro_pixel_format *fmt = (enum retro_pixel_format *)data;
if (*fmt > RETRO_PIXEL_FORMAT_RGB565)
return false;
return video_set_pixel_format(*fmt);
}
case RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY:
case RETRO_ENVIRONMENT_GET_SAVE_DIRECTORY:
*(const char **)data = ".";
return true;
default:
core_log(RETRO_LOG_DEBUG, "Unhandled env #%u", cmd);
return false;
}
return true;
}
static void core_video_refresh(const void *data, unsigned width, unsigned height, size_t pitch) {
if (data)
video_refresh(data, width, height, pitch);
}
static void core_input_poll(void) {
int i;
for (i = 0; g_binds[i].k || g_binds[i].rk; ++i)
g_joy[g_binds[i].rk] = (glfwGetKey(g_win, g_binds[i].k) == GLFW_PRESS);
// Quit nanoarch when pressing the Escape key.
if (glfwGetKey(g_win, GLFW_KEY_ESCAPE) == GLFW_PRESS) {
glfwSetWindowShouldClose(g_win, true);
}
}
static int16_t core_input_state(unsigned port, unsigned device, unsigned index, unsigned id) {
if (port || index || device != RETRO_DEVICE_JOYPAD)
return 0;
return g_joy[id];
}
static void core_audio_sample(int16_t left, int16_t right) {
int16_t buf[2] = {left, right};
audio_write(buf, 1);
}
static size_t core_audio_sample_batch(const int16_t *data, size_t frames) {
return audio_write(data, frames);
}
static void core_load(const char *sofile) {
void (*set_environment)(retro_environment_t) = NULL;
void (*set_video_refresh)(retro_video_refresh_t) = NULL;
void (*set_input_poll)(retro_input_poll_t) = NULL;
void (*set_input_state)(retro_input_state_t) = NULL;
void (*set_audio_sample)(retro_audio_sample_t) = NULL;
void (*set_audio_sample_batch)(retro_audio_sample_batch_t) = NULL;
memset(&g_retro, 0, sizeof(g_retro));
g_retro.handle = dlopen(sofile, RTLD_LAZY);
if (!g_retro.handle)
die("Failed to load core: %s", dlerror());
dlerror();
load_retro_sym(retro_init);
load_retro_sym(retro_deinit);
load_retro_sym(retro_api_version);
load_retro_sym(retro_get_system_info);
load_retro_sym(retro_get_system_av_info);
load_retro_sym(retro_set_controller_port_device);
load_retro_sym(retro_reset);
load_retro_sym(retro_run);
load_retro_sym(retro_load_game);
load_retro_sym(retro_unload_game);
load_retro_sym(retro_serialize_size);
load_retro_sym(retro_serialize);
load_retro_sym(retro_unserialize);
load_sym(set_environment, retro_set_environment);
load_sym(set_video_refresh, retro_set_video_refresh);
load_sym(set_input_poll, retro_set_input_poll);
load_sym(set_input_state, retro_set_input_state);
load_sym(set_audio_sample, retro_set_audio_sample);
load_sym(set_audio_sample_batch, retro_set_audio_sample_batch);
set_environment(core_environment);
set_video_refresh(core_video_refresh);
set_input_poll(core_input_poll);
set_input_state(core_input_state);
set_audio_sample(core_audio_sample);
set_audio_sample_batch(core_audio_sample_batch);
g_retro.retro_init();
g_retro.initialized = true;
puts("Core loaded");
}
static void core_load_game(const char *filename) {
struct retro_system_av_info av = {0};
struct retro_system_info system = {0};
struct retro_game_info info = { filename, 0 };
FILE *file = fopen(filename, "rb");
if (!file)
goto libc_error;
fseek(file, 0, SEEK_END);
info.size = ftell(file);
rewind(file);
g_retro.retro_get_system_info(&system);
if (!system.need_fullpath) {
info.data = malloc(info.size);
if (!info.data || !fread((void*)info.data, info.size, 1, file))
goto libc_error;
}
if (!g_retro.retro_load_game(&info))
die("The core failed to load the content.");
g_retro.retro_get_system_av_info(&av);
video_configure(&av.geometry);
audio_init(av.timing.sample_rate);
return;
libc_error:
die("Failed to load content '%s': %s", filename, strerror(errno));
}
static void core_unload() {
if (g_retro.initialized)
g_retro.retro_deinit();
if (g_retro.handle)
dlclose(g_retro.handle);
}
int main(int argc, char *argv[]) {
if (argc < 3)
die("usage: %s <core> <game> [-s default-scale] [-l load-savestate] [-d save-savestate]", argv[0]);
if (!glfwInit())
die("Failed to initialize glfw");
char **opts = &argv[3];
char *savestatel = NULL;
char *savestated = NULL;
while (*opts) {
if (!strcmp(*opts, "-s"))
g_scale = atoi(*(++opts));
else if (!strcmp(*opts, "-l"))
savestatel = *(++opts);
else if (!strcmp(*opts, "-d"))
savestated = *(++opts);
opts++;
}
core_load(argv[1]);
core_load_game(argv[2]);
if (savestatel) {
FILE *fd = fopen(savestatel, "rb");
if (!fd)
die("Failed to find savestate file '%s'", savestatel);
void *saveblob = malloc(g_retro.retro_serialize_size());
size_t rdb = fread(saveblob, 1, g_retro.retro_serialize_size(), fd);
if (!g_retro.retro_unserialize(saveblob, rdb))
die("Failed to load savestate, core returned error");
fclose(fd);
free(saveblob);
}
while (!glfwWindowShouldClose(g_win)) {
glfwPollEvents();
// Reset core on R key.
if (glfwGetKey(g_win, GLFW_KEY_R) == GLFW_PRESS) {
g_retro.retro_reset();
}
g_retro.retro_run();
glClear(GL_COLOR_BUFFER_BIT);
video_render();
glfwSwapBuffers(g_win);
}
if (savestated) {
FILE *fd = fopen(savestated, "wb");
if (!fd) {
fprintf(stderr, "Could not write savestate dump to '%s'", savestated);
} else {
size_t savsz = g_retro.retro_serialize_size();
void *saveblob = malloc(savsz);
if (!g_retro.retro_serialize(saveblob, savsz)) {
fprintf(stderr, "Could not generate savestate, core returned error");
} else {
fwrite(saveblob, 1, savsz, fd);
}
free(saveblob);
fclose(fd);
}
}
core_unload();
audio_deinit();
video_deinit();
glfwTerminate();
return 0;
}