sdl_v.cpp

Go to the documentation of this file.
00001 /* $Id$ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * 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.
00006  * 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.
00007  * 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/>.
00008  */
00009 
00012 #ifdef WITH_SDL
00013 
00014 #include "../stdafx.h"
00015 #include "../openttd.h"
00016 #include "../gfx_func.h"
00017 #include "../sdl.h"
00018 #include "../rev.h"
00019 #include "../blitter/factory.hpp"
00020 #include "../network/network.h"
00021 #include "../thread/thread.h"
00022 #include "../progress.h"
00023 #include "../core/random_func.hpp"
00024 #include "../core/math_func.hpp"
00025 #include "../fileio_func.h"
00026 #include "sdl_v.h"
00027 #include <SDL.h>
00028 
00029 static FVideoDriver_SDL iFVideoDriver_SDL;
00030 
00031 static SDL_Surface *_sdl_screen;
00032 static SDL_Surface *_sdl_realscreen;
00033 static bool _all_modes;
00034 
00036 static bool _draw_threaded;
00038 static ThreadObject *_draw_thread = NULL;
00040 static ThreadMutex *_draw_mutex = NULL;
00042 static volatile bool _draw_continue;
00043 static Palette _local_palette;
00044 
00045 #define MAX_DIRTY_RECTS 100
00046 static SDL_Rect _dirty_rects[MAX_DIRTY_RECTS];
00047 static int _num_dirty_rects;
00048 static int _use_hwpalette;
00049 static int _requested_hwpalette; /* Did we request a HWPALETTE for the current video mode? */
00050 
00051 void VideoDriver_SDL::MakeDirty(int left, int top, int width, int height)
00052 {
00053   if (_num_dirty_rects < MAX_DIRTY_RECTS) {
00054     _dirty_rects[_num_dirty_rects].x = left;
00055     _dirty_rects[_num_dirty_rects].y = top;
00056     _dirty_rects[_num_dirty_rects].w = width;
00057     _dirty_rects[_num_dirty_rects].h = height;
00058   }
00059   _num_dirty_rects++;
00060 }
00061 
00062 static void UpdatePalette(bool init = false)
00063 {
00064   SDL_Color pal[256];
00065 
00066   for (int i = 0; i != _local_palette.count_dirty; i++) {
00067     pal[i].r = _local_palette.palette[_local_palette.first_dirty + i].r;
00068     pal[i].g = _local_palette.palette[_local_palette.first_dirty + i].g;
00069     pal[i].b = _local_palette.palette[_local_palette.first_dirty + i].b;
00070     pal[i].unused = 0;
00071   }
00072 
00073   SDL_CALL SDL_SetColors(_sdl_screen, pal, _local_palette.first_dirty, _local_palette.count_dirty);
00074 
00075   if (_sdl_screen != _sdl_realscreen && init) {
00076     /* When using a shadow surface, also set our palette on the real screen. This lets SDL
00077      * allocate as much colors (or approximations) as
00078      * possible, instead of using only the default SDL
00079      * palette. This allows us to get more colors exactly
00080      * right and might allow using better approximations for
00081      * other colors.
00082      *
00083      * Note that colors allocations are tried in-order, so
00084      * this favors colors further up into the palette. Also
00085      * note that if two colors from the same animation
00086      * sequence are approximated using the same color, that
00087      * animation will stop working.
00088      *
00089      * Since changing the system palette causes the colours
00090      * to change right away, and allocations might
00091      * drastically change, we can't use this for animation,
00092      * since that could cause weird coloring between the
00093      * palette change and the blitting below, so we only set
00094      * the real palette during initialisation.
00095      */
00096     SDL_CALL SDL_SetColors(_sdl_realscreen, pal, _local_palette.first_dirty, _local_palette.count_dirty);
00097   }
00098 
00099   if (_sdl_screen != _sdl_realscreen && !init) {
00100     /* We're not using real hardware palette, but are letting SDL
00101      * approximate the palette during shadow -> screen copy. To
00102      * change the palette, we need to recopy the entire screen.
00103      *
00104      * Note that this operation can slow down the rendering
00105      * considerably, especially since changing the shadow
00106      * palette will need the next blit to re-detect the
00107      * best mapping of shadow palette colors to real palette
00108      * colors from scratch.
00109      */
00110     SDL_CALL SDL_BlitSurface(_sdl_screen, NULL, _sdl_realscreen, NULL);
00111     SDL_CALL SDL_UpdateRect(_sdl_realscreen, 0, 0, 0, 0);
00112   }
00113 }
00114 
00115 static void InitPalette()
00116 {
00117   _local_palette = _cur_palette;
00118   _local_palette.first_dirty = 0;
00119   _local_palette.count_dirty = 256;
00120   UpdatePalette(true);
00121 }
00122 
00123 static void CheckPaletteAnim()
00124 {
00125   if (_cur_palette.count_dirty != 0) {
00126     Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
00127 
00128     switch (blitter->UsePaletteAnimation()) {
00129       case Blitter::PALETTE_ANIMATION_VIDEO_BACKEND:
00130         UpdatePalette();
00131         break;
00132 
00133       case Blitter::PALETTE_ANIMATION_BLITTER:
00134         blitter->PaletteAnimate(_local_palette);
00135         break;
00136 
00137       case Blitter::PALETTE_ANIMATION_NONE:
00138         break;
00139 
00140       default:
00141         NOT_REACHED();
00142     }
00143     _cur_palette.count_dirty = 0;
00144   }
00145 }
00146 
00147 static void DrawSurfaceToScreen()
00148 {
00149   int n = _num_dirty_rects;
00150   if (n == 0) return;
00151 
00152   _num_dirty_rects = 0;
00153   if (n > MAX_DIRTY_RECTS) {
00154     if (_sdl_screen != _sdl_realscreen) {
00155       SDL_CALL SDL_BlitSurface(_sdl_screen, NULL, _sdl_realscreen, NULL);
00156     }
00157     SDL_CALL SDL_UpdateRect(_sdl_realscreen, 0, 0, 0, 0);
00158   } else {
00159     if (_sdl_screen != _sdl_realscreen) {
00160       for (int i = 0; i < n; i++) {
00161         SDL_CALL SDL_BlitSurface(_sdl_screen, &_dirty_rects[i], _sdl_realscreen, &_dirty_rects[i]);
00162       }
00163     }
00164     SDL_CALL SDL_UpdateRects(_sdl_realscreen, n, _dirty_rects);
00165   }
00166 }
00167 
00168 static void DrawSurfaceToScreenThread(void *)
00169 {
00170   /* First tell the main thread we're started */
00171   _draw_mutex->BeginCritical();
00172   _draw_mutex->SendSignal();
00173 
00174   /* Now wait for the first thing to draw! */
00175   _draw_mutex->WaitForSignal();
00176 
00177   while (_draw_continue) {
00178     CheckPaletteAnim();
00179     /* Then just draw and wait till we stop */
00180     DrawSurfaceToScreen();
00181     _draw_mutex->WaitForSignal();
00182   }
00183 
00184   _draw_mutex->EndCritical();
00185   _draw_thread->Exit();
00186 }
00187 
00188 static const Dimension _default_resolutions[] = {
00189   { 640,  480},
00190   { 800,  600},
00191   {1024,  768},
00192   {1152,  864},
00193   {1280,  800},
00194   {1280,  960},
00195   {1280, 1024},
00196   {1400, 1050},
00197   {1600, 1200},
00198   {1680, 1050},
00199   {1920, 1200}
00200 };
00201 
00202 static void GetVideoModes()
00203 {
00204   SDL_Rect **modes = SDL_CALL SDL_ListModes(NULL, SDL_SWSURFACE | SDL_FULLSCREEN);
00205   if (modes == NULL) usererror("sdl: no modes available");
00206 
00207   _all_modes = (SDL_CALL SDL_ListModes(NULL, SDL_SWSURFACE | (_fullscreen ? SDL_FULLSCREEN : 0)) == (void*)-1);
00208   if (modes == (void*)-1) {
00209     int n = 0;
00210     for (uint i = 0; i < lengthof(_default_resolutions); i++) {
00211       if (SDL_CALL SDL_VideoModeOK(_default_resolutions[i].width, _default_resolutions[i].height, 8, SDL_FULLSCREEN) != 0) {
00212         _resolutions[n] = _default_resolutions[i];
00213         if (++n == lengthof(_resolutions)) break;
00214       }
00215     }
00216     _num_resolutions = n;
00217   } else {
00218     int n = 0;
00219     for (int i = 0; modes[i]; i++) {
00220       uint w = modes[i]->w;
00221       uint h = modes[i]->h;
00222       int j;
00223       for (j = 0; j < n; j++) {
00224         if (_resolutions[j].width == w && _resolutions[j].height == h) break;
00225       }
00226 
00227       if (j == n) {
00228         _resolutions[j].width  = w;
00229         _resolutions[j].height = h;
00230         if (++n == lengthof(_resolutions)) break;
00231       }
00232     }
00233     _num_resolutions = n;
00234     SortResolutions(_num_resolutions);
00235   }
00236 }
00237 
00238 static void GetAvailableVideoMode(uint *w, uint *h)
00239 {
00240   /* All modes available? */
00241   if (_all_modes || _num_resolutions == 0) return;
00242 
00243   /* Is the wanted mode among the available modes? */
00244   for (int i = 0; i != _num_resolutions; i++) {
00245     if (*w == _resolutions[i].width && *h == _resolutions[i].height) return;
00246   }
00247 
00248   /* Use the closest possible resolution */
00249   int best = 0;
00250   uint delta = Delta(_resolutions[0].width, *w) * Delta(_resolutions[0].height, *h);
00251   for (int i = 1; i != _num_resolutions; ++i) {
00252     uint newdelta = Delta(_resolutions[i].width, *w) * Delta(_resolutions[i].height, *h);
00253     if (newdelta < delta) {
00254       best = i;
00255       delta = newdelta;
00256     }
00257   }
00258   *w = _resolutions[best].width;
00259   *h = _resolutions[best].height;
00260 }
00261 
00262 #ifdef WIN32
00263 /* Let's redefine the LoadBMP macro with because we are dynamically
00264  * loading SDL and need to 'SDL_CALL' all functions */
00265 #undef SDL_LoadBMP
00266 #define SDL_LoadBMP(file) SDL_LoadBMP_RW(SDL_CALL SDL_RWFromFile(file, "rb"), 1)
00267 #endif
00268 
00269 bool VideoDriver_SDL::CreateMainSurface(uint w, uint h)
00270 {
00271   SDL_Surface *newscreen, *icon;
00272   char caption[50];
00273   int bpp = BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth();
00274   bool want_hwpalette;
00275 
00276   GetAvailableVideoMode(&w, &h);
00277 
00278   DEBUG(driver, 1, "SDL: using mode %ux%ux%d", w, h, bpp);
00279 
00280   if (bpp == 0) usererror("Can't use a blitter that blits 0 bpp for normal visuals");
00281 
00282   char icon_path[MAX_PATH];
00283   if (FioFindFullPath(icon_path, lengthof(icon_path), BASESET_DIR, "openttd.32.bmp") != NULL) {
00284     /* Give the application an icon */
00285     icon = SDL_CALL SDL_LoadBMP(icon_path);
00286     if (icon != NULL) {
00287       /* Get the colourkey, which will be magenta */
00288       uint32 rgbmap = SDL_CALL SDL_MapRGB(icon->format, 255, 0, 255);
00289 
00290       SDL_CALL SDL_SetColorKey(icon, SDL_SRCCOLORKEY, rgbmap);
00291       SDL_CALL SDL_WM_SetIcon(icon, NULL);
00292       SDL_CALL SDL_FreeSurface(icon);
00293     }
00294   }
00295 
00296   if (_use_hwpalette == 2) {
00297     /* Default is to autodetect when to use SDL_HWPALETTE.
00298      * In this case, SDL_HWPALETTE is only used for 8bpp
00299      * blitters in fullscreen.
00300      *
00301      * When using an 8bpp blitter on a 8bpp system in
00302      * windowed mode with SDL_HWPALETTE, OpenTTD will claim
00303      * the system palette, making all other applications
00304      * get the wrong colours. In this case, we're better of
00305      * trying to approximate the colors we need using system
00306      * colors, using a shadow surface (see below).
00307      *
00308      * On a 32bpp system, SDL_HWPALETTE is ignored, so it
00309      * doesn't matter what we do.
00310      *
00311      * When using a 32bpp blitter on a 8bpp system, setting
00312      * SDL_HWPALETTE messes up rendering (at least on X11),
00313      * so we don't do that. In this case, SDL takes care of
00314      * color approximation using its own shadow surface
00315      * (which we can't force in 8bpp on 8bpp mode,
00316      * unfortunately).
00317      */
00318     want_hwpalette = (bpp == 8 && _fullscreen);
00319   } else {
00320     /* User specified a value manually */
00321     want_hwpalette = _use_hwpalette;
00322   }
00323 
00324   if (want_hwpalette) DEBUG(driver, 1, "SDL: requesting hardware palete");
00325 
00326   /* Free any previously allocated shadow surface */
00327   if (_sdl_screen != NULL && _sdl_screen != _sdl_realscreen) SDL_CALL SDL_FreeSurface(_sdl_screen);
00328 
00329   if (_sdl_realscreen != NULL) {
00330     if (_requested_hwpalette != want_hwpalette) {
00331       /* SDL (at least the X11 driver), reuses the
00332        * same window and palette settings when the bpp
00333        * (and a few flags) are the same. Since we need
00334        * to hwpalette value to change (in particular
00335        * when switching between fullscreen and
00336        * windowed), we restart the entire video
00337        * subsystem to force creating a new window.
00338        */
00339       DEBUG(driver, 0, "SDL: Restarting SDL video subsystem, to force hwpalette change");
00340       SDL_CALL SDL_QuitSubSystem(SDL_INIT_VIDEO);
00341       SDL_CALL SDL_InitSubSystem(SDL_INIT_VIDEO);
00342       ClaimMousePointer();
00343       SetupKeyboard();
00344     }
00345   }
00346   /* Remember if we wanted a hwpalette. We can't reliably query
00347    * SDL for the SDL_HWPALETTE flag, since it might get set even
00348    * though we didn't ask for it (when SDL creates a shadow
00349    * surface, for example). */
00350   _requested_hwpalette = want_hwpalette;
00351 
00352   /* DO NOT CHANGE TO HWSURFACE, IT DOES NOT WORK */
00353   newscreen = SDL_CALL SDL_SetVideoMode(w, h, bpp, SDL_SWSURFACE | (want_hwpalette ? SDL_HWPALETTE : 0) | (_fullscreen ? SDL_FULLSCREEN : SDL_RESIZABLE));
00354   if (newscreen == NULL) {
00355     DEBUG(driver, 0, "SDL: Couldn't allocate a window to draw on");
00356     return false;
00357   }
00358   _sdl_realscreen = newscreen;
00359 
00360   if (bpp == 8 && (_sdl_realscreen->flags & SDL_HWPALETTE) != SDL_HWPALETTE) {
00361     /* Using an 8bpp blitter, if we didn't get a hardware
00362      * palette (most likely because we didn't request one,
00363      * see above), we'll have to set up a shadow surface to
00364      * render on.
00365      *
00366      * Our palette will be applied to this shadow surface,
00367      * while the real screen surface will use the shared
00368      * system palette (which will partly contain our colors,
00369      * but most likely will not have enough free color cells
00370      * for all of our colors). SDL can use these two
00371      * palettes at blit time to approximate colors used in
00372      * the shadow surface using system colors automatically.
00373      *
00374      * Note that when using an 8bpp blitter on a 32bpp
00375      * system, SDL will create an internal shadow surface.
00376      * This shadow surface will have SDL_HWPALLETE set, so
00377      * we won't create a second shadow surface in this case.
00378      */
00379     DEBUG(driver, 1, "SDL: using shadow surface");
00380     newscreen = SDL_CALL SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, bpp, 0, 0, 0, 0);
00381     if (newscreen == NULL) {
00382       DEBUG(driver, 0, "SDL: Couldn't allocate a shadow surface to draw on");
00383       return false;
00384     }
00385   }
00386 
00387   /* Delay drawing for this cycle; the next cycle will redraw the whole screen */
00388   _num_dirty_rects = 0;
00389 
00390   _screen.width = newscreen->w;
00391   _screen.height = newscreen->h;
00392   _screen.pitch = newscreen->pitch / (bpp / 8);
00393   _screen.dst_ptr = newscreen->pixels;
00394   _sdl_screen = newscreen;
00395 
00396   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
00397   blitter->PostResize();
00398 
00399   InitPalette();
00400   switch (blitter->UsePaletteAnimation()) {
00401     case Blitter::PALETTE_ANIMATION_NONE:
00402     case Blitter::PALETTE_ANIMATION_VIDEO_BACKEND:
00403       UpdatePalette();
00404       break;
00405 
00406     case Blitter::PALETTE_ANIMATION_BLITTER:
00407       if (_video_driver != NULL) blitter->PaletteAnimate(_local_palette);
00408       break;
00409 
00410     default:
00411       NOT_REACHED();
00412   }
00413 
00414   snprintf(caption, sizeof(caption), "OpenTTD %s", _openttd_revision);
00415   SDL_CALL SDL_WM_SetCaption(caption, caption);
00416 
00417   GameSizeChanged();
00418 
00419   return true;
00420 }
00421 
00422 bool VideoDriver_SDL::ClaimMousePointer()
00423 {
00424   SDL_CALL SDL_ShowCursor(0);
00425   return true;
00426 }
00427 
00428 struct VkMapping {
00429 #if SDL_VERSION_ATLEAST(1, 3, 0)
00430   SDL_Keycode vk_from;
00431 #else
00432   uint16 vk_from;
00433 #endif
00434   byte vk_count;
00435   byte map_to;
00436 };
00437 
00438 #define AS(x, z) {x, 0, z}
00439 #define AM(x, y, z, w) {x, (byte)(y - x), z}
00440 
00441 static const VkMapping _vk_mapping[] = {
00442   /* Pageup stuff + up/down */
00443   AM(SDLK_PAGEUP, SDLK_PAGEDOWN, WKC_PAGEUP, WKC_PAGEDOWN),
00444   AS(SDLK_UP,     WKC_UP),
00445   AS(SDLK_DOWN,   WKC_DOWN),
00446   AS(SDLK_LEFT,   WKC_LEFT),
00447   AS(SDLK_RIGHT,  WKC_RIGHT),
00448 
00449   AS(SDLK_HOME,   WKC_HOME),
00450   AS(SDLK_END,    WKC_END),
00451 
00452   AS(SDLK_INSERT, WKC_INSERT),
00453   AS(SDLK_DELETE, WKC_DELETE),
00454 
00455   /* Map letters & digits */
00456   AM(SDLK_a, SDLK_z, 'A', 'Z'),
00457   AM(SDLK_0, SDLK_9, '0', '9'),
00458 
00459   AS(SDLK_ESCAPE,    WKC_ESC),
00460   AS(SDLK_PAUSE,     WKC_PAUSE),
00461   AS(SDLK_BACKSPACE, WKC_BACKSPACE),
00462 
00463   AS(SDLK_SPACE,     WKC_SPACE),
00464   AS(SDLK_RETURN,    WKC_RETURN),
00465   AS(SDLK_TAB,       WKC_TAB),
00466 
00467   /* Function keys */
00468   AM(SDLK_F1, SDLK_F12, WKC_F1, WKC_F12),
00469 
00470   /* Numeric part. */
00471   AM(SDLK_KP0, SDLK_KP9, '0', '9'),
00472   AS(SDLK_KP_DIVIDE,   WKC_NUM_DIV),
00473   AS(SDLK_KP_MULTIPLY, WKC_NUM_MUL),
00474   AS(SDLK_KP_MINUS,    WKC_NUM_MINUS),
00475   AS(SDLK_KP_PLUS,     WKC_NUM_PLUS),
00476   AS(SDLK_KP_ENTER,    WKC_NUM_ENTER),
00477   AS(SDLK_KP_PERIOD,   WKC_NUM_DECIMAL),
00478 
00479   /* Other non-letter keys */
00480   AS(SDLK_SLASH,        WKC_SLASH),
00481   AS(SDLK_SEMICOLON,    WKC_SEMICOLON),
00482   AS(SDLK_EQUALS,       WKC_EQUALS),
00483   AS(SDLK_LEFTBRACKET,  WKC_L_BRACKET),
00484   AS(SDLK_BACKSLASH,    WKC_BACKSLASH),
00485   AS(SDLK_RIGHTBRACKET, WKC_R_BRACKET),
00486 
00487   AS(SDLK_QUOTE,   WKC_SINGLEQUOTE),
00488   AS(SDLK_COMMA,   WKC_COMMA),
00489   AS(SDLK_MINUS,   WKC_MINUS),
00490   AS(SDLK_PERIOD,  WKC_PERIOD)
00491 };
00492 
00493 static uint32 ConvertSdlKeyIntoMy(SDL_keysym *sym)
00494 {
00495   const VkMapping *map;
00496   uint key = 0;
00497 
00498   for (map = _vk_mapping; map != endof(_vk_mapping); ++map) {
00499     if ((uint)(sym->sym - map->vk_from) <= map->vk_count) {
00500       key = sym->sym - map->vk_from + map->map_to;
00501       break;
00502     }
00503   }
00504 
00505   /* check scancode for BACKQUOTE key, because we want the key left of "1", not anything else (on non-US keyboards) */
00506 #if defined(WIN32) || defined(__OS2__)
00507   if (sym->scancode == 41) key = WKC_BACKQUOTE;
00508 #elif defined(__APPLE__)
00509   if (sym->scancode == 10) key = WKC_BACKQUOTE;
00510 #elif defined(__MORPHOS__)
00511   if (sym->scancode == 0)  key = WKC_BACKQUOTE;  // yes, that key is code '0' under MorphOS :)
00512 #elif defined(__BEOS__)
00513   if (sym->scancode == 17) key = WKC_BACKQUOTE;
00514 #elif defined(__SVR4) && defined(__sun)
00515   if (sym->scancode == 60) key = WKC_BACKQUOTE;
00516   if (sym->scancode == 49) key = WKC_BACKSPACE;
00517 #elif defined(__sgi__)
00518   if (sym->scancode == 22) key = WKC_BACKQUOTE;
00519 #else
00520   if (sym->scancode == 49) key = WKC_BACKQUOTE;
00521 #endif
00522 
00523   /* META are the command keys on mac */
00524   if (sym->mod & KMOD_META)  key |= WKC_META;
00525   if (sym->mod & KMOD_SHIFT) key |= WKC_SHIFT;
00526   if (sym->mod & KMOD_CTRL)  key |= WKC_CTRL;
00527   if (sym->mod & KMOD_ALT)   key |= WKC_ALT;
00528 
00529   return (key << 16) + sym->unicode;
00530 }
00531 
00532 int VideoDriver_SDL::PollEvent()
00533 {
00534   SDL_Event ev;
00535 
00536   if (!SDL_CALL SDL_PollEvent(&ev)) return -2;
00537 
00538   switch (ev.type) {
00539     case SDL_MOUSEMOTION:
00540       if (_cursor.fix_at) {
00541         int dx = ev.motion.x - _cursor.pos.x;
00542         int dy = ev.motion.y - _cursor.pos.y;
00543         if (dx != 0 || dy != 0) {
00544           _cursor.delta.x = dx;
00545           _cursor.delta.y = dy;
00546           SDL_CALL SDL_WarpMouse(_cursor.pos.x, _cursor.pos.y);
00547         }
00548       } else {
00549         _cursor.delta.x = ev.motion.x - _cursor.pos.x;
00550         _cursor.delta.y = ev.motion.y - _cursor.pos.y;
00551         _cursor.pos.x = ev.motion.x;
00552         _cursor.pos.y = ev.motion.y;
00553         _cursor.dirty = true;
00554       }
00555       HandleMouseEvents();
00556       break;
00557 
00558     case SDL_MOUSEBUTTONDOWN:
00559       if (_rightclick_emulate && SDL_CALL SDL_GetModState() & KMOD_CTRL) {
00560         ev.button.button = SDL_BUTTON_RIGHT;
00561       }
00562 
00563       switch (ev.button.button) {
00564         case SDL_BUTTON_LEFT:
00565           _left_button_down = true;
00566           break;
00567 
00568         case SDL_BUTTON_RIGHT:
00569           _right_button_down = true;
00570           _right_button_clicked = true;
00571           break;
00572 
00573         case SDL_BUTTON_WHEELUP:   _cursor.wheel--; break;
00574         case SDL_BUTTON_WHEELDOWN: _cursor.wheel++; break;
00575 
00576         default: break;
00577       }
00578       HandleMouseEvents();
00579       break;
00580 
00581     case SDL_MOUSEBUTTONUP:
00582       if (_rightclick_emulate) {
00583         _right_button_down = false;
00584         _left_button_down = false;
00585         _left_button_clicked = false;
00586       } else if (ev.button.button == SDL_BUTTON_LEFT) {
00587         _left_button_down = false;
00588         _left_button_clicked = false;
00589       } else if (ev.button.button == SDL_BUTTON_RIGHT) {
00590         _right_button_down = false;
00591       }
00592       HandleMouseEvents();
00593       break;
00594 
00595     case SDL_ACTIVEEVENT:
00596       if (!(ev.active.state & SDL_APPMOUSEFOCUS)) break;
00597 
00598       if (ev.active.gain) { // mouse entered the window, enable cursor
00599         _cursor.in_window = true;
00600       } else {
00601         UndrawMouseCursor(); // mouse left the window, undraw cursor
00602         _cursor.in_window = false;
00603       }
00604       break;
00605 
00606     case SDL_QUIT:
00607       HandleExitGameRequest();
00608       break;
00609 
00610     case SDL_KEYDOWN: // Toggle full-screen on ALT + ENTER/F
00611       if ((ev.key.keysym.mod & (KMOD_ALT | KMOD_META)) &&
00612           (ev.key.keysym.sym == SDLK_RETURN || ev.key.keysym.sym == SDLK_f)) {
00613         ToggleFullScreen(!_fullscreen);
00614       } else {
00615         HandleKeypress(ConvertSdlKeyIntoMy(&ev.key.keysym));
00616       }
00617       break;
00618 
00619     case SDL_VIDEORESIZE: {
00620       int w = max(ev.resize.w, 64);
00621       int h = max(ev.resize.h, 64);
00622       CreateMainSurface(w, h);
00623       break;
00624     }
00625     case SDL_VIDEOEXPOSE: {
00626       /* Force a redraw of the entire screen. Note
00627        * that SDL 1.2 seems to do this automatically
00628        * in most cases, but 1.3 / 2.0 does not. */
00629             _num_dirty_rects = MAX_DIRTY_RECTS + 1;
00630       break;
00631     }
00632   }
00633   return -1;
00634 }
00635 
00636 const char *VideoDriver_SDL::Start(const char * const *parm)
00637 {
00638   char buf[30];
00639   _use_hwpalette = GetDriverParamInt(parm, "hw_palette", 2);
00640 
00641   const char *s = SdlOpen(SDL_INIT_VIDEO);
00642   if (s != NULL) return s;
00643 
00644   GetVideoModes();
00645   if (!CreateMainSurface(_cur_resolution.width, _cur_resolution.height)) {
00646     return SDL_CALL SDL_GetError();
00647   }
00648 
00649   SDL_CALL SDL_VideoDriverName(buf, sizeof buf);
00650   DEBUG(driver, 1, "SDL: using driver '%s'", buf);
00651 
00652   MarkWholeScreenDirty();
00653   SetupKeyboard();
00654 
00655   _draw_threaded = GetDriverParam(parm, "no_threads") == NULL && GetDriverParam(parm, "no_thread") == NULL;
00656 
00657   return NULL;
00658 }
00659 
00660 void VideoDriver_SDL::SetupKeyboard()
00661 {
00662   SDL_CALL SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
00663   SDL_CALL SDL_EnableUNICODE(1);
00664 }
00665 
00666 void VideoDriver_SDL::Stop()
00667 {
00668   SdlClose(SDL_INIT_VIDEO);
00669 }
00670 
00671 void VideoDriver_SDL::MainLoop()
00672 {
00673   uint32 cur_ticks = SDL_CALL SDL_GetTicks();
00674   uint32 last_cur_ticks = cur_ticks;
00675   uint32 next_tick = cur_ticks + MILLISECONDS_PER_TICK;
00676   uint32 mod;
00677   int numkeys;
00678   Uint8 *keys;
00679 
00680   CheckPaletteAnim();
00681 
00682   if (_draw_threaded) {
00683     /* Initialise the mutex first, because that's the thing we *need*
00684      * directly in the newly created thread. */
00685     _draw_mutex = ThreadMutex::New();
00686     if (_draw_mutex == NULL) {
00687       _draw_threaded = false;
00688     } else {
00689       _draw_mutex->BeginCritical();
00690       _draw_continue = true;
00691 
00692       _draw_threaded = ThreadObject::New(&DrawSurfaceToScreenThread, NULL, &_draw_thread);
00693 
00694       /* Free the mutex if we won't be able to use it. */
00695       if (!_draw_threaded) {
00696         _draw_mutex->EndCritical();
00697         delete _draw_mutex;
00698         _draw_mutex = NULL;
00699       } else {
00700         /* Wait till the draw mutex has started itself. */
00701         _draw_mutex->WaitForSignal();
00702       }
00703     }
00704   }
00705 
00706   DEBUG(driver, 1, "SDL: using %sthreads", _draw_threaded ? "" : "no ");
00707 
00708   for (;;) {
00709     uint32 prev_cur_ticks = cur_ticks; // to check for wrapping
00710     InteractiveRandom(); // randomness
00711 
00712     while (PollEvent() == -1) {}
00713     if (_exit_game) break;
00714 
00715     mod = SDL_CALL SDL_GetModState();
00716 #if SDL_VERSION_ATLEAST(1, 3, 0)
00717     keys = SDL_CALL SDL_GetKeyboardState(&numkeys);
00718 #else
00719     keys = SDL_CALL SDL_GetKeyState(&numkeys);
00720 #endif
00721 #if defined(_DEBUG)
00722     if (_shift_pressed)
00723 #else
00724     /* Speedup when pressing tab, except when using ALT+TAB
00725      * to switch to another application */
00726 #if SDL_VERSION_ATLEAST(1, 3, 0)
00727     if (keys[SDL_SCANCODE_TAB] && (mod & KMOD_ALT) == 0)
00728 #else
00729     if (keys[SDLK_TAB] && (mod & KMOD_ALT) == 0)
00730 #endif /* SDL_VERSION_ATLEAST(1, 3, 0) */
00731 #endif /* defined(_DEBUG) */
00732     {
00733       if (!_networking && _game_mode != GM_MENU) _fast_forward |= 2;
00734     } else if (_fast_forward & 2) {
00735       _fast_forward = 0;
00736     }
00737 
00738     cur_ticks = SDL_CALL SDL_GetTicks();
00739     if (cur_ticks >= next_tick || (_fast_forward && !_pause_mode) || cur_ticks < prev_cur_ticks) {
00740       _realtime_tick += cur_ticks - last_cur_ticks;
00741       last_cur_ticks = cur_ticks;
00742       next_tick = cur_ticks + MILLISECONDS_PER_TICK;
00743 
00744       bool old_ctrl_pressed = _ctrl_pressed;
00745 
00746       _ctrl_pressed  = !!(mod & KMOD_CTRL);
00747       _shift_pressed = !!(mod & KMOD_SHIFT);
00748 
00749       /* determine which directional keys are down */
00750       _dirkeys =
00751 #if SDL_VERSION_ATLEAST(1, 3, 0)
00752         (keys[SDL_SCANCODE_LEFT]  ? 1 : 0) |
00753         (keys[SDL_SCANCODE_UP]    ? 2 : 0) |
00754         (keys[SDL_SCANCODE_RIGHT] ? 4 : 0) |
00755         (keys[SDL_SCANCODE_DOWN]  ? 8 : 0);
00756 #else
00757         (keys[SDLK_LEFT]  ? 1 : 0) |
00758         (keys[SDLK_UP]    ? 2 : 0) |
00759         (keys[SDLK_RIGHT] ? 4 : 0) |
00760         (keys[SDLK_DOWN]  ? 8 : 0);
00761 #endif
00762       if (old_ctrl_pressed != _ctrl_pressed) HandleCtrlChanged();
00763 
00764       /* The gameloop is the part that can run asynchronously. The rest
00765        * except sleeping can't. */
00766       if (_draw_mutex != NULL) _draw_mutex->EndCritical();
00767 
00768       GameLoop();
00769 
00770       if (_draw_mutex != NULL) _draw_mutex->BeginCritical();
00771 
00772       UpdateWindows();
00773       _local_palette = _cur_palette;
00774     } else {
00775       /* Release the thread while sleeping */
00776       if (_draw_mutex != NULL) _draw_mutex->EndCritical();
00777       CSleep(1);
00778       if (_draw_mutex != NULL) _draw_mutex->BeginCritical();
00779 
00780       NetworkDrawChatMessage();
00781       DrawMouseCursor();
00782     }
00783 
00784     /* End of the critical part. */
00785     if (_draw_mutex != NULL && !HasModalProgress()) {
00786       _draw_mutex->SendSignal();
00787     } else {
00788       /* Oh, we didn't have threads, then just draw unthreaded */
00789       CheckPaletteAnim();
00790       DrawSurfaceToScreen();
00791     }
00792   }
00793 
00794   if (_draw_mutex != NULL) {
00795     _draw_continue = false;
00796     /* Sending signal if there is no thread blocked
00797      * is very valid and results in noop */
00798     _draw_mutex->SendSignal();
00799     _draw_mutex->EndCritical();
00800     _draw_thread->Join();
00801 
00802     delete _draw_mutex;
00803     delete _draw_thread;
00804 
00805     _draw_mutex = NULL;
00806     _draw_thread = NULL;
00807   }
00808 }
00809 
00810 bool VideoDriver_SDL::ChangeResolution(int w, int h)
00811 {
00812   if (_draw_mutex != NULL) _draw_mutex->BeginCritical();
00813   bool ret = CreateMainSurface(w, h);
00814   if (_draw_mutex != NULL) _draw_mutex->EndCritical();
00815   return ret;
00816 }
00817 
00818 bool VideoDriver_SDL::ToggleFullscreen(bool fullscreen)
00819 {
00820   _fullscreen = fullscreen;
00821   GetVideoModes(); // get the list of available video modes
00822   if (_num_resolutions == 0 || !CreateMainSurface(_cur_resolution.width, _cur_resolution.height)) {
00823     /* switching resolution failed, put back full_screen to original status */
00824     _fullscreen ^= true;
00825     return false;
00826   }
00827   return true;
00828 }
00829 
00830 bool VideoDriver_SDL::AfterBlitterChange()
00831 {
00832   return this->ChangeResolution(_screen.width, _screen.height);
00833 }
00834 
00835 #endif /* WITH_SDL */