-
-
Notifications
You must be signed in to change notification settings - Fork 149
/
sdlmain.cpp
4811 lines (4144 loc) · 154 KB
/
sdlmain.cpp
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
/*
* SPDX-License-Identifier: GPL-2.0-or-later
*
* Copyright (C) 2020-2023 The DOSBox Staging Team
* Copyright (C) 2002-2021 The DOSBox Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "dosbox.h"
#include <array>
#include <cassert>
#include <cerrno>
#include <cmath>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sys/types.h>
#include <tuple>
#include <unistd.h>
#if C_DEBUG
#include <queue>
#endif
#ifdef WIN32
#include <process.h>
#include <signal.h>
#endif
#include <SDL.h>
#if C_OPENGL
#include <SDL_opengl.h>
#endif
#include "../capture/capture.h"
#include "../ints/int10.h"
#include "control.h"
#include "cpu.h"
#include "cross.h"
#include "debug.h"
#include "fs_utils.h"
#include "gui_msgs.h"
#include "joystick.h"
#include "keyboard.h"
#include "mapper.h"
#include "math_utils.h"
#include "mixer.h"
#include "mouse.h"
#include "pacer.h"
#include "pic.h"
#include "render.h"
#include "sdlmain.h"
#include "setup.h"
#include "string_utils.h"
#include "timer.h"
#include "tracy.h"
#include "vga.h"
#include "video.h"
#if C_OPENGL
//Define to report opengl errors
//#define DB_OPENGL_ERROR
#ifndef APIENTRY
#define APIENTRY
#endif
#ifndef APIENTRYP
#define APIENTRYP APIENTRY *
#endif
#ifndef GL_ARB_pixel_buffer_object
#define GL_ARB_pixel_buffer_object 1
#define GL_PIXEL_PACK_BUFFER_ARB 0x88EB
#define GL_PIXEL_UNPACK_BUFFER_ARB 0x88EC
#define GL_PIXEL_PACK_BUFFER_BINDING_ARB 0x88ED
#define GL_PIXEL_UNPACK_BUFFER_BINDING_ARB 0x88EF
#endif
#ifndef GL_ARB_vertex_buffer_object
#define GL_ARB_vertex_buffer_object 1
typedef void (APIENTRYP PFNGLGENBUFFERSARBPROC) (GLsizei n, GLuint *buffers);
typedef void (APIENTRYP PFNGLBINDBUFFERARBPROC) (GLenum target, GLuint buffer);
typedef void (APIENTRYP PFNGLDELETEBUFFERSARBPROC) (GLsizei n, const GLuint *buffers);
typedef void (APIENTRYP PFNGLBUFFERDATAARBPROC) (GLenum target, GLsizeiptr size, const GLvoid *data, GLenum usage);
typedef GLvoid* (APIENTRYP PFNGLMAPBUFFERARBPROC) (GLenum target, GLenum access);
typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERARBPROC) (GLenum target);
#endif
PFNGLGENBUFFERSARBPROC glGenBuffersARB = nullptr;
PFNGLBINDBUFFERARBPROC glBindBufferARB = nullptr;
PFNGLDELETEBUFFERSARBPROC glDeleteBuffersARB = nullptr;
PFNGLBUFFERDATAARBPROC glBufferDataARB = nullptr;
PFNGLMAPBUFFERARBPROC glMapBufferARB = nullptr;
PFNGLUNMAPBUFFERARBPROC glUnmapBufferARB = nullptr;
/* Don't guard these with GL_VERSION_2_0 - Apple defines it but not these typedefs.
* If they're already defined they should match these definitions, so no conflicts.
*/
typedef void (APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader);
typedef void (APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader);
typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC) (void);
typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC) (GLenum type);
typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC) (GLuint program);
typedef void (APIENTRYP PFNGLDELETESHADERPROC) (GLuint shader);
typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index);
typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar *name);
typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params);
typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
typedef void (APIENTRYP PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params);
typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name);
typedef void (APIENTRYP PFNGLLINKPROGRAMPROC) (GLuint program);
//Change to NP, as Khronos changes include guard :(
typedef void (APIENTRYP PFNGLSHADERSOURCEPROC_NP) (GLuint shader, GLsizei count, const GLchar **string, const GLint *length);
typedef void (APIENTRYP PFNGLUNIFORM2FPROC) (GLint location, GLfloat v0, GLfloat v1);
typedef void (APIENTRYP PFNGLUNIFORM1IPROC) (GLint location, GLint v0);
typedef void (APIENTRYP PFNGLUSEPROGRAMPROC) (GLuint program);
typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer);
/* Apple defines these functions in their GL header (as core functions)
* so we can't use their names as function pointers. We can't link
* directly as some platforms may not have them. So they get their own
* namespace here to keep the official names but avoid collisions.
*/
namespace gl2 {
PFNGLATTACHSHADERPROC glAttachShader = nullptr;
PFNGLCOMPILESHADERPROC glCompileShader = nullptr;
PFNGLCREATEPROGRAMPROC glCreateProgram = nullptr;
PFNGLCREATESHADERPROC glCreateShader = nullptr;
PFNGLDELETEPROGRAMPROC glDeleteProgram = nullptr;
PFNGLDELETESHADERPROC glDeleteShader = nullptr;
PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray = nullptr;
PFNGLGETATTRIBLOCATIONPROC glGetAttribLocation = nullptr;
PFNGLGETPROGRAMIVPROC glGetProgramiv = nullptr;
PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog = nullptr;
PFNGLGETSHADERIVPROC glGetShaderiv = nullptr;
PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog = nullptr;
PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation = nullptr;
PFNGLLINKPROGRAMPROC glLinkProgram = nullptr;
PFNGLSHADERSOURCEPROC_NP glShaderSource = nullptr;
PFNGLUNIFORM2FPROC glUniform2f = nullptr;
PFNGLUNIFORM1IPROC glUniform1i = nullptr;
PFNGLUSEPROGRAMPROC glUseProgram = nullptr;
PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer = nullptr;
}
/* "using" is meant to hide identical names declared in outer scope
* but is unreliable, so just redefine instead.
*/
#define glAttachShader gl2::glAttachShader
#define glCompileShader gl2::glCompileShader
#define glCreateProgram gl2::glCreateProgram
#define glCreateShader gl2::glCreateShader
#define glDeleteProgram gl2::glDeleteProgram
#define glDeleteShader gl2::glDeleteShader
#define glEnableVertexAttribArray gl2::glEnableVertexAttribArray
#define glGetAttribLocation gl2::glGetAttribLocation
#define glGetProgramiv gl2::glGetProgramiv
#define glGetProgramInfoLog gl2::glGetProgramInfoLog
#define glGetShaderiv gl2::glGetShaderiv
#define glGetShaderInfoLog gl2::glGetShaderInfoLog
#define glGetUniformLocation gl2::glGetUniformLocation
#define glLinkProgram gl2::glLinkProgram
#define glShaderSource gl2::glShaderSource
#define glUniform2f gl2::glUniform2f
#define glUniform1i gl2::glUniform1i
#define glUseProgram gl2::glUseProgram
#define glVertexAttribPointer gl2::glVertexAttribPointer
#endif // C_OPENGL
#ifdef WIN32
#include <winuser.h>
#define STDOUT_FILE "stdout.txt"
#define STDERR_FILE "stderr.txt"
#endif
#if defined(HAVE_SETPRIORITY)
#include <sys/resource.h>
#define PRIO_TOTAL (PRIO_MAX - PRIO_MIN)
#endif
SDL_Block sdl;
// Masks to be passed when creating SDL_Surface.
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
[[maybe_unused]] constexpr uint32_t RMASK = 0xff000000;
[[maybe_unused]] constexpr uint32_t GMASK = 0x00ff0000;
[[maybe_unused]] constexpr uint32_t BMASK = 0x0000ff00;
[[maybe_unused]] constexpr uint32_t AMASK = 0x000000ff;
#else
[[maybe_unused]] constexpr uint32_t RMASK = 0x000000ff;
[[maybe_unused]] constexpr uint32_t GMASK = 0x0000ff00;
[[maybe_unused]] constexpr uint32_t BMASK = 0x00ff0000;
[[maybe_unused]] constexpr uint32_t AMASK = 0xff000000;
#endif
// Size and ratio constants
// ------------------------
static SDL_Point FALLBACK_WINDOW_DIMENSIONS = {640, 480};
static bool first_window = true;
static SDL_Point restrict_to_viewport_resolution(int width, int height);
static SDL_Rect calc_viewport(const int width, const int height);
static void CleanupSDLResources();
static void HandleVideoResize(int width, int height);
static void update_frame_texture([[maybe_unused]] const uint16_t* changedLines);
static bool present_frame_texture();
#if C_OPENGL
static void update_frame_gl_pbo([[maybe_unused]] const uint16_t *changedLines);
static void update_frame_gl_fb(const uint16_t *changedLines);
static bool present_frame_gl();
#endif
static const char* vsync_state_as_string(const VsyncState state)
{
switch (state) {
case VsyncState::Unset: return "unset";
case VsyncState::Adaptive: return "adaptive";
case VsyncState::Off: return "off";
case VsyncState::On: return "on";
default: return "unknown";
}
}
#if C_DEBUG
extern SDL_Window *pdc_window;
extern std::queue<SDL_Event> pdc_event_queue;
static bool is_debugger_event(const SDL_Event &event)
{
switch (event.type) {
case SDL_KEYDOWN:
case SDL_KEYUP:
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
case SDL_MOUSEMOTION:
case SDL_MOUSEWHEEL:
case SDL_TEXTINPUT:
case SDL_TEXTEDITING:
case SDL_USEREVENT:
case SDL_WINDOWEVENT:
return event.window.windowID == SDL_GetWindowID(pdc_window);
}
return false;
}
SDL_Window *GFX_GetSDLWindow(void)
{
return sdl.window;
}
#endif
#if C_OPENGL
// SDL allows pixels sizes (colour-depth) from 1 to 4 bytes
constexpr uint8_t MAX_BYTES_PER_PIXEL = 4;
#ifdef DB_OPENGL_ERROR
void OPENGL_ERROR(const char* message) {
GLenum r = glGetError();
if (r == GL_NO_ERROR) return;
LOG_ERR("errors from %s",message);
do {
LOG_ERR("%X",r);
} while ( (r=glGetError()) != GL_NO_ERROR);
}
#else
void OPENGL_ERROR(const char*) {
return;
}
#endif
#endif
extern "C" void SDL_CDROMQuit(void);
static void QuitSDL()
{
if (sdl.initialized) {
SDL_CDROMQuit();
#if !C_DEBUG
SDL_Quit();
#endif
}
}
extern const char* RunningProgram;
extern bool CPU_CycleAutoAdjust;
//Globals for keyboard initialisation
bool startup_state_numlock=false;
bool startup_state_capslock=false;
void GFX_SetTitle(const int32_t new_num_cycles, const bool is_paused = false)
{
char title_buf[200] = {0};
#if !defined(NDEBUG)
#define APP_NAME_STR "DOSBox Staging (debug build)"
#else
#define APP_NAME_STR "DOSBox Staging"
#endif
auto &num_cycles = sdl.title_bar.num_cycles;
auto &cycles_ms_str = sdl.title_bar.cycles_ms_str;
auto &hint_mouse_str = sdl.title_bar.hint_mouse_str;
auto &hint_paused_str = sdl.title_bar.hint_paused_str;
if (new_num_cycles != -1)
num_cycles = new_num_cycles;
if (cycles_ms_str.empty()) {
cycles_ms_str = MSG_GetRaw("TITLEBAR_CYCLES_MS");
hint_paused_str = std::string(" ") + MSG_GetRaw("TITLEBAR_HINT_PAUSED");
}
if (CPU_CycleAutoAdjust)
safe_sprintf(title_buf, "%8s - max %d%% - " APP_NAME_STR "%s",
RunningProgram, num_cycles,
is_paused ? hint_paused_str.c_str() : hint_mouse_str.c_str());
else
safe_sprintf(title_buf, "%8s - %d %s - " APP_NAME_STR "%s",
RunningProgram, num_cycles, cycles_ms_str.c_str(),
is_paused ? hint_paused_str.c_str() : hint_mouse_str.c_str());
SDL_SetWindowTitle(sdl.window, title_buf);
}
void GFX_RefreshTitle()
{
constexpr int8_t refresh_cycle_count = -1;
GFX_SetTitle(refresh_cycle_count);
}
// Detects if we're running within a desktop environment (or window manager).
bool GFX_HaveDesktopEnvironment()
{
// On BSD and Linux, it's possible that the user is running directly on the
// console without a windowing environment. For example, SDL can directly
// interface with the host's OpenGL/GLES drivers, the console's frame buffer, or
// the Raspberry Pi's DISPMANX driver.
//
#if defined(BSD) || defined(LINUX)
// The presence of any of the following variables set by either the
// login manager, display manager, or window manager itself is
// sufficient evidence to say the user has a desktop session.
//
// References:
// https://www.freedesktop.org/software/systemd/man/pam_systemd.html#desktop=
// https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#recognized-keys
// https://askubuntu.com/questions/72549/how-to-determine-which-window-manager-and-desktop-environment-is-running
// https://unix.stackexchange.com/questions/116539/how-to-detect-the-desktop-environment-in-a-bash-script
//
constexpr const char* vars[] = {"XDG_CURRENT_DESKTOP",
"XDG_SESSION_DESKTOP",
"DESKTOP_SESSION",
"GDMSESSION"};
return std::any_of(std::begin(vars), std::end(vars), std::getenv);
#else
// Assume we have a desktop environment on all other systems
return true;
#endif
}
static double get_host_refresh_rate()
{
auto get_sdl_rate = []() {
SDL_DisplayMode mode = {};
auto &sdl_rate = mode.refresh_rate;
assert(sdl.window);
const auto display_in_use = SDL_GetWindowDisplayIndex(sdl.window);
if (display_in_use < 0) {
LOG_ERR("SDL: Could not get the current window index: %s",
SDL_GetError());
return RefreshRateHostDefault;
}
if (SDL_GetCurrentDisplayMode(display_in_use, &mode) != 0) {
LOG_ERR("SDL: Could not get the current display mode: %s",
SDL_GetError());
return RefreshRateHostDefault;
}
if (sdl_rate < RefreshRateMin) {
LOG_WARNING("SDL: Got a strange refresh rate of %d Hz",
sdl_rate);
return RefreshRateHostDefault;
}
assert(sdl_rate >= RefreshRateMin);
return sdl_rate;
};
auto get_vrr_rate = [](const int sdl_rate) {
constexpr auto vrr_backoff_hz = 3;
return sdl_rate - vrr_backoff_hz;
};
auto get_sdi_rate = [](const int sdl_rate) {
const auto is_odd = sdl_rate % 2 != 0;
const auto not_div_by_5 = sdl_rate % 5 != 0;
const auto next_is_div_by_3 = (sdl_rate + 1) % 3 == 0;
const bool should_adjust = is_odd && not_div_by_5 && next_is_div_by_3;
constexpr auto sdi_factor = 1.0 - 1.0 / 1000.0;
return should_adjust ? (sdl_rate + 1) * sdi_factor : sdl_rate;
};
// To be populated in the switch
auto rate = 0.0; // refresh rate as a floating point number
const char *rate_description = ""; // description of the refresh rate
switch (sdl.desktop.host_rate_mode) {
case HostRateMode::Auto:
if (const auto sdl_rate = get_sdl_rate();
sdl.desktop.fullscreen && sdl_rate >= InterpolatingVrrMinRateHz) {
rate = get_vrr_rate(sdl_rate);
rate_description = "VRR-adjusted (auto)";
} else {
rate = get_sdi_rate(sdl_rate);
rate_description = "standard SDI (auto)";
}
break;
case HostRateMode::Sdi:
rate = get_sdi_rate(get_sdl_rate());
rate_description = "standard SDI";
break;
case HostRateMode::Vrr:
rate = get_vrr_rate(get_sdl_rate());
rate_description = "VRR-adjusted";
break;
case HostRateMode::Custom:
assert(sdl.desktop.preferred_host_rate >= RefreshRateMin);
rate = sdl.desktop.preferred_host_rate;
rate_description = "custom";
break;
}
assert(rate >= RefreshRateMin);
// Log if changed
static auto last_int_rate = 0;
const auto int_rate = ifloor(rate);
if (last_int_rate != int_rate) {
last_int_rate = int_rate;
LOG_MSG("SDL: Using %s display refresh rate of %2.5g Hz",
rate_description, rate);
}
return rate;
}
// Reset and populate the vsync settings from the user's conf setting. This is
// called on-demand after startup and on output-mode changes (ie: switching from
// an SDL-based drawing context to an OpenGL-based context).
//
static void initialize_vsync_settings()
{
sdl.vsync = {};
const auto section = dynamic_cast<Section_prop*>(control->GetSection("sdl"));
const std::string user_pref = (section ? section->Get_string("vsync") : "auto");
if (has_true(user_pref)) {
sdl.vsync.when_windowed.requested = VsyncState::On;
sdl.vsync.when_fullscreen.requested = VsyncState::On;
} else if (has_false(user_pref)) {
sdl.vsync.when_windowed.requested = VsyncState::Off;
sdl.vsync.when_fullscreen.requested = VsyncState::Off;
} else if (user_pref == "yield") {
sdl.vsync.when_windowed.requested = VsyncState::Yield;
sdl.vsync.when_fullscreen.requested = VsyncState::Yield;
} else {
assert(user_pref == "auto");
// In 'vsync = auto' windowed-mode, we try to disable vsync for
// our Window because enabling vsync both at the program and
// compositor levels (which might be enforced) may add latency
// (i.e,: extra time blocked inside rendering or presentation
// calls), which stalls DOSBox.
//
sdl.vsync.when_windowed.requested = VsyncState::Off;
// In fullscreen-mode, the above still applies however we add
// handling for VRR displays that perform frame interpolation.
// as tehy need vsync enabled to lock onto the content:
const bool prefers_vsync_when_fullscreen =
(get_host_refresh_rate() >= InterpolatingVrrMinRateHz);
sdl.vsync.when_fullscreen.requested = prefers_vsync_when_fullscreen
? VsyncState::On
: VsyncState::Off;
// In 'vsync = auto', we also /assume/ vsync is enabled
// (regardless how the above requests actually played out) by
// overriding the measured state, as follows:
//
sdl.vsync.when_windowed.measured = VsyncState::On;
sdl.vsync.when_fullscreen.measured = VsyncState::On;
//
// A 60 Hz display can only show 60 complete frames per second.
// To achieve a higher frame rate, the host must drop or tear
// frames. This creates two layers of tearing when combined with
// DOS's (potentially) torn frames, which is common in games
// that don't use vblank. In "auto" mode, we aim for the best
// user experience, and dual-tearing isn't it. However, users
// can always set 'vsync = off'.
//
// There is no downside to making this assumption when the host
// display is faster than the DOS rate because all frames will
// be presented.
}
}
/* On macOS, as we use a nicer external icon packaged in App bundle.
*
* Visual Studio bundles .ico file specified in winres.rc into the
* dosbox.exe file.
*
* Other OSes will either use svg icon bundled in the native package, or
* the window uploaded via SDL_SetWindowIcon below.
*/
#if defined(MACOSX) || defined(_MSC_VER)
static void SetIcon() {}
#else
#include "icon.c"
static void SetIcon()
{
constexpr int src_w = icon_data.width;
constexpr int src_h = icon_data.height;
constexpr int src_bpp = icon_data.bytes_per_pixel;
static_assert(src_bpp == 4, "Source image expected in RGBA format.");
std::array<uint8_t, (src_w * src_h * src_bpp)> icon;
ICON_DATA_RUN_LENGTH_DECODE(icon.data(), icon_data.rle_pixel_data,
src_w * src_h, src_bpp);
SDL_Surface *s = SDL_CreateRGBSurfaceFrom(icon.data(), src_w, src_h,
src_bpp * 8, src_w * src_bpp,
RMASK, GMASK, BMASK, AMASK);
assert(s);
SDL_SetWindowIcon(sdl.window, s);
SDL_FreeSurface(s);
}
#endif
void GFX_RequestExit(const bool pressed)
{
shutdown_requested = pressed;
if (shutdown_requested) {
LOG_DEBUG("SDL: Exit requested");
}
}
[[maybe_unused]] static void PauseDOSBox(bool pressed)
{
if (!pressed)
return;
const auto inkeymod = static_cast<uint16_t>(SDL_GetModState());
GFX_RefreshTitle();
bool paused = true;
Delay(500);
SDL_Event event;
while (SDL_PollEvent(&event)) {
// flush event queue.
}
/* NOTE: This is one of the few places where we use SDL key codes
with SDL 2.0, rather than scan codes. Is that the correct behavior? */
while (paused && !shutdown_requested) {
SDL_WaitEvent(&event); // since we're not polling, cpu usage drops to 0.
switch (event.type) {
case SDL_QUIT: GFX_RequestExit(true); break;
case SDL_WINDOWEVENT:
if (event.window.event == SDL_WINDOWEVENT_RESTORED) {
// We may need to re-create a texture and more
GFX_ResetScreen();
}
break;
case SDL_KEYDOWN: // Must use Pause/Break Key to resume.
if (event.key.keysym.sym == SDLK_PAUSE) {
const uint16_t outkeymod = event.key.keysym.mod;
if (inkeymod != outkeymod) {
KEYBOARD_ClrBuffer();
MAPPER_LosingFocus();
//Not perfect if the pressed alt key is switched, but then we have to
//insert the keys into the mapper or create/rewrite the event and push it.
//Which is tricky due to possible use of scancodes.
}
paused = false;
GFX_RefreshTitle();
break;
}
#if defined (MACOSX)
if (event.key.keysym.sym == SDLK_q &&
(event.key.keysym.mod == KMOD_RGUI || event.key.keysym.mod == KMOD_LGUI)) {
/* On macs, all aps exit when pressing cmd-q */
GFX_RequestExit(true);
break;
}
#endif
}
}
}
uint8_t GFX_GetBestMode(const uint8_t flags)
{
return (flags & GFX_CAN_32) & ~(GFX_CAN_8 | GFX_CAN_15 | GFX_CAN_16);
}
// Let the presentation layer safely call no-op functions.
// Useful during output initialization or transitions.
void GFX_DisengageRendering()
{
sdl.frame.update = update_frame_noop;
sdl.frame.present = present_frame_noop;
}
/* Reset the screen with current values in the sdl structure */
void GFX_ResetScreen(void) {
GFX_Stop();
if (sdl.draw.callback)
(sdl.draw.callback)( GFX_CallBackReset );
GFX_Start();
CPU_Reset_AutoAdjust();
}
void GFX_ForceFullscreenExit()
{
sdl.desktop.fullscreen = false;
GFX_ResetScreen();
}
[[maybe_unused]] static int int_log2(int val)
{
int log = 0;
while ((val >>= 1) != 0)
log++;
return log;
}
// This is a hack to prevent SDL2 from re-creating window internally. Prevents
// crashes on Windows and Linux, and prevents initial window from being visibly
// destroyed (for window managers that show animations while creating window,
// e.g. Gnome 3).
static uint32_t opengl_driver_crash_workaround(const RenderingBackend rendering_backend)
{
if (rendering_backend != RenderingBackend::Texture) {
return 0;
}
if (starts_with(sdl.render_driver, "opengl")) {
return SDL_WINDOW_OPENGL;
}
if (sdl.render_driver != "auto")
return 0;
static int default_driver_is_opengl = -1;
if (default_driver_is_opengl >= 0)
return (default_driver_is_opengl ? SDL_WINDOW_OPENGL : 0);
// According to SDL2 documentation, the first driver
// in the list is the default one.
int i = 0;
SDL_RendererInfo info;
while (SDL_GetRenderDriverInfo(i++, &info) == 0) {
if (info.flags & SDL_RENDERER_TARGETTEXTURE)
break;
}
default_driver_is_opengl = starts_with(info.name, "opengl");
return (default_driver_is_opengl ? SDL_WINDOW_OPENGL : 0);
}
static SDL_Rect get_canvas_size(const RenderingBackend rendering_backend);
// Logs the source and target resolution including describing scaling method
// and pixel aspect ratio. Note that this function deliberately doesn't use
// any global structs to disentangle it from the existing sdl-main design.
static void log_display_properties(const int width, const int height,
const VideoMode& video_mode,
const std::optional<SDL_Rect>& viewport_size_override,
const RenderingBackend rendering_backend)
{
// Get the viewport dimensions, with consideration for possible override
// values
auto get_viewport_size = [&]() -> std::pair<int, int> {
if (viewport_size_override) {
const auto vp = calc_viewport(viewport_size_override->w,
viewport_size_override->h);
return {vp.w, vp.h};
}
const auto canvas = get_canvas_size(rendering_backend);
const auto viewport = calc_viewport(canvas.w, canvas.h);
return {viewport.w, viewport.h};
};
const auto [viewport_w, viewport_h] = get_viewport_size();
// Check expectations
assert(width > 0 && height > 0);
assert(viewport_w > 0 && viewport_h > 0);
const auto scale_x = static_cast<double>(viewport_w) / width;
const auto scale_y = static_cast<double>(viewport_h) / height;
[[maybe_unused]] const auto one_per_render_pixel_aspect = scale_y / scale_x;
const auto video_mode_desc = to_string(video_mode);
const char* frame_mode = nullptr;
switch (sdl.frame.mode) {
case FrameMode::Cfr: frame_mode = "CFR"; break;
case FrameMode::Vfr: frame_mode = "VFR"; break;
case FrameMode::ThrottledVfr: frame_mode = "throttled VFR"; break;
case FrameMode::Unset: frame_mode = "Unset frame mode"; break;
default: assertm(false, "Invalid FrameMode");
}
const auto refresh_rate = VGA_GetPreferredRate();
LOG_MSG("DISPLAY: %s at %2.5g Hz %s, "
"scaled to %dx%d with 1:%1.6g (%d:%d) pixel aspect ratio",
video_mode_desc.c_str(),
refresh_rate,
frame_mode,
viewport_w,
viewport_h,
video_mode.pixel_aspect_ratio.Inverse().ToDouble(),
static_cast<int32_t>(video_mode.pixel_aspect_ratio.Num()),
static_cast<int32_t>(video_mode.pixel_aspect_ratio.Denom()));
#if 0
LOG_MSG("DISPLAY: render width: %d, render height: %d, "
"render pixel aspect ratio: 1:%1.3g",
width,
height,
one_per_render_pixel_aspect);
#endif
}
static SDL_Point get_initial_window_position_or_default(int default_val)
{
int x, y;
if (sdl.desktop.window.initial_x_pos >= 0 &&
sdl.desktop.window.initial_y_pos >= 0) {
x = sdl.desktop.window.initial_x_pos;
y = sdl.desktop.window.initial_y_pos;
} else {
x = y = default_val;
}
return {x, y};
}
// A safer way to call SDL_SetWindowSize because it ensures the event-callback
// is disabled during the resize event. This prevents the event callback from
// firing before the window is resized in which case an endless loop can occur
static void safe_set_window_size(const int w, const int h)
{
decltype(sdl.draw.callback) saved_callback = nullptr;
// Swap and save the callback with a a no-op
std::swap(sdl.draw.callback, saved_callback);
assert(sdl.window);
SDL_SetWindowSize(sdl.window, w, h);
// Swap the saved callback back in
std::swap(sdl.draw.callback, saved_callback);
}
static VsyncSettings& get_vsync_settings()
{
if (sdl.vsync.when_fullscreen.requested == VsyncState::Unset ||
sdl.vsync.when_windowed.requested == VsyncState::Unset) {
initialize_vsync_settings();
}
return sdl.desktop.fullscreen ? sdl.vsync.when_fullscreen
: sdl.vsync.when_windowed;
}
// Benchmarks are run in each vsync'd mode as part of the vsync detection
// process. This routine returns the vsync mode's current benchmark rate
// if available.
static std::optional<int> get_benchmarked_vsync_rate()
{
const auto bench_rate = get_vsync_settings().benchmarked_rate;
return (bench_rate != 0 ? std::optional<int>(bench_rate) : std::nullopt);
}
static void set_vfr_dupe_countdown_from_rate(const double dos_rate_hz)
{
constexpr auto max_dupe_rate_hz = 10.0;
assert(dos_rate_hz >= max_dupe_rate_hz);
assert(dos_rate_hz <= RefreshRateMax);
const auto dos_to_dupe_frames = iround(dos_rate_hz / max_dupe_rate_hz);
sdl.frame.vfr_dupe_countdown = check_cast<int8_t>(dos_to_dupe_frames);
#if 0
LOG_MSG("SDL: Setting VFR duplicate countdown to %d "
"from a DOS rate of %.1f Hz ", dos_to_dupe_frames, dos_rate_hz);
#endif
}
static void save_rate_to_frame_period(const double rate_hz)
{
assert(rate_hz > 0);
// backoff by one-onethousandth to avoid hitting the vsync edge
sdl.frame.period_ms = 1'001.0 / rate_hz;
const auto period_us = sdl.frame.period_ms * 1'000;
sdl.frame.period_us = ifloor(period_us);
// Permit the frame period to be off by up to 90% before "out of sync"
sdl.frame.period_us_early = ifloor(55 * period_us / 100);
sdl.frame.period_us_late = ifloor(145 * period_us / 100);
}
static std::unique_ptr<Pacer> render_pacer = {};
static int benchmark_presentation_rate()
{
// If the presentation function is empty, then we can't benchmark
assert(sdl.frame.present != present_frame_noop ||
sdl.frame.update != update_frame_noop);
// Number of frames to benchmark
const auto ten_percent_of_fps = get_host_refresh_rate() / 10;
const auto warmup_frames = ten_percent_of_fps;
const auto bench_frames = ten_percent_of_fps;
// Disable the pacer because we need every frame presented and measured
// so we can hit the vsync wall (if it exists).
render_pacer->SetTimeout(0);
// Warmup round
for (auto i = 0; i < warmup_frames; ++i) {
sdl.frame.update(nullptr);
sdl.frame.present();
}
// Measured round
const auto start_us = GetTicksUs();
for (auto frame = 0; frame < bench_frames; ++frame) {
sdl.frame.update(nullptr);
sdl.frame.present();
}
const auto elapsed_us = std::max(static_cast<int64_t>(1L), GetTicksUsSince(start_us));
return iround(static_cast<int>((bench_frames * 1'000'000) / elapsed_us));
}
static int nearest_common_rate(const double rate)
{
constexpr int common_rates[] = {
24, 30, 50, 60, 70, 71, 72, 75, 80, 85, 90, 100, 120, 144, 165, 240};
int nearest_rate = 0;
int min_difference = INT_MAX;
// Find the nearest refresh rate
for (int common_rate : common_rates) {
int difference = std::abs(iround(rate) - common_rate);
if (difference <= min_difference) {
min_difference = difference;
nearest_rate = common_rate;
continue;
}
break;
}
assert(nearest_rate != 0);
return nearest_rate;
}
static VsyncState measure_vsync_state(int& bench_rate)
{
bench_rate = benchmark_presentation_rate();
const auto host_rate = get_host_refresh_rate();
// Notify the user if the machine is prensetation-starved.
if (bench_rate < host_rate * 0.8) {
LOG_WARNING("SDL: We can only render %d FPS, which is well below"
" the host's reported refresh rate of %2.5g Hz.",
bench_rate,
host_rate);
LOG_WARNING(
"SDL: You will experience rendering lag and stuttering."
" Consider updating your video drivers and try disabling"
" vsync in your host and drivers, set [sdl] vsync = false");
}
if (bench_rate < host_rate * 1.5)
return VsyncState::On;
else if (bench_rate < host_rate * 2.5)
return VsyncState::Adaptive;
else
return VsyncState::Off;
}
static void set_vsync(const VsyncState state)
{
if (state == VsyncState::Yield) {
return;
}
#if C_OPENGL
if (sdl.rendering_backend == RenderingBackend::OpenGl) {
assert(sdl.opengl.context);
const auto interval = static_cast<int>(state);
// -1=adaptive, 0=off, 1=on
assert(interval >= -1 && interval <= 1);
if (SDL_GL_SetSwapInterval(interval) == 0)
return;
// the requested interval is not supported
LOG_WARNING("SDL: Failed setting the OpenGL vsync state to %s (%d): %s",
vsync_state_as_string(state), interval, SDL_GetError());
// Per SDL's recommendation: If an application requests adaptive
// vsync and the system does not support it, this function will
// fail and return -1. In such a case, you should probably retry
// the call with 1 for the interval.
if (interval == -1 && SDL_GL_SetSwapInterval(1) != 0) {
LOG_WARNING("SDL: Tried enabling non-adaptive OpenGL vsync, but it still failed: %s",
SDL_GetError());
}
return;
}
#endif
assert(sdl.rendering_backend == RenderingBackend::Texture);
// https://wiki.libsdl.org/SDL_HINT_RENDER_VSYNC - can only be
// set to "1", "0", adapative is currently not supported, so we
// also treat it as "1"
const auto hint_str = (state == VsyncState::On ||
state == VsyncState::Adaptive)
? "1"
: "0";
if (SDL_SetHint(SDL_HINT_RENDER_VSYNC, hint_str) == SDL_TRUE)
return;
LOG_WARNING("SDL: Failed setting SDL's vsync state to to %s (%s): %s",
vsync_state_as_string(state), hint_str, SDL_GetError());
}
static void update_vsync_state()
{
// Hosts can have different vsync constraints between window modes
auto& vsync_pref = get_vsync_settings();
// Short-hand aliases
auto &requested = vsync_pref.requested;
auto& measured = vsync_pref.measured;
assert(requested != VsyncState::Unset);
// Do we still need to measure the vsync state?
if (measured == VsyncState::Unset) {
set_vsync(requested);
measured = measure_vsync_state(vsync_pref.benchmarked_rate);
}
}
static void remove_window()
{
if (sdl.window) {
SDL_DestroyWindow(sdl.window);
sdl.window = nullptr;
}
}
// The throttled presenter skips frames that have inter-frame spacing narrower
// than the allowed frame period (sdl.frame.period_us). When a frame is skipped,
// the presenter still tries to present it at its next oppourtunity.
//
static void maybe_present_throttled(const bool frame_is_new)
{
static int64_t last_present_time = 0;
static auto was_new_and_throttled = false;
const auto now = GetTicksUs();
const auto elapsed = now - last_present_time;
if (elapsed >= sdl.frame.period_us) {
// If we waited beyond this frame's refresh period, then credit
// this extra wait back by deducting it from the recorded time.
const auto wait_overage = elapsed % sdl.frame.period_us;
last_present_time = now - (9 * wait_overage / 10);