-
Notifications
You must be signed in to change notification settings - Fork 13
/
sdlarch.c
1049 lines (811 loc) · 28.7 KB
/
sdlarch.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
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
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <SDL.h>
#include "libretro.h"
#include "glad.h"
static SDL_Window *g_win = NULL;
static SDL_GLContext *g_ctx = NULL;
static SDL_AudioDeviceID g_pcm = 0;
static struct retro_frame_time_callback runloop_frame_time;
static retro_usec_t runloop_frame_time_last = 0;
static const uint8_t *g_kbd = NULL;
static struct retro_audio_callback audio_callback;
static float g_scale = 3;
bool running = true;
static struct {
GLuint tex_id;
GLuint fbo_id;
GLuint rbo_id;
int glmajor;
int glminor;
GLuint pitch;
GLint tex_w, tex_h;
GLuint clip_w, clip_h;
GLuint pixfmt;
GLuint pixtype;
GLuint bpp;
struct retro_hw_render_callback hw;
} g_video = {0};
static struct {
GLuint vao;
GLuint vbo;
GLuint program;
GLint i_pos;
GLint i_coord;
GLint u_tex;
GLint u_mvp;
} g_shader = {0};
static struct retro_variable *g_vars = NULL;
static const char *g_vshader_src =
"#version 150\n"
"in vec2 i_pos;\n"
"in vec2 i_coord;\n"
"out vec2 o_coord;\n"
"uniform mat4 u_mvp;\n"
"void main() {\n"
"o_coord = i_coord;\n"
"gl_Position = vec4(i_pos, 0.0, 1.0) * u_mvp;\n"
"}";
static const char *g_fshader_src =
"#version 150\n"
"in vec2 o_coord;\n"
"uniform sampler2D u_tex;\n"
"void main() {\n"
"gl_FragColor = texture2D(u_tex, o_coord);\n"
"}";
static struct {
void *handle;
bool initialized;
bool supports_no_game;
// The last performance counter registered. TODO: Make it a linked list.
struct retro_perf_counter* perf_counter_last;
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;
};
static struct keymap g_binds[] = {
{ SDL_SCANCODE_X, RETRO_DEVICE_ID_JOYPAD_A },
{ SDL_SCANCODE_Z, RETRO_DEVICE_ID_JOYPAD_B },
{ SDL_SCANCODE_A, RETRO_DEVICE_ID_JOYPAD_Y },
{ SDL_SCANCODE_S, RETRO_DEVICE_ID_JOYPAD_X },
{ SDL_SCANCODE_UP, RETRO_DEVICE_ID_JOYPAD_UP },
{ SDL_SCANCODE_DOWN, RETRO_DEVICE_ID_JOYPAD_DOWN },
{ SDL_SCANCODE_LEFT, RETRO_DEVICE_ID_JOYPAD_LEFT },
{ SDL_SCANCODE_RIGHT, RETRO_DEVICE_ID_JOYPAD_RIGHT },
{ SDL_SCANCODE_RETURN, RETRO_DEVICE_ID_JOYPAD_START },
{ SDL_SCANCODE_BACKSPACE, RETRO_DEVICE_ID_JOYPAD_SELECT },
{ SDL_SCANCODE_Q, RETRO_DEVICE_ID_JOYPAD_L },
{ SDL_SCANCODE_W, RETRO_DEVICE_ID_JOYPAD_R },
{ 0, 0 }
};
static unsigned g_joy[RETRO_DEVICE_ID_JOYPAD_R3+1] = { 0 };
#define load_sym(V, S) do {\
if (!((*(void**)&V) = SDL_LoadFunction(g_retro.handle, #S))) \
die("Failed to load symbol '" #S "'': %s", SDL_GetError()); \
} 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 GLuint compile_shader(unsigned type, unsigned count, const char **strings) {
GLuint shader = glCreateShader(type);
glShaderSource(shader, count, strings, NULL);
glCompileShader(shader);
GLint status;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE) {
char buffer[4096];
glGetShaderInfoLog(shader, sizeof(buffer), NULL, buffer);
die("Failed to compile %s shader: %s", type == GL_VERTEX_SHADER ? "vertex" : "fragment", buffer);
}
return shader;
}
void ortho2d(float m[4][4], float left, float right, float bottom, float top) {
m[0][0] = 1; m[0][1] = 0; m[0][2] = 0; m[0][3] = 0;
m[1][0] = 0; m[1][1] = 1; m[1][2] = 0; m[1][3] = 0;
m[2][0] = 0; m[2][1] = 0; m[2][2] = 1; m[2][3] = 0;
m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[3][3] = 1;
m[0][0] = 2.0f / (right - left);
m[1][1] = 2.0f / (top - bottom);
m[2][2] = -1.0f;
m[3][0] = -(right + left) / (right - left);
m[3][1] = -(top + bottom) / (top - bottom);
}
static void init_shaders() {
GLuint vshader = compile_shader(GL_VERTEX_SHADER, 1, &g_vshader_src);
GLuint fshader = compile_shader(GL_FRAGMENT_SHADER, 1, &g_fshader_src);
GLuint program = glCreateProgram();
SDL_assert(program);
glAttachShader(program, vshader);
glAttachShader(program, fshader);
glLinkProgram(program);
glDeleteShader(vshader);
glDeleteShader(fshader);
glValidateProgram(program);
GLint status;
glGetProgramiv(program, GL_LINK_STATUS, &status);
if(status == GL_FALSE) {
char buffer[4096];
glGetProgramInfoLog(program, sizeof(buffer), NULL, buffer);
die("Failed to link shader program: %s", buffer);
}
g_shader.program = program;
g_shader.i_pos = glGetAttribLocation(program, "i_pos");
g_shader.i_coord = glGetAttribLocation(program, "i_coord");
g_shader.u_tex = glGetUniformLocation(program, "u_tex");
g_shader.u_mvp = glGetUniformLocation(program, "u_mvp");
glGenVertexArrays(1, &g_shader.vao);
glGenBuffers(1, &g_shader.vbo);
glUseProgram(g_shader.program);
glUniform1i(g_shader.u_tex, 0);
float m[4][4];
if (g_video.hw.bottom_left_origin)
ortho2d(m, -1, 1, 1, -1);
else
ortho2d(m, -1, 1, -1, 1);
glUniformMatrix4fv(g_shader.u_mvp, 1, GL_FALSE, (float*)m);
glUseProgram(0);
}
static void refresh_vertex_data() {
SDL_assert(g_video.tex_w);
SDL_assert(g_video.tex_h);
SDL_assert(g_video.clip_w);
SDL_assert(g_video.clip_h);
float bottom = (float)g_video.clip_h / g_video.tex_h;
float right = (float)g_video.clip_w / g_video.tex_w;
float vertex_data[] = {
// pos, coord
-1.0f, -1.0f, 0.0f, bottom, // left-bottom
-1.0f, 1.0f, 0.0f, 0.0f, // left-top
1.0f, -1.0f, right, bottom,// right-bottom
1.0f, 1.0f, right, 0.0f, // right-top
};
glBindVertexArray(g_shader.vao);
glBindBuffer(GL_ARRAY_BUFFER, g_shader.vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data), vertex_data, GL_STREAM_DRAW);
glEnableVertexAttribArray(g_shader.i_pos);
glEnableVertexAttribArray(g_shader.i_coord);
glVertexAttribPointer(g_shader.i_pos, 2, GL_FLOAT, GL_FALSE, sizeof(float)*4, 0);
glVertexAttribPointer(g_shader.i_coord, 2, GL_FLOAT, GL_FALSE, sizeof(float)*4, (void*)(2 * sizeof(float)));
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
static void init_framebuffer(int width, int height)
{
glGenFramebuffers(1, &g_video.fbo_id);
glBindFramebuffer(GL_FRAMEBUFFER, g_video.fbo_id);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, g_video.tex_id, 0);
if (g_video.hw.depth && g_video.hw.stencil) {
glGenRenderbuffers(1, &g_video.rbo_id);
glBindRenderbuffer(GL_RENDERBUFFER, g_video.rbo_id);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, g_video.rbo_id);
} else if (g_video.hw.depth) {
glGenRenderbuffers(1, &g_video.rbo_id);
glBindRenderbuffer(GL_RENDERBUFFER, g_video.rbo_id);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, width, height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, g_video.rbo_id);
}
if (g_video.hw.depth || g_video.hw.stencil)
glBindRenderbuffer(GL_RENDERBUFFER, 0);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
SDL_assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
static void resize_cb(int w, int h) {
glViewport(0, 0, w, h);
}
static void create_window(int width, int height) {
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
if (g_video.hw.context_type == RETRO_HW_CONTEXT_OPENGL_CORE || g_video.hw.version_major >= 3) {
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, g_video.hw.version_major);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, g_video.hw.version_minor);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
}
switch (g_video.hw.context_type) {
case RETRO_HW_CONTEXT_OPENGL_CORE:
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
break;
case RETRO_HW_CONTEXT_OPENGLES2:
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
break;
case RETRO_HW_CONTEXT_OPENGL:
if (g_video.hw.version_major >= 3)
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);
break;
default:
die("Unsupported hw context %i. (only OPENGL, OPENGL_CORE and OPENGLES2 supported)", g_video.hw.context_type);
}
g_win = SDL_CreateWindow("sdlarch", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL);
if (!g_win)
die("Failed to create window: %s", SDL_GetError());
g_ctx = SDL_GL_CreateContext(g_win);
SDL_GL_MakeCurrent(g_win, g_ctx);
if (!g_ctx)
die("Failed to create OpenGL context: %s", SDL_GetError());
if (g_video.hw.context_type == RETRO_HW_CONTEXT_OPENGLES2) {
if (!gladLoadGLES2Loader((GLADloadproc)SDL_GL_GetProcAddress))
die("Failed to initialize glad.");
} else {
if (!gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress))
die("Failed to initialize glad.");
}
fprintf(stderr, "GL_SHADING_LANGUAGE_VERSION: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
fprintf(stderr, "GL_VERSION: %s\n", glGetString(GL_VERSION));
init_shaders();
SDL_GL_SetSwapInterval(1);
SDL_GL_SwapWindow(g_win); // make apitrace output nicer
resize_cb(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;
SDL_SetWindowSize(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->max_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);
init_framebuffer(geom->max_width, geom->max_height);
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();
g_video.hw.context_reset();
}
static bool video_set_pixel_format(unsigned format) {
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();
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindTexture(GL_TEXTURE_2D, g_video.tex_id);
if (pitch != g_video.pitch)
g_video.pitch = pitch;
if (data && data != RETRO_HW_FRAME_BUFFER_VALID) {
glPixelStorei(GL_UNPACK_ROW_LENGTH, g_video.pitch / g_video.bpp);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height,
g_video.pixtype, g_video.pixfmt, data);
}
int w = 0, h = 0;
SDL_GetWindowSize(g_win, &w, &h);
glViewport(0, 0, w, h);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(g_shader.program);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, g_video.tex_id);
glBindVertexArray(g_shader.vao);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glBindVertexArray(0);
glUseProgram(0);
SDL_GL_SwapWindow(g_win);
}
static void video_deinit() {
if (g_video.fbo_id)
glDeleteFramebuffers(1, &g_video.fbo_id);
if (g_video.tex_id)
glDeleteTextures(1, &g_video.tex_id);
if (g_shader.vao)
glDeleteVertexArrays(1, &g_shader.vao);
if (g_shader.vbo)
glDeleteBuffers(1, &g_shader.vbo);
if (g_shader.program)
glDeleteProgram(g_shader.program);
g_video.fbo_id = 0;
g_video.tex_id = 0;
g_shader.vao = 0;
g_shader.vbo = 0;
g_shader.program = 0;
SDL_GL_MakeCurrent(g_win, g_ctx);
SDL_GL_DeleteContext(g_ctx);
g_ctx = NULL;
SDL_DestroyWindow(g_win);
}
static void audio_init(int frequency) {
SDL_AudioSpec desired;
SDL_AudioSpec obtained;
SDL_zero(desired);
SDL_zero(obtained);
desired.format = AUDIO_S16;
desired.freq = frequency;
desired.channels = 2;
desired.samples = 4096;
g_pcm = SDL_OpenAudioDevice(NULL, 0, &desired, &obtained, 0);
if (!g_pcm)
die("Failed to open playback device: %s", SDL_GetError());
SDL_PauseAudioDevice(g_pcm, 0);
// Let the core know that the audio device has been initialized.
if (audio_callback.set_state) {
audio_callback.set_state(true);
}
}
static void audio_deinit() {
SDL_CloseAudioDevice(g_pcm);
}
static size_t audio_write(const int16_t *buf, unsigned frames) {
SDL_QueueAudio(g_pcm, buf, sizeof(*buf) * frames * 2);
return frames;
}
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 uintptr_t core_get_current_framebuffer() {
return g_video.fbo_id;
}
/**
* cpu_features_get_time_usec:
*
* Gets time in microseconds.
*
* Returns: time in microseconds.
**/
retro_time_t cpu_features_get_time_usec(void) {
return (retro_time_t)SDL_GetTicks() * 1000;
}
/**
* Get the CPU Features.
*
* @see retro_get_cpu_features_t
* @return uint64_t Returns a bit-mask of detected CPU features (RETRO_SIMD_*).
*/
static uint64_t core_get_cpu_features() {
uint64_t cpu = 0;
if (SDL_HasAVX()) {
cpu |= RETRO_SIMD_AVX;
}
if (SDL_HasAVX2()) {
cpu |= RETRO_SIMD_AVX2;
}
if (SDL_HasMMX()) {
cpu |= RETRO_SIMD_MMX;
}
if (SDL_HasSSE()) {
cpu |= RETRO_SIMD_SSE;
}
if (SDL_HasSSE2()) {
cpu |= RETRO_SIMD_SSE2;
}
if (SDL_HasSSE3()) {
cpu |= RETRO_SIMD_SSE3;
}
if (SDL_HasSSE41()) {
cpu |= RETRO_SIMD_SSE4;
}
if (SDL_HasSSE42()) {
cpu |= RETRO_SIMD_SSE42;
}
return cpu;
}
/**
* A simple counter. Usually nanoseconds, but can also be CPU cycles.
*
* @see retro_perf_get_counter_t
* @return retro_perf_tick_t The current value of the high resolution counter.
*/
static retro_perf_tick_t core_get_perf_counter() {
return (retro_perf_tick_t)SDL_GetPerformanceCounter();
}
/**
* Register a performance counter.
*
* @see retro_perf_register_t
*/
static void core_perf_register(struct retro_perf_counter* counter) {
g_retro.perf_counter_last = counter;
counter->registered = true;
}
/**
* Starts a registered counter.
*
* @see retro_perf_start_t
*/
static void core_perf_start(struct retro_perf_counter* counter) {
if (counter->registered) {
counter->start = core_get_perf_counter();
}
}
/**
* Stops a registered counter.
*
* @see retro_perf_stop_t
*/
static void core_perf_stop(struct retro_perf_counter* counter) {
counter->total = core_get_perf_counter() - counter->start;
}
/**
* Log and display the state of performance counters.
*
* @see retro_perf_log_t
*/
static void core_perf_log() {
// TODO: Use a linked list of counters, and loop through them all.
core_log(RETRO_LOG_INFO, "[timer] %s: %i - %i", g_retro.perf_counter_last->ident, g_retro.perf_counter_last->start, g_retro.perf_counter_last->total);
}
static bool core_environment(unsigned cmd, void *data) {
switch (cmd) {
case RETRO_ENVIRONMENT_SET_VARIABLES: {
const struct retro_variable *vars = (const struct retro_variable *)data;
size_t num_vars = 0;
for (const struct retro_variable *v = vars; v->key; ++v) {
num_vars++;
}
g_vars = (struct retro_variable*)calloc(num_vars + 1, sizeof(*g_vars));
for (unsigned i = 0; i < num_vars; ++i) {
const struct retro_variable *invar = &vars[i];
struct retro_variable *outvar = &g_vars[i];
const char *semicolon = strchr(invar->value, ';');
const char *first_pipe = strchr(invar->value, '|');
SDL_assert(semicolon && *semicolon);
semicolon++;
while (isspace(*semicolon))
semicolon++;
if (first_pipe) {
outvar->value = malloc((first_pipe - semicolon) + 1);
memcpy((char*)outvar->value, semicolon, first_pipe - semicolon);
((char*)outvar->value)[first_pipe - semicolon] = '\0';
} else {
outvar->value = strdup(semicolon);
}
outvar->key = strdup(invar->key);
SDL_assert(outvar->key && outvar->value);
}
return true;
}
case RETRO_ENVIRONMENT_GET_VARIABLE: {
struct retro_variable *var = (struct retro_variable *)data;
if (!g_vars)
return false;
for (const struct retro_variable *v = g_vars; v->key; ++v) {
if (strcmp(var->key, v->key) == 0) {
var->value = v->value;
break;
}
}
return true;
}
case RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE: {
bool *bval = (bool*)data;
*bval = false;
return true;
}
case RETRO_ENVIRONMENT_GET_LOG_INTERFACE: {
struct retro_log_callback *cb = (struct retro_log_callback *)data;
cb->log = core_log;
return true;
}
case RETRO_ENVIRONMENT_GET_PERF_INTERFACE: {
struct retro_perf_callback *perf = (struct retro_perf_callback *)data;
perf->get_time_usec = cpu_features_get_time_usec;
perf->get_cpu_features = core_get_cpu_features;
perf->get_perf_counter = core_get_perf_counter;
perf->perf_register = core_perf_register;
perf->perf_start = core_perf_start;
perf->perf_stop = core_perf_stop;
perf->perf_log = core_perf_log;
return true;
}
case RETRO_ENVIRONMENT_GET_CAN_DUPE: {
bool *bval = (bool*)data;
*bval = true;
return true;
}
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_SET_HW_RENDER: {
struct retro_hw_render_callback *hw = (struct retro_hw_render_callback*)data;
hw->get_current_framebuffer = core_get_current_framebuffer;
hw->get_proc_address = (retro_hw_get_proc_address_t)SDL_GL_GetProcAddress;
g_video.hw = *hw;
return true;
}
case RETRO_ENVIRONMENT_SET_FRAME_TIME_CALLBACK: {
const struct retro_frame_time_callback *frame_time =
(const struct retro_frame_time_callback*)data;
runloop_frame_time = *frame_time;
return true;
}
case RETRO_ENVIRONMENT_SET_AUDIO_CALLBACK: {
struct retro_audio_callback *audio_cb = (struct retro_audio_callback*)data;
audio_callback = *audio_cb;
return true;
}
case RETRO_ENVIRONMENT_GET_SAVE_DIRECTORY:
case RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY: {
const char **dir = (const char**)data;
*dir = ".";
return true;
}
case RETRO_ENVIRONMENT_SET_GEOMETRY: {
const struct retro_game_geometry *geom = (const struct retro_game_geometry *)data;
g_video.clip_w = geom->base_width;
g_video.clip_h = geom->base_height;
// some cores call this before we even have a window
if (g_win) {
refresh_vertex_data();
int ow = 0, oh = 0;
resize_to_aspect(geom->aspect_ratio, geom->base_width, geom->base_height, &ow, &oh);
ow *= g_scale;
oh *= g_scale;
SDL_SetWindowSize(g_win, ow, oh);
}
return true;
}
case RETRO_ENVIRONMENT_SET_SUPPORT_NO_GAME: {
g_retro.supports_no_game = *(bool*)data;
return true;
}
case RETRO_ENVIRONMENT_GET_AUDIO_VIDEO_ENABLE: {
int *value = (int*)data;
*value = 1 << 0 | 1 << 1;
return true;
}
default:
core_log(RETRO_LOG_DEBUG, "Unhandled env #%u", cmd);
return false;
}
return false;
}
static void core_video_refresh(const void *data, unsigned width, unsigned height, size_t pitch) {
video_refresh(data, width, height, pitch);
}
static void core_input_poll(void) {
int i;
g_kbd = SDL_GetKeyboardState(NULL);
for (i = 0; g_binds[i].k || g_binds[i].rk; ++i)
g_joy[g_binds[i].rk] = g_kbd[g_binds[i].k];
if (g_kbd[SDL_SCANCODE_ESCAPE])
running = false;
}
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 = SDL_LoadObject(sofile);
if (!g_retro.handle)
die("Failed to load core: %s", SDL_GetError());
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_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 };
info.path = filename;
info.meta = "";
info.data = NULL;
info.size = 0;
if (filename) {
g_retro.retro_get_system_info(&system);
if (!system.need_fullpath) {
SDL_RWops *file = SDL_RWFromFile(filename, "rb");
Sint64 size;
if (!file)
die("Failed to load %s: %s", filename, SDL_GetError());
size = SDL_RWsize(file);
if (size < 0)
die("Failed to query game file size: %s", SDL_GetError());
info.size = size;
info.data = SDL_malloc(info.size);
if (!info.data)
die("Failed to allocate memory for the content");
if (!SDL_RWread(file, (void*)info.data, info.size, 1))
die("Failed to read file data: %s", SDL_GetError());
SDL_RWclose(file);
}
}
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);
if (info.data)
SDL_free((void*)info.data);
// Now that we have the system info, set the window title.
char window_title[255];
snprintf(window_title, sizeof(window_title), "sdlarch %s %s", system.library_name, system.library_version);
SDL_SetWindowTitle(g_win, window_title);
}
static void core_unload() {
if (g_retro.initialized)
g_retro.retro_deinit();
if (g_retro.handle)
SDL_UnloadObject(g_retro.handle);
}
static void noop() {}
int main(int argc, char *argv[]) {
if (argc < 2)
die("usage: %s <core> [game]", argv[0]);
if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO|SDL_INIT_EVENTS) < 0)
die("Failed to initialize SDL");
g_video.hw.version_major = 4;
g_video.hw.version_minor = 5;
g_video.hw.context_type = RETRO_HW_CONTEXT_OPENGL_CORE;
g_video.hw.context_reset = noop;
g_video.hw.context_destroy = noop;
// Load the core.
core_load(argv[1]);
if (!g_retro.supports_no_game && argc < 3)
die("This core requires a game in order to run");
// Load the game.
core_load_game(argc > 2 ? argv[2] : NULL);
// Configure the player input devices.
g_retro.retro_set_controller_port_device(0, RETRO_DEVICE_JOYPAD);
SDL_Event ev;
while (running) {