OpenTTD Source  1.10.3
sdl2_v.cpp
Go to the documentation of this file.
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  */
7 
10 #ifdef WITH_SDL2
11 
12 #include "../stdafx.h"
13 #include "../openttd.h"
14 #include "../gfx_func.h"
15 #include "../rev.h"
16 #include "../blitter/factory.hpp"
17 #include "../network/network.h"
18 #include "../thread.h"
19 #include "../progress.h"
20 #include "../core/random_func.hpp"
21 #include "../core/math_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 #include <algorithm>
30 
31 #include "../safeguards.h"
32 
33 static FVideoDriver_SDL iFVideoDriver_SDL;
34 
35 static SDL_Window *_sdl_window;
36 static SDL_Surface *_sdl_surface;
37 static SDL_Surface *_sdl_realscreen;
38 
40 static bool _draw_threaded;
42 static std::recursive_mutex *_draw_mutex = nullptr;
44 static std::condition_variable_any *_draw_signal = nullptr;
46 static volatile bool _draw_continue;
47 static Palette _local_palette;
48 static SDL_Palette *_sdl_palette;
49 
50 #define MAX_DIRTY_RECTS 100
51 static SDL_Rect _dirty_rects[MAX_DIRTY_RECTS];
52 static int _num_dirty_rects;
53 
54 /* Size of window */
55 static int _window_size_w;
56 static int _window_size_h;
57 
58 void VideoDriver_SDL::MakeDirty(int left, int top, int width, int height)
59 {
60  if (_num_dirty_rects < MAX_DIRTY_RECTS) {
61  _dirty_rects[_num_dirty_rects].x = left;
62  _dirty_rects[_num_dirty_rects].y = top;
63  _dirty_rects[_num_dirty_rects].w = width;
64  _dirty_rects[_num_dirty_rects].h = height;
65  }
66  _num_dirty_rects++;
67 }
68 
69 static void UpdatePalette(bool init = false)
70 {
71  SDL_Color pal[256];
72 
73  for (int i = 0; i != _local_palette.count_dirty; i++) {
74  pal[i].r = _local_palette.palette[_local_palette.first_dirty + i].r;
75  pal[i].g = _local_palette.palette[_local_palette.first_dirty + i].g;
76  pal[i].b = _local_palette.palette[_local_palette.first_dirty + i].b;
77  pal[i].a = 0;
78  }
79 
80  SDL_SetPaletteColors(_sdl_palette, pal, _local_palette.first_dirty, _local_palette.count_dirty);
81  SDL_SetSurfacePalette(_sdl_surface, _sdl_palette);
82 
83  if (_sdl_surface != _sdl_realscreen && init) {
84  /* When using a shadow surface, also set our palette on the real screen. This lets SDL
85  * allocate as many colors (or approximations) as
86  * possible, instead of using only the default SDL
87  * palette. This allows us to get more colors exactly
88  * right and might allow using better approximations for
89  * other colors.
90  *
91  * Note that colors allocations are tried in-order, so
92  * this favors colors further up into the palette. Also
93  * note that if two colors from the same animation
94  * sequence are approximated using the same color, that
95  * animation will stop working.
96  *
97  * Since changing the system palette causes the colours
98  * to change right away, and allocations might
99  * drastically change, we can't use this for animation,
100  * since that could cause weird coloring between the
101  * palette change and the blitting below, so we only set
102  * the real palette during initialisation.
103  */
104  SDL_SetSurfacePalette(_sdl_realscreen, _sdl_palette);
105  }
106 
107  if (_sdl_surface != _sdl_realscreen && !init) {
108  /* We're not using real hardware palette, but are letting SDL
109  * approximate the palette during shadow -> screen copy. To
110  * change the palette, we need to recopy the entire screen.
111  *
112  * Note that this operation can slow down the rendering
113  * considerably, especially since changing the shadow
114  * palette will need the next blit to re-detect the
115  * best mapping of shadow palette colors to real palette
116  * colors from scratch.
117  */
118  SDL_BlitSurface(_sdl_surface, nullptr, _sdl_realscreen, nullptr);
119  SDL_UpdateWindowSurface(_sdl_window);
120  }
121 }
122 
123 static void InitPalette()
124 {
125  _local_palette = _cur_palette;
126  _local_palette.first_dirty = 0;
127  _local_palette.count_dirty = 256;
128  UpdatePalette(true);
129 }
130 
131 static void CheckPaletteAnim()
132 {
133  if (_cur_palette.count_dirty != 0) {
135 
136  switch (blitter->UsePaletteAnimation()) {
138  UpdatePalette();
139  break;
140 
142  blitter->PaletteAnimate(_local_palette);
143  break;
144 
146  break;
147 
148  default:
149  NOT_REACHED();
150  }
152  }
153 }
154 
155 static void DrawSurfaceToScreen()
156 {
157  PerformanceMeasurer framerate(PFE_VIDEO);
158 
159  int n = _num_dirty_rects;
160  if (n == 0) return;
161 
162  _num_dirty_rects = 0;
163 
164  if (n > MAX_DIRTY_RECTS) {
165  if (_sdl_surface != _sdl_realscreen) {
166  SDL_BlitSurface(_sdl_surface, nullptr, _sdl_realscreen, nullptr);
167  }
168 
169  SDL_UpdateWindowSurface(_sdl_window);
170  } else {
171  if (_sdl_surface != _sdl_realscreen) {
172  for (int i = 0; i < n; i++) {
173  SDL_BlitSurface(
174  _sdl_surface, &_dirty_rects[i],
175  _sdl_realscreen, &_dirty_rects[i]);
176  }
177  }
178 
179  SDL_UpdateWindowSurfaceRects(_sdl_window, _dirty_rects, n);
180  }
181 }
182 
183 static void DrawSurfaceToScreenThread()
184 {
185  /* First tell the main thread we're started */
186  std::unique_lock<std::recursive_mutex> lock(*_draw_mutex);
187  _draw_signal->notify_one();
188 
189  /* Now wait for the first thing to draw! */
190  _draw_signal->wait(*_draw_mutex);
191 
192  while (_draw_continue) {
193  CheckPaletteAnim();
194  /* Then just draw and wait till we stop */
195  DrawSurfaceToScreen();
196  _draw_signal->wait(lock);
197  }
198 }
199 
200 static void GetVideoModes()
201 {
202  int modes = SDL_GetNumDisplayModes(0);
203  if (modes == 0) usererror("sdl: no modes available");
204 
205  _resolutions.clear();
206 
207  SDL_DisplayMode mode;
208  for (int i = 0; i < modes; i++) {
209  SDL_GetDisplayMode(0, i, &mode);
210 
211  uint w = mode.w;
212  uint h = mode.h;
213 
214  if (w < 640 || h < 480) continue; // reject too small resolutions
215 
216  if (std::find(_resolutions.begin(), _resolutions.end(), Dimension(w, h)) != _resolutions.end()) continue;
217  _resolutions.emplace_back(w, h);
218  }
219  if (_resolutions.empty()) usererror("No usable screen resolutions found!\n");
220  SortResolutions();
221 }
222 
223 static void GetAvailableVideoMode(uint *w, uint *h)
224 {
225  /* All modes available? */
226  if (!_fullscreen || _resolutions.empty()) return;
227 
228  /* Is the wanted mode among the available modes? */
229  if (std::find(_resolutions.begin(), _resolutions.end(), Dimension(*w, *h)) != _resolutions.end()) return;
230 
231  /* Use the closest possible resolution */
232  uint best = 0;
233  uint delta = Delta(_resolutions[0].width, *w) * Delta(_resolutions[0].height, *h);
234  for (uint i = 1; i != _resolutions.size(); ++i) {
235  uint newdelta = Delta(_resolutions[i].width, *w) * Delta(_resolutions[i].height, *h);
236  if (newdelta < delta) {
237  best = i;
238  delta = newdelta;
239  }
240  }
241  *w = _resolutions[best].width;
242  *h = _resolutions[best].height;
243 }
244 
245 bool VideoDriver_SDL::CreateMainSurface(uint w, uint h, bool resize)
246 {
247  SDL_Surface *newscreen;
248  char caption[50];
250 
251  GetAvailableVideoMode(&w, &h);
252 
253  DEBUG(driver, 1, "SDL2: using mode %ux%ux%d", w, h, bpp);
254 
255  if (bpp == 0) usererror("Can't use a blitter that blits 0 bpp for normal visuals");
256 
257  /* Free any previously allocated shadow surface */
258  if (_sdl_surface != nullptr && _sdl_surface != _sdl_realscreen) SDL_FreeSurface(_sdl_surface);
259 
260  seprintf(caption, lastof(caption), "OpenTTD %s", _openttd_revision);
261 
262  if (_sdl_window == nullptr) {
263  Uint32 flags = SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE;
264 
265  if (_fullscreen) {
266  flags |= SDL_WINDOW_FULLSCREEN;
267  }
268 
269  _sdl_window = SDL_CreateWindow(
270  caption,
271  SDL_WINDOWPOS_UNDEFINED,
272  SDL_WINDOWPOS_UNDEFINED,
273  w, h,
274  flags);
275 
276  if (_sdl_window == nullptr) {
277  DEBUG(driver, 0, "SDL2: Couldn't allocate a window to draw on");
278  return false;
279  }
280 
281  char icon_path[MAX_PATH];
282  if (FioFindFullPath(icon_path, lastof(icon_path), BASESET_DIR, "openttd.32.bmp") != nullptr) {
283  /* Give the application an icon */
284  SDL_Surface *icon = SDL_LoadBMP(icon_path);
285  if (icon != nullptr) {
286  /* Get the colourkey, which will be magenta */
287  uint32 rgbmap = SDL_MapRGB(icon->format, 255, 0, 255);
288 
289  SDL_SetColorKey(icon, SDL_TRUE, rgbmap);
290  SDL_SetWindowIcon(_sdl_window, icon);
291  SDL_FreeSurface(icon);
292  }
293  }
294  }
295 
296  if (resize) SDL_SetWindowSize(_sdl_window, w, h);
297 
298  newscreen = SDL_GetWindowSurface(_sdl_window);
299  if (newscreen == NULL) {
300  DEBUG(driver, 0, "SDL2: Couldn't get window surface: %s", SDL_GetError());
301  return false;
302  }
303 
304  _sdl_realscreen = newscreen;
305 
306  if (bpp == 8) {
307  newscreen = SDL_CreateRGBSurface(0, w, h, 8, 0, 0, 0, 0);
308 
309  if (newscreen == nullptr) {
310  DEBUG(driver, 0, "SDL2: Couldn't allocate shadow surface: %s", SDL_GetError());
311  return false;
312  }
313  }
314 
315  if (_sdl_palette == nullptr) {
316  _sdl_palette = SDL_AllocPalette(256);
317  }
318 
319  if (_sdl_palette == nullptr) {
320  DEBUG(driver, 0, "SDL_AllocPalette() failed: %s", SDL_GetError());
321  return false;
322  }
323 
324  /* Delay drawing for this cycle; the next cycle will redraw the whole screen */
325  _num_dirty_rects = 0;
326 
327  _screen.width = newscreen->w;
328  _screen.height = newscreen->h;
329  _screen.pitch = newscreen->pitch / (bpp / 8);
330  _screen.dst_ptr = newscreen->pixels;
331  _sdl_surface = newscreen;
332 
333  /* When in full screen, we will always have the mouse cursor
334  * within the window, even though SDL does not give us the
335  * appropriate event to know this. */
336  if (_fullscreen) _cursor.in_window = true;
337 
339  blitter->PostResize();
340 
341  InitPalette();
342 
343  GameSizeChanged();
344 
345  return true;
346 }
347 
348 bool VideoDriver_SDL::ClaimMousePointer()
349 {
350  SDL_ShowCursor(0);
351  return true;
352 }
353 
358 {
359  if (!this->edit_box_focused) {
360  SDL_StartTextInput();
361  this->edit_box_focused = true;
362  }
363 }
364 
369 {
370  if (this->edit_box_focused) {
371  SDL_StopTextInput();
372  this->edit_box_focused = false;
373  }
374 }
375 
376 
377 struct VkMapping {
378  SDL_Keycode vk_from;
379  byte vk_count;
380  byte map_to;
381  bool unprintable;
382 };
383 
384 #define AS(x, z) {x, 0, z, false}
385 #define AM(x, y, z, w) {x, (byte)(y - x), z, false}
386 #define AS_UP(x, z) {x, 0, z, true}
387 #define AM_UP(x, y, z, w) {x, (byte)(y - x), z, true}
388 
389 static const VkMapping _vk_mapping[] = {
390  /* Pageup stuff + up/down */
391  AS_UP(SDLK_PAGEUP, WKC_PAGEUP),
392  AS_UP(SDLK_PAGEDOWN, WKC_PAGEDOWN),
393  AS_UP(SDLK_UP, WKC_UP),
394  AS_UP(SDLK_DOWN, WKC_DOWN),
395  AS_UP(SDLK_LEFT, WKC_LEFT),
396  AS_UP(SDLK_RIGHT, WKC_RIGHT),
397 
398  AS_UP(SDLK_HOME, WKC_HOME),
399  AS_UP(SDLK_END, WKC_END),
400 
401  AS_UP(SDLK_INSERT, WKC_INSERT),
402  AS_UP(SDLK_DELETE, WKC_DELETE),
403 
404  /* Map letters & digits */
405  AM(SDLK_a, SDLK_z, 'A', 'Z'),
406  AM(SDLK_0, SDLK_9, '0', '9'),
407 
408  AS_UP(SDLK_ESCAPE, WKC_ESC),
409  AS_UP(SDLK_PAUSE, WKC_PAUSE),
410  AS_UP(SDLK_BACKSPACE, WKC_BACKSPACE),
411 
412  AS(SDLK_SPACE, WKC_SPACE),
413  AS(SDLK_RETURN, WKC_RETURN),
414  AS(SDLK_TAB, WKC_TAB),
415 
416  /* Function keys */
417  AM_UP(SDLK_F1, SDLK_F12, WKC_F1, WKC_F12),
418 
419  /* Numeric part. */
420  AM(SDLK_KP_0, SDLK_KP_9, '0', '9'),
421  AS(SDLK_KP_DIVIDE, WKC_NUM_DIV),
422  AS(SDLK_KP_MULTIPLY, WKC_NUM_MUL),
423  AS(SDLK_KP_MINUS, WKC_NUM_MINUS),
424  AS(SDLK_KP_PLUS, WKC_NUM_PLUS),
425  AS(SDLK_KP_ENTER, WKC_NUM_ENTER),
426  AS(SDLK_KP_PERIOD, WKC_NUM_DECIMAL),
427 
428  /* Other non-letter keys */
429  AS(SDLK_SLASH, WKC_SLASH),
430  AS(SDLK_SEMICOLON, WKC_SEMICOLON),
431  AS(SDLK_EQUALS, WKC_EQUALS),
432  AS(SDLK_LEFTBRACKET, WKC_L_BRACKET),
433  AS(SDLK_BACKSLASH, WKC_BACKSLASH),
434  AS(SDLK_RIGHTBRACKET, WKC_R_BRACKET),
435 
436  AS(SDLK_QUOTE, WKC_SINGLEQUOTE),
437  AS(SDLK_COMMA, WKC_COMMA),
438  AS(SDLK_MINUS, WKC_MINUS),
439  AS(SDLK_PERIOD, WKC_PERIOD)
440 };
441 
442 static uint ConvertSdlKeyIntoMy(SDL_Keysym *sym, WChar *character)
443 {
444  const VkMapping *map;
445  uint key = 0;
446  bool unprintable = false;
447 
448  for (map = _vk_mapping; map != endof(_vk_mapping); ++map) {
449  if ((uint)(sym->sym - map->vk_from) <= map->vk_count) {
450  key = sym->sym - map->vk_from + map->map_to;
451  unprintable = map->unprintable;
452  break;
453  }
454  }
455 
456  /* check scancode for BACKQUOTE key, because we want the key left of "1", not anything else (on non-US keyboards) */
457  if (sym->scancode == SDL_SCANCODE_GRAVE) key = WKC_BACKQUOTE;
458 
459  /* META are the command keys on mac */
460  if (sym->mod & KMOD_GUI) key |= WKC_META;
461  if (sym->mod & KMOD_SHIFT) key |= WKC_SHIFT;
462  if (sym->mod & KMOD_CTRL) key |= WKC_CTRL;
463  if (sym->mod & KMOD_ALT) key |= WKC_ALT;
464 
465  /* The mod keys have no character. Prevent '?' */
466  if (sym->mod & KMOD_GUI ||
467  sym->mod & KMOD_CTRL ||
468  sym->mod & KMOD_ALT ||
469  unprintable) {
470  *character = WKC_NONE;
471  } else {
472  *character = sym->sym;
473  }
474 
475  return key;
476 }
477 
482 static uint ConvertSdlKeycodeIntoMy(SDL_Keycode kc)
483 {
484  const VkMapping *map;
485  uint key = 0;
486 
487  for (map = _vk_mapping; map != endof(_vk_mapping); ++map) {
488  if ((uint)(kc - map->vk_from) <= map->vk_count) {
489  key = kc - map->vk_from + map->map_to;
490  break;
491  }
492  }
493 
494  /* check scancode for BACKQUOTE key, because we want the key left
495  of "1", not anything else (on non-US keyboards) */
496  SDL_Scancode sc = SDL_GetScancodeFromKey(kc);
497  if (sc == SDL_SCANCODE_GRAVE) key = WKC_BACKQUOTE;
498 
499  return key;
500 }
501 
502 int VideoDriver_SDL::PollEvent()
503 {
504  SDL_Event ev;
505 
506  if (!SDL_PollEvent(&ev)) return -2;
507 
508  switch (ev.type) {
509  case SDL_MOUSEMOTION:
510  if (_cursor.UpdateCursorPosition(ev.motion.x, ev.motion.y, true)) {
511  SDL_WarpMouseInWindow(_sdl_window, _cursor.pos.x, _cursor.pos.y);
512  }
514  break;
515 
516  case SDL_MOUSEWHEEL:
517  if (ev.wheel.y > 0) {
518  _cursor.wheel--;
519  } else if (ev.wheel.y < 0) {
520  _cursor.wheel++;
521  }
522  break;
523 
524  case SDL_MOUSEBUTTONDOWN:
525  if (_rightclick_emulate && SDL_GetModState() & KMOD_CTRL) {
526  ev.button.button = SDL_BUTTON_RIGHT;
527  }
528 
529  switch (ev.button.button) {
530  case SDL_BUTTON_LEFT:
531  _left_button_down = true;
532  break;
533 
534  case SDL_BUTTON_RIGHT:
535  _right_button_down = true;
536  _right_button_clicked = true;
537  break;
538 
539  default: break;
540  }
542  break;
543 
544  case SDL_MOUSEBUTTONUP:
545  if (_rightclick_emulate) {
546  _right_button_down = false;
547  _left_button_down = false;
548  _left_button_clicked = false;
549  } else if (ev.button.button == SDL_BUTTON_LEFT) {
550  _left_button_down = false;
551  _left_button_clicked = false;
552  } else if (ev.button.button == SDL_BUTTON_RIGHT) {
553  _right_button_down = false;
554  }
556  break;
557 
558  case SDL_QUIT:
559  HandleExitGameRequest();
560  break;
561 
562  case SDL_KEYDOWN: // Toggle full-screen on ALT + ENTER/F
563  if ((ev.key.keysym.mod & (KMOD_ALT | KMOD_GUI)) &&
564  (ev.key.keysym.sym == SDLK_RETURN || ev.key.keysym.sym == SDLK_f)) {
565  if (ev.key.repeat == 0) ToggleFullScreen(!_fullscreen);
566  } else {
567  WChar character;
568 
569  uint keycode = ConvertSdlKeyIntoMy(&ev.key.keysym, &character);
570  // Only handle non-text keys here. Text is handled in
571  // SDL_TEXTINPUT below.
572  if (!this->edit_box_focused ||
573  keycode == WKC_DELETE ||
574  keycode == WKC_NUM_ENTER ||
575  keycode == WKC_LEFT ||
576  keycode == WKC_RIGHT ||
577  keycode == WKC_UP ||
578  keycode == WKC_DOWN ||
579  keycode == WKC_HOME ||
580  keycode == WKC_END ||
581  keycode & WKC_META ||
582  keycode & WKC_CTRL ||
583  keycode & WKC_ALT ||
584  (keycode >= WKC_F1 && keycode <= WKC_F12) ||
585  !IsValidChar(character, CS_ALPHANUMERAL)) {
586  HandleKeypress(keycode, character);
587  }
588  }
589  break;
590 
591  case SDL_TEXTINPUT: {
592  if (!this->edit_box_focused) break;
593  SDL_Keycode kc = SDL_GetKeyFromName(ev.text.text);
594  uint keycode = ConvertSdlKeycodeIntoMy(kc);
595 
596  if (keycode == WKC_BACKQUOTE && FocusedWindowIsConsole()) {
597  WChar character;
598  Utf8Decode(&character, ev.text.text);
599  HandleKeypress(keycode, character);
600  } else {
601  HandleTextInput(ev.text.text);
602  }
603  break;
604  }
605  case SDL_WINDOWEVENT: {
606  if (ev.window.event == SDL_WINDOWEVENT_EXPOSED) {
607  // Force a redraw of the entire screen.
608  _num_dirty_rects = MAX_DIRTY_RECTS + 1;
609  } else if (ev.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) {
610  int w = max(ev.window.data1, 64);
611  int h = max(ev.window.data2, 64);
612  CreateMainSurface(w, h, w != ev.window.data1 || h != ev.window.data2);
613  } else if (ev.window.event == SDL_WINDOWEVENT_ENTER) {
614  // mouse entered the window, enable cursor
615  _cursor.in_window = true;
616  } else if (ev.window.event == SDL_WINDOWEVENT_LEAVE) {
617  // mouse left the window, undraw cursor
618  UndrawMouseCursor();
619  _cursor.in_window = false;
620  }
621  break;
622  }
623  }
624  return -1;
625 }
626 
627 const char *VideoDriver_SDL::Start(const char * const *parm)
628 {
629  /* Explicitly disable hardware acceleration. Enabling this causes
630  * UpdateWindowSurface() to update the window's texture instead of
631  * its surface. */
632  SDL_SetHint(SDL_HINT_FRAMEBUFFER_ACCELERATION , "0");
633 
634  /* Just on the offchance the audio subsystem started before the video system,
635  * check whether any part of SDL has been initialised before getting here.
636  * Slightly duplicated with sound/sdl_s.cpp */
637  int ret_code = 0;
638  if (SDL_WasInit(SDL_INIT_VIDEO) == 0) {
639  ret_code = SDL_InitSubSystem(SDL_INIT_VIDEO);
640  }
641  if (ret_code < 0) return SDL_GetError();
642 
643  GetVideoModes();
644  if (!CreateMainSurface(_cur_resolution.width, _cur_resolution.height, false)) {
645  return SDL_GetError();
646  }
647 
648  const char *dname = SDL_GetCurrentVideoDriver();
649  DEBUG(driver, 1, "SDL2: using driver '%s'", dname);
650 
652 
653  _draw_threaded = GetDriverParam(parm, "no_threads") == nullptr && GetDriverParam(parm, "no_thread") == nullptr;
654 
655  SDL_StopTextInput();
656  this->edit_box_focused = false;
657 
658  return nullptr;
659 }
660 
662 {
663  SDL_QuitSubSystem(SDL_INIT_VIDEO);
664  if (SDL_WasInit(SDL_INIT_EVERYTHING) == 0) {
665  SDL_Quit(); // If there's nothing left, quit SDL
666  }
667 }
668 
670 {
671  uint32 cur_ticks = SDL_GetTicks();
672  uint32 last_cur_ticks = cur_ticks;
673  uint32 next_tick = cur_ticks + MILLISECONDS_PER_TICK;
674  uint32 mod;
675  int numkeys;
676  const Uint8 *keys;
677 
678  CheckPaletteAnim();
679 
680  std::thread draw_thread;
681  std::unique_lock<std::recursive_mutex> draw_lock;
682  if (_draw_threaded) {
683  /* Initialise the mutex first, because that's the thing we *need*
684  * directly in the newly created thread. */
685  _draw_mutex = new std::recursive_mutex();
686  if (_draw_mutex == nullptr) {
687  _draw_threaded = false;
688  } else {
689  draw_lock = std::unique_lock<std::recursive_mutex>(*_draw_mutex);
690  _draw_signal = new std::condition_variable_any();
691  _draw_continue = true;
692 
693  _draw_threaded = StartNewThread(&draw_thread, "ottd:draw-sdl", &DrawSurfaceToScreenThread);
694 
695  /* Free the mutex if we won't be able to use it. */
696  if (!_draw_threaded) {
697  draw_lock.unlock();
698  draw_lock.release();
699  delete _draw_mutex;
700  delete _draw_signal;
701  _draw_mutex = nullptr;
702  _draw_signal = nullptr;
703  } else {
704  /* Wait till the draw mutex has started itself. */
705  _draw_signal->wait(*_draw_mutex);
706  }
707  }
708  }
709 
710  DEBUG(driver, 1, "SDL2: using %sthreads", _draw_threaded ? "" : "no ");
711 
712  for (;;) {
713  uint32 prev_cur_ticks = cur_ticks; // to check for wrapping
714  InteractiveRandom(); // randomness
715 
716  while (PollEvent() == -1) {}
717  if (_exit_game) break;
718 
719  mod = SDL_GetModState();
720  keys = SDL_GetKeyboardState(&numkeys);
721 
722 #if defined(_DEBUG)
723  if (_shift_pressed)
724 #else
725  /* Speedup when pressing tab, except when using ALT+TAB
726  * to switch to another application */
727  if (keys[SDL_SCANCODE_TAB] && (mod & KMOD_ALT) == 0)
728 #endif /* defined(_DEBUG) */
729  {
730  if (!_networking && _game_mode != GM_MENU) _fast_forward |= 2;
731  } else if (_fast_forward & 2) {
732  _fast_forward = 0;
733  }
734 
735  cur_ticks = SDL_GetTicks();
736  if (SDL_TICKS_PASSED(cur_ticks, next_tick) || (_fast_forward && !_pause_mode) || cur_ticks < prev_cur_ticks) {
737  _realtime_tick += cur_ticks - last_cur_ticks;
738  last_cur_ticks = cur_ticks;
739  next_tick = cur_ticks + MILLISECONDS_PER_TICK;
740 
741  bool old_ctrl_pressed = _ctrl_pressed;
742 
743  _ctrl_pressed = !!(mod & KMOD_CTRL);
744  _shift_pressed = !!(mod & KMOD_SHIFT);
745 
746  /* determine which directional keys are down */
747  _dirkeys =
748  (keys[SDL_SCANCODE_LEFT] ? 1 : 0) |
749  (keys[SDL_SCANCODE_UP] ? 2 : 0) |
750  (keys[SDL_SCANCODE_RIGHT] ? 4 : 0) |
751  (keys[SDL_SCANCODE_DOWN] ? 8 : 0);
752  if (old_ctrl_pressed != _ctrl_pressed) HandleCtrlChanged();
753 
754  /* The gameloop is the part that can run asynchronously. The rest
755  * except sleeping can't. */
756  if (_draw_mutex != nullptr) draw_lock.unlock();
757 
758  GameLoop();
759 
760  if (_draw_mutex != nullptr) draw_lock.lock();
761 
762  UpdateWindows();
763  _local_palette = _cur_palette;
764  } else {
765  /* Release the thread while sleeping */
766  if (_draw_mutex != nullptr) draw_lock.unlock();
767  CSleep(1);
768  if (_draw_mutex != nullptr) draw_lock.lock();
769 
771  DrawMouseCursor();
772  }
773 
774  /* End of the critical part. */
775  if (_draw_mutex != nullptr && !HasModalProgress()) {
776  _draw_signal->notify_one();
777  } else {
778  /* Oh, we didn't have threads, then just draw unthreaded */
779  CheckPaletteAnim();
780  DrawSurfaceToScreen();
781  }
782  }
783 
784  if (_draw_mutex != nullptr) {
785  _draw_continue = false;
786  /* Sending signal if there is no thread blocked
787  * is very valid and results in noop */
788  _draw_signal->notify_one();
789  if (draw_lock.owns_lock()) draw_lock.unlock();
790  draw_lock.release();
791  draw_thread.join();
792 
793  delete _draw_mutex;
794  delete _draw_signal;
795 
796  _draw_mutex = nullptr;
797  _draw_signal = nullptr;
798  }
799 }
800 
801 bool VideoDriver_SDL::ChangeResolution(int w, int h)
802 {
803  std::unique_lock<std::recursive_mutex> lock;
804  if (_draw_mutex != nullptr) lock = std::unique_lock<std::recursive_mutex>(*_draw_mutex);
805 
806  return CreateMainSurface(w, h, true);
807 }
808 
809 bool VideoDriver_SDL::ToggleFullscreen(bool fullscreen)
810 {
811  std::unique_lock<std::recursive_mutex> lock;
812  if (_draw_mutex != nullptr) lock = std::unique_lock<std::recursive_mutex>(*_draw_mutex);
813 
814  /* Remember current window size */
815  if (fullscreen) {
816  SDL_GetWindowSize(_sdl_window, &_window_size_w, &_window_size_h);
817 
818  /* Find fullscreen window size */
819  SDL_DisplayMode dm;
820  if (SDL_GetCurrentDisplayMode(0, &dm) < 0) {
821  DEBUG(driver, 0, "SDL_GetCurrentDisplayMode() failed: %s", SDL_GetError());
822  } else {
823  SDL_SetWindowSize(_sdl_window, dm.w, dm.h);
824  }
825  }
826 
827  DEBUG(driver, 1, "SDL2: Setting %s", fullscreen ? "fullscreen" : "windowed");
828  int ret = SDL_SetWindowFullscreen(_sdl_window, fullscreen ? SDL_WINDOW_FULLSCREEN : 0);
829  if (ret == 0) {
830  /* Switching resolution succeeded, set fullscreen value of window. */
831  _fullscreen = fullscreen;
832  if (!fullscreen) SDL_SetWindowSize(_sdl_window, _window_size_w, _window_size_h);
833  } else {
834  DEBUG(driver, 0, "SDL_SetWindowFullscreen() failed: %s", SDL_GetError());
835  }
836 
837  return ret == 0;
838 }
839 
841 {
842  int w, h;
843  SDL_GetWindowSize(_sdl_window, &w, &h);
844  return CreateMainSurface(w, h, false);
845 }
846 
848 {
849  if (_draw_mutex != nullptr) _draw_mutex->lock();
850 }
851 
853 {
854  if (_draw_mutex != nullptr) _draw_mutex->unlock();
855 }
856 
857 #endif /* WITH_SDL2 */
const char * GetDriverParam(const char *const *parm, const char *name)
Get a string parameter the list of parameters.
Definition: driver.cpp:37
bool _networking
are we in networking mode?
Definition: network.cpp:52
uint32 _realtime_tick
The real time in the game.
Definition: debug.cpp:48
Point pos
logical mouse position
Definition: gfx_type.h:117
Information about the currently used palette.
Definition: gfx_type.h:308
void AcquireBlitterLock() override
Acquire any lock(s) required to be held when changing blitters.
Definition: sdl_v.cpp:821
, Comma
Definition: gfx_type.h:102
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:407
bool _right_button_down
Is right mouse button pressed?
Definition: gfx.cpp:40
void MakeDirty(int left, int top, int width, int height) override
Mark a particular area dirty.
Definition: sdl_v.cpp:54
Colour palette[256]
Current palette. Entry 0 has to be always fully transparent!
Definition: gfx_type.h:309
= Equals
Definition: gfx_type.h:97
void Stop() override
Stop this driver.
Definition: sdl_v.cpp:637
void CSleep(int milliseconds)
Sleep on the current thread for a defined time.
Definition: thread.h:25
size_t Utf8Decode(WChar *c, const char *s)
Decode and consume the next UTF-8 encoded character.
Definition: string.cpp:446
Dimension _cur_resolution
The current resolution.
Definition: driver.cpp:21
static volatile bool _draw_continue
Should we keep continue drawing?
Definition: sdl_v.cpp:45
#define lastof(x)
Get the last element of an fixed size array.
Definition: depend.cpp:48
No palette animation.
Definition: base.hpp:50
How all blitters should look like.
Definition: base.hpp:28
Base of the SDL2 video driver.
RAII class for measuring simple elements of performance.
Subdirectory for all base data (base sets, intro game)
Definition: fileio_type.h:116
static T max(const T a, const T b)
Returns the maximum of two values.
Definition: math_func.hpp:24
virtual void PostResize()
Post resize event.
Definition: base.hpp:201
Palette animation should be done by video backend (8bpp only!)
Definition: base.hpp:51
bool _left_button_clicked
Is left mouse button clicked?
Definition: gfx.cpp:39
std::vector< Dimension > _resolutions
List of resolutions.
Definition: driver.cpp:20
bool AfterBlitterChange() override
Callback invoked after the blitter was changed.
Definition: sdl_v.cpp:816
static std::condition_variable_any * _draw_signal
Signal to draw the next frame.
Definition: sdl_v.cpp:43
bool _ctrl_pressed
Is Ctrl pressed?
Definition: gfx.cpp:35
bool StartNewThread(std::thread *thr, const char *name, TFn &&_Fx, TArgs &&... _Ax)
Start a new thread.
Definition: thread.h:48
&#39; Single quote
Definition: gfx_type.h:101
bool IsValidChar(WChar key, CharSetFilter afilter)
Only allow certain keys.
Definition: string.cpp:348
bool _right_button_clicked
Is right mouse button clicked?
Definition: gfx.cpp:41
The blitter takes care of the palette animation.
Definition: base.hpp:52
char * FioFindFullPath(char *buf, const char *last, Subdirectory subdir, const char *filename)
Find a path to the filename in one of the search directories.
Definition: fileio.cpp:355
virtual void PaletteAnimate(const Palette &palette)=0
Called when the 8bpp palette is changed; you should redraw all pixels on the screen that are equal to...
bool _left_button_down
Is left mouse button pressed?
Definition: gfx.cpp:38
[ Left square bracket
Definition: gfx_type.h:98
] Right square bracket
Definition: gfx_type.h:100
std::mutex lock
synchronization for playback status fields
Definition: win32_m.cpp:34
\ Backslash
Definition: gfx_type.h:99
void CDECL usererror(const char *s,...)
Error handling for fatal user errors.
Definition: openttd.cpp:93
int wheel
mouse wheel movement
Definition: gfx_type.h:119
bool UpdateCursorPosition(int x, int y, bool queued_warp)
Update cursor position on mouse movement.
Definition: gfx.cpp:1785
void EditBoxLostFocus() override
An edit box lost the input focus.
/ Forward slash
Definition: gfx_type.h:95
static const uint MILLISECONDS_PER_TICK
The number of milliseconds per game tick.
Definition: gfx_type.h:305
void HandleKeypress(uint keycode, WChar key)
Handle keyboard input.
Definition: window.cpp:2673
byte _dirkeys
1 = left, 2 = up, 4 = right, 8 = down
Definition: gfx.cpp:31
void HandleMouseEvents()
Handle a mouse event from the video driver.
Definition: window.cpp:2980
bool ToggleFullscreen(bool fullscreen) override
Change the full screen setting.
Definition: sdl_v.cpp:799
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
Definition: factory.hpp:145
int first_dirty
The first dirty element.
Definition: gfx_type.h:310
PauseMode _pause_mode
The current pause mode.
Definition: gfx.cpp:47
; Semicolon
Definition: gfx_type.h:96
Palette _cur_palette
Current palette.
Definition: gfx.cpp:48
bool _shift_pressed
Is Shift pressed?
Definition: gfx.cpp:36
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:35
virtual Blitter::PaletteAnimation UsePaletteAnimation()=0
Check if the blitter uses palette animation at all.
static bool _draw_threaded
Whether the drawing is/may be done in a separate thread.
Definition: sdl_v.cpp:39
void HandleCtrlChanged()
State of CONTROL key has changed.
Definition: window.cpp:2730
Both numeric and alphabetic and spaces and stuff.
Definition: string_type.h:27
void MainLoop() override
Perform the actual drawing.
Definition: sdl_v.cpp:645
Speed of painting drawn video buffer.
bool edit_box_focused
This is true to indicate that keyboard input is in text input mode, and SDL_TEXTINPUT events are enab...
Definition: sdl2_v.h:50
void NetworkDrawChatMessage()
Draw the chat message-box.
static Palette _local_palette
Local copy of the palette for use in the drawing thread.
Definition: win32_v.cpp:76
#define endof(x)
Get the end element of an fixed size array.
Definition: stdafx.h:384
void EditBoxGainedFocus() override
An edit box gained the input focus.
bool in_window
mouse inside this window, determines drawing logic
Definition: gfx_type.h:141
bool ChangeResolution(int w, int h) override
Change the resolution of the window.
Definition: sdl_v.cpp:791
virtual uint8 GetScreenDepth()=0
Get the screen depth this blitter works for.
#define AS(ap_name, size_x, size_y, min_year, max_year, catchment, noise, maint_cost, ttdpatch_type, class_id, name, preview)
AirportSpec definition for airports with at least one depot.
void ReleaseBlitterLock() override
Release any lock(s) required to be held when changing blitters.
Definition: sdl_v.cpp:826
static std::recursive_mutex * _draw_mutex
Mutex to keep the access to the shared memory controlled.
Definition: sdl_v.cpp:41
bool _rightclick_emulate
Whether right clicking is emulated.
Definition: driver.cpp:22
void GameSizeChanged()
Size of the application screen changed.
Definition: main_gui.cpp:594
void HandleTextInput(const char *str, bool marked=false, const char *caret=nullptr, const char *insert_location=nullptr, const char *replacement_end=nullptr)
Handle text input.
Definition: window.cpp:2761
. Period
Definition: gfx_type.h:103
bool FocusedWindowIsConsole()
Check if a console is focused.
Definition: window.cpp:471
Factory for the SDL video driver.
Definition: sdl2_v.h:54
int count_dirty
The number of dirty elements.
Definition: gfx_type.h:311
static T Delta(const T a, const T b)
Returns the (absolute) difference between two (scalar) variables.
Definition: math_func.hpp:230
uint32 WChar
Type for wide characters, i.e.
Definition: string_type.h:35
Dimensions (a width and height) of a rectangle in 2D.
static bool HasModalProgress()
Check if we are currently in a modal progress state.
Definition: progress.h:21
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition: gfx.cpp:1600
const char * Start(const char *const *param) override
Start this driver.
Definition: sdl_v.cpp:599
void UpdateWindows()
Update the continuously changing contents of the windows, such as the viewports.
Definition: window.cpp:3131