allegro_v.cpp

Go to the documentation of this file.
00001 /* $Id: allegro_v.cpp 25984 2013-11-13 21:43:16Z rubidium $ */
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 
00017 #ifdef WITH_ALLEGRO
00018 
00019 #include "../stdafx.h"
00020 #include "../openttd.h"
00021 #include "../gfx_func.h"
00022 #include "../rev.h"
00023 #include "../blitter/factory.hpp"
00024 #include "../network/network.h"
00025 #include "../core/random_func.hpp"
00026 #include "../core/math_func.hpp"
00027 #include "allegro_v.h"
00028 #include <allegro.h>
00029 
00030 #ifdef _DEBUG
00031 /* Allegro replaces SEGV/ABRT signals meaning that the debugger will never
00032  * be triggered, so rereplace the signals and make the debugger useful. */
00033 #include <signal.h>
00034 #endif
00035 
00036 static FVideoDriver_Allegro iFVideoDriver_Allegro;
00037 
00038 static BITMAP *_allegro_screen;
00039 
00040 #define MAX_DIRTY_RECTS 100
00041 static PointDimension _dirty_rects[MAX_DIRTY_RECTS];
00042 static int _num_dirty_rects;
00043 
00044 void VideoDriver_Allegro::MakeDirty(int left, int top, int width, int height)
00045 {
00046   if (_num_dirty_rects < MAX_DIRTY_RECTS) {
00047     _dirty_rects[_num_dirty_rects].x = left;
00048     _dirty_rects[_num_dirty_rects].y = top;
00049     _dirty_rects[_num_dirty_rects].width = width;
00050     _dirty_rects[_num_dirty_rects].height = height;
00051   }
00052   _num_dirty_rects++;
00053 }
00054 
00055 static void DrawSurfaceToScreen()
00056 {
00057   int n = _num_dirty_rects;
00058   if (n == 0) return;
00059 
00060   _num_dirty_rects = 0;
00061   if (n > MAX_DIRTY_RECTS) {
00062     blit(_allegro_screen, screen, 0, 0, 0, 0, _allegro_screen->w, _allegro_screen->h);
00063     return;
00064   }
00065 
00066   for (int i = 0; i < n; i++) {
00067     blit(_allegro_screen, screen, _dirty_rects[i].x, _dirty_rects[i].y, _dirty_rects[i].x, _dirty_rects[i].y, _dirty_rects[i].width, _dirty_rects[i].height);
00068   }
00069 }
00070 
00071 
00072 static void UpdatePalette(uint start, uint count)
00073 {
00074   static PALETTE pal;
00075 
00076   uint end = start + count;
00077   for (uint i = start; i != end; i++) {
00078     pal[i].r = _cur_palette.palette[i].r / 4;
00079     pal[i].g = _cur_palette.palette[i].g / 4;
00080     pal[i].b = _cur_palette.palette[i].b / 4;
00081     pal[i].filler = 0;
00082   }
00083 
00084   set_palette_range(pal, start, end - 1, 1);
00085 }
00086 
00087 static void InitPalette()
00088 {
00089   UpdatePalette(0, 256);
00090 }
00091 
00092 static void CheckPaletteAnim()
00093 {
00094   if (_cur_palette.count_dirty != 0) {
00095     Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
00096 
00097     switch (blitter->UsePaletteAnimation()) {
00098       case Blitter::PALETTE_ANIMATION_VIDEO_BACKEND:
00099         UpdatePalette(_cur_palette.first_dirty, _cur_palette.count_dirty);
00100         break;
00101 
00102       case Blitter::PALETTE_ANIMATION_BLITTER:
00103         blitter->PaletteAnimate(_cur_palette);
00104         break;
00105 
00106       case Blitter::PALETTE_ANIMATION_NONE:
00107         break;
00108 
00109       default:
00110         NOT_REACHED();
00111     }
00112     _cur_palette.count_dirty = 0;
00113   }
00114 }
00115 
00116 static const Dimension default_resolutions[] = {
00117   { 640,  480},
00118   { 800,  600},
00119   {1024,  768},
00120   {1152,  864},
00121   {1280,  800},
00122   {1280,  960},
00123   {1280, 1024},
00124   {1400, 1050},
00125   {1600, 1200},
00126   {1680, 1050},
00127   {1920, 1200}
00128 };
00129 
00130 static void GetVideoModes()
00131 {
00132   /* Need to set a gfx_mode as there is NO other way to autodetect for
00133    * cards ourselves... and we need a card to get the modes. */
00134   set_gfx_mode(_fullscreen ? GFX_AUTODETECT_FULLSCREEN : GFX_AUTODETECT_WINDOWED, 640, 480, 0, 0);
00135 
00136   GFX_MODE_LIST *mode_list = get_gfx_mode_list(gfx_driver->id);
00137   if (mode_list == NULL) {
00138     memcpy(_resolutions, default_resolutions, sizeof(default_resolutions));
00139     _num_resolutions = lengthof(default_resolutions);
00140     return;
00141   }
00142 
00143   GFX_MODE *modes = mode_list->mode;
00144 
00145   int n = 0;
00146   for (int i = 0; modes[i].bpp != 0; i++) {
00147     uint w = modes[i].width;
00148     uint h = modes[i].height;
00149     if (w >= 640 && h >= 480) {
00150       int j;
00151       for (j = 0; j < n; j++) {
00152         if (_resolutions[j].width == w && _resolutions[j].height == h) break;
00153       }
00154 
00155       if (j == n) {
00156         _resolutions[j].width  = w;
00157         _resolutions[j].height = h;
00158         if (++n == lengthof(_resolutions)) break;
00159       }
00160     }
00161   }
00162   _num_resolutions = n;
00163   SortResolutions(_num_resolutions);
00164 
00165   destroy_gfx_mode_list(mode_list);
00166 }
00167 
00168 static void GetAvailableVideoMode(uint *w, uint *h)
00169 {
00170   /* No video modes, so just try it and see where it ends */
00171   if (_num_resolutions == 0) return;
00172 
00173   /* is the wanted mode among the available modes? */
00174   for (int i = 0; i != _num_resolutions; i++) {
00175     if (*w == _resolutions[i].width && *h == _resolutions[i].height) return;
00176   }
00177 
00178   /* use the closest possible resolution */
00179   int best = 0;
00180   uint delta = Delta(_resolutions[0].width, *w) * Delta(_resolutions[0].height, *h);
00181   for (int i = 1; i != _num_resolutions; ++i) {
00182     uint newdelta = Delta(_resolutions[i].width, *w) * Delta(_resolutions[i].height, *h);
00183     if (newdelta < delta) {
00184       best = i;
00185       delta = newdelta;
00186     }
00187   }
00188   *w = _resolutions[best].width;
00189   *h = _resolutions[best].height;
00190 }
00191 
00192 static bool CreateMainSurface(uint w, uint h)
00193 {
00194   int bpp = BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth();
00195   if (bpp == 0) usererror("Can't use a blitter that blits 0 bpp for normal visuals");
00196   set_color_depth(bpp);
00197 
00198   GetAvailableVideoMode(&w, &h);
00199   if (set_gfx_mode(_fullscreen ? GFX_AUTODETECT_FULLSCREEN : GFX_AUTODETECT_WINDOWED, w, h, 0, 0) != 0) {
00200     DEBUG(driver, 0, "Allegro: Couldn't allocate a window to draw on '%s'", allegro_error);
00201     return false;
00202   }
00203 
00204   /* The size of the screen might be bigger than the part we can actually draw on!
00205    * So calculate the size based on the top, bottom, left and right */
00206   _allegro_screen = create_bitmap_ex(bpp, screen->cr - screen->cl, screen->cb - screen->ct);
00207   _screen.width = _allegro_screen->w;
00208   _screen.height = _allegro_screen->h;
00209   _screen.pitch = ((byte*)screen->line[1] - (byte*)screen->line[0]) / (bpp / 8);
00210   _screen.dst_ptr = _allegro_screen->line[0];
00211 
00212   /* Initialise the screen so we don't blit garbage to the screen */
00213   memset(_screen.dst_ptr, 0, _screen.height * _screen.pitch);
00214 
00215   /* Set the mouse at the place where we expect it */
00216   poll_mouse();
00217   _cursor.pos.x = mouse_x;
00218   _cursor.pos.y = mouse_y;
00219 
00220   BlitterFactoryBase::GetCurrentBlitter()->PostResize();
00221 
00222   InitPalette();
00223 
00224   char caption[32];
00225   snprintf(caption, sizeof(caption), "OpenTTD %s", _openttd_revision);
00226   set_window_title(caption);
00227 
00228   enable_hardware_cursor();
00229   select_mouse_cursor(MOUSE_CURSOR_ARROW);
00230   show_mouse(_allegro_screen);
00231 
00232   GameSizeChanged();
00233 
00234   return true;
00235 }
00236 
00237 bool VideoDriver_Allegro::ClaimMousePointer()
00238 {
00239   select_mouse_cursor(MOUSE_CURSOR_NONE);
00240   show_mouse(NULL);
00241   disable_hardware_cursor();
00242   return true;
00243 }
00244 
00245 struct VkMapping {
00246   uint16 vk_from;
00247   byte vk_count;
00248   byte map_to;
00249 };
00250 
00251 #define AS(x, z) {x, 0, z}
00252 #define AM(x, y, z, w) {x, y - x, z}
00253 
00254 static const VkMapping _vk_mapping[] = {
00255   /* Pageup stuff + up/down */
00256   AM(KEY_PGUP, KEY_PGDN, WKC_PAGEUP, WKC_PAGEDOWN),
00257   AS(KEY_UP,     WKC_UP),
00258   AS(KEY_DOWN,   WKC_DOWN),
00259   AS(KEY_LEFT,   WKC_LEFT),
00260   AS(KEY_RIGHT,  WKC_RIGHT),
00261 
00262   AS(KEY_HOME,   WKC_HOME),
00263   AS(KEY_END,    WKC_END),
00264 
00265   AS(KEY_INSERT, WKC_INSERT),
00266   AS(KEY_DEL,    WKC_DELETE),
00267 
00268   /* Map letters & digits */
00269   AM(KEY_A, KEY_Z, 'A', 'Z'),
00270   AM(KEY_0, KEY_9, '0', '9'),
00271 
00272   AS(KEY_ESC,       WKC_ESC),
00273   AS(KEY_PAUSE,     WKC_PAUSE),
00274   AS(KEY_BACKSPACE, WKC_BACKSPACE),
00275 
00276   AS(KEY_SPACE,     WKC_SPACE),
00277   AS(KEY_ENTER,     WKC_RETURN),
00278   AS(KEY_TAB,       WKC_TAB),
00279 
00280   /* Function keys */
00281   AM(KEY_F1, KEY_F12, WKC_F1, WKC_F12),
00282 
00283   /* Numeric part. */
00284   AM(KEY_0_PAD, KEY_9_PAD, '0', '9'),
00285   AS(KEY_SLASH_PAD,   WKC_NUM_DIV),
00286   AS(KEY_ASTERISK,    WKC_NUM_MUL),
00287   AS(KEY_MINUS_PAD,   WKC_NUM_MINUS),
00288   AS(KEY_PLUS_PAD,    WKC_NUM_PLUS),
00289   AS(KEY_ENTER_PAD,   WKC_NUM_ENTER),
00290   AS(KEY_DEL_PAD,     WKC_DELETE),
00291 
00292   /* Other non-letter keys */
00293   AS(KEY_SLASH,        WKC_SLASH),
00294   AS(KEY_SEMICOLON,    WKC_SEMICOLON),
00295   AS(KEY_EQUALS,       WKC_EQUALS),
00296   AS(KEY_OPENBRACE,    WKC_L_BRACKET),
00297   AS(KEY_BACKSLASH,    WKC_BACKSLASH),
00298   AS(KEY_CLOSEBRACE,   WKC_R_BRACKET),
00299 
00300   AS(KEY_QUOTE,   WKC_SINGLEQUOTE),
00301   AS(KEY_COMMA,   WKC_COMMA),
00302   AS(KEY_MINUS,   WKC_MINUS),
00303   AS(KEY_STOP,    WKC_PERIOD),
00304   AS(KEY_TILDE,   WKC_BACKQUOTE),
00305 };
00306 
00307 static uint32 ConvertAllegroKeyIntoMy(WChar *character)
00308 {
00309   int scancode;
00310   int unicode = ureadkey(&scancode);
00311 
00312   const VkMapping *map;
00313   uint key = 0;
00314 
00315   for (map = _vk_mapping; map != endof(_vk_mapping); ++map) {
00316     if ((uint)(scancode - map->vk_from) <= map->vk_count) {
00317       key = scancode - map->vk_from + map->map_to;
00318       break;
00319     }
00320   }
00321 
00322   if (key_shifts & KB_SHIFT_FLAG) key |= WKC_SHIFT;
00323   if (key_shifts & KB_CTRL_FLAG)  key |= WKC_CTRL;
00324   if (key_shifts & KB_ALT_FLAG)   key |= WKC_ALT;
00325 #if 0
00326   DEBUG(driver, 0, "Scancode character pressed %u", scancode);
00327   DEBUG(driver, 0, "Unicode character pressed %u", unicode);
00328 #endif
00329 
00330   *character = unicode;
00331   return key;
00332 }
00333 
00334 static const uint LEFT_BUTTON  = 0;
00335 static const uint RIGHT_BUTTON = 1;
00336 
00337 static void PollEvent()
00338 {
00339   poll_mouse();
00340 
00341   bool mouse_action = false;
00342 
00343   /* Mouse buttons */
00344   static int prev_button_state;
00345   if (prev_button_state != mouse_b) {
00346     uint diff = prev_button_state ^ mouse_b;
00347     while (diff != 0) {
00348       uint button = FindFirstBit(diff);
00349       ClrBit(diff, button);
00350       if (HasBit(mouse_b, button)) {
00351         /* Pressed mouse button */
00352         if (_rightclick_emulate && (key_shifts & KB_CTRL_FLAG)) {
00353           button = RIGHT_BUTTON;
00354           ClrBit(diff, RIGHT_BUTTON);
00355         }
00356         switch (button) {
00357           case LEFT_BUTTON:
00358             _left_button_down = true;
00359             break;
00360 
00361           case RIGHT_BUTTON:
00362             _right_button_down = true;
00363             _right_button_clicked = true;
00364             break;
00365 
00366           default:
00367             /* ignore rest */
00368             break;
00369         }
00370       } else {
00371         /* Released mouse button */
00372         if (_rightclick_emulate) {
00373           _right_button_down = false;
00374           _left_button_down = false;
00375           _left_button_clicked = false;
00376         } else if (button == LEFT_BUTTON) {
00377           _left_button_down = false;
00378           _left_button_clicked = false;
00379         } else if (button == RIGHT_BUTTON) {
00380           _right_button_down = false;
00381         }
00382       }
00383     }
00384     prev_button_state = mouse_b;
00385     mouse_action = true;
00386   }
00387 
00388   /* Mouse movement */
00389   int dx = mouse_x - _cursor.pos.x;
00390   int dy = mouse_y - _cursor.pos.y;
00391   if (dx != 0 || dy != 0) {
00392     if (_cursor.fix_at) {
00393       _cursor.delta.x = dx;
00394       _cursor.delta.y = dy;
00395       position_mouse(_cursor.pos.x, _cursor.pos.y);
00396     } else {
00397       _cursor.delta.x = dx;
00398       _cursor.delta.y = dy;
00399       _cursor.pos.x = mouse_x;
00400       _cursor.pos.y = mouse_y;
00401       _cursor.dirty = true;
00402     }
00403     mouse_action = true;
00404   }
00405 
00406   static int prev_mouse_z = 0;
00407   if (prev_mouse_z != mouse_z) {
00408     _cursor.wheel = (prev_mouse_z - mouse_z) < 0 ? -1 : 1;
00409     prev_mouse_z = mouse_z;
00410     mouse_action = true;
00411   }
00412 
00413   if (mouse_action) HandleMouseEvents();
00414 
00415   poll_keyboard();
00416   if ((key_shifts & KB_ALT_FLAG) && (key[KEY_ENTER] || key[KEY_F])) {
00417     ToggleFullScreen(!_fullscreen);
00418   } else if (keypressed()) {
00419     WChar character;
00420     uint keycode = ConvertAllegroKeyIntoMy(&character);
00421     HandleKeypress(keycode, character);
00422   }
00423 }
00424 
00429 int _allegro_instance_count = 0;
00430 
00431 const char *VideoDriver_Allegro::Start(const char * const *parm)
00432 {
00433   if (_allegro_instance_count == 0 && install_allegro(SYSTEM_AUTODETECT, &errno, NULL)) {
00434     DEBUG(driver, 0, "allegro: install_allegro failed '%s'", allegro_error);
00435     return "Failed to set up Allegro";
00436   }
00437   _allegro_instance_count++;
00438 
00439   install_timer();
00440   install_mouse();
00441   install_keyboard();
00442 
00443 #if defined _DEBUG
00444 /* Allegro replaces SEGV/ABRT signals meaning that the debugger will never
00445  * be triggered, so rereplace the signals and make the debugger useful. */
00446   signal(SIGABRT, NULL);
00447   signal(SIGSEGV, NULL);
00448 #endif
00449 
00450 #if defined(DOS)
00451   /* Force DOS builds to ALWAYS use full screen as
00452    * it can't do windowed. */
00453   _fullscreen = true;
00454 #endif
00455 
00456   GetVideoModes();
00457   if (!CreateMainSurface(_cur_resolution.width, _cur_resolution.height)) {
00458     return "Failed to set up Allegro video";
00459   }
00460   MarkWholeScreenDirty();
00461   set_close_button_callback(HandleExitGameRequest);
00462 
00463   return NULL;
00464 }
00465 
00466 void VideoDriver_Allegro::Stop()
00467 {
00468   if (--_allegro_instance_count == 0) allegro_exit();
00469 }
00470 
00471 #if defined(UNIX) || defined(__OS2__) || defined(PSP) || defined(DOS)
00472 # include <sys/time.h> /* gettimeofday */
00473 
00474 static uint32 GetTime()
00475 {
00476   struct timeval tim;
00477 
00478   gettimeofday(&tim, NULL);
00479   return tim.tv_usec / 1000 + tim.tv_sec * 1000;
00480 }
00481 #else
00482 static uint32 GetTime()
00483 {
00484   return GetTickCount();
00485 }
00486 #endif
00487 
00488 
00489 void VideoDriver_Allegro::MainLoop()
00490 {
00491   uint32 cur_ticks = GetTime();
00492   uint32 last_cur_ticks = cur_ticks;
00493   uint32 next_tick = cur_ticks + MILLISECONDS_PER_TICK;
00494 
00495   CheckPaletteAnim();
00496 
00497   for (;;) {
00498     uint32 prev_cur_ticks = cur_ticks; // to check for wrapping
00499     InteractiveRandom(); // randomness
00500 
00501     PollEvent();
00502     if (_exit_game) return;
00503 
00504 #if defined(_DEBUG)
00505     if (_shift_pressed)
00506 #else
00507     /* Speedup when pressing tab, except when using ALT+TAB
00508      * to switch to another application */
00509     if (key[KEY_TAB] && (key_shifts & KB_ALT_FLAG) == 0)
00510 #endif
00511     {
00512       if (!_networking && _game_mode != GM_MENU) _fast_forward |= 2;
00513     } else if (_fast_forward & 2) {
00514       _fast_forward = 0;
00515     }
00516 
00517     cur_ticks = GetTime();
00518     if (cur_ticks >= next_tick || (_fast_forward && !_pause_mode) || cur_ticks < prev_cur_ticks) {
00519       _realtime_tick += cur_ticks - last_cur_ticks;
00520       last_cur_ticks = cur_ticks;
00521       next_tick = cur_ticks + MILLISECONDS_PER_TICK;
00522 
00523       bool old_ctrl_pressed = _ctrl_pressed;
00524 
00525       _ctrl_pressed  = !!(key_shifts & KB_CTRL_FLAG);
00526       _shift_pressed = !!(key_shifts & KB_SHIFT_FLAG);
00527 
00528       /* determine which directional keys are down */
00529       _dirkeys =
00530         (key[KEY_LEFT]  ? 1 : 0) |
00531         (key[KEY_UP]    ? 2 : 0) |
00532         (key[KEY_RIGHT] ? 4 : 0) |
00533         (key[KEY_DOWN]  ? 8 : 0);
00534 
00535       if (old_ctrl_pressed != _ctrl_pressed) HandleCtrlChanged();
00536 
00537       GameLoop();
00538 
00539       UpdateWindows();
00540       CheckPaletteAnim();
00541       DrawSurfaceToScreen();
00542     } else {
00543       CSleep(1);
00544       NetworkDrawChatMessage();
00545       DrawMouseCursor();
00546       DrawSurfaceToScreen();
00547     }
00548   }
00549 }
00550 
00551 bool VideoDriver_Allegro::ChangeResolution(int w, int h)
00552 {
00553   return CreateMainSurface(w, h);
00554 }
00555 
00556 bool VideoDriver_Allegro::ToggleFullscreen(bool fullscreen)
00557 {
00558 #ifdef DOS
00559   return false;
00560 #else
00561   _fullscreen = fullscreen;
00562   GetVideoModes(); // get the list of available video modes
00563   if (_num_resolutions == 0 || !this->ChangeResolution(_cur_resolution.width, _cur_resolution.height)) {
00564     /* switching resolution failed, put back full_screen to original status */
00565     _fullscreen ^= true;
00566     return false;
00567   }
00568   return true;
00569 #endif
00570 }
00571 
00572 bool VideoDriver_Allegro::AfterBlitterChange()
00573 {
00574   return CreateMainSurface(_screen.width, _screen.height);
00575 }
00576 
00577 #endif /* WITH_ALLEGRO */