Codechange: move all input-handling of video-drivers into InputLoop
[openttd-github.git] / src / video / sdl2_v.cpp
blobb02beacef35d632181a4dc27869a680e0485ab59
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD 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, version 2.
4 * OpenTTD 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.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /** @file sdl2_v.cpp Implementation of the SDL2 video driver. */
10 #include "../stdafx.h"
11 #include "../openttd.h"
12 #include "../gfx_func.h"
13 #include "../rev.h"
14 #include "../blitter/factory.hpp"
15 #include "../network/network.h"
16 #include "../thread.h"
17 #include "../progress.h"
18 #include "../core/random_func.hpp"
19 #include "../core/math_func.hpp"
20 #include "../core/mem_func.hpp"
21 #include "../core/geometry_func.hpp"
22 #include "../fileio_func.h"
23 #include "../framerate_type.h"
24 #include "../window_func.h"
25 #include "sdl2_v.h"
26 #include <SDL.h>
27 #include <mutex>
28 #include <condition_variable>
29 #ifdef __EMSCRIPTEN__
30 # include <emscripten.h>
31 # include <emscripten/html5.h>
32 #endif
34 #include "../safeguards.h"
36 static FVideoDriver_SDL iFVideoDriver_SDL;
38 static SDL_Window *_sdl_window;
39 static SDL_Surface *_sdl_surface;
40 static SDL_Surface *_sdl_rgb_surface;
41 static SDL_Surface *_sdl_real_surface;
43 /** Whether the drawing is/may be done in a separate thread. */
44 static bool _draw_threaded;
45 /** Mutex to keep the access to the shared memory controlled. */
46 static std::recursive_mutex *_draw_mutex = nullptr;
47 /** Signal to draw the next frame. */
48 static std::condition_variable_any *_draw_signal = nullptr;
49 /** Should we keep continue drawing? */
50 static volatile bool _draw_continue;
51 static Palette _local_palette;
52 static SDL_Palette *_sdl_palette;
54 #ifdef __EMSCRIPTEN__
55 /** Whether we just had a window-enter event. */
56 static bool _cursor_new_in_window = false;
57 #endif
59 static Rect _dirty_rect;
61 void VideoDriver_SDL::MakeDirty(int left, int top, int width, int height)
63 Rect r = {left, top, left + width, top + height};
64 _dirty_rect = BoundingRect(_dirty_rect, r);
67 static void UpdatePalette()
69 SDL_Color pal[256];
71 for (int i = 0; i != _local_palette.count_dirty; i++) {
72 pal[i].r = _local_palette.palette[_local_palette.first_dirty + i].r;
73 pal[i].g = _local_palette.palette[_local_palette.first_dirty + i].g;
74 pal[i].b = _local_palette.palette[_local_palette.first_dirty + i].b;
75 pal[i].a = 0;
78 SDL_SetPaletteColors(_sdl_palette, pal, _local_palette.first_dirty, _local_palette.count_dirty);
79 SDL_SetSurfacePalette(_sdl_surface, _sdl_palette);
82 static void MakePalette()
84 if (_sdl_palette == nullptr) {
85 _sdl_palette = SDL_AllocPalette(256);
86 if (_sdl_palette == nullptr) usererror("SDL2: Couldn't allocate palette: %s", SDL_GetError());
89 _cur_palette.first_dirty = 0;
90 _cur_palette.count_dirty = 256;
91 _local_palette = _cur_palette;
92 UpdatePalette();
94 if (_sdl_surface != _sdl_real_surface) {
95 /* When using a shadow surface, also set our palette on the real screen. This lets SDL
96 * allocate as many colors (or approximations) as
97 * possible, instead of using only the default SDL
98 * palette. This allows us to get more colors exactly
99 * right and might allow using better approximations for
100 * other colors.
102 * Note that colors allocations are tried in-order, so
103 * this favors colors further up into the palette. Also
104 * note that if two colors from the same animation
105 * sequence are approximated using the same color, that
106 * animation will stop working.
108 * Since changing the system palette causes the colours
109 * to change right away, and allocations might
110 * drastically change, we can't use this for animation,
111 * since that could cause weird coloring between the
112 * palette change and the blitting below, so we only set
113 * the real palette during initialisation.
115 SDL_SetSurfacePalette(_sdl_real_surface, _sdl_palette);
119 void VideoDriver_SDL::CheckPaletteAnim()
121 if (_cur_palette.count_dirty == 0) return;
123 _local_palette = _cur_palette;
124 this->MakeDirty(0, 0, _screen.width, _screen.height);
127 static void Paint()
129 PerformanceMeasurer framerate(PFE_VIDEO);
131 if (IsEmptyRect(_dirty_rect) && _cur_palette.count_dirty == 0) return;
133 if (_cur_palette.count_dirty != 0) {
134 Blitter *blitter = BlitterFactory::GetCurrentBlitter();
136 switch (blitter->UsePaletteAnimation()) {
137 case Blitter::PALETTE_ANIMATION_VIDEO_BACKEND:
138 UpdatePalette();
139 break;
141 case Blitter::PALETTE_ANIMATION_BLITTER:
142 blitter->PaletteAnimate(_local_palette);
143 break;
145 case Blitter::PALETTE_ANIMATION_NONE:
146 break;
148 default:
149 NOT_REACHED();
151 _cur_palette.count_dirty = 0;
154 SDL_Rect r = { _dirty_rect.left, _dirty_rect.top, _dirty_rect.right - _dirty_rect.left, _dirty_rect.bottom - _dirty_rect.top };
156 if (_sdl_surface != _sdl_real_surface) {
157 SDL_BlitSurface(_sdl_surface, &r, _sdl_real_surface, &r);
159 SDL_UpdateWindowSurfaceRects(_sdl_window, &r, 1);
161 MemSetT(&_dirty_rect, 0);
164 static void PaintThread()
166 /* First tell the main thread we're started */
167 std::unique_lock<std::recursive_mutex> lock(*_draw_mutex);
168 _draw_signal->notify_one();
170 /* Now wait for the first thing to draw! */
171 _draw_signal->wait(*_draw_mutex);
173 while (_draw_continue) {
174 /* Then just draw and wait till we stop */
175 Paint();
176 _draw_signal->wait(lock);
180 static const Dimension default_resolutions[] = {
181 { 640, 480 },
182 { 800, 600 },
183 { 1024, 768 },
184 { 1152, 864 },
185 { 1280, 800 },
186 { 1280, 960 },
187 { 1280, 1024 },
188 { 1400, 1050 },
189 { 1600, 1200 },
190 { 1680, 1050 },
191 { 1920, 1200 }
194 static void FindResolutions()
196 _resolutions.clear();
198 for (int i = 0; i < SDL_GetNumDisplayModes(0); i++) {
199 SDL_DisplayMode mode;
200 SDL_GetDisplayMode(0, i, &mode);
202 if (mode.w < 640 || mode.h < 480) continue;
203 if (std::find(_resolutions.begin(), _resolutions.end(), Dimension(mode.w, mode.h)) != _resolutions.end()) continue;
204 _resolutions.emplace_back(mode.w, mode.h);
207 /* We have found no resolutions, show the default list */
208 if (_resolutions.empty()) {
209 _resolutions.assign(std::begin(default_resolutions), std::end(default_resolutions));
212 SortResolutions();
215 static void GetAvailableVideoMode(uint *w, uint *h)
217 /* All modes available? */
218 if (!_fullscreen || _resolutions.empty()) return;
220 /* Is the wanted mode among the available modes? */
221 if (std::find(_resolutions.begin(), _resolutions.end(), Dimension(*w, *h)) != _resolutions.end()) return;
223 /* Use the closest possible resolution */
224 uint best = 0;
225 uint delta = Delta(_resolutions[0].width, *w) * Delta(_resolutions[0].height, *h);
226 for (uint i = 1; i != _resolutions.size(); ++i) {
227 uint newdelta = Delta(_resolutions[i].width, *w) * Delta(_resolutions[i].height, *h);
228 if (newdelta < delta) {
229 best = i;
230 delta = newdelta;
233 *w = _resolutions[best].width;
234 *h = _resolutions[best].height;
237 static uint FindStartupDisplay(uint startup_display)
239 int num_displays = SDL_GetNumVideoDisplays();
241 /* If the user indicated a valid monitor, use that. */
242 if (IsInsideBS(startup_display, 0, num_displays)) return startup_display;
244 /* Mouse position decides which display to use. */
245 int mx, my;
246 SDL_GetGlobalMouseState(&mx, &my);
247 for (int display = 0; display < num_displays; ++display) {
248 SDL_Rect r;
249 if (SDL_GetDisplayBounds(display, &r) == 0 && IsInsideBS(mx, r.x, r.w) && IsInsideBS(my, r.y, r.h)) {
250 DEBUG(driver, 1, "SDL2: Mouse is at (%d, %d), use display %d (%d, %d, %d, %d)", mx, my, display, r.x, r.y, r.w, r.h);
251 return display;
255 return 0;
258 bool VideoDriver_SDL::CreateMainWindow(uint w, uint h)
260 if (_sdl_window != nullptr) return true;
262 Uint32 flags = SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE;
264 if (_fullscreen) {
265 flags |= SDL_WINDOW_FULLSCREEN;
268 int x = SDL_WINDOWPOS_UNDEFINED, y = SDL_WINDOWPOS_UNDEFINED;
269 SDL_Rect r;
270 if (SDL_GetDisplayBounds(this->startup_display, &r) == 0) {
271 x = r.x + std::max(0, r.w - static_cast<int>(w)) / 2;
272 y = r.y + std::max(0, r.h - static_cast<int>(h)) / 4; // decent desktops have taskbars at the bottom
275 char caption[50];
276 seprintf(caption, lastof(caption), "OpenTTD %s", _openttd_revision);
277 _sdl_window = SDL_CreateWindow(
278 caption,
279 x, y,
280 w, h,
281 flags);
283 if (_sdl_window == nullptr) {
284 DEBUG(driver, 0, "SDL2: Couldn't allocate a window to draw on: %s", SDL_GetError());
285 return false;
288 std::string icon_path = FioFindFullPath(BASESET_DIR, "openttd.32.bmp");
289 if (!icon_path.empty()) {
290 /* Give the application an icon */
291 SDL_Surface *icon = SDL_LoadBMP(icon_path.c_str());
292 if (icon != nullptr) {
293 /* Get the colourkey, which will be magenta */
294 uint32 rgbmap = SDL_MapRGB(icon->format, 255, 0, 255);
296 SDL_SetColorKey(icon, SDL_TRUE, rgbmap);
297 SDL_SetWindowIcon(_sdl_window, icon);
298 SDL_FreeSurface(icon);
302 return true;
305 bool VideoDriver_SDL::CreateMainSurface(uint w, uint h, bool resize)
307 int bpp = BlitterFactory::GetCurrentBlitter()->GetScreenDepth();
309 GetAvailableVideoMode(&w, &h);
310 DEBUG(driver, 1, "SDL2: using mode %ux%ux%d", w, h, bpp);
312 if (!this->CreateMainWindow(w, h)) return false;
313 if (resize) SDL_SetWindowSize(_sdl_window, w, h);
315 _sdl_real_surface = SDL_GetWindowSurface(_sdl_window);
316 if (_sdl_real_surface == nullptr) {
317 DEBUG(driver, 0, "SDL2: Couldn't get window surface: %s", SDL_GetError());
318 return false;
321 /* Free any previously allocated rgb surface. */
322 if (_sdl_rgb_surface != nullptr) {
323 SDL_FreeSurface(_sdl_rgb_surface);
324 _sdl_rgb_surface = nullptr;
327 if (bpp == 8) {
328 _sdl_rgb_surface = SDL_CreateRGBSurface(0, w, h, 8, 0, 0, 0, 0);
330 if (_sdl_rgb_surface == nullptr) {
331 DEBUG(driver, 0, "SDL2: Couldn't allocate shadow surface: %s", SDL_GetError());
332 return false;
335 _sdl_surface = _sdl_rgb_surface;
336 } else {
337 _sdl_surface = _sdl_real_surface;
340 /* X11 doesn't appreciate it if we invalidate areas outside the window
341 * if shared memory is enabled (read: it crashes). So, as we might have
342 * gotten smaller, reset our dirty rects. GameSizeChanged() a bit lower
343 * will mark the whole screen dirty again anyway, but this time with the
344 * new dimensions. */
345 MemSetT(&_dirty_rect, 0);
347 _screen.width = _sdl_surface->w;
348 _screen.height = _sdl_surface->h;
349 _screen.pitch = _sdl_surface->pitch / (bpp / 8);
350 _screen.dst_ptr = _sdl_surface->pixels;
352 MakePalette();
354 /* When in full screen, we will always have the mouse cursor
355 * within the window, even though SDL does not give us the
356 * appropriate event to know this. */
357 if (_fullscreen) _cursor.in_window = true;
359 BlitterFactory::GetCurrentBlitter()->PostResize();
361 GameSizeChanged();
362 return true;
365 bool VideoDriver_SDL::ClaimMousePointer()
367 SDL_ShowCursor(0);
368 #ifdef __EMSCRIPTEN__
369 SDL_SetRelativeMouseMode(SDL_TRUE);
370 #endif
371 return true;
375 * This is called to indicate that an edit box has gained focus, text input mode should be enabled.
377 void VideoDriver_SDL::EditBoxGainedFocus()
379 if (!this->edit_box_focused) {
380 SDL_StartTextInput();
381 this->edit_box_focused = true;
386 * This is called to indicate that an edit box has lost focus, text input mode should be disabled.
388 void VideoDriver_SDL::EditBoxLostFocus()
390 if (this->edit_box_focused) {
391 SDL_StopTextInput();
392 this->edit_box_focused = false;
397 struct SDLVkMapping {
398 SDL_Keycode vk_from;
399 byte vk_count;
400 byte map_to;
401 bool unprintable;
404 #define AS(x, z) {x, 0, z, false}
405 #define AM(x, y, z, w) {x, (byte)(y - x), z, false}
406 #define AS_UP(x, z) {x, 0, z, true}
407 #define AM_UP(x, y, z, w) {x, (byte)(y - x), z, true}
409 static const SDLVkMapping _vk_mapping[] = {
410 /* Pageup stuff + up/down */
411 AS_UP(SDLK_PAGEUP, WKC_PAGEUP),
412 AS_UP(SDLK_PAGEDOWN, WKC_PAGEDOWN),
413 AS_UP(SDLK_UP, WKC_UP),
414 AS_UP(SDLK_DOWN, WKC_DOWN),
415 AS_UP(SDLK_LEFT, WKC_LEFT),
416 AS_UP(SDLK_RIGHT, WKC_RIGHT),
418 AS_UP(SDLK_HOME, WKC_HOME),
419 AS_UP(SDLK_END, WKC_END),
421 AS_UP(SDLK_INSERT, WKC_INSERT),
422 AS_UP(SDLK_DELETE, WKC_DELETE),
424 /* Map letters & digits */
425 AM(SDLK_a, SDLK_z, 'A', 'Z'),
426 AM(SDLK_0, SDLK_9, '0', '9'),
428 AS_UP(SDLK_ESCAPE, WKC_ESC),
429 AS_UP(SDLK_PAUSE, WKC_PAUSE),
430 AS_UP(SDLK_BACKSPACE, WKC_BACKSPACE),
432 AS(SDLK_SPACE, WKC_SPACE),
433 AS(SDLK_RETURN, WKC_RETURN),
434 AS(SDLK_TAB, WKC_TAB),
436 /* Function keys */
437 AM_UP(SDLK_F1, SDLK_F12, WKC_F1, WKC_F12),
439 /* Numeric part. */
440 AM(SDLK_KP_0, SDLK_KP_9, '0', '9'),
441 AS(SDLK_KP_DIVIDE, WKC_NUM_DIV),
442 AS(SDLK_KP_MULTIPLY, WKC_NUM_MUL),
443 AS(SDLK_KP_MINUS, WKC_NUM_MINUS),
444 AS(SDLK_KP_PLUS, WKC_NUM_PLUS),
445 AS(SDLK_KP_ENTER, WKC_NUM_ENTER),
446 AS(SDLK_KP_PERIOD, WKC_NUM_DECIMAL),
448 /* Other non-letter keys */
449 AS(SDLK_SLASH, WKC_SLASH),
450 AS(SDLK_SEMICOLON, WKC_SEMICOLON),
451 AS(SDLK_EQUALS, WKC_EQUALS),
452 AS(SDLK_LEFTBRACKET, WKC_L_BRACKET),
453 AS(SDLK_BACKSLASH, WKC_BACKSLASH),
454 AS(SDLK_RIGHTBRACKET, WKC_R_BRACKET),
456 AS(SDLK_QUOTE, WKC_SINGLEQUOTE),
457 AS(SDLK_COMMA, WKC_COMMA),
458 AS(SDLK_MINUS, WKC_MINUS),
459 AS(SDLK_PERIOD, WKC_PERIOD)
462 static uint ConvertSdlKeyIntoMy(SDL_Keysym *sym, WChar *character)
464 const SDLVkMapping *map;
465 uint key = 0;
466 bool unprintable = false;
468 for (map = _vk_mapping; map != endof(_vk_mapping); ++map) {
469 if ((uint)(sym->sym - map->vk_from) <= map->vk_count) {
470 key = sym->sym - map->vk_from + map->map_to;
471 unprintable = map->unprintable;
472 break;
476 /* check scancode for BACKQUOTE key, because we want the key left of "1", not anything else (on non-US keyboards) */
477 if (sym->scancode == SDL_SCANCODE_GRAVE) key = WKC_BACKQUOTE;
479 /* META are the command keys on mac */
480 if (sym->mod & KMOD_GUI) key |= WKC_META;
481 if (sym->mod & KMOD_SHIFT) key |= WKC_SHIFT;
482 if (sym->mod & KMOD_CTRL) key |= WKC_CTRL;
483 if (sym->mod & KMOD_ALT) key |= WKC_ALT;
485 /* The mod keys have no character. Prevent '?' */
486 if (sym->mod & KMOD_GUI ||
487 sym->mod & KMOD_CTRL ||
488 sym->mod & KMOD_ALT ||
489 unprintable) {
490 *character = WKC_NONE;
491 } else {
492 *character = sym->sym;
495 return key;
499 * Like ConvertSdlKeyIntoMy(), but takes an SDL_Keycode as input
500 * instead of an SDL_Keysym.
502 static uint ConvertSdlKeycodeIntoMy(SDL_Keycode kc)
504 const SDLVkMapping *map;
505 uint key = 0;
507 for (map = _vk_mapping; map != endof(_vk_mapping); ++map) {
508 if ((uint)(kc - map->vk_from) <= map->vk_count) {
509 key = kc - map->vk_from + map->map_to;
510 break;
514 /* check scancode for BACKQUOTE key, because we want the key left
515 * of "1", not anything else (on non-US keyboards) */
516 SDL_Scancode sc = SDL_GetScancodeFromKey(kc);
517 if (sc == SDL_SCANCODE_GRAVE) key = WKC_BACKQUOTE;
519 return key;
522 int VideoDriver_SDL::PollEvent()
524 SDL_Event ev;
526 if (!SDL_PollEvent(&ev)) return -2;
528 switch (ev.type) {
529 case SDL_MOUSEMOTION:
530 #ifdef __EMSCRIPTEN__
531 if (_cursor_new_in_window) {
532 /* The cursor just moved into the window; this means we don't
533 * know the absolutely position yet to move relative from.
534 * Before this time, SDL didn't know it either, and this is
535 * why we postpone it till now. Update the absolute position
536 * for this once, and work relative after. */
537 _cursor.pos.x = ev.motion.x;
538 _cursor.pos.y = ev.motion.y;
539 _cursor.dirty = true;
541 _cursor_new_in_window = false;
542 SDL_SetRelativeMouseMode(SDL_TRUE);
543 } else {
544 _cursor.UpdateCursorPositionRelative(ev.motion.xrel, ev.motion.yrel);
546 #else
547 if (_cursor.UpdateCursorPosition(ev.motion.x, ev.motion.y, true)) {
548 SDL_WarpMouseInWindow(_sdl_window, _cursor.pos.x, _cursor.pos.y);
550 #endif
551 HandleMouseEvents();
552 break;
554 case SDL_MOUSEWHEEL:
555 if (ev.wheel.y > 0) {
556 _cursor.wheel--;
557 } else if (ev.wheel.y < 0) {
558 _cursor.wheel++;
560 break;
562 case SDL_MOUSEBUTTONDOWN:
563 if (_rightclick_emulate && SDL_GetModState() & KMOD_CTRL) {
564 ev.button.button = SDL_BUTTON_RIGHT;
567 switch (ev.button.button) {
568 case SDL_BUTTON_LEFT:
569 _left_button_down = true;
570 break;
572 case SDL_BUTTON_RIGHT:
573 _right_button_down = true;
574 _right_button_clicked = true;
575 break;
577 default: break;
579 HandleMouseEvents();
580 break;
582 case SDL_MOUSEBUTTONUP:
583 if (_rightclick_emulate) {
584 _right_button_down = false;
585 _left_button_down = false;
586 _left_button_clicked = false;
587 } else if (ev.button.button == SDL_BUTTON_LEFT) {
588 _left_button_down = false;
589 _left_button_clicked = false;
590 } else if (ev.button.button == SDL_BUTTON_RIGHT) {
591 _right_button_down = false;
593 HandleMouseEvents();
594 break;
596 case SDL_QUIT:
597 HandleExitGameRequest();
598 break;
600 case SDL_KEYDOWN: // Toggle full-screen on ALT + ENTER/F
601 if ((ev.key.keysym.mod & (KMOD_ALT | KMOD_GUI)) &&
602 (ev.key.keysym.sym == SDLK_RETURN || ev.key.keysym.sym == SDLK_f)) {
603 if (ev.key.repeat == 0) ToggleFullScreen(!_fullscreen);
604 } else {
605 WChar character;
607 uint keycode = ConvertSdlKeyIntoMy(&ev.key.keysym, &character);
608 // Only handle non-text keys here. Text is handled in
609 // SDL_TEXTINPUT below.
610 if (!this->edit_box_focused ||
611 keycode == WKC_DELETE ||
612 keycode == WKC_NUM_ENTER ||
613 keycode == WKC_LEFT ||
614 keycode == WKC_RIGHT ||
615 keycode == WKC_UP ||
616 keycode == WKC_DOWN ||
617 keycode == WKC_HOME ||
618 keycode == WKC_END ||
619 keycode & WKC_META ||
620 keycode & WKC_CTRL ||
621 keycode & WKC_ALT ||
622 (keycode >= WKC_F1 && keycode <= WKC_F12) ||
623 !IsValidChar(character, CS_ALPHANUMERAL)) {
624 HandleKeypress(keycode, character);
627 break;
629 case SDL_TEXTINPUT: {
630 if (!this->edit_box_focused) break;
631 SDL_Keycode kc = SDL_GetKeyFromName(ev.text.text);
632 uint keycode = ConvertSdlKeycodeIntoMy(kc);
634 if (keycode == WKC_BACKQUOTE && FocusedWindowIsConsole()) {
635 WChar character;
636 Utf8Decode(&character, ev.text.text);
637 HandleKeypress(keycode, character);
638 } else {
639 HandleTextInput(ev.text.text);
641 break;
643 case SDL_WINDOWEVENT: {
644 if (ev.window.event == SDL_WINDOWEVENT_EXPOSED) {
645 // Force a redraw of the entire screen.
646 this->MakeDirty(0, 0, _screen.width, _screen.height);
647 } else if (ev.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) {
648 int w = std::max(ev.window.data1, 64);
649 int h = std::max(ev.window.data2, 64);
650 CreateMainSurface(w, h, w != ev.window.data1 || h != ev.window.data2);
651 } else if (ev.window.event == SDL_WINDOWEVENT_ENTER) {
652 // mouse entered the window, enable cursor
653 _cursor.in_window = true;
654 #ifdef __EMSCRIPTEN__
655 /* Disable relative mouse mode for the first mouse motion,
656 * so we can pick up the absolutely position again. */
657 _cursor_new_in_window = true;
658 SDL_SetRelativeMouseMode(SDL_FALSE);
659 #endif
660 } else if (ev.window.event == SDL_WINDOWEVENT_LEAVE) {
661 // mouse left the window, undraw cursor
662 UndrawMouseCursor();
663 _cursor.in_window = false;
665 break;
668 return -1;
671 const char *VideoDriver_SDL::Start(const StringList &parm)
673 if (BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 0) return "Only real blitters supported";
675 /* Explicitly disable hardware acceleration. Enabling this causes
676 * UpdateWindowSurface() to update the window's texture instead of
677 * its surface. */
678 SDL_SetHint(SDL_HINT_FRAMEBUFFER_ACCELERATION, "0");
679 SDL_SetHint(SDL_HINT_MOUSE_RELATIVE_MODE_WARP, "1");
681 /* Just on the offchance the audio subsystem started before the video system,
682 * check whether any part of SDL has been initialised before getting here.
683 * Slightly duplicated with sound/sdl_s.cpp */
684 int ret_code = 0;
685 if (SDL_WasInit(SDL_INIT_VIDEO) == 0) {
686 ret_code = SDL_InitSubSystem(SDL_INIT_VIDEO);
688 if (ret_code < 0) return SDL_GetError();
690 this->UpdateAutoResolution();
692 FindResolutions();
694 this->startup_display = FindStartupDisplay(GetDriverParamInt(parm, "display", -1));
696 if (!CreateMainSurface(_cur_resolution.width, _cur_resolution.height, false)) {
697 return SDL_GetError();
700 const char *dname = SDL_GetCurrentVideoDriver();
701 DEBUG(driver, 1, "SDL2: using driver '%s'", dname);
703 MarkWholeScreenDirty();
705 _draw_threaded = !GetDriverParamBool(parm, "no_threads") && !GetDriverParamBool(parm, "no_thread");
706 /* Wayland SDL video driver uses EGL to render the game. SDL created the
707 * EGL context from the main-thread, and with EGL you are not allowed to
708 * draw in another thread than the context was created. The function of
709 * _draw_threaded is to do exactly this: draw in another thread than the
710 * window was created, and as such, this fails on Wayland SDL video
711 * driver. So, we disable threading by default if Wayland SDL video
712 * driver is detected.
714 if (strcmp(dname, "wayland") == 0) {
715 _draw_threaded = false;
718 SDL_StopTextInput();
719 this->edit_box_focused = false;
721 return nullptr;
724 void VideoDriver_SDL::Stop()
726 SDL_QuitSubSystem(SDL_INIT_VIDEO);
727 if (SDL_WasInit(SDL_INIT_EVERYTHING) == 0) {
728 SDL_Quit(); // If there's nothing left, quit SDL
732 void VideoDriver_SDL::InputLoop()
734 uint32 mod = SDL_GetModState();
735 const Uint8 *keys = SDL_GetKeyboardState(NULL);
737 bool old_ctrl_pressed = _ctrl_pressed;
739 _ctrl_pressed = !!(mod & KMOD_CTRL);
740 _shift_pressed = !!(mod & KMOD_SHIFT);
742 #if defined(_DEBUG)
743 if (_shift_pressed)
744 #else
745 /* Speedup when pressing tab, except when using ALT+TAB
746 * to switch to another application. */
747 if (keys[SDL_SCANCODE_TAB] && (mod & KMOD_ALT) == 0)
748 #endif /* defined(_DEBUG) */
750 if (!_networking && _game_mode != GM_MENU) _fast_forward |= 2;
751 } else if (_fast_forward & 2) {
752 _fast_forward = 0;
755 /* Determine which directional keys are down. */
756 _dirkeys =
757 (keys[SDL_SCANCODE_LEFT] ? 1 : 0) |
758 (keys[SDL_SCANCODE_UP] ? 2 : 0) |
759 (keys[SDL_SCANCODE_RIGHT] ? 4 : 0) |
760 (keys[SDL_SCANCODE_DOWN] ? 8 : 0);
762 if (old_ctrl_pressed != _ctrl_pressed) HandleCtrlChanged();
765 void VideoDriver_SDL::LoopOnce()
767 InteractiveRandom(); // randomness
769 while (PollEvent() == -1) {}
770 if (_exit_game) {
771 #ifdef __EMSCRIPTEN__
772 /* Emscripten is event-driven, and as such the main loop is inside
773 * the browser. So if _exit_game goes true, the main loop ends (the
774 * cancel call), but we still have to call the cleanup that is
775 * normally done at the end of the main loop for non-Emscripten.
776 * After that, Emscripten just halts, and the HTML shows a nice
777 * "bye, see you next time" message. */
778 emscripten_cancel_main_loop();
779 MainLoopCleanup();
780 #endif
781 return;
784 cur_ticks = std::chrono::steady_clock::now();
786 /* If more than a millisecond has passed, increase the _realtime_tick. */
787 if (cur_ticks - last_realtime_tick > std::chrono::milliseconds(1)) {
788 auto delta = std::chrono::duration_cast<std::chrono::milliseconds>(cur_ticks - last_realtime_tick);
789 _realtime_tick += delta.count();
790 last_realtime_tick += delta;
793 if (cur_ticks >= next_game_tick || (_fast_forward && !_pause_mode)) {
794 if (_fast_forward && !_pause_mode) {
795 next_game_tick = cur_ticks + this->GetGameInterval();
796 } else {
797 next_game_tick += this->GetGameInterval();
798 /* Avoid next_game_tick getting behind more and more if it cannot keep up. */
799 if (next_game_tick < cur_ticks - ALLOWED_DRIFT * this->GetGameInterval()) next_game_tick = cur_ticks;
802 /* The gameloop is the part that can run asynchronously. The rest
803 * except sleeping can't. */
804 if (_draw_mutex != nullptr) draw_lock.unlock();
805 GameLoop();
806 if (_draw_mutex != nullptr) draw_lock.lock();
809 /* Prevent drawing when switching mode, as windows can be removed when they should still appear. */
810 if (cur_ticks >= next_draw_tick && (_switch_mode == SM_NONE || HasModalProgress())) {
811 next_draw_tick += this->GetDrawInterval();
812 /* Avoid next_draw_tick getting behind more and more if it cannot keep up. */
813 if (next_draw_tick < cur_ticks - ALLOWED_DRIFT * this->GetDrawInterval()) next_draw_tick = cur_ticks;
815 this->InputLoop();
816 ::InputLoop();
817 UpdateWindows();
818 this->CheckPaletteAnim();
820 if (_draw_mutex != nullptr && !HasModalProgress()) {
821 _draw_signal->notify_one();
822 } else {
823 Paint();
827 /* Emscripten is running an event-based mainloop; there is already some
828 * downtime between each iteration, so no need to sleep. */
829 #ifndef __EMSCRIPTEN__
830 /* If we are not in fast-forward, create some time between calls to ease up CPU usage. */
831 if (!_fast_forward || _pause_mode) {
832 /* See how much time there is till we have to process the next event, and try to hit that as close as possible. */
833 auto next_tick = std::min(next_draw_tick, next_game_tick);
834 auto now = std::chrono::steady_clock::now();
836 if (next_tick > now) {
837 if (_draw_mutex != nullptr) draw_lock.unlock();
838 std::this_thread::sleep_for(next_tick - now);
839 if (_draw_mutex != nullptr) draw_lock.lock();
842 #endif
845 void VideoDriver_SDL::MainLoop()
847 cur_ticks = std::chrono::steady_clock::now();
848 last_realtime_tick = cur_ticks;
849 next_game_tick = cur_ticks;
851 this->CheckPaletteAnim();
853 if (_draw_threaded) {
854 /* Initialise the mutex first, because that's the thing we *need*
855 * directly in the newly created thread. */
856 _draw_mutex = new std::recursive_mutex();
857 if (_draw_mutex == nullptr) {
858 _draw_threaded = false;
859 } else {
860 draw_lock = std::unique_lock<std::recursive_mutex>(*_draw_mutex);
861 _draw_signal = new std::condition_variable_any();
862 _draw_continue = true;
864 _draw_threaded = StartNewThread(&draw_thread, "ottd:draw-sdl", &PaintThread);
866 /* Free the mutex if we won't be able to use it. */
867 if (!_draw_threaded) {
868 draw_lock.unlock();
869 draw_lock.release();
870 delete _draw_mutex;
871 delete _draw_signal;
872 _draw_mutex = nullptr;
873 _draw_signal = nullptr;
874 } else {
875 /* Wait till the draw mutex has started itself. */
876 _draw_signal->wait(*_draw_mutex);
881 DEBUG(driver, 1, "SDL2: using %sthreads", _draw_threaded ? "" : "no ");
883 #ifdef __EMSCRIPTEN__
884 /* Run the main loop event-driven, based on RequestAnimationFrame. */
885 emscripten_set_main_loop_arg(&this->EmscriptenLoop, this, 0, 1);
886 #else
887 while (!_exit_game) {
888 LoopOnce();
891 MainLoopCleanup();
892 #endif
895 void VideoDriver_SDL::MainLoopCleanup()
897 if (_draw_mutex != nullptr) {
898 _draw_continue = false;
899 /* Sending signal if there is no thread blocked
900 * is very valid and results in noop */
901 _draw_signal->notify_one();
902 if (draw_lock.owns_lock()) draw_lock.unlock();
903 draw_lock.release();
904 draw_thread.join();
906 delete _draw_mutex;
907 delete _draw_signal;
909 _draw_mutex = nullptr;
910 _draw_signal = nullptr;
913 #ifdef __EMSCRIPTEN__
914 emscripten_exit_pointerlock();
915 /* In effect, the game ends here. As emscripten_set_main_loop() caused
916 * the stack to be unwound, the code after MainLoop() in
917 * openttd_main() is never executed. */
918 EM_ASM(if (window["openttd_syncfs"]) openttd_syncfs());
919 EM_ASM(if (window["openttd_exit"]) openttd_exit());
920 #endif
923 bool VideoDriver_SDL::ChangeResolution(int w, int h)
925 std::unique_lock<std::recursive_mutex> lock;
926 if (_draw_mutex != nullptr) lock = std::unique_lock<std::recursive_mutex>(*_draw_mutex);
928 return CreateMainSurface(w, h, true);
931 bool VideoDriver_SDL::ToggleFullscreen(bool fullscreen)
933 std::unique_lock<std::recursive_mutex> lock;
934 if (_draw_mutex != nullptr) lock = std::unique_lock<std::recursive_mutex>(*_draw_mutex);
936 int w, h;
938 /* Remember current window size */
939 if (fullscreen) {
940 SDL_GetWindowSize(_sdl_window, &w, &h);
942 /* Find fullscreen window size */
943 SDL_DisplayMode dm;
944 if (SDL_GetCurrentDisplayMode(0, &dm) < 0) {
945 DEBUG(driver, 0, "SDL_GetCurrentDisplayMode() failed: %s", SDL_GetError());
946 } else {
947 SDL_SetWindowSize(_sdl_window, dm.w, dm.h);
951 DEBUG(driver, 1, "SDL2: Setting %s", fullscreen ? "fullscreen" : "windowed");
952 int ret = SDL_SetWindowFullscreen(_sdl_window, fullscreen ? SDL_WINDOW_FULLSCREEN : 0);
953 if (ret == 0) {
954 /* Switching resolution succeeded, set fullscreen value of window. */
955 _fullscreen = fullscreen;
956 if (!fullscreen) SDL_SetWindowSize(_sdl_window, w, h);
957 } else {
958 DEBUG(driver, 0, "SDL_SetWindowFullscreen() failed: %s", SDL_GetError());
961 return ret == 0;
964 bool VideoDriver_SDL::AfterBlitterChange()
966 assert(BlitterFactory::GetCurrentBlitter()->GetScreenDepth() != 0);
967 int w, h;
968 SDL_GetWindowSize(_sdl_window, &w, &h);
969 return CreateMainSurface(w, h, false);
972 void VideoDriver_SDL::AcquireBlitterLock()
974 if (_draw_mutex != nullptr) _draw_mutex->lock();
977 void VideoDriver_SDL::ReleaseBlitterLock()
979 if (_draw_mutex != nullptr) _draw_mutex->unlock();
982 Dimension VideoDriver_SDL::GetScreenSize() const
984 SDL_DisplayMode mode;
985 if (SDL_GetCurrentDisplayMode(this->startup_display, &mode) != 0) return VideoDriver::GetScreenSize();
987 return { static_cast<uint>(mode.w), static_cast<uint>(mode.h) };