OpenTTD
sdl_v.cpp
Go to the documentation of this file.
1 /* $Id$ */
2 
3 /*
4  * This file is part of OpenTTD.
5  * 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.
6  * 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.
7  * 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/>.
8  */
9 
12 #ifdef WITH_SDL
13 
14 #include "../stdafx.h"
15 #include "../openttd.h"
16 #include "../gfx_func.h"
17 #include "../sdl.h"
18 #include "../rev.h"
19 #include "../blitter/factory.hpp"
20 #include "../network/network.h"
21 #include "../thread/thread.h"
22 #include "../progress.h"
23 #include "../core/random_func.hpp"
24 #include "../core/math_func.hpp"
25 #include "../fileio_func.h"
26 #include "../framerate_type.h"
27 #include "sdl_v.h"
28 #include <SDL.h>
29 
30 #include "../safeguards.h"
31 
32 static FVideoDriver_SDL iFVideoDriver_SDL;
33 
34 static SDL_Surface *_sdl_screen;
35 static SDL_Surface *_sdl_realscreen;
36 static bool _all_modes;
37 
39 static bool _draw_threaded;
41 static ThreadObject *_draw_thread = NULL;
43 static ThreadMutex *_draw_mutex = NULL;
45 static volatile bool _draw_continue;
46 static Palette _local_palette;
47 
48 #define MAX_DIRTY_RECTS 100
49 static SDL_Rect _dirty_rects[MAX_DIRTY_RECTS];
50 static int _num_dirty_rects;
51 static int _use_hwpalette;
52 static int _requested_hwpalette; /* Did we request a HWPALETTE for the current video mode? */
53 
54 void VideoDriver_SDL::MakeDirty(int left, int top, int width, int height)
55 {
56  if (_num_dirty_rects < MAX_DIRTY_RECTS) {
57  _dirty_rects[_num_dirty_rects].x = left;
58  _dirty_rects[_num_dirty_rects].y = top;
59  _dirty_rects[_num_dirty_rects].w = width;
60  _dirty_rects[_num_dirty_rects].h = height;
61  }
62  _num_dirty_rects++;
63 }
64 
65 static void UpdatePalette(bool init = false)
66 {
67  SDL_Color pal[256];
68 
69  for (int i = 0; i != _local_palette.count_dirty; i++) {
70  pal[i].r = _local_palette.palette[_local_palette.first_dirty + i].r;
71  pal[i].g = _local_palette.palette[_local_palette.first_dirty + i].g;
72  pal[i].b = _local_palette.palette[_local_palette.first_dirty + i].b;
73  pal[i].unused = 0;
74  }
75 
76  SDL_CALL SDL_SetColors(_sdl_screen, pal, _local_palette.first_dirty, _local_palette.count_dirty);
77 
78  if (_sdl_screen != _sdl_realscreen && init) {
79  /* When using a shadow surface, also set our palette on the real screen. This lets SDL
80  * allocate as much colors (or approximations) as
81  * possible, instead of using only the default SDL
82  * palette. This allows us to get more colors exactly
83  * right and might allow using better approximations for
84  * other colors.
85  *
86  * Note that colors allocations are tried in-order, so
87  * this favors colors further up into the palette. Also
88  * note that if two colors from the same animation
89  * sequence are approximated using the same color, that
90  * animation will stop working.
91  *
92  * Since changing the system palette causes the colours
93  * to change right away, and allocations might
94  * drastically change, we can't use this for animation,
95  * since that could cause weird coloring between the
96  * palette change and the blitting below, so we only set
97  * the real palette during initialisation.
98  */
99  SDL_CALL SDL_SetColors(_sdl_realscreen, pal, _local_palette.first_dirty, _local_palette.count_dirty);
100  }
101 
102  if (_sdl_screen != _sdl_realscreen && !init) {
103  /* We're not using real hardware palette, but are letting SDL
104  * approximate the palette during shadow -> screen copy. To
105  * change the palette, we need to recopy the entire screen.
106  *
107  * Note that this operation can slow down the rendering
108  * considerably, especially since changing the shadow
109  * palette will need the next blit to re-detect the
110  * best mapping of shadow palette colors to real palette
111  * colors from scratch.
112  */
113  SDL_CALL SDL_BlitSurface(_sdl_screen, NULL, _sdl_realscreen, NULL);
114  SDL_CALL SDL_UpdateRect(_sdl_realscreen, 0, 0, 0, 0);
115  }
116 }
117 
118 static void InitPalette()
119 {
120  _local_palette = _cur_palette;
121  _local_palette.first_dirty = 0;
122  _local_palette.count_dirty = 256;
123  UpdatePalette(true);
124 }
125 
126 static void CheckPaletteAnim()
127 {
128  if (_cur_palette.count_dirty != 0) {
130 
131  switch (blitter->UsePaletteAnimation()) {
133  UpdatePalette();
134  break;
135 
137  blitter->PaletteAnimate(_local_palette);
138  break;
139 
141  break;
142 
143  default:
144  NOT_REACHED();
145  }
147  }
148 }
149 
150 static void DrawSurfaceToScreen()
151 {
152  PerformanceMeasurer framerate(PFE_VIDEO);
153 
154  int n = _num_dirty_rects;
155  if (n == 0) return;
156 
157  _num_dirty_rects = 0;
158  if (n > MAX_DIRTY_RECTS) {
159  if (_sdl_screen != _sdl_realscreen) {
160  SDL_CALL SDL_BlitSurface(_sdl_screen, NULL, _sdl_realscreen, NULL);
161  }
162  SDL_CALL SDL_UpdateRect(_sdl_realscreen, 0, 0, 0, 0);
163  } else {
164  if (_sdl_screen != _sdl_realscreen) {
165  for (int i = 0; i < n; i++) {
166  SDL_CALL SDL_BlitSurface(_sdl_screen, &_dirty_rects[i], _sdl_realscreen, &_dirty_rects[i]);
167  }
168  }
169  SDL_CALL SDL_UpdateRects(_sdl_realscreen, n, _dirty_rects);
170  }
171 }
172 
173 static void DrawSurfaceToScreenThread(void *)
174 {
175  /* First tell the main thread we're started */
176  _draw_mutex->BeginCritical();
177  _draw_mutex->SendSignal();
178 
179  /* Now wait for the first thing to draw! */
180  _draw_mutex->WaitForSignal();
181 
182  while (_draw_continue) {
183  CheckPaletteAnim();
184  /* Then just draw and wait till we stop */
185  DrawSurfaceToScreen();
186  _draw_mutex->WaitForSignal();
187  }
188 
189  _draw_mutex->EndCritical();
190  _draw_thread->Exit();
191 }
192 
193 static const Dimension _default_resolutions[] = {
194  { 640, 480},
195  { 800, 600},
196  {1024, 768},
197  {1152, 864},
198  {1280, 800},
199  {1280, 960},
200  {1280, 1024},
201  {1400, 1050},
202  {1600, 1200},
203  {1680, 1050},
204  {1920, 1200}
205 };
206 
207 static void GetVideoModes()
208 {
209  SDL_Rect **modes = SDL_CALL SDL_ListModes(NULL, SDL_SWSURFACE | SDL_FULLSCREEN);
210  if (modes == NULL) usererror("sdl: no modes available");
211 
212  _all_modes = (SDL_CALL SDL_ListModes(NULL, SDL_SWSURFACE | (_fullscreen ? SDL_FULLSCREEN : 0)) == (void*)-1);
213  if (modes == (void*)-1) {
214  int n = 0;
215  for (uint i = 0; i < lengthof(_default_resolutions); i++) {
216  if (SDL_CALL SDL_VideoModeOK(_default_resolutions[i].width, _default_resolutions[i].height, 8, SDL_FULLSCREEN) != 0) {
217  _resolutions[n] = _default_resolutions[i];
218  if (++n == lengthof(_resolutions)) break;
219  }
220  }
221  _num_resolutions = n;
222  } else {
223  int n = 0;
224  for (int i = 0; modes[i]; i++) {
225  uint w = modes[i]->w;
226  uint h = modes[i]->h;
227  int j;
228  for (j = 0; j < n; j++) {
229  if (_resolutions[j].width == w && _resolutions[j].height == h) break;
230  }
231 
232  if (j == n) {
233  _resolutions[j].width = w;
234  _resolutions[j].height = h;
235  if (++n == lengthof(_resolutions)) break;
236  }
237  }
238  _num_resolutions = n;
239  SortResolutions(_num_resolutions);
240  }
241 }
242 
243 static void GetAvailableVideoMode(uint *w, uint *h)
244 {
245  /* All modes available? */
246  if (_all_modes || _num_resolutions == 0) return;
247 
248  /* Is the wanted mode among the available modes? */
249  for (int i = 0; i != _num_resolutions; i++) {
250  if (*w == _resolutions[i].width && *h == _resolutions[i].height) return;
251  }
252 
253  /* Use the closest possible resolution */
254  int best = 0;
255  uint delta = Delta(_resolutions[0].width, *w) * Delta(_resolutions[0].height, *h);
256  for (int i = 1; i != _num_resolutions; ++i) {
257  uint newdelta = Delta(_resolutions[i].width, *w) * Delta(_resolutions[i].height, *h);
258  if (newdelta < delta) {
259  best = i;
260  delta = newdelta;
261  }
262  }
263  *w = _resolutions[best].width;
264  *h = _resolutions[best].height;
265 }
266 
267 #ifdef _WIN32
268 /* Let's redefine the LoadBMP macro with because we are dynamically
269  * loading SDL and need to 'SDL_CALL' all functions */
270 #undef SDL_LoadBMP
271 #define SDL_LoadBMP(file) SDL_LoadBMP_RW(SDL_CALL SDL_RWFromFile(file, "rb"), 1)
272 #endif
273 
274 bool VideoDriver_SDL::CreateMainSurface(uint w, uint h)
275 {
276  SDL_Surface *newscreen, *icon;
277  char caption[50];
279  bool want_hwpalette;
280 
281  GetAvailableVideoMode(&w, &h);
282 
283  DEBUG(driver, 1, "SDL: using mode %ux%ux%d", w, h, bpp);
284 
285  if (bpp == 0) usererror("Can't use a blitter that blits 0 bpp for normal visuals");
286 
287  char icon_path[MAX_PATH];
288  if (FioFindFullPath(icon_path, lastof(icon_path), BASESET_DIR, "openttd.32.bmp") != NULL) {
289  /* Give the application an icon */
290  icon = SDL_CALL SDL_LoadBMP(icon_path);
291  if (icon != NULL) {
292  /* Get the colourkey, which will be magenta */
293  uint32 rgbmap = SDL_CALL SDL_MapRGB(icon->format, 255, 0, 255);
294 
295  SDL_CALL SDL_SetColorKey(icon, SDL_SRCCOLORKEY, rgbmap);
296  SDL_CALL SDL_WM_SetIcon(icon, NULL);
297  SDL_CALL SDL_FreeSurface(icon);
298  }
299  }
300 
301  if (_use_hwpalette == 2) {
302  /* Default is to autodetect when to use SDL_HWPALETTE.
303  * In this case, SDL_HWPALETTE is only used for 8bpp
304  * blitters in fullscreen.
305  *
306  * When using an 8bpp blitter on a 8bpp system in
307  * windowed mode with SDL_HWPALETTE, OpenTTD will claim
308  * the system palette, making all other applications
309  * get the wrong colours. In this case, we're better of
310  * trying to approximate the colors we need using system
311  * colors, using a shadow surface (see below).
312  *
313  * On a 32bpp system, SDL_HWPALETTE is ignored, so it
314  * doesn't matter what we do.
315  *
316  * When using a 32bpp blitter on a 8bpp system, setting
317  * SDL_HWPALETTE messes up rendering (at least on X11),
318  * so we don't do that. In this case, SDL takes care of
319  * color approximation using its own shadow surface
320  * (which we can't force in 8bpp on 8bpp mode,
321  * unfortunately).
322  */
323  want_hwpalette = bpp == 8 && _fullscreen && _support8bpp == S8BPP_HARDWARE;
324  } else {
325  /* User specified a value manually */
326  want_hwpalette = _use_hwpalette;
327  }
328 
329  if (want_hwpalette) DEBUG(driver, 1, "SDL: requesting hardware palette");
330 
331  /* Free any previously allocated shadow surface */
332  if (_sdl_screen != NULL && _sdl_screen != _sdl_realscreen) SDL_CALL SDL_FreeSurface(_sdl_screen);
333 
334  if (_sdl_realscreen != NULL) {
335  if (_requested_hwpalette != want_hwpalette) {
336  /* SDL (at least the X11 driver), reuses the
337  * same window and palette settings when the bpp
338  * (and a few flags) are the same. Since we need
339  * to hwpalette value to change (in particular
340  * when switching between fullscreen and
341  * windowed), we restart the entire video
342  * subsystem to force creating a new window.
343  */
344  DEBUG(driver, 0, "SDL: Restarting SDL video subsystem, to force hwpalette change");
345  SDL_CALL SDL_QuitSubSystem(SDL_INIT_VIDEO);
346  SDL_CALL SDL_InitSubSystem(SDL_INIT_VIDEO);
347  ClaimMousePointer();
348  SetupKeyboard();
349  }
350  }
351  /* Remember if we wanted a hwpalette. We can't reliably query
352  * SDL for the SDL_HWPALETTE flag, since it might get set even
353  * though we didn't ask for it (when SDL creates a shadow
354  * surface, for example). */
355  _requested_hwpalette = want_hwpalette;
356 
357  /* DO NOT CHANGE TO HWSURFACE, IT DOES NOT WORK */
358  newscreen = SDL_CALL SDL_SetVideoMode(w, h, bpp, SDL_SWSURFACE | (want_hwpalette ? SDL_HWPALETTE : 0) | (_fullscreen ? SDL_FULLSCREEN : SDL_RESIZABLE));
359  if (newscreen == NULL) {
360  DEBUG(driver, 0, "SDL: Couldn't allocate a window to draw on");
361  return false;
362  }
363  _sdl_realscreen = newscreen;
364 
365  if (bpp == 8 && (_sdl_realscreen->flags & SDL_HWPALETTE) != SDL_HWPALETTE) {
366  /* Using an 8bpp blitter, if we didn't get a hardware
367  * palette (most likely because we didn't request one,
368  * see above), we'll have to set up a shadow surface to
369  * render on.
370  *
371  * Our palette will be applied to this shadow surface,
372  * while the real screen surface will use the shared
373  * system palette (which will partly contain our colors,
374  * but most likely will not have enough free color cells
375  * for all of our colors). SDL can use these two
376  * palettes at blit time to approximate colors used in
377  * the shadow surface using system colors automatically.
378  *
379  * Note that when using an 8bpp blitter on a 32bpp
380  * system, SDL will create an internal shadow surface.
381  * This shadow surface will have SDL_HWPALLETE set, so
382  * we won't create a second shadow surface in this case.
383  */
384  DEBUG(driver, 1, "SDL: using shadow surface");
385  newscreen = SDL_CALL SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, bpp, 0, 0, 0, 0);
386  if (newscreen == NULL) {
387  DEBUG(driver, 0, "SDL: Couldn't allocate a shadow surface to draw on");
388  return false;
389  }
390  }
391 
392  /* Delay drawing for this cycle; the next cycle will redraw the whole screen */
393  _num_dirty_rects = 0;
394 
395  _screen.width = newscreen->w;
396  _screen.height = newscreen->h;
397  _screen.pitch = newscreen->pitch / (bpp / 8);
398  _screen.dst_ptr = newscreen->pixels;
399  _sdl_screen = newscreen;
400 
401  /* When in full screen, we will always have the mouse cursor
402  * within the window, even though SDL does not give us the
403  * appropriate event to know this. */
404  if (_fullscreen) _cursor.in_window = true;
405 
407  blitter->PostResize();
408 
409  InitPalette();
410 
411  seprintf(caption, lastof(caption), "OpenTTD %s", _openttd_revision);
412  SDL_CALL SDL_WM_SetCaption(caption, caption);
413 
414  GameSizeChanged();
415 
416  return true;
417 }
418 
419 bool VideoDriver_SDL::ClaimMousePointer()
420 {
421  SDL_CALL SDL_ShowCursor(0);
422  return true;
423 }
424 
425 struct VkMapping {
426 #if SDL_VERSION_ATLEAST(1, 3, 0)
427  SDL_Keycode vk_from;
428 #else
429  uint16 vk_from;
430 #endif
431  byte vk_count;
432  byte map_to;
433 };
434 
435 #define AS(x, z) {x, 0, z}
436 #define AM(x, y, z, w) {x, (byte)(y - x), z}
437 
438 static const VkMapping _vk_mapping[] = {
439  /* Pageup stuff + up/down */
440  AM(SDLK_PAGEUP, SDLK_PAGEDOWN, WKC_PAGEUP, WKC_PAGEDOWN),
441  AS(SDLK_UP, WKC_UP),
442  AS(SDLK_DOWN, WKC_DOWN),
443  AS(SDLK_LEFT, WKC_LEFT),
444  AS(SDLK_RIGHT, WKC_RIGHT),
445 
446  AS(SDLK_HOME, WKC_HOME),
447  AS(SDLK_END, WKC_END),
448 
449  AS(SDLK_INSERT, WKC_INSERT),
450  AS(SDLK_DELETE, WKC_DELETE),
451 
452  /* Map letters & digits */
453  AM(SDLK_a, SDLK_z, 'A', 'Z'),
454  AM(SDLK_0, SDLK_9, '0', '9'),
455 
456  AS(SDLK_ESCAPE, WKC_ESC),
457  AS(SDLK_PAUSE, WKC_PAUSE),
458  AS(SDLK_BACKSPACE, WKC_BACKSPACE),
459 
460  AS(SDLK_SPACE, WKC_SPACE),
461  AS(SDLK_RETURN, WKC_RETURN),
462  AS(SDLK_TAB, WKC_TAB),
463 
464  /* Function keys */
465  AM(SDLK_F1, SDLK_F12, WKC_F1, WKC_F12),
466 
467  /* Numeric part. */
468  AM(SDLK_KP0, SDLK_KP9, '0', '9'),
469  AS(SDLK_KP_DIVIDE, WKC_NUM_DIV),
470  AS(SDLK_KP_MULTIPLY, WKC_NUM_MUL),
471  AS(SDLK_KP_MINUS, WKC_NUM_MINUS),
472  AS(SDLK_KP_PLUS, WKC_NUM_PLUS),
473  AS(SDLK_KP_ENTER, WKC_NUM_ENTER),
474  AS(SDLK_KP_PERIOD, WKC_NUM_DECIMAL),
475 
476  /* Other non-letter keys */
477  AS(SDLK_SLASH, WKC_SLASH),
478  AS(SDLK_SEMICOLON, WKC_SEMICOLON),
479  AS(SDLK_EQUALS, WKC_EQUALS),
480  AS(SDLK_LEFTBRACKET, WKC_L_BRACKET),
481  AS(SDLK_BACKSLASH, WKC_BACKSLASH),
482  AS(SDLK_RIGHTBRACKET, WKC_R_BRACKET),
483 
484  AS(SDLK_QUOTE, WKC_SINGLEQUOTE),
485  AS(SDLK_COMMA, WKC_COMMA),
486  AS(SDLK_MINUS, WKC_MINUS),
487  AS(SDLK_PERIOD, WKC_PERIOD)
488 };
489 
490 static uint ConvertSdlKeyIntoMy(SDL_keysym *sym, WChar *character)
491 {
492  const VkMapping *map;
493  uint key = 0;
494 
495  for (map = _vk_mapping; map != endof(_vk_mapping); ++map) {
496  if ((uint)(sym->sym - map->vk_from) <= map->vk_count) {
497  key = sym->sym - map->vk_from + map->map_to;
498  break;
499  }
500  }
501 
502  /* check scancode for BACKQUOTE key, because we want the key left of "1", not anything else (on non-US keyboards) */
503 #if defined(_WIN32) || defined(__OS2__)
504  if (sym->scancode == 41) key = WKC_BACKQUOTE;
505 #elif defined(__APPLE__)
506  if (sym->scancode == 10) key = WKC_BACKQUOTE;
507 #elif defined(__MORPHOS__)
508  if (sym->scancode == 0) key = WKC_BACKQUOTE; // yes, that key is code '0' under MorphOS :)
509 #elif defined(__BEOS__)
510  if (sym->scancode == 17) key = WKC_BACKQUOTE;
511 #elif defined(__SVR4) && defined(__sun)
512  if (sym->scancode == 60) key = WKC_BACKQUOTE;
513  if (sym->scancode == 49) key = WKC_BACKSPACE;
514 #elif defined(__sgi__)
515  if (sym->scancode == 22) key = WKC_BACKQUOTE;
516 #else
517  if (sym->scancode == 49) key = WKC_BACKQUOTE;
518 #endif
519 
520  /* META are the command keys on mac */
521  if (sym->mod & KMOD_META) key |= WKC_META;
522  if (sym->mod & KMOD_SHIFT) key |= WKC_SHIFT;
523  if (sym->mod & KMOD_CTRL) key |= WKC_CTRL;
524  if (sym->mod & KMOD_ALT) key |= WKC_ALT;
525 
526  *character = sym->unicode;
527  return key;
528 }
529 
530 int VideoDriver_SDL::PollEvent()
531 {
532  SDL_Event ev;
533 
534  if (!SDL_CALL SDL_PollEvent(&ev)) return -2;
535 
536  switch (ev.type) {
537  case SDL_MOUSEMOTION:
538  if (_cursor.UpdateCursorPosition(ev.motion.x, ev.motion.y, true)) {
539  SDL_CALL SDL_WarpMouse(_cursor.pos.x, _cursor.pos.y);
540  }
542  break;
543 
544  case SDL_MOUSEBUTTONDOWN:
545  if (_rightclick_emulate && SDL_CALL SDL_GetModState() & KMOD_CTRL) {
546  ev.button.button = SDL_BUTTON_RIGHT;
547  }
548 
549  switch (ev.button.button) {
550  case SDL_BUTTON_LEFT:
551  _left_button_down = true;
552  break;
553 
554  case SDL_BUTTON_RIGHT:
555  _right_button_down = true;
556  _right_button_clicked = true;
557  break;
558 
559  case SDL_BUTTON_WHEELUP: _cursor.wheel--; break;
560  case SDL_BUTTON_WHEELDOWN: _cursor.wheel++; break;
561 
562  default: break;
563  }
565  break;
566 
567  case SDL_MOUSEBUTTONUP:
568  if (_rightclick_emulate) {
569  _right_button_down = false;
570  _left_button_down = false;
571  _left_button_clicked = false;
572  } else if (ev.button.button == SDL_BUTTON_LEFT) {
573  _left_button_down = false;
574  _left_button_clicked = false;
575  } else if (ev.button.button == SDL_BUTTON_RIGHT) {
576  _right_button_down = false;
577  }
579  break;
580 
581  case SDL_ACTIVEEVENT:
582  if (!(ev.active.state & SDL_APPMOUSEFOCUS)) break;
583 
584  if (ev.active.gain) { // mouse entered the window, enable cursor
585  _cursor.in_window = true;
586  } else {
587  UndrawMouseCursor(); // mouse left the window, undraw cursor
588  _cursor.in_window = false;
589  }
590  break;
591 
592  case SDL_QUIT:
593  HandleExitGameRequest();
594  break;
595 
596  case SDL_KEYDOWN: // Toggle full-screen on ALT + ENTER/F
597  if ((ev.key.keysym.mod & (KMOD_ALT | KMOD_META)) &&
598  (ev.key.keysym.sym == SDLK_RETURN || ev.key.keysym.sym == SDLK_f)) {
599  ToggleFullScreen(!_fullscreen);
600  } else {
601  WChar character;
602  uint keycode = ConvertSdlKeyIntoMy(&ev.key.keysym, &character);
603  HandleKeypress(keycode, character);
604  }
605  break;
606 
607  case SDL_VIDEORESIZE: {
608  int w = max(ev.resize.w, 64);
609  int h = max(ev.resize.h, 64);
610  CreateMainSurface(w, h);
611  break;
612  }
613  case SDL_VIDEOEXPOSE: {
614  /* Force a redraw of the entire screen. Note
615  * that SDL 1.2 seems to do this automatically
616  * in most cases, but 1.3 / 2.0 does not. */
617  _num_dirty_rects = MAX_DIRTY_RECTS + 1;
618  break;
619  }
620  }
621  return -1;
622 }
623 
624 const char *VideoDriver_SDL::Start(const char * const *parm)
625 {
626  char buf[30];
627  _use_hwpalette = GetDriverParamInt(parm, "hw_palette", 2);
628 
629  const char *s = SdlOpen(SDL_INIT_VIDEO);
630  if (s != NULL) return s;
631 
632  GetVideoModes();
633  if (!CreateMainSurface(_cur_resolution.width, _cur_resolution.height)) {
634  return SDL_CALL SDL_GetError();
635  }
636 
637  SDL_CALL SDL_VideoDriverName(buf, sizeof buf);
638  DEBUG(driver, 1, "SDL: using driver '%s'", buf);
639 
641  SetupKeyboard();
642 
643  _draw_threaded = GetDriverParam(parm, "no_threads") == NULL && GetDriverParam(parm, "no_thread") == NULL;
644 
645  return NULL;
646 }
647 
648 void VideoDriver_SDL::SetupKeyboard()
649 {
650  SDL_CALL SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
651  SDL_CALL SDL_EnableUNICODE(1);
652 }
653 
655 {
656  SdlClose(SDL_INIT_VIDEO);
657 }
658 
660 {
661  uint32 cur_ticks = SDL_CALL SDL_GetTicks();
662  uint32 last_cur_ticks = cur_ticks;
663  uint32 next_tick = cur_ticks + MILLISECONDS_PER_TICK;
664  uint32 mod;
665  int numkeys;
666  Uint8 *keys;
667 
668  CheckPaletteAnim();
669 
670  if (_draw_threaded) {
671  /* Initialise the mutex first, because that's the thing we *need*
672  * directly in the newly created thread. */
673  _draw_mutex = ThreadMutex::New();
674  if (_draw_mutex == NULL) {
675  _draw_threaded = false;
676  } else {
677  _draw_mutex->BeginCritical();
678  _draw_continue = true;
679 
680  _draw_threaded = ThreadObject::New(&DrawSurfaceToScreenThread, NULL, &_draw_thread, "ottd:draw-sdl");
681 
682  /* Free the mutex if we won't be able to use it. */
683  if (!_draw_threaded) {
684  _draw_mutex->EndCritical();
685  delete _draw_mutex;
686  _draw_mutex = NULL;
687  } else {
688  /* Wait till the draw mutex has started itself. */
689  _draw_mutex->WaitForSignal();
690  }
691  }
692  }
693 
694  DEBUG(driver, 1, "SDL: using %sthreads", _draw_threaded ? "" : "no ");
695 
696  for (;;) {
697  uint32 prev_cur_ticks = cur_ticks; // to check for wrapping
698  InteractiveRandom(); // randomness
699 
700  while (PollEvent() == -1) {}
701  if (_exit_game) break;
702 
703  mod = SDL_CALL SDL_GetModState();
704 #if SDL_VERSION_ATLEAST(1, 3, 0)
705  keys = SDL_CALL SDL_GetKeyboardState(&numkeys);
706 #else
707  keys = SDL_CALL SDL_GetKeyState(&numkeys);
708 #endif
709 #if defined(_DEBUG)
710  if (_shift_pressed)
711 #else
712  /* Speedup when pressing tab, except when using ALT+TAB
713  * to switch to another application */
714 #if SDL_VERSION_ATLEAST(1, 3, 0)
715  if (keys[SDL_SCANCODE_TAB] && (mod & KMOD_ALT) == 0)
716 #else
717  if (keys[SDLK_TAB] && (mod & KMOD_ALT) == 0)
718 #endif /* SDL_VERSION_ATLEAST(1, 3, 0) */
719 #endif /* defined(_DEBUG) */
720  {
721  if (!_networking && _game_mode != GM_MENU) _fast_forward |= 2;
722  } else if (_fast_forward & 2) {
723  _fast_forward = 0;
724  }
725 
726  cur_ticks = SDL_CALL SDL_GetTicks();
727  if (cur_ticks >= next_tick || (_fast_forward && !_pause_mode) || cur_ticks < prev_cur_ticks) {
728  _realtime_tick += cur_ticks - last_cur_ticks;
729  last_cur_ticks = cur_ticks;
730  next_tick = cur_ticks + MILLISECONDS_PER_TICK;
731 
732  bool old_ctrl_pressed = _ctrl_pressed;
733 
734  _ctrl_pressed = !!(mod & KMOD_CTRL);
735  _shift_pressed = !!(mod & KMOD_SHIFT);
736 
737  /* determine which directional keys are down */
738  _dirkeys =
739 #if SDL_VERSION_ATLEAST(1, 3, 0)
740  (keys[SDL_SCANCODE_LEFT] ? 1 : 0) |
741  (keys[SDL_SCANCODE_UP] ? 2 : 0) |
742  (keys[SDL_SCANCODE_RIGHT] ? 4 : 0) |
743  (keys[SDL_SCANCODE_DOWN] ? 8 : 0);
744 #else
745  (keys[SDLK_LEFT] ? 1 : 0) |
746  (keys[SDLK_UP] ? 2 : 0) |
747  (keys[SDLK_RIGHT] ? 4 : 0) |
748  (keys[SDLK_DOWN] ? 8 : 0);
749 #endif
750  if (old_ctrl_pressed != _ctrl_pressed) HandleCtrlChanged();
751 
752  /* The gameloop is the part that can run asynchronously. The rest
753  * except sleeping can't. */
754  if (_draw_mutex != NULL) _draw_mutex->EndCritical();
755 
756  GameLoop();
757 
758  if (_draw_mutex != NULL) _draw_mutex->BeginCritical();
759 
760  UpdateWindows();
761  _local_palette = _cur_palette;
762  } else {
763  /* Release the thread while sleeping */
764  if (_draw_mutex != NULL) _draw_mutex->EndCritical();
765  CSleep(1);
766  if (_draw_mutex != NULL) _draw_mutex->BeginCritical();
767 
769  DrawMouseCursor();
770  }
771 
772  /* End of the critical part. */
773  if (_draw_mutex != NULL && !HasModalProgress()) {
774  _draw_mutex->SendSignal();
775  } else {
776  /* Oh, we didn't have threads, then just draw unthreaded */
777  CheckPaletteAnim();
778  DrawSurfaceToScreen();
779  }
780  }
781 
782  if (_draw_mutex != NULL) {
783  _draw_continue = false;
784  /* Sending signal if there is no thread blocked
785  * is very valid and results in noop */
786  _draw_mutex->SendSignal();
787  _draw_mutex->EndCritical();
788  _draw_thread->Join();
789 
790  delete _draw_mutex;
791  delete _draw_thread;
792 
793  _draw_mutex = NULL;
794  _draw_thread = NULL;
795  }
796 }
797 
799 {
800  if (_draw_mutex != NULL) _draw_mutex->BeginCritical(true);
801  bool ret = CreateMainSurface(w, h);
802  if (_draw_mutex != NULL) _draw_mutex->EndCritical(true);
803  return ret;
804 }
805 
807 {
808  if (_draw_mutex != NULL) _draw_mutex->BeginCritical(true);
809  _fullscreen = fullscreen;
810  GetVideoModes(); // get the list of available video modes
811  bool ret = _num_resolutions != 0 && CreateMainSurface(_cur_resolution.width, _cur_resolution.height);
812 
813  if (!ret) {
814  /* switching resolution failed, put back full_screen to original status */
815  _fullscreen ^= true;
816  }
817 
818  if (_draw_mutex != NULL) _draw_mutex->EndCritical(true);
819  return ret;
820 }
821 
823 {
824  return CreateMainSurface(_screen.width, _screen.height);
825 }
826 
828 {
829  if (_draw_mutex != NULL) _draw_mutex->BeginCritical(true);
830 }
831 
833 {
834  if (_draw_mutex != NULL) _draw_mutex->EndCritical(true);
835 }
836 
837 #endif /* WITH_SDL */
const char * GetDriverParam(const char *const *parm, const char *name)
Get a string parameter the list of parameters.
Definition: driver.cpp:40
bool _networking
are we in networking mode?
Definition: network.cpp:56
uint32 _realtime_tick
The real time in the game.
Definition: debug.cpp:52
Point pos
logical mouse position
Definition: gfx_type.h:119
Information about the currently used palette.
Definition: gfx_type.h:309
, Comma
Definition: gfx_type.h:104
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:409
bool _right_button_down
Is right mouse button pressed?
Definition: gfx.cpp:41
Colour palette[256]
Current palette. Entry 0 has to be always fully transparent!
Definition: gfx_type.h:310
const char * Start(const char *const *param)
Start this driver.
Definition: sdl_v.cpp:624
void MainLoop()
Perform the actual drawing.
Definition: sdl_v.cpp:659
bool ChangeResolution(int w, int h)
Change the resolution of the window.
Definition: sdl_v.cpp:798
Cross-platform Mutex.
Definition: thread.h:56
= Equals
Definition: gfx_type.h:99
Base of the SDL video driver.
Dimension _cur_resolution
The current resolution.
Definition: driver.cpp:24
static volatile bool _draw_continue
Should we keep continue drawing?
Definition: sdl_v.cpp:45
int _num_resolutions
The number of resolutions.
Definition: driver.cpp:22
#define lastof(x)
Get the last element of an fixed size array.
Definition: depend.cpp:50
No palette animation.
Definition: base.hpp:52
How all blitters should look like.
Definition: base.hpp:30
RAII class for measuring simple elements of performance.
Subdirectory for all base data (base sets, intro game)
Definition: fileio_type.h:118
static T max(const T a, const T b)
Returns the maximum of two values.
Definition: math_func.hpp:26
virtual void EndCritical(bool allow_recursive=false)=0
End of the critical section.
virtual void PostResize()
Post resize event.
Definition: base.hpp:203
Palette animation should be done by video backend (8bpp only!)
Definition: base.hpp:53
virtual void SendSignal()=0
Send a signal and wake the &#39;thread&#39; that was waiting for it.
bool _left_button_clicked
Is left mouse button clicked?
Definition: gfx.cpp:40
bool _ctrl_pressed
Is Ctrl pressed?
Definition: gfx.cpp:36
const char * SdlOpen(uint32 x)
Open the SDL library.
Definition: sdl.cpp:88
&#39; Single quote
Definition: gfx_type.h:103
bool _right_button_clicked
Is right mouse button clicked?
Definition: gfx.cpp:42
The blitter takes care of the palette animation.
Definition: base.hpp:54
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:356
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:39
[ Left square bracket
Definition: gfx_type.h:100
] Right square bracket
Definition: gfx_type.h:102
bool ToggleFullscreen(bool fullscreen)
Change the full screen setting.
Definition: sdl_v.cpp:806
\ Backslash
Definition: gfx_type.h:101
void CDECL usererror(const char *s,...)
Error handling for fatal user errors.
Definition: openttd.cpp:91
int wheel
mouse wheel movement
Definition: gfx_type.h:121
bool UpdateCursorPosition(int x, int y, bool queued_warp)
Update cursor position on mouse movement.
Definition: gfx.cpp:1648
/ Forward slash
Definition: gfx_type.h:97
static const uint MILLISECONDS_PER_TICK
The number of milliseconds per game tick.
Definition: gfx_type.h:306
static ThreadMutex * New()
Create a new mutex.
Definition: thread_none.cpp:32
void HandleKeypress(uint keycode, WChar key)
Handle keyboard input.
Definition: window.cpp:2652
byte _dirkeys
1 = left, 2 = up, 4 = right, 8 = down
Definition: gfx.cpp:32
static ThreadObject * _draw_thread
Thread used to &#39;draw&#39; to the screen, i.e.
Definition: sdl_v.cpp:41
void HandleMouseEvents()
Handle a mouse event from the video driver.
Definition: window.cpp:2959
#define lengthof(x)
Return the length of an fixed size array.
Definition: depend.cpp:42
PauseModeByte _pause_mode
The current pause mode.
Definition: gfx.cpp:48
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
Definition: factory.hpp:147
int first_dirty
The first dirty element.
Definition: gfx_type.h:311
; Semicolon
Definition: gfx_type.h:98
Palette _cur_palette
Current palette.
Definition: gfx.cpp:49
bool _shift_pressed
Is Shift pressed?
Definition: gfx.cpp:37
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:36
static ThreadMutex * _draw_mutex
Mutex to keep the access to the shared memory controlled.
Definition: sdl_v.cpp:43
Dimension _resolutions[32]
List of resolutions.
Definition: driver.cpp:23
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:2709
virtual void Join()=0
Join this thread.
void Stop()
Stop this driver.
Definition: sdl_v.cpp:654
Speed of painting drawn video buffer.
void ReleaseBlitterLock()
Release any lock(s) required to be held when changing blitters.
Definition: sdl_v.cpp:832
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:77
#define endof(x)
Get the end element of an fixed size array.
Definition: stdafx.h:403
bool in_window
mouse inside this window, determines drawing logic
Definition: gfx_type.h:143
bool AfterBlitterChange()
Callback invoked after the blitter was changed.
Definition: sdl_v.cpp:822
virtual void WaitForSignal()=0
Wait for a signal to be send.
void AcquireBlitterLock()
Acquire any lock(s) required to be held when changing blitters.
Definition: sdl_v.cpp:827
void SdlClose(uint32 x)
Close the SDL library.
Definition: sdl.cpp:109
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.
int GetDriverParamInt(const char *const *parm, const char *name, int def)
Get an integer parameter the list of parameters.
Definition: driver.cpp:76
bool _rightclick_emulate
Whether right clicking is emulated.
Definition: driver.cpp:25
void GameSizeChanged()
Size of the application screen changed.
Definition: main_gui.cpp:596
. Period
Definition: gfx_type.h:105
virtual void BeginCritical(bool allow_recursive=false)=0
Begin the critical section.
void MakeDirty(int left, int top, int width, int height)
Mark a particular area dirty.
Definition: sdl_v.cpp:54
virtual bool Exit()=0
Exit this thread.
Factory for the SDL video driver.
Definition: sdl_v.h:48
int count_dirty
The number of dirty elements.
Definition: gfx_type.h:312
static T Delta(const T a, const T b)
Returns the (absolute) difference between two (scalar) variables.
Definition: math_func.hpp:232
uint32 WChar
Type for wide characters, i.e.
Definition: string_type.h:35
A Thread Object which works on all our supported OSes.
Definition: thread.h:24
static bool New(OTTDThreadFunc proc, void *param, ThreadObject **thread=NULL, const char *name=NULL)
Create a thread; proc will be called as first function inside the thread, with optional params...
Dimensions (a width and height) of a rectangle in 2D.
Full 8bpp support by OS and hardware.
Definition: gfx_type.h:319
static bool HasModalProgress()
Check if we are currently in a modal progress state.
Definition: progress.h:23
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition: gfx.cpp:1463
void UpdateWindows()
Update the continuously changing contents of the windows, such as the viewports.
Definition: window.cpp:3110